@theokit/sdk 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (369) hide show
  1. package/CHANGELOG.md +1571 -0
  2. package/LICENSE +201 -0
  3. package/README.md +80 -0
  4. package/bin/theokit-migrate-config.mjs +269 -0
  5. package/bin/theokit-migrate-memory.mjs +116 -0
  6. package/dist/agent-builder.d.ts +52 -0
  7. package/dist/agent-factory.d.ts +39 -0
  8. package/dist/agent.d.ts +175 -0
  9. package/dist/batch.d.ts +11 -0
  10. package/dist/budget.d.ts +48 -0
  11. package/dist/cache.d.ts +74 -0
  12. package/dist/cron-1yxL3K2S.d.cts +221 -0
  13. package/dist/cron-BYVdYzob.d.ts +221 -0
  14. package/dist/cron.cjs +14655 -0
  15. package/dist/cron.cjs.map +1 -0
  16. package/dist/cron.d.cts +3 -0
  17. package/dist/cron.d.ts +71 -0
  18. package/dist/cron.js +14652 -0
  19. package/dist/cron.js.map +1 -0
  20. package/dist/define-tool.d.ts +35 -0
  21. package/dist/errors-CK8brCJ1.d.cts +448 -0
  22. package/dist/errors-CvAeEWgE.d.ts +448 -0
  23. package/dist/errors.cjs +255 -0
  24. package/dist/errors.cjs.map +1 -0
  25. package/dist/errors.d.cts +3 -0
  26. package/dist/errors.d.ts +356 -0
  27. package/dist/errors.js +238 -0
  28. package/dist/errors.js.map +1 -0
  29. package/dist/eval.cjs +14826 -0
  30. package/dist/eval.cjs.map +1 -0
  31. package/dist/eval.d.cts +35 -0
  32. package/dist/eval.d.ts +35 -0
  33. package/dist/eval.js +14821 -0
  34. package/dist/eval.js.map +1 -0
  35. package/dist/generate-object.d.ts +67 -0
  36. package/dist/handoff.d.ts +55 -0
  37. package/dist/index.cjs +17127 -0
  38. package/dist/index.cjs.map +1 -0
  39. package/dist/index.d.cts +1878 -0
  40. package/dist/index.d.ts +24 -0
  41. package/dist/index.js +17095 -0
  42. package/dist/index.js.map +1 -0
  43. package/dist/internal/agent-loop/loop-types.d.ts +29 -0
  44. package/dist/internal/agent-loop/loop.d.ts +2 -0
  45. package/dist/internal/agent-loop/message-builders.d.ts +6 -0
  46. package/dist/internal/agent-loop/tool-dispatch.d.ts +4 -0
  47. package/dist/internal/agent-loop/usage-and-cost.d.ts +25 -0
  48. package/dist/internal/budget/calendar-window.d.ts +19 -0
  49. package/dist/internal/budget/compute-cost.d.ts +28 -0
  50. package/dist/internal/budget/enforcement.d.ts +32 -0
  51. package/dist/internal/budget/ledger.d.ts +25 -0
  52. package/dist/internal/budget/normalize-usage.d.ts +27 -0
  53. package/dist/internal/budget/pricing-registry.d.ts +36 -0
  54. package/dist/internal/budget/registry.d.ts +16 -0
  55. package/dist/internal/budget/usage-accumulator.d.ts +31 -0
  56. package/dist/internal/cache/cosine.d.ts +14 -0
  57. package/dist/internal/cache/embed-helper.d.ts +15 -0
  58. package/dist/internal/cache/key.d.ts +15 -0
  59. package/dist/internal/cache/lookup.d.ts +28 -0
  60. package/dist/internal/cache/store-handler.d.ts +24 -0
  61. package/dist/internal/cache/store-json.d.ts +48 -0
  62. package/dist/internal/cache/store.d.ts +54 -0
  63. package/dist/internal/cache/telemetry.d.ts +20 -0
  64. package/dist/internal/cache/ttl.d.ts +11 -0
  65. package/dist/internal/catalog/fixtures.d.ts +16 -0
  66. package/dist/internal/catalog/local-models.d.ts +24 -0
  67. package/dist/internal/cron/run-job.d.ts +1 -0
  68. package/dist/internal/cron/scheduler.d.ts +1 -0
  69. package/dist/internal/cron/store.d.ts +1 -0
  70. package/dist/internal/cron/validate.d.ts +1 -0
  71. package/dist/internal/env.d.ts +1 -0
  72. package/dist/internal/errors/mappers/anthropic.d.ts +30 -0
  73. package/dist/internal/errors/mappers/bedrock.d.ts +16 -0
  74. package/dist/internal/errors/mappers/ollama.d.ts +41 -0
  75. package/dist/internal/errors/mappers/openai-compatible.d.ts +25 -0
  76. package/dist/internal/errors/mappers/shared.d.ts +10 -0
  77. package/dist/internal/errors/mappers/vertex.d.ts +15 -0
  78. package/dist/internal/eval/aggregate.d.ts +9 -0
  79. package/dist/internal/eval/dataset-iter.d.ts +9 -0
  80. package/dist/internal/eval/runner.d.ts +9 -0
  81. package/dist/internal/eval/single-flight.d.ts +16 -0
  82. package/dist/internal/eval/telemetry.d.ts +23 -0
  83. package/dist/internal/fixture-mode.d.ts +16 -0
  84. package/dist/internal/handoff/dispatcher.d.ts +29 -0
  85. package/dist/internal/handoff/registry.d.ts +23 -0
  86. package/dist/internal/handoff/telemetry.d.ts +18 -0
  87. package/dist/internal/handoff/tool-injector.d.ts +34 -0
  88. package/dist/internal/http.d.ts +1 -0
  89. package/dist/internal/ids.d.ts +1 -0
  90. package/dist/internal/judge/judge-call.d.ts +35 -0
  91. package/dist/internal/judge/parse-verdict.d.ts +11 -0
  92. package/dist/internal/judge/types.d.ts +17 -0
  93. package/dist/internal/llm/anthropic-shared.d.ts +89 -0
  94. package/dist/internal/llm/anthropic.d.ts +9 -0
  95. package/dist/internal/llm/bedrock-anthropic.d.ts +36 -0
  96. package/dist/internal/llm/bedrock-token-cache.d.ts +18 -0
  97. package/dist/internal/llm/credential-pool-context.d.ts +11 -0
  98. package/dist/internal/llm/credential-pool-types.d.ts +22 -0
  99. package/dist/internal/llm/credential-pool.d.ts +18 -0
  100. package/dist/internal/llm/fallback-client.d.ts +1 -0
  101. package/dist/internal/llm/fault-injection.d.ts +50 -0
  102. package/dist/internal/llm/finish.d.ts +1 -0
  103. package/dist/internal/llm/model-identifier.d.ts +24 -0
  104. package/dist/internal/llm/ollama-native.d.ts +27 -0
  105. package/dist/internal/llm/openai.d.ts +9 -0
  106. package/dist/internal/llm/pool-aware-client.d.ts +16 -0
  107. package/dist/internal/llm/router.d.ts +17 -0
  108. package/dist/internal/llm/sse.d.ts +9 -0
  109. package/dist/internal/llm/stream-relay.d.ts +17 -0
  110. package/dist/internal/llm/types.d.ts +70 -0
  111. package/dist/internal/llm/vertex-anthropic.d.ts +40 -0
  112. package/dist/internal/llm/vertex-auth.d.ts +30 -0
  113. package/dist/internal/llm/vertex-gemini.d.ts +28 -0
  114. package/dist/internal/llm/vertex-router.d.ts +21 -0
  115. package/dist/internal/mcp/client.d.ts +16 -0
  116. package/dist/internal/memory/active-memory-cache.d.ts +10 -0
  117. package/dist/internal/memory/active-memory.d.ts +45 -0
  118. package/dist/internal/memory/adapters/catalog.d.ts +1 -0
  119. package/dist/internal/memory/adapters/deepinfra-embedding.d.ts +2 -0
  120. package/dist/internal/memory/adapters/mistral-embedding.d.ts +2 -0
  121. package/dist/internal/memory/adapters/ollama-embedding.d.ts +34 -0
  122. package/dist/internal/memory/adapters/openai-compatible.d.ts +23 -0
  123. package/dist/internal/memory/adapters/openai-embedding.d.ts +2 -0
  124. package/dist/internal/memory/adapters/openrouter-embedding.d.ts +2 -0
  125. package/dist/internal/memory/adapters/voyage-embedding.d.ts +2 -0
  126. package/dist/internal/memory/atomic-write.d.ts +7 -0
  127. package/dist/internal/memory/chunk-markdown.d.ts +2 -0
  128. package/dist/internal/memory/circuit-breaker.d.ts +22 -0
  129. package/dist/internal/memory/cwd-mutex.d.ts +1 -0
  130. package/dist/internal/memory/dreaming/diary.d.ts +4 -0
  131. package/dist/internal/memory/dreaming/phases.d.ts +15 -0
  132. package/dist/internal/memory/dreaming/run.d.ts +10 -0
  133. package/dist/internal/memory/embedding-adapter.d.ts +42 -0
  134. package/dist/internal/memory/embedding-cache.d.ts +1 -0
  135. package/dist/internal/memory/index-db.d.ts +10 -0
  136. package/dist/internal/memory/index-manager-dispatch.d.ts +23 -0
  137. package/dist/internal/memory/index-manager.d.ts +68 -0
  138. package/dist/internal/memory/index-schema.d.ts +21 -0
  139. package/dist/internal/memory/lance-index.d.ts +32 -0
  140. package/dist/internal/memory/lance-memory-adapter.d.ts +43 -0
  141. package/dist/internal/memory/markdown-store.d.ts +16 -0
  142. package/dist/internal/memory/memory-index.d.ts +52 -0
  143. package/dist/internal/memory/migrate-sqlite-to-lance.d.ts +15 -0
  144. package/dist/internal/memory/migration.d.ts +9 -0
  145. package/dist/internal/memory/reader.d.ts +8 -0
  146. package/dist/internal/memory/session-loader.d.ts +1 -0
  147. package/dist/internal/memory/session-summary-writer.d.ts +2 -0
  148. package/dist/internal/memory/sqlite-vec-loader.d.ts +3 -0
  149. package/dist/internal/memory/tools.d.ts +14 -0
  150. package/dist/internal/memory/transcript-store.d.ts +1 -0
  151. package/dist/internal/memory/types.d.ts +17 -0
  152. package/dist/internal/memory/vec-index.d.ts +28 -0
  153. package/dist/internal/memory/wiki-loader.d.ts +2 -0
  154. package/dist/internal/observability/tracer-loader.d.ts +20 -0
  155. package/dist/internal/persistence/atomic-write.d.ts +1 -0
  156. package/dist/internal/persistence/conversation-storage-fs.d.ts +37 -0
  157. package/dist/internal/persistence/conversation-storage-memory.d.ts +24 -0
  158. package/dist/internal/persistence/cwd-mutex.d.ts +1 -0
  159. package/dist/internal/persistence/file-lock.d.ts +14 -0
  160. package/dist/internal/persistence/fts5-sanitize.d.ts +16 -0
  161. package/dist/internal/persistence/markdown-config-loader.d.ts +35 -0
  162. package/dist/internal/persistence/paths.d.ts +19 -0
  163. package/dist/internal/persistence/persistence-schema.d.ts +17 -0
  164. package/dist/internal/persistence/schema-version.d.ts +13 -0
  165. package/dist/internal/persistence/sqlite-wal.d.ts +10 -0
  166. package/dist/internal/personality/context.d.ts +17 -0
  167. package/dist/internal/personality/registry.d.ts +17 -0
  168. package/dist/internal/personality/store.d.ts +27 -0
  169. package/dist/internal/personality/switch.d.ts +36 -0
  170. package/dist/internal/personality/types.d.ts +18 -0
  171. package/dist/internal/plugins/context.d.ts +31 -0
  172. package/dist/internal/plugins/manager.d.ts +37 -0
  173. package/dist/internal/plugins/types.d.ts +102 -0
  174. package/dist/internal/providers/builtin/anthropic.d.ts +2 -0
  175. package/dist/internal/providers/builtin/bedrock.d.ts +25 -0
  176. package/dist/internal/providers/builtin/gemini.d.ts +10 -0
  177. package/dist/internal/providers/builtin/index.d.ts +19 -0
  178. package/dist/internal/providers/builtin/llamacpp.d.ts +1 -0
  179. package/dist/internal/providers/builtin/lmstudio.d.ts +1 -0
  180. package/dist/internal/providers/builtin/ollama.d.ts +17 -0
  181. package/dist/internal/providers/builtin/openai.d.ts +2 -0
  182. package/dist/internal/providers/builtin/openrouter.d.ts +2 -0
  183. package/dist/internal/providers/builtin/vertex.d.ts +27 -0
  184. package/dist/internal/providers/discovery.d.ts +14 -0
  185. package/dist/internal/providers/index.d.ts +8 -0
  186. package/dist/internal/providers/registry.d.ts +12 -0
  187. package/dist/internal/providers/types.d.ts +27 -0
  188. package/dist/internal/runtime/abort-utils.d.ts +21 -0
  189. package/dist/internal/runtime/agent-factory-registry.d.ts +16 -0
  190. package/dist/internal/runtime/agent-registry-store.d.ts +61 -0
  191. package/dist/internal/runtime/agent-registry.d.ts +34 -0
  192. package/dist/internal/runtime/agent-session-store.d.ts +3 -0
  193. package/dist/internal/runtime/agent-session.d.ts +2 -0
  194. package/dist/internal/runtime/async-local-storage.d.ts +20 -0
  195. package/dist/internal/runtime/async-semaphore.d.ts +24 -0
  196. package/dist/internal/runtime/budget.d.ts +36 -0
  197. package/dist/internal/runtime/cloud-agent.d.ts +1 -0
  198. package/dist/internal/runtime/cloud-config-serializer.d.ts +3 -0
  199. package/dist/internal/runtime/cloud-payload-types.d.ts +56 -0
  200. package/dist/internal/runtime/cloud-run.d.ts +1 -0
  201. package/dist/internal/runtime/cloud-tool-parity.d.ts +1 -0
  202. package/dist/internal/runtime/context-aggregator.d.ts +26 -0
  203. package/dist/internal/runtime/context-discovery-runner.d.ts +27 -0
  204. package/dist/internal/runtime/context-discovery.d.ts +21 -0
  205. package/dist/internal/runtime/context-frontmatter.d.ts +16 -0
  206. package/dist/internal/runtime/context-import-resolver.d.ts +24 -0
  207. package/dist/internal/runtime/context-loaders.d.ts +42 -0
  208. package/dist/internal/runtime/context-manager.d.ts +11 -0
  209. package/dist/internal/runtime/context-mdc-parser.d.ts +24 -0
  210. package/dist/internal/runtime/default-model.d.ts +1 -0
  211. package/dist/internal/runtime/fixture-events.d.ts +12 -0
  212. package/dist/internal/runtime/fixture-responder.d.ts +1 -0
  213. package/dist/internal/runtime/fixture-run-base.d.ts +45 -0
  214. package/dist/internal/runtime/fixture-scripts.d.ts +21 -0
  215. package/dist/internal/runtime/fixture-types.d.ts +1 -0
  216. package/dist/internal/runtime/fork-agent.d.ts +15 -0
  217. package/dist/internal/runtime/hooks-executor.d.ts +35 -0
  218. package/dist/internal/runtime/hooks-frontmatter.d.ts +26 -0
  219. package/dist/internal/runtime/hooks-source.d.ts +22 -0
  220. package/dist/internal/runtime/live-agent-registry.d.ts +87 -0
  221. package/dist/internal/runtime/local-agent-bootstrap.d.ts +37 -0
  222. package/dist/internal/runtime/local-agent-dispatch.d.ts +57 -0
  223. package/dist/internal/runtime/local-agent-invalidate.d.ts +8 -0
  224. package/dist/internal/runtime/local-agent-memory-direct.d.ts +12 -0
  225. package/dist/internal/runtime/local-agent-memory-hooks.d.ts +41 -0
  226. package/dist/internal/runtime/local-agent-memory.d.ts +1 -0
  227. package/dist/internal/runtime/local-agent-personality-extensions.d.ts +19 -0
  228. package/dist/internal/runtime/local-agent-plugins.d.ts +13 -0
  229. package/dist/internal/runtime/local-agent-runtime-extensions.d.ts +13 -0
  230. package/dist/internal/runtime/local-agent-task-wrap.d.ts +11 -0
  231. package/dist/internal/runtime/local-agent.d.ts +1 -0
  232. package/dist/internal/runtime/local-run.d.ts +1 -0
  233. package/dist/internal/runtime/memory-store.d.ts +4 -0
  234. package/dist/internal/runtime/plugin-frontmatter.d.ts +17 -0
  235. package/dist/internal/runtime/plugins-manager.d.ts +1 -0
  236. package/dist/internal/runtime/post-run-lifecycle.d.ts +1 -0
  237. package/dist/internal/runtime/providers-manager.d.ts +1 -0
  238. package/dist/internal/runtime/real-cloud-run.d.ts +2 -0
  239. package/dist/internal/runtime/real-local-run.d.ts +2 -0
  240. package/dist/internal/runtime/run-registry.d.ts +5 -0
  241. package/dist/internal/runtime/run-until.d.ts +22 -0
  242. package/dist/internal/runtime/shell-tool.d.ts +7 -0
  243. package/dist/internal/runtime/skill-frontmatter.d.ts +1 -0
  244. package/dist/internal/runtime/skills-manager.d.ts +1 -0
  245. package/dist/internal/runtime/spawn-collect.d.ts +8 -0
  246. package/dist/internal/runtime/subagents-loader.d.ts +1 -0
  247. package/dist/internal/runtime/system-prompt/escape.d.ts +1 -0
  248. package/dist/internal/runtime/system-prompt/local-assembly.d.ts +1 -0
  249. package/dist/internal/runtime/system-prompt/pipeline.d.ts +1 -0
  250. package/dist/internal/runtime/system-prompt/providers/active-memory-provider.d.ts +1 -0
  251. package/dist/internal/runtime/system-prompt/providers/base-provider.d.ts +1 -0
  252. package/dist/internal/runtime/system-prompt/providers/context-provider.d.ts +1 -0
  253. package/dist/internal/runtime/system-prompt/providers/memory-provider.d.ts +1 -0
  254. package/dist/internal/runtime/system-prompt/providers/skills-provider.d.ts +1 -0
  255. package/dist/internal/runtime/system-prompt/safe-call.d.ts +1 -0
  256. package/dist/internal/runtime/system-prompt/types.d.ts +5 -0
  257. package/dist/internal/runtime/system-prompt.d.ts +1 -0
  258. package/dist/internal/runtime/validate-agent-options.d.ts +1 -0
  259. package/dist/internal/runtime/workspace-dir.d.ts +9 -0
  260. package/dist/internal/runtime/yaml-frontmatter.d.ts +20 -0
  261. package/dist/internal/scorers/llm-judge.d.ts +24 -0
  262. package/dist/internal/security/index.d.ts +11 -0
  263. package/dist/internal/security/path-guard.d.ts +56 -0
  264. package/dist/internal/security/redact.d.ts +21 -0
  265. package/dist/internal/structured-output-helpers.d.ts +54 -0
  266. package/dist/internal/task/registry.d.ts +61 -0
  267. package/dist/internal/task/ring-buffer.d.ts +10 -0
  268. package/dist/internal/task/store.d.ts +59 -0
  269. package/dist/internal/task/subscribe.d.ts +15 -0
  270. package/dist/internal/task/telemetry.d.ts +27 -0
  271. package/dist/internal/telemetry/adapter-registry.d.ts +2 -0
  272. package/dist/internal/telemetry/adapters/langfuse.d.ts +2 -0
  273. package/dist/internal/telemetry/adapters/posthog.d.ts +2 -0
  274. package/dist/internal/telemetry/adapters/sentry.d.ts +2 -0
  275. package/dist/internal/telemetry/safe-require.d.ts +1 -0
  276. package/dist/internal/telemetry/tracer.d.ts +18 -0
  277. package/dist/internal/tool-dispatch/repair-middleware.d.ts +34 -0
  278. package/dist/internal/tool-dispatch/strip-think.d.ts +22 -0
  279. package/dist/internal/tool-registry/personality-filter.d.ts +37 -0
  280. package/dist/internal/workflow/ctx.d.ts +19 -0
  281. package/dist/internal/workflow/error-shape.d.ts +7 -0
  282. package/dist/internal/workflow/executor.d.ts +15 -0
  283. package/dist/internal/workflow/index.d.ts +12 -0
  284. package/dist/internal/workflow/retry-policy.d.ts +14 -0
  285. package/dist/internal/workflow/run-id.d.ts +9 -0
  286. package/dist/internal/workflow/single-flight.d.ts +18 -0
  287. package/dist/internal/workflow/snapshot-store.d.ts +23 -0
  288. package/dist/internal/workflow/step-agent.d.ts +12 -0
  289. package/dist/internal/workflow/step-branch.d.ts +10 -0
  290. package/dist/internal/workflow/step-dowhile.d.ts +8 -0
  291. package/dist/internal/workflow/step-fn.d.ts +10 -0
  292. package/dist/internal/workflow/step-foreach.d.ts +11 -0
  293. package/dist/internal/workflow/step-parallel.d.ts +17 -0
  294. package/dist/internal/workflow/step-sleep.d.ts +7 -0
  295. package/dist/internal/workflow/telemetry.d.ts +23 -0
  296. package/dist/internal/zod/to-json-schema.d.ts +21 -0
  297. package/dist/memory-adapter-helpers.d.ts +28 -0
  298. package/dist/memory.d.ts +123 -0
  299. package/dist/migrate.d.ts +33 -0
  300. package/dist/path-safety.cjs +126 -0
  301. package/dist/path-safety.cjs.map +1 -0
  302. package/dist/path-safety.d.cts +15 -0
  303. package/dist/path-safety.d.ts +15 -0
  304. package/dist/path-safety.js +120 -0
  305. package/dist/path-safety.js.map +1 -0
  306. package/dist/run-DkCD5DeO.d.cts +2181 -0
  307. package/dist/run-DkCD5DeO.d.ts +2181 -0
  308. package/dist/scorers.d.ts +75 -0
  309. package/dist/security.d.ts +67 -0
  310. package/dist/stream-object.d.ts +74 -0
  311. package/dist/task-store.cjs +237 -0
  312. package/dist/task-store.cjs.map +1 -0
  313. package/dist/task-store.d.cts +8 -0
  314. package/dist/task-store.d.ts +8 -0
  315. package/dist/task-store.js +233 -0
  316. package/dist/task-store.js.map +1 -0
  317. package/dist/task.d.ts +87 -0
  318. package/dist/theokit.d.ts +84 -0
  319. package/dist/tools/_path-scope.d.cts +8 -0
  320. package/dist/tools/_path-scope.d.ts +8 -0
  321. package/dist/tools/_subprocess.d.cts +28 -0
  322. package/dist/tools/_subprocess.d.ts +28 -0
  323. package/dist/tools/git-diff.d.cts +22 -0
  324. package/dist/tools/git-diff.d.ts +22 -0
  325. package/dist/tools/index.d.cts +29 -0
  326. package/dist/tools/index.d.ts +29 -0
  327. package/dist/tools/list-dir.d.cts +26 -0
  328. package/dist/tools/list-dir.d.ts +26 -0
  329. package/dist/tools/read-file.d.cts +31 -0
  330. package/dist/tools/read-file.d.ts +31 -0
  331. package/dist/tools/run-vitest.d.cts +46 -0
  332. package/dist/tools/run-vitest.d.ts +46 -0
  333. package/dist/tools/search-text.d.cts +32 -0
  334. package/dist/tools/search-text.d.ts +32 -0
  335. package/dist/tools.cjs +690 -0
  336. package/dist/tools.cjs.map +1 -0
  337. package/dist/tools.js +683 -0
  338. package/dist/tools.js.map +1 -0
  339. package/dist/trajectory-helpers.d.ts +31 -0
  340. package/dist/types/agent.d.ts +771 -0
  341. package/dist/types/batch.d.ts +112 -0
  342. package/dist/types/budget.d.ts +88 -0
  343. package/dist/types/cache.d.ts +76 -0
  344. package/dist/types/context.d.ts +93 -0
  345. package/dist/types/conversation-storage.d.ts +76 -0
  346. package/dist/types/conversation.d.ts +90 -0
  347. package/dist/types/cron.d.ts +150 -0
  348. package/dist/types/eval.d.ts +132 -0
  349. package/dist/types/goal-events.d.ts +95 -0
  350. package/dist/types/handoff.d.ts +135 -0
  351. package/dist/types/index.d.ts +20 -0
  352. package/dist/types/mcp.d.ts +64 -0
  353. package/dist/types/memory-adapter.d.ts +175 -0
  354. package/dist/types/messages.d.ts +154 -0
  355. package/dist/types/providers.d.ts +102 -0
  356. package/dist/types/run.d.ts +215 -0
  357. package/dist/types/task.d.ts +131 -0
  358. package/dist/types/theokit.d.ts +61 -0
  359. package/dist/types/trajectory.d.ts +49 -0
  360. package/dist/types/updates.d.ts +148 -0
  361. package/dist/types/usage.d.ts +61 -0
  362. package/dist/types/workflow.d.ts +217 -0
  363. package/dist/workflow.cjs +2405 -0
  364. package/dist/workflow.cjs.map +1 -0
  365. package/dist/workflow.d.cts +97 -0
  366. package/dist/workflow.d.ts +97 -0
  367. package/dist/workflow.js +2398 -0
  368. package/dist/workflow.js.map +1 -0
  369. package/package.json +183 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/errors.ts","../src/types/workflow.ts","../src/internal/persistence/atomic-write.ts","../src/internal/workflow/snapshot-store.ts","../src/internal/workflow/ctx.ts","../src/internal/workflow/error-shape.ts","../src/internal/workflow/run-id.ts","../src/internal/workflow/single-flight.ts","../src/internal/workflow/retry-policy.ts","../src/internal/workflow/step-agent.ts","../src/internal/security/redact.ts","../src/internal/workflow/step-branch.ts","../src/internal/workflow/step-dowhile.ts","../src/internal/workflow/step-fn.ts","../src/internal/runtime/async-semaphore.ts","../src/internal/workflow/step-foreach.ts","../src/internal/workflow/step-parallel.ts","../src/internal/workflow/step-sleep.ts","../src/internal/observability/tracer-loader.ts","../src/internal/workflow/telemetry.ts","../src/internal/workflow/executor.ts","../src/types/task.ts","../src/internal/task/ring-buffer.ts","../src/internal/task/store.ts","../src/internal/task/subscribe.ts","../src/internal/task/telemetry.ts","../src/internal/task/registry.ts","../src/internal/persistence/persistence-schema.ts","../src/internal/security/path-guard.ts","../src/workflow.ts"],"names":["dirname","mkdir","fn","resolve","outputs","settled","state","join","readFile","unlink","subscribe","TRACER_NAME","init_telemetry","z","executeWorkflow","resumeWorkflow"],"mappings":";;;;;;;;;;;;;;;;;;;AAAA,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AAI,MAAA;AAAA,EAC9D;AACA,EAAA,IAAI,CAAA,CAAE,IAAA,KAAS,SAAA,IAAa,CAAA,CAAE,IAAA,KAAS,SAAA,EAAW,OAAO,CAAC,CAAC,CAAA,CAAE,IAAI,CAAC,CAAA;AAClE,EAAA,OAAO,EAAC;AACV;AAEA,SAAS,mBAAA,CAAoB,OAA4B,IAAA,EAAyB;AAChF,EAAA,KAAA,MAAW,KAAK,KAAA,EAAO;AACrB,IAAA,IAAI,IAAA,CAAK,IAAI,CAAA,CAAE,EAAE,GAAG,MAAM,IAAI,4BAAA,CAA6B,CAAA,CAAE,EAAE,CAAA;AAC/D,IAAA,IAAA,CAAK,GAAA,CAAI,EAAE,EAAE,CAAA;AACb,IAAA,KAAA,MAAW,MAAA,IAAU,aAAA,CAAc,CAAC,CAAA,EAAG;AACrC,MAAA,mBAAA,CAAoB,QAAQ,IAAI,CAAA;AAAA,IAClC;AAAA,EACF;AACF","file":"workflow.js","sourcesContent":["import type { RunOperation } from \"./types/run.js\";\n\n/**\n * Finite, machine-readable error codes for provider-originated errors\n * (ADR D66). Consumers can `switch (err.metadata?.code)` exhaustively\n * — adding a new variant is an explicit decision + test coverage.\n *\n * @public\n */\nexport type ErrorCode =\n | \"rate_limit\"\n | \"auth_failed\"\n | \"invalid_request\"\n | \"timeout\"\n | \"server_error\"\n | \"context_too_long\"\n | \"content_filtered\"\n | \"model_unavailable\"\n | \"network\"\n | \"unknown\";\n\n/**\n * Codes used by {@link AgentRunError} (Production-Readiness #3, ADR D311).\n *\n * Superset of {@link ErrorCode} extended with codes that do NOT originate\n * from a provider HTTP response:\n *\n * - `quota_exceeded` — billing limit hit (provider 402 or signalled error)\n * - `tool_runtime_error` — custom tool handler threw inside dispatch\n * - `aborted` — caller's `AbortSignal` fired (Phase 4)\n * - `invalid_model` — model id rejected by provider (400 \"model not found\")\n * - `safety_blocked` — provider safety filter blocked req or resp\n * - `provider_unreachable` — DNS/TCP/timeout/5xx at transport boundary\n *\n * The `& {}` tail keeps the literal-union ergonomics (autocomplete) while\n * accepting any string for forward compatibility with constructor calls\n * that pass arbitrary code values (legacy callers).\n *\n * @public\n */\nexport type AgentRunErrorCode =\n | ErrorCode\n | \"quota_exceeded\"\n | \"tool_runtime_error\"\n | \"aborted\"\n | \"invalid_model\"\n | \"safety_blocked\"\n | \"provider_unreachable\"\n | (string & {});\n\n/**\n * Structured context for errors that originated from a provider HTTP\n * call (ADR D65). Lets callers retry with the right backoff (`retryAfter`),\n * surface actionable diagnostics (`provider`, `endpoint`), and inspect the\n * raw response body when needed (`raw`, capped at ~2KB by the mapper).\n *\n * @public\n */\nexport interface ErrorMetadata {\n /** Provider canonical name (e.g., `\"anthropic\"`, `\"openai\"`, `\"openrouter\"`, `\"gemini\"`). */\n provider: string;\n /** HTTP endpoint that failed (e.g., `\"/v1/messages\"`, `\"/v1/chat/completions\"`). */\n endpoint: string;\n /** Machine-readable error code (finite enum). */\n code: ErrorCode;\n /** HTTP status code if applicable. */\n statusCode?: number;\n /** Seconds to wait before retry, per provider's `retry-after` header (numeric form only). */\n retryAfter?: number;\n /** Raw response body for debugging (truncated to ~2KB by the mapper). */\n raw?: unknown;\n}\n\n/**\n * Base class for all errors thrown by `@theokit/sdk`.\n *\n * Use `isRetryable` to drive retry/backoff logic. `code` and `protoErrorCode`\n * are populated for server-originated errors when available. `metadata`\n * (ADR D65) carries structured `{ provider, endpoint, code, ... }` when\n * the error originated from a provider HTTP call.\n *\n * @public\n */\nexport class TheokitAgentError extends Error {\n override readonly name: string = \"TheokitAgentError\";\n readonly isRetryable: boolean;\n readonly code?: string;\n readonly protoErrorCode?: string;\n readonly metadata?: ErrorMetadata;\n\n constructor(\n message: string,\n options: {\n isRetryable?: boolean;\n code?: string;\n protoErrorCode?: string;\n cause?: unknown;\n metadata?: ErrorMetadata;\n } = {},\n ) {\n super(message, options.cause !== undefined ? { cause: options.cause } : undefined);\n this.isRetryable = options.isRetryable ?? false;\n if (options.code !== undefined) this.code = options.code;\n if (options.protoErrorCode !== undefined) this.protoErrorCode = options.protoErrorCode;\n if (options.metadata !== undefined) this.metadata = options.metadata;\n }\n}\n\n/**\n * Invalid API key, not logged in, insufficient permissions.\n *\n * @public\n */\nexport class AuthenticationError extends TheokitAgentError {\n override readonly name: string = \"AuthenticationError\";\n\n constructor(\n message: string,\n options: { code?: string; cause?: unknown; metadata?: ErrorMetadata } = {},\n ) {\n super(message, { ...options, isRetryable: false });\n }\n}\n\n/**\n * Too many requests or usage limits exceeded.\n *\n * @public\n */\nexport class RateLimitError extends TheokitAgentError {\n override readonly name: string = \"RateLimitError\";\n\n constructor(\n message: string,\n options: { code?: string; cause?: unknown; metadata?: ErrorMetadata } = {},\n ) {\n super(message, { ...options, isRetryable: true });\n }\n}\n\n/**\n * Invalid model, bad request parameters, malformed options.\n *\n * @public\n */\nexport class ConfigurationError extends TheokitAgentError {\n override readonly name: string = \"ConfigurationError\";\n\n constructor(\n message: string,\n options: { code?: string; cause?: unknown; metadata?: ErrorMetadata } = {},\n ) {\n super(message, { ...options, isRetryable: false });\n }\n}\n\n/**\n * Thrown when creating a cloud agent for a repo whose SCM provider is not\n * connected. Use `helpUrl` to point the user at the right reconnect flow.\n *\n * @public\n */\nexport class IntegrationNotConnectedError extends ConfigurationError {\n override readonly name: string = \"IntegrationNotConnectedError\";\n readonly provider: string;\n readonly helpUrl: string;\n\n constructor(\n message: string,\n options: {\n provider: string;\n helpUrl: string;\n code?: string;\n cause?: unknown;\n metadata?: ErrorMetadata;\n },\n ) {\n super(message, options);\n this.provider = options.provider;\n this.helpUrl = options.helpUrl;\n }\n}\n\n/**\n * Service unavailable, timeout, transport-level failure.\n *\n * @public\n */\nexport class NetworkError extends TheokitAgentError {\n override readonly name: string = \"NetworkError\";\n\n constructor(\n message: string,\n options: { code?: string; cause?: unknown; metadata?: ErrorMetadata } = {},\n ) {\n super(message, { ...options, isRetryable: true });\n }\n}\n\n/**\n * Catch-all for unclassified server or runtime errors.\n *\n * @public\n */\nexport class UnknownAgentError extends TheokitAgentError {\n override readonly name: string = \"UnknownAgentError\";\n\n constructor(\n message: string,\n options: { code?: string; cause?: unknown; metadata?: ErrorMetadata } = {},\n ) {\n super(message, { ...options, isRetryable: false });\n }\n}\n\n/**\n * Thrown by `Agent.prompt` (and helpers that go through `run.wait()`) when\n * the option `{ throwOnError: true }` is set and the run terminates with\n * `status: 'error'`. Carries the structured `RunResult.error` fields so\n * callers can `catch` once and branch on `code` / `provider` instead of\n * unwrapping the run.\n *\n * Extends {@link TheokitAgentError} per ADR D65 — no new hierarchy.\n *\n * @example\n * try {\n * await Agent.prompt(msg, { apiKey, model, throwOnError: true });\n * } catch (err) {\n * if (err instanceof AgentRunError && err.code === 'auth_failed') {\n * // bad key\n * }\n * }\n *\n * @public\n */\nexport class AgentRunError extends TheokitAgentError {\n override readonly name: string = \"AgentRunError\";\n readonly provider?: string;\n readonly raw?: string;\n /** Provider's request id (`x-request-id` / `request-id` header). Useful for support tickets. */\n readonly requestId?: string;\n /** SDK conversation id this error was raised inside. */\n readonly conversationId?: string;\n\n constructor(\n message: string,\n options: {\n code: AgentRunErrorCode;\n provider?: string;\n raw?: string;\n requestId?: string;\n conversationId?: string;\n retriable?: boolean;\n cause?: unknown;\n metadata?: ErrorMetadata;\n },\n ) {\n super(message, {\n code: options.code,\n cause: options.cause,\n metadata: options.metadata,\n // D311: most AgentRunErrors are not retriable (auth, validation, abort).\n // Provider mappers (D314) override per-status — explicit `retriable` wins\n // over the implicit default when supplied.\n isRetryable: options.retriable ?? defaultRetriableForCode(options.code),\n });\n if (options.provider !== undefined) this.provider = options.provider;\n if (options.raw !== undefined) this.raw = options.raw;\n if (options.requestId !== undefined) this.requestId = options.requestId;\n if (options.conversationId !== undefined) this.conversationId = options.conversationId;\n }\n\n /**\n * Production-Readiness #3 (ADR D311): alias for `isRetryable` exposed as\n * `retriable` to match the handoff contract. Future v2 will deprecate\n * `isRetryable` in favor of this.\n */\n get retriable(): boolean {\n return this.isRetryable;\n }\n\n /**\n * D312: provider's `Retry-After` header in **milliseconds**. Mappers store\n * the header value (seconds) in `metadata.retryAfter`; this getter\n * multiplies by 1000 so the result composes with `Date.now()`/`setTimeout`.\n *\n * Returns `undefined` when no hint was provided. `0` is a legitimate value\n * — use `=== undefined` check rather than truthy check.\n */\n get retryAfterMs(): number | undefined {\n if (this.metadata?.retryAfter === undefined) return undefined;\n return this.metadata.retryAfter * 1000;\n }\n\n /**\n * D313: alias for `metadata.raw`. Provider response body for debugging.\n * Available but NEVER serialized into `.message` (anti-leak invariant).\n */\n get providerError(): unknown {\n return this.metadata?.raw;\n }\n}\n\n/**\n * D311 helper: choose a sensible default `isRetryable` value when the\n * caller did not supply `retriable` explicitly. Conservative defaults —\n * provider mappers override per-status when they know better.\n *\n * @internal\n */\nfunction defaultRetriableForCode(code: AgentRunErrorCode): boolean {\n switch (code) {\n case \"rate_limit\":\n case \"timeout\":\n case \"server_error\":\n case \"network\":\n case \"provider_unreachable\":\n return true;\n default:\n return false;\n }\n}\n\n/**\n * Thrown when a {@link Run} or agent operation is not available on the current\n * runtime. Check first with `run.supports(operation)`.\n *\n * Extends {@link TheokitAgentError} (so error-catching code that branches on\n * `instanceof TheokitAgentError` continues to work) but is never retryable —\n * an unsupported operation will not become supported on retry.\n *\n * @public\n */\nexport class UnsupportedRunOperationError extends TheokitAgentError {\n override readonly name: string = \"UnsupportedRunOperationError\";\n readonly operation: RunOperation;\n\n constructor(\n message: string,\n operation: RunOperation,\n options: { code?: string; cause?: unknown } = {},\n ) {\n super(message, {\n ...options,\n isRetryable: false,\n code: options.code ?? \"unsupported_run_operation\",\n });\n this.operation = operation;\n }\n}\n\n/**\n * Thrown when every credential in a per-provider pool is in cooldown\n * and no healthy key is available (ADR D133). The caller's\n * {@link import(\"./internal/llm/fallback-client.js\").FallbackLlmClient}\n * catches this and tries the next provider in the fallback chain.\n *\n * `metadata.nextRetryAt` (epoch ms) tells callers when the soonest\n * pool entry resumes — useful for manual retry scheduling.\n *\n * @public\n */\nexport class CredentialPoolExhaustedError extends TheokitAgentError {\n override readonly name: string = \"CredentialPoolExhaustedError\";\n readonly provider: string;\n readonly nextRetryAt: number | undefined;\n\n constructor(\n message: string,\n options: {\n provider: string;\n nextRetryAt?: number;\n code?: string;\n cause?: unknown;\n metadata?: ErrorMetadata;\n },\n ) {\n super(message, {\n ...options,\n isRetryable: true,\n code: options.code ?? \"credential_pool_exhausted\",\n });\n this.provider = options.provider;\n this.nextRetryAt = options.nextRetryAt;\n }\n}\n\n/**\n * Finite error codes specific to memory adapter operations (ADR D141).\n *\n * @public\n */\nexport type MemoryAdapterErrorCode =\n | \"auth_failed\"\n | \"rate_limited\"\n | \"not_found\"\n | \"network\"\n | \"invalid_input\"\n | \"unknown\";\n\n/**\n * Error raised by `@theokit-memory-*` adapters. Carries `adapterId`\n * so callers can branch on which provider failed (ADR D141).\n *\n * @public\n */\nexport class MemoryAdapterError extends TheokitAgentError {\n override readonly name: string = \"MemoryAdapterError\";\n readonly adapterId: string;\n\n constructor(\n message: string,\n options: {\n adapterId: string;\n code: MemoryAdapterErrorCode;\n cause?: unknown;\n metadata?: ErrorMetadata;\n },\n ) {\n super(message, {\n isRetryable: options.code === \"rate_limited\" || options.code === \"network\",\n code: options.code,\n ...(options.cause !== undefined ? { cause: options.cause } : {}),\n ...(options.metadata !== undefined ? { metadata: options.metadata } : {}),\n });\n this.adapterId = options.adapterId;\n }\n}\n\n/**\n * Thrown when a user-supplied task ID violates the grammar\n * `^[a-z0-9][a-z0-9_-]*$` (D368) OR starts with a reserved adapter\n * prefix (`wf-` / `b-` / `cron-`, EC-5).\n *\n * @public\n */\nexport class InvalidTaskIdError extends TheokitAgentError {\n override readonly name: string = \"InvalidTaskIdError\";\n readonly taskId: string;\n\n constructor(message: string, taskId: string, options: { cause?: unknown } = {}) {\n super(message, {\n ...options,\n isRetryable: false,\n code: \"invalid_task_id\",\n });\n this.taskId = taskId;\n }\n}\n\n/**\n * Thrown when `Task.subscribe(id)` is called for a task that has been\n * evicted, never submitted, or evicted after retention (D373).\n *\n * @public\n */\nexport class TaskNotFoundError extends TheokitAgentError {\n override readonly name: string = \"TaskNotFoundError\";\n readonly taskId: string;\n\n constructor(taskId: string, options: { cause?: unknown } = {}) {\n super(`Task not found: ${taskId}`, {\n ...options,\n isRetryable: false,\n code: \"task_not_found\",\n });\n this.taskId = taskId;\n }\n}\n\n/**\n * Thrown when `CloudAgent` is asked to wrap a task (D370). Cloud\n * task observability is deferred until Theo PaaS GA.\n *\n * @public\n */\nexport class UnsupportedTaskOperationError extends TheokitAgentError {\n override readonly name: string = \"UnsupportedTaskOperationError\";\n readonly operation: string;\n\n constructor(operation: string, options: { cause?: unknown } = {}) {\n super(\n `Task operation \"${operation}\" is not supported on CloudAgent (pre-release; see ADR D370)`,\n {\n ...options,\n isRetryable: false,\n code: \"task_op_unsupported\",\n },\n );\n this.operation = operation;\n }\n}\n\n/**\n * Thrown by `Budget` enforcement (ADR D386) when a `mode: \"block\"`\n * budget would be exceeded by the upcoming LLM call. Caller pega\n * tipado para retry-after-window-reset or surface to the user.\n *\n * @public\n */\nexport class BudgetExceededError extends TheokitAgentError {\n override readonly name: string = \"BudgetExceededError\";\n readonly budgetName: string;\n readonly window: import(\"./types/budget.js\").BudgetWindow;\n readonly spentUsd: number;\n readonly limitUsd: number;\n readonly mode: import(\"./types/budget.js\").BudgetMode;\n\n constructor(args: {\n budgetName: string;\n window: import(\"./types/budget.js\").BudgetWindow;\n spentUsd: number;\n limitUsd: number;\n mode: import(\"./types/budget.js\").BudgetMode;\n cause?: unknown;\n }) {\n super(\n `Budget \"${args.budgetName}\" exceeded for window ${args.window}: spent $${args.spentUsd.toFixed(4)} > limit $${args.limitUsd.toFixed(4)}`,\n {\n ...(args.cause !== undefined ? { cause: args.cause } : {}),\n isRetryable: false,\n code: \"budget_exceeded\",\n },\n );\n this.budgetName = args.budgetName;\n this.window = args.window;\n this.spentUsd = args.spentUsd;\n this.limitUsd = args.limitUsd;\n this.mode = args.mode;\n }\n}\n\n/**\n * Thrown when `CloudAgent.send({ budget })` is invoked (D388). Cloud\n * budget surface waits for Theo PaaS GA.\n *\n * @public\n */\nexport class UnsupportedBudgetOperationError extends TheokitAgentError {\n override readonly name: string = \"UnsupportedBudgetOperationError\";\n readonly operation: string;\n\n constructor(operation: string, options: { cause?: unknown } = {}) {\n super(\n `Budget operation \"${operation}\" is not supported on CloudAgent (pre-release; see ADR D388)`,\n {\n ...options,\n isRetryable: false,\n code: \"budget_op_unsupported\",\n },\n );\n this.operation = operation;\n }\n}\n","/**\n * Public type contract for `Workflow.create / .run / .resume` (Adoption\n * Roadmap #5; ADRs D230-D248).\n *\n * Step types form a discriminated union by `kind`. Helper factory functions\n * (`fn()`, `agentStep()`) live in `workflow.ts` and hide the discriminator\n * from end users.\n *\n * @public\n */\n\nimport type { ZodType } from \"zod\";\n\nimport type { SDKAgent } from \"./agent.js\";\n\n/* ─── Step discriminated union (D232) ─── */\n\nexport type Step =\n | FnStep\n | AgentStep\n | ParallelStep\n | BranchStep\n | ForeachStep\n | DowhileStep\n | SleepStep\n | SuspendStep;\n\n/** A pure function step. */\nexport interface FnStep {\n readonly kind: \"fn\";\n readonly id: string;\n readonly fn: (input: unknown, ctx: StepContext) => Promise<unknown> | unknown;\n readonly inputSchema?: ZodType;\n readonly outputSchema?: ZodType;\n readonly retry?: RetryPolicy;\n /** D238 — slot reserved; runtime throws if engine not yet implemented. */\n readonly compensate?: (input: unknown, output: unknown, error: Error) => Promise<void> | void;\n}\n\n/** An agent.send-driven step. */\nexport interface AgentStep {\n readonly kind: \"agent\";\n readonly id: string;\n readonly agent: SDKAgent;\n readonly promptTemplate: string | ((input: unknown) => string);\n readonly retry?: RetryPolicy;\n}\n\n/** N concurrent branches, each its own mini-step-list. */\nexport interface ParallelStep {\n readonly kind: \"parallel\";\n readonly id: string;\n readonly branches: ReadonlyArray<ReadonlyArray<Step>>;\n readonly concurrency?: number;\n readonly errorPolicy?: \"fail-fast\" | \"collect\";\n}\n\n/** First-match-wins predicates + optional fallback. */\nexport interface BranchStep {\n readonly kind: \"branch\";\n readonly id: string;\n readonly predicates: ReadonlyArray<\n readonly [(input: unknown) => boolean | Promise<boolean>, ReadonlyArray<Step>]\n >;\n readonly fallback?: ReadonlyArray<Step>;\n}\n\n/** Map a step over an upstream array output. */\nexport interface ForeachStep {\n readonly kind: \"foreach\";\n readonly id: string;\n /** ID of an upstream top-level step whose output is iterable. */\n readonly iterableFrom: string;\n readonly step: Step;\n readonly concurrency?: number;\n}\n\n/** Loop a step until condFn returns false. */\nexport interface DowhileStep {\n readonly kind: \"dowhile\";\n readonly id: string;\n readonly step: Step;\n readonly condFn: (output: unknown, iteration: number) => boolean | Promise<boolean>;\n readonly maxIterations?: number;\n}\n\n/** Pause for a fixed duration. */\nexport interface SleepStep {\n readonly kind: \"sleep\";\n readonly id: string;\n readonly durationMs: number;\n}\n\n/** Standalone explicit suspend point. */\nexport interface SuspendStep {\n readonly kind: \"suspend\";\n readonly id: string;\n readonly payloadSchema?: ZodType;\n}\n\n/* ─── Supporting types ─── */\n\n/** D237 — retry policy applied per fn/agent step. */\nexport interface RetryPolicy {\n /** Total attempts (MIN 1, MAX 20). `1` = no retry. */\n readonly maxAttempts: number;\n readonly initialBackoffMs?: number;\n readonly backoffCoefficient?: number;\n readonly maximumBackoffMs?: number;\n readonly nonRetryableErrors?: ReadonlyArray<string>;\n}\n\n/** D247 — context handed to every step.fn. */\nexport interface StepContext {\n readonly runId: string;\n readonly signal: AbortSignal;\n readonly log: {\n debug: (msg: string, attrs?: Record<string, unknown>) => void;\n info: (msg: string, attrs?: Record<string, unknown>) => void;\n warn: (msg: string, attrs?: Record<string, unknown>) => void;\n };\n /** Pause the workflow; resume via `Workflow.resume({...})`. */\n readonly suspend: (payload?: unknown) => Promise<never>;\n}\n\n/* ─── Result types ─── */\n\nexport interface StepResult {\n readonly stepId: string;\n readonly kind: Step[\"kind\"];\n readonly status: \"completed\" | \"failed\" | \"skipped\" | \"suspended\";\n readonly attempts: number;\n readonly durationMs: number;\n readonly output?: unknown;\n readonly error?: { name: string; message: string };\n}\n\nexport interface WorkflowRun<TOutput = unknown> {\n readonly id: string;\n readonly name: string;\n readonly status: \"running\" | \"completed\" | \"failed\" | \"suspended\" | \"cancelled\";\n readonly output?: TOutput;\n readonly error?: { name: string; message: string };\n readonly startedAt: number;\n readonly endedAt?: number;\n readonly stepResults: ReadonlyArray<StepResult>;\n}\n\nexport interface WorkflowSnapshot {\n readonly _schemaVersion: 1;\n readonly runId: string;\n readonly workflowName: string;\n readonly currentStepId: string;\n readonly suspendedPayload?: unknown;\n readonly stepResults: ReadonlyArray<StepResult>;\n readonly accumulatedInput: unknown;\n readonly suspendedAt: number;\n}\n\n/* ─── Options ─── */\n\nexport interface WorkflowPersistenceOptions {\n readonly backend: \"memory\" | \"json\";\n /** Required for `backend: \"json\"`. */\n readonly dir?: string;\n}\n\nexport interface WorkflowOptions {\n readonly name: string;\n readonly persistence?: WorkflowPersistenceOptions;\n /** Internal — minted at `.commit()`. Not user-facing. */\n readonly workflowId?: string;\n}\n\nexport interface WorkflowRunOptions {\n readonly signal?: AbortSignal;\n /** Override run ID for deterministic resume (advanced; default = mintRunId). */\n readonly runId?: string;\n /**\n * Opt-in Task wrapping (ADRs D363, D374). Registers the workflow run\n * as a `Task` (kind=\"workflow\") with a `wf-` namespaced id (D368,\n * EC-5). The task transitions terminal when `Workflow.run` resolves.\n *\n * Auto-id: `wf-{runId}`.\n *\n * @public\n */\n readonly task?: true | { id?: string; meta?: Record<string, unknown> };\n}\n\nexport interface WorkflowResumeOptions<TI = unknown> {\n readonly runId: string;\n readonly workflow: { run: (input: TI, opts?: WorkflowRunOptions) => Promise<WorkflowRun> };\n readonly payload?: unknown;\n readonly signal?: AbortSignal;\n}\n\n/* ─── Error classes ─── */\n\nexport class WorkflowDuplicateStepIdError extends Error {\n override readonly name = \"WorkflowDuplicateStepIdError\";\n constructor(public readonly stepId: string) {\n super(`Duplicate step id \"${stepId}\" in workflow.`);\n }\n}\n\nexport class WorkflowAlreadyRunningError extends Error {\n override readonly name = \"WorkflowAlreadyRunningError\";\n constructor(\n public readonly workflowName: string,\n public readonly runId: string,\n ) {\n super(`Workflow \"${workflowName}\" run \"${runId}\" already in-flight.`);\n }\n}\n\nexport class WorkflowSnapshotNotFoundError extends Error {\n override readonly name = \"WorkflowSnapshotNotFoundError\";\n constructor(public readonly runId: string) {\n super(`No snapshot found for runId \"${runId}\". Configure persistence to enable resume.`);\n }\n}\n\nexport class WorkflowMaxIterationsExceededError extends Error {\n override readonly name = \"WorkflowMaxIterationsExceededError\";\n constructor(\n public readonly stepId: string,\n public readonly maxIterations: number,\n ) {\n super(`Step \"${stepId}\" exceeded max iterations (${maxIterations}).`);\n }\n}\n\n/** EC-4 absorbed — JSON.stringify failed on snapshot payload. */\nexport class WorkflowNotSerializableError extends Error {\n override readonly name = \"WorkflowNotSerializableError\";\n constructor(\n public readonly stepId: string,\n public readonly underlying: Error,\n ) {\n super(\n `Workflow snapshot at step \"${stepId}\" failed to serialize as JSON: ${underlying.message}. ` +\n `Persisted snapshots support only JSON-serializable values (no BigInt, no circular refs, no class instances with cycles).`,\n );\n }\n}\n\n/** EC-8 absorbed — `currentStepId` from snapshot not found in resumed workflow. */\nexport class WorkflowResumeStepNotFoundError extends Error {\n override readonly name = \"WorkflowResumeStepNotFoundError\";\n constructor(\n public readonly stepId: string,\n public readonly workflowName: string,\n ) {\n super(\n `Cannot resume: step \"${stepId}\" not found in workflow \"${workflowName}\". ` +\n `The Workflow definition diverged from the snapshot.`,\n );\n }\n}\n\n/** Aggregate failure from parallel branches. */\nexport class WorkflowParallelError extends AggregateError {\n override readonly name = \"WorkflowParallelError\";\n constructor(\n errors: ReadonlyArray<Error>,\n public readonly stepId: string,\n ) {\n super(errors, `${errors.length} branch(es) failed in parallel step \"${stepId}\".`);\n }\n}\n\n/** D238 — saga engine not yet implemented. */\nexport class WorkflowCompensateNotImplementedError extends Error {\n override readonly name = \"WorkflowCompensateNotImplementedError\";\n constructor(public readonly stepId: string) {\n super(\n `Step \"${stepId}\" defines compensate, but saga engine is deferred to v1.2. ` +\n `Remove compensate or implement rollback manually.`,\n );\n }\n}\n","import { mkdir, open, rename, unlink } from \"node:fs/promises\";\nimport { dirname } from \"node:path\";\n\n/**\n * Atomic file replacement: write content to a per-call unique tmp path,\n * fsync, then rename over the target. Crash mid-write leaves either the old\n * file intact or the new file complete — never a half-written file.\n *\n * The tmp suffix is `<pid>.<rand>.tmp` so parallel processes (and concurrent\n * burst writes within one process) never collide on the same tmp path — a\n * race that would manifest as `ENOENT` on `rename` after the rival process\n * already moved its tmp into place.\n *\n * Mirrors OpenClaw's `replaceFileAtomic` from\n * `referencia/openclaw/packages/memory-host-sdk/src/host/fs-utils.ts` with\n * the multi-writer robustness fix.\n *\n * @internal\n */\nexport async function replaceFileAtomic(filePath: string, content: string): Promise<void> {\n const tmp = `${filePath}.${process.pid}.${Math.random().toString(36).slice(2, 10)}.tmp`;\n const handle = await open(tmp, \"w\");\n try {\n await handle.writeFile(content, \"utf8\");\n await handle.sync();\n } finally {\n await handle.close();\n }\n try {\n await rename(tmp, filePath);\n } catch (cause) {\n // Cleanup tmp on rename failure so we don't leak stale .tmp files.\n await unlink(tmp).catch(() => undefined);\n throw cause;\n }\n}\n\n/**\n * Options for `atomicWriteJson`.\n *\n * @internal\n */\nexport interface AtomicWriteJsonOptions {\n /** Indent passed to `JSON.stringify`. Default: 2. */\n indent?: number;\n /** Whether to append a trailing newline (POSIX convention). Default: true. */\n trailingNewline?: boolean;\n}\n\n/**\n * Typed JSON atomic write helper.\n *\n * Serializes `data` to JSON, then delegates to `replaceFileAtomic`. The\n * parent directory is auto-created (recursive `mkdir`) to make this helper\n * safe for callers who haven't ensured the directory exists (EC-4 in the\n * persistence-state-hardening plan).\n *\n * Throws `TypeError` on circular refs or `undefined` data (propagates from\n * `JSON.stringify`).\n *\n * @internal\n */\nexport async function atomicWriteJson<T>(\n filePath: string,\n data: T,\n options?: AtomicWriteJsonOptions,\n): Promise<void> {\n const indent = options?.indent ?? 2;\n const trailingNewline = options?.trailingNewline ?? true;\n const json = JSON.stringify(data, null, indent);\n if (json === undefined) {\n throw new TypeError(\"atomicWriteJson: cannot serialize undefined\");\n }\n const content = trailingNewline ? `${json}\\n` : json;\n await mkdir(dirname(filePath), { recursive: true });\n await replaceFileAtomic(filePath, content);\n}\n\n/**\n * Atomic text write. Same crash-safety guarantees as `replaceFileAtomic` +\n * auto-mkdir of the parent directory. Used by `theokit-migrate-config`\n * (T4.1, EC-2 MUST FIX) so a crash mid-migration leaves previous MD files\n * intact rather than corrupting them.\n *\n * @internal\n */\nexport async function atomicWriteText(filePath: string, content: string): Promise<void> {\n await mkdir(dirname(filePath), { recursive: true });\n await replaceFileAtomic(filePath, content);\n}\n","/**\n * Snapshot store interface + InMemory and JsonFile backends (ADR D235).\n *\n * EC-4 absorbed: serialization happens here. `JSON.stringify` failure raises\n * `WorkflowNotSerializableError` instead of letting the underlying `TypeError`\n * leak.\n *\n * @internal\n */\n\nimport { mkdir, readdir, readFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport {\n WorkflowNotSerializableError,\n type WorkflowOptions,\n type WorkflowSnapshot,\n} from \"../../types/workflow.js\";\nimport { atomicWriteText } from \"../persistence/atomic-write.js\";\n\nexport interface WorkflowSnapshotStore {\n save(snapshot: WorkflowSnapshot): Promise<void>;\n load(runId: string): Promise<WorkflowSnapshot | undefined>;\n delete(runId: string): Promise<void>;\n list(\n workflowName?: string,\n ): Promise<ReadonlyArray<{ runId: string; workflowName: string; suspendedAt: number }>>;\n}\n\n/* ─── InMemory backend (default) ─── */\n\nclass InMemoryWorkflowSnapshotStore implements WorkflowSnapshotStore {\n private readonly map = new Map<string, WorkflowSnapshot>();\n\n async save(snapshot: WorkflowSnapshot): Promise<void> {\n // Verify serializability even in-memory so behavior is consistent with json backend.\n try {\n JSON.stringify(snapshot);\n } catch (err) {\n throw new WorkflowNotSerializableError(\n snapshot.currentStepId,\n err instanceof Error ? err : new Error(String(err)),\n );\n }\n this.map.set(snapshot.runId, snapshot);\n }\n async load(runId: string): Promise<WorkflowSnapshot | undefined> {\n return this.map.get(runId);\n }\n async delete(runId: string): Promise<void> {\n this.map.delete(runId);\n }\n async list(\n workflowName?: string,\n ): Promise<ReadonlyArray<{ runId: string; workflowName: string; suspendedAt: number }>> {\n return [...this.map.values()]\n .filter((s) => workflowName === undefined || s.workflowName === workflowName)\n .map((s) => ({\n runId: s.runId,\n workflowName: s.workflowName,\n suspendedAt: s.suspendedAt,\n }));\n }\n}\n\n/* ─── Json file backend (opt-in) ─── */\n\nclass JsonFileWorkflowSnapshotStore implements WorkflowSnapshotStore {\n constructor(private readonly dir: string) {}\n\n private filePath(runId: string): string {\n return join(this.dir, `${runId}.json`);\n }\n\n async save(snapshot: WorkflowSnapshot): Promise<void> {\n let serialized: string;\n try {\n serialized = JSON.stringify(snapshot);\n } catch (err) {\n throw new WorkflowNotSerializableError(\n snapshot.currentStepId,\n err instanceof Error ? err : new Error(String(err)),\n );\n }\n await mkdir(this.dir, { recursive: true });\n await atomicWriteText(this.filePath(snapshot.runId), serialized);\n }\n\n async load(runId: string): Promise<WorkflowSnapshot | undefined> {\n try {\n const raw = await readFile(this.filePath(runId), \"utf8\");\n return JSON.parse(raw) as WorkflowSnapshot;\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") return undefined;\n throw err;\n }\n }\n\n async delete(runId: string): Promise<void> {\n try {\n await (await import(\"node:fs/promises\")).unlink(this.filePath(runId));\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code !== \"ENOENT\") throw err;\n }\n }\n\n private async readEntriesOrEmpty(): Promise<string[]> {\n try {\n return await readdir(this.dir);\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") return [];\n throw err;\n }\n }\n\n private async readSnapshotSafe(file: string): Promise<WorkflowSnapshot | undefined> {\n try {\n const raw = await readFile(join(this.dir, file), \"utf8\");\n return JSON.parse(raw) as WorkflowSnapshot;\n } catch {\n return undefined;\n }\n }\n\n async list(\n workflowName?: string,\n ): Promise<ReadonlyArray<{ runId: string; workflowName: string; suspendedAt: number }>> {\n const entries = await this.readEntriesOrEmpty();\n const results: Array<{ runId: string; workflowName: string; suspendedAt: number }> = [];\n for (const file of entries) {\n if (!file.endsWith(\".json\")) continue;\n const snap = await this.readSnapshotSafe(file);\n if (snap === undefined) continue;\n if (workflowName !== undefined && snap.workflowName !== workflowName) continue;\n results.push({\n runId: snap.runId,\n workflowName: snap.workflowName,\n suspendedAt: snap.suspendedAt,\n });\n }\n return results;\n }\n}\n\n/* ─── Resolver: per-Workflow store cache ─── */\n\nconst memoryStore = new InMemoryWorkflowSnapshotStore();\nconst jsonStores = new Map<string, JsonFileWorkflowSnapshotStore>();\n\nexport function getSnapshotStoreFor(options: WorkflowOptions): WorkflowSnapshotStore {\n if (options.persistence?.backend === \"json\") {\n const dir = options.persistence.dir as string; // schema enforces dir is set\n let store = jsonStores.get(dir);\n if (store === undefined) {\n store = new JsonFileWorkflowSnapshotStore(dir);\n jsonStores.set(dir, store);\n }\n return store;\n }\n return memoryStore;\n}\n\n/** Test seam — clear in-memory store between tests. */\nexport function __resetSnapshotStoresForTests(): void {\n jsonStores.clear();\n // memoryStore has private map; reset via assignment.\n // biome-ignore lint/suspicious/noExplicitAny: test-only seam\n (memoryStore as any).map.clear();\n}\n","/**\n * Build the `StepContext` passed to every step.fn. The `suspend` method\n * throws a `WorkflowSuspendedSentinel` (defined here) that the executor\n * catches to persist a snapshot (D236).\n *\n * @internal\n */\n\nimport type { StepContext } from \"../../types/workflow.js\";\n\n/** Sentinel thrown by `ctx.suspend()`; only the executor catches it. */\nexport class WorkflowSuspendedSentinel extends Error {\n override readonly name = \"WorkflowSuspendedSentinel\";\n constructor(public readonly payload?: unknown) {\n super(\"__workflow_suspended__\");\n }\n}\n\nexport function makeStepContext(runId: string, signal: AbortSignal): StepContext {\n return {\n runId,\n signal,\n log: {\n debug: (msg, attrs) => emit(\"debug\", runId, msg, attrs),\n info: (msg, attrs) => emit(\"info\", runId, msg, attrs),\n warn: (msg, attrs) => emit(\"warn\", runId, msg, attrs),\n },\n suspend: async (payload?: unknown) => {\n throw new WorkflowSuspendedSentinel(payload);\n },\n };\n}\n\nfunction emit(\n level: \"debug\" | \"info\" | \"warn\",\n runId: string,\n msg: string,\n attrs?: Record<string, unknown>,\n): void {\n const tag = `[workflow ${runId}]`;\n if (attrs !== undefined) {\n if (level === \"warn\") console.warn(tag, msg, attrs);\n else console.log(tag, msg, attrs);\n } else {\n if (level === \"warn\") console.warn(tag, msg);\n else console.log(tag, msg);\n }\n}\n\n/**\n * Combine the caller-supplied signal with the flight signal so abort on\n * either side cancels the workflow run.\n */\nexport function combineSignals(...signals: ReadonlyArray<AbortSignal | undefined>): AbortSignal {\n const valid = signals.filter((s): s is AbortSignal => s !== undefined);\n if (valid.length === 0) return new AbortController().signal;\n if (valid.length === 1) return valid[0]!;\n const ctrl = new AbortController();\n for (const s of valid) {\n if (s.aborted) {\n ctrl.abort(s.reason);\n break;\n }\n s.addEventListener(\"abort\", () => ctrl.abort(s.reason), { once: true });\n }\n return ctrl.signal;\n}\n","/**\n * Helper to normalize unknown thrown values to `{ name, message }` shape\n * for use in `StepResult.error` / `WorkflowRun.error`.\n *\n * @internal\n */\n\nexport function errToShape(err: unknown): { name: string; message: string } {\n if (err instanceof Error) {\n return { name: err.name, message: err.message };\n }\n return { name: \"Error\", message: String(err) };\n}\n","/**\n * Generate a short, deterministic workflow run identifier.\n *\n * Format: `wfr-<8 hex chars>`. Used for span keys, snapshot filenames, and\n * single-flight registry keys.\n *\n * @internal\n */\n\nexport function mintRunId(): string {\n return `wfr-${globalThis.crypto.randomUUID().replace(/-/g, \"\").slice(0, 8)}`;\n}\n","/**\n * Single-flight registry for in-flight workflow runs (ADR D242).\n *\n * Key = `${workflowId}:${runId}`. Throws `WorkflowAlreadyRunningError` on\n * duplicate. Process crash auto-releases (in-memory map). Pattern mirrors\n * `internal/eval/single-flight.ts` (D213).\n *\n * EC-5 absorbed: lock uses `workflowId` (minted at `.commit()`), not the\n * user-supplied `name`, so two `Workflow` instances sharing a name don't\n * collide on each other's locks.\n *\n * @internal\n */\n\nimport { WorkflowAlreadyRunningError } from \"../../types/workflow.js\";\n\ninterface Flight {\n controller: AbortController;\n}\n\nconst registry = new Map<string, Flight>();\n\nfunction key(workflowId: string, runId: string): string {\n return `${workflowId}:${runId}`;\n}\n\nexport interface AcquiredFlight {\n signal: AbortSignal;\n release: () => void;\n}\n\nexport function acquireSingleFlight(\n workflowId: string,\n runId: string,\n workflowName: string,\n): AcquiredFlight {\n const k = key(workflowId, runId);\n if (registry.has(k)) {\n throw new WorkflowAlreadyRunningError(workflowName, runId);\n }\n const controller = new AbortController();\n registry.set(k, { controller });\n return {\n signal: controller.signal,\n release: () => {\n registry.delete(k);\n },\n };\n}\n","/**\n * Retry wrapper with exponential backoff (ADR D237).\n *\n * `withRetry(fn, policy, signal)` retries on throw until success or\n * `maxAttempts` reached. Aborts mid-backoff when signal fires.\n * Non-retryable errors (by name) propagate immediately.\n *\n * @internal\n */\n\nimport type { RetryPolicy } from \"../../types/workflow.js\";\n\nconst DEFAULT_NON_RETRYABLE = [\"AbortError\", \"WorkflowSnapshotNotFoundError\", \"ConfigurationError\"];\n\ninterface BackoffConfig {\n init: number;\n coef: number;\n cap: number;\n nonRetryable: Set<string>;\n max: number;\n}\n\nfunction backoffConfigFromPolicy(policy: RetryPolicy): BackoffConfig {\n return {\n max: policy.maxAttempts,\n init: policy.initialBackoffMs ?? 1000,\n coef: policy.backoffCoefficient ?? 2.0,\n cap: policy.maximumBackoffMs ?? 30_000,\n nonRetryable: new Set(policy.nonRetryableErrors ?? DEFAULT_NON_RETRYABLE),\n };\n}\n\nfunction throwIfAborted(signal: AbortSignal): void {\n if (signal.aborted) {\n throw new DOMException(String(signal.reason ?? \"Aborted\"), \"AbortError\");\n }\n}\n\nfunction shouldRethrow(err: unknown, attempt: number, cfg: BackoffConfig): boolean {\n const errName = err instanceof Error ? err.name : \"Error\";\n return cfg.nonRetryable.has(errName) || attempt === cfg.max;\n}\n\nasync function tryOnce<T>(\n fn: () => Promise<T>,\n attempt: number,\n cfg: BackoffConfig,\n signal: AbortSignal,\n): Promise<{ value: T; attempts: number } | { kind: \"retry\" }> {\n try {\n const value = await fn();\n return { value, attempts: attempt };\n } catch (err) {\n if (shouldRethrow(err, attempt, cfg)) throw err;\n await abortableSleep(Math.min(cfg.init * cfg.coef ** (attempt - 1), cfg.cap), signal);\n return { kind: \"retry\" };\n }\n}\n\nexport async function withRetry<T>(\n fn: () => Promise<T>,\n policy: RetryPolicy,\n signal: AbortSignal,\n): Promise<{ value: T; attempts: number }> {\n const cfg = backoffConfigFromPolicy(policy);\n for (let attempt = 1; attempt <= cfg.max; attempt += 1) {\n throwIfAborted(signal);\n const result = await tryOnce(fn, attempt, cfg, signal);\n if (\"value\" in result) return result;\n }\n // Unreachable: tryOnce throws on the final attempt when shouldRethrow returns true.\n throw new Error(\"withRetry: exhausted attempts without throwing\");\n}\n\nexport async function abortableSleep(ms: number, signal: AbortSignal): Promise<void> {\n if (signal.aborted) {\n throw new DOMException(String(signal.reason ?? \"Aborted\"), \"AbortError\");\n }\n return new Promise((resolve, reject) => {\n const timer = setTimeout(() => {\n cleanup();\n resolve();\n }, ms);\n const onAbort = (): void => {\n clearTimeout(timer);\n cleanup();\n reject(new DOMException(String(signal.reason ?? \"Aborted\"), \"AbortError\"));\n };\n const cleanup = (): void => {\n signal.removeEventListener(\"abort\", onAbort);\n };\n signal.addEventListener(\"abort\", onAbort, { once: true });\n });\n}\n","/**\n * Execute an `AgentStep` — render the prompt template, call `agent.send`,\n * wait for completion, return the result text as step output (ADR D244,\n * D245).\n *\n * Cloud guard: agents marked as `CloudAgent` throw `UnsupportedRunOperationError`\n * (workflows are local-only in v1).\n *\n * @internal\n */\n\nimport { UnsupportedRunOperationError } from \"../../errors.js\";\nimport type { AgentStep, StepContext, StepResult } from \"../../types/workflow.js\";\nimport { WorkflowSuspendedSentinel } from \"./ctx.js\";\nimport { errToShape } from \"./error-shape.js\";\nimport { withRetry } from \"./retry-policy.js\";\n\nexport async function runAgentStep(\n step: AgentStep,\n input: unknown,\n ctx: StepContext,\n): Promise<StepResult> {\n const startedAt = Date.now();\n // D244: cloud guard — workflows are LocalAgent-only in v1.\n const agentId = step.agent.agentId;\n if (typeof agentId === \"string\" && agentId.startsWith(\"bc-\")) {\n return {\n stepId: step.id,\n kind: \"agent\",\n status: \"failed\",\n attempts: 0,\n durationMs: Date.now() - startedAt,\n error: errToShape(\n new UnsupportedRunOperationError(\n \"Workflow agent steps not supported on CloudAgent yet (D244).\" +\n ` agent=\"${agentId}\", step=\"${step.id}\"`,\n \"workflow\",\n ),\n ),\n };\n }\n\n let prompt: string;\n try {\n prompt =\n typeof step.promptTemplate === \"string\" ? step.promptTemplate : step.promptTemplate(input);\n } catch (err) {\n return {\n stepId: step.id,\n kind: \"agent\",\n status: \"failed\",\n attempts: 0,\n durationMs: Date.now() - startedAt,\n error: errToShape(err),\n };\n }\n if (typeof prompt !== \"string\" || prompt.length === 0) {\n return {\n stepId: step.id,\n kind: \"agent\",\n status: \"failed\",\n attempts: 0,\n durationMs: Date.now() - startedAt,\n error: errToShape(\n new Error(`agentStep \"${step.id}\": rendered prompt must be a non-empty string`),\n ),\n };\n }\n\n const exec = async (): Promise<string> => {\n const run = await step.agent.send(prompt);\n const result = await run.wait();\n if (result.status === \"finished\") {\n return result.result ?? \"\";\n }\n if (result.status === \"error\") {\n throw (result as { error?: Error }).error ?? new Error(\"agent.send errored\");\n }\n throw new Error(`Unexpected agent status: ${result.status}`);\n };\n\n try {\n const { value, attempts } =\n step.retry !== undefined\n ? await withRetry(exec, step.retry, ctx.signal)\n : { value: await exec(), attempts: 1 };\n return {\n stepId: step.id,\n kind: \"agent\",\n status: \"completed\",\n attempts,\n durationMs: Date.now() - startedAt,\n output: value,\n };\n } catch (err) {\n // Re-throw suspend sentinel so the executor can persist a snapshot.\n if (err instanceof WorkflowSuspendedSentinel) throw err;\n return {\n stepId: step.id,\n kind: \"agent\",\n status: \"failed\",\n attempts: 1,\n durationMs: Date.now() - startedAt,\n error: errToShape(err),\n };\n }\n}\n","/**\n * Canonical secret redaction module (ADRs D68-D73).\n *\n * Single source of truth for credential pattern masking across the SDK.\n * Wired at output boundaries: `ErrorMetadata.raw` (mappers/shared.ts),\n * telemetry span attributes (telemetry/tracer.ts), transcript JSONL\n * appends (agent-session-store.ts), migration logger output\n * (memory/migrate-sqlite-to-lance.ts).\n *\n * - D68: central module, single source of truth (replaces 2 duplicates)\n * - D69: env snapshot at module init (prompt-injection defense)\n * - D70: ON by default, warn on opt-out\n * - D71: two-bucket masking — short fully masked, long preserves prefix+suffix\n * - D72: `codeFile` opt-out for legitimate prefix-shaped content\n * - D73: redact at OUTPUT boundaries, not at storage\n *\n * @internal\n */\n\n// D69: env snapshot captured at module load. Subsequent mutations of\n// process.env.THEOKIT_REDACT_SECRETS are ignored — defends against\n// prompt injection that tries to disable redaction mid-run.\nlet REDACT_ENABLED: boolean = readEnvOnce();\n\nfunction readEnvOnce(): boolean {\n const raw = process.env.THEOKIT_REDACT_SECRETS;\n if (raw === undefined) return true; // D70: default ON\n return [\"1\", \"true\", \"yes\", \"on\"].includes(raw.toLowerCase());\n}\n\n// D70: warn once on opt-out so the user knows they're vulnerable.\nlet warnedOptOut = false;\nif (!REDACT_ENABLED && !warnedOptOut) {\n process.stderr.write(\n \"[theokit-sdk] Secret redaction is DISABLED via THEOKIT_REDACT_SECRETS. \" +\n \"Credentials may leak into errors, telemetry, logs, transcripts.\\n\",\n );\n warnedOptOut = true;\n}\n\n/**\n * Built-in credential patterns. Order matters — more specific prefixes\n * must come before generic ones (e.g., `sk-ant-` before `sk-`). Quantifiers\n * are all bounded `{n,m}` or applied to char classes — linear time, no ReDoS.\n *\n * @internal\n */\nconst BUILTIN_PATTERNS: readonly RegExp[] = [\n /sk-ant-[A-Za-z0-9_-]{10,}/g, // Anthropic\n /sk-proj-[A-Za-z0-9_-]{10,}/g, // OpenAI project key (must precede sk- generic)\n /sk-[A-Za-z0-9_-]{10,}/g, // OpenAI / OpenRouter / DeepInfra. {10,} body floor —\n // real keys are 40+ chars; 10-char floor still skips `sk-test` (4) and\n // `sk-test-key` (8). codeFile mode protects placeholders/examples.\n /ghp_[A-Za-z0-9]{36}/g, // GitHub PAT classic (exact length)\n /github_pat_[A-Za-z0-9_]{82}/g, // GitHub PAT fine-grained\n /glpat-[A-Za-z0-9_-]{20}/g, // GitLab PAT\n /AKIA[A-Z0-9]{16}/g, // AWS access key\n /AIza[A-Za-z0-9_-]{35}/g, // Google API key\n /xox[bpasr]-[A-Za-z0-9-]{10,}/g, //Slack tokens\n /sntrys_[A-Za-z0-9]{40,}/g, // Sentry user auth\n /sk_live_[A-Za-z0-9]{20,}/g, // Stripe secret\n /rk_live_[A-Za-z0-9]{20,}/g, // Stripe restricted\n];\n\n// `Bearer <token>` matched as its own first-class pattern so PARAM_PATTERN\n// doesn't have to handle the unusual `Authorization: Bearer xxx` shape\n// (no `:` or `=` between \"Bearer\" and the value — bare whitespace).\nconst BEARER_PATTERN = /\\b(Bearer\\s+)([A-Za-z0-9_\\-.+/=]{8,})/g;\n\n// Parametric: matches `key=value` and `key: value` (with optional quote\n// between the key and the separator, to handle JSON: `\"api_key\": \"...\"`)\n// in URLs, query strings, JSON-like bodies, HTTP headers. Captures the\n// prefix so we keep it visible while masking the value.\n//\n// `authorization` deliberately excluded — BEARER_PATTERN handles the\n// common `Authorization: Bearer xxx` shape. Including it here causes\n// double-masking (\"Authorization: *** ***\") after Bearer fires.\nconst PARAM_PATTERN =\n /(\\b(?:access_token|api_key|api-key|password|secret|x-api-key)\\b[\"']?\\s*[:=]\\s*[\"']?)([A-Za-z0-9_\\-.+/]+)/gi;\n\nconst _extraPatterns: RegExp[] = [];\n\n/**\n * Add a user-defined redaction pattern. Additive — never removes builtins.\n * Throws if the regex lacks the `/g` flag (without `/g`, `.replace` only\n * substitutes the first match and the rest leaks).\n *\n * @internal — exposed publicly via `Security.addPattern` in `src/security.ts`.\n */\nexport function addPattern(re: RegExp): void {\n if (!re.global) {\n throw new Error(\"Security.addPattern: regex must have /g flag for replace-all semantics\");\n }\n _extraPatterns.push(re);\n}\n\n/**\n * Two-bucket masking (D71):\n * - tokens shorter than 18 chars → fully masked as `***`\n * - tokens >= 18 chars → keep first 6 + `...` + last 4\n *\n * Rationale: long tokens are unique per-account; prefix+suffix preserves\n * debuggability without revealing the secret middle.\n *\n * @internal\n */\nexport function maskToken(token: string): string {\n if (token.length < 18) return \"***\";\n return `${token.slice(0, 6)}...${token.slice(-4)}`;\n}\n\n/**\n * Redact known credential patterns from `text`. Default behavior masks\n * builtins + extras + parametric `key=value` sinks.\n *\n * With `{ codeFile: true }` (D72), skips PARAM_PATTERN to avoid mangling\n * `.env.example`, schema JSON, or test fixtures that legitimately contain\n * prefix-like strings.\n *\n * Returns the redacted string. Coerces non-strings via JSON.stringify;\n * EC-7 fix (edge-case review): wraps in try/catch so circular references\n * never propagate — returns sentinel `\"[unredactable: circular]\"`.\n *\n * @internal\n */\n// Coerce arbitrary input to a string for redaction. Returns `null`\n// sentinel when the value is null/undefined/non-stringifiable, so the\n// caller can short-circuit with `\"\"`. EC-7 fix: circular refs go through\n// the try/catch and produce the sentinel marker, never throwing.\nfunction coerceToString(value: unknown): string | null {\n if (typeof value === \"string\") return value;\n if (value === null || value === undefined) return null;\n if (typeof value === \"object\") {\n try {\n const s = JSON.stringify(value);\n return s === undefined ? null : s;\n } catch {\n return \"[unredactable: circular]\";\n }\n }\n return String(value);\n}\n\nexport function redactSecrets(text: unknown, opts?: { codeFile?: boolean }): string {\n const coerced = coerceToString(text);\n if (coerced === null) return \"\";\n if (!REDACT_ENABLED) return coerced;\n\n let s = coerced;\n for (const re of BUILTIN_PATTERNS) {\n s = s.replace(re, (m) => maskToken(m));\n }\n for (const re of _extraPatterns) {\n s = s.replace(re, (m) => maskToken(m));\n }\n if (!opts?.codeFile) {\n // Bearer first (preserves \"Bearer \" prefix, masks the token after).\n // Must run before PARAM_PATTERN so the bare-whitespace shape doesn't\n // get mis-handled as a value.\n s = s.replace(BEARER_PATTERN, (_, prefix: string) => `${prefix}***`);\n s = s.replace(PARAM_PATTERN, (_, prefix: string) => `${prefix}***`);\n }\n return s;\n}\n\n/**\n * Test-only helper exported for `_test-reset.ts`. NOT included in the\n * `index.ts` barrel — vitest setup imports the dedicated module via\n * explicit path to discourage production callers.\n *\n * @internal\n */\nexport function _resetForTests(opts: { enabled?: boolean; clearExtras?: boolean }): void {\n if (opts.enabled !== undefined) REDACT_ENABLED = opts.enabled;\n if (opts.clearExtras === true) _extraPatterns.length = 0;\n}\n","/**\n * Execute a `BranchStep` — first-match-wins predicates + optional fallback.\n *\n * EC-2 absorbed: predicates that THROW are treated as \"no match\" + stderr\n * warn — user-code bugs in predicates don't take down the whole workflow.\n *\n * @internal\n */\n\nimport type {\n BranchStep,\n Step,\n StepContext,\n StepResult,\n WorkflowOptions,\n} from \"../../types/workflow.js\";\nimport { redactSecrets } from \"../security/redact.js\";\nimport { errToShape } from \"./error-shape.js\";\nimport type { DispatchFn } from \"./step-parallel.js\";\n\nexport async function runBranchStep(\n step: BranchStep,\n input: unknown,\n ctx: StepContext,\n options: WorkflowOptions,\n prevStepResults: ReadonlyArray<StepResult>,\n dispatch: DispatchFn,\n): Promise<StepResult> {\n const startedAt = Date.now();\n\n for (let i = 0; i < step.predicates.length; i += 1) {\n const pair = step.predicates[i]!;\n const [predicate, branch] = pair;\n // EC-2: predicate throw → warn + treat as no-match.\n let matched = false;\n try {\n matched = await Promise.resolve(predicate(input));\n } catch (err) {\n const errText = err instanceof Error ? err.message : String(err);\n console.warn(\n redactSecrets(\n `[workflow] branch \"${step.id}\" predicate ${i} threw, treating as no-match: ${errText}`,\n ),\n );\n }\n if (matched) {\n const r = await runInnerSequence(branch, input, ctx, options, prevStepResults, dispatch);\n return {\n ...r,\n stepId: step.id,\n kind: \"branch\",\n durationMs: Date.now() - startedAt,\n };\n }\n }\n\n if (step.fallback !== undefined) {\n const r = await runInnerSequence(step.fallback, input, ctx, options, prevStepResults, dispatch);\n return {\n ...r,\n stepId: step.id,\n kind: \"branch\",\n durationMs: Date.now() - startedAt,\n };\n }\n\n // No match, no fallback → pass input through unchanged.\n return {\n stepId: step.id,\n kind: \"branch\",\n status: \"skipped\",\n attempts: 0,\n durationMs: Date.now() - startedAt,\n output: input,\n };\n}\n\nasync function runInnerSequence(\n branch: ReadonlyArray<Step>,\n input: unknown,\n ctx: StepContext,\n options: WorkflowOptions,\n prevStepResults: ReadonlyArray<StepResult>,\n dispatch: DispatchFn,\n): Promise<StepResult> {\n let acc: unknown = input;\n let lastAttempts = 1;\n for (const inner of branch) {\n const r = await dispatch(inner, acc, ctx, options, prevStepResults);\n lastAttempts = r.attempts;\n if (r.status === \"failed\") {\n return {\n stepId: inner.id,\n kind: \"branch\",\n status: \"failed\",\n attempts: r.attempts,\n durationMs: 0,\n error: r.error ?? errToShape(new Error(\"branch inner step failed\")),\n };\n }\n acc = r.output;\n }\n return {\n stepId: \"__branch-completed__\",\n kind: \"branch\",\n status: \"completed\",\n attempts: lastAttempts,\n durationMs: 0,\n output: acc,\n };\n}\n","/**\n * Execute a `DowhileStep` — loop the inner step until `condFn` returns\n * false or `maxIterations` is reached (default 100).\n *\n * @internal\n */\n\nimport type {\n DowhileStep,\n StepContext,\n StepResult,\n WorkflowOptions,\n} from \"../../types/workflow.js\";\nimport { WorkflowMaxIterationsExceededError } from \"../../types/workflow.js\";\nimport { errToShape } from \"./error-shape.js\";\nimport type { DispatchFn } from \"./step-parallel.js\";\n\nexport async function runDowhileStep(\n step: DowhileStep,\n input: unknown,\n ctx: StepContext,\n options: WorkflowOptions,\n prevStepResults: ReadonlyArray<StepResult>,\n dispatch: DispatchFn,\n): Promise<StepResult> {\n const startedAt = Date.now();\n const maxIter = step.maxIterations ?? 100;\n let acc = input;\n let i = 0;\n while (true) {\n if (i >= maxIter) {\n return {\n stepId: step.id,\n kind: \"dowhile\",\n status: \"failed\",\n attempts: i,\n durationMs: Date.now() - startedAt,\n error: errToShape(new WorkflowMaxIterationsExceededError(step.id, maxIter)),\n };\n }\n const r = await dispatch(step.step, acc, ctx, options, prevStepResults);\n if (r.status === \"failed\") {\n return {\n stepId: step.id,\n kind: \"dowhile\",\n status: \"failed\",\n attempts: i + 1,\n durationMs: Date.now() - startedAt,\n error: r.error,\n };\n }\n acc = r.output;\n i += 1;\n let shouldContinue = false;\n try {\n shouldContinue = await Promise.resolve(step.condFn(acc, i));\n } catch (err) {\n return {\n stepId: step.id,\n kind: \"dowhile\",\n status: \"failed\",\n attempts: i,\n durationMs: Date.now() - startedAt,\n error: errToShape(err),\n };\n }\n if (!shouldContinue) break;\n }\n return {\n stepId: step.id,\n kind: \"dowhile\",\n status: \"completed\",\n attempts: i,\n durationMs: Date.now() - startedAt,\n output: acc,\n };\n}\n","/**\n * Execute a `FnStep` — call the user-supplied function with `input` + `ctx`.\n * Wraps in `withRetry` if a retry policy is set (D237).\n *\n * Validates input/output via Zod when schemas are supplied. EC-4 / D229\n * pattern: empty/undefined input parses as `{}` only when schema is defined.\n *\n * @internal\n */\n\nimport type { FnStep, StepContext, StepResult } from \"../../types/workflow.js\";\nimport { WorkflowCompensateNotImplementedError } from \"../../types/workflow.js\";\nimport { WorkflowSuspendedSentinel } from \"./ctx.js\";\nimport { errToShape } from \"./error-shape.js\";\nimport { withRetry } from \"./retry-policy.js\";\n\nfunction failedFnResult(\n stepId: string,\n attempts: number,\n startedAt: number,\n err: unknown,\n): StepResult {\n return {\n stepId,\n kind: \"fn\",\n status: \"failed\",\n attempts,\n durationMs: Date.now() - startedAt,\n error: errToShape(err),\n };\n}\n\nfunction validate(schema: { parse: (v: unknown) => unknown } | undefined, value: unknown): unknown {\n if (schema === undefined) return undefined;\n schema.parse(value);\n return undefined;\n}\n\nasync function execWithRetry(\n step: FnStep,\n input: unknown,\n ctx: StepContext,\n): Promise<{ value: unknown; attempts: number }> {\n const exec = async (): Promise<unknown> => step.fn(input, ctx);\n if (step.retry !== undefined) return withRetry(exec, step.retry, ctx.signal);\n return { value: await exec(), attempts: 1 };\n}\n\nexport async function runFnStep(\n step: FnStep,\n input: unknown,\n ctx: StepContext,\n): Promise<StepResult> {\n const startedAt = Date.now();\n // D238: saga engine not implemented in v1 — surface intent loudly.\n if (step.compensate !== undefined) {\n return failedFnResult(\n step.id,\n 0,\n startedAt,\n new WorkflowCompensateNotImplementedError(step.id),\n );\n }\n try {\n validate(step.inputSchema, input);\n } catch (err) {\n return failedFnResult(step.id, 0, startedAt, err);\n }\n\n try {\n const { value, attempts } = await execWithRetry(step, input, ctx);\n try {\n validate(step.outputSchema, value);\n } catch (err) {\n return failedFnResult(step.id, attempts, startedAt, err);\n }\n return {\n stepId: step.id,\n kind: \"fn\",\n status: \"completed\",\n attempts,\n durationMs: Date.now() - startedAt,\n output: value,\n };\n } catch (err) {\n if (err instanceof WorkflowSuspendedSentinel) throw err;\n return failedFnResult(step.id, 1, startedAt, err);\n }\n}\n","/**\n * Async-aware counting semaphore (ADR D135).\n *\n * N-permit gate for cooperative concurrency control inside a single\n * Node process. Used by `Agent.batch` to bound parallel agent count\n * without pulling in `p-limit` or `p-queue` (~30 LoC in-house).\n *\n * Contract: `acquire()` returns a release function. Caller MUST call\n * release exactly once when done — typically in a `finally` block.\n * Release is idempotent (multiple calls are no-ops after the first)\n * for defense against caller bugs, but leaking the release function\n * permanently consumes one permit (EC-G — caller responsibility).\n *\n * @internal\n */\n\nimport { ConfigurationError } from \"../../errors.js\";\n\nexport interface AsyncSemaphore {\n /** Acquire a permit. Returns the release function (call once). */\n acquire(): Promise<() => void>;\n /** Permits currently held in flight. */\n inFlight(): number;\n /** Total: in-flight + queued waiters. */\n pending(): number;\n}\n\nexport function createSemaphore(permits: number): AsyncSemaphore {\n if (!Number.isInteger(permits) || permits < 1) {\n throw new ConfigurationError(\n `async-semaphore: permits must be a positive integer, got ${permits}`,\n { code: \"invalid_concurrency\" },\n );\n }\n let active = 0;\n const queue: Array<() => void> = [];\n\n function tryGrant(): void {\n if (active < permits && queue.length > 0) {\n const resolve = queue.shift();\n if (resolve !== undefined) {\n active += 1;\n resolve();\n }\n }\n }\n\n return {\n inFlight: () => active,\n pending: () => queue.length + active,\n async acquire() {\n await new Promise<void>((resolve) => {\n queue.push(resolve);\n tryGrant();\n });\n let released = false;\n return () => {\n if (released) return;\n released = true;\n active -= 1;\n tryGrant();\n };\n },\n };\n}\n","/**\n * Execute a `ForeachStep` — map a step over the output of an upstream step.\n *\n * EC-7 absorbed: `iterableFrom` MUST reference a top-level step (one of\n * `prevStepResults`). Inner steps from inside `.parallel` / `.branch` /\n * `.foreach` are not reachable.\n *\n * @internal\n */\n\nimport type {\n ForeachStep,\n StepContext,\n StepResult,\n WorkflowOptions,\n} from \"../../types/workflow.js\";\nimport { createSemaphore } from \"../runtime/async-semaphore.js\";\nimport { errToShape } from \"./error-shape.js\";\nimport type { DispatchFn } from \"./step-parallel.js\";\n\nexport async function runForeachStep(\n step: ForeachStep,\n _input: unknown,\n ctx: StepContext,\n options: WorkflowOptions,\n prevStepResults: ReadonlyArray<StepResult>,\n dispatch: DispatchFn,\n): Promise<StepResult> {\n const startedAt = Date.now();\n\n // EC-7: top-level step lookup only.\n const sourceResult = prevStepResults.find((r) => r.stepId === step.iterableFrom);\n if (sourceResult === undefined) {\n return {\n stepId: step.id,\n kind: \"foreach\",\n status: \"failed\",\n attempts: 0,\n durationMs: Date.now() - startedAt,\n error: errToShape(\n new Error(\n `foreach.iterableFrom \"${step.iterableFrom}\" not found in top-level steps. ` +\n `It must reference an earlier top-level step ID — nested step IDs inside ` +\n `parallel/branch/foreach blocks are not visible here.`,\n ),\n ),\n };\n }\n\n const items = sourceResult.output;\n if (!Array.isArray(items)) {\n return {\n stepId: step.id,\n kind: \"foreach\",\n status: \"failed\",\n attempts: 0,\n durationMs: Date.now() - startedAt,\n error: errToShape(\n new Error(\n `foreach.iterableFrom \"${step.iterableFrom}\" output must be Array, got ${typeof items}.`,\n ),\n ),\n };\n }\n\n if (items.length === 0) {\n return {\n stepId: step.id,\n kind: \"foreach\",\n status: \"completed\",\n attempts: 1,\n durationMs: Date.now() - startedAt,\n output: [],\n };\n }\n\n const concurrency = step.concurrency ?? 4;\n const sem = createSemaphore(Math.max(1, Math.min(concurrency, items.length)));\n const failures: Error[] = [];\n const outputs: unknown[] = new Array(items.length);\n\n await Promise.all(\n items.map(async (item, idx) => {\n const release = await sem.acquire();\n try {\n const r = await dispatch(step.step, item, ctx, options, prevStepResults);\n if (r.status === \"failed\") {\n failures.push(new Error(`foreach item ${idx} failed: ${r.error?.message ?? \"unknown\"}`));\n } else {\n outputs[idx] = r.output;\n }\n } finally {\n release();\n }\n }),\n );\n\n if (failures.length > 0) {\n return {\n stepId: step.id,\n kind: \"foreach\",\n status: \"failed\",\n attempts: 1,\n durationMs: Date.now() - startedAt,\n error: errToShape(\n new AggregateError(failures, `foreach \"${step.id}\" had ${failures.length} failure(s)`),\n ),\n };\n }\n\n return {\n stepId: step.id,\n kind: \"foreach\",\n status: \"completed\",\n attempts: 1,\n durationMs: Date.now() - startedAt,\n output: outputs,\n };\n}\n","/**\n * Execute a `ParallelStep` — run N branches concurrently.\n *\n * - `errorPolicy: \"fail-fast\"` (default): first branch error aborts the rest\n * via a derived AbortSignal; `WorkflowParallelError` aggregates failures.\n * - `errorPolicy: \"collect\"`: all branches complete; output is array of\n * `{ ok: true, value } | { ok: false, error }`.\n *\n * Concurrency: bounded by `step.concurrency ?? branches.length` (D240). All\n * branches run inside the same `AsyncSemaphore`.\n *\n * EC-6 absorbed: empty `branches[]` returns `output: []` without error.\n *\n * @internal\n */\n\nimport type {\n ParallelStep,\n Step,\n StepContext,\n StepResult,\n WorkflowOptions,\n} from \"../../types/workflow.js\";\nimport { WorkflowParallelError } from \"../../types/workflow.js\";\nimport { createSemaphore } from \"../runtime/async-semaphore.js\";\nimport { errToShape } from \"./error-shape.js\";\n\nexport type DispatchFn = (\n step: Step,\n input: unknown,\n ctx: StepContext,\n options: WorkflowOptions,\n prevStepResults: ReadonlyArray<StepResult>,\n) => Promise<StepResult>;\n\nexport async function runParallelStep(\n step: ParallelStep,\n input: unknown,\n ctx: StepContext,\n options: WorkflowOptions,\n _prevStepResults: ReadonlyArray<StepResult>,\n dispatch: DispatchFn,\n): Promise<StepResult> {\n const startedAt = Date.now();\n const policy = step.errorPolicy ?? \"fail-fast\";\n const branchCount = step.branches.length;\n\n // EC-6: empty branches → empty output, no error.\n if (branchCount === 0) {\n return {\n stepId: step.id,\n kind: \"parallel\",\n status: \"completed\",\n attempts: 1,\n durationMs: Date.now() - startedAt,\n output: [],\n };\n }\n\n const concurrency = step.concurrency ?? branchCount;\n const sem = createSemaphore(Math.max(1, Math.min(concurrency, branchCount)));\n\n // Derived signal for fail-fast: aborts on first branch failure.\n const failFastCtrl = policy === \"fail-fast\" ? new AbortController() : undefined;\n const branchSignal =\n policy === \"fail-fast\" ? mergeSignals(ctx.signal, failFastCtrl!.signal) : ctx.signal;\n\n // Gate each branch through the semaphore — acquire BEFORE running so the\n // permit cap is honored. (Eager-start would defeat concurrency limits.)\n const semBranchPromises = step.branches.map(async (branch, branchIdx) => {\n const release = await sem.acquire();\n try {\n return await runBranch(\n branch,\n input,\n { ...ctx, signal: branchSignal },\n options,\n dispatch,\n branchIdx,\n );\n } finally {\n release();\n }\n });\n\n if (policy === \"fail-fast\") {\n try {\n const outputs = await Promise.all(semBranchPromises);\n return {\n stepId: step.id,\n kind: \"parallel\",\n status: \"completed\",\n attempts: 1,\n durationMs: Date.now() - startedAt,\n output: outputs,\n };\n } catch (err) {\n failFastCtrl?.abort(err);\n // Collect any settled rejections so the aggregate has all errors.\n const settled = await Promise.allSettled(semBranchPromises);\n const errors = settled\n .filter((s): s is PromiseRejectedResult => s.status === \"rejected\")\n .map((s) => (s.reason instanceof Error ? s.reason : new Error(String(s.reason))));\n return {\n stepId: step.id,\n kind: \"parallel\",\n status: \"failed\",\n attempts: 1,\n durationMs: Date.now() - startedAt,\n error: errToShape(new WorkflowParallelError(errors, step.id)),\n output: undefined,\n };\n }\n }\n\n // collect mode\n const settled = await Promise.allSettled(semBranchPromises);\n const outputs = settled.map((s) =>\n s.status === \"fulfilled\"\n ? { ok: true as const, value: s.value }\n : { ok: false as const, error: errToShape(s.reason) },\n );\n return {\n stepId: step.id,\n kind: \"parallel\",\n status: \"completed\",\n attempts: 1,\n durationMs: Date.now() - startedAt,\n output: outputs,\n };\n}\n\nasync function runBranch(\n branch: ReadonlyArray<Step>,\n input: unknown,\n ctx: StepContext,\n options: WorkflowOptions,\n dispatch: DispatchFn,\n branchIdx: number,\n): Promise<unknown> {\n let acc: unknown = input;\n for (const inner of branch) {\n const r = await dispatch(inner, acc, ctx, options, []);\n if (r.status === \"failed\") {\n throw new Error(\n `parallel branch ${branchIdx} step \"${inner.id}\" failed: ${r.error?.message ?? \"unknown\"}`,\n );\n }\n acc = r.output;\n }\n return acc;\n}\n\nfunction mergeSignals(a: AbortSignal, b: AbortSignal): AbortSignal {\n if (a.aborted) return a;\n if (b.aborted) return b;\n const ctrl = new AbortController();\n const onAbortA = (): void => ctrl.abort(a.reason);\n const onAbortB = (): void => ctrl.abort(b.reason);\n a.addEventListener(\"abort\", onAbortA, { once: true });\n b.addEventListener(\"abort\", onAbortB, { once: true });\n return ctrl.signal;\n}\n","/**\n * Execute a `SleepStep` — pause for `durationMs`. Aborts mid-sleep\n * when the signal fires (D245).\n *\n * @internal\n */\n\nimport type { SleepStep, StepContext, StepResult } from \"../../types/workflow.js\";\nimport { errToShape } from \"./error-shape.js\";\nimport { abortableSleep } from \"./retry-policy.js\";\n\nexport async function runSleepStep(\n step: SleepStep,\n input: unknown,\n ctx: StepContext,\n): Promise<StepResult> {\n const startedAt = Date.now();\n try {\n await abortableSleep(step.durationMs, ctx.signal);\n return {\n stepId: step.id,\n kind: \"sleep\",\n status: \"completed\",\n attempts: 1,\n durationMs: Date.now() - startedAt,\n output: input, // sleep is a pass-through\n };\n } catch (err) {\n return {\n stepId: step.id,\n kind: \"sleep\",\n status: \"failed\",\n attempts: 1,\n durationMs: Date.now() - startedAt,\n error: errToShape(err),\n };\n }\n}\n","/**\n * Shared OTel tracer loader (extracted to eliminate cross-module clones —\n * was previously inlined in cache/, workflow/, eval/, handoff/ telemetry\n * modules). Lazy-loads `@opentelemetry/api` via `createRequire`; users\n * without OTel installed pay zero cost.\n *\n * @internal\n */\n\nimport { createRequire } from \"node:module\";\n\nexport interface SpanLike {\n setAttribute(key: string, value: string | number | boolean): SpanLike;\n end(): void;\n}\n\nexport const noopSpan: SpanLike = {\n setAttribute: () => noopSpan,\n end: () => undefined,\n};\n\nexport interface TracerLike {\n startSpan(\n name: string,\n options?: { attributes?: Record<string, string | number | boolean> },\n ): SpanLike;\n}\n\ninterface CacheEntry {\n tracer: TracerLike | null;\n}\n\nconst tracerCache = new Map<string, CacheEntry>();\n\nexport function getTracer(name: string, version = \"1.0.0\"): TracerLike | undefined {\n const cached = tracerCache.get(name);\n if (cached !== undefined) return cached.tracer ?? undefined;\n try {\n const r = createRequire(import.meta.url);\n const otel = r(\"@opentelemetry/api\") as {\n trace?: { getTracer: (n: string, v?: string) => TracerLike };\n };\n if (otel.trace?.getTracer === undefined) {\n tracerCache.set(name, { tracer: null });\n return undefined;\n }\n const tracer = otel.trace.getTracer(name, version);\n tracerCache.set(name, { tracer });\n return tracer;\n } catch {\n tracerCache.set(name, { tracer: null });\n return undefined;\n }\n}\n\nexport function resetTracerCacheForTests(): void {\n tracerCache.clear();\n}\n","/**\n * OTel telemetry for workflows (ADR D241).\n *\n * Spans:\n * - `workflow.run` — root span per `Workflow.run` invocation\n * - `workflow.step.<id>` — child span per step (retry attempts share the kind)\n *\n * Attributes:\n * - `workflow.name`, `workflow.run_id`, `step.kind`, `step.status`, `step.attempts`\n *\n * @internal\n */\n\nimport {\n getTracer,\n noopSpan,\n resetTracerCacheForTests,\n type SpanLike,\n} from \"../observability/tracer-loader.js\";\n\nconst TRACER_NAME = \"@theokit/sdk/workflow\";\n\nexport function startWorkflowRunSpan(info: { workflowName: string; runId: string }): SpanLike {\n const tracer = getTracer(TRACER_NAME);\n if (tracer === undefined) return noopSpan;\n return tracer.startSpan(\"workflow.run\", {\n attributes: {\n \"workflow.name\": info.workflowName,\n \"workflow.run_id\": info.runId,\n },\n });\n}\n\nexport function startWorkflowStepSpan(info: {\n stepId: string;\n kind: string;\n attempt: number;\n}): SpanLike {\n const tracer = getTracer(TRACER_NAME);\n if (tracer === undefined) return noopSpan;\n return tracer.startSpan(`workflow.step.${info.stepId}`, {\n attributes: {\n \"step.id\": info.stepId,\n \"step.kind\": info.kind,\n \"step.attempt\": info.attempt,\n },\n });\n}\n\n/** Test seam — reset tracer cache so a fresh require attempt happens. */\nexport function __resetTelemetryCacheForTests(): void {\n resetTracerCacheForTests();\n}\n","/**\n * Workflow executor (ADRs D230-D248).\n *\n * Walks `steps[]` sequentially, dispatching to per-kind handlers. Handles\n * suspend (sentinel pattern; D236), single-flight (D242), abort signal\n * boundaries (D245), and snapshot persistence opt-in (D235).\n *\n * @internal\n */\n\nimport {\n type Step,\n type StepContext,\n type StepResult,\n type WorkflowOptions,\n type WorkflowResumeOptions,\n WorkflowResumeStepNotFoundError,\n type WorkflowRun,\n type WorkflowRunOptions,\n type WorkflowSnapshot,\n WorkflowSnapshotNotFoundError,\n} from \"../../types/workflow.js\";\nimport { combineSignals, makeStepContext, WorkflowSuspendedSentinel } from \"./ctx.js\";\nimport { errToShape } from \"./error-shape.js\";\nimport { mintRunId } from \"./run-id.js\";\nimport { acquireSingleFlight } from \"./single-flight.js\";\nimport { getSnapshotStoreFor } from \"./snapshot-store.js\";\nimport { runAgentStep } from \"./step-agent.js\";\nimport { runBranchStep } from \"./step-branch.js\";\nimport { runDowhileStep } from \"./step-dowhile.js\";\nimport { runFnStep } from \"./step-fn.js\";\nimport { runForeachStep } from \"./step-foreach.js\";\nimport { runParallelStep } from \"./step-parallel.js\";\nimport { runSleepStep } from \"./step-sleep.js\";\nimport { startWorkflowRunSpan, startWorkflowStepSpan } from \"./telemetry.js\";\n\ninterface SuspendOutcome<T> {\n kind: \"suspended\" | \"failed\";\n run: WorkflowRun<T>;\n}\n\nasync function handleSuspend<T>(\n err: WorkflowSuspendedSentinel,\n ctx: {\n runId: string;\n name: string;\n step: Step;\n stepResults: StepResult[];\n acc: unknown;\n options: WorkflowOptions;\n startedAt: number;\n stepSpan: ReturnType<typeof startWorkflowStepSpan>;\n },\n): Promise<SuspendOutcome<T>> {\n try {\n await saveSnapshot({\n runId: ctx.runId,\n workflowName: ctx.options.name,\n currentStepId: ctx.step.id,\n suspendedPayload: err.payload,\n stepResults: ctx.stepResults,\n accumulatedInput: ctx.acc,\n options: ctx.options,\n });\n } catch (snapErr) {\n ctx.stepSpan.setAttribute(\"step.status\", \"failed\");\n ctx.stepSpan.end();\n return {\n kind: \"failed\",\n run: assembleRun<T>({\n runId: ctx.runId,\n name: ctx.name,\n status: \"failed\",\n stepResults: ctx.stepResults,\n startedAt: ctx.startedAt,\n error: errToShape(snapErr),\n }),\n };\n }\n ctx.stepSpan.setAttribute(\"step.status\", \"suspended\");\n ctx.stepSpan.end();\n return {\n kind: \"suspended\",\n run: assembleRun<T>({\n runId: ctx.runId,\n name: ctx.name,\n status: \"suspended\",\n stepResults: [\n ...ctx.stepResults,\n {\n stepId: ctx.step.id,\n kind: ctx.step.kind,\n status: \"suspended\",\n attempts: 1,\n durationMs: 0,\n output: undefined,\n },\n ],\n startedAt: ctx.startedAt,\n }),\n };\n}\n\nasync function runOneStep<T>(args: {\n step: Step;\n acc: unknown;\n ctx: StepContext;\n options: WorkflowOptions;\n stepResults: StepResult[];\n runId: string;\n name: string;\n startedAt: number;\n}): Promise<{ kind: \"ok\"; result: StepResult } | { kind: \"terminal\"; run: WorkflowRun<T> }> {\n const stepSpan = startWorkflowStepSpan({\n stepId: args.step.id,\n kind: args.step.kind,\n attempt: 1,\n });\n let result: StepResult;\n try {\n result = await dispatchStep(args.step, args.acc, args.ctx, args.options, args.stepResults);\n } catch (err) {\n if (err instanceof WorkflowSuspendedSentinel) {\n const outcome = await handleSuspend<T>(err, { ...args, stepSpan });\n return { kind: \"terminal\", run: outcome.run };\n }\n result = {\n stepId: args.step.id,\n kind: args.step.kind,\n status: \"failed\",\n attempts: 1,\n durationMs: 0,\n error: errToShape(err),\n };\n }\n stepSpan.setAttribute(\"step.status\", result.status);\n stepSpan.setAttribute(\"step.attempts\", result.attempts);\n stepSpan.end();\n return { kind: \"ok\", result };\n}\n\nfunction abortRun<T>(\n name: string,\n runId: string,\n startedAt: number,\n stepResults: StepResult[],\n signal: AbortSignal,\n): WorkflowRun<T> {\n return assembleRun<T>({\n runId,\n name,\n status: \"cancelled\",\n stepResults,\n startedAt,\n error: { name: \"AbortError\", message: String(signal.reason ?? \"Aborted\") },\n });\n}\n\ninterface LoopParams {\n options: WorkflowOptions;\n steps: ReadonlyArray<Step>;\n input: unknown;\n ctx: StepContext;\n runId: string;\n startedAt: number;\n signal: AbortSignal;\n}\n\nasync function runStepsLoop<TO>(params: LoopParams): Promise<WorkflowRun<TO>> {\n const { options, steps, ctx, runId, startedAt, signal } = params;\n const stepResults: StepResult[] = [];\n let acc: unknown = params.input;\n for (const step of steps) {\n if (signal.aborted) return abortRun<TO>(options.name, runId, startedAt, stepResults, signal);\n const outcome = await runOneStep<TO>({\n step,\n acc,\n ctx,\n options,\n stepResults,\n runId,\n name: options.name,\n startedAt,\n });\n if (outcome.kind === \"terminal\") return outcome.run;\n stepResults.push(outcome.result);\n if (outcome.result.status === \"failed\") {\n return assembleRun<TO>({\n runId,\n name: options.name,\n status: \"failed\",\n stepResults,\n startedAt,\n error: outcome.result.error,\n });\n }\n acc = outcome.result.output;\n }\n return assembleRun<TO>({\n runId,\n name: options.name,\n status: \"completed\",\n output: acc as TO,\n stepResults,\n startedAt,\n });\n}\n\nexport async function executeWorkflow<TInput, TOutput>(\n options: WorkflowOptions,\n steps: ReadonlyArray<Step>,\n input: TInput,\n runOpts?: WorkflowRunOptions,\n): Promise<WorkflowRun<TOutput>> {\n const runId = runOpts?.runId ?? mintRunId();\n const workflowId = options.workflowId ?? `wf-anon`;\n const flight = acquireSingleFlight(workflowId, runId, options.name);\n const startedAt = Date.now();\n const signal = combineSignals(runOpts?.signal, flight.signal);\n const runSpan = startWorkflowRunSpan({ workflowName: options.name, runId });\n\n if (signal.aborted) {\n flight.release();\n runSpan.setAttribute(\"workflow.status\", \"cancelled\");\n runSpan.end();\n return abortRun<TOutput>(options.name, runId, startedAt, [], signal);\n }\n\n const ctx: StepContext = makeStepContext(runId, signal);\n try {\n return await runStepsLoop<TOutput>({\n options,\n steps,\n input,\n ctx,\n runId,\n startedAt,\n signal,\n });\n } finally {\n runSpan.end();\n flight.release();\n }\n}\n\n/**\n * Dispatch single step to the right handler. Exhaustive over `step.kind`.\n */\nexport async function dispatchStep(\n step: Step,\n input: unknown,\n ctx: StepContext,\n options: WorkflowOptions,\n prevStepResults: ReadonlyArray<StepResult>,\n): Promise<StepResult> {\n switch (step.kind) {\n case \"fn\":\n return runFnStep(step, input, ctx);\n case \"agent\":\n return runAgentStep(step, input, ctx);\n case \"parallel\":\n return runParallelStep(step, input, ctx, options, prevStepResults, dispatchStep);\n case \"branch\":\n return runBranchStep(step, input, ctx, options, prevStepResults, dispatchStep);\n case \"foreach\":\n return runForeachStep(step, input, ctx, options, prevStepResults, dispatchStep);\n case \"dowhile\":\n return runDowhileStep(step, input, ctx, options, prevStepResults, dispatchStep);\n case \"sleep\":\n return runSleepStep(step, input, ctx);\n case \"suspend\":\n // Standalone suspend: throw sentinel so executor catches.\n throw new WorkflowSuspendedSentinel(undefined);\n default: {\n const _exhaustive: never = step;\n throw new Error(`Unknown step kind: ${(_exhaustive as Step).kind}`);\n }\n }\n}\n\ninterface AssembleParams<TO> {\n runId: string;\n name: string;\n status: WorkflowRun[\"status\"];\n stepResults: ReadonlyArray<StepResult>;\n startedAt: number;\n output?: TO;\n error?: { name: string; message: string };\n}\n\nfunction assembleRun<TO>(params: AssembleParams<TO>): WorkflowRun<TO> {\n const endedAt = Date.now();\n return {\n id: params.runId,\n name: params.name,\n status: params.status,\n startedAt: params.startedAt,\n endedAt,\n stepResults: params.stepResults,\n ...(params.output !== undefined ? { output: params.output } : {}),\n ...(params.error !== undefined ? { error: params.error } : {}),\n };\n}\n\ninterface SnapshotParams {\n runId: string;\n workflowName: string;\n currentStepId: string;\n suspendedPayload?: unknown;\n stepResults: ReadonlyArray<StepResult>;\n accumulatedInput: unknown;\n options: WorkflowOptions;\n}\n\nasync function saveSnapshot(p: SnapshotParams): Promise<void> {\n const snapshot: WorkflowSnapshot = {\n _schemaVersion: 1,\n runId: p.runId,\n workflowName: p.workflowName,\n currentStepId: p.currentStepId,\n suspendedPayload: p.suspendedPayload,\n stepResults: p.stepResults,\n accumulatedInput: p.accumulatedInput,\n suspendedAt: Date.now(),\n };\n const store = getSnapshotStoreFor(p.options);\n await store.save(snapshot);\n}\n\n/* ─── Resume ─── */\n\nexport async function resumeWorkflow<TO>(opts: WorkflowResumeOptions): Promise<WorkflowRun<TO>> {\n // We need access to the workflow's internal options/steps. The public\n // resume API hands us a `workflow` reference exposing `.run` only — for\n // v1 we accept the user re-running the same workflow with the snapshot's\n // accumulated input + payload merged. Full resume-from-step support\n // would require exposing `__steps` and `__options`; v1 ships a simpler\n // \"re-run from input\" semantics gated by snapshot lookup.\n const wfInternal = opts.workflow as {\n __options?: WorkflowOptions;\n __steps?: ReadonlyArray<Step>;\n run: (input: unknown, runOpts?: WorkflowRunOptions) => Promise<WorkflowRun<TO>>;\n };\n const options = wfInternal.__options;\n const steps = wfInternal.__steps;\n if (options === undefined || steps === undefined) {\n throw new Error(\"Workflow.resume requires an instance from Workflow.create().commit()\");\n }\n const store = getSnapshotStoreFor(options);\n const snapshot = await store.load(opts.runId);\n if (snapshot === undefined) {\n throw new WorkflowSnapshotNotFoundError(opts.runId);\n }\n // EC-8: verify the currentStepId exists in the supplied workflow.\n const stepIdx = steps.findIndex((s) => s.id === snapshot.currentStepId);\n if (stepIdx < 0) {\n throw new WorkflowResumeStepNotFoundError(snapshot.currentStepId, snapshot.workflowName);\n }\n\n // Validate payload if the suspend step declared a schema.\n const suspendStep = steps[stepIdx];\n if (\n suspendStep !== undefined &&\n suspendStep.kind === \"suspend\" &&\n suspendStep.payloadSchema !== undefined\n ) {\n suspendStep.payloadSchema.parse(opts.payload);\n }\n\n // For v1: continue from stepIdx + 1 with `payload` (if any) as the new\n // accumulated input. This is intentionally simpler than full state\n // restoration; the snapshot's `accumulatedInput` is preserved for\n // observability but the resume input is determined by the caller's\n // payload (or the snapshot's accumulator if payload is undefined).\n const resumeInput = opts.payload !== undefined ? opts.payload : snapshot.accumulatedInput;\n const remainingSteps = steps.slice(stepIdx + 1);\n\n // Drop snapshot once we begin (single-shot semantics).\n await store.delete(opts.runId);\n\n return executeWorkflow<unknown, TO>(options, remainingSteps, resumeInput, {\n signal: opts.signal,\n runId: opts.runId,\n });\n}\n","/**\n * Public type contract for the Task observability registry (ADRs D361-D374).\n *\n * Tasks are an opt-in observability layer over async work in the SDK\n * (`Agent.send`, `Agent.batch`, `Workflow.run`, `Cron` fires). They have\n * a closed 5-state lifecycle (D362), discriminated events (D366), and a\n * pluggable store (D364). The `Task` facade in `task.ts` is the public\n * surface; consumers import these types from `@theokit/sdk`.\n *\n * @public\n */\n\n/**\n * Closed enum of the 5 lifecycle states (D362).\n *\n * Transitions are acyclic:\n * queued → running → (finished | error | cancelled)\n * queued → cancelled (direct, no run started)\n */\nexport type TaskState = \"queued\" | \"running\" | \"finished\" | \"error\" | \"cancelled\";\n\n/** Discriminator of the runtime that produced a task (D374). */\nexport type TaskKind = \"run\" | \"batch\" | \"workflow\" | \"cron\" | \"custom\";\n\n/** Discriminated union of task lifecycle events (D366). */\nexport type TaskEvent =\n | {\n readonly type: \"submitted\";\n readonly taskId: string;\n readonly kind: TaskKind;\n readonly submittedAt: number;\n readonly meta?: Record<string, unknown>;\n /** D372 — flag set on the first yielded event when the ring buffer was at cap. */\n readonly truncated?: boolean;\n }\n | { readonly type: \"started\"; readonly taskId: string; readonly startedAt: number }\n | {\n readonly type: \"progress\";\n readonly taskId: string;\n readonly at: number;\n readonly payload: unknown;\n }\n | {\n readonly type: \"finished\";\n readonly taskId: string;\n readonly finishedAt: number;\n readonly result: unknown;\n }\n | {\n readonly type: \"errored\";\n readonly taskId: string;\n readonly erroredAt: number;\n readonly error: { readonly code: string; readonly message: string };\n }\n | {\n readonly type: \"cancelled\";\n readonly taskId: string;\n readonly cancelledAt: number;\n readonly reason?: string;\n };\n\n/** Public read-only view of a task entry in the registry. */\nexport interface TaskHandle {\n readonly id: string;\n readonly kind: TaskKind;\n readonly state: TaskState;\n readonly submittedAt: number;\n readonly startedAt?: number;\n readonly finishedAt?: number;\n readonly cancelledAt?: number;\n readonly erroredAt?: number;\n readonly result?: unknown;\n readonly error?: { readonly code: string; readonly message: string };\n readonly meta?: Record<string, unknown>;\n /**\n * EC-7 — cross-process best-effort cancel flag. Set by CLI\n * `theokit tasks cancel` via JsonFileTaskStore. The owning process\n * polls at checkpoints and honors via AbortController. Always\n * `undefined` for in-process cancel paths (which go directly through\n * AbortController).\n */\n readonly cancelRequested?: boolean;\n}\n\n/** Query filter for `Task.list`. */\nexport interface TaskFilter {\n readonly state?: TaskState | readonly TaskState[];\n readonly kind?: TaskKind | readonly TaskKind[];\n readonly submittedAfter?: number;\n readonly submittedBefore?: number;\n /** Defaults to 100. JsonFileTaskStore hard-caps loaded entries at 256 (D364). */\n readonly limit?: number;\n}\n\n/** Options for `Task.submit`. */\nexport interface TaskSubmitOptions {\n /**\n * Optional user-supplied ID. Must match grammar `^[a-z0-9][a-z0-9_-]*$`\n * and MUST NOT start with the reserved prefixes `wf-` / `b-` / `cron-`\n * (D368, EC-5). When omitted, `crypto.randomUUID()` is used.\n */\n readonly id?: string;\n readonly meta?: Record<string, unknown>;\n /**\n * Optional caller-provided AbortSignal. If already aborted at submit\n * time, the registry short-circuits to `cancelled` without acquiring\n * a semaphore slot (EC-4).\n */\n readonly signal?: AbortSignal;\n}\n\n/** Options shape for `TaskStore` factory (D364). */\nexport type TaskStoreOptions =\n | { readonly backend: \"memory\" }\n | { readonly backend: \"json\"; readonly dir: string };\n\n/** Result of `Task.cancel` (D365 — idempotent). */\nexport interface TaskCancelResult {\n readonly cancelled: boolean;\n readonly alreadyTerminal: boolean;\n}\n\n/**\n * Grammar for user-supplied task IDs (D368).\n * `crypto.randomUUID()` outputs do NOT match this (UUIDs have dashes\n * AND uppercase letters in their canonical form on some Node versions),\n * but the registry normalizes auto-generated IDs to lowercase before\n * insertion, so they pass the same regex.\n */\nconst TASK_ID_GRAMMAR = /^[a-z0-9][a-z0-9_-]*$/;\n\n/** Reserved prefixes for adapter-generated IDs (D368, EC-5). */\nconst RESERVED_PREFIXES = [\"wf-\", \"b-\", \"cron-\"] as const;\n\n/**\n * Validates a task ID against the public grammar + reserved prefixes.\n * Throws `InvalidTaskIdError` from `../errors.js` on rejection.\n *\n * Adapter callers (workflow/batch/cron) MUST set `allowReserved: true`\n * to register their own IDs; user-facing surfaces (`Task.submit`,\n * `agent.send({ task: { id } })`) leave it false.\n */\nexport function isValidTaskId(id: string, allowReserved: boolean): boolean {\n if (!TASK_ID_GRAMMAR.test(id)) return false;\n if (allowReserved) return true;\n for (const prefix of RESERVED_PREFIXES) {\n if (id.startsWith(prefix)) return false;\n }\n return true;\n}\n\n/** Re-exported for adapter implementations + tests. */\nexport const TASK_RESERVED_PREFIXES: readonly string[] = RESERVED_PREFIXES;\n","/**\n * Bounded FIFO ring buffer for late-attach replay (ADR D372).\n *\n * Push always succeeds; when the buffer is at capacity the oldest\n * entry is dropped and the `truncated` flag flips to `true`. Drain\n * returns a snapshot + the current truncated flag.\n *\n * @internal\n */\n\nexport class RingBuffer<T> {\n private readonly buf: T[] = [];\n private truncated = false;\n\n constructor(private readonly cap: number) {\n if (!Number.isInteger(cap) || cap < 1) {\n throw new Error(`RingBuffer capacity must be a positive integer, got ${cap}`);\n }\n }\n\n push(item: T): void {\n if (this.buf.length >= this.cap) {\n this.buf.shift();\n this.truncated = true;\n }\n this.buf.push(item);\n }\n\n drain(): { readonly items: readonly T[]; readonly truncated: boolean } {\n return { items: this.buf.slice(), truncated: this.truncated };\n }\n\n size(): number {\n return this.buf.length;\n }\n\n wasTruncated(): boolean {\n return this.truncated;\n }\n}\n","/**\n * `TaskStore` interface + 2 implementations (ADR D364).\n *\n * - `InMemoryTaskStore` — default, transient, single-process.\n * - `JsonFileTaskStore` — opt-in, one JSON file per task under a\n * dedicated dir; single-process invariant (EC-15 documented).\n *\n * Edge cases absorbed:\n * - EC-1: constructor auto-creates dir (mkdirSync recursive idempotent).\n * - EC-2: every method validates the task id against the public\n * grammar (D368) BEFORE doing any path I/O — path-traversal defense.\n * - EC-6: `list()` returns `[]` on ENOENT (fresh install path).\n * - EC-8: `list()` skips `.tmp.*` orphan files left by interrupted\n * atomic writes.\n * - EC-14 (DOCUMENT): `list()` JSDoc documents the 256-row hard cap\n * and the `submittedBefore` paging idiom.\n * - EC-15 (DOCUMENT): `JsonFileTaskStore` JSDoc documents the\n * single-process invariant; v0.2 SQLite covers cross-process.\n *\n * @internal\n */\n\nimport { mkdirSync, readdirSync } from \"node:fs\";\nimport { readFile, unlink } from \"node:fs/promises\";\nimport { join } from \"node:path\";\n\nimport { InvalidTaskIdError } from \"../../errors.js\";\nimport {\n isValidTaskId,\n type TaskFilter,\n type TaskHandle,\n type TaskState,\n type TaskStoreOptions,\n} from \"../../types/task.js\";\nimport { atomicWriteText } from \"../persistence/atomic-write.js\";\n\nconst JSON_LOAD_CAP = 256;\nconst DEFAULT_LIST_LIMIT = 100;\n\n/** Storage interface used by `TaskRegistry`. */\nexport interface TaskStore {\n insert(handle: TaskHandle): Promise<void>;\n update(id: string, mutate: (h: TaskHandle) => TaskHandle): Promise<TaskHandle | undefined>;\n get(id: string): Promise<TaskHandle | undefined>;\n /**\n * Returns at most `filter.limit ?? 100` matching handles. JsonFile\n * backend hard-caps loaded entries at 256 — callers needing larger\n * pages must use `submittedBefore` to walk the timeline.\n */\n list(filter: TaskFilter): Promise<TaskHandle[]>;\n delete(id: string): Promise<boolean>;\n /** Removes terminal handles whose terminal-timestamp is older than `epochMs`. */\n evictTerminalOlderThan(epochMs: number): Promise<number>;\n}\n\nfunction assertValidIdForStore(id: string): void {\n if (!isValidTaskId(id, /* allowReserved */ true)) {\n throw new InvalidTaskIdError(`store rejects invalid task id: ${id}`, id);\n }\n}\n\nfunction terminalTimestamp(h: TaskHandle): number | undefined {\n if (h.state === \"finished\") return h.finishedAt;\n if (h.state === \"error\") return h.erroredAt;\n if (h.state === \"cancelled\") return h.cancelledAt;\n return undefined;\n}\n\nfunction isTerminal(state: TaskState): boolean {\n return state === \"finished\" || state === \"error\" || state === \"cancelled\";\n}\n\nfunction matchesState(h: TaskHandle, filter: TaskFilter): boolean {\n if (filter.state === undefined) return true;\n const states = Array.isArray(filter.state) ? filter.state : [filter.state];\n return states.includes(h.state);\n}\nfunction matchesKind(h: TaskHandle, filter: TaskFilter): boolean {\n if (filter.kind === undefined) return true;\n const kinds = Array.isArray(filter.kind) ? filter.kind : [filter.kind];\n return kinds.includes(h.kind);\n}\nfunction matchesTime(h: TaskHandle, filter: TaskFilter): boolean {\n if (filter.submittedAfter !== undefined && h.submittedAt <= filter.submittedAfter) return false;\n if (filter.submittedBefore !== undefined && h.submittedAt >= filter.submittedBefore) return false;\n return true;\n}\nfunction matchesFilter(h: TaskHandle, filter: TaskFilter): boolean {\n return matchesState(h, filter) && matchesKind(h, filter) && matchesTime(h, filter);\n}\n\nfunction applyFilter(values: Iterable<TaskHandle>, filter: TaskFilter): TaskHandle[] {\n const limit = filter.limit ?? DEFAULT_LIST_LIMIT;\n const out: TaskHandle[] = [];\n for (const h of values) {\n if (matchesFilter(h, filter)) {\n out.push(h);\n if (out.length >= limit) break;\n }\n }\n return out;\n}\n\n/* ─── InMemory ─── */\n\nexport class InMemoryTaskStore implements TaskStore {\n private readonly map = new Map<string, TaskHandle>();\n\n async insert(handle: TaskHandle): Promise<void> {\n assertValidIdForStore(handle.id);\n this.map.set(handle.id, handle);\n }\n\n async update(id: string, mutate: (h: TaskHandle) => TaskHandle): Promise<TaskHandle | undefined> {\n assertValidIdForStore(id);\n const existing = this.map.get(id);\n if (existing === undefined) return undefined;\n const next = mutate(existing);\n this.map.set(id, next);\n return next;\n }\n\n async get(id: string): Promise<TaskHandle | undefined> {\n assertValidIdForStore(id);\n return this.map.get(id);\n }\n\n async list(filter: TaskFilter): Promise<TaskHandle[]> {\n return applyFilter(this.map.values(), filter);\n }\n\n async delete(id: string): Promise<boolean> {\n assertValidIdForStore(id);\n return this.map.delete(id);\n }\n\n async evictTerminalOlderThan(epochMs: number): Promise<number> {\n let count = 0;\n for (const [id, h] of this.map.entries()) {\n if (!isTerminal(h.state)) continue;\n const ts = terminalTimestamp(h);\n if (ts !== undefined && ts < epochMs) {\n this.map.delete(id);\n count++;\n }\n }\n return count;\n }\n}\n\n/* ─── JsonFile (opt-in) ───\n *\n * IMPORTANT (EC-15): `JsonFileTaskStore` is **single-process**.\n * Concurrent writers from multiple Node processes against the same\n * directory may corrupt entries (atomic-write protects per-file, but\n * the `list()` scan + `update()` read-modify-write cycle is not\n * serialised across processes). Use only when the `TaskRegistry`\n * runs in exactly one process. v0.2 will add a SQLite backend with\n * the same interface for cross-process scenarios (D364 + D61).\n */\nexport class JsonFileTaskStore implements TaskStore {\n constructor(private readonly dir: string) {\n // EC-1: idempotent mkdir; ignore EEXIST.\n try {\n mkdirSync(dir, { recursive: true });\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code !== \"EEXIST\") throw err;\n }\n }\n\n private filePath(id: string): string {\n return join(this.dir, `${id}.json`);\n }\n\n async insert(handle: TaskHandle): Promise<void> {\n assertValidIdForStore(handle.id);\n await atomicWriteText(this.filePath(handle.id), JSON.stringify(handle));\n }\n\n async update(id: string, mutate: (h: TaskHandle) => TaskHandle): Promise<TaskHandle | undefined> {\n assertValidIdForStore(id);\n const existing = await this.get(id);\n if (existing === undefined) return undefined;\n const next = mutate(existing);\n await atomicWriteText(this.filePath(id), JSON.stringify(next));\n return next;\n }\n\n async get(id: string): Promise<TaskHandle | undefined> {\n assertValidIdForStore(id);\n try {\n const raw = await readFile(this.filePath(id), \"utf8\");\n return JSON.parse(raw) as TaskHandle;\n } catch (err) {\n const code = (err as NodeJS.ErrnoException).code;\n if (code === \"ENOENT\") return undefined;\n // Corrupt JSON or other I/O error — log + degrade gracefully (D50/EC-7 cache pattern).\n process.stderr.write(`[task-store] failed to read ${id}: ${(err as Error).message}\\n`);\n return undefined;\n }\n }\n\n async list(filter: TaskFilter): Promise<TaskHandle[]> {\n let entries: string[];\n try {\n entries = readdirSync(this.dir);\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") return []; // EC-6\n throw err;\n }\n // EC-8: skip orphan .tmp files left by interrupted atomic writes.\n const candidates = entries\n .filter((name) => name.endsWith(\".json\") && !name.includes(\".tmp\"))\n .slice(0, JSON_LOAD_CAP);\n\n const loaded = await Promise.all(\n candidates.map(async (name) => {\n const id = name.slice(0, -\".json\".length);\n if (!isValidTaskId(id, true)) return undefined;\n return this.get(id);\n }),\n );\n const handles = loaded.filter((h): h is TaskHandle => h !== undefined);\n return applyFilter(handles, filter);\n }\n\n async delete(id: string): Promise<boolean> {\n assertValidIdForStore(id);\n try {\n await unlink(this.filePath(id));\n return true;\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") return false;\n throw err;\n }\n }\n\n async evictTerminalOlderThan(epochMs: number): Promise<number> {\n const handles = await this.list({ state: [\"finished\", \"error\", \"cancelled\"], limit: 256 });\n let count = 0;\n for (const h of handles) {\n const ts = terminalTimestamp(h);\n if (ts !== undefined && ts < epochMs) {\n if (await this.delete(h.id)) count++;\n }\n }\n return count;\n }\n}\n\n/** Factory used by `TaskRegistry.configure` (D364). */\nexport function getTaskStoreFor(options: TaskStoreOptions): TaskStore {\n if (options.backend === \"memory\") return new InMemoryTaskStore();\n return new JsonFileTaskStore(options.dir);\n}\n","/**\n * `subscribe(id)` — emits the per-task event stream (D372 ring buffer\n * + live tail). The returned AsyncIterable implements `return()` for\n * leak-free cleanup (EC-10).\n *\n * @internal\n */\n\nimport { TaskNotFoundError } from \"../../errors.js\";\nimport { isValidTaskId, type TaskEvent } from \"../../types/task.js\";\nimport type { RingBuffer } from \"./ring-buffer.js\";\n\nexport interface SubscribeDeps {\n getBuffer(id: string): RingBuffer<TaskEvent> | undefined;\n getOrCreateSubscriberSet(id: string): Set<(e: TaskEvent) => void>;\n removeSubscriber(id: string, cb: (e: TaskEvent) => void): void;\n}\n\nfunction isTerminalEvent(event: TaskEvent): boolean {\n return event.type === \"finished\" || event.type === \"errored\" || event.type === \"cancelled\";\n}\n\nfunction drainBuffered(buffer: RingBuffer<TaskEvent>): TaskEvent[] {\n const { items, truncated } = buffer.drain();\n const queue = items.slice();\n if (truncated && queue.length > 0) {\n const first = queue[0];\n if (first !== undefined && first.type === \"submitted\") {\n queue[0] = { ...first, truncated: true } satisfies TaskEvent;\n }\n }\n return queue;\n}\n\nclass TaskIterator implements AsyncIterator<TaskEvent> {\n private readonly queue: TaskEvent[];\n private pendingResolve?: (v: IteratorResult<TaskEvent>) => void;\n private done = false;\n private readonly callback: (e: TaskEvent) => void;\n\n constructor(\n buffer: RingBuffer<TaskEvent>,\n private readonly id: string,\n private readonly deps: SubscribeDeps,\n ) {\n this.queue = drainBuffered(buffer);\n this.callback = (e) => this.deliver(e);\n deps.getOrCreateSubscriberSet(id).add(this.callback);\n }\n\n private deliver(e: TaskEvent): void {\n if (this.done) return;\n if (this.pendingResolve !== undefined) {\n const r = this.pendingResolve;\n this.pendingResolve = undefined;\n r({ value: e, done: false });\n } else {\n this.queue.push(e);\n }\n }\n\n private cleanup(): void {\n if (this.done) return;\n this.done = true;\n this.deps.removeSubscriber(this.id, this.callback);\n if (this.pendingResolve !== undefined) {\n const r = this.pendingResolve;\n this.pendingResolve = undefined;\n r({ value: undefined, done: true });\n }\n }\n\n private dequeue(): IteratorResult<TaskEvent> | undefined {\n const event = this.queue.shift();\n if (event === undefined) return undefined;\n if (isTerminalEvent(event)) queueMicrotask(() => this.cleanup());\n return { value: event, done: false };\n }\n\n next(): Promise<IteratorResult<TaskEvent>> {\n if (this.done) return Promise.resolve({ value: undefined, done: true });\n const queued = this.dequeue();\n if (queued !== undefined) return Promise.resolve(queued);\n return new Promise((resolve) => {\n this.pendingResolve = resolve;\n });\n }\n\n return(): Promise<IteratorResult<TaskEvent>> {\n this.cleanup();\n return Promise.resolve({ value: undefined, done: true });\n }\n}\n\nexport function buildSubscribe(deps: SubscribeDeps) {\n return function subscribe(id: string): AsyncIterable<TaskEvent> {\n if (!isValidTaskId(id, true)) throw new TaskNotFoundError(id);\n const buffer = deps.getBuffer(id);\n if (buffer === undefined) throw new TaskNotFoundError(id);\n\n return {\n [Symbol.asyncIterator](): AsyncIterator<TaskEvent> {\n return new TaskIterator(buffer, id, deps);\n },\n };\n };\n}\n","/**\n * OTel telemetry for the Task registry (ADR D371).\n *\n * Spans:\n * - `task.submit` — short-lived span around the submit + insert.\n * - `task.transition` — per state transition (attrs: from / to).\n * - `task.cancel` — invoked from `Task.cancel` or via cancelRequested honor.\n *\n * Uses the existing tracer seam (D34); when OTel is absent, every helper\n * returns the shared no-op span. No new peer deps.\n *\n * @internal\n */\n\nimport { getTracer, noopSpan, type SpanLike } from \"../observability/tracer-loader.js\";\n\nconst TRACER_NAME = \"@theokit/sdk/task\";\n\nexport function startTaskSubmitSpan(info: { taskId: string; kind: string }): SpanLike {\n const tracer = getTracer(TRACER_NAME);\n if (tracer === undefined) return noopSpan;\n return tracer.startSpan(\"task.submit\", {\n attributes: {\n \"task.id\": info.taskId,\n \"task.kind\": info.kind,\n },\n });\n}\n\nexport function startTaskTransitionSpan(info: {\n taskId: string;\n from: string;\n to: string;\n}): SpanLike {\n const tracer = getTracer(TRACER_NAME);\n if (tracer === undefined) return noopSpan;\n return tracer.startSpan(\"task.transition\", {\n attributes: {\n \"task.id\": info.taskId,\n \"task.state.from\": info.from,\n \"task.state.to\": info.to,\n },\n });\n}\n\nexport function startTaskCancelSpan(info: {\n taskId: string;\n reason?: string;\n via: \"api\" | \"cancelRequested\";\n}): SpanLike {\n const tracer = getTracer(TRACER_NAME);\n if (tracer === undefined) return noopSpan;\n return tracer.startSpan(\"task.cancel\", {\n attributes: {\n \"task.id\": info.taskId,\n \"task.cancel.via\": info.via,\n ...(info.reason !== undefined ? { \"task.cancel.reason\": info.reason } : {}),\n },\n });\n}\n","/**\n * `TaskRegistry` — the singleton coordinating Task submit/list/get/cancel/\n * subscribe. Wraps the pluggable `TaskStore` (D364), the `AsyncSemaphore`\n * (D135 / D369) and a per-task `RingBuffer<TaskEvent>` (D372) for\n * late-attach replay.\n *\n * Edge cases absorbed:\n * - EC-3: work-fn invocation goes through `Promise.resolve().then(...)`\n * so synchronous throws become rejected promises.\n * - EC-4: pre-aborted signal short-circuits to `cancelled` without\n * acquiring a semaphore slot.\n * - EC-7: cross-process cancel via the `cancelRequested` flag on\n * `TaskHandle`. Registry polls at start + each progress event.\n * - EC-9: store-update failures are caught + logged; the event is\n * still emitted so subscribers always observe a terminal event.\n * - EC-10: subscribe iterator implements `return()` for leak-free\n * cleanup.\n * - EC-11: reentrant submit (work-fn calling `Task.submit`) uses an\n * ALS marker to bypass the semaphore queue, avoiding deadlock under\n * low concurrency caps.\n *\n * @internal\n */\n\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport { randomUUID } from \"node:crypto\";\n\nimport { InvalidTaskIdError } from \"../../errors.js\";\nimport {\n isValidTaskId,\n type TaskCancelResult,\n type TaskEvent,\n type TaskFilter,\n type TaskHandle,\n type TaskKind,\n type TaskState,\n type TaskStoreOptions,\n} from \"../../types/task.js\";\nimport { type AsyncSemaphore, createSemaphore } from \"../runtime/async-semaphore.js\";\nimport { RingBuffer } from \"./ring-buffer.js\";\nimport { getTaskStoreFor, InMemoryTaskStore, type TaskStore } from \"./store.js\";\nimport { buildSubscribe } from \"./subscribe.js\";\nimport { startTaskCancelSpan, startTaskSubmitSpan, startTaskTransitionSpan } from \"./telemetry.js\";\n\nconst DEFAULT_CONCURRENCY = 8;\nconst DEFAULT_RETENTION_MS = 60 * 60 * 1000;\nconst EVICTION_INTERVAL_MS = 5 * 60 * 1000;\nconst RING_CAP = 64;\n\n/** EC-11 — ALS flag indicating we are inside a task work-fn. Reentrant submits bypass the semaphore. */\nconst reentryAls = new AsyncLocalStorage<boolean>();\n\nexport interface TaskRegistryOptions {\n readonly store?: TaskStoreOptions;\n readonly maxConcurrent?: number;\n readonly retentionMs?: number;\n}\n\nexport interface TaskWorkContext {\n readonly signal: AbortSignal;\n emit(payload: unknown): void;\n}\n\ntype WorkFn<T> = (ctx: TaskWorkContext) => Promise<T> | T;\n\ninterface InternalState {\n readonly store: TaskStore;\n readonly semaphore: AsyncSemaphore;\n readonly aborters: Map<string, AbortController>;\n readonly buffers: Map<string, RingBuffer<TaskEvent>>;\n readonly subscribers: Map<string, Set<(e: TaskEvent) => void>>;\n retentionMs: number;\n evictTimer?: NodeJS.Timeout;\n firstSubmitSeen: boolean;\n}\n\nfunction buildState(opts: TaskRegistryOptions): InternalState {\n const store = opts.store === undefined ? new InMemoryTaskStore() : getTaskStoreFor(opts.store);\n return {\n store,\n semaphore: createSemaphore(opts.maxConcurrent ?? DEFAULT_CONCURRENCY),\n aborters: new Map(),\n buffers: new Map(),\n subscribers: new Map(),\n retentionMs: opts.retentionMs ?? DEFAULT_RETENTION_MS,\n firstSubmitSeen: false,\n };\n}\n\nlet state: InternalState = buildState({});\n\nexport function __resetTaskRegistryForTests(): void {\n if (state.evictTimer !== undefined) clearInterval(state.evictTimer);\n state = buildState({});\n}\n\nexport function __getSubscribersCountForTests(taskId: string): number {\n return state.subscribers.get(taskId)?.size ?? 0;\n}\n\nexport function __getCancelRequestedForTests(_taskId: string): boolean | undefined {\n // Best-effort: only meaningful for backends that persist the flag.\n // For in-memory check via store read.\n return undefined;\n}\n\nexport function configure(opts: TaskRegistryOptions): void {\n if (state.firstSubmitSeen) {\n process.stderr.write(\n \"[task] configure() ignored — registry already in use; reset via __resetTaskRegistryForTests()\\n\",\n );\n return;\n }\n if (state.evictTimer !== undefined) clearInterval(state.evictTimer);\n state = buildState(opts);\n}\n\nfunction emitToSubscribers(taskId: string, event: TaskEvent): void {\n const buffer = state.buffers.get(taskId);\n if (buffer !== undefined) buffer.push(event);\n const subs = state.subscribers.get(taskId);\n if (subs === undefined) return;\n for (const cb of subs) {\n try {\n cb(event);\n } catch (err) {\n process.stderr.write(`[task] subscriber threw: ${(err as Error).message}\\n`);\n }\n }\n}\n\nasync function safeUpdate(\n taskId: string,\n mutate: (h: TaskHandle) => TaskHandle,\n): Promise<TaskHandle | undefined> {\n try {\n return await state.store.update(taskId, mutate);\n } catch (err) {\n // EC-9: store failure should not swallow the event.\n process.stderr.write(`[task] store.update failed for ${taskId}: ${(err as Error).message}\\n`);\n return undefined;\n }\n}\n\nfunction startEvictTimerIfNeeded(): void {\n if (state.evictTimer !== undefined) return;\n state.evictTimer = setInterval(() => {\n const cutoff = Date.now() - state.retentionMs;\n void state.store\n .evictTerminalOlderThan(cutoff)\n .then((count) => {\n if (count === 0) return;\n // Also drop buffers + subscribers for evicted tasks. We don't\n // know which ones were dropped — clean up any task whose store\n // entry is gone.\n for (const id of state.buffers.keys()) {\n void state.store.get(id).then((h) => {\n if (h === undefined) {\n state.buffers.delete(id);\n state.subscribers.delete(id);\n state.aborters.delete(id);\n }\n });\n }\n })\n .catch(() => {\n /* swallow timer errors */\n });\n }, EVICTION_INTERVAL_MS).unref();\n}\n\nfunction buildSubmittedEvent(handle: TaskHandle): TaskEvent {\n return {\n type: \"submitted\",\n taskId: handle.id,\n kind: handle.kind,\n submittedAt: handle.submittedAt,\n ...(handle.meta !== undefined ? { meta: handle.meta } : {}),\n };\n}\n\nfunction _resolveId(rawId: string | undefined, kind: TaskKind): string {\n if (rawId === undefined) return randomUUID();\n const allowReserved = kind !== \"custom\" && kind !== \"run\";\n // For \"run\" we want to allow user-supplied IDs only — adapter wrapping\n // happens via batch/workflow/cron, which pass their own prefixed IDs.\n if (!isValidTaskId(rawId, allowReserved)) {\n throw new InvalidTaskIdError(`invalid task id: ${rawId}`, rawId);\n }\n return rawId;\n}\n\nasync function shortCircuitAborted(handle: TaskHandle, signal: AbortSignal): Promise<TaskHandle> {\n // EC-4: pre-aborted signal — skip queue/semaphore.\n const cancelled: TaskHandle = {\n ...handle,\n state: \"cancelled\",\n cancelledAt: Date.now(),\n };\n await state.store.insert(cancelled);\n state.buffers.set(handle.id, new RingBuffer(RING_CAP));\n emitToSubscribers(handle.id, buildSubmittedEvent(cancelled));\n emitToSubscribers(handle.id, {\n type: \"cancelled\",\n taskId: handle.id,\n cancelledAt: cancelled.cancelledAt ?? Date.now(),\n reason: signal.reason instanceof Error ? signal.reason.message : \"pre-aborted\",\n });\n return cancelled;\n}\n\nasync function transition<T extends TaskState>(\n taskId: string,\n next: T,\n patch: Partial<TaskHandle>,\n): Promise<void> {\n const before = await state.store.get(taskId);\n const span = startTaskTransitionSpan({\n taskId,\n from: before?.state ?? \"unknown\",\n to: next,\n });\n try {\n await safeUpdate(taskId, (h) => ({ ...h, state: next, ...patch }));\n } finally {\n span.end();\n }\n}\n\ninterface SubmitInternal<T> {\n readonly kind: TaskKind;\n readonly work: WorkFn<T>;\n readonly id?: string;\n readonly meta?: Record<string, unknown>;\n readonly signal?: AbortSignal;\n /** When true (adapter-internal), the validator allows reserved prefixes. */\n readonly allowReservedPrefix?: boolean;\n}\n\nasync function buildAndInsertQueued(\n internal: SubmitInternal<unknown>,\n resolvedId: string,\n): Promise<TaskHandle> {\n const submittedAt = Date.now();\n const handle: TaskHandle = {\n id: resolvedId,\n kind: internal.kind,\n state: \"queued\",\n submittedAt,\n ...(internal.meta !== undefined ? { meta: internal.meta } : {}),\n };\n await state.store.insert(handle);\n state.buffers.set(resolvedId, new RingBuffer(RING_CAP));\n emitToSubscribers(resolvedId, buildSubmittedEvent(handle));\n return handle;\n}\n\nfunction resolveIdInternal(internal: SubmitInternal<unknown>): string {\n if (internal.id === undefined) return randomUUID();\n if (!isValidTaskId(internal.id, internal.allowReservedPrefix ?? false)) {\n throw new InvalidTaskIdError(`invalid task id: ${internal.id}`, internal.id);\n }\n return internal.id;\n}\n\nasync function runWorkAndFinalize<T>(\n taskId: string,\n aborter: AbortController,\n work: WorkFn<T>,\n): Promise<void> {\n const ctx: TaskWorkContext = {\n signal: aborter.signal,\n emit(payload) {\n // EC-7: check cancelRequested at every progress checkpoint.\n void checkCancelRequestedAt(taskId, aborter);\n emitToSubscribers(taskId, {\n type: \"progress\",\n taskId,\n at: Date.now(),\n payload,\n });\n },\n };\n\n try {\n const result = await reentryAls.run(true, () => Promise.resolve().then(() => work(ctx)));\n if (aborter.signal.aborted) {\n const cancelledAt = Date.now();\n await transition(taskId, \"cancelled\", { cancelledAt });\n emitToSubscribers(taskId, { type: \"cancelled\", taskId, cancelledAt });\n return;\n }\n const finishedAt = Date.now();\n await transition(taskId, \"finished\", { finishedAt, result });\n emitToSubscribers(taskId, { type: \"finished\", taskId, finishedAt, result });\n } catch (err) {\n if (aborter.signal.aborted) {\n const cancelledAt = Date.now();\n await transition(taskId, \"cancelled\", { cancelledAt });\n emitToSubscribers(taskId, { type: \"cancelled\", taskId, cancelledAt });\n return;\n }\n const erroredAt = Date.now();\n const error =\n err instanceof Error\n ? { code: (err as { code?: string }).code ?? \"work_threw\", message: err.message }\n : { code: \"work_threw\", message: String(err) };\n await transition(taskId, \"error\", { erroredAt, error });\n emitToSubscribers(taskId, { type: \"errored\", taskId, erroredAt, error });\n }\n}\n\nasync function checkCancelRequestedAt(taskId: string, aborter: AbortController): Promise<void> {\n if (aborter.signal.aborted) return;\n try {\n const handle = await state.store.get(taskId);\n if (handle?.cancelRequested === true) {\n aborter.abort(\"cancelRequested\");\n }\n } catch {\n /* ignore — best-effort poll */\n }\n}\n\nasync function acquireSlot(): Promise<() => void> {\n if (reentryAls.getStore() === true) {\n // EC-11: reentrant submit bypasses the queue.\n return () => {\n /* no-op */\n };\n }\n return state.semaphore.acquire();\n}\n\n/**\n * Submit a task. Validates id (D368, EC-5 via allowReservedPrefix),\n * handles pre-aborted signals (EC-4), enforces single-flight by id\n * (D367), runs work under semaphore (D369/EC-11 reentrant bypass),\n * and produces the canonical event stream (D366).\n */\nexport async function submit<T>(internal: SubmitInternal<T>): Promise<TaskHandle> {\n state.firstSubmitSeen = true;\n startEvictTimerIfNeeded();\n\n const resolvedId = resolveIdInternal(internal);\n const submitSpan = startTaskSubmitSpan({ taskId: resolvedId, kind: internal.kind });\n\n // D367 single-flight.\n const existing = await state.store.get(resolvedId);\n if (existing !== undefined) {\n submitSpan.end();\n return existing;\n }\n\n const queuedHandle = await buildAndInsertQueued(internal, resolvedId);\n submitSpan.end();\n\n // EC-4: pre-aborted signal — short-circuit.\n if (internal.signal?.aborted === true) {\n return shortCircuitAborted(queuedHandle, internal.signal);\n }\n\n const aborter = new AbortController();\n state.aborters.set(resolvedId, aborter);\n if (internal.signal !== undefined) {\n internal.signal.addEventListener(\"abort\", () => aborter.abort(internal.signal?.reason), {\n once: true,\n });\n }\n\n // Fire and forget the actual run; the returned handle is the queued one.\n const release = await acquireSlot();\n void (async () => {\n try {\n // Check cancelRequested before starting (EC-7).\n await checkCancelRequestedAt(resolvedId, aborter);\n if (aborter.signal.aborted) {\n const cancelledAt = Date.now();\n await transition(resolvedId, \"cancelled\", { cancelledAt });\n emitToSubscribers(resolvedId, { type: \"cancelled\", taskId: resolvedId, cancelledAt });\n return;\n }\n const startedAt = Date.now();\n await transition(resolvedId, \"running\", { startedAt });\n emitToSubscribers(resolvedId, { type: \"started\", taskId: resolvedId, startedAt });\n await runWorkAndFinalize(resolvedId, aborter, internal.work as WorkFn<unknown>);\n } finally {\n release();\n state.aborters.delete(resolvedId);\n }\n })();\n\n return queuedHandle;\n}\n\nexport async function list(filter: TaskFilter = {}): Promise<TaskHandle[]> {\n return state.store.list(filter);\n}\n\nexport async function get(id: string): Promise<TaskHandle | undefined> {\n if (!isValidTaskId(id, true)) return undefined;\n return state.store.get(id);\n}\n\nexport async function cancel(id: string, reason?: string): Promise<TaskCancelResult> {\n if (!isValidTaskId(id, true)) return { cancelled: false, alreadyTerminal: false };\n const handle = await state.store.get(id);\n if (handle === undefined) return { cancelled: false, alreadyTerminal: false };\n if (handle.state === \"finished\" || handle.state === \"error\" || handle.state === \"cancelled\") {\n return { cancelled: false, alreadyTerminal: true };\n }\n const span = startTaskCancelSpan({\n taskId: id,\n ...(reason !== undefined ? { reason } : {}),\n via: \"api\",\n });\n try {\n return await cancelInternal(id, handle.state, reason);\n } finally {\n span.end();\n }\n}\n\nasync function cancelInternal(\n id: string,\n currentState: TaskState,\n reason?: string,\n): Promise<TaskCancelResult> {\n if (currentState === \"queued\") {\n const cancelledAt = Date.now();\n await transition(id, \"cancelled\", { cancelledAt });\n emitToSubscribers(id, {\n type: \"cancelled\",\n taskId: id,\n cancelledAt,\n ...(reason !== undefined ? { reason } : {}),\n });\n state.aborters.delete(id);\n return { cancelled: true, alreadyTerminal: false };\n }\n // running: trigger AbortController; runWorkAndFinalize handles the transition.\n const aborter = state.aborters.get(id);\n if (aborter !== undefined) aborter.abort(reason ?? \"cancelled\");\n return { cancelled: true, alreadyTerminal: false };\n}\n\nexport const subscribe = buildSubscribe({\n getBuffer: (id) => state.buffers.get(id),\n getOrCreateSubscriberSet: (id) => {\n let subs = state.subscribers.get(id);\n if (subs === undefined) {\n subs = new Set();\n state.subscribers.set(id, subs);\n }\n return subs;\n },\n removeSubscriber: (id, cb) => {\n const set = state.subscribers.get(id);\n set?.delete(cb);\n if (set !== undefined && set.size === 0) state.subscribers.delete(id);\n },\n});\n\n/** Manual trigger for tests. */\nexport async function evictNow(now: number = Date.now()): Promise<number> {\n return state.store.evictTerminalOlderThan(now - state.retentionMs);\n}\n","/**\n * Shared Zod schema for the `{ backend: \"memory\" | \"json\", dir? }` options\n * used by both `Workflow` snapshots and `Cache` semantic store persistence.\n * Extracted to remove the cross-module clone flagged by jscpd.\n *\n * @internal\n */\n\nimport { z } from \"zod\";\n\n/**\n * `persistence?` opt-in JSON disk backend with `dir` required when chosen.\n */\nexport const PersistenceSchema = z\n .object({\n backend: z.enum([\"memory\", \"json\"]),\n dir: z.string().optional(),\n })\n .refine((p) => p.backend !== \"json\" || (typeof p.dir === \"string\" && p.dir.length > 0), {\n message: 'persistence.dir is required when backend = \"json\"',\n })\n .optional();\n","/**\n * Canonical path-guard module (ADRs D79-D81).\n *\n * Three primitives + one typed error:\n * - `safePathJoin(base, ...parts)` — resolve THEN prefix-check (ADR D80).\n * - `assertNoSymlinkEscape(path, base)` — `realpathSync` resolves entire\n * symlink chain (EC-1 fix; Hermes v0.2 #386, #61).\n * - `sanitizeIdentifier(input, { maxLen })` — strict grammar\n * `^[a-z0-9][a-z0-9-_]*$` (ADR D81; case-insensitive on input,\n * lowercase on output).\n * - `PathTraversalError` — extends ConfigurationError with code\n * `path_traversal` (ADR D65: no new hierarchy).\n *\n * Wire at all sites where user input becomes a path. CI lint gate\n * `tests/lint/no-unguarded-path-input.test.ts` prevents regression\n * (ADR D85).\n *\n * @internal\n */\n\nimport { lstatSync, readlinkSync, realpathSync, type Stats } from \"node:fs\";\nimport { dirname, resolve, sep } from \"node:path\";\n\nimport { ConfigurationError } from \"../../errors.js\";\n\n/**\n * Thrown when a path operation would escape its allowed base directory.\n * Extends `ConfigurationError` (no new error hierarchy per ADR D65).\n *\n * @internal\n */\nexport class PathTraversalError extends ConfigurationError {\n override readonly name: string = \"PathTraversalError\";\n\n constructor(input: string, resolvedPath: string) {\n super(`Path traversal attempt: ${input} → ${resolvedPath}`, {\n code: \"path_traversal\",\n });\n }\n}\n\n/**\n * Thrown when an agent tool is asked to read or write a sensitive path\n * that the blocklist forbids (`.env`, `.git/`, `node_modules/`, `.theo/`,\n * lock files). Distinct from `PathTraversalError` because the path is\n * lexically inside the project — it is just sensitive.\n *\n * Extends `ConfigurationError` (no new error hierarchy per ADR D65).\n *\n * @public\n */\nexport class ForbiddenPathError extends ConfigurationError {\n override readonly name: string = \"ForbiddenPathError\";\n\n constructor(path: string) {\n super(\n `Path '${path}' is in the sensitive-file blocklist (.env, .git/, node_modules/, .theo/, lock files)`,\n {\n code: \"forbidden_path\",\n },\n );\n }\n}\n\n/**\n * Join `base` with `...parts` and ensure the resolved absolute path stays\n * under `base`. Resolves FIRST, then prefix-checks (ADR D80) — prevents\n * normalized-escape bypasses like `subdir/.\\\\./bar`.\n *\n * Returns the safe absolute path. Throws `PathTraversalError` if escape.\n *\n * @internal\n */\nexport function safePathJoin(base: string, ...parts: string[]): string {\n if (base === \"\") {\n throw new Error(\"safePathJoin: base must be non-empty\");\n }\n const baseResolved = resolve(base);\n const target = resolve(base, ...parts);\n if (target !== baseResolved && !target.startsWith(baseResolved + sep)) {\n throw new PathTraversalError(parts.join(\"/\"), target);\n }\n return target;\n}\n\n/**\n * Assert that `path` — including every directory component in the chain —\n * stays under `base` after symlink resolution. No-op when nothing on the\n * path exists yet.\n *\n * Two-bug history:\n * 1. **EC-1** (original fix, kept): a multi-level symlink chain A → B → C\n * must be resolved end-to-end. `realpathSync` does this in 1 syscall.\n * 2. **Defence-in-depth** (added v1.x): the previous implementation only\n * called `lstatSync(path)` on the terminal component. If an INTERMEDIATE\n * directory was a symlink (`base/inner-symlink → /outside`), `lstat` on\n * `base/inner-symlink/file.txt` followed the symlink and reported the\n * regular file — escape went undetected. Fix: walk up to the nearest\n * existing ancestor and `realpath` THAT, then re-attach the suffix and\n * check the result against the canonical base.\n *\n * @internal\n */\nexport function assertNoSymlinkEscape(path: string, base: string): void {\n // Canonical base — symlinks in the base path itself are absorbed once here.\n let baseResolved: string;\n try {\n baseResolved = realpathSync(base);\n } catch {\n // base doesn't exist as a real directory yet — fall back to lexical resolve.\n baseResolved = resolve(base);\n }\n\n // Find the deepest ancestor of `path` that exists, then realpath it.\n // Anything from there onward is \"not yet on disk\" and contributes only\n // its lexical suffix. This covers three cases:\n // - path exists (regular file or symlink at any depth) → realpath the full path\n // - path doesn't exist but intermediate dir is a symlink → realpath the ancestor\n // - nothing on the path exists → no escape risk (return)\n const resolved = realpathOfDeepestExisting(path);\n if (resolved === undefined) return; // path has no existing prefix — nothing to attack\n\n if (resolved !== baseResolved && !resolved.startsWith(baseResolved + sep)) {\n throw new PathTraversalError(`symlink ${path}`, resolved);\n }\n}\n\n/**\n * Find the deepest ancestor of `path` that exists on disk, resolve all\n * symlinks in that ancestor via `realpathSync`, and re-attach the\n * lexical suffix. Returns `undefined` when no ancestor exists.\n *\n * Handles dangling symlinks: if the terminal IS a symlink but its target\n * is missing, we still detect escape via `readlinkSync` + parent resolve.\n */\nfunction realpathOfDeepestExisting(path: string): string | undefined {\n // First try the full path — the common case.\n try {\n return realpathSync(path);\n } catch {\n // Not resolvable. Two sub-cases.\n }\n\n // Sub-case A: terminal is a dangling symlink.\n try {\n const stat: Stats = lstatSync(path);\n if (stat.isSymbolicLink()) {\n const target = readlinkSync(path);\n // Resolve target relative to the REAL parent dir, so intermediate\n // symlinks in the parent chain are absorbed.\n const parentReal = realpathOfDeepestExisting(dirname(path));\n const parentBase = parentReal ?? dirname(path);\n return resolve(parentBase, target);\n }\n } catch {\n // lstat failed too — terminal doesn't exist at all.\n }\n\n // Sub-case B: walk up to the nearest existing ancestor, then re-attach\n // the suffix lexically.\n let cursor = dirname(path);\n let suffix = path.slice(cursor.length);\n while (cursor !== dirname(cursor)) {\n try {\n const real = realpathSync(cursor);\n // Reconstruct: ancestor's realpath + remaining (still-lexical) suffix\n return resolve(real, `.${suffix}`);\n } catch {\n suffix = path.slice(dirname(cursor).length);\n cursor = dirname(cursor);\n }\n }\n // Reached filesystem root without finding any existing ancestor.\n return undefined;\n}\n\nconst LOCK_FILES = new Set([\"pnpm-lock.yaml\", \"package-lock.json\", \"yarn.lock\", \"bun.lockb\"]);\n\n/**\n * Decide whether a project-relative path points to a known-sensitive file\n * that a coding agent must not read or write.\n *\n * Universal blocklist (works for any agent operating on a project tree):\n *\n * - `.env`, `.env.<anything>` — except `.env.example` (template safe to read)\n * - `.git/` — version control internals\n * - `node_modules/` — dependency cache (changes don't belong to the user)\n * - `.theo/` — TheoKit build artefacts / state\n * - Lock files at any depth: `pnpm-lock.yaml`, `package-lock.json`,\n * `yarn.lock`, `bun.lockb`\n *\n * Operates on path segments (forward-slash normalized). Cross-platform safe.\n *\n * Use together with `safePathJoin` + `assertNoSymlinkEscape`: the former two\n * defeat traversal, this one defeats reading a file that is lexically inside\n * the project but should not be agent-visible.\n *\n * @public\n */\nexport function isForbiddenPath(input: string): boolean {\n // Normalize: forward slashes only, strip leading \"./\"\n const normalized = input.replace(/\\\\/g, \"/\").replace(/^\\.\\//, \"\");\n if (normalized.length === 0) return false;\n\n const segments = normalized.split(\"/\").filter((s) => s.length > 0);\n if (segments.length === 0) return false;\n\n const first = segments[0]!;\n // .env.example is explicitly allowlisted (template safe to read)\n if (first === \".env.example\") return false;\n if (first === \".env\") return true;\n if (/^\\.env\\./.test(first)) return true;\n\n if (first === \".git\") return true;\n if (first === \"node_modules\") return true;\n if (first === \".theo\") return true;\n\n const basename = segments[segments.length - 1]!;\n if (LOCK_FILES.has(basename)) return true;\n\n return false;\n}\n\nconst IDENTIFIER_PATTERN = /^[a-z0-9][a-z0-9\\-_]*$/i;\n\n/**\n * Validate that `input` is a safe path component (skill name, agent ID,\n * namespace, etc.) and return its lowercase form. Strict grammar\n * `^[a-z0-9][a-z0-9-_]*$` rejects path separators, dots, null bytes,\n * whitespace, unicode invisible chars, and any leading `-`/`_`.\n *\n * @param input - User-supplied identifier candidate.\n * @param options.maxLen - Maximum allowed length (default 64).\n * @returns Lowercase form of `input`.\n * @throws `ConfigurationError` with code `invalid_identifier` on rejection.\n *\n * @internal\n */\nexport function sanitizeIdentifier(input: string, options?: { maxLen?: number }): string {\n const maxLen = options?.maxLen ?? 64;\n if (input.length === 0 || input.length > maxLen) {\n throw new ConfigurationError(`Identifier length out of range (1-${maxLen}): \"${input}\"`, {\n code: \"invalid_identifier\",\n });\n }\n if (!IDENTIFIER_PATTERN.test(input)) {\n throw new ConfigurationError(`Identifier contains invalid characters: \"${input}\"`, {\n code: \"invalid_identifier\",\n });\n }\n return input.toLowerCase();\n}\n","/**\n * Public `Workflow` class — declarative multi-step orchestration over\n * `Agent.send`, `Handoff`, `Agent.batch` and friends (Adoption Roadmap #5;\n * ADRs D230-D248).\n *\n * Usage:\n *\n * import { Agent } from \"@theokit/sdk\";\n * import { Workflow, fn, agentStep } from \"@theokit/sdk/workflow\";\n *\n * const classifier = await Agent.create({ ... });\n * const wf = Workflow.create({ name: \"demo\" })\n * .then(fn(\"validate\", (input: { id: string }) => {\n * if (!input.id) throw new Error(\"missing id\");\n * return input;\n * }))\n * .then(agentStep(\"classify\", classifier, (i) => `Classify: ${JSON.stringify(i)}`))\n * .commit();\n *\n * const run = await wf.run({ id: \"x\" });\n * console.log(run.status, run.output);\n *\n * @public\n */\n\nimport type { ZodType } from \"zod\";\nimport { z } from \"zod\";\nimport { PersistenceSchema } from \"./internal/persistence/persistence-schema.js\";\nimport { sanitizeIdentifier } from \"./internal/security/path-guard.js\";\nimport type { SDKAgent } from \"./types/agent.js\";\nimport type {\n AgentStep,\n BranchStep,\n DowhileStep,\n FnStep,\n ForeachStep,\n ParallelStep,\n RetryPolicy,\n SleepStep,\n Step,\n StepContext,\n SuspendStep,\n WorkflowOptions,\n WorkflowResumeOptions,\n WorkflowRun,\n WorkflowRunOptions,\n} from \"./types/workflow.js\";\nimport { WorkflowDuplicateStepIdError } from \"./types/workflow.js\";\n\n/* ─── Zod validation schemas ─── */\n\nconst RetryPolicySchema = z.object({\n // EC-3 absorbed: maxAttempts MUST be a finite int in [1, 20].\n maxAttempts: z\n .number()\n .int(\"retry.maxAttempts must be integer\")\n .min(1, \"retry.maxAttempts must be >= 1\")\n .max(20, \"retry.maxAttempts must be <= 20\"),\n initialBackoffMs: z.number().int().min(0).optional(),\n backoffCoefficient: z.number().min(1).optional(),\n maximumBackoffMs: z.number().int().min(0).optional(),\n nonRetryableErrors: z.array(z.string()).optional(),\n});\n\nconst WorkflowOptionsSchema = z.object({\n name: z.string().min(1).max(128),\n persistence: PersistenceSchema,\n});\n\n/* ─── Builder ─── */\n\nexport class WorkflowBuilder<TInput = unknown, TOutput = unknown> {\n private readonly _steps: Step[] = [];\n private _committed = false;\n\n /** @internal */\n constructor(private readonly options: WorkflowOptions) {}\n\n /** @internal — only the executor reads this. */\n get __steps(): ReadonlyArray<Step> {\n return this._steps;\n }\n\n // biome-ignore lint/suspicious/noThenProperty: D233 locks the Mastra-style `.then(step)` builder DSL. The method is fluent, never awaited.\n then<TO = unknown>(step: Step): WorkflowBuilder<TInput, TO> {\n this.assertNotCommitted();\n validateStepId(step.id);\n this._steps.push(step);\n return this as unknown as WorkflowBuilder<TInput, TO>;\n }\n\n parallel(\n branches: ReadonlyArray<ReadonlyArray<Step>>,\n opts?: { id?: string; concurrency?: number; errorPolicy?: \"fail-fast\" | \"collect\" },\n ): WorkflowBuilder<TInput, unknown[]> {\n this.assertNotCommitted();\n const id = opts?.id ?? `parallel_${this._steps.length}`;\n validateStepId(id);\n for (const branch of branches) {\n for (const inner of branch) validateStepId(inner.id);\n }\n const step: ParallelStep = {\n kind: \"parallel\",\n id,\n branches,\n ...(opts?.concurrency !== undefined ? { concurrency: opts.concurrency } : {}),\n ...(opts?.errorPolicy !== undefined ? { errorPolicy: opts.errorPolicy } : {}),\n };\n this._steps.push(step);\n return this as unknown as WorkflowBuilder<TInput, unknown[]>;\n }\n\n branch(\n predicates: BranchStep[\"predicates\"],\n opts?: { id?: string; fallback?: ReadonlyArray<Step> },\n ): WorkflowBuilder<TInput, unknown> {\n this.assertNotCommitted();\n const id = opts?.id ?? `branch_${this._steps.length}`;\n validateStepId(id);\n const step: BranchStep = {\n kind: \"branch\",\n id,\n predicates,\n ...(opts?.fallback !== undefined ? { fallback: opts.fallback } : {}),\n };\n this._steps.push(step);\n return this as unknown as WorkflowBuilder<TInput, unknown>;\n }\n\n foreach(\n iterableFrom: string,\n step: Step,\n opts?: { id?: string; concurrency?: number },\n ): WorkflowBuilder<TInput, unknown[]> {\n this.assertNotCommitted();\n const id = opts?.id ?? `foreach_${this._steps.length}`;\n validateStepId(id);\n validateStepId(iterableFrom);\n validateStepId(step.id);\n const node: ForeachStep = {\n kind: \"foreach\",\n id,\n iterableFrom,\n step,\n ...(opts?.concurrency !== undefined ? { concurrency: opts.concurrency } : {}),\n };\n this._steps.push(node);\n return this as unknown as WorkflowBuilder<TInput, unknown[]>;\n }\n\n dowhile(\n step: Step,\n condFn: DowhileStep[\"condFn\"],\n opts?: { id?: string; maxIterations?: number },\n ): WorkflowBuilder<TInput, unknown> {\n this.assertNotCommitted();\n const id = opts?.id ?? `dowhile_${this._steps.length}`;\n validateStepId(id);\n validateStepId(step.id);\n const node: DowhileStep = {\n kind: \"dowhile\",\n id,\n step,\n condFn,\n ...(opts?.maxIterations !== undefined ? { maxIterations: opts.maxIterations } : {}),\n };\n this._steps.push(node);\n return this as unknown as WorkflowBuilder<TInput, unknown>;\n }\n\n sleep(durationMs: number, id?: string): WorkflowBuilder<TInput, TOutput> {\n this.assertNotCommitted();\n const stepId = id ?? `sleep_${this._steps.length}`;\n validateStepId(stepId);\n if (!Number.isFinite(durationMs) || durationMs < 0) {\n throw new Error(`sleep durationMs must be finite non-negative: ${durationMs}`);\n }\n const step: SleepStep = { kind: \"sleep\", id: stepId, durationMs };\n this._steps.push(step);\n return this;\n }\n\n suspend(opts?: { id?: string; payloadSchema?: ZodType }): WorkflowBuilder<TInput, unknown> {\n this.assertNotCommitted();\n const id = opts?.id ?? `suspend_${this._steps.length}`;\n validateStepId(id);\n const step: SuspendStep = {\n kind: \"suspend\",\n id,\n ...(opts?.payloadSchema !== undefined ? { payloadSchema: opts.payloadSchema } : {}),\n };\n this._steps.push(step);\n return this as unknown as WorkflowBuilder<TInput, unknown>;\n }\n\n commit(): Workflow<TInput, TOutput> {\n this.assertNotCommitted();\n this.validateUniqueIds();\n this._committed = true;\n // EC-5 absorbed: mint unique workflowId so single-flight lock is per-instance\n const workflowId = `wf-${mintShortId()}`;\n return new Workflow<TInput, TOutput>({ ...this.options, workflowId }, [...this._steps]);\n }\n\n private validateUniqueIds(): void {\n const seen = new Set<string>();\n walkStepsValidating(this._steps, seen);\n }\n\n private assertNotCommitted(): void {\n if (this._committed) {\n throw new Error(\"Workflow already committed; create a fresh Workflow.create(...) call.\");\n }\n }\n}\n\n/* ─── Workflow class ─── */\n\nexport class Workflow<TInput = unknown, TOutput = unknown> {\n /** @internal */\n constructor(\n private readonly _options: WorkflowOptions,\n private readonly _steps: ReadonlyArray<Step>,\n ) {}\n\n /** @internal — only the executor reads these. */\n get __options(): WorkflowOptions {\n return this._options;\n }\n /** @internal */\n get __steps(): ReadonlyArray<Step> {\n return this._steps;\n }\n\n /**\n * Construct a workflow builder. Validate options via Zod and return a\n * `WorkflowBuilder` for fluent chaining. Call `.commit()` to obtain the\n * immutable `Workflow`.\n */\n static create<TI = unknown, TO = unknown>(options: WorkflowOptions): WorkflowBuilder<TI, TO> {\n WorkflowOptionsSchema.parse(options);\n return new WorkflowBuilder<TI, TO>(options);\n }\n\n /**\n * Run this workflow with the given input. Returns a populated\n * `WorkflowRun`. Errors inside a step DO NOT throw — they propagate via\n * `run.status === \"failed\"`.\n */\n async run(input: TInput, opts?: WorkflowRunOptions): Promise<WorkflowRun<TOutput>> {\n // Lazy import to keep the public façade lean.\n const { executeWorkflow } = await import(\"./internal/workflow/executor.js\");\n const result = await executeWorkflow<TInput, TOutput>(this._options, this._steps, input, opts);\n // T3.4: opt-in Task wrapping (ADRs D363, D374). Workflows are\n // observable via Task.list/get/subscribe; the underlying run is\n // already terminal here (executor returned), so the Task just\n // records the outcome for inspection.\n if (opts?.task !== undefined) {\n const { submit: taskSubmit } = await import(\"./internal/task/registry.js\");\n const taskOpts = opts.task === true ? {} : opts.task;\n const id = taskOpts.id ?? `wf-${result.id}`;\n await taskSubmit({\n kind: \"workflow\",\n work: async (ctx) => {\n ctx.emit({ status: result.status, runId: result.id });\n return { status: result.status, runId: result.id, output: result.output };\n },\n id,\n meta: {\n workflowName: this._options.name,\n runId: result.id,\n status: result.status,\n ...(taskOpts.meta ?? {}),\n },\n allowReservedPrefix: true,\n });\n }\n return result;\n }\n\n /**\n * Resume a suspended workflow from its snapshot. Throws\n * `WorkflowSnapshotNotFoundError` if `runId` is unknown.\n */\n static async resume<TO = unknown>(opts: WorkflowResumeOptions): Promise<WorkflowRun<TO>> {\n const { resumeWorkflow } = await import(\"./internal/workflow/executor.js\");\n return resumeWorkflow<TO>(opts);\n }\n}\n\n/* ─── Helper factory functions ─── */\n\n/**\n * Build a `FnStep`. `id` must match `^[a-z0-9][a-z0-9_-]*$`.\n */\nexport function fn<I = unknown, O = unknown>(\n id: string,\n step: (input: I, ctx: StepContext) => Promise<O> | O,\n opts?: { inputSchema?: ZodType; outputSchema?: ZodType; retry?: RetryPolicy },\n): FnStep {\n validateStepId(id);\n if (opts?.retry !== undefined) RetryPolicySchema.parse(opts.retry);\n return {\n kind: \"fn\",\n id,\n fn: step as FnStep[\"fn\"],\n ...(opts?.inputSchema !== undefined ? { inputSchema: opts.inputSchema } : {}),\n ...(opts?.outputSchema !== undefined ? { outputSchema: opts.outputSchema } : {}),\n ...(opts?.retry !== undefined ? { retry: opts.retry } : {}),\n };\n}\n\n/**\n * Build an `AgentStep`. The `promptTemplate` can be a static string or a\n * function that receives the input and returns the prompt.\n */\nexport function agentStep(\n id: string,\n agent: SDKAgent,\n promptTemplate: string | ((input: unknown) => string),\n opts?: { retry?: RetryPolicy },\n): AgentStep {\n validateStepId(id);\n if (opts?.retry !== undefined) RetryPolicySchema.parse(opts.retry);\n return {\n kind: \"agent\",\n id,\n agent,\n promptTemplate,\n ...(opts?.retry !== undefined ? { retry: opts.retry } : {}),\n };\n}\n\n/* ─── Test seam re-export ─── */\n\nexport { __resetSnapshotStoresForTests } from \"./internal/workflow/snapshot-store.js\";\n\n/* ─── Re-exports for ergonomics (errors + all public types). After the\n sub-path extraction `@theokit/sdk/workflow` is the single import site,\n so type aliases must surface here (previously they reached consumers\n via `types/index.ts:25 export type * from \"./workflow.js\"`, which the\n extraction removes). ─── */\n\nexport type * from \"./types/workflow.js\";\nexport {\n WorkflowAlreadyRunningError,\n WorkflowCompensateNotImplementedError,\n WorkflowDuplicateStepIdError,\n WorkflowMaxIterationsExceededError,\n WorkflowNotSerializableError,\n WorkflowParallelError,\n WorkflowResumeStepNotFoundError,\n WorkflowSnapshotNotFoundError,\n} from \"./types/workflow.js\";\n\n/* ─── Internal helpers ─── */\n\nfunction validateStepId(id: string): void {\n // Reuses D81 grammar: ^[a-z0-9][a-z0-9_-]*$\n sanitizeIdentifier(id, { maxLen: 64 });\n}\n\nfunction mintShortId(): string {\n return globalThis.crypto.randomUUID().replace(/-/g, \"\").slice(0, 8);\n}\n\nfunction nestedStepsOf(s: Step): ReadonlyArray<ReadonlyArray<Step>> {\n if (s.kind === \"parallel\") return s.branches;\n if (s.kind === \"branch\") {\n const groups = s.predicates.map(([, branch]) => branch);\n return s.fallback !== undefined ? [...groups, s.fallback] : groups;\n }\n if (s.kind === \"foreach\" || s.kind === \"dowhile\") return [[s.step]];\n return [];\n}\n\nfunction walkStepsValidating(steps: ReadonlyArray<Step>, seen: Set<string>): void {\n for (const s of steps) {\n if (seen.has(s.id)) throw new WorkflowDuplicateStepIdError(s.id);\n seen.add(s.id);\n for (const nested of nestedStepsOf(s)) {\n walkStepsValidating(nested, seen);\n }\n }\n}\n"]}