api

package
v2.1.1 Latest Latest
Warning

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

Go to latest
Published: Nov 24, 2026 License: MIT Imports: 23 Imported by: ? modules, 0 packages

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

Documentation

Overview

Package api defines shared types that cross workflow/activity boundaries in the agent runtime.

Index

Constants

View Source
const (
	// SignalPause is the workflow signal name used to pause a run.
	SignalPause = "loom_mcp.runtime.pause"

	// SignalResume is the workflow signal name used to resume a paused run.
	SignalResume = "loom_mcp.runtime.resume"

	// SignalProvideClarification delivers a ClarificationAnswer to a waiting run.
	SignalProvideClarification = "loom_mcp.runtime.provide.clarification"

	// SignalProvideToolResults delivers external tool results to a waiting run.
	SignalProvideToolResults = "loom_mcp.runtime.provide.toolresults"

	// SignalProvideConfirmation delivers a ConfirmationDecision to a waiting run.
	SignalProvideConfirmation = "loom_mcp.runtime.provide.confirmation"

	// SignalProvideTypedInput delivers a TypedInputAnswer to a waiting run.
	SignalProvideTypedInput = "loom_mcp.runtime.provide.typed_input"
)
View Source
const QueryRootRunID = "root_run_id"

QueryRootRunID is the workflow query used by content-producing signal clients.

View Source
const WorkflowProtocolVersion = 21

WorkflowProtocolVersion is the version of the agent workflow's inputs, outputs, signals and state. Every change to workflow code must bump it. Running workflows must be drained before deploying a new version.

Variables

View Source
var ErrWorkflowProtocolMismatch = errors.New("workflow protocol mismatch")

ErrWorkflowProtocolMismatch matches WorkflowProtocolMismatchError via errors.Is.

Functions

This section is empty.

Types

type ChildDispatchInput added in v2.1.0

type ChildDispatchInput struct {
	Call      planner.ToolRequest
	ParentRun run.Context
	View      index.ViewRef
}

ChildDispatchInput carries the call and the parent's view, never its messages.

type ChildDispatchOutput added in v2.1.0

type ChildDispatchOutput struct {
	// IndexHead commits the supplied Pending entries when the validator loaded them.
	// It is empty if no view was loaded or the supplied Pending was empty.
	IndexHead runstore.Hash
	Error     string
	RetryHint *planner.RetryHint
}

ChildDispatchOutput records validation before a child workflow can start.

type ClarificationAnswer

type ClarificationAnswer struct {
	// RunID identifies the run associated with the clarification.
	RunID string

	// ID is the clarification await identifier.
	ID string

	// Answer is the free-form clarification text provided by the actor.
	Answer string

	// AnswerRef addresses the answer text in the root scope.
	AnswerRef runstore.Hash

	// AnswerBytes is overwritten by the runtime client from Answer. A nil
	// measurement is invalid; a pointer to zero measures an empty answer.
	AnswerBytes *int

	// Labels carries optional metadata associated with the clarification answer.
	Labels map[string]string
}

ClarificationAnswer carries a typed answer for a paused clarification request.

type ClarificationContent added in v2.1.0

type ClarificationContent struct {
	TranscriptRef runstore.Hash
	Question      string
}

ClarificationContent preserves streamed text before an awaited question.

type ConfirmationDecision

type ConfirmationDecision struct {
	// RunID identifies the run associated with the confirmation.
	RunID string

	// ID is the confirmation await identifier.
	ID string

	// Approved is true when the operator approved the pending action.
	Approved bool

	// RequestedBy identifies the logical actor that provided the decision.
	RequestedBy string

	// Labels carries optional metadata associated with the decision.
	Labels map[string]string

	// Metadata carries arbitrary structured data for audit trails (for example, ticket IDs or justification codes).
	Metadata map[string]any
}

ConfirmationDecision carries a typed decision for a confirmation await.

type ContextCompaction added in v2.1.0

type ContextCompaction struct {
	// KeepNonTextResident protects original attachments during threshold compaction.
	KeepNonTextResident bool `json:"nontext_resident,omitzero"`
	// ContextModel enables summaries when explicitly configured.
	ContextModel            *ContextModel
	TriggerAt               contextmeasure.Rate
	KeepRecentTokens        int
	ProtectRecentToolTokens int
	MinSavingTokens         int
	RecallDiscoveryCalls    int
	RecallReadCalls         int
	KeepResultTools         []tools.Ident
	Summary                 SummarySettings
}

ContextCompaction configures opt-in threshold compaction. Zero token settings use budget-derived defaults.

type ContextDefault added in v2.1.0

type ContextDefault struct {
	Disabled     bool
	ContextModel *ContextModel
}

ContextDefault configures qualified defaults without explicit thresholds.

type ContextModel added in v2.1.0

type ContextModel = compaction.ContextModel

ContextModel names the summary client and evidence capabilities.

type ContextOverrides added in v2.1.0

type ContextOverrides = compaction.ContextOverrides

ContextOverrides replaces context settings on one run without child inheritance.

type ContextRecovery added in v2.1.0

type ContextRecovery = run.ContextRecovery

ContextRecovery configures context lookup independently of threshold compaction. K14 extends this settings contract with overflow recovery controls.

type ContextStartInput added in v2.1.0

type ContextStartInput struct {
	AgentID   agent.Ident
	SessionID string
	Labels    map[string]string
	Settings  compaction.Settings
}

ContextStartInput resolves a child prompt using its own registered settings.

type ContextStartOutput added in v2.1.0

type ContextStartOutput struct {
	Settings    compaction.Settings
	Fingerprint string
}

ContextStartOutput contains the immutable settings and their stored identity.

type ContinuationStartInput added in v2.1.0

type ContinuationStartInput struct {
	ContextFingerprint string
	SessionID          string
	RunID              string
	AgentID            agent.Ident
	Settings           compaction.Settings
	Timestamp          time.Time
}

ContinuationStartInput enables continuation only for a compaction root.

