@zaalipro/dsh-workflows 0.1.0-rc.3
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/LICENSE +21 -0
- package/NOTICE.md +224 -0
- package/README.i18n.yaml +4 -0
- package/README.md +109 -0
- package/README.zh.md +109 -0
- package/cordis.patch.yml +10 -0
- package/docs/architecture.i18n.yaml +4 -0
- package/docs/architecture.md +177 -0
- package/docs/architecture.zh.md +177 -0
- package/docs/testing.i18n.yaml +4 -0
- package/docs/testing.md +125 -0
- package/docs/testing.zh.md +125 -0
- package/docs/user-guide.i18n.yaml +4 -0
- package/docs/user-guide.md +351 -0
- package/docs/user-guide.zh.md +351 -0
- package/lib/client-types/WorkflowMemberInspector.d.ts +28 -0
- package/lib/client-types/WorkflowMemberInspector.d.ts.map +1 -0
- package/lib/client-types/WorkflowMemberInspector.js +181 -0
- package/lib/client-types/WorkflowMemberInspector.js.map +1 -0
- package/lib/client-types/WorkflowRunPanel.d.ts +43 -0
- package/lib/client-types/WorkflowRunPanel.d.ts.map +1 -0
- package/lib/client-types/WorkflowRunPanel.js +130 -0
- package/lib/client-types/WorkflowRunPanel.js.map +1 -0
- package/lib/client-types/WorkflowsDashboard.d.ts +49 -0
- package/lib/client-types/WorkflowsDashboard.d.ts.map +1 -0
- package/lib/client-types/WorkflowsDashboard.js +942 -0
- package/lib/client-types/WorkflowsDashboard.js.map +1 -0
- package/lib/client-types/adapter.d.ts +60 -0
- package/lib/client-types/adapter.d.ts.map +1 -0
- package/lib/client-types/adapter.js +117 -0
- package/lib/client-types/adapter.js.map +1 -0
- package/lib/client-types/chat-renderer.d.ts +10 -0
- package/lib/client-types/chat-renderer.d.ts.map +1 -0
- package/lib/client-types/chat-renderer.js +11 -0
- package/lib/client-types/chat-renderer.js.map +1 -0
- package/lib/client-types/contract.d.ts +210 -0
- package/lib/client-types/contract.d.ts.map +1 -0
- package/lib/client-types/contract.js +37 -0
- package/lib/client-types/contract.js.map +1 -0
- package/lib/client-types/controller.d.ts +83 -0
- package/lib/client-types/controller.d.ts.map +1 -0
- package/lib/client-types/controller.js +705 -0
- package/lib/client-types/controller.js.map +1 -0
- package/lib/client-types/index.d.ts +19 -0
- package/lib/client-types/index.d.ts.map +1 -0
- package/lib/client-types/index.js +730 -0
- package/lib/client-types/index.js.map +1 -0
- package/lib/client-types/locales.d.ts +257 -0
- package/lib/client-types/locales.d.ts.map +1 -0
- package/lib/client-types/locales.js +270 -0
- package/lib/client-types/locales.js.map +1 -0
- package/lib/client-types/slot-components.d.ts +38 -0
- package/lib/client-types/slot-components.d.ts.map +1 -0
- package/lib/client-types/slot-components.js +22 -0
- package/lib/client-types/slot-components.js.map +1 -0
- package/lib/client-types/store.d.ts +69 -0
- package/lib/client-types/store.d.ts.map +1 -0
- package/lib/client-types/store.js +135 -0
- package/lib/client-types/store.js.map +1 -0
- package/lib/client-types/workflow-definition.d.ts +52 -0
- package/lib/client-types/workflow-definition.d.ts.map +1 -0
- package/lib/client-types/workflow-definition.js +135 -0
- package/lib/client-types/workflow-definition.js.map +1 -0
- package/lib/client.js +11064 -0
- package/lib/client.js.map +1 -0
- package/lib/compat-engine/index.js +1926 -0
- package/lib/compat-engine/index.js.map +1 -0
- package/lib/compat-engine/worker.cjs +1500 -0
- package/lib/compat-engine/worker.cjs.map +1 -0
- package/lib/typert.host.d.ts +3 -0
- package/lib/typert.host.js +1709 -0
- package/lib/typert.remote-client.d.ts +57 -0
- package/lib/typert.remote-client.js +1662 -0
- package/lib/types/commands/aliases.d.ts +4 -0
- package/lib/types/commands/aliases.d.ts.map +1 -0
- package/lib/types/commands/aliases.js +25 -0
- package/lib/types/commands/aliases.js.map +1 -0
- package/lib/types/commands/index.d.ts +66 -0
- package/lib/types/commands/index.d.ts.map +1 -0
- package/lib/types/commands/index.js +550 -0
- package/lib/types/commands/index.js.map +1 -0
- package/lib/types/commands/parser.d.ts +17 -0
- package/lib/types/commands/parser.d.ts.map +1 -0
- package/lib/types/commands/parser.js +45 -0
- package/lib/types/commands/parser.js.map +1 -0
- package/lib/types/config.d.ts +71 -0
- package/lib/types/config.d.ts.map +1 -0
- package/lib/types/config.js +109 -0
- package/lib/types/config.js.map +1 -0
- package/lib/types/index.d.ts +41 -0
- package/lib/types/index.d.ts.map +1 -0
- package/lib/types/index.js +483 -0
- package/lib/types/index.js.map +1 -0
- package/lib/types/invariant.d.ts +21 -0
- package/lib/types/invariant.d.ts.map +1 -0
- package/lib/types/invariant.js +85 -0
- package/lib/types/invariant.js.map +1 -0
- package/lib/types/registry/definition.d.ts +24 -0
- package/lib/types/registry/definition.d.ts.map +1 -0
- package/lib/types/registry/definition.js +189 -0
- package/lib/types/registry/definition.js.map +1 -0
- package/lib/types/registry/index.d.ts +100 -0
- package/lib/types/registry/index.d.ts.map +1 -0
- package/lib/types/registry/index.js +899 -0
- package/lib/types/registry/index.js.map +1 -0
- package/lib/types/registry/names.d.ts +19 -0
- package/lib/types/registry/names.d.ts.map +1 -0
- package/lib/types/registry/names.js +69 -0
- package/lib/types/registry/names.js.map +1 -0
- package/lib/types/registry/remote.d.ts +15 -0
- package/lib/types/registry/remote.d.ts.map +1 -0
- package/lib/types/registry/remote.js +128 -0
- package/lib/types/registry/remote.js.map +1 -0
- package/lib/types/registry/roots.d.ts +44 -0
- package/lib/types/registry/roots.d.ts.map +1 -0
- package/lib/types/registry/roots.js +118 -0
- package/lib/types/registry/roots.js.map +1 -0
- package/lib/types/registry/types.d.ts +62 -0
- package/lib/types/registry/types.d.ts.map +1 -0
- package/lib/types/registry/types.js +2 -0
- package/lib/types/registry/types.js.map +1 -0
- package/lib/types/registry/watchers.d.ts +70 -0
- package/lib/types/registry/watchers.d.ts.map +1 -0
- package/lib/types/registry/watchers.js +152 -0
- package/lib/types/registry/watchers.js.map +1 -0
- package/lib/types/remote-events.d.ts +42 -0
- package/lib/types/remote-events.d.ts.map +1 -0
- package/lib/types/remote-events.js +21 -0
- package/lib/types/remote-events.js.map +1 -0
- package/lib/types/run-recorder.d.ts +44 -0
- package/lib/types/run-recorder.d.ts.map +1 -0
- package/lib/types/run-recorder.js +356 -0
- package/lib/types/run-recorder.js.map +1 -0
- package/lib/types/supervisor/canned-validate.d.ts +25 -0
- package/lib/types/supervisor/canned-validate.d.ts.map +1 -0
- package/lib/types/supervisor/canned-validate.js +122 -0
- package/lib/types/supervisor/canned-validate.js.map +1 -0
- package/lib/types/supervisor/completion-notice.d.ts +49 -0
- package/lib/types/supervisor/completion-notice.d.ts.map +1 -0
- package/lib/types/supervisor/completion-notice.js +281 -0
- package/lib/types/supervisor/completion-notice.js.map +1 -0
- package/lib/types/supervisor/cursors.d.ts +68 -0
- package/lib/types/supervisor/cursors.d.ts.map +1 -0
- package/lib/types/supervisor/cursors.js +158 -0
- package/lib/types/supervisor/cursors.js.map +1 -0
- package/lib/types/supervisor/engine-compat.d.ts +48 -0
- package/lib/types/supervisor/engine-compat.d.ts.map +1 -0
- package/lib/types/supervisor/engine-compat.js +116 -0
- package/lib/types/supervisor/engine-compat.js.map +1 -0
- package/lib/types/supervisor/index.d.ts +183 -0
- package/lib/types/supervisor/index.d.ts.map +1 -0
- package/lib/types/supervisor/index.js +2040 -0
- package/lib/types/supervisor/index.js.map +1 -0
- package/lib/types/supervisor/parallel-compat.d.ts +36 -0
- package/lib/types/supervisor/parallel-compat.d.ts.map +1 -0
- package/lib/types/supervisor/parallel-compat.js +180 -0
- package/lib/types/supervisor/parallel-compat.js.map +1 -0
- package/lib/types/supervisor/remote.d.ts +25 -0
- package/lib/types/supervisor/remote.d.ts.map +1 -0
- package/lib/types/supervisor/remote.js +478 -0
- package/lib/types/supervisor/remote.js.map +1 -0
- package/lib/types/supervisor/storage/bounded-file.d.ts +41 -0
- package/lib/types/supervisor/storage/bounded-file.d.ts.map +1 -0
- package/lib/types/supervisor/storage/bounded-file.js +186 -0
- package/lib/types/supervisor/storage/bounded-file.js.map +1 -0
- package/lib/types/supervisor/storage/details-codec.d.ts +14 -0
- package/lib/types/supervisor/storage/details-codec.d.ts.map +1 -0
- package/lib/types/supervisor/storage/details-codec.js +359 -0
- package/lib/types/supervisor/storage/details-codec.js.map +1 -0
- package/lib/types/supervisor/storage/index.d.ts +26 -0
- package/lib/types/supervisor/storage/index.d.ts.map +1 -0
- package/lib/types/supervisor/storage/index.js +100 -0
- package/lib/types/supervisor/storage/index.js.map +1 -0
- package/lib/types/supervisor/storage/lease.d.ts +34 -0
- package/lib/types/supervisor/storage/lease.d.ts.map +1 -0
- package/lib/types/supervisor/storage/lease.js +289 -0
- package/lib/types/supervisor/storage/lease.js.map +1 -0
- package/lib/types/supervisor/storage/manifest-codec.d.ts +10 -0
- package/lib/types/supervisor/storage/manifest-codec.d.ts.map +1 -0
- package/lib/types/supervisor/storage/manifest-codec.js +335 -0
- package/lib/types/supervisor/storage/manifest-codec.js.map +1 -0
- package/lib/types/supervisor/storage/manifest-store.d.ts +99 -0
- package/lib/types/supervisor/storage/manifest-store.d.ts.map +1 -0
- package/lib/types/supervisor/storage/manifest-store.js +1606 -0
- package/lib/types/supervisor/storage/manifest-store.js.map +1 -0
- package/lib/types/supervisor/storage/manifest-types.d.ts +269 -0
- package/lib/types/supervisor/storage/manifest-types.d.ts.map +1 -0
- package/lib/types/supervisor/storage/manifest-types.js +2 -0
- package/lib/types/supervisor/storage/manifest-types.js.map +1 -0
- package/lib/types/supervisor/storage/private-root.d.ts +143 -0
- package/lib/types/supervisor/storage/private-root.d.ts.map +1 -0
- package/lib/types/supervisor/storage/private-root.js +860 -0
- package/lib/types/supervisor/storage/private-root.js.map +1 -0
- package/lib/types/supervisor/storage/recovery.d.ts +14 -0
- package/lib/types/supervisor/storage/recovery.d.ts.map +1 -0
- package/lib/types/supervisor/storage/recovery.js +126 -0
- package/lib/types/supervisor/storage/recovery.js.map +1 -0
- package/lib/types/supervisor/storage/run-files.d.ts +67 -0
- package/lib/types/supervisor/storage/run-files.d.ts.map +1 -0
- package/lib/types/supervisor/storage/run-files.js +346 -0
- package/lib/types/supervisor/storage/run-files.js.map +1 -0
- package/lib/types/supervisor/types.d.ts +295 -0
- package/lib/types/supervisor/types.d.ts.map +1 -0
- package/lib/types/supervisor/types.js +3 -0
- package/lib/types/supervisor/types.js.map +1 -0
- package/lib/types/supervisor/value-view.d.ts +19 -0
- package/lib/types/supervisor/value-view.d.ts.map +1 -0
- package/lib/types/supervisor/value-view.js +183 -0
- package/lib/types/supervisor/value-view.js.map +1 -0
- package/lib/types/tool/index.d.ts +86 -0
- package/lib/types/tool/index.d.ts.map +1 -0
- package/lib/types/tool/index.js +810 -0
- package/lib/types/tool/index.js.map +1 -0
- package/lib/types/tool/schema.d.ts +158 -0
- package/lib/types/tool/schema.d.ts.map +1 -0
- package/lib/types/tool/schema.js +137 -0
- package/lib/types/tool/schema.js.map +1 -0
- package/lib/types/types.d.ts +9 -0
- package/lib/types/types.d.ts.map +1 -0
- package/lib/types/types.js +3 -0
- package/lib/types/types.js.map +1 -0
- package/lib/types/user-questions.d.ts +9 -0
- package/lib/types/user-questions.d.ts.map +1 -0
- package/lib/types/user-questions.js +91 -0
- package/lib/types/user-questions.js.map +1 -0
- package/package.json +273 -0
- package/skills/create-workflow/SKILL.md +166 -0
- package/vendor/workflow-engine/LICENSE +21 -0
- package/vendor/workflow-engine/README.md +1 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","names":["WorkflowError","StockWorkflowError","Buffer","Buffer","WorkflowError","WorkflowError"],"sources":["../../vendor/workflow-engine/compat-seam.ts","../../vendor/workflow-engine/realm.ts","../../vendor/workflow-engine/protocol.ts","../../vendor/workflow-engine/host.ts","../../vendor/workflow-engine/meta.ts","../../vendor/workflow-engine/index.ts"],"sourcesContent":["/** Local extensions deliberately absent from the official 0.1.1-rc.2 seam. */\nimport { WorkflowError as StockWorkflowError } from '@deepseek-ai/dsh-workflow'\nimport type { Agent } from '@deepseek-ai/dsh-agent'\nimport type { WorkflowMeta } from '@deepseek-ai/dsh-workflow'\nimport type { WorkflowJournalEntry, WorkflowScratchPort } from './types.ts'\n\nexport type CompatWorkflowErrorCode =\n | ConstructorParameters<typeof StockWorkflowError>[1]\n | 'JOURNAL_DIVERGENCE'\n\nexport const WorkflowError = StockWorkflowError as unknown as {\n new(message: string, code: CompatWorkflowErrorCode, options?: ErrorOptions & { fatal?: boolean }): StockWorkflowError\n}\nexport type WorkflowError = StockWorkflowError\n\nexport type WorkflowGateKind = 'user' | 'back_off' | 'no_progress' | 'verification' | 'infra'\nexport interface WorkflowGateInfo { readonly kind: WorkflowGateKind; readonly message: string; readonly resumable: boolean }\nexport interface WorkflowResult {\n readonly value: unknown\n readonly stopReason: 'completed' | 'cancelled' | 'error'\n readonly error?: string\n readonly errorCode?: string\n readonly agentsStarted: number\n}\nexport interface WorkflowStartRequest {\n readonly script: string\n readonly meta: WorkflowMeta\n readonly args?: unknown\n readonly subagentProvider?: string\n readonly maxTotalAgents?: number\n readonly initialAgentSpend?: number\n readonly initialAgentSeq?: number\n readonly journal?: readonly WorkflowJournalEntry[]\n readonly scratchDir?: string\n readonly scratch?: WorkflowScratchPort\n readonly validateOnly?: boolean\n readonly deferStart?: boolean\n readonly replay?: { readonly checkpoint?: { readonly journal: readonly WorkflowJournalEntry[]; readonly agentSpend: number; readonly agentSeq: number } }\n readonly parent: Agent\n readonly signal?: AbortSignal\n}\n","/**\n * Materializes values leaving the script vm into plain JSON before they cross the worker\n * boundary, and renders thrown script values without rejecting the run. The walk rejects\n * values that JSON cannot preserve but trusts model-written workflow scripts: getters and proxy traps may\n * run, and the vm is not a security boundary. The worker provides host-loop isolation and\n * forced termination, not hostile-value containment. See\n * .agents/notes/implemented/feature/2026-07-05-dynamic-workflows.md for the isolation rationale.\n * @module @deepseek-ai/dsh-workflow-worker-thread/realm\n */\n\n/** Thrown by {@link materializeFromRealm}; the caller wraps it into the right `WorkflowError` code. */\nexport class MaterializeError extends Error {\n constructor(public readonly path: string, public readonly reason: string) {\n super(`${path}: ${reason}`)\n this.name = 'MaterializeError'\n }\n}\n\n/**\n * Render a thrown value to failure text without ever throwing: prefer the\n * `stack` (host or realm — a realm error's `stack` is a plain string read),\n * fall back to `message`, then `String()`. Reading those properties MAY run\n * script code (a getter, `toString`) — accepted under the module's trust\n * premise; if that code itself throws, a fixed label is returned instead.\n * @param error - any value thrown in the host or worker realm.\n * @returns human-readable text for the failure report; prefers the stack.\n */\nexport function renderThrown(error: unknown): string {\n try {\n const stack = (error as { stack?: unknown } | null | undefined)?.stack\n if (typeof stack === 'string' && stack.length > 0) return stack\n const message = (error as { message?: unknown } | null | undefined)?.message\n if (typeof message === 'string' && message.length > 0) return message\n return String(error)\n } catch {\n // A throwing accessor/toString on the thrown value — rendering must be\n // total (drive()'s never-reject contract), so fall back to a fixed label.\n return '[unrenderable thrown value]'\n }\n}\n\n/**\n * Whether an object's prototype chain represents a plain data object: `null`, or a prototype\n * whose own prototype is `null` (the realm's `Object.prototype` — which we\n * cannot compare by identity across realms). A `Date`/`Map`/class instance\n * has a longer chain and is rejected.\n */\nfunction hasPlainPrototype(value: object): boolean {\n const proto: unknown = Object.getPrototypeOf(value)\n if (proto === null) return true\n return Object.getPrototypeOf(proto) === null\n}\n\n/**\n * Copy `value` (typically from the vm realm) into plain host JSON data. Root `undefined` is\n * returned unchanged; nested `undefined` and values JSON cannot represent losslessly fail\n * with the offending path. Property accessors run normally, and a throwing read is wrapped\n * with its rendered failure.\n *\n * @param value - the realm value to materialize.\n * @param root - the path label for the root value (error messages).\n * @returns the host-realm copy (plain objects/arrays/scalars only).\n * @throws {@link MaterializeError} for unsupported values, cycles, sparse arrays, exotic\n * prototypes, or property reads that throw.\n */\nexport function materializeFromRealm(value: unknown, root = 'value'): unknown {\n if (value === undefined) return undefined\n try {\n return materialize(value, root, new Set())\n } catch (error: unknown) {\n if (error instanceof MaterializeError) throw error\n // A property read ran script code that threw; total-ize it so callers can\n // keep the narrow MaterializeError contract.\n throw new MaterializeError(root, `reading the value threw: ${renderThrown(error)}`)\n }\n}\n\nfunction materialize(value: unknown, path: string, seen: Set<object>): unknown {\n switch (typeof value) {\n case 'boolean':\n case 'string':\n return value\n case 'number': {\n if (!Number.isFinite(value)) throw new MaterializeError(path, 'non-finite numbers are not JSON data')\n return value\n }\n case 'bigint':\n throw new MaterializeError(path, 'bigints are not JSON data')\n case 'function':\n throw new MaterializeError(path, 'functions are not plain JSON data')\n case 'symbol':\n throw new MaterializeError(path, 'symbols are not plain JSON data')\n case 'undefined':\n throw new MaterializeError(path, 'undefined is not JSON data')\n case 'object':\n break\n }\n if (value === null) return null\n const objectValue: object = value\n if (seen.has(objectValue)) throw new MaterializeError(path, 'circular references are not JSON data')\n seen.add(objectValue)\n try {\n if (Array.isArray(objectValue)) return materializeArray(objectValue, path, seen)\n return materializeObject(objectValue, path, seen)\n } finally {\n seen.delete(objectValue)\n }\n}\n\nfunction materializeArray(value: unknown[], path: string, seen: Set<object>): unknown[] {\n const out: unknown[] = []\n for (let index = 0; index < value.length; index++) {\n if (!(index in value)) throw new MaterializeError(`${path}[${index}]`, 'sparse arrays are not JSON data')\n out.push(materialize(value[index], `${path}[${index}]`, seen))\n }\n // Own enumerable props beyond the indices (e.g. `arr.total = 3`) would be\n // silently dropped by JSON — reject them instead.\n for (const key of Object.keys(value)) {\n const index = Number(key)\n if (!Number.isInteger(index) || index < 0 || index >= value.length) {\n throw new MaterializeError(`${path}.${key}`, 'arrays with non-index properties are not JSON data')\n }\n }\n if (Object.getOwnPropertySymbols(value).length > 0) {\n throw new MaterializeError(path, 'symbol-keyed properties are not plain JSON data')\n }\n return out\n}\n\nfunction materializeObject(value: object, path: string, seen: Set<object>): Record<string, unknown> {\n if (!hasPlainPrototype(value)) {\n throw new MaterializeError(path, 'only plain objects and arrays are JSON data (exotic prototype)')\n }\n if (Object.getOwnPropertySymbols(value).length > 0) {\n throw new MaterializeError(path, 'symbol-keyed properties are not plain JSON data')\n }\n const out: Record<string, unknown> = {}\n // Object.keys = own enumerable string keys, matching JSON.stringify's\n // property selection exactly (non-enumerable props never reach JSON output).\n for (const key of Object.keys(value)) {\n // defineProperty, never assignment: a \"__proto__\" key must become an OWN\n // data property of the copy, not a prototype mutation.\n Object.defineProperty(out, key, {\n value: materialize((value as Record<string, unknown>)[key], `${path}.${key}`, seen),\n enumerable: true,\n writable: true,\n configurable: true,\n })\n }\n return out\n}\n","/**\n * The host⇄worker wire protocol: one string-valued enum of message tags per direction, a\n * payload map giving each tag its parameters (the single source of truth), and the message\n * unions derived from them. Payloads are plain JSON by construction for structured clone. Both\n * directions are closed engine protocols. The host runtime-decodes the worker direction before\n * dispatch; generic typed senders make tag/payload mismatches compile-time errors rather than\n * silently skipped messages.\n * @module @deepseek-ai/dsh-workflow-worker-thread/protocol\n */\n\nimport { Buffer } from 'node:buffer'\nimport { snapshotJsonValue, type JsonValue } from '@deepseek-ai/dsh-session'\nimport { assertObjectJsonSchema } from '@deepseek-ai/dsh-tools'\nimport type {\n WorkflowAgentEndInfo,\n WorkflowAgentInfo,\n} from '@deepseek-ai/dsh-workflow'\nimport type { CompatWorkflowErrorCode as WorkflowErrorCode, WorkflowGateInfo, WorkflowResult } from './compat-seam.ts'\nimport type { ChildResult, ChildStartRequest, WorkflowJournalEntry } from './types.ts'\n\n/** Message tags the worker sends the host (the wire values are the tag strings). */\nexport enum WorkerToHostType {\n /** The startup handshake: the session is listening and awaits {@link HostToWorkerType.Go}. */\n Ready = 'ready',\n /** Observer narration: a `phase(title)` call. */\n Phase = 'phase',\n /** Observer narration: a `log(message)` call. */\n Log = 'log',\n /** Observer lifecycle: one `agent()` call started a child. */\n AgentStart = 'agent-start',\n /** Observer lifecycle: one `agent()` call settled. */\n AgentEnd = 'agent-end',\n /** Observer gate: the script parked on a `pause()`/`await_user()` call. */\n Gate = 'gate',\n /** Journal: one committed host call appended for same-process replay. */\n JournalCommit = 'journal-commit',\n /** Child RPC: start a child on the host (answered by ChildStarted or ChildStartError). */\n ChildStart = 'child-start',\n /** Child RPC: dispose a started child (answered by ChildDisposed). */\n ChildDispose = 'child-dispose',\n /** Scratch RPC: write one single-component scratch file (answered by ScratchWritten). */\n ScratchWrite = 'scratch-write',\n /** Scratch RPC: read one single-component scratch file (answered by ScratchReadResult). */\n ScratchRead = 'scratch-read',\n /** The run's single terminal result. */\n Result = 'result',\n}\n\n/** The payload each worker→host tag carries. */\nexport interface WorkerToHostPayloads {\n /** Ready carries nothing. */\n [WorkerToHostType.Ready]: Record<never, never>\n /** The phase title, verbatim. */\n [WorkerToHostType.Phase]: { title: string }\n /** The logged message, verbatim. */\n [WorkerToHostType.Log]: { message: string }\n /** The call's sequence number, label, phase, and child id. */\n [WorkerToHostType.AgentStart]: { info: WorkflowAgentInfo }\n /** The call identity plus its outcome. */\n [WorkerToHostType.AgentEnd]: { info: WorkflowAgentEndInfo }\n /** A parked gate's kind, message, and resumability. */\n [WorkerToHostType.Gate]: { gate: WorkflowGateInfo }\n /** One committed host call (including a result for result-producing calls). */\n [WorkerToHostType.JournalCommit]: { entry: WorkflowJournalEntry }\n /** The RPC correlation id and the prompt plus validated options. */\n [WorkerToHostType.ChildStart]: { callId: number; request: ChildStartRequest }\n /** The RPC correlation id of the child to dispose. */\n [WorkerToHostType.ChildDispose]: { callId: number }\n /** The RPC correlation id, file name, and content to write. */\n [WorkerToHostType.ScratchWrite]: { callId: number; name: string; content: string }\n /** The RPC correlation id and file name to read. */\n [WorkerToHostType.ScratchRead]: { callId: number; name: string }\n /** The run's terminal outcome. */\n [WorkerToHostType.Result]: { result: WorkflowResult }\n}\n\n/** Message tags the host sends the worker (the wire values are the tag strings). */\nexport enum HostToWorkerType {\n /** Releases the startup gate: run the script body. */\n Go = 'go',\n /** Cancel the run: hooks start throwing and the script dies at its next await. */\n Cancel = 'cancel',\n /** Resume a parked gate: `await_user` returns, `pause` re-fires. */\n Resume = 'resume',\n /** Child RPC reply: the provider fulfilled with a published run (exactly one start reply per ChildStart). */\n ChildStarted = 'child-started',\n /** Child RPC reply: the provider's asynchronous start failed. */\n ChildStartError = 'child-start-error',\n /** Child RPC: a started child's result RESOLVED (its JSON projection). */\n ChildSettled = 'child-settled',\n /** Child RPC: a started child's result REJECTED (an infrastructure fault, rendered). */\n ChildFailed = 'child-failed',\n /** Child RPC reply: a requested disposal completed. */\n ChildDisposed = 'child-disposed',\n /** Scratch RPC reply: a write completed. */\n ScratchWritten = 'scratch-written',\n /** Scratch RPC reply: a read completed with content, or undefined when absent. */\n ScratchReadResult = 'scratch-read-result',\n}\n\n/** The payload each host→worker tag carries. */\nexport interface HostToWorkerPayloads {\n /** Go carries nothing. */\n [HostToWorkerType.Go]: Record<never, never>\n /** The cancel reason, canonical for the whole run. */\n [HostToWorkerType.Cancel]: { reason: string }\n /** Resume carries nothing: release the parked gate. */\n [HostToWorkerType.Resume]: Record<never, never>\n /** The RPC correlation id and the child agent's id (minted by the subagent seam). */\n [HostToWorkerType.ChildStarted]: { callId: number; childId: string }\n /** The RPC correlation id and the rendered start failure. */\n [HostToWorkerType.ChildStartError]: { callId: number; rendered: string }\n /** The RPC correlation id and the child's terminal result projection. */\n [HostToWorkerType.ChildSettled]: { callId: number; result: ChildResult }\n /** The RPC correlation id and the rendered infrastructure fault. */\n [HostToWorkerType.ChildFailed]: { callId: number; rendered: string }\n /** The RPC correlation id of the completed disposal. */\n [HostToWorkerType.ChildDisposed]: { callId: number }\n /** The RPC correlation id of the completed write. */\n [HostToWorkerType.ScratchWritten]: { callId: number }\n /** The RPC correlation id and read content (absent content = file missing). */\n [HostToWorkerType.ScratchReadResult]: { callId: number; content?: string }\n}\n\n/**\n * One worker→host message of tag `T`; unparameterized, the closed union over\n * every tag (a discriminated union — `switch` on `type` narrows).\n */\nexport type WorkerToHostMessage<T extends WorkerToHostType = WorkerToHostType> =\n { [K in T]: { type: K } & WorkerToHostPayloads[K] }[T]\n\n/**\n * One host→worker message of tag `T`; unparameterized, the closed union over\n * every tag (a discriminated union — `switch` on `type` narrows).\n */\nexport type HostToWorkerMessage<T extends HostToWorkerType = HostToWorkerType> =\n { [K in T]: { type: K } & HostToWorkerPayloads[K] }[T]\n\n/** A worker message failed the runtime protocol checks at the untrusted thread boundary. */\nexport class WorkflowProtocolError extends Error {\n constructor(detail: string) {\n super(`invalid workflow worker message: ${detail}`)\n this.name = 'WorkflowProtocolError'\n }\n}\n\n/** Convert one JSON snapshot to a record or reject it with a path-qualified diagnostic. */\nfunction record(value: unknown, path: string): Record<string, unknown> {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n throw new WorkflowProtocolError(`${path} must be an object`)\n }\n return value as Record<string, unknown>\n}\n\n/** Reject missing, extra, or inherited wire fields. */\nfunction fields(\n value: Record<string, unknown>,\n path: string,\n required: readonly string[],\n optional: readonly string[] = [],\n): void {\n const allowed = new Set([...required, ...optional])\n for (const key of required) {\n if (!Object.hasOwn(value, key)) throw new WorkflowProtocolError(`${path}.${key} is required`)\n }\n for (const key of Object.keys(value)) {\n if (!allowed.has(key)) throw new WorkflowProtocolError(`${path}.${key} is not recognized`)\n }\n}\n\nfunction string(value: unknown, path: string, empty = true): string {\n if (typeof value !== 'string' || (!empty && value.length === 0)) {\n throw new WorkflowProtocolError(`${path} must be ${empty ? 'a string' : 'a non-empty string'}`)\n }\n return value\n}\n\nfunction integer(value: unknown, path: string, minimum: number): number {\n if (!Number.isSafeInteger(value) || (value as number) < minimum) {\n throw new WorkflowProtocolError(`${path} must be a safe integer no less than ${minimum}`)\n }\n return value as number\n}\n\nfunction optionalString(value: Record<string, unknown>, key: string, path: string): string | undefined {\n return value[key] === undefined ? undefined : string(value[key], `${path}.${key}`)\n}\n\nfunction agentInfo(value: unknown, path: string): WorkflowAgentInfo {\n const info = record(value, path)\n fields(info, path, ['seq', 'label', 'childId'], ['phase'])\n const phase = optionalString(info, 'phase', path)\n return {\n seq: integer(info.seq, `${path}.seq`, 1),\n label: string(info.label, `${path}.label`),\n ...(phase === undefined ? {} : { phase }),\n childId: string(info.childId, `${path}.childId`, false) as WorkflowAgentInfo['childId'],\n }\n}\n\nfunction agentEndInfo(value: unknown): WorkflowAgentEndInfo {\n const info = record(value, 'message.info')\n fields(info, 'message.info', ['seq', 'label', 'childId', 'outcome'], ['phase'])\n if (info.outcome !== 'completed' && info.outcome !== 'failed' && info.outcome !== 'cancelled') {\n throw new WorkflowProtocolError('message.info.outcome is not recognized')\n }\n const phase = optionalString(info, 'phase', 'message.info')\n return {\n seq: integer(info.seq, 'message.info.seq', 1),\n label: string(info.label, 'message.info.label'),\n ...(phase === undefined ? {} : { phase }),\n childId: string(info.childId, 'message.info.childId', false) as WorkflowAgentInfo['childId'],\n outcome: info.outcome,\n }\n}\n\nfunction gateInfo(value: unknown): WorkflowGateInfo {\n const gate = record(value, 'message.gate')\n fields(gate, 'message.gate', ['kind', 'message', 'resumable'])\n if (gate.kind !== 'user'\n && gate.kind !== 'back_off'\n && gate.kind !== 'no_progress'\n && gate.kind !== 'verification'\n && gate.kind !== 'infra') {\n throw new WorkflowProtocolError('message.gate.kind is not recognized')\n }\n if (typeof gate.resumable !== 'boolean') {\n throw new WorkflowProtocolError('message.gate.resumable must be a boolean')\n }\n return { kind: gate.kind, message: string(gate.message, 'message.gate.message'), resumable: gate.resumable }\n}\n\nfunction childStartRequest(value: unknown): ChildStartRequest {\n const request = record(value, 'message.request')\n fields(request, 'message.request', ['prompt'], ['schema', 'provider', 'model'])\n const schema = request.schema\n if (schema !== undefined) {\n try {\n assertObjectJsonSchema(schema)\n } catch (error: unknown) {\n throw new WorkflowProtocolError(`message.request.schema is unsupported: ${String(error)}`)\n }\n }\n const provider = optionalString(request, 'provider', 'message.request')\n const model = optionalString(request, 'model', 'message.request')\n return {\n prompt: string(request.prompt, 'message.request.prompt', false),\n ...(schema === undefined ? {} : { schema }),\n ...(provider === undefined ? {} : { provider }),\n ...(model === undefined ? {} : { model }),\n }\n}\n\nfunction workflowResult(value: unknown): WorkflowResult {\n const result = record(value, 'message.result')\n fields(result, 'message.result', ['value', 'stopReason', 'agentsStarted'], ['error', 'errorCode'])\n if (result.stopReason !== 'completed' && result.stopReason !== 'cancelled' && result.stopReason !== 'error') {\n throw new WorkflowProtocolError('message.result.stopReason is not recognized')\n }\n const error = optionalString(result, 'error', 'message.result')\n const errorCode = result.errorCode === undefined\n ? undefined\n : workflowErrorCode(result.errorCode, 'message.result.errorCode')\n if (result.stopReason === 'completed' && (error !== undefined || errorCode !== undefined)) {\n throw new WorkflowProtocolError('message.result.error and errorCode are forbidden for a completed result')\n }\n if (result.stopReason !== 'completed' && error === undefined) {\n throw new WorkflowProtocolError('message.result.error is required for a non-completed result')\n }\n return {\n value: result.value as WorkflowResult['value'],\n stopReason: result.stopReason,\n ...(error === undefined ? {} : { error }),\n ...(errorCode === undefined ? {} : { errorCode }),\n agentsStarted: integer(result.agentsStarted, 'message.result.agentsStarted', 0),\n }\n}\n\n/** Compile-time-exhaustive runtime table for the seam's closed failure taxonomy. */\nconst WORKFLOW_ERROR_CODES: { readonly [K in WorkflowErrorCode]: K } = {\n SCRIPT_PARSE: 'SCRIPT_PARSE',\n META_INVALID: 'META_INVALID',\n INVALID_ARGUMENT: 'INVALID_ARGUMENT',\n UNSUPPORTED_OPTION: 'UNSUPPORTED_OPTION',\n UNSUPPORTED_SCHEMA: 'UNSUPPORTED_SCHEMA',\n AGENT_CAP: 'AGENT_CAP',\n ITEM_CAP: 'ITEM_CAP',\n AGENT_START: 'AGENT_START',\n AGENT_RESULT: 'AGENT_RESULT',\n JOURNAL_DIVERGENCE: 'JOURNAL_DIVERGENCE',\n RESULT_UNSERIALIZABLE: 'RESULT_UNSERIALIZABLE',\n CANCELLED: 'CANCELLED',\n}\n\n/** Decode one machine-routable workflow failure code. */\nfunction workflowErrorCode(value: unknown, path: string): WorkflowErrorCode {\n if (typeof value !== 'string' || !Object.hasOwn(WORKFLOW_ERROR_CODES, value)) {\n throw new WorkflowProtocolError(`${path} is not recognized`)\n }\n return WORKFLOW_ERROR_CODES[value as WorkflowErrorCode]\n}\n\nfunction journalEntry(value: unknown): WorkflowJournalEntry {\n const entry = record(value, 'message.entry')\n const kind = string(entry.kind, 'message.entry.kind', false)\n const fingerprint = string(entry.fingerprint, 'message.entry.fingerprint', false)\n if (!/^[a-f0-9]{64}$/u.test(fingerprint)) {\n throw new WorkflowProtocolError('message.entry.fingerprint must be a lowercase SHA-256 digest')\n }\n const base = {\n ordinal: integer(entry.ordinal, 'message.entry.ordinal', 1),\n callId: journalCallId(entry.callId),\n fingerprint,\n }\n switch (kind) {\n case 'agent':\n fields(entry, 'message.entry', ['kind', 'ordinal', 'callId', 'fingerprint', 'seq', 'result'])\n return { ...base, kind, seq: integer(entry.seq, 'message.entry.seq', 1), result: entry.result as JsonValue }\n case 'phase':\n fields(entry, 'message.entry', ['kind', 'ordinal', 'callId', 'fingerprint', 'title'])\n return { ...base, kind, title: string(entry.title, 'message.entry.title', false) }\n case 'log':\n fields(entry, 'message.entry', ['kind', 'ordinal', 'callId', 'fingerprint', 'message'])\n return { ...base, kind, message: string(entry.message, 'message.entry.message') }\n case 'scratch-write':\n case 'await-user':\n fields(entry, 'message.entry', ['kind', 'ordinal', 'callId', 'fingerprint'])\n return { ...base, kind }\n case 'scratch-read': {\n fields(entry, 'message.entry', ['kind', 'ordinal', 'callId', 'fingerprint'], ['content'])\n const content = optionalString(entry, 'content', 'message.entry')\n return { ...base, kind, ...(content === undefined ? {} : { content }) }\n }\n default:\n throw new WorkflowProtocolError('message.entry.kind is not recognized')\n }\n}\n\n/** Decode one non-empty deterministic positive-integer call path. */\nfunction journalCallId(value: unknown): readonly [number, ...number[]] {\n if (!Array.isArray(value) || value.length === 0) {\n throw new WorkflowProtocolError('message.entry.callId must be a non-empty integer array')\n }\n return value.map((part, index) => integer(part, `message.entry.callId[${index}]`, 1)) as [number, ...number[]]\n}\n\n/**\n * Decode and detach one worker→host message before any observer, filesystem,\n * or subagent side effect. The worker is model-script controlled after a VM\n * escape, so TypeScript's protocol union is not evidence at this boundary.\n * @param value - raw structured-clone payload received from the Worker.\n * @param maxBytes - maximum UTF-8 JSON size accepted for one frame.\n * @returns a detached, strictly validated protocol message.\n */\nexport function decodeWorkerToHostMessage(value: unknown, maxBytes = Number.MAX_SAFE_INTEGER): WorkerToHostMessage {\n let detached: unknown\n try {\n detached = snapshotJsonValue(value)\n } catch (error: unknown) {\n throw new WorkflowProtocolError(`message could not be read as JSON data: ${String(error)}`)\n }\n if (detached === undefined) throw new WorkflowProtocolError('message must be lossless JSON data')\n const encoded = JSON.stringify(detached)\n if (Buffer.byteLength(encoded, 'utf8') > maxBytes) {\n throw new WorkflowProtocolError(`message exceeds the ${maxBytes}-byte protocol limit`)\n }\n const message = record(detached, 'message')\n // The exhaustive switch below validates membership before this asserted enum leaves the decoder.\n const type = string(message.type, 'message.type', false) as WorkerToHostType\n switch (type) {\n case WorkerToHostType.Ready:\n fields(message, 'message', ['type'])\n return { type }\n case WorkerToHostType.Phase:\n fields(message, 'message', ['type', 'title'])\n return { type, title: string(message.title, 'message.title', false) }\n case WorkerToHostType.Log:\n fields(message, 'message', ['type', 'message'])\n return { type, message: string(message.message, 'message.message') }\n case WorkerToHostType.AgentStart:\n fields(message, 'message', ['type', 'info'])\n return { type, info: agentInfo(message.info, 'message.info') }\n case WorkerToHostType.AgentEnd:\n fields(message, 'message', ['type', 'info'])\n return { type, info: agentEndInfo(message.info) }\n case WorkerToHostType.Gate:\n fields(message, 'message', ['type', 'gate'])\n return { type, gate: gateInfo(message.gate) }\n case WorkerToHostType.JournalCommit:\n fields(message, 'message', ['type', 'entry'])\n return { type, entry: journalEntry(message.entry) }\n case WorkerToHostType.ChildStart:\n fields(message, 'message', ['type', 'callId', 'request'])\n return { type, callId: integer(message.callId, 'message.callId', 1), request: childStartRequest(message.request) }\n case WorkerToHostType.ChildDispose:\n fields(message, 'message', ['type', 'callId'])\n return { type, callId: integer(message.callId, 'message.callId', 1) }\n case WorkerToHostType.ScratchWrite:\n fields(message, 'message', ['type', 'callId', 'name', 'content'])\n return {\n type,\n callId: integer(message.callId, 'message.callId', 1),\n name: string(message.name, 'message.name', false),\n content: string(message.content, 'message.content'),\n }\n case WorkerToHostType.ScratchRead:\n fields(message, 'message', ['type', 'callId', 'name'])\n return {\n type,\n callId: integer(message.callId, 'message.callId', 1),\n name: string(message.name, 'message.name', false),\n }\n case WorkerToHostType.Result:\n fields(message, 'message', ['type', 'result'])\n return { type, result: workflowResult(message.result) }\n default:\n throw new WorkflowProtocolError(`message.type ${JSON.stringify(type)} is not recognized`)\n }\n}\n","/**\n * Host side of one workflow run. The first worker result, unexpected death, or\n * cancellation-grace expiry owns settlement and closes message admission.\n * Pending starts share one abort signal; published children share idempotent\n * cleanup, and quiescence waits for both while synthesizing any missing end events.\n * @module @deepseek-ai/dsh-workflow-worker-thread/host\n */\n\nimport { Buffer } from 'node:buffer'\nimport { randomBytes } from 'node:crypto'\nimport { constants } from 'node:fs'\nimport { chmod, link, lstat, mkdir, open, readdir, rename, rm } from 'node:fs/promises'\nimport { tmpdir } from 'node:os'\nimport { join } from 'node:path'\nimport { Worker } from 'node:worker_threads'\nimport type { WorkerOptions } from 'node:worker_threads'\nimport { fileURLToPath } from 'node:url'\nimport type { Context } from '@deepseek-ai/cordis'\nimport type { Agent } from '@deepseek-ai/dsh-agent'\nimport { snapshotJsonValue } from '@deepseek-ai/dsh-session'\nimport type SubagentRuntime from '@deepseek-ai/dsh-subagent'\nimport type { SubagentRun } from '@deepseek-ai/dsh-subagent'\nimport type { WorkflowAgentEndInfo, WorkflowAgentInfo, WorkflowMeta, WorkflowRun, WorkflowRunId } from '@deepseek-ai/dsh-workflow'\nimport { WorkflowError, type WorkflowResult } from './compat-seam.ts'\nimport { renderThrown } from './realm.ts'\nimport type { ExecutionObserver } from './runtime.ts'\nimport {\n decodeWorkerToHostMessage,\n HostToWorkerType,\n WorkerToHostType,\n WorkflowProtocolError,\n} from './protocol.ts'\nimport type { HostToWorkerPayloads, WorkerToHostMessage } from './protocol.ts'\nimport type { ChildResult, ChildStartRequest, WorkerHostLimits, WorkerInit, WorkflowCheckpoint, WorkflowScratchPort } from './types.ts'\n\n/** Single-component scratch file name grammar (mirrors the worker-side validation). */\nconst SCRATCH_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]*$/\n\n/** One published child and its shared quiescent-disposal transaction. */\ninterface ChildRecord {\n readonly run: SubagentRun\n resultState: 'pending' | 'settled' | 'failed'\n disposal?: Promise<void>\n}\n\n/** Identity and accounted size of one retained scratch file. */\ninterface ScratchFileState {\n readonly device: number\n readonly inode: number\n size: number\n}\n\n/** Host accounting for the run's private scratch directory. */\ninterface ScratchState {\n readonly dir: string\n readonly device: number\n readonly inode: number\n readonly files: Map<string, ScratchFileState>\n totalBytes: number\n}\n\n/**\n * Build the credential-free environment inherited by a workflow worker.\n * Windows receives only its absolute temp directory; source workers may also\n * receive the tsx paths-map pin used by the source launcher.\n * @param platform - host platform, overridable for tests.\n * @param tsconfigPath - optional source-launcher tsconfig pin.\n * @returns the environment passed to the Worker constructor.\n */\nexport function workerSpawnEnv(\n platform: NodeJS.Platform = process.platform,\n tsconfigPath?: string,\n): NodeJS.ProcessEnv {\n const env: NodeJS.ProcessEnv = {}\n if (platform === 'win32') {\n const tmp = tmpdir()\n env.TMP = tmp\n env.TEMP = tmp\n }\n if (tsconfigPath !== undefined) env.TSX_TSCONFIG_PATH = tsconfigPath\n return env\n}\n\n/** Resolve the built worker or source-mode tsx bootstrap for one isolated run. */\nfunction resolveWorkerSpawn(init: WorkerInit): { entry: string | URL; options: WorkerOptions } {\n /* v8 ignore next 3 -- built-output arm is exercised by the built-worker e2e */\n if (!import.meta.url.endsWith('.ts')) {\n return {\n entry: fileURLToPath(new URL('./worker.cjs', import.meta.url)),\n options: { workerData: init, env: workerSpawnEnv(), execArgv: [] },\n }\n }\n const workerEntry = new URL('./worker.ts', import.meta.url)\n const tsxEsmApiEntry = import.meta.resolve('tsx/esm/api')\n const tsxCjsApiEntry = import.meta.resolve('tsx/cjs/api')\n const bootstrap = [\n `import { register as registerEsm } from ${JSON.stringify(tsxEsmApiEntry)}`,\n `import { register as registerCjs } from ${JSON.stringify(tsxCjsApiEntry)}`,\n 'registerCjs()',\n 'registerEsm()',\n `await import(${JSON.stringify(workerEntry.href)})`,\n ].join('\\n')\n return {\n entry: new URL(`data:text/javascript,${encodeURIComponent(bootstrap)}`),\n options: {\n workerData: init,\n env: workerSpawnEnv(undefined, process.env.TSX_TSCONFIG_PATH),\n execArgv: [],\n },\n }\n}\n\n/**\n * One live worker-engine run — the seam's {@link WorkflowRun}, returned by\n * `start()` directly. Owns the Worker, the child registry, and the result\n * settlement; `result` never rejects. `meta` is trusted same-process data\n * borrowed as immutable by the handle and lifecycle events. The holder-bound\n * SubagentRuntime handle is captured before the\n * engine returns this run, so unloading the engine removes only the ability to\n * start another workflow; this run can still start and clean up its children.\n */\nexport class WorkerRun implements WorkflowRun {\n /** Settles exactly once with the run's outcome; never rejects. */\n readonly result: Promise<WorkflowResult>\n private settleResolve!: (result: WorkflowResult) => void\n private settled = false\n /** Cumulative spend from the terminal worker result (includes queued reservations). */\n private finalAgentSpend = 0\n /** A Result/death/grace outcome atomically won before teardown callbacks. */\n private terminalClaimed = false\n /** The first death signal closes worker-message admission and owns failure-time cleanup. */\n private workerDeathObserved = false\n private cancelReason: string | undefined\n private graceTimer: NodeJS.Timeout | undefined\n private readonly worker: Worker\n /** Set on `exit`: the thread is gone, so posting has nowhere to go. */\n private workerGone = false\n /** The startup handshake is single-use; effect frames are forbidden before it. */\n private workerReady = false\n /** The script's Go frame is supervisor-controlled to close the observer-registration race. */\n private released = false\n /** Accepted `child-start` messages — the terminate-path `agentsStarted` (see module doc). */\n private hostStarted = 0\n /** Published children by callId; an entry leaves only after disposal settles. */\n private readonly children = new Map<number, ChildRecord>()\n /** Provider starts that have not yet fulfilled or rejected. */\n private readonly pendingStarts = new Set<Promise<void>>()\n /** Accepted child calls still starting or published; the host concurrency authority. */\n private readonly activeChildCallIds = new Set<number>()\n /** Every worker-minted RPC id is single-use across child starts and scratch calls. */\n private readonly claimedCallIds = new Set<number>()\n /** Call ids whose first frame was a child start (dispose must reference one). */\n private readonly childCallIds = new Set<number>()\n /** Child call ids whose single disposal request was already accepted. */\n private readonly disposedChildCallIds = new Set<number>()\n /** Child calls whose published handle completed host-side disposal. */\n private readonly reapedChildCallIds = new Set<number>()\n /** Child ids already projected into one observer agent-start event. */\n private readonly announcedChildren = new Set<string>()\n /** Host-published child record paired to each announced member sequence. */\n private readonly agentChildren = new Map<number, ChildRecord>()\n /** Member sequences are single-use even after their paired end. */\n private readonly announcedAgentSeqs = new Set<number>()\n /** Member sequences that already committed their one journal result. */\n private readonly committedAgentSeqs = new Set<number>()\n /** Stable host-call identities retained across attempts or committed here. */\n private readonly committedJournalCallIds = new Set<string>()\n /** Replay seed plus commits from this attempt. */\n private readonly journal: WorkflowCheckpoint['journal']\n /** Last committed host-call ordinal, including replay entries supplied at start. */\n private lastJournalOrdinal = 0\n /** Exact UTF-8 JSON-array bytes retained across this logical run's journal. */\n private journalBytes: number\n /** Entries represented by {@link journalBytes}; determines the next comma byte. */\n private journalEntries: number\n /** Started-but-not-ended agents by seq — the pairing ledger the HOST guarantees (see {@link endAgent}). */\n private readonly liveAgents = new Map<number, WorkflowAgentInfo>()\n /** Scratch operations admitted before cancellation/settlement and not yet quiescent. */\n private readonly pendingScratch = new Set<Promise<void>>()\n /** Scratch RPCs admitted over this attempt, including reads and overwrites. */\n private scratchOperations = 0\n /** Serialize scratch reads/writes so quota accounting and publication are one transaction. */\n private scratchTail: Promise<void> = Promise.resolve()\n /** Lazily verifies the existing scratch directory and computes resume accounting. */\n private scratchState: Promise<ScratchState | undefined> | undefined\n /** Scratch I/O has its own cancellation: normal script settlement drains it instead of aborting it. */\n private readonly scratchController = new AbortController()\n /** First scratch failure, retained while a worker Result waits for admitted effects. */\n private scratchFailure: string | undefined\n /** A worker Result won and is waiting for admitted scratch effects. */\n private drainingWorkerResult = false\n private readonly quiescenceWaiters: (() => void)[] = []\n /** The per-run abort fanout every child start request carries. */\n private readonly controller = new AbortController()\n /** External start signal and the exact callback installed on it, retained only until first settle/teardown. */\n private inputSignal: AbortSignal | undefined\n private inputSignalAbort: (() => void) | undefined\n private disposed: Promise<void> | undefined\n\n constructor(\n private readonly ctx: Context,\n private readonly subagents: SubagentRuntime,\n readonly id: WorkflowRunId,\n readonly meta: WorkflowMeta,\n private readonly parent: Agent,\n private readonly init: WorkerInit,\n private readonly provider: string,\n private readonly disposeGraceMs: number,\n private readonly observer: ExecutionObserver,\n signal: AbortSignal | undefined,\n private readonly scratchDir: string | undefined,\n private readonly hostLimits: WorkerHostLimits,\n private readonly deferStart = false,\n private readonly scratchPort: WorkflowScratchPort | undefined = undefined,\n ) {\n this.result = new Promise<WorkflowResult>((resolve) => { this.settleResolve = resolve })\n const initialJournal = JSON.stringify(init.journal ?? [])\n this.journalBytes = Buffer.byteLength(initialJournal, 'utf8')\n this.journalEntries = init.journal?.length ?? 0\n this.journal = [...(init.journal ?? [])]\n for (const entry of init.journal ?? []) {\n this.committedJournalCallIds.add(entry.callId.join('.'))\n this.lastJournalOrdinal = entry.ordinal\n }\n if (this.journalBytes > hostLimits.maxJournalBytes) {\n throw new WorkflowError(\n `workflow journal exceeds the ${hostLimits.maxJournalBytes}-byte limit before this attempt starts`,\n 'INVALID_ARGUMENT',\n )\n }\n // workerData rides the structured clone: args are plain JSON by the seam\n // contract, so the clone is total and doubles as the caller-isolation\n // copy (a clone failure throws loud out of start()).\n const { entry, options } = resolveWorkerSpawn(init)\n this.worker = new Worker(entry, options)\n this.worker.on('message', (message: unknown) => { this.onRawMessage(message) })\n this.worker.on('error', (error) => { this.onWorkerDeath(`workflow worker failed: ${renderThrown(error)}`, false) })\n /* v8 ignore next -- messageerror: not constructible from the engine's own protocol (every payload is JSON data) */\n this.worker.on('messageerror', (error) => { this.onWorkerDeath(`workflow worker message failed to deserialize: ${renderThrown(error)}`, false) })\n this.worker.on('exit', (code) => {\n this.workerGone = true\n this.onWorkerDeath(`workflow worker exited before the run settled (exit code ${code})`, true)\n })\n if (signal?.aborted) {\n this.cancel('workflow start signal already aborted')\n } else if (signal !== undefined) {\n const onAbort = (): void => {\n this.detachInputSignal()\n this.cancel('workflow signal aborted')\n }\n this.inputSignal = signal\n this.inputSignalAbort = onAbort\n signal.addEventListener('abort', onAbort, { once: true })\n }\n }\n\n /**\n * Cancel the run: the worker is told (its hooks start throwing and the\n * script dies at its next await), the required signal shared by every child\n * start is aborted, and the grace timer\n * arms: a run still unsettled `disposeGraceMs` later force-settles\n * `cancelled` and its worker is TERMINATED. Idempotent; the first reason\n * wins.\n * @param reason - human-readable cause (default `'workflow cancelled'`).\n */\n cancel(reason?: string): void {\n // A settled run has nothing left to cancel, and a terminal source claimed\n // before its cleanup callbacks must exclude cancellation reentered by one\n // of those callbacks. Without the settled guard the\n // ordinary consumer path (await result, then dispose -> cancel) would arm\n // a grace timer nothing ever clears, pinning the run and its Worker\n // closure until the grace expires - a bounded leak per completed run.\n if (this.settled || (this.terminalClaimed && !this.drainingWorkerResult) || this.cancelReason !== undefined) return\n this.cancelReason = reason ?? 'workflow cancelled'\n this.post(HostToWorkerType.Cancel, { reason: this.cancelReason })\n this.abortChildren(this.cancelReason)\n if (!this.scratchController.signal.aborted) this.scratchController.abort(this.cancelReason)\n this.graceTimer = setTimeout(() => {\n // Cancellation already owns the race through cancelReason; close the\n // terminal boundary explicitly before observer teardown callbacks.\n this.terminalClaimed = true\n // The worker may no longer speak (it is about to be terminated): pair\n // every stranded start before the run settles, so ends precede\n // workflow/end.\n this.endStrandedAgents()\n this.settleResult(this.cancelledResult(this.observedAgentSpend()))\n void this.worker.terminate()\n }, this.disposeGraceMs)\n // unref'd: an armed grace timer must never hold the process open.\n this.graceTimer.unref()\n }\n\n /**\n * Release a parked script gate. A no-op once the run settled or a cancel is\n * already in flight (the cancel path owns the terminal state then).\n */\n resume(): void {\n if (this.settled || this.terminalClaimed || this.cancelReason !== undefined) return\n this.post(HostToWorkerType.Resume, {})\n }\n\n /** Release a deferred fresh attempt exactly once. */\n release(): void {\n if (this.released || this.settled || this.cancelReason !== undefined) return\n this.released = true\n if (this.workerReady) this.post(HostToWorkerType.Go, {})\n }\n\n /** Return replay authority only after terminal settlement. */\n checkpoint(): WorkflowCheckpoint | undefined {\n if (!this.settled) return undefined\n const initialSpend = this.init.initialAgentSpend ?? 0\n const cumulativeSpend = Math.max(this.observedAgentSpend(), this.finalAgentSpend)\n return {\n journal: this.journal.map(entry => ({ ...entry, callId: [...entry.callId] as [number, ...number[]] })),\n agentSpend: cumulativeSpend,\n agentSeq: Math.max(\n cumulativeSpend,\n this.init.initialAgentSeq ?? 0,\n (this.init.initialAgentSeq ?? 0) + Math.max(0, cumulativeSpend - initialSpend),\n ...this.announcedAgentSeqs,\n ...this.journal.flatMap(entry => entry.kind === 'agent' ? [entry.seq] : []),\n ),\n }\n }\n\n /**\n * Cancel + bounded settle + termination. Host-drives every registered\n * child's disposal IMMEDIATELY — a wedged worker can relay no dispose RPC,\n * and deferring child teardown to the post-terminate reap would spend the\n * whole grace waiting for a quiescence that cannot start, then return with\n * the disposals still in flight — so child disposal overlaps the same\n * grace the worker gets to settle (the worker's own dispose RPCs join the\n * shared per-child disposal). Waits (at most the grace) for the result and\n * child quiescence, then terminates the worker unconditionally — the\n * thread never outlives its run — and reaps whatever children remain\n * (their disposal is contained, not awaited past the grace, the same\n * abandonment the seam documents for a slow-disposing child). Idempotent;\n * safe on every path.\n * @returns resolves when the run's resources are released or abandoned.\n */\n dispose(): Promise<void> {\n if (this.disposed !== undefined) return this.disposed\n // Claim the public transaction BEFORE its body invokes child/provider\n // disposal. A raw provider callback can reenter handle.dispose(); it must\n // join this promise rather than start a second traversal.\n const claimed = Promise.withResolvers<undefined>()\n this.disposed = claimed.promise\n void (async () => {\n this.detachInputSignal()\n this.cancel('workflow disposed')\n // cancel() deliberately becomes a no-op after terminal settlement, but\n // disposal still owns every registered child. Reap independently so an\n // already-settled workflow cannot wait on child quiescence before it has\n // started the surviving children's disposals. On an unsettled run this\n // joins the cancel path through the per-call cancellation/disposal gates.\n this.reapChildren('workflow disposed')\n await Promise.race([\n (async () => {\n await this.result\n await this.runQuiescence()\n })(),\n sleep(this.disposeGraceMs),\n ])\n await this.worker.terminate()\n this.reapChildren('workflow disposed')\n })().then(\n () => { claimed.resolve(undefined) },\n /* v8 ignore next -- result/quiescence never reject and Worker.terminate is the only external promise */\n (error: unknown) => { claimed.reject(error) },\n )\n return this.disposed\n }\n\n /** Post one message to the worker (payload looked up from the tag's map entry), tolerating a thread that is already gone. */\n private post<T extends HostToWorkerType>(type: T, payload: HostToWorkerPayloads[T]): void {\n if (this.workerGone || this.workerDeathObserved) return\n try {\n this.worker.postMessage({ type, ...payload })\n } catch (error: unknown) {\n // Only a teardown race can land here (every engine message is JSON\n // data, so serialization cannot fail); there is nothing left to\n // deliver to — log and move on.\n /* v8 ignore next -- postMessage teardown race (a throw between exit and its event): not constructible in-process */\n this.ctx.logger.warn(`workflow-worker-thread: postMessage failed: ${renderThrown(error)}`)\n }\n }\n\n /** Decode one untrusted worker frame and contain protocol failures to this run. */\n private onRawMessage(raw: unknown): void {\n if (this.workerDeathObserved || this.terminalClaimed) return\n try {\n this.onMessage(decodeWorkerToHostMessage(raw, this.hostLimits.maxProtocolMessageBytes))\n } catch (error: unknown) {\n const detail = error instanceof WorkflowProtocolError ? error.message : renderThrown(error)\n this.onWorkerDeath(`workflow worker protocol violation: ${detail}`, false)\n void this.worker.terminate()\n }\n }\n\n private onMessage(message: WorkerToHostMessage): void {\n // Node may emit `error`, then deliver an already-queued `message`, then\n // emit `exit`. The first death signal is the host's logical delivery\n // barrier: nothing arriving afterward may create a child, narrate after\n // workflow/end, or compete with the chosen outcome.\n if (!this.workerReady && message.type !== WorkerToHostType.Ready) {\n throw new WorkflowProtocolError(`${message.type} arrived before ready`)\n }\n switch (message.type) {\n case WorkerToHostType.Ready:\n if (this.workerReady) throw new WorkflowProtocolError('ready arrived more than once')\n this.workerReady = true\n if (!this.deferStart || this.released) this.post(HostToWorkerType.Go, {})\n break\n case WorkerToHostType.Phase:\n // Post-cancel narration is suppressed host-side: worker-side the\n // hooks throw once the cancel message is PROCESSED, but narration\n // already in flight (or emitted while the cancel crossed the\n // boundary) must not reach observers — nothing is emitted after\n // cancel() returns.\n this.assertEventText(message.title, 'phase title')\n if (this.cancelReason === undefined && !this.terminalClaimed) this.observer.phase(message.title)\n break\n case WorkerToHostType.Log:\n this.assertEventText(message.message, 'log message')\n if (this.cancelReason === undefined && !this.terminalClaimed) this.observer.log(message.message)\n break\n case WorkerToHostType.AgentStart:\n this.onAgentStart(message.info)\n break\n case WorkerToHostType.AgentEnd:\n // NOT suppressed on cancel: cancelled children report their paired\n // agent-end with outcome 'cancelled'. The gate (with the termination\n // paths' synthesis) is what makes the one-pair-per-started-child\n // contract hold on every stop path.\n this.onAgentEnd(message.info)\n break\n case WorkerToHostType.Gate:\n this.assertEventText(message.gate.message, 'gate message')\n if (this.cancelReason === undefined && !this.terminalClaimed) this.observer.gate(message.gate)\n break\n case WorkerToHostType.JournalCommit:\n this.onJournalCommit(message.entry)\n break\n case WorkerToHostType.ScratchWrite:\n void this.onScratchWrite(message.callId, message.name, message.content)\n break\n case WorkerToHostType.ScratchRead:\n void this.onScratchRead(message.callId, message.name)\n break\n case WorkerToHostType.ChildStart:\n this.onChildStart(message.callId, message.request)\n break\n case WorkerToHostType.ChildDispose:\n this.onChildDispose(message.callId)\n break\n case WorkerToHostType.Result:\n this.onResult(message.result)\n break\n }\n }\n\n /** Why a ready provider result may no longer be admitted to the worker. */\n private childAdmissionFailure(): { reason: string; rendered: string } | undefined {\n if (this.cancelReason !== undefined) {\n return { reason: this.cancelReason, rendered: `workflow run cancelled: ${this.cancelReason}` }\n }\n if (this.workerDeathObserved) {\n return { reason: 'workflow worker gone', rendered: 'workflow worker is no longer available' }\n }\n if (this.terminalClaimed) {\n return { reason: 'workflow settled', rendered: 'workflow run already settled' }\n }\n return undefined\n }\n\n /** Reserve a worker RPC id exactly once across every side-effecting family. */\n private claimCallId(callId: number, operation: string): void {\n if (this.claimedCallIds.has(callId)) {\n throw new WorkflowProtocolError(`${operation} reused callId ${callId}`)\n }\n this.claimedCallIds.add(callId)\n }\n\n /** Bound observer text before retaining or dispatching worker-controlled content. */\n private assertEventText(value: string, label: string): void {\n if (Buffer.byteLength(value, 'utf8') > this.hostLimits.maxEventTextBytes) {\n throw new WorkflowProtocolError(`${label} exceeds the ${this.hostLimits.maxEventTextBytes}-byte limit`)\n }\n }\n\n /** Admit one lifecycle start only for a child the host actually published. */\n private onAgentStart(info: WorkflowAgentInfo): void {\n if (this.cancelReason !== undefined || this.terminalClaimed) return\n this.assertEventText(info.label, 'agent label')\n if (info.phase !== undefined) this.assertEventText(info.phase, 'agent phase')\n const priorSequence = this.init.initialAgentSeq ?? 0\n if (info.seq <= priorSequence) {\n throw new WorkflowProtocolError(`agent-start seq ${info.seq} does not advance prior seq ${priorSequence}`)\n }\n if (info.seq > priorSequence + this.hostStarted) {\n throw new WorkflowProtocolError(`agent-start seq ${info.seq} exceeds the host-observed sequence range`)\n }\n if (this.announcedAgentSeqs.has(info.seq)) {\n throw new WorkflowProtocolError(`agent-start reused seq ${info.seq}`)\n }\n if (this.announcedChildren.has(info.childId)) {\n throw new WorkflowProtocolError(`agent-start reused child id ${JSON.stringify(info.childId)}`)\n }\n const published = [...this.children.values()].find(record => record.run.id === info.childId)\n if (!published) {\n throw new WorkflowProtocolError(`agent-start references unpublished child ${JSON.stringify(info.childId)}`)\n }\n this.announcedChildren.add(info.childId)\n this.announcedAgentSeqs.add(info.seq)\n this.agentChildren.set(info.seq, published)\n this.liveAgents.set(info.seq, info)\n this.observer.agentStart(info)\n }\n\n /** Require one end to match the exact start snapshot before forwarding it. */\n private onAgentEnd(info: WorkflowAgentEndInfo): void {\n const start = this.liveAgents.get(info.seq)\n if (start === undefined) {\n if (this.cancelReason !== undefined || this.terminalClaimed) return\n throw new WorkflowProtocolError(`agent-end references unknown seq ${info.seq}`)\n }\n if (start.label !== info.label || start.phase !== info.phase || start.childId !== info.childId) {\n throw new WorkflowProtocolError(`agent-end metadata does not match agent-start seq ${info.seq}`)\n }\n // Result and cancel use the same port but the child's promise callback can\n // already have posted its completed end when the host accepts cancel.\n // Cancellation owns that race and the journal frame is suppressed, so\n // normalize the still-live pair instead of misclassifying it as corrupt.\n if (this.cancelReason !== undefined) {\n this.endAgent({ ...start, outcome: 'cancelled' })\n return\n }\n const child = this.agentChildren.get(info.seq)\n if (child === undefined) {\n throw new WorkflowProtocolError(`agent-end seq ${info.seq} lost its host child correlation`)\n }\n const committed = this.committedAgentSeqs.has(info.seq)\n if (info.outcome === 'cancelled') {\n throw new WorkflowProtocolError(`agent-end seq ${info.seq} reported cancellation before the run was cancelled`)\n }\n if (info.outcome === 'completed' && (!committed || child.resultState !== 'settled')) {\n throw new WorkflowProtocolError(`agent-end seq ${info.seq} settled without a committed result`)\n }\n if (info.outcome === 'failed'\n && !((committed && child.resultState === 'settled') || (!committed && child.resultState === 'failed'))) {\n throw new WorkflowProtocolError(`agent-end seq ${info.seq} does not match the host-observed child result`)\n }\n this.endAgent(info)\n }\n\n /** Commit one completed host call in monotonic order and at most once. */\n private onJournalCommit(entry: Parameters<ExecutionObserver['journalCommit']>[0]): void {\n if (this.cancelReason !== undefined || this.terminalClaimed) return\n if (entry.ordinal !== this.lastJournalOrdinal + 1) {\n throw new WorkflowProtocolError(`journal-commit ordinal ${entry.ordinal} does not follow ${this.lastJournalOrdinal}`)\n }\n const callKey = entry.callId.join('.')\n if (this.committedJournalCallIds.has(callKey)) {\n throw new WorkflowProtocolError(`journal-commit reused call identity ${JSON.stringify(entry.callId)}`)\n }\n if (entry.kind === 'agent') {\n if (!this.liveAgents.has(entry.seq)) {\n throw new WorkflowProtocolError(`agent journal commit references unknown live seq ${entry.seq}`)\n }\n if (this.agentChildren.get(entry.seq)?.resultState !== 'settled') {\n throw new WorkflowProtocolError(`agent journal commit seq ${entry.seq} arrived before a host-observed child result`)\n }\n if (this.committedAgentSeqs.has(entry.seq)) {\n throw new WorkflowProtocolError(`agent journal commit reused seq ${entry.seq}`)\n }\n }\n const encodedEntry = JSON.stringify(entry)\n const entryBytes = Buffer.byteLength(encodedEntry, 'utf8')\n const addedBytes = entryBytes + (this.journalEntries === 0 ? 0 : 1)\n if (addedBytes > this.hostLimits.maxJournalBytes - this.journalBytes) {\n throw new WorkflowProtocolError(\n `journal-commit exceeds the ${this.hostLimits.maxJournalBytes}-byte journal limit`,\n )\n }\n if (entry.kind === 'agent') this.committedAgentSeqs.add(entry.seq)\n this.committedJournalCallIds.add(callKey)\n this.journal.push(entry)\n this.lastJournalOrdinal = entry.ordinal\n this.journalBytes += addedBytes\n this.journalEntries += 1\n this.observer.journalCommit(entry)\n }\n\n private onChildStart(callId: number, request: ChildStartRequest): void {\n this.claimCallId(callId, 'child-start')\n this.childCallIds.add(callId)\n if (Buffer.byteLength(request.prompt, 'utf8') > this.hostLimits.maxChildPromptBytes) {\n throw new WorkflowProtocolError(`child-start prompt exceeds the ${this.hostLimits.maxChildPromptBytes}-byte limit`)\n }\n const alreadySpent = this.init.initialAgentSpend ?? 0\n if (alreadySpent + this.hostStarted >= this.init.limits.maxTotalAgents) {\n throw new WorkflowProtocolError('child-start exceeds the host-enforced total agent cap')\n }\n if (this.activeChildCallIds.size >= this.init.limits.maxConcurrentAgents) {\n throw new WorkflowProtocolError('child-start exceeds the host-enforced concurrent agent cap')\n }\n const initialFailure = this.childAdmissionFailure()\n if (initialFailure !== undefined) {\n // Refuse after a terminal boundary: a child must never start on an\n // already-aborted signal (a provider subscribing only to future abort\n // events would never observe it).\n this.post(HostToWorkerType.ChildStartError, { callId, rendered: initialFailure.rendered })\n return\n }\n this.hostStarted += 1\n this.activeChildCallIds.add(callId)\n const task = this.startChild(callId, request)\n this.pendingStarts.add(task)\n void task.then(\n () => { this.finishPendingStart(task, callId) },\n /* v8 ignore next -- startChild contains provider and cleanup failures */\n () => { this.finishPendingStart(task, callId) },\n )\n }\n\n /** Await one provider-owned startup transaction and publish only while admitted. */\n private async startChild(callId: number, request: ChildStartRequest): Promise<void> {\n let run: SubagentRun\n try {\n run = await this.subagents.start(this.provider, {\n prompt: [{ type: 'text', text: request.prompt }],\n parent: this.parent,\n signal: this.controller.signal,\n ...request.schema !== undefined ? { outputSchema: request.schema } : {},\n ...request.provider !== undefined || request.model !== undefined\n ? {\n agentOptions: {\n ...request.provider !== undefined ? { provider: request.provider } : {},\n ...request.model !== undefined ? { model: request.model } : {},\n },\n }\n : {},\n })\n } catch (error: unknown) {\n const failure = this.childAdmissionFailure()\n this.post(HostToWorkerType.ChildStartError, {\n callId,\n rendered: failure?.rendered ?? renderThrown(error),\n })\n return\n }\n const failure = this.childAdmissionFailure()\n if (failure !== undefined) {\n this.post(HostToWorkerType.ChildStartError, { callId, rendered: failure.rendered })\n try {\n await run.dispose()\n } catch (error: unknown) {\n this.ctx.logger.warn(`workflow-worker-thread: refused child dispose failed: ${renderThrown(error)}`)\n }\n return\n }\n\n const record: ChildRecord = { run, resultState: 'pending' }\n this.children.set(callId, record)\n // Attach result forwarding before publishing the child handle. Because the\n // callback itself runs in a later microtask, ChildStarted is still posted\n // first even for an already-settled scripted provider.\n const forwardResult = run.result.then<() => void, () => void>(\n (result) => {\n try {\n const snapshot = snapshotJsonValue<ChildResult>({\n output: result.output,\n ...result.structured !== undefined ? { structured: result.structured } : {},\n stopReason: result.stopReason,\n })\n if (snapshot === undefined) throw new TypeError('child result is not losslessly JSON-serializable')\n record.resultState = 'settled'\n return () => { this.post(HostToWorkerType.ChildSettled, { callId, result: snapshot }) }\n } catch (error: unknown) {\n record.resultState = 'failed'\n const rendered = `workflow child result could not cross the worker boundary: ${renderThrown(error)}`\n return () => { this.post(HostToWorkerType.ChildFailed, { callId, rendered }) }\n }\n },\n (error: unknown) => {\n record.resultState = 'failed'\n const rendered = renderThrown(error)\n return () => { this.post(HostToWorkerType.ChildFailed, { callId, rendered }) }\n },\n )\n this.post(HostToWorkerType.ChildStarted, { callId, childId: run.id })\n void forwardResult.then((forward) => { forward() })\n }\n\n private onChildDispose(callId: number): void {\n if (!this.childCallIds.has(callId)) {\n throw new WorkflowProtocolError(`child-dispose references unknown callId ${callId}`)\n }\n if (this.disposedChildCallIds.has(callId)) {\n throw new WorkflowProtocolError(`child-dispose repeated callId ${callId}`)\n }\n this.disposedChildCallIds.add(callId)\n const record = this.children.get(callId)\n if (record === undefined) {\n if (!this.reapedChildCallIds.has(callId)) {\n throw new WorkflowProtocolError(`child-dispose references child ${callId} before host-side disposal`)\n }\n // A dispose() drive or death reap beat the RPC, so the worker-side\n // wrapper is still owed its acknowledgement.\n this.post(HostToWorkerType.ChildDisposed, { callId })\n return\n }\n // disposeChild never rejects (containment is inside), so the ack always follows.\n void this.disposeChild(callId, record).then(() => { this.post(HostToWorkerType.ChildDisposed, { callId }) })\n }\n\n /**\n * Start (or join) one registered child's disposal; the registry entry\n * leaves when it settles. Memoized per callId: the worker's dispose RPC,\n * the dispose() host drive, and the reap can all land on the same child —\n * the child's `dispose()` runs once and every caller awaits that one\n * settlement. A rejection is contained (the subagent seam's dispose() is\n * not supposed to reject, but a backend that does anyway must not break\n * quiescence): logged, and the child still leaves the registry.\n * @param callId - the child's registry key.\n * @param record - the registered child (the caller looked it up).\n * @returns resolves when the disposal settled either way; never rejects.\n */\n private disposeChild(callId: number, record: ChildRecord): Promise<void> {\n if (record.disposal !== undefined) return record.disposal\n record.disposal = Promise.resolve()\n .then(() => record.run.dispose())\n .catch((error: unknown) => {\n this.ctx.logger.warn(`workflow-worker-thread: child dispose failed: ${renderThrown(error)}`)\n })\n .then(() => { this.finishChild(callId) })\n return record.disposal\n }\n\n /** Drop a child record and release quiescence waiters when all work ends. */\n private finishChild(callId: number): void {\n this.children.delete(callId)\n this.reapedChildCallIds.add(callId)\n this.activeChildCallIds.delete(callId)\n this.notifyRunQuiescence()\n }\n\n /** Retire one provider startup transaction. */\n private finishPendingStart(task: Promise<void>, callId: number): void {\n this.pendingStarts.delete(task)\n if (!this.children.has(callId)) this.activeChildCallIds.delete(callId)\n this.notifyRunQuiescence()\n }\n\n /** Release waiters only after provider, child, and scratch work ends. */\n private notifyRunQuiescence(): void {\n if (this.children.size !== 0 || this.pendingStarts.size !== 0 || this.pendingScratch.size !== 0) return\n for (const waiter of this.quiescenceWaiters.splice(0)) waiter()\n }\n\n /** Resolves once every pending start, child, and admitted scratch operation is quiescent. */\n private runQuiescence(): Promise<void> {\n if (this.children.size === 0 && this.pendingStarts.size === 0 && this.pendingScratch.size === 0) {\n return Promise.resolve()\n }\n return new Promise((resolve) => { this.quiescenceWaiters.push(resolve) })\n }\n\n /** Abort + dispose every registered child (worker death / final teardown); disposal is contained, not awaited. */\n private reapChildren(reason: string): void {\n this.abortChildren(this.cancelReason ?? reason)\n for (const [callId, record] of [...this.children]) {\n void this.disposeChild(callId, record)\n }\n }\n\n /** Abort the one canonical signal shared by pending and published children. */\n private abortChildren(reason: string): void {\n if (!this.controller.signal.aborted) this.controller.abort(reason)\n }\n\n private onResult(result: WorkflowResult): void {\n // onRawMessage excludes a late duplicate or a Result queued behind another\n // terminal source before dispatch reaches this method.\n // First-wins is decided when the Result message reaches the host. If no\n // external cancellation was already in flight, this result won. Reaping a\n // stray child below may synchronously reenter cancel() through provider\n // callbacks, but that internal post-result cleanup must not retroactively\n // rewrite the worker result that arrived first.\n const cancellationWasRequested = this.cancelReason !== undefined\n const observedSpend = this.observedAgentSpend()\n if (result.agentsStarted < observedSpend) {\n throw new WorkflowProtocolError(\n `result agentsStarted ${result.agentsStarted} is below the host-observed spend ${observedSpend}`,\n )\n }\n if (result.agentsStarted > this.init.limits.maxTotalAgents) {\n throw new WorkflowProtocolError(\n `result agentsStarted ${result.agentsStarted} exceeds the ${this.init.limits.maxTotalAgents}-agent cap`,\n )\n }\n // Claim before settlement cleanup invokes provider disposal. Once Result\n // won, a later cancellation cannot rewrite it.\n this.terminalClaimed = true\n // Abort pending starts and begin disposing published children before the\n // workflow becomes externally settled. Scratch operations already\n // admitted are effects: drain them before publishing the outcome.\n this.reapChildren('workflow settled')\n this.endStrandedAgents()\n this.drainingWorkerResult = true\n void this.settleAfterScratch(result, cancellationWasRequested)\n }\n\n /** Drain admitted scratch effects before publishing the worker-selected outcome. */\n private async settleAfterScratch(result: WorkflowResult, cancellationWasRequested: boolean): Promise<void> {\n await this.scratchQuiescence()\n /* v8 ignore next -- scratch quiescence resolves before any competing settle can pass the terminal claim */\n if (this.settled) return\n if (cancellationWasRequested || this.cancelReason !== undefined) {\n this.settleResult(result.stopReason === 'cancelled'\n ? result\n : this.cancelledResult(result.agentsStarted))\n return\n }\n /* v8 ignore start -- deterministic tests cannot order Result ahead of\n * scratch-failure termination; onScratchFailure covers I/O failure. */\n if (this.scratchFailure !== undefined) {\n this.settleResult({\n value: null,\n stopReason: 'error',\n error: this.scratchFailure,\n agentsStarted: result.agentsStarted,\n })\n return\n }\n /* v8 ignore stop */\n this.settleResult(result)\n }\n\n /** Serve one quota-checked, atomic scratch write. */\n private onScratchWrite(callId: number, name: string, content: string): Promise<void> {\n this.claimScratchCall(callId, name, 'scratch-write')\n return this.trackScratch(async () => {\n this.scratchController.signal.throwIfAborted()\n if (this.scratchPort !== undefined) {\n await this.scratchPort.write(name, content, this.scratchController.signal)\n this.post(HostToWorkerType.ScratchWritten, { callId })\n return\n }\n const state = await this.getScratchState()\n if (state === undefined) {\n this.post(HostToWorkerType.ScratchWritten, { callId })\n return\n }\n await this.writeScratch(state, name, content)\n this.post(HostToWorkerType.ScratchWritten, { callId })\n })\n }\n\n /** Serve one no-follow, bounded scratch read. */\n private onScratchRead(callId: number, name: string): Promise<void> {\n this.claimScratchCall(callId, name, 'scratch-read')\n return this.trackScratch(async () => {\n this.scratchController.signal.throwIfAborted()\n if (this.scratchPort !== undefined) {\n const content = await this.scratchPort.read(name, this.scratchController.signal)\n this.post(HostToWorkerType.ScratchReadResult, { callId, ...(content === undefined ? {} : { content }) })\n return\n }\n const state = await this.getScratchState()\n if (state === undefined) {\n this.post(HostToWorkerType.ScratchReadResult, { callId })\n return\n }\n const content = await this.readScratch(state, name)\n this.post(HostToWorkerType.ScratchReadResult, {\n callId,\n ...(content === undefined ? {} : { content }),\n })\n })\n }\n\n /** Validate one scratch RPC before queueing any filesystem work. */\n private claimScratchCall(callId: number, name: string, operation: string): void {\n if (!SCRATCH_NAME.test(name)) {\n throw new WorkflowProtocolError(`${operation} name must be one safe path component`)\n }\n if (this.cancelReason !== undefined || this.workerDeathObserved || this.terminalClaimed) {\n throw new WorkflowProtocolError(`${operation} arrived after the run stopped admitting effects`)\n }\n if (this.scratchOperations >= this.hostLimits.scratch.maxOperations) {\n throw new WorkflowProtocolError(\n `${operation} exceeds the ${this.hostLimits.scratch.maxOperations}-operation scratch limit`,\n )\n }\n if (this.pendingScratch.size >= this.hostLimits.scratch.maxPendingOperations) {\n throw new WorkflowProtocolError(\n `${operation} exceeds the ${this.hostLimits.scratch.maxPendingOperations}-operation pending scratch limit`,\n )\n }\n this.claimCallId(callId, operation)\n this.scratchOperations += 1\n }\n\n /** Serialize, retain, and contain one admitted scratch operation. */\n private trackScratch(operation: () => Promise<void>): Promise<void> {\n const execution = this.scratchTail.then(operation)\n this.scratchTail = execution.catch(() => { /* the tracked operation reports the failure */ })\n const tracked = execution.then(\n () => {},\n (error: unknown) => { this.onScratchFailure(error) },\n )\n this.pendingScratch.add(tracked)\n void tracked.then(() => {\n this.pendingScratch.delete(tracked)\n this.notifyRunQuiescence()\n })\n return tracked\n }\n\n /** Resolve once every scratch operation admitted before the terminal frame is quiescent. */\n private scratchQuiescence(): Promise<void> {\n if (this.pendingScratch.size === 0) return Promise.resolve()\n return Promise.all([...this.pendingScratch]).then(() => {})\n }\n\n /** Turn a scratch quota, integrity, or I/O failure into a run-local terminal error. */\n private onScratchFailure(error: unknown): void {\n // Cancellation aborts admitted file operations intentionally. Their\n // rejection only retires quiescence; the cancellation outcome already\n // owns settlement and must not be rewritten as a scratch/worker error.\n if (this.cancelReason !== undefined) return\n if (this.scratchFailure !== undefined) return\n this.scratchFailure = `workflow scratch operation failed: ${renderThrown(error)}`\n if (!this.scratchController.signal.aborted) this.scratchController.abort(this.scratchFailure)\n this.onWorkerDeath(this.scratchFailure, false)\n void this.worker.terminate()\n }\n\n /** Initialize scratch storage at first use, never merely because a run started. */\n private getScratchState(): Promise<ScratchState | undefined> {\n const existing = this.scratchState\n if (existing !== undefined) return existing\n const created = this.initializeScratch()\n this.scratchState = created\n return created\n }\n\n /** Verify/create the owner-private scratch directory and account retained files on resume. */\n private async initializeScratch(): Promise<ScratchState | undefined> {\n if (this.scratchDir === undefined) return undefined\n const dir = join(this.scratchDir, 'scratch')\n await mkdir(dir, { recursive: true, mode: 0o700 })\n const directory = await lstat(dir)\n if (!directory.isDirectory() || directory.isSymbolicLink()) {\n throw new Error('scratch path is not a real directory')\n }\n await chmod(dir, 0o700)\n const files = new Map<string, ScratchFileState>()\n let totalBytes = 0\n for (const entry of await readdir(dir, { withFileTypes: true })) {\n if (!SCRATCH_NAME.test(entry.name) || !entry.isFile() || entry.isSymbolicLink()) {\n throw new Error(`scratch directory contains an unsupported entry ${JSON.stringify(entry.name)}`)\n }\n const file = await this.scratchFileState(join(dir, entry.name))\n if (file.size > this.hostLimits.scratch.maxFileBytes) {\n throw new Error(`scratch file ${JSON.stringify(entry.name)} exceeds the per-file quota`)\n }\n files.set(entry.name, file)\n totalBytes += file.size\n }\n if (files.size > this.hostLimits.scratch.maxFiles) {\n throw new Error(`scratch directory exceeds the ${this.hostLimits.scratch.maxFiles}-file quota`)\n }\n if (totalBytes > this.hostLimits.scratch.maxTotalBytes) {\n throw new Error(`scratch directory exceeds the ${this.hostLimits.scratch.maxTotalBytes}-byte quota`)\n }\n return { dir, device: directory.dev, inode: directory.ino, files, totalBytes }\n }\n\n /** Inspect one singly linked scratch path without following a final symlink. */\n private async scratchFileState(path: string): Promise<ScratchFileState> {\n const before = await lstat(path)\n if (!before.isFile() || before.isSymbolicLink()) {\n throw new Error(`scratch path ${JSON.stringify(path)} is not a regular file`)\n }\n if (before.nlink !== 1) {\n throw new Error(`scratch path ${JSON.stringify(path)} has multiple hard links`)\n }\n const handle = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW)\n try {\n const info = await handle.stat()\n /* v8 ignore next -- a non-file descriptor requires a path replacement between lstat() and open(). */\n if (!info.isFile()) throw new Error(`scratch path ${JSON.stringify(path)} is not a regular file`)\n /* v8 ignore next -- inode mismatch requires a path replacement between lstat() and open(). */\n if (info.dev !== before.dev || info.ino !== before.ino) {\n /* v8 ignore next */\n throw new Error(`scratch path ${JSON.stringify(path)} changed while opening`)\n }\n /* v8 ignore next -- link-count change requires an external hard-link race after lstat(). */\n if (info.nlink !== 1) {\n /* v8 ignore next */\n throw new Error(`scratch path ${JSON.stringify(path)} gained a hard link while opening`)\n }\n /* v8 ignore next -- Node fs.Stat.size is always a non-negative safe integer for an opened local file. */\n if (!Number.isSafeInteger(info.size) || info.size < 0) throw new Error('scratch file size is invalid')\n await handle.chmod(0o600)\n return { device: info.dev, inode: info.ino, size: info.size }\n } finally {\n await handle.close()\n }\n }\n\n /** Atomically publish one owner-only scratch file after quota admission. */\n private async writeScratch(state: ScratchState, name: string, content: string): Promise<void> {\n this.scratchController.signal.throwIfAborted()\n await this.assertScratchDirectory(state)\n const bytes = Buffer.from(content, 'utf8')\n const limits = this.hostLimits.scratch\n if (bytes.length > limits.maxFileBytes) {\n throw new Error(`scratch file ${JSON.stringify(name)} exceeds the ${limits.maxFileBytes}-byte per-file quota`)\n }\n const previous = state.files.get(name)\n if (previous === undefined && state.files.size >= limits.maxFiles) {\n throw new Error(`scratch write exceeds the ${limits.maxFiles}-file quota`)\n }\n const nextTotal = state.totalBytes - (previous?.size ?? 0) + bytes.length\n if (nextTotal > limits.maxTotalBytes) {\n throw new Error(`scratch write exceeds the ${limits.maxTotalBytes}-byte total quota`)\n }\n const target = join(state.dir, name)\n const temporary = join(state.dir, `.${randomBytes(12).toString('hex')}.tmp`)\n const backup = join(state.dir, `.${randomBytes(12).toString('hex')}.bak`)\n let handle: Awaited<ReturnType<typeof open>> | undefined\n let staged: ScratchFileState | undefined\n let previousMoved = false\n let published = false\n try {\n handle = await open(temporary, 'wx', 0o600)\n await handle.chmod(0o600)\n await handle.writeFile(bytes, { signal: this.scratchController.signal })\n await handle.sync()\n const stagedInfo = await handle.stat()\n /* v8 ignore next -- the owner-held wx descriptor cannot change file type; link-count mutation needs an external race. */\n if (!stagedInfo.isFile() || stagedInfo.nlink !== 1) {\n /* v8 ignore next */\n throw new Error('scratch temporary path changed while writing')\n }\n staged = { device: stagedInfo.dev, inode: stagedInfo.ino, size: bytes.length }\n await handle.close()\n handle = undefined\n this.scratchController.signal.throwIfAborted()\n await this.assertScratchDirectory(state)\n if (previous !== undefined) {\n await this.assertScratchFileIdentity(target, previous)\n await rename(target, backup)\n previousMoved = true\n await this.assertScratchFileIdentity(backup, previous)\n this.scratchController.signal.throwIfAborted()\n }\n await link(temporary, target)\n published = true\n await this.assertScratchFileIdentity(target, staged, true)\n await rm(temporary)\n await this.assertScratchFileIdentity(target, staged)\n state.files.set(name, staged)\n state.totalBytes = nextTotal\n if (previousMoved && previous !== undefined) {\n await this.assertScratchFileIdentity(backup, previous)\n await rm(backup)\n previousMoved = false\n }\n } catch (error: unknown) {\n if (previousMoved && !published) {\n // `link` is an atomic no-clobber restore. Keep the unique backup even\n // when it succeeds: a concurrent actor may replace either name after\n // the link, so deleting one here could delete data not owned by this\n // transaction.\n await link(backup, target).catch(() => {})\n }\n throw error\n } finally {\n /* v8 ignore next -- reaching cleanup with an open handle requires an injected fs write/sync failure. */\n if (handle !== undefined) await handle.close().catch(() => {})\n /* v8 ignore next -- cleanup failures are deliberately swallowed after the primary transaction failure. */\n if (!published) await rm(temporary, { force: true }).catch(() => {})\n }\n }\n\n /** Read one expected regular file through an owner-held no-follow descriptor. */\n private async readScratch(state: ScratchState, name: string): Promise<string | undefined> {\n const expected = state.files.get(name)\n if (expected === undefined) return undefined\n this.scratchController.signal.throwIfAborted()\n await this.assertScratchDirectory(state)\n const path = join(state.dir, name)\n let before: Awaited<ReturnType<typeof lstat>>\n try {\n before = await lstat(path)\n } catch (error: unknown) {\n /* v8 ignore next -- safe component + verified directory leaves ENOENT as the only ordinary lstat failure. */\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error\n state.files.delete(name)\n state.totalBytes -= expected.size\n return undefined\n }\n if (!before.isFile() || before.isSymbolicLink()) {\n throw new Error(`scratch path ${JSON.stringify(name)} is not a regular file`)\n }\n if (before.nlink !== 1) {\n throw new Error(`scratch path ${JSON.stringify(name)} has multiple hard links`)\n }\n if (before.dev !== expected.device || before.ino !== expected.inode) {\n throw new Error(`scratch path ${JSON.stringify(name)} changed after initialization`)\n }\n let handle: Awaited<ReturnType<typeof open>>\n try {\n handle = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW)\n } catch (error: unknown) {\n /* v8 ignore next -- after successful lstat, a non-ENOENT open failure requires an external permission/type race. */\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error\n /* v8 ignore start -- disappearance between lstat() and open() is a real filesystem race that deterministic tests cannot order. */\n state.files.delete(name)\n state.totalBytes -= expected.size\n return undefined\n /* v8 ignore stop */\n }\n try {\n const info = await handle.stat()\n /* v8 ignore next -- a non-file descriptor requires a path replacement between lstat() and open(). */\n if (!info.isFile()) throw new Error(`scratch path ${JSON.stringify(name)} is not a regular file`)\n /* v8 ignore next -- inode mismatch requires a path replacement between lstat() and open(). */\n if (info.dev !== before.dev || info.ino !== before.ino) {\n /* v8 ignore next */\n throw new Error(`scratch path ${JSON.stringify(name)} changed while opening`)\n }\n /* v8 ignore next -- link-count change requires an external hard-link race after open(). */\n if (info.nlink !== 1) {\n /* v8 ignore next */\n throw new Error(`scratch path ${JSON.stringify(name)} gained a hard link while opening`)\n }\n if (info.size > this.hostLimits.scratch.maxFileBytes) {\n throw new Error(`scratch file ${JSON.stringify(name)} exceeds the per-file quota`)\n }\n const bytes = await handle.readFile({ signal: this.scratchController.signal })\n /* v8 ignore next -- growth after descriptor stat and before read completion is an external filesystem race. */\n if (bytes.length > this.hostLimits.scratch.maxFileBytes) {\n /* v8 ignore next */\n throw new Error(`scratch file ${JSON.stringify(name)} grew beyond the per-file quota while reading`)\n }\n const nextTotal = state.totalBytes - expected.size + bytes.length\n if (nextTotal > this.hostLimits.scratch.maxTotalBytes) {\n throw new Error('scratch directory grew beyond the total quota while reading')\n }\n expected.size = bytes.length\n state.totalBytes = nextTotal\n return new TextDecoder('utf-8', { fatal: true }).decode(bytes)\n } finally {\n await handle.close()\n }\n }\n\n /** Reject a scratch path whose current inode is not the transaction-owned file. */\n private async assertScratchFileIdentity(\n path: string,\n expected: ScratchFileState,\n allowStagingLink = false,\n ): Promise<void> {\n const current = await lstat(path)\n if (!current.isFile()\n || current.isSymbolicLink()\n || current.dev !== expected.device\n || current.ino !== expected.inode\n || current.nlink !== (allowStagingLink ? 2 : 1)) {\n throw new Error(`scratch file ${JSON.stringify(path)} changed during publication`)\n }\n }\n\n /** Reject a scratch directory that was replaced after lazy initialization. */\n private async assertScratchDirectory(state: ScratchState): Promise<void> {\n const current = await lstat(state.dir)\n if (!current.isDirectory()\n || current.isSymbolicLink()\n || current.dev !== state.device\n || current.ino !== state.inode) {\n throw new Error('scratch directory changed after initialization')\n }\n }\n\n /** Process an error/messageerror/exit signal; `exit` also performs the final disposal sweep. */\n private onWorkerDeath(message: string, isExit: boolean): void {\n if (!this.workerDeathObserved) {\n // Close message admission BEFORE cleanup callbacks: Node can deliver a\n // message queued before the crash after its `error` event. Treating the\n // first death signal as a logical barrier prevents that late message\n // from creating work or narrating after workflow/end.\n this.workerDeathObserved = true\n const outcomeWasClaimed = this.terminalClaimed\n const cancellationWasRequested = this.cancelReason !== undefined\n // A valid Result may race physical worker exit while admitted unawaited\n // scratch effects drain. Preserve those effects; every other death\n // source aborts scratch publication before selecting its outcome.\n if (!outcomeWasClaimed && !this.scratchController.signal.aborted) {\n this.scratchController.abort('workflow worker gone')\n }\n // When death is itself the terminal source, claim BEFORE child reap or\n // synthesized observer callbacks. Either can reenter cancel(); a death\n // that arrived first remains an error, while a cancellation already\n // accepted before death remains cancelled. If Result/grace already won,\n // preserve it while still performing prompt failure-time cleanup.\n if (!outcomeWasClaimed) this.terminalClaimed = true\n if (this.children.size > 0 || this.pendingStarts.size > 0) this.reapChildren('workflow worker gone')\n this.endStrandedAgents()\n if (!outcomeWasClaimed) {\n if (cancellationWasRequested) {\n this.settleResult(this.cancelledResult(this.observedAgentSpend()))\n } else {\n this.settleResult({\n value: null,\n stopReason: 'error',\n error: message,\n agentsStarted: this.observedAgentSpend(),\n })\n }\n }\n }\n if (!isExit) return\n // `error` is not Node's physical delivery barrier: a queued message may\n // precede `exit`. Admission is already closed, so this final sweep only\n // joins/starts disposal for registry survivors; it deliberately does not\n // repeat explicit provider cancellation.\n for (const [callId, record] of [...this.children]) void this.disposeChild(callId, record)\n this.endStrandedAgents()\n }\n\n /**\n * The single agent-end emission gate: forwards `end` iff its start is still\n * unpaired in the ledger, so every forwarded `workflow/agent-start` gets\n * EXACTLY one `workflow/agent-end` — the worker's own report where it can\n * speak, a host-synthesized one where it cannot ({@link endStrandedAgents}).\n * @param end - the settlement to emit (worker-reported or synthesized).\n */\n private endAgent(end: WorkflowAgentEndInfo): void {\n /* v8 ignore next -- a real end still in flight across the grace force-settle: not orderable in-process */\n if (!this.liveAgents.delete(end.seq)) return\n this.observer.agentEnd(end)\n }\n\n /**\n * Synthesize the missing `agent-end` for every started-but-unpaired agent,\n * outcome `'cancelled'`: the reap cancels every child, and a real\n * settlement racing the force-settle loses to that already-started external\n * cancellation. The atomic terminal boundaries in {@link onResult} and\n * {@link onWorkerDeath} deliberately exclude teardown callbacks as contenders.\n * Called where the worker can no longer speak (the grace force-settle,\n * worker death, physical exit). When grace/death is the terminal source it\n * runs before settleResult, so already-known pairs precede `workflow/end`;\n * after an earlier Result, exit cleanup may close a survivor afterward.\n * The ledger preserves exactly-once pairing in both orders.\n */\n private endStrandedAgents(): void {\n for (const info of [...this.liveAgents.values()]) {\n this.endAgent({ ...info, outcome: 'cancelled' })\n }\n }\n\n private cancelledResult(agentsStarted: number): WorkflowResult {\n // cancel() is the only writer of cancelReason and every caller checks it\n // first; the fallback guards the type, not a reachable path.\n /* v8 ignore next */\n const reason = this.cancelReason ?? 'workflow cancelled'\n return {\n value: null,\n stopReason: 'cancelled',\n error: `workflow run cancelled: ${reason}`,\n errorCode: 'CANCELLED',\n agentsStarted,\n }\n }\n\n /** Cumulative logical-agent spend the host can prove across resume attempts. */\n private observedAgentSpend(): number {\n return (this.init.initialAgentSpend ?? 0) + this.hostStarted\n }\n\n /** Remove the exact abort callback installed on the caller's start signal. */\n private detachInputSignal(): void {\n const signal = this.inputSignal\n const onAbort = this.inputSignalAbort\n if (signal === undefined || onAbort === undefined) return\n this.inputSignal = undefined\n this.inputSignalAbort = undefined\n signal.removeEventListener('abort', onAbort)\n }\n\n /** First settle wins; disarms the grace timer and releases the caller signal. */\n private settleResult(result: WorkflowResult): void {\n // Every current terminal source claims ownership before calling here; keep\n // the fallback local so a future caller cannot resolve twice.\n /* v8 ignore next -- defensive fallback outside the claimed state machine */\n if (this.settled) return\n this.terminalClaimed = true\n this.settled = true\n this.finalAgentSpend = Math.max(this.finalAgentSpend, result.agentsStarted)\n this.detachInputSignal()\n clearTimeout(this.graceTimer)\n this.settleResolve(result)\n }\n}\n\n/** A plain timer sleep (the dispose grace); unref'd so it never holds the process open. */\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => {\n const timer = setTimeout(resolve, ms)\n timer.unref()\n })\n}\n","/**\n * Meta validation checks caller-provided DATA against the {@link WorkflowMeta}\n * contract and rejects every violation by name. Meta arrives as schema-checked\n * JSON data, never evaluated script text; evaluating it on the host could run getters outside the\n * worker timeout that exists to isolate model-written code.\n * @module @deepseek-ai/dsh-workflow-worker-thread/meta\n */\n\nimport { WorkflowError } from '@deepseek-ai/dsh-workflow'\nimport type { WorkflowMeta, WorkflowPhase } from '@deepseek-ai/dsh-workflow'\n\n/** Collect shape violations for a meta value (plain JSON data by the seam contract). */\nfunction validateMetaShape(meta: unknown): { meta?: WorkflowMeta; violations: string[] } {\n const violations: string[] = []\n if (typeof meta !== 'object' || meta === null || Array.isArray(meta)) {\n return { violations: ['meta must be an object'] }\n }\n const record = meta as Record<string, unknown>\n const known = new Set(['name', 'description', 'whenToUse', 'phases'])\n for (const key of Object.keys(record)) {\n if (!known.has(key)) violations.push(`meta.${key} is not a recognized field (name/description/whenToUse/phases)`)\n }\n if (typeof record.name !== 'string' || record.name.length === 0) violations.push('meta.name must be a non-empty string')\n if (typeof record.description !== 'string' || record.description.length === 0) violations.push('meta.description must be a non-empty string')\n if (record.whenToUse !== undefined && typeof record.whenToUse !== 'string') violations.push('meta.whenToUse must be a string')\n const phases: WorkflowPhase[] = []\n if (record.phases !== undefined) {\n if (!Array.isArray(record.phases)) {\n violations.push('meta.phases must be an array')\n } else {\n record.phases.forEach((phase, index) => {\n if (typeof phase !== 'object' || phase === null || Array.isArray(phase)) {\n violations.push(`meta.phases[${index}] must be an object`)\n return\n }\n const entry = phase as Record<string, unknown>\n for (const key of Object.keys(entry)) {\n if (!['title', 'detail', 'provider', 'model'].includes(key)) violations.push(`meta.phases[${index}].${key} is not a recognized field`)\n }\n if (typeof entry.title !== 'string' || entry.title.length === 0) violations.push(`meta.phases[${index}].title must be a non-empty string`)\n if (entry.detail !== undefined && typeof entry.detail !== 'string') violations.push(`meta.phases[${index}].detail must be a string`)\n if (entry.provider !== undefined && typeof entry.provider !== 'string') violations.push(`meta.phases[${index}].provider must be a string`)\n if (entry.model !== undefined && typeof entry.model !== 'string') violations.push(`meta.phases[${index}].model must be a string`)\n if (violations.length === 0) {\n phases.push({\n title: entry.title as string,\n ...entry.detail !== undefined ? { detail: entry.detail as string } : {},\n ...entry.provider !== undefined ? { provider: entry.provider as string } : {},\n ...entry.model !== undefined ? { model: entry.model as string } : {},\n })\n }\n })\n }\n }\n if (violations.length > 0) return { violations }\n return {\n violations,\n meta: {\n name: record.name as string,\n description: record.description as string,\n ...record.whenToUse !== undefined ? { whenToUse: record.whenToUse as string } : {},\n ...record.phases !== undefined ? { phases } : {},\n },\n }\n}\n\n/**\n * Validate a caller-provided meta value against the {@link WorkflowMeta}\n * contract. Throws `META_INVALID` naming every violation (unknown fields,\n * missing/mistyped `name`/`description`, malformed `phases`); the returned\n * meta is a NORMALIZED copy built from the validated fields, so the engine\n * never aliases the caller's object.\n * @param value - the meta data from the start request (plain JSON by the seam contract).\n * @returns the validated, normalized meta block.\n */\nexport function validateMeta(value: unknown): WorkflowMeta {\n const { meta, violations } = validateMetaShape(value)\n if (meta === undefined) {\n throw new WorkflowError(`invalid meta: ${violations.join('; ')}`, 'META_INVALID')\n }\n return meta\n}\n","/**\n * Worker-thread workflow engine. Each run executes its model-written script in\n * an escapable vm context on a fresh worker and bridges `agent()` calls to host\n * subagents. The thread prevents synchronous script work from blocking the host\n * and permits forced termination, but it is containment rather than a security boundary.\n * @module @deepseek-ai/dsh-workflow-worker-thread\n */\n\nimport { randomUUID } from 'node:crypto'\nimport { availableParallelism } from 'node:os'\nimport * as vm from 'node:vm'\nimport type { Context } from '@deepseek-ai/cordis'\nimport z from '@deepseek-ai/schemastery'\nimport { WorkflowRunId } from '@deepseek-ai/dsh-workflow'\nimport type { WorkflowRun, WorkflowRunInfo } from '@deepseek-ai/dsh-workflow'\nimport { WorkflowError, type WorkflowStartRequest } from './compat-seam.ts'\nimport type { WorkflowJournalEntry } from './types.ts'\nimport { snapshotJsonValue } from '@deepseek-ai/dsh-session'\nimport { WorkerRun } from './host.ts'\nimport { validateMeta } from './meta.ts'\nimport type { WorkerHostLimits, WorkerInit, WorkerLimits } from './types.ts'\n\nexport { validateMeta } from './meta.ts'\nexport { materializeFromRealm, MaterializeError } from './realm.ts'\nexport type {\n ChildHandle,\n ChildPort,\n ChildResult,\n ChildStartRequest,\n WorkerInit,\n WorkerLimits,\n} from './types.ts'\n\n/** Plugin config (all optional — `static Config` supplies the defaults). */\nexport interface Config {\n /** The `ctx.subagents` provider children run on (default `spawn`). */\n provider?: string\n /** Concurrent `agent()` ceiling; `0` (the default) auto-resolves to `min(16, max(1, cores - 2))`. */\n maxConcurrentAgents?: number\n /** Total `agent()` calls one run may start — the runaway-loop backstop (default 1024). */\n maxTotalAgents?: number\n /** Items accepted by a single `parallel()`/`pipeline()` call (default 4096). */\n maxItemsPerCall?: number\n /** vm timeout for the script's initial synchronous slice, inside the worker (default 5000 ms). */\n syncTimeoutMs?: number\n /**\n * How long after a cancellation an unsettled script may keep running before\n * the run force-settles `cancelled` and its worker is TERMINATED (default\n * 5000 ms); also bounds `dispose()`.\n */\n disposeGraceMs?: number\n /** Maximum encoded bytes accepted for one worker protocol message (default 8 MiB). */\n maxProtocolMessageBytes?: number\n /** Maximum UTF-8 JSON bytes committed to one run's host-call journal (default 64 MiB). */\n maxJournalBytes?: number\n /** Maximum UTF-8 bytes accepted in one child prompt (default 1 MiB). */\n maxChildPromptBytes?: number\n /** Maximum UTF-8 bytes accepted in one progress event string (default 64 KiB). */\n maxEventTextBytes?: number\n /** Maximum scratch reads and writes admitted over one engine attempt (default 4096). */\n scratchMaxOperations?: number\n /** Maximum scratch reads and writes pending at once (default 64). */\n scratchMaxPendingOperations?: number\n /** Maximum scratch files in one run (default 64). */\n scratchMaxFiles?: number\n /** Maximum UTF-8 bytes in one scratch file (default 1 MiB). */\n scratchMaxFileBytes?: number\n /** Maximum UTF-8 bytes across one run's scratch files (default 8 MiB). */\n scratchMaxTotalBytes?: number\n /** Hard wall-clock bound for validate-only execution (default 10000 ms). */\n validationTimeoutMs?: number\n}\n\ntype ResolvedConfig = Required<Config>\n\n/** A body that still carries the Claude Code-style meta header (meta rides the seam as data here). */\nconst META_STATEMENT = /^\\s*export\\s+const\\s+meta\\b/\n\n/**\n * Parse-check the body with the SAME wrapper the worker-side runtime\n * compiles, so `start()` keeps the seam's synchronous `SCRIPT_PARSE` throw\n * (the worker's own compile happens a thread away, after `start()` returned).\n * One redundant parse per run, bought deliberately for the contract. A body\n * opening with `export const meta` gets a pointed message instead of the\n * wrapper's bare SyntaxError — the model's likeliest authoring slip.\n */\nfunction assertBodyParses(body: string, name: string): void {\n if (META_STATEMENT.test(body)) {\n throw new WorkflowError('workflow meta rides the `meta` request field, not the script: remove the `export const meta = {...}` statement from the body', 'SCRIPT_PARSE')\n }\n try {\n // Parse only — the script object is discarded, nothing executes.\n void new vm.Script(`(async () => {\\n${body}\\n})()`, { filename: `workflow:${name}`, lineOffset: -1 })\n } catch (error: unknown) {\n throw new WorkflowError(`workflow script does not parse: ${String(error)}`, 'SCRIPT_PARSE', { cause: error })\n }\n}\n\n/** Resolve one run's provider route before publishing work. */\nfunction resolveSubagentProvider(ctx: Context, configured: string, override: string | undefined): string {\n const provider = override ?? configured\n if (provider.length === 0 || provider !== provider.trim()) {\n throw new WorkflowError(\n 'workflow subagentProvider must be a non-empty normalized string',\n 'INVALID_ARGUMENT',\n )\n }\n if (ctx.subagents.getProvider(provider) === undefined) {\n throw new WorkflowError(`no subagent provider registered for \"${provider}\"`, 'AGENT_START')\n }\n return provider\n}\n\n/** Resolve one run's total-child cap against the engine deployment ceiling. */\nfunction resolveMaxTotalAgents(requested: number | undefined, ceiling: number): number {\n if (requested === undefined) return ceiling\n if (!Number.isSafeInteger(requested) || requested < 1) {\n throw new WorkflowError('workflow maxTotalAgents must be a positive safe integer', 'INVALID_ARGUMENT')\n }\n if (requested > ceiling) {\n throw new WorkflowError(\n `workflow maxTotalAgents ${requested} exceeds the engine ceiling ${ceiling}`,\n 'INVALID_ARGUMENT',\n )\n }\n return requested\n}\n\n/** Validate cumulative spend supplied by a logical-run supervisor. */\nfunction resolveInitialAgentSpend(\n requested: number | undefined,\n total: number,\n journal: WorkflowStartRequest['journal'],\n): number {\n const committed = journal?.filter(entry => entry.kind === 'agent').length ?? 0\n const resolved = requested ?? committed\n if (!Number.isSafeInteger(resolved) || resolved < committed || resolved > total) {\n throw new WorkflowError(\n `workflow initialAgentSpend must be a safe integer between the committed journal count (${committed}) and maxTotalAgents (${total})`,\n 'INVALID_ARGUMENT',\n )\n }\n return resolved\n}\n\n/** Validate the monotonic member sequence seed supplied by a logical-run supervisor. */\nfunction resolveInitialAgentSeq(\n requested: number | undefined,\n spend: number,\n total: number,\n journal: WorkflowStartRequest['journal'],\n): number {\n let journalMaximum = 0\n for (const entry of journal ?? []) {\n if (entry.kind !== 'agent') continue\n journalMaximum = Math.max(journalMaximum, entry.seq)\n }\n const minimum = Math.max(spend, journalMaximum)\n const resolved = requested ?? minimum\n if (!Number.isSafeInteger(resolved)\n || resolved < minimum\n || resolved > Number.MAX_SAFE_INTEGER - (total - spend)) {\n throw new WorkflowError(\n `workflow initialAgentSeq must be a safe integer no less than prior spend or journal sequence (${minimum}) with room for the remaining logical-agent budget`,\n 'INVALID_ARGUMENT',\n )\n }\n return resolved\n}\n\n/** Snapshot and validate replay data before it crosses into workerData. */\nfunction resolveJournal(journal: WorkflowStartRequest['journal']): readonly WorkflowJournalEntry[] | undefined {\n if (journal === undefined) return undefined\n let snapshot: unknown\n try {\n snapshot = snapshotJsonValue<unknown>(journal)\n } catch (error: unknown) {\n throw new WorkflowError('workflow journal must be lossless JSON data', 'JOURNAL_DIVERGENCE', { cause: error })\n }\n if (snapshot === undefined || !Array.isArray(snapshot)) {\n throw new WorkflowError('workflow journal must be lossless JSON data', 'JOURNAL_DIVERGENCE')\n }\n const entries = snapshot as readonly unknown[]\n const callIds = new Set<string>()\n const agentSeqs = new Set<number>()\n let priorOrdinal = 0\n for (const candidate of entries) {\n if (typeof candidate !== 'object' || candidate === null || Array.isArray(candidate)) {\n throw new WorkflowError('workflow journal entries must be objects', 'JOURNAL_DIVERGENCE')\n }\n const entry = candidate as Record<string, unknown>\n const ordinal = entry.ordinal\n if (typeof ordinal !== 'number' || !Number.isSafeInteger(ordinal) || ordinal !== priorOrdinal + 1) {\n throw new WorkflowError('workflow journal entry ordinal must be the next positive safe integer', 'JOURNAL_DIVERGENCE')\n }\n priorOrdinal = ordinal\n const callId = entry.callId\n const callKey = Array.isArray(callId) ? callId.join('.') : ''\n if (!Array.isArray(callId) || callId.length === 0\n || callId.some(part => !Number.isSafeInteger(part) || part <= 0)\n || callIds.has(callKey)) {\n throw new WorkflowError('workflow journal call identities must be non-empty and unique', 'JOURNAL_DIVERGENCE')\n }\n callIds.add(callKey)\n const fingerprint = entry.fingerprint\n if (typeof fingerprint !== 'string' || !/^[a-f0-9]{64}$/u.test(fingerprint)) {\n throw new WorkflowError('workflow journal fingerprint must be a lowercase SHA-256 digest', 'JOURNAL_DIVERGENCE')\n }\n switch (entry.kind) {\n case 'agent':\n if (Object.keys(entry).some(key => !['kind', 'ordinal', 'callId', 'fingerprint', 'seq', 'result'].includes(key))\n || !Object.hasOwn(entry, 'result')) {\n throw new WorkflowError('workflow agent journal fields are not recognized', 'JOURNAL_DIVERGENCE')\n }\n if (typeof entry.seq !== 'number' || !Number.isSafeInteger(entry.seq) || entry.seq < 1) {\n throw new WorkflowError('workflow journal agent seq must be a positive safe integer', 'JOURNAL_DIVERGENCE')\n }\n if (agentSeqs.has(entry.seq)) {\n throw new WorkflowError(`workflow journal repeats agent sequence ${entry.seq}`, 'JOURNAL_DIVERGENCE')\n }\n agentSeqs.add(entry.seq)\n break\n case 'phase':\n if (Object.keys(entry).some(key => !['kind', 'ordinal', 'callId', 'fingerprint', 'title'].includes(key))) {\n throw new WorkflowError('workflow phase journal fields are not recognized', 'JOURNAL_DIVERGENCE')\n }\n if (typeof entry.title !== 'string' || entry.title.length === 0) {\n throw new WorkflowError('workflow phase journal title must be a non-empty string', 'JOURNAL_DIVERGENCE')\n }\n break\n case 'log':\n if (Object.keys(entry).some(key => !['kind', 'ordinal', 'callId', 'fingerprint', 'message'].includes(key))) {\n throw new WorkflowError('workflow log journal fields are not recognized', 'JOURNAL_DIVERGENCE')\n }\n if (typeof entry.message !== 'string') {\n throw new WorkflowError('workflow log journal message must be a string', 'JOURNAL_DIVERGENCE')\n }\n break\n case 'scratch-read':\n if (Object.keys(entry).some(key => !['kind', 'ordinal', 'callId', 'fingerprint', 'content'].includes(key))) {\n throw new WorkflowError('workflow scratch-read journal fields are not recognized', 'JOURNAL_DIVERGENCE')\n }\n if (entry.content !== undefined && typeof entry.content !== 'string') {\n throw new WorkflowError('workflow scratch-read journal content must be a string', 'JOURNAL_DIVERGENCE')\n }\n break\n case 'scratch-write':\n case 'await-user':\n if (Object.keys(entry).some(key => !['kind', 'ordinal', 'callId', 'fingerprint'].includes(key))) {\n throw new WorkflowError(`workflow ${entry.kind} journal fields are not recognized`, 'JOURNAL_DIVERGENCE')\n }\n break\n default:\n throw new WorkflowError('workflow journal entry kind is not recognized', 'JOURNAL_DIVERGENCE')\n }\n }\n return entries as unknown as readonly WorkflowJournalEntry[]\n}\n\n/**\n * The worker-thread engine service. `start()` validates the script up front\n * (meta + a host-side body parse) and returns a {@link WorkflowRun} whose\n * `result` never rejects; the `workflow/*` events fire around the run per\n * the seam contract.\n */\nclass WorkerThreadWorkflowEngine {\n /** Signals the package supervisor not to inject stock evaluator preludes. */\n readonly dshWorkflowsNative = true\n static inject = ['subagents']\n\n static Config: z<Config> = z.object({\n provider: z.string().default('spawn'),\n maxConcurrentAgents: z.natural().default(0),\n maxTotalAgents: z.natural().min(1).default(1024),\n maxItemsPerCall: z.natural().min(1).default(4096),\n syncTimeoutMs: z.natural().min(1).default(5000),\n disposeGraceMs: z.natural().default(5000),\n maxProtocolMessageBytes: z.number().step(1).min(1).max(Number.MAX_SAFE_INTEGER).default(8 * 1024 * 1024),\n maxJournalBytes: z.number().step(1).min(2).max(Number.MAX_SAFE_INTEGER).default(64 * 1024 * 1024),\n maxChildPromptBytes: z.number().step(1).min(1).max(Number.MAX_SAFE_INTEGER).default(1024 * 1024),\n maxEventTextBytes: z.number().step(1).min(1).max(Number.MAX_SAFE_INTEGER).default(64 * 1024),\n scratchMaxOperations: z.number().step(1).min(1).max(Number.MAX_SAFE_INTEGER).default(4096),\n scratchMaxPendingOperations: z.number().step(1).min(1).max(Number.MAX_SAFE_INTEGER).default(64),\n scratchMaxFiles: z.number().step(1).min(1).max(Number.MAX_SAFE_INTEGER).default(64),\n scratchMaxFileBytes: z.number().step(1).min(1).max(Number.MAX_SAFE_INTEGER).default(1024 * 1024),\n scratchMaxTotalBytes: z.number().step(1).min(1).max(Number.MAX_SAFE_INTEGER).default(8 * 1024 * 1024),\n })\n\n private readonly config: ResolvedConfig\n\n constructor(private readonly ctx: Context, config: Config = {}) {\n this.config = {\n provider: config.provider ?? 'spawn',\n maxConcurrentAgents: config.maxConcurrentAgents ?? 0,\n maxTotalAgents: config.maxTotalAgents ?? 1024,\n maxItemsPerCall: config.maxItemsPerCall ?? 4096,\n syncTimeoutMs: config.syncTimeoutMs ?? 5000,\n disposeGraceMs: config.disposeGraceMs ?? 5000,\n maxProtocolMessageBytes: config.maxProtocolMessageBytes ?? 8 * 1024 * 1024,\n maxJournalBytes: config.maxJournalBytes ?? 64 * 1024 * 1024,\n maxChildPromptBytes: config.maxChildPromptBytes ?? 1024 * 1024,\n maxEventTextBytes: config.maxEventTextBytes ?? 64 * 1024,\n scratchMaxOperations: config.scratchMaxOperations ?? 4096,\n scratchMaxPendingOperations: config.scratchMaxPendingOperations ?? 64,\n scratchMaxFiles: config.scratchMaxFiles ?? 64,\n scratchMaxFileBytes: config.scratchMaxFileBytes ?? 1024 * 1024,\n scratchMaxTotalBytes: config.scratchMaxTotalBytes ?? 8 * 1024 * 1024,\n validationTimeoutMs: config.validationTimeoutMs ?? 10_000,\n }\n if (this.config.scratchMaxFileBytes > this.config.scratchMaxTotalBytes) {\n throw new WorkflowError('workflow scratchMaxFileBytes cannot exceed scratchMaxTotalBytes', 'INVALID_ARGUMENT')\n }\n if (this.config.scratchMaxPendingOperations > this.config.scratchMaxOperations) {\n throw new WorkflowError(\n 'workflow scratchMaxPendingOperations cannot exceed scratchMaxOperations',\n 'INVALID_ARGUMENT',\n )\n }\n }\n\n /** Dispatch through the host event registry without registering a global service. */\n private emitWorkflowEvent(name: string, ...args: unknown[]): void {\n const dispatch = (this.ctx as any)?.events?.dispatch\n if (typeof dispatch !== 'function') return\n for (const callback of dispatch.call((this.ctx as any).events, 'emit', [name, ...args]) ?? []) {\n try { void Promise.resolve(callback(...args)).catch(error => (this.ctx as any)?.logger?.warn?.(`workflow: ${name} listener rejected`, error)) }\n catch (error) { (this.ctx as any)?.logger?.warn?.(`workflow: ${name} listener threw`, error) }\n }\n }\n\n /** Side-effect-free smoke validation through the same worker runtime. */\n async validate(request: WorkflowStartRequest): Promise<Record<string, unknown>> {\n const timeout = new AbortController()\n const timer = setTimeout(() => timeout.abort(new Error('workflow validation timed out')), this.config.validationTimeoutMs)\n timer.unref()\n const callerSignal = (request as any).signal as AbortSignal | undefined\n const signal = callerSignal === undefined ? timeout.signal : AbortSignal.any([callerSignal, timeout.signal])\n const files = new Map<string, string>()\n let operations = 0\n let pending = 0\n const bytes = (value: string) => Buffer.byteLength(value, 'utf8')\n const begin = () => {\n operations += 1; pending += 1\n if (operations > this.config.scratchMaxOperations) throw new RangeError('workflow scratch operation limit exceeded')\n if (pending > this.config.scratchMaxPendingOperations) throw new RangeError('workflow scratch pending-operation limit exceeded')\n }\n const scratch = {\n read: async (name: string) => { begin(); try { return files.get(name) } finally { pending -= 1 } },\n write: async (name: string, content: string) => {\n begin()\n try {\n const size = bytes(content)\n if (size > this.config.scratchMaxFileBytes) throw new RangeError('workflow scratch file limit exceeded')\n if (!files.has(name) && files.size >= this.config.scratchMaxFiles) throw new RangeError('workflow scratch file-count limit exceeded')\n let total = size\n for (const [other, value] of files) if (other !== name) total += bytes(value)\n if (total > this.config.scratchMaxTotalBytes) throw new RangeError('workflow scratch total-byte limit exceeded')\n files.set(name, content)\n } finally { pending -= 1 }\n },\n }\n const run = this.start({ ...(request as any), signal, scratch, validateOnly: true, deferStart: true }) as any\n let result: any\n try {\n run.release()\n result = await run.result\n if (callerSignal?.aborted) {\n throw callerSignal.reason ?? new DOMException('This operation was aborted', 'AbortError')\n }\n } finally {\n clearTimeout(timer)\n run.cancel('workflow validation finished')\n await run.dispose()\n }\n if (result.stopReason !== 'completed') {\n return { ok: false, status: 'error', error: result.error ?? 'workflow validation failed', errorCode: result.errorCode }\n }\n if (typeof result.value === 'string' && /^would (?:pause|await_user)\\b/u.test(result.value)) {\n return { ok: true, status: 'would-pause', value: result.value }\n }\n return { ok: true, status: 'completed', value: result.value }\n }\n\n /**\n * Validate and execute a workflow script in a fresh worker thread. Throws\n * {@link WorkflowError} synchronously (`META_INVALID` for a malformed meta\n * block, `SCRIPT_PARSE` for a body that does not compile) for a request\n * that cannot begin; once a run is returned, every failure resolves through\n * `result.stopReason` instead.\n * @param request - the script body, its meta data and `args`, the parent\n * agent, and an optional cancel signal.\n * @returns the live run (its `result` resolves when the script settles).\n */\n start(request: WorkflowStartRequest): WorkflowRun {\n const meta = validateMeta(request.meta)\n assertBodyParses(request.script, meta.name)\n const args = request.args === undefined ? undefined : snapshotJsonValue(request.args)\n if (request.args !== undefined && args === undefined) {\n throw new WorkflowError('workflow args must be losslessly JSON-serializable data', 'INVALID_ARGUMENT')\n }\n const checkpoint = (request as any).replay?.checkpoint\n const journal = resolveJournal((request as any).journal ?? checkpoint?.journal)\n const subagentProvider = resolveSubagentProvider(this.ctx, this.config.provider, request.subagentProvider)\n const maxTotalAgents = resolveMaxTotalAgents(request.maxTotalAgents, this.config.maxTotalAgents)\n const initialAgentSpend = resolveInitialAgentSpend(\n (request as any).initialAgentSpend ?? checkpoint?.agentSpend,\n maxTotalAgents,\n journal,\n )\n const initialAgentSeq = resolveInitialAgentSeq(\n (request as any).initialAgentSeq ?? checkpoint?.agentSeq,\n initialAgentSpend,\n maxTotalAgents,\n journal,\n )\n const id = WorkflowRunId(typeof (request as any).runId === 'string' ? (request as any).runId : randomUUID())\n const info: WorkflowRunInfo = { id, meta }\n const limits: WorkerLimits = {\n maxConcurrentAgents: this.config.maxConcurrentAgents === 0\n ? Math.min(16, Math.max(1, availableParallelism() - 2))\n : this.config.maxConcurrentAgents,\n maxTotalAgents,\n maxItemsPerCall: this.config.maxItemsPerCall,\n syncTimeoutMs: this.config.syncTimeoutMs,\n }\n const init: WorkerInit = {\n meta,\n body: request.script,\n ...args !== undefined ? { args } : {},\n ...journal !== undefined ? { journal } : {},\n initialAgentSpend,\n initialAgentSeq,\n ...request.validateOnly !== undefined ? { validateOnly: request.validateOnly } : {},\n limits,\n }\n // Capture the dependency while this service call is still traced through\n // the start() holder. Cordis strips the engine-provider shadow when it\n // returns the SubagentRuntime handle, so an already-returned run can keep\n // starting children after an engine HMR unload removes ctx.workflowEngine.\n // Re-resolving `this.ctx.subagents` later from WorkerRun would instead walk\n // the now-inactive engine fiber and break the seam's holder-owned lifetime.\n const runCtx = this.ctx\n const subagents = runCtx.subagents\n const workerRun = new WorkerRun(\n runCtx,\n subagents,\n id,\n meta,\n request.parent,\n init,\n subagentProvider,\n this.config.disposeGraceMs,\n {\n phase: (title) => { this.emitWorkflowEvent('workflow/phase', info, title) },\n log: (message) => { this.emitWorkflowEvent('workflow/log', info, message) },\n agentStart: (agent) => { this.emitWorkflowEvent('workflow/agent-start', info, agent) },\n agentEnd: (agent) => { this.emitWorkflowEvent('workflow/agent-end', info, agent) },\n gate: (gate) => { this.emitWorkflowEvent('workflow/gate', info, gate) },\n journalCommit: (entry) => { this.emitWorkflowEvent('workflow/journal-commit', info, entry) },\n },\n request.signal,\n request.scratchDir,\n {\n maxProtocolMessageBytes: this.config.maxProtocolMessageBytes,\n maxJournalBytes: this.config.maxJournalBytes,\n maxChildPromptBytes: this.config.maxChildPromptBytes,\n maxEventTextBytes: this.config.maxEventTextBytes,\n scratch: {\n maxOperations: this.config.scratchMaxOperations,\n maxPendingOperations: this.config.scratchMaxPendingOperations,\n maxFiles: this.config.scratchMaxFiles,\n maxFileBytes: this.config.scratchMaxFileBytes,\n maxTotalBytes: this.config.scratchMaxTotalBytes,\n },\n } satisfies WorkerHostLimits,\n (request as any).deferStart === true,\n (request as any).scratch,\n )\n\n this.emitWorkflowEvent('workflow/start', info)\n // `workflow/end` fires as the (never-rejecting) result settles, with the\n // outcome DATA only — the value stays with the run's holder.\n void workerRun.result.then((settled) => {\n this.emitWorkflowEvent('workflow/end', info, {\n stopReason: settled.stopReason,\n ...settled.error !== undefined ? { error: settled.error } : {},\n ...settled.errorCode !== undefined ? { errorCode: settled.errorCode } : {},\n agentsStarted: settled.agentsStarted,\n })\n })\n\n return workerRun\n }\n}\n\nexport default WorkerThreadWorkflowEngine\n"],"mappings":";;;;;;;;;;;;;;;AAUA,MAAaA,kBAAgBC;;;;;;;;;;;;;ACC7B,IAAa,mBAAb,cAAsC,MAAM;CAC1C,YAAY,MAA8B,QAAgC;EACxE,MAAM,GAAG,KAAK,IAAI,QAAQ;EADA,KAAA,OAAA;EAA8B,KAAA,SAAA;EAExD,KAAK,OAAO;CACd;AACF;;;;;;;;;;AAWA,SAAgB,aAAa,OAAwB;CACnD,IAAI;EACF,MAAM,QAAS,OAAkD;EACjE,IAAI,OAAO,UAAU,YAAY,MAAM,SAAS,GAAG,OAAO;EAC1D,MAAM,UAAW,OAAoD;EACrE,IAAI,OAAO,YAAY,YAAY,QAAQ,SAAS,GAAG,OAAO;EAC9D,OAAO,OAAO,KAAK;CACrB,QAAQ;EAGN,OAAO;CACT;AACF;;;;;;;AAQA,SAAS,kBAAkB,OAAwB;CACjD,MAAM,QAAiB,OAAO,eAAe,KAAK;CAClD,IAAI,UAAU,MAAM,OAAO;CAC3B,OAAO,OAAO,eAAe,KAAK,MAAM;AAC1C;;;;;;;;;;;;;AAcA,SAAgB,qBAAqB,OAAgB,OAAO,SAAkB;CAC5E,IAAI,UAAU,KAAA,GAAW,OAAO,KAAA;CAChC,IAAI;EACF,OAAO,YAAY,OAAO,sBAAM,IAAI,IAAI,CAAC;CAC3C,SAAS,OAAgB;EACvB,IAAI,iBAAiB,kBAAkB,MAAM;EAG7C,MAAM,IAAI,iBAAiB,MAAM,4BAA4B,aAAa,KAAK,GAAG;CACpF;AACF;AAEA,SAAS,YAAY,OAAgB,MAAc,MAA4B;CAC7E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