agentcore

package
v1.5.17 Latest Latest
Warning

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

Go to latest
Published: Oct 28, 2026 License: MIT Imports: 9 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 agentcore defines the core "leaf" data types and control flow for the golder agent harness, a Go reimplementation of the pi agent loop. It is the foundation package that every other agent sub-package depends on and imports nothing from them.

This file defines the Content model: a sealed interface implemented by the four content block kinds (text, thinking, toolCall, image). Because Go's encoding/json cannot dispatch to an interface based on a discriminant field, containers holding []Content implement custom UnmarshalJSON that peeks at the "type" field and decodes into the concrete struct. Mirrors pi's discriminated union (packages/ai/src/types.ts) as interface + type switch.

Index

Constants

View Source
const (
	ContentTypeText     = "text"
	ContentTypeThinking = "thinking"
	ContentTypeToolCall = "toolCall"
	ContentTypeImage    = "image"
)

Content type discriminants, matching pi's wire format.

View Source
const (
	EventAgentStart          = "agent_start"
	EventAgentEnd            = "agent_end"
	EventTurnStart           = "turn_start"
	EventTurnEnd             = "turn_end"
	EventMessageStart        = "message_start"
	EventMessageUpdate       = "message_update"
	EventMessageEnd          = "message_end"
	EventToolExecutionStart  = "tool_execution_start"
	EventToolExecutionUpdate = "tool_execution_update"
	EventToolExecutionEnd    = "tool_execution_end"
	EventCompaction          = "compaction"
	EventCompactionStart     = "compaction_start"
	EventContextUsage        = "context_usage"
	EventTelemetry           = "telemetry"
	EventSubAgentProgress    = "subagent_progress"
	EventProviderNotice      = "provider_notice"
)

Event type discriminants.

View Source
const (
	RoleUser       = "user"
	RoleAssistant  = "assistant"
	RoleToolResult = "toolResult"
	// RoleCompaction marks a compaction checkpoint persisted inline in the
	// message list: it replaces the history summarized before it (pi's
	// "compactionSummary"). It is not sent to the model verbatim; the LLM
	// conversion turns it into a user text block.
	RoleCompaction = "compaction"
)

Message roles, matching pi's wire format.

View Source
const (
	StopReasonEndTurn = "end_turn"
	StopReasonToolUse = "tool_use"
	StopReasonLength  = "length"
	StopReasonError   = "error"
	StopReasonAborted = "aborted"
)

StopReason values, matching pi.

View Source
const (
	ToolCallKindServer = "server"
)

Tool-call kinds: local calls run in golder's tool registry; server calls were already executed by the provider (hosted tools such as web_search) and exist for display + history replay only. Empty means local, so sessions persisted before the marker decode unchanged.

Variables

View Source
var ErrStreamIncomplete = errors.New("agent: event stream ended without a result")

ErrStreamIncomplete is returned by Result when the event channel closed without any result being set (the producer ended abnormally without a terminal event).

Functions

func BareEnvelopeFromContext added in v1.3.4

func BareEnvelopeFromContext(ctx context.Context) (reason string, ok bool)

BareEnvelopeFromContext reports the gate's envelope decision: ok is true when the call may run unconfined, with the reason it may. ok=false is the default and means "contain it".

func BrowserRuntimeGrantedFromContext added in v1.5.13

func BrowserRuntimeGrantedFromContext(ctx context.Context) bool

func ContentToText

func ContentToText(list ContentList) string

ContentToText flattens text blocks of a content list into a single string, the lowest-common-denominator representation accepted by every OpenAI- compatible gateway. Non-text blocks (thinking, tool calls) are surfaced through their own fields, so they are skipped here.

func DirectGrantedFromContext added in v1.3.1

func DirectGrantedFromContext(ctx context.Context) bool

func ExternalToolAuthorized added in v1.5.15

func ExternalToolAuthorized(ctx context.Context) bool

func HostControlGrantedFromContext added in v1.5.5

func HostControlGrantedFromContext(ctx context.Context) bool

func NetworkGrantedFromContext added in v1.3.1

func NetworkGrantedFromContext(ctx context.Context) bool

func OperatorConfirmedFor added in v1.5.16

func OperatorConfirmedFor(ctx context.Context, id, name string, args json.RawMessage) bool

func OriginFromContext added in v1.3.0

func OriginFromContext(ctx context.Context) string

OriginFromContext returns the asking agent's label, or "" when the run is the session's own (or the ctx never carried one).

func ReadGrantFromContext added in v1.2.15

func ReadGrantFromContext(ctx context.Context) string

ReadGrantFromContext returns the one-call read grant, or "" when this call has none. A tool that reads files (read, view_image, grep, find, ls) honours it once; a tool that writes must not, since the grant answers a question about consent to read.

func SandboxRequestedFromContext

func SandboxRequestedFromContext(ctx context.Context) bool

SandboxRequestedFromContext reports whether the permission layer asked for this call to run isolated. A tool that can isolate (bash via sandbox-exec) routes itself into the sandbox; a tool that cannot must refuse rather than run unconfined.

func SystemPromptSnapshotFromContext added in v1.5.4

func SystemPromptSnapshotFromContext(ctx context.Context) string

SystemPromptSnapshotFromContext returns the parent system prompt carried by ctx, or "" when the caller runs outside a run loop (a direct tool call, an embedder, or a test). Callers fall back to their own system prompt.

func WithAgentOrigin added in v1.3.0

func WithAgentOrigin(ctx context.Context, name string) context.Context

WithAgentOrigin returns a child context stamped with name as the asking agent. An empty name leaves ctx unchanged (a direct run needs no label), and a nested call appends to the origin already carried.

func WithBareEnvelope added in v1.3.4

func WithBareEnvelope(ctx context.Context, reason string) context.Context