type ContinuationStartOutput added in v2.1.0

type ContinuationStartOutput struct {
	Prev          *string
	Pos           int
	ContinuedFrom *index.RunCheckpoint
	Outcome       string
	Reason        string
	View          index.ViewRef
	Limits        model.ContextLimits
	Visible       []runstore.Hash
}

ContinuationStartOutput records the selected predecessor and initial view.

type FinalizationContent added in v2.1.0

type FinalizationContent struct {
	Input PlanActivityInput
	Calls []planner.ToolRequest
}

FinalizationContent carries one terminal batch and its bounded policy context.

type FinishRunInput added in v2.1.0

type FinishRunInput struct {
	// Final is the final assistant message, stored before the run completes.
	Final *model.Message
	// RootRunID is the shared storage scope for this run tree.
	RootRunID string
	// ToolEvents is the ordered list with referenced bytes omitted.
	ToolEvents []*ToolEvent
	// FinalToolResult is the selected completion or planner-owned result.
	FinalToolResult *ToolEvent
}

FinishRunInput is the terminal activity envelope. Referenced Result and ServerData bytes are omitted; unreferenced content stays inline.

type FinishRunOutput added in v2.1.0

type FinishRunOutput struct {
	// FinalRef addresses Final in the root run scope, when present.
	FinalRef runstore.Hash
	// ToolEventsRef addresses the stored omitted-bytes event list.
	ToolEventsRef runstore.Hash
	// ToolEventCount counts entries in the stored list.
	ToolEventCount int
	// ToolSummary preserves parent aggregation without loading the list.
	ToolSummary ToolEventSummary
	// FinalToolResult is the selected completion or planner-owned result.
	FinalToolResult *ToolEvent
}

FinishRunOutput contains the stored event-list address and bounded final output.

type HookActivityInput

type HookActivityInput = hooks.ActivityInput

HookActivityInput is the canonical workflow-to-activity envelope for hook events.

type LimitTerminalCall added in v2.1.0

type LimitTerminalCall struct {
	Name    tools.Ident
	Payload rawjson.Message
}

LimitTerminalCall names one terminal bookkeeping tool and its canonical generated payload.

type LimitTerminalPlans added in v2.1.0

type LimitTerminalPlans struct {
	TimeBudget  LimitTerminalCall
	ToolCallCap LimitTerminalCall
	RecoveryCap LimitTerminalCall
}

LimitTerminalPlans contains the complete set of calls used when a workflow exhausts one of its configured limits.

type ModelCallPolicyInput added in v2.1.0

type ModelCallPolicyInput struct {
	AgentID       agent.Ident
	MaxModelCalls *int `json:"max_model_calls,omitzero"`
}

ModelCallPolicyInput snapshots a worker default and an optional per-run override.

type ModelContext added in v2.1.0

type ModelContext struct {
	Model      string              `json:"m"`
	Rate       contextmeasure.Rate `json:"r"`
	Calibrated bool                `json:"c,omitzero"`
	Budget     int                 `json:"b"`
}

ModelContext carries the last adopted calibration for one model.

type ModelRecovery added in v2.1.0

type ModelRecovery struct {
	Kind        model.OutputValidationKind
	Fingerprint [32]byte
	ByteCount   int
	Usage       model.TokenUsage
	Attempt     int
	Correction  string
	// CorrectionRef addresses Correction text stored in the root run scope.
	CorrectionRef runstore.Hash
	DisableTools  bool
	// ToolCatalog is the exact model-visible catalog from the rejected
	// request. Replacement output must stay within this snapshot.
	ToolCatalog []tools.Ident
}

ModelRecovery is the workflow-safe record for one rejected model output. Fingerprint and byte count identify the rejected response without retaining its body; Correction is framework-authored and bounded.

func (ModelRecovery) MarshalJSON added in v2.1.0

func (r ModelRecovery) MarshalJSON() ([]byte, error)

MarshalJSON encodes ModelRecovery with a stable hexadecimal fingerprint. Go's JSON v2 codec does not round-trip a byte array through its default representation, so the workflow boundary owns this explicit wire contract.

func (*ModelRecovery) UnmarshalJSON added in v2.1.0

func (r *ModelRecovery) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes the stable ModelRecovery workflow representation.

type PauseRequest

type PauseRequest struct {
	// RunID identifies the run to pause.
	RunID string

	// Reason describes why the run is being paused (for example, "user_requested").
	Reason string

	// RequestedBy identifies the logical actor requesting the pause (for example, a user ID, service name,
	// or "policy_engine").
	RequestedBy string

	// Labels carries optional key-value metadata associated with the pause request.
	Labels map[string]string

	// Metadata carries arbitrary structured data attached to the pause request.
	Metadata map[string]any
}

PauseRequest carries metadata attached to a pause signal.

type PlanActivityInput

