@warlock.js/core 4.4.0 → 4.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (846) hide show
  1. package/CHANGELOG.md +45 -5
  2. package/README.md +47 -11
  3. package/esm/ai/src/agent/agent-input-builder.mjs +132 -0
  4. package/esm/ai/src/agent/agent-input-builder.mjs.map +1 -0
  5. package/esm/ai/src/agent/agent-log-event.mjs +101 -0
  6. package/esm/ai/src/agent/agent-log-event.mjs.map +1 -0
  7. package/esm/ai/src/agent/agent-stream.mjs +82 -0
  8. package/esm/ai/src/agent/agent-stream.mjs.map +1 -0
  9. package/esm/ai/src/agent/agent-to-stream-event.mjs +86 -0
  10. package/esm/ai/src/agent/agent-to-stream-event.mjs.map +1 -0
  11. package/esm/ai/src/agent/agent.mjs +1157 -0
  12. package/esm/ai/src/agent/agent.mjs.map +1 -0
  13. package/esm/ai/src/agent/index.mjs +5 -0
  14. package/esm/ai/src/agent/json-stream-guard.mjs +400 -0
  15. package/esm/ai/src/agent/json-stream-guard.mjs.map +1 -0
  16. package/esm/ai/src/agent/spawn-sub-agent.mjs +68 -0
  17. package/esm/ai/src/agent/spawn-sub-agent.mjs.map +1 -0
  18. package/esm/ai/src/ai.mjs +155 -0
  19. package/esm/ai/src/ai.mjs.map +1 -0
  20. package/esm/ai/src/batch/batch.mjs +198 -0
  21. package/esm/ai/src/batch/batch.mjs.map +1 -0
  22. package/esm/ai/src/batch/index.mjs +3 -0
  23. package/esm/ai/src/batch/run-batch-item.mjs +100 -0
  24. package/esm/ai/src/batch/run-batch-item.mjs.map +1 -0
  25. package/esm/ai/src/batch/run-with-concurrency.mjs +39 -0
  26. package/esm/ai/src/batch/run-with-concurrency.mjs.map +1 -0
  27. package/esm/ai/src/checkpoint/memory.mjs +0 -0
  28. package/esm/ai/src/checkpoint/memory.mjs.map +1 -0
  29. package/esm/ai/src/checkpoint/pg.mjs +265 -0
  30. package/esm/ai/src/checkpoint/pg.mjs.map +1 -0
  31. package/esm/ai/src/checkpoint/redis.mjs +200 -0
  32. package/esm/ai/src/checkpoint/redis.mjs.map +1 -0
  33. package/esm/ai/src/config.mjs +59 -0
  34. package/esm/ai/src/config.mjs.map +1 -0
  35. package/esm/ai/src/contracts/end.type.mjs +47 -0
  36. package/esm/ai/src/contracts/end.type.mjs.map +1 -0
  37. package/esm/ai/src/errors/agent-cancelled-error.mjs +43 -0
  38. package/esm/ai/src/errors/agent-cancelled-error.mjs.map +1 -0
  39. package/esm/ai/src/errors/agent-execution-error.mjs +35 -0
  40. package/esm/ai/src/errors/agent-execution-error.mjs.map +1 -0
  41. package/esm/ai/src/errors/agent-max-trips-error.mjs +41 -0
  42. package/esm/ai/src/errors/agent-max-trips-error.mjs.map +1 -0
  43. package/esm/ai/src/errors/ai-error.mjs +68 -0
  44. package/esm/ai/src/errors/ai-error.mjs.map +1 -0
  45. package/esm/ai/src/errors/budget-exceeded-error.mjs +31 -0
  46. package/esm/ai/src/errors/budget-exceeded-error.mjs.map +1 -0
  47. package/esm/ai/src/errors/content-filter-error.mjs +28 -0
  48. package/esm/ai/src/errors/content-filter-error.mjs.map +1 -0
  49. package/esm/ai/src/errors/context-length-exceeded-error.mjs +31 -0
  50. package/esm/ai/src/errors/context-length-exceeded-error.mjs.map +1 -0
  51. package/esm/ai/src/errors/guardrail-violation-error.mjs +41 -0
  52. package/esm/ai/src/errors/guardrail-violation-error.mjs.map +1 -0
  53. package/esm/ai/src/errors/index.mjs +37 -0
  54. package/esm/ai/src/errors/invalid-request-error.mjs +31 -0
  55. package/esm/ai/src/errors/invalid-request-error.mjs.map +1 -0
  56. package/esm/ai/src/errors/max-iterations-error.mjs +32 -0
  57. package/esm/ai/src/errors/max-iterations-error.mjs.map +1 -0
  58. package/esm/ai/src/errors/max-steps-exceeded-error.mjs +21 -0
  59. package/esm/ai/src/errors/max-steps-exceeded-error.mjs.map +1 -0
  60. package/esm/ai/src/errors/orchestrator-cancelled-error.mjs +31 -0
  61. package/esm/ai/src/errors/orchestrator-cancelled-error.mjs.map +1 -0
  62. package/esm/ai/src/errors/orchestrator-config-error.mjs +30 -0
  63. package/esm/ai/src/errors/orchestrator-config-error.mjs.map +1 -0
  64. package/esm/ai/src/errors/orchestrator-drift-error.mjs +37 -0
  65. package/esm/ai/src/errors/orchestrator-drift-error.mjs.map +1 -0
  66. package/esm/ai/src/errors/orchestrator-failed-error.mjs +36 -0
  67. package/esm/ai/src/errors/orchestrator-failed-error.mjs.map +1 -0
  68. package/esm/ai/src/errors/outbound-policy-error.mjs +32 -0
  69. package/esm/ai/src/errors/outbound-policy-error.mjs.map +1 -0
  70. package/esm/ai/src/errors/planner-cancelled-error.mjs +29 -0
  71. package/esm/ai/src/errors/planner-cancelled-error.mjs.map +1 -0
  72. package/esm/ai/src/errors/planner-failed-error.mjs +37 -0
  73. package/esm/ai/src/errors/planner-failed-error.mjs.map +1 -0
  74. package/esm/ai/src/errors/planner-plan-invalid-error.mjs +25 -0
  75. package/esm/ai/src/errors/planner-plan-invalid-error.mjs.map +1 -0
  76. package/esm/ai/src/errors/provider-auth-error.mjs +26 -0
  77. package/esm/ai/src/errors/provider-auth-error.mjs.map +1 -0
  78. package/esm/ai/src/errors/provider-error.mjs +42 -0
  79. package/esm/ai/src/errors/provider-error.mjs.map +1 -0
  80. package/esm/ai/src/errors/provider-rate-limit-error.mjs +31 -0
  81. package/esm/ai/src/errors/provider-rate-limit-error.mjs.map +1 -0
  82. package/esm/ai/src/errors/provider-timeout-error.mjs +26 -0
  83. package/esm/ai/src/errors/provider-timeout-error.mjs.map +1 -0
  84. package/esm/ai/src/errors/quota-exceeded-error.mjs +40 -0
  85. package/esm/ai/src/errors/quota-exceeded-error.mjs.map +1 -0
  86. package/esm/ai/src/errors/routing-error.mjs +23 -0
  87. package/esm/ai/src/errors/routing-error.mjs.map +1 -0
  88. package/esm/ai/src/errors/schema-validation-error.mjs +37 -0
  89. package/esm/ai/src/errors/schema-validation-error.mjs.map +1 -0
  90. package/esm/ai/src/errors/step-failed-error.mjs +19 -0
  91. package/esm/ai/src/errors/step-failed-error.mjs.map +1 -0
  92. package/esm/ai/src/errors/supervisor-cancelled-error.mjs +29 -0
  93. package/esm/ai/src/errors/supervisor-cancelled-error.mjs.map +1 -0
  94. package/esm/ai/src/errors/supervisor-drift-error.mjs +30 -0
  95. package/esm/ai/src/errors/supervisor-drift-error.mjs.map +1 -0
  96. package/esm/ai/src/errors/supervisor-failed-error.mjs +43 -0
  97. package/esm/ai/src/errors/supervisor-failed-error.mjs.map +1 -0
  98. package/esm/ai/src/errors/supervisor-routing-error.mjs +39 -0
  99. package/esm/ai/src/errors/supervisor-routing-error.mjs.map +1 -0
  100. package/esm/ai/src/errors/tool-execution-error.mjs +32 -0
  101. package/esm/ai/src/errors/tool-execution-error.mjs.map +1 -0
  102. package/esm/ai/src/errors/workflow-cancelled-error.mjs +23 -0
  103. package/esm/ai/src/errors/workflow-cancelled-error.mjs.map +1 -0
  104. package/esm/ai/src/errors/workflow-drift-error.mjs +24 -0
  105. package/esm/ai/src/errors/workflow-drift-error.mjs.map +1 -0
  106. package/esm/ai/src/errors/workflow-error.mjs +18 -0
  107. package/esm/ai/src/errors/workflow-error.mjs.map +1 -0
  108. package/esm/ai/src/eval/dataset.mjs +112 -0
  109. package/esm/ai/src/eval/dataset.mjs.map +1 -0
  110. package/esm/ai/src/eval/eval-runner.mjs +135 -0
  111. package/esm/ai/src/eval/eval-runner.mjs.map +1 -0
  112. package/esm/ai/src/eval/index.mjs +48 -0
  113. package/esm/ai/src/eval/index.mjs.map +1 -0
  114. package/esm/ai/src/eval/judge-scorer.mjs +87 -0
  115. package/esm/ai/src/eval/judge-scorer.mjs.map +1 -0
  116. package/esm/ai/src/eval/regression.mjs +51 -0
  117. package/esm/ai/src/eval/regression.mjs.map +1 -0
  118. package/esm/ai/src/eval/report-json.mjs +33 -0
  119. package/esm/ai/src/eval/report-json.mjs.map +1 -0
  120. package/esm/ai/src/eval/report-junit.mjs +60 -0
  121. package/esm/ai/src/eval/report-junit.mjs.map +1 -0
  122. package/esm/ai/src/eval/scorers.mjs +101 -0
  123. package/esm/ai/src/eval/scorers.mjs.map +1 -0
  124. package/esm/ai/src/guard/detectors/index.mjs +6 -0
  125. package/esm/ai/src/guard/detectors/injection.mjs +254 -0
  126. package/esm/ai/src/guard/detectors/injection.mjs.map +1 -0
  127. package/esm/ai/src/guard/detectors/moderation.mjs +134 -0
  128. package/esm/ai/src/guard/detectors/moderation.mjs.map +1 -0
  129. package/esm/ai/src/guard/detectors/pii.mjs +199 -0
  130. package/esm/ai/src/guard/detectors/pii.mjs.map +1 -0
  131. package/esm/ai/src/guard/detectors/topic.mjs +99 -0
  132. package/esm/ai/src/guard/detectors/topic.mjs.map +1 -0
  133. package/esm/ai/src/guard/errors.mjs +18 -0
  134. package/esm/ai/src/guard/errors.mjs.map +1 -0
  135. package/esm/ai/src/guard/guard.mjs +209 -0
  136. package/esm/ai/src/guard/guard.mjs.map +1 -0
  137. package/esm/ai/src/guard/guardrail.mjs +22 -0
  138. package/esm/ai/src/guard/guardrail.mjs.map +1 -0
  139. package/esm/ai/src/human/errors.mjs +60 -0
  140. package/esm/ai/src/human/errors.mjs.map +1 -0
  141. package/esm/ai/src/human/human-approval.mjs +170 -0
  142. package/esm/ai/src/human/human-approval.mjs.map +1 -0
  143. package/esm/ai/src/human/policy.mjs +67 -0
  144. package/esm/ai/src/human/policy.mjs.map +1 -0
  145. package/esm/ai/src/human/register.mjs +37 -0
  146. package/esm/ai/src/human/register.mjs.map +1 -0
  147. package/esm/ai/src/human/resume-seed.mjs +53 -0
  148. package/esm/ai/src/human/resume-seed.mjs.map +1 -0
  149. package/esm/ai/src/human/resume.mjs +121 -0
  150. package/esm/ai/src/human/resume.mjs.map +1 -0
  151. package/esm/ai/src/human/stores/index.mjs +5 -0
  152. package/esm/ai/src/human/stores/memory.mjs +91 -0
  153. package/esm/ai/src/human/stores/memory.mjs.map +1 -0
  154. package/esm/ai/src/human/stores/pg.mjs +220 -0
  155. package/esm/ai/src/human/stores/pg.mjs.map +1 -0
  156. package/esm/ai/src/human/stores/redis.mjs +201 -0
  157. package/esm/ai/src/human/stores/redis.mjs.map +1 -0
  158. package/esm/ai/src/index.mjs +174 -0
  159. package/esm/ai/src/memory/derive-id.mjs +24 -0
  160. package/esm/ai/src/memory/derive-id.mjs.map +1 -0
  161. package/esm/ai/src/memory/episodic-memory.mjs +106 -0
  162. package/esm/ai/src/memory/episodic-memory.mjs.map +1 -0
  163. package/esm/ai/src/memory/memory.mjs +166 -0
  164. package/esm/ai/src/memory/memory.mjs.map +1 -0
  165. package/esm/ai/src/memory/procedural-memory.mjs +103 -0
  166. package/esm/ai/src/memory/procedural-memory.mjs.map +1 -0
  167. package/esm/ai/src/memory/semantic-memory.mjs +80 -0
  168. package/esm/ai/src/memory/semantic-memory.mjs.map +1 -0
  169. package/esm/ai/src/memory/working-memory.mjs +62 -0
  170. package/esm/ai/src/memory/working-memory.mjs.map +1 -0
  171. package/esm/ai/src/middleware/builtins/budget.mjs +219 -0
  172. package/esm/ai/src/middleware/builtins/budget.mjs.map +1 -0
  173. package/esm/ai/src/middleware/builtins/guardrail.mjs +76 -0
  174. package/esm/ai/src/middleware/builtins/guardrail.mjs.map +1 -0
  175. package/esm/ai/src/middleware/builtins/semantic-cache.mjs +149 -0
  176. package/esm/ai/src/middleware/builtins/semantic-cache.mjs.map +1 -0
  177. package/esm/ai/src/middleware/helpers/compose.mjs +52 -0
  178. package/esm/ai/src/middleware/helpers/compose.mjs.map +1 -0
  179. package/esm/ai/src/middleware/helpers/for-tool.mjs +80 -0
  180. package/esm/ai/src/middleware/helpers/for-tool.mjs.map +1 -0
  181. package/esm/ai/src/middleware/index.mjs +10 -0
  182. package/esm/ai/src/middleware/pipeline.mjs +100 -0
  183. package/esm/ai/src/middleware/pipeline.mjs.map +1 -0
  184. package/esm/ai/src/middleware/utils/extract-user-text.mjs +47 -0
  185. package/esm/ai/src/middleware/utils/extract-user-text.mjs.map +1 -0
  186. package/esm/ai/src/middleware/utils/namespaced-state.mjs +60 -0
  187. package/esm/ai/src/middleware/utils/namespaced-state.mjs.map +1 -0
  188. package/esm/ai/src/mock/index.mjs +4 -0
  189. package/esm/ai/src/mock/mock-agent.mjs +3 -0
  190. package/esm/ai/src/mock/mock-router.mjs +58 -0
  191. package/esm/ai/src/mock/mock-router.mjs.map +1 -0
  192. package/esm/ai/src/model/fallback-model.mjs +218 -0
  193. package/esm/ai/src/model/fallback-model.mjs.map +1 -0
  194. package/esm/ai/src/model/index.mjs +3 -0
  195. package/esm/ai/src/object-stream/index.mjs +4 -0
  196. package/esm/ai/src/object-stream/parse-partial-json.mjs +78 -0
  197. package/esm/ai/src/object-stream/parse-partial-json.mjs.map +1 -0
  198. package/esm/ai/src/object-stream/stream-object.mjs +97 -0
  199. package/esm/ai/src/object-stream/stream-object.mjs.map +1 -0
  200. package/esm/ai/src/observe/index.mjs +4 -0
  201. package/esm/ai/src/observe/observer-registry.mjs +35 -0
  202. package/esm/ai/src/observe/observer-registry.mjs.map +1 -0
  203. package/esm/ai/src/observe/resolve-observers.mjs +73 -0
  204. package/esm/ai/src/observe/resolve-observers.mjs.map +1 -0
  205. package/esm/ai/src/orchestrator/as-tool.mjs +98 -0
  206. package/esm/ai/src/orchestrator/as-tool.mjs.map +1 -0
  207. package/esm/ai/src/orchestrator/checkpoint.mjs +75 -0
  208. package/esm/ai/src/orchestrator/checkpoint.mjs.map +1 -0
  209. package/esm/ai/src/orchestrator/commands.mjs +34 -0
  210. package/esm/ai/src/orchestrator/commands.mjs.map +1 -0
  211. package/esm/ai/src/orchestrator/compaction.mjs +206 -0
  212. package/esm/ai/src/orchestrator/compaction.mjs.map +1 -0
  213. package/esm/ai/src/orchestrator/dispatch.mjs +171 -0
  214. package/esm/ai/src/orchestrator/dispatch.mjs.map +1 -0
  215. package/esm/ai/src/orchestrator/emitter.mjs +85 -0
  216. package/esm/ai/src/orchestrator/emitter.mjs.map +1 -0
  217. package/esm/ai/src/orchestrator/execution.mjs +395 -0
  218. package/esm/ai/src/orchestrator/execution.mjs.map +1 -0
  219. package/esm/ai/src/orchestrator/index.mjs +11 -0
  220. package/esm/ai/src/orchestrator/load.mjs +49 -0
  221. package/esm/ai/src/orchestrator/load.mjs.map +1 -0
  222. package/esm/ai/src/orchestrator/lock.mjs +75 -0
  223. package/esm/ai/src/orchestrator/lock.mjs.map +1 -0
  224. package/esm/ai/src/orchestrator/memory.mjs +141 -0
  225. package/esm/ai/src/orchestrator/memory.mjs.map +1 -0
  226. package/esm/ai/src/orchestrator/orchestrator-stream.mjs +98 -0
  227. package/esm/ai/src/orchestrator/orchestrator-stream.mjs.map +1 -0
  228. package/esm/ai/src/orchestrator/orchestrator.mjs +206 -0
  229. package/esm/ai/src/orchestrator/orchestrator.mjs.map +1 -0
  230. package/esm/ai/src/orchestrator/resume.mjs +74 -0
  231. package/esm/ai/src/orchestrator/resume.mjs.map +1 -0
  232. package/esm/ai/src/orchestrator/session-lock.mjs +83 -0
  233. package/esm/ai/src/orchestrator/session-lock.mjs.map +1 -0
  234. package/esm/ai/src/orchestrator/signature.mjs +120 -0
  235. package/esm/ai/src/orchestrator/signature.mjs.map +1 -0
  236. package/esm/ai/src/orchestrator/window.mjs +56 -0
  237. package/esm/ai/src/orchestrator/window.mjs.map +1 -0
  238. package/esm/ai/src/planner/dag-scheduler.mjs +97 -0
  239. package/esm/ai/src/planner/dag-scheduler.mjs.map +1 -0
  240. package/esm/ai/src/planner/index.mjs +6 -0
  241. package/esm/ai/src/planner/plan-prompt.mjs +31 -0
  242. package/esm/ai/src/planner/plan-prompt.mjs.map +1 -0
  243. package/esm/ai/src/planner/plan-schema.mjs +120 -0
  244. package/esm/ai/src/planner/plan-schema.mjs.map +1 -0
  245. package/esm/ai/src/planner/planner-run.mjs +614 -0
  246. package/esm/ai/src/planner/planner-run.mjs.map +1 -0
  247. package/esm/ai/src/planner/planner.mjs +120 -0
  248. package/esm/ai/src/planner/planner.mjs.map +1 -0
  249. package/esm/ai/src/planner/signature.mjs +27 -0
  250. package/esm/ai/src/planner/signature.mjs.map +1 -0
  251. package/esm/ai/src/prompt/errors.mjs +73 -0
  252. package/esm/ai/src/prompt/errors.mjs.map +1 -0
  253. package/esm/ai/src/prompt/index.mjs +4 -0
  254. package/esm/ai/src/prompt/prompt-langfuse-sync.mjs +104 -0
  255. package/esm/ai/src/prompt/prompt-langfuse-sync.mjs.map +1 -0
  256. package/esm/ai/src/prompt/prompt-validate.mjs +170 -0
  257. package/esm/ai/src/prompt/prompt-validate.mjs.map +1 -0
  258. package/esm/ai/src/prompt/prompt.mjs +218 -0
  259. package/esm/ai/src/prompt/prompt.mjs.map +1 -0
  260. package/esm/ai/src/prompts/index.mjs +3 -0
  261. package/esm/ai/src/prompts/prompts-manager.mjs +410 -0
  262. package/esm/ai/src/prompts/prompts-manager.mjs.map +1 -0
  263. package/esm/ai/src/prompts/prompts-validate.mjs +200 -0
  264. package/esm/ai/src/prompts/prompts-validate.mjs.map +1 -0
  265. package/esm/ai/src/rag/as-tool.mjs +48 -0
  266. package/esm/ai/src/rag/as-tool.mjs.map +1 -0
  267. package/esm/ai/src/rag/chunk/chunk.mjs +44 -0
  268. package/esm/ai/src/rag/chunk/chunk.mjs.map +1 -0
  269. package/esm/ai/src/rag/chunk/fixed.mjs +32 -0
  270. package/esm/ai/src/rag/chunk/fixed.mjs.map +1 -0
  271. package/esm/ai/src/rag/chunk/markdown.mjs +75 -0
  272. package/esm/ai/src/rag/chunk/markdown.mjs.map +1 -0
  273. package/esm/ai/src/rag/chunk/recursive.mjs +132 -0
  274. package/esm/ai/src/rag/chunk/recursive.mjs.map +1 -0
  275. package/esm/ai/src/rag/chunk/sentence.mjs +73 -0
  276. package/esm/ai/src/rag/chunk/sentence.mjs.map +1 -0
  277. package/esm/ai/src/rag/index.mjs +7 -0
  278. package/esm/ai/src/rag/rag.mjs +126 -0
  279. package/esm/ai/src/rag/rag.mjs.map +1 -0
  280. package/esm/ai/src/rag/rerank/keyword-reranker.mjs +58 -0
  281. package/esm/ai/src/rag/rerank/keyword-reranker.mjs.map +1 -0
  282. package/esm/ai/src/rag/rerank/llm-reranker.mjs +85 -0
  283. package/esm/ai/src/rag/rerank/llm-reranker.mjs.map +1 -0
  284. package/esm/ai/src/rag/retrieve.mjs +68 -0
  285. package/esm/ai/src/rag/retrieve.mjs.map +1 -0
  286. package/esm/ai/src/rag/store/cache-vector-store.mjs +48 -0
  287. package/esm/ai/src/rag/store/cache-vector-store.mjs.map +1 -0
  288. package/esm/ai/src/security/index.mjs +5 -0
  289. package/esm/ai/src/security/outbound-policy.mjs +187 -0
  290. package/esm/ai/src/security/outbound-policy.mjs.map +1 -0
  291. package/esm/ai/src/security/private-ip.mjs +48 -0
  292. package/esm/ai/src/security/private-ip.mjs.map +1 -0
  293. package/esm/ai/src/security/redact.mjs +60 -0
  294. package/esm/ai/src/security/redact.mjs.map +1 -0
  295. package/esm/ai/src/serve/serve.mjs +90 -0
  296. package/esm/ai/src/serve/serve.mjs.map +1 -0
  297. package/esm/ai/src/serve/sse.mjs +25 -0
  298. package/esm/ai/src/serve/sse.mjs.map +1 -0
  299. package/esm/ai/src/serve/stream-to-sse.mjs +37 -0
  300. package/esm/ai/src/serve/stream-to-sse.mjs.map +1 -0
  301. package/esm/ai/src/skills/catalog.mjs +140 -0
  302. package/esm/ai/src/skills/catalog.mjs.map +1 -0
  303. package/esm/ai/src/skills/index.mjs +11 -0
  304. package/esm/ai/src/skills/load-skill-tool.mjs +65 -0
  305. package/esm/ai/src/skills/load-skill-tool.mjs.map +1 -0
  306. package/esm/ai/src/skills/save-skill-tool.mjs +65 -0
  307. package/esm/ai/src/skills/save-skill-tool.mjs.map +1 -0
  308. package/esm/ai/src/skills/skills.mjs +109 -0
  309. package/esm/ai/src/skills/skills.mjs.map +1 -0
  310. package/esm/ai/src/skills/sources/directory-source.mjs +108 -0
  311. package/esm/ai/src/skills/sources/directory-source.mjs.map +1 -0
  312. package/esm/ai/src/skills/sources/index.mjs +27 -0
  313. package/esm/ai/src/skills/sources/index.mjs.map +1 -0
  314. package/esm/ai/src/skills/sources/parse-frontmatter.mjs +46 -0
  315. package/esm/ai/src/skills/sources/parse-frontmatter.mjs.map +1 -0
  316. package/esm/ai/src/skills/sources/store-source.mjs +15 -0
  317. package/esm/ai/src/skills/sources/store-source.mjs.map +1 -0
  318. package/esm/ai/src/skills/sources/url-source.mjs +117 -0
  319. package/esm/ai/src/skills/sources/url-source.mjs.map +1 -0
  320. package/esm/ai/src/snapshot/memory.mjs +81 -0
  321. package/esm/ai/src/snapshot/memory.mjs.map +1 -0
  322. package/esm/ai/src/snapshot/pg.mjs +146 -0
  323. package/esm/ai/src/snapshot/pg.mjs.map +1 -0
  324. package/esm/ai/src/snapshot/redis.mjs +101 -0
  325. package/esm/ai/src/snapshot/redis.mjs.map +1 -0
  326. package/esm/ai/src/supervisor/as-tool.mjs +74 -0
  327. package/esm/ai/src/supervisor/as-tool.mjs.map +1 -0
  328. package/esm/ai/src/supervisor/cancellation.mjs +22 -0
  329. package/esm/ai/src/supervisor/cancellation.mjs.map +1 -0
  330. package/esm/ai/src/supervisor/decide.mjs +272 -0
  331. package/esm/ai/src/supervisor/decide.mjs.map +1 -0
  332. package/esm/ai/src/supervisor/emitter.mjs +47 -0
  333. package/esm/ai/src/supervisor/emitter.mjs.map +1 -0
  334. package/esm/ai/src/supervisor/entries.mjs +206 -0
  335. package/esm/ai/src/supervisor/entries.mjs.map +1 -0
  336. package/esm/ai/src/supervisor/execution.mjs +1921 -0
  337. package/esm/ai/src/supervisor/execution.mjs.map +1 -0
  338. package/esm/ai/src/supervisor/fan-out.mjs +65 -0
  339. package/esm/ai/src/supervisor/fan-out.mjs.map +1 -0
  340. package/esm/ai/src/supervisor/index.mjs +14 -0
  341. package/esm/ai/src/supervisor/router-factory.mjs +141 -0
  342. package/esm/ai/src/supervisor/router-factory.mjs.map +1 -0
  343. package/esm/ai/src/supervisor/router-prompt.mjs +52 -0
  344. package/esm/ai/src/supervisor/router-prompt.mjs.map +1 -0
  345. package/esm/ai/src/supervisor/signature.mjs +89 -0
  346. package/esm/ai/src/supervisor/signature.mjs.map +1 -0
  347. package/esm/ai/src/supervisor/snapshot.mjs +69 -0
  348. package/esm/ai/src/supervisor/snapshot.mjs.map +1 -0
  349. package/esm/ai/src/supervisor/supervisor-stream.mjs +89 -0
  350. package/esm/ai/src/supervisor/supervisor-stream.mjs.map +1 -0
  351. package/esm/ai/src/supervisor/supervisor.mjs +144 -0
  352. package/esm/ai/src/supervisor/supervisor.mjs.map +1 -0
  353. package/esm/ai/src/system-prompt/index.mjs +6 -0
  354. package/esm/ai/src/system-prompt/instruction.mjs +57 -0
  355. package/esm/ai/src/system-prompt/instruction.mjs.map +1 -0
  356. package/esm/ai/src/system-prompt/persona.mjs +57 -0
  357. package/esm/ai/src/system-prompt/persona.mjs.map +1 -0
  358. package/esm/ai/src/system-prompt/render-placeholders.mjs +58 -0
  359. package/esm/ai/src/system-prompt/render-placeholders.mjs.map +1 -0
  360. package/esm/ai/src/system-prompt/system-prompt.mjs +267 -0
  361. package/esm/ai/src/system-prompt/system-prompt.mjs.map +1 -0
  362. package/esm/ai/src/team/gates.mjs +48 -0
  363. package/esm/ai/src/team/gates.mjs.map +1 -0
  364. package/esm/ai/src/team/index.mjs +3 -0
  365. package/esm/ai/src/team/team.mjs +94 -0
  366. package/esm/ai/src/team/team.mjs.map +1 -0
  367. package/esm/ai/src/tool/executable-as-tool.mjs +81 -0
  368. package/esm/ai/src/tool/executable-as-tool.mjs.map +1 -0
  369. package/esm/ai/src/tool/index.mjs +4 -0
  370. package/esm/ai/src/tool/tool.mjs +185 -0
  371. package/esm/ai/src/tool/tool.mjs.map +1 -0
  372. package/esm/ai/src/utils/compute-cost.mjs +112 -0
  373. package/esm/ai/src/utils/compute-cost.mjs.map +1 -0
  374. package/esm/ai/src/utils/extract-json-lenient.mjs +97 -0
  375. package/esm/ai/src/utils/extract-json-lenient.mjs.map +1 -0
  376. package/esm/ai/src/utils/extract-json-payload.mjs +39 -0
  377. package/esm/ai/src/utils/extract-json-payload.mjs.map +1 -0
  378. package/esm/ai/src/utils/generate-run-id.mjs +23 -0
  379. package/esm/ai/src/utils/generate-run-id.mjs.map +1 -0
  380. package/esm/ai/src/utils/index.mjs +12 -0
  381. package/esm/ai/src/utils/json-schema.mjs +89 -0
  382. package/esm/ai/src/utils/json-schema.mjs.map +1 -0
  383. package/esm/ai/src/utils/prepare-attachment-part.mjs +232 -0
  384. package/esm/ai/src/utils/prepare-attachment-part.mjs.map +1 -0
  385. package/esm/ai/src/utils/resolve-attachment.mjs +74 -0
  386. package/esm/ai/src/utils/resolve-attachment.mjs.map +1 -0
  387. package/esm/ai/src/utils/run-context.mjs +89 -0
  388. package/esm/ai/src/utils/run-context.mjs.map +1 -0
  389. package/esm/ai/src/utils/safe-json-parse.mjs +22 -0
  390. package/esm/ai/src/utils/safe-json-parse.mjs.map +1 -0
  391. package/esm/ai/src/utils/stamp-report-lineage.mjs +45 -0
  392. package/esm/ai/src/utils/stamp-report-lineage.mjs.map +1 -0
  393. package/esm/ai/src/vcr/cassette-io.mjs +57 -0
  394. package/esm/ai/src/vcr/cassette-io.mjs.map +1 -0
  395. package/esm/ai/src/vcr/errors.mjs +37 -0
  396. package/esm/ai/src/vcr/errors.mjs.map +1 -0
  397. package/esm/ai/src/vcr/hash-request.mjs +118 -0
  398. package/esm/ai/src/vcr/hash-request.mjs.map +1 -0
  399. package/esm/ai/src/vcr/index.mjs +5 -0
  400. package/esm/ai/src/vcr/vcr.mjs +248 -0
  401. package/esm/ai/src/vcr/vcr.mjs.map +1 -0
  402. package/esm/ai/src/workflow/as-tool.mjs +49 -0
  403. package/esm/ai/src/workflow/as-tool.mjs.map +1 -0
  404. package/esm/ai/src/workflow/cancellation.mjs +44 -0
  405. package/esm/ai/src/workflow/cancellation.mjs.map +1 -0
  406. package/esm/ai/src/workflow/emitter.mjs +40 -0
  407. package/esm/ai/src/workflow/emitter.mjs.map +1 -0
  408. package/esm/ai/src/workflow/engine.mjs +363 -0
  409. package/esm/ai/src/workflow/engine.mjs.map +1 -0
  410. package/esm/ai/src/workflow/index.mjs +5 -0
  411. package/esm/ai/src/workflow/retry.mjs +32 -0
  412. package/esm/ai/src/workflow/retry.mjs.map +1 -0
  413. package/esm/ai/src/workflow/router.mjs +56 -0
  414. package/esm/ai/src/workflow/router.mjs.map +1 -0
  415. package/esm/ai/src/workflow/run-scoped-emitter.mjs +32 -0
  416. package/esm/ai/src/workflow/run-scoped-emitter.mjs.map +1 -0
  417. package/esm/ai/src/workflow/signature.mjs +34 -0
  418. package/esm/ai/src/workflow/signature.mjs.map +1 -0
  419. package/esm/ai/src/workflow/snapshot.mjs +77 -0
  420. package/esm/ai/src/workflow/snapshot.mjs.map +1 -0
  421. package/esm/ai/src/workflow/state.mjs +37 -0
  422. package/esm/ai/src/workflow/state.mjs.map +1 -0
  423. package/esm/ai/src/workflow/step-runner.mjs +370 -0
  424. package/esm/ai/src/workflow/step-runner.mjs.map +1 -0
  425. package/esm/ai/src/workflow/step.mjs +37 -0
  426. package/esm/ai/src/workflow/step.mjs.map +1 -0
  427. package/esm/ai/src/workflow/workflow.mjs +122 -0
  428. package/esm/ai/src/workflow/workflow.mjs.map +1 -0
  429. package/esm/ai-openai/src/embedder.mjs +4 -0
  430. package/esm/ai-openai/src/index.mjs +4 -0
  431. package/esm/ai-openai/src/model.mjs +5 -0
  432. package/esm/ai-openai/src/sdk.mjs +6 -0
  433. package/esm/ai-openai/src/utils/index.mjs +4 -0
  434. package/esm/ai-openai/src/utils/to-openai-tools.mjs +3 -0
  435. package/esm/ai-openai/src/utils/wrap-openai-error.mjs +4 -0
  436. package/esm/cli/commands/dev-server.command.mjs +1 -1
  437. package/esm/cli/commands/dev-server.command.mjs.map +1 -1
  438. package/esm/cli/commands/generate/templates/stubs.mjs +3 -4
  439. package/esm/cli/commands/generate/templates/stubs.mjs.map +1 -1
  440. package/esm/connectors/ai-connector.d.mts +43 -0
  441. package/esm/connectors/ai-connector.d.mts.map +1 -0
  442. package/esm/connectors/ai-connector.mjs +56 -0
  443. package/esm/connectors/ai-connector.mjs.map +1 -0
  444. package/esm/connectors/cache-connector.d.mts +5 -0
  445. package/esm/connectors/cache-connector.d.mts.map +1 -1
  446. package/esm/connectors/cache-connector.mjs +7 -0
  447. package/esm/connectors/cache-connector.mjs.map +1 -1
  448. package/esm/connectors/connectors-manager.d.mts +6 -2
  449. package/esm/connectors/connectors-manager.d.mts.map +1 -1
  450. package/esm/connectors/connectors-manager.mjs +8 -2
  451. package/esm/connectors/connectors-manager.mjs.map +1 -1
  452. package/esm/connectors/http-connector.mjs.map +1 -1
  453. package/esm/connectors/index.d.mts +1 -0
  454. package/esm/connectors/index.mjs +1 -0
  455. package/esm/connectors/socket-connector.d.mts +16 -1
  456. package/esm/connectors/socket-connector.d.mts.map +1 -1
  457. package/esm/connectors/socket-connector.mjs +28 -5
  458. package/esm/connectors/socket-connector.mjs.map +1 -1
  459. package/esm/connectors/storage.connector.d.mts +7 -0
  460. package/esm/connectors/storage.connector.d.mts.map +1 -1
  461. package/esm/connectors/storage.connector.mjs +7 -0
  462. package/esm/connectors/storage.connector.mjs.map +1 -1
  463. package/esm/connectors/types.d.mts +3 -2
  464. package/esm/connectors/types.d.mts.map +1 -1
  465. package/esm/connectors/types.mjs +1 -0
  466. package/esm/connectors/types.mjs.map +1 -1
  467. package/esm/dev-server/development-server.mjs +2 -14
  468. package/esm/dev-server/development-server.mjs.map +1 -1
  469. package/esm/dev-server/file-event-handler.mjs +15 -3
  470. package/esm/dev-server/file-event-handler.mjs.map +1 -1
  471. package/esm/generations/add-command.action.mjs +61 -12
  472. package/esm/generations/add-command.action.mjs.map +1 -1
  473. package/esm/generations/stubs.mjs +31 -1
  474. package/esm/generations/stubs.mjs.map +1 -1
  475. package/esm/http/middleware/cache-response-middleware.d.mts +1 -1
  476. package/esm/http/middleware/cache-response-middleware.d.mts.map +1 -1
  477. package/esm/http/middleware/cache-response-middleware.mjs +15 -6
  478. package/esm/http/middleware/cache-response-middleware.mjs.map +1 -1
  479. package/esm/http/middleware/concurrency-limit.middleware.mjs +2 -0
  480. package/esm/http/middleware/concurrency-limit.middleware.mjs.map +1 -1
  481. package/esm/http/middleware/idempotency.middleware.d.mts.map +1 -1
  482. package/esm/http/middleware/idempotency.middleware.mjs +4 -1
  483. package/esm/http/middleware/idempotency.middleware.mjs.map +1 -1
  484. package/esm/http/middleware/maintenance.middleware.mjs +2 -1
  485. package/esm/http/middleware/maintenance.middleware.mjs.map +1 -1
  486. package/esm/http/request.d.mts +9 -2
  487. package/esm/http/request.d.mts.map +1 -1
  488. package/esm/http/request.mjs +15 -3
  489. package/esm/http/request.mjs.map +1 -1
  490. package/esm/http/response.d.mts +12 -0
  491. package/esm/http/response.d.mts.map +1 -1
  492. package/esm/http/response.mjs +19 -2
  493. package/esm/http/response.mjs.map +1 -1
  494. package/esm/http/server.d.mts.map +1 -1
  495. package/esm/http/server.mjs +1 -1
  496. package/esm/http/server.mjs.map +1 -1
  497. package/esm/index.d.mts +6 -2
  498. package/esm/index.mjs +5 -1
  499. package/esm/node_modules/langfuse/lib/index.mjs +1827 -0
  500. package/esm/node_modules/langfuse/lib/index.mjs.map +1 -0
  501. package/esm/node_modules/langfuse-core/lib/index.mjs +1770 -0
  502. package/esm/node_modules/langfuse-core/lib/index.mjs.map +1 -0
  503. package/esm/node_modules/mustache/mustache.mjs +587 -0
  504. package/esm/node_modules/mustache/mustache.mjs.map +1 -0
  505. package/esm/node_modules/openai/_vendor/partial-json-parser/parser.mjs +180 -0
  506. package/esm/node_modules/openai/_vendor/partial-json-parser/parser.mjs.map +1 -0
  507. package/esm/node_modules/openai/auth/workload-identity-auth.mjs +80 -0
  508. package/esm/node_modules/openai/auth/workload-identity-auth.mjs.map +1 -0
  509. package/esm/node_modules/openai/azure.mjs +82 -0
  510. package/esm/node_modules/openai/azure.mjs.map +1 -0
  511. package/esm/node_modules/openai/client.mjs +638 -0
  512. package/esm/node_modules/openai/client.mjs.map +1 -0
  513. package/esm/node_modules/openai/core/api-promise.mjs +75 -0
  514. package/esm/node_modules/openai/core/api-promise.mjs.map +1 -0
  515. package/esm/node_modules/openai/core/error.mjs +110 -0
  516. package/esm/node_modules/openai/core/error.mjs.map +1 -0
  517. package/esm/node_modules/openai/core/pagination.mjs +160 -0
  518. package/esm/node_modules/openai/core/pagination.mjs.map +1 -0
  519. package/esm/node_modules/openai/core/resource.mjs +10 -0
  520. package/esm/node_modules/openai/core/resource.mjs.map +1 -0
  521. package/esm/node_modules/openai/core/streaming.mjs +238 -0
  522. package/esm/node_modules/openai/core/streaming.mjs.map +1 -0
  523. package/esm/node_modules/openai/index.mjs +8 -0
  524. package/esm/node_modules/openai/internal/decoders/line.mjs +91 -0
  525. package/esm/node_modules/openai/internal/decoders/line.mjs.map +1 -0
  526. package/esm/node_modules/openai/internal/detect-platform.mjs +123 -0
  527. package/esm/node_modules/openai/internal/detect-platform.mjs.map +1 -0
  528. package/esm/node_modules/openai/internal/errors.mjs +26 -0
  529. package/esm/node_modules/openai/internal/errors.mjs.map +1 -0
  530. package/esm/node_modules/openai/internal/headers.mjs +65 -0
  531. package/esm/node_modules/openai/internal/headers.mjs.map +1 -0
  532. package/esm/node_modules/openai/internal/parse.mjs +41 -0
  533. package/esm/node_modules/openai/internal/parse.mjs.map +1 -0
  534. package/esm/node_modules/openai/internal/qs/formats.mjs +12 -0
  535. package/esm/node_modules/openai/internal/qs/formats.mjs.map +1 -0
  536. package/esm/node_modules/openai/internal/qs/stringify.mjs +179 -0
  537. package/esm/node_modules/openai/internal/qs/stringify.mjs.map +1 -0
  538. package/esm/node_modules/openai/internal/qs/utils.mjs +65 -0
  539. package/esm/node_modules/openai/internal/qs/utils.mjs.map +1 -0
  540. package/esm/node_modules/openai/internal/request-options.mjs +11 -0
  541. package/esm/node_modules/openai/internal/request-options.mjs.map +1 -0
  542. package/esm/node_modules/openai/internal/shims.mjs +77 -0
  543. package/esm/node_modules/openai/internal/shims.mjs.map +1 -0
  544. package/esm/node_modules/openai/internal/to-file.mjs +63 -0
  545. package/esm/node_modules/openai/internal/to-file.mjs.map +1 -0
  546. package/esm/node_modules/openai/internal/tslib.mjs +16 -0
  547. package/esm/node_modules/openai/internal/tslib.mjs.map +1 -0
  548. package/esm/node_modules/openai/internal/uploads.mjs +94 -0
  549. package/esm/node_modules/openai/internal/uploads.mjs.map +1 -0
  550. package/esm/node_modules/openai/internal/utils/base64.mjs +22 -0
  551. package/esm/node_modules/openai/internal/utils/base64.mjs.map +1 -0
  552. package/esm/node_modules/openai/internal/utils/bytes.mjs +26 -0
  553. package/esm/node_modules/openai/internal/utils/bytes.mjs.map +1 -0
  554. package/esm/node_modules/openai/internal/utils/env.mjs +16 -0
  555. package/esm/node_modules/openai/internal/utils/env.mjs.map +1 -0
  556. package/esm/node_modules/openai/internal/utils/log.mjs +58 -0
  557. package/esm/node_modules/openai/internal/utils/log.mjs.map +1 -0
  558. package/esm/node_modules/openai/internal/utils/path.mjs +62 -0
  559. package/esm/node_modules/openai/internal/utils/path.mjs.map +1 -0
  560. package/esm/node_modules/openai/internal/utils/query.mjs +10 -0
  561. package/esm/node_modules/openai/internal/utils/query.mjs.map +1 -0
  562. package/esm/node_modules/openai/internal/utils/sleep.mjs +6 -0
  563. package/esm/node_modules/openai/internal/utils/sleep.mjs.map +1 -0
  564. package/esm/node_modules/openai/internal/utils/uuid.mjs +18 -0
  565. package/esm/node_modules/openai/internal/utils/uuid.mjs.map +1 -0
  566. package/esm/node_modules/openai/internal/utils/values.mjs +41 -0
  567. package/esm/node_modules/openai/internal/utils/values.mjs.map +1 -0
  568. package/esm/node_modules/openai/lib/AbstractChatCompletionRunner.mjs +247 -0
  569. package/esm/node_modules/openai/lib/AbstractChatCompletionRunner.mjs.map +1 -0
  570. package/esm/node_modules/openai/lib/AssistantStream.mjs +472 -0
  571. package/esm/node_modules/openai/lib/AssistantStream.mjs.map +1 -0
  572. package/esm/node_modules/openai/lib/ChatCompletionRunner.mjs +26 -0
  573. package/esm/node_modules/openai/lib/ChatCompletionRunner.mjs.map +1 -0
  574. package/esm/node_modules/openai/lib/ChatCompletionStream.mjs +423 -0
  575. package/esm/node_modules/openai/lib/ChatCompletionStream.mjs.map +1 -0
  576. package/esm/node_modules/openai/lib/ChatCompletionStreamingRunner.mjs +26 -0
  577. package/esm/node_modules/openai/lib/ChatCompletionStreamingRunner.mjs.map +1 -0
  578. package/esm/node_modules/openai/lib/EventStream.mjs +163 -0
  579. package/esm/node_modules/openai/lib/EventStream.mjs.map +1 -0
  580. package/esm/node_modules/openai/lib/ResponsesParser.mjs +94 -0
  581. package/esm/node_modules/openai/lib/ResponsesParser.mjs.map +1 -0
  582. package/esm/node_modules/openai/lib/RunnableFunction.mjs +8 -0
  583. package/esm/node_modules/openai/lib/RunnableFunction.mjs.map +1 -0
  584. package/esm/node_modules/openai/lib/Util.mjs +19 -0
  585. package/esm/node_modules/openai/lib/Util.mjs.map +1 -0
  586. package/esm/node_modules/openai/lib/chatCompletionUtils.mjs +11 -0
  587. package/esm/node_modules/openai/lib/chatCompletionUtils.mjs.map +1 -0
  588. package/esm/node_modules/openai/lib/parser.mjs +88 -0
  589. package/esm/node_modules/openai/lib/parser.mjs.map +1 -0
  590. package/esm/node_modules/openai/lib/responses/ResponseStream.mjs +231 -0
  591. package/esm/node_modules/openai/lib/responses/ResponseStream.mjs.map +1 -0
  592. package/esm/node_modules/openai/resources/admin/admin.mjs +15 -0
  593. package/esm/node_modules/openai/resources/admin/admin.mjs.map +1 -0
  594. package/esm/node_modules/openai/resources/admin/organization/admin-api-keys.mjs +81 -0
  595. package/esm/node_modules/openai/resources/admin/organization/admin-api-keys.mjs.map +1 -0
  596. package/esm/node_modules/openai/resources/admin/organization/audit-logs.mjs +31 -0
  597. package/esm/node_modules/openai/resources/admin/organization/audit-logs.mjs.map +1 -0
  598. package/esm/node_modules/openai/resources/admin/organization/certificates.mjs +153 -0
  599. package/esm/node_modules/openai/resources/admin/organization/certificates.mjs.map +1 -0
  600. package/esm/node_modules/openai/resources/admin/organization/data-retention.mjs +42 -0
  601. package/esm/node_modules/openai/resources/admin/organization/data-retention.mjs.map +1 -0
  602. package/esm/node_modules/openai/resources/admin/organization/groups/groups.mjs +106 -0
  603. package/esm/node_modules/openai/resources/admin/organization/groups/groups.mjs.map +1 -0
  604. package/esm/node_modules/openai/resources/admin/organization/groups/roles.mjs +88 -0
  605. package/esm/node_modules/openai/resources/admin/organization/groups/roles.mjs.map +1 -0
  606. package/esm/node_modules/openai/resources/admin/organization/groups/users.mjs +88 -0
  607. package/esm/node_modules/openai/resources/admin/organization/groups/users.mjs.map +1 -0
  608. package/esm/node_modules/openai/resources/admin/organization/invites.mjs +83 -0
  609. package/esm/node_modules/openai/resources/admin/organization/invites.mjs.map +1 -0
  610. package/esm/node_modules/openai/resources/admin/organization/organization.mjs +45 -0
  611. package/esm/node_modules/openai/resources/admin/organization/organization.mjs.map +1 -0
  612. package/esm/node_modules/openai/resources/admin/organization/projects/api-keys.mjs +72 -0
  613. package/esm/node_modules/openai/resources/admin/organization/projects/api-keys.mjs.map +1 -0
  614. package/esm/node_modules/openai/resources/admin/organization/projects/certificates.mjs +78 -0
  615. package/esm/node_modules/openai/resources/admin/organization/projects/certificates.mjs.map +1 -0
  616. package/esm/node_modules/openai/resources/admin/organization/projects/data-retention.mjs +46 -0
  617. package/esm/node_modules/openai/resources/admin/organization/projects/data-retention.mjs.map +1 -0
  618. package/esm/node_modules/openai/resources/admin/organization/projects/groups/groups.mjs +95 -0
  619. package/esm/node_modules/openai/resources/admin/organization/projects/groups/groups.mjs.map +1 -0
  620. package/esm/node_modules/openai/resources/admin/organization/projects/groups/roles.mjs +91 -0
  621. package/esm/node_modules/openai/resources/admin/organization/projects/groups/roles.mjs.map +1 -0
  622. package/esm/node_modules/openai/resources/admin/organization/projects/hosted-tool-permissions.mjs +45 -0
  623. package/esm/node_modules/openai/resources/admin/organization/projects/hosted-tool-permissions.mjs.map +1 -0
  624. package/esm/node_modules/openai/resources/admin/organization/projects/model-permissions.mjs +63 -0
  625. package/esm/node_modules/openai/resources/admin/organization/projects/model-permissions.mjs.map +1 -0
  626. package/esm/node_modules/openai/resources/admin/organization/projects/projects.mjs +137 -0
  627. package/esm/node_modules/openai/resources/admin/organization/projects/projects.mjs.map +1 -0
  628. package/esm/node_modules/openai/resources/admin/organization/projects/rate-limits.mjs +51 -0
  629. package/esm/node_modules/openai/resources/admin/organization/projects/rate-limits.mjs.map +1 -0
  630. package/esm/node_modules/openai/resources/admin/organization/projects/roles.mjs +108 -0
  631. package/esm/node_modules/openai/resources/admin/organization/projects/roles.mjs.map +1 -0
  632. package/esm/node_modules/openai/resources/admin/organization/projects/service-accounts.mjs +112 -0
  633. package/esm/node_modules/openai/resources/admin/organization/projects/service-accounts.mjs.map +1 -0
  634. package/esm/node_modules/openai/resources/admin/organization/projects/spend-alerts.mjs +106 -0
  635. package/esm/node_modules/openai/resources/admin/organization/projects/spend-alerts.mjs.map +1 -0
  636. package/esm/node_modules/openai/resources/admin/organization/projects/users/roles.mjs +91 -0
  637. package/esm/node_modules/openai/resources/admin/organization/projects/users/roles.mjs.map +1 -0
  638. package/esm/node_modules/openai/resources/admin/organization/projects/users/users.mjs +118 -0
  639. package/esm/node_modules/openai/resources/admin/organization/projects/users/users.mjs.map +1 -0
  640. package/esm/node_modules/openai/resources/admin/organization/roles.mjs +96 -0
  641. package/esm/node_modules/openai/resources/admin/organization/roles.mjs.map +1 -0
  642. package/esm/node_modules/openai/resources/admin/organization/spend-alerts.mjs +97 -0
  643. package/esm/node_modules/openai/resources/admin/organization/spend-alerts.mjs.map +1 -0
  644. package/esm/node_modules/openai/resources/admin/organization/usage.mjs +207 -0
  645. package/esm/node_modules/openai/resources/admin/organization/usage.mjs.map +1 -0
  646. package/esm/node_modules/openai/resources/admin/organization/users/roles.mjs +88 -0
  647. package/esm/node_modules/openai/resources/admin/organization/users/roles.mjs.map +1 -0
  648. package/esm/node_modules/openai/resources/admin/organization/users/users.mjs +82 -0
  649. package/esm/node_modules/openai/resources/admin/organization/users/users.mjs.map +1 -0
  650. package/esm/node_modules/openai/resources/audio/audio.mjs +21 -0
  651. package/esm/node_modules/openai/resources/audio/audio.mjs.map +1 -0
  652. package/esm/node_modules/openai/resources/audio/speech.mjs +39 -0
  653. package/esm/node_modules/openai/resources/audio/speech.mjs.map +1 -0
  654. package/esm/node_modules/openai/resources/audio/transcriptions.mjs +22 -0
  655. package/esm/node_modules/openai/resources/audio/transcriptions.mjs.map +1 -0
  656. package/esm/node_modules/openai/resources/audio/translations.mjs +21 -0
  657. package/esm/node_modules/openai/resources/audio/translations.mjs.map +1 -0
  658. package/esm/node_modules/openai/resources/batches.mjs +54 -0
  659. package/esm/node_modules/openai/resources/batches.mjs.map +1 -0
  660. package/esm/node_modules/openai/resources/beta/assistants.mjs +78 -0
  661. package/esm/node_modules/openai/resources/beta/assistants.mjs.map +1 -0
  662. package/esm/node_modules/openai/resources/beta/beta.mjs +24 -0
  663. package/esm/node_modules/openai/resources/beta/beta.mjs.map +1 -0
  664. package/esm/node_modules/openai/resources/beta/chatkit/chatkit.mjs +18 -0
  665. package/esm/node_modules/openai/resources/beta/chatkit/chatkit.mjs.map +1 -0
  666. package/esm/node_modules/openai/resources/beta/chatkit/sessions.mjs +49 -0
  667. package/esm/node_modules/openai/resources/beta/chatkit/sessions.mjs.map +1 -0
  668. package/esm/node_modules/openai/resources/beta/chatkit/threads.mjs +85 -0
  669. package/esm/node_modules/openai/resources/beta/chatkit/threads.mjs.map +1 -0
  670. package/esm/node_modules/openai/resources/beta/realtime/realtime.mjs +21 -0
  671. package/esm/node_modules/openai/resources/beta/realtime/realtime.mjs.map +1 -0
  672. package/esm/node_modules/openai/resources/beta/realtime/sessions.mjs +33 -0
  673. package/esm/node_modules/openai/resources/beta/realtime/sessions.mjs.map +1 -0
  674. package/esm/node_modules/openai/resources/beta/realtime/transcription-sessions.mjs +33 -0
  675. package/esm/node_modules/openai/resources/beta/realtime/transcription-sessions.mjs.map +1 -0
  676. package/esm/node_modules/openai/resources/beta/threads/messages.mjs +83 -0
  677. package/esm/node_modules/openai/resources/beta/threads/messages.mjs.map +1 -0
  678. package/esm/node_modules/openai/resources/beta/threads/runs/runs.mjs +183 -0
  679. package/esm/node_modules/openai/resources/beta/threads/runs/runs.mjs.map +1 -0
  680. package/esm/node_modules/openai/resources/beta/threads/runs/steps.mjs +45 -0
  681. package/esm/node_modules/openai/resources/beta/threads/runs/steps.mjs.map +1 -0
  682. package/esm/node_modules/openai/resources/beta/threads/threads.mjs +101 -0
  683. package/esm/node_modules/openai/resources/beta/threads/threads.mjs.map +1 -0
  684. package/esm/node_modules/openai/resources/chat/chat.mjs +15 -0
  685. package/esm/node_modules/openai/resources/chat/chat.mjs.map +1 -0
  686. package/esm/node_modules/openai/resources/chat/completions/completions.mjs +123 -0
  687. package/esm/node_modules/openai/resources/chat/completions/completions.mjs.map +1 -0
  688. package/esm/node_modules/openai/resources/chat/completions/index.mjs +7 -0
  689. package/esm/node_modules/openai/resources/chat/completions/messages.mjs +35 -0
  690. package/esm/node_modules/openai/resources/chat/completions/messages.mjs.map +1 -0
  691. package/esm/node_modules/openai/resources/chat/index.mjs +5 -0
  692. package/esm/node_modules/openai/resources/completions.mjs +20 -0
  693. package/esm/node_modules/openai/resources/completions.mjs.map +1 -0
  694. package/esm/node_modules/openai/resources/containers/containers.mjs +57 -0
  695. package/esm/node_modules/openai/resources/containers/containers.mjs.map +1 -0
  696. package/esm/node_modules/openai/resources/containers/files/content.mjs +23 -0
  697. package/esm/node_modules/openai/resources/containers/files/content.mjs.map +1 -0
  698. package/esm/node_modules/openai/resources/containers/files/files.mjs +63 -0
  699. package/esm/node_modules/openai/resources/containers/files/files.mjs.map +1 -0
  700. package/esm/node_modules/openai/resources/conversations/conversations.mjs +57 -0
  701. package/esm/node_modules/openai/resources/conversations/conversations.mjs.map +1 -0
  702. package/esm/node_modules/openai/resources/conversations/items.mjs +57 -0
  703. package/esm/node_modules/openai/resources/conversations/items.mjs.map +1 -0
  704. package/esm/node_modules/openai/resources/embeddings.mjs +48 -0
  705. package/esm/node_modules/openai/resources/embeddings.mjs.map +1 -0
  706. package/esm/node_modules/openai/resources/evals/evals.mjs +73 -0
  707. package/esm/node_modules/openai/resources/evals/evals.mjs.map +1 -0
  708. package/esm/node_modules/openai/resources/evals/runs/output-items.mjs +35 -0
  709. package/esm/node_modules/openai/resources/evals/runs/output-items.mjs.map +1 -0
  710. package/esm/node_modules/openai/resources/evals/runs/runs.mjs +72 -0
  711. package/esm/node_modules/openai/resources/evals/runs/runs.mjs.map +1 -0
  712. package/esm/node_modules/openai/resources/files.mjs +111 -0
  713. package/esm/node_modules/openai/resources/files.mjs.map +1 -0
  714. package/esm/node_modules/openai/resources/fine-tuning/alpha/alpha.mjs +15 -0
  715. package/esm/node_modules/openai/resources/fine-tuning/alpha/alpha.mjs.map +1 -0
  716. package/esm/node_modules/openai/resources/fine-tuning/alpha/graders.mjs +60 -0
  717. package/esm/node_modules/openai/resources/fine-tuning/alpha/graders.mjs.map +1 -0
  718. package/esm/node_modules/openai/resources/fine-tuning/checkpoints/checkpoints.mjs +15 -0
  719. package/esm/node_modules/openai/resources/fine-tuning/checkpoints/checkpoints.mjs.map +1 -0
  720. package/esm/node_modules/openai/resources/fine-tuning/checkpoints/permissions.mjs +102 -0
  721. package/esm/node_modules/openai/resources/fine-tuning/checkpoints/permissions.mjs.map +1 -0
  722. package/esm/node_modules/openai/resources/fine-tuning/fine-tuning.mjs +24 -0
  723. package/esm/node_modules/openai/resources/fine-tuning/fine-tuning.mjs.map +1 -0
  724. package/esm/node_modules/openai/resources/fine-tuning/jobs/checkpoints.mjs +34 -0
  725. package/esm/node_modules/openai/resources/fine-tuning/jobs/checkpoints.mjs.map +1 -0
  726. package/esm/node_modules/openai/resources/fine-tuning/jobs/jobs.mjs +148 -0
  727. package/esm/node_modules/openai/resources/fine-tuning/jobs/jobs.mjs.map +1 -0
  728. package/esm/node_modules/openai/resources/fine-tuning/methods.mjs +8 -0
  729. package/esm/node_modules/openai/resources/fine-tuning/methods.mjs.map +1 -0
  730. package/esm/node_modules/openai/resources/graders/grader-models.mjs +8 -0
  731. package/esm/node_modules/openai/resources/graders/grader-models.mjs.map +1 -0
  732. package/esm/node_modules/openai/resources/graders/graders.mjs +15 -0
  733. package/esm/node_modules/openai/resources/graders/graders.mjs.map +1 -0
  734. package/esm/node_modules/openai/resources/images.mjs +46 -0
  735. package/esm/node_modules/openai/resources/images.mjs.map +1 -0
  736. package/esm/node_modules/openai/resources/index.mjs +27 -0
  737. package/esm/node_modules/openai/resources/models.mjs +44 -0
  738. package/esm/node_modules/openai/resources/models.mjs.map +1 -0
  739. package/esm/node_modules/openai/resources/moderations.mjs +23 -0
  740. package/esm/node_modules/openai/resources/moderations.mjs.map +1 -0
  741. package/esm/node_modules/openai/resources/realtime/calls.mjs +79 -0
  742. package/esm/node_modules/openai/resources/realtime/calls.mjs.map +1 -0
  743. package/esm/node_modules/openai/resources/realtime/client-secrets.mjs +39 -0
  744. package/esm/node_modules/openai/resources/realtime/client-secrets.mjs.map +1 -0
  745. package/esm/node_modules/openai/resources/realtime/realtime.mjs +18 -0
  746. package/esm/node_modules/openai/resources/realtime/realtime.mjs.map +1 -0
  747. package/esm/node_modules/openai/resources/responses/input-items.mjs +31 -0
  748. package/esm/node_modules/openai/resources/responses/input-items.mjs.map +1 -0
  749. package/esm/node_modules/openai/resources/responses/input-tokens.mjs +27 -0
  750. package/esm/node_modules/openai/resources/responses/input-tokens.mjs.map +1 -0
  751. package/esm/node_modules/openai/resources/responses/responses.mjs +110 -0
  752. package/esm/node_modules/openai/resources/responses/responses.mjs.map +1 -0
  753. package/esm/node_modules/openai/resources/skills/content.mjs +22 -0
  754. package/esm/node_modules/openai/resources/skills/content.mjs.map +1 -0
  755. package/esm/node_modules/openai/resources/skills/skills.mjs +69 -0
  756. package/esm/node_modules/openai/resources/skills/skills.mjs.map +1 -0
  757. package/esm/node_modules/openai/resources/skills/versions/content.mjs +23 -0
  758. package/esm/node_modules/openai/resources/skills/versions/content.mjs.map +1 -0
  759. package/esm/node_modules/openai/resources/skills/versions/versions.mjs +58 -0
  760. package/esm/node_modules/openai/resources/skills/versions/versions.mjs.map +1 -0
  761. package/esm/node_modules/openai/resources/uploads/parts.mjs +34 -0
  762. package/esm/node_modules/openai/resources/uploads/parts.mjs.map +1 -0
  763. package/esm/node_modules/openai/resources/uploads/uploads.mjs +84 -0
  764. package/esm/node_modules/openai/resources/uploads/uploads.mjs.map +1 -0
  765. package/esm/node_modules/openai/resources/vector-stores/file-batches.mjs +126 -0
  766. package/esm/node_modules/openai/resources/vector-stores/file-batches.mjs.map +1 -0
  767. package/esm/node_modules/openai/resources/vector-stores/files.mjs +147 -0
  768. package/esm/node_modules/openai/resources/vector-stores/files.mjs.map +1 -0
  769. package/esm/node_modules/openai/resources/vector-stores/vector-stores.mjs +87 -0
  770. package/esm/node_modules/openai/resources/vector-stores/vector-stores.mjs.map +1 -0
  771. package/esm/node_modules/openai/resources/videos.mjs +115 -0
  772. package/esm/node_modules/openai/resources/videos.mjs.map +1 -0
  773. package/esm/node_modules/openai/resources/webhooks/index.mjs +3 -0
  774. package/esm/node_modules/openai/resources/webhooks/webhooks.mjs +69 -0
  775. package/esm/node_modules/openai/resources/webhooks/webhooks.mjs.map +1 -0
  776. package/esm/node_modules/openai/resources/webhooks.mjs +4 -0
  777. package/esm/node_modules/openai/streaming.mjs +3 -0
  778. package/esm/node_modules/openai/version.mjs +6 -0
  779. package/esm/node_modules/openai/version.mjs.map +1 -0
  780. package/esm/repositories/adapters/cascade/cascade-query-builder.d.mts +9 -0
  781. package/esm/repositories/adapters/cascade/cascade-query-builder.d.mts.map +1 -1
  782. package/esm/repositories/adapters/cascade/cascade-query-builder.mjs +32 -5
  783. package/esm/repositories/adapters/cascade/cascade-query-builder.mjs.map +1 -1
  784. package/esm/repositories/adapters/cascade/filter-applicator.mjs +17 -3
  785. package/esm/repositories/adapters/cascade/filter-applicator.mjs.map +1 -1
  786. package/esm/repositories/repository.manager.d.mts +11 -1
  787. package/esm/repositories/repository.manager.d.mts.map +1 -1
  788. package/esm/repositories/repository.manager.mjs +79 -25
  789. package/esm/repositories/repository.manager.mjs.map +1 -1
  790. package/esm/router/route-registry.mjs +19 -10
  791. package/esm/router/route-registry.mjs.map +1 -1
  792. package/esm/router/router.d.mts.map +1 -1
  793. package/esm/router/router.mjs +7 -4
  794. package/esm/router/router.mjs.map +1 -1
  795. package/esm/storage/drivers/cloud-driver.d.mts.map +1 -1
  796. package/esm/storage/drivers/cloud-driver.mjs +48 -12
  797. package/esm/storage/drivers/cloud-driver.mjs.map +1 -1
  798. package/esm/storage/drivers/do-spaces-driver.mjs +1 -1
  799. package/esm/storage/drivers/do-spaces-driver.mjs.map +1 -1
  800. package/esm/storage/drivers/local-driver.d.mts +8 -0
  801. package/esm/storage/drivers/local-driver.d.mts.map +1 -1
  802. package/esm/storage/drivers/local-driver.mjs +19 -4
  803. package/esm/storage/drivers/local-driver.mjs.map +1 -1
  804. package/esm/storage/drivers/r2-driver.mjs +1 -1
  805. package/esm/storage/drivers/r2-driver.mjs.map +1 -1
  806. package/esm/storage/drivers/s3-driver.mjs +1 -1
  807. package/esm/storage/drivers/s3-driver.mjs.map +1 -1
  808. package/esm/storage/index.d.mts +4 -1
  809. package/esm/storage/index.mjs +3 -0
  810. package/esm/storage/scoped-storage.d.mts +8 -4
  811. package/esm/storage/scoped-storage.d.mts.map +1 -1
  812. package/esm/storage/scoped-storage.mjs +21 -6
  813. package/esm/storage/scoped-storage.mjs.map +1 -1
  814. package/esm/storage/storage.d.mts +12 -4
  815. package/esm/storage/storage.d.mts.map +1 -1
  816. package/esm/storage/storage.mjs +23 -9
  817. package/esm/storage/storage.mjs.map +1 -1
  818. package/esm/storage/types.d.mts +33 -5
  819. package/esm/storage/types.d.mts.map +1 -1
  820. package/esm/storage/utils/contain-path.d.mts +23 -0
  821. package/esm/storage/utils/contain-path.d.mts.map +1 -0
  822. package/esm/storage/utils/contain-path.mjs +35 -0
  823. package/esm/storage/utils/contain-path.mjs.map +1 -0
  824. package/esm/storage/utils/safe-fetch.d.mts +68 -0
  825. package/esm/storage/utils/safe-fetch.d.mts.map +1 -0
  826. package/esm/storage/utils/safe-fetch.mjs +205 -0
  827. package/esm/storage/utils/safe-fetch.mjs.map +1 -0
  828. package/esm/storage/utils/storage-error.d.mts +35 -0
  829. package/esm/storage/utils/storage-error.d.mts.map +1 -0
  830. package/esm/storage/utils/storage-error.mjs +17 -0
  831. package/esm/storage/utils/storage-error.mjs.map +1 -0
  832. package/esm/use-cases/use-case-pipeline.mjs +4 -1
  833. package/esm/use-cases/use-case-pipeline.mjs.map +1 -1
  834. package/esm/use-cases/use-case.mjs +12 -4
  835. package/esm/use-cases/use-case.mjs.map +1 -1
  836. package/esm/use-cases/use-cases-registry.d.mts +12 -4
  837. package/esm/use-cases/use-cases-registry.d.mts.map +1 -1
  838. package/esm/use-cases/use-cases-registry.mjs +13 -3
  839. package/esm/use-cases/use-cases-registry.mjs.map +1 -1
  840. package/esm/utils/npm-registry.d.mts +1 -1
  841. package/esm/utils/npm-registry.mjs +2 -2
  842. package/esm/utils/npm-registry.mjs.map +1 -1
  843. package/llms-full.txt +29 -1
  844. package/package.json +9 -9
  845. package/skills/add-connector/SKILL.md +6 -1
  846. package/skills/configure-app/SKILL.md +23 -0
