turns

package
v0.7.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 19, 2026 License: Apache-2.0 Imports: 28 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package turns holds the core of a turn and the ports it drives.

Index

Constants

View Source
const (
	RefusalTerminalClosed = "its terminal is closed; it ends on its own"
	RefusalNoAgent        = "its terminal is open with no agent in it: close that terminal, or dismiss this"
	RefusalNoWorkspace    = "it has no workspace to find its terminal in: dismiss this"
)

The close refusals of a session whose terminal runs no agent. A closed terminal clears on its own: the census marks the session dormant once its process is gone or has stayed orphaned (session.mark_dormant). An open one, or a session with no workspace to look for one in, waits for the user.

View Source
const (
	// UsageHeadless is the usage_source of a headless turn's usage, read from its call's answer.
	UsageHeadless = "headless"
	// Interrupted is the summary of a headless turn a restart cut short.
	Interrupted = "interrupted by a restart"
)
View Source
const (
	// NoticeAnswered tells that the user answered a gate of the session's turn: Gate, 0 for an answer that
	// names none, and Unit.
	NoticeAnswered = "answered"
	// NoticeChat tells a live session of a task that the user wrote on the task's chat: Task, Unit, the task's
	// own unit as the loop's commands read it, and Capable, whether the session loaded the loop's MCP server.
	NoticeChat = "chat"
	// NoticeRecordOwed blocks a stop whose turn has no record: Unit, Turn and ScratchDir.
	NoticeRecordOwed = "record_owed"
)

The notices the loop tells a session, and the data each reads besides Name and Command.

View Source
const (
	KindTurnSent            = "turn_sent"          // Key = turn id
	KindTurnDelivered       = "turn_delivered"     // Key = turn id:handle
	KindTurnWithdrawn       = "turn_withdrawn"     // Key = turn id:withdrawn-at, Data = why
	KindTurnStarted         = "turn_started"       // Key = turn id
	KindTurnEnded           = "turn_ended"         // Key = turn id:hash[:12]
	KindAnswered            = "answered"           // Data = the answer on one line
	KindAnswerRouted        = "answer_routed"      // Key = answer id, Data = the route and the handle
	KindQuestionDismissed   = "question_dismissed" // Key = turn id
	KindTurnResumed         = "turn_resumed"       // Key = turn id
	KindSessionStarted      = "session_started"    // Key = handle:started-at
	KindSessionLaunched     = "session_launched"   // Key = handle
	KindSessionAbandoned    = "session_abandoned"  // Key = handle
	KindMCPSeen             = "mcp_seen"           // Key = handle:mcp-at
	KindTurnStopped         = "turn_stopped"       // Key = handle:prompt_id
	KindStopBlocked         = "stop_blocked"       // Key = handle:prompt_id
	KindSessionIdle         = "session_idle"       // Key = handle:idle-since
	KindSessionActive       = "session_active"     // Key = handle:idle-since
	KindSessionClosed       = "session_closed"     // Key = handle, Data = the reason, then "; resume with: " and the line
	KindReconcileReport     = "reconcile_report"
	KindSessionTyped        = "session_typed"    // Key = handle:typed-at
	KindSessionPrompted     = "session_prompted" // Key = handle:seen-at, Data = "user" or "loop"
	KindTurnDismissedByRule = "turn_dismissed"   // Key = seq:reason, Data = the reason
	KindAnswerRefused       = "answer_refused"   // Key = answer id, Data = the reason
	KindAnswerRead          = "answer_read"      // Key = answer id:read-at
)

The kinds of the events the turns' saves write.

View Source
const (
	// Quiet is how long a done pane's terminal prints nothing before its turn
	// counts as stopped.
	Quiet = 2 * time.Minute
	// SentGrace is how long a sent turn waits for an agent to start it,
	// plus one fast job.
	SentGrace = 2 * time.Minute
)
View Source
const DefaultOrphanAfter = 2 * time.Hour

DefaultOrphanAfter is how long a process must stay orphaned, with no output since, before its orphan is durable without a renderer restart to prove it.

View Source
const DefaultOrphanHold = 24 * time.Hour

DefaultOrphanHold is how long a dormant session's close waits on its lingering orphan, the app's windows attached throughout, before it closes the record anyway.

View Source
const KindLateRecord = "late_record" // Key = turn id:hash[:12]

KindLateRecord is the event of a record stored for the history of a replaced or dismissed turn, whose state it leaves alone.

View Source
const KindSessionAdopted = "session_adopted"

KindSessionAdopted is a process no session took becoming a session of its own; Key = session id, Data = manager:handle.

View Source
const KindSessionDormant = "session_dormant"

KindSessionDormant is a session whose process its manager no longer lists; Key = session id:handle.

View Source
const KindSessionMerged = "session_merged"

KindSessionMerged is a session taken from a process before the loop bound the process to the session it started there; Key = the taken session's id, Data = the session it merged into.

View Source
const KindSessionUnit = "session_unit"

KindSessionUnit is the event of a session taking the unit of its first turn; Key = handle, Data = the unit.

View Source
const KindSessionWoken = "session_woken"

KindSessionWoken is a dormant session given a live process again; Key = session id:handle.

View Source
const QuestionTrust = "trust"

QuestionTrust is the agent's question whether to trust the worktree.

View Source
const ReconcileMyReview = "my_review"

ReconcileMyReview is the reconcile that closes an asked turn as done once the user's answer appears in the unit's source.

View Source
const RefusalCloseRaced = "its process changed while it was being closed"

RefusalCloseRaced refuses a close whose session took another process, or woke, between its check and its close.

View Source
const RefusalOrphanLingers = "its process lingers orphaned and may come back; it closes once the process is gone, or after cleanup.orphan_hold"

RefusalOrphanLingers holds the close of a dormant session whose process the census still lists orphaned and has not proven a lasting orphan: a window may reclaim the pane, and the census then wakes the session.

View Source
const RefusalOrphanMoved = "its process is no longer the orphan the census proved"

RefusalOrphanMoved refuses closing an orphan a fresh census no longer lists as the one the sweep proved.

View Source
const RefusalOrphanUnproven = "its process is not proven a lasting orphan"

RefusalOrphanUnproven refuses closing a process the census has not proven a durable orphan (see OrphanDurable).

View Source
const ResumeWith = "; resume with: "

ResumeWith joins a session_closed event's reason and its resume line.

View Source
const RouteLaunch = "launch"

RouteLaunch is the route of a turn the turn service or the headless runner starts, as the plugin protocol names it.

View Source
const StopIdleWait = 15 * time.Second

StopIdleWait is how long the answer queued for a session that just stopped waits for the agent's prompt before it is left to the sweep.

View Source
const StopsKept = 30 * 24 * time.Hour

StopsKept is how long the store keeps a stop.

View Source
const TypedEcho = 30 * time.Second

TypedEcho is how long after the loop typed a line its prompt hook may arrive and still be the loop's. A line queued behind a busy agent may arrive later: the first prompt after it that matches it is the loop's.

View Source
const Warm = time.Hour

Warm is how long after its last output a session still takes a typed answer; a colder one gets a resume turn.

Variables

View Source
var (
	// ErrToolNotAllowed is a Tools entry outside ReadOnlyTools; nothing is spawned.
	ErrToolNotAllowed = errors.New("the call names a tool that is not read-only")
	// ErrNoRestricted is a call with Tools or Dirs while the installed agent lacks a restricted mode; nothing is spawned.
	ErrNoRestricted = errors.New("the installed agent cannot run a restricted call")
	ErrNoAgent      = errors.New("the agent is not on the PATH")
	// ErrOverBudget is a call that ran past Ask.MaxCostUSD.
	ErrOverBudget = errors.New("the call ran over its budget")
	// ErrUnfit is an answer that is not JSON fitting the schema.
	ErrUnfit = errors.New("the answer does not fit the schema")
	// ErrTooLong is a prompt longer than the model reads.
	ErrTooLong = errors.New("the prompt is too long")
	// ErrUnavailable is an agent that cannot answer now: rate limited,
	// overloaded, out of credit, logged out.
	ErrUnavailable = errors.New("the agent is unavailable")
)
View Source
var (
	// ErrRefused is a start the unit's state refuses, such as a prepare that
	// finds nothing to do; no retry of the same request passes.
	ErrRefused = errors.New("the turn is refused")
	// ErrTransient is a start that may pass on a retry: the prepare's plugin,
	// or the daemon that runs it, is out of reach.
	ErrTransient = errors.New("the turn cannot start now")
	// ErrNoTurn is a Turn no Start or Resume made.
	ErrNoTurn = errors.New("no turn was admitted")
	// ErrUsedTurn is a Turn already used once.
	ErrUsedTurn = errors.New("the turn was already used")
	// ErrAnswered is a Guard that answered the request itself, starting no
	// turn: the guidance given with it is dropped and the kept one stays.
	ErrAnswered = errors.New("the request was answered without a turn")
)
View Source
var ErrDormant = errors.New("the session is dormant: it has no live process")