type PlanActivityInput struct {
	// MaxModelCalls is the immutable worker-resolved run admission cap.
	MaxModelCalls int `json:"max_model_calls,omitzero"`
	// ChainPos and ContinuedFrom carry recorded continuation identity.
	ChainPos      int                  `json:"chain_pos,omitzero"`
	ContinuedFrom *index.RunCheckpoint `json:"continued_from,omitzero"`

	// Overflow carries the current planner step after an overflow recovery.
	Overflow        *overflow.Step             `json:"overflow,omitzero"`
	ContextSettings compaction.ContextSettings `json:"context_settings,omitzero"`
	// Models is the sorted snapshot of adopted model rates and budgets.
	Models []ModelContext `json:"models,omitzero"`
	// ExtraTools contains workflow-owned specs added to the model catalog this turn.
	ExtraTools []*model.ToolDefinition `json:"extra_tools,omitzero"`
	// AgentID identifies which agent is being planned.
	AgentID agent.Ident

	// Step is the one-based planner activity schedule number within the run.
	Step int `json:"step,omitzero"`

	// RunID identifies the run being planned.
	RunID string

	// CallFilter preserves per-run filtering before canonical IDs are assigned.
	CallFilter PlanToolFilter

	// View addresses the committed transcript plus one step's pending entries.
	View index.ViewRef
	// RunContext carries nested-run metadata.
	RunContext run.Context

	// Finalize requests a final turn with no further tool calls.
	Finalize *planner.Termination

	// ToolsDisabled records an explicit policy decision disabling tools this turn.
	ToolsDisabled bool `json:"tools_disabled,omitzero"`

	// ToolPolicyActive indicates that AllowedTools is the canonical per-turn
	// model-visible and execution-visible tool allowlist.
	ToolPolicyActive bool

	// AllowedTools lists the tool identifiers available to the planner for this
	// turn after run overrides, runtime policy, and caps are applied.
	AllowedTools []tools.Ident

	// PolicyCaps carries the cap state used to derive AllowedTools.
	PolicyCaps policy.CapsState
	// FinalizeMaxToolCalls preserves the per-turn cap while preparing terminal calls.
	FinalizeMaxToolCalls int `json:"finalize_max_tool_calls,omitzero"`

	// Recovery carries bounded correction guidance from the rejected activity
	// this planner invocation replaces. It never contains rejected model output.
	Recovery *ModelRecovery
}

PlanActivityInput carries the planner input for PlanStart and PlanResume activities.

type PlanActivityOutput

type PlanActivityOutput struct {
	// ModelCallLimit records an unsent reservation refused by the run cap.
	ModelCallLimit *policy.ModelCallLimit `json:"model_call_limit,omitzero"`
	// ContextOverflow replaces a result when any call marks the attempt.
	ContextOverflow *contextmeasure.ContextOverflow `json:"context_overflow,omitzero"`
	// Facts parallels CallKeys and comes from durable Completion.Facts.
	Facts []contextmeasure.RequestFacts `json:"facts,omitzero"`
	// Result is the planner output describing next tool calls, await requests, or final response.
	Result *planner.PlanResult

	// IndexHead is returned only after the input pending entries have been stored.
	IndexHead runstore.Hash

	// View is adopted only for successful planner results, never recovery outputs.
	View *ViewUpdate
	// CallView names the loader-built view used by calls, including rejected outputs.
	// It records evidence without adopting a recovery ViewUpdate.
	CallView *index.ViewRef `json:"call_view,omitzero"`

	// TranscriptRef addresses the encoded non-empty Transcript in the root scope.
	TranscriptRef runstore.Hash

	// TranscriptSize is measured by the planner activity before content is stored.
	TranscriptSize contextmeasure.MessageSize

	// ToolCallRefs addresses each returned Result.ToolCalls entry, in order.
	ToolCallRefs []runstore.Hash

	// AwaitCallRefs contains canonical question/external call refs by ToolCallID.
	AwaitCallRefs map[string]runstore.Hash

	// CallKeys contains every model call started by this activity attempt.
	CallKeys []runstore.CallKey

	// ProducingCall is the last completed call that emitted planner events.
	ProducingCall *runstore.CallKey

	// RequestGrowth carries this attempt's first request dominated by outside-view bytes.
	RequestGrowth *RequestGrowth

	// Usage is the token usage reported by the model provider when available.
	Usage model.TokenUsage

	// ToolPolicyActive echoes the planner input policy envelope.
	ToolPolicyActive bool

	// AllowedTools echoes the canonical allowlist used for this planner turn.
	AllowedTools []tools.Ident

	// PolicyCaps echoes the cap state used to derive AllowedTools.
	PolicyCaps policy.CapsState

	// Recovery is set instead of Result when this activity rejected model
	// output that may be replaced within the workflow recovery budget.
	Recovery *ModelRecovery

	// Attempt is the planner activity attempt that produced this output.
	Attempt int
}

PlanActivityOutput wraps the planner result produced by a plan/resume activity.

type PlanToolFilter added in v2.1.0

type PlanToolFilter struct {
	RestrictToTool tools.Ident
	AllowedTags    []string
	DeniedTags     []string
}

PlanToolFilter carries the per-run filters applied before call canonicalization. It contains no execution history or content payloads.

type PolicyOverrides

type PolicyOverrides struct {
	// MaxModelCalls overrides logical model invocation reservations; nil inherits.
	MaxModelCalls *int `json:"max_model_calls,omitzero"`
	// Context overrides registered context settings for this run only.
	Context *ContextOverrides `json:"context,omitzero"`
	// PerTurnMaxToolCalls limits the number of tool calls the planner may issue per turn.
	PerTurnMaxToolCalls int

	// RestrictToTool restricts tool execution to the given tool identifier.
	RestrictToTool tools.Ident
	// CompletionTool identifies the budgeted tool whose first successful
	// execution completes the run without another planner turn.
	CompletionTool tools.Ident

	// AllowedTags restricts tool execution to tools tagged with at least one of the listed tags.
	AllowedTags []string

	// DeniedTags excludes tools tagged with any of the listed tags from execution.
	DeniedTags []string

	// MaxToolCalls caps the total number of tool calls a run may execute.
	MaxToolCalls int

	// MaxRecoveryTurns caps replacement planner activities after rejected
	// model or tool output before finalizing.
	MaxRecoveryTurns int

	// TimeBudget caps active planner/tool work; human and external waits pause it.
	TimeBudget time.Duration

	// PlanTimeout overrides the per-turn plan/resume activity timeout.
	PlanTimeout time.Duration

	// ToolTimeout overrides the default per-tool execution timeout.
	ToolTimeout time.Duration

	// PerToolTimeout overrides tool execution timeouts for specific tools.
	PerToolTimeout map[tools.Ident]time.Duration

	// FinalizerGrace caps the time spent in the finalizer phase after termination is requested.
	FinalizerGrace time.Duration

	// LimitTerminalPlans supplies deterministic terminal calls for time,
	// tool-call, and recovery limits.
	LimitTerminalPlans *LimitTerminalPlans

	// InterruptsAllowed enables interrupt/pause behavior for the run when supported by the engine.
	InterruptsAllowed bool
}

