@trailstep/core 0.1.1 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +11 -0
- package/dist/index.d.ts +713 -177
- package/dist/index.js +6434 -2719
- package/dist/index.js.map +1 -1
- package/package.json +5 -5
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/contracts/failures/failure.ts","../src/agent-targeting/parse-trailstep-config/expand-agent-refs.ts","../src/agent-targeting/parse-trailstep-config/parse-utils.ts","../src/agent-targeting/parse-trailstep-config/parse-agent-targets.ts","../src/agent-targeting/parse-trailstep-config/parse-agent-mappings.ts","../src/agent-targeting/parse-trailstep-config/parse-custom-providers.ts","../src/agent-targeting/parse-trailstep-config/parse-settings.ts","../src/agent-targeting/parse-trailstep-config/parse-workflow-agent-mappings.ts","../src/known-cli-providers/providers/claude/claude-provider.ts","../src/known-cli-providers/envelopes/envelope.ts","../src/known-cli-providers/providers/prompt-file-reference.ts","../src/known-cli-providers/providers/codex/codex-provider.ts","../src/known-cli-providers/providers/gemini/gemini-provider.ts","../src/known-cli-providers/providers/pi/pi-provider.ts","../src/known-cli-providers/process/resolve-cli-command.ts","../src/known-cli-providers/registry/provider-registry.ts","../src/agent-targeting/parse-trailstep-config/validate-provider-references.ts","../src/agent-targeting/parse-trailstep-config/parse-trailstep-config.ts","../src/agent-targeting/resolve-agent-targets/resolve-agent-targets.ts","../src/runtime/artifacts/run-storage.ts","../src/runtime/run-context/run-context-storage.ts","../src/authoring/document/document.ts","../src/authoring/prompt-composition/prompt-composition.ts","../src/authoring/prompt-template/prompt-template.ts","../src/authoring/shape/json-schema.ts","../src/authoring/state/state.ts","../src/authoring/step/step-node.ts","../src/runtime/sub-prompts/run-sub-prompt.ts","../src/agent-execution/adapter-agent/run-adapter-agent-step/run-adapter-agent-step.ts","../src/agent-execution/dispatch-agent-step/dispatch-agent-step.ts","../src/runtime/artifacts/step-artifacts.ts","../src/runtime/events/create-run-event.ts","../src/agent-execution/interactive-agent/run-interactive-agent-command.ts","../src/runtime/interactive-session/interactive-session-protocol.ts","../src/agent-execution/custom-provider/render-custom-provider-args.ts","../src/agent-execution/working-agent/run-working-agent-command.ts","../src/agent-execution/working-agent/artifacts/resolve-step-agent-files.ts","../src/agent-execution/working-agent/prompts/build-working-agent-prompt.ts","../src/agent-execution/working-agent/targets/run-working-agent-target-attempt.ts","../src/agent-execution/working-agent/output/read-working-agent-output.ts","../src/agent-execution/working-agent/targets/custom-provider/build-working-agent-args.ts","../src/agent-execution/working-agent/targets/custom-provider/spawn-working-agent-process.ts","../src/agent-execution/working-agent/targets/custom-provider/run-custom-working-provider.ts","../src/agent-execution/working-agent/targets/registry-provider/run-registry-working-provider.ts","../src/agent-execution/working-agent/prompts/build-provider-working-prompt.ts","../src/agent-execution/working-agent/targets/registry-provider/repair-provider-output.ts","../src/agent-execution/working-agent/targets/target-failures.ts","../src/runtime/sub-prompts/sub-prompt-artifacts.ts","../src/runtime/failures/failure-like.ts","../src/runtime/sub-prompts/sub-prompt-failures.ts","../src/runtime/sub-prompts/sub-prompt-fingerprint.ts","../src/runtime/sub-prompts/sub-prompt-replay.ts","../src/authoring/step/sub-prompt.ts","../src/deprecations/deprecation-manifest.ts","../src/runtime/retry/latest-unresolved-failure.ts","../src/runtime/retry/retry-policy.ts","../src/runtime/run-workflow/run-workflow.ts","../src/runtime/failures/step-execution-failure.ts","../src/runtime/run-context/with-step-context.ts","../src/runtime/timeout/timeout-policy.ts","../src/runtime/interactive-session/default-interactive-output-shape.ts","../src/runtime/continuation/resolve-step-output-schema/resolve-step-output-schema.ts","../src/runtime/continuation/run-continuation/run-continuation.ts","../src/runtime/failures/workflow-failure.ts","../src/runtime/resume/replay-completed-steps/replay-completed-steps.ts","../src/runtime/resume/reattach-in-progress-step/reattach-in-progress-step.ts","../src/runtime/resume/replay-to-failed-step/replay-to-failed-step.ts","../src/runtime/retry/replay-to-retry-failure.ts","../src/runtime/run-context/create-run-context.ts","../src/runtime/run-workflow/initialize-run.ts","../src/runtime/run-workflow/trailstep-config-input.ts","../src/runtime/runs/run-summaries.ts"],"sourcesContent":["export interface Failure {\n readonly code: string;\n readonly message: string;\n readonly details?: unknown;\n}\n\nexport class TrailStepFailureError extends Error {\n readonly failure: Failure;\n\n constructor(failure: Failure) {\n super(failure.message);\n this.name = \"TrailStepFailureError\";\n this.failure = failure;\n }\n}\n\nexport function validationFailure(message: string, details?: unknown): Failure {\n return {\n code: \"validation_failed\",\n message,\n ...(details === undefined ? {} : { details }),\n };\n}\n","import { TrailStepFailureError } from \"../../contracts/failures/failure.js\";\nimport type {\n TrailStepAgentMappings,\n TrailStepAgentTarget,\n TrailStepSettings,\n} from \"../targeting.types.js\";\nimport type { RawTrailStepAgentMappings, RawTrailStepAgentTarget } from \"./parse-agent-targets.js\";\n\nexport function expandAgentRefs(options: {\n readonly agents: RawTrailStepAgentMappings;\n readonly workflows:\n | Readonly<\n Record<\n string,\n {\n readonly agents?: RawTrailStepAgentMappings;\n readonly settings?: TrailStepSettings;\n }\n >\n >\n | undefined;\n}): {\n readonly agents: TrailStepAgentMappings;\n readonly workflows:\n | Readonly<\n Record<\n string,\n {\n readonly agents?: TrailStepAgentMappings;\n readonly settings?: TrailStepSettings;\n }\n >\n >\n | undefined;\n} {\n const expandedAgents: Record<string, readonly TrailStepAgentTarget[]> = {};\n const memo = new Map<string, readonly TrailStepAgentTarget[]>();\n\n for (const name of Object.keys(options.agents)) {\n expandedAgents[name] = expandTopLevelAgent({\n name,\n agents: options.agents,\n memo,\n stack: [],\n rootRefPath: undefined,\n });\n }\n\n const expandedWorkflows =\n options.workflows === undefined\n ? undefined\n : Object.fromEntries(\n Object.entries(options.workflows).map(([workflowId, workflow]) => {\n const workflowAgents =\n workflow.agents === undefined\n ? undefined\n : Object.fromEntries(\n Object.entries(workflow.agents).map(([roleName, targets]) => [\n roleName,\n expandTargetArray({\n path: `workflows.${workflowId}.agents.${roleName}`,\n targets,\n agents: options.agents,\n memo,\n stack: [],\n rootRefPath: undefined,\n }),\n ]),\n );\n\n return [\n workflowId,\n {\n ...(workflowAgents === undefined ? {} : { agents: workflowAgents }),\n ...(workflow.settings === undefined ? {} : { settings: workflow.settings }),\n },\n ];\n }),\n );\n\n return { agents: expandedAgents, workflows: expandedWorkflows };\n}\n\nfunction expandTopLevelAgent(options: {\n readonly name: string;\n readonly agents: RawTrailStepAgentMappings;\n readonly memo: Map<string, readonly TrailStepAgentTarget[]>;\n readonly stack: readonly string[];\n readonly rootRefPath: string | undefined;\n}): readonly TrailStepAgentTarget[] {\n const memoized = options.memo.get(options.name);\n if (memoized !== undefined) {\n return memoized;\n }\n\n const targets = options.agents[options.name];\n if (targets === undefined) {\n throwUnknownRef(`agents.${options.name}`, options.name);\n }\n\n const expanded = expandTargetArray({\n path: `agents.${options.name}`,\n targets,\n agents: options.agents,\n memo: options.memo,\n stack: [...options.stack, options.name],\n rootRefPath: options.rootRefPath,\n });\n options.memo.set(options.name, expanded);\n return expanded;\n}\n\nfunction expandTargetArray(options: {\n readonly path: string;\n readonly targets: readonly RawTrailStepAgentTarget[];\n readonly agents: RawTrailStepAgentMappings;\n readonly memo: Map<string, readonly TrailStepAgentTarget[]>;\n readonly stack: readonly string[];\n readonly rootRefPath: string | undefined;\n}): readonly TrailStepAgentTarget[] {\n return options.targets.flatMap((target, index) => {\n if (\"provider\" in target) {\n return [target];\n }\n\n const refPath = `${options.path}[${index}].ref`;\n const referencedTargets = options.agents[target.ref];\n if (referencedTargets === undefined) {\n throwUnknownRef(refPath, target.ref);\n }\n\n const existingRefIndex = options.stack.indexOf(target.ref);\n if (existingRefIndex !== -1) {\n throwCycle(options.rootRefPath ?? refPath, [\n ...options.stack.slice(existingRefIndex),\n target.ref,\n ]);\n }\n\n const memoized = options.memo.get(target.ref);\n if (memoized !== undefined) {\n return memoized;\n }\n\n const expanded = expandTargetArray({\n path: `agents.${target.ref}`,\n targets: referencedTargets,\n agents: options.agents,\n memo: options.memo,\n stack: [...options.stack, target.ref],\n rootRefPath: options.rootRefPath ?? refPath,\n });\n options.memo.set(target.ref, expanded);\n return expanded;\n });\n}\n\nfunction throwUnknownRef(path: string, ref: string): never {\n throw new TrailStepFailureError({\n code: \"agent_ref_unknown\",\n message: \"One or more agent refs reference an unknown top-level agent.\",\n details: { diagnostics: [`${path} references unknown agent '${ref}'.`] },\n });\n}\n\nfunction throwCycle(path: string, cycle: readonly string[]): never {\n throw new TrailStepFailureError({\n code: \"agent_ref_cycle\",\n message: \"One or more agent refs create a cycle.\",\n details: { diagnostics: [`${path} creates an agent ref cycle: ${cycle.join(\" -> \")}.`] },\n });\n}\n","import { TrailStepFailureError, validationFailure } from \"../../contracts/failures/failure.js\";\n\nexport function throwValidationFailure(diagnostics: readonly string[]): never {\n throw new TrailStepFailureError(\n validationFailure(\"Invalid .trailstep/config.json.\", { diagnostics }),\n );\n}\n\nexport function isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nexport function parseOptionalStringArray(\n path: string,\n value: unknown,\n diagnostics: string[],\n): readonly string[] | undefined {\n if (value === undefined) {\n return undefined;\n }\n\n if (!Array.isArray(value) || value.some((item) => typeof item !== \"string\")) {\n diagnostics.push(`${path} must be an array of strings when present.`);\n return undefined;\n }\n\n return value;\n}\n\nexport function parseOptionalStringRecord(\n path: string,\n value: unknown,\n diagnostics: string[],\n): Readonly<Record<string, string>> | undefined {\n if (value === undefined) {\n return undefined;\n }\n\n if (!isRecord(value)) {\n diagnostics.push(`${path} must be an object when present.`);\n return undefined;\n }\n\n const env: Record<string, string> = {};\n for (const [key, envValue] of Object.entries(value)) {\n if (typeof envValue !== \"string\") {\n diagnostics.push(`${path}.${key} must be a string.`);\n } else {\n env[key] = envValue;\n }\n }\n\n return env;\n}\n","import type {\n WorkflowAgentSize,\n WorkflowAgentThinking,\n} from \"../../contracts/agents/agent-role.types.js\";\nimport type { TrailStepAgentTarget } from \"../targeting.types.js\";\nimport { isRecord, parseOptionalStringArray } from \"./parse-utils.js\";\n\nexport interface RawTrailStepAgentRef {\n readonly ref: string;\n}\n\nexport type RawTrailStepAgentTarget = TrailStepAgentTarget | RawTrailStepAgentRef;\nexport type RawTrailStepAgentMappings = Readonly<\n Record<string, readonly RawTrailStepAgentTarget[]>\n>;\n\nexport const AGENT_SIZES = new Set<WorkflowAgentSize>([\n \"default\",\n \"tiny\",\n \"small\",\n \"medium\",\n \"large\",\n \"xl\",\n]);\n\nconst THINKING_LEVELS = new Set<WorkflowAgentThinking>([\"low\", \"medium\", \"high\", \"xhigh\", \"max\"]);\n\nexport function parseTargetArray(\n path: string,\n value: unknown,\n diagnostics: string[],\n): readonly RawTrailStepAgentTarget[] {\n if (!Array.isArray(value)) {\n diagnostics.push(`${path} must be an array.`);\n return [];\n }\n\n return value.flatMap((target, index): readonly RawTrailStepAgentTarget[] => {\n const targetPath = `${path}[${index}]`;\n\n if (!isRecord(target)) {\n diagnostics.push(`${targetPath} must be an object.`);\n return [];\n }\n\n if (target.ref !== undefined) {\n if (typeof target.ref !== \"string\" || target.ref.length === 0) {\n diagnostics.push(`${targetPath}.ref must be a non-empty string when present.`);\n return [];\n }\n\n return [{ ref: target.ref }];\n }\n\n if (typeof target.provider !== \"string\" || target.provider.length === 0) {\n diagnostics.push(`${targetPath}.provider must be a non-empty string.`);\n return [];\n }\n\n if (target.model !== undefined && typeof target.model !== \"string\") {\n diagnostics.push(`${targetPath}.model must be a string when present.`);\n }\n\n if (\n target.thinking !== undefined &&\n !THINKING_LEVELS.has(target.thinking as WorkflowAgentThinking)\n ) {\n diagnostics.push(\n `${targetPath}.thinking must be one of low, medium, high, xhigh, or max when present.`,\n );\n }\n\n const model =\n typeof target.model === \"string\" ? optionalNonEmptyString(target.model) : undefined;\n const args = parseOptionalStringArray(`${targetPath}.args`, target.args, diagnostics);\n\n return [\n {\n provider: target.provider,\n ...(model === undefined ? {} : { model }),\n ...(typeof target.thinking === \"string\" &&\n THINKING_LEVELS.has(target.thinking as WorkflowAgentThinking)\n ? { thinking: target.thinking as WorkflowAgentThinking }\n : {}),\n ...(args === undefined ? {} : { args }),\n },\n ];\n });\n}\n\nfunction optionalNonEmptyString(value: string): string | undefined {\n return value.trim().length === 0 ? undefined : value;\n}\n","import {\n parseTargetArray,\n type RawTrailStepAgentMappings,\n type RawTrailStepAgentTarget,\n} from \"./parse-agent-targets.js\";\nimport { isRecord } from \"./parse-utils.js\";\n\nexport function parseAgentMappings(\n path: string,\n value: unknown,\n diagnostics: string[],\n): RawTrailStepAgentMappings {\n const mappings: Record<string, readonly RawTrailStepAgentTarget[]> = {};\n\n if (!isRecord(value)) {\n diagnostics.push(`${path} must be an object.`);\n return mappings;\n }\n\n for (const [name, entry] of Object.entries(value)) {\n mappings[name] = parseTargetArray(`${path}.${name}`, entry, diagnostics);\n }\n\n return mappings;\n}\n","import type { WorkflowAgentThinking } from \"../../contracts/agents/agent-role.types.js\";\nimport type {\n TrailStepCustomProviderConfig,\n TrailStepCustomProviderModelOverrideSupport,\n TrailStepCustomProviderThinkingOverrideSupport,\n} from \"../targeting.types.js\";\nimport { isRecord, parseOptionalStringArray, parseOptionalStringRecord } from \"./parse-utils.js\";\n\nconst THINKING_LEVELS = new Set<WorkflowAgentThinking>([\"low\", \"medium\", \"high\", \"xhigh\", \"max\"]);\n\nexport function parseCustomProviders(\n value: unknown,\n diagnostics: string[],\n): Record<string, TrailStepCustomProviderConfig> {\n const customProviders: Record<string, TrailStepCustomProviderConfig> = {};\n\n if (!isRecord(value)) {\n diagnostics.push(\"customProviders must be an object.\");\n return customProviders;\n }\n\n for (const [name, providerConfig] of Object.entries(value)) {\n if (!isRecord(providerConfig)) {\n diagnostics.push(`customProviders.${name} must be an object.`);\n continue;\n }\n\n if (typeof providerConfig.binary !== \"string\" || providerConfig.binary.length === 0) {\n diagnostics.push(`customProviders.${name}.binary must be a non-empty string.`);\n continue;\n }\n\n const args = parseOptionalStringArray(\n `customProviders.${name}.args`,\n providerConfig.args,\n diagnostics,\n );\n const interactiveArgs = parseOptionalStringArray(\n `customProviders.${name}.interactiveArgs`,\n providerConfig.interactiveArgs,\n diagnostics,\n );\n const model = parseCustomProviderModelSupport(\n `customProviders.${name}.model`,\n providerConfig.model,\n diagnostics,\n );\n const thinking = parseCustomProviderThinkingSupport(\n `customProviders.${name}.thinking`,\n providerConfig.thinking,\n diagnostics,\n );\n const env = parseOptionalStringRecord(\n `customProviders.${name}.env`,\n providerConfig.env,\n diagnostics,\n );\n\n if (providerConfig.cwd !== undefined && typeof providerConfig.cwd !== \"string\") {\n diagnostics.push(`customProviders.${name}.cwd must be a string when present.`);\n }\n\n customProviders[name] = {\n binary: providerConfig.binary,\n ...(args === undefined ? {} : { args }),\n ...(interactiveArgs === undefined ? {} : { interactiveArgs }),\n ...(model === undefined ? {} : { model }),\n ...(thinking === undefined ? {} : { thinking }),\n ...(typeof providerConfig.cwd === \"string\" ? { cwd: providerConfig.cwd } : {}),\n ...(env === undefined ? {} : { env }),\n };\n }\n\n return customProviders;\n}\n\nfunction parseCustomProviderModelSupport(\n path: string,\n value: unknown,\n diagnostics: string[],\n): TrailStepCustomProviderModelOverrideSupport | undefined {\n if (value === undefined) {\n return undefined;\n }\n\n if (!isRecord(value) || typeof value.supported !== \"boolean\") {\n diagnostics.push(`${path} must be an object with a boolean supported field when present.`);\n return undefined;\n }\n\n if (!value.supported) {\n return { supported: false };\n }\n\n if (value.flag !== undefined && (typeof value.flag !== \"string\" || value.flag.length === 0)) {\n diagnostics.push(`${path}.flag must be a non-empty string when present.`);\n return undefined;\n }\n\n return {\n supported: true,\n ...(typeof value.flag === \"string\" ? { flag: value.flag } : {}),\n };\n}\n\nfunction parseCustomProviderThinkingSupport(\n path: string,\n value: unknown,\n diagnostics: string[],\n): TrailStepCustomProviderThinkingOverrideSupport | undefined {\n if (value === undefined) {\n return undefined;\n }\n\n if (!isRecord(value) || typeof value.supported !== \"boolean\") {\n diagnostics.push(`${path} must be an object with a boolean supported field when present.`);\n return undefined;\n }\n\n if (!value.supported) {\n if (value.levels !== undefined && (!Array.isArray(value.levels) || value.levels.length > 0)) {\n diagnostics.push(`${path}.levels must be an empty array when thinking support is disabled.`);\n return undefined;\n }\n\n return value.levels === undefined ? { supported: false } : { supported: false, levels: [] };\n }\n\n if (value.flag !== undefined && (typeof value.flag !== \"string\" || value.flag.length === 0)) {\n diagnostics.push(`${path}.flag must be a non-empty string when present.`);\n return undefined;\n }\n\n if (!Array.isArray(value.levels) || value.levels.length === 0) {\n diagnostics.push(`${path}.levels must be a non-empty array of supported thinking levels.`);\n return undefined;\n }\n\n const levels: WorkflowAgentThinking[] = [];\n for (const [index, level] of value.levels.entries()) {\n if (typeof level !== \"string\" || !THINKING_LEVELS.has(level as WorkflowAgentThinking)) {\n diagnostics.push(`${path}.levels[${index}] must be one of low, medium, high, xhigh, or max.`);\n continue;\n }\n levels.push(level as WorkflowAgentThinking);\n }\n\n if (levels.length !== value.levels.length) {\n return undefined;\n }\n\n return {\n supported: true,\n ...(typeof value.flag === \"string\" ? { flag: value.flag } : {}),\n levels,\n };\n}\n","import type { RetryPolicyInput } from \"../../runtime/retry/retry-policy.js\";\nimport type { TrailStepSettings } from \"../targeting.types.js\";\nimport { isRecord } from \"./parse-utils.js\";\n\nexport function parseSettings(\n path: string,\n value: unknown,\n diagnostics: string[],\n): TrailStepSettings | undefined {\n if (value === undefined) {\n return undefined;\n }\n\n if (!isRecord(value)) {\n diagnostics.push(`${path} must be an object when present.`);\n return undefined;\n }\n\n const settings: Record<string, unknown> = { ...value };\n\n if (value.retry !== undefined) {\n if (!isRecord(value.retry)) {\n diagnostics.push(`${path}.retry must be an object when present.`);\n delete settings.retry;\n } else if (value.retry.maxAttempts === undefined) {\n delete settings.retry;\n } else {\n settings.retry = { maxAttempts: value.retry.maxAttempts } satisfies RetryPolicyInput;\n }\n }\n\n if (value.timeout !== undefined && typeof value.timeout !== \"number\") {\n diagnostics.push(`${path}.timeout must be a number when present.`);\n delete settings.timeout;\n }\n\n return settings;\n}\n","import type { TrailStepSettings } from \"../targeting.types.js\";\nimport { parseAgentMappings } from \"./parse-agent-mappings.js\";\nimport type { RawTrailStepAgentMappings } from \"./parse-agent-targets.js\";\nimport { parseSettings } from \"./parse-settings.js\";\nimport { isRecord } from \"./parse-utils.js\";\n\nexport interface RawTrailStepWorkflowConfig {\n readonly agents?: RawTrailStepAgentMappings;\n readonly settings?: TrailStepSettings;\n}\n\nexport function parseWorkflows(\n value: unknown,\n diagnostics: string[],\n): Record<string, RawTrailStepWorkflowConfig> | undefined {\n if (value === undefined) {\n return undefined;\n }\n\n const workflows: Record<string, RawTrailStepWorkflowConfig> = {};\n\n if (!isRecord(value)) {\n diagnostics.push(\"workflows must be an object when present.\");\n return workflows;\n }\n\n for (const [workflowId, workflow] of Object.entries(value)) {\n if (!isRecord(workflow)) {\n diagnostics.push(`workflows.${workflowId} must be an object.`);\n continue;\n }\n\n const agents =\n workflow.agents === undefined\n ? undefined\n : parseAgentMappings(`workflows.${workflowId}.agents`, workflow.agents, diagnostics);\n\n const settings = parseSettings(\n `workflows.${workflowId}.settings`,\n workflow.settings,\n diagnostics,\n );\n\n workflows[workflowId] = {\n ...(agents === undefined ? {} : { agents }),\n ...(settings === undefined ? {} : { settings }),\n };\n }\n\n return workflows;\n}\n","import { spawn } from \"node:child_process\";\nimport { writeFile } from \"node:fs/promises\";\nimport { performance } from \"node:perf_hooks\";\nimport { TrailStepFailureError } from \"../../../contracts/failures/failure.js\";\nimport type { PlainObject } from \"../../../contracts/shapes/shape.types.js\";\nimport type {\n InteractiveProcessResult,\n InteractiveProcessRunner,\n} from \"../../../runtime/run-workflow/run-workflow.types.js\";\nimport {\n extractEnvelopeMetadata,\n extractEnvelopeOutput,\n extractEnvelopeText,\n} from \"../../envelopes/envelope.js\";\nimport type {\n ProviderAdapter,\n ProviderInteractiveRequest,\n ProviderSpec,\n ProviderWorkingProcessResult,\n ProviderWorkingRepairRequest,\n ProviderWorkingRequest,\n ProviderWorkingRunner,\n} from \"../../registry/provider-registry.types.js\";\nimport { promptFileReference } from \"../prompt-file-reference.js\";\n\nconst CLAUDE_BINARY = \"claude\";\nconst CLAUDE_RESULT_FIELD = \"result\";\n\nconst CLAUDE_SPEC: ProviderSpec = {\n id: \"claude\",\n displayName: \"Claude\",\n model: { supported: true, flag: \"--model\" },\n thinking: {\n supported: true,\n flag: \"--effort\",\n levels: [\"low\", \"medium\", \"high\", \"xhigh\", \"max\"],\n },\n working: {\n command: CLAUDE_BINARY,\n prompt: { kind: \"prompt-file\", reference: \"at-prefixed-argument\" },\n baseArgs: [\n \"-p\",\n \"@{{promptFile}}\",\n \"--output-format\",\n \"json\",\n \"--dangerously-skip-permissions\",\n ],\n output: {\n style: \"stdout-json-envelope\",\n parsing: { resultField: CLAUDE_RESULT_FIELD },\n },\n repair: { supported: true, resumeFlag: \"--resume\", promptDelivery: \"stdin\" },\n },\n interactive: {\n supported: true,\n command: CLAUDE_BINARY,\n requiresSystemPromptFile: true,\n systemPromptFileFlag: \"--append-system-prompt-file\",\n modelFlag: \"--model\",\n permissionBypassFlag: \"--dangerously-skip-permissions\",\n },\n};\n\nasync function runWorking(\n request: ProviderWorkingRequest,\n runner: ProviderWorkingRunner = spawnClaudeCapturingStdout,\n): Promise<void> {\n const args = buildClaudeWorkingArgs(request);\n\n let result: ProviderWorkingProcessResult;\n const startedAt = performance.now();\n try {\n result = await runner({\n command: CLAUDE_BINARY,\n args,\n cwd: request.cwd,\n signal: request.signal,\n });\n } catch (error) {\n throw new TrailStepFailureError({\n code: \"agent_provider_spawn_error\",\n message: \"claude provider process could not be started.\",\n details: { cause: error instanceof Error ? error.message : String(error) },\n });\n }\n\n const harnessDurationMs = Math.max(0, Math.round(performance.now() - startedAt));\n\n if (result.exitCode !== 0) {\n throw new TrailStepFailureError({\n code: \"agent_provider_failed\",\n message: `claude provider process exited with code ${result.exitCode}.`,\n details: { exitCode: result.exitCode },\n });\n }\n\n await writeCapturedOutput({\n stdout: result.stdout,\n outputFile: request.outputFile,\n usageFile: request.usageFile,\n captureMode: request.captureMode,\n harnessDurationMs,\n context: \"working\",\n });\n}\n\n/**\n * A malformed final answer after a real agentic turn still has a resumable\n * session behind it — the model did whatever file edits/tests it did before\n * producing an unusable answer, and that work already happened. Re-running\n * the whole task on a fresh session would risk redoing or conflicting with\n * those side effects, so this asks the *same* session for a reformat-only\n * reply instead. `sessionId`/`rawResultText` are surfaced here (rather than\n * only on the success path) specifically so the caller can attempt that\n * repair; see `attemptProviderOutputRepair` in run-working-agent-command.ts.\n */\nfunction extractFailureContext(rawStdout: string): {\n readonly sessionId?: string;\n readonly rawResultText?: string;\n} {\n const metadata = extractEnvelopeMetadata(rawStdout, { harnessDurationMs: 0 });\n let rawResultText: string | undefined;\n try {\n rawResultText = extractEnvelopeText(rawStdout, { resultField: CLAUDE_RESULT_FIELD });\n } catch {\n rawResultText = undefined;\n }\n\n return {\n ...(metadata.sessionId === undefined ? {} : { sessionId: metadata.sessionId }),\n ...(rawResultText === undefined ? {} : { rawResultText }),\n };\n}\n\nasync function writeCapturedOutput(options: {\n readonly stdout: string;\n readonly outputFile: string;\n readonly usageFile?: string;\n readonly captureMode?: \"json\" | \"raw-text\";\n readonly harnessDurationMs: number;\n readonly context: \"working\" | \"repair\";\n}): Promise<void> {\n const label = options.context === \"repair\" ? \"repair \" : \"\";\n\n if (options.captureMode === \"raw-text\") {\n let text: string;\n try {\n text = extractEnvelopeText(options.stdout, { resultField: CLAUDE_RESULT_FIELD });\n } catch (error) {\n throw new TrailStepFailureError({\n code: \"agent_provider_output_invalid\",\n message: `claude provider ${label}stdout did not contain a usable result.`,\n details: {\n cause: error instanceof Error ? error.message : String(error),\n ...extractFailureContext(options.stdout),\n },\n });\n }\n\n await writeFile(options.outputFile, text, \"utf8\");\n } else {\n let output: PlainObject;\n try {\n output = extractEnvelopeOutput(options.stdout, { resultField: CLAUDE_RESULT_FIELD });\n } catch (error) {\n throw new TrailStepFailureError({\n code: \"agent_provider_output_invalid\",\n message: `claude provider ${label}stdout did not contain a usable JSON result.`,\n details: {\n cause: error instanceof Error ? error.message : String(error),\n ...extractFailureContext(options.stdout),\n },\n });\n }\n\n await writeFile(options.outputFile, `${JSON.stringify(output, null, 2)}\\n`, \"utf8\");\n }\n\n if (options.usageFile) {\n const metadata = extractEnvelopeMetadata(options.stdout, {\n harnessDurationMs: options.harnessDurationMs,\n });\n await writeFile(options.usageFile, `${JSON.stringify(metadata, null, 2)}\\n`, \"utf8\");\n }\n}\n\nasync function repairOutput(\n request: ProviderWorkingRepairRequest,\n runner: ProviderWorkingRunner = spawnClaudeCapturingStdout,\n): Promise<void> {\n const prompt = buildClaudeRepairPrompt(request);\n const args = buildClaudeRepairArgs(request);\n\n let result: ProviderWorkingProcessResult;\n const startedAt = performance.now();\n try {\n result = await runner({\n command: CLAUDE_BINARY,\n args,\n cwd: request.cwd,\n stdin: prompt,\n signal: request.signal,\n });\n } catch (error) {\n throw new TrailStepFailureError({\n code: \"agent_provider_spawn_error\",\n message: \"claude provider repair process could not be started.\",\n details: { cause: error instanceof Error ? error.message : String(error) },\n });\n }\n\n const harnessDurationMs = Math.max(0, Math.round(performance.now() - startedAt));\n\n if (result.exitCode !== 0) {\n throw new TrailStepFailureError({\n code: \"agent_provider_failed\",\n message: `claude provider repair process exited with code ${result.exitCode}.`,\n details: { exitCode: result.exitCode },\n });\n }\n\n await writeCapturedOutput({\n stdout: result.stdout,\n outputFile: request.outputFile,\n usageFile: request.usageFile,\n captureMode: request.captureMode,\n harnessDurationMs,\n context: \"repair\",\n });\n}\n\n// --resume reuses the failed turn's own session (full context, already-done\n// work included) rather than starting a fresh one; the prompt built by\n// buildClaudeRepairPrompt asks only for a reformatted final answer. The repair\n// prompt is still piped through stdin so the resume invocation receives fresh\n// reformat-only instructions without adding a second prompt file artifact.\nfunction buildClaudeRepairArgs(request: ProviderWorkingRepairRequest): string[] {\n const args = [\n \"--resume\",\n request.sessionId,\n \"-p\",\n \"--output-format\",\n \"json\",\n \"--dangerously-skip-permissions\",\n ];\n\n if (request.model) {\n args.push(\"--model\", request.model);\n }\n\n if (request.thinking) {\n args.push(\"--effort\", request.thinking);\n }\n\n return args;\n}\n\nfunction buildClaudeRepairPrompt(request: ProviderWorkingRepairRequest): string {\n if (request.captureMode === \"raw-text\") {\n return [\n \"# TrailStep output repair\",\n \"\",\n \"Your previous final answer in this session could not be used as-is.\",\n \"Do not redo the task or make any further changes - the work is already done.\",\n \"Reply with the document content only, as your entire final answer: no JSON wrapper, no surrounding commentary, no markdown fences unless they are literally part of the document content itself.\",\n \"\",\n \"## Your previous final answer\",\n \"\",\n request.rawResultText,\n \"\",\n ].join(\"\\n\");\n }\n\n return [\n \"# TrailStep output repair\",\n \"\",\n \"Your previous final answer in this session was not valid JSON matching the required schema.\",\n \"Do not redo the task, re-read files, or make any further changes - the work is already done.\",\n \"Reply with exactly one JSON object as your entire final answer: no prose, no markdown fences, no multiple JSON values.\",\n \"\",\n \"The JSON object must match this output schema:\",\n \"\",\n \"```json\",\n JSON.stringify(request.outputSchema, null, 2),\n \"```\",\n \"\",\n \"## Your previous final answer\",\n \"\",\n request.rawResultText,\n \"\",\n ].join(\"\\n\");\n}\n\n// The rendered prompt content is deliberately NOT appended here: Windows'\n// CreateProcess caps the whole argv command-line around 32,767 characters, so\n// a large rendered prompt would fail process creation outright. The tiny @file\n// reference lets the CLI load the full prompt from disk without expanding argv.\nfunction buildClaudeWorkingArgs(request: ProviderWorkingRequest): string[] {\n const args = [\n \"-p\",\n promptFileReference(request.promptFile),\n \"--output-format\",\n \"json\",\n \"--dangerously-skip-permissions\",\n ];\n\n if (request.model) {\n args.push(\"--model\", request.model);\n }\n\n if (request.thinking) {\n args.push(\"--effort\", request.thinking);\n }\n\n return args;\n}\n\nasync function runInteractive(\n request: ProviderInteractiveRequest,\n runner: InteractiveProcessRunner = spawnClaudeInteractive,\n): Promise<InteractiveProcessResult> {\n const args: string[] = [];\n\n if (request.model) {\n args.push(\"--model\", request.model);\n }\n\n if (request.permissionMode !== \"prompt\") {\n args.push(\"--dangerously-skip-permissions\");\n }\n\n if (!request.systemPromptFile) {\n throw new TrailStepFailureError({\n code: \"agent_provider_invalid_request\",\n message: \"claude provider's interactive mode requires systemPromptFile.\",\n });\n }\n\n args.push(\"--append-system-prompt-file\", request.systemPromptFile);\n\n return await runner({\n command: CLAUDE_BINARY,\n args,\n cwd: request.cwd,\n shell: false,\n stdio: \"inherit\",\n env: request.env,\n signal: request.signal,\n });\n}\n\nconst spawnClaudeCapturingStdout: ProviderWorkingRunner = async ({\n command,\n args,\n cwd,\n stdin,\n signal,\n}) => {\n return await new Promise((resolve, reject) => {\n const hasStdin = stdin !== undefined;\n const child = spawn(command, args, {\n cwd,\n shell: false,\n stdio: [hasStdin ? \"pipe\" : \"ignore\", \"pipe\", \"inherit\"],\n detached: process.platform !== \"win32\",\n });\n\n let stdout = \"\";\n child.stdout?.on(\"data\", (chunk: Buffer) => {\n stdout += chunk.toString();\n });\n\n child.stdin?.on(\"error\", reject);\n signal?.addEventListener(\"abort\", () => terminateChildProcessTree(child), { once: true });\n child.on(\"error\", reject);\n child.on(\"close\", (code) => resolve({ exitCode: code ?? 1, stdout }));\n\n if (hasStdin) {\n child.stdin?.end(stdin);\n }\n });\n};\n\nconst spawnClaudeInteractive: InteractiveProcessRunner = async ({\n command,\n args,\n cwd,\n env,\n signal,\n}) => {\n return await new Promise((resolve, reject) => {\n const child = spawn(command, args, {\n cwd,\n env,\n signal,\n detached: process.platform !== \"win32\",\n shell: false,\n stdio: \"inherit\",\n });\n\n signal?.addEventListener(\"abort\", () => terminateChildProcessTree(child), { once: true });\n child.on(\"error\", reject);\n child.on(\"close\", (code) => resolve({ exitCode: code ?? 1 }));\n });\n};\n\nfunction terminateChildProcessTree(child: ReturnType<typeof spawn>): void {\n if (!child.pid) {\n return;\n }\n\n if (process.platform === \"win32\") {\n spawn(\"taskkill\", [\"/PID\", String(child.pid), \"/T\", \"/F\"], { stdio: \"ignore\" }).on(\n \"error\",\n () => {\n child.kill();\n },\n );\n return;\n }\n\n try {\n process.kill(-child.pid, \"SIGTERM\");\n } catch {\n child.kill();\n }\n}\n\nexport const claudeProvider: ProviderAdapter = {\n id: \"claude\",\n spec: CLAUDE_SPEC,\n runWorking,\n repairOutput,\n runInteractive,\n};\n","import type { PlainObject } from \"../../contracts/shapes/shape.types.js\";\n\n/**\n * Extraction logic ported from the retired `claude-rpc-trailstep-agent.mjs` mock\n * wrapper's `extractTrailStepOutput`, parameterized by which envelope field holds\n * the provider's final text (e.g. `\"result\"` for `claude --output-format json`).\n *\n * Handles four shapes of vendor CLI stdout:\n * 1. A single JSON envelope object whose `resultField` holds the final text\n * (or is itself already the final JSON object).\n * 2. Streaming JSON-lines output, where the last line containing a usable\n * `resultField`/`content` wins.\n * 3. A `resultField` value that is itself a message-shaped object with a\n * `content` array of `{type, text}` blocks (confirmed empirically for\n * `pi --mode json`, whose per-event `\"message\"` field nests the final\n * answer inside `message.content[].text` rather than a flat string like\n * Claude's `\"result\"`) — all `type: \"text\"` blocks are concatenated, in\n * order, and the joined text is parsed the same way a flat string would be.\n * 4. Plain text that itself contains (or is) the JSON object.\n */\nexport interface EnvelopeOptions {\n readonly resultField: string;\n}\n\nexport interface EnvelopeMetadataOptions {\n readonly harnessDurationMs: number;\n}\n\nexport interface ClaudeEnvelopeMetadata {\n readonly usage?: PlainObject;\n readonly costUsd?: number;\n readonly durationMs?: number;\n readonly harnessDurationMs: number;\n readonly turns?: number;\n readonly sessionId?: string;\n}\n\nexport function extractEnvelopeMetadata(\n rawStdout: string,\n options: EnvelopeMetadataOptions,\n): ClaudeEnvelopeMetadata {\n const metadata: Record<string, unknown> = { harnessDurationMs: options.harnessDurationMs };\n const envelope = parseEnvelopeObject(rawStdout);\n\n if (envelope) {\n const usage = camelCaseUsage(envelope.usage);\n if (usage) {\n metadata.usage = usage;\n }\n\n if (typeof envelope.total_cost_usd === \"number\") {\n metadata.costUsd = envelope.total_cost_usd;\n }\n\n if (typeof envelope.duration_ms === \"number\") {\n metadata.durationMs = envelope.duration_ms;\n }\n\n if (typeof envelope.num_turns === \"number\") {\n metadata.turns = envelope.num_turns;\n }\n\n if (typeof envelope.session_id === \"string\") {\n metadata.sessionId = envelope.session_id;\n }\n }\n\n return metadata as unknown as ClaudeEnvelopeMetadata;\n}\n\nexport function extractEnvelopeOutput(rawStdout: string, options: EnvelopeOptions): PlainObject {\n const text = rawStdout.trim();\n if (!text) {\n throw new Error(\"Provider process returned empty stdout.\");\n }\n\n const parsedEnvelope = parseJson(text);\n if (isPlainObject(parsedEnvelope)) {\n if (parsedEnvelope.is_error === true) {\n throw new Error(\n `Provider reported an error: ${String(parsedEnvelope[options.resultField] ?? text)}`,\n );\n }\n\n const resolved = resolveFieldValue(parsedEnvelope[options.resultField]);\n if (resolved) {\n return resolved;\n }\n\n if (typeof parsedEnvelope.content === \"string\") {\n return parseObjectFromText(parsedEnvelope.content);\n }\n }\n\n const streamResult = parseLastJsonLineResult(text, options.resultField);\n if (streamResult) {\n return streamResult;\n }\n\n return parseObjectFromText(text);\n}\n\n/**\n * Text-only counterpart to `extractEnvelopeOutput`, for steps whose\n * `captureMode` is `\"raw-text\"` (see `Document.captureMode` in\n * `authoring/document/document.ts`): the agent's final answer is a plain-text\n * document, not JSON, so the `resultField` value must be taken verbatim\n * rather than JSON-parsed. Mirrors the same four documented stdout shapes as\n * `extractEnvelopeOutput` — single JSON envelope, JSON-lines transcript,\n * message-shaped `resultField` with a `content` block array, and plain text —\n * but never throws on non-JSON text; the raw text is always the answer.\n */\nexport function extractEnvelopeText(rawStdout: string, options: EnvelopeOptions): string {\n const text = rawStdout.trim();\n if (!text) {\n throw new Error(\"Provider process returned empty stdout.\");\n }\n\n const parsedEnvelope = parseJson(text);\n if (isPlainObject(parsedEnvelope)) {\n if (parsedEnvelope.is_error === true) {\n throw new Error(\n `Provider reported an error: ${String(parsedEnvelope[options.resultField] ?? text)}`,\n );\n }\n\n const resolved = resolveFieldText(parsedEnvelope[options.resultField]);\n if (resolved !== undefined) {\n return resolved;\n }\n\n if (typeof parsedEnvelope.content === \"string\") {\n return parsedEnvelope.content;\n }\n }\n\n const streamResult = parseLastJsonLineText(text, options.resultField);\n if (streamResult !== undefined) {\n return streamResult;\n }\n\n return text;\n}\n\nfunction parseLastJsonLineText(text: string, resultField: string): string | undefined {\n const lines = text\n .split(/\\r?\\n/u)\n .map((line) => line.trim())\n .filter(Boolean);\n\n for (const line of [...lines].reverse()) {\n const parsed = parseJson(line);\n if (!isPlainObject(parsed)) {\n continue;\n }\n\n const resolved = resolveFieldText(parsed[resultField]);\n if (resolved !== undefined) {\n return resolved;\n }\n\n if (typeof parsed.content === \"string\") {\n return parsed.content;\n }\n }\n\n return undefined;\n}\n\n/**\n * Text-only counterpart to `resolveFieldValue`: resolves a raw `resultField`\n * value into the final raw text, handling a plain string (verbatim) or a\n * message-shaped object carrying a `content` array of text blocks (Pi),\n * without ever attempting to JSON-parse the resolved text.\n */\nfunction resolveFieldText(fieldValue: unknown): string | undefined {\n if (typeof fieldValue === \"string\") {\n return fieldValue;\n }\n\n if (isPlainObject(fieldValue)) {\n return extractTextFromContentBlocks(fieldValue);\n }\n\n return undefined;\n}\n\nfunction parseLastJsonLineResult(text: string, resultField: string): PlainObject | undefined {\n const lines = text\n .split(/\\r?\\n/u)\n .map((line) => line.trim())\n .filter(Boolean);\n\n for (const line of [...lines].reverse()) {\n const parsed = parseJson(line);\n if (!isPlainObject(parsed)) {\n continue;\n }\n\n const resolved = resolveFieldValue(parsed[resultField]);\n if (resolved) {\n return resolved;\n }\n\n if (typeof parsed.content === \"string\") {\n return parseObjectFromText(parsed.content);\n }\n }\n\n return undefined;\n}\n\n/**\n * Resolves a raw `resultField` value into the final output object, handling\n * the three shapes that field's value can take across vendors: a JSON-text\n * string (Claude), an object that already is the final output (also legal for\n * Claude-style envelopes), or a message-shaped object carrying a `content`\n * array of text blocks (Pi). Returns `undefined` when `fieldValue` is absent\n * or is a plain object with no extractable text, so callers can fall through\n * to their next fallback instead of misreporting an unrelated object.\n */\nfunction resolveFieldValue(fieldValue: unknown): PlainObject | undefined {\n if (typeof fieldValue === \"string\") {\n return parseObjectFromText(fieldValue);\n }\n\n if (isPlainObject(fieldValue)) {\n const blockText = extractTextFromContentBlocks(fieldValue);\n if (blockText !== undefined) {\n return parseObjectFromText(blockText);\n }\n\n return fieldValue;\n }\n\n return undefined;\n}\n\n/**\n * Extracts and concatenates `text` from every `{type: \"text\", text: string}`\n * content block in `value.content`, if `value.content` is such an array.\n * Returns `undefined` when `value` has no `content` array to extract from, so\n * the caller can fall back to treating `value` itself as the output object.\n */\nfunction extractTextFromContentBlocks(value: PlainObject): string | undefined {\n const content = value.content;\n if (!Array.isArray(content)) {\n return undefined;\n }\n\n const textParts = content\n .filter(isPlainObject)\n .filter((block) => block.type === \"text\" && typeof block.text === \"string\")\n .map((block) => block.text as string);\n\n if (textParts.length === 0) {\n return undefined;\n }\n\n return textParts.join(\"\");\n}\n\nfunction parseObjectFromText(text: string): PlainObject {\n const parsed = parseJson(text.trim());\n if (isPlainObject(parsed)) {\n return parsed;\n }\n\n const firstBrace = text.indexOf(\"{\");\n const lastBrace = text.lastIndexOf(\"}\");\n if (firstBrace === -1 || lastBrace === -1 || lastBrace <= firstBrace) {\n throw new Error(`Provider response did not contain a JSON object: ${text}`);\n }\n\n const extracted = parseJson(text.slice(firstBrace, lastBrace + 1));\n if (!isPlainObject(extracted)) {\n throw new Error(\"Provider response JSON was not an object.\");\n }\n\n return extracted;\n}\n\nfunction parseEnvelopeObject(rawStdout: string): PlainObject | undefined {\n const text = rawStdout.trim();\n const parsed = parseJson(text);\n if (isPlainObject(parsed)) {\n return parsed;\n }\n\n const lines = text\n .split(/\\r?\\n/u)\n .map((line) => line.trim())\n .filter(Boolean);\n\n for (const line of [...lines].reverse()) {\n const parsedLine = parseJson(line);\n if (isPlainObject(parsedLine)) {\n return parsedLine;\n }\n }\n\n return undefined;\n}\n\nfunction camelCaseUsage(value: unknown): PlainObject | undefined {\n if (!isPlainObject(value)) {\n return undefined;\n }\n\n const usage: Record<string, unknown> = {};\n for (const [key, fieldValue] of Object.entries(value)) {\n if (typeof fieldValue === \"number\") {\n usage[snakeToCamel(key)] = fieldValue;\n }\n }\n\n return Object.keys(usage).length > 0 ? usage : undefined;\n}\n\nfunction snakeToCamel(value: string): string {\n return value.replace(/_([a-z])/gu, (_match, letter: string) => letter.toUpperCase());\n}\n\nfunction parseJson(text: string): unknown {\n try {\n return JSON.parse(text);\n } catch {\n return undefined;\n }\n}\n\nfunction isPlainObject(value: unknown): value is PlainObject {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n","/**\n * Most local coding-agent CLIs support an @file prompt reference in their\n * prompt argument. Passing the tiny reference instead of the rendered prompt\n * avoids OS argv-length ceilings (notably Windows\n * CreateProcess' ~32KB command line cap) while letting the CLI load the full\n * TrailStep prompt from disk.\n */\nexport function promptFileReference(promptFile: string): string {\n return `@${promptFile}`;\n}\n","import { spawn } from \"node:child_process\";\nimport { TrailStepFailureError } from \"../../../contracts/failures/failure.js\";\nimport type {\n InteractiveProcessResult,\n InteractiveProcessRunner,\n} from \"../../../runtime/run-workflow/run-workflow.types.js\";\nimport type {\n ProviderAdapter,\n ProviderInteractiveRequest,\n ProviderSpec,\n ProviderWorkingProcessResult,\n ProviderWorkingRequest,\n ProviderWorkingRunner,\n} from \"../../registry/provider-registry.types.js\";\nimport { promptFileReference } from \"../prompt-file-reference.js\";\n\nconst CODEX_BINARY = \"codex\";\n\n/**\n * Reasoning levels the installed `codex` CLI's `model_reasoning_effort` config\n * key accepts (see `codex exec --help` / the model catalog in\n * `~/.codex/models_cache.json`, which lists exactly `low`/`medium`/`high`/`xhigh`\n * for every current model). Codex has no `\"max\"` tier — unlike Claude's\n * `WorkflowAgentThinking`, which does. There is no faithful mapping from\n * TrailStep's `\"max\"` to a Codex reasoning level, so an unsupported tier is a\n * hard configuration error rather than a silent clamp/guess.\n */\nconst CODEX_THINKING_LEVELS = [\"low\", \"medium\", \"high\", \"xhigh\"] as const;\nconst SUPPORTED_CODEX_THINKING = new Set<string>(CODEX_THINKING_LEVELS);\n\nconst CODEX_SPEC: ProviderSpec = {\n id: \"codex\",\n displayName: \"Codex\",\n model: { supported: true, flag: \"-m\" },\n thinking: {\n supported: true,\n flag: \"-c model_reasoning_effort\",\n levels: CODEX_THINKING_LEVELS,\n },\n working: {\n command: CODEX_BINARY,\n prompt: { kind: \"prompt-file\", reference: \"at-prefixed-argument\" },\n baseArgs: [\n \"exec\",\n \"--dangerously-bypass-approvals-and-sandbox\",\n \"-o\",\n \"{{outputFile}}\",\n \"@{{promptFile}}\",\n ],\n output: { style: \"provider-output-file\" },\n },\n interactive: { supported: true, command: CODEX_BINARY, modelFlag: \"--model\" },\n};\n\n/**\n * Unlike `claudeProvider.runWorking`, this never captures or parses stdout\n * through `known-cli-providers/envelopes/envelope.ts`: `codex exec`'s `-o/--output-last-message\n * <file>` flag writes the agent's final message straight to `outputFile`\n * itself, so this reuses the same plain inherited-stdio process shape as the\n * `customProviders` fallback runner in `run-working-agent-command.ts` (stdio fully\n * inherited, only the exit code is observed).\n */\nasync function runWorking(\n request: ProviderWorkingRequest,\n runner: ProviderWorkingRunner = spawnCodexInheritingStdio,\n): Promise<void> {\n const args = buildCodexWorkingArgs(request);\n\n let result: ProviderWorkingProcessResult;\n try {\n result = await runner({\n command: CODEX_BINARY,\n args,\n cwd: request.cwd,\n signal: request.signal,\n });\n } catch (error) {\n throw new TrailStepFailureError({\n code: \"agent_provider_spawn_error\",\n message: \"codex provider process could not be started.\",\n details: { cause: error instanceof Error ? error.message : String(error) },\n });\n }\n\n if (result.exitCode !== 0) {\n throw new TrailStepFailureError({\n code: \"agent_provider_failed\",\n message: `codex provider process exited with code ${result.exitCode}.`,\n details: { exitCode: result.exitCode },\n });\n }\n\n // No file write here: `codex exec -o <outputFile>` already wrote\n // `request.outputFile` itself as a side effect of the process above.\n}\n\nfunction buildCodexWorkingArgs(request: ProviderWorkingRequest): string[] {\n const args = [\"exec\", \"--dangerously-bypass-approvals-and-sandbox\"];\n\n if (request.model) {\n args.push(\"-m\", request.model);\n }\n\n if (request.thinking) {\n if (!SUPPORTED_CODEX_THINKING.has(request.thinking)) {\n throw new TrailStepFailureError({\n code: \"agent_provider_thinking_unsupported\",\n message: `codex provider does not support thinking level '${request.thinking}'. Codex only supports low|medium|high|xhigh (no \"max\" tier).`,\n details: { thinking: request.thinking },\n });\n }\n\n args.push(\"-c\", `model_reasoning_effort=\"${request.thinking}\"`);\n }\n\n args.push(\"-o\", request.outputFile);\n args.push(promptFileReference(request.promptFile));\n return args;\n}\n\nasync function runInteractive(\n request: ProviderInteractiveRequest,\n runner: InteractiveProcessRunner = spawnCodexInteractive,\n): Promise<InteractiveProcessResult> {\n const args: string[] = [];\n\n if (request.model) {\n args.push(\"--model\", request.model);\n }\n\n args.push(\n request.systemPromptFile ? promptFileReference(request.systemPromptFile) : request.prompt,\n );\n\n return await runner({\n command: CODEX_BINARY,\n args,\n cwd: request.cwd,\n shell: false,\n stdio: \"inherit\",\n env: request.env,\n signal: request.signal,\n });\n}\n\nconst spawnCodexInheritingStdio: ProviderWorkingRunner = async ({ command, args, cwd, signal }) => {\n return await new Promise((resolve, reject) => {\n const child = spawn(command, args, {\n cwd,\n shell: false,\n stdio: \"inherit\",\n detached: process.platform !== \"win32\",\n });\n\n signal?.addEventListener(\"abort\", () => terminateChildProcessTree(child), { once: true });\n child.on(\"error\", reject);\n // `stdout` is unused: codex's `-o` flag writes `outputFile` directly, so\n // nothing here ever gets parsed as an envelope.\n child.on(\"close\", (code) => resolve({ exitCode: code ?? 1, stdout: \"\" }));\n });\n};\n\nconst spawnCodexInteractive: InteractiveProcessRunner = async ({\n command,\n args,\n cwd,\n env,\n signal,\n}) => {\n return await new Promise((resolve, reject) => {\n const child = spawn(command, args, {\n cwd,\n env,\n signal,\n detached: process.platform !== \"win32\",\n shell: false,\n stdio: \"inherit\",\n });\n\n signal?.addEventListener(\"abort\", () => terminateChildProcessTree(child), { once: true });\n child.on(\"error\", reject);\n child.on(\"close\", (code) => resolve({ exitCode: code ?? 1 }));\n });\n};\n\nfunction terminateChildProcessTree(child: ReturnType<typeof spawn>): void {\n if (!child.pid) {\n return;\n }\n\n if (process.platform === \"win32\") {\n spawn(\"taskkill\", [\"/PID\", String(child.pid), \"/T\", \"/F\"], { stdio: \"ignore\" }).on(\n \"error\",\n () => {\n child.kill();\n },\n );\n return;\n }\n\n try {\n process.kill(-child.pid, \"SIGTERM\");\n } catch {\n child.kill();\n }\n}\n\nexport const codexProvider: ProviderAdapter = {\n id: \"codex\",\n spec: CODEX_SPEC,\n runWorking,\n runInteractive,\n};\n","import { spawn } from \"node:child_process\";\nimport { writeFile } from \"node:fs/promises\";\nimport { TrailStepFailureError } from \"../../../contracts/failures/failure.js\";\nimport type { PlainObject } from \"../../../contracts/shapes/shape.types.js\";\nimport type {\n InteractiveProcessResult,\n InteractiveProcessRunner,\n} from \"../../../runtime/run-workflow/run-workflow.types.js\";\nimport { extractEnvelopeOutput, extractEnvelopeText } from \"../../envelopes/envelope.js\";\nimport type {\n ProviderAdapter,\n ProviderInteractiveRequest,\n ProviderSpec,\n ProviderWorkingProcessResult,\n ProviderWorkingRequest,\n ProviderWorkingRunner,\n} from \"../../registry/provider-registry.types.js\";\nimport { promptFileReference } from \"../prompt-file-reference.js\";\n\nconst GEMINI_BINARY = \"gemini\";\n\n/**\n * Gemini's envelope field, per the Gemini CLI's documented `--output-format json`\n * shape (`{\"response\": \"...\", \"stats\": {...}}`) — the vendor CLI itself is NOT\n * installed in this environment, so unlike Claude/Codex/Pi this field name is\n * doc-sourced only, not empirically confirmed against a real invocation. Treat\n * this adapter as the least-verified of the four until a real\n * `gemini --version` + end-to-end smoke test is run.\n */\nconst GEMINI_RESULT_FIELD = \"response\";\n\nconst GEMINI_SPEC: ProviderSpec = {\n id: \"gemini\",\n displayName: \"Gemini\",\n model: { supported: true, flag: \"-m\" },\n thinking: { supported: false },\n working: {\n command: GEMINI_BINARY,\n prompt: { kind: \"prompt-file\", reference: \"at-prefixed-argument\" },\n baseArgs: [\"-p\", \"@{{promptFile}}\", \"--yolo\", \"--output-format\", \"json\"],\n output: {\n style: \"stdout-json-envelope\",\n parsing: { resultField: GEMINI_RESULT_FIELD },\n },\n },\n interactive: { supported: true, command: GEMINI_BINARY, modelFlag: \"-m\" },\n};\n\nasync function runWorking(\n request: ProviderWorkingRequest,\n runner: ProviderWorkingRunner = spawnGeminiCapturingStdout,\n): Promise<void> {\n const args = buildGeminiWorkingArgs(request);\n\n let result: ProviderWorkingProcessResult;\n try {\n result = await runner({\n command: GEMINI_BINARY,\n args,\n cwd: request.cwd,\n signal: request.signal,\n });\n } catch (error) {\n throw new TrailStepFailureError({\n code: \"agent_provider_spawn_error\",\n message: \"gemini provider process could not be started.\",\n details: { cause: error instanceof Error ? error.message : String(error) },\n });\n }\n\n if (result.exitCode !== 0) {\n throw new TrailStepFailureError({\n code: \"agent_provider_failed\",\n message: `gemini provider process exited with code ${result.exitCode}.`,\n details: { exitCode: result.exitCode },\n });\n }\n\n if (request.captureMode === \"raw-text\") {\n let text: string;\n try {\n text = extractEnvelopeText(result.stdout, { resultField: GEMINI_RESULT_FIELD });\n } catch (error) {\n throw new TrailStepFailureError({\n code: \"agent_provider_output_invalid\",\n message: \"gemini provider stdout did not contain a usable result.\",\n details: { cause: error instanceof Error ? error.message : String(error) },\n });\n }\n\n await writeFile(request.outputFile, text, \"utf8\");\n } else {\n let output: PlainObject;\n try {\n output = extractEnvelopeOutput(result.stdout, { resultField: GEMINI_RESULT_FIELD });\n } catch (error) {\n throw new TrailStepFailureError({\n code: \"agent_provider_output_invalid\",\n message: \"gemini provider stdout did not contain a usable JSON result.\",\n details: { cause: error instanceof Error ? error.message : String(error) },\n });\n }\n\n await writeFile(request.outputFile, `${JSON.stringify(output, null, 2)}\\n`, \"utf8\");\n }\n}\n\n/**\n * Builds `-p @<promptFile> --yolo -m <model> --output-format json`, per the Gemini\n * CLI's documented non-interactive flags (`-p/--prompt`, `-m/--model`,\n * `-o/--output-format`, and `-y/--yolo` to auto-accept actions the way\n * Claude's `--dangerously-skip-permissions` and Codex's\n * `--dangerously-bypass-approvals-and-sandbox` do). This has NOT been\n * confirmed against a real `gemini` binary in this environment — the exact\n * flag set is sourced from Gemini CLI documentation only.\n *\n * `request.thinking` is deliberately a documented no-op here: there is no\n * confirmed Gemini CLI flag for a thinking/reasoning-effort level (unlike\n * Claude's `--effort`, Codex's `-c model_reasoning_effort=...`, or Pi's\n * `--thinking`). Guessing a flag name risks the CLI rejecting the whole\n * invocation, so this adapter intentionally does not pass one — do not add a\n * guessed flag here without first confirming it against the real CLI.\n */\nfunction buildGeminiWorkingArgs(request: ProviderWorkingRequest): string[] {\n const args = [\"-p\", promptFileReference(request.promptFile), \"--yolo\"];\n\n if (request.model) {\n args.push(\"-m\", request.model);\n }\n\n args.push(\"--output-format\", \"json\");\n return args;\n}\n\n/**\n * `request.permissionMode` is deliberately unread here — no confirmed Gemini\n * CLI flag exists for approval behavior yet. When available, `systemPromptFile`\n * is passed as an @file prompt reference to avoid argv-length limits.\n */\nasync function runInteractive(\n request: ProviderInteractiveRequest,\n runner: InteractiveProcessRunner = spawnGeminiInteractive,\n): Promise<InteractiveProcessResult> {\n const args: string[] = [];\n\n if (request.model) {\n args.push(\"-m\", request.model);\n }\n\n args.push(\n request.systemPromptFile ? promptFileReference(request.systemPromptFile) : request.prompt,\n );\n\n return await runner({\n command: GEMINI_BINARY,\n args,\n cwd: request.cwd,\n shell: false,\n stdio: \"inherit\",\n env: request.env,\n signal: request.signal,\n });\n}\n\nconst spawnGeminiCapturingStdout: ProviderWorkingRunner = async ({\n command,\n args,\n cwd,\n signal,\n}) => {\n return await new Promise((resolve, reject) => {\n const child = spawn(command, args, {\n cwd,\n shell: false,\n stdio: [\"ignore\", \"pipe\", \"inherit\"],\n detached: process.platform !== \"win32\",\n });\n\n let stdout = \"\";\n child.stdout?.on(\"data\", (chunk: Buffer) => {\n stdout += chunk.toString();\n });\n\n signal?.addEventListener(\"abort\", () => terminateChildProcessTree(child), { once: true });\n child.on(\"error\", reject);\n child.on(\"close\", (code) => resolve({ exitCode: code ?? 1, stdout }));\n });\n};\n\nconst spawnGeminiInteractive: InteractiveProcessRunner = async ({\n command,\n args,\n cwd,\n env,\n signal,\n}) => {\n return await new Promise((resolve, reject) => {\n const child = spawn(command, args, {\n cwd,\n env,\n signal,\n detached: process.platform !== \"win32\",\n shell: false,\n stdio: \"inherit\",\n });\n\n signal?.addEventListener(\"abort\", () => terminateChildProcessTree(child), { once: true });\n child.on(\"error\", reject);\n child.on(\"close\", (code) => resolve({ exitCode: code ?? 1 }));\n });\n};\n\nfunction terminateChildProcessTree(child: ReturnType<typeof spawn>): void {\n if (!child.pid) {\n return;\n }\n\n if (process.platform === \"win32\") {\n spawn(\"taskkill\", [\"/PID\", String(child.pid), \"/T\", \"/F\"], { stdio: \"ignore\" }).on(\n \"error\",\n () => {\n child.kill();\n },\n );\n return;\n }\n\n try {\n process.kill(-child.pid, \"SIGTERM\");\n } catch {\n child.kill();\n }\n}\n\nexport const geminiProvider: ProviderAdapter = {\n id: \"gemini\",\n spec: GEMINI_SPEC,\n runWorking,\n runInteractive,\n};\n","import { spawn } from \"node:child_process\";\nimport { writeFile } from \"node:fs/promises\";\nimport { StringDecoder } from \"node:string_decoder\";\nimport { TrailStepFailureError } from \"../../../contracts/failures/failure.js\";\nimport type { PlainObject } from \"../../../contracts/shapes/shape.types.js\";\nimport type {\n InteractiveProcessResult,\n InteractiveProcessRunner,\n} from \"../../../runtime/run-workflow/run-workflow.types.js\";\nimport { extractEnvelopeOutput, extractEnvelopeText } from \"../../envelopes/envelope.js\";\nimport { resolveCliCommandForSpawn } from \"../../process/resolve-cli-command.js\";\nimport type {\n ProviderAdapter,\n ProviderInteractiveRequest,\n ProviderSpec,\n ProviderWorkingProcessResult,\n ProviderWorkingRequest,\n ProviderWorkingRunner,\n} from \"../../registry/provider-registry.types.js\";\nimport { promptFileReference } from \"../prompt-file-reference.js\";\n\nconst PI_BINARY = \"pi\";\n\n/**\n * Empirically confirmed via `pi -p \"...\" --mode json` (see\n * `mock-local-test/README.md` for the raw probe transcript): unlike Claude's\n * `--output-format json`, `pi --mode json` does not print a single envelope\n * object. It prints one JSON object per line for the whole session transcript\n * (`session`, `agent_start`, `message_start`, `message_update`, `message_end`,\n * `turn_end`, `agent_end`, `agent_settled`, ...). The field that carries the\n * final answer is `\"message\"` — present on the last transcript line whose\n * type actually has that field (`turn_end` in every probe run observed here,\n * since the trailing `agent_end`/`agent_settled` lines carry `\"messages\"`\n * (plural) or no message field at all, and so are skipped by\n * `known-cli-providers/envelopes/envelope.ts`'s reverse-scan fallback).\n *\n * That `\"message\"` value is not itself the final text — it is a message\n * object shaped like `{role, content: [{type, text}, ...], ...}`, so the\n * actual answer lives in the `content` array's `type: \"text\"` block(s) (a\n * `\"thinking\"` block is often present first when `--thinking` is above\n * `\"off\"`). `known-cli-providers/envelopes/envelope.ts` was extended with a generic\n * content-block-array extraction branch to handle this shape, parameterized\n * the same way as Claude's flat `\"result\"` string field — proving the\n * envelope's field-name parameterization is not hardcoded to Claude's shape.\n */\nconst PI_RESULT_FIELD = \"message\";\nconst PI_STDOUT_FALLBACK_TAIL_CHARS = 128_000;\n\nconst PI_SPEC: ProviderSpec = {\n id: \"pi\",\n displayName: \"Pi\",\n model: {\n supported: true,\n flag: \"--model\",\n discovery: {\n command: PI_BINARY,\n args: [\"--list-models\"],\n outputParser: \"pi-list-models-table\",\n },\n },\n thinking: {\n supported: true,\n flag: \"--thinking\",\n levels: [\"low\", \"medium\", \"high\", \"xhigh\", \"max\"],\n },\n working: {\n command: PI_BINARY,\n prompt: { kind: \"prompt-file\", reference: \"at-prefixed-argument\" },\n baseArgs: [\"-p\", \"@{{promptFile}}\", \"--mode\", \"json\"],\n output: {\n style: \"stdout-jsonl-transcript\",\n parsing: { resultField: PI_RESULT_FIELD },\n },\n },\n interactive: { supported: true, command: PI_BINARY, modelFlag: \"--model\" },\n};\n\nasync function runWorking(\n request: ProviderWorkingRequest,\n runner: ProviderWorkingRunner = spawnPiCapturingStdout,\n): Promise<void> {\n const args = buildPiWorkingArgs(request);\n\n let result: ProviderWorkingProcessResult;\n try {\n result = await runner({ command: PI_BINARY, args, cwd: request.cwd, signal: request.signal });\n } catch (error) {\n throw new TrailStepFailureError({\n code: \"agent_provider_spawn_error\",\n message: \"pi provider process could not be started.\",\n details: { cause: error instanceof Error ? error.message : String(error) },\n });\n }\n\n // Pi can return exit code 1 after a tool-using coding turn even when it\n // still prints a valid final answer in the JSON transcript. Treat a usable\n // final envelope as authoritative; if extraction fails, preserve the\n // non-zero process failure.\n if (request.captureMode === \"raw-text\") {\n let text: string;\n try {\n text = extractEnvelopeText(result.stdout, { resultField: PI_RESULT_FIELD });\n } catch (error) {\n throwPiOutputFailure({ exitCode: result.exitCode, error, json: false });\n }\n\n await writeFile(request.outputFile, text, \"utf8\");\n return;\n }\n\n let output: PlainObject;\n try {\n output = extractEnvelopeOutput(result.stdout, { resultField: PI_RESULT_FIELD });\n } catch (error) {\n throwPiOutputFailure({ exitCode: result.exitCode, error, json: true });\n }\n\n await writeFile(request.outputFile, `${JSON.stringify(output, null, 2)}\\n`, \"utf8\");\n}\n\n/**\n * Builds `-p --model <pattern> --thinking <level> @<promptFile> --mode json`.\n * Pi has no dangerous/approval-bypass flag to pass — the CLI does not gate\n * non-interactive `-p` runs on approval the way Claude and Codex do.\n *\n * Pi's `--thinking` vocabulary (`off|minimal|low|medium|high|xhigh|max`,\n * per `pi --help`) is a strict superset of TrailStep's `WorkflowAgentThinking`\n * (`low|medium|high|xhigh|max`), so every TrailStep thinking value passes\n * straight through with no mapping or validation needed (unlike Codex, which\n * has no `\"max\"` tier and must reject it).\n */\nfunction throwPiOutputFailure(options: {\n readonly exitCode: number;\n readonly error: unknown;\n readonly json: boolean;\n}): never {\n if (options.exitCode !== 0) {\n throw new TrailStepFailureError({\n code: \"agent_provider_failed\",\n message: `pi provider process exited with code ${options.exitCode}.`,\n details: { exitCode: options.exitCode },\n });\n }\n\n throw new TrailStepFailureError({\n code: \"agent_provider_output_invalid\",\n message: options.json\n ? \"pi provider stdout did not contain a usable JSON result.\"\n : \"pi provider stdout did not contain a usable result.\",\n details: {\n cause: options.error instanceof Error ? options.error.message : String(options.error),\n },\n });\n}\n\nfunction buildPiWorkingArgs(request: ProviderWorkingRequest): string[] {\n const args = [\"-p\"];\n\n if (request.model) {\n args.push(\"--model\", request.model);\n }\n\n if (request.thinking) {\n args.push(\"--thinking\", request.thinking);\n }\n\n args.push(promptFileReference(request.promptFile));\n args.push(\"--mode\", \"json\");\n return args;\n}\n\n/**\n * `request.permissionMode` is deliberately unread here — no confirmed Pi CLI\n * flag exists for approval behavior yet. When available, `systemPromptFile` is\n * passed as an @file prompt reference to avoid argv-length limits.\n */\nasync function runInteractive(\n request: ProviderInteractiveRequest,\n runner: InteractiveProcessRunner = spawnPiInteractive,\n): Promise<InteractiveProcessResult> {\n const args: string[] = [];\n\n if (request.model) {\n args.push(\"--model\", request.model);\n }\n\n args.push(\n request.systemPromptFile ? promptFileReference(request.systemPromptFile) : request.prompt,\n );\n\n return await runner({\n command: PI_BINARY,\n args,\n cwd: request.cwd,\n shell: false,\n stdio: \"inherit\",\n env: request.env,\n signal: request.signal,\n });\n}\n\nconst spawnPiCapturingStdout: ProviderWorkingRunner = async ({ command, args, cwd, signal }) => {\n const executable = await resolveCliCommandForSpawn({ command, args });\n\n return await new Promise((resolve, reject) => {\n const child = spawn(executable.command, executable.args, {\n cwd,\n shell: false,\n stdio: [\"ignore\", \"pipe\", \"inherit\"],\n detached: process.platform !== \"win32\",\n });\n\n const stdout = createPiJsonStreamStdoutCollector();\n child.stdout?.on(\"data\", (chunk: Buffer) => {\n stdout.append(chunk);\n });\n\n signal?.addEventListener(\"abort\", () => terminateChildProcessTree(child), { once: true });\n child.on(\"error\", reject);\n child.on(\"close\", (code) => resolve({ exitCode: code ?? 1, stdout: stdout.finish() }));\n });\n};\n\ninterface PiJsonStreamStdoutCollector {\n append(chunk: Buffer): void;\n finish(): string;\n}\n\n/**\n * Pi's JSON mode emits a newline-delimited transcript, including frequent\n * message update events. Some updates carry cumulative assistant text, so\n * retaining the whole transcript can grow quadratically with long answers and\n * eventually exceed V8's maximum string length. Keep only the latest usable\n * result-candidate line plus a small bounded tail for invalid-output diagnostics.\n */\nexport function createPiJsonStreamStdoutCollector(): PiJsonStreamStdoutCollector {\n const decoder = new StringDecoder(\"utf8\");\n let pendingLine = \"\";\n let latestResultLine: string | undefined;\n let fallbackTail = \"\";\n\n function appendText(text: string): void {\n fallbackTail = trimFallbackTail(`${fallbackTail}${text}`);\n pendingLine += text;\n\n while (true) {\n const newlineIndex = pendingLine.indexOf(\"\\n\");\n if (newlineIndex === -1) {\n return;\n }\n\n const line = pendingLine.slice(0, newlineIndex).replace(/\\r$/u, \"\");\n rememberLine(line);\n pendingLine = pendingLine.slice(newlineIndex + 1);\n }\n }\n\n return {\n append(chunk) {\n appendText(decoder.write(chunk));\n },\n finish() {\n appendText(decoder.end());\n rememberLine(pendingLine);\n pendingLine = \"\";\n return latestResultLine ?? fallbackTail;\n },\n };\n\n function rememberLine(line: string): void {\n const trimmed = line.trim();\n if (trimmed && isPiResultCandidateLine(trimmed)) {\n latestResultLine = trimmed;\n }\n }\n}\n\nfunction trimFallbackTail(value: string): string {\n if (value.length <= PI_STDOUT_FALLBACK_TAIL_CHARS) {\n return value;\n }\n\n return value.slice(-PI_STDOUT_FALLBACK_TAIL_CHARS);\n}\n\nfunction isPiResultCandidateLine(line: string): boolean {\n return line.includes(`\"${PI_RESULT_FIELD}\"`);\n}\n\nconst spawnPiInteractive: InteractiveProcessRunner = async ({\n command,\n args,\n cwd,\n env,\n signal,\n}) => {\n const executable = await resolveCliCommandForSpawn({ command, args, env });\n\n return await new Promise((resolve, reject) => {\n const child = spawn(executable.command, executable.args, {\n cwd,\n env,\n signal,\n detached: process.platform !== \"win32\",\n shell: false,\n stdio: \"inherit\",\n });\n\n signal?.addEventListener(\"abort\", () => terminateChildProcessTree(child), { once: true });\n child.on(\"error\", reject);\n child.on(\"close\", (code) => resolve({ exitCode: code ?? 1 }));\n });\n};\n\nfunction terminateChildProcessTree(child: ReturnType<typeof spawn>): void {\n if (!child.pid) {\n return;\n }\n\n if (process.platform === \"win32\") {\n spawn(\"taskkill\", [\"/PID\", String(child.pid), \"/T\", \"/F\"], { stdio: \"ignore\" }).on(\n \"error\",\n () => {\n child.kill();\n },\n );\n return;\n }\n\n try {\n process.kill(-child.pid, \"SIGTERM\");\n } catch {\n child.kill();\n }\n}\n\nexport const piProvider: ProviderAdapter = {\n id: \"pi\",\n spec: PI_SPEC,\n runWorking,\n runInteractive,\n};\n","import { constants } from \"node:fs\";\nimport { access, readFile } from \"node:fs/promises\";\nimport { dirname, extname, join } from \"node:path\";\n\nconst WINDOWS_EXECUTABLE_EXTENSIONS = [\".cmd\", \".exe\", \".bat\", \"\"] as const;\n\nexport interface CliCommandSpawnRequest {\n readonly command: string;\n readonly args: readonly string[];\n readonly env?: Readonly<Record<string, string | undefined>>;\n}\n\nexport interface ResolvedCliCommandSpawnRequest {\n readonly command: string;\n readonly args: readonly string[];\n}\n\nexport interface ResolveCliCommandForSpawnOptions {\n readonly platform?: NodeJS.Platform;\n readonly execPath?: string;\n}\n\n/**\n * Built-in provider CLIs are commonly npm-installed. On Windows, npm exposes\n * those CLIs as `.cmd` shims, which cannot be launched through Node's\n * `spawn(..., { shell: false })` by their bare command name. Resolve npm shims\n * to their underlying Node entrypoint when possible so provider prompts remain\n * argv values instead of being reinterpreted by a shell.\n */\nexport async function resolveCliCommandForSpawn(\n request: CliCommandSpawnRequest,\n options: ResolveCliCommandForSpawnOptions = {},\n): Promise<ResolvedCliCommandSpawnRequest> {\n if ((options.platform ?? process.platform) !== \"win32\") {\n return request;\n }\n\n const commandPath = await findWindowsCommandPath(request.command, request.env ?? process.env);\n if (!commandPath) {\n return request;\n }\n\n if (isWindowsCommandShim(commandPath)) {\n const nodeScript = await readNpmCmdShimEntrypoint(commandPath);\n if (nodeScript) {\n return {\n command: options.execPath ?? process.execPath,\n args: [nodeScript, ...request.args],\n };\n }\n\n return {\n command: \"cmd.exe\",\n args: [\"/d\", \"/s\", \"/c\", commandPath, ...request.args],\n };\n }\n\n return { command: commandPath, args: request.args };\n}\n\nasync function findWindowsCommandPath(\n command: string,\n env: Readonly<Record<string, string | undefined>>,\n): Promise<string | undefined> {\n const commandCandidates = windowsCommandCandidates(command);\n if (hasPathSeparator(command)) {\n return await firstExistingPath(commandCandidates);\n }\n\n const pathValue = readCaseInsensitiveEnv(env, \"PATH\");\n if (!pathValue) {\n return await firstExistingPath(commandCandidates);\n }\n\n for (const directory of pathValue.split(windowsPathDelimiter()).filter(Boolean)) {\n const found = await firstExistingPath(\n commandCandidates.map((candidate) => join(directory, candidate)),\n );\n if (found) {\n return found;\n }\n }\n\n return undefined;\n}\n\nfunction windowsCommandCandidates(command: string): readonly string[] {\n if (extname(command)) {\n return [command];\n }\n\n return WINDOWS_EXECUTABLE_EXTENSIONS.map((extension) => `${command}${extension}`);\n}\n\nasync function firstExistingPath(paths: readonly string[]): Promise<string | undefined> {\n for (const path of paths) {\n try {\n await access(path, constants.X_OK);\n return path;\n } catch {\n try {\n await access(path, constants.F_OK);\n return path;\n } catch {\n // Keep looking.\n }\n }\n }\n\n return undefined;\n}\n\nasync function readNpmCmdShimEntrypoint(commandPath: string): Promise<string | undefined> {\n let shim: string;\n try {\n shim = await readFile(commandPath, \"utf8\");\n } catch {\n return undefined;\n }\n\n const match = shim.match(/\"%dp0%\\\\?([^\"]+?\\.js)\"\\s+%\\*/i);\n if (!match?.[1]) {\n return undefined;\n }\n\n return join(dirname(commandPath), match[1].replace(/\\\\/g, \"/\"));\n}\n\nfunction isWindowsCommandShim(path: string): boolean {\n const extension = extname(path).toLowerCase();\n return extension === \".cmd\" || extension === \".bat\";\n}\n\nfunction hasPathSeparator(command: string): boolean {\n return command.includes(\"/\") || command.includes(\"\\\\\");\n}\n\nfunction readCaseInsensitiveEnv(\n env: Readonly<Record<string, string | undefined>>,\n key: string,\n): string | undefined {\n return Object.entries(env).find(([name]) => name.toLowerCase() === key.toLowerCase())?.[1];\n}\n\nfunction windowsPathDelimiter(): string {\n return \";\";\n}\n","import { claudeProvider } from \"../providers/claude/claude-provider.js\";\nimport { codexProvider } from \"../providers/codex/codex-provider.js\";\nimport { geminiProvider } from \"../providers/gemini/gemini-provider.js\";\nimport { piProvider } from \"../providers/pi/pi-provider.js\";\nimport type { ProviderAdapter } from \"./provider-registry.types.js\";\n\n/**\n * Core's built-in known-CLI provider registry. Each entry maps a provider id\n * (matched against a `.trailstep/config.json` target's `provider` field) to a\n * core-owned CLI print-mode invocation for a single named vendor.\n *\n * This is the full four-provider set. Unlike Claude/Codex/Pi, `gemini`'s\n * adapter is structurally verified only (an injected fake stdout-capturing\n * runner in `agent.test.ts`/`gemini.test.ts`) — the real `gemini` CLI is not\n * installed in this environment, so its argv/envelope shape has not been\n * confirmed against a live process.\n */\nexport const providerRegistry: Record<\"claude\" | \"codex\" | \"pi\" | \"gemini\", ProviderAdapter> = {\n claude: claudeProvider,\n codex: codexProvider,\n pi: piProvider,\n gemini: geminiProvider,\n};\n\nexport type ProviderRegistryKey = keyof typeof providerRegistry;\n\nexport function isProviderRegistryKey(provider: string): provider is ProviderRegistryKey {\n return Object.hasOwn(providerRegistry, provider);\n}\n","import { TrailStepFailureError } from \"../../contracts/failures/failure.js\";\nimport { isProviderRegistryKey } from \"../../known-cli-providers/registry/provider-registry.js\";\nimport type { RawTrailStepAgentMappings, RawTrailStepAgentTarget } from \"./parse-agent-targets.js\";\nimport type { RawTrailStepWorkflowConfig } from \"./parse-workflow-agent-mappings.js\";\n\nexport function validateProviderReferences(options: {\n readonly agents: RawTrailStepAgentMappings;\n readonly workflows: Readonly<Record<string, RawTrailStepWorkflowConfig>> | undefined;\n readonly providerNames: Set<string>;\n}): void {\n const providerViolations: string[] = [];\n\n validateAgentMappings(\"agents\", options.agents, options.providerNames, providerViolations);\n\n if (options.workflows !== undefined) {\n for (const [workflowId, workflow] of Object.entries(options.workflows)) {\n validateAgentMappings(\n `workflows.${workflowId}.agents`,\n workflow.agents,\n options.providerNames,\n providerViolations,\n );\n }\n }\n\n if (providerViolations.length > 0) {\n throw new TrailStepFailureError({\n code: \"agent_provider_unknown\",\n message:\n \"One or more agent targets reference a provider that is neither a built-in provider nor a declared customProviders entry.\",\n details: { diagnostics: providerViolations },\n });\n }\n}\n\nfunction validateAgentMappings(\n path: string,\n mappings: RawTrailStepAgentMappings | undefined,\n providerNames: Set<string>,\n diagnostics: string[],\n): void {\n if (mappings === undefined) {\n return;\n }\n\n for (const [name, targets] of Object.entries(mappings)) {\n validateTargetReferences(`${path}.${name}`, targets, providerNames, diagnostics);\n }\n}\n\nfunction validateTargetReferences(\n path: string,\n targets: readonly RawTrailStepAgentTarget[],\n providerNames: Set<string>,\n diagnostics: string[],\n): void {\n for (const [index, target] of targets.entries()) {\n if (!(\"provider\" in target)) {\n continue;\n }\n\n if (!providerNames.has(target.provider) && !isProviderRegistryKey(target.provider)) {\n diagnostics.push(\n `${path}[${index}].provider references unknown provider '${target.provider}'. Declare it under customProviders or use a built-in provider.`,\n );\n }\n }\n}\n","import type { TrailStepConfig } from \"../targeting.types.js\";\nimport { expandAgentRefs } from \"./expand-agent-refs.js\";\nimport { parseAgentMappings } from \"./parse-agent-mappings.js\";\nimport { parseCustomProviders } from \"./parse-custom-providers.js\";\nimport { parseSettings } from \"./parse-settings.js\";\nimport { isRecord, throwValidationFailure } from \"./parse-utils.js\";\nimport { parseWorkflows } from \"./parse-workflow-agent-mappings.js\";\nimport { validateProviderReferences } from \"./validate-provider-references.js\";\n\nconst parsedConfigs = new WeakSet<TrailStepConfig>();\n\nexport function isParsedTrailStepConfig(value: unknown): value is TrailStepConfig {\n return isRecord(value) && parsedConfigs.has(value as unknown as TrailStepConfig);\n}\n\nexport function parseTrailStepConfig(value: unknown): TrailStepConfig {\n const diagnostics: string[] = [];\n\n if (!isRecord(value)) {\n throwValidationFailure([\"config must be an object.\"]);\n }\n\n if (value.version !== 1) {\n diagnostics.push(\"version must be 1.\");\n }\n\n const customProviders = parseCustomProviders(value.customProviders, diagnostics);\n const providerNames = new Set(Object.keys(customProviders));\n const agents = parseAgentMappings(\"agents\", value.agents, diagnostics);\n const settings = parseSettings(\"settings\", value.settings, diagnostics);\n const workflows = parseWorkflows(value.workflows, diagnostics);\n\n if (diagnostics.length > 0) {\n throwValidationFailure(diagnostics);\n }\n\n validateProviderReferences({ agents, workflows, providerNames });\n const expanded = expandAgentRefs({ agents, workflows });\n\n const config: TrailStepConfig = {\n version: 1,\n customProviders,\n agents: expanded.agents,\n ...(settings === undefined ? {} : { settings }),\n ...(expanded.workflows === undefined ? {} : { workflows: expanded.workflows }),\n };\n\n parsedConfigs.add(config);\n\n return config;\n}\n","import { TrailStepFailureError } from \"../../contracts/failures/failure.js\";\nimport type { ResolveAgentTargetsOptions, TrailStepAgentTarget } from \"../targeting.types.js\";\n\nexport function resolveAgentTargets(\n options: ResolveAgentTargetsOptions,\n): readonly TrailStepAgentTarget[] {\n const workflowMappings = options.config.workflows?.[options.workflowId]?.agents;\n\n const targetLists = [\n workflowMappings?.[options.roleName],\n options.config.agents[options.roleSize],\n options.config.agents.default,\n ];\n\n const targets = targetLists.flatMap((targets) =>\n targets && targets.length > 0 ? [...targets] : [],\n );\n\n if (targets.length > 0) {\n return targets;\n }\n\n throw new TrailStepFailureError({\n code: \"agent_targets_unavailable\",\n message: `No agent targets found for role ${options.roleName} with size ${options.roleSize} in workflow ${options.workflowId}.`,\n details: {\n roleName: options.roleName,\n roleSize: options.roleSize,\n workflowId: options.workflowId,\n },\n });\n}\n","import { appendFile, mkdir, readFile, writeFile } from \"node:fs/promises\";\nimport { basename, dirname, join } from \"node:path\";\nimport { TrailStepFailureError } from \"../../contracts/failures/failure.js\";\nimport type { Event } from \"../../runtime/run-workflow/run-workflow.types.js\";\n\nexport type RunState = Record<string, unknown>;\n\nexport function defaultRunsRoot(cwd: string): string {\n return join(cwd, \".trailstep\", \"runs\");\n}\n\nexport async function createRunDirectory(options: {\n readonly cwd: string;\n readonly runName: string;\n readonly runsRoot?: string;\n}): Promise<{ runId: string; runDir: string }> {\n const runsRoot = options.runsRoot ?? defaultRunsRoot(options.cwd);\n validateRunName(options.runName);\n await mkdir(runsRoot, { recursive: true });\n await ensureTrailStepGitignoreForRunsRoot(runsRoot);\n\n for (let suffix = 1; ; suffix += 1) {\n const runId = suffix === 1 ? options.runName : `${options.runName}-${suffix}`;\n const runDir = join(runsRoot, runId);\n\n try {\n await mkdir(runDir);\n return { runId, runDir };\n } catch (error) {\n if (isNodeError(error) && error.code === \"EEXIST\") {\n continue;\n }\n\n throw error;\n }\n }\n}\n\nexport async function appendEvent(runDir: string, event: Event): Promise<void> {\n await appendFile(join(runDir, \"events.jsonl\"), `${JSON.stringify(event)}\\n`, \"utf8\");\n}\n\nexport async function readRunEvents(runDir: string): Promise<Event[]> {\n let contents: string;\n try {\n contents = await readFile(join(runDir, \"events.jsonl\"), \"utf8\");\n } catch (error) {\n if (isNodeError(error)) {\n throw new TrailStepFailureError({\n code: \"resume_target_not_found\",\n message: `Resume target not found or unreadable: ${join(runDir, \"events.jsonl\")}.`,\n details: { runDir, causeCode: error.code },\n });\n }\n\n throw error;\n }\n\n const rawLines = contents.split(\"\\n\");\n const lines = rawLines.filter((line, index) => line.length > 0 || index < rawLines.length - 1);\n const events: Event[] = [];\n\n for (let index = 0; index < lines.length; index += 1) {\n const line = lines[index];\n if (!line) {\n continue;\n }\n\n try {\n events.push(JSON.parse(line) as Event);\n } catch (error) {\n const isTrailingLine = index === lines.length - 1;\n if (isTrailingLine) {\n return events;\n }\n\n throw error;\n }\n }\n\n return events;\n}\n\nexport async function persistEvents(runDir: string, events: readonly Event[]): Promise<void> {\n const jsonl = events.map((event) => JSON.stringify(event)).join(\"\\n\");\n await writeFile(join(runDir, \"events.jsonl\"), `${jsonl}\\n`, \"utf8\");\n}\n\nexport async function writeDocumentArtifact(\n dir: string,\n filename: string,\n content: string,\n): Promise<string> {\n await mkdir(dir, { recursive: true });\n\n const documentPath = join(dir, filename);\n await writeFile(documentPath, content, \"utf8\");\n\n return documentPath;\n}\n\nexport async function readRunState(runDir: string): Promise<RunState> {\n try {\n const contents = await readFile(join(runDir, \"state.json\"), \"utf8\");\n const parsed: unknown = JSON.parse(contents);\n\n if (!isRunState(parsed)) {\n throw new Error(\"run state must be a JSON object\");\n }\n\n return parsed;\n } catch (error) {\n if (isNodeError(error) && error.code === \"ENOENT\") {\n return {};\n }\n\n throw error;\n }\n}\n\nexport async function writeRunState(runDir: string, state: RunState): Promise<void> {\n await writeFile(join(runDir, \"state.json\"), `${JSON.stringify(state, null, 2)}\\n`, \"utf8\");\n}\n\nfunction isNodeError(error: unknown): error is NodeJS.ErrnoException {\n return error instanceof Error && \"code\" in error;\n}\n\nfunction validateRunName(runName: string): void {\n if (\n runName.trim().length === 0 ||\n runName === \".\" ||\n runName === \"..\" ||\n runName.includes(\"/\") ||\n runName.includes(\"\\\\\")\n ) {\n throw new TrailStepFailureError({\n code: \"run_name_invalid\",\n message: \"Run name must be a non-empty single path segment.\",\n details: { runName },\n });\n }\n}\n\nfunction isRunState(value: unknown): value is RunState {\n return (\n typeof value === \"object\" &&\n value !== null &&\n !Array.isArray(value) &&\n Object.getPrototypeOf(value) === Object.prototype\n );\n}\n\nasync function ensureTrailStepGitignoreForRunsRoot(runsRoot: string): Promise<void> {\n const trailstepRoot = dirname(runsRoot);\n if (basename(trailstepRoot) !== \".trailstep\") {\n return;\n }\n\n await ensureTrailStepGitignore(trailstepRoot);\n}\n\nasync function ensureTrailStepGitignore(trailstepRoot: string): Promise<void> {\n try {\n await writeFile(join(trailstepRoot, \".gitignore\"), \"*\\n!.gitignore\\n\", { flag: \"wx\" });\n } catch (error) {\n if (isNodeError(error) && error.code === \"EEXIST\") {\n return;\n }\n\n throw error;\n }\n}\n","import { AsyncLocalStorage } from \"node:async_hooks\";\nimport type { RunContext } from \"../../contracts/run-context/run-context.types.js\";\n\n/**\n * A module-scoped `new AsyncLocalStorage()` is not safe here: the CLI's\n * direct-file workflow resolver loads workflow source through `tsx`'s\n * `tsImport`, which re-transpiles and re-evaluates everything reachable from\n * that entry point -- including this module -- as a second, independent\n * instantiation, even though it's the exact same file on disk. Two distinct\n * `AsyncLocalStorage` objects never see each other's stores no matter how\n * carefully `.run(...)` is nested, so `run-workflow.ts`/`with-step-context.ts`\n * (loaded the normal way) and a workflow's own step code (loaded via\n * `tsImport`) would silently end up talking to two different storages.\n * Keying the single instance off a well-known symbol on `globalThis` -- shared\n * by every module instantiation within the same process/realm -- keeps them\n * talking to the same storage regardless of which loader touched this file.\n */\nconst RUN_CONTEXT_STORAGE_KEY = Symbol.for(\"trailstep.core.runContextStorage\");\n\ninterface GlobalWithRunContextStorage {\n [RUN_CONTEXT_STORAGE_KEY]?: AsyncLocalStorage<RunContext>;\n}\n\nconst globalScope = globalThis as GlobalWithRunContextStorage;\n\nfunction getOrCreateRunContextStorage(): AsyncLocalStorage<RunContext> {\n const existing = globalScope[RUN_CONTEXT_STORAGE_KEY];\n if (existing) {\n return existing;\n }\n\n const created = new AsyncLocalStorage<RunContext>();\n globalScope[RUN_CONTEXT_STORAGE_KEY] = created;\n return created;\n}\n\nexport const runContextStorage: AsyncLocalStorage<RunContext> = getOrCreateRunContextStorage();\n\nexport function currentRunContext(): RunContext {\n const runContext = runContextStorage.getStore();\n if (!runContext) {\n throw new Error(\"state.* called outside an active TrailStep run.\");\n }\n\n return runContext;\n}\n","import { TrailStepFailureError, validationFailure } from \"../../contracts/failures/failure.js\";\nimport type { ValidationDiagnostic } from \"../../contracts/shapes/shape.types.js\";\nimport { writeDocumentArtifact } from \"../../runtime/artifacts/run-storage.js\";\nimport { currentRunContext } from \"../../runtime/run-context/run-context-storage.js\";\n\n/**\n * A captured document artifact. `Document` doubles as its own\n * `Schema<Document>`: `validate`/`diagnostics`/`assert`/`jsonSchema`/\n * `captureMode` are static members, so passing the class itself as\n * `.prompt(source, { output: Document })` gives both the TypeScript output\n * type and the runtime validator from one symbol -- no separate schema\n * constant to import or keep in sync.\n */\nexport class Document {\n // Index signature satisfies the `PlainObject` (`Record<string, unknown>`)\n // constraint required by `Schema<T extends PlainObject>` — a plain class\n // with only named properties does not structurally provide one otherwise.\n [key: string]: unknown;\n\n static readonly captureMode = \"raw-text\" as const;\n\n static readonly jsonSchema: Record<string, unknown> = {\n type: \"string\",\n description: \"Document content, captured as raw text.\",\n };\n\n static validate(value: unknown): value is Document {\n return isDocumentLike(value);\n }\n\n static diagnostics(value: unknown): readonly ValidationDiagnostic[] {\n if (isDocumentLike(value)) {\n return [];\n }\n\n return [\n { path: \"/\", message: \"must be a document (an object with string content and path fields)\" },\n ];\n }\n\n /**\n * Deliberately duck-types instead of checking `instanceof Document`: on\n * resume, a completed step's recorded output is replayed from\n * `events.jsonl` via `JSON.parse`, producing a plain deserialized object —\n * never a live `Document` instance — before `assert` is called on it. An\n * `instanceof` check would fail every such replay. `assert` reconstructs a\n * genuine `Document` from any content/path-shaped value, so every\n * consumer downstream — a live capture or a replayed value alike — always\n * receives a real `Document` instance with working prototype methods.\n */\n static assert(value: unknown, label = \"value\"): Document {\n const valueDiagnostics = Document.diagnostics(value);\n\n if (valueDiagnostics.length > 0 || !isDocumentLike(value)) {\n throw new TrailStepFailureError(\n validationFailure(\n `${label} failed schema validation: ${formatDiagnostics(valueDiagnostics)}`,\n {\n diagnostics: valueDiagnostics,\n },\n ),\n );\n }\n\n return new Document(value.content, value.path);\n }\n\n constructor(\n public readonly content: string,\n public readonly path: string,\n ) {}\n}\n\n/**\n * Captures `content` as a durable document artifact for the currently\n * executing step. Must be called from within a step's `.do()` callback —\n * it reads the step-scoped ambient context (`RunContext.currentStep`, set\n * by `withStepContext` for the duration of the step) to determine both the\n * directory to write into and this call's 1-based index within the step, so\n * that a step calling `document(...)` more than once gets\n * `document-1.md`, `document-2.md`, etc.\n */\nexport async function document(content: string): Promise<Document> {\n const { currentStep } = currentRunContext();\n\n if (!currentStep) {\n throw new Error(\n \"document(...) must be called from within a step's `.do()` callback; no active step context was found.\",\n );\n }\n\n const index = currentStep.nextDocumentIndex();\n const path = await writeDocumentArtifact(currentStep.dir, `document-${index}.md`, content);\n\n return new Document(content, path);\n}\n\nfunction isDocumentLike(value: unknown): value is { content: string; path: string } {\n return (\n typeof value === \"object\" &&\n value !== null &&\n typeof (value as Record<string, unknown>).content === \"string\" &&\n typeof (value as Record<string, unknown>).path === \"string\"\n );\n}\n\nfunction formatDiagnostics(diagnostics: readonly ValidationDiagnostic[]): string {\n return diagnostics.map((diagnostic) => `${diagnostic.path} ${diagnostic.message}`).join(\"; \");\n}\n","import { readFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\n\n/**\n * Synchronously reads each named file relative to `dir` and returns its\n * trimmed content keyed the same way, so a step's `prompt.ts` can load all\n * of its shared markdown fragments in one call:\n * `loadFragments(import.meta.dirname, { methodology: \"../shared/methodology.md\" })`.\n */\nexport function loadFragments<TKey extends string>(\n dir: string,\n files: Record<TKey, string>,\n): Record<TKey, string> {\n const fragments = {} as Record<TKey, string>;\n\n for (const key of Object.keys(files) as TKey[]) {\n fragments[key] = readFileSync(join(dir, files[key]), \"utf8\").trimEnd();\n }\n\n return fragments;\n}\n\n/**\n * Renders `body` as a `## title` markdown section, or `undefined` when\n * `body` is falsy -- so a conditional section can be inlined directly as a\n * `promptSections(...)` argument instead of built up separately.\n */\nexport function section(\n title: string,\n body: string | false | null | undefined,\n): string | undefined {\n return body ? `## ${title}\\n\\n${body.trimEnd()}` : undefined;\n}\n\n/**\n * Joins prompt fragments and `section(...)` results with a blank line\n * between each, dropping any falsy (conditionally-omitted) part.\n */\nexport function promptSections(...parts: ReadonlyArray<string | false | null | undefined>): string {\n return parts.filter((part): part is string => Boolean(part)).join(\"\\n\\n\");\n}\n\n/** Renders `items` as a markdown bullet list, one `- item` per line. */\nexport function list(items: readonly string[]): string {\n return items.map((item) => `- ${item}`).join(\"\\n\");\n}\n","import type { PromptTemplateSource } from \"../step/continuation.types.js\";\n\n/** Loads a step's prompt from a local text file, resolved relative to the workflow's `cwd` at dispatch time. */\nexport function promptTemplate(path: string): PromptTemplateSource {\n return { kind: \"promptTemplate\", path };\n}\n","import { Ajv, type ErrorObject, type JSONSchemaType } from \"ajv/dist/ajv.js\";\n\nimport { TrailStepFailureError, validationFailure } from \"../../contracts/failures/failure.js\";\nimport type {\n PlainObject,\n Schema,\n ShapeInput,\n ShapeObject,\n ValidationDiagnostic,\n} from \"../../contracts/shapes/shape.types.js\";\n\nexport type JsonSchemaObject = JSONSchemaType<PlainObject> | Record<string, unknown>;\n\nconst ajv = new Ajv({ allErrors: true });\n\nexport function normalizeShape<T extends PlainObject>(shapeInput: ShapeInput<T>): Schema<T> {\n if (isSchema(shapeInput)) {\n return shapeInput;\n }\n\n return shape<T>(shapeInput);\n}\n\nexport function shape<T extends PlainObject>(shapeObject: ShapeObject): Schema<T> {\n return jsonSchema<T>({\n type: \"object\",\n properties: Object.fromEntries(\n Object.entries(shapeObject).map(([key, type]) => [key, { type }]),\n ),\n required: Object.keys(shapeObject),\n additionalProperties: false,\n });\n}\n\nexport function jsonSchema<T extends PlainObject>(schema: JsonSchemaObject): Schema<T> {\n const validateWithAjv = ajv.compile(schema);\n\n return {\n validate(value: unknown): value is T {\n return validateWithAjv(value);\n },\n diagnostics(value: unknown): readonly ValidationDiagnostic[] {\n if (!isPlainObject(value)) {\n return [{ path: \"/\", message: \"must be a plain object\" }];\n }\n\n if (validateWithAjv(value)) {\n return [];\n }\n\n return diagnosticsFromAjvErrors(validateWithAjv.errors);\n },\n assert(value: unknown, label = \"value\"): T {\n const diagnostics = this.diagnostics(value);\n\n if (diagnostics.length > 0) {\n throw new TrailStepFailureError(\n validationFailure(\n `${label} failed schema validation: ${formatDiagnostics(diagnostics)}`,\n { diagnostics },\n ),\n );\n }\n\n return value as T;\n },\n jsonSchema: schema as Record<string, unknown>,\n };\n}\n\nfunction isSchema<T extends PlainObject>(value: ShapeInput<T>): value is Schema<T> {\n // Checked structurally rather than via `isPlainObject` so that a class\n // carrying its schema as static members (e.g. `Document`) -- a function,\n // not a plain object -- is recognized as a `Schema<T>` too.\n if (value === null || (typeof value !== \"object\" && typeof value !== \"function\")) {\n return false;\n }\n\n const candidate = value as Record<string, unknown>;\n\n return (\n typeof candidate.validate === \"function\" &&\n typeof candidate.diagnostics === \"function\" &&\n typeof candidate.assert === \"function\"\n );\n}\n\nexport function isPlainObject(value: unknown): value is PlainObject {\n return (\n typeof value === \"object\" &&\n value !== null &&\n !Array.isArray(value) &&\n Object.getPrototypeOf(value) === Object.prototype\n );\n}\n\nfunction diagnosticsFromAjvErrors(\n errors: ErrorObject[] | null | undefined,\n): readonly ValidationDiagnostic[] {\n if (!errors || errors.length === 0) {\n return [{ path: \"/\", message: \"is invalid\" }];\n }\n\n return errors.map((error) => ({\n path: error.instancePath || \"/\",\n message: error.message ?? \"is invalid\",\n }));\n}\n\nfunction formatDiagnostics(diagnostics: readonly ValidationDiagnostic[]): string {\n return diagnostics.map((diagnostic) => `${diagnostic.path} ${diagnostic.message}`).join(\"; \");\n}\n","import { currentRunContext } from \"../../runtime/run-context/run-context-storage.js\";\n\n/**\n * Ambient handle onto the active run's identity and durable key-value store.\n * Backed by AsyncLocalStorage, set once per run by `runWorkflow`; step\n * continuations import this directly rather than receiving it as an argument.\n */\nexport const state = {\n async get<T = unknown>(key: string): Promise<T | undefined> {\n return currentRunContext().state.get<T>(key);\n },\n async set(key: string, value: unknown): Promise<void> {\n await currentRunContext().state.set(key, value);\n },\n get id(): string {\n return currentRunContext().id;\n },\n get name(): string {\n return currentRunContext().name;\n },\n get path(): string {\n return currentRunContext().path;\n },\n get cwd(): string | undefined {\n return currentRunContext().cwd;\n },\n};\n","import type { AgentPrompt } from \"../../contracts/agents/agent-adapter.types.js\";\nimport type { Failure } from \"../../contracts/failures/failure.js\";\nimport type { PlainObject } from \"../../contracts/shapes/shape.types.js\";\nimport type {\n ContinuationStepConfig,\n DoneNode,\n FailNode,\n PromptOptions,\n PromptTemplateSource,\n StepConfig,\n StepContinuation,\n StepErrorContinuation,\n StepFactory,\n StepNode,\n} from \"../step/continuation.types.js\";\n\n/**\n * The only step-authoring primitive. `.prompt(...)` is optional; when present,\n * the step dispatches to an agent and `.do(...)` receives its structured\n * output. When absent, nothing is dispatched -- `.do(...)` receives the\n * step's input directly and is responsible for the work and the continuation\n * in one function. Either way, `.do(...)` produces a reusable `StepFactory`\n * -- call it with a live input value (`stepA(input)`) to get a `StepNode`.\n * When the inferred input type has no required keys, the argument is\n * optional (`stepA()`) and defaults to `{}`.\n */\nexport function step(config: StepConfig): {\n prompt<TInput extends PlainObject = PlainObject, TOutput extends PlainObject = PlainObject>(\n source: AgentPrompt<TInput> | PromptTemplateSource,\n options?: PromptOptions<TOutput>,\n ): {\n do(onOutput: StepContinuation<TInput, TOutput>): StepFactory<TInput, TOutput>;\n };\n do<TInput extends PlainObject = PlainObject>(\n onOutput: StepContinuation<TInput, TInput>,\n ): StepFactory<TInput, TInput>;\n} {\n const buildFactory = <TInput extends PlainObject, TStepOutput extends PlainObject>(\n prompt: AgentPrompt<TInput> | PromptTemplateSource | undefined,\n promptOptions: PromptOptions<TStepOutput> | undefined,\n onOutput: StepContinuation<TInput, TStepOutput>,\n onError?: StepErrorContinuation,\n ): StepFactory<TInput, TStepOutput> => {\n const factory = ((input?: TInput): StepNode<TInput, TStepOutput> => ({\n kind: \"step\",\n config: {\n ...config,\n ...promptOptions,\n prompt,\n input: input ?? ({} as TInput),\n } as ContinuationStepConfig<TInput, TStepOutput>,\n onOutput,\n onError,\n })) as StepFactory<TInput, TStepOutput>;\n\n factory.catch = (nextOnError: StepErrorContinuation) =>\n buildFactory(prompt, promptOptions, onOutput, nextOnError);\n\n return factory;\n };\n\n return {\n prompt(source, options) {\n if (hasRetryOption(options)) {\n throw new TypeError(\"Retry config belongs on step(...), not .prompt(...) options.\");\n }\n\n if (hasTimeoutOption(options)) {\n throw new TypeError(\"Timeout config belongs on step(...), not .prompt(...) options.\");\n }\n\n return {\n do: (onOutput) => buildFactory(source, options, onOutput),\n };\n },\n do(onOutput) {\n return buildFactory(undefined, undefined, onOutput);\n },\n };\n}\n\nexport function done<TOutput extends PlainObject = PlainObject>(\n output?: TOutput,\n): DoneNode<TOutput> {\n return {\n kind: \"done\",\n output: output ?? ({} as TOutput),\n };\n}\n\nexport function fail(failure: Failure): FailNode {\n return {\n kind: \"fail\",\n failure,\n };\n}\n\nexport function isStepNode(value: unknown): value is StepNode {\n return isPlainObject(value) && value.kind === \"step\";\n}\n\nexport function isDoneNode(value: unknown): value is DoneNode {\n return isPlainObject(value) && value.kind === \"done\";\n}\n\nexport function isFailNode(value: unknown): value is FailNode {\n return isPlainObject(value) && value.kind === \"fail\";\n}\n\nfunction hasRetryOption(value: unknown): boolean {\n return isPlainObject(value) && \"retry\" in value;\n}\n\nfunction hasTimeoutOption(value: unknown): boolean {\n return isPlainObject(value) && \"timeout\" in value;\n}\n\nfunction isPlainObject(value: unknown): value is PlainObject {\n return (\n typeof value === \"object\" &&\n value !== null &&\n !Array.isArray(value) &&\n Object.getPrototypeOf(value) === Object.prototype\n );\n}\n","import { mkdir, writeFile } from \"node:fs/promises\";\n\nimport { runAgentStep } from \"../../agent-execution/adapter-agent/run-adapter-agent-step/run-adapter-agent-step.js\";\nimport {\n resolvePromptSource,\n resolveWorkflowAgentRole,\n} from \"../../agent-execution/dispatch-agent-step/dispatch-agent-step.js\";\nimport { runWorkingAgentCommand } from \"../../agent-execution/working-agent/run-working-agent-command.js\";\nimport { normalizeShape } from \"../../authoring/shape/json-schema.js\";\nimport type {\n PromptTemplateSource,\n SubPromptOptions,\n} from \"../../authoring/step/continuation.types.js\";\nimport type { AgentPrompt } from \"../../contracts/agents/agent-adapter.types.js\";\nimport { TrailStepFailureError } from \"../../contracts/failures/failure.js\";\nimport type { PlainObject } from \"../../contracts/shapes/shape.types.js\";\nimport { createEvent } from \"../events/create-run-event.js\";\nimport { runContextStorage } from \"../run-context/run-context-storage.js\";\nimport { resolveSubPromptArtifactPaths } from \"./sub-prompt-artifacts.js\";\nimport {\n emitSubPromptFailed,\n maxSubPromptsGuardError,\n subPromptFailureError,\n throwMissingSubPromptAgentConfig,\n} from \"./sub-prompt-failures.js\";\nimport { fingerprintSubPrompt } from \"./sub-prompt-fingerprint.js\";\nimport { findCompletedSubPromptEvent } from \"./sub-prompt-replay.js\";\n\nexport function resolveMaxSubPrompts(value: unknown): number {\n if (value === undefined) {\n return 25;\n }\n\n if (Number.isInteger(value) && typeof value === \"number\" && value > 0) {\n return value;\n }\n\n throw new TrailStepFailureError({\n code: \"invalid_max_sub_prompts\",\n message: \"maxSubPrompts must be a positive integer.\",\n });\n}\n\nexport async function runSubPrompt<\n TInput extends PlainObject = PlainObject,\n TOutput extends PlainObject = PlainObject,\n>(\n source: AgentPrompt<TInput> | PromptTemplateSource,\n options: SubPromptOptions<TOutput>,\n input?: TInput,\n): Promise<TOutput> {\n const resolvedInput = (input ?? {}) as TInput;\n const context = runContextStorage.getStore();\n if (!context?.currentStep) {\n throw new TrailStepFailureError({\n code: \"sub_prompt_outside_step_context\",\n message: \"subPrompt requires an active TrailStep step run context.\",\n });\n }\n\n if (!context.workflowId || !context.workflowAgents || !context.cwd || !context.emit) {\n throw new TrailStepFailureError({\n code: \"sub_prompt_context_unavailable\",\n message: \"subPrompt requires a full active TrailStep step run context.\",\n });\n }\n\n const parentStep = context.currentStep;\n if (options.output === undefined) {\n throw new TrailStepFailureError({\n code: \"sub_prompt_output_required\",\n message: `subPrompt in step ${parentStep.id} with a prompt requires an output shape`,\n });\n }\n\n const outputSchema = normalizeShape(options.output);\n const ordinal = parentStep.nextSubPromptIndex();\n const maxSubPrompts = resolveMaxSubPrompts(options.maxSubPrompts ?? parentStep.maxSubPrompts);\n if (ordinal > maxSubPrompts) {\n const failureError = maxSubPromptsGuardError(maxSubPrompts);\n await emitSubPromptFailed({\n context,\n parentStepId: parentStep.id,\n ordinal,\n failure: failureError.failure,\n });\n throw failureError;\n }\n\n const renderedPrompt = await resolvePromptSource(source, resolvedInput, context.cwd);\n const fingerprint = fingerprintSubPrompt({ input: resolvedInput, prompt: renderedPrompt });\n const cachedEvent = findCompletedSubPromptEvent(\n context.events?.() ?? [],\n parentStep.id,\n ordinal,\n fingerprint,\n );\n if (cachedEvent) {\n return outputSchema.assert(cachedEvent.payload.output, \"subPrompt output\");\n }\n\n const artifactPaths = resolveSubPromptArtifactPaths({\n runDir: context.path,\n stepDir: parentStep.dir,\n ordinal,\n fingerprint,\n });\n\n await mkdir(artifactPaths.subPromptDir, { recursive: true });\n await writeFile(artifactPaths.promptFile, renderedPrompt, \"utf8\");\n\n const resolvedRole = resolveWorkflowAgentRole({\n agent: options.agent,\n workflowAgents: context.workflowAgents,\n workflowId: context.workflowId,\n stepId: parentStep.id,\n });\n\n await context.emit(\n createEvent({\n runId: context.id,\n workflowId: context.workflowId,\n stepId: parentStep.id,\n type: \"subPrompt.started\",\n payload: {\n parentStepId: parentStep.id,\n ordinal,\n fingerprint,\n artifactPaths: artifactPaths.runRelative,\n },\n }),\n );\n\n try {\n const agentStep = {\n kind: \"agent\" as const,\n id: `${parentStep.id}.subPrompt.${ordinal}`,\n output: outputSchema,\n prompt: renderedPrompt,\n requirements: resolvedRole.role,\n adapter: options.adapter,\n };\n\n if (!context.trailstepConfig && options.adapter === undefined) {\n throwMissingSubPromptAgentConfig({\n workflowId: context.workflowId,\n parentStepId: parentStep.id,\n subPromptId: agentStep.id,\n agent: resolvedRole.roleName,\n });\n }\n\n const rawOutput =\n context.trailstepConfig && options.adapter === undefined\n ? await runWorkingAgentCommand({\n config: context.trailstepConfig,\n workflowId: context.workflowId,\n roleName: resolvedRole.roleName,\n role: resolvedRole.role,\n step: agentStep,\n renderedPrompt,\n runDir: context.path,\n cwd: context.cwd,\n runner: context.workingAgentProcessRunner,\n providerWorkingRunner: context.providerWorkingRunner,\n stepIndex: ordinal,\n files: {\n stepDir: artifactPaths.subPromptDir,\n promptFile: artifactPaths.promptFile,\n outputFile: artifactPaths.outputFile,\n usageFile: artifactPaths.usageFile,\n },\n })\n : await runAgentStep({\n step: agentStep,\n input: resolvedInput,\n onToolCall: async (toolCall) => {\n await context.emit?.(\n createEvent({\n runId: context.id,\n workflowId: context.workflowId ?? \"\",\n stepId: parentStep.id,\n type: \"agent.toolCall\",\n payload: { ...toolCall },\n }),\n );\n },\n });\n\n const output = outputSchema.assert(rawOutput, \"subPrompt output\");\n await writeFile(artifactPaths.outputFile, `${JSON.stringify(output, null, 2)}\\n`, \"utf8\");\n\n await context.emit(\n createEvent({\n runId: context.id,\n workflowId: context.workflowId,\n stepId: parentStep.id,\n type: \"subPrompt.completed\",\n payload: {\n parentStepId: parentStep.id,\n ordinal,\n fingerprint,\n output,\n artifactPaths: artifactPaths.runRelative,\n },\n }),\n );\n\n return output;\n } catch (error) {\n const failureError = subPromptFailureError(error);\n await emitSubPromptFailed({\n context,\n parentStepId: parentStep.id,\n ordinal,\n fingerprint,\n artifactPaths: artifactPaths.runRelative,\n failure: failureError.failure,\n });\n throw failureError;\n }\n}\n","import type { AgentStepRequestConfig } from \"../../../authoring/step/agent-step.types.js\";\nimport type {\n AgentAdapter,\n AgentAdapterSelection,\n AgentPrompt,\n AgentTool,\n} from \"../../../contracts/agents/agent-adapter.types.js\";\nimport type { AgentModelTarget } from \"../../../contracts/agents/agent-role.types.js\";\nimport { TrailStepFailureError } from \"../../../contracts/failures/failure.js\";\nimport type { PlainObject, Schema } from \"../../../contracts/shapes/shape.types.js\";\n\nconst PROVIDER_NEUTRAL_ADAPTER_KEY = \"custom\";\nconst PROVIDER_NEUTRAL_MODEL = \"configured-agent\";\n\nexport interface AgentToolCallEvent {\n readonly name: string;\n readonly input: PlainObject;\n readonly output: PlainObject;\n}\n\nexport interface RunAgentStepOptions<\n TInput extends PlainObject = PlainObject,\n TOutput extends PlainObject = PlainObject,\n> {\n readonly step: AgentStepRequestConfig<TInput, TOutput>;\n readonly input: TInput;\n readonly onToolCall?: (event: AgentToolCallEvent) => void | Promise<void>;\n}\n\nexport async function runAgentStep<\n TInput extends PlainObject = PlainObject,\n TOutput extends PlainObject = PlainObject,\n>(options: RunAgentStepOptions<TInput, TOutput>): Promise<PlainObject> {\n const model = resolveAgentRequirements(options.step.requirements);\n const adapter = resolveAgentAdapter(options.step.adapter);\n let submittedOutput: PlainObject | undefined;\n\n const tools: AgentTool<TOutput>[] = [\n createSubmitOutputTool(options.step.output, async (output) => {\n options.step.output.assert(output, `agent step ${options.step.id} submit_output`);\n submittedOutput = output;\n await options.onToolCall?.({\n name: \"submit_output\",\n input: output,\n output: { accepted: true },\n });\n }),\n ];\n\n const prompt = renderAgentPrompt(options.step.prompt, options.input);\n\n await adapter({\n messages: [{ role: \"user\", content: prompt }],\n tools,\n requirements: options.step.requirements,\n model,\n step: options.step,\n input: options.input,\n });\n\n if (submittedOutput === undefined) {\n throw new TrailStepFailureError({\n code: \"agent_output_missing\",\n message: `Agent step ${options.step.id} did not call submit_output.`,\n });\n }\n\n return submittedOutput;\n}\n\nexport function renderAgentPrompt<TInput extends PlainObject>(\n prompt: AgentPrompt<TInput>,\n input: TInput,\n): string {\n return typeof prompt === \"function\" ? prompt({ input }) : prompt;\n}\n\nexport function resolveAgentRequirements(\n requirements: AgentStepRequestConfig[\"requirements\"],\n): AgentModelTarget {\n return {\n adapterKey: PROVIDER_NEUTRAL_ADAPTER_KEY,\n model: requirements.name ?? requirements.size ?? PROVIDER_NEUTRAL_MODEL,\n };\n}\n\nfunction resolveAgentAdapter<TInput extends PlainObject, TOutput extends PlainObject = PlainObject>(\n selection: AgentAdapterSelection<TInput, TOutput> | undefined,\n): AgentAdapter<TInput, TOutput> {\n if (typeof selection === \"function\") {\n return selection;\n }\n\n if (typeof selection === \"object\" && selection !== null) {\n return (request) => selection.runAgentStep(request);\n }\n\n throw new TrailStepFailureError({\n code: \"agent_adapter_unavailable\",\n message:\n \"Agent steps that do not use a configured command runner require a custom adapter function or adapter object.\",\n });\n}\n\nfunction createSubmitOutputTool<TOutput extends PlainObject>(\n schema: Schema<TOutput>,\n onOutput: (output: TOutput) => void | Promise<void>,\n): AgentTool<TOutput> {\n return {\n name: \"submit_output\",\n description: \"Submit the typed output for this TrailStep agent step.\",\n schema,\n async call(input) {\n await onOutput(input);\n },\n };\n}\n","import { readFile } from \"node:fs/promises\";\nimport { resolve } from \"node:path\";\n\nimport type { TrailStepConfig } from \"../../agent-targeting/targeting.types.js\";\nimport type {\n ContinuationStepConfig,\n PromptTemplateSource,\n} from \"../../authoring/step/continuation.types.js\";\nimport type { AgentPrompt } from \"../../contracts/agents/agent-adapter.types.js\";\nimport type { WorkflowAgentRole } from \"../../contracts/agents/agent-role.types.js\";\nimport { TrailStepFailureError } from \"../../contracts/failures/failure.js\";\nimport type { PlainObject, Schema } from \"../../contracts/shapes/shape.types.js\";\nimport { resolveStepArtifactPaths } from \"../../runtime/artifacts/step-artifacts.js\";\nimport { createEvent } from \"../../runtime/events/create-run-event.js\";\nimport type { Event, RunWorkflowOptions } from \"../../runtime/run-workflow/run-workflow.types.js\";\nimport {\n renderAgentPrompt,\n runAgentStep,\n} from \"../adapter-agent/run-adapter-agent-step/run-adapter-agent-step.js\";\nimport { runInteractiveAgentCommand } from \"../interactive-agent/run-interactive-agent-command.js\";\nimport { runWorkingAgentCommand } from \"../working-agent/run-working-agent-command.js\";\n\n/**\n * Runs a `.prompt(...)` step's agent dispatch: resolves the workflow agent\n * role, renders the prompt, and executes it in adapter, working, or\n * interactive mode. Only called when `config.prompt` is defined — a step\n * with no prompt is never dispatched at all (see `runContinuation` in\n * `engine.ts`, which calls `stepNode.onOutput` directly on the step's input\n * in that case).\n */\nexport async function dispatchAgentStep(options: {\n readonly config: ContinuationStepConfig & {\n readonly prompt: NonNullable<ContinuationStepConfig[\"prompt\"]>;\n };\n readonly outputSchema: Schema;\n readonly interactiveOutputMode: \"session-file\" | \"json\";\n readonly runId: string;\n readonly workflowId: string;\n readonly emit: (event: Event) => Promise<void>;\n readonly workflowAgents: Readonly<Record<string, WorkflowAgentRole>>;\n readonly runDir: string;\n readonly cwd: string;\n readonly trailstepConfig: TrailStepConfig | undefined;\n readonly workingAgentProcessRunner: RunWorkflowOptions[\"workingAgentProcessRunner\"];\n readonly providerWorkingRunner: RunWorkflowOptions[\"providerWorkingRunner\"];\n readonly processRunner: RunWorkflowOptions[\"processRunner\"];\n readonly stepIndex: number;\n readonly signal?: AbortSignal;\n}): Promise<PlainObject> {\n const { config, outputSchema } = options;\n\n const resolvedRole = resolveWorkflowAgentRole({\n agent: config.agent,\n workflowAgents: options.workflowAgents,\n workflowId: options.workflowId,\n stepId: config.id,\n });\n\n const renderedPrompt = await resolvePromptSource(config.prompt, config.input, options.cwd);\n const agentMode = config.mode ?? \"working\";\n\n const agentStep = {\n kind: \"agent\" as const,\n id: config.id,\n output: outputSchema,\n prompt: renderedPrompt,\n requirements: resolvedRole.role,\n adapter: config.adapter,\n };\n\n if (!options.trailstepConfig && config.adapter === undefined) {\n throwMissingAgentConfig({\n workflowId: options.workflowId,\n stepId: config.id,\n agent: resolvedRole.roleName,\n mode: agentMode,\n });\n }\n\n if (options.trailstepConfig && agentMode === \"interactive\") {\n await options.emit(\n createEvent({\n runId: options.runId,\n workflowId: options.workflowId,\n stepId: config.id,\n type: \"interactive.sessionStarted\",\n payload: { roleName: resolvedRole.roleName, stepIndex: options.stepIndex },\n }),\n );\n const artifactPaths = resolveStepArtifactPaths({\n runDir: options.runDir,\n stepId: config.id,\n stepIndex: options.stepIndex,\n });\n const interactiveResult = await runInteractiveAgentCommand({\n config: options.trailstepConfig,\n workflowId: options.workflowId,\n roleName: resolvedRole.roleName,\n role: resolvedRole.role,\n stepId: config.id,\n renderedPrompt,\n runDir: options.runDir,\n runner: options.processRunner,\n outputSchema,\n outputMode: options.interactiveOutputMode,\n artifactPaths,\n signal: options.signal,\n });\n await options.emit(\n createEvent({\n runId: options.runId,\n workflowId: options.workflowId,\n stepId: config.id,\n type: \"interactive.sessionCompleted\",\n payload: {\n exitCode: interactiveResult.exitCode,\n outputMode: options.interactiveOutputMode,\n stepDir: artifactPaths.runRelativeStepDir,\n },\n }),\n );\n return interactiveResult.output;\n }\n\n return options.trailstepConfig && agentMode === \"working\"\n ? await runWorkingAgentCommand({\n config: options.trailstepConfig,\n workflowId: options.workflowId,\n roleName: resolvedRole.roleName,\n role: resolvedRole.role,\n step: agentStep,\n renderedPrompt,\n runDir: options.runDir,\n cwd: options.cwd,\n runner: options.workingAgentProcessRunner,\n providerWorkingRunner: options.providerWorkingRunner,\n stepIndex: options.stepIndex,\n signal: options.signal,\n })\n : await runAgentStep({\n step: agentStep,\n input: config.input,\n onToolCall: async (toolCall) => {\n await options.emit(\n createEvent({\n runId: options.runId,\n workflowId: options.workflowId,\n stepId: config.id,\n type: \"agent.toolCall\",\n payload: { ...toolCall },\n }),\n );\n },\n });\n}\n\n/**\n * Resolves a step's prompt source to a rendered string. A `promptTemplate(...)`\n * source is read from disk relative to the workflow's `cwd`; a thrown/rejected\n * read propagates up through the same try/catch that already wraps step\n * dispatch, so an unreadable file becomes a normal step failure. Any other\n * source (string or callback) renders synchronously via `renderAgentPrompt`.\n */\nexport async function resolvePromptSource<TInput extends PlainObject>(\n source: AgentPrompt<TInput> | PromptTemplateSource,\n input: TInput,\n cwd: string,\n): Promise<string> {\n if (isPromptTemplateSource(source)) {\n return await readFile(resolve(cwd, source.path), \"utf8\");\n }\n\n return renderAgentPrompt(source, input);\n}\n\nfunction isPromptTemplateSource(\n source: AgentPrompt<PlainObject> | PromptTemplateSource,\n): source is PromptTemplateSource {\n return typeof source === \"object\" && source !== null && source.kind === \"promptTemplate\";\n}\n\nfunction throwMissingAgentConfig(options: {\n readonly workflowId: string;\n readonly stepId: string;\n readonly agent: string;\n readonly mode: \"working\" | \"interactive\";\n}): never {\n throw new TrailStepFailureError({\n code: \"missing_agent_config\",\n message: `Missing .trailstep/config.json: workflow ${options.workflowId} step ${options.stepId} needs configured ${options.mode} agent '${options.agent}'.`,\n details: {\n workflowId: options.workflowId,\n stepId: options.stepId,\n agent: options.agent,\n mode: options.mode,\n },\n });\n}\n\nconst DEFAULT_AGENT_ROLE_NAME = \"default\";\n\nconst BUILTIN_DEFAULT_AGENT_ROLE: WorkflowAgentRole = { size: \"default\" };\n\n/**\n * A step's `.agent` is optional. With none given, falls back to\n * `workflow.agents.default` if the workflow declares one, else a builtin\n * `{ size: \"default\" }` role — which `resolveAgentTargets` in turn resolves\n * against `.trailstep/config.json`'s unified `agents.default` mapping. An explicit `.agent(...)` naming an undeclared\n * role is still a hard error (typo protection).\n */\nexport function resolveWorkflowAgentRole(options: {\n readonly agent: string | undefined;\n readonly workflowAgents: Readonly<Record<string, WorkflowAgentRole>>;\n readonly workflowId: string;\n readonly stepId: string;\n}): { readonly role: WorkflowAgentRole; readonly roleName: string } {\n const roleName = options.agent ?? DEFAULT_AGENT_ROLE_NAME;\n const role = options.workflowAgents[roleName];\n\n if (role) {\n return { role, roleName };\n }\n\n if (options.agent === undefined) {\n return { role: BUILTIN_DEFAULT_AGENT_ROLE, roleName: DEFAULT_AGENT_ROLE_NAME };\n }\n\n throw new TrailStepFailureError({\n code: \"agent_role_unknown\",\n message: `Step ${options.stepId} references unknown agent role '${options.agent}' in workflow ${options.workflowId}. Declare workflow.agents.${options.agent} before referencing it with step agent.`,\n details: {\n workflowId: options.workflowId,\n stepId: options.stepId,\n agent: options.agent,\n declaredAgents: Object.keys(options.workflowAgents),\n },\n });\n}\n","import { join } from \"node:path\";\n\nexport interface StepArtifactPaths {\n readonly artifactStepId: string;\n readonly stepDir: string;\n readonly promptFile: string;\n readonly outputFile: string;\n readonly usageFile: string;\n readonly interactiveFile: string;\n readonly sessionDescriptionFile: string;\n readonly runRelativeStepDir: string;\n readonly runRelativeSessionDescriptionFile: string;\n}\n\nexport function resolveStepArtifactPaths(options: {\n readonly runDir: string;\n readonly stepId: string;\n readonly stepIndex: number;\n}): StepArtifactPaths {\n const artifactStepId = `${String(options.stepIndex).padStart(4, \"0\")}-${sanitizeStepId(\n options.stepId,\n )}`;\n const runRelativeStepDir = `steps/${artifactStepId}`;\n const runRelativeSessionDescriptionFile = `${runRelativeStepDir}/session-description.md`;\n const stepDir = join(options.runDir, \"steps\", artifactStepId);\n\n return {\n artifactStepId,\n stepDir,\n promptFile: join(stepDir, \"prompt.txt\"),\n outputFile: join(stepDir, \"output.json\"),\n usageFile: join(stepDir, \"usage.json\"),\n interactiveFile: join(stepDir, \"interactive.json\"),\n sessionDescriptionFile: join(stepDir, \"session-description.md\"),\n runRelativeStepDir,\n runRelativeSessionDescriptionFile,\n };\n}\n\nfunction sanitizeStepId(stepId: string): string {\n return (\n stepId\n .trim()\n .toLowerCase()\n .replace(/[^a-z0-9_-]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\") || \"step\"\n );\n}\n","import { randomUUID } from \"node:crypto\";\n\nimport type { PlainObject } from \"../../contracts/shapes/shape.types.js\";\nimport type { Event } from \"../../runtime/run-workflow/run-workflow.types.js\";\n\nexport function createEvent(options: {\n readonly runId: string;\n readonly workflowId: string;\n readonly stepId?: string;\n readonly type: Event[\"type\"];\n readonly payload?: PlainObject;\n}): Event {\n return {\n id: `evt_${randomUUID()}`,\n runId: options.runId,\n workflowId: options.workflowId,\n stepId: options.stepId,\n type: options.type,\n timestamp: new Date().toISOString(),\n schemaVersion: \"v0\",\n payload: options.payload ?? {},\n };\n}\n","import { spawn } from \"node:child_process\";\nimport { mkdir, writeFile } from \"node:fs/promises\";\nimport { dirname } from \"node:path\";\nimport { resolveAgentTargets } from \"../../agent-targeting/resolve-agent-targets/resolve-agent-targets.js\";\nimport type {\n TrailStepAgentTarget,\n TrailStepConfig,\n} from \"../../agent-targeting/targeting.types.js\";\nimport type { WorkflowAgentRole } from \"../../contracts/agents/agent-role.types.js\";\nimport { TrailStepFailureError } from \"../../contracts/failures/failure.js\";\nimport type { PlainObject, Schema } from \"../../contracts/shapes/shape.types.js\";\nimport { providerRegistry } from \"../../known-cli-providers/registry/provider-registry.js\";\nimport type { StepArtifactPaths } from \"../../runtime/artifacts/step-artifacts.js\";\nimport {\n isInteractiveCompleted,\n readCompletedInteractiveOutput,\n waitForInteractiveCompletion,\n} from \"../../runtime/interactive-session/interactive-session-protocol.js\";\nimport type {\n InteractiveProcessResult,\n InteractiveProcessRunner,\n} from \"../../runtime/run-workflow/run-workflow.types.js\";\nimport { renderCustomProviderArgs } from \"../custom-provider/render-custom-provider-args.js\";\n\nexport async function runInteractiveAgentCommand(options: {\n readonly config: TrailStepConfig;\n readonly workflowId: string;\n readonly roleName: string;\n readonly role: WorkflowAgentRole;\n readonly stepId: string;\n readonly renderedPrompt: string;\n readonly runDir: string;\n readonly outputSchema: Schema;\n readonly artifactPaths: StepArtifactPaths;\n readonly outputMode: \"session-file\" | \"json\";\n readonly runner?: InteractiveProcessRunner;\n readonly signal?: AbortSignal;\n}): Promise<{ readonly exitCode: number; readonly output: PlainObject }> {\n const [target] = resolveAgentTargets({\n config: options.config,\n workflowId: options.workflowId,\n roleName: options.roleName,\n roleSize: options.role.size,\n });\n\n if (!target) {\n throw new TrailStepFailureError({\n code: \"agent_targets_unavailable\",\n message: `No interactive agent targets found for role ${options.roleName} with size ${options.role.size} in workflow ${options.workflowId}.`,\n });\n }\n\n return await runInteractiveAgentTarget({ ...options, target });\n}\n\nasync function runInteractiveAgentTarget(options: {\n readonly config: TrailStepConfig;\n readonly workflowId: string;\n readonly roleName: string;\n readonly role: WorkflowAgentRole;\n readonly stepId: string;\n readonly renderedPrompt: string;\n readonly runDir: string;\n readonly outputSchema: Schema;\n readonly artifactPaths: StepArtifactPaths;\n readonly outputMode: \"session-file\" | \"json\";\n readonly runner?: InteractiveProcessRunner;\n readonly target: TrailStepAgentTarget;\n readonly signal?: AbortSignal;\n}): Promise<{ readonly exitCode: number; readonly output: PlainObject }> {\n const files = options.artifactPaths;\n await prepareInteractiveArtifacts({\n files,\n runDir: options.runDir,\n stepId: options.stepId,\n outputSchema: options.outputSchema,\n outputMode: options.outputMode,\n });\n const prompt = buildInteractivePrompt({\n renderedPrompt: options.renderedPrompt,\n files,\n outputSchema: options.outputSchema,\n outputMode: options.outputMode,\n });\n const env = { ...definedProcessEnv(), TRAILSTEP_INTERACTIVE_FILE: files.interactiveFile };\n\n const abortController = new AbortController();\n options.signal?.addEventListener(\"abort\", () => abortController.abort(), { once: true });\n\n const provider = providerRegistry[options.target.provider as keyof typeof providerRegistry];\n if (provider) {\n return await runProcessUntilExitOrCompletion({\n stepId: options.stepId,\n target: options.target.provider,\n interactiveFile: files.interactiveFile,\n abortController,\n readOutput: async () => await readCompletedOutput(options),\n runProcess: async () => {\n await writeFile(files.promptFile, prompt, \"utf8\");\n return await provider.runInteractive(\n {\n prompt,\n systemPromptFile: files.promptFile,\n cwd: files.stepDir,\n env,\n signal: abortController.signal,\n ...(options.target.model === undefined ? {} : { model: options.target.model }),\n ...(options.target.permissionMode === undefined\n ? {}\n : { permissionMode: options.target.permissionMode }),\n },\n options.runner,\n );\n },\n });\n }\n\n const agentConfig = options.config.customProviders[options.target.provider];\n if (!agentConfig) {\n throw new TrailStepFailureError({\n code: \"agent_provider_unavailable\",\n message: `Interactive agent target '${options.target.provider}' does not reference a configured custom agent.`,\n details: { provider: options.target.provider },\n });\n }\n\n if (!agentConfig.interactiveArgs) {\n throw new TrailStepFailureError({\n code: \"agent_provider_interactive_unsupported\",\n message: `Custom provider '${options.target.provider}' cannot run interactive agent steps because customProviders.${options.target.provider}.interactiveArgs is not declared.`,\n details: { provider: options.target.provider },\n });\n }\n\n const thinking = options.target.thinking ?? options.role.thinking;\n const args = renderCustomProviderArgs({\n argv: options.target.args ?? agentConfig.interactiveArgs,\n values: {\n prompt,\n promptFile: files.promptFile,\n ...(options.target.model === undefined ? {} : { model: options.target.model }),\n ...(thinking === undefined ? {} : { thinking }),\n },\n errorCode: \"interactive_command_invalid\",\n commandDescription: \"Interactive agent command\",\n });\n\n if (args.includes(files.promptFile)) {\n await mkdir(dirname(files.promptFile), { recursive: true });\n await writeFile(files.promptFile, prompt, \"utf8\");\n }\n\n return await runProcessUntilExitOrCompletion({\n stepId: options.stepId,\n target: options.target.provider,\n interactiveFile: files.interactiveFile,\n abortController,\n readOutput: async () => await readCompletedOutput(options),\n mapSpawnError: (error) =>\n new TrailStepFailureError({\n code: \"interactive_command_spawn_error\",\n message: `Interactive agent step ${options.stepId} could not start target '${options.target.provider}'.`,\n details: {\n target: options.target.provider,\n ...(options.target.model === undefined ? {} : { model: options.target.model }),\n cause: error instanceof Error ? error.message : String(error),\n },\n }),\n runProcess: async () =>\n await (options.runner ?? spawnInteractiveProcess)({\n command: agentConfig.binary,\n args,\n cwd: files.stepDir,\n shell: false,\n stdio: \"inherit\",\n env,\n signal: abortController.signal,\n }),\n });\n}\n\nfunction definedProcessEnv(): Record<string, string> {\n return Object.fromEntries(\n Object.entries(process.env).filter(\n (entry): entry is [string, string] => entry[1] !== undefined,\n ),\n );\n}\n\nasync function runProcessUntilExitOrCompletion(options: {\n readonly stepId: string;\n readonly target: string;\n readonly interactiveFile: string;\n readonly abortController: AbortController;\n readonly runProcess: () => Promise<InteractiveProcessResult>;\n readonly readOutput: () => Promise<PlainObject>;\n readonly mapSpawnError?: (error: unknown) => TrailStepFailureError;\n}): Promise<{ readonly exitCode: number; readonly output: PlainObject }> {\n const processPromise = options.runProcess();\n void processPromise.catch(() => undefined);\n const watcherAbortController = new AbortController();\n\n const winner = await Promise.race<\n | { readonly type: \"completed\" }\n | { readonly type: \"process\"; readonly result: InteractiveProcessResult }\n | { readonly type: \"processError\"; readonly error: unknown }\n >([\n processPromise.then(\n (result) => ({ type: \"process\", result }) as const,\n (error) => ({ type: \"processError\", error }) as const,\n ),\n waitForInteractiveCompletion(options.interactiveFile, watcherAbortController.signal).then(\n () => ({ type: \"completed\" }) as const,\n ),\n ]);\n\n watcherAbortController.abort();\n\n if (winner.type === \"processError\") {\n throw options.mapSpawnError?.(winner.error) ?? winner.error;\n }\n\n if (winner.type === \"process\") {\n if (await isInteractiveCompleted(options.interactiveFile)) {\n return { exitCode: 0, output: await options.readOutput() };\n }\n\n if (winner.result.exitCode !== 0) {\n throw new TrailStepFailureError({\n code: \"interactive_session_failed\",\n message: `Interactive agent step ${options.stepId} exited with code ${winner.result.exitCode}.`,\n details: { exitCode: winner.result.exitCode, target: options.target },\n });\n }\n\n return { exitCode: winner.result.exitCode, output: await options.readOutput() };\n }\n\n options.abortController.abort();\n return { exitCode: 0, output: await options.readOutput() };\n}\n\nasync function prepareInteractiveArtifacts(options: {\n readonly files: StepArtifactPaths;\n readonly runDir: string;\n readonly stepId: string;\n readonly outputSchema: Schema;\n readonly outputMode: \"session-file\" | \"json\";\n}): Promise<void> {\n await mkdir(options.files.stepDir, { recursive: true });\n await writeFile(\n options.files.interactiveFile,\n `${JSON.stringify(\n {\n status: \"active\",\n stepId: options.stepId,\n artifactStepId: options.files.artifactStepId,\n outputMode: options.outputMode,\n runDir: options.runDir,\n stepDir: options.files.stepDir,\n promptFile: options.files.promptFile,\n outputFile: options.files.outputFile,\n interactiveFile: options.files.interactiveFile,\n ...(options.outputMode === \"session-file\"\n ? {\n sessionDescriptionFile: options.files.sessionDescriptionFile,\n runRelativeSessionDescriptionFile: options.files.runRelativeSessionDescriptionFile,\n }\n : {}),\n runRelativeStepDir: options.files.runRelativeStepDir,\n outputSchema: options.outputSchema.jsonSchema,\n },\n null,\n 2,\n )}\\n`,\n \"utf8\",\n );\n}\n\nfunction buildInteractivePrompt(options: {\n readonly renderedPrompt: string;\n readonly files: StepArtifactPaths;\n readonly outputSchema: Schema;\n readonly outputMode: \"session-file\" | \"json\";\n}): string {\n const preamble =\n options.outputMode === \"session-file\"\n ? [\n \"You are running inside a TrailStep interactive step.\",\n \"Write a dense session description to session-description.md in the current directory.\",\n \"preserve as much usable context as possible.\",\n \"describe the conversation rather than aggressively summarize it.\",\n \"include decisions, rejected options, tradeoffs, constraints, side comments, terminology, open questions, assumptions, file paths, commands, APIs, package names, examples, preferences, reasoning, and abandoned options.\",\n \"The goal is context preservation, not polish.\",\n \"Do not omit low-importance details merely because they seem minor.\",\n \"When complete, run: trailstep continue --session-file session-description.md\",\n ]\n : [\n \"You are running inside a TrailStep interactive step.\",\n \"Submit a JSON object matching this schema:\",\n JSON.stringify(options.outputSchema.jsonSchema, null, 2),\n \"When complete, run one of:\",\n \" trailstep continue --json-file output.json\",\n ` trailstep continue --json '${JSON.stringify(exampleJsonObject(options.outputSchema.jsonSchema))}'`,\n \"If validation fails, update the JSON so it matches the schema and run trailstep continue again.\",\n ];\n\n return [...preamble, \"\", \"## Original prompt\", options.renderedPrompt].join(\"\\n\");\n}\n\nasync function readCompletedOutput(options: {\n readonly stepId: string;\n readonly artifactPaths: StepArtifactPaths;\n readonly outputSchema: Schema;\n}): Promise<PlainObject> {\n return await readCompletedInteractiveOutput({\n stepId: options.stepId,\n interactiveFile: options.artifactPaths.interactiveFile,\n outputSchema: options.outputSchema,\n });\n}\n\nfunction exampleJsonObject(schema: Record<string, unknown>): Record<string, unknown> {\n const properties =\n typeof schema.properties === \"object\" &&\n schema.properties !== null &&\n !Array.isArray(schema.properties)\n ? (schema.properties as Record<string, unknown>)\n : {};\n\n return Object.fromEntries(\n Object.entries(properties).map(([key, property]) => {\n const type =\n typeof property === \"object\" && property !== null && \"type\" in property\n ? (property as { readonly type?: unknown }).type\n : undefined;\n if (type === \"boolean\") {\n return [key, true];\n }\n if (type === \"number\") {\n return [key, 1];\n }\n return [key, \"string\"];\n }),\n );\n}\n\nconst spawnInteractiveProcess: InteractiveProcessRunner = async ({\n command,\n args,\n cwd,\n env,\n signal,\n}) => {\n return await new Promise((resolve, reject) => {\n const child = spawn(command, args, {\n cwd,\n env,\n signal,\n detached: process.platform !== \"win32\",\n shell: false,\n stdio: \"inherit\",\n });\n\n signal?.addEventListener(\"abort\", () => terminateChildProcessTree(child), { once: true });\n child.on(\"error\", reject);\n child.on(\"close\", (code) => resolve({ exitCode: code ?? 1 }));\n });\n};\n\nfunction terminateChildProcessTree(child: ReturnType<typeof spawn>): void {\n if (!child.pid) {\n return;\n }\n\n if (process.platform === \"win32\") {\n spawn(\"taskkill\", [\"/PID\", String(child.pid), \"/T\", \"/F\"], { stdio: \"ignore\" }).on(\n \"error\",\n () => {\n child.kill();\n },\n );\n return;\n }\n\n try {\n process.kill(-child.pid, \"SIGTERM\");\n } catch {\n child.kill();\n }\n}\n","import { readFile } from \"node:fs/promises\";\nimport { setTimeout as delay } from \"node:timers/promises\";\n\nimport { TrailStepFailureError } from \"../../contracts/failures/failure.js\";\nimport type { PlainObject, Schema } from \"../../contracts/shapes/shape.types.js\";\n\nexport async function waitForInteractiveCompletion(\n interactiveFile: string,\n signal: AbortSignal,\n): Promise<void> {\n while (!signal.aborted) {\n if (await isInteractiveCompleted(interactiveFile)) {\n return;\n }\n\n await delay(100, undefined, { signal }).catch(() => undefined);\n }\n}\n\nexport async function isInteractiveCompleted(interactiveFile: string): Promise<boolean> {\n try {\n const protocol = await readPlainJsonFile(interactiveFile, {\n readCode: \"interactive_session_invalid\",\n invalidCode: \"interactive_session_invalid\",\n message: \"Interactive session protocol file is invalid.\",\n });\n return protocol.status === \"completed\" || protocol.status === \"cancelled\";\n } catch {\n // The process-exit path reports authoritative protocol validation errors.\n // The watcher is intentionally best-effort and only needs to notice completion.\n return false;\n }\n}\n\nexport async function readCompletedInteractiveOutput(options: {\n readonly stepId: string;\n readonly interactiveFile: string;\n readonly outputSchema: Schema;\n}): Promise<PlainObject> {\n const protocol = await readPlainJsonFile(options.interactiveFile, {\n readCode: \"interactive_session_invalid\",\n invalidCode: \"interactive_session_invalid\",\n message: `Interactive agent step ${options.stepId} has an invalid interactive.json file.`,\n });\n\n if (protocol.status === \"cancelled\") {\n throw new TrailStepFailureError({\n code: \"interactive_session_cancelled\",\n message: `Interactive agent step ${options.stepId} was cancelled.`,\n details: {\n status: protocol.status,\n ...(typeof protocol.reason === \"string\" ? { reason: protocol.reason } : {}),\n },\n });\n }\n\n if (protocol.status !== \"completed\") {\n throw new TrailStepFailureError({\n code: \"interactive_session_incomplete\",\n message: `Interactive agent step ${options.stepId} did not complete the file-based protocol.`,\n details: { status: protocol.status },\n });\n }\n\n const outputFile = requireProtocolString(protocol.outputFile, \"outputFile\", options.stepId);\n const output = await readPlainJsonFile(outputFile, {\n readCode: \"interactive_output_missing\",\n invalidCode: \"interactive_output_invalid\",\n message: `Interactive agent step ${options.stepId} completed without a valid output.json file.`,\n });\n\n const diagnostics = options.outputSchema.diagnostics(output);\n if (diagnostics.length > 0) {\n throw new TrailStepFailureError({\n code: \"interactive_output_invalid\",\n message: `Interactive agent step ${options.stepId} output.json failed schema validation: ${formatDiagnostics(diagnostics)}`,\n details: { diagnostics },\n });\n }\n\n return output;\n}\n\nasync function readPlainJsonFile(\n path: string,\n failure: {\n readonly readCode: string;\n readonly invalidCode: string;\n readonly message: string;\n },\n): Promise<PlainObject> {\n let contents: string;\n try {\n contents = await readFile(path, \"utf8\");\n } catch (error) {\n throw new TrailStepFailureError({\n code: failure.readCode,\n message: failure.message,\n details: { path, cause: error instanceof Error ? error.message : String(error) },\n });\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(contents);\n } catch (error) {\n throw new TrailStepFailureError({\n code: failure.invalidCode,\n message: failure.message,\n details: { path, cause: error instanceof Error ? error.message : String(error) },\n });\n }\n\n if (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) {\n throw new TrailStepFailureError({\n code: failure.invalidCode,\n message: `${failure.message} Expected a plain JSON object.`,\n details: { path },\n });\n }\n\n return parsed as PlainObject;\n}\n\nfunction requireProtocolString(value: unknown, field: string, stepId: string): string {\n if (typeof value === \"string\" && value.length > 0) {\n return value;\n }\n\n throw new TrailStepFailureError({\n code: \"interactive_session_invalid\",\n message: `Interactive agent step ${stepId} interactive.json is missing ${field}.`,\n });\n}\n\nfunction formatDiagnostics(\n diagnostics: readonly { readonly path: string; readonly message: string }[],\n): string {\n return diagnostics.map((diagnostic) => `${diagnostic.path} ${diagnostic.message}`).join(\"; \");\n}\n","import type { WorkflowAgentThinking } from \"../../contracts/agents/agent-role.types.js\";\nimport { TrailStepFailureError } from \"../../contracts/failures/failure.js\";\n\ntype PlaceholderName = \"prompt\" | \"promptFile\" | \"outputFile\" | \"model\" | \"thinking\";\ntype ConditionalName = \"model\" | \"thinking\";\n\ntype PlaceholderValues = Readonly<Partial<Record<PlaceholderName, string>>>;\n\nconst PLACEHOLDER_NAMES = new Set<PlaceholderName>([\n \"prompt\",\n \"promptFile\",\n \"outputFile\",\n \"model\",\n \"thinking\",\n]);\nconst CONDITIONAL_NAMES = new Set<ConditionalName>([\"model\", \"thinking\"]);\nconst TEMPLATE_TOKEN_PATTERN = /^{{([#/]?)([A-Za-z][A-Za-z0-9]*)}}$/;\n\nexport function renderCustomProviderArgs(options: {\n readonly argv: readonly string[];\n readonly values: {\n readonly prompt?: string;\n readonly promptFile?: string;\n readonly outputFile?: string;\n readonly model?: string;\n readonly thinking?: WorkflowAgentThinking;\n };\n readonly errorCode: string;\n readonly commandDescription: string;\n}): string[] {\n const values: PlaceholderValues = {\n ...(options.values.prompt === undefined ? {} : { prompt: options.values.prompt }),\n ...(options.values.promptFile === undefined ? {} : { promptFile: options.values.promptFile }),\n ...(options.values.outputFile === undefined ? {} : { outputFile: options.values.outputFile }),\n ...(optionalNonEmptyString(options.values.model) === undefined\n ? {}\n : { model: optionalNonEmptyString(options.values.model) }),\n ...(options.values.thinking === undefined ? {} : { thinking: options.values.thinking }),\n };\n\n return renderRange({\n argv: options.argv,\n values,\n errorCode: options.errorCode,\n commandDescription: options.commandDescription,\n });\n}\n\nfunction renderRange(options: {\n readonly argv: readonly string[];\n readonly values: PlaceholderValues;\n readonly errorCode: string;\n readonly commandDescription: string;\n}): string[] {\n const rendered: string[] = [];\n\n for (let index = 0; index < options.argv.length; index += 1) {\n const arg = options.argv[index] ?? \"\";\n const token = parseTemplateToken(arg);\n\n if (token?.kind === \"open\") {\n const closeIndex = findConditionalClose({\n argv: options.argv,\n openIndex: index,\n condition: token.name,\n errorCode: options.errorCode,\n commandDescription: options.commandDescription,\n });\n if (options.values[token.name] !== undefined) {\n rendered.push(\n ...renderRange({\n ...options,\n argv: options.argv.slice(index + 1, closeIndex),\n }),\n );\n }\n index = closeIndex;\n continue;\n }\n\n if (token?.kind === \"close\") {\n throw templateError({\n code: options.errorCode,\n message: `${options.commandDescription} template has unexpected ${closingToken(token.name)} without a matching ${openingToken(token.name)}.`,\n });\n }\n\n if (token?.kind === \"placeholder\") {\n rendered.push(renderPlaceholder({ ...options, name: token.name }));\n continue;\n }\n\n if (TEMPLATE_TOKEN_PATTERN.test(arg)) {\n throw templateError({\n code: options.errorCode,\n message: `${options.commandDescription} template token ${arg} is not supported.`,\n details: { arg },\n });\n }\n\n if (arg.includes(\"{{\") || arg.includes(\"}}\")) {\n throw templateError({\n code: options.errorCode,\n message: `${options.commandDescription} placeholders and conditional blocks must be whole argv values.`,\n details: { arg },\n });\n }\n\n rendered.push(arg);\n }\n\n return rendered;\n}\n\nfunction parseTemplateToken(\n arg: string,\n):\n | { readonly kind: \"placeholder\"; readonly name: PlaceholderName }\n | { readonly kind: \"open\"; readonly name: ConditionalName }\n | { readonly kind: \"close\"; readonly name: ConditionalName }\n | undefined {\n const match = TEMPLATE_TOKEN_PATTERN.exec(arg);\n if (!match) {\n return undefined;\n }\n\n const prefix = match[1] ?? \"\";\n const name = match[2] ?? \"\";\n\n if (prefix === \"\") {\n if (PLACEHOLDER_NAMES.has(name as PlaceholderName)) {\n return { kind: \"placeholder\", name: name as PlaceholderName };\n }\n return undefined;\n }\n\n if (CONDITIONAL_NAMES.has(name as ConditionalName)) {\n return {\n kind: prefix === \"#\" ? \"open\" : \"close\",\n name: name as ConditionalName,\n };\n }\n\n return undefined;\n}\n\nfunction findConditionalClose(options: {\n readonly argv: readonly string[];\n readonly openIndex: number;\n readonly condition: ConditionalName;\n readonly errorCode: string;\n readonly commandDescription: string;\n}): number {\n let depth = 1;\n\n for (let index = options.openIndex + 1; index < options.argv.length; index += 1) {\n const token = parseTemplateToken(options.argv[index] ?? \"\");\n if (token?.name !== options.condition) {\n continue;\n }\n\n if (token.kind === \"open\") {\n depth += 1;\n continue;\n }\n\n if (token.kind === \"close\") {\n depth -= 1;\n if (depth === 0) {\n return index;\n }\n }\n }\n\n throw templateError({\n code: options.errorCode,\n message: `${options.commandDescription} template is missing ${closingToken(options.condition)} for ${openingToken(options.condition)}.`,\n });\n}\n\nfunction renderPlaceholder(options: {\n readonly name: PlaceholderName;\n readonly values: PlaceholderValues;\n readonly errorCode: string;\n readonly commandDescription: string;\n}): string {\n const value = options.values[options.name];\n if (value !== undefined) {\n return value;\n }\n\n if (options.name === \"model\" || options.name === \"thinking\") {\n throw templateError({\n code: options.errorCode,\n message: `${options.commandDescription} placeholder ${placeholderToken(options.name)} must be guarded with ${openingToken(options.name)} ... ${closingToken(options.name)} when no ${options.name} override is set.`,\n details: { placeholder: placeholderToken(options.name) },\n });\n }\n\n throw templateError({\n code: options.errorCode,\n message: `${options.commandDescription} placeholder ${placeholderToken(options.name)} is not available in this command template.`,\n details: { placeholder: placeholderToken(options.name) },\n });\n}\n\nfunction templateError(options: {\n readonly code: string;\n readonly message: string;\n readonly details?: unknown;\n}): TrailStepFailureError {\n return new TrailStepFailureError({\n code: options.code,\n message: options.message,\n ...(options.details === undefined ? {} : { details: options.details }),\n });\n}\n\nfunction placeholderToken(name: PlaceholderName): string {\n return `{{${name}}}`;\n}\n\nfunction openingToken(name: ConditionalName): string {\n return `{{#${name}}}`;\n}\n\nfunction closingToken(name: ConditionalName): string {\n return `{{/${name}}}`;\n}\n\nfunction optionalNonEmptyString(value: string | undefined): string | undefined {\n if (value === undefined || value.trim().length === 0) {\n return undefined;\n }\n\n return value;\n}\n","import { mkdir, writeFile } from \"node:fs/promises\";\n\nimport { resolveAgentTargets } from \"../../agent-targeting/resolve-agent-targets/resolve-agent-targets.js\";\nimport type { TrailStepConfig } from \"../../agent-targeting/targeting.types.js\";\nimport type { AgentStepRequestConfig } from \"../../authoring/step/agent-step.types.js\";\nimport type { WorkflowAgentRole } from \"../../contracts/agents/agent-role.types.js\";\nimport { TrailStepFailureError } from \"../../contracts/failures/failure.js\";\nimport type { PlainObject } from \"../../contracts/shapes/shape.types.js\";\nimport type { ProviderWorkingRunner } from \"../../known-cli-providers/registry/provider-registry.types.js\";\nimport type { WorkingAgentProcessRunner } from \"../../runtime/run-workflow/run-workflow.types.js\";\nimport {\n resolveStepAgentFiles,\n type WorkingAgentFiles,\n} from \"./artifacts/resolve-step-agent-files.js\";\nimport { buildWorkingAgentPrompt } from \"./prompts/build-working-agent-prompt.js\";\nimport { runWorkingAgentTargetAttempt } from \"./targets/run-working-agent-target-attempt.js\";\nimport {\n summarizeWorkingAgentAttemptFailure,\n type WorkingAgentAttemptFailure,\n} from \"./targets/target-failures.js\";\n\nexport type { WorkingAgentFiles } from \"./artifacts/resolve-step-agent-files.js\";\n\nexport async function runWorkingAgentCommand<TOutput extends PlainObject>(options: {\n readonly config: TrailStepConfig;\n readonly workflowId: string;\n readonly roleName: string;\n readonly role: WorkflowAgentRole;\n readonly step: AgentStepRequestConfig<PlainObject, TOutput>;\n readonly renderedPrompt: string;\n readonly runDir: string;\n readonly cwd: string;\n readonly runner?: WorkingAgentProcessRunner;\n readonly providerWorkingRunner?: ProviderWorkingRunner;\n readonly stepIndex: number;\n readonly files?: WorkingAgentFiles;\n readonly signal?: AbortSignal;\n}): Promise<TOutput> {\n const targets = resolveAgentTargets({\n config: options.config,\n workflowId: options.workflowId,\n roleName: options.roleName,\n roleSize: options.role.size,\n });\n\n const files =\n options.files ??\n resolveStepAgentFiles({\n runDir: options.runDir,\n stepId: options.step.id,\n stepIndex: options.stepIndex,\n });\n await mkdir(files.stepDir, { recursive: true });\n await writeFile(\n files.promptFile,\n buildWorkingAgentPrompt({\n prompt: options.renderedPrompt,\n outputFile: files.outputFile,\n outputSchema: options.step.output.jsonSchema,\n captureMode: options.step.output.captureMode,\n }),\n \"utf8\",\n );\n\n const failures: WorkingAgentAttemptFailure[] = [];\n\n for (const target of targets) {\n try {\n return await runWorkingAgentTargetAttempt({ ...options, target, files });\n } catch (error) {\n failures.push(summarizeWorkingAgentAttemptFailure(target, error));\n }\n }\n\n throw new TrailStepFailureError({\n code: \"agent_target_exhausted\",\n message: `Working agent step ${options.step.id} for role ${options.roleName} exhausted ${failures.length} target(s).`,\n details: {\n stepId: options.step.id,\n roleName: options.roleName,\n attempts: failures,\n },\n });\n}\n","import { join } from \"node:path\";\n\nimport { resolveStepArtifactPaths } from \"../../../runtime/artifacts/step-artifacts.js\";\n\nexport interface WorkingAgentFiles {\n readonly stepDir: string;\n readonly promptFile: string;\n readonly outputFile: string;\n readonly usageFile: string;\n}\n\nexport function resolveStepAgentFiles(options: {\n readonly runDir: string;\n readonly stepId: string;\n readonly stepIndex: number;\n}): WorkingAgentFiles {\n const artifactPaths = resolveStepArtifactPaths(options);\n return {\n stepDir: artifactPaths.stepDir,\n promptFile: join(artifactPaths.stepDir, \"prompt.md\"),\n outputFile: artifactPaths.outputFile,\n usageFile: artifactPaths.usageFile,\n };\n}\n","export function buildWorkingAgentPrompt(options: {\n readonly prompt: string;\n readonly outputFile: string;\n readonly outputSchema: Record<string, unknown>;\n readonly captureMode?: \"json\" | \"raw-text\";\n}): string {\n if (options.captureMode === \"raw-text\") {\n return [\n \"# TrailStep working-agent task\",\n \"\",\n \"Run the task described below and write the document content to the output file.\",\n \"Print the document content directly as your entire response — no JSON wrapper, no surrounding commentary, no markdown fences unless they are literally part of the document content itself.\",\n \"\",\n `Output file: ${options.outputFile}`,\n \"\",\n \"## Original prompt\",\n \"\",\n options.prompt,\n \"\",\n ].join(\"\\n\");\n }\n\n return [\n \"# TrailStep working-agent task\",\n \"\",\n \"Run the task described below and write exactly one JSON object to the output file.\",\n \"Do not write prose, markdown fences, or multiple JSON values to the output file.\",\n \"\",\n `Output file: ${options.outputFile}`,\n \"\",\n \"The JSON object must match this output schema:\",\n \"\",\n \"```json\",\n JSON.stringify(options.outputSchema, null, 2),\n \"```\",\n \"\",\n \"## Original prompt\",\n \"\",\n options.prompt,\n \"\",\n ].join(\"\\n\");\n}\n","import { rm } from \"node:fs/promises\";\n\nimport type {\n TrailStepAgentTarget,\n TrailStepConfig,\n} from \"../../../agent-targeting/targeting.types.js\";\nimport type { AgentStepRequestConfig } from \"../../../authoring/step/agent-step.types.js\";\nimport type { WorkflowAgentRole } from \"../../../contracts/agents/agent-role.types.js\";\nimport type { PlainObject } from \"../../../contracts/shapes/shape.types.js\";\nimport { providerRegistry } from \"../../../known-cli-providers/registry/provider-registry.js\";\nimport type { ProviderWorkingRunner } from \"../../../known-cli-providers/registry/provider-registry.types.js\";\nimport type { WorkingAgentProcessRunner } from \"../../../runtime/run-workflow/run-workflow.types.js\";\nimport type { WorkingAgentFiles } from \"../artifacts/resolve-step-agent-files.js\";\nimport { runCustomWorkingProvider } from \"./custom-provider/run-custom-working-provider.js\";\nimport { runRegistryWorkingProvider } from \"./registry-provider/run-registry-working-provider.js\";\n\nexport async function runWorkingAgentTargetAttempt<TOutput extends PlainObject>(options: {\n readonly config: TrailStepConfig;\n readonly workflowId: string;\n readonly roleName: string;\n readonly role: WorkflowAgentRole;\n readonly step: AgentStepRequestConfig<PlainObject, TOutput>;\n readonly renderedPrompt: string;\n readonly runDir: string;\n readonly cwd: string;\n readonly runner?: WorkingAgentProcessRunner;\n readonly providerWorkingRunner?: ProviderWorkingRunner;\n readonly stepIndex: number;\n readonly target: TrailStepAgentTarget;\n readonly files: WorkingAgentFiles;\n readonly signal?: AbortSignal;\n}): Promise<TOutput> {\n await rm(options.files.outputFile, { force: true });\n await rm(options.files.usageFile, { force: true });\n\n const provider = providerRegistry[options.target.provider as keyof typeof providerRegistry];\n if (provider) {\n return runRegistryWorkingProvider({\n provider,\n role: options.role,\n step: options.step,\n renderedPrompt: options.renderedPrompt,\n cwd: options.cwd,\n providerWorkingRunner: options.providerWorkingRunner,\n target: options.target,\n files: options.files,\n signal: options.signal,\n });\n }\n\n return runCustomWorkingProvider({\n config: options.config,\n step: options.step,\n role: options.role,\n cwd: options.cwd,\n runner: options.runner,\n target: options.target,\n files: options.files,\n signal: options.signal,\n });\n}\n","import { readFile } from \"node:fs/promises\";\n\nimport { document } from \"../../../authoring/document/document.js\";\nimport type { AgentStepRequestConfig } from \"../../../authoring/step/agent-step.types.js\";\nimport { TrailStepFailureError } from \"../../../contracts/failures/failure.js\";\nimport type { PlainObject } from \"../../../contracts/shapes/shape.types.js\";\n\nexport async function readWorkingAgentOutput<TOutput extends PlainObject>(options: {\n readonly stepId: string;\n readonly outputFile: string;\n readonly step: AgentStepRequestConfig<PlainObject, TOutput>;\n}): Promise<TOutput> {\n let raw: string;\n try {\n raw = await readFile(options.outputFile, \"utf8\");\n } catch (error) {\n throw new TrailStepFailureError({\n code: \"agent_output_unreadable\",\n message: `Working agent step ${options.stepId} output.json could not be read.`,\n details:\n error instanceof Error\n ? { path: options.outputFile, cause: error.message }\n : { path: options.outputFile },\n });\n }\n\n if (options.step.output.captureMode === \"raw-text\") {\n // Delegates to the shared `document(...)` capture path (the same one\n // code-authored steps use), so agent-captured and code-captured\n // documents share one persistence implementation. `document(...)`\n // resolves its target directory and index from the ambient step\n // context (`currentStep`), which is active for the whole duration of\n // this step's dispatch (see `withStepContext` in run-continuation.ts).\n const capturedDocument = await document(raw);\n\n return options.step.output.assert(capturedDocument, `step ${options.stepId} output`);\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch (error) {\n throw new TrailStepFailureError({\n code: \"agent_output_invalid_json\",\n message: `Working agent step ${options.stepId} output.json must contain one JSON object.`,\n details:\n error instanceof Error\n ? { path: options.outputFile, cause: error.message }\n : { path: options.outputFile },\n });\n }\n\n if (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) {\n throw new TrailStepFailureError({\n code: \"agent_output_invalid_json\",\n message: `Working agent step ${options.stepId} output.json must contain one JSON object.`,\n details: { path: options.outputFile },\n });\n }\n\n return options.step.output.assert(parsed, `step ${options.stepId} output`);\n}\n","import type { WorkflowAgentThinking } from \"../../../../contracts/agents/agent-role.types.js\";\nimport { renderCustomProviderArgs } from \"../../../custom-provider/render-custom-provider-args.js\";\n\nexport function buildWorkingAgentArgs(options: {\n readonly argv: readonly string[] | undefined;\n readonly promptFile: string;\n readonly outputFile: string;\n readonly model?: string;\n readonly thinking?: WorkflowAgentThinking;\n}): string[] {\n if (!options.argv) {\n return [\n \"--prompt-file\",\n options.promptFile,\n \"--output-file\",\n options.outputFile,\n ...(options.model ? [\"--model\", options.model] : []),\n ];\n }\n\n return renderCustomProviderArgs({\n argv: options.argv,\n values: {\n promptFile: options.promptFile,\n outputFile: options.outputFile,\n ...(options.model === undefined ? {} : { model: options.model }),\n ...(options.thinking === undefined ? {} : { thinking: options.thinking }),\n },\n errorCode: \"agent_provider_invalid\",\n commandDescription: \"Working agent command\",\n });\n}\n","import { spawn } from \"node:child_process\";\n\nimport type { WorkingAgentProcessRunner } from \"../../../../runtime/run-workflow/run-workflow.types.js\";\n\nexport const spawnWorkingAgentProcess: WorkingAgentProcessRunner = async ({\n command,\n args,\n cwd,\n signal,\n}) => {\n return await new Promise((resolve, reject) => {\n const child = spawn(command, args, {\n cwd,\n shell: false,\n stdio: \"inherit\",\n detached: process.platform !== \"win32\",\n });\n\n signal?.addEventListener(\"abort\", () => terminateChildProcessTree(child), { once: true });\n child.on(\"error\", reject);\n child.on(\"close\", (code) => resolve({ exitCode: code ?? 1 }));\n });\n};\n\nfunction terminateChildProcessTree(child: ReturnType<typeof spawn>): void {\n if (!child.pid) {\n return;\n }\n\n if (process.platform === \"win32\") {\n spawn(\"taskkill\", [\"/PID\", String(child.pid), \"/T\", \"/F\"], { stdio: \"ignore\" }).on(\n \"error\",\n () => {\n child.kill();\n },\n );\n return;\n }\n\n try {\n process.kill(-child.pid, \"SIGTERM\");\n } catch {\n child.kill();\n }\n}\n","import type {\n TrailStepAgentTarget,\n TrailStepConfig,\n} from \"../../../../agent-targeting/targeting.types.js\";\nimport type { AgentStepRequestConfig } from \"../../../../authoring/step/agent-step.types.js\";\nimport type { WorkflowAgentRole } from \"../../../../contracts/agents/agent-role.types.js\";\nimport { TrailStepFailureError } from \"../../../../contracts/failures/failure.js\";\nimport type { PlainObject } from \"../../../../contracts/shapes/shape.types.js\";\nimport type {\n WorkingAgentProcessResult,\n WorkingAgentProcessRunner,\n} from \"../../../../runtime/run-workflow/run-workflow.types.js\";\nimport type { WorkingAgentFiles } from \"../../artifacts/resolve-step-agent-files.js\";\nimport { readWorkingAgentOutput } from \"../../output/read-working-agent-output.js\";\nimport { buildWorkingAgentArgs } from \"./build-working-agent-args.js\";\nimport { spawnWorkingAgentProcess } from \"./spawn-working-agent-process.js\";\n\nexport async function runCustomWorkingProvider<TOutput extends PlainObject>(options: {\n readonly config: TrailStepConfig;\n readonly step: AgentStepRequestConfig<PlainObject, TOutput>;\n readonly role: WorkflowAgentRole;\n readonly cwd: string;\n readonly runner?: WorkingAgentProcessRunner;\n readonly target: TrailStepAgentTarget;\n readonly files: WorkingAgentFiles;\n readonly signal?: AbortSignal;\n}): Promise<TOutput> {\n const agentConfig = options.config.customProviders[options.target.provider];\n if (!agentConfig) {\n throw new TrailStepFailureError({\n code: \"agent_provider_unavailable\",\n message: `Working agent target '${options.target.provider}' does not reference a configured custom agent.`,\n details: { provider: options.target.provider },\n });\n }\n\n const thinking = options.target.thinking ?? options.role.thinking;\n const args = buildWorkingAgentArgs({\n argv: options.target.args ?? agentConfig.args,\n promptFile: options.files.promptFile,\n outputFile: options.files.outputFile,\n model: options.target.model,\n thinking,\n });\n\n let result: WorkingAgentProcessResult;\n try {\n result = await (options.runner ?? spawnWorkingAgentProcess)({\n command: agentConfig.binary,\n args,\n cwd: options.cwd,\n shell: false,\n stdio: \"inherit\",\n promptFile: options.files.promptFile,\n outputFile: options.files.outputFile,\n ...(options.target.model === undefined ? {} : { model: options.target.model }),\n signal: options.signal,\n });\n } catch (error) {\n throw new TrailStepFailureError({\n code: \"agent_provider_spawn_error\",\n message: `Working agent step ${options.step.id} could not start target '${options.target.provider}'.`,\n details: {\n target: options.target.provider,\n ...(options.target.model === undefined ? {} : { model: options.target.model }),\n cause: error instanceof Error ? error.message : String(error),\n },\n });\n }\n\n if (result.exitCode !== 0) {\n throw new TrailStepFailureError({\n code: \"agent_provider_failed\",\n message: `Working agent step ${options.step.id} target '${options.target.provider}' exited with code ${result.exitCode}.`,\n details: {\n exitCode: result.exitCode,\n provider: agentConfig.binary,\n target: options.target.provider,\n ...(options.target.model === undefined ? {} : { model: options.target.model }),\n },\n });\n }\n\n return readWorkingAgentOutput({\n stepId: options.step.id,\n outputFile: options.files.outputFile,\n step: options.step,\n });\n}\n","import { writeFile } from \"node:fs/promises\";\n\nimport type { TrailStepAgentTarget } from \"../../../../agent-targeting/targeting.types.js\";\nimport type { AgentStepRequestConfig } from \"../../../../authoring/step/agent-step.types.js\";\nimport type { WorkflowAgentRole } from \"../../../../contracts/agents/agent-role.types.js\";\nimport type { PlainObject } from \"../../../../contracts/shapes/shape.types.js\";\nimport type {\n ProviderAdapter,\n ProviderWorkingRunner,\n} from \"../../../../known-cli-providers/registry/provider-registry.types.js\";\nimport type { WorkingAgentFiles } from \"../../artifacts/resolve-step-agent-files.js\";\nimport { readWorkingAgentOutput } from \"../../output/read-working-agent-output.js\";\nimport { buildProviderWorkingPrompt } from \"../../prompts/build-provider-working-prompt.js\";\nimport { attemptProviderOutputRepair } from \"./repair-provider-output.js\";\n\nexport async function runRegistryWorkingProvider<TOutput extends PlainObject>(options: {\n readonly provider: ProviderAdapter;\n readonly role: WorkflowAgentRole;\n readonly step: AgentStepRequestConfig<PlainObject, TOutput>;\n readonly renderedPrompt: string;\n readonly cwd: string;\n readonly providerWorkingRunner?: ProviderWorkingRunner;\n readonly target: TrailStepAgentTarget;\n readonly files: WorkingAgentFiles;\n readonly signal?: AbortSignal;\n}): Promise<TOutput> {\n await writeFile(\n options.files.promptFile,\n buildProviderWorkingPrompt({\n prompt: options.renderedPrompt,\n outputSchema: options.step.output.jsonSchema,\n captureMode: options.step.output.captureMode,\n }),\n \"utf8\",\n );\n\n const thinking = resolveWorkingThinking(options.target, options.role);\n try {\n await options.provider.runWorking(\n {\n promptFile: options.files.promptFile,\n outputFile: options.files.outputFile,\n usageFile: options.files.usageFile,\n cwd: options.cwd,\n ...(options.target.model === undefined ? {} : { model: options.target.model }),\n ...(thinking === undefined ? {} : { thinking }),\n captureMode: options.step.output.captureMode,\n signal: options.signal,\n },\n options.providerWorkingRunner,\n );\n } catch (error) {\n const repaired = await attemptProviderOutputRepair({\n provider: options.provider,\n error,\n model: options.target.model,\n thinking,\n outputSchema: options.step.output.jsonSchema,\n captureMode: options.step.output.captureMode,\n files: options.files,\n cwd: options.cwd,\n providerWorkingRunner: options.providerWorkingRunner,\n signal: options.signal,\n });\n\n if (!repaired) {\n throw error;\n }\n }\n\n return readWorkingAgentOutput({\n stepId: options.step.id,\n outputFile: options.files.outputFile,\n step: options.step,\n });\n}\n\nfunction resolveWorkingThinking(\n target: TrailStepAgentTarget,\n role: WorkflowAgentRole,\n): WorkflowAgentRole[\"thinking\"] {\n return target.thinking ?? role.thinking;\n}\n","/**\n * Prompt for a built-in registry provider's working-mode invocation. Unlike\n * `buildWorkingAgentPrompt`, this never instructs the vendor CLI to write a\n * file itself: a registry provider adapter captures stdout and writes\n * `outputFile` on the runtime's behalf, so the prompt instead asks for the\n * JSON object as the model's entire final answer.\n */\nexport function buildProviderWorkingPrompt(options: {\n readonly prompt: string;\n readonly outputSchema: Record<string, unknown>;\n readonly captureMode?: \"json\" | \"raw-text\";\n}): string {\n if (options.captureMode === \"raw-text\") {\n return [\n \"# TrailStep working-agent task\",\n \"\",\n \"Print the document content directly as your entire response — no JSON wrapper, no surrounding commentary, no markdown fences unless they are literally part of the document content itself.\",\n \"Do not write output to a file.\",\n \"\",\n \"## Original prompt\",\n \"\",\n options.prompt,\n \"\",\n ].join(\"\\n\");\n }\n\n return [\n \"# TrailStep working-agent task\",\n \"\",\n \"Respond with exactly one JSON object as your entire final answer, and nothing else.\",\n \"Do not write output to a file. Do not include prose, markdown fences, or multiple JSON values in your final answer - only the JSON object itself. This instruction applies to your literal final message, not just the work you do to get there.\",\n \"\",\n \"The JSON object must match this output schema:\",\n \"\",\n \"```json\",\n JSON.stringify(options.outputSchema, null, 2),\n \"```\",\n \"\",\n \"## Original prompt\",\n \"\",\n options.prompt,\n \"\",\n ].join(\"\\n\");\n}\n","import type { WorkflowAgentRole } from \"../../../../contracts/agents/agent-role.types.js\";\nimport { TrailStepFailureError } from \"../../../../contracts/failures/failure.js\";\nimport type {\n ProviderAdapter,\n ProviderWorkingRunner,\n} from \"../../../../known-cli-providers/registry/provider-registry.types.js\";\nimport type { WorkingAgentFiles } from \"../../artifacts/resolve-step-agent-files.js\";\n\n/**\n * At most one repair attempt: a repair resumes the same CLI session, so a\n * second malformed answer in a row signals something deeper than a one-off\n * formatting slip, and repeatedly resuming risks drifting the session\n * further rather than fixing it. If the repair attempt also fails, this\n * falls through to the normal target-exhaustion path unchanged.\n */\nconst MAX_OUTPUT_REPAIR_ATTEMPTS = 1;\n\n/**\n * Malformed JSON from a working-agent's final answer commonly follows a real\n * multi-turn agentic turn — file edits, test runs — that already happened\n * before the model's last message failed to parse. Retrying the whole task\n * (a fresh target, or even a fresh run of the same target) would risk\n * duplicating or conflicting with that already-completed work, so instead of\n * a blind retry, providers that can resume their own CLI session (currently\n * only `claude`, via `repairOutput`) get one bounded attempt to resume that\n * exact session and re-emit just the final answer, reformatted. Providers\n * without that capability (`error.failure.details` lacking a `sessionId`, or\n * no `repairOutput` on the adapter at all) fall straight through to today's\n * immediate-failure behavior.\n */\nexport async function attemptProviderOutputRepair(options: {\n readonly provider: ProviderAdapter;\n readonly error: unknown;\n readonly model?: string;\n readonly thinking?: WorkflowAgentRole[\"thinking\"];\n readonly outputSchema: Record<string, unknown>;\n readonly captureMode?: \"json\" | \"raw-text\";\n readonly files: WorkingAgentFiles;\n readonly cwd: string;\n readonly providerWorkingRunner?: ProviderWorkingRunner;\n readonly signal?: AbortSignal;\n}): Promise<boolean> {\n if (!options.provider.repairOutput) {\n return false;\n }\n\n const repairable = extractRepairableFailure(options.error);\n if (!repairable || MAX_OUTPUT_REPAIR_ATTEMPTS < 1) {\n return false;\n }\n\n try {\n await options.provider.repairOutput(\n {\n sessionId: repairable.sessionId,\n rawResultText: repairable.rawResultText ?? \"\",\n outputFile: options.files.outputFile,\n usageFile: options.files.usageFile,\n cwd: options.cwd,\n ...(options.model === undefined ? {} : { model: options.model }),\n ...(options.thinking === undefined ? {} : { thinking: options.thinking }),\n outputSchema: options.outputSchema,\n captureMode: options.captureMode,\n signal: options.signal,\n },\n options.providerWorkingRunner,\n );\n return true;\n } catch {\n return false;\n }\n}\n\nfunction extractRepairableFailure(\n error: unknown,\n): { readonly sessionId: string; readonly rawResultText?: string } | undefined {\n if (!(error instanceof TrailStepFailureError)) {\n return undefined;\n }\n\n if (error.failure.code !== \"agent_provider_output_invalid\") {\n return undefined;\n }\n\n const details = error.failure.details;\n if (typeof details !== \"object\" || details === null) {\n return undefined;\n }\n\n const sessionId = (details as Record<string, unknown>).sessionId;\n if (typeof sessionId !== \"string\") {\n return undefined;\n }\n\n const rawResultText = (details as Record<string, unknown>).rawResultText;\n return {\n sessionId,\n ...(typeof rawResultText === \"string\" ? { rawResultText } : {}),\n };\n}\n","import type { TrailStepAgentTarget } from \"../../../agent-targeting/targeting.types.js\";\nimport { TrailStepFailureError } from \"../../../contracts/failures/failure.js\";\n\nexport interface WorkingAgentAttemptFailure {\n readonly target: string;\n readonly model?: string;\n readonly code: string;\n readonly message: string;\n readonly details?: unknown;\n}\n\nexport function summarizeWorkingAgentAttemptFailure(\n target: TrailStepAgentTarget,\n error: unknown,\n): WorkingAgentAttemptFailure {\n if (error instanceof TrailStepFailureError) {\n return {\n target: target.provider,\n ...(target.model === undefined ? {} : { model: target.model }),\n code: error.failure.code,\n message: error.failure.message,\n ...(error.failure.details === undefined ? {} : { details: error.failure.details }),\n };\n }\n\n return {\n target: target.provider,\n ...(target.model === undefined ? {} : { model: target.model }),\n code: \"agent_target_failed\",\n message: error instanceof Error ? error.message : \"Working agent target failed.\",\n };\n}\n","import { join, relative } from \"node:path\";\n\nexport function resolveSubPromptArtifactPaths(options: {\n readonly runDir: string;\n readonly stepDir: string;\n readonly ordinal: number;\n readonly fingerprint: string;\n}): {\n readonly subPromptDir: string;\n readonly promptFile: string;\n readonly outputFile: string;\n readonly usageFile: string;\n readonly runRelative: {\n readonly subPromptDir: string;\n readonly promptFile: string;\n readonly outputFile: string;\n };\n} {\n const artifactSubPromptId = `${String(options.ordinal).padStart(4, \"0\")}-${options.fingerprint.slice(0, 12)}`;\n const subPromptDir = join(options.stepDir, \"subPrompts\", artifactSubPromptId);\n const promptFile = join(subPromptDir, \"prompt.txt\");\n const outputFile = join(subPromptDir, \"output.json\");\n const usageFile = join(subPromptDir, \"usage.json\");\n\n return {\n subPromptDir,\n promptFile,\n outputFile,\n usageFile,\n runRelative: {\n subPromptDir: toRunRelativePath(options.runDir, subPromptDir),\n promptFile: toRunRelativePath(options.runDir, promptFile),\n outputFile: toRunRelativePath(options.runDir, outputFile),\n },\n };\n}\n\nfunction toRunRelativePath(runDir: string, path: string): string {\n return relative(runDir, path).replaceAll(\"\\\\\", \"/\");\n}\n","import type { Failure } from \"../../contracts/failures/failure.js\";\n\nexport function isFailureLikeError(error: unknown): error is { readonly failure: Failure } {\n return (\n typeof error === \"object\" &&\n error !== null &&\n \"failure\" in error &&\n typeof error.failure === \"object\" &&\n error.failure !== null &&\n \"code\" in error.failure &&\n typeof error.failure.code === \"string\" &&\n \"message\" in error.failure &&\n typeof error.failure.message === \"string\"\n );\n}\n","import type { Failure } from \"../../contracts/failures/failure.js\";\nimport { TrailStepFailureError } from \"../../contracts/failures/failure.js\";\nimport type { RunContext } from \"../../contracts/run-context/run-context.types.js\";\nimport { createEvent } from \"../events/create-run-event.js\";\nimport { isFailureLikeError } from \"../failures/failure-like.js\";\n\nexport async function emitSubPromptFailed(options: {\n readonly context: RunContext;\n readonly parentStepId: string;\n readonly ordinal: number;\n readonly fingerprint?: string;\n readonly artifactPaths?: {\n readonly subPromptDir: string;\n readonly promptFile: string;\n readonly outputFile: string;\n };\n readonly failure: Failure;\n}): Promise<void> {\n await options.context.emit?.(\n createEvent({\n runId: options.context.id,\n workflowId: options.context.workflowId ?? \"\",\n stepId: options.parentStepId,\n type: \"subPrompt.failed\",\n payload: {\n parentStepId: options.parentStepId,\n ordinal: options.ordinal,\n ...(options.fingerprint === undefined ? {} : { fingerprint: options.fingerprint }),\n ...(options.artifactPaths === undefined ? {} : { artifactPaths: options.artifactPaths }),\n failure: options.failure,\n },\n }),\n );\n}\n\nexport function maxSubPromptsGuardError(maxSubPrompts: number): TrailStepFailureError {\n return new TrailStepFailureError({\n code: \"max_sub_prompts_exceeded\",\n message: `workflow exceeded maxSubPrompts guard (${maxSubPrompts})`,\n });\n}\n\nexport function throwMissingSubPromptAgentConfig(options: {\n readonly workflowId: string;\n readonly parentStepId: string;\n readonly subPromptId: string;\n readonly agent: string;\n}): never {\n throw new TrailStepFailureError({\n code: \"missing_agent_config\",\n message: `Missing .trailstep/config.json: workflow ${options.workflowId} parent step ${options.parentStepId} subPrompt ${options.subPromptId} needs configured working agent '${options.agent}'.`,\n details: {\n workflowId: options.workflowId,\n parentStepId: options.parentStepId,\n subPromptId: options.subPromptId,\n agent: options.agent,\n mode: \"working\",\n },\n });\n}\n\nexport function subPromptFailureError(error: unknown): TrailStepFailureError {\n if (error instanceof TrailStepFailureError) {\n if (error.failure.code === \"validation_failed\") {\n return new TrailStepFailureError({\n ...error.failure,\n message: normalizeSubPromptValidationMessage(error.failure.message),\n });\n }\n\n return error;\n }\n\n if (isFailureLikeError(error)) {\n return new TrailStepFailureError(error.failure);\n }\n\n return new TrailStepFailureError({\n code: \"sub_prompt_failed\",\n message: error instanceof Error ? error.message : \"subPrompt failed.\",\n ...(error instanceof Error\n ? { details: { name: error.name } }\n : error === undefined\n ? {}\n : { details: { cause: error } }),\n });\n}\n\nfunction normalizeSubPromptValidationMessage(message: string): string {\n if (message.startsWith(\"subPrompt output failed schema validation\")) {\n return message;\n }\n\n const diagnostics = message.match(/failed schema validation: (.*)$/)?.[1];\n return diagnostics === undefined\n ? `subPrompt output failed schema validation: ${message}`\n : `subPrompt output failed schema validation: ${diagnostics}`;\n}\n","import { createHash } from \"node:crypto\";\n\nimport type { PlainObject } from \"../../contracts/shapes/shape.types.js\";\n\nexport function fingerprintSubPrompt(options: {\n readonly input: PlainObject;\n readonly prompt: string;\n}): string {\n return createHash(\"sha256\").update(stableJsonStringify(options)).digest(\"hex\");\n}\n\nexport function stableJsonStringify(value: unknown): string {\n if (Array.isArray(value)) {\n return `[${value.map((item) => stableJsonStringify(item)).join(\",\")}]`;\n }\n\n if (isPlainObject(value)) {\n const entries = Object.entries(value).sort(([left], [right]) => left.localeCompare(right));\n return `{${entries\n .map(([key, entryValue]) => `${JSON.stringify(key)}:${stableJsonStringify(entryValue)}`)\n .join(\",\")}}`;\n }\n\n return JSON.stringify(value);\n}\n\nfunction isPlainObject(value: unknown): value is PlainObject {\n return (\n typeof value === \"object\" &&\n value !== null &&\n !Array.isArray(value) &&\n Object.getPrototypeOf(value) === Object.prototype\n );\n}\n","import type { RunContextEvent } from \"../../contracts/run-context/run-context.types.js\";\nimport type { PlainObject } from \"../../contracts/shapes/shape.types.js\";\n\ninterface CompletedSubPromptEventPayload extends PlainObject {\n readonly parentStepId: string;\n readonly ordinal: number;\n readonly fingerprint: string;\n readonly output: PlainObject;\n}\n\nexport function findCompletedSubPromptEvent(\n events: readonly RunContextEvent[],\n parentStepId: string,\n ordinal: number,\n fingerprint: string,\n): RunContextEvent<CompletedSubPromptEventPayload> | undefined {\n for (let index = events.length - 1; index >= 0; index -= 1) {\n const event = events[index];\n if (event?.type !== \"subPrompt.completed\") {\n continue;\n }\n\n const payload = event.payload;\n if (\n payload.parentStepId === parentStepId &&\n payload.ordinal === ordinal &&\n payload.fingerprint === fingerprint &&\n isPlainObject(payload.output)\n ) {\n return event as RunContextEvent<CompletedSubPromptEventPayload>;\n }\n }\n\n return undefined;\n}\n\nfunction isPlainObject(value: unknown): value is PlainObject {\n return (\n typeof value === \"object\" &&\n value !== null &&\n !Array.isArray(value) &&\n Object.getPrototypeOf(value) === Object.prototype\n );\n}\n","import type { AgentPrompt } from \"../../contracts/agents/agent-adapter.types.js\";\nimport type { PlainObject } from \"../../contracts/shapes/shape.types.js\";\nimport { runSubPrompt } from \"../../runtime/sub-prompts/run-sub-prompt.js\";\nimport type {\n PromptTemplateSource,\n SubPromptFactory,\n SubPromptOptions,\n} from \"./continuation.types.js\";\n\nexport function subPrompt<\n TInput extends PlainObject = PlainObject,\n TOutput extends PlainObject = PlainObject,\n>(\n source: AgentPrompt<TInput> | PromptTemplateSource,\n options: SubPromptOptions<TOutput>,\n): SubPromptFactory<TInput, TOutput> {\n const run = (input?: TInput): Promise<TOutput> => runSubPrompt(source, options, input);\n\n return run as SubPromptFactory<TInput, TOutput>;\n}\n","import { lte } from \"semver\";\n\nimport type {\n DeprecationEntry,\n DeprecationManifest,\n DeprecationStatus,\n DeprecationTargetPackage,\n} from \"./deprecations.types.js\";\n\n// Scaffolding only — genuinely empty. No deprecation exists yet in this codebase. Real entries get\n// appended here the day a real breaking change to @trailstep/core or @trailstep/authoring's authoring API\n// actually happens. Do not add a fake/example entry to this array.\nexport const deprecationManifest: DeprecationManifest = [];\n\nexport interface FindDeprecationsAsOfQuery {\n readonly package: DeprecationTargetPackage;\n readonly version: string;\n}\n\n/**\n * Returns every manifest entry for query.package whose deprecatedSince is at or before\n * query.version, tagged with a severity. Calling this once with version set to a target\n * version naturally captures every entry between the installed version and the target, no matter\n * how many majors are being skipped in one update.\n */\nexport function findDeprecationsAsOf(\n manifest: DeprecationManifest,\n query: FindDeprecationsAsOfQuery,\n): readonly DeprecationStatus[] {\n return manifest\n .filter((entry) => entry.package === query.package && lte(entry.deprecatedSince, query.version))\n .map((entry) => toDeprecationStatus(entry, query.version));\n}\n\nfunction toDeprecationStatus(entry: DeprecationEntry, version: string): DeprecationStatus {\n const isRemoved = entry.removedIn !== undefined && lte(entry.removedIn, version);\n return { ...entry, severity: isRemoved ? \"blocking\" : \"warning\" };\n}\n","import type { PlainObject } from \"../../contracts/shapes/shape.types.js\";\nimport type { Event } from \"../run-workflow/run-workflow.types.js\";\n\nexport interface LatestUnresolvedFailure {\n readonly event: Event;\n readonly replayPosition: number;\n readonly sourceFailureEventId?: string;\n readonly workflowId: string;\n readonly workflowInput?: PlainObject;\n readonly stepId?: string;\n}\n\ninterface ResolvedFailureIdentity {\n readonly eventId?: string;\n readonly replayPosition?: number;\n}\n\nexport function selectLatestUnresolvedFailure(\n events: readonly Event[],\n): LatestUnresolvedFailure | undefined {\n const startedEvent = events.find((event) => event.type === \"workflow.started\");\n const workflowInput = startedEvent ? readPlainPayload(startedEvent, \"input\") : undefined;\n const resolvedFailures = events.flatMap((event) =>\n event.type === \"workflow.retryStarted\" ? readResolvedFailureIdentity(event) : [],\n );\n\n let workflowFailureFallback: LatestUnresolvedFailure | undefined;\n let laterWorkflowTerminalSeen = false;\n const laterTerminalStepIds = new Set<string>();\n\n for (let replayPosition = events.length - 1; replayPosition >= 0; replayPosition -= 1) {\n const event = events[replayPosition];\n if (!event) {\n continue;\n }\n\n if (event.type === \"workflow.completed\") {\n return undefined;\n }\n\n if (event.type === \"step.completed\") {\n rememberTerminalStep(event, laterTerminalStepIds);\n continue;\n }\n\n if (event.type === \"step.failed\") {\n rememberTerminalStep(event, laterTerminalStepIds);\n if (isResolvedFailure(event, replayPosition, resolvedFailures)) {\n continue;\n }\n\n return toLatestUnresolvedFailure(event, replayPosition, workflowInput);\n }\n\n if (event.type === \"workflow.failed\") {\n laterWorkflowTerminalSeen = true;\n if (!workflowFailureFallback) {\n if (isResolvedFailure(event, replayPosition, resolvedFailures)) {\n continue;\n }\n\n workflowFailureFallback = toLatestUnresolvedFailure(event, replayPosition, workflowInput);\n }\n continue;\n }\n\n if (\n event.type === \"step.started\" &&\n event.stepId &&\n !laterWorkflowTerminalSeen &&\n !laterTerminalStepIds.has(event.stepId)\n ) {\n if (isResolvedFailure(event, replayPosition, resolvedFailures)) {\n continue;\n }\n\n return toLatestUnresolvedFailure(event, replayPosition, workflowInput);\n }\n }\n\n return workflowFailureFallback;\n}\n\nfunction rememberTerminalStep(event: Event, stepIds: Set<string>): void {\n if (event.stepId) {\n stepIds.add(event.stepId);\n }\n}\n\nfunction readResolvedFailureIdentity(event: Event): readonly ResolvedFailureIdentity[] {\n const { sourceFailureEventId, sourceFailureReplayPosition } = event.payload;\n if (typeof sourceFailureEventId !== \"string\" && typeof sourceFailureReplayPosition !== \"number\") {\n return [];\n }\n\n return [\n {\n eventId: typeof sourceFailureEventId === \"string\" ? sourceFailureEventId : undefined,\n replayPosition:\n typeof sourceFailureReplayPosition === \"number\" ? sourceFailureReplayPosition : undefined,\n },\n ];\n}\n\nfunction isResolvedFailure(\n event: Event,\n replayPosition: number,\n resolvedFailures: readonly ResolvedFailureIdentity[],\n): boolean {\n return resolvedFailures.some((resolvedFailure) => {\n if (resolvedFailure.replayPosition !== undefined) {\n return resolvedFailure.replayPosition === replayPosition;\n }\n\n return resolvedFailure.eventId !== undefined && resolvedFailure.eventId === event.id;\n });\n}\n\nfunction toLatestUnresolvedFailure(\n event: Event,\n replayPosition: number,\n workflowInput: PlainObject | undefined,\n): LatestUnresolvedFailure {\n return {\n event,\n replayPosition,\n sourceFailureEventId: typeof event.id === \"string\" ? event.id : undefined,\n workflowId: event.workflowId,\n workflowInput,\n stepId: event.stepId,\n };\n}\n\nfunction readPlainPayload(event: Event, key: string): PlainObject | undefined {\n const value = event.payload[key];\n return isPlainObject(value) ? value : undefined;\n}\n\nfunction isPlainObject(value: unknown): value is PlainObject {\n return (\n typeof value === \"object\" &&\n value !== null &&\n !Array.isArray(value) &&\n Object.getPrototypeOf(value) === Object.prototype\n );\n}\n","export interface RetryPolicy {\n readonly maxAttempts: number;\n}\n\nexport interface RetryPolicyInput {\n readonly maxAttempts?: unknown;\n}\n\nexport interface ResolveRetryPolicyOptions {\n readonly global?: RetryPolicyInput;\n readonly workflow?: RetryPolicyInput;\n readonly step?: RetryPolicyInput;\n}\n\nconst BUILT_IN_RETRY_POLICY: RetryPolicy = { maxAttempts: 2 };\n\nexport function resolveRetryPolicy(options: ResolveRetryPolicyOptions): RetryPolicy {\n return validateRetryPolicy(\n firstConfiguredPolicy(options.step, options.workflow, options.global) ?? BUILT_IN_RETRY_POLICY,\n );\n}\n\nexport function validateRetryPolicy(input: RetryPolicyInput): RetryPolicy {\n const maxAttempts = input.maxAttempts ?? BUILT_IN_RETRY_POLICY.maxAttempts;\n\n if (typeof maxAttempts !== \"number\" || !Number.isInteger(maxAttempts) || maxAttempts < 1) {\n throw new TypeError(\"retry.maxAttempts must be an integer greater than or equal to 1.\");\n }\n\n return { maxAttempts };\n}\n\nfunction firstConfiguredPolicy(\n ...policies: readonly (RetryPolicyInput | undefined)[]\n): RetryPolicyInput | undefined {\n return policies.find((policy) => policy?.maxAttempts !== undefined);\n}\n","import { basename } from \"node:path\";\nimport { normalizeShape } from \"../../authoring/shape/json-schema.js\";\nimport type { ContinuationResult } from \"../../authoring/step/continuation.types.js\";\nimport type { Failure } from \"../../contracts/failures/failure.js\";\nimport type { PlainObject } from \"../../contracts/shapes/shape.types.js\";\nimport type {\n Event,\n Result,\n RunWorkflowOptions,\n} from \"../../runtime/run-workflow/run-workflow.types.js\";\nimport { appendEvent } from \"../artifacts/run-storage.js\";\nimport { runContinuation } from \"../continuation/run-continuation/run-continuation.js\";\nimport { createEvent } from \"../events/create-run-event.js\";\nimport { isFailureLikeError } from \"../failures/failure-like.js\";\nimport { workflowFailure } from \"../failures/workflow-failure.js\";\nimport {\n findDanglingInteractiveSessionStart,\n reattachInProgressStep,\n} from \"../resume/reattach-in-progress-step/reattach-in-progress-step.js\";\nimport { replayToFailedStep } from \"../resume/replay-to-failed-step/replay-to-failed-step.js\";\nimport { replayToRetryFailure } from \"../retry/replay-to-retry-failure.js\";\nimport { createRunContext } from \"../run-context/create-run-context.js\";\nimport { runContextStorage } from \"../run-context/run-context-storage.js\";\nimport { initializeRun } from \"./initialize-run.js\";\nimport { parseTrailStepConfigInput } from \"./trailstep-config-input.js\";\n\nexport async function runWorkflow<TInput extends PlainObject, TOutput extends PlainObject>(\n options: RunWorkflowOptions<TInput, TOutput>,\n): Promise<Result<TOutput>> {\n const maxSteps = options.maxSteps ?? 1000;\n const isResume = options.resume !== undefined;\n const isRetry = options.retry !== undefined;\n const initialized = await initializeRun(options).catch((error) => {\n const existingRunDir = options.resume?.runDir ?? options.retry?.runDir;\n if (existingRunDir && isFailureLikeError(error)) {\n return {\n status: \"failure\" as const,\n runId: basename(existingRunDir),\n runName: basename(existingRunDir),\n runDir: existingRunDir,\n previousEvents: [],\n failure: workflowFailure(error),\n };\n }\n\n throw error;\n });\n\n if (\"status\" in initialized && initialized.status === \"failure\") {\n return {\n status: \"failure\",\n runId: initialized.runId,\n runDir: initialized.runDir,\n failure: initialized.failure,\n events: initialized.previousEvents,\n };\n }\n\n const { runId, runName, runDir, previousEvents } = initialized;\n const trailstepConfig =\n options.trailstepConfig === undefined\n ? undefined\n : parseTrailStepConfigInput(options.trailstepConfig);\n const cwd = options.cwd ?? process.cwd();\n const events: Event[] = [...previousEvents];\n\n const emit = async (event: Event): Promise<void> => {\n events.push(event);\n await appendEvent(runDir, event);\n await options.eventSink?.(event);\n };\n\n const runContext = createRunContext({\n runId,\n runName,\n runDir,\n workflowId: options.workflow.id,\n workflowAgents: options.workflow.agents ?? {},\n cwd,\n trailstepConfig,\n workingAgentProcessRunner: options.workingAgentProcessRunner,\n providerWorkingRunner: options.providerWorkingRunner,\n emit,\n events: () => events,\n });\n\n const failWorkflow = async (failure: Failure): Promise<Result<TOutput>> => {\n await emit(\n createEvent({\n runId,\n workflowId: options.workflow.id,\n type: \"workflow.failed\",\n payload: { failure },\n }),\n );\n return {\n status: \"failure\",\n runId,\n runDir,\n failure,\n events,\n };\n };\n\n const failResumeValidation = (failure: Failure): Result<TOutput> => ({\n status: \"failure\",\n runId,\n runDir,\n failure,\n events,\n });\n\n try {\n return await runContextStorage.run(runContext, () => runWorkflowBody());\n } catch (error) {\n return await failWorkflow(workflowFailure(error));\n }\n\n async function runWorkflowBody(): Promise<Result<TOutput>> {\n const inputSchema = options.workflow.inputShape\n ? normalizeShape(options.workflow.inputShape)\n : options.workflow.input;\n\n let workflowInput: TInput;\n let startNode: ContinuationResult | undefined;\n\n if (isResume) {\n const danglingAnchor = findDanglingInteractiveSessionStart(previousEvents);\n const replay = danglingAnchor\n ? await reattachInProgressStep({\n workflow: options.workflow,\n events: previousEvents,\n runDir,\n })\n : await replayToFailedStep({\n workflow: options.workflow,\n events: previousEvents,\n runDir,\n });\n if (replay.status === \"failure\") {\n return failResumeValidation(replay.failure);\n }\n\n workflowInput = inputSchema\n ? (inputSchema.assert(replay.input, \"workflow input\") as TInput)\n : (replay.input as TInput);\n startNode = replay.node;\n await emit(\n createEvent({\n runId,\n workflowId: options.workflow.id,\n type: \"workflow.resumed\",\n payload: {\n resumedFromRunDir: runDir,\n resumedStepId: replay.resumedStepId,\n sourceFailureEventId: replay.sourceFailureEventId,\n },\n }),\n );\n } else if (isRetry) {\n const replay = await replayToRetryFailure({\n workflow: options.workflow,\n events: previousEvents,\n runDir,\n });\n if (replay.status === \"failure\") {\n return failResumeValidation(replay.failure);\n }\n\n workflowInput = inputSchema\n ? (inputSchema.assert(replay.input, \"workflow input\") as TInput)\n : (replay.input as TInput);\n startNode = replay.node;\n await emit(\n createEvent({\n runId,\n workflowId: options.workflow.id,\n type: \"workflow.retryStarted\",\n payload: {\n retryKind: options.retry.kind,\n retriedFromRunDir: runDir,\n retriedStepId: replay.retriedStepId,\n sourceFailureEventId: replay.sourceFailureEventId,\n sourceFailureReplayPosition: replay.sourceFailureReplayPosition,\n },\n }),\n );\n } else {\n workflowInput = inputSchema\n ? inputSchema.assert(options.input, \"workflow input\")\n : (options.input as TInput);\n await emit(\n createEvent({\n runId,\n workflowId: options.workflow.id,\n type: \"workflow.started\",\n payload: { input: workflowInput },\n }),\n );\n }\n\n const continuationResult = await runContinuation({\n node: startNode ?? options.workflow.start(workflowInput),\n runId,\n workflowId: options.workflow.id,\n emit,\n maxSteps,\n initialSource: isRetry\n ? `retry for workflow ${options.workflow.id}`\n : isResume\n ? `resume for workflow ${options.workflow.id}`\n : `workflow.start for workflow ${options.workflow.id}`,\n // The original run already used one step-index slot per step.started\n // event ever recorded (successful or failed) -- newly-dispatched steps\n // after resume must continue that sequence, not restart at 1, or their\n // artifact directories collide with the pre-resume steps' directories.\n initialExecutedSteps:\n isResume || isRetry\n ? previousEvents.filter((event) => event.type === \"step.started\").length\n : undefined,\n workflowAgents: options.workflow.agents ?? {},\n workflowTimeout: options.workflow.timeout,\n runDir,\n cwd,\n trailstepConfig,\n workingAgentProcessRunner: options.workingAgentProcessRunner,\n providerWorkingRunner: options.providerWorkingRunner,\n processRunner: options.processRunner,\n });\n\n if (continuationResult.status === \"failure\") {\n return await failWorkflow(continuationResult.failure);\n }\n\n const current = continuationResult.output;\n\n const outputSchema = options.workflow.outputShape\n ? normalizeShape(options.workflow.outputShape)\n : options.workflow.output;\n const output = (\n outputSchema ? outputSchema.assert(current, \"workflow output\") : current\n ) as TOutput;\n\n await emit(\n createEvent({\n runId,\n workflowId: options.workflow.id,\n type: \"workflow.completed\",\n payload: { output },\n }),\n );\n\n return {\n status: \"success\",\n runId,\n runDir,\n output,\n events,\n };\n }\n}\n","import type { Failure } from \"../../contracts/failures/failure.js\";\n\nimport { isFailureLikeError } from \"./failure-like.js\";\n\nexport function stepExecutionFailure(error: unknown): Failure {\n if (isFailureLikeError(error)) {\n return error.failure;\n }\n\n return {\n code: \"step_execution_failed\",\n message: error instanceof Error ? error.message : \"Step execution failed.\",\n ...(error instanceof Error\n ? {\n details: {\n name: error.name,\n },\n }\n : error === undefined\n ? {}\n : { details: { cause: error } }),\n };\n}\n","import { runContextStorage } from \"./run-context-storage.js\";\n\n/**\n * Runs `fn` with a step-scoped ambient `RunContext.currentStep` shadowing\n * whatever run-level context is already active (set once, for the whole\n * run, by `run-workflow.ts`). This is a genuine nested `AsyncLocalStorage`\n * scope — it does not mutate or replace the outer context, only shadows it\n * for the duration of `fn`, so code outside any step (or in a sibling step)\n * is unaffected.\n *\n * `nextDocumentIndex()` hands out 1, 2, 3, ... on each call within this one\n * invocation of `withStepContext` — a fresh counter every time, including\n * across resume replay of already-completed steps and retries of a failed\n * step, since each of those call sites invokes `withStepContext` anew.\n *\n * If there is no ambient run context at all (a step-executing function\n * called directly, outside of `runWorkflow`'s `runContextStorage.run(...)`\n * scope — e.g. unit tests that exercise the resume/continuation internals\n * in isolation), this falls back to running `fn` with no ambient context,\n * matching prior behavior exactly rather than throwing.\n */\nexport async function withStepContext<T>(\n stepId: string,\n stepDir: string,\n fn: () => Promise<T>,\n options: { readonly maxSubPrompts?: unknown } = {},\n): Promise<T> {\n const parentContext = runContextStorage.getStore();\n if (!parentContext) {\n return await fn();\n }\n\n let nextDocumentIndex = 0;\n let nextSubPromptIndex = 0;\n\n const stepContext = {\n ...parentContext,\n currentStep: {\n id: stepId,\n dir: stepDir,\n maxSubPrompts: options.maxSubPrompts,\n nextDocumentIndex(): number {\n nextDocumentIndex += 1;\n return nextDocumentIndex;\n },\n nextSubPromptIndex(): number {\n nextSubPromptIndex += 1;\n return nextSubPromptIndex;\n },\n },\n };\n\n return await runContextStorage.run(stepContext, fn);\n}\n","export interface TimeoutPolicy {\n readonly timeoutMs?: number;\n}\n\nexport type TimeoutPolicyInput = number;\n\nexport interface ResolveTimeoutPolicyOptions {\n readonly global?: TimeoutPolicyInput;\n readonly workflow?: TimeoutPolicyInput;\n readonly step?: TimeoutPolicyInput;\n}\n\nconst BUILT_IN_TIMEOUT_POLICY: TimeoutPolicy = {};\n\nexport function resolveTimeoutPolicy(options: ResolveTimeoutPolicyOptions): TimeoutPolicy {\n const configured = firstConfiguredPolicy(options.step, options.workflow, options.global);\n return configured !== undefined ? validateTimeoutPolicy(configured) : BUILT_IN_TIMEOUT_POLICY;\n}\n\nexport function validateTimeoutPolicy(input: unknown): TimeoutPolicy {\n if (typeof input !== \"number\" || !Number.isInteger(input) || input < 1) {\n throw new TypeError(\n \"timeout must be an integer number of milliseconds greater than or equal to 1.\",\n );\n }\n\n return { timeoutMs: input };\n}\n\nfunction firstConfiguredPolicy(...policies: readonly unknown[]): unknown | undefined {\n return policies.find((policy) => policy !== undefined);\n}\n","export const DEFAULT_INTERACTIVE_OUTPUT_SHAPE = { sessionFile: \"string\" } as const;\n","import { normalizeShape } from \"../../../authoring/shape/json-schema.js\";\nimport type { PlainObject, Schema, ShapeInput } from \"../../../contracts/shapes/shape.types.js\";\nimport { DEFAULT_INTERACTIVE_OUTPUT_SHAPE } from \"../../interactive-session/default-interactive-output-shape.js\";\n\n/**\n * A prompt step's effective output schema: its own `output`, or -- for an\n * interactive step with none given -- the default interactive output shape.\n * Shared by dispatch (`runContinuation`) and both resume paths\n * (`reattachInProgressStep`, `replayCompletedSteps`), which must all resolve\n * the identical schema a step was originally dispatched with.\n */\nexport function resolveStepOutputSchema(config: {\n readonly output?: ShapeInput<PlainObject>;\n readonly mode?: \"working\" | \"interactive\";\n}): Schema<PlainObject> | undefined {\n const effectiveOutput =\n config.output ?? (config.mode === \"interactive\" ? DEFAULT_INTERACTIVE_OUTPUT_SHAPE : undefined);\n\n return effectiveOutput ? normalizeShape(effectiveOutput) : undefined;\n}\n","import { dispatchAgentStep } from \"../../../agent-execution/dispatch-agent-step/dispatch-agent-step.js\";\nimport type { TrailStepConfig } from \"../../../agent-targeting/targeting.types.js\";\nimport type { ContinuationResult } from \"../../../authoring/step/continuation.types.js\";\nimport { isDoneNode, isFailNode, isStepNode } from \"../../../authoring/step/step-node.js\";\nimport type { WorkflowAgentRole } from \"../../../contracts/agents/agent-role.types.js\";\nimport type { Failure } from \"../../../contracts/failures/failure.js\";\nimport { TrailStepFailureError } from \"../../../contracts/failures/failure.js\";\nimport type { PlainObject } from \"../../../contracts/shapes/shape.types.js\";\nimport type {\n Event,\n RunWorkflowOptions,\n} from \"../../../runtime/run-workflow/run-workflow.types.js\";\nimport { resolveStepArtifactPaths } from \"../../artifacts/step-artifacts.js\";\nimport { createEvent } from \"../../events/create-run-event.js\";\nimport { stepExecutionFailure } from \"../../failures/step-execution-failure.js\";\nimport { withStepContext } from \"../../run-context/with-step-context.js\";\nimport type { TimeoutPolicyInput } from \"../../timeout/timeout-policy.js\";\nimport { resolveTimeoutPolicy } from \"../../timeout/timeout-policy.js\";\nimport { resolveStepOutputSchema } from \"../resolve-step-output-schema/resolve-step-output-schema.js\";\n\nexport interface RunContinuationOptions {\n readonly node: ContinuationResult;\n readonly runId: string;\n readonly workflowId: string;\n readonly emit: (event: Event) => Promise<void>;\n readonly maxSteps: number;\n readonly initialSource: string;\n readonly initialExecutedSteps?: number;\n readonly workflowAgents: Readonly<Record<string, WorkflowAgentRole>>;\n readonly workflowTimeout?: TimeoutPolicyInput;\n readonly runDir: string;\n readonly cwd: string;\n readonly trailstepConfig?: TrailStepConfig;\n readonly workingAgentProcessRunner?: RunWorkflowOptions[\"workingAgentProcessRunner\"];\n readonly providerWorkingRunner?: RunWorkflowOptions[\"providerWorkingRunner\"];\n readonly processRunner?: RunWorkflowOptions[\"processRunner\"];\n}\n\nexport type RunContinuationResult =\n | { readonly status: \"success\"; readonly output: PlainObject }\n | { readonly status: \"failure\"; readonly failure: Failure };\n\nexport async function runContinuation(\n options: RunContinuationOptions,\n): Promise<RunContinuationResult> {\n let node: ContinuationResult = options.node;\n let source = options.initialSource;\n // A resumed run's newly-dispatched steps must continue the on-disk step\n // index sequence from where the original run left off (every step.started\n // ever recorded, successful or failed), not restart at 1 -- otherwise their\n // artifact directories collide with/shadow the pre-resume steps' dirs.\n let executedSteps = options.initialExecutedSteps ?? 0;\n const trailstepConfig = options.trailstepConfig;\n\n while (true) {\n if (isDoneNode(node)) {\n return { status: \"success\", output: node.output };\n }\n\n if (isFailNode(node)) {\n return { status: \"failure\", failure: node.failure };\n }\n\n if (!isStepNode(node)) {\n return {\n status: \"failure\",\n failure: continuationFailure(source),\n };\n }\n\n if (executedSteps >= options.maxSteps) {\n return {\n status: \"failure\",\n failure: stepExecutionFailure(\n new Error(`workflow exceeded maxSteps guard (${options.maxSteps})`),\n ),\n };\n }\n executedSteps += 1;\n const stepIndex = executedSteps;\n\n const stepNode = node;\n const { config } = stepNode;\n const hasPrompt = config.prompt !== undefined;\n const timeoutPolicy = resolveTimeoutPolicy({\n global: trailstepConfig?.settings?.timeout,\n workflow:\n options.workflowTimeout ??\n trailstepConfig?.workflows?.[options.workflowId]?.settings?.timeout,\n step: config.timeout,\n });\n const maxSubPrompts =\n config.maxSubPrompts ??\n trailstepConfig?.workflows?.[options.workflowId]?.settings?.maxSubPrompts;\n\n await options.emit(\n createEvent({\n runId: options.runId,\n workflowId: options.workflowId,\n stepId: config.id,\n type: \"step.started\",\n payload: { stepName: config.id, kind: hasPrompt ? \"agent\" : \"code\" },\n }),\n );\n\n try {\n const stepDir = resolveStepArtifactPaths({\n runDir: options.runDir,\n stepId: config.id,\n stepIndex,\n }).stepDir;\n\n const nextNode = await runWithStepTimeout({\n stepId: config.id,\n timeoutMs: timeoutPolicy.timeoutMs,\n run: async (signal) =>\n await withStepContext(\n config.id,\n stepDir,\n async () => {\n let paramForNext: PlainObject;\n\n if (hasPrompt) {\n const outputSchema = resolveStepOutputSchema(config);\n if (!outputSchema) {\n throw new Error(`step ${config.id} with a prompt requires an output shape`);\n }\n\n const rawOutput = await dispatchAgentStep({\n config: config as typeof config & { prompt: NonNullable<typeof config.prompt> },\n outputSchema,\n interactiveOutputMode:\n config.mode === \"interactive\" && config.output !== undefined\n ? \"json\"\n : \"session-file\",\n runId: options.runId,\n workflowId: options.workflowId,\n emit: options.emit,\n workflowAgents: options.workflowAgents,\n runDir: options.runDir,\n cwd: options.cwd,\n trailstepConfig,\n workingAgentProcessRunner: options.workingAgentProcessRunner,\n providerWorkingRunner: options.providerWorkingRunner,\n processRunner: options.processRunner,\n stepIndex,\n signal,\n });\n throwIfStepTimedOut(signal, config.id, timeoutPolicy.timeoutMs);\n paramForNext = outputSchema.assert(rawOutput, `step ${config.id} output`);\n\n await options.emit(\n createEvent({\n runId: options.runId,\n workflowId: options.workflowId,\n stepId: config.id,\n type: \"step.completed\",\n payload: { output: paramForNext },\n }),\n );\n } else {\n paramForNext = config.input;\n }\n\n const nextNode = await stepNode.onOutput(paramForNext, config.input);\n throwIfStepTimedOut(signal, config.id, timeoutPolicy.timeoutMs);\n\n if (isFailNode(nextNode)) {\n await options.emit(\n createEvent({\n runId: options.runId,\n workflowId: options.workflowId,\n stepId: config.id,\n type: \"step.failed\",\n payload: { failure: nextNode.failure },\n }),\n );\n return nextNode;\n }\n\n if (!hasPrompt) {\n // A no-prompt step's .do(...) IS its work — only report completion once it has\n // actually run without throwing or returning fail(...), matching the with-prompt\n // case's \"step.completed means the step's own work succeeded\" meaning.\n await options.emit(\n createEvent({\n runId: options.runId,\n workflowId: options.workflowId,\n stepId: config.id,\n type: \"step.completed\",\n payload: {},\n }),\n );\n }\n\n throwIfStepTimedOut(signal, config.id, timeoutPolicy.timeoutMs);\n return nextNode;\n },\n { maxSubPrompts },\n ),\n });\n\n if (!isStepNode(nextNode) && !isDoneNode(nextNode) && !isFailNode(nextNode)) {\n const failure = continuationFailure(`step ${config.id}`);\n await options.emit(\n createEvent({\n runId: options.runId,\n workflowId: options.workflowId,\n stepId: config.id,\n type: \"step.failed\",\n payload: { failure },\n }),\n );\n return { status: \"failure\", failure };\n }\n\n if (isFailNode(nextNode)) {\n return { status: \"failure\", failure: nextNode.failure };\n }\n\n node = nextNode;\n source = `step ${config.id}`;\n } catch (error) {\n const failure = stepExecutionFailure(error);\n\n await options.emit(\n createEvent({\n runId: options.runId,\n workflowId: options.workflowId,\n stepId: config.id,\n type: \"step.failed\",\n payload: { failure },\n }),\n );\n\n if (!stepNode.onError) {\n return { status: \"failure\", failure };\n }\n\n try {\n const nextNode = stepNode.onError(failure);\n if (!isStepNode(nextNode) && !isDoneNode(nextNode) && !isFailNode(nextNode)) {\n return {\n status: \"failure\",\n failure: continuationFailure(`error continuation for step ${config.id}`),\n };\n }\n\n node = nextNode;\n source = `error continuation for step ${config.id}`;\n } catch (errorContinuationError) {\n return {\n status: \"failure\",\n failure: stepExecutionFailure(\n new Error(\n `error continuation for step ${config.id} failed: ${errorMessage(errorContinuationError)}`,\n ),\n ),\n };\n }\n }\n }\n}\n\nasync function runWithStepTimeout<T>(options: {\n readonly stepId: string;\n readonly timeoutMs?: number;\n readonly run: (signal?: AbortSignal) => Promise<T>;\n}): Promise<T> {\n if (options.timeoutMs === undefined) {\n return await options.run();\n }\n\n const timeoutMs = options.timeoutMs;\n const abortController = new AbortController();\n let timeout: ReturnType<typeof setTimeout> | undefined;\n const timeoutPromise = new Promise<never>((_, reject) => {\n timeout = setTimeout(() => {\n abortController.abort();\n reject(stepTimeoutFailure(options.stepId, timeoutMs));\n }, timeoutMs);\n });\n\n try {\n return await Promise.race([options.run(abortController.signal), timeoutPromise]);\n } finally {\n if (timeout !== undefined) {\n clearTimeout(timeout);\n }\n }\n}\n\nfunction throwIfStepTimedOut(\n signal: AbortSignal | undefined,\n stepId: string,\n timeoutMs: number | undefined,\n): void {\n if (signal?.aborted && timeoutMs !== undefined) {\n throw stepTimeoutFailure(stepId, timeoutMs);\n }\n}\n\nfunction stepTimeoutFailure(stepId: string, timeoutMs: number): TrailStepFailureError {\n return new TrailStepFailureError({\n code: \"step_timeout\",\n message: `Step ${stepId} timed out after ${timeoutMs}ms.`,\n details: { stepId, timeoutMs },\n });\n}\n\nfunction errorMessage(error: unknown): string {\n if (error instanceof TrailStepFailureError) {\n return error.message;\n }\n\n if (error instanceof Error) {\n return error.message;\n }\n\n return \"Error continuation failed.\";\n}\n\nfunction continuationFailure(source: string): Failure {\n return {\n code: \"invalid_continuation\",\n message: `${source} returned an invalid continuation node.`,\n };\n}\n","import type { Failure } from \"../../contracts/failures/failure.js\";\n\nimport { isFailureLikeError } from \"./failure-like.js\";\n\nexport function workflowFailure(error: unknown): Failure {\n if (isFailureLikeError(error)) {\n return error.failure;\n }\n\n return {\n code: \"workflow_failed\",\n message: error instanceof Error ? error.message : \"Unknown workflow failure.\",\n ...(error === undefined ? {} : { details: { cause: error } }),\n };\n}\n","import type { ContinuationResult, StepNode } from \"../../../authoring/step/continuation.types.js\";\nimport { isStepNode } from \"../../../authoring/step/step-node.js\";\nimport type { Failure } from \"../../../contracts/failures/failure.js\";\nimport type { PlainObject } from \"../../../contracts/shapes/shape.types.js\";\nimport type {\n Event,\n RunWorkflowOptions,\n} from \"../../../runtime/run-workflow/run-workflow.types.js\";\nimport { resolveStepArtifactPaths } from \"../../artifacts/step-artifacts.js\";\nimport { resolveStepOutputSchema } from \"../../continuation/resolve-step-output-schema/resolve-step-output-schema.js\";\nimport { withStepContext } from \"../../run-context/with-step-context.js\";\n\n/**\n * Walks a workflow's `start(...)` continuation forward through its recorded\n * `step.completed` history — trusting each completed prompt/agent step's\n * persisted output rather than recomputing it — until it reaches\n * `targetStepId`. Shared by `replayToFailedStep` (target = the step that\n * failed) and `reattachInProgressStep` (target = a dangling interactive\n * step): both need the identical \"replay what already happened\" walk: only\n * their handling of the target step once reached differs.\n */\nexport async function replayCompletedSteps<\n TInput extends PlainObject,\n TOutput extends PlainObject,\n>(options: {\n readonly workflow: RunWorkflowOptions<TInput, TOutput>[\"workflow\"];\n readonly events: readonly Event[];\n readonly input: PlainObject;\n readonly targetStepId: string;\n readonly runDir: string;\n}): Promise<\n | { readonly status: \"success\"; readonly node: StepNode }\n | { readonly status: \"failure\"; readonly failure: Failure }\n> {\n let node: ContinuationResult = options.workflow.start(options.input as TInput);\n const completedStepEvents = options.events.filter((event) => event.type === \"step.completed\");\n\n for (const [completedIndex, completedEvent] of completedStepEvents.entries()) {\n const stepIndex = completedIndex + 1;\n if (!isStepNode(node)) {\n return {\n status: \"failure\",\n failure: replayFailure(\n \"resume_step_id_drift\",\n \"Completed history continues after the current workflow reaches done.\",\n ),\n };\n }\n\n if (node.config.id !== completedEvent.stepId) {\n return {\n status: \"failure\",\n failure: replayFailure(\n \"resume_step_id_drift\",\n `Expected completed step ${node.config.id} but found ${completedEvent.stepId ?? \"<missing>\"}.`,\n ),\n };\n }\n\n if (node.config.prompt !== undefined) {\n const recordedOutput = readPlainPayload(completedEvent, \"output\");\n if (!recordedOutput) {\n return {\n status: \"failure\",\n failure: replayFailure(\n \"resume_missing_step_output\",\n `Completed step ${node.config.id} has no recorded output to resume from.`,\n ),\n };\n }\n\n const outputSchema = resolveStepOutputSchema(node.config);\n if (!outputSchema) {\n return {\n status: \"failure\",\n failure: replayFailure(\n \"resume_output_schema_unresolvable\",\n `Step ${node.config.id} has no resolvable output schema to replay with.`,\n ),\n };\n }\n const validatedOutput = outputSchema.assert(recordedOutput, `step ${node.config.id} output`);\n\n const stepDir = resolveStepArtifactPaths({\n runDir: options.runDir,\n stepId: node.config.id,\n stepIndex,\n }).stepDir;\n const completedNode = node;\n node = await withStepContext(completedNode.config.id, stepDir, async () =>\n completedNode.onOutput(validatedOutput, completedNode.config.input),\n );\n } else {\n const stepDir = resolveStepArtifactPaths({\n runDir: options.runDir,\n stepId: node.config.id,\n stepIndex,\n }).stepDir;\n const completedNode = node;\n node = await withStepContext(completedNode.config.id, stepDir, async () =>\n completedNode.onOutput(completedNode.config.input, completedNode.config.input),\n );\n }\n }\n\n if (!isStepNode(node) || node.config.id !== options.targetStepId) {\n return {\n status: \"failure\",\n failure: replayFailure(\n \"resume_step_id_drift\",\n `Target step ${options.targetStepId} is not the next live step.`,\n ),\n };\n }\n\n return { status: \"success\", node };\n}\n\nfunction readPlainPayload(event: Event, key: string): PlainObject | undefined {\n const value = event.payload[key];\n return isPlainObject(value) ? value : undefined;\n}\n\nfunction isPlainObject(value: unknown): value is PlainObject {\n return (\n typeof value === \"object\" &&\n value !== null &&\n !Array.isArray(value) &&\n Object.getPrototypeOf(value) === Object.prototype\n );\n}\n\nfunction replayFailure(code: string, message: string): Failure {\n return { code, message };\n}\n","import type { ContinuationResult } from \"../../../authoring/step/continuation.types.js\";\nimport type { Failure } from \"../../../contracts/failures/failure.js\";\nimport { TrailStepFailureError } from \"../../../contracts/failures/failure.js\";\nimport type { PlainObject, Schema } from \"../../../contracts/shapes/shape.types.js\";\nimport type {\n Event,\n RunWorkflowOptions,\n} from \"../../../runtime/run-workflow/run-workflow.types.js\";\nimport { resolveStepArtifactPaths } from \"../../artifacts/step-artifacts.js\";\nimport { resolveStepOutputSchema } from \"../../continuation/resolve-step-output-schema/resolve-step-output-schema.js\";\nimport {\n readCompletedInteractiveOutput,\n waitForInteractiveCompletion,\n} from \"../../interactive-session/interactive-session-protocol.js\";\nimport { withStepContext } from \"../../run-context/with-step-context.js\";\nimport { replayCompletedSteps } from \"../replay-completed-steps/replay-completed-steps.js\";\n\n/**\n * Detects the \"process died mid-interactive-step\" resume shape: the run's\n * last event is `interactive.sessionStarted` for a step, with nothing after\n * it — no `interactive.sessionCompleted`, `step.completed`, `step.failed`,\n * `workflow.failed`, or `workflow.completed` was ever written, because the\n * process was killed before any of those could be recorded. Anything else\n * (an already-terminal `workflow.failed`/`workflow.completed` run) is not\n * this shape, even if an interactive.sessionStarted appears earlier in\n * history — `run-workflow.ts` falls back to `replayToFailedStep` for that.\n */\nexport function findDanglingInteractiveSessionStart(events: readonly Event[]): Event | undefined {\n const anchor = events.at(-1);\n if (anchor?.type !== \"interactive.sessionStarted\" || !anchor.stepId) {\n return undefined;\n }\n\n const hasTerminalWorkflowEvent = events.some(\n (event) => event.type === \"workflow.failed\" || event.type === \"workflow.completed\",\n );\n\n return hasTerminalWorkflowEvent ? undefined : anchor;\n}\n\nexport async function reattachInProgressStep<\n TInput extends PlainObject,\n TOutput extends PlainObject,\n>(options: {\n readonly workflow: RunWorkflowOptions<TInput, TOutput>[\"workflow\"];\n readonly events: readonly Event[];\n readonly runDir: string;\n}): Promise<\n | {\n readonly status: \"success\";\n readonly input: PlainObject;\n readonly node: ContinuationResult;\n readonly resumedStepId: string;\n readonly sourceFailureEventId: string;\n }\n | { readonly status: \"failure\"; readonly failure: Failure }\n> {\n const anchor = findDanglingInteractiveSessionStart(options.events);\n if (!anchor?.stepId) {\n return {\n status: \"failure\",\n failure: resumeFailure(\n \"resume_target_not_dangling\",\n \"Resume target has no dangling interactive.sessionStarted event to reattach.\",\n ),\n };\n }\n\n const stepIndex = anchor.payload.stepIndex;\n if (typeof stepIndex !== \"number\") {\n return {\n status: \"failure\",\n failure: resumeFailure(\n \"resume_missing_step_index\",\n `Dangling interactive.sessionStarted event for step ${anchor.stepId} has no recorded stepIndex.`,\n ),\n };\n }\n\n const startedEvent = options.events.find((event) => event.type === \"workflow.started\");\n if (!startedEvent) {\n return {\n status: \"failure\",\n failure: resumeFailure(\n \"resume_target_not_found\",\n \"Resume target has no workflow.started event.\",\n ),\n };\n }\n\n if (startedEvent.workflowId !== options.workflow.id) {\n return {\n status: \"failure\",\n failure: resumeFailure(\n \"resume_workflow_mismatch\",\n `Resume target workflow ${startedEvent.workflowId} does not match ${options.workflow.id}.`,\n ),\n };\n }\n\n const input = readPlainPayload(startedEvent, \"input\");\n if (!input) {\n return {\n status: \"failure\",\n failure: resumeFailure(\n \"resume_target_not_found\",\n \"workflow.started payload is missing input.\",\n ),\n };\n }\n\n const replay = await replayCompletedSteps({\n workflow: options.workflow,\n events: options.events,\n input,\n targetStepId: anchor.stepId,\n runDir: options.runDir,\n });\n if (replay.status === \"failure\") {\n return replay;\n }\n\n const { node } = replay;\n const artifactPaths = resolveStepArtifactPaths({\n runDir: options.runDir,\n stepId: anchor.stepId,\n stepIndex,\n });\n\n const outputSchema = resolveStepOutputSchema(node.config);\n if (!outputSchema) {\n return {\n status: \"failure\",\n failure: resumeFailure(\n \"resume_output_schema_unresolvable\",\n `Step ${node.config.id} has no resolvable output schema to reattach with.`,\n ),\n };\n }\n\n const reattached = await readReattachedInteractiveOutput({\n stepId: anchor.stepId,\n interactiveFile: artifactPaths.interactiveFile,\n outputSchema,\n });\n if (reattached.status === \"failure\") {\n return reattached;\n }\n\n const nextNode = await withStepContext(anchor.stepId, artifactPaths.stepDir, async () =>\n node.onOutput(\n outputSchema.assert(reattached.output, `step ${node.config.id} output`),\n node.config.input,\n ),\n );\n\n return {\n status: \"success\",\n input,\n node: nextNode,\n resumedStepId: anchor.stepId,\n sourceFailureEventId: anchor.id,\n };\n}\n\n/**\n * Reads the anchor step's already-existing interactive.json protocol file —\n * never spawns a new agent process. If the session was still \"active\" when\n * the previous process died, re-enters the same file-polling wait the live\n * dispatch path uses (`waitForInteractiveCompletion`) rather than giving up.\n */\nasync function readReattachedInteractiveOutput(options: {\n readonly stepId: string;\n readonly interactiveFile: string;\n readonly outputSchema: Schema;\n}): Promise<\n | { readonly status: \"success\"; readonly output: PlainObject }\n | { readonly status: \"failure\"; readonly failure: Failure }\n> {\n const first = await tryReadCompletedInteractiveOutput(options);\n if (first.status !== \"still-active\") {\n return first;\n }\n\n const abortController = new AbortController();\n await waitForInteractiveCompletion(options.interactiveFile, abortController.signal);\n\n const second = await tryReadCompletedInteractiveOutput(options);\n if (second.status !== \"still-active\") {\n return second;\n }\n\n throw new TrailStepFailureError({\n code: \"interactive_session_incomplete\",\n message: `Interactive agent step ${options.stepId} did not complete after reattaching.`,\n });\n}\n\nasync function tryReadCompletedInteractiveOutput(options: {\n readonly stepId: string;\n readonly interactiveFile: string;\n readonly outputSchema: Schema;\n}): Promise<\n | { readonly status: \"success\"; readonly output: PlainObject }\n | { readonly status: \"failure\"; readonly failure: Failure }\n | { readonly status: \"still-active\" }\n> {\n try {\n return { status: \"success\", output: await readCompletedInteractiveOutput(options) };\n } catch (error) {\n if (error instanceof TrailStepFailureError) {\n if (error.failure.code === \"interactive_session_incomplete\") {\n return { status: \"still-active\" };\n }\n\n if (error.failure.code === \"interactive_session_cancelled\") {\n return {\n status: \"failure\",\n failure: resumeFailure(\n \"resume_interactive_session_cancelled\",\n `Interactive agent step ${options.stepId} was cancelled and cannot be resumed.`,\n ),\n };\n }\n\n if (error.failure.code === \"interactive_session_invalid\") {\n return {\n status: \"failure\",\n failure: resumeFailure(\n \"resume_interactive_protocol_missing\",\n `Interactive agent step ${options.stepId} has no readable interactive.json to reattach to.`,\n ),\n };\n }\n }\n\n throw error;\n }\n}\n\nfunction readPlainPayload(event: Event, key: string): PlainObject | undefined {\n const value = event.payload[key];\n return isPlainObject(value) ? value : undefined;\n}\n\nfunction isPlainObject(value: unknown): value is PlainObject {\n return (\n typeof value === \"object\" &&\n value !== null &&\n !Array.isArray(value) &&\n Object.getPrototypeOf(value) === Object.prototype\n );\n}\n\nfunction resumeFailure(code: string, message: string): Failure {\n return { code, message };\n}\n","import type { StepNode } from \"../../../authoring/step/continuation.types.js\";\nimport type { Failure } from \"../../../contracts/failures/failure.js\";\nimport type { PlainObject } from \"../../../contracts/shapes/shape.types.js\";\nimport type {\n Event,\n RunWorkflowOptions,\n} from \"../../../runtime/run-workflow/run-workflow.types.js\";\nimport { replayCompletedSteps } from \"../replay-completed-steps/replay-completed-steps.js\";\n\nexport async function replayToFailedStep<\n TInput extends PlainObject,\n TOutput extends PlainObject,\n>(options: {\n readonly workflow: RunWorkflowOptions<TInput, TOutput>[\"workflow\"];\n readonly events: readonly Event[];\n readonly runDir: string;\n}): Promise<\n | {\n readonly status: \"success\";\n readonly input: PlainObject;\n readonly node: StepNode;\n readonly resumedStepId: string;\n readonly sourceFailureEventId: string;\n }\n | { readonly status: \"failure\"; readonly failure: Failure }\n> {\n const startedEvent = options.events.find((event) => event.type === \"workflow.started\");\n if (!startedEvent) {\n return {\n status: \"failure\",\n failure: resumeFailure(\n \"resume_target_not_found\",\n \"Resume target has no workflow.started event.\",\n ),\n };\n }\n\n if (startedEvent.workflowId !== options.workflow.id) {\n return {\n status: \"failure\",\n failure: resumeFailure(\n \"resume_workflow_mismatch\",\n `Resume target workflow ${startedEvent.workflowId} does not match ${options.workflow.id}.`,\n ),\n };\n }\n\n const terminalEvent = options.events.at(-1);\n if (terminalEvent?.type !== \"workflow.failed\") {\n return {\n status: \"failure\",\n failure: resumeFailure(\n \"resume_target_not_failed\",\n \"Resume target must end in workflow.failed.\",\n ),\n };\n }\n\n const recoveredFailedStep = options.events.find(\n (event, index) =>\n event.type === \"step.failed\" &&\n options.events\n .slice(index + 1)\n .some(\n (laterEvent) =>\n laterEvent.type === \"step.completed\" && laterEvent.stepId === event.stepId,\n ),\n );\n if (recoveredFailedStep) {\n return {\n status: \"failure\",\n failure: resumeFailure(\n \"resume_unsupported_history\",\n `Resume does not support recovered onError history for step ${recoveredFailedStep.stepId ?? \"<missing>\"}.`,\n ),\n };\n }\n\n const failedStepEvents = options.events.filter((event) => event.type === \"step.failed\");\n if (failedStepEvents.length !== 1) {\n return {\n status: \"failure\",\n failure: resumeFailure(\n \"resume_multiple_failed_steps\",\n \"Resume target must contain exactly one failed step.\",\n ),\n };\n }\n\n const failedStepEvent = failedStepEvents[0];\n if (!failedStepEvent) {\n return {\n status: \"failure\",\n failure: resumeFailure(\"resume_target_not_failed\", \"Resume target has no failed step.\"),\n };\n }\n\n if (!failedStepEvent.stepId) {\n return {\n status: \"failure\",\n failure: resumeFailure(\"resume_target_not_failed\", \"Failed step event has no step id.\"),\n };\n }\n\n const input = readPlainPayload(startedEvent, \"input\");\n if (!input) {\n return {\n status: \"failure\",\n failure: resumeFailure(\n \"resume_target_not_found\",\n \"workflow.started payload is missing input.\",\n ),\n };\n }\n\n const replay = await replayCompletedSteps({\n workflow: options.workflow,\n events: options.events,\n input,\n targetStepId: failedStepEvent.stepId,\n runDir: options.runDir,\n });\n if (replay.status === \"failure\") {\n return replay;\n }\n\n const { node } = replay;\n if (node.onError) {\n return {\n status: \"failure\",\n failure: resumeFailure(\n \"resume_unsupported_history\",\n `Resume does not support onError history for step ${node.config.id}.`,\n ),\n };\n }\n\n return {\n status: \"success\",\n input,\n node,\n resumedStepId: failedStepEvent.stepId,\n sourceFailureEventId: failedStepEvent.id,\n };\n}\n\nfunction readPlainPayload(event: Event, key: string): PlainObject | undefined {\n const value = event.payload[key];\n return isPlainObject(value) ? value : undefined;\n}\n\nfunction isPlainObject(value: unknown): value is PlainObject {\n return (\n typeof value === \"object\" &&\n value !== null &&\n !Array.isArray(value) &&\n Object.getPrototypeOf(value) === Object.prototype\n );\n}\n\nfunction resumeFailure(code: string, message: string): Failure {\n return { code, message };\n}\n","import type { StepNode } from \"../../authoring/step/continuation.types.js\";\nimport type { Failure } from \"../../contracts/failures/failure.js\";\nimport type { PlainObject } from \"../../contracts/shapes/shape.types.js\";\nimport { replayCompletedSteps } from \"../resume/replay-completed-steps/replay-completed-steps.js\";\nimport type { Event, RunWorkflowOptions } from \"../run-workflow/run-workflow.types.js\";\nimport { selectLatestUnresolvedFailure } from \"./latest-unresolved-failure.js\";\n\nexport async function replayToRetryFailure<\n TInput extends PlainObject,\n TOutput extends PlainObject,\n>(options: {\n readonly workflow: RunWorkflowOptions<TInput, TOutput>[\"workflow\"];\n readonly events: readonly Event[];\n readonly runDir: string;\n}): Promise<\n | {\n readonly status: \"success\";\n readonly input: PlainObject;\n readonly node: StepNode;\n readonly retriedStepId: string;\n readonly sourceFailureEventId: string;\n readonly sourceFailureReplayPosition: number;\n }\n | { readonly status: \"failure\"; readonly failure: Failure }\n> {\n const failure = selectLatestUnresolvedFailure(options.events);\n if (!failure) {\n return {\n status: \"failure\",\n failure: retryFailure(\n \"retry_target_not_failed\",\n \"Retry target has no latest unresolved failure.\",\n ),\n };\n }\n\n if (failure.workflowId !== options.workflow.id) {\n return {\n status: \"failure\",\n failure: retryFailure(\n \"retry_workflow_mismatch\",\n `Retry target workflow ${failure.workflowId} does not match ${options.workflow.id}.`,\n ),\n };\n }\n\n if (!failure.workflowInput) {\n return {\n status: \"failure\",\n failure: retryFailure(\"retry_target_not_found\", \"workflow.started payload is missing input.\"),\n };\n }\n\n if (!failure.stepId) {\n return {\n status: \"failure\",\n failure: retryFailure(\n \"retry_target_not_failed\",\n failure.event.type === \"workflow.failed\"\n ? \"Workflow failure has no associated step ID. This run may use unsupported historical retry metadata.\"\n : \"Failed retry target event has no step ID.\",\n ),\n };\n }\n\n const replay = await replayCompletedSteps({\n workflow: options.workflow,\n events: eventsBeforeRetryTarget(options.events, failure.replayPosition, failure.stepId),\n input: failure.workflowInput,\n targetStepId: failure.stepId,\n runDir: options.runDir,\n });\n if (replay.status === \"failure\") {\n return replay;\n }\n\n const { node } = replay;\n if (node.onError) {\n return {\n status: \"failure\",\n failure: retryFailure(\n \"retry_unsupported_history\",\n `Retry does not support onError history for step ${node.config.id}.`,\n ),\n };\n }\n\n return {\n status: \"success\",\n input: failure.workflowInput,\n node,\n retriedStepId: failure.stepId,\n sourceFailureEventId: failure.sourceFailureEventId ?? failure.event.id,\n sourceFailureReplayPosition: failure.replayPosition,\n };\n}\n\nfunction eventsBeforeRetryTarget(\n events: readonly Event[],\n replayPosition: number,\n targetStepId: string,\n): readonly Event[] {\n const eventsBeforeFailure = events.slice(0, replayPosition);\n let targetAttemptStartPosition = -1;\n\n for (let index = eventsBeforeFailure.length - 1; index >= 0; index -= 1) {\n const event = eventsBeforeFailure[index];\n if (event?.type === \"step.started\" && event.stepId === targetStepId) {\n targetAttemptStartPosition = index;\n break;\n }\n }\n\n if (targetAttemptStartPosition === -1) {\n return eventsBeforeFailure;\n }\n\n return eventsBeforeFailure.filter(\n (event, index) =>\n index <= targetAttemptStartPosition ||\n event.type !== \"step.completed\" ||\n event.stepId !== targetStepId,\n );\n}\n\nfunction retryFailure(code: string, message: string): Failure {\n return { code, message };\n}\n","import type { TrailStepConfig } from \"../../agent-targeting/targeting.types.js\";\nimport type { WorkflowAgentRole } from \"../../contracts/agents/agent-role.types.js\";\nimport type {\n RunContext,\n RunContextEvent,\n RunContextProviderWorkingRunner,\n RunContextWorkingAgentProcessRunner,\n} from \"../../contracts/run-context/run-context.types.js\";\nimport { type RunState, readRunState, writeRunState } from \"../artifacts/run-storage.js\";\n\nexport function createRunContext(options: {\n readonly runId: string;\n readonly runName: string;\n readonly runDir: string;\n readonly workflowId?: string;\n readonly workflowAgents?: Readonly<Record<string, WorkflowAgentRole>>;\n readonly cwd?: string;\n readonly trailstepConfig?: TrailStepConfig;\n readonly workingAgentProcessRunner?: RunContextWorkingAgentProcessRunner;\n readonly providerWorkingRunner?: RunContextProviderWorkingRunner;\n readonly emit?: (event: RunContextEvent) => Promise<void>;\n readonly events?: () => readonly RunContextEvent[];\n}): RunContext {\n // Cache + load memoization scope this instance's state to a single process:\n // a resumed run creates a fresh RunContext and reloads from disk, so staleness\n // across process boundaries isn't a concern.\n let cache: RunState | undefined;\n let loadPromise: Promise<RunState> | undefined;\n let writeQueue: Promise<unknown> = Promise.resolve();\n\n function ensureLoaded(): Promise<RunState> {\n if (cache) return Promise.resolve(cache);\n loadPromise ??= readRunState(options.runDir).then((state) => (cache = state));\n return loadPromise;\n }\n\n // Writes are serialized behind this instance's cache so that concurrent\n // `set` calls (parallel steps) can't interleave their disk writes out of\n // mutation order; each queued write flushes whatever the cache holds when\n // it actually runs, so the file always converges on the latest state.\n function enqueueWrite(): Promise<void> {\n const next = writeQueue.then(async () => {\n // `enqueueWrite` is only invoked after `ensureLoaded` has resolved (see\n // `set` below), so this call resolves synchronously against the\n // already-populated cache rather than re-reading from disk.\n const state = await ensureLoaded();\n await writeRunState(options.runDir, state);\n });\n writeQueue = next.catch(() => {});\n return next;\n }\n\n return {\n id: options.runId,\n name: options.runName,\n path: options.runDir,\n workflowId: options.workflowId,\n workflowAgents: options.workflowAgents,\n cwd: options.cwd,\n trailstepConfig: options.trailstepConfig,\n workingAgentProcessRunner: options.workingAgentProcessRunner,\n providerWorkingRunner: options.providerWorkingRunner,\n emit: options.emit,\n events: options.events,\n state: {\n async get<T = unknown>(key: string): Promise<T | undefined> {\n const state = await ensureLoaded();\n return state[key] as T | undefined;\n },\n async set(key: string, value: unknown): Promise<void> {\n const state = await ensureLoaded();\n state[key] = value;\n await enqueueWrite();\n },\n },\n };\n}\n","import { basename } from \"node:path\";\n\nimport type { PlainObject } from \"../../contracts/shapes/shape.types.js\";\nimport { createRunDirectory, readRunEvents } from \"../artifacts/run-storage.js\";\nimport type { Event, RunWorkflowOptions } from \"./run-workflow.types.js\";\n\nexport async function initializeRun<TInput extends PlainObject, TOutput extends PlainObject>(\n options: RunWorkflowOptions<TInput, TOutput>,\n): Promise<{\n readonly runId: string;\n readonly runName: string;\n readonly runDir: string;\n readonly previousEvents: readonly Event[];\n}> {\n const existingRunDir = options.resume?.runDir ?? options.retry?.runDir;\n if (existingRunDir) {\n const previousEvents = await readRunEvents(existingRunDir);\n const startedEvent = previousEvents.find((event) => event.type === \"workflow.started\");\n return {\n runId: startedEvent?.runId ?? basename(existingRunDir),\n runName: startedEvent?.runId ?? basename(existingRunDir),\n runDir: existingRunDir,\n previousEvents,\n };\n }\n\n const cwd = options.cwd ?? process.cwd();\n const runName = options.runName;\n if (runName === undefined) {\n throw new Error(\"Expected runName for a new workflow run.\");\n }\n const { runId, runDir } = await createRunDirectory({\n cwd,\n runName,\n runsRoot: options.runsRoot,\n });\n return { runId, runName, runDir, previousEvents: [] };\n}\n","import {\n isParsedTrailStepConfig,\n parseTrailStepConfig,\n} from \"../../agent-targeting/parse-trailstep-config/parse-trailstep-config.js\";\nimport type { TrailStepConfig } from \"../../agent-targeting/targeting.types.js\";\nimport type { RunWorkflowOptions } from \"./run-workflow.types.js\";\n\nexport function parseTrailStepConfigInput(\n value: RunWorkflowOptions[\"trailstepConfig\"],\n): TrailStepConfig {\n if (isParsedTrailStepConfig(value) || isFlattenedTrailStepConfig(value)) {\n return value;\n }\n\n return parseTrailStepConfig(value);\n}\n\nfunction isFlattenedTrailStepConfig(\n value: RunWorkflowOptions[\"trailstepConfig\"],\n): value is TrailStepConfig {\n if (!isPlainRecord(value) || value.version !== 1) {\n return false;\n }\n\n if (!isPlainRecord(value.customProviders) || !isFlattenedAgentMappings(value.agents)) {\n return false;\n }\n\n if (value.settings !== undefined && !isFlattenedSettings(value.settings)) {\n return false;\n }\n\n if (value.workflows === undefined) {\n return true;\n }\n\n if (!isPlainRecord(value.workflows)) {\n return false;\n }\n\n return Object.values(value.workflows).every(\n (workflow) =>\n isPlainRecord(workflow) &&\n (workflow.agents === undefined || isFlattenedAgentMappings(workflow.agents)) &&\n (workflow.settings === undefined || isFlattenedSettings(workflow.settings)),\n );\n}\n\nfunction isFlattenedSettings(value: unknown): value is NonNullable<TrailStepConfig[\"settings\"]> {\n return (\n isPlainRecord(value) &&\n (value.retry === undefined || isPlainRecord(value.retry)) &&\n (value.timeout === undefined || typeof value.timeout === \"number\")\n );\n}\n\nfunction isFlattenedAgentMappings(value: unknown): value is TrailStepConfig[\"agents\"] {\n return (\n isPlainRecord(value) &&\n Object.values(value).every(\n (targets) => Array.isArray(targets) && targets.every(isFlattenedAgentTarget),\n )\n );\n}\n\nfunction isFlattenedAgentTarget(\n value: unknown,\n): value is TrailStepConfig[\"agents\"][string][number] {\n if (!isPlainRecord(value) || typeof value.provider !== \"string\") {\n return false;\n }\n\n if (value.model !== undefined) {\n return typeof value.model === \"string\" && value.model.trim().length > 0;\n }\n\n return true;\n}\n\nfunction isPlainRecord(value: unknown): value is Readonly<Record<string, unknown>> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n","import type { Dirent } from \"node:fs\";\nimport { readdir } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { defaultRunsRoot, readRunEvents } from \"../artifacts/run-storage.js\";\nimport type { LatestUnresolvedFailure } from \"../retry/latest-unresolved-failure.js\";\nimport { selectLatestUnresolvedFailure } from \"../retry/latest-unresolved-failure.js\";\nimport type { Event } from \"../run-workflow/run-workflow.types.js\";\n\nexport type RunSummaryStatus = \"active\" | \"completed\" | \"failed\" | \"unknown\";\n\nexport interface RunSummary {\n readonly runId: string;\n readonly runDir: string;\n readonly status: RunSummaryStatus;\n readonly workflowId?: string;\n readonly lastTimestamp?: string;\n readonly latestFailure?: LatestUnresolvedFailure;\n readonly warning?: string;\n}\n\nexport async function listRunSummaries(options: {\n readonly cwd: string;\n readonly runsRoot?: string;\n}): Promise<RunSummary[]> {\n const runsRoot = options.runsRoot ?? defaultRunsRoot(options.cwd);\n\n let entries: Dirent[];\n try {\n entries = await readdir(runsRoot, { withFileTypes: true });\n } catch (error) {\n if (isNodeError(error) && error.code === \"ENOENT\") {\n return [];\n }\n\n throw error;\n }\n\n const summaries: RunSummary[] = [];\n\n for (const entry of entries) {\n if (!entry.isDirectory()) {\n continue;\n }\n\n const runId = entry.name;\n const runDir = join(runsRoot, runId);\n\n try {\n summaries.push(summarizeReadableRun({ runId, runDir, events: await readRunEvents(runDir) }));\n } catch (error) {\n summaries.push({\n runId,\n runDir,\n status: \"unknown\",\n warning: `Warning: Could not read run ${runId}: ${readErrorMessage(error)}`,\n });\n }\n }\n\n return summaries.sort(newestFirst);\n}\n\nexport function selectRecentFailedRunSummaries(\n summaries: readonly RunSummary[],\n options: { readonly now?: Date } = {},\n): RunSummary[] {\n const cutoffMs = (options.now ?? new Date()).getTime() - 7 * 24 * 60 * 60 * 1000;\n\n return summaries\n .filter((summary) => {\n if (summary.status !== \"failed\" || !summary.latestFailure) {\n return false;\n }\n\n const failureTime = Date.parse(summary.latestFailure.event.timestamp);\n return Number.isFinite(failureTime) && failureTime >= cutoffMs;\n })\n .sort(newestFirst)\n .slice(0, 10);\n}\n\nexport function newestFirst(left: RunSummary, right: RunSummary): number {\n return (\n compareTimestampDescending(left.lastTimestamp, right.lastTimestamp) ||\n left.runId.localeCompare(right.runId)\n );\n}\n\nfunction summarizeReadableRun(options: {\n readonly runId: string;\n readonly runDir: string;\n readonly events: readonly Event[];\n}): RunSummary {\n const latestFailure = selectLatestUnresolvedFailure(options.events);\n const terminalStatus = selectTerminalStatus(options.events);\n const lastEvent = options.events.at(-1);\n const workflowId =\n lastEvent?.workflowId ?? options.events.find((event) => event.workflowId)?.workflowId;\n\n if (terminalStatus === \"completed\") {\n return {\n ...options,\n status: \"completed\",\n workflowId,\n lastTimestamp: lastEvent?.timestamp,\n };\n }\n\n if (latestFailure) {\n return {\n ...options,\n status: \"failed\",\n workflowId: latestFailure.workflowId,\n lastTimestamp: latestFailure.event.timestamp,\n latestFailure,\n };\n }\n\n return {\n ...options,\n status: terminalStatus ?? \"active\",\n workflowId,\n lastTimestamp: lastEvent?.timestamp,\n };\n}\n\nfunction selectTerminalStatus(events: readonly Event[]): \"completed\" | \"failed\" | undefined {\n for (let index = events.length - 1; index >= 0; index -= 1) {\n const event = events[index];\n if (event?.type === \"workflow.completed\") {\n return \"completed\";\n }\n\n if (event?.type === \"workflow.failed\") {\n return \"failed\";\n }\n }\n\n return undefined;\n}\n\nfunction compareTimestampDescending(left: string | undefined, right: string | undefined): number {\n const leftTime = left ? Date.parse(left) : Number.NEGATIVE_INFINITY;\n const rightTime = right ? Date.parse(right) : Number.NEGATIVE_INFINITY;\n return rightTime - leftTime;\n}\n\nfunction readErrorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\nfunction isNodeError(error: unknown): error is NodeJS.ErrnoException {\n return error instanceof Error && \"code\" in error;\n}\n"],"mappings":";AAMO,IAAM,wBAAN,cAAoC,MAAM;AAAA,EACtC;AAAA,EAET,YAAY,SAAkB;AAC5B,UAAM,QAAQ,OAAO;AACrB,SAAK,OAAO;AACZ,SAAK,UAAU;AAAA,EACjB;AACF;AAEO,SAAS,kBAAkB,SAAiB,SAA4B;AAC7E,SAAO;AAAA,IACL,MAAM;AAAA,IACN;AAAA,IACA,GAAI,YAAY,SAAY,CAAC,IAAI,EAAE,QAAQ;AAAA,EAC7C;AACF;;;ACdO,SAAS,gBAAgB,SA0B9B;AACA,QAAM,iBAAkE,CAAC;AACzE,QAAM,OAAO,oBAAI,IAA6C;AAE9D,aAAW,QAAQ,OAAO,KAAK,QAAQ,MAAM,GAAG;AAC9C,mBAAe,IAA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B;AACxC,aAAO;AAAA,IACT;AAEA,QAAI,OAAO,SAAS,mBAAmB;AACrC,aAAO;AAAA,IACT;AAAA,EACF;AAEA,SAAO;AACT;AAEA,SAAS,2BAA2B,MAA0B,OAAmC;AAC/F,QAAM,WAAW,OAAO,KAAK,MAAM,IAAI,IAAI,OAAO;AAClD,QAAM,YAAY,QAAQ,KAAK,MAAM,KAAK,IAAI,OAAO;AACrD,SAAO,YAAY;AACrB;AAEA,SAAS,iBAAiB,OAAwB;AAChD,SAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AAC9D;AAEA,SAASD,aAAY,OAAgD;AACnE,SAAO,iBAAiB,SAAS,UAAU;AAC7C;","names":["THINKING_LEVELS","resolve","spawn","runWorking","runInteractive","resolve","spawn","terminateChildProcessTree","spawn","writeFile","runWorking","writeFile","runInteractive","resolve","spawn","terminateChildProcessTree","spawn","writeFile","runWorking","writeFile","runInteractive","resolve","spawn","terminateChildProcessTree","targets","readFile","writeFile","dirname","join","join","readFile","join","writeFile","readFile","state","dirname","join","isPlainObject","formatDiagnostics","isPlainObject","mkdir","writeFile","readFile","join","spawn","mkdir","writeFile","dirname","readFile","formatDiagnostics","readFile","optionalNonEmptyString","writeFile","mkdir","dirname","resolve","spawn","terminateChildProcessTree","mkdir","writeFile","join","join","readFile","readFile","spawn","resolve","terminateChildProcessTree","writeFile","writeFile","mkdir","writeFile","readFile","join","isPlainObject","isPlainObject","mkdir","writeFile","isPlainObject","basename","firstConfiguredPolicy","nextNode","readPlainPayload","isPlainObject","readPlainPayload","isPlainObject","resumeFailure","readPlainPayload","isPlainObject","state","basename","basename","basename","join","isNodeError","join"]}
|
|
1
|
+
{"version":3,"sources":["../src/agent-execution/interactive-agent/launch-interactive-agent-target.ts","../src/cli-provider-runtime/process/resolve-cli-command.ts","../src/contracts/failures/failure.ts","../src/agent-execution/custom-provider/render-custom-provider-args.ts","../src/agent-targeting/parse-trailstep-config/parse-utils.ts","../src/providers/provider-manifest.ts","../src/agent-targeting/parse-trailstep-config/expand-agent-refs.ts","../src/agent-targeting/parse-trailstep-config/parse-agent-targets.ts","../src/agent-targeting/parse-trailstep-config/parse-agent-mappings.ts","../src/agent-targeting/parse-trailstep-config/parse-custom-providers.ts","../src/agent-targeting/parse-trailstep-config/parse-settings.ts","../src/runtime/storage-lifecycle/storage-lifecycle.ts","../src/runtime/artifacts/run-storage.ts","../src/runtime/runs/run-summaries.ts","../src/runtime/retry/latest-unresolved-failure.ts","../src/runtime/runs/track-summary.ts","../src/agent-targeting/parse-trailstep-config/parse-storage-config.ts","../src/agent-targeting/parse-trailstep-config/parse-workflow-agent-mappings.ts","../src/agent-targeting/parse-trailstep-config/validate-provider-references.ts","../src/agent-targeting/parse-trailstep-config/parse-trailstep-config.ts","../src/agent-targeting/resolve-agent-targets/resolve-agent-targets.ts","../src/runtime/run-context/run-context-storage.ts","../src/authoring/document/document.ts","../src/authoring/global-state/global-state.ts","../src/runtime/events/create-run-event.ts","../src/authoring/notify/notify.ts","../src/authoring/prompt-composition/prompt-composition.ts","../src/authoring/prompt-template/prompt-template.ts","../src/authoring/shape/json-schema.ts","../src/authoring/state/state.ts","../src/authoring/step/step-node.ts","../src/runtime/sub-prompts/run-sub-prompt.ts","../src/agent-execution/adapter-agent/run-adapter-agent-step/run-adapter-agent-step.ts","../src/agent-execution/dispatch-agent-step/dispatch-agent-step.ts","../src/runtime/artifacts/step-artifacts.ts","../src/agent-execution/interactive-agent/run-interactive-agent-command.ts","../src/runtime/interactive-session/interactive-session-protocol.ts","../src/agent-execution/working-agent/run-working-agent-command.ts","../src/agent-execution/working-agent/artifacts/resolve-step-agent-files.ts","../src/agent-execution/working-agent/prompts/build-working-agent-prompt.ts","../src/agent-execution/working-agent/targets/run-working-agent-target-attempt.ts","../src/agent-execution/working-agent/output/read-working-agent-output.ts","../src/agent-execution/working-agent/targets/custom-provider/build-working-agent-args.ts","../src/agent-execution/working-agent/targets/custom-provider/spawn-working-agent-process.ts","../src/agent-execution/working-agent/targets/custom-provider/run-custom-working-provider.ts","../src/agent-execution/working-agent/targets/manifest-provider/run-manifest-working-provider.ts","../src/cli-provider-runtime/envelopes/envelope.ts","../src/agent-execution/working-agent/targets/target-failures.ts","../src/runtime/sub-prompts/sub-prompt-artifacts.ts","../src/runtime/failures/failure-like.ts","../src/runtime/sub-prompts/sub-prompt-failures.ts","../src/runtime/sub-prompts/sub-prompt-fingerprint.ts","../src/runtime/sub-prompts/sub-prompt-replay.ts","../src/authoring/step/sub-prompt.ts","../src/authoring/workflow/define-workflow.ts","../src/authoring/workflow/workflow.ts","../src/deprecations/deprecation-manifest.ts","../src/runtime/cancellation/cancellation.ts","../src/runtime/retry/retry-policy.ts","../src/runtime/run-workflow/run-workflow.ts","../src/runtime/continuation/run-continuation/run-continuation.ts","../src/runtime/failures/step-execution-failure.ts","../src/runtime/run-context/with-step-context.ts","../src/runtime/run-workflow/cwd.ts","../src/runtime/timeout/timeout-policy.ts","../src/runtime/interactive-session/default-interactive-output-shape.ts","../src/runtime/continuation/resolve-step-output-schema/resolve-step-output-schema.ts","../src/runtime/failures/workflow-failure.ts","../src/runtime/resume/replay-completed-steps/replay-completed-steps.ts","../src/runtime/resume/reattach-in-progress-step/reattach-in-progress-step.ts","../src/runtime/resume/replay-to-failed-step/replay-to-failed-step.ts","../src/runtime/resume/replay-to-waiting-step/replay-to-waiting-step.ts","../src/runtime/retry/replay-to-retry-failure.ts","../src/runtime/run-context/create-run-context.ts","../src/runtime/run-workflow/initialize-run.ts","../src/runtime/run-workflow/root-continuation-array-scheduler.ts","../src/runtime/run-workflow/trailstep-config-input.ts"],"sourcesContent":["import { spawn } from \"node:child_process\";\nimport { mkdir, writeFile } from \"node:fs/promises\";\nimport { dirname } from \"node:path\";\n\nimport type {\n TrailStepAgentTarget,\n TrailStepConfig,\n} from \"../../agent-targeting/targeting.types.js\";\nimport type { ManagedSessionPromptInjectionMode } from \"../../cli-provider-runtime/catalog/provider-adapter.types.js\";\nimport { resolveCliCommandForSpawn } from \"../../cli-provider-runtime/process/resolve-cli-command.js\";\nimport { TrailStepFailureError } from \"../../contracts/failures/failure.js\";\nimport type {\n InteractiveProcessResult,\n InteractiveProcessRunner,\n} from \"../../runtime/run-workflow/run-workflow.types.js\";\nimport { renderCustomProviderArgs } from \"../custom-provider/render-custom-provider-args.js\";\n\nexport interface LaunchInteractiveAgentTargetOptions {\n readonly config: TrailStepConfig;\n readonly target: TrailStepAgentTarget;\n readonly prompt: string;\n readonly promptFile: string;\n readonly cwd: string;\n readonly runner?: InteractiveProcessRunner;\n readonly signal?: AbortSignal;\n}\n\nexport type LaunchInteractiveAgentTargetResult = InteractiveProcessResult & {\n readonly promptInjectionMode: ManagedSessionPromptInjectionMode;\n};\n\nexport async function launchInteractiveAgentTarget(\n options: LaunchInteractiveAgentTargetOptions,\n): Promise<LaunchInteractiveAgentTargetResult> {\n const manifestProvider = options.config.providers?.[options.target.provider];\n if (manifestProvider !== undefined && manifestProvider.source.type !== \"legacy-custom-provider\") {\n const interactive = manifestProvider.manifest.interactive;\n if (!interactive.supported || interactive.command === undefined) {\n throw new TrailStepFailureError({\n code: \"agent_provider_interactive_unsupported\",\n message: `Provider '${options.target.provider}' does not support interactive launch.`,\n details: { provider: options.target.provider },\n });\n }\n\n const command = interactive.command;\n const args = renderCustomProviderArgs({\n argv: options.target.args ?? [\"{{prompt}}\"],\n values: {\n prompt: options.prompt,\n promptFile: options.promptFile,\n ...(options.target.model === undefined ? {} : { model: options.target.model }),\n ...(options.target.thinking === undefined ? {} : { thinking: options.target.thinking }),\n },\n errorCode: \"interactive_command_invalid\",\n commandDescription: \"Manifest interactive provider command\",\n });\n const promptInjectionMode: ManagedSessionPromptInjectionMode = args.includes(options.promptFile)\n ? \"visible-prompt-file\"\n : \"visible-inline-prompt\";\n\n if (args.includes(options.promptFile)) {\n await mkdir(dirname(options.promptFile), { recursive: true });\n await writeFile(options.promptFile, options.prompt, \"utf8\");\n }\n\n let result: InteractiveProcessResult;\n try {\n result = await (options.runner ?? spawnInteractiveProcess)({\n command,\n args,\n cwd: options.cwd,\n shell: false,\n stdio: \"inherit\",\n env: definedProcessEnv(),\n signal: options.signal,\n });\n } catch (error) {\n throw mapInteractiveProviderLaunchError({\n error,\n provider: options.target.provider,\n command,\n });\n }\n\n return { ...result, promptInjectionMode };\n }\n\n const customProvider = options.config.customProviders[options.target.provider];\n if (!customProvider) {\n throw new TrailStepFailureError({\n code: \"agent_provider_unavailable\",\n message: `Interactive agent target '${options.target.provider}' does not reference a configured custom provider.`,\n details: { provider: options.target.provider },\n });\n }\n\n if (!customProvider.interactiveArgs) {\n throw new TrailStepFailureError({\n code: \"agent_provider_interactive_unsupported\",\n message: `Custom provider '${options.target.provider}' cannot run interactive sessions because customProviders.${options.target.provider}.interactiveArgs is not declared.`,\n details: { provider: options.target.provider },\n });\n }\n\n const args = renderCustomProviderArgs({\n argv: options.target.args ?? customProvider.interactiveArgs,\n values: {\n prompt: options.prompt,\n promptFile: options.promptFile,\n ...(options.target.model === undefined ? {} : { model: options.target.model }),\n ...(options.target.thinking === undefined ? {} : { thinking: options.target.thinking }),\n },\n errorCode: \"interactive_command_invalid\",\n commandDescription: \"Interactive agent command\",\n });\n const promptInjectionMode: ManagedSessionPromptInjectionMode = args.includes(options.promptFile)\n ? \"visible-prompt-file\"\n : \"visible-inline-prompt\";\n\n if (args.includes(options.promptFile)) {\n await mkdir(dirname(options.promptFile), { recursive: true });\n await writeFile(options.promptFile, options.prompt, \"utf8\");\n }\n\n const result = await (options.runner ?? spawnInteractiveProcess)({\n command: customProvider.binary,\n args,\n cwd: options.cwd,\n shell: false,\n stdio: \"inherit\",\n env: { ...definedProcessEnv(), ...customProvider.env },\n signal: options.signal,\n });\n\n return { ...result, promptInjectionMode };\n}\n\nfunction mapInteractiveProviderLaunchError(options: {\n readonly error: unknown;\n readonly provider: string;\n readonly command: string;\n}): unknown {\n if (options.error instanceof TrailStepFailureError) {\n return options.error;\n }\n\n const message = errorMessage(options.error);\n if (isSpawnEnoentError(options.error, options.command, message)) {\n return new TrailStepFailureError({\n code: \"agent_provider_spawn_error\",\n message: `Provider '${options.provider}' could not be opened because the '${options.command}' CLI was not found on PATH. Install the CLI or configure a different TrailStep agent target.`,\n details: { provider: options.provider, command: options.command, cause: message },\n });\n }\n\n return options.error;\n}\n\nfunction isSpawnEnoentError(error: unknown, command: string, message: string): boolean {\n if (isNodeError(error) && error.code === \"ENOENT\") {\n return true;\n }\n\n return new RegExp(\n `(?:spawn|ENOENT).*${escapeRegExp(command)}|${escapeRegExp(command)}.*ENOENT`,\n \"iu\",\n ).test(message);\n}\n\nfunction isNodeError(error: unknown): error is NodeJS.ErrnoException {\n return error instanceof Error && \"code\" in error;\n}\n\nfunction escapeRegExp(value: string): string {\n return value.replace(/[.*+?^${}()|[\\]\\\\]/gu, \"\\\\$&\");\n}\n\nfunction errorMessage(error: unknown): string {\n if (error instanceof Error) {\n return error.message;\n }\n return String(error);\n}\n\nfunction definedProcessEnv(): Record<string, string> {\n return Object.fromEntries(\n Object.entries(process.env).filter(\n (entry): entry is [string, string] => entry[1] !== undefined,\n ),\n );\n}\n\nconst spawnInteractiveProcess: InteractiveProcessRunner = async ({\n command,\n args,\n cwd,\n env,\n signal,\n}) => {\n const executable = await resolveCliCommandForSpawn({ command, args, env });\n\n return await new Promise((resolve, reject) => {\n const child = spawn(executable.command, executable.args, {\n cwd,\n env,\n signal,\n detached: process.platform !== \"win32\",\n shell: false,\n stdio: \"inherit\",\n });\n\n signal?.addEventListener(\"abort\", () => terminateChildProcessTree(child), { once: true });\n child.on(\"error\", reject);\n child.on(\"close\", (code) => resolve({ exitCode: code ?? 1 }));\n });\n};\n\nfunction terminateChildProcessTree(child: ReturnType<typeof spawn>): void {\n if (!child.pid) {\n return;\n }\n\n if (process.platform === \"win32\") {\n spawn(\"taskkill\", [\"/PID\", String(child.pid), \"/T\", \"/F\"], { stdio: \"ignore\" }).on(\n \"error\",\n () => {\n child.kill();\n },\n );\n return;\n }\n\n try {\n process.kill(-child.pid, \"SIGTERM\");\n } catch {\n child.kill();\n }\n}\n","import { constants } from \"node:fs\";\nimport { access, readFile } from \"node:fs/promises\";\nimport { dirname, extname, join } from \"node:path\";\n\nconst WINDOWS_EXECUTABLE_EXTENSIONS = [\".cmd\", \".exe\", \".bat\", \"\"] as const;\n\nexport interface CliCommandSpawnRequest {\n readonly command: string;\n readonly args: readonly string[];\n readonly env?: Readonly<Record<string, string | undefined>>;\n}\n\nexport interface ResolvedCliCommandSpawnRequest {\n readonly command: string;\n readonly args: readonly string[];\n}\n\nexport interface ResolveCliCommandForSpawnOptions {\n readonly platform?: NodeJS.Platform;\n readonly execPath?: string;\n}\n\n/**\n * Built-in provider CLIs are commonly npm-installed. On Windows, npm exposes\n * those CLIs as `.cmd` shims, which cannot be launched through Node's\n * `spawn(..., { shell: false })` by their bare command name. Resolve npm shims\n * to their underlying Node entrypoint when possible so provider prompts remain\n * argv values instead of being reinterpreted by a shell.\n */\nexport async function resolveCliCommandForSpawn(\n request: CliCommandSpawnRequest,\n options: ResolveCliCommandForSpawnOptions = {},\n): Promise<ResolvedCliCommandSpawnRequest> {\n if ((options.platform ?? process.platform) !== \"win32\") {\n return request;\n }\n\n const commandPath = await findWindowsCommandPath(request.command, request.env ?? process.env);\n if (!commandPath) {\n return request;\n }\n\n if (isWindowsCommandShim(commandPath)) {\n const nodeScript = await readNpmCmdShimEntrypoint(commandPath);\n if (nodeScript) {\n return {\n command: options.execPath ?? process.execPath,\n args: [nodeScript, ...request.args],\n };\n }\n\n return {\n command: \"cmd.exe\",\n args: [\"/d\", \"/s\", \"/c\", commandPath, ...request.args],\n };\n }\n\n return { command: commandPath, args: request.args };\n}\n\nasync function findWindowsCommandPath(\n command: string,\n env: Readonly<Record<string, string | undefined>>,\n): Promise<string | undefined> {\n const commandCandidates = windowsCommandCandidates(command);\n if (hasPathSeparator(command)) {\n return await firstExistingPath(commandCandidates);\n }\n\n const pathValue = readCaseInsensitiveEnv(env, \"PATH\");\n if (!pathValue) {\n return await firstExistingPath(commandCandidates);\n }\n\n for (const directory of pathValue.split(windowsPathDelimiter()).filter(Boolean)) {\n const found = await firstExistingPath(\n commandCandidates.map((candidate) => join(directory, candidate)),\n );\n if (found) {\n return found;\n }\n }\n\n return undefined;\n}\n\nfunction windowsCommandCandidates(command: string): readonly string[] {\n if (extname(command)) {\n return [command];\n }\n\n return WINDOWS_EXECUTABLE_EXTENSIONS.map((extension) => `${command}${extension}`);\n}\n\nasync function firstExistingPath(paths: readonly string[]): Promise<string | undefined> {\n for (const path of paths) {\n try {\n await access(path, constants.X_OK);\n return path;\n } catch {\n try {\n await access(path, constants.F_OK);\n return path;\n } catch {\n // Keep looking.\n }\n }\n }\n\n return undefined;\n}\n\nasync function readNpmCmdShimEntrypoint(commandPath: string): Promise<string | undefined> {\n let shim: string;\n try {\n shim = await readFile(commandPath, \"utf8\");\n } catch {\n return undefined;\n }\n\n const match = shim.match(/\"%dp0%\\\\?([^\"]+?\\.js)\"\\s+%\\*/i);\n if (!match?.[1]) {\n return undefined;\n }\n\n return join(dirname(commandPath), match[1].replace(/\\\\/g, \"/\"));\n}\n\nfunction isWindowsCommandShim(path: string): boolean {\n const extension = extname(path).toLowerCase();\n return extension === \".cmd\" || extension === \".bat\";\n}\n\nfunction hasPathSeparator(command: string): boolean {\n return command.includes(\"/\") || command.includes(\"\\\\\");\n}\n\nfunction readCaseInsensitiveEnv(\n env: Readonly<Record<string, string | undefined>>,\n key: string,\n): string | undefined {\n return Object.entries(env).find(([name]) => name.toLowerCase() === key.toLowerCase())?.[1];\n}\n\nfunction windowsPathDelimiter(): string {\n return \";\";\n}\n","export interface Failure {\n readonly code: string;\n readonly message: string;\n readonly details?: unknown;\n}\n\nexport class TrailStepFailureError extends Error {\n readonly failure: Failure;\n\n constructor(failure: Failure) {\n super(failure.message);\n this.name = \"TrailStepFailureError\";\n this.failure = failure;\n }\n}\n\nexport function validationFailure(message: string, details?: unknown): Failure {\n return {\n code: \"validation_failed\",\n message,\n ...(details === undefined ? {} : { details }),\n };\n}\n","import type { WorkflowAgentThinking } from \"../../contracts/agents/agent-role.types.js\";\nimport { TrailStepFailureError } from \"../../contracts/failures/failure.js\";\n\ntype PlaceholderName = \"prompt\" | \"promptFile\" | \"outputFile\" | \"model\" | \"thinking\";\ntype ConditionalName = \"model\" | \"thinking\";\n\ntype PlaceholderValues = Readonly<Partial<Record<PlaceholderName, string>>>;\n\nconst PLACEHOLDER_NAMES = new Set<PlaceholderName>([\n \"prompt\",\n \"promptFile\",\n \"outputFile\",\n \"model\",\n \"thinking\",\n]);\nconst CONDITIONAL_NAMES = new Set<ConditionalName>([\"model\", \"thinking\"]);\nconst TEMPLATE_TOKEN_PATTERN = /^{{([#/]?)([A-Za-z][A-Za-z0-9]*)}}$/;\n\nexport function renderCustomProviderArgs(options: {\n readonly argv: readonly string[];\n readonly values: {\n readonly prompt?: string;\n readonly promptFile?: string;\n readonly outputFile?: string;\n readonly model?: string;\n readonly thinking?: WorkflowAgentThinking;\n };\n readonly errorCode: string;\n readonly commandDescription: string;\n}): string[] {\n const values: PlaceholderValues = {\n ...(options.values.prompt === undefined ? {} : { prompt: options.values.prompt }),\n ...(options.values.promptFile === undefined ? {} : { promptFile: options.values.promptFile }),\n ...(options.values.outputFile === undefined ? {} : { outputFile: options.values.outputFile }),\n ...(optionalNonEmptyString(options.values.model) === undefined\n ? {}\n : { model: optionalNonEmptyString(options.values.model) }),\n ...(options.values.thinking === undefined ? {} : { thinking: options.values.thinking }),\n };\n\n return renderRange({\n argv: options.argv,\n values,\n errorCode: options.errorCode,\n commandDescription: options.commandDescription,\n });\n}\n\nfunction renderRange(options: {\n readonly argv: readonly string[];\n readonly values: PlaceholderValues;\n readonly errorCode: string;\n readonly commandDescription: string;\n}): string[] {\n const rendered: string[] = [];\n\n for (let index = 0; index < options.argv.length; index += 1) {\n const arg = options.argv[index] ?? \"\";\n const token = parseTemplateToken(arg);\n\n if (token?.kind === \"open\") {\n const closeIndex = findConditionalClose({\n argv: options.argv,\n openIndex: index,\n condition: token.name,\n errorCode: options.errorCode,\n commandDescription: options.commandDescription,\n });\n if (options.values[token.name] !== undefined) {\n rendered.push(\n ...renderRange({\n ...options,\n argv: options.argv.slice(index + 1, closeIndex),\n }),\n );\n }\n index = closeIndex;\n continue;\n }\n\n if (token?.kind === \"close\") {\n throw templateError({\n code: options.errorCode,\n message: `${options.commandDescription} template has unexpected ${closingToken(token.name)} without a matching ${openingToken(token.name)}.`,\n });\n }\n\n if (token?.kind === \"placeholder\") {\n rendered.push(renderPlaceholder({ ...options, name: token.name }));\n continue;\n }\n\n if (TEMPLATE_TOKEN_PATTERN.test(arg)) {\n throw templateError({\n code: options.errorCode,\n message: `${options.commandDescription} template token ${arg} is not supported.`,\n details: { arg },\n });\n }\n\n if (arg.includes(\"{{\") || arg.includes(\"}}\")) {\n rendered.push(renderInterpolatedArg({ ...options, arg }));\n continue;\n }\n\n rendered.push(arg);\n }\n\n return rendered;\n}\n\nfunction parseTemplateToken(\n arg: string,\n):\n | { readonly kind: \"placeholder\"; readonly name: PlaceholderName }\n | { readonly kind: \"open\"; readonly name: ConditionalName }\n | { readonly kind: \"close\"; readonly name: ConditionalName }\n | undefined {\n const match = TEMPLATE_TOKEN_PATTERN.exec(arg);\n if (!match) {\n return undefined;\n }\n\n const prefix = match[1] ?? \"\";\n const name = match[2] ?? \"\";\n\n if (prefix === \"\") {\n if (PLACEHOLDER_NAMES.has(name as PlaceholderName)) {\n return { kind: \"placeholder\", name: name as PlaceholderName };\n }\n return undefined;\n }\n\n if (CONDITIONAL_NAMES.has(name as ConditionalName)) {\n return {\n kind: prefix === \"#\" ? \"open\" : \"close\",\n name: name as ConditionalName,\n };\n }\n\n return undefined;\n}\n\nfunction renderInterpolatedArg(options: {\n readonly arg: string;\n readonly values: PlaceholderValues;\n readonly errorCode: string;\n readonly commandDescription: string;\n}): string {\n let foundTemplateToken = false;\n const rendered = options.arg.replaceAll(\n /\\{\\{([#/]?)([A-Za-z][A-Za-z0-9]*)\\}\\}/gu,\n (match: string, prefix: string, name: string) => {\n foundTemplateToken = true;\n\n if (prefix !== \"\") {\n throw templateError({\n code: options.errorCode,\n message: `${options.commandDescription} conditional blocks must be whole argv values.`,\n details: { arg: options.arg, token: match },\n });\n }\n\n if (!PLACEHOLDER_NAMES.has(name as PlaceholderName)) {\n throw templateError({\n code: options.errorCode,\n message: `${options.commandDescription} template token ${match} is not supported.`,\n details: { arg: options.arg },\n });\n }\n\n return renderPlaceholder({ ...options, name: name as PlaceholderName });\n },\n );\n\n if (!foundTemplateToken || rendered.includes(\"{{\") || rendered.includes(\"}}\")) {\n throw templateError({\n code: options.errorCode,\n message: `${options.commandDescription} has malformed template syntax.`,\n details: { arg: options.arg },\n });\n }\n\n return rendered;\n}\n\nfunction findConditionalClose(options: {\n readonly argv: readonly string[];\n readonly openIndex: number;\n readonly condition: ConditionalName;\n readonly errorCode: string;\n readonly commandDescription: string;\n}): number {\n let depth = 1;\n\n for (let index = options.openIndex + 1; index < options.argv.length; index += 1) {\n const token = parseTemplateToken(options.argv[index] ?? \"\");\n if (token?.name !== options.condition) {\n continue;\n }\n\n if (token.kind === \"open\") {\n depth += 1;\n continue;\n }\n\n if (token.kind === \"close\") {\n depth -= 1;\n if (depth === 0) {\n return index;\n }\n }\n }\n\n throw templateError({\n code: options.errorCode,\n message: `${options.commandDescription} template is missing ${closingToken(options.condition)} for ${openingToken(options.condition)}.`,\n });\n}\n\nfunction renderPlaceholder(options: {\n readonly name: PlaceholderName;\n readonly values: PlaceholderValues;\n readonly errorCode: string;\n readonly commandDescription: string;\n}): string {\n const value = options.values[options.name];\n if (value !== undefined) {\n return value;\n }\n\n if (options.name === \"model\" || options.name === \"thinking\") {\n throw templateError({\n code: options.errorCode,\n message: `${options.commandDescription} placeholder ${placeholderToken(options.name)} must be guarded with ${openingToken(options.name)} ... ${closingToken(options.name)} when no ${options.name} override is set.`,\n details: { placeholder: placeholderToken(options.name) },\n });\n }\n\n throw templateError({\n code: options.errorCode,\n message: `${options.commandDescription} placeholder ${placeholderToken(options.name)} is not available in this command template.`,\n details: { placeholder: placeholderToken(options.name) },\n });\n}\n\nfunction templateError(options: {\n readonly code: string;\n readonly message: string;\n readonly details?: unknown;\n}): TrailStepFailureError {\n return new TrailStepFailureError({\n code: options.code,\n message: options.message,\n ...(options.details === undefined ? {} : { details: options.details }),\n });\n}\n\nfunction placeholderToken(name: PlaceholderName): string {\n return `{{${name}}}`;\n}\n\nfunction openingToken(name: ConditionalName): string {\n return `{{#${name}}}`;\n}\n\nfunction closingToken(name: ConditionalName): string {\n return `{{/${name}}}`;\n}\n\nfunction optionalNonEmptyString(value: string | undefined): string | undefined {\n if (value === undefined || value.trim().length === 0) {\n return undefined;\n }\n\n return value;\n}\n","import { TrailStepFailureError, validationFailure } from \"../../contracts/failures/failure.js\";\n\nexport function throwValidationFailure(diagnostics: readonly string[]): never {\n throw new TrailStepFailureError(\n validationFailure(\"Invalid .trailstep/config.json.\", { diagnostics }),\n );\n}\n\nexport function isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nexport function parseOptionalStringArray(\n path: string,\n value: unknown,\n diagnostics: string[],\n): readonly string[] | undefined {\n if (value === undefined) {\n return undefined;\n }\n\n if (!Array.isArray(value) || value.some((item) => typeof item !== \"string\")) {\n diagnostics.push(`${path} must be an array of strings when present.`);\n return undefined;\n }\n\n return value;\n}\n\nexport function parseOptionalStringRecord(\n path: string,\n value: unknown,\n diagnostics: string[],\n): Readonly<Record<string, string>> | undefined {\n if (value === undefined) {\n return undefined;\n }\n\n if (!isRecord(value)) {\n diagnostics.push(`${path} must be an object when present.`);\n return undefined;\n }\n\n const env: Record<string, string> = {};\n for (const [key, envValue] of Object.entries(value)) {\n if (typeof envValue !== \"string\") {\n diagnostics.push(`${path}.${key} must be a string.`);\n } else {\n env[key] = envValue;\n }\n }\n\n return env;\n}\n","import {\n isRecord,\n parseOptionalStringArray,\n parseOptionalStringRecord,\n throwValidationFailure,\n} from \"../agent-targeting/parse-trailstep-config/parse-utils.js\";\nimport type { WorkflowAgentThinking } from \"../contracts/agents/agent-role.types.js\";\n\nexport interface TrailStepProviderRegistration {\n readonly source: TrailStepProviderSource;\n readonly manifest: TrailStepProviderManifest;\n}\n\nexport type TrailStepProviderSource =\n | { readonly type: \"local-manifest\"; readonly path: string }\n | { readonly type: \"legacy-custom-provider\" }\n | {\n readonly type: \"npm\" | \"github\" | \"local-package\";\n readonly packageName: string;\n readonly spec: string;\n readonly resolvedVersion?: string;\n };\n\n/**\n * ESM package contract for provider packages: export `trailstepProvider` from\n * the package root. Keep hook functions outside `manifest` so the manifest is\n * serializable and safe to persist.\n */\nexport interface TrailStepProviderPackageDefinition {\n readonly manifest: TrailStepProviderManifest;\n readonly hooks?: Record<string, unknown>;\n}\n\nexport interface TrailStepProviderManifest {\n readonly schemaVersion: 1;\n readonly id: string;\n readonly displayName: string;\n readonly working: TrailStepProviderWorkingManifest;\n readonly interactive: TrailStepProviderInteractiveManifest;\n readonly model: TrailStepProviderModelManifest;\n readonly thinking: TrailStepProviderThinkingManifest;\n readonly env?: TrailStepProviderEnvironmentManifest;\n readonly hooks?: Record<string, unknown>;\n}\n\nexport type TrailStepProviderPromptFileReferenceStyle = \"at-prefixed-argument\";\n\nexport interface TrailStepProviderPromptManifest {\n readonly kind: \"prompt-file\";\n readonly reference?: TrailStepProviderPromptFileReferenceStyle;\n}\n\nexport type TrailStepProviderOutputStyle =\n | \"provider-output-file\"\n | \"stdout-json-envelope\"\n | \"stdout-jsonl-transcript\";\n\nexport interface TrailStepProviderOutputParsingManifest {\n readonly resultField?: string;\n}\n\nexport interface TrailStepProviderOutputManifest {\n readonly style: TrailStepProviderOutputStyle;\n readonly parsing?: TrailStepProviderOutputParsingManifest;\n}\n\nexport interface TrailStepProviderWorkingManifest {\n readonly supported: boolean;\n readonly command?: string;\n readonly args?: readonly string[];\n readonly prompt?: TrailStepProviderPromptManifest;\n readonly output?: TrailStepProviderOutputManifest;\n}\n\nexport interface TrailStepProviderInteractiveManifest {\n readonly supported: boolean;\n readonly reason?: string;\n readonly command?: string;\n readonly args?: readonly string[];\n readonly requiresSystemPromptFile?: boolean;\n readonly systemPromptFileFlag?: string;\n readonly modelFlag?: string;\n readonly permissionBypassFlag?: string;\n}\n\nexport interface TrailStepProviderEnvironmentManifest {\n readonly required?: readonly string[];\n readonly optional?: readonly string[];\n}\n\nexport interface TrailStepProviderModelDiscoveryManifest {\n readonly command: string;\n readonly args: readonly string[];\n readonly outputParser: string;\n}\n\nexport interface TrailStepProviderModelManifest {\n readonly supported: boolean;\n readonly reason?: string;\n readonly flag?: string;\n readonly discovery?: TrailStepProviderModelDiscoveryManifest;\n}\n\nexport interface TrailStepProviderThinkingManifest {\n readonly supported: boolean;\n readonly reason?: string;\n readonly flag?: string;\n readonly levels?: readonly WorkflowAgentThinking[];\n}\n\nconst THINKING_LEVELS = new Set<WorkflowAgentThinking>([\"low\", \"medium\", \"high\", \"xhigh\", \"max\"]);\n\nexport function parseTrailStepProviderManifest(\n path: string,\n value: unknown,\n diagnostics: string[],\n): TrailStepProviderManifest | undefined {\n return parseManifest(path, value, diagnostics);\n}\n\nexport function parseTrailStepProviderRegistrations(\n path: string,\n value: unknown,\n diagnostics: string[],\n): Record<string, TrailStepProviderRegistration> {\n const start = diagnostics.length;\n const providers: Record<string, TrailStepProviderRegistration> = {};\n\n if (value === undefined) {\n return providers;\n }\n\n if (!isRecord(value)) {\n diagnostics.push(`${path} must be an object when present.`);\n throwIfNewDiagnostics(diagnostics, start);\n return providers;\n }\n\n for (const [name, registration] of Object.entries(value)) {\n const parsed = parseProviderRegistration(`${path}.${name}`, registration, diagnostics);\n if (parsed !== undefined) {\n providers[name] = parsed;\n }\n }\n\n throwIfNewDiagnostics(diagnostics, start);\n return providers;\n}\n\nfunction parseProviderRegistration(\n path: string,\n value: unknown,\n diagnostics: string[],\n): TrailStepProviderRegistration | undefined {\n if (!isRecord(value)) {\n diagnostics.push(`${path} must be an object.`);\n return undefined;\n }\n\n const source = parseSource(`${path}.source`, value.source, diagnostics);\n const manifest =\n source?.type === \"legacy-custom-provider\"\n ? parseLegacyCustomProviderManifest(`${path}.manifest`, value.manifest, diagnostics)\n : parseManifest(`${path}.manifest`, value.manifest, diagnostics);\n\n if (source === undefined || manifest === undefined) {\n return undefined;\n }\n\n return { source, manifest };\n}\n\nfunction parseSource(\n path: string,\n value: unknown,\n diagnostics: string[],\n): TrailStepProviderRegistration[\"source\"] | undefined {\n if (!isRecord(value)) {\n diagnostics.push(`${path} must be an object.`);\n return undefined;\n }\n\n if (value.type === \"local-manifest\") {\n if (typeof value.path !== \"string\" || value.path.length === 0) {\n diagnostics.push(`${path}.path must be a non-empty string.`);\n return undefined;\n }\n return { type: \"local-manifest\", path: value.path };\n }\n\n if (value.type === \"legacy-custom-provider\") {\n return { type: \"legacy-custom-provider\" };\n }\n\n if (value.type === \"npm\" || value.type === \"github\" || value.type === \"local-package\") {\n if (typeof value.packageName !== \"string\" || value.packageName.length === 0) {\n diagnostics.push(`${path}.packageName must be a non-empty string.`);\n }\n if (typeof value.spec !== \"string\" || value.spec.length === 0) {\n diagnostics.push(`${path}.spec must be a non-empty string.`);\n }\n if (\n typeof value.packageName !== \"string\" ||\n value.packageName.length === 0 ||\n typeof value.spec !== \"string\" ||\n value.spec.length === 0\n ) {\n return undefined;\n }\n return {\n type: value.type,\n packageName: value.packageName,\n spec: value.spec,\n ...(typeof value.resolvedVersion === \"string\" && value.resolvedVersion.length > 0\n ? { resolvedVersion: value.resolvedVersion }\n : {}),\n };\n }\n\n diagnostics.push(\n `${path}.type must be local-manifest, legacy-custom-provider, npm, github, or local-package.`,\n );\n return undefined;\n}\n\nfunction parseLegacyCustomProviderManifest(\n path: string,\n value: unknown,\n diagnostics: string[],\n): TrailStepProviderManifest | undefined {\n if (!isRecord(value)) {\n diagnostics.push(`${path} must be an object.`);\n return undefined;\n }\n\n if (value.schemaVersion !== 1) {\n diagnostics.push(`${path}.schemaVersion must be 1.`);\n }\n const id = parseRequiredString(`${path}.id`, value.id, diagnostics);\n const displayName = parseRequiredString(`${path}.displayName`, value.displayName, diagnostics);\n const working = parseWorking(`${path}.working`, value.working, diagnostics);\n const interactive = parseLegacyInteractive(`${path}.interactive`, value.interactive, diagnostics);\n const model = parseLegacyModel(`${path}.model`, value.model, diagnostics);\n const thinking = parseLegacyThinking(`${path}.thinking`, value.thinking, diagnostics);\n const env = parseOptionalStringRecord(`${path}.env`, value.env, diagnostics);\n\n if (\n value.schemaVersion !== 1 ||\n id === undefined ||\n displayName === undefined ||\n working === undefined ||\n interactive === undefined ||\n model === undefined ||\n thinking === undefined\n ) {\n return undefined;\n }\n\n return {\n schemaVersion: 1,\n id,\n displayName,\n working,\n interactive,\n model,\n thinking,\n ...(typeof value.cwd === \"string\" ? { cwd: value.cwd } : {}),\n ...(env === undefined ? {} : { env }),\n } as TrailStepProviderManifest;\n}\n\nfunction parseManifest(\n path: string,\n value: unknown,\n diagnostics: string[],\n): TrailStepProviderManifest | undefined {\n if (!isRecord(value)) {\n diagnostics.push(`${path} must be an object.`);\n return undefined;\n }\n\n if (value.schemaVersion !== 1) {\n diagnostics.push(`${path}.schemaVersion must be 1.`);\n }\n const id = parseRequiredString(`${path}.id`, value.id, diagnostics);\n const displayName = parseRequiredString(`${path}.displayName`, value.displayName, diagnostics);\n const working = parseWorking(`${path}.working`, value.working, diagnostics);\n const interactive = parseInteractive(`${path}.interactive`, value.interactive, diagnostics);\n const model = parseModel(`${path}.model`, value.model, diagnostics);\n const thinking = parseThinking(`${path}.thinking`, value.thinking, diagnostics);\n const env = parseEnvironment(`${path}.env`, value.env, diagnostics);\n\n if (\n value.schemaVersion !== 1 ||\n id === undefined ||\n displayName === undefined ||\n working === undefined ||\n interactive === undefined ||\n model === undefined ||\n thinking === undefined ||\n env === null\n ) {\n return undefined;\n }\n\n return {\n schemaVersion: 1,\n id,\n displayName,\n working,\n interactive,\n model,\n thinking,\n ...(env === undefined ? {} : { env }),\n ...(isRecord(value.hooks) ? { hooks: value.hooks } : {}),\n };\n}\n\nfunction parseWorking(\n path: string,\n value: unknown,\n diagnostics: string[],\n): TrailStepProviderWorkingManifest | undefined {\n if (!isRecord(value) || typeof value.supported !== \"boolean\") {\n diagnostics.push(`${path} must be an object with a boolean supported field.`);\n return undefined;\n }\n\n if (!value.supported) {\n return { supported: false };\n }\n\n const command = parseRequiredString(`${path}.command`, value.command, diagnostics);\n const args = parseOptionalStringArray(`${path}.args`, value.args, diagnostics);\n const prompt = parsePrompt(`${path}.prompt`, value.prompt, diagnostics);\n const output = parseOutput(`${path}.output`, value.output, diagnostics);\n\n if (command === undefined || prompt === undefined || output === undefined) {\n return undefined;\n }\n\n return { supported: true, command, ...(args === undefined ? {} : { args }), prompt, output };\n}\n\nfunction parseLegacyInteractive(\n path: string,\n value: unknown,\n diagnostics: string[],\n): TrailStepProviderManifest[\"interactive\"] | undefined {\n const parsed = parseSupportedObject(path, value, diagnostics);\n if (parsed === undefined || !isRecord(value)) {\n return undefined;\n }\n const command = parseOptionalNonEmptyString(`${path}.command`, value.command, diagnostics);\n const args = parseOptionalStringArray(`${path}.args`, value.args, diagnostics);\n if (command === null) {\n return undefined;\n }\n return {\n ...parsed,\n ...(command === undefined ? {} : { command }),\n ...(args === undefined ? {} : { args }),\n } as TrailStepProviderManifest[\"interactive\"];\n}\n\nfunction parseInteractive(\n path: string,\n value: unknown,\n diagnostics: string[],\n): TrailStepProviderInteractiveManifest | undefined {\n const parsed = parseSupportedObject(path, value, diagnostics);\n if (parsed === undefined || !isRecord(value)) {\n return undefined;\n }\n const command = parseOptionalNonEmptyString(`${path}.command`, value.command, diagnostics);\n const args = parseOptionalStringArray(`${path}.args`, value.args, diagnostics);\n const systemPromptFileFlag = parseOptionalNonEmptyString(\n `${path}.systemPromptFileFlag`,\n value.systemPromptFileFlag,\n diagnostics,\n );\n const modelFlag = parseOptionalNonEmptyString(`${path}.modelFlag`, value.modelFlag, diagnostics);\n const permissionBypassFlag = parseOptionalNonEmptyString(\n `${path}.permissionBypassFlag`,\n value.permissionBypassFlag,\n diagnostics,\n );\n if (\n command === null ||\n systemPromptFileFlag === null ||\n modelFlag === null ||\n permissionBypassFlag === null\n ) {\n return undefined;\n }\n return {\n ...parsed,\n ...(command === undefined ? {} : { command }),\n ...(args === undefined ? {} : { args }),\n ...(typeof value.requiresSystemPromptFile === \"boolean\"\n ? { requiresSystemPromptFile: value.requiresSystemPromptFile }\n : {}),\n ...(systemPromptFileFlag === undefined ? {} : { systemPromptFileFlag }),\n ...(modelFlag === undefined ? {} : { modelFlag }),\n ...(permissionBypassFlag === undefined ? {} : { permissionBypassFlag }),\n };\n}\n\nfunction parseSupportedObject(\n path: string,\n value: unknown,\n diagnostics: string[],\n): { readonly supported: boolean; readonly reason?: string } | undefined {\n if (!isRecord(value) || typeof value.supported !== \"boolean\") {\n diagnostics.push(`${path} must be an object with a boolean supported field.`);\n return undefined;\n }\n return {\n supported: value.supported,\n ...(typeof value.reason === \"string\" ? { reason: value.reason } : {}),\n };\n}\n\nfunction parseEnvironment(\n path: string,\n value: unknown,\n diagnostics: string[],\n): TrailStepProviderEnvironmentManifest | undefined | null {\n if (value === undefined) {\n return undefined;\n }\n if (!isRecord(value)) {\n diagnostics.push(`${path} must be an object when present.`);\n return null;\n }\n const start = diagnostics.length;\n const required = parseOptionalStringArray(`${path}.required`, value.required, diagnostics);\n const optional = parseOptionalStringArray(`${path}.optional`, value.optional, diagnostics);\n if (diagnostics.length > start) {\n return null;\n }\n return {\n ...(required === undefined ? {} : { required }),\n ...(optional === undefined ? {} : { optional }),\n };\n}\n\nfunction parseLegacyModel(\n path: string,\n value: unknown,\n diagnostics: string[],\n): TrailStepProviderManifest[\"model\"] | undefined {\n const parsed = parseSupportedObject(path, value, diagnostics);\n if (parsed === undefined || !isRecord(value)) {\n return undefined;\n }\n const flag = parseOptionalNonEmptyString(`${path}.flag`, value.flag, diagnostics);\n if (flag === null) {\n return undefined;\n }\n return {\n ...parsed,\n ...(flag === undefined ? {} : { flag }),\n } as TrailStepProviderManifest[\"model\"];\n}\n\nfunction parseLegacyThinking(\n path: string,\n value: unknown,\n diagnostics: string[],\n): TrailStepProviderManifest[\"thinking\"] | undefined {\n if (!isRecord(value) || typeof value.supported !== \"boolean\") {\n diagnostics.push(`${path} must be an object with a boolean supported field.`);\n return undefined;\n }\n\n const flag = parseOptionalNonEmptyString(`${path}.flag`, value.flag, diagnostics);\n if (flag === null) {\n return undefined;\n }\n\n if (value.levels !== undefined) {\n if (\n !Array.isArray(value.levels) ||\n value.levels.some(\n (level) =>\n typeof level !== \"string\" || !THINKING_LEVELS.has(level as WorkflowAgentThinking),\n )\n ) {\n diagnostics.push(\n `${path}.levels must be an array of supported thinking levels when present.`,\n );\n return undefined;\n }\n return {\n supported: value.supported,\n ...(flag === undefined ? {} : { flag }),\n levels: value.levels as WorkflowAgentThinking[],\n } as TrailStepProviderManifest[\"thinking\"];\n }\n\n return {\n supported: value.supported,\n ...(flag === undefined ? {} : { flag }),\n } as TrailStepProviderManifest[\"thinking\"];\n}\n\nfunction parseModel(\n path: string,\n value: unknown,\n diagnostics: string[],\n): TrailStepProviderModelManifest | undefined {\n const parsed = parseSupportedObject(path, value, diagnostics);\n if (parsed === undefined || !isRecord(value)) {\n return undefined;\n }\n const flag = parseOptionalNonEmptyString(`${path}.flag`, value.flag, diagnostics);\n const discovery = parseModelDiscovery(`${path}.discovery`, value.discovery, diagnostics);\n if (flag === null || discovery === null) {\n return undefined;\n }\n return {\n ...parsed,\n ...(flag === undefined ? {} : { flag }),\n ...(discovery === undefined ? {} : { discovery }),\n };\n}\n\nfunction parseModelDiscovery(\n path: string,\n value: unknown,\n diagnostics: string[],\n): TrailStepProviderModelDiscoveryManifest | undefined | null {\n if (value === undefined) {\n return undefined;\n }\n if (!isRecord(value)) {\n diagnostics.push(`${path} must be an object when present.`);\n return null;\n }\n const command = parseRequiredString(`${path}.command`, value.command, diagnostics);\n const args = parseRequiredStringArray(`${path}.args`, value.args, diagnostics);\n const outputParser = parseRequiredString(`${path}.outputParser`, value.outputParser, diagnostics);\n if (command === undefined || args === undefined || outputParser === undefined) {\n return null;\n }\n return { command, args, outputParser };\n}\n\nfunction parseThinking(\n path: string,\n value: unknown,\n diagnostics: string[],\n): TrailStepProviderThinkingManifest | undefined {\n const parsed = parseSupportedObject(path, value, diagnostics);\n if (parsed === undefined || !isRecord(value)) {\n return undefined;\n }\n\n const flag = parseOptionalNonEmptyString(`${path}.flag`, value.flag, diagnostics);\n if (flag === null) {\n return undefined;\n }\n\n if (value.levels !== undefined) {\n if (\n !Array.isArray(value.levels) ||\n value.levels.some(\n (level) =>\n typeof level !== \"string\" || !THINKING_LEVELS.has(level as WorkflowAgentThinking),\n )\n ) {\n diagnostics.push(\n `${path}.levels must be an array of supported thinking levels when present.`,\n );\n return undefined;\n }\n return {\n ...parsed,\n ...(flag === undefined ? {} : { flag }),\n levels: value.levels as WorkflowAgentThinking[],\n };\n }\n\n return { ...parsed, ...(flag === undefined ? {} : { flag }) };\n}\n\nfunction parsePrompt(\n path: string,\n value: unknown,\n diagnostics: string[],\n): TrailStepProviderPromptManifest | undefined {\n if (!isRecord(value) || value.kind !== \"prompt-file\") {\n diagnostics.push(`${path}.kind must be prompt-file.`);\n return undefined;\n }\n if (value.reference !== undefined && value.reference !== \"at-prefixed-argument\") {\n diagnostics.push(`${path}.reference must be at-prefixed-argument when present.`);\n return undefined;\n }\n return {\n kind: \"prompt-file\",\n ...(value.reference === undefined ? {} : { reference: value.reference }),\n };\n}\n\nfunction parseOutput(\n path: string,\n value: unknown,\n diagnostics: string[],\n): TrailStepProviderOutputManifest | undefined {\n if (!isRecord(value) || !isProviderOutputStyle(value.style)) {\n diagnostics.push(\n `${path}.style must be provider-output-file, stdout-json-envelope, or stdout-jsonl-transcript.`,\n );\n return undefined;\n }\n const parsing = parseOutputParsing(`${path}.parsing`, value.parsing, diagnostics);\n if (parsing === null) {\n return undefined;\n }\n return {\n style: value.style,\n ...(parsing === undefined ? {} : { parsing }),\n };\n}\n\nfunction parseOutputParsing(\n path: string,\n value: unknown,\n diagnostics: string[],\n): TrailStepProviderOutputParsingManifest | undefined | null {\n if (value === undefined) {\n return undefined;\n }\n if (!isRecord(value)) {\n diagnostics.push(`${path} must be an object when present.`);\n return null;\n }\n const resultField = parseOptionalNonEmptyString(\n `${path}.resultField`,\n value.resultField,\n diagnostics,\n );\n if (resultField === null) {\n return null;\n }\n return {\n ...(resultField === undefined ? {} : { resultField }),\n };\n}\n\nfunction isProviderOutputStyle(value: unknown): value is TrailStepProviderOutputStyle {\n return (\n value === \"provider-output-file\" ||\n value === \"stdout-json-envelope\" ||\n value === \"stdout-jsonl-transcript\"\n );\n}\n\nfunction parseRequiredString(\n path: string,\n value: unknown,\n diagnostics: string[],\n): string | undefined {\n if (typeof value !== \"string\" || value.length === 0) {\n diagnostics.push(`${path} must be a non-empty string.`);\n return undefined;\n }\n return value;\n}\n\nfunction parseRequiredStringArray(\n path: string,\n value: unknown,\n diagnostics: string[],\n): readonly string[] | undefined {\n if (!Array.isArray(value) || value.some((item) => typeof item !== \"string\")) {\n diagnostics.push(`${path} must be an array of strings.`);\n return undefined;\n }\n return value;\n}\n\nfunction parseOptionalNonEmptyString(\n path: string,\n value: unknown,\n diagnostics: string[],\n): string | undefined | null {\n if (value === undefined) {\n return undefined;\n }\n if (typeof value !== \"string\" || value.length === 0) {\n diagnostics.push(`${path} must be a non-empty string when present.`);\n return null;\n }\n return value;\n}\n\nfunction throwIfNewDiagnostics(diagnostics: string[], start: number): void {\n if (diagnostics.length > start) {\n throwValidationFailure(diagnostics);\n }\n}\n","import { TrailStepFailureError } from \"../../contracts/failures/failure.js\";\nimport type {\n TrailStepAgentMappings,\n TrailStepAgentTarget,\n TrailStepSettings,\n} from \"../targeting.types.js\";\nimport type { RawTrailStepAgentMappings, RawTrailStepAgentTarget } from \"./parse-agent-targets.js\";\n\nexport function expandAgentRefs(options: {\n readonly agents: RawTrailStepAgentMappings;\n readonly workflows:\n | Readonly<\n Record<\n string,\n {\n readonly agents?: RawTrailStepAgentMappings;\n readonly settings?: TrailStepSettings;\n }\n >\n >\n | undefined;\n}): {\n readonly agents: TrailStepAgentMappings;\n readonly workflows:\n | Readonly<\n Record<\n string,\n {\n readonly agents?: TrailStepAgentMappings;\n readonly settings?: TrailStepSettings;\n }\n >\n >\n | undefined;\n} {\n const expandedAgents: Record<string, readonly TrailStepAgentTarget[]> = {};\n const memo = new Map<string, readonly TrailStepAgentTarget[]>();\n\n for (const name of Object.keys(options.agents)) {\n expandedAgents[name] = expandTopLevelAgent({\n name,\n agents: options.agents,\n memo,\n stack: [],\n rootRefPath: undefined,\n });\n }\n\n const expandedWorkflows =\n options.workflows === undefined\n ? undefined\n : Object.fromEntries(\n Object.entries(options.workflows).map(([workflowId, workflow]) => {\n const workflowAgents =\n workflow.agents === undefined\n ? undefined\n : Object.fromEntries(\n Object.entries(workflow.agents).map(([roleName, targets]) => [\n roleName,\n expandTargetArray({\n path: `workflows.${workflowId}.agents.${roleName}`,\n targets,\n agents: options.agents,\n memo,\n stack: [],\n rootRefPath: undefined,\n }),\n ]),\n );\n\n return [\n workflowId,\n {\n ...(workflowAgents === undefined ? {} : { agents: workflowAgents }),\n ...(workflow.settings === undefined ? {} : { settings: workflow.settings }),\n },\n ];\n }),\n );\n\n return { agents: expandedAgents, workflows: expandedWorkflows };\n}\n\nfunction expandTopLevelAgent(options: {\n readonly name: string;\n readonly agents: RawTrailStepAgentMappings;\n readonly memo: Map<string, readonly TrailStepAgentTarget[]>;\n readonly stack: readonly string[];\n readonly rootRefPath: string | undefined;\n}): readonly TrailStepAgentTarget[] {\n const memoized = options.memo.get(options.name);\n if (memoized !== undefined) {\n return memoized;\n }\n\n const targets = options.agents[options.name];\n if (targets === undefined) {\n throwUnknownRef(`agents.${options.name}`, options.name);\n }\n\n const expanded = expandTargetArray({\n path: `agents.${options.name}`,\n targets,\n agents: options.agents,\n memo: options.memo,\n stack: [...options.stack, options.name],\n rootRefPath: options.rootRefPath,\n });\n options.memo.set(options.name, expanded);\n return expanded;\n}\n\nfunction expandTargetArray(options: {\n readonly path: string;\n readonly targets: readonly RawTrailStepAgentTarget[];\n readonly agents: RawTrailStepAgentMappings;\n readonly memo: Map<string, readonly TrailStepAgentTarget[]>;\n readonly stack: readonly string[];\n readonly rootRefPath: string | undefined;\n}): readonly TrailStepAgentTarget[] {\n return options.targets.flatMap((target, index) => {\n if (\"provider\" in target) {\n return [target];\n }\n\n const refPath = `${options.path}[${index}].ref`;\n const referencedTargets = options.agents[target.ref];\n if (referencedTargets === undefined) {\n throwUnknownRef(refPath, target.ref);\n }\n\n const existingRefIndex = options.stack.indexOf(target.ref);\n if (existingRefIndex !== -1) {\n throwCycle(options.rootRefPath ?? refPath, [\n ...options.stack.slice(existingRefIndex),\n target.ref,\n ]);\n }\n\n const memoized = options.memo.get(target.ref);\n if (memoized !== undefined) {\n return memoized;\n }\n\n const expanded = expandTargetArray({\n path: `agents.${target.ref}`,\n targets: referencedTargets,\n agents: options.agents,\n memo: options.memo,\n stack: [...options.stack, target.ref],\n rootRefPath: options.rootRefPath ?? refPath,\n });\n options.memo.set(target.ref, expanded);\n return expanded;\n });\n}\n\nfunction throwUnknownRef(path: string, ref: string): never {\n throw new TrailStepFailureError({\n code: \"agent_ref_unknown\",\n message: \"One or more agent refs reference an unknown top-level agent.\",\n details: { diagnostics: [`${path} references unknown agent '${ref}'.`] },\n });\n}\n\nfunction throwCycle(path: string, cycle: readonly string[]): never {\n throw new TrailStepFailureError({\n code: \"agent_ref_cycle\",\n message: \"One or more agent refs create a cycle.\",\n details: { diagnostics: [`${path} creates an agent ref cycle: ${cycle.join(\" -> \")}.`] },\n });\n}\n","import type {\n WorkflowAgentSize,\n WorkflowAgentThinking,\n} from \"../../contracts/agents/agent-role.types.js\";\nimport type { TrailStepAgentTarget } from \"../targeting.types.js\";\nimport { isRecord, parseOptionalStringArray } from \"./parse-utils.js\";\n\nexport interface RawTrailStepAgentRef {\n readonly ref: string;\n}\n\nexport type RawTrailStepAgentTarget = TrailStepAgentTarget | RawTrailStepAgentRef;\nexport type RawTrailStepAgentMappings = Readonly<\n Record<string, readonly RawTrailStepAgentTarget[]>\n>;\n\nexport const AGENT_SIZES = new Set<WorkflowAgentSize>([\n \"default\",\n \"tiny\",\n \"small\",\n \"medium\",\n \"large\",\n \"xl\",\n]);\n\nconst THINKING_LEVELS = new Set<WorkflowAgentThinking>([\"low\", \"medium\", \"high\", \"xhigh\", \"max\"]);\n\nexport function parseTargetArray(\n path: string,\n value: unknown,\n diagnostics: string[],\n): readonly RawTrailStepAgentTarget[] {\n if (!Array.isArray(value)) {\n diagnostics.push(`${path} must be an array.`);\n return [];\n }\n\n return value.flatMap((target, index): readonly RawTrailStepAgentTarget[] => {\n const targetPath = `${path}[${index}]`;\n\n if (!isRecord(target)) {\n diagnostics.push(`${targetPath} must be an object.`);\n return [];\n }\n\n if (target.ref !== undefined) {\n if (typeof target.ref !== \"string\" || target.ref.length === 0) {\n diagnostics.push(`${targetPath}.ref must be a non-empty string when present.`);\n return [];\n }\n\n return [{ ref: target.ref }];\n }\n\n if (typeof target.provider !== \"string\" || target.provider.length === 0) {\n diagnostics.push(`${targetPath}.provider must be a non-empty string.`);\n return [];\n }\n\n if (target.model !== undefined && typeof target.model !== \"string\") {\n diagnostics.push(`${targetPath}.model must be a string when present.`);\n }\n\n if (\n target.thinking !== undefined &&\n !THINKING_LEVELS.has(target.thinking as WorkflowAgentThinking)\n ) {\n diagnostics.push(\n `${targetPath}.thinking must be one of low, medium, high, xhigh, or max when present.`,\n );\n }\n\n const model =\n typeof target.model === \"string\" ? optionalNonEmptyString(target.model) : undefined;\n const args = parseOptionalStringArray(`${targetPath}.args`, target.args, diagnostics);\n\n return [\n {\n provider: target.provider,\n ...(model === undefined ? {} : { model }),\n ...(typeof target.thinking === \"string\" &&\n THINKING_LEVELS.has(target.thinking as WorkflowAgentThinking)\n ? { thinking: target.thinking as WorkflowAgentThinking }\n : {}),\n ...(args === undefined ? {} : { args }),\n },\n ];\n });\n}\n\nfunction optionalNonEmptyString(value: string): string | undefined {\n return value.trim().length === 0 ? undefined : value;\n}\n","import {\n parseTargetArray,\n type RawTrailStepAgentMappings,\n type RawTrailStepAgentTarget,\n} from \"./parse-agent-targets.js\";\nimport { isRecord } from \"./parse-utils.js\";\n\nexport function parseAgentMappings(\n path: string,\n value: unknown,\n diagnostics: string[],\n): RawTrailStepAgentMappings {\n const mappings: Record<string, readonly RawTrailStepAgentTarget[]> = {};\n\n if (!isRecord(value)) {\n diagnostics.push(`${path} must be an object.`);\n return mappings;\n }\n\n for (const [name, entry] of Object.entries(value)) {\n mappings[name] = parseTargetArray(`${path}.${name}`, entry, diagnostics);\n }\n\n return mappings;\n}\n","import type { WorkflowAgentThinking } from \"../../contracts/agents/agent-role.types.js\";\nimport type {\n TrailStepCustomProviderConfig,\n TrailStepCustomProviderModelOverrideSupport,\n TrailStepCustomProviderThinkingOverrideSupport,\n} from \"../targeting.types.js\";\nimport { isRecord, parseOptionalStringArray, parseOptionalStringRecord } from \"./parse-utils.js\";\n\nconst THINKING_LEVELS = new Set<WorkflowAgentThinking>([\"low\", \"medium\", \"high\", \"xhigh\", \"max\"]);\n\nexport function parseCustomProviders(\n value: unknown,\n diagnostics: string[],\n): Record<string, TrailStepCustomProviderConfig> {\n const customProviders: Record<string, TrailStepCustomProviderConfig> = {};\n\n if (value === undefined) {\n return customProviders;\n }\n\n if (!isRecord(value)) {\n diagnostics.push(\"customProviders must be an object.\");\n return customProviders;\n }\n\n for (const [name, providerConfig] of Object.entries(value)) {\n if (!isRecord(providerConfig)) {\n diagnostics.push(`customProviders.${name} must be an object.`);\n continue;\n }\n\n if (typeof providerConfig.binary !== \"string\" || providerConfig.binary.length === 0) {\n diagnostics.push(`customProviders.${name}.binary must be a non-empty string.`);\n continue;\n }\n\n const args = parseOptionalStringArray(\n `customProviders.${name}.args`,\n providerConfig.args,\n diagnostics,\n );\n const interactiveArgs = parseOptionalStringArray(\n `customProviders.${name}.interactiveArgs`,\n providerConfig.interactiveArgs,\n diagnostics,\n );\n const model = parseCustomProviderModelSupport(\n `customProviders.${name}.model`,\n providerConfig.model,\n diagnostics,\n );\n const thinking = parseCustomProviderThinkingSupport(\n `customProviders.${name}.thinking`,\n providerConfig.thinking,\n diagnostics,\n );\n const env = parseOptionalStringRecord(\n `customProviders.${name}.env`,\n providerConfig.env,\n diagnostics,\n );\n\n if (providerConfig.cwd !== undefined && typeof providerConfig.cwd !== \"string\") {\n diagnostics.push(`customProviders.${name}.cwd must be a string when present.`);\n }\n\n customProviders[name] = {\n binary: providerConfig.binary,\n ...(args === undefined ? {} : { args }),\n ...(interactiveArgs === undefined ? {} : { interactiveArgs }),\n ...(model === undefined ? {} : { model }),\n ...(thinking === undefined ? {} : { thinking }),\n ...(typeof providerConfig.cwd === \"string\" ? { cwd: providerConfig.cwd } : {}),\n ...(env === undefined ? {} : { env }),\n };\n }\n\n return customProviders;\n}\n\nfunction parseCustomProviderModelSupport(\n path: string,\n value: unknown,\n diagnostics: string[],\n): TrailStepCustomProviderModelOverrideSupport | undefined {\n if (value === undefined) {\n return undefined;\n }\n\n if (!isRecord(value) || typeof value.supported !== \"boolean\") {\n diagnostics.push(`${path} must be an object with a boolean supported field when present.`);\n return undefined;\n }\n\n if (!value.supported) {\n return { supported: false };\n }\n\n if (value.flag !== undefined && (typeof value.flag !== \"string\" || value.flag.length === 0)) {\n diagnostics.push(`${path}.flag must be a non-empty string when present.`);\n return undefined;\n }\n\n return {\n supported: true,\n ...(typeof value.flag === \"string\" ? { flag: value.flag } : {}),\n };\n}\n\nfunction parseCustomProviderThinkingSupport(\n path: string,\n value: unknown,\n diagnostics: string[],\n): TrailStepCustomProviderThinkingOverrideSupport | undefined {\n if (value === undefined) {\n return undefined;\n }\n\n if (!isRecord(value) || typeof value.supported !== \"boolean\") {\n diagnostics.push(`${path} must be an object with a boolean supported field when present.`);\n return undefined;\n }\n\n if (!value.supported) {\n if (value.levels !== undefined && (!Array.isArray(value.levels) || value.levels.length > 0)) {\n diagnostics.push(`${path}.levels must be an empty array when thinking support is disabled.`);\n return undefined;\n }\n\n return value.levels === undefined ? { supported: false } : { supported: false, levels: [] };\n }\n\n if (value.flag !== undefined && (typeof value.flag !== \"string\" || value.flag.length === 0)) {\n diagnostics.push(`${path}.flag must be a non-empty string when present.`);\n return undefined;\n }\n\n if (!Array.isArray(value.levels) || value.levels.length === 0) {\n diagnostics.push(`${path}.levels must be a non-empty array of supported thinking levels.`);\n return undefined;\n }\n\n const levels: WorkflowAgentThinking[] = [];\n for (const [index, level] of value.levels.entries()) {\n if (typeof level !== \"string\" || !THINKING_LEVELS.has(level as WorkflowAgentThinking)) {\n diagnostics.push(`${path}.levels[${index}] must be one of low, medium, high, xhigh, or max.`);\n continue;\n }\n levels.push(level as WorkflowAgentThinking);\n }\n\n if (levels.length !== value.levels.length) {\n return undefined;\n }\n\n return {\n supported: true,\n ...(typeof value.flag === \"string\" ? { flag: value.flag } : {}),\n levels,\n };\n}\n","import type { RetryPolicyInput } from \"../../runtime/retry/retry-policy.js\";\nimport type { TrailStepSettings } from \"../targeting.types.js\";\nimport { isRecord } from \"./parse-utils.js\";\n\nexport function parseSettings(\n path: string,\n value: unknown,\n diagnostics: string[],\n): TrailStepSettings | undefined {\n if (value === undefined) {\n return undefined;\n }\n\n if (!isRecord(value)) {\n diagnostics.push(`${path} must be an object when present.`);\n return undefined;\n }\n\n const settings: Record<string, unknown> = { ...value };\n\n if (value.retry !== undefined) {\n if (!isRecord(value.retry)) {\n diagnostics.push(`${path}.retry must be an object when present.`);\n delete settings.retry;\n } else if (value.retry.maxAttempts === undefined) {\n delete settings.retry;\n } else {\n settings.retry = { maxAttempts: value.retry.maxAttempts } satisfies RetryPolicyInput;\n }\n }\n\n if (value.timeout !== undefined && typeof value.timeout !== \"number\") {\n diagnostics.push(`${path}.timeout must be a number when present.`);\n delete settings.timeout;\n }\n\n return settings;\n}\n","import { createReadStream, type Dirent } from \"node:fs\";\nimport { mkdir, readdir, readFile, rm, stat, writeFile } from \"node:fs/promises\";\nimport { basename, dirname, join, relative } from \"node:path\";\nimport { promisify } from \"node:util\";\nimport { gunzip, gzip } from \"node:zlib\";\nimport { defaultRunsRoot } from \"../artifacts/run-storage.js\";\nimport { listRunSummaries, type RunSummary } from \"../runs/run-summaries.js\";\n\nconst gzipAsync = promisify(gzip);\nconst gunzipAsync = promisify(gunzip);\n\nexport interface StorageLifecyclePolicy {\n readonly enabled?: boolean;\n readonly archiveAfterDays?: number | false;\n readonly deleteAfterDays?: number | false;\n readonly workflows?: Readonly<\n Record<\n string,\n { readonly archiveAfterDays?: number | false; readonly deleteAfterDays?: number | false }\n >\n >;\n}\n\nexport interface StorageLifecycleAction {\n readonly action: \"archive\" | \"delete-hot\" | \"delete-archive\";\n readonly runId: string;\n readonly reason: string;\n readonly path: string;\n}\n\nexport interface StorageLifecycleStatus {\n readonly runsRoot: string;\n readonly enabled: boolean;\n readonly hotRuns: number;\n readonly archivedRuns: number;\n readonly pinnedRuns: readonly string[];\n}\n\ninterface ArchiveManifest {\n readonly schemaVersion: 1;\n readonly runId: string;\n readonly archivedAt: string;\n readonly sourceRunDir: string;\n readonly workflowId?: string;\n readonly lastTimestamp?: string;\n readonly status?: string;\n readonly pinned?: boolean;\n}\n\ninterface ArchivePayload {\n readonly manifest: ArchiveManifest;\n readonly files: readonly { readonly path: string; readonly contentBase64: string }[];\n}\n\nconst TERMINAL_STATUSES = new Set([\"completed\", \"failed\", \"cancelled\"]);\n\nexport function storageArchiveDir(runsRoot: string): string {\n return join(runsRoot, \".archive\");\n}\n\nexport function storagePinPath(runDir: string): string {\n return join(runDir, \".trailstep-pin.json\");\n}\n\nexport async function readStorageLifecycleStatus(options: {\n readonly cwd: string;\n readonly runsRoot?: string;\n readonly policy?: StorageLifecyclePolicy;\n}): Promise<StorageLifecycleStatus> {\n const runsRoot = options.runsRoot ?? defaultRunsRoot(options.cwd);\n const [runSummaries, archivedRuns, pinnedRuns] = await Promise.all([\n listRunSummaries({ cwd: options.cwd, runsRoot }),\n listArchivedRunIds(runsRoot),\n listPinnedRunIds({ cwd: options.cwd, runsRoot }),\n ]);\n const hotRuns = runSummaries.filter((summary) => summary.status !== \"archived\");\n return {\n runsRoot,\n enabled: options.policy?.enabled === true,\n hotRuns: hotRuns.length,\n archivedRuns: archivedRuns.length,\n pinnedRuns,\n };\n}\n\nexport async function planStorageLifecycle(options: {\n readonly cwd: string;\n readonly runsRoot?: string;\n readonly policy?: StorageLifecyclePolicy;\n readonly now?: Date;\n}): Promise<StorageLifecycleAction[]> {\n const policy = options.policy;\n if (policy?.enabled !== true) {\n return [];\n }\n\n const runsRoot = options.runsRoot ?? defaultRunsRoot(options.cwd);\n const now = options.now ?? new Date();\n const summaries = await listRunSummaries({ cwd: options.cwd, runsRoot });\n const actions: StorageLifecycleAction[] = [];\n\n for (const summary of summaries) {\n if (!isLifecycleEligible(summary) || (await isRunPinned(summary.runDir))) {\n continue;\n }\n\n const workflowPolicy = summary.workflowId ? policy.workflows?.[summary.workflowId] : undefined;\n const archiveAfterDays = resolvePolicyDays(workflowPolicy, policy, \"archiveAfterDays\");\n const deleteAfterDays = resolvePolicyDays(workflowPolicy, policy, \"deleteAfterDays\");\n const ageDays = ageInDays(summary.lastTimestamp, now);\n if (ageDays === undefined) {\n continue;\n }\n\n if (deleteAfterDays !== undefined && ageDays >= deleteAfterDays) {\n actions.push({\n action: \"delete-hot\",\n runId: summary.runId,\n path: summary.runDir,\n reason: `${summary.status} run is ${Math.floor(ageDays)}d old (deleteAfterDays=${deleteAfterDays})`,\n });\n } else if (archiveAfterDays !== undefined && ageDays >= archiveAfterDays) {\n actions.push({\n action: \"archive\",\n runId: summary.runId,\n path: summary.runDir,\n reason: `${summary.status} run is ${Math.floor(ageDays)}d old (archiveAfterDays=${archiveAfterDays})`,\n });\n }\n }\n\n for (const manifest of await readArchiveManifests(runsRoot)) {\n const workflowPolicy = manifest.workflowId\n ? policy.workflows?.[manifest.workflowId]\n : undefined;\n const deleteAfterDays = resolvePolicyDays(workflowPolicy, policy, \"deleteAfterDays\");\n const ageDays = ageInDays(manifest.lastTimestamp, now);\n if (manifest.pinned === true || deleteAfterDays === undefined || ageDays === undefined) {\n continue;\n }\n if (ageDays >= deleteAfterDays) {\n actions.push({\n action: \"delete-archive\",\n runId: manifest.runId,\n path: archivePayloadPath(runsRoot, manifest.runId),\n reason: `archived run is ${Math.floor(ageDays)}d old (deleteAfterDays=${deleteAfterDays})`,\n });\n }\n }\n\n return actions;\n}\n\nexport async function applyStorageLifecycle(options: {\n readonly cwd: string;\n readonly runsRoot?: string;\n readonly policy?: StorageLifecyclePolicy;\n readonly now?: Date;\n readonly dryRun?: boolean;\n}): Promise<StorageLifecycleAction[]> {\n const actions = await planStorageLifecycle(options);\n if (options.dryRun === true) {\n return actions;\n }\n const runsRoot = options.runsRoot ?? defaultRunsRoot(options.cwd);\n for (const action of actions) {\n if (action.action === \"archive\") {\n await archiveRun({ runsRoot, runId: action.runId, now: options.now });\n } else if (action.action === \"delete-hot\") {\n await deleteRun({ runsRoot, runId: action.runId });\n } else {\n await deleteArchivedRun({ runsRoot, runId: action.runId });\n }\n }\n return actions;\n}\n\nexport async function archiveRun(options: {\n readonly runsRoot: string;\n readonly runId: string;\n readonly now?: Date;\n}): Promise<void> {\n assertRunId(options.runId);\n const runDir = join(options.runsRoot, options.runId);\n const summaries = await listRunSummaries({\n cwd: dirname(dirname(options.runsRoot)),\n runsRoot: options.runsRoot,\n });\n const summary = summaries.find(\n (candidate) => candidate.runId === options.runId && candidate.status !== \"archived\",\n );\n if (summary === undefined || !isLifecycleEligible(summary)) {\n throw new Error(`Run ${options.runId} is not a terminal readable run and cannot be archived.`);\n }\n if (await isRunPinned(runDir)) {\n throw new Error(`Run ${options.runId} is pinned and cannot be archived.`);\n }\n\n const manifest: ArchiveManifest = {\n schemaVersion: 1,\n runId: options.runId,\n archivedAt: (options.now ?? new Date()).toISOString(),\n sourceRunDir: runDir,\n ...(summary.workflowId === undefined ? {} : { workflowId: summary.workflowId }),\n ...(summary.lastTimestamp === undefined ? {} : { lastTimestamp: summary.lastTimestamp }),\n status: summary.status,\n };\n const payload: ArchivePayload = { manifest, files: await readDirectoryPayload(runDir) };\n await mkdir(storageArchiveDir(options.runsRoot), { recursive: true });\n await writeFile(\n archivePayloadPath(options.runsRoot, options.runId),\n await gzipAsync(JSON.stringify(payload)),\n \"utf8\",\n );\n await writeFile(\n archiveManifestPath(options.runsRoot, options.runId),\n `${JSON.stringify(manifest, null, 2)}\\n`,\n \"utf8\",\n );\n await rm(runDir, { recursive: true, force: true });\n}\n\nexport async function restoreArchivedRun(options: {\n readonly runsRoot: string;\n readonly runId: string;\n}): Promise<void> {\n assertRunId(options.runId);\n const payloadPath = archivePayloadPath(options.runsRoot, options.runId);\n const manifestPath = archiveManifestPath(options.runsRoot, options.runId);\n const runDir = join(options.runsRoot, options.runId);\n if (await pathExists(runDir)) {\n throw new Error(\n `Run ${options.runId} already exists in hot storage; refusing to overwrite it.`,\n );\n }\n const payload = JSON.parse(\n String(await gunzipAsync(await readFile(payloadPath))),\n ) as ArchivePayload;\n await mkdir(runDir, { recursive: true });\n for (const file of payload.files) {\n const target = join(runDir, file.path);\n if (!relative(runDir, target) || relative(runDir, target).startsWith(\"..\")) {\n throw new Error(`Archive for ${options.runId} contains an invalid path.`);\n }\n await mkdir(dirname(target), { recursive: true });\n await writeFile(target, Buffer.from(file.contentBase64, \"base64\"));\n }\n await rm(payloadPath, { force: true });\n await rm(manifestPath, { force: true });\n}\n\nexport async function pinRun(options: {\n readonly runsRoot: string;\n readonly runId: string;\n}): Promise<void> {\n assertRunId(options.runId);\n const runDir = join(options.runsRoot, options.runId);\n if (!(await pathExists(runDir))) {\n if (await pathExists(archiveManifestPath(options.runsRoot, options.runId))) {\n throw new Error(`Run ${options.runId} is archived; restore it before pinning.`);\n }\n throw new Error(`Run ${options.runId} does not exist.`);\n }\n await writeFile(\n storagePinPath(runDir),\n `${JSON.stringify({ schemaVersion: 1, pinnedAt: new Date().toISOString() }, null, 2)}\\n`,\n \"utf8\",\n );\n}\n\nexport async function unpinRun(options: {\n readonly runsRoot: string;\n readonly runId: string;\n}): Promise<void> {\n assertRunId(options.runId);\n const runDir = join(options.runsRoot, options.runId);\n if (!(await pathExists(runDir))) {\n if (await pathExists(archiveManifestPath(options.runsRoot, options.runId))) {\n throw new Error(`Run ${options.runId} is archived; restore it before unpinning.`);\n }\n throw new Error(`Run ${options.runId} does not exist.`);\n }\n await rm(storagePinPath(runDir), { force: true });\n}\n\nexport async function deleteRun(options: {\n readonly runsRoot: string;\n readonly runId: string;\n}): Promise<void> {\n assertRunId(options.runId);\n const runDir = join(options.runsRoot, options.runId);\n if (await pathExists(runDir)) {\n if (await isRunPinned(runDir)) {\n throw new Error(`Run ${options.runId} is pinned and cannot be deleted.`);\n }\n await rm(runDir, { recursive: true, force: true });\n return;\n }\n const manifest = await readArchiveManifest(options.runsRoot, options.runId);\n if (manifest === undefined) {\n throw new Error(`Run ${options.runId} does not exist.`);\n }\n if (manifest.pinned === true) {\n throw new Error(`Run ${options.runId} is pinned and cannot be deleted.`);\n }\n await deleteArchivedRun(options);\n}\n\nexport async function deleteArchivedRun(options: {\n readonly runsRoot: string;\n readonly runId: string;\n}): Promise<void> {\n assertRunId(options.runId);\n await rm(archivePayloadPath(options.runsRoot, options.runId), { force: true });\n await rm(archiveManifestPath(options.runsRoot, options.runId), { force: true });\n}\n\nasync function readDirectoryPayload(root: string): Promise<ArchivePayload[\"files\"]> {\n const files: { path: string; contentBase64: string }[] = [];\n async function visit(dir: string): Promise<void> {\n for (const entry of await readdir(dir, { withFileTypes: true })) {\n const entryPath = join(dir, entry.name);\n if (entry.isDirectory()) {\n await visit(entryPath);\n } else if (entry.isFile()) {\n files.push({\n path: normalizeArchivePath(relative(root, entryPath)),\n contentBase64: await streamFileBase64(entryPath),\n });\n }\n }\n }\n await visit(root);\n return files;\n}\n\nfunction normalizeArchivePath(path: string): string {\n return path.replace(/\\\\/g, \"/\");\n}\n\nasync function streamFileBase64(path: string): Promise<string> {\n const chunks: Buffer[] = [];\n for await (const chunk of createReadStream(path)) {\n chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));\n }\n return Buffer.concat(chunks).toString(\"base64\");\n}\n\nasync function listPinnedRunIds(options: {\n readonly cwd: string;\n readonly runsRoot: string;\n}): Promise<string[]> {\n const summaries = (await listRunSummaries(options)).filter(\n (summary) => summary.status !== \"archived\",\n );\n const pinned: string[] = [];\n for (const summary of summaries) {\n if (await isRunPinned(summary.runDir)) {\n pinned.push(summary.runId);\n }\n }\n return pinned.sort();\n}\n\nasync function isRunPinned(runDir: string): Promise<boolean> {\n try {\n await stat(storagePinPath(runDir));\n return true;\n } catch (error) {\n if (isNodeError(error) && error.code === \"ENOENT\") {\n return false;\n }\n throw error;\n }\n}\n\nasync function listArchivedRunIds(runsRoot: string): Promise<string[]> {\n return (await readArchiveManifests(runsRoot)).map((manifest) => manifest.runId).sort();\n}\n\nasync function readArchiveManifest(\n runsRoot: string,\n runId: string,\n): Promise<ArchiveManifest | undefined> {\n try {\n return JSON.parse(\n await readFile(archiveManifestPath(runsRoot, runId), \"utf8\"),\n ) as ArchiveManifest;\n } catch (error) {\n if (isNodeError(error) && error.code === \"ENOENT\") {\n return undefined;\n }\n throw error;\n }\n}\n\nasync function readArchiveManifests(runsRoot: string): Promise<ArchiveManifest[]> {\n let entries: Dirent[];\n try {\n entries = await readdir(storageArchiveDir(runsRoot), { withFileTypes: true });\n } catch (error) {\n if (isNodeError(error) && error.code === \"ENOENT\") {\n return [];\n }\n throw error;\n }\n const manifests: ArchiveManifest[] = [];\n for (const entry of entries) {\n if (!entry.isFile() || !entry.name.endsWith(\".manifest.json\")) {\n continue;\n }\n manifests.push(\n JSON.parse(\n await readFile(join(storageArchiveDir(runsRoot), entry.name), \"utf8\"),\n ) as ArchiveManifest,\n );\n }\n return manifests;\n}\n\nfunction archivePayloadPath(runsRoot: string, runId: string): string {\n return join(storageArchiveDir(runsRoot), `${runId}.json.gz`);\n}\n\nfunction archiveManifestPath(runsRoot: string, runId: string): string {\n return join(storageArchiveDir(runsRoot), `${runId}.manifest.json`);\n}\n\nfunction isLifecycleEligible(summary: RunSummary): boolean {\n return TERMINAL_STATUSES.has(summary.status);\n}\n\nfunction resolvePolicyDays(\n workflowPolicy: NonNullable<StorageLifecyclePolicy[\"workflows\"]>[string] | undefined,\n defaultPolicy: StorageLifecyclePolicy,\n key: \"archiveAfterDays\" | \"deleteAfterDays\",\n): number | undefined {\n if (workflowPolicy !== undefined && Object.hasOwn(workflowPolicy, key)) {\n const value = workflowPolicy[key];\n return value === false ? undefined : value;\n }\n const value = defaultPolicy[key];\n return value === false ? undefined : value;\n}\n\nfunction ageInDays(timestamp: string | undefined, now: Date): number | undefined {\n if (timestamp === undefined) {\n return undefined;\n }\n const time = Date.parse(timestamp);\n return Number.isFinite(time) ? (now.getTime() - time) / (24 * 60 * 60 * 1000) : undefined;\n}\n\nexport function parseStorageLifecycleDurationDays(value: string): number | undefined {\n const match = /^(\\d+(?:\\.\\d+)?)(ms|s|m|h|d|w)$/u.exec(value.trim());\n if (match === null) {\n return undefined;\n }\n const amount = Number(match[1]);\n if (!Number.isFinite(amount) || amount < 0) {\n return undefined;\n }\n const unit = match[2] as \"ms\" | \"s\" | \"m\" | \"h\" | \"d\" | \"w\";\n const daysByUnit: Record<typeof unit, number> = {\n ms: 1 / 86_400_000,\n s: 1 / 86_400,\n m: 1 / 1_440,\n h: 1 / 24,\n d: 1,\n w: 7,\n };\n return amount * daysByUnit[unit];\n}\n\nasync function pathExists(path: string): Promise<boolean> {\n try {\n await stat(path);\n return true;\n } catch (error) {\n if (isNodeError(error) && error.code === \"ENOENT\") {\n return false;\n }\n throw error;\n }\n}\n\nfunction assertRunId(runId: string): void {\n if (runId !== basename(runId) || runId === \".\" || runId === \"..\" || runId.trim() === \"\") {\n throw new Error(\"Run id must be a single path segment.\");\n }\n}\n\nfunction isNodeError(error: unknown): error is NodeJS.ErrnoException {\n return error instanceof Error && \"code\" in error;\n}\n","import { appendFile, mkdir, readFile, writeFile } from \"node:fs/promises\";\nimport { basename, dirname, join } from \"node:path\";\nimport { TrailStepFailureError } from \"../../contracts/failures/failure.js\";\nimport type { Event } from \"../../runtime/run-workflow/run-workflow.types.js\";\n\nexport type RunState = Record<string, unknown>;\n\nexport function defaultRunsRoot(cwd: string): string {\n return join(cwd, \".trailstep\", \"runs\");\n}\n\nexport async function createRunDirectory(options: {\n readonly cwd: string;\n readonly runName: string;\n readonly runsRoot?: string;\n}): Promise<{ runId: string; runDir: string }> {\n const runsRoot = options.runsRoot ?? defaultRunsRoot(options.cwd);\n validateRunName(options.runName);\n await mkdir(runsRoot, { recursive: true });\n await ensureTrailStepGitignoreForRunsRoot(runsRoot);\n\n for (let suffix = 1; ; suffix += 1) {\n const runId = suffix === 1 ? options.runName : `${options.runName}-${suffix}`;\n const runDir = join(runsRoot, runId);\n\n try {\n await mkdir(runDir);\n return { runId, runDir };\n } catch (error) {\n if (isNodeError(error) && error.code === \"EEXIST\") {\n continue;\n }\n\n throw error;\n }\n }\n}\n\nexport async function appendEvent(runDir: string, event: Event): Promise<void> {\n await appendFile(join(runDir, \"events.jsonl\"), `${JSON.stringify(event)}\\n`, \"utf8\");\n}\n\nexport async function readRunEvents(runDir: string): Promise<Event[]> {\n let contents: string;\n try {\n contents = await readFile(join(runDir, \"events.jsonl\"), \"utf8\");\n } catch (error) {\n if (isNodeError(error)) {\n throw new TrailStepFailureError({\n code: \"resume_target_not_found\",\n message: `Resume target not found or unreadable: ${join(runDir, \"events.jsonl\")}.`,\n details: { runDir, causeCode: error.code },\n });\n }\n\n throw error;\n }\n\n const rawLines = contents.split(\"\\n\");\n const lines = rawLines.filter((line, index) => line.length > 0 || index < rawLines.length - 1);\n const events: Event[] = [];\n\n for (let index = 0; index < lines.length; index += 1) {\n const line = lines[index];\n if (!line) {\n continue;\n }\n\n try {\n events.push(JSON.parse(line) as Event);\n } catch (error) {\n const isTrailingLine = index === lines.length - 1;\n if (isTrailingLine) {\n return events;\n }\n\n throw error;\n }\n }\n\n return events;\n}\n\nexport async function persistEvents(runDir: string, events: readonly Event[]): Promise<void> {\n const jsonl = events.map((event) => JSON.stringify(event)).join(\"\\n\");\n await writeFile(join(runDir, \"events.jsonl\"), `${jsonl}\\n`, \"utf8\");\n}\n\nexport async function writeDocumentArtifact(\n dir: string,\n filename: string,\n content: string,\n): Promise<string> {\n await mkdir(dir, { recursive: true });\n\n const documentPath = join(dir, filename);\n await writeFile(documentPath, content, \"utf8\");\n\n return documentPath;\n}\n\nexport async function readJsonStateArtifact(path: string): Promise<RunState> {\n try {\n const contents = await readFile(path, \"utf8\");\n const parsed: unknown = JSON.parse(contents);\n\n if (!isRunState(parsed)) {\n throw new Error(\"run state must be a JSON object\");\n }\n\n return parsed;\n } catch (error) {\n if (isNodeError(error) && error.code === \"ENOENT\") {\n return {};\n }\n\n throw error;\n }\n}\n\nexport async function writeJsonStateArtifact(path: string, state: RunState): Promise<void> {\n await mkdir(dirname(path), { recursive: true });\n await writeFile(path, `${JSON.stringify(state, null, 2)}\\n`, \"utf8\");\n}\n\nexport function runStatePath(runDir: string): string {\n return join(runDir, \"state.json\");\n}\n\nexport function globalStatePath(runDir: string): string {\n return join(runDir, \"global-state.json\");\n}\n\nexport function branchStatePath(runDir: string, branchId: string): string {\n return join(runDir, \"branches\", `${branchId}.state.json`);\n}\n\nexport async function readRunState(runDir: string): Promise<RunState> {\n return await readJsonStateArtifact(runStatePath(runDir));\n}\n\nexport async function writeRunState(runDir: string, state: RunState): Promise<void> {\n await writeJsonStateArtifact(runStatePath(runDir), state);\n}\n\nexport async function readGlobalState(runDir: string): Promise<RunState> {\n return await readJsonStateArtifact(globalStatePath(runDir));\n}\n\nexport async function writeGlobalState(runDir: string, state: RunState): Promise<void> {\n await writeJsonStateArtifact(globalStatePath(runDir), state);\n}\n\nexport async function readBranchRunState(runDir: string, branchId: string): Promise<RunState> {\n return await readJsonStateArtifact(branchStatePath(runDir, branchId));\n}\n\nexport async function writeBranchRunState(\n runDir: string,\n branchId: string,\n state: RunState,\n): Promise<void> {\n await writeJsonStateArtifact(branchStatePath(runDir, branchId), state);\n}\n\nfunction isNodeError(error: unknown): error is NodeJS.ErrnoException {\n return error instanceof Error && \"code\" in error;\n}\n\nfunction validateRunName(runName: string): void {\n if (\n runName.trim().length === 0 ||\n runName === \".\" ||\n runName === \"..\" ||\n runName.includes(\"/\") ||\n runName.includes(\"\\\\\")\n ) {\n throw new TrailStepFailureError({\n code: \"run_name_invalid\",\n message: \"Run name must be a non-empty single path segment.\",\n details: { runName },\n });\n }\n}\n\nfunction isRunState(value: unknown): value is RunState {\n return (\n typeof value === \"object\" &&\n value !== null &&\n !Array.isArray(value) &&\n Object.getPrototypeOf(value) === Object.prototype\n );\n}\n\nasync function ensureTrailStepGitignoreForRunsRoot(runsRoot: string): Promise<void> {\n const trailstepRoot = dirname(runsRoot);\n if (basename(trailstepRoot) !== \".trailstep\") {\n return;\n }\n\n await ensureTrailStepGitignore(trailstepRoot);\n}\n\nasync function ensureTrailStepGitignore(trailstepRoot: string): Promise<void> {\n try {\n await writeFile(join(trailstepRoot, \".gitignore\"), \"*\\n!.gitignore\\n\", { flag: \"wx\" });\n } catch (error) {\n if (isNodeError(error) && error.code === \"EEXIST\") {\n return;\n }\n\n throw error;\n }\n}\n","import type { Dirent } from \"node:fs\";\nimport { readdir, readFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { defaultRunsRoot, readRunEvents } from \"../artifacts/run-storage.js\";\nimport type { LatestUnresolvedFailure } from \"../retry/latest-unresolved-failure.js\";\nimport { selectLatestUnresolvedFailure } from \"../retry/latest-unresolved-failure.js\";\nimport type { Event } from \"../run-workflow/run-workflow.types.js\";\nimport type { TrackSummary } from \"./track-summary.js\";\nimport { readTrackSummary } from \"./track-summary.js\";\n\nexport type RunSummaryStatus =\n | \"active\"\n | \"completed\"\n | \"failed\"\n | \"cancelled\"\n | \"archived\"\n | \"unknown\";\n\nexport interface RunSummary {\n readonly runId: string;\n readonly runDir: string;\n readonly status: RunSummaryStatus;\n readonly workflowId?: string;\n readonly lastTimestamp?: string;\n readonly latestFailure?: LatestUnresolvedFailure;\n readonly track?: TrackSummary;\n readonly trackWarning?: string;\n readonly warning?: string;\n}\n\nexport async function listRunSummaries(options: {\n readonly cwd: string;\n readonly runsRoot?: string;\n}): Promise<RunSummary[]> {\n const runsRoot = options.runsRoot ?? defaultRunsRoot(options.cwd);\n\n let entries: Dirent[];\n try {\n entries = await readdir(runsRoot, { withFileTypes: true });\n } catch (error) {\n if (isNodeError(error) && error.code === \"ENOENT\") {\n return [];\n }\n\n throw error;\n }\n\n const summaries: RunSummary[] = [];\n\n for (const entry of entries) {\n if (!entry.isDirectory() || entry.name === \".archive\") {\n continue;\n }\n\n const runId = entry.name;\n const runDir = join(runsRoot, runId);\n\n try {\n summaries.push(\n await summarizeReadableRun({ runId, runDir, events: await readRunEvents(runDir) }),\n );\n } catch (error) {\n summaries.push({\n runId,\n runDir,\n status: \"unknown\",\n warning: `Warning: Could not read run ${runId}: ${readErrorMessage(error)}`,\n });\n }\n }\n\n summaries.push(...(await listArchivedRunSummaries(runsRoot)));\n\n return summaries.sort(newestFirst);\n}\n\nexport function selectRecentFailedRunSummaries(\n summaries: readonly RunSummary[],\n options: { readonly now?: Date } = {},\n): RunSummary[] {\n const cutoffMs = (options.now ?? new Date()).getTime() - 7 * 24 * 60 * 60 * 1000;\n\n return summaries\n .filter((summary) => {\n if (summary.status !== \"failed\" || !summary.latestFailure) {\n return false;\n }\n\n const failureTime = Date.parse(summary.latestFailure.event.timestamp);\n return Number.isFinite(failureTime) && failureTime >= cutoffMs;\n })\n .sort(newestFirst)\n .slice(0, 10);\n}\n\nexport function newestFirst(left: RunSummary, right: RunSummary): number {\n return (\n compareTimestampDescending(left.lastTimestamp, right.lastTimestamp) ||\n left.runId.localeCompare(right.runId)\n );\n}\n\nasync function summarizeReadableRun(options: {\n readonly runId: string;\n readonly runDir: string;\n readonly events: readonly Event[];\n}): Promise<RunSummary> {\n let track: TrackSummary | undefined;\n let trackWarning: string | undefined;\n try {\n track = await readTrackSummary(options);\n } catch (error) {\n trackWarning = `Warning: Could not read track summary for run ${options.runId}: ${readErrorMessage(error)}`;\n }\n const trackFields = {\n ...(track === undefined ? {} : { track }),\n ...(trackWarning === undefined ? {} : { trackWarning }),\n };\n const latestFailure = selectLatestUnresolvedFailure(options.events);\n const terminalStatus = selectTerminalStatus(options.events);\n const lastEvent = options.events.at(-1);\n const workflowId =\n lastEvent?.workflowId ?? options.events.find((event) => event.workflowId)?.workflowId;\n\n if (terminalStatus === \"completed\" || terminalStatus === \"cancelled\") {\n return {\n ...options,\n ...trackFields,\n status: terminalStatus,\n workflowId,\n lastTimestamp: lastEvent?.timestamp,\n };\n }\n\n if (latestFailure) {\n return {\n ...options,\n ...trackFields,\n status: \"failed\",\n workflowId: latestFailure.workflowId,\n lastTimestamp: latestFailure.event.timestamp,\n latestFailure,\n };\n }\n\n return {\n ...options,\n ...trackFields,\n status: terminalStatus ?? \"active\",\n workflowId,\n lastTimestamp: lastEvent?.timestamp,\n };\n}\n\nfunction selectTerminalStatus(\n events: readonly Event[],\n): \"completed\" | \"failed\" | \"cancelled\" | undefined {\n for (let index = events.length - 1; index >= 0; index -= 1) {\n const event = events[index];\n if (event?.type === \"workflow.completed\") {\n return \"completed\";\n }\n\n if (event?.type === \"workflow.failed\") {\n return \"failed\";\n }\n\n if (event?.type === \"workflow.cancelled\") {\n return \"cancelled\";\n }\n }\n\n return undefined;\n}\n\nasync function listArchivedRunSummaries(runsRoot: string): Promise<RunSummary[]> {\n const archiveDir = join(runsRoot, \".archive\");\n let entries: Dirent[];\n try {\n entries = await readdir(archiveDir, { withFileTypes: true });\n } catch (error) {\n if (isNodeError(error) && error.code === \"ENOENT\") {\n return [];\n }\n throw error;\n }\n\n const summaries: RunSummary[] = [];\n for (const entry of entries) {\n if (!entry.isFile() || !entry.name.endsWith(\".manifest.json\")) {\n continue;\n }\n try {\n const manifest = JSON.parse(await readFile(join(archiveDir, entry.name), \"utf8\")) as {\n readonly runId?: unknown;\n readonly workflowId?: unknown;\n readonly lastTimestamp?: unknown;\n };\n if (typeof manifest.runId === \"string\") {\n summaries.push({\n runId: manifest.runId,\n runDir: join(archiveDir, `${manifest.runId}.json.gz`),\n status: \"archived\",\n ...(typeof manifest.workflowId === \"string\" ? { workflowId: manifest.workflowId } : {}),\n ...(typeof manifest.lastTimestamp === \"string\"\n ? { lastTimestamp: manifest.lastTimestamp }\n : {}),\n });\n }\n } catch (error) {\n summaries.push({\n runId: entry.name.replace(/\\.manifest\\.json$/u, \"\"),\n runDir: join(archiveDir, entry.name),\n status: \"unknown\",\n warning: `Warning: Could not read archived run manifest ${entry.name}: ${readErrorMessage(error)}`,\n });\n }\n }\n return summaries;\n}\n\nfunction compareTimestampDescending(left: string | undefined, right: string | undefined): number {\n const leftTime = left ? Date.parse(left) : Number.NEGATIVE_INFINITY;\n const rightTime = right ? Date.parse(right) : Number.NEGATIVE_INFINITY;\n return rightTime - leftTime;\n}\n\nfunction readErrorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\nfunction isNodeError(error: unknown): error is NodeJS.ErrnoException {\n return error instanceof Error && \"code\" in error;\n}\n","import type { PlainObject } from \"../../contracts/shapes/shape.types.js\";\nimport type { Event } from \"../run-workflow/run-workflow.types.js\";\n\nexport interface LatestUnresolvedFailure {\n readonly event: Event;\n readonly replayPosition: number;\n readonly sourceFailureEventId?: string;\n readonly workflowId: string;\n readonly workflowInput?: PlainObject;\n readonly stepId?: string;\n}\n\ninterface ResolvedFailureIdentity {\n readonly eventId?: string;\n readonly replayPosition?: number;\n}\n\nexport function selectLatestUnresolvedFailure(\n events: readonly Event[],\n): LatestUnresolvedFailure | undefined {\n const startedEvent = events.find((event) => event.type === \"workflow.started\");\n const workflowInput = startedEvent ? readPlainPayload(startedEvent, \"input\") : undefined;\n const resolvedFailures = events.flatMap((event) =>\n event.type === \"workflow.retryStarted\" ? readResolvedFailureIdentity(event) : [],\n );\n\n let workflowFailureFallback: LatestUnresolvedFailure | undefined;\n let laterWorkflowTerminalSeen = false;\n const laterTerminalStepCounts = new Map<string, number>();\n\n for (let replayPosition = events.length - 1; replayPosition >= 0; replayPosition -= 1) {\n const event = events[replayPosition];\n if (!event) {\n continue;\n }\n\n if (event.type === \"workflow.completed\" || event.type === \"workflow.cancelled\") {\n return undefined;\n }\n\n if (event.type === \"step.completed\" || event.type === \"step.cancelled\") {\n rememberTerminalStep(event, laterTerminalStepCounts);\n continue;\n }\n\n if (event.type === \"step.failed\") {\n rememberTerminalStep(event, laterTerminalStepCounts);\n if (isResolvedFailure(event, replayPosition, resolvedFailures)) {\n continue;\n }\n\n return toLatestUnresolvedFailure(event, replayPosition, workflowInput);\n }\n\n if (event.type === \"workflow.failed\") {\n laterWorkflowTerminalSeen = true;\n if (!workflowFailureFallback) {\n if (isResolvedFailure(event, replayPosition, resolvedFailures)) {\n continue;\n }\n\n workflowFailureFallback = toLatestUnresolvedFailure(event, replayPosition, workflowInput);\n }\n continue;\n }\n\n if (event.type === \"step.started\" && event.stepId) {\n if (consumeTerminalStep(event.stepId, laterTerminalStepCounts)) {\n continue;\n }\n\n if (!laterWorkflowTerminalSeen) {\n if (isResolvedFailure(event, replayPosition, resolvedFailures)) {\n continue;\n }\n\n return toLatestUnresolvedFailure(event, replayPosition, workflowInput);\n }\n }\n }\n\n return workflowFailureFallback;\n}\n\nfunction rememberTerminalStep(event: Event, stepCounts: Map<string, number>): void {\n if (event.stepId) {\n stepCounts.set(event.stepId, (stepCounts.get(event.stepId) ?? 0) + 1);\n }\n}\n\nfunction consumeTerminalStep(stepId: string, stepCounts: Map<string, number>): boolean {\n const count = stepCounts.get(stepId) ?? 0;\n if (count <= 0) {\n return false;\n }\n\n if (count === 1) {\n stepCounts.delete(stepId);\n } else {\n stepCounts.set(stepId, count - 1);\n }\n return true;\n}\n\nfunction readResolvedFailureIdentity(event: Event): readonly ResolvedFailureIdentity[] {\n const { sourceFailureEventId, sourceFailureReplayPosition } = event.payload;\n if (typeof sourceFailureEventId !== \"string\" && typeof sourceFailureReplayPosition !== \"number\") {\n return [];\n }\n\n return [\n {\n eventId: typeof sourceFailureEventId === \"string\" ? sourceFailureEventId : undefined,\n replayPosition:\n typeof sourceFailureReplayPosition === \"number\" ? sourceFailureReplayPosition : undefined,\n },\n ];\n}\n\nfunction isResolvedFailure(\n event: Event,\n replayPosition: number,\n resolvedFailures: readonly ResolvedFailureIdentity[],\n): boolean {\n return resolvedFailures.some((resolvedFailure) => {\n if (resolvedFailure.replayPosition !== undefined) {\n return resolvedFailure.replayPosition === replayPosition;\n }\n\n return resolvedFailure.eventId !== undefined && resolvedFailure.eventId === event.id;\n });\n}\n\nfunction toLatestUnresolvedFailure(\n event: Event,\n replayPosition: number,\n workflowInput: PlainObject | undefined,\n): LatestUnresolvedFailure {\n return {\n event,\n replayPosition,\n sourceFailureEventId: typeof event.id === \"string\" ? event.id : undefined,\n workflowId: event.workflowId,\n workflowInput,\n stepId: event.stepId,\n };\n}\n\nfunction readPlainPayload(event: Event, key: string): PlainObject | undefined {\n const value = event.payload[key];\n return isPlainObject(value) ? value : undefined;\n}\n\nfunction isPlainObject(value: unknown): value is PlainObject {\n return (\n typeof value === \"object\" &&\n value !== null &&\n !Array.isArray(value) &&\n Object.getPrototypeOf(value) === Object.prototype\n );\n}\n","import { readFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\n\nimport type { PlainObject } from \"../../contracts/shapes/shape.types.js\";\nimport type { Event } from \"../run-workflow/run-workflow.types.js\";\n\nexport interface TrackSummary {\n readonly runId: string;\n readonly status: string;\n readonly workers?: number;\n readonly failurePolicy?: string;\n readonly rootBranchId?: string;\n readonly terminalBranchId?: string;\n readonly terminalKind?: string;\n readonly terminalOutput?: unknown;\n readonly failure?: unknown;\n readonly splitOccurred?: boolean;\n readonly branches: readonly BranchSummary[];\n}\n\nexport interface BranchSummary {\n readonly branchId: string;\n readonly requestedBranchId?: string;\n readonly parentBranchId?: string;\n readonly status?: string;\n readonly workflowId?: string;\n readonly latestStepIndex?: number;\n readonly latestStepId?: string;\n readonly latestMessage?: string;\n readonly wait?: unknown;\n readonly failure?: unknown;\n readonly output?: unknown;\n}\n\nexport async function readTrackSummary(options: {\n readonly runId: string;\n readonly runDir: string;\n readonly events: readonly Event[];\n}): Promise<TrackSummary | undefined> {\n const track = await readJsonObject(join(options.runDir, \"track.json\"));\n if (track === undefined) {\n return undefined;\n }\n\n const branchIds = Array.isArray(track.branches)\n ? track.branches.filter((branchId): branchId is string => typeof branchId === \"string\")\n : [];\n\n const branches = await Promise.all(\n branchIds.map(async (branchId) => summarizeBranch(options.runDir, branchId, options.events)),\n );\n\n return {\n runId: stringValue(track.runId) ?? options.runId,\n status: stringValue(track.status) ?? \"unknown\",\n ...(numberValue(track.workers) === undefined ? {} : { workers: numberValue(track.workers) }),\n ...(stringValue(track.failurePolicy) === undefined\n ? {}\n : { failurePolicy: stringValue(track.failurePolicy) }),\n ...(stringValue(track.rootBranchId) === undefined\n ? {}\n : { rootBranchId: stringValue(track.rootBranchId) }),\n ...(stringValue(track.terminalBranchId) === undefined\n ? {}\n : { terminalBranchId: stringValue(track.terminalBranchId) }),\n ...(stringValue(track.terminalKind) === undefined\n ? {}\n : { terminalKind: stringValue(track.terminalKind) }),\n ...(track.terminalOutput === undefined ? {} : { terminalOutput: track.terminalOutput }),\n ...(track.failure === undefined ? {} : { failure: track.failure }),\n ...(typeof track.splitOccurred === \"boolean\" ? { splitOccurred: track.splitOccurred } : {}),\n branches,\n };\n}\n\nasync function summarizeBranch(\n runDir: string,\n branchId: string,\n events: readonly Event[],\n): Promise<BranchSummary> {\n const branch = (await readJsonObject(join(runDir, \"branches\", `${branchId}.json`))) ?? {};\n const branchEvents = events.filter((event) => event.payload.branchId === branchId);\n const latestFailureMessage = selectLatestEventFailureMessage(branchEvents);\n const latestMessage =\n latestFailureMessage ?? stringValue(branch.message) ?? selectLatestEventMessage(branchEvents);\n const failure = branch.failure ?? selectLatestEventFailure(branchEvents);\n\n return {\n branchId: stringValue(branch.branchId) ?? branchId,\n ...(stringValue(branch.requestedBranchId) === undefined\n ? {}\n : { requestedBranchId: stringValue(branch.requestedBranchId) }),\n ...(stringValue(branch.parentBranchId) === undefined\n ? {}\n : { parentBranchId: stringValue(branch.parentBranchId) }),\n ...(stringValue(branch.status) === undefined ? {} : { status: stringValue(branch.status) }),\n ...(stringValue(branch.workflowId) === undefined\n ? {}\n : { workflowId: stringValue(branch.workflowId) }),\n ...(numberValue(branch.latestStepIndex) === undefined\n ? {}\n : { latestStepIndex: numberValue(branch.latestStepIndex) }),\n ...(stringValue(branch.latestStepId) === undefined\n ? {}\n : { latestStepId: stringValue(branch.latestStepId) }),\n ...(latestMessage === undefined ? {} : { latestMessage }),\n ...(branch.wait === undefined ? {} : { wait: branch.wait }),\n ...(failure === undefined ? {} : { failure }),\n ...(branch.output === undefined ? {} : { output: branch.output }),\n };\n}\n\nasync function readJsonObject(path: string): Promise<PlainObject | undefined> {\n try {\n const value = JSON.parse(await readFile(path, \"utf8\")) as unknown;\n return isPlainObject(value) ? value : {};\n } catch (error) {\n if (isNodeError(error) && error.code === \"ENOENT\") {\n return undefined;\n }\n throw error;\n }\n}\n\nfunction selectLatestEventMessage(events: readonly Event[]): string | undefined {\n for (let index = events.length - 1; index >= 0; index -= 1) {\n const event = events[index];\n const message = stringValue(event?.payload.message);\n if (message !== undefined) {\n return message;\n }\n const failureMessage = isPlainObject(event?.payload.failure)\n ? stringValue(event.payload.failure.message)\n : undefined;\n if (failureMessage !== undefined) {\n return failureMessage;\n }\n }\n return undefined;\n}\n\nfunction selectLatestEventFailureMessage(events: readonly Event[]): string | undefined {\n const failure = selectLatestEventFailure(events);\n return isPlainObject(failure) ? stringValue(failure.message) : undefined;\n}\n\nfunction selectLatestEventFailure(events: readonly Event[]): unknown {\n for (let index = events.length - 1; index >= 0; index -= 1) {\n const failure = events[index]?.payload.failure;\n if (failure !== undefined) {\n return failure;\n }\n }\n return undefined;\n}\n\nfunction stringValue(value: unknown): string | undefined {\n return typeof value === \"string\" ? value : undefined;\n}\n\nfunction numberValue(value: unknown): number | undefined {\n return typeof value === \"number\" && Number.isFinite(value) ? value : undefined;\n}\n\nfunction isPlainObject(value: unknown): value is PlainObject {\n return (\n typeof value === \"object\" &&\n value !== null &&\n !Array.isArray(value) &&\n Object.getPrototypeOf(value) === Object.prototype\n );\n}\n\nfunction isNodeError(error: unknown): error is NodeJS.ErrnoException {\n return error instanceof Error && \"code\" in error;\n}\n","import { parseStorageLifecycleDurationDays } from \"../../runtime/storage-lifecycle/storage-lifecycle.js\";\nimport type { TrailStepStorageConfig } from \"../targeting.types.js\";\nimport { isRecord, parseOptionalStringArray } from \"./parse-utils.js\";\n\nconst VALID_RUN_ON = new Set([\"run\", \"open\", \"runs\"]);\n\nexport function parseStorageConfig(\n value: unknown,\n diagnostics: string[],\n): TrailStepStorageConfig | undefined {\n if (value === undefined) {\n return undefined;\n }\n\n if (!isRecord(value)) {\n diagnostics.push(\"storage must be an object when present.\");\n return undefined;\n }\n\n const lifecycle = parseLifecycleConfig(value.lifecycle, diagnostics);\n return lifecycle === undefined ? {} : { lifecycle };\n}\n\nfunction parseLifecycleConfig(\n value: unknown,\n diagnostics: string[],\n): NonNullable<TrailStepStorageConfig[\"lifecycle\"]> | undefined {\n if (value === undefined) {\n return undefined;\n }\n\n if (!isRecord(value)) {\n diagnostics.push(\"storage.lifecycle must be an object when present.\");\n return undefined;\n }\n\n const runOn = parseOptionalStringArray(\"storage.lifecycle.runOn\", value.runOn, diagnostics);\n if (runOn !== undefined) {\n for (const entry of runOn) {\n if (!VALID_RUN_ON.has(entry)) {\n diagnostics.push(\"storage.lifecycle.runOn entries must be one of run, open, or runs.\");\n break;\n }\n }\n }\n\n if (value.enabled !== undefined && typeof value.enabled !== \"boolean\") {\n diagnostics.push(\"storage.lifecycle.enabled must be a boolean when present.\");\n }\n if (\n value.throttle !== undefined &&\n value.throttle !== false &&\n typeof value.throttle !== \"string\"\n ) {\n diagnostics.push(\"storage.lifecycle.throttle must be a string or false when present.\");\n }\n\n const retention = parseRetentionConfig(\"storage.lifecycle\", value, diagnostics);\n const workflows = parseWorkflowRetentionConfigs(value.workflows, diagnostics);\n\n return {\n ...(typeof value.enabled === \"boolean\" ? { enabled: value.enabled } : {}),\n ...(runOn === undefined ? {} : { runOn: runOn as readonly (\"run\" | \"open\" | \"runs\")[] }),\n ...(value.throttle === undefined ||\n (value.throttle !== false && typeof value.throttle !== \"string\")\n ? {}\n : { throttle: value.throttle }),\n ...(retention === undefined ? {} : retention),\n ...(workflows === undefined ? {} : { workflows }),\n };\n}\n\nfunction parseWorkflowRetentionConfigs(\n value: unknown,\n diagnostics: string[],\n): NonNullable<NonNullable<TrailStepStorageConfig[\"lifecycle\"]>[\"workflows\"]> | undefined {\n if (value === undefined) {\n return undefined;\n }\n if (!isRecord(value)) {\n diagnostics.push(\"storage.lifecycle.workflows must be an object when present.\");\n return undefined;\n }\n\n const workflows: Record<\n string,\n NonNullable<NonNullable<TrailStepStorageConfig[\"lifecycle\"]>[\"workflows\"]>[string]\n > = {};\n for (const [workflowId, config] of Object.entries(value)) {\n const parsed = parseRetentionConfig(\n `storage.lifecycle.workflows.${workflowId}`,\n config,\n diagnostics,\n );\n if (parsed !== undefined) {\n workflows[workflowId] = parsed;\n }\n }\n return workflows;\n}\n\nfunction parseRetentionConfig(\n path: string,\n value: unknown,\n diagnostics: string[],\n): NonNullable<NonNullable<TrailStepStorageConfig[\"lifecycle\"]>[\"workflows\"]>[string] | undefined {\n if (value === undefined) {\n return undefined;\n }\n if (!isRecord(value)) {\n diagnostics.push(`${path} must be an object when present.`);\n return undefined;\n }\n\n validateDurationOrFalse(`${path}.compressAfter`, value.compressAfter, diagnostics);\n validateDurationOrFalse(`${path}.deleteAfter`, value.deleteAfter, diagnostics);\n\n return {\n ...(value.compressAfter === undefined ||\n (value.compressAfter !== false && typeof value.compressAfter !== \"string\")\n ? {}\n : { compressAfter: value.compressAfter }),\n ...(value.deleteAfter === undefined ||\n (value.deleteAfter !== false && typeof value.deleteAfter !== \"string\")\n ? {}\n : { deleteAfter: value.deleteAfter }),\n };\n}\n\nfunction validateDurationOrFalse(path: string, value: unknown, diagnostics: string[]): void {\n if (value === undefined || value === false) {\n return;\n }\n if (typeof value === \"string\" && parseStorageLifecycleDurationDays(value) !== undefined) {\n return;\n }\n diagnostics.push(\n `${path} must be a duration string (for example 7d, 12h, or 2w) or false when present.`,\n );\n}\n","import type { TrailStepSettings } from \"../targeting.types.js\";\nimport { parseAgentMappings } from \"./parse-agent-mappings.js\";\nimport type { RawTrailStepAgentMappings } from \"./parse-agent-targets.js\";\nimport { parseSettings } from \"./parse-settings.js\";\nimport { isRecord } from \"./parse-utils.js\";\n\nexport interface RawTrailStepWorkflowConfig {\n readonly agents?: RawTrailStepAgentMappings;\n readonly settings?: TrailStepSettings;\n}\n\nexport function parseWorkflows(\n value: unknown,\n diagnostics: string[],\n): Record<string, RawTrailStepWorkflowConfig> | undefined {\n if (value === undefined) {\n return undefined;\n }\n\n const workflows: Record<string, RawTrailStepWorkflowConfig> = {};\n\n if (!isRecord(value)) {\n diagnostics.push(\"workflows must be an object when present.\");\n return workflows;\n }\n\n for (const [workflowId, workflow] of Object.entries(value)) {\n if (!isRecord(workflow)) {\n diagnostics.push(`workflows.${workflowId} must be an object.`);\n continue;\n }\n\n const agents =\n workflow.agents === undefined\n ? undefined\n : parseAgentMappings(`workflows.${workflowId}.agents`, workflow.agents, diagnostics);\n\n const settings = parseSettings(\n `workflows.${workflowId}.settings`,\n workflow.settings,\n diagnostics,\n );\n\n workflows[workflowId] = {\n ...(agents === undefined ? {} : { agents }),\n ...(settings === undefined ? {} : { settings }),\n };\n }\n\n return workflows;\n}\n","import { TrailStepFailureError } from \"../../contracts/failures/failure.js\";\nimport type { RawTrailStepAgentMappings, RawTrailStepAgentTarget } from \"./parse-agent-targets.js\";\nimport type { RawTrailStepWorkflowConfig } from \"./parse-workflow-agent-mappings.js\";\n\nexport function validateProviderReferences(options: {\n readonly agents: RawTrailStepAgentMappings;\n readonly workflows: Readonly<Record<string, RawTrailStepWorkflowConfig>> | undefined;\n readonly providerNames: Set<string>;\n}): void {\n const providerViolations: string[] = [];\n\n validateAgentMappings(\"agents\", options.agents, options.providerNames, providerViolations);\n\n if (options.workflows !== undefined) {\n for (const [workflowId, workflow] of Object.entries(options.workflows)) {\n validateAgentMappings(\n `workflows.${workflowId}.agents`,\n workflow.agents,\n options.providerNames,\n providerViolations,\n );\n }\n }\n\n if (providerViolations.length > 0) {\n throw new TrailStepFailureError({\n code: \"agent_provider_unknown\",\n message:\n \"One or more agent targets reference a provider that is not declared under customProviders/providers.\",\n details: { diagnostics: providerViolations },\n });\n }\n}\n\nfunction validateAgentMappings(\n path: string,\n mappings: RawTrailStepAgentMappings | undefined,\n providerNames: Set<string>,\n diagnostics: string[],\n): void {\n if (mappings === undefined) {\n return;\n }\n\n for (const [name, targets] of Object.entries(mappings)) {\n validateTargetReferences(`${path}.${name}`, targets, providerNames, diagnostics);\n }\n}\n\nfunction validateTargetReferences(\n path: string,\n targets: readonly RawTrailStepAgentTarget[],\n providerNames: Set<string>,\n diagnostics: string[],\n): void {\n for (const [index, target] of targets.entries()) {\n if (!(\"provider\" in target)) {\n continue;\n }\n\n if (!providerNames.has(target.provider)) {\n diagnostics.push(\n `${path}[${index}].provider references unknown provider '${target.provider}'. Declare it under customProviders/providers.`,\n );\n }\n }\n}\n","import {\n parseTrailStepProviderRegistrations,\n type TrailStepProviderRegistration,\n} from \"../../providers/provider-manifest.js\";\nimport type { TrailStepConfig } from \"../targeting.types.js\";\nimport { expandAgentRefs } from \"./expand-agent-refs.js\";\nimport { parseAgentMappings } from \"./parse-agent-mappings.js\";\nimport { parseCustomProviders } from \"./parse-custom-providers.js\";\nimport { parseSettings } from \"./parse-settings.js\";\nimport { parseStorageConfig } from \"./parse-storage-config.js\";\nimport { isRecord, throwValidationFailure } from \"./parse-utils.js\";\nimport { parseWorkflows } from \"./parse-workflow-agent-mappings.js\";\nimport { validateProviderReferences } from \"./validate-provider-references.js\";\n\nexport type ParsedTrailStepConfig = TrailStepConfig & {\n readonly providers: NonNullable<TrailStepConfig[\"providers\"]>;\n};\n\nconst parsedConfigs = new WeakSet<TrailStepConfig>();\n\nexport function isParsedTrailStepConfig(value: unknown): value is TrailStepConfig {\n return isRecord(value) && parsedConfigs.has(value as unknown as TrailStepConfig);\n}\n\nexport function parseTrailStepConfig(value: unknown): ParsedTrailStepConfig {\n const diagnostics: string[] = [];\n\n if (!isRecord(value)) {\n throwValidationFailure([\"config must be an object.\"]);\n }\n\n if (value.version !== 1) {\n diagnostics.push(\"version must be 1.\");\n }\n\n const customProviders = parseCustomProviders(value.customProviders, diagnostics);\n const providers = parseTrailStepProviderRegistrations(\"providers\", value.providers, diagnostics);\n for (const providerId of Object.keys(customProviders)) {\n if (providers[providerId] !== undefined) {\n diagnostics.push(\n `providers.${providerId} conflicts with legacy customProviders.${providerId}. Rename one provider id or migrate customProviders.${providerId} to providers.${providerId}.`,\n );\n }\n }\n const compatibilityProviders = legacyCustomProvidersAsRegistrations(customProviders);\n const providerNames = new Set([\n ...Object.keys(customProviders),\n ...Object.keys(providers),\n ...Object.keys(compatibilityProviders),\n ]);\n const agents = parseAgentMappings(\"agents\", value.agents, diagnostics);\n const settings = parseSettings(\"settings\", value.settings, diagnostics);\n const storage = parseStorageConfig(value.storage, diagnostics);\n const workflows = parseWorkflows(value.workflows, diagnostics);\n\n if (diagnostics.length > 0) {\n throwValidationFailure(diagnostics);\n }\n\n validateProviderReferences({ agents, workflows, providerNames });\n const expanded = expandAgentRefs({ agents, workflows });\n\n const unifiedProviders = { ...compatibilityProviders, ...providers };\n const config = {\n version: 1,\n customProviders,\n ...(Object.keys(providers).length === 0 ? {} : { providers: unifiedProviders }),\n agents: expanded.agents,\n ...(settings === undefined ? {} : { settings }),\n ...(storage === undefined ? {} : { storage }),\n ...(expanded.workflows === undefined ? {} : { workflows: expanded.workflows }),\n } as ParsedTrailStepConfig;\n\n if (Object.keys(providers).length === 0) {\n Object.defineProperty(config, \"providers\", { value: unifiedProviders, enumerable: false });\n }\n\n parsedConfigs.add(config);\n\n return config;\n}\n\nfunction legacyCustomProvidersAsRegistrations(\n customProviders: Record<string, TrailStepConfig[\"customProviders\"][string]>,\n): Record<string, TrailStepProviderRegistration> {\n return Object.fromEntries(\n Object.entries(customProviders).map(([id, provider]) => [\n id,\n {\n source: { type: \"legacy-custom-provider\" },\n manifest: {\n schemaVersion: 1,\n id,\n displayName: id,\n working: {\n supported: true,\n command: provider.binary,\n ...(provider.args === undefined ? {} : { args: provider.args }),\n prompt: { kind: \"prompt-file\" },\n output: { style: \"provider-output-file\" },\n },\n interactive: provider.interactiveArgs\n ? {\n supported: true,\n command: provider.binary,\n args: provider.interactiveArgs,\n }\n : { supported: false, reason: \"interactiveArgs is not declared\" },\n model: provider.model ?? { supported: false },\n thinking: provider.thinking ?? { supported: false },\n ...(provider.cwd === undefined ? {} : { cwd: provider.cwd }),\n ...(provider.env === undefined ? {} : { env: provider.env }),\n },\n } as TrailStepProviderRegistration,\n ]),\n );\n}\n","import { TrailStepFailureError } from \"../../contracts/failures/failure.js\";\nimport type { ResolveAgentTargetsOptions, TrailStepAgentTarget } from \"../targeting.types.js\";\n\nexport function resolveAgentTargets(\n options: ResolveAgentTargetsOptions,\n): readonly TrailStepAgentTarget[] {\n const workflowMappings = options.config.workflows?.[options.workflowId]?.agents;\n\n const topLevelAgentKeys = uniqueAgentKeys([options.roleName, options.roleSize, \"default\"]);\n const targetLists = [\n workflowMappings?.[options.roleName],\n ...topLevelAgentKeys.map((key) => options.config.agents[key]),\n ];\n\n const targets = targetLists.flatMap((targets) =>\n targets && targets.length > 0 ? [...targets] : [],\n );\n\n if (targets.length > 0) {\n return targets;\n }\n\n throw new TrailStepFailureError({\n code: \"agent_targets_unavailable\",\n message: `No agent targets found for role ${options.roleName} with size ${options.roleSize} in workflow ${options.workflowId}.`,\n details: {\n roleName: options.roleName,\n roleSize: options.roleSize,\n workflowId: options.workflowId,\n },\n });\n}\n\nfunction uniqueAgentKeys(keys: readonly string[]): readonly string[] {\n return keys.filter((key, index) => keys.indexOf(key) === index);\n}\n","import { AsyncLocalStorage } from \"node:async_hooks\";\nimport type { RunContext } from \"../../contracts/run-context/run-context.types.js\";\n\n/**\n * A module-scoped `new AsyncLocalStorage()` is not safe here: the CLI's\n * direct-file workflow resolver loads workflow source through `tsx`'s\n * `tsImport`, which re-transpiles and re-evaluates everything reachable from\n * that entry point -- including this module -- as a second, independent\n * instantiation, even though it's the exact same file on disk. Two distinct\n * `AsyncLocalStorage` objects never see each other's stores no matter how\n * carefully `.run(...)` is nested, so `run-workflow.ts`/`with-step-context.ts`\n * (loaded the normal way) and a workflow's own step code (loaded via\n * `tsImport`) would silently end up talking to two different storages.\n * Keying the single instance off a well-known symbol on `globalThis` -- shared\n * by every module instantiation within the same process/realm -- keeps them\n * talking to the same storage regardless of which loader touched this file.\n */\nconst RUN_CONTEXT_STORAGE_KEY = Symbol.for(\"trailstep.core.runContextStorage\");\n\ninterface GlobalWithRunContextStorage {\n [RUN_CONTEXT_STORAGE_KEY]?: AsyncLocalStorage<RunContext>;\n}\n\nconst globalScope = globalThis as GlobalWithRunContextStorage;\n\nfunction getOrCreateRunContextStorage(): AsyncLocalStorage<RunContext> {\n const existing = globalScope[RUN_CONTEXT_STORAGE_KEY];\n if (existing) {\n return existing;\n }\n\n const created = new AsyncLocalStorage<RunContext>();\n globalScope[RUN_CONTEXT_STORAGE_KEY] = created;\n return created;\n}\n\nexport const runContextStorage: AsyncLocalStorage<RunContext> = getOrCreateRunContextStorage();\n\nexport function currentRunContext(): RunContext {\n const runContext = runContextStorage.getStore();\n if (!runContext) {\n throw new Error(\"state.* called outside an active TrailStep run.\");\n }\n\n return runContext;\n}\n","import { TrailStepFailureError, validationFailure } from \"../../contracts/failures/failure.js\";\nimport type { ValidationDiagnostic } from \"../../contracts/shapes/shape.types.js\";\nimport { writeDocumentArtifact } from \"../../runtime/artifacts/run-storage.js\";\nimport { currentRunContext } from \"../../runtime/run-context/run-context-storage.js\";\n\n/**\n * A captured document artifact. `Document` doubles as its own\n * `Schema<Document>`: `validate`/`diagnostics`/`assert`/`jsonSchema`/\n * `captureMode` are static members, so passing the class itself as\n * `.prompt(source, { output: Document })` gives both the TypeScript output\n * type and the runtime validator from one symbol -- no separate schema\n * constant to import or keep in sync.\n */\nexport class Document {\n // Index signature satisfies the `PlainObject` (`Record<string, unknown>`)\n // constraint required by `Schema<T extends PlainObject>` — a plain class\n // with only named properties does not structurally provide one otherwise.\n [key: string]: unknown;\n\n static readonly captureMode = \"raw-text\" as const;\n\n static readonly jsonSchema: Record<string, unknown> = {\n type: \"string\",\n description: \"Document content, captured as raw text.\",\n };\n\n static validate(value: unknown): value is Document {\n return isDocumentLike(value);\n }\n\n static diagnostics(value: unknown): readonly ValidationDiagnostic[] {\n if (isDocumentLike(value)) {\n return [];\n }\n\n return [\n { path: \"/\", message: \"must be a document (an object with string content and path fields)\" },\n ];\n }\n\n /**\n * Deliberately duck-types instead of checking `instanceof Document`: on\n * resume, a completed step's recorded output is replayed from\n * `events.jsonl` via `JSON.parse`, producing a plain deserialized object —\n * never a live `Document` instance — before `assert` is called on it. An\n * `instanceof` check would fail every such replay. `assert` reconstructs a\n * genuine `Document` from any content/path-shaped value, so every\n * consumer downstream — a live capture or a replayed value alike — always\n * receives a real `Document` instance with working prototype methods.\n */\n static assert(value: unknown, label = \"value\"): Document {\n const valueDiagnostics = Document.diagnostics(value);\n\n if (valueDiagnostics.length > 0 || !isDocumentLike(value)) {\n throw new TrailStepFailureError(\n validationFailure(\n `${label} failed schema validation: ${formatDiagnostics(valueDiagnostics)}`,\n {\n diagnostics: valueDiagnostics,\n },\n ),\n );\n }\n\n return new Document(value.content, value.path);\n }\n\n constructor(\n public readonly content: string,\n public readonly path: string,\n ) {}\n}\n\n/**\n * Captures `content` as a durable document artifact for the currently\n * executing step. Must be called from within a step's `.do()` callback —\n * it reads the step-scoped ambient context (`RunContext.currentStep`, set\n * by `withStepContext` for the duration of the step) to determine both the\n * directory to write into and this call's 1-based index within the step, so\n * that a step calling `document(...)` more than once gets\n * `document-1.md`, `document-2.md`, etc.\n */\nexport async function document(content: string): Promise<Document> {\n const { currentStep } = currentRunContext();\n\n if (!currentStep) {\n throw new Error(\n \"document(...) must be called from within a step's `.do()` callback; no active step context was found.\",\n );\n }\n\n const index = currentStep.nextDocumentIndex();\n const path = await writeDocumentArtifact(currentStep.dir, `document-${index}.md`, content);\n\n return new Document(content, path);\n}\n\nfunction isDocumentLike(value: unknown): value is { content: string; path: string } {\n return (\n typeof value === \"object\" &&\n value !== null &&\n typeof (value as Record<string, unknown>).content === \"string\" &&\n typeof (value as Record<string, unknown>).path === \"string\"\n );\n}\n\nfunction formatDiagnostics(diagnostics: readonly ValidationDiagnostic[]): string {\n return diagnostics.map((diagnostic) => `${diagnostic.path} ${diagnostic.message}`).join(\"; \");\n}\n","import { currentRunContext } from \"../../runtime/run-context/run-context-storage.js\";\n\n/** Ambient handle onto the active run's track-scoped durable key-value store. */\nexport const globalState = {\n async get<T = unknown>(key: string): Promise<T | undefined> {\n return currentRunContext().globalState.get<T>(key);\n },\n async set(key: string, value: unknown): Promise<void> {\n await currentRunContext().globalState.set(key, value);\n },\n async update<T = unknown>(\n key: string,\n updater: (current: T | undefined) => T | Promise<T>,\n ): Promise<T> {\n return await currentRunContext().globalState.update<T>(key, updater);\n },\n};\n","import { randomUUID } from \"node:crypto\";\n\nimport type { PlainObject } from \"../../contracts/shapes/shape.types.js\";\nimport type { Event } from \"../../runtime/run-workflow/run-workflow.types.js\";\n\nexport function createEvent(options: {\n readonly runId: string;\n readonly workflowId: string;\n readonly stepId?: string;\n readonly type: Event[\"type\"];\n readonly payload?: PlainObject;\n}): Event {\n return {\n id: `evt_${randomUUID()}`,\n runId: options.runId,\n workflowId: options.workflowId,\n stepId: options.stepId,\n type: options.type,\n timestamp: new Date().toISOString(),\n schemaVersion: \"v0\",\n payload: options.payload ?? {},\n };\n}\n","import type { PlainObject } from \"../../contracts/shapes/shape.types.js\";\nimport { createEvent } from \"../../runtime/events/create-run-event.js\";\nimport { runContextStorage } from \"../../runtime/run-context/run-context-storage.js\";\n\nexport interface NotifyArtifact {\n readonly path: string;\n readonly mediaType?: string;\n readonly data?: PlainObject;\n}\n\nexport interface NotifyApi {\n progress(message: string, data?: PlainObject): Promise<void>;\n warning(message: string, data?: PlainObject): Promise<void>;\n artifact(name: string, artifact: NotifyArtifact): Promise<void>;\n}\n\nexport const notify: NotifyApi = {\n async progress(message, data) {\n await emitNotification(\"step.progress\", { message, ...(data === undefined ? {} : { data }) });\n },\n async warning(message, data) {\n await emitNotification(\"step.warning\", { message, ...(data === undefined ? {} : { data }) });\n },\n async artifact(name, artifact) {\n await emitNotification(\"step.artifact\", {\n name,\n path: artifact.path,\n ...(artifact.mediaType === undefined ? {} : { mediaType: artifact.mediaType }),\n ...(artifact.data === undefined ? {} : { data: artifact.data }),\n });\n },\n};\n\nasync function emitNotification(\n type: \"step.progress\" | \"step.warning\" | \"step.artifact\",\n payload: PlainObject,\n): Promise<void> {\n const runContext = runContextStorage.getStore();\n if (!runContext?.workflowId || !runContext.emit) {\n throw new Error(\"notify.* called outside an active TrailStep run.\");\n }\n\n await runContext.emit(\n createEvent({\n runId: runContext.id,\n workflowId: runContext.workflowId,\n ...(runContext.currentStep === undefined ? {} : { stepId: runContext.currentStep.id }),\n type,\n payload,\n }),\n );\n}\n","import { readFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\n\n/**\n * Synchronously reads each named file relative to `dir` and returns its\n * trimmed content keyed the same way, so a step's `prompt.ts` can load all\n * of its shared markdown fragments in one call:\n * `loadFragments(import.meta.dirname, { methodology: \"../shared/methodology.md\" })`.\n */\nexport function loadFragments<TKey extends string>(\n dir: string,\n files: Record<TKey, string>,\n): Record<TKey, string> {\n const fragments = {} as Record<TKey, string>;\n\n for (const key of Object.keys(files) as TKey[]) {\n fragments[key] = readFileSync(join(dir, files[key]), \"utf8\").trimEnd();\n }\n\n return fragments;\n}\n\n/**\n * Renders `body` as a `## title` markdown section, or `undefined` when\n * `body` is falsy -- so a conditional section can be inlined directly as a\n * `promptSections(...)` argument instead of built up separately.\n */\nexport function section(\n title: string,\n body: string | false | null | undefined,\n): string | undefined {\n return body ? `## ${title}\\n\\n${body.trimEnd()}` : undefined;\n}\n\n/**\n * Joins prompt fragments and `section(...)` results with a blank line\n * between each, dropping any falsy (conditionally-omitted) part.\n */\nexport function promptSections(...parts: ReadonlyArray<string | false | null | undefined>): string {\n return parts.filter((part): part is string => Boolean(part)).join(\"\\n\\n\");\n}\n\n/** Renders `items` as a markdown bullet list, one `- item` per line. */\nexport function list(items: readonly string[]): string {\n return items.map((item) => `- ${item}`).join(\"\\n\");\n}\n","import type { PromptTemplateSource } from \"../step/continuation.types.js\";\n\n/** Loads a step's prompt from a local text file, resolved relative to the workflow/project `cwd` at dispatch time. */\nexport function promptTemplate(path: string): PromptTemplateSource {\n return { kind: \"promptTemplate\", path };\n}\n","import { Ajv, type ErrorObject, type JSONSchemaType } from \"ajv/dist/ajv.js\";\n\nimport { TrailStepFailureError, validationFailure } from \"../../contracts/failures/failure.js\";\nimport type {\n PlainObject,\n Schema,\n ShapeInput,\n ShapeObject,\n ValidationDiagnostic,\n} from \"../../contracts/shapes/shape.types.js\";\n\nexport type JsonSchemaObject = JSONSchemaType<PlainObject> | Record<string, unknown>;\n\nconst ajv = new Ajv({ allErrors: true });\n\nexport function normalizeShape<T extends PlainObject>(shapeInput: ShapeInput<T>): Schema<T> {\n if (isSchema(shapeInput)) {\n return shapeInput;\n }\n\n return shape<T>(shapeInput);\n}\n\nexport function shape<T extends PlainObject>(shapeObject: ShapeObject): Schema<T> {\n return jsonSchema<T>({\n type: \"object\",\n properties: Object.fromEntries(\n Object.entries(shapeObject).map(([key, type]) => [key, { type }]),\n ),\n required: Object.keys(shapeObject),\n additionalProperties: false,\n });\n}\n\nexport function jsonSchema<T extends PlainObject>(schema: JsonSchemaObject): Schema<T> {\n const validateWithAjv = ajv.compile(schema);\n\n return {\n validate(value: unknown): value is T {\n return validateWithAjv(value);\n },\n diagnostics(value: unknown): readonly ValidationDiagnostic[] {\n if (!isPlainObject(value)) {\n return [{ path: \"/\", message: \"must be a plain object\" }];\n }\n\n if (validateWithAjv(value)) {\n return [];\n }\n\n return diagnosticsFromAjvErrors(validateWithAjv.errors);\n },\n assert(value: unknown, label = \"value\"): T {\n const diagnostics = this.diagnostics(value);\n\n if (diagnostics.length > 0) {\n throw new TrailStepFailureError(\n validationFailure(\n `${label} failed schema validation: ${formatDiagnostics(diagnostics)}`,\n { diagnostics },\n ),\n );\n }\n\n return value as T;\n },\n jsonSchema: schema as Record<string, unknown>,\n };\n}\n\nfunction isSchema<T extends PlainObject>(value: ShapeInput<T>): value is Schema<T> {\n // Checked structurally rather than via `isPlainObject` so that a class\n // carrying its schema as static members (e.g. `Document`) -- a function,\n // not a plain object -- is recognized as a `Schema<T>` too.\n if (value === null || (typeof value !== \"object\" && typeof value !== \"function\")) {\n return false;\n }\n\n const candidate = value as Record<string, unknown>;\n\n return (\n typeof candidate.validate === \"function\" &&\n typeof candidate.diagnostics === \"function\" &&\n typeof candidate.assert === \"function\"\n );\n}\n\nexport function isPlainObject(value: unknown): value is PlainObject {\n return (\n typeof value === \"object\" &&\n value !== null &&\n !Array.isArray(value) &&\n Object.getPrototypeOf(value) === Object.prototype\n );\n}\n\nfunction diagnosticsFromAjvErrors(\n errors: ErrorObject[] | null | undefined,\n): readonly ValidationDiagnostic[] {\n if (!errors || errors.length === 0) {\n return [{ path: \"/\", message: \"is invalid\" }];\n }\n\n return errors.map((error) => ({\n path: error.instancePath || \"/\",\n message: error.message ?? \"is invalid\",\n }));\n}\n\nfunction formatDiagnostics(diagnostics: readonly ValidationDiagnostic[]): string {\n return diagnostics.map((diagnostic) => `${diagnostic.path} ${diagnostic.message}`).join(\"; \");\n}\n","import { currentRunContext } from \"../../runtime/run-context/run-context-storage.js\";\n\n/**\n * Ambient handle onto the active run's identity and durable key-value store.\n * Backed by AsyncLocalStorage, set once per run by `runWorkflow`; step\n * continuations import this directly rather than receiving it as an argument.\n */\nexport const state = {\n async get<T = unknown>(key: string): Promise<T | undefined> {\n return currentRunContext().state.get<T>(key);\n },\n async getPersisted<T = unknown>(key: string): Promise<T | undefined> {\n return currentRunContext().state.getPersisted<T>(key);\n },\n async set(key: string, value: unknown): Promise<void> {\n const context = currentRunContext();\n await context.state.set(key, value, {\n persist: context.currentStep?.replay?.kind !== \"completed-step\",\n });\n },\n get id(): string {\n return currentRunContext().id;\n },\n get name(): string {\n return currentRunContext().name;\n },\n get path(): string {\n return currentRunContext().path;\n },\n get cwd(): string | undefined {\n return currentRunContext().cwd;\n },\n get executionCwd(): string | undefined {\n return currentRunContext().executionCwd ?? currentRunContext().cwd;\n },\n get isReplayingCompletedStep(): boolean {\n return currentRunContext().currentStep?.replay?.kind === \"completed-step\";\n },\n get projectCwd(): string | undefined {\n return currentRunContext().projectCwd;\n },\n};\n","import type { AgentPrompt } from \"../../contracts/agents/agent-adapter.types.js\";\nimport type { Failure } from \"../../contracts/failures/failure.js\";\nimport type { PlainObject } from \"../../contracts/shapes/shape.types.js\";\nimport type {\n AbsoluteDoneNode,\n AbsoluteFailNode,\n CheckWaitCallback,\n ContinuationArray,\n ContinuationStepConfig,\n DisplayPhase,\n DoneNode,\n DoPhase,\n FailNode,\n ParallelNode,\n ParallelOptions,\n PostContinuation,\n PromptOptions,\n PromptPhase,\n PromptTemplateSource,\n StepConfig,\n StepContextContinuation,\n StepContinuation,\n StepDisplayContent,\n StepErrorContinuation,\n StepFactory,\n StepInvocationOptions,\n StepNode,\n StepPhase,\n TerminalMessageOptions,\n WaitInput,\n WaitOptions,\n WaitPhase,\n WorkflowInvocationNode,\n} from \"../step/continuation.types.js\";\n\n/**\n * The only step-authoring primitive. `.prompt(...)` is optional; when present,\n * the step dispatches to an agent and `.do(...)` receives its structured\n * output. When absent, nothing is dispatched -- `.do(...)` receives the\n * step's input directly and is responsible for the work and the continuation\n * in one function. Either way, `.do(...)` produces a reusable `StepFactory`\n * -- call it with a live input value (`stepA(input)`) to get a `StepNode`.\n * When the inferred input type has no required keys, the argument is\n * optional (`stepA()`) and defaults to `{}`.\n */\ninterface StepBuilder {\n display(\n content?: StepDisplayContent<PlainObject, PlainObject>,\n options?: PlainObject,\n ): StepBuilder;\n wait(wait: WaitInput<PlainObject, PlainObject>): StepBuilder;\n wait<TWaitOutput extends PlainObject = PlainObject>(\n wait: CheckWaitCallback<PlainObject, PlainObject, TWaitOutput>,\n options: WaitOptions<TWaitOutput>,\n ): StepBuilder;\n prompt<TInput extends PlainObject = PlainObject, TOutput extends PlainObject = PlainObject>(\n source: AgentPrompt<TInput> | PromptTemplateSource,\n options?: PromptOptions<TOutput>,\n ): PromptedStepBuilder<TInput, TOutput>;\n do<TInput extends PlainObject = PlainObject>(\n onOutput: StepContextContinuation<TInput, TInput>,\n ): FluentStepFactory<TInput, TInput>;\n do<TInput extends PlainObject = PlainObject>(\n onOutput: StepContinuation<TInput, TInput>,\n ): FluentStepFactory<TInput, TInput>;\n}\n\ninterface PromptedStepBuilder<\n TInput extends PlainObject = PlainObject,\n TOutput extends PlainObject = PlainObject,\n> {\n display(\n content?: StepDisplayContent<TInput, TOutput>,\n options?: PlainObject,\n ): PromptedStepBuilder<TInput, TOutput>;\n wait(wait: WaitInput<TInput, TOutput>): PromptedStepBuilder<TInput, TOutput>;\n wait<TWaitOutput extends PlainObject = PlainObject>(\n wait: CheckWaitCallback<TInput, TOutput, TWaitOutput>,\n options: WaitOptions<TWaitOutput>,\n ): PromptedStepBuilder<TInput, TOutput>;\n do(onOutput: StepContextContinuation<TInput, TOutput>): FluentStepFactory<TInput, TOutput>;\n do(onOutput: StepContinuation<TInput, TOutput>): FluentStepFactory<TInput, TOutput>;\n}\n\ntype FluentStepFactory<\n TInput extends PlainObject = PlainObject,\n TOutput extends PlainObject = PlainObject,\n> = StepFactory<TInput, TOutput> & {\n catch(onError: StepErrorContinuation): FluentStepFactory<TInput, TOutput>;\n display(\n content?: StepDisplayContent<TInput, TOutput>,\n options?: PlainObject,\n ): FluentStepFactory<TInput, TOutput>;\n wait(wait: WaitInput<TInput, TOutput>): FluentStepFactory<TInput, TOutput>;\n wait<TWaitOutput extends PlainObject = PlainObject>(\n wait: CheckWaitCallback<TInput, TOutput, TWaitOutput>,\n options: WaitOptions<TWaitOutput>,\n ): FluentStepFactory<TInput, TOutput>;\n};\n\nexport function step(config: StepConfig): StepBuilder {\n const makeBuilder = (phaseTemplates: readonly StepPhase[] = []): StepBuilder => ({\n display(content, options) {\n return makeBuilder([...phaseTemplates, displayPhase(content, options)]);\n },\n wait(\n wait: WaitInput<PlainObject, PlainObject> | CheckWaitCallback<PlainObject, PlainObject>,\n options?: WaitOptions,\n ) {\n return makeBuilder([...phaseTemplates, waitPhase(wait, options)]);\n },\n prompt<TInput extends PlainObject = PlainObject, TStepOutput extends PlainObject = PlainObject>(\n source: AgentPrompt<TInput> | PromptTemplateSource,\n options?: PromptOptions<TStepOutput>,\n ) {\n assertPromptOptions(options);\n return makePromptedBuilder<TInput, TStepOutput>([\n ...(phaseTemplates as readonly StepPhase<TInput, TStepOutput>[]),\n promptPhase(source, options),\n ]);\n },\n do<TInput extends PlainObject = PlainObject>(onOutput: StepContinuation<TInput, TInput>) {\n return buildFactory<TInput, TInput>(\n [...(phaseTemplates as readonly StepPhase<TInput, TInput>[]), doPhase(onOutput)],\n onOutput,\n );\n },\n });\n\n const makePromptedBuilder = <TInput extends PlainObject, TStepOutput extends PlainObject>(\n phaseTemplates: readonly StepPhase<TInput, TStepOutput>[],\n ): PromptedStepBuilder<TInput, TStepOutput> => ({\n display(content, options) {\n return makePromptedBuilder([...phaseTemplates, displayPhase(content, options)]);\n },\n wait(\n wait: WaitInput<TInput, TStepOutput> | CheckWaitCallback<TInput, TStepOutput>,\n options?: WaitOptions,\n ) {\n return makePromptedBuilder([...phaseTemplates, waitPhase(wait, options)]);\n },\n do(onOutput) {\n return buildFactory([...phaseTemplates, doPhase(onOutput)], onOutput);\n },\n });\n\n const buildFactory = <TInput extends PlainObject, TStepOutput extends PlainObject>(\n phaseTemplates: readonly StepPhase<TInput, TStepOutput>[],\n onOutput: StepContinuation<TInput, TStepOutput> | StepContextContinuation<TInput, TStepOutput>,\n onError?: StepErrorContinuation,\n ): FluentStepFactory<TInput, TStepOutput> => {\n const factory = ((\n input?: TInput,\n options?: StepInvocationOptions,\n ): StepNode<TInput, TStepOutput> => {\n const phases = phaseTemplates.slice();\n const prompt = firstPromptPhase(phases);\n const { branchId: _branchId, ...configOverrides } = options ?? {};\n\n return {\n kind: \"step\",\n config: {\n ...config,\n ...configOverrides,\n ...(prompt ? promptOptionsForConfig(prompt) : {}),\n input: input ?? ({} as TInput),\n } as ContinuationStepConfig<TInput, TStepOutput>,\n phases,\n onOutput: onOutput as StepContinuation<TInput, TStepOutput>,\n onError,\n ...(options === undefined ? {} : { options }),\n };\n }) as FluentStepFactory<TInput, TStepOutput>;\n\n factory.catch = (nextOnError: StepErrorContinuation) =>\n buildFactory(phaseTemplates, onOutput, nextOnError);\n factory.display = (content?: StepDisplayContent<TInput, TStepOutput>, options?: PlainObject) =>\n buildFactory([...phaseTemplates, displayPhase(content, options)], onOutput, onError);\n factory.wait = (\n wait: WaitInput<TInput, TStepOutput> | CheckWaitCallback<TInput, TStepOutput>,\n options?: WaitOptions,\n ) => buildFactory([...phaseTemplates, waitPhase(wait, options)], onOutput, onError);\n\n return factory;\n };\n\n return makeBuilder();\n}\n\nexport function done<TOutput extends PlainObject = PlainObject>(\n output?: TOutput,\n options?: TerminalMessageOptions,\n): DoneNode<TOutput> {\n return {\n kind: \"done\",\n output: output ?? ({} as TOutput),\n ...(options?.message === undefined ? {} : { message: options.message }),\n };\n}\n\nexport function fail(failure: Failure, options?: TerminalMessageOptions): FailNode {\n return {\n kind: \"fail\",\n failure,\n ...(options?.message === undefined ? {} : { message: options.message }),\n };\n}\n\nexport function absoluteDone<TOutput extends PlainObject = PlainObject>(\n output?: TOutput,\n options?: TerminalMessageOptions,\n): AbsoluteDoneNode<TOutput> {\n return {\n kind: \"absoluteDone\",\n output: output ?? ({} as TOutput),\n ...(options?.message === undefined ? {} : { message: options.message }),\n };\n}\n\nexport function absoluteFail(failure: Failure, options?: TerminalMessageOptions): AbsoluteFailNode {\n return {\n kind: \"absoluteFail\",\n failure,\n ...(options?.message === undefined ? {} : { message: options.message }),\n };\n}\n\nexport function parallel<TOutput extends PlainObject = PlainObject>(\n nodes: ContinuationArray,\n options?: ParallelOptions,\n): ParallelNode<TOutput> {\n const makeParallel = (postContinuation?: PostContinuation<TOutput>): ParallelNode<TOutput> => ({\n kind: \"parallel\",\n nodes,\n ...(options === undefined ? {} : { options }),\n ...(postContinuation === undefined ? {} : { postContinuation }),\n post(continuation: PostContinuation<TOutput>) {\n return makeParallel(continuation);\n },\n });\n\n return makeParallel();\n}\n\nexport function isStepNode(value: unknown): value is StepNode {\n return isPlainObject(value) && value.kind === \"step\";\n}\n\nexport function isDoneNode(value: unknown): value is DoneNode {\n return isPlainObject(value) && value.kind === \"done\";\n}\n\nexport function isFailNode(value: unknown): value is FailNode {\n return isPlainObject(value) && value.kind === \"fail\";\n}\n\nexport function isWorkflowInvocationNode(value: unknown): value is WorkflowInvocationNode {\n return isPlainObject(value) && value.kind === \"workflowInvocation\";\n}\n\nexport function isParallelNode(value: unknown): value is ParallelNode {\n return isPlainObject(value) && value.kind === \"parallel\" && Array.isArray(value.nodes);\n}\n\nexport function isAbsoluteDoneNode(value: unknown): value is AbsoluteDoneNode {\n return isPlainObject(value) && value.kind === \"absoluteDone\";\n}\n\nexport function isAbsoluteFailNode(value: unknown): value is AbsoluteFailNode {\n return isPlainObject(value) && value.kind === \"absoluteFail\";\n}\n\n/** Returns a step's ordered phases, synthesizing phases for legacy StepNode-shaped objects. */\nexport function getStepPhases<\n TInput extends PlainObject = PlainObject,\n TOutput extends PlainObject = PlainObject,\n>(node: StepNode<TInput, TOutput>): readonly StepPhase<TInput, TOutput>[] {\n if (Array.isArray(node.phases)) {\n return node.phases;\n }\n\n const phases: StepPhase<TInput, TOutput>[] = [];\n if (node.config.prompt !== undefined) {\n phases.push(\n promptPhase(node.config.prompt, {\n ...(node.config.output === undefined ? {} : { output: node.config.output }),\n ...(node.config.agent === undefined ? {} : { agent: node.config.agent }),\n ...(node.config.mode === undefined ? {} : { mode: node.config.mode }),\n ...(node.config.adapter === undefined ? {} : { adapter: node.config.adapter }),\n ...(node.config.maxSubPrompts === undefined\n ? {}\n : { maxSubPrompts: node.config.maxSubPrompts }),\n }),\n );\n }\n phases.push(doPhase(node.onOutput));\n return phases;\n}\n\nexport function hasPromptPhase(node: StepNode): boolean {\n return getStepPhases(node).some((phase) => phase.kind === \"prompt\");\n}\n\nexport function firstPromptPhase(phases: readonly StepPhase[]): PromptPhase | undefined {\n return phases.find((phase): phase is PromptPhase => phase.kind === \"prompt\");\n}\n\nfunction displayPhase<TInput extends PlainObject, TOutput extends PlainObject>(\n content?: StepDisplayContent<TInput, TOutput>,\n options?: PlainObject,\n): DisplayPhase<TInput, TOutput> {\n return {\n kind: \"display\",\n ...(content === undefined ? {} : { content }),\n ...(options === undefined ? {} : { options }),\n };\n}\n\nfunction waitPhase<TInput extends PlainObject, TOutput extends PlainObject>(\n wait: WaitInput<TInput, TOutput> | CheckWaitCallback<TInput, TOutput>,\n options?: WaitOptions,\n): WaitPhase<TInput, TOutput> {\n return {\n kind: \"wait\",\n wait,\n ...(options === undefined ? {} : { options }),\n };\n}\n\nfunction promptPhase<TInput extends PlainObject, TOutput extends PlainObject>(\n prompt: AgentPrompt<TInput> | PromptTemplateSource,\n options?: PromptOptions<TOutput>,\n): PromptPhase<TInput, TOutput> {\n return {\n kind: \"prompt\",\n ...options,\n prompt,\n };\n}\n\nfunction doPhase<TInput extends PlainObject, TOutput extends PlainObject>(\n onOutput: StepContinuation<TInput, TOutput> | StepContextContinuation<TInput, TOutput>,\n): DoPhase<TInput, TOutput> {\n return { kind: \"do\", onOutput: onOutput as StepContinuation<TInput, TOutput> };\n}\n\nfunction promptOptionsForConfig<TInput extends PlainObject, TOutput extends PlainObject>(\n phase: PromptPhase<TInput, TOutput>,\n): Omit<PromptPhase<TInput, TOutput>, \"kind\"> {\n const { kind: _kind, ...options } = phase;\n return options;\n}\n\nfunction assertPromptOptions(value: unknown): void {\n if (hasRetryOption(value)) {\n throw new TypeError(\"Retry config belongs on step(...), not .prompt(...) options.\");\n }\n\n if (hasTimeoutOption(value)) {\n throw new TypeError(\"Timeout config belongs on step(...), not .prompt(...) options.\");\n }\n}\n\nfunction hasRetryOption(value: unknown): boolean {\n return isPlainObject(value) && \"retry\" in value;\n}\n\nfunction hasTimeoutOption(value: unknown): boolean {\n return isPlainObject(value) && \"timeout\" in value;\n}\n\nfunction isPlainObject(value: unknown): value is PlainObject {\n return (\n typeof value === \"object\" &&\n value !== null &&\n !Array.isArray(value) &&\n Object.getPrototypeOf(value) === Object.prototype\n );\n}\n","import { mkdir, writeFile } from \"node:fs/promises\";\n\nimport { runAgentStep } from \"../../agent-execution/adapter-agent/run-adapter-agent-step/run-adapter-agent-step.js\";\nimport {\n resolvePromptSource,\n resolveWorkflowAgentRole,\n} from \"../../agent-execution/dispatch-agent-step/dispatch-agent-step.js\";\nimport { runWorkingAgentCommand } from \"../../agent-execution/working-agent/run-working-agent-command.js\";\nimport { normalizeShape } from \"../../authoring/shape/json-schema.js\";\nimport type {\n PromptTemplateSource,\n SubPromptOptions,\n} from \"../../authoring/step/continuation.types.js\";\nimport type { AgentPrompt } from \"../../contracts/agents/agent-adapter.types.js\";\nimport { TrailStepFailureError } from \"../../contracts/failures/failure.js\";\nimport type { PlainObject } from \"../../contracts/shapes/shape.types.js\";\nimport { createEvent } from \"../events/create-run-event.js\";\nimport { runContextStorage } from \"../run-context/run-context-storage.js\";\nimport { resolveSubPromptArtifactPaths } from \"./sub-prompt-artifacts.js\";\nimport {\n emitSubPromptFailed,\n maxSubPromptsGuardError,\n subPromptFailureError,\n throwMissingSubPromptAgentConfig,\n} from \"./sub-prompt-failures.js\";\nimport { fingerprintSubPrompt } from \"./sub-prompt-fingerprint.js\";\nimport { findCompletedSubPromptEvent } from \"./sub-prompt-replay.js\";\n\nexport function resolveMaxSubPrompts(value: unknown): number {\n if (value === undefined) {\n return 25;\n }\n\n if (Number.isInteger(value) && typeof value === \"number\" && value > 0) {\n return value;\n }\n\n throw new TrailStepFailureError({\n code: \"invalid_max_sub_prompts\",\n message: \"maxSubPrompts must be a positive integer.\",\n });\n}\n\nexport async function runSubPrompt<\n TInput extends PlainObject = PlainObject,\n TOutput extends PlainObject = PlainObject,\n>(\n source: AgentPrompt<TInput> | PromptTemplateSource,\n options: SubPromptOptions<TOutput>,\n input?: TInput,\n): Promise<TOutput> {\n const resolvedInput = (input ?? {}) as TInput;\n const context = runContextStorage.getStore();\n if (!context?.currentStep) {\n throw new TrailStepFailureError({\n code: \"sub_prompt_outside_step_context\",\n message: \"subPrompt requires an active TrailStep step run context.\",\n });\n }\n\n if (!context.workflowId || !context.workflowAgents || !context.cwd || !context.emit) {\n throw new TrailStepFailureError({\n code: \"sub_prompt_context_unavailable\",\n message: \"subPrompt requires a full active TrailStep step run context.\",\n });\n }\n\n const parentStep = context.currentStep;\n if (options.output === undefined) {\n throw new TrailStepFailureError({\n code: \"sub_prompt_output_required\",\n message: `subPrompt in step ${parentStep.id} with a prompt requires an output shape`,\n });\n }\n\n const outputSchema = normalizeShape(options.output);\n const ordinal = parentStep.nextSubPromptIndex();\n const maxSubPrompts = resolveMaxSubPrompts(options.maxSubPrompts ?? parentStep.maxSubPrompts);\n if (ordinal > maxSubPrompts) {\n const failureError = maxSubPromptsGuardError(maxSubPrompts);\n await emitSubPromptFailed({\n context,\n parentStepId: parentStep.id,\n ordinal,\n failure: failureError.failure,\n });\n throw failureError;\n }\n\n const renderedPrompt = await resolvePromptSource(\n source,\n resolvedInput,\n context.projectCwd ?? context.cwd,\n );\n const fingerprint = fingerprintSubPrompt({ input: resolvedInput, prompt: renderedPrompt });\n const cachedEvent = findCompletedSubPromptEvent(\n context.events?.() ?? [],\n parentStep.id,\n ordinal,\n fingerprint,\n );\n if (cachedEvent) {\n return outputSchema.assert(cachedEvent.payload.output, \"subPrompt output\");\n }\n\n const artifactPaths = resolveSubPromptArtifactPaths({\n runDir: context.path,\n stepDir: parentStep.dir,\n ordinal,\n fingerprint,\n });\n\n await mkdir(artifactPaths.subPromptDir, { recursive: true });\n await writeFile(artifactPaths.promptFile, renderedPrompt, \"utf8\");\n\n const resolvedRole = resolveWorkflowAgentRole({\n agent: options.agent,\n workflowAgents: context.workflowAgents,\n workflowId: context.workflowId,\n stepId: parentStep.id,\n });\n\n await context.emit(\n createEvent({\n runId: context.id,\n workflowId: context.workflowId,\n stepId: parentStep.id,\n type: \"subPrompt.started\",\n payload: {\n parentStepId: parentStep.id,\n ordinal,\n fingerprint,\n artifactPaths: artifactPaths.runRelative,\n },\n }),\n );\n\n try {\n const agentStep = {\n kind: \"agent\" as const,\n id: `${parentStep.id}.subPrompt.${ordinal}`,\n output: outputSchema,\n prompt: renderedPrompt,\n requirements: resolvedRole.role,\n adapter: options.adapter,\n };\n\n if (!context.trailstepConfig && options.adapter === undefined) {\n throwMissingSubPromptAgentConfig({\n workflowId: context.workflowId,\n parentStepId: parentStep.id,\n subPromptId: agentStep.id,\n agent: resolvedRole.roleName,\n });\n }\n\n const rawOutput =\n context.trailstepConfig && options.adapter === undefined\n ? await runWorkingAgentCommand({\n config: context.trailstepConfig,\n workflowId: context.workflowId,\n roleName: resolvedRole.roleName,\n role: resolvedRole.role,\n step: agentStep,\n renderedPrompt,\n runDir: context.path,\n cwd: context.cwd,\n runner: context.workingAgentProcessRunner,\n providerWorkingRunner: context.providerWorkingRunner,\n stepIndex: ordinal,\n files: {\n stepDir: artifactPaths.subPromptDir,\n promptFile: artifactPaths.promptFile,\n outputFile: artifactPaths.outputFile,\n usageFile: artifactPaths.usageFile,\n },\n })\n : await runAgentStep({\n step: agentStep,\n input: resolvedInput,\n onToolCall: async (toolCall) => {\n await context.emit?.(\n createEvent({\n runId: context.id,\n workflowId: context.workflowId ?? \"\",\n stepId: parentStep.id,\n type: \"agent.toolCall\",\n payload: { ...toolCall },\n }),\n );\n },\n });\n\n const output = outputSchema.assert(rawOutput, \"subPrompt output\");\n await writeFile(artifactPaths.outputFile, `${JSON.stringify(output, null, 2)}\\n`, \"utf8\");\n\n await context.emit(\n createEvent({\n runId: context.id,\n workflowId: context.workflowId,\n stepId: parentStep.id,\n type: \"subPrompt.completed\",\n payload: {\n parentStepId: parentStep.id,\n ordinal,\n fingerprint,\n output,\n artifactPaths: artifactPaths.runRelative,\n },\n }),\n );\n\n return output;\n } catch (error) {\n const failureError = subPromptFailureError(error);\n await emitSubPromptFailed({\n context,\n parentStepId: parentStep.id,\n ordinal,\n fingerprint,\n artifactPaths: artifactPaths.runRelative,\n failure: failureError.failure,\n });\n throw failureError;\n }\n}\n","import type { AgentStepRequestConfig } from \"../../../authoring/step/agent-step.types.js\";\nimport type {\n AgentAdapter,\n AgentAdapterSelection,\n AgentPrompt,\n AgentTool,\n} from \"../../../contracts/agents/agent-adapter.types.js\";\nimport type { AgentModelTarget } from \"../../../contracts/agents/agent-role.types.js\";\nimport { TrailStepFailureError } from \"../../../contracts/failures/failure.js\";\nimport type { PlainObject, Schema } from \"../../../contracts/shapes/shape.types.js\";\n\nconst PROVIDER_NEUTRAL_ADAPTER_KEY = \"custom\";\nconst PROVIDER_NEUTRAL_MODEL = \"configured-agent\";\n\nexport interface AgentToolCallEvent {\n readonly name: string;\n readonly input: PlainObject;\n readonly output: PlainObject;\n}\n\nexport interface RunAgentStepOptions<\n TInput extends PlainObject = PlainObject,\n TOutput extends PlainObject = PlainObject,\n> {\n readonly step: AgentStepRequestConfig<TInput, TOutput>;\n readonly input: TInput;\n readonly onToolCall?: (event: AgentToolCallEvent) => void | Promise<void>;\n}\n\nexport async function runAgentStep<\n TInput extends PlainObject = PlainObject,\n TOutput extends PlainObject = PlainObject,\n>(options: RunAgentStepOptions<TInput, TOutput>): Promise<PlainObject> {\n const model = resolveAgentRequirements(options.step.requirements);\n const adapter = resolveAgentAdapter(options.step.adapter);\n let submittedOutput: PlainObject | undefined;\n\n const tools: AgentTool<TOutput>[] = [\n createSubmitOutputTool(options.step.output, async (output) => {\n options.step.output.assert(output, `agent step ${options.step.id} submit_output`);\n submittedOutput = output;\n await options.onToolCall?.({\n name: \"submit_output\",\n input: output,\n output: { accepted: true },\n });\n }),\n ];\n\n const prompt = renderAgentPrompt(options.step.prompt, options.input);\n\n await adapter({\n messages: [{ role: \"user\", content: prompt }],\n tools,\n requirements: options.step.requirements,\n model,\n step: options.step,\n input: options.input,\n });\n\n if (submittedOutput === undefined) {\n throw new TrailStepFailureError({\n code: \"agent_output_missing\",\n message: `Agent step ${options.step.id} did not call submit_output.`,\n });\n }\n\n return submittedOutput;\n}\n\nexport function renderAgentPrompt<TInput extends PlainObject>(\n prompt: AgentPrompt<TInput>,\n input: TInput,\n): string {\n return typeof prompt === \"function\" ? prompt({ input }) : prompt;\n}\n\nexport function resolveAgentRequirements(\n requirements: AgentStepRequestConfig[\"requirements\"],\n): AgentModelTarget {\n return {\n adapterKey: PROVIDER_NEUTRAL_ADAPTER_KEY,\n model: requirements.name ?? requirements.size ?? PROVIDER_NEUTRAL_MODEL,\n };\n}\n\nfunction resolveAgentAdapter<TInput extends PlainObject, TOutput extends PlainObject = PlainObject>(\n selection: AgentAdapterSelection<TInput, TOutput> | undefined,\n): AgentAdapter<TInput, TOutput> {\n if (typeof selection === \"function\") {\n return selection;\n }\n\n if (typeof selection === \"object\" && selection !== null) {\n return (request) => selection.runAgentStep(request);\n }\n\n throw new TrailStepFailureError({\n code: \"agent_adapter_unavailable\",\n message:\n \"Agent steps that do not use a configured command runner require a custom adapter function or adapter object.\",\n });\n}\n\nfunction createSubmitOutputTool<TOutput extends PlainObject>(\n schema: Schema<TOutput>,\n onOutput: (output: TOutput) => void | Promise<void>,\n): AgentTool<TOutput> {\n return {\n name: \"submit_output\",\n description: \"Submit the typed output for this TrailStep agent step.\",\n schema,\n async call(input) {\n await onOutput(input);\n },\n };\n}\n","import { readFile } from \"node:fs/promises\";\nimport { resolve } from \"node:path\";\n\nimport type { TrailStepConfig } from \"../../agent-targeting/targeting.types.js\";\nimport type {\n ContinuationStepConfig,\n PromptTemplateSource,\n} from \"../../authoring/step/continuation.types.js\";\nimport type { AgentPrompt } from \"../../contracts/agents/agent-adapter.types.js\";\nimport type { WorkflowAgentRole } from \"../../contracts/agents/agent-role.types.js\";\nimport { TrailStepFailureError } from \"../../contracts/failures/failure.js\";\nimport type { PlainObject, Schema } from \"../../contracts/shapes/shape.types.js\";\nimport { resolveStepArtifactPaths } from \"../../runtime/artifacts/step-artifacts.js\";\nimport { createEvent } from \"../../runtime/events/create-run-event.js\";\nimport type { Event, RunWorkflowOptions } from \"../../runtime/run-workflow/run-workflow.types.js\";\nimport {\n renderAgentPrompt,\n runAgentStep,\n} from \"../adapter-agent/run-adapter-agent-step/run-adapter-agent-step.js\";\nimport { runInteractiveAgentCommand } from \"../interactive-agent/run-interactive-agent-command.js\";\nimport { runWorkingAgentCommand } from \"../working-agent/run-working-agent-command.js\";\n\n/**\n * Runs a prompt phase's agent dispatch: resolves the workflow agent role,\n * renders the prompt, and executes it in adapter, working, or interactive\n * mode. Steps with no prompt phase are never dispatched at all; their do\n * phase receives the step input directly.\n */\nexport async function dispatchAgentStep(options: {\n readonly config: ContinuationStepConfig & {\n readonly prompt: NonNullable<ContinuationStepConfig[\"prompt\"]>;\n };\n readonly outputSchema: Schema;\n readonly interactiveOutputMode: \"session-file\" | \"json\";\n readonly runId: string;\n readonly workflowId: string;\n readonly emit: (event: Event) => Promise<void>;\n readonly workflowAgents: Readonly<Record<string, WorkflowAgentRole>>;\n readonly runDir: string;\n readonly projectCwd: string;\n readonly cwd: string;\n readonly trailstepConfig: TrailStepConfig | undefined;\n readonly workingAgentProcessRunner: RunWorkflowOptions[\"workingAgentProcessRunner\"];\n readonly providerWorkingRunner: RunWorkflowOptions[\"providerWorkingRunner\"];\n readonly processRunner: RunWorkflowOptions[\"processRunner\"];\n readonly stepIndex: number;\n readonly signal?: AbortSignal;\n}): Promise<PlainObject> {\n const { config, outputSchema } = options;\n\n const resolvedRole = resolveWorkflowAgentRole({\n agent: config.agent,\n workflowAgents: options.workflowAgents,\n workflowId: options.workflowId,\n stepId: config.id,\n });\n\n const renderedPrompt = await resolvePromptSource(config.prompt, config.input, options.projectCwd);\n const agentMode = config.mode ?? \"working\";\n\n const agentStep = {\n kind: \"agent\" as const,\n id: config.id,\n output: outputSchema,\n prompt: renderedPrompt,\n requirements: resolvedRole.role,\n adapter: config.adapter,\n };\n\n if (!options.trailstepConfig && config.adapter === undefined) {\n throwMissingAgentConfig({\n workflowId: options.workflowId,\n stepId: config.id,\n agent: resolvedRole.roleName,\n mode: agentMode,\n });\n }\n\n if (options.trailstepConfig && agentMode === \"interactive\") {\n await options.emit(\n createEvent({\n runId: options.runId,\n workflowId: options.workflowId,\n stepId: config.id,\n type: \"interactive.sessionStarted\",\n payload: { roleName: resolvedRole.roleName, stepIndex: options.stepIndex },\n }),\n );\n const artifactPaths = resolveStepArtifactPaths({\n runDir: options.runDir,\n stepId: config.id,\n stepIndex: options.stepIndex,\n });\n const interactiveResult = await runInteractiveAgentCommand({\n config: options.trailstepConfig,\n workflowId: options.workflowId,\n roleName: resolvedRole.roleName,\n role: resolvedRole.role,\n stepId: config.id,\n renderedPrompt,\n runDir: options.runDir,\n cwd: options.cwd,\n runner: options.processRunner,\n outputSchema,\n outputMode: options.interactiveOutputMode,\n artifactPaths,\n signal: options.signal,\n });\n await options.emit(\n createEvent({\n runId: options.runId,\n workflowId: options.workflowId,\n stepId: config.id,\n type: \"interactive.sessionCompleted\",\n payload: {\n exitCode: interactiveResult.exitCode,\n outputMode: options.interactiveOutputMode,\n stepDir: artifactPaths.runRelativeStepDir,\n },\n }),\n );\n return interactiveResult.output;\n }\n\n return options.trailstepConfig && agentMode === \"working\"\n ? await runWorkingAgentCommand({\n config: options.trailstepConfig,\n workflowId: options.workflowId,\n roleName: resolvedRole.roleName,\n role: resolvedRole.role,\n step: agentStep,\n renderedPrompt,\n runDir: options.runDir,\n cwd: options.cwd,\n runner: options.workingAgentProcessRunner,\n providerWorkingRunner: options.providerWorkingRunner,\n onTargetAttempt: async (target) => {\n await options.emit(\n createEvent({\n runId: options.runId,\n workflowId: options.workflowId,\n stepId: config.id,\n type: \"step.progress\",\n payload: {\n message: `agent ${resolvedRole.roleName} via ${target.provider}${\n target.model === undefined ? \"\" : ` ${target.model}`\n }`,\n },\n }),\n );\n },\n stepIndex: options.stepIndex,\n signal: options.signal,\n })\n : await runAgentStep({\n step: agentStep,\n input: config.input,\n onToolCall: async (toolCall) => {\n await options.emit(\n createEvent({\n runId: options.runId,\n workflowId: options.workflowId,\n stepId: config.id,\n type: \"agent.toolCall\",\n payload: { ...toolCall },\n }),\n );\n },\n });\n}\n\n/**\n * Resolves a step's prompt source to a rendered string. A `promptTemplate(...)`\n * source is read from disk relative to the workflow/project `cwd`; a thrown/rejected\n * read propagates up through the same try/catch that already wraps step\n * dispatch, so an unreadable file becomes a normal step failure. Any other\n * source (string or callback) renders synchronously via `renderAgentPrompt`.\n */\nexport async function resolvePromptSource<TInput extends PlainObject>(\n source: AgentPrompt<TInput> | PromptTemplateSource,\n input: TInput,\n cwd: string,\n): Promise<string> {\n if (isPromptTemplateSource(source)) {\n return await readFile(resolve(cwd, source.path), \"utf8\");\n }\n\n return renderAgentPrompt(source, input);\n}\n\nfunction isPromptTemplateSource(\n source: AgentPrompt<PlainObject> | PromptTemplateSource,\n): source is PromptTemplateSource {\n return typeof source === \"object\" && source !== null && source.kind === \"promptTemplate\";\n}\n\nfunction throwMissingAgentConfig(options: {\n readonly workflowId: string;\n readonly stepId: string;\n readonly agent: string;\n readonly mode: \"working\" | \"interactive\";\n}): never {\n throw new TrailStepFailureError({\n code: \"missing_agent_config\",\n message: `Missing .trailstep/config.json: workflow ${options.workflowId} step ${options.stepId} needs configured ${options.mode} agent '${options.agent}'.`,\n details: {\n workflowId: options.workflowId,\n stepId: options.stepId,\n agent: options.agent,\n mode: options.mode,\n },\n });\n}\n\nconst DEFAULT_AGENT_ROLE_NAME = \"default\";\n\nconst BUILTIN_DEFAULT_AGENT_ROLE: WorkflowAgentRole = { size: \"default\" };\n\n/**\n * A step's `.agent` is optional. With none given, falls back to\n * `workflow.agents.default` if the workflow declares one, else a builtin\n * `{ size: \"default\" }` role — which `resolveAgentTargets` in turn resolves\n * against `.trailstep/config.json`'s unified `agents.default` mapping. An explicit `.agent(...)` naming an undeclared\n * role is still a hard error (typo protection).\n */\nexport function resolveWorkflowAgentRole(options: {\n readonly agent: string | undefined;\n readonly workflowAgents: Readonly<Record<string, WorkflowAgentRole>>;\n readonly workflowId: string;\n readonly stepId: string;\n}): { readonly role: WorkflowAgentRole; readonly roleName: string } {\n const roleName = options.agent ?? DEFAULT_AGENT_ROLE_NAME;\n const role = options.workflowAgents[roleName];\n\n if (role) {\n return { role, roleName };\n }\n\n if (options.agent === undefined) {\n return { role: BUILTIN_DEFAULT_AGENT_ROLE, roleName: DEFAULT_AGENT_ROLE_NAME };\n }\n\n throw new TrailStepFailureError({\n code: \"agent_role_unknown\",\n message: `Step ${options.stepId} references unknown agent role '${options.agent}' in workflow ${options.workflowId}. Declare workflow.agents.${options.agent} before referencing it with step agent.`,\n details: {\n workflowId: options.workflowId,\n stepId: options.stepId,\n agent: options.agent,\n declaredAgents: Object.keys(options.workflowAgents),\n },\n });\n}\n","import { join } from \"node:path\";\n\nexport interface WaitArtifactPaths {\n readonly requestFile: string;\n readonly answerFile: string;\n}\n\nexport interface ResolvedWaitArtifactPaths {\n readonly waitDir: string;\n readonly requestFile: string;\n readonly answerFile: string;\n readonly runRelative: WaitArtifactPaths;\n}\n\nexport interface StepArtifactPaths {\n readonly artifactStepId: string;\n readonly stepDir: string;\n readonly promptFile: string;\n readonly outputFile: string;\n readonly usageFile: string;\n readonly interactiveFile: string;\n readonly sessionDescriptionFile: string;\n readonly runRelativeStepDir: string;\n readonly runRelativeSessionDescriptionFile: string;\n}\n\nexport function resolveStepArtifactPaths(options: {\n readonly runDir: string;\n readonly stepId: string;\n readonly stepIndex: number;\n}): StepArtifactPaths {\n const artifactStepId = `${String(options.stepIndex).padStart(4, \"0\")}-${sanitizeStepId(\n options.stepId,\n )}`;\n const runRelativeStepDir = `steps/${artifactStepId}`;\n const runRelativeSessionDescriptionFile = `${runRelativeStepDir}/session-description.md`;\n const stepDir = join(options.runDir, \"steps\", artifactStepId);\n\n return {\n artifactStepId,\n stepDir,\n promptFile: join(stepDir, \"prompt.txt\"),\n outputFile: join(stepDir, \"output.json\"),\n usageFile: join(stepDir, \"usage.json\"),\n interactiveFile: join(stepDir, \"interactive.json\"),\n sessionDescriptionFile: join(stepDir, \"session-description.md\"),\n runRelativeStepDir,\n runRelativeSessionDescriptionFile,\n };\n}\n\nexport function resolveWaitArtifactPaths(options: {\n readonly runDir: string;\n readonly stepArtifactId: string;\n readonly waitId: string;\n}): ResolvedWaitArtifactPaths {\n const runRelativeWaitDir = `steps/${options.stepArtifactId}/waits/${options.waitId}`;\n const waitDir = join(options.runDir, \"steps\", options.stepArtifactId, \"waits\", options.waitId);\n\n return {\n waitDir,\n requestFile: join(waitDir, \"request.json\"),\n answerFile: join(waitDir, \"answer.json\"),\n runRelative: {\n requestFile: `${runRelativeWaitDir}/request.json`,\n answerFile: `${runRelativeWaitDir}/answer.json`,\n },\n };\n}\n\nfunction sanitizeStepId(stepId: string): string {\n return (\n stepId\n .trim()\n .toLowerCase()\n .replace(/[^a-z0-9_-]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\") || \"step\"\n );\n}\n","import { spawn } from \"node:child_process\";\nimport { mkdir, writeFile } from \"node:fs/promises\";\nimport { dirname } from \"node:path\";\nimport { resolveAgentTargets } from \"../../agent-targeting/resolve-agent-targets/resolve-agent-targets.js\";\nimport type {\n TrailStepAgentTarget,\n TrailStepConfig,\n} from \"../../agent-targeting/targeting.types.js\";\nimport type { WorkflowAgentRole } from \"../../contracts/agents/agent-role.types.js\";\nimport { TrailStepFailureError } from \"../../contracts/failures/failure.js\";\nimport type { PlainObject, Schema } from \"../../contracts/shapes/shape.types.js\";\nimport type { StepArtifactPaths } from \"../../runtime/artifacts/step-artifacts.js\";\nimport {\n isInteractiveCompleted,\n readCompletedInteractiveOutput,\n waitForInteractiveCompletion,\n} from \"../../runtime/interactive-session/interactive-session-protocol.js\";\nimport type {\n InteractiveProcessResult,\n InteractiveProcessRunner,\n} from \"../../runtime/run-workflow/run-workflow.types.js\";\nimport { renderCustomProviderArgs } from \"../custom-provider/render-custom-provider-args.js\";\n\nexport async function runInteractiveAgentCommand(options: {\n readonly config: TrailStepConfig;\n readonly workflowId: string;\n readonly roleName: string;\n readonly role: WorkflowAgentRole;\n readonly stepId: string;\n readonly renderedPrompt: string;\n readonly runDir: string;\n readonly cwd?: string;\n readonly outputSchema: Schema;\n readonly artifactPaths: StepArtifactPaths;\n readonly outputMode: \"session-file\" | \"json\";\n readonly runner?: InteractiveProcessRunner;\n readonly signal?: AbortSignal;\n}): Promise<{ readonly exitCode: number; readonly output: PlainObject }> {\n const [target] = resolveAgentTargets({\n config: options.config,\n workflowId: options.workflowId,\n roleName: options.roleName,\n roleSize: options.role.size,\n });\n\n if (!target) {\n throw new TrailStepFailureError({\n code: \"agent_targets_unavailable\",\n message: `No interactive agent targets found for role ${options.roleName} with size ${options.role.size} in workflow ${options.workflowId}.`,\n });\n }\n\n return await runInteractiveAgentTarget({ ...options, target });\n}\n\nasync function runInteractiveAgentTarget(options: {\n readonly config: TrailStepConfig;\n readonly workflowId: string;\n readonly roleName: string;\n readonly role: WorkflowAgentRole;\n readonly stepId: string;\n readonly renderedPrompt: string;\n readonly runDir: string;\n readonly cwd?: string;\n readonly outputSchema: Schema;\n readonly artifactPaths: StepArtifactPaths;\n readonly outputMode: \"session-file\" | \"json\";\n readonly runner?: InteractiveProcessRunner;\n readonly target: TrailStepAgentTarget;\n readonly signal?: AbortSignal;\n}): Promise<{ readonly exitCode: number; readonly output: PlainObject }> {\n const files = options.artifactPaths;\n const thinking = options.target.thinking ?? options.role.thinking;\n await prepareInteractiveArtifacts({\n files,\n runDir: options.runDir,\n stepId: options.stepId,\n outputSchema: options.outputSchema,\n outputMode: options.outputMode,\n });\n const prompt = buildInteractivePrompt({\n renderedPrompt: options.renderedPrompt,\n files,\n outputSchema: options.outputSchema,\n outputMode: options.outputMode,\n });\n const env = { ...definedProcessEnv(), TRAILSTEP_INTERACTIVE_FILE: files.interactiveFile };\n const executionCwd = options.cwd ?? files.stepDir;\n\n const abortController = new AbortController();\n options.signal?.addEventListener(\"abort\", () => abortController.abort(), { once: true });\n\n const manifestProvider = options.config.providers?.[options.target.provider];\n if (manifestProvider !== undefined && manifestProvider.source.type !== \"legacy-custom-provider\") {\n const interactive = manifestProvider.manifest.interactive;\n if (!interactive.supported || interactive.command === undefined) {\n throw new TrailStepFailureError({\n code: \"agent_provider_interactive_unsupported\",\n message: `Provider '${options.target.provider}' cannot run interactive agent steps because its provider manifest does not declare supported interactive execution.`,\n details: { provider: options.target.provider },\n });\n }\n\n const command = interactive.command;\n const args = renderCustomProviderArgs({\n argv: options.target.args ?? [\"{{prompt}}\"],\n values: {\n prompt,\n promptFile: files.promptFile,\n ...(options.target.model === undefined ? {} : { model: options.target.model }),\n ...(thinking === undefined ? {} : { thinking }),\n },\n errorCode: \"interactive_command_invalid\",\n commandDescription: \"Manifest interactive provider command\",\n });\n\n if (args.includes(files.promptFile)) {\n await mkdir(dirname(files.promptFile), { recursive: true });\n await writeFile(files.promptFile, prompt, \"utf8\");\n }\n\n return await runProcessUntilExitOrCompletion({\n stepId: options.stepId,\n target: options.target.provider,\n interactiveFile: files.interactiveFile,\n abortController,\n readOutput: async () => await readCompletedOutput(options),\n mapSpawnError: (error) =>\n new TrailStepFailureError({\n code: \"interactive_command_spawn_error\",\n message: `Interactive agent step ${options.stepId} could not start provider '${options.target.provider}'.`,\n details: {\n provider: options.target.provider,\n ...(options.target.model === undefined ? {} : { model: options.target.model }),\n cause: error instanceof Error ? error.message : String(error),\n },\n }),\n runProcess: async () =>\n await (options.runner ?? spawnInteractiveProcess)({\n command,\n args,\n cwd: executionCwd,\n shell: false,\n stdio: \"inherit\",\n env,\n signal: abortController.signal,\n }),\n });\n }\n\n const agentConfig = options.config.customProviders[options.target.provider];\n if (!agentConfig) {\n throw new TrailStepFailureError({\n code: \"agent_provider_unavailable\",\n message: `Interactive agent target '${options.target.provider}' does not reference a configured custom agent.`,\n details: { provider: options.target.provider },\n });\n }\n\n if (!agentConfig.interactiveArgs) {\n throw new TrailStepFailureError({\n code: \"agent_provider_interactive_unsupported\",\n message: `Custom provider '${options.target.provider}' cannot run interactive agent steps because customProviders.${options.target.provider}.interactiveArgs is not declared.`,\n details: { provider: options.target.provider },\n });\n }\n\n const args = renderCustomProviderArgs({\n argv: options.target.args ?? agentConfig.interactiveArgs,\n values: {\n prompt,\n promptFile: files.promptFile,\n ...(options.target.model === undefined ? {} : { model: options.target.model }),\n ...(thinking === undefined ? {} : { thinking }),\n },\n errorCode: \"interactive_command_invalid\",\n commandDescription: \"Interactive agent command\",\n });\n\n if (args.includes(files.promptFile)) {\n await mkdir(dirname(files.promptFile), { recursive: true });\n await writeFile(files.promptFile, prompt, \"utf8\");\n }\n\n return await runProcessUntilExitOrCompletion({\n stepId: options.stepId,\n target: options.target.provider,\n interactiveFile: files.interactiveFile,\n abortController,\n readOutput: async () => await readCompletedOutput(options),\n mapSpawnError: (error) =>\n new TrailStepFailureError({\n code: \"interactive_command_spawn_error\",\n message: `Interactive agent step ${options.stepId} could not start target '${options.target.provider}'.`,\n details: {\n target: options.target.provider,\n ...(options.target.model === undefined ? {} : { model: options.target.model }),\n cause: error instanceof Error ? error.message : String(error),\n },\n }),\n runProcess: async () =>\n await (options.runner ?? spawnInteractiveProcess)({\n command: agentConfig.binary,\n args,\n cwd: executionCwd,\n shell: false,\n stdio: \"inherit\",\n env,\n signal: abortController.signal,\n }),\n });\n}\n\nfunction definedProcessEnv(): Record<string, string> {\n return Object.fromEntries(\n Object.entries(process.env).filter(\n (entry): entry is [string, string] => entry[1] !== undefined,\n ),\n );\n}\n\nasync function runProcessUntilExitOrCompletion(options: {\n readonly stepId: string;\n readonly target: string;\n readonly interactiveFile: string;\n readonly abortController: AbortController;\n readonly runProcess: () => Promise<InteractiveProcessResult>;\n readonly readOutput: () => Promise<PlainObject>;\n readonly mapSpawnError?: (error: unknown) => TrailStepFailureError;\n}): Promise<{ readonly exitCode: number; readonly output: PlainObject }> {\n const processPromise = options.runProcess();\n void processPromise.catch(() => undefined);\n const watcherAbortController = new AbortController();\n\n const winner = await Promise.race<\n | { readonly type: \"completed\" }\n | { readonly type: \"process\"; readonly result: InteractiveProcessResult }\n | { readonly type: \"processError\"; readonly error: unknown }\n >([\n processPromise.then(\n (result) => ({ type: \"process\", result }) as const,\n (error) => ({ type: \"processError\", error }) as const,\n ),\n waitForInteractiveCompletion(options.interactiveFile, watcherAbortController.signal).then(\n () => ({ type: \"completed\" }) as const,\n ),\n ]);\n\n watcherAbortController.abort();\n\n if (winner.type === \"processError\") {\n throw options.mapSpawnError?.(winner.error) ?? winner.error;\n }\n\n if (winner.type === \"process\") {\n if (await isInteractiveCompleted(options.interactiveFile)) {\n return { exitCode: 0, output: await options.readOutput() };\n }\n\n if (winner.result.exitCode !== 0) {\n throw new TrailStepFailureError({\n code: \"interactive_session_failed\",\n message: `Interactive agent step ${options.stepId} exited with code ${winner.result.exitCode}.`,\n details: { exitCode: winner.result.exitCode, target: options.target },\n });\n }\n\n return { exitCode: winner.result.exitCode, output: await options.readOutput() };\n }\n\n options.abortController.abort();\n return { exitCode: 0, output: await options.readOutput() };\n}\n\nasync function prepareInteractiveArtifacts(options: {\n readonly files: StepArtifactPaths;\n readonly runDir: string;\n readonly stepId: string;\n readonly outputSchema: Schema;\n readonly outputMode: \"session-file\" | \"json\";\n}): Promise<void> {\n await mkdir(options.files.stepDir, { recursive: true });\n await writeFile(\n options.files.interactiveFile,\n `${JSON.stringify(\n {\n status: \"active\",\n stepId: options.stepId,\n artifactStepId: options.files.artifactStepId,\n outputMode: options.outputMode,\n runDir: options.runDir,\n stepDir: options.files.stepDir,\n promptFile: options.files.promptFile,\n outputFile: options.files.outputFile,\n interactiveFile: options.files.interactiveFile,\n ...(options.outputMode === \"session-file\"\n ? {\n sessionDescriptionFile: options.files.sessionDescriptionFile,\n runRelativeSessionDescriptionFile: options.files.runRelativeSessionDescriptionFile,\n }\n : {}),\n runRelativeStepDir: options.files.runRelativeStepDir,\n outputSchema: options.outputSchema.jsonSchema,\n },\n null,\n 2,\n )}\\n`,\n \"utf8\",\n );\n}\n\nfunction buildInteractivePrompt(options: {\n readonly renderedPrompt: string;\n readonly files: StepArtifactPaths;\n readonly outputSchema: Schema;\n readonly outputMode: \"session-file\" | \"json\";\n}): string {\n const preamble =\n options.outputMode === \"session-file\"\n ? [\n \"You are running inside a TrailStep interactive step.\",\n \"Write a dense session description to session-description.md in the current directory.\",\n \"preserve as much usable context as possible.\",\n \"describe the conversation rather than aggressively summarize it.\",\n \"include decisions, rejected options, tradeoffs, constraints, side comments, terminology, open questions, assumptions, file paths, commands, APIs, package names, examples, preferences, reasoning, and abandoned options.\",\n \"The goal is context preservation, not polish.\",\n \"Do not omit low-importance details merely because they seem minor.\",\n \"When complete, run: trailstep continue --session-file session-description.md\",\n ]\n : [\n \"You are running inside a TrailStep interactive step.\",\n \"Submit a JSON object matching this schema:\",\n JSON.stringify(options.outputSchema.jsonSchema, null, 2),\n \"When complete, run one of:\",\n \" trailstep continue --json-file output.json\",\n ` trailstep continue --json '${JSON.stringify(exampleJsonObject(options.outputSchema.jsonSchema))}'`,\n \"If validation fails, update the JSON so it matches the schema and run trailstep continue again.\",\n ];\n\n return [...preamble, \"\", \"## Original prompt\", options.renderedPrompt].join(\"\\n\");\n}\n\nasync function readCompletedOutput(options: {\n readonly stepId: string;\n readonly artifactPaths: StepArtifactPaths;\n readonly outputSchema: Schema;\n}): Promise<PlainObject> {\n return await readCompletedInteractiveOutput({\n stepId: options.stepId,\n interactiveFile: options.artifactPaths.interactiveFile,\n outputSchema: options.outputSchema,\n });\n}\n\nfunction exampleJsonObject(schema: Record<string, unknown>): Record<string, unknown> {\n const properties =\n typeof schema.properties === \"object\" &&\n schema.properties !== null &&\n !Array.isArray(schema.properties)\n ? (schema.properties as Record<string, unknown>)\n : {};\n\n return Object.fromEntries(\n Object.entries(properties).map(([key, property]) => {\n const type =\n typeof property === \"object\" && property !== null && \"type\" in property\n ? (property as { readonly type?: unknown }).type\n : undefined;\n if (type === \"boolean\") {\n return [key, true];\n }\n if (type === \"number\") {\n return [key, 1];\n }\n return [key, \"string\"];\n }),\n );\n}\n\nconst spawnInteractiveProcess: InteractiveProcessRunner = async ({\n command,\n args,\n cwd,\n env,\n signal,\n}) => {\n return await new Promise((resolve, reject) => {\n const child = spawn(command, args, {\n cwd,\n env,\n signal,\n detached: process.platform !== \"win32\",\n shell: false,\n stdio: \"inherit\",\n });\n\n signal?.addEventListener(\"abort\", () => terminateChildProcessTree(child), { once: true });\n child.on(\"error\", reject);\n child.on(\"close\", (code) => resolve({ exitCode: code ?? 1 }));\n });\n};\n\nfunction terminateChildProcessTree(child: ReturnType<typeof spawn>): void {\n if (!child.pid) {\n return;\n }\n\n if (process.platform === \"win32\") {\n spawn(\"taskkill\", [\"/PID\", String(child.pid), \"/T\", \"/F\"], { stdio: \"ignore\" }).on(\n \"error\",\n () => {\n child.kill();\n },\n );\n return;\n }\n\n try {\n process.kill(-child.pid, \"SIGTERM\");\n } catch {\n child.kill();\n }\n}\n","import { readFile } from \"node:fs/promises\";\nimport { setTimeout as delay } from \"node:timers/promises\";\n\nimport { TrailStepFailureError } from \"../../contracts/failures/failure.js\";\nimport type { PlainObject, Schema } from \"../../contracts/shapes/shape.types.js\";\n\nexport async function waitForInteractiveCompletion(\n interactiveFile: string,\n signal: AbortSignal,\n): Promise<void> {\n while (!signal.aborted) {\n if (await isInteractiveCompleted(interactiveFile)) {\n return;\n }\n\n await delay(100, undefined, { signal }).catch(() => undefined);\n }\n}\n\nexport async function isInteractiveCompleted(interactiveFile: string): Promise<boolean> {\n try {\n const protocol = await readPlainJsonFile(interactiveFile, {\n readCode: \"interactive_session_invalid\",\n invalidCode: \"interactive_session_invalid\",\n message: \"Interactive session protocol file is invalid.\",\n });\n return protocol.status === \"completed\" || protocol.status === \"cancelled\";\n } catch {\n // The process-exit path reports authoritative protocol validation errors.\n // The watcher is intentionally best-effort and only needs to notice completion.\n return false;\n }\n}\n\nexport async function readCompletedInteractiveOutput(options: {\n readonly stepId: string;\n readonly interactiveFile: string;\n readonly outputSchema: Schema;\n}): Promise<PlainObject> {\n const protocol = await readPlainJsonFile(options.interactiveFile, {\n readCode: \"interactive_session_invalid\",\n invalidCode: \"interactive_session_invalid\",\n message: `Interactive agent step ${options.stepId} has an invalid interactive.json file.`,\n });\n\n if (protocol.status === \"cancelled\") {\n throw new TrailStepFailureError({\n code: \"interactive_session_cancelled\",\n message: `Interactive agent step ${options.stepId} was cancelled.`,\n details: {\n status: protocol.status,\n ...(typeof protocol.reason === \"string\" ? { reason: protocol.reason } : {}),\n },\n });\n }\n\n if (protocol.status !== \"completed\") {\n throw new TrailStepFailureError({\n code: \"interactive_session_incomplete\",\n message: `Interactive agent step ${options.stepId} did not complete the file-based protocol.`,\n details: { status: protocol.status },\n });\n }\n\n const outputFile = requireProtocolString(protocol.outputFile, \"outputFile\", options.stepId);\n const output = await readPlainJsonFile(outputFile, {\n readCode: \"interactive_output_missing\",\n invalidCode: \"interactive_output_invalid\",\n message: `Interactive agent step ${options.stepId} completed without a valid output.json file.`,\n });\n\n const diagnostics = options.outputSchema.diagnostics(output);\n if (diagnostics.length > 0) {\n throw new TrailStepFailureError({\n code: \"interactive_output_invalid\",\n message: `Interactive agent step ${options.stepId} output.json failed schema validation: ${formatDiagnostics(diagnostics)}`,\n details: { diagnostics },\n });\n }\n\n return output;\n}\n\nasync function readPlainJsonFile(\n path: string,\n failure: {\n readonly readCode: string;\n readonly invalidCode: string;\n readonly message: string;\n },\n): Promise<PlainObject> {\n let contents: string;\n try {\n contents = await readFile(path, \"utf8\");\n } catch (error) {\n throw new TrailStepFailureError({\n code: failure.readCode,\n message: failure.message,\n details: { path, cause: error instanceof Error ? error.message : String(error) },\n });\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(contents);\n } catch (error) {\n throw new TrailStepFailureError({\n code: failure.invalidCode,\n message: failure.message,\n details: { path, cause: error instanceof Error ? error.message : String(error) },\n });\n }\n\n if (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) {\n throw new TrailStepFailureError({\n code: failure.invalidCode,\n message: `${failure.message} Expected a plain JSON object.`,\n details: { path },\n });\n }\n\n return parsed as PlainObject;\n}\n\nfunction requireProtocolString(value: unknown, field: string, stepId: string): string {\n if (typeof value === \"string\" && value.length > 0) {\n return value;\n }\n\n throw new TrailStepFailureError({\n code: \"interactive_session_invalid\",\n message: `Interactive agent step ${stepId} interactive.json is missing ${field}.`,\n });\n}\n\nfunction formatDiagnostics(\n diagnostics: readonly { readonly path: string; readonly message: string }[],\n): string {\n return diagnostics.map((diagnostic) => `${diagnostic.path} ${diagnostic.message}`).join(\"; \");\n}\n","import { mkdir, writeFile } from \"node:fs/promises\";\n\nimport { resolveAgentTargets } from \"../../agent-targeting/resolve-agent-targets/resolve-agent-targets.js\";\nimport type {\n TrailStepAgentTarget,\n TrailStepConfig,\n} from \"../../agent-targeting/targeting.types.js\";\nimport type { AgentStepRequestConfig } from \"../../authoring/step/agent-step.types.js\";\nimport type { ProviderWorkingRunner } from \"../../cli-provider-runtime/catalog/provider-adapter.types.js\";\nimport type { WorkflowAgentRole } from \"../../contracts/agents/agent-role.types.js\";\nimport { TrailStepFailureError } from \"../../contracts/failures/failure.js\";\nimport type { PlainObject } from \"../../contracts/shapes/shape.types.js\";\nimport type { WorkingAgentProcessRunner } from \"../../runtime/run-workflow/run-workflow.types.js\";\nimport {\n resolveStepAgentFiles,\n type WorkingAgentFiles,\n} from \"./artifacts/resolve-step-agent-files.js\";\nimport { buildWorkingAgentPrompt } from \"./prompts/build-working-agent-prompt.js\";\nimport { runWorkingAgentTargetAttempt } from \"./targets/run-working-agent-target-attempt.js\";\nimport {\n summarizeWorkingAgentAttemptFailure,\n type WorkingAgentAttemptFailure,\n} from \"./targets/target-failures.js\";\n\nexport type { WorkingAgentFiles } from \"./artifacts/resolve-step-agent-files.js\";\n\nexport async function runWorkingAgentCommand<TOutput extends PlainObject>(options: {\n readonly config: TrailStepConfig;\n readonly workflowId: string;\n readonly roleName: string;\n readonly role: WorkflowAgentRole;\n readonly step: AgentStepRequestConfig<PlainObject, TOutput>;\n readonly renderedPrompt: string;\n readonly runDir: string;\n readonly cwd: string;\n readonly runner?: WorkingAgentProcessRunner;\n readonly providerWorkingRunner?: ProviderWorkingRunner;\n /** Called with the selected target immediately before each target attempt runs. */\n readonly onTargetAttempt?: (target: TrailStepAgentTarget) => void | Promise<void>;\n readonly stepIndex: number;\n readonly files?: WorkingAgentFiles;\n readonly signal?: AbortSignal;\n}): Promise<TOutput> {\n const targets = resolveAgentTargets({\n config: options.config,\n workflowId: options.workflowId,\n roleName: options.roleName,\n roleSize: options.role.size,\n });\n\n const files =\n options.files ??\n resolveStepAgentFiles({\n runDir: options.runDir,\n stepId: options.step.id,\n stepIndex: options.stepIndex,\n });\n await mkdir(files.stepDir, { recursive: true });\n await writeFile(\n files.promptFile,\n buildWorkingAgentPrompt({\n prompt: options.renderedPrompt,\n outputFile: files.outputFile,\n outputSchema: options.step.output.jsonSchema,\n captureMode: options.step.output.captureMode,\n }),\n \"utf8\",\n );\n\n const failures: WorkingAgentAttemptFailure[] = [];\n\n for (const target of targets) {\n await options.onTargetAttempt?.(target);\n try {\n return await runWorkingAgentTargetAttempt({ ...options, target, files });\n } catch (error) {\n failures.push(summarizeWorkingAgentAttemptFailure(target, error));\n }\n }\n\n throw new TrailStepFailureError({\n code: \"agent_target_exhausted\",\n message: `Working agent step ${options.step.id} for role ${options.roleName} exhausted ${failures.length} target(s).`,\n details: {\n stepId: options.step.id,\n roleName: options.roleName,\n attempts: failures,\n },\n });\n}\n","import { join } from \"node:path\";\n\nimport { resolveStepArtifactPaths } from \"../../../runtime/artifacts/step-artifacts.js\";\n\nexport interface WorkingAgentFiles {\n readonly stepDir: string;\n readonly promptFile: string;\n readonly outputFile: string;\n readonly usageFile: string;\n}\n\nexport function resolveStepAgentFiles(options: {\n readonly runDir: string;\n readonly stepId: string;\n readonly stepIndex: number;\n}): WorkingAgentFiles {\n const artifactPaths = resolveStepArtifactPaths(options);\n return {\n stepDir: artifactPaths.stepDir,\n promptFile: join(artifactPaths.stepDir, \"prompt.md\"),\n outputFile: artifactPaths.outputFile,\n usageFile: artifactPaths.usageFile,\n };\n}\n","export function buildWorkingAgentPrompt(options: {\n readonly prompt: string;\n readonly outputFile: string;\n readonly outputSchema: Record<string, unknown>;\n readonly captureMode?: \"json\" | \"raw-text\";\n}): string {\n if (options.captureMode === \"raw-text\") {\n return [\n \"# TrailStep working-agent task\",\n \"\",\n \"Run the task described below and write the document content to the output file.\",\n \"Print the document content directly as your entire response — no JSON wrapper, no surrounding commentary, no markdown fences unless they are literally part of the document content itself.\",\n \"\",\n `Output file: ${options.outputFile}`,\n \"\",\n \"## Original prompt\",\n \"\",\n options.prompt,\n \"\",\n ].join(\"\\n\");\n }\n\n return [\n \"# TrailStep working-agent task\",\n \"\",\n \"Run the task described below and write exactly one JSON object to the output file.\",\n \"Do not write prose, markdown fences, or multiple JSON values to the output file.\",\n \"\",\n `Output file: ${options.outputFile}`,\n \"\",\n \"The JSON object must match this output schema:\",\n \"\",\n \"```json\",\n JSON.stringify(options.outputSchema, null, 2),\n \"```\",\n \"\",\n \"## Original prompt\",\n \"\",\n options.prompt,\n \"\",\n ].join(\"\\n\");\n}\n","import { rm } from \"node:fs/promises\";\n\nimport type {\n TrailStepAgentTarget,\n TrailStepConfig,\n} from \"../../../agent-targeting/targeting.types.js\";\nimport type { AgentStepRequestConfig } from \"../../../authoring/step/agent-step.types.js\";\nimport type { ProviderWorkingRunner } from \"../../../cli-provider-runtime/catalog/provider-adapter.types.js\";\nimport type { WorkflowAgentRole } from \"../../../contracts/agents/agent-role.types.js\";\nimport type { PlainObject } from \"../../../contracts/shapes/shape.types.js\";\nimport type { WorkingAgentProcessRunner } from \"../../../runtime/run-workflow/run-workflow.types.js\";\nimport type { WorkingAgentFiles } from \"../artifacts/resolve-step-agent-files.js\";\nimport { runCustomWorkingProvider } from \"./custom-provider/run-custom-working-provider.js\";\nimport { runManifestWorkingProvider } from \"./manifest-provider/run-manifest-working-provider.js\";\n\nexport async function runWorkingAgentTargetAttempt<TOutput extends PlainObject>(options: {\n readonly config: TrailStepConfig;\n readonly workflowId: string;\n readonly roleName: string;\n readonly role: WorkflowAgentRole;\n readonly step: AgentStepRequestConfig<PlainObject, TOutput>;\n readonly renderedPrompt: string;\n readonly runDir: string;\n readonly cwd: string;\n readonly runner?: WorkingAgentProcessRunner;\n readonly providerWorkingRunner?: ProviderWorkingRunner;\n readonly stepIndex: number;\n readonly target: TrailStepAgentTarget;\n readonly files: WorkingAgentFiles;\n readonly signal?: AbortSignal;\n}): Promise<TOutput> {\n await rm(options.files.outputFile, { force: true });\n await rm(options.files.usageFile, { force: true });\n\n if (\n options.config.providers?.[options.target.provider] !== undefined &&\n options.config.providers[options.target.provider]?.source.type !== \"legacy-custom-provider\"\n ) {\n return runManifestWorkingProvider({\n config: options.config,\n step: options.step,\n role: options.role,\n cwd: options.cwd,\n runner: options.runner,\n target: options.target,\n files: options.files,\n signal: options.signal,\n });\n }\n\n return runCustomWorkingProvider({\n config: options.config,\n step: options.step,\n role: options.role,\n cwd: options.cwd,\n runner: options.runner,\n target: options.target,\n files: options.files,\n signal: options.signal,\n });\n}\n","import { readFile } from \"node:fs/promises\";\n\nimport { document } from \"../../../authoring/document/document.js\";\nimport type { AgentStepRequestConfig } from \"../../../authoring/step/agent-step.types.js\";\nimport { TrailStepFailureError } from \"../../../contracts/failures/failure.js\";\nimport type { PlainObject } from \"../../../contracts/shapes/shape.types.js\";\n\nexport async function readWorkingAgentOutput<TOutput extends PlainObject>(options: {\n readonly stepId: string;\n readonly outputFile: string;\n readonly step: AgentStepRequestConfig<PlainObject, TOutput>;\n}): Promise<TOutput> {\n let raw: string;\n try {\n raw = await readFile(options.outputFile, \"utf8\");\n } catch (error) {\n throw new TrailStepFailureError({\n code: \"agent_output_unreadable\",\n message: `Working agent step ${options.stepId} output.json could not be read.`,\n details:\n error instanceof Error\n ? { path: options.outputFile, cause: error.message }\n : { path: options.outputFile },\n });\n }\n\n if (options.step.output.captureMode === \"raw-text\") {\n // Delegates to the shared `document(...)` capture path (the same one\n // code-authored steps use), so agent-captured and code-captured\n // documents share one persistence implementation. `document(...)`\n // resolves its target directory and index from the ambient step\n // context (`currentStep`), which is active for the whole duration of\n // this step's dispatch (see `withStepContext` in run-continuation.ts).\n const capturedDocument = await document(raw);\n\n return options.step.output.assert(capturedDocument, `step ${options.stepId} output`);\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch (error) {\n throw new TrailStepFailureError({\n code: \"agent_output_invalid_json\",\n message: `Working agent step ${options.stepId} output.json must contain one JSON object.`,\n details:\n error instanceof Error\n ? { path: options.outputFile, cause: error.message }\n : { path: options.outputFile },\n });\n }\n\n if (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) {\n throw new TrailStepFailureError({\n code: \"agent_output_invalid_json\",\n message: `Working agent step ${options.stepId} output.json must contain one JSON object.`,\n details: { path: options.outputFile },\n });\n }\n\n return options.step.output.assert(parsed, `step ${options.stepId} output`);\n}\n","import type { WorkflowAgentThinking } from \"../../../../contracts/agents/agent-role.types.js\";\nimport { renderCustomProviderArgs } from \"../../../custom-provider/render-custom-provider-args.js\";\n\nexport function buildWorkingAgentArgs(options: {\n readonly argv: readonly string[] | undefined;\n readonly promptFile: string;\n readonly outputFile: string;\n readonly model?: string;\n readonly thinking?: WorkflowAgentThinking;\n}): string[] {\n if (!options.argv) {\n return [\n \"--prompt-file\",\n options.promptFile,\n \"--output-file\",\n options.outputFile,\n ...(options.model ? [\"--model\", options.model] : []),\n ];\n }\n\n return renderCustomProviderArgs({\n argv: options.argv,\n values: {\n promptFile: options.promptFile,\n outputFile: options.outputFile,\n ...(options.model === undefined ? {} : { model: options.model }),\n ...(options.thinking === undefined ? {} : { thinking: options.thinking }),\n },\n errorCode: \"agent_provider_invalid\",\n commandDescription: \"Working agent command\",\n });\n}\n","import { spawn } from \"node:child_process\";\n\nimport type { WorkingAgentProcessRunner } from \"../../../../runtime/run-workflow/run-workflow.types.js\";\n\nexport const spawnWorkingAgentProcess: WorkingAgentProcessRunner = async ({\n command,\n args,\n cwd,\n stdio,\n signal,\n}) => {\n return await new Promise((resolve, reject) => {\n let stdout = \"\";\n const child = spawn(command, args, {\n cwd,\n shell: false,\n stdio: stdio === \"pipe\" ? [\"ignore\", \"pipe\", \"inherit\"] : \"inherit\",\n detached: process.platform !== \"win32\",\n });\n\n if (child.stdout !== null) {\n child.stdout.setEncoding(\"utf8\");\n child.stdout.on(\"data\", (chunk: string) => {\n stdout += chunk;\n });\n }\n\n signal?.addEventListener(\"abort\", () => terminateChildProcessTree(child), { once: true });\n child.on(\"error\", reject);\n child.on(\"close\", (code) =>\n resolve({ exitCode: code ?? 1, ...(stdio === \"pipe\" ? { stdout } : {}) }),\n );\n });\n};\n\nfunction terminateChildProcessTree(child: ReturnType<typeof spawn>): void {\n if (!child.pid) {\n return;\n }\n\n if (process.platform === \"win32\") {\n spawn(\"taskkill\", [\"/PID\", String(child.pid), \"/T\", \"/F\"], { stdio: \"ignore\" }).on(\n \"error\",\n () => {\n child.kill();\n },\n );\n return;\n }\n\n try {\n process.kill(-child.pid, \"SIGTERM\");\n } catch {\n child.kill();\n }\n}\n","import type {\n TrailStepAgentTarget,\n TrailStepConfig,\n} from \"../../../../agent-targeting/targeting.types.js\";\nimport type { AgentStepRequestConfig } from \"../../../../authoring/step/agent-step.types.js\";\nimport type { WorkflowAgentRole } from \"../../../../contracts/agents/agent-role.types.js\";\nimport { TrailStepFailureError } from \"../../../../contracts/failures/failure.js\";\nimport type { PlainObject } from \"../../../../contracts/shapes/shape.types.js\";\nimport type {\n WorkingAgentProcessResult,\n WorkingAgentProcessRunner,\n} from \"../../../../runtime/run-workflow/run-workflow.types.js\";\nimport type { WorkingAgentFiles } from \"../../artifacts/resolve-step-agent-files.js\";\nimport { readWorkingAgentOutput } from \"../../output/read-working-agent-output.js\";\nimport { buildWorkingAgentArgs } from \"./build-working-agent-args.js\";\nimport { spawnWorkingAgentProcess } from \"./spawn-working-agent-process.js\";\n\nexport async function runCustomWorkingProvider<TOutput extends PlainObject>(options: {\n readonly config: TrailStepConfig;\n readonly step: AgentStepRequestConfig<PlainObject, TOutput>;\n readonly role: WorkflowAgentRole;\n readonly cwd: string;\n readonly runner?: WorkingAgentProcessRunner;\n readonly target: TrailStepAgentTarget;\n readonly files: WorkingAgentFiles;\n readonly signal?: AbortSignal;\n}): Promise<TOutput> {\n const agentConfig = options.config.customProviders[options.target.provider];\n if (!agentConfig) {\n throw new TrailStepFailureError({\n code: \"agent_provider_unavailable\",\n message: `Working agent target '${options.target.provider}' does not reference a configured custom agent.`,\n details: { provider: options.target.provider },\n });\n }\n\n const thinking = options.target.thinking ?? options.role.thinking;\n const args = buildWorkingAgentArgs({\n argv: options.target.args ?? agentConfig.args,\n promptFile: options.files.promptFile,\n outputFile: options.files.outputFile,\n model: options.target.model,\n thinking,\n });\n\n let result: WorkingAgentProcessResult;\n try {\n result = await (options.runner ?? spawnWorkingAgentProcess)({\n command: agentConfig.binary,\n args,\n cwd: options.cwd,\n shell: false,\n stdio: \"inherit\",\n promptFile: options.files.promptFile,\n outputFile: options.files.outputFile,\n ...(options.target.model === undefined ? {} : { model: options.target.model }),\n signal: options.signal,\n });\n } catch (error) {\n throw new TrailStepFailureError({\n code: \"agent_provider_spawn_error\",\n message: `Working agent step ${options.step.id} could not start target '${options.target.provider}'.`,\n details: {\n target: options.target.provider,\n ...(options.target.model === undefined ? {} : { model: options.target.model }),\n cause: error instanceof Error ? error.message : String(error),\n },\n });\n }\n\n if (result.exitCode !== 0) {\n throw new TrailStepFailureError({\n code: \"agent_provider_failed\",\n message: `Working agent step ${options.step.id} target '${options.target.provider}' exited with code ${result.exitCode}.`,\n details: {\n exitCode: result.exitCode,\n provider: agentConfig.binary,\n target: options.target.provider,\n ...(options.target.model === undefined ? {} : { model: options.target.model }),\n },\n });\n }\n\n return readWorkingAgentOutput({\n stepId: options.step.id,\n outputFile: options.files.outputFile,\n step: options.step,\n });\n}\n","import { writeFile } from \"node:fs/promises\";\n\nimport type {\n TrailStepAgentTarget,\n TrailStepConfig,\n} from \"../../../../agent-targeting/targeting.types.js\";\nimport type { AgentStepRequestConfig } from \"../../../../authoring/step/agent-step.types.js\";\nimport {\n extractEnvelopeOutput,\n extractEnvelopeText,\n} from \"../../../../cli-provider-runtime/envelopes/envelope.js\";\nimport type {\n WorkflowAgentRole,\n WorkflowAgentThinking,\n} from \"../../../../contracts/agents/agent-role.types.js\";\nimport { TrailStepFailureError } from \"../../../../contracts/failures/failure.js\";\nimport type { PlainObject } from \"../../../../contracts/shapes/shape.types.js\";\nimport type {\n TrailStepProviderManifest,\n TrailStepProviderOutputManifest,\n} from \"../../../../providers/provider-manifest.js\";\nimport type {\n WorkingAgentProcessResult,\n WorkingAgentProcessRunner,\n} from \"../../../../runtime/run-workflow/run-workflow.types.js\";\nimport { renderCustomProviderArgs } from \"../../../custom-provider/render-custom-provider-args.js\";\nimport type { WorkingAgentFiles } from \"../../artifacts/resolve-step-agent-files.js\";\nimport { readWorkingAgentOutput } from \"../../output/read-working-agent-output.js\";\nimport { spawnWorkingAgentProcess } from \"../custom-provider/spawn-working-agent-process.js\";\n\nexport async function runManifestWorkingProvider<TOutput extends PlainObject>(options: {\n readonly config: TrailStepConfig;\n readonly step: AgentStepRequestConfig<PlainObject, TOutput>;\n readonly role: WorkflowAgentRole;\n readonly cwd: string;\n readonly runner?: WorkingAgentProcessRunner;\n readonly target: TrailStepAgentTarget;\n readonly files: WorkingAgentFiles;\n readonly signal?: AbortSignal;\n}): Promise<TOutput> {\n const registration = options.config.providers?.[options.target.provider];\n const manifest = registration?.manifest;\n const working = manifest?.working;\n\n if (\n manifest === undefined ||\n working === undefined ||\n !working.supported ||\n working.command === undefined\n ) {\n throw new TrailStepFailureError({\n code: \"agent_provider_unavailable\",\n message: `Working agent target '${options.target.provider}' does not reference a supported manifest working provider.`,\n details: { provider: options.target.provider },\n });\n }\n\n const thinking = options.target.thinking ?? options.role.thinking;\n const model = optionalNonEmptyString(options.target.model);\n const args = renderCustomProviderArgs({\n argv:\n working.args ??\n defaultManifestWorkingArgs({\n manifest,\n promptFile: options.files.promptFile,\n outputFile: options.files.outputFile,\n model,\n thinking,\n }),\n values: {\n promptFile: options.files.promptFile,\n outputFile: options.files.outputFile,\n ...(model === undefined ? {} : { model }),\n ...(thinking === undefined ? {} : { thinking }),\n },\n errorCode: \"agent_provider_invalid\",\n commandDescription: \"Manifest working provider command\",\n });\n const captureStdout = working.output?.style !== \"provider-output-file\";\n\n let result: WorkingAgentProcessResult;\n try {\n result = await (options.runner ?? spawnWorkingAgentProcess)({\n command: working.command,\n args,\n cwd: options.cwd,\n shell: false,\n stdio: captureStdout ? \"pipe\" : \"inherit\",\n promptFile: options.files.promptFile,\n outputFile: options.files.outputFile,\n ...(model === undefined ? {} : { model }),\n signal: options.signal,\n });\n } catch (error) {\n throw new TrailStepFailureError({\n code: \"agent_provider_spawn_error\",\n message: `Working agent step ${options.step.id} could not start target '${options.target.provider}'.`,\n details: {\n target: options.target.provider,\n ...(model === undefined ? {} : { model }),\n cause: error instanceof Error ? error.message : String(error),\n },\n });\n }\n\n if (result.exitCode !== 0) {\n throw new TrailStepFailureError({\n code: \"agent_provider_failed\",\n message: `Working agent step ${options.step.id} target '${options.target.provider}' exited with code ${result.exitCode}.`,\n details: {\n exitCode: result.exitCode,\n provider: working.command,\n target: options.target.provider,\n ...(model === undefined ? {} : { model }),\n },\n });\n }\n\n await writeCapturedStdoutOutput({\n provider: options.target.provider,\n stepId: options.step.id,\n outputFile: options.files.outputFile,\n captureMode: options.step.output.captureMode,\n stdout: (result as WorkingAgentProcessResult & { readonly stdout?: string }).stdout,\n output: working.output,\n extractOutputHook: registration?.manifest.hooks?.extractOutput,\n });\n\n return readWorkingAgentOutput({\n stepId: options.step.id,\n outputFile: options.files.outputFile,\n step: options.step,\n });\n}\n\nasync function writeCapturedStdoutOutput(options: {\n readonly provider: string;\n readonly stepId: string;\n readonly outputFile: string;\n readonly captureMode?: \"json\" | \"raw-text\";\n readonly stdout?: string;\n readonly output?: TrailStepProviderOutputManifest;\n readonly extractOutputHook?: unknown;\n}): Promise<void> {\n if (options.stdout === undefined) {\n return;\n }\n\n if (\n options.output?.style === \"stdout-json-envelope\" ||\n options.output?.style === \"stdout-jsonl-transcript\"\n ) {\n await writeEnvelopeOutput({ ...options, stdout: options.stdout });\n return;\n }\n\n if (isRecord(options.extractOutputHook)) {\n const extracted = extractJsonObject(options.stdout);\n if (extracted === undefined) {\n throw new TrailStepFailureError({\n code: \"agent_provider_output_invalid\",\n message: `Working agent step ${options.stepId} provider '${options.provider}' could not extract JSON output from stdout using declared hook metadata.`,\n details: { provider: options.provider },\n });\n }\n\n await writeFile(options.outputFile, `${JSON.stringify(extracted)}\\n`, \"utf8\");\n }\n}\n\nasync function writeEnvelopeOutput(options: {\n readonly provider: string;\n readonly stepId: string;\n readonly outputFile: string;\n readonly captureMode?: \"json\" | \"raw-text\";\n readonly stdout: string;\n readonly output?: TrailStepProviderOutputManifest;\n}): Promise<void> {\n try {\n const resultField = options.output?.parsing?.resultField ?? \"result\";\n if (options.captureMode === \"raw-text\") {\n const text = extractEnvelopeText(options.stdout, { resultField });\n await writeFile(options.outputFile, text, \"utf8\");\n return;\n }\n\n const extracted = extractEnvelopeOutput(options.stdout, { resultField });\n await writeFile(options.outputFile, `${JSON.stringify(extracted)}\\n`, \"utf8\");\n } catch (error) {\n throw new TrailStepFailureError({\n code: \"agent_provider_output_invalid\",\n message: `Working agent step ${options.stepId} provider '${options.provider}' could not parse stdout envelope output.`,\n details: {\n provider: options.provider,\n cause: error instanceof Error ? error.message : String(error),\n },\n });\n }\n}\n\nfunction defaultManifestWorkingArgs(options: {\n readonly manifest: TrailStepProviderManifest;\n readonly promptFile: string;\n readonly outputFile: string;\n readonly model?: string;\n readonly thinking?: WorkflowAgentThinking;\n}): readonly string[] {\n const args: string[] = [];\n\n if (options.model !== undefined && options.manifest.model.supported) {\n args.push(...renderFlaggedValue(options.manifest.model.flag, options.model));\n }\n\n if (options.thinking !== undefined && options.manifest.thinking.supported) {\n args.push(...renderFlaggedValue(options.manifest.thinking.flag, options.thinking));\n }\n\n if (options.manifest.working.prompt?.reference === \"at-prefixed-argument\") {\n args.push(`@${options.promptFile}`);\n } else {\n args.push(\"--prompt-file\", options.promptFile);\n }\n\n if (options.manifest.working.output?.style === \"provider-output-file\") {\n args.push(\"--output-file\", options.outputFile);\n }\n\n return args;\n}\n\nfunction renderFlaggedValue(flag: string | undefined, value: string): readonly string[] {\n if (flag === undefined) {\n return [];\n }\n\n const parts = flag.split(/\\s+/u).filter(Boolean);\n if (parts.length === 0) {\n return [];\n }\n\n if (parts.length === 2) {\n return [parts[0] as string, `${parts[1] as string}=${value}`];\n }\n\n return [...parts, value];\n}\n\nfunction optionalNonEmptyString(value: string | undefined): string | undefined {\n return value === undefined || value.length === 0 ? undefined : value;\n}\n\nfunction extractJsonObject(stdout: string): Record<string, unknown> | undefined {\n const trimmed = stdout.trim();\n const candidates = [trimmed];\n const firstBrace = trimmed.indexOf(\"{\");\n const lastBrace = trimmed.lastIndexOf(\"}\");\n if (firstBrace >= 0 && lastBrace > firstBrace) {\n candidates.push(trimmed.slice(firstBrace, lastBrace + 1));\n }\n\n for (const candidate of candidates) {\n try {\n const parsed = JSON.parse(candidate) as unknown;\n if (isRecord(parsed)) {\n return parsed;\n }\n } catch {\n // Try the next candidate.\n }\n }\n\n return undefined;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n","import type { PlainObject } from \"../../contracts/shapes/shape.types.js\";\n\n/**\n * Extraction logic ported from the retired `claude-rpc-trailstep-agent.mjs` mock\n * wrapper's `extractTrailStepOutput`, parameterized by which envelope field holds\n * the provider's final text (e.g. `\"result\"` for `claude --output-format json`).\n *\n * Handles four shapes of vendor CLI stdout:\n * 1. A single JSON envelope object whose `resultField` holds the final text\n * (or is itself already the final JSON object).\n * 2. Streaming JSON-lines output, where the last line containing a usable\n * `resultField`/`content` wins.\n * 3. A `resultField` value that is itself a message-shaped object with a\n * `content` array of `{type, text}` blocks (confirmed empirically for\n * `pi --mode json`, whose per-event `\"message\"` field nests the final\n * answer inside `message.content[].text` rather than a flat string like\n * Claude's `\"result\"`) — all `type: \"text\"` blocks are concatenated, in\n * order, and the joined text is parsed the same way a flat string would be.\n * 4. Plain text that itself contains (or is) the JSON object.\n */\nexport interface EnvelopeOptions {\n readonly resultField: string;\n}\n\nexport interface EnvelopeMetadataOptions {\n readonly harnessDurationMs: number;\n}\n\nexport interface ClaudeEnvelopeMetadata {\n readonly usage?: PlainObject;\n readonly costUsd?: number;\n readonly durationMs?: number;\n readonly harnessDurationMs: number;\n readonly turns?: number;\n readonly sessionId?: string;\n}\n\nexport function extractEnvelopeMetadata(\n rawStdout: string,\n options: EnvelopeMetadataOptions,\n): ClaudeEnvelopeMetadata {\n const metadata: Record<string, unknown> = { harnessDurationMs: options.harnessDurationMs };\n const envelope = parseEnvelopeObject(rawStdout);\n\n if (envelope) {\n const usage = camelCaseUsage(envelope.usage);\n if (usage) {\n metadata.usage = usage;\n }\n\n if (typeof envelope.total_cost_usd === \"number\") {\n metadata.costUsd = envelope.total_cost_usd;\n }\n\n if (typeof envelope.duration_ms === \"number\") {\n metadata.durationMs = envelope.duration_ms;\n }\n\n if (typeof envelope.num_turns === \"number\") {\n metadata.turns = envelope.num_turns;\n }\n\n if (typeof envelope.session_id === \"string\") {\n metadata.sessionId = envelope.session_id;\n }\n }\n\n return metadata as unknown as ClaudeEnvelopeMetadata;\n}\n\nexport function extractEnvelopeOutput(rawStdout: string, options: EnvelopeOptions): PlainObject {\n const text = rawStdout.trim();\n if (!text) {\n throw new Error(\"Provider process returned empty stdout.\");\n }\n\n const parsedEnvelope = parseJson(text);\n if (isPlainObject(parsedEnvelope)) {\n if (parsedEnvelope.is_error === true) {\n throw new Error(\n `Provider reported an error: ${String(parsedEnvelope[options.resultField] ?? text)}`,\n );\n }\n\n const resolved = resolveFieldValue(parsedEnvelope[options.resultField]);\n if (resolved) {\n return resolved;\n }\n\n if (typeof parsedEnvelope.content === \"string\") {\n return parseObjectFromText(parsedEnvelope.content);\n }\n }\n\n const streamResult = parseLastJsonLineResult(text, options.resultField);\n if (streamResult) {\n return streamResult;\n }\n\n return parseObjectFromText(text);\n}\n\n/**\n * Text-only counterpart to `extractEnvelopeOutput`, for steps whose\n * `captureMode` is `\"raw-text\"` (see `Document.captureMode` in\n * `authoring/document/document.ts`): the agent's final answer is a plain-text\n * document, not JSON, so the `resultField` value must be taken verbatim\n * rather than JSON-parsed. Mirrors the same four documented stdout shapes as\n * `extractEnvelopeOutput` — single JSON envelope, JSON-lines transcript,\n * message-shaped `resultField` with a `content` block array, and plain text —\n * but never throws on non-JSON text; the raw text is always the answer.\n */\nexport function extractEnvelopeText(rawStdout: string, options: EnvelopeOptions): string {\n const text = rawStdout.trim();\n if (!text) {\n throw new Error(\"Provider process returned empty stdout.\");\n }\n\n const parsedEnvelope = parseJson(text);\n if (isPlainObject(parsedEnvelope)) {\n if (parsedEnvelope.is_error === true) {\n throw new Error(\n `Provider reported an error: ${String(parsedEnvelope[options.resultField] ?? text)}`,\n );\n }\n\n const resolved = resolveFieldText(parsedEnvelope[options.resultField]);\n if (resolved !== undefined) {\n return resolved;\n }\n\n if (typeof parsedEnvelope.content === \"string\") {\n return parsedEnvelope.content;\n }\n }\n\n const streamResult = parseLastJsonLineText(text, options.resultField);\n if (streamResult !== undefined) {\n return streamResult;\n }\n\n return text;\n}\n\nfunction parseLastJsonLineText(text: string, resultField: string): string | undefined {\n const lines = text\n .split(/\\r?\\n/u)\n .map((line) => line.trim())\n .filter(Boolean);\n\n for (const line of [...lines].reverse()) {\n const parsed = parseJson(line);\n if (!isPlainObject(parsed)) {\n continue;\n }\n\n const resolved = resolveFieldText(parsed[resultField]);\n if (resolved !== undefined) {\n return resolved;\n }\n\n if (typeof parsed.content === \"string\") {\n return parsed.content;\n }\n }\n\n return undefined;\n}\n\n/**\n * Text-only counterpart to `resolveFieldValue`: resolves a raw `resultField`\n * value into the final raw text, handling a plain string (verbatim) or a\n * message-shaped object carrying a `content` array of text blocks (Pi),\n * without ever attempting to JSON-parse the resolved text.\n */\nfunction resolveFieldText(fieldValue: unknown): string | undefined {\n if (typeof fieldValue === \"string\") {\n return fieldValue;\n }\n\n if (isPlainObject(fieldValue)) {\n return extractTextFromContentBlocks(fieldValue);\n }\n\n return undefined;\n}\n\nfunction parseLastJsonLineResult(text: string, resultField: string): PlainObject | undefined {\n const lines = text\n .split(/\\r?\\n/u)\n .map((line) => line.trim())\n .filter(Boolean);\n\n for (const line of [...lines].reverse()) {\n const parsed = parseJson(line);\n if (!isPlainObject(parsed)) {\n continue;\n }\n\n const resolved = resolveFieldValue(parsed[resultField]);\n if (resolved) {\n return resolved;\n }\n\n if (typeof parsed.content === \"string\") {\n return parseObjectFromText(parsed.content);\n }\n }\n\n return undefined;\n}\n\n/**\n * Resolves a raw `resultField` value into the final output object, handling\n * the three shapes that field's value can take across vendors: a JSON-text\n * string (Claude), an object that already is the final output (also legal for\n * Claude-style envelopes), or a message-shaped object carrying a `content`\n * array of text blocks (Pi). Returns `undefined` when `fieldValue` is absent\n * or is a plain object with no extractable text, so callers can fall through\n * to their next fallback instead of misreporting an unrelated object.\n */\nfunction resolveFieldValue(fieldValue: unknown): PlainObject | undefined {\n if (typeof fieldValue === \"string\") {\n return parseObjectFromText(fieldValue);\n }\n\n if (isPlainObject(fieldValue)) {\n const blockText = extractTextFromContentBlocks(fieldValue);\n if (blockText !== undefined) {\n return parseObjectFromText(blockText);\n }\n\n return fieldValue;\n }\n\n return undefined;\n}\n\n/**\n * Extracts and concatenates `text` from every `{type: \"text\", text: string}`\n * content block in `value.content`, if `value.content` is such an array.\n * Returns `undefined` when `value` has no `content` array to extract from, so\n * the caller can fall back to treating `value` itself as the output object.\n */\nfunction extractTextFromContentBlocks(value: PlainObject): string | undefined {\n const content = value.content;\n if (!Array.isArray(content)) {\n return undefined;\n }\n\n const textParts = content\n .filter(isPlainObject)\n .filter((block) => block.type === \"text\" && typeof block.text === \"string\")\n .map((block) => block.text as string);\n\n if (textParts.length === 0) {\n return undefined;\n }\n\n return textParts.join(\"\");\n}\n\nfunction parseObjectFromText(text: string): PlainObject {\n const parsed = parseJson(text.trim());\n if (isPlainObject(parsed)) {\n return parsed;\n }\n\n const firstBrace = text.indexOf(\"{\");\n const lastBrace = text.lastIndexOf(\"}\");\n if (firstBrace === -1 || lastBrace === -1 || lastBrace <= firstBrace) {\n throw new Error(`Provider response did not contain a JSON object: ${text}`);\n }\n\n const extracted = parseJson(text.slice(firstBrace, lastBrace + 1));\n if (!isPlainObject(extracted)) {\n throw new Error(\"Provider response JSON was not an object.\");\n }\n\n return extracted;\n}\n\nfunction parseEnvelopeObject(rawStdout: string): PlainObject | undefined {\n const text = rawStdout.trim();\n const parsed = parseJson(text);\n if (isPlainObject(parsed)) {\n return parsed;\n }\n\n const lines = text\n .split(/\\r?\\n/u)\n .map((line) => line.trim())\n .filter(Boolean);\n\n for (const line of [...lines].reverse()) {\n const parsedLine = parseJson(line);\n if (isPlainObject(parsedLine)) {\n return parsedLine;\n }\n }\n\n return undefined;\n}\n\nfunction camelCaseUsage(value: unknown): PlainObject | undefined {\n if (!isPlainObject(value)) {\n return undefined;\n }\n\n const usage: Record<string, unknown> = {};\n for (const [key, fieldValue] of Object.entries(value)) {\n if (typeof fieldValue === \"number\") {\n usage[snakeToCamel(key)] = fieldValue;\n }\n }\n\n return Object.keys(usage).length > 0 ? usage : undefined;\n}\n\nfunction snakeToCamel(value: string): string {\n return value.replace(/_([a-z])/gu, (_match, letter: string) => letter.toUpperCase());\n}\n\nfunction parseJson(text: string): unknown {\n try {\n return JSON.parse(text);\n } catch {\n return undefined;\n }\n}\n\nfunction isPlainObject(value: unknown): value is PlainObject {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n","import type { TrailStepAgentTarget } from \"../../../agent-targeting/targeting.types.js\";\nimport { TrailStepFailureError } from \"../../../contracts/failures/failure.js\";\n\nexport interface WorkingAgentAttemptFailure {\n readonly target: string;\n readonly model?: string;\n readonly code: string;\n readonly message: string;\n readonly details?: unknown;\n}\n\nexport function summarizeWorkingAgentAttemptFailure(\n target: TrailStepAgentTarget,\n error: unknown,\n): WorkingAgentAttemptFailure {\n if (error instanceof TrailStepFailureError) {\n return {\n target: target.provider,\n ...(target.model === undefined ? {} : { model: target.model }),\n code: error.failure.code,\n message: error.failure.message,\n ...(error.failure.details === undefined ? {} : { details: error.failure.details }),\n };\n }\n\n return {\n target: target.provider,\n ...(target.model === undefined ? {} : { model: target.model }),\n code: \"agent_target_failed\",\n message: error instanceof Error ? error.message : \"Working agent target failed.\",\n };\n}\n","import { join, relative } from \"node:path\";\n\nexport function resolveSubPromptArtifactPaths(options: {\n readonly runDir: string;\n readonly stepDir: string;\n readonly ordinal: number;\n readonly fingerprint: string;\n}): {\n readonly subPromptDir: string;\n readonly promptFile: string;\n readonly outputFile: string;\n readonly usageFile: string;\n readonly runRelative: {\n readonly subPromptDir: string;\n readonly promptFile: string;\n readonly outputFile: string;\n };\n} {\n const artifactSubPromptId = `${String(options.ordinal).padStart(4, \"0\")}-${options.fingerprint.slice(0, 12)}`;\n const subPromptDir = join(options.stepDir, \"subPrompts\", artifactSubPromptId);\n const promptFile = join(subPromptDir, \"prompt.txt\");\n const outputFile = join(subPromptDir, \"output.json\");\n const usageFile = join(subPromptDir, \"usage.json\");\n\n return {\n subPromptDir,\n promptFile,\n outputFile,\n usageFile,\n runRelative: {\n subPromptDir: toRunRelativePath(options.runDir, subPromptDir),\n promptFile: toRunRelativePath(options.runDir, promptFile),\n outputFile: toRunRelativePath(options.runDir, outputFile),\n },\n };\n}\n\nfunction toRunRelativePath(runDir: string, path: string): string {\n return relative(runDir, path).replaceAll(\"\\\\\", \"/\");\n}\n","import type { Failure } from \"../../contracts/failures/failure.js\";\n\nexport function isFailureLikeError(error: unknown): error is { readonly failure: Failure } {\n return (\n typeof error === \"object\" &&\n error !== null &&\n \"failure\" in error &&\n typeof error.failure === \"object\" &&\n error.failure !== null &&\n \"code\" in error.failure &&\n typeof error.failure.code === \"string\" &&\n \"message\" in error.failure &&\n typeof error.failure.message === \"string\"\n );\n}\n","import type { Failure } from \"../../contracts/failures/failure.js\";\nimport { TrailStepFailureError } from \"../../contracts/failures/failure.js\";\nimport type { RunContext } from \"../../contracts/run-context/run-context.types.js\";\nimport { createEvent } from \"../events/create-run-event.js\";\nimport { isFailureLikeError } from \"../failures/failure-like.js\";\n\nexport async function emitSubPromptFailed(options: {\n readonly context: RunContext;\n readonly parentStepId: string;\n readonly ordinal: number;\n readonly fingerprint?: string;\n readonly artifactPaths?: {\n readonly subPromptDir: string;\n readonly promptFile: string;\n readonly outputFile: string;\n };\n readonly failure: Failure;\n}): Promise<void> {\n await options.context.emit?.(\n createEvent({\n runId: options.context.id,\n workflowId: options.context.workflowId ?? \"\",\n stepId: options.parentStepId,\n type: \"subPrompt.failed\",\n payload: {\n parentStepId: options.parentStepId,\n ordinal: options.ordinal,\n ...(options.fingerprint === undefined ? {} : { fingerprint: options.fingerprint }),\n ...(options.artifactPaths === undefined ? {} : { artifactPaths: options.artifactPaths }),\n failure: options.failure,\n },\n }),\n );\n}\n\nexport function maxSubPromptsGuardError(maxSubPrompts: number): TrailStepFailureError {\n return new TrailStepFailureError({\n code: \"max_sub_prompts_exceeded\",\n message: `workflow exceeded maxSubPrompts guard (${maxSubPrompts})`,\n });\n}\n\nexport function throwMissingSubPromptAgentConfig(options: {\n readonly workflowId: string;\n readonly parentStepId: string;\n readonly subPromptId: string;\n readonly agent: string;\n}): never {\n throw new TrailStepFailureError({\n code: \"missing_agent_config\",\n message: `Missing .trailstep/config.json: workflow ${options.workflowId} parent step ${options.parentStepId} subPrompt ${options.subPromptId} needs configured working agent '${options.agent}'.`,\n details: {\n workflowId: options.workflowId,\n parentStepId: options.parentStepId,\n subPromptId: options.subPromptId,\n agent: options.agent,\n mode: \"working\",\n },\n });\n}\n\nexport function subPromptFailureError(error: unknown): TrailStepFailureError {\n if (error instanceof TrailStepFailureError) {\n if (error.failure.code === \"validation_failed\") {\n return new TrailStepFailureError({\n ...error.failure,\n message: normalizeSubPromptValidationMessage(error.failure.message),\n });\n }\n\n return error;\n }\n\n if (isFailureLikeError(error)) {\n return new TrailStepFailureError(error.failure);\n }\n\n return new TrailStepFailureError({\n code: \"sub_prompt_failed\",\n message: error instanceof Error ? error.message : \"subPrompt failed.\",\n ...(error instanceof Error\n ? { details: { name: error.name } }\n : error === undefined\n ? {}\n : { details: { cause: error } }),\n });\n}\n\nfunction normalizeSubPromptValidationMessage(message: string): string {\n if (message.startsWith(\"subPrompt output failed schema validation\")) {\n return message;\n }\n\n const diagnostics = message.match(/failed schema validation: (.*)$/)?.[1];\n return diagnostics === undefined\n ? `subPrompt output failed schema validation: ${message}`\n : `subPrompt output failed schema validation: ${diagnostics}`;\n}\n","import { createHash } from \"node:crypto\";\n\nimport type { PlainObject } from \"../../contracts/shapes/shape.types.js\";\n\nexport function fingerprintSubPrompt(options: {\n readonly input: PlainObject;\n readonly prompt: string;\n}): string {\n return createHash(\"sha256\").update(stableJsonStringify(options)).digest(\"hex\");\n}\n\nexport function stableJsonStringify(value: unknown): string {\n if (Array.isArray(value)) {\n return `[${value.map((item) => stableJsonStringify(item)).join(\",\")}]`;\n }\n\n if (isPlainObject(value)) {\n const entries = Object.entries(value).sort(([left], [right]) => left.localeCompare(right));\n return `{${entries\n .map(([key, entryValue]) => `${JSON.stringify(key)}:${stableJsonStringify(entryValue)}`)\n .join(\",\")}}`;\n }\n\n return JSON.stringify(value);\n}\n\nfunction isPlainObject(value: unknown): value is PlainObject {\n return (\n typeof value === \"object\" &&\n value !== null &&\n !Array.isArray(value) &&\n Object.getPrototypeOf(value) === Object.prototype\n );\n}\n","import type { RunContextEvent } from \"../../contracts/run-context/run-context.types.js\";\nimport type { PlainObject } from \"../../contracts/shapes/shape.types.js\";\n\ninterface CompletedSubPromptEventPayload extends PlainObject {\n readonly parentStepId: string;\n readonly ordinal: number;\n readonly fingerprint: string;\n readonly output: PlainObject;\n}\n\nexport function findCompletedSubPromptEvent(\n events: readonly RunContextEvent[],\n parentStepId: string,\n ordinal: number,\n fingerprint: string,\n): RunContextEvent<CompletedSubPromptEventPayload> | undefined {\n for (let index = events.length - 1; index >= 0; index -= 1) {\n const event = events[index];\n if (event?.type !== \"subPrompt.completed\") {\n continue;\n }\n\n const payload = event.payload;\n if (\n payload.parentStepId === parentStepId &&\n payload.ordinal === ordinal &&\n payload.fingerprint === fingerprint &&\n isPlainObject(payload.output)\n ) {\n return event as RunContextEvent<CompletedSubPromptEventPayload>;\n }\n }\n\n return undefined;\n}\n\nfunction isPlainObject(value: unknown): value is PlainObject {\n return (\n typeof value === \"object\" &&\n value !== null &&\n !Array.isArray(value) &&\n Object.getPrototypeOf(value) === Object.prototype\n );\n}\n","import type { AgentPrompt } from \"../../contracts/agents/agent-adapter.types.js\";\nimport type { PlainObject } from \"../../contracts/shapes/shape.types.js\";\nimport { runSubPrompt } from \"../../runtime/sub-prompts/run-sub-prompt.js\";\nimport type {\n PromptTemplateSource,\n SubPromptFactory,\n SubPromptOptions,\n} from \"./continuation.types.js\";\n\nexport function subPrompt<\n TInput extends PlainObject = PlainObject,\n TOutput extends PlainObject = PlainObject,\n>(\n source: AgentPrompt<TInput> | PromptTemplateSource,\n options: SubPromptOptions<TOutput>,\n): SubPromptFactory<TInput, TOutput> {\n const run = (input?: TInput): Promise<TOutput> => runSubPrompt(source, options, input);\n\n return run as SubPromptFactory<TInput, TOutput>;\n}\n","import type { PlainObject } from \"../../contracts/shapes/shape.types.js\";\nimport type { WorkflowInvocationOptions } from \"../step/continuation.types.js\";\nimport type { DefinedWorkflow, WorkflowBuilderOptions } from \"./workflow.types.js\";\n\nexport type { DefinedWorkflow, WorkflowBuilderOptions } from \"./workflow.types.js\";\n\nexport function defineWorkflow<\n TInput extends PlainObject = PlainObject,\n TOutput extends PlainObject = PlainObject,\n>(options: WorkflowBuilderOptions<TInput, TOutput>): DefinedWorkflow<TInput, TOutput> {\n assertBuilderObject(options, \"defineWorkflow\");\n if (typeof options.start !== \"function\") {\n throw new TypeError(\"defineWorkflow requires a start function.\");\n }\n\n const workflow = ((input: TInput, invocationOptions?: WorkflowInvocationOptions) => {\n const makeInvocation = (postContinuation?: (output: TOutput) => unknown) => ({\n kind: \"workflowInvocation\" as const,\n workflow,\n input,\n ...(invocationOptions === undefined ? {} : { options: invocationOptions }),\n ...(postContinuation === undefined ? {} : { postContinuation }),\n post(continuation: (output: TOutput) => unknown) {\n return makeInvocation(continuation);\n },\n });\n\n return makeInvocation();\n }) as unknown as DefinedWorkflow<TInput, TOutput>;\n\n return Object.assign(workflow, options);\n}\n\nfunction assertBuilderObject(\n value: unknown,\n builderName: string,\n): asserts value is { readonly id: string } {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n throw new TypeError(`${builderName} requires a single object argument.`);\n }\n if (typeof (value as { readonly id?: unknown }).id !== \"string\") {\n throw new TypeError(`${builderName} requires an id string.`);\n }\n}\n","import type { PlainObject } from \"../../contracts/shapes/shape.types.js\";\nimport { runContextStorage } from \"../../runtime/run-context/run-context-storage.js\";\n\nexport type DeepReadonly<T> = T extends (...args: never[]) => unknown\n ? T\n : T extends readonly (infer U)[]\n ? readonly DeepReadonly<U>[]\n : T extends object\n ? { readonly [K in keyof T]: DeepReadonly<T[K]> }\n : T;\n\nexport interface WorkflowInputApi<TInput extends PlainObject = PlainObject> {\n input(): Promise<DeepReadonly<TInput>>;\n input<TOverrideInput extends PlainObject>(): Promise<DeepReadonly<TOverrideInput>>;\n inputValue<TKey extends keyof TInput & string>(key: TKey): Promise<DeepReadonly<TInput[TKey]>>;\n inputValue<TOverrideInput extends PlainObject, TKey extends keyof TOverrideInput & string>(\n key: TKey,\n ): Promise<DeepReadonly<TOverrideInput[TKey]>>;\n withInput<TTypedInput extends PlainObject>(): WorkflowInputApi<TTypedInput>;\n}\n\nexport const workflow: WorkflowInputApi = createWorkflowInputApi<PlainObject>();\n\nfunction createWorkflowInputApi<TInput extends PlainObject>(): WorkflowInputApi<TInput> {\n return {\n async input() {\n return cloneAndFreeze(readWorkflowInput());\n },\n async inputValue(key: string) {\n const input = readWorkflowInput();\n return cloneAndFreeze(input[key]);\n },\n withInput<TTypedInput extends PlainObject>(): WorkflowInputApi<TTypedInput> {\n return createWorkflowInputApi<TTypedInput>();\n },\n } as WorkflowInputApi<TInput>;\n}\n\nfunction readWorkflowInput(): PlainObject {\n const runContext = runContextStorage.getStore();\n if (!runContext) {\n throw new Error(\"workflow.input() called outside an active TrailStep run.\");\n }\n\n const input = runContext.events?.().find((event) => event.type === \"workflow.started\")\n ?.payload.input;\n if (!isPlainObject(input)) {\n throw new Error(\"workflow input is not available in the active TrailStep run.\");\n }\n\n return input;\n}\n\nfunction cloneAndFreeze<T>(value: T): DeepReadonly<T> {\n return deepFreeze(structuredClone(value)) as DeepReadonly<T>;\n}\n\nfunction deepFreeze<T>(value: T): T {\n if (typeof value !== \"object\" || value === null) {\n return value;\n }\n\n Object.freeze(value);\n for (const property of Object.values(value)) {\n deepFreeze(property);\n }\n\n return value;\n}\n\nfunction isPlainObject(value: unknown): value is PlainObject {\n return (\n typeof value === \"object\" &&\n value !== null &&\n !Array.isArray(value) &&\n Object.getPrototypeOf(value) === Object.prototype\n );\n}\n","import { lte } from \"semver\";\n\nimport type {\n DeprecationEntry,\n DeprecationManifest,\n DeprecationStatus,\n DeprecationTargetPackage,\n} from \"./deprecations.types.js\";\n\n// Scaffolding only — genuinely empty. No deprecation exists yet in this codebase. Real entries get\n// appended here the day a real breaking change to @trailstep/core or @trailstep/authoring's authoring API\n// actually happens. Do not add a fake/example entry to this array.\nexport const deprecationManifest: DeprecationManifest = [];\n\nexport interface FindDeprecationsAsOfQuery {\n readonly package: DeprecationTargetPackage;\n readonly version: string;\n}\n\n/**\n * Returns every manifest entry for query.package whose deprecatedSince is at or before\n * query.version, tagged with a severity. Calling this once with version set to a target\n * version naturally captures every entry between the installed version and the target, no matter\n * how many majors are being skipped in one update.\n */\nexport function findDeprecationsAsOf(\n manifest: DeprecationManifest,\n query: FindDeprecationsAsOfQuery,\n): readonly DeprecationStatus[] {\n return manifest\n .filter((entry) => entry.package === query.package && lte(entry.deprecatedSince, query.version))\n .map((entry) => toDeprecationStatus(entry, query.version));\n}\n\nfunction toDeprecationStatus(entry: DeprecationEntry, version: string): DeprecationStatus {\n const isRemoved = entry.removedIn !== undefined && lte(entry.removedIn, version);\n return { ...entry, severity: isRemoved ? \"blocking\" : \"warning\" };\n}\n","import { mkdir, readFile, writeFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\n\nexport const CANCELLATION_MARKER_FILE = \"cancel.json\";\n\nexport interface CancellationMarker {\n readonly requestedAt?: string;\n readonly reason?: string;\n readonly source?: string;\n}\n\nexport class WorkflowCancellationError extends Error {\n readonly cancellation: CancellationMarker;\n\n constructor(cancellation: CancellationMarker = {}) {\n super(\"Workflow cancellation requested.\");\n this.name = \"WorkflowCancellationError\";\n this.cancellation = cancellation;\n }\n}\n\nexport function cancellationMarkerPath(runDir: string): string {\n return join(runDir, CANCELLATION_MARKER_FILE);\n}\n\nexport async function readCancellationMarker(\n runDir: string,\n): Promise<CancellationMarker | undefined> {\n let contents: string;\n try {\n contents = await readFile(cancellationMarkerPath(runDir), \"utf8\");\n } catch (error) {\n if (isNodeError(error) && error.code === \"ENOENT\") {\n return undefined;\n }\n throw error;\n }\n\n try {\n return normalizeCancellationMarker(JSON.parse(contents));\n } catch {\n return {};\n }\n}\n\nexport async function writeCancellationMarker(options: {\n readonly runDir: string;\n readonly reason?: string;\n readonly source?: string;\n readonly requestedAt?: Date;\n}): Promise<{ readonly marker: CancellationMarker; readonly alreadyExisted: boolean }> {\n const marker: CancellationMarker = {\n requestedAt: (options.requestedAt ?? new Date()).toISOString(),\n ...(options.reason === undefined ? {} : { reason: options.reason }),\n ...(options.source === undefined ? {} : { source: options.source }),\n };\n const path = cancellationMarkerPath(options.runDir);\n\n try {\n await mkdir(options.runDir, { recursive: true });\n await writeFile(path, `${JSON.stringify(marker, null, 2)}\\n`, { flag: \"wx\" });\n return { marker, alreadyExisted: false };\n } catch (error) {\n if (isNodeError(error) && error.code === \"EEXIST\") {\n return { marker: (await readCancellationMarker(options.runDir)) ?? {}, alreadyExisted: true };\n }\n throw error;\n }\n}\n\nexport function cancellationPayload(cancellation: CancellationMarker): Record<string, unknown> {\n return {\n ...(cancellation.requestedAt === undefined ? {} : { requestedAt: cancellation.requestedAt }),\n ...(cancellation.reason === undefined ? {} : { reason: cancellation.reason }),\n ...(cancellation.source === undefined ? {} : { source: cancellation.source }),\n };\n}\n\nexport function isWorkflowCancellationError(error: unknown): error is WorkflowCancellationError {\n return error instanceof WorkflowCancellationError;\n}\n\nexport function throwIfCancellationRequested(cancellation: CancellationMarker | undefined): void {\n if (cancellation !== undefined) {\n throw new WorkflowCancellationError(cancellation);\n }\n}\n\nfunction normalizeCancellationMarker(value: unknown): CancellationMarker {\n if (!isPlainObject(value)) {\n return {};\n }\n\n return {\n ...(typeof value.requestedAt === \"string\" ? { requestedAt: value.requestedAt } : {}),\n ...(typeof value.reason === \"string\" ? { reason: value.reason } : {}),\n ...(typeof value.source === \"string\" ? { source: value.source } : {}),\n };\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return (\n typeof value === \"object\" &&\n value !== null &&\n !Array.isArray(value) &&\n Object.getPrototypeOf(value) === Object.prototype\n );\n}\n\nfunction isNodeError(error: unknown): error is NodeJS.ErrnoException {\n return error instanceof Error && \"code\" in error;\n}\n","export interface RetryPolicy {\n readonly maxAttempts: number;\n}\n\nexport interface RetryPolicyInput {\n readonly maxAttempts?: unknown;\n}\n\nexport interface ResolveRetryPolicyOptions {\n readonly global?: RetryPolicyInput;\n readonly workflow?: RetryPolicyInput;\n readonly step?: RetryPolicyInput;\n}\n\nconst BUILT_IN_RETRY_POLICY: RetryPolicy = { maxAttempts: 2 };\n\nexport function resolveRetryPolicy(options: ResolveRetryPolicyOptions): RetryPolicy {\n return validateRetryPolicy(\n firstConfiguredPolicy(options.step, options.workflow, options.global) ?? BUILT_IN_RETRY_POLICY,\n );\n}\n\nexport function validateRetryPolicy(input: RetryPolicyInput): RetryPolicy {\n const maxAttempts = input.maxAttempts ?? BUILT_IN_RETRY_POLICY.maxAttempts;\n\n if (typeof maxAttempts !== \"number\" || !Number.isInteger(maxAttempts) || maxAttempts < 1) {\n throw new TypeError(\"retry.maxAttempts must be an integer greater than or equal to 1.\");\n }\n\n return { maxAttempts };\n}\n\nfunction firstConfiguredPolicy(\n ...policies: readonly (RetryPolicyInput | undefined)[]\n): RetryPolicyInput | undefined {\n return policies.find((policy) => policy?.maxAttempts !== undefined);\n}\n","import { readFile } from \"node:fs/promises\";\nimport { basename, join } from \"node:path\";\nimport { normalizeShape } from \"../../authoring/shape/json-schema.js\";\nimport type { ContinuationResult } from \"../../authoring/step/continuation.types.js\";\nimport type { Failure } from \"../../contracts/failures/failure.js\";\nimport type { PlainObject } from \"../../contracts/shapes/shape.types.js\";\nimport type {\n Event,\n Result,\n RunWorkflowOptions,\n} from \"../../runtime/run-workflow/run-workflow.types.js\";\nimport { appendEvent, readRunState, writeRunState } from \"../artifacts/run-storage.js\";\nimport {\n type CancellationMarker,\n cancellationPayload,\n isWorkflowCancellationError,\n readCancellationMarker,\n} from \"../cancellation/cancellation.js\";\nimport { runContinuation } from \"../continuation/run-continuation/run-continuation.js\";\nimport { createEvent } from \"../events/create-run-event.js\";\nimport { isFailureLikeError } from \"../failures/failure-like.js\";\nimport { workflowFailure } from \"../failures/workflow-failure.js\";\nimport {\n findDanglingInteractiveSessionStart,\n reattachInProgressStep,\n} from \"../resume/reattach-in-progress-step/reattach-in-progress-step.js\";\nimport { replayToFailedStep } from \"../resume/replay-to-failed-step/replay-to-failed-step.js\";\nimport {\n type ReplayToWaitingStepResult,\n replayToWaitingStep,\n} from \"../resume/replay-to-waiting-step/replay-to-waiting-step.js\";\nimport { replayToRetryFailure } from \"../retry/replay-to-retry-failure.js\";\nimport { createRunContext } from \"../run-context/create-run-context.js\";\nimport { runContextStorage } from \"../run-context/run-context-storage.js\";\nimport { resolveAndValidateRunCwds } from \"./cwd.js\";\nimport { initializeRun } from \"./initialize-run.js\";\nimport { runRootContinuationArrayScheduler } from \"./root-continuation-array-scheduler.js\";\nimport { parseTrailStepConfigInput } from \"./trailstep-config-input.js\";\n\nexport async function runWorkflow<TInput extends PlainObject, TOutput extends PlainObject>(\n options: RunWorkflowOptions<TInput, TOutput>,\n): Promise<Result<TOutput>> {\n const maxSteps = options.maxSteps ?? 1000;\n const isResume = options.resume !== undefined;\n const isRetry = options.retry !== undefined;\n const isWaitContinue = options.continue !== undefined;\n const initialized = await initializeRun(options).catch((error) => {\n const existingRunDir =\n options.resume?.runDir ?? options.retry?.runDir ?? options.continue?.runDir;\n if (existingRunDir && isFailureLikeError(error)) {\n return {\n status: \"failure\" as const,\n runId: basename(existingRunDir),\n runName: basename(existingRunDir),\n runDir: existingRunDir,\n previousEvents: [],\n failure: workflowFailure(error),\n };\n }\n\n throw error;\n });\n\n if (\"status\" in initialized && initialized.status === \"failure\") {\n return {\n status: \"failure\",\n runId: initialized.runId,\n runDir: initialized.runDir,\n failure: initialized.failure,\n events: initialized.previousEvents,\n };\n }\n\n const { runId, runName, runDir, previousEvents } = initialized;\n const trailstepConfig =\n options.trailstepConfig === undefined\n ? undefined\n : parseTrailStepConfigInput(options.trailstepConfig);\n const { projectCwd, cwd } = await resolveAndValidateRunCwds(options);\n const events: Event[] = [...previousEvents];\n\n const emit = async (event: Event): Promise<void> => {\n events.push(event);\n await appendEvent(runDir, event);\n await options.eventSink?.(event);\n };\n\n const runContext = createRunContext({\n runId,\n runName,\n runDir,\n workflowId: options.workflow.id,\n workflowAgents: options.workflow.agents ?? {},\n projectCwd,\n cwd,\n executionCwd: cwd,\n trailstepConfig,\n workingAgentProcessRunner: options.workingAgentProcessRunner,\n providerWorkingRunner: options.providerWorkingRunner,\n emit,\n events: () => events,\n ...(isResume || isRetry ? { initialState: {} } : {}),\n });\n\n const cancelWorkflow = async (cancellation: CancellationMarker): Promise<Result<TOutput>> => {\n if (!events.some((event) => event.type === \"workflow.cancelRequested\")) {\n await emit(\n createEvent({\n runId,\n workflowId: options.workflow.id,\n type: \"workflow.cancelRequested\",\n payload: cancellationPayload(cancellation),\n }),\n );\n }\n\n if (!events.some((event) => event.type === \"workflow.cancelled\")) {\n await emit(\n createEvent({\n runId,\n workflowId: options.workflow.id,\n type: \"workflow.cancelled\",\n payload: cancellationPayload(cancellation),\n }),\n );\n }\n\n return {\n status: \"cancelled\",\n runId,\n runDir,\n cancellation,\n events,\n } as unknown as Result<TOutput>;\n };\n\n const failWorkflow = async (failure: Failure, message?: string): Promise<Result<TOutput>> => {\n await emit(\n createEvent({\n runId,\n workflowId: options.workflow.id,\n type: \"workflow.failed\",\n payload: {\n failure,\n ...(message === undefined ? {} : { message }),\n },\n }),\n );\n return {\n status: \"failure\",\n runId,\n runDir,\n failure,\n events,\n };\n };\n\n const failResumeValidation = (failure: Failure): Result<TOutput> => ({\n status: \"failure\",\n runId,\n runDir,\n failure,\n events,\n });\n\n try {\n return await runContextStorage.run(runContext, () => runWorkflowBody());\n } catch (error) {\n if (isWorkflowCancellationError(error)) {\n return await cancelWorkflow(error.cancellation);\n }\n\n return await failWorkflow(workflowFailure(error));\n }\n\n async function runWorkflowBody(): Promise<Result<TOutput>> {\n const inputSchema = options.workflow.inputShape\n ? normalizeShape(options.workflow.inputShape)\n : options.workflow.input;\n\n const previousTerminalStatus = readPreviousTerminalWorkflowStatus(previousEvents);\n const existingCancellation = readExistingCancellationEvent(previousEvents);\n const cancellation =\n previousTerminalStatus === undefined || previousTerminalStatus === \"cancelled\"\n ? (existingCancellation ?? (await readCancellationMarker(runDir)))\n : undefined;\n if (cancellation !== undefined) {\n return await cancelWorkflow(cancellation);\n }\n\n let workflowInput: TInput;\n let startNode: ContinuationResult | undefined;\n let waitResume: ReplayToWaitingStepResult | undefined;\n let isTrackRetry = false;\n\n if (isResume) {\n const danglingAnchor = findDanglingInteractiveSessionStart(previousEvents);\n const replay = await replayWithoutClobberingStateOnFailure(runDir, () =>\n danglingAnchor\n ? reattachInProgressStep({\n workflow: options.workflow,\n events: previousEvents,\n runDir,\n })\n : replayToFailedStep({\n workflow: options.workflow,\n events: previousEvents,\n runDir,\n }),\n );\n if (replay.status === \"failure\") {\n return failResumeValidation(replay.failure);\n }\n await runContext.state.hydratePersisted();\n\n workflowInput = inputSchema\n ? (inputSchema.assert(replay.input, \"workflow input\") as TInput)\n : (replay.input as TInput);\n startNode = replay.node;\n await emit(\n createEvent({\n runId,\n workflowId: options.workflow.id,\n type: \"workflow.resumed\",\n payload: {\n resumedFromRunDir: runDir,\n resumedStepId: replay.resumedStepId,\n sourceFailureEventId: replay.sourceFailureEventId,\n },\n }),\n );\n } else if (isWaitContinue) {\n if (await hasSupportedRootParallelTrackRetryMetadata(runDir)) {\n return failResumeValidation({\n code: \"continue_parallel_track_unsupported\",\n message:\n \"Continuing a waiting parallel track is not yet supported; retry the run or restart the workflow instead.\",\n });\n }\n\n const replay = await replayWithoutClobberingStateOnFailure(runDir, () =>\n replayToWaitingStep({\n workflow: options.workflow,\n events: previousEvents,\n runDir,\n }),\n );\n if (replay.status === \"failure\") {\n return failResumeValidation(replay.failure);\n }\n await runContext.state.hydratePersisted();\n\n workflowInput = inputSchema\n ? (inputSchema.assert(replay.input, \"workflow input\") as TInput)\n : (replay.input as TInput);\n startNode = replay.node;\n waitResume = replay;\n await emit(\n createEvent({\n runId,\n workflowId: options.workflow.id,\n type: \"workflow.resumed\",\n payload: {\n resumeKind: \"wait\",\n resumedFromRunDir: runDir,\n resumedStepId: replay.resumedStepId,\n sourceWaitEventId: replay.sourceWaitEventId,\n },\n }),\n );\n } else if (isRetry) {\n if (await hasSupportedRootParallelTrackRetryMetadata(runDir)) {\n const persistedInput = readWorkflowStartedInput(previousEvents);\n if (persistedInput === undefined) {\n return failResumeValidation({\n code: \"retry_target_not_found\",\n message: \"workflow.started payload is missing input.\",\n });\n }\n await runContext.state.hydratePersisted();\n await runContext.globalState.hydratePersisted();\n workflowInput = inputSchema\n ? (inputSchema.assert(persistedInput, \"workflow input\") as TInput)\n : (persistedInput as TInput);\n isTrackRetry = true;\n await emit(\n createEvent({\n runId,\n workflowId: options.workflow.id,\n type: \"workflow.retryStarted\",\n payload: {\n retryKind: options.retry.kind,\n retryPlanner: \"track\",\n retriedFromRunDir: runDir,\n },\n }),\n );\n } else {\n const replay = await replayWithoutClobberingStateOnFailure(runDir, () =>\n replayToRetryFailure({\n workflow: options.workflow,\n events: previousEvents,\n runDir,\n }),\n );\n if (replay.status === \"failure\") {\n return failResumeValidation(replay.failure);\n }\n await runContext.state.hydratePersisted();\n\n workflowInput = inputSchema\n ? (inputSchema.assert(replay.input, \"workflow input\") as TInput)\n : (replay.input as TInput);\n startNode = replay.node;\n await emit(\n createEvent({\n runId,\n workflowId: options.workflow.id,\n type: \"workflow.retryStarted\",\n payload: {\n retryKind: options.retry.kind,\n retriedFromRunDir: runDir,\n retriedStepId: replay.retriedStepId,\n sourceFailureEventId: replay.sourceFailureEventId,\n sourceFailureReplayPosition: replay.sourceFailureReplayPosition,\n },\n }),\n );\n }\n } else {\n workflowInput = inputSchema\n ? inputSchema.assert(options.input, \"workflow input\")\n : (options.input as TInput);\n await emit(\n createEvent({\n runId,\n workflowId: options.workflow.id,\n type: \"workflow.started\",\n payload: { input: workflowInput },\n }),\n );\n }\n\n const rootNode = startNode ?? options.workflow.start(workflowInput);\n const rootNodes = Array.isArray(rootNode) ? rootNode : [rootNode];\n const shouldUseRootArrayScheduler = (!isResume && !isRetry && !isWaitContinue) || isTrackRetry;\n const continuationResult = shouldUseRootArrayScheduler\n ? await runRootContinuationArrayScheduler({\n nodes: rootNodes,\n ...(Array.isArray(rootNode) ? { rootIsArray: true } : {}),\n runId,\n workflowId: options.workflow.id,\n emit,\n maxSteps,\n initialSource: `workflow.start for workflow ${options.workflow.id}`,\n workers: options.scheduler?.workers,\n workflowAgents: options.workflow.agents ?? {},\n workflowTimeout: options.workflow.timeout,\n runDir,\n projectCwd,\n cwd,\n trailstepConfig,\n workingAgentProcessRunner: options.workingAgentProcessRunner,\n providerWorkingRunner: options.providerWorkingRunner,\n processRunner: options.processRunner,\n ...(isTrackRetry\n ? {\n retry: {\n initialExecutedSteps: previousEvents.filter(\n (event) => event.type === \"step.started\",\n ).length,\n track: options.retry?.track,\n },\n }\n : {}),\n })\n : await runContinuation({\n node: rootNode,\n runId,\n workflowId: options.workflow.id,\n emit,\n maxSteps,\n initialSource: isRetry\n ? `retry for workflow ${options.workflow.id}`\n : isResume\n ? `resume for workflow ${options.workflow.id}`\n : `workflow.start for workflow ${options.workflow.id}`,\n // The original run already used one step-index slot per step.started\n // event ever recorded (successful or failed) -- newly-dispatched steps\n // after resume must continue that sequence, not restart at 1, or their\n // artifact directories collide with the pre-resume steps' directories.\n initialExecutedSteps:\n isResume || isRetry || isWaitContinue\n ? previousEvents.filter((event) => event.type === \"step.started\").length\n : undefined,\n ...(waitResume === undefined\n ? {}\n : {\n resumeWait: {\n stepId: waitResume.resumedStepId,\n stepIndex: waitResume.stepIndex,\n phaseIndex: waitResume.phaseIndex,\n phaseValue: waitResume.phaseValue,\n waitOutputs: waitResume.waitOutputs,\n seenWaitIds: waitResume.seenWaitIds,\n wait: waitResume.wait,\n },\n }),\n workflowAgents: options.workflow.agents ?? {},\n workflowTimeout: options.workflow.timeout,\n runDir,\n projectCwd,\n cwd,\n trailstepConfig,\n workingAgentProcessRunner: options.workingAgentProcessRunner,\n providerWorkingRunner: options.providerWorkingRunner,\n processRunner: options.processRunner,\n });\n\n if (\n continuationResult.status === \"failure\" ||\n continuationResult.status === \"absoluteFailure\"\n ) {\n return await failWorkflow(continuationResult.failure, continuationResult.message);\n }\n\n if (continuationResult.status === \"cancelled\") {\n return await cancelWorkflow(continuationResult.cancellation);\n }\n\n if (continuationResult.status === \"waiting\") {\n return {\n status: \"waiting\",\n runId,\n runDir,\n wait: continuationResult.wait,\n events,\n } as unknown as Result<TOutput>;\n }\n\n if (continuationResult.status === \"split\") {\n return await failWorkflow({\n code: \"unsupported_continuation\",\n message: \"A continuation array escaped workflow scheduling.\",\n });\n }\n\n const current = continuationResult.output;\n\n const outputSchema = options.workflow.outputShape\n ? normalizeShape(options.workflow.outputShape)\n : options.workflow.output;\n const output = (\n outputSchema ? outputSchema.assert(current, \"workflow output\") : current\n ) as TOutput;\n\n await emit(\n createEvent({\n runId,\n workflowId: options.workflow.id,\n type: \"workflow.completed\",\n payload: {\n output,\n ...(continuationResult.message === undefined\n ? {}\n : { message: continuationResult.message }),\n },\n }),\n );\n\n return {\n status: \"success\",\n runId,\n runDir,\n output,\n events,\n };\n }\n}\n\nasync function replayWithoutClobberingStateOnFailure<T extends { readonly status: string }>(\n runDir: string,\n replay: () => Promise<T>,\n): Promise<T> {\n const stateBeforeReplay = await readRunState(runDir);\n const result = await replay();\n if (result.status === \"failure\") {\n await writeRunState(runDir, stateBeforeReplay);\n }\n return result;\n}\n\nasync function hasSupportedRootParallelTrackRetryMetadata(runDir: string): Promise<boolean> {\n try {\n const track = JSON.parse(await readFile(join(runDir, \"track.json\"), \"utf8\")) as {\n readonly rootBranchId?: unknown;\n readonly splitOccurred?: unknown;\n readonly branches?: unknown;\n };\n if (\n track.splitOccurred !== true ||\n typeof track.rootBranchId !== \"string\" ||\n !Array.isArray(track.branches) ||\n !track.branches.every((branchId): branchId is string => typeof branchId === \"string\")\n ) {\n return false;\n }\n\n const branches = await Promise.all(\n track.branches.map(async (branchId) => {\n const branch = JSON.parse(\n await readFile(join(runDir, \"branches\", `${branchId}.json`), \"utf8\"),\n ) as { readonly branchId?: unknown; readonly parentBranchId?: unknown };\n return branch;\n }),\n );\n\n return branches.every((branch) =>\n branch.branchId === track.rootBranchId\n ? branch.parentBranchId === undefined\n : branch.parentBranchId === track.rootBranchId,\n );\n } catch (error) {\n if (error instanceof Error && \"code\" in error && error.code === \"ENOENT\") {\n return false;\n }\n throw error;\n }\n}\n\nfunction readWorkflowStartedInput(events: readonly Event[]): PlainObject | undefined {\n const started = events.find((event) => event.type === \"workflow.started\");\n const input = started?.payload.input;\n return typeof input === \"object\" && input !== null && !Array.isArray(input)\n ? (input as PlainObject)\n : undefined;\n}\n\nfunction readPreviousTerminalWorkflowStatus(\n events: readonly Event[],\n): \"completed\" | \"failed\" | \"cancelled\" | undefined {\n for (let index = events.length - 1; index >= 0; index -= 1) {\n const event = events[index];\n if (event?.type === \"workflow.completed\") {\n return \"completed\";\n }\n if (event?.type === \"workflow.failed\") {\n return \"failed\";\n }\n if (event?.type === \"workflow.cancelled\") {\n return \"cancelled\";\n }\n }\n\n return undefined;\n}\n\nfunction readExistingCancellationEvent(events: readonly Event[]): CancellationMarker | undefined {\n for (let index = events.length - 1; index >= 0; index -= 1) {\n const event = events[index];\n if (event?.type !== \"workflow.cancelled\") {\n continue;\n }\n\n return cancellationFromPayload(event.payload);\n }\n\n return undefined;\n}\n\nfunction cancellationFromPayload(payload: Record<string, unknown>): CancellationMarker {\n return {\n ...(typeof payload.requestedAt === \"string\" ? { requestedAt: payload.requestedAt } : {}),\n ...(typeof payload.reason === \"string\" ? { reason: payload.reason } : {}),\n ...(typeof payload.source === \"string\" ? { source: payload.source } : {}),\n };\n}\n","import { mkdir, readFile, writeFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { dispatchAgentStep } from \"../../../agent-execution/dispatch-agent-step/dispatch-agent-step.js\";\nimport type { TrailStepConfig } from \"../../../agent-targeting/targeting.types.js\";\nimport { jsonSchema, normalizeShape } from \"../../../authoring/shape/json-schema.js\";\nimport type {\n CheckWaitHelpers,\n ContinuationResult,\n DisplayPhase,\n ParallelOptions,\n PromptPhase,\n StepCwdInput,\n StepDisplayValue,\n StepNode,\n WaitCheckResult,\n WaitDefinition,\n WaitPhase,\n} from \"../../../authoring/step/continuation.types.js\";\nimport {\n done,\n firstPromptPhase,\n getStepPhases,\n isAbsoluteDoneNode,\n isAbsoluteFailNode,\n isDoneNode,\n isFailNode,\n isParallelNode,\n isStepNode,\n isWorkflowInvocationNode,\n} from \"../../../authoring/step/step-node.js\";\nimport type { WorkflowAgentRole } from \"../../../contracts/agents/agent-role.types.js\";\nimport type { Failure } from \"../../../contracts/failures/failure.js\";\nimport { TrailStepFailureError } from \"../../../contracts/failures/failure.js\";\nimport type { PlainObject } from \"../../../contracts/shapes/shape.types.js\";\nimport type {\n Event,\n RunWorkflowOptions,\n} from \"../../../runtime/run-workflow/run-workflow.types.js\";\nimport {\n resolveStepArtifactPaths,\n resolveWaitArtifactPaths,\n type WaitArtifactPaths,\n} from \"../../artifacts/step-artifacts.js\";\nimport {\n type CancellationMarker,\n cancellationPayload,\n isWorkflowCancellationError,\n readCancellationMarker,\n throwIfCancellationRequested,\n WorkflowCancellationError,\n} from \"../../cancellation/cancellation.js\";\nimport { createEvent } from \"../../events/create-run-event.js\";\nimport { stepExecutionFailure } from \"../../failures/step-execution-failure.js\";\nimport { runContextStorage } from \"../../run-context/run-context-storage.js\";\nimport { withStepContext } from \"../../run-context/with-step-context.js\";\nimport { validateDirectoryCwd } from \"../../run-workflow/cwd.js\";\nimport type { TimeoutPolicyInput } from \"../../timeout/timeout-policy.js\";\nimport { resolveTimeoutPolicy } from \"../../timeout/timeout-policy.js\";\nimport { resolveStepOutputSchema } from \"../resolve-step-output-schema/resolve-step-output-schema.js\";\n\nexport interface RunContinuationOptions {\n readonly node: ContinuationResult;\n readonly runId: string;\n readonly workflowId: string;\n readonly emit: (event: Event) => Promise<void>;\n readonly maxSteps: number;\n readonly initialSource: string;\n readonly initialExecutedSteps?: number;\n readonly allocateStepIndex?: () => number;\n readonly workflowAgents: Readonly<Record<string, WorkflowAgentRole>>;\n readonly workflowTimeout?: TimeoutPolicyInput;\n readonly runDir: string;\n readonly projectCwd?: string;\n readonly cwd: string;\n readonly trailstepConfig?: TrailStepConfig;\n readonly workingAgentProcessRunner?: RunWorkflowOptions[\"workingAgentProcessRunner\"];\n readonly providerWorkingRunner?: RunWorkflowOptions[\"providerWorkingRunner\"];\n readonly processRunner?: RunWorkflowOptions[\"processRunner\"];\n readonly resumeWait?: ResumeWaitOptions;\n readonly returnContinuationArrays?: boolean;\n}\n\nexport interface ResumeWaitOptions {\n readonly stepId: string;\n readonly stepIndex: number;\n readonly phaseIndex: number;\n readonly phaseValue: PlainObject;\n readonly waitOutputs: Readonly<Record<string, PlainObject>>;\n readonly seenWaitIds: readonly string[];\n readonly wait: ResumedWaitDetails;\n}\n\ntype WaitKind = \"input\" | \"check\";\n\nexport interface ResumedWaitDetails {\n readonly waitId: string;\n readonly kind: WaitKind;\n readonly message: string;\n readonly artifactPaths: WaitArtifactPaths;\n readonly outputSchema: Record<string, unknown>;\n}\n\nexport interface WaitingWait {\n readonly stepId: string;\n readonly waitId: string;\n readonly kind?: WaitKind;\n readonly message: string;\n readonly retryAfterSeconds?: number;\n readonly artifactPaths: WaitArtifactPaths;\n}\n\ninterface WorkflowInvocationFrame {\n readonly workflowId: string;\n readonly workflowAgents: Readonly<Record<string, WorkflowAgentRole>>;\n readonly workflowTimeout?: TimeoutPolicyInput;\n readonly workflowOutputSchema?: ReturnType<typeof normalizeShape>;\n readonly invocationWorkflowId: string;\n readonly postContinuation?: (\n output: PlainObject,\n ) => ContinuationResult | Promise<ContinuationResult>;\n}\n\nexport type RunContinuationResult =\n | { readonly status: \"success\"; readonly output: PlainObject; readonly message?: string }\n | { readonly status: \"failure\"; readonly failure: Failure; readonly message?: string }\n | { readonly status: \"absoluteSuccess\"; readonly output: PlainObject; readonly message?: string }\n | { readonly status: \"absoluteFailure\"; readonly failure: Failure; readonly message?: string }\n | { readonly status: \"waiting\"; readonly wait: WaitingWait }\n | { readonly status: \"cancelled\"; readonly cancellation: CancellationMarker }\n | {\n readonly status: \"split\";\n readonly nodes: readonly ContinuationResult[];\n readonly source: string;\n readonly parallelOptions?: ParallelOptions;\n readonly postContinuation?: (\n output: PlainObject,\n ) => ContinuationResult | Promise<ContinuationResult>;\n readonly afterPostContinuation?: (\n output: PlainObject,\n ) => ContinuationResult | Promise<ContinuationResult>;\n };\n\nexport async function runContinuation(\n options: RunContinuationOptions,\n): Promise<RunContinuationResult> {\n let node: ContinuationResult = options.node;\n let source = options.initialSource;\n // A resumed run's newly-dispatched steps must continue the on-disk step\n // index sequence from where the original run left off (every step.started\n // ever recorded, successful or failed), not restart at 1 -- otherwise their\n // artifact directories collide with/shadow the pre-resume steps' dirs.\n let executedSteps = options.initialExecutedSteps ?? 0;\n let pendingResumeWait = options.resumeWait;\n const trailstepConfig = options.trailstepConfig;\n const invocationFrames: WorkflowInvocationFrame[] = [];\n let currentWorkflowId = options.workflowId;\n let currentWorkflowAgents = options.workflowAgents;\n let currentWorkflowTimeout = options.workflowTimeout;\n let currentWorkflowOutputSchema: ReturnType<typeof normalizeShape> | undefined;\n\n const splitPostContinuationForInvocationFrames = ():\n | ((output: PlainObject) => ContinuationResult | Promise<ContinuationResult>)\n | undefined => {\n if (invocationFrames.length === 0) {\n return undefined;\n }\n\n const frames = [...invocationFrames];\n const splitWorkflowOutputSchema = currentWorkflowOutputSchema;\n return async (aggregateOutput: PlainObject): Promise<ContinuationResult> => {\n let output: PlainObject;\n try {\n output =\n splitWorkflowOutputSchema === undefined\n ? aggregateOutput\n : splitWorkflowOutputSchema.assert(\n aggregateOutput,\n `invoked workflow ${frames[frames.length - 1]?.invocationWorkflowId ?? currentWorkflowId} output`,\n );\n } catch (error) {\n throw failureFromError(error);\n }\n\n while (frames.length > 0) {\n const frame = frames.pop();\n if (frame?.postContinuation !== undefined) {\n return await frame.postContinuation(output);\n }\n }\n\n return done(output);\n };\n };\n\n const splitPostContinuations = (\n postContinuation:\n | ((output: PlainObject) => ContinuationResult | Promise<ContinuationResult>)\n | undefined,\n ) => {\n const invocationPostContinuation = splitPostContinuationForInvocationFrames();\n if (postContinuation === undefined) {\n return invocationPostContinuation === undefined\n ? {}\n : { postContinuation: invocationPostContinuation };\n }\n return invocationPostContinuation === undefined\n ? { postContinuation }\n : { postContinuation, afterPostContinuation: invocationPostContinuation };\n };\n\n while (true) {\n const pendingCancellation = await readCancellationMarker(options.runDir);\n if (pendingCancellation !== undefined) {\n return { status: \"cancelled\", cancellation: pendingCancellation };\n }\n\n if (isDoneNode(node)) {\n const frame = invocationFrames.pop();\n if (frame !== undefined) {\n const invocationWorkflowId = frame.invocationWorkflowId;\n let output: PlainObject;\n try {\n output =\n currentWorkflowOutputSchema === undefined\n ? node.output\n : currentWorkflowOutputSchema.assert(\n node.output,\n `invoked workflow ${invocationWorkflowId} output`,\n );\n } catch (error) {\n return { status: \"failure\", failure: failureFromError(error) };\n }\n\n currentWorkflowId = frame.workflowId;\n currentWorkflowAgents = frame.workflowAgents;\n currentWorkflowTimeout = frame.workflowTimeout;\n currentWorkflowOutputSchema = frame.workflowOutputSchema;\n\n if (frame.postContinuation !== undefined) {\n try {\n node = await frame.postContinuation(output);\n } catch (error) {\n return {\n status: \"failure\",\n failure: stepExecutionFailure(\n new Error(\n `workflow invocation post failed for ${invocationWorkflowId}: ${errorMessage(error)}`,\n ),\n ),\n };\n }\n source = `post for workflow invocation ${invocationWorkflowId}`;\n continue;\n }\n\n return {\n status: \"success\",\n output,\n ...(node.message === undefined ? {} : { message: node.message }),\n };\n }\n\n return {\n status: \"success\",\n output: node.output,\n ...(node.message === undefined ? {} : { message: node.message }),\n };\n }\n\n if (isFailNode(node)) {\n return {\n status: \"failure\",\n failure: node.failure,\n ...(node.message === undefined ? {} : { message: node.message }),\n };\n }\n\n if (options.returnContinuationArrays === true && isAbsoluteDoneNode(node)) {\n return {\n status: \"absoluteSuccess\",\n output: node.output,\n ...(node.message === undefined ? {} : { message: node.message }),\n };\n }\n\n if (options.returnContinuationArrays === true && isAbsoluteFailNode(node)) {\n return {\n status: \"absoluteFailure\",\n failure: node.failure,\n ...(node.message === undefined ? {} : { message: node.message }),\n };\n }\n\n if (Array.isArray(node) && options.returnContinuationArrays === true) {\n return {\n status: \"split\",\n nodes: node,\n source,\n ...splitPostContinuations(undefined),\n };\n }\n\n if (isParallelNode(node) && options.returnContinuationArrays === true) {\n return {\n status: \"split\",\n nodes: node.nodes,\n source,\n ...(node.options === undefined ? {} : { parallelOptions: node.options }),\n ...splitPostContinuations(node.postContinuation),\n };\n }\n\n if (isWorkflowInvocationNode(node)) {\n const invocation = node;\n const inputSchema = invocation.workflow.inputShape\n ? normalizeShape(invocation.workflow.inputShape)\n : invocation.workflow.input;\n let input: PlainObject;\n try {\n input =\n inputSchema === undefined\n ? invocation.input\n : inputSchema.assert(\n invocation.input,\n `invoked workflow ${invocation.workflow.id} input`,\n );\n } catch (error) {\n return { status: \"failure\", failure: failureFromError(error) };\n }\n\n invocationFrames.push({\n workflowId: currentWorkflowId,\n workflowAgents: currentWorkflowAgents,\n ...(currentWorkflowTimeout === undefined\n ? {}\n : { workflowTimeout: currentWorkflowTimeout }),\n ...(currentWorkflowOutputSchema === undefined\n ? {}\n : { workflowOutputSchema: currentWorkflowOutputSchema }),\n invocationWorkflowId: invocation.workflow.id,\n ...(invocation.postContinuation === undefined\n ? {}\n : { postContinuation: invocation.postContinuation }),\n });\n currentWorkflowId = invocation.workflow.id;\n currentWorkflowAgents = invocation.workflow.agents ?? {};\n currentWorkflowTimeout = invocation.workflow.timeout;\n currentWorkflowOutputSchema = invocation.workflow.outputShape\n ? normalizeShape(invocation.workflow.outputShape)\n : invocation.workflow.output === undefined\n ? undefined\n : normalizeShape(invocation.workflow.output);\n node = invocation.workflow.start(input);\n source = `workflow.start for workflow ${invocation.workflow.id}`;\n continue;\n }\n\n const unsupportedFailure = unsupportedContinuationFailure(node, source);\n if (unsupportedFailure !== undefined) {\n return {\n status: \"failure\",\n failure: unsupportedFailure,\n };\n }\n\n if (!isStepNode(node)) {\n return {\n status: \"failure\",\n failure: continuationFailure(source),\n };\n }\n\n const stepNode = node;\n const { config } = stepNode;\n const resumeWait = pendingResumeWait;\n if (resumeWait !== undefined && resumeWait.stepId !== config.id) {\n return {\n status: \"failure\",\n failure: continuationFailure(`wait resume for step ${resumeWait.stepId}`),\n };\n }\n\n let stepIndex: number;\n if (resumeWait === undefined) {\n if (executedSteps >= options.maxSteps) {\n return {\n status: \"failure\",\n failure: stepExecutionFailure(\n new Error(`workflow exceeded maxSteps guard (${options.maxSteps})`),\n ),\n };\n }\n if (options.allocateStepIndex !== undefined) {\n stepIndex = options.allocateStepIndex();\n executedSteps += 1;\n } else {\n executedSteps += 1;\n stepIndex = executedSteps;\n }\n } else {\n stepIndex = resumeWait.stepIndex;\n pendingResumeWait = undefined;\n }\n const phases = getStepPhases(stepNode);\n const hasPrompt = phases.some((phase) => phase.kind === \"prompt\");\n const timeoutPolicy = resolveTimeoutPolicy({\n global: trailstepConfig?.settings?.timeout,\n workflow:\n currentWorkflowTimeout ??\n trailstepConfig?.workflows?.[currentWorkflowId]?.settings?.timeout,\n step: config.timeout,\n });\n const maxSubPrompts =\n firstPromptPhase(phases)?.maxSubPrompts ??\n config.maxSubPrompts ??\n trailstepConfig?.workflows?.[currentWorkflowId]?.settings?.maxSubPrompts;\n\n if (resumeWait === undefined) {\n await options.emit(\n createEvent({\n runId: options.runId,\n workflowId: currentWorkflowId,\n stepId: config.id,\n type: \"step.started\",\n payload: {\n stepName: config.id,\n ...(config.title === undefined ? {} : { title: config.title }),\n ...(config.description === undefined ? {} : { description: config.description }),\n kind: hasPrompt ? \"agent\" : \"code\",\n },\n }),\n );\n }\n\n try {\n const stepCwd = await resolveStepExecutionCwd({\n stepId: config.id,\n workflowId: currentWorkflowId,\n defaultCwd: options.cwd,\n input: config.input,\n cwdInput: config.cwd,\n });\n const stepArtifacts = resolveStepArtifactPaths({\n runDir: options.runDir,\n stepId: config.id,\n stepIndex,\n });\n\n const stepResult = await runWithStepControl({\n stepId: config.id,\n timeoutMs: timeoutPolicy.timeoutMs,\n readCancellation: async () => await readCancellationMarker(options.runDir),\n run: async (signal) =>\n await withStepContext(\n config.id,\n stepArtifacts.stepDir,\n async () => {\n const phaseResult = await runStepPhases({\n stepNode,\n timeoutMs: timeoutPolicy.timeoutMs,\n signal,\n readCancellation: async () => await readCancellationMarker(options.runDir),\n ...(resumeWait === undefined\n ? {}\n : {\n resume: {\n startPhaseIndex: resumeWait.phaseIndex,\n phaseValue: resumeWait.phaseValue,\n waitOutputs: resumeWait.waitOutputs,\n seenWaitIds: resumeWait.seenWaitIds,\n wait: resumeWait.wait,\n },\n }),\n emitDisplay: async (phase, output, phaseIndex) => {\n const payload = await resolveDisplayPayload({\n phase,\n input: config.input,\n output,\n phaseIndex,\n stepId: config.id,\n });\n\n await options.emit(\n createEvent({\n runId: options.runId,\n workflowId: currentWorkflowId,\n stepId: config.id,\n type: \"step.display\",\n payload,\n }),\n );\n },\n handleWait: async (phase, output, phaseIndex, waits, previousWaitId) => {\n return await handleWaitPhase({\n phase,\n input: config.input,\n output,\n waits,\n phaseIndex,\n previousWaitId,\n stepId: config.id,\n stepArtifactId: stepArtifacts.artifactStepId,\n runDir: options.runDir,\n runId: options.runId,\n workflowId: currentWorkflowId,\n emit: options.emit,\n });\n },\n handleResumedWait: async (wait) =>\n await handleResumedWaitPhase({\n wait,\n stepId: config.id,\n runDir: options.runDir,\n runId: options.runId,\n workflowId: currentWorkflowId,\n emit: options.emit,\n }),\n dispatchPrompt: async (phase) => {\n const outputSchema = resolveStepOutputSchema(phase);\n if (!outputSchema) {\n throw new Error(`step ${config.id} with a prompt requires an output shape`);\n }\n\n const rawOutput = await dispatchAgentStep({\n config: { ...config, ...phase },\n outputSchema,\n interactiveOutputMode:\n phase.mode === \"interactive\" && phase.output !== undefined\n ? \"json\"\n : \"session-file\",\n runId: options.runId,\n workflowId: currentWorkflowId,\n emit: options.emit,\n workflowAgents: currentWorkflowAgents,\n runDir: options.runDir,\n projectCwd: options.projectCwd ?? options.cwd,\n cwd: stepCwd,\n trailstepConfig,\n workingAgentProcessRunner: options.workingAgentProcessRunner,\n providerWorkingRunner: options.providerWorkingRunner,\n processRunner: options.processRunner,\n stepIndex,\n signal,\n });\n throwIfStepTimedOut(signal, config.id, timeoutPolicy.timeoutMs);\n const output = outputSchema.assert(rawOutput, `step ${config.id} output`);\n\n await options.emit(\n createEvent({\n runId: options.runId,\n workflowId: currentWorkflowId,\n stepId: config.id,\n type: \"step.completed\",\n payload: { output },\n }),\n );\n\n return output;\n },\n });\n\n if (phaseResult.status === \"waiting\") {\n return phaseResult;\n }\n\n const nextNode = phaseResult.node;\n if (isFailNode(nextNode)) {\n await options.emit(\n createEvent({\n runId: options.runId,\n workflowId: currentWorkflowId,\n stepId: config.id,\n type: \"step.failed\",\n payload: { failure: nextNode.failure },\n }),\n );\n return phaseResult;\n }\n\n if (!hasPrompt) {\n // A no-prompt step's .do(...) IS its work — only report completion once it has\n // actually run without throwing or returning fail(...), matching the with-prompt\n // case's \"step.completed means the step's own work succeeded\" meaning.\n await options.emit(\n createEvent({\n runId: options.runId,\n workflowId: currentWorkflowId,\n stepId: config.id,\n type: \"step.completed\",\n payload: {},\n }),\n );\n }\n\n throwIfStepTimedOut(signal, config.id, timeoutPolicy.timeoutMs);\n return phaseResult;\n },\n { maxSubPrompts, cwd: stepCwd, executionCwd: stepCwd },\n ),\n });\n\n if (stepResult.status === \"waiting\") {\n return stepResult;\n }\n\n const nextNode = stepResult.node;\n if (Array.isArray(nextNode) && options.returnContinuationArrays === true) {\n return {\n status: \"split\",\n nodes: nextNode,\n source: `step ${config.id}`,\n ...splitPostContinuations(undefined),\n };\n }\n\n if (isParallelNode(nextNode) && options.returnContinuationArrays === true) {\n return {\n status: \"split\",\n nodes: nextNode.nodes,\n source: `step ${config.id}`,\n ...splitPostContinuations(nextNode.postContinuation),\n };\n }\n\n if (options.returnContinuationArrays === true && isAbsoluteDoneNode(nextNode)) {\n return {\n status: \"absoluteSuccess\",\n output: nextNode.output,\n ...(nextNode.message === undefined ? {} : { message: nextNode.message }),\n };\n }\n\n if (options.returnContinuationArrays === true && isAbsoluteFailNode(nextNode)) {\n return {\n status: \"absoluteFailure\",\n failure: nextNode.failure,\n ...(nextNode.message === undefined ? {} : { message: nextNode.message }),\n };\n }\n\n const unsupportedStepFailure = unsupportedContinuationFailure(nextNode, `step ${config.id}`);\n if (unsupportedStepFailure !== undefined) {\n await options.emit(\n createEvent({\n runId: options.runId,\n workflowId: currentWorkflowId,\n stepId: config.id,\n type: \"step.failed\",\n payload: { failure: unsupportedStepFailure },\n }),\n );\n return { status: \"failure\", failure: unsupportedStepFailure };\n }\n\n if (\n !isStepNode(nextNode) &&\n !isWorkflowInvocationNode(nextNode) &&\n !isDoneNode(nextNode) &&\n !isFailNode(nextNode)\n ) {\n const failure = continuationFailure(`step ${config.id}`);\n await options.emit(\n createEvent({\n runId: options.runId,\n workflowId: currentWorkflowId,\n stepId: config.id,\n type: \"step.failed\",\n payload: { failure },\n }),\n );\n return { status: \"failure\", failure };\n }\n\n if (isFailNode(nextNode)) {\n return {\n status: \"failure\",\n failure: nextNode.failure,\n ...(nextNode.message === undefined ? {} : { message: nextNode.message }),\n };\n }\n\n node = nextNode;\n source = `step ${config.id}`;\n } catch (error) {\n if (isWorkflowCancellationError(error)) {\n await options.emit(\n createEvent({\n runId: options.runId,\n workflowId: currentWorkflowId,\n stepId: config.id,\n type: \"step.cancelled\",\n payload: cancellationPayload(error.cancellation),\n }),\n );\n return { status: \"cancelled\", cancellation: error.cancellation };\n }\n\n const failure = stepExecutionFailure(error);\n\n await options.emit(\n createEvent({\n runId: options.runId,\n workflowId: currentWorkflowId,\n stepId: config.id,\n type: \"step.failed\",\n payload: { failure },\n }),\n );\n\n if (!stepNode.onError) {\n return { status: \"failure\", failure };\n }\n\n try {\n const nextNode = stepNode.onError(failure);\n const errorSource = `error continuation for step ${config.id}`;\n if (Array.isArray(nextNode) && options.returnContinuationArrays === true) {\n return {\n status: \"split\",\n nodes: nextNode,\n source: errorSource,\n ...splitPostContinuations(undefined),\n };\n }\n\n if (isParallelNode(nextNode) && options.returnContinuationArrays === true) {\n return {\n status: \"split\",\n nodes: nextNode.nodes,\n source: errorSource,\n ...splitPostContinuations(nextNode.postContinuation),\n };\n }\n\n if (options.returnContinuationArrays === true && isAbsoluteDoneNode(nextNode)) {\n return {\n status: \"absoluteSuccess\",\n output: nextNode.output,\n ...(nextNode.message === undefined ? {} : { message: nextNode.message }),\n };\n }\n\n if (options.returnContinuationArrays === true && isAbsoluteFailNode(nextNode)) {\n return {\n status: \"absoluteFailure\",\n failure: nextNode.failure,\n ...(nextNode.message === undefined ? {} : { message: nextNode.message }),\n };\n }\n\n const unsupportedErrorFailure = unsupportedContinuationFailure(nextNode, errorSource);\n if (unsupportedErrorFailure !== undefined) {\n return {\n status: \"failure\",\n failure: unsupportedErrorFailure,\n };\n }\n\n if (\n !isStepNode(nextNode) &&\n !isWorkflowInvocationNode(nextNode) &&\n !isDoneNode(nextNode) &&\n !isFailNode(nextNode)\n ) {\n return {\n status: \"failure\",\n failure: continuationFailure(errorSource),\n };\n }\n\n node = nextNode;\n source = errorSource;\n } catch (errorContinuationError) {\n return {\n status: \"failure\",\n failure: stepExecutionFailure(\n new Error(\n `error continuation for step ${config.id} failed: ${errorMessage(errorContinuationError)}`,\n ),\n ),\n };\n }\n }\n }\n}\n\ntype RunStepPhasesResult =\n | { readonly status: \"continued\"; readonly node: ContinuationResult }\n | { readonly status: \"waiting\"; readonly wait: WaitingWait };\n\ntype HandleWaitResult =\n | { readonly status: \"satisfied\"; readonly waitId: string; readonly output: PlainObject }\n | { readonly status: \"waiting\"; readonly wait: WaitingWait };\n\nasync function resolveStepExecutionCwd(options: {\n readonly stepId: string;\n readonly workflowId: string;\n readonly defaultCwd: string;\n readonly input: PlainObject;\n readonly cwdInput: StepCwdInput | undefined;\n}): Promise<string> {\n if (options.cwdInput === undefined) {\n return options.defaultCwd;\n }\n\n const cwd =\n typeof options.cwdInput === \"function\"\n ? await resolveStepCwdCallback(options.cwdInput, options)\n : options.cwdInput;\n\n if (typeof cwd !== \"string\") {\n throw new TypeError(`step ${options.stepId} cwd must resolve to a string.`);\n }\n\n await validateDirectoryCwd(cwd, `step ${options.stepId} cwd`);\n return cwd;\n}\n\nasync function resolveStepCwdCallback(\n cwdInput: Exclude<StepCwdInput, string>,\n options: {\n readonly stepId: string;\n readonly workflowId: string;\n readonly input: PlainObject;\n },\n): Promise<unknown> {\n const context = runContextStorage.getStore();\n if (!context) {\n throw new Error(`step ${options.stepId} cwd callback requires an active run context.`);\n }\n\n return await cwdInput({\n input: options.input,\n state: context.state,\n workflow: { id: options.workflowId },\n });\n}\n\nasync function runStepPhases(options: {\n readonly stepNode: StepNode;\n readonly timeoutMs?: number;\n readonly signal?: AbortSignal;\n readonly readCancellation: () => Promise<CancellationMarker | undefined>;\n readonly emitDisplay: (\n phase: DisplayPhase,\n output: PlainObject,\n phaseIndex: number,\n ) => Promise<void>;\n readonly handleWait: (\n phase: WaitPhase,\n output: PlainObject,\n phaseIndex: number,\n waits: Readonly<Record<string, PlainObject>>,\n previousWaitId?: string,\n ) => Promise<HandleWaitResult>;\n readonly handleResumedWait: (wait: ResumedWaitDetails) => Promise<HandleWaitResult>;\n readonly dispatchPrompt: (phase: PromptPhase) => Promise<PlainObject>;\n readonly resume?: {\n readonly startPhaseIndex: number;\n readonly phaseValue: PlainObject;\n readonly waitOutputs: Readonly<Record<string, PlainObject>>;\n readonly seenWaitIds: readonly string[];\n readonly wait: ResumedWaitDetails;\n };\n}): Promise<RunStepPhasesResult> {\n const { stepNode } = options;\n let phaseValue = options.resume?.phaseValue ?? stepNode.config.input;\n let nextNode: ContinuationResult | undefined;\n const waitOutputs: Record<string, PlainObject> = { ...(options.resume?.waitOutputs ?? {}) };\n const seenWaitIds = new Set<string>(options.resume?.seenWaitIds ?? []);\n const phases = getStepPhases(stepNode);\n assertNoDuplicateStaticWaitIds(phases, stepNode.config.id);\n\n for (const [phaseIndex, phase] of phases.entries()) {\n if (phaseIndex < (options.resume?.startPhaseIndex ?? 0)) {\n continue;\n }\n throwIfCancellationRequested(await options.readCancellation());\n\n if (phase.kind === \"display\") {\n await options.emitDisplay(phase, phaseValue, phaseIndex);\n throwIfCancellationRequested(await options.readCancellation());\n throwIfStepTimedOut(options.signal, stepNode.config.id, options.timeoutMs);\n continue;\n }\n\n if (phase.kind === \"wait\") {\n const waitResult =\n options.resume !== undefined && phaseIndex === options.resume.startPhaseIndex\n ? options.resume.wait.kind === \"check\"\n ? await options.handleWait(\n phase,\n phaseValue,\n phaseIndex,\n waitOutputs,\n options.resume.wait.waitId,\n )\n : await options.handleResumedWait(options.resume.wait)\n : await options.handleWait(phase, phaseValue, phaseIndex, waitOutputs);\n const waitId = waitResult.status === \"waiting\" ? waitResult.wait.waitId : waitResult.waitId;\n if (seenWaitIds.has(waitId)) {\n throw new Error(`step ${stepNode.config.id} has duplicate wait id '${waitId}'`);\n }\n seenWaitIds.add(waitId);\n\n if (waitResult.status === \"waiting\") {\n throwIfCancellationRequested(await options.readCancellation());\n return waitResult;\n }\n\n waitOutputs[waitResult.waitId] = waitResult.output;\n throwIfCancellationRequested(await options.readCancellation());\n throwIfStepTimedOut(options.signal, stepNode.config.id, options.timeoutMs);\n continue;\n }\n\n if (nextNode !== undefined) {\n throw new Error(`step ${stepNode.config.id} has executable phases after a do phase`);\n }\n\n if (phase.kind === \"prompt\") {\n phaseValue = await options.dispatchPrompt(phase);\n throwIfCancellationRequested(await options.readCancellation());\n throwIfStepTimedOut(options.signal, stepNode.config.id, options.timeoutMs);\n continue;\n }\n\n nextNode = await phase.onOutput(\n withWaitsDoContext(phaseValue, waitOutputs),\n stepNode.config.input,\n );\n throwIfCancellationRequested(await options.readCancellation());\n throwIfStepTimedOut(options.signal, stepNode.config.id, options.timeoutMs);\n }\n\n if (nextNode === undefined) {\n throw new Error(`step ${stepNode.config.id} has no do phase`);\n }\n\n return { status: \"continued\", node: nextNode };\n}\n\nfunction assertNoDuplicateStaticWaitIds(phases: readonly unknown[], stepId: string): void {\n const seenWaitIds = new Set<string>();\n for (const phase of phases) {\n if (!isPlainObject(phase) || phase.kind !== \"wait\") {\n continue;\n }\n const wait = phase.wait;\n if (typeof wait === \"function\" || !isPlainObject(wait) || typeof wait.id !== \"string\") {\n continue;\n }\n if (seenWaitIds.has(wait.id)) {\n throw new Error(`step ${stepId} has duplicate wait id '${wait.id}'`);\n }\n seenWaitIds.add(wait.id);\n }\n}\n\nasync function handleWaitPhase(options: {\n readonly phase: WaitPhase;\n readonly input: PlainObject;\n readonly output: PlainObject;\n readonly waits: Readonly<Record<string, PlainObject>>;\n readonly phaseIndex: number;\n readonly previousWaitId?: string;\n readonly stepId: string;\n readonly stepArtifactId: string;\n readonly runDir: string;\n readonly runId: string;\n readonly workflowId: string;\n readonly emit: (event: Event) => Promise<void>;\n}): Promise<HandleWaitResult> {\n if (options.phase.options !== undefined) {\n return await handleCheckWaitPhase({\n ...options,\n phase: options.phase as WaitPhase & { readonly options: NonNullable<WaitPhase[\"options\"]> },\n });\n }\n\n const wait = await resolveWaitDefinition(options.phase, {\n input: options.input,\n output: options.output,\n waits: options.waits,\n });\n validateWaitDefinition(wait, options.stepId, options.phaseIndex);\n\n const artifactPaths = resolveWaitArtifactPaths({\n runDir: options.runDir,\n stepArtifactId: options.stepArtifactId,\n waitId: wait.id,\n });\n const request = {\n stepId: options.stepId,\n waitId: wait.id,\n kind: wait.kind,\n message: wait.message,\n phaseIndex: options.phaseIndex,\n outputSchema: normalizeShape(wait.output).jsonSchema,\n };\n\n await mkdir(artifactPaths.waitDir, { recursive: true });\n await writeFile(artifactPaths.requestFile, `${JSON.stringify(request, null, 2)}\\n`, \"utf8\");\n\n const answerText = await readTextIfExists(artifactPaths.answerFile);\n if (answerText.status === \"missing\") {\n const waiting = {\n stepId: options.stepId,\n waitId: wait.id,\n message: wait.message,\n artifactPaths: artifactPaths.runRelative,\n };\n await options.emit(\n createEvent({\n runId: options.runId,\n workflowId: options.workflowId,\n stepId: options.stepId,\n type: \"wait.started\",\n payload: {\n waitId: wait.id,\n kind: wait.kind,\n message: wait.message,\n phaseIndex: options.phaseIndex,\n artifactPaths: artifactPaths.runRelative,\n },\n }),\n );\n return { status: \"waiting\", wait: waiting };\n }\n\n try {\n const parsedAnswer: unknown = JSON.parse(answerText.value);\n if (!isPlainObject(parsedAnswer)) {\n throw new TypeError(`step ${options.stepId} wait ${wait.id} answer must be a plain object`);\n }\n const output = normalizeShape(wait.output).assert(\n parsedAnswer,\n `step ${options.stepId} wait ${wait.id} answer`,\n );\n await options.emit(\n createEvent({\n runId: options.runId,\n workflowId: options.workflowId,\n stepId: options.stepId,\n type: \"wait.satisfied\",\n payload: {\n waitId: wait.id,\n kind: wait.kind,\n message: wait.message,\n phaseIndex: options.phaseIndex,\n artifactPaths: artifactPaths.runRelative,\n output,\n },\n }),\n );\n return { status: \"satisfied\", waitId: wait.id, output };\n } catch (error) {\n await options.emit(\n createEvent({\n runId: options.runId,\n workflowId: options.workflowId,\n stepId: options.stepId,\n type: \"wait.failed\",\n payload: {\n waitId: wait.id,\n kind: wait.kind,\n message: wait.message,\n phaseIndex: options.phaseIndex,\n artifactPaths: artifactPaths.runRelative,\n failure: stepExecutionFailure(error),\n },\n }),\n );\n throw error;\n }\n}\n\nasync function handleCheckWaitPhase(options: {\n readonly phase: WaitPhase & { readonly options: NonNullable<WaitPhase[\"options\"]> };\n readonly input: PlainObject;\n readonly output: PlainObject;\n readonly waits: Readonly<Record<string, PlainObject>>;\n readonly phaseIndex: number;\n readonly previousWaitId?: string;\n readonly stepId: string;\n readonly stepArtifactId: string;\n readonly runDir: string;\n readonly runId: string;\n readonly workflowId: string;\n readonly emit: (event: Event) => Promise<void>;\n}): Promise<HandleWaitResult> {\n const outputSchema = normalizeShape(options.phase.options.output);\n const defaultWaitId = options.previousWaitId ?? `check-${options.phaseIndex}`;\n let waitId = defaultWaitId;\n\n try {\n if (typeof options.phase.wait !== \"function\") {\n throw new TypeError(\n `step ${options.stepId} check wait phase ${options.phaseIndex} requires a callback.`,\n );\n }\n\n const check = options.phase.wait as (context: {\n readonly input: PlainObject;\n readonly output: PlainObject;\n readonly waits: Readonly<Record<string, PlainObject>>;\n readonly wait: CheckWaitHelpers<PlainObject>;\n }) => WaitCheckResult | Promise<WaitCheckResult>;\n const result = await check({\n input: options.input,\n output: options.output,\n waits: options.waits,\n wait: createCheckWaitHelpers(),\n });\n validateCheckWaitResult(result, options.stepId, options.phaseIndex);\n\n if (result.status === \"pending\") {\n validatePendingWait(result, options.stepId, options.phaseIndex);\n waitId = result.id;\n const artifactPaths = resolveWaitArtifactPaths({\n runDir: options.runDir,\n stepArtifactId: options.stepArtifactId,\n waitId,\n });\n const request = {\n stepId: options.stepId,\n waitId,\n kind: \"check\",\n message: result.message,\n phaseIndex: options.phaseIndex,\n ...(result.retryAfterSeconds === undefined\n ? {}\n : { retryAfterSeconds: result.retryAfterSeconds }),\n outputSchema: outputSchema.jsonSchema,\n };\n\n await mkdir(artifactPaths.waitDir, { recursive: true });\n await writeFile(artifactPaths.requestFile, `${JSON.stringify(request, null, 2)}\\n`, \"utf8\");\n\n await options.emit(\n createEvent({\n runId: options.runId,\n workflowId: options.workflowId,\n stepId: options.stepId,\n type: \"wait.started\",\n payload: {\n waitId,\n kind: \"check\",\n message: result.message,\n phaseIndex: options.phaseIndex,\n ...(result.retryAfterSeconds === undefined\n ? {}\n : { retryAfterSeconds: result.retryAfterSeconds }),\n artifactPaths: artifactPaths.runRelative,\n },\n }),\n );\n\n return {\n status: \"waiting\",\n wait: {\n stepId: options.stepId,\n waitId,\n kind: \"check\",\n message: result.message,\n ...(result.retryAfterSeconds === undefined\n ? {}\n : { retryAfterSeconds: result.retryAfterSeconds }),\n artifactPaths: artifactPaths.runRelative,\n },\n };\n }\n\n const output = outputSchema.assert(\n result.output,\n `step ${options.stepId} check wait ${waitId} output`,\n );\n const artifactPaths = resolveWaitArtifactPaths({\n runDir: options.runDir,\n stepArtifactId: options.stepArtifactId,\n waitId,\n });\n await mkdir(artifactPaths.waitDir, { recursive: true });\n await writeFile(\n artifactPaths.requestFile,\n `${JSON.stringify(\n {\n stepId: options.stepId,\n waitId,\n kind: \"check\",\n phaseIndex: options.phaseIndex,\n outputSchema: outputSchema.jsonSchema,\n },\n null,\n 2,\n )}\\n`,\n \"utf8\",\n );\n\n await options.emit(\n createEvent({\n runId: options.runId,\n workflowId: options.workflowId,\n stepId: options.stepId,\n type: \"wait.satisfied\",\n payload: {\n waitId,\n kind: \"check\",\n phaseIndex: options.phaseIndex,\n artifactPaths: artifactPaths.runRelative,\n output,\n },\n }),\n );\n return { status: \"satisfied\", waitId, output };\n } catch (error) {\n await options.emit(\n createEvent({\n runId: options.runId,\n workflowId: options.workflowId,\n stepId: options.stepId,\n type: \"wait.failed\",\n payload: {\n waitId,\n kind: \"check\",\n phaseIndex: options.phaseIndex,\n failure: stepExecutionFailure(error),\n },\n }),\n );\n throw error;\n }\n}\n\nasync function handleResumedWaitPhase(options: {\n readonly wait: ResumedWaitDetails;\n readonly stepId: string;\n readonly runDir: string;\n readonly runId: string;\n readonly workflowId: string;\n readonly emit: (event: Event) => Promise<void>;\n}): Promise<HandleWaitResult> {\n const answerFile = joinRunPath(options.runDir, options.wait.artifactPaths.answerFile);\n const answerText = await readTextIfExists(answerFile);\n if (answerText.status === \"missing\") {\n return {\n status: \"waiting\",\n wait: {\n stepId: options.stepId,\n waitId: options.wait.waitId,\n message: options.wait.message,\n artifactPaths: options.wait.artifactPaths,\n },\n };\n }\n\n try {\n const parsedAnswer: unknown = JSON.parse(answerText.value);\n if (!isPlainObject(parsedAnswer)) {\n throw new TypeError(\n `step ${options.stepId} wait ${options.wait.waitId} answer must be a plain object`,\n );\n }\n const output = jsonSchema<PlainObject>(options.wait.outputSchema).assert(\n parsedAnswer,\n `step ${options.stepId} wait ${options.wait.waitId} answer`,\n );\n await options.emit(\n createEvent({\n runId: options.runId,\n workflowId: options.workflowId,\n stepId: options.stepId,\n type: \"wait.satisfied\",\n payload: {\n waitId: options.wait.waitId,\n kind: options.wait.kind,\n message: options.wait.message,\n artifactPaths: options.wait.artifactPaths,\n output,\n },\n }),\n );\n return { status: \"satisfied\", waitId: options.wait.waitId, output };\n } catch (error) {\n await options.emit(\n createEvent({\n runId: options.runId,\n workflowId: options.workflowId,\n stepId: options.stepId,\n type: \"wait.failed\",\n payload: {\n waitId: options.wait.waitId,\n kind: options.wait.kind,\n message: options.wait.message,\n artifactPaths: options.wait.artifactPaths,\n failure: stepExecutionFailure(error),\n },\n }),\n );\n throw error;\n }\n}\n\nfunction joinRunPath(runDir: string, runRelativePath: string): string {\n return join(runDir, ...runRelativePath.split(\"/\"));\n}\n\nasync function resolveWaitDefinition(\n phase: WaitPhase,\n context: {\n readonly input: PlainObject;\n readonly output: PlainObject;\n readonly waits: Readonly<Record<string, PlainObject>>;\n },\n): Promise<WaitDefinition> {\n if (typeof phase.wait !== \"function\") {\n return phase.wait;\n }\n\n const resolveInputWait = phase.wait as (context: {\n readonly input: PlainObject;\n readonly output: PlainObject;\n readonly waits: Readonly<Record<string, PlainObject>>;\n }) => WaitDefinition | Promise<WaitDefinition>;\n return await resolveInputWait(context);\n}\n\nfunction createCheckWaitHelpers<TWaitOutput extends PlainObject>(): CheckWaitHelpers<TWaitOutput> {\n return {\n done(output) {\n return { status: \"done\", output };\n },\n pending(input) {\n return {\n status: \"pending\",\n id: input.id,\n message: input.message,\n ...(input.retryAfterSeconds === undefined\n ? {}\n : { retryAfterSeconds: input.retryAfterSeconds }),\n };\n },\n };\n}\n\nfunction validateCheckWaitResult(\n result: unknown,\n stepId: string,\n phaseIndex: number,\n): asserts result is WaitCheckResult {\n const label = `step ${stepId} check wait phase ${phaseIndex}`;\n if (!isPlainObject(result)) {\n throw new TypeError(`${label} must return wait.done(...) or wait.pending(...).`);\n }\n\n if (result.status !== \"done\" && result.status !== \"pending\") {\n throw new TypeError(`${label} must return wait.done(...) or wait.pending(...).`);\n }\n\n if (result.status === \"done\" && !(\"output\" in result)) {\n throw new TypeError(`${label} wait.done(...) requires output.`);\n }\n}\n\nfunction validatePendingWait(\n pending: WaitCheckResult,\n stepId: string,\n phaseIndex: number,\n): asserts pending is Extract<WaitCheckResult, { readonly status: \"pending\" }> {\n const label = `step ${stepId} check wait phase ${phaseIndex}`;\n if (pending.status !== \"pending\") {\n throw new TypeError(`${label} expected a pending result.`);\n }\n\n if (typeof pending.id !== \"string\" || pending.id.trim().length === 0) {\n throw new TypeError(`${label} pending result requires a non-empty string id.`);\n }\n\n if (\n pending.id === \".\" ||\n pending.id === \"..\" ||\n pending.id.includes(\"/\") ||\n pending.id.includes(\"\\\\\")\n ) {\n throw new TypeError(`${label} pending result id must be a single path-safe segment.`);\n }\n\n if (typeof pending.message !== \"string\" || pending.message.trim().length === 0) {\n throw new TypeError(`${label} pending result requires a non-empty string message.`);\n }\n\n if (\n pending.retryAfterSeconds !== undefined &&\n (!Number.isFinite(pending.retryAfterSeconds) || pending.retryAfterSeconds < 0)\n ) {\n throw new TypeError(`${label} pending retryAfterSeconds must be a non-negative number.`);\n }\n}\n\nfunction validateWaitDefinition(wait: WaitDefinition, stepId: string, phaseIndex: number): void {\n const label = `step ${stepId} wait phase ${phaseIndex}`;\n if (!isPlainObject(wait)) {\n throw new TypeError(`${label} must resolve to a wait object.`);\n }\n\n if (typeof wait.id !== \"string\" || wait.id.trim().length === 0) {\n throw new TypeError(`${label} requires a non-empty string id.`);\n }\n\n if (wait.id === \".\" || wait.id === \"..\" || wait.id.includes(\"/\") || wait.id.includes(\"\\\\\")) {\n throw new TypeError(`${label} id must be a single path-safe segment.`);\n }\n\n if (wait.kind !== \"input\") {\n throw new TypeError(`${label} kind must be \"input\".`);\n }\n\n if (typeof wait.message !== \"string\" || wait.message.trim().length === 0) {\n throw new TypeError(`${label} requires a non-empty string message.`);\n }\n\n if (!(\"output\" in wait) || wait.output === undefined) {\n throw new TypeError(`${label} requires an output shape.`);\n }\n\n normalizeShape(wait.output);\n}\n\nasync function readTextIfExists(\n path: string,\n): Promise<{ readonly status: \"found\"; readonly value: string } | { readonly status: \"missing\" }> {\n try {\n return { status: \"found\", value: await readFile(path, \"utf8\") };\n } catch (error) {\n if (isNodeError(error) && error.code === \"ENOENT\") {\n return { status: \"missing\" };\n }\n throw error;\n }\n}\n\nfunction withWaitsDoContext(\n output: PlainObject,\n waits: Readonly<Record<string, PlainObject>>,\n): PlainObject {\n return new Proxy(output, {\n get(target, property, receiver) {\n if (property === \"output\") {\n return target;\n }\n if (property === \"waits\") {\n return waits;\n }\n return Reflect.get(target, property, receiver);\n },\n has(target, property) {\n return property === \"output\" || property === \"waits\" || Reflect.has(target, property);\n },\n getOwnPropertyDescriptor(target, property) {\n if (property === \"output\") {\n return { configurable: true, enumerable: false, value: target };\n }\n if (property === \"waits\") {\n return { configurable: true, enumerable: false, value: waits };\n }\n return Reflect.getOwnPropertyDescriptor(target, property);\n },\n });\n}\n\nasync function resolveDisplayPayload(options: {\n readonly phase: DisplayPhase;\n readonly input: PlainObject;\n readonly output: PlainObject;\n readonly phaseIndex: number;\n readonly stepId: string;\n}): Promise<PlainObject> {\n const { phase, input, output, phaseIndex, stepId } = options;\n const rawValue =\n typeof phase.content === \"function\" ? await phase.content({ input, output }) : phase.content;\n\n const display = normalizeDisplayValue(rawValue, { stepId, phaseIndex });\n if (typeof display === \"string\") {\n return { message: display, level: \"info\", phaseIndex };\n }\n\n return {\n message: display.message,\n level: display.level ?? \"info\",\n ...(\"data\" in display ? { data: display.data } : {}),\n phaseIndex,\n };\n}\n\nfunction normalizeDisplayValue(\n value: unknown,\n context: { readonly stepId: string; readonly phaseIndex: number },\n): StepDisplayValue {\n const label = `step ${context.stepId} display phase ${context.phaseIndex}`;\n\n if (typeof value === \"string\") {\n return value;\n }\n\n if (!isPlainObject(value) || typeof value.message !== \"string\") {\n throw new TypeError(`${label} must resolve to a string or an object with a string message.`);\n }\n\n const level = value.level ?? \"info\";\n if (!isDisplayLevel(level)) {\n throw new TypeError(`${label} level must be one of: info, warning, error, debug.`);\n }\n\n return {\n message: value.message,\n level,\n ...(\"data\" in value ? { data: value.data } : {}),\n };\n}\n\nfunction isDisplayLevel(value: unknown): value is \"info\" | \"warning\" | \"error\" | \"debug\" {\n return value === \"info\" || value === \"warning\" || value === \"error\" || value === \"debug\";\n}\n\nfunction isNodeError(error: unknown): error is NodeJS.ErrnoException {\n return error instanceof Error && \"code\" in error;\n}\n\nfunction isPlainObject(value: unknown): value is PlainObject {\n return (\n typeof value === \"object\" &&\n value !== null &&\n !Array.isArray(value) &&\n Object.getPrototypeOf(value) === Object.prototype\n );\n}\n\nasync function runWithStepControl<T>(options: {\n readonly stepId: string;\n readonly timeoutMs?: number;\n readonly readCancellation: () => Promise<CancellationMarker | undefined>;\n readonly run: (signal: AbortSignal) => Promise<T>;\n}): Promise<T> {\n const initialCancellation = await options.readCancellation();\n if (initialCancellation !== undefined) {\n throw new WorkflowCancellationError(initialCancellation);\n }\n\n const abortController = new AbortController();\n let timeout: ReturnType<typeof setTimeout> | undefined;\n let stopCancellationWatch: (() => void) | undefined;\n\n const runPromise = options.run(abortController.signal);\n void runPromise.catch(() => undefined);\n\n const cancellationPromise = new Promise<never>((_, reject) => {\n stopCancellationWatch = watchCancellation(options.readCancellation, (result) => {\n abortController.abort();\n if (\"error\" in result) {\n reject(result.error);\n return;\n }\n reject(new WorkflowCancellationError(result.cancellation));\n });\n });\n\n const raced: Array<Promise<T> | Promise<never>> = [runPromise, cancellationPromise];\n\n if (options.timeoutMs !== undefined) {\n const timeoutMs = options.timeoutMs;\n raced.push(\n new Promise<never>((_, reject) => {\n timeout = setTimeout(() => {\n abortController.abort();\n reject(stepTimeoutFailure(options.stepId, timeoutMs));\n }, timeoutMs);\n }),\n );\n }\n\n try {\n return await Promise.race(raced);\n } finally {\n stopCancellationWatch?.();\n if (timeout !== undefined) {\n clearTimeout(timeout);\n }\n }\n}\n\nfunction watchCancellation(\n readCancellation: () => Promise<CancellationMarker | undefined>,\n onCancel: (\n result: { readonly cancellation: CancellationMarker } | { readonly error: unknown },\n ) => void,\n): () => void {\n let stopped = false;\n let timer: ReturnType<typeof setTimeout> | undefined;\n\n const poll = async (): Promise<void> => {\n if (stopped) {\n return;\n }\n\n try {\n const cancellation = await readCancellation();\n if (cancellation !== undefined) {\n stopped = true;\n onCancel({ cancellation });\n return;\n }\n } catch (error) {\n stopped = true;\n onCancel({ error });\n return;\n }\n\n timer = setTimeout(() => void poll(), 100);\n };\n\n timer = setTimeout(() => void poll(), 0);\n\n return () => {\n stopped = true;\n if (timer !== undefined) {\n clearTimeout(timer);\n }\n };\n}\n\nfunction throwIfStepTimedOut(\n signal: AbortSignal | undefined,\n stepId: string,\n timeoutMs: number | undefined,\n): void {\n if (signal?.aborted && timeoutMs !== undefined) {\n throw stepTimeoutFailure(stepId, timeoutMs);\n }\n}\n\nfunction stepTimeoutFailure(stepId: string, timeoutMs: number): TrailStepFailureError {\n return new TrailStepFailureError({\n code: \"step_timeout\",\n message: `Step ${stepId} timed out after ${timeoutMs}ms.`,\n details: { stepId, timeoutMs },\n });\n}\n\nfunction errorMessage(error: unknown): string {\n if (error instanceof TrailStepFailureError) {\n return error.message;\n }\n\n if (error instanceof Error) {\n return error.message;\n }\n\n return \"Error continuation failed.\";\n}\n\nfunction continuationFailure(source: string): Failure {\n return {\n code: \"invalid_continuation\",\n message: `${source} returned an invalid continuation node.`,\n };\n}\n\nfunction failureFromError(error: unknown): Failure {\n if (error instanceof TrailStepFailureError) {\n return error.failure;\n }\n\n return stepExecutionFailure(error);\n}\n\nfunction unsupportedContinuationFailure(node: unknown, source: string): Failure | undefined {\n const form = unsupportedContinuationForm(node);\n if (form === undefined) {\n return undefined;\n }\n\n return {\n code: \"unsupported_continuation\",\n message: `${source} returned ${form}, but parallel tracks/workflow invocation execution is not implemented yet.`,\n };\n}\n\nfunction unsupportedContinuationForm(node: unknown): string | undefined {\n if (Array.isArray(node)) {\n return \"a continuation array\";\n }\n\n if (isAbsoluteDoneNode(node)) {\n return \"an absolute done continuation\";\n }\n\n if (isAbsoluteFailNode(node)) {\n return \"an absolute fail continuation\";\n }\n\n return undefined;\n}\n","import type { Failure } from \"../../contracts/failures/failure.js\";\n\nimport { isFailureLikeError } from \"./failure-like.js\";\n\nexport function stepExecutionFailure(error: unknown): Failure {\n if (isFailureLikeError(error)) {\n return error.failure;\n }\n\n return {\n code: \"step_execution_failed\",\n message: error instanceof Error ? error.message : \"Step execution failed.\",\n ...(error instanceof Error\n ? {\n details: {\n name: error.name,\n },\n }\n : error === undefined\n ? {}\n : { details: { cause: error } }),\n };\n}\n","import { runContextStorage } from \"./run-context-storage.js\";\n\n/**\n * Runs `fn` with a step-scoped ambient `RunContext.currentStep` shadowing\n * whatever run-level context is already active (set once, for the whole\n * run, by `run-workflow.ts`). This is a genuine nested `AsyncLocalStorage`\n * scope — it does not mutate or replace the outer context, only shadows it\n * for the duration of `fn`, so code outside any step (or in a sibling step)\n * is unaffected.\n *\n * `nextDocumentIndex()` hands out 1, 2, 3, ... on each call within this one\n * invocation of `withStepContext` — a fresh counter every time, including\n * across resume replay of already-completed steps and retries of a failed\n * step, since each of those call sites invokes `withStepContext` anew.\n *\n * If there is no ambient run context at all (a step-executing function\n * called directly, outside of `runWorkflow`'s `runContextStorage.run(...)`\n * scope — e.g. unit tests that exercise the resume/continuation internals\n * in isolation), this falls back to running `fn` with no ambient context,\n * matching prior behavior exactly rather than throwing.\n */\nexport async function withStepContext<T>(\n stepId: string,\n stepDir: string,\n fn: () => Promise<T>,\n options: {\n readonly maxSubPrompts?: unknown;\n readonly cwd?: string;\n readonly executionCwd?: string;\n readonly replay?: { readonly kind: \"completed-step\" };\n } = {},\n): Promise<T> {\n const parentContext = runContextStorage.getStore();\n if (!parentContext) {\n return await fn();\n }\n\n let nextDocumentIndex = 0;\n let nextSubPromptIndex = 0;\n\n const executionCwd = options.executionCwd ?? options.cwd ?? parentContext.executionCwd;\n const stepContext = {\n ...parentContext,\n cwd: executionCwd ?? parentContext.cwd,\n executionCwd: executionCwd ?? parentContext.executionCwd,\n currentStep: {\n id: stepId,\n dir: stepDir,\n maxSubPrompts: options.maxSubPrompts,\n cwd: executionCwd ?? parentContext.cwd,\n executionCwd: executionCwd ?? parentContext.executionCwd,\n replay: options.replay,\n nextDocumentIndex(): number {\n nextDocumentIndex += 1;\n return nextDocumentIndex;\n },\n nextSubPromptIndex(): number {\n nextSubPromptIndex += 1;\n return nextSubPromptIndex;\n },\n },\n };\n\n return await runContextStorage.run(stepContext, fn);\n}\n","import { stat } from \"node:fs/promises\";\n\nexport interface RunCwds {\n /** Root used for workflow/config-relative resolution and default artifact storage. */\n readonly projectCwd: string;\n /** Default execution cwd for steps and agent processes. */\n readonly cwd: string;\n}\n\nexport async function resolveAndValidateRunCwds(options: {\n readonly projectCwd?: string;\n readonly cwd?: string;\n}): Promise<RunCwds> {\n const projectCwd = options.projectCwd ?? options.cwd ?? process.cwd();\n const cwd = options.cwd ?? projectCwd;\n\n await validateDirectoryCwd(projectCwd, \"projectCwd\");\n if (cwd === projectCwd) {\n return { projectCwd, cwd };\n }\n\n await validateDirectoryCwd(cwd, \"cwd\");\n return { projectCwd, cwd };\n}\n\nexport async function validateDirectoryCwd(cwd: string, label: string): Promise<void> {\n if (cwd.trim().length === 0) {\n throw new TypeError(`${label} must be a non-empty string.`);\n }\n\n const stats = await stat(cwd).catch((error) => {\n throw new Error(`${label} must be an existing directory: ${cwd}`, { cause: error });\n });\n\n if (!stats.isDirectory()) {\n throw new Error(`${label} must be an existing directory: ${cwd}`);\n }\n}\n","export interface TimeoutPolicy {\n readonly timeoutMs?: number;\n}\n\nexport type TimeoutPolicyInput = number;\n\nexport interface ResolveTimeoutPolicyOptions {\n readonly global?: TimeoutPolicyInput;\n readonly workflow?: TimeoutPolicyInput;\n readonly step?: TimeoutPolicyInput;\n}\n\nconst BUILT_IN_TIMEOUT_POLICY: TimeoutPolicy = {};\n\nexport function resolveTimeoutPolicy(options: ResolveTimeoutPolicyOptions): TimeoutPolicy {\n const configured = firstConfiguredPolicy(options.step, options.workflow, options.global);\n return configured !== undefined ? validateTimeoutPolicy(configured) : BUILT_IN_TIMEOUT_POLICY;\n}\n\nexport function validateTimeoutPolicy(input: unknown): TimeoutPolicy {\n if (typeof input !== \"number\" || !Number.isInteger(input) || input < 1) {\n throw new TypeError(\n \"timeout must be an integer number of milliseconds greater than or equal to 1.\",\n );\n }\n\n return { timeoutMs: input };\n}\n\nfunction firstConfiguredPolicy(...policies: readonly unknown[]): unknown | undefined {\n return policies.find((policy) => policy !== undefined);\n}\n","export const DEFAULT_INTERACTIVE_OUTPUT_SHAPE = { sessionFile: \"string\" } as const;\n","import { normalizeShape } from \"../../../authoring/shape/json-schema.js\";\nimport type { PlainObject, Schema, ShapeInput } from \"../../../contracts/shapes/shape.types.js\";\nimport { DEFAULT_INTERACTIVE_OUTPUT_SHAPE } from \"../../interactive-session/default-interactive-output-shape.js\";\n\n/**\n * A prompt phase's effective output schema: its own `output`, or -- for an\n * interactive phase with none given -- the default interactive output shape.\n * Shared by dispatch (`runContinuation`) and both resume paths\n * (`reattachInProgressStep`, `replayCompletedSteps`), which must all resolve\n * the identical schema a step was originally dispatched with.\n */\nexport function resolveStepOutputSchema(config: {\n readonly output?: ShapeInput<PlainObject>;\n readonly mode?: \"working\" | \"interactive\";\n}): Schema<PlainObject> | undefined {\n const effectiveOutput =\n config.output ?? (config.mode === \"interactive\" ? DEFAULT_INTERACTIVE_OUTPUT_SHAPE : undefined);\n\n return effectiveOutput ? normalizeShape(effectiveOutput) : undefined;\n}\n","import type { Failure } from \"../../contracts/failures/failure.js\";\n\nimport { isFailureLikeError } from \"./failure-like.js\";\n\nexport function workflowFailure(error: unknown): Failure {\n if (isFailureLikeError(error)) {\n return error.failure;\n }\n\n return {\n code: \"workflow_failed\",\n message: error instanceof Error ? error.message : \"Unknown workflow failure.\",\n ...(error === undefined ? {} : { details: { cause: error } }),\n };\n}\n","import type { ContinuationResult, StepNode } from \"../../../authoring/step/continuation.types.js\";\nimport {\n firstPromptPhase,\n getStepPhases,\n hasPromptPhase,\n isStepNode,\n} from \"../../../authoring/step/step-node.js\";\nimport type { Failure } from \"../../../contracts/failures/failure.js\";\nimport type { PlainObject } from \"../../../contracts/shapes/shape.types.js\";\nimport type {\n Event,\n RunWorkflowOptions,\n} from \"../../../runtime/run-workflow/run-workflow.types.js\";\nimport { resolveStepArtifactPaths } from \"../../artifacts/step-artifacts.js\";\nimport { resolveStepOutputSchema } from \"../../continuation/resolve-step-output-schema/resolve-step-output-schema.js\";\nimport { withStepContext } from \"../../run-context/with-step-context.js\";\n\n/**\n * Walks a workflow's `start(...)` continuation forward through its recorded\n * `step.completed` history — trusting each completed prompt/agent step's\n * persisted output rather than recomputing it — until it reaches\n * `targetStepId`. Shared by `replayToFailedStep` (target = the step that\n * failed) and `reattachInProgressStep` (target = a dangling interactive\n * step): both need the identical \"replay what already happened\" walk: only\n * their handling of the target step once reached differs.\n */\nexport async function replayCompletedSteps<\n TInput extends PlainObject,\n TOutput extends PlainObject,\n>(options: {\n readonly workflow: RunWorkflowOptions<TInput, TOutput>[\"workflow\"];\n readonly events: readonly Event[];\n readonly input: PlainObject;\n readonly targetStepId: string;\n readonly runDir: string;\n}): Promise<\n | { readonly status: \"success\"; readonly node: StepNode }\n | { readonly status: \"failure\"; readonly failure: Failure }\n> {\n let node: ContinuationResult = options.workflow.start(options.input as TInput);\n const completedAttempts = pairCompletedStepAttempts(options.events);\n\n for (const attempt of completedAttempts) {\n const { completedEvent, stepIndex } = attempt;\n if (!isStepNode(node)) {\n return {\n status: \"failure\",\n failure: replayFailure(\n \"resume_step_id_drift\",\n \"Completed history continues after the current workflow reaches done.\",\n ),\n };\n }\n\n if (node.config.id !== completedEvent.stepId) {\n return {\n status: \"failure\",\n failure: replayFailure(\n \"resume_step_id_drift\",\n `Expected completed step ${node.config.id} but found ${completedEvent.stepId ?? \"<missing>\"}.`,\n ),\n };\n }\n\n if (hasPromptPhase(node)) {\n const recordedOutput = readPlainPayload(completedEvent, \"output\");\n if (!recordedOutput) {\n return {\n status: \"failure\",\n failure: replayFailure(\n \"resume_missing_step_output\",\n `Completed step ${node.config.id} has no recorded output to resume from.`,\n ),\n };\n }\n\n const promptPhase = firstPromptPhase(getStepPhases(node));\n const outputSchema = promptPhase ? resolveStepOutputSchema(promptPhase) : undefined;\n if (!outputSchema) {\n return {\n status: \"failure\",\n failure: replayFailure(\n \"resume_output_schema_unresolvable\",\n `Step ${node.config.id} has no resolvable output schema to replay with.`,\n ),\n };\n }\n const validatedOutput = outputSchema.assert(recordedOutput, `step ${node.config.id} output`);\n\n const stepDir = resolveStepArtifactPaths({\n runDir: options.runDir,\n stepId: node.config.id,\n stepIndex,\n }).stepDir;\n const completedNode = node;\n const recordedWaitOutputs = readCompletedStepWaitOutputs({\n events: options.events,\n attempt,\n });\n if (recordedWaitOutputs.status === \"failure\") {\n return recordedWaitOutputs;\n }\n node = await withStepContext(\n completedNode.config.id,\n stepDir,\n async () =>\n replayStepPhases(completedNode, validatedOutput, recordedWaitOutputs.waitOutputs),\n { replay: { kind: \"completed-step\" } },\n );\n } else {\n const stepDir = resolveStepArtifactPaths({\n runDir: options.runDir,\n stepId: node.config.id,\n stepIndex,\n }).stepDir;\n const completedNode = node;\n const recordedWaitOutputs = readCompletedStepWaitOutputs({\n events: options.events,\n attempt,\n });\n if (recordedWaitOutputs.status === \"failure\") {\n return recordedWaitOutputs;\n }\n node = await withStepContext(\n completedNode.config.id,\n stepDir,\n async () => replayStepPhases(completedNode, undefined, recordedWaitOutputs.waitOutputs),\n { replay: { kind: \"completed-step\" } },\n );\n }\n }\n\n if (!isStepNode(node) || node.config.id !== options.targetStepId) {\n return {\n status: \"failure\",\n failure: replayFailure(\n \"resume_step_id_drift\",\n `Target step ${options.targetStepId} is not the next live step.`,\n ),\n };\n }\n\n return { status: \"success\", node };\n}\n\nasync function replayStepPhases(\n stepNode: StepNode,\n recordedPromptOutput?: PlainObject,\n recordedWaitOutputs: Readonly<Record<string, PlainObject>> = {},\n): Promise<ContinuationResult> {\n let phaseValue = stepNode.config.input;\n let usedRecordedPromptOutput = false;\n let nextNode: ContinuationResult | undefined;\n\n for (const phase of getStepPhases(stepNode)) {\n if (phase.kind === \"display\" || phase.kind === \"wait\") {\n continue;\n }\n\n if (nextNode !== undefined) {\n throw new Error(`step ${stepNode.config.id} has executable phases after a do phase`);\n }\n\n if (phase.kind === \"prompt\") {\n if (recordedPromptOutput === undefined || usedRecordedPromptOutput) {\n throw new Error(`step ${stepNode.config.id} has no recorded output to replay prompt phase`);\n }\n phaseValue = recordedPromptOutput;\n usedRecordedPromptOutput = true;\n continue;\n }\n\n nextNode = await phase.onOutput(\n withWaitsDoContext(phaseValue, recordedWaitOutputs),\n stepNode.config.input,\n );\n }\n\n if (nextNode === undefined) {\n throw new Error(`step ${stepNode.config.id} has no do phase`);\n }\n\n return nextNode;\n}\n\ninterface CompletedStepAttempt {\n readonly stepId: string;\n readonly stepIndex: number;\n readonly completedEvent: Event;\n readonly startedEventIndex: number;\n readonly completedEventIndex: number;\n}\n\ninterface CompletedStepAttemptStart {\n readonly event: Event;\n readonly eventIndex: number;\n readonly stepIndex: number;\n}\n\nfunction pairCompletedStepAttempts(events: readonly Event[]): readonly CompletedStepAttempt[] {\n const startedByStepId = new Map<string, CompletedStepAttemptStart[]>();\n const attempts: CompletedStepAttempt[] = [];\n let stepIndex = 0;\n\n for (const [eventIndex, event] of events.entries()) {\n if (event.type === \"step.started\" && event.stepId) {\n stepIndex += 1;\n const starts = startedByStepId.get(event.stepId) ?? [];\n starts.push({ event, eventIndex, stepIndex });\n startedByStepId.set(event.stepId, starts);\n continue;\n }\n\n if (\n (event.type === \"step.completed\" ||\n event.type === \"step.failed\" ||\n event.type === \"step.cancelled\") &&\n event.stepId\n ) {\n const starts = startedByStepId.get(event.stepId);\n const started = starts?.pop();\n if (!started || event.type !== \"step.completed\") {\n continue;\n }\n\n attempts.push({\n stepId: event.stepId,\n stepIndex: started.stepIndex,\n completedEvent: event,\n startedEventIndex: started.eventIndex,\n completedEventIndex: eventIndex,\n });\n }\n }\n\n return attempts.sort((left, right) => left.completedEventIndex - right.completedEventIndex);\n}\n\nfunction readCompletedStepWaitOutputs(options: {\n readonly events: readonly Event[];\n readonly attempt: CompletedStepAttempt;\n}):\n | { readonly status: \"success\"; readonly waitOutputs: Readonly<Record<string, PlainObject>> }\n | { readonly status: \"failure\"; readonly failure: Failure } {\n const inStepEvents = options.events.slice(\n options.attempt.startedEventIndex + 1,\n options.attempt.completedEventIndex,\n );\n const waitOutputs: Record<string, PlainObject> = {};\n\n for (const event of inStepEvents) {\n if (event.type !== \"wait.satisfied\" || event.stepId !== options.attempt.stepId) {\n continue;\n }\n\n const waitId = typeof event.payload.waitId === \"string\" ? event.payload.waitId : undefined;\n const output = readPlainPayload(event, \"output\");\n if (!waitId || !output) {\n return {\n status: \"failure\",\n failure: replayFailure(\n \"resume_missing_wait_output\",\n `Completed step ${options.attempt.stepId} has an invalid recorded satisfied wait output.`,\n ),\n };\n }\n\n if (Object.hasOwn(waitOutputs, waitId)) {\n return {\n status: \"failure\",\n failure: replayFailure(\n \"resume_duplicate_wait_id\",\n `Completed step ${options.attempt.stepId} has duplicate wait id '${waitId}'.`,\n ),\n };\n }\n waitOutputs[waitId] = output;\n }\n\n return { status: \"success\", waitOutputs };\n}\n\nfunction withWaitsDoContext(\n output: PlainObject,\n waits: Readonly<Record<string, PlainObject>>,\n): PlainObject {\n return new Proxy(output, {\n get(target, property, receiver) {\n if (property === \"output\") {\n return target;\n }\n if (property === \"waits\") {\n return waits;\n }\n return Reflect.get(target, property, receiver);\n },\n has(target, property) {\n return property === \"output\" || property === \"waits\" || Reflect.has(target, property);\n },\n getOwnPropertyDescriptor(target, property) {\n if (property === \"output\") {\n return { configurable: true, enumerable: false, value: target };\n }\n if (property === \"waits\") {\n return { configurable: true, enumerable: false, value: waits };\n }\n return Reflect.getOwnPropertyDescriptor(target, property);\n },\n });\n}\n\nfunction readPlainPayload(event: Event, key: string): PlainObject | undefined {\n const value = event.payload[key];\n return isPlainObject(value) ? value : undefined;\n}\n\nfunction isPlainObject(value: unknown): value is PlainObject {\n return (\n typeof value === \"object\" &&\n value !== null &&\n !Array.isArray(value) &&\n Object.getPrototypeOf(value) === Object.prototype\n );\n}\n\nfunction replayFailure(code: string, message: string): Failure {\n return { code, message };\n}\n","import type { ContinuationResult } from \"../../../authoring/step/continuation.types.js\";\nimport { firstPromptPhase, getStepPhases } from \"../../../authoring/step/step-node.js\";\nimport type { Failure } from \"../../../contracts/failures/failure.js\";\nimport { TrailStepFailureError } from \"../../../contracts/failures/failure.js\";\nimport type { PlainObject, Schema } from \"../../../contracts/shapes/shape.types.js\";\nimport type {\n Event,\n RunWorkflowOptions,\n} from \"../../../runtime/run-workflow/run-workflow.types.js\";\nimport { resolveStepArtifactPaths } from \"../../artifacts/step-artifacts.js\";\nimport { resolveStepOutputSchema } from \"../../continuation/resolve-step-output-schema/resolve-step-output-schema.js\";\nimport {\n readCompletedInteractiveOutput,\n waitForInteractiveCompletion,\n} from \"../../interactive-session/interactive-session-protocol.js\";\nimport { withStepContext } from \"../../run-context/with-step-context.js\";\nimport { replayCompletedSteps } from \"../replay-completed-steps/replay-completed-steps.js\";\n\n/**\n * Detects the \"process died mid-interactive-step\" resume shape: the run's\n * last event is `interactive.sessionStarted` for a step, with nothing after\n * it — no `interactive.sessionCompleted`, `step.completed`, `step.failed`,\n * `workflow.failed`, or `workflow.completed` was ever written, because the\n * process was killed before any of those could be recorded. Anything else\n * (an already-terminal `workflow.failed`/`workflow.completed` run) is not\n * this shape, even if an interactive.sessionStarted appears earlier in\n * history — `run-workflow.ts` falls back to `replayToFailedStep` for that.\n */\nexport function findDanglingInteractiveSessionStart(events: readonly Event[]): Event | undefined {\n const anchor = events.at(-1);\n if (anchor?.type !== \"interactive.sessionStarted\" || !anchor.stepId) {\n return undefined;\n }\n\n const hasTerminalWorkflowEvent = events.some(\n (event) => event.type === \"workflow.failed\" || event.type === \"workflow.completed\",\n );\n\n return hasTerminalWorkflowEvent ? undefined : anchor;\n}\n\nexport async function reattachInProgressStep<\n TInput extends PlainObject,\n TOutput extends PlainObject,\n>(options: {\n readonly workflow: RunWorkflowOptions<TInput, TOutput>[\"workflow\"];\n readonly events: readonly Event[];\n readonly runDir: string;\n}): Promise<\n | {\n readonly status: \"success\";\n readonly input: PlainObject;\n readonly node: ContinuationResult;\n readonly resumedStepId: string;\n readonly sourceFailureEventId: string;\n }\n | { readonly status: \"failure\"; readonly failure: Failure }\n> {\n const anchor = findDanglingInteractiveSessionStart(options.events);\n if (!anchor?.stepId) {\n return {\n status: \"failure\",\n failure: resumeFailure(\n \"resume_target_not_dangling\",\n \"Resume target has no dangling interactive.sessionStarted event to reattach.\",\n ),\n };\n }\n\n const stepIndex = anchor.payload.stepIndex;\n if (typeof stepIndex !== \"number\") {\n return {\n status: \"failure\",\n failure: resumeFailure(\n \"resume_missing_step_index\",\n `Dangling interactive.sessionStarted event for step ${anchor.stepId} has no recorded stepIndex.`,\n ),\n };\n }\n\n const startedEvent = options.events.find((event) => event.type === \"workflow.started\");\n if (!startedEvent) {\n return {\n status: \"failure\",\n failure: resumeFailure(\n \"resume_target_not_found\",\n \"Resume target has no workflow.started event.\",\n ),\n };\n }\n\n if (startedEvent.workflowId !== options.workflow.id) {\n return {\n status: \"failure\",\n failure: resumeFailure(\n \"resume_workflow_mismatch\",\n `Resume target workflow ${startedEvent.workflowId} does not match ${options.workflow.id}.`,\n ),\n };\n }\n\n const input = readPlainPayload(startedEvent, \"input\");\n if (!input) {\n return {\n status: \"failure\",\n failure: resumeFailure(\n \"resume_target_not_found\",\n \"workflow.started payload is missing input.\",\n ),\n };\n }\n\n const replay = await replayCompletedSteps({\n workflow: options.workflow,\n events: options.events,\n input,\n targetStepId: anchor.stepId,\n runDir: options.runDir,\n });\n if (replay.status === \"failure\") {\n return replay;\n }\n\n const { node } = replay;\n const artifactPaths = resolveStepArtifactPaths({\n runDir: options.runDir,\n stepId: anchor.stepId,\n stepIndex,\n });\n\n const promptPhase = firstPromptPhase(getStepPhases(node));\n const outputSchema = promptPhase ? resolveStepOutputSchema(promptPhase) : undefined;\n if (!outputSchema) {\n return {\n status: \"failure\",\n failure: resumeFailure(\n \"resume_output_schema_unresolvable\",\n `Step ${node.config.id} has no resolvable output schema to reattach with.`,\n ),\n };\n }\n\n const reattached = await readReattachedInteractiveOutput({\n stepId: anchor.stepId,\n interactiveFile: artifactPaths.interactiveFile,\n outputSchema,\n });\n if (reattached.status === \"failure\") {\n return reattached;\n }\n\n const nextNode = await withStepContext(anchor.stepId, artifactPaths.stepDir, async () =>\n continueAfterPromptPhase(\n node,\n outputSchema.assert(reattached.output, `step ${node.config.id} output`),\n ),\n );\n\n return {\n status: \"success\",\n input,\n node: nextNode,\n resumedStepId: anchor.stepId,\n sourceFailureEventId: anchor.id,\n };\n}\n\n/**\n * Reads the anchor step's already-existing interactive.json protocol file —\n * never spawns a new agent process. If the session was still \"active\" when\n * the previous process died, re-enters the same file-polling wait the live\n * dispatch path uses (`waitForInteractiveCompletion`) rather than giving up.\n */\nasync function readReattachedInteractiveOutput(options: {\n readonly stepId: string;\n readonly interactiveFile: string;\n readonly outputSchema: Schema;\n}): Promise<\n | { readonly status: \"success\"; readonly output: PlainObject }\n | { readonly status: \"failure\"; readonly failure: Failure }\n> {\n const first = await tryReadCompletedInteractiveOutput(options);\n if (first.status !== \"still-active\") {\n return first;\n }\n\n const abortController = new AbortController();\n await waitForInteractiveCompletion(options.interactiveFile, abortController.signal);\n\n const second = await tryReadCompletedInteractiveOutput(options);\n if (second.status !== \"still-active\") {\n return second;\n }\n\n throw new TrailStepFailureError({\n code: \"interactive_session_incomplete\",\n message: `Interactive agent step ${options.stepId} did not complete after reattaching.`,\n });\n}\n\nasync function tryReadCompletedInteractiveOutput(options: {\n readonly stepId: string;\n readonly interactiveFile: string;\n readonly outputSchema: Schema;\n}): Promise<\n | { readonly status: \"success\"; readonly output: PlainObject }\n | { readonly status: \"failure\"; readonly failure: Failure }\n | { readonly status: \"still-active\" }\n> {\n try {\n return { status: \"success\", output: await readCompletedInteractiveOutput(options) };\n } catch (error) {\n if (error instanceof TrailStepFailureError) {\n if (error.failure.code === \"interactive_session_incomplete\") {\n return { status: \"still-active\" };\n }\n\n if (error.failure.code === \"interactive_session_cancelled\") {\n return {\n status: \"failure\",\n failure: resumeFailure(\n \"resume_interactive_session_cancelled\",\n `Interactive agent step ${options.stepId} was cancelled and cannot be resumed.`,\n ),\n };\n }\n\n if (error.failure.code === \"interactive_session_invalid\") {\n return {\n status: \"failure\",\n failure: resumeFailure(\n \"resume_interactive_protocol_missing\",\n `Interactive agent step ${options.stepId} has no readable interactive.json to reattach to.`,\n ),\n };\n }\n }\n\n throw error;\n }\n}\n\nasync function continueAfterPromptPhase(\n stepNode: Extract<ContinuationResult, { kind: \"step\" }>,\n promptOutput: PlainObject,\n): Promise<ContinuationResult> {\n let phaseValue = stepNode.config.input;\n let consumedPromptOutput = false;\n let nextNode: ContinuationResult | undefined;\n\n for (const phase of getStepPhases(stepNode)) {\n if (phase.kind === \"display\" || phase.kind === \"wait\") {\n continue;\n }\n\n if (nextNode !== undefined) {\n throw new Error(`step ${stepNode.config.id} has executable phases after a do phase`);\n }\n\n if (phase.kind === \"prompt\") {\n if (consumedPromptOutput) {\n throw new Error(`step ${stepNode.config.id} cannot reattach multiple prompt phases`);\n }\n phaseValue = promptOutput;\n consumedPromptOutput = true;\n continue;\n }\n\n nextNode = await phase.onOutput(phaseValue, stepNode.config.input);\n }\n\n if (nextNode === undefined) {\n throw new Error(`step ${stepNode.config.id} has no do phase`);\n }\n\n return nextNode;\n}\n\nfunction readPlainPayload(event: Event, key: string): PlainObject | undefined {\n const value = event.payload[key];\n return isPlainObject(value) ? value : undefined;\n}\n\nfunction isPlainObject(value: unknown): value is PlainObject {\n return (\n typeof value === \"object\" &&\n value !== null &&\n !Array.isArray(value) &&\n Object.getPrototypeOf(value) === Object.prototype\n );\n}\n\nfunction resumeFailure(code: string, message: string): Failure {\n return { code, message };\n}\n","import type { StepNode } from \"../../../authoring/step/continuation.types.js\";\nimport type { Failure } from \"../../../contracts/failures/failure.js\";\nimport type { PlainObject } from \"../../../contracts/shapes/shape.types.js\";\nimport type {\n Event,\n RunWorkflowOptions,\n} from \"../../../runtime/run-workflow/run-workflow.types.js\";\nimport { replayCompletedSteps } from \"../replay-completed-steps/replay-completed-steps.js\";\n\nexport async function replayToFailedStep<\n TInput extends PlainObject,\n TOutput extends PlainObject,\n>(options: {\n readonly workflow: RunWorkflowOptions<TInput, TOutput>[\"workflow\"];\n readonly events: readonly Event[];\n readonly runDir: string;\n}): Promise<\n | {\n readonly status: \"success\";\n readonly input: PlainObject;\n readonly node: StepNode;\n readonly resumedStepId: string;\n readonly sourceFailureEventId: string;\n }\n | { readonly status: \"failure\"; readonly failure: Failure }\n> {\n const startedEvent = options.events.find((event) => event.type === \"workflow.started\");\n if (!startedEvent) {\n return {\n status: \"failure\",\n failure: resumeFailure(\n \"resume_target_not_found\",\n \"Resume target has no workflow.started event.\",\n ),\n };\n }\n\n if (startedEvent.workflowId !== options.workflow.id) {\n return {\n status: \"failure\",\n failure: resumeFailure(\n \"resume_workflow_mismatch\",\n `Resume target workflow ${startedEvent.workflowId} does not match ${options.workflow.id}.`,\n ),\n };\n }\n\n const terminalEvent = options.events.at(-1);\n if (terminalEvent?.type !== \"workflow.failed\") {\n return {\n status: \"failure\",\n failure: resumeFailure(\n \"resume_target_not_failed\",\n \"Resume target must end in workflow.failed.\",\n ),\n };\n }\n\n const recoveredFailedStep = options.events.find(\n (event, index) =>\n event.type === \"step.failed\" &&\n options.events\n .slice(index + 1)\n .some(\n (laterEvent) =>\n laterEvent.type === \"step.completed\" && laterEvent.stepId === event.stepId,\n ),\n );\n if (recoveredFailedStep) {\n return {\n status: \"failure\",\n failure: resumeFailure(\n \"resume_unsupported_history\",\n `Resume does not support recovered onError history for step ${recoveredFailedStep.stepId ?? \"<missing>\"}.`,\n ),\n };\n }\n\n const failedStepEvents = options.events.filter((event) => event.type === \"step.failed\");\n if (failedStepEvents.length !== 1) {\n return {\n status: \"failure\",\n failure: resumeFailure(\n \"resume_multiple_failed_steps\",\n \"Resume target must contain exactly one failed step.\",\n ),\n };\n }\n\n const failedStepEvent = failedStepEvents[0];\n if (!failedStepEvent) {\n return {\n status: \"failure\",\n failure: resumeFailure(\"resume_target_not_failed\", \"Resume target has no failed step.\"),\n };\n }\n\n if (!failedStepEvent.stepId) {\n return {\n status: \"failure\",\n failure: resumeFailure(\"resume_target_not_failed\", \"Failed step event has no step id.\"),\n };\n }\n\n const input = readPlainPayload(startedEvent, \"input\");\n if (!input) {\n return {\n status: \"failure\",\n failure: resumeFailure(\n \"resume_target_not_found\",\n \"workflow.started payload is missing input.\",\n ),\n };\n }\n\n const replay = await replayCompletedSteps({\n workflow: options.workflow,\n events: options.events,\n input,\n targetStepId: failedStepEvent.stepId,\n runDir: options.runDir,\n });\n if (replay.status === \"failure\") {\n return replay;\n }\n\n const { node } = replay;\n if (node.onError) {\n return {\n status: \"failure\",\n failure: resumeFailure(\n \"resume_unsupported_history\",\n `Resume does not support onError history for step ${node.config.id}.`,\n ),\n };\n }\n\n return {\n status: \"success\",\n input,\n node,\n resumedStepId: failedStepEvent.stepId,\n sourceFailureEventId: failedStepEvent.id,\n };\n}\n\nfunction readPlainPayload(event: Event, key: string): PlainObject | undefined {\n const value = event.payload[key];\n return isPlainObject(value) ? value : undefined;\n}\n\nfunction isPlainObject(value: unknown): value is PlainObject {\n return (\n typeof value === \"object\" &&\n value !== null &&\n !Array.isArray(value) &&\n Object.getPrototypeOf(value) === Object.prototype\n );\n}\n\nfunction resumeFailure(code: string, message: string): Failure {\n return { code, message };\n}\n","import { readFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport type { StepNode, WaitPhase } from \"../../../authoring/step/continuation.types.js\";\nimport { getStepPhases } from \"../../../authoring/step/step-node.js\";\nimport type { Failure } from \"../../../contracts/failures/failure.js\";\nimport type { PlainObject } from \"../../../contracts/shapes/shape.types.js\";\nimport type {\n Event,\n RunWorkflowOptions,\n} from \"../../../runtime/run-workflow/run-workflow.types.js\";\nimport { resolveStepOutputSchema } from \"../../continuation/resolve-step-output-schema/resolve-step-output-schema.js\";\nimport { withStepContext } from \"../../run-context/with-step-context.js\";\nimport { replayCompletedSteps } from \"../replay-completed-steps/replay-completed-steps.js\";\n\nexport interface ReplayToWaitingStepResult {\n readonly status: \"success\";\n readonly input: PlainObject;\n readonly node: StepNode;\n readonly resumedStepId: string;\n readonly sourceWaitEventId: string;\n readonly stepIndex: number;\n readonly phaseIndex: number;\n readonly phaseValue: PlainObject;\n readonly waitOutputs: Readonly<Record<string, PlainObject>>;\n readonly seenWaitIds: readonly string[];\n readonly wait: {\n readonly waitId: string;\n readonly kind: \"input\" | \"check\";\n readonly message: string;\n readonly artifactPaths: { readonly requestFile: string; readonly answerFile: string };\n readonly outputSchema: Record<string, unknown>;\n };\n}\n\nexport async function replayToWaitingStep<\n TInput extends PlainObject,\n TOutput extends PlainObject,\n>(options: {\n readonly workflow: RunWorkflowOptions<TInput, TOutput>[\"workflow\"];\n readonly events: readonly Event[];\n readonly runDir: string;\n}): Promise<ReplayToWaitingStepResult | { readonly status: \"failure\"; readonly failure: Failure }> {\n const startedEvent = options.events.find((event) => event.type === \"workflow.started\");\n if (!startedEvent) {\n return {\n status: \"failure\",\n failure: resumeFailure(\n \"continue_target_not_found\",\n \"Continue target has no workflow.started event.\",\n ),\n };\n }\n\n if (startedEvent.workflowId !== options.workflow.id) {\n return {\n status: \"failure\",\n failure: resumeFailure(\n \"continue_workflow_mismatch\",\n `Continue target workflow ${startedEvent.workflowId} does not match ${options.workflow.id}.`,\n ),\n };\n }\n\n if (options.events.some((event) => event.type === \"workflow.completed\")) {\n return {\n status: \"failure\",\n failure: resumeFailure(\n \"continue_target_not_waiting\",\n \"Continue target is already completed.\",\n ),\n };\n }\n\n const pendingWait = findLatestPendingWait(options.events);\n if (!pendingWait?.stepId) {\n return {\n status: \"failure\",\n failure: resumeFailure(\"continue_target_not_waiting\", \"Continue target has no pending wait.\"),\n };\n }\n\n const input = readPlainPayload(startedEvent, \"input\");\n if (!input) {\n return {\n status: \"failure\",\n failure: resumeFailure(\n \"continue_target_not_found\",\n \"workflow.started payload is missing input.\",\n ),\n };\n }\n\n const waitId = readWaitId(pendingWait);\n if (!waitId) {\n return {\n status: \"failure\",\n failure: resumeFailure(\"continue_wait_invalid\", \"Pending wait event has no wait id.\"),\n };\n }\n\n const stepIndex =\n readStepIndex(pendingWait) ?? stepStartedOrdinalBefore(options.events, pendingWait);\n if (stepIndex === undefined) {\n return {\n status: \"failure\",\n failure: resumeFailure(\n \"continue_wait_invalid\",\n `Pending wait ${waitId} has no resolvable step artifact index.`,\n ),\n };\n }\n\n const targetStepStartedIndex = findStepStartedIndex(options.events, pendingWait, stepIndex);\n if (targetStepStartedIndex === undefined) {\n return {\n status: \"failure\",\n failure: resumeFailure(\n \"continue_wait_invalid\",\n `Pending wait ${waitId} has no matching step.started event.`,\n ),\n };\n }\n\n const replay = await replayCompletedSteps({\n workflow: options.workflow,\n events: options.events.slice(0, targetStepStartedIndex),\n input,\n targetStepId: pendingWait.stepId,\n runDir: options.runDir,\n });\n if (replay.status === \"failure\") {\n return replay;\n }\n\n const prefix = await withStepContext(\n pendingWait.stepId,\n stepDirForIndex(options.runDir, pendingWait, stepIndex),\n async () =>\n replayWaitingStepPrefix({\n node: replay.node,\n events: options.events,\n targetStepStartedIndex,\n pendingWait,\n }),\n );\n if (prefix.status === \"failure\") {\n return prefix;\n }\n\n const wait = await readResumedWaitDetails(options.runDir, pendingWait, waitId);\n if (wait.status === \"failure\") {\n return wait;\n }\n\n return {\n status: \"success\",\n input,\n node: replay.node,\n resumedStepId: pendingWait.stepId,\n sourceWaitEventId: pendingWait.id,\n stepIndex,\n phaseIndex: prefix.phaseIndex,\n phaseValue: prefix.phaseValue,\n waitOutputs: prefix.waitOutputs,\n seenWaitIds: prefix.seenWaitIds,\n wait: wait.wait,\n };\n}\n\nasync function readResumedWaitDetails(\n runDir: string,\n waitEvent: Event,\n waitId: string,\n): Promise<\n | {\n readonly status: \"success\";\n readonly wait: {\n readonly waitId: string;\n readonly kind: \"input\" | \"check\";\n readonly message: string;\n readonly artifactPaths: { readonly requestFile: string; readonly answerFile: string };\n readonly outputSchema: Record<string, unknown>;\n };\n }\n | { readonly status: \"failure\"; readonly failure: Failure }\n> {\n const artifactPaths = readWaitArtifactPaths(waitEvent);\n if (!artifactPaths) {\n return {\n status: \"failure\",\n failure: resumeFailure(\n \"continue_wait_invalid\",\n `Pending wait ${waitId} has no recorded artifact paths.`,\n ),\n };\n }\n\n let request: unknown;\n try {\n request = JSON.parse(\n await readFile(join(runDir, ...artifactPaths.requestFile.split(\"/\")), \"utf8\"),\n );\n } catch {\n return {\n status: \"failure\",\n failure: resumeFailure(\n \"continue_wait_invalid\",\n `Pending wait ${waitId} has no readable wait request artifact.`,\n ),\n };\n }\n\n if (!isPlainObject(request) || !isPlainObject(request.outputSchema)) {\n return {\n status: \"failure\",\n failure: resumeFailure(\n \"continue_wait_invalid\",\n `Pending wait ${waitId} request artifact is missing outputSchema.`,\n ),\n };\n }\n\n const kind = request.kind === \"check\" ? \"check\" : \"input\";\n const message = typeof waitEvent.payload.message === \"string\" ? waitEvent.payload.message : \"\";\n return {\n status: \"success\",\n wait: {\n waitId,\n kind,\n message,\n artifactPaths,\n outputSchema: request.outputSchema,\n },\n };\n}\n\nfunction findLatestPendingWait(events: readonly Event[]): Event | undefined {\n for (let index = events.length - 1; index >= 0; index -= 1) {\n const event = events[index];\n if (event?.type !== \"wait.started\") {\n continue;\n }\n\n const key = waitEventKey(event);\n if (!key) {\n continue;\n }\n\n const resolvedLater = events\n .slice(index + 1)\n .some(\n (laterEvent) =>\n (laterEvent.type === \"wait.satisfied\" || laterEvent.type === \"wait.failed\") &&\n waitEventKey(laterEvent) === key,\n );\n if (!resolvedLater) {\n return event;\n }\n }\n\n return undefined;\n}\n\nasync function replayWaitingStepPrefix(options: {\n readonly node: StepNode;\n readonly events: readonly Event[];\n readonly targetStepStartedIndex: number;\n readonly pendingWait: Event;\n}): Promise<\n | {\n readonly status: \"success\";\n readonly phaseIndex: number;\n readonly phaseValue: PlainObject;\n readonly waitOutputs: Readonly<Record<string, PlainObject>>;\n readonly seenWaitIds: readonly string[];\n }\n | { readonly status: \"failure\"; readonly failure: Failure }\n> {\n const waitId = readWaitId(options.pendingWait);\n const targetPhaseIndex =\n typeof options.pendingWait.payload.phaseIndex === \"number\"\n ? options.pendingWait.payload.phaseIndex\n : undefined;\n const pendingWaitIndex = options.events.indexOf(options.pendingWait);\n const inStepEvents = options.events.slice(options.targetStepStartedIndex + 1, pendingWaitIndex);\n const promptOutputs = inStepEvents.filter(\n (event) =>\n event.type === \"step.completed\" &&\n event.stepId === options.node.config.id &&\n isPlainObject(event.payload.output),\n );\n const satisfiedWaits = inStepEvents.filter(\n (event) =>\n event.type === \"wait.satisfied\" &&\n event.stepId === options.node.config.id &&\n isPlainObject(event.payload.output) &&\n typeof event.payload.waitId === \"string\",\n );\n\n let phaseValue = options.node.config.input;\n let promptOutputIndex = 0;\n let satisfiedWaitIndex = 0;\n const waitOutputs: Record<string, PlainObject> = {};\n const seenWaitIds: string[] = [];\n\n for (const [phaseIndex, phase] of getStepPhases(options.node).entries()) {\n if (phase.kind === \"display\") {\n continue;\n }\n\n if (phase.kind === \"prompt\") {\n const completedEvent = promptOutputs[promptOutputIndex];\n promptOutputIndex += 1;\n if (!completedEvent || !isPlainObject(completedEvent.payload.output)) {\n return {\n status: \"failure\",\n failure: resumeFailure(\n \"continue_missing_step_output\",\n `Step ${options.node.config.id} has no recorded prompt output before wait ${waitId ?? \"<missing>\"}.`,\n ),\n };\n }\n\n const outputSchema = resolveStepOutputSchema(phase);\n if (!outputSchema) {\n return {\n status: \"failure\",\n failure: resumeFailure(\n \"continue_output_schema_unresolvable\",\n `Step ${options.node.config.id} has no resolvable output schema to continue with.`,\n ),\n };\n }\n phaseValue = outputSchema.assert(\n completedEvent.payload.output,\n `step ${options.node.config.id} output`,\n );\n continue;\n }\n\n if (phase.kind === \"wait\") {\n const isTargetPhase =\n targetPhaseIndex === undefined\n ? await waitPhaseMatches(phase, {\n phaseValue,\n waitOutputs,\n input: options.node.config.input,\n waitId,\n })\n : phaseIndex === targetPhaseIndex;\n if (isTargetPhase) {\n return {\n status: \"success\",\n phaseIndex,\n phaseValue,\n waitOutputs,\n seenWaitIds,\n };\n }\n\n const satisfiedEvent = satisfiedWaits[satisfiedWaitIndex];\n satisfiedWaitIndex += 1;\n const satisfiedWaitId =\n typeof satisfiedEvent?.payload.waitId === \"string\"\n ? satisfiedEvent.payload.waitId\n : undefined;\n if (!satisfiedWaitId || !isPlainObject(satisfiedEvent?.payload.output)) {\n return {\n status: \"failure\",\n failure: resumeFailure(\n \"continue_missing_wait_output\",\n `Step ${options.node.config.id} has no recorded satisfied wait output before wait ${waitId ?? \"<missing>\"}.`,\n ),\n };\n }\n\n if (seenWaitIds.includes(satisfiedWaitId)) {\n return {\n status: \"failure\",\n failure: resumeFailure(\n \"continue_duplicate_wait_id\",\n `Step ${options.node.config.id} has duplicate wait id '${satisfiedWaitId}'.`,\n ),\n };\n }\n seenWaitIds.push(satisfiedWaitId);\n waitOutputs[satisfiedWaitId] = satisfiedEvent.payload.output;\n continue;\n }\n\n return {\n status: \"failure\",\n failure: resumeFailure(\n \"continue_wait_after_do\",\n `Pending wait ${waitId ?? \"<missing>\"} occurs after step ${options.node.config.id}'s do phase.`,\n ),\n };\n }\n\n return {\n status: \"failure\",\n failure: resumeFailure(\n \"continue_wait_not_reachable\",\n `Pending wait ${waitId ?? \"<missing>\"} was not found in step ${options.node.config.id}.`,\n ),\n };\n}\n\nasync function waitPhaseMatches(\n phase: WaitPhase,\n context: {\n readonly phaseValue: PlainObject;\n readonly waitOutputs: Readonly<Record<string, PlainObject>>;\n readonly input: PlainObject;\n readonly waitId: string | undefined;\n },\n): Promise<boolean> {\n if (!context.waitId) {\n return false;\n }\n\n if (phase.options !== undefined) {\n return false;\n }\n\n const wait =\n typeof phase.wait === \"function\"\n ? await (\n phase.wait as (waitContext: {\n readonly input: PlainObject;\n readonly output: PlainObject;\n readonly waits: Readonly<Record<string, PlainObject>>;\n }) => unknown | Promise<unknown>\n )({\n input: context.input,\n output: context.phaseValue,\n waits: context.waitOutputs,\n })\n : phase.wait;\n return isPlainObject(wait) && wait.id === context.waitId;\n}\n\nfunction findStepStartedIndex(\n events: readonly Event[],\n pendingWait: Event,\n stepIndex: number,\n): number | undefined {\n let ordinal = 0;\n for (const [index, event] of events.entries()) {\n if (event.type !== \"step.started\") {\n continue;\n }\n ordinal += 1;\n if (ordinal === stepIndex) {\n return index;\n }\n }\n\n for (let index = events.indexOf(pendingWait); index >= 0; index -= 1) {\n const event = events[index];\n if (event?.type === \"step.started\" && event.stepId === pendingWait.stepId) {\n return index;\n }\n }\n\n return undefined;\n}\n\nfunction stepStartedOrdinalBefore(\n events: readonly Event[],\n pendingWait: Event,\n): number | undefined {\n const waitIndex = events.indexOf(pendingWait);\n if (waitIndex === -1) {\n return undefined;\n }\n const count = events.slice(0, waitIndex).filter((event) => event.type === \"step.started\").length;\n return count > 0 ? count : undefined;\n}\n\nfunction readStepIndex(event: Event): number | undefined {\n const artifactStepId = readArtifactStepId(event);\n const prefix = artifactStepId?.match(/^(\\d+)-/u)?.[1];\n if (prefix === undefined) {\n return undefined;\n }\n\n const stepIndex = Number(prefix);\n return Number.isInteger(stepIndex) && stepIndex > 0 ? stepIndex : undefined;\n}\n\nfunction stepDirForIndex(runDir: string, event: Event, stepIndex: number): string {\n const artifactStepId =\n readArtifactStepId(event) ?? `${String(stepIndex).padStart(4, \"0\")}-${event.stepId ?? \"step\"}`;\n return join(runDir, \"steps\", artifactStepId);\n}\n\nfunction readArtifactStepId(event: Event): string | undefined {\n const artifactPaths = readWaitArtifactPaths(event);\n const path = artifactPaths?.requestFile ?? artifactPaths?.answerFile;\n return path?.match(/^steps\\/([^/]+)\\/waits\\//u)?.[1];\n}\n\nfunction readWaitArtifactPaths(\n event: Event,\n): { readonly requestFile: string; readonly answerFile: string } | undefined {\n const artifactPaths = event.payload.artifactPaths;\n if (!isPlainObject(artifactPaths)) {\n return undefined;\n }\n\n const requestFile = artifactPaths.requestFile;\n const answerFile = artifactPaths.answerFile;\n if (typeof requestFile !== \"string\" || typeof answerFile !== \"string\") {\n return undefined;\n }\n\n return { requestFile, answerFile };\n}\n\nfunction waitEventKey(event: Event): string | undefined {\n const artifactPaths = event.payload.artifactPaths;\n if (isPlainObject(artifactPaths) && typeof artifactPaths.answerFile === \"string\") {\n return artifactPaths.answerFile;\n }\n\n const waitId = readWaitId(event);\n return event.stepId && waitId ? `${event.stepId}:${waitId}` : undefined;\n}\n\nfunction readWaitId(event: Event): string | undefined {\n return typeof event.payload.waitId === \"string\" ? event.payload.waitId : undefined;\n}\n\nfunction readPlainPayload(event: Event, key: string): PlainObject | undefined {\n const value = event.payload[key];\n return isPlainObject(value) ? value : undefined;\n}\n\nfunction isPlainObject(value: unknown): value is PlainObject {\n return (\n typeof value === \"object\" &&\n value !== null &&\n !Array.isArray(value) &&\n Object.getPrototypeOf(value) === Object.prototype\n );\n}\n\nfunction resumeFailure(code: string, message: string): Failure {\n return { code, message };\n}\n","import type { StepNode } from \"../../authoring/step/continuation.types.js\";\nimport type { Failure } from \"../../contracts/failures/failure.js\";\nimport type { PlainObject } from \"../../contracts/shapes/shape.types.js\";\nimport { replayCompletedSteps } from \"../resume/replay-completed-steps/replay-completed-steps.js\";\nimport type { Event, RunWorkflowOptions } from \"../run-workflow/run-workflow.types.js\";\nimport { selectLatestUnresolvedFailure } from \"./latest-unresolved-failure.js\";\n\nexport async function replayToRetryFailure<\n TInput extends PlainObject,\n TOutput extends PlainObject,\n>(options: {\n readonly workflow: RunWorkflowOptions<TInput, TOutput>[\"workflow\"];\n readonly events: readonly Event[];\n readonly runDir: string;\n}): Promise<\n | {\n readonly status: \"success\";\n readonly input: PlainObject;\n readonly node: StepNode;\n readonly retriedStepId: string;\n readonly sourceFailureEventId: string;\n readonly sourceFailureReplayPosition: number;\n }\n | { readonly status: \"failure\"; readonly failure: Failure }\n> {\n const failure = selectLatestUnresolvedFailure(options.events);\n if (!failure) {\n return {\n status: \"failure\",\n failure: retryFailure(\n \"retry_target_not_failed\",\n \"Retry target has no latest unresolved failure.\",\n ),\n };\n }\n\n if (failure.workflowId !== options.workflow.id) {\n return {\n status: \"failure\",\n failure: retryFailure(\n \"retry_workflow_mismatch\",\n `Retry target workflow ${failure.workflowId} does not match ${options.workflow.id}.`,\n ),\n };\n }\n\n if (!failure.workflowInput) {\n return {\n status: \"failure\",\n failure: retryFailure(\"retry_target_not_found\", \"workflow.started payload is missing input.\"),\n };\n }\n\n if (!failure.stepId) {\n return {\n status: \"failure\",\n failure: retryFailure(\n \"retry_target_not_failed\",\n failure.event.type === \"workflow.failed\"\n ? \"Workflow failure has no associated step ID. This run may use unsupported historical retry metadata.\"\n : \"Failed retry target event has no step ID.\",\n ),\n };\n }\n\n const replay = await replayCompletedSteps({\n workflow: options.workflow,\n events: eventsBeforeRetryTarget(\n options.events,\n failure.replayPosition,\n failure.stepId,\n failure.event,\n ),\n input: failure.workflowInput,\n targetStepId: failure.stepId,\n runDir: options.runDir,\n });\n if (replay.status === \"failure\") {\n return replay;\n }\n\n const { node } = replay;\n if (node.onError) {\n return {\n status: \"failure\",\n failure: retryFailure(\n \"retry_unsupported_history\",\n `Retry does not support onError history for step ${node.config.id}.`,\n ),\n };\n }\n\n return {\n status: \"success\",\n input: failure.workflowInput,\n node,\n retriedStepId: failure.stepId,\n sourceFailureEventId: failure.sourceFailureEventId ?? failure.event.id,\n sourceFailureReplayPosition: failure.replayPosition,\n };\n}\n\nfunction eventsBeforeRetryTarget(\n events: readonly Event[],\n replayPosition: number,\n targetStepId: string,\n targetEvent: Event,\n): readonly Event[] {\n const eventsBeforeFailure = events.slice(0, replayPosition);\n const excludedPositions = new Set<number>();\n\n for (const event of eventsBeforeFailure) {\n if (event.type !== \"workflow.retryStarted\") {\n continue;\n }\n\n const resolvedPosition = readSourceFailureReplayPosition(event);\n if (resolvedPosition === undefined || resolvedPosition >= replayPosition) {\n continue;\n }\n\n for (const position of resolvedAttemptPositions(events, resolvedPosition)) {\n excludedPositions.add(position);\n }\n }\n\n if (targetEvent.type === \"step.started\") {\n return eventsBeforeFailure.filter(\n (event, index) => !excludedPositions.has(index) || shouldKeepResolvedAttemptEvent(event),\n );\n }\n\n let targetAttemptStartPosition = -1;\n for (let index = eventsBeforeFailure.length - 1; index >= 0; index -= 1) {\n const event = eventsBeforeFailure[index];\n if (excludedPositions.has(index)) {\n continue;\n }\n\n if (event?.type === \"step.started\" && event.stepId === targetStepId) {\n targetAttemptStartPosition = index;\n break;\n }\n }\n\n return eventsBeforeFailure.filter((event, index) => {\n if (excludedPositions.has(index) && !shouldKeepResolvedAttemptEvent(event)) {\n return false;\n }\n\n return (\n targetAttemptStartPosition === -1 ||\n index <= targetAttemptStartPosition ||\n event.type !== \"step.completed\" ||\n event.stepId !== targetStepId\n );\n });\n}\n\nfunction shouldKeepResolvedAttemptEvent(event: Event): boolean {\n // Replay must not consume completed outputs from a previously failed attempt,\n // but it still needs the attempt's start/terminal events so step artifact\n // ordinals remain aligned with the original event stream and failed starts are\n // paired off before later retried attempts with the same step id complete.\n return (\n event.type === \"step.started\" || event.type === \"step.failed\" || event.type === \"step.cancelled\"\n );\n}\n\nfunction readSourceFailureReplayPosition(event: Event): number | undefined {\n const { sourceFailureReplayPosition } = event.payload;\n return typeof sourceFailureReplayPosition === \"number\" ? sourceFailureReplayPosition : undefined;\n}\n\nfunction resolvedAttemptPositions(\n events: readonly Event[],\n resolvedPosition: number,\n): readonly number[] {\n const resolvedEvent = events[resolvedPosition];\n if (!resolvedEvent?.stepId) {\n return [resolvedPosition];\n }\n\n const attemptStartPosition = findAttemptStartPosition(\n events,\n resolvedPosition,\n resolvedEvent.stepId,\n );\n const startPosition = attemptStartPosition === -1 ? resolvedPosition : attemptStartPosition;\n const positions: number[] = [];\n for (let position = startPosition; position <= resolvedPosition; position += 1) {\n positions.push(position);\n }\n\n return positions;\n}\n\nfunction findAttemptStartPosition(\n events: readonly Event[],\n resolvedPosition: number,\n stepId: string,\n): number {\n for (let index = resolvedPosition; index >= 0; index -= 1) {\n const event = events[index];\n if (event?.type === \"step.started\" && event.stepId === stepId) {\n return index;\n }\n }\n\n return -1;\n}\n\nfunction retryFailure(code: string, message: string): Failure {\n return { code, message };\n}\n","import type { TrailStepConfig } from \"../../agent-targeting/targeting.types.js\";\nimport type { WorkflowAgentRole } from \"../../contracts/agents/agent-role.types.js\";\nimport type {\n RunContext,\n RunContextEvent,\n RunContextGlobalState,\n RunContextProviderWorkingRunner,\n RunContextState,\n RunContextWorkingAgentProcessRunner,\n} from \"../../contracts/run-context/run-context.types.js\";\nimport {\n type RunState,\n readGlobalState,\n readRunState,\n writeGlobalState,\n writeRunState,\n} from \"../artifacts/run-storage.js\";\n\nexport function createRunContext(options: {\n readonly runId: string;\n readonly runName: string;\n readonly runDir: string;\n readonly initialState?: RunState;\n readonly workflowId?: string;\n readonly workflowAgents?: Readonly<Record<string, WorkflowAgentRole>>;\n readonly projectCwd?: string;\n readonly cwd?: string;\n readonly executionCwd?: string;\n readonly trailstepConfig?: TrailStepConfig;\n readonly workingAgentProcessRunner?: RunContextWorkingAgentProcessRunner;\n readonly providerWorkingRunner?: RunContextProviderWorkingRunner;\n readonly emit?: (event: RunContextEvent) => Promise<void>;\n readonly events?: () => readonly RunContextEvent[];\n}): RunContext {\n const state = createQueuedRunState({\n read: () => readRunState(options.runDir),\n write: (nextState) => writeRunState(options.runDir, nextState),\n ...(options.initialState === undefined ? {} : { initialState: options.initialState }),\n });\n const globalState = createQueuedGlobalState({\n read: () => readGlobalState(options.runDir),\n write: (nextState) => writeGlobalState(options.runDir, nextState),\n });\n\n return {\n id: options.runId,\n name: options.runName,\n path: options.runDir,\n workflowId: options.workflowId,\n workflowAgents: options.workflowAgents,\n projectCwd: options.projectCwd,\n cwd: options.cwd,\n executionCwd: options.executionCwd ?? options.cwd,\n trailstepConfig: options.trailstepConfig,\n workingAgentProcessRunner: options.workingAgentProcessRunner,\n providerWorkingRunner: options.providerWorkingRunner,\n emit: options.emit,\n events: options.events,\n state,\n globalState,\n };\n}\n\nexport function createQueuedRunState(options: {\n readonly read: () => Promise<RunState>;\n readonly write: (state: RunState) => Promise<void>;\n readonly initialState?: RunState;\n}): RunContextState {\n let cache: RunState | undefined;\n let loadPromise: Promise<RunState> | undefined;\n let writeQueue: Promise<unknown> = Promise.resolve();\n\n function ensureLoaded(): Promise<RunState> {\n if (cache) return Promise.resolve(cache);\n if (options.initialState !== undefined) {\n cache = { ...options.initialState };\n return Promise.resolve(cache);\n }\n loadPromise ??= options.read().then((state) => (cache = state));\n return loadPromise;\n }\n\n function enqueueWrite(): Promise<void> {\n const next = writeQueue.then(async () => {\n const state = await ensureLoaded();\n await options.write(state);\n });\n writeQueue = next.catch(() => {});\n return next;\n }\n\n return {\n async get<T = unknown>(key: string): Promise<T | undefined> {\n const state = await ensureLoaded();\n return state[key] as T | undefined;\n },\n async getPersisted<T = unknown>(key: string): Promise<T | undefined> {\n const state = await options.read();\n return state[key] as T | undefined;\n },\n async hydratePersisted(): Promise<void> {\n const persisted = await options.read();\n const state = await ensureLoaded();\n cache = { ...state, ...persisted };\n },\n async set(\n key: string,\n value: unknown,\n options: { readonly persist?: boolean } = {},\n ): Promise<void> {\n const state = await ensureLoaded();\n state[key] = value;\n if (options.persist !== false) {\n await enqueueWrite();\n }\n },\n };\n}\n\nexport function createQueuedGlobalState(options: {\n readonly read: () => Promise<RunState>;\n readonly write: (state: RunState) => Promise<void>;\n}): RunContextGlobalState {\n let cache: RunState | undefined;\n let loadPromise: Promise<RunState> | undefined;\n let mutationQueue: Promise<unknown> = Promise.resolve();\n\n function ensureLoaded(): Promise<RunState> {\n if (cache) return Promise.resolve(cache);\n loadPromise ??= options.read().then((state) => (cache = state));\n return loadPromise;\n }\n\n function enqueueMutation<T>(mutation: (state: RunState) => Promise<T>): Promise<T> {\n const next = mutationQueue.then(async () => {\n const state = await ensureLoaded();\n return await mutation(state);\n });\n mutationQueue = next.catch(() => {});\n return next;\n }\n\n return {\n async get<T = unknown>(key: string): Promise<T | undefined> {\n const state = await mutationQueue.then(() => ensureLoaded());\n return state[key] as T | undefined;\n },\n async getPersisted<T = unknown>(key: string): Promise<T | undefined> {\n const state = await mutationQueue.then(() => options.read());\n return state[key] as T | undefined;\n },\n async hydratePersisted(): Promise<void> {\n await enqueueMutation(async (state) => {\n const persisted = await options.read();\n for (const [key, value] of Object.entries(persisted)) {\n state[key] = value;\n }\n });\n },\n async set(\n key: string,\n value: unknown,\n setOptions: { readonly persist?: boolean } = {},\n ): Promise<void> {\n await enqueueMutation(async (state) => {\n state[key] = value;\n if (setOptions.persist !== false) {\n await options.write(state);\n }\n });\n },\n async update<T = unknown>(\n key: string,\n updater: (current: T | undefined) => T | Promise<T>,\n ): Promise<T> {\n return await enqueueMutation(async (state) => {\n const updated = await updater(state[key] as T | undefined);\n state[key] = updated;\n await options.write(state);\n return updated;\n });\n },\n };\n}\n","import { basename } from \"node:path\";\n\nimport type { PlainObject } from \"../../contracts/shapes/shape.types.js\";\nimport { createRunDirectory, readRunEvents } from \"../artifacts/run-storage.js\";\nimport { resolveAndValidateRunCwds } from \"./cwd.js\";\nimport type { Event, RunWorkflowOptions } from \"./run-workflow.types.js\";\n\nexport async function initializeRun<TInput extends PlainObject, TOutput extends PlainObject>(\n options: RunWorkflowOptions<TInput, TOutput>,\n): Promise<{\n readonly runId: string;\n readonly runName: string;\n readonly runDir: string;\n readonly previousEvents: readonly Event[];\n}> {\n const existingRunDir =\n options.resume?.runDir ?? options.retry?.runDir ?? options.continue?.runDir;\n if (existingRunDir) {\n const previousEvents = await readRunEvents(existingRunDir);\n const startedEvent = previousEvents.find((event) => event.type === \"workflow.started\");\n return {\n runId: startedEvent?.runId ?? basename(existingRunDir),\n runName: startedEvent?.runId ?? basename(existingRunDir),\n runDir: existingRunDir,\n previousEvents,\n };\n }\n\n const { projectCwd } = await resolveAndValidateRunCwds(options);\n const runName = options.runName;\n if (runName === undefined) {\n throw new Error(\"Expected runName for a new workflow run.\");\n }\n const { runId, runDir } = await createRunDirectory({\n cwd: projectCwd,\n runName,\n runsRoot: options.runsRoot,\n });\n return { runId, runName, runDir, previousEvents: [] };\n}\n","import { mkdir, readFile, writeFile } from \"node:fs/promises\";\nimport { availableParallelism } from \"node:os\";\nimport { join } from \"node:path\";\nimport type { TrailStepConfig } from \"../../agent-targeting/targeting.types.js\";\nimport type {\n ContinuationResult,\n ParallelFailurePolicy,\n ParallelOptions,\n} from \"../../authoring/step/continuation.types.js\";\nimport {\n isParallelNode,\n isStepNode,\n isWorkflowInvocationNode,\n} from \"../../authoring/step/step-node.js\";\nimport type { WorkflowAgentRole } from \"../../contracts/agents/agent-role.types.js\";\nimport type { Failure } from \"../../contracts/failures/failure.js\";\nimport type { PlainObject } from \"../../contracts/shapes/shape.types.js\";\nimport { readBranchRunState, writeBranchRunState } from \"../artifacts/run-storage.js\";\nimport { resolveStepArtifactPaths } from \"../artifacts/step-artifacts.js\";\nimport {\n type RunContinuationResult,\n runContinuation,\n type WaitingWait,\n} from \"../continuation/run-continuation/run-continuation.js\";\nimport { createQueuedRunState } from \"../run-context/create-run-context.js\";\nimport { runContextStorage } from \"../run-context/run-context-storage.js\";\nimport type { TimeoutPolicyInput } from \"../timeout/timeout-policy.js\";\nimport type {\n Event,\n RunWorkflowOptions,\n RunWorkflowTrackRetryOptions,\n} from \"./run-workflow.types.js\";\n\ninterface RunRootContinuationArraySchedulerOptions {\n readonly nodes: readonly ContinuationResult[];\n readonly rootIsArray?: boolean;\n readonly runId: string;\n readonly workflowId: string;\n readonly emit: (event: Event) => Promise<void>;\n readonly maxSteps: number;\n readonly initialSource: string;\n readonly workers?: number;\n readonly workflowAgents: Readonly<Record<string, WorkflowAgentRole>>;\n readonly workflowTimeout?: TimeoutPolicyInput;\n readonly runDir: string;\n readonly projectCwd?: string;\n readonly cwd: string;\n readonly trailstepConfig?: TrailStepConfig;\n readonly workingAgentProcessRunner?: RunWorkflowOptions[\"workingAgentProcessRunner\"];\n readonly providerWorkingRunner?: RunWorkflowOptions[\"providerWorkingRunner\"];\n readonly processRunner?: RunWorkflowOptions[\"processRunner\"];\n readonly retry?: {\n readonly initialExecutedSteps: number;\n readonly track?: RunWorkflowTrackRetryOptions;\n };\n}\n\ntype BranchStatus = \"queued\" | \"running\" | \"done\" | \"failed\" | \"waiting\" | \"cancelled\" | \"split\";\ntype TrackTerminalKind = \"absoluteDone\" | \"absoluteFail\" | \"failure\" | \"waiting\" | \"cancelled\";\ntype AbsoluteTerminalKind = \"absoluteDone\" | \"absoluteFail\";\n\ninterface TrackStateJson {\n readonly runId: string;\n readonly status: string;\n readonly workers: number;\n readonly failurePolicy: \"fail-fast\";\n readonly rootBranchId: string;\n readonly splitOccurred: boolean;\n readonly branches: readonly string[];\n readonly terminalBranchId?: string;\n readonly terminalKind?: TrackTerminalKind;\n readonly terminalOutput?: PlainObject;\n readonly failure?: Failure;\n}\n\ninterface BranchState {\n readonly branchId: string;\n readonly parentBranchId?: string;\n readonly requestedBranchId?: string;\n readonly joinContinuation?: boolean;\n pendingPostJoin?: boolean;\n readonly workflowId: string;\n readonly createdAt: string;\n status: BranchStatus;\n output?: PlainObject;\n failure?: Failure;\n wait?: WaitingWait;\n terminalKind?: AbsoluteTerminalKind;\n message?: string;\n source: string;\n splitSource?: string;\n updatedAt: string;\n latestStepIndex: number;\n latestStepId?: string;\n}\n\ninterface PendingJoin {\n readonly parentBranchId: string;\n readonly childBranchIds: readonly string[];\n readonly source: string;\n readonly failurePolicy: ParallelFailurePolicy;\n readonly postContinuation: (\n output: PlainObject,\n ) => ContinuationResult | Promise<ContinuationResult>;\n readonly afterPostContinuation?: (\n output: PlainObject,\n ) => ContinuationResult | Promise<ContinuationResult>;\n completed: Readonly<Record<string, PlainObject>>;\n}\n\ninterface BranchStateJson {\n readonly branchId: string;\n readonly parentBranchId?: string;\n readonly requestedBranchId?: string;\n readonly joinContinuation?: boolean;\n readonly pendingPostJoin?: boolean;\n readonly status: BranchStatus;\n readonly workflowId: string;\n readonly source: string;\n readonly splitSource?: string;\n readonly output: PlainObject;\n readonly failure?: Failure;\n readonly wait?: WaitingWait;\n readonly terminalKind?: AbsoluteTerminalKind;\n readonly message?: string;\n readonly createdAt: string;\n readonly updatedAt: string;\n readonly latestStepIndex: number;\n readonly latestStepId?: string;\n}\n\ninterface QueuedBranch {\n readonly node: ContinuationResult;\n readonly branch: BranchState;\n readonly source: string;\n readonly requireRunnableBranchCandidate: boolean;\n readonly parallelGroupId?: string;\n readonly parallelConcurrency?: number;\n readonly failurePolicy: ParallelFailurePolicy;\n}\n\nexport async function runRootContinuationArrayScheduler(\n options: RunRootContinuationArraySchedulerOptions,\n): Promise<RunContinuationResult> {\n const resolvedWorkers = resolveSchedulerWorkerCount(options.workers);\n if (!resolvedWorkers.ok) {\n return resolvedWorkers.failure;\n }\n\n const workers = resolvedWorkers.workers;\n const rootBranchId = \"root\";\n const branches: BranchState[] = [];\n const queue: QueuedBranch[] = [];\n let splitOccurred = options.rootIsArray === true;\n let nextStepIndex = options.retry?.initialExecutedSteps ?? 0;\n let nextBranchId = 1;\n let terminalResult: RunContinuationResult | undefined;\n let terminalBranchId: string | undefined;\n let terminalKind: TrackTerminalKind | undefined;\n const pendingJoins: PendingJoin[] = [];\n const activeByParallelGroup = new Map<string, number>();\n\n const allocateStepIndex = (branch: BranchState): number => {\n if (nextStepIndex >= options.maxSteps) {\n throw new Error(`workflow exceeded maxSteps guard (${options.maxSteps})`);\n }\n nextStepIndex += 1;\n branch.latestStepIndex = nextStepIndex;\n branch.updatedAt = new Date().toISOString();\n return nextStepIndex;\n };\n\n const allocateBranchId = (node: ContinuationResult): string => {\n const explicitBranchId = requestedBranchMetadata(node).requestedBranchId;\n if (explicitBranchId !== undefined) {\n return explicitBranchId;\n }\n\n const baseBranchId = branchIdBaseForNode(node);\n let suffix = 1;\n while (branches.some((branch) => branch.branchId === `${baseBranchId}-${suffix}`)) {\n suffix += 1;\n }\n nextBranchId = Math.max(nextBranchId, suffix + 1);\n return `${baseBranchId}-${suffix}`;\n };\n\n const enqueue = (\n node: ContinuationResult,\n parentBranchId: string | undefined,\n source: string,\n requireRunnableBranchCandidate: boolean,\n joinContinuation = false,\n scheduling?: {\n readonly parallelGroupId?: string;\n readonly parallelConcurrency?: number;\n readonly failurePolicy?: ParallelFailurePolicy;\n },\n ): BranchState => {\n const branch = createBranchRecord({\n node,\n parentBranchId,\n source,\n workflowId: workflowIdForBranchNode(node, options.workflowId),\n branchId:\n parentBranchId === undefined && branches.length === 0\n ? rootBranchId\n : allocateBranchId(node),\n joinContinuation,\n });\n branches.push(branch);\n if (terminalResult === undefined) {\n queue.push({\n node,\n branch,\n source,\n requireRunnableBranchCandidate,\n failurePolicy: scheduling?.failurePolicy ?? \"fail-fast\",\n ...(scheduling?.parallelGroupId === undefined\n ? {}\n : { parallelGroupId: scheduling.parallelGroupId }),\n ...(scheduling?.parallelConcurrency === undefined\n ? {}\n : { parallelConcurrency: scheduling.parallelConcurrency }),\n });\n } else {\n branch.status = \"cancelled\";\n branch.updatedAt = new Date().toISOString();\n }\n return branch;\n };\n\n const cancelQueuedAndPreventableBranches = async (preservedBranchId?: string): Promise<void> => {\n queue.length = 0;\n await cancelPreventableBranches(branches, options.runDir, preservedBranchId);\n };\n\n const terminalizeTrack = async (\n result: RunContinuationResult,\n terminal?: { readonly branchId: string; readonly kind: TrackTerminalKind },\n ): Promise<void> => {\n if (terminalResult === undefined) {\n terminalResult = result;\n terminalBranchId = terminal?.branchId;\n terminalKind = terminal?.kind;\n await cancelQueuedAndPreventableBranches(terminal?.branchId);\n }\n };\n\n if (options.retry !== undefined) {\n const retryPlan = await createPersistedTrackRetryPlan({\n nodes: options.nodes,\n runDir: options.runDir,\n workflowId: options.workflowId,\n initialSource: options.initialSource,\n track: options.retry.track,\n });\n if (retryPlan.status === \"failure\") {\n return retryPlan.failure;\n }\n branches.push(...retryPlan.branches);\n queue.push(...retryPlan.queue);\n splitOccurred = retryPlan.splitOccurred;\n nextBranchId = retryPlan.nextBranchId;\n } else if (options.rootIsArray === true) {\n if (!options.nodes.every(isRunnableBranchCandidate)) {\n return invalidArrayCandidateFailure(options.initialSource);\n }\n const duplicateBranchIdFailure = explicitDuplicateBranchIdFailure(\n options.nodes,\n options.initialSource,\n branches,\n );\n if (duplicateBranchIdFailure !== undefined) {\n return duplicateBranchIdFailure;\n }\n for (const node of options.nodes) {\n enqueue(node, rootBranchId, options.initialSource, true);\n }\n } else {\n const rootNode = options.nodes[0];\n if (rootNode === undefined) {\n return {\n status: \"failure\",\n failure: {\n code: \"invalid_continuation\",\n message: `${options.initialSource} returned an invalid continuation node.`,\n },\n };\n }\n enqueue(rootNode, undefined, options.initialSource, false);\n }\n\n await persistTrack(options, workers, rootBranchId, branches, \"running\", splitOccurred);\n\n let activeWorkers = 0;\n\n await new Promise<void>((resolve, reject) => {\n const schedule = (): void => {\n if (terminalResult !== undefined || queue.length === 0) {\n if (activeWorkers === 0) {\n resolve();\n }\n return;\n }\n\n while (terminalResult === undefined && activeWorkers < workers && queue.length > 0) {\n const queued = shiftRunnableQueuedBranch(queue, activeByParallelGroup);\n if (queued === undefined) {\n if (activeWorkers === 0) {\n resolve();\n }\n return;\n }\n activeWorkers += 1;\n incrementActiveParallelGroup(queued.parallelGroupId, activeByParallelGroup);\n\n void runBranch(queued)\n .then(async (branchResult) => {\n if (branchResult.status !== \"success\") {\n await terminalizeTrack(branchResult);\n }\n })\n .then(\n () => {\n activeWorkers -= 1;\n decrementActiveParallelGroup(queued.parallelGroupId, activeByParallelGroup);\n schedule();\n },\n (error: unknown) => {\n reject(error);\n },\n );\n }\n };\n\n schedule();\n });\n\n if (terminalResult !== undefined) {\n await cancelQueuedAndPreventableBranches(terminalBranchId);\n await Promise.all(branches.map((branch) => persistBranch(options.runDir, branch)));\n await persistTrack(\n options,\n workers,\n rootBranchId,\n branches,\n trackStatusFromTerminalResult(terminalResult),\n splitOccurred,\n terminalResult.status === \"failure\" || terminalResult.status === \"absoluteFailure\"\n ? terminalResult.failure\n : undefined,\n terminalBranchId,\n terminalKind,\n terminalResult.status === \"success\" || terminalResult.status === \"absoluteSuccess\"\n ? terminalResult.output\n : undefined,\n );\n return publicTerminalResult(terminalResult);\n }\n\n await Promise.all(branches.map((branch) => persistBranch(options.runDir, branch)));\n await persistTrack(options, workers, rootBranchId, branches, \"completed\", splitOccurred);\n\n const terminalBranches = branches.filter((branch) => isBranchTerminalStatus(branch.status));\n const joinContinuationBranch = [...terminalBranches]\n .reverse()\n .find((branch) => branch.joinContinuation === true && branch.status === \"done\");\n if (joinContinuationBranch !== undefined) {\n return {\n status: \"success\",\n output: joinContinuationBranch.output ?? {},\n ...(joinContinuationBranch.message === undefined\n ? {}\n : { message: joinContinuationBranch.message }),\n };\n }\n\n if (!splitOccurred && terminalBranches.length === 1 && terminalBranches[0]?.status === \"done\") {\n return {\n status: \"success\",\n output: terminalBranches[0].output ?? {},\n ...(terminalBranches[0].message === undefined\n ? {}\n : { message: terminalBranches[0].message }),\n };\n }\n\n return {\n status: \"success\",\n output: {\n status: \"completed\",\n branches: Object.fromEntries(\n terminalBranches.map((branch) => [branch.branchId, branchSettlementForSummary(branch)]),\n ),\n },\n };\n\n async function runWithBranchState<T>(branchId: string, fn: () => Promise<T>): Promise<T> {\n const parentContext = runContextStorage.getStore();\n if (!parentContext || (!splitOccurred && branchId === rootBranchId)) {\n return await fn();\n }\n\n const branchContext = {\n ...parentContext,\n state: createQueuedRunState({\n read: () => readBranchRunState(options.runDir, branchId),\n write: (nextState) => writeBranchRunState(options.runDir, branchId, nextState),\n }),\n };\n return await runContextStorage.run(branchContext, fn);\n }\n\n async function runBranch(queued: QueuedBranch): Promise<RunContinuationResult> {\n const { node, branch, source, requireRunnableBranchCandidate, failurePolicy } = queued;\n if (requireRunnableBranchCandidate && !isRunnableBranchCandidate(node)) {\n branch.status = \"failed\";\n branch.updatedAt = new Date().toISOString();\n await persistBranch(options.runDir, branch);\n return invalidArrayCandidateFailure(source);\n }\n\n branch.status = \"running\";\n branch.updatedAt = new Date().toISOString();\n await persistBranch(options.runDir, branch);\n\n const branchResult = await runWithBranchState(branch.branchId, async () =>\n runContinuation({\n node,\n runId: options.runId,\n workflowId: options.workflowId,\n emit: async (event) => {\n if (event.type === \"step.started\" && event.stepId !== undefined) {\n branch.latestStepId = event.stepId;\n }\n if (splitOccurred && event.type === \"step.started\" && event.stepId !== undefined) {\n const stepArtifacts = resolveStepArtifactPaths({\n runDir: options.runDir,\n stepId: event.stepId,\n stepIndex: branch.latestStepIndex,\n });\n await mkdir(stepArtifacts.stepDir, { recursive: true });\n }\n await options.emit(decorateBranchEvent(event, options.runId, branch));\n },\n maxSteps: options.maxSteps,\n initialSource:\n !splitOccurred && branch.branchId === rootBranchId\n ? source\n : `${source} branch ${branch.branchId}`,\n allocateStepIndex: () => allocateStepIndex(branch),\n returnContinuationArrays: true,\n workflowAgents: options.workflowAgents,\n workflowTimeout: options.workflowTimeout,\n runDir: options.runDir,\n projectCwd: options.projectCwd,\n cwd: options.cwd,\n trailstepConfig: options.trailstepConfig,\n workingAgentProcessRunner: options.workingAgentProcessRunner,\n providerWorkingRunner: options.providerWorkingRunner,\n processRunner: options.processRunner,\n }),\n );\n\n branch.updatedAt = new Date().toISOString();\n const branchResultWasSplit = branchResult.status === \"split\";\n if (terminalResult !== undefined) {\n if (!isBranchTerminalStatus(branch.status)) {\n branch.status = \"cancelled\";\n branch.updatedAt = new Date().toISOString();\n }\n await persistBranch(options.runDir, branch);\n return { status: \"cancelled\", cancellation: { requestedAt: branch.updatedAt } };\n }\n\n if (branchResult.status === \"absoluteSuccess\") {\n branch.status = \"done\";\n branch.output = branchResult.output;\n branch.message = branchResult.message;\n branch.terminalKind = \"absoluteDone\";\n await terminalizeTrack(branchResult, { branchId: branch.branchId, kind: \"absoluteDone\" });\n await persistBranch(options.runDir, branch);\n return branchResult;\n }\n\n if (branchResult.status === \"absoluteFailure\") {\n branch.status = \"failed\";\n branch.failure = branchResult.failure;\n branch.message = branchResult.message;\n branch.terminalKind = \"absoluteFail\";\n await terminalizeTrack(branchResult, { branchId: branch.branchId, kind: \"absoluteFail\" });\n await persistBranch(options.runDir, branch);\n return branchResult;\n }\n\n if (branchResult.status === \"failure\") {\n branch.status = \"failed\";\n branch.failure = branchResult.failure;\n branch.message = branchResult.message;\n if (failurePolicy === \"all-settled\") {\n await enqueueSatisfiedJoins(branch);\n await persistBranch(options.runDir, branch);\n await persistTrack(options, workers, rootBranchId, branches, \"running\", splitOccurred);\n return { status: \"success\", output: {} };\n }\n await terminalizeTrack(branchResult, { branchId: branch.branchId, kind: \"failure\" });\n await persistBranch(options.runDir, branch);\n return branchResult;\n }\n\n if (branchResult.status === \"waiting\") {\n branch.status = \"waiting\";\n branch.wait = branchResult.wait;\n await terminalizeTrack(branchResult, { branchId: branch.branchId, kind: \"waiting\" });\n await persistBranch(options.runDir, branch);\n return branchResult;\n }\n\n if (branchResult.status === \"cancelled\") {\n branch.status = \"cancelled\";\n await terminalizeTrack(branchResult, { branchId: branch.branchId, kind: \"cancelled\" });\n await persistBranch(options.runDir, branch);\n return branchResult;\n }\n\n if (branchResult.status === \"split\") {\n if (!branchResult.nodes.every(isRunnableBranchCandidate)) {\n branch.status = \"failed\";\n branch.failure = invalidArrayCandidateFailure(branchResult.source).failure;\n await persistBranch(options.runDir, branch);\n return invalidArrayCandidateFailure(branchResult.source);\n }\n const duplicateBranchIdFailure = explicitDuplicateBranchIdFailure(\n branchResult.nodes,\n branchResult.source,\n branches,\n );\n if (duplicateBranchIdFailure !== undefined) {\n branch.status = \"failed\";\n branch.failure = duplicateBranchIdFailure.failure;\n await persistBranch(options.runDir, branch);\n return duplicateBranchIdFailure;\n }\n splitOccurred = true;\n branch.status = \"split\";\n branch.splitSource = branchResult.source;\n if (branch.latestStepId !== undefined && branch.latestStepIndex > 0) {\n const stepArtifacts = resolveStepArtifactPaths({\n runDir: options.runDir,\n stepId: branch.latestStepId,\n stepIndex: branch.latestStepIndex,\n });\n await mkdir(stepArtifacts.stepDir, { recursive: true });\n }\n if (terminalResult !== undefined) {\n branch.status = \"cancelled\";\n branch.updatedAt = new Date().toISOString();\n await persistBranch(options.runDir, branch);\n return { status: \"cancelled\", cancellation: { requestedAt: branch.updatedAt } };\n }\n const parallelOptions = normalizeParallelOptions(branchResult.parallelOptions);\n const childBranches = branchResult.nodes.map((childNode) =>\n enqueue(childNode, branch.branchId, branchResult.source, true, false, {\n parallelGroupId: branch.branchId,\n ...(parallelOptions.concurrency === undefined\n ? {}\n : { parallelConcurrency: parallelOptions.concurrency }),\n failurePolicy: parallelOptions.failurePolicy,\n }),\n );\n if (branchResult.postContinuation !== undefined) {\n branch.pendingPostJoin = true;\n pendingJoins.push({\n parentBranchId: branch.branchId,\n childBranchIds: childBranches.map((childBranch) => childBranch.branchId),\n source: branchResult.source,\n failurePolicy: parallelOptions.failurePolicy,\n postContinuation: branchResult.postContinuation,\n ...(branchResult.afterPostContinuation === undefined\n ? {}\n : { afterPostContinuation: branchResult.afterPostContinuation }),\n completed: {},\n });\n }\n await Promise.all(\n branches.map((persistedBranch) => persistBranch(options.runDir, persistedBranch)),\n );\n } else if (branchResult.status === \"success\") {\n branch.status = \"done\";\n branch.output = branchResult.output;\n branch.message = branchResult.message;\n await enqueueSatisfiedJoins(branch);\n }\n await persistBranch(options.runDir, branch);\n await persistTrack(options, workers, rootBranchId, branches, \"running\", splitOccurred);\n return branchResultWasSplit ? { status: \"success\", output: {} } : branchResult;\n }\n\n async function enqueueSatisfiedJoins(branch: BranchState): Promise<void> {\n for (const join of pendingJoins) {\n if (!join.childBranchIds.includes(branch.branchId)) {\n continue;\n }\n const settlement = branchSettlementForJoin(branch, join.failurePolicy);\n if (settlement === undefined) {\n continue;\n }\n join.completed = { ...join.completed, [branch.branchId]: settlement };\n if (Object.keys(join.completed).length !== join.childBranchIds.length) {\n continue;\n }\n\n let nextNode: ContinuationResult;\n try {\n nextNode = await join.postContinuation({ status: \"completed\", branches: join.completed });\n } catch (error) {\n await terminalizeTrack({\n status: \"failure\",\n failure: {\n code: \"step_execution_failed\",\n message: `parallel post failed for ${join.source}: ${String(error)}`,\n },\n });\n continue;\n }\n const postBranch = enqueue(\n nextNode,\n join.parentBranchId,\n `post for ${join.source}`,\n false,\n true,\n );\n if (join.afterPostContinuation !== undefined) {\n const afterPostContinuation = join.afterPostContinuation;\n pendingJoins.push({\n parentBranchId: join.parentBranchId,\n childBranchIds: [postBranch.branchId],\n source: `post for ${join.source}`,\n failurePolicy: \"fail-fast\",\n postContinuation: async (aggregateOutput) => {\n const branches = aggregateOutput.branches as Record<string, PlainObject> | undefined;\n const [output] = Object.values(branches ?? {});\n return afterPostContinuation(output ?? {});\n },\n completed: {},\n });\n }\n }\n }\n}\n\nfunction createBranchRecord(input: {\n readonly node: ContinuationResult;\n readonly parentBranchId: string | undefined;\n readonly source: string;\n readonly workflowId: string;\n readonly branchId: string;\n readonly joinContinuation: boolean;\n}): BranchState {\n const now = new Date().toISOString();\n return {\n branchId: input.branchId,\n ...(input.parentBranchId === undefined ? {} : { parentBranchId: input.parentBranchId }),\n ...(input.joinContinuation ? { joinContinuation: true } : {}),\n ...requestedBranchMetadata(input.node),\n workflowId: input.workflowId,\n createdAt: now,\n updatedAt: now,\n status: \"queued\",\n source: input.source,\n latestStepIndex: 0,\n };\n}\n\nfunction workflowIdForBranchNode(node: ContinuationResult, fallbackWorkflowId: string): string {\n if (isWorkflowInvocationNode(node)) {\n return node.workflow.id;\n }\n\n return fallbackWorkflowId;\n}\n\nfunction requestedBranchMetadata(node: ContinuationResult): {\n readonly requestedBranchId?: string;\n} {\n if (isWorkflowInvocationNode(node) && node.options?.branchId !== undefined) {\n return { requestedBranchId: node.options.branchId };\n }\n if (isStepNode(node) && node.options?.branchId !== undefined) {\n return { requestedBranchId: node.options.branchId };\n }\n\n return {};\n}\n\nfunction branchIdBaseForNode(node: ContinuationResult): string {\n const rawId = isWorkflowInvocationNode(node)\n ? node.workflow.id\n : isStepNode(node)\n ? node.config.id\n : \"branch\";\n return rawId.replaceAll(/[^A-Za-z0-9._-]/g, \"-\") || \"branch\";\n}\n\nfunction explicitDuplicateBranchIdFailure(\n nodes: readonly ContinuationResult[],\n source: string,\n existingBranches: readonly BranchState[],\n): (RunContinuationResult & { readonly status: \"failure\" }) | undefined {\n const seen = new Set<string>(existingBranches.map((branch) => branch.branchId));\n for (const node of nodes) {\n const branchId = requestedBranchMetadata(node).requestedBranchId;\n if (branchId === undefined) {\n continue;\n }\n if (seen.has(branchId)) {\n return {\n status: \"failure\",\n failure: {\n code: \"duplicate_branch_id\",\n message: `${source} scheduled multiple parallel branches with branchId ${JSON.stringify(\n branchId,\n )}; explicit branchId values must be unique within a parallel track.`,\n },\n };\n }\n seen.add(branchId);\n }\n return undefined;\n}\n\nfunction isRunnableBranchCandidate(node: ContinuationResult): boolean {\n return isStepNode(node) || isWorkflowInvocationNode(node);\n}\n\nfunction invalidArrayCandidateFailure(\n source: string,\n): RunContinuationResult & { readonly status: \"failure\" } {\n return {\n status: \"failure\",\n failure: {\n code: \"invalid_continuation\",\n message: `${source} returned a continuation array containing non-runnable branch candidates; array candidates must be runnable step or workflow invocation nodes.`,\n },\n };\n}\n\nfunction isBranchTerminalStatus(status: BranchStatus): boolean {\n return status === \"done\" || status === \"failed\" || status === \"cancelled\";\n}\n\nfunction normalizeParallelOptions(options: ParallelOptions | undefined): {\n readonly concurrency?: number;\n readonly failurePolicy: ParallelFailurePolicy;\n} {\n const concurrency = options?.concurrency;\n return {\n ...(concurrency === undefined ? {} : { concurrency }),\n failurePolicy: options?.failurePolicy ?? \"fail-fast\",\n };\n}\n\nfunction shiftRunnableQueuedBranch(\n queue: QueuedBranch[],\n activeByParallelGroup: ReadonlyMap<string, number>,\n): QueuedBranch | undefined {\n const index = queue.findIndex((candidate) => {\n if (candidate.parallelGroupId === undefined || candidate.parallelConcurrency === undefined) {\n return true;\n }\n return (\n (activeByParallelGroup.get(candidate.parallelGroupId) ?? 0) < candidate.parallelConcurrency\n );\n });\n if (index < 0) {\n return undefined;\n }\n const [queued] = queue.splice(index, 1);\n return queued;\n}\n\nfunction incrementActiveParallelGroup(\n parallelGroupId: string | undefined,\n activeByParallelGroup: Map<string, number>,\n): void {\n if (parallelGroupId === undefined) {\n return;\n }\n activeByParallelGroup.set(parallelGroupId, (activeByParallelGroup.get(parallelGroupId) ?? 0) + 1);\n}\n\nfunction decrementActiveParallelGroup(\n parallelGroupId: string | undefined,\n activeByParallelGroup: Map<string, number>,\n): void {\n if (parallelGroupId === undefined) {\n return;\n }\n const next = (activeByParallelGroup.get(parallelGroupId) ?? 1) - 1;\n if (next <= 0) {\n activeByParallelGroup.delete(parallelGroupId);\n } else {\n activeByParallelGroup.set(parallelGroupId, next);\n }\n}\n\nfunction branchSettlementForJoin(\n branch: BranchState,\n failurePolicy: ParallelFailurePolicy,\n): PlainObject | undefined {\n if (failurePolicy === \"all-settled\") {\n return branchSettlementForSummary(branch);\n }\n return branch.status === \"done\" && branch.output !== undefined ? branch.output : undefined;\n}\n\nfunction branchSettlementForSummary(branch: BranchState): PlainObject {\n if (branch.status === \"failed\") {\n return {\n status: \"failed\",\n ...(branch.failure === undefined ? {} : { failure: branch.failure }),\n ...(branch.message === undefined ? {} : { message: branch.message }),\n };\n }\n\n return {\n status: branch.status,\n output: branch.output ?? {},\n ...(branch.message === undefined ? {} : { message: branch.message }),\n };\n}\n\nfunction trackStatusFromTerminalResult(result: RunContinuationResult): string {\n if (result.status === \"failure\" || result.status === \"absoluteFailure\") {\n return \"failed\";\n }\n if (result.status === \"absoluteSuccess\") {\n return \"completed\";\n }\n return result.status;\n}\n\nfunction publicTerminalResult(result: RunContinuationResult): RunContinuationResult {\n if (result.status === \"absoluteSuccess\") {\n return {\n status: \"success\",\n output: result.output,\n ...(result.message === undefined ? {} : { message: result.message }),\n };\n }\n\n if (result.status === \"absoluteFailure\") {\n return {\n status: \"failure\",\n failure: result.failure,\n ...(result.message === undefined ? {} : { message: result.message }),\n };\n }\n\n return result;\n}\n\nasync function cancelPreventableBranches(\n branches: readonly BranchState[],\n runDir: string,\n preservedBranchId?: string,\n): Promise<void> {\n const now = new Date().toISOString();\n await Promise.all(\n branches.map((branch) => {\n if (branch.branchId !== preservedBranchId && !isBranchTerminalStatus(branch.status)) {\n branch.status = \"cancelled\";\n branch.updatedAt = now;\n }\n return persistBranch(runDir, branch);\n }),\n );\n}\n\nfunction resolveSchedulerWorkerCount(\n workers: number | undefined,\n):\n | { readonly ok: true; readonly workers: number }\n | { readonly ok: false; readonly failure: RunContinuationResult } {\n if (workers === undefined) {\n return {\n ok: true,\n workers: Math.max(1, Math.floor(availableParallelism() / 2)),\n };\n }\n\n if (!Number.isFinite(workers) || !Number.isInteger(workers) || workers < 1) {\n return {\n ok: false,\n failure: {\n status: \"failure\",\n failure: {\n code: \"invalid_scheduler_workers\",\n message: \"scheduler.workers must be an integer greater than or equal to 1.\",\n },\n },\n };\n }\n\n return { ok: true, workers };\n}\n\nfunction decorateBranchEvent(event: Event, trackId: string, branch: BranchState): Event {\n if (event.type !== \"step.started\" && event.type !== \"step.completed\") {\n return event;\n }\n\n const stepArtifactPaths =\n event.stepId === undefined || branch.latestStepIndex < 1\n ? undefined\n : resolveStepArtifactPaths({\n runDir: \"\",\n stepId: event.stepId,\n stepIndex: branch.latestStepIndex,\n });\n\n return {\n ...event,\n payload: {\n ...event.payload,\n trackId,\n branchId: branch.branchId,\n ...(branch.requestedBranchId === undefined\n ? {}\n : { requestedBranchId: branch.requestedBranchId }),\n ...(stepArtifactPaths === undefined\n ? {}\n : {\n stepIndex: branch.latestStepIndex,\n stepArtifactId: stepArtifactPaths.artifactStepId,\n stepArtifactPath: stepArtifactPaths.runRelativeStepDir,\n }),\n },\n };\n}\n\nasync function createPersistedTrackRetryPlan(input: {\n readonly nodes: readonly ContinuationResult[];\n readonly runDir: string;\n readonly workflowId: string;\n readonly initialSource: string;\n readonly track?: RunWorkflowTrackRetryOptions;\n}): Promise<\n | {\n readonly status: \"success\";\n readonly branches: readonly BranchState[];\n readonly queue: readonly QueuedBranch[];\n readonly splitOccurred: boolean;\n readonly nextBranchId: number;\n }\n | { readonly status: \"failure\"; readonly failure: RunContinuationResult }\n> {\n let track: TrackStateJson;\n try {\n track = JSON.parse(await readFile(join(input.runDir, \"track.json\"), \"utf8\")) as TrackStateJson;\n } catch (error) {\n return {\n status: \"failure\",\n failure: {\n status: \"failure\",\n failure: {\n code: \"retry_track_metadata_unreadable\",\n message: `Retry target track metadata is missing or unreadable: ${error instanceof Error ? error.message : String(error)}`,\n },\n },\n };\n }\n\n const retryRootParallelNode =\n input.nodes.length === 1 && isParallelNode(input.nodes[0]) ? input.nodes[0] : undefined;\n const retryCandidateNodes = retryRootParallelNode?.nodes ?? input.nodes;\n if (retryRootParallelNode?.postContinuation !== undefined) {\n return { status: \"failure\", failure: unsupportedPostJoinRetryFailure() };\n }\n\n if (!retryCandidateNodes.every(isRunnableBranchCandidate)) {\n return { status: \"failure\", failure: invalidArrayCandidateFailure(input.initialSource) };\n }\n\n const branches = await Promise.all(\n track.branches.map(async (branchId) =>\n branchFromJson(\n JSON.parse(\n await readFile(join(input.runDir, \"branches\", `${branchId}.json`), \"utf8\"),\n ) as BranchStateJson,\n ),\n ),\n );\n if (\n branches.some((branch) => branch.joinContinuation === true || branch.pendingPostJoin === true)\n ) {\n return { status: \"failure\", failure: unsupportedPostJoinRetryFailure() };\n }\n\n const nodesByRequestedBranchId = new Map<string, ContinuationResult>();\n for (const node of retryCandidateNodes) {\n const requestedBranchId = requestedBranchMetadata(node).requestedBranchId;\n if (requestedBranchId !== undefined) {\n nodesByRequestedBranchId.set(requestedBranchId, node);\n }\n }\n\n const selection = selectPersistedBranchesForRetry(branches, input.track);\n if (selection.status === \"failure\") {\n return selection;\n }\n\n const queue: QueuedBranch[] = [];\n for (const [index, branch] of branches.entries()) {\n if (!selection.branchIds.has(branch.branchId)) {\n continue;\n }\n if (retryRootParallelNode !== undefined && branch.branchId === track.rootBranchId) {\n continue;\n }\n\n if (branch.status === \"split\") {\n return {\n status: \"failure\",\n failure: {\n status: \"failure\",\n failure: {\n code: \"retry_track_split_branch_unsupported\",\n message: `Retrying split parent branch ${branch.branchId} is not supported; retry a failed child branch or restart the workflow instead.`,\n },\n },\n };\n }\n\n branch.status = \"queued\";\n branch.failure = undefined;\n branch.wait = undefined;\n branch.terminalKind = undefined;\n branch.message = undefined;\n branch.updatedAt = new Date().toISOString();\n const rootParallelBranchIndex =\n retryRootParallelNode === undefined\n ? undefined\n : branches\n .filter((candidate) => candidate.parentBranchId === track.rootBranchId)\n .findIndex((candidate) => candidate.branchId === branch.branchId);\n const node =\n (branch.requestedBranchId === undefined\n ? undefined\n : nodesByRequestedBranchId.get(branch.requestedBranchId)) ??\n (rootParallelBranchIndex === undefined || rootParallelBranchIndex < 0\n ? retryCandidateNodes[index]\n : retryCandidateNodes[rootParallelBranchIndex]);\n if (node === undefined) {\n return {\n status: \"failure\",\n failure: {\n status: \"failure\",\n failure: {\n code: \"retry_track_branch_not_found\",\n message: `Retry target branch ${branch.branchId} no longer has a matching workflow branch candidate.`,\n },\n },\n };\n }\n queue.push({\n node,\n branch,\n source: branch.splitSource ?? branch.source ?? input.initialSource,\n requireRunnableBranchCandidate: true,\n failurePolicy: \"fail-fast\",\n });\n }\n\n const maxNumericBranchId = branches.reduce((max, branch) => {\n const match = /^branch-(\\d+)$/.exec(branch.branchId);\n return match ? Math.max(max, Number(match[1])) : max;\n }, 0);\n\n return {\n status: \"success\",\n branches,\n queue,\n splitOccurred: track.splitOccurred,\n nextBranchId: maxNumericBranchId + 1,\n };\n}\n\nfunction unsupportedPostJoinRetryFailure(): RunContinuationResult {\n return {\n status: \"failure\",\n failure: {\n code: \"retry_parallel_post_join_unsupported\",\n message:\n \"Retrying parallel tracks with pending or completed parallel .post joins is not yet supported; restart the workflow instead.\",\n },\n };\n}\n\nfunction selectPersistedBranchesForRetry(\n branches: readonly BranchState[],\n track: RunWorkflowTrackRetryOptions | undefined,\n):\n | { readonly status: \"success\"; readonly branchIds: ReadonlySet<string> }\n | { readonly status: \"failure\"; readonly failure: RunContinuationResult } {\n if (track === undefined) {\n return {\n status: \"success\",\n branchIds: new Set(\n branches\n .filter((branch) => [\"failed\", \"waiting\", \"cancelled\"].includes(branch.status))\n .map((branch) => branch.branchId),\n ),\n };\n }\n\n if (track.mode === \"failed-only\") {\n if ((track as { readonly branchId?: unknown }).branchId !== undefined) {\n return {\n status: \"failure\",\n failure: {\n status: \"failure\",\n failure: {\n code: \"retry_track_filter_unsupported\",\n message: \"Track failed-only retry cannot also specify a branchId.\",\n },\n },\n };\n }\n\n return {\n status: \"success\",\n branchIds: new Set(\n branches.filter((branch) => branch.status === \"failed\").map((branch) => branch.branchId),\n ),\n };\n }\n\n if (track.mode !== \"branch\") {\n return {\n status: \"failure\",\n failure: {\n status: \"failure\",\n failure: {\n code: \"retry_track_filter_unsupported\",\n message: `Unsupported track retry mode: ${String((track as { readonly mode?: unknown }).mode)}.`,\n },\n },\n };\n }\n\n if (typeof track.branchId !== \"string\" || track.branchId.length === 0) {\n return {\n status: \"failure\",\n failure: {\n status: \"failure\",\n failure: {\n code: \"retry_track_branch_required\",\n message: \"Track branch retry requires a persisted branchId.\",\n },\n },\n };\n }\n\n const branch = branches.find((candidate) => candidate.branchId === track.branchId);\n if (branch === undefined) {\n return {\n status: \"failure\",\n failure: {\n status: \"failure\",\n failure: {\n code: \"retry_track_branch_not_found\",\n message: `Retry target branch ${track.branchId} was not found in persisted track metadata.`,\n },\n },\n };\n }\n\n return { status: \"success\", branchIds: new Set([branch.branchId]) };\n}\n\nfunction branchFromJson(json: BranchStateJson): BranchState {\n return {\n branchId: json.branchId,\n ...(json.parentBranchId === undefined ? {} : { parentBranchId: json.parentBranchId }),\n ...(json.requestedBranchId === undefined ? {} : { requestedBranchId: json.requestedBranchId }),\n ...(json.joinContinuation === undefined ? {} : { joinContinuation: json.joinContinuation }),\n ...(json.pendingPostJoin === undefined ? {} : { pendingPostJoin: json.pendingPostJoin }),\n workflowId: json.workflowId,\n createdAt: json.createdAt,\n updatedAt: json.updatedAt,\n status: json.status,\n source: json.source,\n ...(json.splitSource === undefined ? {} : { splitSource: json.splitSource }),\n output: json.output,\n ...(json.failure === undefined ? {} : { failure: json.failure }),\n ...(json.wait === undefined ? {} : { wait: json.wait }),\n ...(json.terminalKind === undefined ? {} : { terminalKind: json.terminalKind }),\n ...(json.message === undefined ? {} : { message: json.message }),\n latestStepIndex: json.latestStepIndex,\n ...(json.latestStepId === undefined ? {} : { latestStepId: json.latestStepId }),\n };\n}\n\nasync function persistTrack(\n options: RunRootContinuationArraySchedulerOptions,\n workers: number,\n rootBranchId: string,\n branches: readonly BranchState[],\n status: string,\n splitOccurred: boolean,\n failure?: Failure,\n terminalBranchId?: string,\n terminalKind?: TrackTerminalKind,\n terminalOutput?: PlainObject,\n): Promise<void> {\n const trackState: TrackStateJson = {\n runId: options.runId,\n status,\n workers,\n failurePolicy: \"fail-fast\",\n rootBranchId,\n splitOccurred,\n branches: branches.map((branch) => branch.branchId),\n ...(terminalBranchId === undefined ? {} : { terminalBranchId }),\n ...(terminalKind === undefined ? {} : { terminalKind }),\n ...(terminalOutput === undefined ? {} : { terminalOutput }),\n ...(failure === undefined ? {} : { failure }),\n };\n await writeJson(join(options.runDir, \"track.json\"), trackState);\n}\n\nasync function persistBranch(runDir: string, branch: BranchState): Promise<void> {\n const branchState: BranchStateJson = {\n branchId: branch.branchId,\n ...(branch.parentBranchId === undefined ? {} : { parentBranchId: branch.parentBranchId }),\n ...(branch.requestedBranchId === undefined\n ? {}\n : { requestedBranchId: branch.requestedBranchId }),\n ...(branch.joinContinuation === undefined ? {} : { joinContinuation: branch.joinContinuation }),\n ...(branch.pendingPostJoin === undefined ? {} : { pendingPostJoin: branch.pendingPostJoin }),\n status: branch.status,\n workflowId: branch.workflowId,\n source: branch.source,\n ...(branch.splitSource === undefined ? {} : { splitSource: branch.splitSource }),\n output: branch.output ?? {},\n ...(branch.failure === undefined ? {} : { failure: branch.failure }),\n ...(branch.wait === undefined ? {} : { wait: branch.wait }),\n ...(branch.terminalKind === undefined ? {} : { terminalKind: branch.terminalKind }),\n ...(branch.message === undefined ? {} : { message: branch.message }),\n createdAt: branch.createdAt,\n updatedAt: branch.updatedAt,\n latestStepIndex: branch.latestStepIndex,\n ...(branch.latestStepId === undefined ? {} : { latestStepId: branch.latestStepId }),\n };\n await writeJson(join(runDir, \"branches\", `${branch.branchId}.json`), branchState);\n}\n\nasync function writeJson(path: string, value: unknown): Promise<void> {\n await mkdir(join(path, \"..\"), { recursive: true });\n await writeFile(path, `${JSON.stringify(value, null, 2)}\\n`, \"utf8\");\n}\n","import {\n isParsedTrailStepConfig,\n parseTrailStepConfig,\n} from \"../../agent-targeting/parse-trailstep-config/parse-trailstep-config.js\";\nimport type { TrailStepConfig } from \"../../agent-targeting/targeting.types.js\";\nimport type { RunWorkflowOptions } from \"./run-workflow.types.js\";\n\nexport function parseTrailStepConfigInput(\n value: RunWorkflowOptions[\"trailstepConfig\"],\n): TrailStepConfig {\n if (isParsedTrailStepConfig(value) || isFlattenedTrailStepConfig(value)) {\n return value;\n }\n\n return parseTrailStepConfig(value);\n}\n\nfunction isFlattenedTrailStepConfig(\n value: RunWorkflowOptions[\"trailstepConfig\"],\n): value is TrailStepConfig {\n if (!isPlainRecord(value) || value.version !== 1) {\n return false;\n }\n\n if (!isPlainRecord(value.customProviders) || !isFlattenedAgentMappings(value.agents)) {\n return false;\n }\n\n if (value.settings !== undefined && !isFlattenedSettings(value.settings)) {\n return false;\n }\n\n if (value.workflows === undefined) {\n return true;\n }\n\n if (!isPlainRecord(value.workflows)) {\n return false;\n }\n\n return Object.values(value.workflows).every(\n (workflow) =>\n isPlainRecord(workflow) &&\n (workflow.agents === undefined || isFlattenedAgentMappings(workflow.agents)) &&\n (workflow.settings === undefined || isFlattenedSettings(workflow.settings)),\n );\n}\n\nfunction isFlattenedSettings(value: unknown): value is NonNullable<TrailStepConfig[\"settings\"]> {\n return (\n isPlainRecord(value) &&\n (value.retry === undefined || isPlainRecord(value.retry)) &&\n (value.timeout === undefined || typeof value.timeout === \"number\")\n );\n}\n\nfunction isFlattenedAgentMappings(value: unknown): value is TrailStepConfig[\"agents\"] {\n return (\n isPlainRecord(value) &&\n Object.values(value).every(\n (targets) => Array.isArray(targets) && targets.every(isFlattenedAgentTarget),\n )\n );\n}\n\nfunction isFlattenedAgentTarget(\n value: unknown,\n): value is TrailStepConfig[\"agents\"][string][number] {\n if (!isPlainRecord(value) || typeof value.provider !== \"string\") {\n return false;\n }\n\n if (value.model !== undefined) {\n return typeof value.model === \"string\" && value.model.trim().length > 0;\n }\n\n return true;\n}\n\nfunction isPlainRecord(value: unknown): value is Readonly<Record<string, unknown>> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n"],"mappings":";AAAA,SAAS,aAAa;AACtB,SAAS,OAAO,iBAAiB;AACjC,SAAS,WAAAA,gBAAe;;;ACFxB,SAAS,iBAAiB;AAC1B,SAAS,QAAQ,gBAAgB;AACjC,SAAS,SAAS,SAAS,YAAY;AAEvC,IAAM,g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S,sBAAsB;AACxC,aAAO;AAAA,IACT;AAAA,EACF;AAEA,SAAO;AACT;AAEA,SAAS,8BAA8B,QAA0D;AAC/F,WAAS,QAAQ,OAAO,SAAS,GAAG,SAAS,GAAG,SAAS,GAAG;AAC1D,UAAM,QAAQ,OAAO,KAAK;AAC1B,QAAI,OAAO,SAAS,sBAAsB;AACxC;AAAA,IACF;AAEA,WAAO,wBAAwB,MAAM,OAAO;AAAA,EAC9C;AAEA,SAAO;AACT;AAEA,SAAS,wBAAwB,SAAsD;AACrF,SAAO;AAAA,IACL,GAAI,OAAO,QAAQ,gBAAgB,WAAW,EAAE,aAAa,QAAQ,YAAY,IAAI,CAAC;AAAA,IACtF,GAAI,OAAO,QAAQ,WAAW,WAAW,EAAE,QAAQ,QAAQ,OAAO,IAAI,CAAC;AAAA,IACvE,GAAI,OAAO,QAAQ,WAAW,WAAW,EAAE,QAAQ,QAAQ,OAAO,IAAI,CAAC;AAAA,EACzE;AACF;","names":["dirname","args","promptInjectionMode","dirname","result","resolve","workflow","THINKING_LEVELS","optionalNonEmptyString","THINKING_LEVELS","mkdir","readdir","readFile","writeFile","basename","dirname","join","mkdir","readFile","writeFile","dirname","join","join","mkdir","isNodeError","readFile","mkdir","join","writeFile","readFile","isNodeError","state","dirname","readFile","join","readFile","join","isPlainObject","isNodeError","isNodeError","join","readFile","join","dirname","mkdir","writeFile","readFile","readdir","isNodeError","value","basename","workflow","workflow","targets","join","isPlainObject","formatDiagnostics","isPlainObject","mkdir","writeFile","readFile","join","spawn","mkdir","writeFile","dirname","readFile","formatDiagnostics","readFile","definedProcessEnv","args","mkdir","dirname","writeFile","spawnInteractiveProcess","resolve","spawn","terminateChildProcessTree","mkdir","writeFile","join","join","rm","readFile","readFile","spawn","resolve","terminateChildProcessTree","writeFile","isPlainObject","isPlainObject","optionalNonEmptyString","isRecord","writeFile","rm","mkdir","writeFile","readFile","join","relative","isPlainObject","isPlainObject","mkdir","writeFile","workflow","isPlainObject","mkdir","readFile","writeFile","join","isNodeError","isPlainObject","readFile","basename","join","mkdir","readFile","writeFile","join","stat","firstConfiguredPolicy","errorMessage","nextNode","isPlainObject","mkdir","writeFile","artifactPaths","join","readFile","isNodeError","readPlainPayload","promptPhase","withWaitsDoContext","isPlainObject","readPlainPayload","promptPhase","isPlainObject","resumeFailure","readPlainPayload","isPlainObject","readFile","join","resumeFailure","readPlainPayload","readFile","join","isPlainObject","state","globalState","options","basename","basename","mkdir","readFile","writeFile","join","resolve","mkdir","join","branches","readFile","branch","writeFile","workflow","basename","readFile","join"]}
|