@pikku/core 0.12.78 → 0.12.80

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 (341) hide show
  1. package/CHANGELOG.md +234 -0
  2. package/dist/dev/hot-reload.js +1 -6
  3. package/dist/ecosystem.d.ts +27 -0
  4. package/dist/ecosystem.js +26 -0
  5. package/dist/errors/error-handler.js +4 -2
  6. package/dist/function/function-runner.js +20 -42
  7. package/dist/function/functions.types.d.ts +9 -5
  8. package/dist/index.d.ts +4 -9
  9. package/dist/index.js +3 -8
  10. package/dist/middleware/auth-cookie.d.ts +0 -4
  11. package/dist/middleware/auth-cookie.js +38 -2
  12. package/dist/middleware/cors.js +1 -0
  13. package/dist/middleware/index.d.ts +1 -1
  14. package/dist/middleware/index.js +1 -1
  15. package/dist/middleware/remote-auth.js +14 -3
  16. package/dist/permissions.d.ts +8 -10
  17. package/dist/permissions.js +0 -11
  18. package/dist/pikku-state.js +12 -5
  19. package/dist/schema.js +35 -1
  20. package/dist/services/ai-run-state-service.d.ts +7 -1
  21. package/dist/services/in-memory-ai-run-state-service.d.ts +1 -1
  22. package/dist/services/in-memory-ai-run-state-service.js +2 -1
  23. package/dist/services/in-memory-workflow-service.d.ts +10 -0
  24. package/dist/services/in-memory-workflow-service.js +25 -0
  25. package/dist/services/local-content-request-handler.d.ts +21 -0
  26. package/dist/services/local-content-request-handler.js +72 -53
  27. package/dist/services/local-content.d.ts +6 -0
  28. package/dist/services/local-content.js +14 -1
  29. package/dist/services/workflow-service.d.ts +4 -2
  30. package/dist/testing/service-tests/agent-run-service-tests.d.ts +10 -0
  31. package/dist/testing/service-tests/agent-run-service-tests.js +72 -0
  32. package/dist/testing/service-tests/ai-storage-service-tests.d.ts +3 -0
  33. package/dist/testing/service-tests/ai-storage-service-tests.js +226 -0
  34. package/dist/testing/service-tests/channel-store-tests.d.ts +3 -0
  35. package/dist/testing/service-tests/channel-store-tests.js +72 -0
  36. package/dist/testing/service-tests/credential-service-tests.d.ts +3 -0
  37. package/dist/testing/service-tests/credential-service-tests.js +109 -0
  38. package/dist/testing/service-tests/deployment-service-tests.d.ts +3 -0
  39. package/dist/testing/service-tests/deployment-service-tests.js +21 -0
  40. package/dist/testing/service-tests/event-hub-store-tests.d.ts +3 -0
  41. package/dist/testing/service-tests/event-hub-store-tests.js +34 -0
  42. package/dist/testing/service-tests/secret-service-tests.d.ts +3 -0
  43. package/dist/testing/service-tests/secret-service-tests.js +80 -0
  44. package/dist/testing/service-tests/session-store-tests.d.ts +3 -0
  45. package/dist/testing/service-tests/session-store-tests.js +43 -0
  46. package/dist/testing/service-tests/workflow-run-service-tests.d.ts +3 -0
  47. package/dist/testing/service-tests/workflow-run-service-tests.js +42 -0
  48. package/dist/testing/service-tests/workflow-service-tests.d.ts +3 -0
  49. package/dist/testing/service-tests/workflow-service-tests.js +150 -0
  50. package/dist/testing/service-tests.d.ts +6 -0
  51. package/dist/testing/service-tests.js +26 -791
  52. package/dist/types/core.types.d.ts +11 -1
  53. package/dist/types/state.types.d.ts +1 -1
  54. package/dist/utils/node-host-resolver.d.ts +12 -0
  55. package/dist/utils/node-host-resolver.js +16 -0
  56. package/dist/utils/safe-fetch.d.ts +18 -0
  57. package/dist/utils/safe-fetch.js +167 -29
  58. package/dist/wirings/actor-flow/run-conversation.js +1 -6
  59. package/dist/wirings/ai-agent/agent-rpc.d.ts +15 -0
  60. package/dist/wirings/ai-agent/agent-rpc.js +53 -0
  61. package/dist/wirings/ai-agent/ai-agent-agui.js +1 -5
  62. package/dist/wirings/ai-agent/ai-agent-memory.js +3 -1
  63. package/dist/wirings/ai-agent/ai-agent-prepare.js +3 -9
  64. package/dist/wirings/ai-agent/ai-agent-runner.js +28 -107
  65. package/dist/wirings/ai-agent/ai-agent-stream.js +20 -61
  66. package/dist/wirings/ai-agent/ai-agent-turn.d.ts +56 -0
  67. package/dist/wirings/ai-agent/ai-agent-turn.js +81 -0
  68. package/dist/wirings/ai-agent/ai-agent.types.d.ts +1 -1
  69. package/dist/wirings/ai-agent/voice-input.js +1 -6
  70. package/dist/wirings/ai-agent/voice-output.js +2 -12
  71. package/dist/wirings/channel/channel-common.js +1 -0
  72. package/dist/wirings/channel/channel-handler.js +3 -5
  73. package/dist/wirings/channel/channel-rpc-service.d.ts +0 -6
  74. package/dist/wirings/channel/channel-rpc-service.js +0 -8
  75. package/dist/wirings/channel/channel-rpc.types.d.ts +6 -0
  76. package/dist/wirings/channel/channel-rpc.types.js +8 -0
  77. package/dist/wirings/channel/channel-runner.d.ts +1 -3
  78. package/dist/wirings/channel/channel-runner.js +16 -8
  79. package/dist/wirings/channel/channel.types.d.ts +2 -0
  80. package/dist/wirings/channel/pikku-abstract-channel-handler.js +1 -0
  81. package/dist/wirings/channel/serverless/serverless-channel-runner.js +3 -0
  82. package/dist/wirings/cli/channel/cli-channel-runner.js +2 -0
  83. package/dist/wirings/cli/cli-runner.js +4 -2
  84. package/dist/wirings/cli/cli.types.d.ts +0 -8
  85. package/dist/wirings/cli/command-parser.js +13 -0
  86. package/dist/wirings/gateway/gateway-runner.js +41 -5
  87. package/dist/wirings/http/http-routes.js +2 -0
  88. package/dist/wirings/http/http-runner.d.ts +0 -10
  89. package/dist/wirings/http/http-runner.js +6 -13
  90. package/dist/wirings/http/http.types.d.ts +0 -10
  91. package/dist/wirings/http/index.d.ts +1 -1
  92. package/dist/wirings/http/index.js +1 -1
  93. package/dist/wirings/mcp/mcp-runner.d.ts +0 -7
  94. package/dist/wirings/mcp/mcp-runner.js +0 -6
  95. package/dist/wirings/rpc/rpc-runner.d.ts +8 -51
  96. package/dist/wirings/rpc/rpc-runner.js +53 -86
  97. package/dist/wirings/rpc/rpc-types.d.ts +3 -0
  98. package/dist/wirings/secret/validate-secret-definitions.js +2 -0
  99. package/dist/wirings/trigger/pikku-trigger-service.d.ts +0 -4
  100. package/dist/wirings/trigger/trigger-runner.js +1 -0
  101. package/dist/wirings/virtual-user/run-virtual-user.js +11 -11
  102. package/dist/wirings/virtual-user/virtual-user-derive.js +4 -25
  103. package/dist/wirings/virtual-user/virtual-user-dispositions.js +1 -4
  104. package/dist/wirings/workflow/dsl/workflow-dsl.types.d.ts +29 -2
  105. package/dist/wirings/workflow/feature.js +7 -4
  106. package/dist/wirings/workflow/graph/graph-runner.d.ts +1 -2
  107. package/dist/wirings/workflow/graph/graph-runner.js +8 -7
  108. package/dist/wirings/workflow/graph/workflow-graph.types.d.ts +0 -4
  109. package/dist/wirings/workflow/index.d.ts +7 -2
  110. package/dist/wirings/workflow/index.js +5 -1
  111. package/dist/wirings/workflow/pikku-scenario-service.d.ts +17 -3
  112. package/dist/wirings/workflow/pikku-scenario-service.js +38 -10
  113. package/dist/wirings/workflow/pikku-workflow-service.d.ts +44 -111
  114. package/dist/wirings/workflow/pikku-workflow-service.js +86 -404
  115. package/dist/wirings/workflow/workflow-approval.d.ts +39 -0
  116. package/dist/wirings/workflow/workflow-approval.js +114 -0
  117. package/dist/wirings/workflow/workflow-constants.d.ts +26 -0
  118. package/dist/wirings/workflow/workflow-constants.js +35 -0
  119. package/dist/wirings/workflow/workflow-errors.d.ts +58 -0
  120. package/dist/wirings/workflow/workflow-errors.js +112 -0
  121. package/dist/wirings/workflow/workflow-meta-resolver.d.ts +11 -0
  122. package/dist/wirings/workflow/workflow-meta-resolver.js +31 -0
  123. package/dist/wirings/workflow/workflow-queue-routing.d.ts +8 -0
  124. package/dist/wirings/workflow/workflow-queue-routing.js +38 -0
  125. package/dist/wirings/workflow/workflow-queue-wiring.d.ts +20 -0
  126. package/dist/wirings/workflow/workflow-queue-wiring.js +79 -0
  127. package/dist/wirings/workflow/workflow-recovery.d.ts +68 -0
  128. package/dist/wirings/workflow/workflow-recovery.js +101 -0
  129. package/dist/wirings/workflow/workflow-run-engine.types.d.ts +54 -0
  130. package/dist/wirings/workflow/workflow-run-engine.types.js +1 -0
  131. package/dist/wirings/workflow/workflow-run-ownership.d.ts +16 -0
  132. package/dist/wirings/workflow/workflow-run-ownership.js +29 -0
  133. package/dist/wirings/workflow/workflow-suspend.d.ts +12 -0
  134. package/dist/wirings/workflow/workflow-suspend.js +33 -0
  135. package/dist/wirings/workflow/workflow.types.d.ts +7 -0
  136. package/knowledge/decisions/internals/a-non-streaming-agent-run-registers-with-airunstate-too.md +22 -0
  137. package/knowledge/decisions/internals/a-resumed-agent-turn-is-as-interruptible-as-the-first.md +20 -0
  138. package/knowledge/decisions/internals/a-scenario-step-template-is-offered-unfilled.md +21 -0
  139. package/knowledge/decisions/internals/a-virtual-user-decides-whether-to-trust-memory-once-per-turn.md +21 -0
  140. package/knowledge/decisions/internals/a-wall-clock-threshold-is-a-load-test-in-disguise.md +46 -0
  141. package/knowledge/decisions/internals/a-workflow-wire-is-built-from-the-run-not-from-the-rpc-service.md +45 -0
  142. package/knowledge/decisions/internals/agent-context-waits-for-a-tool-result-still-being-written.md +21 -0
  143. package/knowledge/decisions/internals/agent-speech-travels-as-a-custom-agui-event.md +22 -0
  144. package/knowledge/decisions/internals/an-agent-interrupt-is-not-a-failure.md +23 -0
  145. package/knowledge/decisions/internals/an-agent-run-owned-by-another-instance-says-so.md +25 -0
  146. package/knowledge/decisions/internals/an-agent-stream-send-must-return-the-inner-sends-promise.md +22 -0
  147. package/knowledge/decisions/internals/an-empty-text-part-is-omitted-from-an-agent-message.md +20 -0
  148. package/knowledge/decisions/internals/an-empty-transcript-is-not-recorded.md +22 -0
  149. package/knowledge/decisions/internals/an-unref-d-timer-cannot-be-awaited-under-node-test.md +66 -0
  150. package/knowledge/decisions/internals/channel-state-accessors-are-unsound-generics-that-every-implementation-asserts.md +33 -0
  151. package/knowledge/decisions/internals/gateway-listener-middleware-runs-without-an-rpc-on-the-wire.md +43 -0
  152. package/knowledge/decisions/internals/hot-reload-writes-into-the-function-map-captured-at-startup.md +26 -0
  153. package/knowledge/decisions/internals/index.md +38 -26
  154. package/knowledge/decisions/internals/only-exposed-functions-enter-a-virtual-user-catalogue.md +21 -0
  155. package/knowledge/decisions/internals/scenario-given-and-when-are-sugar-but-then-is-not.md +24 -0
  156. package/knowledge/decisions/internals/side-effects-are-an-allowlist-not-a-boolean.md +34 -0
  157. package/knowledge/decisions/internals/speech-synthesis-picks-a-voice-per-sentence-and-warns-once.md +24 -0
  158. package/knowledge/decisions/internals/the-actor-prompt-says-json-because-of-json-object-mode.md +22 -0
  159. package/knowledge/decisions/internals/the-agent-done-event-goes-through-the-middleware-and-is-awaited.md +26 -0
  160. package/knowledge/decisions/internals/the-api-report-pins-members-not-just-names.md +43 -0
  161. package/knowledge/decisions/internals/the-ecosystem-entry-point-carries-the-adapter-surface.md +58 -0
  162. package/knowledge/decisions/internals/the-middleware-resolution-cache-is-deliberately-unbounded.md +40 -0
  163. package/knowledge/decisions/internals/the-per-invocation-rpc-view-is-a-class.md +40 -0
  164. package/knowledge/decisions/internals/the-persona-runtime-is-exported-from-the-persona-entry-point.md +28 -0
  165. package/knowledge/decisions/internals/the-transcript-event-is-sent-ahead-of-the-run.md +25 -0
  166. package/knowledge/decisions/internals/the-virtual-user-catalogue-is-the-only-gate-on-what-may-be-called.md +21 -0
  167. package/knowledge/decisions/internals/the-worker-disposition-is-the-one-that-is-not-testing.md +22 -0
  168. package/knowledge/decisions/internals/thread-history-records-the-transcript-not-the-audio.md +25 -0
  169. package/knowledge/decisions/internals/virtual-user-step-order-comes-from-insertion-order.md +21 -0
  170. package/knowledge/decisions/internals/voice-output-speaks-unless-voice-input-explicitly-says-otherwise.md +24 -0
  171. package/knowledge/decisions/internals/wiring-registries-erase-the-generics-their-wire-functions-capture.md +35 -0
  172. package/knowledge/decisions/security/a-dropped-audit-write-is-always-logged.md +4 -2
  173. package/knowledge/decisions/security/a-graph-run-starts-at-an-entry-node-the-graph-declared.md +33 -0
  174. package/knowledge/decisions/security/a-permission-gets-a-wire-it-cannot-reply-on.md +33 -0
  175. package/knowledge/decisions/security/a-step-runs-the-function-the-workflow-dispatched-it-with.md +37 -0
  176. package/knowledge/decisions/security/a-virtual-user-is-never-offered-a-step-that-would-forge-its-own-oracle.md +28 -0
  177. package/knowledge/decisions/security/a-workflow-run-is-read-and-approved-by-its-owner.md +34 -0
  178. package/knowledge/decisions/security/an-agent-approval-is-claimed-before-the-tool-runs.md +33 -0
  179. package/knowledge/decisions/security/an-upload-is-counted-as-it-arrives-not-buffered-then-measured.md +24 -0
  180. package/knowledge/decisions/security/gateway-handlers-run-through-the-function-runner-gate.md +13 -3
  181. package/knowledge/decisions/security/index.md +7 -0
  182. package/knowledge/questions/channel-middleware-accepts-bare-factories-that-nothing-resolves.md +35 -0
  183. package/knowledge/questions/index.md +2 -1
  184. package/knowledge/questions/unauthorized-channel-replies-escape-the-declared-out-type.md +44 -0
  185. package/package.json +14 -3
  186. package/scripts/generate-api-report.d.mts +1 -0
  187. package/scripts/generate-api-report.mjs +89 -0
  188. package/scripts/generate-api-report.mts +218 -0
  189. package/src/api-report.test.ts +69 -0
  190. package/src/column-form.ts +1 -4
  191. package/src/crypto-utils.test.ts +15 -2
  192. package/src/dev/hot-reload.ts +2 -7
  193. package/src/ecosystem.ts +40 -0
  194. package/src/errors/error-handler.ts +5 -3
  195. package/src/errors/error.test.ts +4 -1
  196. package/src/function/function-runner.test.ts +1 -1
  197. package/src/function/function-runner.ts +28 -39
  198. package/src/function/functions.types.ts +15 -9
  199. package/src/handle-error.ts +1 -1
  200. package/src/index.ts +3 -22
  201. package/src/middleware/auth-cookie.test.ts +50 -0
  202. package/src/middleware/auth-cookie.ts +38 -2
  203. package/src/middleware/cors.ts +2 -1
  204. package/src/middleware/index.ts +1 -1
  205. package/src/middleware/remote-auth.test.ts +43 -0
  206. package/src/middleware/remote-auth.ts +17 -3
  207. package/src/middleware-runner.ts +4 -2
  208. package/src/no-any-casts.test.ts +57 -0
  209. package/src/permissions.test.ts +3 -1
  210. package/src/permissions.ts +22 -24
  211. package/src/pikku-state.ts +17 -6
  212. package/src/public-surface.json +578 -0
  213. package/src/public-surface.json.README +25 -0
  214. package/src/public-surface.test.ts +105 -0
  215. package/src/removed-legacy-exports.test.ts +62 -0
  216. package/src/schema.test.ts +78 -0
  217. package/src/schema.ts +36 -1
  218. package/src/services/ai-run-state-service.ts +7 -1
  219. package/src/services/audit-service.ts +2 -2
  220. package/src/services/in-memory-ai-run-state-service.ts +3 -2
  221. package/src/services/in-memory-workflow-service.ts +25 -0
  222. package/src/services/index.ts +1 -4
  223. package/src/services/local-content-request-handler.test.ts +43 -5
  224. package/src/services/local-content-request-handler.ts +103 -74
  225. package/src/services/local-content.ts +15 -1
  226. package/src/services/local-email-service.ts +5 -1
  227. package/src/services/system-role-guard.test.ts +4 -1
  228. package/src/services/workflow-service.ts +9 -2
  229. package/src/side-effects-are-declared.test.ts +84 -0
  230. package/src/source-files-stay-composable.test.ts +41 -0
  231. package/src/testing/service-tests/agent-run-service-tests.ts +98 -0
  232. package/src/testing/service-tests/ai-storage-service-tests.ts +286 -0
  233. package/src/testing/service-tests/channel-store-tests.ts +98 -0
  234. package/src/testing/service-tests/credential-service-tests.ts +143 -0
  235. package/src/testing/service-tests/deployment-service-tests.ts +33 -0
  236. package/src/testing/service-tests/event-hub-store-tests.ts +48 -0
  237. package/src/testing/service-tests/secret-service-tests.ts +105 -0
  238. package/src/testing/service-tests/session-store-tests.ts +62 -0
  239. package/src/testing/service-tests/workflow-run-service-tests.ts +59 -0
  240. package/src/testing/service-tests/workflow-service-tests.ts +308 -0
  241. package/src/testing/service-tests.ts +31 -1111
  242. package/src/types/core.types.ts +15 -1
  243. package/src/types/state.types.ts +1 -1
  244. package/src/utils/node-host-resolver.ts +20 -0
  245. package/src/utils/safe-fetch.test.ts +143 -1
  246. package/src/utils/safe-fetch.ts +200 -25
  247. package/src/wirings/actor-flow/run-conversation.ts +1 -6
  248. package/src/wirings/ai-agent/agent-rpc.ts +120 -0
  249. package/src/wirings/ai-agent/ai-agent-agui.ts +1 -5
  250. package/src/wirings/ai-agent/ai-agent-interrupt.test.ts +2 -1
  251. package/src/wirings/ai-agent/ai-agent-memory.ts +8 -1
  252. package/src/wirings/ai-agent/ai-agent-prepare.ts +10 -12
  253. package/src/wirings/ai-agent/ai-agent-resume-authorization.test.ts +1 -0
  254. package/src/wirings/ai-agent/ai-agent-runner.test.ts +82 -2
  255. package/src/wirings/ai-agent/ai-agent-runner.ts +49 -120
  256. package/src/wirings/ai-agent/ai-agent-stream.test.ts +2 -0
  257. package/src/wirings/ai-agent/ai-agent-stream.ts +36 -63
  258. package/src/wirings/ai-agent/ai-agent-thread-ownership.test.ts +1 -1
  259. package/src/wirings/ai-agent/ai-agent-turn.ts +121 -0
  260. package/src/wirings/ai-agent/ai-agent.types.ts +1 -1
  261. package/src/wirings/ai-agent/voice-input.ts +1 -6
  262. package/src/wirings/ai-agent/voice-output.ts +2 -12
  263. package/src/wirings/channel/channel-common.ts +5 -2
  264. package/src/wirings/channel/channel-handler-shapes.test.ts +72 -0
  265. package/src/wirings/channel/channel-handler.ts +7 -7
  266. package/src/wirings/channel/channel-rpc-service.ts +0 -14
  267. package/src/wirings/channel/channel-rpc.test.ts +25 -4
  268. package/src/wirings/channel/channel-rpc.types.ts +14 -0
  269. package/src/wirings/channel/channel-runner.ts +33 -20
  270. package/src/wirings/channel/channel.types.ts +2 -0
  271. package/src/wirings/channel/local/local-channel-runner.ts +1 -1
  272. package/src/wirings/channel/pikku-abstract-channel-handler.ts +2 -1
  273. package/src/wirings/channel/serverless/serverless-channel-runner.ts +6 -3
  274. package/src/wirings/cli/channel/cli-channel-runner.ts +3 -1
  275. package/src/wirings/cli/channel/cli-raw-client-runner.ts +4 -1
  276. package/src/wirings/cli/cli-runner.ts +7 -4
  277. package/src/wirings/cli/cli.types.ts +0 -39
  278. package/src/wirings/cli/command-parser.test.ts +19 -0
  279. package/src/wirings/cli/command-parser.ts +17 -1
  280. package/src/wirings/gateway/gateway-authorization.test.ts +131 -0
  281. package/src/wirings/gateway/gateway-channel-meta.test.ts +44 -0
  282. package/src/wirings/gateway/gateway-runner.ts +62 -22
  283. package/src/wirings/http/http-routes.ts +4 -1
  284. package/src/wirings/http/http-runner.ts +11 -26
  285. package/src/wirings/http/http.types.ts +0 -15
  286. package/src/wirings/http/index.ts +1 -7
  287. package/src/wirings/http/pikku-fetch-http-request.ts +2 -2
  288. package/src/wirings/http/web-request.ts +1 -1
  289. package/src/wirings/mcp/mcp-runner.ts +2 -16
  290. package/src/wirings/persona/persona-environments.test.ts +14 -3
  291. package/src/wirings/persona/persona.test.ts +13 -3
  292. package/src/wirings/persona/validate-personas.ts +5 -1
  293. package/src/wirings/queue/queue-runner.ts +1 -1
  294. package/src/wirings/rpc/addon-auth-tags.test.ts +1 -5
  295. package/src/wirings/rpc/rpc-runner.ts +58 -136
  296. package/src/wirings/rpc/rpc-types.ts +7 -0
  297. package/src/wirings/rpc/wire-addon.ts +3 -1
  298. package/src/wirings/secret/validate-secret-definitions.test.ts +69 -0
  299. package/src/wirings/secret/validate-secret-definitions.ts +2 -0
  300. package/src/wirings/trigger/pikku-trigger-service.ts +0 -5
  301. package/src/wirings/trigger/trigger-runner.ts +7 -5
  302. package/src/wirings/virtual-user/run-virtual-user.test.ts +18 -9
  303. package/src/wirings/virtual-user/run-virtual-user.ts +28 -15
  304. package/src/wirings/virtual-user/virtual-user-agents.test.ts +4 -1
  305. package/src/wirings/virtual-user/virtual-user-derive.ts +4 -25
  306. package/src/wirings/virtual-user/virtual-user-dispositions.test.ts +7 -2
  307. package/src/wirings/virtual-user/virtual-user-dispositions.ts +1 -4
  308. package/src/wirings/virtual-user/virtual-user-intents.test.ts +13 -3
  309. package/src/wirings/workflow/dsl/workflow-dsl.types.ts +35 -2
  310. package/src/wirings/workflow/feature.ts +7 -4
  311. package/src/wirings/workflow/graph/graph-node.ts +1 -1
  312. package/src/wirings/workflow/graph/graph-runner.test.ts +4 -2
  313. package/src/wirings/workflow/graph/graph-runner.ts +13 -16
  314. package/src/wirings/workflow/graph/workflow-graph.types.ts +0 -5
  315. package/src/wirings/workflow/index.ts +12 -4
  316. package/src/wirings/workflow/pikku-scenario-service.ts +54 -25
  317. package/src/wirings/workflow/pikku-workflow-service.test.ts +2 -2
  318. package/src/wirings/workflow/pikku-workflow-service.ts +208 -630
  319. package/src/wirings/workflow/scenario-hooks.test.ts +51 -0
  320. package/src/wirings/workflow/workflow-approval.ts +185 -0
  321. package/src/wirings/workflow/workflow-child-run-session.test.ts +89 -0
  322. package/src/wirings/workflow/workflow-constants.ts +47 -0
  323. package/src/wirings/workflow/workflow-dispatch-durability.test.ts +1 -1
  324. package/src/wirings/workflow/workflow-dispatch-relay.test.ts +128 -0
  325. package/src/wirings/workflow/workflow-errors.ts +128 -0
  326. package/src/wirings/workflow/workflow-inline-authority.test.ts +12 -6
  327. package/src/wirings/workflow/workflow-meta-resolver.ts +45 -0
  328. package/src/wirings/workflow/workflow-missing-meta.test.ts +92 -0
  329. package/src/wirings/workflow/workflow-queue-routing.ts +85 -0
  330. package/src/wirings/workflow/workflow-queue-wiring.ts +149 -0
  331. package/src/wirings/workflow/workflow-recovery.ts +162 -0
  332. package/src/wirings/workflow/workflow-retry-policy.test.ts +1 -1
  333. package/src/wirings/workflow/workflow-run-authority.test.ts +215 -0
  334. package/src/wirings/workflow/workflow-run-engine.types.ts +91 -0
  335. package/src/wirings/workflow/workflow-run-ownership.ts +36 -0
  336. package/src/wirings/workflow/workflow-suspend.ts +61 -0
  337. package/src/wirings/workflow/workflow.types.ts +7 -0
  338. package/src/wirings-stay-decoupled.test.ts +123 -0
  339. package/tsconfig.json +1 -1
  340. package/tsconfig.tsbuildinfo +1 -1
  341. package/src/internal.ts +0 -10