PolicyOverrides configures per-run policy constraints. All fields are optional Scalar zero values and nil pointers mean no override.

func (PolicyOverrides) MarshalJSON added in v2.1.0

func (o PolicyOverrides) MarshalJSON() ([]byte, error)

MarshalJSON writes durations as integer nanoseconds for Temporal's workflow payload contract.

func (*PolicyOverrides) UnmarshalJSON added in v2.1.0

func (o *PolicyOverrides) UnmarshalJSON(data []byte) error

UnmarshalJSON restores per-run recovery overrides written before MaxRecoveryTurns replaced MaxConsecutiveFailedToolCalls in workflow history.

type ProvidedContent added in v2.1.0

type ProvidedContent struct {
	// TimestampMS is workflow time at consumption, stable across activity retries.
	TimestampMS int64
	RunContext  run.Context
	AgentID     agent.Ident
	Calls       []planner.ToolRequest
	Results     []*ProvidedToolResult
	First       index.MessageID
	CallRefs    map[string]runstore.Hash
}

ProvidedContent carries only awaited call metadata and signal references.

type ProvidedToolResult

type ProvidedToolResult struct {
	// Refs addresses provided result content stored in the root scope before signalling.
	Refs tools.ResultRefs

	// Name is the canonical <toolset>.<tool> identifier that produced this result.
	Name tools.Ident

	// ToolCallID correlates the result with the original awaited tool call.
	ToolCallID string

	// Result contains the external actor's canonical JSON payload for the tool
	// result. Nil or `null` is allowed when the tool's result contract permits it.
	Result rawjson.Message

	// Bounds carries runtime-owned bounded-result metadata when the tool
	// contract requires it.
	Bounds *agent.Bounds

	// Error is the structured tool failure, when the external tool execution failed.
	Error *planner.ToolError

	// RetryHint optionally provides structured guidance for recovering from a
	// provided tool failure.
	RetryHint *planner.RetryHint

	// Artifacts contains externally supplied artifact references. Bodies are never
	// accepted across this workflow boundary.
	Artifacts []artifact.Ref `json:"artifacts,omitempty"`
}

ProvidedToolResult carries one externally supplied tool result across the await-resume workflow boundary.

Contract:

  • This is a raw input envelope from an external actor (for example, a UI or bridge service), not the runtime's canonical `ToolEvent` representation.
  • Result bytes must use the tool's generated result codec and remain canonical JSON, but server-only sidecars are never provided here; the runtime materializes them after decoding.

type PublishToolContent added in v2.1.0

type PublishToolContent struct {
	AgentID    agent.Ident
	RunContext run.Context
	Call       planner.ToolRequest
	Result     *ToolEvent
	Duration   int64
}

PublishToolContent supplies references and metadata for a tool result hook.

type Ratio added in v2.1.0

type Ratio = compaction.Ratio

Ratio represents an exact fraction with a positive denominator.

type RecallActivityInput added in v2.1.0

type RecallActivityInput struct {
	Parts      model.ToolResultPartSupport
	PartTokens int
	RunID      string
	Scope      string
	ViewRef    index.ViewRef
	Head       runstore.Hash
	Call       planner.ToolRequest
	PageBytes  int
	ScanBytes  int
}

RecallActivityInput carries trusted workflow evidence and untrusted tool arguments.

type RecallActivityOutput added in v2.1.0

type RecallActivityOutput struct {
	Parts   runstore.Hash `json:"parts,omitzero"`
	NonText int           `json:"non_text,omitzero"`
	Result  *ToolOutput
	Code    recall.Code
	Bytes   int
}

RecallActivityOutput addresses the stored eligible result and its event classification.

type RecordContentInput added in v2.1.0

type RecordContentInput struct {
	// ModelCallPolicy resolves the owning worker default alongside initial content.
	ModelCallPolicy *ModelCallPolicyInput `json:"model_call_policy,omitzero"`
	// Compatibility requests an exact check of original attachments.
	Compatibility *contextcompat.Request `json:"compatibility,omitzero"`
	// Continue requests recorded session seeding for a compaction root.
	Continue *ContinuationStartInput `json:"continue,omitzero"`
	// ContextStart pins child context settings outside workflow execution.
	ContextStart *ContextStartInput `json:"context_start,omitzero"`
	// RootRunID is the shared storage scope of the run tree.
	RootRunID string
	// Items contains the exact bytes to store, in order.
	Items [][]byte
	// SeedMessages stores Items as caller messages and commits their first index segments.
	SeedMessages bool
	// Typed validates a referenced answer without returning its content.
	Typed *TypedContentValidation
	// Clarification joins an await-only transcript and its question in one assistant turn.
	Clarification *ClarificationContent
	// Provided materializes external results without exposing signal content to workflows.
	Provided *ProvidedContent
	// FinalizeCalls canonicalizes and stores a fixed terminal plan before dispatch.
	FinalizeCalls *FinalizationContent
}

RecordContentInput carries ordered content to store before workflow adoption.

type RecordContentOutput added in v2.1.0

type RecordContentOutput struct {
	// MaxModelCalls is present when the initial run policy was resolved.
	MaxModelCalls *int `json:"max_model_calls,omitzero"`
	// Compatibility addresses the verified original attachment fact.
	Compatibility *contextcompat.Result `json:"compatibility,omitzero"`
	// Continuation records start lineage and the selected view.
	Continuation *ContinuationStartOutput `json:"continuation,omitzero"`
	// ContextStart is the recorded result of child prompt and settings pinning.
	ContextStart *ContextStartOutput `json:"context_start,omitzero"`
	// Refs addresses Items in the same order and with the same length.
	Refs        []runstore.Hash
	IndexHead   runstore.Hash
	Entries     []index.MessageEntry
	ToolResults []*ToolEvent
	Calls       []planner.ToolRequest
	CallRefs    []runstore.Hash
}

