@stackfactor/agent-utils 1.13.4 → 1.32.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 (252) hide show
  1. package/README.md +667 -23
  2. package/dist/cjs/agentProto.d.ts +13 -3
  3. package/dist/cjs/agentProto.d.ts.map +1 -1
  4. package/dist/cjs/agentProto.js +25 -4
  5. package/dist/cjs/backoff.d.ts +17 -0
  6. package/dist/cjs/backoff.d.ts.map +1 -0
  7. package/dist/cjs/backoff.js +26 -0
  8. package/dist/cjs/cancellation.d.ts +22 -0
  9. package/dist/cjs/cancellation.d.ts.map +1 -0
  10. package/dist/cjs/cancellation.js +36 -0
  11. package/dist/cjs/cli.d.ts +3 -0
  12. package/dist/cjs/cli.d.ts.map +1 -0
  13. package/dist/cjs/cli.js +85 -0
  14. package/dist/cjs/client.d.ts +11 -0
  15. package/dist/cjs/client.d.ts.map +1 -1
  16. package/dist/cjs/client.js +27 -0
  17. package/dist/cjs/const.d.ts +23 -0
  18. package/dist/cjs/const.d.ts.map +1 -1
  19. package/dist/cjs/const.js +23 -0
  20. package/dist/cjs/daemon.d.ts +94 -0
  21. package/dist/cjs/daemon.d.ts.map +1 -0
  22. package/dist/cjs/daemon.js +507 -0
  23. package/dist/cjs/daemonConfig.d.ts +45 -0
  24. package/dist/cjs/daemonConfig.d.ts.map +1 -0
  25. package/dist/cjs/daemonConfig.js +148 -0
  26. package/dist/cjs/daemonEnv.d.ts +10 -0
  27. package/dist/cjs/daemonEnv.d.ts.map +1 -0
  28. package/dist/cjs/daemonEnv.js +12 -0
  29. package/dist/cjs/durable/clientTool.d.ts +39 -0
  30. package/dist/cjs/durable/clientTool.d.ts.map +1 -0
  31. package/dist/cjs/durable/clientTool.js +90 -0
  32. package/dist/cjs/durable/index.d.ts +9 -0
  33. package/dist/cjs/durable/index.d.ts.map +1 -0
  34. package/dist/cjs/durable/index.js +16 -0
  35. package/dist/cjs/durable/journal.d.ts +218 -0
  36. package/dist/cjs/durable/journal.d.ts.map +1 -0
  37. package/dist/cjs/durable/journal.js +392 -0
  38. package/dist/cjs/durable/pause.d.ts +84 -0
  39. package/dist/cjs/durable/pause.d.ts.map +1 -0
  40. package/dist/cjs/durable/pause.js +241 -0
  41. package/dist/cjs/durable/resume.d.ts +27 -0
  42. package/dist/cjs/durable/resume.d.ts.map +1 -0
  43. package/dist/cjs/durable/resume.js +80 -0
  44. package/dist/cjs/durable/snapshotSaver.d.ts +38 -0
  45. package/dist/cjs/durable/snapshotSaver.d.ts.map +1 -0
  46. package/dist/cjs/durable/snapshotSaver.js +81 -0
  47. package/dist/cjs/durable/step.d.ts +28 -0
  48. package/dist/cjs/durable/step.d.ts.map +1 -0
  49. package/dist/cjs/durable/step.js +43 -0
  50. package/dist/cjs/index.d.ts +30 -7
  51. package/dist/cjs/index.d.ts.map +1 -1
  52. package/dist/cjs/index.js +28 -1
  53. package/dist/cjs/infrastructure.d.ts +50 -0
  54. package/dist/cjs/infrastructure.d.ts.map +1 -0
  55. package/dist/cjs/infrastructure.js +163 -0
  56. package/dist/cjs/langChain.d.ts +15 -3
  57. package/dist/cjs/langChain.d.ts.map +1 -1
  58. package/dist/cjs/langChain.js +986 -180
  59. package/dist/cjs/learningActivityMedia.d.ts +196 -0
  60. package/dist/cjs/learningActivityMedia.d.ts.map +1 -0
  61. package/dist/cjs/learningActivityMedia.js +861 -0
  62. package/dist/cjs/learningContentPlan.d.ts +105 -0
  63. package/dist/cjs/learningContentPlan.d.ts.map +1 -0
  64. package/dist/cjs/learningContentPlan.js +305 -0
  65. package/dist/cjs/learningContentThread.d.ts +184 -0
  66. package/dist/cjs/learningContentThread.d.ts.map +1 -0
  67. package/dist/cjs/learningContentThread.js +407 -0
  68. package/dist/cjs/logger.d.ts +1 -0
  69. package/dist/cjs/logger.d.ts.map +1 -1
  70. package/dist/cjs/logger.js +17 -3
  71. package/dist/cjs/modelRates.d.ts +40 -0
  72. package/dist/cjs/modelRates.d.ts.map +1 -0
  73. package/dist/cjs/modelRates.js +76 -0
  74. package/dist/cjs/referenceContext.d.ts +4 -145
  75. package/dist/cjs/referenceContext.d.ts.map +1 -1
  76. package/dist/cjs/referenceContext.js +16 -251
  77. package/dist/cjs/retry.d.ts +64 -0
  78. package/dist/cjs/retry.d.ts.map +1 -0
  79. package/dist/cjs/retry.js +138 -0
  80. package/dist/cjs/runtimeContext.d.ts +8 -1
  81. package/dist/cjs/runtimeContext.d.ts.map +1 -1
  82. package/dist/cjs/runtimeContext.js +3 -1
  83. package/dist/cjs/serve.d.ts +3 -2
  84. package/dist/cjs/serve.d.ts.map +1 -1
  85. package/dist/cjs/serve.js +32 -2
  86. package/dist/cjs/sourceStore.d.ts +378 -0
  87. package/dist/cjs/sourceStore.d.ts.map +1 -0
  88. package/dist/cjs/sourceStore.js +872 -0
  89. package/dist/cjs/stackfactorKnowledge.d.ts +91 -7
  90. package/dist/cjs/stackfactorKnowledge.d.ts.map +1 -1
  91. package/dist/cjs/stackfactorKnowledge.js +108 -44
  92. package/dist/cjs/tavily.d.ts +108 -4
  93. package/dist/cjs/tavily.d.ts.map +1 -1
  94. package/dist/cjs/tavily.js +242 -21
  95. package/dist/cjs/usage.d.ts.map +1 -1
  96. package/dist/cjs/usage.js +9 -15
  97. package/dist/cjs/version.d.ts +3 -0
  98. package/dist/cjs/version.d.ts.map +1 -0
  99. package/dist/cjs/version.js +5 -0
  100. package/dist/cjs/workflow/bookkeeping.d.ts +78 -0
  101. package/dist/cjs/workflow/bookkeeping.d.ts.map +1 -0
  102. package/dist/cjs/workflow/bookkeeping.js +75 -0
  103. package/dist/cjs/workflow/index.d.ts +13 -0
  104. package/dist/cjs/workflow/index.d.ts.map +1 -0
  105. package/dist/cjs/workflow/index.js +51 -0
  106. package/dist/cjs/workflow/limits.d.ts +52 -0
  107. package/dist/cjs/workflow/limits.d.ts.map +1 -0
  108. package/dist/cjs/workflow/limits.js +62 -0
  109. package/dist/cjs/workflow/platformTransport.d.ts +39 -0
  110. package/dist/cjs/workflow/platformTransport.d.ts.map +1 -0
  111. package/dist/cjs/workflow/platformTransport.js +115 -0
  112. package/dist/cjs/workflow/retrying.d.ts +44 -0
  113. package/dist/cjs/workflow/retrying.d.ts.map +1 -0
  114. package/dist/cjs/workflow/retrying.js +82 -0
  115. package/dist/cjs/workflow/run.d.ts +195 -0
  116. package/dist/cjs/workflow/run.d.ts.map +1 -0
  117. package/dist/cjs/workflow/run.js +858 -0
  118. package/dist/cjs/workflow/testing/index.d.ts +3 -0
  119. package/dist/cjs/workflow/testing/index.d.ts.map +1 -0
  120. package/dist/cjs/workflow/testing/index.js +6 -0
  121. package/dist/cjs/workflow/testing/memoryTransport.d.ts +203 -0
  122. package/dist/cjs/workflow/testing/memoryTransport.d.ts.map +1 -0
  123. package/dist/cjs/workflow/testing/memoryTransport.js +1171 -0
  124. package/dist/cjs/workflow/transport.d.ts +219 -0
  125. package/dist/cjs/workflow/transport.d.ts.map +1 -0
  126. package/dist/cjs/workflow/transport.js +19 -0
  127. package/dist/esm/agentProto.d.ts +13 -3
  128. package/dist/esm/agentProto.d.ts.map +1 -1
  129. package/dist/esm/agentProto.js +23 -3
  130. package/dist/esm/backoff.d.ts +17 -0
  131. package/dist/esm/backoff.d.ts.map +1 -0
  132. package/dist/esm/backoff.js +22 -0
  133. package/dist/esm/cancellation.d.ts +22 -0
  134. package/dist/esm/cancellation.d.ts.map +1 -0
  135. package/dist/esm/cancellation.js +27 -0
  136. package/dist/esm/cli.d.ts +3 -0
  137. package/dist/esm/cli.d.ts.map +1 -0
  138. package/dist/esm/cli.js +80 -0
  139. package/dist/esm/client.d.ts +11 -0
  140. package/dist/esm/client.d.ts.map +1 -1
  141. package/dist/esm/client.js +25 -1
  142. package/dist/esm/const.d.ts +23 -0
  143. package/dist/esm/const.d.ts.map +1 -1
  144. package/dist/esm/const.js +23 -0
  145. package/dist/esm/daemon.d.ts +94 -0
  146. package/dist/esm/daemon.d.ts.map +1 -0
  147. package/dist/esm/daemon.js +499 -0
  148. package/dist/esm/daemonConfig.d.ts +45 -0
  149. package/dist/esm/daemonConfig.d.ts.map +1 -0
  150. package/dist/esm/daemonConfig.js +142 -0
  151. package/dist/esm/daemonEnv.d.ts +10 -0
  152. package/dist/esm/daemonEnv.d.ts.map +1 -0
  153. package/dist/esm/daemonEnv.js +9 -0
  154. package/dist/esm/durable/clientTool.d.ts +39 -0
  155. package/dist/esm/durable/clientTool.d.ts.map +1 -0
  156. package/dist/esm/durable/clientTool.js +82 -0
  157. package/dist/esm/durable/index.d.ts +9 -0
  158. package/dist/esm/durable/index.d.ts.map +1 -0
  159. package/dist/esm/durable/index.js +8 -0
  160. package/dist/esm/durable/journal.d.ts +218 -0
  161. package/dist/esm/durable/journal.d.ts.map +1 -0
  162. package/dist/esm/durable/journal.js +374 -0
  163. package/dist/esm/durable/pause.d.ts +84 -0
  164. package/dist/esm/durable/pause.d.ts.map +1 -0
  165. package/dist/esm/durable/pause.js +226 -0
  166. package/dist/esm/durable/resume.d.ts +27 -0
  167. package/dist/esm/durable/resume.d.ts.map +1 -0
  168. package/dist/esm/durable/resume.js +72 -0
  169. package/dist/esm/durable/snapshotSaver.d.ts +38 -0
  170. package/dist/esm/durable/snapshotSaver.d.ts.map +1 -0
  171. package/dist/esm/durable/snapshotSaver.js +77 -0
  172. package/dist/esm/durable/step.d.ts +28 -0
  173. package/dist/esm/durable/step.d.ts.map +1 -0
  174. package/dist/esm/durable/step.js +36 -0
  175. package/dist/esm/index.d.ts +30 -7
  176. package/dist/esm/index.d.ts.map +1 -1
  177. package/dist/esm/index.js +20 -4
  178. package/dist/esm/infrastructure.d.ts +50 -0
  179. package/dist/esm/infrastructure.d.ts.map +1 -0
  180. package/dist/esm/infrastructure.js +156 -0
  181. package/dist/esm/langChain.d.ts +15 -3
  182. package/dist/esm/langChain.d.ts.map +1 -1
  183. package/dist/esm/langChain.js +984 -179
  184. package/dist/esm/learningActivityMedia.d.ts +196 -0
  185. package/dist/esm/learningActivityMedia.d.ts.map +1 -0
  186. package/dist/esm/learningActivityMedia.js +807 -0
  187. package/dist/esm/learningContentPlan.d.ts +105 -0
  188. package/dist/esm/learningContentPlan.d.ts.map +1 -0
  189. package/dist/esm/learningContentPlan.js +299 -0
  190. package/dist/esm/learningContentThread.d.ts +184 -0
  191. package/dist/esm/learningContentThread.d.ts.map +1 -0
  192. package/dist/esm/learningContentThread.js +364 -0
  193. package/dist/esm/logger.d.ts +1 -0
  194. package/dist/esm/logger.d.ts.map +1 -1
  195. package/dist/esm/logger.js +17 -3
  196. package/dist/esm/modelRates.d.ts +40 -0
  197. package/dist/esm/modelRates.d.ts.map +1 -0
  198. package/dist/esm/modelRates.js +68 -0
  199. package/dist/esm/referenceContext.d.ts +4 -145
  200. package/dist/esm/referenceContext.d.ts.map +1 -1
  201. package/dist/esm/referenceContext.js +16 -243
  202. package/dist/esm/retry.d.ts +64 -0
  203. package/dist/esm/retry.d.ts.map +1 -0
  204. package/dist/esm/retry.js +127 -0
  205. package/dist/esm/runtimeContext.d.ts +8 -1
  206. package/dist/esm/runtimeContext.d.ts.map +1 -1
  207. package/dist/esm/runtimeContext.js +3 -1
  208. package/dist/esm/serve.d.ts +3 -2
  209. package/dist/esm/serve.d.ts.map +1 -1
  210. package/dist/esm/serve.js +33 -3
  211. package/dist/esm/sourceStore.d.ts +378 -0
  212. package/dist/esm/sourceStore.d.ts.map +1 -0
  213. package/dist/esm/sourceStore.js +855 -0
  214. package/dist/esm/stackfactorKnowledge.d.ts +91 -7
  215. package/dist/esm/stackfactorKnowledge.d.ts.map +1 -1
  216. package/dist/esm/stackfactorKnowledge.js +101 -41
  217. package/dist/esm/tavily.d.ts +108 -4
  218. package/dist/esm/tavily.d.ts.map +1 -1
  219. package/dist/esm/tavily.js +237 -20
  220. package/dist/esm/usage.d.ts.map +1 -1
  221. package/dist/esm/usage.js +9 -15
  222. package/dist/esm/version.d.ts +3 -0
  223. package/dist/esm/version.d.ts.map +1 -0
  224. package/dist/esm/version.js +2 -0
  225. package/dist/esm/workflow/bookkeeping.d.ts +78 -0
  226. package/dist/esm/workflow/bookkeeping.d.ts.map +1 -0
  227. package/dist/esm/workflow/bookkeeping.js +67 -0
  228. package/dist/esm/workflow/index.d.ts +13 -0
  229. package/dist/esm/workflow/index.d.ts.map +1 -0
  230. package/dist/esm/workflow/index.js +10 -0
  231. package/dist/esm/workflow/limits.d.ts +52 -0
  232. package/dist/esm/workflow/limits.d.ts.map +1 -0
  233. package/dist/esm/workflow/limits.js +59 -0
  234. package/dist/esm/workflow/platformTransport.d.ts +39 -0
  235. package/dist/esm/workflow/platformTransport.d.ts.map +1 -0
  236. package/dist/esm/workflow/platformTransport.js +110 -0
  237. package/dist/esm/workflow/retrying.d.ts +44 -0
  238. package/dist/esm/workflow/retrying.d.ts.map +1 -0
  239. package/dist/esm/workflow/retrying.js +73 -0
  240. package/dist/esm/workflow/run.d.ts +195 -0
  241. package/dist/esm/workflow/run.d.ts.map +1 -0
  242. package/dist/esm/workflow/run.js +850 -0
  243. package/dist/esm/workflow/testing/index.d.ts +3 -0
  244. package/dist/esm/workflow/testing/index.d.ts.map +1 -0
  245. package/dist/esm/workflow/testing/index.js +2 -0
  246. package/dist/esm/workflow/testing/memoryTransport.d.ts +203 -0
  247. package/dist/esm/workflow/testing/memoryTransport.d.ts.map +1 -0
  248. package/dist/esm/workflow/testing/memoryTransport.js +1167 -0
  249. package/dist/esm/workflow/transport.d.ts +219 -0
  250. package/dist/esm/workflow/transport.d.ts.map +1 -0
  251. package/dist/esm/workflow/transport.js +16 -0
  252. package/package.json +8 -7
