@pikku/core 0.12.79 → 0.12.82

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 (479) hide show
  1. package/CHANGELOG.md +473 -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/errors/index.d.ts +1 -1
  7. package/dist/errors/index.js +1 -1
  8. package/dist/function/function-runner.js +22 -47
  9. package/dist/function/functions.types.d.ts +9 -5
  10. package/dist/function/index.d.ts +1 -1
  11. package/dist/index.d.ts +14 -19
  12. package/dist/index.js +6 -11
  13. package/dist/middleware/auth-cookie.d.ts +0 -4
  14. package/dist/middleware/auth-cookie.js +38 -2
  15. package/dist/middleware/cors.js +1 -0
  16. package/dist/middleware/index.d.ts +1 -1
  17. package/dist/middleware/index.js +1 -1
  18. package/dist/middleware/remote-auth.js +14 -3
  19. package/dist/permissions.d.ts +8 -10
  20. package/dist/permissions.js +0 -11
  21. package/dist/pikku-state.js +16 -5
  22. package/dist/schema.js +35 -1
  23. package/dist/services/ai-agent-runner-service.d.ts +7 -0
  24. package/dist/services/ai-run-state-service.d.ts +17 -1
  25. package/dist/services/in-memory-ai-run-state-service.d.ts +6 -2
  26. package/dist/services/in-memory-ai-run-state-service.js +11 -1
  27. package/dist/services/in-memory-workflow-service.js +2 -0
  28. package/dist/services/index.d.ts +15 -15
  29. package/dist/services/index.js +5 -5
  30. package/dist/services/local-content-request-handler.d.ts +21 -0
  31. package/dist/services/local-content-request-handler.js +72 -53
  32. package/dist/services/local-content.d.ts +6 -0
  33. package/dist/services/local-content.js +14 -1
  34. package/dist/services/scoped-credential-service.d.ts +21 -0
  35. package/dist/services/scoped-credential-service.js +53 -0
  36. package/dist/services/workflow-service.d.ts +4 -2
  37. package/dist/testing/service-tests/agent-run-service-tests.d.ts +10 -0
  38. package/dist/testing/service-tests/agent-run-service-tests.js +72 -0
  39. package/dist/testing/service-tests/ai-storage-service-tests.d.ts +3 -0
  40. package/dist/testing/service-tests/ai-storage-service-tests.js +302 -0
  41. package/dist/testing/service-tests/channel-store-tests.d.ts +3 -0
  42. package/dist/testing/service-tests/channel-store-tests.js +72 -0
  43. package/dist/testing/service-tests/credential-service-tests.d.ts +3 -0
  44. package/dist/testing/service-tests/credential-service-tests.js +109 -0
  45. package/dist/testing/service-tests/deployment-service-tests.d.ts +3 -0
  46. package/dist/testing/service-tests/deployment-service-tests.js +21 -0
  47. package/dist/testing/service-tests/event-hub-store-tests.d.ts +3 -0
  48. package/dist/testing/service-tests/event-hub-store-tests.js +34 -0
  49. package/dist/testing/service-tests/secret-service-tests.d.ts +3 -0
  50. package/dist/testing/service-tests/secret-service-tests.js +80 -0
  51. package/dist/testing/service-tests/session-store-tests.d.ts +3 -0
  52. package/dist/testing/service-tests/session-store-tests.js +43 -0
  53. package/dist/testing/service-tests/workflow-run-service-tests.d.ts +3 -0
  54. package/dist/testing/service-tests/workflow-run-service-tests.js +42 -0
  55. package/dist/testing/service-tests/workflow-service-tests.d.ts +3 -0
  56. package/dist/testing/service-tests/workflow-service-tests.js +150 -0
  57. package/dist/testing/service-tests.d.ts +6 -0
  58. package/dist/testing/service-tests.js +26 -791
  59. package/dist/types/core.types.d.ts +11 -3
  60. package/dist/types/state.types.d.ts +14 -1
  61. package/dist/wirings/actor-flow/index.d.ts +1 -1
  62. package/dist/wirings/actor-flow/run-conversation.js +1 -6
  63. package/dist/wirings/ai-agent/agent-rpc.d.ts +15 -0
  64. package/dist/wirings/ai-agent/agent-rpc.js +53 -0
  65. package/dist/wirings/ai-agent/ai-agent-agui.js +1 -5
  66. package/dist/wirings/ai-agent/ai-agent-finalize.d.ts +58 -0
  67. package/dist/wirings/ai-agent/ai-agent-finalize.js +138 -0
  68. package/dist/wirings/ai-agent/ai-agent-interrupt.js +1 -0
  69. package/dist/wirings/ai-agent/ai-agent-memory.d.ts +2 -8
  70. package/dist/wirings/ai-agent/ai-agent-memory.js +37 -18
  71. package/dist/wirings/ai-agent/ai-agent-model-config.d.ts +7 -0
  72. package/dist/wirings/ai-agent/ai-agent-model-config.js +44 -1
  73. package/dist/wirings/ai-agent/ai-agent-prepare.js +5 -9
  74. package/dist/wirings/ai-agent/ai-agent-runner.js +89 -147
  75. package/dist/wirings/ai-agent/ai-agent-stream.js +109 -97
  76. package/dist/wirings/ai-agent/ai-agent-turn.d.ts +57 -0
  77. package/dist/wirings/ai-agent/ai-agent-turn.js +82 -0
  78. package/dist/wirings/ai-agent/ai-agent.types.d.ts +47 -2
  79. package/dist/wirings/ai-agent/index.d.ts +8 -7
  80. package/dist/wirings/ai-agent/index.js +5 -4
  81. package/dist/wirings/ai-agent/voice-input.js +1 -6
  82. package/dist/wirings/ai-agent/voice-output.js +2 -12
  83. package/dist/wirings/ai-scorer/ai-scorer-grade.d.ts +26 -0
  84. package/dist/wirings/ai-scorer/ai-scorer-grade.js +33 -0
  85. package/dist/wirings/ai-scorer/ai-scorer-judge.d.ts +17 -0
  86. package/dist/wirings/ai-scorer/ai-scorer-judge.js +92 -0
  87. package/dist/wirings/ai-scorer/ai-scorer-live.d.ts +15 -0
  88. package/dist/wirings/ai-scorer/ai-scorer-live.js +38 -0
  89. package/dist/wirings/ai-scorer/ai-scorer-registry.d.ts +18 -0
  90. package/dist/wirings/ai-scorer/ai-scorer-registry.js +46 -0
  91. package/dist/wirings/ai-scorer/ai-scorer-sampling.d.ts +8 -0
  92. package/dist/wirings/ai-scorer/ai-scorer-sampling.js +31 -0
  93. package/dist/wirings/ai-scorer/ai-scorer-snapshots.d.ts +10 -0
  94. package/dist/wirings/ai-scorer/ai-scorer-snapshots.js +40 -0
  95. package/dist/wirings/ai-scorer/ai-scorer-worker.d.ts +15 -0
  96. package/dist/wirings/ai-scorer/ai-scorer-worker.js +58 -0
  97. package/dist/wirings/ai-scorer/ai-scorer.d.ts +39 -0
  98. package/dist/wirings/ai-scorer/ai-scorer.js +40 -0
  99. package/dist/wirings/ai-scorer/ai-scorer.types.d.ts +90 -0
  100. package/dist/wirings/ai-scorer/ai-scorer.types.js +4 -0
  101. package/dist/wirings/ai-scorer/index.d.ts +6 -0
  102. package/dist/wirings/ai-scorer/index.js +5 -0
  103. package/dist/wirings/channel/channel-common.js +1 -0
  104. package/dist/wirings/channel/channel-handler.js +3 -5
  105. package/dist/wirings/channel/channel-rpc-service.d.ts +0 -6
  106. package/dist/wirings/channel/channel-rpc-service.js +0 -8
  107. package/dist/wirings/channel/channel-rpc.types.d.ts +6 -0
  108. package/dist/wirings/channel/channel-rpc.types.js +8 -0
  109. package/dist/wirings/channel/channel-runner.d.ts +1 -3
  110. package/dist/wirings/channel/channel-runner.js +16 -8
  111. package/dist/wirings/channel/channel.types.d.ts +2 -0
  112. package/dist/wirings/channel/index.d.ts +5 -6
  113. package/dist/wirings/channel/index.js +3 -4
  114. package/dist/wirings/channel/local/local-channel-runner.js +8 -1
  115. package/dist/wirings/channel/pikku-abstract-channel-handler.js +1 -0
  116. package/dist/wirings/channel/serverless/serverless-channel-runner.js +3 -0
  117. package/dist/wirings/cli/channel/cli-channel-runner.js +2 -0
  118. package/dist/wirings/cli/channel/cli-raw-channel-runner.js +9 -1
  119. package/dist/wirings/cli/channel/index.d.ts +1 -2
  120. package/dist/wirings/cli/channel/index.js +0 -1
  121. package/dist/wirings/cli/cli-runner.js +17 -3
  122. package/dist/wirings/cli/cli.types.d.ts +0 -8
  123. package/dist/wirings/cli/command-parser.js +13 -0
  124. package/dist/wirings/credential/index.d.ts +1 -1
  125. package/dist/wirings/gateway/gateway-runner.js +9 -2
  126. package/dist/wirings/gateway/index.d.ts +1 -1
  127. package/dist/wirings/http/http-routes.js +2 -0
  128. package/dist/wirings/http/http-runner.d.ts +0 -10
  129. package/dist/wirings/http/http-runner.js +14 -15
  130. package/dist/wirings/http/http.types.d.ts +0 -10
  131. package/dist/wirings/http/index.d.ts +2 -3
  132. package/dist/wirings/http/index.js +1 -1
  133. package/dist/wirings/mcp/index.d.ts +1 -1
  134. package/dist/wirings/mcp/mcp-runner.d.ts +15 -7
  135. package/dist/wirings/mcp/mcp-runner.js +18 -11
  136. package/dist/wirings/persona/index.d.ts +3 -4
  137. package/dist/wirings/persona/index.js +2 -3
  138. package/dist/wirings/queue/index.d.ts +1 -3
  139. package/dist/wirings/queue/index.js +1 -3
  140. package/dist/wirings/rpc/addon-runner.d.ts +4 -0
  141. package/dist/wirings/rpc/addon-runner.js +19 -3
  142. package/dist/wirings/rpc/rpc-runner.d.ts +8 -51
  143. package/dist/wirings/rpc/rpc-runner.js +55 -86
  144. package/dist/wirings/rpc/rpc-types.d.ts +7 -0
  145. package/dist/wirings/rpc/wire-addon.d.ts +13 -0
  146. package/dist/wirings/rpc/wire-addon.js +4 -0
  147. package/dist/wirings/scheduler/index.d.ts +1 -1
  148. package/dist/wirings/secret/validate-secret-definitions.js +2 -2
  149. package/dist/wirings/trigger/index.d.ts +1 -1
  150. package/dist/wirings/trigger/pikku-trigger-service.d.ts +0 -4
  151. package/dist/wirings/trigger/trigger-runner.js +1 -0
  152. package/dist/wirings/virtual-user/index.d.ts +5 -6
  153. package/dist/wirings/virtual-user/index.js +2 -4
  154. package/dist/wirings/virtual-user/run-virtual-user.js +11 -11
  155. package/dist/wirings/virtual-user/virtual-user-derive.js +4 -25
  156. package/dist/wirings/virtual-user/virtual-user-dispositions.js +1 -4
  157. package/dist/wirings/workflow/dsl/workflow-dsl.types.d.ts +100 -3
  158. package/dist/wirings/workflow/feature.js +7 -4
  159. package/dist/wirings/workflow/graph/graph-runner.d.ts +1 -2
  160. package/dist/wirings/workflow/graph/graph-runner.js +8 -7
  161. package/dist/wirings/workflow/graph/workflow-graph.types.d.ts +0 -4
  162. package/dist/wirings/workflow/index.d.ts +12 -7
  163. package/dist/wirings/workflow/index.js +7 -3
  164. package/dist/wirings/workflow/pikku-scenario-service.d.ts +17 -3
  165. package/dist/wirings/workflow/pikku-scenario-service.js +64 -10
  166. package/dist/wirings/workflow/pikku-workflow-service.d.ts +28 -147
  167. package/dist/wirings/workflow/pikku-workflow-service.js +85 -493
  168. package/dist/wirings/workflow/scenario-step.types.d.ts +8 -0
  169. package/dist/wirings/workflow/workflow-approval-audit.d.ts +16 -0
  170. package/dist/wirings/workflow/workflow-approval-audit.js +40 -0
  171. package/dist/wirings/workflow/workflow-approval-policy.d.ts +20 -0
  172. package/dist/wirings/workflow/workflow-approval-policy.js +48 -0
  173. package/dist/wirings/workflow/workflow-approval.d.ts +67 -0
  174. package/dist/wirings/workflow/workflow-approval.js +177 -0
  175. package/dist/wirings/workflow/workflow-constants.d.ts +26 -0
  176. package/dist/wirings/workflow/workflow-constants.js +35 -0
  177. package/dist/wirings/workflow/workflow-errors.d.ts +58 -0
  178. package/dist/wirings/workflow/workflow-errors.js +112 -0
  179. package/dist/wirings/workflow/workflow-meta-resolver.d.ts +11 -0
  180. package/dist/wirings/workflow/workflow-meta-resolver.js +31 -0
  181. package/dist/wirings/workflow/workflow-queue-routing.d.ts +8 -0
  182. package/dist/wirings/workflow/workflow-queue-routing.js +38 -0
  183. package/dist/wirings/workflow/workflow-queue-wiring.d.ts +20 -0
  184. package/dist/wirings/workflow/workflow-queue-wiring.js +79 -0
  185. package/dist/wirings/workflow/workflow-recovery.d.ts +68 -0
  186. package/dist/wirings/workflow/workflow-recovery.js +101 -0
  187. package/dist/wirings/workflow/workflow-run-engine.types.d.ts +54 -0
  188. package/dist/wirings/workflow/workflow-run-ownership.d.ts +17 -0
  189. package/dist/wirings/workflow/workflow-run-ownership.js +30 -0
  190. package/dist/wirings/workflow/workflow-suspend.d.ts +12 -0
  191. package/dist/wirings/workflow/workflow-suspend.js +33 -0
  192. package/dist/wirings/workflow/workflow.types.d.ts +8 -1
  193. package/knowledge/decisions/internals/a-non-streaming-agent-run-registers-with-airunstate-too.md +22 -0
  194. package/knowledge/decisions/internals/a-resumed-agent-turn-is-as-interruptible-as-the-first.md +20 -0
  195. package/knowledge/decisions/internals/a-scenario-step-template-is-offered-unfilled.md +21 -0
  196. package/knowledge/decisions/internals/a-virtual-user-decides-whether-to-trust-memory-once-per-turn.md +21 -0
  197. package/knowledge/decisions/internals/a-wall-clock-threshold-is-a-load-test-in-disguise.md +46 -0
  198. package/knowledge/decisions/internals/a-workflow-wire-is-built-from-the-run-not-from-the-rpc-service.md +45 -0
  199. package/knowledge/decisions/internals/addon-pikku-meta-ships-at-the-package-root-or-under-dist.md +32 -0
  200. package/knowledge/decisions/internals/agent-context-waits-for-a-tool-result-still-being-written.md +21 -0
  201. package/knowledge/decisions/internals/agent-speech-travels-as-a-custom-agui-event.md +22 -0
  202. package/knowledge/decisions/internals/an-addon-scope-root-loses-to-a-root-the-host-already-declares.md +39 -0
  203. package/knowledge/decisions/internals/an-agent-interrupt-is-not-a-failure.md +23 -0
  204. package/knowledge/decisions/internals/an-agent-run-owned-by-another-instance-says-so.md +25 -0
  205. package/knowledge/decisions/internals/an-agent-stream-send-must-return-the-inner-sends-promise.md +22 -0
  206. package/knowledge/decisions/internals/an-empty-text-part-is-omitted-from-an-agent-message.md +20 -0
  207. package/knowledge/decisions/internals/an-empty-transcript-is-not-recorded.md +22 -0
  208. package/knowledge/decisions/internals/an-unref-d-timer-cannot-be-awaited-under-node-test.md +66 -0
  209. package/knowledge/decisions/internals/channel-state-accessors-are-unsound-generics-that-every-implementation-asserts.md +33 -0
  210. package/knowledge/decisions/internals/gateway-listener-middleware-runs-without-an-rpc-on-the-wire.md +43 -0
  211. package/knowledge/decisions/internals/hot-reload-writes-into-the-function-map-captured-at-startup.md +26 -0
  212. package/knowledge/decisions/internals/index.md +42 -3
  213. package/knowledge/decisions/internals/only-exposed-functions-enter-a-virtual-user-catalogue.md +21 -0
  214. package/knowledge/decisions/internals/scenario-given-and-when-are-sugar-but-then-is-not.md +24 -0
  215. package/knowledge/decisions/internals/side-effects-are-an-allowlist-not-a-boolean.md +34 -0
  216. package/knowledge/decisions/internals/speech-synthesis-picks-a-voice-per-sentence-and-warns-once.md +24 -0
  217. package/knowledge/decisions/internals/the-actor-prompt-says-json-because-of-json-object-mode.md +22 -0
  218. package/knowledge/decisions/internals/the-agent-done-event-goes-through-the-middleware-and-is-awaited.md +26 -0
  219. package/knowledge/decisions/internals/the-api-report-pins-members-not-just-names.md +43 -0
  220. package/knowledge/decisions/internals/the-ecosystem-entry-point-carries-the-adapter-surface.md +58 -0
  221. package/knowledge/decisions/internals/the-middleware-resolution-cache-is-deliberately-unbounded.md +40 -0
  222. package/knowledge/decisions/internals/the-per-invocation-rpc-view-is-a-class.md +40 -0
  223. package/knowledge/decisions/internals/the-persona-runtime-is-exported-from-the-persona-entry-point.md +28 -0
  224. package/knowledge/decisions/internals/the-transcript-event-is-sent-ahead-of-the-run.md +25 -0
  225. package/knowledge/decisions/internals/the-virtual-user-catalogue-is-the-only-gate-on-what-may-be-called.md +21 -0
  226. package/knowledge/decisions/internals/the-worker-disposition-is-the-one-that-is-not-testing.md +22 -0
  227. package/knowledge/decisions/internals/thread-history-records-the-transcript-not-the-audio.md +25 -0
  228. package/knowledge/decisions/internals/validate-runs-checks-by-precondition.md +115 -0
  229. package/knowledge/decisions/internals/virtual-user-step-order-comes-from-insertion-order.md +21 -0
  230. package/knowledge/decisions/internals/voice-output-speaks-unless-voice-input-explicitly-says-otherwise.md +24 -0
  231. package/knowledge/decisions/internals/wiring-registries-erase-the-generics-their-wire-functions-capture.md +35 -0
  232. package/knowledge/decisions/security/a-dropped-audit-write-is-always-logged.md +4 -2
  233. package/knowledge/decisions/security/a-function-never-receives-the-secret-service.md +37 -0
  234. package/knowledge/decisions/security/a-graph-run-starts-at-an-entry-node-the-graph-declared.md +33 -0
  235. package/knowledge/decisions/security/a-permission-gets-a-wire-it-cannot-reply-on.md +33 -0
  236. package/knowledge/decisions/security/a-step-runs-the-function-the-workflow-dispatched-it-with.md +37 -0
  237. package/knowledge/decisions/security/a-virtual-user-is-never-offered-a-step-that-would-forge-its-own-oracle.md +28 -0
  238. package/knowledge/decisions/security/a-workflow-run-is-read-and-approved-by-its-owner.md +50 -0
  239. package/knowledge/decisions/security/an-agent-approval-is-claimed-before-the-tool-runs.md +33 -0
  240. package/knowledge/decisions/security/an-approval-answer-outlives-the-run-it-answered.md +59 -0
  241. package/knowledge/decisions/security/an-upload-is-counted-as-it-arrives-not-buffered-then-measured.md +24 -0
  242. package/knowledge/decisions/security/index.md +9 -0
  243. package/knowledge/questions/channel-middleware-accepts-bare-factories-that-nothing-resolves.md +35 -0
  244. package/knowledge/questions/index.md +2 -1
  245. package/knowledge/questions/unauthorized-channel-replies-escape-the-declared-out-type.md +44 -0
  246. package/package.json +15 -3
  247. package/scripts/generate-api-report.d.mts +1 -0
  248. package/scripts/generate-api-report.mjs +89 -0
  249. package/scripts/generate-api-report.mts +343 -0
  250. package/src/api-report.test.ts +69 -0
  251. package/src/column-form.ts +1 -4
  252. package/src/crypto-utils.test.ts +15 -2
  253. package/src/dev/hot-reload.ts +2 -7
  254. package/src/ecosystem.ts +40 -0
  255. package/src/errors/error-handler.ts +5 -3
  256. package/src/errors/error.test.ts +4 -1
  257. package/src/errors/index.ts +1 -1
  258. package/src/function/function-runner.test.ts +53 -1
  259. package/src/function/function-runner.ts +33 -48
  260. package/src/function/functions.types.ts +15 -9
  261. package/src/function/index.ts +0 -2
  262. package/src/handle-error.ts +1 -1
  263. package/src/index.ts +3 -57
  264. package/src/middleware/auth-cookie.test.ts +50 -0
  265. package/src/middleware/auth-cookie.ts +38 -2
  266. package/src/middleware/cors.ts +2 -1
  267. package/src/middleware/index.ts +1 -1
  268. package/src/middleware/remote-auth.test.ts +43 -0
  269. package/src/middleware/remote-auth.ts +17 -3
  270. package/src/middleware-runner.ts +4 -2
  271. package/src/no-any-casts.test.ts +57 -0
  272. package/src/permissions.test.ts +3 -1
  273. package/src/permissions.ts +22 -24
  274. package/src/pikku-state.ts +22 -6
  275. package/src/public-surface.json +554 -0
  276. package/src/public-surface.json.README +25 -0
  277. package/src/public-surface.test.ts +105 -0
  278. package/src/removed-legacy-exports.test.ts +62 -0
  279. package/src/schema.test.ts +78 -0
  280. package/src/schema.ts +36 -1
  281. package/src/services/ai-agent-runner-service.ts +12 -1
  282. package/src/services/ai-run-state-service.ts +18 -1
  283. package/src/services/audit-service.ts +2 -2
  284. package/src/services/in-memory-ai-run-state-service.ts +16 -2
  285. package/src/services/in-memory-workflow-service.ts +2 -0
  286. package/src/services/index.ts +4 -47
  287. package/src/services/local-content-request-handler.test.ts +43 -5
  288. package/src/services/local-content-request-handler.ts +103 -74
  289. package/src/services/local-content.ts +15 -1
  290. package/src/services/local-email-service.ts +5 -1
  291. package/src/services/scoped-credential-service.test.ts +86 -0
  292. package/src/services/scoped-credential-service.ts +63 -0
  293. package/src/services/system-role-guard.test.ts +4 -1
  294. package/src/services/workflow-service.ts +9 -2
  295. package/src/side-effects-are-declared.test.ts +84 -0
  296. package/src/source-files-stay-composable.test.ts +41 -0
  297. package/src/testing/service-tests/agent-run-service-tests.ts +98 -0
  298. package/src/testing/service-tests/ai-storage-service-tests.ts +379 -0
  299. package/src/testing/service-tests/channel-store-tests.ts +98 -0
  300. package/src/testing/service-tests/credential-service-tests.ts +143 -0
  301. package/src/testing/service-tests/deployment-service-tests.ts +33 -0
  302. package/src/testing/service-tests/event-hub-store-tests.ts +48 -0
  303. package/src/testing/service-tests/secret-service-tests.ts +105 -0
  304. package/src/testing/service-tests/session-store-tests.ts +62 -0
  305. package/src/testing/service-tests/workflow-run-service-tests.ts +59 -0
  306. package/src/testing/service-tests/workflow-service-tests.ts +308 -0
  307. package/src/testing/service-tests.ts +31 -1111
  308. package/src/types/core.types.ts +14 -3
  309. package/src/types/state.types.ts +17 -1
  310. package/src/wirings/actor-flow/index.ts +0 -3
  311. package/src/wirings/actor-flow/run-conversation.ts +1 -6
  312. package/src/wirings/ai-agent/agent-rpc.ts +120 -0
  313. package/src/wirings/ai-agent/ai-agent-agui.ts +1 -5
  314. package/src/wirings/ai-agent/ai-agent-finalize.test.ts +186 -0
  315. package/src/wirings/ai-agent/ai-agent-finalize.ts +197 -0
  316. package/src/wirings/ai-agent/ai-agent-interrupt.test.ts +2 -1
  317. package/src/wirings/ai-agent/ai-agent-interrupt.ts +1 -0
  318. package/src/wirings/ai-agent/ai-agent-memory.ts +62 -39
  319. package/src/wirings/ai-agent/ai-agent-model-config.test.ts +72 -3
  320. package/src/wirings/ai-agent/ai-agent-model-config.ts +49 -1
  321. package/src/wirings/ai-agent/ai-agent-prepare.ts +12 -12
  322. package/src/wirings/ai-agent/ai-agent-resume-authorization.test.ts +1 -0
  323. package/src/wirings/ai-agent/ai-agent-runner.test.ts +82 -2
  324. package/src/wirings/ai-agent/ai-agent-runner.ts +120 -160
  325. package/src/wirings/ai-agent/ai-agent-stream-output-hooks.test.ts +353 -0
  326. package/src/wirings/ai-agent/ai-agent-stream.test.ts +2 -0
  327. package/src/wirings/ai-agent/ai-agent-stream.ts +152 -117
  328. package/src/wirings/ai-agent/ai-agent-thread-ownership.test.ts +1 -1
  329. package/src/wirings/ai-agent/ai-agent-turn.test.ts +67 -0
  330. package/src/wirings/ai-agent/ai-agent-turn.ts +122 -0
  331. package/src/wirings/ai-agent/ai-agent.types.ts +65 -5
  332. package/src/wirings/ai-agent/index.ts +2 -16
  333. package/src/wirings/ai-agent/voice-input.ts +1 -6
  334. package/src/wirings/ai-agent/voice-output.ts +2 -12
  335. package/src/wirings/ai-scorer/ai-scorer-grade.test.ts +106 -0
  336. package/src/wirings/ai-scorer/ai-scorer-grade.ts +55 -0
  337. package/src/wirings/ai-scorer/ai-scorer-judge.test.ts +143 -0
  338. package/src/wirings/ai-scorer/ai-scorer-judge.ts +120 -0
  339. package/src/wirings/ai-scorer/ai-scorer-live.test.ts +174 -0
  340. package/src/wirings/ai-scorer/ai-scorer-live.ts +56 -0
  341. package/src/wirings/ai-scorer/ai-scorer-registry.ts +63 -0
  342. package/src/wirings/ai-scorer/ai-scorer-sampling.test.ts +34 -0
  343. package/src/wirings/ai-scorer/ai-scorer-sampling.ts +36 -0
  344. package/src/wirings/ai-scorer/ai-scorer-snapshots.test.ts +49 -0
  345. package/src/wirings/ai-scorer/ai-scorer-snapshots.ts +46 -0
  346. package/src/wirings/ai-scorer/ai-scorer-worker.test.ts +122 -0
  347. package/src/wirings/ai-scorer/ai-scorer-worker.ts +69 -0
  348. package/src/wirings/ai-scorer/ai-scorer.ts +76 -0
  349. package/src/wirings/ai-scorer/ai-scorer.types.ts +107 -0
  350. package/src/wirings/ai-scorer/index.ts +24 -0
  351. package/src/wirings/channel/channel-common.ts +5 -2
  352. package/src/wirings/channel/channel-handler-shapes.test.ts +72 -0
  353. package/src/wirings/channel/channel-handler.ts +7 -7
  354. package/src/wirings/channel/channel-rpc-service.ts +0 -14
  355. package/src/wirings/channel/channel-rpc.test.ts +25 -4
  356. package/src/wirings/channel/channel-rpc.types.ts +14 -0
  357. package/src/wirings/channel/channel-runner.ts +33 -20
  358. package/src/wirings/channel/channel.types.ts +2 -0
  359. package/src/wirings/channel/index.ts +1 -20
  360. package/src/wirings/channel/local/local-channel-runner.test.ts +68 -0
  361. package/src/wirings/channel/local/local-channel-runner.ts +9 -2
  362. package/src/wirings/channel/pikku-abstract-channel-handler.ts +2 -1
  363. package/src/wirings/channel/serverless/serverless-channel-runner.ts +6 -3
  364. package/src/wirings/cli/channel/cli-channel-runner.ts +3 -1
  365. package/src/wirings/cli/channel/cli-raw-channel-runner.test.ts +23 -0
  366. package/src/wirings/cli/channel/cli-raw-channel-runner.ts +12 -1
  367. package/src/wirings/cli/channel/cli-raw-client-runner.ts +4 -1
  368. package/src/wirings/cli/channel/index.ts +0 -7
  369. package/src/wirings/cli/cli-runner.test.ts +68 -0
  370. package/src/wirings/cli/cli-runner.ts +25 -5
  371. package/src/wirings/cli/cli.types.ts +0 -39
  372. package/src/wirings/cli/command-parser.test.ts +19 -0
  373. package/src/wirings/cli/command-parser.ts +17 -1
  374. package/src/wirings/credential/index.ts +0 -1
  375. package/src/wirings/gateway/gateway-channel-meta.test.ts +44 -0
  376. package/src/wirings/gateway/gateway-runner.ts +27 -19
  377. package/src/wirings/gateway/index.ts +0 -3
  378. package/src/wirings/http/http-routes.ts +4 -1
  379. package/src/wirings/http/http-runner.test.ts +66 -0
  380. package/src/wirings/http/http-runner.ts +21 -28
  381. package/src/wirings/http/http.types.ts +0 -15
  382. package/src/wirings/http/index.ts +2 -8
  383. package/src/wirings/http/pikku-fetch-http-request.ts +2 -2
  384. package/src/wirings/http/web-request.ts +1 -1
  385. package/src/wirings/mcp/index.ts +0 -1
  386. package/src/wirings/mcp/mcp-runner.test.ts +181 -0
  387. package/src/wirings/mcp/mcp-runner.ts +37 -21
  388. package/src/wirings/persona/index.ts +0 -8
  389. package/src/wirings/persona/persona-environments.test.ts +14 -3
  390. package/src/wirings/persona/persona.test.ts +13 -3
  391. package/src/wirings/persona/validate-personas.ts +5 -1
  392. package/src/wirings/queue/index.ts +0 -14
  393. package/src/wirings/queue/queue-runner.ts +1 -1
  394. package/src/wirings/rpc/addon-auth-tags.test.ts +1 -5
  395. package/src/wirings/rpc/addon-runner.ts +34 -3
  396. package/src/wirings/rpc/addon-secrets.test.ts +261 -0
  397. package/src/wirings/rpc/rpc-runner.test.ts +2 -0
  398. package/src/wirings/rpc/rpc-runner.ts +60 -136
  399. package/src/wirings/rpc/rpc-types.ts +11 -0
  400. package/src/wirings/rpc/wire-addon.ts +20 -1
  401. package/src/wirings/scheduler/index.ts +0 -1
  402. package/src/wirings/secret/validate-secret-definitions.test.ts +22 -0
  403. package/src/wirings/secret/validate-secret-definitions.ts +2 -2
  404. package/src/wirings/trigger/index.ts +0 -1
  405. package/src/wirings/trigger/pikku-trigger-service.ts +0 -5
  406. package/src/wirings/trigger/trigger-runner.ts +7 -5
  407. package/src/wirings/virtual-user/index.ts +0 -16
  408. package/src/wirings/virtual-user/run-virtual-user.test.ts +18 -9
  409. package/src/wirings/virtual-user/run-virtual-user.ts +28 -15
  410. package/src/wirings/virtual-user/virtual-user-agents.test.ts +4 -1
  411. package/src/wirings/virtual-user/virtual-user-derive.ts +4 -25
  412. package/src/wirings/virtual-user/virtual-user-dispositions.test.ts +7 -2
  413. package/src/wirings/virtual-user/virtual-user-dispositions.ts +1 -4
  414. package/src/wirings/virtual-user/virtual-user-intents.test.ts +13 -3
  415. package/src/wirings/workflow/dsl/workflow-dsl.types.ts +117 -4
  416. package/src/wirings/workflow/feature.ts +7 -4
  417. package/src/wirings/workflow/graph/graph-node.ts +1 -1
  418. package/src/wirings/workflow/graph/graph-runner.test.ts +76 -2
  419. package/src/wirings/workflow/graph/graph-runner.ts +13 -16
  420. package/src/wirings/workflow/graph/workflow-graph.types.ts +0 -5
  421. package/src/wirings/workflow/index.ts +14 -24
  422. package/src/wirings/workflow/pikku-scenario-service.ts +101 -27
  423. package/src/wirings/workflow/pikku-workflow-service.test.ts +15 -14
  424. package/src/wirings/workflow/pikku-workflow-service.ts +214 -743
  425. package/src/wirings/workflow/scenario-expectations.test.ts +75 -0
  426. package/src/wirings/workflow/scenario-hooks.test.ts +52 -0
  427. package/src/wirings/workflow/scenario-step.types.ts +8 -0
  428. package/src/wirings/workflow/workflow-approval-audit.ts +47 -0
  429. package/src/wirings/workflow/workflow-approval-policy.test.ts +524 -0
  430. package/src/wirings/workflow/workflow-approval-policy.ts +68 -0
  431. package/src/wirings/workflow/workflow-approval.ts +289 -0
  432. package/src/wirings/workflow/workflow-child-run-session.test.ts +89 -0
  433. package/src/wirings/workflow/workflow-constants.ts +47 -0
  434. package/src/wirings/workflow/workflow-dispatch-durability.test.ts +1 -1
  435. package/src/wirings/workflow/workflow-errors.ts +128 -0
  436. package/src/wirings/workflow/workflow-inline-authority.test.ts +12 -6
  437. package/src/wirings/workflow/workflow-meta-resolver.ts +45 -0
  438. package/src/wirings/workflow/workflow-missing-meta.test.ts +92 -0
  439. package/src/wirings/workflow/workflow-queue-routing.ts +85 -0
  440. package/src/wirings/workflow/workflow-queue-wiring.ts +149 -0
  441. package/src/wirings/workflow/workflow-recovery.ts +162 -0
  442. package/src/wirings/workflow/workflow-retry-policy.test.ts +1 -1
  443. package/src/wirings/workflow/workflow-run-authority.test.ts +212 -0
  444. package/src/wirings/workflow/workflow-run-engine.types.ts +91 -0
  445. package/src/wirings/workflow/workflow-run-ownership.ts +37 -0
  446. package/src/wirings/workflow/workflow-suspend.ts +61 -0
  447. package/src/wirings/workflow/workflow.types.ts +7 -9
  448. package/src/wirings-stay-decoupled.test.ts +127 -0
  449. package/tsconfig.json +1 -1
  450. package/tsconfig.tsbuildinfo +1 -1
  451. package/dist/internal.d.ts +0 -3
  452. package/dist/internal.js +0 -2
  453. package/dist/middleware/timeout.d.ts +0 -9
  454. package/dist/middleware/timeout.js +0 -15
  455. package/dist/pikku-response.d.ts +0 -6
  456. package/dist/pikku-response.js +0 -6
  457. package/dist/services/gopass-secrets.d.ts +0 -15
  458. package/dist/services/gopass-secrets.js +0 -76
  459. package/dist/services/http-scenario-actors.d.ts +0 -75
  460. package/dist/services/http-scenario-actors.js +0 -195
  461. package/dist/services/http-user-flow-actors.d.ts +0 -67
  462. package/dist/services/http-user-flow-actors.js +0 -193
  463. package/dist/services/scenario-actors-service.d.ts +0 -127
  464. package/dist/services/scenario-actors-service.js +0 -40
  465. package/dist/services/user-flow-actors-service.d.ts +0 -39
  466. package/dist/wirings/credential/wire-credential.d.ts +0 -48
  467. package/dist/wirings/credential/wire-credential.js +0 -47
  468. package/dist/wirings/oauth2/oauth2-client.d.ts +0 -47
  469. package/dist/wirings/oauth2/oauth2-client.js +0 -263
  470. package/dist/wirings/oauth2/oauth2-routes.d.ts +0 -35
  471. package/dist/wirings/oauth2/oauth2-routes.js +0 -146
  472. package/dist/wirings/scope/wire-scope.d.ts +0 -33
  473. package/dist/wirings/scope/wire-scope.js +0 -32
  474. package/dist/wirings/workflow/dsl/index.d.ts +0 -5
  475. package/dist/wirings/workflow/dsl/index.js +0 -4
  476. package/dist/wirings/workflow/graph/index.d.ts +0 -5
  477. package/dist/wirings/workflow/graph/index.js +0 -4
  478. package/src/internal.ts +0 -10
  479. /package/dist/{services/user-flow-actors-service.js → wirings/workflow/workflow-run-engine.types.js} +0 -0