RecordContentOutput is returned only after every input item has been stored.

type RequestGrowth added in v2.1.0

type RequestGrowth struct {
	// Key identifies the started model call.
	Key runstore.CallKey
	// Inside counts encoded message bytes matched to the recorded view.
	Inside int
	// Outside counts encoded message bytes supplied independently of the view.
	Outside int
}

RequestGrowth identifies a request whose message bytes outside the view exceed those inside it. Workflow state controls once-per-run publication.

type ResumeRequest

type ResumeRequest struct {
	// RunID identifies the run to resume.
	RunID string

	// Notes carries optional human-readable context provided when resuming the run.
	Notes string

	// RequestedBy identifies the logical actor requesting the resume.
	RequestedBy string

	// Labels carries optional key-value metadata associated with the resume request.
	Labels map[string]string

	// Messages allows human or policy actors to inject new conversational messages before the planner resumes execution.
	Messages []*model.Message

	// MessageRefs addresses each encoded Messages entry in the root scope.
	MessageRefs []runstore.Hash

	// MessageSizes is overwritten by the runtime client from Messages.
	MessageSizes []contextmeasure.MessageSize
}

ResumeRequest carries metadata attached to a resume signal.

type RetryPolicy

type RetryPolicy struct {
	// MaxAttempts caps the total number of retry attempts. Zero means engine default.
	MaxAttempts int

	// InitialInterval is the delay before the first retry. Zero means engine default.
	InitialInterval time.Duration

	// BackoffCoefficient multiplies the delay after each retry (for example, 2.0 for exponential).
	BackoffCoefficient float64
}

RetryPolicy defines retry semantics shared by workflows and activities at the API layer.

type RunInput

type RunInput struct {
	// ContextSettings snapshots resolved recovery settings for every agent.
	ContextSettings compaction.ContextSettings `json:"context_settings,omitzero"`
	// ContextFingerprint addresses the canonical settings in the root scope.
	ContextFingerprint string `json:"context_fingerprint,omitzero"`
	// ContextDefaultAgents snapshots default policy for child dispatch.
	ContextDefaultAgents map[agent.Ident]ContextDefault `json:"context_default_agents,omitzero"`
	// ContextCompaction is runtime-stamped configuration for this run.
	ContextCompaction *ContextCompaction `json:"context_compaction,omitzero"`
	// ContextRecovery is the resolved runtime-stamped lookup configuration.
	ContextRecovery ContextRecovery `json:"context_recovery"`
	// RecoveryAgents snapshots child recovery settings independently of workers.
	RecoveryAgents map[agent.Ident]ContextRecovery `json:"recovery_agents,omitzero"`
	// CompactionAgents snapshots child-agent settings so child starts replay independently of worker options.
	CompactionAgents map[agent.Ident]ContextCompaction `json:"compaction_agents,omitzero"`
	// WorkflowProtocolVersion is stamped by the runtime and must match the
	// worker's WorkflowProtocolVersion, including when replaying history.
	WorkflowProtocolVersion int

	// AgentID identifies which agent should process the run.
	AgentID agent.Ident

	// RunID is the durable workflow execution identifier.
	RunID string

	// RootRunID identifies the root run of the run tree; it is the run store scope.
	RootRunID string

	// SessionID groups related runs (for example, multi-turn conversations).
	SessionID string

	// TurnID identifies the conversational turn (optional). When set, all events
	// produced during this run are tagged with this TurnID for UI grouping.
	TurnID string

	// ParentToolCallID identifies the parent tool call when this run represents a
	// nested agent execution (agent-as-tool). Empty for top-level runs. Used to
	// correlate ToolCallUpdated events and propagate parent-child relationships.
	ParentToolCallID string

	// ParentRunID identifies the run that scheduled this nested execution. Empty for
	// top-level runs. When set, tool events emitted by this run can be attributed to
	// the parent run.
	ParentRunID string

	// ParentAgentID identifies the agent that invoked this nested execution. Empty for
	// top-level runs. When set with ParentRunID, tool events can retain the parent agent
	// identity even though execution happens in a child agent.
	ParentAgentID agent.Ident

	// Tool identifies the fully-qualified tool name when this run is a nested
	// agent-as-tool execution. For top-level runs (not invoked via a parent tool),
	// Tool is empty. Planners may use this to select method-specific prompts.
	// Format: "<toolset>.<tool>".
	Tool tools.Ident

	// ToolArgs carries the original JSON arguments for the parent tool when this run
	// is an agent-as-tool execution. Nil for top-level runs. Nested agent planners
	// can use this structured input to render method-specific prompts without
	// reparsing free-form messages.
	ToolArgs rawjson.Message

	// Messages carries the conversation history supplied by the caller.
	Messages []*model.Message

	// Labels contains caller-provided metadata (account, priority, etc.).
	Labels map[string]string

	// Metadata allows orchestrators to attach arbitrary structured data.
	Metadata map[string]any

	// WorkflowOptions carries engine-specific start options (memo, search attributes,
	// custom task queues). If nil, the runtime derives defaults from the agent registration.
	WorkflowOptions *WorkflowOptions

	// Policy carries optional per-run policy overrides applied on every planner turn.
	// These options allow callers to set caps and tool filters without modifying
	// the agent registration defaults.
	Policy *PolicyOverrides
}

RunInput captures everything a workflow needs to start or resume a run. It includes the full conversational context plus caller-provided labels and metadata.

type RunOutput

