@warlock.js/ai 4.2.11 → 4.4.0

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 (432) hide show
  1. package/CHANGELOG.md +68 -1
  2. package/cjs/index.cjs +10155 -4626
  3. package/cjs/index.cjs.map +1 -1
  4. package/cjs/magic-string.es-BtxW4VqG.cjs +1015 -0
  5. package/cjs/magic-string.es-BtxW4VqG.cjs.map +1 -0
  6. package/cjs/matcher-logic-SBnzYohQ.cjs +217 -0
  7. package/cjs/matcher-logic-SBnzYohQ.cjs.map +1 -0
  8. package/cjs/matchers-BBh3gyB-.cjs +13739 -0
  9. package/cjs/matchers-BBh3gyB-.cjs.map +1 -0
  10. package/esm/agent/agent-config.type.d.mts +19 -6
  11. package/esm/agent/agent-config.type.d.mts.map +1 -1
  12. package/esm/agent/agent.d.mts.map +1 -1
  13. package/esm/agent/agent.mjs +17 -6
  14. package/esm/agent/agent.mjs.map +1 -1
  15. package/esm/agent/index.d.mts +2 -1
  16. package/esm/agent/index.mjs +1 -0
  17. package/esm/agent/spawn-sub-agent.d.mts +87 -0
  18. package/esm/agent/spawn-sub-agent.d.mts.map +1 -0
  19. package/esm/agent/spawn-sub-agent.mjs +68 -0
  20. package/esm/agent/spawn-sub-agent.mjs.map +1 -0
  21. package/esm/ai.d.mts +58 -3
  22. package/esm/ai.d.mts.map +1 -1
  23. package/esm/ai.mjs +58 -3
  24. package/esm/ai.mjs.map +1 -1
  25. package/esm/batch/batch.d.mts +43 -0
  26. package/esm/batch/batch.d.mts.map +1 -0
  27. package/esm/batch/batch.mjs +179 -0
  28. package/esm/batch/batch.mjs.map +1 -0
  29. package/esm/batch/batch.type.d.mts +144 -0
  30. package/esm/batch/batch.type.d.mts.map +1 -0
  31. package/esm/batch/index.mjs +3 -0
  32. package/esm/batch/run-batch-item.mjs +100 -0
  33. package/esm/batch/run-batch-item.mjs.map +1 -0
  34. package/esm/batch/run-with-concurrency.mjs +39 -0
  35. package/esm/batch/run-with-concurrency.mjs.map +1 -0
  36. package/esm/checkpoint/index.d.mts +3 -0
  37. package/esm/checkpoint/memory.d.mts +21 -0
  38. package/esm/checkpoint/memory.d.mts.map +1 -0
  39. package/esm/checkpoint/memory.mjs +0 -0
  40. package/esm/checkpoint/memory.mjs.map +1 -0
  41. package/esm/checkpoint/pg.d.mts +37 -0
  42. package/esm/checkpoint/pg.d.mts.map +1 -0
  43. package/esm/checkpoint/pg.mjs +265 -0
  44. package/esm/checkpoint/pg.mjs.map +1 -0
  45. package/esm/checkpoint/redis.d.mts +39 -0
  46. package/esm/checkpoint/redis.d.mts.map +1 -0
  47. package/esm/checkpoint/redis.mjs +200 -0
  48. package/esm/checkpoint/redis.mjs.map +1 -0
  49. package/esm/config.d.mts +61 -14
  50. package/esm/config.d.mts.map +1 -1
  51. package/esm/config.mjs +25 -6
  52. package/esm/config.mjs.map +1 -1
  53. package/esm/contracts/agent/agent.contract.d.mts +43 -0
  54. package/esm/contracts/agent/agent.contract.d.mts.map +1 -1
  55. package/esm/contracts/agent/eval.type.d.mts +143 -0
  56. package/esm/contracts/agent/eval.type.d.mts.map +1 -0
  57. package/esm/contracts/agent/index.d.mts +1 -0
  58. package/esm/contracts/events/supervisor-events.type.d.mts +3 -3
  59. package/esm/contracts/fallback-model.contract.d.mts +65 -0
  60. package/esm/contracts/fallback-model.contract.d.mts.map +1 -0
  61. package/esm/contracts/index.d.mts +32 -12
  62. package/esm/contracts/memory/index.d.mts +4 -0
  63. package/esm/contracts/memory/memory-config.type.d.mts +150 -0
  64. package/esm/contracts/memory/memory-config.type.d.mts.map +1 -0
  65. package/esm/contracts/memory/memory-item.type.d.mts +64 -0
  66. package/esm/contracts/memory/memory-item.type.d.mts.map +1 -0
  67. package/esm/contracts/memory/memory.contract.d.mts +87 -0
  68. package/esm/contracts/memory/memory.contract.d.mts.map +1 -0
  69. package/esm/contracts/memory/recall-options.type.d.mts +33 -0
  70. package/esm/contracts/memory/recall-options.type.d.mts.map +1 -0
  71. package/esm/contracts/middleware/index.d.mts +2 -2
  72. package/esm/contracts/middleware/middleware-context.type.d.mts +42 -2
  73. package/esm/contracts/middleware/middleware-context.type.d.mts.map +1 -1
  74. package/esm/contracts/middleware/middleware.contract.d.mts +46 -2
  75. package/esm/contracts/middleware/middleware.contract.d.mts.map +1 -1
  76. package/esm/contracts/model.contract.d.mts +63 -2
  77. package/esm/contracts/model.contract.d.mts.map +1 -1
  78. package/esm/contracts/orchestrator/checkpoint-store.contract.d.mts +91 -0
  79. package/esm/contracts/orchestrator/checkpoint-store.contract.d.mts.map +1 -0
  80. package/esm/contracts/orchestrator/index.d.mts +8 -0
  81. package/esm/contracts/orchestrator/orchestrator-commands.type.d.mts +43 -0
  82. package/esm/contracts/orchestrator/orchestrator-commands.type.d.mts.map +1 -0
  83. package/esm/contracts/orchestrator/orchestrator-config.type.d.mts +170 -0
  84. package/esm/contracts/orchestrator/orchestrator-config.type.d.mts.map +1 -0
  85. package/esm/contracts/orchestrator/orchestrator-event.type.d.mts +118 -0
  86. package/esm/contracts/orchestrator/orchestrator-event.type.d.mts.map +1 -0
  87. package/esm/contracts/orchestrator/orchestrator-execute-options.type.d.mts +44 -0
  88. package/esm/contracts/orchestrator/orchestrator-execute-options.type.d.mts.map +1 -0
  89. package/esm/contracts/orchestrator/orchestrator.contract.d.mts +129 -0
  90. package/esm/contracts/orchestrator/orchestrator.contract.d.mts.map +1 -0
  91. package/esm/contracts/orchestrator/session.contract.d.mts +26 -0
  92. package/esm/contracts/orchestrator/session.contract.d.mts.map +1 -0
  93. package/esm/contracts/orchestrator/snapshot-store.contract.d.mts +89 -0
  94. package/esm/contracts/orchestrator/snapshot-store.contract.d.mts.map +1 -0
  95. package/esm/contracts/planner/index.d.mts +6 -0
  96. package/esm/contracts/planner/planner-capability.type.d.mts +39 -0
  97. package/esm/contracts/planner/planner-capability.type.d.mts.map +1 -0
  98. package/esm/contracts/planner/planner-config.type.d.mts +78 -0
  99. package/esm/contracts/planner/planner-config.type.d.mts.map +1 -0
  100. package/esm/contracts/planner/planner-execute-options.type.d.mts +43 -0
  101. package/esm/contracts/planner/planner-execute-options.type.d.mts.map +1 -0
  102. package/esm/contracts/planner/planner-plan.type.d.mts +48 -0
  103. package/esm/contracts/planner/planner-plan.type.d.mts.map +1 -0
  104. package/esm/contracts/planner/planner-result.type.d.mts +88 -0
  105. package/esm/contracts/planner/planner-result.type.d.mts.map +1 -0
  106. package/esm/contracts/planner/planner.contract.d.mts +60 -0
  107. package/esm/contracts/planner/planner.contract.d.mts.map +1 -0
  108. package/esm/contracts/result/base-report.type.d.mts +7 -2
  109. package/esm/contracts/result/base-report.type.d.mts.map +1 -1
  110. package/esm/contracts/result/base-report.type.mjs.map +1 -1
  111. package/esm/contracts/result/index.d.mts +2 -1
  112. package/esm/contracts/result/model-pricing.type.d.mts +10 -0
  113. package/esm/contracts/result/model-pricing.type.d.mts.map +1 -1
  114. package/esm/contracts/result/orchestrator-result.type.d.mts +143 -0
  115. package/esm/contracts/result/orchestrator-result.type.d.mts.map +1 -0
  116. package/esm/contracts/result/session-send-result.type.d.mts +12 -3
  117. package/esm/contracts/result/session-send-result.type.d.mts.map +1 -1
  118. package/esm/contracts/result/supervisor-result.type.d.mts +2 -2
  119. package/esm/contracts/result/supervisor-result.type.d.mts.map +1 -1
  120. package/esm/contracts/result/tool-call.type.d.mts +2 -2
  121. package/esm/contracts/result/tool-call.type.d.mts.map +1 -1
  122. package/esm/contracts/result/usage.type.d.mts +24 -0
  123. package/esm/contracts/result/usage.type.d.mts.map +1 -1
  124. package/esm/contracts/result/workflow-result.type.d.mts +1 -1
  125. package/esm/contracts/result/workflow-result.type.d.mts.map +1 -1
  126. package/esm/contracts/sdk-adapter.contract.d.mts +1 -1
  127. package/esm/contracts/supervisor/dispatch-context.type.d.mts +3 -3
  128. package/esm/contracts/supervisor/evaluate-context.type.d.mts +1 -1
  129. package/esm/contracts/supervisor/index.d.mts +5 -5
  130. package/esm/contracts/supervisor/route-context.type.d.mts +2 -2
  131. package/esm/contracts/supervisor/supervisor-config.type.d.mts +55 -13
  132. package/esm/contracts/supervisor/supervisor-config.type.d.mts.map +1 -1
  133. package/esm/contracts/supervisor/supervisor-snapshot.type.d.mts +1 -1
  134. package/esm/contracts/supervisor/supervisor.contract.d.mts +9 -2
  135. package/esm/contracts/supervisor/supervisor.contract.d.mts.map +1 -1
  136. package/esm/contracts/workflow/index.d.mts +2 -2
  137. package/esm/contracts/workflow/workflow.contract.d.mts +28 -7
  138. package/esm/contracts/workflow/workflow.contract.d.mts.map +1 -1
  139. package/esm/errors/error-code.type.d.mts +1 -1
  140. package/esm/errors/index.d.mts +7 -0
  141. package/esm/errors/index.mjs +7 -0
  142. package/esm/errors/orchestrator-cancelled-error.d.mts +32 -0
  143. package/esm/errors/orchestrator-cancelled-error.d.mts.map +1 -0
  144. package/esm/errors/orchestrator-cancelled-error.mjs +31 -0
  145. package/esm/errors/orchestrator-cancelled-error.mjs.map +1 -0
  146. package/esm/errors/orchestrator-config-error.d.mts +26 -0
  147. package/esm/errors/orchestrator-config-error.d.mts.map +1 -0
  148. package/esm/errors/orchestrator-config-error.mjs +30 -0
  149. package/esm/errors/orchestrator-config-error.mjs.map +1 -0
  150. package/esm/errors/orchestrator-drift-error.d.mts +38 -0
  151. package/esm/errors/orchestrator-drift-error.d.mts.map +1 -0
  152. package/esm/errors/orchestrator-drift-error.mjs +37 -0
  153. package/esm/errors/orchestrator-drift-error.mjs.map +1 -0
  154. package/esm/errors/orchestrator-failed-error.d.mts +33 -0
  155. package/esm/errors/orchestrator-failed-error.d.mts.map +1 -0
  156. package/esm/errors/orchestrator-failed-error.mjs +36 -0
  157. package/esm/errors/orchestrator-failed-error.mjs.map +1 -0
  158. package/esm/errors/planner-cancelled-error.d.mts +33 -0
  159. package/esm/errors/planner-cancelled-error.d.mts.map +1 -0
  160. package/esm/errors/planner-cancelled-error.mjs +29 -0
  161. package/esm/errors/planner-cancelled-error.mjs.map +1 -0
  162. package/esm/errors/planner-failed-error.d.mts +40 -0
  163. package/esm/errors/planner-failed-error.d.mts.map +1 -0
  164. package/esm/errors/planner-failed-error.mjs +37 -0
  165. package/esm/errors/planner-failed-error.mjs.map +1 -0
  166. package/esm/errors/planner-plan-invalid-error.d.mts +21 -0
  167. package/esm/errors/planner-plan-invalid-error.d.mts.map +1 -0
  168. package/esm/errors/planner-plan-invalid-error.mjs +25 -0
  169. package/esm/errors/planner-plan-invalid-error.mjs.map +1 -0
  170. package/esm/eval/eval-runner.d.mts +17 -0
  171. package/esm/eval/eval-runner.d.mts.map +1 -0
  172. package/esm/eval/eval-runner.mjs +121 -0
  173. package/esm/eval/eval-runner.mjs.map +1 -0
  174. package/esm/eval/index.d.mts +29 -0
  175. package/esm/eval/index.d.mts.map +1 -0
  176. package/esm/eval/index.mjs +30 -0
  177. package/esm/eval/index.mjs.map +1 -0
  178. package/esm/eval/judge-scorer.d.mts +21 -0
  179. package/esm/eval/judge-scorer.d.mts.map +1 -0
  180. package/esm/eval/judge-scorer.mjs +87 -0
  181. package/esm/eval/judge-scorer.mjs.map +1 -0
  182. package/esm/eval/scorers.d.mts +50 -0
  183. package/esm/eval/scorers.d.mts.map +1 -0
  184. package/esm/eval/scorers.mjs +101 -0
  185. package/esm/eval/scorers.mjs.map +1 -0
  186. package/esm/index.d.mts +95 -30
  187. package/esm/index.mjs +66 -22
  188. package/esm/memory/derive-id.mjs +24 -0
  189. package/esm/memory/derive-id.mjs.map +1 -0
  190. package/esm/memory/episodic-memory.mjs +106 -0
  191. package/esm/memory/episodic-memory.mjs.map +1 -0
  192. package/esm/memory/index.d.mts +5 -0
  193. package/esm/memory/memory.d.mts +42 -0
  194. package/esm/memory/memory.d.mts.map +1 -0
  195. package/esm/memory/memory.mjs +166 -0
  196. package/esm/memory/memory.mjs.map +1 -0
  197. package/esm/memory/procedural-memory.mjs +103 -0
  198. package/esm/memory/procedural-memory.mjs.map +1 -0
  199. package/esm/memory/semantic-memory.mjs +80 -0
  200. package/esm/memory/semantic-memory.mjs.map +1 -0
  201. package/esm/memory/working-memory.mjs +62 -0
  202. package/esm/memory/working-memory.mjs.map +1 -0
  203. package/esm/middleware/builtins/budget-contract.type.d.mts +126 -0
  204. package/esm/middleware/builtins/budget-contract.type.d.mts.map +1 -0
  205. package/esm/middleware/builtins/budget.d.mts +71 -1
  206. package/esm/middleware/builtins/budget.d.mts.map +1 -1
  207. package/esm/middleware/builtins/budget.mjs +119 -4
  208. package/esm/middleware/builtins/budget.mjs.map +1 -1
  209. package/esm/middleware/builtins/semantic-cache.d.mts +1 -1
  210. package/esm/middleware/index.d.mts +2 -1
  211. package/esm/middleware/index.mjs +1 -1
  212. package/esm/middleware/pipeline.d.mts +9 -6
  213. package/esm/middleware/pipeline.d.mts.map +1 -1
  214. package/esm/middleware/pipeline.mjs.map +1 -1
  215. package/esm/mock/index.d.mts +1 -0
  216. package/esm/mock/index.mjs +1 -0
  217. package/esm/mock/mock-router.d.mts +63 -0
  218. package/esm/mock/mock-router.d.mts.map +1 -0
  219. package/esm/mock/mock-router.mjs +58 -0
  220. package/esm/mock/mock-router.mjs.map +1 -0
  221. package/esm/model/fallback-model.d.mts +45 -0
  222. package/esm/model/fallback-model.d.mts.map +1 -0
  223. package/esm/model/fallback-model.mjs +218 -0
  224. package/esm/model/fallback-model.mjs.map +1 -0
  225. package/esm/model/index.d.mts +2 -0
  226. package/esm/model/index.mjs +3 -0
  227. package/esm/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs +78 -0
  228. package/esm/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs.map +1 -0
  229. package/esm/node_modules/@vitest/expect/dist/index.mjs +1473 -0
  230. package/esm/node_modules/@vitest/expect/dist/index.mjs.map +1 -0
  231. package/esm/node_modules/@vitest/pretty-format/dist/index.mjs +888 -0
  232. package/esm/node_modules/@vitest/pretty-format/dist/index.mjs.map +1 -0
  233. package/esm/node_modules/@vitest/runner/dist/chunk-artifact.mjs +1533 -0
  234. package/esm/node_modules/@vitest/runner/dist/chunk-artifact.mjs.map +1 -0
  235. package/esm/node_modules/@vitest/runner/dist/index.mjs +3 -0
  236. package/esm/node_modules/@vitest/runner/dist/utils.mjs +3 -0
  237. package/esm/node_modules/@vitest/snapshot/dist/index.mjs +922 -0
  238. package/esm/node_modules/@vitest/snapshot/dist/index.mjs.map +1 -0
  239. package/esm/node_modules/@vitest/spy/dist/index.mjs +386 -0
  240. package/esm/node_modules/@vitest/spy/dist/index.mjs.map +1 -0
  241. package/esm/node_modules/@vitest/utils/dist/chunk-pathe.M-eThtNZ.mjs +82 -0
  242. package/esm/node_modules/@vitest/utils/dist/chunk-pathe.M-eThtNZ.mjs.map +1 -0
  243. package/esm/node_modules/@vitest/utils/dist/diff.mjs +1357 -0
  244. package/esm/node_modules/@vitest/utils/dist/diff.mjs.map +1 -0
  245. package/esm/node_modules/@vitest/utils/dist/display.mjs +559 -0
  246. package/esm/node_modules/@vitest/utils/dist/display.mjs.map +1 -0
  247. package/esm/node_modules/@vitest/utils/dist/error.mjs +38 -0
  248. package/esm/node_modules/@vitest/utils/dist/error.mjs.map +1 -0
  249. package/esm/node_modules/@vitest/utils/dist/helpers.mjs +181 -0
  250. package/esm/node_modules/@vitest/utils/dist/helpers.mjs.map +1 -0
  251. package/esm/node_modules/@vitest/utils/dist/offset.mjs +27 -0
  252. package/esm/node_modules/@vitest/utils/dist/offset.mjs.map +1 -0
  253. package/esm/node_modules/@vitest/utils/dist/serialize.mjs +77 -0
  254. package/esm/node_modules/@vitest/utils/dist/serialize.mjs.map +1 -0
  255. package/esm/node_modules/@vitest/utils/dist/source-map.mjs +374 -0
  256. package/esm/node_modules/@vitest/utils/dist/source-map.mjs.map +1 -0
  257. package/esm/node_modules/@vitest/utils/dist/timers.mjs +37 -0
  258. package/esm/node_modules/@vitest/utils/dist/timers.mjs.map +1 -0
  259. package/esm/node_modules/chai/index.mjs +2973 -0
  260. package/esm/node_modules/chai/index.mjs.map +1 -0
  261. package/esm/node_modules/magic-string/dist/magic-string.es.mjs +940 -0
  262. package/esm/node_modules/magic-string/dist/magic-string.es.mjs.map +1 -0
  263. package/esm/node_modules/tinyrainbow/dist/index.mjs +87 -0
  264. package/esm/node_modules/tinyrainbow/dist/index.mjs.map +1 -0
  265. package/esm/node_modules/vitest/dist/chunks/_commonjsHelpers.D26ty3Ew.mjs +6 -0
  266. package/esm/node_modules/vitest/dist/chunks/_commonjsHelpers.D26ty3Ew.mjs.map +1 -0
  267. package/esm/node_modules/vitest/dist/chunks/rpc.MzXet3jl.mjs +52 -0
  268. package/esm/node_modules/vitest/dist/chunks/rpc.MzXet3jl.mjs.map +1 -0
  269. package/esm/node_modules/vitest/dist/chunks/test.DNmyFkvJ.mjs +2697 -0
  270. package/esm/node_modules/vitest/dist/chunks/test.DNmyFkvJ.mjs.map +1 -0
  271. package/esm/node_modules/vitest/dist/chunks/utils.BX5Fg8C4.mjs +45 -0
  272. package/esm/node_modules/vitest/dist/chunks/utils.BX5Fg8C4.mjs.map +1 -0
  273. package/esm/orchestrator/as-tool.d.mts +42 -0
  274. package/esm/orchestrator/as-tool.d.mts.map +1 -0
  275. package/esm/orchestrator/as-tool.mjs +98 -0
  276. package/esm/orchestrator/as-tool.mjs.map +1 -0
  277. package/esm/orchestrator/checkpoint.mjs +75 -0
  278. package/esm/orchestrator/checkpoint.mjs.map +1 -0
  279. package/esm/orchestrator/commands.d.mts +38 -0
  280. package/esm/orchestrator/commands.d.mts.map +1 -0
  281. package/esm/orchestrator/commands.mjs +34 -0
  282. package/esm/orchestrator/commands.mjs.map +1 -0
  283. package/esm/orchestrator/compaction.mjs +206 -0
  284. package/esm/orchestrator/compaction.mjs.map +1 -0
  285. package/esm/orchestrator/dispatch.mjs +171 -0
  286. package/esm/orchestrator/dispatch.mjs.map +1 -0
  287. package/esm/orchestrator/emitter-port.type.d.mts +31 -0
  288. package/esm/orchestrator/emitter-port.type.d.mts.map +1 -0
  289. package/esm/orchestrator/emitter.d.mts +56 -0
  290. package/esm/orchestrator/emitter.d.mts.map +1 -0
  291. package/esm/orchestrator/emitter.mjs +85 -0
  292. package/esm/orchestrator/emitter.mjs.map +1 -0
  293. package/esm/orchestrator/engine-context.type.d.mts +56 -0
  294. package/esm/orchestrator/engine-context.type.d.mts.map +1 -0
  295. package/esm/orchestrator/execution.d.mts +116 -0
  296. package/esm/orchestrator/execution.d.mts.map +1 -0
  297. package/esm/orchestrator/execution.mjs +406 -0
  298. package/esm/orchestrator/execution.mjs.map +1 -0
  299. package/esm/orchestrator/index.d.mts +8 -0
  300. package/esm/orchestrator/index.mjs +10 -0
  301. package/esm/orchestrator/load.mjs +49 -0
  302. package/esm/orchestrator/load.mjs.map +1 -0
  303. package/esm/orchestrator/lock.mjs +75 -0
  304. package/esm/orchestrator/lock.mjs.map +1 -0
  305. package/esm/orchestrator/memory.d.mts +84 -0
  306. package/esm/orchestrator/memory.d.mts.map +1 -0
  307. package/esm/orchestrator/memory.mjs +141 -0
  308. package/esm/orchestrator/memory.mjs.map +1 -0
  309. package/esm/orchestrator/orchestrator-stream.d.mts +42 -0
  310. package/esm/orchestrator/orchestrator-stream.d.mts.map +1 -0
  311. package/esm/orchestrator/orchestrator-stream.mjs +98 -0
  312. package/esm/orchestrator/orchestrator-stream.mjs.map +1 -0
  313. package/esm/orchestrator/orchestrator.d.mts +38 -0
  314. package/esm/orchestrator/orchestrator.d.mts.map +1 -0
  315. package/esm/orchestrator/orchestrator.mjs +173 -0
  316. package/esm/orchestrator/orchestrator.mjs.map +1 -0
  317. package/esm/orchestrator/resume.mjs +74 -0
  318. package/esm/orchestrator/resume.mjs.map +1 -0
  319. package/esm/orchestrator/signature.d.mts +40 -0
  320. package/esm/orchestrator/signature.d.mts.map +1 -0
  321. package/esm/orchestrator/signature.mjs +120 -0
  322. package/esm/orchestrator/signature.mjs.map +1 -0
  323. package/esm/orchestrator/window.mjs +56 -0
  324. package/esm/orchestrator/window.mjs.map +1 -0
  325. package/esm/planner/index.d.mts +5 -0
  326. package/esm/planner/index.mjs +6 -0
  327. package/esm/planner/plan-prompt.d.mts +17 -0
  328. package/esm/planner/plan-prompt.d.mts.map +1 -0
  329. package/esm/planner/plan-prompt.mjs +30 -0
  330. package/esm/planner/plan-prompt.mjs.map +1 -0
  331. package/esm/planner/plan-schema.d.mts +27 -0
  332. package/esm/planner/plan-schema.d.mts.map +1 -0
  333. package/esm/planner/plan-schema.mjs +120 -0
  334. package/esm/planner/plan-schema.mjs.map +1 -0
  335. package/esm/planner/planner-run.d.mts +23 -0
  336. package/esm/planner/planner-run.d.mts.map +1 -0
  337. package/esm/planner/planner-run.mjs +344 -0
  338. package/esm/planner/planner-run.mjs.map +1 -0
  339. package/esm/planner/planner.d.mts +37 -0
  340. package/esm/planner/planner.d.mts.map +1 -0
  341. package/esm/planner/planner.mjs +120 -0
  342. package/esm/planner/planner.mjs.map +1 -0
  343. package/esm/planner/signature.d.mts +18 -0
  344. package/esm/planner/signature.d.mts.map +1 -0
  345. package/esm/planner/signature.mjs +27 -0
  346. package/esm/planner/signature.mjs.map +1 -0
  347. package/esm/snapshot/index.d.mts +3 -0
  348. package/esm/snapshot/memory.d.mts +26 -0
  349. package/esm/snapshot/memory.d.mts.map +1 -0
  350. package/esm/snapshot/memory.mjs +81 -0
  351. package/esm/snapshot/memory.mjs.map +1 -0
  352. package/esm/snapshot/pg.d.mts +41 -0
  353. package/esm/snapshot/pg.d.mts.map +1 -0
  354. package/esm/snapshot/pg.mjs +146 -0
  355. package/esm/snapshot/pg.mjs.map +1 -0
  356. package/esm/snapshot/redis.d.mts +42 -0
  357. package/esm/snapshot/redis.d.mts.map +1 -0
  358. package/esm/snapshot/redis.mjs +101 -0
  359. package/esm/snapshot/redis.mjs.map +1 -0
  360. package/esm/supervisor/as-tool.d.mts +0 -6
  361. package/esm/supervisor/as-tool.d.mts.map +1 -1
  362. package/esm/supervisor/as-tool.mjs +0 -6
  363. package/esm/supervisor/as-tool.mjs.map +1 -1
  364. package/esm/supervisor/execution.d.mts +43 -8
  365. package/esm/supervisor/execution.d.mts.map +1 -1
  366. package/esm/supervisor/execution.mjs +66 -16
  367. package/esm/supervisor/execution.mjs.map +1 -1
  368. package/esm/supervisor/fan-out.d.mts +65 -0
  369. package/esm/supervisor/fan-out.d.mts.map +1 -0
  370. package/esm/supervisor/fan-out.mjs +65 -0
  371. package/esm/supervisor/fan-out.mjs.map +1 -0
  372. package/esm/supervisor/index.d.mts +5 -3
  373. package/esm/supervisor/index.mjs +3 -1
  374. package/esm/supervisor/router-factory.d.mts +110 -0
  375. package/esm/supervisor/router-factory.d.mts.map +1 -0
  376. package/esm/supervisor/router-factory.mjs +141 -0
  377. package/esm/supervisor/router-factory.mjs.map +1 -0
  378. package/esm/supervisor/router-prompt.d.mts +1 -1
  379. package/esm/supervisor/snapshot.d.mts +4 -10
  380. package/esm/supervisor/snapshot.d.mts.map +1 -1
  381. package/esm/supervisor/snapshot.mjs +8 -16
  382. package/esm/supervisor/snapshot.mjs.map +1 -1
  383. package/esm/supervisor/supervisor.mjs +1 -0
  384. package/esm/supervisor/supervisor.mjs.map +1 -1
  385. package/esm/system-prompt/index.mjs +6 -0
  386. package/esm/system-prompt/system-prompt.d.mts +51 -3
  387. package/esm/system-prompt/system-prompt.d.mts.map +1 -1
  388. package/esm/system-prompt/system-prompt.mjs +52 -6
  389. package/esm/system-prompt/system-prompt.mjs.map +1 -1
  390. package/esm/testing/matcher-logic.d.mts +76 -0
  391. package/esm/testing/matcher-logic.d.mts.map +1 -0
  392. package/esm/testing/matcher-logic.mjs +144 -0
  393. package/esm/testing/matcher-logic.mjs.map +1 -0
  394. package/esm/testing/matchers.d.mts +48 -0
  395. package/esm/testing/matchers.d.mts.map +1 -0
  396. package/esm/testing/matchers.mjs +37 -0
  397. package/esm/testing/matchers.mjs.map +1 -0
  398. package/esm/testing/register-lazy.d.mts +20 -0
  399. package/esm/testing/register-lazy.d.mts.map +1 -0
  400. package/esm/testing/register-lazy.mjs +24 -0
  401. package/esm/testing/register-lazy.mjs.map +1 -0
  402. package/esm/tool/executable-as-tool.d.mts +87 -0
  403. package/esm/tool/executable-as-tool.d.mts.map +1 -0
  404. package/esm/tool/executable-as-tool.mjs +81 -0
  405. package/esm/tool/executable-as-tool.mjs.map +1 -0
  406. package/esm/tool/index.d.mts +2 -1
  407. package/esm/tool/index.mjs +1 -0
  408. package/esm/workflow/as-tool.mjs +0 -6
  409. package/esm/workflow/as-tool.mjs.map +1 -1
  410. package/esm/workflow/engine.mjs +2 -2
  411. package/esm/workflow/snapshot.mjs +13 -7
  412. package/esm/workflow/snapshot.mjs.map +1 -1
  413. package/esm/workflow/step-runner.mjs +1 -1
  414. package/esm/workflow/workflow.mjs +1 -0
  415. package/esm/workflow/workflow.mjs.map +1 -1
  416. package/llms-full.txt +947 -42
  417. package/llms.txt +13 -8
  418. package/package.json +3 -3
  419. package/skills/README.md +25 -5
  420. package/skills/ai-basics/SKILL.md +18 -7
  421. package/skills/ai-dx-helpers/SKILL.md +180 -0
  422. package/skills/attach-ai-middleware/SKILL.md +32 -3
  423. package/skills/handle-ai-errors/SKILL.md +20 -6
  424. package/skills/manage-ai-stores/SKILL.md +127 -0
  425. package/skills/persist-ai-data/SKILL.md +21 -10
  426. package/skills/pick-ai-provider/SKILL.md +46 -12
  427. package/skills/run-ai-agent/SKILL.md +51 -2
  428. package/skills/run-orchestrator/SKILL.md +198 -0
  429. package/skills/run-planner/SKILL.md +68 -0
  430. package/skills/run-supervisor/SKILL.md +47 -2
  431. package/skills/use-ai-memory/SKILL.md +124 -0
  432. package/skills/write-system-prompt/SKILL.md +14 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"spawn-sub-agent.mjs","names":[],"sources":["../../../../../../../@warlock.js/ai/src/agent/spawn-sub-agent.ts"],"sourcesContent":["import type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport type { AgentExecuteOptions } from \"../contracts/agent/agent-options.type\";\nimport type { AgentContract } from \"../contracts/agent/agent.contract\";\nimport type { AgentResult } from \"../contracts/result/agent-result.type\";\nimport type { ModelContract } from \"../contracts/model.contract\";\nimport type { SystemPromptContract } from \"../contracts/system-prompt.contract\";\nimport { budget, type BudgetOptions } from \"../middleware/builtins/budget\";\nimport type { AgentToolEntry } from \"../tool/executable-as-tool\";\nimport { agent } from \"./agent\";\n\n/**\n * Spec for `spawnSubAgent` — a one-shot agent invocation. `spawnSubAgent`\n * is a thin convenience wrapper: it builds a fresh `agent()` from this\n * spec, optionally attaches a `budget` middleware, runs the `task` once,\n * and returns the `AgentResult`. There is no separate \"sub-agent\" runtime\n * — a spawn is an ordinary new `agent()` instance, so it starts from an\n * empty conversation with its own tools/prompt exactly the way every\n * `agent()` does.\n *\n * `budget` is the one field that adds something a bare `agent()` config\n * doesn't already give you ergonomically: a first-class per-task\n * cost/token cap. When set, the spawn runs under a `budget` middleware\n * that aborts the moment a cap is crossed, so a delegated subtask cannot\n * overrun its allowance. (Equivalent to passing\n * `middleware: [budget(...)]` to a plain agent — this just promotes it to\n * a spec field.) Distinct from `maxTrips`, which caps round-trips, not spend.\n */\nexport type SpawnSubAgentSpec<TOutput = unknown> = {\n /** Stable identifier for the spawned agent. */\n name: string;\n /** The model the sub-agent runs against. */\n model: ModelContract;\n /** The subtask instruction handed to the sub-agent's `execute()`. */\n task: string;\n /** Optional system prompt scoping the sub-agent's behavior. */\n systemPrompt?: SystemPromptContract | string;\n /** Tools the spawned agent may call inside its own loop (a fresh agent, so not shared with the caller). */\n tools?: AgentToolEntry<unknown, unknown>[];\n /** Per-spawn round-trip cap. Forwarded to the agent. Defaults to the agent default. */\n maxTrips?: number;\n /**\n * Per-task budget. When set, the spawn runs under a `budget` middleware\n * that aborts once a cap (`maxTokens` / `maxCostUSD`) is crossed — a\n * spend ceiling scoped to this one subtask. Because each spawn is its\n * own `agent()` instance, that ledger starts fresh per spawn.\n */\n budget?: BudgetOptions;\n /** Structured-output schema validated into `result.data`. */\n output?: StandardSchemaV1<TOutput>;\n /** Cancellation handle threaded into the sub-agent run. */\n signal?: AbortSignal;\n /**\n * Session identifier propagated onto the sub-agent's report tree so\n * the spawned run groups under the parent's session in flat trace\n * queries.\n */\n sessionId?: string;\n};\n\n/**\n * Build a fresh agent, run a single subtask through it once, and return\n * the unified {@link AgentResult}. Equivalent to\n * `agent({ ...spec, middleware: spec.budget && [budget(spec.budget)] }).execute(spec.task, { output, signal, sessionId })`.\n *\n * **Role.** A general-purpose \"build, run, discard\" primitive: a caller\n * (an agent tool, a workflow step, a planner step, a route callback, or\n * hand-rolled orchestration) hands a self-contained subtask to a\n * single-use agent created just for it, instead of reusing a long-lived\n * agent. The spawned `report` slots under the caller's\n * `report.children[]` like any executable, so cost and traces roll up\n * uniformly. It is not tied to any one primitive — it depends only on\n * `agent()` and the optional `budget` middleware.\n *\n * **What it is NOT.** Not a sandbox or a separate runtime. Each spawn is\n * a plain new `agent()` — its fresh conversation, own tools, and own\n * middleware state are ordinary new-instance behavior, not special\n * isolation (every `agent()` already has them). It is also a *narrower*\n * surface than `agent.execute`: one-shot, with no `history`,\n * `placeholders`, per-call event handlers, or `repair`. Reach for it when\n * you want a named single-use delegation with a per-task budget cap;\n * otherwise just construct an `agent()` and call it.\n *\n * Never throws on runtime failure — the agent surfaces failures on\n * `result.error` and a `\"failed\"` / `\"cancelled\"` report status.\n *\n * @example\n * const result = await spawnSubAgent({\n * name: \"extract-entities\",\n * model,\n * task: \"Pull every company name from this article: ...\",\n * budget: { maxCostUSD: 0.05 },\n * output: z.object({ companies: z.array(z.string()) }),\n * });\n */\nexport async function spawnSubAgent<TOutput = unknown>(\n spec: SpawnSubAgentSpec<TOutput>,\n): Promise<AgentResult<TOutput>> {\n const subAgent = buildSubAgent<TOutput>(spec);\n\n const options: AgentExecuteOptions<TOutput> = {};\n\n if (spec.output !== undefined) {\n options.output = spec.output;\n }\n\n if (spec.signal !== undefined) {\n options.signal = spec.signal;\n }\n\n if (spec.sessionId !== undefined) {\n options.sessionId = spec.sessionId;\n }\n\n return subAgent.execute(spec.task, options);\n}\n\n/**\n * Construct the fresh agent for one spawn. Attaches a `budget`\n * middleware only when a cap was requested, so the common no-budget case\n * is just a plain agent.\n */\nfunction buildSubAgent<TOutput>(spec: SpawnSubAgentSpec<TOutput>): AgentContract<TOutput> {\n const middleware = spec.budget !== undefined ? [budget(spec.budget)] : undefined;\n\n return agent<TOutput>({\n name: spec.name,\n model: spec.model,\n systemPrompt: spec.systemPrompt,\n tools: spec.tools,\n maxTrips: spec.maxTrips,\n output: spec.output,\n middleware,\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8FA,eAAsB,cACpB,MAC+B;CAC/B,MAAM,WAAW,cAAuB,IAAI;CAE5C,MAAM,UAAwC,CAAC;CAE/C,IAAI,KAAK,WAAW,QAClB,QAAQ,SAAS,KAAK;CAGxB,IAAI,KAAK,WAAW,QAClB,QAAQ,SAAS,KAAK;CAGxB,IAAI,KAAK,cAAc,QACrB,QAAQ,YAAY,KAAK;CAG3B,OAAO,SAAS,QAAQ,KAAK,MAAM,OAAO;AAC5C;;;;;;AAOA,SAAS,cAAuB,MAA0D;CACxF,MAAM,aAAa,KAAK,WAAW,SAAY,CAAC,OAAO,KAAK,MAAM,CAAC,IAAI;CAEvE,OAAO,MAAe;EACpB,MAAM,KAAK;EACX,OAAO,KAAK;EACZ,cAAc,KAAK;EACnB,OAAO,KAAK;EACZ,UAAU,KAAK;EACf,QAAQ,KAAK;EACb;CACF,CAAC;AACH"}
