@warlock.js/core 4.8.0 → 4.8.1

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 (769) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/esm/connectors/ai-connector.mjs +1 -1
  3. package/package.json +12 -9
  4. package/esm/ai/src/agent/agent-input-builder.mjs +0 -133
  5. package/esm/ai/src/agent/agent-input-builder.mjs.map +0 -1
  6. package/esm/ai/src/agent/agent-log-event.mjs +0 -101
  7. package/esm/ai/src/agent/agent-log-event.mjs.map +0 -1
  8. package/esm/ai/src/agent/agent-stream.mjs +0 -82
  9. package/esm/ai/src/agent/agent-stream.mjs.map +0 -1
  10. package/esm/ai/src/agent/agent-to-stream-event.mjs +0 -86
  11. package/esm/ai/src/agent/agent-to-stream-event.mjs.map +0 -1
  12. package/esm/ai/src/agent/agent.mjs +0 -1276
  13. package/esm/ai/src/agent/agent.mjs.map +0 -1
  14. package/esm/ai/src/agent/index.mjs +0 -5
  15. package/esm/ai/src/agent/json-stream-guard.mjs +0 -400
  16. package/esm/ai/src/agent/json-stream-guard.mjs.map +0 -1
  17. package/esm/ai/src/agent/signature.mjs +0 -57
  18. package/esm/ai/src/agent/signature.mjs.map +0 -1
  19. package/esm/ai/src/agent/snapshot.mjs +0 -101
  20. package/esm/ai/src/agent/snapshot.mjs.map +0 -1
  21. package/esm/ai/src/agent/spawn-sub-agent.mjs +0 -68
  22. package/esm/ai/src/agent/spawn-sub-agent.mjs.map +0 -1
  23. package/esm/ai/src/ai.mjs +0 -191
  24. package/esm/ai/src/ai.mjs.map +0 -1
  25. package/esm/ai/src/batch/batch.mjs +0 -198
  26. package/esm/ai/src/batch/batch.mjs.map +0 -1
  27. package/esm/ai/src/batch/index.mjs +0 -3
  28. package/esm/ai/src/batch/run-batch-item.mjs +0 -100
  29. package/esm/ai/src/batch/run-batch-item.mjs.map +0 -1
  30. package/esm/ai/src/batch/run-with-concurrency.mjs +0 -39
  31. package/esm/ai/src/batch/run-with-concurrency.mjs.map +0 -1
  32. package/esm/ai/src/checkpoint/memory.mjs +0 -0
  33. package/esm/ai/src/checkpoint/memory.mjs.map +0 -1
  34. package/esm/ai/src/checkpoint/pg.mjs +0 -265
  35. package/esm/ai/src/checkpoint/pg.mjs.map +0 -1
  36. package/esm/ai/src/checkpoint/redis.mjs +0 -200
  37. package/esm/ai/src/checkpoint/redis.mjs.map +0 -1
  38. package/esm/ai/src/config.mjs +0 -59
  39. package/esm/ai/src/config.mjs.map +0 -1
  40. package/esm/ai/src/contracts/end.type.mjs +0 -47
  41. package/esm/ai/src/contracts/end.type.mjs.map +0 -1
  42. package/esm/ai/src/errors/agent-cancelled-error.mjs +0 -43
  43. package/esm/ai/src/errors/agent-cancelled-error.mjs.map +0 -1
  44. package/esm/ai/src/errors/agent-drift-error.mjs +0 -31
  45. package/esm/ai/src/errors/agent-drift-error.mjs.map +0 -1
  46. package/esm/ai/src/errors/agent-execution-error.mjs +0 -35
  47. package/esm/ai/src/errors/agent-execution-error.mjs.map +0 -1
  48. package/esm/ai/src/errors/agent-max-trips-error.mjs +0 -41
  49. package/esm/ai/src/errors/agent-max-trips-error.mjs.map +0 -1
  50. package/esm/ai/src/errors/ai-error.mjs +0 -68
  51. package/esm/ai/src/errors/ai-error.mjs.map +0 -1
  52. package/esm/ai/src/errors/budget-exceeded-error.mjs +0 -31
  53. package/esm/ai/src/errors/budget-exceeded-error.mjs.map +0 -1
  54. package/esm/ai/src/errors/content-filter-error.mjs +0 -28
  55. package/esm/ai/src/errors/content-filter-error.mjs.map +0 -1
  56. package/esm/ai/src/errors/context-length-exceeded-error.mjs +0 -31
  57. package/esm/ai/src/errors/context-length-exceeded-error.mjs.map +0 -1
  58. package/esm/ai/src/errors/guardrail-violation-error.mjs +0 -41
  59. package/esm/ai/src/errors/guardrail-violation-error.mjs.map +0 -1
  60. package/esm/ai/src/errors/index.mjs +0 -40
  61. package/esm/ai/src/errors/invalid-request-error.mjs +0 -31
  62. package/esm/ai/src/errors/invalid-request-error.mjs.map +0 -1
  63. package/esm/ai/src/errors/max-iterations-error.mjs +0 -32
  64. package/esm/ai/src/errors/max-iterations-error.mjs.map +0 -1
  65. package/esm/ai/src/errors/max-steps-exceeded-error.mjs +0 -21
  66. package/esm/ai/src/errors/max-steps-exceeded-error.mjs.map +0 -1
  67. package/esm/ai/src/errors/orchestrator-cancelled-error.mjs +0 -31
  68. package/esm/ai/src/errors/orchestrator-cancelled-error.mjs.map +0 -1
  69. package/esm/ai/src/errors/orchestrator-config-error.mjs +0 -30
  70. package/esm/ai/src/errors/orchestrator-config-error.mjs.map +0 -1
  71. package/esm/ai/src/errors/orchestrator-drift-error.mjs +0 -37
  72. package/esm/ai/src/errors/orchestrator-drift-error.mjs.map +0 -1
  73. package/esm/ai/src/errors/orchestrator-failed-error.mjs +0 -36
  74. package/esm/ai/src/errors/orchestrator-failed-error.mjs.map +0 -1
  75. package/esm/ai/src/errors/outbound-policy-error.mjs +0 -32
  76. package/esm/ai/src/errors/outbound-policy-error.mjs.map +0 -1
  77. package/esm/ai/src/errors/planner-cancelled-error.mjs +0 -29
  78. package/esm/ai/src/errors/planner-cancelled-error.mjs.map +0 -1
  79. package/esm/ai/src/errors/planner-drift-error.mjs +0 -33
  80. package/esm/ai/src/errors/planner-drift-error.mjs.map +0 -1
  81. package/esm/ai/src/errors/planner-failed-error.mjs +0 -37
  82. package/esm/ai/src/errors/planner-failed-error.mjs.map +0 -1
  83. package/esm/ai/src/errors/planner-plan-invalid-error.mjs +0 -25
  84. package/esm/ai/src/errors/planner-plan-invalid-error.mjs.map +0 -1
  85. package/esm/ai/src/errors/prompt-refinement-error.mjs +0 -27
  86. package/esm/ai/src/errors/prompt-refinement-error.mjs.map +0 -1
  87. package/esm/ai/src/errors/provider-auth-error.mjs +0 -26
  88. package/esm/ai/src/errors/provider-auth-error.mjs.map +0 -1
  89. package/esm/ai/src/errors/provider-error.mjs +0 -42
  90. package/esm/ai/src/errors/provider-error.mjs.map +0 -1
  91. package/esm/ai/src/errors/provider-rate-limit-error.mjs +0 -31
  92. package/esm/ai/src/errors/provider-rate-limit-error.mjs.map +0 -1
  93. package/esm/ai/src/errors/provider-timeout-error.mjs +0 -26
  94. package/esm/ai/src/errors/provider-timeout-error.mjs.map +0 -1
  95. package/esm/ai/src/errors/quota-exceeded-error.mjs +0 -40
  96. package/esm/ai/src/errors/quota-exceeded-error.mjs.map +0 -1
  97. package/esm/ai/src/errors/routing-error.mjs +0 -23
  98. package/esm/ai/src/errors/routing-error.mjs.map +0 -1
  99. package/esm/ai/src/errors/schema-validation-error.mjs +0 -37
  100. package/esm/ai/src/errors/schema-validation-error.mjs.map +0 -1
  101. package/esm/ai/src/errors/step-failed-error.mjs +0 -19
  102. package/esm/ai/src/errors/step-failed-error.mjs.map +0 -1
  103. package/esm/ai/src/errors/supervisor-cancelled-error.mjs +0 -29
  104. package/esm/ai/src/errors/supervisor-cancelled-error.mjs.map +0 -1
  105. package/esm/ai/src/errors/supervisor-drift-error.mjs +0 -30
  106. package/esm/ai/src/errors/supervisor-drift-error.mjs.map +0 -1
  107. package/esm/ai/src/errors/supervisor-failed-error.mjs +0 -43
  108. package/esm/ai/src/errors/supervisor-failed-error.mjs.map +0 -1
  109. package/esm/ai/src/errors/supervisor-routing-error.mjs +0 -39
  110. package/esm/ai/src/errors/supervisor-routing-error.mjs.map +0 -1
  111. package/esm/ai/src/errors/tool-execution-error.mjs +0 -32
  112. package/esm/ai/src/errors/tool-execution-error.mjs.map +0 -1
  113. package/esm/ai/src/errors/workflow-cancelled-error.mjs +0 -23
  114. package/esm/ai/src/errors/workflow-cancelled-error.mjs.map +0 -1
  115. package/esm/ai/src/errors/workflow-drift-error.mjs +0 -24
  116. package/esm/ai/src/errors/workflow-drift-error.mjs.map +0 -1
  117. package/esm/ai/src/errors/workflow-error.mjs +0 -18
  118. package/esm/ai/src/errors/workflow-error.mjs.map +0 -1
  119. package/esm/ai/src/eval/dataset.mjs +0 -112
  120. package/esm/ai/src/eval/dataset.mjs.map +0 -1
  121. package/esm/ai/src/eval/eval-runner.mjs +0 -135
  122. package/esm/ai/src/eval/eval-runner.mjs.map +0 -1
  123. package/esm/ai/src/eval/index.mjs +0 -48
  124. package/esm/ai/src/eval/index.mjs.map +0 -1
  125. package/esm/ai/src/eval/judge-scorer.mjs +0 -87
  126. package/esm/ai/src/eval/judge-scorer.mjs.map +0 -1
  127. package/esm/ai/src/eval/regression.mjs +0 -51
  128. package/esm/ai/src/eval/regression.mjs.map +0 -1
  129. package/esm/ai/src/eval/report-json.mjs +0 -33
  130. package/esm/ai/src/eval/report-json.mjs.map +0 -1
  131. package/esm/ai/src/eval/report-junit.mjs +0 -60
  132. package/esm/ai/src/eval/report-junit.mjs.map +0 -1
  133. package/esm/ai/src/eval/scorers.mjs +0 -101
  134. package/esm/ai/src/eval/scorers.mjs.map +0 -1
  135. package/esm/ai/src/guard/detectors/index.mjs +0 -6
  136. package/esm/ai/src/guard/detectors/injection.mjs +0 -254
  137. package/esm/ai/src/guard/detectors/injection.mjs.map +0 -1
  138. package/esm/ai/src/guard/detectors/moderation.mjs +0 -134
  139. package/esm/ai/src/guard/detectors/moderation.mjs.map +0 -1
  140. package/esm/ai/src/guard/detectors/pii.mjs +0 -199
  141. package/esm/ai/src/guard/detectors/pii.mjs.map +0 -1
  142. package/esm/ai/src/guard/detectors/topic.mjs +0 -99
  143. package/esm/ai/src/guard/detectors/topic.mjs.map +0 -1
  144. package/esm/ai/src/guard/errors.mjs +0 -18
  145. package/esm/ai/src/guard/errors.mjs.map +0 -1
  146. package/esm/ai/src/guard/guard.mjs +0 -209
  147. package/esm/ai/src/guard/guard.mjs.map +0 -1
  148. package/esm/ai/src/guard/guardrail.mjs +0 -22
  149. package/esm/ai/src/guard/guardrail.mjs.map +0 -1
  150. package/esm/ai/src/human/errors.mjs +0 -60
  151. package/esm/ai/src/human/errors.mjs.map +0 -1
  152. package/esm/ai/src/human/human-approval.mjs +0 -170
  153. package/esm/ai/src/human/human-approval.mjs.map +0 -1
  154. package/esm/ai/src/human/policy.mjs +0 -67
  155. package/esm/ai/src/human/policy.mjs.map +0 -1
  156. package/esm/ai/src/human/register.mjs +0 -37
  157. package/esm/ai/src/human/register.mjs.map +0 -1
  158. package/esm/ai/src/human/resume-seed.mjs +0 -53
  159. package/esm/ai/src/human/resume-seed.mjs.map +0 -1
  160. package/esm/ai/src/human/resume.mjs +0 -121
  161. package/esm/ai/src/human/resume.mjs.map +0 -1
  162. package/esm/ai/src/human/stores/index.mjs +0 -5
  163. package/esm/ai/src/human/stores/memory.mjs +0 -91
  164. package/esm/ai/src/human/stores/memory.mjs.map +0 -1
  165. package/esm/ai/src/human/stores/pg.mjs +0 -220
  166. package/esm/ai/src/human/stores/pg.mjs.map +0 -1
  167. package/esm/ai/src/human/stores/redis.mjs +0 -201
  168. package/esm/ai/src/human/stores/redis.mjs.map +0 -1
  169. package/esm/ai/src/image/image-cost.mjs +0 -55
  170. package/esm/ai/src/image/image-cost.mjs.map +0 -1
  171. package/esm/ai/src/image/image.mjs +0 -112
  172. package/esm/ai/src/image/image.mjs.map +0 -1
  173. package/esm/ai/src/image/index.mjs +0 -4
  174. package/esm/ai/src/index.mjs +0 -196
  175. package/esm/ai/src/memory/derive-id.mjs +0 -24
  176. package/esm/ai/src/memory/derive-id.mjs.map +0 -1
  177. package/esm/ai/src/memory/episodic-memory.mjs +0 -106
  178. package/esm/ai/src/memory/episodic-memory.mjs.map +0 -1
  179. package/esm/ai/src/memory/memory.mjs +0 -166
  180. package/esm/ai/src/memory/memory.mjs.map +0 -1
  181. package/esm/ai/src/memory/procedural-memory.mjs +0 -103
  182. package/esm/ai/src/memory/procedural-memory.mjs.map +0 -1
  183. package/esm/ai/src/memory/semantic-memory.mjs +0 -80
  184. package/esm/ai/src/memory/semantic-memory.mjs.map +0 -1
  185. package/esm/ai/src/memory/working-memory.mjs +0 -62
  186. package/esm/ai/src/memory/working-memory.mjs.map +0 -1
  187. package/esm/ai/src/middleware/builtins/budget.mjs +0 -219
  188. package/esm/ai/src/middleware/builtins/budget.mjs.map +0 -1
  189. package/esm/ai/src/middleware/builtins/guardrail.mjs +0 -76
  190. package/esm/ai/src/middleware/builtins/guardrail.mjs.map +0 -1
  191. package/esm/ai/src/middleware/builtins/semantic-cache.mjs +0 -149
  192. package/esm/ai/src/middleware/builtins/semantic-cache.mjs.map +0 -1
  193. package/esm/ai/src/middleware/helpers/compose.mjs +0 -52
  194. package/esm/ai/src/middleware/helpers/compose.mjs.map +0 -1
  195. package/esm/ai/src/middleware/helpers/for-tool.mjs +0 -80
  196. package/esm/ai/src/middleware/helpers/for-tool.mjs.map +0 -1
  197. package/esm/ai/src/middleware/index.mjs +0 -10
  198. package/esm/ai/src/middleware/pipeline.mjs +0 -100
  199. package/esm/ai/src/middleware/pipeline.mjs.map +0 -1
  200. package/esm/ai/src/middleware/utils/extract-user-text.mjs +0 -47
  201. package/esm/ai/src/middleware/utils/extract-user-text.mjs.map +0 -1
  202. package/esm/ai/src/middleware/utils/namespaced-state.mjs +0 -60
  203. package/esm/ai/src/middleware/utils/namespaced-state.mjs.map +0 -1
  204. package/esm/ai/src/mock/index.mjs +0 -4
  205. package/esm/ai/src/mock/mock-agent.mjs +0 -3
  206. package/esm/ai/src/mock/mock-router.mjs +0 -58
  207. package/esm/ai/src/mock/mock-router.mjs.map +0 -1
  208. package/esm/ai/src/model/fallback-model.mjs +0 -218
  209. package/esm/ai/src/model/fallback-model.mjs.map +0 -1
  210. package/esm/ai/src/model/index.mjs +0 -3
  211. package/esm/ai/src/object-stream/index.mjs +0 -4
  212. package/esm/ai/src/object-stream/parse-partial-json.mjs +0 -78
  213. package/esm/ai/src/object-stream/parse-partial-json.mjs.map +0 -1
  214. package/esm/ai/src/object-stream/stream-object.mjs +0 -97
  215. package/esm/ai/src/object-stream/stream-object.mjs.map +0 -1
  216. package/esm/ai/src/observe/index.mjs +0 -4
  217. package/esm/ai/src/observe/observer-registry.mjs +0 -35
  218. package/esm/ai/src/observe/observer-registry.mjs.map +0 -1
  219. package/esm/ai/src/observe/resolve-observers.mjs +0 -73
  220. package/esm/ai/src/observe/resolve-observers.mjs.map +0 -1
  221. package/esm/ai/src/orchestrator/as-tool.mjs +0 -98
  222. package/esm/ai/src/orchestrator/as-tool.mjs.map +0 -1
  223. package/esm/ai/src/orchestrator/checkpoint.mjs +0 -75
  224. package/esm/ai/src/orchestrator/checkpoint.mjs.map +0 -1
  225. package/esm/ai/src/orchestrator/commands.mjs +0 -34
  226. package/esm/ai/src/orchestrator/commands.mjs.map +0 -1
  227. package/esm/ai/src/orchestrator/compaction.mjs +0 -206
  228. package/esm/ai/src/orchestrator/compaction.mjs.map +0 -1
  229. package/esm/ai/src/orchestrator/dispatch.mjs +0 -171
  230. package/esm/ai/src/orchestrator/dispatch.mjs.map +0 -1
  231. package/esm/ai/src/orchestrator/emitter.mjs +0 -85
  232. package/esm/ai/src/orchestrator/emitter.mjs.map +0 -1
  233. package/esm/ai/src/orchestrator/execution.mjs +0 -395
  234. package/esm/ai/src/orchestrator/execution.mjs.map +0 -1
  235. package/esm/ai/src/orchestrator/index.mjs +0 -11
  236. package/esm/ai/src/orchestrator/load.mjs +0 -49
  237. package/esm/ai/src/orchestrator/load.mjs.map +0 -1
  238. package/esm/ai/src/orchestrator/lock.mjs +0 -75
  239. package/esm/ai/src/orchestrator/lock.mjs.map +0 -1
  240. package/esm/ai/src/orchestrator/memory.mjs +0 -141
  241. package/esm/ai/src/orchestrator/memory.mjs.map +0 -1
  242. package/esm/ai/src/orchestrator/orchestrator-stream.mjs +0 -98
  243. package/esm/ai/src/orchestrator/orchestrator-stream.mjs.map +0 -1
  244. package/esm/ai/src/orchestrator/orchestrator.mjs +0 -206
  245. package/esm/ai/src/orchestrator/orchestrator.mjs.map +0 -1
  246. package/esm/ai/src/orchestrator/resume.mjs +0 -74
  247. package/esm/ai/src/orchestrator/resume.mjs.map +0 -1
  248. package/esm/ai/src/orchestrator/session-lock.mjs +0 -83
  249. package/esm/ai/src/orchestrator/session-lock.mjs.map +0 -1
  250. package/esm/ai/src/orchestrator/signature.mjs +0 -120
  251. package/esm/ai/src/orchestrator/signature.mjs.map +0 -1
  252. package/esm/ai/src/orchestrator/window.mjs +0 -56
  253. package/esm/ai/src/orchestrator/window.mjs.map +0 -1
  254. package/esm/ai/src/planner/dag-scheduler.mjs +0 -97
  255. package/esm/ai/src/planner/dag-scheduler.mjs.map +0 -1
  256. package/esm/ai/src/planner/index.mjs +0 -6
  257. package/esm/ai/src/planner/plan-prompt.mjs +0 -31
  258. package/esm/ai/src/planner/plan-prompt.mjs.map +0 -1
  259. package/esm/ai/src/planner/plan-schema.mjs +0 -120
  260. package/esm/ai/src/planner/plan-schema.mjs.map +0 -1
  261. package/esm/ai/src/planner/planner-run.mjs +0 -769
  262. package/esm/ai/src/planner/planner-run.mjs.map +0 -1
  263. package/esm/ai/src/planner/planner.mjs +0 -144
  264. package/esm/ai/src/planner/planner.mjs.map +0 -1
  265. package/esm/ai/src/planner/signature.mjs +0 -27
  266. package/esm/ai/src/planner/signature.mjs.map +0 -1
  267. package/esm/ai/src/planner/snapshot.mjs +0 -95
  268. package/esm/ai/src/planner/snapshot.mjs.map +0 -1
  269. package/esm/ai/src/prompt/errors.mjs +0 -73
  270. package/esm/ai/src/prompt/errors.mjs.map +0 -1
  271. package/esm/ai/src/prompt/index.mjs +0 -4
  272. package/esm/ai/src/prompt/prompt-langfuse-sync.mjs +0 -104
  273. package/esm/ai/src/prompt/prompt-langfuse-sync.mjs.map +0 -1
  274. package/esm/ai/src/prompt/prompt-validate.mjs +0 -170
  275. package/esm/ai/src/prompt/prompt-validate.mjs.map +0 -1
  276. package/esm/ai/src/prompt/prompt.mjs +0 -218
  277. package/esm/ai/src/prompt/prompt.mjs.map +0 -1
  278. package/esm/ai/src/prompts/index.mjs +0 -3
  279. package/esm/ai/src/prompts/prompts-manager.mjs +0 -410
  280. package/esm/ai/src/prompts/prompts-manager.mjs.map +0 -1
  281. package/esm/ai/src/prompts/prompts-validate.mjs +0 -0
  282. package/esm/ai/src/prompts/prompts-validate.mjs.map +0 -1
  283. package/esm/ai/src/rag/as-tool.mjs +0 -48
  284. package/esm/ai/src/rag/as-tool.mjs.map +0 -1
  285. package/esm/ai/src/rag/chunk/chunk.mjs +0 -44
  286. package/esm/ai/src/rag/chunk/chunk.mjs.map +0 -1
  287. package/esm/ai/src/rag/chunk/fixed.mjs +0 -32
  288. package/esm/ai/src/rag/chunk/fixed.mjs.map +0 -1
  289. package/esm/ai/src/rag/chunk/markdown.mjs +0 -75
  290. package/esm/ai/src/rag/chunk/markdown.mjs.map +0 -1
  291. package/esm/ai/src/rag/chunk/recursive.mjs +0 -132
  292. package/esm/ai/src/rag/chunk/recursive.mjs.map +0 -1
  293. package/esm/ai/src/rag/chunk/sentence.mjs +0 -73
  294. package/esm/ai/src/rag/chunk/sentence.mjs.map +0 -1
  295. package/esm/ai/src/rag/hybrid/bm25.mjs +0 -51
  296. package/esm/ai/src/rag/hybrid/bm25.mjs.map +0 -1
  297. package/esm/ai/src/rag/hybrid/hybrid-rank.mjs +0 -29
  298. package/esm/ai/src/rag/hybrid/hybrid-rank.mjs.map +0 -1
  299. package/esm/ai/src/rag/hybrid/rrf.mjs +0 -30
  300. package/esm/ai/src/rag/hybrid/rrf.mjs.map +0 -1
  301. package/esm/ai/src/rag/index.mjs +0 -18
  302. package/esm/ai/src/rag/loaders/errors.mjs +0 -25
  303. package/esm/ai/src/rag/loaders/errors.mjs.map +0 -1
  304. package/esm/ai/src/rag/loaders/index.mjs +0 -7
  305. package/esm/ai/src/rag/loaders/load-html.mjs +0 -138
  306. package/esm/ai/src/rag/loaders/load-html.mjs.map +0 -1
  307. package/esm/ai/src/rag/loaders/load-pdf.mjs +0 -150
  308. package/esm/ai/src/rag/loaders/load-pdf.mjs.map +0 -1
  309. package/esm/ai/src/rag/loaders/load-text.mjs +0 -60
  310. package/esm/ai/src/rag/loaders/load-text.mjs.map +0 -1
  311. package/esm/ai/src/rag/loaders/load-web.mjs +0 -89
  312. package/esm/ai/src/rag/loaders/load-web.mjs.map +0 -1
  313. package/esm/ai/src/rag/rag.mjs +0 -126
  314. package/esm/ai/src/rag/rag.mjs.map +0 -1
  315. package/esm/ai/src/rag/rerank/keyword-reranker.mjs +0 -58
  316. package/esm/ai/src/rag/rerank/keyword-reranker.mjs.map +0 -1
  317. package/esm/ai/src/rag/rerank/llm-reranker.mjs +0 -85
  318. package/esm/ai/src/rag/rerank/llm-reranker.mjs.map +0 -1
  319. package/esm/ai/src/rag/retrieve.mjs +0 -68
  320. package/esm/ai/src/rag/retrieve.mjs.map +0 -1
  321. package/esm/ai/src/rag/store/cache-vector-store.mjs +0 -48
  322. package/esm/ai/src/rag/store/cache-vector-store.mjs.map +0 -1
  323. package/esm/ai/src/rag/store/pg-vector-store.mjs +0 -328
  324. package/esm/ai/src/rag/store/pg-vector-store.mjs.map +0 -1
  325. package/esm/ai/src/rag/transforms/multi-query.mjs +0 -41
  326. package/esm/ai/src/rag/transforms/multi-query.mjs.map +0 -1
  327. package/esm/ai/src/security/index.mjs +0 -5
  328. package/esm/ai/src/security/outbound-policy.mjs +0 -187
  329. package/esm/ai/src/security/outbound-policy.mjs.map +0 -1
  330. package/esm/ai/src/security/private-ip.mjs +0 -48
  331. package/esm/ai/src/security/private-ip.mjs.map +0 -1
  332. package/esm/ai/src/security/redact.mjs +0 -60
  333. package/esm/ai/src/security/redact.mjs.map +0 -1
  334. package/esm/ai/src/serve/serve.mjs +0 -90
  335. package/esm/ai/src/serve/serve.mjs.map +0 -1
  336. package/esm/ai/src/serve/sse.mjs +0 -25
  337. package/esm/ai/src/serve/sse.mjs.map +0 -1
  338. package/esm/ai/src/serve/stream-to-sse.mjs +0 -37
  339. package/esm/ai/src/serve/stream-to-sse.mjs.map +0 -1
  340. package/esm/ai/src/skills/catalog.mjs +0 -140
  341. package/esm/ai/src/skills/catalog.mjs.map +0 -1
  342. package/esm/ai/src/skills/index.mjs +0 -11
  343. package/esm/ai/src/skills/load-skill-tool.mjs +0 -65
  344. package/esm/ai/src/skills/load-skill-tool.mjs.map +0 -1
  345. package/esm/ai/src/skills/save-skill-tool.mjs +0 -65
  346. package/esm/ai/src/skills/save-skill-tool.mjs.map +0 -1
  347. package/esm/ai/src/skills/skills.mjs +0 -109
  348. package/esm/ai/src/skills/skills.mjs.map +0 -1
  349. package/esm/ai/src/skills/sources/directory-source.mjs +0 -108
  350. package/esm/ai/src/skills/sources/directory-source.mjs.map +0 -1
  351. package/esm/ai/src/skills/sources/index.mjs +0 -27
  352. package/esm/ai/src/skills/sources/index.mjs.map +0 -1
  353. package/esm/ai/src/skills/sources/parse-frontmatter.mjs +0 -46
  354. package/esm/ai/src/skills/sources/parse-frontmatter.mjs.map +0 -1
  355. package/esm/ai/src/skills/sources/store-source.mjs +0 -15
  356. package/esm/ai/src/skills/sources/store-source.mjs.map +0 -1
  357. package/esm/ai/src/skills/sources/url-source.mjs +0 -117
  358. package/esm/ai/src/skills/sources/url-source.mjs.map +0 -1
  359. package/esm/ai/src/snapshot/memory.mjs +0 -81
  360. package/esm/ai/src/snapshot/memory.mjs.map +0 -1
  361. package/esm/ai/src/snapshot/pg.mjs +0 -146
  362. package/esm/ai/src/snapshot/pg.mjs.map +0 -1
  363. package/esm/ai/src/snapshot/redis.mjs +0 -101
  364. package/esm/ai/src/snapshot/redis.mjs.map +0 -1
  365. package/esm/ai/src/speech/index.mjs +0 -3
  366. package/esm/ai/src/speech/speech.mjs +0 -122
  367. package/esm/ai/src/speech/speech.mjs.map +0 -1
  368. package/esm/ai/src/supervisor/as-tool.mjs +0 -74
  369. package/esm/ai/src/supervisor/as-tool.mjs.map +0 -1
  370. package/esm/ai/src/supervisor/cancellation.mjs +0 -22
  371. package/esm/ai/src/supervisor/cancellation.mjs.map +0 -1
  372. package/esm/ai/src/supervisor/decide.mjs +0 -272
  373. package/esm/ai/src/supervisor/decide.mjs.map +0 -1
  374. package/esm/ai/src/supervisor/emitter.mjs +0 -47
  375. package/esm/ai/src/supervisor/emitter.mjs.map +0 -1
  376. package/esm/ai/src/supervisor/entries.mjs +0 -206
  377. package/esm/ai/src/supervisor/entries.mjs.map +0 -1
  378. package/esm/ai/src/supervisor/execution.mjs +0 -1921
  379. package/esm/ai/src/supervisor/execution.mjs.map +0 -1
  380. package/esm/ai/src/supervisor/fan-out.mjs +0 -65
  381. package/esm/ai/src/supervisor/fan-out.mjs.map +0 -1
  382. package/esm/ai/src/supervisor/index.mjs +0 -14
  383. package/esm/ai/src/supervisor/router-factory.mjs +0 -141
  384. package/esm/ai/src/supervisor/router-factory.mjs.map +0 -1
  385. package/esm/ai/src/supervisor/router-prompt.mjs +0 -52
  386. package/esm/ai/src/supervisor/router-prompt.mjs.map +0 -1
  387. package/esm/ai/src/supervisor/signature.mjs +0 -89
  388. package/esm/ai/src/supervisor/signature.mjs.map +0 -1
  389. package/esm/ai/src/supervisor/snapshot.mjs +0 -69
  390. package/esm/ai/src/supervisor/snapshot.mjs.map +0 -1
  391. package/esm/ai/src/supervisor/supervisor-stream.mjs +0 -89
  392. package/esm/ai/src/supervisor/supervisor-stream.mjs.map +0 -1
  393. package/esm/ai/src/supervisor/supervisor.mjs +0 -144
  394. package/esm/ai/src/supervisor/supervisor.mjs.map +0 -1
  395. package/esm/ai/src/system-prompt/index.mjs +0 -7
  396. package/esm/ai/src/system-prompt/instruction.mjs +0 -57
  397. package/esm/ai/src/system-prompt/instruction.mjs.map +0 -1
  398. package/esm/ai/src/system-prompt/persona.mjs +0 -57
  399. package/esm/ai/src/system-prompt/persona.mjs.map +0 -1
  400. package/esm/ai/src/system-prompt/refined-system-prompt.mjs +0 -461
  401. package/esm/ai/src/system-prompt/refined-system-prompt.mjs.map +0 -1
  402. package/esm/ai/src/system-prompt/render-placeholders.mjs +0 -58
  403. package/esm/ai/src/system-prompt/render-placeholders.mjs.map +0 -1
  404. package/esm/ai/src/system-prompt/system-prompt.mjs +0 -286
  405. package/esm/ai/src/system-prompt/system-prompt.mjs.map +0 -1
  406. package/esm/ai/src/team/gates.mjs +0 -48
  407. package/esm/ai/src/team/gates.mjs.map +0 -1
  408. package/esm/ai/src/team/index.mjs +0 -3
  409. package/esm/ai/src/team/team.mjs +0 -94
  410. package/esm/ai/src/team/team.mjs.map +0 -1
  411. package/esm/ai/src/tool/executable-as-tool.mjs +0 -81
  412. package/esm/ai/src/tool/executable-as-tool.mjs.map +0 -1
  413. package/esm/ai/src/tool/index.mjs +0 -4
  414. package/esm/ai/src/tool/tool.mjs +0 -185
  415. package/esm/ai/src/tool/tool.mjs.map +0 -1
  416. package/esm/ai/src/transcribe/audio-input.mjs +0 -84
  417. package/esm/ai/src/transcribe/audio-input.mjs.map +0 -1
  418. package/esm/ai/src/transcribe/index.mjs +0 -4
  419. package/esm/ai/src/transcribe/transcribe.mjs +0 -127
  420. package/esm/ai/src/transcribe/transcribe.mjs.map +0 -1
  421. package/esm/ai/src/utils/compute-cost.mjs +0 -112
  422. package/esm/ai/src/utils/compute-cost.mjs.map +0 -1
  423. package/esm/ai/src/utils/extract-json-lenient.mjs +0 -97
  424. package/esm/ai/src/utils/extract-json-lenient.mjs.map +0 -1
  425. package/esm/ai/src/utils/extract-json-payload.mjs +0 -39
  426. package/esm/ai/src/utils/extract-json-payload.mjs.map +0 -1
  427. package/esm/ai/src/utils/generate-run-id.mjs +0 -23
  428. package/esm/ai/src/utils/generate-run-id.mjs.map +0 -1
  429. package/esm/ai/src/utils/index.mjs +0 -12
  430. package/esm/ai/src/utils/json-schema.mjs +0 -89
  431. package/esm/ai/src/utils/json-schema.mjs.map +0 -1
  432. package/esm/ai/src/utils/prepare-attachment-part.mjs +0 -232
  433. package/esm/ai/src/utils/prepare-attachment-part.mjs.map +0 -1
  434. package/esm/ai/src/utils/resolve-attachment.mjs +0 -74
  435. package/esm/ai/src/utils/resolve-attachment.mjs.map +0 -1
  436. package/esm/ai/src/utils/run-context.mjs +0 -89
  437. package/esm/ai/src/utils/run-context.mjs.map +0 -1
  438. package/esm/ai/src/utils/safe-json-parse.mjs +0 -22
  439. package/esm/ai/src/utils/safe-json-parse.mjs.map +0 -1
  440. package/esm/ai/src/utils/stamp-report-lineage.mjs +0 -45
  441. package/esm/ai/src/utils/stamp-report-lineage.mjs.map +0 -1
  442. package/esm/ai/src/vcr/cassette-io.mjs +0 -57
  443. package/esm/ai/src/vcr/cassette-io.mjs.map +0 -1
  444. package/esm/ai/src/vcr/errors.mjs +0 -37
  445. package/esm/ai/src/vcr/errors.mjs.map +0 -1
  446. package/esm/ai/src/vcr/hash-request.mjs +0 -118
  447. package/esm/ai/src/vcr/hash-request.mjs.map +0 -1
  448. package/esm/ai/src/vcr/index.mjs +0 -5
  449. package/esm/ai/src/vcr/vcr.mjs +0 -248
  450. package/esm/ai/src/vcr/vcr.mjs.map +0 -1
  451. package/esm/ai/src/workflow/as-tool.mjs +0 -49
  452. package/esm/ai/src/workflow/as-tool.mjs.map +0 -1
  453. package/esm/ai/src/workflow/cancellation.mjs +0 -44
  454. package/esm/ai/src/workflow/cancellation.mjs.map +0 -1
  455. package/esm/ai/src/workflow/emitter.mjs +0 -40
  456. package/esm/ai/src/workflow/emitter.mjs.map +0 -1
  457. package/esm/ai/src/workflow/engine.mjs +0 -363
  458. package/esm/ai/src/workflow/engine.mjs.map +0 -1
  459. package/esm/ai/src/workflow/index.mjs +0 -5
  460. package/esm/ai/src/workflow/retry.mjs +0 -32
  461. package/esm/ai/src/workflow/retry.mjs.map +0 -1
  462. package/esm/ai/src/workflow/router.mjs +0 -56
  463. package/esm/ai/src/workflow/router.mjs.map +0 -1
  464. package/esm/ai/src/workflow/run-scoped-emitter.mjs +0 -32
  465. package/esm/ai/src/workflow/run-scoped-emitter.mjs.map +0 -1
  466. package/esm/ai/src/workflow/signature.mjs +0 -34
  467. package/esm/ai/src/workflow/signature.mjs.map +0 -1
  468. package/esm/ai/src/workflow/snapshot.mjs +0 -77
  469. package/esm/ai/src/workflow/snapshot.mjs.map +0 -1
  470. package/esm/ai/src/workflow/state.mjs +0 -37
  471. package/esm/ai/src/workflow/state.mjs.map +0 -1
  472. package/esm/ai/src/workflow/step-runner.mjs +0 -370
  473. package/esm/ai/src/workflow/step-runner.mjs.map +0 -1
  474. package/esm/ai/src/workflow/step.mjs +0 -37
  475. package/esm/ai/src/workflow/step.mjs.map +0 -1
  476. package/esm/ai/src/workflow/workflow.mjs +0 -122
  477. package/esm/ai/src/workflow/workflow.mjs.map +0 -1
  478. package/esm/ai-openai/src/embedder.mjs +0 -4
  479. package/esm/ai-openai/src/image.mjs +0 -5
  480. package/esm/ai-openai/src/index.mjs +0 -7
  481. package/esm/ai-openai/src/model.mjs +0 -5
  482. package/esm/ai-openai/src/sdk.mjs +0 -9
  483. package/esm/ai-openai/src/speech.mjs +0 -5
  484. package/esm/ai-openai/src/transcription.mjs +0 -6
  485. package/esm/ai-openai/src/utils/index.mjs +0 -5
  486. package/esm/ai-openai/src/utils/to-openai-messages.mjs +0 -3
  487. package/esm/ai-openai/src/utils/to-openai-tools.mjs +0 -3
  488. package/esm/ai-openai/src/utils/wrap-openai-error.mjs +0 -4
  489. package/esm/node_modules/langfuse/lib/index.mjs +0 -1827
  490. package/esm/node_modules/langfuse/lib/index.mjs.map +0 -1
  491. package/esm/node_modules/langfuse-core/lib/index.mjs +0 -1770
  492. package/esm/node_modules/langfuse-core/lib/index.mjs.map +0 -1
  493. package/esm/node_modules/mustache/mustache.mjs +0 -587
  494. package/esm/node_modules/mustache/mustache.mjs.map +0 -1
  495. package/esm/node_modules/openai/_vendor/partial-json-parser/parser.mjs +0 -180
  496. package/esm/node_modules/openai/_vendor/partial-json-parser/parser.mjs.map +0 -1
  497. package/esm/node_modules/openai/auth/workload-identity-auth.mjs +0 -80
  498. package/esm/node_modules/openai/auth/workload-identity-auth.mjs.map +0 -1
  499. package/esm/node_modules/openai/azure.mjs +0 -82
  500. package/esm/node_modules/openai/azure.mjs.map +0 -1
  501. package/esm/node_modules/openai/client.mjs +0 -638
  502. package/esm/node_modules/openai/client.mjs.map +0 -1
  503. package/esm/node_modules/openai/core/api-promise.mjs +0 -75
  504. package/esm/node_modules/openai/core/api-promise.mjs.map +0 -1
  505. package/esm/node_modules/openai/core/error.mjs +0 -110
  506. package/esm/node_modules/openai/core/error.mjs.map +0 -1
  507. package/esm/node_modules/openai/core/pagination.mjs +0 -160
  508. package/esm/node_modules/openai/core/pagination.mjs.map +0 -1
  509. package/esm/node_modules/openai/core/resource.mjs +0 -10
  510. package/esm/node_modules/openai/core/resource.mjs.map +0 -1
  511. package/esm/node_modules/openai/core/streaming.mjs +0 -238
  512. package/esm/node_modules/openai/core/streaming.mjs.map +0 -1
  513. package/esm/node_modules/openai/index.mjs +0 -8
  514. package/esm/node_modules/openai/internal/decoders/line.mjs +0 -91
  515. package/esm/node_modules/openai/internal/decoders/line.mjs.map +0 -1
  516. package/esm/node_modules/openai/internal/detect-platform.mjs +0 -123
  517. package/esm/node_modules/openai/internal/detect-platform.mjs.map +0 -1
  518. package/esm/node_modules/openai/internal/errors.mjs +0 -26
  519. package/esm/node_modules/openai/internal/errors.mjs.map +0 -1
  520. package/esm/node_modules/openai/internal/headers.mjs +0 -65
  521. package/esm/node_modules/openai/internal/headers.mjs.map +0 -1
  522. package/esm/node_modules/openai/internal/parse.mjs +0 -41
  523. package/esm/node_modules/openai/internal/parse.mjs.map +0 -1
  524. package/esm/node_modules/openai/internal/qs/formats.mjs +0 -12
  525. package/esm/node_modules/openai/internal/qs/formats.mjs.map +0 -1
  526. package/esm/node_modules/openai/internal/qs/stringify.mjs +0 -179
  527. package/esm/node_modules/openai/internal/qs/stringify.mjs.map +0 -1
  528. package/esm/node_modules/openai/internal/qs/utils.mjs +0 -65
  529. package/esm/node_modules/openai/internal/qs/utils.mjs.map +0 -1
  530. package/esm/node_modules/openai/internal/request-options.mjs +0 -11
  531. package/esm/node_modules/openai/internal/request-options.mjs.map +0 -1
  532. package/esm/node_modules/openai/internal/shims.mjs +0 -77
  533. package/esm/node_modules/openai/internal/shims.mjs.map +0 -1
  534. package/esm/node_modules/openai/internal/to-file.mjs +0 -63
  535. package/esm/node_modules/openai/internal/to-file.mjs.map +0 -1
  536. package/esm/node_modules/openai/internal/tslib.mjs +0 -16
  537. package/esm/node_modules/openai/internal/tslib.mjs.map +0 -1
  538. package/esm/node_modules/openai/internal/uploads.mjs +0 -94
  539. package/esm/node_modules/openai/internal/uploads.mjs.map +0 -1
  540. package/esm/node_modules/openai/internal/utils/base64.mjs +0 -22
  541. package/esm/node_modules/openai/internal/utils/base64.mjs.map +0 -1
  542. package/esm/node_modules/openai/internal/utils/bytes.mjs +0 -26
  543. package/esm/node_modules/openai/internal/utils/bytes.mjs.map +0 -1
  544. package/esm/node_modules/openai/internal/utils/env.mjs +0 -16
  545. package/esm/node_modules/openai/internal/utils/env.mjs.map +0 -1
  546. package/esm/node_modules/openai/internal/utils/log.mjs +0 -58
  547. package/esm/node_modules/openai/internal/utils/log.mjs.map +0 -1
  548. package/esm/node_modules/openai/internal/utils/path.mjs +0 -62
  549. package/esm/node_modules/openai/internal/utils/path.mjs.map +0 -1
  550. package/esm/node_modules/openai/internal/utils/query.mjs +0 -10
  551. package/esm/node_modules/openai/internal/utils/query.mjs.map +0 -1
  552. package/esm/node_modules/openai/internal/utils/sleep.mjs +0 -6
  553. package/esm/node_modules/openai/internal/utils/sleep.mjs.map +0 -1
  554. package/esm/node_modules/openai/internal/utils/uuid.mjs +0 -18
  555. package/esm/node_modules/openai/internal/utils/uuid.mjs.map +0 -1
  556. package/esm/node_modules/openai/internal/utils/values.mjs +0 -41
  557. package/esm/node_modules/openai/internal/utils/values.mjs.map +0 -1
  558. package/esm/node_modules/openai/lib/AbstractChatCompletionRunner.mjs +0 -247
  559. package/esm/node_modules/openai/lib/AbstractChatCompletionRunner.mjs.map +0 -1
  560. package/esm/node_modules/openai/lib/AssistantStream.mjs +0 -472
  561. package/esm/node_modules/openai/lib/AssistantStream.mjs.map +0 -1
  562. package/esm/node_modules/openai/lib/ChatCompletionRunner.mjs +0 -26
  563. package/esm/node_modules/openai/lib/ChatCompletionRunner.mjs.map +0 -1
  564. package/esm/node_modules/openai/lib/ChatCompletionStream.mjs +0 -423
  565. package/esm/node_modules/openai/lib/ChatCompletionStream.mjs.map +0 -1
  566. package/esm/node_modules/openai/lib/ChatCompletionStreamingRunner.mjs +0 -26
  567. package/esm/node_modules/openai/lib/ChatCompletionStreamingRunner.mjs.map +0 -1
  568. package/esm/node_modules/openai/lib/EventStream.mjs +0 -163
  569. package/esm/node_modules/openai/lib/EventStream.mjs.map +0 -1
  570. package/esm/node_modules/openai/lib/ResponsesParser.mjs +0 -94
  571. package/esm/node_modules/openai/lib/ResponsesParser.mjs.map +0 -1
  572. package/esm/node_modules/openai/lib/RunnableFunction.mjs +0 -8
  573. package/esm/node_modules/openai/lib/RunnableFunction.mjs.map +0 -1
  574. package/esm/node_modules/openai/lib/Util.mjs +0 -19
  575. package/esm/node_modules/openai/lib/Util.mjs.map +0 -1
  576. package/esm/node_modules/openai/lib/chatCompletionUtils.mjs +0 -11
  577. package/esm/node_modules/openai/lib/chatCompletionUtils.mjs.map +0 -1
  578. package/esm/node_modules/openai/lib/parser.mjs +0 -88
  579. package/esm/node_modules/openai/lib/parser.mjs.map +0 -1
  580. package/esm/node_modules/openai/lib/responses/ResponseStream.mjs +0 -231
  581. package/esm/node_modules/openai/lib/responses/ResponseStream.mjs.map +0 -1
  582. package/esm/node_modules/openai/resources/admin/admin.mjs +0 -15
  583. package/esm/node_modules/openai/resources/admin/admin.mjs.map +0 -1
  584. package/esm/node_modules/openai/resources/admin/organization/admin-api-keys.mjs +0 -81
  585. package/esm/node_modules/openai/resources/admin/organization/admin-api-keys.mjs.map +0 -1
  586. package/esm/node_modules/openai/resources/admin/organization/audit-logs.mjs +0 -31
  587. package/esm/node_modules/openai/resources/admin/organization/audit-logs.mjs.map +0 -1
  588. package/esm/node_modules/openai/resources/admin/organization/certificates.mjs +0 -153
  589. package/esm/node_modules/openai/resources/admin/organization/certificates.mjs.map +0 -1
  590. package/esm/node_modules/openai/resources/admin/organization/data-retention.mjs +0 -42
  591. package/esm/node_modules/openai/resources/admin/organization/data-retention.mjs.map +0 -1
  592. package/esm/node_modules/openai/resources/admin/organization/groups/groups.mjs +0 -106
  593. package/esm/node_modules/openai/resources/admin/organization/groups/groups.mjs.map +0 -1
  594. package/esm/node_modules/openai/resources/admin/organization/groups/roles.mjs +0 -88
  595. package/esm/node_modules/openai/resources/admin/organization/groups/roles.mjs.map +0 -1
  596. package/esm/node_modules/openai/resources/admin/organization/groups/users.mjs +0 -88
  597. package/esm/node_modules/openai/resources/admin/organization/groups/users.mjs.map +0 -1
  598. package/esm/node_modules/openai/resources/admin/organization/invites.mjs +0 -83
  599. package/esm/node_modules/openai/resources/admin/organization/invites.mjs.map +0 -1
  600. package/esm/node_modules/openai/resources/admin/organization/organization.mjs +0 -45
  601. package/esm/node_modules/openai/resources/admin/organization/organization.mjs.map +0 -1
  602. package/esm/node_modules/openai/resources/admin/organization/projects/api-keys.mjs +0 -72
  603. package/esm/node_modules/openai/resources/admin/organization/projects/api-keys.mjs.map +0 -1
  604. package/esm/node_modules/openai/resources/admin/organization/projects/certificates.mjs +0 -78
  605. package/esm/node_modules/openai/resources/admin/organization/projects/certificates.mjs.map +0 -1
  606. package/esm/node_modules/openai/resources/admin/organization/projects/data-retention.mjs +0 -46
  607. package/esm/node_modules/openai/resources/admin/organization/projects/data-retention.mjs.map +0 -1
  608. package/esm/node_modules/openai/resources/admin/organization/projects/groups/groups.mjs +0 -95
  609. package/esm/node_modules/openai/resources/admin/organization/projects/groups/groups.mjs.map +0 -1
  610. package/esm/node_modules/openai/resources/admin/organization/projects/groups/roles.mjs +0 -91
  611. package/esm/node_modules/openai/resources/admin/organization/projects/groups/roles.mjs.map +0 -1
  612. package/esm/node_modules/openai/resources/admin/organization/projects/hosted-tool-permissions.mjs +0 -45
  613. package/esm/node_modules/openai/resources/admin/organization/projects/hosted-tool-permissions.mjs.map +0 -1
  614. package/esm/node_modules/openai/resources/admin/organization/projects/model-permissions.mjs +0 -63
  615. package/esm/node_modules/openai/resources/admin/organization/projects/model-permissions.mjs.map +0 -1
  616. package/esm/node_modules/openai/resources/admin/organization/projects/projects.mjs +0 -137
  617. package/esm/node_modules/openai/resources/admin/organization/projects/projects.mjs.map +0 -1
  618. package/esm/node_modules/openai/resources/admin/organization/projects/rate-limits.mjs +0 -51
  619. package/esm/node_modules/openai/resources/admin/organization/projects/rate-limits.mjs.map +0 -1
  620. package/esm/node_modules/openai/resources/admin/organization/projects/roles.mjs +0 -108
  621. package/esm/node_modules/openai/resources/admin/organization/projects/roles.mjs.map +0 -1
  622. package/esm/node_modules/openai/resources/admin/organization/projects/service-accounts.mjs +0 -112
  623. package/esm/node_modules/openai/resources/admin/organization/projects/service-accounts.mjs.map +0 -1
  624. package/esm/node_modules/openai/resources/admin/organization/projects/spend-alerts.mjs +0 -106
  625. package/esm/node_modules/openai/resources/admin/organization/projects/spend-alerts.mjs.map +0 -1
  626. package/esm/node_modules/openai/resources/admin/organization/projects/users/roles.mjs +0 -91
  627. package/esm/node_modules/openai/resources/admin/organization/projects/users/roles.mjs.map +0 -1
  628. package/esm/node_modules/openai/resources/admin/organization/projects/users/users.mjs +0 -118
  629. package/esm/node_modules/openai/resources/admin/organization/projects/users/users.mjs.map +0 -1
  630. package/esm/node_modules/openai/resources/admin/organization/roles.mjs +0 -96
  631. package/esm/node_modules/openai/resources/admin/organization/roles.mjs.map +0 -1
  632. package/esm/node_modules/openai/resources/admin/organization/spend-alerts.mjs +0 -97
  633. package/esm/node_modules/openai/resources/admin/organization/spend-alerts.mjs.map +0 -1
  634. package/esm/node_modules/openai/resources/admin/organization/usage.mjs +0 -207
  635. package/esm/node_modules/openai/resources/admin/organization/usage.mjs.map +0 -1
  636. package/esm/node_modules/openai/resources/admin/organization/users/roles.mjs +0 -88
  637. package/esm/node_modules/openai/resources/admin/organization/users/roles.mjs.map +0 -1
  638. package/esm/node_modules/openai/resources/admin/organization/users/users.mjs +0 -82
  639. package/esm/node_modules/openai/resources/admin/organization/users/users.mjs.map +0 -1
  640. package/esm/node_modules/openai/resources/audio/audio.mjs +0 -21
  641. package/esm/node_modules/openai/resources/audio/audio.mjs.map +0 -1
  642. package/esm/node_modules/openai/resources/audio/speech.mjs +0 -39
  643. package/esm/node_modules/openai/resources/audio/speech.mjs.map +0 -1
  644. package/esm/node_modules/openai/resources/audio/transcriptions.mjs +0 -22
  645. package/esm/node_modules/openai/resources/audio/transcriptions.mjs.map +0 -1
  646. package/esm/node_modules/openai/resources/audio/translations.mjs +0 -21
  647. package/esm/node_modules/openai/resources/audio/translations.mjs.map +0 -1
  648. package/esm/node_modules/openai/resources/batches.mjs +0 -54
  649. package/esm/node_modules/openai/resources/batches.mjs.map +0 -1
  650. package/esm/node_modules/openai/resources/beta/assistants.mjs +0 -78
  651. package/esm/node_modules/openai/resources/beta/assistants.mjs.map +0 -1
  652. package/esm/node_modules/openai/resources/beta/beta.mjs +0 -24
  653. package/esm/node_modules/openai/resources/beta/beta.mjs.map +0 -1
  654. package/esm/node_modules/openai/resources/beta/chatkit/chatkit.mjs +0 -18
  655. package/esm/node_modules/openai/resources/beta/chatkit/chatkit.mjs.map +0 -1
  656. package/esm/node_modules/openai/resources/beta/chatkit/sessions.mjs +0 -49
  657. package/esm/node_modules/openai/resources/beta/chatkit/sessions.mjs.map +0 -1
  658. package/esm/node_modules/openai/resources/beta/chatkit/threads.mjs +0 -85
  659. package/esm/node_modules/openai/resources/beta/chatkit/threads.mjs.map +0 -1
  660. package/esm/node_modules/openai/resources/beta/realtime/realtime.mjs +0 -21
  661. package/esm/node_modules/openai/resources/beta/realtime/realtime.mjs.map +0 -1
  662. package/esm/node_modules/openai/resources/beta/realtime/sessions.mjs +0 -33
  663. package/esm/node_modules/openai/resources/beta/realtime/sessions.mjs.map +0 -1
  664. package/esm/node_modules/openai/resources/beta/realtime/transcription-sessions.mjs +0 -33
  665. package/esm/node_modules/openai/resources/beta/realtime/transcription-sessions.mjs.map +0 -1
  666. package/esm/node_modules/openai/resources/beta/threads/messages.mjs +0 -83
  667. package/esm/node_modules/openai/resources/beta/threads/messages.mjs.map +0 -1
  668. package/esm/node_modules/openai/resources/beta/threads/runs/runs.mjs +0 -183
  669. package/esm/node_modules/openai/resources/beta/threads/runs/runs.mjs.map +0 -1
  670. package/esm/node_modules/openai/resources/beta/threads/runs/steps.mjs +0 -45
  671. package/esm/node_modules/openai/resources/beta/threads/runs/steps.mjs.map +0 -1
  672. package/esm/node_modules/openai/resources/beta/threads/threads.mjs +0 -101
  673. package/esm/node_modules/openai/resources/beta/threads/threads.mjs.map +0 -1
  674. package/esm/node_modules/openai/resources/chat/chat.mjs +0 -15
  675. package/esm/node_modules/openai/resources/chat/chat.mjs.map +0 -1
  676. package/esm/node_modules/openai/resources/chat/completions/completions.mjs +0 -123
  677. package/esm/node_modules/openai/resources/chat/completions/completions.mjs.map +0 -1
  678. package/esm/node_modules/openai/resources/chat/completions/index.mjs +0 -7
  679. package/esm/node_modules/openai/resources/chat/completions/messages.mjs +0 -35
  680. package/esm/node_modules/openai/resources/chat/completions/messages.mjs.map +0 -1
  681. package/esm/node_modules/openai/resources/chat/index.mjs +0 -5
  682. package/esm/node_modules/openai/resources/completions.mjs +0 -20
  683. package/esm/node_modules/openai/resources/completions.mjs.map +0 -1
  684. package/esm/node_modules/openai/resources/containers/containers.mjs +0 -57
  685. package/esm/node_modules/openai/resources/containers/containers.mjs.map +0 -1
  686. package/esm/node_modules/openai/resources/containers/files/content.mjs +0 -23
  687. package/esm/node_modules/openai/resources/containers/files/content.mjs.map +0 -1
  688. package/esm/node_modules/openai/resources/containers/files/files.mjs +0 -63
  689. package/esm/node_modules/openai/resources/containers/files/files.mjs.map +0 -1
  690. package/esm/node_modules/openai/resources/conversations/conversations.mjs +0 -57
  691. package/esm/node_modules/openai/resources/conversations/conversations.mjs.map +0 -1
  692. package/esm/node_modules/openai/resources/conversations/items.mjs +0 -57
  693. package/esm/node_modules/openai/resources/conversations/items.mjs.map +0 -1
  694. package/esm/node_modules/openai/resources/embeddings.mjs +0 -48
  695. package/esm/node_modules/openai/resources/embeddings.mjs.map +0 -1
  696. package/esm/node_modules/openai/resources/evals/evals.mjs +0 -73
  697. package/esm/node_modules/openai/resources/evals/evals.mjs.map +0 -1
  698. package/esm/node_modules/openai/resources/evals/runs/output-items.mjs +0 -35
  699. package/esm/node_modules/openai/resources/evals/runs/output-items.mjs.map +0 -1
  700. package/esm/node_modules/openai/resources/evals/runs/runs.mjs +0 -72
  701. package/esm/node_modules/openai/resources/evals/runs/runs.mjs.map +0 -1
  702. package/esm/node_modules/openai/resources/files.mjs +0 -111
  703. package/esm/node_modules/openai/resources/files.mjs.map +0 -1
  704. package/esm/node_modules/openai/resources/fine-tuning/alpha/alpha.mjs +0 -15
  705. package/esm/node_modules/openai/resources/fine-tuning/alpha/alpha.mjs.map +0 -1
  706. package/esm/node_modules/openai/resources/fine-tuning/alpha/graders.mjs +0 -60
  707. package/esm/node_modules/openai/resources/fine-tuning/alpha/graders.mjs.map +0 -1
  708. package/esm/node_modules/openai/resources/fine-tuning/checkpoints/checkpoints.mjs +0 -15
  709. package/esm/node_modules/openai/resources/fine-tuning/checkpoints/checkpoints.mjs.map +0 -1
  710. package/esm/node_modules/openai/resources/fine-tuning/checkpoints/permissions.mjs +0 -102
  711. package/esm/node_modules/openai/resources/fine-tuning/checkpoints/permissions.mjs.map +0 -1
  712. package/esm/node_modules/openai/resources/fine-tuning/fine-tuning.mjs +0 -24
  713. package/esm/node_modules/openai/resources/fine-tuning/fine-tuning.mjs.map +0 -1
  714. package/esm/node_modules/openai/resources/fine-tuning/jobs/checkpoints.mjs +0 -34
  715. package/esm/node_modules/openai/resources/fine-tuning/jobs/checkpoints.mjs.map +0 -1
  716. package/esm/node_modules/openai/resources/fine-tuning/jobs/jobs.mjs +0 -148
  717. package/esm/node_modules/openai/resources/fine-tuning/jobs/jobs.mjs.map +0 -1
  718. package/esm/node_modules/openai/resources/fine-tuning/methods.mjs +0 -8
  719. package/esm/node_modules/openai/resources/fine-tuning/methods.mjs.map +0 -1
  720. package/esm/node_modules/openai/resources/graders/grader-models.mjs +0 -8
  721. package/esm/node_modules/openai/resources/graders/grader-models.mjs.map +0 -1
  722. package/esm/node_modules/openai/resources/graders/graders.mjs +0 -15
  723. package/esm/node_modules/openai/resources/graders/graders.mjs.map +0 -1
  724. package/esm/node_modules/openai/resources/images.mjs +0 -46
  725. package/esm/node_modules/openai/resources/images.mjs.map +0 -1
  726. package/esm/node_modules/openai/resources/index.mjs +0 -27
  727. package/esm/node_modules/openai/resources/models.mjs +0 -44
  728. package/esm/node_modules/openai/resources/models.mjs.map +0 -1
  729. package/esm/node_modules/openai/resources/moderations.mjs +0 -23
  730. package/esm/node_modules/openai/resources/moderations.mjs.map +0 -1
  731. package/esm/node_modules/openai/resources/realtime/calls.mjs +0 -79
  732. package/esm/node_modules/openai/resources/realtime/calls.mjs.map +0 -1
  733. package/esm/node_modules/openai/resources/realtime/client-secrets.mjs +0 -39
  734. package/esm/node_modules/openai/resources/realtime/client-secrets.mjs.map +0 -1
  735. package/esm/node_modules/openai/resources/realtime/realtime.mjs +0 -18
  736. package/esm/node_modules/openai/resources/realtime/realtime.mjs.map +0 -1
  737. package/esm/node_modules/openai/resources/responses/input-items.mjs +0 -31
  738. package/esm/node_modules/openai/resources/responses/input-items.mjs.map +0 -1
  739. package/esm/node_modules/openai/resources/responses/input-tokens.mjs +0 -27
  740. package/esm/node_modules/openai/resources/responses/input-tokens.mjs.map +0 -1
  741. package/esm/node_modules/openai/resources/responses/responses.mjs +0 -110
  742. package/esm/node_modules/openai/resources/responses/responses.mjs.map +0 -1
  743. package/esm/node_modules/openai/resources/skills/content.mjs +0 -22
  744. package/esm/node_modules/openai/resources/skills/content.mjs.map +0 -1
  745. package/esm/node_modules/openai/resources/skills/skills.mjs +0 -69
  746. package/esm/node_modules/openai/resources/skills/skills.mjs.map +0 -1
  747. package/esm/node_modules/openai/resources/skills/versions/content.mjs +0 -23
  748. package/esm/node_modules/openai/resources/skills/versions/content.mjs.map +0 -1
  749. package/esm/node_modules/openai/resources/skills/versions/versions.mjs +0 -58
  750. package/esm/node_modules/openai/resources/skills/versions/versions.mjs.map +0 -1
  751. package/esm/node_modules/openai/resources/uploads/parts.mjs +0 -34
  752. package/esm/node_modules/openai/resources/uploads/parts.mjs.map +0 -1
  753. package/esm/node_modules/openai/resources/uploads/uploads.mjs +0 -84
  754. package/esm/node_modules/openai/resources/uploads/uploads.mjs.map +0 -1
  755. package/esm/node_modules/openai/resources/vector-stores/file-batches.mjs +0 -126
  756. package/esm/node_modules/openai/resources/vector-stores/file-batches.mjs.map +0 -1
  757. package/esm/node_modules/openai/resources/vector-stores/files.mjs +0 -147
  758. package/esm/node_modules/openai/resources/vector-stores/files.mjs.map +0 -1
  759. package/esm/node_modules/openai/resources/vector-stores/vector-stores.mjs +0 -87
  760. package/esm/node_modules/openai/resources/vector-stores/vector-stores.mjs.map +0 -1
  761. package/esm/node_modules/openai/resources/videos.mjs +0 -115
  762. package/esm/node_modules/openai/resources/videos.mjs.map +0 -1
  763. package/esm/node_modules/openai/resources/webhooks/index.mjs +0 -3
  764. package/esm/node_modules/openai/resources/webhooks/webhooks.mjs +0 -69
  765. package/esm/node_modules/openai/resources/webhooks/webhooks.mjs.map +0 -1
  766. package/esm/node_modules/openai/resources/webhooks.mjs +0 -4
  767. package/esm/node_modules/openai/streaming.mjs +0 -3
  768. package/esm/node_modules/openai/version.mjs +0 -6
  769. package/esm/node_modules/openai/version.mjs.map +0 -1