type RunOutput struct {
	// AgentID echoes the agent that produced the result.
	AgentID agent.Ident

	// RunID echoes the workflow execution identifier.
	RunID string

	// Final is the assistant reply returned to the caller.
	Final *model.Message

	// FinalRef addresses the encoded Final message in the root run scope.
	FinalRef runstore.Hash

	// FinalToolResult is the canonical parent tool_result for nested agent runs
	// when the child planner/runtime owns the outer tool contract directly.
	//
	// Contract:
	// - This uses the same workflow-safe envelope as ToolEvents because it also
	//   crosses a workflow boundary.
	// - Result bytes are canonical JSON for the parent tool's result schema.
	// - Top-level runs normally leave this nil.
	FinalToolResult *ToolEvent

	// ToolEventsRef addresses the complete event list in the root run scope.
	// Use runtime.LoadRunToolEvents to restore result and server-data bytes.
	ToolEventsRef runstore.Hash

	// ToolEventCount is the number of events behind ToolEventsRef.
	ToolEventCount int

	// ToolSummary preserves child-run error and telemetry aggregation without
	// carrying the event list across the workflow boundary.
	ToolSummary ToolEventSummary

	// Notes aggregates planner annotations produced during the final turn.
	Notes []*planner.PlannerAnnotation

	// Usage aggregates model-reported token usage during the run when available.
	Usage *model.TokenUsage
}

RunOutput represents the final outcome returned by a run workflow, including the concluding assistant message plus tool traces and planner notes for callers.

type SealRecordInput added in v2.1.0

type SealRecordInput struct {
	// Continuation projection excludes the separately carried index head and pending entries.
	Checkpoint        *runstore.Hash     `json:"checkpoint,omitzero"`
	TailFrom          index.MessageID    `json:"tail_from,omitzero"`
	ClearedThrough    index.MessageID    `json:"cleared_through,omitzero"`
	PreviewThrough    index.MessageID    `json:"preview_through,omitzero"`
	ForceClearThrough index.MessageID    `json:"force_clear_through,omitzero"`
	Pinned            []index.MessageID  `json:"pinned,omitzero"`
	Budget            index.RenderBudget `json:"budget,omitzero"`
	// MinB is the smallest adopted usable context budget.
	MinB int `json:"min_b,omitzero"`
	// SessionID, Expected and Pos bind publication to the recorded start.
	SessionID string  `json:"session_id,omitzero"`
	Expected  *string `json:"expected,omitzero"`
	Pos       int     `json:"pos,omitzero"`
	// FinalHash addresses the final response. Publish excludes children and failures.
	FinalHash runstore.Hash `json:"final_hash,omitzero"`
	Publish   bool          `json:"publish,omitzero"`

	// ContextFingerprint identifies the stored canonical effective settings.
	ContextFingerprint string `json:"context_fingerprint,omitzero"`
	// ContextSettings snapshots resolved settings even before a first plan.
	ContextSettings compaction.ContextSettings
	// ContextRecovery is the resolved run configuration.
	ContextRecovery ContextRecovery
	// ContextCompaction preserves stamped settings even for a run with no adopted planner step.
	ContextCompaction *ContextCompaction `json:"context_compaction,omitzero"`
	// RootRunID is the shared content storage scope for the run tree.
	RootRunID string
	// RunID identifies the run whose transcript is sealed.
	RunID string
	// ProtocolVersion is copied from the workflow's validated RunInput.
	ProtocolVersion int
	// IndexHead is the most recently adopted index head.
	IndexHead runstore.Hash
	// Pending contains the remaining uncommitted transcript entries.
	Pending []index.MessageEntry
	// EventKey is the fixed logical identity run_sealed:<run>.
	EventKey string
	// Timestamp is fixed by the workflow clock before the first attempt.
	Timestamp time.Time
}

SealRecordInput fixes the terminal index and event identity before scheduling. Retries must receive the same pending entries, key and workflow timestamp.

type SealRecordOutput added in v2.1.0

type SealRecordOutput struct {
	// IndexHead addresses the complete sealed transcript.
	IndexHead runstore.Hash
}

SealRecordOutput identifies the terminal head after all pending entries commit.

type SummarizeContextInput added in v2.1.0

type SummarizeContextInput struct {
	// MaxModelCalls is the immutable recorded run admission cap.
	MaxModelCalls                   int `json:"max_model_calls,omitzero"`
	ContextSettings                 compaction.Settings
	ContextFingerprint              string
	AgentID                         agent.Ident
	RunID, Scope, SessionID, TurnID string
	Labels                          map[string]string
	Step                            int
	ViewRef                         index.ViewRef
	From, To                        index.MessageID
	Budget                          index.RenderBudget
	Rate                            contextmeasure.Rate
	ContextModel                    ContextModel
	PromptID                        prompt.Ident
	Settings                        SummarySettings
}

SummarizeContextInput binds one synchronous summary to an immutable cut.

type SummarizeContextOutput added in v2.1.0

type SummarizeContextOutput struct {
	// ModelCallLimit records an unsent logical invocation refused by the run cap.
	ModelCallLimit *policy.ModelCallLimit `json:"model_call_limit,omitzero"`
	// Latency measures the whole summary activity attempt in nanoseconds.
	Latency                              int64
	From, To                             index.MessageID
	IndexHead                            runstore.Hash
	Checkpoint                           *runstore.Hash
	Pinned                               []index.MessageID
	Kind                                 string
	CallKeys                             []runstore.CallKey
	Facts                                []contextmeasure.RequestFacts
	Prompt                               *prompt.PromptRef
	Usage                                model.TokenUsage
	Chunks, UnsummarisedBytes, LooseRefs int
}

SummarizeContextOutput exposes only durable addresses and bounded metadata. CallKeys includes every started call, independently of checkpoint Calls.

type SummaryPrompt added in v2.1.0

type SummaryPrompt = compaction.SummaryPrompt

SummaryPrompt pins a root-scoped summary template and its prompt identity.

type SummarySettings added in v2.1.0

type SummarySettings = compaction.SummarySettings

SummarySettings configures the summary baseline and additional instructions.

type ToolCallOutput