WithBareEnvelope marks ctx as one whose call may run outside the OS sandbox, carrying the reason so the transcript can say why.

func WithBrowserRuntimeGrant added in v1.5.13

func WithBrowserRuntimeGrant(ctx context.Context) context.Context

func WithDirectGrant added in v1.3.1

func WithDirectGrant(ctx context.Context) context.Context

WithDirectGrant marks an explicitly authorized one-call sandbox escape.

func WithExternalToolAuthorization added in v1.5.15

func WithExternalToolAuthorization(ctx context.Context) context.Context

WithExternalToolAuthorization is set only after the executor's configured host gate has accepted the final call. Extension configuration is not consent.

func WithHostControlGrant added in v1.5.5

func WithHostControlGrant(ctx context.Context) context.Context

func WithMessageSnapshot

func WithMessageSnapshot(ctx context.Context, msgs MessageList) context.Context

WithMessageSnapshot returns a child context carrying a snapshot of the conversation as of the tool batch dispatch. Context-sensitive collaborators (the risk judge) read it to grade a call against the user intent and recent history. The slice header is a copy: the loop appends only past its length, so the captured view stays stable.

func WithNetworkGrant added in v1.3.1

func WithNetworkGrant(ctx context.Context) context.Context

WithNetworkGrant records the authorization gate's decision, not the tool's request. The execution layer cannot infer this capability from arguments.

func WithOperatorConfirmation added in v1.5.16

func WithOperatorConfirmation(ctx context.Context, id, name string, args json.RawMessage) context.Context

func WithProgressEmitter

func WithProgressEmitter(ctx context.Context, emit EmitFunc) context.Context

WithProgressEmitter returns a child context carrying emit as the run-level progress emitter. The task tool injects the parent loop's EmitFunc here so a dispatched sub-agent can surface SubAgentProgressEvent up the parent stream.

func WithReadGrant added in v1.2.15

func WithReadGrant(ctx context.Context, path string) context.Context

WithReadGrant returns a child context that allows the tool to read one path outside the workspace. The tool executor publishes it when the beforeToolCall hook returns a decision with ReadGrant set — the "allow once" answer to the workspace-boundary question — so the grant lives exactly as long as this call and needs no per-driver wiring.

func WithSandboxRequest

func WithSandboxRequest(ctx context.Context) context.Context

WithSandboxRequest returns a child context that asks the tool to run its call under OS-level isolation. The tool executor publishes it when the beforeToolCall hook returns a decision with Sandbox set, so the requirement travels the same gate → executor → tool path as every other permission outcome and needs no per-driver wiring.

func WithSystemPromptSnapshot added in v1.5.4

func WithSystemPromptSnapshot(ctx context.Context, prompt string) context.Context

WithSystemPromptSnapshot returns a child context carrying the system prompt the parent run uses for this tool batch.

func WithToolGates added in v1.2.17

func WithToolGates(ctx context.Context, chain *ToolGateChain) context.Context

WithToolGates returns a child context carrying chain. The tool executor publishes it for the executing tool, so a sub-agent the tool spawns can run under the same gates as the run that dispatched it.

func WithWriteGrant added in v1.3.0

func WithWriteGrant(ctx context.Context, path string) context.Context

WithWriteGrant returns a child context that allows the tool to write one path outside the workspace. It is the write side's twin of WithReadGrant: the executor publishes it when the gate returns a decision with WriteGrant set — the "allow this write once" answer to the boundary question about a patch — so the grant lives exactly as long as this call.

func WriteGrantFromContext added in v1.3.0

func WriteGrantFromContext(ctx context.Context) string

WriteGrantFromContext returns the one-call write grant, or "" when this call has none. Only a tool that writes honours it, and only for the path named: the answer covers the one file the user was asked about, not the tree holding it — that answer is the session grant, and it lives in the authorization table where every reader can see it.

Types

type AfterToolCallFunc

type AfterToolCallFunc func(ctx context.Context, call AgentToolCall, result AgentToolResult, isError bool) *AfterToolCallResult

AfterToolCallFunc runs after execution and may override the result field-by-field via AfterToolCallResult (FR-5, no deep merge). Optional.

type AfterToolCallResult

type AfterToolCallResult struct {
	Content   *ContentList
	Details   *any
	Terminate *bool
	IsError   *bool
}

AfterToolCallResult is the optional override returned by the afterToolCall hook. Every field is a pointer so the loop can distinguish "not provided" (nil) from "provided, possibly zero" — pi expresses this with `??`, Go needs pointers. Fields are applied with field-level replacement, no deep merge (FR-5).

type AgentContext

type AgentContext struct {
	SystemPrompt string      `json:"systemPrompt"`
	Messages     MessageList `json:"messages"`
	Tools        []AgentTool `json:"-"`
}

AgentContext is the input state for a loop run: system prompt, conversation messages, and the tools available to the model.

type AgentEndEvent

type AgentEndEvent struct {
	Messages []AgentMessage
}

AgentEndEvent is emitted once when a loop run ends, carrying the messages newly produced during this run (the EventStream result).

func (AgentEndEvent) EventType

func (AgentEndEvent) EventType() string

type AgentEvent

type AgentEvent interface {

	// EventType returns the discriminant string, useful for logging and for
	// serialising events to the stream-json/stdio protocol (US-020).
	EventType() string
	// contains filtered or unexported methods
}

AgentEvent is the sealed interface implemented by every event the loop emits. Consumers dispatch with a type switch, consistent with Content. golder covers all 10 of pi's event types (PRD FR-24).

type AgentMessage

type AgentMessage = Message

AgentMessage is the loop-level message type. It is the same as Message; the alias documents intent at call sites that deal with the loop rather than raw LLM messages.

type AgentStartEvent

type AgentStartEvent struct {
	SessionID string
}