package/esm/ai.d.mts CHANGED
@@ -1,15 +1,32 @@
1
1
  import { tool } from "./tool/tool.mjs";
2
2
  import { agent } from "./agent/agent.mjs";
3
+ import { budget, readBudgetFallbackSignal } from "./middleware/builtins/budget.mjs";
4
+ import { spawnSubAgent } from "./agent/spawn-sub-agent.mjs";
5
+ import { SystemPromptFactory } from "./system-prompt/system-prompt.mjs";
6
+ import { judge } from "./eval/judge-scorer.mjs";
7
+ import { contains, exact, predicate } from "./eval/scorers.mjs";
8
+ import { batch } from "./batch/batch.mjs";
9
+ import { memory } from "./checkpoint/memory.mjs";
10
+ import { pg } from "./checkpoint/pg.mjs";
11
+ import { redis } from "./checkpoint/redis.mjs";
3
12
  import { setAIConfig } from "./config.mjs";
4
- import { budget } from "./middleware/builtins/budget.mjs";
13
+ import { memory as memory$1 } from "./memory/memory.mjs";
5
14
  import { guardrail } from "./middleware/builtins/guardrail.mjs";
6
15
  import { semanticCache } from "./middleware/builtins/semantic-cache.mjs";
7
16
  import { composeMiddleware } from "./middleware/helpers/compose.mjs";
