@librechat/agents 3.3.10 → 3.3.12

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 (211) hide show
  1. package/dist/cjs/graphs/Graph.cjs +248 -27
  2. package/dist/cjs/graphs/Graph.cjs.map +1 -1
  3. package/dist/cjs/langfuseToolOutputTracing.cjs +228 -16
  4. package/dist/cjs/langfuseToolOutputTracing.cjs.map +1 -1
  5. package/dist/cjs/llm/bedrock/index.cjs +13 -2
  6. package/dist/cjs/llm/bedrock/index.cjs.map +1 -1
  7. package/dist/cjs/llm/init.cjs +1 -1
  8. package/dist/cjs/llm/invoke.cjs +160 -43
  9. package/dist/cjs/llm/invoke.cjs.map +1 -1
  10. package/dist/cjs/llm/openai/index.cjs +190 -13
  11. package/dist/cjs/llm/openai/index.cjs.map +1 -1
  12. package/dist/cjs/llm/streamLimits.cjs +723 -0
  13. package/dist/cjs/llm/streamLimits.cjs.map +1 -0
  14. package/dist/cjs/main.cjs +12 -3
  15. package/dist/cjs/messages/core.cjs +592 -27
  16. package/dist/cjs/messages/core.cjs.map +1 -1
  17. package/dist/cjs/run.cjs +7 -3
  18. package/dist/cjs/run.cjs.map +1 -1
  19. package/dist/cjs/session/AgentSession.cjs +4 -1
  20. package/dist/cjs/session/AgentSession.cjs.map +1 -1
  21. package/dist/cjs/stream.cjs +105 -14
  22. package/dist/cjs/stream.cjs.map +1 -1
  23. package/dist/cjs/summarization/node.cjs +157 -37
  24. package/dist/cjs/summarization/node.cjs.map +1 -1
  25. package/dist/cjs/tools/BashExecutor.cjs +3 -2
  26. package/dist/cjs/tools/BashExecutor.cjs.map +1 -1
  27. package/dist/cjs/tools/CodeExecutor.cjs +4 -3
  28. package/dist/cjs/tools/CodeExecutor.cjs.map +1 -1
  29. package/dist/cjs/tools/ProgrammaticToolCalling.cjs +5 -3
  30. package/dist/cjs/tools/ProgrammaticToolCalling.cjs.map +1 -1
  31. package/dist/cjs/tools/ToolNode.cjs +77 -4
  32. package/dist/cjs/tools/ToolNode.cjs.map +1 -1
  33. package/dist/cjs/tools/ToolSearch.cjs +3 -2
  34. package/dist/cjs/tools/ToolSearch.cjs.map +1 -1
  35. package/dist/cjs/tools/search/crw-scraper.cjs +7 -1
  36. package/dist/cjs/tools/search/crw-scraper.cjs.map +1 -1
  37. package/dist/cjs/tools/search/crw-search.cjs +3 -1
  38. package/dist/cjs/tools/search/crw-search.cjs.map +1 -1
  39. package/dist/cjs/tools/search/firecrawl.cjs +7 -1
  40. package/dist/cjs/tools/search/firecrawl.cjs.map +1 -1
  41. package/dist/cjs/tools/search/keenable-scraper.cjs +7 -1
  42. package/dist/cjs/tools/search/keenable-scraper.cjs.map +1 -1
  43. package/dist/cjs/tools/search/keenable-search.cjs +3 -1
  44. package/dist/cjs/tools/search/keenable-search.cjs.map +1 -1
  45. package/dist/cjs/tools/search/rerankers.cjs +26 -8
  46. package/dist/cjs/tools/search/rerankers.cjs.map +1 -1
  47. package/dist/cjs/tools/search/search.cjs +30 -10
  48. package/dist/cjs/tools/search/search.cjs.map +1 -1
  49. package/dist/cjs/tools/search/serper-scraper.cjs +7 -1
  50. package/dist/cjs/tools/search/serper-scraper.cjs.map +1 -1
  51. package/dist/cjs/tools/search/tavily-scraper.cjs +7 -1
  52. package/dist/cjs/tools/search/tavily-scraper.cjs.map +1 -1
  53. package/dist/cjs/tools/search/tavily-search.cjs +3 -1
  54. package/dist/cjs/tools/search/tavily-search.cjs.map +1 -1
  55. package/dist/cjs/tools/search/tool.cjs +17 -3
  56. package/dist/cjs/tools/search/tool.cjs.map +1 -1
  57. package/dist/cjs/tools/subagent/SubagentExecutor.cjs +54 -3
  58. package/dist/cjs/tools/subagent/SubagentExecutor.cjs.map +1 -1
  59. package/dist/cjs/utils/index.cjs +2 -1
  60. package/dist/cjs/utils/misc.cjs +12 -0
  61. package/dist/cjs/utils/misc.cjs.map +1 -1
  62. package/dist/cjs/utils/proxy.cjs +63 -0
  63. package/dist/cjs/utils/proxy.cjs.map +1 -0
  64. package/dist/esm/graphs/Graph.mjs +247 -26
  65. package/dist/esm/graphs/Graph.mjs.map +1 -1
  66. package/dist/esm/langfuseToolOutputTracing.mjs +228 -16
  67. package/dist/esm/langfuseToolOutputTracing.mjs.map +1 -1
  68. package/dist/esm/llm/bedrock/index.mjs +13 -2
  69. package/dist/esm/llm/bedrock/index.mjs.map +1 -1
  70. package/dist/esm/llm/init.mjs +1 -1
  71. package/dist/esm/llm/invoke.mjs +160 -43
  72. package/dist/esm/llm/invoke.mjs.map +1 -1
  73. package/dist/esm/llm/openai/index.mjs +192 -15
  74. package/dist/esm/llm/openai/index.mjs.map +1 -1
  75. package/dist/esm/llm/streamLimits.mjs +704 -0
  76. package/dist/esm/llm/streamLimits.mjs.map +1 -0
  77. package/dist/esm/main.mjs +8 -6
  78. package/dist/esm/messages/core.mjs +592 -28
  79. package/dist/esm/messages/core.mjs.map +1 -1
  80. package/dist/esm/run.mjs +7 -3
  81. package/dist/esm/run.mjs.map +1 -1
  82. package/dist/esm/session/AgentSession.mjs +4 -1
  83. package/dist/esm/session/AgentSession.mjs.map +1 -1
  84. package/dist/esm/stream.mjs +105 -14
  85. package/dist/esm/stream.mjs.map +1 -1
  86. package/dist/esm/summarization/node.mjs +157 -37
  87. package/dist/esm/summarization/node.mjs.map +1 -1
  88. package/dist/esm/tools/BashExecutor.mjs +3 -2
  89. package/dist/esm/tools/BashExecutor.mjs.map +1 -1
  90. package/dist/esm/tools/CodeExecutor.mjs +4 -3
  91. package/dist/esm/tools/CodeExecutor.mjs.map +1 -1
  92. package/dist/esm/tools/ProgrammaticToolCalling.mjs +5 -3
  93. package/dist/esm/tools/ProgrammaticToolCalling.mjs.map +1 -1
  94. package/dist/esm/tools/ToolNode.mjs +77 -4
  95. package/dist/esm/tools/ToolNode.mjs.map +1 -1
  96. package/dist/esm/tools/ToolSearch.mjs +3 -2
  97. package/dist/esm/tools/ToolSearch.mjs.map +1 -1
  98. package/dist/esm/tools/search/crw-scraper.mjs +7 -1
  99. package/dist/esm/tools/search/crw-scraper.mjs.map +1 -1
  100. package/dist/esm/tools/search/crw-search.mjs +3 -1
  101. package/dist/esm/tools/search/crw-search.mjs.map +1 -1
  102. package/dist/esm/tools/search/firecrawl.mjs +7 -1
  103. package/dist/esm/tools/search/firecrawl.mjs.map +1 -1
  104. package/dist/esm/tools/search/keenable-scraper.mjs +7 -1
  105. package/dist/esm/tools/search/keenable-scraper.mjs.map +1 -1
  106. package/dist/esm/tools/search/keenable-search.mjs +3 -1
  107. package/dist/esm/tools/search/keenable-search.mjs.map +1 -1
  108. package/dist/esm/tools/search/rerankers.mjs +26 -8
  109. package/dist/esm/tools/search/rerankers.mjs.map +1 -1
  110. package/dist/esm/tools/search/search.mjs +30 -10
  111. package/dist/esm/tools/search/search.mjs.map +1 -1
  112. package/dist/esm/tools/search/serper-scraper.mjs +7 -1
  113. package/dist/esm/tools/search/serper-scraper.mjs.map +1 -1
  114. package/dist/esm/tools/search/tavily-scraper.mjs +7 -1
  115. package/dist/esm/tools/search/tavily-scraper.mjs.map +1 -1
  116. package/dist/esm/tools/search/tavily-search.mjs +3 -1
  117. package/dist/esm/tools/search/tavily-search.mjs.map +1 -1
  118. package/dist/esm/tools/search/tool.mjs +17 -3
  119. package/dist/esm/tools/search/tool.mjs.map +1 -1
  120. package/dist/esm/tools/subagent/SubagentExecutor.mjs +54 -3
  121. package/dist/esm/tools/subagent/SubagentExecutor.mjs.map +1 -1
  122. package/dist/esm/utils/index.mjs +2 -1
  123. package/dist/esm/utils/misc.mjs +12 -1
  124. package/dist/esm/utils/misc.mjs.map +1 -1
  125. package/dist/esm/utils/proxy.mjs +62 -0
  126. package/dist/esm/utils/proxy.mjs.map +1 -0
  127. package/dist/types/graphs/Graph.d.ts +53 -1
  128. package/dist/types/index.d.ts +2 -0
  129. package/dist/types/langfuseToolOutputTracing.d.ts +1 -0
  130. package/dist/types/llm/invoke.d.ts +26 -5
  131. package/dist/types/llm/openai/index.d.ts +3 -0
  132. package/dist/types/llm/streamLimits.d.ts +314 -0
  133. package/dist/types/messages/core.d.ts +11 -6
  134. package/dist/types/run.d.ts +1 -0
  135. package/dist/types/summarization/node.d.ts +27 -2
  136. package/dist/types/tools/BashExecutor.d.ts +2 -2
  137. package/dist/types/tools/CodeExecutor.d.ts +3 -3
  138. package/dist/types/tools/ToolNode.d.ts +11 -1
  139. package/dist/types/tools/search/crw-scraper.d.ts +2 -0
  140. package/dist/types/tools/search/firecrawl.d.ts +2 -0
  141. package/dist/types/tools/search/keenable-scraper.d.ts +2 -0
  142. package/dist/types/tools/search/rerankers.d.ts +9 -5
  143. package/dist/types/tools/search/serper-scraper.d.ts +2 -0
  144. package/dist/types/tools/search/tavily-scraper.d.ts +2 -0
  145. package/dist/types/tools/search/types.d.ts +28 -33
  146. package/dist/types/tools/subagent/SubagentExecutor.d.ts +44 -0
  147. package/dist/types/types/graph.d.ts +7 -1
  148. package/dist/types/types/run.d.ts +46 -1
  149. package/dist/types/types/tools.d.ts +21 -0
  150. package/dist/types/utils/index.d.ts +1 -0
  151. package/dist/types/utils/misc.d.ts +7 -0
  152. package/dist/types/utils/proxy.d.ts +31 -0
  153. package/package.json +2 -1
  154. package/src/__tests__/stream.eagerArgsDivergence.test.ts +158 -0
  155. package/src/__tests__/stream.eagerEventExecution.test.ts +1 -0
  156. package/src/__tests__/stream.streamLimits.test.ts +1982 -0
  157. package/src/graphs/Graph.ts +302 -27
  158. package/src/graphs/__tests__/Graph.breakerLifecycle.test.ts +234 -0
  159. package/src/index.ts +11 -0
  160. package/src/langfuseToolOutputTracing.ts +410 -14
  161. package/src/llm/bedrock/index.ts +22 -2
  162. package/src/llm/custom-chat-models.smoke.test.ts +747 -0
  163. package/src/llm/invoke.streamLimits.test.ts +142 -0
  164. package/src/llm/invoke.test.ts +187 -1
  165. package/src/llm/invoke.ts +231 -43
  166. package/src/llm/openai/cacheWriteTokens.test.ts +112 -0
  167. package/src/llm/openai/index.ts +348 -31
  168. package/src/llm/openai/llm.spec.ts +107 -6
  169. package/src/llm/streamLimits.test.ts +450 -0
  170. package/src/llm/streamLimits.ts +1158 -0
  171. package/src/messages/core.ts +1290 -42
  172. package/src/messages/formatAgentMessages.test.ts +2623 -0
  173. package/src/run.ts +4 -0
  174. package/src/session/AgentSession.ts +5 -0
  175. package/src/specs/langfuse-tool-output-tracing.test.ts +887 -0
  176. package/src/specs/preemptSeal.test.ts +374 -5
  177. package/src/stream.ts +141 -6
  178. package/src/summarization/__tests__/node.test.ts +269 -0
  179. package/src/summarization/chunkHandler.test.ts +196 -0
  180. package/src/summarization/node.ts +203 -6
  181. package/src/tools/BashExecutor.ts +4 -3
  182. package/src/tools/CodeExecutor.ts +5 -4
  183. package/src/tools/ProgrammaticToolCalling.ts +7 -5
  184. package/src/tools/ToolNode.ts +109 -6
  185. package/src/tools/ToolSearch.ts +4 -3
  186. package/src/tools/__tests__/BashExecutor.test.ts +2 -2
  187. package/src/tools/__tests__/ProgrammaticToolCalling.test.ts +2 -4
  188. package/src/tools/__tests__/SubagentExecutor.test.ts +126 -0
  189. package/src/tools/__tests__/ToolNode.breakerSignal.test.ts +389 -0
  190. package/src/tools/__tests__/ToolNode.streamLimits.test.ts +69 -0
  191. package/src/tools/search/crw-scraper.ts +6 -0
  192. package/src/tools/search/crw-search.ts +6 -1
  193. package/src/tools/search/firecrawl.ts +6 -0
  194. package/src/tools/search/http-agent.test.ts +133 -0
  195. package/src/tools/search/keenable-scraper.ts +6 -0
  196. package/src/tools/search/keenable-search.ts +6 -1
  197. package/src/tools/search/rerankers.ts +36 -10
  198. package/src/tools/search/search.ts +29 -11
  199. package/src/tools/search/serper-scraper.ts +6 -0
  200. package/src/tools/search/tavily-scraper.ts +6 -0
  201. package/src/tools/search/tavily-search.ts +2 -0
  202. package/src/tools/search/tool.ts +16 -0
  203. package/src/tools/search/types.ts +31 -33
  204. package/src/tools/subagent/SubagentExecutor.ts +96 -3
  205. package/src/types/graph.ts +7 -0
  206. package/src/types/run.ts +49 -1
  207. package/src/types/tools.ts +21 -0
  208. package/src/utils/index.ts +1 -0
  209. package/src/utils/misc.ts +19 -0
  210. package/src/utils/proxy.test.ts +176 -0
  211. package/src/utils/proxy.ts +93 -0
