runtime

package
v0.31.1 Latest Latest
Warning

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

Go to latest
Published: Oct 31, 2026 License: MIT Imports: 24 Imported by: 0

Documentation

Overview

Package runtime — top-level ICM orchestrator.

The Orchestrator drives a single workflow run from the first stage through the last. It owns no LLM client, no HITL surface, and no session storage directly: every sub-agent dispatch routes through a Dispatcher (typically *delegate.Runtime), every operator interaction routes through HITLDispatch (supplied by the plugin), and every artifact / state write is funneled through a *session.Session. Tests substitute fakes for the Dispatcher and HITLDispatch fields to exercise control flow without touching the LLM surface.

Package runtime assembles per-turn XML payloads for ICM sub-agent dispatch.

A payload bundles the grounding (skills + grounding files the agent must internalize) and the layer data (declared input artifacts and an optional fan-out item) the sub-agent transforms. Optional feedback blocks (previous_attempt, previous_iteration) carry retry / loop signal. An optional session_context block surfaces the session's current non-reserved Labels, read fresh on every Build call — dynamic per-turn context lives only here, never (only) in the system prompt. The builder is pure — it reads from the filesystem only, never the event bus — so it can be exercised in isolation. The operator system prompt is rendered separately at posture-registration time and is NOT produced here.

Package runtime — posture derivation for ICM stage dispatch.

This file builds a `posture.AgentPosture` for each stage and verifier in the workspace by layering:

  1. The plugin's `default_workflow_posture` (registry lookup) — provides base Model/AllowedTools/Budget/MaxRecursionDepth.
  2. The stage's named `agent.posture` from the registry (when set, replaces the layer-1 base entirely).
  3. The stage's `agent.{model_role, tools, prompt_overlay, budget, max_recursion_depth}` overrides applied on top.

The base posture's SystemPrompt is always discarded. The derived SystemPrompt is rendered fresh from `workspace.Operator.Body` (workspace operator template, already including the workspace operator overlay when present) and the stage-level `agent.prompt_overlay`. Run-time values (runID, turn, iteration, item) never enter the system prompt — they live only on the per-turn XML payload.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func SkillToolName

func SkillToolName(instanceID string) string

SkillToolName returns the instance-scoped read_skill_reference tool name. The default instance gets the bare name; suffixed instances get `read_skill_reference_<suffix>` so multi-instance ICM configurations don't collide on a shared tool name.

Types

type Dispatcher

type Dispatcher interface {
	Run(ctx context.Context, in delegate.Input) (delegate.Output, error)
}

Dispatcher is the narrow contract the orchestrator uses to invoke a sub-agent. *delegate.Runtime satisfies this interface; tests substitute a fake that returns canned outputs without touching the LLM surface.

type HITLDispatchFunc

type HITLDispatchFunc func(ctx context.Context, req events.HITLRequest) (events.HITLResponse, error)

HITLDispatchFunc is the orchestrator-facing HITL gateway. The plugin wires it to its own emit-and-wait machinery (predicates_wiring.go) so the orchestrator never touches the bus directly for HITL traffic.

type NewHITLIDFunc

type NewHITLIDFunc func(kind, runID, stageID, extra string) string

NewHITLIDFunc generates a unique HITL request ID. The plugin's newHITLID helper satisfies this; the orchestrator never invents IDs itself so the hitl-prefix filter in handleHITLResponded stays the sole source of truth.

type OperatorTemplateCtx

type OperatorTemplateCtx struct {
	// Workspace describes the workflow as a whole.
	Workspace WorkspaceTplCtx
	// Stage describes the single stage this posture dispatches.
	Stage StageTplCtx
	// Context is the session's current non-reserved Labels (see
	// engine.IsReservedLabelKey), read fresh at render time — never a value
	// cached at PostureBuilder construction — so a tag written mid-session
	// is visible to any stage template rendered afterward. Reserved
	// ("_"-prefixed) keys, e.g. "_principal_id", are filtered out
	// unconditionally and never reach this map. Usable in operator.md and
	// other stage templates as `{{ .Context.<key> }}`. Empty, non-nil when
	// there is no session or no non-reserved labels are set.
	Context map[string]string
}

OperatorTemplateCtx is the value passed to the workspace operator template at posture build time. The Run vars deliberately do NOT appear: dynamic per-turn context lives only in the XML payload's <icm_turn> attributes, never in the system prompt.

type Orchestrator

