application

package
v0.11.5 Latest Latest
Warning

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

Go to latest
Published: Oct 27, 2026 License: EUPL-1.2 Imports: 46 Imported by: 0

Documentation

Overview

Package application provides application services that orchestrate domain operations.

The application layer sits between the interfaces layer (CLI, API) and the domain layer, coordinating workflow execution through ports and domain entities. Services in this package implement use cases and business workflows without containing business rules (which reside in the domain layer). All infrastructure dependencies are injected via port interfaces.

Architecture Role

In the hexagonal architecture:

  • Application services receive requests from interfaces layer (CLI commands)
  • Services orchestrate domain entities (Workflow, Step, ExecutionContext)
  • Services delegate infrastructure work to ports (CommandExecutor, StateStore)
  • Services coordinate cross-cutting concerns (logging, state persistence, history)

The application layer enforces the dependency rule: it depends on domain ports (inward) but is depended upon by the interfaces layer (outward). Infrastructure adapters implement the ports that services consume.

Core Orchestration Services

## WorkflowService (service.go)

High-level workflow operations:

  • ListWorkflows: Enumerate available workflows
  • GetWorkflow: Load workflow definition by name
  • ValidateWorkflow: Static validation of workflow structure
  • WorkflowExists: Check if workflow is available

Dependencies: WorkflowRepository, StateStore, CommandExecutor, Logger

## ExecutionService (execution_service.go)

Core workflow execution orchestrator:

  • ExecuteWorkflow: Full workflow execution with state machine traversal
  • ExecuteStep: Single step execution dispatcher (routes by StepType)
  • HandleTransitions: Conditional transition evaluation
  • SaveCheckpoint: Persist execution state for resumption

Step type handlers:

  • executeCommandStep: Shell command execution with capture
  • executeAgentStep: AI agent invocation (single-shot and conversation)
  • executeParallelStep: Concurrent branch execution
  • executeForEachStep: Loop over items
  • executeWhileStep: Conditional loop
  • executeOperationStep: Plugin operation invocation
  • executeCallWorkflowStep: Nested sub-workflow execution
  • executeTerminalStep: Workflow completion

Dependencies: WorkflowService, CommandExecutor, ParallelExecutor, StateStore, Logger, ExpressionEvaluator, HookExecutor, LoopExecutor, TemplateService, HistoryService, OperationProvider, AgentRegistry, ConversationExecutor

Optional configuration:

  • SetOutputWriters: Configure stdout/stderr streaming
  • SetTemplateService: Enable template expansion
  • SetOperationProvider: Enable plugin operations
  • SetAgentRegistry: Enable AI agent steps
  • SetEvaluator: Enable conditional transitions
  • SetConversationManager: Enable multi-turn conversations

## HistoryService (history_service.go)

Workflow execution history and analytics:

  • RecordExecution: Persist workflow run record with metadata
  • GetExecutionHistory: Query execution records (filtering, pagination)
  • GetExecutionStats: Aggregate statistics (counts, durations, success rates)
  • PruneOldHistory: Clean up old execution records

Dependencies: HistoryStore, Logger

## TemplateService (template_service.go)

Workflow template expansion and validation:

  • ExpandTemplate: Resolve template reference into concrete steps
  • ValidateTemplate: Check template syntax and parameter bindings
  • LoadTemplate: Retrieve template definition by name

Dependencies: TemplateRepository, Logger, ExpressionValidator

## PluginService (plugin_service.go)

Plugin lifecycle management:

  • DiscoverPlugins: Scan and list available plugins
  • LoadPlugin: Initialize plugin with configuration
  • EnablePlugin: Activate plugin for workflow use
  • DisablePlugin: Deactivate plugin
  • GetPluginStatus: Check plugin enabled/disabled state

Dependencies: PluginManager, PluginStateStore, Logger

## InputCollectionService (input_collection_service.go)

Interactive input gathering:

  • CollectInputs: Prompt user for missing workflow inputs
  • ValidateInputs: Check input values against validation rules
  • BuildInputMap: Construct workflow input map from user responses

Dependencies: InputCollector, Logger

Specialized Executors

## ParallelExecutor (parallel_executor.go)

Concurrent branch execution with strategies:

  • Execute: Run branches concurrently with semaphore control
  • all_succeed: All branches must succeed
  • any_succeed: At least one branch succeeds
  • best_effort: Execute all, report best outcome

Features:

  • MaxConcurrent: Limit concurrent goroutines
  • DependsOn: Branch execution ordering constraints
  • Graceful cancellation via context

Dependencies: StepExecutor, Logger

## LoopExecutor (loop_executor.go)

Iterative step execution:

  • ExecuteForEach: Iterate over items collection
  • ExecuteWhile: Conditional loop with guard expression
  • BuildLoopContext: Construct loop variables (item, index, first, last)
  • EvaluateLoopCondition: Check while loop guard

Loop context variables:

  • {{loop.item}}: Current item value
  • {{loop.index}}: Zero-based iteration index
  • {{loop.first}}: Boolean first iteration flag
  • {{loop.last}}: Boolean last iteration flag
  • {{loop.length}}: Total items count (for_each only)

Dependencies: StepExecutor, ExpressionEvaluator, Logger

## InteractiveExecutor (interactive_executor.go)

Step-by-step interactive execution:

  • ExecuteInteractive: Prompt user before each step
  • PromptUserAction: Present execution options (run, skip, retry, abort, edit)
  • HandleUserChoice: Process user action and update state

User actions:

  • Run: Execute step normally
  • Skip: Skip step and proceed to next
  • Retry: Re-attempt previous step
  • Abort: Halt workflow execution
  • Edit: Modify step parameters before execution

Dependencies: InteractivePrompt, StepExecutor, Logger

## DryRunExecutor (dry_run_executor.go)

Workflow validation without side effects:

  • ExecuteDryRun: Traverse workflow without executing commands
  • LogPlannedActions: Report steps that would execute
  • ValidateGraph: Check state transitions are valid

Dependencies: WorkflowService, Logger

## HookExecutor (hook_executor.go)

Workflow and step lifecycle hooks:

  • ExecuteWorkflowHooks: Workflow start/end/error/cancel events
  • ExecuteStepHooks: Step pre/post execution hooks
  • ExecuteHookAction: Process individual hook (log or command)

Hook types:

  • Log: Structured log message with template interpolation
  • Command: Shell command execution

Dependencies: CommandExecutor, Logger, ExpressionEvaluator

## ConversationManager (conversation_manager.go)

Multi-turn AI agent conversations:

  • ExecuteConversation: Manage conversation loop with turn limits
  • EvaluateStopConditions: Check conversation termination criteria
  • ManageContextWindow: Trim conversation history for token budget
  • RecordMessage: Append user/assistant messages to history

Context window strategies:

  • truncate_middle: Remove middle messages, keep first/last
  • summarize: Use LLM to summarize old messages
  • truncate_oldest: Drop oldest messages first

Dependencies: AgentProvider, Tokenizer, ExpressionEvaluator, Logger

Supporting Services

## OutputStreamer (output_streamer.go)

Real-time command output streaming:

  • StreamOutput: Write command stdout to writer during execution
  • StreamError: Write command stderr to writer during execution
  • CaptureOutput: Buffer output for context interpolation

Dependencies: io.Writer (stdout, stderr)

## OutputLimiter (output_limiter.go)

Memory protection for large outputs:

  • LimitOutput: Enforce maximum output size
  • TruncateOutput: Trim output exceeding limit
  • ReportTruncation: Log truncation events

Prevents out-of-memory errors from unbounded command output accumulation.

Dependencies: Logger

Usage Examples

## Basic Workflow Execution

Orchestrate workflow execution with injected dependencies:

wfSvc := NewWorkflowService(repo, store, executor, logger, validator)
execSvc := NewExecutionService(wfSvc, executor, parallelExec, store, logger, resolver, historySvc)

// Validate workflow before execution
if err := wfSvc.ValidateWorkflow(ctx, "deploy-app"); err != nil {
    log.Fatalf("validation failed: %v", err)
}

// Execute workflow with inputs
result, err := execSvc.ExecuteWorkflow(ctx, "deploy-app", map[string]any{
    "environment": "production",
    "version": "v1.2.3",
})
if err != nil {
    log.Fatalf("execution failed: %v", err)
}

## Configure Optional Features

Enable specialized executors:

execSvc.SetOutputWriters(os.Stdout, os.Stderr)
execSvc.SetTemplateService(templateSvc)
execSvc.SetOperationProvider(pluginRegistry)
execSvc.SetAgentRegistry(agentRegistry)
execSvc.SetEvaluator(expressionEvaluator)
execSvc.SetConversationManager(conversationMgr)

## Interactive Mode Execution

Run workflow with step-by-step control:

interactiveExec := NewInteractiveExecutor(prompter, stepExecutor, logger)
result, err := interactiveExec.ExecuteInteractive(ctx, workflow, inputs)

## Query Execution History

historySvc := NewHistoryService(historyStore, logger)

// Get recent executions
history, err := historySvc.GetExecutionHistory(ctx, &HistoryQuery{
    WorkflowName: "deploy-app",
    Limit: 10,
})

// Get aggregate statistics
stats, err := historySvc.GetExecutionStats(ctx, "deploy-app")
fmt.Printf("Success rate: %.1f%%\n", stats.SuccessRate*100)

## Manage Plugins

pluginSvc := NewPluginService(manager, stateStore, logger)

// Discover available plugins
plugins, err := pluginSvc.DiscoverPlugins(ctx)

// Enable plugin for use
if err := pluginSvc.EnablePlugin(ctx, "my-plugin"); err != nil {
    log.Fatalf("failed to enable plugin: %v", err)
}

## Expand Workflow Template

templateSvc := NewTemplateService(templateRepo, logger)

// Expand template reference
steps, err := templateSvc.ExpandTemplate(ctx, &workflow.WorkflowTemplateRef{
    Template: "deploy-steps",
    With: map[string]any{
        "environment": "staging",
    },
})

## Collect Missing Inputs

inputSvc := NewInputCollectionService(collector, logger)

// Prompt user for undefined inputs
inputs, err := inputSvc.CollectInputs(ctx, workflow, providedInputs)

Design Principles

## Dependency Injection

All services use constructor injection:

  • Port interfaces injected via NewXxxService constructors
  • No global state or singletons
  • Testable with mock implementations
  • Optional dependencies via SetXxx methods

## Orchestration, Not Business Logic

Services coordinate but don't contain rules:

  • Validation logic lives in domain entities (Workflow.Validate)
  • State transitions handled by domain (ExecutionContext)
  • Services delegate to domain methods, don't duplicate logic

## Error Propagation

Services wrap errors with context:

  • Use fmt.Errorf with %w for error chains
  • Preserve underlying error for error.Is checks
  • Add operation context for debugging

Example:

if err := s.repo.Load(ctx, name); err != nil {
    return fmt.Errorf("load workflow %s: %w", name, err)
}

## Context Propagation

All operations accept context.Context:

  • Enables cancellation and timeout control
  • Graceful shutdown of long-running operations
  • Pass context to all port calls

## Thread Safety

Services are stateless and thread-safe:

  • No mutable state fields (all dependencies are ports)
  • Multiple goroutines can call service methods concurrently
  • State mutations delegated to thread-safe ExecutionContext
  • internal/domain/workflow: Core entities orchestrated by services
  • internal/domain/ports: Port interfaces implemented by infrastructure
  • internal/infrastructure: Concrete port implementations
  • internal/interfaces/cli: CLI commands that invoke services

Index

Constants

