agent

package
v0.5.2 Latest Latest
Warning

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

Go to latest
Published: Oct 22, 2026 License: MIT Imports: 30 Imported by: 4

Documentation

Overview

Package agent provides the core agent loop and message types. Mirrors packages/agent of the pinned Pi release.

Ports packages/agent/src/types.ts.

Index

Constants

View Source
const (
	RoleUser       = "user"
	RoleAssistant  = "assistant"
	RoleToolResult = "toolResult"
	// Custom roles used by the coding agent layer.
	RoleBashExecution     = "bashExecution"
	RoleCustom            = "custom"
	RoleBranchSummary     = "branchSummary"
	RoleCompactionSummary = "compactionSummary"
)

Role constants mirror upstream.

Variables

View Source
var DefaultAgentIdentity = ai.ClientIdentity{Attribution: new(ai.PiAttribution)}

DefaultAgentIdentity is the request identity of agent loops: the ai package's defaults with provider attribution to PiG. The loop config's Identity overrides it field by field (agent-loop.ts DEFAULT_AGENT_IDENTITY).

View Source
var ErrAlreadyProcessing = errors.New("Agent is already processing.")

ErrAlreadyProcessing is returned when Continue or Reset is called while a run is active. Mirrors upstream Agent.continue and Agent.reset.

View Source
var ErrAlreadyProcessingPrompt = errors.New("Agent is already processing a prompt. Use steer() or followUp() to queue messages, or wait for completion.")

ErrAlreadyProcessingPrompt is returned when a prompt is sent while a run is active. Mirrors upstream Agent.prompt's "Agent is already processing a prompt" error: queue the message with Steer or FollowUp instead.

View Source
var ErrMaxTurnsReached = errors.New("agent stopped at its turn limit with tool results still unanswered")

ErrMaxTurnsReached reports that a run stopped at AgentOptions.MaxTurns with tool results still waiting for a model response.

View Source
var ErrNoDefaultStreamFunction = errors.New("No default stream function configured. Pass streamFn explicitly or call setDefaultStreamFn().")

ErrNoDefaultStreamFunction is Pi's getDefaultStreamFn failure: no stream function was passed and none is configured.

View Source
var ErrNoMessagesToContinue = errors.New("No messages to continue from")

ErrNoMessagesToContinue is returned by Continue on an empty transcript. Mirrors upstream Agent.continue's "No messages to continue from".

View Source
var ErrNoModelSelected = errors.New("no model selected")

ErrNoModelSelected is returned when a turn is requested with no usable model. Upstream agent-session.prompt() throws formatNoModelSelectedMessage() before streaming; pig surfaces the same condition as an error rather than panicking on a nil model in runLoop.

View Source
var ErrToolResultsUnanswered = errors.New("agent run ended after tool results without a model response")

ErrToolResultsUnanswered reports that a run ended with tool results the model never answered although no tool asked to terminate the run. It guards the invariant that a run never ends silently mid-task.

Functions

func BranchSummaryContextText

func BranchSummaryContextText(summary string) string

BranchSummaryContextText wraps a branch summary for LLM context. Mirrors upstream BRANCH_SUMMARY_PREFIX + summary + BRANCH_SUMMARY_SUFFIX from packages/coding-agent/src/core/messages.ts.

func CalculateContextTokens

func CalculateContextTokens(usage ai.Usage) int

CalculateContextTokens computes context tokens from usage stats. Mirrors upstream calculateContextTokens (compaction.ts:135): prefer the provider-reported total, else sum the components.

func CompactionSummaryContextText

func CompactionSummaryContextText(summary string) string

CompactionSummaryContextText wraps a compaction summary for LLM context. Mirrors upstream COMPACTION_SUMMARY_PREFIX + summary + COMPACTION_SUMMARY_SUFFIX from packages/coding-agent/src/core/messages.ts.

func ConvertToLLM

func ConvertToLLM(msgs []AgentMessage) []ai.Message

ConvertToLLM converts AgentMessages to the wire format expected by the AI provider (convertToLlm, messages.ts:148). Like upstream it only converts: the agent loop passes the result to the stream function as it is, and a provider filters errored/aborted assistant messages and closes orphaned tool calls itself (transformMessages).

func EstimateTokens

func EstimateTokens(msg AgentMessage) int

EstimateTokens estimates the token count for a single message using a chars/4 heuristic covering all roles. Mirrors upstream estimateTokens (compaction.ts:232).

func EventObservation

func EventObservation(event AgentEvent) *ai.StreamObservation

EventObservation returns the attached stream scope for synchronous host dispatch. Session transfers that scope before notifying its synchronous subscribers; it is not message data or wire metadata.

func SetDefaultStreamFn

func SetDefaultStreamFn(fn StreamFn)

SetDefaultStreamFn configures the stream used by newly constructed agents when their caller omits StreamFn. Nil removes the configured fallback.

func StreamProxy

func StreamProxy(ctx context.Context, model *ai.Model, transcript ai.TranscriptContext, options ProxyStreamOptions) *ai.AssistantMessageEventStream

StreamProxy streams through a server that manages provider authentication. Each toolcall_start replaces the indexed tool and its accumulated JSON. It returns immediately; request, protocol, and cancellation failures are delivered as terminal error events.

func SystemReplayError

func SystemReplayError(messages []AgentMessage) error

SystemReplayError returns the TypeError Pi's getCurrentSystemMessage throws while it replays messages, or nil. Pi parses a session without validation, so a system message read from a session can hold a content, toolsAdded or toolsRemoved member of a JSON type the replay cannot read. The replay first renders the content of every system message (pi-ai utils/transcript.ts getCurrentSystemMessage, utils/text.ts contentText) and then applies their tool lists (getCurrentTools), so a content error comes before any tool list error. Only a message decoded from such text can hold one; its retained source keeps the member as it was read.

func ToolBatchFromContext

func ToolBatchFromContext(ctx context.Context, toolCallID string) string

ToolBatchFromContext returns the identifier of the parallel batch the call toolCallID belongs to, "" for a call outside one (a sequential batch, or a call another tool makes inside its own). It is the same for every call of a batch and differs between batches. A runtime that executes the batch's calls on threads of its own uses it to order only the calls of one batch, as Pi's single thread orders them.

func ToolHookStartedFromContext

func ToolHookStartedFromContext(ctx context.Context) func()

ToolHookStartedFromContext returns the function a call's after-tool-call hooks call once their first extension handler has been invoked, or nil for a call outside a parallel batch. Calling it lets the batch start the hooks of the calls that settled after this one (agent-loop.ts:619-647: the hooks start in settle order and each runs to its first await before the next starts). It is idempotent, and the batch calls it when the hooks return.

func ToolReplayError

func ToolReplayError(messages []AgentMessage) error

ToolReplayError returns the TypeError Pi's _restoreToolsFromTranscript throws for the system messages of a whole branch, or nil. It first collects the tools the branch ever added or removed, `systemMessages.flatMap((message) => [...(message.toolsAdded ?? []), ...(message.toolsRemoved ?? [])]).map((tool) => tool.name)`, and then replays them with getCurrentTools; every member getCurrentTools cannot read fails in the first step, so only the first step's errors are reported. Unlike SystemReplayError it never reads a message's content. A spread of a value that is not iterable, in any message, throws before any element's name is read, a message's added list before its removed list; a string spreads into characters that have no name.

func ToolSettleFromContext

func ToolSettleFromContext(ctx context.Context, toolCallID string) *jsloop.SettleSlot

ToolSettleFromContext returns the slot of the call toolCallID of a parallel batch. A tool whose result arrives from outside this process settles it from the goroutine that reads the result, so the batch emits the calls' tool_execution_end events in the order the results arrived (agent-loop.ts executeToolCallsParallel: each call's end follows its own settle). A tool that never settles it settles it when its Execute returns. The slot belongs to one call: a call another tool makes inside its own (a different toolCallID) gets none.

func ToolUpdatesObserved

func ToolUpdatesObserved(ctx context.Context, onUpdate ToolUpdateCallback) bool

ToolUpdatesObserved reports whether anything could see an update the tool sends to onUpdate now: false for a nil callback, and for the loop's callback while no agent listener, Agent option, session listener, Events consumer or extension tool_execution_update handler is there to see one. Every other callback is observed. A tool that skips its update work while this is false asks again as it runs, so an observer that appears during the execution gets the updates from then on, as a Pi listener added mid-execution sees the updates emitted after it subscribed.

func WithMutationTicket

func WithMutationTicket(ctx context.Context, ticket *MutationTicket) context.Context

WithMutationTicket returns ctx carrying a reservation for the tool call it is passed into. Execute implementations that also implement QueueOrderable must check MutationTicketFromContext and honor an existing reservation instead of registering a second time.

func WithToolCallHookContext

func WithToolCallHookContext(ctx context.Context, hookContext ToolCallHookContext) context.Context

WithToolCallHookContext returns ctx carrying the hook context.

func WithToolEnvironment

func WithToolEnvironment(ctx context.Context, env ToolEnvironment) context.Context

WithToolEnvironment returns ctx carrying env for the tools it executes.

Types

type AfterToolCallContext

type AfterToolCallContext struct {
	AssistantMessage *AssistantMessage
	ToolCall         ai.ToolCall
	Args             json.RawMessage
	// Result is the executed tool result before any afterToolCall override.
	Result AgentToolResult
	// IsError is whether the executed result is treated as an error.
	IsError bool
	Context AgentContext
}

AfterToolCallContext is the context of an afterToolCall hook (upstream types.ts AfterToolCallContext).

type AfterToolCallFunc

type AfterToolCallFunc func(ctx context.Context, call AfterToolCallContext) *AfterToolCallResult

AfterToolCallFunc is Pi's single afterToolCall property: it runs after the tool executed and before the result is finalized, in front of the Go hook list, and may override parts of the result. A nil result keeps it. The context.Context is Pi's signal.

upstream: packages/agent/src/types.ts AgentLoopConfig.afterToolCall, agent-loop.ts:860-895

type AfterToolCallHook

type AfterToolCallHook func(ctx context.Context, toolCallID, toolName string, args json.RawMessage, result AgentToolResult) AfterToolCallResult

AfterToolCallHook is called after a tool executes and may override its result. Full upstream contract, including terminate signals and result overrides. Replaces the old void-return signature which had no override capability. upstream: agent-loop.ts afterToolCall({ toolCall, args, result, isError })

type AfterToolCallResult

type AfterToolCallResult struct {
	Content   []ai.ToolResultMessageContent
	Details   any
	IsError   *bool // nil = keep original
	Usage     *ai.Usage
	Terminate *bool
	// StructuredContent replaces the result's structured content. When Content is replaced without it, the structured content is dropped, because it may no longer match the content.
	StructuredContent json.RawMessage
}

AfterToolCallResult carries per-tool overrides returned by AfterToolCallHook. Mirrors upstream types.ts AfterToolCallResult (agent-loop.ts:617-640). Merge semantics: field-by-field replace; no deep merge. Nil fields keep the original; a non-nil empty Content replaces it with an empty array.

  • Content: if non-nil, replaces the ordered content, including an empty array.
  • 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. The agent stops after the batch only when every finalized result terminates (upstream shouldTerminateToolBatch).

type Agent

type Agent struct {
	// BeforeToolCall and AfterToolCall are Pi's public hook properties (agent.ts:201-207). They start as the options' functions and may be assigned between runs; a run reads them when it starts.
	BeforeToolCall BeforeToolCallFunc
	AfterToolCall  AfterToolCallFunc
	// contains filtered or unexported fields
}

Agent is the agent loop.

Mirrors upstream packages/agent/src/agent.ts (class Agent).

func NewAgent

func NewAgent(opts AgentOptions) (*Agent, error)

NewAgent creates a new Agent. Like Pi's constructor (`streamFn ?? getDefaultStreamFn()`), it fails with ErrNoDefaultStreamFunction when the options carry no stream function and no host default is configured; a model's own Provider does not stand in for one.

func (*Agent) Abort

func (a *Agent) Abort()

Abort cancels the active run. Calling Abort on an idle agent does nothing.

func (*Agent) AddAfterToolCallHook

func (a *Agent) AddAfterToolCallHook(h AfterToolCallHook)

AddAfterToolCallHook appends a hook that fires after each tool execution. Mirrors upstream agent.afterToolCall assignment (agent-session.ts:396).

func (*Agent) AddBeforeToolCallHook

func (a *Agent) AddBeforeToolCallHook(h BeforeToolCallHook)

AddBeforeToolCallHook appends a hook that fires before each tool execution. Mirrors upstream agent.beforeToolCall assignment (agent-session.ts:373).

func (*Agent) BeginSendContent

func (a *Agent) BeginSendContent(ctx context.Context, content []ai.UserContentBlock) (*PromptRun, error)

BeginSendContent claims the agent and binds its cancellation context synchronously without starting events. Pending preflight is not an active run; a claimed prompt is active before its first awaited listener finishes.

func (*Agent) BeginSendMessages

func (a *Agent) BeginSendMessages(ctx context.Context, messages []AgentMessage) (*PromptRun, error)

BeginSendMessages claims a turn for already-built messages without starting events. The owner calls Run exactly once, even if Start fails, just as for BeginSendContent.

func (*Agent) ClearAllQueues

func (a *Agent) ClearAllQueues()

ClearAllQueues removes all queued steering and follow-up messages. Mirrors upstream agent.ts clearAllQueues, which returns nothing.

