@stackfactor/agent-utils 1.13.4 → 1.33.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 +688 -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 +117 -0
  63. package/dist/cjs/learningContentPlan.d.ts.map +1 -0
  64. package/dist/cjs/learningContentPlan.js +327 -0
  65. package/dist/cjs/learningContentThread.d.ts +213 -0
  66. package/dist/cjs/learningContentThread.d.ts.map +1 -0
  67. package/dist/cjs/learningContentThread.js +448 -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 +117 -0
  188. package/dist/esm/learningContentPlan.d.ts.map +1 -0
  189. package/dist/esm/learningContentPlan.js +320 -0
  190. package/dist/esm/learningContentThread.d.ts +213 -0
  191. package/dist/esm/learningContentThread.d.ts.map +1 -0
  192. package/dist/esm/learningContentThread.js +403 -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
@@ -4,13 +4,21 @@ import { ChatGoogleGenerativeAI } from "@langchain/google-genai";
4
4
  import { OpenAI } from "openai";
5
5
  import { GoogleGenAI } from "@google/genai";
6
6
  import constants from "./const.js";
7
- import { createAgent as createLangChainAgent } from "langchain";
7
+ import { createAgent as createLangChainAgent, humanInTheLoopMiddleware } from "langchain";
8
+ import { Command, isGraphBubbleUp, isInterrupted } from "@langchain/langgraph";
8
9
  import errorHandlingHelper from "./errorHandling.js";
9
10
  import logger from "./logger.js";
11
+ import { RETRY_WAITS, isNetworkFailure, messageOf } from "./retry.js";
10
12
  import { z } from "zod";
11
13
  import { transformJSONSchema } from "@anthropic-ai/sdk/lib/transform-json-schema";
12
14
  import { getAbortSignal } from "./runtimeContext.js";
15
+ import { isRequestCancelled, requestCancelledError, throwIfRequestCancelled } from "./cancellation.js";
13
16
  import { recordUsage } from "./usage.js";
17
+ import { requirePricedModel } from "./modelRates.js";
18
+ import { activeTurn, journaled, noteUsage } from "./durable/journal.js";
19
+ import { SnapshotSaver } from "./durable/snapshotSaver.js";
20
+ import { isClientTool } from "./durable/clientTool.js";
21
+ import { LIMITS } from "./workflow/limits.js";
14
22
  import { assertTavilyUsable, buildTavilyTools, getTavilyOptions, } from "./tavily.js";
15
23
  const JSON_ESCAPE_INSTRUCTION = `
16
24
  CRITICAL - Your response must be valid JSON. Escape ALL special characters in string values:
@@ -23,7 +31,7 @@ Do NOT include raw newlines, tabs, or unescaped quotes inside JSON string values
23
31
  `.trim();
24
32
  /**
25
33
  * Providers for which `getLLMModel` configures native, schema-constrained JSON
26
- * output (OpenAI `response_format`, Anthropic `output_config.format`, Gemini
34
+ * output (OpenAI `text.format`, Anthropic `output_config.format`, Gemini
27
35
  * `responseSchema` + JSON mode). For these the model emits JSON directly, so the
28
36
  * prompt-injected schema and the schema-validation retry are skipped. Every
29
37
  * supported provider is listed here; the check remains so that adding one
@@ -107,9 +115,12 @@ const countUsage = (tracker, modelName, unit, amount) => {
107
115
  if (!Number.isFinite(amount) || amount <= 0)
108
116
  return;
109
117
  recordUsage(modelName, unit, amount);
118
+ const key = `${modelName}_${unit}`;
119
+ // A journaled unit keeps what it used, so a replay gives it back to the
120
+ // caller's tracker without reporting it again (durable/journal.ts).
121
+ noteUsage(key, amount);
110
122
  if (!tracker)
111
123
  return;
112
- const key = `${modelName}_${unit}`;
113
124
  tracker.tokens[key] = (tracker.tokens[key] || 0) + amount;
114
125
  };
115
126
  /** Makes `{}` a tracker. `cost` stays 0: the platform prices what was used. */
