@pikku/core 0.12.106 → 0.12.111

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 (589) hide show
  1. package/CHANGELOG.md +358 -0
  2. package/dist/analytics/analytics.d.ts +6 -0
  3. package/dist/analytics/analytics.js +58 -0
  4. package/dist/analytics/analytics.types.d.ts +156 -0
  5. package/dist/analytics/analytics.types.js +1 -0
  6. package/dist/analytics/anonymous-analytics-identity.d.ts +23 -0
  7. package/dist/analytics/anonymous-analytics-identity.js +27 -0
  8. package/dist/analytics/compose-analytics-identity.d.ts +14 -0
  9. package/dist/analytics/compose-analytics-identity.js +33 -0
  10. package/dist/analytics/cookie-analytics-identity.d.ts +24 -0
  11. package/dist/analytics/cookie-analytics-identity.js +37 -0
  12. package/dist/analytics/define-analytics-events.d.ts +22 -0
  13. package/dist/analytics/define-analytics-events.js +9 -0
  14. package/dist/analytics/fan-out-analytics.d.ts +15 -0
  15. package/dist/analytics/fan-out-analytics.js +36 -0
  16. package/dist/analytics/index.d.ts +13 -0
  17. package/dist/analytics/index.js +8 -0
  18. package/dist/analytics/logger-analytics-service.d.ts +14 -0
  19. package/dist/analytics/logger-analytics-service.js +23 -0
  20. package/dist/analytics/mint-cookie.d.ts +44 -0
  21. package/dist/analytics/mint-cookie.js +55 -0
  22. package/dist/errors/errors.d.ts +7 -0
  23. package/dist/errors/errors.js +17 -0
  24. package/dist/function/function-meta.types.d.ts +2 -0
  25. package/dist/function/function-runner.js +29 -0
  26. package/dist/function/functions.types.d.ts +22 -3
  27. package/dist/middleware/auth-apikey.d.ts +1 -1
  28. package/dist/pikku-state.d.ts +1 -1
  29. package/dist/scopes.d.ts +11 -0
  30. package/dist/scopes.js +17 -0
  31. package/dist/services/credential-wire-service.d.ts +1 -1
  32. package/dist/services/feature-flag-service.d.ts +100 -0
  33. package/dist/services/feature-flag-service.js +1 -0
  34. package/dist/services/index.d.ts +1 -0
  35. package/dist/services/meta-service.d.ts +16 -0
  36. package/dist/services/meta-service.js +19 -0
  37. package/dist/services/webhook-service.d.ts +7 -2
  38. package/dist/services/webhook-service.js +11 -6
  39. package/dist/testing/service-tests/agent-run-service-tests.d.ts +2 -2
  40. package/dist/testing/service-tests/agent-storage-service-tests.d.ts +1 -1
  41. package/dist/testing/service-tests/channel-store-tests.d.ts +1 -1
  42. package/dist/testing/service-tests/credential-service-tests.d.ts +1 -1
  43. package/dist/testing/service-tests/deployment-service-tests.d.ts +1 -1
  44. package/dist/testing/service-tests/event-hub-store-tests.d.ts +1 -1
  45. package/dist/testing/service-tests/secret-service-tests.d.ts +1 -1
  46. package/dist/testing/service-tests/session-store-tests.d.ts +1 -1
  47. package/dist/testing/service-tests/workflow-run-service-tests.d.ts +1 -1
  48. package/dist/testing/service-tests/workflow-service-tests.d.ts +1 -1
  49. package/dist/types/core.types.d.ts +23 -0
  50. package/dist/wirings/agent/agent-rpc.d.ts +1 -1
  51. package/dist/wirings/agent/agent-turn.d.ts +1 -1
  52. package/dist/wirings/agent-scorer/agent-scorer-live.d.ts +1 -1
  53. package/dist/wirings/channel/channel-common.d.ts +1 -1
  54. package/dist/wirings/channel/channel-rpc-validators.d.ts +2 -2
  55. package/dist/wirings/channel/channel-runner.d.ts +1 -1
  56. package/dist/wirings/channel/local/local-channel-runner.d.ts +1 -1
  57. package/dist/wirings/channel/serverless/serverless-channel-runner.d.ts +1 -1
  58. package/dist/wirings/cli/channel/cli-approval.d.ts +2 -2
  59. package/dist/wirings/flag/assert-feature-available.d.ts +15 -0
  60. package/dist/wirings/flag/assert-feature-available.js +23 -0
  61. package/dist/wirings/flag/cached-flag-source.d.ts +73 -0
  62. package/dist/wirings/flag/cached-flag-source.js +96 -0
  63. package/dist/wirings/flag/define-feature-flags.d.ts +33 -0
  64. package/dist/wirings/flag/define-feature-flags.js +32 -0
  65. package/dist/wirings/flag/flag.types.d.ts +97 -0
  66. package/dist/wirings/flag/flag.types.js +1 -0
  67. package/dist/wirings/flag/index.d.ts +7 -0
  68. package/dist/wirings/flag/index.js +5 -0
  69. package/dist/wirings/flag/resolve-flag.d.ts +52 -0
  70. package/dist/wirings/flag/resolve-flag.js +90 -0
  71. package/dist/wirings/flag/validate-flag-definitions.d.ts +26 -0
  72. package/dist/wirings/flag/validate-flag-definitions.js +103 -0
  73. package/dist/wirings/rpc/rpc-runner.js +3 -0
  74. package/dist/wirings/virtual-user/virtual-user-scaffold.d.ts +8 -8
  75. package/dist/wirings/virtual-user/virtual-user-schedule.d.ts +1 -1
  76. package/dist/wirings/workflow/workflow-queue-routing.d.ts +1 -1
  77. package/package.json +11 -5
  78. package/run-tests.sh +17 -9
  79. package/src/public-surface.json +26 -0
  80. package/src/agent-naming.test.ts +0 -68
  81. package/src/api-report.test.ts +0 -138
  82. package/src/app-alias-surface.test.ts +0 -179
  83. package/src/app-leaf-surface.test.ts +0 -222
  84. package/src/bootstrap-compat/root.ts +0 -20
  85. package/src/classification/column-form.test.ts +0 -97
  86. package/src/classification/column-form.ts +0 -55
  87. package/src/classification/data-classification.ts +0 -73
  88. package/src/classification/index.ts +0 -40
  89. package/src/classification/key-ids.ts +0 -2
  90. package/src/classification/secret-value.test.ts +0 -204
  91. package/src/classification/secret-value.ts +0 -106
  92. package/src/crypto-utils.test.ts +0 -668
  93. package/src/crypto-utils.ts +0 -460
  94. package/src/dev/hot-reload.test.ts +0 -587
  95. package/src/dev/hot-reload.ts +0 -225
  96. package/src/dev/module-runner.test.ts +0 -235
  97. package/src/dev/module-runner.ts +0 -138
  98. package/src/dev/reload-meta.test.ts +0 -183
  99. package/src/dev/reload-meta.ts +0 -144
  100. package/src/ecosystem-tier-removed.test.ts +0 -72
  101. package/src/env.ts +0 -1
  102. package/src/errors/error-handler.ts +0 -77
  103. package/src/errors/error.test.ts +0 -229
  104. package/src/errors/errors.ts +0 -393
  105. package/src/errors/index.ts +0 -11
  106. package/src/errors/serialized-error.ts +0 -12
  107. package/src/factory-functions.test.ts +0 -111
  108. package/src/function/abort-scope.test.ts +0 -97
  109. package/src/function/abort-scope.ts +0 -80
  110. package/src/function/function-meta.types.ts +0 -151
  111. package/src/function/function-runner.test.ts +0 -1619
  112. package/src/function/function-runner.ts +0 -499
  113. package/src/function/functions.types.ts +0 -319
  114. package/src/function/index.ts +0 -40
  115. package/src/function/list.types.test.ts +0 -100
  116. package/src/function/list.types.ts +0 -69
  117. package/src/function/pikku-request.test.ts +0 -35
  118. package/src/function/pikku-request.ts +0 -17
  119. package/src/gopass-secrets-removed.test.ts +0 -51
  120. package/src/handle-error.test.ts +0 -532
  121. package/src/handle-error.ts +0 -64
  122. package/src/middleware/auth-apikey.test.ts +0 -362
  123. package/src/middleware/auth-apikey.ts +0 -39
  124. package/src/middleware/auth-bearer.test.ts +0 -566
  125. package/src/middleware/auth-bearer.ts +0 -83
  126. package/src/middleware/auth-cookie.test.ts +0 -572
  127. package/src/middleware/auth-cookie.ts +0 -107
  128. package/src/middleware/cors.test.ts +0 -579
  129. package/src/middleware/cors.ts +0 -103
  130. package/src/middleware/index.ts +0 -30
  131. package/src/middleware/middleware-factories.ts +0 -76
  132. package/src/middleware/middleware.types.ts +0 -61
  133. package/src/middleware/remote-auth.test.ts +0 -547
  134. package/src/middleware/remote-auth.ts +0 -95
  135. package/src/middleware/remote-jobs-secret.ts +0 -35
  136. package/src/middleware/require-origin.test.ts +0 -115
  137. package/src/middleware/require-origin.ts +0 -79
  138. package/src/middleware/telemetry.ts +0 -83
  139. package/src/middleware-runner.test.ts +0 -578
  140. package/src/middleware-runner.ts +0 -232
  141. package/src/no-any-casts.test.ts +0 -57
  142. package/src/no-root-barrel.test.ts +0 -122
  143. package/src/permissions.test.ts +0 -256
  144. package/src/permissions.ts +0 -217
  145. package/src/pikku-state.test.ts +0 -198
  146. package/src/pikku-state.ts +0 -206
  147. package/src/production-barrels-stay-lean.test.ts +0 -110
  148. package/src/public-surface.test.ts +0 -133
  149. package/src/remote.test.ts +0 -173
  150. package/src/remote.ts +0 -56
  151. package/src/removed-legacy-exports.test.ts +0 -66
  152. package/src/run-tests-script.test.ts +0 -67
  153. package/src/schema.test.ts +0 -430
  154. package/src/schema.ts +0 -204
  155. package/src/scopes.test.ts +0 -203
  156. package/src/scopes.ts +0 -67
  157. package/src/services/agent-run-state-service.ts +0 -37
  158. package/src/services/agent-runner-service.ts +0 -238
  159. package/src/services/agent-storage-service.ts +0 -39
  160. package/src/services/ai-embedding-service.ts +0 -9
  161. package/src/services/audit-service.test.ts +0 -44
  162. package/src/services/audit-service.ts +0 -280
  163. package/src/services/content-service.ts +0 -65
  164. package/src/services/credential-service.ts +0 -20
  165. package/src/services/credential-wire-service.test.ts +0 -235
  166. package/src/services/credential-wire-service.ts +0 -120
  167. package/src/services/deployment-service.ts +0 -32
  168. package/src/services/email-service.test.ts +0 -100
  169. package/src/services/email-service.ts +0 -60
  170. package/src/services/email-template.test.ts +0 -311
  171. package/src/services/email-template.ts +0 -254
  172. package/src/services/file-scenario-run-store.test.ts +0 -349
  173. package/src/services/file-scenario-run-store.ts +0 -282
  174. package/src/services/gateway-service.ts +0 -5
  175. package/src/services/http-personas-converse.test.ts +0 -274
  176. package/src/services/http-personas.test.ts +0 -379
  177. package/src/services/http-personas.ts +0 -508
  178. package/src/services/in-memory-agent-run-state-service.ts +0 -87
  179. package/src/services/in-memory-queue-service.test.ts +0 -162
  180. package/src/services/in-memory-queue-service.ts +0 -78
  181. package/src/services/in-memory-session-store.test.ts +0 -58
  182. package/src/services/in-memory-session-store.ts +0 -20
  183. package/src/services/in-memory-trigger-service.ts +0 -47
  184. package/src/services/in-memory-workflow-service.test.ts +0 -430
  185. package/src/services/in-memory-workflow-service.ts +0 -595
  186. package/src/services/index.ts +0 -192
  187. package/src/services/istanbul-coverage-service.test.ts +0 -66
  188. package/src/services/istanbul-coverage-service.ts +0 -59
  189. package/src/services/jwt-service.ts +0 -15
  190. package/src/services/local-content-request-handler.test.ts +0 -240
  191. package/src/services/local-content-request-handler.ts +0 -295
  192. package/src/services/local-content.test.ts +0 -186
  193. package/src/services/local-content.ts +0 -242
  194. package/src/services/local-credential-service.ts +0 -63
  195. package/src/services/local-email-service.test.ts +0 -182
  196. package/src/services/local-email-service.ts +0 -43
  197. package/src/services/local-gateway-service.ts +0 -51
  198. package/src/services/local-secrets.test.ts +0 -95
  199. package/src/services/local-secrets.ts +0 -71
  200. package/src/services/local-variables.test.ts +0 -61
  201. package/src/services/local-variables.ts +0 -45
  202. package/src/services/logger-console.test.ts +0 -117
  203. package/src/services/logger-console.ts +0 -174
  204. package/src/services/logger.ts +0 -48
  205. package/src/services/meta-service.test.ts +0 -75
  206. package/src/services/meta-service.ts +0 -767
  207. package/src/services/persona-actor-secret.test.ts +0 -68
  208. package/src/services/persona-actor-secret.ts +0 -70
  209. package/src/services/persona-sign-in.test.ts +0 -219
  210. package/src/services/persona-sign-in.ts +0 -238
  211. package/src/services/personas-service.ts +0 -191
  212. package/src/services/pikku-user-id.test.ts +0 -62
  213. package/src/services/pikku-user-id.ts +0 -13
  214. package/src/services/queue-webhook-service.test.ts +0 -409
  215. package/src/services/queue-webhook-service.ts +0 -150
  216. package/src/services/remote-jobs.test.ts +0 -106
  217. package/src/services/remote-jobs.ts +0 -92
  218. package/src/services/scheduler-service.ts +0 -37
  219. package/src/services/schema-service.ts +0 -10
  220. package/src/services/scope-service.ts +0 -91
  221. package/src/services/scoped-credential-service.test.ts +0 -86
  222. package/src/services/scoped-credential-service.ts +0 -63
  223. package/src/services/scoped-secret-service.test.ts +0 -93
  224. package/src/services/scoped-secret-service.ts +0 -40
  225. package/src/services/secret-host-binding.test.ts +0 -138
  226. package/src/services/secret-host-binding.ts +0 -51
  227. package/src/services/secret-service.ts +0 -25
  228. package/src/services/secretless.test.ts +0 -54
  229. package/src/services/secretless.ts +0 -29
  230. package/src/services/session-store.ts +0 -9
  231. package/src/services/stub-tracker.test.ts +0 -104
  232. package/src/services/stub-tracker.ts +0 -175
  233. package/src/services/system-role-guard.test.ts +0 -96
  234. package/src/services/system-role-guard.ts +0 -71
  235. package/src/services/temporary-file-service.ts +0 -76
  236. package/src/services/trigger-service.ts +0 -5
  237. package/src/services/typed-credential-service.ts +0 -83
  238. package/src/services/typed-secret-service.test.ts +0 -204
  239. package/src/services/typed-secret-service.ts +0 -132
  240. package/src/services/typed-variables-service.test.ts +0 -166
  241. package/src/services/typed-variables-service.ts +0 -166
  242. package/src/services/user-session-service.test.ts +0 -147
  243. package/src/services/user-session-service.ts +0 -85
  244. package/src/services/v8-coverage-service.test.ts +0 -69
  245. package/src/services/v8-coverage-service.ts +0 -163
  246. package/src/services/variables-service.ts +0 -13
  247. package/src/services/webhook-service.ts +0 -147
  248. package/src/services/workflow-service.ts +0 -120
  249. package/src/side-effects-are-declared.test.ts +0 -84
  250. package/src/source-files-stay-composable.test.ts +0 -41
  251. package/src/template-alias-surface.test.ts +0 -240
  252. package/src/test-utils.ts +0 -38
  253. package/src/testing/index.ts +0 -3
  254. package/src/testing/service-tests/agent-run-service-tests.ts +0 -98
  255. package/src/testing/service-tests/agent-storage-service-tests.ts +0 -379
  256. package/src/testing/service-tests/channel-store-tests.ts +0 -98
  257. package/src/testing/service-tests/credential-service-tests.ts +0 -143
  258. package/src/testing/service-tests/deployment-service-tests.ts +0 -33
  259. package/src/testing/service-tests/event-hub-store-tests.ts +0 -48
  260. package/src/testing/service-tests/secret-service-tests.ts +0 -105
  261. package/src/testing/service-tests/session-store-tests.ts +0 -62
  262. package/src/testing/service-tests/workflow-run-service-tests.ts +0 -59
  263. package/src/testing/service-tests/workflow-service-tests.ts +0 -308
  264. package/src/testing/service-tests.ts +0 -95
  265. package/src/time-utils.test.ts +0 -56
  266. package/src/time-utils.ts +0 -89
  267. package/src/types/core.types.ts +0 -446
  268. package/src/types/index.ts +0 -25
  269. package/src/types/state.types.ts +0 -226
  270. package/src/types/typed-credentials.test.ts +0 -72
  271. package/src/utils/hash.test.ts +0 -68
  272. package/src/utils/hash.ts +0 -26
  273. package/src/utils/hmac.ts +0 -21
  274. package/src/utils/node-host-resolver.ts +0 -20
  275. package/src/utils/safe-fetch.test.ts +0 -515
  276. package/src/utils/safe-fetch.ts +0 -347
  277. package/src/utils.test.ts +0 -359
  278. package/src/utils.ts +0 -165
  279. package/src/version.test.ts +0 -80
  280. package/src/version.ts +0 -25
  281. package/src/wirings/actor-flow/actor-flow.types.ts +0 -40
  282. package/src/wirings/actor-flow/index.ts +0 -10
  283. package/src/wirings/actor-flow/run-conversation.test.ts +0 -187
  284. package/src/wirings/actor-flow/run-conversation.ts +0 -280
  285. package/src/wirings/addon/addon-auth-tags.test.ts +0 -219
  286. package/src/wirings/addon/addon-runner.ts +0 -236
  287. package/src/wirings/addon/addon-scopes.test.ts +0 -225
  288. package/src/wirings/addon/addon-secrets.test.ts +0 -391
  289. package/src/wirings/addon/index.ts +0 -12
  290. package/src/wirings/addon/remote-addon-auth.ts +0 -65
  291. package/src/wirings/addon/wire-addon.test.ts +0 -102
  292. package/src/wirings/addon/wire-addon.ts +0 -202
  293. package/src/wirings/addon/wire-remote-addon.ts +0 -41
  294. package/src/wirings/agent/agent-agui.test.ts +0 -1213
  295. package/src/wirings/agent/agent-agui.ts +0 -405
  296. package/src/wirings/agent/agent-authorization.test.ts +0 -208
  297. package/src/wirings/agent/agent-finalize.test.ts +0 -187
  298. package/src/wirings/agent/agent-finalize.ts +0 -197
  299. package/src/wirings/agent/agent-helpers.test.ts +0 -215
  300. package/src/wirings/agent/agent-helpers.ts +0 -96
  301. package/src/wirings/agent/agent-interrupt.test.ts +0 -833
  302. package/src/wirings/agent/agent-interrupt.ts +0 -400
  303. package/src/wirings/agent/agent-memory.test.ts +0 -397
  304. package/src/wirings/agent/agent-memory.ts +0 -496
  305. package/src/wirings/agent/agent-middleware.types.test.ts +0 -41
  306. package/src/wirings/agent/agent-model-config.test.ts +0 -103
  307. package/src/wirings/agent/agent-model-config.ts +0 -59
  308. package/src/wirings/agent/agent-prepare.test.ts +0 -977
  309. package/src/wirings/agent/agent-prepare.ts +0 -1083
  310. package/src/wirings/agent/agent-registry.test.ts +0 -455
  311. package/src/wirings/agent/agent-registry.ts +0 -99
  312. package/src/wirings/agent/agent-resume-authorization.test.ts +0 -206
  313. package/src/wirings/agent/agent-rpc.ts +0 -116
  314. package/src/wirings/agent/agent-runner.test.ts +0 -1229
  315. package/src/wirings/agent/agent-runner.ts +0 -858
  316. package/src/wirings/agent/agent-stream-delegate.test.ts +0 -381
  317. package/src/wirings/agent/agent-stream-output-hooks.test.ts +0 -353
  318. package/src/wirings/agent/agent-stream.test.ts +0 -1800
  319. package/src/wirings/agent/agent-stream.ts +0 -1639
  320. package/src/wirings/agent/agent-thread-ownership.test.ts +0 -297
  321. package/src/wirings/agent/agent-turn.test.ts +0 -65
  322. package/src/wirings/agent/agent-turn.ts +0 -122
  323. package/src/wirings/agent/agent-utils.ts +0 -20
  324. package/src/wirings/agent/agent.types.ts +0 -676
  325. package/src/wirings/agent/index.ts +0 -58
  326. package/src/wirings/agent/voice-input.test.ts +0 -220
  327. package/src/wirings/agent/voice-input.ts +0 -180
  328. package/src/wirings/agent/voice-output.test.ts +0 -510
  329. package/src/wirings/agent/voice-output.ts +0 -311
  330. package/src/wirings/agent-scorer/agent-scorer-grade.test.ts +0 -106
  331. package/src/wirings/agent-scorer/agent-scorer-grade.ts +0 -55
  332. package/src/wirings/agent-scorer/agent-scorer-judge.test.ts +0 -285
  333. package/src/wirings/agent-scorer/agent-scorer-judge.ts +0 -180
  334. package/src/wirings/agent-scorer/agent-scorer-live.test.ts +0 -174
  335. package/src/wirings/agent-scorer/agent-scorer-live.ts +0 -56
  336. package/src/wirings/agent-scorer/agent-scorer-registry.ts +0 -66
  337. package/src/wirings/agent-scorer/agent-scorer-sampling.test.ts +0 -34
  338. package/src/wirings/agent-scorer/agent-scorer-sampling.ts +0 -36
  339. package/src/wirings/agent-scorer/agent-scorer-snapshots.test.ts +0 -49
  340. package/src/wirings/agent-scorer/agent-scorer-snapshots.ts +0 -46
  341. package/src/wirings/agent-scorer/agent-scorer-worker.test.ts +0 -122
  342. package/src/wirings/agent-scorer/agent-scorer-worker.ts +0 -71
  343. package/src/wirings/agent-scorer/agent-scorer.ts +0 -102
  344. package/src/wirings/agent-scorer/agent-scorer.types.ts +0 -128
  345. package/src/wirings/agent-scorer/index.ts +0 -23
  346. package/src/wirings/channel/channel-common.ts +0 -102
  347. package/src/wirings/channel/channel-handler-shapes.test.ts +0 -72
  348. package/src/wirings/channel/channel-handler.test.ts +0 -322
  349. package/src/wirings/channel/channel-handler.ts +0 -259
  350. package/src/wirings/channel/channel-host-rpc.test.ts +0 -150
  351. package/src/wirings/channel/channel-host-rpc.ts +0 -69
  352. package/src/wirings/channel/channel-middleware-runner.test.ts +0 -188
  353. package/src/wirings/channel/channel-middleware-runner.ts +0 -126
  354. package/src/wirings/channel/channel-rpc-registry.ts +0 -116
  355. package/src/wirings/channel/channel-rpc-responder.ts +0 -117
  356. package/src/wirings/channel/channel-rpc-service.ts +0 -132
  357. package/src/wirings/channel/channel-rpc-validators.ts +0 -65
  358. package/src/wirings/channel/channel-rpc.test.ts +0 -841
  359. package/src/wirings/channel/channel-rpc.ts +0 -5
  360. package/src/wirings/channel/channel-rpc.types.ts +0 -160
  361. package/src/wirings/channel/channel-runner.ts +0 -164
  362. package/src/wirings/channel/channel-store.ts +0 -35
  363. package/src/wirings/channel/channel.types.ts +0 -193
  364. package/src/wirings/channel/define-channel-routes.ts +0 -5
  365. package/src/wirings/channel/eventhub-service.ts +0 -16
  366. package/src/wirings/channel/eventhub-store.ts +0 -13
  367. package/src/wirings/channel/index.ts +0 -40
  368. package/src/wirings/channel/local/index.ts +0 -3
  369. package/src/wirings/channel/local/local-channel-handler.ts +0 -98
  370. package/src/wirings/channel/local/local-channel-runner.test.ts +0 -339
  371. package/src/wirings/channel/local/local-channel-runner.ts +0 -271
  372. package/src/wirings/channel/local/local-eventhub-service.test.ts +0 -77
  373. package/src/wirings/channel/local/local-eventhub-service.ts +0 -69
  374. package/src/wirings/channel/log-channels.ts +0 -16
  375. package/src/wirings/channel/pikku-abstract-channel-handler.test.ts +0 -135
  376. package/src/wirings/channel/pikku-abstract-channel-handler.ts +0 -60
  377. package/src/wirings/channel/serverless/index.ts +0 -6
  378. package/src/wirings/channel/serverless/serverless-channel-runner.ts +0 -328
  379. package/src/wirings/cli/channel/cli-approval.test.ts +0 -177
  380. package/src/wirings/cli/channel/cli-approval.ts +0 -135
  381. package/src/wirings/cli/channel/cli-channel-runner.ts +0 -118
  382. package/src/wirings/cli/channel/cli-raw-channel-runner.test.ts +0 -192
  383. package/src/wirings/cli/channel/cli-raw-channel-runner.ts +0 -148
  384. package/src/wirings/cli/channel/cli-raw-client-runner.test.ts +0 -480
  385. package/src/wirings/cli/channel/cli-raw-client-runner.ts +0 -188
  386. package/src/wirings/cli/channel/index.ts +0 -6
  387. package/src/wirings/cli/cli-runner.test.ts +0 -969
  388. package/src/wirings/cli/cli-runner.ts +0 -538
  389. package/src/wirings/cli/cli.types.ts +0 -388
  390. package/src/wirings/cli/command-parser.test.ts +0 -1120
  391. package/src/wirings/cli/command-parser.ts +0 -713
  392. package/src/wirings/cli/define-cli-commands.ts +0 -13
  393. package/src/wirings/cli/format-cli-error.test.ts +0 -91
  394. package/src/wirings/cli/format-cli-error.ts +0 -96
  395. package/src/wirings/cli/index.ts +0 -19
  396. package/src/wirings/credential/credential.types.ts +0 -37
  397. package/src/wirings/credential/define-credential.ts +0 -49
  398. package/src/wirings/credential/index.ts +0 -7
  399. package/src/wirings/credential/validate-credential-definitions.ts +0 -63
  400. package/src/wirings/gateway/gateway-authorization.test.ts +0 -575
  401. package/src/wirings/gateway/gateway-channel-meta.test.ts +0 -44
  402. package/src/wirings/gateway/gateway-runner.test.ts +0 -581
  403. package/src/wirings/gateway/gateway-runner.ts +0 -411
  404. package/src/wirings/gateway/gateway.types.ts +0 -137
  405. package/src/wirings/gateway/index.ts +0 -15
  406. package/src/wirings/http/http-routes.test.ts +0 -318
  407. package/src/wirings/http/http-routes.ts +0 -111
  408. package/src/wirings/http/http-runner-addon-ref.test.ts +0 -238
  409. package/src/wirings/http/http-runner.test.ts +0 -503
  410. package/src/wirings/http/http-runner.ts +0 -462
  411. package/src/wirings/http/http.types.ts +0 -307
  412. package/src/wirings/http/index.ts +0 -27
  413. package/src/wirings/http/log-http-routes.ts +0 -18
  414. package/src/wirings/http/pikku-fetch-http-request.test.ts +0 -318
  415. package/src/wirings/http/pikku-fetch-http-request.ts +0 -260
  416. package/src/wirings/http/pikku-fetch-http-response.test.ts +0 -123
  417. package/src/wirings/http/pikku-fetch-http-response.ts +0 -149
  418. package/src/wirings/http/routers/http-router.ts +0 -13
  419. package/src/wirings/http/routers/path-to-regex.test.ts +0 -306
  420. package/src/wirings/http/routers/path-to-regex.ts +0 -115
  421. package/src/wirings/http/web-request.test.ts +0 -382
  422. package/src/wirings/http/web-request.ts +0 -162
  423. package/src/wirings/mcp/index.ts +0 -26
  424. package/src/wirings/mcp/mcp-endpoint-registry.test.ts +0 -388
  425. package/src/wirings/mcp/mcp-endpoint-registry.ts +0 -159
  426. package/src/wirings/mcp/mcp-runner.test.ts +0 -588
  427. package/src/wirings/mcp/mcp-runner.ts +0 -330
  428. package/src/wirings/mcp/mcp.types.ts +0 -199
  429. package/src/wirings/node/index.ts +0 -2
  430. package/src/wirings/node/node.types.ts +0 -23
  431. package/src/wirings/oauth2/index.ts +0 -1
  432. package/src/wirings/oauth2/oauth2.types.ts +0 -12
  433. package/src/wirings/persona/define-personas.ts +0 -33
  434. package/src/wirings/persona/index.ts +0 -75
  435. package/src/wirings/persona/persona-app-scopes.test.ts +0 -47
  436. package/src/wirings/persona/persona-app-scopes.ts +0 -74
  437. package/src/wirings/persona/persona-email.ts +0 -87
  438. package/src/wirings/persona/persona-environments.test.ts +0 -194
  439. package/src/wirings/persona/persona-environments.ts +0 -138
  440. package/src/wirings/persona/persona-mailbox.ts +0 -156
  441. package/src/wirings/persona/persona.test.ts +0 -230
  442. package/src/wirings/persona/persona.types.ts +0 -156
  443. package/src/wirings/persona/validate-personas.ts +0 -137
  444. package/src/wirings/queue/index.ts +0 -29
  445. package/src/wirings/queue/queue-identity.test.ts +0 -454
  446. package/src/wirings/queue/queue-identity.ts +0 -176
  447. package/src/wirings/queue/queue-runner.test.ts +0 -705
  448. package/src/wirings/queue/queue-runner.ts +0 -181
  449. package/src/wirings/queue/queue.types.ts +0 -161
  450. package/src/wirings/queue/register-queue-helper.ts +0 -46
  451. package/src/wirings/queue/signed-queue-service.ts +0 -60
  452. package/src/wirings/queue/validate-worker-config.test.ts +0 -108
  453. package/src/wirings/queue/validate-worker-config.ts +0 -90
  454. package/src/wirings/role/define-system-role.ts +0 -33
  455. package/src/wirings/role/index.ts +0 -13
  456. package/src/wirings/role/role.test.ts +0 -104
  457. package/src/wirings/role/role.types.ts +0 -47
  458. package/src/wirings/role/validate-role-definitions.ts +0 -93
  459. package/src/wirings/rpc/index.ts +0 -8
  460. package/src/wirings/rpc/rpc-runner.test.ts +0 -1130
  461. package/src/wirings/rpc/rpc-runner.ts +0 -566
  462. package/src/wirings/rpc/rpc-types.ts +0 -87
  463. package/src/wirings/scheduler/index.ts +0 -11
  464. package/src/wirings/scheduler/log-schedulers.ts +0 -16
  465. package/src/wirings/scheduler/scheduler-runner.test.ts +0 -835
  466. package/src/wirings/scheduler/scheduler-runner.ts +0 -138
  467. package/src/wirings/scheduler/scheduler.types.ts +0 -42
  468. package/src/wirings/scope/define-scope.ts +0 -33
  469. package/src/wirings/scope/index.ts +0 -15
  470. package/src/wirings/scope/scope.test.ts +0 -159
  471. package/src/wirings/scope/scope.types.ts +0 -42
  472. package/src/wirings/scope/validate-scope-definitions.ts +0 -107
  473. package/src/wirings/secret/index.ts +0 -9
  474. package/src/wirings/secret/secret.types.ts +0 -70
  475. package/src/wirings/secret/validate-secret-definitions.test.ts +0 -232
  476. package/src/wirings/secret/validate-secret-definitions.ts +0 -88
  477. package/src/wirings/trigger/index.ts +0 -9
  478. package/src/wirings/trigger/pikku-trigger-service.ts +0 -107
  479. package/src/wirings/trigger/trigger-runner.test.ts +0 -78
  480. package/src/wirings/trigger/trigger-runner.ts +0 -113
  481. package/src/wirings/trigger/trigger.types.ts +0 -100
  482. package/src/wirings/variable/index.ts +0 -8
  483. package/src/wirings/variable/validate-variable-definitions.test.ts +0 -115
  484. package/src/wirings/variable/validate-variable-definitions.ts +0 -71
  485. package/src/wirings/variable/variable.types.ts +0 -40
  486. package/src/wirings/virtual-user/index.ts +0 -107
  487. package/src/wirings/virtual-user/prepare-virtual-user-run.test.ts +0 -115
  488. package/src/wirings/virtual-user/prepare-virtual-user-run.ts +0 -95
  489. package/src/wirings/virtual-user/run-virtual-user.test.ts +0 -774
  490. package/src/wirings/virtual-user/run-virtual-user.ts +0 -684
  491. package/src/wirings/virtual-user/virtual-user-agents.test.ts +0 -72
  492. package/src/wirings/virtual-user/virtual-user-agents.ts +0 -62
  493. package/src/wirings/virtual-user/virtual-user-catalogue.test.ts +0 -215
  494. package/src/wirings/virtual-user/virtual-user-catalogue.ts +0 -184
  495. package/src/wirings/virtual-user/virtual-user-derive.test.ts +0 -426
  496. package/src/wirings/virtual-user/virtual-user-derive.ts +0 -161
  497. package/src/wirings/virtual-user/virtual-user-dispositions.test.ts +0 -68
  498. package/src/wirings/virtual-user/virtual-user-dispositions.ts +0 -210
  499. package/src/wirings/virtual-user/virtual-user-intents.test.ts +0 -218
  500. package/src/wirings/virtual-user/virtual-user-intents.ts +0 -185
  501. package/src/wirings/virtual-user/virtual-user-rng.test.ts +0 -72
  502. package/src/wirings/virtual-user/virtual-user-rng.ts +0 -50
  503. package/src/wirings/virtual-user/virtual-user-run-store.ts +0 -131
  504. package/src/wirings/virtual-user/virtual-user-scaffold.test.ts +0 -854
  505. package/src/wirings/virtual-user/virtual-user-scaffold.ts +0 -664
  506. package/src/wirings/virtual-user/virtual-user-schedule-store.ts +0 -93
  507. package/src/wirings/virtual-user/virtual-user-schedule.test.ts +0 -280
  508. package/src/wirings/virtual-user/virtual-user-schedule.ts +0 -156
  509. package/src/wirings/virtual-user/virtual-user-target.ts +0 -47
  510. package/src/wirings/virtual-user/virtual-user.types.ts +0 -215
  511. package/src/wirings/workflow/dsl/workflow-dsl.types.ts +0 -709
  512. package/src/wirings/workflow/dsl/workflow-runner.ts +0 -25
  513. package/src/wirings/workflow/feature.test.ts +0 -131
  514. package/src/wirings/workflow/feature.ts +0 -59
  515. package/src/wirings/workflow/graph/graph-foreach-queued.test.ts +0 -569
  516. package/src/wirings/workflow/graph/graph-foreach.test.ts +0 -626
  517. package/src/wirings/workflow/graph/graph-node.ts +0 -115
  518. package/src/wirings/workflow/graph/graph-runner.test.ts +0 -1049
  519. package/src/wirings/workflow/graph/graph-runner.ts +0 -1376
  520. package/src/wirings/workflow/graph/graph-validation.test.ts +0 -27
  521. package/src/wirings/workflow/graph/graph-validation.ts +0 -41
  522. package/src/wirings/workflow/graph/template.test.ts +0 -49
  523. package/src/wirings/workflow/graph/template.ts +0 -42
  524. package/src/wirings/workflow/graph/wire-workflow-graph.ts +0 -39
  525. package/src/wirings/workflow/graph/workflow-graph.types.ts +0 -75
  526. package/src/wirings/workflow/index.ts +0 -107
  527. package/src/wirings/workflow/pikku-scenario-service.ts +0 -1013
  528. package/src/wirings/workflow/pikku-workflow-service.test.ts +0 -963
  529. package/src/wirings/workflow/pikku-workflow-service.ts +0 -1993
  530. package/src/wirings/workflow/run-timeline.test.ts +0 -199
  531. package/src/wirings/workflow/run-timeline.ts +0 -185
  532. package/src/wirings/workflow/scenario-cookie-jar.test.ts +0 -107
  533. package/src/wirings/workflow/scenario-cookie-jar.ts +0 -57
  534. package/src/wirings/workflow/scenario-expectations.test.ts +0 -238
  535. package/src/wirings/workflow/scenario-hooks.test.ts +0 -259
  536. package/src/wirings/workflow/scenario-poll.test.ts +0 -64
  537. package/src/wirings/workflow/scenario-poll.ts +0 -27
  538. package/src/wirings/workflow/scenario-prose.test.ts +0 -275
  539. package/src/wirings/workflow/scenario-prose.ts +0 -86
  540. package/src/wirings/workflow/scenario-run.types.ts +0 -193
  541. package/src/wirings/workflow/scenario-service.test.ts +0 -147
  542. package/src/wirings/workflow/scenario-step-guards.ts +0 -23
  543. package/src/wirings/workflow/scenario-step.test.ts +0 -800
  544. package/src/wirings/workflow/scenario-step.types.ts +0 -262
  545. package/src/wirings/workflow/scenario-surface.test.ts +0 -146
  546. package/src/wirings/workflow/scenario-surface.ts +0 -71
  547. package/src/wirings/workflow/scenario.types.ts +0 -63
  548. package/src/wirings/workflow/workflow-approval-audit.ts +0 -47
  549. package/src/wirings/workflow/workflow-approval-policy.test.ts +0 -594
  550. package/src/wirings/workflow/workflow-approval-policy.ts +0 -68
  551. package/src/wirings/workflow/workflow-approval.ts +0 -290
  552. package/src/wirings/workflow/workflow-child-run-session.test.ts +0 -168
  553. package/src/wirings/workflow/workflow-constants.ts +0 -66
  554. package/src/wirings/workflow/workflow-dispatch-durability.test.ts +0 -116
  555. package/src/wirings/workflow/workflow-dispatch-payload.test.ts +0 -55
  556. package/src/wirings/workflow/workflow-dispatch-relay.test.ts +0 -128
  557. package/src/wirings/workflow/workflow-errors.ts +0 -132
  558. package/src/wirings/workflow/workflow-inline-authority.test.ts +0 -175
  559. package/src/wirings/workflow/workflow-invocation-id.test.ts +0 -51
  560. package/src/wirings/workflow/workflow-invocation-id.ts +0 -28
  561. package/src/wirings/workflow/workflow-meta-resolver.ts +0 -45
  562. package/src/wirings/workflow/workflow-mirror.test.ts +0 -171
  563. package/src/wirings/workflow/workflow-missing-meta.test.ts +0 -92
  564. package/src/wirings/workflow/workflow-on-error.test.ts +0 -145
  565. package/src/wirings/workflow/workflow-queue-routing.ts +0 -129
  566. package/src/wirings/workflow/workflow-queue-wiring.ts +0 -149
  567. package/src/wirings/workflow/workflow-queue-workers.test.ts +0 -131
  568. package/src/wirings/workflow/workflow-queue-workers.ts +0 -66
  569. package/src/wirings/workflow/workflow-recovery.ts +0 -192
  570. package/src/wirings/workflow/workflow-replay-snapshot.test.ts +0 -140
  571. package/src/wirings/workflow/workflow-retry-policy.test.ts +0 -113
  572. package/src/wirings/workflow/workflow-run-authority.test.ts +0 -212
  573. package/src/wirings/workflow/workflow-run-context.test.ts +0 -172
  574. package/src/wirings/workflow/workflow-run-engine.types.ts +0 -92
  575. package/src/wirings/workflow/workflow-run-ownership.ts +0 -37
  576. package/src/wirings/workflow/workflow-run-polling.test.ts +0 -127
  577. package/src/wirings/workflow/workflow-stalled-recovery.test.ts +0 -152
  578. package/src/wirings/workflow/workflow-status-stream.test.ts +0 -354
  579. package/src/wirings/workflow/workflow-status-stream.ts +0 -144
  580. package/src/wirings/workflow/workflow-step-claim.ts +0 -46
  581. package/src/wirings/workflow/workflow-step-ordinal.test.ts +0 -94
  582. package/src/wirings/workflow/workflow-step-session.test.ts +0 -87
  583. package/src/wirings/workflow/workflow-suspend.ts +0 -61
  584. package/src/wirings/workflow/workflow-terminal-run-guard.test.ts +0 -105
  585. package/src/wirings/workflow/workflow.types.ts +0 -268
  586. package/src/wirings-stay-decoupled.test.ts +0 -130
  587. package/tsconfig.json +0 -14
  588. package/tsconfig.tsbuildinfo +0 -1
  589. package/tsconfig.type-tests.json +0 -15