View Source
const (

	// AWFPackNameKey is the awfMap key used to inject pack context into path resolution.
	// When set, resolveLocalOverGlobal and resolveCommandAWFPaths apply 3-tier pack resolution.
	AWFPackNameKey = "pack_name"
)

ErrInternal is the fallback ErrorCode when MapError encounters an unrecognized variant. Signals a mapping gap: add a case to MapError when a new StructuredError code is introduced.

View Source
const MaxPromptBytes = 1 << 20 // 1 MiB

MaxPromptBytes is the upper bound on prompt size accepted by the ACP server. A 1 MiB cap prevents tokenizePrompt from consuming unbounded memory on a malicious or misbehaving editor client that sends an arbitrarily large prompt (m-4 fix). Exported as the single source of truth: the infrastructure agent adapter (internal/infrastructure/acp) reuses it for its own pre-handler guard so the two layers cannot drift apart.

Variables

View Source
var (
	// ErrCircularWorkflowCall is returned when a circular sub-workflow call is detected.
	ErrCircularWorkflowCall = errors.New("circular workflow call detected")

	// ErrMaxNestingExceeded is returned when sub-workflow nesting depth exceeds the maximum allowed.
	ErrMaxNestingExceeded = errors.New("maximum sub-workflow nesting depth exceeded")

	// ErrSubWorkflowNotFound is returned when a referenced sub-workflow does not exist.
	ErrSubWorkflowNotFound = errors.New("sub-workflow not found")
)

Sub-workflow execution errors.

View Source
var ErrExecutionNotFound = errors.New("execution not found")

Resume continues an interrupted workflow execution from where it left off. It loads persisted state, validates resumability, merges input overrides, and continues execution from the resolved fromStep while skipping completed steps. fromStep may be "current", "previous", or a literal step name present in States. ErrExecutionNotFound is returned by Resume when the requested workflow execution record does not exist in the state store (Load returned nil without error). Callers should test with errors.Is(err, ErrExecutionNotFound) rather than inspecting the error message string.

View Source
var ErrNoAgentRegistry = errors.New("agent registry not configured")

ErrNoAgentRegistry is returned when an agent step is executed without a configured registry.

View Source
var ErrNoOperationProvider = errors.New("operation provider not configured")

ErrNoOperationProvider is returned when an operation step is executed without a configured provider.

View Source
var ErrNoStepTypeProvider = errors.New("step type provider not configured")

ErrNoStepTypeProvider is returned when a custom step type is executed without a configured provider.

View Source
var ErrPluginDisabled = errors.New("plugin is disabled")

ErrPluginDisabled indicates the plugin is disabled and cannot be loaded.

View Source
var ErrPluginNameEmpty = errors.New("plugin name cannot be empty")

ErrPluginNameEmpty indicates an empty plugin name was provided.

View Source
var ErrRecordNotFound = errors.New("execution record not found")

ErrRecordNotFound is returned by GetByID when no execution record matches the requested ID. Callers should test with errors.Is(err, ErrRecordNotFound).

View Source
var ErrUnknownPlugin = errors.New("unknown plugin")

ErrUnknownPlugin indicates the plugin name is not registered (builtin or external).

View Source
var ErrUnsupportedContentBlock = errors.New("unsupported content block")

ErrUnsupportedContentBlock is the sentinel error returned by flattenContentBlocks when the prompt contains a block type the agent does not handle (image, audio, resource). Callers test with errors.Is to distinguish unsupported-block failures from other errors.

Functions

func BuildRoleSystemPrompt added in v0.11.2

func BuildRoleSystemPrompt(
	ctx context.Context,
	repo ports.AgentRoleRepository,
	resolver interpolation.Resolver,
	step *workflow.Step,
	workflowDir string,
	intCtx *interpolation.Context,
) (string, error)

BuildRoleSystemPrompt resolves the agent role template, loads role content from the repository, and composes the final system prompt.

func ComposeSystemPrompt added in v0.11.2

func ComposeSystemPrompt(roleContent, inline string) string

ComposeSystemPrompt concatenates role content and an inline system_prompt. Composition order: role + "\n\n" + inline. Empty parts are omitted.

func DecodeFromACP added in v0.11.2

func DecodeFromACP(s string) string

DecodeFromACP converts an ACP "pack:workflow" identifier to canonical "pack/workflow" form.

The decoding replaces the first ":" with "/" to recover the canonical form. It is bijective only when the original canonical identifier contained no colons — see the package-level bijectivity constraint.

func DecodeFromMCP added in v0.11.2

func DecodeFromMCP(s string) string

DecodeFromMCP converts an MCP "pack_workflow" identifier to canonical "pack/workflow" form.

The decoding replaces the first "_" with "/" to recover the canonical form. It is bijective only when the original canonical identifier contained no underscores — see the package-level bijectivity constraint.

func Drain added in v0.11.2

func Drain(session ports.RunSession) error

Drain consumes all events from session until its Events channel closes, then returns session.Err(). Rendering is the caller's responsibility — Drain performs no output itself. This is the single shared consumer helper (FR-015); interfaces MUST NOT reimplement it.

Drain blocks forever if the session never closes. Use DrainContext when a deadline or cancellation signal is available.

func DrainContext added in v0.11.2

func DrainContext(ctx context.Context, session ports.RunSession) error

DrainContext consumes all events from session until its Events channel closes or ctx is cancelled (whichever comes first). When ctx is cancelled before the session closes, DrainContext returns ctx.Err(). When the session closes normally, it returns session.Err() (nil on success, the execution error on failure).

Use DrainContext in preference to Drain whenever a deadline or parent context is available; it prevents goroutine leaks when the workflow is slow or hung.

Drain is a thin wrapper around DrainContext with context.Background().

func EncodeForACP added in v0.11.2

func EncodeForACP(s string) string

EncodeForACP converts a canonical "pack/workflow" identifier to ACP "pack:workflow" form.

The encoding replaces every "/" with ":". It is bijective only when the canonical identifier contains no colons — see the package-level bijectivity constraint. Use ValidateAndEncodeForACP when encoding user-supplied identifiers.

func EncodeForMCP added in v0.11.2

func EncodeForMCP(s string) string

EncodeForMCP converts a canonical "pack/workflow" identifier to MCP "pack_workflow" form.

The encoding replaces every "/" with "_". It is bijective only when the canonical identifier contains no underscores — see the package-level bijectivity constraint. Use ValidateAndEncodeForMCP when encoding user-supplied identifiers.

func ExitCode added in v0.11.2

func ExitCode(code domainerrors.ErrorCode) int

ExitCode maps an ErrorCode to the process exit code for the category. Returns 0 for empty code, 1–4 per the error taxonomy in CLAUDE.md:

USER      → 1 (bad input, missing file)
WORKFLOW  → 2 (invalid state reference, cycle)
EXECUTION → 3 (command failed, timeout)
SYSTEM    → 4 (IO, permissions, internal unmapped)

Unknown categories return 4 (system/internal) rather than 1, so that unrecognized codes do not masquerade as user errors and are clearly distinguished from successful exit (0).

func FormatSkillContent added in v0.11.2

func FormatSkillContent(skill *workflow.Skill) string

FormatSkillContent wraps skill content in an agentskills.io <skill_content> XML block.

func MapError added in v0.11.2

func MapError(err error) domainerrors.ErrorCode

MapError extracts the canonical ErrorCode from a StructuredError. Returns empty ErrorCode for nil, ErrInternal for non-StructuredError types (fail-closed, D8).

func MergeInputs added in v0.11.2

func MergeInputs(configInputs, cliInputs map[string]any) map[string]any

MergeInputs returns configInputs merged with cliInputs. CLI wins on conflict. Neither input map is mutated.

func NewBuiltinOperationProvider added in v0.11.4

func NewBuiltinOperationProvider(logger ports.Logger, notifyConfig NotifyConfig) ports.OperationProvider

NewBuiltinOperationProvider exposes the same builtin schemas and configured notification defaults used during execution, without constructing execution, audit, history, or agent services. Construction performs no operation calls.

func ProjectEvent added in v0.11.2

func ProjectEvent(ev transcript.ExchangeEvent) (ports.Event, error)

ProjectEvent maps a transcript.ExchangeEvent to a ports.Event. Unknown event types fail closed to EventKindUnknown + non-fatal error (NFR-007). Pure function — no I/O, no state, no provider branching (D10).

func RenderFacadeEventsToACPSessionUpdate added in v0.11.2

func RenderFacadeEventsToACPSessionUpdate(events []ports.Event) []byte

RenderFacadeEventsToACPSessionUpdate projects a slice of facade events to the ACP session/update JSONL wire format using the SAME projection table that the live ACP dispatch path (projectFacadeEvents → emitFacadeEvent) emits through (facadeEventToUpdate).

It is the ACP analog of cli.RenderFacadeEventsToText, api.ProjectEventToSSEFrame, and tui.RenderEventsToTUIMsgs: the conformance suite (F108 T079 golden) calls it so the golden reflects the real projector rather than a test-only stub. Each projected event becomes one JSON object line carrying its session/update "kind" merged with the projected fields; events that do not project to an ACP notification (kind == "") are skipped, exactly as the live emitter skips them.

func ResolveAgentRole added in v0.11.2

func ResolveAgentRole(ctx context.Context, repo ports.AgentRoleRepository, ref, workflowDir string) (*workflow.AgentRole, error)

ResolveAgentRole resolves a role reference to an AgentRole. An empty ref is a no-op and returns (nil, nil). References containing path separators or starting with '.', '~', '/' are treated as paths; everything else is resolved by name through the repository.

func ResolveAndFormatSkills added in v0.11.2

func ResolveAndFormatSkills(
	ctx context.Context,
	repo ports.SkillRepository,
	refs []workflow.SkillReference,
	workflowDir string,
) (string, error)

ResolveAndFormatSkills resolves each SkillReference via repo and returns concatenated formatted content.

func SplitCallWorkflowName added in v0.11.2

func SplitCallWorkflowName(name string) (packName, workflowName string)

SplitCallWorkflowName splits a call_workflow target into pack and workflow components. Returns ("", name) for unnamespaced references, (pack, workflow) for namespaced ones. Note: duplicates parseWorkflowNamespace in internal/interfaces/cli/pack_resolver.go — cross-layer import (application→interfaces) is forbidden by go-arch-lint.

func ValidateAndEncodeForACP added in v0.11.2

func ValidateAndEncodeForACP(s string) (string, error)

ValidateAndEncodeForACP validates that the canonical identifier satisfies the ACP bijectivity constraint (no ":" characters) and then encodes it to ACP form.

Returns an error when the canonical identifier contains a colon, because the ACP encoding would not be reversible: EncodeForACP("a:b/c") == EncodeForACP("a/b:c"). Pack and workflow names MUST NOT contain colons when used over the ACP protocol.

func ValidateAndEncodeForMCP added in v0.11.2

func ValidateAndEncodeForMCP(s string) (string, error)

ValidateAndEncodeForMCP validates that the canonical identifier satisfies the MCP bijectivity constraint (no "_" characters) and then encodes it to MCP form.

Returns an error when the canonical identifier contains an underscore, because the MCP encoding would not be reversible: EncodeForMCP("a_b/c") == EncodeForMCP("a/b_c"). Pack and workflow names MUST NOT contain underscores when used over the MCP protocol.

Types

type ACPErrorKind added in v0.11.2

type ACPErrorKind int

ACPErrorKind classifies an ACP request-handler failure independently of any transport. The interfaces/cli layer maps each kind onto its JSON-RPC error code (see adaptACPHandler in the cli package), so the application layer never imports pkg/acpserver and the transport stays an interface-layer concern.

