Documentation
¶
Overview ¶
Package run executes agent conversations in the background and records their events.
A Run owns one live agent process (agent.Conversation) and an append-only, sequence-numbered event log. Transports (SSE, WebSocket, the synchronous query endpoint) are readers of that log: they can attach at any time, resume after a given sequence number and detach without affecting the run. Control actions (messages, interrupts, permission answers, close, cancel) are methods on Run. Finished runs are kept for a retention period so clients can reconnect and read the outcome.
Index ¶
- Constants
- Variables
- type Context
- type Control
- type ControlResolution
- type Cursor
- type ErrorCode
- type ErrorInfo
- type Event
- type Manager
- type Mode
- type Observation
- type ObservationTimes
- type Observations
- type Options
- type Permission
- type PermissionResolution
- type Progress
- type RequestTimes
- type Rules
- type Run
- func (r *Run) Answer(answer agent.PermissionAnswer, scope string) error
- func (r *Run) Cancel(cause error)
- func (r *Run) CloseInput() error
- func (r *Run) Control(ctx context.Context, request json.RawMessage) (json.RawMessage, error)
- func (r *Run) Done() <-chan struct{}
- func (r *Run) ID() string
- func (r *Run) Interrupt() error
- func (r *Run) Read(cursor *Cursor) (events []Event, changed <-chan struct{}, finished bool)
- func (r *Run) Respond(id string, response json.RawMessage, errMessage string) error
- func (r *Run) Send(text string) error
- func (r *Run) Snapshot() Snapshot
- func (r *Run) Stream(ctx context.Context, cursor Cursor, send func(Event) error) error
- type Snapshot
- type Status
- type Times
- type Trace
- type TurnInfo
- type Waiting
Constants ¶
const ( // EventAgent carries one native agent event in Data, unmodified. EventAgent = "agent" // EventTurn marks the end of a turn that answered a client message; Data is a TurnInfo. EventTurn = "turn" // EventPermissionRequest asks the client to allow or deny a tool; Data is a // Permission. Answer with Run.Answer. EventPermissionRequest = "permission_request" // EventPermissionResolved reports the answer to a permission request (from a client or // from a session/workspace rule); Data is a PermissionResolution. EventPermissionResolved = "permission_resolved" // EventControlRequest is a native control request from the agent that the client must // answer with Run.Respond; Data is a Control. EventControlRequest = "control_request" // EventControlResolved reports that a control request was answered; Data is a // ControlResolution. EventControlResolved = "control_resolved" // EventPartial carries incremental output (Data: native event). Partial events are not // stored: Seq is 0, they are only delivered to readers attached at that moment and are // dropped once the complete message is recorded. EventPartial = "partial" // EventDiagnostic carries bounded, redacted adapter diagnostics explicitly requested for // the run. Data is {"text":"..."}; it is retained but is not a native CLI event. EventDiagnostic = "diagnostic" // EventDone is the terminal event of a successful run; Data is the Snapshot. EventDone = "done" // EventError is the terminal event of a failed or cancelled run; Data is the Snapshot, // whose error says why. EventError = "error" )
Event types.
Variables ¶
var ( ErrCancelled = errors.New("run cancelled by client") ErrFinished = errors.New("run has finished") ErrNotInteractive = errors.New("run is not interactive") ErrInputClosed = errors.New("run input is closed") // ErrUnknownPermission means the permission request is not pending. ErrUnknownPermission = agent.ErrUnknownPermission // ErrUnknownControl means the control request is not pending. ErrUnknownControl = agent.ErrUnknownControl )
Errors returned by Run control methods.
var (
ErrNotFound = errors.New("run not found")
)
Causes used to stop a run.
Functions ¶
This section is empty.
Types ¶
type Context ¶
type Context struct {
WorkspaceID string `json:"workspace_id,omitempty"`
SessionID string `json:"session_id,omitempty"`
// NativeSessionID is the agent's own identifier of the conversation (Claude: the session
// ID, Codex: the thread ID).
NativeSessionID string `json:"native_session_id,omitempty"`
}
Context is the workspace and session of a run.
type Control ¶
type Control struct {
agent.ControlRequest
Times RequestTimes `json:"times"`
}
Control is a native control request the agent waits on; it is also the payload of an EventControlRequest.
type ControlResolution ¶
type ControlResolution struct {
ID string `json:"control_id"`
}
ControlResolution is the payload of an EventControlResolved.
type Cursor ¶
type Cursor struct {
Seq int64
// contains filtered or unexported fields
}
Cursor is a reader position: the last stored sequence number seen and the position in the partial buffer. The zero value starts at the beginning.
func CursorAfter ¶
CursorAfter returns a cursor that resumes after sequence number seq.
type ErrorCode ¶ added in v0.2.0
type ErrorCode string
ErrorCode is a stable ErrorInfo code.
const ( ErrorAgentRunFailed ErrorCode = "agent_run_failed" ErrorAgentStartFailed ErrorCode = "agent_start_failed" ErrorCancelled ErrorCode = "cancelled" ErrorEventLimit ErrorCode = "event_limit" ErrorNativeSessionBindFailed ErrorCode = "native_session_bind_failed" ErrorNativeSessionMissing ErrorCode = "native_session_missing" ErrorTimeout ErrorCode = "timeout" )
Run error codes. The API document and docs/api.md list them with their meaning.
func ErrorCodes ¶ added in v0.2.0
func ErrorCodes() []ErrorCode
ErrorCodes returns every run error code, sorted.
type ErrorInfo ¶
type ErrorInfo struct {
Code ErrorCode `json:"code" doc:"Stable code."`
Message string `json:"message"`
}
ErrorInfo says why a run failed or was cancelled.
type Event ¶
type Event struct {
Seq int64 `json:"seq"`
Type string `json:"type"`
Time time.Time `json:"time"`
Data json.RawMessage `json:"data"`
}
Event is one entry of a run's event log.
type Manager ¶
type Manager struct {
// contains filtered or unexported fields
}
Manager starts runs and keeps them addressable by ID.
func NewManager ¶
func NewManager(base context.Context, retention time.Duration, maxRetained int, logger *slog.Logger) *Manager
NewManager returns a Manager. Cancelling base cancels all running runs.
type Mode ¶
type Mode struct {
// Interactive runs accept further messages; an ask answers one prompt.
Interactive bool `json:"interactive"`
// Stateless is true for an ask without a workspace: no tools, nothing is kept, and the
// context is empty.
Stateless bool `json:"stateless"`
Permissions string `json:"permissions,omitempty" enum:"bypass,ask" doc:"Absent for a stateless ask."`
}
Mode is how the run was started.
type Observation ¶
type Observation struct {
agent.Observation
Times ObservationTimes `json:"times"`
}
Observation is the latest known state of a native task, subagent, or background process.
type ObservationTimes ¶
type ObservationTimes struct {
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
FinishedAt *time.Time `json:"finished_at,omitempty"`
}
ObservationTimes are the timestamps of an observation.
type Observations ¶
type Observations struct {
Items []Observation `json:"items"`
// Dropped counts observations not kept because of NATIVE_AGENT_MAX_RUN_OBSERVATIONS.
Dropped int `json:"dropped"`
}
Observations is the bounded observation list.
type Options ¶
type Options struct {
Agent agent.Agent
Request agent.Request
// Interactive keeps the conversation open after a turn until CloseInput, Cancel or
// IdleTimeout. Otherwise input is closed after the first turn.
Interactive bool
// TurnTimeout bounds each turn (including time spent waiting for permission answers).
TurnTimeout time.Duration
// IdleTimeout closes an interactive run that has had no turn for this long.
IdleTimeout time.Duration
MaxEvents int
MaxObservations int
// Release is called once when the run ends (frees concurrency slots and session locks).
Release func()
// Finished receives the immutable terminal snapshot exactly once.
Finished func(Snapshot)
// Started persists an opaque native session binding before the run is exposed.
Started func(nativeSessionID string) error
// Rules answers permission requests covered by session/workspace rules (may be nil).
Rules Rules
// RequestID is the X-Request-ID of the HTTP request that started the run; it is logged
// with every record of the run and shown in its snapshot.
RequestID string
}
Options describe one run.
type Permission ¶
type Permission struct {
agent.PermissionRequest
Times RequestTimes `json:"times"`
}
Permission is a permission request the agent waits on; it is also the payload of an EventPermissionRequest.
type PermissionResolution ¶
type PermissionResolution struct {
ID string `json:"permission_id"`
Kind string `json:"kind" enum:"command,file_change,mcp,other"`
Behavior string `json:"behavior" enum:"allow,deny"`
Scope string `json:"scope" enum:"once,session,workspace"`
// Auto is true when an existing session/workspace rule answered without asking.
Auto bool `json:"auto"`
}
PermissionResolution is the payload of an EventPermissionResolved.
type Progress ¶
type Progress struct {
Turns int `json:"turns" doc:"Turns that answered a client message."`
Events int64 `json:"events" doc:"Stored events."`
// InputClosed is true once no further messages are accepted.
InputClosed bool `json:"input_closed"`
}
Progress is how far the run got.
type RequestTimes ¶
RequestTimes are the timestamps of a pending request. Waiting for an answer counts toward the turn timeout.
type Rules ¶
type Rules interface {
Allowed(workspaceID, sessionID, kind string) (scope string, ok bool)
Allow(workspaceID, sessionID, kind, scope string)
}
Rules are the session/workspace permission rules consulted for permission requests. They match by permission kind.
type Run ¶
type Run struct {
// contains filtered or unexported fields
}
Run is one agent conversation executing in the background. It is safe for concurrent use.
func (*Run) Answer ¶
func (r *Run) Answer(answer agent.PermissionAnswer, scope string) error
Answer resolves a pending permission request. An allow with scope session or workspace also records a rule that answers later requests for the same tool automatically.
func (*Run) CloseInput ¶
CloseInput ends the conversation gracefully after the current turn.
func (*Run) Control ¶
func (r *Run) Control(ctx context.Context, request json.RawMessage) (json.RawMessage, error)
Control sends a native control request to the agent and returns its response.
func (*Run) Done ¶
func (r *Run) Done() <-chan struct{}
Done is closed when the run reaches a terminal status.
func (*Run) Interrupt ¶
Interrupt stops the current turn; an interactive run then waits for the next message.
func (*Run) Read ¶
Read returns the events after cursor (stored events first, then the partial events of the message in progress), advances cursor, and returns a channel closed on the next change and whether the run has finished.
type Snapshot ¶
type Snapshot struct {
ID string `json:"run_id"`
Status Status `json:"status" enum:"running,succeeded,failed,cancelled"`
// Context is where the run works; empty for a stateless ask.
Context Context `json:"context"`
Mode Mode `json:"mode"`
Progress Progress `json:"progress"`
Waiting Waiting `json:"waiting"`
// Observations are the native tasks, subagents and background processes of the run.
Observations Observations `json:"observations"`
// Result is the outcome of the latest turn that answered a client message.
Result *agent.Result `json:"result,omitempty"`
// Usage sums the token counts of every native turn of the run.
Usage agent.UsageTotal `json:"usage"`
// Error is set when the run failed or was cancelled.
Error *ErrorInfo `json:"error,omitempty"`
Times Times `json:"times"`
Trace Trace `json:"trace"`
}
Snapshot is the externally visible state of a run.
type Status ¶
type Status string
Status is the lifecycle state of a run.
type Times ¶
type Times struct {
CreatedAt time.Time `json:"created_at"`
// StartedAt is when the native process started.
StartedAt *time.Time `json:"started_at,omitempty"`
UpdatedAt time.Time `json:"updated_at"`
FinishedAt *time.Time `json:"finished_at,omitempty"`
}
Times are the run's timestamps.
type Trace ¶
type Trace struct {
// RequestID is the X-Request-ID of the HTTP request that started the run.
RequestID string `json:"request_id,omitempty"`
}
Trace correlates the run with logs.
type TurnInfo ¶
type TurnInfo struct {
Turn int `json:"turn" doc:"Number of the turn in this run, from 1."`
Result agent.Result `json:"result"`
}
TurnInfo is the payload of an EventTurn.
type Waiting ¶
type Waiting struct {
Permissions []Permission `json:"permissions"`
Controls []Control `json:"controls"`
}
Waiting are the requests the agent waits for the client to answer.