@trailstep/core 0.1.0 → 0.1.1

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/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/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 args = parseOptionalStringArray(`${targetPath}.args`, target.args, diagnostics);\n\n return [\n {\n provider: target.provider,\n ...(typeof target.model === \"string\" ? { model: target.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","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 { TrailStepCustomProviderConfig } from \"../targeting.types.js\";\nimport { isRecord, parseOptionalStringArray, parseOptionalStringRecord } from \"./parse-utils.js\";\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 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 ...(typeof providerConfig.cwd === \"string\" ? { cwd: providerConfig.cwd } : {}),\n ...(env === undefined ? {} : { env }),\n };\n }\n\n return customProviders;\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 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\";\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: \"result\" });\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: \"result\" });\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: \"result\" });\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 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 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 SUPPORTED_CODEX_THINKING = new Set([\"low\", \"medium\", \"high\", \"xhigh\"]);\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 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 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\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 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 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\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 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 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 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\";\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 args = await substitutePromptPlaceholders({\n argv: options.target.args ?? agentConfig.interactiveArgs,\n prompt,\n promptFile: files.promptFile,\n model: options.target.model,\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\nasync function substitutePromptPlaceholders(options: {\n readonly argv: readonly string[];\n readonly prompt: string;\n readonly promptFile: string;\n readonly model?: string;\n}): Promise<string[]> {\n let needsPromptFile = false;\n const substituted = options.argv.map((arg) => {\n if (arg === \"{{prompt}}\") {\n return options.prompt;\n }\n\n if (arg === \"{{promptFile}}\") {\n needsPromptFile = true;\n return options.promptFile;\n }\n\n if (arg === \"{{model}}\") {\n return options.model ?? \"\";\n }\n\n if (arg.includes(\"{{prompt}}\") || arg.includes(\"{{promptFile}}\") || arg.includes(\"{{model}}\")) {\n throw new TrailStepFailureError({\n code: \"interactive_command_invalid\",\n message: \"Interactive prompt placeholders must be whole argv values.\",\n });\n }\n\n return arg;\n });\n\n if (needsPromptFile) {\n await mkdir(dirname(options.promptFile), { recursive: true });\n await writeFile(options.promptFile, options.prompt, \"utf8\");\n }\n\n return substituted;\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 { 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 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 { TrailStepFailureError } from \"../../../../contracts/failures/failure.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}): 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 options.argv.map((arg) => {\n switch (arg) {\n case \"{{promptFile}}\":\n return options.promptFile;\n case \"{{outputFile}}\":\n return options.outputFile;\n case \"{{model}}\":\n return options.model ?? \"\";\n default:\n if (\n arg.includes(\"{{promptFile}}\") ||\n arg.includes(\"{{outputFile}}\") ||\n arg.includes(\"{{model}}\")\n ) {\n throw new TrailStepFailureError({\n code: \"agent_provider_invalid\",\n message: \"Working agent command placeholders must be whole argv values.\",\n });\n }\n return arg;\n }\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 { 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 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 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 });\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 return isPlainRecord(value) && typeof value.provider === \"string\";\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,IAAI,IAAI,oBAAoB;AAAA,MACzC;AAAA,MACA,QAAQ,QAAQ;AAAA,MAChB;AAAA,MACA,OAAO,CAAC;AAAA,MACR,aAAa;AAAA,IACf,CAAC;AAAA,EACH;AAEA,QAAM,oBACJ,QAAQ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AAAA,MACR;AAAA,MACA,eAAe,WAAW;AAAA,IAC5B;AAAA,EACF;AAEA,MAAI,eAAe;AACjB,WAAO;AAAA,MACL,GAAG;AAAA,MACH,QAAQ;AAAA,MACR,YAAY,cAAc;AAAA,MAC1B,eAAe,cAAc,MAAM;AAAA,MACnC;AAAA,IACF;AAAA,EACF;AAEA,SAAO;AAAA,IACL,GAAG;AAAA,IACH,QAAQ,kBAAkB;AAAA,IAC1B;AAAA,IACA,eAAe,WAAW;AAAA,EAC5B;AACF;AAEA,SAAS,qBAAqB,QAA8D;AAC1F,WAAS,QAAQ,OAAO,SAAS,GAAG,SAAS,GAAG,SAAS,GAAG;AAC1D,UAAM,QAAQ,OAAO,KAAK;AAC1B,QAAI,OAAO,SAAS,sBAAsB;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":["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","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/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,IAAI,IAA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C,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"]}