8
17
  import { forTool } from "./middleware/helpers/for-tool.mjs";
18
+ import { mockRouter } from "./mock/mock-router.mjs";
19
+ import { fallbackModel } from "./model/fallback-model.mjs";
20
+ import { orchestrator } from "./orchestrator/orchestrator.mjs";
21
+ import { planner } from "./planner/planner.mjs";
22
+ import { memory as memory$2 } from "./snapshot/memory.mjs";
23
+ import { pg as pg$1 } from "./snapshot/pg.mjs";
24
+ import { redis as redis$1 } from "./snapshot/redis.mjs";
25
+ import { fanOut } from "./supervisor/fan-out.mjs";
26
+ import { router } from "./supervisor/router-factory.mjs";
9
27
  import { supervisor } from "./supervisor/supervisor.mjs";
10
28
  import { instruction } from "./system-prompt/instruction.mjs";
11
29
  import { persona } from "./system-prompt/persona.mjs";
12
- import { systemPrompt } from "./system-prompt/system-prompt.mjs";
13
30
  import { step } from "./workflow/step.mjs";
14
31
  import { workflow } from "./workflow/workflow.mjs";
15
32
 
@@ -23,6 +40,18 @@ import { workflow } from "./workflow/workflow.mjs";
23
40
  * - `ai.systemPrompt(...)` — compose a layered persona + instructions prompt.