AgentStartEvent is emitted once when a loop run begins. SessionID, when set, is the id of the session backing this run; it is carried in the first stream-json event so a caller can associate output with a session and resume it later (mirrors pi/Claude Code, which put a session id in the first event).

func (AgentStartEvent) EventType

func (AgentStartEvent) EventType() string

type AgentTool

type AgentTool interface {
	Name() string
	Description() string
	// Schema returns the JSON Schema (as raw JSON) for the tool's arguments.
	Schema() json.RawMessage
	// ExecutionMode reports whether this tool forces sequential execution.
	ExecutionMode() ToolExecutionMode
	// Execute runs the tool. onUpdate may be nil.
	Execute(ctx context.Context, id string, args json.RawMessage, onUpdate ToolUpdateFunc) (AgentToolResult, error)
}

AgentTool is a tool the model can invoke. Schema is the JSON Schema used to validate arguments before execution (US-014).

type AgentToolCall

type AgentToolCall struct {
	ID        string          `json:"id"`
	Name      string          `json:"name"`
	Arguments json.RawMessage `json:"arguments"`
	// RequireOperatorConfirmation is set by the tool registry, never decoded
	// from model output. It forces an exact, interactive one-call approval.
	RequireOperatorConfirmation bool `json:"-"`
}

AgentToolCall is a decoded request to invoke a tool (the loop-level view of a ToolCallContent block).

type AgentToolResult

type AgentToolResult struct {
	Content   ContentList `json:"content"`
	Details   any         `json:"details,omitempty"`
	Terminate *bool       `json:"terminate,omitempty"`
	// IsError marks a result that reports a failure in its content (a refused
	// command, a patch that did not apply) while the tool itself returned
	// normally. Without it the execution layer cannot tell "ran and succeeded"
	// from "refused to run", so a refusal would be recorded as success.
	IsError bool `json:"isError,omitempty"`
}

AgentToolResult is the outcome of executing a tool.