ErrDormant is a session with no live process to type into.

View Source
var ErrHeadlessBusy = errors.New("the unit already has a headless turn started")

ErrHeadlessBusy is BeginHeadless's refusal while the unit has a headless turn started.

View Source
var ErrNoIntents = errors.New("turns unavailable: no intents are wired")

ErrNoIntents is a wiring error: the service has no Intents port.

View Source
var ErrOverCap = errors.New("the headless spend cap is reached")

ErrOverCap is a call the day's headless spend leaves no room for.

View Source
var ErrWorkspaceGone = errors.New("the workspace is gone")

ErrWorkspaceGone is what a Launcher returns when the workspace a resume runs in no longer exists.

View Source
var ReadOnlyTools = []string{"Read", "Grep", "Glob"}

Functions

func AnswerOnItsWay added in v0.4.0

func AnswerOnItsWay(i turn.Intent) string

AnswerOnItsWay is why an automated send of intent i waits: its open question has an answer stored that the turn has not taken yet.

func CloseGone added in v0.4.0

func CloseGone(handle, why string) bool

CloseGone says whether why, a CloseRefusal of handle, holds for good: there is no such session, or it is closed.

func CloseOrphanGone added in v0.4.0

func CloseOrphanGone(id, why string) bool

CloseOrphanGone says whether why, a CloseOrphanRefusal of id, holds for good: there is no such session, or it is closed or dormant, so no process of it is left to close.

func InputsOf added in v0.6.0

func InputsOf(t turn.Turn) map[string]any

InputsOf are the turn's inputs without the items and task kept among them.

func ItemsOf

func ItemsOf(t turn.Turn) []string

ItemsOf are the item ids the turn was sent about, kept in its inputs.

func LastStop

func LastStop(ctx context.Context, r Registry, handle string) (turn.Stop, bool, error)

LastStop returns the newest stop of one handle.

func MissingSubject added in v0.3.0

func MissingSubject(id string) string

MissingSubject is the Subject of the gate turn id opens when it ends without its record or failed.

func MissingTurn added in v0.3.0

func MissingTurn(subject string) (string, bool)

MissingTurn is the turn id a missing gate's Subject names; false for any other subject.

func NewSessionID

func NewSessionID() string

NewSessionID mints a session id: a random UUID, which the agent can also take as its own conversation id.

func TaskOf added in v0.3.0

func TaskOf(t turn.Turn) string

TaskOf is the task the turn was asked from, kept in its inputs; "" none.

func UserApproved added in v0.5.0

func UserApproved(g gate.Gate, d draft.Draft) bool

UserApproved says whether g, d's gate, approved d by the user: a person, or a session the user drives.

Types

type Agent

type Agent interface {
	Name() string
	// Binary is the executable an interactive session runs.
	Binary() string
	// Command is the shell line that starts an interactive session.
	Command(s AgentSession) (string, error)
	// Preflight checks, without changing anything, that a session of s can
	// start unattended; an *UntrustedError names a worktree the agent's
	// home does not trust.
	Preflight(ctx context.Context, s AgentSession) error
	// Resume is the shell line that resumes agentSession with home, "" for
	// the agent's default home.
	Resume(home, agentSession string) string
}

Agent starts interactive sessions of one coding agent.

type AgentObservation

type AgentObservation struct {
	// Pane is an opaque key of the agent's pane, equal to turn.Session.Pane for the same pane.
	// TerminalKey equals the Key of the terminal the agent runs in, "" when unknown.
	WorkspaceID, Pane, TerminalKey string
	State                          turn.AgentState
	// StateSince is when the agent entered State, zero when unknown; a repaint does not move it.
	StateSince  time.Time
	LastMessage string
	// UserActive means the workspace is the one open in the app.
	UserActive bool
}

AgentObservation is what the app sees an agent doing, a signal and never a turn's state.

func AgentOf

func AgentOf(agents []AgentObservation, sess turn.Session, term Terminal) (AgentObservation, bool)

AgentOf is the agent running in the session's terminal, matched as cleanup and session.close match them.

type AgentSession

type AgentSession struct {
	// SessionID is the id the loop minted for the session, which the agent
	// takes as its own conversation id; "" lets the agent pick one.
	SessionID string
	// Resume is the agent's own id of a conversation the session resumes,
	// "" for a new one.
	Resume   string
	Worktree string
	// Home is the agent's configuration directory, "" for its default.
	Home string
	// Model is a model name of the agent's own that the user pinned, "" for
	// its default; the core passes it on unread.
	Model string
	// Name is what the agent shows the session as, "" for its default.
	Name   string
	Policy Policy
	// Trusted says the pull request passes the trust check of automated
	// rounds, so the session may run unattended. The loop never trusts the
	// worktree in the agent's home for it: that stays the user's decision.
	Trusted bool
	// TrustedAtLaunch says the workspace manager may trust the worktree in
	// Home as it launches the session, after any preflight reads it.
	TrustedAtLaunch bool
}

type AgentSessionInfo

type AgentSessionInfo struct {
	ID, Kind, Session, Home, Worktree, Transcript string
	At                                            time.Time
}

type AgentSessions

type AgentSessions interface {
	SaveAgentSession(ctx context.Context, a AgentSessionInfo) error
}

AgentSessions keeps what the hooks tell of each agent session, so a turn's usage is found after its session moved on.

type Answer

type Answer struct {
	JSON []byte
	// Model names the agent's model that answered: the id it reports, else
	// the name it was asked for.
	Model string
	// CostUSD is nil when the agent did not report it.
	CostUSD  *float64
	Duration time.Duration
	// Tokens is nil when the agent did not report them.
	Tokens *usage.Tokens
}

type AnswerRequest

type AnswerRequest struct {
	Unit           unit.Unit
	Text, OptionID string
	// Yes and No are a confirm's explicit choice; Text is then a note.
	Yes, No bool
	Source  turn.Source
	// Message is the Inbox message answered: the question of the unit's turn, or, when Posted, one the agent
	// posted during turn Turn, whose answer never resumes a turn.
	Message, Turn int64
	Posted        bool
	// Gate is the gate whose resolution the answer is.
	Gate int64
	// BySession is the session an agent answered through, "" for a person.
	BySession string
	// Approves says the answer's option approved the draft it points to: the answer is stored, routed
	// approved and delivered to no session; the turn ends when the draft is sent.
	Approves bool
}

type AnswerResult

type AnswerResult struct {
	Route turn.Route
	// Handle is the session a typed answer went to.
	Handle string
	// Note is why the answer went the way it did, kept in its routed event.
	Note string
}

type Answers added in v0.3.0

type Answers interface {
	Answers(ctx context.Context, u unit.Unit, since time.Time) ([]SourceAnswer, error)
}

Answers reads the user's answers on a unit since a time.

type Ask

type Ask struct {
	// Home is the agent's configuration directory, "" for its default.
	Home   string
	Tier   Tier
	Prompt string
	Schema string
	// MaxCostUSD caps the call; 0 leaves it to the agent.
	MaxCostUSD float64
	// Tools are read-only tools the call may use, a subset of ReadOnlyTools; nil is none.
	Tools []string
	// Dirs are absolute directories the call may read (the placed checkout).
	Dirs []string
}

Ask is one headless call: Prompt in, JSON fitting Schema out, with no MCP servers, no user settings and no saved session. Without Tools and Dirs it has no tools at all; with either it runs restricted, reading only Dirs.

type Asker

type Asker interface {
	Ask(ctx context.Context, a Ask) (Answer, error)
}

Asker runs the headless calls of one coding agent.

type AskingAgent

type AskingAgent interface {
	Asker(dir string, models map[Tier]string) (Asker, error)
}

AskingAgent is an Agent that also answers headless calls: Asker returns its caller running in dir, with models pinning tiers to model names of the agent's own.

type Budget added in v0.4.0

type Budget struct {
	Caps BudgetCaps
	// Spent is the day's headless spend as stored; nil counts none.
	Spent func(ctx context.Context, day time.Time) (float64, error)
	Clock port.Clock
	// contains filtered or unexported fields
}