const (
	// ACPErrInvalidParams reports malformed params or a request the caller got
	// wrong (unknown session, prompt already in flight). Maps to JSON-RPC -32602.
	ACPErrInvalidParams ACPErrorKind = iota
	// ACPErrInternal reports a server-side failure (missing dependency, factory
	// error, corrupted session state). Maps to JSON-RPC -32603.
	ACPErrInternal
	// ACPErrMethodNotFound maps to JSON-RPC -32601. Reserved for handlers that
	// dispatch on a sub-method; unused today.
	ACPErrMethodNotFound
)

type ACPHandlerError added in v0.11.2

type ACPHandlerError struct {
	Kind    ACPErrorKind
	Message string
	// Data is optional machine-readable context (e.g. an ErrorCode string).
	// It is mapped to the JSON-RPC error object's "data" field at the interface boundary.
	Data any
}

ACPHandlerError is the transport-neutral error returned by ACPSessionService handlers. Kind selects the JSON-RPC code at the interface boundary; Message is the human-readable detail surfaced to the editor. Data carries machine-readable supplementary information (e.g. an error code) that the interface layer maps to the JSON-RPC error object's "data" field — keeping codes out of Message (C-3 fix).

func (*ACPHandlerError) Error added in v0.11.2

func (e *ACPHandlerError) Error() string

type ACPInputResponder added in v0.11.2

type ACPInputResponder interface {
	ports.UserInputReader
	Respond(text string)
	SetParkHooks(onPark, onUnpark func())
}

ACPInputResponder is the subset of the ACP input reader the session service drives: it satisfies ports.UserInputReader (for the workflow executor) and accepts responses routed from subsequent session/prompt turns. Declaring it as an interface keeps the application layer free of a direct dependency on internal/infrastructure/acp; the concrete *acp.ACPInputReader is injected by the interfaces/cli wiring layer.

SetParkHooks installs the OnPark/OnUnpark callbacks the reader fires around its blocking wait for user input. The session service wires them to bump ACPSession.ParkedTurnCount so a continuation prompt (arriving while a workflow goroutine is parked) is routed to Respond instead of starting a new run. This is the production seam that makes the parking branch in HandleSessionPrompt live (CRITIQUE-3); the contract is one OnUnpark per OnPark.

type ACPRunnerFactory added in v0.11.2

type ACPRunnerFactory func(sessionID string) (ACPInputResponder, *atomic.Bool, func(), ports.WorkflowFacade, error)

ACPRunnerFactory builds the per-session wiring for one ACP session. It returns the session's input reader (so continuation turns can route text to it), the streamed flag (set to true by the output writers/renderer when an emit succeeds), a cleanup that releases that session's resources, and the per-session facade (T075: one ports.WorkflowFacade per session, rooted at the session-scoped stateStore — the sole workflow execution entry point). Injected by the interfaces/cli wiring layer; nil in unit tests, where dispatch falls back to the service-level facade (SetFacade).

type ACPSession added in v0.11.2

type ACPSession struct {
	ID string
	// CWD is the working directory provided at session/new.
	// TODO(F102-v2): currently stored but not yet propagated to the workflow
	// runner as an interpolation variable. See ADR-018.
	CWD        string
	MCPServers map[string]MCPServerSpec

	InFlight atomic.Bool

	// ParkedTurnCount is atomic: the parked workflow goroutine increments it while a
	// prompt handler reads it (lock-free, mirroring InFlight). It is bumped via the
	// ACPInputReader park hooks wired in the interfaces layer, so a continuation prompt
	// routes to the parked reader instead of starting a new workflow.
	ParkedTurnCount atomic.Int32
	// contains filtered or unexported fields
}

ACPSession holds the per-session runtime state for an ACP server session.

type ACPSessionService added in v0.11.2

type ACPSessionService struct {
	// contains filtered or unexported fields
}

ACPSessionService owns the per-session state map and routes ACP method calls to the workflow facade and ConversationManager. Mirrors ConversationManager placement.

func NewACPSessionService added in v0.11.2

func NewACPSessionService(
	convMgr *ConversationManager,
	workflowRepo ports.WorkflowRepository,
	logger ports.Logger,
) *ACPSessionService

NewACPSessionService constructs an ACPSessionService. A nil logger is replaced with a no-op so the handlers never panic on a missing logger. Workflow execution is wired separately via SetFacade (service-level) and/or SetRunnerFactory (per-session).

func (*ACPSessionService) HandleSessionCancel added in v0.11.2

func (s *ACPSessionService) HandleSessionCancel(ctx context.Context, params json.RawMessage) (any, *ACPHandlerError)

HandleSessionCancel handles a session/cancel request. The transport-neutral *ACPHandlerError is mapped to the SDK request-error variant by the infrastructure acp.Agent adapter (via toACPError).

func (*ACPSessionService) HandleSessionNew added in v0.11.2

func (s *ACPSessionService) HandleSessionNew(ctx context.Context, params json.RawMessage) (any, *ACPHandlerError)

HandleSessionNew handles a session/new request. The transport-neutral *ACPHandlerError is mapped to the SDK request-error variant by the infrastructure acp.Agent adapter (via toACPError).

func (*ACPSessionService) HandleSessionPrompt added in v0.11.2

func (s *ACPSessionService) HandleSessionPrompt(ctx context.Context, params json.RawMessage) (any, *ACPHandlerError)

HandleSessionPrompt handles a session/prompt request. The transport-neutral *ACPHandlerError is mapped to the SDK request-error variant by the infrastructure acp.Agent adapter (via toACPError).

func (*ACPSessionService) SetFacade added in v0.11.2

func (s *ACPSessionService) SetFacade(f ports.WorkflowFacade)

SetFacade installs the pack-aware WorkflowFacade for Run/Respond delegation (T063, D36). When set, HandleSessionPrompt routes through facade.Run and RunSession.Respond instead of the legacy in-place runner. Optional; must be called during the single-threaded initialization sequence before Serve, like the other Set* wiring.

func (*ACPSessionService) SetRunnerFactory added in v0.11.2

func (s *ACPSessionService) SetRunnerFactory(f ACPRunnerFactory)

SetRunnerFactory installs a per-session wiring factory. When set, each session builds its own session-scoped wiring (input reader, output writers, renderer, and per-session facade) on first prompt. Optional: when unset, dispatch falls back to the service-level facade installed via SetFacade (the unit-test path).

func (*ACPSessionService) SetServerContext added in v0.11.2

func (s *ACPSessionService) SetServerContext(ctx context.Context)

SetServerContext installs the server-lifetime context used as the parent for every session-lifetime context (ACPSession.sessionCtx). Must be called before Serve starts (same single-threaded initialization contract as SetSessionUpdateEmitter and SetRunnerFactory). When not called, HandleSessionNew falls back to context.Background() so unit tests that omit wiring continue to work.

func (*ACPSessionService) SetSessionUpdateEmitter added in v0.11.2

func (s *ACPSessionService) SetSessionUpdateEmitter(e SessionUpdateEmitter)

SetSessionUpdateEmitter wires the session/update notification sink. Optional.

func (*ACPSessionService) SetWorkflowProvider added in v0.11.2

func (s *ACPSessionService) SetWorkflowProvider(p WorkflowProvider)

SetWorkflowProvider installs the pack-aware workflow lister/loader. When set, HandleSessionNew advertises every workflow returned by WorkflowProvider.ListAllWorkflows — including pack workflows — instead of the pack-blind workflowRepo.ListWithSource. Optional; must be called during the single-threaded initialization sequence before Serve, like the other Set* wiring.

func (*ACPSessionService) Shutdown added in v0.11.2

func (s *ACPSessionService) Shutdown()

Shutdown releases every session's per-session resources (the cleanup returned by the runner factory). Safe to call once at server shutdown; idempotent on sessions without a factory-built runner.

Ordering matters (CRITIQUE-1): the JSON-RPC server's wait group only covers request handlers, not the internal goroutines an ExecutionService spawns. So Shutdown must (1) set shutdownStarted to close the session-creation window (issue #8), (2) cancel every session's run context to interrupt in-flight workflows, (3) wait for each session's run goroutine to actually return (runWG), and only then (4) invoke the per-session cleanup — otherwise cleanup could close SQLite/temp

resources a workflow is still using.

type Adapter added in v0.11.2

type Adapter struct {
	// contains filtered or unexported fields
}

Adapter implements ports.WorkflowFacade by composing services without modifying them (D17). It is the sole caller of ports.Recorder.Subscribe — one Subscribe per RunSession (D15, SC-001).

Thread-safety: the optional edge fields (userInputReader, runRecorderFactory) are protected by mu. Set* methods acquire the write lock; getters used inside Run/Resume goroutines acquire the read lock. The core dependencies (workflowSvc, executionSvc, historySvc, resolver, recorder, registry) are set once at construction and are read-only thereafter — no lock needed.

func NewAdapter added in v0.11.2

func NewAdapter(
	workflowSvc *WorkflowService,
	executionSvc *ExecutionService,
	historySvc *HistoryService,
	resolver *Resolver,
	recorder ports.Recorder,
	registry *SessionRegistry,
) *Adapter

NewAdapter constructs a new Adapter. All parameters are required; optional edge fields are configured via the Set* methods after construction.

func (*Adapter) GetWorkflow added in v0.11.2

func (a *Adapter) GetWorkflow(ctx context.Context, identifier string) (*workflow.Workflow, error)

GetWorkflow loads a single workflow definition by its canonical identifier (ports.WorkflowReader). It delegates directly to the WorkflowService without going through the resolver, mirroring the pre-facade HTTP read path: the identifier is the already-recomposed "scope/name" the interface layer passes, and a missing workflow surfaces as the underlying StructuredError (ErrorCodeUserInputMissingFile) so callers can map it to 404.

func (*Adapter) History added in v0.11.2

func (a *Adapter) History(ctx context.Context, filter ports.HistoryFilter) ([]ports.RunRecord, error)

History returns past run records from the history service, mapped to facade records.

func (*Adapter) HistoryStats added in v0.11.2

func (a *Adapter) HistoryStats(ctx context.Context, filter ports.HistoryFilter) (*workflow.HistoryStats, error)

HistoryStats returns aggregate execution statistics for the given filter (ports.WorkflowReader). It mirrors History's filter mapping and returns the domain stats value verbatim so the HTTP response shape is unchanged.

func (*Adapter) List added in v0.11.2

func (a *Adapter) List(ctx context.Context) ([]ports.WorkflowSummary, error)

List returns every discoverable workflow (local, global, env, and packs) via the workflow service, mapped to lightweight summaries.

func (*Adapter) Resume added in v0.11.2

Resume re-drives a previously persisted, non-completed run identified by req.RunID (FR: US-resume). It loads the saved ExecutionContext, resumes from req.FromStep (or "current" when empty), applies req.InputOverrides when provided, and streams transcript events through the same RunSession machinery as Run. The resumed session is registered under the original runID so Status/SSE lookups resolve it.

An empty req.RunID returns ErrInvalidRequest so that callers can use errors.Is(err, ports.ErrInvalidRequest) without importing the domain.

func (*Adapter) Run added in v0.11.2

Run resolves the canonical identifier (FR-019), creates a RunSession, subscribes to the Recorder exactly once (D15, SC-001), drives execution, and projects transcript events into the session. A resolver rejection propagates synchronously without leaking a session; execution success/failure is reported via the terminal event.

An empty Identifier returns ErrInvalidRequest (wrapping the StructuredError) so that callers can use errors.Is(err, ports.ErrInvalidRequest) without importing the domain.

func (*Adapter) RunStep added in v0.11.2