type ToolCallOutput struct {
	// Call addresses the stored dispatched call when Refs.Payload is empty.
	Call runstore.Hash

	// Refs addresses stored activity content in the root run scope. ServerData and
	// Payload are server-only and must never enter model-facing messages.
	Refs tools.ResultRefs

	// Name is the canonical <toolset>.<tool> identifier that was executed.
	Name tools.Ident

	// ToolCallID is the correlation identifier for this tool invocation.
	ToolCallID string

	// Payload is the canonical JSON payload passed to the tool.
	Payload rawjson.Message

	// Result is the canonical JSON result payload encoded using the tool result codec.
	Result rawjson.Message

	// ResultBytes is the size, in bytes, of the canonical JSON result payload
	// produced by the runtime before any workflow-boundary trimming is applied.
	ResultBytes int

	// ResultOmitted indicates that the runtime intentionally omitted Result bytes
	// from this envelope to satisfy workflow-boundary payload budgets.
	ResultOmitted bool

	// ResultOmittedReason provides a stable, machine-readable reason for omitting
	// the result bytes. Empty when ResultOmitted is false.
	ResultOmittedReason string

	// ServerData carries canonical server-only data emitted alongside the tool result.
	ServerData rawjson.Message

	// Bounds describes how the result has been bounded relative to the full underlying data set.
	Bounds *agent.Bounds

	// Error is the structured tool error when tool execution failed.
	Error *planner.ToolError

	// RetryHint is optional structured guidance for recovering from tool failures.
	RetryHint *planner.RetryHint

	// Telemetry contains tool execution metrics (duration, token usage, model).
	Telemetry *telemetry.ToolTelemetry

	// Artifacts contains workflow-safe references to persisted artifacts.
	Artifacts []artifact.Ref `json:"artifacts,omitempty"`
}

ToolCallOutput is the workflow-boundary safe record of one executed tool call passed into planner resume/finalization activities.

Contract:

  • Payload is the canonical JSON input sent to the tool.
  • Result and ServerData are canonical JSON bytes, not decoded Go values.
  • This preserves the exact executed tool boundary for planners that need authoritative execution history.

type ToolEvent

type ToolEvent struct {
	// Preview is the planner-visible result summary.
	Preview string
	// Refs addresses stored activity content in the root run scope. ServerData and
	// Payload are server-only and must never enter model-facing messages.
	Refs tools.ResultRefs

	// Name is the canonical <toolset>.<tool> identifier that produced this result.
	Name tools.Ident

	// Result is the canonical JSON result payload encoded using the tool result codec.
	Result rawjson.Message

	// ResultBytes is the size, in bytes, of the canonical JSON result payload
	// produced by the runtime before any workflow-boundary trimming is applied.
	//
	// When ResultOmitted is true, ResultBytes reports the original size even though
	// Result is nil.
	ResultBytes int

	// ResultOmitted indicates that the runtime intentionally omitted Result bytes
	// from this envelope to satisfy workflow-boundary payload budgets.
	//
	// This is used in planner activity inputs: workflow orchestration must not
	// shuttle large tool payloads. Full tool results remain available via hooks
	// (memory/streams) and through runtime.LoadRunToolEvents.
	ResultOmitted bool

	// ResultOmittedReason provides a stable, machine-readable reason for omitting
	// the result bytes. Empty when ResultOmitted is false.
	//
	// Example values: "workflow_budget".
	ResultOmittedReason string

	// ServerData carries server-only data emitted alongside the tool result.
	// It is never sent to model providers.
	ServerData rawjson.Message

	// Bounds, when non-nil, describes how the result has been bounded relative
	// to the full underlying data set (for example, list/window/graph caps).
	Bounds *agent.Bounds

	// Error is the structured tool error when tool execution failed.
	Error *planner.ToolError

	// RetryHint is optional structured guidance for recovering from tool failures.
	RetryHint *planner.RetryHint

	// Telemetry contains tool execution metrics (duration, token usage, model).
	Telemetry *telemetry.ToolTelemetry

	// ToolCallID is the correlation identifier for this tool invocation.
	ToolCallID string

	// ChildrenCount records how many nested tool results were observed when this
	// result came from an agent-as-tool execution.
	ChildrenCount int

	// RunLink links this tool result to a nested agent run when it was produced by
	// an agent-as-tool. Nil for service-backed tools.
	RunLink *run.Handle

	// Artifacts contains workflow-safe references to persisted artifacts.
	Artifacts []artifact.Ref `json:"artifacts,omitempty"`
}

ToolEvent is the workflow-boundary safe representation of a tool result emitted by a run.

Contract:

  • Result and ServerData are canonical JSON bytes, not decoded Go values.
  • Runtimes must decode Result bytes using the registered tool result codec.
  • This is required for agent-as-tool: child workflow outputs cross a workflow boundary, and `any` fields would otherwise rehydrate as map[string]any.

type ToolEventSummary added in v2.1.0

type ToolEventSummary struct {
	// FailedCount counts events carrying tool errors.
	FailedCount int
	// LastError is the last tool error, used when every child tool failed.
	LastError *planner.ToolError
	// Telemetry sums tokens and duration and retains the first reported model.
	Telemetry *telemetry.ToolTelemetry
}

ToolEventSummary preserves child-run aggregation in a fixed number of fields.

type ToolInput

type ToolInput struct {
	// RunID identifies the run that owns this tool call.
	RunID string

	// RootRunID identifies the root run of the run tree; it is the run store scope.
	RootRunID string

	// AgentID identifies the agent that owns this tool call.
	AgentID agent.Ident

	// ToolsetName identifies the owning toolset when known; it may be empty when inferred by ToolName.
	ToolsetName string

	// ToolName is the canonical <toolset>.<tool> identifier.
	ToolName tools.Ident

	// ToolCallID uniquely identifies the tool invocation for correlation across events.
	ToolCallID string

	// Payload is the canonical JSON payload for the tool call.
	Payload rawjson.Message

	// SessionID is the logical session identifier (for example, a chat conversation).
	SessionID string

	// Labels carries runtime-owned routing and policy labels for this tool call.
	Labels map[string]string

	// TurnID identifies the conversational turn that produced this tool call.
	TurnID string

	// ParentToolCallID is the identifier of the parent tool call when this invocation is nested.
	ParentToolCallID string
}