func (*Agent) ClearFollowUpQueue

func (a *Agent) ClearFollowUpQueue()

ClearFollowUpQueue removes all queued follow-up messages. Mirrors upstream agent.ts clearFollowUpQueue, which returns nothing.

func (*Agent) ClearQueuedUserMessages

func (a *Agent) ClearQueuedUserMessages()

ClearQueuedUserMessages removes the queued user messages from both queues and leaves queued custom messages in place. pig divergence (D135): upstream clearAllQueues also destroys custom messages that nothing reports back to the caller.

func (*Agent) ClearSteeringQueue

func (a *Agent) ClearSteeringQueue()

ClearSteeringQueue removes all queued steering messages. Mirrors upstream agent.ts clearSteeringQueue, which returns nothing.

func (*Agent) ClearSystemPrompt

func (a *Agent) ClearSystemPrompt()

ClearSystemPrompt removes a SetSystemPrompt projection, so later requests use the transcript's own system prompt again.

func (*Agent) Continue

func (a *Agent) Continue(ctx context.Context) error

Continue is Pi's agent.continue() (agent.ts:384): it continues from the current transcript and returns nothing but the error. ContinueMessages returns the produced messages as well.

func (*Agent) ContinueMessages

func (a *Agent) ContinueMessages(ctx context.Context) ([]AgentMessage, error)

ContinueMessages runs the agent loop from the current message state without prepending a new user message and returns the messages the run produced. Used to retry a turn after auto-compaction when an overflow error is recovered by compacting and replaying. Continue is the same run in Pi's shape.

If the last message is an assistant message, ContinueMessages first checks the steering queue, then the follow-up queue. Without queued input it rejects the assistant tail. Mirrors upstream Agent.continue (packages/agent/src/agent.ts).

func (*Agent) ConvertToLlm

func (a *Agent) ConvertToLlm() func([]AgentMessage) ([]ai.Message, error)

ConvertToLlm returns the converter from agent messages to provider messages, or nil for the standard conversion. Mirrors upstream Agent.convertToLlm (agent.ts:155).

func (*Agent) CurrentSystemMessageError

func (a *Agent) CurrentSystemMessageError() error

CurrentSystemMessageError returns the TypeError Pi's getCurrentSystemMessage throws while it replays the agent's history, or nil (see SystemReplayError). It reads the history under the lock a run appends under, without copying it.

func (*Agent) EffectiveStreamFunction

func (a *Agent) EffectiveStreamFunction() StreamFn

EffectiveStreamFunction returns the function every run sends provider requests through: the caller's override, else the default stream. Mirrors upstream Agent.streamFunction (`runtimeOptions.streamFn ?? getDefaultStreamFn()`), which summarization passes to compact and generateBranchSummary so those requests take the same request path as the agent's. Unlike Agent.StreamFunction, it is never the nil that stands for the stock stream.

func (*Agent) ErrorMessage

func (a *Agent) ErrorMessage() string

ErrorMessage returns the last failed turn's error, cleared at the next run or reset.

func (*Agent) FinishTurnHook

func (a *Agent) FinishTurnHook() FinishTurn

FinishTurnHook returns the current FinishTurn hook, or nil.

func (*Agent) FollowUp

func (a *Agent) FollowUp(msg AgentMessage)

FollowUp enqueues a follow-up message. Follow-up messages are delivered only after the agent has no more tool calls AND no steering messages, starting a fresh outer-loop iteration.

func (*Agent) FollowUpMode

func (a *Agent) FollowUpMode() QueueMode

FollowUpMode returns the current follow-up drain policy.

func (*Agent) GetAPIKeyFunc

func (a *Agent) GetAPIKeyFunc() func(provider string) (string, error)

GetAPIKeyFunc returns the credential resolver the next run uses, or nil. Mirrors upstream Agent.getApiKey.

func (*Agent) HasPendingMessages

func (a *Agent) HasPendingMessages() bool

HasPendingMessages reports whether either queue has messages.

func (*Agent) HasQueuedMessages

func (a *Agent) HasQueuedMessages() bool

HasQueuedMessages reports whether either queue still contains pending messages. Mirrors upstream agent.ts:290.

func (*Agent) Identity

func (a *Agent) Identity() *ai.ClientIdentity

Identity returns the request identity merged over DefaultAgentIdentity, or nil. Mirrors upstream Agent.identity.

func (*Agent) IsStreaming

func (a *Agent) IsStreaming() bool

IsStreaming returns true when the agent is actively in a Send/Continue loop. Mirrors upstream AgentState.isStreaming for extension queries.

func (*Agent) MaxRetryDelayMs

func (a *Agent) MaxRetryDelayMs() *int

MaxRetryDelayMs returns the cap on provider-requested retry delays, or nil. Mirrors upstream Agent.maxRetryDelayMs (agent.ts:189).

func (*Agent) Messages

func (a *Agent) Messages() []AgentMessage

Messages returns the current message history.

func (*Agent) MessagesSnapshot

func (a *Agent) MessagesSnapshot() []AgentMessage

MessagesSnapshot copies the message history. Unlike Messages it is safe to call from any goroutine while a run appends.

func (*Agent) Model

func (a *Agent) Model() *ai.Model

Model returns the active model. New agents use the upstream unknown descriptor until one is selected; SetModel(nil) clears it.

func (*Agent) ObserveRunSignal

func (a *Agent) ObserveRunSignal(observe func()) func()

ObserveRunSignal registers observe to run after a run claims the agent, when Signal already returns the run's context, and after the run releases it, when Signal already returns nil. Pi's `agent.signal` is a getter (agent.ts:336-338), so an owner that replicates the signal elsewhere learns of both instants here. observe runs on the goroutine that changes the run, after the agent's lock is released, so it may call Signal; the run waits for observe to return. The returned function removes the observer and can be called repeatedly.

func (*Agent) OnProviderStreamEvent

func (a *Agent) OnProviderStreamEvent() func(ctx context.Context, data any, model *ai.Model) error

OnProviderStreamEvent returns the observer forwarded to every provider request. Mirrors upstream Agent.onProviderStreamEvent (agent.ts:161).

func (*Agent) OnResponse

func (a *Agent) OnResponse() func(context.Context, ai.ProviderResponse, *ai.Model) error

OnResponse returns the hook that runs once per provider response before its body is consumed. Mirrors upstream Agent.onResponse (agent.ts:160).

func (*Agent) PeekQueuedMessages

func (a *Agent) PeekQueuedMessages() []AgentMessage

PeekQueuedMessages previews the messages selected for the next turn without consuming them: the steering queue's selection, or the follow-up queue's when no steering is queued. Mirrors upstream Agent.peekQueuedMessages.

func (*Agent) PendingMessages

func (a *Agent) PendingMessages() (steering, followUp []AgentMessage)

PendingMessages returns a snapshot of both queues without draining. Used for UI display (e.g. "2 steering, 1 follow-up pending").

func (*Agent) PendingToolCalls

func (a *Agent) PendingToolCalls() []string

PendingToolCalls returns the active tool call IDs in start order.

func (*Agent) PrepareNextTurnHook

func (a *Agent) PrepareNextTurnHook() func(ctx context.Context) (*AgentLoopTurnUpdate, error)

PrepareNextTurnHook returns the current context-only PrepareNextTurn hook, or nil.

func (*Agent) PrepareNextTurnWithContextHook

func (a *Agent) PrepareNextTurnWithContextHook() PrepareNextTurn

PrepareNextTurnWithContextHook returns the current PrepareNextTurnWithContext hook, or nil.

func (*Agent) PreparePromptHook

func (a *Agent) PreparePromptHook() func(context.Context, []AgentMessage) ([]AgentMessage, error)

PreparePromptHook returns the current prompt-preparation hook, or nil.

func (*Agent) PrepareRequestHook

func (a *Agent) PrepareRequestHook() PrepareRequest

PrepareRequestHook returns the current PrepareRequest hook, or nil.

func (*Agent) PrepareToolResultHook

func (a *Agent) PrepareToolResultHook() func(context.Context, AgentToolResult) AgentToolResult

PrepareToolResultHook returns the current tool-result hook, or nil.

func (*Agent) Prompt

func (a *Agent) Prompt(ctx context.Context, input string, images ...ai.ImageContent) error

Prompt is Pi's agent.prompt(input, images?) (agent.ts:372): it starts a run from a user message made of the text and the images and returns when the run settles. Pi's method resolves to nothing; the produced messages are the transcript's new tail, which Send returns to a caller that wants them.

Like Pi, it fails when a run is already active.

func (*Agent) PromptMessages

func (a *Agent) PromptMessages(ctx context.Context, messages []AgentMessage) error

PromptMessages is Pi's agent.prompt(message | message[]) overload (agent.ts:371): it starts a run from the given messages. Like Pi's prompt([]) (agent.ts:371-379), an empty batch still claims the agent and runs a turn from the current transcript; SendMessages instead returns without a run.

func (*Agent) QueueNextTurn

func (a *Agent) QueueNextTurn(msg AgentMessage)

QueueNextTurn defers a message to the start of the next user turn, where it is injected beside the user message as context for the first model call.

This is not FollowUp. A follow-up continues the turn that is running, so it reaches the model only after the current response completes; a message meant to inform the next prompt would arrive a model call too late, and on an idle agent it would sit in a queue with no goroutine to drain it.

func (*Agent) Reset

func (a *Agent) Reset() error

Reset retains the replayed system baseline and clears conversation state and queues. It refuses while a run is active, as upstream Agent.reset throws. Mirrors upstream Agent.reset.

func (*Agent) Send

func (a *Agent) Send(ctx context.Context, content string) ([]AgentMessage, error)

Send sends a plain-text user message and runs the agent loop until the LLM stops calling tools. Steering and follow-up messages queued via Steer/FollowUp are polled at the appropriate points in the loop.

func (*Agent) SendContent

func (a *Agent) SendContent(ctx context.Context, content []ai.UserContentBlock) ([]AgentMessage, error)

SendContent is the structured-content variant of Send.

func (*Agent) SendMessages

func (a *Agent) SendMessages(ctx context.Context, msgs []AgentMessage) ([]AgentMessage, error)

SendMessages seeds a turn with already-built messages instead of a user prompt, mirroring upstream agent.prompt(messages) (agent-session.ts:1063). An extension delivering a custom message while the agent is idle needs a turn to start from that message; without this the message can only be enqueued for a turn that may never run.

func (*Agent) SessionID

func (a *Agent) SessionID() string

SessionID returns the session identifier forwarded to providers. Mirrors upstream Agent.sessionId (agent.ts:183).

func (*Agent) SetBeforeProviderHook

func (a *Agent) SetBeforeProviderHook(fn func(payload any, model *ai.Model) (any, error))

SetBeforeProviderHook transforms each provider's final wire payload. It is the assignment of Pi's public Agent.onPayload (agent.ts:198): a run captures the hook when it starts (createLoopConfig, agent.ts:473), so an assignment during a run takes effect on the next run.

func (*Agent) SetConvertToLlm

func (a *Agent) SetConvertToLlm(convert func([]AgentMessage) ([]ai.Message, error))

SetConvertToLlm replaces the converter from agent messages to provider messages for future runs; nil restores the standard conversion.

func (*Agent) SetFinishTurn

func (a *Agent) SetFinishTurn(fn FinishTurn)

SetFinishTurn replaces the FinishTurn hook for later runs. Mirrors assigning upstream's public Agent.finishTurn; FinishTurnHook returns the current one so a caller can chain it.

func (*Agent) SetFollowUpMode

func (a *Agent) SetFollowUpMode(mode QueueMode)

SetFollowUpMode changes the follow-up queue's drain policy.

func (*Agent) SetGetAPIKey

func (a *Agent) SetGetAPIKey(fn func(provider string) (string, error))

SetGetAPIKey replaces the credential resolver for subsequent runs; nil removes it. Mirrors assigning upstream Agent.getApiKey, which each run reads when it starts.

func (*Agent) SetIdentity

func (a *Agent) SetIdentity(identity *ai.ClientIdentity)

SetIdentity replaces the request identity for future runs; nil leaves DefaultAgentIdentity alone.

func (*Agent) SetLoopTurns

func (a *Agent) SetLoopTurns(turns *jsloop.Turns)

