turns

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Oct 26, 2026 License: Apache-2.0 Imports: 23 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 (
	// 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 (
	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
)

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 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 review appears on GitHub.

View Source
const ResumeWith = "; resume with: "

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

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 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 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 EntryOf

func EntryOf(t turn.Turn) string

EntryOf is the GTD entry the turn was asked from, kept in its inputs; "" none.

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 NewSessionID

func NewSessionID() string

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

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
	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, when not 0, is the Inbox message an agent posted during turn Turn, and Text the answer as the
	// agent reads it: typed into the posting session when idle, queued while busy, stored without a resume
	// when the session is gone.
	Message, Turn int64
}

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 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, the dossier).
	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 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
}

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) RuntimeOf

func (c Census) RuntimeOf(manager string) string

RuntimeOf is the runtime that answered for manager.

type Control

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

Control is what drives the workspace managers: command prefixes and paths a session the loop starts may neither run nor read, so it cannot steer the manager that hosts it or another session.

type Dir

type Dir struct {
	Path  string
	Write []string
}

Dir is an absolute path and the subpaths the agent may write, e.g. log, sources, drafts.

type GitHub

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

GitHub reads facts the collector already stored.

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
	Entry string
	// ResumeOf is the headless turn whose question this run answers, 0 none.
	ResumeOf int64
}

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 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 a new turn's; a resume inherits the trigger of the turn it
	// resumes and ignores this.
	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
}

type Launcher

type Launcher interface {
	Launch(ctx context.Context, l Launch) 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 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 MyReview

type MyReview struct {
	// State is APPROVED, CHANGES_REQUESTED or COMMENTED.
	ID, State, URL string
	At             time.Time
}

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
	// Drafts lets the session call the loop's slack_draft tool without a prompt; it posts nothing.
	Drafts         bool
	NoGitHubWrites bool
	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
	// Dirs are directories outside the worktree the agent may read, and write under their Write subpaths.
	Dirs []Dir
	// 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.

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
}

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
}

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 my review on GitHub 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 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 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
	// Items and Entry are the unit's item ids and the GTD entry the turn was asked about, kept with
	// the turn so its drafts are tied to them.
	Items []string
	Entry string
}

type Service

type Service struct {
	Store    Store
	Registry Registry
	// AgentSessions is nil when nothing keeps agent sessions.
	AgentSessions AgentSessions
	Sessions      Sessions
	Launcher      Launcher
	GitHub        GitHub
	// 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
	// FastJob is the configured interval of the fast job Reconcile runs on.
	FastJob 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
	// 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) AnswerText

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

AnswerText is the whole text of the newest answer typed into the handle's session, which a multi-line answer points the agent to.

func (*Service) BeginHeadless

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

BeginHeadless stores 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) 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; it changes nothing. ProcessGone then names the ones missed by two censuses at least FastJob apart. A manager that cannot list completely marks none of its sessions.

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) 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) 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) 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. The session stays open, and its manager can wake it. It refuses a session the manager still lists in any state, one with no workspace, and a manager that cannot list completely.

func (*Service) MintID

func (s *Service) MintID() string

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

func (*Service) NewestAnswer

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

NewestAnswer is the newest answer the user gave to a turn of the unit the handle's session owns, as the agent reads it, but one still queued; false when there is none.

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) 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) 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 my review on GitHub answered. 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) 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) Send

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

Send stores 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, r SendRequest, handle string) (turn.Turn, error)

StartByHand stores 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) 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) 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 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 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 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