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 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 workflow-handle completion observation and terminal hook repair so durable runs emit one canonical RunCompleted event while asynchronous starters remain non-blocking.
Package runtime centralizes the active-work deadline contract used by workflow execution.
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 BoundGeneratedRetryHint(hint *planner.RetryHint) *planner.RetryHint
- func ChildDispatchActivityName(id agent.Ident) string
- 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 FinishRunActivityName(id agent.Ident) string
- func IsRunNotAwaitable(err error) bool
- func LoadRunToolEvents(ctx context.Context, store runstore.Store, scope string, ref runstore.Hash) ([]*api.ToolEvent, error)
- func LoadToolResult(ctx context.Context, store runstore.Store, scope string, spec tools.ToolSpec, ...) (any, error)
- 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 RecallActivityName(id agent.Ident) string
- func RecordContentActivityName(id agent.Ident) string
- func RecordToolPayload(ctx context.Context, payload any) error
- func SealRecordActivityName(id agent.Ident) string
- func SummarizeContextActivityName(id agent.Ident) string
- 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 CallRecording
- func (r *CallRecording) Facts() []contextmeasure.RequestFacts
- func (r *CallRecording) Finish(ctx context.Context) error
- func (r *CallRecording) Keys() []runstore.CallKey
- func (r *CallRecording) Overflow() *contextmeasure.ContextOverflow
- func (r *CallRecording) ProducingCall(eventKeys []runstore.CallKey) *runstore.CallKey
- func (r *CallRecording) RequestGrowth() *RequestGrowth
- type CodexConfig
- type ContextCompaction
- type ContextDefault
- type ContextModel
- type ContextOverflowError
- type ContextOverrides
- type ContextRecovery
- type ContextSettingsError
- type DispatchMode
- type EventInterceptor
- type GeminiConfig
- type HintOverrideFunc
- type HookActivityInput
- type Interceptor
- type LimitTerminalCall
- type LimitTerminalPlans
- type LongTermMemoryPreloadPolicy
- type MemoryPreloadPolicy
- type MemoryScope
- type MemoryToolsetConfig
- type MissingFieldsAction
- type ModelInterceptor
- type ModelRecovery
- type OllamaConfig
- type OneShotRunInput
- type OpenAIConfig
- type Options
- type PlanActivityInput
- type PlanActivityInputBudgetError
- type PlanActivityOutput
- type PolicyOverrides
- type PromptBuilder
- type PromptRenderHookContext
- type Qualification
- type Ratio
- type RecallAccess
- type RequestGrowth
- type ResultMaterializer
- type RetryAndReflectConfig
- type RunInput
- type RunInterceptor
- type RunNotAwaitableError
- type RunNotAwaitableReason
- type RunOption
- func WithAllowedTags(tags []string) RunOption
- func WithContextOverrides(overrides ContextOverrides) RunOption
- func WithDeniedTags(tags []string) RunOption
- func WithLabels(labels map[string]string) RunOption
- func WithLimitTerminalPlans(plans LimitTerminalPlans) 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 WithRunCompletionTool(id tools.Ident) RunOption
- func WithRunFinalizerGrace(d time.Duration) RunOption
- func WithRunID(id string) RunOption
- func WithRunInterruptsAllowed(allowed bool) RunOption
- func WithRunMaxModelCalls(n int) RunOption
- func WithRunMaxRecoveryTurns(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) ChildDispatchActivity(ctx context.Context, in *api.ChildDispatchInput) (*api.ChildDispatchOutput, 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) FinishRunActivity(ctx context.Context, input *api.FinishRunInput) (*api.FinishRunOutput, error)
- func (r *Runtime) GetRunSnapshot(ctx context.Context, runID string) (*run.Snapshot, error)
- func (r *Runtime) HasEventInterceptors() bool
- 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) ModelIDs() []string
- 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) NewCodexModelClient(cfg CodexConfig) (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) (out *PlanActivityOutput, activityErr error)
- func (r *Runtime) PlanStartActivity(ctx context.Context, input *PlanActivityInput) (out *PlanActivityOutput, activityErr 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) RecallActivity(ctx context.Context, input *api.RecallActivityInput) (*api.RecallActivityOutput, error)
- func (r *Runtime) RecordContentActivity(ctx context.Context, input *api.RecordContentInput) (*api.RecordContentOutput, error)
- func (r *Runtime) RegisterAgent(ctx context.Context, reg AgentRegistration) error
- func (r *Runtime) RegisterModel(id string, client model.Client) error
- func (r *Runtime) RegisterModelClient(id string, client model.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) SealRecordActivity(ctx context.Context, input *api.SealRecordInput) (*api.SealRecordOutput, error)
- func (r *Runtime) SummarizeContextActivity(ctx context.Context, in *SummarizeContextInput) (out *SummarizeContextOutput, activityErr error)
- func (r *Runtime) ToolDispatchMode(name tools.Ident) (DispatchMode, bool)
- 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 WithContextCompaction(id agent.Ident, settings ContextCompaction) RuntimeOption
- func WithContextLimits(overrides map[string]model.ContextLimits) RuntimeOption
- func WithContextQualification(q Qualification) RuntimeOption
- func WithContextRecovery(id agent.Ident, settings ContextRecovery) 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 WithRecallAuthorizer(authorize func(context.Context, RecallAccess) error) RuntimeOption
- func WithRunEventStore(s runlog.Store) RuntimeOption
- func WithRunStore(s runstore.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 WithViewCacheRuns(n int) RuntimeOption
- func WithWorker(id agent.Ident, cfg WorkerConfig) RuntimeOption
- func WithoutContextDefault(id agent.Ident) RuntimeOption
- type SkillToolsetConfig
- type SubscriberMode
- type SummarizeContextInput
- type SummarizeContextOutput
- type SummaryModel
- type SummaryPrompt
- type SummarySettings
- type Timing
- type ToolActivityExecutor
- type ToolAwaitNotReadyError
- 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 ViewLoader
- 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 ( // PlannerContractErrorType identifies non-retryable planner contract failures. PlannerContractErrorType = "planner_contract" // ToolResultContractErrorType identifies non-retryable tool-result contract failures. ToolResultContractErrorType = "tool_result_contract" )
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 )
const ( // FinalizationReasonLabel records why the runtime is executing a terminal // tool during finalization. The runtime overwrites this reserved label after // caller, planner, and policy labels have been applied. FinalizationReasonLabel = "loom-mcp.finalization_reason" )
Variables ¶
var ( // ErrContextBudget rejects an advisory pre-send guard check. ErrContextBudget = errors.New("model request exceeds the context guard budget") // ErrContextOverflowPending prevents later calls in a marked attempt. ErrContextOverflowPending = errors.New("context overflow recovery is pending") // ErrContextOverflowNoProgress reports a request that recovery cannot shrink. ErrContextOverflowNoProgress = errors.New("context overflow recovery made no progress") // ErrContextBudgetExceeded reports an overflow in the minimal view. ErrContextBudgetExceeded = errors.New("minimal context exceeds the model budget") // ErrContextOverflowBudget reports three provider overflows in one planner step. ErrContextOverflowBudget = errors.New("context overflow recovery budget exhausted") )
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: runtime is sealed") )
var ( // ErrRunNotAwaitable matches all RunNotAwaitableError instances via errors.Is. ErrRunNotAwaitable = errors.New("run is not awaitable") )
Functions ¶
func BoundGeneratedRetryHint ¶ added in v2.1.0
BoundGeneratedRetryHint removes submitted payloads and bounds generated retry guidance before it crosses a durable or provider-facing boundary.
func ChildDispatchActivityName ¶ added in v2.1.0
ChildDispatchActivityName returns the validation activity on the parent's queue.
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 FinishRunActivityName ¶ added in v2.1.0
FinishRunActivityName returns the terminal activity name registered for an agent.
func IsRunNotAwaitable ¶
IsRunNotAwaitable reports whether err classifies as run-not-awaitable.
func LoadRunToolEvents ¶ added in v2.1.0
func LoadRunToolEvents(ctx context.Context, store runstore.Store, scope string, ref runstore.Hash) ([]*api.ToolEvent, error)
LoadRunToolEvents loads the event list addressed by RunOutput.ToolEventsRef and restores eligible Result and server-only ServerData bytes. Scope must be the root run ID, including when loading a child run's events. Missing list or content hashes fail with wrapped store errors. Callers must authorize access to the scope; returned events include server-only data.
func LoadToolResult ¶ added in v2.1.0
func LoadToolResult(ctx context.Context, store runstore.Store, scope string, spec tools.ToolSpec, hash runstore.Hash) (any, error)
LoadToolResult loads the full eligible result from the root run scope and decodes it with the tool's generated result codec. Missing hashes and content fail immediately; this helper never loads server-only content implicitly.
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 RecallActivityName ¶ added in v2.1.0
RecallActivityName identifies the lookup activity registered on an agent's queue.
func RecordContentActivityName ¶ added in v2.1.0
RecordContentActivityName returns the content activity registered on an agent's queue.
func RecordToolPayload ¶ added in v2.1.0
RecordToolPayload records the payload immediately before invoking a tool's implementation, after mapping and injection. Generated dispatchers call it to report the actual server-only input to ExecuteToolActivity. Custom executors that transform their input must also call it with the final value. It encodes a snapshot as JSON inside the activity; outside an activity it is a no-op. Encoding failures must be returned by the executor.
func SealRecordActivityName ¶ added in v2.1.0
SealRecordActivityName returns the terminal sealing activity registered for an agent.
func SummarizeContextActivityName ¶ added in v2.1.0
SummarizeContextActivityName identifies the registered summary activity.
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 ¶
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 ¶
AfterEventInput is passed after hook event publication succeeds or fails.
type AfterModelDecision ¶
AfterModelDecision changes the model response or error.
type AfterModelInput ¶
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 ¶
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 ¶
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 ¶
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 ¶
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
View ViewLoader
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 ¶
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 ¶
BeforeEventDecision changes or drops hook event publication.
type BeforeEventInput ¶
type BeforeEventInput struct {
Event hooks.Event
Payload []byte
Input HookActivityInput
}
BeforeEventInput is passed before hook events are persisted or published.
type BeforeModelDecision ¶
BeforeModelDecision changes the model request or short-circuits with a response.
type BeforeModelInput ¶
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 ¶
type BeforeRunDecision struct {
Input *RunInput
}
BeforeRunDecision changes the run input before execution begins.
type BeforeRunInput ¶
type BeforeRunInput struct {
AgentID agent.Ident
RunID string
Input RunInput
RunContext run.Context
}
BeforeRunInput is passed before workflow run events are published.
type BeforeToolDecision ¶
type BeforeToolDecision struct {
Payload rawjson.Message
Result *ToolExecutionResult
}
BeforeToolDecision changes the tool request or returns a result without invoking the registered executor.
type BeforeToolInput ¶
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 CallRecording ¶ added in v2.1.0
type CallRecording struct {
// contains filtered or unexported fields
}
CallRecording owns call evidence for one activity attempt. Workflow state owns run-level adoption and growth event publication.
func NewCallRecording ¶ added in v2.1.0
func NewCallRecording(store runstore.Store, scope string, ref index.ViewRef, view []*model.Message, step int) *CallRecording
NewCallRecording snapshots the committed pre-policy view for an activity. A snapshot error rejects calls before sending. Step is the monotonic planner schedule number, independent of the conversational TurnID and engine Attempt.
func (*CallRecording) Facts ¶ added in v2.1.0
func (r *CallRecording) Facts() []contextmeasure.RequestFacts
Facts returns durable completions in the same start order as Keys. Finish must succeed before adoption.
func (*CallRecording) Finish ¶ added in v2.1.0
func (r *CallRecording) Finish(ctx context.Context) error
Finish synchronously marks every still-open stream failed as stream_abandoned. Call on every activity exit, including failed and canceled attempts.
func (*CallRecording) Keys ¶ added in v2.1.0
func (r *CallRecording) Keys() []runstore.CallKey
Keys returns every key successfully started by this attempt, in start order.
func (*CallRecording) Overflow ¶ added in v2.1.0
func (r *CallRecording) Overflow() *contextmeasure.ContextOverflow
Overflow returns an owned copy of the attempt's durable rejection.
func (*CallRecording) ProducingCall ¶ added in v2.1.0
func (r *CallRecording) ProducingCall(eventKeys []runstore.CallKey) *runstore.CallKey
ProducingCall returns the last successfully completed call that emitted planner events. All started keys are adopted independently of this content correlation.
func (*CallRecording) RequestGrowth ¶ added in v2.1.0
func (r *CallRecording) RequestGrowth() *RequestGrowth
RequestGrowth returns an owned copy of the first growth warning, or nil.
type CodexConfig ¶ added in v2.1.0
type CodexConfig struct {
// ReasoningEffort selects a provider effort identifier; empty uses the provider default.
ReasoningEffort string
CredentialSource codexfeature.CredentialSource
HTTPClient *http.Client
WebSocketDialer *websocket.Dialer
Transport codexfeature.Transport
ClientVersion string
ResponsesLite bool
StreamIdleTimeout time.Duration
DefaultModel string
HighModel string
SmallModel string
}
CodexConfig configures the ChatGPT-backed Codex subscription model client. Credentials are resolved through the application-owned source for every logical request; the runtime never discovers or persists credentials.
type ContextCompaction ¶ added in v2.1.0
type ContextCompaction = api.ContextCompaction
ContextCompaction configures opt-in context compaction for one agent.
type ContextDefault ¶ added in v2.1.0
type ContextDefault = api.ContextDefault
ContextDefault configures qualified compaction defaults for an agent.
type ContextModel ¶ added in v2.1.0
type ContextModel = api.ContextModel
ContextModel identifies the registered summariser and its accepted evidence.
type ContextOverflowError ¶ added in v2.1.0
type ContextOverflowError struct {
Reason string
Planner agent.Ident
Calls []runstore.CallKey
Facts contextmeasure.RequestFacts
FirstMessage index.MessageID
FixedTokens int
Shortfall *compaction.BudgetShortfallError
Cause error `json:"-"`
}
ContextOverflowError explains a planner step's authoritative provider failure.
func (*ContextOverflowError) Error ¶ added in v2.1.0
func (e *ContextOverflowError) Error() string
Error names the planner and the recorded calls explaining the failure.
func (*ContextOverflowError) Unwrap ¶ added in v2.1.0
func (e *ContextOverflowError) Unwrap() []error
Unwrap preserves the distinct category and recorded provider cause.
type ContextOverrides ¶ added in v2.1.0
type ContextOverrides = compaction.ContextOverrides
ContextOverrides selects per-run context settings; nil members inherit.
type ContextRecovery ¶ added in v2.1.0
type ContextRecovery = api.ContextRecovery
ContextRecovery is the stamped lookup configuration. K14 adds overflow controls.
type ContextSettingsError ¶ added in v2.1.0
type ContextSettingsError = compaction.ContextSettingsError
ContextSettingsError names invalid context configuration at start or adoption.
type DispatchMode ¶
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 ¶
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 ¶
type GeminiConfig struct {
// MaxGenerationRequests caps generation requests including the initial request.
// Zero disables continuation; SDK transport retries remain separate.
MaxGenerationRequests int
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 HookActivityInput ¶
type HookActivityInput = api.HookActivityInput
type Interceptor ¶
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 ¶
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. Failure tracking retains at most retryReflectFailureLimit recent run/tool keys in each process.
type LimitTerminalCall ¶ added in v2.1.0
type LimitTerminalCall = api.LimitTerminalCall
type LimitTerminalPlans ¶ added in v2.1.0
type LimitTerminalPlans = api.LimitTerminalPlans
type LongTermMemoryPreloadPolicy ¶
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 ¶
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 ¶
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 ¶
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 ¶
type ModelInterceptor interface {
BeforeModel(context.Context, *BeforeModelInput) (*BeforeModelDecision, error)
AfterModel(context.Context, *AfterModelInput) (*AfterModelDecision, error)
}
ModelInterceptor observes or changes model invocation behavior.
type ModelRecovery ¶ added in v2.1.0
type ModelRecovery = api.ModelRecovery
type OllamaConfig ¶
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 ¶
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 {
// ContextDefault configures implicit threshold policy by agent.
ContextDefault map[agent.Ident]ContextDefault
// ContextQualifications are application-owned exact model attestations.
ContextQualifications []Qualification
// ContextLimits overrides adapter limits by resolved model, with registered-ID fallback.
// Positive fields win; negative values or max output above the window panic.
ContextLimits map[string]model.ContextLimits
// ContextCompaction enables threshold compaction per agent.
ContextCompaction map[agent.Ident]ContextCompaction
// ContextRecovery configures lookup independently of threshold compaction.
ContextRecovery map[agent.Ident]ContextRecovery
// RecallAuthorizer authorizes every run whose eligible evidence is read.
RecallAuthorizer func(context.Context, RecallAccess) error
// 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
// RunStore holds scoped content and opaque call records.
RunStore runstore.Store
// ViewCacheRuns bounds cached run views. Zero uses the default of 256.
ViewCacheRuns int
// 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
// contains filtered or unexported fields
}
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 PlanActivityInputBudgetError ¶ added in v2.1.0
PlanActivityInputBudgetError reports an oversized planner activity envelope.
func (*PlanActivityInputBudgetError) Error ¶ added in v2.1.0
func (e *PlanActivityInputBudgetError) Error() string
Error describes the serialized envelope size and configured limit.
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
// PlannerStep identifies the planner activity rendering this prompt; nil for tool rendering.
PlannerStep *int
}
PromptRenderHookContext identifies one agent run turn for prompt_rendered hook emission.
type Qualification ¶ added in v2.1.0
type Qualification = compaction.Qualification
Qualification self-certifies one exact provider configuration and model set.
type Ratio ¶ added in v2.1.0
type Ratio = compaction.Ratio
Ratio is an exact fraction with a positive denominator.
type RecallAccess ¶ added in v2.1.0
RecallAccess identifies one authorized run whose evidence a lookup enters.
type RequestGrowth ¶ added in v2.1.0
type RequestGrowth = api.RequestGrowth
RequestGrowth identifies the first started call carrying more encoded message bytes outside the recorded view than inside it.
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.
- Provided-result preflight also invokes the materializer before validation. Client and worker runtimes must register the same materializer.
- For provided results, materializers must be deterministic and free of I/O and side effects. Preflight discards enrichment; activities repeat it before persistence.
type RetryAndReflectConfig ¶
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 ¶
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 WithContextOverrides ¶ added in v2.1.0
func WithContextOverrides(overrides ContextOverrides) RunOption
WithContextOverrides snapshots settings for one run. Children use their own registration.
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 WithLimitTerminalPlans ¶ added in v2.1.0
func WithLimitTerminalPlans(plans LimitTerminalPlans) RunOption
WithLimitTerminalPlans sets the deterministic terminal calls used when this run exhausts its time, tool-call, or recovery limit.
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 WithRunCompletionTool ¶ added in v2.1.0
WithRunCompletionTool requires one budgeted tool to succeed before the run can complete.
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 WithRunMaxModelCalls ¶ added in v2.1.0
WithRunMaxModelCalls caps logical model invocation reservations for this run. The value must be positive; nil policy overrides inherit the worker default.
func WithRunMaxRecoveryTurns ¶ added in v2.1.0
WithRunMaxRecoveryTurns caps replacement planner activities after rejected model or tool output.
func WithRunMaxToolCalls ¶
WithRunMaxToolCalls sets a per-run cap on total tool executions.
func WithRunTimeBudget ¶
WithRunTimeBudget sets the active-work budget for planner and tool work in the run. External-input waits pause this budget.
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 {
// MaxModelCalls caps logical model invocation reservations; zero is unlimited.
MaxModelCalls int
// ContextDefault configures qualified compaction defaults.
ContextDefault *ContextDefault
// MaxToolCalls caps the total number of tool invocations per run (0 = unlimited).
MaxToolCalls int
// MaxRecoveryTurns caps replacement planner activities after rejected
// model or tool output. Zero selects the framework default.
MaxRecoveryTurns int
// TimeBudget is the active-work budget for planner and tool work within the
// run (0 = unlimited). External-input waits pause it. Agent workflow submission
// does not set a fixed engine timeout because every workflow can enter an
// external await queue. Enforce an independent wall-clock limit at the caller
// or workflow boundary when needed.
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
// ContextCompaction declares context policy; conflicts with WithContextCompaction.
ContextCompaction *ContextCompaction
// ContextRecovery declares recovery policy; conflicts with WithContextRecovery.
ContextRecovery *ContextRecovery
// 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
// RunStore holds scoped content and opaque call records.
RunStore runstore.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 ¶
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 ¶
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) ChildDispatchActivity ¶ added in v2.1.0
func (r *Runtime) ChildDispatchActivity(ctx context.Context, in *api.ChildDispatchInput) (*api.ChildDispatchOutput, error)
ChildDispatchActivity runs application validation outside workflow execution. A structured failure becomes a tool result; an infrastructure error fails the activity. No child is admitted or started until the workflow receives success.
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) FinishRunActivity ¶ added in v2.1.0
func (r *Runtime) FinishRunActivity(ctx context.Context, input *api.FinishRunInput) (*api.FinishRunOutput, error)
FinishRunActivity stores the event list in the root scope and resolves the selected final result with its generated codec. RegisterAgent registers this activity automatically on the agent's workflow queue.
func (*Runtime) GetRunSnapshot ¶
GetRunSnapshot derives a compact snapshot of the run state by replaying the canonical run log.
func (*Runtime) HasEventInterceptors ¶ added in v2.1.0
HasEventInterceptors reports whether runtime or registered agent middleware can alter observed events. RuntimeInterceptorFuncs with no BeforeEventFunc are excluded. The check is conservative across every registered agent, including agents that may run as children.
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. Unlike PlannerContext.ModelClient, it does not attach model.CallInfo or allocate a run store sequence for calls.
func (*Runtime) ModelIDs ¶ added in v2.1.0
ModelIDs returns a sorted owned copy of the registered model identifiers.
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 that encodes requests from the planner's messages only.
func (*Runtime) NewCodexModelClient ¶ added in v2.1.0
func (r *Runtime) NewCodexModelClient(cfg CodexConfig) (model.Client, error)
NewCodexModelClient constructs a model.Client backed by a ChatGPT Codex subscription. The client is not registered automatically; pass it to RegisterModel with the model ID your planners use.
func (*Runtime) NewGeminiModelClient ¶
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 ¶
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 ¶
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 ¶
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) (out *PlanActivityOutput, activityErr 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) (out *PlanActivityOutput, activityErr 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 validates external results against a pending await before storing or signalling. Contract failures return a non-retryable application error of type ToolResultContractErrorType and leave the run awaiting.
func (*Runtime) ProvideTypedInput ¶
ProvideTypedInput sends a schema-typed human input answer to a waiting run.
func (*Runtime) PutMemoryEntry ¶
func (r *Runtime) PutMemoryEntry(ctx context.Context, input memory.PutEntryInput) (memory.Entry, error)
PutMemoryEntry writes a direct long-term memory entry.
func (*Runtime) RecallActivity ¶ added in v2.1.0
func (r *Runtime) RecallActivity(ctx context.Context, input *api.RecallActivityInput) (*api.RecallActivityOutput, error)
RecallActivity resolves eligible evidence and stores the rendered result before returning only its address and bounded preview. Session identity comes from the store.
func (*Runtime) RecordContentActivity ¶ added in v2.1.0
func (r *Runtime) RecordContentActivity(ctx context.Context, input *api.RecordContentInput) (*api.RecordContentOutput, error)
RecordContentActivity stores Items in the root scope, returning ordered references only after every Put succeeds. Workflows retain references instead of content.
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. Registration fails with ErrRegistrationClosed after the runtime is sealed or its first run is submitted.
func (*Runtime) RegisterModelClient ¶ added in v2.1.0
RegisterModelClient registers client under id, replacing any existing client with that identifier, and returns the exact stored client, including runtime context-limit decoration and any harness-owned capture gate. Storage and retrieval happen under one registry lock; the returned value is not affected by a later registration replacing the entry.
An empty id or nil client returns an error. After Seal or the first submitted run closes registration, RegisterModelClient returns ErrRegistrationClosed, including for otherwise invalid arguments. Every error returns a nil client and leaves the registry unchanged.
Bootstrap code can retain the returned value to verify its registration after sealing without a separate, racy ModelClient lookup. As with model.Client generally, callers must ensure its concrete value is comparable before using ==; this method does not impose comparability on client implementations.
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/RegisterModel calls fail fast even if activation later fails. Callers may retry Seal after a context-limited activation failure.
func (*Runtime) SealRecordActivity ¶ added in v2.1.0
func (r *Runtime) SealRecordActivity(ctx context.Context, input *api.SealRecordInput) (*api.SealRecordOutput, error)
SealRecordActivity commits the remaining transcript before appending its seal. Fixed input identity and timestamp make retries, including lost acknowledgements, exact duplicates. Canonical append bypasses event interceptors and projections.
func (*Runtime) SummarizeContextActivity ¶ added in v2.1.0
func (r *Runtime) SummarizeContextActivity(ctx context.Context, in *SummarizeContextInput) (out *SummarizeContextOutput, activityErr error)
SummarizeContextActivity folds eligible evidence and stores a validated record before returning its address. It neither changes a view nor adopts call keys.
func (*Runtime) ToolDispatchMode ¶ added in v2.1.0
func (r *Runtime) ToolDispatchMode(name tools.Ident) (DispatchMode, bool)
ToolDispatchMode returns the resolved dispatch mode for a registered tool. Unknown tools or tools without a registered toolset return DispatchUnset, false.
func (*Runtime) ToolSchema ¶
ToolSchema returns the parsed JSON schema for the tool payload when available.
type RuntimeInterceptorFuncs ¶
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 ¶
func (f RuntimeInterceptorFuncs) AfterEvent(ctx context.Context, input *AfterEventInput) (*AfterEventDecision, error)
AfterEvent implements EventInterceptor.
func (RuntimeInterceptorFuncs) AfterModel ¶
func (f RuntimeInterceptorFuncs) AfterModel(ctx context.Context, input *AfterModelInput) (*AfterModelDecision, error)
AfterModel implements ModelInterceptor.
func (RuntimeInterceptorFuncs) AfterRun ¶
func (f RuntimeInterceptorFuncs) AfterRun(ctx context.Context, input *AfterRunInput) (*AfterRunDecision, error)
AfterRun implements RunInterceptor.
func (RuntimeInterceptorFuncs) AfterTool ¶
func (f RuntimeInterceptorFuncs) AfterTool(ctx context.Context, input *AfterToolInput) (*AfterToolDecision, error)
AfterTool implements ToolInterceptor.
func (RuntimeInterceptorFuncs) BeforeEvent ¶
func (f RuntimeInterceptorFuncs) BeforeEvent(ctx context.Context, input *BeforeEventInput) (*BeforeEventDecision, error)
BeforeEvent implements EventInterceptor.
func (RuntimeInterceptorFuncs) BeforeModel ¶
func (f RuntimeInterceptorFuncs) BeforeModel(ctx context.Context, input *BeforeModelInput) (*BeforeModelDecision, error)
BeforeModel implements ModelInterceptor.
func (RuntimeInterceptorFuncs) BeforeRun ¶
func (f RuntimeInterceptorFuncs) BeforeRun(ctx context.Context, input *BeforeRunInput) (*BeforeRunDecision, error)
BeforeRun implements RunInterceptor.
func (RuntimeInterceptorFuncs) BeforeTool ¶
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 ¶
func WithArtifactStore(s artifact.Store) RuntimeOption
WithArtifactStore sets the artifact store.
func WithCaptureGenAIMessages ¶
func WithCaptureGenAIMessages(enabled bool) RuntimeOption
WithCaptureGenAIMessages opts model spans into sensitive GenAI message attributes.
func WithContextCompaction ¶ added in v2.1.0
func WithContextCompaction(id agent.Ident, settings ContextCompaction) RuntimeOption
WithContextCompaction enables explicit threshold compaction.
func WithContextLimits ¶ added in v2.1.0
func WithContextLimits(overrides map[string]model.ContextLimits) RuntimeOption
WithContextLimits sets per-model limits overrides. Positive fields replace adapter values; zero fields retain them. Invalid values panic at construction.
func WithContextQualification ¶ added in v2.1.0
func WithContextQualification(q Qualification) RuntimeOption
WithContextQualification self-certifies an exact provider/model configuration. It retains default policy provenance and attachment residency protection.
func WithContextRecovery ¶ added in v2.1.0
func WithContextRecovery(id agent.Ident, settings ContextRecovery) RuntimeOption
WithContextRecovery configures context lookup for an agent independently of compaction.
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 ¶
func WithInterceptors(interceptors ...Interceptor) RuntimeOption
WithInterceptors registers call-path interceptors in execution order.
func WithMemoryScopeResolver ¶
func WithMemoryScopeResolver(r memory.ScopeResolver) RuntimeOption
WithMemoryScopeResolver sets the long-term memory scope resolver.
func WithMemorySearcher ¶
func WithMemorySearcher(s memory.Searcher) RuntimeOption
WithMemorySearcher sets the indexed or cross-run memory searcher.
func WithMemoryService ¶
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 ¶
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 WithRecallAuthorizer ¶ added in v2.1.0
func WithRecallAuthorizer(authorize func(context.Context, RecallAccess) error) RuntimeOption
WithRecallAuthorizer authorizes each run entered by a lookup, including its current run. Its errors become recall_unauthorized without exposing the application's reason.
func WithRunEventStore ¶
func WithRunEventStore(s runlog.Store) RuntimeOption
WithRunEventStore sets the canonical run event store.
func WithRunStore ¶ added in v2.1.0
func WithRunStore(s runstore.Store) RuntimeOption
WithRunStore sets the scoped content and call record 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 WithViewCacheRuns ¶ added in v2.1.0
func WithViewCacheRuns(n int) RuntimeOption
WithViewCacheRuns sets the maximum number of worker-local cached run views. The default is 256. Evicted views rebuild from the run store on their next load. It panics if n is not greater than zero.
func WithWorker ¶
func WithWorker(id agent.Ident, cfg WorkerConfig) RuntimeOption
WithWorker configures the worker for a specific agent.
func WithoutContextDefault ¶ added in v2.1.0
func WithoutContextDefault(id agent.Ident) RuntimeOption
WithoutContextDefault disables implicit threshold compaction for an agent. An explicit WithContextCompaction remains authoritative.
type SkillToolsetConfig ¶
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 ¶
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 SummarizeContextInput ¶ added in v2.1.0
type SummarizeContextInput = api.SummarizeContextInput
SummarizeContextInput binds one summary to its immutable cut.
type SummarizeContextOutput ¶ added in v2.1.0
type SummarizeContextOutput = api.SummarizeContextOutput
SummarizeContextOutput contains durable summary addresses and attempt evidence.
type SummaryModel ¶ added in v2.1.0
type SummaryModel = api.ContextModel
SummaryModel is the activity's summary model configuration.
type SummaryPrompt ¶ added in v2.1.0
type SummaryPrompt = compaction.SummaryPrompt
SummaryPrompt identifies the stored summary template pinned for this run.
type SummarySettings ¶ added in v2.1.0
type SummarySettings = api.SummarySettings
SummarySettings configures summary instructions and the registered baseline.
type Timing ¶
type Timing struct {
// Budget caps active planner/tool work; human and external waits pause it.
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 ToolAwaitNotReadyError ¶ added in v2.1.0
type ToolAwaitNotReadyError struct {
ID string
}
ToolAwaitNotReadyError identifies a submission whose await is not the current tool-channel head. The ID can also be unknown, already accepted, or consumed. Callers must wait until QueryToolAwaits advertises this ID before resubmitting.
func (*ToolAwaitNotReadyError) Error ¶ added in v2.1.0
func (e *ToolAwaitNotReadyError) Error() string
Error describes the unavailable tool await.
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 ¶
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 ¶
func Executed(result *planner.ToolResult) *ToolExecutionResult
Executed wraps a durable tool result with no current-batch pause.
type ToolInterceptor ¶
type ToolInterceptor interface {
BeforeTool(context.Context, *BeforeToolInput) (*BeforeToolDecision, error)
AfterTool(context.Context, *AfterToolInput) (*AfterToolDecision, error)
}
ToolInterceptor observes or changes tool execution behavior.
type ToolInterceptorFuncs ¶
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 ¶
func (f ToolInterceptorFuncs) AfterTool(ctx context.Context, input *AfterToolInput) (*AfterToolDecision, error)
AfterTool implements Interceptor.
func (ToolInterceptorFuncs) BeforeTool ¶
func (f ToolInterceptorFuncs) BeforeTool(ctx context.Context, input *BeforeToolInput) (*BeforeToolDecision, error)
BeforeTool implements Interceptor.
type ToolOutput ¶
type ToolOutput = api.ToolOutput
type ToolPauseClarification ¶
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 jsontext.Value) (jsontext.Value, 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 ¶
func NewArtifactToolsetRegistration(cfg ArtifactToolsetConfig) ToolsetRegistration
NewArtifactToolsetRegistration exposes persisted run artifacts as ordinary model tools.
func NewMemoryToolsetRegistration ¶
func NewMemoryToolsetRegistration(cfg MemoryToolsetConfig) ToolsetRegistration
NewMemoryToolsetRegistration exposes memory lookup as ordinary model tools.
func NewSkillToolsetRegistration ¶
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 ¶
type VertexConfig struct {
// MaxGenerationRequests caps generation requests including the initial request.
// Zero disables continuation; SDK transport retries remain separate.
MaxGenerationRequests int
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 ViewLoader ¶ added in v2.1.0
ViewLoader loads an owned snapshot of the parent's canonical messages inside pre-child validation. A load error fails child dispatch even if ignored by the validator. It is scoped to the parent's root run and supplied view. Loading performs store I/O; validators must use the activity context.
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
- call_recording.go
- call_recording_stream.go
- child_dispatch.go
- child_tracker.go
- clarification_content.go
- client.go
- confirmation.go
- confirmation_workflow.go
- context_compaction.go
- context_default.go
- context_limits.go
- context_overflow_errors.go
- context_overrides.go
- context_registration.go
- context_telemetry.go
- continuation_chain.go
- continuation_earlier.go
- continuation_events.go
- continuation_seal.go
- continuation_seed.go
- contract_errors.go
- event_interceptors.go
- finalization_content.go
- finish_activity.go
- hook_activity.go
- hook_batch.go
- index_segments.go
- interceptors.go
- memory_preload.go
- memory_projection.go
- memory_reader.go
- memory_service.go
- memory_toolset.go
- model_call_budget.go
- model_call_info.go
- model_call_policy.go
- model_interceptors.go
- model_presentation.go
- model_recovery.go
- model_registration_hook.go
- model_tracing.go
- model_wrapper.go
- one_shot_run.go
- planner_activities.go
- planner_content.go
- planner_events.go
- prompt_refs.go
- provided_content.go
- provided_tool_results.go
- recall_activity.go
- recall_dispatch.go
- recall_model.go
- recall_options.go
- recall_workflow.go
- record_content.go
- recovery_turns.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
- run_tool_events.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_observability.go
- runtime_policy_helpers.go
- runtime_registration.go
- runtime_runs.go
- runtime_subscribers.go
- runtime_text_helpers.go
- seal_record.go
- session_lifecycle.go
- signal_content.go
- skill_toolset.go
- start_admission.go
- summarize_activity.go
- summary_checkpoint.go
- summary_fold.go
- summary_model.go
- summary_prompt.go
- summary_record.go
- terminal_policy.go
- tool_activity.go
- tool_calls.go
- tool_calls_collect.go
- tool_calls_dispatch.go
- tool_calls_timeout.go
- tool_codecs.go
- tool_content.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
- view_checkpoint.go
- view_content.go
- view_loader.go
- view_render.go
- workflow.go
- workflow_await.go
- workflow_await_publication.go
- workflow_await_queue.go
- workflow_await_wait.go
- workflow_clarification.go
- workflow_compaction.go
- workflow_content_batch.go
- workflow_entry_sizes.go
- workflow_finalize.go
- workflow_finish.go
- workflow_helpers.go
- workflow_index.go
- workflow_index_results.go
- workflow_interrupts.go
- workflow_loop.go
- workflow_nontext.go
- workflow_overflow.go
- workflow_pending_results.go
- workflow_plan_activity.go
- workflow_policy.go
- workflow_start_hook.go
- workflow_state.go
- workflow_summary.go
- workflow_transcript.go
- workflow_turn.go