@@ -0,0 +1,1157 @@
1
+ import { AIError } from "../errors/ai-error.mjs";
2
+ import { AgentExecutionError } from "../errors/agent-execution-error.mjs";
3
+ import { AgentCancelledError } from "../errors/agent-cancelled-error.mjs";
4
+ import { AgentMaxTripsError } from "../errors/agent-max-trips-error.mjs";
5
+ import { SchemaValidationError } from "../errors/schema-validation-error.mjs";
6
+ import "../errors/index.mjs";
7
+ import { computeCost, mergeUsage } from "../utils/compute-cost.mjs";
8
+ import { extractJsonPayload } from "../utils/extract-json-payload.mjs";
9
+ import { extractJsonLenient } from "../utils/extract-json-lenient.mjs";
10
+ import { generateRunId } from "../utils/generate-run-id.mjs";
11
+ import { captureChildReport } from "../utils/run-context.mjs";
12
+ import { safeJsonParse } from "../utils/safe-json-parse.mjs";
13
+ import { stampReportLineage } from "../utils/stamp-report-lineage.mjs";
14
+ import "../utils/index.mjs";
15
+ import { runEval } from "../eval/eval-runner.mjs";
16
+ import { runPipeline } from "../middleware/pipeline.mjs";
17
+ import "../middleware/index.mjs";
18
+ import { notifyObservers } from "../observe/resolve-observers.mjs";
19
+ import { skills } from "../skills/skills.mjs";
20
+ import "../skills/index.mjs";
21
+ import { normalizeAgentTools } from "../tool/executable-as-tool.mjs";
22
+ import { buildAgentInputMessages } from "./agent-input-builder.mjs";
23
+ import { logAgentEvent } from "./agent-log-event.mjs";
24
+ import { createAgentStream } from "./agent-stream.mjs";
25
+ import { agentEventToStreamEvent } from "./agent-to-stream-event.mjs";
26
+ import { JsonStreamGuard } from "./json-stream-guard.mjs";
27
+ import { log } from "@warlock.js/logger";
28
+
29
+ //#region ../@warlock.js/ai/src/agent/agent.ts
30
+ const LOG_MODULE = "ai.agent";
31
+ /**
32
+ * Duck-type a value as a {@link SkillsContract} (vs a raw `SkillsConfig`).
33
+ * A contract exposes the agent-facing methods; a config is a plain spec.
34
+ * Checking `catalogPrompt` is sufficient to discriminate the two shapes.
35
+ */
36
+ function isSkillsContract(value) {
37
+ return typeof value === "object" && value !== null && typeof value.catalogPrompt === "function";
38
+ }
39
+ /**
40
+ * Detect abort-flavored errors surfaced by SDK HTTP layers — the
41
+ * DOM `AbortError`, axios `ERR_CANCELED`, node-fetch's own
42
+ * `AbortError`. Used to classify them as cancellation rather than
43
+ * generic agent-execution failures.
44
+ */
45
+ function isAbortLike(err) {
46
+ if (!err || typeof err !== "object") return false;
47
+ const e = err;
48
+ return e.name === "AbortError" || e.code === "ERR_CANCELED" || e.code === "ABORT_ERR";
49
+ }
50
+ /**
51
+ * Readable synthetic name for agents constructed without an explicit
52
+ * `name`. Format: `anon_<provider>_<model>[_<tool1>+<tool2>+...]` —
53
+ * deterministic (same config → same name across restarts) and
54
+ * human-readable in logs / workflow snapshots.
55
+ *
56
+ * Keeps drift detection honest for the `ai.agent({ model })`
57
+ * one-liner without punishing it with a hashed id nobody can read.
58
+ */
59
+ function synthesizeAgentName(config) {
60
+ const provider = config.model?.provider ?? "unknown";
61
+ const model = config.model?.name ?? "unknown";
62
+ const tools = (config.tools ?? []).map((tool) => tool.name).sort().join("+");
63
+ const base = `anon_${sanitize(provider)}_${sanitize(model)}`;
64
+ return tools ? `${base}_${sanitize(tools, { keepPlus: true })}` : base;
65
+ }
66
+ function sanitize(value, opts = {}) {
67
+ const allowed = opts.keepPlus ? /[^a-zA-Z0-9._+-]/g : /[^a-zA-Z0-9._-]/g;
68
+ return value.replace(allowed, "-");
69
+ }
70
+ /**
71
+ * Authoring-time check on the middleware array. Throws an
72
+ * `AgentExecutionError` with `context: { authoring: true }` the
73
+ * moment an invalid entry is found — the agent factory surface is
74
+ * where config bugs should surface, not ten trips into a run.
75
+ *
76
+ * Validates:
77
+ * - Every entry is a non-null object with a non-empty string `name`.
78
+ * - No two entries share the same `name` (would silently collide on
79
+ * `ctx.state` keys and produce impossible-to-debug behavior).
80
+ *
81
+ * Does NOT validate that hook maps contain callable functions —
82
+ * that would catch late-binding bugs but also reject legitimate
83
+ * patterns like `before` being conditionally `undefined`. Runtime
84
+ * dispatch handles missing hooks safely.
85
+ */
86
+ function validateMiddleware(middleware) {
87
+ if (!middleware || middleware.length === 0) return;
88
+ const seen = /* @__PURE__ */ new Set();
89
+ for (let index = 0; index < middleware.length; index++) {
90
+ const entry = middleware[index];
91
+ if (!entry || typeof entry !== "object") throw new AgentExecutionError(`middleware[${index}] must be an object; received ${entry === null ? "null" : typeof entry}`, { context: {
92
+ authoring: true,
93
+ index
94
+ } });
95
+ const name = entry.name;
96
+ if (typeof name !== "string" || name.length === 0) throw new AgentExecutionError(`middleware[${index}] must have a non-empty string "name"`, { context: {
97
+ authoring: true,
98
+ index
99
+ } });
100
+ if (seen.has(name)) throw new AgentExecutionError(`duplicate middleware name "${name}" — each middleware needs a unique name so ctx.state keys do not collide`, { context: {
101
+ authoring: true,
102
+ index,
103
+ name
104
+ } });
105
+ seen.add(name);
106
+ }
107
+ }
108
+ /**
109
+ * Normalize the public `judge` flag (`boolean | JudgeConfig | undefined`)
110
+ * into a resolved {@link JudgeConfig} or `undefined` when the preset is
111
+ * off. `true` ⇒ all defaults (`{}`); a partial config fills missing fields
112
+ * from the defaults; `false` / absent ⇒ `undefined` (judge mode off).
113
+ */
114
+ function resolveJudgeConfig(judge) {
115
+ if (!judge) return;
116
+ return { repairAttempts: (judge === true ? {} : judge).repairAttempts ?? 2 };
117
+ }
118
+ /**
119
+ * Creates an executable AI agent from the given configuration.
120
+ *
121
+ * The agent runs a bounded trip loop: each trip calls the model, dispatches
122
+ * any requested tool calls, then loops until the model stops or `maxTrips`
123
+ * is reached. Each `execute()` / `stream()` call spawns a fresh internal
124
+ * `Execution` instance — the factory itself holds no state across calls.
125
+ *
126
+ * `execute()` never throws — any error is attached to the returned result
127
+ * under `result.error`. `stream()` surfaces errors both on the terminal
128
+ * `error` stream event and via the `stream.result` promise.
129
+ *
130
+ * @example
131
+ * const myAgent = agent({
132
+ * model: openai.model({ name: "gpt-4o" }),
133
+ * systemPrompt: "You are a helpful assistant.",
134
+ * tools: [searchTool],
135
+ * });
136
+ *
137
+ * const result = await myAgent.execute("What is the capital of Egypt?");
138
+ *
139
+ * @example
140
+ * const stream = myAgent.stream("Write a haiku about Cairo.");
141
+ *
142
+ * for await (const event of stream) {
143
+ * if (event.type === "streaming") process.stdout.write(event.delta);
144
+ * }
145
+ *
146
+ * const result = await stream.result;
147
+ */
148
+ function agent(config) {
149
+ validateMiddleware(config.middleware);
150
+ const isAnonymous = !config.name || typeof config.name !== "string";
151
+ const tools = normalizeAgentTools(config.tools);
152
+ const name = isAnonymous ? synthesizeAgentName({
153
+ ...config,
154
+ tools
155
+ }) : config.name;
156
+ const skillsLib = config.skills ? isSkillsContract(config.skills) ? config.skills : skills(config.skills) : void 0;
157
+ const resolvedConfig = {
158
+ ...config,
159
+ name,
160
+ tools,
161
+ skillsLib
162
+ };
163
+ const instanceHandlers = /* @__PURE__ */ new Map();
164
+ function on(event, handler) {
165
+ const existing = instanceHandlers.get(event);
166
+ const bucket = existing ?? /* @__PURE__ */ new Set();
167
+ if (!existing) instanceHandlers.set(event, bucket);
168
+ bucket.add(handler);
169
+ return () => off(event, handler);
170
+ }
171
+ function off(event, handler) {
172
+ const bucket = instanceHandlers.get(event);
173
+ if (!bucket) return;
174
+ bucket.delete(handler);
175
+ if (bucket.size === 0) instanceHandlers.delete(event);
176
+ }
177
+ const agentContract = {
178
+ name,
179
+ isAnonymous,
180
+ description: config.description,
181
+ async execute(input, options) {
182
+ return new Execution(resolvedConfig, input, options, void 0, instanceHandlers).run();
183
+ },
184
+ stream(input, options) {
185
+ const { controller, stream } = createAgentStream();
186
+ new Execution(resolvedConfig, input, options, controller, instanceHandlers).run();
187
+ return stream;
188
+ },
189
+ on,
190
+ off,
191
+ eval(options) {
192
+ return runEval(agentContract, options);
193
+ }
194
+ };
195
+ return agentContract;
196
+ }
197
+ /**
198
+ * Build a judge-safe agent — sugar for `agent({ ...config, judge })`.
199
+ *
200
+ * Use this for LLM-as-judge graders and verdict classifiers running on
201
+ * models that may emit corrupted structured output (e.g. the Amazon Nova
202
+ * family). The returned agent parses verdicts leniently (tolerates fenced
203
+ * ` ```json ` blocks + surrounding prose), auto-enables a couple of repair
204
+ * re-asks, and never throws on a parse miss — surfacing `result.error` with
205
+ * `result.data` left undefined so a flaky judge degrades gracefully.
206
+ *
207
+ * See {@link AgentConfig.judge} for the full behavior + the resilience-over-
208
+ * strictness trade-off.
209
+ *
210
+ * @param config - Any agent config (model, system prompt, output schema, …).
211
+ * @param judge - Optional fine-tuning ({@link JudgeConfig}); defaults to `true`.
212
+ *
213
+ * @example
214
+ * const grader = ai.agent.judge({
215
+ * model: nova.model({ name: "amazon.nova-pro-v1:0" }),
216
+ * systemPrompt: "Grade the answer. Respond with JSON only.",
217
+ * output: verdictSchema,
218
+ * });
219
+ *
220
+ * const result = await grader.execute(prompt);
221
+ * if (result.error) {
222
+ * // graceful default — the judge couldn't produce a clean verdict
223
+ * }
224
+ */
225
+ function judgeAgent(config, judge = true) {
226
+ return agent({
227
+ ...config,
228
+ judge
229
+ });
230
+ }
231
+ agent.judge = judgeAgent;
232
+ /**
233
+ * Per-call driver that owns the full lifecycle of a single
234
+ * `agent.execute()` or `agent.stream()` invocation.
235
+ *
236
+ * **Role.** An `Execution` is the short-lived state container and phase
237
+ * orchestrator for one agent run. The public `agent()` factory stays purely
238
+ * functional — all mutable bookkeeping (trips, tool calls, usage totals,
239
+ * message history, terminal error, parsed output) lives here so each call
240
+ * gets a fresh, isolated instance.
241
+ *
242
+ * **Responsibility.**
243
+ * - Owns: building the initial message list, driving the bounded trip loop,
244
+ * dispatching tool calls safely, parsing the final output against the
245
+ * caller's schema, emitting lifecycle events (to both the user handler
246
+ * and, in stream mode, the `StreamController`), and producing the
247
+ * `AgentResult`.
248
+ * - Does NOT own: how the model produces responses (delegated to
249
+ * `ModelContract.complete` / `ModelContract.stream`), how tools execute
250
+ * (delegated to `ToolContract.invoke`), the async-queue plumbing for
251
+ * streaming (delegated to `createAgentStream`), or any cross-call state
252
+ * (factory-level concerns live in `agent()`).
253
+ *
254
+ * Streaming mode is opt-in via the fourth constructor argument: pass a
255
+ * `StreamController` and every event is mirrored into it while model calls
256
+ * are driven via `model.stream()` instead of `model.complete()`. The public
257
+ * contract of `execute()` says it never throws — `Execution` enforces that
258
+ * by funneling every unexpected error into `this.error` and returning a
259
+ * well-formed result regardless of what went wrong.
260
+ *
261
+ * Not exported — consumers interact only with the `agent()` factory (see
262
+ * §4.2 of code-style.md — "per-call execution state across phases").
263
+ *
264
+ * @example
265
+ * // Non-streaming — inside agent.execute():
266
+ * const result = await new Execution(config, input, options).run();
267
+ *
268
+ * @example
269
+ * // Streaming — inside agent.stream():
270
+ * const { controller, stream } = createAgentStream();
271
+ * void new Execution(config, input, options, controller).run();
272
+ * return stream;
273
+ */
274
+ var Execution = class {
275
+ constructor(config, input, options, streamController, instanceHandlers) {
276
+ this.config = config;
277
+ this.input = input;
278
+ this.options = options;
279
+ this.streamController = streamController;
280
+ this.instanceHandlers = instanceHandlers;
281
+ this.trips = [];
282
+ this.toolCalls = [];
283
+ this.usage = {
284
+ input: 0,
285
+ output: 0,
286
+ total: 0
287
+ };
288
+ this.messages = [];
289
+ this.startedAt = /* @__PURE__ */ new Date();
290
+ this.start = performance.now();
291
+ this.runId = generateRunId("agent");
292
+ this.logger = log;
293
+ this.warnedHandlerEvents = /* @__PURE__ */ new Set();
294
+ this.middlewareState = /* @__PURE__ */ new Map();
295
+ this.maxTrips = config.maxTrips ?? 10;
296
+ this.middleware = config.middleware ?? [];
297
+ this.judgeConfig = resolveJudgeConfig(config.judge);
298
+ const skillTools = config.skillsLib ? normalizeAgentTools(config.skillsLib.tools(this.runId)) ?? [] : [];
299
+ this.effectiveTools = [...config.tools ?? [], ...skillTools];
300
+ }
301
+ /**
302
+ * Base middleware context shared by every level. `state` is the
303
+ * single mutable bag threaded through `execute`, `trip`, and `tool`
304
+ * hooks for the lifetime of this execution — fresh per `execute()`
305
+ * call, never reused across runs.
306
+ */
307
+ buildExecuteContext() {
308
+ return {
309
+ agent: {
310
+ name: this.config.name ?? this.config.model.name,
311
+ isAnonymous: !this.config.name
312
+ },
313
+ model: {
314
+ name: this.config.model.name,
315
+ provider: this.config.model.provider
316
+ },
317
+ input: this.input,
318
+ options: this.options,
319
+ state: this.middlewareState,
320
+ signal: this.options?.signal
321
+ };
322
+ }
323
+ /**
324
+ * Entry point for a single agent execution. Wraps the real work
325
+ * (`runCore`) in the `execute`-level middleware pipeline, then
326
+ * emits the terminal `agent.completed` / `agent.error` events and
327
+ * closes the stream (if any) with the post-pipeline result — so
328
+ * middleware that short-circuits or transforms the final result
329
+ * still produces a well-formed public outcome.
330
+ *
331
+ * Must never throw: any error that escapes the pipeline is
332
+ * converted into an `AgentResult` with `error` populated before
333
+ * returning, preserving the `agent.execute()` public contract.
334
+ */
335
+ async run() {
336
+ const context = this.buildExecuteContext();
337
+ let result;
338
+ try {
339
+ result = await runPipeline(this.middleware, "execute", context, () => this.runCore(), this.logger);
340
+ } catch (thrown) {
341
+ this.error = this.toAIError(thrown);
342
+ result = this.buildResult();
343
+ }
344
+ if (result.error) this.emit("agent.error", { error: result.error });
345
+ this.emit("agent.completed", { result });
346
+ await this.fireCompleteHook(result);
347
+ await notifyObservers(this.config.observe, result.report);
348
+ captureChildReport(result.report);
349
+ this.streamController?.end(result);
350
+ return result;
351
+ }
352
+ /**
353
+ * Inner body wrapped by the `execute`-level pipeline. Drives the
354
+ * full lifecycle — build messages → emit starting → run trip loop
355
+ * → parse output → build result. Catches any unexpected throw and
356
+ * funnels it into `this.error` so the returned result is always
357
+ * well-formed; `execute`-level `after` hooks receive the result,
358
+ * with `error` populated when things went wrong.
359
+ */
360
+ async runCore() {
361
+ try {
362
+ await this.buildInitialMessages();
363
+ this.emit("agent.starting", { input: this.input });
364
+ await this.runTripLoop();
365
+ if (await this.parseOutput() === "failed" && this.resolveRepairAttempts() > 0) await this.runRepairLoop();
366
+ } catch (thrown) {
367
+ this.error = this.toAIError(thrown);
368
+ }
369
+ return this.buildResult();
370
+ }
371
+ /**
372
+ * Resolve the system prompt (string or `SystemPromptContract`), merge
373
+ * placeholders from config + execute options, inject a structured-output
374
+ * instruction when the caller wants typed output but the model can't
375
+ * enforce it natively, prepend any conversation history, and append the
376
+ * user input. Produces the initial `messages` array the first trip sends
377
+ * to the model. Runs exactly once per execution.
378
+ */
379
+ async buildInitialMessages() {
380
+ const { messages, responseSchema, systemPrompt, promptName, promptVersion } = await buildAgentInputMessages({
381
+ config: this.config,
382
+ input: this.input,
383
+ options: this.options
384
+ });
385
+ this.messages.push(...messages);
386
+ this.responseSchema = responseSchema;
387
+ this.systemPrompt = systemPrompt;
388
+ this.promptName = promptName;
389
+ this.promptVersion = promptVersion;
390
+ await this.injectSkills();
391
+ }
392
+ /**
393
+ * Prepend the skills library's contribution to the system prompt — the
394
+ * always-injected metadata catalog first, then (only under `inject`) the
395
+ * preloaded skill bodies, then the developer's resolved system prompt.
396
+ * Never replaces the developer prompt.
397
+ *
398
+ * No-op when no skills library is attached. `catalogPrompt` returns `""`
399
+ * when nothing is in scope and `preload` returns `[]` when `inject` is
400
+ * omitted (the default), so the prepend is a no-op in those cases too.
401
+ *
402
+ * Awaited inside `buildInitialMessages`, which runs inside `runCore`'s
403
+ * try/catch — a source/embedder failure funnels into `this.error` like
404
+ * any other build failure, no new error handling needed.
405
+ */
406
+ async injectSkills() {
407
+ const lib = this.config.skillsLib;
408
+ if (!lib) return;
409
+ const catalogBlock = await lib.catalogPrompt(this.input);
410
+ const preloaded = await lib.preload(this.input);
411
+ const blocks = [];
412
+ if (catalogBlock) blocks.push(catalogBlock);
413
+ for (const record of preloaded) if (record.body) blocks.push(record.body);
414
+ if (blocks.length === 0) return;
415
+ const prefix = blocks.join("\n\n");
416
+ const merged = this.systemPrompt ? `${prefix}\n\n${this.systemPrompt}` : prefix;
417
+ this.systemPrompt = merged;
418
+ const firstMessage = this.messages[0];
419
+ if (firstMessage?.role === "system") firstMessage.content = merged;
420
+ else this.messages.unshift({
421
+ role: "system",
422
+ content: merged
423
+ });
424
+ }
425
+ /**
426
+ * Drive sequential trips up to `maxTrips`. Each trip may stop the loop
427
+ * naturally (model returned a non-tool-call finish), abort it (model
428
+ * threw), or continue it (model requested tools). When the loop exits
429
+ * after the cap without a natural stop, records a "Max trips exceeded"
430
+ * error so the caller can distinguish runaway tool loops from a real result.
431
+ */
432
+ async runTripLoop() {
433
+ for (let tripIndex = 0; tripIndex < this.maxTrips; tripIndex++) {
434
+ if (this.options?.signal?.aborted) {
435
+ this.error = this.makeCancelledError();
436
+ return;
437
+ }
438
+ const tripInput = tripIndex === 0 ? this.input : "[tool results]";
439
+ const outcome = await this.runTrip(tripIndex, tripInput);
440
+ if (outcome === "error" || outcome === "stop") return;
441
+ }
442
+ if (this.trips[this.trips.length - 1]?.finishReason === "tool_calls") this.error = new AgentMaxTripsError("Max trips exceeded", { maxTrips: this.maxTrips });
443
+ }
444
+ /**
445
+ * Execute one round-trip to the model. Aggregates usage into the running
446
+ * total, dispatches any requested tool calls, appends the assistant +
447
+ * tool-result messages for the next trip, and records an `LLMTrip`.
448
+ * Returns an outcome that tells `runTripLoop` whether to continue, stop,
449
+ * or abort.
450
+ */
451
+ async runTrip(tripIndex, tripInput) {
452
+ this.emit("agent.trip.started", {
453
+ tripIndex,
454
+ input: tripInput
455
+ });
456
+ const tripStartedAt = /* @__PURE__ */ new Date();
457
+ const tripStart = performance.now();
458
+ let response;
459
+ try {
460
+ response = await this.runTripThroughPipeline(tripIndex);
461
+ } catch (thrown) {
462
+ this.error = this.toAIError(thrown);
463
+ const failedTrip = {
464
+ index: tripIndex,
465
+ input: tripInput,
466
+ output: "",
467
+ finishReason: "error",
468
+ startedAt: tripStartedAt.toISOString(),
469
+ endedAt: (/* @__PURE__ */ new Date()).toISOString(),
470
+ duration: performance.now() - tripStart,
471
+ usage: {
472
+ input: 0,
473
+ output: 0,
474
+ total: 0
475
+ },
476
+ error: this.error
477
+ };
478
+ this.trips.push(failedTrip);
479
+ this.emit("agent.trip.completed", { trip: failedTrip });
480
+ this.emit("agent.error", { error: this.error });
481
+ return "error";
482
+ }
483
+ if (response.usage.cost === void 0) response.usage.cost = computeCost(response.usage, this.config.model.pricing);
484
+ mergeUsage(this.usage, response.usage);
485
+ await this.fireUsageHook(tripIndex, response.usage);
486
+ const isToolCallTrip = response.finishReason === "tool_calls" && response.toolCalls !== void 0 && response.toolCalls.length > 0;
487
+ const tripToolCalls = [];
488
+ if (isToolCallTrip) {
489
+ this.messages.push({
490
+ role: "assistant",
491
+ content: response.content,
492
+ toolCalls: response.toolCalls
493
+ });
494
+ for (const toolCallRequest of response.toolCalls) {
495
+ const record = await this.dispatchToolCall(toolCallRequest, tripIndex);
496
+ tripToolCalls.push(record);
497
+ }
498
+ }
499
+ const trip = {
500
+ index: tripIndex,
501
+ input: tripInput,
502
+ output: response.content,
503
+ finishReason: response.finishReason,
504
+ startedAt: tripStartedAt.toISOString(),
505
+ endedAt: (/* @__PURE__ */ new Date()).toISOString(),
506
+ duration: performance.now() - tripStart,
507
+ usage: response.usage,
508
+ toolCalls: tripToolCalls.length > 0 ? tripToolCalls : void 0
509
+ };
510
+ this.trips.push(trip);
511
+ this.emit("agent.trip.completed", { trip });
512
+ if (!isToolCallTrip) return "stop";
513
+ return response.toolCalls.every((request) => {
514
+ return this.effectiveTools.find((tool) => tool.name === request.name)?.mode === "silent";
515
+ }) ? "stop" : "continue";
516
+ }
517
+ /**
518
+ * Route `getModelResponse` through the `trip`-level middleware
519
+ * pipeline. `trip.before` hooks can short-circuit the trip by
520
+ * returning a synthetic `ModelResponse` (semantic cache hit).
521
+ * `trip.after` hooks can transform the response before the trip
522
+ * record is built or any tool calls are dispatched. `trip.onError`
523
+ * hooks can recover from provider failures (fallback chain).
524
+ */
525
+ async runTripThroughPipeline(tripIndex) {
526
+ const context = {
527
+ ...this.buildExecuteContext(),
528
+ tripIndex,
529
+ messages: this.messages
530
+ };
531
+ return await runPipeline(this.middleware, "trip", context, () => this.getModelResponse(tripIndex), this.logger);
532
+ }
533
+ /**
534
+ * Produce the `ModelResponse` for the current trip. In non-streaming
535
+ * mode, delegates straight to `model.complete()`. In streaming mode,
536
+ * drains `model.stream()` while emitting `streaming` events per delta
537
+ * and accumulates the chunks into the same `ModelResponse` shape, so the
538
+ * rest of the trip pipeline (tool dispatch, trip record, usage
539
+ * aggregation) stays identical between the two modes.
540
+ */
541
+ async getModelResponse(tripIndex) {
542
+ const callOptions = {
543
+ ...this.config.modelOptions,
544
+ tools: this.effectiveTools,
545
+ ...this.responseSchema ? { responseSchema: this.responseSchema } : {},
546
+ ...this.options?.signal ? { signal: this.options.signal } : {}
547
+ };
548
+ if (!this.streamController) return this.config.model.complete(this.messages, callOptions);
549
+ let content = "";
550
+ let finishReason = "stop";
551
+ let usage = {
552
+ input: 0,
553
+ output: 0,
554
+ total: 0
555
+ };
556
+ const toolCalls = [];
557
+ const recoveredCalls = [];
558
+ const guardConfig = this.resolveStreamingToolGuard();
559
+ const guard = guardConfig ? new JsonStreamGuard({
560
+ tools: this.effectiveTools,
561
+ maxBufferBytes: guardConfig.maxBufferBytes,
562
+ onSafeDelta: (delta) => {
563
+ content += delta;
564
+ this.emit("agent.trip.streaming", {
565
+ delta,
566
+ tripIndex
567
+ });
568
+ },
569
+ onRecoveredCall: (request) => {
570
+ recoveredCalls.push(request);
571
+ }
572
+ }) : void 0;
573
+ for await (const chunk of this.config.model.stream(this.messages, callOptions)) {
574
+ if (this.options?.signal?.aborted) throw this.makeCancelledError();
575
+ if (chunk.type === "delta") {
576
+ if (guard) await guard.feed(chunk.content);
577
+ else {
578
+ content += chunk.content;
579
+ this.emit("agent.trip.streaming", {
580
+ delta: chunk.content,
581
+ tripIndex
582
+ });
583
+ }
584
+ continue;
585
+ }
586
+ if (chunk.type === "tool-call") {
587
+ toolCalls.push({
588
+ id: chunk.id,
589
+ name: chunk.name,
590
+ input: chunk.input,
591
+ ...chunk.providerMetadata ? { providerMetadata: chunk.providerMetadata } : {}
592
+ });
593
+ continue;
594
+ }
595
+ finishReason = chunk.finishReason;
596
+ usage = chunk.usage;
597
+ }
598
+ if (guard) await guard.finalize();
599
+ const dedupedRecovered = recoveredCalls.filter((recovered) => !isDuplicateToolCall(recovered, toolCalls));
600
+ const mergedToolCalls = [...toolCalls, ...dedupedRecovered];
601
+ const resolvedFinishReason = dedupedRecovered.length > 0 && finishReason === "stop" ? "tool_calls" : finishReason;
602
+ return {
603
+ content,
604
+ finishReason: resolvedFinishReason,
605
+ usage,
606
+ toolCalls: mergedToolCalls.length > 0 ? mergedToolCalls : void 0
607
+ };
608
+ }
609
+ /**
610
+ * Resolve the effective `streamingToolGuard` for this trip.
611
+ * Per-call options win over the agent-level config when the key is
612
+ * explicitly present on options (including the explicit `undefined`
613
+ * "disable for this call" form). Returns `undefined` when no guard
614
+ * should run.
615
+ */
616
+ resolveStreamingToolGuard() {
617
+ if (this.options !== void 0 && Object.prototype.hasOwnProperty.call(this.options, "streamingToolGuard")) return this.options.streamingToolGuard;
618
+ return this.config.streamingToolGuard;
619
+ }
620
+ /**
621
+ * Dispatch a single tool call requested by the model. Looks up the tool
622
+ * by name, invokes it via the safe `ToolContract.invoke` entry, pushes a
623
+ * matching tool-result message into `this.messages` so the next trip can
624
+ * see it, and emits the right lifecycle event (`tool-called` on success,
625
+ * `tool-calling-failed` when the tool is unregistered or invoke returned
626
+ * an error). Never throws — always returns a `ToolCall` record.
627
+ */
628
+ async dispatchToolCall(toolCallRequest, tripIndex) {
629
+ const registeredTool = this.effectiveTools.find((tool) => tool.name === toolCallRequest.name);
630
+ if (!registeredTool) {
631
+ const error = new AgentExecutionError(`Tool not registered: ${toolCallRequest.name}`, { context: {
632
+ toolName: toolCallRequest.name,
633
+ tripIndex
634
+ } });
635
+ const nowIso = (/* @__PURE__ */ new Date()).toISOString();
636
+ const record = {
637
+ runId: generateRunId("tool"),
638
+ rootRunId: this.runId,
639
+ name: toolCallRequest.name,
640
+ type: "tool",
641
+ status: "failed",
642
+ startedAt: nowIso,
643
+ endedAt: nowIso,
644
+ duration: 0,
645
+ usage: {
646
+ input: 0,
647
+ output: 0,
648
+ total: 0
649
+ },
650
+ children: [],
651
+ tripIndex,
652
+ input: toolCallRequest.input,
653
+ error,
654
+ ...toolCallRequest.recoveredFrom ? { recoveredFrom: toolCallRequest.recoveredFrom } : {}
655
+ };
656
+ this.toolCalls.push(record);
657
+ this.messages.push({
658
+ role: "tool",
659
+ toolCallId: toolCallRequest.id,
660
+ content: JSON.stringify({ error: error.message })
661
+ });
662
+ this.emit("agent.tool.failed", {
663
+ tool: {
664
+ name: toolCallRequest.name,
665
+ description: "(unregistered tool — no description available)"
666
+ },
667
+ input: toolCallRequest.input,
668
+ error,
669
+ tripIndex
670
+ });
671
+ return record;
672
+ }
673
+ const toolMeta = {
674
+ name: registeredTool.name,
675
+ description: registeredTool.description,
676
+ action: resolveToolAction(registeredTool, toolCallRequest.input)
677
+ };
678
+ this.emit("agent.tool.calling", {
679
+ tool: toolMeta,
680
+ input: toolCallRequest.input,
681
+ tripIndex
682
+ });
683
+ const toolContext = {
684
+ ...this.buildExecuteContext(),
685
+ tripIndex,
686
+ messages: this.messages,
687
+ tool: {
688
+ name: registeredTool.name,
689
+ description: registeredTool.description,
690
+ mode: registeredTool.mode
691
+ },
692
+ request: toolCallRequest
693
+ };
694
+ const runSignal = this.options?.signal;
695
+ const dispatchToolCtx = runSignal ? {
696
+ artifacts: this.options?.toolCtx?.artifacts ?? {},
697
+ ...this.options?.toolCtx,
698
+ signal: runSignal
699
+ } : this.options?.toolCtx;
700
+ let invokeResult;
701
+ try {
702
+ invokeResult = await runPipeline(this.middleware, "tool", toolContext, () => registeredTool.invoke(toolCallRequest.input, dispatchToolCtx), this.logger);
703
+ } catch (thrown) {
704
+ const error = this.toAIError(thrown);
705
+ const nowIso = (/* @__PURE__ */ new Date()).toISOString();
706
+ const emptyUsage = {
707
+ input: 0,
708
+ output: 0,
709
+ total: 0
710
+ };
711
+ const failedRunId = generateRunId("tool");
712
+ invokeResult = {
713
+ error,
714
+ usage: emptyUsage,
715
+ report: {
716
+ runId: failedRunId,
717
+ rootRunId: failedRunId,
718
+ name: registeredTool.name,
719
+ version: registeredTool.version,
720
+ type: "tool",
721
+ status: "failed",
722
+ startedAt: nowIso,
723
+ endedAt: nowIso,
724
+ duration: 0,
725
+ usage: emptyUsage,
726
+ children: []
727
+ }
728
+ };
729
+ }
730
+ const innerReport = invokeResult.report;
731
+ const isComposite = innerReport.type !== "tool";
732
+ const record = {
733
+ runId: innerReport.runId,
734
+ rootRunId: this.runId,
735
+ name: toolCallRequest.name,
736
+ version: registeredTool.version,
737
+ type: "tool",
738
+ status: innerReport.status,
739
+ startedAt: innerReport.startedAt,
740
+ endedAt: innerReport.endedAt,
741
+ duration: innerReport.duration,
742
+ usage: invokeResult.usage,
743
+ children: isComposite ? [innerReport] : innerReport.children,
744
+ tripIndex,
745
+ input: toolCallRequest.input,
746
+ output: invokeResult.data,
747
+ error: invokeResult.error,
748
+ ...toolCallRequest.recoveredFrom ? { recoveredFrom: toolCallRequest.recoveredFrom } : {}
749
+ };
750
+ this.toolCalls.push(record);
751
+ mergeUsage(this.usage, invokeResult.usage);
752
+ this.messages.push({
753
+ role: "tool",
754
+ toolCallId: toolCallRequest.id,
755
+ content: invokeResult.error ? JSON.stringify({ error: invokeResult.error.message }) : JSON.stringify(invokeResult.data ?? null)
756
+ });
757
+ if (invokeResult.error) this.emit("agent.tool.failed", {
758
+ tool: toolMeta,
759
+ input: toolCallRequest.input,
760
+ error: invokeResult.error,
761
+ tripIndex
762
+ });
763
+ else this.emit("agent.tool.called", {
764
+ ...record,
765
+ tool: toolMeta
766
+ });
767
+ return record;
768
+ }
769
+ /**
770
+ * Parse the final trip output against the user-supplied schema (if any).
771
+ * Failures populate `this.error` but never throw. Returns an outcome the
772
+ * caller uses to decide whether self-repair is worth attempting:
773
+ *
774
+ * - `"skipped"` — no schema, or a prior trip-level error already set
775
+ * `this.error` (model crash, max trips). Not repairable; the failure
776
+ * isn't a parse problem the model can fix by re-asking.
777
+ * - `"failed"` — schema present, output text either failed JSON.parse
778
+ * or failed `~standard.validate`. Repairable via `runRepairLoop`.
779
+ * - `"success"` — parsed and validated; `this.data` populated.
780
+ *
781
+ * Under the judge-safe preset (`judge: true`) the JSON extraction is
782
+ * lenient — it tolerates fenced ` ```json ` blocks plus leading /
783
+ * trailing prose by slicing the first balanced object / array out of the
784
+ * response. Never throws regardless of preset: a parse / validation miss
785
+ * sets `this.error` and returns `"failed"`, leaving `this.data`
786
+ * undefined for the graceful-default path.
787
+ */
788
+ async parseOutput() {
789
+ const schema = this.options?.output ?? this.config.output;
790
+ if (!schema || this.error) return "skipped";
791
+ const text = this.trips[this.trips.length - 1]?.output ?? "";
792
+ if (!text) return "skipped";
793
+ const payload = this.judgeConfig ? extractJsonLenient(text) : extractJsonPayload(text);
794
+ const sentinel = Symbol("parse-failed");
795
+ const parsed = safeJsonParse(payload, sentinel);
796
+ if (parsed === sentinel) {
797
+ this.error = new SchemaValidationError("Failed to parse model output as JSON", { context: { text } });
798
+ return "failed";
799
+ }
800
+ const validation = await schema["~standard"].validate(parsed);
801
+ if (validation.issues) {
802
+ const summary = validation.issues.map((issue) => issue.message).join("; ");
803
+ this.error = new SchemaValidationError(summary, { issues: validation.issues });
804
+ return "failed";
805
+ }
806
+ this.data = validation.value;
807
+ return "success";
808
+ }
809
+ /**
810
+ * Resolve how many repair re-asks this run should perform after a parse
811
+ * failure. Per-call `options.repair` wins when explicitly set (preserving
812
+ * the existing surface). Otherwise the judge-safe preset supplies its
813
+ * default attempt count — so `judge: true` enables repair without the
814
+ * caller also having to pass `repair`. Returns `0` when neither applies,
815
+ * which leaves the historical "no repair unless asked" behavior intact.
816
+ */
817
+ resolveRepairAttempts() {
818
+ if (this.options?.repair) return this.options.repair.maxAttempts ?? 1;
819
+ if (this.judgeConfig) return this.judgeConfig.repairAttempts ?? 2;
820
+ return 0;
821
+ }
822
+ /**
823
+ * Opt-in self-repair loop for `output` schema failures. Triggered only
824
+ * when repair attempts remain (`resolveRepairAttempts() > 0`) and
825
+ * `parseOutput()` returned `"failed"`.
826
+ *
827
+ * Each attempt:
828
+ * 1. Pushes the bad assistant response into `this.messages` (so the
829
+ * model can see what it just produced).
830
+ * 2. Pushes a corrective user message naming the validation/parse error.
831
+ * 3. Runs another trip — counted against the same `maxTrips` cap as
832
+ * normal trips so a stuck model can't loop forever.
833
+ * 4. Re-parses. Stops on success, on a trip-level error, or when
834
+ * either `maxAttempts` or `maxTrips` is exhausted.
835
+ *
836
+ * Resets `this.error` and `this.data` before each attempt so the final
837
+ * outcome (success or last failure) is what surfaces to the caller.
838
+ */
839
+ async runRepairLoop() {
840
+ const maxAttempts = this.resolveRepairAttempts();
841
+ for (let attempt = 0; attempt < maxAttempts; attempt++) {
842
+ if (this.trips.length >= this.maxTrips) return;
843
+ const badResponse = this.trips[this.trips.length - 1]?.output ?? "";
844
+ const failureReason = this.error?.message ?? "unknown validation failure";
845
+ this.error = void 0;
846
+ this.data = void 0;
847
+ this.messages.push({
848
+ role: "assistant",
849
+ content: badResponse
850
+ });
851
+ this.messages.push({
852
+ role: "user",
853
+ content: [`Your previous response failed validation: ${failureReason}.`, "Respond again with valid JSON only — no prose, no markdown fences, no commentary."].join(" ")
854
+ });
855
+ const tripIndex = this.trips.length;
856
+ this.logger.warn(LOG_MODULE, "repair.attempting", "retrying after validation failure", {
857
+ attempt: attempt + 1,
858
+ maxAttempts,
859
+ reason: failureReason
860
+ });
861
+ if (await this.runTrip(tripIndex, "[repair attempt]") === "error") return;
862
+ if (await this.parseOutput() === "success") return;
863
+ }
864
+ }
865
+ /**
866
+ * Build the final `AgentResult` snapshot from accumulated state
867
+ * (trips, tool calls, data/error, usage, timing).
868
+ *
869
+ * Pure — no side effects. `run()` owns terminal event emission and
870
+ * stream closure so the post-pipeline result (possibly transformed
871
+ * or short-circuited by an `execute`-level middleware) is what
872
+ * flows out to consumers and listeners.
873
+ *
874
+ * Trips, tool calls, status, and timing live under `report` so the
875
+ * root stays focused on the four things callers reach for most:
876
+ * `data`, `text`, `usage`, `error`.
877
+ */
878
+ buildResult() {
879
+ const finalTrip = this.trips[this.trips.length - 1];
880
+ const endedAt = /* @__PURE__ */ new Date();
881
+ const agentName = this.config.name ?? this.config.model.name;
882
+ const status = this.error ? this.error instanceof AgentCancelledError ? "cancelled" : "failed" : "completed";
883
+ const report = {
884
+ runId: this.runId,
885
+ rootRunId: this.runId,
886
+ name: agentName,
887
+ version: this.config.version,
888
+ type: "agent",
889
+ status,
890
+ ...this.error ? { error: this.error } : {},
891
+ startedAt: this.startedAt.toISOString(),
892
+ endedAt: endedAt.toISOString(),
893
+ duration: performance.now() - this.start,
894
+ usage: this.usage,
895
+ children: this.toolCalls,
896
+ model: {
897
+ name: this.config.model.name,
898
+ provider: this.config.model.provider
899
+ },
900
+ trips: this.trips,
901
+ systemPrompt: this.systemPrompt,
902
+ ...this.promptName ? {
903
+ promptName: this.promptName,
904
+ promptVersion: this.promptVersion
905
+ } : {},
906
+ ...this.config.captureMessages ? { messages: this.captureMessages() } : {}
907
+ };
908
+ stampReportLineage(report, {
909
+ rootRunId: this.runId,
910
+ sessionId: this.options?.sessionId
911
+ });
912
+ return {
913
+ type: "agent",
914
+ data: this.data,
915
+ text: finalTrip?.output,
916
+ report,
917
+ usage: this.usage,
918
+ error: this.error
919
+ };
920
+ }
921
+ /**
922
+ * Normalize the accumulated runtime `Message[]` into the JSON-safe
923
+ * {@link CapturedMessage}[] persisted on `AgentReport.messages` (F2).
924
+ * Flattens `ContentPart[]` content to a string, and forwards
925
+ * `toolCalls` (assistant turns) / `toolCallId` (tool-result turns)
926
+ * only when present so the captured shape stays lean. Called only when
927
+ * `captureMessages` is enabled.
928
+ */
929
+ captureMessages() {
930
+ return this.messages.map((message) => {
931
+ const captured = {
932
+ role: message.role,
933
+ content: typeof message.content === "string" ? message.content : JSON.stringify(message.content)
934
+ };
935
+ if (message.toolCalls !== void 0) captured.toolCalls = message.toolCalls;
936
+ if (message.toolCallId !== void 0) captured.toolCallId = message.toolCallId;
937
+ return captured;
938
+ });
939
+ }
940
+ /**
941
+ * Normalize any thrown value into an `AIError`. `AIError` instances
942
+ * pass through untouched; provider-adapter SDK errors are caught by
943
+ * the adapter and already arrive typed, so this branch mainly
944
+ * handles runtime crashes (TypeError, ReferenceError) inside
945
+ * model.complete / model.stream and non-Error values (`throw "bad"`).
946
+ */
947
+ toAIError(thrown) {
948
+ if (thrown instanceof AIError) return thrown;
949
+ if (isAbortLike(thrown)) return this.makeCancelledError();
950
+ return new AgentExecutionError(thrown instanceof Error ? thrown.message : String(thrown), { cause: thrown });
951
+ }
952
+ /**
953
+ * Build the typed cancelled error that both the trip-loop guard
954
+ * and the mid-stream guard emit. Captures the abort reason when
955
+ * one was supplied to `controller.abort(reason)` so logs and
956
+ * telemetry can see what cancelled the run.
957
+ */
958
+ makeCancelledError() {
959
+ const reason = this.options?.signal?.reason;
960
+ const reasonText = reason === void 0 ? "" : String(reason);
961
+ return new AgentCancelledError("agent execution cancelled", {
962
+ cause: reason,
963
+ cancelledAt: (/* @__PURE__ */ new Date()).toISOString(),
964
+ reason: reasonText
965
+ });
966
+ }
967
+ /**
968
+ * Fire a single event through all three subscription tiers in order
969
+ * — factory → instance → per-call — and mirror it into the
970
+ * `StreamController` when streaming is active. A throwing user
971
+ * handler must never crash the agent, so every dispatch is wrapped
972
+ * in `safeCall`. Stream events are converted from the internal
973
+ * `AgentEventMap` payload to the public `StreamEvent` shape because
974
+ * some of them differ (e.g. the tool-called payload vs stream
975
+ * event).
976
+ */
977
+ emit(event, payload) {
978
+ const fullPayload = {
979
+ ...payload,
980
+ runId: this.runId,
981
+ rootRunId: this.runId
982
+ };
983
+ this.logEvent(event, fullPayload);
984
+ const onError = (error) => this.surfaceHandlerError(event, error);
985
+ const factoryHandler = this.config.on?.[event];
986
+ if (factoryHandler) safeCall(factoryHandler, fullPayload, onError);
987
+ const bucket = this.instanceHandlers?.get(event);
988
+ if (bucket) for (const handler of bucket) safeCall(handler, fullPayload, onError);
989
+ const perCallHandler = this.options?.on?.[event];
990
+ if (perCallHandler) safeCall(perCallHandler, fullPayload, onError);
991
+ if (this.streamController) {
992
+ const body = this.toStreamEvent(event, fullPayload);
993
+ if (body) this.streamController.push({
994
+ runId: this.runId,
995
+ rootRunId: this.runId,
996
+ ...body
997
+ });
998
+ }
999
+ }
1000
+ /**
1001
+ * Surface an isolated event-handler failure (C5). A throwing user
1002
+ * handler never crashes the agent — that isolation is preserved — but
1003
+ * total silence is the wrong default: a broken `on` handler would
1004
+ * otherwise disappear from production with no signal. Routed to the
1005
+ * structured logger (matching the `onUsage` / `onComplete` policy) and
1006
+ * warned at most once per event type so a hot event can't spam the log.
1007
+ */
1008
+ surfaceHandlerError(event, error) {
1009
+ if (this.warnedHandlerEvents.has(event)) return;
1010
+ this.warnedHandlerEvents.add(event);
1011
+ this.logger.warn(LOG_MODULE, "event.handler.error", "an event handler threw and was isolated", {
1012
+ runId: this.runId,
1013
+ event,
1014
+ error: error instanceof Error ? error.message : String(error)
1015
+ });
1016
+ }
1017
+ /**
1018
+ * Emit a structured log line for a lifecycle event. The action
1019
+ * string mirrors the event name with the `agent.` prefix stripped
1020
+ * (`agent.trip.started` → `trip.started`) so log grep filters and
1021
+ * event handlers read the same vocabulary. Level mapping follows
1022
+ * the convention documented on `@warlock.js/logger`'s `Logger`.
1023
+ */
1024
+ logEvent(event, payload) {
1025
+ const agentName = this.config.name || this.config.model.name;
1026
+ logAgentEvent(this.logger, {
1027
+ module: `${LOG_MODULE}.${agentName}`,
1028
+ maxTrips: this.maxTrips,
1029
+ modelName: this.config.model.name,
1030
+ totalUsage: this.usage,
1031
+ totalDurationMs: performance.now() - this.start,
1032
+ trips: this.trips,
1033
+ toolCalls: this.toolCalls
1034
+ }, event, payload);
1035
+ }
1036
+ toStreamEvent(event, payload) {
1037
+ return agentEventToStreamEvent(event, payload);
1038
+ }
1039
+ /**
1040
+ * Invoke the `onUsage` hook (when configured) with a flat payload
1041
+ * carrying stable identity. Awaits the handler so async ledger
1042
+ * writes complete before the next trip starts; swallows any throw
1043
+ * so consumer bugs cannot crash the agent. Sync handlers wrapped
1044
+ * via `Promise.resolve()` so the await is safe in either case.
1045
+ */
1046
+ async fireUsageHook(tripIndex, tripUsage) {
1047
+ const handler = this.config.onUsage;
1048
+ if (!handler) return;
1049
+ const event = {
1050
+ runId: this.runId,
1051
+ tripIndex,
1052
+ model: {
1053
+ name: this.config.model.name,
1054
+ provider: this.config.model.provider
1055
+ },
1056
+ usage: { ...tripUsage },
1057
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
1058
+ };
1059
+ try {
1060
+ await Promise.resolve(handler(event));
1061
+ } catch (err) {
1062
+ this.logger.warn(LOG_MODULE, "onUsage.hook.error", "onUsage handler threw", {
1063
+ runId: this.runId,
1064
+ tripIndex,
1065
+ error: err instanceof Error ? err.message : String(err)
1066
+ });
1067
+ }
1068
+ }
1069
+ /**
1070
+ * Invoke the `onComplete` hook (when configured) once at the end
1071
+ * of every run. Receives the full `AgentResult` plus pre-extracted
1072
+ * `runId` and `durationMs`. Same swallow-and-log error policy as
1073
+ * `fireUsageHook`.
1074
+ */
1075
+ async fireCompleteHook(result) {
1076
+ const handler = this.config.onComplete;
1077
+ if (!handler) return;
1078
+ const event = {
1079
+ result,
1080
+ runId: this.runId,
1081
+ durationMs: performance.now() - this.start
1082
+ };
1083
+ try {
1084
+ await Promise.resolve(handler(event));
1085
+ } catch (err) {
1086
+ this.logger.warn(LOG_MODULE, "onComplete.hook.error", "onComplete handler threw", {
1087
+ runId: this.runId,
1088
+ error: err instanceof Error ? err.message : String(err)
1089
+ });
1090
+ }
1091
+ }
1092
+ };
1093
+ /**
1094
+ * Decide whether a guard-synthesized tool call duplicates a real one
1095
+ * the provider already streamed structurally. Match key is
1096
+ * `name + key-sorted JSON of input` so identical calls (regardless of
1097
+ * argument key order) collapse, but two legitimate calls to the same
1098
+ * tool with different inputs still both dispatch.
1099
+ */
1100
+ function isDuplicateToolCall(recovered, realCalls) {
1101
+ const recoveredKey = `${recovered.name}|${stableStringify(recovered.input)}`;
1102
+ for (const real of realCalls) if (`${real.name}|${stableStringify(real.input)}` === recoveredKey) return true;
1103
+ return false;
1104
+ }
1105
+ /**
1106
+ * `JSON.stringify` variant that sorts object keys at every nesting
1107
+ * level so structurally-equal inputs serialize to identical strings.
1108
+ * Used only for dedupe-key comparison; never surfaces to consumers.
1109
+ */
1110
+ function stableStringify(value) {
1111
+ return JSON.stringify(value, (_key, val) => {
1112
+ if (val !== null && typeof val === "object" && !Array.isArray(val)) {
1113
+ const source = val;
1114
+ const sorted = {};
1115
+ for (const key of Object.keys(source).sort()) sorted[key] = source[key];
1116
+ return sorted;
1117
+ }
1118
+ return val;
1119
+ });
1120
+ }
1121
+ /**
1122
+ * Invoke a user-supplied event handler without letting exceptions
1123
+ * escape the agent. A throw is isolated (it never crashes the agent)
1124
+ * but no longer silent: the optional `onError` surfaces it — the agent
1125
+ * routes it to its structured logger, matching the swallow-and-log
1126
+ * policy of the `onUsage` / `onComplete` hooks (C5).
1127
+ */
1128
+ function safeCall(handler, payload, onError) {
1129
+ try {
1130
+ handler(payload);
1131
+ } catch (error) {
1132
+ onError?.(error);
1133
+ }
1134
+ }
1135
+ /**
1136
+ * Resolve a tool's `action` declaration into a plain string for
1137
+ * inclusion in `ToolEventMeta`. Static strings pass through;
1138
+ * function-shaped actions are invoked with the model's raw,
1139
+ * pre-validation input (before `execute`'s schema validation runs).
1140
+ *
1141
+ * Defensive: if the user's callback throws, swallow and return
1142
+ * `undefined` rather than crashing the agent — UI strings are not
1143
+ * worth aborting an LLM dispatch over.
1144
+ */
1145
+ function resolveToolAction(tool, input) {
1146
+ if (tool.action === void 0) return void 0;
1147
+ if (typeof tool.action === "string") return tool.action;
1148
+ try {
1149
+ return tool.action(input);
1150
+ } catch {
1151
+ return;
1152
+ }
1153
+ }
1154
+
1155
+ //#endregion
1156
+ export { agent };
1157
+ //# sourceMappingURL=agent.mjs.map