SetLoopTurns gives the agent the owner's model of Pi's event loop. The runs that start afterwards tell it when real work completes (a model response's I/O) and when a tool runs, so the owner can run the timer callbacks Pi's loop would run then. Pass nil to remove it.

func (*Agent) SetMaxRetryDelayMs

func (a *Agent) SetMaxRetryDelayMs(maxRetryDelayMs *int)

SetMaxRetryDelayMs replaces the cap on provider-requested retry delays for future runs; nil keeps each provider's default.

func (*Agent) SetMessages

func (a *Agent) SetMessages(msgs []AgentMessage)

SetMessages replaces the message history (used for session restore). The agent keeps a copy of the top-level slice, as upstream's state.messages setter copies the assigned array.

func (*Agent) SetModel

func (a *Agent) SetModel(m *ai.Model)

SetModel swaps the active LLM model. The next run uses the new provider/model; a run in flight keeps the model it started with (agent.ts:471). The agent's tools, system prompt, and message history are unchanged. Mid-session model switch.

func (*Agent) SetOnProviderStreamEvent

func (a *Agent) SetOnProviderStreamEvent(observe func(ctx context.Context, data any, model *ai.Model) error)

SetOnProviderStreamEvent replaces the provider stream event observer for future runs.

func (*Agent) SetOnResponse

func (a *Agent) SetOnResponse(hook func(context.Context, ai.ProviderResponse, *ai.Model) error)

SetOnResponse replaces the provider response hook for future runs.

func (*Agent) SetPrepareNextTurn

func (a *Agent) SetPrepareNextTurn(fn func(ctx context.Context) (*AgentLoopTurnUpdate, error))

SetPrepareNextTurn replaces the context-only PrepareNextTurn hook for later runs. Mirrors assigning upstream's public Agent.prepareNextTurn.

func (*Agent) SetPrepareNextTurnWithContext

func (a *Agent) SetPrepareNextTurnWithContext(fn PrepareNextTurn)

SetPrepareNextTurnWithContext replaces the PrepareNextTurnWithContext hook for later runs. Mirrors assigning upstream's public Agent.prepareNextTurnWithContext.

func (*Agent) SetPreparePrompt

func (a *Agent) SetPreparePrompt(fn func(context.Context, []AgentMessage) ([]AgentMessage, error))

SetPreparePrompt replaces the hook that prepares new prompt messages before a run starts, for later runs. It is the Go counterpart of the prompt preparation an owning Session installs (agent-session.ts _installAgentForcedPromptProjection); PreparePromptHook returns the current one so a caller can chain it.

func (*Agent) SetPrepareRequest

func (a *Agent) SetPrepareRequest(fn PrepareRequest)

SetPrepareRequest replaces the PrepareRequest hook for later runs. Mirrors assigning upstream's public Agent.prepareRequest.

func (*Agent) SetPrepareToolResult

func (a *Agent) SetPrepareToolResult(fn func(context.Context, AgentToolResult) AgentToolResult)

SetPrepareToolResult replaces the hook that processes each final extension-modified tool result, for later runs.

func (*Agent) SetSessionFile

func (a *Agent) SetSessionFile(fn func() string)

SetSessionFile replaces the function that reports the session file tools may expose, for later runs.

func (*Agent) SetSessionID

func (a *Agent) SetSessionID(id string)

SetSessionID updates the session ID used for prompt caching. Called after session creation/resume when the stable session ID is known.

func (*Agent) SetSteeringMode

func (a *Agent) SetSteeringMode(mode QueueMode)

SetSteeringMode changes the steering queue's drain policy.

func (*Agent) SetStreamFunction

func (a *Agent) SetStreamFunction(streamFn StreamFn)

SetStreamFunction replaces the provider request function for subsequent runs: a run reads it once when it starts (agent.ts:443,455), matching Agent.streamFunction assignment in Pi. Nil restores the stock stream.

func (*Agent) SetSystemPrompt

func (a *Agent) SetSystemPrompt(prompt string)

SetSystemPrompt projects a replacement system prompt onto subsequent provider requests without rewriting transcript history.

func (*Agent) SetThinkingBudgets

func (a *Agent) SetThinkingBudgets(budgets *ai.ThinkingBudgets)

SetThinkingBudgets replaces the per-level thinking token budgets for future runs.

func (*Agent) SetThinkingLevel

func (a *Agent) SetThinkingLevel(level ai.ModelThinkingLevel)

SetThinkingLevel updates the reasoning depth used for future Send calls. Wired by InteractiveMode.cycleThinkingLevel() on Shift+Tab. The current in-flight call (if any) is unaffected; the new level applies starting with the next agent.Send invocation.

func (*Agent) SetToolExecution

func (a *Agent) SetToolExecution(mode ToolExecutionMode)

SetToolExecution replaces the batch strategy for assistant messages with several tool calls, for future runs. Mirrors assigning upstream Agent.toolExecution (agent.ts:191).

func (*Agent) SetTools

func (a *Agent) SetTools(tools []AgentTool)

SetTools replaces the active tool list for subsequent turns.

func (*Agent) SetTransformContext

func (a *Agent) SetTransformContext(fn func(msgs []AgentMessage) []AgentMessage)

SetTransformContext sets a hook that fires before each LLM call to allow extensions to modify the message context. Mirrors assigning upstream Agent.transformContext (agent.ts:494): a run reads it once when it starts, so an assignment during a run applies to the next one.

func (*Agent) SetTransformContextWithContext

func (a *Agent) SetTransformContextWithContext(fn func(context.Context, []AgentMessage) ([]AgentMessage, error))

SetTransformContextWithContext installs a request transform with cancellation and error propagation owned by the active agent run.

func (*Agent) SetTransformHeaders

func (a *Agent) SetTransformHeaders(fn func(context.Context, ai.ProviderHeaders) (ai.ProviderHeaders, error))

SetTransformHeaders sets the hook that rewrites each provider request's merged HTTP headers. Mirrors upstream StreamOptions.transformHeaders.

func (*Agent) SetTransformLLMMessages

func (a *Agent) SetTransformLLMMessages(fn func([]ai.Message) []ai.Message)

SetTransformLLMMessages replaces the hook that post-processes the provider messages before each request, for later runs. TransformLLMMessagesHook returns the current one so a caller can chain it, as agent-session.ts _installHiddenDeclarationsProjection chains transformContext.

func (*Agent) SetTransport

func (a *Agent) SetTransport(transport ai.Transport)

SetTransport updates the preferred provider transport for future Send calls.

func (*Agent) Signal

func (a *Agent) Signal() context.Context

Signal returns the active run's cancellation context, or nil when idle.

func (*Agent) State

func (a *Agent) State() AgentState

State returns the live state view (upstream agent.state).

func (*Agent) Steer

func (a *Agent) Steer(msg AgentMessage)

Steer enqueues a steering message. Steering messages are delivered after the current tool batch finishes but before the next LLM call, allowing the user to redirect the agent mid-turn.

func (*Agent) SteeringMode

func (a *Agent) SteeringMode() QueueMode

SteeringMode returns the current steering drain policy.

func (*Agent) StreamFunction

func (a *Agent) StreamFunction() StreamFn

Ports packages/agent/src/agent.ts StreamFunction returns the caller's stream override. Nil denotes the stock stream, allowing summarization to distinguish optional custom-stream auth from required stock auth without comparing Go function values.

func (*Agent) StreamingMessage

func (a *Agent) StreamingMessage() *AgentMessage

StreamingMessage returns a snapshot of the message currently streaming.

func (*Agent) Subscribe

func (a *Agent) Subscribe(listener func(context.Context, AgentEvent) error) func()

Subscribe registers a lifecycle listener. Listeners run in subscription order with the active run context; the run waits for each callback to return. The returned function removes this subscription and can be called repeatedly.

func (*Agent) SubscribeObserving

func (a *Agent) SubscribeObserving(listener func(context.Context, AgentEvent) error, observesToolUpdates func() bool) func()

SubscribeObserving is Subscribe for a listener that can say whether it currently does anything with a tool_execution_update event. observesToolUpdates is asked when a tool execution starts and again while it runs (ToolUpdatesObserved); nil means the listener always may. The listener still receives every event.

func (*Agent) SubscribeObservingUpdates

func (a *Agent) SubscribeObservingUpdates(listener func(context.Context, AgentEvent) error, observesToolUpdates, observesMessageUpdates func() bool) func()

SubscribeObservingUpdates is SubscribeObserving for a listener that can also say whether it currently does anything with a message_update event. observesMessageUpdates is asked for every message_update; nil means the listener always may. While neither it nor anything else the Agent delivers events to may observe one (messageUpdatesObserved), the update is not delivered at all: no listener runs for it and the run does not await it. Once one may, every later update reaches every listener as before.

func (*Agent) SystemPrompt

func (a *Agent) SystemPrompt() string

SystemPrompt returns the current replayed instructions or an explicit provider prompt override. It is safe to call while the agent appends messages.

func (*Agent) SystemPromptOverride

func (a *Agent) SystemPromptOverride() (string, bool)

SystemPromptOverride returns only the explicit provider projection and its presence, not replayed transcript instructions.

func (*Agent) SystemPromptSnapshot

func (a *Agent) SystemPromptSnapshot() (string, bool)

SystemPromptSnapshot reads the prompt and whether it is present under one lock. Presence distinguishes an empty projected prompt from an uninitialized transcript.

func (*Agent) TakePendingNextTurn

func (a *Agent) TakePendingNextTurn() []AgentMessage

TakePendingNextTurn removes and returns the messages QueueNextTurn deferred. A run that starts from built messages delivers them beside its starting message (agent-session.ts:1918-1920 _prepareRun).

func (*Agent) ThinkingBudgets

func (a *Agent) ThinkingBudgets() *ai.ThinkingBudgets

ThinkingBudgets returns the per-level thinking token budgets forwarded to the stream function, or nil. Mirrors upstream Agent.thinkingBudgets (agent.ts:185).

func (*Agent) ThinkingLevel

func (a *Agent) ThinkingLevel() ai.ModelThinkingLevel

ThinkingLevel returns the reasoning depth used for future Send calls.

func (*Agent) Timings

func (a *Agent) Timings() *Recorder

Timings returns the agent's timing recorder. Read-only consumers (status line, /cost, --diagnose) hold this reference for the session's lifetime and call Snapshot()/Elapsed() on demand.

func (*Agent) ToolExecutionMode

func (a *Agent) ToolExecutionMode() ToolExecutionMode

ToolExecutionMode returns the batch strategy for assistant messages with several tool calls. Mirrors upstream Agent.toolExecution.

func (*Agent) Tools

func (a *Agent) Tools() []AgentTool

Tools returns the agent's current tool list. Defensive copy.

func (*Agent) TransformLLMMessagesHook

func (a *Agent) TransformLLMMessagesHook() func([]ai.Message) []ai.Message

TransformLLMMessagesHook returns the current provider-message hook, or nil.

func (*Agent) Transport

func (a *Agent) Transport() ai.Transport

Transport returns the preferred provider transport. Mirrors upstream Agent.transport (agent.ts:187).

func (*Agent) WaitForIdle

func (a *Agent) WaitForIdle()

WaitForIdle waits for the current run and its synchronous listeners to settle. It returns immediately when no run is active.

type AgentContext

type AgentContext struct {
	Messages []AgentMessage
	Tools    []AgentTool
}

AgentContext is the state a standalone loop starts from. Mirrors upstream AgentContext (types.ts): the transcript visible to the model and the tools available in the run.

type AgentEndEvent

type AgentEndEvent struct {
	Messages  []AgentMessage
	WillRetry bool
}

type AgentEvent

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

AgentEvent is emitted by the agent loop to notify observers.

func RefreshEvent

func RefreshEvent(event AgentEvent) AgentEvent

RefreshEvent returns the message event with the assistant message's and the provider event's partial fields set to the stream state at this call. A host dispatcher calls it when it delivers a retained event to a listener after an awaited step. An event whose message and partial already hold that state (the stream published nothing since they were taken), and other events, are returned unchanged.

func WithEventObservation

func WithEventObservation(event AgentEvent, observation *ai.StreamObservation) AgentEvent

WithEventObservation carries a stream scope across synchronous host dispatch without changing message identity or serialized fields. Events outside the message lifecycle are unchanged.

type AgentEventSink

type AgentEventSink func(AgentEvent) error

AgentEventSink receives every event of a standalone run in order and returns before the loop continues, as upstream awaits its sink. An error stops the run and is returned from it. Mirrors upstream AgentEventSink.

type AgentEventStream

type AgentEventStream = ai.EventStream[AgentEvent, []AgentMessage]

AgentEventStream is the EventStream upstream agentLoop returns (EventStream<AgentEvent, AgentMessage[]>, agent-loop.ts:153-157): the events of a standalone run in order, buffered without bound until read. The agent_end event completes it, so Result resolves with that event's messages whether or not anyone reads the events.

func AgentLoop

func AgentLoop(ctx context.Context, prompts []AgentMessage, agentContext AgentContext, config AgentLoopConfig, streamFn StreamFn) *AgentEventStream

AgentLoop is RunAgentLoop with the events delivered through a stream. The run proceeds on its own goroutine, which ends with the run; cancel ctx to stop it. Mirrors upstream agentLoop.

func AgentLoopContinue

func AgentLoopContinue(ctx context.Context, agentContext AgentContext, config AgentLoopConfig, streamFn StreamFn) (*AgentEventStream, error)

AgentLoopContinue is RunAgentLoopContinue with the events delivered through a stream. It rejects an empty context and a context that ends with an assistant message before starting. Mirrors upstream agentLoopContinue.

type AgentInitialState

type AgentInitialState struct {
	// SystemPrompt seeds the leading system message when Messages does not start with one.
	SystemPrompt  string
	Model         *ai.Model
	ThinkingLevel ai.ModelThinkingLevel
	Tools         []AgentTool
	// Messages is the starting transcript; it is copied.
	Messages []AgentMessage
}

AgentOptions configures the agent loop. AgentInitialState seeds a new agent's state. A field that is set takes the place of the same-named AgentOptions field.

upstream: packages/agent/src/agent.ts:115 (AgentOptions.initialState: Partial<Omit<AgentState, "pendingToolCalls" | "isStreaming" | ...>>)

type AgentLoopConfig

type AgentLoopConfig struct {
	Model *ai.Model
	// StreamOptions are the base request options upstream AgentLoopConfig inherits from SimpleStreamOptions: API key, reasoning, thinking budgets, session id, transport, retry limits, payload and response hooks. They are embedded, so each is also a field of the config. Thinking (upstream reasoning) is the run's thinking level: empty is "off" for PrepareRequest, and PrepareRequest or PrepareNextTurn may replace it for later requests. The loop sets model cost and the output-token limit per request.
	ai.StreamOptions

	// ConvertToLlm converts the transformed context to provider messages. Nil uses the standard conversion.
	ConvertToLlm func([]AgentMessage) ([]ai.Message, error)
	// TransformLLMMessages post-processes the provider messages that the standard conversion produced.
	TransformLLMMessages func([]ai.Message) []ai.Message
	// TransformContext runs before ConvertToLlm on every request.
	TransformContext func(context.Context, []AgentMessage) ([]AgentMessage, error)
	// GetAPIKey resolves the credential for the model's provider before every request, for tokens that expire during a long run. An empty result keeps StreamOptions.APIKey. An error fails the run, as upstream awaits getApiKey unguarded. Mirrors upstream getApiKey.
	GetAPIKey func(provider string) (string, error)
	// SystemPromptOverride projects a replacement system prompt onto every request without rewriting the transcript.
	SystemPromptOverride func() *string

	FinishTurn      FinishTurn
	PrepareRequest  PrepareRequest
	PrepareNextTurn PrepareNextTurn
	// GetSteeringMessages and GetFollowUpMessages supply queued messages. Nil means none.
	GetSteeringMessages func() []AgentMessage
	GetFollowUpMessages func() []AgentMessage
	ToolExecution       ToolExecutionMode
	// BeforeToolCall and AfterToolCall are the AgentLoopConfig properties of Pi (types.ts:123-124); the hook lists run after them.
	BeforeToolCall      BeforeToolCallFunc
	AfterToolCall       AfterToolCallFunc
	BeforeToolCallHooks []BeforeToolCallHook
	AfterToolCallHooks  []AfterToolCallHook
	PrepareToolResult   func(context.Context, AgentToolResult) AgentToolResult

	// MaxTurns stops a run after that many turns; zero is unlimited, as upstream.
	MaxTurns int
	// SessionFile reports the session file tools may expose; nil or empty exports nothing.
	SessionFile func() string
	// contains filtered or unexported fields
}

AgentLoopConfig configures a standalone loop run. Mirrors upstream AgentLoopConfig, which extends SimpleStreamOptions: StreamOptions carries the base request options. The Agent builds one for every run it starts.

type AgentLoopTurnUpdate

type AgentLoopTurnUpdate struct {
	// Context replaces the loop context (transcript and executable tools) for
	// the next provider request; nil keeps the current one (upstream's
	// `context ?? currentContext`).
	Context *AgentContext
	// Messages are appended before the next provider request, with normal
	// lifecycle events.
	Messages []AgentMessage
	// Model is the model for the next provider request.
	Model *ai.Model
	// ThinkingLevel is the thinking level for the next provider request.
	ThinkingLevel *ThinkingLevel
}

AgentLoopTurnUpdate carries optional next-turn overrides returned by PrepareNextTurn. Mirrors upstream AgentLoopTurnUpdate.

type AgentMessage

type AgentMessage struct {
	System     *ai.SystemMessage
	User       *UserMessage
	Assistant  *AssistantMessage
	ToolResult *ToolResultMessage
	// Custom message types (bash execution, branch summary, etc.)
	Custom map[string]any // raw JSON for custom types
	// contains filtered or unexported fields
}

AgentMessage is the union of all message types. Only one field is non-nil.

func NormalizeMessages

func NormalizeMessages(msgs []AgentMessage, model *ai.Model) []AgentMessage

NormalizeMessages filters and normalizes msgs before they are converted to the provider wire format by convertToLLM. Two guarantees are provided:

  1. Assistant messages with StopReason "error" or "aborted" are dropped. Replaying them causes API errors (partial reasoning, orphaned tool calls, OpenAI "reasoning without following item").

  2. Orphaned tool calls: tool_use blocks in an assistant message with no matching tool_result: get a synthetic ToolResultMessage injected immediately after the assistant message. This keeps the message sequence valid for all providers.

  3. Cross-model thinking blocks are normalized against the target model (upstream transform-messages.ts isSameModel branch): redacted thinking is dropped for a different model, same-model signed thinking is kept for replay, empty thinking is dropped, and other cross-model thinking is converted to plain text so a foreign reasoning signature never reaches a provider converter. model may be nil on contextless/test paths, which is treated as same-model (thinking passes through).

The returned slice may be shorter than msgs (dropped aborted/errored entries) or longer (inserted synthetic tool results). Assistant entries whose thinking is normalized are copied; other non-modified entries share their underlying struct pointers with msgs.

func RunAgentLoop

func RunAgentLoop(ctx context.Context, prompts []AgentMessage, agentContext AgentContext, config AgentLoopConfig, emit AgentEventSink, streamFn StreamFn) ([]AgentMessage, error)

RunAgentLoop starts a loop with new prompt messages and returns the messages the run produced, the prompts first. The prompts are added to a copy of the context; the caller's context is not modified. A failure of the sink, ConvertToLlm, a hook callback, or a missing stream function is returned instead of becoming a failed turn; the Agent owns that conversion. A nil streamFn uses the host's default stream function. Mirrors upstream runAgentLoop.

func RunAgentLoopContinue

func RunAgentLoopContinue(ctx context.Context, agentContext AgentContext, config AgentLoopConfig, emit AgentEventSink, streamFn StreamFn) ([]AgentMessage, error)

RunAgentLoopContinue continues a loop from the context without adding a message and returns the messages the run produced. The last context message must convert to a user or tool-result message; the provider rejects the request otherwise. Mirrors upstream runAgentLoopContinue.

func (AgentMessage) AppendStringify

func (m AgentMessage) AppendStringify(dst []byte) ([]byte, error)

AppendStringify appends the JSON.stringify text of MarshalJSON's output to dst (json.StringifyAppender), encoding the message's members into dst itself.

func (AgentMessage) AsSystemMessage

func (m AgentMessage) AsSystemMessage() (ai.SystemMessage, bool)

AsSystemMessage returns the wrapped system message, which the transcript helpers read when the role is "system".

func (AgentMessage) Clone

func (m AgentMessage) Clone() AgentMessage

Clone copies the message envelope and mutable top-level slices/maps. A streaming assistant becomes an independently owned current observation.

func (AgentMessage) ContentBlocks

func (m AgentMessage) ContentBlocks() []ai.ContentBlock

func (AgentMessage) DecodedForm

func (m AgentMessage) DecodedForm() (AgentMessage, bool)

DecodedForm returns the message that json.Unmarshal of m's encoding yields, and true when that can be proven from m alone. It reports false for a message it cannot prove round-trips, and the caller decodes the encoding: a system or custom message, one that keeps the source it was decoded from, a streaming assistant, streaming scratch on a block, a tool call whose arguments are not an object of plain JSON values, a number that is not finite or is negative zero or beyond 2^53, text that is not valid UTF-8 (a lone surrogate included), diagnostics, a deferred handle, nested calls, or tool result details other than null, a scalar, or canonical raw JSON.

func (AgentMessage) MarshalJSON

func (m AgentMessage) MarshalJSON() ([]byte, error)

MarshalJSON emits the upstream flat role-discriminated AgentMessage union. User strings and text blocks retain their JavaScript UTF-16 units.

func (AgentMessage) MessageRole

func (m AgentMessage) MessageRole() string

MessageRole is the role property of the message (ai.RoleMessage): an agent transcript goes to the transcript helpers as it is.

func (AgentMessage) NullContent

func (m AgentMessage) NullContent() bool

NullContent reports a system, user, assistant or toolResult message whose content is null or missing: in the object it was decoded from, or in its fields when it was not decoded.

func (AgentMessage) Role

func (m AgentMessage) Role() string

Role returns the role string.

func (AgentMessage) SourceJSON

func (m AgentMessage) SourceJSON() ([]byte, error)

SourceJSON returns the JSON.stringify text of the object m was decoded from, as Pi keeps the parsed object and every writer of the message stringifies it, when that text differs from the encoding of m's fields; otherwise it returns nil. A Custom message encodes its current members in the decoded object's member order; one decoded from a value that is not an object returns that value.

func (AgentMessage) TextBytes

func (m AgentMessage) TextBytes() int

TextBytes is the length of the strings that make up most of m's JSON: the text it was decoded from, or its content's text, thinking, image data and tool-call argument strings and keys, a tool result's details strings, and a custom message's strings. A writer sizes the buffer it encodes m into from it.

func (*AgentMessage) UnmarshalJSON

func (m *AgentMessage) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes the upstream flat role-discriminated AgentMessage union and retains lone UTF-16 units in user content as WTF-8. When the decoded fields would encode to other text than JSON.stringify writes for data (member order, members PiG does not model, or a spelling the fields cannot keep), the message keeps that text: Pi holds the parsed object and writes it unchanged.

The fields decode JSON.stringify's text of data, so a number keeps the message in any spelling, as JSON.parse keeps it: an integral value spelled with a fraction or exponent decodes as the integer in every nested record too, and a fraction or a value beyond the range of a nested record's integer field leaves that field zero. A member of another JSON type than its field holds reads as absent (decodeLax).

func (AgentMessage) WithEmptyContent

func (m AgentMessage) WithEmptyContent() AgentMessage

WithEmptyContent returns a copy of m with empty content, as the JavaScript spread { ...m, content: [] } builds it, and { ...m, content: "" } for a system message: a content member of the decoded object keeps its place, and a missing one follows the other members.

type AgentOptions

type AgentOptions struct {
	// InitialState seeds the model, thinking level, tools, system prompt and transcript.
	// upstream: agent.ts:115 (initialState)
	InitialState    *AgentInitialState
	Model           *ai.Model
	Tools           []AgentTool
	SystemPrompt    string
	MaxTurns        int // 0 = unlimited, as upstream, which has no turn cap
	ThinkingLevel   ai.ModelThinkingLevel
	ThinkingBudgets *ai.ThinkingBudgets
	Transport       ai.Transport
	// SessionID is forwarded to the provider for prompt caching
	// (OpenAI prompt_cache_key). Set by the session wrapper when
	// the session has a stable identifier.
	SessionID string
	// SessionFile, when set, reports the session file tools may expose as
	// PI_SESSION_FILE. Nil or an empty result exports nothing.
	SessionFile func() string

	// SteeringMode controls how steering messages are drained (default: one-at-a-time).
	// Mirrors upstream packages/agent/src/agent.ts:104.
	SteeringMode QueueMode
	// FollowUpMode controls how follow-up messages are drained (default: one-at-a-time).
	// Mirrors upstream packages/agent/src/agent.ts:105.
	FollowUpMode QueueMode

	// BeforeToolCall and AfterToolCall are Pi's single hook-function properties (agent.ts:201-207); BeforeToolCallHooks and AfterToolCallHooks are the Go hook lists, which run after them.
	BeforeToolCall      BeforeToolCallFunc
	AfterToolCall       AfterToolCallFunc
	BeforeToolCallHooks []BeforeToolCallHook
	AfterToolCallHooks  []AfterToolCallHook
	// PrepareToolResult processes the final extension-modified result before
	// events and persistence. Processing failures preserve the original result.
	PrepareToolResult func(context.Context, AgentToolResult) AgentToolResult
	// FinishTurn runs after a turn's assistant message and tool results and
	// before TurnEndEvent; it may end the run or request one more request.
	FinishTurn FinishTurn
	// PrepareRequest runs immediately before every provider request and may
	// replace the context, model, and thinking level for the run.
	PrepareRequest PrepareRequest
	// ConvertToLlm converts the transformed agent context to provider messages.
	// The run waits for it and reports conversion failures through its lifecycle.
	// Nil uses the standard message conversion.
	ConvertToLlm func([]AgentMessage) ([]ai.Message, error)
	// TransformLLMMessages post-processes the provider messages that the
	// built-in conversion produced for each request. The coding session uses
	// it as upstream createAgentSession wraps convertToLlm
	// (convertToLlmWithBlockImages in sdk.ts).
	TransformLLMMessages func([]ai.Message) []ai.Message
	// PrepareNextTurn is the hook that sees only the run's context. It is ignored when PrepareNextTurnWithContext is set.
	// upstream: agent.ts:127 (AgentOptions.prepareNextTurn(signal))
	PrepareNextTurn func(ctx context.Context) (*AgentLoopTurnUpdate, error)
	// PrepareNextTurnWithContext runs before the next turn starts when the loop
	// continues, receives the completed turn, and may replace or extend the next request's state.
	// upstream: agent.ts:130 (AgentOptions.prepareNextTurnWithContext(context, signal))
	PrepareNextTurnWithContext PrepareNextTurn
	// PreparePrompt lets the owning Session prepare new prompt messages before
	// their lifecycle events and persistence. It does not run for continuation
	// or queued steering/follow-up messages.
	PreparePrompt func(context.Context, []AgentMessage) ([]AgentMessage, error)
	// ToolExecution is the batch strategy for assistant messages with several
	// tool calls (default parallel). A tool whose ExecutionMode is sequential
	// forces its batch to run sequentially. Mirrors upstream Agent.toolExecution.
	ToolExecution ToolExecutionMode

	// EventCh receives agent events. If nil, events are discarded. Every
	// event is delivered, including after the run's context is cancelled, as
	// upstream awaits every listener; emit blocks until the event is received
	// or EventDone is closed.
	EventCh chan<- AgentEvent
	// EventDone, when closed, reports that EventCh has no receiver anymore.
	// Events emitted after that are dropped instead of blocking the agent.
	EventDone <-chan struct{}

	// OnEvent, if set, runs synchronously for every event before the event is
	// persisted or delivered, as upstream Agent awaits its listeners before it
	// continues. It may replace a message_end message in place (mutating the
	// pointed-to message or custom map), and the replacement is what agent
	// state, persistence and EventCh observe.
	OnEvent func(AgentEvent)
	// AfterEvent runs after persistence and channel publication, before the loop polls queued work. An error fails the same run.
	AfterEvent func(AgentEvent) error
	// StreamFn sends each provider request. Nil uses DefaultStreamFn or the configured host default; NewAgent fails when none exists.
	// Mirrors upstream AgentOptions.streamFn.
	StreamFn StreamFn
	// DefaultStreamFn supplies the host's stock request path without making it a caller override. Nil uses the configured host default.
	DefaultStreamFn StreamFn

	// OnMessagePersist, if set, is invoked exactly once for each NEW message
	// the agent produces during a turn: the user prompt, steering / follow-up
	// user messages, assistant messages (including aborted/error ones), and
	// tool-result messages: in production order. It is driven by message_end in
	// emit() and is NOT called for replayed/resumed context (the runLoop replay
	// emits message_end only for this run's new messages, never loaded history).
	// Mirrors upstream's single incremental persistence site (agent-session.ts
	// message_end handler) so a turn interrupted mid-flight is durably recorded
	// instead of lost on the next resume. An error fails the run the way a
	// throwing message_end listener does upstream: the loop stops and the run
	// ends with an error assistant message.
	OnMessagePersist func(AgentMessage) error
	// GetAPIKey resolves the credential for each provider request, for tokens that expire during a run. An empty result keeps the static key; an error fails the run, as a rejected getApiKey does. Mirrors upstream AgentOptions.getApiKey.
	GetAPIKey func(provider string) (string, error)
	// TransformContext rewrites the agent context before each provider request, ahead of ConvertToLlm. Mirrors upstream AgentOptions.transformContext; the context carries the run's AbortSignal and an error fails the turn.
	TransformContext func(context.Context, []AgentMessage) ([]AgentMessage, error)
	// OnPayload inspects or replaces each provider payload after the adapter builds it. SetBeforeProviderHook replaces it later. Mirrors upstream AgentOptions.onPayload.
	OnPayload func(payload any, model *ai.Model) (any, error)
	// OnResponse runs once per provider response before its body is consumed. Mirrors upstream AgentOptions.onResponse.
	OnResponse func(context.Context, ai.ProviderResponse, *ai.Model) error
	// MaxRetryDelayMs caps the delay a provider waits before one retry; nil keeps the provider default. Mirrors upstream AgentOptions.maxRetryDelayMs.
	MaxRetryDelayMs *int
	// Identity is how requests identify the app to providers, merged field by field over DefaultAgentIdentity (attribution to PiG). Pass an identity with AttributionNull to send no attribution headers. Mirrors upstream AgentOptions.identity.
	Identity *ai.ClientIdentity
	// OnProviderStreamEvent is forwarded to every provider request. Mirrors upstream AgentOptions.onProviderStreamEvent (packages/agent/src/agent.ts:122).
	OnProviderStreamEvent func(ctx context.Context, data any, model *ai.Model) error
}

type AgentRequestUpdate

type AgentRequestUpdate struct {
	// Context replaces the loop context (transcript and executable tools); nil keeps the current one.
	Context       *AgentContext
	Model         *ai.Model
	ThinkingLevel *ThinkingLevel
}

AgentRequestUpdate replaces runtime state for the provider request being prepared and later requests in the run. Mirrors upstream AgentRequestUpdate (AgentLoopTurnUpdate without messages).

type AgentSettledEvent

type AgentSettledEvent struct {
	// Aborted is whether the run ended because it was aborted, for example with Escape (agent-session.ts:203).
	Aborted bool
}

AgentSettledEvent fires once an agent run has fully settled: no automatic retry, compaction, or queued continuation will follow. Upstream emits it from the _runAgentPrompt finally (agent-session.ts:1073) to both the extension runner and the session event stream.

type AgentStartEvent

type AgentStartEvent struct{}

type AgentState

type AgentState struct {
	// contains filtered or unexported fields
}

AgentState is the live view of the agent's state that Pi exposes as `agent.state` (types.ts:382-421). Reads see the agent's current values and the writable properties write through: SetModel, SetThinkingLevel, SetTools and SetMessages are Pi's `state.model = ...`, `state.thinkingLevel = ...`, `state.tools = ...` and `state.messages = ...`. The value is cheap and holds no copy, so it may be kept: it always reflects the agent it came from.

func (AgentState) ErrorMessage

func (s AgentState) ErrorMessage() string

ErrorMessage is the error of the most recent failed or aborted assistant turn; empty when there is none.

func (AgentState) IsStreaming

func (s AgentState) IsStreaming() bool

IsStreaming is true while the agent is processing a prompt or continuation.

func (AgentState) Messages

func (s AgentState) Messages() []AgentMessage

Messages is the conversation transcript.

func (AgentState) Model

func (s AgentState) Model() *ai.Model

Model is the active model used for future turns.

func (AgentState) PendingToolCalls

func (s AgentState) PendingToolCalls() []string

PendingToolCalls are the tool call ids currently executing, in start order, as Pi's insertion-ordered Set iterates them.

func (AgentState) SetMessages

func (s AgentState) SetMessages(messages []AgentMessage)

SetMessages assigns the transcript; the top-level slice is copied (upstream `state.messages = messages`).

func (AgentState) SetModel

func (s AgentState) SetModel(model *ai.Model)

SetModel assigns the active model (upstream `state.model = model`).

func (AgentState) SetThinkingLevel

func (s AgentState) SetThinkingLevel(level ai.ModelThinkingLevel)

SetThinkingLevel assigns the requested reasoning level (upstream `state.thinkingLevel = level`).

func (AgentState) SetTools

func (s AgentState) SetTools(tools []AgentTool)

SetTools assigns the executable tools; the top-level slice is copied (upstream `state.tools = tools`).

func (AgentState) Snapshot

func (s AgentState) Snapshot() AgentStateSnapshot

Snapshot reads every value of the state at once.

func (AgentState) StreamingMessage

func (s AgentState) StreamingMessage() *AgentMessage

StreamingMessage is the partial assistant message of the current streamed response, if any.

func (AgentState) SystemPrompt

func (s AgentState) SystemPrompt() string

SystemPrompt is the current system prompt, replayed from the transcript's system messages. It is read-only: append a system message to change it.

func (AgentState) ThinkingLevel

func (s AgentState) ThinkingLevel() ai.ModelThinkingLevel

ThinkingLevel is the requested reasoning level for future turns.

func (AgentState) Tools

func (s AgentState) Tools() []AgentTool

Tools are the executable tools; the slice is a copy of the list.

type AgentStateSnapshot

type AgentStateSnapshot struct {
	// SystemPrompt is the current system prompt, replayed from the transcript's system messages.
	SystemPrompt string
	// Model is the active model used for future turns.
	Model *ai.Model
	// ThinkingLevel is the requested reasoning level for future turns.
	ThinkingLevel ai.ModelThinkingLevel
	// Tools are the executable tools.
	Tools []AgentTool
	// Messages is the conversation transcript.
	Messages []AgentMessage
	// IsStreaming is true while the agent is processing a prompt or continuation.
	IsStreaming bool
	// StreamingMessage is the partial assistant message of the current streamed response, if any.
	StreamingMessage *AgentMessage
	// PendingToolCalls are the tool call ids currently executing, in start order, as Pi's insertion-ordered Set iterates them.
	PendingToolCalls []string
	// ErrorMessage is the error of the most recent failed or aborted assistant turn, if any; empty when there is none.
	ErrorMessage string
}

AgentStateSnapshot is the values of the agent's state read at one moment. It holds copies, so it does not follow the agent.

type AgentTool

type AgentTool interface {
	// Name is the tool's name as known to the LLM.
	Name() string
	// Label returns a human-readable display name for the tool header.
	// If empty, Name() is used for display. Mirrors upstream AgentTool.label.
	Label() string
	// Schema returns the JSON Schema for the tool's parameters.
	Schema() ai.ToolSchema
	// Execute runs the tool.
	Execute(ctx context.Context, toolCallID string, params json.RawMessage,
		onUpdate ToolUpdateCallback) (AgentToolResult, error)
	// ExecutionMode returns the tool's parallelism preference.
	ExecutionMode() ToolExecutionMode
}

AgentTool is the interface that all tools must implement.

type AgentToolCall

type AgentToolCall = ai.ToolCall

AgentToolCall is a tool call block of an assistant message. Mirrors upstream AgentToolCall.

type AgentToolCallOutcome

type AgentToolCallOutcome struct {
	ToolCall AgentToolCall
	Result   AgentToolResult
	IsError  bool
	// DurationMs is the milliseconds execute() took, measured with a monotonic clock; nil when the tool did not run.
	DurationMs *int64
}

AgentToolCallOutcome is the final outcome of a tool call after the hooks ran. Mirrors upstream AgentToolCallOutcome (packages/agent/src/types.ts).

func RunToolCall

func RunToolCall(ctx context.Context, call AgentToolCall, options RunToolCallOptions) (AgentToolCallOutcome, error)

RunToolCall runs one tool call through the same steps as a model-issued call: argument preparation, schema validation, the before hooks, execution, and the after hooks. It emits no events and adds no messages. Tools that call other tools use it so the hooks (for example permission checks) apply to those calls too. Mirrors upstream runToolCall (agent-loop.ts:800-820).

It never fails for tool failures: unknown tools, validation errors, blocked calls, and panics come back as an outcome with IsError set. It returns the first error of options.OnUpdate after the tool returned, without running the after hooks, as upstream's promise rejects.

type AgentToolResult

type AgentToolResult struct {
	// MemberOrder names the members of the result object in the order its tool wrote them (content, details,
	// isError, structuredContent, usage, terminate). Upstream hands the tool's own object on, so JSON.stringify
	// writes its members in that order; a result without it (a built-in tool, a Go tool) has the declared order.
	// upstream: agent-loop.ts:778-786, 912-919
	MemberOrder []string
	Content     []ai.ToolResultMessageContent
	Details     any
	// StructuredContent is the machine-readable result of a tool that declares
	// an output schema. upstream: structuredContent?: JsonValue
	StructuredContent json.RawMessage
	// IsError is upstream's `result.isError`: the tool returned a failure instead of throwing it, so
	// details and structuredContent are kept. A thrown error, an unknown tool, invalid arguments and a
	// blocked call produce a result without it; the failure is reported by ToolExecutionEndEvent.IsError
	// and AgentToolCallOutcome.IsError. upstream: types.ts:436-441, agent-loop.ts:906-910
	IsError bool
	// Thrown marks a result that stands for an error upstream's tool throws. The agent reports the call as failed, drops
	// the result's IsError and Thrown, and keeps the rest, which is createErrorToolResult's content and empty details
	// (agent-loop.ts:906-910). A tool that returns a Go error has the same effect.
	Thrown bool
	// StructuredContentAppended records that afterToolCall gave a result that had no structuredContent one. Upstream's
	// `{...result}` spread keeps the tool's key order and assigning an existing key keeps its position, so only a key the
	// hook adds follows every key the tool set (agent-loop.ts:877-889). It only orders the serialized result.
	StructuredContentAppended bool
	// Usage is the usage of the tool execution itself, if available. It is
	// not used for main LLM context accounting. upstream: usage?: Usage
	Usage *ai.Usage
	// Terminate hints that the agent should stop after the current tool
	// batch. Early termination happens only when every finalized result in
	// the batch sets it. upstream: terminate?: boolean
	Terminate bool
	// pig additive (D160): the collapsed-view preview of a subprocess extension's tool result.
	// Preview is an optional short summary shown when the tool result is
	// collapsed in the TUI. When non-empty, overrides the default
	// tail-preview behavior. Extensions can set this to provide a
	// custom collapsed view (e.g. a table header, a line count, or a
	// brief summary) without implementing a full BodyRenderer.
	// pig extension: no upstream equivalent (Pi extensions use in-process
	// renderResult callbacks; subprocess extensions need a serializable
	// alternative).
	Preview string
}

AgentToolResult carries the ordered text/image blocks returned by a tool. Ports packages/agent/src/types.ts.

func (AgentToolResult) DetailsNull

func (r AgentToolResult) DetailsNull() bool

DetailsNull reports a result that holds details: null: the tool wrote the details member with no value. A Go tool that leaves Details nil and records no MemberOrder holds no details.

func (AgentToolResult) Images

func (r AgentToolResult) Images() []ai.ImageContent

Images selects image blocks for displays with a separate image area.

func (AgentToolResult) MemberNames

func (r AgentToolResult) MemberNames() []string

MemberNames lists the members of the result object this result holds (content, details, structuredContent, isError, usage, terminate), in the order upstream's object keeps them. Without a recorded MemberOrder that is the order the built-in tools build theirs in, with a structuredContent a hook added last. With one it is the tool's own order, and a member the tool did not set, which a hook added, follows the tool's in the order of the hook's spread, `{...result, content, details, usage, terminate}`, then the structuredContent assigned after it (agent-loop.ts:877-889). Content is always listed. A member MemberOrder names is held even when its value is a zero value (details or usage null, isError or terminate false): the tool wrote it, so upstream's object has it and JSON.stringify writes it. upstream: agent-loop.ts:778-786, 877-889, 912-919; coding-agent/src/core/tools/bash.ts:403-409

func (AgentToolResult) Text

func (r AgentToolResult) Text() string

Text joins text blocks for text-only displays; Content retains their boundaries and image positions.

type AgentTurnAction

type AgentTurnAction string

AgentTurnAction is the action of an AgentTurnDecision.

const (
	// AgentTurnContinue ensures one more provider request after the turn.
	AgentTurnContinue AgentTurnAction = "continue"
	// AgentTurnEnd ends the run without polling queues or preparing another request.
	AgentTurnEnd AgentTurnAction = "end"
)

type AgentTurnContext

type AgentTurnContext struct {
	// Message is the assistant message that completed the turn.
	Message *AssistantMessage
	// ToolResults are the tool result messages emitted for the completed turn.
	ToolResults []ToolResultMessage
	// Context is the loop context (transcript and executable tools) after the
	// turn's assistant message and tool results have been appended.
	Context AgentContext
	// NewMessages are the messages this run returns if it exits now. 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 (FinishTurn and PrepareNextTurn). Mirrors upstream packages/agent/src/types.ts AgentTurnContext.

type AgentTurnDecision

type AgentTurnDecision struct {
	Action AgentTurnAction
}

AgentTurnDecision is returned by FinishTurn. A nil decision preserves normal scheduling. Mirrors upstream AgentTurnDecision.

type ArgumentPreparer

type ArgumentPreparer interface {
	PrepareArguments(raw json.RawMessage) (json.RawMessage, error)
}

ArgumentPreparer is an optional interface tools may implement to normalize / coerce their raw input BEFORE schema validation runs. Mirrors upstream's per-tool `prepareArguments` hook (.upstream/current/packages/coding-agent/src/core/tools/edit.ts:308, `parameters: editSchema, ... prepareArguments: prepareEditArguments`).

Use cases:

  • edit tool: rewrites the legacy `{path, oldText, newText}` flat input shape into `{path, edits:[{oldText, newText}]}` so the strict editSchema accepts it (LLMs like Opus 4.6 / GLM-5.1 still emit the flat shape).
  • any future tool that accepts multiple wire shapes for the same semantic input.

Without this hook, schema validation in dispatch() rejects valid legacy inputs before tool.Execute() ever runs, breaking parity with upstream which normalizes first and validates after.

type AssistantMessage

type AssistantMessage struct {
	Role                  string                     `json:"role"` // "assistant"
	Content               []ai.AssistantContentBlock `json:"content"`
	Thinking              string                     `json:"-"`
	Timestamp             int64                      `json:"timestamp"`
	Usage                 *ai.Usage                  `json:"usage,omitempty"`
	API                   ai.API                     `json:"api,omitempty"`
	Provider              string                     `json:"provider,omitempty"`
	ModelID               string                     `json:"model,omitempty"`
	ResponseModel         string                     `json:"responseModel,omitempty"`
	ResponseID            string                     `json:"responseId,omitempty"`
	ProviderThinkingLevel string                     `json:"providerThinkingLevel,omitempty"`
	// ThinkingLevel is the level the agent loop requested for this response; see ai.AssistantMessage.ThinkingLevel.
	ThinkingLevel ai.ModelThinkingLevel           `json:"thinkingLevel,omitempty"`
	Diagnostics   []ai.AssistantMessageDiagnostic `json:"diagnostics,omitempty"`
	Deferred      *ai.DeferredHandle              `json:"deferred,omitempty"`
	// StopReason records why the assistant turn ended. Mirrors upstream
	// AssistantMessage.stopReason in packages/ai/src/types.ts.
	// Values: "stop" (normal), "toolUse" (tool calls present),
	//         "aborted" (context cancelled), "error" (EventError received).
	StopReason ai.StopReason `json:"stopReason,omitempty"`
	// ErrorMessage holds the error string when StopReason == "error".
	ErrorMessage string `json:"errorMessage,omitempty"`
	// ErrorBeforeTimestamp records that the message was built with errorMessage before timestamp; see ai.AssistantMessage.ErrorBeforeTimestamp.
	ErrorBeforeTimestamp bool   `json:"-"`
	RawStopReason        string `json:"rawStopReason,omitempty"`
	EndTurn              *bool  `json:"endTurn,omitempty"`
	// DurationMs is the milliseconds from the start of the request to the final message, measured with a monotonic clock by the AssistantMessageEventStream. Nil for legacy messages and for deferred results fetched later.
	// upstream: ai/src/types.ts:582 AssistantMessage.durationMs
	DurationMs *int64 `json:"durationMs,omitempty"`
	// ThinkingSignature is a legacy runtime convenience; durable signatures
	// live on ThinkingContent blocks in the upstream wire shape.
	ThinkingSignature string `json:"-"`
	// contains filtered or unexported fields
}

AssistantMessage is a streamed response from the LLM. Streaming events retain a shallow provider view; Observe and JSON serialization read its current nested state without mutating these exported fields.

func (AssistantMessage) AppendStringify

func (m AssistantMessage) AppendStringify(dst []byte) ([]byte, error)

AppendStringify appends the JSON.stringify text of MarshalJSON's output to dst (json.StringifyAppender).

func (*AssistantMessage) LLMMessage

func (m *AssistantMessage) LLMMessage() ai.AssistantMessage

LLMMessage returns the provider-facing form of an assistant message. Plain messages share content and diagnostics slices with m; retained streaming views produce an owned observation.

func (AssistantMessage) MarshalJSON

func (m AssistantMessage) MarshalJSON() ([]byte, error)

MarshalJSON observes retained streaming messages at the serialization boundary.

func (*AssistantMessage) Observe

func (m *AssistantMessage) Observe() *AssistantMessage

Observe returns an independently owned observation of the message. A streaming shallow view keeps its copied top-level values while observing its retained nested objects.

func (*AssistantMessage) ObserveProjection

func (m *AssistantMessage) ObserveProjection(content []ai.AssistantContentProjection) (blocks []ai.AssistantContentProjection, stopReason ai.StopReason, errorMessage string)

ObserveProjection is Observe for a reader of block kinds, texts, thinking, tool calls, stop reason and error message (ai.AssistantMessage.ObserveProjection): it appends one projection per content block to content, returns that slice with the stop reason and error message, and copies nothing else. A streaming view projects its retained stream state; other messages their own fields.

func (*AssistantMessage) ObserveUsage

func (m *AssistantMessage) ObserveUsage() *ai.Usage

ObserveUsage returns an owned usage snapshot without traversing message content or metadata. Streaming views observe their retained usage reference; ordinary absent usage stays absent.

func (*AssistantMessage) Publication

func (m *AssistantMessage) Publication() (cell uintptr, seq uint64)

Publication is ai.AssistantMessage.Publication for the stream state a streaming view observes: while it is unchanged, Observe returns the same message. A message without a stream view returns (0, 0).

type AutoRetryEndEvent

type AutoRetryEndEvent struct {
	Success    bool
	Attempt    int
	FinalError string // set when Success==false
}

AutoRetryEndEvent fires when an auto-retry cycle completes (success or exhausted). Mirrors upstream auto_retry_end (agent-session.ts:131).

type AutoRetryStartEvent

type AutoRetryStartEvent struct {
	Attempt      int
	MaxAttempts  int
	DelayMs      int
	ErrorMessage string
}

AutoRetryStartEvent fires when pig is about to retry a failed request due to a transient error (overload, rate limit, server error). Mirrors upstream auto_retry_start (agent-session.ts:130).

type BashExecutionUpdateEvent

type BashExecutionUpdateEvent struct {
	ID    *string
	Delta string
}

BashExecutionUpdateEvent reports one command-output delta. A nil ID omits the correlation identifier; a non-nil empty ID remains explicit.

type BeforeToolCallContext

type BeforeToolCallContext struct {
	// AssistantMessage is the assistant message that requested the tool call; nil for a call made without one.
	AssistantMessage *AssistantMessage
	// ToolCall is the raw tool call block from the assistant message.
	ToolCall ai.ToolCall
	// Args is the validated tool arguments.
	Args json.RawMessage
	// Context is the agent context when the tool call is prepared.
	Context AgentContext
}

BeforeToolCallContext is the context of a beforeToolCall hook (upstream types.ts BeforeToolCallContext).

type BeforeToolCallFunc

type BeforeToolCallFunc func(ctx context.Context, call BeforeToolCallContext) *BeforeToolCallResult

BeforeToolCall is Pi's single beforeToolCall property: it runs after argument validation and before the tool executes, in front of the Go hook list. Returning a result with Block set prevents execution; the loop then emits an error tool result. A nil result lets the call run. The context.Context is Pi's signal.

upstream: packages/agent/src/types.ts AgentLoopConfig.beforeToolCall, agent-loop.ts:728-760

type BeforeToolCallHook

type BeforeToolCallHook func(ctx context.Context, toolCallID, toolName string, args json.RawMessage) ToolCallHookResult

BeforeToolCallHook is called before a tool executes. Return ToolCallHookResult{Block: true} to prevent execution.

type BeforeToolCallResult

type BeforeToolCallResult = ToolCallHookResult

BeforeToolCallResult is what a beforeToolCall hook returns (upstream types.ts BeforeToolCallResult). It is the result type of the hook lists too.

type CompactionEndEvent

type CompactionEndEvent struct {
	Reason               string
	Aborted              bool
	WillRetry            bool
	Summary              string
	FirstKeptEntryID     string
	TokensBefore         int
	EstimatedTokensAfter int
	Usage                *ai.Usage
	Details              any
	ErrorMessage         string
}

CompactionEndEvent fires when compaction completes, aborts, or errors. Mirrors upstream compaction_end event (agent-session.ts).

type CompactionStartEvent

type CompactionStartEvent struct {
	Reason string // "manual" | "threshold" | "overflow"
}

CompactionStartEvent fires when auto-compaction or /compact begins. Mirrors upstream compaction_start event (agent-session.ts).

type ContextUsageEstimate

type ContextUsageEstimate struct {
	Tokens         int
	UsageTokens    int
	TrailingTokens int
	LastUsageIndex int // -1 if not found
}

ContextUsageEstimate is the result of EstimateContextTokens. Mirrors upstream ContextUsageEstimate (compaction.ts:177).

func EstimateContextTokens

func EstimateContextTokens(messages []AgentMessage) ContextUsageEstimate

EstimateContextTokens estimates context token usage from a message slice. Uses the last assistant usage that is not aborted, errored, or all-zero (upstream getAssistantUsage), plus a chars/4 estimate of the messages trailing it; falls back to a full estimate when no usage is present. Mirrors upstream estimateContextTokens (compaction.ts:186).

type EntryAppendedEvent

type EntryAppendedEvent struct {
	Entry json.RawMessage
}

EntryAppendedEvent reports a Session entry appended outside the agent loop, such as cache-warming usage. Entry is the persisted entry's JSON. Mirrors upstream AgentSessionEvent entry_appended (agent-session.ts:178).

type ExtensionTool

type ExtensionTool interface {
	// RunsInExtension reports whether the tool's Execute runs in an extension; a wrapper reports its wrapped tool's answer.
	RunsInExtension() bool
}

ExtensionTool is implemented by a tool whose Execute runs in an extension runtime, on an event loop of its own. Pi's loop turns during such a tool only if the tool awaits real work, which the host cannot tell, so the agent opens no wait for it (jsloop.Turns).

type FinishTurn

type FinishTurn func(ctx context.Context, turn AgentTurnContext) (*AgentTurnDecision, error)

FinishTurn is called after a completed assistant turn and all of its tool-result messages, but before TurnEndEvent. On a normal turn, AgentTurnContinue ensures one next provider request: tool-result, steering, or follow-up scheduling satisfies that request without adding another; otherwise the loop continues once with the current context. Error and aborted responses remain hard exits. ctx is the run's context (upstream's abort signal). A rejected callback enters the owning failed-turn lifecycle. Mirrors upstream FinishTurn.

type MayTakeFileMutationQueue

type MayTakeFileMutationQueue interface {
	MayTakeFileMutationQueue() bool
}

MayTakeFileMutationQueue is implemented by a tool whose code can register in the file mutation queue itself, after the dispatcher started it: an extension tool, whose extension calls withFileMutationQueue. Pi's Promise.all(calls.map(...)) runs each call's synchronous prefix in call order, and withFileMutationQueue registers in the queue in the order it is called (core/tools/file-mutation-queue.ts: registrationQueue), so an extension tool that takes the queue in its first statement registers before the edit or write call that follows it in the batch. The extension is another process, so its registration arrives a hop after the dispatcher started the call; the dispatcher holds every later call that registers in the queue behind the end of the extension tool's synchronous prefix (the call's start window).