type Orchestrator struct {
	Workflow       *workspace.Workflow
	Session        *session.Session
	Runtime        Dispatcher
	Evaluator      *predicates.Evaluator
	Payload        *PayloadBuilder
	PostureBuilder *PostureBuilder
	Bus            engine.EventBus
	Logger         *slog.Logger

	// HITLDispatch dispatches a HITL request and waits for the response.
	// nil disables every human-gate path: gates auto-resolve as allow and
	// HITL-backed predicates surface as failures.
	HITLDispatch HITLDispatchFunc
	// NewHITLID supplies request IDs. Required when HITLDispatch is set.
	NewHITLID NewHITLIDFunc

	// InstanceID identifies the plugin instance owning this run; surfaces
	// in event payloads + StageEvalContext.
	InstanceID string
	// RunID identifies the run. Mirrors Session.RunID; carried separately
	// so event payloads can be assembled before the session loads.
	RunID string
	// ParentTurnID is the upstream turn that triggered the run, propagated
	// for causation.
	ParentTurnID string
	// ParentDepth is the sub-agent depth of the upstream turn.
	ParentDepth int
	// LoopMaxRestarts caps how many times a single looping stage may be
	// restarted via the human_gate exhaustion path. 0 disables the cap.
	LoopMaxRestarts int
	// EmitThinkingSteps mirrors the plugin's emit_progress_thinking_steps
	// option. Currently unused by the orchestrator surface; reserved for
	// future thinking-step emission per stage transition.
	EmitThinkingSteps bool
	// contains filtered or unexported fields
}

Orchestrator runs a single ICM workflow end-to-end. Construct via the plugin (Plugin.buildOrchestrator) — direct construction is allowed in tests but production code should funnel through the plugin so every field is populated.

func (*Orchestrator) Run

func (o *Orchestrator) Run(ctx context.Context) error

Run drives the workflow from first stage to last. Returns a non-nil error on any halt path (dispatch error policy halt, rejected gate, loop exhausted under on_exhausted=error, cancelled context). The run is always reported via either ICMRunCompleted or ICMRunHalted before return.

type OutputTplCtx

type OutputTplCtx struct {
	// Format is "text" or "json".
	Format string
	// Filename is the artifact filename.
	Filename string
	// Schema is the workspace-relative JSON schema path; empty for text
	// stages. Surfaced so the prompt can reference it for documentation.
	Schema string
}

OutputTplCtx is the stage output slice exposed to the operator template.

type PayloadBuilder

type PayloadBuilder struct {
	// Workflow is the loaded workspace contract.
	Workflow *workspace.Workflow
	// Session is the active run that owns artifact paths.
	Session *session.Session
	// EngineSession is the engine-level session workspace, used to read the
	// current session's Labels fresh on every Build call (see
	// sessionContextBody). Nil is tolerated — the <session_context> block is
	// simply omitted — for builders constructed without a session (e.g.
	// tests).
	EngineSession *engine.SessionWorkspace
	// InlineArtifactLimitBytes is the inline-vs-ref size threshold.
	// Zero falls back to defaultInlineArtifactLimitBytes.
	InlineArtifactLimitBytes int
	// Logger receives WARN entries when artifacts / grounding files are
	// missing or oversized. nil falls back to slog.Default().
	Logger *slog.Logger
}

PayloadBuilder assembles per-turn XML payloads for sub-agent dispatch.

A single builder is reused across the turns of a workflow run. It is stateless beyond its configuration and safe for sequential use.

func (*PayloadBuilder) Build

func (b *PayloadBuilder) Build(in PayloadInputs) (string, error)

Build assembles the user-message XML payload for a single turn.

Pure I/O: reads grounding files and input artifacts from disk; never touches the event bus or HITL surfaces. Missing artifacts and missing grounding files become <artifact_ref missing="true"/> / <file_ref/> elements plus a WARN log entry — no error is returned. Genuine I/O failures (e.g. permission denied) propagate.

type PayloadInputs

type PayloadInputs struct {
	// Stage is the stage being dispatched.
	Stage *workspace.Stage
	// Iteration is 1-based for loop iterations; 0 for non-loop stages.
	Iteration int
	// Turn is the 1-based turn within the current invocation.
	Turn int
	// ItemID identifies a fan-out item; "" for non-fan-out stages.
	ItemID string
	// ItemValue is the JSON-marshallable fan-out item value, populated
	// only for fan-out invocations.
	ItemValue any
	// RunID is the active session's run ID, surfaced as an attribute on
	// the root element when non-empty.
	RunID string
	// PreviousAttempt carries the prior turn's output + validator failures
	// for retry feedback within the same invocation.
	PreviousAttempt *PreviousAttempt
	// PreviousIteration carries the prior loop iteration's artifact + exit
	// failures.
	PreviousIteration *PreviousIteration
}

PayloadInputs is the per-turn context supplied by the orchestrator.

