@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.
Files changed (229) hide show
  1. package/LICENSE +21 -0
  2. package/NOTICE.md +224 -0
  3. package/README.i18n.yaml +4 -0
  4. package/README.md +109 -0
  5. package/README.zh.md +109 -0
  6. package/cordis.patch.yml +10 -0
  7. package/docs/architecture.i18n.yaml +4 -0
  8. package/docs/architecture.md +177 -0
  9. package/docs/architecture.zh.md +177 -0
  10. package/docs/testing.i18n.yaml +4 -0
  11. package/docs/testing.md +125 -0
  12. package/docs/testing.zh.md +125 -0
  13. package/docs/user-guide.i18n.yaml +4 -0
  14. package/docs/user-guide.md +351 -0
  15. package/docs/user-guide.zh.md +351 -0
  16. package/lib/client-types/WorkflowMemberInspector.d.ts +28 -0
  17. package/lib/client-types/WorkflowMemberInspector.d.ts.map +1 -0
  18. package/lib/client-types/WorkflowMemberInspector.js +181 -0
  19. package/lib/client-types/WorkflowMemberInspector.js.map +1 -0
  20. package/lib/client-types/WorkflowRunPanel.d.ts +43 -0
  21. package/lib/client-types/WorkflowRunPanel.d.ts.map +1 -0
  22. package/lib/client-types/WorkflowRunPanel.js +130 -0
  23. package/lib/client-types/WorkflowRunPanel.js.map +1 -0
  24. package/lib/client-types/WorkflowsDashboard.d.ts +49 -0
  25. package/lib/client-types/WorkflowsDashboard.d.ts.map +1 -0
  26. package/lib/client-types/WorkflowsDashboard.js +942 -0
  27. package/lib/client-types/WorkflowsDashboard.js.map +1 -0
  28. package/lib/client-types/adapter.d.ts +60 -0
  29. package/lib/client-types/adapter.d.ts.map +1 -0
  30. package/lib/client-types/adapter.js +117 -0
  31. package/lib/client-types/adapter.js.map +1 -0
  32. package/lib/client-types/chat-renderer.d.ts +10 -0
  33. package/lib/client-types/chat-renderer.d.ts.map +1 -0
  34. package/lib/client-types/chat-renderer.js +11 -0
  35. package/lib/client-types/chat-renderer.js.map +1 -0
  36. package/lib/client-types/contract.d.ts +210 -0
  37. package/lib/client-types/contract.d.ts.map +1 -0
  38. package/lib/client-types/contract.js +37 -0
  39. package/lib/client-types/contract.js.map +1 -0
  40. package/lib/client-types/controller.d.ts +83 -0
  41. package/lib/client-types/controller.d.ts.map +1 -0
  42. package/lib/client-types/controller.js +705 -0
  43. package/lib/client-types/controller.js.map +1 -0
  44. package/lib/client-types/index.d.ts +19 -0
  45. package/lib/client-types/index.d.ts.map +1 -0
  46. package/lib/client-types/index.js +730 -0
  47. package/lib/client-types/index.js.map +1 -0
  48. package/lib/client-types/locales.d.ts +257 -0
  49. package/lib/client-types/locales.d.ts.map +1 -0
  50. package/lib/client-types/locales.js +270 -0
  51. package/lib/client-types/locales.js.map +1 -0
  52. package/lib/client-types/slot-components.d.ts +38 -0
  53. package/lib/client-types/slot-components.d.ts.map +1 -0
  54. package/lib/client-types/slot-components.js +22 -0
  55. package/lib/client-types/slot-components.js.map +1 -0
  56. package/lib/client-types/store.d.ts +69 -0
  57. package/lib/client-types/store.d.ts.map +1 -0
  58. package/lib/client-types/store.js +135 -0
  59. package/lib/client-types/store.js.map +1 -0
  60. package/lib/client-types/workflow-definition.d.ts +52 -0
  61. package/lib/client-types/workflow-definition.d.ts.map +1 -0
  62. package/lib/client-types/workflow-definition.js +135 -0
  63. package/lib/client-types/workflow-definition.js.map +1 -0
  64. package/lib/client.js +11064 -0
  65. package/lib/client.js.map +1 -0
  66. package/lib/compat-engine/index.js +1926 -0
  67. package/lib/compat-engine/index.js.map +1 -0
  68. package/lib/compat-engine/worker.cjs +1500 -0
  69. package/lib/compat-engine/worker.cjs.map +1 -0
  70. package/lib/typert.host.d.ts +3 -0
  71. package/lib/typert.host.js +1709 -0
  72. package/lib/typert.remote-client.d.ts +57 -0
  73. package/lib/typert.remote-client.js +1662 -0
  74. package/lib/types/commands/aliases.d.ts +4 -0
  75. package/lib/types/commands/aliases.d.ts.map +1 -0
  76. package/lib/types/commands/aliases.js +25 -0
  77. package/lib/types/commands/aliases.js.map +1 -0
  78. package/lib/types/commands/index.d.ts +66 -0
  79. package/lib/types/commands/index.d.ts.map +1 -0
  80. package/lib/types/commands/index.js +550 -0
  81. package/lib/types/commands/index.js.map +1 -0
  82. package/lib/types/commands/parser.d.ts +17 -0
  83. package/lib/types/commands/parser.d.ts.map +1 -0
  84. package/lib/types/commands/parser.js +45 -0
  85. package/lib/types/commands/parser.js.map +1 -0
  86. package/lib/types/config.d.ts +71 -0
  87. package/lib/types/config.d.ts.map +1 -0
  88. package/lib/types/config.js +109 -0
  89. package/lib/types/config.js.map +1 -0
  90. package/lib/types/index.d.ts +41 -0
  91. package/lib/types/index.d.ts.map +1 -0
  92. package/lib/types/index.js +483 -0
  93. package/lib/types/index.js.map +1 -0
  94. package/lib/types/invariant.d.ts +21 -0
  95. package/lib/types/invariant.d.ts.map +1 -0
  96. package/lib/types/invariant.js +85 -0
  97. package/lib/types/invariant.js.map +1 -0
  98. package/lib/types/registry/definition.d.ts +24 -0
  99. package/lib/types/registry/definition.d.ts.map +1 -0
  100. package/lib/types/registry/definition.js +189 -0
  101. package/lib/types/registry/definition.js.map +1 -0
  102. package/lib/types/registry/index.d.ts +100 -0
  103. package/lib/types/registry/index.d.ts.map +1 -0
  104. package/lib/types/registry/index.js +899 -0
  105. package/lib/types/registry/index.js.map +1 -0
  106. package/lib/types/registry/names.d.ts +19 -0
  107. package/lib/types/registry/names.d.ts.map +1 -0
  108. package/lib/types/registry/names.js +69 -0
  109. package/lib/types/registry/names.js.map +1 -0
  110. package/lib/types/registry/remote.d.ts +15 -0
  111. package/lib/types/registry/remote.d.ts.map +1 -0
  112. package/lib/types/registry/remote.js +128 -0
  113. package/lib/types/registry/remote.js.map +1 -0
  114. package/lib/types/registry/roots.d.ts +44 -0
  115. package/lib/types/registry/roots.d.ts.map +1 -0
  116. package/lib/types/registry/roots.js +118 -0
  117. package/lib/types/registry/roots.js.map +1 -0
  118. package/lib/types/registry/types.d.ts +62 -0
  119. package/lib/types/registry/types.d.ts.map +1 -0
  120. package/lib/types/registry/types.js +2 -0
  121. package/lib/types/registry/types.js.map +1 -0
  122. package/lib/types/registry/watchers.d.ts +70 -0
  123. package/lib/types/registry/watchers.d.ts.map +1 -0
  124. package/lib/types/registry/watchers.js +152 -0
  125. package/lib/types/registry/watchers.js.map +1 -0
  126. package/lib/types/remote-events.d.ts +42 -0
  127. package/lib/types/remote-events.d.ts.map +1 -0
  128. package/lib/types/remote-events.js +21 -0
  129. package/lib/types/remote-events.js.map +1 -0
  130. package/lib/types/run-recorder.d.ts +44 -0
  131. package/lib/types/run-recorder.d.ts.map +1 -0
  132. package/lib/types/run-recorder.js +356 -0
  133. package/lib/types/run-recorder.js.map +1 -0
  134. package/lib/types/supervisor/canned-validate.d.ts +25 -0
  135. package/lib/types/supervisor/canned-validate.d.ts.map +1 -0
  136. package/lib/types/supervisor/canned-validate.js +122 -0
  137. package/lib/types/supervisor/canned-validate.js.map +1 -0
  138. package/lib/types/supervisor/completion-notice.d.ts +49 -0
  139. package/lib/types/supervisor/completion-notice.d.ts.map +1 -0
  140. package/lib/types/supervisor/completion-notice.js +281 -0
  141. package/lib/types/supervisor/completion-notice.js.map +1 -0
  142. package/lib/types/supervisor/cursors.d.ts +68 -0
  143. package/lib/types/supervisor/cursors.d.ts.map +1 -0
  144. package/lib/types/supervisor/cursors.js +158 -0
  145. package/lib/types/supervisor/cursors.js.map +1 -0
  146. package/lib/types/supervisor/engine-compat.d.ts +48 -0
  147. package/lib/types/supervisor/engine-compat.d.ts.map +1 -0
  148. package/lib/types/supervisor/engine-compat.js +116 -0
  149. package/lib/types/supervisor/engine-compat.js.map +1 -0
  150. package/lib/types/supervisor/index.d.ts +183 -0
  151. package/lib/types/supervisor/index.d.ts.map +1 -0
  152. package/lib/types/supervisor/index.js +2040 -0
  153. package/lib/types/supervisor/index.js.map +1 -0
  154. package/lib/types/supervisor/parallel-compat.d.ts +36 -0
  155. package/lib/types/supervisor/parallel-compat.d.ts.map +1 -0
  156. package/lib/types/supervisor/parallel-compat.js +180 -0
  157. package/lib/types/supervisor/parallel-compat.js.map +1 -0
  158. package/lib/types/supervisor/remote.d.ts +25 -0
  159. package/lib/types/supervisor/remote.d.ts.map +1 -0
  160. package/lib/types/supervisor/remote.js +478 -0
  161. package/lib/types/supervisor/remote.js.map +1 -0
  162. package/lib/types/supervisor/storage/bounded-file.d.ts +41 -0
  163. package/lib/types/supervisor/storage/bounded-file.d.ts.map +1 -0
  164. package/lib/types/supervisor/storage/bounded-file.js +186 -0
  165. package/lib/types/supervisor/storage/bounded-file.js.map +1 -0
  166. package/lib/types/supervisor/storage/details-codec.d.ts +14 -0
  167. package/lib/types/supervisor/storage/details-codec.d.ts.map +1 -0
  168. package/lib/types/supervisor/storage/details-codec.js +359 -0
  169. package/lib/types/supervisor/storage/details-codec.js.map +1 -0
  170. package/lib/types/supervisor/storage/index.d.ts +26 -0
  171. package/lib/types/supervisor/storage/index.d.ts.map +1 -0
  172. package/lib/types/supervisor/storage/index.js +100 -0
  173. package/lib/types/supervisor/storage/index.js.map +1 -0
  174. package/lib/types/supervisor/storage/lease.d.ts +34 -0
  175. package/lib/types/supervisor/storage/lease.d.ts.map +1 -0
  176. package/lib/types/supervisor/storage/lease.js +289 -0
  177. package/lib/types/supervisor/storage/lease.js.map +1 -0
  178. package/lib/types/supervisor/storage/manifest-codec.d.ts +10 -0
  179. package/lib/types/supervisor/storage/manifest-codec.d.ts.map +1 -0
  180. package/lib/types/supervisor/storage/manifest-codec.js +335 -0
  181. package/lib/types/supervisor/storage/manifest-codec.js.map +1 -0
  182. package/lib/types/supervisor/storage/manifest-store.d.ts +99 -0
  183. package/lib/types/supervisor/storage/manifest-store.d.ts.map +1 -0
  184. package/lib/types/supervisor/storage/manifest-store.js +1606 -0
  185. package/lib/types/supervisor/storage/manifest-store.js.map +1 -0
  186. package/lib/types/supervisor/storage/manifest-types.d.ts +269 -0
  187. package/lib/types/supervisor/storage/manifest-types.d.ts.map +1 -0
  188. package/lib/types/supervisor/storage/manifest-types.js +2 -0
  189. package/lib/types/supervisor/storage/manifest-types.js.map +1 -0
  190. package/lib/types/supervisor/storage/private-root.d.ts +143 -0
  191. package/lib/types/supervisor/storage/private-root.d.ts.map +1 -0
  192. package/lib/types/supervisor/storage/private-root.js +860 -0
  193. package/lib/types/supervisor/storage/private-root.js.map +1 -0
  194. package/lib/types/supervisor/storage/recovery.d.ts +14 -0
  195. package/lib/types/supervisor/storage/recovery.d.ts.map +1 -0
  196. package/lib/types/supervisor/storage/recovery.js +126 -0
  197. package/lib/types/supervisor/storage/recovery.js.map +1 -0
  198. package/lib/types/supervisor/storage/run-files.d.ts +67 -0
  199. package/lib/types/supervisor/storage/run-files.d.ts.map +1 -0
  200. package/lib/types/supervisor/storage/run-files.js +346 -0
  201. package/lib/types/supervisor/storage/run-files.js.map +1 -0
  202. package/lib/types/supervisor/types.d.ts +295 -0
  203. package/lib/types/supervisor/types.d.ts.map +1 -0
  204. package/lib/types/supervisor/types.js +3 -0
  205. package/lib/types/supervisor/types.js.map +1 -0
  206. package/lib/types/supervisor/value-view.d.ts +19 -0
  207. package/lib/types/supervisor/value-view.d.ts.map +1 -0
  208. package/lib/types/supervisor/value-view.js +183 -0
  209. package/lib/types/supervisor/value-view.js.map +1 -0
  210. package/lib/types/tool/index.d.ts +86 -0
  211. package/lib/types/tool/index.d.ts.map +1 -0
  212. package/lib/types/tool/index.js +810 -0
  213. package/lib/types/tool/index.js.map +1 -0
  214. package/lib/types/tool/schema.d.ts +158 -0
  215. package/lib/types/tool/schema.d.ts.map +1 -0
  216. package/lib/types/tool/schema.js +137 -0
  217. package/lib/types/tool/schema.js.map +1 -0
  218. package/lib/types/types.d.ts +9 -0
  219. package/lib/types/types.d.ts.map +1 -0
  220. package/lib/types/types.js +3 -0
  221. package/lib/types/types.js.map +1 -0
  222. package/lib/types/user-questions.d.ts +9 -0
  223. package/lib/types/user-questions.d.ts.map +1 -0
  224. package/lib/types/user-questions.js +91 -0
  225. package/lib/types/user-questions.js.map +1 -0
  226. package/package.json +273 -0
  227. package/skills/create-workflow/SKILL.md +166 -0
  228. package/vendor/workflow-engine/LICENSE +21 -0
  229. package/vendor/workflow-engine/README.md +1 -0