24
41
  * - `ai.persona(text)` — reusable persona block (can be passed to `systemPrompt`).
25
42
  * - `ai.instruction(text)` — reusable instruction block (can be passed to `systemPrompt`).
43
+ * - `ai.orchestrator(...)` — session-state manager wrapped around a supervisor (durable session, drift detection, resume, commands).
44
+ * - `ai.memory(...)` — build an agent-memory store with WORKING (in-run scratch) and SEMANTIC (cache-driver `.similar()` recall) tiers.
45
+ * - `ai.planner(...)` — build an executable that generates an ordered plan over registered capabilities, then runs it step-by-step.
46
+ * - `ai.spawnSubAgent(spec)` — thin wrapper that builds a fresh one-shot `agent()` with an optional per-task `budget` and runs the task once. A general primitive (not planner-specific).
47
+ * - `ai.router(...)` — build a supervisor-compatible routing agent from named intents.
48
+ * - `ai.fanOut(unit, count)` — spread one agent/workflow into N intent entries for voting / self-consistency.
49
+ * - `ai.batch(executable, items, opts?)` — run any executable over a dataset with bounded concurrency + per-item retry.
50
+ * - `ai.fallbackModel(models, opts?)` — wrap an ordered model list that fails over to the next on transient provider errors.
51
+ * - `ai.eval.{exact,contains,predicate,judge}(...)` — built-in scorer factories for `agent.eval(...)`.
52
+ * - `ai.mockRouter(decisions, opts?)` — deterministic supervisor `route` callback for tests.
53
+ * - `ai.checkpoint.{memory,pg,redis}()` — durable orchestrator session checkpoint stores.
54
+ * - `ai.snapshot.{memory,pg,redis}()` — supervisor-run snapshot stores for `iterate: true` resume.
26
55
  * - `ai.openai.model(...)` / `ai.anthropic.model(...)` / ... once the adapter SDK is registered.
27
56
  *
28
57
  * @example
@@ -45,18 +74,44 @@ declare const ai: {
45
74
  config: typeof setAIConfig;
46
75
  tool: typeof tool;
47
76
  agent: typeof agent;
48
- systemPrompt: typeof systemPrompt;
77
+ systemPrompt: SystemPromptFactory;
49
78
  persona: typeof persona;
50
79
  instruction: typeof instruction;
51
80
  workflow: typeof workflow;
52
81
  step: typeof step;
53
82
  supervisor: typeof supervisor;
83
+ orchestrator: typeof orchestrator;
84
+ memory: typeof memory$1;
85
+ planner: typeof planner;
86
+ spawnSubAgent: typeof spawnSubAgent;
87
+ router: typeof router;
88
+ fanOut: typeof fanOut;
89
+ batch: typeof batch;
90
+ fallbackModel: typeof fallbackModel;
91
+ eval: {
92
+ exact: typeof exact;
93
+ contains: typeof contains;
94
+ predicate: typeof predicate;
95
+ judge: typeof judge;
96
+ };
97
+ mockRouter: typeof mockRouter;
54
98
  middleware: {
55
99
  budget: typeof budget;
56
100
  guardrail: typeof guardrail;
57
101
  semanticCache: typeof semanticCache;
58
102
  compose: typeof composeMiddleware;
59
103
  forTool: typeof forTool;
104
+ readBudgetFallbackSignal: typeof readBudgetFallbackSignal;
105
+ };
106
+ checkpoint: {
107
+ memory: typeof memory;
108
+ pg: typeof pg;
109
+ redis: typeof redis;
110
+ };
111
+ snapshot: {
112
+ memory: typeof memory$2;
113
+ pg: typeof pg$1;
114
+ redis: typeof redis$1;
60
115
  };
61
116
  };
62
117
  //#endregion