type PostureBuilder

type PostureBuilder struct {
	// Workflow is the loaded workspace contract.
	Workflow *workspace.Workflow
	// InstanceID is the full plugin instance ID
	// (e.g. "nexus.workflows.icm" or "nexus.workflows.icm/script").
	InstanceID string
	// DefaultBasePosture is the plugin config `default_workflow_posture`
	// name. Empty when not configured.
	DefaultBasePosture string
	// Registry is the posture registry to look up named bases against.
	Registry posture.Registry
	// SkillToolName is the instance-scoped read_skill_reference tool name.
	SkillToolName string
	// AutoIncludeSkillTool controls whether stages with non-empty
	// Inputs.Skills automatically get SkillToolName appended to their
	// AllowedTools.
	AutoIncludeSkillTool bool
	// Session is the engine session workspace, used to read the current
	// session's Labels at each operator-template render (see
	// OperatorTemplateCtx.Context). Nil is tolerated — Context resolves to
	// an empty map — for instances built without a session (e.g. tests).
	Session *engine.SessionWorkspace
}

PostureBuilder derives a posture per stage by composing the plugin's default workflow posture, an optional stage-named base posture, and the stage's per-field overrides.

One builder is constructed per plugin instance at Ready() time. It is stateless beyond its configuration and safe for sequential use.

func (*PostureBuilder) Build

Build returns the derived AgentPosture for a workflow stage. The posture's Name is the registry key derived from PostureName.

Errors propagate from base lookup (referenced posture missing) and operator template rendering.

func (*PostureBuilder) BuildVerifier

func (b *PostureBuilder) BuildVerifier(verifier *workspace.Stage) (posture.AgentPosture, error)

BuildVerifier returns the derived AgentPosture for a verifier stage. Identical to Build aside from the registry key shape (which already matches because verifier IDs are flat strings handled the same way).

func (*PostureBuilder) PostureName

func (b *PostureBuilder) PostureName(stageID string) string

PostureName returns the registry name a stage (or verifier) posture is registered under. Default instance: `icm.<stageID>`. Suffixed instance (`nexus.workflows.icm/<suffix>`): `icm.<suffix>.<stageID>`.

func (*PostureBuilder) PredicateSchemaName

func (b *PostureBuilder) PredicateSchemaName(stageID, predicateName string) string

PredicateSchemaName returns the schema registry key used for a per- predicate JSON schema (output validator or loop `until` condition).

func (*PostureBuilder) SchemaName

func (b *PostureBuilder) SchemaName(stageID string) string

SchemaName returns the engine SchemaRegistry key used for a stage's `output` schema. Default instance: `icm.<stageID>.output`. Suffixed: `icm.<suffix>.<stageID>.output`.

type PreviousAttempt

type PreviousAttempt struct {
	// Turn is the 1-based turn number of the prior attempt.
	Turn int
	// Output is the raw output produced by the prior turn.
	Output []byte
	// Failures lists the validator results that triggered the retry.
	// Entries with Verdict == "pass" are filtered out.
	Failures []icmtypes.ConditionResult
	// HumanFeedback is the free-text response from a HITL `continue`
	// action under turn_policy=until_human_approves. Optional.
	HumanFeedback string
}

PreviousAttempt represents one prior turn's output + failures within the same invocation (turn-loop retry feedback).

type PreviousIteration

type PreviousIteration struct {
	// Index is the 1-based prior iteration number.
	Index int
	// Artifact is the raw bytes of the prior iteration's artifact.
	Artifact []byte
	// Path is the logical ref ("<stage_id>/<filename>") for the artifact.
	Path string
	// Failures lists the loop exit-condition results that triggered the
	// next iteration. Entries with Verdict == "pass" are filtered out.
	Failures []icmtypes.ConditionResult
}

PreviousIteration represents the immediately prior loop iteration.

type StageTplCtx

type StageTplCtx struct {
	// ID is the stage folder ID (e.g. "02_script") or verifier ID.
	ID string
	// Display is the human-readable label resolved by the loader.
	Display string
	// Role is the contract body (markdown after frontmatter).
	Role string
	// Output is a flattened view of the stage's output spec.
	Output OutputTplCtx
	// HumanGate is the stage's human-gate position rendered as a string.
	HumanGate string
}

StageTplCtx is the stage-level slice of OperatorTemplateCtx.

type WorkspaceTplCtx

type WorkspaceTplCtx struct {
	// Name is the basename of the workspace root folder.
	Name string
	// Description is the first non-empty line of workspace.md.
	Description string
}

WorkspaceTplCtx is the workspace-level slice of OperatorTemplateCtx.

Jump to

Keyboard shortcuts

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