Documentation
¶
Overview ¶
Package agent runs the native agent loop over narrow ports implemented by core.
Index ¶
- Constants
- Variables
- func ContextLimit(model Model, windowTokens int, outputLimit int) int
- func DenialResult(reason string) tools.Result
- func ImageInputAllowed(model Model) bool
- func ToolCallMessage(id, sessionID, runID, name string, args []byte, finished bool, at time.Time) transcript.Message
- func ToolResultMessage(id, sessionID, runID, callID, name string, result tools.Result, at time.Time) (transcript.Message, error)
- func ToolResultStatus(result tools.Result) tools.ResultStatus
- func ToolUseAllowed(model Model) bool
- type Admission
- type Approvals
- type AwaitSignals
- type AwaitWake
- type Budget
- type CompactRequest
- type Config
- type Decision
- type Engine
- type Event
- type EventKind
- type Grant
- type Hooks
- type Inbox
- type Journal
- type LoopKind
- type Model
- type Outcome
- type Pending
- type Phase
- type Prompts
- type Recovery
- type RunState
- type Settle
- type Sink
- type State
- type Status
- type Steer
- type Step
- type StopReason
- type Task
- type TaskEvent
- type Todos
- type ToolBatch
- type Tools
- type Verdict
- type Verifier
- type Window
Constants ¶
const CompactStopReason = "compact"
CompactStopReason marks summary generations in run_steps; they use no budget step.
const ProgressFlushInterval = 750 * time.Millisecond
ProgressFlushInterval is how often a streaming reply is written to the journal.
Variables ¶
var ErrCanceled = errors.New("run canceled by user")
ErrCanceled is the cause of a run's context when the user canceled the run; a context stopped for any other cause interrupts the run.
var ErrContextExhausted = errors.New("context_exhausted: the conversation no longer fits the model's context window")
ErrContextExhausted fails a run whose conversation no longer fits the model's window even after summarising it.
Functions ¶
func ContextLimit ¶
ContextLimit is the prompt room of model in a window of windowTokens: the window without a reserve and the output limit its requests send, outputLimit when set, else the model's own.
func DenialResult ¶
DenialResult is the result the model reads for a call the user denied.
func ImageInputAllowed ¶
ImageInputAllowed reports whether the model accepts inline images.
func ToolCallMessage ¶
func ToolCallMessage(id, sessionID, runID, name string, args []byte, finished bool, at time.Time) transcript.Message
ToolCallMessage is the transcript message of one requested tool call.
func ToolResultMessage ¶
func ToolResultMessage(id, sessionID, runID, callID, name string, result tools.Result, at time.Time) (transcript.Message, error)
ToolResultMessage is the transcript message carrying a tool result.
func ToolResultStatus ¶
func ToolResultStatus(result tools.Result) tools.ResultStatus
ToolResultStatus is the stored status of a tool result.
func ToolUseAllowed ¶
ToolUseAllowed reports whether the model can receive tool definitions.
Types ¶
type Admission ¶ added in v0.2.1
type Admission struct {
Allowed bool
Reason string
Barrier bool
Key string
Delegated bool
Grant Grant
}
Admission is Authorize's answer for one call; Reason goes back to the model when it may not run. A Barrier call that waits for approval holds back the calls after it in its batch. Calls sharing a non-empty Key run one at a time, across runs too. A Delegated call runs another agent, whose time is not this run's. Grant is opaque to the engine, which hands it to Execute unchanged.
type AwaitSignals ¶ added in v0.2.1
AwaitSignals is what a run parked by await may wake for: the user wrote to it, a task the await names ended, a finished task's event is pending.
type AwaitWake ¶ added in v0.2.1
type AwaitWake int
AwaitWake is why a run parked by await goes on; AwaitParked keeps it parked.
type CompactRequest ¶ added in v0.2.1
type CompactRequest struct {
SessionID string
RunID string
Continues []string
WorkingDir string
// Model summarises unless CompactModel is set and succeeds; a window of 0
// is unknown.
Model Model
WindowTokens int
CompactModel Model
CompactWindowTokens int
// BaseTokens estimates what every request sends besides the history.
BaseTokens int
}
CompactRequest asks Engine.Compact for a summary of everything the model sees of a session. RunID, when set, is the run whose steps record the summary's usage and whose user messages, with those of Continues, stay verbatim.
type Config ¶
type Config struct {
Journal Journal
Tools Tools
Approvals Approvals
Inbox Inbox
Sink Sink
Prompts Prompts
Todos Todos
// Hooks runs the user's hooks; nil runs none.
Hooks Hooks
// Verifier checks the session goal when a run would end; nil checks none.
Verifier Verifier
Attachments agentcontext.AttachmentReader
Now func() time.Time
NewID func(prefix string) string
// Sleep waits d or until ctx stops; nil uses a real timer.
Sleep func(ctx context.Context, d time.Duration) error
// ModelSlots bounds the model requests of every run sharing it; nil is unbounded.
ModelSlots *toolsched.Semaphore
// Locks serialises tool calls sharing a concurrency key across every run
// using it; nil gives the engine locks of its own.
Locks *toolsched.Locks
}
Config wires the ports of one run.
type Decision ¶
Decision is where the newest approval of a call stands: Pending until the user answers, then granted or Denied with the user's Reason.
type Engine ¶
type Engine struct {
// contains filtered or unexported fields
}
Engine runs the native agent loop over its ports.
func (*Engine) ClearContext ¶ added in v0.2.1
ClearContext starts the session's model context afresh with a boundary that covers every message so far.
func (*Engine) Compact ¶ added in v0.2.1
func (e *Engine) Compact(ctx context.Context, req CompactRequest) (transcript.Message, error)
Compact summarises the session's whole context into a new boundary outside a run, the way a run does when its context fills up. ErrNothingToSummarise means the context holds nothing a summary could keep.
type Event ¶
type Event struct {
Kind EventKind
SessionID string
RunID string
Message transcript.Message
ToolCallID string
ToolName string
ResultMessageID string
Result tools.Result
ContextTokens int
WindowTokens int
}
Event is live progress for clients.
type EventKind ¶
type EventKind string
EventKind names what Sink receives.
const ( EventMessageCreated EventKind = "message.created" EventMessageUpdated EventKind = "message.updated" EventToolRequested EventKind = "tool.requested" EventToolFinished EventKind = "tool.finished" // EventContextMeasured carries ContextTokens and WindowTokens after a step. EventContextMeasured EventKind = "context.measured" )
type Grant ¶ added in v0.2.1
type Grant any
Grant is the Tools port's own record of a call it authorized.
type Hooks ¶ added in v0.2.1
type Hooks interface {
SessionStart(ctx context.Context, source string) string
Stop(ctx context.Context, reply string, active bool) string
PreCompact(ctx context.Context, trigger string)
}
Hooks runs the user's hooks at the engine's seams. SessionStart returns context for the model, Stop why a run that would end must go on ("" lets it end; active says a Stop hook already kept it going), PreCompact only observes.
type Inbox ¶
type Inbox interface {
Steers(ctx context.Context) ([]Steer, error)
ConsumeSteers(ctx context.Context, ids []string) error
Events(ctx context.Context) ([]TaskEvent, error)
ConsumeEvents(ctx context.Context, taskIDs []string) error
Decisions(ctx context.Context) ([]Decision, error)
Finished(ctx context.Context, taskIDs []string) (bool, error)
}
Inbox delivers outside input to one run. Steers and events stay pending until the engine consumes them; Decisions lists the newest approval of each call that asked, oldest first. Finished reports whether any of the background tasks ended, even if its event went elsewhere.
type Journal ¶
type Journal interface {
Load(ctx context.Context, sessionID string) (Window, error)
Append(ctx context.Context, msg transcript.Message) (seq int64, err error)
BeginStreaming(ctx context.Context, msg transcript.Message) (seq int64, err error)
Stream(ctx context.Context, msg transcript.Message) error
FinishStreaming(ctx context.Context, msg transcript.Message) error
Checkpoint(ctx context.Context, state State) error
RecordStep(ctx context.Context, step Step)
}
Journal persists one session's transcript; during a run the engine is its only writer. BeginStreaming/Stream use the fast progress path; FinishStreaming is the durable update of an in-flight assistant message and the only update of a written message. RecordStep is usage accounting: the adapter logs a failed write, the run goes on.
type Model ¶
type Model interface {
Generate(ctx context.Context, req providers.Request) (providers.Response, error)
}
Model generates one assistant turn; providers.Runtime satisfies it.
type Outcome ¶
type Outcome struct {
Status Status
Interrupted bool
StopReason StopReason
Assistant *transcript.Message
AssistantSaved bool
Err error
MarkErrored bool
RunState RunState
}
Outcome is applied by core. Interrupted is set when ctx stopped for a cause other than the user's cancel; Status is then what the last step reached, or empty when it reached nothing to commit. Assistant is the final reply (completed), the reply to seal (canceled, interrupted) or the errored reply (failed with MarkErrored). StopReason is set whenever the run completed, and for a context-exhausted failure. RunState is the run's state when it stopped.
type Pending ¶
type Pending struct {
RunID string
SessionID string
ToolCallID string
ToolName string
Request tools.ApprovalRequest
}
Pending is a tool call that waits for a user decision.
type Prompts ¶
type Prompts interface {
System(ctx context.Context, history []transcript.Message) (system, custom string)
Context(ctx context.Context) string
}
Prompts supplies the core-owned parts of every request: the system prompt and custom instructions, fixed for a run, and the changing state the engine sends as a context note whenever it changes.
type Recovery ¶ added in v0.2.1
type Recovery struct {
Settle Settle
Request tools.ApprovalRequest
Result tools.Result
}
Recovery settles one interrupted call: Request is what SettleAsk asks, Result what SettleAnswer journals.
type RunState ¶ added in v0.2.1
type RunState struct {
Steps int `json:"steps,omitempty"`
Tokens int64 `json:"tokens,omitempty"`
Active time.Duration `json:"active,omitempty"`
WrapUpSent bool `json:"wrap_up_sent,omitempty"`
// LoopRecent and LoopReplies hold the loop guard's windows of calls and
// long replies; LoopKind, LoopTool and LoopRepeats are what it saw.
LoopRecent string `json:"loop_recent,omitempty"`
LoopReplies string `json:"loop_replies,omitempty"`
LoopKind LoopKind `json:"loop_kind,omitempty"`
LoopTool string `json:"loop_tool,omitempty"`
LoopRepeats int `json:"loop_repeats,omitempty"`
LoopWarned bool `json:"loop_warned,omitempty"`
// Continuations counts replies in a row cut by the output limit; CallCut is
// set until the model is told a cut dropped its tool call.
Continuations int `json:"continuations,omitempty"`
CallCut bool `json:"call_cut,omitempty"`
OutputLimit int `json:"output_limit,omitempty"`
// Malformed counts replies in a row whose tool call could not be decoded.
Malformed int `json:"malformed,omitempty"`
LowYield int `json:"low_yield,omitempty"`
ElidedResults int64 `json:"elided_results,omitempty"`
ElidedImages int64 `json:"elided_images,omitempty"`
HistoryEdit int64 `json:"history_edit,omitempty"`
LearnedLimit int `json:"learned_limit,omitempty"`
TodoNudged bool `json:"todo_nudged,omitempty"`
// Unverified is set while files changed since the run's last successful
// build, test or lint command; VerifyNudged once the model was asked to check.
Unverified bool `json:"unverified,omitempty"`
VerifyNudged bool `json:"verify_nudged,omitempty"`
// StopHooks counts the replies Stop hooks held back.
StopHooks int `json:"stop_hooks,omitempty"`
// GoalHolds counts the replies a failed goal check held back.
GoalHolds int `json:"goal_holds,omitempty"`
// Await is set while the run waits for what an await call asked for.
Await *tools.Await `json:"await,omitempty"`
}
RunState is what a run has used and what the engine remembers between its steps: budget use, the loop guard's window, output-limit cuts, summaries, elision, learned prompt room, the notes already sent and what the run awaits. It is checkpointed so a parked or restarted run continues from it.
type Settle ¶
type Settle string
Settle is how a resumed run settles a call its interrupted execution left without a result.
type State ¶
State is the checkpoint the engine writes before each model call, when it starts calls of a tool batch and when the run parks; its RunState lets a parked or restarted run keep its budget.
type Steer ¶ added in v0.2.1
type Steer struct {
ID string
Text string
Attachments []transcript.MessagePart
}
Steer is input the user sent the running run: Text with the images and files sent with it.
type Step ¶
type Step struct {
RunID string
Model string
Provider string
Usage providers.Usage
StopReason string
Latency time.Duration
ToolCalls int
}
Step is one successful model generation (a run_steps row). StopReason is a provider stop reason or "compact" for a summary generation.
type StopReason ¶
type StopReason string
StopReason says why a completed run stopped.
const ( StopDone StopReason = "done" StopBudgetExhausted StopReason = "budget_exhausted" StopLoopDetected StopReason = "loop_detected" StopContextExhausted StopReason = "context_exhausted" )
func (StopReason) Continuable ¶
func (r StopReason) Continuable() bool
Continuable reports whether a run stopped before its work was done.
type Task ¶
type Task struct {
RunID string
SessionID string
Client string
ExternalKey string
WorkingDir string
Model Model
// WindowTokens is the model's context window; 0 means unknown.
WindowTokens int
// CompactModel writes the run's summaries instead of Model when set;
// CompactWindowTokens is its context window, 0 when unknown.
CompactModel Model
CompactWindowTokens int
Budget Budget
Resume RunState
// Continues lists the runs this one continues, nearest first; what they keep
// verbatim past a summary stays kept.
Continues []string
// Recovering is set when a restart or an interruption stopped the run's
// previous execution; the calls it left without a result are settled as
// Tools.Recovery says.
Recovering bool
}
Task is one native run to execute. Resume holds the state the run had reached before it was parked or interrupted; a new run starts from what the session's previous run carried over.
type ToolBatch ¶
type ToolBatch struct {
CallIDs []string `json:"call_ids"`
DeferredIDs []string `json:"deferred_ids,omitempty"`
}
ToolBatch names the calls of the batch being run, in call order, and those of them held back (deferred) when the checkpoint was written; crash recovery defers those again.
type Tools ¶
type Tools interface {
Specs(ctx context.Context) []tools.Spec
Authorize(ctx context.Context, name string, call tools.Call) (Admission, error)
Execute(ctx context.Context, grant Grant) (tools.Result, *tools.ApprovalRequest, error)
Recovery(ctx context.Context, name string, call tools.Call) (Recovery, error)
}
Tools lists, authorizes and executes the tools of one run. Execute runs a call Authorize allowed and returns either a result or, for a call that waits for the user, its approval request. Execute errors are fatal; tool failures come back as error results. Execute runs on a goroutine of its own, concurrently with other calls of the batch; the other methods run on the engine goroutine. Recovery says how a resumed run settles a call its interrupted execution left without a result.
type Verifier ¶ added in v0.2.1
Verifier checks the session's goal when a run would end with a reply. Hold keeps the run going with Note (a failed check); otherwise a Note (a passed check, a goal marked blocked) is journaled for the user and the run ends. A session without an active goal or check gets the zero Verdict.
type Window ¶
type Window struct {
Boundary *transcript.Message
Messages []transcript.Message
}
Window is the transcript a run starts from: the session's newest context boundary, if any, and the messages after what it covers, ordered by seq.
func (Window) Compaction ¶
func (w Window) Compaction() *transcript.Compaction
Compaction is the boundary's compaction; nil without a boundary.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package agenttest provides a scripted model and in-memory fakes for the agent ports.
|
Package agenttest provides a scripted model and in-memory fakes for the agent ports. |
|
Package agentcontext builds the model's view of a session: provider conversation, context boundaries and summaries, and token estimates.
|
Package agentcontext builds the model's view of a session: provider conversation, context boundaries and summaries, and token estimates. |
|
Package prompt holds the fixed texts of the native agent's system prompt.
|
Package prompt holds the fixed texts of the native agent's system prompt. |
|
Package todo is the agent's todo list: its items, their validation and how they are shown to the model.
|
Package todo is the agent's todo list: its items, their validation and how they are shown to the model. |
|
Package toolsched holds the daemon-wide scheduling primitives of native runs: a semaphore for model requests and keyed locks and batches for tool calls.
|
Package toolsched holds the daemon-wide scheduling primitives of native runs: a semaphore for model requests and keyed locks and batches for tool calls. |