run

package
v0.2.1 Latest Latest
Warning

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

Go to latest
Published: Nov 11, 2026 License: Apache-2.0 Imports: 12 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 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

View Source
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

View Source
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.

View Source
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

func CursorAfter(seq int64) Cursor

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.

func (ErrorCode) Meaning added in v0.2.0

func (c ErrorCode) Meaning() string

Meaning describes the code, or returns "" for an unknown value.

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.

func (*Manager) Get

func (m *Manager) Get(id string) (*Run, error)

Get returns a run by ID.

func (*Manager) List

func (m *Manager) List() []Snapshot

List returns snapshots of all known runs, newest first.

func (*Manager) Running

func (m *Manager) Running() int

Running returns the number of runs that have not finished.

func (*Manager) Start

func (m *Manager) Start(opts Options) *Run

Start launches the agent process and returns the run. Process start failures produce a run that has already failed.

func (*Manager) Wait

func (m *Manager) Wait()

Wait blocks until every native process started by the manager has settled.

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

type RequestTimes struct {
	CreatedAt time.Time `json:"created_at"`
}

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

func (r *Run) Cancel(cause error)

Cancel kills the agent process. It is a no-op for finished runs.

func (*Run) CloseInput

func (r *Run) CloseInput() error

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

func (r *Run) ID() string

ID returns the run identifier.

func (*Run) Interrupt

func (r *Run) Interrupt() error

Interrupt stops the current turn; an interactive run then waits for the next message.

func (*Run) Read

func (r *Run) Read(cursor *Cursor) (events []Event, changed <-chan struct{}, finished bool)

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.

func (*Run) Respond

func (r *Run) Respond(id string, response json.RawMessage, errMessage string) error

Respond answers a pending control request from the agent.

func (*Run) Send

func (r *Run) Send(text string) error

Send queues a user message. Messages sent during a turn start the next turn.

func (*Run) Snapshot

func (r *Run) Snapshot() Snapshot

Snapshot returns the current state.

func (*Run) Stream

func (r *Run) Stream(ctx context.Context, cursor Cursor, send func(Event) error) error

Stream calls send for every event after cursor until the run finishes, ctx ends or send fails.

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.

const (
	StatusRunning   Status = "running"
	StatusSucceeded Status = "succeeded"
	StatusFailed    Status = "failed"
	StatusCancelled Status = "cancelled"
)

Statuses. Every run starts as StatusRunning and ends in exactly one terminal status.

func (Status) Terminal

func (s Status) Terminal() bool

Terminal reports whether the status is final.

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.

Jump to

Keyboard shortcuts

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