@@ -184,6 +184,57 @@ describe('scenario before/after hooks', () => {
184
184
  ])
185
185
  })
186
186
 
187
+ test('after reads what the body wrote to the scenario context', async () => {
188
+ // The reason the context exists: teardown needs the ids the body minted,
189
+ // and a hook only ever receives the run's *input*.
190
+ let seen: any
191
+ await runScenario('contextHandover', {
192
+ after: async (_services, _data, wire) => {
193
+ seen = { ...wire.scenario.context }
194
+ },
195
+ func: async (_services, _data, wire) => {
196
+ wire.scenario.context.projectId = 'p_1'
197
+ return { projectId: 'p_1' }
198
+ },
199
+ })
200
+ assert.deepEqual(seen, { projectId: 'p_1' })
201
+ })
202
+
203
+ test('after sees the context of a body that threw after writing it', async () => {
204
+ // The failing path is the one that matters — a passing run could have
205
+ // returned the ids instead.
206
+ let seen: any
207
+ const { error } = await runScenario('contextOnFailure', {
208
+ after: async (_services, _data, wire) => {
209
+ seen = { ...wire.scenario.context }
210
+ },
211
+ func: async (_services, _data, wire) => {
212
+ wire.scenario.context.projectId = 'p_2'
213
+ throw new Error('body blew up')
214
+ },
215
+ })
216
+ assert.equal(error?.message, 'body blew up')
217
+ assert.deepEqual(seen, { projectId: 'p_2' })
218
+ })
219
+
220
+ test('before, the body and after all share one context object', async () => {
221
+ let seen: any
222
+ await runScenario('contextShared', {
223
+ before: async (_services, _data, wire) => {
224
+ wire.scenario.context.seededBy = 'before'
225
+ },
226
+ after: async (_services, _data, wire) => {
227
+ seen = { ...wire.scenario.context }
228
+ },
229
+ func: async (_services, _data, wire) => {
230
+ assert.equal(wire.scenario.context.seededBy, 'before')
231
+ wire.scenario.context.addedBy = 'func'
232
+ return { ok: true }
233
+ },
234
+ })
235
+ assert.deepEqual(seen, { seededBy: 'before', addedBy: 'func' })
236
+ })
237
+
187
238
  test('hooks are scenario-only — a plain DSL workflow never runs them', async () => {
188
239
  const order: string[] = []
189
240
  await runScenario(
@@ -0,0 +1,185 @@
1
+ import { getDurationInMilliseconds } from '../../time-utils.js'
2
+ import {
3
+ WorkflowApprovalResolvedError,
4
+ WorkflowSuspendedException,
5
+ } from './workflow-errors.js'
6
+ import type {
7
+ ApprovalOutcome,
8
+ StepState,
9
+ WorkflowApprovalOptions,
10
+ } from './workflow.types.js'
11
+
12
+ /** The durable step name an approval point is recorded under. */
13
+ export const approvalStepNameFor = (reason: string): string =>
14
+ `__workflow_approval:${reason}`
15
+
16
+ /**
17
+ * The run-state key holding an approval's decision.
18
+ *
19
+ * Hex-encoded because the key is composed from a caller-supplied reason, and
20
+ * run state is a flat record — an unescaped reason could collide with, or
21
+ * shadow, another key.
22
+ */
23
+ export const approvalStateKey = (stepName: string): string => {
24
+ let hex = ''
25
+ for (const byte of new TextEncoder().encode(stepName)) {
26
+ hex += byte.toString(16).padStart(2, '0')
27
+ }
28
+ return `__approval_${hex}`
29
+ }
30
+
31
+ /** What the approval gate needs from the workflow service. */
32
+ export type ApprovalStore = {
33
+ getStepState: (runId: string, stepName: string) => Promise<StepState>
34
+ insertStepState: (
35
+ runId: string,
36
+ stepName: string,
37
+ rpcName: string,
38
+ input: unknown,
39
+ output: undefined,
40
+ fromStepName?: string
41
+ ) => Promise<StepState>
42
+ setStepRunning: (stepId: string) => Promise<void>
43
+ setStepResult: (stepId: string, result: unknown) => Promise<void>
44
+ getRunState: (runId: string) => Promise<Record<string, unknown>>
45
+ updateRunState: (runId: string, key: string, value: unknown) => Promise<void>
46
+ resumeWorkflow: (runId: string) => Promise<void>
47
+ scheduleRunWake: (runId: string, delay: number) => Promise<void>
48
+ }
49
+
50
+ /**
51
+ * Record a decision against an approval point and wake the run.
52
+ *
53
+ * A decision arriving for an already-settled approval is refused rather than
54
+ * overwriting it: the run has moved on, and a second answer would be recorded
55
+ * against a gate nobody is waiting at.
56
+ */
57
+ export const recordApprovalDecision = async (
58
+ store: ApprovalStore,
59
+ runId: string,
60
+ reason: string,
61
+ decision: unknown
62
+ ): Promise<void> => {
63
+ const stepName = approvalStepNameFor(reason)
64
+ const stateKey = approvalStateKey(stepName)
65
+
66
+ let resolved: StepState | undefined
67
+ try {
68
+ resolved = await store.getStepState(runId, stepName)
69
+ } catch {
70
+ // knowledge: decisions/security/workflow-approval-payloads-are-validated-on-replay-inside-the-workflow.md
71
+ }
72
+ if (resolved?.stepId && resolved.status === 'succeeded') {
73
+ const outcome = resolved.result as ApprovalOutcome<unknown> | undefined
74
+ throw new WorkflowApprovalResolvedError(
75
+ reason,
76
+ outcome?.status ?? 'decided'
77
+ )
78
+ }
79
+
80
+ const state = await store.getRunState(runId)
81
+ const record = (state[stateKey] ?? {}) as Record<string, unknown>
82
+ await store.updateRunState(runId, stateKey, {
83
+ ...record,
84
+ decision,
85
+ decidedAt: new Date().toISOString(),
86
+ error: undefined,
87
+ })
88
+ await store.resumeWorkflow(runId)
89
+ }
90
+
91
+ /**
92
+ * Evaluate an approval gate on replay.
93
+ *
94
+ * The payload is validated here rather than where it was submitted, because the
95
+ * schema is a value on the workflow and only the workflow has it. A payload
96
+ * that fails validation is cleared and the run suspends again, so a bad
97
+ * submission cannot settle the gate.
98
+ */
99
+ export const evaluateApprovalStep = async (
100
+ store: ApprovalStore,
101
+ runId: string,
102
+ reason: string,
103
+ approvalStepName: string,
104
+ fromStepName: string | undefined,
105
+ options: WorkflowApprovalOptions
106
+ ): Promise<ApprovalOutcome<unknown>> => {
107
+ const insert = () =>
108
+ store.insertStepState(
109
+ runId,
110
+ approvalStepName,
111
+ 'pikkuWorkflowApproval',
112
+ { reason, expiry: options.expiry },
113
+ undefined,
114
+ fromStepName
115
+ )
116
+
117
+ let stepState: StepState
118
+ try {
119
+ stepState = await store.getStepState(runId, approvalStepName)
120
+ } catch {
121
+ stepState = await insert()
122
+ }
123
+ if (!stepState.stepId) {
124
+ stepState = await insert()
125
+ }
126
+
127
+ if (stepState.status === 'succeeded') {
128
+ return stepState.result as ApprovalOutcome<unknown>
129
+ }
130
+
131
+ const stateKey = approvalStateKey(approvalStepName)
132
+ let record = ((await store.getRunState(runId))[stateKey] ?? {}) as {
133
+ decision?: unknown
134
+ decidedAt?: string
135
+ expiresAt?: string
136
+ error?: unknown
137
+ }
138
+
139
+ if (stepState.status === 'pending') {
140
+ await store.setStepRunning(stepState.stepId)
141
+ if (options.expiry !== undefined && !record.expiresAt) {
142
+ const expiry = getDurationInMilliseconds(options.expiry)
143
+ record = {
144
+ ...record,
145
+ expiresAt: new Date(Date.now() + expiry).toISOString(),
146
+ }
147
+ await store.updateRunState(runId, stateKey, record)
148
+ await store.scheduleRunWake(runId, expiry)
149
+ }
150
+ }
151
+
152
+ if (record.decision !== undefined) {
153
+ const validation = await options.schema['~standard'].validate(
154
+ record.decision
155
+ )
156
+ if (validation.issues) {
157
+ await store.updateRunState(runId, stateKey, {
158
+ ...record,
159
+ decision: undefined,
160
+ decidedAt: undefined,
161
+ error: validation.issues.map((issue) => ({
162
+ message: issue.message,
163
+ path: issue.path?.map((segment) =>
164
+ typeof segment === 'object' ? segment.key : segment
165
+ ),
166
+ })),
167
+ })
168
+ throw new WorkflowSuspendedException(runId, reason)
169
+ }
170
+ const outcome: ApprovalOutcome<unknown> = {
171
+ status: 'decided',
172
+ data: validation.value,
173
+ }
174
+ await store.setStepResult(stepState.stepId, outcome)
175
+ return outcome
176
+ }
177
+
178
+ if (record.expiresAt && Date.now() >= Date.parse(record.expiresAt)) {
179
+ const outcome: ApprovalOutcome<unknown> = { status: 'expired' }
180
+ await store.setStepResult(stepState.stepId, outcome)
181
+ return outcome
182
+ }
183
+
184
+ throw new WorkflowSuspendedException(runId, reason)
185
+ }
@@ -0,0 +1,89 @@
1
+ import { describe, test } from 'node:test'
2
+ import assert from 'node:assert/strict'
3
+
4
+ import { InMemoryWorkflowService } from '../../services/in-memory-workflow-service.js'
5
+ import { pikkuState, resetPikkuState } from '../../pikku-state.js'
6
+
7
+ const silentLogger = { error() {}, info() {}, warn() {}, debug() {} }
8
+
9
+ const registerChildWorkflow = (name: string) => {
10
+ pikkuState(null, 'workflows', 'meta', {
11
+ [name]: { name, pikkuFuncId: name, source: 'dsl', graphHash: 'h' },
12
+ } as any)
13
+ pikkuState(null, 'workflows', 'registrations').set(name, {
14
+ name,
15
+ func: async () => undefined,
16
+ } as any)
17
+ pikkuState(null, 'function', 'meta', {
18
+ [name]: {
19
+ pikkuFuncId: name,
20
+ inputSchemaName: null,
21
+ outputSchemaName: null,
22
+ sessionless: true,
23
+ },
24
+ } as any)
25
+ pikkuState(null, 'function', 'functions').set(name, {
26
+ func: async () => undefined,
27
+ } as any)
28
+ }
29
+
30
+ /**
31
+ * A step whose rpcName names a workflow starts that workflow as a child. The
32
+ * child's wire is built by the parent, so whatever identifies the caller has to
33
+ * be copied across explicitly — nothing else carries it.
34
+ */
35
+ describe('a child workflow inherits the parent run wire pikkuUserId', () => {
36
+ const startParentWithChildStep = async (pikkuUserId?: string) => {
37
+ resetPikkuState()
38
+ pikkuState(null, 'package', 'singletonServices', {
39
+ logger: silentLogger,
40
+ } as any)
41
+ registerChildWorkflow('childFlow')
42
+
43
+ const ws = new InMemoryWorkflowService()
44
+ const runId = await ws.createRun('parentFlow', {}, true, '', {
45
+ type: 'test',
46
+ ...(pikkuUserId ? { pikkuUserId } : {}),
47
+ })
48
+ ws.registerInlineRun(runId)
49
+ await ws.insertStepState(runId, 'callChild', 'childFlow', {})
50
+
51
+ await (ws as any).rpcStep(runId, 'callChild', 'childFlow', {}, {})
52
+ return ws
53
+ }
54
+
55
+ const childRunWire = async (ws: InMemoryWorkflowService) => {
56
+ const runs: any[] = []
57
+ for (const id of (ws as any).runs?.keys?.() ?? []) {
58
+ const run = await ws.getRun(id)
59
+ if (run?.workflow === 'childFlow') runs.push(run)
60
+ }
61
+ assert.equal(runs.length, 1, 'exactly one child run should have started')
62
+ return runs[0]!.wire
63
+ }
64
+
65
+ test('the child run wire carries the parent pikkuUserId', async () => {
66
+ const ws = await startParentWithChildStep('user-abc')
67
+
68
+ assert.equal(
69
+ (await childRunWire(ws)).pikkuUserId,
70
+ 'user-abc',
71
+ 'a child started from a step must inherit who the parent was running as'
72
+ )
73
+ })
74
+
75
+ test('no pikkuUserId is invented when the parent has none', async () => {
76
+ const ws = await startParentWithChildStep()
77
+
78
+ assert.equal((await childRunWire(ws)).pikkuUserId, undefined)
79
+ })
80
+
81
+ test('the child records its parent', async () => {
82
+ const ws = await startParentWithChildStep('user-abc')
83
+ const wire = await childRunWire(ws)
84
+
85
+ assert.equal(wire.type, 'workflow')
86
+ assert.equal(wire.id, 'childFlow')
87
+ assert.ok(wire.parentRunId, 'the child must name the run that started it')
88
+ })
89
+ })
@@ -0,0 +1,47 @@
1
+ export const DEFAULT_STEP_RETRIES = 5
2
+
3
+ /** Statuses from which a run never advances again on its own. */
4
+ export const WORKFLOW_END_STATES: ReadonlySet<string> = new Set([
5
+ 'completed',
6
+ 'failed',
7
+ 'cancelled',
8
+ 'suspended',
9
+ ])
10
+
11
+ /** Statuses a run cannot leave at all. */
12
+ export const WORKFLOW_TERMINAL_STATES: ReadonlySet<string> = new Set([
13
+ 'completed',
14
+ 'failed',
15
+ 'cancelled',
16
+ ])
17
+
18
+ export const WORKFLOW_POLL_MIN_MS = 10
19
+
20
+ export const WORKFLOW_POLL_FACTOR = 1.6
21
+
22
+ export const WORKFLOW_CHILD_POLL_MAX_MS = 500
23
+
24
+ /** Idle window before a `running` run with nothing in flight is treated as stalled. */
25
+ export const DEFAULT_STALLED_RUN_MS = 5 * 60_000
26
+
27
+ /** Runs re-driven per `recoverStalledRuns` call, so one sweep is bounded. */
28
+ export const DEFAULT_STALLED_RUN_LIMIT = 100
29
+
30
+ /**
31
+ * How long a step may sit `pending` before the relay assumes its dispatch was
32
+ * lost. This is a bet that no healthy queue takes this long to move a job from
33
+ * `pending` to `running`; set it above the observed p99 of that latency.
34
+ */
35
+ export const DEFAULT_UNDISPATCHED_STEP_MS = 30_000
36
+
37
+ /** Steps re-driven per `relayUndispatchedSteps` call, so one tick is bounded. */
38
+ export const DEFAULT_UNDISPATCHED_STEP_LIMIT = 100
39
+
40
+ /** First wait before a step already re-dispatched once is re-dispatched again. */
41
+ export const REDISPATCH_BACKOFF_MS = 30_000
42
+
43
+ /** Ceiling on the doubling backoff, so a permanently stuck step still gets swept. */
44
+ export const REDISPATCH_BACKOFF_MAX_MS = 10 * 60_000
45
+
46
+ /** Bound on the in-process backoff map, so a long-lived process cannot grow it without bound. */
47
+ export const REDISPATCH_BACKOFF_MAX_ENTRIES = 10_000
@@ -3,7 +3,7 @@ import assert from 'node:assert/strict'
3
3
 
4
4
  import { InMemoryWorkflowService } from '../../services/in-memory-workflow-service.js'
5
5
  import { pikkuState } from '../../pikku-state.js'
6
- import { WorkflowDispatchException } from './pikku-workflow-service.js'
6
+ import { WorkflowDispatchException } from './workflow-errors.js'
7
7
 
8
8
  function registerDispatchedFn(rpcName: string): void {
9
9
  const funcId = `fn:${rpcName}`
@@ -0,0 +1,128 @@
1
+ import { describe, test } from 'node:test'
2
+ import assert from 'node:assert/strict'
3
+
4
+ import { InMemoryWorkflowService } from '../../services/in-memory-workflow-service.js'
5
+ import { pikkuState } from '../../pikku-state.js'
6
+
7
+ const silentLogger = { error() {}, info() {}, warn() {}, debug() {} }
8
+
9
+ /**
10
+ * `relayUndispatchedSteps` re-drives a run by putting it back on the
11
+ * orchestrator queue, so the queue is the observation point.
12
+ */
13
+ function trackResumes(): { runIds: string[] } {
14
+ const seen: string[] = []
15
+ pikkuState(null, 'package', 'singletonServices', {
16
+ queueService: {
17
+ add: async (_queue: string, data: { runId: string }) => {
18
+ seen.push(data.runId)
19
+ },
20
+ },
21
+ logger: silentLogger,
22
+ } as any)
23
+ return { runIds: seen }
24
+ }
25
+
26
+ /** Backdates a step's timestamp so it reads as undispatched. */
27
+ async function backdateSteps(
28
+ ws: InMemoryWorkflowService,
29
+ runId: string,
30
+ ms: number
31
+ ): Promise<void> {
32
+ const past = new Date(Date.now() - ms)
33
+ for (const step of await ws.getRunHistory(runId)) {
34
+ ;(step as any).updatedAt = past
35
+ }
36
+ }
37
+
38
+ describe('undispatched step relay', () => {
39
+ test('re-dispatches a step whose arming was lost', async () => {
40
+ const resumes = trackResumes()
41
+ const ws = new InMemoryWorkflowService()
42
+ const runId = await ws.createRun('flow', {}, false, 'hash', {
43
+ type: 'test',
44
+ })
45
+ // The row committed; the process died before the timer was armed.
46
+ await ws.insertStepState(runId, 'Wait 15s', null, { duration: 15000 })
47
+ await backdateSteps(ws, runId, 60_000)
48
+
49
+ const { redispatched } = await ws.relayUndispatchedSteps()
50
+
51
+ assert.deepEqual(redispatched, [runId], 'the run is re-dispatched')
52
+ assert.deepEqual(resumes.runIds, [runId], 'it is put back on the queue')
53
+ })
54
+
55
+ test('leaves a freshly written step alone', async () => {
56
+ const resumes = trackResumes()
57
+ const ws = new InMemoryWorkflowService()
58
+ const runId = await ws.createRun('flow', {}, false, 'hash', {
59
+ type: 'test',
60
+ })
61
+ // Written milliseconds ago — its dispatch is almost certainly in flight.
62
+ await ws.insertStepState(runId, 'Wait 15s', null, { duration: 15000 })
63
+
64
+ const { redispatched } = await ws.relayUndispatchedSteps()
65
+
66
+ assert.deepEqual(redispatched, [], 'nothing is re-dispatched')
67
+ assert.deepEqual(resumes.runIds, [], 'nothing is queued')
68
+ })
69
+
70
+ test('backs off rather than re-dispatching the same step every tick', async () => {
71
+ const resumes = trackResumes()
72
+ const ws = new InMemoryWorkflowService()
73
+ const runId = await ws.createRun('flow', {}, false, 'hash', {
74
+ type: 'test',
75
+ })
76
+ await ws.insertStepState(runId, 'Charge card', 'charge', {})
77
+ await backdateSteps(ws, runId, 60_000)
78
+
79
+ const first = await ws.relayUndispatchedSteps()
80
+ // The step is still pending — a real queue backlog looks exactly like this.
81
+ const second = await ws.relayUndispatchedSteps()
82
+
83
+ assert.deepEqual(first.redispatched, [runId], 'the first tick relays it')
84
+ assert.deepEqual(
85
+ second.redispatched,
86
+ [],
87
+ 'the next tick is held off by the backoff'
88
+ )
89
+ assert.deepEqual(resumes.runIds, [runId], 'only one queue message')
90
+ })
91
+
92
+ test('ignores steps belonging to a settled run', async () => {
93
+ const resumes = trackResumes()
94
+ const ws = new InMemoryWorkflowService()
95
+ const runId = await ws.createRun('flow', {}, false, 'hash', {
96
+ type: 'test',
97
+ })
98
+ await ws.insertStepState(runId, 'Wait 15s', null, { duration: 15000 })
99
+ await backdateSteps(ws, runId, 60_000)
100
+ await ws.updateRunStatus(runId, 'completed', {})
101
+
102
+ const { redispatched } = await ws.relayUndispatchedSteps()
103
+
104
+ assert.deepEqual(redispatched, [], 'a finished run is not re-dispatched')
105
+ assert.deepEqual(resumes.runIds, [], 'nothing is queued')
106
+ })
107
+
108
+ test('re-dispatches each stuck run once per tick', async () => {
109
+ const resumes = trackResumes()
110
+ const ws = new InMemoryWorkflowService()
111
+ const runIds: string[] = []
112
+ for (const n of [1, 2]) {
113
+ const runId = await ws.createRun('flow', {}, false, 'hash', {
114
+ type: 'test',
115
+ })
116
+ // Two orphaned steps in one run must still produce a single resume.
117
+ await ws.insertStepState(runId, `Wait ${n}a`, null, { duration: 1000 })
118
+ await ws.insertStepState(runId, `Wait ${n}b`, null, { duration: 1000 })
119
+ await backdateSteps(ws, runId, 60_000)
120
+ runIds.push(runId)
121
+ }
122
+
123
+ const { redispatched } = await ws.relayUndispatchedSteps()
124
+
125
+ assert.deepEqual(redispatched.sort(), runIds.sort(), 'both runs relayed')
126
+ assert.equal(resumes.runIds.length, 2, 'one queue message per run')
127
+ })
128
+ })
@@ -0,0 +1,128 @@
1
+ import { PikkuError, addError } from '../../errors/error-handler.js'
2
+ import type { ApprovalOutcome } from './workflow.types.js'
3
+
4
+ /**
5
+ * Thrown to unwind a run that cannot continue on this tick. Not a failure:
6
+ * the run resumes from its recorded step state.
7
+ */
8
+ export class WorkflowAsyncException extends Error {
9
+ constructor(
10
+ public readonly runId: string,
11
+ public readonly stepName: string
12
+ ) {
13
+ super(`Workflow paused at step: ${stepName}`)
14
+ this.name = 'WorkflowAsyncException'
15
+ }
16
+ }
17
+
18
+ export class WorkflowCancelledException extends Error {
19
+ constructor(
20
+ public readonly runId: string,
21
+ public readonly reason?: string
22
+ ) {
23
+ super(reason || 'Workflow cancelled')
24
+ this.name = 'WorkflowCancelledException'
25
+ }
26
+ }
27
+
28
+ export class WorkflowSuspendedException extends Error {
29
+ constructor(
30
+ public readonly runId: string,
31
+ public readonly reason: string
32
+ ) {
33
+ super(reason || 'Workflow suspended')
34
+ this.name = 'WorkflowSuspendedException'
35
+ }
36
+ }
37
+
38
+ export class WorkflowDispatchException extends Error {
39
+ constructor(
40
+ public readonly runId: string,
41
+ public readonly stepName: string,
42
+ options?: { cause?: unknown }
43
+ ) {
44
+ super(
45
+ `Failed to dispatch workflow step '${stepName}' (run ${runId})`,
46
+ options
47
+ )
48
+ this.name = 'WorkflowDispatchException'
49
+ }
50
+ }
51
+
52
+ export class WorkflowNotFoundError extends PikkuError {
53
+ constructor(name: string) {
54
+ super(`Workflow not found: ${name}`)
55
+ }
56
+ }
57
+ addError(WorkflowNotFoundError, {
58
+ status: 404,
59
+ message: 'Workflow not found.',
60
+ })
61
+
62
+ export class WorkflowRunNotFoundError extends PikkuError {
63
+ constructor(runId: string) {
64
+ super(`Workflow run not found: ${runId}`)
65
+ }
66
+ }
67
+ addError(WorkflowRunNotFoundError, {
68
+ status: 404,
69
+ message: 'Workflow run not found.',
70
+ })
71
+
72
+ export class WorkflowRunFailedError extends PikkuError {
73
+ public payload: { message?: string }
74
+ constructor(message?: string) {
75
+ super(`Workflow run failed: ${message ?? 'unknown'}`)
76
+ this.payload = { message }
77
+ }
78
+ }
79
+ addError(WorkflowRunFailedError, {
80
+ status: 422,
81
+ message: 'Workflow run failed.',
82
+ })
83
+
84
+ export class WorkflowRunCancelledError extends PikkuError {
85
+ constructor() {
86
+ super('Workflow was cancelled')
87
+ }
88
+ }
89
+ addError(WorkflowRunCancelledError, {
90
+ status: 409,
91
+ message: 'Workflow was cancelled.',
92
+ })
93
+
94
+ export class WorkflowApprovalResolvedError extends PikkuError {
95
+ public payload: {
96
+ reason: string
97
+ outcome: ApprovalOutcome<unknown>['status']
98
+ }
99
+ constructor(reason: string, outcome: ApprovalOutcome<unknown>['status']) {
100
+ super(`Approval already ${outcome}: ${reason}`)
101
+ this.payload = { reason, outcome }
102
+ }
103
+ }
104
+ addError(WorkflowApprovalResolvedError, {
105
+ status: 409,
106
+ message: 'Approval has already been resolved.',
107
+ })
108
+
109
+ export class WorkflowStepFunctionMismatchError extends PikkuError {
110
+ constructor(
111
+ public readonly runId: string,
112
+ public readonly stepName: string
113
+ ) {
114
+ super(
115
+ `Workflow step '${stepName}' (run ${runId}) was dispatched with a different function`
116
+ )
117
+ }
118
+ }
119
+ addError(WorkflowStepFunctionMismatchError, {
120
+ status: 409,
121
+ message: 'Workflow step was dispatched with a different function.',
122
+ })
123
+
124
+ export class WorkflowStepNameNotString extends Error {
125
+ constructor(stepName: unknown) {
126
+ super(`Workflow step name must be a string. Received: ${typeof stepName}`)
127
+ }
128
+ }
@@ -153,12 +153,18 @@ describe('a run that stops executing here leaves no per-run state behind', () =>
153
153
  })
154
154
  await ws.insertStepState(runId, 'a', 'someRpc', {})
155
155
 
156
- await ws.executeWorkflowStep(runId, 'a', 'someRpc', {}, {
157
- rpcWithWire: async () => {
158
- await ws.inlineStep(runId, 'nested', async () => 'ok')
159
- return 'ok'
160
- },
161
- })
156
+ await ws.executeWorkflowStep(
157
+ runId,
158
+ 'a',
159
+ 'someRpc',
160
+ {},
161
+ {
162
+ rpcWithWire: async () => {
163
+ await ws.inlineStep(runId, 'nested', async () => 'ok')
164
+ return 'ok'
165
+ },
166
+ }
167
+ )
162
168
 
163
169
  assert.equal(
164
170
  ws.runContexts.size,