type MessageEndEvent

type MessageEndEvent struct {
	Message AgentMessage
	// contains filtered or unexported fields
}

type MessageStartEvent

type MessageStartEvent struct {
	Message AgentMessage
	// contains filtered or unexported fields
}

type MessageUpdateEvent

type MessageUpdateEvent struct {
	Message               AgentMessage
	AssistantMessageEvent ai.AssistantMessageEvent
	// contains filtered or unexported fields
}

type MutationTicket

type MutationTicket struct {
	Wait    func()
	Release func()
}

MutationTicket is a reserved position in a shared per-path mutation queue (internal/codingagent/tools.FileMutationQueue), obtained synchronously, in tool-call source order, before the parallel dispatcher spawns this call's goroutine. Wait blocks until it is this ticket's turn; Release must run exactly once, after the tool's mutation completes, regardless of outcome.

func MutationTicketFromContext

func MutationTicketFromContext(ctx context.Context) (*MutationTicket, bool)

MutationTicketFromContext returns the ticket the dispatcher reserved for this call, if any.

type OutputSchemaProvider

type OutputSchemaProvider interface {
	OutputSchema() json.RawMessage
}

OutputSchemaProvider is implemented by a tool that declares the JSON Schema of the structured content in its successful results. Mirrors upstream AgentTool.outputSchema.