@@ -289,9 +300,11 @@ const accumulateChunkUsage = (acc, chunk) => {
289
300
  /**
290
301
  * Sums token usage across every message in an agent invocation response. Each
291
302
  * AIMessage in `response.messages` may carry its own `usage_metadata` (one per
292
- * LLM round-trip the agent made).
303
+ * LLM round-trip the agent made). `counted` leaves out the messages whose
304
+ * usage was counted already: a resumed agent's answer carries the
305
+ * conversation it paused in, which the run that paused it counted.
293
306
  */
294
- const sumAgentResponseUsage = (response) => {
307
+ const sumAgentResponseUsage = (response, counted = null) => {
295
308
  const messages = response?.messages;
296
309
  if (!Array.isArray(messages) || messages.length === 0)
297
310
  return null;
@@ -302,6 +315,8 @@ const sumAgentResponseUsage = (response) => {
302
315
  };
303
316
  let found = false;
304
317
  for (const msg of messages) {
318
+ if (counted && counted.has(msg?.id))
319
+ continue;
305
320
  const um = msg?.usage_metadata;
306
321
  if (um) {
307
322
  total.input_tokens += um.input_tokens || 0;
@@ -409,10 +424,13 @@ const isHTMLResponse = (text) => {
409
424
  * include markdown code fences, invalid escape sequences, control characters, or other
410
425
  * extraneous formatting. Falls back through multiple strategies in order:
411
426
  * 1. Direct parse after stripping fences and fixing `\'` escapes
412
- * 2. Extract and parse the first `{...}` object block
413
- * 3. Same as above after sanitising control characters and normalising line endings
414
- * 4. Extract and parse the first `[...]` array block (with the same sanitisation)
415
- * 5. Strip all non-printable characters and retry both object and array extraction
427
+ * 2. A body escaped once too often, unescaped: parsed directly, then read by
428
+ * the block strategies below
429
+ * 3. The block strategies on the text itself (`parseJsonBlock`): the first
430
+ * `{...}` object or `[...]` array block as it is, with control characters
431
+ * sanitised, then with invisible characters removed
432
+ *
433
+ * Nothing repairs structure: an answer with a bracket too many is not JSON.
416
434
  *
417
435
  * Returns `null` if every strategy fails. Throws an error with `BAD_GATEWAY` if the
418
436
  * response appears to be an HTML page (likely an API error or rate-limit redirect).
@@ -426,72 +444,226 @@ const extractJSONFromResponse = (text) => {
426
444
  if (isHTMLResponse(text)) {
427
445
  throw errorHandlingHelper.create(constants.HTTP_CODES.BAD_GATEWAY, "LLM API returned HTML instead of JSON. This may indicate an API error, rate limit, or network issue. Please retry.");
428
446
  }
429
- // Remove markdown code blocks and fix invalid escape sequences
430
- const cleaned = text
431
- .replace(/```json\s*/gi, "")
432
- .replace(/```\s*/g, "")
433
- .replace(/\\'/g, "'") // Fix invalid \' escape (not valid in JSON)
434
- .trim();
435
- // Try parsing directly first
447
+ const cleaned = withoutFences(text);
448
+ // Try parsing directly first. A JSON string holding an object or array
449
+ // (an answer quoted once too often) is parsed again for what it holds.
436
450
  try {
437
- return JSON.parse(cleaned);
451
+ const value = JSON.parse(cleaned);
452
+ return typeof value === "string" ? (jsonHeldBy(value) ?? value) : value;
438
453
  }
439
454
  catch {
440
455
  // Continue to fallback methods
441
456
  }
442
- // Try to find JSON object boundaries
443
- const jsonMatch = cleaned.match(/\{[\s\S]*\}/);
444
- if (jsonMatch) {
457
+ // A JSON body escaped once too often: a JSON string's contents without
458
+ // its quotes — `{\"keptIds\":[\"m0\"]}` with literal backslashes, as Claude
459
+ // and Gemini both answered in production (2026-11-09). Unescaping it once
460
+ // gives the JSON itself, or text the block strategies read like any other:
461
+ // the body wrapped in prose, or holding a raw line break inside a value.
462
+ const unescaped = unescapeJsonBody(cleaned);
463
+ if (unescaped !== null) {
445
464
  try {
446
- return JSON.parse(jsonMatch[0]);
465
+ return JSON.parse(unescaped);
447
466
  }
448
467
  catch {
449
- // Try cleaning special characters
450
- try {
451
- const sanitized = jsonMatch[0]
452
- .replace(/[\u0000-\u001F\u007F-\u009F]/g, " ") // Remove control characters
453
- .replace(/\r\n/g, "\\n") // Normalize line endings
454
- .replace(/\r/g, "\\n")
455
- .replace(/\t/g, "\\t"); // Escape tabs
456
- return JSON.parse(sanitized);
457
- }
458
- catch {
459
- // Continue to next fallback
460
- }
468
+ // not JSON as it stands: a block inside it may be
461
469
  }
462
- }
463
- // Try to find JSON array boundaries
464
- const arrayMatch = cleaned.match(/\[[\s\S]*\]/);
465
- if (arrayMatch) {
470
+ const held = parseJsonBlock(unescaped).value;
471
+ if (held !== undefined)
472
+ return held;
473
+ }
474
+ // A body escaped in part: it opens as plain JSON and escapes its quotes
475
+ // somewhere inside (`{"a":[],\"b\":[{\"c\":\"d\"}],"e":[]}`), as Gemini
476
+ // answered a review in production (2026-11-16). Unescaping the whole of it
477
+ // would break the plain part, so each string is closed the way it opened.
478
+ const mended = withEscapedStringsMended(cleaned);
479
+ if (mended !== null) {
466
480
  try {
467
- return JSON.parse(arrayMatch[0]);
481
+ return JSON.parse(mended);
468
482
  }
469
483
  catch {
484
+ // not JSON even so
485
+ }
486
+ }
487
+ return parseJsonBlock(cleaned).value ?? null;
488
+ };
489
+ /** An answer without its markdown code fences and its invalid `\'` escapes, trimmed. */
490
+ const withoutFences = (text) => text
491
+ .replace(/```json\s*/gi, "")
492
+ .replace(/```\s*/g, "")
493
+ .replace(/\\'/g, "'") // Fix invalid \' escape (not valid in JSON)
494
+ .trim();
495
+ const OBJECT_BLOCK = /\{[\s\S]*\}/;
496
+ const ARRAY_BLOCK = /\[[\s\S]*\]/;
497
+ /**
498
+ * The block strategies: the JSON a block inside `text` holds. The array when
499
+ * the text opens with one (an array of objects would otherwise be read as its
500
+ * first object alone), else the object. Each block as it is, then with control
501
+ * characters sanitised, then with invisible characters removed — never with
502
+ * its non-ASCII text blanked, which would damage every accent and dash in the
503
+ * values. Nothing is repaired: a block that is not JSON stays unread.
504
+ * @param text The cleaned answer, or the text an escaped answer stands for
505
+ * @returns `value` when a block parsed; else `failed`, the first block as it
506
+ * was last tried with the parse error it gave, when the text held a block
507
+ */
508
+ const parseJsonBlock = (text) => {
509
+ const opensWithArray = /^[^[{]*\[/.test(text);
510
+ const blocks = opensWithArray ? [ARRAY_BLOCK, OBJECT_BLOCK] : [OBJECT_BLOCK, ARRAY_BLOCK];
511
+ let failed;
512
+ for (const pattern of blocks) {
513
+ const block = text.match(pattern)?.[0];
514
+ if (!block)
515
+ continue;
516
+ const sanitized = sanitizeControls(block);
517
+ let last;
518
+ for (const candidate of [block, sanitized, withoutInvisibles(sanitized)]) {
470
519
  try {
471
- const sanitized = arrayMatch[0]
472
- .replace(/[\u0000-\u001F\u007F-\u009F]/g, " ")
473
- .replace(/\r\n/g, "\\n")
474
- .replace(/\r/g, "\\n")
475
- .replace(/\t/g, "\\t");
476
- return JSON.parse(sanitized);
520
+ return { value: JSON.parse(candidate) };
477
521
  }
478
- catch {
479
- // Continue to next fallback
522
+ catch (error) {
523
+ last = { text: candidate, error }; // next candidate
480
524
  }
481
525
  }
526
+ // the first block's failure is the one reported: the reason that outlived every strategy
527
+ failed ??= last;
482
528
  }
483
- // Last resort: strip all non-printable except standard whitespace
529
+ return { failed };
530
+ };
531
+ /** Control characters replaced by spaces, line endings normalised, tabs escaped (what a model pastes into a value raw). */
532
+ const sanitizeControls = (block) => block
533
+ .replace(/[\u0000-\u001F\u007F-\u009F]/g, " ")
534
+ .replace(/\r\n/g, "\\n")
535
+ .replace(/\r/g, "\\n")
536
+ .replace(/\t/g, "\\t");
537
+ /**
538
+ * Invisible characters a model may leave in its answer — a byte-order mark, a
539
+ * soft hyphen, zero-width and directional marks — removed; a non-breaking
540
+ * space becomes a space. Printable text in any script is kept.
541
+ */
542
+ const withoutInvisibles = (block) => block.replace(/[\u00AD\u200B-\u200F\u2028-\u202E\u2060-\u206F\uFEFF]/g, "").replace(/\u00A0/g, " ");
543
+ /**
544
+ * The object or array a string holds when it is JSON itself (`'{"a":1}'`);
545
+ * null when it is any other text.
546
+ * @param text A string value a model answered
547
+ */
548
+ const jsonHeldBy = (text) => {
549
+ const trimmed = text.trim();
550
+ if (!/^[[{]/.test(trimmed))
551
+ return null;
484
552
  try {
485
- const stripped = cleaned.replace(/[^\x20-\x7E\n]/g, " ");
486
- const finalMatch = stripped.match(/\{[\s\S]*\}/) || stripped.match(/\[[\s\S]*\]/);
487
- if (finalMatch) {
488
- return JSON.parse(finalMatch[0]);
553
+ const value = JSON.parse(trimmed);
554
+ return typeof value === "object" && value !== null ? value : null;
555
+ }
556
+ catch {
557
+ return null;
558
+ }
559
+ };
560
+ /**
561
+ * A JSON text some of whose strings were escaped once too often, with those
562
+ * strings unescaped: outside a string, `\"` can only be a quote the model
563
+ * escaped by mistake, so it opens a string that the next bare `\"` closes,
564
+ * and what lies between is read one level down (`\\\"` is a quote inside the
565
+ * string, `\\n` a line break in it). A string opened by a plain quote is
566
+ * left exactly as it is, and so is everything else. A `\n`, `\r` or `\t`
567
+ * between tokens, where the escaped part was pretty-printed, is white space.
568
+ * Null when no string opens with an escaped quote: there is nothing to mend,
569
+ * and valid JSON never does.
570
+ * @param text The cleaned answer
571
+ */
572
+ const withEscapedStringsMended = (text) => {
573
+ let out = "";
574
+ let mended = false;
575
+ // Where the walk is: outside any string, in one a plain quote opened, or in
576
+ // one an escaped quote opened.
577
+ let within = "none";
578
+ for (let i = 0; i < text.length; i += 1) {
579
+ const char = text[i];
580
+ const next = text[i + 1];
581
+ if (within === "none") {
582
+ if (char === "\\" && next === '"') {
583
+ out += '"';
584
+ within = "escaped";
585
+ mended = true;
586
+ i += 1;
587
+ }
588
+ else if (char === "\\" && (next === "n" || next === "r" || next === "t")) {
589
+ out += " ";
590
+ i += 1;
591
+ }
592
+ else {
593
+ if (char === '"')
594
+ within = "plain";
595
+ out += char;
596
+ }
597
+ }
598
+ else if (within === "plain") {
599
+ if (char === "\\" && next !== undefined) {
600
+ out += char + next;
601
+ i += 1;
602
+ }
603
+ else {
604
+ if (char === '"')
605
+ within = "none";
606
+ out += char;
607
+ }
608
+ }
609
+ else if (char !== "\\") {
610
+ out += char;
611
+ }
612
+ else if (next === '"') {
613
+ out += '"';
614
+ within = "none";
615
+ i += 1;
616
+ }
617
+ else if (next === "\\") {
618
+ // An escaped backslash stands for the backslash of an escape one level
619
+ // down: what follows it is that escape's character, itself escaped
620
+ // when it is a quote or a backslash.
621
+ const after = text[i + 2];
622
+ const escapedAfter = after === "\\" && (text[i + 3] === '"' || text[i + 3] === "\\");
623
+ out += `\\${escapedAfter ? text[i + 3] : (after ?? "")}`;
624
+ i += escapedAfter ? 3 : 2;
489
625
  }
626
+ else {
627
+ out += char;
628
+ }
629
+ }
630
+ return mended ? out : null;
631
+ };
632
+ /**
633
+ * A JSON string's contents without the quote left at either end: a model that
634
+ * answers a JSON string may drop one of its two quotes and keep the other
635
+ * (`{\"a\":1}"`, prod 2026-11-15), and with both kept a raw control
636
+ * character inside still fails the direct parse. A quote at the start, and one
637
+ * at the end that no backslash escapes, is a delimiter and not part of the
638
+ * contents: every quote inside a string's contents is escaped.
639
+ * @param text The cleaned answer, carrying JSON escapes
640
+ */
641
+ const withoutStrayQuotes = (text) => {
642
+ const opened = text.startsWith('"') ? text.slice(1) : text;
643
+ const backslashes = /(\\*)"$/.exec(opened)?.[1].length;
644
+ return backslashes !== undefined && backslashes % 2 === 0 ? opened.slice(0, -1) : opened;
645
+ };
646
+ /**
647
+ * The text a JSON string's escaped contents stand for: `text` carrying JSON
648
+ * escapes (`\"`, `\n`) parsed once, between quotes, into the string it
649
+ * encodes. Raw control characters — a line break or a tab between the tokens
650
+ * of a pretty-printed body, or inside a value — are kept as they are: a JSON
651
+ * string may not hold one raw, so each is escaped for the parse, which before
652
+ * 2026-11-13 failed on them and left the answer unread. A quote the answer
653
+ * kept at either end is set aside first (withoutStrayQuotes). Null when
654
+ * `text` carries no escape or is not a string's contents.
655
+ * @param text The cleaned answer
656
+ */
657
+ const unescapeJsonBody = (text) => {
658
+ if (!/\\["\\nrt]/.test(text))
659
+ return null;
660
+ const contents = withoutStrayQuotes(text).replace(/[\u0000-\u001F]/g, (control) => `\\u${control.charCodeAt(0).toString(16).padStart(4, "0")}`);
661
+ try {
662
+ return JSON.parse(`"${contents}"`);
490
663
  }
491
664
  catch {
492
- // All attempts failed
665
+ return null;
493
666
  }
494
- return null;
495
667
  };
496
668
  /**
497
669
  * Whether a model accepts the `temperature` sampling parameter at all. Some
@@ -521,6 +693,35 @@ const modelSupportsTemperature = (modelName) => {
521
693
  return false;
522
694
  return true;
523
695
  };
696
+ /**
697
+ * Whether an OpenAI model reasons before it answers: the GPT-5 and GPT-6
698
+ * generations, bar the `gpt-5-chat` ids, which do not. Such a model can hand
699
+ * back its reasoning in encrypted form for the next turn of a tool loop; one
700
+ * that does not reason is refused the request field that asks for it.
701
+ * @param modelName - the model identifier being routed
702
+ * @returns `true` when the model reasons
703
+ */
704
+ const openAIModelReasons = (modelName) => /^gpt-[56]($|[.-])/.test(modelName) && !modelName.startsWith("gpt-5-chat");
705
+ /**
706
+ * Whether a Claude model refuses to run with thinking turned off.
707
+ * @langchain/anthropic sends `thinking: {type: "disabled"}` unless told
708
+ * otherwise, which Claude Opus 5.5, Sonnet 5.5, Fable 5/5.1 and Mythos 5/5.1
709
+ * reject with a 400; on these thinking is always on and effort is the only
710
+ * control. Opus 5, Sonnet 5, Haiku 5.5 and earlier still accept it disabled.
711
+ * @param modelName - the model identifier being routed
712
+ * @returns `true` when the model must be sent adaptive thinking
713
+ */
714
+ const modelRequiresThinking = (modelName) => {
715
+ if (!modelName)
716
+ return false;
717
+ if (/^claude-(fable|mythos)-/.test(modelName))
718
+ return true;
719
+ if (/^claude-(opus|sonnet)-5-([5-9]|\d\d)\b/.test(modelName))
720
+ return true;
721
+ if (/^claude-(opus|sonnet)-([6-9]|\d\d)\b/.test(modelName))
722
+ return true;
723
+ return false;
724
+ };
524
725
  /**
525
726
  * Per-provider valid `temperature` range, used to clamp caller-supplied values.
526
727
  * Anthropic caps at 1.0; OpenAI and Gemini accept up to 2.0. Only consulted for
@@ -559,6 +760,58 @@ const resolveTemperatureSetting = (modelName, config) => {
559
760
  }
560
761
  return { temperature: clamped };
561
762
  };
763
+ /** The `output_config.effort` levels Anthropic accepts, lowest first. */
764
+ const EFFORT_LEVELS = ["low", "medium", "high", "xhigh", "max"];
765
+ /**
766
+ * Whether a Claude model accepts `output_config.effort`. Anthropic added it
767
+ * with Opus 4.6 and Sonnet 4.6; every later Opus and Sonnet (4.7, 4.8, …),
768
+ * the whole 5-series (Opus, Sonnet and Haiku) and Fable / Mythos take it.
769
+ * Haiku 4.5, Opus 4.5, Sonnet 4.5 and earlier reject it with a 400. Only the
770
+ * Claude branch of getLLMModel consults this: other providers' models never
771
+ * see the setting and raise no warning for it.
772
+ * @param modelName - the model identifier being routed
773
+ * @returns `true` when the model accepts an `effort` setting
774
+ */
775
+ const modelSupportsEffort = (modelName) => {
776
+ if (/^claude-(fable|mythos)-/.test(modelName))
777
+ return true;
778
+ if (/^claude-(opus|sonnet)-4-([6-9]|\d\d)\b/.test(modelName))
779
+ return true;
780
+ if (/^claude-(opus|sonnet|haiku)-([5-9]|\d\d)\b/.test(modelName))
781
+ return true;
782
+ return false;
783
+ };
784
+ /**
785
+ * Resolves the `reasoningEffort` model setting (`config.reasoningEffort`) for
786
+ * a Claude model. It becomes `output_config.effort`, the one control over how
787
+ * much a 5-series model thinks (Opus 5.5 defaults to `medium`, Opus 5 to
788
+ * `high`, so an agent that wants parity across them sets it explicitly).
789
+ * Applied in order:
790
+ * 1. presence — an absent or empty value leaves the provider default;
791
+ * 2. validity — a value outside `EFFORT_LEVELS` is ignored, with a warning;
792
+ * 3. support — a model that rejects the parameter gets it omitted, with a
793
+ * warning, to avoid an HTTP 400.
794
+ * Returns the level to send, or `undefined` when the field should be omitted.
795
+ */
796
+ const resolveEffortSetting = (modelName, config) => {
797
+ const effort = config?.reasoningEffort;
798
+ if (effort === undefined || effort === null || effort === "") {
799
+ return undefined;
800
+ }
801
+ if (typeof effort !== "string" ||
802
+ !EFFORT_LEVELS.includes(effort)) {
803
+ // Described, not serialised: a bigint or a cyclic object would make
804
+ // JSON.stringify throw from inside a warning that must never throw.
805
+ const shown = typeof effort === "string" ? `"${effort}"` : `of type ${typeof effort}`;
806
+ logger.log(null, logger.levels.warn, `Reasoning effort ${shown} is not one of ${EFFORT_LEVELS.join(", ")}; ignoring it for "${modelName}".`);
807
+ return undefined;
808
+ }
809
+ if (!modelSupportsEffort(modelName)) {
810
+ logger.log(null, logger.levels.warn, `Model "${modelName}" does not accept a reasoning effort parameter; ignoring configured effort "${effort}".`);
811
+ return undefined;
812
+ }
813
+ return effort;
814
+ };
562
815
  /**
563
816
  * Flattens LangChain message content into plain text. Content is a string for
564
817
  * ordinary completions, but providers switch to an array of blocks whenever the
@@ -588,7 +841,7 @@ const extractTextContent = (content) => {
588
841
  * name prefix. `claude-` maps to `ChatAnthropic`, `gemini-` maps to
589
842
  * `ChatGoogleGenerativeAI`, and `gpt-` maps to `ChatOpenAI`. When a Zod
590
843
  * `schema` is provided, native structured output is configured per provider: OpenAI
591
- * via `response_format` with `json_schema`, Anthropic via `output_config.format`, and
844
+ * via `text.format` with `json_schema` (the Responses API), Anthropic via `output_config.format`, and
592
845
  * Gemini via JSON mode (`json: true`) plus `responseSchema`. In every case the model
593
846
  * emits JSON as the message text, so the caller's parse/validate pipeline is unchanged.
594
847
  * Throws a `BAD_REQUEST` error for unrecognised model names.
@@ -600,7 +853,8 @@ const extractTextContent = (content) => {
600
853
  * @param modelName - The model identifier, e.g. `"gpt-4o"`, `"claude-3-5-sonnet"`,
601
854
  * `"gemini-1.5-pro"`
602
855
  * @param config - Configuration object containing API keys (`openAIAPIKey`,
603
- * `anthropicAPIKey`, `googleAPIKey`) and optional `temperature`
856
+ * `anthropicAPIKey`, `googleAPIKey`) and optional `temperature` and
857
+ * `reasoningEffort` (Claude models from Opus 4.6 / Sonnet 4.6 on)
604
858
  * @param schema - Optional Zod schema used to configure native structured JSON output
605
859
  * @returns A configured LangChain chat model (or bound runnable) instance
606
860
  */
@@ -629,15 +883,30 @@ export const getLLMModel = (modelName, config, schema = null) => {
629
883
  // `transformJSONSchema` applies the same strict-schema normalisation
630
884
  // (additionalProperties: false, required fields) that @langchain/anthropic
631
885
  // uses internally, which the API requires.
632
- const outputConfig = schema
633
- ? {
634
- outputConfig: {
886
+ //
887
+ // `output_config.effort` rides in the same object when the agent's config
888
+ // sets `reasoningEffort` and the model takes it (see resolveEffortSetting).
889
+ // The field is left off entirely when neither applies, so the request
890
+ // carries no `output_config` at all in that case.
891
+ const effort = resolveEffortSetting(modelName, config);
892
+ const outputConfigFields = {
893
+ ...(schema
894
+ ? {
635
895
  format: {
636
896
  type: "json_schema",
637
897
  schema: transformJSONSchema(z.toJSONSchema(schema)),
638
898
  },
639
- },
640
- }
899
+ }
900
+ : {}),
901
+ ...(effort ? { effort } : {}),
902
+ };
903
+ const outputConfig = Object.keys(outputConfigFields).length
904
+ ? { outputConfig: outputConfigFields }
905
+ : {};
906
+ // Thinking blocks in the answer are dropped by extractTextContent, so the
907
+ // parse pipeline still sees only the JSON text.
908
+ const thinking = modelRequiresThinking(modelName)
909
+ ? { thinking: { type: "adaptive" } }
641
910
  : {};
642
911
  const model = new ChatAnthropic({
643
912
  apiKey: config.anthropicAPIKey,
@@ -646,6 +915,7 @@ export const getLLMModel = (modelName, config, schema = null) => {
646
915
  streaming: true,
647
916
  invocationKwargs: { cache_control: { type: "ephemeral" } },
648
917
  ...outputConfig,
918
+ ...thinking,
649
919
  ...modelSettings,
650
920
  });
651
921
  return model;
@@ -676,47 +946,56 @@ export const getLLMModel = (modelName, config, schema = null) => {
676
946
  }
677
947
  // GPT models (OpenAI)
678
948
  else if (modelName.startsWith("gpt-")) {
949
+ // Every OpenAI call goes to the Responses API (/v1/responses), never to
950
+ // Chat Completions. Chat Completions refuses function tools beside a
951
+ // reasoning model's reasoning (prod, 2026-11-16: every judging call that
952
+ // had a page to read failed with "400 Function tools with reasoning_effort
953
+ // are not supported for gpt-6.1-sol in /v1/chat/completions. To use
954
+ // function tools, use /v1/responses or set reasoning_effort to 'none'";
955
+ // the gpt-5.6 family fails the same way). Turning reasoning off to get
956
+ // tools gives up what a strong-tier model is chosen for; on the Responses
957
+ // API a model reasons and calls tools in the same request, so no model is
958
+ // sent a reasoning override. One endpoint for every `gpt-` model keeps one
959
+ // request shape to reason about, whatever the model and with or without
960
+ // tools.
961
+ //
962
+ // `zdrEnabled` sends `store: false`: the Responses API keeps each response
963
+ // on OpenAI's side by default, and Chat Completions kept nothing, so
964
+ // nothing is kept here either. With nothing stored, a tool loop has to
965
+ // carry the model's reasoning itself: a reasoning model is asked for its
966
+ // reasoning in encrypted form (`include`), which LangChain hands back on
967
+ // the next turn of the loop. Models that do not reason are not asked: the
968
+ // API refuses the field for them.
679
969
  const openAISettings = {
680
970
  apiKey: config.openAIAPIKey,
681
- // No output limit is sent: OpenAI defaults to the model's maximum. The
682
- // snake_case `max_tokens` that used to sit here was never a recognised
683
- // ChatOpenAI field and was silently dropped by LangChain.
971
+ // No output limit is sent: OpenAI defaults to the model's maximum.
684
972
  modelName: modelName,
685
973
  ...modelSettings,
974
+ useResponsesApi: true,
975
+ zdrEnabled: true,
686
976
  };
687
- // The gpt-5.6 family's /v1/chat/completions endpoint 400s whenever function
688
- // tools are bound, because it rejects the model's own server-side default
689
- // reasoning effort in that combination ("use /v1/responses or set
690
- // reasoning_effort to 'none'"); forcing it to "none" here avoids the
691
- // collision. The restriction belongs to the family, not to one id: the
692
- // `gpt-5.6` alias resolves to `gpt-5.6-sol`, and `gpt-5.6-terra` /
693
- // `gpt-5.6-luna` are separately addressable ids that hit the same 400, as
694
- // do dated snapshots (`gpt-5.6-2026-08-22`). Matching the alias alone left
695
- // every one of those unpatched, so match the whole family. Still excludes
696
- // sibling releases (gpt-5.5, gpt-5.7): they are not confirmed to share the
697
- // bug, and reasoning effort is worth keeping wherever it is accepted.
698
- const reasoningEffortOverride = /^gpt-5\.6($|-)/.test(modelName)
699
- ? { reasoning_effort: "none" }
700
- : {};
701
- // Use native structured output with a JSON schema. `modelKwargs` is spread
702
- // verbatim into the Chat Completions request. Merge (not overwrite) with
703
- // the reasoning-effort override above, since both may apply at once.
704
- if (schema) {
705
- const jsonSchema = strictifyJsonSchema(buildJsonSchema(schema));
706
- openAISettings.modelKwargs = {
707
- ...reasoningEffortOverride,
708
- response_format: {
709
- type: "json_schema",
710
- json_schema: {
711
- name: "response_schema",
712
- strict: true,
713
- schema: jsonSchema,
977
+ // `modelKwargs` is spread verbatim into the Responses request. Native
978
+ // structured output is `text.format` there (Chat Completions called it
979
+ // `response_format`, with the schema one level deeper).
980
+ const modelKwargs = {
981
+ ...(openAIModelReasons(modelName)
982
+ ? { include: ["reasoning.encrypted_content"] }
983
+ : {}),
984
+ ...(schema
985
+ ? {
986
+ text: {
987
+ format: {
988
+ type: "json_schema",
989
+ name: "response_schema",
990
+ strict: true,
991
+ schema: strictifyJsonSchema(buildJsonSchema(schema)),
992
+ },
714
993
  },
715
- },
716
- };
717
- }
718
- else if (Object.keys(reasoningEffortOverride).length > 0) {
719
- openAISettings.modelKwargs = { ...reasoningEffortOverride };
994
+ }
995
+ : {}),
996
+ };
997
+ if (Object.keys(modelKwargs).length > 0) {
998
+ openAISettings.modelKwargs = modelKwargs;
720
999
  }
721
1000
  return new ChatOpenAI(openAISettings);
722
1001
  }
@@ -736,9 +1015,12 @@ export const getLLMModel = (modelName, config, schema = null) => {
736
1015
  * etc.), plus optional `tavily` (`true` or a `TavilyConfig`) to append the web tools
737
1016
  * @param usageTracker - Optional accumulator the Tavily tools bill their credits and
738
1017
  * record their sources into; the LLM's own token usage is tracked by `runAgent`
1018
+ * @param options - Optional LangChain `middleware` and `checkpointer`. An agent whose
1019
+ * checkpointer is a `durable.SnapshotSaver` can pause inside a `workflow.run` turn
1020
+ * (an interrupt in a tool or a middleware) and resume in another run
739
1021
  * @returns A configured LangChain agent instance ready to be run with `runAgent`
740
1022
  */
741
- const createAgent = (name, modelName, systemPrompt, tools = [], responseFormat, config, usageTracker = null) => {
1023
+ const createAgent = (name, modelName, systemPrompt, tools = [], responseFormat, config, usageTracker = null, options = {}) => {
742
1024
  // The Tavily tools join the agent's tool list rather than being bound inside
743
1025
  // `getLLMModel`: they run client-side, so only the agent loop can execute
744
1026
  // them, and the agent binds its own tools to the model anyway — anything
@@ -755,18 +1037,48 @@ const createAgent = (name, modelName, systemPrompt, tools = [], responseFormat,
755
1037
  systemPrompt: systemPrompt.trim(),
756
1038
  tools: tavilyTools.length > 0 ? [...tools, ...tavilyTools] : tools,
757
1039
  ...(responseFormat ? { responseFormat: responseFormat } : {}),
1040
+ ...(options?.middleware?.length ? { middleware: options.middleware } : {}),
1041
+ ...(options?.checkpointer ? { checkpointer: options.checkpointer } : {}),
758
1042
  });
759
1043
  return agent;
760
1044
  };
761
1045
  // What the progress bar says while each tool agent-utils registers (the
762
- // Tavily tools in tavily.ts) runs. A Map, so a tool named after an
763
- // Object.prototype key ("constructor") is not mistaken for a label.
1046
+ // Tavily tools in tavily.ts, the source tool in sourceStore.ts) runs. A Map,
1047
+ // so a tool named after an Object.prototype key ("constructor") is not
1048
+ // mistaken for a label. The source tool says more itself, by title, to a
1049
+ // caller that gives it `onProgress`; these are what is said without it.
764
1050
  const TOOL_PROGRESS_LABELS = new Map([
765
1051
  ["web_search", "Searching the web"],
766
1052
  ["web_extract", "Reading web pages"],
767
1053
  ["web_map", "Listing the pages of a site"],
768
1054
  ["web_crawl", "Reading the pages of a site"],
1055
+ ["list_sources", "Looking over the references"],
1056
+ ["get_outline", "Looking through a reference"],
1057
+ ["read_pages", "Reading a reference"],
1058
+ ["read_document", "Reading a reference"],
1059
+ ]);
1060
+ // The lucide icon the progress dialog shows while each of those tools runs.
1061
+ // A tool without one (an agent's own) sends none, and the dialog keeps its own.
1062
+ const TOOL_PROGRESS_ICONS = new Map([
1063
+ ["web_search", "search"],
1064
+ ["web_extract", "globe"],
1065
+ ["web_map", "map"],
1066
+ ["web_crawl", "file-search"],
1067
+ ["list_sources", "list"],
1068
+ ["get_outline", "list"],
1069
+ ["read_pages", "book-open"],
1070
+ ["read_document", "book-open"],
769
1071
  ]);
1072
+ /**
1073
+ * The `icon` field of a tool call's progress event: the tool's icon, or
1074
+ * nothing at all when it has none.
1075
+ * @param name - The tool's registered name
1076
+ * @returns `{ icon }` to spread into the event, or `{}`
1077
+ */
1078
+ const toolProgressIcon = (name) => {
1079
+ const icon = TOOL_PROGRESS_ICONS.get(String(name ?? ""));
1080
+ return icon ? { icon } : {};
1081
+ };
770
1082
  /**
771
1083
  * The progress message for a tool call, in words the person watching the run
772
1084
  * can read. A tool without a label (an agent's own) reads as its name with
@@ -782,6 +1094,110 @@ const toolProgressLabel = (name) => {
782
1094
  const words = text.replace(/_+/g, " ").trim();
783
1095
  return words ? `Using ${words}` : "Using a tool";
784
1096
  };
1097
+ /**
1098
+ * `agent.invoke`, waiting out a 429 up to MAX_RATE_LIMIT_RETRIES times. The
1099
+ * agent loop may issue many internal LLM calls, but a rate limit surfaces as a
1100
+ * thrown error from the wrapping invoke. `retryInput` says what a retry sends:
1101
+ * the prompt again restarts the run from scratch (an agent without a
1102
+ * checkpointer keeps no state to go on from); `null` continues a
1103
+ * checkpointed thread from its last step, so nothing is appended twice.
1104
+ */
1105
+ const invokeAgent = async (agent, input, options, onProgress, modelName, retryInput) => {
1106
+ let next = input;
1107
+ let rateLimitAttempt = 0;
1108
+ let droppedAttempt = 0;
1109
+ while (true) {
1110
+ // A cancelled request starts no agent run, and one cancelled mid-run
1111
+ // says so, whatever the aborted call inside it threw.
1112
+ throwIfRequestCancelled();
1113
+ try {
1114
+ return await agent.invoke(next, options);
1115
+ }
1116
+ catch (err) {
1117
+ if (isRequestCancelled())
1118
+ throw requestCancelledError();
1119
+ if (isRateLimitError(err) && rateLimitAttempt < MAX_RATE_LIMIT_RETRIES) {
1120
+ rateLimitAttempt++;
1121
+ const { waitMs, source } = getRateLimitWaitMs(err);
1122
+ const waitSeconds = Math.round(waitMs / 1000);
1123
+ logger.log(null, logger.levels.warn, `Rate limited by "${modelName}" (agent), waiting ${waitSeconds}s before retry (${rateLimitAttempt}/${MAX_RATE_LIMIT_RETRIES}, source=${source}): ${err?.message ?? err}`);
1124
+ if (onProgress) {
1125
+ onProgress({
1126
+ type: "rate_limit",
1127
+ message: `AI service is busy. Retrying in ${waitSeconds}s...`,
1128
+ icon: "hourglass",
1129
+ });
1130
+ }
1131
+ await sleep(waitMs);
1132
+ next = retryInput(next);
1133
+ continue;
1134
+ }
1135
+ const droppedWait = droppedConnectionWait(err, droppedAttempt);
1136
+ if (droppedWait !== null) {
1137
+ droppedAttempt++;
1138
+ logDroppedConnection(modelName, err, droppedWait, droppedAttempt);
1139
+ await sleep(droppedWait);
1140
+ next = retryInput(next);
1141
+ continue;
1142
+ }
1143
+ throw err;
1144
+ }
1145
+ }
1146
+ };
1147
+ /**
1148
+ * The agent run as it always was: from scratch on a 429 (partial progress is
1149
+ * discarded, the agent state isn't externally checkpointed), usage recorded
1150
+ * only on a successful completion, as the non-agentic paths do.
1151
+ */
1152
+ const invokeAndCount = async (agent, freshInput, options, config, onProgress, modelName, usageTracker) => {
1153
+ const response = await invokeAgent(agent, freshInput(), options, onProgress, modelName, freshInput);
1154
+ updateUsageTracker(usageTracker, modelName, sumAgentResponseUsage(response), config);
1155
+ return response;
1156
+ };
1157
+ /**
1158
+ * A journaled agent unit whose agent is checkpointed by a SnapshotSaver
1159
+ * (design #964 §10.2): its thread is its unit key, a 429 continues it from
1160
+ * its last step, and an interrupt pauses the turn with the thread exported.
1161
+ * On the turn's resume, its thread is imported from the checkpoint and
1162
+ * invoked with `Command({ resume })`, the answers by interrupt id, and only
1163
+ * the usage of what the resume added is counted (the run that paused counted
1164
+ * the rest). A finished invocation deletes its thread.
1165
+ */
1166
+ const invokeDurably = async (agent, unit, input, options, config, onProgress, modelName, usageTracker) => {
1167
+ const saver = agent.options.checkpointer;
1168
+ const counted = new Set(unit.paused?.counted ?? []);
1169
+ // The unit's thread is its own: whatever an earlier turn left under its key
1170
+ // in this saver (one that failed mid-way) is not this conversation.
1171
+ await saver.deleteThread(unit.key);
1172
+ let first = input;
1173
+ if (unit.paused) {
1174
+ if (!unit.thread) {
1175
+ throw errorHandlingHelper.create(constants.HTTP_CODES.INTERNAL_SERVER_ERROR, `durable: ${unit.key} paused and the checkpoint does not hold its thread`);
1176
+ }
1177
+ saver.importThreads({ [unit.key]: unit.thread });
1178
+ first = new Command({ resume: unit.resume });
1179
+ }
1180
+ const response = await invokeAgent(agent, first, { ...options, configurable: { thread_id: unit.key } }, onProgress, modelName, () => null);
1181
+ updateUsageTracker(usageTracker, modelName, sumAgentResponseUsage(response, counted), config);
1182
+ // Checked on a copy: the type guard would narrow `response` to the interrupt alone.
1183
+ const answered = response;
1184
+ if (isInterrupted(answered)) {
1185
+ const ids = (response.messages ?? [])
1186
+ .map((message) => message?.id)
1187
+ .filter((id) => typeof id === "string");
1188
+ unit.pause({
1189
+ interrupts: response.__interrupt__.map((interrupt) => ({ id: String(interrupt.id), value: interrupt.value })),
1190
+ thread: saver.exportThreads([unit.key])[unit.key] ?? null,
1191
+ counted: [...new Set([...counted, ...ids])],
1192
+ options: {
1193
+ approvals: config?.approvals ? { addressees: config.approvals.addressees, deadline: config.approvals.deadline } : null,
1194
+ clientTools: config?.clientTools ? { addressees: config.clientTools.addressees, deadline: config.clientTools.deadline } : null,
1195
+ },
1196
+ });
1197
+ }
1198
+ await saver.deleteThread(unit.key);
1199
+ return response;
1200
+ };
785
1201
  /**
786
1202
  * Executes a LangChain agent with a single user prompt and returns the raw agent
787
1203
  * response. When an `onProgress` callback is provided, LangChain callbacks are
@@ -818,23 +1234,30 @@ const runAgent = async (agent, prompt, config, onProgress = null, usageTracker =
818
1234
  onProgress({
819
1235
  type: "tool_start",
820
1236
  message: toolProgressLabel(name),
1237
+ ...toolProgressIcon(name),
821
1238
  tool: name,
822
1239
  progress,
823
1240
  });
824
1241
  },
825
1242
  // `action.log` is the model's own text (LangChain's default reads
826
1243
  // "Invoking: `web_extract` with `{...}`", the raw tool input), so it
827
- // never reaches the progress bar.
1244
+ // never reaches the progress bar; nor does `action.toolInput`, since
1245
+ // tool args never reach onProgress (spec §4).
828
1246
  handleAgentAction: (action) => {
829
1247
  onProgress({
830
1248
  type: "agent_action",
831
1249
  message: toolProgressLabel(action.tool),
1250
+ ...toolProgressIcon(action.tool),
832
1251
  tool: action.tool,
833
- input: action.toolInput,
834
1252
  progress,
835
1253
  });
836
1254
  },
837
1255
  handleChainError: (err) => {
1256
+ // An interrupt is the graph stopping for an answer, not an error,
1257
+ // and its message is the interrupts' JSON: a tool call's args and
1258
+ // description, which never reach the progress bar.
1259
+ if (isGraphBubbleUp(err))
1260
+ return;
838
1261
  onProgress({
839
1262
  type: "error",
840
1263
  message: `Error: ${err?.message || String(err)}`,
@@ -845,43 +1268,33 @@ const runAgent = async (agent, prompt, config, onProgress = null, usageTracker =
845
1268
  ]
846
1269
  : undefined;
847
1270
  const modelName = agent.options?.model?.modelName || agent.options?.model?.model || "";
848
- // Wait + retry on 429 around the full agent run. The agent loop may issue
849
- // many internal LLM calls, but a rate limit surfaces as a thrown error from
850
- // the wrapping invoke. On retry we restart the agent run from scratch — any
851
- // partial progress (tool calls, intermediate messages) is discarded, since
852
- // the agent state isn't externally checkpointed. Usage is only recorded on a
853
- // successful completion. Matches the behavior of the non-agentic paths.
854
- let response;
855
- let rateLimitAttempt = 0;
856
- while (true) {
857
- try {
858
- response = await agent.invoke({
859
- messages: [{ role: "user", content: prompt }],
860
- }, {
861
- recursionLimit: config.recursionLimit || 25,
862
- ...(callbacks ? { callbacks } : {}),
863
- });
864
- break;
865
- }
866
- catch (err) {
867
- if (isRateLimitError(err) && rateLimitAttempt < MAX_RATE_LIMIT_RETRIES) {
868
- rateLimitAttempt++;
869
- const { waitMs, source } = getRateLimitWaitMs(err);
870
- const waitSeconds = Math.round(waitMs / 1000);
871
- logger.log(null, logger.levels.warn, `Rate limited by "${modelName}" (agent), waiting ${waitSeconds}s before retry (${rateLimitAttempt}/${MAX_RATE_LIMIT_RETRIES}, source=${source}): ${err?.message ?? err}`);
872
- if (onProgress) {
873
- onProgress({
874
- type: "rate_limit",
875
- message: `AI service is busy. Retrying in ${waitSeconds}s...`,
876
- });
877
- }
878
- await sleep(waitMs);
879
- continue;
1271
+ // The request's signal stops the agent loop between and inside its steps,
1272
+ // as it stops a plain model call: an abandoned run stops paying.
1273
+ const abortSignal = getAbortSignal();
1274
+ const options = {
1275
+ recursionLimit: config.recursionLimit || 25,
1276
+ ...(callbacks ? { callbacks } : {}),
1277
+ ...(abortSignal ? { signal: abortSignal } : {}),
1278
+ };
1279
+ const freshInput = () => ({ messages: [{ role: "user", content: prompt }] });
1280
+ // In a workflow.run turn the invocation is one journaled unit (`agent#n`):
1281
+ // a paused turn's resume gets its saved answer back without running it, and
1282
+ // an agent checkpointed by a SnapshotSaver can pause on an interrupt and go
1283
+ // on from it (durable/journal.ts). Outside a turn it runs as it always has.
1284
+ const response = await journaled("agent", usageTracker, async (unit) => {
1285
+ // Inside the unit: a resumed turn's replay calls nothing, so asks nothing.
1286
+ await requirePricedModel(modelName);
1287
+ if (agent?.options?.checkpointer instanceof SnapshotSaver) {
1288
+ // Its interrupts pause a turn: with no unit of one to pause (outside a
1289
+ // turn, or under another agent's tool) its answer would be returned as
1290
+ // if it were final.
1291
+ if (!unit) {
1292
+ throw errorHandlingHelper.create(constants.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");
880
1293
  }
881
- throw err;
1294
+ return invokeDurably(agent, unit, freshInput(), options, config, onProgress, modelName, usageTracker);
882
1295
  }
883
- }
884
- updateUsageTracker(usageTracker, modelName, sumAgentResponseUsage(response), config);
1296
+ return invokeAndCount(agent, freshInput, options, config, onProgress, modelName, usageTracker);
1297
+ });
885
1298
  const endTime = Date.now();
886
1299
  const duration = endTime - startTime;
887
1300
  logger.log(null, logger.levels.info, `Agent "${agent.options?.name}" completed in ${Math.round(duration / 1000)} seconds.`);
@@ -1006,13 +1419,33 @@ const getRateLimitWaitMs = (err) => {
1006
1419
  Math.floor(Math.random() * (RATE_LIMIT_MAX_WAIT_MS - RATE_LIMIT_MIN_WAIT_MS + 1));
1007
1420
  return { waitMs, source: "random" };
1008
1421
  };
1422
+ /**
1423
+ * How long to wait before a model call the network dropped is made again, in
1424
+ * milliseconds; null when it is not made again. A call that got no answer, or
1425
+ * whose stream was cut mid-answer (`terminated`), is made again after each of
1426
+ * RETRY_WAITS: the provider's client retries a request that never connected,
1427
+ * never one whose answer had begun, so until 2026-11-15 a stream cut once
1428
+ * failed its call outright. A failure that carries a status was answered and
1429
+ * is not the network's.
1430
+ * @param err What the call failed with
1431
+ * @param made How many times this call has already been made again for the network
1432
+ */
1433
+ const droppedConnectionWait = (err, made) => made < RETRY_WAITS.length && isNetworkFailure(err) ? RETRY_WAITS[made] : null;
1434
+ /**
1435
+ * Logs that a model call the network dropped is being made again.
1436
+ * @param modelName The model called
1437
+ * @param err What the call failed with
1438
+ * @param waitMs How long the retry waits first
1439
+ * @param attempt Which retry this is, from 1
1440
+ */
1441
+ const logDroppedConnection = (modelName, err, waitMs, attempt) => logger.log(null, logger.levels.warn, `Connection to "${modelName}" dropped (${messageOf(err)}), trying again in ${waitMs} ms (${attempt}/${RETRY_WAITS.length})`);
1009
1442
  /**
1010
1443
  * Detects rate-limit (HTTP 429) errors across LangChain and provider SDK shapes.
1011
1444
  * Different SDKs surface the status in different places (status, statusCode,
1012
1445
  * response.status, code) and sometimes only in the message text, so this checks
1013
1446
  * each known shape rather than assuming a single field.
1014
1447
  */
1015
- const isRateLimitError = (err) => {
1448
+ export const isRateLimitError = (err) => {
1016
1449
  if (!err)
1017
1450
  return false;
1018
1451
  const statusCandidates = [
@@ -1033,6 +1466,106 @@ const isRateLimitError = (err) => {
1033
1466
  /rate.?limit/i.test(message) ||
1034
1467
  /too many requests/i.test(message));
1035
1468
  };
1469
+ /** How much of an unparseable response the error quotes: its head and its tail. */
1470
+ const UNPARSEABLE_HEAD = 100;
1471
+ const UNPARSEABLE_TAIL = 200;
1472
+ /**
1473
+ * Describes a response that was expected to be JSON and could not be read: the
1474
+ * text (whole when short, else its first 100 and last 200 characters, so a cut
1475
+ * shows), its length, and the reason `JSON.parse` gave when it was tried. In
1476
+ * production the error quoted the first 100 characters of an output that began
1477
+ * as valid JSON and nothing else (2026-11-01), so whether it was cut short or
1478
+ * held a stray quote was unknowable from the log.
1479
+ *
1480
+ * When the answer is a JSON body escaped once too often that could not be read
1481
+ * once unescaped either, the direct reason is only the backslash at position 1:
1482
+ * the unescaped body's own failure follows it — its length, the parse reason,
1483
+ * the character at that position and the text around it — because the head and
1484
+ * tail quote hides the middle, where 20+ ownership answers failed unexplained
1485
+ * in production (2026-11-13).
1486
+ * @param rawContent - What the model answered
1487
+ * @param parseError - What `JSON.parse` threw on it, when it was tried
1488
+ */
1489
+ const describeUnparseableResponse = (rawContent, parseError) => {
1490
+ let text = "";
1491
+ if (typeof rawContent === "string") {
1492
+ text = rawContent;
1493
+ }
1494
+ else if (typeof rawContent === "object" && rawContent !== null) {
1495
+ text = JSON.stringify(rawContent);
1496
+ }
1497
+ else if (rawContent !== undefined && rawContent !== null) {
1498
+ text = String(rawContent);
1499
+ }
1500
+ if (text === "")
1501
+ return "[empty response]";
1502
+ // An output cut short begins as JSON and ends mid-value, so the direct parse
1503
+ // was never tried on it: try it here, for the reason.
1504
+ if (parseError === undefined && /^\s*[[{]/.test(text)) {
1505
+ try {
1506
+ JSON.parse(text);
1507
+ }
1508
+ catch (error) {
1509
+ parseError = error;
1510
+ }
1511
+ }
1512
+ const quoted = text.length <= UNPARSEABLE_HEAD + UNPARSEABLE_TAIL
1513
+ ? `"${text}"`
1514
+ : `"${text.slice(0, UNPARSEABLE_HEAD)}" … "${text.slice(-UNPARSEABLE_TAIL)}"`;
1515
+ const reason = parseError instanceof Error ? `; ${describeParseFailure(text, parseError)}` : "";
1516
+ return `${quoted} (${text.length} characters${reason}${describeUnescapedFailure(text)})`;
1517
+ };
1518
+ /** How much of an unescaped body the error quotes on each side of the failing position. */
1519
+ const UNESCAPED_EXCERPT = 60;
1520
+ /**
1521
+ * Why `JSON.parse` refused `text`: its message, then the character it stopped
1522
+ * at, by code point — an invisible one, or a backslash in a body escaped once
1523
+ * too often, says nothing in a quote.
1524
+ * @param text - The text that was parsed
1525
+ * @param parseError - What `JSON.parse` threw on it
1526
+ * @param excerpt - Whether to quote the text around the failing position too
1527
+ */
1528
+ const describeParseFailure = (text, parseError, excerpt = false) => {
1529
+ const position = /at position (\d+)/.exec(parseError.message);
1530
+ if (!position)
1531
+ return parseError.message;
1532
+ const at = Number(position[1]);
1533
+ const culprit = at < text.length
1534
+ ? `; character at position ${at}: U+${text.codePointAt(at).toString(16).toUpperCase().padStart(4, "0")} ${JSON.stringify(String.fromCodePoint(text.codePointAt(at)))}`
1535
+ : "";
1536
+ if (!excerpt)
1537
+ return `${parseError.message}${culprit}`;
1538
+ const from = Math.max(0, at - UNESCAPED_EXCERPT);
1539
+ const to = Math.min(text.length, at + UNESCAPED_EXCERPT + 1);
1540
+ const around = `${from > 0 ? "…" : ""}${text.slice(from, to)}${to < text.length ? "…" : ""}`;
1541
+ return `${parseError.message}${culprit}; around position ${at}: "${around}"`;
1542
+ };
1543
+ /**
1544
+ * Why an answer escaped once too often was not JSON once unescaped: the block
1545
+ * inside the unescaped text as the block strategies last tried it (the text
1546
+ * itself when it opens as JSON and holds no closed block, as an answer cut
1547
+ * short does), with its length, parse reason, failing character and the text
1548
+ * around it. Empty when the answer is not an escaped body, or stands for text
1549
+ * that holds no JSON to report on.
1550
+ * @param text - What the model answered
1551
+ */
1552
+ const describeUnescapedFailure = (text) => {
1553
+ const unescaped = unescapeJsonBody(withoutFences(text));
1554
+ if (unescaped === null)
1555
+ return "";
1556
+ let failed = parseJsonBlock(unescaped).failed;
1557
+ if (!failed && /^\s*[[{]/.test(unescaped)) {
1558
+ try {
1559
+ JSON.parse(unescaped);
1560
+ }
1561
+ catch (error) {
1562
+ failed = { text: unescaped, error };
1563
+ }
1564
+ }
1565
+ if (!failed)
1566
+ return "";
1567
+ return `; unescaped body (${failed.text.length} characters): ${describeParseFailure(failed.text, failed.error, true)}`;
1568
+ };
1036
1569
  /**
1037
1570
  * Parses raw LLM content as JSON and validates against an optional Zod schema,
1038
1571
  * returning the canonical JSON string. Tries a direct parse of the trimmed text
@@ -1041,6 +1574,7 @@ const isRateLimitError = (err) => {
1041
1574
  * `INTERNAL_SERVER_ERROR` when no JSON can be extracted from the response at all.
1042
1575
  */
1043
1576
  const parseAndValidateJSONResponse = (rawContent, schema) => {
1577
+ let directParseError;
1044
1578
  if (typeof rawContent === "string") {
1045
1579
  const trimmed = rawContent.trim();
1046
1580
  if ((trimmed.startsWith("{") && trimmed.endsWith("}")) ||
@@ -1057,6 +1591,7 @@ const parseAndValidateJSONResponse = (rawContent, schema) => {
1057
1591
  throw parseError;
1058
1592
  }
1059
1593
  // JSON.parse failed (not a validation error) — fall through to extraction.
1594
+ directParseError = parseError;
1060
1595
  }
1061
1596
  }
1062
1597
  const extracted = extractJSONFromResponse(rawContent);
@@ -1067,20 +1602,7 @@ const parseAndValidateJSONResponse = (rawContent, schema) => {
1067
1602
  return JSON.stringify(extracted);
1068
1603
  }
1069
1604
  }
1070
- let preview = "";
1071
- if (typeof rawContent === "string") {
1072
- preview = rawContent.substring(0, 100);
1073
- }
1074
- else if (typeof rawContent === "object" && rawContent !== null) {
1075
- preview = JSON.stringify(rawContent).substring(0, 100);
1076
- }
1077
- else if (rawContent !== undefined && rawContent !== null) {
1078
- preview = String(rawContent).substring(0, 100);
1079
- }
1080
- else {
1081
- preview = "[empty response]";
1082
- }
1083
- throw errorHandlingHelper.create(constants.HTTP_CODES.INTERNAL_SERVER_ERROR, `LLM returned non-JSON response when JSON was expected: ${preview}...`);
1605
+ throw errorHandlingHelper.create(constants.HTTP_CODES.INTERNAL_SERVER_ERROR, `LLM returned non-JSON response when JSON was expected: ${describeUnparseableResponse(rawContent, directParseError)}`);
1084
1606
  };
1085
1607
  /**
1086
1608
  * Appends the model's failed output as an assistant turn followed by a user turn
@@ -1171,6 +1693,7 @@ const buildValidationRetryMessages = (priorMessages, rawContent, validationError
1171
1693
  * @returns The JSON, re-serialised
1172
1694
  */
1173
1695
  const parseAgenticJsonResponse = (rawContent, schema) => {
1696
+ let directParseError;
1174
1697
  if (typeof rawContent === "string") {
1175
1698
  const trimmed = rawContent.trim();
1176
1699
  if ((trimmed.startsWith("{") && trimmed.endsWith("}")) ||
@@ -1186,6 +1709,7 @@ const parseAgenticJsonResponse = (rawContent, schema) => {
1186
1709
  if (parseError?.code === constants.HTTP_CODES.UNPROCESSABLE_ENTITY) {
1187
1710
  throw parseError;
1188
1711
  }
1712
+ directParseError = parseError;
1189
1713
  }
1190
1714
  }
1191
1715
  // Try to extract JSON from markdown or other wrapping
@@ -1197,20 +1721,65 @@ const parseAgenticJsonResponse = (rawContent, schema) => {
1197
1721
  return JSON.stringify(extracted);
1198
1722
  }
1199
1723
  }
1200
- let preview = "";
1201
- if (typeof rawContent === "string") {
1202
- preview = rawContent.substring(0, 100);
1203
- }
1204
- else if (typeof rawContent === "object" && rawContent !== null) {
1205
- preview = JSON.stringify(rawContent).substring(0, 100);
1206
- }
1207
- else if (rawContent !== undefined && rawContent !== null) {
1208
- preview = String(rawContent).substring(0, 100);
1209
- }
1210
- else {
1211
- preview = "[empty response]";
1724
+ throw errorHandlingHelper.create(constants.HTTP_CODES.INTERNAL_SERVER_ERROR, `Agent returned non-JSON response when JSON was expected: ${describeUnparseableResponse(rawContent, directParseError)}`);
1725
+ };
1726
+ /**
1727
+ * Refuses, before the model is called, an agentic call that would pause where
1728
+ * it cannot (outside a `workflow.run` turn) or with settings its wait would
1729
+ * be refused for. A 500: the agent's code is wrong, not its caller's input.
1730
+ * @param approvals - `config.approvals`, or null
1731
+ * @param clientTools - `config.clientTools`, or null
1732
+ * @param callsClient - Whether the call can pause for a client tool
1733
+ */
1734
+ const checkPauseSettings = (approvals, clientTools, callsClient) => {
1735
+ const refuse = (message) => {
1736
+ throw errorHandlingHelper.create(constants.HTTP_CODES.INTERNAL_SERVER_ERROR, message);
1737
+ };
1738
+ const userIds = (ids) => ids === undefined ||
1739
+ (Array.isArray(ids) &&
1740
+ ids.length >= 1 &&
1741
+ ids.length <= LIMITS.ADDRESSEES_MAX &&
1742
+ ids.every((id) => typeof id === "string" && id.length > 0));
1743
+ // Ruling 34, known at the turn's start: an event's run does not know the
1744
+ // workflow's creator, so its pause must name who answers. Refused here, not
1745
+ // after the turn's LLM calls, which a retried turn would run again.
1746
+ const eventTurn = activeTurn()?.event === true;
1747
+ if (approvals) {
1748
+ if (!activeTurn()) {
1749
+ refuse("config.approvals works only inside a workflow.run turn: a paused conversation needs a workflow to wait on");
1750
+ }
1751
+ const guarded = approvals.tools;
1752
+ if (!guarded || typeof guarded !== "object" || Array.isArray(guarded) || Object.keys(guarded).length === 0) {
1753
+ refuse("config.approvals.tools names the tools that need approval: { tools: { <tool>: true | { allowedDecisions, description? } } }");
1754
+ }
1755
+ if (!userIds(approvals.addressees))
1756
+ refuse(`config.approvals.addressees is a list of 1 to ${LIMITS.ADDRESSEES_MAX} user ids`);
1757
+ if (eventTurn && !approvals.addressees) {
1758
+ refuse("an event's turn must name who answers: set config.approvals.addressees (an event's run does not know the workflow's creator)");
1759
+ }
1760
+ const deadline = approvals.deadline;
1761
+ const at = deadline instanceof Date ? deadline.getTime() : typeof deadline === "string" ? Date.parse(deadline) : NaN;
1762
+ if (deadline !== undefined && Number.isNaN(at))
1763
+ refuse("config.approvals.deadline is a time: an ISO string or a Date");
1764
+ }
1765
+ if (callsClient) {
1766
+ if (!activeTurn()) {
1767
+ refuse("config.clientTools and durable.clientTool work only inside a workflow.run turn: the caller runs the tool while the turn waits");
1768
+ }
1769
+ if (clientTools !== null) {
1770
+ if (typeof clientTools !== "object" || Array.isArray(clientTools))
1771
+ refuse("config.clientTools is { deadline?, addressees? }");
1772
+ const seconds = clientTools.deadline;
1773
+ if (seconds !== undefined && !(typeof seconds === "number" && Number.isFinite(seconds) && seconds >= LIMITS.MIN_TIMER_SECONDS)) {
1774
+ refuse(`config.clientTools.deadline is seconds, at least ${LIMITS.MIN_TIMER_SECONDS}`);
1775
+ }
1776
+ if (!userIds(clientTools.addressees))
1777
+ refuse(`config.clientTools.addressees is a list of 1 to ${LIMITS.ADDRESSEES_MAX} user ids`);
1778
+ }
1779
+ if (eventTurn && !clientTools?.addressees) {
1780
+ refuse("an event's turn must name who answers: set config.clientTools.addressees (an event's run does not know the workflow's creator)");
1781
+ }
1212
1782
  }
1213
- throw errorHandlingHelper.create(constants.HTTP_CODES.INTERNAL_SERVER_ERROR, `Agent returned non-JSON response when JSON was expected: ${preview}...`);
1214
1783
  };
1215
1784
  /**
1216
1785
  * Sends a prompt to an LLM and returns the response, with support for streaming,
@@ -1237,7 +1806,7 @@ const parseAgenticJsonResponse = (rawContent, schema) => {
1237
1806
  * `web_extract` to those URLs.
1238
1807
  * @param modelName - The model identifier, e.g. `"gpt-4o"`, `"claude-3-5-sonnet"`,
1239
1808
  * `"gemini-1.5-pro"`
1240
- * @param config - Configuration object with API keys, `temperature`, optional `agentic`
1809
+ * @param config - Configuration object with API keys, `temperature`, `reasoningEffort`, optional `agentic`
1241
1810
  * flag, optional `recursionLimit`, and optional `tavily` (`true` or a
1242
1811
  * `TavilyConfig`)
1243
1812
  * @param prompt - The prompt to send; either a plain string (user message only) or an
@@ -1263,6 +1832,15 @@ const parseAgenticJsonResponse = (rawContent, schema) => {
1263
1832
  const runPromptWithModel = async (modelName, config, prompt, onProgressReport, minPercent = 0, maxPercent = 100, expectsJsonResponse = true, schema = null, agentName = "StackFactor", tools = [], usageTracker = null) => {
1264
1833
  // Agentic mode: use an agent with tools instead of simple LLM invocation
1265
1834
  if (config.agentic === true) {
1835
+ // Approval inside the tool loop (design #964 §10.2) and client tools
1836
+ // (interactive tool calls §2): the turn pauses on the tool call and goes
1837
+ // on with the person's decision or the caller's result, so each needs a
1838
+ // workflow.run turn to pause, checked before anything else runs.
1839
+ const approvals = config.approvals ?? null;
1840
+ const clientTools = config.clientTools ?? null;
1841
+ const callsClient = clientTools !== null || tools.some(isClientTool);
1842
+ if (approvals || callsClient)
1843
+ checkPauseSettings(approvals, clientTools, callsClient);
1266
1844
  // Extract system prompt and user prompt from the prompt parameter
1267
1845
  let systemPrompt = "";
1268
1846
  let userPrompt = "";
@@ -1293,8 +1871,20 @@ const runPromptWithModel = async (modelName, config, prompt, onProgressReport, m
1293
1871
  // Create the agent with tools. The tracker is handed over at construction
1294
1872
  // because the Tavily tools bill their own credits as they run, rather than
1295
1873
  // being reconciled from the response afterwards.
1874
+ // With approvals, humanInTheLoopMiddleware interrupts on the guarded
1875
+ // tools' calls (config.approvals.tools as it is: a tool named
1876
+ // `addressees` or `deadline` is never confused with the wait's options);
1877
+ // a client tool interrupts in its own body. A SnapshotSaver keeps the
1878
+ // thread the pause exports.
1296
1879
  const agent = createAgent(agentName, modelName, systemPrompt, [...tools], null, // responseFormat
1297
- config, usageTracker);
1880
+ config, usageTracker, ...(approvals || callsClient
1881
+ ? [
1882
+ {
1883
+ middleware: approvals ? [humanInTheLoopMiddleware({ interruptOn: approvals.tools })] : [],
1884
+ checkpointer: new SnapshotSaver(),
1885
+ },
1886
+ ]
1887
+ : []));
1298
1888
  // The JSON stage is retried like the non-agentic paths (canRetryValidation):
1299
1889
  // the agent is run again with its rejected output and the errors appended
1300
1890
  // to the user prompt, up to MAX_VALIDATION_RETRIES. Until now this path
@@ -1333,6 +1923,20 @@ const runPromptWithModel = async (modelName, config, prompt, onProgressReport, m
1333
1923
  }
1334
1924
  }
1335
1925
  }
1926
+ // A non-agentic call is one journaled unit of a workflow.run turn
1927
+ // (`llm#n`): a paused turn's resume gets its saved answer back without
1928
+ // calling the model again. Outside a turn it runs as it always has.
1929
+ return journaled("llm", usageTracker, () => runPromptWithModelOnce(modelName, config, prompt, onProgressReport, minPercent, maxPercent, expectsJsonResponse, schema, agentName, usageTracker));
1930
+ };
1931
+ /**
1932
+ * One non-agentic call of {@link runPromptWithModel}: streamed with progress
1933
+ * when `onProgressReport` is given, else invoked, JSON validated and retried
1934
+ * as that function describes.
1935
+ */
1936
+ const runPromptWithModelOnce = async (modelName, config, prompt, onProgressReport, minPercent, maxPercent, expectsJsonResponse, schema, agentName, usageTracker) => {
1937
+ // Here rather than in runPromptWithModel: a resumed turn's replay returns
1938
+ // the saved answer without calling the model, so it asks nothing.
1939
+ await requirePricedModel(modelName);
1336
1940
  let messages;
1337
1941
  if (typeof prompt === "string") {
1338
1942
  messages = [{ role: "user", content: prompt }];
@@ -1410,7 +2014,10 @@ const runPromptWithModel = async (modelName, config, prompt, onProgressReport, m
1410
2014
  // error out with a rate limit are not counted. A 429 fired mid-stream
1411
2015
  // simply discards the partial output and restarts cleanly.
1412
2016
  let rateLimitAttempt = 0;
2017
+ let droppedAttempt = 0;
1413
2018
  while (true) {
2019
+ // A cancelled request starts no model call.
2020
+ throwIfRequestCancelled();
1414
2021
  rawContent = "";
1415
2022
  chunkCount = 0;
1416
2023
  streamUsage = { input_tokens: 0, output_tokens: 0, total_tokens: 0 };
@@ -1423,9 +2030,8 @@ const runPromptWithModel = async (modelName, config, prompt, onProgressReport, m
1423
2030
  runName: agentName,
1424
2031
  });
1425
2032
  for await (const chunk of stream) {
1426
- if (abortSignal?.aborted) {
1427
- throw errorHandlingHelper.create(constants.HTTP_CODES.BAD_REQUEST, "Request cancelled by caller");
1428
- }
2033
+ if (abortSignal?.aborted)
2034
+ throw requestCancelledError();
1429
2035
  accumulateChunkUsage(streamUsage, chunk);
1430
2036
  // Counting every chunk (not just the ones carrying text) keeps
1431
2037
  // progress ticking through pauses in the stream.
@@ -1441,6 +2047,9 @@ const runPromptWithModel = async (modelName, config, prompt, onProgressReport, m
1441
2047
  break; // stream completed without 429
1442
2048
  }
1443
2049
  catch (err) {
2050
+ // The request's own signal ended the stream: the caller is gone.
2051
+ if (isRequestCancelled())
2052
+ throw requestCancelledError();
1444
2053
  if (isRateLimitError(err) &&
1445
2054
  rateLimitAttempt < MAX_RATE_LIMIT_RETRIES) {
1446
2055
  rateLimitAttempt++;
@@ -1449,11 +2058,21 @@ const runPromptWithModel = async (modelName, config, prompt, onProgressReport, m
1449
2058
  logger.log(null, logger.levels.warn, `Rate limited by "${modelName}", waiting ${waitSeconds}s before retry (${rateLimitAttempt}/${MAX_RATE_LIMIT_RETRIES}, source=${source}): ${err?.message ?? err}`);
1450
2059
  await onProgressReport({
1451
2060
  message: `AI service is busy. Retrying in ${waitSeconds}s...`,
2061
+ icon: "hourglass",
1452
2062
  progress: Math.min(calcCurrentProgress(), maxPercent - 5),
1453
2063
  });
1454
2064
  await sleep(waitMs);
1455
2065
  continue;
1456
2066
  }
2067
+ // A stream the network cut is discarded like one a 429 cut, and
2068
+ // the call made again.
2069
+ const droppedWait = droppedConnectionWait(err, droppedAttempt);
2070
+ if (droppedWait !== null) {
2071
+ droppedAttempt++;
2072
+ logDroppedConnection(modelName, err, droppedWait, droppedAttempt);
2073
+ await sleep(droppedWait);
2074
+ continue;
2075
+ }
1457
2076
  throw err;
1458
2077
  }
1459
2078
  }
@@ -1544,12 +2163,21 @@ const runPromptWithModel = async (modelName, config, prompt, onProgressReport, m
1544
2163
  // the wait is silent to the caller — only the warn log is emitted.
1545
2164
  let response;
1546
2165
  let rateLimitAttempt = 0;
2166
+ let droppedAttempt = 0;
1547
2167
  while (true) {
2168
+ // A cancelled request starts no model call, and one cancelled
2169
+ // mid-call says so.
2170
+ throwIfRequestCancelled();
1548
2171
  try {
1549
- response = await llm.invoke(activeMessages, { runName: agentName });
2172
+ response = await llm.invoke(activeMessages, {
2173
+ runName: agentName,
2174
+ signal: getAbortSignal() ?? undefined,
2175
+ });
1550
2176
  break;
1551
2177
  }
1552
2178
  catch (err) {
2179
+ if (isRequestCancelled())
2180
+ throw requestCancelledError();
1553
2181
  if (isRateLimitError(err) &&
1554
2182
  rateLimitAttempt < MAX_RATE_LIMIT_RETRIES) {
1555
2183
  rateLimitAttempt++;
@@ -1558,6 +2186,13 @@ const runPromptWithModel = async (modelName, config, prompt, onProgressReport, m
1558
2186
  await sleep(waitMs);
1559
2187
  continue;
1560
2188
  }
2189
+ const droppedWait = droppedConnectionWait(err, droppedAttempt);
2190
+ if (droppedWait !== null) {
2191
+ droppedAttempt++;
2192
+ logDroppedConnection(modelName, err, droppedWait, droppedAttempt);
2193
+ await sleep(droppedWait);
2194
+ continue;
2195
+ }
1561
2196
  throw err;
1562
2197
  }
1563
2198
  }
@@ -1623,6 +2258,7 @@ const getImageModelProvider = (modelName) => {
1623
2258
  * or `{ images: [...] }` for multiple images
1624
2259
  */
1625
2260
  const generateImageWithOpenAI = async (modelName, config, prompt, options, usageTracker = null) => {
2261
+ await requirePricedModel(modelName);
1626
2262
  const { size = "1024x1024", style = "vivid", responseFormat = "url", n = 1, } = options;
1627
2263
  if (!config.openAIAPIKey) {
1628
2264
  throw errorHandlingHelper.create(constants.HTTP_CODES.BAD_REQUEST, "OpenAI API key is required for OpenAI image generation");
@@ -1710,6 +2346,7 @@ const generateImageWithOpenAI = async (modelName, config, prompt, options, usage
1710
2346
  * requested, or `{ images: [...] }` for multiple images
1711
2347
  */
1712
2348
  const generateImageWithGoogle = async (modelName, config, prompt, options, usageTracker = null) => {
2349
+ await requirePricedModel(modelName);
1713
2350
  const { aspectRatio = "1:1", imageSize, numberOfImages = 1, negativePrompt = "", } = options;
1714
2351
  if (!config.googleAPIKey) {
1715
2352
  throw errorHandlingHelper.create(constants.HTTP_CODES.BAD_REQUEST, "Google API key is required for Google image generation");
@@ -1823,6 +2460,7 @@ const generateImageWithGoogle = async (modelName, config, prompt, options, usage
1823
2460
  * @returns The generated image data object returned by the provider-specific function
1824
2461
  */
1825
2462
  const runPromptWithModelForImageGeneration = async (modelName, config, prompt, options = {}, usageTracker = null) => {
2463
+ await requirePricedModel(modelName);
1826
2464
  const provider = getImageModelProvider(modelName);
1827
2465
  if (!provider) {
1828
2466
  throw errorHandlingHelper.create(constants.HTTP_CODES.BAD_REQUEST, `Unable to determine provider for model: ${modelName}. Model name should start with 'gpt-image-', 'gemini-', or 'imagen-'.`);
@@ -1857,14 +2495,22 @@ const runPromptWithModelForImageGeneration = async (modelName, config, prompt, o
1857
2495
  };
1858
2496
  /**
1859
2497
  * Determines the video generation provider for a model name from its prefix.
1860
- * `veo-` maps to `"google"`, `sora-` to `"openai"`. Returns `null` for anything
1861
- * else so the caller can reject an unrecognised id rather than guess at it.
2498
+ * `gemini-omni-` maps to `"google-omni"`, `veo-` to `"google"`, `sora-` to
2499
+ * `"openai"`. Returns `null` for anything else so the caller can reject an
2500
+ * unrecognised id rather than guess at it.
2501
+ *
2502
+ * Omni and Veo are both Google, but they are different APIs: Veo is a
2503
+ * `predictLongRunning` operation, Omni an Interactions API call. Google shut
2504
+ * the Veo 3.1 previews down on the Gemini API on 2026-10-22 and named
2505
+ * `gemini-omni-1.2-flash` as their replacement.
1862
2506
  * @param modelName - The video model identifier to inspect
1863
- * @returns `"openai"`, `"google"`, or `null`
2507
+ * @returns `"openai"`, `"google"`, `"google-omni"`, or `null`
1864
2508
  */
1865
2509
  const getVideoModelProvider = (modelName) => {
1866
2510
  if (modelName.startsWith("sora-"))
1867
2511
  return "openai";
2512
+ if (modelName.startsWith("gemini-omni-"))
2513
+ return "google-omni";
1868
2514
  if (modelName.startsWith("veo-"))
1869
2515
  return "google";
1870
2516
  return null;
@@ -1900,6 +2546,7 @@ const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
1900
2546
  * @returns `{ b64_json, mimeType, seconds, model }`
1901
2547
  */
1902
2548
  const generateVideoWithGoogle = async (modelName, config, prompt, options = {}, usageTracker = null) => {
2549
+ await requirePricedModel(modelName);
1903
2550
  const { aspectRatio = "16:9", resolution = "720p", durationSeconds = 8, negativePrompt, personGeneration, pollTimeoutMs = VIDEO_POLL_TIMEOUT_MS, } = options;
1904
2551
  const ai = new GoogleGenAI({ apiKey: config.googleAPIKey });
1905
2552
  let operation = await ai.models.generateVideos({
@@ -1968,6 +2615,7 @@ const generateVideoWithGoogle = async (modelName, config, prompt, options = {},
1968
2615
  * @returns `{ b64_json, mimeType, seconds, model }`
1969
2616
  */
1970
2617
  const generateVideoWithOpenAI = async (modelName, config, prompt, options = {}, usageTracker = null) => {
2618
+ await requirePricedModel(modelName);
1971
2619
  const { size = "1280x720", durationSeconds = 8, pollTimeoutMs = VIDEO_POLL_TIMEOUT_MS, } = options;
1972
2620
  const openai = new OpenAI({ apiKey: config.openAIAPIKey });
1973
2621
  // Sora takes the duration as one of a fixed set of STRINGS ("4", "8", "12").
@@ -2003,16 +2651,169 @@ const generateVideoWithOpenAI = async (modelName, config, prompt, options = {},
2003
2651
  model: modelName,
2004
2652
  };
2005
2653
  };
2654
+ /** The Gemini API base every Omni call goes to. */
2655
+ const GEMINI_API_BASE = "https://generativelanguage.googleapis.com/v1beta";
2656
+ /**
2657
+ * Reads a failed Gemini API response as an error that keeps the HTTP status
2658
+ * and Google's own message, falling back to the status line when the body is
2659
+ * not Google's JSON (a proxy's HTML page, say).
2660
+ */
2661
+ const omniHttpError = async (modelName, response) => {
2662
+ let reason = `${response.status} ${response.statusText}`.trim();
2663
+ try {
2664
+ const body = (await response.json());
2665
+ if (body?.error?.message)
2666
+ reason = body.error.message;
2667
+ }
2668
+ catch {
2669
+ // Not JSON: the status line is all there is.
2670
+ }
2671
+ return errorHandlingHelper.create(response.status, `Video generation with "${modelName}" failed: ${reason}`);
2672
+ };
2673
+ /**
2674
+ * Generates a video with Google Gemini Omni (`gemini-omni-*`).
2675
+ *
2676
+ * Omni is the Gemini API's video model since the Veo 3.1 previews were shut
2677
+ * down there (2026-10-22). It is not `predictLongRunning`: a clip is one POST
2678
+ * to the Interactions API, which answers when the clip is done. That call is
2679
+ * made over REST because the pinned @google/genai predates Omni's video
2680
+ * response format.
2681
+ *
2682
+ * The clip is asked for with `delivery: "uri"`: Google returns inline base64
2683
+ * only up to 4 MB, and an 8-second 720p clip can be larger. A uri is a file on
2684
+ * Google's file service that has to reach ACTIVE before it can be downloaded,
2685
+ * and it needs the API key, so this waits for it and downloads the bytes here.
2686
+ * Google may still answer with inline `data`, which is used as it is.
2687
+ *
2688
+ * The key always travels in the `x-goog-api-key` header, never in a URL.
2689
+ *
2690
+ * Omni has no negative prompt or person-generation setting; those options are
2691
+ * not sent.
2692
+ *
2693
+ * @param modelName - An Omni model id, e.g. `"gemini-omni-1.2-flash"`
2694
+ * @param config - Configuration object; must include `googleAPIKey`
2695
+ * @param prompt - The text prompt describing the video
2696
+ * @param options - `aspectRatio` ("16:9" default, or "9:16"), `resolution`
2697
+ * ("720p" default), `durationSeconds` (whole seconds, 3 to 15, default 8),
2698
+ * `pollTimeoutMs` (the deadline for the whole generation)
2699
+ * @param usageTracker - Accumulator billed per second of generated video
2700
+ * @returns `{ b64_json, mimeType, seconds, model }`
2701
+ */
2702
+ const generateVideoWithOmni = async (modelName, config, prompt, options = {}, usageTracker = null) => {
2703
+ await requirePricedModel(modelName);
2704
+ const { aspectRatio = "16:9", resolution = "720p", durationSeconds = 8, pollTimeoutMs = VIDEO_POLL_TIMEOUT_MS, } = options;
2705
+ const seconds = Number(durationSeconds);
2706
+ if (!Number.isInteger(seconds) || seconds < 3 || seconds > 15) {
2707
+ throw errorHandlingHelper.create(constants.HTTP_CODES.BAD_REQUEST, `Invalid durationSeconds "${durationSeconds}" for ${modelName}. Omni takes a whole number of seconds from 3 to 15.`);
2708
+ }
2709
+ const headers = { "x-goog-api-key": config.googleAPIKey ?? "" };
2710
+ const deadline = Date.now() + pollTimeoutMs;
2711
+ const timedOut = () => errorHandlingHelper.create(constants.HTTP_CODES.INTERNAL_SERVER_ERROR, `Video generation with "${modelName}" did not finish within ${Math.round(pollTimeoutMs / 1000)} seconds.`);
2712
+ let response;
2713
+ try {
2714
+ response = await fetch(`${GEMINI_API_BASE}/interactions`, {
2715
+ method: "POST",
2716
+ headers: { "Content-Type": "application/json", ...headers },
2717
+ body: JSON.stringify({
2718
+ model: modelName,
2719
+ input: prompt,
2720
+ response_format: {
2721
+ type: "video",
2722
+ aspect_ratio: aspectRatio,
2723
+ resolution,
2724
+ duration: `${seconds}s`,
2725
+ delivery: "uri",
2726
+ },
2727
+ }),
2728
+ signal: AbortSignal.timeout(Math.max(0, pollTimeoutMs)),
2729
+ });
2730
+ }
2731
+ catch (error) {
2732
+ if (error instanceof Error && error.name === "TimeoutError")
2733
+ throw timedOut();
2734
+ throw error;
2735
+ }
2736
+ if (!response.ok)
2737
+ throw await omniHttpError(modelName, response);
2738
+ let interaction = (await response.json());
2739
+ // The POST answers when the clip is done, but an interaction still in
2740
+ // progress is polled rather than failed.
2741
+ while (interaction.status === "in_progress" && interaction.id) {
2742
+ if (Date.now() > deadline)
2743
+ throw timedOut();
2744
+ await delay(VIDEO_POLL_INTERVAL_MS);
2745
+ const poll = await fetch(`${GEMINI_API_BASE}/interactions/${encodeURIComponent(interaction.id)}`, { headers });
2746
+ if (!poll.ok)
2747
+ throw await omniHttpError(modelName, poll);
2748
+ interaction = (await poll.json());
2749
+ }
2750
+ if (interaction.status && interaction.status !== "completed") {
2751
+ const reasons = (interaction.errors ?? [])
2752
+ .map((e) => e?.message)
2753
+ .filter((m) => Boolean(m));
2754
+ throw errorHandlingHelper.create(constants.HTTP_CODES.INTERNAL_SERVER_ERROR, `Video generation with "${modelName}" ${interaction.status}: ${reasons.join("; ") || "no reason given"}`);
2755
+ }
2756
+ const outputs = (interaction.steps ?? [])
2757
+ .filter((step) => step?.type === "model_output")
2758
+ .flatMap((step) => step.content ?? []);
2759
+ const video = outputs.find((item) => item?.type === "video");
2760
+ if (!video) {
2761
+ // A refused prompt can come back as text instead of a clip: say what it said.
2762
+ const said = outputs
2763
+ .filter((item) => item?.type === "text" && item.text)
2764
+ .map((item) => item.text)
2765
+ .join(" ");
2766
+ throw errorHandlingHelper.create(constants.HTTP_CODES.INTERNAL_SERVER_ERROR, `No video was generated by ${modelName}${said ? `: ${said}` : ""}`);
2767
+ }
2768
+ let b64 = video.data;
2769
+ if (!b64) {
2770
+ if (!video.uri) {
2771
+ throw errorHandlingHelper.create(constants.HTTP_CODES.INTERNAL_SERVER_ERROR, `${modelName} returned a video with neither inline bytes nor a uri`);
2772
+ }
2773
+ // The uri is .../files/<id>:download?alt=media; the file's state is at .../files/<id>.
2774
+ const fileId = /\/files\/([^/:?]+)/.exec(video.uri)?.[1];
2775
+ if (fileId) {
2776
+ for (;;) {
2777
+ const check = await fetch(`${GEMINI_API_BASE}/files/${encodeURIComponent(fileId)}`, { headers });
2778
+ if (!check.ok)
2779
+ throw await omniHttpError(modelName, check);
2780
+ const { state } = (await check.json());
2781
+ if (state === "ACTIVE")
2782
+ break;
2783
+ if (state === "FAILED") {
2784
+ throw errorHandlingHelper.create(constants.HTTP_CODES.INTERNAL_SERVER_ERROR, `The video ${modelName} generated could not be prepared for download (file state FAILED)`);
2785
+ }
2786
+ if (Date.now() > deadline)
2787
+ throw timedOut();
2788
+ await delay(VIDEO_POLL_INTERVAL_MS);
2789
+ }
2790
+ }
2791
+ const download = await fetch(video.uri, { headers });
2792
+ if (!download.ok) {
2793
+ throw errorHandlingHelper.create(constants.HTTP_CODES.INTERNAL_SERVER_ERROR, `Downloading the generated video failed with ${download.status} ${download.statusText}`);
2794
+ }
2795
+ b64 = Buffer.from(await download.arrayBuffer()).toString("base64");
2796
+ }
2797
+ // Billed on the duration ASKED FOR, as Veo is: Omni bills the clip it rendered.
2798
+ updateVideoUsageTracker(usageTracker, modelName, seconds, config);
2799
+ return {
2800
+ b64_json: b64,
2801
+ mimeType: video.mime_type || "video/mp4",
2802
+ seconds,
2803
+ model: modelName,
2804
+ };
2805
+ };
2006
2806
  /**
2007
2807
  * Top-level entry point for AI video generation, mirroring
2008
- * `runPromptWithModelForImageGeneration`. Routes to Veo or Sora on the model
2009
- * name prefix and logs the total generation time on success.
2808
+ * `runPromptWithModelForImageGeneration`. Routes to Omni, Veo or Sora on the
2809
+ * model name prefix and logs the total generation time on success.
2010
2810
  *
2011
- * Unlike image generation this always returns bytes — never a url. Both
2012
- * providers hand back a link that requires their API key, so a url would be
2811
+ * Unlike image generation this always returns bytes — never a url. Every
2812
+ * provider hands back a link that requires its API key, so a url would be
2013
2813
  * useless to any caller that is not this process.
2014
2814
  *
2015
- * @param modelName - The video model identifier; must start with `veo-` or `sora-`
2815
+ * @param modelName - The video model identifier; must start with
2816
+ * `gemini-omni-`, `veo-` or `sora-`
2016
2817
  * @param config - Configuration object with `googleAPIKey` or `openAIAPIKey`
2017
2818
  * @param prompt - The text prompt describing the video to generate
2018
2819
  * @param options - Provider-specific generation options
@@ -2020,15 +2821,18 @@ const generateVideoWithOpenAI = async (modelName, config, prompt, options = {},
2020
2821
  * @returns `{ b64_json, mimeType, seconds, model }`
2021
2822
  */
2022
2823
  const runPromptWithModelForVideoGeneration = async (modelName, config, prompt, options = {}, usageTracker = null) => {
2824
+ await requirePricedModel(modelName);
2023
2825
  const provider = getVideoModelProvider(modelName);
2024
2826
  if (!provider) {
2025
- throw errorHandlingHelper.create(constants.HTTP_CODES.BAD_REQUEST, `Unable to determine provider for model: ${modelName}. Model name should start with 'veo-' or 'sora-'.`);
2827
+ throw errorHandlingHelper.create(constants.HTTP_CODES.BAD_REQUEST, `Unable to determine provider for model: ${modelName}. Model name should start with 'gemini-omni-', 'veo-' or 'sora-'.`);
2026
2828
  }
2027
2829
  const startTime = Date.now();
2028
2830
  try {
2029
2831
  const result = provider === "openai"
2030
2832
  ? await generateVideoWithOpenAI(modelName, config, prompt, options, usageTracker)
2031
- : await generateVideoWithGoogle(modelName, config, prompt, options, usageTracker);
2833
+ : provider === "google-omni"
2834
+ ? await generateVideoWithOmni(modelName, config, prompt, options, usageTracker)
2835
+ : await generateVideoWithGoogle(modelName, config, prompt, options, usageTracker);
2032
2836
  const duration = Date.now() - startTime;
2033
2837
  logger.log(null, logger.levels.info, `Video generation with "${modelName}" completed in ${Math.round(duration / 1000)} seconds.`);
2034
2838
  return result;
@@ -2049,6 +2853,7 @@ export default {
2049
2853
  isRetryableJsonFailure,
2050
2854
  buildAgenticRetryPrompt,
2051
2855
  parseAgenticJsonResponse,
2856
+ parseAndValidateJSONResponse,
2052
2857
  supportsNativeSchema,
2053
2858
  checkIfAIProviderConfigured,
2054
2859
  createAgent,