ToolInput is the payload passed to tool executors. Payload is JSON-encoded.

type ToolOutput

type ToolOutput struct {
	// NonText is the recalled attachment token estimate.
	NonText int `json:"non_text,omitzero"`
	// Preview is the planner-visible result summary.
	Preview string
	// ResultBytes is the stored eligible result size.
	ResultBytes int
	// Refs addresses stored activity content in the root run scope. ServerData and
	// Payload are server-only and must never enter model-facing messages.
	Refs tools.ResultRefs

	// Payload is the tool result encoded as JSON. The runtime decodes it using the registered tool codec.
	Payload rawjson.Message

	// ServerData carries server-only data emitted alongside the tool result. It is
	// never forwarded to model providers, but it must cross workflow/activity
	// boundaries so in-process subscribers (persistence, metrics, UIs) can
	// consume it.
	//
	// Contract:
	//   - This is canonical JSON (typically a JSON array of server data items).
	//   - Tool implementations may return nil when no server data is present.
	ServerData rawjson.Message

	// Bounds carries canonical bounded-result metadata across workflow/activity
	// boundaries when the tool contract declares an out-of-band bounds channel.
	Bounds *agent.Bounds

	// Telemetry contains execution timing and provider usage metadata when available.
	Telemetry *telemetry.ToolTelemetry

	// Artifacts contains workflow-safe references to persisted artifacts.
	Artifacts []artifact.Ref `json:"artifacts,omitempty"`

	// Error is a plain-text error message when tool execution failed.
	Error string

	// ErrorKind carries a stable machine-readable classification when policy
	// must distinguish this failure across the activity boundary.
	ErrorKind planner.ToolErrorKind

	// RetryHint provides structured retry guidance when execution failed due to invalid payloads.
	RetryHint *planner.RetryHint

	// Pause carries an optional runtime-owned pause signal emitted by the tool
	// from the current execution batch.
	//
	// Contract:
	//   - This survives the tool activity boundary so the workflow thread can
	//     pause before the next planner resume.
	//   - The runtime consumes it from the current batch only and does not
	//     persist it into cumulative planner ToolOutputs history.
	Pause *ToolPause
}

ToolOutput is returned by tool executors after invoking the tool implementation.

type ToolPause

type ToolPause struct {
	Clarification *ToolPauseClarification
}

ToolPause describes one runtime-owned pause request emitted by a tool.

Exactly one payload field must be set.

type ToolPauseClarification

type ToolPauseClarification struct {
	// ID uniquely identifies this pause request.
	ID string

	// Question is the operator-facing prompt to present.
	Question string
}

ToolPauseClarification requests free-form operator input before the runtime resumes planning.

type ToolResultRefs added in v2.1.0

type ToolResultRefs = tools.ResultRefs

ToolResultRefs addresses the eligible result and server-only activity content.

type ToolResultsSet

type ToolResultsSet struct {
	// RunID identifies the run associated with the external tool results.
	RunID string

	// ID is the await identifier corresponding to the original AwaitExternalTools
	// or AwaitQuestions event. It is required: ProvideToolResults rejects a set
	// whose ID does not match the run's pending tool await.
	ID string

	// Results contains the tool results provided by an external system.
	//
	// Contract:
	// - This field crosses a workflow signal boundary. It must be wire-safe and must
	//   not embed planner.ToolResult (which contains `any`) or the runtime-owned
	//   `ToolEvent` envelope.
	// - The runtime owns decoding, result materialization, canonicalization,
	//   and server-side sidecar attachment after this signal is received.
	Results []*ProvidedToolResult
}

ToolResultsSet carries results for an external tools await request.

type TypedContentValidation added in v2.1.0

type TypedContentValidation struct {
	Schema     rawjson.Message
	PayloadRef runstore.Hash
}

TypedContentValidation validates one stored answer against its awaited schema.

type TypedInputAnswer

type TypedInputAnswer struct {
	// RunID identifies the run associated with the typed input.
	RunID string

	// ID is the typed input await identifier.
	ID string

	// PayloadRef addresses the canonical answer JSON in the root scope.
	PayloadRef runstore.Hash

	// Payload is the canonical JSON answer payload.
	Payload rawjson.Message

	// Labels carries optional metadata associated with the answer.
	Labels map[string]string
}

TypedInputAnswer carries a typed human-input answer for an await request.

type ViewUpdate added in v2.1.0

type ViewUpdate struct {
	// Checkpoint is returned only after the immutable record is stored.
	Checkpoint runstore.Hash
	// Pinned is the selection for the current record and render budget.
	Pinned []index.MessageID
	// CheckpointBytes measures the rendered model-facing text.
	CheckpointBytes int
}

ViewUpdate reports a stored checkpoint and its current rendering.

type WorkflowOptions

type WorkflowOptions struct {
	// Memo is a map of key-value pairs that can be used to store data for the workflow.
	Memo map[string]any

	// SearchAttributes is a map of key-value pairs indexed by the engine for visibility.
	SearchAttributes map[string]any

	// TaskQueue is the name of the task queue to use for the workflow.
	TaskQueue string

	// RetryPolicy is the retry policy to use for workflow start.
	RetryPolicy RetryPolicy
}

WorkflowOptions mirrors a subset of engine start options exposed through the runtime. Engine adapters convert these into native options at start time.

type WorkflowProtocolMismatchError added in v2.1.0

type WorkflowProtocolMismatchError struct {
	// Want is the protocol version required by this worker.
	Want int
	// Got is the protocol version stamped into the workflow input.
	Got int
}

WorkflowProtocolMismatchError reports an input recorded for a different agent workflow protocol. Running workflows must be drained before upgrading.

func (*WorkflowProtocolMismatchError) Error added in v2.1.0

Error describes both versions and the required upgrade procedure.

func (*WorkflowProtocolMismatchError) Is added in v2.1.0

Is classifies this error as ErrWorkflowProtocolMismatch.

Jump to

Keyboard shortcuts

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