@pi-unipi/unipi 3.0.0-alpha.2 → 3.0.0-alpha.21

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 (359) hide show
  1. package/CHANGELOG.md +292 -0
  2. package/README.md +8 -11
  3. package/docs/prefix-cache-architecture.md +14 -0
  4. package/package.json +22 -24
  5. package/packages/ask-user/README.md +55 -107
  6. package/packages/ask-user/ask-ui.ts +306 -732
  7. package/packages/ask-user/clipboard.ts +50 -0
  8. package/packages/ask-user/config.ts +74 -78
  9. package/packages/ask-user/package.json +2 -2
  10. package/packages/ask-user/questions.ts +151 -0
  11. package/packages/ask-user/skills/ask-user/SKILL.md +59 -133
  12. package/packages/ask-user/tools.ts +198 -432
  13. package/packages/autocomplete/package.json +1 -1
  14. package/packages/autocomplete/src/constants.ts +38 -43
  15. package/packages/autocomplete/src/sorting.ts +8 -0
  16. package/packages/background-tasks/package.json +2 -2
  17. package/packages/background-tasks/src/config.ts +0 -73
  18. package/packages/background-tasks/src/index.ts +20 -16
  19. package/packages/background-tasks/src/registry.ts +1 -171
  20. package/packages/background-tasks/src/types.ts +0 -32
  21. package/packages/btw/README.md +13 -56
  22. package/packages/btw/extensions/btw.ts +403 -1796
  23. package/packages/btw/package.json +5 -2
  24. package/packages/btw/skills/btw/SKILL.md +7 -143
  25. package/packages/compactor/README.md +56 -287
  26. package/packages/compactor/package.json +5 -9
  27. package/packages/compactor/skills/compactor/SKILL.md +13 -20
  28. package/packages/compactor/src/card.ts +90 -0
  29. package/packages/compactor/src/commands/index.ts +73 -130
  30. package/packages/compactor/src/compaction/compact-args.ts +5 -3
  31. package/packages/compactor/src/compaction/filter-noise.ts +1 -1
  32. package/packages/compactor/src/compaction/hooks.ts +487 -311
  33. package/packages/compactor/src/compaction/source.ts +178 -0
  34. package/packages/compactor/src/compaction/summarize.ts +586 -52
  35. package/packages/compactor/src/config/manager.ts +130 -127
  36. package/packages/compactor/src/config/schema.ts +32 -48
  37. package/packages/compactor/src/index.ts +40 -431
  38. package/packages/compactor/src/info-screen.ts +44 -190
  39. package/packages/compactor/src/session/recall-blocks.ts +1 -1
  40. package/packages/compactor/src/stats.ts +76 -0
  41. package/packages/compactor/src/tools/context-budget.ts +17 -34
  42. package/packages/compactor/src/tools/ctx-doctor.ts +45 -36
  43. package/packages/compactor/src/tools/register.ts +29 -269
  44. package/packages/compactor/src/types.ts +47 -186
  45. package/packages/core/README.md +25 -0
  46. package/packages/core/child-agent.ts +1 -0
  47. package/packages/core/command-echo.ts +63 -0
  48. package/packages/core/compaction-context.ts +41 -0
  49. package/packages/core/constants.ts +8 -38
  50. package/packages/core/events.ts +0 -53
  51. package/packages/core/fusion-status.ts +4 -0
  52. package/packages/core/global.d.ts +10 -0
  53. package/packages/core/harness-messages.ts +392 -0
  54. package/packages/core/index.ts +14 -0
  55. package/packages/core/kanboard-status.ts +49 -0
  56. package/packages/core/long-horizon-owner-status.ts +46 -0
  57. package/packages/core/model-cache.ts +81 -7
  58. package/packages/core/package.json +6 -3
  59. package/packages/core/src/attach/detect.ts +163 -0
  60. package/packages/core/src/child-agent/child-args.ts +31 -0
  61. package/packages/core/src/child-agent/delivery.ts +41 -0
  62. package/packages/core/src/child-agent/index.ts +5 -0
  63. package/packages/core/src/child-agent/readers.ts +203 -0
  64. package/packages/core/src/child-agent/runtime.ts +584 -0
  65. package/packages/core/src/evidence.ts +78 -0
  66. package/packages/core/src/hints/browser.ts +278 -0
  67. package/packages/core/src/hints/crab-data.ts +19 -0
  68. package/packages/core/src/hints/index.ts +865 -0
  69. package/packages/core/src/hints/lines.ts +607 -0
  70. package/packages/core/src/hints/store.ts +120 -0
  71. package/packages/core/src/jev/chatter.ts +24 -0
  72. package/packages/core/src/jev/settings.ts +177 -14
  73. package/packages/core/src/package-colors.ts +2 -0
  74. package/packages/core/src/settings/catalog.ts +39 -15
  75. package/packages/core/src/settings/engine.ts +48 -2
  76. package/packages/core/src/settings/hub.ts +83 -20
  77. package/packages/core/src/settings/open.ts +49 -0
  78. package/packages/core/src/settings/schema.ts +27 -7
  79. package/packages/core/src/tui/hub-kit.ts +18 -5
  80. package/packages/core/src/tui/kit.ts +198 -0
  81. package/packages/core/src/tui/progress.ts +73 -0
  82. package/packages/core/src/turn/arbiter.ts +290 -0
  83. package/packages/footer/README.md +4 -6
  84. package/packages/footer/package.json +3 -3
  85. package/packages/footer/src/glance-editor.ts +19 -11
  86. package/packages/footer/src/help.ts +1 -1
  87. package/packages/footer/src/index.ts +36 -3
  88. package/packages/footer/src/presets.ts +3 -4
  89. package/packages/footer/src/rendering/icons.ts +0 -20
  90. package/packages/footer/src/segments/compactor.ts +52 -142
  91. package/packages/footer/src/segments/status-ext.ts +0 -1
  92. package/packages/fusion/README.md +14 -4
  93. package/packages/fusion/package.json +4 -3
  94. package/packages/fusion/src/child-args.ts +1 -0
  95. package/packages/fusion/src/index.ts +161 -8
  96. package/packages/fusion/src/pi-settings.ts +57 -0
  97. package/packages/fusion/src/picker.ts +186 -51
  98. package/packages/fusion/src/preset.ts +56 -2
  99. package/packages/fusion/src/prompts.ts +1 -1
  100. package/packages/fusion/src/sidekick-runtime.ts +1 -420
  101. package/packages/fusion/src/tools.ts +107 -128
  102. package/packages/fusion/src/transcript.ts +27 -85
  103. package/packages/info-screen/package.json +2 -2
  104. package/packages/input-shortcuts/README.md +18 -30
  105. package/packages/input-shortcuts/package.json +2 -2
  106. package/packages/input-shortcuts/src/burst.ts +88 -0
  107. package/packages/input-shortcuts/src/chord-overlay.ts +20 -70
  108. package/packages/input-shortcuts/src/cleared-input.ts +97 -0
  109. package/packages/input-shortcuts/src/index.ts +99 -193
  110. package/packages/input-shortcuts/src/last-response.ts +40 -0
  111. package/packages/input-shortcuts/src/registers.ts +8 -23
  112. package/packages/input-shortcuts/src/types.ts +4 -16
  113. package/packages/input-shortcuts/src/undo-redo.ts +59 -47
  114. package/packages/kanboard/README.md +51 -47
  115. package/packages/kanboard/index.ts +293 -55
  116. package/packages/kanboard/package.json +8 -8
  117. package/packages/kanboard/skills/kanboard/SKILL.md +61 -27
  118. package/packages/kanboard/src/badges.ts +93 -0
  119. package/packages/kanboard/src/bin.ts +4 -2
  120. package/packages/kanboard/src/commands.ts +218 -84
  121. package/packages/kanboard/src/debug.ts +20 -0
  122. package/packages/kanboard/src/guard.ts +267 -109
  123. package/packages/kanboard/src/monitor.ts +330 -0
  124. package/packages/kanboard/src/notice-buffer.ts +74 -0
  125. package/packages/kanboard/src/progress.ts +27 -0
  126. package/packages/kanboard/src/reminders.ts +234 -0
  127. package/packages/kanboard/src/settings.ts +69 -15
  128. package/packages/kanboard/src/shapes.ts +5 -0
  129. package/packages/long-horizon/index.ts +190 -13
  130. package/packages/long-horizon/package.json +3 -3
  131. package/packages/long-horizon/src/commands.ts +103 -7
  132. package/packages/long-horizon/src/compaction-brief.ts +35 -0
  133. package/packages/long-horizon/src/engine/continuation.ts +84 -15
  134. package/packages/long-horizon/src/engine/goal-state.ts +64 -13
  135. package/packages/long-horizon/src/engine/nudge-stash.ts +71 -0
  136. package/packages/long-horizon/src/engine/ralph.ts +3 -2
  137. package/packages/long-horizon/src/engine/runaway.ts +68 -11
  138. package/packages/long-horizon/src/engine/verifier.ts +19 -0
  139. package/packages/long-horizon/src/gate.ts +37 -12
  140. package/packages/long-horizon/src/judge/resolve.ts +1 -0
  141. package/packages/long-horizon/src/owner.ts +35 -2
  142. package/packages/long-horizon/src/progress.ts +87 -0
  143. package/packages/long-horizon/src/prompts/goal.ts +1 -1
  144. package/packages/long-horizon/src/runtime.ts +172 -18
  145. package/packages/long-horizon/src/settings.ts +54 -39
  146. package/packages/long-horizon/src/tools/goal.ts +6 -0
  147. package/packages/long-horizon/src/tools/graph.ts +1 -1
  148. package/packages/long-horizon/src/tools/swarm.ts +3 -3
  149. package/packages/mcp/package.json +2 -2
  150. package/packages/memory/commands.ts +7 -2
  151. package/packages/memory/index.ts +210 -32
  152. package/packages/memory/package.json +3 -3
  153. package/packages/memory/save-session.ts +264 -0
  154. package/packages/memory/settings.ts +17 -0
  155. package/packages/memory/tools.ts +253 -203
  156. package/packages/notify/package.json +2 -2
  157. package/packages/skill-registry/README.md +53 -16
  158. package/packages/skill-registry/index.ts +230 -0
  159. package/packages/skill-registry/package.json +19 -8
  160. package/packages/skill-registry/src/editor.ts +206 -0
  161. package/packages/skill-registry/src/judge.ts +289 -0
  162. package/packages/skill-registry/src/registry.ts +87 -0
  163. package/packages/skill-registry/src/settings.ts +259 -0
  164. package/packages/skill-registry/src/vault.ts +80 -0
  165. package/packages/subagents/README.md +39 -119
  166. package/packages/subagents/package.json +6 -13
  167. package/packages/subagents/skills/subagents/SKILL.md +18 -42
  168. package/packages/subagents/src/agents.ts +213 -0
  169. package/packages/subagents/src/cards.ts +182 -0
  170. package/packages/subagents/src/index.ts +609 -1084
  171. package/packages/subagents/src/manager.ts +429 -0
  172. package/packages/subagents/src/profiles.ts +130 -0
  173. package/packages/subagents/src/transcript.ts +154 -0
  174. package/packages/subagents/src/ui.ts +389 -0
  175. package/packages/unipi/bundled.js +39756 -45569
  176. package/packages/unipi/index.ts +55 -10
  177. package/packages/updater/package.json +2 -2
  178. package/packages/utility/README.md +76 -69
  179. package/packages/utility/package.json +2 -2
  180. package/packages/utility/skills/image/SKILL.md +37 -0
  181. package/packages/utility/skills/utility/SKILL.md +17 -60
  182. package/packages/utility/src/answer/extract.ts +128 -0
  183. package/packages/utility/src/answer/index.ts +213 -0
  184. package/packages/utility/src/answer/reply.ts +133 -0
  185. package/packages/utility/src/answer/web.ts +167 -0
  186. package/packages/utility/src/attach/index.ts +205 -0
  187. package/packages/utility/src/commands.ts +38 -142
  188. package/packages/utility/src/diagnostics/engine.ts +50 -5
  189. package/packages/utility/src/image/index.ts +33 -0
  190. package/packages/utility/src/image/models.ts +221 -0
  191. package/packages/{image/src → utility/src/image}/recognize.ts +2 -2
  192. package/packages/utility/src/image/settings.ts +178 -0
  193. package/packages/{image/src/image-source.ts → utility/src/image/source.ts} +1 -1
  194. package/packages/utility/src/image/tools.ts +168 -0
  195. package/packages/utility/src/image/transports.ts +186 -0
  196. package/packages/utility/src/index.ts +68 -389
  197. package/packages/utility/src/lifecycle/cleanup.ts +116 -311
  198. package/packages/utility/src/rename/gate.ts +102 -0
  199. package/packages/utility/src/rename/index.ts +191 -0
  200. package/packages/utility/src/rename/session.ts +170 -0
  201. package/packages/utility/src/render/delegated.ts +285 -0
  202. package/packages/utility/src/render/harness.ts +683 -0
  203. package/packages/utility/src/render/parse.ts +156 -0
  204. package/packages/utility/src/render/pi-settings.ts +38 -0
  205. package/packages/utility/src/render/reply-bg.ts +307 -0
  206. package/packages/utility/src/render/simple.ts +724 -0
  207. package/packages/utility/src/render/spacing.ts +235 -0
  208. package/packages/utility/src/render/styled.ts +251 -0
  209. package/packages/utility/src/render/tools.ts +353 -0
  210. package/packages/utility/src/settings.ts +166 -233
  211. package/packages/utility/src/types.ts +1 -222
  212. package/packages/watchdog/index.ts +17 -6
  213. package/packages/watchdog/package.json +3 -3
  214. package/packages/watchdog/src/config.ts +3 -2
  215. package/packages/web-api/package.json +2 -2
  216. package/packages/workflow/README.md +3 -0
  217. package/packages/workflow/index.ts +0 -2
  218. package/packages/workflow/package.json +2 -2
  219. package/packages/workflow/src/permission/decide.ts +6 -4
  220. package/packages/workflow/src/permission/index.ts +17 -7
  221. package/packages/workflow/src/permission/settings.ts +39 -4
  222. package/packages/workflow/src/plan/index.ts +19 -4
  223. package/packages/background-tasks/extensions/delegate-child.ts +0 -1
  224. package/packages/background-tasks/src/context-parent-snapshot.ts +0 -142
  225. package/packages/background-tasks/src/context-token-budget.ts +0 -903
  226. package/packages/background-tasks/src/context-visible-conversation-v2.ts +0 -551
  227. package/packages/background-tasks/src/delegate/artifacts.ts +0 -487
  228. package/packages/background-tasks/src/delegate/budget.ts +0 -415
  229. package/packages/background-tasks/src/delegate/hook-contract-evidence.json +0 -18
  230. package/packages/background-tasks/src/delegate/hook-contract.ts +0 -154
  231. package/packages/background-tasks/src/delegate/launch.ts +0 -484
  232. package/packages/background-tasks/src/delegate/result-package.ts +0 -459
  233. package/packages/background-tasks/src/delegate/runner.ts +0 -430
  234. package/packages/background-tasks/src/delegate/seed.ts +0 -423
  235. package/packages/background-tasks/src/delegate/types.ts +0 -323
  236. package/packages/background-tasks/src/delegate-child-extension.ts +0 -978
  237. package/packages/background-tasks/src/delegate-extension.ts +0 -654
  238. package/packages/background-tasks/src/fixtures/delegate-context-incident.json +0 -17
  239. package/packages/compactor/skills/compactor-detail/SKILL.md +0 -116
  240. package/packages/compactor/skills/compactor-doctor/SKILL.md +0 -71
  241. package/packages/compactor/skills/compactor-stats/SKILL.md +0 -51
  242. package/packages/compactor/src/compaction/build-sections.ts +0 -76
  243. package/packages/compactor/src/compaction/extract/goals.ts +0 -36
  244. package/packages/compactor/src/compaction/extract/preferences.ts +0 -40
  245. package/packages/compactor/src/compaction/format.ts +0 -53
  246. package/packages/compactor/src/compaction/merge.ts +0 -143
  247. package/packages/compactor/src/config/presets.ts +0 -160
  248. package/packages/compactor/src/executor/executor.ts +0 -233
  249. package/packages/compactor/src/executor/runtime.ts +0 -115
  250. package/packages/compactor/src/security/evaluator.ts +0 -89
  251. package/packages/compactor/src/security/policy.ts +0 -96
  252. package/packages/compactor/src/security/scanner.ts +0 -65
  253. package/packages/compactor/src/session/auto-inject.ts +0 -60
  254. package/packages/compactor/src/session/db.ts +0 -325
  255. package/packages/compactor/src/session/extract.ts +0 -144
  256. package/packages/compactor/src/session/resume-inject.ts +0 -64
  257. package/packages/compactor/src/session/snapshot.ts +0 -327
  258. package/packages/compactor/src/tools/ctx-batch-execute.ts +0 -41
  259. package/packages/compactor/src/tools/ctx-execute-file.ts +0 -23
  260. package/packages/compactor/src/tools/ctx-execute.ts +0 -23
  261. package/packages/compactor/src/tools/ctx-stats.ts +0 -96
  262. package/packages/image/README.md +0 -99
  263. package/packages/image/package.json +0 -61
  264. package/packages/image/skills/image/SKILL.md +0 -76
  265. package/packages/image/src/generate.ts +0 -256
  266. package/packages/image/src/index.ts +0 -135
  267. package/packages/image/src/models.ts +0 -519
  268. package/packages/image/src/openai-images-api.ts +0 -282
  269. package/packages/image/src/register-providers.ts +0 -209
  270. package/packages/image/src/settings.ts +0 -173
  271. package/packages/image/src/tools.ts +0 -326
  272. package/packages/input-shortcuts/src/clipboard.ts +0 -119
  273. package/packages/kanboard/src/runner.ts +0 -817
  274. package/packages/skill-registry/skills/auto/SKILL.md +0 -465
  275. package/packages/skill-registry/skills/brainstorm/SKILL.md +0 -219
  276. package/packages/skill-registry/skills/chore-create/SKILL.md +0 -315
  277. package/packages/skill-registry/skills/chore-execute/SKILL.md +0 -314
  278. package/packages/skill-registry/skills/consolidate/SKILL.md +0 -142
  279. package/packages/skill-registry/skills/consultant/SKILL.md +0 -97
  280. package/packages/skill-registry/skills/debug/SKILL.md +0 -228
  281. package/packages/skill-registry/skills/document/SKILL.md +0 -120
  282. package/packages/skill-registry/skills/fix/SKILL.md +0 -212
  283. package/packages/skill-registry/skills/gather-context/SKILL.md +0 -145
  284. package/packages/skill-registry/skills/plan/SKILL.md +0 -231
  285. package/packages/skill-registry/skills/quick-fix/SKILL.md +0 -135
  286. package/packages/skill-registry/skills/quick-work/SKILL.md +0 -110
  287. package/packages/skill-registry/skills/research/SKILL.md +0 -251
  288. package/packages/skill-registry/skills/review-work/SKILL.md +0 -187
  289. package/packages/skill-registry/skills/scan-issues/SKILL.md +0 -195
  290. package/packages/skill-registry/skills/work/SKILL.md +0 -218
  291. package/packages/skill-registry/skills/worktree-create/SKILL.md +0 -69
  292. package/packages/skill-registry/skills/worktree-list/SKILL.md +0 -78
  293. package/packages/skill-registry/skills/worktree-merge/SKILL.md +0 -89
  294. package/packages/subagents/agents/delegate.md +0 -14
  295. package/packages/subagents/agents/oracle.md +0 -78
  296. package/packages/subagents/agents/researcher.md +0 -52
  297. package/packages/subagents/agents/reviewer.md +0 -80
  298. package/packages/subagents/agents/scout.md +0 -50
  299. package/packages/subagents/agents/worker.md +0 -59
  300. package/packages/subagents/prompts/council.md +0 -48
  301. package/packages/subagents/prompts/gather-context-and-clarify.md +0 -13
  302. package/packages/subagents/prompts/parallel-cleanup.md +0 -59
  303. package/packages/subagents/prompts/parallel-research.md +0 -50
  304. package/packages/subagents/prompts/parallel-review.md +0 -54
  305. package/packages/subagents/prompts/review-loop.md +0 -43
  306. package/packages/subagents/skills/council-mode/SKILL.md +0 -230
  307. package/packages/subagents/skills/subagents/references/constraints-and-recipes.md +0 -259
  308. package/packages/subagents/skills/subagents/references/execution-controls.md +0 -454
  309. package/packages/subagents/skills/subagents/references/management-authoring-rpc.md +0 -161
  310. package/packages/subagents/skills/subagents/references/multi-lane-orchestration.md +0 -39
  311. package/packages/subagents/skills/subagents/references/prompting-and-roles.md +0 -267
  312. package/packages/subagents/src/acceptance.ts +0 -331
  313. package/packages/subagents/src/agent-manager.ts +0 -405
  314. package/packages/subagents/src/agent-memory.ts +0 -300
  315. package/packages/subagents/src/agent-overrides.ts +0 -183
  316. package/packages/subagents/src/agent-runner.ts +0 -271
  317. package/packages/subagents/src/async-runner.ts +0 -422
  318. package/packages/subagents/src/authority-policy.ts +0 -47
  319. package/packages/subagents/src/budgets.ts +0 -285
  320. package/packages/subagents/src/child-safety.ts +0 -140
  321. package/packages/subagents/src/config.ts +0 -249
  322. package/packages/subagents/src/conversation-viewer.ts +0 -281
  323. package/packages/subagents/src/core-compat.ts +0 -94
  324. package/packages/subagents/src/custom-agents.ts +0 -343
  325. package/packages/subagents/src/file-system-retry.ts +0 -50
  326. package/packages/subagents/src/fleet-data.ts +0 -105
  327. package/packages/subagents/src/fleet-view.ts +0 -322
  328. package/packages/subagents/src/foreground-detach.ts +0 -59
  329. package/packages/subagents/src/fork-context.ts +0 -285
  330. package/packages/subagents/src/global.d.ts +0 -7
  331. package/packages/subagents/src/guide.ts +0 -129
  332. package/packages/subagents/src/mission-state.ts +0 -133
  333. package/packages/subagents/src/mission-store.ts +0 -436
  334. package/packages/subagents/src/output-limits.ts +0 -142
  335. package/packages/subagents/src/parity-types.ts +0 -315
  336. package/packages/subagents/src/pi-args.ts +0 -167
  337. package/packages/subagents/src/result-files.ts +0 -232
  338. package/packages/subagents/src/result-watcher.ts +0 -221
  339. package/packages/subagents/src/retained-children.ts +0 -176
  340. package/packages/subagents/src/run-fanout-budget.ts +0 -356
  341. package/packages/subagents/src/scheduled-runs.ts +0 -349
  342. package/packages/subagents/src/schemas.ts +0 -263
  343. package/packages/subagents/src/slash-commands.ts +0 -80
  344. package/packages/subagents/src/supervisor-channel.ts +0 -249
  345. package/packages/subagents/src/tool-handler.ts +0 -1144
  346. package/packages/subagents/src/types.ts +0 -238
  347. package/packages/subagents/src/widget.ts +0 -457
  348. package/packages/subagents/src/workflow-script.ts +0 -737
  349. package/packages/subagents/src/workflow-worker.ts +0 -384
  350. package/packages/subagents/src/worktree.ts +0 -614
  351. package/packages/utility/src/analytics/collector.ts +0 -293
  352. package/packages/utility/src/info-screen.ts +0 -80
  353. package/packages/utility/src/lifecycle/process.ts +0 -162
  354. package/packages/utility/src/prefix-cache.ts +0 -263
  355. package/packages/utility/src/skill-discovery.ts +0 -542
  356. package/packages/utility/src/tools/env.ts +0 -113
  357. package/packages/utility/src/tui/name-badge-state.ts +0 -315
  358. package/packages/utility/src/tui/name-badge.ts +0 -109
  359. /package/packages/{subagents/src → core/src/child-agent}/pi-spawn.ts +0 -0