@@ -1,1639 +0,0 @@
1
- import type {
2
- AgentStreamChannel,
3
- AgentStreamEvent,
4
- AgentStep,
5
- AgentMessage,
6
- AgentToolCall,
7
- AgentToolResult,
8
- PikkuAgentMiddlewareHooks,
9
- AgentRunState,
10
- CoreAgent,
11
- AgentMemoryConfig,
12
- } from './agent.types.js'
13
- import { finalizeAgentRun, lastUserMessageText } from './agent-finalize.js'
14
- import { pikkuState, getSingletonServices } from '../../pikku-state.js'
15
- import { applyInputMiddleware } from './agent-turn.js'
16
- import { AIProviderNotConfiguredError } from '../../errors/errors.js'
17
- import { deniedToolResult, randomUUID } from './agent-utils.js'
18
- import { SPOKEN_TRANSCRIPT } from './voice-input.js'
19
- import {
20
- combineChannelMiddleware,
21
- wrapChannelWithMiddleware,
22
- } from '../channel/channel-middleware-runner.js'
23
- import type { CorePikkuChannelMiddleware } from '../channel/channel.types.js'
24
- import type { CoreSingletonServices } from '../../types/core.types.js'
25
- import type { AgentStorageService } from '../../services/agent-storage-service.js'
26
- import type {
27
- AgentRunnerParams,
28
- AgentStepResult,
29
- } from '../../services/agent-runner-service.js'
30
-
31
- import {
32
- resolveMemoryServices,
33
- loadContextMessages,
34
- trimMessages,
35
- getWorkingMemoryMiddleware,
36
- } from './agent-memory.js'
37
- import {
38
- prepareAgentRun,
39
- resolveAgent,
40
- buildInstructions,
41
- buildToolDefs,
42
- createScopedChannel,
43
- resolveOwnerResourceId,
44
- agentSessionScope,
45
- assertResourceOwner,
46
- assertResourcePrincipalOwner,
47
- assertAgentAuthorized,
48
- ToolApprovalRequired,
49
- ToolCredentialRequired,
50
- APPROVAL_REQUIRED,
51
- CREDENTIAL_REQUIRED,
52
- type RunAgentParams,
53
- type StreamAgentOptions,
54
- type StreamContext,
55
- } from './agent-prepare.js'
56
- import { resolveModelConfig } from './agent-model-config.js'
57
- import type { AgentRunStateService } from '../../services/agent-run-state-service.js'
58
- import type { AgentRunnerService } from '../../services/agent-runner-service.js'
59
- import {
60
- getInFlightTools,
61
- isAbortError,
62
- persistOrphanedToolResults,
63
- registerInterruptibleRun,
64
- signalRunInterrupt,
65
- trackInterruptNote,
66
- trackToolExecution,
67
- type AgentInterruption,
68
- type AgentInterruptResult,
69
- } from './agent-interrupt.js'
70
-
71
- type PersistingChannel = AgentStreamChannel & {
72
- fullText: string
73
- flush: (opts?: { interrupted?: boolean }) => Promise<void>
74
- totalUsage: { inputTokens: number; outputTokens: number; model?: string }
75
- /** Every tool the run called, kept for the whole run rather than per step. */
76
- runToolCalls: NonNullable<AgentStep['toolCalls']>
77
- }
78
-
79
- function createPersistingChannel(
80
- parent: AgentStreamChannel,
81
- storage: AgentStorageService | undefined,
82
- threadId: string,
83
- logger?: { error: (...args: any[]) => void }
84
- ): PersistingChannel {
85
- let fullText = ''
86
- let stepText = ''
87
- let stepGenerativeUI: unknown | null = null
88
- let stepToolCalls: AgentToolCall[] = []
89
- let stepToolResults: AgentToolResult[] = []
90
- const totalUsage: {
91
- inputTokens: number
92
- outputTokens: number
93
- model?: string
94
- } = {
95
- inputTokens: 0,
96
- outputTokens: 0,
97
- }
98
- // Survives the per-step flush below, which clears its own buffers: the run
99
- // record needs every call the run made, not just the last step's.
100
- const runToolCalls: NonNullable<AgentStep['toolCalls']> = []
101
-
102
- const flushStep = async (opts?: { interrupted?: boolean }) => {
103
- if (!storage) return
104
- const text = stepText
105
- const generativeUI = stepGenerativeUI
106
- const calls = stepToolCalls
107
- const results = stepToolResults
108
- stepText = ''
109
- stepGenerativeUI = null
110
- stepToolCalls = []
111
- stepToolResults = []
112
- if (text || generativeUI != null || calls.length > 0) {
113
- const assistantMsg: AgentMessage = {
114
- id: randomUUID(),
115
- role: 'assistant',
116
- content:
117
- generativeUI != null
118
- ? [
119
- ...(text ? [{ type: 'text' as const, text }] : []),
120
- { type: 'generative-ui' as const, spec: generativeUI },
121
- ]
122
- : text || undefined,
123
- toolCalls: calls.length > 0 ? calls : undefined,
124
- ...(opts?.interrupted ? { interrupted: true } : {}),
125
- createdAt: new Date(),
126
- }
127
- const messages: AgentMessage[] = [assistantMsg]
128
- if (results.length > 0) {
129
- messages.push({
130
- id: randomUUID(),
131
- role: 'tool',
132
- toolResults: results,
133
- createdAt: new Date(),
134
- })
135
- }
136
- await storage.saveMessages(threadId, messages)
137
- }
138
- }
139
-
140
- const flushDetached = () => {
141
- void flushStep().catch((error) => {
142
- logger?.error('Failed to persist agent messages', {
143
- threadId,
144
- error,
145
- })
146
- })
147
- }
148
-
149
- const runToolCallIndex = new Map<string, number>()
150
-
151
- const channel: PersistingChannel = {
152
- channelId: parent.channelId,
153
- openingData: parent.openingData,
154
- get state() {
155
- return parent.state
156
- },
157
- get fullText() {
158
- return fullText
159
- },
160
- get totalUsage() {
161
- return totalUsage
162
- },
163
- get runToolCalls() {
164
- return runToolCalls
165
- },
166
- flush: flushStep,
167
- close: () => parent.close(),
168
- sendBinary: (data) => parent.sendBinary(data),
169
- send: (event: AgentStreamEvent) => {
170
- // Accumulated whether or not storage is configured: `fullText` is what
171
- // the client was streamed, and an interrupted run has to be able to
172
- // report the fragment it got through even with persistence turned off.
173
- if (event.type === 'text-delta') fullText += event.text
174
- if (event.type === 'tool-call') {
175
- runToolCallIndex.set(event.toolCallId, runToolCalls.length)
176
- runToolCalls.push({
177
- name: event.toolName,
178
- args: event.args as Record<string, unknown>,
179
- result: '',
180
- })
181
- }
182
- if (event.type === 'tool-result') {
183
- const index = runToolCallIndex.get(event.toolCallId)
184
- const result =
185
- typeof event.result === 'string'
186
- ? event.result
187
- : JSON.stringify(event.result)
188
- const call = index === undefined ? undefined : runToolCalls[index]
189
- if (call) {
190
- call.result = result
191
- if (event.error) call.error = event.error
192
- }
193
- }
194
- if (storage) {
195
- switch (event.type) {
196
- case 'text-delta':
197
- stepText += event.text
198
- break
199
- case 'tool-call':
200
- stepToolCalls.push({
201
- id: event.toolCallId,
202
- name: event.toolName,
203
- args: event.args as Record<string, unknown>,
204
- })
205
- break
206
- case 'tool-result':
207
- stepToolResults.push({
208
- id: event.toolCallId,
209
- name: event.toolName,
210
- result:
211
- typeof event.result === 'string'
212
- ? event.result
213
- : JSON.stringify(event.result),
214
- ...(event.error ? { error: event.error } : {}),
215
- })
216
- break
217
- case 'generative-ui':
218
- stepGenerativeUI = event.spec
219
- break
220
- case 'usage':
221
- totalUsage.inputTokens += event.tokens.input
222
- totalUsage.outputTokens += event.tokens.output
223
- if (event.model) totalUsage.model = event.model
224
- flushDetached()
225
- break
226
- case 'done':
227
- flushDetached()
228
- break
229
- }
230
- }
231
- parent.send(event)
232
- },
233
- setState: (s) => parent.setState(s),
234
- getState: () => parent.getState(),
235
- clearState: () => parent.clearState(),
236
- remote: (funcName: string, data?: unknown) => parent.remote(funcName, data),
237
- }
238
- return channel
239
- }
240
-
241
- /**
242
- * Agents already warned about, so a per-request hook does not become a
243
- * per-request log line.
244
- */
245
- const warnedUnstreamedOutputHooks = new Set<string>()
246
-
247
- /**
248
- * `modifyOutput` does not run on a streamed run at all. Nothing here could act
249
- * on what it returns — the text has already reached the client, and
250
- * `createPersistingChannel` flushes each step to storage as it goes, so by the
251
- * time the run ends the transcript is already written.
252
- *
253
- * Rewriting on this path belongs to `modifyOutputStream`, which genuinely
254
- * works: the stream middleware wraps the persisting channel, so what is stored
255
- * and accumulated is already what the client was sent. A middleware that
256
- * rewrites in `modifyOutput` only — a redaction hook, typically — is therefore
257
- * silently ineffective when the agent is streamed, and is told so once.
258
- */
259
- const warnUnstreamedOutputHooks = (
260
- agentName: string,
261
- agentMiddlewares: PikkuAgentMiddlewareHooks[],
262
- logger?: { warn: (...args: any[]) => void }
263
- ) => {
264
- if (warnedUnstreamedOutputHooks.has(agentName)) return
265
- const unstreamed = agentMiddlewares.some(
266
- (mw) => mw.modifyOutput && !mw.modifyOutputStream
267
- )
268
- if (!unstreamed) return
269
- warnedUnstreamedOutputHooks.add(agentName)
270
- logger?.warn(
271
- `Agent '${agentName}' has AI middleware with modifyOutput but no modifyOutputStream — modifyOutput does not apply to streamed runs. Implement modifyOutputStream to affect a streamed reply.`
272
- )
273
- }
274
-
275
- async function postStreamCleanup(
276
- persistingChannel: PersistingChannel,
277
- agentRunState: AgentRunStateService,
278
- runId: string,
279
- run: {
280
- agentName: string
281
- threadId: string
282
- resourceId?: string
283
- input: string
284
- }
285
- ): Promise<void> {
286
- await finalizeAgentRun(agentRunState, {
287
- runId,
288
- agentName: run.agentName,
289
- threadId: run.threadId,
290
- resourceId: run.resourceId,
291
- input: run.input,
292
- // Already what the client received: the stream middleware wraps the
293
- // persisting channel, so both were accumulated post-rewrite.
294
- text: persistingChannel.fullText,
295
- steps: [
296
- {
297
- usage: persistingChannel.totalUsage,
298
- toolCalls: persistingChannel.runToolCalls,
299
- },
300
- ],
301
- usage: persistingChannel.totalUsage,
302
- })
303
- }
304
-
305
- /**
306
- * Adapts `modifyOutputStream` hooks to channel middleware, one closure per
307
- * hook so each keeps its own `state` and event log for the whole run.
308
- */
309
- const toChannelStreamMiddleware = (
310
- hooks: PikkuAgentMiddlewareHooks[],
311
- sharedNotes: Record<string, unknown>,
312
- signal: AbortSignal
313
- ) =>
314
- hooks
315
- .filter((mw) => mw.modifyOutputStream)
316
- .map((mw) => {
317
- const state: Record<string, unknown> = {}
318
- const allEvents: AgentStreamEvent[] = []
319
- return async (services: any, event: any, next: any) => {
320
- allEvents.push(event)
321
- const result = await mw.modifyOutputStream!(services, {
322
- event,
323
- allEvents,
324
- state,
325
- shared: sharedNotes,
326
- // Sends downstream directly, so a hook can hand back the fast event
327
- // now and push the slow one when it is ready.
328
- emit: next,
329
- signal,
330
- })
331
- if (result == null) return
332
- if (Array.isArray(result)) {
333
- for (const r of result) await next(r)
334
- } else {
335
- await next(result)
336
- }
337
- }
338
- })
339
-
340
- /**
341
- * The branch a delegating parent's own spoken text is routed down once it has
342
- * handed off: the same working-memory hook instances as the main chain, so the
343
- * in-band `<working_memory>` blocks are still collected, ending in a sink so
344
- * neither the client, the thread history, nor user channel middleware sees
345
- * text the parent was supposed to keep to itself.
346
- *
347
- * Routing at ingress rather than dropping further down the chain keeps the
348
- * decision synchronous with the send: the working-memory hook is async, so a
349
- * hand-off landing mid-flight would otherwise retroactively suppress text the
350
- * parent spoke before it.
351
- */
352
- const createWorkingMemoryOnlyChannel = (
353
- channel: AgentStreamChannel,
354
- services: CoreSingletonServices,
355
- workingMemoryMiddleware: readonly CorePikkuChannelMiddleware[]
356
- ): AgentStreamChannel =>
357
- wrapChannelWithMiddleware(
358
- { channel: { ...channel, send: () => {} } as AgentStreamChannel },
359
- services,
360
- workingMemoryMiddleware
361
- ).channel as AgentStreamChannel
362
-
363
- type StepLoopParams = {
364
- agent: CoreAgent
365
- runnerParams: AgentRunnerParams
366
- maxSteps: number
367
- agentRunner: AgentRunnerService
368
- streamChannel: AgentStreamChannel
369
- persistingChannel: PersistingChannel
370
- channel: AgentStreamChannel
371
- agentMiddlewares: PikkuAgentMiddlewareHooks[]
372
- }
373
-
374
- type StepLoopResult =
375
- | { outcome: 'done' }
376
- | { outcome: 'approval'; approvals: ToolApprovalRequired[] }
377
- | { outcome: 'credential'; credentialRequests: ToolCredentialRequired[] }
378
-
379
- async function runStreamStepLoop(
380
- params: StepLoopParams
381
- ): Promise<StepLoopResult> {
382
- const {
383
- agent,
384
- runnerParams,
385
- maxSteps,
386
- agentRunner,
387
- streamChannel,
388
- channel,
389
- agentMiddlewares,
390
- } = params
391
-
392
- const singletonServices = getSingletonServices()
393
-
394
- for (let step = 0; step < maxSteps; step++) {
395
- if (agent.prepareStep) {
396
- let stopped = false
397
- await agent.prepareStep({
398
- stepNumber: step,
399
- messages: runnerParams.messages,
400
- tools: runnerParams.tools,
401
- toolChoice: runnerParams.toolChoice,
402
- model: runnerParams.model,
403
- stop: () => {
404
- stopped = true
405
- },
406
- })
407
- if (stopped) break
408
- }
409
-
410
- channel.send({ type: 'step-start', stepNumber: step })
411
-
412
- const stepResult = await agentRunner.stream(runnerParams, streamChannel)
413
-
414
- for (const mw of agentMiddlewares) {
415
- if (mw.afterStep) {
416
- await mw.afterStep(singletonServices, {
417
- stepNumber: step,
418
- text: stepResult.text,
419
- toolCalls: stepResult.toolCalls,
420
- toolResults: stepResult.toolResults,
421
- usage: stepResult.usage,
422
- finishReason: stepResult.finishReason,
423
- })
424
- }
425
- }
426
-
427
- if (stepResult.toolCalls.length === 0) break
428
-
429
- const approvalsNeeded = checkForApprovals(stepResult, runnerParams.tools)
430
- if (approvalsNeeded.length > 0) {
431
- for (const approval of approvalsNeeded) {
432
- const toolDef = runnerParams.tools.find(
433
- (t) => t.name === approval.toolName
434
- )
435
- if (toolDef?.approvalDescriptionFn && !approval.reason) {
436
- try {
437
- approval.reason = await toolDef.approvalDescriptionFn(approval.args)
438
- } catch {}
439
- }
440
- }
441
- return { outcome: 'approval', approvals: approvalsNeeded }
442
- }
443
-
444
- const credentialRequests = checkForCredentialRequests(stepResult)
445
- if (credentialRequests.length > 0) {
446
- appendStepMessages(runnerParams, stepResult)
447
- return { outcome: 'credential', credentialRequests }
448
- }
449
-
450
- appendStepMessages(runnerParams, stepResult)
451
- }
452
-
453
- return { outcome: 'done' }
454
- }
455
-
456
- export function checkForApprovals(
457
- stepResult: AgentStepResult,
458
- tools: AgentRunnerParams['tools']
459
- ): ToolApprovalRequired[] {
460
- const approvals: ToolApprovalRequired[] = []
461
- for (const tc of stepResult.toolCalls) {
462
- const toolDef = tools.find((t) => t.name === tc.toolName)
463
-
464
- if (toolDef?.needsApproval) {
465
- approvals.push(
466
- new ToolApprovalRequired(tc.toolCallId, tc.toolName, tc.args)
467
- )
468
- continue
469
- }
470
-
471
- if (!toolDef?.forwardsApproval) {
472
- continue
473
- }
474
-
475
- const tr = stepResult.toolResults.find(
476
- (r) => r.toolCallId === tc.toolCallId
477
- )
478
- if (
479
- tr?.result &&
480
- typeof tr.result === 'object' &&
481
- APPROVAL_REQUIRED in (tr.result as object)
482
- ) {
483
- const r = tr.result as {
484
- toolName: string
485
- args: unknown
486
- reason?: string
487
- displayToolName?: string
488
- displayArgs?: unknown
489
- agentRunId?: string
490
- subApprovals?: Array<{
491
- toolCallId: string
492
- toolName: string
493
- args: unknown
494
- reason?: string
495
- runId: string
496
- }>
497
- }
498
- if (r.subApprovals?.length) {
499
- for (const sub of r.subApprovals) {
500
- approvals.push(
501
- new ToolApprovalRequired(
502
- sub.toolCallId,
503
- r.toolName,
504
- r.args,
505
- sub.reason,
506
- sub.toolName,
507
- sub.args,
508
- r.agentRunId
509
- )
510
- )
511
- }
512
- } else {
513
- approvals.push(
514
- new ToolApprovalRequired(
515
- tc.toolCallId,
516
- r.toolName,
517
- r.args,
518
- r.reason,
519
- r.displayToolName,
520
- r.displayArgs,
521
- r.agentRunId
522
- )
523
- )
524
- }
525
- }
526
- }
527
- return approvals
528
- }
529
-
530
- export function checkForCredentialRequests(
531
- stepResult: AgentStepResult
532
- ): ToolCredentialRequired[] {
533
- const requests: ToolCredentialRequired[] = []
534
- for (const tr of stepResult.toolResults) {
535
- // knowledge: decisions/security/agent-credential-requests-are-symbol-branded.md
536
- if (
537
- tr.result &&
538
- typeof tr.result === 'object' &&
539
- CREDENTIAL_REQUIRED in (tr.result as object)
540
- ) {
541
- const r = tr.result as {
542
- credentialName: string
543
- credentialType: 'oauth2' | 'apikey'
544
- connectUrl?: string
545
- }
546
- const tc = stepResult.toolCalls.find(
547
- (t) => t.toolCallId === tr.toolCallId
548
- )
549
- requests.push(
550
- new ToolCredentialRequired(
551
- tr.toolCallId,
552
- tc?.toolName ?? 'unknown',
553
- tc?.args ?? {},
554
- r.credentialName,
555
- r.credentialType,
556
- r.connectUrl
557
- )
558
- )
559
- }
560
- }
561
- return requests
562
- }
563
-
564
- export function appendStepMessages(
565
- runnerParams: AgentRunnerParams,
566
- stepResult: AgentStepResult
567
- ): void {
568
- const structuredOutput =
569
- stepResult.object && typeof stepResult.object === 'object'
570
- ? (stepResult.object as Record<string, unknown>)
571
- : null
572
- const assistantContent =
573
- structuredOutput?.ui != null
574
- ? [
575
- ...(stepResult.text
576
- ? [{ type: 'text' as const, text: stepResult.text }]
577
- : []),
578
- { type: 'generative-ui' as const, spec: structuredOutput.ui },
579
- ]
580
- : stepResult.text || undefined
581
-
582
- const assistantMsg: AgentMessage = {
583
- id: randomUUID(),
584
- role: 'assistant',
585
- content: assistantContent,
586
- toolCalls:
587
- stepResult.toolCalls.length > 0
588
- ? stepResult.toolCalls.map((tc) => ({
589
- id: tc.toolCallId,
590
- name: tc.toolName,
591
- args: tc.args as Record<string, unknown>,
592
- }))
593
- : undefined,
594
- ...(stepResult.reasoningContent
595
- ? { reasoningContent: stepResult.reasoningContent }
596
- : {}),
597
- createdAt: new Date(),
598
- }
599
- runnerParams.messages.push(assistantMsg)
600
-
601
- if (stepResult.toolResults.length > 0) {
602
- const toolMsg: AgentMessage = {
603
- id: randomUUID(),
604
- role: 'tool',
605
- toolResults: stepResult.toolResults.map((tr) => ({
606
- id: tr.toolCallId,
607
- name: tr.toolName,
608
- result:
609
- typeof tr.result === 'string' ? tr.result : JSON.stringify(tr.result),
610
- })),
611
- createdAt: new Date(),
612
- }
613
- runnerParams.messages.push(toolMsg)
614
- }
615
- }
616
-
617
- function handleApprovals(
618
- approvals: ToolApprovalRequired[],
619
- runId: string,
620
- channel: AgentStreamChannel,
621
- agentRunState: AgentRunStateService,
622
- persistingChannel: PersistingChannel
623
- ): Promise<void> {
624
- return (async () => {
625
- await persistingChannel.flush()
626
-
627
- const pendingApprovals = approvals.map((err) =>
628
- err.agentRunId
629
- ? {
630
- type: 'agent-call' as const,
631
- toolCallId: err.toolCallId,
632
- agentName: err.toolName,
633
- agentRunId: err.agentRunId,
634
- displayToolName: err.displayToolName ?? err.toolName,
635
- displayArgs: err.displayArgs ?? err.args,
636
- }
637
- : {
638
- type: 'tool-call' as const,
639
- toolCallId: err.toolCallId,
640
- toolName: err.toolName,
641
- args: err.args,
642
- }
643
- )
644
-
645
- await agentRunState.updateRun(runId, {
646
- status: 'suspended',
647
- suspendReason: 'approval',
648
- pendingApprovals,
649
- })
650
-
651
- for (const err of approvals) {
652
- const approvalEvent = {
653
- type: 'approval-request' as const,
654
- toolCallId: err.toolCallId,
655
- toolName: err.displayToolName ?? err.toolName,
656
- args: err.displayArgs ?? err.args,
657
- reason: err.reason,
658
- runId,
659
- }
660
- channel.send(approvalEvent)
661
- }
662
- channel.send({ type: 'done' })
663
- channel.close()
664
- })()
665
- }
666
-
667
- function handleCredentialRequests(
668
- requests: ToolCredentialRequired[],
669
- runId: string,
670
- channel: AgentStreamChannel,
671
- agentRunState: AgentRunStateService,
672
- persistingChannel: PersistingChannel
673
- ): Promise<void> {
674
- return (async () => {
675
- await persistingChannel.flush()
676
-
677
- const pendingApprovals = requests.map((req) => ({
678
- type: 'credential-request' as const,
679
- toolCallId: req.toolCallId,
680
- toolName: req.toolName,
681
- args: req.args,
682
- credentialName: req.credentialName,
683
- credentialType: req.credentialType,
684
- connectUrl: req.connectUrl,
685
- }))
686
-
687
- await agentRunState.updateRun(runId, {
688
- status: 'suspended',
689
- suspendReason: 'credential',
690
- pendingApprovals,
691
- })
692
-
693
- for (const req of requests) {
694
- channel.send({
695
- type: 'credential-request',
696
- toolCallId: req.toolCallId,
697
- toolName: req.toolName,
698
- args: req.args,
699
- credentialName: req.credentialName,
700
- credentialType: req.credentialType,
701
- connectUrl: req.connectUrl,
702
- runId,
703
- })
704
- }
705
- channel.send({ type: 'done' })
706
- channel.close()
707
- })()
708
- }
709
-
710
- export async function streamAgent(
711
- agentName: string,
712
- input: {
713
- message: string
714
- threadId: string
715
- resourceId: string
716
- model?: string
717
- temperature?: number
718
- },
719
- channel: AgentStreamChannel,
720
- params: RunAgentParams,
721
- agentSessionMap?: Map<string, string>,
722
- options?: StreamAgentOptions
723
- ): Promise<string> {
724
- const sessionMap = agentSessionMap ?? new Map<string, string>()
725
-
726
- const normalizedInput = {
727
- ...input,
728
- resourceId: resolveOwnerResourceId(
729
- params,
730
- agentSessionScope(agentName),
731
- input.resourceId
732
- ),
733
- }
734
-
735
- const streamContext: StreamContext = { channel, options }
736
-
737
- const {
738
- agent,
739
- packageName,
740
- resolvedName,
741
- agentRunner,
742
- storage,
743
- memoryConfig,
744
- threadId,
745
- userMessage,
746
- runnerParams,
747
- maxSteps,
748
- missingRpcs,
749
- workingMemorySchemaName,
750
- } = await prepareAgentRun(
751
- agentName,
752
- normalizedInput,
753
- params,
754
- sessionMap,
755
- streamContext
756
- )
757
-
758
- runnerParams.agentId = agentName
759
-
760
- const singletonServices = getSingletonServices()
761
- const { agentRunState } = singletonServices
762
- if (!agentRunState) {
763
- throw new Error('AgentRunStateService not available in singletonServices')
764
- }
765
-
766
- if (missingRpcs.length > 0) {
767
- await agentRunState.createRun({
768
- agentName,
769
- threadId,
770
- resourceId: normalizedInput.resourceId,
771
- status: 'suspended',
772
- suspendReason: 'rpc-missing',
773
- missingRpcs,
774
- usage: { inputTokens: 0, outputTokens: 0, model: agent.model },
775
- createdAt: new Date(),
776
- updatedAt: new Date(),
777
- })
778
- channel.send({ type: 'suspended', reason: 'rpc-missing', missingRpcs })
779
- channel.send({ type: 'done' })
780
- return ''
781
- }
782
-
783
- const workingMemoryMiddleware = getWorkingMemoryMiddleware(
784
- memoryConfig,
785
- storage,
786
- {
787
- threadId,
788
- workingMemorySchemaName,
789
- logger: singletonServices.logger,
790
- schemaService: singletonServices.schema,
791
- }
792
- )
793
- const agentMiddlewares: PikkuAgentMiddlewareHooks[] = [
794
- ...workingMemoryMiddleware,
795
- ...(agent.agentMiddleware ?? []),
796
- ]
797
-
798
- // One bag per run, shared by every middleware — see PikkuAgentMiddlewareHooks.
799
- const sharedNotes: Record<string, unknown> = {}
800
-
801
- const { messages: modifiedMessages, instructions: modifiedInstructions } =
802
- await applyInputMiddleware(
803
- agentMiddlewares,
804
- singletonServices,
805
- {
806
- messages: runnerParams.messages,
807
- instructions: runnerParams.instructions,
808
- },
809
- sharedNotes
810
- )
811
- runnerParams.messages = modifiedMessages
812
- runnerParams.instructions = modifiedInstructions
813
-
814
- // knowledge: decisions/internals/the-transcript-event-is-sent-ahead-of-the-run.md
815
- const transcript = sharedNotes[SPOKEN_TRANSCRIPT]
816
- if (typeof transcript === 'string') {
817
- channel.send({ type: 'transcript', text: transcript })
818
- }
819
-
820
- // knowledge: decisions/internals/thread-history-records-the-transcript-not-the-audio.md
821
- const lastModified = modifiedMessages[modifiedMessages.length - 1]
822
- const persistedUserMessage =
823
- lastModified?.id === userMessage.id ? lastModified : userMessage
824
-
825
- const runId = await agentRunState.createRun({
826
- agentName,
827
- threadId,
828
- resourceId: normalizedInput.resourceId,
829
- status: 'running',
830
- usage: { inputTokens: 0, outputTokens: 0, model: agent.model },
831
- createdAt: new Date(),
832
- updatedAt: new Date(),
833
- })
834
- options?.onRunCreated?.(runId)
835
-
836
- // Registered before the first model call and released in `finally`, so the
837
- // window in which an interrupt can land is exactly the window in which there
838
- // is something to interrupt.
839
- const interruptHandle = registerInterruptibleRun(runId)
840
- runnerParams.abortSignal = interruptHandle.signal
841
- runnerParams.tools = trackToolExecution(runnerParams.tools, interruptHandle)
842
-
843
- if (storage) {
844
- await storage.saveMessages(threadId, [persistedUserMessage])
845
- }
846
-
847
- warnUnstreamedOutputHooks(
848
- agentName,
849
- agentMiddlewares,
850
- singletonServices.logger
851
- )
852
-
853
- const workingMemoryStreamMiddleware = toChannelStreamMiddleware(
854
- workingMemoryMiddleware,
855
- sharedNotes,
856
- interruptHandle.signal
857
- )
858
- const streamMiddleware = toChannelStreamMiddleware(
859
- agent.agentMiddleware ?? [],
860
- sharedNotes,
861
- interruptHandle.signal
862
- )
863
-
864
- const agentsMeta = pikkuState(packageName, 'agent', 'agentsMeta')
865
- const meta = agentsMeta[resolvedName]
866
-
867
- const isDelegateMode = agent.agentMode !== 'supervise' && meta?.agents?.length
868
- const delegateState = { delegated: false }
869
- if (isDelegateMode) {
870
- streamContext.delegateState = delegateState
871
- }
872
-
873
- const allChannelMiddleware = [
874
- ...workingMemoryStreamMiddleware,
875
- ...combineChannelMiddleware('agent', `stream:${agentName}`, {
876
- wireInheritedChannelMiddleware: meta?.channelMiddleware,
877
- wireChannelMiddleware: [
878
- ...(agent.channelMiddleware ?? []),
879
- ...streamMiddleware,
880
- ],
881
- }),
882
- ]
883
-
884
- const persistingChannel = createPersistingChannel(
885
- channel,
886
- storage,
887
- threadId,
888
- singletonServices.logger
889
- )
890
-
891
- const wrappedChannel =
892
- allChannelMiddleware.length > 0
893
- ? (wrapChannelWithMiddleware(
894
- { channel: persistingChannel },
895
- singletonServices,
896
- allChannelMiddleware
897
- ).channel as AgentStreamChannel)
898
- : persistingChannel
899
-
900
- const credentialFilteredChannel: AgentStreamChannel = {
901
- ...wrappedChannel,
902
- // knowledge: decisions/internals/an-agent-stream-send-must-return-the-inner-sends-promise.md
903
- send: (event: AgentStreamEvent) => {
904
- if (
905
- event.type === 'tool-result' &&
906
- event.result !== null &&
907
- typeof event.result === 'object' &&
908
- '__credentialRequired' in event.result
909
- ) {
910
- return
911
- }
912
- return wrappedChannel.send(event)
913
- },
914
- }
915
-
916
- const workingMemoryOnlyChannel =
917
- isDelegateMode && workingMemoryStreamMiddleware.length > 0
918
- ? createWorkingMemoryOnlyChannel(
919
- channel,
920
- singletonServices,
921
- workingMemoryStreamMiddleware
922
- )
923
- : undefined
924
-
925
- const outputChannel: AgentStreamChannel = isDelegateMode
926
- ? {
927
- ...credentialFilteredChannel,
928
- send: (event: AgentStreamEvent) => {
929
- if (
930
- delegateState.delegated &&
931
- (event.type === 'text-delta' || event.type === 'reasoning-delta')
932
- ) {
933
- return workingMemoryOnlyChannel?.send(event)
934
- }
935
- return credentialFilteredChannel.send(event)
936
- },
937
- }
938
- : credentialFilteredChannel
939
-
940
- try {
941
- const loopResult = await runStreamStepLoop({
942
- agent,
943
- runnerParams,
944
- maxSteps,
945
- agentRunner,
946
- streamChannel: outputChannel,
947
- persistingChannel,
948
- channel,
949
- agentMiddlewares,
950
- })
951
-
952
- if (loopResult.outcome === 'approval') {
953
- await handleApprovals(
954
- loopResult.approvals,
955
- runId,
956
- channel,
957
- agentRunState,
958
- persistingChannel
959
- )
960
- return persistingChannel.fullText
961
- }
962
-
963
- if (loopResult.outcome === 'credential') {
964
- await handleCredentialRequests(
965
- loopResult.credentialRequests,
966
- runId,
967
- channel,
968
- agentRunState,
969
- persistingChannel
970
- )
971
- return persistingChannel.fullText
972
- }
973
-
974
- await postStreamCleanup(persistingChannel, agentRunState, runId, {
975
- agentName,
976
- threadId,
977
- resourceId: input.resourceId,
978
- input: lastUserMessageText(runnerParams.messages),
979
- })
980
-
981
- // knowledge: decisions/internals/the-agent-done-event-goes-through-the-middleware-and-is-awaited.md
982
- await outputChannel.send({ type: 'done' })
983
- channel.close()
984
- return persistingChannel.fullText
985
- } catch (err) {
986
- // An interrupt is not a failure: the truncated text is real output the user
987
- // already heard part of, so it is persisted and marked rather than dropped.
988
- const interruption = interruptHandle.interruption
989
- if (interruption || isAbortError(err)) {
990
- await persistingChannel.flush({ interrupted: true })
991
- await agentRunState.updateRun(runId, { status: 'interrupted' })
992
- // Deliberately not awaited. A tool still running must not hold the stream
993
- // open — the whole point of barge-in is that the agent stops now — so the
994
- // note lands later and the next run on this thread waits for it instead.
995
- if (storage) {
996
- trackInterruptNote(
997
- threadId,
998
- persistOrphanedToolResults(interruptHandle, storage, threadId)
999
- )
1000
- }
1001
- channel.send({
1002
- type: 'interrupted',
1003
- runId,
1004
- text: persistingChannel.fullText,
1005
- reason: interruption?.reason ?? 'user',
1006
- })
1007
- channel.send({ type: 'done' })
1008
- channel.close()
1009
- return persistingChannel.fullText
1010
- }
1011
-
1012
- for (const mw of agentMiddlewares) {
1013
- if (mw.onError) {
1014
- try {
1015
- await mw.onError(singletonServices, {
1016
- error: err instanceof Error ? err : new Error(String(err)),
1017
- stepNumber: -1,
1018
- messages: runnerParams.messages,
1019
- })
1020
- } catch {}
1021
- }
1022
- }
1023
- await agentRunState.updateRun(runId, {
1024
- status: 'failed',
1025
- errorMessage: err instanceof Error ? err.message : String(err),
1026
- })
1027
- channel.send({
1028
- type: 'error',
1029
- message: err instanceof Error ? err.message : String(err),
1030
- })
1031
- channel.send({ type: 'done' })
1032
- channel.close()
1033
- return persistingChannel.fullText
1034
- } finally {
1035
- interruptHandle.release()
1036
- }
1037
- }
1038
-
1039
- /**
1040
- * Stop an in-flight run on behalf of a caller, after checking the run is theirs.
1041
- *
1042
- * Unlike {@link resumeAgent} this needs no channel: it does not continue the
1043
- * stream, it ends one. The `interrupted` event and the truncated message are
1044
- * emitted by the original {@link streamAgent} call on its own channel, so this
1045
- * can be reached over a plain RPC while the stream is held open elsewhere —
1046
- * which is exactly the shape a voice barge-in needs.
1047
- *
1048
- * Ownership is the whole gate, deliberately without {@link assertAgentAuthorized}.
1049
- * Resuming re-enters the agent and approves a tool call, so a revoked grant must
1050
- * block it; stopping is the opposite — if a caller's access to an agent was
1051
- * revoked mid-run, being able to stop their own run is harmless and arguably
1052
- * what you want.
1053
- *
1054
- * Returns `false` when there was nothing to stop. Racing a run that finishes on
1055
- * its own is the normal case in voice, so it is not an error.
1056
- */
1057
- export async function interruptAgent(
1058
- input: { runId: string; reason?: AgentInterruption['reason'] },
1059
- params: RunAgentParams
1060
- ): Promise<AgentInterruptResult> {
1061
- const { agentRunState, logger } = getSingletonServices()
1062
- if (!agentRunState) {
1063
- throw new Error('AgentRunStateService not available in singletonServices')
1064
- }
1065
-
1066
- const run = await agentRunState.getRun(input.runId)
1067
- if (!run) {
1068
- throw new Error(`No run found for runId ${input.runId}`)
1069
- }
1070
- assertResourceOwner(
1071
- resolveOwnerResourceId(
1072
- params,
1073
- agentSessionScope(run.agentName),
1074
- run.resourceId
1075
- ),
1076
- run.resourceId,
1077
- 'run'
1078
- )
1079
-
1080
- const stopped = signalRunInterrupt(input.runId, {
1081
- reason: input.reason ?? 'user',
1082
- })
1083
-
1084
- // knowledge: decisions/internals/an-agent-run-owned-by-another-instance-says-so.md
1085
- if (!stopped && run.status === 'running') {
1086
- logger?.warn(
1087
- `Could not interrupt run ${input.runId}: it is running in another process. ` +
1088
- 'Interrupts are process-local; fan them out over eventHub to support multiple instances.'
1089
- )
1090
- }
1091
-
1092
- // Reported after the abort so it names what is *still* running: aborting the
1093
- // model call does nothing to a tool already executing.
1094
- return { stopped, inFlightTools: getInFlightTools(input.runId) }
1095
- }
1096
-
1097
- export async function resumeAgent(
1098
- input: {
1099
- runId: string
1100
- toolCallId: string
1101
- approved: boolean
1102
- },
1103
- channel: AgentStreamChannel,
1104
- params: RunAgentParams,
1105
- options?: StreamAgentOptions
1106
- ): Promise<void> {
1107
- const singletonServices = getSingletonServices()
1108
- const { agentRunState } = singletonServices
1109
- if (!agentRunState) {
1110
- throw new Error('AgentRunStateService not available in singletonServices')
1111
- }
1112
-
1113
- const run = await agentRunState.getRun(input.runId)
1114
- if (!run) {
1115
- throw new Error(`No run found for runId ${input.runId}`)
1116
- }
1117
- assertResourcePrincipalOwner(
1118
- params,
1119
- agentSessionScope(run.agentName),
1120
- run.resourceId,
1121
- 'run'
1122
- )
1123
-
1124
- const pending = run.pendingApprovals?.find(
1125
- (p) => p.toolCallId === input.toolCallId
1126
- )
1127
- if (!pending) {
1128
- throw new Error(
1129
- `No pending approval for toolCallId ${input.toolCallId} on run ${input.runId}`
1130
- )
1131
- }
1132
-
1133
- const { agent, packageName, resolvedName } = resolveAgent(run.agentName)
1134
-
1135
- await assertAgentAuthorized(agent, params, packageName)
1136
-
1137
- // The read above is not a claim — concurrent resumes all see the same pending
1138
- // approval. `resolveApproval` is the claim, and the loser must not go on to
1139
- // run the tool a second time.
1140
- const claimed = await agentRunState.resolveApproval(
1141
- input.toolCallId,
1142
- input.approved ? 'approved' : 'denied'
1143
- )
1144
- if (!claimed) {
1145
- throw new Error(
1146
- `Approval for toolCallId ${input.toolCallId} was already resolved by another caller`
1147
- )
1148
- }
1149
-
1150
- const { storage } = resolveMemoryServices(agent, singletonServices)
1151
- const memoryConfig = agent.memory
1152
- const agentRunner = singletonServices.agentRunner
1153
- if (!agentRunner) {
1154
- throw new AIProviderNotConfiguredError()
1155
- }
1156
-
1157
- if (!input.approved) {
1158
- if (pending.type === 'agent-call') {
1159
- await agentRunState.updateRun(pending.agentRunId, { status: 'failed' })
1160
- }
1161
-
1162
- const denialResult = deniedToolResult()
1163
-
1164
- if (storage) {
1165
- await storage.saveMessages(run.threadId, [
1166
- {
1167
- id: randomUUID(),
1168
- role: 'tool',
1169
- toolResults: [
1170
- {
1171
- id: input.toolCallId,
1172
- name:
1173
- pending.type === 'tool-call' ||
1174
- pending.type === 'credential-request'
1175
- ? pending.toolName
1176
- : pending.agentName,
1177
- result: denialResult,
1178
- },
1179
- ],
1180
- createdAt: new Date(),
1181
- },
1182
- ])
1183
- }
1184
-
1185
- channel.send({
1186
- type: 'tool-result',
1187
- toolCallId: input.toolCallId,
1188
- toolName:
1189
- pending.type === 'tool-call' || pending.type === 'credential-request'
1190
- ? pending.toolName
1191
- : pending.agentName,
1192
- result: denialResult,
1193
- })
1194
-
1195
- const updatedRun = await agentRunState.getRun(run.runId)
1196
- const remaining = updatedRun?.pendingApprovals ?? []
1197
-
1198
- if (remaining.length > 0) {
1199
- channel.send({ type: 'done' })
1200
- channel.close()
1201
- return
1202
- }
1203
-
1204
- await agentRunState.updateRun(run.runId, { status: 'running' })
1205
-
1206
- await continueAfterToolResult(
1207
- run,
1208
- agent,
1209
- packageName,
1210
- resolvedName,
1211
- storage,
1212
- memoryConfig,
1213
- agentRunner,
1214
- channel,
1215
- params,
1216
- agentRunState,
1217
- options
1218
- )
1219
- return
1220
- }
1221
-
1222
- if (pending.type === 'agent-call') {
1223
- const subRun = await agentRunState.getRun(pending.agentRunId)
1224
- if (!subRun) {
1225
- throw new Error(`Sub-agent run not found: ${pending.agentRunId}`)
1226
- }
1227
- const subPending =
1228
- subRun.pendingApprovals?.find((p) => p.toolCallId === input.toolCallId) ??
1229
- subRun.pendingApprovals?.[0]
1230
- if (!subPending) {
1231
- throw new Error(
1232
- `No pending approval on sub-agent run ${pending.agentRunId}`
1233
- )
1234
- }
1235
-
1236
- const subChannel = createScopedChannel(channel, subRun.agentName, 'resume')
1237
- channel.send({
1238
- type: 'agent-call',
1239
- agentName: subRun.agentName,
1240
- session: 'resume',
1241
- input: null,
1242
- })
1243
-
1244
- await resumeAgent(
1245
- {
1246
- runId: pending.agentRunId,
1247
- toolCallId: subPending.toolCallId,
1248
- approved: true,
1249
- },
1250
- subChannel,
1251
- params,
1252
- options
1253
- )
1254
-
1255
- channel.send({
1256
- type: 'agent-result',
1257
- agentName: subRun.agentName,
1258
- session: 'resume',
1259
- result: null,
1260
- })
1261
-
1262
- if (storage) {
1263
- await storage.saveMessages(run.threadId, [
1264
- {
1265
- id: randomUUID(),
1266
- role: 'tool',
1267
- toolResults: [
1268
- {
1269
- id: input.toolCallId,
1270
- name: pending.agentName,
1271
- result: 'Sub-agent completed successfully',
1272
- },
1273
- ],
1274
- createdAt: new Date(),
1275
- },
1276
- ])
1277
- }
1278
- } else {
1279
- const streamContext: StreamContext = {
1280
- channel,
1281
- options: { ...options, requiresToolApproval: false },
1282
- }
1283
- const agentMiddlewaresForResume: PikkuAgentMiddlewareHooks[] =
1284
- agent.agentMiddleware ?? []
1285
- const { tools } = await buildToolDefs(
1286
- params,
1287
- new Map<string, string>(),
1288
- run.resourceId,
1289
- resolvedName,
1290
- packageName,
1291
- streamContext,
1292
- agentMiddlewaresForResume
1293
- )
1294
-
1295
- const matchingTool = tools.find((t) => t.name === pending.toolName)
1296
- if (!matchingTool) {
1297
- throw new Error(
1298
- `Tool "${pending.toolName}" not found in agent definition`
1299
- )
1300
- }
1301
-
1302
- const toolArgs =
1303
- typeof pending.args === 'string' ? JSON.parse(pending.args) : pending.args
1304
-
1305
- let toolResult: unknown
1306
- let toolError: string | undefined
1307
- try {
1308
- toolResult = await matchingTool.execute(toolArgs)
1309
- } catch (execErr: any) {
1310
- if (execErr?.payload?.error === 'missing_credential') {
1311
- toolResult = execErr.payload
1312
- toolError = 'missing_credential'
1313
- } else {
1314
- toolError = execErr instanceof Error ? execErr.message : String(execErr)
1315
- toolResult = `Error: ${toolError}`
1316
- }
1317
- }
1318
-
1319
- const resultStr =
1320
- typeof toolResult === 'string' ? toolResult : JSON.stringify(toolResult)
1321
- if (storage) {
1322
- await storage.saveMessages(run.threadId, [
1323
- {
1324
- id: randomUUID(),
1325
- role: 'tool',
1326
- toolResults: [
1327
- {
1328
- id: input.toolCallId,
1329
- name: pending.toolName,
1330
- result: resultStr,
1331
- },
1332
- ],
1333
- createdAt: new Date(),
1334
- },
1335
- ])
1336
- }
1337
-
1338
- channel.send({
1339
- type: 'tool-result',
1340
- toolCallId: input.toolCallId,
1341
- toolName: pending.toolName,
1342
- result: toolResult,
1343
- ...(toolError ? { error: toolError } : {}),
1344
- })
1345
- }
1346
-
1347
- const updatedRun = await agentRunState.getRun(run.runId)
1348
- const remaining = updatedRun?.pendingApprovals ?? []
1349
-
1350
- if (remaining.length > 0) {
1351
- channel.send({ type: 'done' })
1352
- channel.close()
1353
- return
1354
- }
1355
-
1356
- await agentRunState.updateRun(run.runId, { status: 'running' })
1357
-
1358
- await continueAfterToolResult(
1359
- run,
1360
- agent,
1361
- packageName,
1362
- resolvedName,
1363
- storage,
1364
- memoryConfig,
1365
- agentRunner,
1366
- channel,
1367
- params,
1368
- agentRunState,
1369
- options
1370
- )
1371
- }
1372
-
1373
- async function continueAfterToolResult(
1374
- run: AgentRunState,
1375
- agent: CoreAgent,
1376
- packageName: string | null,
1377
- resolvedName: string,
1378
- storage: AgentStorageService | undefined,
1379
- memoryConfig: AgentMemoryConfig | undefined,
1380
- agentRunner: AgentRunnerService,
1381
- channel: AgentStreamChannel,
1382
- params: RunAgentParams,
1383
- agentRunState: AgentRunStateService,
1384
- options?: StreamAgentOptions
1385
- ): Promise<void> {
1386
- const singletonServices = getSingletonServices()
1387
- const agentsMeta = pikkuState(packageName, 'agent', 'agentsMeta')
1388
- const meta = agentsMeta[resolvedName]
1389
- const workingMemorySchemaName = meta?.workingMemorySchema ?? null
1390
-
1391
- const messages = storage
1392
- ? await storage.getMessages(run.threadId, {
1393
- lastN: memoryConfig?.lastMessages ?? 20,
1394
- })
1395
- : []
1396
-
1397
- const workingMemoryJsonSchema = workingMemorySchemaName
1398
- ? pikkuState(packageName, 'misc', 'schemas').get(workingMemorySchemaName)
1399
- : undefined
1400
-
1401
- const contextMessages = await loadContextMessages(
1402
- memoryConfig,
1403
- storage,
1404
- { message: '', threadId: run.threadId, resourceId: run.resourceId },
1405
- workingMemoryJsonSchema
1406
- )
1407
-
1408
- const allMessages = [...contextMessages, ...messages]
1409
- const trimmedMessages = trimMessages(allMessages)
1410
-
1411
- const instructions = await buildInstructions(resolvedName, packageName)
1412
-
1413
- const workingMemoryMiddleware = getWorkingMemoryMiddleware(
1414
- memoryConfig,
1415
- storage,
1416
- {
1417
- threadId: run.threadId,
1418
- workingMemorySchemaName,
1419
- logger: singletonServices.logger,
1420
- schemaService: singletonServices.schema,
1421
- }
1422
- )
1423
- const agentMiddlewares: PikkuAgentMiddlewareHooks[] = [
1424
- ...workingMemoryMiddleware,
1425
- ...(agent.agentMiddleware ?? []),
1426
- ]
1427
- // One bag per run, shared by every middleware — see PikkuAgentMiddlewareHooks.
1428
- const sharedNotes: Record<string, unknown> = {}
1429
-
1430
- const { messages: modifiedMessages, instructions: modifiedInstructions } =
1431
- await applyInputMiddleware(
1432
- agentMiddlewares,
1433
- singletonServices,
1434
- { messages: trimmedMessages, instructions: instructions },
1435
- sharedNotes
1436
- )
1437
-
1438
- // knowledge: decisions/internals/a-resumed-agent-turn-is-as-interruptible-as-the-first.md
1439
- const interruptHandle = registerInterruptibleRun(run.runId)
1440
-
1441
- warnUnstreamedOutputHooks(
1442
- run.agentName,
1443
- agentMiddlewares,
1444
- singletonServices.logger
1445
- )
1446
-
1447
- const workingMemoryStreamMiddleware = toChannelStreamMiddleware(
1448
- workingMemoryMiddleware,
1449
- sharedNotes,
1450
- interruptHandle.signal
1451
- )
1452
- const streamMiddleware = toChannelStreamMiddleware(
1453
- agent.agentMiddleware ?? [],
1454
- sharedNotes,
1455
- interruptHandle.signal
1456
- )
1457
-
1458
- const allChannelMiddleware = [
1459
- ...workingMemoryStreamMiddleware,
1460
- ...combineChannelMiddleware('agent', `stream:${run.agentName}`, {
1461
- wireInheritedChannelMiddleware: meta?.channelMiddleware,
1462
- wireChannelMiddleware: [
1463
- ...(agent.channelMiddleware ?? []),
1464
- ...streamMiddleware,
1465
- ],
1466
- }),
1467
- ]
1468
-
1469
- const persistingChannel = createPersistingChannel(
1470
- channel,
1471
- storage,
1472
- run.threadId,
1473
- singletonServices.logger
1474
- )
1475
-
1476
- const wrappedChannel =
1477
- allChannelMiddleware.length > 0
1478
- ? (wrapChannelWithMiddleware(
1479
- { channel: persistingChannel },
1480
- singletonServices,
1481
- allChannelMiddleware
1482
- ).channel as AgentStreamChannel)
1483
- : persistingChannel
1484
-
1485
- const isDelegateMode = agent.agentMode !== 'supervise' && meta?.agents?.length
1486
- const delegateState = { delegated: false }
1487
-
1488
- const streamContext: StreamContext = { channel, options }
1489
- if (isDelegateMode) {
1490
- streamContext.delegateState = delegateState
1491
- }
1492
-
1493
- const workingMemoryOnlyChannel =
1494
- isDelegateMode && workingMemoryStreamMiddleware.length > 0
1495
- ? createWorkingMemoryOnlyChannel(
1496
- channel,
1497
- singletonServices,
1498
- workingMemoryStreamMiddleware
1499
- )
1500
- : undefined
1501
-
1502
- const outputChannel: AgentStreamChannel = isDelegateMode
1503
- ? {
1504
- ...wrappedChannel,
1505
- send: (event: AgentStreamEvent) => {
1506
- if (
1507
- delegateState.delegated &&
1508
- (event.type === 'text-delta' || event.type === 'reasoning-delta')
1509
- ) {
1510
- return workingMemoryOnlyChannel?.send(event)
1511
- }
1512
- return wrappedChannel.send(event)
1513
- },
1514
- }
1515
- : wrappedChannel
1516
-
1517
- const resumeTools = (
1518
- await buildToolDefs(
1519
- params,
1520
- new Map<string, string>(),
1521
- run.resourceId,
1522
- resolvedName,
1523
- packageName,
1524
- streamContext,
1525
- agentMiddlewares
1526
- )
1527
- ).tools
1528
-
1529
- const resolved = resolveModelConfig(resolvedName, agent)
1530
- const maxSteps = resolved.maxSteps ?? 10
1531
-
1532
- const runnerParams: AgentRunnerParams = {
1533
- model: resolved.model,
1534
- temperature: resolved.temperature,
1535
- instructions: modifiedInstructions,
1536
- messages: modifiedMessages,
1537
- tools: resumeTools,
1538
- maxSteps: 1,
1539
- toolChoice: (agent.toolChoice ?? 'auto') as 'auto' | 'required' | 'none',
1540
- providerOptions: agent.providerOptions,
1541
- outputSchema: meta?.outputSchema
1542
- ? pikkuState(packageName, 'misc', 'schemas').get(meta.outputSchema)
1543
- : undefined,
1544
- }
1545
-
1546
- runnerParams.abortSignal = interruptHandle.signal
1547
- runnerParams.tools = trackToolExecution(runnerParams.tools, interruptHandle)
1548
-
1549
- try {
1550
- const loopResult = await runStreamStepLoop({
1551
- agent,
1552
- runnerParams,
1553
- maxSteps,
1554
- agentRunner,
1555
- streamChannel: outputChannel,
1556
- persistingChannel,
1557
- channel,
1558
- agentMiddlewares,
1559
- })
1560
-
1561
- if (loopResult.outcome === 'approval') {
1562
- await handleApprovals(
1563
- loopResult.approvals,
1564
- run.runId,
1565
- channel,
1566
- agentRunState,
1567
- persistingChannel
1568
- )
1569
- return
1570
- }
1571
-
1572
- if (loopResult.outcome === 'credential') {
1573
- await handleCredentialRequests(
1574
- loopResult.credentialRequests,
1575
- run.runId,
1576
- channel,
1577
- agentRunState,
1578
- persistingChannel
1579
- )
1580
- return
1581
- }
1582
-
1583
- await postStreamCleanup(persistingChannel, agentRunState, run.runId, {
1584
- ...run,
1585
- input: lastUserMessageText(runnerParams.messages),
1586
- })
1587
-
1588
- // knowledge: decisions/internals/the-agent-done-event-goes-through-the-middleware-and-is-awaited.md
1589
- await wrappedChannel.send({ type: 'done' })
1590
- channel.close()
1591
- } catch (err) {
1592
- // Same reasoning as the first turn: an interrupt is not a failure, and the
1593
- // part of the reply the user already heard is real output.
1594
- const interruption = interruptHandle.interruption
1595
- if (interruption || isAbortError(err)) {
1596
- await persistingChannel.flush({ interrupted: true })
1597
- await agentRunState.updateRun(run.runId, { status: 'interrupted' })
1598
- if (storage) {
1599
- trackInterruptNote(
1600
- run.threadId,
1601
- persistOrphanedToolResults(interruptHandle, storage, run.threadId)
1602
- )
1603
- }
1604
- channel.send({
1605
- type: 'interrupted',
1606
- runId: run.runId,
1607
- text: persistingChannel.fullText,
1608
- reason: interruption?.reason ?? 'user',
1609
- })
1610
- channel.send({ type: 'done' })
1611
- channel.close()
1612
- return
1613
- }
1614
-
1615
- for (const mw of agentMiddlewares) {
1616
- if (mw.onError) {
1617
- try {
1618
- await mw.onError(singletonServices, {
1619
- error: err instanceof Error ? err : new Error(String(err)),
1620
- stepNumber: -1,
1621
- messages: runnerParams.messages,
1622
- })
1623
- } catch {}
1624
- }
1625
- }
1626
- await agentRunState.updateRun(run.runId, {
1627
- status: 'failed',
1628
- errorMessage: err instanceof Error ? err.message : String(err),
1629
- })
1630
- channel.send({
1631
- type: 'error',
1632
- message: err instanceof Error ? err.message : String(err),
1633
- })
1634
- channel.send({ type: 'done' })
1635
- channel.close()
1636
- } finally {
1637
- interruptHandle.release()
1638
- }
1639
- }