package/esm/ai.d.mts.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"ai.d.mts","names":[],"sources":["../../../../../../@warlock.js/ai/src/ai.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;AAyCA;;;;;;;;;;;;;;;;;;;;;;;cAAa,EAAA"}
1
+ {"version":3,"file":"ai.d.mts","names":[],"sources":["../../../../../../@warlock.js/ai/src/ai.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoEA;;;;;;;;;;;;;;;;;;cAAa,EAAA"}
package/esm/ai.mjs CHANGED
@@ -1,12 +1,34 @@
1
- import { budget } from "./middleware/builtins/budget.mjs";
1
+ import { budget, readBudgetFallbackSignal } from "./middleware/builtins/budget.mjs";
2
2
  import { guardrail } from "./middleware/builtins/guardrail.mjs";
3
3
  import { setAIConfig } from "./config.mjs";
4
4
  import { semanticCache } from "./middleware/builtins/semantic-cache.mjs";
5
5
  import { composeMiddleware } from "./middleware/helpers/compose.mjs";
6
6
  import { forTool } from "./middleware/helpers/for-tool.mjs";
7
- import { agent } from "./agent/agent.mjs";
8
7
  import { tool } from "./tool/tool.mjs";
8
+ import { agent } from "./agent/agent.mjs";
9
+ import { spawnSubAgent } from "./agent/spawn-sub-agent.mjs";
10
+ import { batch } from "./batch/batch.mjs";
11
+ import "./batch/index.mjs";
12
+ import { memory } from "./checkpoint/memory.mjs";
13
+ import { pg } from "./checkpoint/pg.mjs";
14
+ import { redis } from "./checkpoint/redis.mjs";
15
+ import { evalScorers } from "./eval/index.mjs";
16
+ import { memory as memory$1 } from "./memory/memory.mjs";
17
+ import { mockRouter } from "./mock/mock-router.mjs";
18
+ import "./mock/index.mjs";
19
+ import { fallbackModel } from "./model/fallback-model.mjs";
20
+ import "./model/index.mjs";
9
21
  import { supervisor } from "./supervisor/supervisor.mjs";
22
+ import { orchestrator } from "./orchestrator/orchestrator.mjs";
23
+ import "./orchestrator/index.mjs";
24
+ import { planner } from "./planner/planner.mjs";
25
+ import "./planner/index.mjs";
26
+ import { memory as memory$2 } from "./snapshot/memory.mjs";
27
+ import { pg as pg$1 } from "./snapshot/pg.mjs";
28
+ import { redis as redis$1 } from "./snapshot/redis.mjs";
29
+ import { fanOut } from "./supervisor/fan-out.mjs";
30
+ import { router } from "./supervisor/router-factory.mjs";
31
+ import "./supervisor/index.mjs";
10
32
  import { instruction } from "./system-prompt/instruction.mjs";
11
33
  import { persona } from "./system-prompt/persona.mjs";
12
34
  import { systemPrompt } from "./system-prompt/system-prompt.mjs";
@@ -23,6 +45,18 @@ import { workflow } from "./workflow/workflow.mjs";
23
45
  * - `ai.systemPrompt(...)` — compose a layered persona + instructions prompt.
24
46
  * - `ai.persona(text)` — reusable persona block (can be passed to `systemPrompt`).
25
47
  * - `ai.instruction(text)` — reusable instruction block (can be passed to `systemPrompt`).
48
+ * - `ai.orchestrator(...)` — session-state manager wrapped around a supervisor (durable session, drift detection, resume, commands).
49
+ * - `ai.memory(...)` — build an agent-memory store with WORKING (in-run scratch) and SEMANTIC (cache-driver `.similar()` recall) tiers.
50
+ * - `ai.planner(...)` — build an executable that generates an ordered plan over registered capabilities, then runs it step-by-step.
51
+ * - `ai.spawnSubAgent(spec)` — thin wrapper that builds a fresh one-shot `agent()` with an optional per-task `budget` and runs the task once. A general primitive (not planner-specific).
52
+ * - `ai.router(...)` — build a supervisor-compatible routing agent from named intents.
53
+ * - `ai.fanOut(unit, count)` — spread one agent/workflow into N intent entries for voting / self-consistency.
54
+ * - `ai.batch(executable, items, opts?)` — run any executable over a dataset with bounded concurrency + per-item retry.
55
+ * - `ai.fallbackModel(models, opts?)` — wrap an ordered model list that fails over to the next on transient provider errors.
56
+ * - `ai.eval.{exact,contains,predicate,judge}(...)` — built-in scorer factories for `agent.eval(...)`.
57
+ * - `ai.mockRouter(decisions, opts?)` — deterministic supervisor `route` callback for tests.
58
+ * - `ai.checkpoint.{memory,pg,redis}()` — durable orchestrator session checkpoint stores.
59
+ * - `ai.snapshot.{memory,pg,redis}()` — supervisor-run snapshot stores for `iterate: true` resume.
26
60
  * - `ai.openai.model(...)` / `ai.anthropic.model(...)` / ... once the adapter SDK is registered.
27
61
  *
28
62
  * @example
@@ -51,12 +85,33 @@ const ai = {
51
85
  workflow,
52
86
  step,
53
87
  supervisor,
88
+ orchestrator,
89
+ memory: memory$1,
90
+ planner,
91
+ spawnSubAgent,
92
+ router,
93
+ fanOut,
94
+ batch,
95
+ fallbackModel,
96
+ eval: evalScorers,
97
+ mockRouter,
54
98
  middleware: {
55
99
  budget,
56
100
  guardrail,
57
101
  semanticCache,
58
102
  compose: composeMiddleware,
59
- forTool
103
+ forTool,
104
+ readBudgetFallbackSignal
105
+ },
106
+ checkpoint: {
107
+ memory,
108
+ pg,
109
+ redis
110
+ },
111
+ snapshot: {
112
+ memory: memory$2,
113
+ pg: pg$1,
114
+ redis: redis$1
60
115
  }
61
116
  };
62
117
 
package/esm/ai.mjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"ai.mjs","names":[],"sources":["../../../../../../@warlock.js/ai/src/ai.ts"],"sourcesContent":["import { agent } from \"./agent/agent\";\nimport { setAIConfig } from \"./config\";\nimport { budget } from \"./middleware/builtins/budget\";\nimport { guardrail } from \"./middleware/builtins/guardrail\";\nimport { semanticCache } from \"./middleware/builtins/semantic-cache\";\nimport { composeMiddleware, forTool } from \"./middleware/helpers\";\nimport { supervisor } from \"./supervisor/supervisor\";\nimport { instruction } from \"./system-prompt/instruction\";\nimport { persona } from \"./system-prompt/persona\";\nimport { systemPrompt } from \"./system-prompt/system-prompt\";\nimport { tool } from \"./tool/tool\";\nimport { step } from \"./workflow/step\";\nimport { workflow } from \"./workflow/workflow\";\n\n/**\n * Top-level `ai` namespace — holds built-in factories and user-registered SDK adapters.\n *\n * Factories:\n * - `ai.tool(...)` — wrap an async function with a schema-validated input.\n * - `ai.agent(...)` — build an executable agent from model + tools + prompt.\n * - `ai.systemPrompt(...)` — compose a layered persona + instructions prompt.\n * - `ai.persona(text)` — reusable persona block (can be passed to `systemPrompt`).\n * - `ai.instruction(text)` — reusable instruction block (can be passed to `systemPrompt`).\n * - `ai.openai.model(...)` / `ai.anthropic.model(...)` / ... once the adapter SDK is registered.\n *\n * @example\n * const alex = ai.persona(\"You are Alex, a TypeScript expert.\");\n * const replyIn = ai.instruction(\"Respond in {{language|English}}.\");\n *\n * const prompt = ai.systemPrompt().persona(alex).instruction(replyIn);\n *\n * const myAgent = ai.agent({\n * model: ai.openai.model({ name: \"gpt-4o\" }),\n * systemPrompt: prompt,\n * tools: [myTool],\n * });\n *\n * const result = await myAgent.execute(\"What is the weather in Cairo?\", {\n * placeholders: { language: \"Arabic\" },\n * });\n */\nexport const ai = {\n config: setAIConfig,\n tool,\n agent,\n systemPrompt,\n persona,\n instruction,\n workflow,\n step,\n supervisor,\n middleware: {\n budget,\n guardrail,\n semanticCache,\n compose: composeMiddleware,\n forTool,\n },\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyCA,MAAa,KAAK;CAChB,QAAQ;CACR;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA,YAAY;EACV;EACA;EACA;EACA,SAAS;EACT;CACF;AACF"}
1
+ {"version":3,"file":"ai.mjs","names":["checkpointMemory","checkpointPg","checkpointRedis","snapshotMemory","snapshotPg","snapshotRedis"],"sources":["../../../../../../@warlock.js/ai/src/ai.ts"],"sourcesContent":["import { agent } from \"./agent/agent\";\nimport { batch } from \"./batch\";\nimport {\n checkpointMemory,\n checkpointPg,\n checkpointRedis,\n} from \"./checkpoint\";\nimport { setAIConfig } from \"./config\";\nimport { evalScorers } from \"./eval\";\nimport { budget, readBudgetFallbackSignal } from \"./middleware/builtins/budget\";\nimport { memory } from \"./memory\";\nimport { guardrail } from \"./middleware/builtins/guardrail\";\nimport { semanticCache } from \"./middleware/builtins/semantic-cache\";\nimport { composeMiddleware, forTool } from \"./middleware/helpers\";\nimport { mockRouter } from \"./mock\";\nimport { fallbackModel } from \"./model\";\nimport { orchestrator } from \"./orchestrator\";\nimport { planner } from \"./planner\";\nimport { spawnSubAgent } from \"./agent/spawn-sub-agent\";\nimport { snapshotMemory, snapshotPg, snapshotRedis } from \"./snapshot\";\nimport { fanOut, router } from \"./supervisor\";\nimport { supervisor } from \"./supervisor/supervisor\";\nimport { instruction } from \"./system-prompt/instruction\";\nimport { persona } from \"./system-prompt/persona\";\nimport { systemPrompt } from \"./system-prompt/system-prompt\";\nimport { tool } from \"./tool/tool\";\nimport { step } from \"./workflow/step\";\nimport { workflow } from \"./workflow/workflow\";\n\n/**\n * Top-level `ai` namespace — holds built-in factories and user-registered SDK adapters.\n *\n * Factories:\n * - `ai.tool(...)` — wrap an async function with a schema-validated input.\n * - `ai.agent(...)` — build an executable agent from model + tools + prompt.\n * - `ai.systemPrompt(...)` — compose a layered persona + instructions prompt.\n * - `ai.persona(text)` — reusable persona block (can be passed to `systemPrompt`).\n * - `ai.instruction(text)` — reusable instruction block (can be passed to `systemPrompt`).\n * - `ai.orchestrator(...)` — session-state manager wrapped around a supervisor (durable session, drift detection, resume, commands).\n * - `ai.memory(...)` — build an agent-memory store with WORKING (in-run scratch) and SEMANTIC (cache-driver `.similar()` recall) tiers.\n * - `ai.planner(...)` — build an executable that generates an ordered plan over registered capabilities, then runs it step-by-step.\n * - `ai.spawnSubAgent(spec)` — thin wrapper that builds a fresh one-shot `agent()` with an optional per-task `budget` and runs the task once. A general primitive (not planner-specific).\n * - `ai.router(...)` — build a supervisor-compatible routing agent from named intents.\n * - `ai.fanOut(unit, count)` — spread one agent/workflow into N intent entries for voting / self-consistency.\n * - `ai.batch(executable, items, opts?)` — run any executable over a dataset with bounded concurrency + per-item retry.\n * - `ai.fallbackModel(models, opts?)` — wrap an ordered model list that fails over to the next on transient provider errors.\n * - `ai.eval.{exact,contains,predicate,judge}(...)` — built-in scorer factories for `agent.eval(...)`.\n * - `ai.mockRouter(decisions, opts?)` — deterministic supervisor `route` callback for tests.\n * - `ai.checkpoint.{memory,pg,redis}()` — durable orchestrator session checkpoint stores.\n * - `ai.snapshot.{memory,pg,redis}()` — supervisor-run snapshot stores for `iterate: true` resume.\n * - `ai.openai.model(...)` / `ai.anthropic.model(...)` / ... once the adapter SDK is registered.\n *\n * @example\n * const alex = ai.persona(\"You are Alex, a TypeScript expert.\");\n * const replyIn = ai.instruction(\"Respond in {{language|English}}.\");\n *\n * const prompt = ai.systemPrompt().persona(alex).instruction(replyIn);\n *\n * const myAgent = ai.agent({\n * model: ai.openai.model({ name: \"gpt-4o\" }),\n * systemPrompt: prompt,\n * tools: [myTool],\n * });\n *\n * const result = await myAgent.execute(\"What is the weather in Cairo?\", {\n * placeholders: { language: \"Arabic\" },\n * });\n */\nexport const ai = {\n config: setAIConfig,\n tool,\n agent,\n systemPrompt,\n persona,\n instruction,\n workflow,\n step,\n supervisor,\n orchestrator,\n memory,\n planner,\n spawnSubAgent,\n router,\n fanOut,\n batch,\n fallbackModel,\n eval: evalScorers,\n mockRouter,\n middleware: {\n budget,\n guardrail,\n semanticCache,\n compose: composeMiddleware,\n forTool,\n readBudgetFallbackSignal,\n },\n checkpoint: {\n memory: checkpointMemory,\n pg: checkpointPg,\n redis: checkpointRedis,\n },\n snapshot: {\n memory: snapshotMemory,\n pg: snapshotPg,\n redis: snapshotRedis,\n },\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoEA,MAAa,KAAK;CAChB,QAAQ;CACR;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA,MAAM;CACN;CACA,YAAY;EACV;EACA;EACA;EACA,SAAS;EACT;EACA;CACF;CACA,YAAY;EACFA;EACJC;EACGC;CACT;CACA,UAAU;EACR,QAAQC;EACR,IAAIC;EACJ,OAAOC;CACT;AACF"}
@@ -0,0 +1,43 @@
1
+ import { BaseResult } from "../contracts/result/base-result.type.mjs";
2
+ import { ExecuteResult } from "../contracts/result/execute-result.type.mjs";
3
+ import { ExecutableContract } from "../contracts/executable.contract.mjs";
4
+ import { BatchOptions, BatchResult } from "./batch.type.mjs";
5
+
6
+ //#region ../@warlock.js/ai/src/batch/batch.d.ts
7
+ /**
8
+ * Run an executable AI primitive (agent, workflow, supervisor, tool,
9
+ * or anything satisfying {@link ExecutableContract}) over a dataset
10
+ * with bounded concurrency and per-item retry, returning per-item
11
+ * outcomes plus rolled-up usage and a walkable report tree.
12
+ *
13
+ * **Role.** The fan-out primitive of `@warlock.js/ai`. Where an agent
14
+ * runs once, `batch` runs the SAME executable N times — once per item
15
+ * — and aggregates the results into the unified {@link ExecuteResult}
16
+ * envelope, so a batch slots into cost dashboards and trace tooling
17
+ * exactly like a single run does.
18
+ *
19
+ * **Isolation.** Items are independent: one item's failure (after its
20
+ * retries are exhausted) never cancels a sibling, and the batch as a
21
+ * whole never rejects — failures live on each {@link BatchItemResult}.
22
+ * Reach for `result.report.failed` / `item.status` to inspect them.
23
+ *
24
+ * **Usage rollup.** `result.usage` and `result.report.usage` sum every
25
+ * item's usage, satisfying the universal rollup invariant ("own cost
26
+ * + sum of children"; a batch has zero own cost). Each item's own
27
+ * report is attached under `report.children[]`, in original item
28
+ * order, so a trace walker sees every run.
29
+ *
30
+ * @example
31
+ * const result = await batch(summarizer, articles, {
32
+ * concurrency: 4,
33
+ * retry: { attempts: 3, backoff: "exponential" },
34
+ * onItem: (item) => log.info("batch", "item", "settled", { index: item.index }),
35
+ * });
36
+ *
37
+ * console.log(`${result.report.succeeded}/${result.report.total} ok`);
38
+ * console.log(`${result.usage.total} tokens total`);
39
+ */
40
+ declare function batch<TInput, TOptions, TResult extends BaseResult = ExecuteResult>(executable: ExecutableContract<TInput, TOptions, TResult>, items: readonly TInput[], options?: BatchOptions<TResult>): Promise<BatchResult<TResult>>;
41
+ //#endregion
42
+ export { batch };
43
+ //# sourceMappingURL=batch.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"batch.d.mts","names":[],"sources":["../../../../../../../@warlock.js/ai/src/batch/batch.ts"],"mappings":";;;;;;;;AAmDA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAAsB,KAAA,mCAAwC,UAAA,GAAa,aAAA,EACzE,UAAA,EAAY,kBAAA,CAAmB,MAAA,EAAQ,QAAA,EAAU,OAAA,GACjD,KAAA,WAAgB,MAAA,IAChB,OAAA,GAAS,YAAA,CAAa,OAAA,IACrB,OAAA,CAAQ,WAAA,CAAY,OAAA"}
@@ -0,0 +1,179 @@
1
+ import { accumulateCost } from "../utils/compute-cost.mjs";
2
+ import { generateRunId } from "../utils/generate-run-id.mjs";
3
+ import { REPORT_SCHEMA_VERSION } from "../contracts/result/base-report.type.mjs";
4
+ import { stampReportLineage } from "../utils/stamp-report-lineage.mjs";
5
+ import { runBatchItem } from "./run-batch-item.mjs";
6
+ import { runWithConcurrency } from "./run-with-concurrency.mjs";
7
+
8
+ //#region ../@warlock.js/ai/src/batch/batch.ts
9
+ /**
10
+ * Run an executable AI primitive (agent, workflow, supervisor, tool,
11
+ * or anything satisfying {@link ExecutableContract}) over a dataset
12
+ * with bounded concurrency and per-item retry, returning per-item
13
+ * outcomes plus rolled-up usage and a walkable report tree.
14
+ *
15
+ * **Role.** The fan-out primitive of `@warlock.js/ai`. Where an agent
16
+ * runs once, `batch` runs the SAME executable N times — once per item
17
+ * — and aggregates the results into the unified {@link ExecuteResult}
18
+ * envelope, so a batch slots into cost dashboards and trace tooling
19
+ * exactly like a single run does.
20
+ *
21
+ * **Isolation.** Items are independent: one item's failure (after its
22
+ * retries are exhausted) never cancels a sibling, and the batch as a
23
+ * whole never rejects — failures live on each {@link BatchItemResult}.
24
+ * Reach for `result.report.failed` / `item.status` to inspect them.
25
+ *
26
+ * **Usage rollup.** `result.usage` and `result.report.usage` sum every
27
+ * item's usage, satisfying the universal rollup invariant ("own cost
28
+ * + sum of children"; a batch has zero own cost). Each item's own
29
+ * report is attached under `report.children[]`, in original item
30
+ * order, so a trace walker sees every run.
31
+ *
32
+ * @example
33
+ * const result = await batch(summarizer, articles, {
34
+ * concurrency: 4,
35
+ * retry: { attempts: 3, backoff: "exponential" },
36
+ * onItem: (item) => log.info("batch", "item", "settled", { index: item.index }),
37
+ * });
38
+ *
39
+ * console.log(`${result.report.succeeded}/${result.report.total} ok`);
40
+ * console.log(`${result.usage.total} tokens total`);
41
+ */
42
+ async function batch(executable, items, options = {}) {
43
+ return new BatchRun(executable, items, options).run();
44
+ }
45
+ /**
46
+ * Per-call orchestration state for one {@link batch} invocation.
47
+ * Instantiated fresh inside the factory so the mutable accumulators
48
+ * (`results`, `usage`) are never shared across batches. Unexported —
49
+ * callers only ever see the plain {@link BatchResult}.
50
+ */
51
+ var BatchRun = class {
52
+ constructor(executable, items, options) {
53
+ this.executable = executable;
54
+ this.items = items;
55
+ this.options = options;
56
+ this.startedAt = (/* @__PURE__ */ new Date()).toISOString();
57
+ this.startPerf = performance.now();
58
+ this.runId = generateRunId("batch");
59
+ this.results = new Array(items.length);
60
+ }
61
+ /**
62
+ * Dispatch every item through the concurrency pool, then assemble
63
+ * the rolled-up {@link BatchResult}. Runs once per `batch()` call.
64
+ */
65
+ async run() {
66
+ const concurrency = this.options.concurrency ?? this.items.length;
67
+ await runWithConcurrency(this.items.length, concurrency, (index) => this.processItem(index));
68
+ return this.buildResult();
69
+ }
70
+ /**
71
+ * Run a single item with retry, record it positionally, then fire
72
+ * the `onItem` hook. A throw from the hook is swallowed — a progress
73
+ * callback must never break the batch.
74
+ */
75
+ async processItem(index) {
76
+ const item = await runBatchItem({
77
+ index,
78
+ input: this.items[index],
79
+ executable: this.executable,
80
+ retry: this.options.retry,
81
+ signal: this.options.signal
82
+ });
83
+ this.results[index] = item;
84
+ if (this.options.onItem) try {
85
+ await this.options.onItem(item);
86
+ } catch {}
87
+ }
88
+ /**
89
+ * Fold the per-item outcomes into rolled-up usage, the child report
90
+ * list, and the final {@link BatchResult}, then stamp lineage across
91
+ * the whole subtree so every child shares this batch's root run id.
92
+ */
93
+ buildResult() {
94
+ const usage = {
95
+ input: 0,
96
+ output: 0,
97
+ total: 0
98
+ };
99
+ const children = [];
100
+ const data = new Array(this.items.length).fill(void 0);
101
+ let succeeded = 0;
102
+ let failed = 0;
103
+ let cancelled = 0;
104
+ for (const item of this.results) {
105
+ if (item.status === "completed") succeeded += 1;
106
+ else if (item.status === "failed") failed += 1;
107
+ else cancelled += 1;
108
+ const itemResult = item.result;
109
+ if (itemResult) {
110
+ this.mergeUsage(usage, itemResult.usage);
111
+ if ("report" in itemResult && itemResult.report) children.push(itemResult.report);
112
+ if (item.status === "completed" && "data" in itemResult) data[item.index] = itemResult.data;
113
+ }
114
+ }
115
+ const report = this.buildReport(usage, children, {
116
+ succeeded,
117
+ failed,
118
+ cancelled
119
+ });
120
+ stampReportLineage(report, {
121
+ rootRunId: this.runId,
122
+ sessionId: this.options.sessionId
123
+ });
124
+ return {
125
+ type: "batch",
126
+ data,
127
+ usage,
128
+ report,
129
+ items: this.results
130
+ };
131
+ }
132
+ /**
133
+ * Add a child's usage into the running batch total. Scalar token
134
+ * channels sum directly; the optional cost breakdown merges via
135
+ * {@link accumulateCost} so a single unpriced child can't erase the
136
+ * cost of priced siblings. Optional token sub-channels
137
+ * (`cachedTokens`, etc.) accumulate only when some child reports
138
+ * them, preserving the "never reported anywhere" signal.
139
+ */
140
+ mergeUsage(target, child) {
141
+ target.input += child.input;
142
+ target.output += child.output;
143
+ target.total += child.total;
144
+ if (child.cachedTokens !== void 0) target.cachedTokens = (target.cachedTokens ?? 0) + child.cachedTokens;
145
+ if (child.reasoningTokens !== void 0) target.reasoningTokens = (target.reasoningTokens ?? 0) + child.reasoningTokens;
146
+ if (child.cacheWriteTokens !== void 0) target.cacheWriteTokens = (target.cacheWriteTokens ?? 0) + child.cacheWriteTokens;
147
+ const mergedCost = accumulateCost(target.cost, child.cost);
148
+ if (mergedCost !== void 0) target.cost = mergedCost;
149
+ }
150
+ /**
151
+ * Build the batch's own {@link BatchReport} node. `parentRunId` /
152
+ * `rootRunId` are placeholders here — {@link stampReportLineage}
153
+ * rewrites them across the whole subtree right after.
154
+ */
155
+ buildReport(usage, children, counts) {
156
+ const status = counts.failed > 0 || counts.cancelled > 0 ? "failed" : "completed";
157
+ return {
158
+ runId: this.runId,
159
+ rootRunId: this.runId,
160
+ name: this.options.name ?? "batch",
161
+ type: "batch",
162
+ status,
163
+ startedAt: this.startedAt,
164
+ endedAt: (/* @__PURE__ */ new Date()).toISOString(),
165
+ duration: performance.now() - this.startPerf,
166
+ usage,
167
+ children,
168
+ total: this.items.length,
169
+ succeeded: counts.succeeded,
170
+ failed: counts.failed,
171
+ cancelled: counts.cancelled,
172
+ reportSchemaVersion: 1
173
+ };
174
+ }
175
+ };
176
+
177
+ //#endregion
178
+ export { batch };
179
+ //# sourceMappingURL=batch.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"batch.mjs","names":[],"sources":["../../../../../../../@warlock.js/ai/src/batch/batch.ts"],"sourcesContent":["import type { BaseReport } from \"../contracts/result/base-report.type\";\nimport { REPORT_SCHEMA_VERSION } from \"../contracts/result/base-report.type\";\nimport type { BaseResult } from \"../contracts/result/base-result.type\";\nimport type { ExecutableContract } from \"../contracts/executable.contract\";\nimport type { ExecuteResult } from \"../contracts/result/execute-result.type\";\nimport type { Usage } from \"../contracts/result/usage.type\";\nimport { accumulateCost } from \"../utils/compute-cost\";\nimport { generateRunId } from \"../utils/generate-run-id\";\nimport { stampReportLineage } from \"../utils/stamp-report-lineage\";\nimport type {\n BatchItemResult,\n BatchOptions,\n BatchReport,\n BatchResult,\n} from \"./batch.type\";\nimport { runBatchItem } from \"./run-batch-item\";\nimport { runWithConcurrency } from \"./run-with-concurrency\";\n\n/**\n * Run an executable AI primitive (agent, workflow, supervisor, tool,\n * or anything satisfying {@link ExecutableContract}) over a dataset\n * with bounded concurrency and per-item retry, returning per-item\n * outcomes plus rolled-up usage and a walkable report tree.\n *\n * **Role.** The fan-out primitive of `@warlock.js/ai`. Where an agent\n * runs once, `batch` runs the SAME executable N times — once per item\n * — and aggregates the results into the unified {@link ExecuteResult}\n * envelope, so a batch slots into cost dashboards and trace tooling\n * exactly like a single run does.\n *\n * **Isolation.** Items are independent: one item's failure (after its\n * retries are exhausted) never cancels a sibling, and the batch as a\n * whole never rejects — failures live on each {@link BatchItemResult}.\n * Reach for `result.report.failed` / `item.status` to inspect them.\n *\n * **Usage rollup.** `result.usage` and `result.report.usage` sum every\n * item's usage, satisfying the universal rollup invariant (\"own cost\n * + sum of children\"; a batch has zero own cost). Each item's own\n * report is attached under `report.children[]`, in original item\n * order, so a trace walker sees every run.\n *\n * @example\n * const result = await batch(summarizer, articles, {\n * concurrency: 4,\n * retry: { attempts: 3, backoff: \"exponential\" },\n * onItem: (item) => log.info(\"batch\", \"item\", \"settled\", { index: item.index }),\n * });\n *\n * console.log(`${result.report.succeeded}/${result.report.total} ok`);\n * console.log(`${result.usage.total} tokens total`);\n */\nexport async function batch<TInput, TOptions, TResult extends BaseResult = ExecuteResult>(\n executable: ExecutableContract<TInput, TOptions, TResult>,\n items: readonly TInput[],\n options: BatchOptions<TResult> = {},\n): Promise<BatchResult<TResult>> {\n return new BatchRun(executable, items, options).run();\n}\n\n/**\n * Per-call orchestration state for one {@link batch} invocation.\n * Instantiated fresh inside the factory so the mutable accumulators\n * (`results`, `usage`) are never shared across batches. Unexported —\n * callers only ever see the plain {@link BatchResult}.\n */\nclass BatchRun<TInput, TOptions, TResult extends BaseResult> {\n private readonly runId: string;\n private readonly results: BatchItemResult<TResult>[];\n private readonly startedAt = new Date().toISOString();\n private readonly startPerf = performance.now();\n\n public constructor(\n private readonly executable: ExecutableContract<TInput, TOptions, TResult>,\n private readonly items: readonly TInput[],\n private readonly options: BatchOptions<TResult>,\n ) {\n this.runId = generateRunId(\"batch\");\n this.results = new Array<BatchItemResult<TResult>>(items.length);\n }\n\n /**\n * Dispatch every item through the concurrency pool, then assemble\n * the rolled-up {@link BatchResult}. Runs once per `batch()` call.\n */\n public async run(): Promise<BatchResult<TResult>> {\n const concurrency = this.options.concurrency ?? this.items.length;\n\n await runWithConcurrency(this.items.length, concurrency, (index) =>\n this.processItem(index),\n );\n\n return this.buildResult();\n }\n\n /**\n * Run a single item with retry, record it positionally, then fire\n * the `onItem` hook. A throw from the hook is swallowed — a progress\n * callback must never break the batch.\n */\n private async processItem(index: number): Promise<void> {\n const item = await runBatchItem({\n index,\n input: this.items[index] as TInput,\n executable: this.executable,\n retry: this.options.retry,\n signal: this.options.signal,\n });\n\n this.results[index] = item;\n\n if (this.options.onItem) {\n try {\n await this.options.onItem(item);\n } catch {\n // A progress hook must never break the batch — swallow its throw.\n }\n }\n }\n\n /**\n * Fold the per-item outcomes into rolled-up usage, the child report\n * list, and the final {@link BatchResult}, then stamp lineage across\n * the whole subtree so every child shares this batch's root run id.\n */\n private buildResult(): BatchResult<TResult> {\n const usage: Usage = { input: 0, output: 0, total: 0 };\n const children: BaseReport[] = [];\n const data: (unknown | undefined)[] = new Array(this.items.length).fill(undefined);\n\n let succeeded = 0;\n let failed = 0;\n let cancelled = 0;\n\n for (const item of this.results) {\n if (item.status === \"completed\") {\n succeeded += 1;\n } else if (item.status === \"failed\") {\n failed += 1;\n } else {\n cancelled += 1;\n }\n\n const itemResult = item.result;\n if (itemResult) {\n this.mergeUsage(usage, itemResult.usage);\n\n if (\"report\" in itemResult && itemResult.report) {\n children.push(itemResult.report as BaseReport);\n }\n\n if (item.status === \"completed\" && \"data\" in itemResult) {\n data[item.index] = (itemResult as { data?: unknown }).data;\n }\n }\n }\n\n const report = this.buildReport(usage, children, { succeeded, failed, cancelled });\n\n stampReportLineage(report, {\n rootRunId: this.runId,\n sessionId: this.options.sessionId,\n });\n\n return {\n type: \"batch\",\n data,\n usage,\n report,\n items: this.results,\n };\n }\n\n /**\n * Add a child's usage into the running batch total. Scalar token\n * channels sum directly; the optional cost breakdown merges via\n * {@link accumulateCost} so a single unpriced child can't erase the\n * cost of priced siblings. Optional token sub-channels\n * (`cachedTokens`, etc.) accumulate only when some child reports\n * them, preserving the \"never reported anywhere\" signal.\n */\n private mergeUsage(target: Usage, child: Usage): void {\n target.input += child.input;\n target.output += child.output;\n target.total += child.total;\n\n if (child.cachedTokens !== undefined) {\n target.cachedTokens = (target.cachedTokens ?? 0) + child.cachedTokens;\n }\n\n if (child.reasoningTokens !== undefined) {\n target.reasoningTokens = (target.reasoningTokens ?? 0) + child.reasoningTokens;\n }\n\n if (child.cacheWriteTokens !== undefined) {\n target.cacheWriteTokens = (target.cacheWriteTokens ?? 0) + child.cacheWriteTokens;\n }\n\n const mergedCost = accumulateCost(target.cost, child.cost);\n if (mergedCost !== undefined) {\n target.cost = mergedCost;\n }\n }\n\n /**\n * Build the batch's own {@link BatchReport} node. `parentRunId` /\n * `rootRunId` are placeholders here — {@link stampReportLineage}\n * rewrites them across the whole subtree right after.\n */\n private buildReport(\n usage: Usage,\n children: BaseReport[],\n counts: { succeeded: number; failed: number; cancelled: number },\n ): BatchReport {\n const status = counts.failed > 0 || counts.cancelled > 0 ? \"failed\" : \"completed\";\n\n return {\n runId: this.runId,\n rootRunId: this.runId,\n name: this.options.name ?? \"batch\",\n type: \"batch\",\n status,\n startedAt: this.startedAt,\n endedAt: new Date().toISOString(),\n duration: performance.now() - this.startPerf,\n usage,\n children,\n total: this.items.length,\n succeeded: counts.succeeded,\n failed: counts.failed,\n cancelled: counts.cancelled,\n reportSchemaVersion: REPORT_SCHEMA_VERSION,\n };\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmDA,eAAsB,MACpB,YACA,OACA,UAAiC,CAAC,GACH;CAC/B,OAAO,IAAI,SAAS,YAAY,OAAO,OAAO,CAAC,CAAC,IAAI;AACtD;;;;;;;AAQA,IAAM,WAAN,MAA6D;CAM3D,AAAO,YACL,AAAiB,YACjB,AAAiB,OACjB,AAAiB,SACjB;EAHiB;EACA;EACA;oCANU,IAAI,KAAK,EAAC,CAAC,YAAY;mBACvB,YAAY,IAAI;EAO3C,KAAK,QAAQ,cAAc,OAAO;EAClC,KAAK,UAAU,IAAI,MAAgC,MAAM,MAAM;CACjE;;;;;CAMA,MAAa,MAAqC;EAChD,MAAM,cAAc,KAAK,QAAQ,eAAe,KAAK,MAAM;EAE3D,MAAM,mBAAmB,KAAK,MAAM,QAAQ,cAAc,UACxD,KAAK,YAAY,KAAK,CACxB;EAEA,OAAO,KAAK,YAAY;CAC1B;;;;;;CAOA,MAAc,YAAY,OAA8B;EACtD,MAAM,OAAO,MAAM,aAAa;GAC9B;GACA,OAAO,KAAK,MAAM;GAClB,YAAY,KAAK;GACjB,OAAO,KAAK,QAAQ;GACpB,QAAQ,KAAK,QAAQ;EACvB,CAAC;EAED,KAAK,QAAQ,SAAS;EAEtB,IAAI,KAAK,QAAQ,QACf,IAAI;GACF,MAAM,KAAK,QAAQ,OAAO,IAAI;EAChC,QAAQ,CAER;CAEJ;;;;;;CAOA,AAAQ,cAAoC;EAC1C,MAAM,QAAe;GAAE,OAAO;GAAG,QAAQ;GAAG,OAAO;EAAE;EACrD,MAAM,WAAyB,CAAC;EAChC,MAAM,OAAgC,IAAI,MAAM,KAAK,MAAM,MAAM,CAAC,CAAC,KAAK,MAAS;EAEjF,IAAI,YAAY;EAChB,IAAI,SAAS;EACb,IAAI,YAAY;EAEhB,KAAK,MAAM,QAAQ,KAAK,SAAS;GAC/B,IAAI,KAAK,WAAW,aAClB,aAAa;QACR,IAAI,KAAK,WAAW,UACzB,UAAU;QAEV,aAAa;GAGf,MAAM,aAAa,KAAK;GACxB,IAAI,YAAY;IACd,KAAK,WAAW,OAAO,WAAW,KAAK;IAEvC,IAAI,YAAY,cAAc,WAAW,QACvC,SAAS,KAAK,WAAW,MAAoB;IAG/C,IAAI,KAAK,WAAW,eAAe,UAAU,YAC3C,KAAK,KAAK,SAAU,WAAkC;GAE1D;EACF;EAEA,MAAM,SAAS,KAAK,YAAY,OAAO,UAAU;GAAE;GAAW;GAAQ;EAAU,CAAC;EAEjF,mBAAmB,QAAQ;GACzB,WAAW,KAAK;GAChB,WAAW,KAAK,QAAQ;EAC1B,CAAC;EAED,OAAO;GACL,MAAM;GACN;GACA;GACA;GACA,OAAO,KAAK;EACd;CACF;;;;;;;;;CAUA,AAAQ,WAAW,QAAe,OAAoB;EACpD,OAAO,SAAS,MAAM;EACtB,OAAO,UAAU,MAAM;EACvB,OAAO,SAAS,MAAM;EAEtB,IAAI,MAAM,iBAAiB,QACzB,OAAO,gBAAgB,OAAO,gBAAgB,KAAK,MAAM;EAG3D,IAAI,MAAM,oBAAoB,QAC5B,OAAO,mBAAmB,OAAO,mBAAmB,KAAK,MAAM;EAGjE,IAAI,MAAM,qBAAqB,QAC7B,OAAO,oBAAoB,OAAO,oBAAoB,KAAK,MAAM;EAGnE,MAAM,aAAa,eAAe,OAAO,MAAM,MAAM,IAAI;EACzD,IAAI,eAAe,QACjB,OAAO,OAAO;CAElB;;;;;;CAOA,AAAQ,YACN,OACA,UACA,QACa;EACb,MAAM,SAAS,OAAO,SAAS,KAAK,OAAO,YAAY,IAAI,WAAW;EAEtE,OAAO;GACL,OAAO,KAAK;GACZ,WAAW,KAAK;GAChB,MAAM,KAAK,QAAQ,QAAQ;GAC3B,MAAM;GACN;GACA,WAAW,KAAK;GAChB,0BAAS,IAAI,KAAK,EAAC,CAAC,YAAY;GAChC,UAAU,YAAY,IAAI,IAAI,KAAK;GACnC;GACA;GACA,OAAO,KAAK,MAAM;GAClB,WAAW,OAAO;GAClB,QAAQ,OAAO;GACf,WAAW,OAAO;GAClB;EACF;CACF;AACF"}
@@ -0,0 +1,144 @@
1
+ import { AIError } from "../errors/ai-error.mjs";
2
+ import { BaseResult } from "../contracts/result/base-result.type.mjs";
3
+ import { BaseReport } from "../contracts/result/base-report.type.mjs";
4
+ import { ExecuteResult } from "../contracts/result/execute-result.type.mjs";
5
+ import { RetryConfig } from "../contracts/workflow/retry-config.type.mjs";
6
+
7
+ //#region ../@warlock.js/ai/src/batch/batch.type.d.ts
8
+ /**
9
+ * Terminal status of a single batch item. Mirrors the relevant subset
10
+ * of {@link import("../contracts/result/base-report.type").ReportStatus}
11
+ * — an item either ran to completion, failed (after exhausting its
12
+ * retries), or was cancelled before it started because the batch was
13
+ * aborted.
14
+ */
15
+ type BatchItemStatus = "completed" | "failed" | "cancelled";
16
+ /**
17
+ * Outcome of running the executable over one input item.
18
+ *
19
+ * `result` is the underlying primitive's own {@link ExecuteResult}
20
+ * (an `AgentResult`, `WorkflowResult`, etc.) when the item ran — it
21
+ * carries the item's own `usage` and `report`. `result` is `undefined`
22
+ * only when the item was `"cancelled"` before it ever executed.
23
+ *
24
+ * `error` is the typed failure cause when `status` is `"failed"` or
25
+ * `"cancelled"`, and `undefined` on success. It mirrors
26
+ * `result?.error` for failed items so callers can branch on the item
27
+ * envelope without reaching into the inner result.
28
+ *
29
+ * @example
30
+ * const batchResult = await ai.batch(summarizer, articles);
31
+ *
32
+ * for (const item of batchResult.items) {
33
+ * if (item.status === "completed") {
34
+ * console.log(item.index, item.result?.data);
35
+ * } else {
36
+ * console.warn(item.index, item.error?.code);
37
+ * }
38
+ * }
39
+ */
40
+ type BatchItemResult<TResult extends BaseResult = ExecuteResult> = {
41
+ /** 0-based position of this item in the original `items` array. */index: number; /** Terminal status of this item. */
42
+ status: BatchItemStatus;
43
+ /**
44
+ * Underlying primitive result when the item ran (success OR failure).
45
+ * `undefined` only for items cancelled before execution started.
46
+ */
47
+ result?: TResult; /** Typed failure cause; `undefined` on success. */
48
+ error?: AIError; /** Number of attempts spent on this item (1 when no retry happened). */
49
+ attempts: number;
50
+ };
51
+ /**
52
+ * Batch-specific execution report — a {@link BaseReport} whose
53
+ * `children[]` are the per-item reports, in original item order. The
54
+ * root `usage` is the rolled-up sum of every child's usage, matching
55
+ * the universal rollup invariant ("own cost + sum of children"; a
56
+ * batch has zero own cost — it's pure orchestration).
57
+ */
58
+ type BatchReport = BaseReport & {
59
+ type: "batch"; /** Total number of items dispatched. */
60
+ total: number; /** Count of items that completed successfully. */
61
+ succeeded: number; /** Count of items that failed after exhausting retries. */
62
+ failed: number; /** Count of items cancelled before they ran (batch aborted). */
63
+ cancelled: number;
64
+ };
65
+ /**
66
+ * Result returned by `ai.batch(...)`. Satisfies the unified
67
+ * {@link ExecuteResult} envelope — `usage` and `report` are the
68
+ * rolled-up totals across every item — and adds the per-item
69
+ * breakdown under `items`.
70
+ *
71
+ * `data` holds the ordered array of successful items' `result.data`
72
+ * with `undefined` in the slots of failed/cancelled items, so callers
73
+ * that don't care about per-item status can read `data` positionally.
74
+ * `error` is left `undefined` — a batch never fails as a whole; an
75
+ * individual item's failure lives on its `BatchItemResult`.
76
+ *
77
+ * @example
78
+ * const { items, usage, report } = await ai.batch(agent, prompts, {
79
+ * concurrency: 4,
80
+ * retry: { attempts: 3, backoff: "exponential" },
81
+ * });
82
+ *
83
+ * console.log(`${report.succeeded}/${report.total} ok, ${usage.total} tokens`);
84
+ */
85
+ type BatchResult<TResult extends BaseResult = ExecuteResult> = Omit<ExecuteResult, "data" | "report"> & {
86
+ type: "batch";
87
+ /**
88
+ * Positional outputs: each successful item's `result.data` in
89
+ * original order, with `undefined` in the slots of failed or
90
+ * cancelled items.
91
+ */
92
+ data: (unknown | undefined)[]; /** Per-item outcomes in original item order. */
93
+ items: BatchItemResult<TResult>[]; /** Batch-specific report (extends `report` with item counts). */
94
+ report: BatchReport;
95
+ };
96
+ /**
97
+ * Callback fired once per item as soon as it settles (success or
98
+ * failure), regardless of dispatch order. Useful for streaming
99
+ * progress to a UI or a log without waiting for the whole batch.
100
+ *
101
+ * Fired AFTER an item's retries are exhausted — `item.attempts`
102
+ * reflects the final count. A throw from this hook is swallowed (it
103
+ * must never break the batch); log inside it if you need failures.
104
+ */
105
+ type BatchItemHandler<TResult extends BaseResult = ExecuteResult> = (item: BatchItemResult<TResult>) => void | Promise<void>;
106
+ /**
107
+ * Options for {@link import("./batch").batch}.
108
+ *
109
+ * Every field is optional with a safe default — `ai.batch(exec, items)`
110
+ * runs the whole dataset with unbounded concurrency and no retry.
111
+ */
112
+ type BatchOptions<TResult extends BaseResult = ExecuteResult> = {
113
+ /**
114
+ * Maximum number of items running at once. A positive integer.
115
+ * Defaults to `items.length` (all at once). Values `<= 0` are
116
+ * treated as `1` (fully serial).
117
+ */
118
+ concurrency?: number;
119
+ /**
120
+ * Per-item retry policy, reusing the workflow {@link RetryConfig}
121
+ * semantics (attempts, backoff, `retryOn`, `onRetry`). Applied
122
+ * independently to each item — one item's retries never block
123
+ * another's. Omit (or `attempts: 1`) for no retry.
124
+ */
125
+ retry?: RetryConfig; /** Fired once per item the moment it settles. See {@link BatchItemHandler}. */
126
+ onItem?: BatchItemHandler<TResult>;
127
+ /**
128
+ * Cancellation handle. When aborted, in-flight items receive the
129
+ * same signal (so a primitive honoring `signal` stops promptly) and
130
+ * not-yet-started items are reported as `"cancelled"` without
131
+ * running.
132
+ */
133
+ signal?: AbortSignal;
134
+ /**
135
+ * Caller-supplied session identifier propagated onto the batch
136
+ * report and every child item report (lineage), so flat trace
137
+ * queries group the whole batch under one session.
138
+ */
139
+ sessionId?: string; /** Optional name for the batch report node. Defaults to `"batch"`. */
140
+ name?: string;
141
+ };
142
+ //#endregion
143
+ export { BatchItemHandler, BatchItemResult, BatchItemStatus, BatchOptions, BatchReport, BatchResult };
144
+ //# sourceMappingURL=batch.type.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"batch.type.d.mts","names":[],"sources":["../../../../../../../@warlock.js/ai/src/batch/batch.type.ts"],"mappings":";;;;;;;;;AAaA;;;;AAA2B;KAAf,eAAA;;;;;;;;;;;;;;;;;;;;;;AAuCF;AAUV;;KAvBY,eAAA,iBAAgC,UAAA,GAAa,aAAA;EAuBrB,mEArBlC,KAAA,UAsBA;EApBA,MAAA,EAAQ,eAAA;EAwBR;;;;EAnBA,MAAA,GAAS,OAAA,EA8CC;EA5CV,KAAA,GAAQ,OAAA,EA4Ca;EA1CrB,QAAA;AAAA;;;;;;;;KAUU,WAAA,GAAc,UAAU;EAClC,IAAA,WA+BmD;EA7BnD,KAAA,UA8BA;EA5BA,SAAA,UAqCA;EAnCA,MAAA,UAqCO;EAnCP,SAAA;AAAA;;;AAqCmB;AAYrB;;;;;;;;;;;;;;;;;KA1BY,WAAA,iBAA4B,UAAA,GAAa,aAAA,IAAiB,IAAA,CACpE,aAAA;EAGA,IAAA;EAgCU;;;;;EA1BV,IAAA,2BAyC0B;EAvC1B,KAAA,EAAO,eAAA,CAAgB,OAAA,KA8Cd;EA5CT,MAAA,EAAQ,WAAA;AAAA;;;;;;;;;;KAYE,gBAAA,iBAAiC,UAAA,GAAa,aAAA,KACxD,IAAA,EAAM,eAAA,CAAgB,OAAA,aACZ,OAAA;;;;;AAsCN;;KA9BM,YAAA,iBAA6B,UAAA,GAAa,aAAA;;;;;;EAMpD,WAAA;;;;;;;EAOA,KAAA,GAAQ,WAAA;EAER,MAAA,GAAS,gBAAA,CAAiB,OAAA;;;;;;;EAO1B,MAAA,GAAS,WAAA;;;;;;EAMT,SAAA;EAEA,IAAA;AAAA"}
@@ -0,0 +1,3 @@
1
+ import { batch } from "./batch.mjs";
2
+
3
+ export { };