api

package
v1.0.4 Latest Latest
Warning

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

Go to latest
Published: Mar 23, 2026 License: MIT Imports: 11 Imported by: 0

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"
)

Variables

This section is empty.

Functions

This section is empty.

Types

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

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

ClarificationAnswer carries a typed answer for a paused clarification request.

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 HookActivityInput

type HookActivityInput = hooks.ActivityInput

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

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 {
	// AgentID identifies which agent is being planned.
	AgentID agent.Ident

	// RunID identifies the run being planned.
	RunID string

	// Messages is the current conversation transcript provided to the planner.
	Messages []*model.Message

	// RunContext carries nested-run metadata (parent IDs, tool identifiers, etc.).
	RunContext run.Context

	// ToolOutputs is the accumulated executed tool-call history for the run so far.
	//
	// Contract:
	// - This is the sole planner-facing execution-history field across the
	//   workflow/activity boundary.
	// - Entries preserve the canonical tool input, output, and server data bytes.
	ToolOutputs []*ToolCallOutput

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

PlanActivityInput carries the planner input for PlanStart and PlanResume activities.

type PlanActivityOutput

type PlanActivityOutput struct {
	// Result is the planner output describing next tool calls, await requests, or final response.
	Result *planner.PlanResult

	// Transcript contains the provider-visible transcript produced by the planner.
	Transcript []*model.Message

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

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

func (*PlanActivityOutput) UnmarshalJSON

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

UnmarshalJSON handles decoding PlanActivityOutput so that Transcript entries are deserialized through the richer model.Message decoder (which materializes Part implementations). This keeps workflows resilient to legacy payloads.

type PolicyOverrides

type PolicyOverrides struct {
	// 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

	// 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

	// MaxConsecutiveFailedToolCalls caps the number of consecutive failing tool calls before finalizing.
	MaxConsecutiveFailedToolCalls int

	// TimeBudget caps the total wall-clock runtime budget for the run.
	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

	// 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; zero values mean no override.

type ProvidedToolResult

type ProvidedToolResult struct {
	// Name is the fully-qualified 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
}

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 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
}

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 {
	// AgentID identifies which agent should process the run.
	AgentID agent.Ident

	// RunID is the durable workflow execution identifier.
	RunID 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: "<service>.<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

	// 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

	// ToolEvents captures all tool results emitted before completion in execution order.
	//
	// Contract:
	// - ToolEvents must be workflow-boundary safe. Do not embed planner.ToolResult here:
	//   planner.ToolResult contains `any` fields (Result) which Temporal will
	//   rehydrate as map[string]any in parent workflows, eliminating strong typing
	//   at the boundary.
	ToolEvents []*ToolEvent

	// 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 ToolCallOutput

type ToolCallOutput struct {
	// Name is the fully-qualified 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
}

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 {
	// Name is the fully-qualified 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 in RunOutput.ToolEvents.
	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
}

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 ToolInput

type ToolInput struct {
	// RunID identifies the run that owns this tool call.
	RunID 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 fully-qualified 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

	// 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 {
	// 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

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

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

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

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 event.
	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 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.

Jump to

Keyboard shortcuts

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