@warlock.js/ai 4.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (490) hide show
  1. package/README.md +72 -0
  2. package/cjs/index.cjs +8625 -0
  3. package/cjs/index.cjs.map +1 -0
  4. package/esm/agent/agent-config.type.d.mts +160 -0
  5. package/esm/agent/agent-config.type.d.mts.map +1 -0
  6. package/esm/agent/agent-input-builder.mjs +111 -0
  7. package/esm/agent/agent-input-builder.mjs.map +1 -0
  8. package/esm/agent/agent-log-event.mjs +101 -0
  9. package/esm/agent/agent-log-event.mjs.map +1 -0
  10. package/esm/agent/agent-stream.d.mts +47 -0
  11. package/esm/agent/agent-stream.d.mts.map +1 -0
  12. package/esm/agent/agent-stream.mjs +82 -0
  13. package/esm/agent/agent-stream.mjs.map +1 -0
  14. package/esm/agent/agent-to-stream-event.mjs +86 -0
  15. package/esm/agent/agent-to-stream-event.mjs.map +1 -0
  16. package/esm/agent/agent.d.mts +38 -0
  17. package/esm/agent/agent.d.mts.map +1 -0
  18. package/esm/agent/agent.mjs +974 -0
  19. package/esm/agent/agent.mjs.map +1 -0
  20. package/esm/agent/index.d.mts +3 -0
  21. package/esm/agent/index.mjs +4 -0
  22. package/esm/agent/json-stream-guard.mjs +400 -0
  23. package/esm/agent/json-stream-guard.mjs.map +1 -0
  24. package/esm/ai.d.mts +64 -0
  25. package/esm/ai.d.mts.map +1 -0
  26. package/esm/ai.mjs +65 -0
  27. package/esm/ai.mjs.map +1 -0
  28. package/esm/config.d.mts +79 -0
  29. package/esm/config.d.mts.map +1 -0
  30. package/esm/config.mjs +43 -0
  31. package/esm/config.mjs.map +1 -0
  32. package/esm/contracts/agent/agent-options.type.d.mts +132 -0
  33. package/esm/contracts/agent/agent-options.type.d.mts.map +1 -0
  34. package/esm/contracts/agent/agent.contract.d.mts +92 -0
  35. package/esm/contracts/agent/agent.contract.d.mts.map +1 -0
  36. package/esm/contracts/agent/index.d.mts +2 -0
  37. package/esm/contracts/attachment.type.d.mts +100 -0
  38. package/esm/contracts/attachment.type.d.mts.map +1 -0
  39. package/esm/contracts/content-part.type.d.mts +55 -0
  40. package/esm/contracts/content-part.type.d.mts.map +1 -0
  41. package/esm/contracts/conversation-message.type.d.mts +51 -0
  42. package/esm/contracts/conversation-message.type.d.mts.map +1 -0
  43. package/esm/contracts/embedder.contract.d.mts +69 -0
  44. package/esm/contracts/embedder.contract.d.mts.map +1 -0
  45. package/esm/contracts/end.type.d.mts +53 -0
  46. package/esm/contracts/end.type.d.mts.map +1 -0
  47. package/esm/contracts/end.type.mjs +47 -0
  48. package/esm/contracts/end.type.mjs.map +1 -0
  49. package/esm/contracts/events/agent-events.type.d.mts +71 -0
  50. package/esm/contracts/events/agent-events.type.d.mts.map +1 -0
  51. package/esm/contracts/events/complete-event.type.d.mts +33 -0
  52. package/esm/contracts/events/complete-event.type.d.mts.map +1 -0
  53. package/esm/contracts/events/event-identity.type.d.mts +30 -0
  54. package/esm/contracts/events/event-identity.type.d.mts.map +1 -0
  55. package/esm/contracts/events/event-map.type.d.mts +80 -0
  56. package/esm/contracts/events/event-map.type.d.mts.map +1 -0
  57. package/esm/contracts/events/index.d.mts +7 -0
  58. package/esm/contracts/events/supervisor-events.type.d.mts +162 -0
  59. package/esm/contracts/events/supervisor-events.type.d.mts.map +1 -0
  60. package/esm/contracts/events/usage-event.type.d.mts +39 -0
  61. package/esm/contracts/events/usage-event.type.d.mts.map +1 -0
  62. package/esm/contracts/events/workflow-events.type.d.mts +51 -0
  63. package/esm/contracts/events/workflow-events.type.d.mts.map +1 -0
  64. package/esm/contracts/executable.contract.d.mts +25 -0
  65. package/esm/contracts/executable.contract.d.mts.map +1 -0
  66. package/esm/contracts/finish-reason.type.d.mts +17 -0
  67. package/esm/contracts/finish-reason.type.d.mts.map +1 -0
  68. package/esm/contracts/index.d.mts +63 -0
  69. package/esm/contracts/middleware/index.d.mts +3 -0
  70. package/esm/contracts/middleware/middleware-context.type.d.mts +99 -0
  71. package/esm/contracts/middleware/middleware-context.type.d.mts.map +1 -0
  72. package/esm/contracts/middleware/middleware-state.type.d.mts +34 -0
  73. package/esm/contracts/middleware/middleware-state.type.d.mts.map +1 -0
  74. package/esm/contracts/middleware/middleware.contract.d.mts +140 -0
  75. package/esm/contracts/middleware/middleware.contract.d.mts.map +1 -0
  76. package/esm/contracts/model-tool-call-request.type.d.mts +58 -0
  77. package/esm/contracts/model-tool-call-request.type.d.mts.map +1 -0
  78. package/esm/contracts/model.contract.d.mts +164 -0
  79. package/esm/contracts/model.contract.d.mts.map +1 -0
  80. package/esm/contracts/placeholders.type.d.mts +23 -0
  81. package/esm/contracts/placeholders.type.d.mts.map +1 -0
  82. package/esm/contracts/result/agent-result.type.d.mts +33 -0
  83. package/esm/contracts/result/agent-result.type.d.mts.map +1 -0
  84. package/esm/contracts/result/attempt-entry.type.d.mts +40 -0
  85. package/esm/contracts/result/attempt-entry.type.d.mts.map +1 -0
  86. package/esm/contracts/result/base-report.type.d.mts +137 -0
  87. package/esm/contracts/result/base-report.type.d.mts.map +1 -0
  88. package/esm/contracts/result/base-report.type.mjs +17 -0
  89. package/esm/contracts/result/base-report.type.mjs.map +1 -0
  90. package/esm/contracts/result/base-result.type.d.mts +26 -0
  91. package/esm/contracts/result/base-result.type.d.mts.map +1 -0
  92. package/esm/contracts/result/execute-result.type.d.mts +40 -0
  93. package/esm/contracts/result/execute-result.type.d.mts.map +1 -0
  94. package/esm/contracts/result/execution-report.type.d.mts +50 -0
  95. package/esm/contracts/result/execution-report.type.d.mts.map +1 -0
  96. package/esm/contracts/result/index.d.mts +14 -0
  97. package/esm/contracts/result/llm-trip.type.d.mts +36 -0
  98. package/esm/contracts/result/llm-trip.type.d.mts.map +1 -0
  99. package/esm/contracts/result/model-pricing.type.d.mts +51 -0
  100. package/esm/contracts/result/model-pricing.type.d.mts.map +1 -0
  101. package/esm/contracts/result/session-send-result.type.d.mts +29 -0
  102. package/esm/contracts/result/session-send-result.type.d.mts.map +1 -0
  103. package/esm/contracts/result/step-result.type.d.mts +43 -0
  104. package/esm/contracts/result/step-result.type.d.mts.map +1 -0
  105. package/esm/contracts/result/supervisor-result.type.d.mts +86 -0
  106. package/esm/contracts/result/supervisor-result.type.d.mts.map +1 -0
  107. package/esm/contracts/result/tool-call.type.d.mts +44 -0
  108. package/esm/contracts/result/tool-call.type.d.mts.map +1 -0
  109. package/esm/contracts/result/usage.type.d.mts +57 -0
  110. package/esm/contracts/result/usage.type.d.mts.map +1 -0
  111. package/esm/contracts/result/workflow-result.type.d.mts +45 -0
  112. package/esm/contracts/result/workflow-result.type.d.mts.map +1 -0
  113. package/esm/contracts/sdk-adapter.contract.d.mts +77 -0
  114. package/esm/contracts/sdk-adapter.contract.d.mts.map +1 -0
  115. package/esm/contracts/stream/stream-event.type.d.mts +68 -0
  116. package/esm/contracts/stream/stream-event.type.d.mts.map +1 -0
  117. package/esm/contracts/stream/stream.contract.d.mts +61 -0
  118. package/esm/contracts/stream/stream.contract.d.mts.map +1 -0
  119. package/esm/contracts/streaming-tool-guard-config.type.d.mts +78 -0
  120. package/esm/contracts/streaming-tool-guard-config.type.d.mts.map +1 -0
  121. package/esm/contracts/supervisor/ack-entry.type.d.mts +97 -0
  122. package/esm/contracts/supervisor/ack-entry.type.d.mts.map +1 -0
  123. package/esm/contracts/supervisor/classifier-context.type.d.mts +189 -0
  124. package/esm/contracts/supervisor/classifier-context.type.d.mts.map +1 -0
  125. package/esm/contracts/supervisor/dispatch-context.type.d.mts +235 -0
  126. package/esm/contracts/supervisor/dispatch-context.type.d.mts.map +1 -0
  127. package/esm/contracts/supervisor/evaluate-context.type.d.mts +124 -0
  128. package/esm/contracts/supervisor/evaluate-context.type.d.mts.map +1 -0
  129. package/esm/contracts/supervisor/index.d.mts +16 -0
  130. package/esm/contracts/supervisor/intent-entry.type.d.mts +254 -0
  131. package/esm/contracts/supervisor/intent-entry.type.d.mts.map +1 -0
  132. package/esm/contracts/supervisor/iteration-snapshot.type.d.mts +117 -0
  133. package/esm/contracts/supervisor/iteration-snapshot.type.d.mts.map +1 -0
  134. package/esm/contracts/supervisor/next.type.d.mts +25 -0
  135. package/esm/contracts/supervisor/next.type.d.mts.map +1 -0
  136. package/esm/contracts/supervisor/route-context.type.d.mts +91 -0
  137. package/esm/contracts/supervisor/route-context.type.d.mts.map +1 -0
  138. package/esm/contracts/supervisor/router-entry.type.d.mts +67 -0
  139. package/esm/contracts/supervisor/router-entry.type.d.mts.map +1 -0
  140. package/esm/contracts/supervisor/supervisor-config.type.d.mts +356 -0
  141. package/esm/contracts/supervisor/supervisor-config.type.d.mts.map +1 -0
  142. package/esm/contracts/supervisor/supervisor-execute-options.type.d.mts +90 -0
  143. package/esm/contracts/supervisor/supervisor-execute-options.type.d.mts.map +1 -0
  144. package/esm/contracts/supervisor/supervisor-input.type.d.mts +24 -0
  145. package/esm/contracts/supervisor/supervisor-input.type.d.mts.map +1 -0
  146. package/esm/contracts/supervisor/supervisor-snapshot.type.d.mts +49 -0
  147. package/esm/contracts/supervisor/supervisor-snapshot.type.d.mts.map +1 -0
  148. package/esm/contracts/supervisor/supervisor-stream-event.type.d.mts +16 -0
  149. package/esm/contracts/supervisor/supervisor-stream-event.type.d.mts.map +1 -0
  150. package/esm/contracts/supervisor/supervisor.contract.d.mts +126 -0
  151. package/esm/contracts/supervisor/supervisor.contract.d.mts.map +1 -0
  152. package/esm/contracts/system-prompt.contract.d.mts +118 -0
  153. package/esm/contracts/system-prompt.contract.d.mts.map +1 -0
  154. package/esm/contracts/tool.contract.d.mts +161 -0
  155. package/esm/contracts/tool.contract.d.mts.map +1 -0
  156. package/esm/contracts/workflow/index.d.mts +6 -0
  157. package/esm/contracts/workflow/next-step-result.type.d.mts +17 -0
  158. package/esm/contracts/workflow/next-step-result.type.d.mts.map +1 -0
  159. package/esm/contracts/workflow/retry-config.type.d.mts +19 -0
  160. package/esm/contracts/workflow/retry-config.type.d.mts.map +1 -0
  161. package/esm/contracts/workflow/step.contract.d.mts +189 -0
  162. package/esm/contracts/workflow/step.contract.d.mts.map +1 -0
  163. package/esm/contracts/workflow/workflow-context.type.d.mts +45 -0
  164. package/esm/contracts/workflow/workflow-context.type.d.mts.map +1 -0
  165. package/esm/contracts/workflow/workflow-snapshot.type.d.mts +24 -0
  166. package/esm/contracts/workflow/workflow-snapshot.type.d.mts.map +1 -0
  167. package/esm/contracts/workflow/workflow.contract.d.mts +142 -0
  168. package/esm/contracts/workflow/workflow.contract.d.mts.map +1 -0
  169. package/esm/errors/agent-cancelled-error.d.mts +49 -0
  170. package/esm/errors/agent-cancelled-error.d.mts.map +1 -0
  171. package/esm/errors/agent-cancelled-error.mjs +43 -0
  172. package/esm/errors/agent-cancelled-error.mjs.map +1 -0
  173. package/esm/errors/agent-execution-error.d.mts +32 -0
  174. package/esm/errors/agent-execution-error.d.mts.map +1 -0
  175. package/esm/errors/agent-execution-error.mjs +35 -0
  176. package/esm/errors/agent-execution-error.mjs.map +1 -0
  177. package/esm/errors/agent-max-trips-error.d.mts +45 -0
  178. package/esm/errors/agent-max-trips-error.d.mts.map +1 -0
  179. package/esm/errors/agent-max-trips-error.mjs +41 -0
  180. package/esm/errors/agent-max-trips-error.mjs.map +1 -0
  181. package/esm/errors/ai-error.d.mts +94 -0
  182. package/esm/errors/ai-error.d.mts.map +1 -0
  183. package/esm/errors/ai-error.mjs +68 -0
  184. package/esm/errors/ai-error.mjs.map +1 -0
  185. package/esm/errors/budget-exceeded-error.d.mts +41 -0
  186. package/esm/errors/budget-exceeded-error.d.mts.map +1 -0
  187. package/esm/errors/budget-exceeded-error.mjs +31 -0
  188. package/esm/errors/budget-exceeded-error.mjs.map +1 -0
  189. package/esm/errors/content-filter-error.d.mts +33 -0
  190. package/esm/errors/content-filter-error.d.mts.map +1 -0
  191. package/esm/errors/content-filter-error.mjs +28 -0
  192. package/esm/errors/content-filter-error.mjs.map +1 -0
  193. package/esm/errors/context-length-exceeded-error.d.mts +38 -0
  194. package/esm/errors/context-length-exceeded-error.d.mts.map +1 -0
  195. package/esm/errors/context-length-exceeded-error.mjs +31 -0
  196. package/esm/errors/context-length-exceeded-error.mjs.map +1 -0
  197. package/esm/errors/error-category.type.d.mts +30 -0
  198. package/esm/errors/error-category.type.d.mts.map +1 -0
  199. package/esm/errors/error-code.type.d.mts +19 -0
  200. package/esm/errors/error-code.type.d.mts.map +1 -0
  201. package/esm/errors/guardrail-violation-error.d.mts +55 -0
  202. package/esm/errors/guardrail-violation-error.d.mts.map +1 -0
  203. package/esm/errors/guardrail-violation-error.mjs +41 -0
  204. package/esm/errors/guardrail-violation-error.mjs.map +1 -0
  205. package/esm/errors/index.d.mts +29 -0
  206. package/esm/errors/index.mjs +29 -0
  207. package/esm/errors/invalid-request-error.d.mts +27 -0
  208. package/esm/errors/invalid-request-error.d.mts.map +1 -0
  209. package/esm/errors/invalid-request-error.mjs +31 -0
  210. package/esm/errors/invalid-request-error.mjs.map +1 -0
  211. package/esm/errors/max-iterations-error.d.mts +31 -0
  212. package/esm/errors/max-iterations-error.d.mts.map +1 -0
  213. package/esm/errors/max-iterations-error.mjs +32 -0
  214. package/esm/errors/max-iterations-error.mjs.map +1 -0
  215. package/esm/errors/max-steps-exceeded-error.d.mts +20 -0
  216. package/esm/errors/max-steps-exceeded-error.d.mts.map +1 -0
  217. package/esm/errors/max-steps-exceeded-error.mjs +21 -0
  218. package/esm/errors/max-steps-exceeded-error.mjs.map +1 -0
  219. package/esm/errors/provider-auth-error.d.mts +22 -0
  220. package/esm/errors/provider-auth-error.d.mts.map +1 -0
  221. package/esm/errors/provider-auth-error.mjs +26 -0
  222. package/esm/errors/provider-auth-error.mjs.map +1 -0
  223. package/esm/errors/provider-error.d.mts +38 -0
  224. package/esm/errors/provider-error.d.mts.map +1 -0
  225. package/esm/errors/provider-error.mjs +42 -0
  226. package/esm/errors/provider-error.mjs.map +1 -0
  227. package/esm/errors/provider-rate-limit-error.d.mts +34 -0
  228. package/esm/errors/provider-rate-limit-error.d.mts.map +1 -0
  229. package/esm/errors/provider-rate-limit-error.mjs +31 -0
  230. package/esm/errors/provider-rate-limit-error.mjs.map +1 -0
  231. package/esm/errors/provider-timeout-error.d.mts +22 -0
  232. package/esm/errors/provider-timeout-error.d.mts.map +1 -0
  233. package/esm/errors/provider-timeout-error.mjs +26 -0
  234. package/esm/errors/provider-timeout-error.mjs.map +1 -0
  235. package/esm/errors/quota-exceeded-error.d.mts +36 -0
  236. package/esm/errors/quota-exceeded-error.d.mts.map +1 -0
  237. package/esm/errors/quota-exceeded-error.mjs +40 -0
  238. package/esm/errors/quota-exceeded-error.mjs.map +1 -0
  239. package/esm/errors/routing-error.d.mts +23 -0
  240. package/esm/errors/routing-error.d.mts.map +1 -0
  241. package/esm/errors/routing-error.mjs +23 -0
  242. package/esm/errors/routing-error.mjs.map +1 -0
  243. package/esm/errors/schema-validation-error.d.mts +40 -0
  244. package/esm/errors/schema-validation-error.d.mts.map +1 -0
  245. package/esm/errors/schema-validation-error.mjs +37 -0
  246. package/esm/errors/schema-validation-error.mjs.map +1 -0
  247. package/esm/errors/step-failed-error.d.mts +20 -0
  248. package/esm/errors/step-failed-error.d.mts.map +1 -0
  249. package/esm/errors/step-failed-error.mjs +19 -0
  250. package/esm/errors/step-failed-error.mjs.map +1 -0
  251. package/esm/errors/supervisor-cancelled-error.d.mts +29 -0
  252. package/esm/errors/supervisor-cancelled-error.d.mts.map +1 -0
  253. package/esm/errors/supervisor-cancelled-error.mjs +29 -0
  254. package/esm/errors/supervisor-cancelled-error.mjs.map +1 -0
  255. package/esm/errors/supervisor-drift-error.d.mts +31 -0
  256. package/esm/errors/supervisor-drift-error.d.mts.map +1 -0
  257. package/esm/errors/supervisor-drift-error.mjs +30 -0
  258. package/esm/errors/supervisor-drift-error.mjs.map +1 -0
  259. package/esm/errors/supervisor-failed-error.d.mts +40 -0
  260. package/esm/errors/supervisor-failed-error.d.mts.map +1 -0
  261. package/esm/errors/supervisor-failed-error.mjs +43 -0
  262. package/esm/errors/supervisor-failed-error.mjs.map +1 -0
  263. package/esm/errors/supervisor-routing-error.d.mts +44 -0
  264. package/esm/errors/supervisor-routing-error.d.mts.map +1 -0
  265. package/esm/errors/supervisor-routing-error.mjs +39 -0
  266. package/esm/errors/supervisor-routing-error.mjs.map +1 -0
  267. package/esm/errors/tool-execution-error.d.mts +35 -0
  268. package/esm/errors/tool-execution-error.d.mts.map +1 -0
  269. package/esm/errors/tool-execution-error.mjs +32 -0
  270. package/esm/errors/tool-execution-error.mjs.map +1 -0
  271. package/esm/errors/workflow-cancelled-error.d.mts +23 -0
  272. package/esm/errors/workflow-cancelled-error.d.mts.map +1 -0
  273. package/esm/errors/workflow-cancelled-error.mjs +23 -0
  274. package/esm/errors/workflow-cancelled-error.mjs.map +1 -0
  275. package/esm/errors/workflow-drift-error.d.mts +25 -0
  276. package/esm/errors/workflow-drift-error.d.mts.map +1 -0
  277. package/esm/errors/workflow-drift-error.mjs +24 -0
  278. package/esm/errors/workflow-drift-error.mjs.map +1 -0
  279. package/esm/errors/workflow-error.d.mts +15 -0
  280. package/esm/errors/workflow-error.d.mts.map +1 -0
  281. package/esm/errors/workflow-error.mjs +18 -0
  282. package/esm/errors/workflow-error.mjs.map +1 -0
  283. package/esm/index.d.mts +137 -0
  284. package/esm/index.mjs +81 -0
  285. package/esm/middleware/builtins/budget.d.mts +103 -0
  286. package/esm/middleware/builtins/budget.d.mts.map +1 -0
  287. package/esm/middleware/builtins/budget.mjs +100 -0
  288. package/esm/middleware/builtins/budget.mjs.map +1 -0
  289. package/esm/middleware/builtins/guardrail.d.mts +92 -0
  290. package/esm/middleware/builtins/guardrail.d.mts.map +1 -0
  291. package/esm/middleware/builtins/guardrail.mjs +76 -0
  292. package/esm/middleware/builtins/guardrail.mjs.map +1 -0
  293. package/esm/middleware/builtins/semantic-cache.d.mts +106 -0
  294. package/esm/middleware/builtins/semantic-cache.d.mts.map +1 -0
  295. package/esm/middleware/builtins/semantic-cache.mjs +149 -0
  296. package/esm/middleware/builtins/semantic-cache.mjs.map +1 -0
  297. package/esm/middleware/helpers/compose.d.mts +42 -0
  298. package/esm/middleware/helpers/compose.d.mts.map +1 -0
  299. package/esm/middleware/helpers/compose.mjs +52 -0
  300. package/esm/middleware/helpers/compose.mjs.map +1 -0
  301. package/esm/middleware/helpers/for-tool.d.mts +55 -0
  302. package/esm/middleware/helpers/for-tool.d.mts.map +1 -0
  303. package/esm/middleware/helpers/for-tool.mjs +80 -0
  304. package/esm/middleware/helpers/for-tool.mjs.map +1 -0
  305. package/esm/middleware/helpers/index.d.mts +2 -0
  306. package/esm/middleware/index.d.mts +8 -0
  307. package/esm/middleware/index.mjs +10 -0
  308. package/esm/middleware/pipeline.d.mts +70 -0
  309. package/esm/middleware/pipeline.d.mts.map +1 -0
  310. package/esm/middleware/pipeline.mjs +100 -0
  311. package/esm/middleware/pipeline.mjs.map +1 -0
  312. package/esm/middleware/utils/extract-user-text.d.mts +33 -0
  313. package/esm/middleware/utils/extract-user-text.d.mts.map +1 -0
  314. package/esm/middleware/utils/extract-user-text.mjs +40 -0
  315. package/esm/middleware/utils/extract-user-text.mjs.map +1 -0
  316. package/esm/middleware/utils/index.d.mts +2 -0
  317. package/esm/middleware/utils/namespaced-state.d.mts +60 -0
  318. package/esm/middleware/utils/namespaced-state.d.mts.map +1 -0
  319. package/esm/middleware/utils/namespaced-state.mjs +60 -0
  320. package/esm/middleware/utils/namespaced-state.mjs.map +1 -0
  321. package/esm/mock/index.d.mts +4 -0
  322. package/esm/mock/index.mjs +5 -0
  323. package/esm/mock/mock-agent.d.mts +41 -0
  324. package/esm/mock/mock-agent.d.mts.map +1 -0
  325. package/esm/mock/mock-agent.mjs +39 -0
  326. package/esm/mock/mock-agent.mjs.map +1 -0
  327. package/esm/mock/mock-config.type.d.mts +31 -0
  328. package/esm/mock/mock-config.type.d.mts.map +1 -0
  329. package/esm/mock/mock-model.d.mts +94 -0
  330. package/esm/mock/mock-model.d.mts.map +1 -0
  331. package/esm/mock/mock-model.mjs +150 -0
  332. package/esm/mock/mock-model.mjs.map +1 -0
  333. package/esm/mock/mock-sdk.d.mts +25 -0
  334. package/esm/mock/mock-sdk.d.mts.map +1 -0
  335. package/esm/mock/mock-sdk.mjs +37 -0
  336. package/esm/mock/mock-sdk.mjs.map +1 -0
  337. package/esm/supervisor/as-tool.d.mts +45 -0
  338. package/esm/supervisor/as-tool.d.mts.map +1 -0
  339. package/esm/supervisor/as-tool.mjs +80 -0
  340. package/esm/supervisor/as-tool.mjs.map +1 -0
  341. package/esm/supervisor/cancellation.d.mts +12 -0
  342. package/esm/supervisor/cancellation.d.mts.map +1 -0
  343. package/esm/supervisor/cancellation.mjs +22 -0
  344. package/esm/supervisor/cancellation.mjs.map +1 -0
  345. package/esm/supervisor/decide.mjs +272 -0
  346. package/esm/supervisor/decide.mjs.map +1 -0
  347. package/esm/supervisor/emitter.d.mts +27 -0
  348. package/esm/supervisor/emitter.d.mts.map +1 -0
  349. package/esm/supervisor/emitter.mjs +47 -0
  350. package/esm/supervisor/emitter.mjs.map +1 -0
  351. package/esm/supervisor/entries.d.mts +141 -0
  352. package/esm/supervisor/entries.d.mts.map +1 -0
  353. package/esm/supervisor/entries.mjs +206 -0
  354. package/esm/supervisor/entries.mjs.map +1 -0
  355. package/esm/supervisor/execution.d.mts +637 -0
  356. package/esm/supervisor/execution.d.mts.map +1 -0
  357. package/esm/supervisor/execution.mjs +1868 -0
  358. package/esm/supervisor/execution.mjs.map +1 -0
  359. package/esm/supervisor/index.d.mts +11 -0
  360. package/esm/supervisor/index.mjs +12 -0
  361. package/esm/supervisor/router-prompt.d.mts +56 -0
  362. package/esm/supervisor/router-prompt.d.mts.map +1 -0
  363. package/esm/supervisor/router-prompt.mjs +52 -0
  364. package/esm/supervisor/router-prompt.mjs.map +1 -0
  365. package/esm/supervisor/signature.d.mts +28 -0
  366. package/esm/supervisor/signature.d.mts.map +1 -0
  367. package/esm/supervisor/signature.mjs +89 -0
  368. package/esm/supervisor/signature.mjs.map +1 -0
  369. package/esm/supervisor/snapshot.d.mts +54 -0
  370. package/esm/supervisor/snapshot.d.mts.map +1 -0
  371. package/esm/supervisor/snapshot.mjs +77 -0
  372. package/esm/supervisor/snapshot.mjs.map +1 -0
  373. package/esm/supervisor/supervisor-stream.d.mts +29 -0
  374. package/esm/supervisor/supervisor-stream.d.mts.map +1 -0
  375. package/esm/supervisor/supervisor-stream.mjs +89 -0
  376. package/esm/supervisor/supervisor-stream.mjs.map +1 -0
  377. package/esm/supervisor/supervisor.d.mts +27 -0
  378. package/esm/supervisor/supervisor.d.mts.map +1 -0
  379. package/esm/supervisor/supervisor.mjs +138 -0
  380. package/esm/supervisor/supervisor.mjs.map +1 -0
  381. package/esm/system-prompt/instruction.d.mts +52 -0
  382. package/esm/system-prompt/instruction.d.mts.map +1 -0
  383. package/esm/system-prompt/instruction.mjs +57 -0
  384. package/esm/system-prompt/instruction.mjs.map +1 -0
  385. package/esm/system-prompt/persona.d.mts +52 -0
  386. package/esm/system-prompt/persona.d.mts.map +1 -0
  387. package/esm/system-prompt/persona.mjs +57 -0
  388. package/esm/system-prompt/persona.mjs.map +1 -0
  389. package/esm/system-prompt/render-placeholders.d.mts +31 -0
  390. package/esm/system-prompt/render-placeholders.d.mts.map +1 -0
  391. package/esm/system-prompt/render-placeholders.mjs +58 -0
  392. package/esm/system-prompt/render-placeholders.mjs.map +1 -0
  393. package/esm/system-prompt/system-prompt.d.mts +117 -0
  394. package/esm/system-prompt/system-prompt.d.mts.map +1 -0
  395. package/esm/system-prompt/system-prompt.mjs +137 -0
  396. package/esm/system-prompt/system-prompt.mjs.map +1 -0
  397. package/esm/tool/index.d.mts +1 -0
  398. package/esm/tool/index.mjs +3 -0
  399. package/esm/tool/tool.d.mts +64 -0
  400. package/esm/tool/tool.d.mts.map +1 -0
  401. package/esm/tool/tool.mjs +184 -0
  402. package/esm/tool/tool.mjs.map +1 -0
  403. package/esm/utils/compute-cost.d.mts +58 -0
  404. package/esm/utils/compute-cost.d.mts.map +1 -0
  405. package/esm/utils/compute-cost.mjs +87 -0
  406. package/esm/utils/compute-cost.mjs.map +1 -0
  407. package/esm/utils/extract-json-payload.d.mts +33 -0
  408. package/esm/utils/extract-json-payload.d.mts.map +1 -0
  409. package/esm/utils/extract-json-payload.mjs +39 -0
  410. package/esm/utils/extract-json-payload.mjs.map +1 -0
  411. package/esm/utils/generate-run-id.d.mts +20 -0
  412. package/esm/utils/generate-run-id.d.mts.map +1 -0
  413. package/esm/utils/generate-run-id.mjs +23 -0
  414. package/esm/utils/generate-run-id.mjs.map +1 -0
  415. package/esm/utils/index.d.mts +9 -0
  416. package/esm/utils/index.mjs +11 -0
  417. package/esm/utils/json-schema.d.mts +57 -0
  418. package/esm/utils/json-schema.d.mts.map +1 -0
  419. package/esm/utils/json-schema.mjs +89 -0
  420. package/esm/utils/json-schema.mjs.map +1 -0
  421. package/esm/utils/prepare-attachment-part.d.mts +36 -0
  422. package/esm/utils/prepare-attachment-part.d.mts.map +1 -0
  423. package/esm/utils/prepare-attachment-part.mjs +140 -0
  424. package/esm/utils/prepare-attachment-part.mjs.map +1 -0
  425. package/esm/utils/resolve-attachment.d.mts +33 -0
  426. package/esm/utils/resolve-attachment.d.mts.map +1 -0
  427. package/esm/utils/resolve-attachment.mjs +73 -0
  428. package/esm/utils/resolve-attachment.mjs.map +1 -0
  429. package/esm/utils/safe-json-parse.d.mts +14 -0
  430. package/esm/utils/safe-json-parse.d.mts.map +1 -0
  431. package/esm/utils/safe-json-parse.mjs +22 -0
  432. package/esm/utils/safe-json-parse.mjs.map +1 -0
  433. package/esm/utils/stamp-report-lineage.d.mts +61 -0
  434. package/esm/utils/stamp-report-lineage.d.mts.map +1 -0
  435. package/esm/utils/stamp-report-lineage.mjs +47 -0
  436. package/esm/utils/stamp-report-lineage.mjs.map +1 -0
  437. package/esm/utils/token-count.d.mts +15 -0
  438. package/esm/utils/token-count.d.mts.map +1 -0
  439. package/esm/utils/token-count.mjs +18 -0
  440. package/esm/utils/token-count.mjs.map +1 -0
  441. package/esm/workflow/as-tool.mjs +55 -0
  442. package/esm/workflow/as-tool.mjs.map +1 -0
  443. package/esm/workflow/cancellation.mjs +44 -0
  444. package/esm/workflow/cancellation.mjs.map +1 -0
  445. package/esm/workflow/emitter.mjs +40 -0
  446. package/esm/workflow/emitter.mjs.map +1 -0
  447. package/esm/workflow/engine.mjs +362 -0
  448. package/esm/workflow/engine.mjs.map +1 -0
  449. package/esm/workflow/index.d.mts +3 -0
  450. package/esm/workflow/index.mjs +5 -0
  451. package/esm/workflow/retry.mjs +32 -0
  452. package/esm/workflow/retry.mjs.map +1 -0
  453. package/esm/workflow/router.mjs +56 -0
  454. package/esm/workflow/router.mjs.map +1 -0
  455. package/esm/workflow/run-scoped-emitter.mjs +32 -0
  456. package/esm/workflow/run-scoped-emitter.mjs.map +1 -0
  457. package/esm/workflow/signature.d.mts +7 -0
  458. package/esm/workflow/signature.d.mts.map +1 -0
  459. package/esm/workflow/signature.mjs +34 -0
  460. package/esm/workflow/signature.mjs.map +1 -0
  461. package/esm/workflow/snapshot.mjs +71 -0
  462. package/esm/workflow/snapshot.mjs.map +1 -0
  463. package/esm/workflow/state.mjs +37 -0
  464. package/esm/workflow/state.mjs.map +1 -0
  465. package/esm/workflow/step-runner.mjs +371 -0
  466. package/esm/workflow/step-runner.mjs.map +1 -0
  467. package/esm/workflow/step.d.mts +19 -0
  468. package/esm/workflow/step.d.mts.map +1 -0
  469. package/esm/workflow/step.mjs +37 -0
  470. package/esm/workflow/step.mjs.map +1 -0
  471. package/esm/workflow/workflow.d.mts +12 -0
  472. package/esm/workflow/workflow.d.mts.map +1 -0
  473. package/esm/workflow/workflow.mjs +116 -0
  474. package/esm/workflow/workflow.mjs.map +1 -0
  475. package/llms-full.txt +2293 -0
  476. package/llms.txt +20 -0
  477. package/package.json +37 -0
  478. package/skills/README.md +53 -0
  479. package/skills/ai-basics/SKILL.md +95 -0
  480. package/skills/attach-ai-middleware/SKILL.md +184 -0
  481. package/skills/define-ai-tool/SKILL.md +186 -0
  482. package/skills/embed-text/SKILL.md +105 -0
  483. package/skills/handle-ai-errors/SKILL.md +194 -0
  484. package/skills/log-ai-calls/SKILL.md +141 -0
  485. package/skills/persist-ai-data/SKILL.md +207 -0
  486. package/skills/pick-ai-provider/SKILL.md +164 -0
  487. package/skills/run-ai-agent/SKILL.md +267 -0
  488. package/skills/run-ai-workflow/SKILL.md +258 -0
  489. package/skills/run-supervisor/SKILL.md +309 -0
  490. package/skills/write-system-prompt/SKILL.md +129 -0
