Documentation
¶
Index ¶
- Constants
- Variables
- func BackgroundText(text string) *responses.FunctionCallOutputMessage
- func ClientToolOutput(content json.RawMessage) string
- func CloseBackgroundTaskStream(ctx context.Context, broker StreamBroker, ref BackgroundTaskRef) error
- func DeliverBackgroundResult(ctx context.Context, broker StreamBroker, ref BackgroundTaskRef, ...) (start bool, msg history.Message, err error)
- func ExecuteGetPromptWithMiddleware(ctx context.Context, middlewares []PromptMiddleware, deps *Dependencies, ...) (string, error)
- func ExecuteLoadMessagesWithMiddleware(ctx context.Context, middlewares []HistoryMiddleware, ...) ([]history.ConversationMessage, error)
- func ExecuteModelCallWithMiddleware(ctx context.Context, middlewares []ModelCallMiddleware, call *ModelCall, ...) (*responses.Response, error)
- func ExecuteSaveMessagesWithMiddleware(ctx context.Context, middlewares []HistoryMiddleware, ...) error
- func InvokeModelCall(ctx context.Context, provider llm.Provider, call *ModelCall, ...) (*responses.Response, error)
- func IsModelCallAborted(err error) bool
- func IsModelStreamTransformError(err error) bool
- func IsTerminalModelCallError(err error) bool
- func IsToolCallAborted(err error) bool
- func ModelCallText(text string) *responses.Response
- func ModelStreamCommitted(err error) bool
- func ReadSkillWithMiddleware(ctx context.Context, client SkillClient, namespace string, rc map[string]any, ...) (string, error)
- func RunStoppable[T any](ctx context.Context, watcher StopWatcher, grace time.Duration, streamID string, ...) (T, error)
- func StopCancelContext(ctx context.Context, watcher StopWatcher, streamID string) (context.Context, context.CancelFunc)
- func StreamIDForTask(namespace, threadID, taskID string) string
- func StreamIDForThread(namespace, threadID string) string
- func WithModelStreamTransform(ctx context.Context, transform ModelStreamTransform) context.Context
- func WrapHistoryPersistence(p history.ConversationPersistenceAdapter, middlewares ...HistoryMiddleware) history.ConversationPersistenceAdapter
- type A2A
- type A2AAuthorizer
- type A2AOption
- type Accumulator
- type Agent
- func (a *Agent) A2A(card *a2a.AgentCard, opts ...A2AOption) *A2A
- func (e *Agent) AddHandoffs(handoffs ...*Handoff)
- func (e *Agent) Execute(ctx context.Context, in *AgentInput) (*AgentHandle, error)
- func (e *Agent) ExecuteLocal(ctx context.Context, in *AgentInput) (output *AgentOutput, executionErr error)
- func (e *Agent) ExecuteWithRun(ctx context.Context, in *AgentInput, run *history.ConversationRunManager) (*AgentOutput, error)
- func (e *Agent) ExecuteWithoutTrace(ctx context.Context, in *AgentInput) (*AgentOutput, error)
- func (e *Agent) GetRunID(ctx context.Context) string
- func (e *Agent) History() *history.CommonConversationManager
- func (e *Agent) ListSkills(ctx context.Context, namespace string, runContext map[string]any, ...) ([]ListedSkill, error)
- func (e *Agent) MCPClient() MCPClient
- func (e *Agent) PrepareHandoffTools(ctx context.Context) []Tool
- func (e *Agent) PrepareMCPTools(ctx context.Context, in *AgentInput) ([]ConnectorStatus, []Tool, error)
- func (e *Agent) Run(ctx context.Context, in *AgentInput) (result *AgentOutput, err error)
- func (e *Agent) SingleTurn() bool
- func (e *Agent) StickyHandoff() bool
- func (e *Agent) Stop(ctx context.Context, streamID string) error
- func (e *Agent) StreamBroker() StreamBroker
- func (e *Agent) ToolExecutor() ToolExecutor
- func (e *Agent) WaitForBackgroundTasks()
- func (e *Agent) WithLLM(wrappedLLM LLM) *Agent
- type AgentHandle
- func (h *AgentHandle) Cancel(ctx context.Context) error
- func (h *AgentHandle) EnqueueMessage(ctx context.Context, msg history.Message) error
- func (h *AgentHandle) Result() (*AgentOutput, error)
- func (h *AgentHandle) Stop(ctx context.Context) error
- func (h *AgentHandle) Wait(contexts ...context.Context) (*AgentOutput, error)
- type AgentInput
- type AgentOptions
- type AgentOutput
- type BackgroundResult
- type BackgroundRunner
- type BackgroundTaskRef
- type BackgroundTool
- type BaseTool
- type BrokerAwareToolExecutor
- type ClientToolDefinition
- type ClientToolOptions
- type ConnectorStatus
- type DefaultToolExecutor
- type DeferredToolInfo
- type Dependencies
- type DurableStep
- type ExecutableToolCall
- type GetPromptFunc
- type Handoff
- type HandoffTarget
- type HandoffTool
- type HistoryMiddleware
- type Input
- type LLM
- type ListedSkill
- type LoadMessagesFunc
- type LoadMessagesRequest
- type MCPClient
- type MCPListing
- type MCPSelection
- type MCPToolSelection
- type MCPToolset
- type Middleware
- type MiddlewareAwareToolExecutor
- type ModelCall
- type ModelCallError
- type ModelCallFunc
- type ModelCallMiddleware
- type ModelStreamTransform
- type ModelTargetProvider
- type NoopMiddleware
- func (NoopMiddleware) WrapGetPrompt(next GetPromptFunc) GetPromptFunc
- func (NoopMiddleware) WrapLoadMessages(next LoadMessagesFunc) LoadMessagesFunc
- func (NoopMiddleware) WrapModelCall(next ModelCallFunc) ModelCallFunc
- func (NoopMiddleware) WrapSaveMessages(next SaveMessagesFunc) SaveMessagesFunc
- func (NoopMiddleware) WrapToolCall(next ToolCallFunc) ToolCallFunc
- type ProgressReporter
- type PromptMiddleware
- type ReadSkillInput
- type Registry
- type RunClaimBroker
- type RunEvent
- type RunFeed
- type Runtime
- type SaveMessagesFunc
- type SaveMessagesRequest
- type Skill
- type SkillClient
- type SkillReadExecutor
- type SkillSelection
- type StaticAgents
- type StopMiddleware
- type StopWatcher
- type StreamBroker
- type StreamReplayReader
- type SystemPromptProvider
- type Tool
- type ToolAnnotations
- type ToolCall
- type ToolCallFunc
- type ToolCallMiddleware
- type ToolCallResponse
- func ExecuteToolCallWithMiddleware(ctx context.Context, middlewares []ToolCallMiddleware, tool *BaseTool, ...) (*ToolCallResponse, error)
- func ExecuteToolWithMiddleware(ctx context.Context, middlewares []ToolCallMiddleware, exec ExecutableToolCall, ...) (*ToolCallResponse, error)
- func ExecuteWithTrace(ctx context.Context, tool Tool, params *ToolCall, ...) (*ToolCallResponse, error)
- func ToolCallResult(call *ToolCall, output string) *ToolCallResponse
- type ToolExecution
- type ToolExecutionResult
- type ToolExecutor
- type ToolProgress
- type ToolSearchInput
- type ToolSearchTool
- type ToolsetError
- type ToolsetErrorKind
- type WrappedLLM
Constants ¶
const ( RunEventStarted = "RUN_STARTED" RunEventFinished = "RUN_FINISHED" )
Run lifecycle events, in the vocabulary the AG-UI stream uses.
const DefaultCancelGrace = 2 * time.Second
DefaultCancelGrace bounds how long a cancelled call may take to unwind. Long enough that a clean unwind is never cut off, short enough that a tool ignoring ctx doesn't leave the stop looking broken.
const DefaultClientToolTimeout = 30 * time.Second
DefaultClientToolTimeout is how long a client tool call waits for the client's result, when no timeout is configured, before the run pauses on it.
const ReadSkillToolName = "read_skill"
ReadSkillToolName is the name the model calls to read a skill. The prompt names the same tool, so the two never drift apart.
const SkillFileName = "SKILL.md"
SkillFileName is the file a skill folder must contain. Everything else in the folder is a bundled resource the skill can point the model at.
const StreamBufferSize = 256
StreamBufferSize bounds the pending event backlog for one handle.
Variables ¶
var ErrBackgroundUnsupported = fmt.Errorf("background tool tasks are not supported by this runtime")
ErrBackgroundUnsupported is returned when a tool starts a background task under a runtime that cannot wait for one.
The wait outlives the call that started it, which is exactly what a durable runtime cannot express as an ordinary goroutine: the activity or step ends and takes the wait with it, so the task would run to completion and no one would ever hear. Failing the run says so, rather than leaving a task that silently never lands.
var ErrModelCallAborted = errors.New("model call aborted by middleware")
ErrModelCallAborted marks an error returned by model middleware itself. Durable runtimes use it to avoid retrying deterministic failures such as missing attachments or denied access. The original error remains unwrap-able.
var ErrModelCallStopped = errors.New("model call cancelled: the run was stopped")
ErrModelCallStopped reports a streaming model call the stop cut short. The loop treats it as the stop it is rather than as a failed call, and ends the run the same way a stop between iterations does.
var ErrStreamOverflow = errors.New("agent stream buffer overflow: event stream is incomplete")
ErrStreamOverflow reports an incomplete event stream; the final output remains available.
var ErrToolCallAborted = errors.New("tool call aborted by middleware")
ErrToolCallAborted is what a run fails with when a middleware returned an error of its own. Every such error is wrapped in it on the way out, so a caller can tell a run a middleware stopped from one a tool broke.
var ErrToolCancelled = errors.New("tool call cancelled: the run was stopped")
ErrToolCancelled reports a call the stop unwound. Executors turn it into ToolExecutionResult.Cancelled.
Functions ¶
func BackgroundText ¶ added in v0.0.17
func BackgroundText(text string) *responses.FunctionCallOutputMessage
BackgroundText is the ordinary result: a line of text for the model.
func ClientToolOutput ¶ added in v0.0.25
func ClientToolOutput(content json.RawMessage) string
ClientToolOutput renders a client's result for the model: a JSON string is used as text, and any other JSON value is passed through as JSON text.
func CloseBackgroundTaskStream ¶ added in v0.0.17
func CloseBackgroundTaskStream(ctx context.Context, broker StreamBroker, ref BackgroundTaskRef) error
CloseBackgroundTaskStream ends a task's own stream, so a client watching it sees the task end when it ends rather than when the agent has finished reacting to it.
func DeliverBackgroundResult ¶ added in v0.0.17
func DeliverBackgroundResult( ctx context.Context, broker StreamBroker, ref BackgroundTaskRef, result BackgroundResult, awaitErr error, ) (start bool, msg history.Message, err error)
DeliverBackgroundResult puts a finished task's outcome in front of the agent, and reports whether a new run has to be started to react to it.
The decision is shared by every runtime because getting it wrong is the same mistake everywhere: joining a run that has ended strands the result, and starting one that has not leaves two runs writing one stream. Only the act of starting differs — a goroutine here, a workflow there — and that is left to the caller.
A true return means the caller now holds the channel's claim and must start a run with msg as its input.
func ExecuteGetPromptWithMiddleware ¶ added in v0.0.17
func ExecuteGetPromptWithMiddleware(ctx context.Context, middlewares []PromptMiddleware, deps *Dependencies, next GetPromptFunc) (string, error)
func ExecuteLoadMessagesWithMiddleware ¶ added in v0.0.17
func ExecuteLoadMessagesWithMiddleware(ctx context.Context, middlewares []HistoryMiddleware, request *LoadMessagesRequest, next LoadMessagesFunc) ([]history.ConversationMessage, error)
func ExecuteModelCallWithMiddleware ¶ added in v0.0.17
func ExecuteModelCallWithMiddleware(ctx context.Context, middlewares []ModelCallMiddleware, call *ModelCall, request *responses.Request, invoke ModelCallFunc) (*responses.Response, error)
ExecuteModelCallWithMiddleware runs invoke through the middleware chain. Durable runtimes call it inside the provider step, so request changes stay transient and are never journaled. A nil call is replaced with an empty one. Middleware errors are marked as terminal; provider errors retain their original classification. A nil response without an error is invalid.
func ExecuteSaveMessagesWithMiddleware ¶ added in v0.0.17
func ExecuteSaveMessagesWithMiddleware(ctx context.Context, middlewares []HistoryMiddleware, request *SaveMessagesRequest, next SaveMessagesFunc) error
func InvokeModelCall ¶ added in v0.0.17
func InvokeModelCall(ctx context.Context, provider llm.Provider, call *ModelCall, request *responses.Request, publish func(*responses.ResponseChunk)) (*responses.Response, error)
InvokeModelCall calls the provider with a request copy and records whether any stream chunk was published.
func IsModelCallAborted ¶ added in v0.0.17
IsModelCallAborted reports whether middleware returned the error.
func IsModelStreamTransformError ¶ added in v0.0.17
IsModelStreamTransformError reports an error raised while middleware was transforming a live model chunk. Resilience middleware must not retry it.
func IsTerminalModelCallError ¶ added in v0.0.17
IsTerminalModelCallError reports whether a durable runtime must not run the call again. This is true after output was published, a policy was exhausted, or middleware returned its own error.
func IsToolCallAborted ¶ added in v0.0.14
IsToolCallAborted reports whether a run ended because a middleware returned an error, as opposed to a tool failing or the caller going away. The middleware's own error stays reachable with errors.Is and errors.As.
func ModelCallText ¶
ModelCallText builds a reply of a single assistant message and no tool calls, so the loop takes it as the model's final word and the turn ends. It is the usual answer of a wrap that refuses a call, such as one over budget.
func ModelStreamCommitted ¶ added in v0.0.17
func ReadSkillWithMiddleware ¶ added in v0.0.25
func ReadSkillWithMiddleware(ctx context.Context, client SkillClient, namespace string, rc map[string]any, name, file string, call *ToolCall, middlewares []ToolCallMiddleware) (string, error)
ReadSkillWithMiddleware runs a read inside a durable execution step. Local tools already receive this wrapping from their ToolExecutor.
func RunStoppable ¶
func RunStoppable[T any]( ctx context.Context, watcher StopWatcher, grace time.Duration, streamID string, fn func(ctx context.Context) (T, error), ) (T, error)
RunStoppable runs fn so that stopping the run stops the work: it cancels fn's context when the stop flag lands on streamID, and abandons an fn that ignores it after grace, returning ErrToolCancelled.
Every runtime calls this from wherever its tools actually run — the local executor, a Temporal activity, a Restate run step — because that's the only place holding a context the tool can honour. Cancelling a durable step from the workflow side ends the waiting, not the work: the step keeps running and a remote MCP server never hears about it.
An abandoned call runs on to its own end, unobserved. Callers crossing a durable boundary must translate ErrToolCancelled into a non-retryable (Temporal) or terminal (Restate) failure, or the runtime re-runs the call the user just cancelled.
It is generic because the shape of a tool's result differs by call site: the loop's executors hand back a *ToolCallResponse, while a Temporal activity interceptor only sees `any`. Both need the same cancellation semantics, and a caller that adapted this by assigning into a captured variable would race the abandoned goroutine.
With no watcher or no stream, this is just fn.
func StopCancelContext ¶
func StopCancelContext(ctx context.Context, watcher StopWatcher, streamID string) (context.Context, context.CancelFunc)
StopCancelContext returns a context that is cancelled when the run on streamID is stopped, so work already in flight can unwind rather than finishing into a run nobody is waiting for.
This is the streaming counterpart of RunStoppable. Model calls unwind cooperatively: the stream reader watches the context, and middleware must honor it too. Abandoning the chain could leave streaming callbacks writing after a durable step returns. Cancellation also reaches the provider request.
With no watcher or no stream, the context is returned unchanged (with a no-op cancel), so a caller can wrap unconditionally.
func StreamIDForTask ¶ added in v0.0.17
StreamIDForTask returns the broker channel a background task streams its progress on.
A task gets a channel of its own rather than sharing the thread's. The thread's channel belongs to whatever run holds it, and a run claiming it resets the transcript — so a task publishing there would have its progress wiped by the next turn, and what survived would be interleaved into another run's stream keyed to a call that run never made.
Like StreamIDForThread it is deterministic, so a client holding the task id can derive the channel rather than being told it. Task ids are expected to be unique per task: two tasks sharing one id share one channel.
func StreamIDForThread ¶
StreamIDForThread returns the broker channel a thread's runs stream on.
It is deterministic, so a client that reconnects — or one that never held the id — can derive the same channel and rejoin the run in flight. The namespace is folded in so the same thread id in two namespaces never collides.
A run with no thread to key on gets a random id: nothing could rejoin it anyway, and sharing one channel between unrelated runs would mix their transcripts.
func WithModelStreamTransform ¶ added in v0.0.17
func WithModelStreamTransform(ctx context.Context, transform ModelStreamTransform) context.Context
WithModelStreamTransform installs a response-side transform for the model call beneath it. Multiple transforms compose in middleware response order: the innermost transform runs first. Transforms must not mutate provider chunks.
func WrapHistoryPersistence ¶ added in v0.0.17
func WrapHistoryPersistence(p history.ConversationPersistenceAdapter, middlewares ...HistoryMiddleware) history.ConversationPersistenceAdapter
WrapHistoryPersistence wraps only LoadMessages and SaveMessages. Runtime adapters wrap the real persistence here, then invoke it inside their existing activity/run step. IDs, clocks, summaries, listing and transcripts retain their existing behavior and optional capabilities.
Types ¶
type A2A ¶
type A2A struct {
InvokeHandler http.Handler
AgentCardHandler http.Handler
// contains filtered or unexported fields
}
A2A exposes an agent using the A2A 1.0 JSON-RPC binding. Retain the adapter across requests: its default task store and execution manager are in memory.
type A2AAuthorizer ¶ added in v0.0.17
type A2AAuthorizer interface {
Instructions(ctx context.Context, input *AgentInput, interrupts []responses.Interrupt) (string, error)
Authorize(ctx context.Context, input *AgentInput, interrupts []responses.Interrupt) ([]responses.InterruptResolution, error)
}
A2AAuthorizer bridges the host's trusted out-of-band authorization flow. Instructions must explain how to authorize the pending actions (for example, an approval URL). Authorize waits for a decision and must honor ctx cancellation. Resolutions are internal SDK values; they are never requested over A2A. The host must authenticate the approver and scope decisions to these interrupts.
type A2AOption ¶ added in v0.0.17
type A2AOption func(*A2A)
func WithA2AAuthorizer ¶ added in v0.0.17
func WithA2AAuthorizer(authorizer A2AAuthorizer) A2AOption
func WithA2AHandlerOptions ¶ added in v0.0.17
func WithA2AHandlerOptions(opts ...a2asrv.RequestHandlerOption) A2AOption
WithA2AHandlerOptions configures the upstream task store, queues and limits. Stores and queues must be isolated to this adapter's agent and namespace.
func WithA2ANamespace ¶ added in v0.0.17
WithA2ANamespace binds an adapter to a host-resolved namespace. Client metadata and A2A tenant parameters cannot override it. Use separate adapters per namespace.
type Accumulator ¶
type Accumulator struct {
}
func (*Accumulator) ReadStream ¶
func (a *Accumulator) ReadStream(ctx context.Context, stream chan *responses.ResponseChunk, cb func(chunk *responses.ResponseChunk)) (*responses.Response, error)
ReadStream folds a provider's chunk stream into one response, publishing each chunk as it arrives.
It gives up when ctx is cancelled — which is how a stop ends a model call mid-stream — and reports ErrModelCallStopped. Whatever had accumulated is dropped rather than returned: a stopped run does not answer, and the loop writes its cancellation notice instead. The unread remainder is drained in the background so the provider's sender is never left blocked on a channel nobody is reading.
type Agent ¶
type Agent struct {
Name string
// contains filtered or unexported fields
}
func NewAgent ¶
func NewAgent(opts *AgentOptions) *Agent
func (*Agent) AddHandoffs ¶
AddHandoffs appends handoff edges to the agent after construction.
func (*Agent) Execute ¶
func (e *Agent) Execute(ctx context.Context, in *AgentInput) (*AgentHandle, error)
Execute starts a detached execution with an event subscription. Canceling ctx disconnects the subscription; use Stop to stop the execution.
func (*Agent) ExecuteLocal ¶
func (e *Agent) ExecuteLocal(ctx context.Context, in *AgentInput) (output *AgentOutput, executionErr error)
ExecuteLocal runs the agent's state machine in the calling goroutine. LocalRuntime calls this inside its goroutine; ExecuteWithoutTrace calls it when no runtime is set.
ExecuteLocal owns the broker stream's lifecycle: it closes the stream channel on return so subscribers terminate cleanly. Callers (Agent.Execute, the gateway's runtime workflows, etc.) don't need to call Close themselves.
func (*Agent) ExecuteWithRun ¶
func (e *Agent) ExecuteWithRun(ctx context.Context, in *AgentInput, run *history.ConversationRunManager) (*AgentOutput, error)
func (*Agent) ExecuteWithoutTrace ¶
func (e *Agent) ExecuteWithoutTrace(ctx context.Context, in *AgentInput) (*AgentOutput, error)
ExecuteWithoutTrace dispatches to the configured runtime, falling back to the in-process loop when none is set. Runtime workflow handlers (Temporal, Restate) call this directly after constructing their proxy agent so it skips tracing setup.
func (*Agent) History ¶
func (e *Agent) History() *history.CommonConversationManager
History returns the agent's conversation manager. Callers can use it to inspect stored conversations, e.g. listing threads when the persistence adapter implements history.ThreadLister.
func (*Agent) ListSkills ¶ added in v0.0.17
func (e *Agent) ListSkills(ctx context.Context, namespace string, runContext map[string]any, selection SkillSelection) ([]ListedSkill, error)
ListSkills returns the current catalog for a UI or other caller. A run lists again using its own context; this result is not a reservation or authorization.
func (*Agent) MCPClient ¶ added in v0.0.31
MCPClient returns the agent's MCP client, or nil when it has none. Callers can use it to describe the agent's connectors, e.g. listing them without connecting when the client implements mcpclient.ServerLister.
func (*Agent) PrepareMCPTools ¶
func (e *Agent) PrepareMCPTools(ctx context.Context, in *AgentInput) ([]ConnectorStatus, []Tool, error)
PrepareMCPTools delegates discovery and selection to the agent's configured MCP client.
func (*Agent) Run ¶ added in v0.0.17
func (e *Agent) Run(ctx context.Context, in *AgentInput) (result *AgentOutput, err error)
Run executes synchronously without subscribing to events. Canceling ctx cancels local I/O and signals remote execution through the broker.
func (*Agent) SingleTurn ¶ added in v0.0.17
SingleTurn reports whether the run ends as soon as the model has responded, before any tool is executed.
func (*Agent) StickyHandoff ¶ added in v0.0.17
StickyHandoff reports whether a new turn resumes in the specialist a prior turn ended in, rather than re-entering this agent.
Exported for the same reason StreamBroker and History are: a durable runtime rebuilds the agent on the far side of a boundary, and something has to be able to check that what it rebuilt is what was configured.
func (*Agent) Stop ¶
Stop asks the run on streamID to stop — the same request AgentHandle.Stop makes, for callers that don't hold the handle.
It goes to the broker, so with a shared broker any process holding this agent can stop a run streaming in another. Returning means the request was recorded, not that a run was there to receive it: stopping a finished run, or an unknown stream id, is not an error.
func (*Agent) StreamBroker ¶
func (e *Agent) StreamBroker() StreamBroker
StreamBroker returns the broker the agent streams through, for callers that need the run's channel directly — rejoining a stream in flight, or folding a turn into a live run (see RunClaimBroker).
func (*Agent) ToolExecutor ¶
func (e *Agent) ToolExecutor() ToolExecutor
ToolExecutor returns the executor the agent runs tool calls through — the one it was configured with, after the broker and the agent's tool call middlewares were injected into it.
func (*Agent) WaitForBackgroundTasks ¶ added in v0.0.17
func (e *Agent) WaitForBackgroundTasks()
WaitForBackgroundTasks blocks until every background task this agent started has been delivered.
No run waits on this: a run that starts a task finishes without it, which is the point. It is for shutting down without abandoning work in flight, and for tests that need to observe the delivery rather than race it.
A durable runtime keeps its waits outside this process, so there is nothing here to wait on and this returns at once.
func (*Agent) WithLLM ¶
WithLLM returns a copy of the agent bound to a different LLM. It copies the struct wholesale rather than listing fields: this used to enumerate them, and a field added anywhere else was silently dropped here — the copy simply lost it, with nothing to fail until the behaviour went missing at runtime.
type AgentHandle ¶
type AgentHandle struct {
StreamID string
Chunks <-chan *responses.ResponseChunk
// contains filtered or unexported fields
}
AgentHandle observes one run. Wait is independent of event consumption. Chunks has one consumer and bounded buffering; an incomplete stream is reported by Wait as ErrStreamOverflow alongside the final result.
func (*AgentHandle) Cancel ¶ added in v0.0.17
func (h *AgentHandle) Cancel(ctx context.Context) error
Cancel requests cooperative cancellation, including remote work through the shared broker. Its context bounds the request, not the execution lifetime.
func (*AgentHandle) EnqueueMessage ¶
EnqueueMessage pushes msg onto the run's broker queue. The agent drains the queue at iteration boundaries (alongside the IsStopped check) and folds queued messages into the current run via ProcessIncomingMessages — approval responses become approve/reject queues; other input messages slot into the next LLM call.
Use this to deliver follow-ups (user messages, approval/rejection decisions) to a run that's still in flight. For runs that have already paused and exited, the next agent.Execute on the same thread is the right entry instead.
func (*AgentHandle) Result ¶
func (h *AgentHandle) Result() (*AgentOutput, error)
Result returns the final result. It is equivalent to Wait; event draining is automatic. Prefer Run when no events are needed.
func (*AgentHandle) Stop ¶
func (h *AgentHandle) Stop(ctx context.Context) error
Stop signals the agent to stop and transition to completed state.
A tool call already running has its context cancelled, and is abandoned after a grace period if it ignores that — it keeps running in the background, unobserved. Each cancelled call gets a synthetic result so history keeps its call/result pairing. An in-flight model request has its context cancelled too, including while waiting for HTTP headers.
Reaching a running tool needs a broker implementing StopWatcher (the memory and Redis brokers do); the tool wrapper watches that flag wherever the tool runs. With a plain broker the stop still lands, at the loop's next iteration boundary.
Use Wait or Result to block until the run finishes.
func (*AgentHandle) Wait ¶
func (h *AgentHandle) Wait(contexts ...context.Context) (*AgentOutput, error)
Wait waits for completion. An optional context cancels only this wait, never the execution. Omitting it waits indefinitely. It is safe to call repeatedly or concurrently, without consuming Chunks.
type AgentInput ¶
type AgentInput struct {
// GroupID groups new conversations within a namespace (for example a routine or project). Empty selects "default".
GroupID string `json:"group_id,omitempty"`
// Skills disables user-owned skills by name for this execution, including resumes.
Skills SkillSelection `json:"skills,omitempty"`
MCP MCPSelection `json:"mcp,omitempty"`
// ClientTools are tools the client runs itself for this execution,
// including resumes. Server-side tools win name collisions.
ClientTools []ClientToolDefinition `json:"client_tools,omitempty"`
// RunID optionally identifies this execution. History generates one when omitted.
RunID string `json:"run_id,omitempty"`
Namespace string `json:"namespace"`
ThreadID string `json:"thread_id"`
PreviousRunID string `json:"previous_run_id"`
Message history.Message `json:"messages"`
RunContext map[string]any `json:"run_context"`
// StreamID is the broker channel used for streaming chunks and for
// stop signaling. The runtime and the agent loop use it to publish
// and to poll IsStopped. Execute generates one if empty.
StreamID string `json:"stream_id,omitempty"`
// SessionID is the conversation ID shared by parent agents, sub-agents and
// forked threads. When provided, it also seeds new conversation history.
SessionID string `json:"shared_session_id"`
// contains filtered or unexported fields
}
type AgentOptions ¶
type AgentOptions struct {
History *history.CommonConversationManager
Instruction SystemPromptProvider
Parameters responses.Parameters
Name string
LLM llm.Provider
Output map[string]any
Tools []Tool
Handoffs []*Handoff
// SkillClient lists global and namespace skills once per run; enabled
// skills share the read_skill tool.
SkillClient SkillClient
// ClientTools configures how runs wait for tools the client runs itself.
ClientTools ClientToolOptions
MCPClient MCPClient
Runtime Runtime
MaxLoops *int
ToolExecutor ToolExecutor
StreamBroker StreamBroker
DurableStep DurableStep
StickyHandoff bool
// Middlewares wrap tool/model calls, history LoadMessages/SaveMessages,
// and prompt GetPrompt. Embed NoopMiddleware to override selected methods.
// The first registered is outermost. Each chain executes inside the same
// activity or run step as its underlying operation, never around a durable
// proxy. Middleware may run again if that execution step retries.
Middlewares []Middleware
// BackgroundRunner waits on the tasks this agent's tools start. A durable
// runtime supplies its own, since a goroutine there would end with the
// activity or step that opened it. Left nil, a local agent gets an
// in-process one and a durable agent gets none — see BackgroundRunner.
BackgroundRunner BackgroundRunner
// SingleTurn ends the run as soon as the model has responded, before any
// tool is executed. The returned AgentOutput carries exactly what the model
// emitted — assistant text and/or tool calls — with status completed.
//
// This is for evaluating a single decision rather than an outcome: offline
// single-turn evals score "given this conversation, what does the model do
// next?", where executing the tool (or faking its result) would replace the
// thing under test with an improvised continuation.
//
// Note this is not the same as MaxLoops=1, which still executes the first
// round of tools and then fails the run with "exceeded maximum loops".
SingleTurn bool
}
type AgentOutput ¶
type AgentOutput struct {
RunID string `json:"run_id"`
Status agentstate.RunStatus `json:"status"`
Output []responses.InputMessageUnion `json:"output"`
Interrupts []responses.Interrupt `json:"interrupts,omitempty"`
}
AgentOutput represents the result of agent execution
func (*AgentOutput) Text ¶ added in v0.0.17
func (o *AgentOutput) Text() string
Text concatenates assistant output text in order, excluding reasoning and tool messages. It is safe for nil, empty and multimodal results.
type BackgroundResult ¶ added in v0.0.17
type BackgroundResult struct {
// Output is the result, in the same shape a tool returns from Execute —
// so a task can answer with an image or a file, not only a line of text.
//
// Its CallID is not used: the call that started the task was answered when
// it returned, and a provider will not take a second output against it.
// Only the content travels.
Output *responses.FunctionCallOutputMessage `json:"output,omitempty"`
}
BackgroundResult is what a finished task has to tell the model.
type BackgroundRunner ¶ added in v0.0.17
type BackgroundRunner interface {
StartTask(ctx context.Context, tool BackgroundTool, ref BackgroundTaskRef) error
}
BackgroundRunner begins the wait for a background task. It is how a runtime says what "outliving the call that started it" means where it runs.
In this process it is a goroutine. Under a durable runtime the wait has to outlive the activity or step the tool ran in, so it becomes something that runtime can keep: a detached child workflow under Temporal, a one-way call to another handler under Restate.
StartTask must return promptly. The run does not wait for the task, and a runner that blocked here would make it.
type BackgroundTaskRef ¶ added in v0.0.17
type BackgroundTaskRef struct {
Skills SkillSelection `json:"skills,omitempty"`
MCP MCPSelection `json:"mcp,omitempty"`
// TaskID is what the tool called the task when it answered. It is the
// tool's own identifier — a job id from whatever service it queued work
// with — and nothing here does more than carry it back.
TaskID string `json:"task_id"`
// CallID is the tool call that started the task. Progress published while
// the task runs is keyed to it, so a client that already drew the call
// updates that row rather than growing a new one.
CallID string `json:"call_id"`
ToolName string `json:"tool_name"`
// AgentName is the agent the run entered at — the one that owns the
// thread, and the one a run started by this task's result enters at.
// After a handoff that is not the agent whose loop called the tool.
AgentName string `json:"agent_name"`
Namespace string `json:"namespace"`
ThreadID string `json:"thread_id"`
SessionID string `json:"session_id"`
// TaskStreamID is the task's own broker channel, where its progress is
// published. Nothing else writes to it and no run resets it, so progress
// survives whatever the thread does in the meantime and stays replayable
// to a client that subscribes late. It closes when the task ends.
TaskStreamID string `json:"task_stream_id"`
// ThreadStreamID is the thread's channel, where the result is delivered
// when the task ends — into the run holding it, or as a new run.
ThreadStreamID string `json:"thread_stream_id"`
// RunID is the run that started the task, for correlation. The run itself
// is usually finished by the time the task is.
RunID string `json:"run_id,omitempty"`
// RunContext is the run context of the call that started the task, so a
// run started by its completion carries the same per-tenant data.
RunContext map[string]any `json:"run_context,omitempty"`
// ClientTools are the tools the client offered the run that started the
// task. A run started by its completion offers them again: the server
// learns a client's tools only from the request that starts a run, and
// nobody sends one for this run. The client that offered them may be gone
// by then; a call nobody answers pauses the run like any other.
ClientTools []ClientToolDefinition `json:"client_tools,omitempty"`
// Payload is whatever the tool set on the response that started the task.
// It is how the call's arguments reach the wait, which happens in another
// call and, under a durable runtime, in another process.
Payload json.RawMessage `json:"payload,omitempty"`
}
BackgroundTaskRef identifies one background task to the tool waiting on it, and tells that tool where its progress and result belong.
Every field is a plain value, so the same struct describes a task whether the wait happens in this process or somewhere that had to be told about it.
type BackgroundTool ¶ added in v0.0.17
type BackgroundTool interface {
Tool
AwaitTask(ctx context.Context, task BackgroundTaskRef, progress ProgressReporter) (BackgroundResult, error)
}
BackgroundTool is an optional Tool capability: the tool starts work that outlives the call, answers immediately with a task id, and is asked later to wait for the outcome.
Execute returns a ToolCallResponse carrying TaskID — its Output is what the model reads now ("started indexing, job 41ff"), and the run carries on. The agent then calls AwaitTask, and whatever that returns is delivered to the thread when it returns: into the run that started the task if it is still going, or as a new run if the agent has since gone idle.
AwaitTask must block until the task is done. Poll, subscribe, wait on a channel — whatever the underlying service offers. Report progress through the reporter as it goes; it publishes the same tool.progress chunks the tool itself can emit during Execute, so a client sees one continuous account of the call whether the work happened inside it or after it.
Progress publishes to the task's own channel, named by BackgroundTaskRef.TaskStreamID, not to the thread's. It therefore survives whatever the thread does while the task runs, and a client that subscribes late still gets the whole account of it. The channel closes when the task ends.
Returning an error is not the same as a task that failed. An error means the wait itself broke down — the service became unreachable, the poll gave up — and is reported to the model as such. A task that ran and failed is an ordinary result whose Output says so.
func WrapBackgroundTool ¶ added in v0.0.17
func WrapBackgroundTool(agentName string, tool BackgroundTool, middlewares ...ToolCallMiddleware) BackgroundTool
WrapBackgroundTool binds the tool's agent and middleware to its AwaitTask operation. Execute is unchanged: its middleware belongs to the tool executor. Durable runtimes wrap the real tool on the worker, then call AwaitTask inside the wait activity or run step. The returned result is ready to journal.
type BaseTool ¶
type BaseTool struct {
// MCPServerName routes MCP calls across durable execution; ToolCall supplies the namespace.
MCPServerName string `json:"mcp_server_name,omitempty"`
// Name is the tool's own name, without any prefix the model-facing name
// carries. Only sources that have a name of their own set it — an MCP
// server's tools do, a locally defined function tool does not, since for it
// the two are the same name. A middleware is always shown it filled in either way
// (see SerializeTool).
Name string
ToolUnion responses.ToolUnion
RequiresApproval bool
Deferred bool
// Annotations are the tool's self-reported behavioural hints (read-only,
// destructive, ...). Nil when the tool declared none. They ride along with
// the rest of BaseTool across a durable runtime's serialization boundary,
// so a policy on the far side sees the same hints the server sent.
Annotations *ToolAnnotations
Meta map[string]any
}
func SerializeTool ¶ added in v0.0.17
SerializeTool is the tool as a middleware is shown it: plain data, because the real tool may be a proxy for one running in another process, and there is nothing else a middleware could portably be handed. descriptor is what the tool's GetToolDescriptor reports, call the call it is being asked to run.
It is what every path hands a middleware, so a middleware sees the same tool wherever the chain runs: the local executor calls it, and a runtime adapter that runs the chain inside its own activity or step calls it with the real tool's descriptor there. Name is always filled in — only a tool with a name of its own sets it, an MCP server's does and a function tool does not, and a middleware should not have to know which — and the result is never nil.
A tool that cannot describe itself still gets its call checked — refusing to run middlewares over it would fail open — so this always returns something. That something has to carry a ToolUnion: under a durable runtime it crosses to the worker as an argument, and a BaseTool whose union is empty cannot be encoded at all (ToolUnion.MarshalJSON yields no bytes), which would fail the call rather than the identity. Naming it from the call is both encodable and more use to a middleware than nothing.
func (*BaseTool) GetToolDescriptor ¶ added in v0.0.16
GetToolDescriptor implements Tool. A tool that embeds *BaseTool is already the plain data, so this hands back the embedded value itself.
type BrokerAwareToolExecutor ¶
type BrokerAwareToolExecutor interface {
ToolExecutor
// WithStreamBroker returns a copy bound to broker, rather than
// mutating, so an executor shared between agents is never re-pointed
// at another agent's broker.
WithStreamBroker(broker StreamBroker) ToolExecutor
}
BrokerAwareToolExecutor is an optional ToolExecutor capability: the executor wants the run's broker, to watch the stop flag. NewAgent injects the same broker the loop uses.
type ClientToolDefinition ¶ added in v0.0.25
type ClientToolDefinition struct {
Name string `json:"name"`
Description string `json:"description,omitempty"`
Parameters map[string]any `json:"parameters,omitempty"`
}
ClientToolDefinition is one tool a client offers for a run.
type ClientToolOptions ¶ added in v0.0.25
type ClientToolOptions struct {
// Timeout bounds how long a client tool call waits for the client's result
// before the run pauses on it. Defaults to DefaultClientToolTimeout. A
// negative timeout pauses at once, for clients that only answer after the
// run has paused.
Timeout time.Duration
}
ClientToolOptions configures an agent's client tools. The zero value is ready to use.
type ConnectorStatus ¶ added in v0.0.15
type ConnectorStatus struct {
Name string `json:"name"`
Connected bool `json:"connected"`
// ToolCount is what this connector contributed after filtering, so it is
// the number the model can actually call, not the number the server
// publishes.
ToolCount int `json:"tool_count"`
// Kind and Detail are set only when Connected is false. They are the
// classification and the raw cause; turning either into something a model
// reads is the prompt's job, not this package's.
Kind ToolsetErrorKind `json:"kind,omitempty"`
Detail string `json:"detail,omitempty"`
}
ConnectorStatus is how one MCP server fared this run: whether it connected, how many tools it contributed, and — when it did not — why.
Every enabled connector gets one, not just the ones that failed. What the agent has is as much a fact about the run as what it is missing, and a model told a connector holds twelve tools stops guessing at a thirteenth.
Plain data rather than an error because it travels: into the prompt's Dependencies, and across a durable runtime's serialization boundary with it.
func ConnectedConnectorStatus ¶ added in v0.0.25
func ConnectedConnectorStatus(name string, toolCount int) ConnectorStatus
ConnectedConnectorStatus records a connector that listed, and what it brought.
func FailedConnectorStatus ¶ added in v0.0.25
func FailedConnectorStatus(name string, err error) ConnectorStatus
FailedConnectorStatus records a connector that did not list, and why.
type DefaultToolExecutor ¶
type DefaultToolExecutor struct {
// StopWatcher is how this executor learns the run was stopped.
// NewAgent fills it in from the broker; set it directly to override.
// Left nil, tool calls run to completion and the stop is honoured at
// the loop's next iteration boundary.
StopWatcher StopWatcher
// CancelGracePeriod bounds how long a cancelled call may take to
// unwind before it is abandoned. Zero or less selects
// DefaultCancelGrace.
CancelGracePeriod time.Duration
// Middlewares wrap every call this executor runs, whatever the tool's source —
// the agent's own function tools, its sub-agent tools, and every MCP
// server's. This is the only place tool call middlewares run.
//
// Handoffs do not pass through them: transfer_to_agent is settled by the
// loop before anything reaches an executor, and the target agent's own
// middlewares apply to what it then does.
Middlewares []ToolCallMiddleware
}
DefaultToolExecutor executes tool calls sequentially.
func (*DefaultToolExecutor) ExecuteAll ¶
func (e *DefaultToolExecutor) ExecuteAll(ctx context.Context, executions []ExecutableToolCall) []ToolExecutionResult
ExecuteAll runs calls sequentially, with stop middleware outside user middleware.
func (*DefaultToolExecutor) WithStreamBroker ¶
func (e *DefaultToolExecutor) WithStreamBroker(broker StreamBroker) ToolExecutor
WithStreamBroker implements BrokerAwareToolExecutor. A watcher set by the caller wins; injection only fills a gap.
func (*DefaultToolExecutor) WithToolCallMiddlewares ¶ added in v0.0.17
func (e *DefaultToolExecutor) WithToolCallMiddlewares(middlewares []ToolCallMiddleware) ToolExecutor
WithToolCallMiddlewares implements MiddlewareAwareToolExecutor.
type DeferredToolInfo ¶
type DeferredToolInfo struct {
Name string `json:"name"`
Description string `json:"description,omitempty"`
}
DeferredToolInfo is the projection of a deferred Tool that prompt providers actually consume — just the schema's name and description. Kept as a plain struct (not the Tool interface) so Dependencies can JSON-roundtrip across Temporal activity boundaries; the full Tool interface carries closure state (workflow ctx, broker handles, etc.) that doesn't deserialize on the worker side.
type Dependencies ¶
type Dependencies struct {
RunContext map[string]any
Handoffs []*Handoff
DeferredTools []DeferredToolInfo
// Skills contains the enabled catalog for this execution. Legacy providers
// supply their own hint; dynamic sets share read_skill. Only serializable
// metadata crosses a durable prompt boundary, never resolver functions.
Skills []Skill `json:"skills,omitempty"`
SkillHint string `json:"skill_hint,omitempty"`
// Connectors is how each configured MCP server fared when its tools were
// listed for this run — see ConnectorStatus. Every one of them is here,
// connected or not, because a prompt that only ever hears about failures
// cannot tell the model what it does have.
//
// A run with no MCP servers has none, and the resolver that renders these
// leaves such a prompt untouched.
Connectors []ConnectorStatus `json:"connectors,omitempty"`
}
type DurableStep ¶
type DurableStep interface {
Do(fn func())
}
DurableStep runs a side effect exactly once per logical occurrence, even when the agent loop replays under a durable runtime.
The agent loop emits fire-and-forget side effects at run-lifecycle boundaries — publishing run.created / run.completed / run.paused and tool output chunks to the stream broker. Under a durable runtime (Temporal, Restate) the loop re-executes from the top on every replay, so without protection each of these would be resent many times. Wrapping them in a DurableStep collapses them to a single occurrence:
- Local: runs fn immediately (no replay, nothing to guard).
- Temporal: runs fn only at the live edge via workflow.IsReplaying — the canonical Temporal pattern for once-only external actions like logging.
- Restate: runs fn inside restate.RunVoid, a journaled step skipped on replay.
fn must not perform durable-runtime commands (schedule activities, await futures, etc.) — it is for external, best-effort side effects only. Steps are correlated by execution order, which the agent loop keeps deterministic.
type ExecutableToolCall ¶
type GetPromptFunc ¶ added in v0.0.17
type GetPromptFunc func(context.Context, *Dependencies) (string, error)
type Handoff ¶
type Handoff struct {
Name string
Description string
Agent HandoffTarget `json:"-"`
}
type HandoffTarget ¶
type HandoffTarget interface {
ExecuteWithRun(ctx context.Context, in *AgentInput, run *history.ConversationRunManager) (*AgentOutput, error)
}
type HandoffTool ¶
type HandoffTool struct {
*BaseTool
// contains filtered or unexported fields
}
func NewHandoffTool ¶
func NewHandoffTool(t *responses.ToolUnion) *HandoffTool
func (*HandoffTool) Execute ¶
func (t *HandoffTool) Execute(ctx context.Context, params *ToolCall) (*ToolCallResponse, error)
type HistoryMiddleware ¶ added in v0.0.17
type HistoryMiddleware interface {
WrapLoadMessages(LoadMessagesFunc) LoadMessagesFunc
WrapSaveMessages(SaveMessagesFunc) SaveMessagesFunc
}
HistoryMiddleware wraps persistence reads and writes inside their execution boundary. Middleware may return without calling next. Errors propagate to the caller. Treat requests and returned messages as read-only; pass copies when transforming them. Registration order is outermost first.
func HistoryMiddlewaresOf ¶ added in v0.0.17
func HistoryMiddlewaresOf(middlewares []Middleware) []HistoryMiddleware
type Input ¶ added in v0.0.17
type Input = AgentInput
Input is an alias for the common execution input.
type LLM ¶
type LLM interface {
NewStreamingResponses(ctx context.Context, call *ModelCall, in *responses.Request, cb func(chunk *responses.ResponseChunk)) (*responses.Response, error)
}
LLM is the loop's view of the model: one streamed call per iteration. call is the ModelCall the request belongs to, for a runtime that runs the middlewares' WrapModelCall on the far side of a boundary and has to hand it to them.
type ListedSkill ¶ added in v0.0.17
ListedSkill is a catalog entry for clients building a skill picker. Name can be copied directly into SkillSelection. Enabled describes the supplied selection; a Global entry is always enabled.
type LoadMessagesFunc ¶ added in v0.0.17
type LoadMessagesFunc func(context.Context, *LoadMessagesRequest) ([]history.ConversationMessage, error)
type LoadMessagesRequest ¶ added in v0.0.17
type MCPClient ¶ added in v0.0.25
type MCPClient interface {
ListTools(context.Context, string, map[string]any, ...MCPSelection) ([]ConnectorStatus, []Tool, error)
CallTool(context.Context, *BaseTool, *ToolCall) (*ToolCallResponse, error)
}
MCPClient owns discovery, selection, connector status, and execution across MCP servers. Listing failures for individual servers are statuses; store/configuration failures are errors. Implementations must support concurrent namespaces without mutating shared run configuration.
type MCPListing ¶ added in v0.0.25
type MCPListing struct {
Connectors []ConnectorStatus `json:"connectors"`
Tools []BaseTool `json:"tools"`
}
MCPListing crosses durable boundaries using only statuses and tool descriptors.
type MCPSelection ¶ added in v0.0.25
type MCPSelection struct {
Disable []string `json:"disable,omitempty"`
Tools map[string]MCPToolSelection `json:"tools,omitempty"`
}
MCPSelection selects a namespace's own servers and their original, unprefixed tool names for a run. Global servers are mandatory: a run can neither disable them nor narrow their tools, so names of global servers are ignored in both Disable and Tools; narrow those with ServerConfig.ToolFilter or mcpclient.Filter instead. Namespace servers are enabled unless disabled. Unknown names are ignored across handoffs. It mirrors SkillSelection. Selection cannot expose tools excluded by the server's configured ToolFilter.
func (MCPSelection) Clone ¶ added in v0.0.25
func (s MCPSelection) Clone() MCPSelection
Clone isolates mutable selection when a continuation outlives the current run.
type MCPToolSelection ¶ added in v0.0.25
type MCPToolSelection struct {
Include []string `json:"include,omitempty"`
Exclude []string `json:"exclude,omitempty"`
}
MCPToolSelection narrows a namespace-owned server's tools for one run. An empty Include means all configured tools; Exclude wins. Global servers ignore it.
type MCPToolset ¶
type Middleware ¶ added in v0.0.17
type Middleware interface {
ToolCallMiddleware
ModelCallMiddleware
HistoryMiddleware
PromptMiddleware
}
Middleware wraps agent operations. Embed NoopMiddleware and override the Wrap methods relevant to your implementation. All methods are statically checked at registration; first registered middleware is outermost.
type MiddlewareAwareToolExecutor ¶ added in v0.0.17
type MiddlewareAwareToolExecutor interface {
ToolExecutor
// WithToolCallMiddlewares returns a copy bound to middlewares, rather than mutating,
// so an executor shared between agents never runs another agent's middleware.
WithToolCallMiddlewares(middlewares []ToolCallMiddleware) ToolExecutor
}
MiddlewareAwareToolExecutor is an optional ToolExecutor capability: the executor runs the agent's tool call middlewares around each call. NewAgent injects the middlewares the agent was configured with.
The local executor runs them directly. Durable executors leave them on the worker, inside the same step as the tool. An executor that does not implement this capability must arrange middleware at its own execution boundary.
type ModelCall ¶
type ModelCall struct {
AgentName string `json:"agent_name"`
Namespace string `json:"namespace"`
ThreadID string `json:"thread_id"`
SessionID string `json:"session_id,omitempty"`
StreamID string `json:"stream_id,omitempty"`
RunID string `json:"run_id,omitempty"`
RunContext map[string]any `json:"run_context,omitempty"`
// Model is the model the request is addressed to.
Model string `json:"model"`
// Target explicitly overrides routing for this attempt (Provider/model).
Target string `json:"target,omitempty"`
// LoopIteration is the run's loop counter as MaxLoops counts it: zero
// for the first call of the run, one more after each round of tools.
LoopIteration int `json:"loop_iteration"`
// ContextTokens estimates how full the context window is: the last
// measured prompt plus an estimate of everything appended since.
ContextTokens int `json:"context_tokens"`
// Usage is what the run has consumed so far, across all its calls.
Usage responses.Usage `json:"usage"`
// State is a snapshot of the run's key-value scratchpad, the same one
// tools read through ToolCall.State and write through
// ToolCallResponse.StateUpdates. A wrap reads it; writes to the copy
// reach nothing.
State map[string]string `json:"state,omitempty"`
}
ModelCall describes the call a wrap is around: which agent, thread and run it belongs to, the model, and what the run has used so far.
type ModelCallError ¶ added in v0.0.17
ModelCallError tells durable runtimes whether a call must not be retried. The original error remains available through errors.Is and errors.As.
func (*ModelCallError) Error ¶ added in v0.0.17
func (e *ModelCallError) Error() string
func (*ModelCallError) Unwrap ¶ added in v0.0.17
func (e *ModelCallError) Unwrap() error
type ModelCallFunc ¶ added in v0.0.17
type ModelCallFunc func(ctx context.Context, call *ModelCall, request *responses.Request) (*responses.Response, error)
ModelCallFunc sends a request to the provider, on behalf of call, and returns the reply. It is the shape of next in WrapModelCall and of the function a wrap returns.
func WrapModelCall ¶ added in v0.0.17
func WrapModelCall(middlewares []ModelCallMiddleware, next ModelCallFunc) ModelCallFunc
WrapModelCall chains the middleware around next. The first middleware is outermost; nil entries are skipped.
type ModelCallMiddleware ¶ added in v0.0.17
type ModelCallMiddleware interface {
// WrapModelCall returns the function that runs in place of next, with the
// call the request belongs to. Call next to reach the provider: what next
// receives is what the provider is sent, and what the wrap returns is the
// reply. To answer in the model's place, return a reply without calling
// next; ModelCallText builds the usual one. To put a note in front of the
// model for this call only, hand next a copy of the request with the note
// appended: the loop keeps its own request, so the note is never stored.
//
// Return your own error for a middleware failure. Return next's error when
// the provider failed, so retry policies can classify it correctly.
//
// It runs inside the provider step and may run again if that step retries.
// Do not mutate the supplied request. Middlewares are nested in registration
// order; the first registered middleware is outermost.
WrapModelCall(next ModelCallFunc) ModelCallFunc
}
ModelCallMiddleware wraps every model call made by an agent. It can inspect or change the request, short-circuit the call, or inspect the response.
Durable runtimes run middleware inside the same activity or step as the provider call.
func ModelCallMiddlewaresOf ¶ added in v0.0.17
func ModelCallMiddlewaresOf(middlewares []Middleware) []ModelCallMiddleware
ModelCallMiddlewaresOf narrows a middleware list to the model-call side, which is what the agent loop runs.
type ModelStreamTransform ¶ added in v0.0.17
type ModelStreamTransform func(context.Context, *responses.ResponseChunk) (*responses.ResponseChunk, error)
ModelStreamTransform can copy, replace, or suppress one provider stream chunk before it is published. Returning nil suppresses the chunk. Returning an error ends and drains the attempt; the error is classified as a middleware failure, not a provider failure.
type ModelTargetProvider ¶ added in v0.0.17
type ModelTargetProvider interface {
NewStreamingResponsesForModel(context.Context, string, *responses.Request) (chan *responses.ResponseChunk, error)
}
ModelTargetProvider supports explicit per-call routing without changing the provider bound to an agent. Target uses Provider/model notation.
type NoopMiddleware ¶ added in v0.0.17
type NoopMiddleware struct{}
NoopMiddleware supplies pass-through implementations for every operation.
func (NoopMiddleware) WrapGetPrompt ¶ added in v0.0.17
func (NoopMiddleware) WrapGetPrompt(next GetPromptFunc) GetPromptFunc
func (NoopMiddleware) WrapLoadMessages ¶ added in v0.0.17
func (NoopMiddleware) WrapLoadMessages(next LoadMessagesFunc) LoadMessagesFunc
func (NoopMiddleware) WrapModelCall ¶ added in v0.0.17
func (NoopMiddleware) WrapModelCall(next ModelCallFunc) ModelCallFunc
func (NoopMiddleware) WrapSaveMessages ¶ added in v0.0.17
func (NoopMiddleware) WrapSaveMessages(next SaveMessagesFunc) SaveMessagesFunc
func (NoopMiddleware) WrapToolCall ¶ added in v0.0.17
func (NoopMiddleware) WrapToolCall(next ToolCallFunc) ToolCallFunc
type ProgressReporter ¶
type ProgressReporter interface {
Report(ctx context.Context, update ToolProgress)
}
ProgressReporter lets a running tool emit progress updates that stream to the run's client on the same channel as the rest of the run. It is injected into ToolCall.Progress at execution time (never serialized), so it is a runtime-agnostic seam: the local runtime publishes straight to the broker, and durable runtimes re-inject their own reporter inside the tool activity.
Report is best-effort and must be safe to call concurrently and on a nil reporter is guarded by ToolCall.ReportProgress — tool authors should prefer that helper over calling Report directly.
func NewStreamProgressReporter ¶
func NewStreamProgressReporter(broker StreamBroker, streamID, callID, toolName string) ProgressReporter
NewStreamProgressReporter builds a ProgressReporter that publishes tool.progress chunks to the given broker/stream. It exists for runtimes that must re-establish the reporter after a ToolCall crosses a serialization boundary that drops ToolCall.Progress — e.g. the Temporal tool activity, which rebuilds it from the worker's broker and the workflow execution id. It returns nil when broker or streamID is empty, which is nil-safe via ToolCall.ReportProgress and the MCP bridge.
type PromptMiddleware ¶ added in v0.0.17
type PromptMiddleware interface {
WrapGetPrompt(GetPromptFunc) GetPromptFunc
}
PromptMiddleware wraps prompt retrieval inside the provider's execution step. Return a prompt without calling next to short-circuit. Pass copies when modifying dependencies; returned errors propagate to the caller.
func PromptMiddlewaresOf ¶ added in v0.0.17
func PromptMiddlewaresOf(middlewares []Middleware) []PromptMiddleware
type ReadSkillInput ¶
type Registry ¶ added in v0.0.31
type Registry interface {
// Agent returns the agent namespace runs under name. ok is false when the
// namespace has no such agent; an error means the lookup itself failed.
Agent(ctx context.Context, namespace, name string) (agent *Agent, ok bool, err error)
// AgentNames lists the agents namespace can run.
AgentNames(ctx context.Context, namespace string) ([]string, error)
}
Registry finds the agents a namespace can run. Handlers and schedulers ask it on every request, with the namespace they authenticated, so agents may be created per namespace at run time: agentconfig.Registry builds them from stored configs, and another namespace never finds them. Wrap a fixed set of agents built in code with StaticRegistry.
Implementations must be safe for concurrent callers.
func StaticRegistry ¶ added in v0.0.31
func StaticRegistry(set StaticAgents) Registry
StaticRegistry offers the same agents to every namespace — the Registry for agents built in code:
registry := hastekit.NewRegistry()
registry.Register(agent)
http.ListenAndServe(":8080", agui.NewHandler(agents.StaticRegistry(registry)))
type RunClaimBroker ¶
type RunClaimBroker interface {
// EnqueueOrStart atomically routes a turn for streamID:
// - if a run is already live on the channel, it appends msgs to the
// run's queue (tool outputs as EnqueueMessage keeps them) and
// returns started=false;
// - if that run has already published its end, it waits (bounded) for
// the run to release the channel, so a turn sent in answer to the
// end starts the next run instead of joining one that is finishing;
// - otherwise it claims the channel, resets any stale transcript /
// queue / stop state, and returns started=true — the caller then
// Subscribes and runs with msgs as the run's input.
// The claim is released by Close.
EnqueueOrStart(ctx context.Context, streamID string, msgs []history.Message) (started bool, err error)
}
RunClaimBroker is an optional StreamBroker capability that enables deterministic, per-thread stream IDs. With a deterministic streamID the same broker channel is reused across a thread's turns, so EnqueueOrStart must atomically decide, in one shot, whether a turn joins an in-flight run or starts a fresh one — and reset the channel when it starts, so a reused channel never replays a previous turn's transcript.
type RunEvent ¶ added in v0.0.17
type RunEvent = streambroker.RunEvent
RunEvent is one run beginning or ending, as a watcher of a whole namespace sees it.
type RunFeed ¶ added in v0.0.17
type RunFeed interface {
// PublishRunEvent records one run beginning or ending. The namespace is
// passed rather than derived: a channel id is a one-way hash of it.
PublishRunEvent(ctx context.Context, event RunEvent) error
// ReadRunEvents returns what happened in these namespaces after cursor,
// waiting up to wait for something if there is nothing yet.
//
// The returned cursor is opaque and belongs to the implementation; a
// client stores it and passes it back. An empty cursor means "from now",
// not "from the beginning" — a client attaching for the first time wants
// what happens next, not a replay of the day.
ReadRunEvents(ctx context.Context, namespaces []string, cursor string, wait time.Duration) ([]RunEvent, string, error)
}
RunFeed is an optional StreamBroker capability: run lifecycle fanned in per namespace, so a client can watch every conversation in a namespace instead of one thread at a time.
The thread streams cannot answer this. Each is keyed by its own channel, and a conversation that has not started yet has no channel to name — so a client sitting in one conversation could never learn that another had begun. This is a second, much thinner wire alongside them, carrying only the fact that a run started or ended.
It is a feed rather than a broadcast because the interesting runs are the ones nobody was watching: a background task finishing at 3am. A client that reconnects passes back the cursor it last held and is told what it missed, which a fire-and-forget subscription could not do.
type Runtime ¶
type Runtime interface {
// RegisterAgent registers the resolved configuration before execution. NewAgent
// calls it after validation. Runtimes that need no registration may return nil.
RegisterAgent(options *AgentOptions) error
// StreamBroker returns the broker shared by the runtime and its agents.
StreamBroker() StreamBroker
Run(ctx context.Context, agent *Agent, in *AgentInput) (*AgentOutput, error)
}
type SaveMessagesFunc ¶ added in v0.0.17
type SaveMessagesFunc func(context.Context, *SaveMessagesRequest) error
type SaveMessagesRequest ¶ added in v0.0.17
type SaveMessagesRequest struct {
GroupID string
Namespace string `json:"namespace"`
RunID string `json:"run_id"`
PreviousRunID string `json:"previous_run_id,omitempty"`
ThreadID string `json:"thread_id"`
ConversationID string `json:"conversation_id"`
Messages []history.Message `json:"messages"`
Meta map[string]any `json:"meta,omitempty"`
}
type Skill ¶
type Skill struct {
// Global marks a developer-owned skill. Users cannot disable it, and it
// shadows a user-owned skill with the same name. Set by the SkillClient,
// never read from uploaded frontmatter.
Global bool `json:"global,omitempty"`
Name string `json:"name"` // Skill name from SKILL.md frontmatter
Description string `json:"description"` // Skill description from SKILL.md frontmatter
FileLocation string `json:"file_location"` // Path to the SKILL.md file, as a reader would type it
// Resources are the skill's other files, as paths relative to the skill
// folder. read_skill serves them by name; nothing outside this list (and
// SKILL.md itself) is reachable through the tool.
Resources []string `json:"resources,omitempty"`
}
type SkillClient ¶ added in v0.0.25
type SkillClient interface {
ListSkills(ctx context.Context, namespace string, runContext map[string]any) ([]Skill, error)
ReadSkill(ctx context.Context, namespace string, runContext map[string]any, name, file string) (string, error)
}
SkillClient owns an agent's skill catalog: the developer's global skills plus the skills a namespace added itself. It mirrors MCPClient.
ListSkills returns every skill visible to the namespace, globals marked Global. A global shadows a user skill with the same name, so names are unique. An empty namespace lists globals only. ReadSkill resolves by the same precedence: a request for instructions passes an empty file and receives the SKILL.md body without frontmatter; "SKILL.md" returns the original document. Namespace is authoritative and passed explicitly; RunContext is application data. Implementations must be safe for concurrent use.
type SkillReadExecutor ¶ added in v0.0.17
type SkillReadExecutor interface {
ReadSkillCall(ctx context.Context, namespace string, runContext map[string]any, name, file string, call *ToolCall) (string, error)
}
SkillReadExecutor is implemented by durable runtime proxies to carry the tool call to their execution boundary for tracing, stop handling, and middleware. Application SkillClients need only implement ReadSkill.
type SkillSelection ¶ added in v0.0.17
type SkillSelection struct {
Disable []string `json:"disable,omitempty"`
}
SkillSelection disables user-owned skills by name for one run. Global skills cannot be disabled; every other visible skill is enabled unless named here. Unknown names are ignored so one selection can pass through agents with different catalogs during handoffs.
type StaticAgents ¶ added in v0.0.31
StaticAgents is a fixed set of agents built in code, such as *hastekit.AgentRegistry.
type StopMiddleware ¶ added in v0.0.17
type StopMiddleware struct {
NoopMiddleware
Watcher StopWatcher
// CancelGracePeriod applies to tools that ignore cancellation. Zero uses
// DefaultCancelGrace. Model calls must unwind cooperatively because their
// streaming callbacks may still be active.
CancelGracePeriod time.Duration
// StreamID overrides call metadata when the runtime owns the stream ID.
// Otherwise the middleware uses ToolCall.StreamID or ModelCall.StreamID.
StreamID string
}
StopMiddleware cancels the call chain when its stream is stopped. Executors install it inside the execution boundary, outside user middleware. Durable proxies do not install it; the worker owns cancellation.
func (StopMiddleware) WrapModelCall ¶ added in v0.0.17
func (m StopMiddleware) WrapModelCall(next ModelCallFunc) ModelCallFunc
func (StopMiddleware) WrapToolCall ¶ added in v0.0.17
func (m StopMiddleware) WrapToolCall(next ToolCallFunc) ToolCallFunc
type StopWatcher ¶
type StopWatcher interface {
// WatchStop returns a channel closed once Stop has been called for the
// channel (immediately, if it already has), plus a release func the
// caller must invoke.
//
// Implementations must not close it for any other reason, nor before
// the stop is durably recorded: a subsequent IsStopped read has to
// agree, since that read is what ends the run.
WatchStop(ctx context.Context, channel string) (<-chan struct{}, func())
}
StopWatcher is an optional StreamBroker capability that turns the poll-based stop flag into something to wait on. Tool wrappers use it to cancel a call mid-flight, so a stop lands during a long-running tool instead of only at the loop's next iteration boundary.
Remote-backed brokers implement it by polling their own flag; in-process brokers close the channel directly from Stop. The durable-runtime proxies deliberately do not implement it — a poll goroutine is not something a workflow can journal — so under those runtimes the watch runs in the activity or run step instead.
func StopWatcherFrom ¶
func StopWatcherFrom(broker StreamBroker) StopWatcher
StopWatcherFrom returns the broker's stop-watch capability, or nil if it has none.
type StreamBroker ¶
type StreamBroker interface {
// StartHeartbeat starts liveness for this execution and returns an idempotent stop function.
// Stop must finish before Close applies replay retention. Runtime proxies own their scheduling.
StartHeartbeat(ctx context.Context, channel string) (stop func())
// Publish sends a response chunk to subscribers of the given channel.
// The channel is typically the run ID or a unique identifier for the execution.
Publish(ctx context.Context, channel string, chunk *responses.ResponseChunk) error
// Subscribe returns a channel that receives response chunks for the given channel.
// The returned channel will be closed when Close is called or the context is cancelled.
Subscribe(ctx context.Context, channel string) (<-chan *responses.ResponseChunk, error)
// Close signals that no more chunks will be published to the channel.
// This should close all subscriber channels for the given channel.
Close(ctx context.Context, channel string) error
// Stop records a stop request for the given channel. The agent loop
// reads this via IsStopped at iteration boundaries and transitions
// to completed when set. Idempotent.
Stop(ctx context.Context, channel string) error
// IsStopped reports whether Stop has been called for the channel.
IsStopped(ctx context.Context, channel string) (bool, error)
// EnqueueMessage pushes an input message onto the channel's queue.
// The agent loop drains this queue at iteration boundaries — same
// cadence as IsStopped — and once more when the model has finished
// answering, and folds queued messages into the current run. The
// message's tool outputs are kept for their calls instead, where
// WaitToolResult reads them.
EnqueueMessage(ctx context.Context, channel string, msg history.Message) error
// WaitToolResult returns the output a client sent for callID into the
// run on channel (as a tool message, through EnqueueMessage or
// RunClaimBroker.EnqueueOrStart), waiting up to timeout for it. found is
// false when nothing arrived in time; a zero timeout only takes an output
// already there. The first output for a call wins, and it stays stored,
// so a retried activity or step reads the same answer.
WaitToolResult(ctx context.Context, channel, callID string, timeout time.Duration) (result string, found bool, err error)
// DrainMessages atomically returns and clears all queued messages
// for the channel. Empty slice if nothing queued.
DrainMessages(ctx context.Context, channel string) ([]history.Message, error)
// IsActive reports whether the channel has an in-flight run — used
// by the gateway to decide between enqueueing onto an existing
// stream and starting a fresh one. A channel is active once
// Subscribe has been called and stays active until Close.
IsActive(ctx context.Context, channel string) (bool, error)
}
StreamBroker provides streaming between workers and clients, including execution-scoped liveness. Runtime-specific proxies implement StartHeartbeat with their own scheduling semantics.
type StreamReplayReader ¶ added in v0.0.17
type StreamReplayReader interface {
Replay(ctx context.Context, channel string) ([]*responses.ResponseChunk, error)
}
StreamReplayReader provides a read-only snapshot for validating SSE resume cursors and replaying completed runs. Retention follows the broker's limits. MemoryStreamBroker and RedisStreamBroker implement this optional capability.
type SystemPromptProvider ¶
type SystemPromptProvider interface {
GetPrompt(ctx context.Context, data *Dependencies) (string, error)
}
func WrapPromptProvider ¶ added in v0.0.17
func WrapPromptProvider(provider SystemPromptProvider, middlewares ...PromptMiddleware) SystemPromptProvider
WrapPromptProvider binds middleware to the real provider. Durable adapters call its GetPrompt inside the existing prompt activity or run step.
type Tool ¶
type Tool interface {
Execute(ctx context.Context, params *ToolCall) (*ToolCallResponse, error)
// GetToolDescriptor projects the tool onto the plain data every tool has in
// common — its schema, its name, and the flags the loop reads off it. That
// projection is the only form of the tool that can cross a durable
// runtime's boundary or reach a middleware, and it is also what the loop itself
// reads, so a tool describes itself in exactly one place. Embedding
// *BaseTool satisfies this.
//
// Describing itself is not something a tool is allowed to fail at: nil is
// the only way to say nothing, and every caller treats a tool that says
// nothing as one that is not there.
GetToolDescriptor() *BaseTool
}
type ToolAnnotations ¶
type ToolAnnotations struct {
// Title is a human-readable name for the tool, for UI use.
Title string `json:"title,omitempty"`
// ReadOnlyHint: the tool does not modify its environment. Default false.
ReadOnlyHint *bool `json:"readOnlyHint,omitempty"`
// DestructiveHint: the tool may perform destructive updates, as opposed to
// only additive ones. Meaningful only when the tool is not read-only.
// Default true.
DestructiveHint *bool `json:"destructiveHint,omitempty"`
// IdempotentHint: repeating the call with the same arguments has no
// additional effect. Meaningful only when the tool is not read-only.
// Default false.
IdempotentHint *bool `json:"idempotentHint,omitempty"`
// OpenWorldHint: the tool interacts with an open world of external
// entities (a web search does; a memory lookup does not). Default true.
OpenWorldHint *bool `json:"openWorldHint,omitempty"`
}
ToolAnnotations carries the behavioural hints a tool advertises about itself. The shape mirrors MCP's tool annotations so hints coming off an MCP server and hints declared on a locally defined function tool are the same thing, and a single permission policy can read both.
Every hint is a pointer so "nothing was said" stays distinguishable from "false was said": a policy usually wants to treat silence conservatively rather than as a promise. The Is* helpers already apply the MCP defaults (read-only false, destructive true, idempotent false, open-world true), so prefer them over reading the fields directly.
Hints are self-reported. They describe intent, not enforcement — never let a hint from an untrusted server widen what a tool is allowed to do.
func (*ToolAnnotations) IsDeclaredDestructive ¶
func (a *ToolAnnotations) IsDeclaredDestructive() bool
IsDeclaredDestructive reports whether the tool actually said it may destroy or overwrite state, as opposed to IsDestructive's "assume the worst when nothing was said".
This is usually the one a middleware gating tool calls wants: an unannotated tool has made no claim, and gating on the absence of a claim would put every tool written before annotations behind a prompt.
func (*ToolAnnotations) IsDestructive ¶
func (a *ToolAnnotations) IsDestructive() bool
IsDestructive reports whether the tool may destroy or overwrite state. A read-only tool is never destructive; otherwise an unset hint reads as destructive, which is the MCP default and the safe assumption for a permission check.
func (*ToolAnnotations) IsIdempotent ¶
func (a *ToolAnnotations) IsIdempotent() bool
IsIdempotent reports whether repeating the call is harmless. Read-only tools are idempotent by definition; otherwise an unset hint reads as false.
func (*ToolAnnotations) IsOpenWorld ¶
func (a *ToolAnnotations) IsOpenWorld() bool
IsOpenWorld reports whether the tool reaches outside a closed, known set of entities. An unset hint reads as open, the MCP default.
func (*ToolAnnotations) IsReadOnly ¶
func (a *ToolAnnotations) IsReadOnly() bool
IsReadOnly reports whether the tool promised not to modify anything. Silence is not a promise: an unset hint reads as false.
type ToolCall ¶
type ToolCall struct {
*responses.FunctionCallMessage
AgentName string `json:"agent_name"`
AgentVersion string `json:"agent_version"`
Namespace string `json:"namespace"`
SessionID string `json:"session_id"`
ThreadID string `json:"thread_id"`
StreamID string `json:"stream_id,omitempty"`
RunContext map[string]any `json:"run_context"`
// State is the run's key-value scratchpad: whatever earlier tools and
// middlewares have written, and whatever survived from earlier runs on this
// thread.
//
// Write with ToolCallResponse.StateUpdates, not by assigning here. A
// durable runtime rebuilds this map from a serialized payload, so writes
// to it on the far side reach nothing; it is copied locally too, so that
// mistake fails the same way in both places instead of only in production.
State map[string]string `json:"state,omitempty"`
// ShouldResume tells Execute to continue an in-flight call
// instead of starting a fresh one. The tool implementation reads
// this flag and switches to its resume code path — typically
// recovering saved per-call state from State (e.g., a sub-agent's
// thread id and prior run id) and feeding ResumeMessages into
// the underlying run as a continuation.
ShouldResume bool `json:"should_resume,omitempty"`
// ResumeMessages carries the continuation messages the tool
// should forward into its inner run on resume — typically a
// single FunctionCallInterruptResolutionMessage built by the agent
// loop from QueuedApprovals / QueuedRejections. Nil when
// ShouldResume is false.
ResumeMessages []responses.InputMessageUnion `json:"resume_messages,omitempty"`
// Progress is the sink for mid-execution progress updates. It is
// injected by whoever runs the tool in-process (the agent loop for the
// local runtime; the tool activity/step for durable runtimes) and is
// deliberately not serialized — it does not survive an activity
// boundary and is re-injected on the far side. Tools should emit via
// ReportProgress, which is nil-safe, rather than touching this directly.
Progress ProgressReporter `json:"-"`
}
func (*ToolCall) ReportProgress ¶
func (t *ToolCall) ReportProgress(ctx context.Context, update ToolProgress)
ReportProgress emits a progress update for this call if a reporter is wired. It is nil-safe, so tools can call it unconditionally without worrying about which runtime injected (or didn't inject) a reporter.
type ToolCallFunc ¶ added in v0.0.17
type ToolCallFunc func(ctx context.Context, tool *BaseTool, call *ToolCall) (*ToolCallResponse, error)
ToolCallFunc is a tool call as a middleware wraps it: given the tool and the call, it produces the result. It is what WrapToolCall is handed as next, and what it returns.
func WrapToolCall ¶ added in v0.0.17
func WrapToolCall(middlewares []ToolCallMiddleware, next ToolCallFunc) ToolCallFunc
WrapToolCall builds the chain of every middleware's WrapToolCall around next, the first middleware outermost: the first registered is the last to see a result on its way back. Nil middlewares are skipped.
type ToolCallMiddleware ¶ added in v0.0.17
type ToolCallMiddleware interface {
// WrapToolCall returns the function that runs in place of next. Call next
// to run the tool and return what should stand as the result, or answer
// the call without calling next at all. The call carries the tool's name,
// the arguments the model chose, the run it belongs to, and RunContext,
// where a caller's own per-run values live; tool is the tool itself as
// plain data, since the real one may be a proxy for one running elsewhere.
//
// A refusal is an answer, not a failure: return ToolCallResult with the
// reason and the model reads it and works around it. An error of the
// middleware's own ends the run. An error from next is the tool's and is
// reported to the model as one, so pass it back as it came. Return results
// as given or as copies; never write to the one supplied.
//
// It runs inside the execution boundary, before the result is journaled:
// the tool activity or run step under a durable runtime, the executor's
// own goroutine locally. It is not a separate durable step, and it may run
// again if that step retries. Middlewares nest in registration order, the first
// outermost: a result flows from the tool through the last middleware's wrap to
// the first's.
//
// A background tool has two execution boundaries: Execute starts the task,
// and AwaitTask waits for completion. Each runs its own chain. The wait
// carries the original call ID and the task stream ID; short-circuiting it
// skips waiting, but does not cancel the already-started external task.
WrapToolCall(next ToolCallFunc) ToolCallFunc
}
ToolCallMiddleware wraps every tool call an agent makes, middleware-style.
It is an interface rather than a function so a durable runtime can hold the real middleware on the worker and run it inside the activity or step that runs the tool.
func ToolCallMiddlewaresOf ¶ added in v0.0.17
func ToolCallMiddlewaresOf(middlewares []Middleware) []ToolCallMiddleware
ToolCallMiddlewaresOf narrows a middleware list to the tool-call side, which is what the executor runs. Go has no covariance for slices, so the conversion is a loop.
type ToolCallResponse ¶
type ToolCallResponse struct {
*responses.FunctionCallOutputMessage
StateUpdates map[string]string `json:"state_updates,omitempty"`
Interrupts []responses.Interrupt `json:"interrupts,omitempty"`
// TaskID says the tool has started work that outlives this call, and
// names it. The Output alongside it is what the model reads now — "started
// indexing, job 41ff" — and the run carries on rather than waiting.
//
// The tool must implement BackgroundTool: the agent calls AwaitTask to
// wait for the outcome, and delivers it to the thread when it arrives. A
// task id from a tool that cannot be waited on fails the run, because the
// work has already started and nothing would ever report it.
TaskID string `json:"task_id,omitempty"`
// TaskPayload is whatever the tool needs when it is asked to wait, carried
// back to it on BackgroundTaskRef.Payload.
//
// It exists because starting a task and waiting for one are not the same
// call, and under a durable runtime they are not even the same process:
// anything the wait needs — the call's arguments, a cursor, a handle — has
// to travel, and a field in memory does not.
TaskPayload json.RawMessage `json:"task_payload,omitempty"`
}
func ExecuteToolCallWithMiddleware ¶ added in v0.0.17
func ExecuteToolCallWithMiddleware(ctx context.Context, middlewares []ToolCallMiddleware, tool *BaseTool, call *ToolCall, fn func(context.Context, *ToolCall) (*ToolCallResponse, error)) (*ToolCallResponse, error)
ExecuteToolCallWithMiddleware runs fn through every middleware's WrapToolCall, first middleware outermost, inside the caller's execution boundary — which is where durable runtimes call it, so what the wraps make of the result is what the step returns and journals. A middleware's error comes back marked as the run's end (see IsToolCallAborted); the tool's own error comes back as it was.
func ExecuteToolWithMiddleware ¶ added in v0.0.17
func ExecuteToolWithMiddleware( ctx context.Context, middlewares []ToolCallMiddleware, exec ExecutableToolCall, fn func(context.Context, *ToolCall) (*ToolCallResponse, error), ) (*ToolCallResponse, error)
ExecuteToolWithMiddleware runs one tool call through its middlewares' WrapToolCall chain, first middleware outermost, and pairs the result with the call.
This is the seam a durable runtime replaces. Locally the middlewares are the real ones and fn is the tool; inside a workflow the executor holds no middlewares and fn is the tool's activity, which runs the real chain on the worker.
A middleware's error ends the run and comes back marked (see IsToolCallAborted), so the loop knows not to hand it to the model; a tool's error comes back as it was, leaving the loop free to report a broken tool to the model.
func ExecuteWithTrace ¶
func ExecuteWithTrace( ctx context.Context, tool Tool, params *ToolCall, exec func(context.Context, *ToolCall) (*ToolCallResponse, error), ) (*ToolCallResponse, error)
ExecuteWithTrace brackets a single tool execution with an OpenTelemetry execute_tool span following the GenAI semantic conventions: it opens the span, stamps the tool identity and arguments, runs exec, records the result (or the error), and ends the span.
Every runtime calls this from its single durable tool-execution point — the in-process executor goroutine, the Temporal activity, the Restate step — so the span fires exactly once per real tool call, never on replay, and is always complete because each call runs start-to-finish inside one step.
tool supplies the span's description metadata and may be nil; exec performs the real execution and is usually a method value — tool.Execute for a plain tool, or an MCP toolset's call method. Splitting them lets callers whose execution isn't a Tool.Execute (e.g. MCP wrappers) still report the tool's identity.
The run-wrapping invoke_agent span is intentionally not opened here: under a durable runtime a run's start and end can execute in different processes, so a span opened in the loop cannot reliably bracket the run. Callers that want one open it outside the durable boundary (e.g. around the workflow invocation) and let these tool spans nest under it.
func ToolCallResult ¶
func ToolCallResult(call *ToolCall, output string) *ToolCallResponse
ToolCallResult builds the response a middleware returns when it answers a call itself. It stamps the call's ids onto the result, which is what pairs the answer with the function_call already in history.
type ToolExecution ¶
type ToolExecution struct {
ExecutableToolCall ExecutableToolCall
Fn func(ctx context.Context) (*ToolCallResponse, error)
}
ToolExecution represents a single tool execution to be run.
type ToolExecutionResult ¶
type ToolExecutionResult struct {
Response *ToolCallResponse
Err error
// Cancelled marks a call the stop unwound, as opposed to one that
// failed on its own: the loop reports it to the model as cancelled
// rather than as a tool error.
//
// Set it from the call's own outcome, never from a live read of the
// stop flag — the outcome is already in the runtime's ledger and so
// replays with it, while a fresh read could answer differently.
Cancelled bool
}
ToolExecutionResult holds the result of a single tool execution.
type ToolExecutor ¶
type ToolExecutor interface {
ExecuteAll(ctx context.Context, executions []ExecutableToolCall) []ToolExecutionResult
}
ToolExecutor executes tool calls sequentially in input order. Implementations must return results in the same order and merge each successful response's StateUpdates into the next call's State snapshot.
type ToolProgress ¶
ToolProgress is a single mid-execution progress update emitted by a tool. Its fields mirror MCP's notifications/progress so MCP tools map their server-sent progress onto it verbatim, while function tools construct it directly. Progress should increase monotonically across a call; Total is optional (0 means unknown).
type ToolSearchInput ¶
type ToolSearchTool ¶
type ToolSearchTool struct {
*BaseTool
// contains filtered or unexported fields
}
func NewToolSearchTool ¶
func NewToolSearchTool(deferredTools []Tool) *ToolSearchTool
func (*ToolSearchTool) Execute ¶
func (t *ToolSearchTool) Execute(ctx context.Context, params *ToolCall) (*ToolCallResponse, error)
type ToolsetError ¶ added in v0.0.15
type ToolsetError struct {
Kind ToolsetErrorKind
Err error
}
ToolsetError is a listing failure the toolset has classified for itself. Only the toolset knows what its transport's errors mean, so it says; a toolset that returns a bare error is read as ToolsetErrorUnavailable.
func NewToolsetError ¶ added in v0.0.15
func NewToolsetError(kind ToolsetErrorKind, err error) *ToolsetError
func (*ToolsetError) Error ¶ added in v0.0.15
func (e *ToolsetError) Error() string
func (*ToolsetError) Unwrap ¶ added in v0.0.15
func (e *ToolsetError) Unwrap() error
type ToolsetErrorKind ¶ added in v0.0.15
type ToolsetErrorKind string
ToolsetErrorKind says why a toolset could not be listed. It decides the wording the model is given, because the two ask different things of the user: a server that needs reconnecting is something they can act on, one that is merely down is not.
const ( // ToolsetErrorAuth is a credential the server rejected — a 401 or 403. // Retrying changes nothing; the user has to authorize. ToolsetErrorAuth ToolsetErrorKind = "auth" // unreachable, or answered with something unusable. ToolsetErrorUnavailable ToolsetErrorKind = "unavailable" )
type WrappedLLM ¶
type WrappedLLM struct {
// contains filtered or unexported fields
}
func (*WrappedLLM) NewStreamingResponses ¶
Source Files
¶
- a2a.go
- agent.go
- background.go
- background_middleware.go
- client_tool.go
- durable.go
- execution.go
- handle.go
- handoff.go
- history_middleware.go
- input_stream.go
- llm.go
- mcp_client.go
- mcp_toolset.go
- message_ids.go
- middleware.go
- model_attempt.go
- model_middleware.go
- progress.go
- prompt_middleware.go
- prompts.go
- registry.go
- runtime.go
- skill.go
- skill_client.go
- skill_tool.go
- stop.go
- stop_middleware.go
- stream_broker.go
- tool.go
- tool_annotations.go
- tool_executor.go
- tool_middleware.go
- tool_search_tool.go
- toolset_error.go
- tracing.go
Directories
¶
| Path | Synopsis |
|---|---|
|
Package agentconfig defines agents as data: a serializable Config, a Registry that finds the configs a namespace can run, and a Builder that turns them into a plain agents.Agent from dependencies held in code.
|
Package agentconfig defines agents as data: a serializable Config, a Registry that finds the configs a namespace can run, and a Builder that turns them into a plain agents.Agent from dependencies held in code. |
|
Package attachments resolves application-owned immutable files without putting their contents in conversation or workflow state.
|
Package attachments resolves application-owned immutable files without putting their contents in conversation or workflow state. |
|
Package eval runs an agent against a fixed set of cases and scores what it did, so a change to a prompt, a model, or a tool can be measured instead of eyeballed.
|
Package eval runs an agent against a fixed set of cases and scores what it did, so a change to a prompt, a model, or a tool can be measured instead of eyeballed. |
|
runtime
|
|
|
local_runtime
Package local_runtime provides a goroutine-based agent runtime that streams via a StreamBroker, mirroring the structure of the Temporal and Restate runtimes.
|
Package local_runtime provides a goroutine-based agent runtime that streams via a StreamBroker, mirroring the structure of the Temporal and Restate runtimes. |
|
restate_agent_builder
Package restate_agent_builder runs config-built agents (see agentconfig) on Restate through one generic workflow, so an agent created after the service started runs durably without registering anything.
|
Package restate_agent_builder runs config-built agents (see agentconfig) on Restate through one generic workflow, so an agent created after the service started runs durably without registering anything. |
|
temporal_agent_builder
Package temporal_agent_builder runs config-built agents (see agentconfig) on Temporal through one generic workflow, so an agent created after the worker started runs durably without registering anything.
|
Package temporal_agent_builder runs config-built agents (see agentconfig) on Temporal through one generic workflow, so an agent created after the worker started runs durably without registering anything. |
|
internal/execsandbox
Package execsandbox implements sandbox.Sandbox over a provider's native exec, for containers that run no process of ours.
|
Package execsandbox implements sandbox.Sandbox over a provider's native exec, for containers that run no process of ours. |
|
internal/httpapi
Package httpapi contains transport shared by sandbox provider adapters.
|
Package httpapi contains transport shared by sandbox provider adapters. |
|
internal/provision
Package provision contains configuration helpers for providers that create their own containers.
|
Package provision contains configuration helpers for providers that create their own containers. |
|
internal/sandboxtest
Package sandboxtest checks what a provider's exec path promises against a real container, which is the only place these behaviours can be observed: they come from the container runtime, the shell and the tools in the image.
|
Package sandboxtest checks what a provider's exec path promises against a real container, which is the only place these behaviours can be observed: they come from the container runtime, the shell and the tools in the image. |
|
providers/daytona
Package daytona implements sandbox.Provider using Daytona's control and toolbox APIs.
|
Package daytona implements sandbox.Provider using Daytona's control and toolbox APIs. |
|
providers/docker
Package docker provisions sandboxes through the Docker Engine API and runs commands in them with its exec API.
|
Package docker provisions sandboxes through the Docker Engine API and runs commands in them with its exec API. |
|
providers/e2b
Package e2b uses the E2B lifecycle API and envd's native Connect/file protocols.
|
Package e2b uses the E2B lifecycle API and envd's native Connect/file protocols. |
|
providers/k8s
Package k8s provisions sandbox pods with the official Kubernetes client and runs commands in them through the API server's exec subresource.
|
Package k8s provisions sandbox pods with the official Kubernetes client and runs commands in them through the API server's exec subresource. |
|
Package skills persists complete skill bundles independently of agent configuration.
|
Package skills persists complete skill bundles independently of agent configuration. |