Details uses `any` in the first version (matching pi's internal AgentToolResult<any>); a generic form can be added later. Terminate is a *bool so "not set" is distinguishable from an explicit false — the loop only signals early termination when every result in a batch has Terminate=true.

type AssistantMessage

type AssistantMessage struct {
	RoleField    string      `json:"role"`
	Content      ContentList `json:"content"`
	API          string      `json:"api,omitempty"`
	Provider     string      `json:"provider,omitempty"`
	Model        string      `json:"model,omitempty"`
	Usage        *Usage      `json:"usage,omitempty"`
	StopReason   string      `json:"stopReason,omitempty"`
	ErrorMessage string      `json:"errorMessage,omitempty"`
	Timestamp    int64       `json:"timestamp"`

	// Optional diagnostics, kept for cross-provider replay/observability.
	ResponseModel string `json:"responseModel,omitempty"`
	ResponseID    string `json:"responseId,omitempty"`
	// ReasoningItems preserves the provider's opaque Responses reasoning items
	// for a stateless continuation. OpenCode Go/DeepSeek requires its original
	// reasoning/thinking before replayed function calls; the UI's ThinkingContent is
	// NOT a replacement for this protocol data. Only the Responses driver reads
	// these items, and only when replaying to the same provider and requested
	// model (the gateway's ResponseModel diagnostic may be a different alias).
	ReasoningItems []json.RawMessage `json:"reasoningItems,omitempty"`
}

AssistantMessage is a model response. Content may hold text/thinking/toolCall blocks. StopReason follows pi's set (end_turn/tool_use/length/error/aborted).

func LastAssistantOf

func LastAssistantOf(msgs []AgentMessage) *AssistantMessage

LastAssistantOf returns a pointer to the last AssistantMessage in msgs, or nil.

func (AssistantMessage) HasThinking added in v1.3.8

func (m AssistantMessage) HasThinking() bool

HasThinking reports whether the turn carried a reasoning block. It exists to name the reasoning-only turn when there is no visible output: the two shapes (nothing at all, and reasoning with nothing else) need different words, since only the first is a protocol mismatch worth checking --model/--base-url for.

func (AssistantMessage) HasVisibleOutput added in v1.3.8

func (m AssistantMessage) HasVisibleOutput() bool

LastAssistantOf returns a pointer to the last AssistantMessage in msgs, or nil.

HasVisibleOutput reports whether an assistant turn says anything the person can act on: non-blank text, or a tool call (local or provider-executed).

Reasoning is deliberately NOT output. A message carrying only a thinking block has answered nothing and asked for nothing — it is the shape a model produces when it exhausts its response on reasoning and then ends the turn — and both front-ends and the provider's empty-completion retry need that distinction. Asking "is there any content at all?" instead is what let such a turn settle in silence: a reasoning block IS content, so the turn looked finished, printed nothing, and left the person staring at the last tool card with no way to tell "done" from "stalled".

func (AssistantMessage) Role

func (m AssistantMessage) Role() string

func (AssistantMessage) ToolCalls

func (m AssistantMessage) ToolCalls() []ToolCallContent

ToolCalls returns the tool call blocks in this assistant message, in order.

type BeforeToolCallDecision

type BeforeToolCallDecision struct {
	Block   bool
	Content *ContentList
	Details *any
	// OperatorConfirmed records a person's exact-call answer. It cannot be
	// supplied by tool arguments or the automatic reviewer.
	OperatorConfirmed bool
	// Sandbox asks the execution layer to run this call under OS-level
	// isolation (e.g. a permission gate graded the command into a sandbox
	// tier). The executor publishes the request into the context the tool
	// executes with (SandboxRequestedFromContext); a tool that cannot isolate
	// must fail closed. Ignored when Block is set.
	Sandbox bool
	// Network grants outbound network access to this invocation's sandbox. A
	// model's "network:on" argument is only a REQUEST; only the authorization
	// gate can set this bit after a reviewer/user approved the capability.
	Network bool
	// HostControl authorizes this call's explicitly requested access to a pane
	// or browser not created by this agent. It is never a standing grant.
	HostControl bool
	// Direct is a separate per-call escape decision from the authorization gate
	// (reviewer in auto, person in ask/uncertain). An Allow alone cannot set it.
	Direct bool
	// BrowserRuntime permits only the trusted browser launcher to omit the
	// outer macOS Seatbelt layer. It is not a Direct grant to bash or workers.
	BrowserRuntime bool
	// ReadGrant, when non-empty, allows this one call to read the given path
	// outside the workspace. The executor publishes it into the context the
	// tool executes with (ReadGrantFromContext). It carries a single path
	// rather than a directory on purpose: the answer to the boundary question
	// is either "just this one" (this field) or "this directory for the
	// session" (the read-root registry in internal/permissions), which needs
	// no plumbing because every tool reads it directly. Ignored when Block is
	// set.
	ReadGrant string
	// WriteGrant, when non-empty, allows this one call to write the given path
	// outside the workspace: the write side of ReadGrant, set by the boundary
	// gate's "allow this write once" answer to a patch that reaches outside.
	// The executor publishes it into the context the tool executes with
	// (WriteGrantFromContext). Ignored when Block is set.
	WriteGrant string
	// Bare asks the execution layer to run this call OUTSIDE the OS sandbox,
	// because everything the command touches is enumerable from its text (see
	// judge.EnvelopeBare). It is not an escape the model asked for — that is
	// Direct — but the routine case: the gate decided the call may run, and the
	// command's whole effect is readable, so containment buys nothing and costs
	// the call its credentials. The executor publishes it
	// (BareEnvelopeFromContext); the sandbox ladder still wins inside the tool
	// (GOLDER_SANDBOX=enforce contains it anyway). Ignored when Block is set,
	// and never set together with Sandbox.
	Bare bool
	// BareReason is the sentence a note and the card carry when Bare is set.
	BareReason string
}

BeforeToolCallDecision is the optional result of the beforeToolCall hook. When Block is true the tool is not executed and an error result is produced; Content/Details override the default block message when set. When Block is false, Sandbox asks for OS-level isolation of the already-validated call. PreToolUse argument rewrites happen in PrepareArguments, before this decision.

type BeforeToolCallFunc

type BeforeToolCallFunc func(ctx context.Context, call AgentToolCall) *BeforeToolCallDecision

BeforeToolCallFunc runs after validation and may block the call (permission / sandbox checks, FR-4/FR-26). Returning nil allows the call. Optional.

type CompactionEvent

type CompactionEvent struct {
	// Reason is why compaction ran: "manual", "threshold", or "overflow".
	Reason string
	// TokensBefore is the estimated context tokens prior to compaction.
	TokensBefore int
	// TokensAfter is the estimated context tokens after compaction (equals
	// TokensBefore when compaction failed or was a no-op).
	TokensAfter int
	// SummarizedCount is the number of messages folded into the summary.
	SummarizedCount int
	// KeptCount is the number of recent messages retained verbatim.
	KeptCount int
	// ErrorMessage is non-empty when compaction failed; the original context is
	// preserved in that case.
	ErrorMessage string
}

CompactionEvent is emitted when the loop compacts the context window, either automatically (threshold/overflow) or on an explicit /compact request. It carries before/after token counts and how many messages were summarized vs. retained. When compaction fails it is still emitted with ErrorMessage set and the token/count fields describing the unchanged context, so consumers can surface the failure without the session aborting (US-004).

func (CompactionEvent) EventType

func (CompactionEvent) EventType() string

type CompactionMessage

type CompactionMessage struct {
	RoleField    string `json:"role"`
	Summary      string `json:"summary"`
	TokensBefore int    `json:"tokensBefore,omitempty"`
	// KeptCount is how many messages were retained verbatim after this
	// checkpoint when it was written. Token accounting uses it to know that the
	// usage readings carried by those messages described the pre-compaction
	// request (the summarized prefix plus the tail) and must not be read back as
	// the current context size. 0 (older sessions) means "unknown".
	KeptCount int `json:"keptCount,omitempty"`
	// Details is opaque at this layer (the compaction package owns its shape);
	// kept as raw JSON so agentcore stays free of a compaction dependency.
	Details   json.RawMessage `json:"details,omitempty"`
	Timestamp int64           `json:"timestamp"`
}

CompactionMessage is a summarization checkpoint persisted inline in the message list. It stands in for the history compacted before it: Summary is the structured checkpoint text and TokensBefore records the estimated context size at compaction time (for observability). Details optionally holds the file operations extracted from the compacted range. Mirrors pi's CompactionSummaryMessage + CompactionEntry.

func (CompactionMessage) AsUserMessage

func (m CompactionMessage) AsUserMessage() UserMessage

AsUserMessage renders a compaction checkpoint as the user text message that stands in for the compacted history when building the LLM request. The provider encoders call this so a persisted compaction line replays as context rather than being dropped.

func (CompactionMessage) Role

func (m CompactionMessage) Role() string

type CompactionStartEvent

type CompactionStartEvent struct {
	// Reason is why compaction is running: "manual", "threshold", or "overflow".
	Reason string
	// TokensBefore is the estimated context tokens that triggered compaction.
	TokensBefore int
}

CompactionStartEvent is emitted immediately before the loop runs compaction, so a front-end can show an in-progress "Compacting conversation…" indicator while the summarization request is in flight. The matching CompactionEvent is emitted when it completes (or fails). Reason mirrors CompactionEvent.Reason.

func (CompactionStartEvent) EventType

func (CompactionStartEvent) EventType() string

type Content

type Content interface {
	// contains filtered or unexported methods
}

Content is a sealed interface implemented by every content block kind. Consumers dispatch with a type switch. The interface is sealed via the unexported isContent marker so no type outside this package can satisfy it.

type ContentList

type ContentList []Content

ContentList is a slice of Content with discriminated JSON (un)marshalling. Fields typed []Content in messages use this so decoding dispatches on "type".

func (*ContentList) UnmarshalJSON

func (cl *ContentList) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes a JSON array of content blocks, dispatching each element on its "type" discriminant.

type ContextUsageEvent added in v1.2.3

type ContextUsageEvent struct {
	// Tokens is the estimated context-token usage once the turn settled (after
	// any compaction), computed the same way as TelemetryEvent.ContextTokens.
	Tokens int
	// Window is the model's total context-token budget (always > 0; the loop
	// only emits this event when the window is known).
	Window int
}

ContextUsageEvent reports the conversation's estimated context-token usage mid-run, emitted at every turn boundary (after any compaction) when the context window is known. It is the incremental counterpart to the run-end TelemetryEvent: a front-end refreshes its context gauge from it while a long multi-tool run is still in flight, instead of showing a stale figure until the run ends (parity with Codex's per-sampling-step TokenCount event). Consumers that ignore it behave exactly as before, and the run-end telemetry summary remains the authoritative final figure.