func (a *Adapter) RunStep(ctx context.Context, req ports.RunStepRequest) (ports.StepResult, error)

RunStep executes a single workflow step in isolation by delegating to the underlying ExecutionService.ExecuteSingleStep. It maps the application-layer SingleStepResult to the facade ports.StepResult so callers never import the application package directly. Returns an error when the execution service is not configured (nil) or when ExecuteSingleStep itself reports a hard error (workflow/step not found, etc.).

func (*Adapter) SetRunRecorderFactory added in v0.11.2

func (a *Adapter) SetRunRecorderFactory(f func(runID string) (ports.Recorder, error))

SetRunRecorderFactory wires a per-run Recorder factory (HTTP/TUI). With it set, every Run/Resume creates its own recorder so live step/message events flow to the right session under concurrency. Without it the Adapter uses its single shared recorder (CLI/ACP).

func (*Adapter) SetUserInputReader added in v0.11.2

func (a *Adapter) SetUserInputReader(r ports.UserInputReader)

SetUserInputReader wires an optional user-input reader for interactive conversations.

func (*Adapter) Status added in v0.11.2

func (a *Adapter) Status(ctx context.Context, id string) (ports.RunStatus, error)

Status returns the current state of a run identified by id.

Priority: live session registry (always wins) → workflow-scoped history → history via GetByID. A history-unavailable error (nil store, missing record) degrades to ErrRunNotFound rather than panicking (Acceptance #35).

func (*Adapter) Validate added in v0.11.2

Validate resolves the canonical identifier (FR-019) and reports validity. A resolver rejection (e.g. empty identifier) propagates as the validation error.

func (*Adapter) ValidateDir added in v0.11.2

func (a *Adapter) ValidateDir(ctx context.Context, dir string, opts ports.ValidateOptions) ([]ports.FileValidationResult, error)

ValidateDir validates all .yaml workflow files found directly in dir (non-recursive). It implements ports.BatchValidator. A WorkflowService is constructed ad hoc against dir so that the validation runs on exactly the files in that directory, independent of the project-level workflowSvc whose repository is scoped to the whole project tree.

ValidateDir uses a dir-scoped ad-hoc WorkflowService with NO plugin validator provider wired; therefore opts.SkipPlugins is inherently satisfied and opts.ValidatorTimeout bounds nothing here. opts is accepted for BatchValidator interface symmetry and forward-compatibility.

Returns ErrInvalidRequest when dir is empty. Returns an OS-level error when dir cannot be read. Per-file validation failures are captured in FileValidationResult.Errors rather than bubbled as the function error so that the caller can display a full per-file summary.

func (*Adapter) ValidatePack added in v0.11.2

func (a *Adapter) ValidatePack(ctx context.Context, packName string, opts ports.ValidateOptions) ([]ports.FileValidationResult, error)

ValidatePack validates all .yaml workflow files inside the installed pack identified by packName. It implements ports.BatchValidator. Pack discovery uses the Adapter's PackDiscoverer (wired via the Resolver): workflows whose Name begins with "packName/" are loaded by name and validated, so the pack's canonical loader (including its repo path resolution) is exercised — not a raw filesystem scan.

Returns ErrInvalidRequest when packName is empty. Returns an error when the pack produces no workflows (unknown/uninstalled pack). Per-file failures are captured in FileValidationResult.Errors. opts controls the plugin-validator phase (SkipPlugins, ValidatorTimeout) and is forwarded to ValidateLoadedWorkflow for each workflow.

type ContextBuilderFunc

type ContextBuilderFunc func(execCtx *workflow.ExecutionContext) *interpolation.Context

ContextBuilderFunc builds an interpolation context from execution context.

type ConversationExecutor

type ConversationExecutor interface {
	ExecuteConversation(
		ctx context.Context,
		step *workflow.Step,
		config *workflow.ConversationConfig,
		execCtx *workflow.ExecutionContext,
		buildContext ContextBuilderFunc,
		workflowDir string,
		stdoutW, stderrW io.Writer,
	) (*workflow.ConversationResult, error)
}

ConversationExecutor defines the interface for executing multi-turn conversations. This interface allows for dependency injection and testing with mocks.

type ConversationManager

type ConversationManager struct {
	// contains filtered or unexported fields
}

ConversationManager orchestrates interactive user→agent→user conversations.

Each turn: resolve initial prompt → send to provider → stream response → read user input → repeat until empty input or context cancellation.

func NewConversationManager

func NewConversationManager(
	logger ports.Logger,
	resolver interpolation.Resolver,
	agentRegistry ports.AgentRegistry,
) *ConversationManager

func (*ConversationManager) ExecuteConversation

func (m *ConversationManager) ExecuteConversation(
	ctx context.Context,
	step *workflow.Step,
	config *workflow.ConversationConfig,
	execCtx *workflow.ExecutionContext,
	buildContext ContextBuilderFunc,
	workflowDir string,
	stdoutW, stderrW io.Writer,
) (*workflow.ConversationResult, error)

ExecuteConversation orchestrates an interactive user→agent→user conversation.

Flow:

  1. Initialize conversation state with system prompt (if provided)
  2. Execute initial user prompt to start conversation
  3. Read user input; empty input ends the conversation (StopReasonUserExit)
  4. Repeat until empty input or context cancellation

Parameters: - ctx: context for cancellation and timeout - step: agent step configuration with conversation settings - config: conversation configuration (continue_from) - execCtx: execution context with state and inputs - buildContext: function to build interpolation context for template resolution

Returns: - ConversationResult with final state, output, and stop reason - error if conversation execution fails

func (*ConversationManager) SetAgentRoleRepository added in v0.11.2

func (m *ConversationManager) SetAgentRoleRepository(repo ports.AgentRoleRepository)

SetAgentRoleRepository wires the optional agent role repository for role-based system prompt injection. When nil, steps that reference a role will return an error.

func (*ConversationManager) SetToolProxyService added in v0.11.2

func (m *ConversationManager) SetToolProxyService(svc *tools.ProxyService)

SetToolProxyService wires the optional F099 MCP tool proxy. When set and the step's MCPProxy is enabled, the proxy is started before the turn loop and torn down after. The temp config path is injected into options so provider injectors can reference it.

func (*ConversationManager) SetTurnEmitter added in v0.11.2

func (m *ConversationManager) SetTurnEmitter(fn func(ctx context.Context, ec *workflow.ExecutionContext, role workflow.TurnRole, provider, content string))

SetTurnEmitter wires the optional per-turn transcript emitter (see emitTurn).

func (*ConversationManager) SetUserInputReader added in v0.11.2

func (m *ConversationManager) SetUserInputReader(r ports.UserInputReader)

SetUserInputReader wires the optional user input reader for interactive conversations. When nil, conversations that require user input will return an error.

type DryRunExecutor

type DryRunExecutor struct {
	// contains filtered or unexported fields
}

DryRunExecutor walks through a workflow without executing commands. It produces an execution plan showing what would happen.

func NewDryRunExecutor

func NewDryRunExecutor(
	wfSvc *WorkflowService,
	resolver interpolation.Resolver,
	evaluator ports.ExpressionEvaluator,
	logger ports.Logger,
) *DryRunExecutor

func (*DryRunExecutor) Execute

func (e *DryRunExecutor) Execute(ctx context.Context, workflowName string, inputs map[string]any) (*workflow.DryRunPlan, error)

func (*DryRunExecutor) SetAWFPaths

func (e *DryRunExecutor) SetAWFPaths(paths map[string]string)

SetAWFPaths configures the AWF XDG directory paths for F063 template interpolation.

func (*DryRunExecutor) SetTemplateService

func (e *DryRunExecutor) SetTemplateService(svc *TemplateService)

type ExecutionService

type ExecutionService struct {
	// contains filtered or unexported fields
}

ExecutionService orchestrates workflow execution.

func NewExecutionService

func NewExecutionService(
	wfSvc *WorkflowService,
	executor ports.CommandExecutor,
	parallelExecutor ports.ParallelExecutor,
	store ports.StateStore,
	logger ports.Logger,
	resolver interpolation.Resolver,
	historySvc *HistoryService,
) *ExecutionService

NewExecutionService - historySvc can be nil to disable history recording.

func NewExecutionServiceWithEvaluator

func NewExecutionServiceWithEvaluator(
	wfSvc *WorkflowService,
	executor ports.CommandExecutor,
	parallelExecutor ports.ParallelExecutor,
	store ports.StateStore,
	logger ports.Logger,
	resolver interpolation.Resolver,
	historySvc *HistoryService,
	evaluator ports.ExpressionEvaluator,
) *ExecutionService

NewExecutionServiceWithEvaluator enables conditional transitions using the `when:` clause.

func (*ExecutionService) ExecuteSingleStep

func (s *ExecutionService) ExecuteSingleStep(
	ctx context.Context,
	workflowName string,
	stepName string,
	inputs map[string]any,
	mocks map[string]string,
) (*SingleStepResult, error)

ExecuteSingleStep executes a single step from a workflow in isolation. It bypasses the state machine and directly runs the specified step. Mocked states can be provided to simulate dependencies on previous steps. Supports pack workflows via namespace syntax (pack/workflow).

func (*ExecutionService) HandleMaxIterationFailure

func (s *ExecutionService) HandleMaxIterationFailure(
	ctx context.Context,
	result *workflow.LoopResult,
	step *workflow.Step,
	wf *workflow.Workflow,
	execCtx *workflow.ExecutionContext,
	loopState *workflow.StepState,
) (string, error)

HandleMaxIterationFailure handles the case when a loop hits max iterations with problematic patterns. If OnComplete is configured, completes successfully via that transition (e.g., retry patterns). Otherwise, treats as failure and returns error or transitions via OnFailure.

func (*ExecutionService) IsProblematicMaxIterationPattern

func (s *ExecutionService) IsProblematicMaxIterationPattern(
	result *workflow.LoopResult,
	step *workflow.Step,
	wf *workflow.Workflow,
) bool

IsProblematicMaxIterationPattern checks if a loop hit max iterations with problematic patterns. Returns true if the loop completed by hitting max iterations AND has step failures or complex nesting.

func (*ExecutionService) ListResumable

func (s *ExecutionService) ListResumable(ctx context.Context) ([]*workflow.ExecutionContext, error)

ListResumable returns all workflow executions that can be resumed. A workflow is resumable if its status is not completed.

func (*ExecutionService) Resume

func (s *ExecutionService) Resume(
	ctx context.Context,
	workflowID string,
	inputOverrides map[string]any,
	fromStep string,
) (*workflow.ExecutionContext, error)

func (*ExecutionService) RunWithWorkflowAndRunID added in v0.11.2

func (s *ExecutionService) RunWithWorkflowAndRunID(
	ctx context.Context,
	wf *workflow.Workflow,
	inputs map[string]any,
	runID string,
) (*workflow.ExecutionContext, error)

RunWithWorkflowAndRunID executes a pre-loaded workflow using runID as the execution's WorkflowID. This lets callers (e.g. the CLI run command) reuse the same identifier for the transcript filename (<run-id>.jsonl) and the run_id stamped on every emitted event, keeping the on-disk file and its contents correlatable (F106 SC-001).

func (*ExecutionService) SetAWFPaths

func (s *ExecutionService) SetAWFPaths(paths map[string]string)

SetAWFPaths configures the AWF XDG directory paths for F063 template interpolation. Keys: prompts_dir, config_dir, data_dir, workflows_dir, plugins_dir, scripts_dir.

func (*ExecutionService) SetAgentOutputNormalizer added in v0.11.2

func (s *ExecutionService) SetAgentOutputNormalizer(n ports.AgentOutputNormalizer)

SetAgentOutputNormalizer configures the normalizer that converts provider raw output into transcript ContentBlocks for F106 message.assistant emission. When nil, agent output is not normalized into the transcript (graceful no-op).

func (*ExecutionService) SetAgentRegistry

func (s *ExecutionService) SetAgentRegistry(registry ports.AgentRegistry)

SetAgentRegistry configures the agent registry for F039 agent step execution. When set, agent-type steps can execute AI provider operations.

func (*ExecutionService) SetAgentRoleRepository added in v0.11.2

func (s *ExecutionService) SetAgentRoleRepository(repo ports.AgentRoleRepository)

func (*ExecutionService) SetAuditTrailWriter

func (s *ExecutionService) SetAuditTrailWriter(w ports.AuditTrailWriter)

SetAuditTrailWriter configures the audit trail writer for F071 structured audit events. When nil, audit emission is skipped without error.

func (*ExecutionService) SetConversationManager

func (s *ExecutionService) SetConversationManager(mgr ConversationExecutor)

SetConversationManager configures the conversation manager for F033 multi-turn conversations. When set, agent-type steps with mode: conversation can execute managed conversations. Accepts ConversationExecutor interface to allow dependency injection and testing with mocks.

func (*ExecutionService) SetDisplayRendererFactory added in v0.11.2

func (s *ExecutionService) SetDisplayRendererFactory(f func(stepID string) display.EventRenderer)

SetDisplayRendererFactory installs a per-step renderer factory. When set, each agent step's context carries the renderer returned for that step name, enabling transports (e.g. ACP) to receive typed display events. A factory returning nil leaves the step using the default (inner-writer) rendering path.

func (*ExecutionService) SetEvaluator

func (s *ExecutionService) SetEvaluator(evaluator ports.ExpressionEvaluator)

SetEvaluator configures the expression evaluator for conditional transitions. When set, enables evaluation of "when" clauses in workflow transitions.

func (*ExecutionService) SetEventPublisher added in v0.11.2

func (s *ExecutionService) SetEventPublisher(p ports.EventPublisher)

SetEventPublisher configures the event publisher for workflow lifecycle event emission.

func (*ExecutionService) SetOperationProvider

func (s *ExecutionService) SetOperationProvider(provider ports.OperationProvider)

SetOperationProvider configures the plugin operation provider for F021. When set, operation-type steps can execute plugin-provided operations.

func (*ExecutionService) SetOutputWriters

func (s *ExecutionService) SetOutputWriters(stdout, stderr io.Writer)

SetOutputWriters configures streaming output writers.

func (*ExecutionService) SetPackWorkflowLoader added in v0.11.2

func (s *ExecutionService) SetPackWorkflowLoader(loader PackWorkflowLoader)

SetPackWorkflowLoader configures the pack workflow loader for C072 namespaced call_workflow resolution. When set, namespaced call_workflow references (e.g. "pack/workflow") route through this loader. When nil, namespaced references return an error (backward compatible for unnamespaced workflows).

func (*ExecutionService) SetPluginService

func (s *ExecutionService) SetPluginService(svc *PluginService)

SetPluginService configures the plugin service for disabled-plugin detection. When set, executePluginOperation checks if the plugin is disabled before lookup. When nil, the check is skipped (backward compatible).

func (*ExecutionService) SetRecorder added in v0.11.2

func (s *ExecutionService) SetRecorder(r ports.Recorder)

SetRecorder configures the transcript recorder for F106 canonical exchange transcript. When nil, transcript emission is skipped without error.

func (*ExecutionService) SetRecorderFactory added in v0.11.2

func (s *ExecutionService) SetRecorderFactory(f ports.RecorderFactory)

SetRecorderFactory configures the factory used to create child recorders for call_workflow sub-runs. When nil, child transcript recording is skipped.

func (*ExecutionService) SetSkillRepository added in v0.11.2

func (s *ExecutionService) SetSkillRepository(repo ports.SkillRepository)

func (*ExecutionService) SetStepTypeProvider added in v0.5.0

func (s *ExecutionService) SetStepTypeProvider(provider ports.StepTypeProvider)

SetStepTypeProvider configures the plugin step type provider for C069 custom step type execution. When set, unknown step types are delegated to the provider via ExecuteStep. When nil, unknown step types fall through to the default command executor (backward compatible).

func (*ExecutionService) SetTemplateService

func (s *ExecutionService) SetTemplateService(svc *TemplateService)

SetTemplateService configures the template service for expanding template references.

func (*ExecutionService) SetToolProxyService added in v0.11.2

func (s *ExecutionService) SetToolProxyService(svc *tools.ProxyService)

SetToolProxyService configures the MCP tool proxy for F099 per-step proxy lifecycle. Must be called after SetAgentRegistry and before SetConversationManager. When nil, proxy behavior is skipped and existing flows are unaffected.

func (*ExecutionService) SetTracer added in v0.11.2

func (s *ExecutionService) SetTracer(tracer ports.Tracer)

func (*ExecutionService) SetTranscriptDir added in v0.11.2

func (s *ExecutionService) SetTranscriptDir(dir string)

SetTranscriptDir configures the directory where transcript files are written. Derived from the same config as the parent recorder's path.

type ExecutionSetup added in v0.11.2

type ExecutionSetup struct {
	// contains filtered or unexported fields
}

ExecutionSetup centralizes ExecutionService wiring. It is the single authoritative place where all Set*() calls on ExecutionService are performed, so both CLI runWorkflow and TUI buildBridge share an identical service configuration.

Architecture note: this type lives in the application layer but imports concrete infrastructure packages. This is an accepted pragmatic trade-off: pushing all provider construction into callers would replicate the buildProviders logic across every entry point, defeating the purpose of this centralized builder.

func NewExecutionSetup added in v0.11.2

func NewExecutionSetup(
	repo ports.WorkflowRepository,
	stateStore ports.StateStore,
	shellExecutor ports.CommandExecutor,
	logger ports.Logger,
	opts ...SetupOption,
) *ExecutionSetup

NewExecutionSetup creates an ExecutionSetup with the required core dependencies. Optional behavior is configured through SetupOption functional options.

func (*ExecutionSetup) Build added in v0.11.2

Build constructs and wires all services according to the configured options. The returned SetupResult.Cleanup must be deferred by the caller.

type HistoryService

type HistoryService struct {
	// contains filtered or unexported fields
}

HistoryService provides business logic for workflow execution history.

func NewHistoryService

func NewHistoryService(store ports.HistoryStore, logger ports.Logger) *HistoryService

NewHistoryService constructs a HistoryService backed by the given store and logger. Either dependency may be nil; nil-store calls degrade gracefully.

func (*HistoryService) GetByID added in v0.11.2

GetByID returns the execution record with the given ID. Returns (nil, nil) when the store is not configured (degraded mode). Returns ErrRecordNotFound when no record matches. The HistoryStore port does not expose an ID-scoped lookup, so this method performs a full List scan; the O(N) cost is centralized here so callers do not duplicate the scan logic.

func (*HistoryService) GetStats

GetStats returns aggregated execution statistics for the given filter. Returns (nil, nil) when the store is not configured (degraded mode).

func (*HistoryService) IsEnabled added in v0.11.5

func (s *HistoryService) IsEnabled() bool

func (*HistoryService) List

List returns execution records matching the given filter. Returns an error when the store is not configured so callers can distinguish "no records" from "store unavailable".

func (*HistoryService) Record

func (s *HistoryService) Record(ctx context.Context, record *workflow.ExecutionRecord) error

Record persists a single execution record to the history store. Returns nil without error when the store is not configured (degraded mode).

type HookExecutor

type HookExecutor struct {
	// contains filtered or unexported fields
}

HookExecutor executes workflow and step hooks.

func NewHookExecutor

func NewHookExecutor(
	executor ports.CommandExecutor,
	logger ports.Logger,
	resolver interpolation.Resolver,
) *HookExecutor

func (*HookExecutor) ExecuteHooks

func (h *HookExecutor) ExecuteHooks(
	ctx context.Context,
	hook workflow.Hook,
	intCtx *interpolation.Context,
	failOnError bool,
) error

ExecuteHooks executes a list of hook actions sequentially. If failOnError is false, errors are logged but execution continues. If failOnError is true, execution stops on first error.

type InputCollectionService

type InputCollectionService struct {
	// contains filtered or unexported fields
}

InputCollectionService coordinates interactive collection of missing workflow inputs. This service detects which required inputs are missing from command-line arguments and delegates to the InputCollector port for user interaction.

Key responsibilities:

  • Detect missing required inputs by comparing workflow definition with provided values
  • Coordinate input collection via InputCollector port
  • Merge collected inputs with provided inputs
  • Handle optional inputs with default values

Usage:

service := NewInputCollectionService(collector, logger)
allInputs, err := service.CollectMissingInputs(workflow, providedInputs)
if err != nil {
    return fmt.Errorf("input collection failed: %w", err)
}

func NewInputCollectionService

func NewInputCollectionService(
	collector ports.InputCollector,
	logger ports.Logger,
) *InputCollectionService

NewInputCollectionService creates a new input collection service.

func (*InputCollectionService) CollectMissingInputs

func (s *InputCollectionService) CollectMissingInputs(
	ctx context.Context,
	wf *workflow.Workflow,
	providedInputs map[string]any,
) (map[string]any, error)

CollectMissingInputs detects missing required inputs and prompts the user interactively.

Logic:

  • Iterates through workflow.Inputs
  • For each required input not in providedInputs: prompt user and collect value
  • For each optional input not in providedInputs: prompt user (can skip with Enter)
  • Returns merged map containing both provided and collected inputs

Parameters:

  • ctx: Context for cancellation (e.g., Ctrl+C via signal)
  • wf: Workflow definition containing input specifications
  • providedInputs: Input values already provided via command-line flags

Returns:

  • Complete input map (provided + collected)
  • Error if collection fails or user cancels

type InputSpec added in v0.11.2

type InputSpec struct {
	Name        string `json:"name"`
	Type        string `json:"type"`
	Description string `json:"description,omitempty"`
}

InputSpec describes a single input parameter for a workflow slash command.

type InteractiveExecutor

type InteractiveExecutor struct {
	// contains filtered or unexported fields
}

InteractiveExecutor executes workflows in step-by-step interactive mode. It pauses before each step, prompts for user action, and displays results.

func NewInteractiveExecutor

func NewInteractiveExecutor(
	wfSvc *WorkflowService,
	executor ports.CommandExecutor,
	parallelExecutor ports.ParallelExecutor,
	store ports.StateStore,
	logger ports.Logger,
	resolver interpolation.Resolver,
	evaluator ports.ExpressionEvaluator,
	prompt ports.InteractivePrompt,
) *InteractiveExecutor

NewInteractiveExecutor creates a new interactive executor.

func (*InteractiveExecutor) HandleExecutionError

func (e *InteractiveExecutor) HandleExecutionError(
	ctx context.Context,
	step *workflow.Step,
	state *workflow.StepState,
	execErr error,
	intCtx *interpolation.Context,
) (string, error)

HandleExecutionError handles the case where command execution returns an error. It records the failure state, executes post-hooks, and determines the next step based on ContinueOnError or OnFailure configuration.

func (*InteractiveExecutor) HandleNonZeroExit

func (e *InteractiveExecutor) HandleNonZeroExit(
	ctx context.Context,
	step *workflow.Step,
	state *workflow.StepState,
	result *ports.CommandResult,
	intCtx *interpolation.Context,
) (string, error)

HandleNonZeroExit handles the case where command execution succeeds but returns non-zero exit code. It records the failure state, executes post-hooks, and determines the next step based on ContinueOnError or OnFailure configuration.

func (*InteractiveExecutor) HandleSuccess

func (e *InteractiveExecutor) HandleSuccess(
	ctx context.Context,
	step *workflow.Step,
	state *workflow.StepState,
	intCtx *interpolation.Context,
) (string, error)

HandleSuccess handles the case where command execution succeeds with zero exit code. It records the success state, executes post-hooks, and determines the next step based on transitions or legacy OnSuccess configuration.

func (*InteractiveExecutor) Run

func (e *InteractiveExecutor) Run(ctx context.Context, workflowName string, inputs map[string]any) (*workflow.ExecutionContext, error)

Run executes the workflow in interactive mode. It returns the final execution context and any error.

func (*InteractiveExecutor) SetAWFPaths

func (e *InteractiveExecutor) SetAWFPaths(paths map[string]string)

SetAWFPaths configures the AWF XDG directory paths for template interpolation. Keys: prompts_dir, config_dir, data_dir, workflows_dir, plugins_dir, scripts_dir.

func (*InteractiveExecutor) SetBreakpoints

func (e *InteractiveExecutor) SetBreakpoints(breakpoints []string)

SetBreakpoints sets specific steps to pause at. If breakpoints is nil or empty, all steps will pause.

func (*InteractiveExecutor) SetOutputWriters

func (e *InteractiveExecutor) SetOutputWriters(stdout, stderr io.Writer)

SetOutputWriters configures streaming output writers.

func (*InteractiveExecutor) SetTemplateService

func (e *InteractiveExecutor) SetTemplateService(svc *TemplateService)

SetTemplateService configures the template service for workflow expansion.

type LimitResult

type LimitResult struct {
	Output     string // Truncated or full output
	Stderr     string // Truncated or full stderr
	OutputPath string // Path to temp file if streamed
	StderrPath string // Path to temp file if streamed
	Truncated  bool   // True if output was truncated
}

LimitResult contains the result of applying output limits.

type LoopExecutor

type LoopExecutor struct {
	// contains filtered or unexported fields
}

LoopExecutor executes for_each and while loop constructs.

func NewLoopExecutor

func NewLoopExecutor(
	logger ports.Logger,
	evaluator ports.ExpressionEvaluator,
	resolver interpolation.Resolver,
) *LoopExecutor

NewLoopExecutor creates a new LoopExecutor.

func (*LoopExecutor) BuildBodyStepIndices

func (e *LoopExecutor) BuildBodyStepIndices(body []string) (map[string]int, error)

BuildBodyStepIndices creates a map from step name to index in the body slice. Used by F048 to support transitions within loop bodies by enabling jump-to-index logic. Returns a map where keys are step names and values are their positions in the body array, or an error if duplicate step names are detected (to prevent silent configuration errors). F048 T004: Body Step Index Mapping

INTERNAL: This method is exported for testing purposes only.

func (*LoopExecutor) ExecuteForEach

func (e *LoopExecutor) ExecuteForEach(
	ctx context.Context,
	wf *workflow.Workflow,
	step *workflow.Step,
	execCtx *workflow.ExecutionContext,
	stepExecutor StepExecutorFunc,
	buildContext ContextBuilderFunc,
) (*workflow.LoopResult, error)

ExecuteForEach iterates over items and executes body steps for each.

func (*LoopExecutor) ExecuteWhile

func (e *LoopExecutor) ExecuteWhile(
	ctx context.Context,
	wf *workflow.Workflow,
	step *workflow.Step,
	execCtx *workflow.ExecutionContext,
	stepExecutor StepExecutorFunc,
	buildContext ContextBuilderFunc,
) (*workflow.LoopResult, error)

ExecuteWhile repeats body steps while condition is true.

func (*LoopExecutor) ParseItems

func (e *LoopExecutor) ParseItems(itemsStr string) ([]any, error)

ParseItems converts items string to slice. Used by ExecuteForEach to parse the items expression result. Supports JSON arrays and comma-separated values.

func (*LoopExecutor) PopLoopContext

func (e *LoopExecutor) PopLoopContext(execCtx *workflow.ExecutionContext) *workflow.LoopContext

PopLoopContext restores the parent loop context. Returns the popped context for inspection if needed. F043: Nested Loop Execution

func (*LoopExecutor) PushLoopContext

func (e *LoopExecutor) PushLoopContext(
	execCtx *workflow.ExecutionContext,
	item any,
	index int,
	first, last bool,
	length int,
)

PushLoopContext sets a new loop context, linking to existing as parent. This enables nested loops by preserving outer loop state. F043: Nested Loop Execution

func (*LoopExecutor) ResolveMaxIterations

func (e *LoopExecutor) ResolveMaxIterations(maxIterExpr string, ctx *interpolation.Context) (int, error)

ResolveMaxIterations resolves a dynamic max_iterations expression to an integer. It performs template interpolation first ({{var}} substitution), then evaluates any arithmetic expressions, and finally validates the result is within bounds. Returns error if the expression cannot be resolved, is not a valid integer, or the value is outside the allowed range (1-10000). F037: Dynamic Variable Interpolation in Loops

type MCPEnvVariable added in v0.11.2

type MCPEnvVariable struct {
	Name  string `json:"name"`
	Value string `json:"value"`
}

MCPEnvVariable mirrors one ACP McpServerStdio env entry. The ACP wire format serializes env vars as a JSON array of {name, value} objects, NOT a JSON object — so the field below MUST decode the array form. Decoding into a map[string]string fails json.Unmarshal for the whole session/new payload, which rejected every session/new that carried an MCP stdio server with environment variables (the mandatory transport — "All Agents MUST support stdio").

type MCPServerSpec added in v0.11.2

type MCPServerSpec struct {
	Name    string           `json:"name"`
	Command string           `json:"command"`
	Args    []string         `json:"args"`
	Env     []MCPEnvVariable `json:"env"`
}

MCPServerSpec is an editor-provided MCP server launch spec decoded from a session/new `mcpServers` array entry (ACP). Distinct from workflow.MCPProxyConfig (interception config).

type NotifyConfig added in v0.11.2

type NotifyConfig struct {
	DefaultBackend string
}

NotifyConfig provides notification backend configuration.

type OutputLimiter

type OutputLimiter struct {
	// contains filtered or unexported fields
}

OutputLimiter handles output size management for step execution. C019: Prevents OOM from unbounded StepState.Output/Stderr growth.

func NewOutputLimiter

func NewOutputLimiter(config workflow.OutputLimits) *OutputLimiter

NewOutputLimiter creates a new OutputLimiter with the given configuration.

func (*OutputLimiter) Apply

func (l *OutputLimiter) Apply(output, stderr string) (*LimitResult, error)

Apply applies output limits to the given output and stderr strings. Returns a LimitResult indicating what happened (truncation, streaming, or pass-through).

func (*OutputLimiter) ShouldLimit

func (l *OutputLimiter) ShouldLimit(output string) bool

ShouldLimit returns true if the output exceeds the configured limit.

func (*OutputLimiter) Truncate

func (l *OutputLimiter) Truncate(output string) string

Truncate truncates the output to the configured limit with a truncation marker.

type OutputStreamer

type OutputStreamer struct {
	// contains filtered or unexported fields
}

OutputStreamer handles streaming large outputs to temporary files. C019: Prevents OOM from unbounded StepState.Output/Stderr growth by streaming to disk.

func NewOutputStreamer

func NewOutputStreamer(config workflow.OutputLimits) *OutputStreamer

NewOutputStreamer creates a new OutputStreamer with the given configuration.

func (*OutputStreamer) StreamBoth

func (s *OutputStreamer) StreamBoth(output, stderr string) (outputPath, stderrPath string, err error)

StreamBoth streams both output and stderr if they exceed limits. Returns paths to temp files (empty if not streamed) and any error.

func (*OutputStreamer) StreamOutput

func (s *OutputStreamer) StreamOutput(content string) (string, error)

StreamOutput writes output to a temp file if it exceeds the configured limit. Returns the path to the temp file if streamed, or empty string if not streamed. Returns an error if temp file creation fails.

type OutputWriterPair added in v0.11.2

type OutputWriterPair struct {
	Stdout io.Writer
	Stderr io.Writer
}

OutputWriterPair holds stdout/stderr writers for streaming mode.

type PackWorkflowLoader added in v0.11.2

type PackWorkflowLoader func(ctx context.Context, packName, workflowName string) (*workflow.Workflow, string, error)

PackWorkflowLoader loads a workflow from an installed pack. Returns the loaded workflow, the resolved pack directory, and an error. Note: duplicates resolvePackWorkflow in internal/interfaces/cli/pack_resolver.go — cross-layer import (application→interfaces) is forbidden by go-arch-lint.

type ParallelExecutor

type ParallelExecutor struct {
	// contains filtered or unexported fields
}

ParallelExecutor executes parallel branches using errgroup with semaphore.

func NewParallelExecutor

func NewParallelExecutor(logger ports.Logger) *ParallelExecutor

NewParallelExecutor creates a new ParallelExecutor.

func (*ParallelExecutor) CheckBranchSuccess

func (e *ParallelExecutor) CheckBranchSuccess(
	branchResult *workflow.BranchResult,
	firstSuccess *bool,
	mu *sync.Mutex,
	successChan chan struct{},
	cancel context.CancelFunc,
)

CheckBranchSuccess checks if a branch succeeded and signals cancellation if it's the first success. Handles synchronization for success detection in any_succeed strategy.

NOTE: Exported temporarily for T008 testing. Will be made private after TDD cycle completes.

func (*ParallelExecutor) Execute

func (e *ParallelExecutor) Execute(
	ctx context.Context,
	wf *workflow.Workflow,
	branches []string,
	config workflow.ParallelConfig,
	execCtx *workflow.ExecutionContext,
	stepExecutor ports.StepExecutor,
) (*workflow.ParallelResult, error)

Execute runs multiple branches concurrently according to the given strategy.

func (*ParallelExecutor) RunBranchWithSemaphore

func (e *ParallelExecutor) RunBranchWithSemaphore(
	ctx context.Context,
	branch string,
	sem chan struct{},
	stepExecutor ports.StepExecutor,
	wf *workflow.Workflow,
	execCtx *workflow.ExecutionContext,
	result *workflow.ParallelResult,
	mu *sync.Mutex,
) (*workflow.BranchResult, error)

RunBranchWithSemaphore executes a single branch with semaphore control. It acquires the semaphore, executes the branch, and adds the result to the parallel result. Returns the branch result and any error encountered during execution.

NOTE: Exported temporarily for T007 testing. Will be made private after TDD cycle completes.

type PluginProviders added in v0.11.2

type PluginProviders struct {
	Operations ports.OperationProvider
	Validators ports.WorkflowValidatorProvider
	StepTypes  ports.StepTypeProvider
}

PluginProviders groups optional plugin-provided capabilities.

type PluginService

type PluginService struct {
	// contains filtered or unexported fields
}

PluginService orchestrates plugin lifecycle operations. It coordinates between the PluginManager (loading/init/shutdown) and PluginStateStore (enable/disable persistence).

func NewPluginService

func NewPluginService(
	manager ports.PluginManager,
	stateStore ports.PluginStateStore,
	logger ports.Logger,
) *PluginService

NewPluginService creates a new PluginService with injected dependencies.

func (*PluginService) DisablePlugin

func (s *PluginService) DisablePlugin(ctx context.Context, name string) error

DisablePlugin disables a plugin, shuts it down if running, and persists the state.

func (*PluginService) DiscoverPlugins

func (s *PluginService) DiscoverPlugins(ctx context.Context) ([]*pluginmodel.PluginInfo, error)

DiscoverPlugins scans the plugins directory and returns discovered plugins. It filters out disabled plugins based on the state store.

func (*PluginService) EnablePlugin

func (s *PluginService) EnablePlugin(ctx context.Context, name string) error

EnablePlugin enables a plugin and persists the state. Does not automatically load or initialize the plugin.

func (*PluginService) GetPlugin

func (s *PluginService) GetPlugin(name string) (*pluginmodel.PluginInfo, bool)

GetPlugin returns plugin info by name. Returns (nil, false) if plugin not found.

func (*PluginService) GetPluginConfig

func (s *PluginService) GetPluginConfig(name string) map[string]any

GetPluginConfig retrieves stored configuration for a plugin.

func (*PluginService) InitPlugin

func (s *PluginService) InitPlugin(ctx context.Context, name string) error

InitPlugin initializes a loaded plugin with stored configuration. The configuration is retrieved from the state store.

func (*PluginService) IsPluginEnabled

func (s *PluginService) IsPluginEnabled(name string) bool

IsPluginEnabled returns whether a plugin is enabled.

func (*PluginService) ListDisabledPlugins

func (s *PluginService) ListDisabledPlugins() []string

ListDisabledPlugins returns names of disabled plugins.

func (*PluginService) ListEnabledPlugins

func (s *PluginService) ListEnabledPlugins() []*pluginmodel.PluginInfo

ListEnabledPlugins returns only enabled plugins.

func (*PluginService) ListPlugins

func (s *PluginService) ListPlugins() []*pluginmodel.PluginInfo

ListPlugins returns all known plugins.

func (*PluginService) LoadAndInitPlugin

func (s *PluginService) LoadAndInitPlugin(ctx context.Context, name string) error

LoadAndInitPlugin loads and initializes a plugin in one operation. Convenience method for typical plugin startup.

func (*PluginService) LoadPlugin

func (s *PluginService) LoadPlugin(ctx context.Context, name string) error

LoadPlugin loads a single plugin by name. Returns an error if the plugin is disabled.

func (*PluginService) LoadState

func (s *PluginService) LoadState(ctx context.Context) error

LoadState loads plugin states from storage.

func (*PluginService) RegisterBuiltin

func (s *PluginService) RegisterBuiltin(name, description, version string, operations []string)

RegisterBuiltin registers a built-in operation provider as a synthesized PluginInfo entry. Must be called during initialization before any concurrent access.

func (*PluginService) SaveState

func (s *PluginService) SaveState(ctx context.Context) error

SaveState persists all plugin states to storage.

func (*PluginService) SetPluginConfig

func (s *PluginService) SetPluginConfig(ctx context.Context, name string, config map[string]any) error

SetPluginConfig stores configuration for a plugin.

func (*PluginService) ShutdownAll

func (s *PluginService) ShutdownAll(ctx context.Context) error

ShutdownAll gracefully stops all running plugins.

func (*PluginService) ShutdownPlugin

func (s *PluginService) ShutdownPlugin(ctx context.Context, name string) error

ShutdownPlugin gracefully stops a running plugin.

func (*PluginService) StartupEnabledPlugins

func (s *PluginService) StartupEnabledPlugins(ctx context.Context) error

StartupEnabledPlugins discovers, loads, and initializes all enabled plugins. Typically called at application startup.

type PluginStateChecker added in v0.11.2

type PluginStateChecker interface {
	IsPluginEnabled(name string) bool
}

PluginStateChecker abstracts plugin enable/disable state lookup.

type PromptResult added in v0.11.2

type PromptResult struct {
	StopReason string `json:"stopReason"`
}

PromptResult is the typed result envelope for session/prompt and session/cancel responses. Using a named struct instead of map[string]any prevents accidental key misspellings and makes the wire format explicit. The json tag preserves the camelCase ACP wire key. Exported so infrastructure adapters (e.g. acp.Agent) can type-assert without a JSON round-trip and receive a compile-time guarantee on the field name.

type Resolver added in v0.11.2

type Resolver struct {
	// contains filtered or unexported fields
}

Resolver consolidates pack-based and repository-based workflow resolution into a single canonical entry point for the application layer. The three prior implementations (cli/pack_resolver.go, tui/command.go:resolvePackWorkflow, subworkflow_executor.go:SplitCallWorkflowName) are replaced here; coexistence is preserved until T060–T063 migrate each interface.

func NewResolver added in v0.11.2

func NewResolver(packDiscoverer ports.PackDiscoverer, repo ports.WorkflowRepository) *Resolver

func (*Resolver) Resolve added in v0.11.2

func (r *Resolver) Resolve(ctx context.Context, identifier string) (*workflow.Workflow, error)

Resolve parses a canonical "pack/workflow" identifier and loads the corresponding workflow. Empty identifier and missing "/" segment return USER.FACADE.* structured errors (declared by T055).

type RunSession added in v0.11.2

type RunSession struct {
	// contains filtered or unexported fields
}

RunSession is the concrete implementation of ports.RunSession. The adapter (T058) owns the subscription goroutine and drives appendEvent. No goroutine is started here — see constraint in T057.

Concurrency contract for appendEvent / Close:

  • s.closed is set to true inside Close() while holding s.mu (write lock).
  • appendEvent() checks s.closed under s.mu (write lock) before any send. If closed, it returns without touching s.events.
  • The channel send in appendEvent() is performed while still holding s.mu, so it is serialized against the close(s.events) in Close().
  • Receivers (range s.Events()) never take s.mu, so holding s.mu for the non-blocking send cannot cause a deadlock.

func (*RunSession) CancelWithEvent added in v0.11.2

func (s *RunSession) CancelWithEvent(reason string) error

CancelWithEvent emits a terminal cancellation event before closing the session. It is used by interfaces that cancel a live facade run directly through the session instead of waiting for the execution goroutine to return.

func (*RunSession) Close added in v0.11.2

func (s *RunSession) Close() error

Close is idempotent via sync.Once. Cancels ctx and closes the events channel. Buffered events are NOT drained: a closed buffered channel still yields its buffered values to range readers, so all in-flight events remain visible.

If an onClose hook was registered (by the adapter for registry eviction, BUG #7), it is called synchronously inside the Once block after the channel is closed.

func (*RunSession) Err added in v0.11.2

func (s *RunSession) Err() error

func (*RunSession) Events added in v0.11.2

func (s *RunSession) Events() <-chan ports.Event

func (*RunSession) ID added in v0.11.2

func (s *RunSession) ID() string

func (*RunSession) ReplayFromSeq added in v0.11.2

func (s *RunSession) ReplayFromSeq(seq uint64) []ports.Event

ReplayFromSeq is the exported form of replayFromSeq consumed at the interface boundary — the SSE handler type-asserts this method on ports.RunSession to replay buffered events on a Last-Event-ID reconnect. Without it the assertion silently fails and replay is a no-op.

func (*RunSession) Respond added in v0.11.2

func (s *RunSession) Respond(r ports.InputResponse) error

Respond delivers a response to the input bridge consumer (T059). Non-blocking: if no consumer is parked, returns ErrDuplicateResponse (capacity=1 buffer full). Returns ErrSessionClosed without panicking if called after Close.

The closed flag is checked under a read lock before the select to give a deterministic ErrSessionClosed when the session is already closed. Without the lock-guarded pre-check, the three-branch select races between ctx.Done() and the empty respondCh send — both are immediately ready after Close(), so the scheduler could non-deterministically choose either branch.

func (*RunSession) StatusSnapshot added in v0.11.2

func (s *RunSession) StatusSnapshot() ports.RunStatus

StatusSnapshot derives a rich run status from the buffered event history WITHOUT consuming the live Events() channel: it scans the replay buffer under a read lock, so it never competes with the SSE/CLI/TUI consumer for events. Interfaces that need a point-in-time status (HTTP GET /executions/{id}, awf status) use this while the live stream stays owned by a single consumer.

Status starts at "running" (a tracked session is, by definition, underway) and is refined as the buffer is scanned in order:

  • EventRunStarted stamps StartedAt.
  • EventStepStarted records the step in stepIndex (observation order) and sets CurrentStep.
  • EventStepCompleted stamps the step's CompletedAt, clears CurrentStep, and increments Progress.Completed.
  • EventWorkflowFailed / EventWorkflowCompleted set the terminal Status and CompletedAt.

A closed session keeps its buffer, so a completed run still reports "completed" after Close(). When the recorder is a NopRecorder (HTTP/TUI facade) only the terminal event is buffered, so StartedAt/CurrentStep stay zero and the caller supplies StartedAt from its own tracking.

Inputs is populated from the session's stored inputs field (set once AFTER construction by setInputs, called by Adapter.Run immediately after newSession returns). It is nil when inputs were not supplied at run-start (Resume path, tests).

type SessionRegistry added in v0.11.2

type SessionRegistry struct {
	// contains filtered or unexported fields
}

SessionRegistry is an in-process registry of active RunSessions keyed by ID. D12: simple map + RWMutex; multi-viewer fan-out is out of scope (A4, spec line 20).

Sessions are stored as the ports.RunSession interface so that any facade implementation (the concrete *RunSession produced by the Adapter, or a test double such as facadetest.FakeSession) can be registered and resolved by ID. The interface storage also lets interface-layer adapters (e.g. the HTTP sessionLookup in api/server.go) hand back a ports.RunSession without an extra wrapping shim (R5).

func NewSessionRegistry added in v0.11.2

func NewSessionRegistry() *SessionRegistry

func (*SessionRegistry) Add added in v0.11.2

Add registers a session keyed by its own ID(). Returns ports.ErrSessionExists if the ID is already registered.

func (*SessionRegistry) Get added in v0.11.2

func (r *SessionRegistry) Get(id string) (ports.RunSession, bool)

func (*SessionRegistry) Len added in v0.11.2

func (r *SessionRegistry) Len() int

func (*SessionRegistry) Remove added in v0.11.2

func (r *SessionRegistry) Remove(id string)

type SessionUpdateEmitter added in v0.11.2

type SessionUpdateEmitter interface {
	EmitSessionUpdate(ctx context.Context, sessionID, kind string, fields map[string]any) error
}

SessionUpdateEmitter streams a session/update notification to the editor for the given session. The infrastructure acp.Emitter backs it with the SDK AgentSideConnection's SessionUpdate call (wired in interfaces/cli). It is optional: when unset the session service runs workflows without streaming lifecycle updates.

type SetupOption added in v0.11.2

type SetupOption func(*setupConfig)

SetupOption configures an ExecutionSetup.

func WithAgentRoleRepository added in v0.11.2

func WithAgentRoleRepository(repo ports.AgentRoleRepository) SetupOption

WithAgentRoleRepository injects an agent role repository for F098 role resolution.

func WithAuditWriter added in v0.11.2

func WithAuditWriter(w ports.AuditTrailWriter) SetupOption

WithAuditWriter configures an audit trail writer for execution events.

func WithDisplayRendererFactory added in v0.11.2

func WithDisplayRendererFactory(f func(stepID string) display.EventRenderer) SetupOption

WithDisplayRendererFactory installs a per-step display renderer factory on the ExecutionService (used by the ACP entry point to stream typed display events).

func WithEventPublisher added in v0.11.2

func WithEventPublisher(p ports.EventPublisher) SetupOption

WithEventPublisher injects an event publisher into the execution service.

func WithHistoryStore added in v0.11.2

func WithHistoryStore(s ports.HistoryStore) SetupOption

WithHistoryStore enables execution history recording. If the store also implements io.Closer, it will be closed by SetupResult.Cleanup.

func WithNotifyConfig added in v0.11.2

func WithNotifyConfig(cfg NotifyConfig) SetupOption

WithNotifyConfig configures notification backend defaults.

func WithOutputWriters added in v0.11.2

func WithOutputWriters(stdout, stderr io.Writer) SetupOption

WithOutputWriters configures streaming output writers for step execution.

func WithPackContext added in v0.11.2

func WithPackContext(name string, resolver PackWorkflowLoader) SetupOption

WithPackContext sets the pack name and its associated workflow loader. When packName is non-empty, pack-scoped XDG paths are used instead of the global paths.

func WithPluginProviders added in v0.11.2

func WithPluginProviders(p PluginProviders) SetupOption

WithPluginProviders injects plugin-provided operation, validator, and step-type extensions.

func WithPluginService added in v0.11.2

func WithPluginService(svc *PluginService) SetupOption

WithPluginService injects the plugin lifecycle manager into the execution service.

func WithPluginState added in v0.11.2

func WithPluginState(checker PluginStateChecker) SetupOption

WithPluginState configures a checker that gates individual built-in providers.

func WithRecorder added in v0.11.2

func WithRecorder(r ports.Recorder) SetupOption

WithRecorder configures a transcript recorder for F106 canonical exchange format.

func WithRecorderFactory added in v0.11.2

func WithRecorderFactory(f ports.RecorderFactory) SetupOption

WithRecorderFactory configures the factory used to create per-sub-run child recorders for F106 sub-workflow transcript linkage. The execution service needs this factory to open and link child transcript files.

func WithTemplatePaths added in v0.11.2

func WithTemplatePaths(paths []string) SetupOption

WithTemplatePaths registers additional YAML template search paths.

func WithToolProxy added in v0.11.2

func WithToolProxy(cliExec ports.CLIExecutor) SetupOption

WithToolProxy injects the CLIExecutor used to construct the MCP ToolProxyService (F099). The ProviderFactory is built internally so it can capture the composite OperationProvider constructed during Build (required to expose plugin tools alongside built-ins). When cliExec is nil, the proxy is not wired and existing flows are unaffected.

func WithTracer added in v0.11.2

func WithTracer(t ports.Tracer) SetupOption

WithTracer configures a distributed tracing implementation.

func WithTranscriptDir added in v0.11.2

func WithTranscriptDir(dir string) SetupOption

WithTranscriptDir configures the directory where child transcript files are written for F106 sub-workflow linkage. Paired with WithRecorderFactory.

func WithUserInputReader added in v0.11.2

func WithUserInputReader(r ports.UserInputReader) SetupOption

WithUserInputReader configures the source for interactive user input in conversations.

type SetupResult added in v0.11.2

type SetupResult struct {
	ExecService *ExecutionService
	WorkflowSvc *WorkflowService
	HistorySvc  *HistoryService
	// Cleanup releases resources allocated during Build (e.g. closes HistoryStore).
	// It is safe to call multiple times.
	Cleanup func()
}

SetupResult is returned by Build and bundles the fully wired services together with a Cleanup function that releases any resources acquired during construction.

type SingleStepResult

type SingleStepResult struct {
	StepName    string
	Output      string
	Stderr      string
	ExitCode    int
	Status      workflow.ExecutionStatus
	Error       string
	StartedAt   time.Time
	CompletedAt time.Time
}

SingleStepResult holds the result of executing a single step.

type StepExecutorFunc

type StepExecutorFunc func(ctx context.Context, stepName string, intCtx *interpolation.Context) (string, error)

StepExecutorFunc executes a step by name within the current loop context. Returns the next step name (if transition matched) and any error encountered. F048: Support transitions within loop body

type TemplateService

type TemplateService struct {
	// contains filtered or unexported fields
}

TemplateService handles template resolution and expansion.

func NewTemplateService

func NewTemplateService(
	repo ports.TemplateRepository,
	logger ports.Logger,
) *TemplateService

NewTemplateService creates a new template service.

func (*TemplateService) ApplyTemplateFields

func (s *TemplateService) ApplyTemplateFields(
	step *workflow.Step,
	templateStep *workflow.Step,
	params map[string]any,
) error

ApplyTemplateFields merges template fields into the workflow step. Step values take precedence over template values for most fields. Exported for testing during TDD RED phase (C005-T001).

func (*TemplateService) ExpandNestedTemplate

func (s *TemplateService) ExpandNestedTemplate(
	ctx context.Context,
	stepName string,
	templateStep *workflow.Step,
	visited map[string]bool,
) error

ExpandNestedTemplate recursively expands nested template references. Exported for testing during TDD RED phase (C005-T001).

func (*TemplateService) ExpandWorkflow

func (s *TemplateService) ExpandWorkflow(ctx context.Context, wf *workflow.Workflow) error

ExpandWorkflow resolves all template references in a workflow.

func (*TemplateService) SelectPrimaryStep

func (s *TemplateService) SelectPrimaryStep(tmpl *workflow.Template) (*workflow.Step, error)

SelectPrimaryStep determines which step to use from the template. Priority: step with same name as template > first step. Exported for testing during TDD RED phase (C005-T001).

func (*TemplateService) ValidateAndLoadTemplate

func (s *TemplateService) ValidateAndLoadTemplate(
	ctx context.Context,
	ref *workflow.WorkflowTemplateRef,
	visited map[string]bool,
) (*workflow.Template, error)

ValidateAndLoadTemplate checks for circular references and loads the template. Combines circular detection with template loading. Exported for testing during TDD RED phase (C005-T001). Note: Does not clean up visited map - caller is responsible for cleanup.

func (*TemplateService) ValidateTemplateRef

func (s *TemplateService) ValidateTemplateRef(ctx context.Context, ref *workflow.WorkflowTemplateRef) error

ValidateTemplateRef validates a template reference without expanding.

type WorkflowProvider added in v0.11.2

type WorkflowProvider interface {
	ListAllWorkflows(ctx context.Context) ([]workflow.WorkflowEntry, error)
	GetWorkflow(ctx context.Context, name string) (*workflow.Workflow, error)
}

WorkflowProvider lists and loads workflows from every configured source — including installed packs — by delegating to the application's pack-aware WorkflowService.

ACPSessionService depends on this narrow port (rather than the pack-blind ports.WorkflowRepository) so that pack workflows ("packName/workflowName") are advertised as ACP slash commands in available_commands_update and resolvable by name. This mirrors the CLI, TUI, and HTTP interfaces, all of which list via WorkflowService.ListAllWorkflows (which merges ports.PackDiscoverer results) and load via WorkflowService.GetWorkflow (which routes a "pack/workflow" name to PackDiscoverer.LoadWorkflow). *WorkflowService satisfies this interface. It is optional: when unset, HandleSessionNew falls back to the pack-blind workflowRepo path for callers that do not inject a provider (the legacy default).

type WorkflowService

type WorkflowService struct {
	// contains filtered or unexported fields
}

func NewWorkflowService

func NewWorkflowService(
	repo ports.WorkflowRepository,
	store ports.StateStore,
	executor ports.CommandExecutor,
	logger ports.Logger,
	validator ports.ExpressionValidator,
) *WorkflowService

func (*WorkflowService) GetWorkflow

func (s *WorkflowService) GetWorkflow(ctx context.Context, name string) (*workflow.Workflow, error)

func (*WorkflowService) LastValidationWarnings added in v0.11.2

func (s *WorkflowService) LastValidationWarnings() []workflow.ValidationError

LastValidationWarnings returns the structured ValidationError warnings from the most recent ValidateWorkflow call. Warnings do not fail validation but are surfaced here for callers that want to display or log them (e.g. UNSUPPORTED_PROVIDER). The slice is replaced on each ValidateWorkflow invocation; nil means no warnings.

func (*WorkflowService) ListAllWorkflows added in v0.11.2

func (s *WorkflowService) ListAllWorkflows(ctx context.Context) ([]workflow.WorkflowEntry, error)

func (*WorkflowService) SetAgentRegistry added in v0.11.4

func (s *WorkflowService) SetAgentRegistry(registry ports.AgentRegistry)

func (*WorkflowService) SetPackDiscoverer added in v0.11.2

func (s *WorkflowService) SetPackDiscoverer(d ports.PackDiscoverer)

func (*WorkflowService) SetPluginOperationProvider added in v0.11.2

func (s *WorkflowService) SetPluginOperationProvider(p ports.OperationProvider)

func (*WorkflowService) SetSkillRepository added in v0.11.2

func (s *WorkflowService) SetSkillRepository(repo ports.SkillRepository)

func (*WorkflowService) SetTemplateAnalyzer added in v0.11.2

func (s *WorkflowService) SetTemplateAnalyzer(a workflow.TemplateAnalyzer)

SetTemplateAnalyzer wires the analyzer used by the template-reference validation phase (forward references, unknown namespaces, {{error.*}} outside error hooks). It is an optional dependency: when no analyzer is wired, ValidateLoadedWorkflow skips that phase, preserving read-only-facade behavior for callers that only need the structural and expression-compilation checks.

func (*WorkflowService) SetUserInputReader added in v0.11.4

func (s *WorkflowService) SetUserInputReader(reader ports.UserInputReader)

func (*WorkflowService) SetValidatorProvider added in v0.5.0

func (s *WorkflowService) SetValidatorProvider(p ports.WorkflowValidatorProvider)

func (*WorkflowService) ValidateLoadedWorkflow added in v0.11.2

func (s *WorkflowService) ValidateLoadedWorkflow(ctx context.Context, wf *workflow.Workflow, name string, opts ports.ValidateOptions) error

ValidateLoadedWorkflow runs the full validation pipeline (domain state/expression validation, prompt files, plugin validators, MCP proxy) on an already-loaded workflow. It is shared by ValidateWorkflow (load-then-validate) and the WorkflowFacade adapter, which loads via the canonical-identifier Resolver and must not re-load by bare name. A nil validator skips only the expression-compilation step so a read-only facade without an expression validator wired still performs the remaining structural checks. opts controls the plugin-validator phase: SkipPlugins suppresses it entirely; ValidatorTimeout > 0 bounds it with a context deadline.

func (*WorkflowService) ValidateLoadedWorkflowWithInputs added in v0.11.4

func (s *WorkflowService) ValidateLoadedWorkflowWithInputs(ctx context.Context, wf *workflow.Workflow, name string, opts ports.ValidateOptions, inputs map[string]any) error

func (*WorkflowService) ValidateWorkflow

func (s *WorkflowService) ValidateWorkflow(ctx context.Context, name string) error

type WorkflowSlashCommand added in v0.11.2

type WorkflowSlashCommand struct {
	Name string `json:"name"`
	// Description is REQUIRED by the ACP AvailableCommand schema: strict clients (e.g. Zed's
	// serde parser) reject the entire availableCommands array when a command omits it, which
	// blanks the slash-command suggestion menu. It is therefore never omitempty and is always
	// populated with a non-empty fallback (see ensureCommandDescriptions).
	Description    string      `json:"description"`
	RequiredInputs []InputSpec `json:"requiredInputs,omitempty"`
	OptionalInputs []InputSpec `json:"optionalInputs,omitempty"`
}

WorkflowSlashCommand is the DTO emitted in available_commands_update. Built from ports.WorkflowInfo + workflow.Input definitions.

Directories

Path Synopsis
Package tools implements the application-layer MCP proxy infrastructure for F099: tool interception and routing in AI agent workflows.
Package tools implements the application-layer MCP proxy infrastructure for F099: tool interception and routing in AI agent workflows.

Jump to

Keyboard shortcuts

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