@warlock.js/ai 4.4.0 → 4.5.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 (535) hide show
  1. package/CHANGELOG.md +52 -55
  2. package/cjs/index.cjs +221 -14147
  3. package/cjs/src-C02yzsLs.cjs +22991 -0
  4. package/cjs/src-C02yzsLs.cjs.map +1 -0
  5. package/cjs/src-DFibP2FQ.cjs +30 -0
  6. package/esm/agent/agent-config.type.d.mts +90 -1
  7. package/esm/agent/agent-config.type.d.mts.map +1 -1
  8. package/esm/agent/agent-input-builder.mjs +27 -6
  9. package/esm/agent/agent-input-builder.mjs.map +1 -1
  10. package/esm/agent/agent.d.mts +40 -1
  11. package/esm/agent/agent.d.mts.map +1 -1
  12. package/esm/agent/agent.mjs +203 -30
  13. package/esm/agent/agent.mjs.map +1 -1
  14. package/esm/agent/index.d.mts +2 -1
  15. package/esm/agent/index.mjs +1 -0
  16. package/esm/agent/judge-config.type.d.mts +33 -0
  17. package/esm/agent/judge-config.type.d.mts.map +1 -0
  18. package/esm/agent/judge-config.type.mjs +13 -0
  19. package/esm/agent/judge-config.type.mjs.map +1 -0
  20. package/esm/ai-openai/src/embedder.mjs +4 -0
  21. package/esm/ai-openai/src/index.mjs +4 -0
  22. package/esm/ai-openai/src/model.mjs +5 -0
  23. package/esm/ai-openai/src/sdk.mjs +6 -0
  24. package/esm/ai-openai/src/utils/index.mjs +4 -0
  25. package/esm/ai-openai/src/utils/to-openai-tools.mjs +3 -0
  26. package/esm/ai-openai/src/utils/wrap-openai-error.mjs +4 -0
  27. package/esm/ai.d.mts +119 -53
  28. package/esm/ai.d.mts.map +1 -1
  29. package/esm/ai.mjs +43 -8
  30. package/esm/ai.mjs.map +1 -1
  31. package/esm/batch/batch.d.mts.map +1 -1
  32. package/esm/batch/batch.mjs +21 -1
  33. package/esm/batch/batch.mjs.map +1 -1
  34. package/esm/batch/batch.type.d.mts +11 -4
  35. package/esm/batch/batch.type.d.mts.map +1 -1
  36. package/esm/config.d.mts +39 -3
  37. package/esm/config.d.mts.map +1 -1
  38. package/esm/config.mjs +26 -2
  39. package/esm/config.mjs.map +1 -1
  40. package/esm/contracts/agent/agent-options.type.d.mts +11 -3
  41. package/esm/contracts/agent/agent-options.type.d.mts.map +1 -1
  42. package/esm/contracts/agent/eval.type.d.mts +43 -2
  43. package/esm/contracts/agent/eval.type.d.mts.map +1 -1
  44. package/esm/contracts/attachment-policy.type.d.mts +51 -0
  45. package/esm/contracts/attachment-policy.type.d.mts.map +1 -0
  46. package/esm/contracts/attachment.type.d.mts +16 -7
  47. package/esm/contracts/attachment.type.d.mts.map +1 -1
  48. package/esm/contracts/content-part.type.d.mts +14 -5
  49. package/esm/contracts/content-part.type.d.mts.map +1 -1
  50. package/esm/contracts/events/supervisor-events.type.d.mts.map +1 -1
  51. package/esm/contracts/index.d.mts +6 -4
  52. package/esm/contracts/model.contract.d.mts +11 -8
  53. package/esm/contracts/model.contract.d.mts.map +1 -1
  54. package/esm/contracts/orchestrator/index.d.mts +1 -0
  55. package/esm/contracts/orchestrator/orchestrator-config.type.d.mts +31 -2
  56. package/esm/contracts/orchestrator/orchestrator-config.type.d.mts.map +1 -1
  57. package/esm/contracts/orchestrator/session-lock.contract.d.mts +47 -0
  58. package/esm/contracts/orchestrator/session-lock.contract.d.mts.map +1 -0
  59. package/esm/contracts/planner/index.d.mts +1 -1
  60. package/esm/contracts/planner/planner-config.type.d.mts +31 -0
  61. package/esm/contracts/planner/planner-config.type.d.mts.map +1 -1
  62. package/esm/contracts/planner/planner-execute-options.type.d.mts +48 -1
  63. package/esm/contracts/planner/planner-execute-options.type.d.mts.map +1 -1
  64. package/esm/contracts/planner/planner-result.type.d.mts +8 -0
  65. package/esm/contracts/planner/planner-result.type.d.mts.map +1 -1
  66. package/esm/contracts/planner/planner.contract.d.mts +1 -1
  67. package/esm/contracts/result/agent-result.type.d.mts +6 -4
  68. package/esm/contracts/result/agent-result.type.d.mts.map +1 -1
  69. package/esm/contracts/result/base-report.type.d.mts +21 -3
  70. package/esm/contracts/result/base-report.type.d.mts.map +1 -1
  71. package/esm/contracts/result/base-report.type.mjs.map +1 -1
  72. package/esm/contracts/result/execution-report.type.d.mts +53 -1
  73. package/esm/contracts/result/execution-report.type.d.mts.map +1 -1
  74. package/esm/contracts/result/supervisor-result.type.d.mts +14 -2
  75. package/esm/contracts/result/supervisor-result.type.d.mts.map +1 -1
  76. package/esm/contracts/result/workflow-result.type.d.mts +2 -1
  77. package/esm/contracts/result/workflow-result.type.d.mts.map +1 -1
  78. package/esm/contracts/supervisor/supervisor-config.type.d.mts +29 -0
  79. package/esm/contracts/supervisor/supervisor-config.type.d.mts.map +1 -1
  80. package/esm/contracts/system-prompt.contract.d.mts +103 -1
  81. package/esm/contracts/system-prompt.contract.d.mts.map +1 -1
  82. package/esm/contracts/team/index.d.mts +1 -0
  83. package/esm/contracts/team/team-config.type.d.mts +127 -0
  84. package/esm/contracts/team/team-config.type.d.mts.map +1 -0
  85. package/esm/contracts/tool.contract.d.mts +4 -2
  86. package/esm/contracts/tool.contract.d.mts.map +1 -1
  87. package/esm/contracts/workflow/step.contract.d.mts +30 -5
  88. package/esm/contracts/workflow/step.contract.d.mts.map +1 -1
  89. package/esm/contracts/workflow/workflow.contract.d.mts +16 -0
  90. package/esm/contracts/workflow/workflow.contract.d.mts.map +1 -1
  91. package/esm/errors/error-code.type.d.mts +1 -1
  92. package/esm/errors/index.d.mts +1 -0
  93. package/esm/errors/index.mjs +1 -0
  94. package/esm/errors/outbound-policy-error.d.mts +27 -0
  95. package/esm/errors/outbound-policy-error.d.mts.map +1 -0
  96. package/esm/errors/outbound-policy-error.mjs +32 -0
  97. package/esm/errors/outbound-policy-error.mjs.map +1 -0
  98. package/esm/eval/dataset.d.mts +28 -0
  99. package/esm/eval/dataset.d.mts.map +1 -0
  100. package/esm/eval/dataset.mjs +112 -0
  101. package/esm/eval/dataset.mjs.map +1 -0
  102. package/esm/eval/dataset.type.d.mts +53 -0
  103. package/esm/eval/dataset.type.d.mts.map +1 -0
  104. package/esm/eval/eval-runner.d.mts.map +1 -1
  105. package/esm/eval/eval-runner.mjs +16 -2
  106. package/esm/eval/eval-runner.mjs.map +1 -1
  107. package/esm/eval/index.d.mts +20 -1
  108. package/esm/eval/index.d.mts.map +1 -1
  109. package/esm/eval/index.mjs +20 -2
  110. package/esm/eval/index.mjs.map +1 -1
  111. package/esm/eval/regression.d.mts +30 -0
  112. package/esm/eval/regression.d.mts.map +1 -0
  113. package/esm/eval/regression.mjs +51 -0
  114. package/esm/eval/regression.mjs.map +1 -0
  115. package/esm/eval/report-json.d.mts +30 -0
  116. package/esm/eval/report-json.d.mts.map +1 -0
  117. package/esm/eval/report-json.mjs +33 -0
  118. package/esm/eval/report-json.mjs.map +1 -0
  119. package/esm/eval/report-junit.d.mts +22 -0
  120. package/esm/eval/report-junit.d.mts.map +1 -0
  121. package/esm/eval/report-junit.mjs +60 -0
  122. package/esm/eval/report-junit.mjs.map +1 -0
  123. package/esm/guard/contracts/guard-options.type.d.mts +165 -0
  124. package/esm/guard/contracts/guard-options.type.d.mts.map +1 -0
  125. package/esm/guard/contracts/guardrail.contract.d.mts +78 -0
  126. package/esm/guard/contracts/guardrail.contract.d.mts.map +1 -0
  127. package/esm/guard/contracts/index.d.mts +4 -0
  128. package/esm/guard/contracts/openai-client.contract.d.mts +51 -0
  129. package/esm/guard/contracts/openai-client.contract.d.mts.map +1 -0
  130. package/esm/guard/contracts/verdict.type.d.mts +76 -0
  131. package/esm/guard/contracts/verdict.type.d.mts.map +1 -0
  132. package/esm/guard/detectors/index.d.mts +4 -0
  133. package/esm/guard/detectors/index.mjs +6 -0
  134. package/esm/guard/detectors/injection.d.mts +34 -0
  135. package/esm/guard/detectors/injection.d.mts.map +1 -0
  136. package/esm/guard/detectors/injection.mjs +254 -0
  137. package/esm/guard/detectors/injection.mjs.map +1 -0
  138. package/esm/guard/detectors/moderation.d.mts +32 -0
  139. package/esm/guard/detectors/moderation.d.mts.map +1 -0
  140. package/esm/guard/detectors/moderation.mjs +134 -0
  141. package/esm/guard/detectors/moderation.mjs.map +1 -0
  142. package/esm/guard/detectors/pii.d.mts +41 -0
  143. package/esm/guard/detectors/pii.d.mts.map +1 -0
  144. package/esm/guard/detectors/pii.mjs +199 -0
  145. package/esm/guard/detectors/pii.mjs.map +1 -0
  146. package/esm/guard/detectors/topic.d.mts +29 -0
  147. package/esm/guard/detectors/topic.d.mts.map +1 -0
  148. package/esm/guard/detectors/topic.mjs +99 -0
  149. package/esm/guard/detectors/topic.mjs.map +1 -0
  150. package/esm/guard/errors.d.mts +12 -0
  151. package/esm/guard/errors.d.mts.map +1 -0
  152. package/esm/guard/errors.mjs +18 -0
  153. package/esm/guard/errors.mjs.map +1 -0
  154. package/esm/guard/guard.d.mts +67 -0
  155. package/esm/guard/guard.d.mts.map +1 -0
  156. package/esm/guard/guard.mjs +209 -0
  157. package/esm/guard/guard.mjs.map +1 -0
  158. package/esm/guard/guardrail.d.mts +39 -0
  159. package/esm/guard/guardrail.d.mts.map +1 -0
  160. package/esm/guard/guardrail.mjs +22 -0
  161. package/esm/guard/guardrail.mjs.map +1 -0
  162. package/esm/human/contracts/approval.type.d.mts +154 -0
  163. package/esm/human/contracts/approval.type.d.mts.map +1 -0
  164. package/esm/human/contracts/human-approval.type.d.mts +38 -0
  165. package/esm/human/contracts/human-approval.type.d.mts.map +1 -0
  166. package/esm/human/contracts/index.d.mts +4 -0
  167. package/esm/human/contracts/interrupt-store.contract.d.mts +112 -0
  168. package/esm/human/contracts/interrupt-store.contract.d.mts.map +1 -0
  169. package/esm/human/contracts/resume.type.d.mts +77 -0
  170. package/esm/human/contracts/resume.type.d.mts.map +1 -0
  171. package/esm/human/errors.d.mts +84 -0
  172. package/esm/human/errors.d.mts.map +1 -0
  173. package/esm/human/errors.mjs +60 -0
  174. package/esm/human/errors.mjs.map +1 -0
  175. package/esm/human/human-approval.d.mts +57 -0
  176. package/esm/human/human-approval.d.mts.map +1 -0
  177. package/esm/human/human-approval.mjs +170 -0
  178. package/esm/human/human-approval.mjs.map +1 -0
  179. package/esm/human/policy.d.mts +55 -0
  180. package/esm/human/policy.d.mts.map +1 -0
  181. package/esm/human/policy.mjs +67 -0
  182. package/esm/human/policy.mjs.map +1 -0
  183. package/esm/human/register.mjs +37 -0
  184. package/esm/human/register.mjs.map +1 -0
  185. package/esm/human/resume-seed.mjs +53 -0
  186. package/esm/human/resume-seed.mjs.map +1 -0
  187. package/esm/human/resume.d.mts +54 -0
  188. package/esm/human/resume.d.mts.map +1 -0
  189. package/esm/human/resume.mjs +121 -0
  190. package/esm/human/resume.mjs.map +1 -0
  191. package/esm/human/stores/index.mjs +5 -0
  192. package/esm/human/stores/memory.d.mts +30 -0
  193. package/esm/human/stores/memory.d.mts.map +1 -0
  194. package/esm/human/stores/memory.mjs +91 -0
  195. package/esm/human/stores/memory.mjs.map +1 -0
  196. package/esm/human/stores/pg.d.mts +59 -0
  197. package/esm/human/stores/pg.d.mts.map +1 -0
  198. package/esm/human/stores/pg.mjs +220 -0
  199. package/esm/human/stores/pg.mjs.map +1 -0
  200. package/esm/human/stores/redis.d.mts +56 -0
  201. package/esm/human/stores/redis.d.mts.map +1 -0
  202. package/esm/human/stores/redis.mjs +201 -0
  203. package/esm/human/stores/redis.mjs.map +1 -0
  204. package/esm/index.d.mts +113 -22
  205. package/esm/index.mjs +82 -11
  206. package/esm/middleware/builtins/budget.mjs +6 -2
  207. package/esm/middleware/builtins/budget.mjs.map +1 -1
  208. package/esm/middleware/utils/extract-user-text.d.mts +8 -1
  209. package/esm/middleware/utils/extract-user-text.d.mts.map +1 -1
  210. package/esm/middleware/utils/extract-user-text.mjs +8 -1
  211. package/esm/middleware/utils/extract-user-text.mjs.map +1 -1
  212. package/esm/object-stream/index.d.mts +2 -0
  213. package/esm/object-stream/index.mjs +4 -0
  214. package/esm/object-stream/parse-partial-json.d.mts +22 -0
  215. package/esm/object-stream/parse-partial-json.d.mts.map +1 -0
  216. package/esm/object-stream/parse-partial-json.mjs +78 -0
  217. package/esm/object-stream/parse-partial-json.mjs.map +1 -0
  218. package/esm/object-stream/stream-object.d.mts +68 -0
  219. package/esm/object-stream/stream-object.d.mts.map +1 -0
  220. package/esm/object-stream/stream-object.mjs +104 -0
  221. package/esm/object-stream/stream-object.mjs.map +1 -0
  222. package/esm/observe/index.mjs +4 -0
  223. package/esm/observe/observer-registry.d.mts +30 -0
  224. package/esm/observe/observer-registry.d.mts.map +1 -0
  225. package/esm/observe/observer-registry.mjs +51 -0
  226. package/esm/observe/observer-registry.mjs.map +1 -0
  227. package/esm/observe/observer.contract.d.mts +40 -0
  228. package/esm/observe/observer.contract.d.mts.map +1 -0
  229. package/esm/observe/resolve-observers.d.mts +40 -0
  230. package/esm/observe/resolve-observers.d.mts.map +1 -0
  231. package/esm/observe/resolve-observers.mjs +73 -0
  232. package/esm/observe/resolve-observers.mjs.map +1 -0
  233. package/esm/orchestrator/execution.d.mts.map +1 -1
  234. package/esm/orchestrator/execution.mjs +5 -2
  235. package/esm/orchestrator/execution.mjs.map +1 -1
  236. package/esm/orchestrator/index.d.mts +1 -0
  237. package/esm/orchestrator/index.mjs +1 -0
  238. package/esm/orchestrator/orchestrator.d.mts.map +1 -1
  239. package/esm/orchestrator/orchestrator.mjs +39 -6
  240. package/esm/orchestrator/orchestrator.mjs.map +1 -1
  241. package/esm/orchestrator/session-lock.d.mts +25 -0
  242. package/esm/orchestrator/session-lock.d.mts.map +1 -0
  243. package/esm/orchestrator/session-lock.mjs +83 -0
  244. package/esm/orchestrator/session-lock.mjs.map +1 -0
  245. package/esm/planner/dag-scheduler.mjs +97 -0
  246. package/esm/planner/dag-scheduler.mjs.map +1 -0
  247. package/esm/planner/plan-prompt.d.mts +1 -1
  248. package/esm/planner/plan-prompt.d.mts.map +1 -1
  249. package/esm/planner/plan-prompt.mjs +2 -1
  250. package/esm/planner/plan-prompt.mjs.map +1 -1
  251. package/esm/planner/planner-run.d.mts.map +1 -1
  252. package/esm/planner/planner-run.mjs +300 -29
  253. package/esm/planner/planner-run.mjs.map +1 -1
  254. package/esm/planner/planner.mjs +1 -1
  255. package/esm/planner/planner.mjs.map +1 -1
  256. package/esm/prompt/errors.d.mts +57 -0
  257. package/esm/prompt/errors.d.mts.map +1 -0
  258. package/esm/prompt/errors.mjs +73 -0
  259. package/esm/prompt/errors.mjs.map +1 -0
  260. package/esm/prompt/index.d.mts +3 -0
  261. package/esm/prompt/index.mjs +4 -0
  262. package/esm/prompt/prompt-langfuse-sync.mjs +104 -0
  263. package/esm/prompt/prompt-langfuse-sync.mjs.map +1 -0
  264. package/esm/prompt/prompt-langfuse-sync.type.d.mts +32 -0
  265. package/esm/prompt/prompt-langfuse-sync.type.d.mts.map +1 -0
  266. package/esm/prompt/prompt-validate.mjs +170 -0
  267. package/esm/prompt/prompt-validate.mjs.map +1 -0
  268. package/esm/prompt/prompt.d.mts +54 -0
  269. package/esm/prompt/prompt.d.mts.map +1 -0
  270. package/esm/prompt/prompt.mjs +218 -0
  271. package/esm/prompt/prompt.mjs.map +1 -0
  272. package/esm/prompt/prompt.type.d.mts +174 -0
  273. package/esm/prompt/prompt.type.d.mts.map +1 -0
  274. package/esm/prompts/index.d.mts +3 -0
  275. package/esm/prompts/index.mjs +3 -0
  276. package/esm/prompts/prompts-manager.contract.d.mts +154 -0
  277. package/esm/prompts/prompts-manager.contract.d.mts.map +1 -0
  278. package/esm/prompts/prompts-manager.d.mts +38 -0
  279. package/esm/prompts/prompts-manager.d.mts.map +1 -0
  280. package/esm/prompts/prompts-manager.mjs +410 -0
  281. package/esm/prompts/prompts-manager.mjs.map +1 -0
  282. package/esm/prompts/prompts-manager.type.d.mts +172 -0
  283. package/esm/prompts/prompts-manager.type.d.mts.map +1 -0
  284. package/esm/prompts/prompts-validate.mjs +200 -0
  285. package/esm/prompts/prompts-validate.mjs.map +1 -0
  286. package/esm/rag/as-tool.mjs +48 -0
  287. package/esm/rag/as-tool.mjs.map +1 -0
  288. package/esm/rag/chunk/chunk.d.mts +24 -0
  289. package/esm/rag/chunk/chunk.d.mts.map +1 -0
  290. package/esm/rag/chunk/chunk.mjs +44 -0
  291. package/esm/rag/chunk/chunk.mjs.map +1 -0
  292. package/esm/rag/chunk/fixed.mjs +32 -0
  293. package/esm/rag/chunk/fixed.mjs.map +1 -0
  294. package/esm/rag/chunk/markdown.mjs +75 -0
  295. package/esm/rag/chunk/markdown.mjs.map +1 -0
  296. package/esm/rag/chunk/recursive.mjs +132 -0
  297. package/esm/rag/chunk/recursive.mjs.map +1 -0
  298. package/esm/rag/chunk/sentence.mjs +73 -0
  299. package/esm/rag/chunk/sentence.mjs.map +1 -0
  300. package/esm/rag/contracts/chunk-options.type.d.mts +35 -0
  301. package/esm/rag/contracts/chunk-options.type.d.mts.map +1 -0
  302. package/esm/rag/contracts/citation.type.d.mts +35 -0
  303. package/esm/rag/contracts/citation.type.d.mts.map +1 -0
  304. package/esm/rag/contracts/index.d.mts +4 -0
  305. package/esm/rag/contracts/rag-config.type.d.mts +68 -0
  306. package/esm/rag/contracts/rag-config.type.d.mts.map +1 -0
  307. package/esm/rag/contracts/rag-document.type.d.mts +21 -0
  308. package/esm/rag/contracts/rag-document.type.d.mts.map +1 -0
  309. package/esm/rag/hybrid/bm25.d.mts +23 -0
  310. package/esm/rag/hybrid/bm25.d.mts.map +1 -0
  311. package/esm/rag/hybrid/bm25.mjs +51 -0
  312. package/esm/rag/hybrid/bm25.mjs.map +1 -0
  313. package/esm/rag/hybrid/hybrid-rank.d.mts +33 -0
  314. package/esm/rag/hybrid/hybrid-rank.d.mts.map +1 -0
  315. package/esm/rag/hybrid/hybrid-rank.mjs +29 -0
  316. package/esm/rag/hybrid/hybrid-rank.mjs.map +1 -0
  317. package/esm/rag/hybrid/rrf.d.mts +25 -0
  318. package/esm/rag/hybrid/rrf.d.mts.map +1 -0
  319. package/esm/rag/hybrid/rrf.mjs +30 -0
  320. package/esm/rag/hybrid/rrf.mjs.map +1 -0
  321. package/esm/rag/index.d.mts +15 -0
  322. package/esm/rag/index.mjs +11 -0
  323. package/esm/rag/rag.d.mts +38 -0
  324. package/esm/rag/rag.d.mts.map +1 -0
  325. package/esm/rag/rag.mjs +126 -0
  326. package/esm/rag/rag.mjs.map +1 -0
  327. package/esm/rag/rerank/keyword-reranker.d.mts +32 -0
  328. package/esm/rag/rerank/keyword-reranker.d.mts.map +1 -0
  329. package/esm/rag/rerank/keyword-reranker.mjs +58 -0
  330. package/esm/rag/rerank/keyword-reranker.mjs.map +1 -0
  331. package/esm/rag/rerank/llm-reranker.d.mts +36 -0
  332. package/esm/rag/rerank/llm-reranker.d.mts.map +1 -0
  333. package/esm/rag/rerank/llm-reranker.mjs +85 -0
  334. package/esm/rag/rerank/llm-reranker.mjs.map +1 -0
  335. package/esm/rag/rerank/reranker.contract.d.mts +28 -0
  336. package/esm/rag/rerank/reranker.contract.d.mts.map +1 -0
  337. package/esm/rag/retrieve.mjs +68 -0
  338. package/esm/rag/retrieve.mjs.map +1 -0
  339. package/esm/rag/store/cache-vector-store.d.mts +27 -0
  340. package/esm/rag/store/cache-vector-store.d.mts.map +1 -0
  341. package/esm/rag/store/cache-vector-store.mjs +48 -0
  342. package/esm/rag/store/cache-vector-store.mjs.map +1 -0
  343. package/esm/rag/store/vector-store.contract.d.mts +38 -0
  344. package/esm/rag/store/vector-store.contract.d.mts.map +1 -0
  345. package/esm/rag/transforms/multi-query.d.mts +27 -0
  346. package/esm/rag/transforms/multi-query.d.mts.map +1 -0
  347. package/esm/rag/transforms/multi-query.mjs +41 -0
  348. package/esm/rag/transforms/multi-query.mjs.map +1 -0
  349. package/esm/security/index.mjs +5 -0
  350. package/esm/security/outbound-policy.d.mts +46 -0
  351. package/esm/security/outbound-policy.d.mts.map +1 -0
  352. package/esm/security/outbound-policy.mjs +187 -0
  353. package/esm/security/outbound-policy.mjs.map +1 -0
  354. package/esm/security/outbound-policy.type.d.mts +74 -0
  355. package/esm/security/outbound-policy.type.d.mts.map +1 -0
  356. package/esm/security/private-ip.d.mts +15 -0
  357. package/esm/security/private-ip.d.mts.map +1 -0
  358. package/esm/security/private-ip.mjs +48 -0
  359. package/esm/security/private-ip.mjs.map +1 -0
  360. package/esm/security/redact.d.mts +59 -0
  361. package/esm/security/redact.d.mts.map +1 -0
  362. package/esm/security/redact.mjs +122 -0
  363. package/esm/security/redact.mjs.map +1 -0
  364. package/esm/serve/serve.d.mts +50 -0
  365. package/esm/serve/serve.d.mts.map +1 -0
  366. package/esm/serve/serve.mjs +90 -0
  367. package/esm/serve/serve.mjs.map +1 -0
  368. package/esm/serve/sse.d.mts +20 -0
  369. package/esm/serve/sse.d.mts.map +1 -0
  370. package/esm/serve/sse.mjs +25 -0
  371. package/esm/serve/sse.mjs.map +1 -0
  372. package/esm/serve/stream-to-sse.d.mts +29 -0
  373. package/esm/serve/stream-to-sse.d.mts.map +1 -0
  374. package/esm/serve/stream-to-sse.mjs +37 -0
  375. package/esm/serve/stream-to-sse.mjs.map +1 -0
  376. package/esm/skills/catalog.d.mts +49 -0
  377. package/esm/skills/catalog.d.mts.map +1 -0
  378. package/esm/skills/catalog.mjs +140 -0
  379. package/esm/skills/catalog.mjs.map +1 -0
  380. package/esm/skills/contracts/skill-record.type.d.mts +37 -0
  381. package/esm/skills/contracts/skill-record.type.d.mts.map +1 -0
  382. package/esm/skills/contracts/skills-config.type.d.mts +108 -0
  383. package/esm/skills/contracts/skills-config.type.d.mts.map +1 -0
  384. package/esm/skills/contracts/skills-store.contract.d.mts +28 -0
  385. package/esm/skills/contracts/skills-store.contract.d.mts.map +1 -0
  386. package/esm/skills/contracts/skills.contract.d.mts +43 -0
  387. package/esm/skills/contracts/skills.contract.d.mts.map +1 -0
  388. package/esm/skills/index.d.mts +16 -0
  389. package/esm/skills/index.mjs +14 -0
  390. package/esm/skills/load-skill-tool.d.mts +38 -0
  391. package/esm/skills/load-skill-tool.d.mts.map +1 -0
  392. package/esm/skills/load-skill-tool.mjs +65 -0
  393. package/esm/skills/load-skill-tool.mjs.map +1 -0
  394. package/esm/skills/review-gate.d.mts +33 -0
  395. package/esm/skills/review-gate.d.mts.map +1 -0
  396. package/esm/skills/review-gate.mjs +60 -0
  397. package/esm/skills/review-gate.mjs.map +1 -0
  398. package/esm/skills/save-skill-tool.d.mts +39 -0
  399. package/esm/skills/save-skill-tool.d.mts.map +1 -0
  400. package/esm/skills/save-skill-tool.mjs +65 -0
  401. package/esm/skills/save-skill-tool.mjs.map +1 -0
  402. package/esm/skills/skills.d.mts +33 -0
  403. package/esm/skills/skills.d.mts.map +1 -0
  404. package/esm/skills/skills.mjs +109 -0
  405. package/esm/skills/skills.mjs.map +1 -0
  406. package/esm/skills/sources/directory-source.d.mts +19 -0
  407. package/esm/skills/sources/directory-source.d.mts.map +1 -0
  408. package/esm/skills/sources/directory-source.mjs +108 -0
  409. package/esm/skills/sources/directory-source.mjs.map +1 -0
  410. package/esm/skills/sources/index.d.mts +18 -0
  411. package/esm/skills/sources/index.d.mts.map +1 -0
  412. package/esm/skills/sources/index.mjs +27 -0
  413. package/esm/skills/sources/index.mjs.map +1 -0
  414. package/esm/skills/sources/parse-frontmatter.d.mts +27 -0
  415. package/esm/skills/sources/parse-frontmatter.d.mts.map +1 -0
  416. package/esm/skills/sources/parse-frontmatter.mjs +46 -0
  417. package/esm/skills/sources/parse-frontmatter.mjs.map +1 -0
  418. package/esm/skills/sources/store-source.d.mts +14 -0
  419. package/esm/skills/sources/store-source.d.mts.map +1 -0
  420. package/esm/skills/sources/store-source.mjs +15 -0
  421. package/esm/skills/sources/store-source.mjs.map +1 -0
  422. package/esm/skills/sources/url-source.d.mts +29 -0
  423. package/esm/skills/sources/url-source.d.mts.map +1 -0
  424. package/esm/skills/sources/url-source.mjs +117 -0
  425. package/esm/skills/sources/url-source.mjs.map +1 -0
  426. package/esm/skills/store/mock-skills-store.d.mts +57 -0
  427. package/esm/skills/store/mock-skills-store.d.mts.map +1 -0
  428. package/esm/skills/store/mock-skills-store.mjs +100 -0
  429. package/esm/skills/store/mock-skills-store.mjs.map +1 -0
  430. package/esm/skills/store/procedural-skill-store.d.mts +30 -0
  431. package/esm/skills/store/procedural-skill-store.d.mts.map +1 -0
  432. package/esm/skills/store/procedural-skill-store.mjs +125 -0
  433. package/esm/skills/store/procedural-skill-store.mjs.map +1 -0
  434. package/esm/supervisor/as-tool.mjs +2 -2
  435. package/esm/supervisor/as-tool.mjs.map +1 -1
  436. package/esm/supervisor/execution.d.mts.map +1 -1
  437. package/esm/supervisor/execution.mjs +31 -28
  438. package/esm/supervisor/execution.mjs.map +1 -1
  439. package/esm/supervisor/supervisor.d.mts.map +1 -1
  440. package/esm/supervisor/supervisor.mjs +8 -3
  441. package/esm/supervisor/supervisor.mjs.map +1 -1
  442. package/esm/system-prompt/index.d.mts +4 -0
  443. package/esm/system-prompt/system-prompt.d.mts +68 -4
  444. package/esm/system-prompt/system-prompt.d.mts.map +1 -1
  445. package/esm/system-prompt/system-prompt.mjs +89 -5
  446. package/esm/system-prompt/system-prompt.mjs.map +1 -1
  447. package/esm/team/gates.mjs +48 -0
  448. package/esm/team/gates.mjs.map +1 -0
  449. package/esm/team/index.d.mts +1 -0
  450. package/esm/team/index.mjs +3 -0
  451. package/esm/team/team.d.mts +42 -0
  452. package/esm/team/team.d.mts.map +1 -0
  453. package/esm/team/team.mjs +94 -0
  454. package/esm/team/team.mjs.map +1 -0
  455. package/esm/tool/executable-as-tool.d.mts.map +1 -1
  456. package/esm/tool/executable-as-tool.mjs +2 -2
  457. package/esm/tool/executable-as-tool.mjs.map +1 -1
  458. package/esm/tool/tool.d.mts.map +1 -1
  459. package/esm/tool/tool.mjs +2 -2
  460. package/esm/tool/tool.mjs.map +1 -1
  461. package/esm/utils/compute-cost.d.mts +17 -1
  462. package/esm/utils/compute-cost.d.mts.map +1 -1
  463. package/esm/utils/compute-cost.mjs +26 -1
  464. package/esm/utils/compute-cost.mjs.map +1 -1
  465. package/esm/utils/extract-json-lenient.d.mts +42 -0
  466. package/esm/utils/extract-json-lenient.d.mts.map +1 -0
  467. package/esm/utils/extract-json-lenient.mjs +97 -0
  468. package/esm/utils/extract-json-lenient.mjs.map +1 -0
  469. package/esm/utils/index.d.mts +4 -2
  470. package/esm/utils/index.mjs +3 -1
  471. package/esm/utils/json-schema.d.mts +1 -1
  472. package/esm/utils/prepare-attachment-part.d.mts +10 -1
  473. package/esm/utils/prepare-attachment-part.d.mts.map +1 -1
  474. package/esm/utils/prepare-attachment-part.mjs +103 -11
  475. package/esm/utils/prepare-attachment-part.mjs.map +1 -1
  476. package/esm/utils/resolve-attachment.d.mts +4 -3
  477. package/esm/utils/resolve-attachment.d.mts.map +1 -1
  478. package/esm/utils/resolve-attachment.mjs +4 -3
  479. package/esm/utils/resolve-attachment.mjs.map +1 -1
  480. package/esm/utils/run-context.d.mts +94 -0
  481. package/esm/utils/run-context.d.mts.map +1 -0
  482. package/esm/utils/run-context.mjs +98 -0
  483. package/esm/utils/run-context.mjs.map +1 -0
  484. package/esm/vcr/cassette-io.mjs +57 -0
  485. package/esm/vcr/cassette-io.mjs.map +1 -0
  486. package/esm/vcr/errors.d.mts +42 -0
  487. package/esm/vcr/errors.d.mts.map +1 -0
  488. package/esm/vcr/errors.mjs +37 -0
  489. package/esm/vcr/errors.mjs.map +1 -0
  490. package/esm/vcr/hash-request.d.mts +28 -0
  491. package/esm/vcr/hash-request.d.mts.map +1 -0
  492. package/esm/vcr/hash-request.mjs +118 -0
  493. package/esm/vcr/hash-request.mjs.map +1 -0
  494. package/esm/vcr/index.d.mts +4 -0
  495. package/esm/vcr/index.mjs +5 -0
  496. package/esm/vcr/vcr.d.mts +32 -0
  497. package/esm/vcr/vcr.d.mts.map +1 -0
  498. package/esm/vcr/vcr.mjs +248 -0
  499. package/esm/vcr/vcr.mjs.map +1 -0
  500. package/esm/vcr/vcr.type.d.mts +118 -0
  501. package/esm/vcr/vcr.type.d.mts.map +1 -0
  502. package/esm/workflow/as-tool.mjs +2 -2
  503. package/esm/workflow/as-tool.mjs.map +1 -1
  504. package/esm/workflow/engine.mjs +1 -0
  505. package/esm/workflow/engine.mjs.map +1 -1
  506. package/esm/workflow/step-runner.mjs +19 -20
  507. package/esm/workflow/step-runner.mjs.map +1 -1
  508. package/esm/workflow/workflow.d.mts.map +1 -1
  509. package/esm/workflow/workflow.mjs +8 -3
  510. package/esm/workflow/workflow.mjs.map +1 -1
  511. package/llms-full.txt +1683 -68
  512. package/llms.txt +16 -4
  513. package/package.json +7 -3
  514. package/skills/README.md +40 -4
  515. package/skills/ai-dx-helpers/SKILL.md +2 -2
  516. package/skills/approve-tool-calls/SKILL.md +134 -0
  517. package/skills/attach-ai-middleware/SKILL.md +1 -1
  518. package/skills/detect-and-redact-pii/SKILL.md +104 -0
  519. package/skills/durable-resume/SKILL.md +128 -0
  520. package/skills/escalate-block-to-human/SKILL.md +85 -0
  521. package/skills/eval-datasets-and-ci/SKILL.md +117 -0
  522. package/skills/guard-input-output/SKILL.md +117 -0
  523. package/skills/manage-prompts/SKILL.md +186 -0
  524. package/skills/observe-ai-flows/SKILL.md +94 -0
  525. package/skills/record-replay-llm/SKILL.md +92 -0
  526. package/skills/run-ai-agent/SKILL.md +26 -1
  527. package/skills/run-ai-rag/SKILL.md +139 -0
  528. package/skills/run-ai-team/SKILL.md +107 -0
  529. package/skills/run-orchestrator/SKILL.md +2 -0
  530. package/skills/run-planner/SKILL.md +73 -8
  531. package/skills/run-supervisor/SKILL.md +20 -1
  532. package/skills/use-runtime-skills/SKILL.md +106 -0
  533. package/skills/write-system-prompt/SKILL.md +30 -1
  534. package/cjs/index.cjs.map +0 -1
  535. package/esm/contracts/result/index.d.mts +0 -15