func (ContextUsageEvent) EventType added in v1.2.3

func (ContextUsageEvent) EventType() string

type EmitFunc

type EmitFunc func(ctx context.Context, ev AgentEvent) error

EmitFunc emits a loop-level AgentEvent honoring cancellation.

func ProgressEmitterFromContext

func ProgressEmitterFromContext(ctx context.Context) EmitFunc

ProgressEmitterFromContext returns the run-level progress emitter carried by ctx, or nil if none was set (in which case callers should skip progress reporting rather than panic).

type EventStream

type EventStream[T any, R any] struct {

	// IsComplete reports whether an event is the terminal one. Optional: if
	// set, Emit auto-captures the result via ExtractResult when it returns true.
	IsComplete func(event T) bool
	// ExtractResult derives the final result from the terminal event. Required
	// when IsComplete is set.
	ExtractResult func(event T) R
	// contains filtered or unexported fields
}

EventStream is the Go equivalent of pi's EventStream<T,R>: a producer pushes events onto a channel while a consumer ranges over them, and a terminal event yields a final result R. It replaces pi's async generator (event-stream.ts).

Design (research §2.2):

  • Iteration: Events() returns <-chan T for `for ev := range s.Events()`.
  • Result: Result(ctx) blocks until the producer sets a result (or the stream fails/cancels). The result is NOT sent on the event channel, so a consumer that stops reading events can still obtain it.
  • Cancellation: the producer selects on ctx.Done() when sending, so a consumer that stops reading never leaks the producer goroutine.

pi's isComplete/extractResult callbacks are retained as optional fields so a producer can let the stream detect the terminal event itself; a producer may instead call SetResult explicitly (more Go-idiomatic). Either path resolves Result exactly once.

func NewEventStream

func NewEventStream[T any, R any](buffer int) *EventStream[T, R]

NewEventStream constructs an EventStream with the given channel buffer size. A buffer of 0 gives fully synchronous back-pressure (each Emit blocks until a consumer receives), matching pi's sequential `await emit(...)`.

func (*EventStream[T, R]) Close

func (s *EventStream[T, R]) Close()

Close closes the event channel, ending consumer iteration. If no result was set, Result will report ErrStreamIncomplete. Call exactly once from the producer after the last Emit.

func (*EventStream[T, R]) Emit

func (s *EventStream[T, R]) Emit(ctx context.Context, event T) error

Emit sends an event to consumers, honoring cancellation. If ctx is cancelled before the event is received, Emit returns ctx.Err() and the event is dropped. When IsComplete is configured and reports true for the event, the result is captured (once) before the send.

func (*EventStream[T, R]) Events

func (s *EventStream[T, R]) Events() <-chan T

Events returns the receive-only event channel. Ranging over it terminates when the producer calls Close.

func (*EventStream[T, R]) Result

func (s *EventStream[T, R]) Result(ctx context.Context) (R, error)

Result blocks until the producer sets a result/error, ctx is cancelled, or the stream closes without a result. It is safe to call concurrently and returns the same outcome on every call.

An outcome the producer has ALREADY recorded wins over a cancelled ctx. The two race whenever a run is cancelled and settles at the same time — the interrupt cancels ctx while the loop's own finish() sets the result — and the result is the more truthful of the two: it says what the run produced. Preferring ctx.Err() there made an interrupted run report differently from one moment to the next (the driver printed the cancellation as a failure on some interrupts and nothing on others, from the same user action). The non-blocking check below is what reorders that race; when no outcome exists yet, the wait still ends on ctx cancellation.

func (*EventStream[T, R]) SetError

func (s *EventStream[T, R]) SetError(err error)

SetError records a terminal error as the stream's outcome. Only the first call among SetResult/SetError wins.

func (*EventStream[T, R]) SetResult

func (s *EventStream[T, R]) SetResult(result R)

SetResult records the final result. Only the first call wins; later calls (including SetError) are no-ops. Safe to call before Close.

type ImageContent

type ImageContent struct {
	Type     string `json:"type"`
	Data     string `json:"data"`
	MimeType string `json:"mimeType"`
}

ImageContent is an image block (base64 data + mime type).

func NewImageContent

func NewImageContent(data, mimeType string) ImageContent

NewImageContent returns an ImageContent with the type discriminant set.

type Message

type Message interface {

	// Role returns the discriminant ("user" | "assistant" | "toolResult").
	Role() string
	// contains filtered or unexported methods
}