@@ -3,7 +3,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.getLLMModel = void 0;
6
+ exports.isRateLimitError = exports.getLLMModel = void 0;
7
7
  const openai_1 = require("@langchain/openai");
8
8
  const anthropic_1 = require("@langchain/anthropic");
9
9
  const google_genai_1 = require("@langchain/google-genai");
@@ -11,12 +11,20 @@ const openai_2 = require("openai");
11
11
  const genai_1 = require("@google/genai");
12
12
  const const_js_1 = __importDefault(require("./const.js"));
13
13
  const langchain_1 = require("langchain");
14
+ const langgraph_1 = require("@langchain/langgraph");
14
15
  const errorHandling_js_1 = __importDefault(require("./errorHandling.js"));
15
16
  const logger_js_1 = __importDefault(require("./logger.js"));
17
+ const retry_js_1 = require("./retry.js");
16
18
  const zod_1 = require("zod");
17
19
  const transform_json_schema_1 = require("@anthropic-ai/sdk/lib/transform-json-schema");
18
20
  const runtimeContext_js_1 = require("./runtimeContext.js");
21
+ const cancellation_js_1 = require("./cancellation.js");
19
22
  const usage_js_1 = require("./usage.js");
23
+ const modelRates_js_1 = require("./modelRates.js");
24
+ const journal_js_1 = require("./durable/journal.js");
25
+ const snapshotSaver_js_1 = require("./durable/snapshotSaver.js");
26
+ const clientTool_js_1 = require("./durable/clientTool.js");
27
+ const limits_js_1 = require("./workflow/limits.js");
20
28
  const tavily_js_1 = require("./tavily.js");
21
29
  const JSON_ESCAPE_INSTRUCTION = `
22
30
  CRITICAL - Your response must be valid JSON. Escape ALL special characters in string values:
@@ -29,7 +37,7 @@ Do NOT include raw newlines, tabs, or unescaped quotes inside JSON string values
29
37
  `.trim();
30
38
  /**
31
39
  * Providers for which `getLLMModel` configures native, schema-constrained JSON
32
- * output (OpenAI `response_format`, Anthropic `output_config.format`, Gemini
40
+ * output (OpenAI `text.format`, Anthropic `output_config.format`, Gemini
33
41
  * `responseSchema` + JSON mode). For these the model emits JSON directly, so the
34
42
  * prompt-injected schema and the schema-validation retry are skipped. Every
35
43
  * supported provider is listed here; the check remains so that adding one
@@ -113,9 +121,12 @@ const countUsage = (tracker, modelName, unit, amount) => {
113
121
  if (!Number.isFinite(amount) || amount <= 0)
114
122
  return;
115
123
  (0, usage_js_1.recordUsage)(modelName, unit, amount);
124
+ const key = `${modelName}_${unit}`;
125
+ // A journaled unit keeps what it used, so a replay gives it back to the
126
+ // caller's tracker without reporting it again (durable/journal.ts).
127
+ (0, journal_js_1.noteUsage)(key, amount);
116
128
  if (!tracker)
117
129
  return;
118
- const key = `${modelName}_${unit}`;
119
130
  tracker.tokens[key] = (tracker.tokens[key] || 0) + amount;
120
131
  };
121
132
  /** Makes `{}` a tracker. `cost` stays 0: the platform prices what was used. */