@@ -0,0 +1 @@
1
+ {"version":3,"file":"worker.cjs","names":["WorkflowError","StockWorkflowError","WorkflowError","JsonSchemaError","validateJsonSchemaValue","AsyncLocalStorage","vm","SessionId","isFatalWorkflowError","createHash","WorkflowError","parentPort","workerData"],"sources":["../../vendor/workflow-engine/realm.ts","../../vendor/workflow-engine/compat-seam.ts","../../vendor/workflow-engine/runtime.ts","../../vendor/workflow-engine/session.ts","../../vendor/workflow-engine/worker.ts"],"sourcesContent":["/**\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","/** 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 * Per-run worker-side vm hooks, child RPC, concurrency/caps, cancellation, and result serialization; it\n * never touches Cordis. Script values leaving the realm are materialized as plain JSON before\n * messaging. Values entering the trusted model-written realm are passed directly; `args` alone is\n * cloned so script mutation cannot alter initialization data. See `./realm.ts` for the trust model.\n *\n * Fatal workflow errors—bad hook arguments, unsupported schemas/options, caps, start failures, and\n * cancellation—propagate through combinators. Only child failures and ordinary stage errors become\n * per-item nulls. Every returned promise has a rejection consumer so dropped script promises cannot\n * kill the worker. A cancelled script that never settles emits nothing; the host force-settles the\n * run within grace and terminates the thread.\n * @module @deepseek-ai/dsh-workflow-worker-thread/runtime\n */\n\nimport { AsyncLocalStorage } from 'node:async_hooks'\nimport { createHash } from 'node:crypto'\nimport * as vm from 'node:vm'\nimport type { ContentBlock } from '@deepseek-ai/dsh-llm'\nimport { SessionId, type JsonValue } from '@deepseek-ai/dsh-session'\nimport { assertObjectJsonSchema, JsonSchemaError, validateJsonSchemaValue } from '@deepseek-ai/dsh-tools'\nimport type { JsonSchemaNode, ObjectJsonSchema } from '@deepseek-ai/dsh-tools'\nimport { isFatalWorkflowError } from '@deepseek-ai/dsh-workflow'\nimport type {\n WorkflowAgentEndInfo,\n WorkflowAgentInfo,\n WorkflowMeta,\n} from '@deepseek-ai/dsh-workflow'\nimport { WorkflowError, type WorkflowGateInfo, type WorkflowGateKind, type WorkflowResult } from './compat-seam.ts'\nimport { materializeFromRealm, MaterializeError, renderThrown } from './realm.ts'\nimport type { ChildHandle, ChildPort, WorkerLimits, WorkflowJournalEntry } from './types.ts'\n\n/** The observers the execution reports progress through (the session posts them to the host). */\nexport interface ExecutionObserver {\n phase(title: string): void\n log(message: string): void\n agentStart(info: WorkflowAgentInfo): void\n agentEnd(info: WorkflowAgentEndInfo): void\n gate(gate: WorkflowGateInfo): void\n journalCommit(entry: WorkflowJournalEntry): void\n}\n\n/** One new journal entry before the runtime assigns its commit ordinal. */\ntype PendingJournalEntry = WorkflowJournalEntry extends infer Entry\n ? Entry extends WorkflowJournalEntry ? Omit<Entry, 'ordinal'> : never\n : never\n\n/** Deterministic position of one concurrently executing combinator branch. */\ninterface CallScope {\n readonly path: readonly number[]\n nextNode: number\n currentPhase?: string\n reservation?: AgentReservation\n}\n\n/** One atomically admitted declarative job; exactly one direct `agent()` consumes it. */\ninterface AgentReservation {\n available: boolean\n}\n\n/** Validated options used for one child request and its replay fingerprint. */\ninterface AgentOptions {\n label?: string\n phase?: string\n provider?: string\n model?: string\n schema?: ObjectJsonSchema\n}\n\n/**\n * One authored schema plus the RC2-compatible projection sent to the stock\n * subagent seam. The authored tree remains the authority for fingerprints,\n * canned validation, and child-result validation; only the provider copy has\n * the two forward-compatible array-bound keywords removed.\n */\ninterface PreparedAgentOptions {\n readonly options: AgentOptions\n readonly providerSchema?: ObjectJsonSchema\n}\n\n/** RC2's public type predates the two array-bound fields supported here. */\ntype BoundedJsonSchemaNode = JsonSchemaNode & {\n readonly minItems?: number\n readonly maxItems?: number\n}\n\n/** One validated parallel item plus whether its single child is statically known. */\ninterface ParallelItem {\n readonly run: () => unknown\n readonly kind: 'thunk' | 'job'\n readonly reservesAgent: boolean\n}\n\n/**\n * Build a callable/constructable global that fails before exposing ambient\n * process state. The vm is not a security boundary, but ordinary authored\n * workflows must not accidentally make resumed control flow depend on the\n * clock, randomness, garbage collection, or timer-like atomics.\n */\nfunction unavailableNondeterministicGlobal(name: string): unknown {\n const fail = (): never => {\n throw new WorkflowError(\n `${name} is unavailable in workflow scripts because runs must derive control flow from args and committed host results`,\n 'INVALID_ARGUMENT',\n )\n }\n /* v8 ignore next -- every call/construct/property operation is intercepted by the Proxy traps below */\n const target = Object.freeze(function unavailableWorkflowGlobal(): never { return fail() })\n return Object.freeze(new Proxy(target, {\n apply: fail,\n construct: fail,\n get: fail,\n set: fail,\n }))\n}\n\n/** Clone the deterministic Math surface while replacing its random source. */\nfunction deterministicMath(): Math {\n const descriptors = Object.getOwnPropertyDescriptors(Math)\n descriptors.random = {\n ...descriptors.random,\n value: Object.freeze((): never => {\n throw new WorkflowError(\n 'Math.random() is unavailable in workflow scripts because runs must derive control flow from args and committed host results',\n 'INVALID_ARGUMENT',\n )\n }),\n }\n return Object.freeze(Object.defineProperties(Object.create(Reflect.getPrototypeOf(Math)) as Math, descriptors))\n}\n\n/** Define one JSON object key without giving `__proto__` assignment semantics. */\nfunction defineJsonProperty(target: Record<string, JsonValue>, key: string, value: JsonValue): void {\n Object.defineProperty(target, key, {\n configurable: true,\n enumerable: true,\n writable: true,\n value,\n })\n}\n\n/** Copy one generated JSON object while retaining every key as data. */\nfunction copyJsonObject(source: Readonly<Record<string, JsonValue>>): Record<string, JsonValue> {\n const copy: Record<string, JsonValue> = {}\n for (const [key, value] of Object.entries(source)) defineJsonProperty(copy, key, value)\n return copy\n}\n\n/** Define a schema key without giving `__proto__` assignment semantics. */\nfunction defineSchemaProperty(target: Record<string, unknown>, key: string, value: unknown): void {\n Object.defineProperty(target, key, {\n configurable: true,\n enumerable: true,\n writable: true,\n value,\n })\n}\n\n/** Whether a bound is a lossless, non-negative safe integer (including rejecting `-0`). */\nfunction isArrayBound(value: unknown): value is number {\n return typeof value === 'number'\n && Number.isSafeInteger(value)\n && value >= 0\n && !Object.is(value, -0)\n}\n\n/**\n * Validate the plugin's two forward-compatible schema keywords and produce\n * the projection accepted by stock RC2. Traversal follows schema-bearing\n * locations only: annotation payloads are data and must not be rewritten.\n */\nfunction prepareObjectSchema(authored: unknown): { authored: ObjectJsonSchema; provider: ObjectJsonSchema } {\n const boundViolations: string[] = []\n\n const visit = (rawNode: unknown, path: string): unknown => {\n if (typeof rawNode !== 'object' || rawNode === null || Array.isArray(rawNode)) return rawNode\n const node = rawNode as Record<string, unknown>\n const provider: Record<string, unknown> = {}\n const hasMin = Object.hasOwn(node, 'minItems')\n const hasMax = Object.hasOwn(node, 'maxItems')\n const hasOneOf = Object.hasOwn(node, 'oneOf')\n\n for (const keyword of ['minItems', 'maxItems'] as const) {\n if (!Object.hasOwn(node, keyword)) continue\n if (hasOneOf) {\n boundViolations.push(`${path}.${keyword} is not supported beside oneOf`)\n } else if (node.type !== 'array') {\n boundViolations.push(Object.hasOwn(node, 'type')\n ? `${path}.${keyword} is not supported on type ${JSON.stringify(node.type)}`\n : `${path}.${keyword} requires type or oneOf`)\n }\n }\n\n let minimum: number | undefined\n let maximum: number | undefined\n if (!hasOneOf && node.type === 'array') {\n if (hasMin) {\n if (!isArrayBound(node.minItems)) {\n boundViolations.push(`${path}.minItems must be a non-negative safe integer`)\n } else {\n minimum = node.minItems\n }\n }\n if (hasMax) {\n if (!isArrayBound(node.maxItems)) {\n boundViolations.push(`${path}.maxItems must be a non-negative safe integer`)\n } else {\n maximum = node.maxItems\n }\n }\n if (minimum !== undefined && maximum !== undefined && minimum > maximum) {\n boundViolations.push(`${path}.minItems must not exceed ${path}.maxItems`)\n }\n }\n\n for (const [key, value] of Object.entries(node)) {\n if (key === 'minItems' || key === 'maxItems') continue\n if (key === 'items') {\n defineSchemaProperty(provider, key, visit(value, `${path}.items`))\n continue\n }\n if (key === 'oneOf' && Array.isArray(value)) {\n defineSchemaProperty(provider, key, value.map((branch, index) => visit(branch, `${path}.oneOf[${index}]`)))\n continue\n }\n if (key === 'properties' && typeof value === 'object' && value !== null && !Array.isArray(value)) {\n const properties: Record<string, unknown> = {}\n for (const [name, child] of Object.entries(value as Record<string, unknown>)) {\n defineSchemaProperty(properties, name, visit(child, `${path}.properties.${name}`))\n }\n defineSchemaProperty(provider, key, properties)\n continue\n }\n defineSchemaProperty(provider, key, value)\n }\n return provider\n }\n\n const provider = visit(authored, 'schema')\n let stockViolations: string[] = []\n try {\n assertObjectJsonSchema(provider)\n } catch (error: unknown) {\n /* v8 ignore next -- assertObjectJsonSchema only throws JsonSchemaError */\n if (!(error instanceof JsonSchemaError)) throw error\n stockViolations = error.violations\n }\n const violations = [...boundViolations, ...stockViolations]\n if (violations.length > 0) throw new JsonSchemaError(violations)\n return { authored: authored as ObjectJsonSchema, provider: provider as ObjectJsonSchema }\n}\n\n/**\n * Validate against the authored extended subset while continuing to delegate\n * all ordinary JSON/type/scalar checks to RC2's shared validator. Object and\n * array children are walked here so bounds can participate in exact-one\n * `oneOf` matching instead of the stripped provider branches becoming\n * spuriously overlapping.\n */\nfunction schemaValueMatches(schema: JsonSchemaNode, value: unknown): boolean {\n if (schema.oneOf !== undefined) {\n let matches = 0\n for (const branch of schema.oneOf) {\n if (schemaValueMatches(branch, value)) matches += 1\n if (matches > 1) return false\n }\n return matches === 1\n }\n\n if (schema.type === 'object') {\n if (validateJsonSchemaValue({ type: 'object' }, value).length > 0) return false\n const record = value as Record<string, unknown>\n const properties = schema.properties ?? {}\n for (const required of schema.required ?? []) {\n if (!Object.hasOwn(record, required)) return false\n }\n if (schema.additionalProperties === false) {\n for (const key of Object.keys(record)) {\n if (!Object.hasOwn(properties, key)) return false\n }\n }\n for (const [key, childSchema] of Object.entries(properties)) {\n if (Object.hasOwn(record, key) && !schemaValueMatches(childSchema, record[key])) return false\n }\n return true\n }\n\n if (schema.type === 'array') {\n if (validateJsonSchemaValue({ type: 'array' }, value).length > 0) return false\n const array = value as unknown[]\n const bounded = schema as BoundedJsonSchemaNode\n if (bounded.minItems !== undefined && array.length < bounded.minItems) return false\n if (bounded.maxItems !== undefined && array.length > bounded.maxItems) return false\n if (schema.items !== undefined) {\n for (const item of array) {\n if (!schemaValueMatches(schema.items, item)) return false\n }\n }\n return true\n }\n\n return validateJsonSchemaValue(schema, value).length === 0\n}\n\n/** Deterministic unconstrained candidates used to disambiguate exact-one unions. */\nconst ANY_JSON_CANDIDATES: readonly JsonValue[] = [null, false, true, 0, 0.5, '', 'value', [], {}]\n\n/** Count serialized JSON nodes up to a configured smoke-host work limit. */\nfunction jsonNodeCount(value: JsonValue, limit: number): number {\n let count = 0\n const pending: JsonValue[] = [value]\n for (let current = pending.pop(); current !== undefined; current = pending.pop()) {\n count += 1\n if (count > limit) return count\n if (Array.isArray(current)) {\n for (const child of current) pending.push(child)\n } else if (typeof current === 'object' && current !== null) {\n for (const child of Object.values(current)) pending.push(child)\n }\n }\n return count\n}\n\n/**\n * Produce deterministic candidates for one already-validated schema node.\n * Returned candidates satisfy the node; an empty list means the supported\n * exact-one vocabulary has no value this smoke host can construct.\n */\nfunction cannedSchemaCandidates(schema: JsonSchemaNode, maxArrayItems: number): JsonValue[] {\n let candidates: JsonValue[]\n if (schema.oneOf !== undefined) {\n candidates = []\n for (const branch of schema.oneOf) {\n for (const candidate of cannedSchemaCandidates(branch, maxArrayItems)) {\n if (candidates.length >= maxArrayItems) break\n candidates.push(candidate)\n }\n if (candidates.length >= maxArrayItems) break\n }\n for (const candidate of ANY_JSON_CANDIDATES) {\n if (candidates.length >= maxArrayItems) break\n candidates.push(candidate)\n }\n } else if (Object.hasOwn(schema, 'const')) {\n candidates = [schema.const as JsonValue]\n } else if (schema.enum !== undefined) {\n candidates = [...schema.enum]\n } else {\n switch (schema.type) {\n case 'object': {\n const properties = schema.properties ?? {}\n const required = schema.required ?? []\n const base: Record<string, JsonValue> = {}\n const requiredCandidates = new Map<string, JsonValue[]>()\n for (const key of required) {\n const values = cannedSchemaCandidates(properties[key] as JsonSchemaNode, maxArrayItems)\n if (values.length === 0) return []\n requiredCandidates.set(key, values)\n defineJsonProperty(base, key, values[0] as JsonValue)\n }\n candidates = [base]\n for (const [key, values] of requiredCandidates) {\n for (const value of values.slice(1)) {\n if (candidates.length >= maxArrayItems) break\n const alternate = copyJsonObject(base)\n defineJsonProperty(alternate, key, value)\n candidates.push(alternate)\n }\n }\n const optional = Object.entries(properties).filter(([key]) => !requiredCandidates.has(key))\n const withAllOptional = copyJsonObject(base)\n let hasAllOptional = false\n for (const [key, childSchema] of optional) {\n const values = cannedSchemaCandidates(childSchema, maxArrayItems)\n for (const value of values) {\n if (candidates.length >= maxArrayItems) break\n const alternate = copyJsonObject(base)\n defineJsonProperty(alternate, key, value)\n candidates.push(alternate)\n }\n if (values[0] !== undefined) {\n defineJsonProperty(withAllOptional, key, values[0])\n hasAllOptional = true\n }\n }\n if (hasAllOptional) candidates.push(withAllOptional)\n break\n }\n case 'array': {\n const arraySchema = schema as JsonSchemaNode & { minItems?: number; maxItems?: number }\n const minimum = arraySchema.minItems ?? 0\n if (minimum > maxArrayItems) return []\n const mayContainItem = arraySchema.maxItems === undefined || arraySchema.maxItems > 0\n const itemCandidates = schema.items === undefined ? [null] : cannedSchemaCandidates(schema.items, maxArrayItems)\n candidates = minimum === 0 ? [[]] : []\n for (const value of itemCandidates) {\n if (minimum > 0 && 1 + minimum * jsonNodeCount(value, maxArrayItems) <= maxArrayItems) {\n candidates.push(Array.from({ length: minimum }, () => value))\n }\n else if (mayContainItem) candidates.push([value])\n }\n break\n }\n case 'string': candidates = ['', 'value']; break\n case 'number': candidates = [0, 0.5, 1, -1]; break\n case 'integer': candidates = [0, 1, -1]; break\n case 'boolean': candidates = [false, true]; break\n case 'null': candidates = [null]; break\n case undefined: candidates = [...ANY_JSON_CANDIDATES]; break\n /* v8 ignore next -- assertObjectJsonSchema validated the closed schema vocabulary recursively. */\n default: return []\n }\n }\n return candidates\n .filter(candidate => jsonNodeCount(candidate, maxArrayItems) <= maxArrayItems)\n .filter(candidate => schemaValueMatches(schema, candidate))\n .slice(0, maxArrayItems)\n}\n\n/** Synthesize one schema-conforming structured result for `validate_only`. */\nfunction cannedSchemaValue(schema: ObjectJsonSchema, maxArrayItems: number): JsonValue {\n const candidate = cannedSchemaCandidates(schema, maxArrayItems)[0]\n if (candidate !== undefined) return candidate\n throw new WorkflowError(\n 'validate_only could not synthesize a canned result that conforms to the agent() schema',\n 'UNSUPPORTED_SCHEMA',\n )\n}\n\n/** The `agent()` options the script may pass; everything else rejects loud. */\nconst SUPPORTED_AGENT_OPTIONS = new Set(['label', 'phase', 'schema', 'provider', 'model'])\n/** Deferred Claude Code options we name explicitly in the rejection message. */\nconst DEFERRED_AGENT_OPTIONS = new Set(['effort', 'isolation', 'agentType'])\n\n/** Flatten a child's final output blocks to text (the non-schema `agent()` result). */\nfunction outputText(blocks: ContentBlock[]): string {\n return blocks\n .filter((block): block is Extract<ContentBlock, { type: 'text' }> => block.type === 'text')\n .map(block => block.text)\n .join('')\n}\n\n/** A short display label derived from the prompt when the script passes none. */\nfunction defaultLabel(prompt: string): string {\n const newline = prompt.indexOf('\\n')\n const line = newline === -1 ? prompt : prompt.slice(0, newline)\n return line.length <= 48 ? line : `${line.slice(0, 47)}…`\n}\n\n/**\n * One live script execution inside the worker. Constructed per run by the\n * session; `drive()` is called exactly once and NEVER rejects — every failure\n * becomes a {@link WorkflowResult} with a non-`completed` stop reason. The\n * host owns cancellation and cleanup of any dropped child work.\n */\nexport class WorkflowExecution {\n /** Cumulative logical-agent spend, including earlier attempts and current reservations. */\n private started: number\n /** Last member sequence issued; unlike spend, it never decreases when a reservation is refunded. */\n private nextAgentSeq: number\n private activeSlots = 0\n private readonly slotWaiters: { resolve(): void; reject(error: unknown): void }[] = []\n private cancelReason: string | undefined\n private cancelError: WorkflowError | undefined\n /** A `complete(value)` terminal, materialized before the sentinel throw. */\n private completed: { value: JsonValue } | undefined\n /** An invalid `complete(value)` terminal; script catches cannot turn it into success. */\n private completionError: WorkflowError | undefined\n private readonly completionGate = Promise.withResolvers<void>()\n /** Resolver for the gate the script is currently parked on. */\n private gateResume: (() => void) | undefined\n private readonly journal: ReadonlyMap<string, WorkflowJournalEntry>\n /** Replay entries actually consumed along this attempt's control-flow path. */\n private readonly replayedJournalCallIds = new Set<string>()\n /** Last host-call commit ordinal retained or issued by this attempt. */\n private nextJournalOrdinal: number\n private readonly callScopes = new AsyncLocalStorage<CallScope>()\n private readonly rootScope: CallScope = { path: [], nextNode: 0 }\n private readonly context: vm.Context\n private readonly compiled: vm.Script\n\n constructor(\n meta: WorkflowMeta,\n body: string,\n args: unknown,\n private readonly limits: WorkerLimits,\n private readonly observer: ExecutionObserver,\n private readonly children: ChildPort,\n journal: readonly WorkflowJournalEntry[] | undefined,\n private readonly validateOnly = false,\n initialAgentSpend = 0,\n initialAgentSeq = initialAgentSpend,\n ) {\n // Compile FIRST: a body syntax error must throw out of the constructor\n // before any realm state exists. The host pre-parses the identical\n // wrapper, so under one Node version this throw is unreachable in\n // production — the session still maps it to an error result defensively.\n // lineOffset compensates for the wrapper line, so stack traces carry the\n // script's own line numbers.\n try {\n this.compiled = new vm.Script(`(async () => {\\n${body}\\n})()`, {\n filename: `workflow:${meta.name}`,\n lineOffset: -1,\n })\n } catch (error: unknown) {\n throw new WorkflowError(`workflow script does not parse: ${String(error)}`, 'SCRIPT_PARSE', { cause: error })\n }\n\n const committedAgents = (journal ?? []).filter(entry => entry.kind === 'agent')\n this.started = Math.max(initialAgentSpend, committedAgents.length)\n let journalMaximum = 0\n let ordinalMaximum = 0\n for (const entry of committedAgents) journalMaximum = Math.max(journalMaximum, entry.seq)\n for (const entry of journal ?? []) ordinalMaximum = Math.max(ordinalMaximum, entry.ordinal)\n this.nextAgentSeq = Math.max(initialAgentSeq, this.started, journalMaximum)\n this.nextJournalOrdinal = ordinalMaximum\n this.journal = indexJournal(journal)\n this.context = vm.createContext({}, { name: `workflow:${meta.name}` })\n\n const globals: Record<string, unknown> = {\n agent: (prompt: unknown, opts?: unknown) => this.contain(this.agent(prompt, opts)),\n parallel: (items: unknown) => this.contain(this.parallel(items)),\n pipeline: (items: unknown, ...stages: unknown[]) => this.contain(this.pipeline(items, stages)),\n phase: (title: unknown) => { this.phase(title) },\n log: (message: unknown) => { this.log(message) },\n complete: (value: unknown) => { this.complete(value) },\n pause: (kind: unknown, message?: unknown) => this.contain(this.gate(kind, message, false)),\n await_user: (kind: unknown, message?: unknown) => this.contain(this.gate(kind, message, true)),\n budget: () => this.budget(),\n write_scratch_file: (name: unknown, content: unknown) => this.contain(this.writeScratch(name, content)),\n read_scratch_file: (name: unknown) => this.contain(this.readScratch(name)),\n Date: unavailableNondeterministicGlobal('Date'),\n Math: deterministicMath(),\n Atomics: unavailableNondeterministicGlobal('Atomics'),\n SharedArrayBuffer: unavailableNondeterministicGlobal('SharedArrayBuffer'),\n WeakRef: unavailableNondeterministicGlobal('WeakRef'),\n FinalizationRegistry: unavailableNondeterministicGlobal('FinalizationRegistry'),\n // workerData already performed the real cross-thread structured clone.\n args,\n }\n for (const [key, value] of Object.entries(globals)) {\n // Data properties on the contextified global; frozen shape not required —\n // a script overwriting its own hooks only sabotages itself.\n ;(this.context as Record<string, unknown>)[key] = typeof value === 'function' ? Object.freeze(value) : value\n }\n }\n\n /** Release the gate the script is parked on, if any. */\n resume(): void {\n this.gateResume?.()\n }\n\n /**\n * Whether the run has been cancelled. A METHOD, not an inline property\n * read: `cancel()` mutates `cancelReason` concurrently (the session's\n * message handler), and an inline read after an `await` gets narrowed by\n * control flow into an always-false comparison.\n */\n private isCancelled(): boolean {\n return this.cancelReason !== undefined\n }\n\n /**\n * Shared hook entry guard: after {@link cancel}, EVERY hook throws\n * `CANCELLED` at its next call — cancellation is the next HOOK boundary,\n * not just the next `agent()`, so a script that caught one cancelled\n * rejection cannot keep emitting progress through `phase`/`log` or enter a\n * combinator.\n */\n private throwIfCancelled(): void {\n if (this.completed !== undefined || this.completionError !== undefined) throw COMPLETE_SENTINEL\n if (this.isCancelled()) throw this.cancelledError()\n }\n\n /**\n * Cancel the run: waiting `agent()` slots reject and every future hook call\n * throws `CANCELLED` — the script dies at its next await. A script that\n * never settles anyway (parked on a promise no hook owns) is the HOST's\n * problem: its grace timer force-settles the run and terminates the\n * worker. Idempotent; the first reason wins.\n * @param reason - human-readable cause carried on the CANCELLED error. The\n * host independently aborts the required signal shared by every child.\n */\n cancel(reason: string): void {\n if (this.cancelReason !== undefined) return\n this.cancelReason = reason\n this.cancelError = new WorkflowError(`workflow run cancelled: ${this.cancelReason}`, 'CANCELLED')\n for (const waiter of this.slotWaiters.splice(0)) waiter.reject(this.cancelledError())\n this.gateResume?.()\n }\n\n /**\n * Run the script to settlement. Resolves — never rejects — with the run's\n * {@link WorkflowResult}: the materialized return value on `completed`, the\n * failure message on `error`, and `cancelled` when the script died of\n * cancellation. This method only chooses the result; the session publishes\n * it and the host owns terminal child cancellation.\n * @returns the settled outcome — this promise NEVER rejects (the seam's\n * `result`-never-rejects contract); every failure maps to a variant.\n */\n async drive(): Promise<WorkflowResult> {\n try {\n // Cancelled before the body ever ran (an already-aborted start signal,\n // relayed by the host before its `go`): the script must not execute at\n // all, let alone report `completed`.\n if (this.isCancelled()) throw this.cancelledError()\n const scriptPromise = this.callScopes.run(\n this.rootScope,\n () => this.compiled.runInContext(this.context, { timeout: this.limits.syncTimeoutMs }) as Promise<unknown>,\n )\n const scriptResult = this.contain(Promise.resolve(scriptPromise)).then(value => ({ kind: 'script' as const, value }))\n const completed = this.completionGate.promise.then(() => ({ kind: 'complete' as const }))\n const settled = await Promise.race([scriptResult, completed])\n if (settled.kind === 'complete') return this.completedResult()\n const raw: unknown = settled.value\n // `complete()` wins even when the script caught its sentinel and later\n // returned another value.\n /* v8 ignore next -- complete() resolves completionGate before a caught sentinel can settle scriptPromise */\n if (this.completed !== undefined || this.completionError !== undefined) return this.completedResult()\n // Cancelled while the body ran: a script that settled without touching\n // another hook (or without any) must still report `cancelled` — the\n // holder asked for cancellation and `completed` would be a lie.\n if (this.isCancelled()) throw this.cancelledError()\n const value = raw === undefined ? null : this.materializeResult(raw)\n const missingReplay = this.unreplayedJournalError()\n if (missingReplay !== undefined) throw missingReplay\n return { value, stopReason: 'completed', agentsStarted: this.started }\n } catch (error: unknown) {\n /* v8 ignore next -- completionGate wins the race whenever complete() has claimed a terminal */\n if (this.completed !== undefined || this.completionError !== undefined) return this.completedResult()\n // Any failure after cancel() reports `cancelled` with the canonical\n // reason — the reject path mirrors the resolve path's post-settle check.\n if (this.isCancelled()) {\n return {\n value: null,\n stopReason: 'cancelled',\n error: this.cancelledError().message,\n errorCode: 'CANCELLED',\n agentsStarted: this.started,\n }\n }\n /* v8 ignore next -- the out-of-band completionGate always wins before the sentinel reaches drive() */\n if (error === COMPLETE_SENTINEL) return this.completedResult()\n // renderThrown is total (thrown values of any realm), so this arm\n // cannot throw — drive() resolving is the `result` never-rejects contract\n // contract.\n return {\n value: null,\n stopReason: 'error',\n error: renderThrown(error),\n ...error instanceof WorkflowError ? { errorCode: error.code } : {},\n agentsStarted: this.started,\n }\n }\n }\n\n /** Materialize and report the `complete(value)` terminal. */\n private completedResult(): WorkflowResult {\n if (this.completionError !== undefined) {\n return {\n value: null,\n stopReason: 'error',\n error: this.completionError.message,\n errorCode: this.completionError.code,\n agentsStarted: this.started,\n }\n }\n const missingReplay = this.unreplayedJournalError()\n if (missingReplay !== undefined) {\n return {\n value: null,\n stopReason: 'error',\n error: missingReplay.message,\n errorCode: missingReplay.code,\n agentsStarted: this.started,\n }\n }\n const value = (this.completed as { value: JsonValue }).value\n return { value, stopReason: 'completed', agentsStarted: this.started }\n }\n\n /**\n * Attach a no-op rejection consumer WITHOUT changing what the caller\n * receives: if the script drops the promise (no await), cancellation cannot\n * become an unhandled rejection (which would kill the worker thread); if\n * the script does await it, it still observes the rejection.\n */\n private contain<T>(promise: Promise<T>): Promise<T> {\n promise.catch(() => { /* consumed: see method contract — a dropped hook promise must not surface an unhandled rejection */ })\n return promise\n }\n\n private cancelledError(): WorkflowError {\n // cancel() arms cancelError before any caller can observe isCancelled()\n // === true; the fallback guards the type, not a reachable path.\n /* v8 ignore next */\n return this.cancelError ?? new WorkflowError('workflow run cancelled', 'CANCELLED')\n }\n\n /** Materialize the script's return value; violations become RESULT_UNSERIALIZABLE. */\n private materializeResult(raw: unknown): JsonValue {\n try {\n return materializeFromRealm(raw, 'workflow result') as JsonValue\n } catch (error: unknown) {\n /* v8 ignore next -- defensive rethrow arm: materializeFromRealm only throws MaterializeError */\n if (!(error instanceof MaterializeError)) throw error\n throw new WorkflowError(\n `the workflow's return value is not plain JSON data — ${error.message}. Return only JSON-serializable objects/arrays/scalars.`,\n 'RESULT_UNSERIALIZABLE',\n { cause: error },\n )\n }\n }\n\n /**\n * Acquire one concurrency slot (FIFO). Cancellation rejects QUEUED waiters\n * (see {@link cancel}); the callers guard their own entry and post-acquire\n * windows, so no cancelled-precheck is duplicated here.\n */\n private acquireSlot(): Promise<void> {\n if (this.activeSlots < this.limits.maxConcurrentAgents) {\n this.activeSlots += 1\n return Promise.resolve()\n }\n return new Promise<void>((resolve, reject) => {\n this.slotWaiters.push({\n resolve: () => {\n this.activeSlots += 1\n resolve()\n },\n reject,\n })\n })\n }\n\n private releaseSlot(): void {\n this.activeSlots -= 1\n const next = this.slotWaiters.shift()\n if (next) next.resolve()\n }\n\n /** Claim the next deterministic node under the current combinator branch. */\n private claimCallId(_kind: 'agent' | 'parallel' | 'pipeline' | 'phase' | 'log' | 'scratch-read' | 'scratch-write' | 'await-user'): readonly [number, ...number[]] {\n const scope = this.currentScope()\n scope.nextNode += 1\n return [...scope.path, scope.nextNode] as unknown as [number, ...number[]]\n }\n\n /** Resolve and verify one committed replay entry for the current call. */\n private replayEntry<K extends WorkflowJournalEntry['kind']>(\n callId: readonly [number, ...number[]],\n kind: K,\n fingerprint: string,\n ): Extract<WorkflowJournalEntry, { kind: K }> | undefined {\n const key = callId.join('.')\n const replay = this.journal.get(key)\n if (replay === undefined) return undefined\n if (replay.kind !== kind || replay.fingerprint !== fingerprint) {\n throw new WorkflowError(\n `workflow journal diverged at ${callId}: the replayed ${kind} request does not match the committed request`,\n 'JOURNAL_DIVERGENCE',\n )\n }\n this.replayedJournalCallIds.add(key)\n return replay as Extract<WorkflowJournalEntry, { kind: K }>\n }\n\n /** Detect a resumed path that skipped a previously committed host call. */\n private unreplayedJournalError(): WorkflowError | undefined {\n for (const callId of this.journal.keys()) {\n if (!this.replayedJournalCallIds.has(callId)) {\n return new WorkflowError(\n `workflow journal diverged: the resumed path did not replay committed call ${callId}`,\n 'JOURNAL_DIVERGENCE',\n )\n }\n }\n return undefined\n }\n\n /** Append one completed host call unless this is a non-persistent smoke check. */\n private commitJournal(entry: PendingJournalEntry): void {\n if (this.validateOnly) return\n this.nextJournalOrdinal += 1\n this.observer.journalCommit({ ...entry, ordinal: this.nextJournalOrdinal })\n }\n\n /** Atomically admit one direct-agent reservation for every new panel item. */\n private reservePanel(scopes: CallScope[]): void {\n const reservations = scopes.flatMap(scope => scope.reservation === undefined ? [] : [scope.reservation])\n if (this.started + reservations.length > this.limits.maxTotalAgents) {\n throw this.agentCapError(reservations.length)\n }\n this.started += reservations.length\n }\n\n /** Consume a panel reservation or admit one standalone/nested agent call. */\n private spendAgentBudget(): number {\n const reservation = this.callScopes.getStore()?.reservation\n if (reservation !== undefined && reservation.available) {\n reservation.available = false\n this.nextAgentSeq += 1\n return this.nextAgentSeq\n }\n if (this.started >= this.limits.maxTotalAgents) throw this.agentCapError(1)\n this.started += 1\n this.nextAgentSeq += 1\n return this.nextAgentSeq\n }\n\n /** Build the fatal error for a budget admission that would exceed the cap. */\n private agentCapError(requested: number): WorkflowError {\n return new WorkflowError(\n `this run cannot admit ${requested} agent${requested === 1 ? '' : 's'}: ${this.started} of ${this.limits.maxTotalAgents} logical-agent budget is already spent and the total agent cap (${this.limits.maxTotalAgents}) would be exceeded — raise the applicable maxTotalAgents limit if the scale is intentional`,\n 'AGENT_CAP',\n )\n }\n\n /** The `agent(prompt, opts)` hook. */\n private async agent(rawPrompt: unknown, rawOpts: unknown): Promise<unknown> {\n this.throwIfCancelled()\n if (typeof rawPrompt !== 'string' || rawPrompt.length === 0) {\n throw new WorkflowError('agent() requires a non-empty prompt string', 'INVALID_ARGUMENT')\n }\n const prepared = this.readAgentOptions(rawOpts)\n const opts = prepared.options\n const label = opts.label ?? defaultLabel(rawPrompt)\n const phase = opts.phase ?? this.currentScope().currentPhase\n const callId = this.claimCallId('agent')\n // Replay compares the effective observer/request vocabulary, not only the\n // explicit options. A changed current phase or derived label is therefore\n // a deterministic divergence rather than a silently misattributed result.\n const fingerprint = fingerprintHostCall('agent', {\n prompt: rawPrompt,\n options: { ...opts, label, ...phase === undefined ? {} : { phase } },\n })\n // Journal replay: a committed result from the original run returns without\n // spending budget or launching a child (schema-correction and journal\n // replays are free by contract).\n const replay = this.replayEntry(callId, 'agent', fingerprint)\n if (replay !== undefined) {\n return replay.result\n }\n const seq = this.spendAgentBudget()\n // Smoke-check mode: canned success instead of launching a child.\n if (this.validateOnly) {\n return opts.schema !== undefined ? cannedSchemaValue(opts.schema, this.limits.maxItemsPerCall) : ''\n }\n\n await this.acquireSlot()\n try {\n // Re-check after the acquire: the await yields at least one microtask\n // tick even when a slot is free, and a queued waiter resumes a tick\n // after its release — a cancel() landing in either window must not\n // reach the host (which would refuse anyway, but the refusal reads as\n // a start failure rather than the cancellation it is).\n this.throwIfCancelled()\n let run: ChildHandle\n try {\n run = await this.children.startAgent({\n prompt: rawPrompt,\n ...prepared.providerSchema !== undefined ? { schema: prepared.providerSchema } : {},\n ...opts.provider !== undefined ? { provider: opts.provider } : {},\n ...opts.model !== undefined ? { model: opts.model } : {},\n })\n } catch (error: unknown) {\n // The host refuses starts once the run is cancelled — a refusal that\n // races our own cancel state must read as the cancellation it is,\n // not as a broken contract.\n if (this.isCancelled()) throw this.cancelledError()\n throw new WorkflowError(`agent() could not start a child: ${renderThrown(error)}`, 'AGENT_START', { cause: error })\n }\n // The start round-trip yields to the event loop, so a cancel CAN land\n // between the host starting the child and this continuation running —\n // wind the fresh child down instead of leaving it live behind a dead\n // script.\n if (this.isCancelled()) {\n await run.dispose()\n throw this.cancelledError()\n }\n const info: WorkflowAgentInfo = { seq, label, ...phase !== undefined ? { phase } : {}, childId: SessionId(run.id) }\n this.observer.agentStart(info)\n try {\n let result\n try {\n result = await run.result\n } catch (error: unknown) {\n // A rejected child result is an INFRASTRUCTURE fault relayed by the\n // host — distinct from a child that failed and resolved. Pair the\n // lifecycle before propagating, and propagate FATAL: an ordinary\n // throw would dissolve to a per-item null inside the combinators,\n // and a broken provider must not read as a failed child.\n if (this.isCancelled()) {\n this.observer.agentEnd({ ...info, outcome: 'cancelled' })\n throw this.cancelledError()\n }\n this.observer.agentEnd({ ...info, outcome: 'failed' })\n throw new WorkflowError(`child agent run failed: ${renderThrown(error)}`, 'AGENT_RESULT', { cause: error })\n }\n if (this.isCancelled()) {\n this.observer.agentEnd({ ...info, outcome: 'cancelled' })\n throw this.cancelledError()\n }\n if (result.stopReason === 'completed') {\n if (opts.schema !== undefined) {\n // The provider honored outputSchema (capability-gated at start), so\n // a completed run without a structured value is a child failure.\n if (result.structured === undefined) {\n this.commitJournal({ kind: 'agent', seq, callId, fingerprint, result: null })\n this.observer.agentEnd({ ...info, outcome: 'failed' })\n return null\n }\n const structured = result.structured as JsonValue\n if (!schemaValueMatches(opts.schema, structured)) {\n this.commitJournal({ kind: 'agent', seq, callId, fingerprint, result: null })\n this.observer.agentEnd({ ...info, outcome: 'failed' })\n return null\n }\n this.commitJournal({ kind: 'agent', seq, callId, fingerprint, result: structured })\n this.observer.agentEnd({ ...info, outcome: 'completed' })\n return result.structured\n }\n const text = outputText(result.output)\n this.commitJournal({ kind: 'agent', seq, callId, fingerprint, result: text })\n this.observer.agentEnd({ ...info, outcome: 'completed' })\n return text\n }\n // A child that failed for its own reasons resolves null (scripts\n // filter null slots); cancellation was checked immediately above.\n this.commitJournal({ kind: 'agent', seq, callId, fingerprint, result: null })\n this.observer.agentEnd({ ...info, outcome: 'failed' })\n return null\n } finally {\n await run.dispose()\n }\n } finally {\n this.releaseSlot()\n }\n }\n\n /** Materialize + validate the `agent()` options bag from the realm. */\n private readAgentOptions(rawOpts: unknown): PreparedAgentOptions {\n if (rawOpts === undefined) return { options: {} }\n let opts: unknown\n try {\n opts = materializeFromRealm(rawOpts, 'agent() options')\n } catch (error: unknown) {\n /* v8 ignore next -- defensive rethrow arm: materializeFromRealm only throws MaterializeError */\n if (!(error instanceof MaterializeError)) throw error\n throw new WorkflowError(`agent() options must be plain JSON data — ${error.message}`, 'INVALID_ARGUMENT', { cause: error })\n }\n if (typeof opts !== 'object' || opts === null || Array.isArray(opts)) {\n throw new WorkflowError('agent() options must be an object', 'INVALID_ARGUMENT')\n }\n const record = opts as Record<string, unknown>\n for (const key of Object.keys(record)) {\n if (SUPPORTED_AGENT_OPTIONS.has(key)) continue\n if (DEFERRED_AGENT_OPTIONS.has(key)) {\n throw new WorkflowError(`agent() option \"${key}\" is deferred and not supported by this engine (supported: label, phase, schema, provider, model)`, 'UNSUPPORTED_OPTION')\n }\n throw new WorkflowError(`agent() option \"${key}\" is not recognized (supported: label, phase, schema, provider, model)`, 'UNSUPPORTED_OPTION')\n }\n for (const key of ['label', 'phase', 'provider', 'model'] as const) {\n if (record[key] !== undefined && typeof record[key] !== 'string') {\n throw new WorkflowError(`agent() option \"${key}\" must be a string`, 'INVALID_ARGUMENT')\n }\n }\n let schema: ObjectJsonSchema | undefined\n let providerSchema: ObjectJsonSchema | undefined\n if (record.schema !== undefined) {\n try {\n const prepared = prepareObjectSchema(record.schema)\n schema = prepared.authored\n providerSchema = prepared.provider\n } catch (error: unknown) {\n /* v8 ignore next -- defensive rethrow arm: assertObjectJsonSchema only throws JsonSchemaError */\n if (!(error instanceof JsonSchemaError)) throw error\n throw new WorkflowError(`agent() schema is outside the supported subset — ${error.message}`, 'UNSUPPORTED_SCHEMA', { cause: error })\n }\n }\n return {\n options: {\n ...record.label !== undefined ? { label: record.label as string } : {},\n ...record.phase !== undefined ? { phase: record.phase as string } : {},\n ...record.provider !== undefined ? { provider: record.provider as string } : {},\n ...record.model !== undefined ? { model: record.model as string } : {},\n ...schema !== undefined ? { schema } : {},\n },\n ...providerSchema !== undefined ? { providerSchema } : {},\n }\n }\n\n /**\n * The `parallel(items)` hook. Declarative job maps preflight and reserve as\n * one atomic panel; arbitrary thunks admit their unknowable agent calls at\n * execution time. Every item is a barrier slot; ordinary failures become\n * `null` and fatal workflow errors propagate.\n */\n private async parallel(rawItems: unknown): Promise<unknown[]> {\n this.throwIfCancelled()\n if (!Array.isArray(rawItems)) {\n throw new WorkflowError('parallel() requires an array of zero-argument functions or job maps', 'INVALID_ARGUMENT')\n }\n this.assertItemCap(rawItems.length, 'parallel()')\n const panelPath = this.claimCallId('parallel')\n const items = rawItems.map((item, index) => this.parallelItem(\n item,\n index,\n [...panelPath, index + 1, 1],\n ))\n if (items.some(item => item.kind === 'job') && items.some(item => item.kind === 'thunk')) {\n throw new WorkflowError(\n 'parallel() cannot mix function thunks and declarative job maps in one panel',\n 'INVALID_ARGUMENT',\n )\n }\n const inheritedPhase = this.currentScope().currentPhase\n const branches = items.map((item, index) => ({\n item,\n scope: {\n path: [...panelPath, index + 1],\n nextNode: 0,\n ...inheritedPhase === undefined ? {} : { currentPhase: inheritedPhase },\n // A declarative job map has exactly one direct agent call, so the whole\n // known panel can be admitted atomically. Arbitrary thunks may contain\n // zero, many, or nested panels and therefore admit their calls when run.\n ...item.reservesAgent\n ? { reservation: { available: true } }\n : {},\n } satisfies CallScope,\n }))\n this.reservePanel(branches.map(branch => branch.scope))\n return Promise.all(branches.map(({ item, scope }) => this.callScopes.run(scope, async () => {\n try {\n return await item.run()\n } catch (error: unknown) {\n // Hook failures are WorkflowErrors built OUTSIDE the script's realm;\n // fatality is recognized by `instanceof` against this realm's class —\n // a script-built object can never pass it, so fatality cannot be\n // forged (nor accidentally dissolved).\n if (isFatalWorkflowError(error)) throw error\n return null\n }\n })))\n }\n\n /** Accept one `parallel()` item as a zero-arg thunk or a Grok job map `{ prompt, ...opts }`. */\n private parallelItem(item: unknown, index: number, callId: readonly [number, ...number[]]): ParallelItem {\n if (typeof item === 'function') return { run: item as () => unknown, kind: 'thunk', reservesAgent: false }\n let job: unknown\n try {\n job = materializeFromRealm(item, `parallel() item ${index}`)\n } catch (error: unknown) {\n /* v8 ignore next -- defensive rethrow arm: materializeFromRealm only throws MaterializeError */\n if (!(error instanceof MaterializeError)) throw error\n throw new WorkflowError(`parallel() item ${index} must be a function or plain job map — ${error.message}`, 'INVALID_ARGUMENT', { cause: error })\n }\n if (typeof job !== 'object' || job === null || Array.isArray(job)) {\n throw new WorkflowError(`parallel() item ${index} is not a function or job map`, 'INVALID_ARGUMENT')\n }\n const record = job as Record<string, unknown>\n const prompt = record.prompt\n if (typeof prompt !== 'string' || prompt.length === 0) {\n throw new WorkflowError(`parallel() job ${index} requires a non-empty \"prompt\" string`, 'INVALID_ARGUMENT')\n }\n const rawOpts: Record<string, unknown> = {}\n for (const key of Object.keys(record)) {\n if (key === 'prompt') continue\n rawOpts[key] = record[key]\n }\n // Validate the entire declarative panel before any branch launches. Capture\n // its inherited phase now so concurrent thunk narration cannot change a\n // job map's effective request between preflight and execution.\n const opts = this.readAgentOptions(rawOpts).options\n const label = opts.label ?? defaultLabel(prompt)\n const phase = opts.phase ?? this.currentScope().currentPhase\n const effectiveOptions: AgentOptions = { ...opts, label, ...phase === undefined ? {} : { phase } }\n const replay = this.replayEntry(\n callId,\n 'agent',\n fingerprintHostCall('agent', { prompt, options: effectiveOptions }),\n )\n return {\n run: () => this.agent(prompt, effectiveOptions),\n kind: 'job',\n reservesAgent: replay === undefined,\n }\n }\n\n /** The `pipeline(items, ...stages)` hook: per-item stage chains, NO cross-stage barrier. */\n private async pipeline(rawItems: unknown, rawStages: unknown[]): Promise<unknown[]> {\n this.throwIfCancelled()\n if (!Array.isArray(rawItems)) {\n throw new WorkflowError('pipeline() requires an items array', 'INVALID_ARGUMENT')\n }\n this.assertItemCap(rawItems.length, 'pipeline()')\n if (rawStages.length === 0) {\n throw new WorkflowError('pipeline() requires at least one stage function', 'INVALID_ARGUMENT')\n }\n const stages = rawStages.map((stage, index) => {\n if (typeof stage !== 'function') {\n throw new WorkflowError(`pipeline() stage ${index} is not a function`, 'INVALID_ARGUMENT')\n }\n return stage as (previous: unknown, item: unknown, index: number) => unknown\n })\n const pipelinePath = this.claimCallId('pipeline')\n const inheritedPhase = this.currentScope().currentPhase\n return Promise.all(rawItems.map((item: unknown, index) => this.callScopes.run({\n path: [...pipelinePath, index + 1],\n nextNode: 0,\n ...inheritedPhase === undefined ? {} : { currentPhase: inheritedPhase },\n }, async () => {\n let value: unknown = item\n try {\n for (const stage of stages) {\n value = await stage(value, item, index)\n }\n return value\n } catch (error: unknown) {\n // An ordinary stage throw drops the ITEM to null and skips its\n // remaining stages; a fatal WorkflowError (see parallel()) kills the\n // whole script.\n if (isFatalWorkflowError(error)) throw error\n return null\n }\n })))\n }\n\n private assertItemCap(length: number, hook: string): void {\n if (length > this.limits.maxItemsPerCall) {\n throw new WorkflowError(\n `${hook} received ${length} items — over the per-call cap (${this.limits.maxItemsPerCall}); split the work or raise maxItemsPerCall in the engine config`,\n 'ITEM_CAP',\n )\n }\n }\n\n /** The `phase(title)` hook: sets the current label for subsequent `agent()` calls and notifies observers. */\n private phase(title: unknown): void {\n this.throwIfCancelled()\n if (typeof title !== 'string' || title.length === 0) {\n throw new WorkflowError('phase() requires a non-empty title string', 'INVALID_ARGUMENT')\n }\n const callId = this.claimCallId('phase')\n const fingerprint = fingerprintHostCall('phase', { title })\n const replay = this.replayEntry(callId, 'phase', fingerprint)\n this.currentScope().currentPhase = title\n if (replay !== undefined) return\n this.observer.phase(title)\n this.commitJournal({ kind: 'phase', callId, fingerprint, title })\n }\n\n /** The `log(message)` hook: narration to observers. */\n private log(message: unknown): void {\n this.throwIfCancelled()\n if (typeof message !== 'string') {\n throw new WorkflowError('log() requires a message string', 'INVALID_ARGUMENT')\n }\n const callId = this.claimCallId('log')\n const fingerprint = fingerprintHostCall('log', { message })\n if (this.replayEntry(callId, 'log', fingerprint) !== undefined) return\n this.observer.log(message)\n this.commitJournal({ kind: 'log', callId, fingerprint, message })\n }\n\n /** Resolve the deterministic call scope for a root hook or combinator branch. */\n private currentScope(): CallScope {\n return this.callScopes.getStore() as CallScope\n }\n\n /** The `complete(value)` hook: terminate the run successfully with a JSON value. */\n private complete(value: unknown): never {\n this.throwIfCancelled()\n try {\n this.completed = { value: value === undefined ? null : this.materializeResult(value) }\n } catch (error: unknown) {\n /* v8 ignore next -- materializeResult totalizes every failure as WorkflowError. */\n if (!(error instanceof WorkflowError)) {\n throw new Error('materializing a workflow result threw outside the documented error type', { cause: error })\n }\n this.completionError = error\n }\n // Resolve out of band before throwing: drive() races this terminal against\n // the script promise, so a caught sentinel cannot keep the run alive.\n this.completionGate.resolve()\n throw COMPLETE_SENTINEL\n }\n\n /** The `budget()` hook: this run's logical agent budget and its spend. */\n private budget(): { total: number; spent: number; reserved: 0; remaining: number } {\n this.throwIfCancelled()\n const total = this.limits.maxTotalAgents\n const spent = this.started\n return { total, spent, reserved: 0, remaining: Math.max(0, total - spent) }\n }\n\n /** The `pause()`/`await_user()` gate: park the run until a resume message releases it. */\n private async gate(rawKind: unknown, rawMessage: unknown, resumable: boolean): Promise<void> {\n this.throwIfCancelled()\n if (typeof rawKind !== 'string' || rawKind.length === 0) {\n throw new WorkflowError(`${resumable ? 'await_user' : 'pause'}() requires a non-empty kind string`, 'INVALID_ARGUMENT')\n }\n const kind = this.readGateKind(rawKind, resumable)\n const message = rawMessage === undefined ? '' : typeof rawMessage === 'string' ? rawMessage : undefined\n if (message === undefined) {\n throw new WorkflowError(`${resumable ? 'await_user' : 'pause'}() message must be a string`, 'INVALID_ARGUMENT')\n }\n if (this.validateOnly) {\n // Smoke-check mode: a gate is a successful terminal, not a hang. Claim\n // completion out of band so a script catch cannot execute past it.\n const diagnostic = `would ${resumable ? 'await_user' : 'pause'} (${kind}): ${message}`\n this.observer.log(diagnostic)\n this.complete(diagnostic)\n }\n const callId = resumable ? this.claimCallId('await-user') : undefined\n const fingerprint = resumable ? fingerprintHostCall('await-user', { kind, message }) : undefined\n if (callId !== undefined && fingerprint !== undefined\n && this.replayEntry(callId, 'await-user', fingerprint) !== undefined) return\n if (this.gateResume !== undefined) {\n throw new WorkflowError('workflow scripts may park on only one pause()/await_user() gate at a time', 'INVALID_ARGUMENT')\n }\n while (true) {\n this.throwIfCancelled()\n const gate: WorkflowGateInfo = { kind, message, resumable }\n this.observer.gate(gate)\n await new Promise<void>((resolve) => { this.gateResume = resolve })\n this.gateResume = undefined\n this.throwIfCancelled()\n // `pause` (non-resumable) re-fires the gate; `await_user` continues past it.\n if (resumable) {\n this.commitJournal(\n { kind: 'await-user', callId: callId as [number, ...number[]], fingerprint: fingerprint as string },\n )\n return\n }\n }\n }\n\n /** Normalize a gate kind with its `backoff`/`blocked` aliases. */\n private readGateKind(rawKind: string, resumable: boolean): WorkflowGateKind {\n switch (rawKind) {\n case 'user':\n case 'back_off':\n case 'backoff':\n case 'no_progress':\n case 'verification':\n case 'blocked':\n case 'infra':\n break\n default:\n throw new WorkflowError(`${resumable ? 'await_user' : 'pause'}() kind \"${rawKind}\" is not recognized (user, back_off, no_progress, verification, infra)`, 'INVALID_ARGUMENT')\n }\n const normalized = rawKind === 'backoff' ? 'back_off' : rawKind === 'blocked' ? 'verification' : rawKind\n return normalized\n }\n\n /** The `write_scratch_file(name, content)` hook: write one single-component scratch file. */\n private async writeScratch(rawName: unknown, rawContent: unknown): Promise<void> {\n this.throwIfCancelled()\n const name = this.readScratchName(rawName)\n if (typeof rawContent !== 'string') {\n throw new WorkflowError('write_scratch_file() content must be a string', 'INVALID_ARGUMENT')\n }\n const callId = this.claimCallId('scratch-write')\n const fingerprint = fingerprintHostCall('scratch-write', { name, content: rawContent })\n if (this.replayEntry(callId, 'scratch-write', fingerprint) !== undefined) return\n await this.children.writeScratch(name, rawContent)\n this.commitJournal({ kind: 'scratch-write', callId, fingerprint })\n }\n\n /** The `read_scratch_file(name)` hook: read one single-component scratch file. */\n private async readScratch(rawName: unknown): Promise<string | undefined> {\n this.throwIfCancelled()\n const name = this.readScratchName(rawName)\n const callId = this.claimCallId('scratch-read')\n const fingerprint = fingerprintHostCall('scratch-read', { name })\n const replay = this.replayEntry(callId, 'scratch-read', fingerprint)\n if (replay !== undefined) {\n return replay.content\n }\n const content = await this.children.readScratch(name)\n this.commitJournal({\n kind: 'scratch-read',\n callId,\n fingerprint,\n ...content === undefined ? {} : { content },\n })\n return content\n }\n\n /** Validate a single-component scratch file name (no separators or traversal). */\n private readScratchName(rawName: unknown): string {\n if (typeof rawName !== 'string' || !SCRATCH_NAME.test(rawName)) {\n throw new WorkflowError('scratch file name must be a single component (letters, digits, . _ -)', 'INVALID_ARGUMENT')\n }\n return rawName\n }\n}\n\n/** Index a journal while rejecting ambiguous replay identities. */\nfunction indexJournal(entries: readonly WorkflowJournalEntry[] | undefined): ReadonlyMap<string, WorkflowJournalEntry> {\n const byCallId = new Map<string, WorkflowJournalEntry>()\n const agentSequences = new Set<number>()\n let priorOrdinal = 0\n for (const entry of entries ?? []) {\n if (!Number.isSafeInteger(entry.ordinal) || entry.ordinal !== priorOrdinal + 1) {\n throw new WorkflowError('workflow journal entry ordinal must be the next positive safe integer', 'JOURNAL_DIVERGENCE')\n }\n priorOrdinal = entry.ordinal\n if (!Array.isArray(entry.callId) || entry.callId.length === 0\n || entry.callId.some(part => !Number.isSafeInteger(part) || part <= 0)\n || byCallId.has(entry.callId.join('.'))) {\n throw new WorkflowError(`workflow journal repeats or omits call identity ${JSON.stringify(entry.callId)}`, 'JOURNAL_DIVERGENCE')\n }\n if (entry.kind === 'agent' && (!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 (entry.kind === 'agent' && agentSequences.has(entry.seq)) {\n throw new WorkflowError(`workflow journal repeats agent sequence ${entry.seq}`, 'JOURNAL_DIVERGENCE')\n }\n if (!/^[a-f0-9]{64}$/u.test(entry.fingerprint)) {\n throw new WorkflowError('workflow journal fingerprint must be a lowercase SHA-256 digest', 'JOURNAL_DIVERGENCE')\n }\n byCallId.set(entry.callId.join('.'), entry)\n if (entry.kind === 'agent') agentSequences.add(entry.seq)\n }\n return byCallId\n}\n\n/** SHA-256 one canonical effective host request for journal replay validation. */\nfunction fingerprintHostCall(kind: WorkflowJournalEntry['kind'], request: unknown): string {\n return createHash('sha256').update(canonicalJson({ kind, request })).digest('hex')\n}\n\n/** Serialize JSON-like data with recursively sorted object keys. */\nfunction canonicalJson(value: unknown): string {\n if (value === null || typeof value !== 'object') return JSON.stringify(value)\n if (Array.isArray(value)) return `[${value.map(canonicalJson).join(',')}]`\n const entries = Object.entries(value as Record<string, unknown>)\n .filter(([, child]) => child !== undefined)\n // Object keys are unique, so equality is not a possible comparator input.\n .sort(([left], [right]) => left < right ? -1 : 1)\n return `{${entries.map(([key, child]) => `${JSON.stringify(key)}:${canonicalJson(child)}`).join(',')}}`\n}\n\n/** Single-component scratch file name grammar. */\nconst SCRATCH_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]*$/\n\n/** Sentinel thrown by `complete()`; drive() recognizes it to terminate successfully. */\nconst COMPLETE_SENTINEL = new Error('workflow completed')\n","/**\n * The worker-side half of the engine: {@link runWorkerSession} wires one MessagePort to one\n * {@link WorkflowExecution} — hook progress and child starts go out as messages, run control\n * and child lifecycle come back in — and posts the run's terminal result exactly once. Keeping it\n * separate from `worker.ts` lets unit tests drive the session over a MessageChannel, because main\n * process coverage cannot observe code inside a real Worker.\n *\n * The session announces ready and waits for `go`, so cancellation racing startup can prevent even\n * the script's synchronous prefix. A cancel in place of `go` releases the gate into a cancelled\n * drive without executing the body.\n * @module @deepseek-ai/dsh-workflow-worker-thread/session\n */\n\nimport type { MessagePort } from 'node:worker_threads'\nimport { WorkflowError } from '@deepseek-ai/dsh-workflow'\nimport { assertNever } from '@deepseek-ai/dsh-llm'\nimport { HostToWorkerType, WorkerToHostType } from './protocol.ts'\nimport type { HostToWorkerMessage, WorkerToHostPayloads } from './protocol.ts'\nimport { renderThrown } from './realm.ts'\nimport { WorkflowExecution } from './runtime.ts'\nimport type { ExecutionObserver } from './runtime.ts'\nimport type {\n ChildHandle,\n ChildPort,\n ChildResult,\n ChildStartRequest,\n WorkerInit,\n} from './types.ts'\n\n/** The book-keeping for one in-flight child RPC (keyed by callId). */\ninterface PendingChild {\n started: PromiseWithResolvers<string>\n settled: PromiseWithResolvers<ChildResult>\n disposed: PromiseWithResolvers<void>\n}\n\n/** The typed post half of the port: each tag pairs with ITS payload from the map (a mismatch is a compile error at the call site). */\ntype Post = <T extends WorkerToHostType>(type: T, payload: WorkerToHostPayloads[T]) => void\n\n/**\n * The worker-side handle for one started child agent ({@link ChildHandle}):\n * every member is an RPC to the host keyed by this call's `callId`, resolved\n * by the session's message handler through the bridge's pending entry.\n */\nclass RpcChildHandle implements ChildHandle {\n readonly result: Promise<ChildResult>\n\n constructor(\n private readonly post: Post,\n private readonly callId: number,\n private readonly entry: PendingChild,\n readonly id: string,\n ) {\n this.result = entry.settled.promise\n }\n\n dispose(): Promise<void> {\n this.post(WorkerToHostType.ChildDispose, { callId: this.callId })\n return this.entry.disposed.promise\n }\n}\n\n/**\n * The worker-side child-RPC bridge ({@link ChildPort}): allocates callIds,\n * posts the start/dispose RPCs, and owns the per-call pending\n * book-keeping the session's message handler settles via the `onChild*`\n * entry points.\n */\nclass ChildRpcBridge implements ChildPort {\n private nextCallId = 0\n private readonly pending = new Map<number, PendingChild>()\n private readonly pendingScratch = new Map<number, PromiseWithResolvers<{ content?: string }>>()\n\n constructor(private readonly post: Post) {}\n\n async startAgent(request: ChildStartRequest): Promise<ChildHandle> {\n this.nextCallId += 1\n const callId = this.nextCallId\n const entry: PendingChild = {\n started: Promise.withResolvers<string>(),\n settled: Promise.withResolvers<ChildResult>(),\n disposed: Promise.withResolvers<void>(),\n }\n // Containment: when asynchronous provider start fails (or\n // the run is torn down), the settled promise may never gain a consumer —\n // it must not surface as an unhandled rejection and kill the worker.\n entry.settled.promise.catch(() => { /* consumed: unconsumed child settlement after failed start */ })\n this.pending.set(callId, entry)\n this.post(WorkerToHostType.ChildStart, { callId, request })\n const childId = await entry.started.promise\n return new RpcChildHandle(this.post, callId, entry, childId)\n }\n\n async writeScratch(name: string, content: string): Promise<void> {\n const callId = this.claimCallId()\n const resolve = Promise.withResolvers<{ content?: string }>()\n this.pendingScratch.set(callId, resolve)\n this.post(WorkerToHostType.ScratchWrite, { callId, name, content })\n await resolve.promise\n }\n\n async readScratch(name: string): Promise<string | undefined> {\n const callId = this.claimCallId()\n const resolve = Promise.withResolvers<{ content?: string }>()\n this.pendingScratch.set(callId, resolve)\n this.post(WorkerToHostType.ScratchRead, { callId, name })\n const result = await resolve.promise\n return result.content\n }\n\n private claimCallId(): number {\n this.nextCallId += 1\n return this.nextCallId\n }\n\n /** The host established a published child; releases the `startAgent` await. */\n onChildStarted(callId: number, childId: string): void {\n this.pending.get(callId)?.started.resolve(childId)\n }\n\n /** Asynchronous provider start failed; reject and retire the pending RPC. */\n onChildStartError(callId: number, rendered: string): void {\n const entry = this.pending.get(callId)\n this.pending.delete(callId)\n entry?.started.reject(new Error(rendered))\n }\n\n /** The child's terminal result arrived. */\n onChildSettled(callId: number, result: ChildResult): void {\n this.pending.get(callId)?.settled.resolve(result)\n }\n\n /** The child's `result` rejected host-side (an infrastructure fault, relayed as fatal). */\n onChildFailed(callId: number, rendered: string): void {\n this.pending.get(callId)?.settled.reject(new Error(rendered))\n }\n\n /** The host acked the dispose; the call's book-keeping is complete. */\n onChildDisposed(callId: number): void {\n const entry = this.pending.get(callId)\n this.pending.delete(callId)\n entry?.disposed.resolve()\n }\n\n /** The host completed a scratch write. */\n onScratchWritten(callId: number): void {\n const entry = this.pendingScratch.get(callId)\n this.pendingScratch.delete(callId)\n entry?.resolve({})\n }\n\n /** The host completed a scratch read (content absent = file missing). */\n onScratchReadResult(callId: number, content?: string): void {\n const entry = this.pendingScratch.get(callId)\n this.pendingScratch.delete(callId)\n entry?.resolve({ ...content !== undefined ? { content } : {} })\n }\n}\n\n/**\n * Narrow the nullable `parentPort` the bootstrap reads from\n * `node:worker_threads`.\n * @param port - `parentPort` as imported (null on the main thread).\n * @returns the port, non-null.\n */\nexport function requireParentPort(port: MessagePort | null): MessagePort {\n if (port === null) throw new Error('the workflow worker entry must be loaded inside a worker thread (no parentPort)')\n return port\n}\n\n/**\n * Run one workflow script to settlement against `port`, posting the terminal result message\n * exactly once; resolves after that post (stray children may still be winding down through the\n * port — the host owns their teardown and ultimately terminates the thread). It never rejects:\n * constructor failure becomes an error result. Host pre-parse makes syntax failure here a likely\n * Node-version skew, but the session still reports it instead of dying silently.\n * @param port - the channel to the host (the real `parentPort`, or one side\n * of an in-process `MessageChannel` in tests).\n * @param init - the run payload the host provided as `workerData`.\n */\nexport async function runWorkerSession(port: MessagePort, init: WorkerInit): Promise<void> {\n const post: Post = (type, payload) => {\n port.postMessage({ type, ...payload })\n }\n const children = new ChildRpcBridge(post)\n\n const observer: ExecutionObserver = {\n phase: (title) => { post(WorkerToHostType.Phase, { title }) },\n log: (message) => { post(WorkerToHostType.Log, { message }) },\n agentStart: (info) => { post(WorkerToHostType.AgentStart, { info }) },\n agentEnd: (info) => { post(WorkerToHostType.AgentEnd, { info }) },\n gate: (gate) => { post(WorkerToHostType.Gate, { gate }) },\n journalCommit: (entry) => { post(WorkerToHostType.JournalCommit, { entry }) },\n }\n\n let execution: WorkflowExecution\n try {\n execution = new WorkflowExecution(\n init.meta,\n init.body,\n init.args,\n init.limits,\n observer,\n children,\n init.journal,\n init.validateOnly,\n init.initialAgentSpend,\n init.initialAgentSeq,\n )\n } catch (error: unknown) {\n // Constructor failure still follows the ordinary startup ordering so the\n // strict Host state machine has no special pre-ready terminal case.\n post(WorkerToHostType.Ready, {})\n post(WorkerToHostType.Result, {\n result: {\n value: null,\n stopReason: 'error',\n error: renderThrown(error),\n ...error instanceof WorkflowError ? { errorCode: error.code } : {},\n agentsStarted: Math.max(\n init.initialAgentSpend ?? 0,\n init.journal?.filter(entry => entry.kind === 'agent').length ?? 0,\n ),\n },\n })\n return\n }\n\n const gate = Promise.withResolvers<void>()\n port.on('message', (message: HostToWorkerMessage) => {\n switch (message.type) {\n case HostToWorkerType.Go:\n gate.resolve()\n break\n case HostToWorkerType.Cancel:\n execution.cancel(message.reason)\n // A cancel doubles as the gate release: drive() checks the cancelled\n // state before running the body, so the script never executes.\n gate.resolve()\n break\n case HostToWorkerType.Resume:\n execution.resume()\n break\n case HostToWorkerType.ChildStarted:\n children.onChildStarted(message.callId, message.childId)\n break\n case HostToWorkerType.ChildStartError:\n children.onChildStartError(message.callId, message.rendered)\n break\n case HostToWorkerType.ChildSettled:\n children.onChildSettled(message.callId, message.result)\n break\n case HostToWorkerType.ChildFailed:\n children.onChildFailed(message.callId, message.rendered)\n break\n case HostToWorkerType.ChildDisposed:\n children.onChildDisposed(message.callId)\n break\n case HostToWorkerType.ScratchWritten:\n children.onScratchWritten(message.callId)\n break\n case HostToWorkerType.ScratchReadResult:\n children.onScratchReadResult(message.callId, message.content)\n break\n /* v8 ignore next 2 -- closed engine-owned union; the arm only makes adding a message type a compile error */\n default:\n assertNever(message, 'host-to-worker message')\n }\n })\n\n post(WorkerToHostType.Ready, {})\n await gate.promise\n const result = await execution.drive()\n post(WorkerToHostType.Result, { result })\n}\n","/**\n * Single-statement worker entry that boots `runWorkerSession` on real `parentPort`. Logic remains in\n * the session module for in-process MessageChannel coverage; importing this entry on the main thread\n * exercises `requireParentPort`'s failure path.\n * @module @deepseek-ai/dsh-workflow-worker-thread/worker\n */\n\nimport { parentPort, workerData } from 'node:worker_threads'\nimport { requireParentPort, runWorkerSession } from './session.ts'\nimport type { WorkerInit } from './types.ts'\n\n// workerData is `any` at the node:worker_threads boundary; the engine is the\n// only spawner and always provides a WorkerInit.\nvoid runWorkerSession(requireParentPort(parentPort), workerData as WorkerInit)\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAWA,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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