Message is the sealed interface implemented by the three message roles. AgentMessage (the loop's message abstraction) is simply Message: custom message kinds implement the same interface and convertToLlm filters out any that are not LLM-bound. This deliberately replaces pi's declaration merging, which has no Go equivalent.

type MessageEndEvent

type MessageEndEvent struct {
	Message AgentMessage
}

MessageEndEvent is emitted when a message finishes streaming.

func (MessageEndEvent) EventType

func (MessageEndEvent) EventType() string

type MessageList

type MessageList []Message

MessageList is a slice of Message with discriminated JSON (un)marshalling, dispatching on the "role" field. Used by AgentContext and session persistence.

func MessageSnapshotFromContext

func MessageSnapshotFromContext(ctx context.Context) MessageList

MessageSnapshotFromContext returns the conversation snapshot carried by ctx, or nil when the caller runs outside a run loop (e.g. a remote-control confirm seam); callers must degrade to context-free grading rather than failing.

func (*MessageList) UnmarshalJSON

func (ml *MessageList) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes a JSON array of messages, dispatching each element on its "role" discriminant.

type MessageStartEvent

type MessageStartEvent struct {
	Message AgentMessage
}

MessageStartEvent is emitted when a message begins streaming.

func (MessageStartEvent) EventType

func (MessageStartEvent) EventType() string

type MessageUpdateEvent

type MessageUpdateEvent struct {
	Message               AgentMessage
	AssistantMessageEvent any
}

MessageUpdateEvent is emitted for each streaming delta, carrying the current partial message and the raw provider-level event that produced it.

func (MessageUpdateEvent) EventType

func (MessageUpdateEvent) EventType() string

type PrepareArgumentsFunc

type PrepareArgumentsFunc func(ctx context.Context, toolName string, args json.RawMessage) (json.RawMessage, error)

PrepareArgumentsFunc optionally rewrites a tool's raw arguments before schema validation (e.g. injecting defaults). An error aborts the call with an error result. Optional (nil = identity).

type ProviderNoticeEvent added in v1.3.3

type ProviderNoticeEvent struct {
	// Kind is the notice family; "retry" is the only one today.
	Kind string
	// Provider names the gateway whose stream was cut.
	Provider string
	// Reason is the cut kind: "idle", "stall", "truncated", or "silent".
	Reason string
	// Window is the watchdog window that expired, for idle/stall; zero
	// otherwise.
	Window time.Duration
	// Attempt is the 1-based retry about to start, and MaxAttempts the budget it
	// is counting against; both are zero for notices that are not a retry.
	Attempt     int
	MaxAttempts int
	// Detail is the watchdog's evidence for the cut, when it had any.
	Detail string
}

ProviderNoticeEvent is a non-terminal provider-layer progress note surfaced to the UI while the run continues: today, a cut stream that is being retried. It is not a message event and never enters the conversation; a front-end that ignores it behaves exactly as before.

func (ProviderNoticeEvent) EventType added in v1.3.3

func (ProviderNoticeEvent) EventType() string

type SubAgentProgressEvent

type SubAgentProgressEvent struct {
	// ToolCallID is the parent task call's tool-call id, used as the key for
	// the status line.
	ToolCallID string
	// Description is the task call's description, for display (may be empty).
	Description string
	// Activity is the current activity: tool name / phase, e.g. "Editing",
	// "Running bash", "Thinking".
	Activity string
	// Tokens is the estimated sub-agent output token count (0 = unknown).
	Tokens int
}

SubAgentProgressEvent carries structured progress from a running sub-agent (dispatched by the task tool). It is reported at the sub-agent's tool execution / turn boundaries so a TUI (multi-line status panel) or headless mode (stderr line) can display live progress. Elapsed time is intentionally omitted: consumers compute it themselves (TUI from tool-start time, headless from when the id was first seen) to avoid emitting an event per frame.

func (SubAgentProgressEvent) EventType

func (SubAgentProgressEvent) EventType() string

type TelemetryEvent

type TelemetryEvent struct {
	// Turns is the number of turns (turn_start events) the run executed.
	Turns int
	// ToolDurationsMs maps a tool name to its aggregated timing over the run.
	ToolDurationsMs map[string]ToolTiming
	// TruncationCount is how many assistant responses stopped with reason
	// "length" (truncated by the output token cap), each triggering a resend.
	TruncationCount int
	// CompactionCount is how many successful context compactions occurred.
	CompactionCount int
	// ContextUtilization is the latest used/window ratio in [0,1], or 0 when the
	// context window is unknown. Computed as ContextTokens / ContextWindow.
	ContextUtilization float64
	// ContextTokens is the most recently observed estimated context-token usage.
	ContextTokens int
	// ContextWindow is the model's total context-token budget (0 when unknown).
	ContextWindow int
}

TelemetryEvent is a lightweight, additive observability summary emitted once at run end (just before agent_end) so scripts consuming the stream-json output can read structured metrics without a new dependency (no Prometheus/OTLP). It is purely observational: consumers that ignore it behave exactly as before. Metrics covered (observability — structured telemetry collection):

  • per-tool wall-clock durations (ToolDurationsMs, aggregated by tool name),
  • how many turns ran (Turns),
  • how many assistant responses were truncated by the output cap (TruncationCount),
  • how many times the context was compacted (CompactionCount),
  • the latest context-utilization ratio (ContextUtilization = used tokens / ContextWindow) and the raw numbers behind it.

func (TelemetryEvent) EventType

func (TelemetryEvent) EventType() string

type TextContent

type TextContent struct {
	Type          string `json:"type"`
	Text          string `json:"text"`
	TextSignature string `json:"textSignature,omitempty"`
}

TextContent is a plain text block.

func NewTextContent

func NewTextContent(text string) TextContent

NewTextContent returns a TextContent with the type discriminant set.

type ThinkingContent

type ThinkingContent struct {
	Type              string `json:"type"`
	Thinking          string `json:"thinking"`
	ThinkingSignature string `json:"thinkingSignature,omitempty"`
	Redacted          bool   `json:"redacted,omitempty"`
}

ThinkingContent is a reasoning/thinking block. Never folded into text.

func NewThinkingContent

func NewThinkingContent(thinking string) ThinkingContent

NewThinkingContent returns a ThinkingContent with the type discriminant set.

type ThinkingLevel

type ThinkingLevel string

ThinkingLevel is the unified reasoning-effort enum (agent layer). It keeps pi's full seven levels; providers map it to their own wire format via a per-model ThinkingLevelMap (decision #10).

const (
	ThinkingOff     ThinkingLevel = "off"
	ThinkingMinimal ThinkingLevel = "minimal"
	ThinkingLow     ThinkingLevel = "low"
	ThinkingMedium  ThinkingLevel = "medium"
	ThinkingHigh    ThinkingLevel = "high"
	ThinkingXHigh   ThinkingLevel = "xhigh"
	ThinkingMax     ThinkingLevel = "max"
)

type ThinkingLevelMap

type ThinkingLevelMap map[ThinkingLevel]*string

ThinkingLevelMap maps a unified level to a provider-specific wire value. A nil value means "supported but disabled at this level"; an absent key means "this level is not supported by the model". The pointer is what distinguishes those two cases, so it must stay *string.

type ToolAuth added in v1.2.17

type ToolAuth struct {
	// SessionTrust is the session trust decision for the working directory: the
	// interactive "trust this folder" answer, the "all tools here" answer to a
	// trust question, or (for a non-interactive run) the invocation itself.
	SessionTrust bool `json:"sessionTrust,omitempty"`
	// SessionReads is the trust gate's middle rung: local reads allowed in the
	// working directory for this session.
	SessionReads bool `json:"sessionReads,omitempty"`
	// ReadRoots are the workspace-boundary grants (directories the user allowed
	// the read tools to reach outside the workspace, this session).
	ReadRoots []string `json:"readRoots,omitempty"`
	// WritableRoots are the same, for writing: directories the user allowed a
	// write inside (a sandbox dialog, /boundary writable add, or an escalation
	// answer), this session. They travel for the same reason the read roots do
	// — a child that saw none of them would refuse a write its parent had
	// already been granted, and, having no prompt of its own, could not even
	// ask. A remembered root needs no carrying (it is in grants.json, which the
	// child process opens too); a session-only one exists nowhere but here.
	WritableRoots []string `json:"writableRoots,omitempty"`
}

ToolAuth is the authorization state a derived run is seeded with when it crosses a process boundary. It carries the session's decisions, not the session's prompts: a process-isolated sub-agent speaks JSON-RPC on its stdin, so it has nowhere to ask, and every request it cannot settle from this snapshot fails closed on its own side.

type ToolCallContent

type ToolCallContent struct {
	Type             string          `json:"type"`
	ID               string          `json:"id"`
	Name             string          `json:"name"`
	Arguments        json.RawMessage `json:"arguments"`
	ThoughtSignature string          `json:"thoughtSignature,omitempty"`
	Kind             string          `json:"kind,omitempty"`
}

ToolCallContent is a request from the model to invoke a tool. Arguments are kept as raw JSON so validation (JSON Schema) and shaping happen downstream.

func NewServerToolCallContent

func NewServerToolCallContent(id, name string, arguments json.RawMessage) ToolCallContent

NewServerToolCallContent returns a provider-executed call (hosted tool): the executor skips it, history replay renders it natively, and the UI shows it display-only.

func NewToolCallContent

func NewToolCallContent(id, name string, arguments json.RawMessage) ToolCallContent

NewToolCallContent returns a ToolCallContent with the type discriminant set.

func (ToolCallContent) IsServer

func (c ToolCallContent) IsServer() bool

IsServer reports whether the call was executed provider-side and must never reach the local registry (no "unknown tool" failure, no approval prompt, no function_call_output pairing on replay).

func (ToolCallContent) MarshalJSON

func (t ToolCallContent) MarshalJSON() ([]byte, error)

MarshalJSON encodes a ToolCallContent, tolerating malformed Arguments. A model can stream syntactically invalid tool-call JSON (a truncated or duplicated key, e.g. `{"todos": []{}...`); such bytes are kept verbatim in Arguments so schema validation can report "not valid JSON" to the model, but json.RawMessage.MarshalJSON rejects them, which would otherwise abort every downstream serialization (session persistence, provider re-serialization) and take the whole turn down. To keep those paths crash-free we emit invalid arguments as a JSON string of the raw bytes: valid JSON that round-trips the original text. Well-formed arguments are emitted unchanged.

type ToolExecutionEndEvent

type ToolExecutionEndEvent struct {
	ToolCallID string
	ToolName   string
	Result     AgentToolResult
	IsError    bool
}

ToolExecutionEndEvent is emitted when a tool finishes.

func (ToolExecutionEndEvent) EventType

func (ToolExecutionEndEvent) EventType() string

type ToolExecutionMode

type ToolExecutionMode string

ToolExecutionMode selects how a tool is executed relative to others in a batch.

const (
	// ToolExecutionParallel allows the tool to run concurrently with others.
	ToolExecutionParallel ToolExecutionMode = "parallel"
	// ToolExecutionSequential forces the whole batch to run serially.
	ToolExecutionSequential ToolExecutionMode = "sequential"
)

type ToolExecutionStartEvent

type ToolExecutionStartEvent struct {
	ToolCallID string
	ToolName   string
	Args       any
}

ToolExecutionStartEvent is emitted before a tool runs.

func (ToolExecutionStartEvent) EventType

func (ToolExecutionStartEvent) EventType() string

type ToolExecutionUpdateEvent

type ToolExecutionUpdateEvent struct {
	ToolCallID    string
	ToolName      string
	PartialResult AgentToolResult
}

ToolExecutionUpdateEvent carries a partial result during tool execution.

func (ToolExecutionUpdateEvent) EventType

func (ToolExecutionUpdateEvent) EventType() string

type ToolGateChain added in v1.2.17

type ToolGateChain struct {
	// PrepareArguments runs PreToolUse rewrites before validation and before
	// the three gates. A derived run must inherit it along with the gate so it
	// never authorizes the original arguments and executes rewritten ones.
	PrepareArguments PrepareArgumentsFunc
	// BeforeToolCall is the composed gate (trust → read-scope → permission),
	// after any PreToolUse rewrite. Nil means the run is ungated.
	BeforeToolCall BeforeToolCallFunc
	// AfterToolCall is the PostToolUse seam. Nil is a no-op.
	AfterToolCall AfterToolCallFunc
	// Snapshot, when set, reports the session authorizations a derived run must
	// be seeded with when it runs where these seams cannot reach — the process
	// boundary. Nil means nothing to carry.
	Snapshot func() ToolAuth
	// OnChildStop, when set, is consulted when the derived run is about to end
	// naturally: the SubagentStop hook family, which fires with the child's
	// context and its own consecutive-block budget. It reports whether to keep
	// the child running and any guidance to append. Nil leaves the child's end
	// to the child.
	OnChildStop func(ctx context.Context, agentCtx *AgentContext) (block bool, guidance string)
}

ToolGateChain is the tool-gating chain a run executes under: the before/after tool-call seams plus the authorization snapshot a derived run needs when it cannot share them (a sub-agent in another process).

It exists so a derived run inherits the session's gates instead of each dispatch site assembling its own. The tool executor publishes the chain it was configured with onto every tool call's context (see WithToolGates), so the sub-agent tool can hand the very same chain to the child run — the child is then gated by the session's trust, workspace-boundary and permission gates with no per-driver wiring, and a nested child inherits again the same way.

The session's own loop-level seams (OnStop, checkpoints) are deliberately NOT here: a child run is a bounded unit whose end is its own, and inheriting the session's Stop hook would let a hook written for the conversation trap a child in a loop. OnChildStop is the counterpart that does belong: the hook event written for children, with the child's own context and block budget.

func ToolGatesFromContext added in v1.2.17

func ToolGatesFromContext(ctx context.Context) *ToolGateChain

ToolGatesFromContext returns the chain published for this tool call, or nil when the call runs outside a gated executor (a unit test, an SDK session with no gates).

type ToolResultMessage

type ToolResultMessage struct {
	RoleField  string      `json:"role"`
	ToolCallID string      `json:"toolCallId"`
	ToolName   string      `json:"toolName"`
	Content    ContentList `json:"content"`
	Details    any         `json:"details,omitempty"`
	IsError    bool        `json:"isError"`
	Timestamp  int64       `json:"timestamp"`
}

ToolResultMessage carries the outcome of executing a single tool call. Content is restricted to text/image blocks at construction.

func (ToolResultMessage) Role

func (m ToolResultMessage) Role() string

type ToolTiming

type ToolTiming struct {
	// Count is how many times the tool was invoked over the run.
	Count int
	// TotalMs is the summed wall-clock duration of every invocation, in
	// milliseconds.
	TotalMs int64
}

ToolTiming records how long one tool invocation took, keyed by tool name in TelemetryEvent.ToolDurationsMs. It aggregates repeated calls of the same tool so a summary stays compact regardless of turn count.

type ToolUpdateFunc

type ToolUpdateFunc func(partial AgentToolResult)

ToolUpdateFunc receives a partial result during tool execution; the loop turns each call into a tool_execution_update event.

type TurnEndEvent

type TurnEndEvent struct {
	Message     AssistantMessage
	ToolResults []ToolResultMessage
	// Stalled and StallLimit report that this turn produced nothing the person
	// can act on — no visible text and no tool call, only reasoning — and what
	// the loop did about it. Stalled is the number of such turns in a row ending
	// with this one (0 for an ordinary turn); when it is at or below StallLimit
	// the loop has asked the model to carry on, and above it the loop has given
	// up and the run stops here. A consumer uses the pair to say which happened:
	// the turn itself is silent, and a silent turn with no explanation is the
	// failure this exists to remove (see AssistantMessage.HasVisibleOutput).
	Stalled    int
	StallLimit int
}

TurnEndEvent marks the end of a turn, with the assistant message and any tool results produced during it.

func (TurnEndEvent) EventType

func (TurnEndEvent) EventType() string

type TurnStartEvent

type TurnStartEvent struct{}

TurnStartEvent marks the start of a turn (a single assistant response cycle).

func (TurnStartEvent) EventType

func (TurnStartEvent) EventType() string

type Usage

type Usage struct {
	InputTokens  int `json:"inputTokens"`
	OutputTokens int `json:"outputTokens"`
	// CacheReadTokens / CacheWriteTokens are prompt-cache accounting from
	// Anthropic-wire providers, whose input_tokens counts only the uncached
	// remainder. OpenAI-wire providers fold cache hits into InputTokens, so
	// their decoders leave these zero; context accounting adds them on top.
	CacheReadTokens  int `json:"cacheReadTokens,omitempty"`
	CacheWriteTokens int `json:"cacheWriteTokens,omitempty"`
}

Usage reports token accounting for an assistant response.

type UserMessage

type UserMessage struct {
	RoleField string      `json:"role"`
	Content   ContentList `json:"content"`
	Timestamp int64       `json:"timestamp"`
}

UserMessage is input from the user. Content is restricted at construction to text/image blocks (runtime constraint, not a separate interface).

func (UserMessage) Role

func (m UserMessage) Role() string

Jump to

Keyboard shortcuts

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