package/llms.txt ADDED
@@ -0,0 +1,20 @@
1
+ # Warlock AI
2
+
3
+ > Package: `@warlock.js/ai`
4
+
5
+ > Core @warlock.js AI framework — contracts, agent, workflow, supervisor
6
+
7
+ ## Skills
8
+
9
+ - [ai-basics](@warlock.js/ai/ai-basics/SKILL.md): Start with @warlock.js/ai — provider-agnostic core for agents / tools / workflows / supervisors. 4-primitive ladder (agent → workflow → supervisor → orchestrator v2). Every primitive returns {data, error, usage, report}. Triggers: `ai.agent`, `ai.tool`, `ai.workflow`, `ai.supervisor`, `ai.systemPrompt`, `ExecuteResult`, `BaseReport`, `AIError`; 'which AI primitive do I use', 'what is warlock ai', 'pick an AI skill'; typical import `import { ai } from "@warlock.js/ai"`. Skip: agent details — `@warlock.js/ai/run-ai-agent/SKILL.md`; competing libs `langchain`, `llamaindex`, `ai` (Vercel SDK); raw `openai` / `@anthropic-ai/sdk`.
10
+ - [attach-ai-middleware](@warlock.js/ai/attach-ai-middleware/SKILL.md): Wire agent middleware — ai.middleware.budget (token / USD caps), ai.middleware.guardrail (pre / post content checks), ai.middleware.semanticCache (exact + vector cache), plus authoring custom hooks (execute / trip / tool). Triggers: `ai.middleware.budget`, `ai.middleware.guardrail`, `ai.middleware.semanticCache`, `ai.middleware.compose`, `ai.middleware.forTool`, `AgentMiddleware`, `BudgetExceededError`, `GuardrailViolationError`; 'cap token cost', 'block pii in prompts', 'semantic cache before LLM', 'write custom hook'; typical import `import { ai } from "@warlock.js/ai"`. Skip: agent lifecycle — `@warlock.js/ai/run-ai-agent/SKILL.md`; cache drivers — `@warlock.js/ai/persist-ai-data/SKILL.md`; competing libs `langchain` callbacks.
11
+ - [define-ai-tool](@warlock.js/ai/define-ai-tool/SKILL.md): Define tools with ai.tool({...}) — typed validated async functions the model can call. Covers name / description / action / mode (feedback / silent) / input / execute, `ctx.artifacts` side-channel, `ToolExecutionError`. Triggers: `ai.tool`, `ToolContract`, `ToolContext`, `ToolCall`, `ToolExecutionError`, `artifactsSchema`, `mode: "silent"`, `workflow.asTool`; 'define a tool', 'wire tool into agent', 'tool input validation', 'side-channel artifacts'; typical import `import { ai } from "@warlock.js/ai"`. Skip: agent loop — `@warlock.js/ai/run-ai-agent/SKILL.md`; supervisor artifacts — `@warlock.js/ai/run-supervisor/SKILL.md`; competing libs `langchain` tools, raw `openai` function-calling.
12
+ - [embed-text](@warlock.js/ai/embed-text/SKILL.md): Text-to-vector via sdk.embedder({...}) — embed(string) for single, embedMany(string[]) for batch. Peer primitive on the SDK adapter, not wired into agents. Compose into RAG tools, workflow run steps, or ai.middleware.semanticCache. Triggers: `sdk.embedder`, `EmbedderContract`, `embedder.embed`, `embedder.embedMany`, `EmbeddingResult`, `EmbeddingBatchResult`, `dimensions`; 'embed text', 'build RAG tool', 'populate vector store', 'embedding batch'; typical import `import { OpenAISDK } from "@warlock.js/ai-openai"`. Skip: cache similarity — `@warlock.js/cache/use-cache-similarity/SKILL.md`; pgvector queries — `@warlock.js/cascade/search-by-vector/SKILL.md`; competing libs `langchain` embeddings, raw `openai.embeddings.create`.
13
+ - [handle-ai-errors](@warlock.js/ai/handle-ai-errors/SKILL.md): Typed AIError hierarchy with stable code strings + coarse category for retry-policy dispatch. execute() never throws — errors surface via result.error. Triggers: `AIError`, `ProviderRateLimitError`, `ProviderAuthError`, `ContextLengthExceededError`, `ContentFilterError`, `SchemaValidationError`, `ToolExecutionError`, `WorkflowDriftError`, `BudgetExceededError`, `GuardrailViolationError`, `error.code`, `error.category`; 'handle ai error', 'retry on rate limit', 'branch on error code', 'build fallback ladder'; typical import `import { AIError } from "@warlock.js/ai"`. Skip: log surfacing — `@warlock.js/ai/log-ai-calls/SKILL.md`; native `try / catch` on raw `openai`.
14
+ - [log-ai-calls](@warlock.js/ai/log-ai-calls/SKILL.md): Framework logging delegated to @warlock.js/logger — every primitive emits via the log singleton, configure channels / levels / redaction once at boot. Four-arg call convention (module, action, message, context). Triggers: `log.configure`, `log.setMinLevel`, `log.setChannels`, `ConsoleLog`, `FileLog`, `LogChannel`, `redact.paths`, `ai.agent.<name>` / `ai.workflow.<name>` / `ai.supervisor.<name>` modules; 'configure ai logging', 'mask prompts in logs', 'silence logs in tests', 'capture log entries'; typical import `import { log } from "@warlock.js/logger"`. Skip: error hierarchy — `@warlock.js/ai/handle-ai-errors/SKILL.md`; competing libs `pino`, `winston`, `console.log`.
15
+ - [persist-ai-data](@warlock.js/ai/persist-ai-data/SKILL.md): Persistence delegated to @warlock.js/cache — workflow + supervisor snapshot resume via snapshotStore, semantic cache via vector-capable CacheDriver, global default via ai.config({defaultStore}). Covers drift detection + three recovery paths. Triggers: `ai.config`, `defaultStore`, `snapshotStore`, `wf.resume`, `supervisor.resume`, `WorkflowSnapshot`, `SupervisorSnapshot`, `WorkflowDriftError`, `SupervisorDriftError`, `force: true`; 'resume a workflow run', 'configure snapshot store', 'handle signature drift', 'wire pg vector cache'; typical import `import { ai } from "@warlock.js/ai"`. Skip: cache driver catalog — `@warlock.js/cache/cache-basics/SKILL.md`; competing libs `temporal`, `inngest`.
16
+ - [pick-ai-provider](@warlock.js/ai/pick-ai-provider/SKILL.md): Choose an AI provider adapter — @warlock.js/ai-openai (shipped, also handles OpenRouter / Azure via baseURL), @warlock.js/ai-anthropic, @warlock.js/ai-bedrock, @warlock.js/ai-google, @warlock.js/ai-ollama. Triggers: `OpenAISDK`, `SDKAdapterContract`, `ModelContract`, `sdk.model`, `sdk.embedder`, `capabilities.vision`, `capabilities.structuredOutput`, `pricing`, `baseURL`, `provider: "openrouter"`; 'pick a provider', 'openai vs openrouter', 'does this model support vision', 'configure pricing'; typical import `import { OpenAISDK } from "@warlock.js/ai-openai"`. Skip: agent factory — `@warlock.js/ai/run-ai-agent/SKILL.md`; competing libs raw `openai`, `@anthropic-ai/sdk`, `@aws-sdk/client-bedrock-runtime`.
17
+ - [run-ai-agent](@warlock.js/ai/run-ai-agent/SKILL.md): Build agents with ai.agent({...}) — the single-LLM-turn primitive. Covers execute / stream, attachments, structured output, placeholders, events. Triggers: `ai.agent`, `agent.execute`, `agent.stream`, `AgentResult`, `AgentReport`, `streamingToolGuard`, `attachments`, `repair`, `maxTrips`, `sessionId`; 'run an agent', 'stream an agent response', 'structured output schema', 'pass image to agent', 'cancel an agent run'; typical import `import { ai } from "@warlock.js/ai"`. Skip: tool definition — `@warlock.js/ai/define-ai-tool/SKILL.md`; workflows — `@warlock.js/ai/run-ai-workflow/SKILL.md`; competing libs `langchain`, `ai` (Vercel), raw `openai`.
18
+ - [run-ai-workflow](@warlock.js/ai/run-ai-workflow/SKILL.md): Build durable resumable pipelines with ai.workflow({...}) + ai.step({...}) — lifecycle (skip / before / run|agent|parallel / output / after / nextStep), retry, parallel groups, snapshot resume. Triggers: `ai.workflow`, `ai.step`, `wf.execute`, `wf.resume`, `WorkflowContext`, `WorkflowResult`, `StepSnapshot`, `nextStep`, `onFailure`, `WorkflowDriftError`; 'build a workflow', 'define a step', 'resume after crash', 'parallel steps', 'retry with backoff'; typical import `import { ai } from "@warlock.js/ai"`. Skip: agent — `@warlock.js/ai/run-ai-agent/SKILL.md`; supervisor — `@warlock.js/ai/run-supervisor/SKILL.md`; competing libs `temporal`, `inngest`, `bullmq`.
19
+ - [run-supervisor](@warlock.js/ai/run-supervisor/SKILL.md): Multi-intent routing with ai.supervisor({...}) — classifier (iter-0 dispatch), router agent OR route callback, intents as agents / workflows / callbacks, fan-out, evaluate quality loop, ack receptionist. Triggers: `ai.supervisor`, `supervisor.execute`, `supervisor.resume`, `intents`, `router`, `route`, `classifier`, `evaluate`, `ack`, `artifactsSchema`, `END`, `ctx.intents.X.execute`; 'route one input across specialists', 'multi-intent dispatch', 'fan-out then evaluate', 'classifier then router'; typical import `import { ai } from "@warlock.js/ai"`. Skip: fixed pipelines — `@warlock.js/ai/run-ai-workflow/SKILL.md`; single agent — `@warlock.js/ai/run-ai-agent/SKILL.md`; competing libs `langgraph`, `crewai`.
20
+ - [write-system-prompt](@warlock.js/ai/write-system-prompt/SKILL.md): Compose system prompts via ai.systemPrompt() / ai.persona() / ai.instruction() — immutable builders with {{placeholder}} substitution. Triggers: `ai.systemPrompt`, `ai.persona`, `ai.instruction`, `SystemPromptBlockContract`, `PersonaContract`, `InstructionContract`, `placeholders`, `{{placeholder|default}}`; 'write a system prompt', 'compose persona + instructions', 'per-call prompt override', 'mustache placeholder'; typical import `import { ai } from "@warlock.js/ai"`. Skip: agent factory wiring — `@warlock.js/ai/run-ai-agent/SKILL.md`; competing libs `langchain` `PromptTemplate`, raw f-strings.
package/package.json ADDED
@@ -0,0 +1,37 @@
1
+ {
2
+ "name": "@warlock.js/ai",
3
+ "description": "Core @warlock.js AI framework — contracts, agent, workflow, supervisor",
4
+ "keywords": [
5
+ "warlock",
6
+ "ai"
7
+ ],
8
+ "author": "Hasan Zohdy",
9
+ "license": "MIT",
10
+ "repository": {
11
+ "type": "git",
12
+ "url": "https://github.com/warlockjs/ai"
13
+ },
14
+ "dependencies": {
15
+ "@standard-schema/spec": "^1.0.0"
16
+ },
17
+ "peerDependencies": {
18
+ "@warlock.js/cache": "*",
19
+ "@warlock.js/logger": "*"
20
+ },
21
+ "version": "4.1.1",
22
+ "main": "./cjs/index.cjs",
23
+ "module": "./esm/index.mjs",
24
+ "types": "./esm/index.d.mts",
25
+ "exports": {
26
+ ".": {
27
+ "import": {
28
+ "types": "./esm/index.d.mts",
29
+ "default": "./esm/index.mjs"
30
+ },
31
+ "require": {
32
+ "types": "./esm/index.d.mts",
33
+ "default": "./cjs/index.cjs"
34
+ }
35
+ }
36
+ }
37
+ }
@@ -0,0 +1,53 @@
1
+ # `@warlock.js/ai` — skills index
2
+
3
+ Per-task skills. All cross-references use the form `@warlock.js/<pkg>/<skill>/SKILL.md`.
4
+
5
+ ## Skills
6
+
7
+ ### [`ai-basics/`](./ai-basics/SKILL.md)
8
+
9
+ Start with @warlock.js/ai — provider-agnostic core for agents / tools / workflows / supervisors. 4-primitive ladder (agent → workflow → supervisor → orchestrator v2). Every primitive returns {data, error, usage, report}. Persistence + logging delegated. Load when importing @warlock.js/ai, picking a primitive, or choosing which AI skill to load.
10
+
11
+ ### [`attach-ai-middleware/`](./attach-ai-middleware/SKILL.md)
12
+
13
+ Wire agent middleware — ai.middleware.budget (token / USD caps), ai.middleware.guardrail (pre / post content checks), ai.middleware.semanticCache (exact + vector cache via @warlock.js/cache), plus authoring custom hooks (execute / trip / tool). Load when capping cost / tokens, gating input or output, hitting semantic cache before the LLM, or writing custom hooks.
14
+
15
+ ### [`define-ai-tool/`](./define-ai-tool/SKILL.md)
16
+
17
+ Define tools with ai.tool({...}) — typed validated async functions the model can call. Covers name / description / action / mode (feedback / silent) / input / execute, ctx.artifacts side-channel, ToolExecutionError. Load when wiring tools into an agent, authoring ai.tool, inspecting result.report.toolCalls, or debugging a ToolExecutionError.
18
+
19
+ ### [`embed-text/`](./embed-text/SKILL.md)
20
+
21
+ Text-to-vector via sdk.embedder({...}) — embed(string) for single, embedMany(string[]) for batch. Peer primitive on the SDK adapter, not wired into agents. Compose into RAG tools, workflow run steps, or ai.middleware.semanticCache. Load when calling sdk.embedder, building RAG tools, or populating a vector store.
22
+
23
+ ### [`handle-ai-errors/`](./handle-ai-errors/SKILL.md)
24
+
25
+ Typed AIError hierarchy with stable code strings + coarse category for retry-policy dispatch. execute() never throws — errors surface via result.error. Load when inspecting result.error, branching on error.code / error.category, designing retry / fallback logic, or wrapping framework errors in HTTP errors.
26
+
27
+ ### [`log-ai-calls/`](./log-ai-calls/SKILL.md)
28
+
29
+ Framework logging delegated to @warlock.js/logger — every primitive emits via the log singleton, configure channels / levels / redaction once at boot. Four-arg call convention (module, action, message, context). Load when configuring AI logging, masking prompts / API keys / PII, picking which events surface, or filtering by module / action.
30
+
31
+ ### [`persist-ai-data/`](./persist-ai-data/SKILL.md)
32
+
33
+ Persistence delegated to @warlock.js/cache — workflow + supervisor snapshot resume via snapshotStore, semantic cache via vector-capable CacheDriver, global default via ai.config({defaultStore}). Covers drift detection + three recovery paths. Load when configuring snapshotStore, calling resume(runId), or handling WorkflowDriftError / SupervisorDriftError.
34
+
35
+ ### [`pick-ai-provider/`](./pick-ai-provider/SKILL.md)
36
+
37
+ Choose an AI provider adapter — @warlock.js/ai-openai (shipped, also handles OpenRouter / Azure via baseURL), @warlock.js/ai-anthropic, @warlock.js/ai-bedrock, @warlock.js/ai-google, @warlock.js/ai-ollama. Load when picking a provider, deciding between OpenAI direct vs OpenRouter, or understanding which adapter supports a feature (vision / structured / embeddings).
38
+
39
+ ### [`run-ai-agent/`](./run-ai-agent/SKILL.md)
40
+
41
+ Build agents with ai.agent({...}) — the single-LLM-turn primitive. Covers execute / stream, attachments, structured output, placeholders, events, AgentResult envelope, streamingToolGuard. Load when calling ai.agent(...), reading AgentResult, wiring options.output / attachments / repair, or streaming.
42
+
43
+ ### [`run-ai-workflow/`](./run-ai-workflow/SKILL.md)
44
+
45
+ Build durable resumable pipelines with ai.workflow({...}) + ai.step({...}) — lifecycle (skip / before / run|agent|parallel / output / after / nextStep), routing on success / failure, retry with backoff, parallel groups, cancel via AbortSignal, snapshot resume. Load when authoring ai.workflow, defining steps, handling WorkflowDriftError, or resuming a run.
46
+
47
+ ### [`run-supervisor/`](./run-supervisor/SKILL.md)
48
+
49
+ Multi-intent routing with ai.supervisor({...}) — classifier (iter-0 dispatch), router agent OR route callback (iter 1+), intents as agents / workflows / callbacks, fan-out, evaluate quality loop, ack receptionist, ctx.intents.X.execute composition. Load when routing one user input across a fixed roster of specialists.
50
+
51
+ ### [`write-system-prompt/`](./write-system-prompt/SKILL.md)
52
+
53
+ Compose system prompts via ai.systemPrompt() / ai.persona() / ai.instruction() — immutable builders with {{placeholder}} substitution. Load when building or chaining system prompts, mixing persona + instruction blocks, using {{placeholder}}, or doing per-call override via agent.execute(input, {systemPrompt}).
@@ -0,0 +1,95 @@
1
+ ---
2
+ name: ai-basics
3
+ description: 'Start with @warlock.js/ai — provider-agnostic core for agents / tools / workflows / supervisors. 4-primitive ladder (agent → workflow → supervisor → orchestrator v2). Every primitive returns {data, error, usage, report}. Triggers: `ai.agent`, `ai.tool`, `ai.workflow`, `ai.supervisor`, `ai.systemPrompt`, `ExecuteResult`, `BaseReport`, `AIError`; ''which AI primitive do I use'', ''what is warlock ai'', ''pick an AI skill''; typical import `import { ai } from "@warlock.js/ai"`. Skip: agent details — `@warlock.js/ai/run-ai-agent/SKILL.md`; competing libs `langchain`, `llamaindex`, `ai` (Vercel SDK); raw `openai` / `@anthropic-ai/sdk`.'
4
+ ---
5
+
6
+ # AI foundations
7
+
8
+ Provider-agnostic core for building AI primitives in TypeScript. Adapters live in sibling packages — all five first-party adapters ship today: `@warlock.js/ai-openai`, `-anthropic`, `-bedrock`, `-google`, `-ollama`.
9
+
10
+ > This skill is the AI **map** — read it first, then load the specific skill for the task.
11
+
12
+ ## The 4-primitive ladder
13
+
14
+ ```
15
+ ai.agent() → single task, stateless [shipped]
16
+ ai.workflow() → static predefined steps, resumable [shipped]
17
+ ai.supervisor() → multi-agent dynamic routing, resumable [shipped]
18
+ ai.orchestrator() → stateful — owns session/history/ctx (v2)
19
+ ```
20
+
21
+ Each primitive is an escape hatch to the next level of complexity. Users start low, graduate upward only when needed. Every primitive returns the same result envelope — canonical destructure `{ data, error, usage, report }` (the shared `BaseResult` guarantees `usage` + optional `error`; each primitive adds `data` + `report`). Workflows and supervisors expose `.asTool()` so an agent can call them inside its tool loop; compose freely.
22
+
23
+ ## Foundations
24
+
25
+ 1. **Public API is functional factories.** Use `ai.agent({...})`, `ai.tool({...})`, `ai.workflow({...})`, `ai.step({...})`, `ai.supervisor({...})`, `ai.systemPrompt()`, `ai.persona()`, `ai.instruction()`. Never `new Agent()`.
26
+ 2. **Adapter entry points are classes.** `new OpenAISDK({ apiKey })` from [`@warlock.js/ai-openai/setup-openai/SKILL.md`](@warlock.js/ai-openai/setup-openai/SKILL.md).
27
+ 3. **Schemas everywhere are `StandardSchemaV1<T>`.** Recommended: [`@warlock.js/seal`](@warlock.js/seal/seal-basics/SKILL.md) — `v.object({...})`. Zod, Valibot, hand-rolled all interop.
28
+ 4. **`execute()` never throws.** Errors funnel into `result.error` as a typed `AIError` subclass. Same for `stream.result`, `workflow.execute()` / `resume()`, `supervisor.execute()` / `resume()`. See [`@warlock.js/ai/handle-ai-errors/SKILL.md`](@warlock.js/ai/handle-ai-errors/SKILL.md).
29
+ 5. **Each `execute()` call is isolated.** Fresh internal execution instance per call.
30
+ 6. **Every error is an `AIError`.** Plain `Error` never leaks. Branch on `error.code` (stable string), `error.category` (coarse), or `instanceof`.
31
+ 7. **Result shape is uniform.** `{ data, error, usage, report }` across every primitive. `report` is a recursive `BaseReport` tree.
32
+ 8. **Persistence is delegated** to `@warlock.js/cache`. See [`@warlock.js/ai/persist-ai-data/SKILL.md`](@warlock.js/ai/persist-ai-data/SKILL.md).
33
+ 9. **Logging is delegated** to `@warlock.js/logger`. See [`@warlock.js/ai/log-ai-calls/SKILL.md`](@warlock.js/ai/log-ai-calls/SKILL.md).
34
+ 10. **`name` on agents is optional.** Anonymous agents get a deterministic `anon_<provider>_<model>` fingerprint.
35
+ 11. **Every report carries lineage** — `rootRunId` + `parentRunId` + `reportSchemaVersion: 1`.
36
+ 12. **`version` is dev-curated, `sessionId` is caller-supplied** — both propagate through nested reports.
37
+ 13. **Cost is computed at emit time as a per-channel breakdown.** Set `pricing` on the model adapter; `Usage.cost` carries `{ input, output, cachedInput?, cachedOutput? }` per trip, rolled up bottom-up.
38
+ 14. **Every `AIError` carries a coarse `category`** for retry-policy dispatch (`rate-limit`, `auth`, `content-filter`, `schema`, etc.).
39
+
40
+ ## 30-second example
41
+
42
+ ```ts
43
+ import { ai } from "@warlock.js/ai";
44
+ import { OpenAISDK } from "@warlock.js/ai-openai";
45
+
46
+ const openai = new OpenAISDK({ apiKey: process.env.OPENAI_API_KEY! });
47
+ const myAgent = ai.agent({ model: openai.model({ name: "gpt-4o-mini" }) });
48
+
49
+ const { data, text, report, usage, error } = await myAgent.execute("Hello");
50
+
51
+ if (error) /* typed AIError */ ;
52
+ console.log(text, usage.total, report.duration);
53
+ ```
54
+
55
+ ## Pick a skill
56
+
57
+ | If the task is about… | Load |
58
+ | --- | --- |
59
+ | `ai.agent({...})` — single-LLM-turn primitive, structured output, streaming, attachments | [`@warlock.js/ai/run-ai-agent/SKILL.md`](@warlock.js/ai/run-ai-agent/SKILL.md) |
60
+ | `ai.tool({...})` — typed validated functions the model can call | [`@warlock.js/ai/define-ai-tool/SKILL.md`](@warlock.js/ai/define-ai-tool/SKILL.md) |
61
+ | `ai.systemPrompt()` / `ai.persona()` / `ai.instruction()` — composable prompts with placeholders | [`@warlock.js/ai/write-system-prompt/SKILL.md`](@warlock.js/ai/write-system-prompt/SKILL.md) |
62
+ | `ai.workflow({...})` — durable resumable pipelines with steps, routing, retry | [`@warlock.js/ai/run-ai-workflow/SKILL.md`](@warlock.js/ai/run-ai-workflow/SKILL.md) |
63
+ | `ai.supervisor({...})` — multi-intent routing, fan-out, evaluate loops | [`@warlock.js/ai/run-supervisor/SKILL.md`](@warlock.js/ai/run-supervisor/SKILL.md) |
64
+ | `sdk.embedder({...})` — text-to-vector for RAG tools, vector ingest | [`@warlock.js/ai/embed-text/SKILL.md`](@warlock.js/ai/embed-text/SKILL.md) |
65
+ | Agent middleware — `budget` / `guardrail` / `semanticCache` + custom hooks | [`@warlock.js/ai/attach-ai-middleware/SKILL.md`](@warlock.js/ai/attach-ai-middleware/SKILL.md) |
66
+ | Snapshot resume + semantic cache via `@warlock.js/cache` | [`@warlock.js/ai/persist-ai-data/SKILL.md`](@warlock.js/ai/persist-ai-data/SKILL.md) |
67
+ | Configuring framework logging | [`@warlock.js/ai/log-ai-calls/SKILL.md`](@warlock.js/ai/log-ai-calls/SKILL.md) |
68
+ | `AIError` hierarchy, `error.code` / `error.category`, retry patterns | [`@warlock.js/ai/handle-ai-errors/SKILL.md`](@warlock.js/ai/handle-ai-errors/SKILL.md) |
69
+ | Choosing a provider adapter (OpenAI / OpenRouter / Anthropic / Bedrock / Ollama) | [`@warlock.js/ai/pick-ai-provider/SKILL.md`](@warlock.js/ai/pick-ai-provider/SKILL.md) |
70
+
71
+ ## Package layout
72
+
73
+ ```
74
+ @warlock.js/ai — agent, tool, workflow, supervisor, system-prompt, errors, middleware
75
+ @warlock.js/ai-openai — OpenAI SDK adapter (model + embedder); also OpenRouter / Azure via baseURL
76
+ @warlock.js/ai-anthropic — Anthropic / Claude adapter (Messages API)
77
+ @warlock.js/ai-bedrock — AWS Bedrock adapter (Converse API + Titan embeddings)
78
+ @warlock.js/ai-google — Google / Gemini adapter (@google/genai + batch embeddings)
79
+ @warlock.js/ai-ollama — Ollama adapter for local models
80
+ ```
81
+
82
+ Runtime deps: `@warlock.js/cache` (persistence), `@warlock.js/logger` (logging), `@warlock.js/seal` (recommended schema lib).
83
+
84
+ ## When NOT to use this skill
85
+
86
+ - Code importing `openai` / `@anthropic-ai/sdk` directly without going through `@warlock.js/ai` — those are raw provider SDKs.
87
+ - Generic JS/TS questions unrelated to agent / tool / workflow / supervisor wiring.
88
+
89
+ ## Design references
90
+
91
+ - `domains/ai/design/decisions.md` — locked architectural decisions with rationale
92
+ - `domains/ai/design/workflow.md` — workflow spec
93
+ - `domains/ai/design/supervisor.md` — supervisor spec
94
+ - `domains/ai/design/execution-result.md` — unified `ExecuteResult` + recursive `BaseReport` tree
95
+ - `domains/ai/conventions/errors.md` — framework-vs-consumer-app error split
@@ -0,0 +1,184 @@
1
+ ---
2
+ name: attach-ai-middleware
3
+ description: 'Wire agent middleware — ai.middleware.budget (token / USD caps), ai.middleware.guardrail (pre / post content checks), ai.middleware.semanticCache (exact + vector cache), plus authoring custom hooks (execute / trip / tool). Triggers: `ai.middleware.budget`, `ai.middleware.guardrail`, `ai.middleware.semanticCache`, `ai.middleware.compose`, `ai.middleware.forTool`, `AgentMiddleware`, `BudgetExceededError`, `GuardrailViolationError`; ''cap token cost'', ''block pii in prompts'', ''semantic cache before LLM'', ''write custom hook''; typical import `import { ai } from "@warlock.js/ai"`. Skip: agent lifecycle — `@warlock.js/ai/run-ai-agent/SKILL.md`; cache drivers — `@warlock.js/ai/persist-ai-data/SKILL.md`; competing libs `langchain` callbacks.'
4
+ ---
5
+
6
+ # Middleware — agent-level pipeline
7
+
8
+ Cross-cutting concerns wrapped around an agent run at three granularities: `execute`, `trip`, `tool`. One middleware = one object. Ships with `budget`, `guardrail`, and `semanticCache` built-ins.
9
+
10
+ ## Install order at a glance
11
+
12
+ ```ts
13
+ import { ai } from "@warlock.js/ai";
14
+ import { OpenAISDK } from "@warlock.js/ai-openai";
15
+ import { cache } from "@warlock.js/cache";
16
+
17
+ const openai = new OpenAISDK({ apiKey: process.env.OPENAI_API_KEY! });
18
+
19
+ ai.config({ defaultStore: cache.driver("redis", { client: redisClient }) });
20
+
21
+ const myAgent = ai.agent({
22
+ model: openai.model({ name: "gpt-4o" }),
23
+ middleware: [
24
+ ai.middleware.semanticCache({
25
+ embedder: openai.embedder({ name: "text-embedding-3-small" }),
26
+ threshold: 0.95,
27
+ }),
28
+ ai.middleware.budget({ maxTokens: 50_000 }),
29
+ ai.middleware.guardrail({
30
+ inputCheck: async (text) =>
31
+ text.match(/\bSSN\b/) ? { ok: false, reason: "pii" } : { ok: true },
32
+ }),
33
+ ],
34
+ });
35
+ ```
36
+
37
+ **Canonical order: `[cache, budget, guardrail, observability]`** — see "Ordering invariants" below.
38
+
39
+ ## `ai.middleware.budget(options)`
40
+
41
+ Cumulative token / USD cap across all trips of one execution.
42
+
43
+ ```ts
44
+ ai.middleware.budget({
45
+ maxTokens: 50_000,
46
+ maxCostUSD: 0.5,
47
+ pricing: { "gpt-4o": { inputPer1K: 0.005, outputPer1K: 0.015 } },
48
+ onExceeded: "abort", // or "warn"
49
+ });
50
+ ```
51
+
52
+ Breach → `BudgetExceededError` on `result.error`. Inspect `error.unit` (`"tokens" | "usd"`), `error.limit`, `error.actual`. Warn mode logs and continues — useful for measuring before enforcing.
53
+
54
+ USD only fires when both `maxCostUSD` AND a matching `pricing[modelName]` entry exist.
55
+
56
+ ## `ai.middleware.guardrail(options)`
57
+
58
+ Pre / post content checks.
59
+
60
+ ```ts
61
+ ai.middleware.guardrail({
62
+ inputCheck: async (text, ctx) =>
63
+ text.includes("forbidden") ? { ok: false, reason: "policy-1" } : { ok: true },
64
+ outputCheck: async (text) =>
65
+ text.length > 10_000 ? { ok: false, reason: "too-long" } : { ok: true },
66
+ name: "pii-guardrail",
67
+ });
68
+ ```
69
+
70
+ Rejection → `GuardrailViolationError` with `phase: "input" | "output"` and the configured `reason`. Output checks fire BEFORE tool dispatch — a rejected response means the tools it requested are never invoked.
71
+
72
+ Checks run on every trip (including tool follow-ups and repair attempts). Gate only the first trip via `ctx.tripIndex === 0`.
73
+
74
+ ## `ai.middleware.semanticCache(options)`
75
+
76
+ Two-tier cache — exact-match key first, vector similarity second. Delegates to any vector-capable `CacheDriver`.
77
+
78
+ ```ts
79
+ ai.middleware.semanticCache({
80
+ embedder: openai.embedder({ name: "text-embedding-3-small" }),
81
+ // store optional — falls back to ai.config({ defaultStore })
82
+ store: cache.driver("pg", {
83
+ client: pgPool,
84
+ vector: { dimensions: 1536, index: "hnsw" },
85
+ }),
86
+ threshold: 0.95,
87
+ ttlMs: 60 * 60 * 1000,
88
+ namespace: "support-faq",
89
+ });
90
+ ```
91
+
92
+ **Driver requirements.** Must support `similar()` — `pg` (with `vector` config), `redis` (with RediSearch), or memory drivers for dev. Without similarity → `CacheUnsupportedError` at first vector op.
93
+
94
+ **How it works.**
95
+ - **Exact-match** — FNV hash over the message list. `store.get(hash)` returns an instant hit.
96
+ - **Vector-match** — embeds the prompt, calls `store.similar(vector, { topK: 1, threshold })`. Driver uses its native ANN index.
97
+ - **Hits** return a synthetic `ModelResponse` with `usage: { input: 0, output: 0, total: 0 }`.
98
+ - **Writes** happen at `trip.after` on miss.
99
+ - **Trip-zero only** — only first-trip responses are cached. Tool-using loops never serve cached tool-call responses (would infinite-loop).
100
+ - **Never use memory drivers in production** — linear scan per query.
101
+
102
+ ## Writing your own middleware
103
+
104
+ One object. Any subset of three hook maps.
105
+
106
+ ```ts
107
+ import type { AgentMiddleware } from "@warlock.js/ai";
108
+
109
+ const latencyLogger: AgentMiddleware = {
110
+ name: "latency-logger",
111
+ execute: {
112
+ before(ctx) {
113
+ ctx.state.set("latency.start", performance.now());
114
+ },
115
+ after(ctx, result) {
116
+ const start = ctx.state.get("latency.start") as number;
117
+ console.log(`agent ${ctx.agent.name} finished in ${performance.now() - start}ms`);
118
+ },
119
+ },
120
+ trip: {
121
+ before(ctx) {
122
+ ctx.state.set(`latency.trip.${ctx.tripIndex}.start`, performance.now());
123
+ },
124
+ after(ctx) {
125
+ const start = ctx.state.get(`latency.trip.${ctx.tripIndex}.start`) as number;
126
+ console.log(` trip ${ctx.tripIndex}: ${performance.now() - start}ms`);
127
+ },
128
+ },
129
+ };
130
+ ```
131
+
132
+ ### Rules
133
+
134
+ - **Never close over mutable state.** Use `ctx.state` — fresh per `execute()` call.
135
+ - **Abort with a typed `AIError` subclass.** Never `throw new Error(...)`.
136
+ - **Short-circuit by returning from `before`.** Return the level's result type — the pipeline skips the real work and outer `after` hooks still run on your synthetic value.
137
+ - **`onError` is opt-in recovery.** Return a value to recover; return `void` to let the error propagate.
138
+ - **`log: false`** suppresses framework debug emission for that middleware (the middleware itself still runs).
139
+
140
+ ## Ordering invariants — read before shipping
141
+
142
+ 1. **Cache MUST be outermost when guardrails are present.** Guardrail `trip.after` throws to reject bad output — but `after` hooks run bottom-up. If guardrail is outside the cache, rejection fires AFTER the cache has written the bad response. Canonical order `[cache, budget, guardrail]` keeps rejected outputs out of the cache.
143
+ 2. **Budget before guardrails.** Guardrails may call classifiers with their own token costs.
144
+ 3. **Observability last.** It should see the final decision every other middleware made.
145
+
146
+ ## Helpers
147
+
148
+ ### `ai.middleware.compose(...sources)`
149
+
150
+ Flatten multiple sources into one ordered array. No sorting, no dedup.
151
+
152
+ ```ts
153
+ ai.agent({
154
+ model,
155
+ middleware: ai.middleware.compose(standardStack, toolRules, auditMiddleware),
156
+ });
157
+ ```
158
+
159
+ ### `ai.middleware.forTool(name | names, middleware)`
160
+
161
+ Scope `tool.*` hooks to specific tool names. `execute` and `trip` hooks pass through.
162
+
163
+ ```ts
164
+ const scoped = ai.middleware.forTool(["paid_api", "expensive_db"], toolRateLimit({ maxCalls: 5 }));
165
+ ```
166
+
167
+ ## Caveats
168
+
169
+ - **`tool.onError` is almost-never-useful.** `ToolContract.invoke()` never throws — errors are captured into `result.error`. `tool.onError` only fires when another middleware's `tool.before`/`tool.after` itself throws. For "the tool itself failed," branch on `result.error` in a `tool.after`.
170
+ - **Middleware does NOT observe unregistered tool calls.** When the model asks for a tool the agent wasn't configured with, the pipeline is bypassed and a failed `ToolCall` is recorded directly.
171
+ - **`name` must be unique** across an agent's middleware array.
172
+ - **Middleware state does NOT cross `agent.execute()` boundaries.** One execute → one fresh `ctx.state`.
173
+
174
+ ## Workflow + middleware — what works today (v1)
175
+
176
+ - Inside a workflow step with `agent: myAgent` — the agent's own middleware fires normally.
177
+ - `workflow.asTool()` called from an agent — the calling agent's `tool`-level middleware wraps the workflow.
178
+ - Step-level / workflow-level / supervisor-level middleware does NOT exist yet.
179
+
180
+ ## See also
181
+
182
+ - [`@warlock.js/ai/run-ai-agent/SKILL.md`](@warlock.js/ai/run-ai-agent/SKILL.md) — agent lifecycle the middleware wraps
183
+ - [`@warlock.js/ai/persist-ai-data/SKILL.md`](@warlock.js/ai/persist-ai-data/SKILL.md) — `defaultStore` for semantic cache
184
+ - [`@warlock.js/ai/handle-ai-errors/SKILL.md`](@warlock.js/ai/handle-ai-errors/SKILL.md) — `BudgetExceededError` / `GuardrailViolationError`
@@ -0,0 +1,186 @@
1
+ ---
2
+ name: define-ai-tool
3
+ description: 'Define tools with ai.tool({...}) — typed validated async functions the model can call. Covers name / description / action / mode (feedback / silent) / input / execute, `ctx.artifacts` side-channel, `ToolExecutionError`. Triggers: `ai.tool`, `ToolContract`, `ToolContext`, `ToolCall`, `ToolExecutionError`, `artifactsSchema`, `mode: "silent"`, `workflow.asTool`; ''define a tool'', ''wire tool into agent'', ''tool input validation'', ''side-channel artifacts''; typical import `import { ai } from "@warlock.js/ai"`. Skip: agent loop — `@warlock.js/ai/run-ai-agent/SKILL.md`; supervisor artifacts — `@warlock.js/ai/run-supervisor/SKILL.md`; competing libs `langchain` tools, raw `openai` function-calling.'
4
+ ---
5
+
6
+ # `ai.tool()` — typed tool factory
7
+
8
+ Tools are async functions the model can call by name during a trip loop. Define one with `ai.tool()`, pass it in `agent({ tools: [...] })`, and the agent handles dispatch, input validation, and error surfacing automatically.
9
+
10
+ ## Factory shape
11
+
12
+ ```ts
13
+ ai.tool({
14
+ name: string, // stable identifier
15
+ description: string, // sent to the model
16
+ version?: string, // mirrored onto tool reports
17
+ action?: string | ((input: TInput) => string), // UI label for streaming UX
18
+ mode?: "feedback" | "silent", // result feedback control
19
+ input: StandardSchemaV1<TInput>, // validated before execute
20
+ execute: (input: TInput, ctx?: ToolContext) => Promise<unknown>,
21
+ });
22
+ ```
23
+
24
+ Returns a `ToolContract<TInput, TOutput>`. One tool can be attached to many agents.
25
+
26
+ ## `description` vs `action`
27
+
28
+ Two roles, two fields:
29
+
30
+ - **`description`** — what the LLM reads when deciding whether to call this tool.
31
+ - **`action`** — present-progressive UI string surfaced to humans on `agent.tool.calling` / `agent.tool.called` events.
32
+
33
+ ```ts
34
+ ai.tool({
35
+ name: "search_catalog",
36
+ description: "Search the product catalog. Returns matching products with SKU, name, price.",
37
+ action: ({ query }) => `Searching the catalog for "${query}"`,
38
+ input: v.object({ query: v.string() }),
39
+ execute: async ({ query }) => searchProducts(query),
40
+ });
41
+ ```
42
+
43
+ Two forms supported: static string or function. Function form runs after input validation; throws are swallowed (UI strings aren't worth aborting LLM dispatch over).
44
+
45
+ ## Schema via Standard Schema V1
46
+
47
+ Input is typed as `StandardSchemaV1<T>`. Recommended: `@warlock.js/seal`. Zod / Valibot / hand-rolled all interop.
48
+
49
+ ```ts
50
+ import { v } from "@warlock.js/seal";
51
+
52
+ const searchTool = ai.tool({
53
+ name: "search",
54
+ description: "Search the docs index",
55
+ input: v.object({
56
+ query: v.string(),
57
+ limit: v.number().optional(),
58
+ }),
59
+ execute: async ({ query, limit }) => fetchDocs(query, limit ?? 10),
60
+ });
61
+ ```
62
+
63
+ ## Input validation is automatic
64
+
65
+ The agent calls `input["~standard"].validate(rawArgs)` before invoking `execute`. Validation failures **do not throw** — the failure is recorded on the trip's `ToolCall.error` and fed back to the model on the next trip as a tool error message. The model gets a chance to correct and retry within the bounded `maxTrips` loop.
66
+
67
+ ## What gets returned to the model
68
+
69
+ Whatever your `execute` resolves with is `JSON.stringify`'d and sent back as the next trip's `tool` message. Strings pass through unchanged. Throw (or return a rejected promise) to signal failure — the agent records the error on `ToolCall.error` and tells the model.
70
+
71
+ ## `mode` — feedback vs silent
72
+
73
+ Default `"feedback"`.
74
+
75
+ - **`mode: "feedback"`** (default) — standard round-trip. Result feeds back into next trip; the model reads it and replies. Use for tools whose output the model needs to narrate: `search_catalog`, `search_knowledge_base`, `ask_questions`.
76
+ - **`mode: "silent"`** — fire-and-forget. Result NOT fed back to the model. When EVERY tool call in a single generation is silent, the agent loop terminates after dispatch. Use for pure side-effect tools: `update_state`, `set_locale`, telemetry pings.
77
+
78
+ ```ts
79
+ ai.tool({
80
+ name: "update_state",
81
+ description: "Persist customer slot-fill across turns.",
82
+ mode: "silent",
83
+ input: v.object({ preferences: v.array(v.string()).optional() }),
84
+ execute: async (patch, ctx) => {
85
+ ctx.artifacts.stateUpdate = patch;
86
+ return { ok: true }; // model never sees this
87
+ },
88
+ });
89
+ ```
90
+
91
+ **All-silent rule.** The loop terminates only when EVERY tool call this trip is silent. Silent + feedback in the same generation → loop continues (the feedback tool still round-trips, the silent one piggybacks).
92
+
93
+ **Constraints for silent tools.** MUST be cheap + fast (HTTP request still open until dispatch resolves), should be idempotent (no surface to communicate failure to the model), side-effect-only.
94
+
95
+ ## Tool context — `ctx.artifacts` side-channel
96
+
97
+ `execute` accepts an optional **second argument** — a `ToolContext` with a mutable `artifacts` bag and the dispatch's `signal`. Use it to capture system-only data (renderable blocks, citations, files, telemetry, soft signals) that the LLM should NOT see.
98
+
99
+ ```ts
100
+ ai.tool({
101
+ name: "search_catalog",
102
+ input: v.object({ query: v.string() }),
103
+ execute: async (input, ctx) => {
104
+ const items = await searchItems(input.query);
105
+
106
+ // Side-channel — never reaches the LLM.
107
+ ctx.artifacts.blocks ??= [];
108
+ ctx.artifacts.blocks.push({ type: "items", itemIds: items.map(i => i.id) });
109
+
110
+ // LLM-visible — what the agent reasons over.
111
+ return { total: items.length };
112
+ },
113
+ });
114
+ ```
115
+
116
+ Under a supervisor: bag starts empty per iteration, accumulates writes from all tool calls, merges into state at iteration end (auto-spread by default; `finalizeArtifacts` for concat / dedupe). See [`@warlock.js/ai/run-supervisor/SKILL.md`](@warlock.js/ai/run-supervisor/SKILL.md).
117
+
118
+ Standalone (no supervisor): framework supplies `{ artifacts: {} }`. Mutations are harmless no-ops.
119
+
120
+ ## Type contract for artifacts
121
+
122
+ The supervisor declares an `artifactsSchema`; tools registered to it inherit typed `ctx.artifacts.*`. Standalone tools fall back to `Record<string, unknown>`.
123
+
124
+ ```ts
125
+ ai.supervisor({
126
+ artifactsSchema: v.object({
127
+ blocks: v.array(blockSchema).optional(),
128
+ citations: v.array(citationSchema).optional(),
129
+ }),
130
+ // tools see ctx.artifacts typed as { blocks?, citations? }
131
+ });
132
+ ```
133
+
134
+ ## Error categorization
135
+
136
+ `invoke()` never throws — failures surface on the returned `error` field, and the agent records them on the dispatch's `ToolCall.error`. The error class depends on what failed:
137
+
138
+ - **Input schema rejected the model's args** → `SchemaValidationError` (`code: "SCHEMA_VALIDATION_FAILED"`), `issues` preserved. NOT wrapped in `ToolExecutionError`.
139
+ - **Schema's own `validate()` threw** → `SchemaValidationError` wrapping the cause.
140
+ - **Your `execute()` threw** → `ToolExecutionError` (`code: "TOOL_EXEC_FAILED"`, category `tool`) with `toolName`, and the thrown value on `error.cause`.
141
+
142
+ `ToolExecutionError` carries `toolName` always; `tripIndex` is stamped by the agent that dispatched it. The validation failure is fed back to the model on the next trip so it can correct within the `maxTrips` loop.
143
+
144
+ See [`@warlock.js/ai/handle-ai-errors/SKILL.md`](@warlock.js/ai/handle-ai-errors/SKILL.md).
145
+
146
+ ## Inspecting tool calls
147
+
148
+ ```ts
149
+ const result = await myAgent.execute("Pick a city and tell me the weather.");
150
+
151
+ const toolCalls = result.report.children.filter((c) => c.type === "tool");
152
+
153
+ for (const call of toolCalls) {
154
+ console.log(call.tripIndex, call.name, call.input, call.output, call.duration);
155
+ }
156
+ ```
157
+
158
+ Tool dispatches are child `BaseReport` nodes on `report.children` (not a separate `report.toolCalls` field) — filter by `c.type === "tool"`. Each `ToolCall` is a `BaseReport & { type: "tool", tripIndex, input, output?, error? }`, so it carries `name` / `startedAt` / `endedAt` / `duration` from the report base.
159
+
160
+ ## Events
161
+
162
+ - `agent.tool.calling` — `{ tool, input, tripIndex }`
163
+ - `agent.tool.called` — `ToolCall & { tool }` (full record)
164
+ - `agent.tool.failed` — `{ tool, input, error, tripIndex }`
165
+
166
+ Subscribe at factory / instance / per-call.
167
+
168
+ ## Pattern — workflow as a tool
169
+
170
+ ```ts
171
+ const wrapped = myWorkflow.asTool({
172
+ description: "Run the catalog ingestion workflow",
173
+ inputSchema: v.object({ url: v.string() }),
174
+ });
175
+
176
+ const agent = ai.agent({ model, tools: [wrapped] });
177
+ ```
178
+
179
+ Workflow errors surface as `ToolExecutionError` with `cause` pointing at the original `WorkflowError` subclass.
180
+
181
+ ## See also
182
+
183
+ - [`@warlock.js/ai/run-ai-agent/SKILL.md`](@warlock.js/ai/run-ai-agent/SKILL.md) — how tools plug into the trip loop
184
+ - [`@warlock.js/ai/handle-ai-errors/SKILL.md`](@warlock.js/ai/handle-ai-errors/SKILL.md) — error hierarchy
185
+ - [`@warlock.js/ai/run-supervisor/SKILL.md`](@warlock.js/ai/run-supervisor/SKILL.md) — artifacts under a supervisor
186
+ - [`@warlock.js/ai/run-ai-workflow/SKILL.md`](@warlock.js/ai/run-ai-workflow/SKILL.md) — `workflow.asTool()` composition