type PendingMessageQueue

type PendingMessageQueue struct {
	// contains filtered or unexported fields
}

PendingMessageQueue is a thread-safe FIFO of agent messages with a configurable drain policy. Used for steering and follow-up queues.

Mirrors upstream packages/agent/src/agent.ts:113 (class PendingMessageQueue).

func NewPendingMessageQueue

func NewPendingMessageQueue(mode QueueMode) *PendingMessageQueue

NewPendingMessageQueue creates a queue with the given drain mode.

func (*PendingMessageQueue) Clear

func (q *PendingMessageQueue) Clear() []AgentMessage

Clear removes and returns all queued messages regardless of mode.

func (*PendingMessageQueue) ClearUserMessages

func (q *PendingMessageQueue) ClearUserMessages() []AgentMessage

ClearUserMessages removes and returns the queued user messages and keeps every other queued message in order.

func (*PendingMessageQueue) Drain

func (q *PendingMessageQueue) Drain() []AgentMessage

Drain removes and returns pending messages according to the queue's mode. "all" drains every message; "one-at-a-time" drains the oldest single message. Returns nil when the queue is empty. Mirrors upstream PendingMessageQueue.drain.

func (*PendingMessageQueue) Enqueue

func (q *PendingMessageQueue) Enqueue(msg AgentMessage)

Enqueue appends a message to the queue.

func (*PendingMessageQueue) HasItems

func (q *PendingMessageQueue) HasItems() bool

HasItems reports whether the queue has any pending messages.

func (*PendingMessageQueue) Len

func (q *PendingMessageQueue) Len() int

Len returns the number of queued messages.

func (*PendingMessageQueue) Messages

func (q *PendingMessageQueue) Messages() []AgentMessage

Messages returns copies of all queued messages without draining, whatever the mode. Used for UI display of pending steering/follow-up messages.

func (*PendingMessageQueue) Mode

func (q *PendingMessageQueue) Mode() QueueMode

Mode returns the current drain mode.

func (*PendingMessageQueue) Peek

func (q *PendingMessageQueue) Peek() []AgentMessage

Peek returns the messages the next Drain would remove, without removing them: every message in "all" mode, the oldest one in "one-at-a-time" mode. Mirrors upstream PendingMessageQueue.peek.

func (*PendingMessageQueue) SetMode

func (q *PendingMessageQueue) SetMode(mode QueueMode)

SetMode changes the drain mode.

type PrepareNextTurn

type PrepareNextTurn func(ctx context.Context, turn PrepareNextTurnContext) (*AgentLoopTurnUpdate, error)

PrepareNextTurn is called after TurnEndEvent when the loop continues, immediately before the next turn starts. ctx is the run's context. Mirrors upstream prepareNextTurnWithContext. An error preserves Promise rejection and prevents the next provider request.

type PrepareNextTurnContext

type PrepareNextTurnContext = AgentTurnContext

PrepareNextTurnContext mirrors upstream's PrepareNextTurnContext, which extends AgentTurnContext without adding fields.

type PrepareRequest

type PrepareRequest func(ctx context.Context, request PrepareRequestContext) (*AgentRequestUpdate, error)

PrepareRequest is called immediately before every provider request, including the first. Pending messages have already been appended and emitted when it runs, and it does not poll queues. A rejected callback enters the owning failed-turn lifecycle. Mirrors upstream PrepareRequest.

type PrepareRequestContext

type PrepareRequestContext struct {
	Context       AgentContext
	Model         *ai.Model
	ThinkingLevel ThinkingLevel
}

PrepareRequestContext is the runtime state available immediately before a provider request. Mirrors upstream PrepareRequestContext.

type PromptRun

type PromptRun struct {
	// contains filtered or unexported fields
}

PromptRun owns a claimed prompt and its cancellation context. Start dispatches agent_start; Run drains the remaining events and releases the claim. The owner must call Run exactly once, even if Start fails or the context is cancelled.

func (*PromptRun) Run

func (r *PromptRun) Run() ([]AgentMessage, error)

Run drains the claimed prompt and releases its active-run state, including when Start failed. The owner calls Run once; it calls Start when needed.

func (*PromptRun) Start

func (r *PromptRun) Start() error

Start prepares the prompt and dispatches agent_start without requesting a Provider response or committing unfinished prompt messages. Repeated calls return the first result.

type ProxyAssistantMessageEvent

type ProxyAssistantMessageEvent struct {
	Type                  ProxyAssistantMessageEventType `json:"type"`
	ContentIndex          int                            `json:"contentIndex"`
	Delta                 string                         `json:"delta"`
	ContentSignature      *string                        `json:"contentSignature,omitempty"`
	ID                    string                         `json:"id"`
	ToolName              string                         `json:"toolName"`
	ToolCall              *ai.ToolCall                   `json:"toolCall,omitempty"`
	Reason                ai.StopReason                  `json:"reason"`
	Usage                 ai.Usage                       `json:"usage"`
	ErrorMessage          *string                        `json:"errorMessage,omitempty"`
	ProviderThinkingLevel *string                        `json:"providerThinkingLevel,omitempty"`
	// contains filtered or unexported fields
}

ProxyAssistantMessageEvent is one compact event returned by a proxy server. Partial assistant messages are omitted and reconstructed by StreamProxy.

func (ProxyAssistantMessageEvent) MarshalJSON

func (event ProxyAssistantMessageEvent) MarshalJSON() ([]byte, error)

MarshalJSON emits only the fields carried by the selected proxy event variant.

func (*ProxyAssistantMessageEvent) UnmarshalJSON

func (event *ProxyAssistantMessageEvent) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes the event and records the members of a toolcall_end toolCall.

type ProxyAssistantMessageEventType

type ProxyAssistantMessageEventType string

ProxyAssistantMessageEventType is the closed `type` union of a proxy event (proxy.ts ProxyAssistantMessageEvent).

const (
	ProxyEventStart         ProxyAssistantMessageEventType = "start"
	ProxyEventTextStart     ProxyAssistantMessageEventType = "text_start"
	ProxyEventTextDelta     ProxyAssistantMessageEventType = "text_delta"
	ProxyEventTextEnd       ProxyAssistantMessageEventType = "text_end"
	ProxyEventThinkingStart ProxyAssistantMessageEventType = "thinking_start"
	ProxyEventThinkingDelta ProxyAssistantMessageEventType = "thinking_delta"
	ProxyEventThinkingEnd   ProxyAssistantMessageEventType = "thinking_end"
	ProxyEventToolcallStart ProxyAssistantMessageEventType = "toolcall_start"
	ProxyEventToolcallDelta ProxyAssistantMessageEventType = "toolcall_delta"
	ProxyEventToolcallEnd   ProxyAssistantMessageEventType = "toolcall_end"
	ProxyEventDone          ProxyAssistantMessageEventType = "done"
	ProxyEventError         ProxyAssistantMessageEventType = "error"
)

The proxy event types.

type ProxyStreamOptions

type ProxyStreamOptions struct {
	Temperature     *float64
	SamplingParams  map[string]any
	MaxTokens       *int
	Reasoning       ai.ModelThinkingLevel
	CacheRetention  ai.CacheRetention
	SessionID       string
	Headers         ai.ProviderHeaders
	Metadata        map[string]any
	Transport       ai.Transport
	ThinkingBudgets *ProxyThinkingBudgets
	MaxRetryDelayMs *int
	AuthToken       string
	ProxyURL        string
}

ProxyStreamOptions configures StreamProxy. Context cancellation is the Go equivalent of upstream's optional AbortSignal. Non-nil maps retain empty objects. ThinkingBudgets preserves each budget's presence, including explicit zeros.

type ProxyThinkingBudgets

type ProxyThinkingBudgets struct {
	Minimal *int `json:"minimal,omitempty"`
	Low     *int `json:"low,omitempty"`
	Medium  *int `json:"medium,omitempty"`
	High    *int `json:"high,omitempty"`
}

ProxyThinkingBudgets carries optional per-level token budgets to the proxy server. Nil fields stay omitted; non-nil fields send their value, including zero. A non-nil empty struct sends an empty object without overriding server defaults.

type QueueMode

type QueueMode string

QueueMode controls how PendingMessageQueue.Drain behaves. Mirrors upstream packages/agent/src/agent.ts:55 (type QueueMode).

const (
	// QueueModeAll drains all queued messages at once.
	QueueModeAll QueueMode = "all"
	// QueueModeOneAtATime drains one message per call.
	QueueModeOneAtATime QueueMode = "one-at-a-time"
)

type QueueOrderable

type QueueOrderable interface {
	ReserveMutationOrder(params json.RawMessage) (*MutationTicket, bool)
}

QueueOrderable is an optional interface a tool may implement so the parallel dispatcher reserves its place in a shared mutation queue in tool-call order, before any goroutine starts, rather than leaving admission order to goroutine-arrival order.

Upstream dispatches parallel tool calls via Promise.all(calls.map(tool => executeToolCall(tool))): Array.prototype.map runs its callback synchronously per element, in array order, so every call's synchronous prefix — including withFileMutationQueue's registration step (file-mutation-queue.ts:32-45), which chains the new call onto whatever is currently in the per-path map — completes for call N before call N+1's synchronous prefix begins, even though the calls then run concurrently (agent-loop.ts executeToolCallsParallel). Go's per-call goroutines (tool_execution.go executeToolCallsParallel) give no equivalent guarantee: nothing stops goroutine N+1 from reaching the queue before goroutine N. ReserveMutationOrder lets the dispatcher perform that registration step itself, synchronously, in its own call-ordered loop, closing that gap.

ReserveMutationOrder returns ok=false when the call will not reach the queue at all (a tool implementing this must return exactly the same ok/no-ok decision its Execute would reach, or a reservation could be left registered but never released). The returned params are the same (possibly ArgumentPreparer-normalized) arguments Execute receives.

type QueueUpdateEvent

type QueueUpdateEvent struct {
	Steering []string
	FollowUp []string
}

QueueUpdateEvent reports the current pending steering and follow-up text. It mirrors the coding-agent session queue_update event.

type Recorder

type Recorder struct {
	// contains filtered or unexported fields
}

Recorder captures per-turn and per-tool timing data for one agent session: turn start/end and tool execution latencies, so the status line, /cost, and --diagnose can all read from a single source. It is PiG's own recorder; Pi's startup profiler (core/timings.ts) is internal/codingagent/timings.

All methods are safe for concurrent use. Tool execution may run in parallel goroutines, so RecordTool can be called from multiple goroutines at once.

func NewRecorder

func NewRecorder() *Recorder

NewRecorder creates a Recorder. SessionStart is set to time.Now().

func (*Recorder) CurrentTurnElapsed

func (r *Recorder) CurrentTurnElapsed() time.Duration

CurrentTurnElapsed returns the elapsed time of the in-flight turn, or 0 if no turn is in flight.

func (*Recorder) Elapsed

func (r *Recorder) Elapsed() time.Duration

Elapsed returns wall-clock time since session start.

func (*Recorder) EndTurn

func (r *Recorder) EndTurn() time.Duration

EndTurn appends the elapsed turn duration and clears turn state. Returns the recorded duration. If StartTurn was not called, returns 0.

func (*Recorder) LastTurnDuration

func (r *Recorder) LastTurnDuration() time.Duration

LastTurnDuration returns the duration of the most recently completed turn, or 0 if no turn has completed yet. This is a static snapshot (not a live counter), suitable for display in the status line when the agent is idle.

func (*Recorder) RecordTool

func (r *Recorder) RecordTool(name string, d time.Duration)

RecordTool aggregates a tool execution latency.

func (*Recorder) Snapshot

func (r *Recorder) Snapshot() TimingSnapshot

Snapshot returns an immutable copy of recorder state.

func (*Recorder) StartTurn

func (r *Recorder) StartTurn()

StartTurn marks the beginning of an LLM turn.

type RegistersInFileMutationQueue

type RegistersInFileMutationQueue interface {
	RegistersInFileMutationQueue() bool
}

RegistersInFileMutationQueue is implemented by a tool whose ReserveMutationOrder registers the call in the file mutation queue (the edit and write tools).

type RunToolCallOptions

type RunToolCallOptions struct {
	ToolCallHooks
	// Tools the call resolves against.
	Tools []AgentTool
	// OnUpdate receives the tool's progress updates.
	OnUpdate ToolUpdateSink
	// AssistantMessage is the message that issued the call. The before and after hooks read it through [ToolCallHookContextFrom].
	AssistantMessage *AssistantMessage
	// Context is the agent context the call runs in. The hooks read it through [ToolCallHookContextFrom].
	Context AgentContext
}

RunToolCallOptions configures RunToolCall. Mirrors upstream RunToolCallOptions (packages/agent/src/agent-loop.ts runToolCall); the context argument of RunToolCall is upstream's signal.

type SessionInfoChangedEvent

type SessionInfoChangedEvent struct {
	Name string
}

SessionInfoChangedEvent reports the effective Session name; an empty name clears it.

type StartWindow

type StartWindow struct {
	// contains filtered or unexported fields
}

StartWindow is the window of one extension tool call: it is open from the call's start until the call's synchronous prefix is over. Close ends it, and AwaitSettled returns once every edit or write call that waited for it registered in the file mutation queue, which Pi has done before the extension's own later registration when the extension tool awaited something first.

func ToolStartWindowFromContext

func ToolStartWindowFromContext(ctx context.Context, toolCallID string) *StartWindow

ToolStartWindowFromContext returns the window of the call toolCallID, for a tool that MayTakeFileMutationQueue. The tool closes it when its synchronous prefix is over, which is Pi's first await of the tool's execute: an extension's host call that returns a Promise, a report that its handler awaits, or its answer. It returns nil for a call that holds no window. Close is idempotent, and the dispatcher closes the window when the call ends, so a tool that never closes it holds nobody back for long.

func (*StartWindow) AwaitSettled

func (w *StartWindow) AwaitSettled()

AwaitSettled returns once every call that waited for the window registered (at once when none did, once the dispatcher has prepared its batch).

func (*StartWindow) Close

func (w *StartWindow) Close()

Close ends the window. It is idempotent.

type StreamFn

type StreamFn func(ctx context.Context, model *ai.Model, transcript ai.TranscriptContext, options ai.StreamOptions) (*ai.AssistantMessageEventStream, error)

StreamFn starts one provider request for an already normalized transcript. Mirrors upstream StreamFn.

func GetDefaultStreamFn

func GetDefaultStreamFn() (StreamFn, error)

GetDefaultStreamFn returns the configured host stream function, or an error when no host has installed one.

type SummarizationRetryAttemptStartEvent

type SummarizationRetryAttemptStartEvent struct {
	Source string
	Reason string
}

SummarizationRetryAttemptStartEvent fires after the backoff sleep, right before the retried summarization call. Source is "compaction" or "branchSummary"; Reason ("manual"|"threshold"|"overflow") applies to compaction and lets the TUI recreate the right status indicator. Mirrors upstream summarization_retry_attempt_start (agent-session.ts:173).

type SummarizationRetryFinishedEvent

type SummarizationRetryFinishedEvent struct{}

SummarizationRetryFinishedEvent fires once when a retried summarization loop ends. Mirrors upstream summarization_retry_finished (agent-session.ts:179).

type SummarizationRetryScheduledEvent

type SummarizationRetryScheduledEvent struct {
	Attempt      int
	MaxAttempts  int
	DelayMs      int
	ErrorMessage string
}

SummarizationRetryScheduledEvent fires before the backoff sleep of each retry of a compaction or branch-summary summarization call. Mirrors upstream summarization_retry_scheduled (agent-session.ts:167).

type ThinkingLevel

type ThinkingLevel = ai.ModelThinkingLevel

ThinkingLevel is the agent's reasoning level: "off" or an ai.ThinkingLevel (types.ts ThinkingLevel). It is ai.ModelThinkingLevel.

type ThinkingLevelChangedEvent

type ThinkingLevelChangedEvent struct {
	Level ai.ModelThinkingLevel
}

ThinkingLevelChangedEvent reports an effective reasoning-level change.

type TimingEvent deprecated

type TimingEvent = timingEvent

TimingEvent retains the former diagnostic event shape for source compatibility. The agent no longer emits timing events, matching Pi's event stream.

Deprecated: Read Agent.Timings or observe TurnEndEvent and ToolExecutionEndEvent.

type TimingSnapshot

type TimingSnapshot struct {
	Total       time.Duration
	TurnCount   int
	ToolTotals  map[string]time.Duration
	ToolCounts  map[string]int
	CurrentTurn time.Duration // 0 if idle

	// Token usage. Populated externally (not by Recorder itself) -
	// the caller fills these before passing to formatCostSummary.
	TotalIn    int
	TotalOut   int
	CacheRead  int
	CacheWrite int
	// Cost is the accumulated per-turn cost (USD), tier/cache-aware.
	Cost float64
}

TimingSnapshot is an immutable copy of recorder state.

type ToolCallHookContext

type ToolCallHookContext struct {
	// AssistantMessage issued the tool call. Nil for a RunToolCall made without one.
	AssistantMessage *AssistantMessage
	// Context is the agent context (messages and tools) the call runs in.
	Context AgentContext
}

ToolCallHookContext is what Pi hands a tool-call hook beside the call itself: the assistant message that issued the call and the agent context at that point.

A before or after hook receives it through its context.Context (ToolCallHookContextFrom); the loop and RunToolCall attach it before the hooks run.

upstream: packages/agent/src/types.ts BeforeToolCallContext / AfterToolCallContext (assistantMessage, context)

func ToolCallHookContextFrom

func ToolCallHookContextFrom(ctx context.Context) (ToolCallHookContext, bool)

ToolCallHookContextFrom returns the hook context a tool-call hook runs with.

type ToolCallHookResult

type ToolCallHookResult struct {
	Block     bool
	Reason    string
	Terminate bool
	// Mutated args (if the hook wants to rewrite them). They execute without
	// revalidation, as upstream executes a hook's mutated args.
	Args json.RawMessage
	// Err is the error the hook threw. Upstream's beforeToolCall throws instead (agent-loop.ts prepareToolCall catch): the tool does not run and its error result carries Err's message, even an empty one, with no default reason and no terminate.
	Err error
}

ToolCallHookResult controls whether tool execution proceeds.

Mirrors upstream BeforeToolCallResult. Terminate on a blocked call joins the batch early-termination rule: the agent stops after the batch only when every finalized result in it terminates.

type ToolCallHooks

type ToolCallHooks struct {
	BeforeToolCall      BeforeToolCallFunc
	AfterToolCall       AfterToolCallFunc
	BeforeToolCallHooks []BeforeToolCallHook
	AfterToolCallHooks  []AfterToolCallHook
	PrepareToolResult   func(context.Context, AgentToolResult) AgentToolResult
}

ToolCallHooks are the hooks a tool call runs through. Mirrors upstream ToolCallHooks.

type ToolEnvironment

type ToolEnvironment struct {
	SessionID      string
	SessionFile    string
	Provider       string
	Model          string
	ThinkingLevel  string
	InputLimits    *ai.ModelInputLimits
	SupportsImages *bool
}

ToolEnvironment is the session state a tool may expose to the processes it starts. Upstream's bash tool exports it as PI_SESSION_ID, PI_SESSION_FILE, PI_PROVIDER, PI_MODEL, and PI_REASONING_LEVEL. Empty fields are not exported. Image metadata supplies the selected model profile to read tools.

func ToolEnvironmentFrom

func ToolEnvironmentFrom(ctx context.Context) (ToolEnvironment, bool)

ToolEnvironmentFrom returns the environment the agent attached to a tool call.

type ToolExecutionEndEvent

type ToolExecutionEndEvent struct {
	ToolCallID string
	ToolName   string
	Result     AgentToolResult
	// IsError is upstream's `event.isError`: the call failed, whether the tool threw, returned `isError`, or an
	// afterToolCall hook said so. It is not Result.IsError. upstream: agent-loop.ts:912-919
	IsError bool
	// DurationMs is the milliseconds the tool's execute() took, measured with a monotonic clock; nil when the tool did not run.
	// upstream: agent/src/types.ts tool_execution_end.durationMs
	DurationMs *int64
	// ParentToolCallID is set on the events of a call another tool made through `ctx.executeTool()`. upstream: agent-session.ts:182-189 (WithParentToolCallId)
	ParentToolCallID string
}

type ToolExecutionMode

type ToolExecutionMode string

ToolExecutionMode controls parallelism.

const (
	ToolModeSequential ToolExecutionMode = "sequential"
	ToolModeParallel   ToolExecutionMode = "parallel"
)

type ToolExecutionStartEvent

type ToolExecutionStartEvent struct {
	ToolCallID string
	ToolName   string
	ToolLabel  string // human-readable display name (empty = use ToolName)
	Args       json.RawMessage
	// ParentToolCallID is set on the events of a call another tool made through `ctx.executeTool()`. upstream: agent-session.ts:182-189 (WithParentToolCallId)
	ParentToolCallID string
}

type ToolExecutionUpdateEvent

type ToolExecutionUpdateEvent struct {
	ToolCallID string
	ToolName   string
	// PartialResult is the tool's streaming progress. Subsequent updates carry the full accumulated result so far (upstream's onUpdate contract: every update is a complete-so-far snapshot, not a delta). Tool components in the TUI replace their visible body with each update, giving a live tail. upstream: agent-loop.ts:778-786
	PartialResult AgentToolResult
	// Args is the original tool call arguments (same as ToolExecutionStartEvent.Args).
	// Passed through for extensions that need to correlate updates with inputs.
	Args json.RawMessage
	// ParentToolCallID is set on the events of a call another tool made through `ctx.executeTool()`. upstream: agent-session.ts:182-189 (WithParentToolCallId)
	ParentToolCallID string
}

type ToolResultMessage

type ToolResultMessage struct {
	Role       string                        `json:"role"` // "toolResult"
	ToolCallID string                        `json:"toolCallId"`
	ToolName   string                        `json:"toolName"`
	Content    []ai.ToolResultMessageContent `json:"content"`
	// Details is the tool's details value. Nil is no details unless DetailsNull is set.
	Details any `json:"details,omitempty"`
	// DetailsNull marks a nil Details as an explicit JSON null: the tool wrote details: null, and JSON writes
	// `"details":null`. Without it a nil Details is absent and JSON omits the key. It has no effect when Details is set.
	DetailsNull bool      `json:"-"`
	Usage       *ai.Usage `json:"usage,omitempty"`
	// NestedCalls are the calls this tool made to other tools. Kept for the session record; not sent to the model.
	// upstream: .upstream/v0.99.1/packages/ai/src/types.ts:604
	NestedCalls *ai.NestedToolCalls `json:"nestedCalls,omitempty"`
	IsError     bool                `json:"isError"`
	// DurationMs is the milliseconds execute() took, measured with a monotonic clock. Nil when the tool did not run, and for
	// results stored before it was recorded. upstream: ai/src/types.ts ToolResultMessage.durationMs
	DurationMs *int64 `json:"durationMs,omitempty"`
	Timestamp  int64  `json:"timestamp"`
	// contains filtered or unexported fields
}

ToolResultMessage carries one tool execution result back to the LLM. Mirrors upstream pi-ai ToolResultMessage.

func (ToolResultMessage) AppendStringify

func (m ToolResultMessage) AppendStringify(dst []byte) ([]byte, error)

AppendStringify appends the JSON.stringify text of MarshalJSON's output to dst (json.StringifyAppender).

func (ToolResultMessage) Images

func (m ToolResultMessage) Images() []ai.ImageContent

func (ToolResultMessage) MarshalJSON

func (m ToolResultMessage) MarshalJSON() ([]byte, error)

MarshalJSON emits the pi-ai ToolResultMessage object an AgentMessage holding it emits: the "toolResult" role first and an explicit `"details":null` when the tool wrote it.

func (ToolResultMessage) Result

Result is the result a display renders for this message: its content, details and error flag. A message with details: null gives a result that holds details: null.

func (ToolResultMessage) Text

func (m ToolResultMessage) Text() string

type ToolUpdateCallback

type ToolUpdateCallback func(partial AgentToolResult)

ToolUpdateCallback is called when a tool emits a streaming progress update. The partial result is the complete-so-far AgentToolResult, which the tool_execution_update event carries verbatim as `partialResult`. upstream: packages/agent/src/types.ts AgentToolUpdateCallback, agent-loop.ts:778-786

type ToolUpdateSink

type ToolUpdateSink = func(partial AgentToolResult) error

ToolUpdateSink receives the progress updates of a tool call that RunToolCall runs. A non-nil error is upstream's rejected promise: the update is not delivered further, later updates still reach the sink, and the call fails with the first error once the tool returns.

upstream: agent-loop.ts:685 (ToolUpdateSink), 820-849 (executePreparedToolCall)

type TurnEndEvent

type TurnEndEvent struct {
	TurnIndex          int
	Message            AgentMessage
	ToolResults        []ToolResultMessage
	MessageEntryID     string
	ToolResultEntryIDs []string
}

type TurnStartEvent

type TurnStartEvent struct {
	TurnIndex int
	Timestamp time.Time
}

type UserMessage

type UserMessage struct {
	Role      string         `json:"role"` // "user"
	Content   ai.UserContent `json:"content"`
	Timestamp int64          `json:"timestamp"`
	// contains filtered or unexported fields
}

UserMessage is a user turn whose content retains the upstream string-or-block-array shape.

func (*UserMessage) LLMMessage

func (m *UserMessage) LLMMessage() ai.UserMessage

LLMMessage retains the user content variant and normalizes an omitted Go content value to an empty array.

Jump to

Keyboard shortcuts

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