@@ -84,7 +84,6 @@ export const runPikkuFunc = async (wireType, wireId, funcName, { singletonServic
84
84
  throw new Error(`Function meta not found: ${funcName}`);
85
85
  }
86
86
  const resolvedFunctionId = funcMeta.pikkuFuncId ?? funcName;
87
- const keepsSecrets = funcMeta.secretBroker === true;
88
87
  const resolvedSingletonServices = packageName
89
88
  ? await getOrCreatePackageSingletonServices(packageName, singletonServices, addonInstance)
90
89
  : singletonServices;
@@ -124,6 +123,23 @@ export const runPikkuFunc = async (wireType, wireId, funcName, { singletonServic
124
123
  const previousAudit = invocationWire.audit;
125
124
  const previousAddonNamespace = invocationWire.addonNamespace;
126
125
  const previousRpcDescriptor = Object.getOwnPropertyDescriptor(invocationWire, 'rpc');
126
+ // knowledge: decisions/internals/core-function-runner-restores-the-wire-fields-it-overwrites.md
127
+ const restoreInvocationWire = () => {
128
+ if (previousRpcDescriptor) {
129
+ Object.defineProperty(invocationWire, 'rpc', previousRpcDescriptor);
130
+ }
131
+ restoreField('functionId', previousFunctionId);
132
+ restoreField('audit', previousAudit);
133
+ restoreField('addonNamespace', previousAddonNamespace);
134
+ };
135
+ function restoreField(key, previous) {
136
+ if (previous === undefined) {
137
+ delete invocationWire[key];
138
+ }
139
+ else {
140
+ invocationWire[key] = previous;
141
+ }
142
+ }
127
143
  invocationWire.functionId = resolvedFunctionId;
128
144
  invocationWire.audit = resolvedAuditConfig;
129
145
  // Track which addon instance is executing so intra-addon sibling calls
@@ -184,9 +200,8 @@ export const runPikkuFunc = async (wireType, wireId, funcName, { singletonServic
184
200
  }
185
201
  await runPermissions({
186
202
  funcPermissions: funcConfig.permissions,
187
- services: keepsSecrets
188
- ? resolvedSingletonServices
189
- : withoutSecrets(resolvedSingletonServices, 'a permission'),
203
+ services: withoutSecrets(resolvedSingletonServices, 'a permission'),
204
+ // knowledge: decisions/security/a-permission-gets-a-wire-it-cannot-reply-on.md
190
205
  wire: invocationWire,
191
206
  data: actualData,
192
207
  packageName,
@@ -219,7 +234,7 @@ export const runPikkuFunc = async (wireType, wireId, funcName, { singletonServic
219
234
  configurable: true,
220
235
  enumerable: true,
221
236
  });
222
- return await funcConfig.func(keepsSecrets ? services : withoutSecrets(services, 'a pikku function'), actualData, invocationWire);
237
+ return await funcConfig.func(withoutSecrets(services, 'a pikku function'), actualData, invocationWire);
223
238
  }
224
239
  finally {
225
240
  // Flush the runner-installed audit buffer before wire services close.
@@ -244,53 +259,13 @@ export const runPikkuFunc = async (wireType, wireId, funcName, { singletonServic
244
259
  return (await runMiddleware(resolvedSingletonServices, invocationWire, allMiddleware, executeFunction));
245
260
  }
246
261
  finally {
247
- if (previousRpcDescriptor) {
248
- Object.defineProperty(invocationWire, 'rpc', previousRpcDescriptor);
249
- }
250
- if (previousFunctionId === undefined) {
251
- delete invocationWire.functionId;
252
- }
253
- else {
254
- invocationWire.functionId = previousFunctionId;
255
- }
256
- if (previousAudit === undefined) {
257
- delete invocationWire.audit;
258
- }
259
- else {
260
- invocationWire.audit = previousAudit;
261
- }
262
- if (previousAddonNamespace === undefined) {
263
- delete invocationWire.addonNamespace;
264
- }
265
- else {
266
- invocationWire.addonNamespace = previousAddonNamespace;
267
- }
262
+ restoreInvocationWire();
268
263
  }
269
264
  }
270
265
  try {
271
266
  return (await executeFunction());
272
267
  }
273
268
  finally {
274
- if (previousRpcDescriptor) {
275
- Object.defineProperty(invocationWire, 'rpc', previousRpcDescriptor);
276
- }
277
- if (previousFunctionId === undefined) {
278
- delete invocationWire.functionId;
279
- }
280
- else {
281
- invocationWire.functionId = previousFunctionId;
282
- }
283
- if (previousAudit === undefined) {
284
- delete invocationWire.audit;
285
- }
286
- else {
287
- invocationWire.audit = previousAudit;
288
- }
289
- if (previousAddonNamespace === undefined) {
290
- delete invocationWire.addonNamespace;
291
- }
292
- else {
293
- invocationWire.addonNamespace = previousAddonNamespace;
294
- }
269
+ restoreInvocationWire();
295
270
  }
296
271
  };
@@ -5,11 +5,6 @@ import type { PikkuError } from '../errors/error-handler.js';
5
5
  import type { CoreNodeConfig } from '../wirings/node/node.types.js';
6
6
  import type { ScenarioSurface } from '../wirings/workflow/scenario-step.types.js';
7
7
  import type { Safe } from '../secret-value.js';
8
- /**
9
- * @deprecated Use StandardSchemaV1 from @standard-schema/spec instead.
10
- * This alias exists only for backward compatibility with generated code.
11
- */
12
- export type ZodLike<T = any> = StandardSchemaV1<T, T>;
13
8
  export type CorePikkuFunction<In, Out, Services extends CoreSecretlessSingletonServices = SecretlessServices<CoreServices>, Session extends CoreUserSession = CoreUserSession, Wire extends PikkuWire<In, Out, true, Session, PikkuRPC, null, string> = PikkuWire<In, Out, true, Session>> = (services: Services, data: In, wire: Wire) => Wire['channel'] extends null ? Promise<Safe<Out>> : Promise<Safe<Out>> | Promise<void>;
14
9
  export type CorePikkuFunctionSessionless<In, Out, Services extends CoreSecretlessSingletonServices = SecretlessServices<CoreServices>, Session extends CoreUserSession = CoreUserSession, Wire extends PikkuWire<In, Out, false, Session, PikkuRPC, null, string> = PikkuWire<In, Out, false, Session>> = (services: Services, data: In, wire: Wire) => Wire['channel'] extends null ? Promise<Safe<Out>> : Promise<Safe<Out>> | Promise<void>;
15
10
  export type CorePikkuPermission<In = any, Services extends CoreSecretlessSingletonServices = SecretlessServices<CoreServices>, Wire extends PikkuWire<In, never, false, any, PikkuRPC, never, never> = PikkuWire<In, never, false, any, PikkuRPC, never, never>> = (services: Services, data: In, wire: Wire) => Promise<boolean>;
@@ -33,6 +28,15 @@ export type CorePikkuAuthConfig<Services extends CoreSecretlessSingletonServices
33
28
  name?: string;
34
29
  description?: string;
35
30
  };
31
+ /**
32
+ * Marks a permission produced by `pikkuAuth`, so agent tool filtering can tell a
33
+ * session check apart from an ordinary permission.
34
+ *
35
+ * knowledge: decisions/security/permission-auth-filtering-requires-live-permission-functions.md
36
+ */
37
+ export type AuthBranded = {
38
+ __pikkuAuth?: true;
39
+ };
36
40
  export declare const pikkuAuth: <Services extends CoreSecretlessSingletonServices = SecretlessServices<CoreServices>, Session extends CoreUserSession = CoreUserSession>(auth: CorePikkuAuth<Services, Session> | CorePikkuAuthConfig<Services, Session>) => CorePikkuPermission<any, Services, any>;
37
41
  export type CorePermissionGroup<PikkuPermission = CorePikkuPermission<any>> = Record<string, PikkuPermission | PikkuPermission[]> | undefined;
38
42
  /**
@@ -1,4 +1,4 @@
1
1
  export { addFunction, getAllFunctionNames } from './function-runner.js';
2
2
  export { pikkuAuth, pikkuPermission, pikkuPermissionFactory, pikkuApprovalDescription, } from './functions.types.js';
3
3
  export type { CorePikkuFunction, CorePikkuFunctionSessionless, CorePikkuFunctionConfig, CorePikkuSessionlessFunctionConfig, CorePikkuAuth, CorePikkuAuthConfig, CorePikkuPermission, } from './functions.types.js';
4
- export type { ListInput, ListOutput, Filter, LeafFilter, LeafValue, } from './list.types.js';
4
+ export type { ListInput, ListOutput, Filter, } from './list.types.js';
package/dist/index.d.ts CHANGED
@@ -1,30 +1,26 @@
1
1
  /**
2
2
  * @module @pikku/core
3
3
  */
4
- export type { AuthInstance, CommonWireMeta, CoreConfig, CorePikkuMiddleware, CorePikkuMiddlewareConfig, CorePikkuMiddlewareFactory, CorePikkuMiddlewareGroup, CoreServices, CoreSecretlessSingletonServices, CoreSingletonServices, CoreUserSession, SecretlessServices, CreateConfig, ServerLifecycle, FunctionMeta, FunctionRuntimeMeta, FunctionServicesMeta, FunctionWiresMeta, FunctionsMeta, FunctionsRuntimeMeta, JSONPrimitive, JSONValue, MakeRequired, MiddlewareMetadata, MiddlewarePriority, PermissionMetadata, PickOptional, PickRequired, PikkuAIMiddlewareHooks, PikkuWire, PikkuRawWire, PikkuWiringTypes, PostgresConfig, RequireAtLeastOne, SecurityAuditIssue, SecurityAuditReport, SecurityAuditSummary, SecurityAuditUpdate, SecuritySeverity, SecurityUpdateLevel, SerializedError, WireServices, } from './types/core.types.js';
4
+ export type { AuthInstance, CommonWireMeta, CoreConfig, CorePikkuMiddleware, CorePikkuMiddlewareConfig, CorePikkuMiddlewareFactory, CorePikkuMiddlewareGroup, CoreServices, CoreSecretlessSingletonServices, CoreSingletonServices, CoreUserSession, SecretlessServices, CreateConfig, ServerLifecycle, FunctionMeta, FunctionServicesMeta, FunctionWiresMeta, FunctionsMeta, FunctionsRuntimeMeta, JSONValue, MakeRequired, MiddlewareMetadata, MiddlewarePriority, PermissionMetadata, PickOptional, PickRequired, PikkuAIMiddlewareHooks, PikkuWire, PikkuRawWire, PikkuWiringTypes, PostgresConfig, RequireAtLeastOne, SecurityAuditIssue, SecurityAuditReport, SecurityAuditSummary, SecurityAuditUpdate, SecuritySeverity, SecurityUpdateLevel, SerializedError, } from './types/core.types.js';
5
5
  export { pikkuAIMiddleware, pikkuChannelMiddleware, pikkuChannelMiddlewareFactory, pikkuMiddleware, pikkuMiddlewareFactory, } from './types/core.types.js';
6
- export type { CorePikkuAuth, CorePikkuAuthConfig, CorePikkuFunction, CorePikkuFunctionConfig, CorePikkuFunctionHook, CorePikkuPermission, CorePikkuPermissionConfig, CorePikkuPermissionFactory, CorePikkuApprovalDescription, CorePermissionGroup, ZodLike, } from './function/functions.types.js';
6
+ export type { CorePikkuAuth, CorePikkuAuthConfig, CorePikkuFunction, CorePikkuFunctionConfig, CorePikkuPermission, CorePikkuPermissionConfig, CorePikkuPermissionFactory, CorePikkuApprovalDescription, CorePermissionGroup, } from './function/functions.types.js';
7
7
  export { pikkuAuth, pikkuPermission, pikkuPermissionFactory, pikkuApprovalDescription, } from './function/functions.types.js';
8
- export { addFunction, getAllFunctionNames } from './function/index.js';
9
- export type { ListInput, ListOutput, Filter, LeafFilter, LeafValue, } from './function/list.types.js';
8
+ export { getAllFunctionNames } from './function/index.js';
9
+ export type { ListInput, ListOutput, Filter, } from './function/list.types.js';
10
+ export { pikkuCLIRender } from './wirings/cli/cli-runner.js';
10
11
  export { PikkuRequest } from './pikku-request.js';
11
12
  export { getRelativeTimeOffsetFromNow, parseDurationString, } from './time-utils.js';
12
13
  export type { RelativeTimeInput } from './time-utils.js';
13
14
  export { formatVersionedId, isVersionedId, parseVersionedId, } from './version.js';
14
- export { runPikkuFunc } from './function/function-runner.js';
15
- export { AbandonedError, beginChanges, getAbortScope, runInAbortScope, type AbortScope, } from './function/abort-scope.js';
16
- export { runCLICommand, pikkuCLIRender } from './wirings/cli/cli-runner.js';
15
+ export { AbandonedError, type AbortScope, } from './function/abort-scope.js';
17
16
  export { fetch } from './wirings/http/http-runner.js';
18
- export { runMCPTool, runMCPResource, runMCPPrompt, } from './wirings/mcp/mcp-runner.js';
19
17
  export type { MCPToolResponse, MCPResourceResponse, MCPPromptResponse, } from './wirings/mcp/mcp.types.js';
20
- export { runQueueJob } from './wirings/queue/queue-runner.js';
21
- export { runScheduledTask } from './wirings/scheduler/scheduler-runner.js';
22
18
  export { AIProviderAuthError, AIProviderNotConfiguredError, BadGatewayError, BadRequestError, ConflictError, ExpectationFailedError, ForbiddenError, GatewayTimeoutError, GoneError, HTTPVersionNotSupportedError, InternalServerError, InvalidMiddlewareWireError, InvalidOriginError, InvalidSessionError, LengthRequiredError, LocalEnvironmentOnlyError, LockedError, MaxComputeTimeReachedError, MethodNotAllowedError, MissingCredentialError, MissingSchemaError, MissingScopeError, MissingServiceError, MissingSessionError, NotAcceptableError, NotFoundError, NotImplementedError, PayloadTooLargeError, PaymentRequiredError, PikkuMissingMetaError, PreconditionFailedError, ProxyAuthenticationRequiredError, RangeNotSatisfiableError, ReadonlySessionError, RequestTimeoutError, ServiceUnavailableError, TooManyRequestsError, URITooLongError, UnauthorizedError, UnprocessableContentError, UnsupportedMediaTypeError, } from './errors/errors.js';
23
19
  export { PikkuError, isExpectedError } from './errors/error-handler.js';
24
20
  export type { EventHubService } from './wirings/channel/eventhub-service.js';
25
21
  export type { QueueService } from './wirings/queue/queue.types.js';
26
22
  export type { JWTService } from './services/jwt-service.js';
27
- export type { EmailService, EmailTemplateReference, SendEmailInput, SendEmailResult, SendHTMLEmailInput, SendTemplateEmailInput, SendTextEmailInput, } from './services/email-service.js';
23
+ export type { EmailService, SendEmailInput, SendEmailResult, SendHTMLEmailInput, SendTemplateEmailInput, SendTextEmailInput, } from './services/email-service.js';
28
24
  export type { SecretService } from './services/secret-service.js';
29
25
  export { SecretAccessDeniedError, withoutSecrets, } from './services/secretless.js';
30
26
  export { SecretHostNotAllowedError, assertSecretAllowedForHost, } from './services/secret-host-binding.js';
@@ -36,13 +32,13 @@ export type { GatewayService } from './services/gateway-service.js';
36
32
  export type { TriggerService } from './services/trigger-service.js';
37
33
  export type { SchemaService } from './services/schema-service.js';
38
34
  export type { SessionService } from './services/user-session-service.js';
39
- export { NoopAuditService, createInvocationAudit, resolveAuditConfig, resolveAuditUserIdentityFromWire, } from './services/audit-service.js';
40
- export type { AuditConfig, AuditDurability, AuditEvent, AuditEventBatch, AuditFacets, AuditLog, AuditLogWriteInput, AuditOutcome, AuditQuery, AuditQueryResult, AuditService, AuditSource, AuditUserIdentity, ResolvedAuditConfig, } from './services/audit-service.js';
41
- export type { AIAgentRunnerService, AIEmbedManyParams, AIEmbedManyResult, AIEmbedParams, AIEmbedResult, AIGenerateImageParams, AIGenerateImagePrompt, AIGenerateImageResult, AIGenerateSpeechParams, AIGenerateSpeechResult, AIProviderOptions, AIRerankParams, AIRerankResult, AITranscriptionParams, AITranscriptionResult, } from './services/ai-agent-runner-service.js';
35
+ export { NoopAuditService, createInvocationAudit, } from './services/audit-service.js';
36
+ export type { AuditConfig, AuditDurability, AuditEvent, AuditEventBatch, AuditFacets, AuditLog, AuditQuery, AuditQueryResult, AuditService, AuditUserIdentity, ResolvedAuditConfig, } from './services/audit-service.js';
37
+ export type { AIAgentRunnerService, } from './services/ai-agent-runner-service.js';
42
38
  export type { AIEmbeddingService } from './services/ai-embedding-service.js';
43
39
  export type { AIRunStateService } from './services/ai-run-state-service.js';
44
40
  export type { AIStorageService } from './services/ai-storage-service.js';
45
- export type { EmailsMeta, EmailTemplateMeta, EmailTemplateLocaleMeta, EmailTemplateAssets, MetaService, } from './services/meta-service.js';
41
+ export type { EmailsMeta, EmailTemplateMeta, MetaService, } from './services/meta-service.js';
46
42
  export type { HTTPMethod } from './wirings/http/http.types.js';
47
43
  export type { GraphNodeConfig } from './wirings/workflow/graph/workflow-graph.types.js';
48
44
  export { createGraph } from './wirings/workflow/graph/graph-node.js';
@@ -51,15 +47,14 @@ export type { WireAddonConfig } from './wirings/rpc/wire-addon.js';
51
47
  export { wireRemoteAddon } from './wirings/rpc/wire-remote-addon.js';
52
48
  export type { WireRemoteAddonConfig, RemoteAddonAuth, } from './wirings/rpc/wire-remote-addon.js';
53
49
  export type { PikkuPackageState } from './types/state.types.js';
54
- export { runMiddleware, addTagMiddleware, addTagMiddleware as addMiddleware, addGlobalMiddleware, } from './middleware-runner.js';
50
+ export { runMiddleware, addTagMiddleware } from './middleware-runner.js';
55
51
  export { addGlobalPermission, checkAuthPermissions } from './permissions.js';
56
52
  export { hasScopes, verifyScopes } from './scopes.js';
57
53
  export { isSerializable, stopSingletonServices, pikkuServerLifecycle, } from './utils.js';
58
- export { getSingletonServices, getCreateWireServices, setSingletonServices, } from './pikku-state.js';
59
54
  export { clearPikkuRuntimeState } from './test-utils.js';
60
55
  export { type ScheduledTaskInfo, type ScheduledTaskSummary, } from './services/scheduler-service.js';
61
56
  export { SchedulerService } from './services/scheduler-service.js';
62
- export type { Private, Pii, Secret, Classification, AnonymizeStrategy, ColumnClassification, ClassificationManifest, ColumnForm, WrappedValue, SealedValue, HashedValue, } from './data-classification.js';
63
- export { hashToken, unsafeAsWrapped, unsafeAsSealed, unsafeAsHashed, } from './column-form.js';
57
+ export type { Private, Pii, Secret, Classification, AnonymizeStrategy, ClassificationManifest, ColumnForm, WrappedValue, SealedValue, HashedValue, } from './data-classification.js';
58
+ export { hashToken, } from './column-form.js';
64
59
  export type { SecretValue, Safe } from './secret-value.js';
65
60
  export { createSecretValue, isSecretValue, SecretCoercionError, REDACTED, } from './secret-value.js';
package/dist/index.js CHANGED
@@ -1,30 +1,25 @@
1
1
  export { pikkuAIMiddleware, pikkuChannelMiddleware, pikkuChannelMiddlewareFactory, pikkuMiddleware, pikkuMiddlewareFactory, } from './types/core.types.js';
2
2
  export { pikkuAuth, pikkuPermission, pikkuPermissionFactory, pikkuApprovalDescription, } from './function/functions.types.js';
3
- export { addFunction, getAllFunctionNames } from './function/index.js';
3
+ export { getAllFunctionNames } from './function/index.js';
4
+ export { pikkuCLIRender } from './wirings/cli/cli-runner.js';
4
5
  export { PikkuRequest } from './pikku-request.js';
5
6
  export { getRelativeTimeOffsetFromNow, parseDurationString, } from './time-utils.js';
6
7
  export { formatVersionedId, isVersionedId, parseVersionedId, } from './version.js';
7
- export { runPikkuFunc } from './function/function-runner.js';
8
- export { AbandonedError, beginChanges, getAbortScope, runInAbortScope, } from './function/abort-scope.js';
9
- export { runCLICommand, pikkuCLIRender } from './wirings/cli/cli-runner.js';
8
+ export { AbandonedError, } from './function/abort-scope.js';
10
9
  export { fetch } from './wirings/http/http-runner.js';
11
- export { runMCPTool, runMCPResource, runMCPPrompt, } from './wirings/mcp/mcp-runner.js';
12
- export { runQueueJob } from './wirings/queue/queue-runner.js';
13
- export { runScheduledTask } from './wirings/scheduler/scheduler-runner.js';
14
10
  export { AIProviderAuthError, AIProviderNotConfiguredError, BadGatewayError, BadRequestError, ConflictError, ExpectationFailedError, ForbiddenError, GatewayTimeoutError, GoneError, HTTPVersionNotSupportedError, InternalServerError, InvalidMiddlewareWireError, InvalidOriginError, InvalidSessionError, LengthRequiredError, LocalEnvironmentOnlyError, LockedError, MaxComputeTimeReachedError, MethodNotAllowedError, MissingCredentialError, MissingSchemaError, MissingScopeError, MissingServiceError, MissingSessionError, NotAcceptableError, NotFoundError, NotImplementedError, PayloadTooLargeError, PaymentRequiredError, PikkuMissingMetaError, PreconditionFailedError, ProxyAuthenticationRequiredError, RangeNotSatisfiableError, ReadonlySessionError, RequestTimeoutError, ServiceUnavailableError, TooManyRequestsError, URITooLongError, UnauthorizedError, UnprocessableContentError, UnsupportedMediaTypeError, } from './errors/errors.js';
15
11
  export { PikkuError, isExpectedError } from './errors/error-handler.js';
16
12
  export { SecretAccessDeniedError, withoutSecrets, } from './services/secretless.js';
17
13
  export { SecretHostNotAllowedError, assertSecretAllowedForHost, } from './services/secret-host-binding.js';
18
- export { NoopAuditService, createInvocationAudit, resolveAuditConfig, resolveAuditUserIdentityFromWire, } from './services/audit-service.js';
14
+ export { NoopAuditService, createInvocationAudit, } from './services/audit-service.js';
19
15
  export { createGraph } from './wirings/workflow/graph/graph-node.js';
20
16
  export { wireAddon } from './wirings/rpc/wire-addon.js';
21
17
  export { wireRemoteAddon } from './wirings/rpc/wire-remote-addon.js';
22
- export { runMiddleware, addTagMiddleware, addTagMiddleware as addMiddleware, addGlobalMiddleware, } from './middleware-runner.js';
18
+ export { runMiddleware, addTagMiddleware } from './middleware-runner.js';
23
19
  export { addGlobalPermission, checkAuthPermissions } from './permissions.js';
24
20
  export { hasScopes, verifyScopes } from './scopes.js';
25
21
  export { isSerializable, stopSingletonServices, pikkuServerLifecycle, } from './utils.js';
26
- export { getSingletonServices, getCreateWireServices, setSingletonServices, } from './pikku-state.js';
27
22
  export { clearPikkuRuntimeState } from './test-utils.js';
28
23
  export { SchedulerService } from './services/scheduler-service.js';
29
- export { hashToken, unsafeAsWrapped, unsafeAsSealed, unsafeAsHashed, } from './column-form.js';
24
+ export { hashToken, } from './column-form.js';
30
25
  export { createSecretValue, isSecretValue, SecretCoercionError, REDACTED, } from './secret-value.js';
@@ -1,9 +1,5 @@
1
1
  import type { SerializeOptions } from 'cookie';
2
2
  import type { RelativeTimeInput } from '../time-utils.js';
3
- /**
4
- * Reads a JWT session from a cookie, and re-issues the cookie after the
5
- * request whenever the session changed (e.g. after login).
6
- */
7
3
  export declare const authCookie: import("../types/core.types.js").CorePikkuMiddlewareFactory<{
8
4
  name: string;
9
5
  options: SerializeOptions;
@@ -4,6 +4,26 @@ import { getRelativeTimeOffsetFromNow } from '../time-utils.js';
4
4
  * Reads a JWT session from a cookie, and re-issues the cookie after the
5
5
  * request whenever the session changed (e.g. after login).
6
6
  */
7
+ /** Standard JWT registered claims — present on a token even with no session. */
8
+ const JWT_REGISTERED_CLAIMS = new Set([
9
+ 'iat',
10
+ 'exp',
11
+ 'nbf',
12
+ 'iss',
13
+ 'aud',
14
+ 'sub',
15
+ 'jti',
16
+ ]);
17
+ /**
18
+ * Whether a decoded payload carries an actual session, as opposed to being
19
+ * absent or a bare JWT envelope of `{ iat, exp }`. True only for a non-null
20
+ * object with at least one key that is not a registered JWT claim.
21
+ */
22
+ const hasSessionIdentity = (session) => {
23
+ if (!session || typeof session !== 'object')
24
+ return false;
25
+ return Object.keys(session).some((key) => !JWT_REGISTERED_CLAIMS.has(key));
26
+ };
7
27
  export const authCookie = pikkuMiddlewareFactory(({ name, options, expiresIn }) => {
8
28
  const mergedOptions = {
9
29
  httpOnly: true,
@@ -19,7 +39,12 @@ export const authCookie = pikkuMiddlewareFactory(({ name, options, expiresIn })
19
39
  const cookieValue = http.request.cookie(name);
20
40
  if (cookieValue && jwtService) {
21
41
  const userSession = await jwtService.decode(cookieValue);
22
- if (userSession) {
42
+ // Not just truthy: a JWT of an absent session still decodes to a
43
+ // `{ iat, exp }` object, which is truthy and which the function runner
44
+ // would accept as a session. Require at least one claim that is not a
45
+ // standard JWT timestamp, so an identity-less token is treated as no
46
+ // session rather than as an authenticated one.
47
+ if (userSession && hasSessionIdentity(userSession)) {
23
48
  setSession?.(userSession);
24
49
  }
25
50
  }
@@ -29,7 +54,18 @@ export const authCookie = pikkuMiddlewareFactory(({ name, options, expiresIn })
29
54
  }
30
55
  if (hasSessionChanged?.()) {
31
56
  const currentSession = await getSession?.();
32
- if (jwtService) {
57
+ // Logout path: `clearSession()` marks the session changed while leaving
58
+ // it absent. Re-signing that into a fresh, unexpired cookie would hand
59
+ // the browser a credential on the way out — so clear the cookie instead
60
+ // of minting one, and never call `encode` with an absent session.
61
+ if (!hasSessionIdentity(currentSession)) {
62
+ http.response.cookie(name, '', {
63
+ ...mergedOptions,
64
+ expires: new Date(0),
65
+ maxAge: 0,
66
+ });
67
+ }
68
+ else if (jwtService) {
33
69
  http.response.cookie(name, await jwtService.encode(expiresIn, currentSession), {
34
70
  ...mergedOptions,
35
71
  expires: getRelativeTimeOffsetFromNow(expiresIn),
@@ -45,6 +45,7 @@ export const cors = pikkuMiddlewareFactory(({ origin = '*', methods = ['GET', 'P
45
45
  }
46
46
  if (request.method() === 'options') {
47
47
  response.header('Access-Control-Max-Age', String(maxAge));
48
+ // 204 carries no body, and `json` has no no-content overload.
48
49
  response.status(204).json(undefined);
49
50
  return;
50
51
  }
@@ -5,4 +5,4 @@ export { pikkuRemoteAuthMiddleware } from './remote-auth.js';
5
5
  export { cors } from './cors.js';
6
6
  export { telemetryOuter, telemetryInner } from './telemetry.js';
7
7
  export { addTagMiddleware, addTagMiddleware as addMiddleware, addGlobalMiddleware, runMiddleware, } from '../middleware-runner.js';
8
- export { addGlobalPermission, addTagPermission } from '../permissions.js';
8
+ export { addGlobalPermission } from '../permissions.js';
@@ -5,4 +5,4 @@ export { pikkuRemoteAuthMiddleware } from './remote-auth.js';
5
5
  export { cors } from './cors.js';
6
6
  export { telemetryOuter, telemetryInner } from './telemetry.js';
7
7
  export { addTagMiddleware, addTagMiddleware as addMiddleware, addGlobalMiddleware, runMiddleware, } from '../middleware-runner.js';
8
- export { addGlobalPermission, addTagPermission } from '../permissions.js';
8
+ export { addGlobalPermission } from '../permissions.js';
@@ -1,6 +1,15 @@
1
1
  import { UnauthorizedError } from '../errors/errors.js';
2
2
  import { pikkuMiddleware } from '../types/core.types.js';
3
3
  import { assertStrongKeyMaterial, decryptWithKeyMaterial, REMOTE_SESSION_INFO, } from '../crypto-utils.js';
4
+ const REMOTE_RPC_PREFIX = '/remote/rpc/';
5
+ /**
6
+ * Whether this request targets the remote-RPC surface. Compared case-insensitively
7
+ * because the router matches routes that way (path-to-regexp defaults to
8
+ * `sensitive: false`), so `/Remote/RPC/fn` reaches the same handler as
9
+ * `/remote/rpc/fn`. A case-sensitive check here let a case-varied path slip
10
+ * past the trust gate and the token's `fn` binding while still being dispatched.
11
+ */
12
+ const isRemoteRpcPath = (path) => path.toLowerCase().startsWith(REMOTE_RPC_PREFIX);
4
13
  export const pikkuRemoteAuthMiddleware = pikkuMiddleware(async ({ secrets, jwt }, { http, setSession }, next) => {
5
14
  if (!http?.request || !secrets) {
6
15
  return next();
@@ -10,7 +19,7 @@ export const pikkuRemoteAuthMiddleware = pikkuMiddleware(async ({ secrets, jwt }
10
19
  secret = (await secrets.getSecret('PIKKU_REMOTE_SECRET')).reveal();
11
20
  }
12
21
  catch {
13
- if (http.request.path().startsWith('/remote/rpc/')) {
22
+ if (isRemoteRpcPath(http.request.path())) {
14
23
  throw new UnauthorizedError();
15
24
  }
16
25
  return next();
@@ -38,8 +47,10 @@ export const pikkuRemoteAuthMiddleware = pikkuMiddleware(async ({ secrets, jwt }
38
47
  if (payload?.aud !== 'pikku-remote') {
39
48
  throw new UnauthorizedError();
40
49
  }
41
- if (payload?.fn && http.request.path().startsWith('/remote/rpc/')) {
42
- const fn = decodeURIComponent(http.request.path().slice('/remote/rpc/'.length));
50
+ if (payload?.fn && isRemoteRpcPath(http.request.path())) {
51
+ // The prefix length is the same in any case, so slicing the raw path
52
+ // keeps the requested function name in its original case for the compare.
53
+ const fn = decodeURIComponent(http.request.path().slice(REMOTE_RPC_PREFIX.length));
43
54
  if (fn && payload.fn !== fn) {
44
55
  throw new UnauthorizedError();
45
56
  }
@@ -1,20 +1,18 @@
1
1
  import type { CoreServices, CoreUserSession, PikkuWire } from './types/core.types.js';
2
+ import type { PikkuRPC } from './wirings/rpc/rpc-types.js';
3
+ /**
4
+ * The wire a permission function sees. `Out = never` denies it `channel.send`.
5
+ *
6
+ * knowledge: decisions/security/a-permission-gets-a-wire-it-cannot-reply-on.md
7
+ */
8
+ export type PermissionWire = PikkuWire<any, never, false, any, PikkuRPC, never, never>;
2
9
  import type { CorePermissionGroup, CorePikkuPermission } from './function/functions.types.js';
3
10
  export declare const clearPermissionsCache: () => void;
4
11
  export declare const addGlobalPermission: (permissions: CorePermissionGroup | CorePikkuPermission[], packageName?: string | null) => CorePermissionGroup | CorePikkuPermission[];
5
- /**
6
- * @deprecated Tag-level permissions were removed in #972 — permissions are now
7
- * function-scoped only (declare them on the function via `pikkuFunc({ permissions })`).
8
- * This throwing stub exists solely so the pinned bootstrap CLI (which still
9
- * generates an `addTagPermission` wrapper) can resolve the import at build time;
10
- * it is never called. Delete once `PIKKU_CLI_VERSION` in the CLI build is bumped
11
- * past the release that removes tag permissions.
12
- */
13
- export declare const addTagPermission: (_tag: string, _permissions: CorePermissionGroup | CorePikkuPermission[], _packageName?: string | null) => never;
14
12
  export declare const runPermissions: ({ funcPermissions, services, wire, data, packageName, label, }: {
15
13
  funcPermissions?: CorePermissionGroup | CorePikkuPermission[];
16
14
  services: CoreServices;
17
- wire: PikkuWire<any, never, any, CoreUserSession, never, never, never>;
15
+ wire: PermissionWire;
18
16
  data: any;
19
17
  packageName?: string | null;
20
18
  /** What the non-global gate is called in debug logs, e.g. 'function', 'agent'. */
@@ -40,17 +40,6 @@ export const addGlobalPermission = (permissions, packageName = null) => {
40
40
  clearPermissionsCache();
41
41
  return permissions;
42
42
  };
43
- /**
44
- * @deprecated Tag-level permissions were removed in #972 — permissions are now
45
- * function-scoped only (declare them on the function via `pikkuFunc({ permissions })`).
46
- * This throwing stub exists solely so the pinned bootstrap CLI (which still
47
- * generates an `addTagPermission` wrapper) can resolve the import at build time;
48
- * it is never called. Delete once `PIKKU_CLI_VERSION` in the CLI build is bumped
49
- * past the release that removes tag permissions.
50
- */
51
- export const addTagPermission = (_tag, _permissions, _packageName = null) => {
52
- throw new Error('addTagPermission was removed in #972 — tag-level permissions no longer exist. Declare permissions on the function definition instead: pikkuFunc({ permissions }).');
53
- };
54
43
  const bucket = (packageName) => pikkuState(packageName, 'permissions', 'global') ?? [];
55
44
  /**
56
45
  * Global permissions in effect for a function, root ones first.
@@ -1,10 +1,17 @@
1
1
  const PIKKU_STATE_KEY = Symbol.for('@pikku/core/state');
2
+ /**
3
+ * State is parked on `globalThis` under a registered symbol so separate copies
4
+ * of @pikku/core in one process share it. Typed once here rather than at each
5
+ * access.
6
+ */
7
+ const stateHost = globalThis;
2
8
  export const getAllPackageStates = () => {
3
- if (!globalThis[PIKKU_STATE_KEY]) {
4
- ;
5
- globalThis[PIKKU_STATE_KEY] = new Map();
9
+ let states = stateHost[PIKKU_STATE_KEY];
10
+ if (!states) {
11
+ states = new Map();
12
+ stateHost[PIKKU_STATE_KEY] = states;
6
13
  }
7
- return globalThis[PIKKU_STATE_KEY];
14
+ return states;
8
15
  };
9
16
  export const pikkuState = (packageName, type, content, value) => {
10
17
  const resolvedPackageName = packageName ?? '__main__';
@@ -77,6 +84,9 @@ const createEmptyPackageState = () => ({
77
84
  agent: {
78
85
  agents: new Map(),
79
86
  agentsMeta: {},
87
+ scorers: new Map(),
88
+ scorersMeta: {},
89
+ modelAliases: {},
80
90
  },
81
91
  gateway: {
82
92
  gateways: new Map(),
@@ -110,6 +120,7 @@ const createEmptyPackageState = () => ({
110
120
  authFactory: null,
111
121
  credentialsMeta: null,
112
122
  requiredParentServices: null,
123
+ declaredSecrets: null,
113
124
  },
114
125
  });
115
126
  export const initializePikkuState = (packageName) => {
@@ -120,7 +131,7 @@ export const initializePikkuState = (packageName) => {
120
131
  export const resetPikkuState = () => {
121
132
  // Error definitions come from module-import side effects that never re-run.
122
133
  const existingErrors = getAllPackageStates().get('__main__')?.misc.errors;
123
- globalThis[PIKKU_STATE_KEY] = new Map();
134
+ stateHost[PIKKU_STATE_KEY] = new Map();
124
135
  initializePikkuState('__main__');
125
136
  if (existingErrors) {
126
137
  const mainState = getAllPackageStates().get('__main__');
package/dist/schema.js CHANGED
@@ -98,6 +98,40 @@ export const coerceTopLevelDataFromSchema = (schemaName, data, packageName = nul
98
98
  }
99
99
  }
100
100
  };
101
+ /**
102
+ * Drops object properties whose value is literally `undefined`.
103
+ *
104
+ * JSON Schema has no way to describe such a property, and the validator refuses
105
+ * the whole instance rather than reporting it — `{ a: undefined }` throws
106
+ * "Instances of \"undefined\" type are not supported" instead of validating.
107
+ *
108
+ * That matters because whether a payload can contain one depends on how the
109
+ * call travelled. Over HTTP `JSON.stringify` drops these keys before the
110
+ * request is built, so they never arrive. Dispatched in-process — an inline
111
+ * workflow step calling an RPC — the object is handed over as-is, and
112
+ * `{ retries: data.maybeRetries }` with the field omitted by the caller is
113
+ * enough to kill the step. Normalising here makes the two paths agree, and an
114
+ * explicitly-undefined *required* field now reports as the missing property it
115
+ * is rather than as an internal error.
116
+ *
117
+ * Deliberately not a JSON round-trip: `coerceTopLevelDataFromSchema` puts real
118
+ * `Date` instances on the data first, and stringifying would flatten them back
119
+ * to strings the validator has never been given.
120
+ */
121
+ const stripUndefinedValues = (value) => {
122
+ if (Array.isArray(value))
123
+ return value.map(stripUndefinedValues);
124
+ if (value === null || typeof value !== 'object')
125
+ return value;
126
+ // Only plain objects: a Date, Map or class instance is data, not a bag of
127
+ // properties to be rewritten.
128
+ const prototype = Object.getPrototypeOf(value);
129
+ if (prototype !== Object.prototype && prototype !== null)
130
+ return value;
131
+ return Object.fromEntries(Object.entries(value)
132
+ .filter(([, entry]) => entry !== undefined)
133
+ .map(([key, entry]) => [key, stripUndefinedValues(entry)]));
134
+ };
101
135
  export const validateSchema = async (logger, schemaService, schemaName, data, packageName = null) => {
102
136
  if (schemaService) {
103
137
  if (!schemaName) {
@@ -118,6 +152,6 @@ export const validateSchema = async (logger, schemaService, schemaName, data, pa
118
152
  throw new MissingSchemaError(`Schema '${schemaName}' not found. Ensure schema generation has been run.`);
119
153
  }
120
154
  await schemaService.compileSchema(key, schema);
121
- await schemaService.validateSchema(key, data ?? {});
155
+ await schemaService.validateSchema(key, stripUndefinedValues(data ?? {}));
122
156
  }
123
157
  };
@@ -54,6 +54,13 @@ export type AIAgentStepResult = {
54
54
  toolCallId: string;
55
55
  toolName: string;
56
56
  result: unknown;
57
+ /**
58
+ * Set when the tool threw rather than returned. Carried as its own field
59
+ * because `result` is a rendered string by the time anything downstream
60
+ * reads it, and "did this tool fail" is not answerable by looking for an
61
+ * `Error:` prefix in text a tool could legitimately have returned.
62
+ */
63
+ error?: string;
57
64
  }[];
58
65
  usage: {
59
66
  inputTokens: number;
@@ -1,13 +1,29 @@
1
1
  import type { AgentRunState, PendingApproval } from '../wirings/ai-agent/ai-agent.types.js';
2
+ import type { AIRunScore } from '../wirings/ai-scorer/ai-scorer.types.js';
2
3
  export type CreateRunInput = Omit<AgentRunState, 'runId'>;
4
+ export type SaveScoreInput = Omit<AIRunScore, 'createdAt'>;
3
5
  export interface AIRunStateService {
4
6
  createRun(run: CreateRunInput): Promise<string>;
5
7
  updateRun(runId: string, updates: Partial<AgentRunState>): Promise<void>;
6
8
  getRun(runId: string): Promise<AgentRunState | null>;
7
9
  getRunsByThread(threadId: string): Promise<AgentRunState[]>;
8
- resolveApproval(toolCallId: string, status: 'approved' | 'denied'): Promise<void>;
10
+ /**
11
+ * Claims an approval: removes it from the run's pending list and records the
12
+ * decision, as one atomic step. Returns whether THIS caller made the claim —
13
+ * concurrent approvals of the same tool call produce exactly one `true`, and
14
+ * only that caller may run the tool.
15
+ */
16
+ resolveApproval(toolCallId: string, status: 'approved' | 'denied'): Promise<boolean>;
9
17
  findRunByToolCallId(toolCallId: string): Promise<{
10
18
  run: AgentRunState;
11
19
  approval: PendingApproval;
12
20
  } | null>;
21
+ /**
22
+ * Record one scorer's grade of a finished run. A run accumulates one row per
23
+ * scorer, and a scorer may grade the same run more than once — a retried job
24
+ * appends rather than replaces, so a re-grade never silently overwrites the
25
+ * grade that was acted on.
26
+ */
27
+ saveScore(score: SaveScoreInput): Promise<void>;
28
+ getScores(runId: string): Promise<AIRunScore[]>;
13
29
  }
@@ -1,15 +1,19 @@
1
- import type { AIRunStateService, CreateRunInput } from './ai-run-state-service.js';
1
+ import type { AIRunStateService, CreateRunInput, SaveScoreInput } from './ai-run-state-service.js';
2
2
  import type { AgentRunState, PendingApproval } from '../wirings/ai-agent/ai-agent.types.js';
3
+ import type { AIRunScore } from '../wirings/ai-scorer/ai-scorer.types.js';
3
4
  export declare class InMemoryAIRunStateService implements AIRunStateService {
4
5
  private runs;
6
+ private scores;
5
7
  private counter;
6
8
  createRun(run: CreateRunInput): Promise<string>;
7
9
  updateRun(runId: string, updates: Partial<AgentRunState>): Promise<void>;
8
10
  getRun(runId: string): Promise<AgentRunState | null>;
9
11
  getRunsByThread(threadId: string): Promise<AgentRunState[]>;
10
- resolveApproval(toolCallId: string, status: 'approved' | 'denied'): Promise<void>;
12
+ resolveApproval(toolCallId: string, status: 'approved' | 'denied'): Promise<boolean>;
11
13
  findRunByToolCallId(toolCallId: string): Promise<{
12
14
  run: AgentRunState;
13
15
  approval: PendingApproval;
14
16
  } | null>;
17
+ saveScore(score: SaveScoreInput): Promise<void>;
18
+ getScores(runId: string): Promise<AIRunScore[]>;
15
19
  }