@@ -1,1921 +0,0 @@
1
- import { AIError } from "../errors/ai-error.mjs";
2
- import { SupervisorFailedError } from "../errors/supervisor-failed-error.mjs";
3
- import { MaxIterationsError } from "../errors/max-iterations-error.mjs";
4
- import { SchemaValidationError } from "../errors/schema-validation-error.mjs";
5
- import { SupervisorCancelledError } from "../errors/supervisor-cancelled-error.mjs";
6
- import "../errors/index.mjs";
7
- import { mergeUsage } from "../utils/compute-cost.mjs";
8
- import { withRunFrame, withoutRunFrame } from "../utils/run-context.mjs";
9
- import { stampReportLineage } from "../utils/stamp-report-lineage.mjs";
10
- import "../utils/index.mjs";
11
- import { runPipeline } from "../middleware/pipeline.mjs";
12
- import { END } from "../contracts/end.type.mjs";
13
- import { isAgentResult, isWorkflowResult } from "./entries.mjs";
14
- import { createCancelledError } from "./cancellation.mjs";
15
- import { decide } from "./decide.mjs";
16
- import { persistSupervisorSnapshot } from "./snapshot.mjs";
17
- import { log } from "@warlock.js/logger";
18
-
19
- //#region ../@warlock.js/ai/src/supervisor/execution.ts
20
- const DEFAULT_MAX_ITERATIONS = 10;
21
- const LOG_MODULE_BASE = "ai.supervisor";
22
- /**
23
- * Per-call driver that owns the full lifecycle of one supervisor run.
24
- *
25
- * **Role.** Short-lived state container and phase orchestrator —
26
- * mirrors `agent/Execution` and `workflow/runWorkflow`, one level up.
27
- *
28
- * **Responsibility.**
29
- * - Owns: the iteration loop, per-iteration dispatch (single or
30
- * fan-out), evaluate scheduling, usage aggregation across router +
31
- * every branch + evaluate, snapshot collection, event emission
32
- * through all three tiers, KV-store checkpointing, final result
33
- * assembly (state validation against the output schema → typed data).
34
- * - Does NOT own: how child agents produce responses (delegated via
35
- * `agent.execute` / `workflow.execute`), the routing decision
36
- * itself (delegated to `decide.ts`), snapshot persistence mechanics
37
- * (delegated to `snapshot.ts`), the stream queue plumbing
38
- * (delegated to `supervisor-stream.ts`).
39
- *
40
- * `execute()` never throws — every unexpected failure funnels into
41
- * `this.error` and is returned on `result.error` with an appropriate
42
- * `SupervisorFailedError` / `MaxIterationsError` / `SupervisorRoutingError`
43
- * / `SupervisorCancelledError`.
44
- *
45
- * @example
46
- * // Inside supervisor.execute() — never constructed by user code directly:
47
- * return new SupervisorExecution(params).run();
48
- */
49
- var SupervisorExecution = class {
50
- constructor(params) {
51
- this.logger = log;
52
- this.middlewareState = /* @__PURE__ */ new Map();
53
- this.snapshots = [];
54
- this.childReports = [];
55
- this.usage = {
56
- input: 0,
57
- output: 0,
58
- total: 0
59
- };
60
- this.startPerf = performance.now();
61
- this.iteration = 0;
62
- this.terminatedBy = "error";
63
- this.status = "failed";
64
- this.lastDispatchIntents = [];
65
- this.state = {};
66
- this.currentArtifacts = {};
67
- this.capturedIterationArtifacts = Object.freeze({});
68
- this.classifierHalted = false;
69
- this.config = params.config;
70
- this.entries = params.entries;
71
- this.signature = params.signature;
72
- this.emitter = params.emitter;
73
- this.input = params.input;
74
- this.runId = params.runId;
75
- this.options = params.options;
76
- this.streamController = params.streamController;
77
- this.resumeFrom = params.resumeFrom;
78
- this.maxIterations = params.config.maxIterations ?? DEFAULT_MAX_ITERATIONS;
79
- this.logModule = `${LOG_MODULE_BASE}.${params.config.name}`;
80
- this.middleware = params.config.middleware ?? [];
81
- this.context = Object.freeze({ ...params.options?.context ?? {} });
82
- this.history = Object.freeze([...params.options?.history ?? params.config.history ?? []]);
83
- if (typeof params.config.goal === "string") this.goal = params.config.goal;
84
- else if (params.config.goal) this.goal = params.config.goal.resolve();
85
- else this.goal = void 0;
86
- if (params.resumeFrom) {
87
- this.snapshots.push(...params.resumeFrom.snapshots);
88
- this.iteration = params.resumeFrom.iteration + 1;
89
- this.startedAtIso = params.resumeFrom.startedAt;
90
- const lastSnapshot = params.resumeFrom.snapshots[params.resumeFrom.snapshots.length - 1];
91
- this.state = { ...lastSnapshot?.state ?? params.config.state ?? {} };
92
- } else {
93
- this.startedAtIso = (/* @__PURE__ */ new Date()).toISOString();
94
- this.state = { ...params.config.state ?? {} };
95
- }
96
- }
97
- /**
98
- * Resolve the history slice forwarded to a child execution (router /
99
- * dispatched agent / ack). Precedence:
100
- *
101
- * 1. Per-entry `history` callback — full override; whatever it
102
- * returns goes through (after defensive copy).
103
- * 2. `SupervisorConfig.historyWindow.<role>` — last-N slice of the
104
- * caller-supplied history.
105
- * 3. Default — full history for `router`/`agents`, empty for `ack`
106
- * (receptionists rarely benefit from scroll-back).
107
- *
108
- * Always returns a fresh `Message[]` (the agent layer
109
- * mutates by reference internally, e.g. via `messages.push(...)`).
110
- */
111
- resolveHistoryFor(role, routeContext, entrySlicer) {
112
- if (entrySlicer) {
113
- const sliced = entrySlicer(routeContext);
114
- return sliced ? [...sliced] : [];
115
- }
116
- const window = this.config.historyWindow?.[role];
117
- if (role === "ack") {
118
- if (window === void 0 || window <= 0) return [];
119
- return this.history.slice(-window);
120
- }
121
- if (window === void 0 || window < 0) return [...this.history];
122
- if (window === 0) return [];
123
- return this.history.slice(-window);
124
- }
125
- /**
126
- * Apply only the global `historyWindow.agents` slice — used by the
127
- * recursive `ctx.intents.X.execute()` re-entry path where no
128
- * `RouteContext` is available to feed the per-entry slicer.
129
- */
130
- applyAgentsWindow() {
131
- const window = this.config.historyWindow?.agents;
132
- if (window === void 0 || window < 0) return [...this.history];
133
- if (window === 0) return [];
134
- return this.history.slice(-window);
135
- }
136
- /**
137
- * Entry point. Wraps the core run (`runCore`) in the
138
- * `supervisor`-level middleware pipeline, then emits the terminal
139
- * `supervisor.cancelled` / `supervisor.error` / `supervisor.completed`
140
- * events and closes the stream (if any) with the post-pipeline result
141
- * — so a middleware that short-circuits or transforms the final
142
- * result still produces a well-formed public outcome. Returns the
143
- * uniform `{ data, report, usage, error }` shape. Never throws.
144
- */
145
- async run() {
146
- const context = this.buildSupervisorContext();
147
- let result;
148
- try {
149
- result = await runPipeline(this.middleware, "supervisor", context, () => this.runCore(), this.logger);
150
- } catch (thrown) {
151
- this.error = toAIError(thrown);
152
- this.status = this.error instanceof SupervisorCancelledError ? "cancelled" : "failed";
153
- this.terminatedBy = this.error instanceof SupervisorCancelledError ? "cancelled" : "error";
154
- if (this.error instanceof SupervisorCancelledError) this.cancelledAtIso = this.error.cancelledAt;
155
- if (this.error instanceof MaxIterationsError) {
156
- this.status = "max-iterations";
157
- this.terminatedBy = "max-iterations";
158
- }
159
- result = await this.finalize();
160
- }
161
- if (result.error) if (this.status === "cancelled") this.emit("supervisor.cancelled", {
162
- cancelledAt: this.cancelledAtIso ?? (/* @__PURE__ */ new Date()).toISOString(),
163
- reason: result.error.reason
164
- });
165
- else this.emit("supervisor.error", { error: result.error });
166
- this.emit("supervisor.completed", { result });
167
- this.streamController?.end(result);
168
- this.logger.info(this.logModule, "completed", "supervisor completed", {
169
- runId: this.runId,
170
- status: this.status,
171
- iterations: this.snapshots.length,
172
- duration: performance.now() - this.startPerf
173
- });
174
- return result;
175
- }
176
- /**
177
- * Build the `supervisor`-level middleware context — the stable
178
- * identity of this run plus the per-run shared-state bag every hook
179
- * sees. Constructed once per run, before the pipeline `before` hooks
180
- * fire. Mirrors the agent's `buildExecuteContext`, one level up.
181
- */
182
- buildSupervisorContext() {
183
- return {
184
- supervisor: {
185
- name: this.config.name,
186
- signature: this.signature
187
- },
188
- input: this.input,
189
- options: this.options,
190
- state: this.middlewareState,
191
- signal: this.options?.signal
192
- };
193
- }
194
- /**
195
- * Inner body wrapped by the `supervisor`-level pipeline. Emits the
196
- * `supervisor.starting` event, drives the iteration loop, absorbs
197
- * every iteration-loop failure into `this.error` (so the run never
198
- * throws from here), and returns the assembled `SupervisorResult`.
199
- * `supervisor`-level `after` hooks receive this result, with `error`
200
- * populated when the loop failed; `before` hooks can short-circuit
201
- * before this ever runs.
202
- */
203
- async runCore() {
204
- this.emit("supervisor.starting", {
205
- supervisorName: this.config.name,
206
- input: this.input
207
- });
208
- this.logger.info(this.logModule, "starting", "supervisor starting", {
209
- runId: this.runId,
210
- maxIterations: this.maxIterations
211
- });
212
- try {
213
- await this.runIterationLoop();
214
- } catch (thrown) {
215
- this.error = toAIError(thrown);
216
- this.status = this.error instanceof SupervisorCancelledError ? "cancelled" : "failed";
217
- this.terminatedBy = this.error instanceof SupervisorCancelledError ? "cancelled" : "error";
218
- if (this.error instanceof SupervisorCancelledError) this.cancelledAtIso = this.error.cancelledAt;
219
- if (this.error instanceof MaxIterationsError) {
220
- this.status = "max-iterations";
221
- this.terminatedBy = "max-iterations";
222
- }
223
- }
224
- return this.finalize();
225
- }
226
- /**
227
- * Drive the iteration loop until a terminal condition fires:
228
- * `END` / `satisfied:true` / `maxIterations` / signal abort /
229
- * routing error. Between-iteration cancellation is guaranteed —
230
- * the signal is checked before every iteration starts.
231
- */
232
- async runIterationLoop() {
233
- while (this.iteration < this.maxIterations) {
234
- this.throwIfCancelled();
235
- if (!await this.runIteration()) return;
236
- this.iteration += 1;
237
- }
238
- throw new MaxIterationsError(`supervisor "${this.config.name}" exceeded maxIterations=${this.maxIterations}`, { maxIterations: this.maxIterations });
239
- }
240
- /**
241
- * Run one iteration end-to-end: decide → dispatch → evaluate →
242
- * snapshot. Returns `true` when the loop should continue to the
243
- * next iteration, `false` when this iteration terminated the run
244
- * (success or satisfied-verdict). Failures throw — the loop's
245
- * outer catch converts them into typed errors on the result.
246
- */
247
- async runIteration() {
248
- const iterationStartedAt = /* @__PURE__ */ new Date();
249
- const iterationStart = performance.now();
250
- const iterationUsage = {
251
- input: 0,
252
- output: 0,
253
- total: 0
254
- };
255
- this.capturedIterationArtifacts = Object.freeze({});
256
- this.emit("supervisor.iteration.starting", { iteration: this.iteration });
257
- const ackPromise = this.iteration === 0 && !this.resumeFrom && this.config.ack ? this.runAck() : void 0;
258
- if (this.iteration === 0 && !this.resumeFrom && this.config.classifier) {
259
- await this.runClassifier();
260
- if (this.classifierHalted) {
261
- await this.settleAck(ackPromise, iterationUsage);
262
- this.terminatedBy = "classifier";
263
- this.status = "completed";
264
- await this.recordTerminalDecisionSnapshot({
265
- kind: "end",
266
- source: "classifier",
267
- raw: END,
268
- durationMs: 0
269
- }, iterationStartedAt, iterationStart, iterationUsage);
270
- return false;
271
- }
272
- }
273
- const decision = await this.decideDispatch();
274
- this.aggregateUsage(iterationUsage, decision.usage);
275
- if (decision.kind === "end") {
276
- await this.settleAck(ackPromise, iterationUsage);
277
- this.terminatedBy = decision.source === "route" ? "route" : "router";
278
- this.status = "completed";
279
- await this.recordTerminalDecisionSnapshot(decision, iterationStartedAt, iterationStart, iterationUsage);
280
- return false;
281
- }
282
- const branchSnapshots = await this.dispatchBranches(decision);
283
- for (const snapshot of branchSnapshots) this.aggregateUsage(iterationUsage, snapshot.usage);
284
- await this.settleAck(ackPromise, iterationUsage);
285
- this.mergeBranchesIntoState(decision.intents, branchSnapshots);
286
- await this.mergeArtifactsIntoState();
287
- this.lastDispatchIntents = decision.intents;
288
- const evaluateVerdict = await this.runEvaluate(branchSnapshots);
289
- if (evaluateVerdict !== void 0 && evaluateVerdict !== null) this.emit("supervisor.evaluate.verdict", {
290
- iteration: this.iteration,
291
- verdict: evaluateVerdict
292
- });
293
- const iterationEndedAt = /* @__PURE__ */ new Date();
294
- const duration = performance.now() - iterationStart;
295
- const snapshot = Object.freeze({
296
- iteration: this.iteration,
297
- result: indexByIntent(branchSnapshots),
298
- decision: {
299
- source: decision.source,
300
- next: decision.raw,
301
- reasoning: decision.reasoning,
302
- durationMs: decision.durationMs
303
- },
304
- evaluateVerdict,
305
- state: { ...this.state },
306
- artifacts: this.capturedIterationArtifacts,
307
- startedAt: iterationStartedAt.toISOString(),
308
- endedAt: iterationEndedAt.toISOString(),
309
- duration,
310
- usage: iterationUsage
311
- });
312
- this.snapshots.push(snapshot);
313
- this.emit("supervisor.iteration.completed", {
314
- iteration: this.iteration,
315
- snapshot
316
- });
317
- await this.checkpoint("running");
318
- if (evaluateVerdict?.satisfied) {
319
- this.terminatedBy = "evaluate";
320
- this.status = "completed";
321
- return false;
322
- }
323
- this.carriedFeedback = evaluateVerdict;
324
- if (!(evaluateVerdict?.reassignTo !== void 0 && normalizeReassign(evaluateVerdict.reassignTo).length > 0)) {
325
- const collected = this.collectIntentNext(decision.intents, branchSnapshots);
326
- if (collected?.kind === "end") {
327
- this.terminatedBy = "route";
328
- this.status = "completed";
329
- this.carriedNextDispatch = void 0;
330
- return false;
331
- }
332
- if (collected?.kind === "dispatch") this.carriedNextDispatch = { intents: collected.intents };
333
- }
334
- if (this.iteration === 0 && this.config.classifier && !this.config.router && !this.config.route && !this.carriedNextDispatch) {
335
- this.terminatedBy = "classifier";
336
- this.status = "completed";
337
- return false;
338
- }
339
- return true;
340
- }
341
- /**
342
- * Resolve the dispatch decision for this iteration — defers to
343
- * `decide.ts`. When `carriedFeedback.reassignTo` is set the
344
- * supervisor overrides the router/route decision with an
345
- * evaluator-forced dispatch (design §2 — "Evaluate can override
346
- * router").
347
- */
348
- async decideDispatch() {
349
- if (this.config.router) this.emit("supervisor.router.deciding", { iteration: this.iteration });
350
- const reassignTo = normalizeReassign(this.carriedFeedback?.reassignTo);
351
- if (reassignTo.length > 0) {
352
- this.carriedNextDispatch = void 0;
353
- for (const intent of reassignTo) if (!this.entries.has(intent)) throw new SupervisorFailedError(`evaluate.reassignTo targeted unknown agent "${intent}"`, { context: { available: [...this.entries.keys()] } });
354
- const decision = {
355
- kind: "dispatch",
356
- intents: reassignTo,
357
- source: "route",
358
- raw: reassignTo.length === 1 ? reassignTo[0] : reassignTo,
359
- durationMs: 0
360
- };
361
- this.emit("supervisor.router.decided", {
362
- iteration: this.iteration,
363
- next: decision.raw,
364
- reasoning: this.carriedFeedback?.feedback,
365
- durationMs: 0
366
- });
367
- return decision;
368
- }
369
- if (this.carriedClassifierDispatch) {
370
- const carried = this.carriedClassifierDispatch;
371
- this.carriedClassifierDispatch = void 0;
372
- const decision = {
373
- kind: "dispatch",
374
- intents: [carried.intent],
375
- source: "classifier",
376
- raw: carried.intent,
377
- durationMs: 0
378
- };
379
- this.emit("supervisor.router.decided", {
380
- iteration: this.iteration,
381
- next: decision.raw,
382
- reasoning: this.classifierSnapshot?.reasoning,
383
- durationMs: 0
384
- });
385
- return decision;
386
- }
387
- if (this.carriedNextDispatch) {
388
- const carried = this.carriedNextDispatch;
389
- this.carriedNextDispatch = void 0;
390
- const decision = {
391
- kind: "dispatch",
392
- intents: carried.intents,
393
- source: "route",
394
- raw: carried.intents.length === 1 ? carried.intents[0] : carried.intents,
395
- durationMs: 0
396
- };
397
- this.emit("supervisor.router.decided", {
398
- iteration: this.iteration,
399
- next: decision.raw,
400
- reasoning: void 0,
401
- durationMs: 0
402
- });
403
- return decision;
404
- }
405
- const decision = await decide({
406
- config: this.config,
407
- entries: this.entries,
408
- iteration: this.iteration,
409
- maxIterations: this.maxIterations,
410
- iterations: this.snapshots,
411
- input: this.input,
412
- state: this.state,
413
- context: this.context,
414
- history: this.history,
415
- goal: this.goal,
416
- evaluateFeedback: this.carriedFeedback,
417
- classifier: this.classifierSnapshot,
418
- signal: this.options?.signal,
419
- useInitialAgent: this.iteration === 0 && !this.resumeFrom
420
- });
421
- if (decision.routerReport) this.childReports.push(decision.routerReport);
422
- this.emit("supervisor.router.decided", {
423
- iteration: this.iteration,
424
- next: decision.raw,
425
- reasoning: decision.reasoning,
426
- durationMs: decision.durationMs
427
- });
428
- return decision;
429
- }
430
- /**
431
- * Dispatch every intent named by the decision in parallel. Per-
432
- * branch errors don't abort siblings — they're recorded on the
433
- * branch snapshot and let evaluate (or default termination logic)
434
- * decide the response.
435
- */
436
- async dispatchBranches(decision) {
437
- return await Promise.all(decision.intents.map((intent) => this.dispatchOne(intent)));
438
- }
439
- /**
440
- * Execute a single branch — resolve the input, invoke the
441
- * agent / workflow / callback, apply the per-intent `output`
442
- * transformer, and produce an immutable `AgentBranchSnapshot`.
443
- */
444
- async dispatchOne(intent) {
445
- const entry = this.entries.get(intent);
446
- if (entry.type === "callback") return this.dispatchCallback(entry);
447
- const routeContext = {
448
- iteration: this.iteration,
449
- input: this.input,
450
- state: this.state,
451
- iterations: this.snapshots,
452
- feedback: typeof this.carriedFeedback?.feedback === "string" ? this.carriedFeedback.feedback : void 0,
453
- evaluateFeedback: this.carriedFeedback,
454
- context: this.context,
455
- history: this.history,
456
- goal: this.goal,
457
- classifier: this.classifierSnapshot
458
- };
459
- const resolvedInput = this.resolveBranchInput(entry, routeContext);
460
- const dispatchCtxForPlaceholders = this.seedDispatchContext(intent, resolvedInput, new Set([intent]), []);
461
- const placeholders = entry.placeholders ? entry.placeholders(dispatchCtxForPlaceholders) : void 0;
462
- this.emit("supervisor.agent.starting", {
463
- iteration: this.iteration,
464
- intent,
465
- input: resolvedInput
466
- });
467
- const startedAt = /* @__PURE__ */ new Date();
468
- const startPerf = performance.now();
469
- let rawResult;
470
- let branchError;
471
- let branchUsage = {
472
- input: 0,
473
- output: 0,
474
- total: 0
475
- };
476
- try {
477
- rawResult = await withoutRunFrame(() => this.invokeUnit(entry, resolvedInput, placeholders, routeContext));
478
- if (rawResult.error) branchError = rawResult.error;
479
- branchUsage = rawResult.usage;
480
- if (rawResult.report) this.childReports.push(rawResult.report);
481
- } catch (thrown) {
482
- branchError = toAIError(thrown);
483
- }
484
- const sliceOutcome = await this.applyOutputSchema(entry, rawResult);
485
- const transformedOutput = sliceOutcome.value;
486
- if (sliceOutcome.error && !branchError) branchError = sliceOutcome.error;
487
- const endedAt = /* @__PURE__ */ new Date();
488
- const duration = performance.now() - startPerf;
489
- const snapshot = Object.freeze({
490
- intent,
491
- input: resolvedInput,
492
- output: transformedOutput,
493
- usage: branchUsage,
494
- startedAt: startedAt.toISOString(),
495
- endedAt: endedAt.toISOString(),
496
- duration,
497
- error: branchError
498
- });
499
- if (branchError) this.emit("supervisor.agent.failed", {
500
- iteration: this.iteration,
501
- intent,
502
- error: branchError
503
- });
504
- else this.emit("supervisor.agent.completed", {
505
- iteration: this.iteration,
506
- intent,
507
- output: transformedOutput,
508
- usage: branchUsage,
509
- duration
510
- });
511
- return snapshot;
512
- }
513
- /**
514
- * Dispatch a callback intent as a top-level branch — produces an
515
- * `AgentBranchSnapshot` and pushes the synthesized callback report
516
- * onto the supervisor's recursive children. Delegates the actual
517
- * callback invocation to {@link runCallback} so nested
518
- * `ctx.intents.X.execute()` calls can reuse the same machinery.
519
- *
520
- * Each branch dispatch starts with a fresh per-branch call stack —
521
- * sibling fan-out branches don't share cycle-detection state, so
522
- * branch A and branch B both invoking the same intent isn't a
523
- * cycle. The branch's own intent name is seeded onto the stack so
524
- * a callback that re-enters itself via `ctx.intents.X.execute()` trips
525
- * cycle detection on the first recursion.
526
- */
527
- async dispatchCallback(entry) {
528
- const intent = entry.intent;
529
- const callStack = new Set([intent]);
530
- const callbackInput = entry.input ? entry.input(this.seedDispatchContext(intent, this.input, callStack, [])) : this.input;
531
- const inputForSnapshot = typeof callbackInput === "string" ? callbackInput : safeStringify(callbackInput);
532
- this.emit("supervisor.agent.starting", {
533
- iteration: this.iteration,
534
- intent,
535
- input: inputForSnapshot
536
- });
537
- const outcome = await this.runCallback(entry, callbackInput, callStack, this.childReports);
538
- const snapshot = Object.freeze({
539
- intent,
540
- input: inputForSnapshot,
541
- output: outcome.output,
542
- usage: outcome.report.usage,
543
- startedAt: outcome.report.startedAt,
544
- endedAt: outcome.report.endedAt,
545
- duration: outcome.report.duration,
546
- error: outcome.error
547
- });
548
- if (outcome.error) this.emit("supervisor.agent.failed", {
549
- iteration: this.iteration,
550
- intent,
551
- error: outcome.error
552
- });
553
- else this.emit("supervisor.agent.completed", {
554
- iteration: this.iteration,
555
- intent,
556
- output: outcome.output,
557
- usage: outcome.report.usage,
558
- duration: outcome.report.duration
559
- });
560
- return snapshot;
561
- }
562
- /**
563
- * Run a callback intent and produce its leaf report + final
564
- * output. Used both for top-level branch dispatch (via
565
- * {@link dispatchCallback}) and for nested `dispatch.byName`
566
- * recursion. The synthesized report is appended to `reportSink`,
567
- * which is either `this.childReports` (top-level) or the calling
568
- * callback's own `children[]` (nested) — that's what gives the
569
- * unified report tree its compositional shape.
570
- *
571
- * Usage on the report rolls up children's usage; the callback
572
- * itself contributes zero (it's dev code, no token spend).
573
- */
574
- async runCallback(entry, input, callStack, reportSink) {
575
- const childReports = [];
576
- const dispatchCtx = this.seedDispatchContext(entry.intent, input, callStack, childReports);
577
- const callbackRunId = `${this.runId}.${entry.intent}`;
578
- const startedAt = /* @__PURE__ */ new Date();
579
- const startPerf = performance.now();
580
- let rawOutput;
581
- let error;
582
- try {
583
- rawOutput = await withRunFrame({
584
- sink: childReports,
585
- rootRunId: this.runId,
586
- parentRunId: callbackRunId,
587
- sessionId: this.options?.sessionId
588
- }, () => Promise.resolve(entry.callback(dispatchCtx)));
589
- } catch (thrown) {
590
- error = thrown instanceof AIError ? thrown : new SupervisorFailedError(`callback intent "${entry.intent}" threw: ${thrown instanceof Error ? thrown.message : String(thrown)}`, { cause: thrown });
591
- }
592
- let transformedOutput = rawOutput;
593
- if (!error && entry.output) {
594
- const validation = await entry.output["~standard"].validate(rawOutput);
595
- if (validation.issues) {
596
- error = new SchemaValidationError(`intent "${entry.intent}" output failed validation: ${validation.issues.map((issue) => issue.message).join("; ")}`, { issues: validation.issues });
597
- transformedOutput = void 0;
598
- } else transformedOutput = validation.value;
599
- }
600
- const endedAt = /* @__PURE__ */ new Date();
601
- const duration = performance.now() - startPerf;
602
- const rolledUsage = aggregateChildUsage(childReports);
603
- const report = {
604
- runId: callbackRunId,
605
- rootRunId: this.runId,
606
- name: entry.intent,
607
- type: "callback",
608
- status: error ? "failed" : "completed",
609
- startedAt: startedAt.toISOString(),
610
- endedAt: endedAt.toISOString(),
611
- duration,
612
- usage: rolledUsage,
613
- children: childReports
614
- };
615
- reportSink.push(report);
616
- return {
617
- output: transformedOutput,
618
- error,
619
- report
620
- };
621
- }
622
- /**
623
- * Build a {@link DispatchContext} with a typed `intents` map of
624
- * `IntentRunner` closures, each closing over the supplied call
625
- * stack and report sink. Cycle detection uses the call stack —
626
- * re-entering an intent already on it throws
627
- * `SupervisorFailedError` with code `SUPERVISOR_DISPATCH_CYCLE`
628
- * and the offending chain in the message.
629
- *
630
- * Replaces the Phase-3.3 `ctx.dispatch.byName` plumbing with
631
- * property-access on a typed map (Q5/Q6) — autocomplete, no typo
632
- * crashes, `.execute()` matches every other primitive's verb.
633
- */
634
- seedDispatchContext(intent, input, callStack, reportSink) {
635
- const intentsMap = {};
636
- for (const target of this.entries.keys()) intentsMap[target] = {
637
- execute: (override) => this.runIntent(target, override === void 0 ? input : override, callStack, reportSink),
638
- stream: (override) => this.streamIntent(target, override === void 0 ? input : override, callStack, reportSink, intent)
639
- };
640
- return {
641
- iteration: this.iteration,
642
- intent,
643
- input,
644
- state: this.state,
645
- result: {},
646
- iterations: this.snapshots,
647
- signal: this.options?.signal ?? new AbortController().signal,
648
- intents: intentsMap,
649
- context: this.context,
650
- history: this.history,
651
- goal: this.goal,
652
- run: (executable, runInput, runOptions) => this.runInline(executable, runInput, runOptions, callStack, reportSink),
653
- stream: (executable, runInput, runOptions) => this.streamInline(executable, runInput, runOptions, callStack, reportSink, intent),
654
- classifier: this.classifierSnapshot
655
- };
656
- }
657
- /**
658
- * Backing implementation for `ctx.intents.X.execute(input?)`.
659
- * Looks up the named intent in the supervisor's registry, asserts
660
- * the call wouldn't close a cycle, and runs the dispatchable
661
- * through the same machinery a top-level branch would — except
662
- * the resulting report nests under the calling callback's
663
- * `children[]` rather than the supervisor's top-level child list,
664
- * and only the final output is returned (no snapshot).
665
- */
666
- async runIntent(target, callerInput, callStack, reportSink) {
667
- if (callStack.has(target)) throw new SupervisorFailedError(`ctx.intents.${target}.execute: cycle detected (${[...callStack, target].join(" → ")})`, { context: { intent: target } }, "SUPERVISOR_DISPATCH_CYCLE");
668
- const entry = this.entries.get(target);
669
- if (!entry) throw new SupervisorFailedError(`ctx.intents.${target}.execute: unknown intent "${target}" — must be a key in the supervisor's \`intents\` map`, { context: { intent: target } });
670
- callStack.add(target);
671
- try {
672
- if (entry.type === "callback") {
673
- const { output, error } = await this.runCallback(entry, callerInput, callStack, reportSink);
674
- if (error) throw error;
675
- return output;
676
- }
677
- const inputString = typeof callerInput === "string" ? callerInput : safeStringify(callerInput);
678
- if (entry.type === "agent") {
679
- const reentryHistory = this.applyAgentsWindow();
680
- const result = await withoutRunFrame(() => entry.unit.execute(inputString, {
681
- signal: this.options?.signal,
682
- ...reentryHistory.length > 0 ? { history: reentryHistory } : {}
683
- }));
684
- if (result.report) reportSink.push(result.report);
685
- if (result.error) throw result.error;
686
- return result.data ?? result.text ?? void 0;
687
- }
688
- const result = await withoutRunFrame(() => entry.unit.execute(inputString, { signal: this.options?.signal }));
689
- if (result.report) reportSink.push(result.report);
690
- if (result.error) throw result.error;
691
- return result.data;
692
- } finally {
693
- callStack.delete(target);
694
- }
695
- }
696
- /**
697
- * Backing implementation for `ctx.intents.X.stream(input?)` (Phase 6
698
- * / decisions §36). Streaming sibling of {@link runIntent} — same
699
- * cycle protection, same auto-merge of supervisor-level concerns,
700
- * but routes through the unit's `.stream()` method when available
701
- * and bubbles deltas as `supervisor.agent.streaming` under the
702
- * **calling callback's** intent name (not the dispatched intent's).
703
- */
704
- streamIntent(target, callerInput, callStack, reportSink, callerIntent) {
705
- if (callStack.has(target)) throw new SupervisorFailedError(`ctx.intents.${target}.stream: cycle detected (${[...callStack, target].join(" → ")})`, { context: { intent: target } }, "SUPERVISOR_DISPATCH_CYCLE");
706
- const entry = this.entries.get(target);
707
- if (!entry) throw new SupervisorFailedError(`ctx.intents.${target}.stream: unknown intent "${target}" — must be a key in the supervisor's \`intents\` map`, { context: { intent: target } });
708
- if (entry.type === "callback") throw new SupervisorFailedError(`ctx.intents.${target}.stream: callback intents are not streamable — use \`.execute(input?)\` instead`, { context: { intent: target } });
709
- callStack.add(target);
710
- const inputString = typeof callerInput === "string" ? callerInput : safeStringify(callerInput);
711
- return this.streamSupervisedExecutable(entry.unit, inputString, void 0, callerIntent, reportSink, () => callStack.delete(target));
712
- }
713
- /**
714
- * Backing implementation for `ctx.run(executable, input, options?)`
715
- * (Phase 6 / decisions §36). Runs an inline / un-registered
716
- * executable under supervision: auto-merges `signal`, `toolCtx`,
717
- * `history` defaults; nests the resulting report under the
718
- * calling callback's `children[]`. Per-call options REPLACE auto-
719
- * defaults — standard Warlock convention.
720
- *
721
- * Cycle protection by executable `name` matches the registered-
722
- * intent path so a callback that recurses on the same agent trips
723
- * the same error, regardless of whether the agent was looked up
724
- * via `ctx.intents.X.execute()` or passed inline.
725
- */
726
- async runInline(executable, input, options, callStack, reportSink) {
727
- const name = executable.name;
728
- if (callStack.has(name)) throw new SupervisorFailedError(`ctx.run("${name}"): cycle detected (${[...callStack, name].join(" → ")})`, { context: { intent: name } }, "SUPERVISOR_DISPATCH_CYCLE");
729
- callStack.add(name);
730
- try {
731
- const merged = this.mergeInlineOptions(options);
732
- const inputForExecutable = this.coerceInlineInput(executable, input);
733
- const result = await withoutRunFrame(() => executable.execute(inputForExecutable, merged));
734
- if (result.report) reportSink.push(result.report);
735
- return result;
736
- } finally {
737
- callStack.delete(name);
738
- }
739
- }
740
- /**
741
- * Backing implementation for `ctx.stream(executable, input, options?)`
742
- * (Phase 6 / decisions §36). Streaming sibling of {@link runInline}.
743
- * Routes through the executable's native `.stream()` method,
744
- * subscribes to delta events, and bubbles them as
745
- * `supervisor.agent.streaming` under the calling callback's intent
746
- * name. The returned `StreamContract` is the executable's own —
747
- * iteration and `.result` work identically.
748
- *
749
- * Cycle protection on entry mirrors {@link runInline}; release runs
750
- * after `.result` settles so a same-callback recursion is caught
751
- * regardless of which path closed the cycle.
752
- */
753
- streamInline(executable, input, options, callStack, reportSink, callerIntent) {
754
- const name = executable.name;
755
- if (callStack.has(name)) throw new SupervisorFailedError(`ctx.stream("${name}"): cycle detected (${[...callStack, name].join(" → ")})`, { context: { intent: name } }, "SUPERVISOR_DISPATCH_CYCLE");
756
- callStack.add(name);
757
- return this.streamSupervisedExecutable(executable, this.coerceInlineInput(executable, input), options, callerIntent, reportSink, () => callStack.delete(name));
758
- }
759
- /**
760
- * Shared wiring for both `ctx.intents.X.stream()` and
761
- * `ctx.stream(...)`. Subscribes to the executable's stream, re-
762
- * emits deltas as `supervisor.agent.streaming` under the calling
763
- * callback's intent name, and pushes the inner report onto the
764
- * reportSink once `.result` settles. The returned StreamContract
765
- * is the executable's own — the framework attaches handlers
766
- * transparently via `.on(...)`.
767
- */
768
- streamSupervisedExecutable(executable, input, options, callerIntent, reportSink, release) {
769
- const merged = this.mergeInlineOptions(options);
770
- const stream = withoutRunFrame(() => executable.stream(input, merged));
771
- stream.on({
772
- "agent.trip.streaming": ({ delta }) => {
773
- this.emit("supervisor.agent.streaming", {
774
- iteration: this.iteration,
775
- intent: callerIntent,
776
- delta
777
- });
778
- },
779
- "supervisor.agent.streaming": ({ delta }) => {
780
- this.emit("supervisor.agent.streaming", {
781
- iteration: this.iteration,
782
- intent: callerIntent,
783
- delta
784
- });
785
- }
786
- });
787
- stream.result.then((result) => {
788
- if (result?.report) reportSink.push(result.report);
789
- release();
790
- }, () => release());
791
- return stream;
792
- }
793
- /**
794
- * Build the options object passed into an inline `.execute()` /
795
- * `.stream()` call. Auto-merges supervisor-level defaults
796
- * (`signal`, `toolCtx`, `history` window) under the caller's
797
- * options. Per-call values REPLACE the auto-defaults — when the
798
- * dev passes `signal: undefined` they explicitly opt out.
799
- */
800
- mergeInlineOptions(options) {
801
- const supplied = options ?? {};
802
- const merged = { ...supplied };
803
- if (!("signal" in supplied)) merged.signal = this.options?.signal;
804
- if (!("toolCtx" in supplied)) merged.toolCtx = {
805
- artifacts: this.currentArtifacts,
806
- signal: this.options?.signal
807
- };
808
- if (!("history" in supplied)) {
809
- const window = this.applyAgentsWindow();
810
- if (window.length > 0) merged.history = window;
811
- }
812
- return merged;
813
- }
814
- /**
815
- * Coerce an arbitrary inline input into the shape the underlying
816
- * executable expects. Agents take `string`; workflows + supervisors
817
- * take whatever they declared. We safe-stringify objects only when
818
- * passing to an agent — workflow / supervisor calls hand the value
819
- * through unchanged so structured inputs work.
820
- */
821
- coerceInlineInput(executable, input) {
822
- if (!("signature" in executable) && typeof executable.execute === "function" && !this.isSupervisor(executable) && typeof input !== "string") return safeStringify(input);
823
- return input;
824
- }
825
- /**
826
- * Heuristic detection of `SupervisorContract` — the contract carries
827
- * a `signature` getter same as workflows, but supervisors expose
828
- * `resume()` while workflows expose `resume(runId, options)` too.
829
- * Cleanest distinguisher in the public surface: supervisors carry
830
- * the `asTool` method name `as` … unfortunately so do workflows.
831
- * Use the `streamableType` brand if we add one in v2; for now lean
832
- * on a duck-typed check that's good enough for the ctx.run path
833
- * (incorrect routing for workflows would still produce a runnable
834
- * call — workflow.execute accepts the same args either way).
835
- */
836
- isSupervisor(executable) {
837
- return typeof executable.resume === "function" && typeof executable.signature === "string" && typeof executable.stream === "function";
838
- }
839
- /**
840
- * Invoke the underlying dispatchable unit. Agents and workflows
841
- * both satisfy `ExecutableContract<string, …>` so the call shape
842
- * is uniform; the `type` discriminator picks which options get
843
- * threaded through (e.g. per-call stream event bubbling for
844
- * agents, which we wire inline so child agent tokens surface as
845
- * `supervisor.agent.streaming`).
846
- */
847
- async invokeUnit(entry, input, placeholders, routeContext) {
848
- const isStreaming = this.streamController !== void 0;
849
- if (entry.type === "agent") {
850
- const agent = entry.unit;
851
- const handlers = { "agent.trip.streaming": ({ delta }) => {
852
- this.emit("supervisor.agent.streaming", {
853
- iteration: this.iteration,
854
- intent: entry.intent,
855
- delta
856
- });
857
- } };
858
- const isStreamMode = entry.mode === "stream";
859
- const resolvedHistory = this.resolveHistoryFor("agents", routeContext, entry.history);
860
- const agentOptions = {
861
- signal: this.options?.signal,
862
- on: handlers,
863
- ...placeholders ? { placeholders } : {},
864
- ...entry.output && !isStreamMode ? { output: entry.output } : {},
865
- ...resolvedHistory.length > 0 ? { history: resolvedHistory } : {},
866
- toolCtx: {
867
- artifacts: this.currentArtifacts,
868
- signal: this.options?.signal
869
- }
870
- };
871
- if (isStreamMode || isStreaming) return agent.stream(input, agentOptions).result;
872
- return agent.execute(input, agentOptions);
873
- }
874
- return entry.unit.execute(input, {
875
- signal: this.options?.signal,
876
- on: { "workflow.step.streaming": ({ delta }) => {
877
- this.emit("supervisor.agent.streaming", {
878
- iteration: this.iteration,
879
- intent: entry.intent,
880
- delta
881
- });
882
- } }
883
- });
884
- }
885
- /**
886
- * Build the input string passed to a branch's child execution.
887
- * Default: pass the supervisor's original `ctx.input` through
888
- * unchanged. The per-intent `entry.input` override is the escape
889
- * hatch for the rare case where the agent's user message itself
890
- * must vary per intent.
891
- *
892
- * Q17 lock: dropped `composeAgentInput` + `defaultComposeAgentInput`.
893
- * Their three jobs (carry original / prior outputs / feedback) all
894
- * have cleaner homes in the new model — original is the input
895
- * itself, prior outputs are state (Stage 4b), feedback is a
896
- * router-only signal (Q18).
897
- */
898
- resolveBranchInput(entry, ctx) {
899
- const override = entry.input?.(ctx);
900
- if (typeof override === "string") return override;
901
- return typeof ctx.input === "string" ? ctx.input : safeStringify(ctx.input);
902
- }
903
- /**
904
- * Strip-merge the agent/workflow's raw output against the per-intent
905
- * `output` schema (Q11/Q13). Returns the validated slice that:
906
- *
907
- * 1. Lands on `IterationSnapshot.result[intent].output` (so
908
- * consumers see the same shape that hit state).
909
- * 2. Shallow-merges into `this.state` (handled by the caller).
910
- *
911
- * When `entry.output` is omitted the agent's full `data` (or `text`
912
- * fallback for unstructured agents) flows through unvalidated — but
913
- * is NOT auto-merged into state. State contribution is opt-in via
914
- * declaring the slice schema.
915
- *
916
- * Validation failure surfaces as a per-branch error on the
917
- * snapshot; sibling branches still run.
918
- */
919
- async applyOutputSchema(entry, raw) {
920
- if (!raw) return { value: void 0 };
921
- const sourceValue = isAgentResult(raw) ? raw.data ?? raw.text ?? void 0 : isWorkflowResult(raw) ? raw.data : void 0;
922
- if (entry.type === "agent" && entry.mode === "stream") {
923
- const text = typeof sourceValue === "string" ? sourceValue : "";
924
- return { value: { [entry.streamTo]: text } };
925
- }
926
- if (!entry.output) return { value: sourceValue };
927
- const validation = await entry.output["~standard"].validate(sourceValue);
928
- if (validation.issues) return {
929
- value: void 0,
930
- error: new SchemaValidationError(`intent "${entry.intent}" output failed validation: ${validation.issues.map((issue) => issue.message).join("; ")}`, { issues: validation.issues })
931
- };
932
- return { value: validation.value };
933
- }
934
- /**
935
- * Fire the receptionist (`ack`) — runs in parallel with phase A on
936
- * iteration 0 only. Accepts three shapes:
937
- *
938
- * - `AckEntry` — `{ agent, placeholders?, input?, output? }`. LLM
939
- * form. Streams tokens via `supervisor.ack.streaming`; report
940
- * node pushes onto `childReports[]`.
941
- * - `AckRunEntry` — `{ run, output? }`. Pure-code callback. Settles
942
- * without an LLM call. No streaming events; just `.completed`.
943
- * - `AckCallback` — bare `(ctx) => slice` shorthand for the
944
- * pure-code form when no schema is declared.
945
- *
946
- * Failures are recorded but never abort the run — the receptionist
947
- * tripping doesn't stop the specialist from doing the actual job.
948
- * The returned outcome is what `mergeAckIntoState` consumes.
949
- */
950
- async runAck() {
951
- const ack = this.config.ack;
952
- if (!ack) return void 0;
953
- const routeContext = {
954
- iteration: this.iteration,
955
- input: this.input,
956
- state: this.state,
957
- iterations: this.snapshots,
958
- feedback: typeof this.carriedFeedback?.feedback === "string" ? this.carriedFeedback.feedback : void 0,
959
- evaluateFeedback: this.carriedFeedback,
960
- context: this.context,
961
- history: this.history,
962
- goal: this.goal,
963
- classifier: this.classifierSnapshot
964
- };
965
- const startedAt = /* @__PURE__ */ new Date();
966
- const startPerf = performance.now();
967
- if (typeof ack === "function") return this.runAckCallback(ack, void 0, routeContext, startedAt, startPerf);
968
- if ("run" in ack && typeof ack.run === "function") {
969
- const runEntry = ack;
970
- return this.runAckCallback(runEntry.run, runEntry.output, routeContext, startedAt, startPerf);
971
- }
972
- return this.runAckAgent(ack, routeContext, startedAt, startPerf);
973
- }
974
- /**
975
- * Pure-code receptionist path — invokes the callback, strip-validates
976
- * the return value (when an `output` schema is declared), records the
977
- * snapshot, emits `supervisor.ack.completed`, returns the outcome.
978
- * No streaming events fire (callbacks settle synchronously from the
979
- * supervisor's POV).
980
- */
981
- async runAckCallback(run, output, routeContext, startedAt, startPerf) {
982
- const usage = {
983
- input: 0,
984
- output: 0,
985
- total: 0
986
- };
987
- let validatedOutput;
988
- let ackError;
989
- try {
990
- const raw = await run(routeContext);
991
- if (output) {
992
- const validation = await output["~standard"].validate(raw);
993
- if (validation.issues) ackError = new SchemaValidationError(`ack output failed validation: ${validation.issues.map((issue) => issue.message).join("; ")}`, { issues: validation.issues });
994
- else validatedOutput = validation.value;
995
- } else validatedOutput = raw;
996
- } catch (thrown) {
997
- ackError = toAIError(thrown);
998
- }
999
- const endedAt = /* @__PURE__ */ new Date();
1000
- const duration = performance.now() - startPerf;
1001
- this.ackSnapshot = Object.freeze({
1002
- input: typeof this.input === "string" ? this.input : safeStringify(this.input),
1003
- output: validatedOutput,
1004
- usage,
1005
- startedAt: startedAt.toISOString(),
1006
- endedAt: endedAt.toISOString(),
1007
- duration,
1008
- error: ackError
1009
- });
1010
- this.emit("supervisor.ack.completed", {
1011
- output: validatedOutput,
1012
- usage,
1013
- duration,
1014
- error: ackError
1015
- });
1016
- return {
1017
- output: validatedOutput,
1018
- usage,
1019
- duration,
1020
- error: ackError
1021
- };
1022
- }
1023
- /**
1024
- * Agent-driven receptionist path — invokes the agent, streams tokens
1025
- * via `supervisor.ack.streaming`, captures the report node, strip-
1026
- * validates against `output` (when declared), records the snapshot,
1027
- * emits `supervisor.ack.completed`.
1028
- */
1029
- async runAckAgent(ack, routeContext, startedAt, startPerf) {
1030
- const placeholders = ack.placeholders?.(routeContext);
1031
- const inputForAck = ack.input?.(routeContext) ?? (typeof this.input === "string" ? this.input : safeStringify(this.input));
1032
- const isStreaming = this.streamController !== void 0;
1033
- const handlers = { "agent.trip.streaming": ({ delta }) => {
1034
- this.emit("supervisor.ack.streaming", { delta });
1035
- } };
1036
- const resolvedHistory = this.resolveHistoryFor("ack", routeContext, ack.history);
1037
- const agentOptions = {
1038
- signal: this.options?.signal,
1039
- on: handlers,
1040
- ...placeholders ? { placeholders } : {},
1041
- ...ack.output ? { output: ack.output } : {},
1042
- ...resolvedHistory.length > 0 ? { history: resolvedHistory } : {}
1043
- };
1044
- let rawResult;
1045
- let ackError;
1046
- let usage = {
1047
- input: 0,
1048
- output: 0,
1049
- total: 0
1050
- };
1051
- try {
1052
- if (isStreaming) rawResult = await ack.agent.stream(inputForAck, agentOptions).result;
1053
- else rawResult = await ack.agent.execute(inputForAck, agentOptions);
1054
- if (rawResult.error) ackError = rawResult.error;
1055
- usage = rawResult.usage ?? usage;
1056
- if (rawResult.report) this.childReports.push(rawResult.report);
1057
- } catch (thrown) {
1058
- ackError = toAIError(thrown);
1059
- }
1060
- const endedAt = /* @__PURE__ */ new Date();
1061
- const duration = performance.now() - startPerf;
1062
- let validatedOutput;
1063
- if (rawResult && !ackError && ack.output) {
1064
- const sourceValue = rawResult.data ?? rawResult.text ?? void 0;
1065
- const validation = await ack.output["~standard"].validate(sourceValue);
1066
- if (validation.issues) ackError = new SchemaValidationError(`ack output failed validation: ${validation.issues.map((issue) => issue.message).join("; ")}`, { issues: validation.issues });
1067
- else validatedOutput = validation.value;
1068
- } else if (rawResult && !ackError) validatedOutput = rawResult.data ?? rawResult.text ?? void 0;
1069
- this.ackSnapshot = Object.freeze({
1070
- input: inputForAck,
1071
- output: validatedOutput,
1072
- usage,
1073
- startedAt: startedAt.toISOString(),
1074
- endedAt: endedAt.toISOString(),
1075
- duration,
1076
- error: ackError
1077
- });
1078
- this.emit("supervisor.ack.completed", {
1079
- output: validatedOutput,
1080
- usage,
1081
- duration,
1082
- error: ackError
1083
- });
1084
- return {
1085
- output: validatedOutput,
1086
- usage,
1087
- duration,
1088
- error: ackError
1089
- };
1090
- }
1091
- /**
1092
- * Probe the ack promise non-blockingly. Yields one macrotask cycle
1093
- * (`setImmediate`) so an already-resolved ack wins via microtask
1094
- * priority; if the probe returns first, the slice is abandoned —
1095
- * warning logged, error captured on `report.ack`, run completes
1096
- * regardless. Specialists own the actual answer; the receptionist
1097
- * was just a reassuring preview.
1098
- */
1099
- async settleAck(ackPromise, iterationUsage) {
1100
- if (!ackPromise) return;
1101
- const NOT_READY = Symbol("ack-not-ready");
1102
- const probe = await Promise.race([ackPromise, new Promise((resolve) => setTimeout(() => resolve(NOT_READY), 0))]);
1103
- if (probe === NOT_READY) {
1104
- this.logger.warn(this.logModule, "ack.abandoned", "ack receptionist did not settle before iteration completed; slice dropped");
1105
- const abandonedAt = /* @__PURE__ */ new Date();
1106
- this.ackSnapshot = Object.freeze({
1107
- input: typeof this.input === "string" ? this.input : safeStringify(this.input),
1108
- output: void 0,
1109
- usage: {
1110
- input: 0,
1111
- output: 0,
1112
- total: 0
1113
- },
1114
- startedAt: abandonedAt.toISOString(),
1115
- endedAt: abandonedAt.toISOString(),
1116
- duration: 0,
1117
- error: new SupervisorFailedError("ack receptionist did not settle before iteration completed", { context: { ackAbandoned: true } })
1118
- });
1119
- return;
1120
- }
1121
- const ackOutcome = probe;
1122
- if (ackOutcome) {
1123
- this.aggregateUsage(iterationUsage, ackOutcome.usage);
1124
- this.mergeAckIntoState(ackOutcome);
1125
- }
1126
- }
1127
- /**
1128
- * Merge the receptionist's strip-validated slice into state. Called
1129
- * from `settleAck` BEFORE branch merges so specialists override the
1130
- * receptionist on key collision — the receptionist hedges, the
1131
- * specialist commits.
1132
- */
1133
- mergeAckIntoState(ackOutcome) {
1134
- if (ackOutcome.error || !ackOutcome.output) return;
1135
- if (typeof ackOutcome.output !== "object" || ackOutcome.output === null) return;
1136
- const slice = ackOutcome.output;
1137
- for (const [key, value] of Object.entries(slice)) this.state[key] = value;
1138
- }
1139
- /**
1140
- * Run the iter-0 classifier prelude (Phase 7 / decisions §37).
1141
- * Resolves the configured classifier (agent / callback / entry
1142
- * form), invokes it, runs the optional `refine` post-process hook,
1143
- * and either:
1144
- *
1145
- * - sets `carriedClassifierDispatch` so the upcoming
1146
- * `decideDispatch` short-circuits to the chosen intent, OR
1147
- * - sets `classifierHalted = true` so `runIteration` terminates
1148
- * before any dispatch (refine returned `END`).
1149
- *
1150
- * Captures the full forensic record on `classifierSnapshot` —
1151
- * surfaced on `SupervisorReport.classifier` and threaded into
1152
- * `ctx.classifier` on every downstream context.
1153
- *
1154
- * Errors in the classifier OR the refine hook abort the run with
1155
- * a `SupervisorFailedError` so issues surface loudly instead of
1156
- * silently falling through to router/route.
1157
- */
1158
- async runClassifier() {
1159
- const startedAt = /* @__PURE__ */ new Date();
1160
- const startPerf = performance.now();
1161
- const startedAtIso = startedAt.toISOString();
1162
- this.emit("supervisor.classifier.starting", { iteration: 0 });
1163
- const ctx = this.buildClassifierContext();
1164
- const config = this.config.classifier;
1165
- let raw;
1166
- let usage = {
1167
- input: 0,
1168
- output: 0,
1169
- total: 0
1170
- };
1171
- let executionError;
1172
- try {
1173
- const outcome = await this.invokeClassifier(config, ctx);
1174
- raw = outcome.output;
1175
- usage = outcome.usage;
1176
- } catch (thrown) {
1177
- executionError = toAIError(thrown);
1178
- }
1179
- if (executionError || !raw) {
1180
- const error = executionError ?? new SupervisorFailedError(`ai.supervisor("${this.config.name}"): classifier produced no output`, { context: { iteration: 0 } });
1181
- this.classifierSnapshot = {
1182
- intent: void 0,
1183
- refined: false,
1184
- halted: true,
1185
- raw: raw ?? { intent: "" },
1186
- startedAt: startedAtIso,
1187
- endedAt: (/* @__PURE__ */ new Date()).toISOString(),
1188
- duration: performance.now() - startPerf,
1189
- usage,
1190
- error
1191
- };
1192
- mergeUsage(this.usage, usage);
1193
- this.emit("supervisor.classifier.failed", { error });
1194
- throw error;
1195
- }
1196
- if (!this.entries.has(raw.intent)) {
1197
- const error = new SupervisorFailedError(`ai.supervisor("${this.config.name}"): classifier picked unknown intent "${raw.intent}" — must be a key in \`intents\``, { context: {
1198
- iteration: 0,
1199
- available: [...this.entries.keys()]
1200
- } }, "SUPERVISOR_INVALID_ROUTE");
1201
- this.classifierSnapshot = {
1202
- intent: void 0,
1203
- refined: false,
1204
- halted: true,
1205
- raw,
1206
- startedAt: startedAtIso,
1207
- endedAt: (/* @__PURE__ */ new Date()).toISOString(),
1208
- duration: performance.now() - startPerf,
1209
- usage,
1210
- error
1211
- };
1212
- mergeUsage(this.usage, usage);
1213
- this.emit("supervisor.classifier.failed", { error });
1214
- throw error;
1215
- }
1216
- const refineHook = this.resolveRefineHook(config);
1217
- let final = raw;
1218
- let refined = false;
1219
- let halted = false;
1220
- if (refineHook) {
1221
- let refineResult;
1222
- try {
1223
- refineResult = await refineHook(this.buildClassifierRefineContext(ctx, raw));
1224
- } catch (thrown) {
1225
- const error = toAIError(thrown);
1226
- this.classifierSnapshot = {
1227
- intent: void 0,
1228
- refined: false,
1229
- halted: true,
1230
- raw,
1231
- startedAt: startedAtIso,
1232
- endedAt: (/* @__PURE__ */ new Date()).toISOString(),
1233
- duration: performance.now() - startPerf,
1234
- usage,
1235
- error
1236
- };
1237
- mergeUsage(this.usage, usage);
1238
- this.emit("supervisor.classifier.failed", { error });
1239
- throw error;
1240
- }
1241
- const interpretation = this.interpretRefineResult(refineResult, raw);
1242
- if (interpretation.error) {
1243
- this.classifierSnapshot = {
1244
- intent: void 0,
1245
- refined: true,
1246
- halted: true,
1247
- raw,
1248
- startedAt: startedAtIso,
1249
- endedAt: (/* @__PURE__ */ new Date()).toISOString(),
1250
- duration: performance.now() - startPerf,
1251
- usage,
1252
- error: interpretation.error
1253
- };
1254
- mergeUsage(this.usage, usage);
1255
- this.emit("supervisor.classifier.failed", { error: interpretation.error });
1256
- throw interpretation.error;
1257
- }
1258
- refined = interpretation.refined;
1259
- halted = interpretation.halted;
1260
- final = interpretation.final ?? raw;
1261
- if (interpretation.sliceToMerge) for (const [key, value] of Object.entries(interpretation.sliceToMerge)) this.state[key] = value;
1262
- }
1263
- for (const [key, value] of Object.entries(final)) this.state[key] = value;
1264
- this.classifierSnapshot = {
1265
- intent: halted ? void 0 : final.intent,
1266
- reasoning: final.reasoning,
1267
- confidence: final.confidence,
1268
- refined,
1269
- halted,
1270
- raw,
1271
- startedAt: startedAtIso,
1272
- endedAt: (/* @__PURE__ */ new Date()).toISOString(),
1273
- duration: performance.now() - startPerf,
1274
- usage
1275
- };
1276
- mergeUsage(this.usage, usage);
1277
- this.emit("supervisor.classifier.completed", {
1278
- output: {
1279
- intent: this.classifierSnapshot.intent,
1280
- reasoning: this.classifierSnapshot.reasoning,
1281
- confidence: this.classifierSnapshot.confidence
1282
- },
1283
- intent: this.classifierSnapshot.intent,
1284
- refined,
1285
- halted,
1286
- duration: this.classifierSnapshot.duration,
1287
- usage
1288
- });
1289
- if (halted) {
1290
- this.classifierHalted = true;
1291
- return;
1292
- }
1293
- if (!this.entries.has(final.intent)) {
1294
- const error = new SupervisorFailedError(`ai.supervisor("${this.config.name}"): classifier.refine returned unknown intent "${final.intent}" — must be a key in \`intents\``, { context: {
1295
- iteration: 0,
1296
- available: [...this.entries.keys()]
1297
- } }, "SUPERVISOR_INVALID_ROUTE");
1298
- this.classifierSnapshot = {
1299
- ...this.classifierSnapshot,
1300
- halted: true,
1301
- error
1302
- };
1303
- this.classifierHalted = true;
1304
- this.emit("supervisor.classifier.failed", { error });
1305
- throw error;
1306
- }
1307
- this.carriedClassifierDispatch = { intent: final.intent };
1308
- }
1309
- /**
1310
- * Resolve the configured classifier into a callable that returns
1311
- * `{ output, usage }`. Handles the four accepted shapes — bare
1312
- * agent / bare callback / agent-entry / run-entry. Pure shape
1313
- * normalization; no side effects.
1314
- */
1315
- async invokeClassifier(config, ctx) {
1316
- if (typeof config === "function") return {
1317
- output: await config(ctx),
1318
- usage: {
1319
- input: 0,
1320
- output: 0,
1321
- total: 0
1322
- }
1323
- };
1324
- if (typeof config.run === "function") {
1325
- const runFn = config.run;
1326
- return {
1327
- output: await runFn(ctx),
1328
- usage: {
1329
- input: 0,
1330
- output: 0,
1331
- total: 0
1332
- }
1333
- };
1334
- }
1335
- if (typeof config.agent?.execute === "function") {
1336
- const entry = config;
1337
- return this.invokeClassifierAgent(entry.agent, ctx, entry.placeholders, entry.input, entry.history);
1338
- }
1339
- if (typeof config.execute === "function") return this.invokeClassifierAgent(config, ctx);
1340
- throw new SupervisorFailedError(`ai.supervisor("${this.config.name}"): \`classifier\` is not an agent, callback, or entry object`, { context: { authoring: true } });
1341
- }
1342
- /**
1343
- * Invoke a classifier agent with the supervisor's standard wiring
1344
- * — placeholders, input override, history slicing, signal,
1345
- * streaming bubble. Output schema validation belongs to the agent
1346
- * itself; we just pull the typed `data` (or fall back to parsing
1347
- * `text`) and assert the locked `intent` field.
1348
- */
1349
- async invokeClassifierAgent(agent, ctx, placeholders, inputResolver, historySlicer) {
1350
- const inputForAgent = inputResolver?.(ctx) ?? (typeof ctx.input === "string" ? ctx.input : safeStringify(ctx.input));
1351
- const history = historySlicer ? [...historySlicer(ctx)] : this.applyAgentsWindow();
1352
- const isStreaming = this.streamController !== void 0;
1353
- const agentOptions = {
1354
- signal: this.options?.signal,
1355
- on: { "agent.trip.streaming": ({ delta }) => {
1356
- this.emit("supervisor.classifier.streaming", { delta });
1357
- } },
1358
- ...placeholders ? { placeholders: placeholders(ctx) } : {},
1359
- ...history.length > 0 ? { history } : {}
1360
- };
1361
- let result;
1362
- if (isStreaming) result = await agent.stream(inputForAgent, agentOptions).result;
1363
- else result = await agent.execute(inputForAgent, agentOptions);
1364
- if (result.error) throw result.error;
1365
- if (result.report) this.childReports.push(result.report);
1366
- const data = result.data ?? result.text ?? void 0;
1367
- return {
1368
- output: this.coerceClassifierOutput(data),
1369
- usage: result.usage
1370
- };
1371
- }
1372
- /**
1373
- * Coerce an agent's output into the locked classifier shape.
1374
- * Accepts a typed object with `intent` (the canonical case) or a
1375
- * plain string (interpreted as the intent name with no reasoning).
1376
- * Throws `SupervisorFailedError` if neither shape matches.
1377
- */
1378
- coerceClassifierOutput(data) {
1379
- if (typeof data === "string") return { intent: data };
1380
- if (data && typeof data === "object" && typeof data.intent === "string") {
1381
- const record = data;
1382
- return {
1383
- intent: record.intent,
1384
- reasoning: typeof record.reasoning === "string" ? record.reasoning : void 0,
1385
- confidence: typeof record.confidence === "number" ? record.confidence : void 0
1386
- };
1387
- }
1388
- throw new SupervisorFailedError(`ai.supervisor("${this.config.name}"): classifier output missing required \`intent\` field — got ${JSON.stringify(data)?.slice(0, 200)}`, { context: { iteration: 0 } });
1389
- }
1390
- /**
1391
- * Build the read-only context passed to a classifier callback / agent
1392
- * resolvers. No dispatch helpers — registered intents haven't fired
1393
- * yet; pre-running them from the classifier would be confusing.
1394
- */
1395
- buildClassifierContext() {
1396
- return {
1397
- iteration: 0,
1398
- input: this.input,
1399
- state: this.state,
1400
- context: this.context,
1401
- history: this.history,
1402
- signal: this.options?.signal ?? new AbortController().signal,
1403
- goal: this.goal
1404
- };
1405
- }
1406
- /**
1407
- * Build the refine context — extends ClassifierContext with the
1408
- * classifier's just-resolved output plus `run` / `stream` so the
1409
- * refine hook can spin up secondary classifiers / validators
1410
- * inline (Phase 6 features).
1411
- */
1412
- buildClassifierRefineContext(base, raw) {
1413
- const callStack = /* @__PURE__ */ new Set();
1414
- const reportSink = this.childReports;
1415
- return {
1416
- ...base,
1417
- result: { data: raw },
1418
- run: (executable, runInput, runOptions) => this.runInline(executable, runInput, runOptions, callStack, reportSink),
1419
- stream: (executable, runInput, runOptions) => this.streamInline(executable, runInput, runOptions, callStack, reportSink, "classifier")
1420
- };
1421
- }
1422
- /**
1423
- * Pull the optional `refine` hook off whichever classifier-config
1424
- * shape was supplied. Bare-callback and bare-agent forms have no
1425
- * refine; only entry forms do.
1426
- */
1427
- resolveRefineHook(config) {
1428
- if (typeof config === "function") return;
1429
- const refine = config.refine;
1430
- return typeof refine === "function" ? refine : void 0;
1431
- }
1432
- /**
1433
- * Interpret a refine return value into actionable bits — final
1434
- * classifier output to dispatch, slice-to-merge, halted/refined
1435
- * flags, or an error. See {@link ClassifierRefineResult} for the
1436
- * accepted shapes.
1437
- */
1438
- interpretRefineResult(refineResult, raw) {
1439
- if (refineResult === void 0) return {
1440
- final: raw,
1441
- refined: false,
1442
- halted: false
1443
- };
1444
- if (refineResult === "__warlock:end__") return {
1445
- refined: true,
1446
- halted: true
1447
- };
1448
- if (typeof refineResult !== "object" || refineResult === null) return {
1449
- refined: false,
1450
- halted: true,
1451
- error: new SupervisorFailedError(`ai.supervisor("${this.config.name}"): classifier.refine returned an unsupported value — expected undefined, END, or an object`, { context: { iteration: 0 } })
1452
- };
1453
- const record = refineResult;
1454
- const intentField = record.intent;
1455
- const halted = intentField === END;
1456
- const intentOverride = typeof intentField === "string" ? intentField : void 0;
1457
- const slice = {};
1458
- for (const [key, value] of Object.entries(record)) {
1459
- if (key === "intent") continue;
1460
- slice[key] = value;
1461
- }
1462
- const final = {
1463
- ...raw,
1464
- ...intentOverride ? { intent: intentOverride } : {}
1465
- };
1466
- return {
1467
- final: halted ? void 0 : final,
1468
- sliceToMerge: Object.keys(slice).length > 0 ? slice : void 0,
1469
- refined: true,
1470
- halted
1471
- };
1472
- }
1473
- /**
1474
- * Run the `evaluate` callback (when configured) after the
1475
- * iteration's branches settle and outputs have merged into state.
1476
- * Errors in the callback surface as `SupervisorFailedError` so a
1477
- * buggy evaluate doesn't silently swallow the whole run.
1478
- *
1479
- * Phase 3.4 (Stage 4b) — `EvaluateContext.state` carries the
1480
- * post-merge accumulator so verdicts can be state-aware. Q9
1481
- * lifted the router-only restriction; evaluate now runs in both
1482
- * router and route modes.
1483
- */
1484
- async runEvaluate(branches) {
1485
- if (!this.config.evaluate) return;
1486
- const evaluateContext = {
1487
- iteration: this.iteration,
1488
- input: this.input,
1489
- state: this.state,
1490
- result: indexBranchesForEvaluate(branches),
1491
- iterations: this.snapshots,
1492
- context: this.context,
1493
- history: this.history,
1494
- goal: this.goal,
1495
- classifier: this.classifierSnapshot
1496
- };
1497
- try {
1498
- return await this.config.evaluate(evaluateContext);
1499
- } catch (thrown) {
1500
- throw new SupervisorFailedError(`evaluate callback threw: ${thrown instanceof Error ? thrown.message : String(thrown)}`, { cause: thrown });
1501
- }
1502
- }
1503
- /**
1504
- * Merge each branch's output into supervisor `state` in
1505
- * `decision.intents` order — Q15 conflict rule: last intent in
1506
- * the array wins on key collisions. Errored branches don't
1507
- * contribute. Non-object outputs (primitives, null) are skipped
1508
- * with a warning log; they can't shallow-merge into an object.
1509
- *
1510
- * For agent/workflow intents: merging is opt-in via declaring an
1511
- * `output` schema (the strip-merge gate). Without a schema, the
1512
- * raw output stays on the branch snapshot but doesn't pollute
1513
- * state. For callback intents: their return is already strip-merged
1514
- * (or pass-through) inside `runCallback` — we just merge what's on
1515
- * the branch snapshot.
1516
- */
1517
- mergeBranchesIntoState(intentsOrder, branches) {
1518
- const indexed = /* @__PURE__ */ new Map();
1519
- for (const branch of branches) indexed.set(branch.intent, branch);
1520
- const mergedKeys = /* @__PURE__ */ new Map();
1521
- for (const intent of intentsOrder) {
1522
- const branch = indexed.get(intent);
1523
- if (!branch || branch.error) continue;
1524
- const entry = this.entries.get(intent);
1525
- const isStreamModeAgent = entry?.type === "agent" && entry.mode === "stream";
1526
- if (!(entry?.type === "callback" || entry && entry.output !== void 0 || isStreamModeAgent)) continue;
1527
- const slice = branch.output;
1528
- if (!slice || typeof slice !== "object" || Array.isArray(slice)) {
1529
- if (slice !== void 0) this.logger.warn(this.logModule, "state.merge.skip", `intent "${intent}" output is not a mergeable object — skipping state merge`, {
1530
- intent,
1531
- type: typeof slice
1532
- });
1533
- continue;
1534
- }
1535
- for (const [key, value] of Object.entries(slice)) {
1536
- const previousOwner = mergedKeys.get(key);
1537
- if (previousOwner !== void 0 && previousOwner !== intent) this.logger.warn(this.logModule, "state.merge.conflict", `state key "${key}" written by both "${previousOwner}" and "${intent}" — last-in-decision-array wins (Q15)`, {
1538
- key,
1539
- previousOwner,
1540
- currentIntent: intent
1541
- });
1542
- this.state[key] = value;
1543
- mergedKeys.set(key, intent);
1544
- }
1545
- }
1546
- }
1547
- /**
1548
- * Merge the iteration's accumulated `currentArtifacts` bag into
1549
- * supervisor state (Phase 5 / decisions §35). Runs once per
1550
- * iteration after branch slices land and before evaluate.
1551
- *
1552
- * Order of operations:
1553
- *
1554
- * 1. **Empty-bag fast path** — if no tool wrote anything, skip
1555
- * validation and merge entirely; reset the bag for the next
1556
- * iteration is also a no-op (already empty).
1557
- * 2. **Schema validation** — when `config.artifactsSchema` is set,
1558
- * validate the bag against it. Failure aborts the iteration via
1559
- * a thrown `SchemaValidationError`; the iteration loop's outer
1560
- * catch surfaces it on `result.error`. Validation is opt-in
1561
- * (no schema → no validation cost).
1562
- * 3. **Merge** — `config.finalizeArtifacts` when supplied, else
1563
- * auto-spread `state = { ...state, ...artifacts }`. Replace
1564
- * semantics under auto-spread; `finalizeArtifacts` carries
1565
- * full responsibility for concat / dedupe / cross-iteration
1566
- * accumulation when configured.
1567
- * 4. **Reset** — `currentArtifacts = {}`. The next iteration's
1568
- * tool calls start with a fresh empty bag; long runs never
1569
- * accumulate raw artifacts here.
1570
- */
1571
- async mergeArtifactsIntoState() {
1572
- const artifacts = this.currentArtifacts;
1573
- const keys = Object.keys(artifacts);
1574
- this.capturedIterationArtifacts = Object.freeze({ ...artifacts });
1575
- if (keys.length === 0) return;
1576
- const schema = this.config.artifactsSchema;
1577
- if (schema) {
1578
- const validation = await schema["~standard"].validate(artifacts);
1579
- if (validation.issues) throw new SchemaValidationError(`supervisor "${this.config.name}": iteration ${this.iteration} artifacts failed validation: ${validation.issues.map((issue) => issue.message).join("; ")}`, {
1580
- issues: validation.issues,
1581
- context: { iteration: this.iteration }
1582
- });
1583
- }
1584
- const finalize = this.config.finalizeArtifacts;
1585
- if (finalize) {
1586
- const merged = finalize(this.state, artifacts);
1587
- for (const key of Object.keys(this.state)) if (!(key in merged)) delete this.state[key];
1588
- for (const [key, value] of Object.entries(merged)) this.state[key] = value;
1589
- } else for (const [key, value] of Object.entries(artifacts)) this.state[key] = value;
1590
- this.currentArtifacts = {};
1591
- }
1592
- /**
1593
- * Collect each branch's `intent.next(ctx)` directive after state
1594
- * merge (Stage 4d / Q24). Iterates `decision.intents` order so
1595
- * union resolution is deterministic.
1596
- *
1597
- * Rules:
1598
- * - Errored branch → silent (treated as if no `next` defined).
1599
- * - Branch with no `next` → silent; abstains (does NOT drag the
1600
- * iteration to the router).
1601
- * - Branch returns `END` → supreme; terminates immediately and
1602
- * discards other branches' opinions.
1603
- * - Branch returns `string` or `string[]` → contributes to the
1604
- * union of unique intent names. Validated against the
1605
- * supervisor's registry; unknown keys throw `SupervisorFailedError`.
1606
- * - All branches silent → returns `undefined`; caller falls back
1607
- * to router/route.
1608
- */
1609
- collectIntentNext(intentsOrder, branches) {
1610
- const indexed = /* @__PURE__ */ new Map();
1611
- for (const branch of branches) indexed.set(branch.intent, branch);
1612
- const collected = [];
1613
- const seen = /* @__PURE__ */ new Set();
1614
- for (const intent of intentsOrder) {
1615
- const branch = indexed.get(intent);
1616
- if (!branch || branch.error) continue;
1617
- const entry = this.entries.get(intent);
1618
- if (!entry?.next) continue;
1619
- const dispatchCtx = this.seedDispatchContext(intent, branch.input, new Set([intent]), []);
1620
- let raw;
1621
- try {
1622
- raw = entry.next(dispatchCtx);
1623
- } catch (thrown) {
1624
- throw new SupervisorFailedError(`intent "${intent}" \`next\` resolver threw: ${thrown instanceof Error ? thrown.message : String(thrown)}`, {
1625
- cause: thrown,
1626
- context: { intent }
1627
- });
1628
- }
1629
- if (raw === void 0) continue;
1630
- if (raw === "__warlock:end__") return { kind: "end" };
1631
- const proposed = Array.isArray(raw) ? raw : [raw];
1632
- for (const target of proposed) {
1633
- if (typeof target !== "string") throw new SupervisorFailedError(`intent "${intent}" \`next\` returned a non-string value`, { context: { intent } });
1634
- if (!this.entries.has(target)) throw new SupervisorFailedError(`intent "${intent}" \`next\` returned unknown intent "${target}"`, { context: {
1635
- intent,
1636
- target,
1637
- available: [...this.entries.keys()]
1638
- } });
1639
- if (!seen.has(target)) {
1640
- seen.add(target);
1641
- collected.push(target);
1642
- }
1643
- }
1644
- }
1645
- if (collected.length === 0) return;
1646
- return {
1647
- kind: "dispatch",
1648
- intents: collected
1649
- };
1650
- }
1651
- /**
1652
- * Finalize the supervisor result: validate accumulated state
1653
- * against the output schema and build the public `SupervisorResult`.
1654
- * Assemble-only — event emission and stream close happen in
1655
- * `run()` around this call.
1656
- */
1657
- async finalize() {
1658
- if (this.status === "completed" && !this.error) try {
1659
- this.data = await this.buildTypedData();
1660
- } catch (thrown) {
1661
- this.error = toAIError(thrown);
1662
- this.status = "failed";
1663
- this.terminatedBy = "error";
1664
- }
1665
- const endedAt = /* @__PURE__ */ new Date();
1666
- const finalStatus = this.status === "max-iterations" || this.status === "awaiting-input" || this.status === "awaiting-approval" ? "failed" : this.status;
1667
- await this.checkpoint(finalStatus);
1668
- const report = {
1669
- runId: this.runId,
1670
- rootRunId: this.runId,
1671
- name: this.config.name,
1672
- version: this.config.version,
1673
- type: this.config.reportType ?? "supervisor",
1674
- supervisorName: this.config.name,
1675
- signature: this.signature,
1676
- status: this.status,
1677
- ...this.error ? { error: this.error } : {},
1678
- terminatedBy: this.terminatedBy,
1679
- iterations: this.snapshots.length,
1680
- startedAt: this.startedAtIso,
1681
- endedAt: endedAt.toISOString(),
1682
- duration: performance.now() - this.startPerf,
1683
- cancelledAt: this.cancelledAtIso,
1684
- usage: this.usage,
1685
- children: this.childReports,
1686
- snapshots: this.snapshots,
1687
- ack: this.ackSnapshot,
1688
- classifier: this.classifierSnapshot
1689
- };
1690
- stampReportLineage(report, {
1691
- rootRunId: this.runId,
1692
- sessionId: this.options?.sessionId
1693
- });
1694
- return {
1695
- type: this.config.reportType ?? "supervisor",
1696
- data: this.data,
1697
- report,
1698
- usage: this.usage,
1699
- error: this.error
1700
- };
1701
- }
1702
- /**
1703
- * Build the typed `data` at finalize. Stage 4c — single mode:
1704
- *
1705
- * - When `config.output` is declared, validate the accumulated
1706
- * `state` against it and return the validated value (Q8).
1707
- * `result.data` always matches the schema, or `result.error`
1708
- * carries the validation issues.
1709
- * - When `config.output` is omitted, return the raw state object.
1710
- *
1711
- * Validation failure surfaces as `SchemaValidationError` on
1712
- * `result.error`; the run is still considered semantically
1713
- * "completed" (intents ran, evaluate said done) but the typed
1714
- * data slot is empty.
1715
- */
1716
- async buildTypedData() {
1717
- if (this.config.output) return validateOutput(this.config.output, this.state);
1718
- return this.state;
1719
- }
1720
- /**
1721
- * Record a snapshot for an iteration whose first decision was
1722
- * `END` — no dispatch, no evaluate, just the decision record. Keeps
1723
- * the snapshot log uniform so a late-route-to-END still appears in
1724
- * the forensic history rather than vanishing.
1725
- */
1726
- async recordTerminalDecisionSnapshot(decision, iterationStartedAt, iterationStart, iterationUsage) {
1727
- const snapshot = Object.freeze({
1728
- iteration: this.iteration,
1729
- result: {},
1730
- decision: {
1731
- source: decision.source,
1732
- next: decision.raw,
1733
- reasoning: decision.reasoning,
1734
- durationMs: decision.durationMs
1735
- },
1736
- state: { ...this.state },
1737
- artifacts: this.capturedIterationArtifacts,
1738
- startedAt: iterationStartedAt.toISOString(),
1739
- endedAt: (/* @__PURE__ */ new Date()).toISOString(),
1740
- duration: performance.now() - iterationStart,
1741
- usage: iterationUsage
1742
- });
1743
- this.snapshots.push(snapshot);
1744
- this.emit("supervisor.iteration.completed", {
1745
- iteration: this.iteration,
1746
- snapshot
1747
- });
1748
- await this.checkpoint("running");
1749
- }
1750
- /**
1751
- * Write the current run state to the configured KV store (if any).
1752
- * Persistence failures surface as `supervisor.error` events and
1753
- * logged warnings but never abort the run — checkpoint best-effort
1754
- * by design, matching `workflow` semantics.
1755
- */
1756
- async checkpoint(status) {
1757
- if (!(await persistSupervisorSnapshot({
1758
- config: this.config,
1759
- signature: this.signature,
1760
- runId: this.runId,
1761
- input: this.input,
1762
- startedAt: this.startedAtIso,
1763
- iteration: this.snapshots.length - 1,
1764
- snapshots: this.snapshots,
1765
- status
1766
- })).ok) this.logger.warn(this.logModule, "persist.failed", "snapshot persist failed", { runId: this.runId });
1767
- }
1768
- /**
1769
- * Between-iteration cancellation check. Called at the top of
1770
- * every iteration; signal abort here means the loop exits before
1771
- * any routing happens.
1772
- */
1773
- throwIfCancelled() {
1774
- if (this.options?.signal?.aborted) throw createCancelledError(this.options.signal);
1775
- }
1776
- /**
1777
- * Aggregate one usage record (typically a branch or a router call)
1778
- * into both the run-wide total and the iteration-local total.
1779
- */
1780
- aggregateUsage(iterationUsage, partial) {
1781
- if (!partial) return;
1782
- mergeUsage(this.usage, partial);
1783
- mergeUsage(iterationUsage, partial);
1784
- }
1785
- /**
1786
- * Fan an event out through the three-tier emitter AND mirror it
1787
- * into the stream controller when streaming. Event names map 1:1
1788
- * to stream event types so consumers iterating the stream see the
1789
- * exact same surface as `.on()` / `options.on` handlers.
1790
- */
1791
- emit(event, payload) {
1792
- const identity = {
1793
- runId: this.runId,
1794
- rootRunId: this.runId
1795
- };
1796
- const fullPayload = {
1797
- ...payload,
1798
- ...identity
1799
- };
1800
- this.emitter.emit(event, fullPayload, this.options?.on);
1801
- this.logEvent(event, fullPayload);
1802
- if (this.streamController) this.streamController.push({
1803
- type: event,
1804
- ...fullPayload
1805
- });
1806
- }
1807
- logEvent(event, payload) {
1808
- const action = event.replace(/^supervisor\./, "");
1809
- switch (event) {
1810
- case "supervisor.starting":
1811
- this.logger.info(this.logModule, action, "supervisor starting", { runId: this.runId });
1812
- return;
1813
- case "supervisor.iteration.starting":
1814
- this.logger.debug(this.logModule, action, "iteration starting", { iteration: payload.iteration });
1815
- return;
1816
- case "supervisor.router.decided":
1817
- this.logger.debug(this.logModule, action, "router decided", {
1818
- iteration: payload.iteration,
1819
- next: payload.next
1820
- });
1821
- return;
1822
- case "supervisor.agent.completed": {
1823
- const typed = payload;
1824
- this.logger.success(this.logModule, action, `branch "${typed.intent}" done`, {
1825
- duration: typed.duration,
1826
- usage: typed.usage
1827
- });
1828
- return;
1829
- }
1830
- case "supervisor.agent.failed": {
1831
- const typed = payload;
1832
- this.logger.warn(this.logModule, action, `branch "${typed.intent}" failed`, {
1833
- code: typed.error.code,
1834
- message: typed.error.message
1835
- });
1836
- return;
1837
- }
1838
- case "supervisor.error": {
1839
- const { error } = payload;
1840
- this.logger.error(this.logModule, action, error.message, { code: error.code });
1841
- return;
1842
- }
1843
- case "supervisor.cancelled": {
1844
- const typed = payload;
1845
- this.logger.warn(this.logModule, action, "supervisor cancelled", {
1846
- cancelledAt: typed.cancelledAt,
1847
- reason: typed.reason
1848
- });
1849
- return;
1850
- }
1851
- case "supervisor.iteration.completed":
1852
- this.logger.debug(this.logModule, action, "iteration completed", { iteration: payload.iteration });
1853
- return;
1854
- default: return;
1855
- }
1856
- }
1857
- };
1858
- function indexByIntent(branches) {
1859
- const indexed = {};
1860
- for (const branch of branches) indexed[branch.intent] = branch;
1861
- return indexed;
1862
- }
1863
- function indexBranchesForEvaluate(branches) {
1864
- const indexed = {};
1865
- for (const branch of branches) indexed[branch.intent] = {
1866
- output: branch.output,
1867
- input: branch.input,
1868
- usage: branch.usage,
1869
- durationMs: branch.duration,
1870
- error: branch.error
1871
- };
1872
- return indexed;
1873
- }
1874
- function normalizeReassign(reassignTo) {
1875
- if (!reassignTo) return [];
1876
- if (Array.isArray(reassignTo)) return reassignTo;
1877
- return [reassignTo];
1878
- }
1879
- function toAIError(thrown) {
1880
- if (thrown instanceof AIError) return thrown;
1881
- return new SupervisorFailedError(thrown instanceof Error ? thrown.message : String(thrown), { cause: thrown });
1882
- }
1883
- /**
1884
- * Sum a list of child `BaseReport.usage` values. Callbacks
1885
- * themselves contribute zero own-cost (they're dev code, not LLM
1886
- * calls); their report's `usage` equals the sum of whatever
1887
- * agents / workflows / nested callbacks they dispatched via
1888
- * `ctx.intents.X.execute()`. Mirrors `compositeAsTool` semantics.
1889
- */
1890
- function aggregateChildUsage(children) {
1891
- const total = {
1892
- input: 0,
1893
- output: 0,
1894
- total: 0
1895
- };
1896
- for (const child of children) mergeUsage(total, child.usage);
1897
- return total;
1898
- }
1899
- /**
1900
- * Best-effort stringification for the snapshot's `input` field when
1901
- * a callback intent's resolved input is a non-string value. Falls
1902
- * back to a typed placeholder if `JSON.stringify` throws (circular
1903
- * refs, BigInt, etc.) so a snapshot write never fails on its own.
1904
- */
1905
- function safeStringify(value) {
1906
- if (value === void 0) return "undefined";
1907
- try {
1908
- return JSON.stringify(value);
1909
- } catch {
1910
- return `[unserializable: ${typeof value}]`;
1911
- }
1912
- }
1913
- async function validateOutput(schema, value) {
1914
- const validation = await schema["~standard"].validate(value);
1915
- if (validation.issues) throw new SchemaValidationError(validation.issues.map((issue) => issue.message).join("; "), { issues: validation.issues });
1916
- return validation.value;
1917
- }
1918
-
1919
- //#endregion
1920
- export { SupervisorExecution };
1921
- //# sourceMappingURL=execution.mjs.map