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.
- `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 ¶
- 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 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 BedrockConfig
- type CachePolicy
- type CompressOption
- type HintOverrideFunc
- type HistoryPolicy
- type HookActivityInput
- type MissingFieldsAction
- type OneShotRunInput
- type Options
- type PlanActivityInput
- type PlanActivityOutput
- type PolicyOverrides
- type PromptBuilder
- type PromptRenderHookContext
- type ResultMaterializer
- type RunInput
- 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) 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) (_ *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) 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) 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 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 WithLogger(l telemetry.Logger) RuntimeOption
- func WithMemoryStore(m memory.Store) RuntimeOption
- func WithMetrics(m telemetry.Metrics) 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 Timing
- type ToolActivityExecutor
- type ToolCallExecutor
- type ToolCallExecutorFunc
- type ToolCallMeta
- type ToolConfirmation
- type ToolConfirmationConfig
- type ToolInput
- type ToolOutput
- type ToolsetRegistration
- type WorkerConfig
- type WorkerOption
- type WorkflowOptions
Constants ¶
This section is empty.
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 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
}
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 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 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).
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 HistoryPolicy ¶
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(triggerAt, keepRecent int, client model.Client, opts ...CompressOption) HistoryPolicy
Compress returns a policy that summarizes older conversation history when the turn count exceeds triggerAt. The policy uses the provided model client to generate a summary of older turns, keeping the most recent keepRecent turns intact.
Hysteresis: Compression only triggers when len(turns) >= triggerAt. After compression, history drops to keepRecent + 1 (summary), so it won't trigger again until history regrows to triggerAt.
The policy always preserves:
- All System messages at the start of the conversation
- The most recent keepRecent turns in full fidelity
- Tool use/result integrity in the kept turns
Example: Compress(30, 10, client) triggers at 30 turns, compresses to a summary + 10 recent turns, then won't trigger again until 30 turns accumulate.
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 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 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 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
// 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
// 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
// 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 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
}
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
// 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) 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) (_ *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) 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) 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.
func (*Runtime) ToolSchema ¶
ToolSchema returns the parsed JSON schema for the tool payload when available.
type RuntimeOption ¶
type RuntimeOption func(*Options)
RuntimeOption configures the runtime via functional options passed to NewWith.
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 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 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 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) (*planner.ToolResult, error)
}
ToolCallExecutor executes a tool call and returns a planner.ToolResult. 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) (*planner.ToolResult, error)
ToolCallExecutorFunc adapts a function to the ToolCallExecutor interface.
func (ToolCallExecutorFunc) Execute ¶
func (f ToolCallExecutorFunc) Execute(ctx context.Context, meta *ToolCallMeta, call *planner.ToolRequest) (*planner.ToolResult, 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 ToolOutput ¶
type ToolOutput = api.ToolOutput
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) (*planner.ToolResult, 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
}
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.
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
¶
- activities.go
- activity_heartbeat.go
- activity_input_budget.go
- agent_context.go
- agent_tools.go
- agent_tools_config.go
- agent_tools_output.go
- agent_tools_request.go
- aggregation_summary.go
- await_errors.go
- child_tracker.go
- client.go
- confirmation.go
- confirmation_workflow.go
- history.go
- hook_activity.go
- memory_projection.go
- memory_reader.go
- model_tracing.go
- model_wrapper.go
- one_shot_run.go
- planner_events.go
- prompt_refs.go
- result_preview.go
- run_completion.go
- run_id.go
- run_snapshot.go
- run_status.go
- run_timing.go
- runtime.go
- runtime_catalog.go
- runtime_clone_helpers.go
- runtime_hints_sink.go
- runtime_hook_helpers.go
- runtime_ids.go
- runtime_options.go
- runtime_policy_helpers.go
- runtime_registration.go
- runtime_runs.go
- runtime_text_helpers.go
- session_lifecycle.go
- tool_calls.go
- tool_calls_collect.go
- tool_calls_dispatch.go
- tool_events.go
- tool_result_contract.go
- tool_result_encoding.go
- tool_result_materialization.go
- tool_result_reminders.go
- tool_unavailable.go
- types.go
- workflow.go
- workflow_await.go
- workflow_await_publication.go
- workflow_await_queue.go
- workflow_await_wait.go
- workflow_finish.go
- workflow_helpers.go
- workflow_loop.go
- workflow_policy.go
- workflow_state.go
- workflow_support.go
- workflow_transcript.go
- workflow_turn.go