Documentation
¶
Overview ¶
Package runtime emits cooperative activity heartbeats for long-running planner and tool activities so engine-driven cancellation reaches streaming provider calls promptly instead of after the activity returns on its own.
Package runtime provides the loom-mcp runtime implementation.
This file contains agent-as-tool support: a toolset registration that executes a nested agent run and adapts its canonical run output into a parent tool_result.
Contract highlights:
- The nested run context always carries the canonical JSON tool payload as RunContext.ToolArgs for provider planners to decode once and render method-specific prompts.
- Consumer-side prompt rendering (PromptSpecs/Templates/Texts) is optional and must be payload-only: it cannot depend on provider-only server context.
- When no consumer-side prompt content is configured, the runtime uses the canonical tool payload to construct the nested user message deterministically.
Package runtime defines typed error contracts exposed to callers.
This file contains await-resume delivery errors returned by Provide* operations. These errors let service layers distinguish stale/closed runs from internal dependency failures without inspecting backend-specific text.
Package runtime provides typed clients for sessionful and one-shot agent runs.
Package runtime provides history management policies for bounding conversation context. HistoryPolicy implementations transform message history before each planner invocation to prevent unbounded context growth.
Package runtime provides explicit one-shot run execution and canonical run-log persistence for sessionless request/response flows.
Package runtime owns execution-time result preview rendering.
This file defines the template contract for `ResultHintTemplate(...)`.
Contract:
- `Result` is the semantic typed tool result returned by the executor.
- `Args` is the semantic typed tool payload when it can be decoded.
- `Bounds` is the runtime-owned bounded-result metadata when present.
- Preview rendering does not reshape semantic results or synthesize fields.
Package runtime coordinates lazy workflow-handle waiting and terminal hook repair so durable runs still emit one canonical RunCompleted event without forcing every starter process to block on workflow completion.
Package runtime centralizes the timeout contract shared by run submission and workflow execution so the engine-level run timeout can never undercut the workflow's own hard deadline.
Package runtime implements the core orchestration engine for loom-mcp agents. It coordinates workflow execution, planner invocations, tool scheduling, policy enforcement, memory persistence, and event streaming. The Runtime instance serves as the central registry for agents, toolsets, models, and manages their lifecycle through durable workflow execution (typically via Temporal).
Key responsibilities:
- Agent and toolset registration with validation
- Workflow lifecycle management (start, execute, resume)
- Policy enforcement (caps, timeouts, tool filtering)
- Memory persistence via hook subscriptions
- Event streaming and telemetry integration
- Tool execution and JSON codec management
The Runtime is thread-safe and can be used concurrently to register agents and execute workflows. Production deployments typically configure the Runtime with a durable workflow engine (Temporal) and a durable memory store.
Example usage: use AgentClient for execution.
rt := runtime.New(runtime.Options{ Engine: temporalEngine, ... })
if err := rt.RegisterAgent(ctx, agentReg); err != nil {
log.Fatal(err)
}
client := rt.MustClient(agent.Ident("service.agent"))
out, err := client.Run(ctx, "s1", messages)
Package runtime executes agent runs and enforces runtime-owned tool-result contracts, including bounded-result invariants across all ingress paths.
Package runtime owns execution-time result encoding and projection.
This file owns canonical tool-result encoding across runtime-managed and custom workflow boundaries.
Contract:
- Callers pass typed Go result values, never pre-encoded JSON bytes.
- Generated result codecs remain the single authority for semantic JSON.
- Bounded-result projection is applied exactly once after codec encoding.
Index ¶
- Constants
- Variables
- func CompileAgentToolTemplates(raw map[tools.Ident]string, userFuncs template.FuncMap) (map[tools.Ident]*template.Template, error)
- func ConvertRunOutputToToolResult(toolName tools.Ident, output *RunOutput) planner.ToolResult
- func EncodeCanonicalToolResult(spec tools.ToolSpec, value any, bounds *agent.Bounds) (rawjson.Message, error)
- func IsRunNotAwaitable(err error) bool
- func NestedRunID(parentRunID string, toolName tools.Ident) string
- func NestedRunIDForToolCall(parentRunID string, toolName tools.Ident, toolCallID string) string
- func PayloadToString(payload any) (string, error)
- func ValidateAgentToolCoverage(texts map[tools.Ident]string, templates map[tools.Ident]*template.Template, ...) error
- func ValidateAgentToolTemplates(templates map[tools.Ident]*template.Template, toolIDs []tools.Ident, ...) error
- func WithPromptRenderHookContext(ctx context.Context, meta PromptRenderHookContext) context.Context
- type ActivityToolExecutor
- type AfterEventDecision
- type AfterEventInput
- type AfterModelDecision
- type AfterModelInput
- type AfterRunDecision
- type AfterRunInput
- type AfterToolDecision
- type AfterToolInput
- type AgentClient
- type AgentRegistration
- type AgentRoute
- type AgentToolConfig
- type AgentToolContent
- type AgentToolOption
- func WithPromptSpec(id tools.Ident, promptID prompt.Ident) AgentToolOption
- func WithTemplate(id tools.Ident, t *template.Template) AgentToolOption
- func WithTemplateAll(ids []tools.Ident, t *template.Template) AgentToolOption
- func WithText(id tools.Ident, s string) AgentToolOption
- func WithTextAll(ids []tools.Ident, s string) AgentToolOption
- type AgentToolValidationError
- type AgentToolValidationInput
- type AgentToolValidator
- type AggregationChild
- type AggregationSummary
- type ArtifactToolsetConfig
- type BedrockConfig
- type BeforeEventDecision
- type BeforeEventInput
- type BeforeModelDecision
- type BeforeModelInput
- type BeforeRunDecision
- type BeforeRunInput
- type BeforeToolDecision
- type BeforeToolInput
- type CachePolicy
- type CompressOption
- type DispatchMode
- type EventInterceptor
- type GeminiConfig
- type HintOverrideFunc
- type HistoryCompressionConfig
- type HistoryPolicy
- type HookActivityInput
- type Interceptor
- type LongTermMemoryPreloadPolicy
- type MemoryPreloadPolicy
- type MemoryScope
- type MemoryToolsetConfig
- type MissingFieldsAction
- type ModelInterceptor
- type OllamaConfig
- type OneShotRunInput
- type OpenAIConfig
- type Options
- type PlanActivityInput
- type PlanActivityOutput
- type PolicyOverrides
- type PromptBuilder
- type PromptRenderHookContext
- type ResultMaterializer
- type RetryAndReflectConfig
- type RunInput
- type RunInterceptor
- type RunNotAwaitableError
- type RunNotAwaitableReason
- type RunOption
- func WithAllowedTags(tags []string) RunOption
- func WithDeniedTags(tags []string) RunOption
- func WithLabels(labels map[string]string) RunOption
- func WithMemo(m map[string]any) RunOption
- func WithMetadata(meta map[string]any) RunOption
- func WithPerTurnMaxToolCalls(n int) RunOption
- func WithRestrictToTool(id tools.Ident) RunOption
- func WithRunFinalizerGrace(d time.Duration) RunOption
- func WithRunID(id string) RunOption
- func WithRunInterruptsAllowed(allowed bool) RunOption
- func WithRunMaxConsecutiveFailedToolCalls(n int) RunOption
- func WithRunMaxToolCalls(n int) RunOption
- func WithRunTimeBudget(d time.Duration) RunOption
- func WithSearchAttributes(sa map[string]any) RunOption
- func WithTaskQueue(name string) RunOption
- func WithTiming(t Timing) RunOption
- func WithTurnID(id string) RunOption
- func WithWorkflowOptions(o *WorkflowOptions) RunOption
- type RunOutput
- type RunPolicy
- type Runtime
- func (r *Runtime) AddEventsToMemory(ctx context.Context, input memory.IngestEventsInput) (memory.IngestResult, error)
- func (r *Runtime) AddRunToMemory(ctx context.Context, input memory.IngestRunInput) (memory.IngestResult, error)
- func (r *Runtime) CancelRun(ctx context.Context, runID string) error
- func (r *Runtime) Client(id agent.Ident) (AgentClient, error)
- func (r *Runtime) ClientFor(route AgentRoute) (AgentClient, error)
- func (r *Runtime) CreateSession(ctx context.Context, sessionID string) (session.Session, error)
- func (r *Runtime) DeleteSession(ctx context.Context, sessionID string) (session.Session, error)
- func (r *Runtime) ExecuteAgentChildWithRoute(wfCtx engine.WorkflowContext, route AgentRoute, messages []*model.Message, ...) (*RunOutput, error)
- func (r *Runtime) ExecuteToolActivity(ctx context.Context, req *ToolInput) (*ToolOutput, error)
- func (r *Runtime) ExecuteWorkflow(wfCtx engine.WorkflowContext, input *RunInput) (out *RunOutput, retErr error)
- func (r *Runtime) GetRunSnapshot(ctx context.Context, runID string) (*run.Snapshot, error)
- func (r *Runtime) ListAgents() []agent.Ident
- func (r *Runtime) ListRunEvents(ctx context.Context, runID, cursor string, limit int) (runlog.Page, error)
- func (r *Runtime) ListToolsets() []string
- func (r *Runtime) ModelClient(id string) (model.Client, bool)
- func (r *Runtime) MustClient(id agent.Ident) AgentClient
- func (r *Runtime) MustClientFor(route AgentRoute) AgentClient
- func (r *Runtime) NewBedrockModelClient(awsrt *bedrockruntime.Client, cfg BedrockConfig) (model.Client, error)
- func (r *Runtime) NewGeminiModelClient(ctx context.Context, cfg GeminiConfig) (model.Client, error)
- func (r *Runtime) NewOllamaModelClient(cfg OllamaConfig) (model.Client, error)
- func (r *Runtime) NewOpenAIModelClient(cfg OpenAIConfig) (model.Client, error)
- func (r *Runtime) NewVertexGeminiModelClient(ctx context.Context, cfg VertexConfig) (model.Client, error)
- func (r *Runtime) OverridePolicy(agentID agent.Ident, delta RunPolicy) error
- func (r *Runtime) PauseRun(ctx context.Context, req interrupt.PauseRequest) error
- func (r *Runtime) PlanResumeActivity(ctx context.Context, input *PlanActivityInput) (*PlanActivityOutput, error)
- func (r *Runtime) PlanStartActivity(ctx context.Context, input *PlanActivityInput) (*PlanActivityOutput, error)
- func (r *Runtime) ProvideClarification(ctx context.Context, ans interrupt.ClarificationAnswer) error
- func (r *Runtime) ProvideConfirmation(ctx context.Context, dec interrupt.ConfirmationDecision) error
- func (r *Runtime) ProvideToolResults(ctx context.Context, rs interrupt.ToolResultsSet) error
- func (r *Runtime) ProvideTypedInput(ctx context.Context, ans interrupt.TypedInputAnswer) error
- func (r *Runtime) PutMemoryEntry(ctx context.Context, input memory.PutEntryInput) (memory.Entry, error)
- func (r *Runtime) RegisterAgent(ctx context.Context, reg AgentRegistration) error
- func (r *Runtime) RegisterModel(id string, client model.Client) error
- func (r *Runtime) RegisterToolset(ts ToolsetRegistration) error
- func (r *Runtime) ResolvePromptRefs(ctx context.Context, runID string) ([]prompt.PromptRef, error)
- func (r *Runtime) ResumeRun(ctx context.Context, req interrupt.ResumeRequest) error
- func (r *Runtime) RunOneShot(ctx context.Context, input OneShotRunInput, ...) error
- func (r *Runtime) Seal(ctx context.Context) error
- func (r *Runtime) ToolSchema(name tools.Ident) (map[string]any, bool)
- func (r *Runtime) ToolSpec(name tools.Ident) (tools.ToolSpec, bool)
- func (r *Runtime) ToolSpecsForAgent(agentID agent.Ident) []tools.ToolSpec
- type RuntimeInterceptorFuncs
- func (f RuntimeInterceptorFuncs) AfterEvent(ctx context.Context, input *AfterEventInput) (*AfterEventDecision, error)
- func (f RuntimeInterceptorFuncs) AfterModel(ctx context.Context, input *AfterModelInput) (*AfterModelDecision, error)
- func (f RuntimeInterceptorFuncs) AfterRun(ctx context.Context, input *AfterRunInput) (*AfterRunDecision, error)
- func (f RuntimeInterceptorFuncs) AfterTool(ctx context.Context, input *AfterToolInput) (*AfterToolDecision, error)
- func (f RuntimeInterceptorFuncs) BeforeEvent(ctx context.Context, input *BeforeEventInput) (*BeforeEventDecision, error)
- func (f RuntimeInterceptorFuncs) BeforeModel(ctx context.Context, input *BeforeModelInput) (*BeforeModelDecision, error)
- func (f RuntimeInterceptorFuncs) BeforeRun(ctx context.Context, input *BeforeRunInput) (*BeforeRunDecision, error)
- func (f RuntimeInterceptorFuncs) BeforeTool(ctx context.Context, input *BeforeToolInput) (*BeforeToolDecision, error)
- type RuntimeOption
- func WithArtifactStore(s artifact.Store) RuntimeOption
- func WithCaptureGenAIMessages(enabled bool) RuntimeOption
- func WithEngine(e engine.Engine) RuntimeOption
- func WithHintOverrides(m map[tools.Ident]HintOverrideFunc) RuntimeOption
- func WithHookActivityTimeout(d time.Duration) RuntimeOption
- func WithHooks(b hooks.Bus) RuntimeOption
- func WithInterceptors(interceptors ...Interceptor) RuntimeOption
- func WithLogger(l telemetry.Logger) RuntimeOption
- func WithMemoryScopeResolver(r memory.ScopeResolver) RuntimeOption
- func WithMemorySearcher(s memory.Searcher) RuntimeOption
- func WithMemoryService(s memory.Service) RuntimeOption
- func WithMemoryStore(m memory.Store) RuntimeOption
- func WithMetrics(m telemetry.Metrics) RuntimeOption
- func WithNamedInterceptors(interceptors map[string]Interceptor) RuntimeOption
- func WithPolicy(p policy.Engine) RuntimeOption
- func WithPromptStore(s prompt.Store) RuntimeOption
- func WithRunEventStore(s runlog.Store) RuntimeOption
- func WithSessionStore(s session.Store) RuntimeOption
- func WithStream(s stream.Sink) RuntimeOption
- func WithToolConfirmation(cfg *ToolConfirmationConfig) RuntimeOption
- func WithTracer(t telemetry.Tracer) RuntimeOption
- func WithWorker(id agent.Ident, cfg WorkerConfig) RuntimeOption
- type SkillToolsetConfig
- type SubscriberMode
- type Timing
- type ToolActivityExecutor
- type ToolCallExecutor
- type ToolCallExecutorFunc
- type ToolCallMeta
- type ToolConfirmation
- type ToolConfirmationConfig
- type ToolExecutionResult
- type ToolInput
- type ToolInterceptor
- type ToolInterceptorFuncs
- type ToolOutput
- type ToolPause
- type ToolPauseClarification
- type ToolsetRegistration
- func NewAgentToolsetRegistration(rt *Runtime, cfg AgentToolConfig) ToolsetRegistration
- func NewArtifactToolsetRegistration(cfg ArtifactToolsetConfig) ToolsetRegistration
- func NewMemoryToolsetRegistration(cfg MemoryToolsetConfig) ToolsetRegistration
- func NewSkillToolsetRegistration(cfg SkillToolsetConfig) ToolsetRegistration
- type VertexConfig
- type WorkerConfig
- type WorkerOption
- type WorkflowOptions
Constants ¶
const ( // DefaultArtifactListLimit bounds listed artifact refs when MaxArtifacts is unset. DefaultArtifactListLimit = 100 // DefaultArtifactLoadMaxBytes bounds loaded artifact content when MaxArtifactBytes is unset. DefaultArtifactLoadMaxBytes = 256 * 1024 )
const ( // DefaultMemoryToolResultLimit bounds memory tool results when MaxResults is unset. DefaultMemoryToolResultLimit = 100 // UnlimitedToolsetLimit disables built-in runtime ceilings for toolset limits. UnlimitedToolsetLimit = -1 )
const ( // SkillPreloadNone leaves skill instructions unloaded until requested. SkillPreloadNone = mcpskills.PreloadNone // SkillPreloadOnStart preloads SKILL.md when the toolset registration is built. SkillPreloadOnStart = mcpskills.PreloadOnStart // SkillReloadNever reuses loaded content until the toolset registration is rebuilt. SkillReloadNever = mcpskills.ReloadNever // SkillReloadPerCall reloads skill files for each load call. SkillReloadPerCall = mcpskills.ReloadPerCall )
Variables ¶
var ( // Typed error sentinels for common invalid states. ErrAgentNotFound = errors.New("agent not found") ErrEngineNotConfigured = errors.New("runtime engine not configured") ErrInvalidConfig = errors.New("invalid configuration") ErrMissingSessionID = errors.New("session id is required") ErrSessionNotAllowed = errors.New("session id is not allowed") ErrWorkflowStartFailed = errors.New("workflow start failed") ErrRegistrationClosed = errors.New("registration closed after first run") )
var ( // ErrRunNotAwaitable matches all RunNotAwaitableError instances via errors.Is. ErrRunNotAwaitable = errors.New("run is not awaitable") )
Functions ¶
func CompileAgentToolTemplates ¶
func CompileAgentToolTemplates(raw map[tools.Ident]string, userFuncs template.FuncMap) (map[tools.Ident]*template.Template, error)
CompileAgentToolTemplates compiles per-tool message templates from plain strings.
func ConvertRunOutputToToolResult ¶
func ConvertRunOutputToToolResult(toolName tools.Ident, output *RunOutput) planner.ToolResult
ConvertRunOutputToToolResult converts a nested agent RunOutput into a planner.ToolResult.
func EncodeCanonicalToolResult ¶
func EncodeCanonicalToolResult(spec tools.ToolSpec, value any, bounds *agent.Bounds) (rawjson.Message, error)
EncodeCanonicalToolResult encodes a typed tool result into the canonical JSON contract exposed by loom-mcp.
It uses the generated result codec from spec as the sole semantic encoder, then overlays any runtime-owned bounded-result metadata from bounds. Callers that create workflow-safe envelopes outside ExecuteToolActivity should use this helper instead of duplicating codec and bounded-result projection logic.
func IsRunNotAwaitable ¶
IsRunNotAwaitable reports whether err classifies as run-not-awaitable.
func NestedRunID ¶
NestedRunID generates a hierarchical run ID for nested agent execution.
func NestedRunIDForToolCall ¶
NestedRunIDForToolCall generates a child workflow ID for agent-as-tool runs.
func PayloadToString ¶
PayloadToString converts a tool payload to a string for agent consumption.
func ValidateAgentToolCoverage ¶
func ValidateAgentToolCoverage(texts map[tools.Ident]string, templates map[tools.Ident]*template.Template, toolIDs []tools.Ident) error
ValidateAgentToolCoverage verifies that every tool in toolIDs has exactly one configured content source.
func ValidateAgentToolTemplates ¶
func ValidateAgentToolTemplates(templates map[tools.Ident]*template.Template, toolIDs []tools.Ident, zeroByTool map[tools.Ident]any) error
ValidateAgentToolTemplates ensures that templates exist for all provided tool IDs.
func WithPromptRenderHookContext ¶
func WithPromptRenderHookContext(ctx context.Context, meta PromptRenderHookContext) context.Context
WithPromptRenderHookContext returns ctx stamped with run metadata used by runtime prompt observer callbacks.
Types ¶
type ActivityToolExecutor ¶
type ActivityToolExecutor struct {
// contains filtered or unexported fields
}
ActivityToolExecutor implements ToolActivityExecutor for regular tools that execute via workflow activities. It uses ExecuteActivityAsync for parallel execution with other tools in the same batch.
func (*ActivityToolExecutor) Execute ¶
func (e *ActivityToolExecutor) Execute(ctx context.Context, wfCtx engine.WorkflowContext, input *ToolInput) (*ToolOutput, error)
Execute schedules the tool as a workflow activity and waits for its result. This maintains workflow determinism while allowing the tool to run out-of-process. The input is passed through to the activity as-is (already properly formatted).
type AfterEventDecision ¶ added in v1.2.2
type AfterEventDecision struct {
Err error
}
AfterEventDecision changes the event publication error. Only a non-nil Err is adopted; an empty decision is an observer no-op that preserves the current publication error, so canonical run-log append failures cannot be cleared by observer interceptors.
type AfterEventInput ¶ added in v1.2.2
AfterEventInput is passed after hook event publication succeeds or fails.
type AfterModelDecision ¶ added in v1.2.2
AfterModelDecision changes the model response or error.
type AfterModelInput ¶ added in v1.2.2
type AfterModelInput struct {
AgentID agent.Ident
RunID string
SessionID string
TurnID string
ModelID string
Request *model.Request
Response *model.Response
Err error
}
AfterModelInput is passed after a model client invocation returns.
type AfterRunDecision ¶ added in v1.2.2
AfterRunDecision changes the run outcome. Set Output to replace the run output; when Output is set the decision's Err (including nil) also replaces the current run error. A decision with nil Output and nil Err is an observer no-op and leaves the current outcome, including any run error, unchanged.
type AfterRunInput ¶ added in v1.2.2
type AfterRunInput struct {
AgentID agent.Ident
RunID string
Input RunInput
Output *RunOutput
Err error
RunContext run.Context
}
AfterRunInput is passed after workflow execution produces an outcome.
type AfterToolDecision ¶ added in v1.2.2
type AfterToolDecision struct {
Execution *ToolExecutionResult
Result *planner.ToolResult
Err error
}
AfterToolDecision changes the executor outcome. Set Execution when the interceptor needs to replace the full runtime envelope, or Result when only the planner-visible tool result changes.
type AfterToolInput ¶ added in v1.2.2
type AfterToolInput struct {
Call planner.ToolRequest
Meta ToolCallMeta
Result *planner.ToolResult
Execution *ToolExecutionResult
Err error
Duration time.Duration
}
AfterToolInput is passed to interceptors after a tool executor returns.
type AgentClient ¶
type AgentClient interface {
// Run starts one sessionful workflow and blocks until completion.
//
// Run is request/response oriented: it is equivalent to Start followed by
// handle.Wait on the returned workflow handle.
Run(ctx context.Context, sessionID string, messages []*model.Message, opts ...RunOption) (*RunOutput, error)
// Start starts one sessionful workflow and returns immediately with a
// workflow handle for asynchronous coordination.
//
// Callers use the handle to wait, signal, or cancel. Start does not block
// on workflow completion.
Start(ctx context.Context, sessionID string, messages []*model.Message, opts ...RunOption) (engine.WorkflowHandle, error)
// OneShotRun starts one sessionless workflow and blocks until completion.
//
// One-shot runs do not participate in session lifecycle and do not emit
// session-scoped stream events. They still append canonical lifecycle and
// prompt/tool events to the run log.
OneShotRun(ctx context.Context, messages []*model.Message, opts ...RunOption) (*RunOutput, error)
}
AgentClient is the high-level execution surface for one agent.
Contract:
- Run and Start are sessionful APIs: callers must provide a concrete session ID that already exists in the runtime SessionStore.
- OneShotRun is sessionless: callers provide no session ID and the runtime persists only canonical run-log events for introspection by RunID.
- Generated code typically returns AgentClient implementations via NewClient helpers bound to one agent route.
type AgentRegistration ¶
type AgentRegistration struct {
// ID is the unique agent identifier (service.agent).
ID agent.Ident
// Planner is the concrete planner implementation for the agent.
Planner planner.Planner
// Workflow describes the durable workflow registered with the engine.
Workflow engine.WorkflowDefinition
// Toolsets enumerates tool registrations exposed by this agent package.
Toolsets []ToolsetRegistration
// PlanActivityName names the activity used for PlanStart.
PlanActivityName string
// PlanActivityOptions describes retry/timeout behavior for the PlanStart activity.
PlanActivityOptions engine.ActivityOptions
// ResumeActivityName names the activity used for PlanResume.
ResumeActivityName string
// ResumeActivityOptions describes retry/timeout behavior for the PlanResume activity.
ResumeActivityOptions engine.ActivityOptions
// ExecuteToolActivity is the logical name of the registered ExecuteTool activity.
ExecuteToolActivity string
// ExecuteToolActivityOptions describes retry/timeout/queue for the ExecuteTool activity.
// When set, these options are applied to all service-backed tool activities
// scheduled by this agent. Agent-as-tool executions run as child workflows.
ExecuteToolActivityOptions engine.ActivityOptions
// Specs provides JSON codecs for every tool declared in the agent design.
Specs []tools.ToolSpec
// Policy configures caps/time budget/interrupt settings for the agent.
Policy RunPolicy
// Interceptors configures agent-scoped tool middleware. These run after
// runtime-level interceptors for tool calls issued by this agent.
Interceptors []Interceptor
// contains filtered or unexported fields
}
AgentRegistration bundles the generated assets for an agent. This struct is produced by codegen and passed to RegisterAgent to make an agent available for execution.
type AgentRoute ¶
type AgentRoute struct {
// ID is the canonical agent identifier.
// It must match the identifier used by worker-side registration.
ID agent.Ident
// WorkflowName is the engine-registered workflow definition name.
// It must match the workflow name workers register with the engine.
WorkflowName string
// DefaultTaskQueue is the default queue workers use for this agent.
// Per-run overrides may replace this queue via WithTaskQueue.
DefaultTaskQueue string
}
AgentRoute carries the minimum metadata needed to run an agent when the caller process does not register that agent locally.
Generated NewClient helpers embed this route metadata so most callers do not construct AgentRoute directly. Use Runtime.ClientFor when routing is dynamic (for example, gateway and orchestration processes).
type AgentToolConfig ¶
type AgentToolConfig struct {
AgentID agent.Ident
Route AgentRoute
PlanActivityName string
ResumeActivityName string
ExecuteToolActivity string
SystemPrompt string
AgentToolContent
PreChildValidator AgentToolValidator
Name string
Description string
TaskQueue string
Aliases map[tools.Ident]tools.Ident
}
AgentToolConfig configures how an agent-tool executes.
type AgentToolContent ¶
type AgentToolContent struct {
Templates map[tools.Ident]*template.Template
Texts map[tools.Ident]string
PromptSpecs map[tools.Ident]prompt.Ident
Prompt PromptBuilder
}
AgentToolContent configures the optional consumer-side rendering of the nested agent's initial user message.
type AgentToolOption ¶
type AgentToolOption func(*AgentToolConfig)
AgentToolOption configures per-tool content for agent-as-tool registrations.
func WithPromptSpec ¶
func WithPromptSpec(id tools.Ident, promptID prompt.Ident) AgentToolOption
WithPromptSpec configures a prompt registry ID for the given tool ID.
func WithTemplate ¶
func WithTemplate(id tools.Ident, t *template.Template) AgentToolOption
WithTemplate sets a compiled template for the given tool ID.
func WithTemplateAll ¶
func WithTemplateAll(ids []tools.Ident, t *template.Template) AgentToolOption
WithTemplateAll applies the same template to all provided tool IDs.
func WithText ¶
func WithText(id tools.Ident, s string) AgentToolOption
WithText sets plain text content for the given tool ID.
func WithTextAll ¶
func WithTextAll(ids []tools.Ident, s string) AgentToolOption
WithTextAll applies the same text to all provided tool IDs.
type AgentToolValidationError ¶
type AgentToolValidationError struct {
// contains filtered or unexported fields
}
AgentToolValidationError reports a tool-scoped validation failure at the agent-as-tool boundary.
func NewAgentToolValidationError ¶
func NewAgentToolValidationError(message string, issues []*tools.FieldIssue, descriptions map[string]string) *AgentToolValidationError
NewAgentToolValidationError constructs a structured validation error for an agent-as-tool pre-child validator.
func (*AgentToolValidationError) Descriptions ¶
func (e *AgentToolValidationError) Descriptions() map[string]string
Descriptions returns optional human-readable descriptions for the invalid fields.
func (*AgentToolValidationError) Error ¶
func (e *AgentToolValidationError) Error() string
Error implements the error interface.
func (*AgentToolValidationError) Issues ¶
func (e *AgentToolValidationError) Issues() []*tools.FieldIssue
Issues returns the structured field issues associated with this validation failure.
type AgentToolValidationInput ¶
type AgentToolValidationInput struct {
Call *planner.ToolRequest
Payload any
Messages []*model.Message
ParentRun *run.Context
}
AgentToolValidationInput captures the data available to PreChildValidator.
type AgentToolValidator ¶
type AgentToolValidator func(ctx context.Context, input *AgentToolValidationInput) *AgentToolValidationError
AgentToolValidator validates a nested agent-tool call before the child run starts.
type AggregationChild ¶
type AggregationChild struct {
Tool tools.Ident `json:"tool"`
Status string `json:"status"`
Result any `json:"result,omitempty"`
Error string `json:"error,omitempty"`
}
AggregationChild captures one child tool outcome in a provider-facing aggregation summary.
type AggregationSummary ¶
type AggregationSummary struct {
Method tools.Ident `json:"method"`
ToolCallID string `json:"tool_call_id,omitempty"`
Payload any `json:"payload,omitempty"`
Children []AggregationChild `json:"children"`
}
AggregationSummary is the provider-facing summary payload for provider-owned result finalizers. The runtime exports only the stable types; it no longer builds parent-side aggregation behavior itself.
type ArtifactToolsetConfig ¶ added in v1.2.2
type ArtifactToolsetConfig struct {
// Name is the toolset name used to construct canonical tool IDs.
Name string
// Store is the artifact store used by the generated tools.
Store artifact.Store
// MaxArtifactBytes caps load_artifact responses. Zero uses DefaultArtifactLoadMaxBytes.
// Set UnlimitedToolsetLimit to disable the runtime ceiling.
MaxArtifactBytes int
// MaxArtifacts caps list_artifacts responses. Zero uses DefaultArtifactListLimit.
// Set UnlimitedToolsetLimit to disable the runtime ceiling.
MaxArtifacts int
}
ArtifactToolsetConfig configures model-facing artifact tools.
type BedrockConfig ¶
type BedrockConfig struct {
DefaultModel string
HighModel string
SmallModel string
MaxTokens int
ThinkingBudget int
Temperature float32
}
BedrockConfig configures the bedrock-backed model client created by the runtime.
type BeforeEventDecision ¶ added in v1.2.2
BeforeEventDecision changes or drops hook event publication.
type BeforeEventInput ¶ added in v1.2.2
type BeforeEventInput struct {
Event hooks.Event
Payload []byte
Input HookActivityInput
}
BeforeEventInput is passed before hook events are persisted or published.
type BeforeModelDecision ¶ added in v1.2.2
BeforeModelDecision changes the model request or short-circuits with a response.
type BeforeModelInput ¶ added in v1.2.2
type BeforeModelInput struct {
AgentID agent.Ident
RunID string
SessionID string
TurnID string
ModelID string
Request *model.Request
}
BeforeModelInput is passed immediately before a model client invocation.
type BeforeRunDecision ¶ added in v1.2.2
type BeforeRunDecision struct {
Input *RunInput
}
BeforeRunDecision changes the run input before execution begins.
type BeforeRunInput ¶ added in v1.2.2
type BeforeRunInput struct {
AgentID agent.Ident
RunID string
Input RunInput
RunContext run.Context
}
BeforeRunInput is passed before workflow run events are published.
type BeforeToolDecision ¶ added in v1.2.2
type BeforeToolDecision struct {
Payload rawjson.Message
Result *ToolExecutionResult
}
BeforeToolDecision changes the tool request or returns a result without invoking the registered executor.
type BeforeToolInput ¶ added in v1.2.2
type BeforeToolInput struct {
Call planner.ToolRequest
Meta ToolCallMeta
}
BeforeToolInput is passed to interceptors immediately before a tool executor runs.
type CachePolicy ¶
type CachePolicy struct {
// AfterSystem places a checkpoint after all system messages.
AfterSystem bool
// AfterTools places a checkpoint after tool definitions. Not all
// providers support tool-level checkpoints (e.g., Nova does not).
AfterTools bool
}
CachePolicy configures automatic cache checkpoint placement for an agent. The runtime applies this policy to model requests by populating model.Request.Cache when it is nil so planners do not need to thread CacheOptions through every call site. Providers that do not support caching ignore these options.
type CompressOption ¶
type CompressOption func(*compressConfig)
CompressOption configures the Compress history policy.
func WithModelClass ¶
func WithModelClass(class model.ModelClass) CompressOption
WithModelClass sets the model class used for summarization.
func WithSummaryPrompt ¶
func WithSummaryPrompt(prompt string) CompressOption
WithSummaryPrompt sets a custom summarization prompt. The prompt should contain a %s placeholder where the conversation text will be inserted.
func WithSummaryRole ¶
func WithSummaryRole(role model.ConversationRole) CompressOption
WithSummaryRole sets the role for the summary message (system or user).
func WithTokenCounter ¶ added in v1.2.0
func WithTokenCounter(counter model.TokenCounter) CompressOption
WithTokenCounter sets the exact counter used for token-trigger and token-retention budgets. This is intended for tests and custom provider adapters; production model clients should normally satisfy model.TokenCounter themselves.
type DispatchMode ¶ added in v1.1.3
type DispatchMode int
DispatchMode selects how the runtime executes tool calls for a given toolset. The runtime sets it at registration time from the existing Inline/AgentTool signals when DispatchMode is DispatchUnset, so dispatch code can branch on a single explicit field instead of probing multiple optional ones.
const ( // DispatchUnset preserves backwards compatibility for registrations that // still rely on Inline / AgentTool being inferred during registration. DispatchUnset DispatchMode = iota // DispatchActivity runs tools as workflow activities (default for // service-backed toolsets: isolation, retries, per-queue placement). DispatchActivity // DispatchInline runs tool Execute callbacks directly in the workflow loop. // Used for workflow-native toolsets that must share the workflow context. DispatchInline // DispatchAgentChild starts a nested agent as a child workflow and adapts // its RunOutput to a ToolResult. Used for agent-as-tool registrations. DispatchAgentChild )
Dispatch modes for ToolsetRegistration. See DispatchMode for context.
type EventInterceptor ¶ added in v1.2.2
type EventInterceptor interface {
BeforeEvent(context.Context, *BeforeEventInput) (*BeforeEventDecision, error)
AfterEvent(context.Context, *AfterEventInput) (*AfterEventDecision, error)
}
EventInterceptor observes or changes hook event publication behavior.
type GeminiConfig ¶ added in v1.2.0
type GeminiConfig struct {
APIKey string
DefaultModel string
HighModel string
SmallModel string
MaxTokens int
ThinkingBudget int
Temperature float32
}
GeminiConfig configures the Gemini API-backed model client created by the runtime.
type HintOverrideFunc ¶
type HintOverrideFunc func(ctx context.Context, tool tools.Ident, payload any) (hint string, ok bool)
HintOverrideFunc can override the call hint for a tool invocation.
Contract:
- Returning (hint, true) selects hint as the DisplayHint, even when a DSL template exists.
- Returning ("", false) indicates no override applies and the runtime should use its default behavior.
- The payload value is the typed payload decoded via the tool payload codec when possible; it may be nil when decoding fails.
type HistoryCompressionConfig ¶ added in v1.2.0
type HistoryCompressionConfig struct {
// CompressAtTurns triggers summarization once at least this many logical
// turns are present. Zero disables the turn-count trigger.
CompressAtTurns int
// CompressAtMaxInputTokens triggers summarization once the full
// provider-visible transcript exceeds this input-token count. Zero
// disables the token trigger.
CompressAtMaxInputTokens int
// KeepMaxTurns caps exact retention to this many newest logical turns.
// Zero disables the turn-count retention cap.
KeepMaxTurns int
// KeepMaxInputTokens caps exact retention by input tokens. The newest
// turn is always retained; this budget bounds the measured cost of the
// older whole turns that join it, anchored on the newest tail so fixed
// system-prompt and tool-catalog overhead cancels out.
KeepMaxInputTokens int
}
HistoryCompressionConfig describes the runtime defaults or overrides for a compression history policy.
Compression has two independent decisions:
- CompressAtTurns and CompressAtMaxInputTokens decide when older history should be summarized. The triggers are ORed.
- KeepMaxTurns and KeepMaxInputTokens decide which newest complete turns remain exact after summarization. The budgets are ANDed when both are set.
Token counts are computed at runtime with the configured history model. KeepMaxInputTokens never truncates a turn; it keeps newest whole turns until adding the next older turn would exceed the budget.
func (HistoryCompressionConfig) Validate ¶ added in v1.2.0
func (cfg HistoryCompressionConfig) Validate() error
Validate checks whether the compression config is internally consistent.
type HistoryPolicy ¶
type HistoryPolicy func(ctx context.Context, msgs []*model.Message, tools []*model.ToolDefinition) ([]*model.Message, error)
HistoryPolicy transforms message history before planning. Implementations must:
- Preserve the System Prompt (typically the first message(s) with system role).
- Respect turn boundaries (User + Assistant pairs).
- Maintain ToolUse/ToolResult integrity (never orphan a result without its call).
Policies are applied by the runtime before each planner invocation (PlanStart and PlanResume). Callers may log policy errors and fall back to the original messages when appropriate.
func Compress ¶
func Compress(client model.Client, policyCfg HistoryCompressionConfig, opts ...CompressOption) HistoryPolicy
Compress returns a policy that summarizes older conversation history when the configured turn-count or exact input-token trigger is exceeded. After summarization it keeps a newest exact tail selected by whole logical turns, bounded by KeepMaxTurns, KeepMaxInputTokens, or both.
The policy always preserves:
- All System messages at the start of the conversation
- The newest turn in full fidelity
- Tool use/result integrity in the kept turns
KeepMaxInputTokens is an exact-tail budget, not a truncation budget. The newest complete turn is always retained. If even the newest turn alone cannot fit under CompressAtMaxInputTokens, Compress returns an error: no amount of summarization can produce a planner request that would not immediately re-trigger compression.
func KeepRecentTurns ¶
func KeepRecentTurns(n int) HistoryPolicy
KeepRecentTurns returns a policy that keeps only the most recent N turns of conversation history. A "turn" is defined as a User message followed by its corresponding Assistant response (including any tool use/result exchanges).
The policy always preserves:
- All System messages at the start of the conversation
- Complete turn boundaries (never splits a user query from its response)
- Tool use/result integrity (keeps results with their corresponding calls)
Example: KeepRecentTurns(5) keeps the last 5 user-assistant exchanges.
type HookActivityInput ¶
type HookActivityInput = api.HookActivityInput
type Interceptor ¶ added in v1.2.2
type Interceptor interface{}
Interceptor observes or changes runtime call-path behavior.
Interceptors are executed in registration order. They are separate from hooks: hooks publish durable observability events, while interceptors run inline before or after execution decisions are made.
func NewRetryAndReflectInterceptor ¶ added in v1.2.2
func NewRetryAndReflectInterceptor(cfg RetryAndReflectConfig) Interceptor
NewRetryAndReflectInterceptor returns an interceptor that converts tool execution errors into planner-visible tool errors with structured retry guidance. This keeps the run alive so the planner can repair the call.
type LongTermMemoryPreloadPolicy ¶ added in v1.2.2
type LongTermMemoryPreloadPolicy struct {
// Visibility selects user or shared long-term memory.
Visibility memory.Visibility
// MaxResults caps the number of entries injected into planner input.
MaxResults int
}
LongTermMemoryPreloadPolicy configures bounded planner-input long-term memory preload.
type MemoryPreloadPolicy ¶ added in v1.2.2
type MemoryPreloadPolicy struct {
// Scope selects the memory source.
Scope MemoryScope
// MaxResults caps the number of memory events injected into planner input.
MaxResults int
}
MemoryPreloadPolicy configures bounded planner-input memory preload.
type MemoryScope ¶ added in v1.2.2
type MemoryScope string
MemoryScope identifies which memory backing source a query should use.
const ( // MemoryScopeCurrentRun scopes memory lookup to the current run snapshot. MemoryScopeCurrentRun MemoryScope = "current_run" // MemoryScopeIndexed scopes memory lookup to the configured memory searcher. MemoryScopeIndexed MemoryScope = "indexed" )
type MemoryToolsetConfig ¶ added in v1.2.2
type MemoryToolsetConfig struct {
// Name is the toolset name used to construct canonical tool IDs.
Name string
// Store reads current-run memory when no Searcher is configured.
Store memory.Store
// Searcher performs indexed or cross-run memory lookup.
Searcher memory.Searcher
// Service performs long-term memory entry search.
Service memory.Service
// ScopeResolver derives tenant/user routing for long-term memory.
ScopeResolver memory.ScopeResolver
// Sources selects which memory tools and transcript scopes are enabled.
Sources []memory.ToolSource
// Visibility is the widest long-term memory visibility allowed by this toolset.
Visibility memory.Visibility
// MaxResults caps memory responses. Zero uses DefaultMemoryToolResultLimit.
// Set UnlimitedToolsetLimit to disable the runtime ceiling.
MaxResults int
}
MemoryToolsetConfig configures model-facing memory tools.
type MissingFieldsAction ¶
type MissingFieldsAction string
MissingFieldsAction controls behavior when a tool validation error indicates missing fields. It is string-backed for JSON friendliness. Empty value means unspecified (planner decides).
const ( // MissingFieldsFinalize instructs the runtime to finalize immediately // when fields are missing. MissingFieldsFinalize MissingFieldsAction = "finalize" // MissingFieldsAwaitClarification instructs the runtime to pause and await user clarification. MissingFieldsAwaitClarification MissingFieldsAction = "await_clarification" // MissingFieldsResume instructs the runtime to continue without pausing; surface hints to the planner. MissingFieldsResume MissingFieldsAction = "resume" )
type ModelInterceptor ¶ added in v1.2.2
type ModelInterceptor interface {
BeforeModel(context.Context, *BeforeModelInput) (*BeforeModelDecision, error)
AfterModel(context.Context, *AfterModelInput) (*AfterModelDecision, error)
}
ModelInterceptor observes or changes model invocation behavior.
type OllamaConfig ¶ added in v1.2.2
type OllamaConfig struct {
ServerURL string
HTTPClient *http.Client
DefaultModel string
HighModel string
SmallModel string
MaxTokens int
Temperature float32
Timeout time.Duration
}
OllamaConfig configures the local Ollama-backed model client created by the runtime.
type OneShotRunInput ¶
type OneShotRunInput struct {
// AgentID identifies the logical agent identity for hook and run-log events.
AgentID agent.Ident
// RunID is the durable run identifier used by run-log storage.
RunID string
// TurnID identifies the logical turn for event grouping.
TurnID string
// Labels attaches optional metadata to the run context.
Labels map[string]string
// Metadata carries caller-provided structured metadata.
Metadata map[string]any
}
OneShotRunInput configures one-shot run execution.
One-shot runs are explicit sessionless executions used for request/response workloads that still require durable run-log introspection.
Contract: - AgentID is required. - Session ownership is always empty; one-shot runs never attach to a session. - TurnID defaults to RunID when omitted. - RunID defaults to a generated ID when omitted.
type OpenAIConfig ¶ added in v1.2.0
type OpenAIConfig struct {
APIKey string
BaseURL string
DefaultModel string
HighModel string
SmallModel string
}
OpenAIConfig configures the OpenAI-backed model client created by the runtime.
type Options ¶
type Options struct {
// Engine is the workflow backend adapter (Temporal by default).
Engine engine.Engine
// MemoryStore persists run transcripts and annotations.
MemoryStore memory.Store
// MemorySearcher provides indexed or cross-run memory lookup.
MemorySearcher memory.Searcher
// MemoryService stores and searches long-term entry memory.
MemoryService memory.Service
// MemoryScopeResolver derives tenant/user scope for runtime-owned memory calls.
MemoryScopeResolver memory.ScopeResolver
// ArtifactStore persists tool-produced run artifacts.
ArtifactStore artifact.Store
// PromptStore resolves scoped prompt overrides. When nil, prompt rendering
// uses baseline registered PromptSpecs only.
PromptStore prompt.Store
// SessionStore persists session lifecycle state and run metadata.
SessionStore session.Store
// Policy evaluates allowlists and caps per planner turn.
Policy policy.Engine
// RunEventStore is the canonical append-only run event log.
RunEventStore runlog.Store
// Hooks is the Pulse-backed bus used for streaming runtime events.
Hooks hooks.Bus
// Stream publishes planner/tool/assistant events to the caller.
Stream stream.Sink
// Logger emits structured logs (usually backed by Clue).
Logger telemetry.Logger
// Metrics records counters/histograms for runtime operations.
Metrics telemetry.Metrics
// Tracer emits spans for planner/tool execution.
Tracer telemetry.Tracer
// CaptureGenAIMessages records full model input/output messages on GenAI
// spans. This is default-off because the payload can contain sensitive data.
CaptureGenAIMessages bool
// HookActivityTimeout overrides the StartToClose timeout for the
// hook publishing activity (`runtime.publish_hook`). Zero means use the
// runtime default.
HookActivityTimeout time.Duration
// Workers provides per-agent worker configuration. If an agent lacks
// an entry, the runtime uses a default worker configuration. Engines
// that do not poll (in-memory) ignore this map.
Workers map[agent.Ident]WorkerConfig
// ToolConfirmation configures runtime-enforced confirmation overrides for selected
// tools (for example, requiring explicit operator approval before executing
// additional tools that are not marked with design-time Confirmation).
ToolConfirmation *ToolConfirmationConfig
// Interceptors observe or change runtime call-path behavior before durable
// hook events are emitted.
Interceptors []Interceptor
// NamedInterceptors maps design-owned interceptor IDs to application-owned
// implementations used by generated agent registrations.
NamedInterceptors map[string]Interceptor
// HintOverrides optionally overrides DSL-authored call hints for specific tools
// when streaming tool_start events.
HintOverrides map[tools.Ident]HintOverrideFunc
}
Options configures the Runtime instance. All fields are optional except Engine for production deployments. Noop implementations are substituted for nil Logger, Metrics, and Tracer. A default in-memory event bus is created if Hooks is nil.
type PlanActivityInput ¶
type PlanActivityInput = api.PlanActivityInput
type PlanActivityOutput ¶
type PlanActivityOutput = api.PlanActivityOutput
type PolicyOverrides ¶
type PolicyOverrides = api.PolicyOverrides
PolicyOverrides configures per-run policy constraints. All fields are optional; zero values mean no override.
type PromptBuilder ¶
PromptBuilder builds a user message for a tool call from its payload when no explicit text or template is configured.
type PromptRenderHookContext ¶
type PromptRenderHookContext struct {
RunID string
AgentID agent.Ident
SessionID string
TurnID string
}
PromptRenderHookContext identifies one agent run turn for prompt_rendered hook emission.
type ResultMaterializer ¶
type ResultMaterializer func(ctx context.Context, meta ToolCallMeta, call *planner.ToolRequest, result *planner.ToolResult) error
ResultMaterializer enriches a typed tool result before the runtime encodes and publishes it.
Contract:
- The runtime invokes materializers on both the normal execution path and the externally provided-result await path.
- Materializers may attach server-only sidecars to `result.ServerData` and may normalize the typed semantic result before canonical encoding.
- Materializers must be deterministic and must not perform I/O when they run inside workflow code.
type RetryAndReflectConfig ¶ added in v1.2.2
type RetryAndReflectConfig struct {
// MaxRetries is the number of tool failures that receive reflective retry
// guidance before the policy stops handling the error. Defaults to 3.
MaxRetries int
// ErrorIfRetryExceeded returns the original tool execution error once the
// retry budget is exhausted. When false, the final failure is still returned
// as a tool result with retry guidance.
ErrorIfRetryExceeded bool
}
RetryAndReflectConfig configures the retry-and-reflect interceptor.
type RunInterceptor ¶ added in v1.2.2
type RunInterceptor interface {
BeforeRun(context.Context, *BeforeRunInput) (*BeforeRunDecision, error)
AfterRun(context.Context, *AfterRunInput) (*AfterRunDecision, error)
}
RunInterceptor observes or changes run lifecycle behavior.
type RunNotAwaitableError ¶
type RunNotAwaitableError struct {
// RunID identifies the rejected run.
RunID string
// Reason describes why the run rejected await-resume input.
Reason RunNotAwaitableReason
// Cause stores the underlying engine-level error.
Cause error
}
RunNotAwaitableError reports that a run cannot accept clarification answers, confirmation decisions, or external tool results.
Reason indicates whether the run is unknown or already completed. Cause carries the underlying engine error.
func AsRunNotAwaitable ¶
func AsRunNotAwaitable(err error) (*RunNotAwaitableError, bool)
AsRunNotAwaitable extracts a typed run-not-awaitable error.
func (*RunNotAwaitableError) Error ¶
func (e *RunNotAwaitableError) Error() string
Error returns a stable, human-readable classification for logs.
func (*RunNotAwaitableError) Is ¶
func (e *RunNotAwaitableError) Is(target error) bool
Is allows errors.Is(err, ErrRunNotAwaitable) classification.
func (*RunNotAwaitableError) Unwrap ¶
func (e *RunNotAwaitableError) Unwrap() error
Unwrap exposes the engine cause.
type RunNotAwaitableReason ¶
type RunNotAwaitableReason string
RunNotAwaitableReason classifies why a run cannot accept await-resume input.
const ( // RunNotAwaitableUnknownRun indicates no workflow exists for RunID. RunNotAwaitableUnknownRun RunNotAwaitableReason = "unknown_run" // RunNotAwaitableCompletedRun indicates the workflow already reached a terminal state. RunNotAwaitableCompletedRun RunNotAwaitableReason = "completed_run" )
type RunOption ¶
type RunOption func(*RunInput)
RunOption configures optional fields on RunInput for Run and Start. Required values such as SessionID are positional arguments on AgentClient methods and must not be set via RunOption.
func WithAllowedTags ¶
WithAllowedTags filters candidate tools to those whose tags intersect this list.
func WithDeniedTags ¶
WithDeniedTags filters out candidate tools that have any of these tags.
func WithLabels ¶
WithLabels merges the provided labels into the constructed RunInput.
func WithMetadata ¶
WithMetadata merges the provided metadata into the constructed RunInput.
func WithPerTurnMaxToolCalls ¶
WithPerTurnMaxToolCalls sets a per-turn cap on tool executions. Zero means unlimited.
func WithRestrictToTool ¶
WithRestrictToTool restricts candidate tools to a single tool for the run.
func WithRunFinalizerGrace ¶
WithRunFinalizerGrace reserves time to produce a final assistant message after the run budget is exhausted.
func WithRunInterruptsAllowed ¶
WithRunInterruptsAllowed enables human-in-the-loop interruptions for this run.
func WithRunMaxConsecutiveFailedToolCalls ¶
WithRunMaxConsecutiveFailedToolCalls caps consecutive failures before aborting the run.
func WithRunMaxToolCalls ¶
WithRunMaxToolCalls sets a per-run cap on total tool executions.
func WithRunTimeBudget ¶
WithRunTimeBudget sets the semantic wall-clock budget for planner and tool work in the run.
func WithSearchAttributes ¶
WithSearchAttributes sets search attributes on WorkflowOptions for this run.
func WithTaskQueue ¶
WithTaskQueue sets the target task queue on WorkflowOptions for this run.
func WithTiming ¶
WithTiming sets run-level timing overrides in a single structured option. Budget is the semantic run budget; Plan and Tools are attempt budgets. Zero- valued fields are ignored.
func WithTurnID ¶
WithTurnID sets the TurnID on the constructed RunInput.
func WithWorkflowOptions ¶
func WithWorkflowOptions(o *WorkflowOptions) RunOption
WithWorkflowOptions sets workflow engine options on the constructed RunInput.
type RunOutput ¶
RunOutput represents the final outcome returned by a run workflow, including the concluding assistant message plus tool traces and planner notes for callers.
type RunPolicy ¶
type RunPolicy struct {
// MaxToolCalls caps the total number of tool invocations per run (0 = unlimited).
MaxToolCalls int
// MaxConsecutiveFailedToolCalls caps sequential failures before aborting (0 = unlimited).
MaxConsecutiveFailedToolCalls int
// TimeBudget is the semantic wall-clock budget for planner and tool work
// within the run (0 = unlimited). The runtime derives the engine run timeout
// from this budget plus finalizer reserve and a small engine headroom.
TimeBudget time.Duration
// FinalizerGrace reserves time to produce a last assistant message after the
// budget is exhausted. When set, the runtime stops scheduling new work once
// the remaining time is less than or equal to this value and requests a final
// response from the planner. Zero means no reserved window; defaults may apply.
FinalizerGrace time.Duration
// InterruptsAllowed indicates whether the workflow can be paused and resumed.
InterruptsAllowed bool
// OnMissingFields controls behavior when validation indicates missing fields:
// "finalize" | "await_clarification" | "resume"
OnMissingFields MissingFieldsAction
// History, when non-nil, transforms the message history before each planner
// invocation (PlanStart and PlanResume). It can truncate or compress history
// while preserving system prompts and logical turn boundaries.
History HistoryPolicy
// Cache configures automatic prompt cache checkpoint placement.
Cache CachePolicy
// NamedInterceptors lists application-owned interceptor IDs declared in
// the agent design.
NamedInterceptors []string
// PreloadMemory injects bounded memory snippets into planner inputs before
// each planning turn. Nil preserves the default no-preload behavior.
PreloadMemory *MemoryPreloadPolicy
// PreloadLongTermMemory injects bounded long-term memory entries into
// planner inputs before each planning turn.
PreloadLongTermMemory *LongTermMemoryPreloadPolicy
}
RunPolicy configures per-agent runtime behavior (caps, time budgets, interrupts). These values are evaluated during workflow execution to enforce limits and prevent runaway tool loops or budget overruns.
type Runtime ¶
type Runtime struct {
// Engine is the workflow backend adapter (Temporal by default).
Engine engine.Engine
// MemoryStore persists run transcripts and annotations.
Memory memory.Store
// MemorySearcher provides indexed or cross-run memory lookup.
MemorySearcher memory.Searcher
// MemoryService stores and searches long-term entry memory.
MemoryService memory.Service
// MemoryScopeResolver derives tenant/user scope for runtime-owned memory calls.
MemoryScopeResolver memory.ScopeResolver
// ArtifactStore persists tool-produced run artifacts.
ArtifactStore artifact.Store
// PromptRegistry resolves prompt specs and optional scoped overrides.
PromptRegistry *prompt.Registry
// SessionStore persists session lifecycle state and run metadata.
SessionStore session.Store
// Policy evaluates allowlists and caps per planner turn.
Policy policy.Engine
// RunEventStore is the canonical append-only run event log.
RunEventStore runlog.Store
// Bus is the bus used for streaming runtime events.
Bus hooks.Bus
// Stream publishes planner/tool/assistant events to the caller.
Stream stream.Sink
// contains filtered or unexported fields
}
Runtime orchestrates agent workflows, policy enforcement, memory persistence, and event streaming. It serves as the central registry for agents, toolsets, and models. All public methods are thread-safe and can be called concurrently.
The Runtime coordinates with several subsystems:
- Workflow engine (Temporal) for durable execution
- Policy engine for runtime caps and tool filtering
- Memory store for transcript persistence
- Event bus (hooks) for observability and streaming
- Telemetry subsystems (logging, metrics, tracing)
Lifecycle:
- Construct with New()
- Register agents, toolsets, and models
- Start workflows via AgentClient (Run or Start)
The Runtime automatically subscribes to hooks for memory persistence and stream publishing when MemoryStore or Stream are configured.
func New ¶
func New(opts ...RuntimeOption) *Runtime
New constructs a Runtime using functional options.
func (*Runtime) AddEventsToMemory ¶ added in v1.2.2
func (r *Runtime) AddEventsToMemory(ctx context.Context, input memory.IngestEventsInput) (memory.IngestResult, error)
AddEventsToMemory ingests event deltas into the configured long-term memory service.
func (*Runtime) AddRunToMemory ¶ added in v1.2.2
func (r *Runtime) AddRunToMemory(ctx context.Context, input memory.IngestRunInput) (memory.IngestResult, error)
AddRunToMemory ingests a run snapshot into the configured long-term memory service.
func (*Runtime) Client ¶
func (r *Runtime) Client(id agent.Ident) (AgentClient, error)
Client returns a typed client for one locally registered agent.
Returns ErrAgentNotFound when id is empty or not present in runtime registration.
func (*Runtime) ClientFor ¶
func (r *Runtime) ClientFor(route AgentRoute) (AgentClient, error)
ClientFor returns a typed client for one externally supplied route.
Use this in caller-only processes that do not register agents locally but still need to start workflows against worker-owned routes. Returns ErrAgentNotFound when route metadata is incomplete.
func (*Runtime) CreateSession ¶
CreateSession creates (or returns) an active session with the given ID.
Contract: - sessionID must be non-empty and non-whitespace. - Creating an already-active session is idempotent. - Creating an ended session returns session.ErrSessionEnded.
func (*Runtime) DeleteSession ¶
DeleteSession ends a session with the given ID.
Contract: - Ending a session is durable and monotonic. - Cancellation of in-flight runs is best-effort and bounded.
func (*Runtime) ExecuteAgentChildWithRoute ¶
func (r *Runtime) ExecuteAgentChildWithRoute( wfCtx engine.WorkflowContext, route AgentRoute, messages []*model.Message, nestedRunCtx run.Context, ) (*RunOutput, error)
ExecuteAgentChildWithRoute starts a provider agent as a child workflow using the explicit route metadata (workflow name and task queue). The child executes its own plan/execute loop and returns a RunOutput which is adapted by callers.
func (*Runtime) ExecuteToolActivity ¶
ExecuteToolActivity runs a tool invocation as a workflow activity.
Advanced & generated integration
- Intended to be registered by generated code with the workflow engine.
- Normal applications should use AgentClient (Runtime.Client(...).Run/Start) rather than invoking activities directly.
It decodes the tool payload, runs the registered tool implementation, and encodes the result using the tool‑specific codec. Returns an error if the toolset is not registered or if encoding/decoding fails.
func (*Runtime) ExecuteWorkflow ¶
func (r *Runtime) ExecuteWorkflow(wfCtx engine.WorkflowContext, input *RunInput) (out *RunOutput, retErr error)
ExecuteWorkflow is the main entry point for the generated workflow handler.
Advanced & generated integration
- Intended to be invoked by code generated by loom-mcp during agent registration, or by advanced users writing custom engine adapters.
- Normal applications should prefer the high‑level AgentClient API (Runtime.Client(...).Run/Start) rather than calling this directly.
It executes the agent's plan/tool loop using the configured planner, policy, and runtime hooks. Returns the final agent output or an error if the workflow fails. Generated code calls this from the workflow handler registered with the engine.
func (*Runtime) GetRunSnapshot ¶
GetRunSnapshot derives a compact snapshot of the run state by replaying the canonical run log.
func (*Runtime) ListAgents ¶
ListAgents returns the IDs of registered agents.
func (*Runtime) ListRunEvents ¶
func (r *Runtime) ListRunEvents(ctx context.Context, runID, cursor string, limit int) (runlog.Page, error)
ListRunEvents returns a forward page of canonical run events for the given run.
func (*Runtime) ListToolsets ¶
ListToolsets returns the names of registered toolsets.
func (*Runtime) ModelClient ¶
ModelClient returns a registered model client by ID, if present.
func (*Runtime) MustClient ¶
func (r *Runtime) MustClient(id agent.Ident) AgentClient
MustClient is like Client but panics when the agent is unknown.
This is intended for process initialization paths where missing agent registration is a startup bug.
func (*Runtime) MustClientFor ¶
func (r *Runtime) MustClientFor(route AgentRoute) AgentClient
MustClientFor is like ClientFor but panics on invalid route metadata.
This is intended for startup paths where route metadata is expected to be validated by construction.
func (*Runtime) NewBedrockModelClient ¶
func (r *Runtime) NewBedrockModelClient(awsrt *bedrockruntime.Client, cfg BedrockConfig) (model.Client, error)
NewBedrockModelClient constructs a model.Client backed by AWS Bedrock using the runtime's own ledger access.
func (*Runtime) NewGeminiModelClient ¶ added in v1.2.0
NewGeminiModelClient constructs a model.Client backed by the Gemini API using Google's official Gen AI SDK. The client is not registered automatically; pass it to RegisterModel with the model ID your planners use.
func (*Runtime) NewOllamaModelClient ¶ added in v1.2.2
func (r *Runtime) NewOllamaModelClient(cfg OllamaConfig) (model.Client, error)
NewOllamaModelClient constructs a model.Client backed by a local Ollama server. The client is not registered automatically; pass it to RegisterModel with the model ID your planners use.
func (*Runtime) NewOpenAIModelClient ¶ added in v1.2.0
func (r *Runtime) NewOpenAIModelClient(cfg OpenAIConfig) (model.Client, error)
NewOpenAIModelClient constructs a model.Client backed by the OpenAI Responses API using the official OpenAI Go SDK. The client is not registered automatically; pass it to RegisterModel with the model ID your planners use.
func (*Runtime) NewVertexGeminiModelClient ¶ added in v1.2.0
func (r *Runtime) NewVertexGeminiModelClient(ctx context.Context, cfg VertexConfig) (model.Client, error)
NewVertexGeminiModelClient constructs a model.Client backed by Vertex AI Gemini using Google's official Gen AI SDK. Authentication is delegated to the SDK's Vertex backend, which uses Application Default Credentials when no explicit credentials are supplied by the environment.
func (*Runtime) OverridePolicy ¶
OverridePolicy applies a best-effort in-process override of the registered agent policy.
func (*Runtime) PauseRun ¶
PauseRun requests the underlying workflow to pause via the standard pause signal.
func (*Runtime) PlanResumeActivity ¶
func (r *Runtime) PlanResumeActivity(ctx context.Context, input *PlanActivityInput) (*PlanActivityOutput, error)
PlanResumeActivity executes the planner's PlanResume method.
Advanced & generated integration
- Intended to be registered by generated code with the workflow engine.
- Normal applications should use AgentClient (Runtime.Client(...).Run/Start) instead of invoking activities directly.
This activity is registered with the workflow engine and invoked after tool execution to produce the next plan. The activity creates an agent context with memory access and delegates to the planner's PlanResume implementation.
func (*Runtime) PlanStartActivity ¶
func (r *Runtime) PlanStartActivity(ctx context.Context, input *PlanActivityInput) (*PlanActivityOutput, error)
PlanStartActivity executes the planner's PlanStart method.
Advanced & generated integration
- Intended to be registered by generated code with the workflow engine.
- Normal applications should use AgentClient (Runtime.Client(...).Run/Start) instead of invoking activities directly.
This activity is registered with the workflow engine and invoked at the beginning of a run to produce the initial plan. The activity creates an agent context with memory access and delegates to the planner's PlanStart implementation.
func (*Runtime) ProvideClarification ¶
func (r *Runtime) ProvideClarification(ctx context.Context, ans interrupt.ClarificationAnswer) error
ProvideClarification sends a typed clarification answer to a waiting run.
func (*Runtime) ProvideConfirmation ¶
func (r *Runtime) ProvideConfirmation(ctx context.Context, dec interrupt.ConfirmationDecision) error
ProvideConfirmation sends a typed confirmation decision to a waiting run.
func (*Runtime) ProvideToolResults ¶
ProvideToolResults sends a set of external tool results to a waiting run.
func (*Runtime) ProvideTypedInput ¶ added in v1.2.2
ProvideTypedInput sends a schema-typed human input answer to a waiting run.
func (*Runtime) PutMemoryEntry ¶ added in v1.2.2
func (r *Runtime) PutMemoryEntry(ctx context.Context, input memory.PutEntryInput) (memory.Entry, error)
PutMemoryEntry writes a direct long-term memory entry.
func (*Runtime) RegisterAgent ¶
func (r *Runtime) RegisterAgent(ctx context.Context, reg AgentRegistration) error
RegisterAgent validates the registration, registers workflows and activities, and stores agent metadata.
func (*Runtime) RegisterModel ¶
RegisterModel registers a ModelClient by identifier for planner lookup.
func (*Runtime) RegisterToolset ¶
func (r *Runtime) RegisterToolset(ts ToolsetRegistration) error
RegisterToolset registers a toolset outside of agent registration.
func (*Runtime) ResolvePromptRefs ¶
ResolvePromptRefs returns prompt refs for the run and all linked child runs.
This is a convenience wrapper around session.ResolvePromptRefs that uses the runtime's configured SessionStore.
func (*Runtime) RunOneShot ¶
func (r *Runtime) RunOneShot(ctx context.Context, input OneShotRunInput, execute func(context.Context) error) error
RunOneShot executes one sessionless run and appends canonical lifecycle/prompt events to the run log.
The execute callback receives a context stamped with PromptRenderHookContext so prompt renders inside the callback emit canonical prompt_rendered run-log events.
Contract: - RunOneShot never creates/loads/updates session state. - RunOneShot never emits session stream events. - Hook append failures are terminal.
func (*Runtime) Seal ¶
Seal closes the registration phase and activates engines that stage worker handlers until the runtime is fully configured. Worker deployments should call Seal after registering all toolsets and agents, before serving traffic. When the engine supports staged workers, Seal returns only after activation succeeds or ctx ends.
Successful Seal calls are idempotent. The first call closes registration so later RegisterAgent/RegisterToolset calls fail fast even if activation later fails. Callers may retry Seal after a context-limited activation failure.
func (*Runtime) ToolSchema ¶
ToolSchema returns the parsed JSON schema for the tool payload when available.
type RuntimeInterceptorFuncs ¶ added in v1.2.2
type RuntimeInterceptorFuncs struct {
BeforeRunFunc func(context.Context, *BeforeRunInput) (*BeforeRunDecision, error)
AfterRunFunc func(context.Context, *AfterRunInput) (*AfterRunDecision, error)
BeforeToolFunc func(context.Context, *BeforeToolInput) (*BeforeToolDecision, error)
AfterToolFunc func(context.Context, *AfterToolInput) (*AfterToolDecision, error)
BeforeModelFunc func(context.Context, *BeforeModelInput) (*BeforeModelDecision, error)
AfterModelFunc func(context.Context, *AfterModelInput) (*AfterModelDecision, error)
BeforeEventFunc func(context.Context, *BeforeEventInput) (*BeforeEventDecision, error)
AfterEventFunc func(context.Context, *AfterEventInput) (*AfterEventDecision, error)
}
RuntimeInterceptorFuncs adapts function fields into typed interceptors.
func (RuntimeInterceptorFuncs) AfterEvent ¶ added in v1.2.2
func (f RuntimeInterceptorFuncs) AfterEvent(ctx context.Context, input *AfterEventInput) (*AfterEventDecision, error)
AfterEvent implements EventInterceptor.
func (RuntimeInterceptorFuncs) AfterModel ¶ added in v1.2.2
func (f RuntimeInterceptorFuncs) AfterModel(ctx context.Context, input *AfterModelInput) (*AfterModelDecision, error)
AfterModel implements ModelInterceptor.
func (RuntimeInterceptorFuncs) AfterRun ¶ added in v1.2.2
func (f RuntimeInterceptorFuncs) AfterRun(ctx context.Context, input *AfterRunInput) (*AfterRunDecision, error)
AfterRun implements RunInterceptor.
func (RuntimeInterceptorFuncs) AfterTool ¶ added in v1.2.2
func (f RuntimeInterceptorFuncs) AfterTool(ctx context.Context, input *AfterToolInput) (*AfterToolDecision, error)
AfterTool implements ToolInterceptor.
func (RuntimeInterceptorFuncs) BeforeEvent ¶ added in v1.2.2
func (f RuntimeInterceptorFuncs) BeforeEvent(ctx context.Context, input *BeforeEventInput) (*BeforeEventDecision, error)
BeforeEvent implements EventInterceptor.
func (RuntimeInterceptorFuncs) BeforeModel ¶ added in v1.2.2
func (f RuntimeInterceptorFuncs) BeforeModel(ctx context.Context, input *BeforeModelInput) (*BeforeModelDecision, error)
BeforeModel implements ModelInterceptor.
func (RuntimeInterceptorFuncs) BeforeRun ¶ added in v1.2.2
func (f RuntimeInterceptorFuncs) BeforeRun(ctx context.Context, input *BeforeRunInput) (*BeforeRunDecision, error)
BeforeRun implements RunInterceptor.
func (RuntimeInterceptorFuncs) BeforeTool ¶ added in v1.2.2
func (f RuntimeInterceptorFuncs) BeforeTool(ctx context.Context, input *BeforeToolInput) (*BeforeToolDecision, error)
BeforeTool implements ToolInterceptor.
type RuntimeOption ¶
type RuntimeOption func(*Options)
RuntimeOption configures the runtime via functional options passed to NewWith.
func WithArtifactStore ¶ added in v1.2.2
func WithArtifactStore(s artifact.Store) RuntimeOption
WithArtifactStore sets the artifact store.
func WithCaptureGenAIMessages ¶ added in v1.2.0
func WithCaptureGenAIMessages(enabled bool) RuntimeOption
WithCaptureGenAIMessages opts model spans into sensitive GenAI message attributes.
func WithEngine ¶
func WithEngine(e engine.Engine) RuntimeOption
WithEngine sets the workflow engine.
func WithHintOverrides ¶
func WithHintOverrides(m map[tools.Ident]HintOverrideFunc) RuntimeOption
WithHintOverrides configures per-tool call hint overrides.
func WithHookActivityTimeout ¶
func WithHookActivityTimeout(d time.Duration) RuntimeOption
WithHookActivityTimeout sets the StartToClose timeout for the hook publishing activity.
func WithInterceptors ¶ added in v1.2.2
func WithInterceptors(interceptors ...Interceptor) RuntimeOption
WithInterceptors registers call-path interceptors in execution order.
func WithMemoryScopeResolver ¶ added in v1.2.2
func WithMemoryScopeResolver(r memory.ScopeResolver) RuntimeOption
WithMemoryScopeResolver sets the long-term memory scope resolver.
func WithMemorySearcher ¶ added in v1.2.2
func WithMemorySearcher(s memory.Searcher) RuntimeOption
WithMemorySearcher sets the indexed or cross-run memory searcher.
func WithMemoryService ¶ added in v1.2.2
func WithMemoryService(s memory.Service) RuntimeOption
WithMemoryService sets the long-term memory service.
func WithMemoryStore ¶
func WithMemoryStore(m memory.Store) RuntimeOption
WithMemoryStore sets the memory store.
func WithMetrics ¶
func WithMetrics(m telemetry.Metrics) RuntimeOption
WithMetrics sets the metrics recorder.
func WithNamedInterceptors ¶ added in v1.2.2
func WithNamedInterceptors(interceptors map[string]Interceptor) RuntimeOption
WithNamedInterceptors registers application-owned interceptors by design ID.
func WithPromptStore ¶
func WithPromptStore(s prompt.Store) RuntimeOption
WithPromptStore sets the prompt override store.
func WithRunEventStore ¶
func WithRunEventStore(s runlog.Store) RuntimeOption
WithRunEventStore sets the canonical run event store.
func WithSessionStore ¶
func WithSessionStore(s session.Store) RuntimeOption
WithSessionStore sets the session store.
func WithToolConfirmation ¶
func WithToolConfirmation(cfg *ToolConfirmationConfig) RuntimeOption
WithToolConfirmation configures runtime-enforced confirmation for selected tools.
func WithWorker ¶
func WithWorker(id agent.Ident, cfg WorkerConfig) RuntimeOption
WithWorker configures the worker for a specific agent.
type SkillToolsetConfig ¶ added in v1.2.2
type SkillToolsetConfig struct {
// Name is the toolset name used to construct canonical tool IDs.
Name string
// Roots are filesystem directories containing child skill directories.
Roots []string
// Preload controls global skill preloading when skill metadata does not opt in.
Preload mcpskills.PreloadMode
// Reload controls global skill reload behavior when skill metadata does not override it.
Reload mcpskills.ReloadMode
}
SkillToolsetConfig configures a model-facing skill toolset.
type SubscriberMode ¶ added in v1.1.3
type SubscriberMode int
SubscriberMode classifies how a hook-bus subscriber's errors are treated.
- SubscriberCritical: errors propagate out of Bus.Publish and can fail the hook activity (and therefore the agent run). Use for sinks whose correctness is coupled to the canonical run record (audit/runlog).
- SubscriberBestEffort: errors are recorded on the logger and tracer but never propagate. Use for derived projections (session metadata, memory projection) and external observers (stream) that must not corrupt the canonical record.
const ( // SubscriberCritical subscribers fail the hook activity (and therefore the // run) on error. SubscriberCritical SubscriberMode = iota // SubscriberBestEffort subscribers cannot fail a run; their errors are // logged and recorded on the tracer only. SubscriberBestEffort )
type Timing ¶
type Timing struct {
// Budget sets the total wall-clock budget for this run.
Budget time.Duration
// Plan sets the Plan/Resume activity timeout for this run.
Plan time.Duration
// Tools sets the default ExecuteTool activity timeout for this run.
Tools time.Duration
// PerToolTimeout allows targeting specific tools with custom timeouts.
PerToolTimeout map[tools.Ident]time.Duration
}
Timing groups per-run timing overrides in a single structure. Zero values mean no override.
type ToolActivityExecutor ¶
type ToolActivityExecutor interface {
// Execute runs the tool with the given input and returns the result.
// The workflow context is provided for workflow-level operations (activities,
// timers, etc.). Input and output use the ToolInput/ToolOutput envelope.
Execute(ctx context.Context, wfCtx engine.WorkflowContext, input *ToolInput) (*ToolOutput, error)
}
ToolActivityExecutor handles execution of a single tool via workflow activities. Implementations decide how to schedule and await activity completion while preserving workflow determinism.
type ToolCallExecutor ¶
type ToolCallExecutor interface {
Execute(ctx context.Context, meta *ToolCallMeta, call *planner.ToolRequest) (*ToolExecutionResult, error)
}
ToolCallExecutor executes a tool call and returns a runtime-owned execution result. This generic interface enables a uniform execution model across method-backed tools, MCP tools, and agent-tools. Registrations accept a ToolCallExecutor and the runtime delegates execution via this interface.
type ToolCallExecutorFunc ¶
type ToolCallExecutorFunc func(ctx context.Context, meta *ToolCallMeta, call *planner.ToolRequest) (*ToolExecutionResult, error)
ToolCallExecutorFunc adapts a function to the ToolCallExecutor interface.
func (ToolCallExecutorFunc) Execute ¶
func (f ToolCallExecutorFunc) Execute(ctx context.Context, meta *ToolCallMeta, call *planner.ToolRequest) (*ToolExecutionResult, error)
Execute calls f(ctx, meta, call).
type ToolCallMeta ¶
type ToolCallMeta struct {
// RunID is the durable workflow execution identifier of the run that
// owns this tool call. It remains stable across retries and is used to
// correlate runtime records and telemetry.
RunID string
// SessionID logically groups related runs (for example a chat
// conversation). Services typically index memory and search attributes
// by session.
SessionID string
// TurnID identifies the conversational turn that produced this tool
// call. When set, event streams use it to order and group events.
TurnID string
// ToolCallID uniquely identifies this tool invocation. It is used to
// correlate start/update/end events and parent/child relationships.
ToolCallID string
// ParentToolCallID is the identifier of the parent tool call when this
// invocation is a child (for example a tool launched by an agent-tool).
// UIs and subscribers use it to reconstruct the call tree.
ParentToolCallID string
}
ToolCallMeta carries run-scoped identifiers for executors. It provides explicit access to business context (RunID, SessionID, TurnID, correlation IDs) without relying on context values.
type ToolConfirmation ¶
type ToolConfirmation struct {
// Prompt returns the deterministic prompt shown to the user for this call.
Prompt func(ctx context.Context, call *planner.ToolRequest) (string, error)
// DeniedResult constructs a schema-compatible tool result value representing
// a user denial. The runtime attaches it to the original tool_call_id with
// Error unset.
DeniedResult func(ctx context.Context, call *planner.ToolRequest) (any, error)
}
ToolConfirmation defines how to request confirmation and how to represent a user denial for a given tool.
type ToolConfirmationConfig ¶
type ToolConfirmationConfig struct {
// Confirm maps tool IDs to confirmation handlers.
//
// These handlers are an override mechanism used to:
// - require confirmation for tools that do not declare design-time Confirmation
// - override prompt/denied-result rendering for specific tool IDs
Confirm map[tools.Ident]*ToolConfirmation
}
ToolConfirmationConfig configures runtime-enforced confirmation for specific tools. When enabled, the runtime requires explicit operator approval before executing configured tool calls.
This is runtime-owned policy: planners do not need to special-case confirmation flows for configured tools.
type ToolExecutionResult ¶ added in v1.1.6
type ToolExecutionResult struct {
ToolResult *planner.ToolResult
Pause *ToolPause
}
ToolExecutionResult captures the runtime-owned outcome of one tool invocation.
Contract:
- ToolResult is required and carries the durable planner-visible tool outcome for transcript, hooks, and cumulative ToolOutputs history.
- Pause is optional and is consumed only by the current execution batch.
- Pause is never copied into cumulative planner ToolOutputs history.
func Executed ¶ added in v1.1.6
func Executed(result *planner.ToolResult) *ToolExecutionResult
Executed wraps a durable tool result with no current-batch pause.
type ToolInterceptor ¶ added in v1.2.2
type ToolInterceptor interface {
BeforeTool(context.Context, *BeforeToolInput) (*BeforeToolDecision, error)
AfterTool(context.Context, *AfterToolInput) (*AfterToolDecision, error)
}
ToolInterceptor observes or changes tool execution behavior.
type ToolInterceptorFuncs ¶ added in v1.2.2
type ToolInterceptorFuncs struct {
BeforeToolFunc func(context.Context, *BeforeToolInput) (*BeforeToolDecision, error)
AfterToolFunc func(context.Context, *AfterToolInput) (*AfterToolDecision, error)
}
ToolInterceptorFuncs adapts function fields into an Interceptor.
func (ToolInterceptorFuncs) AfterTool ¶ added in v1.2.2
func (f ToolInterceptorFuncs) AfterTool(ctx context.Context, input *AfterToolInput) (*AfterToolDecision, error)
AfterTool implements Interceptor.
func (ToolInterceptorFuncs) BeforeTool ¶ added in v1.2.2
func (f ToolInterceptorFuncs) BeforeTool(ctx context.Context, input *BeforeToolInput) (*BeforeToolDecision, error)
BeforeTool implements Interceptor.
type ToolOutput ¶
type ToolOutput = api.ToolOutput
type ToolPauseClarification ¶ added in v1.1.6
type ToolPauseClarification = api.ToolPauseClarification
type ToolsetRegistration ¶
type ToolsetRegistration struct {
// Name is the qualified toolset name (e.g., "service.toolset_name").
Name string
// Description provides human-readable context for tooling.
Description string
// Metadata captures structured policy metadata about the toolset.
Metadata policy.ToolMetadata
// Execute invokes the concrete tool implementation for a given tool call.
// Returns a ToolResult containing the payload, telemetry, errors, and retry hints.
//
// For service-based tools, codegen generates this function to call service clients.
// For agent-tools (Exports), generated registrations set Inline=true and
// populate AgentTool so the workflow runtime can start nested agents as child
// workflows and adapt their RunOutput into a ToolResult.
// For custom/server-side tools, users provide their own implementation.
Execute func(ctx context.Context, call *planner.ToolRequest) (*ToolExecutionResult, error)
// Specs enumerates the codecs associated with each tool in the set.
// Used by the runtime for JSON marshaling/unmarshaling and schema validation.
Specs []tools.ToolSpec
// TaskQueue optionally overrides the queue used when scheduling this toolset's activities.
TaskQueue string
// Inline indicates that tools in this toolset execute inside the workflow
// context (not as activities). For agent-as-tool, the executor needs a
// WorkflowContext to start the provider as a child workflow. Service-backed
// toolsets should leave this false so calls run as activities (isolation/retries).
Inline bool
// CallHints optionally provides precompiled templates for call display hints
// keyed by tool ident. When present, RegisterToolset installs these in the
// global hints registry so sinks can render concise, domain-authored labels.
CallHints map[tools.Ident]*template.Template
// ResultHints optionally provides precompiled templates for result previews
// keyed by tool ident. Templates receive the runtime-owned preview wrapper
// where semantic data is available under `.Result` and bounded metadata
// under `.Bounds`. When present, RegisterToolset installs these in the
// global hints registry so sinks can render concise result previews.
ResultHints map[tools.Ident]*template.Template
// PayloadAdapter normalizes or enriches raw JSON payloads prior to decoding.
// The adapter is applied exactly once at the activity boundary, or before
// inline execution for Inline toolsets. When nil, no adaptation is applied.
PayloadAdapter func(ctx context.Context, meta ToolCallMeta, tool tools.Ident, raw json.RawMessage) (json.RawMessage, error)
// ResultMaterializer enriches typed tool results before the runtime encodes
// them for hooks, workflow boundaries, or callers. When nil, the runtime
// publishes the tool result exactly as produced by the executor.
ResultMaterializer ResultMaterializer
// DecodeInExecutor instructs the runtime to pass raw JSON payloads through to
// the executor without pre-decoding. The executor must decode using generated
// codecs. Defaults to false.
DecodeInExecutor bool
// TelemetryBuilder can be provided to build or enrich telemetry consistently
// across transports. When set, the runtime may invoke it with timing/context.
TelemetryBuilder func(ctx context.Context, meta ToolCallMeta, tool tools.Ident, start, end time.Time, extras map[string]any) *telemetry.ToolTelemetry
// AgentTool, when non-nil, carries configuration for agent-as-tool toolsets.
// It is populated by NewAgentToolsetRegistration so the workflow runtime can
// start nested agent runs directly (fan-out/fan-in) without relying on the
// synchronous Execute callback.
AgentTool *AgentToolConfig
// DispatchMode selects the runtime dispatch path. Registration derives
// this from Inline/AgentTool when unset so dispatch code branches on one
// explicit field.
DispatchMode DispatchMode
}
ToolsetRegistration holds the metadata and execution logic for a toolset. Users register toolsets by providing an Execute function that handles all tools in the toolset. Codegen auto-generates registrations for service-based tools and agent-tools; users provide registrations for custom/server-side tools.
The Execute function is the core dispatch mechanism for toolsets that run inside activities or other non-workflow contexts. For inline toolsets, the runtime may invoke Execute directly from the workflow loop.
func NewAgentToolsetRegistration ¶
func NewAgentToolsetRegistration(rt *Runtime, cfg AgentToolConfig) ToolsetRegistration
NewAgentToolsetRegistration creates a toolset registration for an agent-as-tool.
func NewArtifactToolsetRegistration ¶ added in v1.2.2
func NewArtifactToolsetRegistration(cfg ArtifactToolsetConfig) ToolsetRegistration
NewArtifactToolsetRegistration exposes persisted run artifacts as ordinary model tools.
func NewMemoryToolsetRegistration ¶ added in v1.2.2
func NewMemoryToolsetRegistration(cfg MemoryToolsetConfig) ToolsetRegistration
NewMemoryToolsetRegistration exposes memory lookup as ordinary model tools.
func NewSkillToolsetRegistration ¶ added in v1.2.2
func NewSkillToolsetRegistration(cfg SkillToolsetConfig) ToolsetRegistration
NewSkillToolsetRegistration exposes skill directories as ordinary model tools. This is complementary to MCP skill:// resources: planners can advertise these tools directly to a model, while generated MCP servers can continue to expose the same files through resources/list and resources/read.
type VertexConfig ¶ added in v1.2.0
type VertexConfig struct {
ProjectID string
Location string
APIKey string
Credentials *auth.Credentials
HTTPClient *http.Client
HTTPOptions genai.HTTPOptions
DefaultModel string
HighModel string
SmallModel string
MaxTokens int
ThinkingBudget int
Temperature float32
}
VertexConfig configures the Vertex AI Gemini model client created by the runtime.
type WorkerConfig ¶
type WorkerConfig struct {
// Queue overrides the default task queue for this agent's workflow and
// activities. When set, the runtime rebases workflow, planner, and tool
// activities onto this queue. Engine-specific liveness and queue-wait tuning
// belongs in the engine adapter, not the generic runtime surface.
Queue string
}
WorkerConfig configures per-agent queue placement. Engines that support background workers (for example Temporal) use this to select the workflow and activity queue for the agent. Engine-specific concurrency, liveness, and queue-wait tuning belongs in the engine adapter. In-memory engines ignore this configuration.
type WorkerOption ¶
type WorkerOption func(*WorkerConfig)
WorkerOption configures a WorkerConfig.
func WithQueue ¶
func WithQueue(name string) WorkerOption
WithQueue returns a WorkerOption that sets the queue name on a WorkerConfig.
type WorkflowOptions ¶
type WorkflowOptions = api.WorkflowOptions
WorkflowOptions mirrors the subset of engine start options we expose through the runtime. Memo and SearchAttributes remain generic visibility metadata so each engine can map them to its own durable workflow substrate.
Source Files
¶
- activity_heartbeat.go
- activity_input_budget.go
- agent_context.go
- agent_tools.go
- agent_tools_config.go
- agent_tools_output.go
- agent_tools_prompt.go
- agent_tools_request.go
- agent_tools_validation.go
- aggregation_summary.go
- artifact_toolset.go
- await_errors.go
- child_tracker.go
- client.go
- confirmation.go
- confirmation_workflow.go
- history.go
- hook_activity.go
- interceptors.go
- memory_preload.go
- memory_projection.go
- memory_reader.go
- memory_service.go
- memory_toolset.go
- model_interceptors.go
- model_tracing.go
- model_wrapper.go
- one_shot_run.go
- planner_activities.go
- planner_events.go
- prompt_refs.go
- result_preview.go
- retry_reflect.go
- run_completion.go
- run_id.go
- run_options.go
- run_snapshot.go
- run_status.go
- run_timing.go
- runtime.go
- runtime_bootstrap.go
- runtime_catalog.go
- runtime_clone_helpers.go
- runtime_hints_sink.go
- runtime_hook_helpers.go
- runtime_ids.go
- runtime_models.go
- runtime_policy_helpers.go
- runtime_registration.go
- runtime_runs.go
- runtime_subscribers.go
- runtime_text_helpers.go
- session_lifecycle.go
- skill_toolset.go
- tool_activity.go
- tool_calls.go
- tool_calls_collect.go
- tool_calls_dispatch.go
- tool_calls_timeout.go
- tool_codecs.go
- tool_events.go
- tool_result_contract.go
- tool_result_encoding.go
- tool_result_materialization.go
- tool_result_reminders.go
- tool_retry_hints.go
- tool_unavailable.go
- types.go
- workflow.go
- workflow_await.go
- workflow_await_publication.go
- workflow_await_queue.go
- workflow_await_wait.go
- workflow_clarification.go
- workflow_finalize.go
- workflow_finish.go
- workflow_helpers.go
- workflow_interrupts.go
- workflow_loop.go
- workflow_plan_activity.go
- workflow_policy.go
- workflow_state.go
- workflow_transcript.go
- workflow_turn.go