@@ -0,0 +1,94 @@
1
+ import { SupervisorFailedError } from "../errors/supervisor-failed-error.mjs";
2
+ import "../errors/index.mjs";
3
+ import { supervisor } from "../supervisor/supervisor.mjs";
4
+ import { buildQualityGate, buildVerifyGate } from "./gates.mjs";
5
+
6
+ //#region ../@warlock.js/ai/src/team/team.ts
7
+ /**
8
+ * `ai.team(config)` — thin, transparent sugar over `ai.supervisor`.
9
+ *
10
+ * Builds a {@link SupervisorConfig} from the team-shaped config and
11
+ * calls `supervisor(...)`, returning the **unchanged**
12
+ * `SupervisorContract<TOutput>` — the same object `ai.supervisor`
13
+ * returns, so `ctx.intents.<member>.execute()`, `.asTool()`,
14
+ * `.resume()`, snapshots, and events all stay intact. `team()` owns no
15
+ * loop: the manager becomes `route`/`router`, the members become
16
+ * `intents`, and the `gate` becomes `evaluate`. Everything else passes
17
+ * through 1:1.
18
+ *
19
+ * A `gate: "quality" | "verify"` string selects a pre-built `evaluate`
20
+ * strategy ({@link buildQualityGate} / {@link buildVerifyGate}); a
21
+ * function forwards straight to `SupervisorConfig.evaluate` (full
22
+ * escape hatch). When the gate is a string, the resolved `fixer` (and,
23
+ * for `"quality"`, the `reviewer`) roles are validated against
24
+ * `members` at construction — a missing role throws an authoring-style
25
+ * {@link SupervisorFailedError} (`context: { authoring: true }`) rather
26
+ * than silently starving until `maxIterations`.
27
+ *
28
+ * @example
29
+ * const codeTeam = ai.team({
30
+ * name: "code-team",
31
+ * goal: "Ship a tested module that passes review.",
32
+ * manager: techLeadRouter,
33
+ * members: { builder, reviewer, fixer },
34
+ * gate: "quality",
35
+ * output: v.object({ code: v.string() }),
36
+ * maxIterations: 6,
37
+ * });
38
+ *
39
+ * const { data, report } = await codeTeam.execute("Build a debounce<T> utility.");
40
+ */
41
+ function team(config) {
42
+ const supervisorConfig = {
43
+ name: config.name,
44
+ version: config.version,
45
+ reportType: "team",
46
+ intents: config.members,
47
+ evaluate: resolveGate(config),
48
+ goal: config.goal,
49
+ output: config.output,
50
+ state: config.state,
51
+ maxIterations: config.maxIterations,
52
+ snapshotStore: config.snapshotStore,
53
+ on: config.on,
54
+ observe: config.observe
55
+ };
56
+ if (isRouteManager(config.manager)) supervisorConfig.route = config.manager.route;
57
+ else supervisorConfig.router = config.manager;
58
+ return supervisor(supervisorConfig);
59
+ }
60
+ /**
61
+ * Resolve the team's `gate` into a concrete `evaluate` callback. A
62
+ * function forwards untouched; a {@link TeamGate} string is validated
63
+ * against `members` and desugared into the matching pre-built gate.
64
+ */
65
+ function resolveGate(config) {
66
+ if (typeof config.gate === "function") return config.gate;
67
+ const gate = config.gate;
68
+ const fixerRole = config.roles?.fixer ?? "fixer";
69
+ assertMemberExists(config, fixerRole, "fixer");
70
+ if (gate === "quality") {
71
+ assertMemberExists(config, config.roles?.reviewer ?? "reviewer", "reviewer");
72
+ return buildQualityGate(config.gateKey ?? "approved", fixerRole);
73
+ }
74
+ return buildVerifyGate(config.gateKey ?? "passed", fixerRole);
75
+ }
76
+ /**
77
+ * Construction-time guard: assert the resolved role key exists in
78
+ * `members`, throwing an authoring-style {@link SupervisorFailedError}
79
+ * (tagged `authoring: true`) listing the missing role when it doesn't.
80
+ */
81
+ function assertMemberExists(config, role, label) {
82
+ if (!Object.prototype.hasOwnProperty.call(config.members, role)) throw new SupervisorFailedError(`ai.team("${config.name}"): gate "${config.gate}" needs a "${label}" member but no \`members.${role}\` key exists`, { context: { authoring: true } });
83
+ }
84
+ /**
85
+ * Discriminate the `manager` union: `true` when it is the deterministic
86
+ * `{ route }` form, `false` for a bare `AgentContract` / `RouterEntry`.
87
+ */
88
+ function isRouteManager(manager) {
89
+ return typeof manager === "object" && manager !== null && "route" in manager && typeof manager.route === "function";
90
+ }
91
+
92
+ //#endregion
93
+ export { team };
94
+ //# sourceMappingURL=team.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"team.mjs","names":[],"sources":["../../../../../../../@warlock.js/ai/src/team/team.ts"],"sourcesContent":["import type {\n EvaluateContext,\n EvaluateResult,\n} from \"../contracts/supervisor/evaluate-context.type\";\nimport type { SupervisorIntentValue } from \"../contracts/supervisor/intent-entry.type\";\nimport type { SupervisorConfig } from \"../contracts/supervisor/supervisor-config.type\";\nimport type { SupervisorContract } from \"../contracts/supervisor/supervisor.contract\";\nimport type {\n TeamConfig,\n TeamGate,\n TeamGateFn,\n TeamMemberValue,\n} from \"../contracts/team/team-config.type\";\nimport { SupervisorFailedError } from \"../errors\";\nimport { supervisor } from \"../supervisor/supervisor\";\nimport { buildQualityGate, buildVerifyGate } from \"./gates\";\n\n/**\n * `ai.team(config)` — thin, transparent sugar over `ai.supervisor`.\n *\n * Builds a {@link SupervisorConfig} from the team-shaped config and\n * calls `supervisor(...)`, returning the **unchanged**\n * `SupervisorContract<TOutput>` — the same object `ai.supervisor`\n * returns, so `ctx.intents.<member>.execute()`, `.asTool()`,\n * `.resume()`, snapshots, and events all stay intact. `team()` owns no\n * loop: the manager becomes `route`/`router`, the members become\n * `intents`, and the `gate` becomes `evaluate`. Everything else passes\n * through 1:1.\n *\n * A `gate: \"quality\" | \"verify\"` string selects a pre-built `evaluate`\n * strategy ({@link buildQualityGate} / {@link buildVerifyGate}); a\n * function forwards straight to `SupervisorConfig.evaluate` (full\n * escape hatch). When the gate is a string, the resolved `fixer` (and,\n * for `\"quality\"`, the `reviewer`) roles are validated against\n * `members` at construction — a missing role throws an authoring-style\n * {@link SupervisorFailedError} (`context: { authoring: true }`) rather\n * than silently starving until `maxIterations`.\n *\n * @example\n * const codeTeam = ai.team({\n * name: \"code-team\",\n * goal: \"Ship a tested module that passes review.\",\n * manager: techLeadRouter,\n * members: { builder, reviewer, fixer },\n * gate: \"quality\",\n * output: v.object({ code: v.string() }),\n * maxIterations: 6,\n * });\n *\n * const { data, report } = await codeTeam.execute(\"Build a debounce<T> utility.\");\n */\nexport function team<\n TOutput = unknown,\n TState = TOutput,\n TMembers extends Record<string, TeamMemberValue> = Record<string, TeamMemberValue>,\n>(config: TeamConfig<TOutput, TState, TMembers>): SupervisorContract<TOutput> {\n const supervisorConfig: SupervisorConfig<TOutput, TState> = {\n name: config.name,\n version: config.version,\n // Stamp the report/result discriminator as \"team\" so team runs are\n // distinguishable on the wire (Panoptic groups/filters them as their\n // own type) — the only behavioural difference from a plain supervisor.\n reportType: \"team\",\n intents: config.members as unknown as Record<string, SupervisorIntentValue>,\n evaluate: resolveGate<TOutput, TState, TMembers>(config),\n goal: config.goal,\n output: config.output,\n state: config.state,\n maxIterations: config.maxIterations,\n snapshotStore: config.snapshotStore,\n on: config.on,\n // Forward observability verbatim — the supervisor `team()` returns\n // routes its report through the generic Observer seam, so a team\n // inherits observation with no team-specific wiring (F1/F3).\n observe: config.observe,\n };\n\n // Manager → `route` XOR `router`. Reuse the supervisor's own XOR\n // validation; team() forwards exactly one of the two, so a malformed\n // manager surfaces the existing SupervisorFailedError downstream.\n if (isRouteManager(config.manager)) {\n supervisorConfig.route = config.manager.route;\n } else {\n supervisorConfig.router = config.manager;\n }\n\n return supervisor<TOutput, TState>(supervisorConfig);\n}\n\n/**\n * Resolve the team's `gate` into a concrete `evaluate` callback. A\n * function forwards untouched; a {@link TeamGate} string is validated\n * against `members` and desugared into the matching pre-built gate.\n */\nfunction resolveGate<\n TOutput,\n TState,\n TMembers extends Record<string, TeamMemberValue>,\n>(\n config: TeamConfig<TOutput, TState, TMembers>,\n): (ctx: EvaluateContext<TState>) => EvaluateResult | Promise<EvaluateResult> {\n if (typeof config.gate === \"function\") {\n return config.gate as TeamGateFn<TState>;\n }\n\n const gate: TeamGate = config.gate;\n const fixerRole = config.roles?.fixer ?? \"fixer\";\n\n assertMemberExists(config, fixerRole, \"fixer\");\n\n if (gate === \"quality\") {\n const reviewerRole = config.roles?.reviewer ?? \"reviewer\";\n\n assertMemberExists(config, reviewerRole, \"reviewer\");\n\n const gateKey = config.gateKey ?? \"approved\";\n\n return buildQualityGate<TState>(gateKey, fixerRole);\n }\n\n const gateKey = config.gateKey ?? \"passed\";\n\n return buildVerifyGate<TState>(gateKey, fixerRole);\n}\n\n/**\n * Construction-time guard: assert the resolved role key exists in\n * `members`, throwing an authoring-style {@link SupervisorFailedError}\n * (tagged `authoring: true`) listing the missing role when it doesn't.\n */\nfunction assertMemberExists<\n TOutput,\n TState,\n TMembers extends Record<string, TeamMemberValue>,\n>(\n config: TeamConfig<TOutput, TState, TMembers>,\n role: string,\n label: string,\n): void {\n if (!Object.prototype.hasOwnProperty.call(config.members, role)) {\n throw new SupervisorFailedError(\n `ai.team(\"${config.name}\"): gate \"${config.gate as string}\" needs a \"${label}\" member but no \\`members.${role}\\` key exists`,\n { context: { authoring: true } },\n );\n }\n}\n\n/**\n * Discriminate the `manager` union: `true` when it is the deterministic\n * `{ route }` form, `false` for a bare `AgentContract` / `RouterEntry`.\n */\nfunction isRouteManager<TOutput, TState>(\n manager: TeamConfig<TOutput, TState>[\"manager\"],\n): manager is { route: NonNullable<SupervisorConfig<TOutput, TState>[\"route\"]> } {\n return (\n typeof manager === \"object\" &&\n manager !== null &&\n \"route\" in manager &&\n typeof (manager as { route?: unknown }).route === \"function\"\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmDA,SAAgB,KAId,QAA4E;CAC5E,MAAM,mBAAsD;EAC1D,MAAM,OAAO;EACb,SAAS,OAAO;EAIhB,YAAY;EACZ,SAAS,OAAO;EAChB,UAAU,YAAuC,MAAM;EACvD,MAAM,OAAO;EACb,QAAQ,OAAO;EACf,OAAO,OAAO;EACd,eAAe,OAAO;EACtB,eAAe,OAAO;EACtB,IAAI,OAAO;EAIX,SAAS,OAAO;CAClB;CAKA,IAAI,eAAe,OAAO,OAAO,GAC/B,iBAAiB,QAAQ,OAAO,QAAQ;MAExC,iBAAiB,SAAS,OAAO;CAGnC,OAAO,WAA4B,gBAAgB;AACrD;;;;;;AAOA,SAAS,YAKP,QAC4E;CAC5E,IAAI,OAAO,OAAO,SAAS,YACzB,OAAO,OAAO;CAGhB,MAAM,OAAiB,OAAO;CAC9B,MAAM,YAAY,OAAO,OAAO,SAAS;CAEzC,mBAAmB,QAAQ,WAAW,OAAO;CAE7C,IAAI,SAAS,WAAW;EAGtB,mBAAmB,QAFE,OAAO,OAAO,YAAY,YAEN,UAAU;EAInD,OAAO,iBAFS,OAAO,WAAW,YAEO,SAAS;CACpD;CAIA,OAAO,gBAFS,OAAO,WAAW,UAEM,SAAS;AACnD;;;;;;AAOA,SAAS,mBAKP,QACA,MACA,OACM;CACN,IAAI,CAAC,OAAO,UAAU,eAAe,KAAK,OAAO,SAAS,IAAI,GAC5D,MAAM,IAAI,sBACR,YAAY,OAAO,KAAK,YAAY,OAAO,KAAe,aAAa,MAAM,4BAA4B,KAAK,gBAC9G,EAAE,SAAS,EAAE,WAAW,KAAK,EAAE,CACjC;AAEJ;;;;;AAMA,SAAS,eACP,SAC+E;CAC/E,OACE,OAAO,YAAY,YACnB,YAAY,QACZ,WAAW,WACX,OAAQ,QAAgC,UAAU;AAEtD"}
@@ -1 +1 @@
1
- {"version":3,"file":"executable-as-tool.d.mts","names":[],"sources":["../../../../../../../@warlock.js/ai/src/tool/executable-as-tool.ts"],"mappings":";;;;;;;;;;AAK4D;;;;KASvD,kBAAA,YAA8B,UAAA;EACjC,IAAA,GAAO,OAAA;EACP,KAAA,GAAQ,OAAA;EACR,MAAA,EAAQ,UAAA;AAAA;;;;;;;;;;AAAU;AAsBpB;;;;;;;;;KAAY,cAAA;EAAA,SACD,IAAA;EAAA,SACA,WAAA;EAAA,SACA,WAAA,GAAc,gBAAA,CAAiB,MAAA;EACxC,OAAA,CAAQ,KAAA,EAAO,MAAA,EAAQ,OAAA,aAAoB,OAAA,CAAQ,kBAAA,CAAmB,OAAA;EACtE,MAAA;AAAA;;;;;;;KASU,cAAA,wCACR,YAAA,CAAa,MAAA,EAAQ,OAAA,IACrB,cAAA,CAAe,MAAA,EAAQ,OAAA;;;;;AAXnB;AASR;;iBA4BgB,gBAAA,CAAiB,KAAA,YAAiB,KAAA,IAAS,cAAc;;;;;;;;;;;;;;iBAuBzD,gBAAA,kBACd,UAAA,EAAY,cAAA,CAAe,MAAA,EAAQ,OAAA,IAClC,YAAA,CAAa,MAAA,EAAQ,OAAA;;;;AAnDU;AA0BlC;;;;;iBAmEgB,mBAAA,CACd,KAAA,EAAO,aAAA,CAAc,cAAA,gBACpB,YAAA"}
1
+ {"version":3,"file":"executable-as-tool.d.mts","names":[],"sources":["../../../../../../../@warlock.js/ai/src/tool/executable-as-tool.ts"],"mappings":";;;;;;;;;;AAK4D;;;;KASvD,kBAAA,YAA8B,UAAA;EACjC,IAAA,GAAO,OAAA;EACP,KAAA,GAAQ,OAAA;EACR,MAAA,EAAQ,UAAA;AAAA;;;;;;;;;;AAAU;AAsBpB;;;;;;;;;KAAY,cAAA;EAAA,SACD,IAAA;EAAA,SACA,WAAA;EAAA,SACA,WAAA,GAAc,gBAAA,CAAiB,MAAA;EACxC,OAAA,CAAQ,KAAA,EAAO,MAAA,EAAQ,OAAA,aAAoB,OAAA,CAAQ,kBAAA,CAAmB,OAAA;EACtE,MAAA;AAAA;;;;;;;KASU,cAAA,wCACR,YAAA,CAAa,MAAA,EAAQ,OAAA,IACrB,cAAA,CAAe,MAAA,EAAQ,OAAA;;;;;AAXnB;AASR;;iBA4BgB,gBAAA,CAAiB,KAAA,YAAiB,KAAA,IAAS,cAAc;;;;;;;;;;;;;;iBAuBzD,gBAAA,kBACd,UAAA,EAAY,cAAA,CAAe,MAAA,EAAQ,OAAA,IAClC,YAAA,CAAa,MAAA,EAAQ,OAAA;;;;AAnDU;AA0BlC;;;;;iBA0EgB,mBAAA,CACd,KAAA,EAAO,aAAA,CAAc,cAAA,gBACpB,YAAA"}
@@ -48,8 +48,8 @@ function executableToTool(executable) {
48
48
  name: executable.name,
49
49
  description: executable.description ?? `Invoke "${executable.name}" as a tool.`,
50
50
  input: executable.inputSchema ?? passthroughSchema(),
51
- execute: async (input) => {
52
- const result = await executable.execute(input);
51
+ execute: async (input, ctx) => {
52
+ const result = await executable.execute(input, ctx?.signal ? { signal: ctx.signal } : void 0);
53
53
  if (result.error) throw result.error;
54
54
  return {
55
55
  data: result.data,
@@ -1 +1 @@
1
- {"version":3,"file":"executable-as-tool.mjs","names":[],"sources":["../../../../../../../@warlock.js/ai/src/tool/executable-as-tool.ts"],"sourcesContent":["import type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport type { BaseReport } from \"../contracts/result/base-report.type\";\nimport type { BaseResult } from \"../contracts/result/base-result.type\";\nimport type { Usage } from \"../contracts/result/usage.type\";\nimport { AgentExecutionError, type AIError } from \"../errors\";\nimport { compositeAsTool, type ToolContract } from \"./tool\";\n\n/**\n * Envelope every executable's `execute()` resolves to. Agent, workflow,\n * and supervisor results all satisfy this shape — `data` / `error`\n * carry the outcome while `usage` and `report` are always present —\n * which is exactly what {@link compositeAsTool} needs to nest the inner\n * run under the outer tool-call node.\n */\ntype ExecutableEnvelope<TOutput> = BaseResult & {\n data?: TOutput;\n error?: AIError;\n report: BaseReport;\n};\n\n/**\n * Structural view of an executable primitive (agent / workflow /\n * supervisor) when it is dropped straight into an agent's `tools: []`\n * array WITHOUT being wrapped via `.asTool()` first.\n *\n * Only the fields the auto-adapt path reads are declared:\n * - `name` — becomes the LLM tool name (required; anonymous executables\n * are rejected at author time, mirroring `.asTool()`).\n * - `description` — the \"when would the model pick this?\" line.\n * - `inputSchema` — opt-in Standard Schema typing the tool's arguments.\n * Surfaced on `WorkflowInstance` / `SupervisorContract` from the new\n * optional `inputSchema` config field. Absent for agents (which take\n * a plain string prompt).\n * - `execute` — the dispatch entry every `ExecutableContract` exposes.\n *\n * `invoke` is declared `never` so a `ToolContract` (which HAS `invoke`)\n * can never be mistaken for an executable by the {@link isExecutableTool}\n * guard.\n */\nexport type ExecutableTool<TInput = unknown, TOutput = unknown> = {\n readonly name: string;\n readonly description?: string;\n readonly inputSchema?: StandardSchemaV1<TInput>;\n execute(input: TInput, options?: unknown): Promise<ExecutableEnvelope<TOutput>>;\n invoke?: never;\n};\n\n/**\n * Entry accepted in an agent's `tools: []` array — either an already-\n * built `ToolContract` (the `.asTool()` / `ai.tool()` path) or a raw\n * executable primitive the framework auto-adapts on the caller's\n * behalf.\n */\nexport type AgentToolEntry<TInput = unknown, TOutput = unknown> =\n | ToolContract<TInput, TOutput>\n | ExecutableTool<TInput, TOutput>;\n\n/**\n * Identity passthrough schema used when an executable is registered as\n * a tool without declaring an `inputSchema`. The model's raw arguments\n * flow straight to `execute()` unchanged — the executable validates\n * internally (workflows via their steps, supervisors/agents via their\n * own input handling).\n */\nfunction passthroughSchema<TInput>(): StandardSchemaV1<TInput> {\n return {\n \"~standard\": {\n version: 1,\n vendor: \"warlock-ai\",\n validate: (value: unknown) => ({ value: value as TInput }),\n },\n };\n}\n\n/**\n * Type guard distinguishing a raw executable primitive from a built\n * `ToolContract`. An executable exposes `execute()` and no `invoke()`;\n * a `ToolContract` exposes `invoke()`. The `invoke` check is the\n * load-bearing discriminator — `.asTool()`-wrapped composites keep\n * their own `execute` too, so checking `execute` alone is insufficient.\n */\nexport function isExecutableTool(entry: unknown): entry is ExecutableTool {\n if (!entry || typeof entry !== \"object\") {\n return false;\n }\n\n const candidate = entry as { execute?: unknown; invoke?: unknown };\n\n return typeof candidate.execute === \"function\" && typeof candidate.invoke !== \"function\";\n}\n\n/**\n * Adapt a raw executable primitive (agent / workflow / supervisor) into\n * a `ToolContract` so an agent can dispatch it inside its tool-call\n * loop WITHOUT the caller writing `.asTool()`. Derives the LLM tool\n * manifest from the executable's own `name` + `description` +\n * (optional) `inputSchema`, then dispatches through the executable's\n * `execute()` — the inner report nests under the outer tool-call node\n * exactly like an explicit `.asTool()` wrapper.\n *\n * Throws `AgentExecutionError` at author time when the executable lacks\n * a usable `name` — the agent's tool surface needs a stable id, the\n * same constraint `.asTool()` enforces.\n */\nexport function executableToTool<TInput, TOutput>(\n executable: ExecutableTool<TInput, TOutput>,\n): ToolContract<TInput, TOutput> {\n if (!executable.name || typeof executable.name !== \"string\") {\n throw new AgentExecutionError(\n \"tools[]: an executable (agent/workflow/supervisor) used as a tool must have a `name`\",\n { context: { authoring: true } },\n );\n }\n\n return compositeAsTool<TInput, TOutput>({\n name: executable.name,\n description: executable.description ?? `Invoke \"${executable.name}\" as a tool.`,\n input: executable.inputSchema ?? passthroughSchema<TInput>(),\n execute: async (input) => {\n const result = await executable.execute(input);\n\n if (result.error) {\n // Surface the inner typed error so the surrounding\n // `compositeAsTool` wrapper produces a `ToolExecutionError`\n // with `cause` pointing back at the original subclass — the\n // agent's tool-call loop sees one uniform error class\n // regardless of which primitive failed.\n throw result.error;\n }\n\n return {\n data: result.data as TOutput,\n usage: result.usage as Usage,\n report: result.report,\n };\n },\n });\n}\n\n/**\n * Normalize an agent's `tools: []` array into a uniform\n * `ToolContract[]` for the runtime. Already-built `ToolContract`s\n * (`.asTool()` / `ai.tool()`) pass through untouched; raw executable\n * primitives are auto-adapted via {@link executableToTool}.\n *\n * Returns `undefined` when no tools were supplied so the agent's\n * existing `config.tools ?? []` fallbacks stay byte-identical.\n */\nexport function normalizeAgentTools(\n tools: ReadonlyArray<AgentToolEntry> | undefined,\n): ToolContract<unknown, unknown>[] | undefined {\n if (!tools) {\n return undefined;\n }\n\n return tools.map((entry) => {\n if (isExecutableTool(entry)) {\n return executableToTool(entry) as ToolContract<unknown, unknown>;\n }\n\n return entry as ToolContract<unknown, unknown>;\n });\n}\n"],"mappings":";;;;;;;;;;;;AAgEA,SAAS,oBAAsD;CAC7D,OAAO,EACL,aAAa;EACX,SAAS;EACT,QAAQ;EACR,WAAW,WAAoB,EAAS,MAAgB;CAC1D,EACF;AACF;;;;;;;;AASA,SAAgB,iBAAiB,OAAyC;CACxE,IAAI,CAAC,SAAS,OAAO,UAAU,UAC7B,OAAO;CAGT,MAAM,YAAY;CAElB,OAAO,OAAO,UAAU,YAAY,cAAc,OAAO,UAAU,WAAW;AAChF;;;;;;;;;;;;;;AAeA,SAAgB,iBACd,YAC+B;CAC/B,IAAI,CAAC,WAAW,QAAQ,OAAO,WAAW,SAAS,UACjD,MAAM,IAAI,oBACR,wFACA,EAAE,SAAS,EAAE,WAAW,KAAK,EAAE,CACjC;CAGF,OAAO,gBAAiC;EACtC,MAAM,WAAW;EACjB,aAAa,WAAW,eAAe,WAAW,WAAW,KAAK;EAClE,OAAO,WAAW,eAAe,kBAA0B;EAC3D,SAAS,OAAO,UAAU;GACxB,MAAM,SAAS,MAAM,WAAW,QAAQ,KAAK;GAE7C,IAAI,OAAO,OAMT,MAAM,OAAO;GAGf,OAAO;IACL,MAAM,OAAO;IACb,OAAO,OAAO;IACd,QAAQ,OAAO;GACjB;EACF;CACF,CAAC;AACH;;;;;;;;;;AAWA,SAAgB,oBACd,OAC8C;CAC9C,IAAI,CAAC,OACH;CAGF,OAAO,MAAM,KAAK,UAAU;EAC1B,IAAI,iBAAiB,KAAK,GACxB,OAAO,iBAAiB,KAAK;EAG/B,OAAO;CACT,CAAC;AACH"}
1
+ {"version":3,"file":"executable-as-tool.mjs","names":[],"sources":["../../../../../../../@warlock.js/ai/src/tool/executable-as-tool.ts"],"sourcesContent":["import type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport type { BaseReport } from \"../contracts/result/base-report.type\";\nimport type { BaseResult } from \"../contracts/result/base-result.type\";\nimport type { Usage } from \"../contracts/result/usage.type\";\nimport { AgentExecutionError, type AIError } from \"../errors\";\nimport { compositeAsTool, type ToolContract } from \"./tool\";\n\n/**\n * Envelope every executable's `execute()` resolves to. Agent, workflow,\n * and supervisor results all satisfy this shape — `data` / `error`\n * carry the outcome while `usage` and `report` are always present —\n * which is exactly what {@link compositeAsTool} needs to nest the inner\n * run under the outer tool-call node.\n */\ntype ExecutableEnvelope<TOutput> = BaseResult & {\n data?: TOutput;\n error?: AIError;\n report: BaseReport;\n};\n\n/**\n * Structural view of an executable primitive (agent / workflow /\n * supervisor) when it is dropped straight into an agent's `tools: []`\n * array WITHOUT being wrapped via `.asTool()` first.\n *\n * Only the fields the auto-adapt path reads are declared:\n * - `name` — becomes the LLM tool name (required; anonymous executables\n * are rejected at author time, mirroring `.asTool()`).\n * - `description` — the \"when would the model pick this?\" line.\n * - `inputSchema` — opt-in Standard Schema typing the tool's arguments.\n * Surfaced on `WorkflowInstance` / `SupervisorContract` from the new\n * optional `inputSchema` config field. Absent for agents (which take\n * a plain string prompt).\n * - `execute` — the dispatch entry every `ExecutableContract` exposes.\n *\n * `invoke` is declared `never` so a `ToolContract` (which HAS `invoke`)\n * can never be mistaken for an executable by the {@link isExecutableTool}\n * guard.\n */\nexport type ExecutableTool<TInput = unknown, TOutput = unknown> = {\n readonly name: string;\n readonly description?: string;\n readonly inputSchema?: StandardSchemaV1<TInput>;\n execute(input: TInput, options?: unknown): Promise<ExecutableEnvelope<TOutput>>;\n invoke?: never;\n};\n\n/**\n * Entry accepted in an agent's `tools: []` array — either an already-\n * built `ToolContract` (the `.asTool()` / `ai.tool()` path) or a raw\n * executable primitive the framework auto-adapts on the caller's\n * behalf.\n */\nexport type AgentToolEntry<TInput = unknown, TOutput = unknown> =\n | ToolContract<TInput, TOutput>\n | ExecutableTool<TInput, TOutput>;\n\n/**\n * Identity passthrough schema used when an executable is registered as\n * a tool without declaring an `inputSchema`. The model's raw arguments\n * flow straight to `execute()` unchanged — the executable validates\n * internally (workflows via their steps, supervisors/agents via their\n * own input handling).\n */\nfunction passthroughSchema<TInput>(): StandardSchemaV1<TInput> {\n return {\n \"~standard\": {\n version: 1,\n vendor: \"warlock-ai\",\n validate: (value: unknown) => ({ value: value as TInput }),\n },\n };\n}\n\n/**\n * Type guard distinguishing a raw executable primitive from a built\n * `ToolContract`. An executable exposes `execute()` and no `invoke()`;\n * a `ToolContract` exposes `invoke()`. The `invoke` check is the\n * load-bearing discriminator — `.asTool()`-wrapped composites keep\n * their own `execute` too, so checking `execute` alone is insufficient.\n */\nexport function isExecutableTool(entry: unknown): entry is ExecutableTool {\n if (!entry || typeof entry !== \"object\") {\n return false;\n }\n\n const candidate = entry as { execute?: unknown; invoke?: unknown };\n\n return typeof candidate.execute === \"function\" && typeof candidate.invoke !== \"function\";\n}\n\n/**\n * Adapt a raw executable primitive (agent / workflow / supervisor) into\n * a `ToolContract` so an agent can dispatch it inside its tool-call\n * loop WITHOUT the caller writing `.asTool()`. Derives the LLM tool\n * manifest from the executable's own `name` + `description` +\n * (optional) `inputSchema`, then dispatches through the executable's\n * `execute()` — the inner report nests under the outer tool-call node\n * exactly like an explicit `.asTool()` wrapper.\n *\n * Throws `AgentExecutionError` at author time when the executable lacks\n * a usable `name` — the agent's tool surface needs a stable id, the\n * same constraint `.asTool()` enforces.\n */\nexport function executableToTool<TInput, TOutput>(\n executable: ExecutableTool<TInput, TOutput>,\n): ToolContract<TInput, TOutput> {\n if (!executable.name || typeof executable.name !== \"string\") {\n throw new AgentExecutionError(\n \"tools[]: an executable (agent/workflow/supervisor) used as a tool must have a `name`\",\n { context: { authoring: true } },\n );\n }\n\n return compositeAsTool<TInput, TOutput>({\n name: executable.name,\n description: executable.description ?? `Invoke \"${executable.name}\" as a tool.`,\n input: executable.inputSchema ?? passthroughSchema<TInput>(),\n execute: async (input, ctx) => {\n // Relay the outer run's cancellation signal so a cancelled parent\n // aborts this nested agent/workflow/supervisor (C2). Omit the\n // options object entirely when there's no signal so primitives that\n // treat any second arg as meaningful stay byte-identical.\n const result = await executable.execute(\n input,\n ctx?.signal ? { signal: ctx.signal } : undefined,\n );\n\n if (result.error) {\n // Surface the inner typed error so the surrounding\n // `compositeAsTool` wrapper produces a `ToolExecutionError`\n // with `cause` pointing back at the original subclass — the\n // agent's tool-call loop sees one uniform error class\n // regardless of which primitive failed.\n throw result.error;\n }\n\n return {\n data: result.data as TOutput,\n usage: result.usage as Usage,\n report: result.report,\n };\n },\n });\n}\n\n/**\n * Normalize an agent's `tools: []` array into a uniform\n * `ToolContract[]` for the runtime. Already-built `ToolContract`s\n * (`.asTool()` / `ai.tool()`) pass through untouched; raw executable\n * primitives are auto-adapted via {@link executableToTool}.\n *\n * Returns `undefined` when no tools were supplied so the agent's\n * existing `config.tools ?? []` fallbacks stay byte-identical.\n */\nexport function normalizeAgentTools(\n tools: ReadonlyArray<AgentToolEntry> | undefined,\n): ToolContract<unknown, unknown>[] | undefined {\n if (!tools) {\n return undefined;\n }\n\n return tools.map((entry) => {\n if (isExecutableTool(entry)) {\n return executableToTool(entry) as ToolContract<unknown, unknown>;\n }\n\n return entry as ToolContract<unknown, unknown>;\n });\n}\n"],"mappings":";;;;;;;;;;;;AAgEA,SAAS,oBAAsD;CAC7D,OAAO,EACL,aAAa;EACX,SAAS;EACT,QAAQ;EACR,WAAW,WAAoB,EAAS,MAAgB;CAC1D,EACF;AACF;;;;;;;;AASA,SAAgB,iBAAiB,OAAyC;CACxE,IAAI,CAAC,SAAS,OAAO,UAAU,UAC7B,OAAO;CAGT,MAAM,YAAY;CAElB,OAAO,OAAO,UAAU,YAAY,cAAc,OAAO,UAAU,WAAW;AAChF;;;;;;;;;;;;;;AAeA,SAAgB,iBACd,YAC+B;CAC/B,IAAI,CAAC,WAAW,QAAQ,OAAO,WAAW,SAAS,UACjD,MAAM,IAAI,oBACR,wFACA,EAAE,SAAS,EAAE,WAAW,KAAK,EAAE,CACjC;CAGF,OAAO,gBAAiC;EACtC,MAAM,WAAW;EACjB,aAAa,WAAW,eAAe,WAAW,WAAW,KAAK;EAClE,OAAO,WAAW,eAAe,kBAA0B;EAC3D,SAAS,OAAO,OAAO,QAAQ;GAK7B,MAAM,SAAS,MAAM,WAAW,QAC9B,OACA,KAAK,SAAS,EAAE,QAAQ,IAAI,OAAO,IAAI,MACzC;GAEA,IAAI,OAAO,OAMT,MAAM,OAAO;GAGf,OAAO;IACL,MAAM,OAAO;IACb,OAAO,OAAO;IACd,QAAQ,OAAO;GACjB;EACF;CACF,CAAC;AACH;;;;;;;;;;AAWA,SAAgB,oBACd,OAC8C;CAC9C,IAAI,CAAC,OACH;CAGF,OAAO,MAAM,KAAK,UAAU;EAC1B,IAAI,iBAAiB,KAAK,GACxB,OAAO,iBAAiB,KAAK;EAG/B,OAAO;CACT,CAAC;AACH"}
@@ -1 +1 @@
1
- {"version":3,"file":"tool.d.mts","names":[],"sources":["../../../../../../../@warlock.js/ai/src/tool/tool.ts"],"mappings":";;;;;;;;;;AAwCA;;;;;;;;;;;;;;;;;KAAY,gBAAA;EAQQ,iFANlB,IAAA,GAAO,OAAA,EAgBQ;EAdf,KAAA,GAAQ,OAAA,EAcmB;EAZ3B,KAAA,EAAO,KAAA,EAcP;EAZA,MAAA,EAAQ,UAAA;AAAA;;;;;;;;UAUO,YAAA,8CAA0D,UAAA,CACzE,MAAA,EACA,OAAA;EADA;;;;;;;;;;AAoB8E;AAuJhF;;;;;;EAvJE,MAAA,CAAO,QAAA,WAAmB,GAAA,GAAM,WAAA,GAAc,OAAA,CAAQ,gBAAA,CAAiB,OAAA;AAAA;AAAA,iBAuJzD,IAAA,kBACd,QAAA,EAAU,UAAA,CAAW,MAAA,EAAQ,OAAA,IAC5B,YAAA,CAAa,MAAA,EAAQ,OAAA"}
1
+ {"version":3,"file":"tool.d.mts","names":[],"sources":["../../../../../../../@warlock.js/ai/src/tool/tool.ts"],"mappings":";;;;;;;;;;AAwCA;;;;;;;;;;;;;;;;;KAAY,gBAAA;EAQQ,iFANlB,IAAA,GAAO,OAAA,EAgBQ;EAdf,KAAA,GAAQ,OAAA,EAcmB;EAZ3B,KAAA,EAAO,KAAA,EAcP;EAZA,MAAA,EAAQ,UAAA;AAAA;;;;;;;;UAUO,YAAA,8CAA0D,UAAA,CACzE,MAAA,EACA,OAAA;EADA;;;;;;;;;;AAoB8E;AA6JhF;;;;;;EA7JE,MAAA,CAAO,QAAA,WAAmB,GAAA,GAAM,WAAA,GAAc,OAAA,CAAQ,gBAAA,CAAiB,OAAA;AAAA;AAAA,iBA6JzD,IAAA,kBACd,QAAA,EAAU,UAAA,CAAW,MAAA,EAAQ,OAAA,IAC5B,YAAA,CAAa,MAAA,EAAQ,OAAA"}
package/esm/tool/tool.mjs CHANGED
@@ -66,7 +66,7 @@ function compositeAsTool(contract) {
66
66
  meta: contract.meta,
67
67
  input: contract.input,
68
68
  execute: publicExecute,
69
- async invoke(rawInput, _ctx) {
69
+ async invoke(rawInput, ctx) {
70
70
  const startedAtDate = /* @__PURE__ */ new Date();
71
71
  const start = performance.now();
72
72
  const runId = generateRunId("tool");
@@ -106,7 +106,7 @@ function compositeAsTool(contract) {
106
106
  context: { toolName: contract.name }
107
107
  }));
108
108
  try {
109
- const composite = await contract.execute(validationResult.value);
109
+ const composite = await contract.execute(validationResult.value, ctx);
110
110
  return {
111
111
  data: composite.data,
112
112
  error: composite.error,
@@ -1 +1 @@
1
- {"version":3,"file":"tool.mjs","names":[],"sources":["../../../../../../../@warlock.js/ai/src/tool/tool.ts"],"sourcesContent":["import type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport type { BaseReport } from \"../contracts/result/base-report.type\";\nimport type { Usage } from \"../contracts/result/usage.type\";\nimport type { ToolConfig, ToolContext } from \"../contracts/tool.contract\";\nimport { AIError, SchemaValidationError, ToolExecutionError } from \"../errors\";\nimport { generateRunId } from \"../utils/generate-run-id\";\n\n/**\n * Degraded `ToolContext` supplied when no caller threads one through\n * (`tool.invoke(input)` standalone, batch scripts, tests). Per\n * decisions §35 — mutations on the empty bag are harmless no-ops;\n * production paths under a supervisor receive a real ctx with the\n * iteration's shared bag.\n */\nfunction defaultToolContext(): ToolContext {\n return { artifacts: {} };\n}\n\nconst EMPTY_USAGE: Usage = Object.freeze({ input: 0, output: 0, total: 0 });\n\n/**\n * Result returned by `ToolContract.invoke()`.\n *\n * **Canonical destructure:** `const { data, usage, report, error }` —\n * matches every other executable (`AgentResult`, `WorkflowResult`,\n * `SupervisorResult`) so parent agents can treat every tool dispatch\n * uniformly.\n *\n * **Shape.** `data` / `error` carry the outcome; `usage` and `report`\n * are always present. For leaf tools, `usage` is zero and `report`\n * is a framework-synthesized {@link BaseReport} (`type: \"tool\"`,\n * `children: []`, real timing) so parents never have to nil-check.\n * For composites wrapped via `asTool()`, `usage` and `report` mirror\n * the inner primitive's — the nested tree lives in `report.children`.\n *\n * @example\n * const result = await myTool.invoke({ city: \"Cairo\" });\n * if (result.error) console.error(result.error.message);\n * else console.log(result.data, result.report.duration);\n */\nexport type ToolInvokeResult<TOutput> = {\n /** Successfully-returned output. Undefined if execution or validation failed. */\n data?: TOutput;\n /** Typed AI error produced by validation or execute(), if any. */\n error?: AIError;\n /** Rolled-up usage (zero for leaf tools, populated for composites). */\n usage: Usage;\n /** Recursive execution report — `report.children` carries nested executables. */\n report: BaseReport;\n};\n\n/**\n * A `ToolConfig` augmented with a safe `invoke()` entry point for the agent runtime.\n *\n * @example\n * const wrapped: ToolContract<{ city: string }, { temp: number }> = tool(contract);\n * const result = await wrapped.invoke({ city: \"Cairo\" });\n */\nexport interface ToolContract<TInput = unknown, TOutput = unknown> extends ToolConfig<\n TInput,\n TOutput\n> {\n /**\n * Agent-runtime entry point. Validates raw input against the tool's schema,\n * calls execute(), catches errors, and reports duration.\n * Never throws — errors surface in the returned `error` field as\n * typed `AIError` subclasses.\n *\n * The optional second argument is a `ToolContext` (Phase 5 /\n * decisions §35) — when supplied, threaded into `execute(input, ctx)`\n * so tools can write system-only side data into `ctx.artifacts`.\n * Standalone callers may omit it; the framework supplies a\n * degraded `{ artifacts: {} }` so single-arg legacy handlers keep\n * working unchanged.\n *\n * @example\n * const result = await myTool.invoke(rawLLMArgs);\n * if (result.error) handleError(result.error);\n */\n invoke(rawInput: unknown, ctx?: ToolContext): Promise<ToolInvokeResult<TOutput>>;\n}\n\n/**\n * Wraps a raw `ToolConfig` and adds a safe `invoke()` method for the agent runtime.\n * The returned object preserves all original contract fields unchanged.\n *\n * Error categorization:\n * - Input schema rejects model args → `SchemaValidationError` (issues preserved).\n * - Schema's `validate()` itself throws → `SchemaValidationError` wrapping the cause.\n * - `execute()` throws → `ToolExecutionError` wrapping the cause.\n *\n * @example\n * const weatherTool = tool({\n * name: \"getWeather\",\n * description: \"Fetch current weather for a city\",\n * input: z.object({ city: z.string() }),\n * execute: async ({ city }) => ({ temp: 72 }),\n * });\n *\n * const result = await weatherTool.invoke({ city: \"Cairo\" });\n */\n/**\n * Internal factory for `asTool()` wrappers on composite primitives\n * (agent / workflow / supervisor). Unlike the public `tool()` factory\n * (which synthesizes a leaf `BaseReport` every time), this variant\n * lets the composite's own `ExecuteResult` flow through: the inner\n * primitive's `report` becomes the sole child of the outer tool-call\n * node, and the inner `usage` is surfaced so parents can roll it up.\n *\n * The caller supplies `execute()` returning `{ data, usage, report }`\n * from the composite's own `execute()` method. Validation failures\n * and thrown errors still produce a synthesized failed leaf report —\n * the inner-report propagation is strictly a success-path concern.\n *\n * Not exported from the package barrel — used by `agent.asTool()`,\n * `workflow.asTool()`, `supervisor.asTool()` only.\n */\nexport function compositeAsTool<TInput, TOutput>(contract: {\n name: string;\n description?: string;\n version?: string;\n meta?: ToolConfig[\"meta\"];\n input: StandardSchemaV1<TInput>;\n /** Runs the underlying composite and returns its full envelope. */\n execute: (input: TInput) => Promise<{\n data?: TOutput;\n error?: AIError;\n usage: Usage;\n report: BaseReport;\n }>;\n}): ToolContract<TInput, TOutput> {\n // The underlying `ToolConfig<TInput, TOutput>.execute` is typed as\n // `(input) => Promise<TOutput>`, but composite wrappers return an\n // envelope object instead. Surface a contract-shaped view that\n // extracts `.data` on demand for any code that still treats this\n // like a plain tool.\n const publicExecute = async (input: TInput): Promise<TOutput> => {\n const envelope = await contract.execute(input);\n if (envelope.error) throw envelope.error;\n return envelope.data as TOutput;\n };\n\n return {\n name: contract.name,\n description: contract.description ?? `Composite tool \"${contract.name}\".`,\n meta: contract.meta,\n input: contract.input,\n execute: publicExecute,\n\n async invoke(rawInput: unknown, _ctx?: ToolContext): Promise<ToolInvokeResult<TOutput>> {\n // Composite tools (asTool-wrapped agent/workflow/supervisor) do\n // NOT relay the ctx into their inner execution — composites\n // have their own state/scope; an inner supervisor gets a fresh\n // artifacts bag. The parameter is accepted for signature parity\n // with `tool()` so callers can use both interchangeably.\n const startedAtDate = new Date();\n const start = performance.now();\n const runId = generateRunId(\"tool\");\n\n const failLeaf = (error: AIError): ToolInvokeResult<TOutput> => {\n const endedAt = new Date().toISOString();\n const duration = performance.now() - start;\n return {\n error,\n usage: EMPTY_USAGE,\n report: {\n runId,\n rootRunId: runId,\n name: contract.name,\n version: contract.version,\n type: \"tool\",\n status: \"failed\",\n startedAt: startedAtDate.toISOString(),\n endedAt,\n duration,\n usage: EMPTY_USAGE,\n children: [],\n },\n };\n };\n\n let validationResult: StandardSchemaV1.Result<TInput>;\n try {\n const schema = contract.input as StandardSchemaV1<TInput>;\n validationResult = await schema[\"~standard\"].validate(rawInput);\n } catch (thrown) {\n const message = thrown instanceof Error ? thrown.message : String(thrown);\n return failLeaf(\n new SchemaValidationError(\n `Schema validation threw for tool \"${contract.name}\": ${message}`,\n { cause: thrown, context: { toolName: contract.name } },\n ),\n );\n }\n\n if (validationResult.issues) {\n const summary = validationResult.issues.map((issue) => issue.message).join(\"; \");\n return failLeaf(\n new SchemaValidationError(`Validation failed: ${summary}`, {\n issues: validationResult.issues,\n context: { toolName: contract.name },\n }),\n );\n }\n\n try {\n const composite = await contract.execute(validationResult.value);\n // Surface the inner primitive's full envelope. The outer\n // ToolInvokeResult carries the composite's usage and report\n // verbatim; the agent runtime nests the report as a child of\n // the tool-dispatch node it records.\n return {\n data: composite.data,\n error: composite.error,\n usage: composite.usage,\n report: composite.report,\n };\n } catch (thrown) {\n const message = thrown instanceof Error ? thrown.message : String(thrown);\n return failLeaf(\n new ToolExecutionError(message, {\n cause: thrown,\n toolName: contract.name,\n }),\n );\n }\n },\n };\n}\n\nexport function tool<TInput, TOutput>(\n contract: ToolConfig<TInput, TOutput>,\n): ToolContract<TInput, TOutput> {\n return {\n ...contract,\n\n async invoke(rawInput: unknown, ctx?: ToolContext): Promise<ToolInvokeResult<TOutput>> {\n const startedAtDate = new Date();\n const start = performance.now();\n const runId = generateRunId(\"tool\");\n const handlerCtx = ctx ?? defaultToolContext();\n\n const finish = (partial: { data?: TOutput; error?: AIError }): ToolInvokeResult<TOutput> => {\n const endedAt = new Date().toISOString();\n const duration = performance.now() - start;\n const status: BaseReport[\"status\"] = partial.error ? \"failed\" : \"completed\";\n const report: BaseReport = {\n runId,\n rootRunId: runId,\n name: contract.name,\n version: contract.version,\n type: \"tool\",\n status,\n startedAt: startedAtDate.toISOString(),\n endedAt,\n duration,\n usage: EMPTY_USAGE,\n children: [],\n };\n\n return {\n ...partial,\n usage: EMPTY_USAGE,\n report,\n };\n };\n\n let validationResult: StandardSchemaV1.Result<TInput>;\n if (contract.input) {\n try {\n validationResult = await contract.input[\"~standard\"].validate(rawInput);\n } catch (thrown) {\n const message = thrown instanceof Error ? thrown.message : String(thrown);\n\n return finish({\n error: new SchemaValidationError(\n `Schema validation threw for tool \"${contract.name}\": ${message}`,\n { cause: thrown, context: { toolName: contract.name } },\n ),\n });\n }\n } else {\n // `input` is optional on ToolConfig — this is a no-argument tool\n // (e.g. view_cart, checkout). With no schema there is nothing to\n // validate, so pass the raw model args straight to execute()\n // instead of dereferencing a missing schema's `~standard`.\n validationResult = { value: rawInput as TInput };\n }\n\n if (validationResult.issues) {\n const summary = validationResult.issues.map((issue) => issue.message).join(\"; \");\n\n return finish({\n error: new SchemaValidationError(`Validation failed: ${summary}`, {\n issues: validationResult.issues,\n context: { toolName: contract.name },\n }),\n });\n }\n\n try {\n const output = await contract.execute(validationResult.value, handlerCtx);\n return finish({ data: output });\n } catch (thrown) {\n const message = thrown instanceof Error ? thrown.message : String(thrown);\n\n return finish({\n error: new ToolExecutionError(message, {\n cause: thrown,\n toolName: contract.name,\n }),\n });\n }\n },\n };\n}\n"],"mappings":"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"}
1
+ {"version":3,"file":"tool.mjs","names":[],"sources":["../../../../../../../@warlock.js/ai/src/tool/tool.ts"],"sourcesContent":["import type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport type { BaseReport } from \"../contracts/result/base-report.type\";\nimport type { Usage } from \"../contracts/result/usage.type\";\nimport type { ToolConfig, ToolContext } from \"../contracts/tool.contract\";\nimport { AIError, SchemaValidationError, ToolExecutionError } from \"../errors\";\nimport { generateRunId } from \"../utils/generate-run-id\";\n\n/**\n * Degraded `ToolContext` supplied when no caller threads one through\n * (`tool.invoke(input)` standalone, batch scripts, tests). Per\n * decisions §35 — mutations on the empty bag are harmless no-ops;\n * production paths under a supervisor receive a real ctx with the\n * iteration's shared bag.\n */\nfunction defaultToolContext(): ToolContext {\n return { artifacts: {} };\n}\n\nconst EMPTY_USAGE: Usage = Object.freeze({ input: 0, output: 0, total: 0 });\n\n/**\n * Result returned by `ToolContract.invoke()`.\n *\n * **Canonical destructure:** `const { data, usage, report, error }` —\n * matches every other executable (`AgentResult`, `WorkflowResult`,\n * `SupervisorResult`) so parent agents can treat every tool dispatch\n * uniformly.\n *\n * **Shape.** `data` / `error` carry the outcome; `usage` and `report`\n * are always present. For leaf tools, `usage` is zero and `report`\n * is a framework-synthesized {@link BaseReport} (`type: \"tool\"`,\n * `children: []`, real timing) so parents never have to nil-check.\n * For composites wrapped via `asTool()`, `usage` and `report` mirror\n * the inner primitive's — the nested tree lives in `report.children`.\n *\n * @example\n * const result = await myTool.invoke({ city: \"Cairo\" });\n * if (result.error) console.error(result.error.message);\n * else console.log(result.data, result.report.duration);\n */\nexport type ToolInvokeResult<TOutput> = {\n /** Successfully-returned output. Undefined if execution or validation failed. */\n data?: TOutput;\n /** Typed AI error produced by validation or execute(), if any. */\n error?: AIError;\n /** Rolled-up usage (zero for leaf tools, populated for composites). */\n usage: Usage;\n /** Recursive execution report — `report.children` carries nested executables. */\n report: BaseReport;\n};\n\n/**\n * A `ToolConfig` augmented with a safe `invoke()` entry point for the agent runtime.\n *\n * @example\n * const wrapped: ToolContract<{ city: string }, { temp: number }> = tool(contract);\n * const result = await wrapped.invoke({ city: \"Cairo\" });\n */\nexport interface ToolContract<TInput = unknown, TOutput = unknown> extends ToolConfig<\n TInput,\n TOutput\n> {\n /**\n * Agent-runtime entry point. Validates raw input against the tool's schema,\n * calls execute(), catches errors, and reports duration.\n * Never throws — errors surface in the returned `error` field as\n * typed `AIError` subclasses.\n *\n * The optional second argument is a `ToolContext` (Phase 5 /\n * decisions §35) — when supplied, threaded into `execute(input, ctx)`\n * so tools can write system-only side data into `ctx.artifacts`.\n * Standalone callers may omit it; the framework supplies a\n * degraded `{ artifacts: {} }` so single-arg legacy handlers keep\n * working unchanged.\n *\n * @example\n * const result = await myTool.invoke(rawLLMArgs);\n * if (result.error) handleError(result.error);\n */\n invoke(rawInput: unknown, ctx?: ToolContext): Promise<ToolInvokeResult<TOutput>>;\n}\n\n/**\n * Wraps a raw `ToolConfig` and adds a safe `invoke()` method for the agent runtime.\n * The returned object preserves all original contract fields unchanged.\n *\n * Error categorization:\n * - Input schema rejects model args → `SchemaValidationError` (issues preserved).\n * - Schema's `validate()` itself throws → `SchemaValidationError` wrapping the cause.\n * - `execute()` throws → `ToolExecutionError` wrapping the cause.\n *\n * @example\n * const weatherTool = tool({\n * name: \"getWeather\",\n * description: \"Fetch current weather for a city\",\n * input: z.object({ city: z.string() }),\n * execute: async ({ city }) => ({ temp: 72 }),\n * });\n *\n * const result = await weatherTool.invoke({ city: \"Cairo\" });\n */\n/**\n * Internal factory for `asTool()` wrappers on composite primitives\n * (agent / workflow / supervisor). Unlike the public `tool()` factory\n * (which synthesizes a leaf `BaseReport` every time), this variant\n * lets the composite's own `ExecuteResult` flow through: the inner\n * primitive's `report` becomes the sole child of the outer tool-call\n * node, and the inner `usage` is surfaced so parents can roll it up.\n *\n * The caller supplies `execute()` returning `{ data, usage, report }`\n * from the composite's own `execute()` method. Validation failures\n * and thrown errors still produce a synthesized failed leaf report —\n * the inner-report propagation is strictly a success-path concern.\n *\n * Not exported from the package barrel — used by `agent.asTool()`,\n * `workflow.asTool()`, `supervisor.asTool()` only.\n */\nexport function compositeAsTool<TInput, TOutput>(contract: {\n name: string;\n description?: string;\n version?: string;\n meta?: ToolConfig[\"meta\"];\n input: StandardSchemaV1<TInput>;\n /**\n * Runs the underlying composite and returns its full envelope. The\n * optional `ctx` relays the outer run's cancellation `signal` so a\n * cancelled parent aborts the nested primitive instead of letting it\n * outlive the cancellation (C2).\n */\n execute: (input: TInput, ctx?: ToolContext) => Promise<{\n data?: TOutput;\n error?: AIError;\n usage: Usage;\n report: BaseReport;\n }>;\n}): ToolContract<TInput, TOutput> {\n // The underlying `ToolConfig<TInput, TOutput>.execute` is typed as\n // `(input) => Promise<TOutput>`, but composite wrappers return an\n // envelope object instead. Surface a contract-shaped view that\n // extracts `.data` on demand for any code that still treats this\n // like a plain tool.\n const publicExecute = async (input: TInput): Promise<TOutput> => {\n const envelope = await contract.execute(input);\n if (envelope.error) throw envelope.error;\n return envelope.data as TOutput;\n };\n\n return {\n name: contract.name,\n description: contract.description ?? `Composite tool \"${contract.name}\".`,\n meta: contract.meta,\n input: contract.input,\n execute: publicExecute,\n\n async invoke(rawInput: unknown, ctx?: ToolContext): Promise<ToolInvokeResult<TOutput>> {\n // Composite tools (asTool-wrapped agent/workflow/supervisor) run in\n // their own state/scope — the ctx's `artifacts` bag is NOT shared\n // into the inner primitive (an inner supervisor gets a fresh bag).\n // The cancellation `signal`, however, IS relayed (below, into\n // `contract.execute`) so a cancelled outer run aborts the nested\n // primitive instead of letting it outlive the cancellation (C2).\n const startedAtDate = new Date();\n const start = performance.now();\n const runId = generateRunId(\"tool\");\n\n const failLeaf = (error: AIError): ToolInvokeResult<TOutput> => {\n const endedAt = new Date().toISOString();\n const duration = performance.now() - start;\n return {\n error,\n usage: EMPTY_USAGE,\n report: {\n runId,\n rootRunId: runId,\n name: contract.name,\n version: contract.version,\n type: \"tool\",\n status: \"failed\",\n startedAt: startedAtDate.toISOString(),\n endedAt,\n duration,\n usage: EMPTY_USAGE,\n children: [],\n },\n };\n };\n\n let validationResult: StandardSchemaV1.Result<TInput>;\n try {\n const schema = contract.input as StandardSchemaV1<TInput>;\n validationResult = await schema[\"~standard\"].validate(rawInput);\n } catch (thrown) {\n const message = thrown instanceof Error ? thrown.message : String(thrown);\n return failLeaf(\n new SchemaValidationError(\n `Schema validation threw for tool \"${contract.name}\": ${message}`,\n { cause: thrown, context: { toolName: contract.name } },\n ),\n );\n }\n\n if (validationResult.issues) {\n const summary = validationResult.issues.map((issue) => issue.message).join(\"; \");\n return failLeaf(\n new SchemaValidationError(`Validation failed: ${summary}`, {\n issues: validationResult.issues,\n context: { toolName: contract.name },\n }),\n );\n }\n\n try {\n const composite = await contract.execute(validationResult.value, ctx);\n // Surface the inner primitive's full envelope. The outer\n // ToolInvokeResult carries the composite's usage and report\n // verbatim; the agent runtime nests the report as a child of\n // the tool-dispatch node it records.\n return {\n data: composite.data,\n error: composite.error,\n usage: composite.usage,\n report: composite.report,\n };\n } catch (thrown) {\n const message = thrown instanceof Error ? thrown.message : String(thrown);\n return failLeaf(\n new ToolExecutionError(message, {\n cause: thrown,\n toolName: contract.name,\n }),\n );\n }\n },\n };\n}\n\nexport function tool<TInput, TOutput>(\n contract: ToolConfig<TInput, TOutput>,\n): ToolContract<TInput, TOutput> {\n return {\n ...contract,\n\n async invoke(rawInput: unknown, ctx?: ToolContext): Promise<ToolInvokeResult<TOutput>> {\n const startedAtDate = new Date();\n const start = performance.now();\n const runId = generateRunId(\"tool\");\n const handlerCtx = ctx ?? defaultToolContext();\n\n const finish = (partial: { data?: TOutput; error?: AIError }): ToolInvokeResult<TOutput> => {\n const endedAt = new Date().toISOString();\n const duration = performance.now() - start;\n const status: BaseReport[\"status\"] = partial.error ? \"failed\" : \"completed\";\n const report: BaseReport = {\n runId,\n rootRunId: runId,\n name: contract.name,\n version: contract.version,\n type: \"tool\",\n status,\n startedAt: startedAtDate.toISOString(),\n endedAt,\n duration,\n usage: EMPTY_USAGE,\n children: [],\n };\n\n return {\n ...partial,\n usage: EMPTY_USAGE,\n report,\n };\n };\n\n let validationResult: StandardSchemaV1.Result<TInput>;\n if (contract.input) {\n try {\n validationResult = await contract.input[\"~standard\"].validate(rawInput);\n } catch (thrown) {\n const message = thrown instanceof Error ? thrown.message : String(thrown);\n\n return finish({\n error: new SchemaValidationError(\n `Schema validation threw for tool \"${contract.name}\": ${message}`,\n { cause: thrown, context: { toolName: contract.name } },\n ),\n });\n }\n } else {\n // `input` is optional on ToolConfig — this is a no-argument tool\n // (e.g. view_cart, checkout). With no schema there is nothing to\n // validate, so pass the raw model args straight to execute()\n // instead of dereferencing a missing schema's `~standard`.\n validationResult = { value: rawInput as TInput };\n }\n\n if (validationResult.issues) {\n const summary = validationResult.issues.map((issue) => issue.message).join(\"; \");\n\n return finish({\n error: new SchemaValidationError(`Validation failed: ${summary}`, {\n issues: validationResult.issues,\n context: { toolName: contract.name },\n }),\n });\n }\n\n try {\n const output = await contract.execute(validationResult.value, handlerCtx);\n return finish({ data: output });\n } catch (thrown) {\n const message = thrown instanceof Error ? thrown.message : String(thrown);\n\n return finish({\n error: new ToolExecutionError(message, {\n cause: thrown,\n toolName: contract.name,\n }),\n });\n }\n },\n };\n}\n"],"mappings":"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"}
@@ -53,6 +53,22 @@ declare function computeCost(usage: Usage, pricing: ModelPricing | undefined): M
53
53
  * pricing" from "genuinely zero").
54
54
  */
55
55
  declare function accumulateCost(parent: ModelPricing | undefined, child: ModelPricing | undefined): ModelPricing | undefined;
56
+ /**
57
+ * Accumulate a child {@link Usage} into a running parent total, mutating
58
+ * `target` in place. Scalar token channels (`input` / `output` / `total`)
59
+ * sum directly; the optional sub-channels (`cachedTokens`,
60
+ * `reasoningTokens`, `cacheWriteTokens`) accumulate only when some
61
+ * contributor reported them (preserving the "never reported anywhere"
62
+ * signal); and the cost breakdown merges via {@link accumulateCost} so a
63
+ * single unpriced child can never erase a priced sibling's cost.
64
+ *
65
+ * This is the ONE canonical usage rollup — every aggregator (agent,
66
+ * workflow, supervisor, team, planner, batch) routes through it so cost +
67
+ * cache/reasoning telemetry propagates identically to the top-level
68
+ * `result.usage`. Re-implementing a bare `input/output/total` sum at a
69
+ * call site silently drops those optional channels.
70
+ */
71
+ declare function mergeUsage(target: Usage, child: Usage): void;
56
72
  //#endregion
57
- export { accumulateCost, computeCost };
73
+ export { accumulateCost, computeCost, mergeUsage };
58
74
  //# sourceMappingURL=compute-cost.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"compute-cost.d.mts","names":[],"sources":["../../../../../../../@warlock.js/ai/src/utils/compute-cost.ts"],"mappings":";;;;;;AAuCA;;;;;;;;;;;;;;AAA0F;AAkC1F;;;;;;;;;;;;;;AAGe;;;;;iBArCC,WAAA,CAAY,KAAA,EAAO,KAAA,EAAO,OAAA,EAAS,YAAA,eAA2B,YAAA;;;;;;;;;;;;;;iBAkC9D,cAAA,CACd,MAAA,EAAQ,YAAA,cACR,KAAA,EAAO,YAAA,eACN,YAAA"}
1
+ {"version":3,"file":"compute-cost.d.mts","names":[],"sources":["../../../../../../../@warlock.js/ai/src/utils/compute-cost.ts"],"mappings":";;;;;;AAuCA;;;;;;;;;;;;;;AAA0F;AAkC1F;;;;;;;;;;;;;;AAGe;AAwDf;;;;iBA7FgB,WAAA,CAAY,KAAA,EAAO,KAAA,EAAO,OAAA,EAAS,YAAA,eAA2B,YAAA;;;;;AA6FxB;;;;;;;;;iBA3DtC,cAAA,CACd,MAAA,EAAQ,YAAA,cACR,KAAA,EAAO,YAAA,eACN,YAAA;;;;;;;;;;;;;;;;iBAwDa,UAAA,CAAW,MAAA,EAAQ,KAAA,EAAO,KAAA,EAAO,KAAK"}
@@ -81,7 +81,32 @@ function sumOptional(parent, child) {
81
81
  if (parent === void 0 && child === void 0) return;
82
82
  return (parent ?? 0) + (child ?? 0);
83
83
  }
84
+ /**
85
+ * Accumulate a child {@link Usage} into a running parent total, mutating
86
+ * `target` in place. Scalar token channels (`input` / `output` / `total`)
87
+ * sum directly; the optional sub-channels (`cachedTokens`,
88
+ * `reasoningTokens`, `cacheWriteTokens`) accumulate only when some
89
+ * contributor reported them (preserving the "never reported anywhere"
90
+ * signal); and the cost breakdown merges via {@link accumulateCost} so a
91
+ * single unpriced child can never erase a priced sibling's cost.
92
+ *
93
+ * This is the ONE canonical usage rollup — every aggregator (agent,
94
+ * workflow, supervisor, team, planner, batch) routes through it so cost +
95
+ * cache/reasoning telemetry propagates identically to the top-level
96
+ * `result.usage`. Re-implementing a bare `input/output/total` sum at a
97
+ * call site silently drops those optional channels.
98
+ */
99
+ function mergeUsage(target, child) {
100
+ target.input += child.input;
101
+ target.output += child.output;
102
+ target.total += child.total;
103
+ if (child.cachedTokens !== void 0) target.cachedTokens = (target.cachedTokens ?? 0) + child.cachedTokens;
104
+ if (child.reasoningTokens !== void 0) target.reasoningTokens = (target.reasoningTokens ?? 0) + child.reasoningTokens;
105
+ if (child.cacheWriteTokens !== void 0) target.cacheWriteTokens = (target.cacheWriteTokens ?? 0) + child.cacheWriteTokens;
106
+ const mergedCost = accumulateCost(target.cost, child.cost);
107
+ if (mergedCost !== void 0) target.cost = mergedCost;
108
+ }
84
109
 
85
110
  //#endregion
86
- export { accumulateCost, computeCost };
111
+ export { accumulateCost, computeCost, mergeUsage };
87
112
  //# sourceMappingURL=compute-cost.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"compute-cost.mjs","names":[],"sources":["../../../../../../../@warlock.js/ai/src/utils/compute-cost.ts"],"sourcesContent":["import type { ModelPricing } from \"../contracts/result/model-pricing.type\";\nimport type { Usage } from \"../contracts/result/usage.type\";\n\n/**\n * Compute a per-channel USD cost breakdown for a single `Usage` against\n * a model's pricing table. Returns `undefined` when no pricing is\n * configured — the framework treats unpriced runs as \"cost unknown,\"\n * not \"cost zero,\" so dashboards can distinguish free-tier from\n * un-instrumented.\n *\n * **Shape mirrors `ModelPricing`** — `input`, `output`, optional\n * `cachedInput` / `cachedOutput`. Consumers needing a scalar total\n * sum the populated fields. The breakdown is the value-add: it tells\n * downstream tooling HOW the total was reached (input-vs-output\n * share, cache savings) without re-deriving against pricing tables\n * that may have shifted since the report was written.\n *\n * **Cache-aware.** `usage.cachedTokens` is the subset of `usage.input`\n * served from the provider's prompt cache and bills at\n * `pricing.cachedInput` (falls back to full `pricing.input` when the\n * provider doesn't publish a cache rate). The remaining `input -\n * cachedTokens` bills at full rate and shows up in `cost.input`. The\n * `cachedOutput` channel is reserved for Anthropic-style cache writes;\n * until an adapter populates `usage.cacheWriteTokens`, the framework\n * leaves it undefined.\n *\n * Pricing values are USD-per-million-tokens. The function divides\n * once at the end to avoid floating-point accumulation error on\n * per-token math.\n *\n * @example\n * const usage: Usage = { input: 150_000, output: 30_000, total: 180_000, cachedTokens: 90_000 };\n * const cost = computeCost(usage, { input: 0.15, output: 0.6, cachedInput: 0.075 });\n * // cost = {\n * // input: (60_000 * 0.15) / 1e6 = 0.009,\n * // output: (30_000 * 0.6) / 1e6 = 0.018,\n * // cachedInput: (90_000 * 0.075) / 1e6 = 0.00675,\n * // }\n */\nexport function computeCost(usage: Usage, pricing: ModelPricing | undefined): ModelPricing | undefined {\n if (!pricing) {\n return undefined;\n }\n\n const cachedInput = usage.cachedTokens ?? 0;\n const uncachedInput = Math.max(0, usage.input - cachedInput);\n\n const cost: ModelPricing = {\n input: (uncachedInput * pricing.input) / 1_000_000,\n output: (usage.output * pricing.output) / 1_000_000,\n };\n\n if (cachedInput > 0) {\n const cachedInputRate = pricing.cachedInput ?? pricing.input;\n cost.cachedInput = (cachedInput * cachedInputRate) / 1_000_000;\n }\n\n return cost;\n}\n\n/**\n * Merge a child's cost breakdown into a running parent total. Each\n * channel (`input`, `output`, `cachedInput`, `cachedOutput`) sums\n * independently — an undefined channel on either side is treated as\n * zero contribution rather than dropping the other side's value. A\n * single unpriced child should never erase the cost of its priced\n * siblings.\n *\n * Returns the new parent breakdown, or `undefined` when neither parent\n * nor child carried any cost data (preserves the \"no priced\n * contributor has appeared yet\" signal that distinguishes \"missing\n * pricing\" from \"genuinely zero\").\n */\nexport function accumulateCost(\n parent: ModelPricing | undefined,\n child: ModelPricing | undefined,\n): ModelPricing | undefined {\n if (!child) {\n return parent;\n }\n\n if (!parent) {\n return { ...child };\n }\n\n const merged: ModelPricing = {\n input: parent.input + child.input,\n output: parent.output + child.output,\n };\n\n const cachedInput = sumOptional(parent.cachedInput, child.cachedInput);\n if (cachedInput !== undefined) {\n merged.cachedInput = cachedInput;\n }\n\n const cachedOutput = sumOptional(parent.cachedOutput, child.cachedOutput);\n if (cachedOutput !== undefined) {\n merged.cachedOutput = cachedOutput;\n }\n\n return merged;\n}\n\n/**\n * Add two optional numbers, treating either side's `undefined` as\n * zero — but return `undefined` when both are absent. Keeps \"this\n * channel was never reported anywhere\" distinguishable from \"this\n * channel was reported as 0.\"\n */\nfunction sumOptional(parent: number | undefined, child: number | undefined): number | undefined {\n if (parent === undefined && child === undefined) {\n return undefined;\n }\n\n return (parent ?? 0) + (child ?? 0);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuCA,SAAgB,YAAY,OAAc,SAA6D;CACrG,IAAI,CAAC,SACH;CAGF,MAAM,cAAc,MAAM,gBAAgB;CAG1C,MAAM,OAAqB;EACzB,OAHoB,KAAK,IAAI,GAAG,MAAM,QAAQ,WAG1B,IAAI,QAAQ,QAAS;EACzC,QAAS,MAAM,SAAS,QAAQ,SAAU;CAC5C;CAEA,IAAI,cAAc,GAEhB,KAAK,cAAe,eADI,QAAQ,eAAe,QAAQ,SACF;CAGvD,OAAO;AACT;;;;;;;;;;;;;;AAeA,SAAgB,eACd,QACA,OAC0B;CAC1B,IAAI,CAAC,OACH,OAAO;CAGT,IAAI,CAAC,QACH,OAAO,EAAE,GAAG,MAAM;CAGpB,MAAM,SAAuB;EAC3B,OAAO,OAAO,QAAQ,MAAM;EAC5B,QAAQ,OAAO,SAAS,MAAM;CAChC;CAEA,MAAM,cAAc,YAAY,OAAO,aAAa,MAAM,WAAW;CACrE,IAAI,gBAAgB,QAClB,OAAO,cAAc;CAGvB,MAAM,eAAe,YAAY,OAAO,cAAc,MAAM,YAAY;CACxE,IAAI,iBAAiB,QACnB,OAAO,eAAe;CAGxB,OAAO;AACT;;;;;;;AAQA,SAAS,YAAY,QAA4B,OAA+C;CAC9F,IAAI,WAAW,UAAa,UAAU,QACpC;CAGF,QAAQ,UAAU,MAAM,SAAS;AACnC"}
1
+ {"version":3,"file":"compute-cost.mjs","names":[],"sources":["../../../../../../../@warlock.js/ai/src/utils/compute-cost.ts"],"sourcesContent":["import type { ModelPricing } from \"../contracts/result/model-pricing.type\";\nimport type { Usage } from \"../contracts/result/usage.type\";\n\n/**\n * Compute a per-channel USD cost breakdown for a single `Usage` against\n * a model's pricing table. Returns `undefined` when no pricing is\n * configured — the framework treats unpriced runs as \"cost unknown,\"\n * not \"cost zero,\" so dashboards can distinguish free-tier from\n * un-instrumented.\n *\n * **Shape mirrors `ModelPricing`** — `input`, `output`, optional\n * `cachedInput` / `cachedOutput`. Consumers needing a scalar total\n * sum the populated fields. The breakdown is the value-add: it tells\n * downstream tooling HOW the total was reached (input-vs-output\n * share, cache savings) without re-deriving against pricing tables\n * that may have shifted since the report was written.\n *\n * **Cache-aware.** `usage.cachedTokens` is the subset of `usage.input`\n * served from the provider's prompt cache and bills at\n * `pricing.cachedInput` (falls back to full `pricing.input` when the\n * provider doesn't publish a cache rate). The remaining `input -\n * cachedTokens` bills at full rate and shows up in `cost.input`. The\n * `cachedOutput` channel is reserved for Anthropic-style cache writes;\n * until an adapter populates `usage.cacheWriteTokens`, the framework\n * leaves it undefined.\n *\n * Pricing values are USD-per-million-tokens. The function divides\n * once at the end to avoid floating-point accumulation error on\n * per-token math.\n *\n * @example\n * const usage: Usage = { input: 150_000, output: 30_000, total: 180_000, cachedTokens: 90_000 };\n * const cost = computeCost(usage, { input: 0.15, output: 0.6, cachedInput: 0.075 });\n * // cost = {\n * // input: (60_000 * 0.15) / 1e6 = 0.009,\n * // output: (30_000 * 0.6) / 1e6 = 0.018,\n * // cachedInput: (90_000 * 0.075) / 1e6 = 0.00675,\n * // }\n */\nexport function computeCost(usage: Usage, pricing: ModelPricing | undefined): ModelPricing | undefined {\n if (!pricing) {\n return undefined;\n }\n\n const cachedInput = usage.cachedTokens ?? 0;\n const uncachedInput = Math.max(0, usage.input - cachedInput);\n\n const cost: ModelPricing = {\n input: (uncachedInput * pricing.input) / 1_000_000,\n output: (usage.output * pricing.output) / 1_000_000,\n };\n\n if (cachedInput > 0) {\n const cachedInputRate = pricing.cachedInput ?? pricing.input;\n cost.cachedInput = (cachedInput * cachedInputRate) / 1_000_000;\n }\n\n return cost;\n}\n\n/**\n * Merge a child's cost breakdown into a running parent total. Each\n * channel (`input`, `output`, `cachedInput`, `cachedOutput`) sums\n * independently — an undefined channel on either side is treated as\n * zero contribution rather than dropping the other side's value. A\n * single unpriced child should never erase the cost of its priced\n * siblings.\n *\n * Returns the new parent breakdown, or `undefined` when neither parent\n * nor child carried any cost data (preserves the \"no priced\n * contributor has appeared yet\" signal that distinguishes \"missing\n * pricing\" from \"genuinely zero\").\n */\nexport function accumulateCost(\n parent: ModelPricing | undefined,\n child: ModelPricing | undefined,\n): ModelPricing | undefined {\n if (!child) {\n return parent;\n }\n\n if (!parent) {\n return { ...child };\n }\n\n const merged: ModelPricing = {\n input: parent.input + child.input,\n output: parent.output + child.output,\n };\n\n const cachedInput = sumOptional(parent.cachedInput, child.cachedInput);\n if (cachedInput !== undefined) {\n merged.cachedInput = cachedInput;\n }\n\n const cachedOutput = sumOptional(parent.cachedOutput, child.cachedOutput);\n if (cachedOutput !== undefined) {\n merged.cachedOutput = cachedOutput;\n }\n\n return merged;\n}\n\n/**\n * Add two optional numbers, treating either side's `undefined` as\n * zero — but return `undefined` when both are absent. Keeps \"this\n * channel was never reported anywhere\" distinguishable from \"this\n * channel was reported as 0.\"\n */\nfunction sumOptional(parent: number | undefined, child: number | undefined): number | undefined {\n if (parent === undefined && child === undefined) {\n return undefined;\n }\n\n return (parent ?? 0) + (child ?? 0);\n}\n\n/**\n * Accumulate a child {@link Usage} into a running parent total, mutating\n * `target` in place. Scalar token channels (`input` / `output` / `total`)\n * sum directly; the optional sub-channels (`cachedTokens`,\n * `reasoningTokens`, `cacheWriteTokens`) accumulate only when some\n * contributor reported them (preserving the \"never reported anywhere\"\n * signal); and the cost breakdown merges via {@link accumulateCost} so a\n * single unpriced child can never erase a priced sibling's cost.\n *\n * This is the ONE canonical usage rollup — every aggregator (agent,\n * workflow, supervisor, team, planner, batch) routes through it so cost +\n * cache/reasoning telemetry propagates identically to the top-level\n * `result.usage`. Re-implementing a bare `input/output/total` sum at a\n * call site silently drops those optional channels.\n */\nexport function 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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuCA,SAAgB,YAAY,OAAc,SAA6D;CACrG,IAAI,CAAC,SACH;CAGF,MAAM,cAAc,MAAM,gBAAgB;CAG1C,MAAM,OAAqB;EACzB,OAHoB,KAAK,IAAI,GAAG,MAAM,QAAQ,WAG1B,IAAI,QAAQ,QAAS;EACzC,QAAS,MAAM,SAAS,QAAQ,SAAU;CAC5C;CAEA,IAAI,cAAc,GAEhB,KAAK,cAAe,eADI,QAAQ,eAAe,QAAQ,SACF;CAGvD,OAAO;AACT;;;;;;;;;;;;;;AAeA,SAAgB,eACd,QACA,OAC0B;CAC1B,IAAI,CAAC,OACH,OAAO;CAGT,IAAI,CAAC,QACH,OAAO,EAAE,GAAG,MAAM;CAGpB,MAAM,SAAuB;EAC3B,OAAO,OAAO,QAAQ,MAAM;EAC5B,QAAQ,OAAO,SAAS,MAAM;CAChC;CAEA,MAAM,cAAc,YAAY,OAAO,aAAa,MAAM,WAAW;CACrE,IAAI,gBAAgB,QAClB,OAAO,cAAc;CAGvB,MAAM,eAAe,YAAY,OAAO,cAAc,MAAM,YAAY;CACxE,IAAI,iBAAiB,QACnB,OAAO,eAAe;CAGxB,OAAO;AACT;;;;;;;AAQA,SAAS,YAAY,QAA4B,OAA+C;CAC9F,IAAI,WAAW,UAAa,UAAU,QACpC;CAGF,QAAQ,UAAU,MAAM,SAAS;AACnC;;;;;;;;;;;;;;;;AAiBA,SAAgB,WAAW,QAAe,OAAoB;CAC5D,OAAO,SAAS,MAAM;CACtB,OAAO,UAAU,MAAM;CACvB,OAAO,SAAS,MAAM;CAEtB,IAAI,MAAM,iBAAiB,QACzB,OAAO,gBAAgB,OAAO,gBAAgB,KAAK,MAAM;CAG3D,IAAI,MAAM,oBAAoB,QAC5B,OAAO,mBAAmB,OAAO,mBAAmB,KAAK,MAAM;CAGjE,IAAI,MAAM,qBAAqB,QAC7B,OAAO,oBAAoB,OAAO,oBAAoB,KAAK,MAAM;CAGnE,MAAM,aAAa,eAAe,OAAO,MAAM,MAAM,IAAI;CACzD,IAAI,eAAe,QACjB,OAAO,OAAO;AAElB"}
@@ -0,0 +1,42 @@
1
+ //#region ../@warlock.js/ai/src/utils/extract-json-lenient.d.ts
2
+ /**
3
+ * Lenient counterpart to {@link extractJsonPayload}, tuned for the
4
+ * structured-output judges that emit *corrupted* JSON — notably the
5
+ * Amazon Nova family, which routinely wraps its verdict in fenced
6
+ * ` ```json ` blocks, prepends an explanation paragraph, or trails the
7
+ * object with commentary.
8
+ *
9
+ * Where `extractJsonPayload` deliberately refuses the "first `{` … last
10
+ * `}`" heuristic (it would corrupt strict callers when prose contains
11
+ * stray braces), this helper *opts into* that resilience: after fence
12
+ * stripping it scans for the first balanced JSON object (`{…}`) or array
13
+ * (`[…]`) and returns just that slice. Brace/bracket counting is
14
+ * string-aware (it ignores braces inside JSON string literals and honors
15
+ * `\"` escapes), so prose-embedded braces inside the JSON's own strings
16
+ * don't throw off the balance.
17
+ *
18
+ * Returns the fence-stripped, trimmed text unchanged when no balanced
19
+ * structure is found, so the caller's `JSON.parse` still fails loudly on
20
+ * genuine garbage rather than this helper inventing a value.
21
+ *
22
+ * **Trade-off:** resilience over strictness. Use it only where a tolerant
23
+ * parse is wanted (the judge preset) — for normal structured output keep
24
+ * `extractJsonPayload`, which fails fast on malformed responses so real
25
+ * prompt/model defects surface instead of being silently papered over.
26
+ *
27
+ * @example
28
+ * extractJsonLenient('Here is my verdict:\n```json\n{"score":0.9}\n``` — done.');
29
+ * // => '{"score":0.9}'
30
+ *
31
+ * @example
32
+ * extractJsonLenient('The answer is {"verdict":"pass"} for sure.');
33
+ * // => '{"verdict":"pass"}'
34
+ *
35
+ * @example
36
+ * extractJsonLenient('{"valid":true}');
37
+ * // => '{"valid":true}' (clean JSON passes through)
38
+ */
39
+ declare function extractJsonLenient(text: string): string;
40
+ //#endregion
41
+ export { extractJsonLenient };
42
+ //# sourceMappingURL=extract-json-lenient.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"extract-json-lenient.d.mts","names":[],"sources":["../../../../../../../@warlock.js/ai/src/utils/extract-json-lenient.ts"],"mappings":";;AAuCA;;;;AAA+C;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAA/B,kBAAA,CAAmB,IAAY"}
@@ -0,0 +1,97 @@
1
+ import { extractJsonPayload } from "./extract-json-payload.mjs";
2
+
3
+ //#region ../@warlock.js/ai/src/utils/extract-json-lenient.ts
4
+ /**
5
+ * Lenient counterpart to {@link extractJsonPayload}, tuned for the
6
+ * structured-output judges that emit *corrupted* JSON — notably the
7
+ * Amazon Nova family, which routinely wraps its verdict in fenced
8
+ * ` ```json ` blocks, prepends an explanation paragraph, or trails the
9
+ * object with commentary.
10
+ *
11
+ * Where `extractJsonPayload` deliberately refuses the "first `{` … last
12
+ * `}`" heuristic (it would corrupt strict callers when prose contains
13
+ * stray braces), this helper *opts into* that resilience: after fence
14
+ * stripping it scans for the first balanced JSON object (`{…}`) or array
15
+ * (`[…]`) and returns just that slice. Brace/bracket counting is
16
+ * string-aware (it ignores braces inside JSON string literals and honors
17
+ * `\"` escapes), so prose-embedded braces inside the JSON's own strings
18
+ * don't throw off the balance.
19
+ *
20
+ * Returns the fence-stripped, trimmed text unchanged when no balanced
21
+ * structure is found, so the caller's `JSON.parse` still fails loudly on
22
+ * genuine garbage rather than this helper inventing a value.
23
+ *
24
+ * **Trade-off:** resilience over strictness. Use it only where a tolerant
25
+ * parse is wanted (the judge preset) — for normal structured output keep
26
+ * `extractJsonPayload`, which fails fast on malformed responses so real
27
+ * prompt/model defects surface instead of being silently papered over.
28
+ *
29
+ * @example
30
+ * extractJsonLenient('Here is my verdict:\n```json\n{"score":0.9}\n``` — done.');
31
+ * // => '{"score":0.9}'
32
+ *
33
+ * @example
34
+ * extractJsonLenient('The answer is {"verdict":"pass"} for sure.');
35
+ * // => '{"verdict":"pass"}'
36
+ *
37
+ * @example
38
+ * extractJsonLenient('{"valid":true}');
39
+ * // => '{"valid":true}' (clean JSON passes through)
40
+ */
41
+ function extractJsonLenient(text) {
42
+ const stripped = extractJsonPayload(text);
43
+ return sliceFirstBalanced(stripped) ?? stripped;
44
+ }
45
+ /**
46
+ * Scan for the first balanced JSON object or array and return its raw
47
+ * slice. Returns `undefined` when no opening `{`/`[` is found or the
48
+ * structure never closes (truncated / partial output) — the caller then
49
+ * falls back to the fence-stripped text so the failure stays visible.
50
+ *
51
+ * String-literal aware: braces and brackets appearing *inside* a JSON
52
+ * string are not counted toward the balance, and a backslash escapes the
53
+ * next character so an escaped quote (`\"`) doesn't prematurely end the
54
+ * string scan.
55
+ */
56
+ function sliceFirstBalanced(text) {
57
+ const start = firstOpenerIndex(text);
58
+ if (start === -1) return;
59
+ const opener = text[start];
60
+ const closer = opener === "{" ? "}" : "]";
61
+ let depth = 0;
62
+ let inString = false;
63
+ let escaped = false;
64
+ for (let index = start; index < text.length; index++) {
65
+ const char = text[index];
66
+ if (inString) {
67
+ if (escaped) escaped = false;
68
+ else if (char === "\\") escaped = true;
69
+ else if (char === "\"") inString = false;
70
+ continue;
71
+ }
72
+ if (char === "\"") {
73
+ inString = true;
74
+ continue;
75
+ }
76
+ if (char === opener) depth++;
77
+ else if (char === closer) {
78
+ depth--;
79
+ if (depth === 0) return text.slice(start, index + 1);
80
+ }
81
+ }
82
+ }
83
+ /**
84
+ * Index of the first JSON structure opener (`{` or `[`), whichever
85
+ * appears earliest, or `-1` when neither is present.
86
+ */
87
+ function firstOpenerIndex(text) {
88
+ const brace = text.indexOf("{");
89
+ const bracket = text.indexOf("[");
90
+ if (brace === -1) return bracket;
91
+ if (bracket === -1) return brace;
92
+ return Math.min(brace, bracket);
93
+ }
94
+
95
+ //#endregion
96
+ export { extractJsonLenient };
97
+ //# sourceMappingURL=extract-json-lenient.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"extract-json-lenient.mjs","names":[],"sources":["../../../../../../../@warlock.js/ai/src/utils/extract-json-lenient.ts"],"sourcesContent":["import { extractJsonPayload } from \"./extract-json-payload\";\n\n/**\n * Lenient counterpart to {@link extractJsonPayload}, tuned for the\n * structured-output judges that emit *corrupted* JSON — notably the\n * Amazon Nova family, which routinely wraps its verdict in fenced\n * ` ```json ` blocks, prepends an explanation paragraph, or trails the\n * object with commentary.\n *\n * Where `extractJsonPayload` deliberately refuses the \"first `{` … last\n * `}`\" heuristic (it would corrupt strict callers when prose contains\n * stray braces), this helper *opts into* that resilience: after fence\n * stripping it scans for the first balanced JSON object (`{…}`) or array\n * (`[…]`) and returns just that slice. Brace/bracket counting is\n * string-aware (it ignores braces inside JSON string literals and honors\n * `\\\"` escapes), so prose-embedded braces inside the JSON's own strings\n * don't throw off the balance.\n *\n * Returns the fence-stripped, trimmed text unchanged when no balanced\n * structure is found, so the caller's `JSON.parse` still fails loudly on\n * genuine garbage rather than this helper inventing a value.\n *\n * **Trade-off:** resilience over strictness. Use it only where a tolerant\n * parse is wanted (the judge preset) — for normal structured output keep\n * `extractJsonPayload`, which fails fast on malformed responses so real\n * prompt/model defects surface instead of being silently papered over.\n *\n * @example\n * extractJsonLenient('Here is my verdict:\\n```json\\n{\"score\":0.9}\\n``` — done.');\n * // => '{\"score\":0.9}'\n *\n * @example\n * extractJsonLenient('The answer is {\"verdict\":\"pass\"} for sure.');\n * // => '{\"verdict\":\"pass\"}'\n *\n * @example\n * extractJsonLenient('{\"valid\":true}');\n * // => '{\"valid\":true}' (clean JSON passes through)\n */\nexport function extractJsonLenient(text: string): string {\n // First reuse the strict fence stripper. When the model produced a\n // clean fenced block this already yields the exact payload, so the\n // balanced scan below becomes a no-op pass-through.\n const stripped = extractJsonPayload(text);\n\n const sliced = sliceFirstBalanced(stripped);\n\n return sliced ?? stripped;\n}\n\n/**\n * Scan for the first balanced JSON object or array and return its raw\n * slice. Returns `undefined` when no opening `{`/`[` is found or the\n * structure never closes (truncated / partial output) — the caller then\n * falls back to the fence-stripped text so the failure stays visible.\n *\n * String-literal aware: braces and brackets appearing *inside* a JSON\n * string are not counted toward the balance, and a backslash escapes the\n * next character so an escaped quote (`\\\"`) doesn't prematurely end the\n * string scan.\n */\nfunction sliceFirstBalanced(text: string): string | undefined {\n const start = firstOpenerIndex(text);\n\n if (start === -1) {\n return undefined;\n }\n\n const opener = text[start];\n const closer = opener === \"{\" ? \"}\" : \"]\";\n\n let depth = 0;\n let inString = false;\n let escaped = false;\n\n for (let index = start; index < text.length; index++) {\n const char = text[index];\n\n if (inString) {\n if (escaped) {\n escaped = false;\n } else if (char === \"\\\\\") {\n escaped = true;\n } else if (char === '\"') {\n inString = false;\n }\n\n continue;\n }\n\n if (char === '\"') {\n inString = true;\n continue;\n }\n\n if (char === opener) {\n depth++;\n } else if (char === closer) {\n depth--;\n\n if (depth === 0) {\n return text.slice(start, index + 1);\n }\n }\n }\n\n // Opener with no matching close — truncated / partial output. Leave it\n // to the caller's fallback (and its loud parse failure).\n return undefined;\n}\n\n/**\n * Index of the first JSON structure opener (`{` or `[`), whichever\n * appears earliest, or `-1` when neither is present.\n */\nfunction firstOpenerIndex(text: string): number {\n const brace = text.indexOf(\"{\");\n const bracket = text.indexOf(\"[\");\n\n if (brace === -1) {\n return bracket;\n }\n\n if (bracket === -1) {\n return brace;\n }\n\n return Math.min(brace, bracket);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuCA,SAAgB,mBAAmB,MAAsB;CAIvD,MAAM,WAAW,mBAAmB,IAAI;CAIxC,OAFe,mBAAmB,QAEtB,KAAK;AACnB;;;;;;;;;;;;AAaA,SAAS,mBAAmB,MAAkC;CAC5D,MAAM,QAAQ,iBAAiB,IAAI;CAEnC,IAAI,UAAU,IACZ;CAGF,MAAM,SAAS,KAAK;CACpB,MAAM,SAAS,WAAW,MAAM,MAAM;CAEtC,IAAI,QAAQ;CACZ,IAAI,WAAW;CACf,IAAI,UAAU;CAEd,KAAK,IAAI,QAAQ,OAAO,QAAQ,KAAK,QAAQ,SAAS;EACpD,MAAM,OAAO,KAAK;EAElB,IAAI,UAAU;GACZ,IAAI,SACF,UAAU;QACL,IAAI,SAAS,MAClB,UAAU;QACL,IAAI,SAAS,MAClB,WAAW;GAGb;EACF;EAEA,IAAI,SAAS,MAAK;GAChB,WAAW;GACX;EACF;EAEA,IAAI,SAAS,QACX;OACK,IAAI,SAAS,QAAQ;GAC1B;GAEA,IAAI,UAAU,GACZ,OAAO,KAAK,MAAM,OAAO,QAAQ,CAAC;EAEtC;CACF;AAKF;;;;;AAMA,SAAS,iBAAiB,MAAsB;CAC9C,MAAM,QAAQ,KAAK,QAAQ,GAAG;CAC9B,MAAM,UAAU,KAAK,QAAQ,GAAG;CAEhC,IAAI,UAAU,IACZ,OAAO;CAGT,IAAI,YAAY,IACd,OAAO;CAGT,OAAO,KAAK,IAAI,OAAO,OAAO;AAChC"}
@@ -1,9 +1,11 @@
1
- import { accumulateCost, computeCost } from "./compute-cost.mjs";
1
+ import { accumulateCost, computeCost, mergeUsage } from "./compute-cost.mjs";
2
+ import { extractJsonLenient } from "./extract-json-lenient.mjs";
2
3
  import { extractJsonPayload } from "./extract-json-payload.mjs";
3
4
  import { generateRunId } from "./generate-run-id.mjs";
4
- import { extractJsonSchema } from "./json-schema.mjs";
5
+ import { ExtractJsonSchemaOptions, JsonSchemaTarget, extractJsonSchema } from "./json-schema.mjs";
5
6
  import { prepareAttachmentPart } from "./prepare-attachment-part.mjs";
6
7
  import { resolveAttachment } from "./resolve-attachment.mjs";
8
+ import { RunFrame, captureChildReport, currentRunFrame, withRunFrame, withoutRunFrame } from "./run-context.mjs";
7
9
  import { safeJsonParse } from "./safe-json-parse.mjs";
8
10
  import { LineageStamp, stampReportLineage } from "./stamp-report-lineage.mjs";
9
11
  import { approximateTokenCount } from "./token-count.mjs";
@@ -1,9 +1,11 @@
1
- import { accumulateCost, computeCost } from "./compute-cost.mjs";
1
+ import { accumulateCost, computeCost, mergeUsage } from "./compute-cost.mjs";
2
2
  import { extractJsonPayload } from "./extract-json-payload.mjs";
3
+ import { extractJsonLenient } from "./extract-json-lenient.mjs";
3
4
  import { generateRunId } from "./generate-run-id.mjs";
4
5
  import { extractJsonSchema } from "./json-schema.mjs";
5
6
  import { resolveAttachment } from "./resolve-attachment.mjs";
6
7
  import { prepareAttachmentPart } from "./prepare-attachment-part.mjs";
8
+ import { captureChildReport, currentRunFrame, withRunFrame, withoutRunFrame } from "./run-context.mjs";
7
9
  import { safeJsonParse } from "./safe-json-parse.mjs";
8
10
  import { stampReportLineage } from "./stamp-report-lineage.mjs";
9
11
  import { approximateTokenCount } from "./token-count.mjs";
@@ -53,5 +53,5 @@ type ExtractJsonSchemaOptions = {
53
53
  */
54
54
  declare function extractJsonSchema(schema: StandardSchemaV1<unknown> | undefined, options?: ExtractJsonSchemaOptions): Record<string, unknown> | undefined;
55
55
  //#endregion
56
- export { extractJsonSchema };
56
+ export { ExtractJsonSchemaOptions, JsonSchemaTarget, extractJsonSchema };
57
57
  //# sourceMappingURL=json-schema.d.mts.map
@@ -1,3 +1,4 @@
1
+ import { AttachmentPolicy } from "../contracts/attachment-policy.type.mjs";
1
2
  import { Attachment } from "../contracts/attachment.type.mjs";
2
3
  import { ContentPart } from "../contracts/content-part.type.mjs";
3
4
 
@@ -29,8 +30,16 @@ import { ContentPart } from "../contracts/content-part.type.mjs";
29
30
  * @example
30
31
  * await prepareAttachmentPart({ type: "text", source: "./notes.txt" });
31
32
  * // → { type: "text", text: "<file contents>" }
33
+ *
34
+ * **Trust boundary (S1).** Attachment references are often user-controlled,
35
+ * so server-side I/O is policy-gated by `policy` ({@link AttachmentPolicy}):
36
+ * remote text fetches are default-deny and, when enabled, run through the
37
+ * shared `OutboundPolicy` (scheme/host/private-IP/max-bytes/timeout); local
38
+ * reads honor an `allowedRoots` sandbox; bare-string local paths warn
39
+ * (staged deprecation). URL *image* attachments are passed to the provider
40
+ * untouched (never fetched here).
32
41
  */
33
- declare function prepareAttachmentPart(attachment: Attachment): Promise<ContentPart>;
42
+ declare function prepareAttachmentPart(attachment: Attachment, policy?: AttachmentPolicy): Promise<ContentPart>;
34
43
  //#endregion
35
44
  export { prepareAttachmentPart };
36
45
  //# sourceMappingURL=prepare-attachment-part.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"prepare-attachment-part.d.mts","names":[],"sources":["../../../../../../../@warlock.js/ai/src/utils/prepare-attachment-part.ts"],"mappings":";;;;;;AA+CA;;;;;;;;;;;;;AAEsB;;;;;;;;;;;;;iBAFA,qBAAA,CACpB,UAAA,EAAY,UAAA,GACX,OAAA,CAAQ,WAAA"}
1
+ {"version":3,"file":"prepare-attachment-part.d.mts","names":[],"sources":["../../../../../../../@warlock.js/ai/src/utils/prepare-attachment-part.ts"],"mappings":";;;;;;;AAmEA;;;;;;;;;;;;;;;;AAGsB;;;;;;;;;;;;;;;;;;iBAHA,qBAAA,CACpB,UAAA,EAAY,UAAA,EACZ,MAAA,GAAS,gBAAA,GACR,OAAA,CAAQ,WAAA"}