@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,160 @@
1
+ import { ToolContract } from "../tool/tool.mjs";
2
+ import { Placeholders } from "../contracts/placeholders.type.mjs";
3
+ import { SystemPromptContract } from "../contracts/system-prompt.contract.mjs";
4
+ import { AgentEventMap } from "../contracts/events/event-map.type.mjs";
5
+ import { StreamingToolGuardConfig } from "../contracts/streaming-tool-guard-config.type.mjs";
6
+ import { ModelCallOptions, ModelContract } from "../contracts/model.contract.mjs";
7
+ import { AgentMiddleware } from "../contracts/middleware/middleware.contract.mjs";
8
+ import { CompleteEvent } from "../contracts/events/complete-event.type.mjs";
9
+ import { UsageEvent } from "../contracts/events/usage-event.type.mjs";
10
+ import { StandardSchemaV1 } from "@standard-schema/spec";
11
+
12
+ //#region ../../@warlock.js/ai/src/agent/agent-config.type.d.ts
13
+ /**
14
+ * Map of factory-level event handlers. Every key is optional; handlers
15
+ * registered here fire on every `execute()` / `stream()` call made
16
+ * through this agent, before instance-level and per-call handlers.
17
+ */
18
+ type AgentEventHandlers = Partial<{ [K in keyof AgentEventMap]: (payload: AgentEventMap[K]) => void }>;
19
+ /**
20
+ * Configuration passed to `agent()` to create an AgentContract instance.
21
+ *
22
+ * @example
23
+ * const config: AgentConfig<{ answer: string }> = {
24
+ * model: openai.model({ name: "gpt-4o" }),
25
+ * systemPrompt: "You are a helpful assistant.",
26
+ * tools: [searchTool, calculatorTool],
27
+ * placeholders: { language: "English" },
28
+ * maxTrips: 5,
29
+ * modelOptions: { temperature: 0.2 },
30
+ * };
31
+ *
32
+ * @example
33
+ * // With a SystemPromptContract instance
34
+ * const config: AgentConfig = {
35
+ * model: myModel,
36
+ * systemPrompt: systemPrompt
37
+ * .persona("You are Alex, a TypeScript expert")
38
+ * .instruction("Always respond in {{language|English}}"),
39
+ * placeholders: { language: "Arabic" },
40
+ * };
41
+ */
42
+ type AgentConfig<TOutput = unknown> = {
43
+ /**
44
+ * Stable identifier for this agent. Optional — when absent, the
45
+ * factory synthesizes a deterministic anonymous fingerprint
46
+ * (`anon_<provider>_<model>[_<tool>+...]`) used for logs and trace
47
+ * attribution.
48
+ *
49
+ * **Required at real boundaries:** boundaries that depend on *stable*
50
+ * agent identity (workflow signature drift detection when used as a
51
+ * step's `agent`, `agent.asTool()` wrapper) throw `WorkflowError` /
52
+ * `ToolError` if the agent is still anonymous. Pass a name whenever
53
+ * the agent will be composed into a higher-level primitive.
54
+ */
55
+ name?: string;
56
+ /**
57
+ * Short natural-language summary of what this agent does — the "when
58
+ * would a router pick this?" line. Used by `ai.supervisor()`'s router
59
+ * prompt and by `agent.asTool()` as the default tool description.
60
+ * Optional at the agent level; entries in a supervisor's `agents` map
61
+ * may override it per-use.
62
+ */
63
+ description?: string;
64
+ /**
65
+ * Dev-curated version string for this agent — free-form (semver,
66
+ * date, hash, anything). Stored on every report node this agent
67
+ * produces so trip-archive consumers can distinguish runs of "agent
68
+ * X v2.1" from "agent X v2.2" even when name + signature are
69
+ * identical.
70
+ *
71
+ * Bump when you change behavior in a way that matters to stored
72
+ * reports — prompt rewrite, model swap, tool list change. The
73
+ * framework neither parses nor compares it; signature drift
74
+ * detection remains independent.
75
+ */
76
+ version?: string; /** The model to use for LLM calls */
77
+ model: ModelContract;
78
+ /**
79
+ * System prompt for the agent. A plain string is treated as a single instruction.
80
+ * A SystemPromptContract gives full builder control with placeholder support.
81
+ */
82
+ systemPrompt?: SystemPromptContract | string; /** Tools exposed to the LLM during execution */
83
+ tools?: ToolContract<any, any>[]; /** Placeholder values merged into system prompt templates */
84
+ placeholders?: Placeholders;
85
+ /**
86
+ * Maximum number of LLM trips before aborting with an error.
87
+ * Prevents infinite tool-call loops. Defaults to 10.
88
+ */
89
+ maxTrips?: number; /** Base model call options merged with per-execute options (execute wins on conflict) */
90
+ modelOptions?: ModelCallOptions;
91
+ /**
92
+ * Default Standard Schema for structured output. Bakes the output
93
+ * contract into the agent's identity for agents whose shape never
94
+ * varies per call (title generators, intent classifiers, routers).
95
+ * `execute()` / `stream()` callers can still pass `options.output`
96
+ * to override for a single run — call-site fully replaces this,
97
+ * no merging.
98
+ */
99
+ output?: StandardSchemaV1<TOutput>;
100
+ /**
101
+ * Factory-level event handlers. Fire before instance-level `.on()`
102
+ * additions and before per-call `options.on` handlers on every
103
+ * `execute()` / `stream()` call.
104
+ */
105
+ on?: AgentEventHandlers;
106
+ /**
107
+ * Agent-level middleware pipeline. Each middleware may hook any
108
+ * subset of three levels: `execute` (wraps the whole run), `trip`
109
+ * (wraps each LLM round-trip), `tool` (wraps each tool dispatch).
110
+ *
111
+ * Registration order is execution order — `before` hooks run
112
+ * top-down, `after` / `onError` run bottom-up (onion model).
113
+ * Canonical install order: `[cache, budget, guardrail, observability]`.
114
+ *
115
+ * See `AgentMiddleware` for the full contract.
116
+ */
117
+ middleware?: AgentMiddleware[];
118
+ /**
119
+ * Opt-in stream-time guard that recovers a tool call when the model
120
+ * emits its structured input as **text** in the content channel
121
+ * instead of as a structured tool-call. Off when absent (faithful
122
+ * relay); `{}` enables it with defaults. Per-call
123
+ * `AgentExecuteOptions.streamingToolGuard` overrides this on a single
124
+ * `execute()` / `stream()` call. See {@link StreamingToolGuardConfig}
125
+ * for the full contract — limitations, latency tradeoff, matcher
126
+ * tier.
127
+ */
128
+ streamingToolGuard?: StreamingToolGuardConfig;
129
+ /**
130
+ * Per-trip usage callback. Fires once after every LLM round-trip
131
+ * (initial trip, continuation trips after tool results, repair
132
+ * trips) with a flat `{ runId, tripIndex, model, provider, usage,
133
+ * timestamp }` payload — pre-packaged so cost-ledger code can write
134
+ * one row per trip without joining identity from elsewhere.
135
+ *
136
+ * Sync or async. Errors thrown inside the hook are swallowed so
137
+ * consumer bugs cannot crash the agent loop.
138
+ *
139
+ * Distinct from the existing `agent.trip.completed` event — that
140
+ * event still fires for general subscribers; `onUsage` is the
141
+ * dedicated cost-attribution surface.
142
+ */
143
+ onUsage?: (event: UsageEvent) => void | Promise<void>;
144
+ /**
145
+ * Per-execution completion callback. Fires once at the end of every
146
+ * `agent.execute()` / `agent.stream()` call — completed, failed,
147
+ * cancelled. Receives the full `AgentResult` plus pre-extracted
148
+ * `runId` and end-to-end `durationMs`. Audit-log code subscribes
149
+ * here to write one `ai_runs` row per execution with the (redacted)
150
+ * report.
151
+ *
152
+ * Sync or async. Errors thrown inside the hook are swallowed.
153
+ *
154
+ * Distinct from the existing `agent.completed` event — both fire.
155
+ */
156
+ onComplete?: (event: CompleteEvent<TOutput>) => void | Promise<void>;
157
+ };
158
+ //#endregion
159
+ export { AgentConfig };
160
+ //# sourceMappingURL=agent-config.type.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"agent-config.type.d.mts","names":[],"sources":["../../../../../../@warlock.js/ai/src/agent/agent-config.type.ts"],"mappings":";;;;;;;;;;;;;;;AAgBA;;KAAY,kBAAA,GAAqB,OAAA,eACnB,aAAA,IAAiB,OAAA,EAAS,aAAA,CAAc,CAAA;;;;;;;;;;;;AAAE;AA0BxD;;;;;;;;;;;KAAY,WAAA;EA0FW;;;;;;;;;;;;EA7ErB,IAAA;EAuBO;;;;;;;EAfP,WAAA;EA+BA;;;;;;;;;;;;EAlBA,OAAA,WAuEW;EArEX,KAAA,EAAO,aAAA;EAkFP;;;;EA7EA,YAAA,GAAe,oBAAA,WA6E+C;EA3E9D,KAAA,GAAQ,YAAA;EAER,YAAA,GAAe,YAAA;;;;;EAKf,QAAA;EAEA,YAAA,GAAe,gBAAA;;;;;;;;;EASf,MAAA,GAAS,gBAAA,CAAiB,OAAA;;;;;;EAM1B,EAAA,GAAK,kBAAA;;;;;;;;;;;;EAYL,UAAA,GAAa,eAAA;;;;;;;;;;;EAWb,kBAAA,GAAqB,wBAAA;;;;;;;;;;;;;;;EAerB,OAAA,IAAW,KAAA,EAAO,UAAA,YAAsB,OAAA;;;;;;;;;;;;;EAaxC,UAAA,IAAc,KAAA,EAAO,aAAA,CAAc,OAAA,aAAoB,OAAA;AAAA"}
@@ -0,0 +1,111 @@
1
+ import { InvalidRequestError } from "../errors/invalid-request-error.mjs";
2
+ import "../errors/index.mjs";
3
+ import { extractJsonSchema } from "../utils/json-schema.mjs";
4
+ import { prepareAttachmentPart } from "../utils/prepare-attachment-part.mjs";
5
+ import "../utils/index.mjs";
6
+
7
+ //#region ../../@warlock.js/ai/src/agent/agent-input-builder.ts
8
+ /**
9
+ * Assemble the seed conversation for an agent execution. Runs exactly
10
+ * once per run — subsequent trips append to the same message list.
11
+ *
12
+ * Responsibilities (previously three methods on `Execution`):
13
+ * 1. Merge factory + per-call placeholders.
14
+ * 2. Resolve the system prompt (string, contract, or absent).
15
+ * 3. When an output schema is supplied:
16
+ * - cache its JSON Schema form for `ModelCallOptions.responseSchema`
17
+ * so native-structured-output providers enforce it at the token
18
+ * level;
19
+ * - fall back to a soft system-prompt instruction for providers
20
+ * that don't advertise `structuredOutput` capability.
21
+ * 4. Append caller-supplied `history` (e.g. session-level prior turns).
22
+ * 5. Shape the user message — plain string in the common case,
23
+ * multipart `ContentPart[]` when `attachments` are present. Image
24
+ * attachments require model vision capability; mismatch throws
25
+ * `InvalidRequestError` here rather than failing opaquely at the
26
+ * provider.
27
+ *
28
+ * Extracted from the `Execution` class to isolate the declarative
29
+ * input-shaping phase from the stateful trip loop.
30
+ */
31
+ async function buildAgentInputMessages(params) {
32
+ const { config, input, options } = params;
33
+ const placeholders = {
34
+ ...config.placeholders,
35
+ ...options?.placeholders
36
+ };
37
+ const systemPrompt = options?.systemPrompt ?? config.systemPrompt;
38
+ let systemContent = "";
39
+ if (typeof systemPrompt === "string") systemContent = systemPrompt;
40
+ else if (systemPrompt) systemContent = systemPrompt.resolve(placeholders);
41
+ const { responseSchema, instruction } = resolveStructuredOutput({
42
+ outputSchema: options?.output ?? config.output,
43
+ overrideResponseSchema: options?.responseSchema,
44
+ modelSupportsStructuredOutput: Boolean(config.model.capabilities?.structuredOutput)
45
+ });
46
+ if (instruction) systemContent = systemContent ? `${systemContent}\n\n${instruction}` : instruction;
47
+ const messages = [];
48
+ if (systemContent) messages.push({
49
+ role: "system",
50
+ content: systemContent
51
+ });
52
+ if (options?.history) messages.push(...options.history);
53
+ const userContent = await buildUserMessageContent({
54
+ input,
55
+ attachments: options?.attachments,
56
+ modelName: config.model.name,
57
+ modelSupportsVision: Boolean(config.model.capabilities?.vision)
58
+ });
59
+ messages.push({
60
+ role: "user",
61
+ content: userContent
62
+ });
63
+ return {
64
+ messages,
65
+ responseSchema
66
+ };
67
+ }
68
+ /**
69
+ * Build the user message `content` field. Plain string when no
70
+ * attachments (the hot path) — keeps wire payloads small. Multipart
71
+ * `ContentPart[]` when attachments exist: input text first, resolved
72
+ * parts in declaration order.
73
+ */
74
+ async function buildUserMessageContent(params) {
75
+ const { input, attachments, modelName, modelSupportsVision } = params;
76
+ if (!attachments || attachments.length === 0) return input;
77
+ const parts = await Promise.all(attachments.map((attachment) => prepareAttachmentPart(attachment)));
78
+ if (parts.some((part) => part.type === "image") && !modelSupportsVision) throw new InvalidRequestError(`Model "${modelName}" does not declare vision capability — image attachments are not supported`, { context: { modelName } });
79
+ return [{
80
+ type: "text",
81
+ text: input
82
+ }, ...parts];
83
+ }
84
+ /**
85
+ * When the caller supplied an `output` schema, resolve two artifacts:
86
+ *
87
+ * - `responseSchema` — extracted JSON Schema to attach on every trip.
88
+ * Adapters that natively support structured output (OpenAI's
89
+ * `response_format: json_schema`) consume it; others ignore it.
90
+ * - `instruction` — a soft fallback appended to the system prompt
91
+ * **only** for models without native structured-output capability.
92
+ * Capable adapters skip it to save tokens and avoid redundancy.
93
+ */
94
+ function resolveStructuredOutput(params) {
95
+ const { outputSchema, overrideResponseSchema, modelSupportsStructuredOutput } = params;
96
+ if (!outputSchema) return {};
97
+ const responseSchema = overrideResponseSchema ?? extractJsonSchema(outputSchema);
98
+ if (modelSupportsStructuredOutput) return { responseSchema };
99
+ return {
100
+ responseSchema,
101
+ instruction: [
102
+ "You MUST respond with a single valid JSON value only.",
103
+ "Do not wrap it in markdown code fences. Do not include prose, commentary, or explanation — JSON only.",
104
+ responseSchema ? `\n\nThe response MUST match this JSON Schema:\n${JSON.stringify(responseSchema, null, 2)}` : ""
105
+ ].join("").trim()
106
+ };
107
+ }
108
+
109
+ //#endregion
110
+ export { buildAgentInputMessages };
111
+ //# sourceMappingURL=agent-input-builder.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"agent-input-builder.mjs","names":[],"sources":["../../../../../../@warlock.js/ai/src/agent/agent-input-builder.ts"],"sourcesContent":["import type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport type { AgentExecuteOptions } from \"../contracts/agent/agent-options.type\";\nimport type { Attachment } from \"../contracts/attachment.type\";\nimport type { ContentPart } from \"../contracts/content-part.type\";\nimport type { Message } from \"../contracts/conversation-message.type\";\nimport type { Placeholders } from \"../contracts/placeholders.type\";\nimport { InvalidRequestError } from \"../errors\";\nimport { extractJsonSchema, prepareAttachmentPart } from \"../utils\";\nimport type { AgentConfig } from \"./agent-config.type\";\n\n/**\n * Outcome of `buildAgentInputMessages` — the seeded message list and\n * the JSON Schema cached for every trip's\n * `ModelCallOptions.responseSchema`. `responseSchema` is `undefined`\n * when the caller didn't ask for structured output.\n */\nexport type AgentInputBuildResult = {\n messages: Message[];\n responseSchema?: Record<string, unknown>;\n};\n\n/**\n * Assemble the seed conversation for an agent execution. Runs exactly\n * once per run — subsequent trips append to the same message list.\n *\n * Responsibilities (previously three methods on `Execution`):\n * 1. Merge factory + per-call placeholders.\n * 2. Resolve the system prompt (string, contract, or absent).\n * 3. When an output schema is supplied:\n * - cache its JSON Schema form for `ModelCallOptions.responseSchema`\n * so native-structured-output providers enforce it at the token\n * level;\n * - fall back to a soft system-prompt instruction for providers\n * that don't advertise `structuredOutput` capability.\n * 4. Append caller-supplied `history` (e.g. session-level prior turns).\n * 5. Shape the user message — plain string in the common case,\n * multipart `ContentPart[]` when `attachments` are present. Image\n * attachments require model vision capability; mismatch throws\n * `InvalidRequestError` here rather than failing opaquely at the\n * provider.\n *\n * Extracted from the `Execution` class to isolate the declarative\n * input-shaping phase from the stateful trip loop.\n */\nexport async function buildAgentInputMessages<TOutput>(params: {\n config: AgentConfig<TOutput>;\n input: string;\n options?: AgentExecuteOptions<TOutput>;\n}): Promise<AgentInputBuildResult> {\n const { config, input, options } = params;\n\n const placeholders: Placeholders = {\n ...config.placeholders,\n ...options?.placeholders,\n };\n\n const systemPrompt = options?.systemPrompt ?? config.systemPrompt;\n let systemContent = \"\";\n\n if (typeof systemPrompt === \"string\") {\n systemContent = systemPrompt;\n } else if (systemPrompt) {\n systemContent = systemPrompt.resolve(placeholders);\n }\n\n const { responseSchema, instruction } = resolveStructuredOutput({\n outputSchema: options?.output ?? config.output,\n overrideResponseSchema: options?.responseSchema,\n modelSupportsStructuredOutput: Boolean(config.model.capabilities?.structuredOutput),\n });\n\n if (instruction) {\n systemContent = systemContent ? `${systemContent}\\n\\n${instruction}` : instruction;\n }\n\n const messages: Message[] = [];\n\n if (systemContent) {\n messages.push({ role: \"system\", content: systemContent });\n }\n\n if (options?.history) {\n messages.push(...options.history);\n }\n\n const userContent = await buildUserMessageContent({\n input,\n attachments: options?.attachments,\n modelName: config.model.name,\n modelSupportsVision: Boolean(config.model.capabilities?.vision),\n });\n\n messages.push({ role: \"user\", content: userContent });\n\n return { messages, responseSchema };\n}\n\n/**\n * Build the user message `content` field. Plain string when no\n * attachments (the hot path) — keeps wire payloads small. Multipart\n * `ContentPart[]` when attachments exist: input text first, resolved\n * parts in declaration order.\n */\nasync function buildUserMessageContent(params: {\n input: string;\n attachments?: Attachment[];\n modelName: string;\n modelSupportsVision: boolean;\n}): Promise<string | ContentPart[]> {\n const { input, attachments, modelName, modelSupportsVision } = params;\n\n if (!attachments || attachments.length === 0) {\n return input;\n }\n\n const parts: ContentPart[] = await Promise.all(\n attachments.map((attachment) => prepareAttachmentPart(attachment)),\n );\n\n const hasImage = parts.some((part) => part.type === \"image\");\n\n if (hasImage && !modelSupportsVision) {\n throw new InvalidRequestError(\n `Model \"${modelName}\" does not declare vision capability — image attachments are not supported`,\n { context: { modelName } },\n );\n }\n\n return [{ type: \"text\", text: input }, ...parts];\n}\n\n/**\n * When the caller supplied an `output` schema, resolve two artifacts:\n *\n * - `responseSchema` — extracted JSON Schema to attach on every trip.\n * Adapters that natively support structured output (OpenAI's\n * `response_format: json_schema`) consume it; others ignore it.\n * - `instruction` — a soft fallback appended to the system prompt\n * **only** for models without native structured-output capability.\n * Capable adapters skip it to save tokens and avoid redundancy.\n */\nfunction resolveStructuredOutput(params: {\n outputSchema?: StandardSchemaV1<unknown>;\n overrideResponseSchema?: Record<string, unknown>;\n modelSupportsStructuredOutput: boolean;\n}): {\n responseSchema?: Record<string, unknown>;\n instruction?: string;\n} {\n const { outputSchema, overrideResponseSchema, modelSupportsStructuredOutput } = params;\n\n if (!outputSchema) {\n return {};\n }\n\n const responseSchema = overrideResponseSchema ?? extractJsonSchema(outputSchema);\n\n if (modelSupportsStructuredOutput) {\n return { responseSchema };\n }\n\n const schemaHint = responseSchema\n ? `\\n\\nThe response MUST match this JSON Schema:\\n${JSON.stringify(responseSchema, null, 2)}`\n : \"\";\n\n const instruction = [\n \"You MUST respond with a single valid JSON value only.\",\n \"Do not wrap it in markdown code fences. Do not include prose, commentary, or explanation — JSON only.\",\n schemaHint,\n ]\n .join(\"\")\n .trim();\n\n return { responseSchema, instruction };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4CA,eAAsB,wBAAiC,QAIpB;CACjC,MAAM,EAAE,QAAQ,OAAO,YAAY;CAEnC,MAAM,eAA6B;EACjC,GAAG,OAAO;EACV,GAAG,SAAS;CACd;CAEA,MAAM,eAAe,SAAS,gBAAgB,OAAO;CACrD,IAAI,gBAAgB;CAEpB,IAAI,OAAO,iBAAiB,UAC1B,gBAAgB;MACX,IAAI,cACT,gBAAgB,aAAa,QAAQ,YAAY;CAGnD,MAAM,EAAE,gBAAgB,gBAAgB,wBAAwB;EAC9D,cAAc,SAAS,UAAU,OAAO;EACxC,wBAAwB,SAAS;EACjC,+BAA+B,QAAQ,OAAO,MAAM,cAAc,gBAAgB;CACpF,CAAC;CAED,IAAI,aACF,gBAAgB,gBAAgB,GAAG,cAAc,MAAM,gBAAgB;CAGzE,MAAM,WAAsB,CAAC;CAE7B,IAAI,eACF,SAAS,KAAK;EAAE,MAAM;EAAU,SAAS;CAAc,CAAC;CAG1D,IAAI,SAAS,SACX,SAAS,KAAK,GAAG,QAAQ,OAAO;CAGlC,MAAM,cAAc,MAAM,wBAAwB;EAChD;EACA,aAAa,SAAS;EACtB,WAAW,OAAO,MAAM;EACxB,qBAAqB,QAAQ,OAAO,MAAM,cAAc,MAAM;CAChE,CAAC;CAED,SAAS,KAAK;EAAE,MAAM;EAAQ,SAAS;CAAY,CAAC;CAEpD,OAAO;EAAE;EAAU;CAAe;AACpC;;;;;;;AAQA,eAAe,wBAAwB,QAKH;CAClC,MAAM,EAAE,OAAO,aAAa,WAAW,wBAAwB;CAE/D,IAAI,CAAC,eAAe,YAAY,WAAW,GACzC,OAAO;CAGT,MAAM,QAAuB,MAAM,QAAQ,IACzC,YAAY,KAAK,eAAe,sBAAsB,UAAU,CAAC,CACnE;CAIA,IAFiB,MAAM,MAAM,SAAS,KAAK,SAAS,OAEzC,KAAK,CAAC,qBACf,MAAM,IAAI,oBACR,UAAU,UAAU,6EACpB,EAAE,SAAS,EAAE,UAAU,EAAE,CAC3B;CAGF,OAAO,CAAC;EAAE,MAAM;EAAQ,MAAM;CAAM,GAAG,GAAG,KAAK;AACjD;;;;;;;;;;;AAYA,SAAS,wBAAwB,QAO/B;CACA,MAAM,EAAE,cAAc,wBAAwB,kCAAkC;CAEhF,IAAI,CAAC,cACH,OAAO,CAAC;CAGV,MAAM,iBAAiB,0BAA0B,kBAAkB,YAAY;CAE/E,IAAI,+BACF,OAAO,EAAE,eAAe;CAe1B,OAAO;EAAE;EAAgB,aARL;GAClB;GACA;GANiB,iBACf,kDAAkD,KAAK,UAAU,gBAAgB,MAAM,CAAC,MACxF;EAMJ,EACG,KAAK,EAAE,EACP,KAEgC;CAAE;AACvC"}
@@ -0,0 +1,101 @@
1
+ //#region ../../@warlock.js/ai/src/agent/agent-log-event.ts
2
+ /**
3
+ * Structured logging for agent lifecycle events. Mirrors
4
+ * `Execution.emit`'s call sites without touching class state — the
5
+ * caller passes the ambient snapshot in `ctx`, we route each event to
6
+ * the right logger level and enrich with the per-event forensic
7
+ * detail.
8
+ *
9
+ * Log-level convention:
10
+ * - `info` — lifecycle boundaries (agent starting / completed) users
11
+ * want to see at default verbosity
12
+ * - `debug` — per-trip + per-tool progress (hot-path, opt-in)
13
+ * - `success` — trip completion + tool success (terminal per-step state)
14
+ * - `warn` — tool failures (recoverable, agent loop continues)
15
+ * - `error` — agent-level terminal errors
16
+ *
17
+ * Streaming deltas (`agent.trip.streaming`) are intentionally skipped
18
+ * to avoid token-granularity log spam.
19
+ */
20
+ function logAgentEvent(logger, ctx, event, payload) {
21
+ const action = event.replace(/^agent\./, "");
22
+ switch (event) {
23
+ case "agent.starting": {
24
+ const { input } = payload;
25
+ logger.info(ctx.module, action, "agent starting", {
26
+ maxTrips: ctx.maxTrips,
27
+ model: ctx.modelName,
28
+ inputLength: input.length
29
+ });
30
+ return;
31
+ }
32
+ case "agent.trip.started": {
33
+ const { tripIndex } = payload;
34
+ logger.debug(ctx.module, action, "trip started", { tripIndex });
35
+ return;
36
+ }
37
+ case "agent.trip.streaming": return;
38
+ case "agent.trip.completed": {
39
+ const { trip } = payload;
40
+ logger.success(ctx.module, action, "trip completed", {
41
+ tripIndex: trip.index,
42
+ duration: trip.duration,
43
+ usage: trip.usage,
44
+ finishReason: trip.finishReason
45
+ });
46
+ return;
47
+ }
48
+ case "agent.tool.calling": {
49
+ const { tool, tripIndex } = payload;
50
+ logger.debug(ctx.module, action, `calling tool "${tool.name}"`, {
51
+ tool: tool.name,
52
+ action: tool.action,
53
+ tripIndex
54
+ });
55
+ return;
56
+ }
57
+ case "agent.tool.called": {
58
+ const toolCall = payload;
59
+ logger.success(ctx.module, action, `tool "${toolCall.name}" finished`, {
60
+ tool: toolCall.name,
61
+ duration: toolCall.duration,
62
+ tripIndex: toolCall.tripIndex
63
+ });
64
+ return;
65
+ }
66
+ case "agent.tool.failed": {
67
+ const { tool, error, tripIndex } = payload;
68
+ logger.warn(ctx.module, action, `tool "${tool.name}" failed`, {
69
+ tool: tool.name,
70
+ tripIndex,
71
+ error: {
72
+ code: error.code,
73
+ message: error.message,
74
+ name: error.name,
75
+ stack: error.stack
76
+ }
77
+ });
78
+ return;
79
+ }
80
+ case "agent.completed":
81
+ logger.info(ctx.module, action, "agent completed", {
82
+ duration: ctx.totalDurationMs,
83
+ usage: ctx.totalUsage,
84
+ trips: ctx.trips.length,
85
+ tools: ctx.toolCalls.length
86
+ });
87
+ return;
88
+ case "agent.error": {
89
+ const { error } = payload;
90
+ logger.error(ctx.module, action, error.message, {
91
+ code: error.code,
92
+ context: error.context
93
+ });
94
+ return;
95
+ }
96
+ }
97
+ }
98
+
99
+ //#endregion
100
+ export { logAgentEvent };
101
+ //# sourceMappingURL=agent-log-event.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"agent-log-event.mjs","names":[],"sources":["../../../../../../@warlock.js/ai/src/agent/agent-log-event.ts"],"sourcesContent":["import type { Logger } from \"@warlock.js/logger\";\nimport type { AgentEventMap } from \"../contracts/events/event-map.type\";\nimport type { LLMTrip } from \"../contracts/result/llm-trip.type\";\nimport type { ToolCall } from \"../contracts/result/tool-call.type\";\nimport type { Usage } from \"../contracts/result/usage.type\";\n\n/**\n * Aggregate snapshot the agent-level log entries need at emission time\n * (agent completion + model name + running totals). Passed instead of\n * storing a back-reference to the Execution class — keeps this helper\n * a pure function.\n */\nexport type AgentLogContext = {\n /** Dotted logger module, e.g. `\"ai.agent.my-writer\"`. */\n module: string;\n /** Maximum trips configured for this run — logged once on `agent.starting`. */\n maxTrips: number;\n /** Model identifier — logged once on `agent.starting`. */\n modelName: string;\n /** Final running usage totals at the moment `agent.completed` fires. */\n totalUsage: Usage;\n /** Monotonic duration (ms) since start at the moment `agent.completed` fires. */\n totalDurationMs: number;\n /** All trips recorded so far — logged count on `agent.completed`. */\n trips: LLMTrip[];\n /** All tool calls recorded so far — logged count on `agent.completed`. */\n toolCalls: ToolCall[];\n};\n\n/**\n * Structured logging for agent lifecycle events. Mirrors\n * `Execution.emit`'s call sites without touching class state — the\n * caller passes the ambient snapshot in `ctx`, we route each event to\n * the right logger level and enrich with the per-event forensic\n * detail.\n *\n * Log-level convention:\n * - `info` — lifecycle boundaries (agent starting / completed) users\n * want to see at default verbosity\n * - `debug` — per-trip + per-tool progress (hot-path, opt-in)\n * - `success` — trip completion + tool success (terminal per-step state)\n * - `warn` — tool failures (recoverable, agent loop continues)\n * - `error` — agent-level terminal errors\n *\n * Streaming deltas (`agent.trip.streaming`) are intentionally skipped\n * to avoid token-granularity log spam.\n */\nexport function logAgentEvent<K extends keyof AgentEventMap>(\n logger: Logger,\n ctx: AgentLogContext,\n event: K,\n payload: AgentEventMap[K],\n): void {\n const action = event.replace(/^agent\\./, \"\");\n\n switch (event) {\n case \"agent.starting\": {\n const { input } = payload as AgentEventMap[\"agent.starting\"];\n logger.info(ctx.module, action, \"agent starting\", {\n maxTrips: ctx.maxTrips,\n model: ctx.modelName,\n inputLength: input.length,\n });\n return;\n }\n\n case \"agent.trip.started\": {\n const { tripIndex } = payload as AgentEventMap[\"agent.trip.started\"];\n logger.debug(ctx.module, action, \"trip started\", { tripIndex });\n return;\n }\n\n case \"agent.trip.streaming\": {\n // Deltas are too high-volume to log at token granularity.\n // Skipped on purpose; debug level still fires on trip boundaries.\n return;\n }\n\n case \"agent.trip.completed\": {\n const { trip } = payload as AgentEventMap[\"agent.trip.completed\"];\n logger.success(ctx.module, action, \"trip completed\", {\n tripIndex: trip.index,\n duration: trip.duration,\n usage: trip.usage,\n finishReason: trip.finishReason,\n });\n return;\n }\n\n case \"agent.tool.calling\": {\n const { tool, tripIndex } =\n payload as AgentEventMap[\"agent.tool.calling\"];\n logger.debug(ctx.module, action, `calling tool \"${tool.name}\"`, {\n tool: tool.name,\n action: tool.action,\n tripIndex,\n });\n return;\n }\n\n case \"agent.tool.called\": {\n const toolCall = payload as AgentEventMap[\"agent.tool.called\"];\n logger.success(ctx.module, action, `tool \"${toolCall.name}\" finished`, {\n tool: toolCall.name,\n duration: toolCall.duration,\n tripIndex: toolCall.tripIndex,\n });\n return;\n }\n\n case \"agent.tool.failed\": {\n const { tool, error, tripIndex } =\n payload as AgentEventMap[\"agent.tool.failed\"];\n logger.warn(ctx.module, action, `tool \"${tool.name}\" failed`, {\n tool: tool.name,\n tripIndex,\n error: {\n code: error.code,\n message: error.message,\n name: error.name,\n stack: error.stack,\n },\n });\n return;\n }\n\n case \"agent.completed\": {\n logger.info(ctx.module, action, \"agent completed\", {\n duration: ctx.totalDurationMs,\n usage: ctx.totalUsage,\n trips: ctx.trips.length,\n tools: ctx.toolCalls.length,\n });\n return;\n }\n\n case \"agent.error\": {\n const { error } = payload as AgentEventMap[\"agent.error\"];\n logger.error(ctx.module, action, error.message, {\n code: error.code,\n context: error.context,\n });\n return;\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AA+CA,SAAgB,cACd,QACA,KACA,OACA,SACM;CACN,MAAM,SAAS,MAAM,QAAQ,YAAY,EAAE;CAE3C,QAAQ,OAAR;EACE,KAAK,kBAAkB;GACrB,MAAM,EAAE,UAAU;GAClB,OAAO,KAAK,IAAI,QAAQ,QAAQ,kBAAkB;IAChD,UAAU,IAAI;IACd,OAAO,IAAI;IACX,aAAa,MAAM;GACrB,CAAC;GACD;EACF;EAEA,KAAK,sBAAsB;GACzB,MAAM,EAAE,cAAc;GACtB,OAAO,MAAM,IAAI,QAAQ,QAAQ,gBAAgB,EAAE,UAAU,CAAC;GAC9D;EACF;EAEA,KAAK,wBAGH;EAGF,KAAK,wBAAwB;GAC3B,MAAM,EAAE,SAAS;GACjB,OAAO,QAAQ,IAAI,QAAQ,QAAQ,kBAAkB;IACnD,WAAW,KAAK;IAChB,UAAU,KAAK;IACf,OAAO,KAAK;IACZ,cAAc,KAAK;GACrB,CAAC;GACD;EACF;EAEA,KAAK,sBAAsB;GACzB,MAAM,EAAE,MAAM,cACZ;GACF,OAAO,MAAM,IAAI,QAAQ,QAAQ,iBAAiB,KAAK,KAAK,IAAI;IAC9D,MAAM,KAAK;IACX,QAAQ,KAAK;IACb;GACF,CAAC;GACD;EACF;EAEA,KAAK,qBAAqB;GACxB,MAAM,WAAW;GACjB,OAAO,QAAQ,IAAI,QAAQ,QAAQ,SAAS,SAAS,KAAK,aAAa;IACrE,MAAM,SAAS;IACf,UAAU,SAAS;IACnB,WAAW,SAAS;GACtB,CAAC;GACD;EACF;EAEA,KAAK,qBAAqB;GACxB,MAAM,EAAE,MAAM,OAAO,cACnB;GACF,OAAO,KAAK,IAAI,QAAQ,QAAQ,SAAS,KAAK,KAAK,WAAW;IAC5D,MAAM,KAAK;IACX;IACA,OAAO;KACL,MAAM,MAAM;KACZ,SAAS,MAAM;KACf,MAAM,MAAM;KACZ,OAAO,MAAM;IACf;GACF,CAAC;GACD;EACF;EAEA,KAAK;GACH,OAAO,KAAK,IAAI,QAAQ,QAAQ,mBAAmB;IACjD,UAAU,IAAI;IACd,OAAO,IAAI;IACX,OAAO,IAAI,MAAM;IACjB,OAAO,IAAI,UAAU;GACvB,CAAC;GACD;EAGF,KAAK,eAAe;GAClB,MAAM,EAAE,UAAU;GAClB,OAAO,MAAM,IAAI,QAAQ,QAAQ,MAAM,SAAS;IAC9C,MAAM,MAAM;IACZ,SAAS,MAAM;GACjB,CAAC;GACD;EACF;CACF;AACF"}
@@ -0,0 +1,47 @@
1
+ import { StreamEvent } from "../contracts/stream/stream-event.type.mjs";
2
+ import { StreamContract } from "../contracts/stream/stream.contract.mjs";
3
+ //#region ../../@warlock.js/ai/src/agent/agent-stream.d.ts
4
+ /**
5
+ * Internal async-queue `StreamContract` used by `agent().stream()`.
6
+ *
7
+ * **Role.** The bridge between a streaming `Execution` (which runs in the
8
+ * background, pushing events as they happen) and a consumer that reads
9
+ * those events with `for await` or an `on(...)` handler map.
10
+ *
11
+ * **Responsibility.**
12
+ * - Owns: the event queue, the pending-read promise chain, the terminal
13
+ * `result` promise, and any user-registered event handlers.
14
+ * - Does NOT own: any knowledge of agents, models, or tool calls — it is a
15
+ * generic producer/consumer pipe parameterized by `TResult`. The streaming
16
+ * execution writes via `push()` / `end()` / `fail()`; the consumer reads
17
+ * via the AsyncIterable surface.
18
+ *
19
+ * Events are coalesced into a queue so that a consumer that starts
20
+ * iterating late still sees every event in order — nothing is dropped. The
21
+ * `on()` handlers fire the moment an event is pushed, independent of
22
+ * whether anyone is iterating.
23
+ *
24
+ * @example
25
+ * // Inside agent.stream():
26
+ * const { controller, stream } = createAgentStream<AgentResult<TOutput>>();
27
+ * new Execution(config, input, options, controller).run();
28
+ * return stream;
29
+ *
30
+ * // Consumer:
31
+ * for await (const event of stream) {
32
+ * if (event.type === "streaming") process.stdout.write(event.delta);
33
+ * }
34
+ * const result = await stream.result;
35
+ */
36
+ type StreamController<TResult> = {
37
+ push(event: StreamEvent): void;
38
+ end(result: TResult): void;
39
+ fail(error: Error): void;
40
+ };
41
+ declare function createAgentStream<TResult>(): {
42
+ controller: StreamController<TResult>;
43
+ stream: StreamContract<TResult>;
44
+ };
45
+ //#endregion
46
+ export { StreamController, createAgentStream };
47
+ //# sourceMappingURL=agent-stream.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"agent-stream.d.mts","names":[],"sources":["../../../../../../@warlock.js/ai/src/agent/agent-stream.ts"],"mappings":";;;;;;;AAkCA;;;;;;;;;;;;;;;;;;;AAGmB;AAQnB;;;;;;;;KAXY,gBAAA;EACV,IAAA,CAAK,KAAA,EAAO,WAAA;EACZ,GAAA,CAAI,MAAA,EAAQ,OAAA;EACZ,IAAA,CAAK,KAAA,EAAO,KAAA;AAAA;AAAA,iBAQE,iBAAA,SAAA,CAAA;EACd,UAAA,EAAY,gBAAA,CAAiB,OAAA;EAC7B,MAAA,EAAQ,cAAA,CAAe,OAAA;AAAA"}
@@ -0,0 +1,82 @@
1
+ //#region ../../@warlock.js/ai/src/agent/agent-stream.ts
2
+ function createAgentStream() {
3
+ const queue = [];
4
+ const pending = [];
5
+ const handlers = /* @__PURE__ */ new Map();
6
+ let closed = false;
7
+ let failure;
8
+ let resolveResult;
9
+ let rejectResult;
10
+ const result = new Promise((resolve, reject) => {
11
+ resolveResult = resolve;
12
+ rejectResult = reject;
13
+ });
14
+ const controller = {
15
+ push(event) {
16
+ const handler = handlers.get(event.type);
17
+ if (handler) try {
18
+ handler(event);
19
+ } catch {}
20
+ const reader = pending.shift();
21
+ if (reader) {
22
+ reader.resolve({
23
+ value: event,
24
+ done: false
25
+ });
26
+ return;
27
+ }
28
+ queue.push(event);
29
+ },
30
+ end(finalResult) {
31
+ closed = true;
32
+ resolveResult(finalResult);
33
+ while (pending.length > 0) pending.shift()?.resolve({
34
+ value: void 0,
35
+ done: true
36
+ });
37
+ },
38
+ fail(error) {
39
+ closed = true;
40
+ failure = error;
41
+ rejectResult(error);
42
+ while (pending.length > 0) pending.shift()?.reject(error);
43
+ }
44
+ };
45
+ const iterator = { next() {
46
+ if (queue.length > 0) return Promise.resolve({
47
+ value: queue.shift(),
48
+ done: false
49
+ });
50
+ if (closed) {
51
+ if (failure) return Promise.reject(failure);
52
+ return Promise.resolve({
53
+ value: void 0,
54
+ done: true
55
+ });
56
+ }
57
+ return new Promise((resolve, reject) => {
58
+ pending.push({
59
+ resolve,
60
+ reject
61
+ });
62
+ });
63
+ } };
64
+ const stream = {
65
+ result,
66
+ on(handlerMap) {
67
+ for (const [key, handler] of Object.entries(handlerMap)) if (handler) handlers.set(key, handler);
68
+ return stream;
69
+ },
70
+ [Symbol.asyncIterator]() {
71
+ return iterator;
72
+ }
73
+ };
74
+ return {
75
+ controller,
76
+ stream
77
+ };
78
+ }
79
+
80
+ //#endregion
81
+ export { createAgentStream };
82
+ //# sourceMappingURL=agent-stream.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"agent-stream.mjs","names":[],"sources":["../../../../../../@warlock.js/ai/src/agent/agent-stream.ts"],"sourcesContent":["import type { StreamContract, StreamEvent } from \"../contracts\";\n\n/**\n * Internal async-queue `StreamContract` used by `agent().stream()`.\n *\n * **Role.** The bridge between a streaming `Execution` (which runs in the\n * background, pushing events as they happen) and a consumer that reads\n * those events with `for await` or an `on(...)` handler map.\n *\n * **Responsibility.**\n * - Owns: the event queue, the pending-read promise chain, the terminal\n * `result` promise, and any user-registered event handlers.\n * - Does NOT own: any knowledge of agents, models, or tool calls — it is a\n * generic producer/consumer pipe parameterized by `TResult`. The streaming\n * execution writes via `push()` / `end()` / `fail()`; the consumer reads\n * via the AsyncIterable surface.\n *\n * Events are coalesced into a queue so that a consumer that starts\n * iterating late still sees every event in order — nothing is dropped. The\n * `on()` handlers fire the moment an event is pushed, independent of\n * whether anyone is iterating.\n *\n * @example\n * // Inside agent.stream():\n * const { controller, stream } = createAgentStream<AgentResult<TOutput>>();\n * new Execution(config, input, options, controller).run();\n * return stream;\n *\n * // Consumer:\n * for await (const event of stream) {\n * if (event.type === \"streaming\") process.stdout.write(event.delta);\n * }\n * const result = await stream.result;\n */\nexport type StreamController<TResult> = {\n push(event: StreamEvent): void;\n end(result: TResult): void;\n fail(error: Error): void;\n};\n\ntype PendingRead = {\n resolve(value: IteratorResult<StreamEvent>): void;\n reject(error: Error): void;\n};\n\nexport function createAgentStream<TResult>(): {\n controller: StreamController<TResult>;\n stream: StreamContract<TResult>;\n} {\n const queue: StreamEvent[] = [];\n const pending: PendingRead[] = [];\n const handlers = new Map<StreamEvent[\"type\"], (event: StreamEvent) => void>();\n\n let closed = false;\n let failure: Error | undefined;\n let resolveResult!: (value: TResult) => void;\n let rejectResult!: (error: Error) => void;\n\n const result = new Promise<TResult>((resolve, reject) => {\n resolveResult = resolve;\n rejectResult = reject;\n });\n\n const controller: StreamController<TResult> = {\n push(event) {\n const handler = handlers.get(event.type);\n\n if (handler) {\n try {\n handler(event);\n } catch {\n // User-provided stream handlers must never crash the agent.\n // Swallow — structured logging attaches here in Phase 0.5.\n }\n }\n\n const reader = pending.shift();\n\n if (reader) {\n reader.resolve({ value: event, done: false });\n return;\n }\n\n queue.push(event);\n },\n\n end(finalResult) {\n closed = true;\n resolveResult(finalResult);\n\n while (pending.length > 0) {\n const reader = pending.shift();\n\n reader?.resolve({ value: undefined, done: true });\n }\n },\n\n fail(error) {\n closed = true;\n failure = error;\n rejectResult(error);\n\n while (pending.length > 0) {\n const reader = pending.shift();\n\n reader?.reject(error);\n }\n },\n };\n\n const iterator: AsyncIterator<StreamEvent> = {\n next() {\n if (queue.length > 0) {\n return Promise.resolve({ value: queue.shift()!, done: false });\n }\n\n if (closed) {\n if (failure) {\n return Promise.reject(failure);\n }\n\n return Promise.resolve({ value: undefined, done: true });\n }\n\n return new Promise<IteratorResult<StreamEvent>>((resolve, reject) => {\n pending.push({ resolve, reject });\n });\n },\n };\n\n const stream: StreamContract<TResult> = {\n result,\n on(handlerMap) {\n for (const [key, handler] of Object.entries(handlerMap)) {\n if (handler) {\n handlers.set(\n key as StreamEvent[\"type\"],\n handler as (event: StreamEvent) => void,\n );\n }\n }\n\n return stream;\n },\n [Symbol.asyncIterator]() {\n return iterator;\n },\n };\n\n return { controller, stream };\n}\n"],"mappings":";AA6CA,SAAgB,oBAGd;CACA,MAAM,QAAuB,CAAC;CAC9B,MAAM,UAAyB,CAAC;CAChC,MAAM,2BAAW,IAAI,IAAuD;CAE5E,IAAI,SAAS;CACb,IAAI;CACJ,IAAI;CACJ,IAAI;CAEJ,MAAM,SAAS,IAAI,SAAkB,SAAS,WAAW;EACvD,gBAAgB;EAChB,eAAe;CACjB,CAAC;CAED,MAAM,aAAwC;EAC5C,KAAK,OAAO;GACV,MAAM,UAAU,SAAS,IAAI,MAAM,IAAI;GAEvC,IAAI,SACF,IAAI;IACF,QAAQ,KAAK;GACf,QAAQ,CAGR;GAGF,MAAM,SAAS,QAAQ,MAAM;GAE7B,IAAI,QAAQ;IACV,OAAO,QAAQ;KAAE,OAAO;KAAO,MAAM;IAAM,CAAC;IAC5C;GACF;GAEA,MAAM,KAAK,KAAK;EAClB;EAEA,IAAI,aAAa;GACf,SAAS;GACT,cAAc,WAAW;GAEzB,OAAO,QAAQ,SAAS,GAGtB,AAFe,QAAQ,MAElB,GAAG,QAAQ;IAAE,OAAO;IAAW,MAAM;GAAK,CAAC;EAEpD;EAEA,KAAK,OAAO;GACV,SAAS;GACT,UAAU;GACV,aAAa,KAAK;GAElB,OAAO,QAAQ,SAAS,GAGtB,AAFe,QAAQ,MAElB,GAAG,OAAO,KAAK;EAExB;CACF;CAEA,MAAM,WAAuC,EAC3C,OAAO;EACL,IAAI,MAAM,SAAS,GACjB,OAAO,QAAQ,QAAQ;GAAE,OAAO,MAAM,MAAM;GAAI,MAAM;EAAM,CAAC;EAG/D,IAAI,QAAQ;GACV,IAAI,SACF,OAAO,QAAQ,OAAO,OAAO;GAG/B,OAAO,QAAQ,QAAQ;IAAE,OAAO;IAAW,MAAM;GAAK,CAAC;EACzD;EAEA,OAAO,IAAI,SAAsC,SAAS,WAAW;GACnE,QAAQ,KAAK;IAAE;IAAS;GAAO,CAAC;EAClC,CAAC;CACH,EACF;CAEA,MAAM,SAAkC;EACtC;EACA,GAAG,YAAY;GACb,KAAK,MAAM,CAAC,KAAK,YAAY,OAAO,QAAQ,UAAU,GACpD,IAAI,SACF,SAAS,IACP,KACA,OACF;GAIJ,OAAO;EACT;EACA,CAAC,OAAO,iBAAiB;GACvB,OAAO;EACT;CACF;CAEA,OAAO;EAAE;EAAY;CAAO;AAC9B"}
@@ -0,0 +1,86 @@
1
+ //#region ../../@warlock.js/ai/src/agent/agent-to-stream-event.ts
2
+ /**
3
+ * Map an internal `AgentEventMap` entry into the public `StreamEvent`
4
+ * shape. Event names are the same dot-notation strings on both sides;
5
+ * only the payload shape needs per-event translation — the notable
6
+ * case is `agent.tool.called`, whose event-map payload is a bare
7
+ * `ToolCall` but whose stream wrapper is `{ toolCall }`.
8
+ *
9
+ * Extracted from the `Execution` class in `agent.ts` because it's
10
+ * fully stateless (pure function of event name + payload) and used
11
+ * only from the stream-forwarding path. Keeps the class focused on
12
+ * stateful orchestration.
13
+ */
14
+ function agentEventToStreamEvent(event, payload) {
15
+ switch (event) {
16
+ case "agent.starting": {
17
+ const { input } = payload;
18
+ return {
19
+ type: "agent.starting",
20
+ input
21
+ };
22
+ }
23
+ case "agent.trip.started": {
24
+ const { tripIndex, input } = payload;
25
+ return {
26
+ type: "agent.trip.started",
27
+ tripIndex,
28
+ input
29
+ };
30
+ }
31
+ case "agent.trip.streaming": {
32
+ const { delta, tripIndex } = payload;
33
+ return {
34
+ type: "agent.trip.streaming",
35
+ delta,
36
+ tripIndex
37
+ };
38
+ }
39
+ case "agent.tool.calling": {
40
+ const { tool, input, tripIndex } = payload;
41
+ return {
42
+ type: "agent.tool.calling",
43
+ tool,
44
+ input,
45
+ tripIndex
46
+ };
47
+ }
48
+ case "agent.tool.called": {
49
+ const { tool, ...toolCall } = payload;
50
+ return {
51
+ type: "agent.tool.called",
52
+ toolCall,
53
+ tool
54
+ };
55
+ }
56
+ case "agent.tool.failed": {
57
+ const { tool, error, tripIndex } = payload;
58
+ return {
59
+ type: "agent.tool.failed",
60
+ tool,
61
+ error,
62
+ tripIndex
63
+ };
64
+ }
65
+ case "agent.trip.completed": {
66
+ const { trip } = payload;
67
+ return {
68
+ type: "agent.trip.completed",
69
+ trip
70
+ };
71
+ }
72
+ case "agent.completed": return { type: "agent.completed" };
73
+ case "agent.error": {
74
+ const { error } = payload;
75
+ return {
76
+ type: "agent.error",
77
+ error
78
+ };
79
+ }
80
+ default: return;
81
+ }
82
+ }
83
+
84
+ //#endregion
85
+ export { agentEventToStreamEvent };
86
+ //# sourceMappingURL=agent-to-stream-event.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"agent-to-stream-event.mjs","names":["called"],"sources":["../../../../../../@warlock.js/ai/src/agent/agent-to-stream-event.ts"],"sourcesContent":["import type { AgentEventMap } from \"../contracts/events/event-map.type\";\nimport type { StreamEventBody } from \"../contracts/stream/stream-event.type\";\n\n/**\n * Map an internal `AgentEventMap` entry into the public `StreamEvent`\n * shape. Event names are the same dot-notation strings on both sides;\n * only the payload shape needs per-event translation — the notable\n * case is `agent.tool.called`, whose event-map payload is a bare\n * `ToolCall` but whose stream wrapper is `{ toolCall }`.\n *\n * Extracted from the `Execution` class in `agent.ts` because it's\n * fully stateless (pure function of event name + payload) and used\n * only from the stream-forwarding path. Keeps the class focused on\n * stateful orchestration.\n */\nexport function agentEventToStreamEvent<K extends keyof AgentEventMap>(\n event: K,\n payload: AgentEventMap[K],\n): StreamEventBody | undefined {\n switch (event) {\n case \"agent.starting\": {\n const { input } = payload as AgentEventMap[\"agent.starting\"];\n return { type: \"agent.starting\", input };\n }\n\n case \"agent.trip.started\": {\n const { tripIndex, input } =\n payload as AgentEventMap[\"agent.trip.started\"];\n return { type: \"agent.trip.started\", tripIndex, input };\n }\n\n case \"agent.trip.streaming\": {\n const { delta, tripIndex } =\n payload as AgentEventMap[\"agent.trip.streaming\"];\n return { type: \"agent.trip.streaming\", delta, tripIndex };\n }\n\n case \"agent.tool.calling\": {\n const { tool, input, tripIndex } =\n payload as AgentEventMap[\"agent.tool.calling\"];\n return { type: \"agent.tool.calling\", tool, input, tripIndex };\n }\n\n case \"agent.tool.called\": {\n const called = payload as AgentEventMap[\"agent.tool.called\"];\n // Split off the agent's enriched ToolCall record from the tool meta\n // so the stream event surface mirrors the bus payload shape.\n const { tool, ...toolCall } = called;\n return { type: \"agent.tool.called\", toolCall, tool };\n }\n\n case \"agent.tool.failed\": {\n const { tool, error, tripIndex } =\n payload as AgentEventMap[\"agent.tool.failed\"];\n return { type: \"agent.tool.failed\", tool, error, tripIndex };\n }\n\n case \"agent.trip.completed\": {\n const { trip } = payload as AgentEventMap[\"agent.trip.completed\"];\n return { type: \"agent.trip.completed\", trip };\n }\n\n case \"agent.completed\": {\n return { type: \"agent.completed\" };\n }\n\n case \"agent.error\": {\n const { error } = payload as AgentEventMap[\"agent.error\"];\n return { type: \"agent.error\", error };\n }\n\n default: {\n return undefined;\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;AAeA,SAAgB,wBACd,OACA,SAC6B;CAC7B,QAAQ,OAAR;EACE,KAAK,kBAAkB;GACrB,MAAM,EAAE,UAAU;GAClB,OAAO;IAAE,MAAM;IAAkB;GAAM;EACzC;EAEA,KAAK,sBAAsB;GACzB,MAAM,EAAE,WAAW,UACjB;GACF,OAAO;IAAE,MAAM;IAAsB;IAAW;GAAM;EACxD;EAEA,KAAK,wBAAwB;GAC3B,MAAM,EAAE,OAAO,cACb;GACF,OAAO;IAAE,MAAM;IAAwB;IAAO;GAAU;EAC1D;EAEA,KAAK,sBAAsB;GACzB,MAAM,EAAE,MAAM,OAAO,cACnB;GACF,OAAO;IAAE,MAAM;IAAsB;IAAM;IAAO;GAAU;EAC9D;EAEA,KAAK,qBAAqB;GAIxB,MAAM,EAAE,MAAM,GAAG,aAAaA;GAC9B,OAAO;IAAE,MAAM;IAAqB;IAAU;GAAK;EACrD;EAEA,KAAK,qBAAqB;GACxB,MAAM,EAAE,MAAM,OAAO,cACnB;GACF,OAAO;IAAE,MAAM;IAAqB;IAAM;IAAO;GAAU;EAC7D;EAEA,KAAK,wBAAwB;GAC3B,MAAM,EAAE,SAAS;GACjB,OAAO;IAAE,MAAM;IAAwB;GAAK;EAC9C;EAEA,KAAK,mBACH,OAAO,EAAE,MAAM,kBAAkB;EAGnC,KAAK,eAAe;GAClB,MAAM,EAAE,UAAU;GAClB,OAAO;IAAE,MAAM;IAAe;GAAM;EACtC;EAEA,SACE;CAEJ;AACF"}