acpx 0.19.0 → 0.19.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/{agent-registry-Ct2yWPW7.js → agent-registry-DWlx5BQ4.js} +3 -2
- package/dist/agent-registry-DWlx5BQ4.js.map +1 -0
- package/dist/agent-registry.js +1 -1
- package/dist/{cli-Bmki9cj5.js → cli-BerngYEz.js} +5 -5
- package/dist/{cli-Bmki9cj5.js.map → cli-BerngYEz.js.map} +1 -1
- package/dist/cli.js +31 -15
- package/dist/cli.js.map +1 -1
- package/dist/{client-DzaUKazo.d.ts → client-BchvQRpz.d.ts} +8 -1
- package/dist/client-BchvQRpz.d.ts.map +1 -0
- package/dist/{flows--Ewxn_fQ.js → flows-DimX0it5.js} +33 -20
- package/dist/flows-DimX0it5.js.map +1 -0
- package/dist/flows.d.ts +2 -1
- package/dist/flows.d.ts.map +1 -1
- package/dist/flows.js +1 -1
- package/dist/{invocation-options-DRzxHZmr.js → invocation-options-vobVApfO.js} +5 -5
- package/dist/{invocation-options-DRzxHZmr.js.map → invocation-options-vobVApfO.js.map} +1 -1
- package/dist/{ipc-fMgj5vrO.js → ipc-DAApJ5mi.js} +536 -57
- package/dist/ipc-DAApJ5mi.js.map +1 -0
- package/dist/{output-D6kDs8BN.js → output-Cnuji8Bo.js} +20 -12
- package/dist/output-Cnuji8Bo.js.map +1 -0
- package/dist/{queue-owner-runtime-CLwjMYNL.js → queue-owner-runtime-C4OOosbo.js} +253 -240
- package/dist/queue-owner-runtime-C4OOosbo.js.map +1 -0
- package/dist/runtime.d.ts +1 -1
- package/dist/runtime.d.ts.map +1 -1
- package/dist/runtime.js +5 -5
- package/dist/runtime.js.map +1 -1
- package/dist/{session-watch-BfdIo-n4.js → session-watch-Bj9LoYUq.js} +4 -4
- package/dist/{session-watch-BfdIo-n4.js.map → session-watch-Bj9LoYUq.js.map} +1 -1
- package/dist/{watch-DH-zXQH2.js → watch-Cz6jbrRs.js} +2 -2
- package/dist/{watch-DH-zXQH2.js.map → watch-Cz6jbrRs.js.map} +1 -1
- package/package.json +1 -1
- package/skills/acpx/SKILL.md +2 -0
- package/dist/agent-registry-Ct2yWPW7.js.map +0 -1
- package/dist/client-DzaUKazo.d.ts.map +0 -1
- package/dist/flows--Ewxn_fQ.js.map +0 -1
- package/dist/ipc-fMgj5vrO.js.map +0 -1
- package/dist/output-D6kDs8BN.js.map +0 -1
- package/dist/queue-owner-runtime-CLwjMYNL.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"flows-DimX0it5.js","names":["wait","isoNow","isoNow","exhaustive","recordConversationSessionUpdate","recordConversationClientOperation"],"sources":["../src/flows/attempt.ts","../src/flows/authoring.ts","../src/flows/schema.ts","../src/flows/definition.ts","../src/flows/executors/shell-output.ts","../src/flows/executors/shell-process.ts","../src/flows/executors/shell.ts","../src/flows/graph.ts","../src/flows/runtime-support.ts","../src/flows/store.ts","../src/flows/runtime.ts","../src/flows/json.ts","../src/flows/decision.ts"],"sourcesContent":["import { performance } from \"node:perf_hooks\";\nimport { TimeoutError } from \"../async-control.js\";\n\ntype OwnedOutcome = { ok: true } | { ok: false; error: unknown };\n\n/** One node attempt owns admission and completion of its managed operations. */\nexport class FlowAttempt {\n readonly signal: AbortSignal;\n readonly nodeId: string;\n readonly attemptId: string;\n readonly startedAt: string;\n terminationSignal: NodeJS.Signals = \"SIGTERM\";\n\n private readonly controller = new AbortController();\n private readonly pending = new Set<Promise<OwnedOutcome>>();\n private readonly cancellations = new Set<(signal: NodeJS.Signals) => Promise<void>>();\n private readonly cleanupFailures: unknown[] = [];\n private readonly deadlineAt?: number;\n private readonly timeoutMs?: number;\n private readonly timer?: NodeJS.Timeout;\n private accepting = true;\n private finished = false;\n\n constructor(options: {\n nodeId: string;\n attemptId: string;\n startedAt: string;\n timeoutMs?: number;\n }) {\n this.nodeId = options.nodeId;\n this.attemptId = options.attemptId;\n this.startedAt = options.startedAt;\n this.signal = this.controller.signal;\n if (options.timeoutMs != null && options.timeoutMs > 0) {\n this.timeoutMs = options.timeoutMs;\n this.deadlineAt = performance.now() + options.timeoutMs;\n this.timer = setTimeout(\n () => this.cancel(new TimeoutError(options.timeoutMs!)),\n options.timeoutMs,\n );\n }\n }\n\n get active(): boolean {\n return this.accepting && !this.signal.aborted;\n }\n\n assertActive(): void {\n this.checkDeadline();\n this.signal.throwIfAborted();\n if (!this.accepting) {\n throw new Error(\"Flow attempt has finished accepting work\");\n }\n }\n\n remainingTimeoutMs(): number | undefined {\n this.assertActive();\n return this.deadlineAt === undefined\n ? undefined\n : Math.max(1, Math.ceil(this.deadlineAt - performance.now()));\n }\n\n cancel(reason: unknown, signal: NodeJS.Signals = \"SIGTERM\"): void {\n if (this.finished || this.signal.aborted) {\n return;\n }\n this.accepting = false;\n this.terminationSignal = signal;\n this.controller.abort(reason);\n for (const cancel of this.cancellations) {\n this.trackCancellation(cancel);\n }\n }\n\n registerCancellation(cancel: (signal: NodeJS.Signals) => Promise<void>): () => void {\n if (!this.active) {\n this.trackCancellation(cancel);\n return () => {};\n }\n this.cancellations.add(cancel);\n return () => {\n this.cancellations.delete(cancel);\n };\n }\n\n /** Track runtime work, never an arbitrary user callback that may ignore cancellation. */\n own<T>(run: () => Promise<T>, options: { bestEffort?: boolean } = {}): Promise<T> {\n this.assertActive();\n const operation = run().then((value) => {\n this.checkDeadline();\n if (this.signal.aborted) {\n this.signal.throwIfAborted();\n }\n return value;\n });\n const outcome = operation.then<OwnedOutcome, OwnedOutcome>(\n () => ({ ok: true }),\n (error: unknown) => (options.bestEffort ? { ok: true } : { ok: false, error }),\n );\n this.pending.add(outcome);\n void outcome.then(() => this.pending.delete(outcome));\n return operation;\n }\n\n async run<T>(run: () => Promise<T>): Promise<T> {\n let rejectAbort: (reason: unknown) => void = () => {};\n const aborted = new Promise<never>((_resolve, reject) => {\n rejectAbort = reject;\n });\n const onAbort = () => rejectAbort(this.signal.reason);\n this.signal.addEventListener(\"abort\", onAbort, { once: true });\n try {\n this.assertActive();\n const value = await Promise.race([run(), aborted]);\n this.accepting = false;\n const errors = await this.drain();\n if (errors.length > 0) {\n throw this.cleanupError(errors);\n }\n this.checkDeadline();\n this.signal.throwIfAborted();\n return value;\n } catch (error) {\n this.cancel(error);\n const errors = await this.drain();\n if (errors.length > 0) {\n throw this.cleanupError([error, ...errors]);\n }\n throw error;\n } finally {\n this.accepting = false;\n this.finished = true;\n clearTimeout(this.timer);\n this.signal.removeEventListener(\"abort\", onAbort);\n }\n }\n\n private checkDeadline(): void {\n if (this.deadlineAt !== undefined && performance.now() >= this.deadlineAt) {\n this.cancel(new TimeoutError(this.timeoutMs!));\n }\n }\n\n private async drain(): Promise<unknown[]> {\n const errors: unknown[] = [];\n while (this.pending.size > 0) {\n for (const outcome of await Promise.all(this.pending)) {\n if (!outcome.ok && outcome.error !== this.signal.reason) {\n errors.push(outcome.error);\n }\n }\n }\n return [...new Set([...errors, ...this.cleanupFailures.splice(0)])];\n }\n\n private trackCancellation(cancel: (signal: NodeJS.Signals) => Promise<void>): void {\n const outcome = Promise.resolve()\n .then(() => cancel(this.terminationSignal))\n .then<OwnedOutcome, OwnedOutcome>(\n () => ({ ok: true }),\n (error: unknown) => {\n this.cleanupFailures.push(error);\n return { ok: true };\n },\n );\n this.pending.add(outcome);\n void outcome.then(() => this.pending.delete(outcome));\n }\n\n private cleanupError(errors: unknown[]): Error {\n const reason: unknown = this.signal.reason;\n const failures = [...new Set([...(this.signal.aborted ? [reason] : []), ...errors])];\n return new AggregateError(failures, \"Flow attempt cleanup failed\", { cause: failures[0] });\n }\n}\n","import type { FlowDefinition } from \"./types.js\";\n\nconst FLOW_DEFINITION_BRAND = Symbol.for(\"acpx.flow.definition\");\n\nexport function markDefinedFlow<TFlow extends FlowDefinition>(definition: TFlow): TFlow {\n if (isDefinedFlow(definition)) {\n return definition;\n }\n\n Object.defineProperty(definition, FLOW_DEFINITION_BRAND, {\n value: true,\n enumerable: false,\n configurable: false,\n writable: false,\n });\n return definition;\n}\n\nexport function isDefinedFlow(value: unknown): value is FlowDefinition {\n return (\n value != null &&\n typeof value === \"object\" &&\n (value as Record<PropertyKey, unknown>)[FLOW_DEFINITION_BRAND] === true\n );\n}\n","import { ZodError, z } from \"zod\";\nimport { PERMISSION_MODES } from \"../types.js\";\nimport type {\n AcpNodeDefinition,\n ActionNodeDefinition,\n CheckpointNodeDefinition,\n ComputeNodeDefinition,\n FlowDefinition,\n FlowRunDefinition,\n FunctionActionNodeDefinition,\n ShellActionNodeDefinition,\n} from \"./types.js\";\n\nconst FLOW_NODE_TYPES = [\"acp\", \"compute\", \"action\", \"checkpoint\"] as const;\n\nconst finiteNonNegativeNumberSchema = z.number().finite().nonnegative();\nconst nonEmptyTrimmedStringSchema = z.string().refine((value) => value.trim().length > 0, {\n message: \"must not be empty\",\n});\n\nfunction extensibleObject<TShape extends z.ZodRawShape>(shape: TShape) {\n return z.object(shape).passthrough();\n}\n\nfunction functionSchema<T extends Function>(label: string): z.ZodType<T> {\n return z.custom<T>((value) => typeof value === \"function\", {\n message: `${label} must be a function`,\n });\n}\n\nconst flowNodeCommonShape = {\n timeoutMs: finiteNonNegativeNumberSchema.optional(),\n heartbeatMs: finiteNonNegativeNumberSchema.optional(),\n statusDetail: z.string().optional(),\n} satisfies z.ZodRawShape;\n\nconst flowPermissionRequirementsSchema = extensibleObject({\n requiredMode: z.enum(PERMISSION_MODES),\n requireExplicitGrant: z.boolean().optional(),\n reason: nonEmptyTrimmedStringSchema.optional(),\n});\n\nconst flowRunDefinitionSchema = extensibleObject({\n title: z\n .union([\n z.string(),\n functionSchema<Exclude<FlowRunDefinition[\"title\"], string | undefined>>(\"run.title\"),\n ])\n .optional(),\n});\n\nconst acpSessionSchema = extensibleObject({\n handle: z.string().optional(),\n isolated: z.boolean().optional(),\n});\n\nconst acpNodeSchema = extensibleObject({\n ...flowNodeCommonShape,\n nodeType: z.literal(\"acp\"),\n profile: z.string().optional(),\n cwd: z\n .union([\n z.string(),\n functionSchema<Exclude<AcpNodeDefinition[\"cwd\"], string | undefined>>(\"cwd\"),\n ])\n .optional(),\n session: acpSessionSchema.optional(),\n prompt: functionSchema<AcpNodeDefinition[\"prompt\"]>(\"prompt\"),\n parse: functionSchema<NonNullable<AcpNodeDefinition[\"parse\"]>>(\"parse\").optional(),\n});\n\nconst computeNodeSchema = extensibleObject({\n ...flowNodeCommonShape,\n nodeType: z.literal(\"compute\"),\n run: functionSchema<ComputeNodeDefinition[\"run\"]>(\"run\"),\n});\n\nconst functionActionNodeSchema = extensibleObject({\n ...flowNodeCommonShape,\n nodeType: z.literal(\"action\"),\n run: functionSchema<FunctionActionNodeDefinition[\"run\"]>(\"run\"),\n});\n\nconst shellActionNodeSchema = extensibleObject({\n ...flowNodeCommonShape,\n nodeType: z.literal(\"action\"),\n exec: functionSchema<ShellActionNodeDefinition[\"exec\"]>(\"exec\"),\n parse: functionSchema<NonNullable<ShellActionNodeDefinition[\"parse\"]>>(\"parse\").optional(),\n}).refine((node) => !hasOwn(node, \"run\"), {\n message: \"shell action nodes must not define run\",\n});\n\nconst checkpointNodeSchema = extensibleObject({\n ...flowNodeCommonShape,\n nodeType: z.literal(\"checkpoint\"),\n summary: z.string().optional(),\n run: functionSchema<NonNullable<CheckpointNodeDefinition[\"run\"]>>(\"run\").optional(),\n});\n\nconst directFlowEdgeSchema = extensibleObject({\n from: z.string(),\n to: z.string(),\n});\n\nconst switchFlowEdgeSchema = extensibleObject({\n from: z.string(),\n switch: extensibleObject({\n on: z.string(),\n cases: z.record(z.string(), z.string()),\n }),\n});\n\nconst flowDefinitionSchema = extensibleObject({\n name: nonEmptyTrimmedStringSchema,\n run: flowRunDefinitionSchema.optional(),\n permissions: flowPermissionRequirementsSchema.optional(),\n startAt: z.string(),\n nodes: z.record(z.string(), z.unknown()),\n edges: z.array(z.unknown()),\n});\n\nconst flowNodeTypeSchema = z.object({\n nodeType: z.enum(FLOW_NODE_TYPES),\n});\n\nexport function assertValidFlowDefinitionShape(flow: FlowDefinition): void {\n const parsed = parseWithSchema(\"flow definition\", flowDefinitionSchema, flow);\n\n // Zod strips __proto__ record entries; validate the original own node values.\n for (const [nodeId, node] of Object.entries(flow.nodes)) {\n assertValidFlowNodeDefinitionShape(node, `flow node \"${nodeId}\"`);\n }\n parsed.edges.forEach((edge, index) => {\n assertValidFlowEdgeShape(edge, `flow definition: edges.${index}`);\n });\n}\n\nexport function assertValidAcpNodeDefinition(node: AcpNodeDefinition): void {\n parseWithSchema(\"acp node definition\", acpNodeSchema, node);\n}\n\nexport function assertValidComputeNodeDefinition(node: ComputeNodeDefinition): void {\n parseWithSchema(\"compute node definition\", computeNodeSchema, node);\n}\n\nexport function assertValidActionNodeDefinition(node: ActionNodeDefinition): void {\n assertValidActionNodeDefinitionShape(node, \"action node definition\");\n}\n\nexport function assertValidShellActionNodeDefinition(node: ShellActionNodeDefinition): void {\n parseWithSchema(\"shell action node definition\", shellActionNodeSchema, node);\n}\n\nexport function assertValidCheckpointNodeDefinition(node: CheckpointNodeDefinition): void {\n parseWithSchema(\"checkpoint node definition\", checkpointNodeSchema, node);\n}\n\nfunction assertValidFlowNodeDefinitionShape(node: unknown, label: string): void {\n const { nodeType } = parseWithSchema(label, flowNodeTypeSchema, node);\n\n switch (nodeType) {\n case \"acp\":\n parseWithSchema(label, acpNodeSchema, node);\n return;\n case \"compute\":\n parseWithSchema(label, computeNodeSchema, node);\n return;\n case \"action\":\n assertValidActionNodeDefinitionShape(node, label);\n return;\n case \"checkpoint\":\n parseWithSchema(label, checkpointNodeSchema, node);\n return;\n }\n}\n\nfunction assertValidActionNodeDefinitionShape(node: unknown, label: string): void {\n const hasRun = hasOwn(node, \"run\");\n const hasExec = hasOwn(node, \"exec\");\n\n if (hasRun === hasExec) {\n throw new Error(`Invalid ${label}: action nodes must define exactly one of run or exec`);\n }\n\n if (hasExec) {\n parseWithSchema(label, shellActionNodeSchema, node);\n return;\n }\n\n parseWithSchema(label, functionActionNodeSchema, node);\n}\n\nfunction assertValidFlowEdgeShape(edge: unknown, label: string): void {\n const hasTo = hasOwn(edge, \"to\");\n const hasSwitch = hasOwn(edge, \"switch\");\n\n if (hasTo === hasSwitch) {\n throw new Error(`Invalid ${label}: edge must define exactly one of to or switch`);\n }\n\n if (hasTo) {\n parseWithSchema(label, directFlowEdgeSchema, edge);\n return;\n }\n\n parseWithSchema(label, switchFlowEdgeSchema, edge);\n // The shape check validates the containers, but skips __proto__ record values.\n const cases = (edge as { switch: { cases: Record<string, unknown> } }).switch.cases;\n for (const [key, target] of Object.entries(cases)) {\n parseWithSchema(`${label}: switch.cases.${key}`, z.string(), target);\n }\n}\n\nfunction parseWithSchema<T>(label: string, schema: z.ZodType<T>, value: unknown): T {\n try {\n return schema.parse(value);\n } catch (error) {\n if (error instanceof ZodError) {\n throw new Error(formatValidationError(label, error), { cause: error });\n }\n throw error;\n }\n}\n\nfunction formatValidationError(label: string, error: ZodError): string {\n const details = Array.from(new Set(error.issues.flatMap((issue) => formatIssue(issue)))).join(\n \"; \",\n );\n return `Invalid ${label}: ${details}`;\n}\n\nfunction formatIssue(issue: z.ZodIssue, parentPath: string[] = []): string[] {\n const path = [...parentPath, ...issue.path.map(String)];\n\n if (issue.code === \"invalid_union\") {\n return issue.errors.flatMap((branch) =>\n branch.flatMap((nestedIssue) => formatIssue(nestedIssue, path)),\n );\n }\n\n const renderedPath = path.join(\".\");\n return [renderedPath ? `${renderedPath}: ${issue.message}` : issue.message];\n}\n\nfunction hasOwn(value: unknown, key: string): boolean {\n return (\n value != null && typeof value === \"object\" && Object.prototype.hasOwnProperty.call(value, key)\n );\n}\n","import { markDefinedFlow } from \"./authoring.js\";\nimport {\n assertValidAcpNodeDefinition,\n assertValidActionNodeDefinition,\n assertValidCheckpointNodeDefinition,\n assertValidComputeNodeDefinition,\n assertValidFlowDefinitionShape,\n assertValidShellActionNodeDefinition,\n} from \"./schema.js\";\nimport type {\n AcpNodeDefinition,\n ActionNodeDefinition,\n CheckpointNodeDefinition,\n ComputeNodeDefinition,\n FlowDefinition,\n FunctionActionNodeDefinition,\n ShellActionNodeDefinition,\n} from \"./types.js\";\n\nexport function defineFlow<TFlow extends FlowDefinition>(definition: TFlow): TFlow {\n assertValidFlowDefinitionShape(definition);\n return markDefinedFlow(definition);\n}\n\nexport function acp(definition: Omit<AcpNodeDefinition, \"nodeType\">): AcpNodeDefinition {\n const node: AcpNodeDefinition = {\n nodeType: \"acp\",\n ...definition,\n };\n assertValidAcpNodeDefinition(node);\n return node;\n}\n\nexport function compute(\n definition: Omit<ComputeNodeDefinition, \"nodeType\">,\n): ComputeNodeDefinition {\n const node: ComputeNodeDefinition = {\n nodeType: \"compute\",\n ...definition,\n };\n assertValidComputeNodeDefinition(node);\n return node;\n}\n\nexport function action(\n definition: Omit<FunctionActionNodeDefinition, \"nodeType\">,\n): FunctionActionNodeDefinition;\nexport function action(\n definition: Omit<ShellActionNodeDefinition, \"nodeType\">,\n): ShellActionNodeDefinition;\nexport function action(\n definition:\n | Omit<FunctionActionNodeDefinition, \"nodeType\">\n | Omit<ShellActionNodeDefinition, \"nodeType\">,\n): ActionNodeDefinition {\n const node: ActionNodeDefinition = {\n nodeType: \"action\",\n ...definition,\n };\n assertValidActionNodeDefinition(node);\n return node;\n}\n\nexport function shell(\n definition: Omit<ShellActionNodeDefinition, \"nodeType\">,\n): ShellActionNodeDefinition {\n const node: ShellActionNodeDefinition = {\n nodeType: \"action\",\n ...definition,\n };\n assertValidShellActionNodeDefinition(node);\n return node;\n}\n\nexport function checkpoint(\n definition: Omit<CheckpointNodeDefinition, \"nodeType\"> = {},\n): CheckpointNodeDefinition {\n const node: CheckpointNodeDefinition = {\n nodeType: \"checkpoint\",\n ...definition,\n };\n assertValidCheckpointNodeDefinition(node);\n return node;\n}\n","type ShellOutputStream = \"stdout\" | \"stderr\";\n\nexport function validateShellActionMaxBufferBytes(value: number | undefined): void {\n if (value === undefined) {\n return;\n }\n if (!Number.isSafeInteger(value) || value < 0) {\n throw new Error(\"Shell action maxBufferBytes must be a non-negative safe integer\");\n }\n}\n\nexport function createShellOutputCapture(\n maxBufferBytes: number | undefined,\n inactive: () => boolean,\n overflow: (error: Error) => void,\n) {\n const output = { stdout: \"\", stderr: \"\" };\n const bytes = { stdout: 0, stderr: 0 };\n return {\n output,\n append(stream: ShellOutputStream, chunk: string): void {\n if (inactive()) {\n return;\n }\n if (maxBufferBytes !== undefined) {\n bytes[stream] += Buffer.byteLength(chunk, \"utf8\");\n if (bytes[stream] > maxBufferBytes) {\n overflow(\n new Error(`Shell action exceeded maxBuffer (${maxBufferBytes} bytes) on ${stream}`),\n );\n return;\n }\n }\n output[stream] += chunk;\n },\n };\n}\n","import type { ChildProcess } from \"node:child_process\";\nimport { setTimeout as wait } from \"node:timers/promises\";\nimport { runTimedExecFile } from \"../../acp/client-process.js\";\nimport { withTimeout } from \"../../async-control.js\";\n\nconst KILL_GRACE_MS = 1_000;\ntype PosixProcess = { pid: number; parent: number; group: number; state: string };\n\nasync function readPosixProcesses(): Promise<PosixProcess[]> {\n const output = await runTimedExecFile(\"ps\", [\"-eo\", \"pid=,ppid=,pgid=,stat=\"]);\n return output\n .trim()\n .split(\"\\n\")\n .map((line) => {\n const [pid, parent, group, state = \"\"] = line.trim().split(/\\s+/u);\n return { pid: Number(pid), parent: Number(parent), group: Number(group), state };\n })\n .filter((entry) => Number.isInteger(entry.pid) && entry.pid > 0);\n}\n\nfunction isLive(entry: PosixProcess): boolean {\n // Orphan zombies have terminated; only their new parent can reap them.\n return entry.state.length > 0 && !entry.state.startsWith(\"Z\");\n}\n\nfunction rememberOwnedProcesses(rows: PosixProcess[], root: number, owned: Set<number>): void {\n for (const entry of rows) {\n if (entry.group === root) {\n owned.add(entry.pid);\n }\n }\n for (const parent of owned) {\n for (const entry of rows) {\n if (entry.parent === parent) {\n owned.add(entry.pid);\n }\n }\n }\n}\n\nfunction signalPid(pid: number, signal: NodeJS.Signals): void {\n try {\n process.kill(pid, signal);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== \"ESRCH\") {\n throw error;\n }\n }\n}\n\nasync function signalGroup(root: number, signal: NodeJS.Signals): Promise<void> {\n try {\n process.kill(-root, signal);\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code;\n if (code === \"ESRCH\") {\n return;\n }\n if (\n code === \"EPERM\" &&\n !(await readPosixProcesses()).some((entry) => entry.group === root && isLive(entry))\n ) {\n return;\n }\n throw error;\n }\n}\n\nasync function signalOwned(\n root: number,\n owned: Set<number>,\n signal: NodeJS.Signals,\n): Promise<void> {\n const rows = await readPosixProcesses();\n rememberOwnedProcesses(rows, root, owned);\n await signalGroup(root, signal);\n // Group members receive the initial signal once; escaped descendants need direct delivery.\n for (const entry of rows) {\n if (owned.has(entry.pid) && entry.group !== root && isLive(entry)) {\n signalPid(entry.pid, signal);\n }\n }\n}\n\nasync function waitForOwned(root: number, owned: Set<number>): Promise<boolean> {\n const deadline = Date.now() + KILL_GRACE_MS;\n do {\n const rows = await readPosixProcesses();\n rememberOwnedProcesses(rows, root, owned);\n if (!rows.some((entry) => owned.has(entry.pid) && isLive(entry))) {\n return true;\n }\n await wait(25);\n } while (Date.now() < deadline);\n return false;\n}\n\nasync function forceKnownProcesses(root: number, owned: Set<number>): Promise<void> {\n const results = await Promise.allSettled([\n signalGroup(root, \"SIGKILL\"),\n ...[...owned].map(async (pid) => signalPid(pid, \"SIGKILL\")),\n ]);\n const errors: unknown[] = [];\n for (const result of results) {\n if (result.status === \"rejected\") {\n errors.push(result.reason);\n }\n }\n if (errors.length > 0) {\n throw new AggregateError(errors, \"Known shell processes could not be stopped\", {\n cause: errors[0],\n });\n }\n}\n\nasync function stopPosixTree(pid: number, signal: NodeJS.Signals): Promise<void> {\n const owned = new Set([pid]);\n try {\n await signalOwned(pid, owned, signal);\n if (await waitForOwned(pid, owned)) {\n return;\n }\n await signalOwned(pid, owned, \"SIGKILL\");\n if (!(await waitForOwned(pid, owned))) {\n throw new Error(\"Shell process tree did not terminate after SIGKILL\");\n }\n } catch (error) {\n try {\n await forceKnownProcesses(pid, owned);\n } catch (cleanupError) {\n throw new AggregateError([error, cleanupError], \"Shell process cleanup failed\", {\n cause: cleanupError,\n });\n }\n throw error;\n }\n}\n\nasync function stopWindowsTree(child: ChildProcess): Promise<void> {\n if (child.pid == null || child.exitCode != null || child.signalCode != null) {\n return;\n }\n try {\n await runTimedExecFile(\"taskkill\", [\"/pid\", String(child.pid), \"/t\", \"/f\"], {\n windowsHide: true,\n });\n } catch (error) {\n // Do not infer Windows ancestry from reusable numeric ParentProcessId values.\n child.kill(\"SIGKILL\");\n throw error;\n }\n}\n\nasync function waitForShellClose(closed: Promise<void>): Promise<void> {\n try {\n await withTimeout(closed, KILL_GRACE_MS);\n } catch (cause) {\n throw new Error(\"Shell process streams did not close after termination\", { cause });\n }\n}\n\nexport async function stopShellProcess(\n child: ChildProcess,\n closed: Promise<void>,\n signal: NodeJS.Signals,\n): Promise<void> {\n try {\n if (child.pid != null) {\n if (process.platform === \"win32\") {\n await stopWindowsTree(child);\n } else {\n await stopPosixTree(child.pid, signal);\n }\n }\n } catch (error) {\n try {\n await waitForShellClose(closed);\n } catch (closeError) {\n throw new AggregateError([error, closeError], \"Shell process cleanup failed\", {\n cause: closeError,\n });\n }\n throw error;\n }\n await waitForShellClose(closed);\n}\n\nexport function hasShellProcesses(child: ChildProcess): boolean {\n if (child.pid == null) {\n return false;\n }\n if (process.platform === \"win32\") {\n return child.exitCode == null && child.signalCode == null;\n }\n try {\n process.kill(-child.pid, 0);\n return true;\n } catch (error) {\n return (error as NodeJS.ErrnoException).code !== \"ESRCH\";\n }\n}\n","import { spawn, type ChildProcess } from \"node:child_process\";\nimport { InterruptedError, TimeoutError } from \"../../async-control.js\";\nimport type { ShellActionExecution, ShellActionResult } from \"../runtime.js\";\nimport type { FlowShellExecution, FlowShellResult } from \"../types.js\";\nimport { createShellOutputCapture, validateShellActionMaxBufferBytes } from \"./shell-output.js\";\nimport { hasShellProcesses, stopShellProcess } from \"./shell-process.js\";\n\nfunction writeShellStdin(child: ChildProcess, stdin: string | undefined): void {\n const stream = child.stdin;\n if (!stream) {\n return;\n }\n stream.on(\"error\", () => {\n // A child may close its input early; its exit status remains authoritative.\n });\n if (stdin != null && stream.writable && !stream.writableEnded) {\n stream.write(stdin);\n }\n if (stream.writable && !stream.writableEnded) {\n stream.end();\n }\n}\n\nexport function formatShellActionSummary(spec: ShellActionExecution): string {\n return `shell: ${renderShellCommand(spec.command, spec.args ?? [])}`;\n}\n\nexport function renderShellCommand(command: string, args: string[]): string {\n const renderedArgs = args.map((arg) => JSON.stringify(arg)).join(\" \");\n return renderedArgs.length > 0 ? `${command} ${renderedArgs}` : command;\n}\n\nfunction createShellFailureError(\n spec: ShellActionExecution,\n args: string[],\n exitCode: number | null,\n signal: NodeJS.Signals | null,\n stderr: string,\n): Error {\n const status = signal ? `signal ${signal}` : `exit ${String(exitCode)}`;\n const details = stderr.length > 0 ? `\\n${stderr.trim()}` : \"\";\n return new Error(\n `Shell action failed (${renderShellCommand(spec.command, args)}): ${status}${details}`,\n );\n}\n\n/**\n * Resolve a shell-action timeout.\n * Non-positive values match withTimeout: no deadline (undefined).\n * Positive values arm SIGTERM/SIGKILL after that many ms.\n */\nexport function resolveShellActionTimeoutMs(timeoutMs: number | undefined): number | undefined {\n if (timeoutMs == null || !(timeoutMs > 0)) {\n return undefined;\n }\n return timeoutMs;\n}\n\nexport type ShellProcessOwner = {\n cancel: (signal: NodeJS.Signals) => Promise<void>;\n release: () => void;\n};\n\nexport type RunShellActionOptions = {\n /** Cancellation waits for the owned process tree to terminate. */\n signal?: AbortSignal;\n terminationSignal?: NodeJS.Signals;\n registerOwner?: (owner: ShellProcessOwner) => () => void;\n};\n\nexport async function withShellAbort<T>(run: () => Promise<T>, signal: AbortSignal): Promise<T> {\n signal.throwIfAborted();\n let rejectAbort: (reason: unknown) => void = () => {};\n const aborted = new Promise<never>((_resolve, reject) => {\n rejectAbort = reject;\n });\n const onAbort = () => rejectAbort(signal.reason);\n signal.addEventListener(\"abort\", onAbort, { once: true });\n try {\n return await Promise.race([run(), aborted]);\n } finally {\n signal.removeEventListener(\"abort\", onAbort);\n }\n}\n\nfunction rejectIfShellFailed(\n spec: ShellActionExecution,\n args: string[],\n result: ShellActionResult,\n timedOut: boolean,\n timeoutMs: number | undefined,\n): Error | undefined {\n if (timedOut) {\n return new TimeoutError(timeoutMs ?? spec.timeoutMs ?? 0);\n }\n if (((result.exitCode ?? 0) !== 0 || result.signal != null) && spec.allowNonZeroExit !== true) {\n return createShellFailureError(spec, args, result.exitCode, result.signal, result.stderr);\n }\n return undefined;\n}\n\nfunction waitForShellResult(\n child: ChildProcess,\n spec: ShellActionExecution,\n args: string[],\n cwd: string,\n startMs: number,\n termination: {\n timedOut: () => boolean;\n cancelled: () => boolean;\n cancel: ShellProcessOwner[\"cancel\"];\n },\n mode: \"node\" | \"command\",\n): Promise<FlowShellResult> {\n const stdoutStream = child.stdout;\n const stderrStream = child.stderr;\n if (!stdoutStream || !stderrStream) {\n throw new Error(\"Shell action child is missing stdio pipes\");\n }\n\n return new Promise<FlowShellResult>((resolve, reject) => {\n let settled = false;\n const fail = (error: unknown) => {\n settled = true;\n reject(error);\n };\n const capture = createShellOutputCapture(\n spec.maxBufferBytes,\n () => settled || (mode === \"node\" && termination.cancelled()),\n (error) => {\n if (termination.cancelled()) {\n return;\n }\n fail(error);\n void termination.cancel(\"SIGTERM\").catch(fail);\n },\n );\n stdoutStream.setEncoding(\"utf8\");\n stderrStream.setEncoding(\"utf8\");\n stdoutStream.on(\"data\", (chunk: string) => {\n capture.append(\"stdout\", chunk);\n });\n stderrStream.on(\"data\", (chunk: string) => {\n capture.append(\"stderr\", chunk);\n });\n\n child.once(\"error\", fail);\n child.once(mode === \"node\" ? \"exit\" : \"close\", (exitCode, signal) => {\n settled = true;\n const { stdout, stderr } = capture.output;\n const result: FlowShellResult = {\n command: spec.command,\n args,\n cwd,\n stdout,\n stderr,\n combinedOutput: `${stdout}${stderr}`,\n exitCode,\n signal,\n durationMs: Date.now() - startMs,\n timedOut: mode === \"node\" ? termination.cancelled() : termination.timedOut(),\n };\n resolve(result);\n });\n });\n}\n\nfunction createShellTermination(\n child: ChildProcess,\n timeoutMs: number | undefined,\n options: RunShellActionOptions,\n) {\n const closed = new Promise<void>((resolve) => child.once(\"close\", () => resolve()));\n let rejectCleanup: (error: unknown) => void = () => {};\n const cleanupFailure = new Promise<never>((_resolve, reject) => {\n rejectCleanup = reject;\n });\n let termination: Promise<void> | undefined;\n let timedOut = false;\n let cancelled = false;\n let released = false;\n let deadline: NodeJS.Timeout | undefined;\n let monitor: NodeJS.Timeout | undefined;\n let unregister: (() => void) | undefined;\n const clearDeadline = () => {\n if (deadline) {\n clearTimeout(deadline);\n }\n };\n const release = () => {\n if (released) {\n return;\n }\n released = true;\n clearDeadline();\n if (monitor) {\n clearInterval(monitor);\n }\n options.signal?.removeEventListener(\"abort\", onAbort);\n unregister?.();\n };\n const cancel = (signal: NodeJS.Signals): Promise<void> => {\n if (termination) {\n return termination;\n }\n if (released) {\n return Promise.resolve();\n }\n clearDeadline();\n cancelled = true;\n termination = stopShellProcess(child, closed, signal).finally(release);\n void termination.catch(rejectCleanup);\n return termination;\n };\n const onAbort = () => {\n void cancel(options.terminationSignal ?? \"SIGTERM\");\n };\n options.signal?.addEventListener(\"abort\", onAbort, { once: true });\n if (timeoutMs != null) {\n deadline = setTimeout(() => {\n timedOut = true;\n void cancel(\"SIGTERM\");\n }, timeoutMs);\n }\n unregister = options.registerOwner?.({ cancel, release });\n if (unregister) {\n child.once(\"close\", () => {\n if (released || termination) {\n return;\n }\n const prune = () => {\n if (!termination && !hasShellProcesses(child)) {\n release();\n }\n };\n monitor = setInterval(prune, 100);\n monitor.unref();\n prune();\n });\n }\n return {\n cancel,\n timedOut: () => timedOut,\n cancelled: () => cancelled,\n cleanupFailure,\n async dispose() {\n clearDeadline();\n try {\n await termination;\n } finally {\n if (!unregister) {\n release();\n }\n }\n },\n };\n}\n\nexport async function runShellAction(\n spec: ShellActionExecution,\n options: RunShellActionOptions = {},\n): Promise<ShellActionResult> {\n const { timedOut, ...result } = await runShellProcess(spec, options, \"node\");\n const failure = rejectIfShellFailed(\n spec,\n result.args,\n result,\n timedOut,\n resolveShellActionTimeoutMs(spec.timeoutMs),\n );\n if (failure) {\n throw failure;\n }\n return result;\n}\n\nexport async function runShellCommand(\n spec: FlowShellExecution,\n options: RunShellActionOptions,\n): Promise<FlowShellResult> {\n return await runShellProcess(spec, options, \"command\");\n}\n\nasync function runShellProcess(\n spec: ShellActionExecution,\n options: RunShellActionOptions,\n mode: \"node\" | \"command\",\n): Promise<FlowShellResult> {\n options.signal?.throwIfAborted();\n const cwd = spec.cwd ?? process.cwd();\n const args = spec.args ?? [];\n const startMs = Date.now();\n const timeoutMs = resolveShellActionTimeoutMs(spec.timeoutMs);\n validateShellActionMaxBufferBytes(spec.maxBufferBytes);\n const child = spawn(spec.command, args, {\n cwd,\n env: {\n ...process.env,\n ...spec.env,\n },\n shell: spec.shell,\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n windowsHide: true,\n detached: process.platform !== \"win32\",\n });\n\n const termination = createShellTermination(child, timeoutMs, options);\n const finish = waitForShellResult(child, spec, args, cwd, startMs, termination, mode);\n writeShellStdin(child, spec.stdin);\n try {\n const result = await Promise.race([finish, termination.cleanupFailure]);\n throwIfShellCancelled(options.signal, mode);\n return result;\n } finally {\n await termination.dispose();\n }\n}\n\nfunction throwIfShellCancelled(signal: AbortSignal | undefined, mode: \"node\" | \"command\"): void {\n if (!signal?.aborted) {\n return;\n }\n const reason: unknown = signal.reason;\n if (mode === \"command\" || reason instanceof TimeoutError || reason instanceof InterruptedError) {\n throw reason;\n }\n}\n","import { assertValidFlowDefinitionShape } from \"./schema.js\";\nimport type { FlowDefinition, FlowEdge, FlowNodeResult } from \"./types.js\";\n\nexport function validateFlowDefinition(flow: FlowDefinition): void {\n assertValidFlowDefinitionShape(flow);\n assertKnownFlowNode(flow, flow.startAt, \"Flow start node is missing\");\n\n const outgoingEdges = new Set<string>();\n for (const edge of flow.edges) {\n validateFlowEdge(flow, edge, outgoingEdges);\n }\n}\n\nfunction assertKnownFlowNode(flow: FlowDefinition, nodeId: string, description: string): void {\n if (!Object.hasOwn(flow.nodes, nodeId)) {\n throw new Error(`${description}: ${nodeId}`);\n }\n}\n\nfunction isDirectEdge(edge: FlowEdge): edge is Extract<FlowEdge, { to: string }> {\n return Object.hasOwn(edge, \"to\");\n}\n\nfunction validateFlowEdge(flow: FlowDefinition, edge: FlowEdge, outgoingEdges: Set<string>): void {\n assertKnownFlowNode(flow, edge.from, \"Flow edge references unknown from-node\");\n if (outgoingEdges.has(edge.from)) {\n throw new Error(`Flow node must not declare multiple outgoing edges: ${edge.from}`);\n }\n outgoingEdges.add(edge.from);\n\n if (isDirectEdge(edge)) {\n assertKnownFlowNode(flow, edge.to, \"Flow edge references unknown to-node\");\n return;\n }\n\n for (const target of Object.values(edge.switch.cases)) {\n assertKnownFlowNode(flow, target, \"Flow switch references unknown to-node\");\n }\n}\n\nfunction canFollowEdge(edge: FlowEdge, result: FlowNodeResult | undefined): boolean {\n return (\n !result ||\n result.outcome === \"ok\" ||\n (!isDirectEdge(edge) && edge.switch.on.startsWith(\"$result.\"))\n );\n}\n\nexport function resolveNext(\n edges: FlowEdge[],\n from: string,\n output: unknown,\n result?: FlowNodeResult,\n): string | null {\n const edge = edges.find((candidate) => candidate.from === from);\n if (!edge || !canFollowEdge(edge, result)) {\n return null;\n }\n\n if (isDirectEdge(edge)) {\n return edge.to;\n }\n\n const value = getBySwitchPath(output, result, edge.switch.on);\n if (typeof value !== \"string\" && typeof value !== \"number\" && typeof value !== \"boolean\") {\n throw new Error(`Flow switch value must be scalar for ${edge.switch.on}`);\n }\n const key = String(value);\n if (!Object.hasOwn(edge.switch.cases, key)) {\n throw new Error(`No flow switch case for ${edge.switch.on}=${JSON.stringify(value)}`);\n }\n return edge.switch.cases[key];\n}\n\nfunction getBySwitchPath(\n output: unknown,\n result: FlowNodeResult | undefined,\n jsonPath: string,\n): unknown {\n if (jsonPath.startsWith(\"$result.\")) {\n return getByPath(result, `$.${jsonPath.slice(\"$result.\".length)}`);\n }\n if (jsonPath.startsWith(\"$output.\")) {\n return getByPath(output, `$.${jsonPath.slice(\"$output.\".length)}`);\n }\n return getByPath(output, jsonPath);\n}\n\nfunction getByPath(value: unknown, jsonPath: string): unknown {\n if (!jsonPath.startsWith(\"$.\")) {\n throw new Error(`Unsupported JSON path: ${jsonPath}`);\n }\n\n return jsonPath\n .slice(2)\n .split(\".\")\n .reduce((current: unknown, key) => {\n if (current == null || typeof current !== \"object\") {\n return undefined;\n }\n return (current as Record<string, unknown>)[key];\n }, value);\n}\n","import { createHash, randomUUID } from \"node:crypto\";\nimport path from \"node:path\";\nimport { InterruptedError, TimeoutError } from \"../async-control.js\";\nimport { createOutputFormatter } from \"../cli/output/output.js\";\nimport { textPrompt } from \"../prompt-content.js\";\nimport { defaultSessionEventLog } from \"../session/event-log.js\";\nimport { SESSION_RECORD_SCHEMA } from \"../types.js\";\nimport type { PromptInput, SessionRecord } from \"../types.js\";\nimport type { FlowRunStore } from \"./store.js\";\nimport type {\n AcpNodeDefinition,\n FlowDefinition,\n FlowNodeContext,\n FlowNodeDefinition,\n FlowNodeOutcome,\n FlowNodeResult,\n FlowRunState,\n FlowSessionBinding,\n FlowStepTrace,\n ResolvedFlowAgent,\n} from \"./types.js\";\n\ntype MemoryWritable = {\n write(chunk: string): void;\n};\n\nexport function isoNow(): string {\n return new Date().toISOString();\n}\n\nexport function persistRunFailure(\n store: FlowRunStore,\n runDir: string,\n state: FlowRunState,\n error: unknown,\n): Promise<void> {\n if (\n state.finishedAt !== undefined &&\n (state.status === \"failed\" || state.status === \"timed_out\")\n ) {\n return Promise.resolve();\n }\n\n state.status = error instanceof TimeoutError ? \"timed_out\" : \"failed\";\n state.updatedAt = isoNow();\n state.finishedAt = state.updatedAt;\n state.error = error instanceof Error ? error.message : String(error);\n state.statusDetail = state.currentNode\n ? `Failed in ${state.currentNode}: ${state.error}`\n : state.error;\n return store.writeSnapshot(runDir, state, {\n scope: \"run\",\n type: \"run_failed\",\n payload: {\n status: state.status,\n error: state.error,\n },\n });\n}\n\nexport function makeFlowNodeContext(\n state: FlowRunState,\n input: unknown,\n services: FlowNodeContext[\"services\"],\n): FlowNodeContext {\n return {\n input,\n outputs: state.outputs,\n results: state.results,\n state,\n services,\n };\n}\n\nexport function markNodeStarted(\n state: FlowRunState,\n nodeId: string,\n attemptId: string,\n nodeType: FlowNodeDefinition[\"nodeType\"],\n startedAt: string,\n detail?: string,\n): void {\n state.status = \"running\";\n state.waitingOn = undefined;\n state.currentNode = nodeId;\n state.currentAttemptId = attemptId;\n state.currentNodeType = nodeType;\n state.currentNodeStartedAt = startedAt;\n state.lastHeartbeatAt = startedAt;\n state.statusDetail = detail ?? `Running ${nodeType} node ${nodeId}`;\n}\n\nexport function clearActiveNode(state: FlowRunState, detail?: string): void {\n state.currentNode = undefined;\n state.currentAttemptId = undefined;\n state.currentNodeType = undefined;\n state.currentNodeStartedAt = undefined;\n state.lastHeartbeatAt = undefined;\n state.statusDetail = detail;\n}\n\nexport function updateStatusDetail(state: FlowRunState, detail?: string): void {\n if (!detail) {\n return;\n }\n state.statusDetail = detail;\n}\n\nexport async function finalizeStepTrace(\n store: FlowRunStore,\n runDir: string,\n state: FlowRunState,\n nodeId: string,\n attemptId: string,\n output: unknown,\n baseTrace: FlowStepTrace | null,\n): Promise<FlowStepTrace | null> {\n const trace: FlowStepTrace = baseTrace ? structuredClone(baseTrace) : {};\n if (output !== undefined) {\n const inlineOutput = toInlineOutput(output);\n if (inlineOutput !== undefined) {\n trace.outputInline = inlineOutput;\n } else {\n trace.outputArtifact = await store.writeArtifact(runDir, state, output, {\n mediaType: outputArtifactMediaType(output),\n extension: outputArtifactExtension(output),\n nodeId,\n attemptId,\n });\n }\n }\n return Object.keys(trace).length > 0 ? trace : null;\n}\n\nexport function normalizePromptInput(prompt: PromptInput | string): PromptInput {\n return typeof prompt === \"string\" ? textPrompt(prompt) : prompt;\n}\n\nexport async function resolveNodeCwd(\n defaultCwd: string,\n cwd: AcpNodeDefinition[\"cwd\"],\n context: FlowNodeContext,\n): Promise<string> {\n if (typeof cwd === \"function\") {\n const resolved = (await cwd(context)) ?? defaultCwd;\n return path.resolve(defaultCwd, resolved);\n }\n return path.resolve(defaultCwd, cwd ?? defaultCwd);\n}\n\nexport function resolveShellActionCwd(defaultCwd: string, cwd: string | undefined): string {\n return path.resolve(defaultCwd, cwd ?? defaultCwd);\n}\n\nexport function summarizePrompt(promptText: string, explicitDetail?: string): string {\n if (explicitDetail) {\n return explicitDetail;\n }\n\n const line = promptText\n .split(\"\\n\")\n .map((candidate) => candidate.trim())\n .find((candidate) => candidate.length > 0);\n\n if (!line) {\n return \"Running ACP prompt\";\n }\n\n const truncated = line.length > 120 ? `${line.slice(0, 117)}...` : line;\n return `ACP: ${truncated}`;\n}\n\nexport function createQuietCaptureOutput(): {\n formatter: ReturnType<typeof createOutputFormatter>;\n read: () => string;\n sessionId: () => string | undefined;\n} {\n const chunks: string[] = [];\n let sessionId: string | undefined;\n const stdout: MemoryWritable = {\n write(chunk: string) {\n chunks.push(chunk);\n },\n };\n\n const formatter = createOutputFormatter(\"quiet\", { stdout });\n const setContext = formatter.setContext.bind(formatter);\n formatter.setContext = (context) => {\n sessionId = context.sessionId ?? sessionId;\n setContext(context);\n };\n return {\n formatter,\n read: () => chunks.join(\"\").trim(),\n sessionId: () => sessionId,\n };\n}\n\nexport async function resolveFlowRunTitle(\n flow: FlowDefinition,\n input: unknown,\n flowPath?: string,\n): Promise<string | undefined> {\n const titleDefinition = flow.run?.title;\n if (titleDefinition === undefined) {\n return undefined;\n }\n\n const resolved =\n typeof titleDefinition === \"function\"\n ? await Promise.resolve(titleDefinition({ input, flowName: flow.name, flowPath }))\n : titleDefinition;\n\n return normalizeFlowRunTitle(resolved);\n}\n\nexport function normalizeFlowRunTitle(value: string | undefined): string | undefined {\n const trimmed = value?.trim();\n return trimmed ? trimmed : undefined;\n}\n\nexport function createRunId(flowName: string): string {\n const stamp = isoNow().replaceAll(\":\", \"\").replaceAll(\".\", \"\");\n const slug = slugifyAsciiIdPart(flowName);\n return `${stamp}-${slug}-${randomUUID().slice(0, 8)}`;\n}\n\nexport function createSessionBindingKey(\n agentCommand: string,\n cwd: string,\n handle: string,\n agentArgv?: readonly string[],\n): string {\n return JSON.stringify([agentCommand, agentArgv ?? null, cwd, handle]);\n}\n\nexport function createSessionName(\n flowName: string,\n handle: string,\n cwd: string,\n runId: string,\n): string {\n const stamp = stableShortHash(cwd);\n return `${flowName}-${handle}-${stamp}-${runId.slice(-8)}`;\n}\n\nexport function createSessionBundleId(handle: string, key: string): string {\n const safeHandle = slugifyAsciiIdPart(handle);\n return `${safeHandle || \"session\"}-${stableShortHash(key)}`;\n}\n\nfunction slugifyAsciiIdPart(value: string): string {\n let slug = \"\";\n let lastWasSeparator = false;\n\n for (const char of value) {\n const safeChar = toLowerAsciiAlphaNumeric(char);\n if (safeChar) {\n slug += safeChar;\n lastWasSeparator = false;\n continue;\n }\n\n if (slug.length > 0 && !lastWasSeparator) {\n slug += \"-\";\n lastWasSeparator = true;\n }\n }\n\n return lastWasSeparator ? slug.slice(0, -1) : slug;\n}\n\nfunction toLowerAsciiAlphaNumeric(char: string): string | null {\n const code = char.charCodeAt(0);\n if (code >= 48 && code <= 57) {\n return char;\n }\n if (code >= 65 && code <= 90) {\n return String.fromCharCode(code + 32);\n }\n if (code >= 97 && code <= 122) {\n return char;\n }\n return null;\n}\n\nexport function createIsolatedSessionBinding(\n flowName: string,\n runId: string,\n attemptId: string,\n profile: string | undefined,\n agent: ResolvedFlowAgent,\n): FlowSessionBinding {\n const key = `isolated::${attemptId}`;\n const handle = \"isolated\";\n return {\n key,\n handle,\n bundleId: createSessionBundleId(`${handle}-${attemptId}`, `${key}::${agent.cwd}`),\n name: `${flowName}-${attemptId}-${runId.slice(-8)}`,\n profile,\n agentName: agent.agentName,\n agentCommand: agent.agentCommand,\n agentArgv: agent.agentArgv,\n cwd: agent.cwd,\n acpxRecordId: key,\n acpSessionId: key,\n };\n}\n\nexport function createSyntheticSessionRecord(options: {\n binding: FlowSessionBinding;\n createdAt: string;\n updatedAt: string;\n conversation: Pick<\n SessionRecord,\n | \"title\"\n | \"messages\"\n | \"updated_at\"\n | \"cumulative_token_usage\"\n | \"request_token_usage\"\n | \"cumulative_cost\"\n >;\n acpxState: SessionRecord[\"acpx\"] | undefined;\n lastSeq: number;\n}): SessionRecord {\n return {\n schema: SESSION_RECORD_SCHEMA,\n acpxRecordId: options.binding.acpxRecordId,\n acpSessionId: options.binding.acpSessionId,\n agentSessionId: options.binding.agentSessionId,\n agentCommand: options.binding.agentCommand,\n agentArgv: options.binding.agentArgv,\n cwd: options.binding.cwd,\n name: options.binding.name,\n createdAt: options.createdAt,\n lastUsedAt: options.updatedAt,\n lastSeq: options.lastSeq,\n lastRequestId: undefined,\n eventLog: defaultSessionEventLog(options.binding.acpxRecordId),\n closed: true,\n closedAt: options.updatedAt,\n title: options.conversation.title,\n messages: options.conversation.messages,\n updated_at: options.conversation.updated_at,\n cumulative_token_usage: options.conversation.cumulative_token_usage,\n cumulative_cost: options.conversation.cumulative_cost,\n request_token_usage: options.conversation.request_token_usage,\n acpx: options.acpxState,\n };\n}\n\nexport function createNodeResult(options: {\n attemptId: string;\n nodeId: string;\n nodeType: FlowNodeDefinition[\"nodeType\"];\n outcome: FlowNodeOutcome;\n startedAt: string;\n finishedAt: string;\n output?: unknown;\n error?: string;\n}): FlowNodeResult {\n return {\n attemptId: options.attemptId,\n nodeId: options.nodeId,\n nodeType: options.nodeType,\n outcome: options.outcome,\n startedAt: options.startedAt,\n finishedAt: options.finishedAt,\n durationMs: new Date(options.finishedAt).getTime() - new Date(options.startedAt).getTime(),\n output: options.output,\n error: options.error,\n };\n}\n\nexport function outcomeForError(error: unknown): FlowNodeOutcome {\n if (error instanceof TimeoutError) {\n return \"timed_out\";\n }\n if (error instanceof InterruptedError) {\n return \"cancelled\";\n }\n return \"failed\";\n}\n\nfunction stableShortHash(value: string): string {\n return createHash(\"sha1\").update(value).digest(\"hex\").slice(0, 8);\n}\n\nexport function nextAttemptId(attemptCounts: Map<string, number>, nodeId: string): string {\n const next = (attemptCounts.get(nodeId) ?? 0) + 1;\n attemptCounts.set(nodeId, next);\n return `${nodeId}#${next}`;\n}\n\nexport function createNodeOutcomePayload(\n result: FlowNodeResult,\n trace: FlowStepTrace | null,\n): Record<string, unknown> {\n return {\n nodeType: result.nodeType,\n outcome: result.outcome,\n durationMs: result.durationMs,\n error: result.error ?? null,\n ...trace,\n };\n}\n\nexport function attachStepTrace(error: unknown, trace: FlowStepTrace | null): Error {\n const attached =\n error instanceof Error ? error : new Error(typeof error === \"string\" ? error : String(error));\n (attached as Error & { flowStepTrace?: FlowStepTrace | null }).flowStepTrace = trace;\n return attached;\n}\n\nexport function extractAttachedStepTrace(error: unknown): FlowStepTrace | null | undefined {\n if (!(error instanceof Error)) {\n return undefined;\n }\n return (error as Error & { flowStepTrace?: FlowStepTrace | null }).flowStepTrace;\n}\n\nfunction toInlineOutput(value: unknown): undefined | null | boolean | number | string | object {\n if (value == null || typeof value === \"number\" || typeof value === \"boolean\") {\n return value;\n }\n if (typeof value === \"string\") {\n return isInlineSerializableText(value) ? value : undefined;\n }\n try {\n const serialized = JSON.stringify(value);\n if (isInlineSerializableText(serialized)) {\n return value;\n }\n } catch {\n return undefined;\n }\n return undefined;\n}\n\nfunction isInlineSerializableText(value: string): boolean {\n return value.length <= 200 && !value.includes(\"\\n\");\n}\n\nfunction outputArtifactMediaType(value: unknown): string {\n return typeof value === \"string\" ? \"text/plain\" : \"application/json\";\n}\n\nfunction outputArtifactExtension(value: unknown): string {\n return typeof value === \"string\" ? \"txt\" : \"json\";\n}\n\nexport function findConversationDeltaStart(\n before: SessionRecord[\"messages\"],\n after: SessionRecord[\"messages\"],\n): number {\n const maxOverlap = Math.min(before.length, after.length);\n for (let overlap = maxOverlap; overlap >= 0; overlap -= 1) {\n let matches = true;\n for (let index = 0; index < overlap; index += 1) {\n const beforeMessage = before[before.length - overlap + index];\n const afterMessage = after[index];\n if (!deepEqualJson(beforeMessage, afterMessage)) {\n matches = false;\n break;\n }\n }\n if (matches) {\n return overlap;\n }\n }\n return 0;\n}\n\nfunction deepEqualJson(left: unknown, right: unknown): boolean {\n return JSON.stringify(left) === JSON.stringify(right);\n}\n","import { createHash } from \"node:crypto\";\nimport fs from \"node:fs/promises\";\nimport os from \"node:os\";\nimport path from \"node:path\";\nimport { appendRegularFile } from \"@openclaw/fs-safe/advanced\";\nimport { writePrivateFile, writePrivateJsonFile } from \"../state-files.js\";\nimport type { AcpJsonRpcMessage, AcpMessageDirection, SessionRecord } from \"../types.js\";\nimport type {\n AcpNodeDefinition,\n FlowArtifactRef,\n FlowDefinition,\n FlowDefinitionSnapshot,\n FlowManifestSessionEntry,\n FlowNodeDefinition,\n FlowRunManifest,\n FlowRunState,\n FlowSessionBinding,\n FlowTraceEvent,\n FlowTraceEventDraft,\n} from \"./types.js\";\n\nconst FLOW_BUNDLE_SCHEMA = \"acpx.flow-run-bundle.v1\" as const;\nconst FLOW_TRACE_SCHEMA = \"acpx.flow-trace-event.v1\" as const;\nconst FLOW_SNAPSHOT_SCHEMA = \"acpx.flow-definition-snapshot.v1\" as const;\n\nconst MANIFEST_PATH = \"manifest.json\";\nconst FLOW_SNAPSHOT_PATH = \"flow.json\";\nconst TRACE_PATH = \"trace.ndjson\";\nconst PROJECTIONS_DIR = \"projections\";\nconst RUN_PROJECTION_PATH = \"projections/run.json\";\nconst LIVE_PROJECTION_PATH = \"projections/live.json\";\nconst STEPS_PROJECTION_PATH = \"projections/steps.json\";\nconst SESSIONS_DIR = \"sessions\";\nconst ARTIFACTS_DIR = \"artifacts\";\n\ntype FlowLiveState = {\n runId: string;\n flowName: string;\n runTitle?: string;\n flowPath?: string;\n startedAt: string;\n finishedAt?: string;\n updatedAt: string;\n status: FlowRunState[\"status\"];\n currentNode?: string;\n currentAttemptId?: string;\n currentNodeType?: FlowRunState[\"currentNodeType\"];\n currentNodeStartedAt?: string;\n lastHeartbeatAt?: string;\n statusDetail?: string;\n waitingOn?: string;\n error?: string;\n sessionBindings: FlowRunState[\"sessionBindings\"];\n};\n\ntype WriteArtifactOptions = {\n mediaType: string;\n extension: string;\n nodeId?: string;\n attemptId?: string;\n sessionId?: string;\n emitTrace?: boolean;\n};\n\nexport function flowRunsBaseDir(homeDir: string = os.homedir()): string {\n return path.join(homeDir, \".acpx\", \"flows\", \"runs\");\n}\n\nexport class FlowRunStore {\n readonly outputRoot: string;\n private readonly traceSeqByRun = new Map<string, number>();\n private readonly sessionSeqByBundle = new Map<string, { allocated: number; persisted: number }>();\n private readonly manifestByRun = new Map<string, FlowRunManifest>();\n private readonly writeChainByPath = new Map<string, Promise<void>>();\n\n constructor(outputRoot: string = flowRunsBaseDir()) {\n this.outputRoot = outputRoot;\n }\n\n releaseRun(runDir: string): void {\n this.traceSeqByRun.delete(runDir);\n this.manifestByRun.delete(runDir);\n for (const key of this.sessionSeqByBundle.keys()) {\n if (key.startsWith(`${runDir}::`)) {\n this.sessionSeqByBundle.delete(key);\n }\n }\n }\n\n async createRunDir(runId: string): Promise<string> {\n const runDir = path.join(this.outputRoot, runId);\n await fs.mkdir(path.join(runDir, PROJECTIONS_DIR), { recursive: true, mode: 0o700 });\n await fs.mkdir(path.join(runDir, SESSIONS_DIR), { recursive: true, mode: 0o700 });\n await fs.mkdir(path.join(runDir, ARTIFACTS_DIR), { recursive: true, mode: 0o700 });\n this.traceSeqByRun.set(runDir, 0);\n return runDir;\n }\n\n async initializeRunBundle(\n runDir: string,\n options: {\n flow: FlowDefinition;\n state: FlowRunState;\n inputArtifact?: FlowArtifactRef;\n },\n ): Promise<void> {\n const snapshot = createFlowDefinitionSnapshot(options.flow);\n const manifest = createRunManifest(options.state);\n\n this.manifestByRun.set(runDir, manifest);\n await writePrivateJsonFile(this.resolveRunPath(runDir, FLOW_SNAPSHOT_PATH), snapshot);\n await writePrivateJsonFile(this.resolveRunPath(runDir, MANIFEST_PATH), manifest);\n await writePrivateJsonFile(this.resolveRunPath(runDir, RUN_PROJECTION_PATH), options.state);\n await writePrivateJsonFile(\n this.resolveRunPath(runDir, LIVE_PROJECTION_PATH),\n createLiveState(options.state),\n );\n await writePrivateJsonFile(\n this.resolveRunPath(runDir, STEPS_PROJECTION_PATH),\n options.state.steps,\n );\n await ensureFile(this.resolveRunPath(runDir, TRACE_PATH));\n\n await this.appendTrace(runDir, options.state, {\n scope: \"run\",\n type: \"run_started\",\n payload: {\n flowName: options.state.flowName,\n ...(options.state.runTitle ? { runTitle: options.state.runTitle } : {}),\n ...(options.state.flowPath ? { flowPath: options.state.flowPath } : {}),\n ...(options.inputArtifact ? { inputArtifact: options.inputArtifact } : {}),\n },\n });\n }\n\n async writeSnapshot(\n runDir: string,\n state: FlowRunState,\n event: FlowTraceEventDraft,\n ): Promise<void> {\n state.updatedAt = isoNow();\n await writePrivateJsonFile(this.resolveRunPath(runDir, RUN_PROJECTION_PATH), state);\n await writePrivateJsonFile(\n this.resolveRunPath(runDir, LIVE_PROJECTION_PATH),\n createLiveState(state),\n );\n await writePrivateJsonFile(this.resolveRunPath(runDir, STEPS_PROJECTION_PATH), state.steps);\n await this.writeManifest(runDir, state);\n await this.appendTrace(runDir, state, event);\n }\n\n async writeLive(runDir: string, state: FlowRunState, event: FlowTraceEventDraft): Promise<void> {\n state.updatedAt = isoNow();\n await writePrivateJsonFile(\n this.resolveRunPath(runDir, LIVE_PROJECTION_PATH),\n createLiveState(state),\n );\n await this.writeManifest(runDir, state);\n await this.appendTrace(runDir, state, event);\n }\n\n async appendTrace(\n runDir: string,\n state: FlowRunState,\n event: FlowTraceEventDraft,\n ): Promise<FlowTraceEvent> {\n const traceEvent: FlowTraceEvent = {\n seq: this.nextTraceSeq(runDir),\n at: isoNow(),\n runId: state.runId,\n ...event,\n };\n await this.appendJsonLine(this.resolveRunPath(runDir, TRACE_PATH), traceEvent);\n return traceEvent;\n }\n\n async writeArtifact(\n runDir: string,\n state: FlowRunState,\n content: unknown,\n options: WriteArtifactOptions,\n ): Promise<FlowArtifactRef> {\n const buffer = toArtifactBuffer(content, options.mediaType);\n const sha256 = createHash(\"sha256\").update(buffer).digest(\"hex\");\n const relativePath = path.posix.join(\n ARTIFACTS_DIR,\n `sha256-${sha256}${normalizeArtifactExtension(options.extension)}`,\n );\n const filePath = this.resolveRunPath(runDir, relativePath);\n try {\n await fs.access(filePath);\n } catch {\n await writePrivateFile(filePath, buffer);\n }\n\n const artifact: FlowArtifactRef = {\n path: relativePath,\n mediaType: options.mediaType,\n bytes: buffer.byteLength,\n sha256,\n };\n if (options.emitTrace !== false) {\n await this.appendTrace(runDir, state, {\n scope: \"artifact\",\n type: \"artifact_written\",\n nodeId: options.nodeId,\n attemptId: options.attemptId,\n sessionId: options.sessionId,\n artifact,\n payload: {\n artifact,\n },\n });\n }\n return artifact;\n }\n\n async ensureSessionBundle(\n runDir: string,\n state: FlowRunState,\n inputBinding: FlowSessionBinding,\n record?: SessionRecord,\n ): Promise<void> {\n const binding = structuredClone(inputBinding);\n const sessionDir = this.resolveRunPath(runDir, sessionDirPath(binding.bundleId));\n // Preserve the first binding and publication order across concurrent metadata updates.\n await this.serializeWrite(path.join(sessionDir, \"binding.json\"), async () => {\n await fs.mkdir(sessionDir, { recursive: true, mode: 0o700 });\n await writePrivateJsonFile(path.join(sessionDir, \"binding.json\"), binding);\n await ensureFile(path.join(sessionDir, \"events.ndjson\"));\n if (record) {\n await this.writeSessionRecord(runDir, state, binding, record);\n }\n\n const manifest = this.getManifest(runDir, state);\n const existing = manifest.sessions.find((entry) => entry.id === binding.bundleId);\n if (!existing) {\n // The trace keeps its initial snapshot while binding.json tracks current metadata.\n const bindingArtifact = await this.writeArtifact(runDir, state, binding, {\n mediaType: \"application/json\",\n extension: \"json\",\n emitTrace: false,\n });\n const entry: FlowManifestSessionEntry = {\n id: binding.bundleId,\n handle: binding.handle,\n bindingPath: path.posix.join(sessionDirPath(binding.bundleId), \"binding.json\"),\n recordPath: path.posix.join(sessionDirPath(binding.bundleId), \"record.json\"),\n eventsPath: path.posix.join(sessionDirPath(binding.bundleId), \"events.ndjson\"),\n };\n manifest.sessions.push(entry);\n await writePrivateJsonFile(this.resolveRunPath(runDir, MANIFEST_PATH), manifest);\n await this.appendTrace(runDir, state, {\n scope: \"session\",\n type: \"session_bound\",\n sessionId: binding.bundleId,\n payload: {\n sessionId: binding.bundleId,\n handle: binding.handle,\n bindingArtifact,\n },\n });\n }\n });\n }\n\n async writeSessionRecord(\n runDir: string,\n _state: FlowRunState,\n binding: FlowSessionBinding,\n record: SessionRecord,\n ): Promise<void> {\n const bundleSeq = this.sessionSeqByBundle.get(`${runDir}::${binding.bundleId}`)?.persisted ?? 0;\n const bundledRecord = createBundledSessionRecord(binding, record, bundleSeq);\n await writePrivateJsonFile(\n this.resolveRunPath(runDir, path.posix.join(sessionDirPath(binding.bundleId), \"record.json\")),\n bundledRecord,\n );\n }\n\n async appendSessionEvent(\n runDir: string,\n binding: FlowSessionBinding,\n direction: AcpMessageDirection,\n message: AcpJsonRpcMessage,\n ): Promise<number> {\n const sessionKey = `${runDir}::${binding.bundleId}`;\n const sequence = this.sessionSeqByBundle.get(sessionKey) ?? { allocated: 0, persisted: 0 };\n this.sessionSeqByBundle.set(sessionKey, sequence);\n // Reserve ordering immediately, but publish only successfully written cursors.\n const seq = ++sequence.allocated;\n await this.appendJsonLine(\n this.resolveRunPath(\n runDir,\n path.posix.join(sessionDirPath(binding.bundleId), \"events.ndjson\"),\n ),\n {\n seq,\n at: isoNow(),\n direction,\n message,\n },\n );\n sequence.persisted = Math.max(sequence.persisted, seq);\n return seq;\n }\n\n private getManifest(runDir: string, state: FlowRunState): FlowRunManifest {\n const existing = this.manifestByRun.get(runDir);\n if (existing) {\n existing.startedAt = state.startedAt;\n existing.finishedAt = state.finishedAt;\n existing.status = state.status;\n existing.flowPath = state.flowPath;\n existing.flowName = state.flowName;\n existing.runTitle = state.runTitle;\n return existing;\n }\n\n const created = createRunManifest(state);\n this.manifestByRun.set(runDir, created);\n return created;\n }\n\n private async writeManifest(runDir: string, state: FlowRunState): Promise<void> {\n const manifest = this.getManifest(runDir, state);\n await writePrivateJsonFile(this.resolveRunPath(runDir, MANIFEST_PATH), manifest);\n }\n\n private nextTraceSeq(runDir: string): number {\n const next = (this.traceSeqByRun.get(runDir) ?? 0) + 1;\n this.traceSeqByRun.set(runDir, next);\n return next;\n }\n\n private resolveRunPath(runDir: string, relativePath: string): string {\n return path.join(runDir, ...relativePath.split(\"/\"));\n }\n\n private async appendJsonLine(filePath: string, value: unknown): Promise<void> {\n await this.serializeWrite(filePath, async () => {\n await fs.mkdir(path.dirname(filePath), { recursive: true, mode: 0o700 });\n await appendRegularFile({ filePath, content: `${JSON.stringify(value)}\\n`, mode: 0o600 });\n });\n }\n\n private async serializeWrite(filePath: string, write: () => Promise<void>): Promise<void> {\n const prior = this.writeChainByPath.get(filePath) ?? Promise.resolve();\n const nextWrite = prior.then(write);\n const tracked = nextWrite.finally(() => {\n if (this.writeChainByPath.get(filePath) === tracked) {\n this.writeChainByPath.delete(filePath);\n }\n });\n this.writeChainByPath.set(filePath, tracked);\n await tracked;\n }\n}\n\nfunction createRunManifest(state: FlowRunState): FlowRunManifest {\n return {\n schema: FLOW_BUNDLE_SCHEMA,\n runId: state.runId,\n flowName: state.flowName,\n runTitle: state.runTitle,\n flowPath: state.flowPath,\n startedAt: state.startedAt,\n finishedAt: state.finishedAt,\n status: state.status,\n traceSchema: FLOW_TRACE_SCHEMA,\n paths: {\n flow: FLOW_SNAPSHOT_PATH,\n trace: TRACE_PATH,\n runProjection: RUN_PROJECTION_PATH,\n liveProjection: LIVE_PROJECTION_PATH,\n stepsProjection: STEPS_PROJECTION_PATH,\n sessionsDir: SESSIONS_DIR,\n artifactsDir: ARTIFACTS_DIR,\n },\n sessions: [],\n };\n}\n\nfunction createLiveState(state: FlowRunState): FlowLiveState {\n return {\n runId: state.runId,\n flowName: state.flowName,\n runTitle: state.runTitle,\n flowPath: state.flowPath,\n startedAt: state.startedAt,\n finishedAt: state.finishedAt,\n updatedAt: state.updatedAt,\n status: state.status,\n currentNode: state.currentNode,\n currentAttemptId: state.currentAttemptId,\n currentNodeType: state.currentNodeType,\n currentNodeStartedAt: state.currentNodeStartedAt,\n lastHeartbeatAt: state.lastHeartbeatAt,\n statusDetail: state.statusDetail,\n waitingOn: state.waitingOn,\n error: state.error,\n sessionBindings: state.sessionBindings,\n };\n}\n\nfunction createFlowDefinitionSnapshot(flow: FlowDefinition): FlowDefinitionSnapshot {\n return {\n schema: FLOW_SNAPSHOT_SCHEMA,\n name: flow.name,\n ...(flow.run?.title !== undefined ? { run: { hasTitle: true } } : {}),\n ...(flow.permissions ? { permissions: structuredClone(flow.permissions) } : {}),\n startAt: flow.startAt,\n nodes: Object.fromEntries(\n Object.entries(flow.nodes).map(([nodeId, node]) => [nodeId, snapshotNode(node)]),\n ),\n edges: structuredClone(flow.edges),\n };\n}\n\nfunction snapshotNode(node: FlowNodeDefinition): FlowDefinitionSnapshot[\"nodes\"][string] {\n const common = snapshotCommonNodeFields(node);\n\n switch (node.nodeType) {\n case \"acp\":\n return snapshotAcpNode(node, common);\n case \"compute\":\n return {\n ...common,\n hasRun: true,\n };\n case \"action\": {\n const actionExecution: \"shell\" | \"function\" = \"exec\" in node ? \"shell\" : \"function\";\n return {\n ...common,\n actionExecution,\n hasRun: \"run\" in node,\n hasExec: \"exec\" in node,\n hasParse: \"parse\" in node && typeof node.parse === \"function\",\n };\n }\n case \"checkpoint\":\n return {\n ...common,\n ...(node.summary ? { summary: node.summary } : {}),\n hasRun: typeof node.run === \"function\",\n };\n }\n\n throw new Error(`Unsupported flow node type: ${String(node satisfies never)}`);\n}\n\nfunction snapshotCommonNodeFields(node: FlowNodeDefinition): {\n nodeType: FlowNodeDefinition[\"nodeType\"];\n timeoutMs?: number;\n heartbeatMs?: number;\n statusDetail?: string;\n} {\n return {\n nodeType: node.nodeType,\n ...(node.timeoutMs !== undefined ? { timeoutMs: node.timeoutMs } : {}),\n ...(node.heartbeatMs !== undefined ? { heartbeatMs: node.heartbeatMs } : {}),\n ...(node.statusDetail ? { statusDetail: node.statusDetail } : {}),\n };\n}\n\nfunction snapshotAcpNode(\n node: Extract<FlowNodeDefinition, { nodeType: \"acp\" }>,\n common: ReturnType<typeof snapshotCommonNodeFields>,\n): FlowDefinitionSnapshot[\"nodes\"][string] {\n return {\n ...common,\n ...(node.profile ? { profile: node.profile } : {}),\n session: {\n ...(node.session?.handle ? { handle: node.session.handle } : {}),\n ...(node.session?.isolated ? { isolated: true } : {}),\n },\n cwd: snapshotCwd(node.cwd),\n hasPrompt: true,\n hasParse: typeof node.parse === \"function\",\n };\n}\n\nfunction snapshotCwd(cwd: AcpNodeDefinition[\"cwd\"]): {\n mode: \"default\" | \"static\" | \"dynamic\";\n value?: string;\n} {\n if (typeof cwd === \"function\") {\n return { mode: \"dynamic\" };\n }\n if (typeof cwd === \"string\") {\n return { mode: \"static\", value: cwd };\n }\n return { mode: \"default\" };\n}\n\nfunction createBundledSessionRecord(\n binding: FlowSessionBinding,\n record: SessionRecord,\n bundleLastSeq: number,\n): SessionRecord {\n return {\n ...structuredClone(record),\n lastSeq: bundleLastSeq,\n eventLog: {\n ...structuredClone(record.eventLog),\n active_path: path.posix.join(sessionDirPath(binding.bundleId), \"events.ndjson\"),\n segment_count: 1,\n max_segments: 1,\n },\n };\n}\n\nasync function ensureFile(filePath: string): Promise<void> {\n await appendRegularFile({ filePath, content: \"\", mode: 0o600 });\n}\n\nfunction toArtifactBuffer(content: unknown, mediaType: string): Buffer {\n if (typeof content === \"string\") {\n return Buffer.from(content, \"utf8\");\n }\n if (Buffer.isBuffer(content)) {\n return content;\n }\n if (content instanceof Uint8Array) {\n return Buffer.from(content);\n }\n if (mediaType === \"application/json\") {\n return Buffer.from(`${JSON.stringify(content, null, 2)}\\n`, \"utf8\");\n }\n return Buffer.from(String(content), \"utf8\");\n}\n\nfunction normalizeArtifactExtension(extension: string): string {\n if (!extension) {\n return \"\";\n }\n return extension.startsWith(\".\") ? extension : `.${extension}`;\n}\n\nfunction sessionDirPath(bundleId: string): string {\n return path.posix.join(SESSIONS_DIR, bundleId);\n}\n\nfunction isoNow(): string {\n return new Date().toISOString();\n}\n","import type { AcpClient } from \"../acp/client.js\";\nimport { InterruptedError, withInterrupt } from \"../async-control.js\";\nimport { promptToDisplayText } from \"../prompt-content.js\";\nimport {\n cloneSessionAcpxState,\n createSessionConversation,\n recordClientOperation as recordConversationClientOperation,\n recordPromptSubmission,\n recordSessionUpdate as recordConversationSessionUpdate,\n} from \"../session/conversation-model.js\";\nimport { resolveSessionRecord } from \"../session/persistence.js\";\nimport { createSessionWithClient, runOnce, sendSessionDirect } from \"../session/session.js\";\nimport type {\n AcpJsonRpcMessage,\n AcpMessageDirection,\n PromptInput,\n SessionRecord,\n} from \"../types.js\";\nimport { FlowAttempt } from \"./attempt.js\";\nimport { acp, action, checkpoint, compute, defineFlow, shell } from \"./definition.js\";\nimport {\n formatShellActionSummary,\n resolveShellActionTimeoutMs,\n runShellAction,\n runShellCommand,\n type RunShellActionOptions,\n type ShellProcessOwner,\n} from \"./executors/shell.js\";\nimport { resolveNext, validateFlowDefinition } from \"./graph.js\";\nimport {\n attachStepTrace,\n clearActiveNode,\n createIsolatedSessionBinding,\n createNodeOutcomePayload,\n createNodeResult,\n createQuietCaptureOutput,\n createRunId,\n createSessionBindingKey,\n createSessionBundleId,\n createSessionName,\n createSyntheticSessionRecord,\n extractAttachedStepTrace,\n finalizeStepTrace,\n findConversationDeltaStart,\n isoNow,\n makeFlowNodeContext,\n markNodeStarted,\n nextAttemptId,\n normalizePromptInput,\n outcomeForError,\n persistRunFailure,\n resolveFlowRunTitle,\n resolveNodeCwd,\n resolveShellActionCwd,\n summarizePrompt,\n updateStatusDetail,\n} from \"./runtime-support.js\";\nimport { FlowRunStore } from \"./store.js\";\nimport type {\n AcpNodeDefinition,\n CheckpointNodeDefinition,\n ComputeNodeDefinition,\n FunctionActionNodeDefinition,\n FlowDefinition,\n FlowNodeCommon,\n FlowNodeContext,\n FlowShellExecution,\n FlowShellResult,\n FlowNodeDefinition,\n FlowStepTrace,\n FlowArtifactRef,\n FlowRunResult,\n FlowRunState,\n FlowRunnerOptions,\n FlowSessionBinding,\n FlowNodeResult,\n FlowNodeOutcome,\n ResolvedFlowAgent,\n ShellActionExecution,\n ShellActionNodeDefinition,\n} from \"./types.js\";\n\nexport { acp, action, checkpoint, compute, defineFlow, shell };\nexport type {\n AcpNodeDefinition,\n ActionNodeDefinition,\n CheckpointNodeDefinition,\n ComputeNodeDefinition,\n FlowDefinition,\n FlowEdge,\n FlowNodeCommon,\n FlowNodeContext,\n FlowShellExecution,\n FlowShellResult,\n FlowNodeDefinition,\n FlowPermissionRequirements,\n FlowNodeOutcome,\n FlowNodeResult,\n FlowRunResult,\n FlowRunState,\n FlowRunnerOptions,\n FlowSessionBinding,\n FlowStepRecord,\n FunctionActionNodeDefinition,\n ResolvedFlowAgent,\n ShellActionExecution,\n ShellActionNodeDefinition,\n ShellActionResult,\n} from \"./types.js\";\n\nconst DEFAULT_FLOW_HEARTBEAT_MS = 5_000;\nconst DEFAULT_FLOW_STEP_TIMEOUT_MS = 15 * 60_000;\n\ntype FlowNodeExecutionResult = {\n output: unknown;\n promptText: string | null;\n rawText: string | null;\n sessionInfo: FlowSessionBinding | null;\n agentInfo: ResolvedFlowAgent | null;\n trace: FlowStepTrace | null;\n};\n\ntype FlowStepExecutionResult = FlowNodeExecutionResult & {\n attemptId: string;\n nodeResult: FlowNodeResult;\n nodeId: string;\n node: FlowNodeDefinition;\n startedAt: string;\n state: FlowRunState;\n executionError?: unknown;\n};\n\ntype TracedPromptResult = {\n rawText: string;\n sessionInfo: FlowSessionBinding;\n conversation?: FlowStepTrace[\"conversation\"];\n rawResponseArtifact: FlowArtifactRef;\n};\n\ntype PromptCaptureReceipt<T> = {\n outcome: PromiseSettledResult<T>;\n events?: { eventStartSeq: number; eventEndSeq: number };\n lastSeq: number;\n};\n\ntype PreparedAcpPrompt = {\n agentInfo: ResolvedFlowAgent;\n prompt: PromptInput;\n promptArtifact: FlowArtifactRef;\n attempt: FlowAttempt;\n result: FlowNodeExecutionResult;\n};\n\ntype FlowAttemptContext = {\n nodeContext: FlowNodeContext;\n attempt: FlowAttempt;\n acpResult?: FlowNodeExecutionResult;\n};\n\nfunction setNodeValue<T>(values: Record<string, T>, nodeId: string, value: T): void {\n // Define data properties so __proto__ is an ordinary node ID.\n Object.defineProperty(values, nodeId, {\n value,\n enumerable: true,\n configurable: true,\n writable: true,\n });\n}\n\nexport class FlowRunner {\n private readonly resolveAgent;\n private readonly defaultCwd;\n private readonly connectionOptions;\n private readonly defaultNodeTimeoutMs;\n private readonly suppressSdkConsoleErrors?;\n private readonly sessionOptions?;\n private readonly services;\n private readonly store;\n private readonly pendingPersistentSessionClients = new Map<string, Map<string, AcpClient>>();\n private readonly attempts = new Map<string, FlowAttempt>();\n private readonly pendingClientReleases = new WeakMap<AcpClient, () => void>();\n private readonly runInterruptions = new Map<string, InterruptedError>();\n private readonly shellOwners = new Map<string, Set<ShellProcessOwner>>();\n\n constructor(options: FlowRunnerOptions) {\n this.resolveAgent = options.resolveAgent;\n this.defaultCwd = options.resolveAgent(undefined).cwd;\n this.connectionOptions = {\n permissionMode: options.permissionMode,\n mcpServers: options.mcpServers,\n nonInteractivePermissions: options.nonInteractivePermissions,\n permissionPolicy: options.permissionPolicy,\n authCredentials: options.authCredentials,\n authPolicy: options.authPolicy,\n fs: options.fs,\n verbose: options.verbose,\n };\n this.defaultNodeTimeoutMs =\n options.defaultNodeTimeoutMs ?? options.timeoutMs ?? DEFAULT_FLOW_STEP_TIMEOUT_MS;\n this.suppressSdkConsoleErrors = options.suppressSdkConsoleErrors;\n this.sessionOptions = options.sessionOptions;\n this.services = options.services ?? {};\n this.store = new FlowRunStore(options.outputRoot);\n }\n\n async run(\n flow: FlowDefinition,\n input: unknown,\n options: { flowPath?: string } = {},\n ): Promise<FlowRunResult> {\n validateFlowDefinition(flow);\n\n const runId = createRunId(flow.name);\n const runTitle = await resolveFlowRunTitle(flow, input, options.flowPath);\n const runDir = await this.store.createRunDir(runId);\n const state: FlowRunState = {\n runId,\n flowName: flow.name,\n runTitle,\n flowPath: options.flowPath,\n startedAt: isoNow(),\n updatedAt: isoNow(),\n status: \"running\",\n input,\n outputs: {},\n results: {},\n steps: [],\n sessionBindings: {},\n };\n try {\n const inputArtifact = await this.store.writeArtifact(runDir, state, input, {\n mediaType: \"application/json\",\n extension: \"json\",\n emitTrace: false,\n });\n await this.store.initializeRunBundle(runDir, {\n flow,\n state,\n inputArtifact,\n });\n return await this.runWithOwnership(flow, input, runDir, state);\n } finally {\n try {\n await this.closePendingPersistentSessionClients(runDir);\n } finally {\n // Publication and client cleanup own these caches until both settle.\n // Release only this run; the runner can host concurrent executions.\n this.store.releaseRun(runDir);\n }\n }\n }\n\n private async runWithOwnership(\n flow: FlowDefinition,\n input: unknown,\n runDir: string,\n state: FlowRunState,\n ): Promise<FlowRunResult> {\n let execution: Promise<FlowRunResult> | undefined;\n let cancellation: Promise<void> | undefined;\n let interruption: InterruptedError | undefined;\n const result = await withInterrupt(\n () => {\n execution = this.executeFlowRun(flow, input, runDir, state);\n return execution;\n },\n async (signal) => {\n const reason = interruption ?? new InterruptedError();\n interruption = reason;\n this.runInterruptions.set(runDir, reason);\n cancellation ??= this.cancelShellOwners(runDir, signal);\n void cancellation.catch(() => {});\n this.attempts.get(runDir)?.cancel(reason, signal);\n await execution?.catch(() => {});\n },\n ).then(\n (value) => ({ ok: true as const, value }),\n (error: unknown) => ({ ok: false as const, error }),\n );\n try {\n try {\n await cancellation;\n } catch (cleanupError) {\n const failure =\n result.ok || result.error === cleanupError\n ? cleanupError\n : new AggregateError(\n [result.error, cleanupError],\n \"Shell cleanup failed during interruption\",\n { cause: cleanupError },\n );\n await persistRunFailure(this.store, runDir, state, failure);\n throw failure;\n }\n if (result.ok && !interruption) {\n return result.value;\n }\n const failure = result.ok ? interruption : result.error;\n if (interruption) {\n await persistRunFailure(this.store, runDir, state, failure);\n }\n throw failure;\n } finally {\n this.releaseShellOwners(runDir);\n }\n }\n\n private registerShellOwner(runDir: string, owner: ShellProcessOwner): () => void {\n let owners = this.shellOwners.get(runDir);\n if (!owners) {\n owners = new Set();\n this.shellOwners.set(runDir, owners);\n }\n owners.add(owner);\n const registered = owners;\n return () => {\n registered.delete(owner);\n if (registered.size === 0) {\n this.shellOwners.delete(runDir);\n }\n };\n }\n\n private async cancelShellOwners(runDir: string, signal: NodeJS.Signals): Promise<void> {\n const owners = [...(this.shellOwners.get(runDir) ?? [])];\n const results = await Promise.allSettled(owners.map((owner) => owner.cancel(signal)));\n const errors: unknown[] = [];\n for (const result of results) {\n if (result.status === \"rejected\") {\n errors.push(result.reason);\n }\n }\n if (errors.length > 0) {\n throw new AggregateError(errors, \"Shell process cleanup failed\", { cause: errors[0] });\n }\n }\n\n private releaseShellOwners(runDir: string): void {\n for (const owner of this.shellOwners.get(runDir) ?? []) {\n owner.release();\n }\n this.shellOwners.delete(runDir);\n }\n\n private async executeFlowRun(\n flow: FlowDefinition,\n input: unknown,\n runDir: string,\n state: FlowRunState,\n ): Promise<FlowRunResult> {\n let current: string | null = flow.startAt;\n const attemptCounts = new Map<string, number>();\n try {\n while (current !== null) {\n this.throwIfRunInterrupted(runDir);\n const step = await this.executeFlowStep(flow, input, runDir, state, current, attemptCounts);\n this.throwIfRunInterrupted(runDir, step.executionError);\n const waiting = await this.maybeCompleteCheckpointStep(runDir, state, step);\n if (waiting) {\n return waiting;\n }\n await this.recordFlowStepOutcome(runDir, state, step);\n current = this.resolveNextNode(flow, step);\n }\n return await this.completeFlowRun(runDir, state);\n } catch (error) {\n if (!this.runInterruptions.has(runDir)) {\n await persistRunFailure(this.store, runDir, state, error);\n }\n throw error;\n } finally {\n this.runInterruptions.delete(runDir);\n }\n }\n\n private throwIfRunInterrupted(runDir: string, error?: unknown): void {\n const interrupted = this.runInterruptions.get(runDir);\n if (interrupted) {\n throw error ?? interrupted;\n }\n }\n\n private async executeFlowStep(\n flow: FlowDefinition,\n input: unknown,\n runDir: string,\n state: FlowRunState,\n nodeId: string,\n attemptCounts: Map<string, number>,\n ): Promise<FlowStepExecutionResult> {\n if (!Object.hasOwn(flow.nodes, nodeId)) {\n throw new Error(`Unknown flow node: ${nodeId}`);\n }\n const node = flow.nodes[nodeId];\n const attemptId = nextAttemptId(attemptCounts, nodeId);\n const startedAt = isoNow();\n markNodeStarted(state, nodeId, attemptId, node.nodeType, startedAt, node.statusDetail);\n const attempt = new FlowAttempt({\n nodeId,\n attemptId,\n startedAt,\n timeoutMs: node.timeoutMs ?? this.defaultNodeTimeoutMs,\n });\n this.attempts.set(runDir, attempt);\n const context = this.makeAttemptContext(runDir, state, input, node, attempt);\n let stopHeartbeat = () => {};\n let executed: FlowNodeExecutionResult;\n let outcome: FlowNodeOutcome = \"ok\";\n let executionError: unknown;\n try {\n this.throwIfRunInterrupted(runDir);\n executed = await attempt.run(async () => {\n await attempt.own(() =>\n this.writeNodeStartedSnapshot(runDir, state, nodeId, attemptId, node),\n );\n stopHeartbeat = this.startHeartbeat(runDir, state, node, attempt);\n const result = await this.executeNode(runDir, state, flow, nodeId, node, context);\n result.trace = await attempt.own(() =>\n finalizeStepTrace(\n this.store,\n runDir,\n state,\n nodeId,\n attemptId,\n result.output,\n result.trace,\n ),\n );\n return result;\n });\n this.throwIfRunInterrupted(runDir);\n } catch (error) {\n outcome = outcomeForError(error);\n executionError = error;\n executed = {\n output: undefined,\n promptText: null,\n rawText: null,\n sessionInfo: null,\n agentInfo: null,\n ...context.acpResult,\n trace: await finalizeStepTrace(\n this.store,\n runDir,\n state,\n nodeId,\n attemptId,\n undefined,\n context.acpResult ? context.acpResult.trace : (extractAttachedStepTrace(error) ?? null),\n ),\n };\n } finally {\n stopHeartbeat();\n this.attempts.delete(runDir);\n }\n const nodeResult = createNodeResult({\n attemptId,\n nodeId,\n nodeType: node.nodeType,\n outcome,\n startedAt,\n finishedAt: isoNow(),\n ...(outcome === \"ok\"\n ? { output: executed.output }\n : {\n error:\n executionError instanceof Error ? executionError.message : String(executionError),\n }),\n });\n setNodeValue(state.results, nodeId, nodeResult);\n return { ...executed, nodeResult, executionError, attemptId, nodeId, node, startedAt, state };\n }\n\n private makeAttemptContext(\n runDir: string,\n state: FlowRunState,\n input: unknown,\n node: FlowNodeDefinition,\n attempt: FlowAttempt,\n ): FlowAttemptContext {\n const context: FlowAttemptContext = {\n nodeContext: { ...makeFlowNodeContext(state, input, this.services), signal: attempt.signal },\n attempt,\n };\n if (node.nodeType === \"action\" && \"run\" in node) {\n context.nodeContext.runShell = (execution) =>\n this.runCallbackShell(runDir, attempt, execution);\n }\n return context;\n }\n\n private async writeNodeStartedSnapshot(\n runDir: string,\n state: FlowRunState,\n nodeId: string,\n attemptId: string,\n node: FlowNodeDefinition,\n ): Promise<void> {\n await this.store.writeSnapshot(runDir, state, {\n scope: \"node\",\n type: \"node_started\",\n nodeId,\n attemptId,\n payload: {\n nodeType: node.nodeType,\n timeoutMs: node.timeoutMs ?? this.defaultNodeTimeoutMs,\n ...(state.statusDetail ? { statusDetail: state.statusDetail } : {}),\n },\n });\n }\n\n private async maybeCompleteCheckpointStep(\n runDir: string,\n state: FlowRunState,\n step: FlowStepExecutionResult,\n ): Promise<FlowRunResult | undefined> {\n if (step.nodeResult.outcome !== \"ok\" || step.node.nodeType !== \"checkpoint\") {\n return undefined;\n }\n setNodeValue(state.outputs, step.nodeId, step.output);\n state.waitingOn = step.nodeId;\n state.updatedAt = isoNow();\n state.status = \"waiting\";\n await this.recordFlowStepOutcome(runDir, state, step, {\n statusDetail: (step.output as { summary?: string } | null)?.summary ?? step.nodeId,\n });\n return { runDir, state };\n }\n\n private resolveNextNode(flow: FlowDefinition, step: FlowStepExecutionResult): string | null {\n if (step.nodeResult.outcome === \"ok\") {\n setNodeValue(step.state.outputs, step.nodeId, step.output);\n return resolveNext(flow.edges, step.nodeId, step.output, step.nodeResult);\n }\n const next = resolveNext(flow.edges, step.nodeId, undefined, step.nodeResult);\n if (next !== null) {\n return next;\n }\n throw step.executionError;\n }\n\n private async completeFlowRun(runDir: string, state: FlowRunState): Promise<FlowRunResult> {\n state.status = \"completed\";\n state.finishedAt = isoNow();\n state.updatedAt = state.finishedAt;\n clearActiveNode(state);\n await this.store.writeSnapshot(runDir, state, {\n scope: \"run\",\n type: \"run_completed\",\n payload: {\n status: state.status,\n },\n });\n return { runDir, state };\n }\n\n private async recordFlowStepOutcome(\n runDir: string,\n state: FlowRunState,\n step: FlowStepExecutionResult,\n overrides: {\n statusDetail?: string;\n } = {},\n ): Promise<void> {\n state.updatedAt = isoNow();\n clearActiveNode(state, overrides.statusDetail);\n state.steps.push({\n attemptId: step.attemptId,\n nodeId: step.nodeId,\n nodeType: step.node.nodeType,\n outcome: step.nodeResult.outcome,\n startedAt: step.startedAt,\n finishedAt: step.nodeResult.finishedAt,\n promptText: step.promptText,\n rawText: step.rawText,\n output: step.output,\n error: step.nodeResult.error,\n session: step.sessionInfo,\n agent: step.agentInfo,\n ...(step.trace ? { trace: step.trace } : {}),\n });\n await this.store.writeSnapshot(runDir, state, {\n scope: \"node\",\n type: \"node_outcome\",\n nodeId: step.nodeId,\n attemptId: step.attemptId,\n payload: createNodeOutcomePayload(step.nodeResult, step.trace),\n });\n }\n\n private async executeNode(\n runDir: string,\n state: FlowRunState,\n flow: FlowDefinition,\n nodeId: string,\n node: FlowNodeDefinition,\n context: FlowAttemptContext,\n ): Promise<FlowNodeExecutionResult> {\n switch (node.nodeType) {\n case \"compute\":\n return await this.executeCallbackNode(nodeId, node, context);\n case \"action\":\n return \"run\" in node\n ? await this.executeCallbackNode(nodeId, node, context)\n : await this.executeShellNode(runDir, state, node, context);\n case \"checkpoint\":\n return await this.executeCallbackNode(nodeId, node, context);\n case \"acp\":\n return await this.executeAcpNode(runDir, state, flow, node, context);\n default: {\n const exhaustive: never = node;\n throw new Error(`Unsupported flow node: ${String(exhaustive)}`);\n }\n }\n }\n\n private async executeCallbackNode(\n nodeId: string,\n node: ComputeNodeDefinition | FunctionActionNodeDefinition | CheckpointNodeDefinition,\n context: FlowAttemptContext,\n ): Promise<FlowNodeExecutionResult> {\n context.attempt.assertActive();\n const output =\n node.nodeType === \"checkpoint\" && typeof node.run !== \"function\"\n ? { checkpoint: nodeId, summary: node.summary ?? nodeId }\n : await node.run?.(context.nodeContext);\n context.attempt.assertActive();\n return {\n output,\n promptText: null,\n rawText: null,\n sessionInfo: null,\n agentInfo: null,\n trace: node.nodeType === \"action\" ? { action: { actionType: \"function\" } } : null,\n };\n }\n\n private async executeShellNode(\n runDir: string,\n state: FlowRunState,\n node: ShellActionNodeDefinition,\n context: FlowAttemptContext,\n ): Promise<FlowNodeExecutionResult> {\n const attempt = context.attempt;\n const execution = await node.exec(context.nodeContext);\n attempt.assertActive();\n const effectiveExecution: ShellActionExecution = {\n ...execution,\n cwd: resolveShellActionCwd(this.defaultCwd, execution.cwd),\n timeoutMs: resolveShellActionTimeoutMs(execution.timeoutMs ?? attempt.remainingTimeoutMs()),\n };\n updateStatusDetail(state, formatShellActionSummary(effectiveExecution));\n await attempt.own(() =>\n this.store.writeLive(runDir, state, {\n scope: \"node\",\n type: \"node_heartbeat\",\n nodeId: attempt.nodeId,\n attemptId: attempt.attemptId,\n payload: { statusDetail: state.statusDetail },\n }),\n );\n await attempt.own(() =>\n this.store.appendTrace(runDir, state, {\n scope: \"action\",\n type: \"action_prepared\",\n nodeId: attempt.nodeId,\n attemptId: attempt.attemptId,\n payload: {\n action: {\n actionType: \"shell\",\n command: effectiveExecution.command,\n args: effectiveExecution.args ?? [],\n cwd: effectiveExecution.cwd,\n },\n },\n }),\n );\n const result = await attempt.own(() =>\n runShellAction(effectiveExecution, this.shellControl(runDir, attempt)),\n );\n const stdoutArtifact = await attempt.own(() =>\n this.store.writeArtifact(runDir, state, result.stdout, {\n mediaType: \"text/plain\",\n extension: \"txt\",\n nodeId: attempt.nodeId,\n attemptId: attempt.attemptId,\n }),\n );\n const stderrArtifact = await attempt.own(() =>\n this.store.writeArtifact(runDir, state, result.stderr, {\n mediaType: \"text/plain\",\n extension: \"txt\",\n nodeId: attempt.nodeId,\n attemptId: attempt.attemptId,\n }),\n );\n const actionTrace = {\n actionType: \"shell\" as const,\n command: result.command,\n args: result.args,\n cwd: result.cwd,\n exitCode: result.exitCode,\n signal: result.signal,\n durationMs: result.durationMs,\n };\n await attempt.own(() =>\n this.store.appendTrace(runDir, state, {\n scope: \"action\",\n type: \"action_completed\",\n nodeId: attempt.nodeId,\n attemptId: attempt.attemptId,\n payload: { action: actionTrace, stdoutArtifact, stderrArtifact },\n }),\n );\n const trace: FlowStepTrace = { action: actionTrace, stdoutArtifact, stderrArtifact };\n let output: unknown;\n try {\n output = node.parse ? await node.parse(result, context.nodeContext) : result;\n attempt.assertActive();\n } catch (error) {\n throw attachStepTrace(error, trace);\n }\n return {\n output,\n promptText: null,\n rawText: result.combinedOutput,\n sessionInfo: null,\n agentInfo: null,\n trace,\n };\n }\n\n private shellControl(runDir: string, attempt: FlowAttempt): RunShellActionOptions {\n return {\n signal: attempt.signal,\n get terminationSignal() {\n return attempt.terminationSignal;\n },\n registerOwner: (owner) => {\n const releaseAttempt = attempt.registerCancellation((signal) => owner.cancel(signal));\n const releaseRun = this.registerShellOwner(runDir, owner);\n return () => {\n releaseAttempt();\n releaseRun();\n };\n },\n };\n }\n\n private runCallbackShell(\n runDir: string,\n attempt: FlowAttempt,\n execution: FlowShellExecution,\n ): Promise<FlowShellResult> {\n return attempt.own(() =>\n runShellCommand(\n {\n ...execution,\n cwd: resolveShellActionCwd(this.defaultCwd, execution.cwd),\n },\n this.shellControl(runDir, attempt),\n ),\n );\n }\n\n private async executeAcpNode(\n runDir: string,\n state: FlowRunState,\n flow: FlowDefinition,\n node: AcpNodeDefinition,\n context: FlowAttemptContext,\n ): Promise<FlowNodeExecutionResult> {\n const attempt = context.attempt;\n const prepared = await this.prepareAcpPrompt(runDir, state, node, context);\n if (node.session?.isolated) {\n return await this.executeIsolatedAcpPrompt(runDir, state, flow, node, context, prepared);\n }\n const boundSession = await this.ensureSessionBinding(\n runDir,\n state,\n flow,\n node,\n prepared.agentInfo,\n attempt,\n );\n return await this.executePersistentAcpPrompt(\n runDir,\n state,\n node,\n context,\n prepared,\n boundSession,\n );\n }\n\n private async prepareAcpPrompt(\n runDir: string,\n state: FlowRunState,\n node: AcpNodeDefinition,\n context: FlowAttemptContext,\n ): Promise<PreparedAcpPrompt> {\n const resolvedAgent = this.resolveAgent(node.profile);\n const agentInfo = {\n ...resolvedAgent,\n agentArgv: resolvedAgent.agentArgv?.slice(),\n cwd: await resolveNodeCwd(resolvedAgent.cwd, node.cwd, context.nodeContext),\n };\n context.attempt.assertActive();\n const prompt = normalizePromptInput(await Promise.resolve(node.prompt(context.nodeContext)));\n context.attempt.assertActive();\n const promptText = promptToDisplayText(prompt);\n const result: FlowNodeExecutionResult = {\n output: undefined,\n promptText,\n rawText: null,\n sessionInfo: null,\n agentInfo,\n trace: null,\n };\n context.acpResult = result;\n updateStatusDetail(state, summarizePrompt(promptText, node.statusDetail));\n await context.attempt.own(() => this.writeAcpPromptHeartbeat(runDir, state, context.attempt));\n const promptArtifact = await context.attempt.own(() =>\n this.store.writeArtifact(runDir, state, promptText, {\n mediaType: \"text/plain\",\n extension: \"txt\",\n nodeId: context.attempt.nodeId,\n attemptId: context.attempt.attemptId,\n }),\n );\n result.trace = { promptArtifact };\n return {\n agentInfo,\n prompt,\n promptArtifact,\n attempt: context.attempt,\n result,\n };\n }\n\n private async writeAcpPromptHeartbeat(\n runDir: string,\n state: FlowRunState,\n attempt: FlowAttempt,\n ): Promise<void> {\n await this.store.writeLive(runDir, state, {\n scope: \"node\",\n type: \"node_heartbeat\",\n nodeId: attempt.nodeId,\n attemptId: attempt.attemptId,\n payload: {\n statusDetail: state.statusDetail,\n },\n });\n }\n\n private async executeIsolatedAcpPrompt(\n runDir: string,\n state: FlowRunState,\n flow: FlowDefinition,\n node: AcpNodeDefinition,\n context: FlowAttemptContext,\n prepared: PreparedAcpPrompt,\n ): Promise<FlowNodeExecutionResult> {\n const binding = createIsolatedSessionBinding(\n flow.name,\n state.runId,\n prepared.attempt.attemptId,\n node.profile,\n prepared.agentInfo,\n );\n prepared.result.sessionInfo = binding;\n await prepared.attempt.own(() =>\n this.initializeIsolatedSessionBundle(runDir, state, binding, prepared.attempt),\n );\n await prepared.attempt.own(() =>\n this.appendAcpPromptPreparedTrace(\n runDir,\n state,\n binding,\n prepared.promptArtifact,\n prepared.attempt,\n ),\n );\n const prompt = await prepared.attempt.own(() =>\n this.runIsolatedPrompt(runDir, state, binding, prepared),\n );\n return await this.finishAcpPrompt(runDir, state, node, context, prepared, prompt);\n }\n\n private async initializeIsolatedSessionBundle(\n runDir: string,\n state: FlowRunState,\n binding: FlowSessionBinding,\n attempt: FlowAttempt,\n ): Promise<void> {\n const timestamp = attempt.startedAt;\n const initialRecord = createSyntheticSessionRecord({\n binding,\n createdAt: timestamp,\n updatedAt: timestamp,\n conversation: createSessionConversation(timestamp),\n acpxState: undefined,\n lastSeq: 0,\n });\n await this.store.ensureSessionBundle(runDir, state, binding, initialRecord);\n }\n\n private async executePersistentAcpPrompt(\n runDir: string,\n state: FlowRunState,\n node: AcpNodeDefinition,\n context: FlowAttemptContext,\n prepared: PreparedAcpPrompt,\n binding: FlowSessionBinding,\n ): Promise<FlowNodeExecutionResult> {\n prepared.result.sessionInfo = binding;\n await prepared.attempt.own(() =>\n this.appendAcpPromptPreparedTrace(\n runDir,\n state,\n binding,\n prepared.promptArtifact,\n prepared.attempt,\n ),\n );\n const prompt = await prepared.attempt.own(() =>\n this.runPersistentPrompt(runDir, state, binding, prepared),\n );\n return await this.finishAcpPrompt(runDir, state, node, context, prepared, prompt);\n }\n\n private async appendAcpPromptPreparedTrace(\n runDir: string,\n state: FlowRunState,\n binding: FlowSessionBinding,\n promptArtifact: FlowArtifactRef,\n attempt: FlowAttempt,\n ): Promise<void> {\n await this.store.appendTrace(runDir, state, {\n scope: \"acp\",\n type: \"acp_prompt_prepared\",\n nodeId: attempt.nodeId,\n attemptId: attempt.attemptId,\n sessionId: binding.bundleId,\n payload: {\n sessionId: binding.bundleId,\n promptArtifact,\n },\n });\n }\n\n private async finishAcpPrompt(\n runDir: string,\n state: FlowRunState,\n node: AcpNodeDefinition,\n context: FlowAttemptContext,\n prepared: PreparedAcpPrompt,\n prompt: TracedPromptResult,\n ): Promise<FlowNodeExecutionResult> {\n await prepared.attempt.own(() =>\n this.appendAcpResponseParsedTrace(runDir, state, prompt, prepared.attempt),\n );\n const output = await this.parseAcpOutput(node, context, prompt.rawText);\n return { ...prepared.result, output };\n }\n\n private async publishAcpCapture(\n runDir: string,\n state: FlowRunState,\n prepared: PreparedAcpPrompt,\n sessionInfo: FlowSessionBinding,\n record: SessionRecord,\n messageStart: number,\n rawText: string,\n events: PromptCaptureReceipt<unknown>[\"events\"],\n ): Promise<TracedPromptResult> {\n const result = prepared.result;\n result.sessionInfo = sessionInfo;\n const trace: FlowStepTrace = {\n sessionId: sessionInfo.bundleId,\n promptArtifact: prepared.promptArtifact,\n };\n result.trace = trace;\n // This finalization belongs to the admitted prompt, including after abort.\n await this.store.ensureSessionBundle(runDir, state, sessionInfo);\n await this.store.writeSessionRecord(runDir, state, sessionInfo, record);\n if (events) {\n trace.conversation = {\n sessionId: sessionInfo.bundleId,\n messageStart,\n messageEnd: Math.max(messageStart, record.messages.length - 1),\n ...events,\n };\n }\n const rawResponseArtifact = await this.store.writeArtifact(runDir, state, rawText, {\n mediaType: \"text/plain\",\n extension: \"txt\",\n nodeId: prepared.attempt.nodeId,\n attemptId: prepared.attempt.attemptId,\n sessionId: sessionInfo.bundleId,\n });\n trace.rawResponseArtifact = rawResponseArtifact;\n return { rawText, sessionInfo, conversation: trace.conversation, rawResponseArtifact };\n }\n\n private async appendAcpResponseParsedTrace(\n runDir: string,\n state: FlowRunState,\n prompt: TracedPromptResult,\n attempt: FlowAttempt,\n ): Promise<void> {\n await this.store.appendTrace(runDir, state, {\n scope: \"acp\",\n type: \"acp_response_parsed\",\n nodeId: attempt.nodeId,\n attemptId: attempt.attemptId,\n sessionId: prompt.sessionInfo.bundleId,\n payload: {\n sessionId: prompt.sessionInfo.bundleId,\n conversation: prompt.conversation,\n rawResponseArtifact: prompt.rawResponseArtifact,\n },\n });\n }\n\n private async parseAcpOutput(\n node: AcpNodeDefinition,\n context: FlowAttemptContext,\n rawText: string,\n ): Promise<unknown> {\n context.attempt.assertActive();\n const output = node.parse ? await node.parse(rawText, context.nodeContext) : rawText;\n context.attempt.assertActive();\n return output;\n }\n\n private startHeartbeat(\n runDir: string,\n state: FlowRunState,\n node: FlowNodeCommon,\n attempt: FlowAttempt,\n ): () => void {\n const heartbeatMs = Math.max(0, Math.round(node.heartbeatMs ?? DEFAULT_FLOW_HEARTBEAT_MS));\n if (heartbeatMs === 0) {\n return () => {};\n }\n let pending = false;\n const heartbeat = async () => {\n if (!attempt.active || pending) {\n return;\n }\n pending = true;\n try {\n await attempt.own(\n async () => {\n state.lastHeartbeatAt = isoNow();\n state.updatedAt = state.lastHeartbeatAt;\n await this.store.writeLive(runDir, state, {\n scope: \"node\",\n type: \"node_heartbeat\",\n nodeId: attempt.nodeId,\n attemptId: attempt.attemptId,\n payload: { statusDetail: state.statusDetail },\n });\n },\n { bestEffort: true },\n );\n } catch {\n /* Heartbeats remain best-effort, including retirement at the deadline. */\n } finally {\n pending = false;\n }\n };\n const timer = setInterval(() => {\n void heartbeat();\n }, heartbeatMs);\n return () => clearInterval(timer);\n }\n\n private async ensureSessionBinding(\n runDir: string,\n state: FlowRunState,\n flow: FlowDefinition,\n node: AcpNodeDefinition,\n agent: ResolvedFlowAgent,\n attempt: FlowAttempt,\n ): Promise<FlowSessionBinding> {\n const handle = node.session?.handle ?? \"main\";\n const key = createSessionBindingKey(agent.agentCommand, agent.cwd, handle, agent.agentArgv);\n const existing = state.sessionBindings[key];\n if (existing) {\n await attempt.own(() => this.store.ensureSessionBundle(runDir, state, existing));\n return existing;\n }\n\n const name = createSessionName(flow.name, handle, agent.cwd, state.runId);\n const created = await attempt.own(async () => {\n const acquired = await createSessionWithClient({\n agentCommand: agent.agentCommand,\n agentArgv: agent.agentArgv,\n cwd: agent.cwd,\n name,\n ...this.connectionOptions,\n signal: attempt.signal,\n handleProcessInterrupts: false,\n sessionOptions: this.sessionOptions,\n });\n this.pendingClientReleases.set(\n acquired.client,\n attempt.registerCancellation(async () => {\n const clients = this.pendingPersistentSessionClients.get(runDir);\n if (clients?.get(key) === acquired.client) {\n clients.delete(key);\n }\n await acquired.client.close();\n }),\n );\n return acquired;\n });\n attempt.assertActive();\n\n const binding: FlowSessionBinding = {\n key,\n handle,\n bundleId: createSessionBundleId(handle, key),\n name,\n profile: node.profile,\n agentName: agent.agentName,\n agentCommand: agent.agentCommand,\n agentArgv: agent.agentArgv,\n cwd: agent.cwd,\n acpxRecordId: created.record.acpxRecordId,\n acpSessionId: created.record.acpSessionId,\n agentSessionId: created.record.agentSessionId,\n };\n state.sessionBindings[key] = binding;\n let clients = this.pendingPersistentSessionClients.get(runDir);\n if (!clients) {\n clients = new Map();\n this.pendingPersistentSessionClients.set(runDir, clients);\n }\n clients.set(binding.key, created.client);\n await attempt.own(() => this.store.ensureSessionBundle(runDir, state, binding, created.record));\n return binding;\n }\n\n private createPromptEventCapture(runDir: string, binding: FlowSessionBinding) {\n const pending = new Set<Promise<void>>();\n let ordinal = 0;\n let failure: { ordinal: number; reason: unknown } | undefined;\n let eventStartSeq: number | undefined;\n let eventEndSeq = 0;\n const snapshot = <T>(outcome: PromiseSettledResult<T>): PromptCaptureReceipt<T> => ({\n outcome,\n events: !failure && eventStartSeq !== undefined ? { eventStartSeq, eventEndSeq } : undefined,\n lastSeq: eventEndSeq,\n });\n return {\n onAcpMessage: (direction: AcpMessageDirection, message: AcpJsonRpcMessage): void => {\n const index = ordinal++;\n const write = this.store\n .appendSessionEvent(runDir, binding, direction, message)\n .then(\n (seq) => {\n eventStartSeq = Math.min(eventStartSeq ?? seq, seq);\n eventEndSeq = Math.max(eventEndSeq, seq);\n },\n (reason: unknown) => {\n if (!failure || index < failure.ordinal) {\n failure = { ordinal: index, reason };\n }\n },\n )\n .finally(() => pending.delete(write));\n // Only unfinished I/O owns a promise; long prompts must not retain every\n // settled write. Error precedence still follows event admission order.\n pending.add(write);\n },\n async run<T, F>(\n operation: () => Promise<T>,\n finalize: (receipt: PromptCaptureReceipt<T>) => Promise<F>,\n ): Promise<F> {\n let result: PromiseSettledResult<T>;\n try {\n result = { status: \"fulfilled\", value: await operation() };\n } catch (reason) {\n result = { status: \"rejected\", reason };\n }\n // The enclosing attempt still owns this drain, including its deadline and interrupts.\n await Promise.all(pending);\n let finalized: PromiseSettledResult<F>;\n try {\n finalized = {\n status: \"fulfilled\",\n value: await finalize(snapshot(result)),\n };\n } catch (reason) {\n finalized = { status: \"rejected\", reason };\n }\n if (result.status === \"rejected\") {\n throw result.reason;\n }\n if (failure) {\n throw failure.reason;\n }\n if (eventStartSeq === undefined) {\n throw new Error(`Missing ACP event capture for session ${binding.bundleId}`);\n }\n if (finalized.status === \"rejected\") {\n throw finalized.reason;\n }\n return finalized.value;\n },\n };\n }\n\n private async runPersistentPrompt(\n runDir: string,\n state: FlowRunState,\n binding: FlowSessionBinding,\n prepared: PreparedAcpPrompt,\n ): Promise<TracedPromptResult> {\n const { attempt, prompt } = prepared;\n const capture = createQuietCaptureOutput();\n const beforeRecord = await resolveSessionRecord(binding.acpxRecordId);\n attempt.assertActive();\n const events = this.createPromptEventCapture(runDir, binding);\n const clients = this.pendingPersistentSessionClients.get(runDir);\n const initialClient = clients?.get(binding.key);\n if (initialClient) {\n clients?.delete(binding.key);\n this.pendingClientReleases.get(initialClient)?.();\n this.pendingClientReleases.delete(initialClient);\n }\n\n return await events.run(\n () =>\n sendSessionDirect(\n {\n sessionId: binding.acpxRecordId,\n prompt,\n resumePolicy: \"same-session-only\",\n ...this.connectionOptions,\n outputFormatter: capture.formatter,\n errorEmissionPolicy: { queueErrorAlreadyEmitted: false },\n onAcpMessage: events.onAcpMessage,\n suppressSdkConsoleErrors: this.suppressSdkConsoleErrors,\n client: initialClient,\n },\n { signal: attempt.signal, handleProcessInterrupts: false },\n ),\n async (receipt) => {\n const rawText = capture.read();\n prepared.result.rawText = rawText;\n const afterRecord = await resolveSessionRecord(binding.acpxRecordId);\n const sessionInfo = {\n ...binding,\n acpSessionId: afterRecord.acpSessionId,\n agentSessionId: afterRecord.agentSessionId,\n };\n state.sessionBindings[sessionInfo.key] = sessionInfo;\n return await this.publishAcpCapture(\n runDir,\n state,\n prepared,\n sessionInfo,\n afterRecord,\n findConversationDeltaStart(beforeRecord.messages, afterRecord.messages),\n rawText,\n receipt.events,\n );\n },\n );\n }\n\n private async closePendingPersistentSessionClients(runDir: string): Promise<void> {\n const pendingClients = [...(this.pendingPersistentSessionClients.get(runDir)?.values() ?? [])];\n this.pendingPersistentSessionClients.delete(runDir);\n const closed = await Promise.allSettled(\n pendingClients.map(async (client) => {\n this.pendingClientReleases.get(client)?.();\n this.pendingClientReleases.delete(client);\n await client.close();\n }),\n );\n const failure = closed.find((result) => result.status === \"rejected\");\n if (failure?.status === \"rejected\") {\n throw failure.reason;\n }\n }\n\n private async runIsolatedPrompt(\n runDir: string,\n state: FlowRunState,\n binding: FlowSessionBinding,\n prepared: PreparedAcpPrompt,\n ): Promise<TracedPromptResult> {\n const { agentInfo: agent, prompt, attempt } = prepared;\n const capture = createQuietCaptureOutput();\n const conversation = createSessionConversation(attempt.startedAt);\n let acpxState: SessionRecord[\"acpx\"] | undefined;\n recordPromptSubmission(conversation, prompt, attempt.startedAt);\n const events = this.createPromptEventCapture(runDir, binding);\n return await events.run(\n () =>\n runOnce(\n {\n agentCommand: agent.agentCommand,\n agentArgv: agent.agentArgv,\n cwd: agent.cwd,\n prompt,\n ...this.connectionOptions,\n outputFormatter: capture.formatter,\n errorEmissionPolicy: { queueErrorAlreadyEmitted: false },\n onAcpMessage: events.onAcpMessage,\n onSessionUpdate: (notification) => {\n acpxState = recordConversationSessionUpdate(conversation, acpxState, notification);\n },\n onClientOperation: (operation) => {\n acpxState = recordConversationClientOperation(conversation, acpxState, operation);\n },\n suppressSdkConsoleErrors: this.suppressSdkConsoleErrors,\n sessionOptions: this.sessionOptions,\n },\n { signal: attempt.signal, handleProcessInterrupts: false },\n ),\n async (receipt) => {\n const rawText = capture.read();\n prepared.result.rawText = rawText;\n const sessionId =\n receipt.outcome.status === \"fulfilled\"\n ? receipt.outcome.value.sessionId\n : capture.sessionId();\n const sessionInfo =\n sessionId === undefined\n ? binding\n : { ...binding, acpxRecordId: sessionId, acpSessionId: sessionId };\n const record = createSyntheticSessionRecord({\n binding: sessionInfo,\n createdAt: attempt.startedAt,\n updatedAt: conversation.updated_at,\n conversation,\n acpxState: cloneSessionAcpxState(acpxState),\n lastSeq: receipt.lastSeq,\n });\n return await this.publishAcpCapture(\n runDir,\n state,\n prepared,\n sessionInfo,\n record,\n 0,\n rawText,\n receipt.events,\n );\n },\n );\n }\n}\n","export type JsonObjectParseMode = \"strict\" | \"fenced\" | \"compat\";\n\nfunction normalizeJsonText(text: unknown): string {\n if (typeof text === \"string\") {\n return text.trim();\n }\n if (text == null) {\n return \"\";\n }\n if (\n typeof text === \"number\" ||\n typeof text === \"boolean\" ||\n typeof text === \"bigint\" ||\n typeof text === \"symbol\"\n ) {\n return String(text).trim();\n }\n return \"\";\n}\n\n// The generic entrypoint when a workflow wants to choose its tolerance level\n// explicitly. Most callers should still use one of the small helpers below.\nexport function parseJsonObject(\n text: string,\n options: {\n mode?: JsonObjectParseMode;\n } = {},\n): unknown {\n const trimmed = normalizeJsonText(text);\n if (!trimmed) {\n throw new Error(\"Expected JSON output, got empty text\");\n }\n const mode = options.mode ?? \"compat\";\n\n const direct = tryParse(trimmed);\n if (direct.ok) {\n return direct.value;\n }\n\n const fenced = parseFencedJsonIfAllowed(trimmed, mode);\n if (fenced.ok) {\n return fenced.value;\n }\n\n if (mode === \"compat\") {\n const balanced = parseBalancedJsonCandidate(trimmed);\n if (balanced.ok) {\n return balanced.value;\n }\n }\n\n throw new Error(`Could not parse JSON from assistant output:\\n${trimmed}`);\n}\n\nfunction parseFencedJsonIfAllowed(\n text: string,\n mode: JsonObjectParseMode,\n): { ok: true; value: unknown } | { ok: false } {\n if (mode !== \"fenced\" && mode !== \"compat\") {\n return { ok: false };\n }\n const fencedText = extractFencedJsonText(text);\n return fencedText === null ? { ok: false } : tryParse(fencedText);\n}\n\nconst COMPAT_JSON_WORK_MULTIPLIER = 8;\n\ntype JsonRecoveryBudget = { remaining: number };\n\nfunction consumeRecoveryWork(budget: JsonRecoveryBudget, units: number): boolean {\n if (units > budget.remaining) {\n budget.remaining = 0;\n return false;\n }\n budget.remaining -= units;\n return true;\n}\n\nfunction parseBalancedJsonCandidate(text: string): { ok: true; value: unknown } | { ok: false } {\n const budget = { remaining: text.length * COMPAT_JSON_WORK_MULTIPLIER };\n for (let index = 0; index < text.length && budget.remaining > 0; index += 1) {\n if (text[index] !== \"{\" && text[index] !== \"[\") {\n continue;\n }\n const end = scanBalanced(text, index, budget);\n if (end === null) {\n continue;\n }\n // Reserve parsing work before allocating a slice, including failed parses.\n if (!consumeRecoveryWork(budget, end - index)) {\n return { ok: false };\n }\n const parsed = tryParse(text.slice(index, end));\n if (parsed.ok) {\n return parsed;\n }\n }\n return { ok: false };\n}\n\n// Use this when the model contract must be exact JSON and any extra text\n// should fail the step immediately.\nexport function parseStrictJsonObject(text: string): unknown {\n return parseJsonObject(text, { mode: \"strict\" });\n}\n\n// Default workflow parser: direct JSON first, fenced JSON second, and finally\n// a balanced embedded object for compatibility with chatty model output.\nexport function extractJsonObject(text: string): unknown {\n return parseJsonObject(text, { mode: \"compat\" });\n}\n\nfunction tryParse(text: string): { ok: true; value: unknown } | { ok: false } {\n try {\n return {\n ok: true,\n value: JSON.parse(text),\n };\n } catch {\n return {\n ok: false,\n };\n }\n}\n\nfunction extractFencedJsonText(text: string): string | null {\n const openingFenceIndex = text.indexOf(\"```\");\n if (openingFenceIndex === -1) {\n return null;\n }\n\n let contentStart = openingFenceIndex + 3;\n if (\n text.slice(contentStart, contentStart + 4).toLowerCase() === \"json\" &&\n isFenceWhitespace(text[contentStart + 4])\n ) {\n contentStart += 4;\n }\n\n while (isFenceWhitespace(text[contentStart])) {\n contentStart += 1;\n }\n\n const closingFenceIndex = text.indexOf(\"```\", contentStart);\n if (closingFenceIndex === -1) {\n return null;\n }\n\n return text.slice(contentStart, closingFenceIndex).trim();\n}\n\nfunction isFenceWhitespace(char: string | undefined): boolean {\n return char === \" \" || char === \"\\n\" || char === \"\\r\" || char === \"\\t\";\n}\n\nfunction scanBalanced(text: string, startIndex: number, budget: JsonRecoveryBudget): number | null {\n const stack: string[] = [];\n let inString = false;\n let escaped = false;\n\n for (let index = startIndex; index < text.length; index += 1) {\n if (!consumeRecoveryWork(budget, 1)) {\n return null;\n }\n const char = text[index];\n\n if (inString) {\n const next = scanStringChar(char, escaped);\n escaped = next.escaped;\n inString = next.inString;\n continue;\n }\n\n if (char === '\"') {\n inString = true;\n continue;\n }\n\n const result = scanBalancedToken(index, char, stack);\n if (result !== SCAN_CONTINUE) {\n return result;\n }\n }\n\n return null;\n}\n\nconst SCAN_CONTINUE = Symbol(\"scan-continue\");\n\nfunction scanBalancedToken(\n index: number,\n char: string,\n stack: string[],\n): number | null | typeof SCAN_CONTINUE {\n if (char === \"{\" || char === \"[\") {\n stack.push(char);\n return SCAN_CONTINUE;\n }\n\n if (char !== \"}\" && char !== \"]\") {\n return SCAN_CONTINUE;\n }\n\n if (!balancedClosingTokenMatches(stack.at(-1), char)) {\n return null;\n }\n\n stack.pop();\n return stack.length === 0 ? index + 1 : SCAN_CONTINUE;\n}\n\nfunction balancedClosingTokenMatches(open: string | undefined, close: string): boolean {\n if (open === \"{\") {\n return close === \"}\";\n }\n if (open === \"[\") {\n return close === \"]\";\n }\n return false;\n}\n\nfunction scanStringChar(char: string, escaped: boolean): { escaped: boolean; inString: boolean } {\n if (escaped) {\n return { escaped: false, inString: true };\n }\n if (char === \"\\\\\") {\n return { escaped: true, inString: true };\n }\n return { escaped: false, inString: char !== '\"' };\n}\n","import { acp } from \"./definition.js\";\nimport { extractJsonObject } from \"./json.js\";\nimport type { AcpNodeDefinition, FlowEdge, FlowNodeContext } from \"./types.js\";\n\nconst DEFAULT_FIELD = \"route\";\nconst SIMPLE_FIELD_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/;\n\n// All `acp` node fields except the ones the decision helper owns.\ntype DecisionAcpOptions = Omit<AcpNodeDefinition, \"nodeType\" | \"prompt\" | \"parse\">;\n\nexport type DecisionDefinition<TChoice extends string> = DecisionAcpOptions & {\n question: string | ((context: FlowNodeContext) => string | Promise<string>);\n choices: readonly TChoice[];\n field?: string;\n};\n\n// Build an `acp` node that asks the model to pick one of `choices` and reply\n// with a JSON object whose chosen field is validated. Pair with `decisionEdge`\n// (or any `switch` edge keyed on `$.<field>`) to route on the result.\nexport function decision<TChoice extends string>(\n definition: DecisionDefinition<TChoice>,\n): AcpNodeDefinition {\n const { question, choices, field: fieldOverride, ...acpOptions } = definition;\n const field = normalizeField(fieldOverride);\n assertValidChoices(choices);\n const allowed = new Set<string>(choices);\n\n return acp({\n ...acpOptions,\n async prompt(context) {\n const text = typeof question === \"function\" ? await question(context) : question;\n return formatDecisionPrompt(text, choices, field);\n },\n parse(text) {\n const raw = extractJsonObject(text);\n if (raw === null || typeof raw !== \"object\" || Array.isArray(raw)) {\n throw new Error(`Decision response must be a JSON object, got ${typeof raw}`);\n }\n const value = (raw as Record<string, unknown>)[field];\n if (typeof value !== \"string\" || !allowed.has(value)) {\n const allowedLabels = choices.map((choice) => JSON.stringify(choice)).join(\", \");\n throw new Error(\n `Decision returned invalid ${field}=${JSON.stringify(value)}; expected one of ${allowedLabels}`,\n );\n }\n return raw;\n },\n });\n}\n\n// Build the matching `switch` edge for a `decision` node. Typing `cases` as\n// `Record<TChoice, string>` makes a missing case a compile error.\nexport function decisionEdge<TChoice extends string>(args: {\n from: string;\n choices: readonly TChoice[];\n field?: string;\n cases: Record<TChoice, string>;\n}): FlowEdge {\n const field = normalizeField(args.field);\n assertValidChoices(args.choices);\n for (const choice of args.choices) {\n if (!Object.hasOwn(args.cases, choice)) {\n throw new Error(`Decision edge is missing case for choice ${JSON.stringify(choice)}`);\n }\n }\n return {\n from: args.from,\n switch: {\n on: `$.${field}`,\n cases: args.cases,\n },\n };\n}\n\nfunction assertValidChoices(choices: readonly string[]): void {\n if (choices.length === 0) {\n throw new Error(\"Decision choices must include at least one value\");\n }\n const seen = new Set<string>();\n for (const choice of choices) {\n if (typeof choice !== \"string\" || choice.length === 0) {\n throw new Error(\"Decision choices must be non-empty strings\");\n }\n if (seen.has(choice)) {\n throw new Error(`Decision choices must be unique; duplicate ${JSON.stringify(choice)}`);\n }\n seen.add(choice);\n }\n}\n\nfunction normalizeField(fieldOverride: string | undefined): string {\n const field = fieldOverride ?? DEFAULT_FIELD;\n if (!SIMPLE_FIELD_PATTERN.test(field)) {\n throw new Error(\n `Decision field must be a simple JSON key matching ${SIMPLE_FIELD_PATTERN.source}`,\n );\n }\n return field;\n}\n\nfunction formatDecisionPrompt(question: string, choices: readonly string[], field: string): string {\n const allowed = choices.map((choice) => JSON.stringify(choice)).join(\" | \");\n return [\n question,\n \"\",\n \"Return exactly one JSON object with this shape:\",\n \"{\",\n ` ${JSON.stringify(field)}: ${allowed},`,\n ' \"reason\": \"short justification\"',\n \"}\",\n \"\",\n \"Do not include any other text outside the JSON object.\",\n ].join(\"\\n\");\n}\n"],"mappings":";;;;;;;;;;;;;;;AAMA,IAAa,cAAb,MAAyB;CACvB;CACA;CACA;CACA;CACA,oBAAoC;CAEpC,aAA8B,IAAI,gBAAgB;CAClD,0BAA2B,IAAI,IAA2B;CAC1D,gCAAiC,IAAI,IAA+C;CACpF,kBAA8C,CAAC;CAC/C;CACA;CACA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mBAAmB,KAAK,OAAO;CAC/B,KAAK,MAAM,UAAU,KAAK,SACxB,IAAI,CAAC,OAAO,OAAO,KAAK,OAAO,MAAM,GACnC,MAAM,IAAI,MAAM,4CAA4C,KAAK,UAAU,MAAM,GAAG;CAGxF,OAAO;EACL,MAAM,KAAK;EACX,QAAQ;GACN,IAAI,KAAK;GACT,OAAO,KAAK;EACd;CACF;AACF;AAEA,SAAS,mBAAmB,SAAkC;CAC5D,IAAI,QAAQ,WAAW,GACrB,MAAM,IAAI,MAAM,kDAAkD;CAEpE,MAAM,uBAAO,IAAI,IAAY;CAC7B,KAAK,MAAM,UAAU,SAAS;EAC5B,IAAI,OAAO,WAAW,YAAY,OAAO,WAAW,GAClD,MAAM,IAAI,MAAM,4CAA4C;EAE9D,IAAI,KAAK,IAAI,MAAM,GACjB,MAAM,IAAI,MAAM,8CAA8C,KAAK,UAAU,MAAM,GAAG;EAExF,KAAK,IAAI,MAAM;CACjB;AACF;AAEA,SAAS,eAAe,eAA2C;CACjE,MAAM,QAAQ,iBAAiB;CAC/B,IAAI,CAAC,qBAAqB,KAAK,KAAK,GAClC,MAAM,IAAI,MACR,qDAAqD,qBAAqB,QAC5E;CAEF,OAAO;AACT;AAEA,SAAS,qBAAqB,UAAkB,SAA4B,OAAuB;CACjG,MAAM,UAAU,QAAQ,KAAK,WAAW,KAAK,UAAU,MAAM,CAAC,CAAC,CAAC,KAAK,KAAK;CAC1E,OAAO;EACL;EACA;EACA;EACA;EACA,KAAK,KAAK,UAAU,KAAK,EAAE,IAAI,QAAQ;EACvC;EACA;EACA;EACA;CACF,CAAC,CAAC,KAAK,IAAI;AACb"}
|
package/dist/flows.d.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { C as PermissionPolicy, E as PromptInput, S as PermissionMode, b as McpServer$1, t as SessionAgentOptions, x as NonInteractivePermissionPolicy, y as AuthPolicy } from "./session-options-Dp6mzNSy.js";
|
|
2
|
-
import "./client-
|
|
2
|
+
import "./client-BchvQRpz.js";
|
|
3
3
|
import { SetSessionConfigOptionResponse } from "@agentclientprotocol/sdk";
|
|
4
|
+
import net from "node:net";
|
|
4
5
|
//#region src/flows/types.d.ts
|
|
5
6
|
type MaybePromise<T> = T | Promise<T>;
|
|
6
7
|
type FlowRunDefinition<TInput = unknown> = {
|
package/dist/flows.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"flows.d.ts","names":[],"sources":["../src/flows/types.ts","../src/flows/definition.ts","../src/flows/runtime.ts","../src/flows/decision.ts","../src/flows/store.ts","../src/flows/json.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"flows.d.ts","names":[],"sources":["../src/flows/types.ts","../src/flows/definition.ts","../src/flows/runtime.ts","../src/flows/decision.ts","../src/flows/store.ts","../src/flows/json.ts"],"mappings":";;;;;KAaK,aAAa,KAAK,IAAI,QAAQ;KAEvB,kBAAkB;EAC5B,mBAEM;IACA,OAAO;IACP;IACA;QACI;;KAGA,gBAAgB;EAC1B,OAAO;EACP,SAAS;EACT,SAAS,eAAe;EACxB,OAAO;EACP,UAAU;;EAEV,SAAS;;EAET,YAAY,WAAW,uBAAuB,QAAQ;;KAG5C;EACV;EACA;EACA;;KAGU;EAEN;EACA;;EAGA;EACA;IACE;IACA,OAAO;;;KAIH,oBAAoB;EAC9B;EACA;EACA,iBAAiB,SAAS,oBAAoB;EAC9C;IACE;IACA;;EAEF,SAAS,SAAS,oBAAoB,aAAa;EACnD,SAAS,cAAc,SAAS,oBAAoB;;KAG1C,wBAAwB;EAClC;EACA,MAAM,SAAS,oBAAoB;;KAGzB,+BAA+B;EACzC;EACA,MAAM,SAAS,oBAAoB;;KAGzB;EACV;EACA;EACA;EACA,MAAM;EACN;EACA;EACA;EACA;;EAEA;;KAGU;EACV;EACA;EACA;EACA;EACA;EACA;EACA;EACA,QAAQ,OAAO;EACf;;KAGU,qBAAqB,KAAK;KAE1B,kBAAkB;;EAE5B;;KAGU,4BAA4B;EACtC;EACA,OAAO,SAAS,oBAAoB,aAAa;EACjD,SAAS,QAAQ,mBAAmB,SAAS,oBAAoB;;KAGvD,uBAAuB,+BAA+B;KAEtD,2BAA2B;EACrC;EACA;EACA,OAAO,SAAS,oBAAoB;;KAG1B,qBACR,oBACA,wBACA,uBACA;KAEQ;EACV,cAAc;EACd;EACA;;KAGU;EACV;EACA,MAAM;EACN,cAAc;EACd;EACA,OAAO,eAAe;EACtB,OAAO;;KAkCG;KAEA;EACV;EACA;EACA,UAAU;EACV,SAAS;EACT;EACA;EACA;EACA;EACA;;KAGU;EACV;EACA;EACA;EACA;;KAGU;EACV;EACA;EACA;EACA;EACA;;KAGU;EACV;EACA;EACA;EACA;EACA;EACA,SAAS,OAAO;EAChB;;KAGU;EACV;EACA,iBAAiB;EACjB,sBAAsB;EACtB,iBAAiB;EACjB;EACA,iBAAiB;EACjB,iBAAiB;EACjB,eAAe;EACf,SAAS;;KAGC;EACV;EACA;EACA,UAAU;EACV,SAAS;EACT;EACA;EACA;EACA;EACA;EACA;EACA,SAAS;EACT;IACE;IACA;IACA;;EAEF,QAAQ;;KAGE;EACV;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;KAGU;EACV;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,SAAS;EACT,SAAS,eAAe;EACxB,OAAO;EACP,iBAAiB,eAAe;EAChC;EACA;EACA,kBAAkB;EAClB;EACA;EACA;EACA;EACA;;KAGU;EACV;EACA,OAAO;;KA4DG;EACV;EACA;EACA;EACA;;KAGU;EACV,eAAe,qBAAqB;EACpC,gBAAgB;EAChB,aAAa;EACb,4BAA4B;EAC5B,mBAAmB;EACnB,kBAAkB;EAClB,aAAa;EACb;EACA;EACA;EACA;EACA;EACA;EACA,iBAAiB;EACjB,WAAW;EACX;;;;wBChWc,WAAW,cAAc,gBAAgB,YAAY,QAAQ;wBAK7D,IAAI,YAAY,KAAK,iCAAiC;wBAStD,QACd,YAAY,KAAK,qCAChB;wBASa,OACd,YAAY,KAAK,4CAChB;wBACa,OACd,YAAY,KAAK,yCAChB;wBAca,MACd,YAAY,KAAK,yCAChB;wBASa,WACd,aAAY,KAAK,wCAChB;;;qBC6FU;mBACM;mBACA;mBACA;mBACA;mBACA;mBACA;mBACA;mBACA;mBACA;mBACA;mBACA;mBACA;mBACA;EAEL,YAAA,SAAS;EAqBf,IACJ,MAAM,gBACN,gBACA;IAAW;MACV,QAAQ;UA2CG;UAuDN;UAgBM;UAcN;UAOM;UA+BN;UAOM;UA2FN;UAkBM;UAoBA;UAkBN;UAYM;UAeA;UAkCA;UA0BA;UAqBA;UA+FN;UAiBA;UAgBM;UA8BA;UA6CA;UAgBA;UAkCA;UAkBA;UAwBA;UAoBA;UAeA;UAuCA;UAoBA;UAWN;UA2CM;UAmEN;UAsEM;UA2DA;UAgBA;;;;KCpwCX,qBAAqB,KAAK;KAEnB,mBAAmB,0BAA0B;EACvD,qBAAqB,SAAS,6BAA6B;EAC3D,kBAAkB;EAClB;;wBAMc,SAAS,wBACvB,YAAY,mBAAmB,WAC9B;wBA+Ba,aAAa,wBAAwB;EACnD;EACA,kBAAkB;EAClB;EACA,OAAO,OAAO;IACZ;;;wBCOY,gBAAgB;;;KChEpB;wBAsBI,gBACd,cACA;EACE,OAAO;;wBA6EK,sBAAsB;wBAMtB,kBAAkB"}
|
package/dist/flows.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { a as parseStrictJsonObject, d as checkpoint, f as compute, i as parseJsonObject, l as acp, m as shell, n as decisionEdge, o as FlowRunner, p as defineFlow, r as extractJsonObject, s as flowRunsBaseDir, t as decision, u as action } from "./flows
|
|
1
|
+
import { a as parseStrictJsonObject, d as checkpoint, f as compute, i as parseJsonObject, l as acp, m as shell, n as decisionEdge, o as FlowRunner, p as defineFlow, r as extractJsonObject, s as flowRunsBaseDir, t as decision, u as action } from "./flows-DimX0it5.js";
|
|
2
2
|
export { FlowRunner, acp, action, checkpoint, compute, decision, decisionEdge, defineFlow, extractJsonObject, flowRunsBaseDir, parseJsonObject, parseStrictJsonObject, shell };
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import "./output-
|
|
2
|
-
import { At as PERMISSION_POLICY_ACTIONS, Ct as AUTH_POLICIES, Ot as OUTPUT_FORMATS, Tt as NON_INTERACTIVE_PERMISSION_POLICIES } from "./ipc-
|
|
3
|
-
import "./queue-owner-runtime-
|
|
4
|
-
import { d as resolveAgentCommand, l as normalizeAgentName, p as resolveCanonicalAgentName, u as resolveAgentArgv } from "./agent-registry-
|
|
1
|
+
import "./output-Cnuji8Bo.js";
|
|
2
|
+
import { At as PERMISSION_POLICY_ACTIONS, Ct as AUTH_POLICIES, Ot as OUTPUT_FORMATS, Tt as NON_INTERACTIVE_PERMISSION_POLICIES } from "./ipc-DAApJ5mi.js";
|
|
3
|
+
import "./queue-owner-runtime-C4OOosbo.js";
|
|
4
|
+
import { d as resolveAgentCommand, l as normalizeAgentName, p as resolveCanonicalAgentName, u as resolveAgentArgv } from "./agent-registry-DWlx5BQ4.js";
|
|
5
5
|
import path from "node:path";
|
|
6
6
|
import { InvalidArgumentError } from "commander";
|
|
7
7
|
import fs from "node:fs/promises";
|
|
@@ -348,4 +348,4 @@ async function resolvePermissionPolicyFromFlags(globalFlags) {
|
|
|
348
348
|
//#endregion
|
|
349
349
|
export { resolvePermissionMode as C, toTimerMilliseconds as D, resolveSessionsListFlags as E, resolveOutputPolicy as S, resolveSessionNameFromFlags as T, parseSessionName as _, addGlobalFlags as a, resolveAgentInvocation as b, addSessionOption as c, parseDaysOlderThan as d, parseHistoryLimit as f, parsePruneBeforeDate as g, parseOutputFormat as h, addExecConfigOption as i, hasExplicitPermissionModeFlag as l, parseNonEmptyValue as m, sessionConnectionOptions as n, addPromptInputOption as o, parseMaxTurns as p, sessionOptionsFromGlobalFlags as r, addSessionNameOption as s, resolvePermissionPolicyFromFlags as t, parseAllowedTools as u, parseTimeoutSeconds as v, resolvePromptFlags as w, resolveGlobalFlags as x, parseTtlSeconds as y };
|
|
350
350
|
|
|
351
|
-
//# sourceMappingURL=invocation-options-
|
|
351
|
+
//# sourceMappingURL=invocation-options-vobVApfO.js.map
|