@@ -0,0 +1 @@
1
+ {"version":3,"file":"streamLimits.mjs","names":[],"sources":["../../../src/llm/streamLimits.ts"],"sourcesContent":["// src/llm/streamLimits.ts\nimport type { ToolCallChunk } from '@langchain/core/messages/tool';\nimport type * as t from '@/types';\nimport { getStreamedToolCallSeal } from '@/tools/streamedToolCallSeals';\n\n/**\n * Circuit breakers for pathological model streams.\n *\n * A malformed generation can stream a single tool call's arguments for many\n * minutes at the provider's full token rate while the arguments never become\n * executable (observed live: one 149,923-char SQL argument streamed for 26\n * minutes before the 64k output-token ceiling finally ended the run). These\n * guards fail fast instead: when a limit trips, the stream handler throws\n * `StreamLimitExceededError` out of the run's `streamEvents` loop, which\n * tears down the in-flight provider request where it stands (see the\n * mid-flight halt notes in `Run.processStream`: leaving the loop cancels the\n * reader and langgraph aborts the model call).\n */\n\n/** Default cap on a single streamed tool call's cumulative argument bytes (64 KiB). */\nexport const DEFAULT_MAX_TOOL_CALL_ARG_BYTES = 65_536;\n\n/** Limits normalized by {@link resolveStreamLimits}; `0` uniformly means disabled. */\nexport interface ResolvedStreamLimits {\n maxToolCallArgBytes: number;\n /** Per-tool overrides of the byte cap, keyed by model-facing tool name. */\n maxToolCallArgBytesByTool?: Readonly<Record<string, number>>;\n maxDeltaEventsPerTurn: number;\n /** Precomputed once: whether ANY argument byte limit can fire. False when\n * the global cap is disabled and every per-tool entry is a zero-valued\n * disable — accounting must not allocate for guards that judge nothing. */\n hasEnforceableToolCallArgLimit: boolean;\n}\n\n/** Cumulative streamed argument bytes for one in-flight tool call. */\nexport interface StreamedToolCallArgTally {\n bytes: number;\n name?: string;\n /** The graph's breaker epoch when this tally was created. Entries from\n * the epoch that is ending survive one `resetValues` sweep, so producer\n * loops of straggling attempts — which are not behind the consumer-only\n * epoch gate — stay on their original budgets instead of receiving a\n * fresh allowance at every run start. */\n epoch?: number;\n /** Every tally-map key this tally is registered under: its primary key\n * (which can migrate through identifier transitions), the batch-position\n * fallback for id-bearing chunks, and the id for chunks carrying both\n * identifiers. Release deletes all of them — a call sealed through one\n * identity must not leave entries behind under another. */\n keys?: string[];\n /**\n * True when the previous chunk ended on an unpaired UTF-16 high surrogate.\n * Counting each half of a split surrogate pair alone yields 3 bytes per\n * half (the replacement-character encoding) versus 4 for the pair, so the\n * next chunk starting with the low surrogate reconciles by subtracting 2.\n */\n pendingHighSurrogate?: boolean;\n}\n\n/** Immutable snapshot of one run's breaker identity. Captured at\n * model/event/tool-batch entry and revalidated by REFERENCE after awaits —\n * one identity comparison proves no reset interleaved. */\nexport interface RunBreakerScope {\n readonly epoch: number;\n readonly controller: AbortController;\n}\n\n/** Streamed chunk events counted against one generation's event cap. */\nexport interface StreamDeltaEventTally {\n count: number;\n /** Creation-epoch tag, same grace semantics as\n * {@link StreamedToolCallArgTally.epoch}. */\n epoch?: number;\n}\n\n/**\n * The graph-owned state the guards read and write. Structural on purpose:\n * handler-level tests stub graphs with plain objects, and the guards lazily\n * create the tally maps so partial stubs need no extra setup.\n */\nexport interface StreamLimitState {\n streamLimits?: ResolvedStreamLimits;\n streamedToolCallArgTallies?: Map<string, StreamedToolCallArgTally>;\n streamDeltaEventCounts?: Map<string, StreamDeltaEventTally>;\n /** The graph's live breaker epoch; new accounting entries are tagged with\n * it so `resetValues` can sweep by age instead of clearing outright. */\n breakerEpoch?: number;\n /** Generation keys of model attempts still in flight. Each attempt leases\n * its generation at entry and releases it (with its accounting entries)\n * from its `finally`, so retention follows ATTEMPT LIFETIME — a\n * cancellation-ignoring straggler keeps its original budget no matter how\n * many runs start and reset while it drains. */\n activeStreamLimitGenerations?: Set<string>;\n /** Per-chunk-object, per-generation charge balance: producer visits\n * increment, consumer (handler echo) visits decrement, and a visit only\n * charges when the other side has not pre-charged the same emission.\n * Count-balancing rather than a lifetime set, because a streaming model\n * may mutate and re-yield the same chunk object; scoped by generation so\n * parallel generations sharing one reused object cannot cancel each\n * other's charges. */\n streamLimitChargeCredits?: WeakMap<object, Map<string, number>>;\n}\n\nfunction resolveLimit(value: number | undefined, fallback: number): number {\n if (value == null || Number.isNaN(value)) {\n return fallback;\n }\n if (!Number.isFinite(value)) {\n return 0;\n }\n const whole = Math.floor(value);\n return whole > 0 ? whole : 0;\n}\n\n/**\n * Normalizes host-supplied limits once at graph construction. `undefined`\n * applies the default for each guard (the tool-argument byte cap is ON by\n * default, the per-turn event cap is opt-in), `0` and negative values\n * disable a guard, `Infinity` means \"no limit\" and also disables, and `NaN`\n * falls back to the default.\n */\nexport function resolveStreamLimits(\n limits?: t.StreamLimits\n): ResolvedStreamLimits {\n const maxToolCallArgBytes = resolveLimit(\n limits?.maxToolCallArgBytes,\n DEFAULT_MAX_TOOL_CALL_ARG_BYTES\n );\n let maxToolCallArgBytesByTool: Record<string, number> | undefined;\n if (limits?.maxToolCallArgBytesByTool != null) {\n for (const [name, value] of Object.entries(\n limits.maxToolCallArgBytesByTool\n )) {\n /** An unusable entry (NaN) falls back to the global cap by omission,\n * matching how the global field treats NaN. */\n if (name === '' || Number.isNaN(value)) {\n continue;\n }\n /** Prototype-free: bracket-assigning a `__proto__` tool name into a\n * plain object invokes the prototype setter instead of creating an own\n * property, silently dropping that tool's configured override. */\n maxToolCallArgBytesByTool ??= Object.create(null) as Record<\n string,\n number\n >;\n maxToolCallArgBytesByTool[name] = resolveLimit(\n value,\n maxToolCallArgBytes\n );\n }\n }\n const hasEnforceableToolCallArgLimit =\n maxToolCallArgBytes > 0 ||\n (maxToolCallArgBytesByTool != null &&\n Object.values(maxToolCallArgBytesByTool).some((value) => value > 0));\n return {\n maxToolCallArgBytes,\n ...(maxToolCallArgBytesByTool != null && { maxToolCallArgBytesByTool }),\n maxDeltaEventsPerTurn: resolveLimit(limits?.maxDeltaEventsPerTurn, 0),\n hasEnforceableToolCallArgLimit,\n };\n}\n\nconst DEFAULT_RESOLVED_LIMITS: ResolvedStreamLimits = resolveStreamLimits();\n\nexport type StreamLimitKind = 'tool_call_args' | 'delta_events';\n\nfunction buildLimitMessage(\n kind: StreamLimitKind,\n limit: number,\n toolName?: string\n): string {\n if (kind === 'tool_call_args') {\n const named =\n toolName != null && toolName !== '' ? ` (tool call: ${toolName})` : '';\n return (\n `Streamed tool call arguments exceeded the ${limit}-byte safety limit${named}. ` +\n 'The generation was aborted mid-stream: arguments growing this large without completing ' +\n 'usually indicate a runaway or malformed tool call. Raise \\'maxToolCallArgBytes\\' (or the ' +\n 'tool\\'s \\'maxToolCallArgBytesByTool\\' entry) if your tools legitimately need larger arguments.'\n );\n }\n return (\n `Model stream exceeded the ${limit}-event safety limit for a single generation turn. ` +\n 'The generation was aborted mid-stream: this usually indicates a looping or duplicated ' +\n 'provider stream. Raise \\'maxDeltaEventsPerTurn\\' if legitimate generations need more stream events.'\n );\n}\n\n/**\n * Raised when a {@link t.StreamLimits} guard trips. Thrown from inside the\n * run's `streamEvents` loop, so the in-flight provider request is torn down\n * and `processStream` rejects with this error.\n */\nexport class StreamLimitExceededError extends Error {\n readonly kind: StreamLimitKind;\n readonly limit: number;\n readonly observed: number;\n readonly toolName?: string;\n\n constructor({\n kind,\n limit,\n observed,\n toolName,\n }: {\n kind: StreamLimitKind;\n limit: number;\n observed: number;\n toolName?: string;\n }) {\n super(buildLimitMessage(kind, limit, toolName));\n this.name = 'StreamLimitExceededError';\n this.kind = kind;\n this.limit = limit;\n this.observed = observed;\n this.toolName = toolName;\n }\n}\n\n/**\n * Identity of one model generation, derived from langgraph's node-execution\n * metadata. Deliberately NOT `Graph.getStepKey()`: the step key forks within\n * a single generation on reasoning transitions (`'reasoning'` /\n * `post-reasoning-<n>` suffixes in `getKeyList`) and on mid-turn server-tool\n * results (`invokedToolIds` count), which would hand a fresh budget to each\n * segment. One agent-node execution is one superstep, so\n * `checkpoint_ns + node + step` stays stable for the whole generation and\n * distinguishes parallel agents in the same superstep.\n *\n * The attempt stamp scopes attempts within one node execution:\n * `attemptInvoke` is the single funnel for primary, fallback, and\n * summarization model calls and stamps {@link STREAM_LIMIT_ATTEMPT_KEY}\n * with a unique sequence number into each attempt's callback metadata. A\n * fallback's chunks therefore key separately from the failed primary's,\n * even for two fallbacks configured with the same provider and model name,\n * and even when the decoupled `streamEvents` reader drains a failed\n * attempt's buffered chunks late. Those late chunks land in their own\n * attempt's bucket instead of polluting the next one's.\n */\nexport function resolveGenerationKey(\n metadata: Record<string, unknown> | undefined\n): string {\n if (metadata == null) {\n return '';\n }\n const checkpointNs = metadata.langgraph_checkpoint_ns ?? '';\n const node = metadata.langgraph_node ?? '';\n const step = metadata.langgraph_step ?? '';\n const attempt = metadata[STREAM_LIMIT_ATTEMPT_KEY] ?? '';\n return `${checkpointNs}|${node}|${step}|${attempt}`;\n}\n\n/**\n * Metadata key carrying the unique per-model-attempt sequence number that\n * `attemptInvoke` stamps into every attempt's callback metadata. Part of\n * the generation key so budgets never alias across attempts.\n */\nexport const STREAM_LIMIT_ATTEMPT_KEY = 'lc_stream_limit_attempt';\n\n/**\n * Event-metadata marker for a chunk the SDK re-dispatches inline after\n * transforming it (`attemptInvoke`'s OpenRouter final-reasoning replay). The\n * original wire chunk still reaches the handler through `streamEvents` and\n * is counted there, so the re-dispatch must not consume a second\n * event-budget slot.\n */\nexport const STREAM_LIMIT_REDISPATCH_KEY = 'lc_stream_limit_redispatch';\n\n/**\n * Metadata key carrying the graph's breaker epoch at the time a model\n * attempt started. The stream handler trips the shared breaker only when\n * the event's epoch matches the live controller's — a straggling chunk from\n * a failed run that outlived `resetValues()` must fail its own (dead) run,\n * not abort the controller now serving the next one. A primitive rather\n * than the controller itself so attempt metadata stays serialization-safe\n * for tracing.\n */\nexport const STREAM_LIMIT_EPOCH_KEY = 'lc_stream_limit_epoch';\n\n/**\n * Configurable key carrying the tool batch's entry-captured\n * {@link RunBreakerScope} to tools that spawn their own runs (subagents).\n * Captured BEFORE PreToolUse hooks, so a reset during a hook cannot rebind\n * the spawned child to the new run's controller. Stripped from host-facing\n * batch requests and from child-graph configurables.\n */\nexport const RUN_BREAKER_SCOPE_CONFIG_KEY = 'lc_run_breaker_scope';\n\n/**\n * True when the event's `single` seal marks this chunk's own call as\n * complete. On the OpenAI Responses adapter the sealing chunk RESTATES the\n * full argument string (`response.function_call_arguments.done`), so summing\n * it would double-count every legitimate call; on Bedrock Converse the\n * sealing chunk carries empty args. Either way the call is finished: its\n * tally is replaced by the sealing chunk's own bytes, checked, and released.\n */\nfunction sealsChunk(\n seal: ReturnType<typeof getStreamedToolCallSeal>,\n chunk: ToolCallChunk\n): boolean {\n if (seal == null || seal.kind !== 'single') {\n return false;\n }\n /** Either supplied identifier agreeing is sufficient (matching the\n * eager-call seal handling in stream.ts): a mismatch on one identifier\n * must not veto a match on the other, or an OpenAI-style full-argument\n * restatement gets ADDED to the tally instead of replacing it, and an\n * empty seal leaves the tally unreleased. */\n if (\n seal.index != null &&\n chunk.index != null &&\n seal.index === chunk.index\n ) {\n return true;\n }\n const sealId = seal.id != null && seal.id !== '' ? seal.id : undefined;\n return sealId != null && sealId === chunkCallId(chunk);\n}\n\nfunction chunkToolName(chunk: ToolCallChunk): string | undefined {\n return chunk.name != null && chunk.name !== '' ? chunk.name : undefined;\n}\n\n/** The chunk's id with empty-string placeholders treated as absent —\n * OpenAI-compatible adapters emit `id: ''` on continuation deltas, and a\n * shared placeholder must not merge independent calls onto one identity\n * (mirrors `getEagerToolChunkKey`). */\nfunction chunkCallId(chunk: ToolCallChunk): string | undefined {\n return chunk.id != null && chunk.id !== '' ? chunk.id : undefined;\n}\n\nfunction isHighSurrogate(code: number): boolean {\n return code >= 0xd800 && code <= 0xdbff;\n}\n\nfunction isLowSurrogate(code: number): boolean {\n return code >= 0xdc00 && code <= 0xdfff;\n}\n\n/**\n * Accumulates the UTF-8 byte size of streamed tool-call argument chunks per\n * in-flight tool call and throws once a single call's cumulative bytes\n * exceed `maxToolCallArgBytes`. Runs once per streamed chunk event, before\n * complete tool calls are dispatched or eagerly executed and before chunks\n * are recorded, so a tripped limit stops the run without dispatching the\n * offending call.\n *\n * Calls are keyed by generation and chunk `index`, falling back to the\n * chunk `id` and then to the chunk's position within the event's batch when\n * a provider identifies chunks by neither (Google emits complete parallel\n * calls with optional ids and no index). A `kind: 'all'` arrival seal marks\n * every chunk in the event as its own complete call, so those are checked\n * standalone and never share a budget; a matching `kind: 'single'` seal\n * replaces the call's tally with the sealing chunk's own bytes (the OpenAI\n * Responses done-chunk restates the full argument string) and releases it.\n */\nexport function enforceStreamedToolCallArgLimit({\n graph,\n metadata,\n toolCallChunks,\n responseMetadata,\n parsedToolCalls,\n}: {\n graph: StreamLimitState;\n metadata: Record<string, unknown> | undefined;\n toolCallChunks: ToolCallChunk[];\n responseMetadata?: Record<string, unknown>;\n /** Complete parsed calls from the same event, used to name anonymous raw\n * chunks so per-tool overrides are honored before the global cap trips. */\n parsedToolCalls?: CompleteToolCallLike[];\n}): void {\n const resolved = graph.streamLimits ?? DEFAULT_RESOLVED_LIMITS;\n const globalLimit = resolved.maxToolCallArgBytes;\n const byTool = resolved.maxToolCallArgBytesByTool;\n if (!resolved.hasEnforceableToolCallArgLimit) {\n return;\n }\n /** An inline re-dispatch of a transformed chunk (OpenRouter final-reasoning\n * replay) duplicates tool-call chunks the original `streamEvents` event\n * already charged — the original always survives the content-specific\n * skips when it carries tool calls, so counting the marked copy would\n * double every legitimate argument byte. */\n if (metadata?.[STREAM_LIMIT_REDISPATCH_KEY] === true) {\n return;\n }\n const tallies: Map<string, StreamedToolCallArgTally> =\n (graph.streamedToolCallArgTallies ??= new Map<\n string,\n StreamedToolCallArgTally\n >());\n const generationKey = resolveGenerationKey(metadata);\n const seal = getStreamedToolCallSeal(responseMetadata);\n /** The complete call in this event sharing the chunk's id — the strongest\n * name evidence: adapters may stream raw names in FRAGMENTS, and an\n * id-correlated complete call states the full name outright. */\n const correlateParsedNameById = (id: string): string | undefined => {\n if (parsedToolCalls == null) {\n return undefined;\n }\n for (const parsed of parsedToolCalls) {\n if (parsed.id === id && parsed.name != null && parsed.name !== '') {\n return parsed.name;\n }\n }\n return undefined;\n };\n const generationPrefix = `${generationKey}:`;\n const getLiveGenerationTallies = (): StreamedToolCallArgTally[] => {\n const live = new Set<StreamedToolCallArgTally>();\n for (const [tallyKey, tally] of tallies) {\n if (tallyKey.startsWith(generationPrefix)) {\n live.add(tally);\n }\n }\n return [...live];\n };\n const resolveChunkName = (chunk: ToolCallChunk): string | undefined => {\n const chunkId = chunkCallId(chunk);\n const correlated =\n chunkId != null ? correlateParsedNameById(chunkId) : undefined;\n if (correlated != null) {\n return correlated;\n }\n const name = chunkToolName(chunk);\n if (name != null || parsedToolCalls == null || chunkId != null) {\n return name;\n }\n /** No id to correlate on; positional association is unambiguous only\n * when the event carries exactly one raw chunk AND one parsed call —\n * with several id-less raw chunks in flight, handing one parsed call's\n * name (and its override) to all of them would let an unrelated\n * still-partial call bypass the global cap. */\n if (parsedToolCalls.length === 1 && toolCallChunks.length === 1) {\n const only = parsedToolCalls[0];\n if (only.name != null && only.name !== '') {\n return only.name;\n }\n }\n return undefined;\n };\n const enforceTallyLimit = (target: StreamedToolCallArgTally): void => {\n const tallyLimit =\n byTool != null &&\n target.name != null &&\n Object.hasOwn(byTool, target.name)\n ? byTool[target.name]\n : globalLimit;\n if (tallyLimit > 0 && target.bytes > tallyLimit) {\n throw new StreamLimitExceededError({\n kind: 'tool_call_args',\n limit: tallyLimit,\n observed: target.bytes,\n toolName: target.name,\n });\n }\n };\n for (let i = 0; i < toolCallChunks.length; i++) {\n const chunk = toolCallChunks[i];\n const args = chunk.args;\n const hasArgs = typeof args === 'string' && args !== '';\n if (seal?.kind === 'all') {\n if (!hasArgs) {\n continue;\n }\n const bytes = Buffer.byteLength(args, 'utf8');\n const sealedName = resolveChunkName(chunk);\n const limit =\n byTool != null && sealedName != null && Object.hasOwn(byTool, sealedName)\n ? byTool[sealedName]\n : globalLimit;\n if (limit > 0 && bytes > limit) {\n throw new StreamLimitExceededError({\n kind: 'tool_call_args',\n limit,\n observed: bytes,\n toolName: sealedName,\n });\n }\n continue;\n }\n /** Keys are namespaced by identity kind (`i:` index, `c:` id, `#`\n * batch position) so an index and a string id with the same textual\n * value — index 0 and id \"0\" — cannot alias distinct calls onto one\n * tally. Empty-string ids are placeholders, not identities. */\n const chunkId = chunkCallId(chunk);\n const sealed = sealsChunk(seal, chunk);\n /** Applies this chunk's name contribution and reports whether the\n * effective name changed. Adapters may stream the name in FRAGMENTS\n * (\"create_\" then \"file\"), so unsealed fragments append — matching\n * langchain's own tool-call-chunk merge — while a sealing chunk's name\n * is a full restatement and replaces, mirroring how sealed args replace\n * the tally bytes. An id-correlated complete call in the same event\n * outranks both; positional parsed-call correlation fills in only when\n * the chunk carries no fragment. */\n const applyChunkName = (target: StreamedToolCallArgTally): boolean => {\n const correlated =\n chunkId != null ? correlateParsedNameById(chunkId) : undefined;\n const fragment = chunkToolName(chunk);\n let next = target.name;\n if (correlated != null) {\n /** An id-correlated complete call wins over fragment accumulation:\n * a raw name like \"create_\" must not hide the \"create_file\"\n * override behind the global cap. */\n next = correlated;\n } else if (fragment != null) {\n if (sealed || target.name == null) {\n next = fragment;\n } else if (fragment !== target.name) {\n /** A fragment identical to the accumulated name is a repeated\n * full-name delta (a common provider shape) and is a no-op; a\n * differing fragment is a continuation and appends. */\n next = target.name + fragment;\n }\n } else if (target.name == null) {\n next = resolveChunkName(chunk);\n }\n if (next === target.name) {\n return false;\n }\n target.name = next;\n return true;\n };\n /** A single identifier-less event while calls are live is a sparse\n * parallel continuation: its position is relative to this event, not to\n * the original batch, so `#0` cannot identify which call it belongs to.\n * With exactly one live call the association is unambiguous — charge\n * that tally, keeping its budget continuous (a fresh `#0` tally here\n * would RESET the sole remaining call's byte budget). With several,\n * charge every live candidate. Each tally is judged under its OWN\n * name-specific limit: comparing only against the global cap would let\n * a call with a lower per-tool override stream past it indefinitely\n * while its chunks stay anonymous. */\n if (\n chunk.index == null &&\n chunkId == null &&\n toolCallChunks.length === 1\n ) {\n const liveTallies = getLiveGenerationTallies();\n if (liveTallies.length > 0) {\n if (liveTallies.length === 1 && applyChunkName(liveTallies[0])) {\n /** A late name can select a lower override than the limit under\n * which prior bytes were accepted, so re-judge before charging\n * this continuation. */\n enforceTallyLimit(liveTallies[0]);\n }\n if (hasArgs) {\n const argBytes = Buffer.byteLength(args, 'utf8');\n for (const liveTally of liveTallies) {\n const reconcilesSplitPair =\n liveTally.pendingHighSurrogate === true &&\n isLowSurrogate(args.charCodeAt(0));\n liveTally.bytes += reconcilesSplitPair ? argBytes - 2 : argBytes;\n liveTally.pendingHighSurrogate = isHighSurrogate(\n args.charCodeAt(args.length - 1)\n );\n enforceTallyLimit(liveTally);\n }\n }\n continue;\n }\n }\n let key: string;\n if (chunk.index != null) {\n key = `${generationKey}:i:${chunk.index}`;\n } else if (chunkId != null) {\n key = `${generationKey}:c:${chunkId}`;\n } else {\n key = `${generationKey}:#${i}`;\n }\n /** Batch position is a stable identity only when the event carries a\n * single chunk: sparse parallel events reuse position 0 for whichever\n * call happens to continue, and a position alias would hand one call's\n * tally — and its per-tool override — to another live call's deltas. */\n const positionAliasSafe = toolCallChunks.length === 1;\n /** Secondary keys this call is also reachable under, so a later delta\n * that drops one or both identifiers still lands on the same tally:\n * id-bearing chunks register the batch-position fallback (single-chunk\n * events only), and chunks carrying both identifiers additionally\n * register the id. */\n const aliasCandidates: string[] = [];\n if (chunkId != null) {\n if (positionAliasSafe) {\n aliasCandidates.push(`${generationKey}:#${i}`);\n }\n if (chunk.index != null) {\n aliasCandidates.push(`${generationKey}:c:${chunkId}`);\n }\n }\n let tally = tallies.get(key);\n /** A later delta can also ADD an identifier, changing the primary key;\n * adopt the call's existing tally through a stronger prior identity\n * before allocating. An index maps to that call's original batch\n * position, never this sparse event's position. A newly arrived id can\n * adopt a position only when one anonymous tally is live; with several,\n * positional association is ambiguous. The old identity is recorded as\n * an alias and released together with the rest. */\n if (tally == null) {\n const adoptionCandidates: string[] = [];\n if (chunkId != null) {\n adoptionCandidates.push(`${generationKey}:c:${chunkId}`);\n }\n if (chunk.index != null) {\n /** An index is stable across sparse events; the loop position is\n * merely this event's position and may be 0 for call index 1. */\n const indexedPositionKey = `${generationKey}:#${chunk.index}`;\n adoptionCandidates.push(indexedPositionKey);\n /** A single anonymous call may first appear alone at event position\n * #0 and reveal a nonzero provider index only later. Exact indexed\n * position wins above; when it does not exist, one anonymous tally\n * is still an unambiguous fallback. */\n const liveTallies = getLiveGenerationTallies();\n const soleTally = liveTallies.length === 1 ? liveTallies[0] : undefined;\n if (\n soleTally?.keys?.[0]?.startsWith(`${generationPrefix}#`) === true\n ) {\n const anonymousKey = soleTally.keys[0];\n if (anonymousKey !== indexedPositionKey) {\n adoptionCandidates.push(anonymousKey);\n }\n }\n } else if (chunkId != null) {\n const anonymousTallies = getLiveGenerationTallies().filter(\n (liveTally: StreamedToolCallArgTally) =>\n liveTally.keys?.[0]?.startsWith(`${generationPrefix}#`) === true\n );\n if (anonymousTallies.length === 1) {\n const anonymousKey = anonymousTallies[0].keys?.[0];\n if (anonymousKey != null) {\n adoptionCandidates.push(anonymousKey);\n }\n }\n }\n for (const adoptionKey of adoptionCandidates) {\n if (adoptionKey === key) {\n continue;\n }\n const existing = tallies.get(adoptionKey);\n if (existing == null) {\n continue;\n }\n /** A position entry may only be adopted when the tally was CREATED\n * anonymous (its first key is the position): id-bearing calls also\n * alias their position, and adopting a live parallel call's alias\n * would merge distinct budgets. */\n if (\n adoptionKey.includes(':#') &&\n existing.keys?.[0] !== adoptionKey\n ) {\n continue;\n }\n tally = existing;\n tallies.set(key, existing);\n if (existing.keys?.includes(adoptionKey) !== true) {\n (existing.keys ??= []).push(adoptionKey);\n }\n if (!existing.keys.includes(key)) {\n existing.keys.push(key);\n }\n break;\n }\n }\n const registerAliasKeys = (\n target: StreamedToolCallArgTally,\n candidates: string[]\n ): void => {\n for (const aliasKey of candidates) {\n const currentOwner = tallies.get(aliasKey);\n if (currentOwner === target) {\n continue;\n }\n /** Parallel calls can contend for one batch position, so the newest\n * live call takes the alias over and the previous owner is disowned\n * — its seal must not delete a key it no longer holds. */\n if (currentOwner?.keys != null) {\n const remaining = currentOwner.keys.filter(\n (ownedKey: string) => ownedKey !== aliasKey\n );\n currentOwner.keys = remaining.length > 0 ? remaining : undefined;\n }\n tallies.set(aliasKey, target);\n (target.keys ??= []).push(aliasKey);\n }\n };\n const registerAliases = (target: StreamedToolCallArgTally): void => {\n registerAliasKeys(target, aliasCandidates);\n };\n /** Index-only calls register their batch position ONCE, at creation:\n * later deltas that drop the index then land on the same tally, while\n * the per-delta hot path (indexed id-less deltas) stays free of alias\n * work. */\n const registerCreationPositionAlias = (\n target: StreamedToolCallArgTally\n ): void => {\n if (chunkId != null || chunk.index == null || sealed) {\n return;\n }\n if (!positionAliasSafe) {\n return;\n }\n registerAliasKeys(target, [`${generationKey}:#${i}`]);\n };\n const releaseTally = (target: StreamedToolCallArgTally): void => {\n tallies.delete(key);\n if (target.keys == null) {\n return;\n }\n for (const aliasKey of target.keys) {\n if (tallies.get(aliasKey) === target) {\n tallies.delete(aliasKey);\n }\n }\n };\n if (!hasArgs) {\n if (tally == null) {\n if (!sealed) {\n tally = {\n bytes: 0,\n name: resolveChunkName(chunk),\n keys: [key],\n epoch: graph.breakerEpoch,\n };\n tallies.set(key, tally);\n registerAliases(tally);\n registerCreationPositionAlias(tally);\n }\n continue;\n }\n /** A sealing chunk is about to release this tally; taking the position\n * alias here would steal it from a still-live parallel call. */\n if (!sealed) {\n registerAliases(tally);\n }\n if (applyChunkName(tally)) {\n /** Bytes tallied under the previous (or absent) name were held\n * against that name's limit; a changed name — late arrival or a\n * completed fragment — must re-judge them, including on a sealing\n * chunk about to release the tally. */\n enforceTallyLimit(tally);\n }\n if (sealed) {\n releaseTally(tally);\n }\n continue;\n }\n if (tally == null) {\n tally = { bytes: 0, keys: [key], epoch: graph.breakerEpoch };\n tallies.set(key, tally);\n registerCreationPositionAlias(tally);\n }\n if (!sealed) {\n registerAliases(tally);\n }\n applyChunkName(tally);\n const argBytes = Buffer.byteLength(args, 'utf8');\n if (sealed) {\n tally.bytes = argBytes;\n } else {\n const reconcilesSplitPair =\n tally.pendingHighSurrogate === true &&\n isLowSurrogate(args.charCodeAt(0));\n tally.bytes += reconcilesSplitPair ? argBytes - 2 : argBytes;\n }\n tally.pendingHighSurrogate =\n !sealed && isHighSurrogate(args.charCodeAt(args.length - 1));\n const toolName = tally.name ?? resolveChunkName(chunk);\n const limit =\n byTool != null && toolName != null && Object.hasOwn(byTool, toolName)\n ? byTool[toolName]\n : globalLimit;\n if (limit > 0 && tally.bytes > limit) {\n throw new StreamLimitExceededError({\n kind: 'tool_call_args',\n limit,\n observed: tally.bytes,\n toolName,\n });\n }\n if (sealed) {\n releaseTally(tally);\n }\n }\n}\n\n/** Structural subset of a complete parsed tool call. */\ninterface CompleteToolCallLike {\n id?: string;\n name?: string;\n args?: unknown;\n}\n\n/**\n * Standalone byte check for complete parsed tool calls that arrive without a\n * raw chunk representation: a streaming custom or OpenAI-compatible\n * `ChatModel` can yield fully parsed `tool_calls` with empty\n * `tool_call_chunks`, which would otherwise dispatch without consuming any\n * byte budget. Complete calls are self-contained, so each is judged\n * standalone without tallying.\n */\nexport function enforceCompleteToolCallArgLimit({\n graph,\n metadata,\n toolCalls,\n}: {\n graph: StreamLimitState;\n metadata: Record<string, unknown> | undefined;\n toolCalls: CompleteToolCallLike[];\n}): void {\n const resolved = graph.streamLimits ?? DEFAULT_RESOLVED_LIMITS;\n const globalLimit = resolved.maxToolCallArgBytes;\n const byTool = resolved.maxToolCallArgBytesByTool;\n if (!resolved.hasEnforceableToolCallArgLimit) {\n return;\n }\n if (metadata?.[STREAM_LIMIT_REDISPATCH_KEY] === true) {\n return;\n }\n for (const toolCall of toolCalls) {\n const name =\n toolCall.name != null && toolCall.name !== '' ? toolCall.name : undefined;\n const limit =\n byTool != null && name != null && Object.hasOwn(byTool, name)\n ? byTool[name]\n : globalLimit;\n if (limit <= 0) {\n continue;\n }\n const args = toolCall.args;\n let serialized: string;\n if (typeof args === 'string') {\n serialized = args;\n } else if (args == null) {\n serialized = '';\n } else {\n serialized = JSON.stringify(args);\n }\n const bytes = Buffer.byteLength(serialized, 'utf8');\n if (bytes > limit) {\n throw new StreamLimitExceededError({\n kind: 'tool_call_args',\n limit,\n observed: bytes,\n toolName: name,\n });\n }\n }\n}\n\n/**\n * Whether a chunk needs charge accounting at all. With the event cap off\n * (the default) and no tool payload on the chunk, there is nothing a claim\n * could ever gate — skipping restores the documented zero-cost-disabled\n * behavior by avoiding a WeakMap entry and nested Map per ordinary text\n * delta. Both the producer and consumer paths use this same predicate on\n * the same chunk, so claim pairing is unaffected.\n */\nexport function requiresStreamLimitAccounting(\n graph: StreamLimitState,\n chunk: {\n tool_call_chunks?: unknown[];\n tool_calls?: unknown[];\n invalid_tool_calls?: unknown[];\n }\n): boolean {\n const resolved = graph.streamLimits ?? DEFAULT_RESOLVED_LIMITS;\n if (resolved.maxDeltaEventsPerTurn > 0) {\n return true;\n }\n /** With no argument limit able to fire (byte cap disabled and every\n * per-tool entry a zero-valued disable), neither enforcement function can\n * trip — hosts that explicitly disable the guards for legitimate large\n * arguments must not pay per-chunk claim allocations (generation keys,\n * WeakMap entries, nested Maps) for bookkeeping that judges nothing. */\n if (!resolved.hasEnforceableToolCallArgLimit) {\n return false;\n }\n return (\n (chunk.tool_call_chunks?.length ?? 0) > 0 ||\n (chunk.tool_calls?.length ?? 0) > 0 ||\n (chunk.invalid_tool_calls?.length ?? 0) > 0\n );\n}\n\n/** True when any stream-limit guard can fire for this graph. The attempt\n * lease and per-chunk claims are both gated on it — fully disabled guards\n * must allocate no bookkeeping at all, per-attempt included. */\nexport function streamLimitAccountingEnabled(\n graph: StreamLimitState\n): boolean {\n const resolved = graph.streamLimits ?? DEFAULT_RESOLVED_LIMITS;\n return (\n resolved.hasEnforceableToolCallArgLimit ||\n resolved.maxDeltaEventsPerTurn > 0\n );\n}\n\n/** Leases a model attempt's generation: entries under it are exempt from\n * the reset sweep until {@link releaseStreamLimitGeneration} runs from the\n * attempt's `finally`. */\nexport function registerActiveStreamLimitGeneration(\n graph: StreamLimitState,\n generationKey: string\n): void {\n (graph.activeStreamLimitGenerations ??= new Set()).add(generationKey);\n}\n\n/** Ends an attempt's lease and deletes its accounting entries — the\n * authoritative retirement point for attempt-scoped state. */\nexport function releaseStreamLimitGeneration(\n graph: StreamLimitState,\n generationKey: string\n): void {\n graph.activeStreamLimitGenerations?.delete(generationKey);\n deleteGenerationEntries(graph.streamedToolCallArgTallies, generationKey);\n deleteGenerationEntries(graph.streamDeltaEventCounts, generationKey);\n}\n\nfunction deleteGenerationEntries(\n entries: Map<string, unknown> | undefined,\n generationKey: string\n): void {\n if (entries == null) {\n return;\n }\n const prefix = `${generationKey}:`;\n for (const key of entries.keys()) {\n if (key === generationKey || key.startsWith(prefix)) {\n entries.delete(key);\n }\n }\n}\n\nfunction isOwnedByActiveGeneration(\n key: string,\n activeGenerations: ReadonlySet<string>\n): boolean {\n for (const generationKey of activeGenerations) {\n if (key === generationKey || key.startsWith(`${generationKey}:`)) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * Deletes accounting entries older than the epoch that is ending, EXCEPT\n * entries leased by a still-active attempt. Called by `resetValues` instead\n * of clearing: producer loops of straggling attempts use the graph's maps\n * directly and are not behind the consumer-only epoch gate, so a clear\n * would hand a cancellation-ignoring provider a fresh allowance at every\n * run start. Leased entries live until their attempt's `finally` releases\n * them; unleased entries (direct callers with no attempt stamp) get one\n * grace reset via their epoch tag.\n */\nexport function sweepStaleStreamLimitEntries(\n entries: Map<string, { epoch?: number }>,\n endingEpoch: number,\n activeGenerations?: ReadonlySet<string>\n): void {\n const hasActive = activeGenerations != null && activeGenerations.size > 0;\n for (const [key, value] of entries) {\n if (value.epoch === endingEpoch) {\n continue;\n }\n if (hasActive && isOwnedByActiveGeneration(key, activeGenerations)) {\n continue;\n }\n entries.delete(key);\n }\n}\n\n/** Links a secondary representation of a wire chunk (e.g. a provider\n * adapter's callback copy) to its canonical emission object, so claim\n * accounting treats both as one emission even though their identities\n * differ. Non-enumerable, so the link stays out of serialization and chunk\n * merges. */\nconst STREAM_LIMIT_CANONICAL: unique symbol = Symbol('streamLimitCanonical');\n\nexport function linkStreamLimitCanonical(\n copy: object,\n canonical: object\n): void {\n Object.defineProperty(copy, STREAM_LIMIT_CANONICAL, {\n value: canonical,\n enumerable: false,\n configurable: true,\n });\n}\n\nfunction canonicalChunk(chunk: object): object {\n const linked = (chunk as Record<PropertyKey, unknown>)[\n STREAM_LIMIT_CANONICAL\n ];\n return typeof linked === 'object' && linked != null ? linked : chunk;\n}\n\n/**\n * Claims accounting ownership of one EMISSION of a wire chunk. LangChain can\n * hand the same chunk object to the decoupled `streamEvents` handler\n * (`consumer`) and to the dispatch loop (`producer`) in either order, and a\n * streaming model may mutate and re-yield the same object across emissions —\n * so dedup is a signed credit balance per object rather than a lifetime set.\n * Each producer visit adds a credit, each consumer visit removes one, and a\n * visit charges only when the other side has not already charged that\n * emission (positive balance = producer ahead, negative = consumer ahead).\n * Paths where only one side ever observes the chunk (summarization, local\n * replay-skip) charge every visit, since their balance never crosses zero\n * the other way. Balances are scoped by generation identity so parallel\n * generations sharing one reused chunk object cannot cancel each other's\n * charges. Non-object chunks cannot be identity-tracked and are always\n * claimable.\n */\nexport function claimStreamLimitCharge(\n graph: StreamLimitState,\n chunk: unknown,\n side: 'producer' | 'consumer',\n metadata: Record<string, unknown> | undefined\n): boolean {\n if (typeof chunk !== 'object' || chunk == null) {\n return true;\n }\n const emission = canonicalChunk(chunk);\n const credits = (graph.streamLimitChargeCredits ??= new WeakMap());\n let byGeneration = credits.get(emission);\n if (byGeneration == null) {\n byGeneration = new Map();\n credits.set(emission, byGeneration);\n }\n const generationKey = resolveGenerationKey(metadata);\n const balance = byGeneration.get(generationKey) ?? 0;\n if (side === 'producer') {\n byGeneration.set(generationKey, balance + 1);\n return balance >= 0;\n }\n byGeneration.set(generationKey, balance - 1);\n return balance <= 0;\n}\n\n/**\n * Synchronous producer-side accounting for wire chunks that would otherwise\n * be judged only when the decoupled `streamEvents` reader catches up — or,\n * on replay-skipped and summarization chunks, not at all. A lagging reader\n * would let an oversized complete call return to LangGraph and reach\n * `ToolNode` before the queued handler throws; charging in the producer\n * loop keeps the breaker ahead of graph progression. Claim-based, so\n * whichever of this path and the handler echo sees the chunk object first\n * charges it and the other skips.\n */\nexport function enforceStreamLimitsForWireChunk({\n graph,\n metadata,\n chunk,\n side = 'producer',\n}: {\n graph: StreamLimitState;\n metadata: Record<string, unknown> | undefined;\n chunk: {\n tool_call_chunks?: ToolCallChunk[];\n tool_calls?: CompleteToolCallLike[];\n invalid_tool_calls?: CompleteToolCallLike[];\n response_metadata?: Record<string, unknown>;\n };\n /** Claim side for the credit balance. The local dispatch branch charges\n * as `consumer` because its handler-handled and replay-skipped emissions\n * of one reused object ALTERNATE — mixed sides would pair them as\n * producer/echo and swallow a charge. */\n side?: 'producer' | 'consumer';\n}): void {\n if (!requiresStreamLimitAccounting(graph, chunk)) {\n return;\n }\n if (!claimStreamLimitCharge(graph, chunk, side, metadata)) {\n return;\n }\n enforceStreamDeltaEventLimit({ graph, metadata });\n /** Combined view computed first so the raw-chunk guard can correlate\n * names from BOTH parsed and invalid calls in the same event; an unnamed\n * raw chunk twinned with a named invalid call must select that tool's\n * override, not the global cap. */\n const completeCalls = combineCompleteToolCalls(chunk);\n if (chunk.tool_call_chunks != null && chunk.tool_call_chunks.length > 0) {\n enforceStreamedToolCallArgLimit({\n graph,\n metadata,\n toolCallChunks: chunk.tool_call_chunks,\n responseMetadata: chunk.response_metadata,\n parsedToolCalls: completeCalls,\n });\n }\n /** Judged whenever parsed calls are present, not only when raw chunks are\n * absent: an adapter can pair an empty or partial raw chunk with a\n * complete parsed call, and the standalone check is stateless so the\n * common both-present case is not double-tallied. `invalid_tool_calls`\n * are included — ToolNode processes and promotes them, and a malformed\n * call streaming oversized arguments is the exact pathology this breaker\n * exists to stop. */\n if (completeCalls != null) {\n enforceCompleteToolCallArgLimit({ graph, metadata, toolCalls: completeCalls });\n }\n}\n\n/** Combined view of a chunk's parsed and invalid complete calls, avoiding\n * allocation on the common paths where one or both are absent. */\nexport function combineCompleteToolCalls(chunk: {\n tool_calls?: CompleteToolCallLike[];\n invalid_tool_calls?: CompleteToolCallLike[];\n}): CompleteToolCallLike[] | undefined {\n const parsed = chunk.tool_calls;\n const invalid = chunk.invalid_tool_calls;\n const hasParsed = parsed != null && parsed.length > 0;\n const hasInvalid = invalid != null && invalid.length > 0;\n if (hasParsed && hasInvalid) {\n return [...parsed, ...invalid];\n }\n if (hasParsed) {\n return parsed;\n }\n return hasInvalid ? invalid : undefined;\n}\n\n/**\n * Counts streamed chunk events per model generation and throws once a single\n * generation exceeds `maxDeltaEventsPerTurn`. Opt-in defense in depth for\n * pathologies a byte cap cannot see, such as a provider stream looping on\n * empty chunks. Zero cost while disabled.\n */\nexport function enforceStreamDeltaEventLimit({\n graph,\n metadata,\n}: {\n graph: StreamLimitState;\n metadata: Record<string, unknown> | undefined;\n}): void {\n const limit = (graph.streamLimits ?? DEFAULT_RESOLVED_LIMITS)\n .maxDeltaEventsPerTurn;\n if (limit <= 0) {\n return;\n }\n if (metadata?.[STREAM_LIMIT_REDISPATCH_KEY] === true) {\n return;\n }\n const counts = (graph.streamDeltaEventCounts ??= new Map());\n const key = resolveGenerationKey(metadata);\n const existing = counts.get(key);\n const next = (existing?.count ?? 0) + 1;\n if (next > limit) {\n throw new StreamLimitExceededError({\n kind: 'delta_events',\n limit,\n observed: next,\n });\n }\n if (existing != null) {\n existing.count = next;\n } else {\n counts.set(key, { count: next, epoch: graph.breakerEpoch });\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAoBA,MAAa,kCAAkC;AAmF/C,SAAS,aAAa,OAA2B,UAA0B;CACzE,IAAI,SAAS,QAAQ,OAAO,MAAM,KAAK,GACrC,OAAO;CAET,IAAI,CAAC,OAAO,SAAS,KAAK,G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EAAM,OAAO,MAAM;CAAa,CAAC;AAE9D"}
package/dist/esm/main.mjs CHANGED
@@ -1,11 +1,11 @@
1
- import { isPresent, parseBooleanEnv, unescapeObject } from "./utils/misc.mjs";
1
+ import { composeAbortSignals, isPresent, parseBooleanEnv, unescapeObject } from "./utils/misc.mjs";
2
2
  import { ANTHROPIC_TOOL_TOKEN_MULTIPLIER, DEFAULT_MAX_SEALS, DEFAULT_RECURSION_LIMIT, DEFAULT_TOOL_TOKEN_MULTIPLIER, PREEMPT_BOUNDARY_HOOK_TIMEOUT_MS } from "./common/constants.mjs";
3
3
  import { CODE_EXECUTION_TOOLS, Callback, CommonEvents, Constants, ContentTypes, EnvVar, GraphEvents, GraphNodeActions, GraphNodeKeys, LOCAL_CODING_BUNDLE_NAMES, LOCAL_CODING_TOOL_NAMES, Providers, StepTypes, TitleMethod, ToolCallTypes } from "./common/enum.mjs";
4
4
  import "./common/index.mjs";
5
5
  import { HARD_MAX_TOOL_RESULT_CHARS, HARD_MAX_TOTAL_TOOL_OUTPUT_SIZE, calculateMaxToolResultChars, calculateMaxTotalToolOutputSize, truncateToolInput, truncateToolResultContent } from "./utils/truncation.mjs";
6
6
  import { IMAGE_TOKEN_SAFETY_MARGIN, TokenEncoderManager, apportionTokenCounts, createTokenCounter, encodingForModel, estimateAnthropicImageTokens, estimateDocumentBlockTokens, estimateImageBlockTokens, estimateOpenAIImageTokens, estimateTimedMediaBlockTokens, extractImageDimensions, getTokenCountForMessage, hasUnsafeStructuredSerialization } from "./utils/tokens.mjs";
7
7
  import { DEFAULT_PROMPT_CACHE_TTL, addBedrockCacheControl, addBedrockTailCacheControl, addCacheControl, addCacheControlToStablePrefixMessages, addTailCacheControl, buildAnthropicCacheControl, buildBedrockCachePoint, cloneMessage, resolveBedrockPromptCacheTtl, resolvePromptCacheTtl, stripAnthropicCacheControl, stripBedrockCacheControl, supportsBedrockToolCache } from "./messages/cache.mjs";
8
- import { convertMessagesToContent, findLastIndex, formatAnthropicArtifactContent, formatAnthropicMessage, formatArtifactPayload, getConverseOverrideMessage, modifyDeltaProperties, projectAnthropicArtifactContent, projectArtifactPayload, projectCacheControlledToolOutputsToText, projectComputerCallOutputsToText, projectOpenAIChatToolMessageContent, projectOpenAIResponsesToolMessageContent, projectOpenAIToolMessageContent, projectOpenRouterToolMessageContent, projectSingleTextToolOutputsToText, projectStructuredToolOutputsToText, projectToolStreamContentForProvider } from "./messages/core.mjs";
8
+ import { OPENAI_RESPONSES_REPLAY_POSITIONS_KEY, convertMessagesToContent, findLastIndex, formatAnthropicArtifactContent, formatAnthropicMessage, formatArtifactPayload, getConverseOverrideMessage, modifyDeltaProperties, projectAnthropicArtifactContent, projectArtifactPayload, projectCacheControlledToolOutputsToText, projectComputerCallOutputsToText, projectOpenAIChatToolMessageContent, projectOpenAIResponsesToolMessageContent, projectOpenAIToolMessageContent, projectOpenRouterToolMessageContent, projectSingleTextToolOutputsToText, projectStructuredToolOutputsToText, projectToolStreamContentForProvider } from "./messages/core.mjs";
9
9
  import { getMessageId } from "./messages/ids.mjs";
10
10
  import { DEFAULT_CONTEXT_PRUNING_SETTINGS, resolveContextPruningSettings } from "./messages/contextPruningSettings.mjs";
11
11
  import { applyContextPruning } from "./messages/contextPruning.mjs";
@@ -21,16 +21,18 @@ import { PREDECESSOR_HANDOFF_CUE, appendPredecessorHandoffCue, removePredecessor
21
21
  import { REMOVE_ALL_MESSAGES, createRemoveAllMessage, messagesStateReducer } from "./messages/reducer.mjs";
22
22
  import { DEFAULT_RETAIN_RECENT_TURNS, splitAtRecencyBoundary } from "./messages/recency.mjs";
23
23
  import "./messages/index.mjs";
24
+ import { handleServerToolResult, handleToolCallChunks, handleToolCalls, toolResultTypes } from "./tools/handlers.mjs";
25
+ import { DEFAULT_MAX_TOOL_CALL_ARG_BYTES, StreamLimitExceededError, resolveStreamLimits } from "./llm/streamLimits.mjs";
24
26
  import { INTENT_ARG, INTENT_DESCRIPTION, INTENT_LABEL_MARKER, INTENT_PROPERTY, applyOutcome, isIntentLabelProperty, outcomeFieldsFromResult, readIntent, readOutcomeFields, resolveToolOutcome, stripIntent, withIntent, withoutIntent } from "./tools/intentArg.mjs";
27
+ import { isAnthropicLike, isGoogleLike, isOpenAILike } from "./utils/llm.mjs";
28
+ import { ChatModelStreamHandler, SDK_STREAM_DISPATCH, createContentAggregator, dispatchesChatModelStream, getChunkContent } from "./stream.mjs";
25
29
  import { CustomOpenAIClient } from "./llm/openai/index.mjs";
26
30
  import { ChatOpenRouter } from "./llm/openrouter/index.mjs";
27
31
  import { getChatModelClass } from "./llm/providers.mjs";
28
32
  import { extractErrorMessage, getContextOverflowInfo, isContextOverflowError, isLikelyContextOverflowError } from "./utils/errors.mjs";
29
33
  import { canSealPreempt } from "./llm/preempt.mjs";
30
- import { handleServerToolResult, handleToolCallChunks, handleToolCalls, toolResultTypes } from "./tools/handlers.mjs";
31
- import { isAnthropicLike, isGoogleLike, isOpenAILike } from "./utils/llm.mjs";
32
- import { ChatModelStreamHandler, SDK_STREAM_DISPATCH, createContentAggregator, dispatchesChatModelStream, getChunkContent } from "./stream.mjs";
33
34
  import { joinKeys, resetIfNotEmpty } from "./utils/graph.mjs";
35
+ import { resolveFetchProxyAgent, shouldBypassProxy } from "./utils/proxy.mjs";
34
36
  import { HandlerRegistry, LLMStreamHandler, ModelEndHandler, TestChatStreamHandler, TestLLMStreamHandler, ToolEndHandler, composeEventHandlers, createMetadataAggregator } from "./events.mjs";
35
37
  import { createHandlers } from "./utils/handlers.mjs";
36
38
  import { RunnableCallable, sleep } from "./utils/run.mjs";
@@ -102,4 +104,4 @@ import { Runnable, RunnableLambda, RunnableSequence } from "./langchain/runnable
102
104
  import { DynamicStructuredTool, StructuredTool, Tool, tool } from "./langchain/tools.mjs";
103
105
  import "./langchain/index.mjs";
104
106
  import { BaseCheckpointSaver, Command, INTERRUPT, MemorySaver, interrupt, isInterrupted } from "@langchain/langgraph";
105
- export { AIMessage, AIMessageChunk, ANTHROPIC_TOOL_TOKEN_MULTIPLIER, AgentSession, BASH_SHELL_GUIDANCE, BaseCheckpointSaver, BaseMessage, BaseMessageChunk, BashExecutionToolDefinition, BashExecutionToolDescription, BashExecutionToolName, BashExecutionToolSchema, BashProgrammaticToolCallingDefinition, BashProgrammaticToolCallingDescription, BashProgrammaticToolCallingName, BashProgrammaticToolCallingSchema, BashToolOutputReferencesGuide, CALIBRATION_RATIO_MAX, CALIBRATION_RATIO_MIN, CLOUDFLARE_BASH_CODING_TOOL_NAMES, CLOUDFLARE_CODING_TOOL_NAMES, CODE_API_AUTHORIZATION_ERROR_MESSAGE, CODE_API_EXECUTION_FAILED_ERROR_MESSAGE, CODE_API_INVALID_REQUEST_ERROR_MESSAGE, CODE_API_RATE_LIMITED_ERROR_MESSAGE, CODE_API_UNAVAILABLE_ERROR_MESSAGE, CODE_ARTIFACT_PATH_GUIDANCE, CODE_EXECUTION_TOOLS, Calculator, CalculatorSchema, CalculatorToolDefinition, CalculatorToolDescription, CalculatorToolName, Callback, ChatModelStreamHandler, ChatOpenRouter, CloudflareBashExecutionToolDescription, CloudflareCodeExecutionToolDescription, CodeApiRequestError, CodeExecutionToolDefinition, CodeExecutionToolDescription, CodeExecutionToolName, CodeExecutionToolSchema, Command, CommonEvents, CompileCheckToolName, Constants, ContentTypes, CustomOpenAIClient, DATE_RANGE, DEFAULT_CONTEXT_PRUNING_SETTINGS, DEFAULT_COUNTRY_DESCRIPTION, DEFAULT_HOOK_TIMEOUT_MS, DEFAULT_MAX_SEALS, DEFAULT_PROMPT_CACHE_TTL, DEFAULT_QUERY_DESCRIPTION, DEFAULT_RECURSION_LIMIT, DEFAULT_RESERVE_RATIO, DEFAULT_RETAIN_RECENT_TURNS, DEFAULT_TOOL_TOKEN_MULTIPLIER, DynamicStructuredTool, EnvVar, FAILED_EXECUTION_FILE_REMINDER, FakeChatModel, Graph, GraphEvents, GraphNodeActions, GraphNodeKeys, HARD_MAX_TOOL_RESULT_CHARS, HARD_MAX_TOTAL_TOOL_OUTPUT_SIZE, HOOK_EVENTS, HOOK_INJECTED_MESSAGES_CAPABLE, HOOK_PREEMPT_BOUNDARY_CAPABLE, HandlerRegistry, HookRegistry, HumanMessage, IMAGE_TOKEN_SAFETY_MARGIN, INTENT_ARG, INTENT_DESCRIPTION, INTENT_LABEL_MARKER, INTENT_PROPERTY, INTERRUPT, JsonlSessionStore, LLMStreamHandler, LOCAL_CODING_BUNDLE_NAMES, LOCAL_CODING_TOOL_NAMES, LOCAL_SPAWN_TIMEOUT_MS, LocalBashExecutionToolDescription, LocalCodeExecutionToolDescription, LocalEditFileToolName, LocalEditFileToolSchema, LocalFileCheckpointerImpl, LocalGlobSearchToolName, LocalGlobSearchToolSchema, LocalGrepSearchToolName, LocalGrepSearchToolSchema, LocalListDirectoryToolName, LocalListDirectoryToolSchema, LocalReadFileToolSchema, LocalWriteFileToolName, LocalWriteFileToolSchema, MAX_CACHE_SIZE, MAX_PATTERN_LENGTH, MemorySaver, ModelEndHandler, MultiAgentGraph, ORIGINAL_CONTENT_MAX_CHARS, PREDECESSOR_HANDOFF_CUE, PREEMPT_BOUNDARY_HOOK_TIMEOUT_MS, ProgrammaticToolCallingDefinition, ProgrammaticToolCallingDescription, ProgrammaticToolCallingName, ProgrammaticToolCallingSchema, PromptTemplate, Providers, REMOVE_ALL_MESSAGES, REPLY_PRIMER_TOKENS, ReadFileToolDefinition, ReadFileToolDescription, ReadFileToolName, ReadFileToolSchema, Run, Runnable, RunnableCallable, RunnableLambda, RunnableSequence, SDK_STREAM_DISPATCH, STATEFUL_BASH_NOTE, STATEFUL_ENV_NOTE, SessionManager, SkillToolDefinition, SkillToolDescription, SkillToolName, SkillToolSchema, StandardGraph, StatefulBashExecutionToolDescription, StatefulCodeExecutionToolDescription, StepTypes, StructuredTool, SubagentExecutor, SubagentToolDefinition, SubagentToolDescription, SubagentToolName, SubagentToolSchema, SystemMessage, TMP_SCRATCH_OUTPUT_REMINDER, TestChatStreamHandler, TestLLMStreamHandler, TitleMethod, TokenEncoderManager, Tool, ToolCallTypes, ToolEndHandler, ToolMessage, ToolNode, ToolSearchToolDefinition, ToolSearchToolDescription, ToolSearchToolName, ToolSearchToolSchema, WebSearchToolDefinition, WebSearchToolDescription, WebSearchToolName, WebSearchToolSchema, _createBashProgramForTests, _resetLocalEngineWarningsForTests, _resetRipgrepCacheForTests, _resetSyntaxCheckProbeCacheForTests, _resetUnrecognizedTriggerWarnings, addBedrockCacheControl, addBedrockTailCacheControl, addCacheControl, addCacheControlToStablePrefixMessages, addTailCacheControl, appendCodeSessionFileSummary, appendFailedExecutionFileReminder, appendPredecessorHandoffCue, appendTmpScratchReminder, applyContextPruning, applyEdit, applyOutcome, applyPreToolUseHooksForBridge, apportionTokenCounts, askUserQuestion, attemptInvoke, bashAstFindingsToErrors, buildAnthropicCacheControl, buildBashExecutionToolDescription, buildBashExecutionToolSchema, buildBedrockCachePoint, buildChildInputs, buildCodeApiExecutionErrorMessage, buildCodeApiHttpErrorMessage, buildCodeExecutionToolDescription, buildCodeExecutionToolSchema, buildSandboxRuntimeConfig, buildSubagentToolParams, calculateMaxToolCallInputChars, calculateMaxToolResultChars, calculateMaxTotalToolOutputSize, calculateTotalTokens, canSealPreempt, checkValidNumber, clampCalibrationRatio, classifyAttachment, clientExecTimeoutMs, clientFsTimeoutMs, cloneMessage, coalesceAdjacentUserTurns, composeEventHandlers, convertInjectedMessages, convertMessagesToContent, countNestedGroups, countrySchema, createAgentSession, createBashExecutionTool, createBashProgrammaticToolCallingSchema, createBashProgrammaticToolCallingTool, createCloudflareBashExecutionTool, createCloudflareBashProgrammaticToolCallingTool, createCloudflareBridgeRuntime, createCloudflareCodeExecutionTool, createCloudflareCodingToolBundle, createCloudflareCodingTools, createCloudflareExecutionTool, createCloudflareLocalExecutionConfig, createCloudflareProgrammaticToolCallingTool, createCloudflareWorkspaceFS, createCodeExecutionTool, createCompileCheckTool, createCompileCheckToolDefinition, createContentAggregator, createFakeStreamingLLM, createHandlers, createLocalBashExecutionTool, createLocalBashProgrammaticToolCallingTool, createLocalCodeExecutionTool, createLocalCodingToolBundle, createLocalCodingToolDefinitions, createLocalCodingToolRegistry, createLocalCodingTools, createLocalEditFileTool, createLocalFileCheckpointer, createLocalGlobSearchTool, createLocalGrepSearchTool, createLocalListDirectoryTool, createLocalProgrammaticToolCallingTool, createLocalReadFileTool, createLocalWriteFileTool, createMetadataAggregator, createProgrammaticToolCallingSchema, createProgrammaticToolCallingTool, createPruneMessages, createRemoveAllMessage, createRunHandlers, createSchemaOnlyTool, createSchemaOnlyTools, createSearchTool, createSubagentToolDefinition, createTokenCounter, createToolErrorOwnership, createToolPolicyHook, createToolSearch, createWorkspacePolicyHook, dateSchema, decodeFile, defaultOmitOptions, deserializeMessage, dispatchesChatModelStream, emptyOutputMessage, encodeFile, encodingForModel, enforceOriginalContentCap, ensureThinkingBlockInMessages, escapeRegexSpecialChars, estimateAnthropicImageTokens, estimateDocumentBlockTokens, estimateImageBlockTokens, estimateOpenAIImageTokens, estimateTimedMediaBlockTokens, execWithClientTimeout, executeCloudflareBash, executeCloudflareCode, executeHooks, executeLocalBash, executeLocalBashWithArgs, executeLocalCode, executeParallelSearches, executeTools, extractErrorMessage, extractImageDimensions, extractMcpServerName, extractTextFromContent, extractToolDiscoveries, extractUsedBashToolNames, extractUsedToolNames, fetchSessionFiles, filterBashToolsByUsage, filterSubagentResult, filterToolsByUsage, findLastIndex, foldToolBlocksForToollessAgent, formatAgentMessages, formatAnthropicArtifactContent, formatAnthropicMessage, formatArtifactPayload, formatCloudflareOutput, formatCompletedResponse, formatContentStrings, formatFromLangChain, formatLangChainMessages, formatMediaMessage, formatMessage, formatServerListing, formatSkillCatalog, getAvailableMcpServers, getBaseToolName, getBufferString, getChatModelClass, getChunkContent, getCloudflareWorkspaceRoot, getCodeBaseURL, getContextOverflowInfo, getConverseOverrideMessage, getDeferredToolsListing, getLocalCwd, getLocalSessionId, getMaxOutputTokensKey, getMessageId, getMessagesWithinTokenLimit, getReadRoots, getSpawn, getTokenCountForMessage, getWorkspaceFS, getWorkspaceRoots, getWriteRoots, handleServerToolResult, handleToolCallChunks, handleToolCalls, hasNestedQuantifier, hasNestedQuantifiers, hasToolSearchInCurrentTurn, hasUnsafeStructuredSerialization, imageAttachmentContent, imagesSchema, initializeModel, interrupt, isAIMessage, isAnthropicLike, isBaseMessage, isContextOverflowError, isDangerousPattern, isFromAnyMcpServer, isFromMcpServer, isGoogleLike, isIntentLabelProperty, isInterrupted, isLegacyConvertible, isLikelyContextOverflowError, isOpenAILike, isPresent, isSyntheticProviderContextMessage, isThinkingEnabled, isToolMessage, isZodSchema, joinKeys, labelContentByAgent, locateEdit, makeIsDeferred, makeRequest, maskConsumedToolResults, matchesQuery, messagesStateReducer, modifyDeltaProperties, newsSchema, normalizeBashToolResultsForReplay, normalizeCodeApiRequestError, normalizeServerFilter, normalizeToBashIdentifier, normalizeToPythonIdentifier, outcomeFieldsFromResult, parseBooleanEnv, partitionAndMarkAnthropicToolCache, performLocalSearch, preFlightTruncateToolCallInputs, preFlightTruncateToolResults, projectAgentContextUsage, projectAnthropicArtifactContent, projectArtifactPayload, projectCacheControlledToolOutputsToText, projectComputerCallOutputsToText, projectOpenAIChatToolMessageContent, projectOpenAIResponsesToolMessageContent, projectOpenAIToolMessageContent, projectOpenRouterToolMessageContent, projectSingleTextToolOutputsToText, projectStructuredToolOutputsToText, projectToolCallInputs, projectToolStreamContentForProvider, querySchema, readIntent, readOutcomeFields, removePredecessorHandoffCue, repairOrphanedToolMessages, resetIfNotEmpty, resolveBedrockPromptCacheTtl, resolveCloudflareSandbox, resolveCodeApiAuthHeaders, resolveContextPruningSettings, resolveLocalExecutionConfig, resolveLocalExecutionTools, resolveLocalToolRegistry, resolveLocalToolsForBinding, resolvePromptCacheTtl, resolveSearchOutcome, resolveSubagentConfigs, resolveToolOutcome, resolveWorkspacePath, resolveWorkspacePathSafe, runBashAstChecks, runPostEditSyntaxCheck, sanitizeOrphanToolBlocks, sanitizeRegex, serializeMessage, serializeToolCallInput, shellQuote, shiftIndexTokenCountMap, shouldTriggerSummarization, sleep, spawnLocalProcess, splitAtRecencyBoundary, strictAlternationProviders, stripAnthropicCacheControl, stripBedrockCacheControl, stripCodeSessionFileSummary, stripIntent, summarizeEvent, supportsBedrockToolCache, syncBudgetDerivedFields, toJsonSchema, tool, toolResultTypes, toolsCondition, truncateLocalOutput, truncateToolInput, truncateToolResultContent, tryFallbackProviders, unescapeObject, unwrapToolResponse, validateBashCommand, validateCloudflareBashCommand, videosSchema, withClientTimeout, withIntent, withMessageRole, withoutIntent };
107
+ export { AIMessage, AIMessageChunk, ANTHROPIC_TOOL_TOKEN_MULTIPLIER, AgentSession, BASH_SHELL_GUIDANCE, BaseCheckpointSaver, BaseMessage, BaseMessageChunk, BashExecutionToolDefinition, BashExecutionToolDescription, BashExecutionToolName, BashExecutionToolSchema, BashProgrammaticToolCallingDefinition, BashProgrammaticToolCallingDescription, BashProgrammaticToolCallingName, BashProgrammaticToolCallingSchema, BashToolOutputReferencesGuide, CALIBRATION_RATIO_MAX, CALIBRATION_RATIO_MIN, CLOUDFLARE_BASH_CODING_TOOL_NAMES, CLOUDFLARE_CODING_TOOL_NAMES, CODE_API_AUTHORIZATION_ERROR_MESSAGE, CODE_API_EXECUTION_FAILED_ERROR_MESSAGE, CODE_API_INVALID_REQUEST_ERROR_MESSAGE, CODE_API_RATE_LIMITED_ERROR_MESSAGE, CODE_API_UNAVAILABLE_ERROR_MESSAGE, CODE_ARTIFACT_PATH_GUIDANCE, CODE_EXECUTION_TOOLS, Calculator, CalculatorSchema, CalculatorToolDefinition, CalculatorToolDescription, CalculatorToolName, Callback, ChatModelStreamHandler, ChatOpenRouter, CloudflareBashExecutionToolDescription, CloudflareCodeExecutionToolDescription, CodeApiRequestError, CodeExecutionToolDefinition, CodeExecutionToolDescription, CodeExecutionToolName, CodeExecutionToolSchema, Command, CommonEvents, CompileCheckToolName, Constants, ContentTypes, CustomOpenAIClient, DATE_RANGE, DEFAULT_CONTEXT_PRUNING_SETTINGS, DEFAULT_COUNTRY_DESCRIPTION, DEFAULT_HOOK_TIMEOUT_MS, DEFAULT_MAX_SEALS, DEFAULT_MAX_TOOL_CALL_ARG_BYTES, DEFAULT_PROMPT_CACHE_TTL, DEFAULT_QUERY_DESCRIPTION, DEFAULT_RECURSION_LIMIT, DEFAULT_RESERVE_RATIO, DEFAULT_RETAIN_RECENT_TURNS, DEFAULT_TOOL_TOKEN_MULTIPLIER, DynamicStructuredTool, EnvVar, FAILED_EXECUTION_FILE_REMINDER, FakeChatModel, Graph, GraphEvents, GraphNodeActions, GraphNodeKeys, HARD_MAX_TOOL_RESULT_CHARS, HARD_MAX_TOTAL_TOOL_OUTPUT_SIZE, HOOK_EVENTS, HOOK_INJECTED_MESSAGES_CAPABLE, HOOK_PREEMPT_BOUNDARY_CAPABLE, HandlerRegistry, HookRegistry, HumanMessage, IMAGE_TOKEN_SAFETY_MARGIN, INTENT_ARG, INTENT_DESCRIPTION, INTENT_LABEL_MARKER, INTENT_PROPERTY, INTERRUPT, JsonlSessionStore, LLMStreamHandler, LOCAL_CODING_BUNDLE_NAMES, LOCAL_CODING_TOOL_NAMES, LOCAL_SPAWN_TIMEOUT_MS, LocalBashExecutionToolDescription, LocalCodeExecutionToolDescription, LocalEditFileToolName, LocalEditFileToolSchema, LocalFileCheckpointerImpl, LocalGlobSearchToolName, LocalGlobSearchToolSchema, LocalGrepSearchToolName, LocalGrepSearchToolSchema, LocalListDirectoryToolName, LocalListDirectoryToolSchema, LocalReadFileToolSchema, LocalWriteFileToolName, LocalWriteFileToolSchema, MAX_CACHE_SIZE, MAX_PATTERN_LENGTH, MemorySaver, ModelEndHandler, MultiAgentGraph, OPENAI_RESPONSES_REPLAY_POSITIONS_KEY, ORIGINAL_CONTENT_MAX_CHARS, PREDECESSOR_HANDOFF_CUE, PREEMPT_BOUNDARY_HOOK_TIMEOUT_MS, ProgrammaticToolCallingDefinition, ProgrammaticToolCallingDescription, ProgrammaticToolCallingName, ProgrammaticToolCallingSchema, PromptTemplate, Providers, REMOVE_ALL_MESSAGES, REPLY_PRIMER_TOKENS, ReadFileToolDefinition, ReadFileToolDescription, ReadFileToolName, ReadFileToolSchema, Run, Runnable, RunnableCallable, RunnableLambda, RunnableSequence, SDK_STREAM_DISPATCH, STATEFUL_BASH_NOTE, STATEFUL_ENV_NOTE, SessionManager, SkillToolDefinition, SkillToolDescription, SkillToolName, SkillToolSchema, StandardGraph, StatefulBashExecutionToolDescription, StatefulCodeExecutionToolDescription, StepTypes, StreamLimitExceededError, StructuredTool, SubagentExecutor, SubagentToolDefinition, SubagentToolDescription, SubagentToolName, SubagentToolSchema, SystemMessage, TMP_SCRATCH_OUTPUT_REMINDER, TestChatStreamHandler, TestLLMStreamHandler, TitleMethod, TokenEncoderManager, Tool, ToolCallTypes, ToolEndHandler, ToolMessage, ToolNode, ToolSearchToolDefinition, ToolSearchToolDescription, ToolSearchToolName, ToolSearchToolSchema, WebSearchToolDefinition, WebSearchToolDescription, WebSearchToolName, WebSearchToolSchema, _createBashProgramForTests, _resetLocalEngineWarningsForTests, _resetRipgrepCacheForTests, _resetSyntaxCheckProbeCacheForTests, _resetUnrecognizedTriggerWarnings, addBedrockCacheControl, addBedrockTailCacheControl, addCacheControl, addCacheControlToStablePrefixMessages, addTailCacheControl, appendCodeSessionFileSummary, appendFailedExecutionFileReminder, appendPredecessorHandoffCue, appendTmpScratchReminder, applyContextPruning, applyEdit, applyOutcome, applyPreToolUseHooksForBridge, apportionTokenCounts, askUserQuestion, attemptInvoke, bashAstFindingsToErrors, buildAnthropicCacheControl, buildBashExecutionToolDescription, buildBashExecutionToolSchema, buildBedrockCachePoint, buildChildInputs, buildCodeApiExecutionErrorMessage, buildCodeApiHttpErrorMessage, buildCodeExecutionToolDescription, buildCodeExecutionToolSchema, buildSandboxRuntimeConfig, buildSubagentToolParams, calculateMaxToolCallInputChars, calculateMaxToolResultChars, calculateMaxTotalToolOutputSize, calculateTotalTokens, canSealPreempt, checkValidNumber, clampCalibrationRatio, classifyAttachment, clientExecTimeoutMs, clientFsTimeoutMs, cloneMessage, coalesceAdjacentUserTurns, composeAbortSignals, composeEventHandlers, convertInjectedMessages, convertMessagesToContent, countNestedGroups, countrySchema, createAgentSession, createBashExecutionTool, createBashProgrammaticToolCallingSchema, createBashProgrammaticToolCallingTool, createCloudflareBashExecutionTool, createCloudflareBashProgrammaticToolCallingTool, createCloudflareBridgeRuntime, createCloudflareCodeExecutionTool, createCloudflareCodingToolBundle, createCloudflareCodingTools, createCloudflareExecutionTool, createCloudflareLocalExecutionConfig, createCloudflareProgrammaticToolCallingTool, createCloudflareWorkspaceFS, createCodeExecutionTool, createCompileCheckTool, createCompileCheckToolDefinition, createContentAggregator, createFakeStreamingLLM, createHandlers, createLocalBashExecutionTool, createLocalBashProgrammaticToolCallingTool, createLocalCodeExecutionTool, createLocalCodingToolBundle, createLocalCodingToolDefinitions, createLocalCodingToolRegistry, createLocalCodingTools, createLocalEditFileTool, createLocalFileCheckpointer, createLocalGlobSearchTool, createLocalGrepSearchTool, createLocalListDirectoryTool, createLocalProgrammaticToolCallingTool, createLocalReadFileTool, createLocalWriteFileTool, createMetadataAggregator, createProgrammaticToolCallingSchema, createProgrammaticToolCallingTool, createPruneMessages, createRemoveAllMessage, createRunHandlers, createSchemaOnlyTool, createSchemaOnlyTools, createSearchTool, createSubagentToolDefinition, createTokenCounter, createToolErrorOwnership, createToolPolicyHook, createToolSearch, createWorkspacePolicyHook, dateSchema, decodeFile, defaultOmitOptions, deserializeMessage, dispatchesChatModelStream, emptyOutputMessage, encodeFile, encodingForModel, enforceOriginalContentCap, ensureThinkingBlockInMessages, escapeRegexSpecialChars, estimateAnthropicImageTokens, estimateDocumentBlockTokens, estimateImageBlockTokens, estimateOpenAIImageTokens, estimateTimedMediaBlockTokens, execWithClientTimeout, executeCloudflareBash, executeCloudflareCode, executeHooks, executeLocalBash, executeLocalBashWithArgs, executeLocalCode, executeParallelSearches, executeTools, extractErrorMessage, extractImageDimensions, extractMcpServerName, extractTextFromContent, extractToolDiscoveries, extractUsedBashToolNames, extractUsedToolNames, fetchSessionFiles, filterBashToolsByUsage, filterSubagentResult, filterToolsByUsage, findLastIndex, foldToolBlocksForToollessAgent, formatAgentMessages, formatAnthropicArtifactContent, formatAnthropicMessage, formatArtifactPayload, formatCloudflareOutput, formatCompletedResponse, formatContentStrings, formatFromLangChain, formatLangChainMessages, formatMediaMessage, formatMessage, formatServerListing, formatSkillCatalog, getAvailableMcpServers, getBaseToolName, getBufferString, getChatModelClass, getChunkContent, getCloudflareWorkspaceRoot, getCodeBaseURL, getContextOverflowInfo, getConverseOverrideMessage, getDeferredToolsListing, getLocalCwd, getLocalSessionId, getMaxOutputTokensKey, getMessageId, getMessagesWithinTokenLimit, getReadRoots, getSpawn, getTokenCountForMessage, getWorkspaceFS, getWorkspaceRoots, getWriteRoots, handleServerToolResult, handleToolCallChunks, handleToolCalls, hasNestedQuantifier, hasNestedQuantifiers, hasToolSearchInCurrentTurn, hasUnsafeStructuredSerialization, imageAttachmentContent, imagesSchema, initializeModel, interrupt, isAIMessage, isAnthropicLike, isBaseMessage, isContextOverflowError, isDangerousPattern, isFromAnyMcpServer, isFromMcpServer, isGoogleLike, isIntentLabelProperty, isInterrupted, isLegacyConvertible, isLikelyContextOverflowError, isOpenAILike, isPresent, isSyntheticProviderContextMessage, isThinkingEnabled, isToolMessage, isZodSchema, joinKeys, labelContentByAgent, locateEdit, makeIsDeferred, makeRequest, maskConsumedToolResults, matchesQuery, messagesStateReducer, modifyDeltaProperties, newsSchema, normalizeBashToolResultsForReplay, normalizeCodeApiRequestError, normalizeServerFilter, normalizeToBashIdentifier, normalizeToPythonIdentifier, outcomeFieldsFromResult, parseBooleanEnv, partitionAndMarkAnthropicToolCache, performLocalSearch, preFlightTruncateToolCallInputs, preFlightTruncateToolResults, projectAgentContextUsage, projectAnthropicArtifactContent, projectArtifactPayload, projectCacheControlledToolOutputsToText, projectComputerCallOutputsToText, projectOpenAIChatToolMessageContent, projectOpenAIResponsesToolMessageContent, projectOpenAIToolMessageContent, projectOpenRouterToolMessageContent, projectSingleTextToolOutputsToText, projectStructuredToolOutputsToText, projectToolCallInputs, projectToolStreamContentForProvider, querySchema, readIntent, readOutcomeFields, removePredecessorHandoffCue, repairOrphanedToolMessages, resetIfNotEmpty, resolveBedrockPromptCacheTtl, resolveCloudflareSandbox, resolveCodeApiAuthHeaders, resolveContextPruningSettings, resolveFetchProxyAgent, resolveLocalExecutionConfig, resolveLocalExecutionTools, resolveLocalToolRegistry, resolveLocalToolsForBinding, resolvePromptCacheTtl, resolveSearchOutcome, resolveStreamLimits, resolveSubagentConfigs, resolveToolOutcome, resolveWorkspacePath, resolveWorkspacePathSafe, runBashAstChecks, runPostEditSyntaxCheck, sanitizeOrphanToolBlocks, sanitizeRegex, serializeMessage, serializeToolCallInput, shellQuote, shiftIndexTokenCountMap, shouldBypassProxy, shouldTriggerSummarization, sleep, spawnLocalProcess, splitAtRecencyBoundary, strictAlternationProviders, stripAnthropicCacheControl, stripBedrockCacheControl, stripCodeSessionFileSummary, stripIntent, summarizeEvent, supportsBedrockToolCache, syncBudgetDerivedFields, toJsonSchema, tool, toolResultTypes, toolsCondition, truncateLocalOutput, truncateToolInput, truncateToolResultContent, tryFallbackProviders, unescapeObject, unwrapToolResponse, validateBashCommand, validateCloudflareBashCommand, videosSchema, withClientTimeout, withIntent, withMessageRole, withoutIntent };