@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
@@ -0,0 +1,100 @@
1
+ import { BudgetExceededError } from "../../errors/budget-exceeded-error.mjs";
2
+ import "../../errors/index.mjs";
3
+ import { namespacedState } from "../utils/namespaced-state.mjs";
4
+
5
+ //#region ../../@warlock.js/ai/src/middleware/builtins/budget.ts
6
+ function breach(limit, actual, unit, name) {
7
+ throw new BudgetExceededError(`budget "${name}" exceeded — ${actual} ${unit} (cap: ${limit})`, {
8
+ limit,
9
+ actual,
10
+ unit
11
+ });
12
+ }
13
+ /**
14
+ * Enforced token and / or USD budget for an agent run.
15
+ *
16
+ * **Role.** Guards against runaway tool loops, misconfigured
17
+ * prompts, and unexpected provider price swings by capping
18
+ * cumulative usage across every LLM trip of a single execution.
19
+ * Aborts the run with a typed `BudgetExceededError` the moment a cap
20
+ * is breached, rather than letting the damage grow trip by trip.
21
+ *
22
+ * **Scope.** Per-execution. A fresh counter is created at
23
+ * `execute.before` and lives in the middleware state bag until the
24
+ * run ends. Two concurrent `agent.execute()` calls on the same
25
+ * agent therefore enforce the cap independently.
26
+ *
27
+ * **Token accounting.** After each successful trip, the middleware
28
+ * adds `response.usage.total` to its running total and checks
29
+ * against `maxTokens`. Synthetic trips (cache hits) contribute
30
+ * `usage.total` as returned by the cache — cache middleware is
31
+ * expected to surface zero usage on a hit, which naturally excludes
32
+ * those trips from the budget.
33
+ *
34
+ * **USD accounting.** When `maxCostUSD` + `pricing[modelName]` are
35
+ * both present, the middleware converts per-trip input / output
36
+ * tokens to USD and accumulates. Missing pricing silently degrades
37
+ * to tokens-only — explicit rather than guessing.
38
+ *
39
+ * **Warn mode.** `onExceeded: "warn"` logs a single warning the first
40
+ * time a cap is breached and lets the run continue. Useful for
41
+ * measuring real-world traffic against a proposed cap before flipping
42
+ * to `"abort"` in production.
43
+ *
44
+ * @example
45
+ * const budgetMiddleware = budget({ maxTokens: 50_000 });
46
+ *
47
+ * const myAgent = agent({
48
+ * model,
49
+ * middleware: [budgetMiddleware],
50
+ * });
51
+ *
52
+ * @example
53
+ * // With USD cap and custom pricing
54
+ * const guard = budget({
55
+ * maxCostUSD: 0.5,
56
+ * pricing: {
57
+ * "gpt-4o": { inputPer1K: 0.005, outputPer1K: 0.015 },
58
+ * },
59
+ * });
60
+ */
61
+ function budget(options) {
62
+ const name = options.name ?? "budget";
63
+ const onExceeded = options.onExceeded ?? "abort";
64
+ const hasTokenCap = typeof options.maxTokens === "number";
65
+ const hasCostCap = typeof options.maxCostUSD === "number";
66
+ return {
67
+ name,
68
+ execute: { before(context) {
69
+ namespacedState(context, name).set({
70
+ tokens: 0,
71
+ costUSD: 0,
72
+ warned: false
73
+ });
74
+ } },
75
+ trip: { after(context, response) {
76
+ const counters = namespacedState(context, name).get();
77
+ if (!counters) return;
78
+ counters.tokens += response.usage.total;
79
+ if (hasCostCap && options.pricing) {
80
+ const pricing = options.pricing[context.model.name];
81
+ if (pricing) {
82
+ const tripCost = response.usage.input / 1e3 * pricing.inputPer1K + response.usage.output / 1e3 * pricing.outputPer1K;
83
+ counters.costUSD += tripCost;
84
+ }
85
+ }
86
+ if (hasTokenCap && counters.tokens > options.maxTokens) {
87
+ if (onExceeded === "abort") breach(options.maxTokens, counters.tokens, "tokens", name);
88
+ if (!counters.warned) counters.warned = true;
89
+ }
90
+ if (hasCostCap && counters.costUSD > options.maxCostUSD) {
91
+ if (onExceeded === "abort") breach(options.maxCostUSD, counters.costUSD, "usd", name);
92
+ if (!counters.warned) counters.warned = true;
93
+ }
94
+ } }
95
+ };
96
+ }
97
+
98
+ //#endregion
99
+ export { budget };
100
+ //# sourceMappingURL=budget.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"budget.mjs","names":[],"sources":["../../../../../../../@warlock.js/ai/src/middleware/builtins/budget.ts"],"sourcesContent":["import type { AgentMiddleware } from \"../../contracts/middleware\";\nimport { BudgetExceededError, type BudgetUnit } from \"../../errors\";\nimport { namespacedState } from \"../utils\";\n\n/**\n * Per-model pricing used to compute USD cost from token counts.\n * Caller-supplied — no bundled table. Keys are model names (the\n * `ModelContract.name` value); values are input / output token\n * prices expressed as **USD per 1K tokens** to match every major\n * provider's published pricing sheet.\n */\nexport type BudgetPricing = Record<\n string,\n {\n /** USD per 1,000 input tokens. */\n inputPer1K: number;\n /** USD per 1,000 output tokens. */\n outputPer1K: number;\n }\n>;\n\n/**\n * Configuration for `budget()`. At least one of `maxTokens` or\n * `maxCostUSD` must be supplied — a budget with no cap is a no-op.\n */\nexport type BudgetOptions = {\n /**\n * Hard cap on cumulative total tokens (input + output, summed\n * across every trip of the run). Inclusive — exceeding triggers\n * the configured `onExceeded`.\n */\n maxTokens?: number;\n /**\n * Hard cap on cumulative USD cost. Requires `pricing` for the\n * agent's configured model — without a pricing entry the USD check\n * silently skips (tokens-only enforcement still applies).\n */\n maxCostUSD?: number;\n /**\n * Per-model pricing table used to compute USD cost. Only consulted\n * when `maxCostUSD` is set. Model names must match the running\n * agent's `ModelContract.name` exactly.\n */\n pricing?: BudgetPricing;\n /**\n * Behavior when a cap is breached. `\"abort\"` throws\n * `BudgetExceededError` — surfaces on `result.error`, stops the\n * run at the next trip boundary. `\"warn\"` logs a warning and\n * lets the run continue (useful for observability-first rollouts\n * before flipping the switch to abort). Default `\"abort\"`.\n */\n onExceeded?: \"abort\" | \"warn\";\n /**\n * Override the middleware name. Useful when two budgets coexist\n * (e.g. a per-request cap plus a session-wide cap via different\n * instances). Default `\"budget\"`.\n */\n name?: string;\n};\n\ntype BudgetCounters = {\n tokens: number;\n costUSD: number;\n warned: boolean;\n};\n\nfunction breach(\n limit: number,\n actual: number,\n unit: BudgetUnit,\n name: string,\n): never {\n throw new BudgetExceededError(\n `budget \"${name}\" exceeded — ${actual} ${unit} (cap: ${limit})`,\n { limit, actual, unit },\n );\n}\n\n/**\n * Enforced token and / or USD budget for an agent run.\n *\n * **Role.** Guards against runaway tool loops, misconfigured\n * prompts, and unexpected provider price swings by capping\n * cumulative usage across every LLM trip of a single execution.\n * Aborts the run with a typed `BudgetExceededError` the moment a cap\n * is breached, rather than letting the damage grow trip by trip.\n *\n * **Scope.** Per-execution. A fresh counter is created at\n * `execute.before` and lives in the middleware state bag until the\n * run ends. Two concurrent `agent.execute()` calls on the same\n * agent therefore enforce the cap independently.\n *\n * **Token accounting.** After each successful trip, the middleware\n * adds `response.usage.total` to its running total and checks\n * against `maxTokens`. Synthetic trips (cache hits) contribute\n * `usage.total` as returned by the cache — cache middleware is\n * expected to surface zero usage on a hit, which naturally excludes\n * those trips from the budget.\n *\n * **USD accounting.** When `maxCostUSD` + `pricing[modelName]` are\n * both present, the middleware converts per-trip input / output\n * tokens to USD and accumulates. Missing pricing silently degrades\n * to tokens-only — explicit rather than guessing.\n *\n * **Warn mode.** `onExceeded: \"warn\"` logs a single warning the first\n * time a cap is breached and lets the run continue. Useful for\n * measuring real-world traffic against a proposed cap before flipping\n * to `\"abort\"` in production.\n *\n * @example\n * const budgetMiddleware = budget({ maxTokens: 50_000 });\n *\n * const myAgent = agent({\n * model,\n * middleware: [budgetMiddleware],\n * });\n *\n * @example\n * // With USD cap and custom pricing\n * const guard = budget({\n * maxCostUSD: 0.5,\n * pricing: {\n * \"gpt-4o\": { inputPer1K: 0.005, outputPer1K: 0.015 },\n * },\n * });\n */\nexport function budget(options: BudgetOptions): AgentMiddleware {\n const name = options.name ?? \"budget\";\n const onExceeded = options.onExceeded ?? \"abort\";\n const hasTokenCap = typeof options.maxTokens === \"number\";\n const hasCostCap = typeof options.maxCostUSD === \"number\";\n\n return {\n name,\n execute: {\n before(context) {\n const counters = namespacedState<BudgetCounters>(context, name);\n counters.set({ tokens: 0, costUSD: 0, warned: false });\n },\n },\n trip: {\n after(context, response) {\n const counters = namespacedState<BudgetCounters>(context, name).get();\n\n if (!counters) {\n return;\n }\n\n counters.tokens += response.usage.total;\n\n if (hasCostCap && options.pricing) {\n const pricing = options.pricing[context.model.name];\n\n if (pricing) {\n const tripCost =\n (response.usage.input / 1000) * pricing.inputPer1K +\n (response.usage.output / 1000) * pricing.outputPer1K;\n counters.costUSD += tripCost;\n }\n }\n\n if (hasTokenCap && counters.tokens > options.maxTokens!) {\n if (onExceeded === \"abort\") {\n breach(options.maxTokens!, counters.tokens, \"tokens\", name);\n }\n\n if (!counters.warned) {\n counters.warned = true;\n }\n }\n\n if (hasCostCap && counters.costUSD > options.maxCostUSD!) {\n if (onExceeded === \"abort\") {\n breach(options.maxCostUSD!, counters.costUSD, \"usd\", name);\n }\n\n if (!counters.warned) {\n counters.warned = true;\n }\n }\n },\n },\n };\n}\n"],"mappings":";;;;;AAkEA,SAAS,OACP,OACA,QACA,MACA,MACO;CACP,MAAM,IAAI,oBACR,WAAW,KAAK,eAAe,OAAO,GAAG,KAAK,SAAS,MAAM,IAC7D;EAAE;EAAO;EAAQ;CAAK,CACxB;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkDA,SAAgB,OAAO,SAAyC;CAC9D,MAAM,OAAO,QAAQ,QAAQ;CAC7B,MAAM,aAAa,QAAQ,cAAc;CACzC,MAAM,cAAc,OAAO,QAAQ,cAAc;CACjD,MAAM,aAAa,OAAO,QAAQ,eAAe;CAEjD,OAAO;EACL;EACA,SAAS,EACP,OAAO,SAAS;GAEd,AADiB,gBAAgC,SAAS,IACnD,EAAE,IAAI;IAAE,QAAQ;IAAG,SAAS;IAAG,QAAQ;GAAM,CAAC;EACvD,EACF;EACA,MAAM,EACJ,MAAM,SAAS,UAAU;GACvB,MAAM,WAAW,gBAAgC,SAAS,IAAI,EAAE,IAAI;GAEpE,IAAI,CAAC,UACH;GAGF,SAAS,UAAU,SAAS,MAAM;GAElC,IAAI,cAAc,QAAQ,SAAS;IACjC,MAAM,UAAU,QAAQ,QAAQ,QAAQ,MAAM;IAE9C,IAAI,SAAS;KACX,MAAM,WACH,SAAS,MAAM,QAAQ,MAAQ,QAAQ,aACvC,SAAS,MAAM,SAAS,MAAQ,QAAQ;KAC3C,SAAS,WAAW;IACtB;GACF;GAEA,IAAI,eAAe,SAAS,SAAS,QAAQ,WAAY;IACvD,IAAI,eAAe,SACjB,OAAO,QAAQ,WAAY,SAAS,QAAQ,UAAU,IAAI;IAG5D,IAAI,CAAC,SAAS,QACZ,SAAS,SAAS;GAEtB;GAEA,IAAI,cAAc,SAAS,UAAU,QAAQ,YAAa;IACxD,IAAI,eAAe,SACjB,OAAO,QAAQ,YAAa,SAAS,SAAS,OAAO,IAAI;IAG3D,IAAI,CAAC,SAAS,QACZ,SAAS,SAAS;GAEtB;EACF,EACF;CACF;AACF"}
@@ -0,0 +1,92 @@
1
+ import { MiddlewareTripContext } from "../../contracts/middleware/middleware-context.type.mjs";
2
+ import { AgentMiddleware } from "../../contracts/middleware/middleware.contract.mjs";
3
+ //#region ../../@warlock.js/ai/src/middleware/builtins/guardrail.d.ts
4
+ /**
5
+ * Decision returned by a guardrail check function. `ok: true`
6
+ * permits the call; `ok: false` rejects with a human-readable
7
+ * `reason` surfaced on `GuardrailViolationError`.
8
+ */
9
+ type GuardrailCheckResult = {
10
+ ok: true;
11
+ } | {
12
+ ok: false;
13
+ reason: string;
14
+ };
15
+ /**
16
+ * Synchronous or asynchronous check invoked against the outbound
17
+ * prompt (`inputCheck`) or the inbound response (`outputCheck`).
18
+ * Receives the raw text and the surrounding trip context so
19
+ * consumers can classify, route to an external moderation API, or
20
+ * branch on tripIndex / messages history.
21
+ */
22
+ type GuardrailCheck = (text: string, context: MiddlewareTripContext) => GuardrailCheckResult | Promise<GuardrailCheckResult>;
23
+ /**
24
+ * Configuration for `guardrail()`. At least one of `inputCheck` or
25
+ * `outputCheck` must be supplied — a guardrail with no checks is a
26
+ * no-op.
27
+ */
28
+ type GuardrailOptions = {
29
+ /**
30
+ * Run against the outbound prompt just before the model sees it.
31
+ * Fires every trip with the concatenated last user-message text.
32
+ * Rejection aborts the trip with a `GuardrailViolationError` whose
33
+ * `phase === "input"`.
34
+ */
35
+ inputCheck?: GuardrailCheck;
36
+ /**
37
+ * Run against the model's response text after the trip completes.
38
+ * Fires every trip with `response.content`. Rejection aborts with
39
+ * a `GuardrailViolationError` whose `phase === "output"`.
40
+ *
41
+ * Output checks run BEFORE any tool dispatch — a rejected response
42
+ * means the tool calls it requested are never invoked.
43
+ */
44
+ outputCheck?: GuardrailCheck;
45
+ /**
46
+ * Override the middleware name — surfaces on
47
+ * `GuardrailViolationError.guardrail` so operators can tell two
48
+ * guardrails apart in logs. Default `"guardrail"`.
49
+ */
50
+ name?: string;
51
+ };
52
+ /**
53
+ * Pre/post content guardrail for an agent run.
54
+ *
55
+ * **Role.** Inspects outbound prompts and inbound responses against
56
+ * caller-supplied policies, aborting the trip with a typed
57
+ * `GuardrailViolationError` when either trips a check. Consumers
58
+ * distinguish `"input"` vs `"output"` violations off `error.phase`
59
+ * — the two failure modes have very different product responses
60
+ * (block the user vs re-prompt the model).
61
+ *
62
+ * **Scope.** Per-trip. Fires on every round-trip the agent makes,
63
+ * including repair attempts and tool-follow-up trips. Input checks
64
+ * evaluate the last user-role message; output checks evaluate the
65
+ * raw model response text before any tool call is dispatched.
66
+ *
67
+ * **Composition.** A single middleware instance can carry both
68
+ * `inputCheck` and `outputCheck`, or two separate instances can be
69
+ * registered (useful when input and output policies come from
70
+ * different teams / services). Registration order determines which
71
+ * guardrail's violation surfaces first — the short-circuit throws
72
+ * from the innermost offending hook, and outer guardrails never run
73
+ * after an abort.
74
+ *
75
+ * **Not a sanitizer.** The guardrail either passes a trip unchanged
76
+ * or aborts it. Mutating the prompt / response in-place is out of
77
+ * scope — use a bespoke middleware for content rewriting.
78
+ *
79
+ * @example
80
+ * const policy = guardrail({
81
+ * inputCheck: async (text) =>
82
+ * text.includes("SSN") ? { ok: false, reason: "pii" } : { ok: true },
83
+ * outputCheck: async (text) =>
84
+ * text.length > 10_000 ? { ok: false, reason: "too-long" } : { ok: true },
85
+ * });
86
+ *
87
+ * const myAgent = agent({ model, middleware: [policy] });
88
+ */
89
+ declare function guardrail(options: GuardrailOptions): AgentMiddleware;
90
+ //#endregion
91
+ export { GuardrailCheck, GuardrailCheckResult, GuardrailOptions, guardrail };
92
+ //# sourceMappingURL=guardrail.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"guardrail.d.mts","names":[],"sources":["../../../../../../../@warlock.js/ai/src/middleware/builtins/guardrail.ts"],"mappings":";;;;;;;AAaA;KAAY,oBAAA;EAAyB,EAAA;AAAA;EAAe,EAAA;EAAW,MAAA;AAAA;;AAAM;AASrE;;;;;KAAY,cAAA,IACV,IAAA,UACA,OAAA,EAAS,qBAAA,KACN,oBAAA,GAAuB,OAAA,CAAQ,oBAAA;;;;;;KAOxB,gBAAA;EAPP;;;;AAAmD;AAOxD;EAOE,UAAA,GAAa,cAAA;;;;;;;;;EASb,WAAA,GAAc,cAAc;EA8Cd;;;;;EAxCd,IAAA;AAAA;;AAwCmE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAArD,SAAA,CAAU,OAAA,EAAS,gBAAA,GAAmB,eAAe"}
@@ -0,0 +1,76 @@
1
+ import { GuardrailViolationError } from "../../errors/guardrail-violation-error.mjs";
2
+ import "../../errors/index.mjs";
3
+ import { extractUserText } from "../utils/extract-user-text.mjs";
4
+
5
+ //#region ../../@warlock.js/ai/src/middleware/builtins/guardrail.ts
6
+ /**
7
+ * Pre/post content guardrail for an agent run.
8
+ *
9
+ * **Role.** Inspects outbound prompts and inbound responses against
10
+ * caller-supplied policies, aborting the trip with a typed
11
+ * `GuardrailViolationError` when either trips a check. Consumers
12
+ * distinguish `"input"` vs `"output"` violations off `error.phase`
13
+ * — the two failure modes have very different product responses
14
+ * (block the user vs re-prompt the model).
15
+ *
16
+ * **Scope.** Per-trip. Fires on every round-trip the agent makes,
17
+ * including repair attempts and tool-follow-up trips. Input checks
18
+ * evaluate the last user-role message; output checks evaluate the
19
+ * raw model response text before any tool call is dispatched.
20
+ *
21
+ * **Composition.** A single middleware instance can carry both
22
+ * `inputCheck` and `outputCheck`, or two separate instances can be
23
+ * registered (useful when input and output policies come from
24
+ * different teams / services). Registration order determines which
25
+ * guardrail's violation surfaces first — the short-circuit throws
26
+ * from the innermost offending hook, and outer guardrails never run
27
+ * after an abort.
28
+ *
29
+ * **Not a sanitizer.** The guardrail either passes a trip unchanged
30
+ * or aborts it. Mutating the prompt / response in-place is out of
31
+ * scope — use a bespoke middleware for content rewriting.
32
+ *
33
+ * @example
34
+ * const policy = guardrail({
35
+ * inputCheck: async (text) =>
36
+ * text.includes("SSN") ? { ok: false, reason: "pii" } : { ok: true },
37
+ * outputCheck: async (text) =>
38
+ * text.length > 10_000 ? { ok: false, reason: "too-long" } : { ok: true },
39
+ * });
40
+ *
41
+ * const myAgent = agent({ model, middleware: [policy] });
42
+ */
43
+ function guardrail(options) {
44
+ const name = options.name ?? "guardrail";
45
+ const { inputCheck, outputCheck } = options;
46
+ return {
47
+ name,
48
+ trip: {
49
+ async before(context) {
50
+ if (!inputCheck) return;
51
+ const prompt = extractUserText(context.messages);
52
+ if (!prompt) return;
53
+ const verdict = await inputCheck(prompt, context);
54
+ if (!verdict.ok) throw new GuardrailViolationError(`guardrail "${name}" rejected input — ${verdict.reason}`, {
55
+ phase: "input",
56
+ reason: verdict.reason,
57
+ guardrail: name
58
+ });
59
+ },
60
+ async after(context, response) {
61
+ if (!outputCheck) return;
62
+ if (!response.content) return;
63
+ const verdict = await outputCheck(response.content, context);
64
+ if (!verdict.ok) throw new GuardrailViolationError(`guardrail "${name}" rejected output — ${verdict.reason}`, {
65
+ phase: "output",
66
+ reason: verdict.reason,
67
+ guardrail: name
68
+ });
69
+ }
70
+ }
71
+ };
72
+ }
73
+
74
+ //#endregion
75
+ export { guardrail };
76
+ //# sourceMappingURL=guardrail.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"guardrail.mjs","names":[],"sources":["../../../../../../../@warlock.js/ai/src/middleware/builtins/guardrail.ts"],"sourcesContent":["import type {\n AgentMiddleware,\n MiddlewareTripContext,\n} from \"../../contracts/middleware\";\nimport type { ModelResponse } from \"../../contracts/model.contract\";\nimport { GuardrailViolationError } from \"../../errors\";\nimport { extractUserText } from \"../utils\";\n\n/**\n * Decision returned by a guardrail check function. `ok: true`\n * permits the call; `ok: false` rejects with a human-readable\n * `reason` surfaced on `GuardrailViolationError`.\n */\nexport type GuardrailCheckResult = { ok: true } | { ok: false; reason: string };\n\n/**\n * Synchronous or asynchronous check invoked against the outbound\n * prompt (`inputCheck`) or the inbound response (`outputCheck`).\n * Receives the raw text and the surrounding trip context so\n * consumers can classify, route to an external moderation API, or\n * branch on tripIndex / messages history.\n */\nexport type GuardrailCheck = (\n text: string,\n context: MiddlewareTripContext,\n) => GuardrailCheckResult | Promise<GuardrailCheckResult>;\n\n/**\n * Configuration for `guardrail()`. At least one of `inputCheck` or\n * `outputCheck` must be supplied — a guardrail with no checks is a\n * no-op.\n */\nexport type GuardrailOptions = {\n /**\n * Run against the outbound prompt just before the model sees it.\n * Fires every trip with the concatenated last user-message text.\n * Rejection aborts the trip with a `GuardrailViolationError` whose\n * `phase === \"input\"`.\n */\n inputCheck?: GuardrailCheck;\n /**\n * Run against the model's response text after the trip completes.\n * Fires every trip with `response.content`. Rejection aborts with\n * a `GuardrailViolationError` whose `phase === \"output\"`.\n *\n * Output checks run BEFORE any tool dispatch — a rejected response\n * means the tool calls it requested are never invoked.\n */\n outputCheck?: GuardrailCheck;\n /**\n * Override the middleware name — surfaces on\n * `GuardrailViolationError.guardrail` so operators can tell two\n * guardrails apart in logs. Default `\"guardrail\"`.\n */\n name?: string;\n};\n\n/**\n * Pre/post content guardrail for an agent run.\n *\n * **Role.** Inspects outbound prompts and inbound responses against\n * caller-supplied policies, aborting the trip with a typed\n * `GuardrailViolationError` when either trips a check. Consumers\n * distinguish `\"input\"` vs `\"output\"` violations off `error.phase`\n * — the two failure modes have very different product responses\n * (block the user vs re-prompt the model).\n *\n * **Scope.** Per-trip. Fires on every round-trip the agent makes,\n * including repair attempts and tool-follow-up trips. Input checks\n * evaluate the last user-role message; output checks evaluate the\n * raw model response text before any tool call is dispatched.\n *\n * **Composition.** A single middleware instance can carry both\n * `inputCheck` and `outputCheck`, or two separate instances can be\n * registered (useful when input and output policies come from\n * different teams / services). Registration order determines which\n * guardrail's violation surfaces first — the short-circuit throws\n * from the innermost offending hook, and outer guardrails never run\n * after an abort.\n *\n * **Not a sanitizer.** The guardrail either passes a trip unchanged\n * or aborts it. Mutating the prompt / response in-place is out of\n * scope — use a bespoke middleware for content rewriting.\n *\n * @example\n * const policy = guardrail({\n * inputCheck: async (text) =>\n * text.includes(\"SSN\") ? { ok: false, reason: \"pii\" } : { ok: true },\n * outputCheck: async (text) =>\n * text.length > 10_000 ? { ok: false, reason: \"too-long\" } : { ok: true },\n * });\n *\n * const myAgent = agent({ model, middleware: [policy] });\n */\nexport function guardrail(options: GuardrailOptions): AgentMiddleware {\n const name = options.name ?? \"guardrail\";\n const { inputCheck, outputCheck } = options;\n\n return {\n name,\n trip: {\n async before(context) {\n if (!inputCheck) {\n return;\n }\n\n const prompt = extractUserText(context.messages);\n\n if (!prompt) {\n return;\n }\n\n const verdict = await inputCheck(prompt, context);\n\n if (!verdict.ok) {\n throw new GuardrailViolationError(\n `guardrail \"${name}\" rejected input — ${verdict.reason}`,\n { phase: \"input\", reason: verdict.reason, guardrail: name },\n );\n }\n },\n async after(context, response: ModelResponse) {\n if (!outputCheck) {\n return;\n }\n\n if (!response.content) {\n return;\n }\n\n const verdict = await outputCheck(response.content, context);\n\n if (!verdict.ok) {\n throw new GuardrailViolationError(\n `guardrail \"${name}\" rejected output — ${verdict.reason}`,\n { phase: \"output\", reason: verdict.reason, guardrail: name },\n );\n }\n },\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8FA,SAAgB,UAAU,SAA4C;CACpE,MAAM,OAAO,QAAQ,QAAQ;CAC7B,MAAM,EAAE,YAAY,gBAAgB;CAEpC,OAAO;EACL;EACA,MAAM;GACJ,MAAM,OAAO,SAAS;IACpB,IAAI,CAAC,YACH;IAGF,MAAM,SAAS,gBAAgB,QAAQ,QAAQ;IAE/C,IAAI,CAAC,QACH;IAGF,MAAM,UAAU,MAAM,WAAW,QAAQ,OAAO;IAEhD,IAAI,CAAC,QAAQ,IACX,MAAM,IAAI,wBACR,cAAc,KAAK,qBAAqB,QAAQ,UAChD;KAAE,OAAO;KAAS,QAAQ,QAAQ;KAAQ,WAAW;IAAK,CAC5D;GAEJ;GACA,MAAM,MAAM,SAAS,UAAyB;IAC5C,IAAI,CAAC,aACH;IAGF,IAAI,CAAC,SAAS,SACZ;IAGF,MAAM,UAAU,MAAM,YAAY,SAAS,SAAS,OAAO;IAE3D,IAAI,CAAC,QAAQ,IACX,MAAM,IAAI,wBACR,cAAc,KAAK,sBAAsB,QAAQ,UACjD;KAAE,OAAO;KAAU,QAAQ,QAAQ;KAAQ,WAAW;IAAK,CAC7D;GAEJ;EACF;CACF;AACF"}
@@ -0,0 +1,106 @@
1
+ import { EmbedderContract } from "../../contracts/embedder.contract.mjs";
2
+ import { AgentMiddleware } from "../../contracts/middleware/middleware.contract.mjs";
3
+ import { CacheDriver } from "@warlock.js/cache";
4
+
5
+ //#region ../../@warlock.js/ai/src/middleware/builtins/semantic-cache.d.ts
6
+ /**
7
+ * Configuration for `semanticCache()`.
8
+ */
9
+ type SemanticCacheOptions = {
10
+ /** Embedder used to produce the query vector from the prompt text. */embedder: EmbedderContract;
11
+ /**
12
+ * Vector-capable cache driver from `@warlock.js/cache`. Production
13
+ * deployments pick a driver with a real ANN index (`pg` with
14
+ * pgvector, `redis` with RediSearch). Dev / test environments use
15
+ * `new MemoryCacheDriver()` — zero config, correct, but O(N) per
16
+ * query. Drivers without similarity support throw
17
+ * `CacheUnsupportedError` from `set({ vector })` / `similar()`.
18
+ *
19
+ * Falls back to `ai.config({ defaultStore })` when omitted. When
20
+ * neither is set, the factory throws at construction time —
21
+ * semantic cache cannot operate without a store.
22
+ */
23
+ store?: CacheDriver<any, any>;
24
+ /**
25
+ * Minimum cosine similarity for a vector hit. Between 0 and 1 —
26
+ * 0.95 is a solid default for question-answering caches.
27
+ */
28
+ threshold: number;
29
+ /**
30
+ * Optional TTL in milliseconds. Entries whose `storedAt` is older
31
+ * than this are treated as misses on read and overwritten on the
32
+ * next write. Default: no expiry — entries live until the store
33
+ * evicts them (per its own TTL/eviction policy).
34
+ */
35
+ ttlMs?: number;
36
+ /**
37
+ * Namespace prefix applied to every key the cache writes. Lets
38
+ * multiple agents share one driver without collision. Default
39
+ * `"ai.cache"`.
40
+ */
41
+ namespace?: string;
42
+ /**
43
+ * Middleware name — also the state-bag key prefix inside a single
44
+ * execution. Default `"semantic-cache"`.
45
+ */
46
+ name?: string;
47
+ };
48
+ /**
49
+ * Semantic-similarity response cache for an agent run.
50
+ *
51
+ * **Role.** Skips LLM round-trips when the current prompt is
52
+ * semantically close to one the agent has already answered. For
53
+ * FAQ / support-style traffic this often eliminates 60–80% of
54
+ * model calls — the production win is massive for cost and
55
+ * latency.
56
+ *
57
+ * **Delegation to `@warlock.js/cache`.** This middleware does NOT
58
+ * implement similarity search itself. It delegates to the supplied
59
+ * `CacheDriver`. Production deployments pick a driver with an ANN
60
+ * index (`pg` + pgvector, `redis` + RediSearch). Dev / test
61
+ * environments pass `new MemoryCacheDriver()` — zero config, correct,
62
+ * but O(N) per query. Drivers without similarity support throw
63
+ * `CacheUnsupportedError` from `set({ vector })` / `similar()`.
64
+ *
65
+ * **Two-tier lookup.**
66
+ * 1. *Exact-match key* — a cheap FNV hash over the entire message
67
+ * list. `store.get(hash)` returns the entry without an embedding
68
+ * round trip when the prompt hasn't changed at all.
69
+ * 2. *Vector-match* — on exact-match miss, embed the prompt and
70
+ * call `store.similar(vector, { topK: 1, threshold })`. The
71
+ * driver uses its native similarity index; anything clearing
72
+ * `threshold` is returned as a hit.
73
+ *
74
+ * **Write-on-miss.** When both tiers miss, `trip.before` stashes
75
+ * the prompt hash + vector in `ctx.state`; `trip.after` reads back
76
+ * the pending entry and calls
77
+ * `store.set(hash, entry, { vector })`. If an outer middleware
78
+ * (guardrail) throws in `trip.after` before the cache's `trip.after`
79
+ * runs, the pending entry is never written — bad responses stay out
80
+ * of the cache **as long as the canonical install order is followed**
81
+ * (cache outermost).
82
+ *
83
+ * **Synthetic-response on hit.** Returns a `ModelResponse` with
84
+ * `usage: { input: 0, output: 0, total: 0 }` so budget /
85
+ * observability correctly exclude the saved trip.
86
+ *
87
+ * @example
88
+ * import { semanticCache } from "@warlock.js/ai";
89
+ * import { MemoryCacheDriver } from "@warlock.js/cache";
90
+ *
91
+ * const store = new MemoryCacheDriver();
92
+ * store.setOptions({});
93
+ *
94
+ * const cache = semanticCache({
95
+ * embedder: openai.embedder({ name: "text-embedding-3-small" }),
96
+ * store,
97
+ * threshold: 0.95,
98
+ * ttlMs: 60 * 60 * 1000,
99
+ * });
100
+ *
101
+ * const myAgent = agent({ model, middleware: [cache] });
102
+ */
103
+ declare function semanticCache(options: SemanticCacheOptions): AgentMiddleware;
104
+ //#endregion
105
+ export { SemanticCacheOptions, semanticCache };
106
+ //# sourceMappingURL=semantic-cache.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"semantic-cache.d.mts","names":[],"sources":["../../../../../../../@warlock.js/ai/src/middleware/builtins/semantic-cache.ts"],"mappings":";;;;;;;;KAWY,oBAAA;EAAoB,sEAE9B,QAAA,EAAU,gBAAA;EAaS;;;;;;;;;;AAuBf;AAkHN;EAzIE,KAAA,GAAQ,WAAW;;;;;EAKnB,SAAA;EAoI2E;AAAA;;;;;EA7H3E,KAAA;;;;;;EAMA,SAAA;;;;;EAKA,IAAA;AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAkHc,aAAA,CAAc,OAAA,EAAS,oBAAA,GAAuB,eAAe"}
@@ -0,0 +1,149 @@
1
+ import { extractUserText } from "../utils/extract-user-text.mjs";
2
+ import { resolveDefaultStore } from "../../config.mjs";
3
+
4
+ //#region ../../@warlock.js/ai/src/middleware/builtins/semantic-cache.ts
5
+ const DEFAULT_NAMESPACE = "ai.cache";
6
+ /**
7
+ * Build a stable fingerprint for a prompt covering the full message
8
+ * list (system + history + user turn). Ensures two prompts sharing
9
+ * the user text but differing in prior context do not collide on
10
+ * the exact-match fast path.
11
+ *
12
+ * FNV-1a variant — cheap, collision-resistant enough for a cache,
13
+ * dependency-free. NOT a cryptographic hash: collisions would
14
+ * surface as wrong cache hits, not a security issue in the current
15
+ * trust model.
16
+ */
17
+ function hashPrompt(messages) {
18
+ const serialized = messages.map((message) => {
19
+ return `${message.role}:${Array.isArray(message.content) ? message.content.filter((part) => part.type === "text").map((part) => part.text).join("|") : message.content}`;
20
+ }).join("||");
21
+ let hash = 2166136261;
22
+ for (let index = 0; index < serialized.length; index++) {
23
+ hash ^= serialized.charCodeAt(index);
24
+ hash = Math.imul(hash, 16777619);
25
+ }
26
+ return (hash >>> 0).toString(16);
27
+ }
28
+ function isFresh(entry, ttlMs) {
29
+ if (ttlMs === void 0) return true;
30
+ return Date.now() - entry.storedAt <= ttlMs;
31
+ }
32
+ /**
33
+ * Semantic-similarity response cache for an agent run.
34
+ *
35
+ * **Role.** Skips LLM round-trips when the current prompt is
36
+ * semantically close to one the agent has already answered. For
37
+ * FAQ / support-style traffic this often eliminates 60–80% of
38
+ * model calls — the production win is massive for cost and
39
+ * latency.
40
+ *
41
+ * **Delegation to `@warlock.js/cache`.** This middleware does NOT
42
+ * implement similarity search itself. It delegates to the supplied
43
+ * `CacheDriver`. Production deployments pick a driver with an ANN
44
+ * index (`pg` + pgvector, `redis` + RediSearch). Dev / test
45
+ * environments pass `new MemoryCacheDriver()` — zero config, correct,
46
+ * but O(N) per query. Drivers without similarity support throw
47
+ * `CacheUnsupportedError` from `set({ vector })` / `similar()`.
48
+ *
49
+ * **Two-tier lookup.**
50
+ * 1. *Exact-match key* — a cheap FNV hash over the entire message
51
+ * list. `store.get(hash)` returns the entry without an embedding
52
+ * round trip when the prompt hasn't changed at all.
53
+ * 2. *Vector-match* — on exact-match miss, embed the prompt and
54
+ * call `store.similar(vector, { topK: 1, threshold })`. The
55
+ * driver uses its native similarity index; anything clearing
56
+ * `threshold` is returned as a hit.
57
+ *
58
+ * **Write-on-miss.** When both tiers miss, `trip.before` stashes
59
+ * the prompt hash + vector in `ctx.state`; `trip.after` reads back
60
+ * the pending entry and calls
61
+ * `store.set(hash, entry, { vector })`. If an outer middleware
62
+ * (guardrail) throws in `trip.after` before the cache's `trip.after`
63
+ * runs, the pending entry is never written — bad responses stay out
64
+ * of the cache **as long as the canonical install order is followed**
65
+ * (cache outermost).
66
+ *
67
+ * **Synthetic-response on hit.** Returns a `ModelResponse` with
68
+ * `usage: { input: 0, output: 0, total: 0 }` so budget /
69
+ * observability correctly exclude the saved trip.
70
+ *
71
+ * @example
72
+ * import { semanticCache } from "@warlock.js/ai";
73
+ * import { MemoryCacheDriver } from "@warlock.js/cache";
74
+ *
75
+ * const store = new MemoryCacheDriver();
76
+ * store.setOptions({});
77
+ *
78
+ * const cache = semanticCache({
79
+ * embedder: openai.embedder({ name: "text-embedding-3-small" }),
80
+ * store,
81
+ * threshold: 0.95,
82
+ * ttlMs: 60 * 60 * 1000,
83
+ * });
84
+ *
85
+ * const myAgent = agent({ model, middleware: [cache] });
86
+ */
87
+ function semanticCache(options) {
88
+ const name = options.name ?? "semantic-cache";
89
+ const namespace = options.namespace ?? DEFAULT_NAMESPACE;
90
+ const pendingKey = `${name}.pending`;
91
+ const store = options.store ?? resolveDefaultStore();
92
+ if (!store) throw new Error(`semanticCache: no store supplied — pass \`store\` in options or call \`ai.config({ defaultStore })\` at app boot before constructing the middleware`);
93
+ const keyFor = (hash) => `${namespace}.${hash}`;
94
+ return {
95
+ name,
96
+ log: true,
97
+ trip: {
98
+ async before(context) {
99
+ if (context.tripIndex !== 0) return;
100
+ const promptText = extractUserText(context.messages);
101
+ if (!promptText) return;
102
+ const promptKey = hashPrompt(context.messages);
103
+ const scopedKey = keyFor(promptKey);
104
+ const exact = await store.get(scopedKey);
105
+ if (exact && isFresh(exact, options.ttlMs)) return toSyntheticResponse(exact.response);
106
+ const query = await options.embedder.embed(promptText);
107
+ const [hit] = await store.similar(query.vector, {
108
+ topK: 1,
109
+ threshold: options.threshold
110
+ });
111
+ if (hit && isFresh(hit.value, options.ttlMs)) {
112
+ if (hit.key.startsWith(`${namespace}.`)) return toSyntheticResponse(hit.value.response);
113
+ }
114
+ const pending = {
115
+ promptKey,
116
+ vector: query.vector
117
+ };
118
+ context.state.set(pendingKey, pending);
119
+ },
120
+ async after(context, response) {
121
+ const pending = context.state.get(pendingKey);
122
+ if (!pending) return;
123
+ if (response.finishReason === "tool_calls") return;
124
+ context.state.delete(pendingKey);
125
+ const entry = {
126
+ response,
127
+ storedAt: Date.now()
128
+ };
129
+ await store.set(keyFor(pending.promptKey), entry, { vector: pending.vector });
130
+ }
131
+ }
132
+ };
133
+ }
134
+ function toSyntheticResponse(response) {
135
+ return {
136
+ content: response.content,
137
+ finishReason: response.finishReason,
138
+ usage: {
139
+ input: 0,
140
+ output: 0,
141
+ total: 0
142
+ },
143
+ toolCalls: response.toolCalls
144
+ };
145
+ }
146
+
147
+ //#endregion
148
+ export { semanticCache };
149
+ //# sourceMappingURL=semantic-cache.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"semantic-cache.mjs","names":[],"sources":["../../../../../../../@warlock.js/ai/src/middleware/builtins/semantic-cache.ts"],"sourcesContent":["import type { CacheDriver } from \"@warlock.js/cache\";\nimport { resolveDefaultStore } from \"../../config\";\nimport type { Message } from \"../../contracts/conversation-message.type\";\nimport type { EmbedderContract } from \"../../contracts/embedder.contract\";\nimport type { AgentMiddleware } from \"../../contracts/middleware\";\nimport type { ModelResponse } from \"../../contracts/model.contract\";\nimport { extractUserText } from \"../utils\";\n\n/**\n * Configuration for `semanticCache()`.\n */\nexport type SemanticCacheOptions = {\n /** Embedder used to produce the query vector from the prompt text. */\n embedder: EmbedderContract;\n /**\n * Vector-capable cache driver from `@warlock.js/cache`. Production\n * deployments pick a driver with a real ANN index (`pg` with\n * pgvector, `redis` with RediSearch). Dev / test environments use\n * `new MemoryCacheDriver()` — zero config, correct, but O(N) per\n * query. Drivers without similarity support throw\n * `CacheUnsupportedError` from `set({ vector })` / `similar()`.\n *\n * Falls back to `ai.config({ defaultStore })` when omitted. When\n * neither is set, the factory throws at construction time —\n * semantic cache cannot operate without a store.\n */\n store?: CacheDriver<any, any>;\n /**\n * Minimum cosine similarity for a vector hit. Between 0 and 1 —\n * 0.95 is a solid default for question-answering caches.\n */\n threshold: number;\n /**\n * Optional TTL in milliseconds. Entries whose `storedAt` is older\n * than this are treated as misses on read and overwritten on the\n * next write. Default: no expiry — entries live until the store\n * evicts them (per its own TTL/eviction policy).\n */\n ttlMs?: number;\n /**\n * Namespace prefix applied to every key the cache writes. Lets\n * multiple agents share one driver without collision. Default\n * `\"ai.cache\"`.\n */\n namespace?: string;\n /**\n * Middleware name — also the state-bag key prefix inside a single\n * execution. Default `\"semantic-cache\"`.\n */\n name?: string;\n};\n\ntype CachedEntry = {\n response: ModelResponse;\n storedAt: number;\n};\n\ntype PendingWrite = {\n promptKey: string;\n vector: number[];\n};\n\nconst DEFAULT_NAMESPACE = \"ai.cache\";\n\n/**\n * Build a stable fingerprint for a prompt covering the full message\n * list (system + history + user turn). Ensures two prompts sharing\n * the user text but differing in prior context do not collide on\n * the exact-match fast path.\n *\n * FNV-1a variant — cheap, collision-resistant enough for a cache,\n * dependency-free. NOT a cryptographic hash: collisions would\n * surface as wrong cache hits, not a security issue in the current\n * trust model.\n */\nfunction hashPrompt(messages: ReadonlyArray<Message>): string {\n const serialized = messages\n .map((message) => {\n const role = message.role;\n const content = Array.isArray(message.content)\n ? message.content\n .filter((part) => part.type === \"text\")\n .map((part) => (part as { text: string }).text)\n .join(\"|\")\n : message.content;\n\n return `${role}:${content}`;\n })\n .join(\"||\");\n\n let hash = 0x811c9dc5;\n\n for (let index = 0; index < serialized.length; index++) {\n hash ^= serialized.charCodeAt(index);\n hash = Math.imul(hash, 0x01000193);\n }\n\n return (hash >>> 0).toString(16);\n}\n\nfunction isFresh(entry: CachedEntry, ttlMs: number | undefined): boolean {\n if (ttlMs === undefined) {\n return true;\n }\n\n return Date.now() - entry.storedAt <= ttlMs;\n}\n\n/**\n * Semantic-similarity response cache for an agent run.\n *\n * **Role.** Skips LLM round-trips when the current prompt is\n * semantically close to one the agent has already answered. For\n * FAQ / support-style traffic this often eliminates 60–80% of\n * model calls — the production win is massive for cost and\n * latency.\n *\n * **Delegation to `@warlock.js/cache`.** This middleware does NOT\n * implement similarity search itself. It delegates to the supplied\n * `CacheDriver`. Production deployments pick a driver with an ANN\n * index (`pg` + pgvector, `redis` + RediSearch). Dev / test\n * environments pass `new MemoryCacheDriver()` — zero config, correct,\n * but O(N) per query. Drivers without similarity support throw\n * `CacheUnsupportedError` from `set({ vector })` / `similar()`.\n *\n * **Two-tier lookup.**\n * 1. *Exact-match key* — a cheap FNV hash over the entire message\n * list. `store.get(hash)` returns the entry without an embedding\n * round trip when the prompt hasn't changed at all.\n * 2. *Vector-match* — on exact-match miss, embed the prompt and\n * call `store.similar(vector, { topK: 1, threshold })`. The\n * driver uses its native similarity index; anything clearing\n * `threshold` is returned as a hit.\n *\n * **Write-on-miss.** When both tiers miss, `trip.before` stashes\n * the prompt hash + vector in `ctx.state`; `trip.after` reads back\n * the pending entry and calls\n * `store.set(hash, entry, { vector })`. If an outer middleware\n * (guardrail) throws in `trip.after` before the cache's `trip.after`\n * runs, the pending entry is never written — bad responses stay out\n * of the cache **as long as the canonical install order is followed**\n * (cache outermost).\n *\n * **Synthetic-response on hit.** Returns a `ModelResponse` with\n * `usage: { input: 0, output: 0, total: 0 }` so budget /\n * observability correctly exclude the saved trip.\n *\n * @example\n * import { semanticCache } from \"@warlock.js/ai\";\n * import { MemoryCacheDriver } from \"@warlock.js/cache\";\n *\n * const store = new MemoryCacheDriver();\n * store.setOptions({});\n *\n * const cache = semanticCache({\n * embedder: openai.embedder({ name: \"text-embedding-3-small\" }),\n * store,\n * threshold: 0.95,\n * ttlMs: 60 * 60 * 1000,\n * });\n *\n * const myAgent = agent({ model, middleware: [cache] });\n */\nexport function semanticCache(options: SemanticCacheOptions): AgentMiddleware {\n const name = options.name ?? \"semantic-cache\";\n const namespace = options.namespace ?? DEFAULT_NAMESPACE;\n const pendingKey = `${name}.pending`;\n\n // Resolve the effective store at factory time, not per-call. Every\n // subsequent hook closes over `store` so the resolution happens once.\n // Throws now (loud, at construction) instead of later during the\n // first trip (silent until the agent actually runs).\n const store = options.store ?? resolveDefaultStore();\n\n if (!store) {\n throw new Error(\n `semanticCache: no store supplied — pass \\`store\\` in options or call \\`ai.config({ defaultStore })\\` at app boot before constructing the middleware`,\n );\n }\n\n // Cache's parseKey replaces \":\" with \".\" so the namespace boundary\n // matches what `similar()` actually returns in `hit.key`. Using a\n // dot here keeps prefix checks aligned with stored keys.\n const keyFor = (hash: string): string => `${namespace}.${hash}`;\n\n return {\n name,\n log: true,\n trip: {\n async before(context) {\n // Only cache the first trip's response. Subsequent trips\n // happen because the previous trip requested tool calls — the\n // message list now carries tool results the original prompt\n // never saw, so a semantic match on the unchanged user text\n // would serve back the prior `tool_calls` response and loop\n // the agent forever. The first turn is also the only one\n // where a \"same question → same final answer\" caching story\n // is sound.\n if (context.tripIndex !== 0) {\n return;\n }\n\n const promptText = extractUserText(context.messages);\n\n if (!promptText) {\n return;\n }\n\n const promptKey = hashPrompt(context.messages);\n const scopedKey = keyFor(promptKey);\n\n const exact = await store.get<CachedEntry>(scopedKey);\n\n if (exact && isFresh(exact, options.ttlMs)) {\n return toSyntheticResponse(exact.response);\n }\n\n const query = await options.embedder.embed(promptText);\n\n const [hit] = await store.similar<CachedEntry>(query.vector, {\n topK: 1,\n threshold: options.threshold,\n });\n\n if (hit && isFresh(hit.value, options.ttlMs)) {\n // Only return hits whose stored key is within this cache's\n // namespace. Drivers shared across namespaces would otherwise\n // leak foreign entries into queries.\n if (hit.key.startsWith(`${namespace}.`)) {\n return toSyntheticResponse(hit.value.response);\n }\n }\n\n const pending: PendingWrite = { promptKey, vector: query.vector };\n context.state.set(pendingKey, pending);\n\n return;\n },\n async after(context, response) {\n const pending = context.state.get(pendingKey) as PendingWrite | undefined;\n\n if (!pending) {\n return;\n }\n\n // Mid-stream tool-call responses must not be cached — the\n // useful answer comes from the trip *after* the tool returns.\n // Crucially, leave the pending entry in place so a later trip\n // (the one that actually finishes with `stop`) can read it\n // and write the final response under the *original* trip-0\n // prompt key. Deleting here would orphan the pending and the\n // post-tool answer would never make it into the store.\n if (response.finishReason === \"tool_calls\") {\n return;\n }\n\n context.state.delete(pendingKey);\n\n const entry: CachedEntry = { response, storedAt: Date.now() };\n\n await store.set(keyFor(pending.promptKey), entry, {\n vector: pending.vector,\n });\n\n return;\n },\n },\n };\n}\n\nfunction toSyntheticResponse(response: ModelResponse): ModelResponse {\n return {\n content: response.content,\n finishReason: response.finishReason,\n usage: { input: 0, output: 0, total: 0 },\n toolCalls: response.toolCalls,\n };\n}\n"],"mappings":";;;;AA8DA,MAAM,oBAAoB;;;;;;;;;;;;AAa1B,SAAS,WAAW,UAA0C;CAC5D,MAAM,aAAa,SAChB,KAAK,YAAY;EAShB,OAAO,GARM,QAAQ,KAQN,GAPC,MAAM,QAAQ,QAAQ,OAAO,IACzC,QAAQ,QACL,QAAQ,SAAS,KAAK,SAAS,MAAM,EACrC,KAAK,SAAU,KAA0B,IAAI,EAC7C,KAAK,GAAG,IACX,QAAQ;CAGd,CAAC,EACA,KAAK,IAAI;CAEZ,IAAI,OAAO;CAEX,KAAK,IAAI,QAAQ,GAAG,QAAQ,WAAW,QAAQ,SAAS;EACtD,QAAQ,WAAW,WAAW,KAAK;EACnC,OAAO,KAAK,KAAK,MAAM,QAAU;CACnC;CAEA,QAAQ,SAAS,GAAG,SAAS,EAAE;AACjC;AAEA,SAAS,QAAQ,OAAoB,OAAoC;CACvE,IAAI,UAAU,QACZ,OAAO;CAGT,OAAO,KAAK,IAAI,IAAI,MAAM,YAAY;AACxC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyDA,SAAgB,cAAc,SAAgD;CAC5E,MAAM,OAAO,QAAQ,QAAQ;CAC7B,MAAM,YAAY,QAAQ,aAAa;CACvC,MAAM,aAAa,GAAG,KAAK;CAM3B,MAAM,QAAQ,QAAQ,SAAS,oBAAoB;CAEnD,IAAI,CAAC,OACH,MAAM,IAAI,MACR,qJACF;CAMF,MAAM,UAAU,SAAyB,GAAG,UAAU,GAAG;CAEzD,OAAO;EACL;EACA,KAAK;EACL,MAAM;GACJ,MAAM,OAAO,SAAS;IASpB,IAAI,QAAQ,cAAc,GACxB;IAGF,MAAM,aAAa,gBAAgB,QAAQ,QAAQ;IAEnD,IAAI,CAAC,YACH;IAGF,MAAM,YAAY,WAAW,QAAQ,QAAQ;IAC7C,MAAM,YAAY,OAAO,SAAS;IAElC,MAAM,QAAQ,MAAM,MAAM,IAAiB,SAAS;IAEpD,IAAI,SAAS,QAAQ,OAAO,QAAQ,KAAK,GACvC,OAAO,oBAAoB,MAAM,QAAQ;IAG3C,MAAM,QAAQ,MAAM,QAAQ,SAAS,MAAM,UAAU;IAErD,MAAM,CAAC,OAAO,MAAM,MAAM,QAAqB,MAAM,QAAQ;KAC3D,MAAM;KACN,WAAW,QAAQ;IACrB,CAAC;IAED,IAAI,OAAO,QAAQ,IAAI,OAAO,QAAQ,KAAK,GAIzC;SAAI,IAAI,IAAI,WAAW,GAAG,UAAU,EAAE,GACpC,OAAO,oBAAoB,IAAI,MAAM,QAAQ;IAC/C;IAGF,MAAM,UAAwB;KAAE;KAAW,QAAQ,MAAM;IAAO;IAChE,QAAQ,MAAM,IAAI,YAAY,OAAO;GAGvC;GACA,MAAM,MAAM,SAAS,UAAU;IAC7B,MAAM,UAAU,QAAQ,MAAM,IAAI,UAAU;IAE5C,IAAI,CAAC,SACH;IAUF,IAAI,SAAS,iBAAiB,cAC5B;IAGF,QAAQ,MAAM,OAAO,UAAU;IAE/B,MAAM,QAAqB;KAAE;KAAU,UAAU,KAAK,IAAI;IAAE;IAE5D,MAAM,MAAM,IAAI,OAAO,QAAQ,SAAS,GAAG,OAAO,EAChD,QAAQ,QAAQ,OAClB,CAAC;GAGH;EACF;CACF;AACF;AAEA,SAAS,oBAAoB,UAAwC;CACnE,OAAO;EACL,SAAS,SAAS;EAClB,cAAc,SAAS;EACvB,OAAO;GAAE,OAAO;GAAG,QAAQ;GAAG,OAAO;EAAE;EACvC,WAAW,SAAS;CACtB;AACF"}
@@ -0,0 +1,42 @@
1
+ import { AgentMiddleware } from "../../contracts/middleware/middleware.contract.mjs";
2
+ //#region ../../@warlock.js/ai/src/middleware/helpers/compose.d.ts
3
+ /**
4
+ * Flatten one or more middleware sources into a single ordered
5
+ * array suitable for `agent({ middleware: [...] })`.
6
+ *
7
+ * **Role.** As middleware catalogs grow, agent configs accumulate
8
+ * long arrays that mix "always-on" stacks (cache + budget + guardrail)
9
+ * with per-concern extras (per-tool rate-limits, audit hooks). A
10
+ * single `compose` call lets callers keep those sources as named
11
+ * variables and flatten at the registration site.
12
+ *
13
+ * **Semantics.** Registration order is preserved across sources —
14
+ * `compose(a, b, c)` produces `[...a, ...b, ...c]`. Because the
15
+ * pipeline's onion is strictly registration-ordered, the flattened
16
+ * order is the execution order. No de-duplication, no sorting, no
17
+ * priority logic — that would hide bugs, not fix them.
18
+ *
19
+ * **Accepts arrays OR individual middlewares.** Both forms are
20
+ * common in callsite code; the helper flattens either.
21
+ *
22
+ * @example
23
+ * const standardStack = [
24
+ * ai.middleware.semanticCache({ ... }),
25
+ * ai.middleware.budget({ maxTokens: 20_000 }),
26
+ * ai.middleware.guardrail({ ... }),
27
+ * ];
28
+ *
29
+ * const toolRateLimits = [
30
+ * toolRateLimit({ tool: "search_web", maxCalls: 3 }),
31
+ * toolRateLimit({ tool: "expensive_api", maxCalls: 1 }),
32
+ * ];
33
+ *
34
+ * const myAgent = ai.agent({
35
+ * model,
36
+ * middleware: ai.middleware.compose(standardStack, toolRateLimits, auditMiddleware),
37
+ * });
38
+ */
39
+ declare function composeMiddleware(...sources: ReadonlyArray<AgentMiddleware | ReadonlyArray<AgentMiddleware>>): AgentMiddleware[];
40
+ //#endregion
41
+ export { composeMiddleware };
42
+ //# sourceMappingURL=compose.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"compose.d.mts","names":[],"sources":["../../../../../../../@warlock.js/ai/src/middleware/helpers/compose.ts"],"mappings":";;;;;AAsCA;;;;;;;;;;;;;;;;;AAEkB;;;;;;;;;;;;;;;;iBAFF,iBAAA,CAAA,GACX,OAAA,EAAS,aAAA,CAAc,eAAA,GAAkB,aAAA,CAAc,eAAA,KACzD,eAAA"}