Documentation
¶
Overview ¶
pi: agent.ts — stateful wrapper around the low-level agent loop.
`Agent` owns the current transcript, emits lifecycle events, executes tools, and exposes queueing APIs for steering and follow-up messages.
Mapping deviations, all declared here:
- TS's single-threaded event loop guaranteed unsynchronized reads of agent state from other "tasks". pig guards state, queues, listeners, and the active run with one mutex, and adds Snapshot() for race-safe reads from goroutines that are not the run goroutine. Direct reads through State() are safe from listener callbacks (same goroutine as the state write) or when idle.
- pi's state.tools/state.messages accessor properties copy the assigned top-level array. Go cannot intercept field assignment, so the copy semantics live on SetTools/SetMessages; plain field writes through State() do not copy.
- pi's runWithLifecycle catches ANY throw from the executor (a throwing streamFn, a throwing hook, a rejected listener) and converts it into the failure event sequence. pig models that catch-all with recover() around the executor; a panic in a parallel tool goroutine is NOT covered (different goroutine) — tools report failures via error returns, matching the loop's contract.
- processEvents' "Agent listener invoked outside active run" throw is unreachable in pig (the event sink is only installed inside runWithLifecycle); it panics to keep the invariant loud, and the panic lands in the same recover → handleRunFailure path as TS's throw.
- prompt() overloads: Go splits into Prompt(ctx, messages...) (the AgentMessage | AgentMessage[] overload) and PromptText(ctx, input, images...) (the string + images overload).
- AbortController → ctx+cancel; the run context derives from the ctx passed to Prompt/Continue (pig addition: caller ctx cancellation also aborts the run; pi only aborts via agent.abort()).
pi: agent-loop.ts — agent loop that works with AgentMessage throughout. Transforms to Message[] only at the LLM call boundary.
Mapping notes:
- pi's `signal: AbortSignal | undefined` parameters become the leading ctx context.Context (AbortSignal → context rule); `signal?.aborted` checks become signalAborted(ctx).
- AgentEventSink returns Promise<void> | void in pi; pig callbacks are synchronous (callback rule).
- When streamFn is nil and no default is configured, pi throws inside the run promise after agent_start/turn_start/message events were emitted, leaving the EventStream unresolved (unhandled rejection). pig cannot leave a goroutine hanging: it returns the messages collected so far and the caller ends the stream with them (same resolution rule as the EventStream zero-result deviation).
Package agent corresponds to pi's packages/agent/src.
pi: proxy.ts — proxy stream function for apps that route LLM calls through a server. The server manages auth and proxies requests to LLM providers.
Mapping notes:
- pi's `options.signal` becomes the leading ctx (AbortSignal → context rule); the signal abort listener collapses into ctx cancellation closing the response body.
- pi's ProxyMessageEventStream class restates the EventStream generic with done/error terminals and the final message as result; pig's AssistantMessageEventStream already encodes exactly that contract.
- The `partial` field is a live object shared into every event in pi; pig snapshots it per event (same rule as the openai adapter's push).
pi: stream-fn.ts.
Index ¶
- func AgentLoop(ctx context.Context, prompts []AgentMessage, agentContext AgentContext, ...) *types.EventStream[AgentEvent, []AgentMessage]
- func AgentLoopContinue(ctx context.Context, agentContext AgentContext, config AgentLoopConfig, ...) (*types.EventStream[AgentEvent, []AgentMessage], error)
- func SetDefaultStreamFn(streamFn StreamFn)
- func StreamProxy(ctx context.Context, model *types.Model, llmContext *types.TranscriptContext, ...) *types.AssistantMessageEventStream
- type AfterToolCallContext
- type AfterToolCallResult
- type Agent
- func (a *Agent) Abort()
- func (a *Agent) ClearAllQueues()
- func (a *Agent) ClearFollowUpQueue()
- func (a *Agent) ClearSteeringQueue()
- func (a *Agent) Continue(ctx context.Context) error
- func (a *Agent) FollowUp(message AgentMessage)
- func (a *Agent) FollowUpMode() QueueMode
- func (a *Agent) HasQueuedMessages() bool
- func (a *Agent) PeekQueuedMessages() []AgentMessage
- func (a *Agent) Prompt(ctx context.Context, messages ...AgentMessage) error
- func (a *Agent) PromptText(ctx context.Context, input string, images ...types.ImageContent) error
- func (a *Agent) Reset() error
- func (a *Agent) SetFollowUpMode(mode QueueMode)
- func (a *Agent) SetMessages(messages []AgentMessage)
- func (a *Agent) SetSteeringMode(mode QueueMode)
- func (a *Agent) SetTools(tools []AgentTool)
- func (a *Agent) Signal() context.Context
- func (a *Agent) Snapshot() AgentState
- func (a *Agent) State() *AgentState
- func (a *Agent) Steer(message AgentMessage)
- func (a *Agent) SteeringMode() QueueMode
- func (a *Agent) Subscribe(listener func(ctx context.Context, event AgentEvent)) (unsubscribe func())
- func (a *Agent) WaitForIdle()
- type AgentContext
- type AgentEvent
- type AgentEventSink
- type AgentEventType
- type AgentLoopConfig
- type AgentLoopTurnUpdate
- type AgentMessage
- type AgentOptions
- type AgentRequestUpdate
- type AgentState
- type AgentTool
- type AgentToolCall
- type AgentToolReplay
- type AgentToolResult
- type AgentToolUpdateCallback
- type AgentTurnAction
- type AgentTurnContext
- type AgentTurnDecision
- type BeforeToolCallContext
- type BeforeToolCallResult
- type CannotContinueError
- type FinishTurn
- type PrepareNextTurnContext
- type PrepareRequest
- type PrepareRequestContext
- type ProxyAssistantMessageEvent
- type ProxySerializableStreamOptions
- type ProxyStreamOptions
- type QueueMode
- type StreamFn
- type ThinkingLevel
- type ToolExecutionMode
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func AgentLoop ¶
func AgentLoop(ctx context.Context, prompts []AgentMessage, agentContext AgentContext, config AgentLoopConfig, streamFn StreamFn) *types.EventStream[AgentEvent, []AgentMessage]
AgentLoop starts an agent loop with new prompt messages. The prompts are added to the context and events are emitted for them. ctx carries the caller's cancellation (pi: signal).
func AgentLoopContinue ¶
func AgentLoopContinue(ctx context.Context, agentContext AgentContext, config AgentLoopConfig, streamFn StreamFn) (*types.EventStream[AgentEvent, []AgentMessage], error)
AgentLoopContinue continues an agent loop from the current context without adding a new message. Used for retries - context already has user message or tool results.
**Important:** The last message in context must convert to a `user` or `toolResult` message via `convertToLlm`. If it doesn't, the LLM provider will reject the request. This cannot be validated here since `convertToLlm` is only called once per turn.
pi throws synchronously on the two invalid-context cases; pig returns an error before the stream is created.
func SetDefaultStreamFn ¶
func SetDefaultStreamFn(streamFn StreamFn)
SetDefaultStreamFn configures the fallback used by Agent and low-level loops when callers omit streamFn.
Hosts that provide a default model runtime can install its stream function here without making the agent package depend on a provider catalog or compatibility layer.
func StreamProxy ¶
func StreamProxy(ctx context.Context, model *types.Model, llmContext *types.TranscriptContext, options *ProxyStreamOptions) *types.AssistantMessageEventStream
StreamProxy streams through a proxy server instead of calling LLM providers directly. The server strips the partial field from delta events to reduce bandwidth; we reconstruct the partial message client-side. Use this as the streamFn when creating an Agent that needs to go through a proxy (pi: streamProxy).
Types ¶
type AfterToolCallContext ¶
type AfterToolCallContext struct {
// AssistantMessage is the assistant message that requested the tool call.
AssistantMessage types.AssistantMessage
// ToolCall is the raw tool call block from AssistantMessage.Content.
ToolCall AgentToolCall
// Args are the validated tool arguments for the target tool schema.
Args any
// Result is the executed tool result before any `afterToolCall` overrides
// are applied.
Result AgentToolResult
// IsError reports whether the executed tool result is currently treated
// as an error.
IsError bool
// Context is the current agent context at the time the tool call is
// finalized.
Context *AgentContext
}
AfterToolCallContext is passed to `afterToolCall`.
type AfterToolCallResult ¶
type AfterToolCallResult struct {
Content []types.Content
Details any
IsError *bool
// Usage from the final tool execution itself, if available. Not used for
// main LLM context accounting.
Usage *types.Usage
// Terminate hints that the agent should stop after the current tool batch.
// Early termination only happens when every finalized tool result in the
// batch sets this to true.
Terminate *bool
}
AfterToolCallResult is the partial override returned from `afterToolCall`.
Merge semantics are field-by-field:
- Content: if non-nil, replaces the tool result content array in full
- Details: if non-nil, replaces the tool result details value in full
- IsError: if non-nil, replaces the tool result error flag
- Usage: if non-nil, replaces the tool result usage
- Terminate: if non-nil, replaces the early-termination hint
Nil fields keep the original executed tool result values. There is no deep merge for Content, Details, or Usage. (pi distinguishes undefined from an explicit null override; Go folds both into nil — a hook cannot null out Details, matching the practical override use case.)
type Agent ¶
type Agent struct {
// Public, user-settable fields (pi: public fields on Agent).
ConvertToLlm func(messages []AgentMessage) []types.Message
TransformContext func(ctx context.Context, messages []AgentMessage) []AgentMessage
StreamFunction StreamFn
GetApiKey func(provider types.ProviderID) string
OnPayload func(payload any, model *types.Model) any
OnResponse func(response types.ProviderResponse, model *types.Model)
BeforeToolCall func(ctx context.Context, context BeforeToolCallContext) (*BeforeToolCallResult, error)
AfterToolCall func(ctx context.Context, context AfterToolCallContext) (*AfterToolCallResult, error)
FinishTurn FinishTurn
PrepareRequest PrepareRequest
PrepareNextTurn func(ctx context.Context) *AgentLoopTurnUpdate
PrepareNextTurnWithContext func(ctx context.Context, context PrepareNextTurnContext) *AgentLoopTurnUpdate
// SessionID is forwarded to providers for cache-aware backends.
SessionID string
// ThinkingBudgets is forwarded to the stream function.
ThinkingBudgets *types.ThinkingBudgets
// Transport is forwarded to the stream function.
Transport types.Transport
// MaxRetryDelayMs caps provider-requested retry delays.
MaxRetryDelayMs *int64
// ToolExecution is the tool execution strategy for assistant messages
// that contain multiple tool calls.
ToolExecution ToolExecutionMode
// contains filtered or unexported fields
}
Agent is the stateful wrapper around the low-level agent loop.
func NewAgent ¶
func NewAgent(options AgentOptions) (*Agent, error)
NewAgent constructs an Agent. pi throws for a missing stream function with no default configured; NewAgent returns the error instead.
func (*Agent) Abort ¶
func (a *Agent) Abort()
Abort aborts the current run, if one is active. Safe to call when idle.
func (*Agent) ClearAllQueues ¶
func (a *Agent) ClearAllQueues()
ClearAllQueues removes all queued steering and follow-up messages.
func (*Agent) ClearFollowUpQueue ¶
func (a *Agent) ClearFollowUpQueue()
ClearFollowUpQueue removes all queued follow-up messages.
func (*Agent) ClearSteeringQueue ¶
func (a *Agent) ClearSteeringQueue()
ClearSteeringQueue removes all queued steering messages.
func (*Agent) Continue ¶
Continue continues from the current transcript. The last message must be a user or tool-result message. pi throws on the invalid cases; pig returns errors.
func (*Agent) FollowUp ¶
func (a *Agent) FollowUp(message AgentMessage)
FollowUp queues a message to run only after the agent would otherwise stop.
func (*Agent) FollowUpMode ¶
FollowUpMode reports how queued follow-up messages are drained.
func (*Agent) HasQueuedMessages ¶
HasQueuedMessages returns true when either queue still contains pending messages.
func (*Agent) PeekQueuedMessages ¶ added in v0.87.0
func (a *Agent) PeekQueuedMessages() []AgentMessage
PeekQueuedMessages previews the messages selected for the next turn without consuming them (pi v0.87.0: steering wins over follow-up).
func (*Agent) Prompt ¶
func (a *Agent) Prompt(ctx context.Context, messages ...AgentMessage) error
Prompt starts a new prompt from one message or a batch of messages (pi: prompt(message: AgentMessage | AgentMessage[])). pi throws while a run is active; pig returns an error.
func (*Agent) PromptText ¶
PromptText starts a new prompt from text and optional images (pi: prompt(input: string, images?: ImageContent[])).
func (*Agent) Reset ¶
Reset clears transcript state, runtime state, and queued messages. pi throws when a run is active; pig returns an error.
func (*Agent) SetFollowUpMode ¶
SetFollowUpMode controls how queued follow-up messages are drained (pi: followUpMode accessor).
func (*Agent) SetMessages ¶
func (a *Agent) SetMessages(messages []AgentMessage)
SetMessages replaces the transcript, copying the top-level slice (pi: state.messages setter).
func (*Agent) SetSteeringMode ¶
SetSteeringMode controls how queued steering messages are drained (pi: steeringMode accessor).
func (*Agent) SetTools ¶
SetTools replaces the tools, copying the top-level slice (pi: state.tools setter).
func (*Agent) Snapshot ¶
func (a *Agent) Snapshot() AgentState
Snapshot returns a race-safe copy of the agent state (pig addition: pi relies on the single-threaded event loop; pig callers outside the run goroutine need synchronization).
func (*Agent) State ¶
func (a *Agent) State() *AgentState
State returns the agent state for direct access.
Assigning SystemPrompt/Model/ThinkingLevel works as plain fields. For Tools/Messages use SetTools/SetMessages to get pi's copy-on-assign behavior. Reads from goroutines outside the run while a run is active should use Snapshot instead.
func (*Agent) Steer ¶
func (a *Agent) Steer(message AgentMessage)
Steer queues a message to be injected after the current assistant turn finishes.
func (*Agent) SteeringMode ¶
SteeringMode reports how queued steering messages are drained.
func (*Agent) Subscribe ¶
func (a *Agent) Subscribe(listener func(ctx context.Context, event AgentEvent)) (unsubscribe func())
Subscribe registers a listener for agent lifecycle events and returns an unsubscribe function.
Listener promises are awaited in subscription order and are included in the current run's settlement (in pig: listeners run synchronously in the emit goroutine, so Prompt does not return until they finish). Listeners also receive the active run context for the current run.
`agent_end` is the final emitted event for a run, but the agent does not become idle until all awaited listeners for that event have settled.
func (*Agent) WaitForIdle ¶
func (a *Agent) WaitForIdle()
WaitForIdle resolves when the current run and all awaited event listeners have finished. This returns after `agent_end` listeners settle.
type AgentContext ¶
type AgentContext struct {
// Messages is the transcript visible to the model.
Messages []AgentMessage
// Tools are available for execution in this run.
Tools []*AgentTool
}
AgentContext is the context snapshot passed into the low-level agent loop.
type AgentEvent ¶
type AgentEvent struct {
Type AgentEventType
// Messages (agent_end) are the messages produced by the run. agent_end is
// the last event emitted for a run, but awaited Agent.subscribe()
// listeners for that event are still part of run settlement. The agent
// becomes idle only after those listeners finish.
Messages []AgentMessage
// Message (turn_end, message_start, message_update, message_end) is the
// message the event refers to.
Message AgentMessage
// ToolResults (turn_end) are the tool result messages of the turn.
ToolResults []types.ToolResultMessage
// AssistantMessageEvent (message_update) is the raw streaming event.
AssistantMessageEvent *types.AssistantMessageEvent
// ToolCallID (tool_execution_*) identifies the tool call.
ToolCallID string
// ToolName (tool_execution_*) names the tool.
ToolName string
// Args (tool_execution_*) are the raw tool call arguments.
Args any
// PartialResult (tool_execution_update) is the streamed partial result.
PartialResult any
// Result (tool_execution_end) is the finalized AgentToolResult.
Result any
// IsError (tool_execution_end) reports tool failure.
IsError bool
// DurationMs (tool_execution_end) is how long the tool's Execute took,
// measured with a monotonic clock; nil when the tool did not run (pi:
// durationMs, #10549).
DurationMs *int64
// Aborted (agent_settled) reports whether the run ended because it was
// aborted, for example with Escape (pi: AgentSettledEvent.aborted,
// S17 503c60552).
Aborted bool
}
AgentEvent is one event emitted by the agent loop. pi models it as a discriminated union; pig uses a single struct where exactly the fields named by Type are meaningful:
agent_start (no payload)
agent_end Messages
turn_start (no payload)
turn_end Message, ToolResults
message_start Message
message_update Message, AssistantMessageEvent — only emitted for
assistant messages during streaming
message_end Message
tool_execution_start ToolCallID, ToolName, Args
tool_execution_update ToolCallID, ToolName, Args, PartialResult
tool_execution_end ToolCallID, ToolName, Result, IsError, DurationMs
type AgentEventSink ¶
type AgentEventSink func(event AgentEvent)
AgentEventSink consumes agent events. pi's Promise<void> | void collapses to a synchronous callback; emit points are all sequential in the loop.
type AgentEventType ¶
type AgentEventType string
AgentEventType discriminates the events emitted by the Agent for UI updates (pi: AgentEvent discriminated union; pig uses a single struct where exactly the fields named by Type are meaningful).
const ( AgentEventAgentStart AgentEventType = "agent_start" AgentEventAgentEnd AgentEventType = "agent_end" AgentEventTurnStart AgentEventType = "turn_start" AgentEventTurnEnd AgentEventType = "turn_end" AgentEventMessageStart AgentEventType = "message_start" AgentEventMessageUpdate AgentEventType = "message_update" AgentEventMessageEnd AgentEventType = "message_end" AgentEventToolExecutionStart AgentEventType = "tool_execution_start" AgentEventToolExecutionUpdate AgentEventType = "tool_execution_update" AgentEventToolExecutionEnd AgentEventType = "tool_execution_end" )
type AgentLoopConfig ¶
type AgentLoopConfig struct {
types.SimpleStreamOptions
Model *types.Model
// ConvertToLlm converts AgentMessage[] to LLM-compatible Message[] before
// each LLM call.
//
// Each AgentMessage must be converted to a SystemMessage, UserMessage,
// AssistantMessage, or ToolResultMessage that the LLM can understand.
// AgentMessages that cannot be converted (e.g., UI-only notifications,
// status messages) should be filtered out.
//
// Contract: must not panic. Return a safe fallback value instead.
// Panicking interrupts the low-level agent loop without producing a
// normal event sequence.
ConvertToLlm func(messages []AgentMessage) []types.Message
// TransformContext is an optional transform applied to the context before
// `convertToLlm`.
//
// Use this for operations that work at the AgentMessage level:
// - Context window management (pruning old messages)
// - Injecting context from external sources
//
// Contract: must not panic. Return the original messages or another safe
// fallback value instead.
TransformContext func(ctx context.Context, messages []AgentMessage) []AgentMessage
// GetApiKey resolves an API key dynamically for each LLM call.
//
// Useful for short-lived OAuth tokens (e.g., GitHub Copilot) that may
// expire during long-running tool execution phases.
//
// Contract: must not panic. Return "" when no key is available.
GetApiKey func(provider types.ProviderID) string
// FinishTurn is called after the assistant message and all tool-result
// messages have been emitted, immediately before `turn_end`.
//
// `{ action: "end" }` ends the run without polling queues or preparing
// another request. On a normal turn, `{ action: "continue" }` ensures one
// next provider request. Tool-result, steering, or follow-up scheduling
// can satisfy that request and adds no extra request; otherwise the loop
// continues once with the current context. Returning nil preserves normal
// scheduling. Error and aborted responses remain hard exits (the callback
// still runs, but its decision is ignored).
//
// Contract: must not panic. Panicking interrupts the low-level agent loop
// without producing a normal event sequence.
FinishTurn FinishTurn
// PrepareRequest is called immediately before every conversational
// provider request, including the first. Pending messages have already
// been appended. The returned context, model, and thinking level replace
// the runtime values for this and later requests in the run. This hook
// does not poll queues. Return nil to keep using the current
// context/config.
PrepareRequest PrepareRequest
// PrepareNextTurn is called after `turn_end` when the loop will continue,
// immediately before the next turn starts. Return replacement
// context/model/thinking state to affect that turn.
// Return nil to keep using the current context/config.
PrepareNextTurn func(context PrepareNextTurnContext) *AgentLoopTurnUpdate
// GetSteeringMessages returns steering messages to inject into the
// conversation mid-run.
//
// Called after the current assistant turn finishes executing its tool
// calls, unless `finishTurn` ends the run. If messages are
// returned, they are added to the context before the next LLM call. Tool
// calls from the current assistant message are not skipped.
//
// Use this for "steering" the agent while it's working.
//
// Contract: must not panic. Return nil when no steering messages are
// available.
GetSteeringMessages func() []AgentMessage
// GetFollowUpMessages returns follow-up messages to process after the
// agent would otherwise stop.
//
// Called when the agent has no more tool calls and no steering messages.
// If messages are returned, they're added to the context and the agent
// continues with another turn.
//
// Use this for follow-up messages that should wait until the agent
// finishes.
//
// Contract: must not panic. Return nil when no follow-up messages are
// available.
GetFollowUpMessages func() []AgentMessage
// ToolExecution selects the tool execution mode.
// - "sequential": execute tool calls one by one
// - "parallel": preflight tool calls sequentially, then execute allowed
// tools concurrently; emit `tool_execution_end` in tool completion
// order after each tool is finalized, then emit tool-result message
// artifacts later in assistant source order
//
// Default: "parallel" (empty value).
ToolExecution ToolExecutionMode
// BeforeToolCall is called before a tool is executed, after arguments
// have been validated.
//
// Return a BeforeToolCallResult with Block=true to prevent execution. The
// loop emits an error tool result instead. A blocked result can also set
// Terminate to participate in the batch early-termination rule. The hook
// receives the agent context and is responsible for honoring
// cancellation.
//
// Returning a non-nil error models pi's hook throwing: the loop converts
// it into an error tool result.
BeforeToolCall func(ctx context.Context, context BeforeToolCallContext) (*BeforeToolCallResult, error)
// AfterToolCall is called after a tool finishes executing, before
// `tool_execution_end` and tool-result message events are emitted.
//
// Return an AfterToolCallResult to override parts of the executed tool
// result:
// - Content replaces the full content array
// - Details replaces the full details payload
// - IsError replaces the error flag
// - Usage replaces the tool result usage
// - Terminate replaces the early-termination hint
//
// Any nil fields keep their original values. No deep merge is performed.
// The hook receives the agent context and is responsible for honoring
// cancellation.
//
// Returning a non-nil error models pi's hook throwing: the loop converts
// it into an error tool result.
AfterToolCall func(ctx context.Context, context AfterToolCallContext) (*AfterToolCallResult, error)
}
AgentLoopConfig extends SimpleStreamOptions with the agent loop's hooks. Field comments carry pi's behavioral contracts verbatim; all callbacks are synchronous in pig (pi's Promise-returning hooks resolve inside the loop's own await points), and ctx carries the abort signal (pi: signal parameter).
type AgentLoopTurnUpdate ¶
type AgentLoopTurnUpdate struct {
// Context is the context for the next provider request.
Context *AgentContext
// Messages are appended before the next provider request, with normal
// lifecycle events (pi v0.86.0: messages).
Messages []AgentMessage
// Model is the model for the next provider request.
Model *types.Model
// ThinkingLevel is the thinking level for the next provider request.
ThinkingLevel ThinkingLevel
}
AgentLoopTurnUpdate is replacement runtime state used by the agent loop before starting another provider request.
type AgentMessage ¶
AgentMessage is the union of LLM messages plus custom messages. This abstraction allows apps to add custom message types while maintaining type safety and compatibility with the base LLM messages (pi: Message | CustomAgentMessages[keyof CustomAgentMessages]; in Go the union is simply the open types.Message interface — any type implementing MessageRole(), including app-defined ones — so a bare alias suffices).
func RunAgentLoop ¶
func RunAgentLoop(ctx context.Context, prompts []AgentMessage, agentContext AgentContext, config AgentLoopConfig, emit AgentEventSink, streamFn StreamFn) []AgentMessage
RunAgentLoop is the prompt-entry variant of the loop without the EventStream wrapper; events go to emit (pi: runAgentLoop).
func RunAgentLoopContinue ¶
func RunAgentLoopContinue(ctx context.Context, agentContext AgentContext, config AgentLoopConfig, emit AgentEventSink, streamFn StreamFn) ([]AgentMessage, error)
RunAgentLoopContinue is the continue-entry variant of the loop without the EventStream wrapper; events go to emit (pi: runAgentLoopContinue).
type AgentOptions ¶
type AgentOptions struct {
// InitialState seeds the agent state; nil/zero fields use defaults
// (pi: Partial<Omit<AgentState, ...>>).
InitialState *AgentState
ConvertToLlm func(messages []AgentMessage) []types.Message
// TransformContext is applied to the context before convertToLlm (pi:
// (messages, signal?); ctx carries the run cancellation).
TransformContext func(ctx context.Context, messages []AgentMessage) []AgentMessage
// StreamFn is required; when nil, the default stream function must be
// configured (SetDefaultStreamFn) or NewAgent fails (pi: throws).
StreamFn StreamFn
// GetApiKey resolves an API key per LLM call (pi: (provider) =>
// string | undefined | Promise<...>; sync in pig, "" = no key).
GetApiKey func(provider types.ProviderID) string
// OnPayload and OnResponse forward to the stream options.
OnPayload func(payload any, model *types.Model) any
OnResponse func(response types.ProviderResponse, model *types.Model)
// BeforeToolCall and AfterToolCall forward to the loop config; their
// error returns model pi's hook throws (caught by the loop).
BeforeToolCall func(ctx context.Context, context BeforeToolCallContext) (*BeforeToolCallResult, error)
AfterToolCall func(ctx context.Context, context AfterToolCallContext) (*AfterToolCallResult, error)
// FinishTurn forwards to the loop config (pi v0.87.0: (context, signal);
// the loop ctx carries the run cancellation).
FinishTurn FinishTurn
// PrepareRequest forwards to the loop config (pi: (request, signal)).
PrepareRequest PrepareRequest
// PrepareNextTurn receives only the run context (pi: (signal)).
PrepareNextTurn func(ctx context.Context) *AgentLoopTurnUpdate
// PrepareNextTurnWithContext receives the turn context and the run
// context (pi: (context, signal)); it wins over PrepareNextTurn.
PrepareNextTurnWithContext func(ctx context.Context, context PrepareNextTurnContext) *AgentLoopTurnUpdate
// SteeringMode and FollowUpMode control queue draining; empty defaults
// to QueueModeOneAtATime.
SteeringMode QueueMode
FollowUpMode QueueMode
// SessionID forwards to providers for cache-aware backends.
SessionID string
// ThinkingBudgets forwards per-level thinking token budgets to the stream
// function.
ThinkingBudgets *types.ThinkingBudgets
// Transport is the preferred transport; empty defaults to
// types.TransportAuto.
Transport types.Transport
// MaxRetryDelayMs caps provider-requested retry delays.
MaxRetryDelayMs *int64
// ToolExecution is the tool execution strategy for assistant messages
// that contain multiple tool calls; empty defaults to
// ToolExecutionParallel.
ToolExecution ToolExecutionMode
}
AgentOptions are the options for constructing an Agent (pi: AgentOptions). Hook ctx parameters carry the active run's cancellation (pi: the signal argument); unset optional fields use their zero value.
type AgentRequestUpdate ¶ added in v0.87.0
type AgentRequestUpdate struct {
Context *AgentContext
Model *types.Model
ThinkingLevel ThinkingLevel
}
AgentRequestUpdate is replacement runtime state for the provider request being prepared (pi: Omit<AgentLoopTurnUpdate, "messages">).
type AgentState ¶
type AgentState struct {
// SystemPrompt is the current system prompt, replayed from the
// transcript's system messages. Read-only: to change the prompt, append
// a system message with Content or Sections. In the initial state this
// seeds the leading system message (pi v0.86.0: readonly getter).
SystemPrompt string
// Model is the active model used for future turns.
Model *types.Model
// ThinkingLevel is the requested reasoning level for future turns.
ThinkingLevel ThinkingLevel
// Tools are the executable tools. Assigning a new slice copies the
// top-level slice. Differences from the tools declared in the transcript
// are announced to the model with a system message before the next
// request.
Tools []AgentTool
// Messages is the conversation transcript. Assigning a new slice copies
// the top-level slice. System messages in the transcript carry the
// prompt and tool declarations.
Messages []AgentMessage
// IsStreaming is true while the agent is processing a prompt or
// continuation.
//
// This remains true until awaited `agent_end` listeners settle.
IsStreaming bool
// StreamingMessage is the partial assistant message for the current
// streamed response, if any.
StreamingMessage AgentMessage
// PendingToolCalls are the tool call ids currently executing.
PendingToolCalls map[string]bool
// ErrorMessage is from the most recent failed or aborted assistant turn,
// if any.
ErrorMessage string
}
AgentState is the public agent state.
Tools and Messages are plain fields in pig; the copy-on-assign accessor behavior pi gets from setter properties is enforced by the Agent implementation (pi: agent.ts, future agent.go).
type AgentTool ¶
type AgentTool struct {
types.Tool
// Label is a human-readable label for UI display.
Label string
// PrepareArguments is an optional compatibility shim for raw tool-call
// arguments before schema validation. Must return a value that matches
// the tool's parameter schema. Returning the input map unchanged (the
// same reference) means "nothing to prepare"; the loop detects a new map
// and swaps it into the tool call.
PrepareArguments func(args any) any
// Execute runs the tool call. ctx carries the agent's cancellation (pi:
// signal). Return an error on failure; the loop converts it into an error
// tool result.
Execute func(ctx context.Context, toolCallID string, params any, onUpdate AgentToolUpdateCallback) (AgentToolResult, error)
// ExecutionMode is the per-tool execution mode override.
// - "sequential": this tool must execute one at a time with other tool
// calls.
// - "parallel": this tool can execute concurrently with other tool
// calls.
//
// If empty, the default execution mode applies.
ExecutionMode ToolExecutionMode
// Replay is the recovery policy for an effect whose durable intent
// exists but whose outcome is unknown (pi: AgentTool.replay).
Replay AgentToolReplay
}
AgentTool is a tool definition used by the agent runtime (pi: AgentTool<TParameters extends TSchema, TDetails> extends Tool<TParameters>; generics are dropped — see the package comment). Execute returns an error on failure instead of encoding errors in Content.
type AgentToolCall ¶
AgentToolCall is a single tool call content block emitted by an assistant message (pi: Extract<AssistantMessage["content"][number], { type: "toolCall" }>); pig's content model already names this type.
type AgentToolReplay ¶
type AgentToolReplay string
AgentToolReplay is the recovery policy carried by AgentTool.Replay (pi: `replay?: "never" | "safe"`; closed string union → named type per the ToolExecutionMode precedent).
const ( // AgentToolReplayNever means the effect must never be re-issued; its // durable intent may exist but the outcome is unknown. AgentToolReplayNever AgentToolReplay = "never" // AgentToolReplaySafe means re-issuing the effect is safe when its // outcome is unknown. AgentToolReplaySafe AgentToolReplay = "safe" )
type AgentToolResult ¶
type AgentToolResult struct {
// Content is the text or image content returned to the model.
Content []types.Content
// Details is arbitrary structured details for logs or UI rendering.
Details any
// Usage, from the final tool execution itself, if available. Not used for
// main LLM context accounting.
Usage *types.Usage
// pi v0.86.0 removed AgentToolResult.addedToolNames: tool introductions
// moved to transcript system messages.
StopAfterTool *bool
// Terminate hints that the agent should stop after the current tool
// batch. Early termination only happens when every finalized tool result
// in the batch sets this to true.
Terminate bool
}
AgentToolResult is the final or partial result produced by a tool.
type AgentToolUpdateCallback ¶
type AgentToolUpdateCallback func(partialResult AgentToolResult)
AgentToolUpdateCallback is the callback used by tools to stream partial execution updates.
The callback is scoped to the current Execute() invocation. Calls made after the tool returns are ignored.
type AgentTurnAction ¶ added in v0.87.0
type AgentTurnAction string
AgentTurnAction enumerates the decisions FinishTurn may return (pi: { action: "continue" } | { action: "end" }).
const ( AgentTurnActionContinue AgentTurnAction = "continue" AgentTurnActionEnd AgentTurnAction = "end" )
type AgentTurnContext ¶ added in v0.87.0
type AgentTurnContext struct {
// Message is the assistant message that completed the turn.
Message types.AssistantMessage
// ToolResults are the tool result messages emitted for the completed
// turn (pi v0.87.0 wording).
ToolResults []types.ToolResultMessage
// Context is the current agent context after the turn's assistant message
// and tool results have been appended.
Context *AgentContext
// NewMessages are the messages this loop invocation will return if it
// exits at this point. Prompt runs include the initial prompt messages;
// continuation runs do not include pre-existing context messages.
NewMessages []AgentMessage
}
AgentTurnContext is passed to completed-turn callbacks (pi v0.87.0: renamed from ShouldStopAfterTurnContext; consumed by finishTurn, prepareNextTurn, and their Agent-level variants).
type AgentTurnDecision ¶ added in v0.87.0
type AgentTurnDecision struct {
Action AgentTurnAction
}
AgentTurnDecision is the decision returned by FinishTurn. nil preserves normal scheduling (pi: returning undefined).
type BeforeToolCallContext ¶
type BeforeToolCallContext struct {
// AssistantMessage is the assistant message that requested the tool call.
AssistantMessage types.AssistantMessage
// ToolCall is the raw tool call block from AssistantMessage.Content.
ToolCall AgentToolCall
// Args are the validated tool arguments for the target tool schema.
Args any
// Context is the current agent context at the time the tool call is
// prepared.
Context *AgentContext
}
BeforeToolCallContext is passed to `beforeToolCall`.
type BeforeToolCallResult ¶
type BeforeToolCallResult struct {
Block bool
Reason string
// Terminate hints that the agent should stop after the current tool batch
// when this call is blocked. Early termination only happens when every
// finalized tool result in the batch sets this to true.
Terminate bool
}
BeforeToolCallResult is returned from `beforeToolCall`.
Returning Block=true prevents the tool from executing. The loop emits an error tool result instead. Reason becomes the text shown in that error result. If empty, a default blocked message is used.
type CannotContinueError ¶
type CannotContinueError struct {
Reason string
}
CannotContinueError is returned by AgentLoopContinue for the contexts pi rejects synchronously (empty context, last message role assistant).
func (*CannotContinueError) Error ¶
func (e *CannotContinueError) Error() string
type FinishTurn ¶ added in v0.87.0
type FinishTurn func(ctx context.Context, turn AgentTurnContext) *AgentTurnDecision
FinishTurn is called after a completed assistant turn and all of its tool-result messages, but before `turn_end`. On a normal turn, { action: "continue" } ensures one next provider request. Tool-result, steering, or follow-up scheduling can satisfy that request and adds no extra request; otherwise the loop continues once with the current context. Error and aborted responses remain hard exits (the decision is ignored).
type PrepareNextTurnContext ¶
type PrepareNextTurnContext = AgentTurnContext
PrepareNextTurnContext is the context passed to `prepareNextTurn` (pi v0.87.0 re-declares it as an extension-free alias of AgentTurnContext).
type PrepareRequest ¶ added in v0.87.0
type PrepareRequest func(ctx context.Context, request PrepareRequestContext) *AgentRequestUpdate
PrepareRequest is called immediately before every conversational provider request, including the first. Pending messages have already been appended and emitted when this callback runs. The returned context, model, and thinking level replace the runtime values for this and later requests in the run. This hook does not poll queues.
type PrepareRequestContext ¶ added in v0.87.0
type PrepareRequestContext struct {
Context *AgentContext
Model *types.Model
// ThinkingLevel mirrors pi's `config.reasoning ?? "off"`: never empty.
ThinkingLevel ThinkingLevel
}
PrepareRequestContext is the runtime state available immediately before a conversational provider request (pi v0.87.0).
type ProxyAssistantMessageEvent ¶
type ProxyAssistantMessageEvent struct {
Type string `json:"type"`
// ContentIndex is set on text_*/thinking_*/toolcall_* events.
ContentIndex int `json:"contentIndex,omitempty"`
// Delta is set on text_delta/thinking_delta/toolcall_delta.
Delta string `json:"delta,omitempty"`
// ContentSignature is the optional signature on text_end/thinking_end.
ContentSignature string `json:"contentSignature,omitempty"`
// ID and ToolName are set on toolcall_start.
ID string `json:"id,omitempty"`
ToolName string `json:"toolName,omitempty"`
// ToolCall is set on toolcall_end.
ToolCall *types.ToolCall `json:"toolCall,omitempty"`
// Reason is set on done (stop|length|toolUse) and error (aborted|error).
Reason types.StopReason `json:"reason,omitempty"`
// Usage is set on done/error.
Usage types.Usage `json:"usage,omitempty"`
// ErrorMessage is set on error.
ErrorMessage string `json:"errorMessage,omitempty"`
// ProviderThinkingLevel is set on done/error.
ProviderThinkingLevel string `json:"providerThinkingLevel,omitempty"`
}
ProxyAssistantMessageEvent is one proxy event. The server sends these with the partial field stripped to reduce bandwidth (pi: ProxyAssistantMessageEvent discriminated union; pig uses a single struct where exactly the fields named by Type are meaningful).
type ProxySerializableStreamOptions ¶
type ProxySerializableStreamOptions struct {
Temperature *float64 `json:"temperature,omitempty"`
SamplingParams map[string]any `json:"samplingParams,omitempty"`
MaxTokens *int64 `json:"maxTokens,omitempty"`
Reasoning types.ThinkingLevel `json:"reasoning,omitempty"`
CacheRetention types.CacheRetention `json:"cacheRetention,omitempty"`
SessionID string `json:"sessionId,omitempty"`
Headers types.ProviderHeaders `json:"headers,omitempty"`
Metadata map[string]any `json:"metadata,omitempty"`
Transport types.Transport `json:"transport,omitempty"`
ThinkingBudgets *types.ThinkingBudgets `json:"thinkingBudgets,omitempty"`
MaxRetryDelayMs *int64 `json:"maxRetryDelayMs,omitempty"`
}
ProxySerializableStreamOptions is the subset of SimpleStreamOptions the proxy request serializes (pi: ProxySerializableStreamOptions Pick).
type ProxyStreamOptions ¶
type ProxyStreamOptions struct {
ProxySerializableStreamOptions
// AuthToken is the auth token for the proxy server.
AuthToken string
// ProxyURL is the proxy server URL (e.g. "https://genai.example.com").
ProxyURL string
}
ProxyStreamOptions configures StreamProxy (pi: ProxyStreamOptions; pi's `signal?` member is absent — the local abort signal travels as the Go context parameter).
type QueueMode ¶
type QueueMode string
QueueMode controls how many queued user messages are injected when the agent loop reaches a queue drain point.
- "all": drain and inject every queued message at that point.
- "one-at-a-time": drain and inject only the oldest queued message, leaving the rest queued for later drain points.
type StreamFn ¶
type StreamFn func(ctx context.Context, model *types.Model, llmContext *types.TranscriptContext, options *types.SimpleStreamOptions) *types.AssistantMessageEventStream
StreamFn is the stream function used by the agent loop. `Models.StreamSimple` satisfies this shape.
Contract:
- Must not throw or return a rejected promise for request/model/runtime failures; Go encoding: must not panic on those either.
- Must return an AssistantMessageEventStream.
- Failures must be encoded in the returned stream via protocol events and a final AssistantMessage with stopReason "error" or "aborted" and errorMessage.
ctx carries the caller's cancellation (pi: signal travels through the options object); per the AbortSignal → context rule it is a parameter here.
func GetDefaultStreamFn ¶
GetDefaultStreamFn returns the configured fallback. pi throws when none is configured; Go returns an error instead.
type ThinkingLevel ¶
type ThinkingLevel = types.ModelThinkingLevel
ThinkingLevel is the thinking/reasoning level for models that support it. pi's agent re-declares the pi-ai union with "off" added; that exact union is types.ModelThinkingLevel in pig. Note: "xhigh" and "max" are only supported by selected model families. Use model thinking-level metadata from the ai package to detect support for a concrete model.
type ToolExecutionMode ¶
type ToolExecutionMode string
ToolExecutionMode configures how tool calls from a single assistant message are executed.
- "sequential": each tool call is prepared, executed, and finalized before the next one starts.
- "parallel": tool calls are prepared sequentially, then allowed tools execute concurrently. `tool_execution_end` is emitted in tool completion order after each tool is finalized, while tool-result message artifacts are emitted later in assistant source order.
const ( ToolExecutionSequential ToolExecutionMode = "sequential" ToolExecutionParallel ToolExecutionMode = "parallel" )
Directories
¶
| Path | Synopsis |
|---|---|
|
pi: harness/context.ts — telemetry-context propagation helpers.
|
pi: harness/context.ts — telemetry-context propagation helpers. |
|
agentharness
Package agentharness corresponds to pi's packages/agent/src/harness/agent-harness.ts.
|
Package agentharness corresponds to pi's packages/agent/src/harness/agent-harness.ts. |
|
compaction
pi: src/harness/compaction/branch-summarization.ts — summarization of abandoned session branches before navigation.
|
pi: src/harness/compaction/branch-summarization.ts — summarization of abandoned session branches before navigation. |
|
env
Package env corresponds to pi's packages/agent/src/harness/env.
|
Package env corresponds to pi's packages/agent/src/harness/env. |
|
reducer
Package reducer corresponds to pi's packages/agent/src/harness/reducer.ts — pure lane-state reconstruction and record-log validation over bounded recovery slices.
|
Package reducer corresponds to pi's packages/agent/src/harness/reducer.ts — pure lane-state reconstruction and record-log validation over bounded recovery slices. |
|
session
pi: harness/session/commit.ts — transaction write materialization and validation shared by every storage backend.
|
pi: harness/session/commit.ts — transaction write materialization and validation shared by every storage backend. |
|
session/jsonl
pi: harness/session/jsonl/codec.ts — header parsing/validation for both the current format-4 header and the legacy v3 session header.
|
pi: harness/session/jsonl/codec.ts — header parsing/validation for both the current format-4 header and the legacy v3 session header. |
|
session/testing
pi: harness/session/testing/conformance/session-repo.ts — SessionRepo conformance case groups (lifecycle, ownership, messages, forks, fork coordination).
|
pi: harness/session/testing/conformance/session-repo.ts — SessionRepo conformance case groups (lifecycle, ownership, messages, forks, fork coordination). |
|
tools
pi: src/harness/tools/bash.ts — the bash tool.
|
pi: src/harness/tools/bash.ts — the bash tool. |
|
utils
Package utils corresponds to pi's packages/agent/src/harness/utils.
|
Package utils corresponds to pi's packages/agent/src/harness/utils. |
|
Package search ports pi's packages/agent/src/search — the session search service contract.
|
Package search ports pi's packages/agent/src/search — the session search service contract. |