Budget books the headless spend of calls that are not turns (the omnibox's): each call reserves its per-call cap before it runs and settles its cost when it returns.

func (*Budget) Reserve added in v0.4.0

func (b *Budget) Reserve(ctx context.Context) error

Reserve books a call's cap, refusing it with ErrOverCap when the day's spend and the running calls reach PerDayUSD.

func (*Budget) Reserved added in v0.4.0

func (b *Budget) Reserved() float64

Reserved is the per-call caps of the calls running, which no store holds yet.

func (*Budget) Settle added in v0.4.0

func (b *Budget) Settle(ctx context.Context, cost *float64, record func(ctx context.Context, cost float64) error) error

Settle records a reserved call's cost, the per-call cap when none was reported, and then releases its reservation, so the call always counts, stored or reserved. It returns record's error.

type BudgetCaps added in v0.4.0

type BudgetCaps struct {
	PerCallUSD, PerDayUSD float64
}

BudgetCaps are the headless caps a Budget books against; a zero PerDayUSD caps no day.

type Census

type Census struct {
	Sessions map[string]string
	// Complete is false when the list may leave processes out: cut short, a host
	// left out, or a manager not ready. CompleteFor is per manager.
	Complete    bool
	CompleteFor map[string]bool
	// RuntimeID names the manager instance that answered; another one after a
	// restart may list other handles. RuntimeIDs is per manager.
	RuntimeID  string
	RuntimeIDs map[string]string
	At         time.Time
	// Processes address each listed session's process.
	Processes map[string]ProcessRef
	// Orphans are the listed sessions whose process no app window shows and
	// runs no agent, each with the process's last output, zero when unknown.
	// A census still lists them: only a step that proves the orphan durable
	// closes one.
	Orphans map[string]time.Time
	// Epoch is the renderer graph epoch of the app that answered, which changes
	// when its windows restart and reattach their processes; "" when unknown.
	// Epochs is per manager.
	Epoch  string
	Epochs map[string]string
	// Shown says the app's windows showed some terminal of the list: the app
	// is attached. ShownFor is per manager.
	Shown    bool
	ShownFor map[string]bool
}

Census is every session with a live process, with its workspace id.

func (Census) CompleteOf

func (c Census) CompleteOf(manager string) bool

CompleteOf says whether the census lists every process of manager.

func (Census) EpochOf added in v0.4.0

func (c Census) EpochOf(manager string) string

EpochOf is manager's renderer graph epoch in the census.

func (Census) RuntimeOf

func (c Census) RuntimeOf(manager string) string

RuntimeOf is the runtime that answered for manager.

func (Census) ShownOf added in v0.4.0

func (c Census) ShownOf(manager string) bool

ShownOf says whether manager's windows showed some terminal in the census.

type Chats added in v0.3.0

type Chats interface {
	// Waiting is the task whose chat holds such messages, of the tasks unit u is; false when none does.
	Waiting(ctx context.Context, u unit.Unit) (task unit.Unit, ok bool, err error)
	// Noticed notes that an agent was told of every message on the chat of the task whose own unit is task.
	Noticed(ctx context.Context, task unit.Unit) error
}

Chats are the messages the user wrote on a task's chat that no notice told an agent of yet.

type Control

type Control struct {
	Commands [][]string
	Paths    []string
}

Control is what drives the workspace managers from outside their own CLI: command prefixes and paths a session the loop starts may neither run nor read, so it does not steer another session through them by mistake.

type Def added in v0.6.0

type Def struct {
	dintent.Def
	// HandsGuidance is the intent's turn.guidance_handed: the guidance kept
	// for the unit's next turn goes to its turns, and comes back when one
	// does not go out.
	HandsGuidance bool
}

Def is an intent as Start reads it.

type Defs added in v0.6.0

type Defs interface {
	Def(name turn.Intent) (Def, bool)
}

Defs are the loaded intents.

type DraftGates added in v0.5.0

type DraftGates interface {
	// Draft is draft id; false when there is none.
	Draft(ctx context.Context, id draft.ID) (draft.Draft, bool, error)
	GateOf(ctx context.Context, d draft.Draft) (gate.Gate, bool, error)
}

DraftGates reads a draft and the gate it waited on, as the outbox keeps them.

type Gates added in v0.3.0

type Gates interface {
	// OpenNamed opens the gate name declares, of its kind and intents, on g's
	// task and unit.
	OpenNamed(ctx context.Context, name string, g gate.Gate) (gate.Gate, error)
}

Gates opens the gates of gates.toml by name.

type Gone added in v0.4.0

type Gone struct{ Reason string }

Gone is a Refusal no retry can pass: what the request acts on is gone or closed. errors.As reads it as a Refusal too.

func (Gone) As added in v0.4.0

func (g Gone) As(target any) bool

func (Gone) Error added in v0.4.0

func (g Gone) Error() string

type Guarder added in v0.6.0

type Guarder interface {
	Guard(ctx context.Context, t Turn) error
}

Guarder is a Runner that can refuse a turn before any effect applies.

type Guides added in v0.6.0

type Guides interface {
	// Ready refuses a turn of d whose instructions compose guides that do
	// not read.
	Ready(d Def) error
}

Guides are the profile's guides an intent's instructions compose.

type Handles

type Handles interface {
	// SessionOf is the session whose process the manager addressed by handle.
	SessionOf(ctx context.Context, manager, handle string) (string, bool, error)
	// SessionOfHandle is SessionOf over every manager; ok is false when no
	// manager or more than one gave the handle out.
	SessionOfHandle(ctx context.Context, handle string) (id, manager string, ok bool, err error)
	// BindHandle makes handle the session's open handle, ending the one before.
	BindHandle(ctx context.Context, id, manager, handle, runtime string, at time.Time) error
	// EndHandle ends the session's open handle: the session is dormant.
	EndHandle(ctx context.Context, id string, at time.Time) error
}

Handles maps the handles managers gave the processes of a session to the session's id.

type HeadlessAgent

type HeadlessAgent interface {
	Headless(ctx context.Context, s AgentSession, prompt string) ([]byte, error)
}

HeadlessAgent is an Agent that also runs one session to its end without a terminal, in s.Worktree with s.Home.

type HeadlessEnd

type HeadlessEnd struct {
	Rec    record.Record
	Answer Answer // cost, tokens, model
	Err    error
}

type HeadlessStart

type HeadlessStart struct {
	Unit     unit.Unit
	Intent   turn.Intent
	Turn     string
	Trigger  turn.Trigger
	Guidance string
	Workflow string
	// Role is the role the turn's intent holds, "" none.
	Role   string
	Items  []string
	Task   string
	Inputs map[string]any
	// ResumeOf is the headless turn whose question this run answers, 0 none.
	ResumeOf int64
}

HeadlessStart is what a headless runner rendered of a turn. Its Unit, Intent, Trigger, Guidance, Inputs and ResumeOf are the admitted Turn's: BeginHeadless records those of the Turn it is given.

type HomeDefaulter

type HomeDefaulter interface {
	IsDefaultHome(home string) bool
}

HomeDefaulter is an agent that tells its default configuration home from another one.

type IdleWaiter

type IdleWaiter interface {
	WaitIdle(ctx context.Context, handle string, timeout time.Duration) (idle bool, err error)
}

IdleWaiter is a Sessions that can wait, up to timeout, for an agent's prompt to take input again.

type Intents

type Intents interface {
	// Rules errs, saying why, for an intent whose records cannot be checked.
	Rules(intent string) (dintent.RecordRules, error)
	Answerable() []string
	ClosesWhenDone(intent string) bool
	Reconcile(intent string) string
	SessionTitles() []string
}

Intents is what the turns ask of the loaded intents: the record rules, the intents an answer can address and what closes, reconciles and titles their sessions.

type InvalidAnswer

type InvalidAnswer struct{ Reason string }

InvalidAnswer is an answer the question does not take.

func (InvalidAnswer) Error

func (e InvalidAnswer) Error() string

type KeptBack added in v0.6.0

type KeptBack interface {
	KeptBack(guidance string)
}

KeptBack is a Runner told of the guidance Start kept back for the unit's next turn, so the person who asked hears of it; it is not told when the guidance the request gave was dropped.

type KeptGuidance added in v0.6.0

type KeptGuidance interface {
	Take(ctx context.Context, u unit.Unit) (string, error)
	// Keep stores guidance a turn took and did not use, unless newer guidance is stored.
	Keep(ctx context.Context, u unit.Unit, guidance string) error
}

KeptGuidance is the user's guidance kept for a unit's next turn.

type Key

type Key struct{ Turn, Session string }

Key finds a book by the id of one of its turns or by the handle a turn was sent to or started on; the newest matching turn wins.

type LastAgents

type LastAgents interface {
	LastAgents() (agents []AgentObservation, ok bool)
}

LastAgents is a Sessions whose agents can be read from its last snapshot, without asking the manager; ok is false when they are unknown.

type Launch

type Launch struct {
	Unit     unit.Unit
	Intent   turn.Intent
	ResumeOf int64
	Answer   string
	Guidance string
	Inputs   map[string]any
	// Trigger is the new turn's, also when it resumes an earlier turn's
	// session.
	Trigger turn.Trigger
	// WorkspaceID, Home and Model are set by the probe: run in this
	// workspace, with this agent home and model, instead of the intent's rules.
	WorkspaceID, Home, Model string
	// Why is the workflow that started the turn; nil for a turn started by hand.
	Why *workflow.Why
	// ByPerson is a new turn a person asked for, whatever its Trigger.
	ByPerson bool
	// Turn is the turn the Launcher records, as Start or Resume admitted
	// it; its Unit, Intent, Guidance, Inputs, Trigger and ResumeOf are the
	// launch's.
	Turn Turn
}

type Launcher

type Launcher interface {
	Launch(ctx context.Context, l Launch) (Outcome, error)
}

Launcher runs a turn the core asks for (a resume or a Continue) through the round code: it ensures the workspace, picks or starts a turn-capable session, renders and sends the turn through Service.Send.

type Ledger

type Ledger interface {
	coreitems.Applier
	Log(ctx context.Context, u unit.Unit, since time.Time) ([]coreitems.LogEntry, error)
}

Ledger is the items ledger a record's ops go to, and the unit's items and op outcomes its turns' instructions list.

type Live

type Live struct {
	Session    turn.Session
	LastOutput time.Time
}

type Loop added in v0.6.0

type Loop interface {
	Enter(ctx context.Context, u unit.Unit) (context.Context, func(), error)
}

Loop is the loop's mutex: Enter reads ahead what u's turn reads, takes the mutex and returns the context to run under and its release.

type ManagerIdleWaiter

type ManagerIdleWaiter interface {
	WaitIdle(ctx context.Context, handle string, timeout time.Duration) (idle bool, err error)
}

ManagerIdleWaiter is a ManagerSessions that can wait for a process's prompt to take input again.

type ManagerLastAgents

type ManagerLastAgents interface {
	LastAgents() (agents []AgentObservation, ok bool)
}

ManagerLastAgents is a ManagerSessions whose agents can be read from its last snapshot.

type ManagerRefresher

type ManagerRefresher interface{ Refresh() }

ManagerRefresher is a ManagerSessions whose reads come from a snapshot.

type ManagerSessions

type ManagerSessions interface {
	Processes(ctx context.Context, workspaceID string) ([]Process, error)
	Agents(ctx context.Context) ([]AgentObservation, error)
	Type(ctx context.Context, handle, line string) (submitted bool, err error)
	Census(ctx context.Context) (ProcessCensus, error)
	// Close ends the handle's process; one already gone is not an error.
	Close(ctx context.Context, handle string) error
}

ManagerSessions is one workspace manager's processes, addressed by its handles; the router also asks it its manager's Name.

type Notices added in v0.3.0

type Notices interface {
	// Notice is the text named name over data.
	Notice(name string, data map[string]any) (string, error)
}

Notices words what the loop tells an agent's session, from the profile.

type Outcome added in v0.6.0

type Outcome struct {
	ID, Head  string
	Submitted bool
}

Outcome is what a runner did with a turn: the id it recorded the turn under, the head it saw and whether the prompt reached the agent.

type Policy

type Policy struct {
	// Allow and Deny are command prefixes; a token may hold a * wildcard.
	Allow, Deny [][]string
	// WritePaths are directories, relative to the worktree, the agent may
	// write files in.
	WritePaths []string
	// TurnEnd lets the session call the loop's turn_end tool without a prompt.
	TurnEnd bool
	// DraftTools are the tools that propose or revise a draft, which the session may call without a prompt.
	DraftTools []string
	NoMCP      bool
	// Strict makes the policy the only permissions: the user's permission
	// mode, hooks and the worktree's own settings do not apply. A hook that
	// rewrites a command takes it out of the allow rules.
	Strict bool
	// UserSettingsOnly starts the session with the user's own agent
	// settings alone: the worktree's settings, hooks, MCP servers and
	// instruction files do not load.
	UserSettingsOnly bool
	// DenyPaths are absolute paths the agent may neither read nor write.
	DenyPaths []string
}

Policy is what a session may run, as command prefixes; each agent translates it into its own permission settings.

func (Policy) Denied

func (p Policy) Denied(c Control) Policy

Denied is p with every command and path of c denied.

func (Policy) WithoutSourceWrites added in v0.5.0

func (p Policy) WithoutSourceWrites(s dintent.Session, writes [][]string) Policy

WithoutSourceWrites is p with writes, the command prefixes the plugins' manifests declare as writes to their source, denied when s, the session of an intent, sets source_writes = false.

type Preparer added in v0.6.0

type Preparer interface {
	PrepareTurn(ctx context.Context, intent string, u unit.Unit, guidance string, inputs map[string]any) (map[string]any, error)
}

Preparer runs the prepare of an intent's role, which fills the turn's inputs; a refusal wraps ErrRefused, a prepare out of reach ErrTransient.

type Process

type Process struct {
	// Key joins the process to the agents running in it; opaque, set by the adapter.
	Handle, Key, Title, Agent string
	LastOutput                time.Time
}

Process is a live run of a session, as its manager lists it: Handle is the manager's address of it, never a session's identity.

type ProcessCensus

type ProcessCensus struct {
	Handles map[string]string
	// Complete is false when the list may leave processes out: cut short, a host
	// left out, or the manager not ready.
	Complete bool
	// RuntimeID names the manager instance that answered; another one after a
	// restart may list other handles.
	RuntimeID string
	At        time.Time
	// Orphans are the listed handles no app window shows, with no agent in
	// them, each with its last output, zero when unknown.
	Orphans map[string]time.Time
	// Epoch is the renderer graph epoch the list was read in: it changes when
	// the app's windows restart, while RuntimeID stays; "" when unknown.
	Epoch string
	// Shown says a window of the app showed some listed terminal.
	Shown bool
}

ProcessCensus is every process handle one manager lists, with its workspace id.

type ProcessRef

type ProcessRef struct{ Manager, Handle string }

ProcessRef is a process's manager and handle.

type PromptFacts

type PromptFacts struct {
	// Knowable is false when neither the prompt hook nor a readable
	// transcript tells when a person last prompted the session.
	Knowable bool
	// TypedAfterTurn is a managed session prompted after the loop's last turn.
	TypedAfterTurn bool
	// PromptedWhileIdle is a session prompted after its idle period began.
	PromptedWhileIdle bool
}

PromptFacts are what session.close's prompt guard reads, as facts.

type Prompts

type Prompts interface {
	// LastUserPrompt is ok false when the session's transcript cannot be
	// found or read; a readable one with no prompt is ok with a zero at.
	LastUserPrompt(ctx context.Context, sess turn.Session) (at time.Time, ok bool, err error)
}

Prompts reads, from the agent's own transcript, when a person last prompted a session.

type QuestionError

type QuestionError struct {
	Question string
	// Root is the folder whose answer the agent's home records.
	Root    string
	Message string
	Cause   error
}

QuestionError is a session start that waits on a question of the agent only the user answers.

func (*QuestionError) Error

func (e *QuestionError) Error() string

func (*QuestionError) Unwrap

func (e *QuestionError) Unwrap() error

type Questions

type Questions interface {
	// BlockedOn names the question a session's screen shows that the
	// workspace manager does not report, "" for none.
	BlockedOn(screen string) string
	// Explain is the error that tells the user what to do about question in
	// a session of s, nil for a question the kind does not know. A trust
	// question is an *UntrustedError, any other a *QuestionError.
	Explain(ctx context.Context, s AgentSession, question string) error
	// Unanswered says whether s's home still records no answer to question
	// for s's worktree.
	Unanswered(ctx context.Context, s AgentSession, question string) bool
}

Questions is what an agent knows of the questions a starting session stops on that only the user answers. None of it writes.

type RecordRequest

type RecordRequest struct {
	Session, AgentSession, Turn string
	// Unit is set when the command line names it; MCP does not.
	Unit unit.Unit
	// Via is "mcp" or "socket", written into turn_ended's data.
	Via    string
	Record record.Record
}

type Recorded

type Recorded struct {
	Unit  unit.Unit
	State record.State
	Added bool
	// Note tells the agent its record changes nothing: the turn was replaced
	// or dismissed.
	Note string
	// Ledger is what the items ledger made of the record's ops; nil when
	// none were applied.
	Ledger *coreitems.Result
	// Dropped counts the record's ops left unapplied because the turn had
	// already ended or was replaced.
	Dropped int
	// contains filtered or unexported fields
}

func (Recorded) DroppedNote

func (r Recorded) DroppedNote() string

DroppedNote tells the agent its ops did not reach the ledger; "" when none were dropped.

type Refresher

type Refresher interface{ Refresh() }

Refresher is a Sessions whose reads come from a snapshot: Refresh marks its agents and terminals stale and starts reloading them without waiting.

type Refusal

type Refusal struct{ Reason string }

Refusal is a request the turn's state or the caller's identity refuses.

func (Refusal) Error

func (r Refusal) Error() string

type Registry

type Registry interface {
	Session(ctx context.Context, id string) (turn.Session, bool, error)
	SaveSession(ctx context.Context, s turn.Session, evs ...port.Event) error
	// Sessions lists the sessions not closed.
	Sessions(ctx context.Context) ([]turn.Session, error)
	// LastStops returns the newest stop of each handle that logged one.
	LastStops(ctx context.Context, handles []string) (map[string]turn.Stop, error)
	// LogStop stores s.
	LogStop(ctx context.Context, s turn.Stop, evs ...port.Event) error
}

Registry is the sessions; the store behind it also keeps their Handles.

type Report

type Report struct {
	Unrecorded []unit.Unit
	// Closed are the asked turns the user's answer in the source closed.
	Closed       []unit.Unit
	GoneSessions []string
	// Queued are the pull requests with an answer queued for a busy session,
	// for Deliver.
	Queued []unit.Unit
	// Warnings are the Orca reads that failed; a workspace whose terminals
	// could not be read counts as listing none.
	Warnings []string
}

type Reports

type Reports interface {
	// WithTurns lists the units with at least one turn of i that is not
	// withdrawn.
	WithTurns(ctx context.Context, i turn.Intent) ([]unit.Unit, error)
}

type Request added in v0.6.0

type Request struct {
	Unit     unit.Unit
	Intent   turn.Intent
	Guidance string
	Inputs   map[string]any
	Trigger  turn.Trigger
	// Route is how the turn goes out, as the plugin's turn effects read it.
	Route string
	// ByPerson is a turn a person asked for.
	ByPerson bool
	// Reason is how the person asked for it, as the host's sent effects
	// record it; "" for the route's own.
	Reason string
	// ResumeOf is the turn whose session the new turn resumes, 0 none.
	ResumeOf int64
	// Planned is a turn that sends a round its unit's plan named, whose
	// marks the plan writes once the round is sent.
	Planned bool
}

Request is a new turn an entry asks for.

type Results added in v0.3.0

type Results interface {
	// UnitOf is the unit a web address names; false for an address of none.
	UnitOf(url string) (unit.Unit, bool)
	Attach(ctx context.Context, tk task.ID, u unit.Unit) error
}

Results attaches to a task the unit a turn on it produced.

type Resumer

type Resumer interface {
	Resume(home, agentSession string) string
}

Resumer is an agent's resume command, as a session_closed line names it.

type Router

type Router struct {
	// Managers are the enabled managers in their configured order.
	Managers []namedSessions
	Registry interface {
		Session(ctx context.Context, id string) (sessionHandle, bool, error)
	}
	Handles Handles
	// contains filtered or unexported fields
}

Router is the sessions of every enabled manager, addressed by session id: it routes each call to the manager the session's open handle belongs to.

func NewRouter

func NewRouter(reg Registry, managers ...namedSessions) *Router

NewRouter routes over managers, resolving handles through reg. NewRouter routes over managers, each a ManagerSessions with a Name, resolving handles through reg, which must keep them.

func (*Router) Agents

func (r *Router) Agents(ctx context.Context) ([]AgentObservation, error)

Agents are every reachable manager's agents; a manager that cannot be read lists none, and only all of them failing is an error.

func (*Router) Census

func (r *Router) Census(ctx context.Context) (Census, error)

Census is every manager's census, keyed by the session that took each handle; a manager that cannot be read counts as incomplete, never as listing no session.

func (*Router) Close

func (r *Router) Close(ctx context.Context, id string) error

func (*Router) Forget

func (r *Router) Forget(manager, handle string)

Forget drops the cached session of the manager's handle, for a handle bound anew.

func (*Router) LastAgents

func (r *Router) LastAgents() ([]AgentObservation, bool)

func (*Router) Refresh

func (r *Router) Refresh()

func (*Router) Terminals

func (r *Router) Terminals(ctx context.Context, workspaceID string) ([]Terminal, error)

Terminals are the processes every manager lists in the workspace, each with the session that took its handle, "" for none.

func (*Router) Type

func (r *Router) Type(ctx context.Context, id, line string) (bool, error)

func (*Router) WaitIdle

func (r *Router) WaitIdle(ctx context.Context, id string, timeout time.Duration) (bool, error)

func (*Router) With

func (r *Router) With(m namedSessions) *Router

With adds m, a ManagerSessions with a Name, after the router's managers.

type Run added in v0.3.0

type Run struct {
	Turn          turn.Turn
	Manager       string
	Workspace     string
	Worktree      string
	Session       string
	State         string
	Resume        string
	HasTranscript bool
}

Run is one turn on a task as its timeline shows it: the workspace manager, workspace path and worktree it ran in, its agent session, the session's live state and the command that resumes it. A headless call has no Manager, Workspace or Session.

type Runner added in v0.6.0

type Runner interface {
	Run(ctx context.Context, t Turn) (Outcome, error)
}

Runner renders, places, records and delivers a turn Start admitted. An Outcome with no ID is a turn the runner did not record; a runner that recorded the turn and then failed answers its ID with the error.

type SendRequest

type SendRequest struct {
	Unit           unit.Unit
	Intent         turn.Intent
	Turn           string
	Trigger        turn.Trigger
	Guidance, Head string
	ResumeOf       int64
	// Inputs are the intent's inputs the turn is sent with.
	Inputs map[string]any
	// Agent is the agent of the pull request's project.
	Agent string
	// BriefRun is the brief run the turn's instructions carry, 0 for none.
	BriefRun int64
	// Records is false for a dry run and the take-over question: no turn.
	Records bool
	// Workflow is the workflow whose turn.start step started the turn, "" none.
	Workflow string
	// Role is the role the turn's intent holds, "" none.
	Role string
	// PerSession replaces, on a start by hand, only the open turns of the
	// intent on the starting session, as the role says.
	PerSession bool
	// Items and Task are the unit's item ids and the task the turn was asked about, kept with
	// the turn so its drafts are tied to them.
	Items []string
	Task  string
}

SendRequest is what a runner rendered of a turn. Its Unit, Intent, Trigger, Guidance and ResumeOf are the admitted Turn's: a sink records those of the Turn it is given.

type Service

type Service struct {
	Store    Store
	Registry Registry
	// AgentSessions is nil when nothing keeps agent sessions.
	AgentSessions AgentSessions
	Sessions      Sessions
	Launcher      Launcher
	// Starter admits the new turns Launch starts; nil starts none.
	Starter *Starter
	// Answers are the user's answers asked turns reconcile with; nil reads
	// none.
	Answers Answers
	// Changed tells the views the pull requests whose turns changed; nil
	// does nothing.
	Changed func(ctx context.Context, refs ...unit.Unit)
	Pub     port.Publisher
	Clock   port.Clock
	// Command is how messages name the binary.
	Command string
	// Chats are the chat messages a session's stop tells of; nil tells of none.
	Chats Chats
	// Notices words what the loop tells a session; nil names each notice and its data.
	Notices Notices
	// FastJob is the configured interval of the fast job Reconcile runs on.
	FastJob time.Duration
	// OrphanAfter is how long a process stays orphaned, with no output, before
	// OrphanDurable holds without a renderer restart; zero is DefaultOrphanAfter.
	OrphanAfter time.Duration
	// OrphanHold is how long a dormant session's close waits on its lingering
	// orphan, the app attached throughout; zero is DefaultOrphanHold.
	OrphanHold time.Duration
	// AgentFor is the agent the sessions of the unit's project run, the
	// top-level kind for the zero unit, nil for none; with nil, a session_closed
	// line names no resume command.
	AgentFor func(u unit.Unit) Resumer
	// Intents is the loaded intents; nil is a wiring error that fails the
	// calls that need them.
	Intents Intents
	// Log reports what fails without failing the call; nil drops it.
	Log func(format string, args ...any)
	// Prompts is nil when no transcript can be read.
	Prompts Prompts
	// Items is nil when records' ledger ops are not applied.
	Items Ledger
	// Gates opens the gate an intent's record.missing names when a turn of it
	// ends without the record it requires; nil opens none.
	Gates Gates
	// Results attaches a done record's outcome url to the turn's task when
	// its intent's record.attach_url says so; nil attaches nothing.
	Results Results
	// DraftGates read the gate a sent draft waited on, for whether the user approved it; nil reads none,
	// so no sent draft counts as the user's.
	DraftGates DraftGates
	// DraftVerdict is the verdict a sent draft posted, as its kind's manifest declares it; nil, or "",
	// records none, so the turn publishes no verdict.
	DraftVerdict func(d draft.Draft) string
	// Usage is where EndHeadless writes a headless turn's usage; nil writes none.
	Usage UsageWriter
	// NewID mints session ids; nil mints random UUIDs.
	NewID func() string
	// Headless runs a headless turn again after the user answered its question; said is the answer as
	// Book.Said renders it. Set by the wiring to headless.Service.Again; nil routes the answer refused.
	Headless func(ctx context.Context, q turn.Turn, said string) (AnswerResult, error)
	// contains filtered or unexported fields
}

Service runs the turn use cases: the loop sends, starts, records, answers, resumes and reconciles turns, with the calling session as identity.

func (*Service) Abandoned

func (s *Service) Abandoned(ctx context.Context, handle string) error

Abandoned marks closed a session the loop started for a round that never reached it, so no later round types into it.

func (*Service) Answer

func (s *Service) Answer(ctx context.Context, r AnswerRequest) (AnswerResult, error)

Answer stores the user's answer to the pull request's question and routes it: typed into the session that asked, queued while it is busy until Deliver types it, or a resume turn when that session is gone, cold or not turn-capable. An answer to a failed or unrecorded turn always resumes it: only a resume turn owes a record.

func (*Service) BeginHeadless

func (s *Service) BeginHeadless(ctx context.Context, t Turn, h HeadlessStart) (int64, error)

BeginHeadless stores t, a turn sent and started with Mode headless and no handle, with Items in the turn's Inputs under "items"; ErrHeadlessBusy when the unit already has a headless turn started.

func (*Service) Bind

func (s *Service) Bind(ctx context.Context, id, manager, handle, runtime string) error

Bind makes handle the live process of the session id, which a manager just started or woke. A session a hook or a sweep took from the same process before the bind merges into id: its first sightings move over and it closes.

func (*Service) Busy added in v0.3.0

func (s *Service) Busy(ctx context.Context, sess turn.Session) (bool, error)

Busy says whether sess's agent is working or waiting on a permission, as an answer's route reads it: a chat to it waits for its next stop.

func (*Service) Capable

func (s *Service) Capable(ctx context.Context, handle string) (bool, error)

Capable says whether the loop may type a turn into the handle's session.

func (*Service) Census

func (s *Service) Census(ctx context.Context) error

Census reads every manager's census and marks the active sessions whose manager's complete census misses their process, and those it lists orphaned; it changes nothing but waking a dormant session whose process is listed again in a window of its app. ProcessGone then names the ones missed by two censuses at least FastJob apart, and OrphanDurable the orphans proven durable. A manager that cannot list completely marks none of its sessions.

func (*Service) ClaimFor added in v0.3.0

func (s *Service) ClaimFor(ctx context.Context, id string, u unit.Unit) error

ClaimFor makes u the unit of the session id whatever unit it had, for a session that attaches to u.

func (*Service) CloseOrphan added in v0.4.0

func (s *Service) CloseOrphan(ctx context.Context, id string) error

CloseOrphan ends the session's orphaned process when CloseOrphanRefusal allows it and a fresh census still lists the process orphaned with no agent in the runtime and epoch the proof was made in. It records nothing on the session: the censuses that then miss the process mark it dormant.

func (*Service) CloseOrphanRefusal added in v0.4.0

func (s *Service) CloseOrphanRefusal(ctx context.Context, id string) (string, error)

CloseOrphanRefusal is why CloseOrphan may not end the session's orphaned process, "" when it may: the guards of session.close but the shown terminal it no longer has, and the census's proof that the orphan is durable. It writes nothing; an error is a read that failed.

func (*Service) CloseRecord added in v0.4.0

func (s *Service) CloseRecord(ctx context.Context, handle, reason string) error

CloseRecord is CloseSession for a session whose workspace goes away: it also closes a dormant session whose orphan lingers, which ends no process, as nothing is left to reattach it to.

func (*Service) CloseRefusal

func (s *Service) CloseRefusal(ctx context.Context, handle string) (string, error)

CloseRefusal is why session.close may not close the handle's session, "" when it may. It writes nothing; an error is a read that failed.

func (*Service) CloseSession

func (s *Service) CloseSession(ctx context.Context, handle, reason string) error

CloseSession closes the handle's session for reason when CloseRefusal allows it, and records session_closed with its resume line.

func (*Service) Continue

func (s *Service) Continue(ctx context.Context, u unit.Unit) error

Continue resumes the unit's asked or stopped turn with no answer.

func (*Service) Deliver

func (s *Service) Deliver(ctx context.Context, units ...unit.Unit) error

Deliver routes the queued answers of units, as Answer would have, once their sessions are no longer busy. A queued answer whose turn no longer waits on the user is refused.

func (*Service) DeliverStopped

func (s *Service) DeliverStopped(ctx context.Context, handle string) error

DeliverStopped routes the queued answer of the handle's session, which just stopped, whatever Orca still shows of it.

func (*Service) Dismiss

func (s *Service) Dismiss(ctx context.Context, u unit.Unit) error

Dismiss closes the unit's asked or stopped turn without an answer.

func (*Service) DismissTurn

func (s *Service) DismissTurn(ctx context.Context, u unit.Unit, seq int64, reason string) error

DismissTurn closes the unit's open or stopped turn seq for reason and refuses its queued and pending answers, so none is typed into it later.

func (*Service) DormantFor

func (s *Service) DormantFor(ctx context.Context, u unit.Unit, manager, workspaceID string, ghosts bool) (turn.Session, time.Time, bool, error)

DormantFor is the newest dormant session of u in the workspace that its manager could wake, with when it was last active. With ghosts, the caller knows the manager lists no process in the workspace, so an active session there is one whose process just died and counts as dormant too.

func (*Service) DormantRefusal added in v0.4.0

func (s *Service) DormantRefusal(ctx context.Context, id string) (string, error)

DormantRefusal is why MarkDormant may not retire the session whose process its manager lists orphaned, "" when it may: the census has listed it orphaned for FastJob (ProcessOrphaned), and session.close's guards that need no shown terminal pass. It writes nothing.

func (*Service) DraftEnded added in v0.5.0

func (s *Service) DraftEnded(ctx context.Context, d draft.Draft) error

DraftEnded ends, when d failed or was dropped, the asked turn that waits on d because the user's answer approved it: the turn ends done with d in its outcome and no url, approved by nobody, so the unit is free for the round its draft facts start. A turn that only points to d, with no such answer, still asks.

func (*Service) DraftRecorded added in v0.5.0

func (s *Service) DraftRecorded(ctx context.Context, u unit.Unit, id string, ref record.DraftRef) error

DraftRecorded fills, when turn id on u has just recorded done with outcome.draft ref and no url, the url of that draft if it is sent already, as DraftSent does when the send comes after the record: a rule may release and post a draft before its turn records it. Only a draft of that turn's chain, or of its session, on u counts.

func (*Service) DraftSent added in v0.5.0

func (s *Service) DraftSent(ctx context.Context, d draft.Draft) error

DraftSent ends the turn of d's chain that waits on d now that d is sent: an asked turn whose question points to d ends done, and a done turn whose outcome left d in its url's place gets d's url. The url is d's evidence permalink and the verdict the one DraftVerdict reads from d, never the agent's. The outcome says the user approved d only when d's gate was resolved by a person, or a session the user drives that neither proposed nor revised d, at the rev the turn pinned; a rule's or a window's release never does. A draft of no turn, or of a chain whose turns point elsewhere, ends nothing, and a call made again changes nothing more.

func (*Service) EndHeadless

func (s *Service) EndHeadless(ctx context.Context, seq int64, e HeadlessEnd) (Recorded, error)

EndHeadless stores the record (failed with Err as its summary when set, or with the problems of a record that does not fit the intent's rules), applies its ledger ops as a turn_end does, writes turn_usage from Answer with usage_source "headless" and emits the usual turn events.

func (*Service) EndInterruptedHeadless

func (s *Service) EndInterruptedHeadless(ctx context.Context, perCallUSD float64) (int, error)

EndInterruptedHeadless ends failed, as interrupted by a restart, every headless turn left started, charging each perCallUSD since its cost is unknown; the daemon calls it at start, before any headless run.

func (*Service) KeepSessions

func (s *Service) KeepSessions(ctx context.Context) error

KeepSessions registers the agent terminals that carry the loop's titles and keeps the idle period of every open managed session.

func (*Service) LastRun added in v0.3.0

func (s *Service) LastRun(ctx context.Context, u unit.Unit) (turn.Turn, bool, error)

LastRun is u's newest turn that ran in a session, which a new turn can resume; false when none did.

func (*Service) Launch added in v0.3.0

func (s *Service) Launch(ctx context.Context, l Launch) error

Launch starts l's turn through the Starter, which runs it through the Launcher. A turn that resumes an earlier one's session is a new turn too, with its own trigger whatever the turn it resumes was.

func (*Service) Launched

func (s *Service) Launched(ctx context.Context, st turn.Session) error

Launched registers a session the loop started; its start time comes from the SessionStart hook.

func (*Service) LiveOn added in v0.3.0

func (s *Service) LiveOn(ctx context.Context, units ...unit.Unit) (turn.Session, bool, error)

LiveOn is the newest started session with a live process whose unit is one of units and that holds a turn on one of them; false when none is. A session with no turn there, as a start left waiting on the agent's trust dialog, cannot read the task's chat, so it is not the task's agent.

func (*Service) MCPSeen

func (s *Service) MCPSeen(ctx context.Context, handle string) error

MCPSeen notes an MCP initialize from the process the handle addresses; it may arrive before the SessionStart hook, and before the loop bound the handle of a session it started, which then takes it when bound.

func (*Service) MarkDormant

func (s *Service) MarkDormant(ctx context.Context, id string) error

MarkDormant records that the session's process is gone: its manager no longer lists it, or lists it orphaned, no window of the app showing it, where DormantRefusal allows. The session stays open, and its manager can wake it: a census that lists its process in a window again does. It refuses a session the manager still lists otherwise, one with no workspace, and a manager that cannot list completely. It ends no process.

func (*Service) MarkRead added in v0.3.0

func (s *Service) MarkRead(ctx context.Context, u unit.Unit, ids []int64) error

MarkRead notes that the agent read the answers ids of the unit, now; one read before keeps its time. A refused answer the agent reads reached it after all: it turns typed, so its question no longer asks.

func (*Service) MintID

func (s *Service) MintID() string

MintID mints a session id with the service's minter.

func (*Service) NextGone

func (s *Service) NextGone() time.Time

NextGone is the earliest time a census mark can make a session gone, zero when no session is marked; a session already gone has no deadline left.

func (*Service) OrphanDurable added in v0.4.0

func (s *Service) OrphanDurable(id string) bool

OrphanDurable says whether the last Census proved the open session's process a durable orphan: complete readings of the same runtime have listed it orphaned since it was first seen so, the latest renderer graph epoch held across two readings at least FastJob apart while the app's windows showed some terminal, and the orphan either outlived a change of epoch after staying orphaned for FastJob in an epoch whose windows showed some terminal, or stayed orphaned for OrphanAfter, every reading showing some terminal, with a known last output from before that run.

func (*Service) Placed

func (s *Service) Placed(ctx context.Context, id, workspaceID, worktree string, u unit.Unit)

Placed fills the workspace, worktree and unit of the session id while it has none, for a session the loop took from a live process. A failure is logged: the session works without them.

func (*Service) ProcessGone

func (s *Service) ProcessGone(id string) bool

ProcessGone says whether the last Census found the active session's process missing from two complete censuses of its manager's same runtime, at least FastJob apart.

func (*Service) ProcessLingers added in v0.4.0

func (s *Service) ProcessLingers(ctx context.Context, id string) (bool, error)

ProcessLingers says whether a fresh census lists a process of the session, orphaned or not, or cannot tell: waking it with a new process would run two on one agent session.

func (*Service) ProcessOrphaned added in v0.4.0

func (s *Service) ProcessOrphaned(id string) bool

ProcessOrphaned says whether complete censuses of the same runtime have listed the active session's process orphaned, with no agent in it, for at least FastJob: no window of the app shows it. It proves nothing about the process staying so; MarkDormant retires such a session without ending it.

func (*Service) PromptFacts

func (s *Service) PromptFacts(ctx context.Context, sess turn.Session, agent AgentObservation) (PromptFacts, error)

PromptFacts reads the session's prompt facts with the windows CloseRefusal uses; agent is the session's agent, zero when it has none. It writes nothing.

func (*Service) PromptSubmitted

func (s *Service) PromptSubmitted(ctx context.Context, handle, prompt string) error

PromptSubmitted notes a prompt the handle's session took, from its prompt hook: the user's, unless it is the line the loop typed within TypedEcho. A session the registry does not know is left alone.

func (*Service) Reconcile

func (s *Service) Reconcile(ctx context.Context, startup bool) (Report, error)

Reconcile closes the open turns whose sessions stopped without a record, that no agent started, or that the user's answer in the source closed. At start-up one observation of a done pane suffices and a session a complete census misses counts as stopped; later, only a closed one does.

func (*Service) RecordTurnEnd

func (s *Service) RecordTurnEnd(ctx context.Context, r RecordRequest) (Recorded, error)

RecordTurnEnd stores the record an agent ended its turn with. It returns record.Problems for a malformed record and a Refusal when the turn is not the caller's.

func (*Service) RefuseAnswer

func (s *Service) RefuseAnswer(ctx context.Context, u unit.Unit, id int64, reason string) error

RefuseAnswer refuses the unit's pending or queued answer id for reason; an answer already refused is left as it is.

func (*Service) Resolve

func (s *Service) Resolve(ctx context.Context, manager, handle string) (string, error)

Resolve is the session the manager's handle belongs to; a process no session took yet becomes a session of its own.

func (*Service) RunOf added in v0.3.0

func (s *Service) RunOf(ctx context.Context, seq int64) (Run, unit.Unit, bool, error)

RunOf is the run of turn seq and its unit; false when no book holds it.

func (*Service) RunningHeadless

func (s *Service) RunningHeadless(ctx context.Context) (int, error)

RunningHeadless counts the headless turns started and not ended, whichever process started them.

func (*Service) RunsOf added in v0.3.0

func (s *Service) RunsOf(ctx context.Context, u unit.Unit) ([]Run, error)

RunsOf are the runs of u, newest first: its turns but the withdrawn and replaced ones, each with the session it ran in. A run's Turn.AgentSession is the turn's agent session, else its session's.

func (*Service) Send

func (s *Service) Send(ctx context.Context, t Turn, r SendRequest) (turn.Turn, error)

Send stores t, a new turn, replacing the open one of the same intent. The views learn it from SentTo, once it is typed.

func (*Service) SentTo

func (s *Service) SentTo(ctx context.Context, u unit.Unit, id, handle string) error

SentTo names the session the turn was typed into.

func (*Service) SessionFor

func (s *Service) SessionFor(ctx context.Context, u unit.Unit, workspaceID string) (Live, bool, error)

SessionFor is the newest-started open session of u in that workspace whose handle the Sessions port lists as a usable terminal of the workspace, with that terminal's LastOutput for the warm rule.

func (*Service) SessionOfHandle

func (s *Service) SessionOfHandle(ctx context.Context, handle string) (string, bool, error)

SessionOfHandle is the session of a handle some manager gave out, for a caller that knows the handle alone, such as an MCP request; ok is false for a handle no session took.

func (*Service) SessionStarted

func (s *Service) SessionStarted(ctx context.Context, st SessionStart) error

SessionStarted upserts the session the SessionStart hook reports, filling empty fields and never clearing one.

func (*Service) Start

func (s *Service) Start(ctx context.Context, handle, id string) (turn.Turn, error)

Start marks the turn of id started on handle's session, the one an agent runs `instructions --turn` from.

func (*Service) StartByHand

func (s *Service) StartByHand(ctx context.Context, x Turn, r SendRequest, handle string) (turn.Turn, error)

StartByHand stores t, a turn the user started in handle's session, "" when the session runs outside Orca.

func (*Service) Stop

func (s *Service) Stop(ctx context.Context, r StopRequest) (StopAnswer, error)

Stop decides the Stop hook of the handle's session: allow, or block once per prompt when its turn owes a record.

func (*Service) TellChat added in v0.3.0

func (s *Service) TellChat(ctx context.Context, sess turn.Session, task unit.Unit) (bool, error)

TellChat types into live session sess the notice that the user wrote on the chat of the task whose own unit is task, which carries no message: the agent reads it with a tool, or with the command when the session has not loaded the loop's MCP server. It is false when the agent took the line without submitting it.

func (*Service) Typed

func (s *Service) Typed(ctx context.Context, handle, line string) error

Typed notes the line the loop typed into the handle's session, so its prompt hook and transcript tell it from the user's.

func (*Service) Typing

func (s *Service) Typing(handle string) (done func())

Typing marks the loop typing into the handle's session until done is called; session.close refuses it meanwhile, before the turn names the handle and before TypedAt moves.

func (*Service) UserDriven added in v0.4.0

func (s *Service) UserDriven(ctx context.Context, id string) (bool, error)

UserDriven says whether the user drives session id, as turn.Session.UserDriven reads it from the session; a session the registry does not know is not, nor one the loop is typing a turn into, which it stamps only once the line is typed.

func (*Service) Withdraw

func (s *Service) Withdraw(ctx context.Context, u unit.Unit, id, why string) error

Withdraw undoes the send of id's turn, one the loop failed to type: the turn is withdrawn and the turns it replaced are open again, as if it was never sent.

func (*Service) Woken

func (s *Service) Woken(ctx context.Context, id, manager, handle string) error

Woken records that the manager gave the dormant session id a live process again.

type SessionStart

type SessionStart struct {
	Session, Pane, WorkspaceID, AgentSession, Source, Cwd, Home string
	Agent, Transcript                                           string
}

SessionStart is what the SessionStart hook reports; Agent is the hook's agent.

type Sessionless added in v0.6.0

type Sessionless interface {
	Sessionless() bool
}

Sessionless is a Runner whose turn runs in no agent session, such as a headless call: the guidance of its turn is recorded only when its intent hands guidance.

type Sessions

type Sessions interface {
	Terminals(ctx context.Context, workspaceID string) ([]Terminal, error)
	Agents(ctx context.Context) ([]AgentObservation, error)
	Type(ctx context.Context, session, line string) (submitted bool, err error)
	// Census lists every session with a live process, in any state.
	Census(ctx context.Context) (Census, error)
	// Close ends the session's process; a session with none is not an error.
	Close(ctx context.Context, session string) error
}

Sessions are the live processes of the loop's sessions, addressed by session id.

type SettingsRenderer

type SettingsRenderer interface {
	Settings(p Policy) string
}

SettingsRenderer is an agent that renders a policy as the permission settings it reads, for a manager that writes them where the agent loads them instead of passing them on the command line.

type SourceAnswer added in v0.3.0

type SourceAnswer struct {
	// State is the answer's state in its source; Verdict is the record's
	// verdict it gives, "" for a state that answers nothing.
	ID, State, Verdict, URL string
	At                      time.Time
}

SourceAnswer is the user's answer, in a unit's source, to a turn that asked them, such as their review of a pull request.

type Starter added in v0.6.0

type Starter struct {
	Defs     Defs
	Preparer Preparer
	Kept     KeptGuidance
	Loop     Loop
	Effects  TurnEffects
	Store    Store
	// Guides check the profile's guides before anything is touched for a
	// turn; nil checks none.
	Guides Guides
	// Log reports what fails without failing the start; nil drops it.
	Log func(format string, args ...any)
}

Starter is the one way a new turn starts: it applies the intent's role and effects around the runner, in one order whatever entry asks.

func (*Starter) Resume added in v0.6.0

func (s *Starter) Resume(ctx context.Context, u unit.Unit, seq int64) (Turn, error)

Resume admits the turn that resumes u's stored turn seq: its intent, trigger, guidance and inputs, with no guidance taken and no host effect.

func (*Starter) ResumeAnswered added in v0.6.0

func (s *Starter) ResumeAnswered(ctx context.Context, u unit.Unit, seq int64, said string) (Turn, error)

ResumeAnswered is Resume of a turn whose guidance is the answer said, as a headless turn, which reads no resume of its own, takes it.

func (*Starter) Start added in v0.6.0

func (s *Starter) Start(ctx context.Context, r Request, x Runner) (Outcome, error)

Start admits r's turn under the loop and runs it with x.

type StopAnswer

type StopAnswer struct {
	Block  bool
	Reason string
}

type StopRequest

type StopRequest struct {
	Session, AgentSession, PromptID, LastMessage string
	Agent, Transcript                            string
}

StopRequest is what the Stop hook reports; Agent is the hook's agent.

type Store

type Store interface {
	// Books has a book for every unit, empty when it has no turn; with no unit,
	// the book of every unit with a turn.
	Books(ctx context.Context, units ...unit.Unit) (map[unit.Unit]turn.Book, error)
	BookOf(ctx context.Context, k Key) (turn.Book, bool, error)
	// UnitsOf maps each handle to the unit of the newest turn sent to or
	// started on it; a handle with no turn is absent.
	UnitsOf(ctx context.Context, handles []string) (map[string]unit.Unit, error)
	// Save writes the book and evs in one transaction and returns the book as
	// stored, with Seq and ID assigned to its new entries. A new record or
	// answer with TurnSeq 0, and a replaced turn with Before set and
	// ReplacedBy 0, belong to the book's newest new turn.
	Save(ctx context.Context, b turn.Book, evs ...port.Event) (turn.Book, error)
	// Open lists the units with a sent, started or asked turn.
	Open(ctx context.Context) ([]unit.Unit, error)
}

type Terminal

type Terminal struct {
	// Key joins the terminal to the agents running in it; opaque, set by the adapter.
	Session, Key, Title, Agent string
	// Manager and Handle address the process.
	Manager, Handle string
	LastOutput      time.Time
}

Terminal is a live process of a workspace, with the session that runs in it, "" for a process no session took; a session whose process the manager no longer lists is dormant.

type Tier

type Tier string

Tier is a provider-neutral class of model; each agent maps it to one of its own models.

const (
	// TierFast is the cheapest model, for short mechanical calls.
	TierFast Tier = "fast"
	// TierBalanced is the everyday workhorse.
	TierBalanced Tier = "balanced"
	// TierFrontier is the most capable model.
	TierFrontier Tier = "frontier"
)

func ParseTier

func ParseTier(s string) (Tier, error)

type TranscriptLine added in v0.3.0

type TranscriptLine struct {
	Role string
	Text string
	At   time.Time
}

TranscriptLine is one message of an agent session's transcript.

type Transcripts added in v0.3.0

type Transcripts interface {
	// Page is at most limit lines from line from (0-based), oldest first,
	// and the transcript's line count.
	Page(ctx context.Context, agentSession string, from, limit int) ([]TranscriptLine, int, error)
}

Transcripts pages an agent session's transcript.

type Turn added in v0.6.0

type Turn struct {
	// contains filtered or unexported fields
}

Turn is a turn Start or Resume admitted; a sink records it once.

func (Turn) Guidance added in v0.6.0

func (t Turn) Guidance() string

func (Turn) Inputs added in v0.6.0

func (t Turn) Inputs() map[string]any

func (Turn) Intent added in v0.6.0

func (t Turn) Intent() turn.Intent

func (Turn) ResumeOf added in v0.6.0

func (t Turn) ResumeOf() int64

func (Turn) Resumed added in v0.6.0

func (t Turn) Resumed() bool

Resumed is a turn Resume admitted, whose effects its first turn's start applied: Start applied none of its own.

func (Turn) Trigger added in v0.6.0

func (t Turn) Trigger() turn.Trigger

func (Turn) Unit added in v0.6.0

func (t Turn) Unit() unit.Unit

func (Turn) Use added in v0.6.0

func (t Turn) Use() error

Use claims t for the one record it allows.

type TurnEffects added in v0.6.0

type TurnEffects interface {
	// Check refuses a turn of d on u whose plugin effects no running plugin applies.
	Check(ctx context.Context, d Def, u unit.Unit) error
	// Before applies the host's effects that run before a person's turn goes out.
	Before(ctx context.Context, d Def, u unit.Unit) error
	// Recorded applies the plugin's effects of a recorded turn.
	Recorded(ctx context.Context, o TurnOut) error
	// Sent applies the host's effects of a person's turn that went out.
	Sent(ctx context.Context, o TurnOut) error
	// Handed records the guidance a turn carried.
	Handed(ctx context.Context, o TurnOut) error
}

TurnEffects apply the turn effects an intent names, each at its phase.

type TurnOut added in v0.6.0

type TurnOut struct {
	Def      Def
	Unit     unit.Unit
	Route    string
	Reason   string
	Guidance string
	Inputs   map[string]any
	Outcome  Outcome
	// Planned is a turn that sends a round its unit's plan named.
	Planned bool
}

TurnOut is what a turn's effects read of a turn the runner recorded.

type TurnUnits added in v0.3.0

type TurnUnits interface {
	UnitOfTurn(ctx context.Context, seq int64) (unit.Unit, bool, error)
}

TurnUnits is a Store that finds the unit of a turn by its seq without reading every book.

type UnheldPin added in v0.5.0

type UnheldPin struct {
	Where       string
	Draft       int64
	State, Gate string
}

UnheldPin is a pin of a record's question, at Where in the record, on draft Draft that no answer decides: its State is not held, or its gate's status Gate is not open ("" when it has none). State is "" when there is no such draft.

type UnheldPins added in v0.5.0

type UnheldPins []UnheldPin

UnheldPins refuses a record whose question pins drafts no answer decides.

func (UnheldPins) Error added in v0.5.0

func (p UnheldPins) Error() string

type UntrustedError

type UntrustedError struct {
	Folder string
	// Home is "" when the session runs with its terminal's own home.
	Home string
	// Root is the main checkout whose trust covers every worktree of its
	// repository; it outlives a worktree the loop removes.
	Root string
	// Fix is the command that trusts Root in Home, "" when the loop does not
	// suggest one.
	Fix string
	// Terminal is the terminal waiting on the dialog, "" for a preflight.
	Terminal string
	Cause    error
}

UntrustedError is a worktree the agent's home does not trust, so its session waits, or would wait, on the agent's trust dialog.

func (*UntrustedError) Error

func (e *UntrustedError) Error() string

func (*UntrustedError) Unwrap

func (e *UntrustedError) Unwrap() error

type UsageWriter

type UsageWriter interface {
	SaveUsage(ctx context.Context, seq int64, rows []dusage.Model, source string, at time.Time, evs ...port.Event) error
}

UsageWriter stores a turn's usage rows and marks it read by source.

Directories

Path Synopsis
Package turnstest holds the fakes of the turns ports and the contracts every implementation passes.
Package turnstest holds the fakes of the turns ports and the contracts every implementation passes.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL