agentcore

package
v1.2.10 Latest Latest
Warning

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

Go to latest
Published: Oct 8, 2026 License: MIT Imports: 7 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package agentcore defines the core "leaf" data types and control flow for the golder agent harness, a Go reimplementation of the pi agent loop. It is the foundation package that every other agent sub-package depends on and imports nothing from them.

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

Index

Constants

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

Content type discriminants, matching pi's wire format.

View Source
const (
	ToolCallKindLocal  = "local"
	ToolCallKindServer = "server"
)

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

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

Event type discriminants.

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

Message roles, matching pi's wire format.

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

StopReason values, matching pi.

Variables

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

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

Functions

func ContentToText

func ContentToText(list ContentList) string

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

func SandboxRequestedFromContext

func SandboxRequestedFromContext(ctx context.Context) bool

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

func WithMessageSnapshot

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

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

func WithProgressEmitter

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

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

func WithSandboxRequest

func WithSandboxRequest(ctx context.Context) context.Context

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

Types

type AfterToolCallFunc

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

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

type AfterToolCallResult

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

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

type AgentContext

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

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

type AgentEndEvent

type AgentEndEvent struct {
	Messages []AgentMessage
}

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

func (AgentEndEvent) EventType

func (AgentEndEvent) EventType() string

type AgentEvent

type AgentEvent interface {

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

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

type AgentLoopTurnUpdate

type AgentLoopTurnUpdate struct {
	Context       *AgentContext
	Model         *string
	ThinkingLevel *ThinkingLevel
}

AgentLoopTurnUpdate is the optional result of the prepareNextTurn hook: it can swap the context, model, or thinking level for the next turn. Pointer fields distinguish "not provided" from an explicit value; ThinkingLevel is three-state (nil = keep, &"off" = disable, &level = set).

type AgentMessage

type AgentMessage = Message

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

type AgentStartEvent

type AgentStartEvent struct {
	SessionID string
}

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

func (AgentStartEvent) EventType

func (AgentStartEvent) EventType() string

type AgentTool

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

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

type AgentToolCall

type AgentToolCall struct {
	ID        string          `json:"id"`
	Name      string          `json:"name"`
	Arguments json.RawMessage `json:"arguments"`
}

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

type AgentToolResult

type AgentToolResult struct {
	Content   ContentList `json:"content"`
	Details   any         `json:"details,omitempty"`
	Terminate *bool       `json:"terminate,omitempty"`
}

AgentToolResult is the outcome of executing a tool.

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

type AssistantMessage

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

	// Optional diagnostics, kept for cross-provider replay/observability.
	ResponseModel string `json:"responseModel,omitempty"`
	ResponseID    string `json:"responseId,omitempty"`
}

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

func LastAssistantOf

func LastAssistantOf(msgs []AgentMessage) *AssistantMessage

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

func (AssistantMessage) Role

func (m AssistantMessage) Role() string

func (AssistantMessage) ToolCalls

func (m AssistantMessage) ToolCalls() []ToolCallContent

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

type BeforeToolCallDecision

type BeforeToolCallDecision struct {
	Block        bool
	Content      *ContentList
	Details      *any
	UpdatedInput json.RawMessage
	// Sandbox asks the execution layer to run this call under OS-level
	// isolation (e.g. a permission gate graded the command into a sandbox
	// tier). The executor publishes the request into the context the tool
	// executes with (SandboxRequestedFromContext); a tool that cannot isolate
	// must fail closed. Ignored when Block is set.
	Sandbox bool
}

BeforeToolCallDecision is the optional result of the beforeToolCall hook. When Block is true the tool is not executed and an error result is produced; Content/Details override the default block message when set. When Block is false, UpdatedInput (when non-empty) replaces the tool's raw arguments before execution (PreToolUse rewrite, FR-8; the replacement is re-validated against the tool schema) and Sandbox asks for OS-level isolation of the call.

type BeforeToolCallFunc

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

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

type CompactionEvent

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

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

func (CompactionEvent) EventType

func (CompactionEvent) EventType() string

type CompactionMessage

type CompactionMessage struct {
	RoleField    string `json:"role"`
	Summary      string `json:"summary"`
	TokensBefore int    `json:"tokensBefore,omitempty"`
	// Details is opaque at this layer (the compaction package owns its shape);
	// kept as raw JSON so agentcore stays free of a compaction dependency.
	Details   json.RawMessage `json:"details,omitempty"`
	Timestamp int64           `json:"timestamp"`
}

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

func (CompactionMessage) AsUserMessage

func (m CompactionMessage) AsUserMessage() UserMessage

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

func (CompactionMessage) Role

func (m CompactionMessage) Role() string

type CompactionStartEvent

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

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

func (CompactionStartEvent) EventType

func (CompactionStartEvent) EventType() string

type Content

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

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

type ContentList

type ContentList []Content

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

func (*ContentList) UnmarshalJSON

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

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

type ContextUsageEvent added in v1.2.3

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

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

func (ContextUsageEvent) EventType added in v1.2.3

func (ContextUsageEvent) EventType() string

type EmitFunc

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

EmitFunc emits a loop-level AgentEvent honoring cancellation.

func ProgressEmitterFromContext

func ProgressEmitterFromContext(ctx context.Context) EmitFunc

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

type EventStream

type EventStream[T any, R any] struct {

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

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

Design (research §2.2):

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

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

func NewEventStream

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

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

func (*EventStream[T, R]) Close

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

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

func (*EventStream[T, R]) Emit

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

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

func (*EventStream[T, R]) Events

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

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

func (*EventStream[T, R]) Result

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

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

func (*EventStream[T, R]) SetError

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

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

func (*EventStream[T, R]) SetResult

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

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

type ImageContent

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

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

func NewImageContent

func NewImageContent(data, mimeType string) ImageContent

NewImageContent returns an ImageContent with the type discriminant set.

type Message

type Message interface {

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

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

type MessageEndEvent

type MessageEndEvent struct {
	Message AgentMessage
}

MessageEndEvent is emitted when a message finishes streaming.

func (MessageEndEvent) EventType

func (MessageEndEvent) EventType() string

type MessageList

type MessageList []Message

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

func MessageSnapshotFromContext

func MessageSnapshotFromContext(ctx context.Context) MessageList

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

func (*MessageList) UnmarshalJSON

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

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

type MessageStartEvent

type MessageStartEvent struct {
	Message AgentMessage
}

MessageStartEvent is emitted when a message begins streaming.

func (MessageStartEvent) EventType

func (MessageStartEvent) EventType() string

type MessageUpdateEvent

type MessageUpdateEvent struct {
	Message               AgentMessage
	AssistantMessageEvent any
}

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

func (MessageUpdateEvent) EventType

func (MessageUpdateEvent) EventType() string

type PrepareArgumentsFunc

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

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

type SubAgentProgressEvent

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

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

func (SubAgentProgressEvent) EventType

func (SubAgentProgressEvent) EventType() string

type TelemetryEvent

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

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

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

func (TelemetryEvent) EventType

func (TelemetryEvent) EventType() string

type TextContent

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

TextContent is a plain text block.

func NewTextContent

func NewTextContent(text string) TextContent

NewTextContent returns a TextContent with the type discriminant set.

type ThinkingContent

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

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

func NewThinkingContent

func NewThinkingContent(thinking string) ThinkingContent

NewThinkingContent returns a ThinkingContent with the type discriminant set.

type ThinkingLevel

type ThinkingLevel string

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

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

type ThinkingLevelMap

type ThinkingLevelMap map[ThinkingLevel]*string

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

type ToolCallContent

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

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

func NewServerToolCallContent

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

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

func NewToolCallContent

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

NewToolCallContent returns a ToolCallContent with the type discriminant set.

func (ToolCallContent) IsServer

func (c ToolCallContent) IsServer() bool

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

func (ToolCallContent) MarshalJSON

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

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

type ToolExecutionEndEvent

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

ToolExecutionEndEvent is emitted when a tool finishes.

func (ToolExecutionEndEvent) EventType

func (ToolExecutionEndEvent) EventType() string

type ToolExecutionMode

type ToolExecutionMode string

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

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

type ToolExecutionStartEvent

type ToolExecutionStartEvent struct {
	ToolCallID string
	ToolName   string
	Args       any
}

ToolExecutionStartEvent is emitted before a tool runs.

func (ToolExecutionStartEvent) EventType

func (ToolExecutionStartEvent) EventType() string

type ToolExecutionUpdateEvent

type ToolExecutionUpdateEvent struct {
	ToolCallID    string
	ToolName      string
	PartialResult AgentToolResult
}

ToolExecutionUpdateEvent carries a partial result during tool execution.

func (ToolExecutionUpdateEvent) EventType

func (ToolExecutionUpdateEvent) EventType() string

type ToolResultMessage

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

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

func (ToolResultMessage) Role

func (m ToolResultMessage) Role() string

type ToolTiming

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

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

type ToolUpdateFunc

type ToolUpdateFunc func(partial AgentToolResult)

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

type TurnEndEvent

type TurnEndEvent struct {
	Message     AssistantMessage
	ToolResults []ToolResultMessage
}

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

func (TurnEndEvent) EventType

func (TurnEndEvent) EventType() string

type TurnStartEvent

type TurnStartEvent struct{}

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

func (TurnStartEvent) EventType

func (TurnStartEvent) EventType() string

type Usage

type Usage struct {
	InputTokens  int `json:"inputTokens"`
	OutputTokens int `json:"outputTokens"`
}

Usage reports token accounting for an assistant response.

type UserMessage

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

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

func (UserMessage) Role

func (m UserMessage) Role() string

Jump to

Keyboard shortcuts

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