@@ -1,737 +0,0 @@
1
- /**
2
- * @pi-unipi/subagents — workflowScript host runtime
3
- *
4
- * Ported from pi-subagents src/workflows/scripted-workflow.ts (host half).
5
- * Spawns the sandbox worker, routes RPC calls (run/all/steer/status/state) to
6
- * host callbacks, tracks children + trace, enforces the unawaited-launch
7
- * contract, and resolves with { value, emits, console, trace, children }.
8
- *
9
- * The launch callback is OURS: in-process AgentManager.spawn (foreground) —
10
- * Phase 3 swaps in the process-based runner for async workflows.
11
- */
12
-
13
- import { Worker } from "node:worker_threads";
14
- import { createRequire } from "node:module";
15
- import { readFileSync } from "node:fs";
16
- import { dirname, resolve as resolvePath } from "node:path";
17
- import { fileURLToPath } from "node:url";
18
-
19
- const requireFromPackage = createRequire(import.meta.url);
20
-
21
- export interface WorkflowScriptTraceEntry {
22
- operation: "run" | "steer" | "status";
23
- key: string;
24
- state: string;
25
- durationMs?: number;
26
- phase?: string;
27
- label?: string;
28
- agent?: string;
29
- runId?: string;
30
- error?: string;
31
- }
32
-
33
- export interface WorkflowScriptChildResult {
34
- key: string;
35
- ok: boolean;
36
- output: string;
37
- error?: string;
38
- detached?: boolean;
39
- runId?: string;
40
- agent?: string;
41
- artifactPaths?: string[];
42
- [extra: string]: unknown;
43
- }
44
-
45
- export interface WorkflowSteerResult {
46
- key: string;
47
- state: "queued" | "delivered" | "missed" | "failed";
48
- requestId?: string;
49
- error?: string;
50
- }
51
-
52
- export interface WorkflowScriptResult {
53
- value: unknown;
54
- emits: unknown[];
55
- console: Array<{ level: "log" | "info" | "warn" | "error"; text: string }>;
56
- trace: WorkflowScriptTraceEntry[];
57
- children: WorkflowScriptChildResult[];
58
- }
59
-
60
- export class WorkflowScriptError extends Error {
61
- readonly partial: Omit<WorkflowScriptResult, "value">;
62
-
63
- constructor(message: string, partial: Omit<WorkflowScriptResult, "value">) {
64
- super(message);
65
- this.name = "WorkflowScriptError";
66
- this.partial = partial;
67
- }
68
- }
69
-
70
- export interface RunWorkflowScriptOptions {
71
- script: string;
72
- timeoutMs?: number;
73
- signal?: AbortSignal;
74
- /** Spawn-budget admission hook (called before children start; may throw). */
75
- admit?: (calls: Array<{ key: string; params: Record<string, unknown> }>) => void | Promise<void>;
76
- /** OUR launch path: in-process foreground spawn (Phase 3: process runner). */
77
- launch: (
78
- key: string,
79
- params: Record<string, unknown>,
80
- signal: AbortSignal,
81
- admission: { admitted: boolean },
82
- ) => Promise<WorkflowScriptChildResult>;
83
- status: (keyOrRunId: string, signal: AbortSignal) => Promise<WorkflowScriptChildResult>;
84
- steer?: (
85
- key: string,
86
- message: string,
87
- options: { mode?: string; index?: number; ackTimeoutMs?: number },
88
- signal: AbortSignal,
89
- ) => Promise<WorkflowSteerResult>;
90
- state?: {
91
- get: (key: string) => unknown | Promise<unknown>;
92
- set: (key: string, value: unknown) => void | Promise<void>;
93
- };
94
- onTrace?: (trace: WorkflowScriptTraceEntry[]) => void;
95
- onEmit?: (emits: unknown[]) => void;
96
- }
97
-
98
- function isRecord(value: unknown): value is Record<string, unknown> {
99
- return !!value && typeof value === "object" && !Array.isArray(value);
100
- }
101
-
102
- function isPlainJsonObject(value: unknown): value is Record<string, unknown> {
103
- if (!isRecord(value)) return false;
104
- const prototype = Object.getPrototypeOf(value);
105
- return prototype === null || prototype === Object.prototype;
106
- }
107
-
108
- export function assertWorkflowJsonValue(value: unknown, path = "value", seen = new Set<object>()): void {
109
- if (value === null || typeof value === "string" || typeof value === "boolean") return;
110
- if (typeof value === "number") {
111
- if (!Number.isFinite(value)) throw new Error(`${path} must contain only finite JSON numbers.`);
112
- return;
113
- }
114
- if (typeof value !== "object") throw new Error(`${path} must be a JSON value; received ${typeof value}.`);
115
- if (seen.has(value)) throw new Error(`${path} must not contain cycles.`);
116
- seen.add(value);
117
- if (Array.isArray(value)) {
118
- for (let index = 0; index < value.length; index++) {
119
- if (!Object.hasOwn(value, index)) throw new Error(`${path} must not contain sparse array entries.`);
120
- assertWorkflowJsonValue(value[index], `${path}[${index}]`, seen);
121
- }
122
- } else {
123
- const prototype = Object.getPrototypeOf(value);
124
- if (prototype !== null && prototype !== Object.prototype) {
125
- throw new Error(`${path} must contain only plain JSON objects.`);
126
- }
127
- if (Object.getOwnPropertySymbols(value).length > 0) {
128
- throw new Error(`${path} must not contain symbol keys.`);
129
- }
130
- for (const [key, entry] of Object.entries(value)) {
131
- assertWorkflowJsonValue(entry, `${path}.${key}`, seen);
132
- }
133
- }
134
- seen.delete(value);
135
- }
136
-
137
- export function formatWorkflowJsonPreview(value: unknown, maxLength: number): string | undefined {
138
- try {
139
- assertWorkflowJsonValue(value);
140
- const serialized = JSON.stringify(value);
141
- return typeof serialized === "string" ? serialized.slice(0, maxLength) : undefined;
142
- } catch {
143
- return undefined;
144
- }
145
- }
146
-
147
- export interface SimpleWorkflowRunPreview {
148
- agent?: string;
149
- task?: string;
150
- }
151
-
152
- /** Display-only preview for the exact simple `return runs.run(key, {...})` form. */
153
- export function previewSimpleWorkflowRun(script: string | undefined): SimpleWorkflowRunPreview | undefined {
154
- const body = script
155
- ?.match(/^\s*return\s+(?:await\s+)?runs\.run\s*\(\s*(?:"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|`[^`$\\]*`)\s*,\s*\{([\s\S]*)\}\s*\)\s*;?\s*$/)
156
- ?.[1];
157
- if (body === undefined) return undefined;
158
- const readProperty = (name: "agent" | "task"): string | undefined => {
159
- const match = body.match(
160
- new RegExp(`(?:^|,)\\s*(?:${name}|["']${name}["'])\\s*:\\s*("(?:\\\\.|[^"\\\\])*"|'(?:\\\\.|[^'\\\\])*'|\u0060[^\u0060$\\\\]*\u0060)`),
161
- );
162
- if (!match?.[1]) return undefined;
163
- const literal = match[1];
164
- if (literal.startsWith('"')) {
165
- try {
166
- return JSON.parse(literal) as string;
167
- } catch {
168
- return undefined;
169
- }
170
- }
171
- if (literal.slice(1, -1).includes("\\")) return undefined;
172
- return literal.slice(1, -1);
173
- };
174
- const agent = readProperty("agent");
175
- const task = readProperty("task");
176
- return { ...(agent !== undefined ? { agent } : {}), ...(task !== undefined ? { task } : {}) };
177
- }
178
-
179
- function stableJson(value: unknown): string {
180
- if (Array.isArray(value)) return `[${value.map(stableJson).join(",")}]`;
181
- if (isRecord(value)) {
182
- return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${stableJson(value[key])}`).join(",")}}`;
183
- }
184
- return JSON.stringify(value) ?? "undefined";
185
- }
186
-
187
- function omitUndefinedWorkflowValues(value: unknown, seen = new Set<object>()): unknown {
188
- if (value === null || typeof value !== "object") return value;
189
- if (seen.has(value)) return value;
190
- seen.add(value);
191
- const normalized = Array.isArray(value)
192
- ? value.map((entry) => (entry === undefined ? null : omitUndefinedWorkflowValues(entry, seen)))
193
- : isPlainJsonObject(value)
194
- ? Object.fromEntries(
195
- Object.entries(value).flatMap(([key, entry]) =>
196
- entry === undefined ? [] : [[key, omitUndefinedWorkflowValues(entry, seen)]],
197
- ),
198
- )
199
- : value;
200
- seen.delete(value);
201
- return normalized;
202
- }
203
-
204
- function omitNonJsonWorkflowResultMetadata(value: unknown): unknown {
205
- const normalized = omitUndefinedWorkflowValues(value);
206
- if (!isPlainJsonObject(normalized) || !Object.hasOwn(normalized, "results")) return normalized;
207
- try {
208
- assertWorkflowJsonValue(normalized.results, "runs.run result.results");
209
- return normalized;
210
- } catch {
211
- const { results: _results, ...safeResult } = normalized;
212
- return safeResult;
213
- }
214
- }
215
-
216
- const KEY_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
217
-
218
- function validateKey(value: unknown, owner = "runs.run"): string {
219
- if (typeof value !== "string" || !KEY_PATTERN.test(value)) {
220
- throw new Error(`${owner} key must be 1-128 characters using letters, numbers, '.', '_' or '-', and start with a letter or number.`);
221
- }
222
- return value;
223
- }
224
-
225
- function workflowStringMetadata(params: Record<string, unknown>): Pick<WorkflowScriptTraceEntry, "phase" | "label" | "agent"> {
226
- return {
227
- ...(typeof params.phase === "string" && params.phase.trim() ? { phase: params.phase.trim() } : {}),
228
- ...(typeof params.label === "string" && params.label.trim() ? { label: params.label.trim() } : {}),
229
- ...(typeof params.agent === "string" && params.agent.trim() ? { agent: params.agent.trim() } : {}),
230
- };
231
- }
232
-
233
- /** Resolve acorn robustly (bare specifier, then package.json main). */
234
- function resolveWorkflowParserEntry(): string {
235
- try {
236
- return requireFromPackage.resolve("acorn");
237
- } catch (primaryError) {
238
- try {
239
- const manifestPath = requireFromPackage.resolve("acorn/package.json");
240
- const manifest = JSON.parse(readFileSync(manifestPath, "utf8")) as { main?: unknown };
241
- const entry = typeof manifest.main === "string" && manifest.main ? manifest.main : "./dist/acorn.js";
242
- return resolvePath(dirname(manifestPath), entry);
243
- } catch {
244
- throw primaryError;
245
- }
246
- }
247
- }
248
-
249
- /** Worker source: compiled .js in published installs, .ts under jiti/tsx (transpiled inline). */
250
- function loadWorkerSource(): string {
251
- const base = resolvePath(dirname(fileURLToPath(import.meta.url)), "workflow-worker");
252
- for (const candidate of [`${base}.js`, `${base}.ts`]) {
253
- try {
254
- return readFileSync(candidate, "utf8");
255
- } catch {
256
- // try next
257
- }
258
- }
259
- throw new Error("workflow-worker source not found (expected workflow-worker.js or .ts)");
260
- }
261
-
262
- export async function runWorkflowScript(options: RunWorkflowScriptOptions): Promise<WorkflowScriptResult> {
263
- if (!options.script.trim()) throw new Error("workflowScript must not be empty.");
264
- if (options.timeoutMs !== undefined && (!Number.isInteger(options.timeoutMs) || options.timeoutMs < 1)) {
265
- throw new Error("workflow script timeout must be a positive integer.");
266
- }
267
-
268
- let acornPath: string;
269
- try {
270
- acornPath = resolveWorkflowParserEntry();
271
- } catch (error) {
272
- throw new Error(
273
- "Workflow parser dependency 'acorn' is unavailable from @pi-unipi/subagents. Reinstall dependencies before launching workflowScript.",
274
- { cause: error },
275
- );
276
- }
277
-
278
- const worker = new Worker(loadWorkerSource(), { eval: true, workerData: { acornPath } });
279
- const emits: unknown[] = [];
280
- const consoleEntries: WorkflowScriptResult["console"] = [];
281
- const trace: WorkflowScriptTraceEntry[] = [];
282
- const children = new Map<string, WorkflowScriptChildResult>();
283
- const childOrder: string[] = [];
284
- const launches = new Map<string, { fingerprint: string; promise: Promise<WorkflowScriptChildResult>; observed: boolean }>();
285
- const steers = new Map<number, { key: string; promise: Promise<WorkflowSteerResult>; observed: boolean }>();
286
- const stoppedLaunches = new Set<string>();
287
- const batchAdmissions = new Map<string, Promise<void>>();
288
- const childController = new AbortController();
289
- let settled = false;
290
- let finishing = false;
291
-
292
- const partial = (): Omit<WorkflowScriptResult, "value"> => ({
293
- emits,
294
- console: consoleEntries,
295
- trace,
296
- children: childOrder.flatMap((key) => {
297
- const child = children.get(key);
298
- return child ? [child] : [];
299
- }),
300
- });
301
-
302
- const traceChanged = () => {
303
- try {
304
- options.onTrace?.([...trace]);
305
- } catch (error) {
306
- console.error("Workflow onTrace callback failed:", error);
307
- }
308
- };
309
-
310
- return await new Promise<WorkflowScriptResult>((resolve, reject) => {
311
- const finish = (outcome: { value: unknown } | { error: Error }) => {
312
- if (settled || finishing) return;
313
- finishing = true;
314
- childController.abort("error" in outcome ? outcome.error : new Error("Workflow script completed."));
315
- void Promise.allSettled([...steers.values()].map(({ promise }) => promise)).then(() => {
316
- if (settled) return;
317
- settled = true;
318
- if (timer) clearTimeout(timer);
319
- options.signal?.removeEventListener("abort", onAbort);
320
- void worker.terminate();
321
- const unobservedKeys =
322
- "value" in outcome ? [...launches].filter(([, launch]) => !launch.observed).map(([key]) => key) : [];
323
- const completionError =
324
- unobservedKeys.length > 0
325
- ? new Error(
326
- `workflowScript completed with unawaited runs.run launch(es): ${unobservedKeys.map((key) => `'${key}'`).join(", ")}. For ordinary parallel fanout use await runs.all([{key, agent, task}, ...]); do not read .output from unawaited launches.`,
327
- )
328
- : "value" in outcome
329
- ? (() => {
330
- const unobservedSteers = [...steers.values()].filter((steer) => !steer.observed).map((steer) => steer.key);
331
- return unobservedSteers.length > 0
332
- ? new Error(`workflowScript completed with unawaited runs.steer call(s): ${unobservedSteers.map((key) => `'${key}'`).join(", ")}. Await or return each call.`)
333
- : undefined;
334
- })()
335
- : undefined;
336
- if ("error" in outcome) reject(new WorkflowScriptError(outcome.error.message, partial()));
337
- else if (completionError) reject(new WorkflowScriptError(completionError.message, partial()));
338
- else resolve({ value: outcome.value, ...partial() });
339
- });
340
- };
341
- const onAbort = () => {
342
- const signalReason = options.signal?.reason;
343
- const error =
344
- signalReason instanceof Error
345
- ? signalReason
346
- : typeof signalReason === "string"
347
- ? new Error(signalReason)
348
- : new Error("Workflow script aborted.");
349
- for (const key of launches.keys()) {
350
- if (children.has(key)) continue;
351
- stoppedLaunches.add(key);
352
- const started = trace.findLast(
353
- (entry) => entry.operation === "run" && entry.key === key && entry.state === "started",
354
- );
355
- trace.push({
356
- operation: "run",
357
- key,
358
- state: "stopped",
359
- ...(started?.agent ? { agent: started.agent } : {}),
360
- ...(started?.phase ? { phase: started.phase } : {}),
361
- ...(started?.label ? { label: started.label } : {}),
362
- error: error.message,
363
- });
364
- }
365
- traceChanged();
366
- finish({ error });
367
- };
368
- const timer =
369
- options.timeoutMs === undefined
370
- ? undefined
371
- : setTimeout(() => finish({ error: new Error(`Workflow script timed out after ${options.timeoutMs}ms.`) }), options.timeoutMs);
372
- options.signal?.addEventListener("abort", onAbort, { once: true });
373
- if (options.signal?.aborted) return onAbort();
374
-
375
- worker.on("error", (error) =>
376
- finish({ error: new Error(`Workflow worker failed: ${error instanceof Error ? error.message : String(error)}`) }),
377
- );
378
- worker.on("exit", (code) => {
379
- if (!settled && code !== 0) finish({ error: new Error(`Workflow worker exited with code ${code}.`) });
380
- });
381
-
382
-
383
- worker.on("message", (msg: Record<string, unknown>) => {
384
- if (settled) return;
385
- if (msg.type === "emit") {
386
- try {
387
- assertWorkflowJsonValue(msg.value, "emit");
388
- } catch (error) {
389
- finish({ error: new Error(`Workflow emit could not be persisted: ${error instanceof Error ? error.message : String(error)}`) });
390
- return;
391
- }
392
- emits.push(msg.value);
393
- try {
394
- options.onEmit?.([...emits]);
395
- } catch (error) {
396
- emits.pop();
397
- finish({ error: new Error(`Workflow emit could not be persisted: ${error instanceof Error ? error.message : String(error)}`) });
398
- }
399
- return;
400
- }
401
- if (msg.type === "console") {
402
- const level = msg.level;
403
- if ((level === "log" || level === "info" || level === "warn" || level === "error") && typeof msg.text === "string") {
404
- consoleEntries.push({ level, text: msg.text });
405
- }
406
- return;
407
- }
408
- if (msg.type === "complete") {
409
- try {
410
- assertWorkflowJsonValue(msg.value, "return");
411
- } catch (error) {
412
- return finish({ error: new Error(`Workflow return could not be persisted: ${error instanceof Error ? error.message : String(error)}`) });
413
- }
414
- return finish({ value: msg.value });
415
- }
416
- if (msg.type === "error") {
417
- return finish({ error: new Error(typeof msg.error === "string" ? msg.error : "Workflow script failed.") });
418
- }
419
- if (msg.type === "callObserved" && typeof msg.callId === "number") {
420
- if (msg.operation === "steer") {
421
- const steer = steers.get(msg.callId);
422
- if (steer) steer.observed = true;
423
- }
424
- // run/all observations are tracked via the launches map by key.
425
- return;
426
- }
427
- if (msg.type !== "call" || typeof msg.callId !== "number" || typeof msg.method !== "string" || !isRecord(msg.args)) {
428
- return;
429
- }
430
-
431
- const respond = (promise: Promise<unknown>, responsePath?: string) => {
432
- void promise.then(
433
- (value) => {
434
- if (settled) return;
435
- const normalized = responsePath ? omitNonJsonWorkflowResultMetadata(value) : omitUndefinedWorkflowValues(value);
436
- if (!responsePath) {
437
- worker.postMessage({ type: "response", callId: msg.callId, ok: true, value: normalized });
438
- return;
439
- }
440
- try {
441
- assertWorkflowJsonValue(normalized, responsePath);
442
- worker.postMessage({ type: "response", callId: msg.callId, ok: true, value: normalized });
443
- } catch (error) {
444
- worker.postMessage({
445
- type: "response",
446
- callId: msg.callId,
447
- ok: false,
448
- error: `${responsePath} must contain only JSON data before it can be returned from workflowScript. Return a plain projection such as { runId, ok, output }. ${error instanceof Error ? error.message : String(error)}`,
449
- });
450
- }
451
- },
452
- (error: unknown) => {
453
- if (!settled) {
454
- worker.postMessage({
455
- type: "response",
456
- callId: msg.callId,
457
- ok: false,
458
- error: error instanceof Error ? error.message : String(error),
459
- });
460
- }
461
- },
462
- );
463
- };
464
-
465
- if (msg.method === "state.get" || msg.method === "state.set") {
466
- if (!options.state) return respond(Promise.reject(new Error("Workflow state is unavailable without a mission.")));
467
- let key: string;
468
- try {
469
- key = validateKey(msg.args.key, "state");
470
- } catch (error) {
471
- return respond(Promise.reject(error));
472
- }
473
- if (msg.method === "state.get") return respond(Promise.resolve().then(() => options.state!.get(key)));
474
- const value = msg.args.value;
475
- try {
476
- assertWorkflowJsonValue(value, `state.set('${key}') value`);
477
- } catch (error) {
478
- return respond(Promise.reject(error));
479
- }
480
- return respond(Promise.resolve().then(() => options.state!.set(key, value)));
481
- }
482
-
483
- if (msg.method === "status") {
484
- const keyOrRunId = msg.args.keyOrRunId;
485
- if (typeof keyOrRunId !== "string" || !keyOrRunId.trim()) {
486
- return respond(Promise.reject(new Error("runs.status(keyOrRunId) requires a non-empty string.")));
487
- }
488
- const known = children.get(keyOrRunId);
489
- const target = known?.runId ?? keyOrRunId;
490
- trace.push({ operation: "status", key: keyOrRunId, state: "started", ...(known?.runId ? { runId: known.runId } : {}) });
491
- traceChanged();
492
- if (settled || finishing) return;
493
- respond(
494
- options.status(target, childController.signal).then((result) => {
495
- if (settled || finishing) return result;
496
- trace.push({
497
- operation: "status",
498
- key: keyOrRunId,
499
- state: result.ok ? "completed" : "failed",
500
- ...(result.runId ? { runId: result.runId } : {}),
501
- ...(!result.ok ? { error: result.output } : {}),
502
- });
503
- traceChanged();
504
- if (!result.ok) throw new Error(`Status '${keyOrRunId}' failed: ${result.output}`);
505
- return result;
506
- }),
507
- );
508
- return;
509
- }
510
-
511
- if (msg.method === "steer") {
512
- let key: string;
513
- try {
514
- key = validateKey(msg.args.key, "runs.steer");
515
- } catch (error) {
516
- return respond(Promise.reject(error));
517
- }
518
- const steerMessage = msg.args.message;
519
- if (typeof steerMessage !== "string" || !steerMessage.trim()) {
520
- return respond(Promise.reject(new Error(`runs.steer('${key}') requires a non-empty message.`)));
521
- }
522
- const steerOptions = isRecord(msg.args.options) ? (msg.args.options as { mode?: string; index?: number; ackTimeoutMs?: number }) : {};
523
- const startedAt = Date.now();
524
- trace.push({ operation: "steer", key, state: "started" });
525
- traceChanged();
526
- const promise = Promise.resolve()
527
- .then(() => {
528
- if (!launches.has(key)) throw new Error(`runs.steer('${key}') requires a prior runs.run/runs.all launch with that key.`);
529
- if (!options.steer) throw new Error("Workflow steering is unavailable in this host.");
530
- return options.steer(key, steerMessage.trim(), steerOptions, childController.signal);
531
- })
532
- .then(
533
- (receipt) => {
534
- trace.push({ operation: "steer", key, state: receipt.state, durationMs: Date.now() - startedAt, ...(receipt.error ? { error: receipt.error } : {}) });
535
- traceChanged();
536
- return receipt;
537
- },
538
- (error: unknown) => {
539
- const text = error instanceof Error ? error.message : String(error);
540
- trace.push({ operation: "steer", key, state: "failed", durationMs: Date.now() - startedAt, error: text });
541
- traceChanged();
542
- throw error;
543
- },
544
- );
545
- steers.set(msg.callId, { key, promise, observed: false });
546
- respond(promise);
547
- return;
548
- }
549
-
550
- if (msg.method === "all") {
551
- // runs.all(...) is itself the observation: every child is awaited by the batch.
552
- // Batch launch: runs.all([...]) — admits the whole group atomically.
553
- const calls = Array.isArray(msg.args.calls) ? msg.args.calls : [];
554
- const valid = calls.filter(
555
- (call): call is { key: string; params: Record<string, unknown> } =>
556
- isRecord(call) && typeof call.key === "string" && isRecord(call.params),
557
- );
558
- const admission = Promise.resolve().then(() => {
559
- if (settled || finishing) return;
560
- return options.admit?.(valid);
561
- }).catch((error: unknown) => {
562
- // Admission failures (e.g. fanout budget) reject every child in the
563
- // batch; runs.all collects them as ordinary failures (reference
564
- // semantics: no partial starts, siblings report the rejection).
565
- const text = error instanceof Error ? error.message : String(error);
566
- for (const { key } of valid) {
567
- const failure: WorkflowScriptChildResult = { key, ok: false, output: text, error: text, artifactPaths: [] };
568
- children.set(key, failure);
569
- if (!childOrder.includes(key)) childOrder.push(key);
570
- }
571
- throw error;
572
- });
573
- const promises = valid.map(({ key, params }) =>
574
- admission.then(async () => {
575
- if (settled || finishing || stoppedLaunches.has(key)) {
576
- const reason = childController.signal.reason;
577
- const text = reason instanceof Error ? reason.message : typeof reason === "string" ? reason : "Workflow script aborted.";
578
- return { key, ok: false, output: text, error: text, artifactPaths: [] };
579
- }
580
- const startedAt = Date.now();
581
- return options.launch(key, { ...params, async: params.async ?? false }, childController.signal, { admitted: true }).then(
582
- (result) => {
583
- const normalized = !result.ok && !result.error ? { ...result, error: result.output } : result;
584
- children.set(key, normalized);
585
- childOrder.push(key);
586
- trace.push({
587
- operation: "run",
588
- key,
589
- state: normalized.ok ? "completed" : "failed",
590
- durationMs: Date.now() - startedAt,
591
- ...workflowStringMetadata(params),
592
- ...(normalized.agent ? { agent: normalized.agent } : {}),
593
- ...(normalized.runId ? { runId: normalized.runId } : {}),
594
- ...(!normalized.ok ? { error: normalized.error ?? normalized.output } : {}),
595
- });
596
- traceChanged();
597
- return normalized;
598
- },
599
- (error: unknown) => {
600
- const text = error instanceof Error ? error.message : String(error);
601
- const failure: WorkflowScriptChildResult = { key, ok: false, output: text, error: text, artifactPaths: [] };
602
- children.set(key, failure);
603
- childOrder.push(key);
604
- trace.push({ operation: "run", key, state: "failed", durationMs: Date.now() - startedAt, ...workflowStringMetadata(params), error: text });
605
- traceChanged();
606
- return failure;
607
- },
608
- );
609
- }, (error: unknown) => {
610
- // Admission rejection already recorded the failure per child; map
611
- // this arm to the same failure so Promise.all collects it.
612
- const text = error instanceof Error ? error.message : String(error);
613
- return { key, ok: false, output: text, error: text, artifactPaths: [] } satisfies WorkflowScriptChildResult;
614
- }),
615
- );
616
- // Mark all keys observed (runs.all is itself the observation).
617
- for (const { key } of valid) {
618
- const existing = launches.get(key);
619
- if (existing) existing.observed = true;
620
- }
621
- const batchPromise = Promise.all(promises).then((results) => {
622
- for (const result of results) {
623
- const entry = launches.get(result.key);
624
- if (entry) entry.observed = true;
625
- }
626
- return results;
627
- });
628
- for (const { key, params } of valid) {
629
- const fingerprint = stableJson(params);
630
- launches.set(key, { fingerprint, promise: batchPromise.then((rs) => rs.find((r) => r.key === key)!) , observed: true });
631
- }
632
- respond(batchPromise, "runs.all(...) results");
633
- return;
634
- }
635
-
636
- if (msg.method !== "run") return respond(Promise.reject(new Error(`Unknown runs API method '${msg.method}'.`)));
637
-
638
- let key: string;
639
- try {
640
- key = validateKey(msg.args.key);
641
- } catch (error) {
642
- return respond(Promise.reject(error));
643
- }
644
- const params = msg.args.params;
645
- if (!isRecord(params)) return respond(Promise.reject(new Error(`runs.run('${key}', params) requires a params object.`)));
646
- if (params.action !== undefined) return respond(Promise.reject(new Error(`runs.run('${key}') accepts execution params only; management action is not allowed.`)));
647
- if (params.workflowScript !== undefined) return respond(Promise.reject(new Error(`runs.run('${key}') cannot start a nested workflow script.`)));
648
- if (params.tasks !== undefined || params.chain !== undefined || params.parallel !== undefined || params.concurrency !== undefined) {
649
- return respond(Promise.reject(new Error(`runs.run('${key}') accepts one child via { agent, task }; use runs.all(...) and JavaScript control flow for orchestration.`)));
650
- }
651
- if (params.resume !== undefined && params.agent !== undefined) {
652
- return respond(Promise.reject(new Error(`runs.run('${key}') resume and agent are mutually exclusive.`)));
653
- }
654
- if (typeof params.resume === "string" && !params.resume.trim()) {
655
- return respond(Promise.reject(new Error(`runs.run('${key}') resume must be a non-empty retained run id.`)));
656
- }
657
- if (params.resume !== undefined && (typeof params.task !== "string" || !params.task.trim())) {
658
- return respond(Promise.reject(new Error(`runs.run('${key}') resume requires a non-empty task follow-up.`)));
659
- }
660
-
661
- const fingerprint = stableJson(params);
662
- const existing = launches.get(key);
663
- if (existing) {
664
- if (existing.fingerprint !== fingerprint) {
665
- return respond(Promise.reject(new Error(`Duplicate workflow key '${key}' used with incompatible launch params.`)));
666
- }
667
- existing.observed = true;
668
- trace.push({ operation: "run", key, state: "reused", ...workflowStringMetadata(params) });
669
- traceChanged();
670
- return respond(
671
- existing.promise.then((result) => {
672
- if (result.ok) return result;
673
- throw new Error(`Run '${key}' failed: ${result.error ?? result.output}`);
674
- }),
675
- `runs.run('${key}') result`,
676
- );
677
- }
678
-
679
- const startedAt = Date.now();
680
- const admission = Promise.resolve().then(() => {
681
- if (settled || finishing) return;
682
- return options.admit?.([{ key, params }]);
683
- });
684
- const promise = admission
685
- .then(async () => {
686
- if (settled || finishing || stoppedLaunches.has(key)) {
687
- const reason = childController.signal.reason;
688
- const text = reason instanceof Error ? reason.message : typeof reason === "string" ? reason : "Workflow script aborted.";
689
- return { key, ok: false, output: text, error: text, artifactPaths: [] };
690
- }
691
- return options.launch(key, { ...params, async: params.async ?? false }, childController.signal, { admitted: true });
692
- })
693
- .then(
694
- (result) => {
695
- const normalized = !result.ok && !result.error ? { ...result, error: result.output } : result;
696
- if (stoppedLaunches.has(key)) return normalized;
697
- children.set(key, normalized);
698
- const state = normalized.ok ? "completed" : "failed";
699
- trace.push({
700
- operation: "run",
701
- key,
702
- state,
703
- durationMs: Date.now() - startedAt,
704
- ...workflowStringMetadata(params),
705
- ...(normalized.agent ? { agent: normalized.agent } : {}),
706
- ...(normalized.runId ? { runId: normalized.runId } : {}),
707
- ...(!normalized.ok ? { error: normalized.error ?? normalized.output } : {}),
708
- });
709
- traceChanged();
710
- return normalized;
711
- },
712
- (error: unknown) => {
713
- const text = error instanceof Error ? error.message : String(error);
714
- const failure: WorkflowScriptChildResult = { key, ok: false, output: text, error: text, artifactPaths: [] };
715
- if (stoppedLaunches.has(key)) return failure;
716
- children.set(key, failure);
717
- trace.push({ operation: "run", key, state: "failed", durationMs: Date.now() - startedAt, ...workflowStringMetadata(params), error: text });
718
- traceChanged();
719
- return failure;
720
- },
721
- );
722
- launches.set(key, { fingerprint, promise, observed: true });
723
- if (!childOrder.includes(key)) childOrder.push(key);
724
- trace.push({ operation: "run", key, state: "started", ...workflowStringMetadata(params) });
725
- traceChanged();
726
- respond(
727
- promise.then((result) => {
728
- if (result.ok) return result;
729
- throw new Error(`Run '${key}' failed: ${result.error ?? result.output}`);
730
- }),
731
- `runs.run('${key}') result`,
732
- );
733
- });
734
-
735
- worker.postMessage({ type: "start", script: options.script, stateEnabled: options.state !== undefined });
736
- });
737
- }