@@ -295,9 +306,11 @@ const accumulateChunkUsage = (acc, chunk) => {
295
306
  /**
296
307
  * Sums token usage across every message in an agent invocation response. Each
297
308
  * AIMessage in `response.messages` may carry its own `usage_metadata` (one per
298
- * LLM round-trip the agent made).
309
+ * LLM round-trip the agent made). `counted` leaves out the messages whose
310
+ * usage was counted already: a resumed agent's answer carries the
311
+ * conversation it paused in, which the run that paused it counted.
299
312
  */
300
- const sumAgentResponseUsage = (response) => {
313
+ const sumAgentResponseUsage = (response, counted = null) => {
301
314
  const messages = response?.messages;
302
315
  if (!Array.isArray(messages) || messages.length === 0)
303
316
  return null;
@@ -308,6 +321,8 @@ const sumAgentResponseUsage = (response) => {
308
321
  };
309
322
  let found = false;
310
323
  for (const msg of messages) {
324
+ if (counted && counted.has(msg?.id))
325
+ continue;
311
326
  const um = msg?.usage_metadata;
312
327
  if (um) {
313
328
  total.input_tokens += um.input_tokens || 0;
@@ -415,10 +430,13 @@ const isHTMLResponse = (text) => {
415
430
  * include markdown code fences, invalid escape sequences, control characters, or other
416
431
  * extraneous formatting. Falls back through multiple strategies in order:
417
432
  * 1. Direct parse after stripping fences and fixing `\'` escapes
418
- * 2. Extract and parse the first `{...}` object block
419
- * 3. Same as above after sanitising control characters and normalising line endings
420
- * 4. Extract and parse the first `[...]` array block (with the same sanitisation)
421
- * 5. Strip all non-printable characters and retry both object and array extraction
433
+ * 2. A body escaped once too often, unescaped: parsed directly, then read by
434
+ * the block strategies below
435
+ * 3. The block strategies on the text itself (`parseJsonBlock`): the first
436
+ * `{...}` object or `[...]` array block as it is, with control characters
437
+ * sanitised, then with invisible characters removed
438
+ *
439
+ * Nothing repairs structure: an answer with a bracket too many is not JSON.
422
440
  *
423
441
  * Returns `null` if every strategy fails. Throws an error with `BAD_GATEWAY` if the
424
442
  * response appears to be an HTML page (likely an API error or rate-limit redirect).
@@ -432,72 +450,226 @@ const extractJSONFromResponse = (text) => {
432
450
  if (isHTMLResponse(text)) {
433
451
  throw errorHandling_js_1.default.create(const_js_1.default.HTTP_CODES.BAD_GATEWAY, "LLM API returned HTML instead of JSON. This may indicate an API error, rate limit, or network issue. Please retry.");
434
452
  }
435
- // Remove markdown code blocks and fix invalid escape sequences
436
- const cleaned = text
437
- .replace(/```json\s*/gi, "")
438
- .replace(/```\s*/g, "")
439
- .replace(/\\'/g, "'") // Fix invalid \' escape (not valid in JSON)
440
- .trim();
441
- // Try parsing directly first
453
+ const cleaned = withoutFences(text);
454
+ // Try parsing directly first. A JSON string holding an object or array
455
+ // (an answer quoted once too often) is parsed again for what it holds.
442
456
  try {
443
- return JSON.parse(cleaned);
457
+ const value = JSON.parse(cleaned);
458
+ return typeof value === "string" ? (jsonHeldBy(value) ?? value) : value;
444
459
  }
445
460
  catch {
446
461
  // Continue to fallback methods
447
462
  }
448
- // Try to find JSON object boundaries
449
- const jsonMatch = cleaned.match(/\{[\s\S]*\}/);
450
- if (jsonMatch) {
463
+ // A JSON body escaped once too often: a JSON string's contents without
464
+ // its quotes — `{\"keptIds\":[\"m0\"]}` with literal backslashes, as Claude
465
+ // and Gemini both answered in production (2026-11-09). Unescaping it once
466
+ // gives the JSON itself, or text the block strategies read like any other:
467
+ // the body wrapped in prose, or holding a raw line break inside a value.
468
+ const unescaped = unescapeJsonBody(cleaned);
469
+ if (unescaped !== null) {
451
470
  try {
452
- return JSON.parse(jsonMatch[0]);
471
+ return JSON.parse(unescaped);
453
472
  }
454
473
  catch {
455
- // Try cleaning special characters
456
- try {
457
- const sanitized = jsonMatch[0]
458
- .replace(/[\u0000-\u001F\u007F-\u009F]/g, " ") // Remove control characters
459
- .replace(/\r\n/g, "\\n") // Normalize line endings
460
- .replace(/\r/g, "\\n")
461
- .replace(/\t/g, "\\t"); // Escape tabs
462
- return JSON.parse(sanitized);
463
- }
464
- catch {
465
- // Continue to next fallback
466
- }
474
+ // not JSON as it stands: a block inside it may be
467
475
  }
468
- }
469
- // Try to find JSON array boundaries
470
- const arrayMatch = cleaned.match(/\[[\s\S]*\]/);
471
- if (arrayMatch) {
476
+ const held = parseJsonBlock(unescaped).value;
477
+ if (held !== undefined)
478
+ return held;
479
+ }
480
+ // A body escaped in part: it opens as plain JSON and escapes its quotes
481
+ // somewhere inside (`{"a":[],\"b\":[{\"c\":\"d\"}],"e":[]}`), as Gemini
482
+ // answered a review in production (2026-11-16). Unescaping the whole of it
483
+ // would break the plain part, so each string is closed the way it opened.
484
+ const mended = withEscapedStringsMended(cleaned);
485
+ if (mended !== null) {
472
486
  try {
473
- return JSON.parse(arrayMatch[0]);
487
+ return JSON.parse(mended);
474
488
  }
475
489
  catch {
490
+ // not JSON even so
491
+ }
492
+ }
493
+ return parseJsonBlock(cleaned).value ?? null;
494
+ };
495
+ /** An answer without its markdown code fences and its invalid `\'` escapes, trimmed. */
496
+ const withoutFences = (text) => text
497
+ .replace(/```json\s*/gi, "")
498
+ .replace(/```\s*/g, "")
499
+ .replace(/\\'/g, "'") // Fix invalid \' escape (not valid in JSON)
500
+ .trim();
501
+ const OBJECT_BLOCK = /\{[\s\S]*\}/;
502
+ const ARRAY_BLOCK = /\[[\s\S]*\]/;
503
+ /**
504
+ * The block strategies: the JSON a block inside `text` holds. The array when
505
+ * the text opens with one (an array of objects would otherwise be read as its
506
+ * first object alone), else the object. Each block as it is, then with control
507
+ * characters sanitised, then with invisible characters removed — never with
508
+ * its non-ASCII text blanked, which would damage every accent and dash in the
509
+ * values. Nothing is repaired: a block that is not JSON stays unread.
510
+ * @param text The cleaned answer, or the text an escaped answer stands for
511
+ * @returns `value` when a block parsed; else `failed`, the first block as it
512
+ * was last tried with the parse error it gave, when the text held a block
513
+ */
514
+ const parseJsonBlock = (text) => {
515
+ const opensWithArray = /^[^[{]*\[/.test(text);
516
+ const blocks = opensWithArray ? [ARRAY_BLOCK, OBJECT_BLOCK] : [OBJECT_BLOCK, ARRAY_BLOCK];
517
+ let failed;
518
+ for (const pattern of blocks) {
519
+ const block = text.match(pattern)?.[0];
520
+ if (!block)
521
+ continue;
522
+ const sanitized = sanitizeControls(block);
523
+ let last;
524
+ for (const candidate of [block, sanitized, withoutInvisibles(sanitized)]) {
476
525
  try {
477
- const sanitized = arrayMatch[0]
478
- .replace(/[\u0000-\u001F\u007F-\u009F]/g, " ")
479
- .replace(/\r\n/g, "\\n")
480
- .replace(/\r/g, "\\n")
481
- .replace(/\t/g, "\\t");
482
- return JSON.parse(sanitized);
526
+ return { value: JSON.parse(candidate) };
483
527
  }
484
- catch {
485
- // Continue to next fallback
528
+ catch (error) {
529
+ last = { text: candidate, error }; // next candidate
486
530
  }
487
531
  }
532
+ // the first block's failure is the one reported: the reason that outlived every strategy
533
+ failed ??= last;
488
534
  }
489
- // Last resort: strip all non-printable except standard whitespace
535
+ return { failed };
536
+ };
537
+ /** Control characters replaced by spaces, line endings normalised, tabs escaped (what a model pastes into a value raw). */
538
+ const sanitizeControls = (block) => block
539
+ .replace(/[\u0000-\u001F\u007F-\u009F]/g, " ")
540
+ .replace(/\r\n/g, "\\n")
541
+ .replace(/\r/g, "\\n")
542
+ .replace(/\t/g, "\\t");
543
+ /**
544
+ * Invisible characters a model may leave in its answer — a byte-order mark, a
545
+ * soft hyphen, zero-width and directional marks — removed; a non-breaking
546
+ * space becomes a space. Printable text in any script is kept.
547
+ */
548
+ const withoutInvisibles = (block) => block.replace(/[\u00AD\u200B-\u200F\u2028-\u202E\u2060-\u206F\uFEFF]/g, "").replace(/\u00A0/g, " ");
549
+ /**
550
+ * The object or array a string holds when it is JSON itself (`'{"a":1}'`);
551
+ * null when it is any other text.
552
+ * @param text A string value a model answered
553
+ */
554
+ const jsonHeldBy = (text) => {
555
+ const trimmed = text.trim();
556
+ if (!/^[[{]/.test(trimmed))
557
+ return null;
490
558
  try {
491
- const stripped = cleaned.replace(/[^\x20-\x7E\n]/g, " ");
492
- const finalMatch = stripped.match(/\{[\s\S]*\}/) || stripped.match(/\[[\s\S]*\]/);
493
- if (finalMatch) {
494
- return JSON.parse(finalMatch[0]);
559
+ const value = JSON.parse(trimmed);
560
+ return typeof value === "object" && value !== null ? value : null;
561
+ }
562
+ catch {
563
+ return null;
564
+ }
565
+ };
566
+ /**
567
+ * A JSON text some of whose strings were escaped once too often, with those
568
+ * strings unescaped: outside a string, `\"` can only be a quote the model
569
+ * escaped by mistake, so it opens a string that the next bare `\"` closes,
570
+ * and what lies between is read one level down (`\\\"` is a quote inside the
571
+ * string, `\\n` a line break in it). A string opened by a plain quote is
572
+ * left exactly as it is, and so is everything else. A `\n`, `\r` or `\t`
573
+ * between tokens, where the escaped part was pretty-printed, is white space.
574
+ * Null when no string opens with an escaped quote: there is nothing to mend,
575
+ * and valid JSON never does.
576
+ * @param text The cleaned answer
577
+ */
578
+ const withEscapedStringsMended = (text) => {
579
+ let out = "";
580
+ let mended = false;
581
+ // Where the walk is: outside any string, in one a plain quote opened, or in
582
+ // one an escaped quote opened.
583
+ let within = "none";
584
+ for (let i = 0; i < text.length; i += 1) {
585
+ const char = text[i];
586
+ const next = text[i + 1];
587
+ if (within === "none") {
588
+ if (char === "\\" && next === '"') {
589
+ out += '"';
590
+ within = "escaped";
591
+ mended = true;
592
+ i += 1;
593
+ }
594
+ else if (char === "\\" && (next === "n" || next === "r" || next === "t")) {
595
+ out += " ";
596
+ i += 1;
597
+ }
598
+ else {
599
+ if (char === '"')
600
+ within = "plain";
601
+ out += char;
602
+ }
603
+ }
604
+ else if (within === "plain") {
605
+ if (char === "\\" && next !== undefined) {
606
+ out += char + next;
607
+ i += 1;
608
+ }
609
+ else {
610
+ if (char === '"')
611
+ within = "none";
612
+ out += char;
613
+ }
614
+ }
615
+ else if (char !== "\\") {
616
+ out += char;
617
+ }
618
+ else if (next === '"') {
619
+ out += '"';
620
+ within = "none";
621
+ i += 1;
622
+ }
623
+ else if (next === "\\") {
624
+ // An escaped backslash stands for the backslash of an escape one level
625
+ // down: what follows it is that escape's character, itself escaped
626
+ // when it is a quote or a backslash.
627
+ const after = text[i + 2];
628
+ const escapedAfter = after === "\\" && (text[i + 3] === '"' || text[i + 3] === "\\");
629
+ out += `\\${escapedAfter ? text[i + 3] : (after ?? "")}`;
630
+ i += escapedAfter ? 3 : 2;
631
+ }
632
+ else {
633
+ out += char;
495
634
  }
496
635
  }
636
+ return mended ? out : null;
637
+ };
638
+ /**
639
+ * A JSON string's contents without the quote left at either end: a model that
640
+ * answers a JSON string may drop one of its two quotes and keep the other
641
+ * (`{\"a\":1}"`, prod 2026-11-15), and with both kept a raw control
642
+ * character inside still fails the direct parse. A quote at the start, and one
643
+ * at the end that no backslash escapes, is a delimiter and not part of the
644
+ * contents: every quote inside a string's contents is escaped.
645
+ * @param text The cleaned answer, carrying JSON escapes
646
+ */
647
+ const withoutStrayQuotes = (text) => {
648
+ const opened = text.startsWith('"') ? text.slice(1) : text;
649
+ const backslashes = /(\\*)"$/.exec(opened)?.[1].length;
650
+ return backslashes !== undefined && backslashes % 2 === 0 ? opened.slice(0, -1) : opened;
651
+ };
652
+ /**
653
+ * The text a JSON string's escaped contents stand for: `text` carrying JSON
654
+ * escapes (`\"`, `\n`) parsed once, between quotes, into the string it
655
+ * encodes. Raw control characters — a line break or a tab between the tokens
656
+ * of a pretty-printed body, or inside a value — are kept as they are: a JSON
657
+ * string may not hold one raw, so each is escaped for the parse, which before
658
+ * 2026-11-13 failed on them and left the answer unread. A quote the answer
659
+ * kept at either end is set aside first (withoutStrayQuotes). Null when
660
+ * `text` carries no escape or is not a string's contents.
661
+ * @param text The cleaned answer
662
+ */
663
+ const unescapeJsonBody = (text) => {
664
+ if (!/\\["\\nrt]/.test(text))
665
+ return null;
666
+ const contents = withoutStrayQuotes(text).replace(/[\u0000-\u001F]/g, (control) => `\\u${control.charCodeAt(0).toString(16).padStart(4, "0")}`);
667
+ try {
668
+ return JSON.parse(`"${contents}"`);
669
+ }
497
670
  catch {
498
- // All attempts failed
671
+ return null;
499
672
  }
500
- return null;
501
673
  };
502
674
  /**
503
675
  * Whether a model accepts the `temperature` sampling parameter at all. Some
@@ -527,6 +699,35 @@ const modelSupportsTemperature = (modelName) => {
527
699
  return false;
528
700
  return true;
529
701
  };
702
+ /**
703
+ * Whether an OpenAI model reasons before it answers: the GPT-5 and GPT-6
704
+ * generations, bar the `gpt-5-chat` ids, which do not. Such a model can hand
705
+ * back its reasoning in encrypted form for the next turn of a tool loop; one
706
+ * that does not reason is refused the request field that asks for it.
707
+ * @param modelName - the model identifier being routed
708
+ * @returns `true` when the model reasons
709
+ */
710
+ const openAIModelReasons = (modelName) => /^gpt-[56]($|[.-])/.test(modelName) && !modelName.startsWith("gpt-5-chat");
711
+ /**
712
+ * Whether a Claude model refuses to run with thinking turned off.
713
+ * @langchain/anthropic sends `thinking: {type: "disabled"}` unless told
714
+ * otherwise, which Claude Opus 5.5, Sonnet 5.5, Fable 5/5.1 and Mythos 5/5.1
715
+ * reject with a 400; on these thinking is always on and effort is the only
716
+ * control. Opus 5, Sonnet 5, Haiku 5.5 and earlier still accept it disabled.
717
+ * @param modelName - the model identifier being routed
718
+ * @returns `true` when the model must be sent adaptive thinking
719
+ */
720
+ const modelRequiresThinking = (modelName) => {
721
+ if (!modelName)
722
+ return false;
723
+ if (/^claude-(fable|mythos)-/.test(modelName))
724
+ return true;
725
+ if (/^claude-(opus|sonnet)-5-([5-9]|\d\d)\b/.test(modelName))
726
+ return true;
727
+ if (/^claude-(opus|sonnet)-([6-9]|\d\d)\b/.test(modelName))
728
+ return true;
729
+ return false;
730
+ };
530
731
  /**
531
732
  * Per-provider valid `temperature` range, used to clamp caller-supplied values.
532
733
  * Anthropic caps at 1.0; OpenAI and Gemini accept up to 2.0. Only consulted for
@@ -565,6 +766,58 @@ const resolveTemperatureSetting = (modelName, config) => {
565
766
  }
566
767
  return { temperature: clamped };
567
768
  };
769
+ /** The `output_config.effort` levels Anthropic accepts, lowest first. */
770
+ const EFFORT_LEVELS = ["low", "medium", "high", "xhigh", "max"];
771
+ /**
772
+ * Whether a Claude model accepts `output_config.effort`. Anthropic added it
773
+ * with Opus 4.6 and Sonnet 4.6; every later Opus and Sonnet (4.7, 4.8, …),
774
+ * the whole 5-series (Opus, Sonnet and Haiku) and Fable / Mythos take it.
775
+ * Haiku 4.5, Opus 4.5, Sonnet 4.5 and earlier reject it with a 400. Only the
776
+ * Claude branch of getLLMModel consults this: other providers' models never
777
+ * see the setting and raise no warning for it.
778
+ * @param modelName - the model identifier being routed
779
+ * @returns `true` when the model accepts an `effort` setting
780
+ */
781
+ const modelSupportsEffort = (modelName) => {
782
+ if (/^claude-(fable|mythos)-/.test(modelName))
783
+ return true;
784
+ if (/^claude-(opus|sonnet)-4-([6-9]|\d\d)\b/.test(modelName))
785
+ return true;
786
+ if (/^claude-(opus|sonnet|haiku)-([5-9]|\d\d)\b/.test(modelName))
787
+ return true;
788
+ return false;
789
+ };
790
+ /**
791
+ * Resolves the `reasoningEffort` model setting (`config.reasoningEffort`) for
792
+ * a Claude model. It becomes `output_config.effort`, the one control over how
793
+ * much a 5-series model thinks (Opus 5.5 defaults to `medium`, Opus 5 to
794
+ * `high`, so an agent that wants parity across them sets it explicitly).
795
+ * Applied in order:
796
+ * 1. presence — an absent or empty value leaves the provider default;
797
+ * 2. validity — a value outside `EFFORT_LEVELS` is ignored, with a warning;
798
+ * 3. support — a model that rejects the parameter gets it omitted, with a
799
+ * warning, to avoid an HTTP 400.
800
+ * Returns the level to send, or `undefined` when the field should be omitted.
801
+ */
802
+ const resolveEffortSetting = (modelName, config) => {
803
+ const effort = config?.reasoningEffort;
804
+ if (effort === undefined || effort === null || effort === "") {
805
+ return undefined;
806
+ }
807
+ if (typeof effort !== "string" ||
808
+ !EFFORT_LEVELS.includes(effort)) {
809
+ // Described, not serialised: a bigint or a cyclic object would make
810
+ // JSON.stringify throw from inside a warning that must never throw.
811
+ const shown = typeof effort === "string" ? `"${effort}"` : `of type ${typeof effort}`;
812
+ logger_js_1.default.log(null, logger_js_1.default.levels.warn, `Reasoning effort ${shown} is not one of ${EFFORT_LEVELS.join(", ")}; ignoring it for "${modelName}".`);
813
+ return undefined;
814
+ }
815
+ if (!modelSupportsEffort(modelName)) {
816
+ logger_js_1.default.log(null, logger_js_1.default.levels.warn, `Model "${modelName}" does not accept a reasoning effort parameter; ignoring configured effort "${effort}".`);
817
+ return undefined;
818
+ }
819
+ return effort;
820
+ };
568
821
  /**
569
822
  * Flattens LangChain message content into plain text. Content is a string for
570
823
  * ordinary completions, but providers switch to an array of blocks whenever the
@@ -594,7 +847,7 @@ const extractTextContent = (content) => {
594
847
  * name prefix. `claude-` maps to `ChatAnthropic`, `gemini-` maps to
595
848
  * `ChatGoogleGenerativeAI`, and `gpt-` maps to `ChatOpenAI`. When a Zod
596
849
  * `schema` is provided, native structured output is configured per provider: OpenAI
597
- * via `response_format` with `json_schema`, Anthropic via `output_config.format`, and
850
+ * via `text.format` with `json_schema` (the Responses API), Anthropic via `output_config.format`, and
598
851
  * Gemini via JSON mode (`json: true`) plus `responseSchema`. In every case the model
599
852
  * emits JSON as the message text, so the caller's parse/validate pipeline is unchanged.
600
853
  * Throws a `BAD_REQUEST` error for unrecognised model names.
@@ -606,7 +859,8 @@ const extractTextContent = (content) => {
606
859
  * @param modelName - The model identifier, e.g. `"gpt-4o"`, `"claude-3-5-sonnet"`,
607
860
  * `"gemini-1.5-pro"`
608
861
  * @param config - Configuration object containing API keys (`openAIAPIKey`,
609
- * `anthropicAPIKey`, `googleAPIKey`) and optional `temperature`
862
+ * `anthropicAPIKey`, `googleAPIKey`) and optional `temperature` and
863
+ * `reasoningEffort` (Claude models from Opus 4.6 / Sonnet 4.6 on)
610
864
  * @param schema - Optional Zod schema used to configure native structured JSON output
611
865
  * @returns A configured LangChain chat model (or bound runnable) instance
612
866
  */
@@ -635,15 +889,30 @@ const getLLMModel = (modelName, config, schema = null) => {
635
889
  // `transformJSONSchema` applies the same strict-schema normalisation
636
890
  // (additionalProperties: false, required fields) that @langchain/anthropic
637
891
  // uses internally, which the API requires.
638
- const outputConfig = schema
639
- ? {
640
- outputConfig: {
892
+ //
893
+ // `output_config.effort` rides in the same object when the agent's config
894
+ // sets `reasoningEffort` and the model takes it (see resolveEffortSetting).
895
+ // The field is left off entirely when neither applies, so the request
896
+ // carries no `output_config` at all in that case.
897
+ const effort = resolveEffortSetting(modelName, config);
898
+ const outputConfigFields = {
899
+ ...(schema
900
+ ? {
641
901
  format: {
642
902
  type: "json_schema",
643
903
  schema: (0, transform_json_schema_1.transformJSONSchema)(zod_1.z.toJSONSchema(schema)),
644
904
  },
645
- },
646
- }
905
+ }
906
+ : {}),
907
+ ...(effort ? { effort } : {}),
908
+ };
909
+ const outputConfig = Object.keys(outputConfigFields).length
910
+ ? { outputConfig: outputConfigFields }
911
+ : {};
912
+ // Thinking blocks in the answer are dropped by extractTextContent, so the
913
+ // parse pipeline still sees only the JSON text.
914
+ const thinking = modelRequiresThinking(modelName)
915
+ ? { thinking: { type: "adaptive" } }
647
916
  : {};
648
917
  const model = new anthropic_1.ChatAnthropic({
649
918
  apiKey: config.anthropicAPIKey,
@@ -652,6 +921,7 @@ const getLLMModel = (modelName, config, schema = null) => {
652
921
  streaming: true,
653
922
  invocationKwargs: { cache_control: { type: "ephemeral" } },
654
923
  ...outputConfig,
924
+ ...thinking,
655
925
  ...modelSettings,
656
926
  });
657
927
  return model;
@@ -682,47 +952,56 @@ const getLLMModel = (modelName, config, schema = null) => {
682
952
  }
683
953
  // GPT models (OpenAI)
684
954
  else if (modelName.startsWith("gpt-")) {
955
+ // Every OpenAI call goes to the Responses API (/v1/responses), never to
956
+ // Chat Completions. Chat Completions refuses function tools beside a
957
+ // reasoning model's reasoning (prod, 2026-11-16: every judging call that
958
+ // had a page to read failed with "400 Function tools with reasoning_effort
959
+ // are not supported for gpt-6.1-sol in /v1/chat/completions. To use
960
+ // function tools, use /v1/responses or set reasoning_effort to 'none'";
961
+ // the gpt-5.6 family fails the same way). Turning reasoning off to get
962
+ // tools gives up what a strong-tier model is chosen for; on the Responses
963
+ // API a model reasons and calls tools in the same request, so no model is
964
+ // sent a reasoning override. One endpoint for every `gpt-` model keeps one
965
+ // request shape to reason about, whatever the model and with or without
966
+ // tools.
967
+ //
968
+ // `zdrEnabled` sends `store: false`: the Responses API keeps each response
969
+ // on OpenAI's side by default, and Chat Completions kept nothing, so
970
+ // nothing is kept here either. With nothing stored, a tool loop has to
971
+ // carry the model's reasoning itself: a reasoning model is asked for its
972
+ // reasoning in encrypted form (`include`), which LangChain hands back on
973
+ // the next turn of the loop. Models that do not reason are not asked: the
974
+ // API refuses the field for them.
685
975
  const openAISettings = {
686
976
  apiKey: config.openAIAPIKey,
687
- // No output limit is sent: OpenAI defaults to the model's maximum. The
688
- // snake_case `max_tokens` that used to sit here was never a recognised
689
- // ChatOpenAI field and was silently dropped by LangChain.
977
+ // No output limit is sent: OpenAI defaults to the model's maximum.
690
978
  modelName: modelName,
691
979
  ...modelSettings,
980
+ useResponsesApi: true,
981
+ zdrEnabled: true,
692
982
  };
693
- // The gpt-5.6 family's /v1/chat/completions endpoint 400s whenever function
694
- // tools are bound, because it rejects the model's own server-side default
695
- // reasoning effort in that combination ("use /v1/responses or set
696
- // reasoning_effort to 'none'"); forcing it to "none" here avoids the
697
- // collision. The restriction belongs to the family, not to one id: the
698
- // `gpt-5.6` alias resolves to `gpt-5.6-sol`, and `gpt-5.6-terra` /
699
- // `gpt-5.6-luna` are separately addressable ids that hit the same 400, as
700
- // do dated snapshots (`gpt-5.6-2026-08-22`). Matching the alias alone left
701
- // every one of those unpatched, so match the whole family. Still excludes
702
- // sibling releases (gpt-5.5, gpt-5.7): they are not confirmed to share the
703
- // bug, and reasoning effort is worth keeping wherever it is accepted.
704
- const reasoningEffortOverride = /^gpt-5\.6($|-)/.test(modelName)
705
- ? { reasoning_effort: "none" }
706
- : {};
707
- // Use native structured output with a JSON schema. `modelKwargs` is spread
708
- // verbatim into the Chat Completions request. Merge (not overwrite) with
709
- // the reasoning-effort override above, since both may apply at once.
710
- if (schema) {
711
- const jsonSchema = strictifyJsonSchema(buildJsonSchema(schema));
712
- openAISettings.modelKwargs = {
713
- ...reasoningEffortOverride,
714
- response_format: {
715
- type: "json_schema",
716
- json_schema: {
717
- name: "response_schema",
718
- strict: true,
719
- schema: jsonSchema,
983
+ // `modelKwargs` is spread verbatim into the Responses request. Native
984
+ // structured output is `text.format` there (Chat Completions called it
985
+ // `response_format`, with the schema one level deeper).
986
+ const modelKwargs = {
987
+ ...(openAIModelReasons(modelName)
988
+ ? { include: ["reasoning.encrypted_content"] }
989
+ : {}),
990
+ ...(schema
991
+ ? {
992
+ text: {
993
+ format: {
994
+ type: "json_schema",
995
+ name: "response_schema",
996
+ strict: true,
997
+ schema: strictifyJsonSchema(buildJsonSchema(schema)),
998
+ },
720
999
  },
721
- },
722
- };
723
- }
724
- else if (Object.keys(reasoningEffortOverride).length > 0) {
725
- openAISettings.modelKwargs = { ...reasoningEffortOverride };
1000
+ }
1001
+ : {}),
1002
+ };
1003
+ if (Object.keys(modelKwargs).length > 0) {
1004
+ openAISettings.modelKwargs = modelKwargs;
726
1005
  }
727
1006
  return new openai_1.ChatOpenAI(openAISettings);
728
1007
  }
@@ -743,9 +1022,12 @@ exports.getLLMModel = getLLMModel;
743
1022
  * etc.), plus optional `tavily` (`true` or a `TavilyConfig`) to append the web tools
744
1023
  * @param usageTracker - Optional accumulator the Tavily tools bill their credits and
745
1024
  * record their sources into; the LLM's own token usage is tracked by `runAgent`
1025
+ * @param options - Optional LangChain `middleware` and `checkpointer`. An agent whose
1026
+ * checkpointer is a `durable.SnapshotSaver` can pause inside a `workflow.run` turn
1027
+ * (an interrupt in a tool or a middleware) and resume in another run
746
1028
  * @returns A configured LangChain agent instance ready to be run with `runAgent`
747
1029
  */
748
- const createAgent = (name, modelName, systemPrompt, tools = [], responseFormat, config, usageTracker = null) => {
1030
+ const createAgent = (name, modelName, systemPrompt, tools = [], responseFormat, config, usageTracker = null, options = {}) => {
749
1031
  // The Tavily tools join the agent's tool list rather than being bound inside
750
1032
  // `getLLMModel`: they run client-side, so only the agent loop can execute
751
1033
  // them, and the agent binds its own tools to the model anyway — anything
@@ -762,18 +1044,48 @@ const createAgent = (name, modelName, systemPrompt, tools = [], responseFormat,
762
1044
  systemPrompt: systemPrompt.trim(),
763
1045
  tools: tavilyTools.length > 0 ? [...tools, ...tavilyTools] : tools,
764
1046
  ...(responseFormat ? { responseFormat: responseFormat } : {}),
1047
+ ...(options?.middleware?.length ? { middleware: options.middleware } : {}),
1048
+ ...(options?.checkpointer ? { checkpointer: options.checkpointer } : {}),
765
1049
  });
766
1050
  return agent;
767
1051
  };
768
1052
  // What the progress bar says while each tool agent-utils registers (the
769
- // Tavily tools in tavily.ts) runs. A Map, so a tool named after an
770
- // Object.prototype key ("constructor") is not mistaken for a label.
1053
+ // Tavily tools in tavily.ts, the source tool in sourceStore.ts) runs. A Map,
1054
+ // so a tool named after an Object.prototype key ("constructor") is not
1055
+ // mistaken for a label. The source tool says more itself, by title, to a
1056
+ // caller that gives it `onProgress`; these are what is said without it.
771
1057
  const TOOL_PROGRESS_LABELS = new Map([
772
1058
  ["web_search", "Searching the web"],
773
1059
  ["web_extract", "Reading web pages"],
774
1060
  ["web_map", "Listing the pages of a site"],
775
1061
  ["web_crawl", "Reading the pages of a site"],
1062
+ ["list_sources", "Looking over the references"],
1063
+ ["get_outline", "Looking through a reference"],
1064
+ ["read_pages", "Reading a reference"],
1065
+ ["read_document", "Reading a reference"],
1066
+ ]);
1067
+ // The lucide icon the progress dialog shows while each of those tools runs.
1068
+ // A tool without one (an agent's own) sends none, and the dialog keeps its own.
1069
+ const TOOL_PROGRESS_ICONS = new Map([
1070
+ ["web_search", "search"],
1071
+ ["web_extract", "globe"],
1072
+ ["web_map", "map"],
1073
+ ["web_crawl", "file-search"],
1074
+ ["list_sources", "list"],
1075
+ ["get_outline", "list"],
1076
+ ["read_pages", "book-open"],
1077
+ ["read_document", "book-open"],
776
1078
  ]);
1079
+ /**
1080
+ * The `icon` field of a tool call's progress event: the tool's icon, or
1081
+ * nothing at all when it has none.
1082
+ * @param name - The tool's registered name
1083
+ * @returns `{ icon }` to spread into the event, or `{}`
1084
+ */
1085
+ const toolProgressIcon = (name) => {
1086
+ const icon = TOOL_PROGRESS_ICONS.get(String(name ?? ""));
1087
+ return icon ? { icon } : {};
1088
+ };
777
1089
  /**
778
1090
  * The progress message for a tool call, in words the person watching the run
779
1091
  * can read. A tool without a label (an agent's own) reads as its name with
@@ -789,6 +1101,110 @@ const toolProgressLabel = (name) => {
789
1101
  const words = text.replace(/_+/g, " ").trim();
790
1102
  return words ? `Using ${words}` : "Using a tool";
791
1103
  };
1104
+ /**
1105
+ * `agent.invoke`, waiting out a 429 up to MAX_RATE_LIMIT_RETRIES times. The
1106
+ * agent loop may issue many internal LLM calls, but a rate limit surfaces as a
1107
+ * thrown error from the wrapping invoke. `retryInput` says what a retry sends:
1108
+ * the prompt again restarts the run from scratch (an agent without a
1109
+ * checkpointer keeps no state to go on from); `null` continues a
1110
+ * checkpointed thread from its last step, so nothing is appended twice.
1111
+ */
1112
+ const invokeAgent = async (agent, input, options, onProgress, modelName, retryInput) => {
1113
+ let next = input;
1114
+ let rateLimitAttempt = 0;
1115
+ let droppedAttempt = 0;
1116
+ while (true) {
1117
+ // A cancelled request starts no agent run, and one cancelled mid-run
1118
+ // says so, whatever the aborted call inside it threw.
1119
+ (0, cancellation_js_1.throwIfRequestCancelled)();
1120
+ try {
1121
+ return await agent.invoke(next, options);
1122
+ }
1123
+ catch (err) {
1124
+ if ((0, cancellation_js_1.isRequestCancelled)())
1125
+ throw (0, cancellation_js_1.requestCancelledError)();
1126
+ if ((0, exports.isRateLimitError)(err) && rateLimitAttempt < MAX_RATE_LIMIT_RETRIES) {
1127
+ rateLimitAttempt++;
1128
+ const { waitMs, source } = getRateLimitWaitMs(err);
1129
+ const waitSeconds = Math.round(waitMs / 1000);
1130
+ logger_js_1.default.log(null, logger_js_1.default.levels.warn, `Rate limited by "${modelName}" (agent), waiting ${waitSeconds}s before retry (${rateLimitAttempt}/${MAX_RATE_LIMIT_RETRIES}, source=${source}): ${err?.message ?? err}`);
1131
+ if (onProgress) {
1132
+ onProgress({
1133
+ type: "rate_limit",
1134
+ message: `AI service is busy. Retrying in ${waitSeconds}s...`,
1135
+ icon: "hourglass",
1136
+ });
1137
+ }
1138
+ await sleep(waitMs);
1139
+ next = retryInput(next);
1140
+ continue;
1141
+ }
1142
+ const droppedWait = droppedConnectionWait(err, droppedAttempt);
1143
+ if (droppedWait !== null) {
1144
+ droppedAttempt++;
1145
+ logDroppedConnection(modelName, err, droppedWait, droppedAttempt);
1146
+ await sleep(droppedWait);
1147
+ next = retryInput(next);
1148
+ continue;
1149
+ }
1150
+ throw err;
1151
+ }
1152
+ }
1153
+ };
1154
+ /**
1155
+ * The agent run as it always was: from scratch on a 429 (partial progress is
1156
+ * discarded, the agent state isn't externally checkpointed), usage recorded
1157
+ * only on a successful completion, as the non-agentic paths do.
1158
+ */
1159
+ const invokeAndCount = async (agent, freshInput, options, config, onProgress, modelName, usageTracker) => {
1160
+ const response = await invokeAgent(agent, freshInput(), options, onProgress, modelName, freshInput);
1161
+ updateUsageTracker(usageTracker, modelName, sumAgentResponseUsage(response), config);
1162
+ return response;
1163
+ };
1164
+ /**
1165
+ * A journaled agent unit whose agent is checkpointed by a SnapshotSaver
1166
+ * (design #964 §10.2): its thread is its unit key, a 429 continues it from
1167
+ * its last step, and an interrupt pauses the turn with the thread exported.
1168
+ * On the turn's resume, its thread is imported from the checkpoint and
1169
+ * invoked with `Command({ resume })`, the answers by interrupt id, and only
1170
+ * the usage of what the resume added is counted (the run that paused counted
1171
+ * the rest). A finished invocation deletes its thread.
1172
+ */
1173
+ const invokeDurably = async (agent, unit, input, options, config, onProgress, modelName, usageTracker) => {
1174
+ const saver = agent.options.checkpointer;
1175
+ const counted = new Set(unit.paused?.counted ?? []);
1176
+ // The unit's thread is its own: whatever an earlier turn left under its key
1177
+ // in this saver (one that failed mid-way) is not this conversation.
1178
+ await saver.deleteThread(unit.key);
1179
+ let first = input;
1180
+ if (unit.paused) {
1181
+ if (!unit.thread) {
1182
+ throw errorHandling_js_1.default.create(const_js_1.default.HTTP_CODES.INTERNAL_SERVER_ERROR, `durable: ${unit.key} paused and the checkpoint does not hold its thread`);
1183
+ }
1184
+ saver.importThreads({ [unit.key]: unit.thread });
1185
+ first = new langgraph_1.Command({ resume: unit.resume });
1186
+ }
1187
+ const response = await invokeAgent(agent, first, { ...options, configurable: { thread_id: unit.key } }, onProgress, modelName, () => null);
1188
+ updateUsageTracker(usageTracker, modelName, sumAgentResponseUsage(response, counted), config);
1189
+ // Checked on a copy: the type guard would narrow `response` to the interrupt alone.
1190
+ const answered = response;
1191
+ if ((0, langgraph_1.isInterrupted)(answered)) {
1192
+ const ids = (response.messages ?? [])
1193
+ .map((message) => message?.id)
1194
+ .filter((id) => typeof id === "string");
1195
+ unit.pause({
1196
+ interrupts: response.__interrupt__.map((interrupt) => ({ id: String(interrupt.id), value: interrupt.value })),
1197
+ thread: saver.exportThreads([unit.key])[unit.key] ?? null,
1198
+ counted: [...new Set([...counted, ...ids])],
1199
+ options: {
1200
+ approvals: config?.approvals ? { addressees: config.approvals.addressees, deadline: config.approvals.deadline } : null,
1201
+ clientTools: config?.clientTools ? { addressees: config.clientTools.addressees, deadline: config.clientTools.deadline } : null,
1202
+ },
1203
+ });
1204
+ }
1205
+ await saver.deleteThread(unit.key);
1206
+ return response;
1207
+ };
792
1208
  /**
793
1209
  * Executes a LangChain agent with a single user prompt and returns the raw agent
794
1210
  * response. When an `onProgress` callback is provided, LangChain callbacks are
@@ -825,23 +1241,30 @@ const runAgent = async (agent, prompt, config, onProgress = null, usageTracker =
825
1241
  onProgress({
826
1242
  type: "tool_start",
827
1243
  message: toolProgressLabel(name),
1244
+ ...toolProgressIcon(name),
828
1245
  tool: name,
829
1246
  progress,
830
1247
  });
831
1248
  },
832
1249
  // `action.log` is the model's own text (LangChain's default reads
833
1250
  // "Invoking: `web_extract` with `{...}`", the raw tool input), so it
834
- // never reaches the progress bar.
1251
+ // never reaches the progress bar; nor does `action.toolInput`, since
1252
+ // tool args never reach onProgress (spec §4).
835
1253
  handleAgentAction: (action) => {
836
1254
  onProgress({
837
1255
  type: "agent_action",
838
1256
  message: toolProgressLabel(action.tool),
1257
+ ...toolProgressIcon(action.tool),
839
1258
  tool: action.tool,
840
- input: action.toolInput,
841
1259
  progress,
842
1260
  });
843
1261
  },
844
1262
  handleChainError: (err) => {
1263
+ // An interrupt is the graph stopping for an answer, not an error,
1264
+ // and its message is the interrupts' JSON: a tool call's args and
1265
+ // description, which never reach the progress bar.
1266
+ if ((0, langgraph_1.isGraphBubbleUp)(err))
1267
+ return;
845
1268
  onProgress({
846
1269
  type: "error",
847
1270
  message: `Error: ${err?.message || String(err)}`,
@@ -852,43 +1275,33 @@ const runAgent = async (agent, prompt, config, onProgress = null, usageTracker =
852
1275
  ]
853
1276
  : undefined;
854
1277
  const modelName = agent.options?.model?.modelName || agent.options?.model?.model || "";
855
- // Wait + retry on 429 around the full agent run. The agent loop may issue
856
- // many internal LLM calls, but a rate limit surfaces as a thrown error from
857
- // the wrapping invoke. On retry we restart the agent run from scratch — any
858
- // partial progress (tool calls, intermediate messages) is discarded, since
859
- // the agent state isn't externally checkpointed. Usage is only recorded on a
860
- // successful completion. Matches the behavior of the non-agentic paths.
861
- let response;
862
- let rateLimitAttempt = 0;
863
- while (true) {
864
- try {
865
- response = await agent.invoke({
866
- messages: [{ role: "user", content: prompt }],
867
- }, {
868
- recursionLimit: config.recursionLimit || 25,
869
- ...(callbacks ? { callbacks } : {}),
870
- });
871
- break;
872
- }
873
- catch (err) {
874
- if (isRateLimitError(err) && rateLimitAttempt < MAX_RATE_LIMIT_RETRIES) {
875
- rateLimitAttempt++;
876
- const { waitMs, source } = getRateLimitWaitMs(err);
877
- const waitSeconds = Math.round(waitMs / 1000);
878
- logger_js_1.default.log(null, logger_js_1.default.levels.warn, `Rate limited by "${modelName}" (agent), waiting ${waitSeconds}s before retry (${rateLimitAttempt}/${MAX_RATE_LIMIT_RETRIES}, source=${source}): ${err?.message ?? err}`);
879
- if (onProgress) {
880
- onProgress({
881
- type: "rate_limit",
882
- message: `AI service is busy. Retrying in ${waitSeconds}s...`,
883
- });
884
- }
885
- await sleep(waitMs);
886
- continue;
1278
+ // The request's signal stops the agent loop between and inside its steps,
1279
+ // as it stops a plain model call: an abandoned run stops paying.
1280
+ const abortSignal = (0, runtimeContext_js_1.getAbortSignal)();
1281
+ const options = {
1282
+ recursionLimit: config.recursionLimit || 25,
1283
+ ...(callbacks ? { callbacks } : {}),
1284
+ ...(abortSignal ? { signal: abortSignal } : {}),
1285
+ };
1286
+ const freshInput = () => ({ messages: [{ role: "user", content: prompt }] });
1287
+ // In a workflow.run turn the invocation is one journaled unit (`agent#n`):
1288
+ // a paused turn's resume gets its saved answer back without running it, and
1289
+ // an agent checkpointed by a SnapshotSaver can pause on an interrupt and go
1290
+ // on from it (durable/journal.ts). Outside a turn it runs as it always has.
1291
+ const response = await (0, journal_js_1.journaled)("agent", usageTracker, async (unit) => {
1292
+ // Inside the unit: a resumed turn's replay calls nothing, so asks nothing.
1293
+ await (0, modelRates_js_1.requirePricedModel)(modelName);
1294
+ if (agent?.options?.checkpointer instanceof snapshotSaver_js_1.SnapshotSaver) {
1295
+ // Its interrupts pause a turn: with no unit of one to pause (outside a
1296
+ // turn, or under another agent's tool) its answer would be returned as
1297
+ // if it were final.
1298
+ if (!unit) {
1299
+ throw errorHandling_js_1.default.create(const_js_1.default.HTTP_CODES.INTERNAL_SERVER_ERROR, "an agent checkpointed by a durable.SnapshotSaver runs only in a workflow.run turn, not outside one nor inside another agent's tool");
887
1300
  }
888
- throw err;
1301
+ return invokeDurably(agent, unit, freshInput(), options, config, onProgress, modelName, usageTracker);
889
1302
  }
890
- }
891
- updateUsageTracker(usageTracker, modelName, sumAgentResponseUsage(response), config);
1303
+ return invokeAndCount(agent, freshInput, options, config, onProgress, modelName, usageTracker);
1304
+ });
892
1305
  const endTime = Date.now();
893
1306
  const duration = endTime - startTime;
894
1307
  logger_js_1.default.log(null, logger_js_1.default.levels.info, `Agent "${agent.options?.name}" completed in ${Math.round(duration / 1000)} seconds.`);
@@ -1013,6 +1426,26 @@ const getRateLimitWaitMs = (err) => {
1013
1426
  Math.floor(Math.random() * (RATE_LIMIT_MAX_WAIT_MS - RATE_LIMIT_MIN_WAIT_MS + 1));
1014
1427
  return { waitMs, source: "random" };
1015
1428
  };
1429
+ /**
1430
+ * How long to wait before a model call the network dropped is made again, in
1431
+ * milliseconds; null when it is not made again. A call that got no answer, or
1432
+ * whose stream was cut mid-answer (`terminated`), is made again after each of
1433
+ * RETRY_WAITS: the provider's client retries a request that never connected,
1434
+ * never one whose answer had begun, so until 2026-11-15 a stream cut once
1435
+ * failed its call outright. A failure that carries a status was answered and
1436
+ * is not the network's.
1437
+ * @param err What the call failed with
1438
+ * @param made How many times this call has already been made again for the network
1439
+ */
1440
+ const droppedConnectionWait = (err, made) => made < retry_js_1.RETRY_WAITS.length && (0, retry_js_1.isNetworkFailure)(err) ? retry_js_1.RETRY_WAITS[made] : null;
1441
+ /**
1442
+ * Logs that a model call the network dropped is being made again.
1443
+ * @param modelName The model called
1444
+ * @param err What the call failed with
1445
+ * @param waitMs How long the retry waits first
1446
+ * @param attempt Which retry this is, from 1
1447
+ */
1448
+ const logDroppedConnection = (modelName, err, waitMs, attempt) => logger_js_1.default.log(null, logger_js_1.default.levels.warn, `Connection to "${modelName}" dropped (${(0, retry_js_1.messageOf)(err)}), trying again in ${waitMs} ms (${attempt}/${retry_js_1.RETRY_WAITS.length})`);
1016
1449
  /**
1017
1450
  * Detects rate-limit (HTTP 429) errors across LangChain and provider SDK shapes.
1018
1451
  * Different SDKs surface the status in different places (status, statusCode,
@@ -1040,6 +1473,107 @@ const isRateLimitError = (err) => {
1040
1473
  /rate.?limit/i.test(message) ||
1041
1474
  /too many requests/i.test(message));
1042
1475
  };
1476
+ exports.isRateLimitError = isRateLimitError;
1477
+ /** How much of an unparseable response the error quotes: its head and its tail. */
1478
+ const UNPARSEABLE_HEAD = 100;
1479
+ const UNPARSEABLE_TAIL = 200;
1480
+ /**
1481
+ * Describes a response that was expected to be JSON and could not be read: the
1482
+ * text (whole when short, else its first 100 and last 200 characters, so a cut
1483
+ * shows), its length, and the reason `JSON.parse` gave when it was tried. In
1484
+ * production the error quoted the first 100 characters of an output that began
1485
+ * as valid JSON and nothing else (2026-11-01), so whether it was cut short or
1486
+ * held a stray quote was unknowable from the log.
1487
+ *
1488
+ * When the answer is a JSON body escaped once too often that could not be read
1489
+ * once unescaped either, the direct reason is only the backslash at position 1:
1490
+ * the unescaped body's own failure follows it — its length, the parse reason,
1491
+ * the character at that position and the text around it — because the head and
1492
+ * tail quote hides the middle, where 20+ ownership answers failed unexplained
1493
+ * in production (2026-11-13).
1494
+ * @param rawContent - What the model answered
1495
+ * @param parseError - What `JSON.parse` threw on it, when it was tried
1496
+ */
1497
+ const describeUnparseableResponse = (rawContent, parseError) => {
1498
+ let text = "";
1499
+ if (typeof rawContent === "string") {
1500
+ text = rawContent;
1501
+ }
1502
+ else if (typeof rawContent === "object" && rawContent !== null) {
1503
+ text = JSON.stringify(rawContent);
1504
+ }
1505
+ else if (rawContent !== undefined && rawContent !== null) {
1506
+ text = String(rawContent);
1507
+ }
1508
+ if (text === "")
1509
+ return "[empty response]";
1510
+ // An output cut short begins as JSON and ends mid-value, so the direct parse
1511
+ // was never tried on it: try it here, for the reason.
1512
+ if (parseError === undefined && /^\s*[[{]/.test(text)) {
1513
+ try {
1514
+ JSON.parse(text);
1515
+ }
1516
+ catch (error) {
1517
+ parseError = error;
1518
+ }
1519
+ }
1520
+ const quoted = text.length <= UNPARSEABLE_HEAD + UNPARSEABLE_TAIL
1521
+ ? `"${text}"`
1522
+ : `"${text.slice(0, UNPARSEABLE_HEAD)}" … "${text.slice(-UNPARSEABLE_TAIL)}"`;
1523
+ const reason = parseError instanceof Error ? `; ${describeParseFailure(text, parseError)}` : "";
1524
+ return `${quoted} (${text.length} characters${reason}${describeUnescapedFailure(text)})`;
1525
+ };
1526
+ /** How much of an unescaped body the error quotes on each side of the failing position. */
1527
+ const UNESCAPED_EXCERPT = 60;
1528
+ /**
1529
+ * Why `JSON.parse` refused `text`: its message, then the character it stopped
1530
+ * at, by code point — an invisible one, or a backslash in a body escaped once
1531
+ * too often, says nothing in a quote.
1532
+ * @param text - The text that was parsed
1533
+ * @param parseError - What `JSON.parse` threw on it
1534
+ * @param excerpt - Whether to quote the text around the failing position too
1535
+ */
1536
+ const describeParseFailure = (text, parseError, excerpt = false) => {
1537
+ const position = /at position (\d+)/.exec(parseError.message);
1538
+ if (!position)
1539
+ return parseError.message;
1540
+ const at = Number(position[1]);
1541
+ const culprit = at < text.length
1542
+ ? `; character at position ${at}: U+${text.codePointAt(at).toString(16).toUpperCase().padStart(4, "0")} ${JSON.stringify(String.fromCodePoint(text.codePointAt(at)))}`
1543
+ : "";
1544
+ if (!excerpt)
1545
+ return `${parseError.message}${culprit}`;
1546
+ const from = Math.max(0, at - UNESCAPED_EXCERPT);
1547
+ const to = Math.min(text.length, at + UNESCAPED_EXCERPT + 1);
1548
+ const around = `${from > 0 ? "…" : ""}${text.slice(from, to)}${to < text.length ? "…" : ""}`;
1549
+ return `${parseError.message}${culprit}; around position ${at}: "${around}"`;
1550
+ };
1551
+ /**
1552
+ * Why an answer escaped once too often was not JSON once unescaped: the block
1553
+ * inside the unescaped text as the block strategies last tried it (the text
1554
+ * itself when it opens as JSON and holds no closed block, as an answer cut
1555
+ * short does), with its length, parse reason, failing character and the text
1556
+ * around it. Empty when the answer is not an escaped body, or stands for text
1557
+ * that holds no JSON to report on.
1558
+ * @param text - What the model answered
1559
+ */
1560
+ const describeUnescapedFailure = (text) => {
1561
+ const unescaped = unescapeJsonBody(withoutFences(text));
1562
+ if (unescaped === null)
1563
+ return "";
1564
+ let failed = parseJsonBlock(unescaped).failed;
1565
+ if (!failed && /^\s*[[{]/.test(unescaped)) {
1566
+ try {
1567
+ JSON.parse(unescaped);
1568
+ }
1569
+ catch (error) {
1570
+ failed = { text: unescaped, error };
1571
+ }
1572
+ }
1573
+ if (!failed)
1574
+ return "";
1575
+ return `; unescaped body (${failed.text.length} characters): ${describeParseFailure(failed.text, failed.error, true)}`;
1576
+ };
1043
1577
  /**
1044
1578
  * Parses raw LLM content as JSON and validates against an optional Zod schema,
1045
1579
  * returning the canonical JSON string. Tries a direct parse of the trimmed text
@@ -1048,6 +1582,7 @@ const isRateLimitError = (err) => {
1048
1582
  * `INTERNAL_SERVER_ERROR` when no JSON can be extracted from the response at all.
1049
1583
  */
1050
1584
  const parseAndValidateJSONResponse = (rawContent, schema) => {
1585
+ let directParseError;
1051
1586
  if (typeof rawContent === "string") {
1052
1587
  const trimmed = rawContent.trim();
1053
1588
  if ((trimmed.startsWith("{") && trimmed.endsWith("}")) ||
@@ -1064,6 +1599,7 @@ const parseAndValidateJSONResponse = (rawContent, schema) => {
1064
1599
  throw parseError;
1065
1600
  }
1066
1601
  // JSON.parse failed (not a validation error) — fall through to extraction.
1602
+ directParseError = parseError;
1067
1603
  }
1068
1604
  }
1069
1605
  const extracted = extractJSONFromResponse(rawContent);
@@ -1074,20 +1610,7 @@ const parseAndValidateJSONResponse = (rawContent, schema) => {
1074
1610
  return JSON.stringify(extracted);
1075
1611
  }
1076
1612
  }
1077
- let preview = "";
1078
- if (typeof rawContent === "string") {
1079
- preview = rawContent.substring(0, 100);
1080
- }
1081
- else if (typeof rawContent === "object" && rawContent !== null) {
1082
- preview = JSON.stringify(rawContent).substring(0, 100);
1083
- }
1084
- else if (rawContent !== undefined && rawContent !== null) {
1085
- preview = String(rawContent).substring(0, 100);
1086
- }
1087
- else {
1088
- preview = "[empty response]";
1089
- }
1090
- throw errorHandling_js_1.default.create(const_js_1.default.HTTP_CODES.INTERNAL_SERVER_ERROR, `LLM returned non-JSON response when JSON was expected: ${preview}...`);
1613
+ throw errorHandling_js_1.default.create(const_js_1.default.HTTP_CODES.INTERNAL_SERVER_ERROR, `LLM returned non-JSON response when JSON was expected: ${describeUnparseableResponse(rawContent, directParseError)}`);
1091
1614
  };
1092
1615
  /**
1093
1616
  * Appends the model's failed output as an assistant turn followed by a user turn
@@ -1178,6 +1701,7 @@ const buildValidationRetryMessages = (priorMessages, rawContent, validationError
1178
1701
  * @returns The JSON, re-serialised
1179
1702
  */
1180
1703
  const parseAgenticJsonResponse = (rawContent, schema) => {
1704
+ let directParseError;
1181
1705
  if (typeof rawContent === "string") {
1182
1706
  const trimmed = rawContent.trim();
1183
1707
  if ((trimmed.startsWith("{") && trimmed.endsWith("}")) ||
@@ -1193,6 +1717,7 @@ const parseAgenticJsonResponse = (rawContent, schema) => {
1193
1717
  if (parseError?.code === const_js_1.default.HTTP_CODES.UNPROCESSABLE_ENTITY) {
1194
1718
  throw parseError;
1195
1719
  }
1720
+ directParseError = parseError;
1196
1721
  }
1197
1722
  }
1198
1723
  // Try to extract JSON from markdown or other wrapping
@@ -1204,20 +1729,65 @@ const parseAgenticJsonResponse = (rawContent, schema) => {
1204
1729
  return JSON.stringify(extracted);
1205
1730
  }
1206
1731
  }
1207
- let preview = "";
1208
- if (typeof rawContent === "string") {
1209
- preview = rawContent.substring(0, 100);
1210
- }
1211
- else if (typeof rawContent === "object" && rawContent !== null) {
1212
- preview = JSON.stringify(rawContent).substring(0, 100);
1213
- }
1214
- else if (rawContent !== undefined && rawContent !== null) {
1215
- preview = String(rawContent).substring(0, 100);
1216
- }
1217
- else {
1218
- preview = "[empty response]";
1732
+ throw errorHandling_js_1.default.create(const_js_1.default.HTTP_CODES.INTERNAL_SERVER_ERROR, `Agent returned non-JSON response when JSON was expected: ${describeUnparseableResponse(rawContent, directParseError)}`);
1733
+ };
1734
+ /**
1735
+ * Refuses, before the model is called, an agentic call that would pause where
1736
+ * it cannot (outside a `workflow.run` turn) or with settings its wait would
1737
+ * be refused for. A 500: the agent's code is wrong, not its caller's input.
1738
+ * @param approvals - `config.approvals`, or null
1739
+ * @param clientTools - `config.clientTools`, or null
1740
+ * @param callsClient - Whether the call can pause for a client tool
1741
+ */
1742
+ const checkPauseSettings = (approvals, clientTools, callsClient) => {
1743
+ const refuse = (message) => {
1744
+ throw errorHandling_js_1.default.create(const_js_1.default.HTTP_CODES.INTERNAL_SERVER_ERROR, message);
1745
+ };
1746
+ const userIds = (ids) => ids === undefined ||
1747
+ (Array.isArray(ids) &&
1748
+ ids.length >= 1 &&
1749
+ ids.length <= limits_js_1.LIMITS.ADDRESSEES_MAX &&
1750
+ ids.every((id) => typeof id === "string" && id.length > 0));
1751
+ // Ruling 34, known at the turn's start: an event's run does not know the
1752
+ // workflow's creator, so its pause must name who answers. Refused here, not
1753
+ // after the turn's LLM calls, which a retried turn would run again.
1754
+ const eventTurn = (0, journal_js_1.activeTurn)()?.event === true;
1755
+ if (approvals) {
1756
+ if (!(0, journal_js_1.activeTurn)()) {
1757
+ refuse("config.approvals works only inside a workflow.run turn: a paused conversation needs a workflow to wait on");
1758
+ }
1759
+ const guarded = approvals.tools;
1760
+ if (!guarded || typeof guarded !== "object" || Array.isArray(guarded) || Object.keys(guarded).length === 0) {
1761
+ refuse("config.approvals.tools names the tools that need approval: { tools: { <tool>: true | { allowedDecisions, description? } } }");
1762
+ }
1763
+ if (!userIds(approvals.addressees))
1764
+ refuse(`config.approvals.addressees is a list of 1 to ${limits_js_1.LIMITS.ADDRESSEES_MAX} user ids`);
1765
+ if (eventTurn && !approvals.addressees) {
1766
+ refuse("an event's turn must name who answers: set config.approvals.addressees (an event's run does not know the workflow's creator)");
1767
+ }
1768
+ const deadline = approvals.deadline;
1769
+ const at = deadline instanceof Date ? deadline.getTime() : typeof deadline === "string" ? Date.parse(deadline) : NaN;
1770
+ if (deadline !== undefined && Number.isNaN(at))
1771
+ refuse("config.approvals.deadline is a time: an ISO string or a Date");
1772
+ }
1773
+ if (callsClient) {
1774
+ if (!(0, journal_js_1.activeTurn)()) {
1775
+ refuse("config.clientTools and durable.clientTool work only inside a workflow.run turn: the caller runs the tool while the turn waits");
1776
+ }
1777
+ if (clientTools !== null) {
1778
+ if (typeof clientTools !== "object" || Array.isArray(clientTools))
1779
+ refuse("config.clientTools is { deadline?, addressees? }");
1780
+ const seconds = clientTools.deadline;
1781
+ if (seconds !== undefined && !(typeof seconds === "number" && Number.isFinite(seconds) && seconds >= limits_js_1.LIMITS.MIN_TIMER_SECONDS)) {
1782
+ refuse(`config.clientTools.deadline is seconds, at least ${limits_js_1.LIMITS.MIN_TIMER_SECONDS}`);
1783
+ }
1784
+ if (!userIds(clientTools.addressees))
1785
+ refuse(`config.clientTools.addressees is a list of 1 to ${limits_js_1.LIMITS.ADDRESSEES_MAX} user ids`);
1786
+ }
1787
+ if (eventTurn && !clientTools?.addressees) {
1788
+ refuse("an event's turn must name who answers: set config.clientTools.addressees (an event's run does not know the workflow's creator)");
1789
+ }
1219
1790
  }
1220
- throw errorHandling_js_1.default.create(const_js_1.default.HTTP_CODES.INTERNAL_SERVER_ERROR, `Agent returned non-JSON response when JSON was expected: ${preview}...`);
1221
1791
  };
1222
1792
  /**
1223
1793
  * Sends a prompt to an LLM and returns the response, with support for streaming,
@@ -1244,7 +1814,7 @@ const parseAgenticJsonResponse = (rawContent, schema) => {
1244
1814
  * `web_extract` to those URLs.
1245
1815
  * @param modelName - The model identifier, e.g. `"gpt-4o"`, `"claude-3-5-sonnet"`,
1246
1816
  * `"gemini-1.5-pro"`
1247
- * @param config - Configuration object with API keys, `temperature`, optional `agentic`
1817
+ * @param config - Configuration object with API keys, `temperature`, `reasoningEffort`, optional `agentic`
1248
1818
  * flag, optional `recursionLimit`, and optional `tavily` (`true` or a
1249
1819
  * `TavilyConfig`)
1250
1820
  * @param prompt - The prompt to send; either a plain string (user message only) or an
@@ -1270,6 +1840,15 @@ const parseAgenticJsonResponse = (rawContent, schema) => {
1270
1840
  const runPromptWithModel = async (modelName, config, prompt, onProgressReport, minPercent = 0, maxPercent = 100, expectsJsonResponse = true, schema = null, agentName = "StackFactor", tools = [], usageTracker = null) => {
1271
1841
  // Agentic mode: use an agent with tools instead of simple LLM invocation
1272
1842
  if (config.agentic === true) {
1843
+ // Approval inside the tool loop (design #964 §10.2) and client tools
1844
+ // (interactive tool calls §2): the turn pauses on the tool call and goes
1845
+ // on with the person's decision or the caller's result, so each needs a
1846
+ // workflow.run turn to pause, checked before anything else runs.
1847
+ const approvals = config.approvals ?? null;
1848
+ const clientTools = config.clientTools ?? null;
1849
+ const callsClient = clientTools !== null || tools.some(clientTool_js_1.isClientTool);
1850
+ if (approvals || callsClient)
1851
+ checkPauseSettings(approvals, clientTools, callsClient);
1273
1852
  // Extract system prompt and user prompt from the prompt parameter
1274
1853
  let systemPrompt = "";
1275
1854
  let userPrompt = "";
@@ -1300,8 +1879,20 @@ const runPromptWithModel = async (modelName, config, prompt, onProgressReport, m
1300
1879
  // Create the agent with tools. The tracker is handed over at construction
1301
1880
  // because the Tavily tools bill their own credits as they run, rather than
1302
1881
  // being reconciled from the response afterwards.
1882
+ // With approvals, humanInTheLoopMiddleware interrupts on the guarded
1883
+ // tools' calls (config.approvals.tools as it is: a tool named
1884
+ // `addressees` or `deadline` is never confused with the wait's options);
1885
+ // a client tool interrupts in its own body. A SnapshotSaver keeps the
1886
+ // thread the pause exports.
1303
1887
  const agent = createAgent(agentName, modelName, systemPrompt, [...tools], null, // responseFormat
1304
- config, usageTracker);
1888
+ config, usageTracker, ...(approvals || callsClient
1889
+ ? [
1890
+ {
1891
+ middleware: approvals ? [(0, langchain_1.humanInTheLoopMiddleware)({ interruptOn: approvals.tools })] : [],
1892
+ checkpointer: new snapshotSaver_js_1.SnapshotSaver(),
1893
+ },
1894
+ ]
1895
+ : []));
1305
1896
  // The JSON stage is retried like the non-agentic paths (canRetryValidation):
1306
1897
  // the agent is run again with its rejected output and the errors appended
1307
1898
  // to the user prompt, up to MAX_VALIDATION_RETRIES. Until now this path
@@ -1340,6 +1931,20 @@ const runPromptWithModel = async (modelName, config, prompt, onProgressReport, m
1340
1931
  }
1341
1932
  }
1342
1933
  }
1934
+ // A non-agentic call is one journaled unit of a workflow.run turn
1935
+ // (`llm#n`): a paused turn's resume gets its saved answer back without
1936
+ // calling the model again. Outside a turn it runs as it always has.
1937
+ return (0, journal_js_1.journaled)("llm", usageTracker, () => runPromptWithModelOnce(modelName, config, prompt, onProgressReport, minPercent, maxPercent, expectsJsonResponse, schema, agentName, usageTracker));
1938
+ };
1939
+ /**
1940
+ * One non-agentic call of {@link runPromptWithModel}: streamed with progress
1941
+ * when `onProgressReport` is given, else invoked, JSON validated and retried
1942
+ * as that function describes.
1943
+ */
1944
+ const runPromptWithModelOnce = async (modelName, config, prompt, onProgressReport, minPercent, maxPercent, expectsJsonResponse, schema, agentName, usageTracker) => {
1945
+ // Here rather than in runPromptWithModel: a resumed turn's replay returns
1946
+ // the saved answer without calling the model, so it asks nothing.
1947
+ await (0, modelRates_js_1.requirePricedModel)(modelName);
1343
1948
  let messages;
1344
1949
  if (typeof prompt === "string") {
1345
1950
  messages = [{ role: "user", content: prompt }];
@@ -1417,7 +2022,10 @@ const runPromptWithModel = async (modelName, config, prompt, onProgressReport, m
1417
2022
  // error out with a rate limit are not counted. A 429 fired mid-stream
1418
2023
  // simply discards the partial output and restarts cleanly.
1419
2024
  let rateLimitAttempt = 0;
2025
+ let droppedAttempt = 0;
1420
2026
  while (true) {
2027
+ // A cancelled request starts no model call.
2028
+ (0, cancellation_js_1.throwIfRequestCancelled)();
1421
2029
  rawContent = "";
1422
2030
  chunkCount = 0;
1423
2031
  streamUsage = { input_tokens: 0, output_tokens: 0, total_tokens: 0 };
@@ -1430,9 +2038,8 @@ const runPromptWithModel = async (modelName, config, prompt, onProgressReport, m
1430
2038
  runName: agentName,
1431
2039
  });
1432
2040
  for await (const chunk of stream) {
1433
- if (abortSignal?.aborted) {
1434
- throw errorHandling_js_1.default.create(const_js_1.default.HTTP_CODES.BAD_REQUEST, "Request cancelled by caller");
1435
- }
2041
+ if (abortSignal?.aborted)
2042
+ throw (0, cancellation_js_1.requestCancelledError)();
1436
2043
  accumulateChunkUsage(streamUsage, chunk);
1437
2044
  // Counting every chunk (not just the ones carrying text) keeps
1438
2045
  // progress ticking through pauses in the stream.
@@ -1448,7 +2055,10 @@ const runPromptWithModel = async (modelName, config, prompt, onProgressReport, m
1448
2055
  break; // stream completed without 429
1449
2056
  }
1450
2057
  catch (err) {
1451
- if (isRateLimitError(err) &&
2058
+ // The request's own signal ended the stream: the caller is gone.
2059
+ if ((0, cancellation_js_1.isRequestCancelled)())
2060
+ throw (0, cancellation_js_1.requestCancelledError)();
2061
+ if ((0, exports.isRateLimitError)(err) &&
1452
2062
  rateLimitAttempt < MAX_RATE_LIMIT_RETRIES) {
1453
2063
  rateLimitAttempt++;
1454
2064
  const { waitMs, source } = getRateLimitWaitMs(err);
@@ -1456,11 +2066,21 @@ const runPromptWithModel = async (modelName, config, prompt, onProgressReport, m
1456
2066
  logger_js_1.default.log(null, logger_js_1.default.levels.warn, `Rate limited by "${modelName}", waiting ${waitSeconds}s before retry (${rateLimitAttempt}/${MAX_RATE_LIMIT_RETRIES}, source=${source}): ${err?.message ?? err}`);
1457
2067
  await onProgressReport({
1458
2068
  message: `AI service is busy. Retrying in ${waitSeconds}s...`,
2069
+ icon: "hourglass",
1459
2070
  progress: Math.min(calcCurrentProgress(), maxPercent - 5),
1460
2071
  });
1461
2072
  await sleep(waitMs);
1462
2073
  continue;
1463
2074
  }
2075
+ // A stream the network cut is discarded like one a 429 cut, and
2076
+ // the call made again.
2077
+ const droppedWait = droppedConnectionWait(err, droppedAttempt);
2078
+ if (droppedWait !== null) {
2079
+ droppedAttempt++;
2080
+ logDroppedConnection(modelName, err, droppedWait, droppedAttempt);
2081
+ await sleep(droppedWait);
2082
+ continue;
2083
+ }
1464
2084
  throw err;
1465
2085
  }
1466
2086
  }
@@ -1551,13 +2171,22 @@ const runPromptWithModel = async (modelName, config, prompt, onProgressReport, m
1551
2171
  // the wait is silent to the caller — only the warn log is emitted.
1552
2172
  let response;
1553
2173
  let rateLimitAttempt = 0;
2174
+ let droppedAttempt = 0;
1554
2175
  while (true) {
2176
+ // A cancelled request starts no model call, and one cancelled
2177
+ // mid-call says so.
2178
+ (0, cancellation_js_1.throwIfRequestCancelled)();
1555
2179
  try {
1556
- response = await llm.invoke(activeMessages, { runName: agentName });
2180
+ response = await llm.invoke(activeMessages, {
2181
+ runName: agentName,
2182
+ signal: (0, runtimeContext_js_1.getAbortSignal)() ?? undefined,
2183
+ });
1557
2184
  break;
1558
2185
  }
1559
2186
  catch (err) {
1560
- if (isRateLimitError(err) &&
2187
+ if ((0, cancellation_js_1.isRequestCancelled)())
2188
+ throw (0, cancellation_js_1.requestCancelledError)();
2189
+ if ((0, exports.isRateLimitError)(err) &&
1561
2190
  rateLimitAttempt < MAX_RATE_LIMIT_RETRIES) {
1562
2191
  rateLimitAttempt++;
1563
2192
  const { waitMs, source } = getRateLimitWaitMs(err);
@@ -1565,6 +2194,13 @@ const runPromptWithModel = async (modelName, config, prompt, onProgressReport, m
1565
2194
  await sleep(waitMs);
1566
2195
  continue;
1567
2196
  }
2197
+ const droppedWait = droppedConnectionWait(err, droppedAttempt);
2198
+ if (droppedWait !== null) {
2199
+ droppedAttempt++;
2200
+ logDroppedConnection(modelName, err, droppedWait, droppedAttempt);
2201
+ await sleep(droppedWait);
2202
+ continue;
2203
+ }
1568
2204
  throw err;
1569
2205
  }
1570
2206
  }
@@ -1630,6 +2266,7 @@ const getImageModelProvider = (modelName) => {
1630
2266
  * or `{ images: [...] }` for multiple images
1631
2267
  */
1632
2268
  const generateImageWithOpenAI = async (modelName, config, prompt, options, usageTracker = null) => {
2269
+ await (0, modelRates_js_1.requirePricedModel)(modelName);
1633
2270
  const { size = "1024x1024", style = "vivid", responseFormat = "url", n = 1, } = options;
1634
2271
  if (!config.openAIAPIKey) {
1635
2272
  throw errorHandling_js_1.default.create(const_js_1.default.HTTP_CODES.BAD_REQUEST, "OpenAI API key is required for OpenAI image generation");
@@ -1717,6 +2354,7 @@ const generateImageWithOpenAI = async (modelName, config, prompt, options, usage
1717
2354
  * requested, or `{ images: [...] }` for multiple images
1718
2355
  */
1719
2356
  const generateImageWithGoogle = async (modelName, config, prompt, options, usageTracker = null) => {
2357
+ await (0, modelRates_js_1.requirePricedModel)(modelName);
1720
2358
  const { aspectRatio = "1:1", imageSize, numberOfImages = 1, negativePrompt = "", } = options;
1721
2359
  if (!config.googleAPIKey) {
1722
2360
  throw errorHandling_js_1.default.create(const_js_1.default.HTTP_CODES.BAD_REQUEST, "Google API key is required for Google image generation");
@@ -1830,6 +2468,7 @@ const generateImageWithGoogle = async (modelName, config, prompt, options, usage
1830
2468
  * @returns The generated image data object returned by the provider-specific function
1831
2469
  */
1832
2470
  const runPromptWithModelForImageGeneration = async (modelName, config, prompt, options = {}, usageTracker = null) => {
2471
+ await (0, modelRates_js_1.requirePricedModel)(modelName);
1833
2472
  const provider = getImageModelProvider(modelName);
1834
2473
  if (!provider) {
1835
2474
  throw errorHandling_js_1.default.create(const_js_1.default.HTTP_CODES.BAD_REQUEST, `Unable to determine provider for model: ${modelName}. Model name should start with 'gpt-image-', 'gemini-', or 'imagen-'.`);
@@ -1864,14 +2503,22 @@ const runPromptWithModelForImageGeneration = async (modelName, config, prompt, o
1864
2503
  };
1865
2504
  /**
1866
2505
  * Determines the video generation provider for a model name from its prefix.
1867
- * `veo-` maps to `"google"`, `sora-` to `"openai"`. Returns `null` for anything
1868
- * else so the caller can reject an unrecognised id rather than guess at it.
2506
+ * `gemini-omni-` maps to `"google-omni"`, `veo-` to `"google"`, `sora-` to
2507
+ * `"openai"`. Returns `null` for anything else so the caller can reject an
2508
+ * unrecognised id rather than guess at it.
2509
+ *
2510
+ * Omni and Veo are both Google, but they are different APIs: Veo is a
2511
+ * `predictLongRunning` operation, Omni an Interactions API call. Google shut
2512
+ * the Veo 3.1 previews down on the Gemini API on 2026-10-22 and named
2513
+ * `gemini-omni-1.2-flash` as their replacement.
1869
2514
  * @param modelName - The video model identifier to inspect
1870
- * @returns `"openai"`, `"google"`, or `null`
2515
+ * @returns `"openai"`, `"google"`, `"google-omni"`, or `null`
1871
2516
  */
1872
2517
  const getVideoModelProvider = (modelName) => {
1873
2518
  if (modelName.startsWith("sora-"))
1874
2519
  return "openai";
2520
+ if (modelName.startsWith("gemini-omni-"))
2521
+ return "google-omni";
1875
2522
  if (modelName.startsWith("veo-"))
1876
2523
  return "google";
1877
2524
  return null;
@@ -1907,6 +2554,7 @@ const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
1907
2554
  * @returns `{ b64_json, mimeType, seconds, model }`
1908
2555
  */
1909
2556
  const generateVideoWithGoogle = async (modelName, config, prompt, options = {}, usageTracker = null) => {
2557
+ await (0, modelRates_js_1.requirePricedModel)(modelName);
1910
2558
  const { aspectRatio = "16:9", resolution = "720p", durationSeconds = 8, negativePrompt, personGeneration, pollTimeoutMs = VIDEO_POLL_TIMEOUT_MS, } = options;
1911
2559
  const ai = new genai_1.GoogleGenAI({ apiKey: config.googleAPIKey });
1912
2560
  let operation = await ai.models.generateVideos({
@@ -1975,6 +2623,7 @@ const generateVideoWithGoogle = async (modelName, config, prompt, options = {},
1975
2623
  * @returns `{ b64_json, mimeType, seconds, model }`
1976
2624
  */
1977
2625
  const generateVideoWithOpenAI = async (modelName, config, prompt, options = {}, usageTracker = null) => {
2626
+ await (0, modelRates_js_1.requirePricedModel)(modelName);
1978
2627
  const { size = "1280x720", durationSeconds = 8, pollTimeoutMs = VIDEO_POLL_TIMEOUT_MS, } = options;
1979
2628
  const openai = new openai_2.OpenAI({ apiKey: config.openAIAPIKey });
1980
2629
  // Sora takes the duration as one of a fixed set of STRINGS ("4", "8", "12").
@@ -2010,16 +2659,169 @@ const generateVideoWithOpenAI = async (modelName, config, prompt, options = {},
2010
2659
  model: modelName,
2011
2660
  };
2012
2661
  };
2662
+ /** The Gemini API base every Omni call goes to. */
2663
+ const GEMINI_API_BASE = "https://generativelanguage.googleapis.com/v1beta";
2664
+ /**
2665
+ * Reads a failed Gemini API response as an error that keeps the HTTP status
2666
+ * and Google's own message, falling back to the status line when the body is
2667
+ * not Google's JSON (a proxy's HTML page, say).
2668
+ */
2669
+ const omniHttpError = async (modelName, response) => {
2670
+ let reason = `${response.status} ${response.statusText}`.trim();
2671
+ try {
2672
+ const body = (await response.json());
2673
+ if (body?.error?.message)
2674
+ reason = body.error.message;
2675
+ }
2676
+ catch {
2677
+ // Not JSON: the status line is all there is.
2678
+ }
2679
+ return errorHandling_js_1.default.create(response.status, `Video generation with "${modelName}" failed: ${reason}`);
2680
+ };
2681
+ /**
2682
+ * Generates a video with Google Gemini Omni (`gemini-omni-*`).
2683
+ *
2684
+ * Omni is the Gemini API's video model since the Veo 3.1 previews were shut
2685
+ * down there (2026-10-22). It is not `predictLongRunning`: a clip is one POST
2686
+ * to the Interactions API, which answers when the clip is done. That call is
2687
+ * made over REST because the pinned @google/genai predates Omni's video
2688
+ * response format.
2689
+ *
2690
+ * The clip is asked for with `delivery: "uri"`: Google returns inline base64
2691
+ * only up to 4 MB, and an 8-second 720p clip can be larger. A uri is a file on
2692
+ * Google's file service that has to reach ACTIVE before it can be downloaded,
2693
+ * and it needs the API key, so this waits for it and downloads the bytes here.
2694
+ * Google may still answer with inline `data`, which is used as it is.
2695
+ *
2696
+ * The key always travels in the `x-goog-api-key` header, never in a URL.
2697
+ *
2698
+ * Omni has no negative prompt or person-generation setting; those options are
2699
+ * not sent.
2700
+ *
2701
+ * @param modelName - An Omni model id, e.g. `"gemini-omni-1.2-flash"`
2702
+ * @param config - Configuration object; must include `googleAPIKey`
2703
+ * @param prompt - The text prompt describing the video
2704
+ * @param options - `aspectRatio` ("16:9" default, or "9:16"), `resolution`
2705
+ * ("720p" default), `durationSeconds` (whole seconds, 3 to 15, default 8),
2706
+ * `pollTimeoutMs` (the deadline for the whole generation)
2707
+ * @param usageTracker - Accumulator billed per second of generated video
2708
+ * @returns `{ b64_json, mimeType, seconds, model }`
2709
+ */
2710
+ const generateVideoWithOmni = async (modelName, config, prompt, options = {}, usageTracker = null) => {
2711
+ await (0, modelRates_js_1.requirePricedModel)(modelName);
2712
+ const { aspectRatio = "16:9", resolution = "720p", durationSeconds = 8, pollTimeoutMs = VIDEO_POLL_TIMEOUT_MS, } = options;
2713
+ const seconds = Number(durationSeconds);
2714
+ if (!Number.isInteger(seconds) || seconds < 3 || seconds > 15) {
2715
+ throw errorHandling_js_1.default.create(const_js_1.default.HTTP_CODES.BAD_REQUEST, `Invalid durationSeconds "${durationSeconds}" for ${modelName}. Omni takes a whole number of seconds from 3 to 15.`);
2716
+ }
2717
+ const headers = { "x-goog-api-key": config.googleAPIKey ?? "" };
2718
+ const deadline = Date.now() + pollTimeoutMs;
2719
+ const timedOut = () => errorHandling_js_1.default.create(const_js_1.default.HTTP_CODES.INTERNAL_SERVER_ERROR, `Video generation with "${modelName}" did not finish within ${Math.round(pollTimeoutMs / 1000)} seconds.`);
2720
+ let response;
2721
+ try {
2722
+ response = await fetch(`${GEMINI_API_BASE}/interactions`, {
2723
+ method: "POST",
2724
+ headers: { "Content-Type": "application/json", ...headers },
2725
+ body: JSON.stringify({
2726
+ model: modelName,
2727
+ input: prompt,
2728
+ response_format: {
2729
+ type: "video",
2730
+ aspect_ratio: aspectRatio,
2731
+ resolution,
2732
+ duration: `${seconds}s`,
2733
+ delivery: "uri",
2734
+ },
2735
+ }),
2736
+ signal: AbortSignal.timeout(Math.max(0, pollTimeoutMs)),
2737
+ });
2738
+ }
2739
+ catch (error) {
2740
+ if (error instanceof Error && error.name === "TimeoutError")
2741
+ throw timedOut();
2742
+ throw error;
2743
+ }
2744
+ if (!response.ok)
2745
+ throw await omniHttpError(modelName, response);
2746
+ let interaction = (await response.json());
2747
+ // The POST answers when the clip is done, but an interaction still in
2748
+ // progress is polled rather than failed.
2749
+ while (interaction.status === "in_progress" && interaction.id) {
2750
+ if (Date.now() > deadline)
2751
+ throw timedOut();
2752
+ await delay(VIDEO_POLL_INTERVAL_MS);
2753
+ const poll = await fetch(`${GEMINI_API_BASE}/interactions/${encodeURIComponent(interaction.id)}`, { headers });
2754
+ if (!poll.ok)
2755
+ throw await omniHttpError(modelName, poll);
2756
+ interaction = (await poll.json());
2757
+ }
2758
+ if (interaction.status && interaction.status !== "completed") {
2759
+ const reasons = (interaction.errors ?? [])
2760
+ .map((e) => e?.message)
2761
+ .filter((m) => Boolean(m));
2762
+ throw errorHandling_js_1.default.create(const_js_1.default.HTTP_CODES.INTERNAL_SERVER_ERROR, `Video generation with "${modelName}" ${interaction.status}: ${reasons.join("; ") || "no reason given"}`);
2763
+ }
2764
+ const outputs = (interaction.steps ?? [])
2765
+ .filter((step) => step?.type === "model_output")
2766
+ .flatMap((step) => step.content ?? []);
2767
+ const video = outputs.find((item) => item?.type === "video");
2768
+ if (!video) {
2769
+ // A refused prompt can come back as text instead of a clip: say what it said.
2770
+ const said = outputs
2771
+ .filter((item) => item?.type === "text" && item.text)
2772
+ .map((item) => item.text)
2773
+ .join(" ");
2774
+ throw errorHandling_js_1.default.create(const_js_1.default.HTTP_CODES.INTERNAL_SERVER_ERROR, `No video was generated by ${modelName}${said ? `: ${said}` : ""}`);
2775
+ }
2776
+ let b64 = video.data;
2777
+ if (!b64) {
2778
+ if (!video.uri) {
2779
+ throw errorHandling_js_1.default.create(const_js_1.default.HTTP_CODES.INTERNAL_SERVER_ERROR, `${modelName} returned a video with neither inline bytes nor a uri`);
2780
+ }
2781
+ // The uri is .../files/<id>:download?alt=media; the file's state is at .../files/<id>.
2782
+ const fileId = /\/files\/([^/:?]+)/.exec(video.uri)?.[1];
2783
+ if (fileId) {
2784
+ for (;;) {
2785
+ const check = await fetch(`${GEMINI_API_BASE}/files/${encodeURIComponent(fileId)}`, { headers });
2786
+ if (!check.ok)
2787
+ throw await omniHttpError(modelName, check);
2788
+ const { state } = (await check.json());
2789
+ if (state === "ACTIVE")
2790
+ break;
2791
+ if (state === "FAILED") {
2792
+ throw errorHandling_js_1.default.create(const_js_1.default.HTTP_CODES.INTERNAL_SERVER_ERROR, `The video ${modelName} generated could not be prepared for download (file state FAILED)`);
2793
+ }
2794
+ if (Date.now() > deadline)
2795
+ throw timedOut();
2796
+ await delay(VIDEO_POLL_INTERVAL_MS);
2797
+ }
2798
+ }
2799
+ const download = await fetch(video.uri, { headers });
2800
+ if (!download.ok) {
2801
+ throw errorHandling_js_1.default.create(const_js_1.default.HTTP_CODES.INTERNAL_SERVER_ERROR, `Downloading the generated video failed with ${download.status} ${download.statusText}`);
2802
+ }
2803
+ b64 = Buffer.from(await download.arrayBuffer()).toString("base64");
2804
+ }
2805
+ // Billed on the duration ASKED FOR, as Veo is: Omni bills the clip it rendered.
2806
+ updateVideoUsageTracker(usageTracker, modelName, seconds, config);
2807
+ return {
2808
+ b64_json: b64,
2809
+ mimeType: video.mime_type || "video/mp4",
2810
+ seconds,
2811
+ model: modelName,
2812
+ };
2813
+ };
2013
2814
  /**
2014
2815
  * Top-level entry point for AI video generation, mirroring
2015
- * `runPromptWithModelForImageGeneration`. Routes to Veo or Sora on the model
2016
- * name prefix and logs the total generation time on success.
2816
+ * `runPromptWithModelForImageGeneration`. Routes to Omni, Veo or Sora on the
2817
+ * model name prefix and logs the total generation time on success.
2017
2818
  *
2018
- * Unlike image generation this always returns bytes — never a url. Both
2019
- * providers hand back a link that requires their API key, so a url would be
2819
+ * Unlike image generation this always returns bytes — never a url. Every
2820
+ * provider hands back a link that requires its API key, so a url would be
2020
2821
  * useless to any caller that is not this process.
2021
2822
  *
2022
- * @param modelName - The video model identifier; must start with `veo-` or `sora-`
2823
+ * @param modelName - The video model identifier; must start with
2824
+ * `gemini-omni-`, `veo-` or `sora-`
2023
2825
  * @param config - Configuration object with `googleAPIKey` or `openAIAPIKey`
2024
2826
  * @param prompt - The text prompt describing the video to generate
2025
2827
  * @param options - Provider-specific generation options
@@ -2027,15 +2829,18 @@ const generateVideoWithOpenAI = async (modelName, config, prompt, options = {},
2027
2829
  * @returns `{ b64_json, mimeType, seconds, model }`
2028
2830
  */
2029
2831
  const runPromptWithModelForVideoGeneration = async (modelName, config, prompt, options = {}, usageTracker = null) => {
2832
+ await (0, modelRates_js_1.requirePricedModel)(modelName);
2030
2833
  const provider = getVideoModelProvider(modelName);
2031
2834
  if (!provider) {
2032
- throw errorHandling_js_1.default.create(const_js_1.default.HTTP_CODES.BAD_REQUEST, `Unable to determine provider for model: ${modelName}. Model name should start with 'veo-' or 'sora-'.`);
2835
+ throw errorHandling_js_1.default.create(const_js_1.default.HTTP_CODES.BAD_REQUEST, `Unable to determine provider for model: ${modelName}. Model name should start with 'gemini-omni-', 'veo-' or 'sora-'.`);
2033
2836
  }
2034
2837
  const startTime = Date.now();
2035
2838
  try {
2036
2839
  const result = provider === "openai"
2037
2840
  ? await generateVideoWithOpenAI(modelName, config, prompt, options, usageTracker)
2038
- : await generateVideoWithGoogle(modelName, config, prompt, options, usageTracker);
2841
+ : provider === "google-omni"
2842
+ ? await generateVideoWithOmni(modelName, config, prompt, options, usageTracker)
2843
+ : await generateVideoWithGoogle(modelName, config, prompt, options, usageTracker);
2039
2844
  const duration = Date.now() - startTime;
2040
2845
  logger_js_1.default.log(null, logger_js_1.default.levels.info, `Video generation with "${modelName}" completed in ${Math.round(duration / 1000)} seconds.`);
2041
2846
  return result;
@@ -2056,6 +2861,7 @@ exports.default = {
2056
2861
  isRetryableJsonFailure,
2057
2862
  buildAgenticRetryPrompt,
2058
2863
  parseAgenticJsonResponse,
2864
+ parseAndValidateJSONResponse,
2059
2865
  supportsNativeSchema,
2060
2866
  checkIfAIProviderConfigured,
2061
2867
  createAgent,