@librechat/agents 3.3.3 → 3.3.5

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 (274) hide show
  1. package/dist/cjs/agents/AgentContext.cjs +2 -1
  2. package/dist/cjs/agents/AgentContext.cjs.map +1 -1
  3. package/dist/cjs/common/constants.cjs +21 -0
  4. package/dist/cjs/common/constants.cjs.map +1 -1
  5. package/dist/cjs/events.cjs +10 -1
  6. package/dist/cjs/events.cjs.map +1 -1
  7. package/dist/cjs/graphs/Graph.cjs +793 -111
  8. package/dist/cjs/graphs/Graph.cjs.map +1 -1
  9. package/dist/cjs/graphs/MultiAgentGraph.cjs +3 -1
  10. package/dist/cjs/graphs/MultiAgentGraph.cjs.map +1 -1
  11. package/dist/cjs/hooks/HookRegistry.cjs +25 -0
  12. package/dist/cjs/hooks/HookRegistry.cjs.map +1 -1
  13. package/dist/cjs/hooks/index.cjs +12 -0
  14. package/dist/cjs/hooks/index.cjs.map +1 -1
  15. package/dist/cjs/hooks/types.cjs +1 -0
  16. package/dist/cjs/hooks/types.cjs.map +1 -1
  17. package/dist/cjs/langfuse.cjs +8 -0
  18. package/dist/cjs/langfuse.cjs.map +1 -1
  19. package/dist/cjs/llm/anthropic/utils/message_inputs.cjs +79 -6
  20. package/dist/cjs/llm/anthropic/utils/message_inputs.cjs.map +1 -1
  21. package/dist/cjs/llm/bedrock/utils/message_inputs.cjs +38 -13
  22. package/dist/cjs/llm/bedrock/utils/message_inputs.cjs.map +1 -1
  23. package/dist/cjs/llm/google/utils/common.cjs +19 -7
  24. package/dist/cjs/llm/google/utils/common.cjs.map +1 -1
  25. package/dist/cjs/llm/invoke.cjs +331 -5
  26. package/dist/cjs/llm/invoke.cjs.map +1 -1
  27. package/dist/cjs/llm/openai/index.cjs +41 -5
  28. package/dist/cjs/llm/openai/index.cjs.map +1 -1
  29. package/dist/cjs/llm/openai/utils/index.cjs +25 -4
  30. package/dist/cjs/llm/openai/utils/index.cjs.map +1 -1
  31. package/dist/cjs/llm/openrouter/index.cjs +4 -1
  32. package/dist/cjs/llm/openrouter/index.cjs.map +1 -1
  33. package/dist/cjs/llm/preempt.cjs +132 -0
  34. package/dist/cjs/llm/preempt.cjs.map +1 -0
  35. package/dist/cjs/main.cjs +36 -5
  36. package/dist/cjs/messages/alternation.cjs +92 -0
  37. package/dist/cjs/messages/alternation.cjs.map +1 -0
  38. package/dist/cjs/messages/cache.cjs +54 -33
  39. package/dist/cjs/messages/cache.cjs.map +1 -1
  40. package/dist/cjs/messages/contextPruning.cjs +17 -43
  41. package/dist/cjs/messages/contextPruning.cjs.map +1 -1
  42. package/dist/cjs/messages/core.cjs +315 -23
  43. package/dist/cjs/messages/core.cjs.map +1 -1
  44. package/dist/cjs/messages/format.cjs +290 -60
  45. package/dist/cjs/messages/format.cjs.map +1 -1
  46. package/dist/cjs/messages/handoffCue.cjs +63 -0
  47. package/dist/cjs/messages/handoffCue.cjs.map +1 -0
  48. package/dist/cjs/messages/index.cjs +4 -1
  49. package/dist/cjs/messages/injected.cjs +60 -0
  50. package/dist/cjs/messages/injected.cjs.map +1 -0
  51. package/dist/cjs/messages/prune.cjs +503 -127
  52. package/dist/cjs/messages/prune.cjs.map +1 -1
  53. package/dist/cjs/run.cjs +80 -7
  54. package/dist/cjs/run.cjs.map +1 -1
  55. package/dist/cjs/session/handlers.cjs +18 -9
  56. package/dist/cjs/session/handlers.cjs.map +1 -1
  57. package/dist/cjs/stream.cjs +35 -10
  58. package/dist/cjs/stream.cjs.map +1 -1
  59. package/dist/cjs/summarization/node.cjs +28 -14
  60. package/dist/cjs/summarization/node.cjs.map +1 -1
  61. package/dist/cjs/tools/ToolNode.cjs +56 -63
  62. package/dist/cjs/tools/ToolNode.cjs.map +1 -1
  63. package/dist/cjs/tools/search/keenable-scraper.cjs +90 -0
  64. package/dist/cjs/tools/search/keenable-scraper.cjs.map +1 -0
  65. package/dist/cjs/tools/search/tool.cjs +9 -1
  66. package/dist/cjs/tools/search/tool.cjs.map +1 -1
  67. package/dist/cjs/tools/toolOutputReferences.cjs +6 -0
  68. package/dist/cjs/tools/toolOutputReferences.cjs.map +1 -1
  69. package/dist/cjs/utils/index.cjs +1 -1
  70. package/dist/cjs/utils/llm.cjs +1 -1
  71. package/dist/cjs/utils/llm.cjs.map +1 -1
  72. package/dist/cjs/utils/tokens.cjs +307 -20
  73. package/dist/cjs/utils/tokens.cjs.map +1 -1
  74. package/dist/cjs/utils/toolContent.cjs +1514 -0
  75. package/dist/cjs/utils/toolContent.cjs.map +1 -0
  76. package/dist/esm/agents/AgentContext.mjs +2 -1
  77. package/dist/esm/agents/AgentContext.mjs.map +1 -1
  78. package/dist/esm/common/constants.mjs +19 -1
  79. package/dist/esm/common/constants.mjs.map +1 -1
  80. package/dist/esm/events.mjs +10 -1
  81. package/dist/esm/events.mjs.map +1 -1
  82. package/dist/esm/graphs/Graph.mjs +798 -116
  83. package/dist/esm/graphs/Graph.mjs.map +1 -1
  84. package/dist/esm/graphs/MultiAgentGraph.mjs +3 -1
  85. package/dist/esm/graphs/MultiAgentGraph.mjs.map +1 -1
  86. package/dist/esm/hooks/HookRegistry.mjs +25 -0
  87. package/dist/esm/hooks/HookRegistry.mjs.map +1 -1
  88. package/dist/esm/hooks/index.mjs +12 -1
  89. package/dist/esm/hooks/index.mjs.map +1 -1
  90. package/dist/esm/hooks/types.mjs +1 -0
  91. package/dist/esm/hooks/types.mjs.map +1 -1
  92. package/dist/esm/langfuse.mjs +9 -1
  93. package/dist/esm/langfuse.mjs.map +1 -1
  94. package/dist/esm/llm/anthropic/utils/message_inputs.mjs +79 -6
  95. package/dist/esm/llm/anthropic/utils/message_inputs.mjs.map +1 -1
  96. package/dist/esm/llm/bedrock/utils/message_inputs.mjs +38 -13
  97. package/dist/esm/llm/bedrock/utils/message_inputs.mjs.map +1 -1
  98. package/dist/esm/llm/google/utils/common.mjs +19 -7
  99. package/dist/esm/llm/google/utils/common.mjs.map +1 -1
  100. package/dist/esm/llm/invoke.mjs +332 -8
  101. package/dist/esm/llm/invoke.mjs.map +1 -1
  102. package/dist/esm/llm/openai/index.mjs +41 -5
  103. package/dist/esm/llm/openai/index.mjs.map +1 -1
  104. package/dist/esm/llm/openai/utils/index.mjs +25 -4
  105. package/dist/esm/llm/openai/utils/index.mjs.map +1 -1
  106. package/dist/esm/llm/openrouter/index.mjs +4 -1
  107. package/dist/esm/llm/openrouter/index.mjs.map +1 -1
  108. package/dist/esm/llm/preempt.mjs +131 -0
  109. package/dist/esm/llm/preempt.mjs.map +1 -0
  110. package/dist/esm/main.mjs +14 -11
  111. package/dist/esm/messages/alternation.mjs +91 -0
  112. package/dist/esm/messages/alternation.mjs.map +1 -0
  113. package/dist/esm/messages/cache.mjs +55 -34
  114. package/dist/esm/messages/cache.mjs.map +1 -1
  115. package/dist/esm/messages/contextPruning.mjs +17 -43
  116. package/dist/esm/messages/contextPruning.mjs.map +1 -1
  117. package/dist/esm/messages/core.mjs +305 -24
  118. package/dist/esm/messages/core.mjs.map +1 -1
  119. package/dist/esm/messages/format.mjs +290 -61
  120. package/dist/esm/messages/format.mjs.map +1 -1
  121. package/dist/esm/messages/handoffCue.mjs +61 -0
  122. package/dist/esm/messages/handoffCue.mjs.map +1 -0
  123. package/dist/esm/messages/index.mjs +4 -1
  124. package/dist/esm/messages/injected.mjs +60 -0
  125. package/dist/esm/messages/injected.mjs.map +1 -0
  126. package/dist/esm/messages/prune.mjs +500 -128
  127. package/dist/esm/messages/prune.mjs.map +1 -1
  128. package/dist/esm/run.mjs +80 -7
  129. package/dist/esm/run.mjs.map +1 -1
  130. package/dist/esm/session/handlers.mjs +19 -10
  131. package/dist/esm/session/handlers.mjs.map +1 -1
  132. package/dist/esm/stream.mjs +34 -11
  133. package/dist/esm/stream.mjs.map +1 -1
  134. package/dist/esm/summarization/node.mjs +28 -14
  135. package/dist/esm/summarization/node.mjs.map +1 -1
  136. package/dist/esm/tools/ToolNode.mjs +56 -63
  137. package/dist/esm/tools/ToolNode.mjs.map +1 -1
  138. package/dist/esm/tools/search/keenable-scraper.mjs +88 -0
  139. package/dist/esm/tools/search/keenable-scraper.mjs.map +1 -0
  140. package/dist/esm/tools/search/tool.mjs +9 -1
  141. package/dist/esm/tools/search/tool.mjs.map +1 -1
  142. package/dist/esm/tools/toolOutputReferences.mjs +6 -0
  143. package/dist/esm/tools/toolOutputReferences.mjs.map +1 -1
  144. package/dist/esm/utils/index.mjs +1 -1
  145. package/dist/esm/utils/llm.mjs +1 -1
  146. package/dist/esm/utils/llm.mjs.map +1 -1
  147. package/dist/esm/utils/tokens.mjs +307 -21
  148. package/dist/esm/utils/tokens.mjs.map +1 -1
  149. package/dist/esm/utils/toolContent.mjs +1503 -0
  150. package/dist/esm/utils/toolContent.mjs.map +1 -0
  151. package/dist/types/common/constants.d.ts +18 -0
  152. package/dist/types/graphs/Graph.d.ts +139 -2
  153. package/dist/types/hooks/HookRegistry.d.ts +15 -0
  154. package/dist/types/hooks/index.d.ts +12 -1
  155. package/dist/types/hooks/types.d.ts +45 -6
  156. package/dist/types/index.d.ts +1 -1
  157. package/dist/types/llm/invoke.d.ts +34 -1
  158. package/dist/types/llm/openai/index.d.ts +4 -0
  159. package/dist/types/llm/openai/utils/index.d.ts +2 -0
  160. package/dist/types/llm/openrouter/index.d.ts +5 -0
  161. package/dist/types/llm/preempt.d.ts +40 -0
  162. package/dist/types/messages/alternation.d.ts +23 -0
  163. package/dist/types/messages/contextPruning.d.ts +2 -1
  164. package/dist/types/messages/core.d.ts +36 -0
  165. package/dist/types/messages/format.d.ts +6 -0
  166. package/dist/types/messages/handoffCue.d.ts +40 -0
  167. package/dist/types/messages/index.d.ts +3 -0
  168. package/dist/types/messages/injected.d.ts +3 -0
  169. package/dist/types/messages/prune.d.ts +16 -12
  170. package/dist/types/run.d.ts +7 -0
  171. package/dist/types/stream.d.ts +14 -0
  172. package/dist/types/tools/ToolNode.d.ts +0 -7
  173. package/dist/types/tools/search/keenable-scraper.d.ts +15 -0
  174. package/dist/types/tools/search/types.d.ts +31 -2
  175. package/dist/types/types/graph.d.ts +8 -1
  176. package/dist/types/types/run.d.ts +65 -0
  177. package/dist/types/types/stream.d.ts +1 -26
  178. package/dist/types/utils/tokens.d.ts +7 -0
  179. package/dist/types/utils/toolContent.d.ts +107 -0
  180. package/package.json +1 -1
  181. package/src/__tests__/stream.eagerEventExecution.test.ts +74 -0
  182. package/src/agents/AgentContext.ts +1 -0
  183. package/src/{splitStream.test.ts → aggregator.test.ts} +59 -666
  184. package/src/common/constants.ts +21 -0
  185. package/src/events.ts +15 -1
  186. package/src/graphs/Graph.ts +1261 -198
  187. package/src/graphs/MultiAgentGraph.ts +6 -1
  188. package/src/graphs/__tests__/Graph.contextOverflow.test.ts +1139 -4
  189. package/src/graphs/__tests__/Graph.preemptSignal.test.ts +126 -0
  190. package/src/hooks/HookRegistry.ts +40 -0
  191. package/src/hooks/__tests__/preemptBoundary.test.ts +152 -0
  192. package/src/hooks/index.ts +16 -2
  193. package/src/hooks/types.ts +47 -3
  194. package/src/index.ts +1 -1
  195. package/src/langfuse.ts +26 -1
  196. package/src/llm/anthropic/utils/message_inputs.ts +158 -12
  197. package/src/llm/anthropic/utils/tool-id-normalization.test.ts +109 -0
  198. package/src/llm/bedrock/utils/message_inputs.test.ts +131 -1
  199. package/src/llm/bedrock/utils/message_inputs.ts +100 -24
  200. package/src/llm/bedrock/utils/toolResultCachePoint.test.ts +15 -0
  201. package/src/llm/google/utils/common.test.ts +75 -9
  202. package/src/llm/google/utils/common.ts +34 -3
  203. package/src/llm/invoke.alternation.test.ts +87 -0
  204. package/src/llm/invoke.handoffCue.test.ts +112 -0
  205. package/src/llm/invoke.test.ts +488 -0
  206. package/src/llm/invoke.ts +611 -8
  207. package/src/llm/openai/index.ts +106 -6
  208. package/src/llm/openai/utils/index.ts +109 -53
  209. package/src/llm/openai/utils/messages.test.ts +330 -1
  210. package/src/llm/openrouter/index.ts +12 -2
  211. package/src/llm/openrouter/reasoning.test.ts +314 -0
  212. package/src/llm/preempt.test.ts +323 -0
  213. package/src/llm/preempt.ts +178 -0
  214. package/src/messages/__tests__/observationMasking.test.ts +93 -2
  215. package/src/messages/alternation.test.ts +212 -0
  216. package/src/messages/alternation.ts +112 -0
  217. package/src/messages/cache.tail.test.ts +193 -0
  218. package/src/messages/cache.test.ts +113 -0
  219. package/src/messages/cache.ts +92 -60
  220. package/src/messages/contextPruning.test.ts +184 -0
  221. package/src/messages/contextPruning.ts +49 -42
  222. package/src/messages/core.ts +653 -40
  223. package/src/messages/ensureThinkingBlock.test.ts +49 -1
  224. package/src/messages/foldToollessToolBlocks.test.ts +163 -5
  225. package/src/messages/format.ts +454 -91
  226. package/src/messages/formatAgentMessages.steer.test.ts +267 -0
  227. package/src/messages/formatAgentMessages.test.ts +604 -14
  228. package/src/messages/formatAgentMessages.tools.test.ts +103 -0
  229. package/src/messages/handoffCue.test.ts +96 -0
  230. package/src/messages/handoffCue.ts +78 -0
  231. package/src/messages/index.ts +3 -0
  232. package/src/messages/injected.test.ts +90 -0
  233. package/src/messages/injected.ts +74 -0
  234. package/src/messages/prune.ts +996 -183
  235. package/src/run.ts +91 -6
  236. package/src/scripts/preempt-probe.ts +330 -0
  237. package/src/scripts/preempt-scenarios.ts +388 -0
  238. package/src/session/handlers.ts +32 -12
  239. package/src/specs/handoffCue.test.ts +165 -0
  240. package/src/specs/langfuse-callbacks.test.ts +352 -2
  241. package/src/specs/preemptSeal.test.ts +309 -0
  242. package/src/specs/prune.test.ts +1083 -6
  243. package/src/specs/summarization-unit.test.ts +105 -0
  244. package/src/specs/tokens.test.ts +609 -32
  245. package/src/stream.dispatch.test.ts +63 -0
  246. package/src/stream.ts +59 -23
  247. package/src/summarization/__tests__/node.test.ts +77 -0
  248. package/src/summarization/node.ts +46 -18
  249. package/src/tools/ToolNode.ts +150 -99
  250. package/src/tools/__tests__/ToolNode.onResultCompletion.test.ts +148 -1
  251. package/src/tools/__tests__/ToolNode.outputReferences.test.ts +112 -3
  252. package/src/tools/__tests__/annotateMessagesForLLM.test.ts +32 -0
  253. package/src/tools/__tests__/directToolHooks.test.ts +255 -7
  254. package/src/tools/search/keenable-scraper.test.ts +153 -0
  255. package/src/tools/search/keenable-scraper.ts +137 -0
  256. package/src/tools/search/tool.ts +13 -2
  257. package/src/tools/search/types.ts +50 -3
  258. package/src/tools/toolOutputReferences.ts +6 -0
  259. package/src/types/graph.ts +12 -1
  260. package/src/types/run.ts +67 -0
  261. package/src/types/stream.ts +1 -42
  262. package/src/utils/llm.test.ts +18 -0
  263. package/src/utils/llm.ts +4 -1
  264. package/src/utils/tokens.ts +586 -31
  265. package/src/utils/toolContent.test.ts +1432 -0
  266. package/src/utils/toolContent.ts +2707 -0
  267. package/dist/cjs/splitStream.cjs +0 -151
  268. package/dist/cjs/splitStream.cjs.map +0 -1
  269. package/dist/esm/splitStream.mjs +0 -150
  270. package/dist/esm/splitStream.mjs.map +0 -1
  271. package/dist/types/mockStream.d.ts +0 -32
  272. package/dist/types/splitStream.d.ts +0 -37
  273. package/src/mockStream.ts +0 -99
  274. package/src/splitStream.ts +0 -234
@@ -0,0 +1 @@
1
+ {"version":3,"file":"toolContent.mjs","names":[],"sources":["../../../src/utils/toolContent.ts"],"sourcesContent":["import { isProxy } from 'node:util/types';\nimport { ToolMessage, type BaseMessage } from '@langchain/core/messages';\nimport {\n HARD_MAX_TOTAL_TOOL_OUTPUT_SIZE,\n truncateToolResultContent,\n} from './truncation';\n\ntype ToolContent = BaseMessage['content'];\ntype ToolContentBlock = Exclude<ToolContent, string>[number];\ntype TextToolContentBlock = ToolContentBlock & { type: 'text'; text: string };\n\nconst ATOMIC_CONTENT_TYPES = new Set([\n 'audio',\n 'computer_screenshot',\n 'document',\n 'file',\n 'image',\n 'image_file',\n 'image_url',\n 'input_audio',\n 'input_image',\n 'media',\n 'resource',\n 'resource_link',\n 'video',\n 'video_url',\n]);\nconst MAX_TOOL_CONTENT_TYPE_CHARS = 256;\nconst MAX_PROVIDER_IMAGE_URL_CHARS = 16_384;\nconst MAX_PROVIDER_FILE_ID_CHARS = 4_096;\n\nconst PROVIDER_NATIVE_TOOL_RESULT_TYPES = new Set([\n 'search_result',\n 'server_tool_call_result',\n 'tool_result',\n 'toolResponse',\n 'web_search_result',\n 'web_search_tool_result',\n]);\n\n/**\n * Serializes values that providers render as JSON without throwing on values\n * such as bigint or circular diagnostic metadata.\n */\nexport function serializeStructuredValue(value: unknown): string {\n return serializeStructuredValueBounded(value, Number.MAX_SAFE_INTEGER)\n .content;\n}\n\nconst SERIALIZATION_CHUNK_SIZE = 4_096;\nconst MAX_STRUCTURED_SERIALIZATION_DEPTH = 200;\nconst MAX_STRUCTURED_SERIALIZATION_WORK = 1_000_000;\nconst MAX_STRUCTURED_CHARACTER_WORK = 1_000_000;\nconst MAX_STRUCTURED_PROPERTY_CACHE_ENTRIES = 10_000;\nconst PROXY_VALUE_PLACEHOLDER = '[Proxy value omitted]';\nconst CHARACTER_WORK_PLACEHOLDER =\n '[truncated: character traversal limit exceeded]';\n\ntype StructuredWorkState = {\n remaining: number;\n characterRemaining: number;\n exceeded: boolean;\n failurePlaceholder?: string;\n propertyCache: WeakMap<object, Map<string, unknown>>;\n propertyCacheEntries: number;\n};\n\nfunction createStructuredWorkState(): StructuredWorkState {\n return {\n remaining: MAX_STRUCTURED_SERIALIZATION_WORK,\n characterRemaining: MAX_STRUCTURED_CHARACTER_WORK,\n exceeded: false,\n propertyCache: new WeakMap<object, Map<string, unknown>>(),\n propertyCacheEntries: 0,\n };\n}\n\nfunction consumeStructuredWork(state: StructuredWorkState): boolean {\n if (state.remaining <= 0) {\n state.exceeded = true;\n state.failurePlaceholder ??= '[Traversal limit exceeded]';\n return false;\n }\n state.remaining--;\n return true;\n}\n\nfunction consumeStructuredCharacterWork(state: StructuredWorkState): boolean {\n if (state.characterRemaining <= 0) {\n state.exceeded = true;\n state.failurePlaceholder ??= CHARACTER_WORK_PLACEHOLDER;\n return false;\n }\n state.characterRemaining--;\n return true;\n}\n\nfunction hasExceededStructuredWork(state: StructuredWorkState): boolean {\n return state.exceeded;\n}\n\nfunction conservativeStructuredLength(limit: number): number {\n return limit >= Number.MAX_SAFE_INTEGER ? Number.MAX_SAFE_INTEGER : limit + 1;\n}\n\nfunction jsonStringLength(\n value: string,\n limit: number,\n work: StructuredWorkState\n): number {\n let length = 2;\n for (let i = 0; i < value.length; i++) {\n if (!consumeStructuredCharacterWork(work)) {\n return conservativeStructuredLength(limit);\n }\n const code = value.charCodeAt(i);\n if (\n code === 0x08 ||\n code === 0x09 ||\n code === 0x0a ||\n code === 0x0c ||\n code === 0x0d ||\n code === 0x22 ||\n code === 0x5c\n ) {\n length += 2;\n } else if (code < 0x20) {\n length += 6;\n } else if (code >= 0xd800 && code <= 0xdbff) {\n if (!consumeStructuredCharacterWork(work)) {\n return conservativeStructuredLength(limit);\n }\n const next = value.charCodeAt(i + 1);\n if (next >= 0xdc00 && next <= 0xdfff) {\n length += 2;\n i++;\n } else {\n length += 6;\n }\n } else if (code >= 0xdc00 && code <= 0xdfff) {\n length += 6;\n } else {\n length++;\n }\n if (length > limit) {\n return conservativeStructuredLength(limit);\n }\n }\n return length;\n}\n\ntype NativeDateRead = { matched: true; time: number } | { matched: false };\n\nfunction readNativeArrayBufferByteLength(value: unknown): number | undefined {\n if (\n value == null ||\n typeof value !== 'object' ||\n NATIVE_ARRAY_BUFFER_BYTE_LENGTH_GETTER == null\n ) {\n return undefined;\n }\n try {\n return NATIVE_ARRAY_BUFFER_BYTE_LENGTH_GETTER.call(value) as number;\n } catch {\n return undefined;\n }\n}\n\nfunction readNativeDate(value: unknown): NativeDateRead {\n if (value == null || typeof value !== 'object') {\n return { matched: false };\n }\n try {\n return { matched: true, time: NATIVE_DATE_GET_TIME.call(value) };\n } catch {\n return { matched: false };\n }\n}\n\nfunction readNativeBoxedString(value: object): string | undefined {\n try {\n return String.prototype.valueOf.call(value);\n } catch {\n return undefined;\n }\n}\n\nfunction readNativeBoxedNumber(value: object): number | undefined {\n try {\n return Number.prototype.valueOf.call(value);\n } catch {\n return undefined;\n }\n}\n\nfunction readNativeBoxedBoolean(value: object): boolean | undefined {\n try {\n return Boolean.prototype.valueOf.call(value);\n } catch {\n return undefined;\n }\n}\n\nfunction estimateStructuredChars(\n value: unknown,\n limit = Number.MAX_SAFE_INTEGER,\n ancestors: object[] = [],\n work = createStructuredWorkState(),\n depth = 0\n): number {\n if (hasExceededStructuredWork(work)) {\n return conservativeStructuredLength(limit);\n }\n if (typeof value === 'string') {\n return jsonStringLength(value, limit, work);\n }\n if (typeof value === 'bigint') {\n return jsonStringLength(value.toString(), limit, work);\n }\n if (typeof value === 'number') {\n return Number.isFinite(value) ? String(value === 0 ? 0 : value).length : 4;\n }\n if (typeof value === 'boolean' || value == null) {\n return String(value).length;\n }\n if (isProxy(value)) {\n work.exceeded = true;\n work.failurePlaceholder = PROXY_VALUE_PLACEHOLDER;\n return conservativeStructuredLength(limit);\n }\n if (typeof value === 'undefined' || typeof value === 'function') {\n return 4;\n }\n if (typeof value !== 'object') {\n return jsonStringLength(String(value), limit, work);\n }\n\n const valueIsArray = isArray(value);\n if (!valueIsArray) {\n const arrayBufferByteLength = readNativeArrayBufferByteLength(value);\n if (arrayBufferByteLength != null) {\n if (!isSafeNativeArrayBuffer(value as ArrayBuffer)) {\n work.exceeded = true;\n return conservativeStructuredLength(limit);\n }\n return Math.min(\n limit + 1,\n Math.ceil((arrayBufferByteLength * 4) / 3) + 32\n );\n }\n if (ArrayBuffer.isView(value)) {\n const view = readSafeNativeArrayBufferView(\n value,\n undefined,\n undefined,\n false\n );\n if (view == null) {\n work.exceeded = true;\n return conservativeStructuredLength(limit);\n }\n return Math.min(limit + 1, Math.ceil((view.byteLength * 4) / 3) + 32);\n }\n const date = readNativeDate(value);\n if (date.matched) {\n if (!isSafeNativeDate(value as Date)) {\n work.exceeded = true;\n return conservativeStructuredLength(limit);\n }\n return Number.isFinite(date.time)\n ? jsonStringLength(Date.prototype.toISOString.call(value), limit, work)\n : 4;\n }\n const boxedString = readNativeBoxedString(value);\n if (boxedString != null) {\n return jsonStringLength(boxedString, limit, work);\n }\n const boxedNumber = readNativeBoxedNumber(value);\n if (boxedNumber != null) {\n return Number.isFinite(boxedNumber)\n ? String(boxedNumber === 0 ? 0 : boxedNumber).length\n : 4;\n }\n const boxedBoolean = readNativeBoxedBoolean(value);\n if (boxedBoolean != null) {\n return String(boxedBoolean).length;\n }\n let prototype: object | null;\n try {\n prototype = Object.getPrototypeOf(value) as object | null;\n } catch {\n work.exceeded = true;\n return conservativeStructuredLength(limit);\n }\n if (\n isProxy(prototype) ||\n (prototype !== Object.prototype && prototype !== null)\n ) {\n work.exceeded = true;\n return conservativeStructuredLength(limit);\n }\n } else {\n let prototype: object | null;\n try {\n prototype = Object.getPrototypeOf(value) as object | null;\n } catch {\n work.exceeded = true;\n return conservativeStructuredLength(limit);\n }\n if (\n isProxy(prototype) ||\n (prototype !== Array.prototype && prototype !== null)\n ) {\n work.exceeded = true;\n return conservativeStructuredLength(limit);\n }\n }\n if (depth >= MAX_STRUCTURED_SERIALIZATION_DEPTH) {\n return jsonStringLength('[Max serialization depth]', limit, work);\n }\n if (ancestors.includes(value)) {\n return 12;\n }\n\n ancestors.push(value);\n let length = 2;\n try {\n if (valueIsArray) {\n const arrayLength = readStructuredArrayLength(value, work);\n if (arrayLength == null) {\n return conservativeStructuredLength(limit);\n }\n for (let i = 0; i < arrayLength && length <= limit; i++) {\n if (!consumeStructuredWork(work)) {\n return conservativeStructuredLength(limit);\n }\n if (i > 0) {\n length++;\n }\n length += estimateStructuredChars(\n readStructuredProperty(value, i, work),\n Math.max(0, limit - length),\n ancestors,\n work,\n depth + 1\n );\n }\n } else {\n let emitted = 0;\n for (const key in value) {\n if (!consumeStructuredWork(work)) {\n return conservativeStructuredLength(limit);\n }\n if (!Object.prototype.propertyIsEnumerable.call(value, key)) {\n continue;\n }\n if (length > limit) {\n break;\n }\n const nested = readStructuredProperty(\n value as Record<string, unknown>,\n key,\n work\n );\n if (\n typeof nested === 'undefined' ||\n typeof nested === 'function' ||\n typeof nested === 'symbol'\n ) {\n continue;\n }\n if (emitted > 0) {\n length++;\n }\n length += jsonStringLength(key, Math.max(0, limit - length), work) + 1;\n length += estimateStructuredChars(\n nested,\n Math.max(0, limit - length),\n ancestors,\n work,\n depth + 1\n );\n emitted++;\n }\n }\n } catch {\n work.exceeded = true;\n return conservativeStructuredLength(limit);\n } finally {\n ancestors.pop();\n }\n if (hasExceededStructuredWork(work)) {\n return conservativeStructuredLength(limit);\n }\n return Math.min(limit + 1, length);\n}\n\ntype StructuredSerializationCollector = {\n totalChars: number;\n prefix: SegmentedStringBuffer;\n suffix: SegmentedStringBuffer;\n prefixLimit: number;\n suffixLimit: number;\n work: StructuredWorkState;\n};\n\ntype SegmentedStringBuffer = {\n segments: string[];\n head: number;\n pending: string[];\n pendingChars: number;\n length: number;\n};\n\nexport type BoundedStructuredSerialization = {\n /** Provider-facing head/tail preview, bounded by `maxChars`. */\n content: string;\n /** Exact serialized prefix up to the defensive traversal-work ceiling. */\n prefix: string;\n /** Exact length, or `Number.MAX_SAFE_INTEGER` when traversal was capped. */\n originalChars: number;\n truncated: boolean;\n};\n\nfunction normalizeCharLimit(limit: number): number {\n return Number.isFinite(limit)\n ? Math.max(0, Math.floor(limit))\n : Number.MAX_SAFE_INTEGER;\n}\n\nfunction createSegmentedStringBuffer(): SegmentedStringBuffer {\n return {\n segments: [],\n head: 0,\n pending: [],\n pendingChars: 0,\n length: 0,\n };\n}\n\nfunction flushSegmentedStringBuffer(buffer: SegmentedStringBuffer): void {\n if (buffer.pendingChars === 0) {\n return;\n }\n buffer.segments.push(buffer.pending.join(''));\n buffer.pending = [];\n buffer.pendingChars = 0;\n}\n\nfunction appendToSegmentedStringBuffer(\n buffer: SegmentedStringBuffer,\n chunk: string\n): void {\n if (chunk.length === 0) {\n return;\n }\n buffer.pending.push(chunk);\n buffer.pendingChars += chunk.length;\n buffer.length += chunk.length;\n if (buffer.pendingChars >= SERIALIZATION_CHUNK_SIZE) {\n flushSegmentedStringBuffer(buffer);\n }\n}\n\nfunction trimSegmentedStringBufferStart(\n buffer: SegmentedStringBuffer,\n chars: number\n): void {\n let remaining = Math.min(chars, buffer.length);\n if (remaining <= 0) {\n return;\n }\n flushSegmentedStringBuffer(buffer);\n while (remaining > 0 && buffer.head < buffer.segments.length) {\n const segment = buffer.segments[buffer.head];\n if (segment.length <= remaining) {\n remaining -= segment.length;\n buffer.length -= segment.length;\n buffer.head++;\n } else {\n buffer.segments[buffer.head] = segment.slice(remaining);\n buffer.length -= remaining;\n remaining = 0;\n }\n }\n if (buffer.head >= 1_024 && buffer.head * 2 >= buffer.segments.length) {\n buffer.segments = buffer.segments.slice(buffer.head);\n buffer.head = 0;\n }\n}\n\nfunction materializeSegmentedStringBuffer(\n buffer: SegmentedStringBuffer\n): string {\n const segments = buffer.segments.slice(buffer.head);\n if (buffer.pendingChars > 0) {\n segments.push(buffer.pending.join(''));\n }\n return segments.join('');\n}\n\nfunction appendSerializedChunk(\n collector: StructuredSerializationCollector,\n chunk: string\n): void {\n if (chunk.length === 0) {\n return;\n }\n\n collector.totalChars += chunk.length;\n\n const prefixRemaining = collector.prefixLimit - collector.prefix.length;\n if (prefixRemaining > 0) {\n appendToSegmentedStringBuffer(\n collector.prefix,\n chunk.slice(0, prefixRemaining)\n );\n }\n\n if (collector.suffixLimit <= 0) {\n return;\n }\n appendToSegmentedStringBuffer(collector.suffix, chunk);\n if (\n collector.suffix.length >=\n collector.suffixLimit + SERIALIZATION_CHUNK_SIZE\n ) {\n trimSegmentedStringBufferStart(\n collector.suffix,\n collector.suffix.length - collector.suffixLimit\n );\n }\n}\n\nfunction appendJsonSafeRange(\n collector: StructuredSerializationCollector,\n value: string,\n start: number,\n end: number\n): void {\n let offset = start;\n while (offset < end) {\n let chunkEnd = Math.min(end, offset + SERIALIZATION_CHUNK_SIZE);\n if (\n chunkEnd < end &&\n chunkEnd > offset &&\n value.charCodeAt(chunkEnd - 1) >= 0xd800 &&\n value.charCodeAt(chunkEnd - 1) <= 0xdbff &&\n value.charCodeAt(chunkEnd) >= 0xdc00 &&\n value.charCodeAt(chunkEnd) <= 0xdfff\n ) {\n chunkEnd--;\n }\n appendSerializedChunk(collector, value.slice(offset, chunkEnd));\n offset = chunkEnd;\n }\n}\n\n/**\n * Emits one JSON string incrementally. Calling JSON.stringify on the complete\n * string would allocate an escaped copy before the output cap could apply.\n */\nfunction appendJsonString(\n collector: StructuredSerializationCollector,\n value: string\n): void {\n if (collector.work.exceeded) {\n appendSerializedChunk(\n collector,\n `\"${collector.work.failurePlaceholder ?? CHARACTER_WORK_PLACEHOLDER}\"`\n );\n return;\n }\n appendSerializedChunk(collector, '\"');\n let safeStart = 0;\n\n for (let i = 0; i < value.length; i++) {\n if (!consumeStructuredCharacterWork(collector.work)) {\n appendJsonSafeRange(collector, value, safeStart, i);\n appendSerializedChunk(collector, `${CHARACTER_WORK_PLACEHOLDER}\"`);\n return;\n }\n const code = value.charCodeAt(i);\n let escaped: string | undefined;\n switch (code) {\n case 0x08:\n escaped = '\\\\b';\n break;\n case 0x09:\n escaped = '\\\\t';\n break;\n case 0x0a:\n escaped = '\\\\n';\n break;\n case 0x0c:\n escaped = '\\\\f';\n break;\n case 0x0d:\n escaped = '\\\\r';\n break;\n case 0x22:\n escaped = '\\\\\"';\n break;\n case 0x5c:\n escaped = '\\\\\\\\';\n break;\n default:\n if (code < 0x20) {\n escaped = `\\\\u${code.toString(16).padStart(4, '0')}`;\n } else if (code >= 0xd800 && code <= 0xdbff) {\n if (!consumeStructuredCharacterWork(collector.work)) {\n appendJsonSafeRange(collector, value, safeStart, i);\n appendSerializedChunk(collector, `${CHARACTER_WORK_PLACEHOLDER}\"`);\n return;\n }\n const next = value.charCodeAt(i + 1);\n if (next >= 0xdc00 && next <= 0xdfff) {\n i++;\n } else {\n escaped = `\\\\u${code.toString(16).padStart(4, '0')}`;\n }\n } else if (code >= 0xdc00 && code <= 0xdfff) {\n escaped = `\\\\u${code.toString(16).padStart(4, '0')}`;\n }\n }\n\n if (escaped != null) {\n appendJsonSafeRange(collector, value, safeStart, i);\n appendSerializedChunk(collector, escaped);\n safeStart = i + 1;\n }\n }\n appendJsonSafeRange(collector, value, safeStart, value.length);\n appendSerializedChunk(collector, '\"');\n}\n\nfunction readStructuredProperty(\n value: Record<string, unknown> | unknown[],\n key: string | number,\n work: StructuredWorkState\n): unknown {\n const normalizedKey = String(key);\n // Callers still consume traversal work for every occurrence. This bounded\n // cache only avoids re-reading the same descriptor through shared references.\n const cachedProperties = work.propertyCache.get(value);\n if (cachedProperties != null && cachedProperties.has(normalizedKey)) {\n return cachedProperties.get(normalizedKey);\n }\n\n try {\n const descriptor = Object.getOwnPropertyDescriptor(value, normalizedKey);\n let propertyValue: unknown;\n if (descriptor == null) {\n propertyValue = undefined;\n } else if ('value' in descriptor) {\n propertyValue = descriptor.value;\n } else {\n propertyValue = '[Property accessor omitted]';\n }\n if (work.propertyCacheEntries < MAX_STRUCTURED_PROPERTY_CACHE_ENTRIES) {\n const properties = cachedProperties ?? new Map<string, unknown>();\n if (cachedProperties == null) {\n work.propertyCache.set(value, properties);\n }\n properties.set(normalizedKey, propertyValue);\n work.propertyCacheEntries++;\n }\n return propertyValue;\n } catch {\n work.exceeded = true;\n work.remaining = 0;\n return '[Unreadable property omitted]';\n }\n}\n\nfunction readStructuredArrayLength(\n value: unknown[],\n work: StructuredWorkState\n): number | undefined {\n const length = readStructuredProperty(value, 'length', work);\n if (\n typeof length === 'number' &&\n Number.isSafeInteger(length) &&\n length >= 0\n ) {\n return length;\n }\n work.exceeded = true;\n work.remaining = 0;\n return undefined;\n}\n\n/**\n * Provider-neutral JSON writer which deliberately does not invoke `toJSON` or\n * property accessors. Native `JSON.stringify` can invoke both before a replacer\n * can bound their output.\n */\nfunction appendStructuredValue(\n collector: StructuredSerializationCollector,\n value: unknown,\n ancestors: Set<object>,\n depth: number,\n position: 'top' | 'array' | 'object'\n): boolean {\n if (collector.work.exceeded) {\n appendSerializedChunk(\n collector,\n `\"${collector.work.failurePlaceholder ?? CHARACTER_WORK_PLACEHOLDER}\"`\n );\n return true;\n }\n if (typeof value === 'string') {\n appendJsonString(collector, value);\n return true;\n }\n if (typeof value === 'bigint') {\n appendJsonString(collector, value.toString());\n return true;\n }\n if (typeof value === 'number') {\n appendSerializedChunk(\n collector,\n Number.isFinite(value) ? String(value === 0 ? 0 : value) : 'null'\n );\n return true;\n }\n if (typeof value === 'boolean' || value === null) {\n appendSerializedChunk(collector, String(value));\n return true;\n }\n if (isProxy(value)) {\n appendSerializedChunk(collector, `\"${PROXY_VALUE_PLACEHOLDER}\"`);\n collector.work.exceeded = true;\n collector.work.failurePlaceholder = PROXY_VALUE_PLACEHOLDER;\n return true;\n }\n if (\n typeof value === 'undefined' ||\n typeof value === 'function' ||\n typeof value === 'symbol'\n ) {\n if (position === 'object') {\n return false;\n }\n if (position === 'array') {\n appendSerializedChunk(collector, 'null');\n } else if (typeof value === 'undefined') {\n appendSerializedChunk(collector, 'undefined');\n } else {\n appendJsonString(\n collector,\n typeof value === 'function' ? '[Function]' : String(value)\n );\n }\n return true;\n }\n const valueIsArray = isArray(value);\n if (!valueIsArray) {\n const arrayBufferByteLength = readNativeArrayBufferByteLength(value);\n if (arrayBufferByteLength != null) {\n if (!isSafeNativeArrayBuffer(value as ArrayBuffer)) {\n appendSerializedChunk(collector, '\"[Unsafe ArrayBuffer omitted]\"');\n collector.work.exceeded = true;\n return true;\n }\n appendJsonString(\n collector,\n `[ArrayBuffer: ${arrayBufferByteLength} bytes]`\n );\n return true;\n }\n if (ArrayBuffer.isView(value)) {\n const view = readSafeNativeArrayBufferView(\n value,\n undefined,\n undefined,\n false\n );\n if (view == null) {\n appendSerializedChunk(collector, '\"[Unsafe ArrayBufferView omitted]\"');\n collector.work.exceeded = true;\n return true;\n }\n appendJsonString(collector, `[${view.name}: ${view.byteLength} bytes]`);\n return true;\n }\n const date = readNativeDate(value);\n if (date.matched) {\n if (!isSafeNativeDate(value as Date)) {\n appendSerializedChunk(collector, '\"[Unsafe Date omitted]\"');\n collector.work.exceeded = true;\n } else if (!Number.isFinite(date.time)) {\n appendSerializedChunk(collector, 'null');\n } else {\n appendJsonString(collector, Date.prototype.toISOString.call(value));\n }\n return true;\n }\n const boxedString = readNativeBoxedString(value);\n if (boxedString != null) {\n appendJsonString(collector, boxedString);\n return true;\n }\n const boxedNumber = readNativeBoxedNumber(value);\n if (boxedNumber != null) {\n appendSerializedChunk(\n collector,\n Number.isFinite(boxedNumber)\n ? String(boxedNumber === 0 ? 0 : boxedNumber)\n : 'null'\n );\n return true;\n }\n const boxedBoolean = readNativeBoxedBoolean(value);\n if (boxedBoolean != null) {\n appendSerializedChunk(collector, String(boxedBoolean));\n return true;\n }\n let prototype: object | null;\n try {\n prototype = Object.getPrototypeOf(value) as object | null;\n } catch {\n appendSerializedChunk(collector, '\"[Unreadable object omitted]\"');\n collector.work.exceeded = true;\n return true;\n }\n if (\n isProxy(prototype) ||\n (prototype !== Object.prototype && prototype !== null)\n ) {\n appendSerializedChunk(collector, '\"[Unsupported object omitted]\"');\n collector.work.exceeded = true;\n return true;\n }\n } else {\n let prototype: object | null;\n try {\n prototype = Object.getPrototypeOf(value) as object | null;\n } catch {\n appendSerializedChunk(collector, '\"[Unreadable array omitted]\"');\n collector.work.exceeded = true;\n return true;\n }\n if (\n isProxy(prototype) ||\n (prototype !== Array.prototype && prototype !== null)\n ) {\n appendSerializedChunk(collector, '\"[Unsafe array omitted]\"');\n collector.work.exceeded = true;\n return true;\n }\n }\n if (depth >= MAX_STRUCTURED_SERIALIZATION_DEPTH) {\n appendJsonString(collector, '[Max serialization depth]');\n return true;\n }\n if (ancestors.has(value)) {\n appendJsonString(collector, '[Circular]');\n return true;\n }\n\n ancestors.add(value);\n try {\n if (valueIsArray) {\n const arrayLength = readStructuredArrayLength(value, collector.work);\n if (arrayLength == null) {\n appendJsonString(collector, '[Unreadable array omitted]');\n return true;\n }\n appendSerializedChunk(collector, '[');\n for (let i = 0; i < arrayLength; i++) {\n if (!consumeStructuredWork(collector.work)) {\n if (i > 0) {\n appendSerializedChunk(collector, ',');\n }\n appendJsonString(\n collector,\n `[Traversal limit exceeded: ${arrayLength - i} array entries omitted]`\n );\n break;\n }\n if (i > 0) {\n appendSerializedChunk(collector, ',');\n }\n appendStructuredValue(\n collector,\n readStructuredProperty(value, i, collector.work),\n ancestors,\n depth + 1,\n 'array'\n );\n }\n appendSerializedChunk(collector, ']');\n return true;\n }\n\n appendSerializedChunk(collector, '{');\n let emitted = 0;\n // `Object.keys()` allocates an array proportional to the complete object\n // before either output limit applies. Filter a streaming `for…in` walk to\n // retain JSON's own-enumerable-key semantics without that extra array.\n for (const key in value) {\n if (!consumeStructuredWork(collector.work)) {\n if (emitted > 0) {\n appendSerializedChunk(collector, ',');\n }\n appendSerializedChunk(\n collector,\n '\"_truncated\":\"[Traversal limit exceeded]\"'\n );\n break;\n }\n if (!Object.prototype.propertyIsEnumerable.call(value, key)) {\n continue;\n }\n const nested = readStructuredProperty(\n value as Record<string, unknown>,\n key,\n collector.work\n );\n if (\n typeof nested === 'undefined' ||\n typeof nested === 'function' ||\n typeof nested === 'symbol'\n ) {\n continue;\n }\n if (emitted > 0) {\n appendSerializedChunk(collector, ',');\n }\n appendJsonString(collector, key);\n appendSerializedChunk(collector, ':');\n appendStructuredValue(collector, nested, ancestors, depth + 1, 'object');\n emitted++;\n }\n appendSerializedChunk(collector, '}');\n return true;\n } finally {\n ancestors.delete(value);\n }\n}\n\nfunction formatBoundedStructuredContent(\n collector: StructuredSerializationCollector,\n maxChars: number,\n prefix: string,\n suffix: string\n): string {\n if (collector.totalChars <= maxChars) {\n return prefix.slice(0, collector.totalChars);\n }\n\n const indicator = collector.work.exceeded\n ? '\\n\\n… [truncated: safe traversal limit exceeded] …\\n\\n'\n : `\\n\\n… [truncated: ${collector.totalChars} chars exceeded ` +\n `${maxChars} limit] …\\n\\n`;\n const available = maxChars - indicator.length;\n if (available <= 0) {\n return prefix.slice(0, maxChars);\n }\n if (available < 200) {\n return prefix.slice(0, available) + indicator.trimEnd();\n }\n\n const headSize = Math.ceil(available * 0.7);\n const tailSize = available - headSize;\n let headEnd = headSize;\n const headNewline = prefix.lastIndexOf('\\n', headSize);\n if (headNewline > headSize - 200 && headNewline > 0) {\n headEnd = headNewline;\n }\n\n let tailStart = Math.max(0, suffix.length - tailSize);\n const tailNewline = suffix.indexOf('\\n', tailStart);\n if (tailNewline > 0 && tailNewline < tailStart + 200) {\n tailStart = tailNewline + 1;\n }\n\n return prefix.slice(0, headEnd) + indicator + suffix.slice(tailStart);\n}\n\n/**\n * Serializes structured output while retaining at most the requested provider\n * preview and registry prefix. The traversal never calls `toJSON` and never\n * materializes the complete serialized string when it exceeds those limits.\n *\n * `prefixChars` is useful for the tool-output registry: it receives the exact\n * serialized prefix up to `registry.perOutputLimit`, while `content` retains\n * the provider-facing head/tail truncation behavior at `maxChars`. Property\n * accessors are represented by a fixed placeholder instead of being invoked.\n */\nexport function serializeStructuredValueBounded(\n value: unknown,\n maxChars: number,\n prefixChars = 0,\n work = createStructuredWorkState()\n): BoundedStructuredSerialization {\n const normalizedMaxChars = normalizeCharLimit(maxChars);\n const normalizedPrefixChars = normalizeCharLimit(prefixChars);\n const prefixLimit = Math.max(normalizedMaxChars, normalizedPrefixChars);\n const collector: StructuredSerializationCollector = {\n totalChars: 0,\n prefix: createSegmentedStringBuffer(),\n suffix: createSegmentedStringBuffer(),\n prefixLimit,\n suffixLimit:\n normalizedMaxChars === Number.MAX_SAFE_INTEGER ? 0 : normalizedMaxChars,\n work,\n };\n\n try {\n appendStructuredValue(collector, value, new Set<object>(), 0, 'top');\n } catch {\n collector.totalChars = 0;\n collector.prefix = createSegmentedStringBuffer();\n collector.suffix = createSegmentedStringBuffer();\n collector.work.exceeded = true;\n appendSerializedChunk(collector, '\"[Unserializable structured value]\"');\n }\n\n const prefix = materializeSegmentedStringBuffer(collector.prefix);\n const suffix = materializeSegmentedStringBuffer(collector.suffix);\n const originalChars = collector.work.exceeded\n ? Number.MAX_SAFE_INTEGER\n : collector.totalChars;\n return {\n content: formatBoundedStructuredContent(\n collector,\n normalizedMaxChars,\n prefix,\n suffix\n ),\n prefix: prefix.slice(0, normalizedPrefixChars),\n originalChars,\n truncated:\n collector.work.exceeded || collector.totalChars > normalizedMaxChars,\n };\n}\n\nfunction serializeStructuredValueWithinLimit(\n value: unknown,\n maxChars: number,\n work = createStructuredWorkState()\n): string {\n return serializeStructuredValueBounded(value, maxChars, 0, work).content;\n}\n\nfunction isTextBlockUnchecked(value: unknown): value is TextToolContentBlock {\n if (!isRecord(value) || isProxy(value)) {\n return false;\n }\n try {\n const prototype = Object.getPrototypeOf(value);\n if (prototype !== Object.prototype && prototype !== null) {\n return false;\n }\n const keys = Object.keys(value);\n if (keys.length !== 2 || !keys.includes('type') || !keys.includes('text')) {\n return false;\n }\n const type = readOwnEnumerableDataProperty(value, 'type');\n const text = readOwnEnumerableDataProperty(value, 'text');\n return (\n type.found &&\n type.value === 'text' &&\n text.found &&\n typeof text.value === 'string'\n );\n } catch {\n return false;\n }\n}\n\nfunction isArray(value: unknown): value is unknown[] {\n try {\n return Array.isArray(value);\n } catch {\n return false;\n }\n}\n\nfunction getDenseTextBlockArrayLength(content: unknown[]): number | undefined {\n if (isProxy(content)) {\n return undefined;\n }\n const validation = createToolBlockClassificationContext();\n const containerWork = { value: MAX_ATOMIC_VALIDATION_WORK };\n let contentLength: number;\n try {\n const prototype = Object.getPrototypeOf(content);\n if (\n (prototype !== Array.prototype && prototype !== null) ||\n hasPotentiallyCallableToJSON(\n content,\n containerWork,\n validation.totalRemaining\n )\n ) {\n return undefined;\n }\n contentLength = content.length;\n } catch {\n return undefined;\n }\n if (\n contentLength === 0 ||\n contentLength > MAX_STRUCTURED_SERIALIZATION_WORK\n ) {\n return undefined;\n }\n\n let length = contentLength - 1;\n try {\n for (let i = 0; i < contentLength; i++) {\n const descriptor = Object.getOwnPropertyDescriptor(content, String(i));\n if (descriptor == null || !('value' in descriptor)) {\n return undefined;\n }\n const block = descriptor.value;\n if (\n classifyToolContentBlock(block, validation) !== TOOL_BLOCK_TEXT ||\n validation.totalRemaining.value <= 0\n ) {\n return undefined;\n }\n const text = readOwnEnumerableDataProperty(block, 'text');\n length += typeof text.value === 'string' ? text.value.length : 0;\n if (length >= Number.MAX_SAFE_INTEGER) {\n return Number.MAX_SAFE_INTEGER;\n }\n }\n } catch {\n return undefined;\n }\n return length;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value != null;\n}\n\ntype OwnDataProperty =\n | { found: true; value: unknown }\n | { found: false; value?: never };\n\nfunction readOwnEnumerableDataProperty(\n record: Record<string, unknown>,\n key: string\n): OwnDataProperty {\n try {\n const descriptor = Object.getOwnPropertyDescriptor(record, key);\n if (\n descriptor == null ||\n descriptor.enumerable !== true ||\n !('value' in descriptor)\n ) {\n return { found: false };\n }\n return { found: true, value: descriptor.value };\n } catch {\n return { found: false };\n }\n}\n\nfunction hasString(record: Record<string, unknown>, key: string): boolean {\n const property = readOwnEnumerableDataProperty(record, key);\n return (\n property.found &&\n typeof property.value === 'string' &&\n property.value !== ''\n );\n}\n\nfunction hasValue(record: Record<string, unknown>, key: string): boolean {\n const property = readOwnEnumerableDataProperty(record, key);\n return property.found && property.value !== undefined;\n}\n\nfunction isStringPayload(value: unknown): boolean {\n return typeof value === 'string' && value.length > 0;\n}\n\nfunction isBinaryPayload(value: unknown): boolean {\n if (typeof value === 'string') {\n return value.length > 0;\n }\n if (isArray(value)) {\n return false;\n }\n const arrayBufferByteLength = readNativeArrayBufferByteLength(value);\n if (arrayBufferByteLength != null) {\n return (\n isSafeNativeArrayBuffer(value as ArrayBuffer) && arrayBufferByteLength > 0\n );\n }\n if (ArrayBuffer.isView(value)) {\n const view = readSafeNativeArrayBufferView(value);\n return view != null && view.byteLength > 0;\n }\n return false;\n}\n\nfunction isContentPayload(value: unknown): boolean {\n return isArray(value) && value.length > 0;\n}\n\nfunction hasPayloadPath(\n record: Record<string, unknown>,\n path: string[],\n validator: (value: unknown) => boolean = isBinaryPayload\n): boolean {\n let value: unknown = record;\n for (const key of path) {\n if (!isRecord(value)) {\n return false;\n }\n const property = readOwnEnumerableDataProperty(value, key);\n if (!property.found) {\n return false;\n }\n value = property.value;\n }\n return validator(value);\n}\n\nfunction hasAnyPayloadPath(\n record: Record<string, unknown>,\n paths: string[][],\n validator: (value: unknown) => boolean = isBinaryPayload\n): boolean {\n return paths.some((path) => hasPayloadPath(record, path, validator));\n}\n\nfunction isProviderNativeToolResultBlock(\n record: Record<string, unknown>,\n type: string\n): boolean {\n if (type === 'search_result') {\n return (\n hasString(record, 'title') &&\n hasString(record, 'source') &&\n hasPayloadPath(record, ['content'], isArray)\n );\n }\n if (type === 'web_search_result') {\n return hasString(record, 'url');\n }\n if (type === 'web_search_tool_result') {\n const content = readOwnEnumerableDataProperty(record, 'content');\n return (\n hasString(record, 'tool_use_id') &&\n content.found &&\n (isArray(content.value) || isRecord(content.value))\n );\n }\n if (type === 'tool_result') {\n return hasString(record, 'tool_use_id');\n }\n if (type === 'server_tool_call_result') {\n const status = readOwnEnumerableDataProperty(record, 'status');\n return (\n hasString(record, 'toolCallId') &&\n status.found &&\n (status.value === 'success' || status.value === 'error') &&\n hasValue(record, 'output')\n );\n }\n if (type === 'toolResponse') {\n const response = readOwnEnumerableDataProperty(record, 'toolResponse');\n return response.found && isRecord(response.value);\n }\n return false;\n}\n\nconst MAX_ATOMIC_VALIDATION_WORK = 10_000;\nconst MAX_ATOMIC_VALIDATION_DEPTH = 50;\ntype AtomicValidationWork = { value: number };\nconst NATIVE_ARRAY_BUFFER_BYTE_LENGTH_GETTER = Object.getOwnPropertyDescriptor(\n ArrayBuffer.prototype,\n 'byteLength'\n)?.get;\nconst NATIVE_TYPED_ARRAY_PROTOTYPE = Object.getPrototypeOf(\n Uint8Array.prototype\n) as object;\nconst NATIVE_TYPED_ARRAY_BYTE_LENGTH_GETTER = Object.getOwnPropertyDescriptor(\n NATIVE_TYPED_ARRAY_PROTOTYPE,\n 'byteLength'\n)?.get;\nconst NATIVE_DATA_VIEW_BYTE_LENGTH_GETTER = Object.getOwnPropertyDescriptor(\n DataView.prototype,\n 'byteLength'\n)?.get;\nconst NATIVE_ARRAY_BUFFER_VIEW_NAMES = new Map<object, string>([\n [Buffer.prototype, 'Buffer'],\n [DataView.prototype, 'DataView'],\n [Int8Array.prototype, 'Int8Array'],\n [Uint8Array.prototype, 'Uint8Array'],\n [Uint8ClampedArray.prototype, 'Uint8ClampedArray'],\n [Int16Array.prototype, 'Int16Array'],\n [Uint16Array.prototype, 'Uint16Array'],\n [Int32Array.prototype, 'Int32Array'],\n [Uint32Array.prototype, 'Uint32Array'],\n [Float32Array.prototype, 'Float32Array'],\n [Float64Array.prototype, 'Float64Array'],\n [BigInt64Array.prototype, 'BigInt64Array'],\n [BigUint64Array.prototype, 'BigUint64Array'],\n]);\nconst NATIVE_DATE_GET_TIME = Date.prototype.getTime;\nconst NATIVE_DATE_TO_JSON = Date.prototype.toJSON;\nconst NATIVE_DATE_TO_ISO_STRING = Date.prototype.toISOString;\nconst NATIVE_DATE_VALUE_OF = Date.prototype.valueOf;\nconst NATIVE_DATE_TO_STRING = Date.prototype.toString;\nconst NATIVE_DATE_TO_PRIMITIVE = Date.prototype[Symbol.toPrimitive];\nconst NATIVE_DATE_PROTOTYPE_METHODS: ReadonlyArray<\n readonly [PropertyKey, unknown]\n> = [\n ['getTime', NATIVE_DATE_GET_TIME],\n ['toJSON', NATIVE_DATE_TO_JSON],\n ['toISOString', NATIVE_DATE_TO_ISO_STRING],\n ['valueOf', NATIVE_DATE_VALUE_OF],\n ['toString', NATIVE_DATE_TO_STRING],\n [Symbol.toPrimitive, NATIVE_DATE_TO_PRIMITIVE],\n];\n\nfunction consumeAtomicValidationWork(\n remaining: AtomicValidationWork,\n totalRemaining: AtomicValidationWork | undefined,\n amount = 1\n): boolean {\n if (\n amount > remaining.value ||\n (totalRemaining != null && amount > totalRemaining.value)\n ) {\n remaining.value = 0;\n if (totalRemaining != null) {\n totalRemaining.value = 0;\n }\n return false;\n }\n remaining.value -= amount;\n if (totalRemaining != null) {\n totalRemaining.value -= amount;\n }\n return true;\n}\n\nfunction hasPotentiallyCallableToJSON(\n value: object,\n remaining?: AtomicValidationWork,\n totalRemaining?: AtomicValidationWork\n): boolean {\n let current: object | null = value;\n const seen = new Set<object>();\n for (let depth = 0; current != null && depth < 100; depth++) {\n if (isProxy(current)) {\n return true;\n }\n if (\n remaining != null &&\n !consumeAtomicValidationWork(remaining, totalRemaining)\n ) {\n return true;\n }\n if (seen.has(current)) {\n return true;\n }\n seen.add(current);\n const descriptor = Object.getOwnPropertyDescriptor(current, 'toJSON');\n if (descriptor != null) {\n return (\n typeof descriptor.value === 'function' ||\n typeof descriptor.get === 'function'\n );\n }\n current = Object.getPrototypeOf(current) as object | null;\n }\n return current != null;\n}\n\ntype NativeArrayBufferViewRead = {\n byteLength: number;\n name: string;\n};\n\nfunction readSafeNativeArrayBufferView(\n value: ArrayBufferView,\n remaining?: AtomicValidationWork,\n totalRemaining?: AtomicValidationWork,\n rejectCallableToJSON = true\n): NativeArrayBufferViewRead | undefined {\n try {\n const prototype = Object.getPrototypeOf(value) as object | null;\n if (prototype == null || isProxy(prototype)) {\n return undefined;\n }\n const name = NATIVE_ARRAY_BUFFER_VIEW_NAMES.get(prototype);\n if (\n name == null ||\n Object.getOwnPropertyDescriptor(value, 'byteLength') != null ||\n Object.getOwnPropertyDescriptor(value, 'constructor') != null ||\n Object.getOwnPropertyDescriptor(value, 'toJSON') != null ||\n (rejectCallableToJSON &&\n hasPotentiallyCallableToJSON(value, remaining, totalRemaining))\n ) {\n return undefined;\n }\n const getter =\n prototype === DataView.prototype\n ? NATIVE_DATA_VIEW_BYTE_LENGTH_GETTER\n : NATIVE_TYPED_ARRAY_BYTE_LENGTH_GETTER;\n if (getter == null) {\n return undefined;\n }\n const byteLength = getter.call(value) as number;\n return Number.isSafeInteger(byteLength) && byteLength >= 0\n ? { byteLength, name }\n : undefined;\n } catch {\n return undefined;\n }\n}\n\nfunction isSafeNativeArrayBuffer(\n value: ArrayBuffer,\n remaining?: AtomicValidationWork,\n totalRemaining?: AtomicValidationWork\n): boolean {\n try {\n if (\n Object.getPrototypeOf(value) !== ArrayBuffer.prototype ||\n NATIVE_ARRAY_BUFFER_BYTE_LENGTH_GETTER == null ||\n Object.getOwnPropertyDescriptor(ArrayBuffer.prototype, 'byteLength')\n ?.get !== NATIVE_ARRAY_BUFFER_BYTE_LENGTH_GETTER ||\n hasPotentiallyCallableToJSON(value, remaining, totalRemaining)\n ) {\n return false;\n }\n NATIVE_ARRAY_BUFFER_BYTE_LENGTH_GETTER.call(value);\n for (const key in value) {\n if (\n remaining != null &&\n !consumeAtomicValidationWork(remaining, totalRemaining)\n ) {\n return false;\n }\n if (Object.prototype.propertyIsEnumerable.call(value, key)) {\n return false;\n }\n }\n return Object.getOwnPropertyDescriptor(value, 'byteLength') == null;\n } catch {\n return false;\n }\n}\n\nfunction isSafeNativeDate(value: Date): boolean {\n try {\n if (Object.getPrototypeOf(value) !== Date.prototype) {\n return false;\n }\n NATIVE_DATE_GET_TIME.call(value);\n for (const [key, nativeMethod] of NATIVE_DATE_PROTOTYPE_METHODS) {\n if (\n Object.getOwnPropertyDescriptor(value, key) != null ||\n Object.getOwnPropertyDescriptor(Date.prototype, key)?.value !==\n nativeMethod\n ) {\n return false;\n }\n }\n return true;\n } catch {\n return false;\n }\n}\n\nfunction hasUnsafeCallableToJSON(\n value: unknown,\n seen = new Set<object>(),\n remaining = { value: MAX_ATOMIC_VALIDATION_WORK },\n depth = 0,\n totalRemaining?: AtomicValidationWork\n): boolean {\n if (isProxy(value)) {\n return true;\n }\n if (!isRecord(value)) {\n return false;\n }\n if (\n seen.has(value) ||\n depth >= MAX_ATOMIC_VALIDATION_DEPTH ||\n !consumeAtomicValidationWork(remaining, totalRemaining)\n ) {\n return true;\n }\n const valueIsArray = isArray(value);\n if (!valueIsArray) {\n const arrayBufferByteLength = readNativeArrayBufferByteLength(value);\n if (arrayBufferByteLength != null) {\n return !isSafeNativeArrayBuffer(\n value as unknown as ArrayBuffer,\n remaining,\n totalRemaining\n );\n }\n const date = readNativeDate(value);\n if (date.matched) {\n return !isSafeNativeDate(value as unknown as Date);\n }\n if (ArrayBuffer.isView(value)) {\n return (\n readSafeNativeArrayBufferView(value, remaining, totalRemaining) == null\n );\n }\n }\n\n seen.add(value);\n try {\n if (hasPotentiallyCallableToJSON(value, remaining, totalRemaining)) {\n return true;\n }\n if (valueIsArray) {\n const prototype = Object.getPrototypeOf(value);\n if (prototype !== Array.prototype && prototype !== null) {\n return true;\n }\n const lengthDescriptor = Object.getOwnPropertyDescriptor(value, 'length');\n const length = lengthDescriptor?.value;\n if (\n typeof length !== 'number' ||\n !Number.isSafeInteger(length) ||\n length < 0 ||\n !consumeAtomicValidationWork(remaining, totalRemaining, length)\n ) {\n return true;\n }\n for (let i = 0; i < length; i++) {\n const descriptor = Object.getOwnPropertyDescriptor(value, String(i));\n if (\n descriptor == null ||\n typeof descriptor.get === 'function' ||\n typeof descriptor.set === 'function'\n ) {\n return true;\n }\n if (\n hasUnsafeCallableToJSON(\n descriptor.value,\n seen,\n remaining,\n depth + 1,\n totalRemaining\n )\n ) {\n return true;\n }\n }\n return false;\n }\n\n const prototype = Object.getPrototypeOf(value);\n if (prototype !== Object.prototype && prototype !== null) {\n return true;\n }\n for (const key in value) {\n const descriptor = Object.getOwnPropertyDescriptor(value, key);\n if (descriptor == null) {\n return true;\n }\n if (descriptor.enumerable !== true) {\n continue;\n }\n if (\n typeof descriptor.get === 'function' ||\n typeof descriptor.set === 'function' ||\n !consumeAtomicValidationWork(remaining, totalRemaining)\n ) {\n return true;\n }\n if (\n hasUnsafeCallableToJSON(\n descriptor.value,\n seen,\n remaining,\n depth + 1,\n totalRemaining\n )\n ) {\n return true;\n }\n }\n return false;\n } catch {\n return true;\n } finally {\n seen.delete(value);\n }\n}\n\nexport function isAtomicToolContentBlock(value: unknown): boolean {\n try {\n return (\n !hasUnsafeCallableToJSON(value) &&\n isAtomicToolContentBlockUnchecked(value)\n );\n } catch {\n return false;\n }\n}\n\nfunction isAtomicToolContentBlockUnchecked(value: unknown): boolean {\n if (!isRecord(value)) {\n return false;\n }\n const record = value;\n const typeProperty = readOwnEnumerableDataProperty(record, 'type');\n if (!typeProperty.found) {\n const cachePointProperty = readOwnEnumerableDataProperty(\n record,\n 'cachePoint'\n );\n if (!cachePointProperty.found || !isRecord(cachePointProperty.value)) {\n return false;\n }\n const cachePointType = readOwnEnumerableDataProperty(\n cachePointProperty.value,\n 'type'\n );\n return cachePointType.found && cachePointType.value === 'default';\n }\n const type = typeof typeProperty.value === 'string' ? typeProperty.value : '';\n if (type.length > MAX_TOOL_CONTENT_TYPE_CHARS) {\n return false;\n }\n const slashIndex = type.indexOf('/');\n const isMimeType =\n slashIndex > 0 &&\n slashIndex < type.length - 1 &&\n slashIndex === type.lastIndexOf('/');\n if (\n !ATOMIC_CONTENT_TYPES.has(type) &&\n !PROVIDER_NATIVE_TOOL_RESULT_TYPES.has(type) &&\n !isMimeType\n ) {\n return false;\n }\n\n if (PROVIDER_NATIVE_TOOL_RESULT_TYPES.has(type)) {\n return isProviderNativeToolResultBlock(record, type);\n }\n\n if (type === 'computer_screenshot') {\n return hasAnyPayloadPath(\n record,\n [['image_url'], ['file_id']],\n isStringPayload\n );\n }\n if (type === 'input_image') {\n return hasAnyPayloadPath(\n record,\n [['image_url'], ['file_id']],\n isStringPayload\n );\n }\n if (type === 'image_url') {\n return hasAnyPayloadPath(\n record,\n [['image_url'], ['image_url', 'url']],\n isStringPayload\n );\n }\n if (type === 'image_file') {\n return hasAnyPayloadPath(\n record,\n [\n ['image_file', 'file_id'],\n ['image_file', 'fileId'],\n ],\n isStringPayload\n );\n }\n if (type === 'input_audio') {\n return hasAnyPayloadPath(record, [\n ['input_audio', 'data'],\n ['input_audio', 'bytes'],\n ]);\n }\n if (type === 'resource_link') {\n return hasString(record, 'uri');\n }\n if (type === 'video_url') {\n return hasAnyPayloadPath(\n record,\n [['video_url'], ['video_url', 'url']],\n isStringPayload\n );\n }\n if (type === 'resource') {\n return (\n hasAnyPayloadPath(record, [\n ['resource', 'blob'],\n ['resource', 'bytes'],\n ['resource', 'data'],\n ['resource', 'text'],\n ]) || hasPayloadPath(record, ['resource', 'content'], isContentPayload)\n );\n }\n\n if (isMimeType) {\n return hasPayloadPath(record, ['data'], isStringPayload);\n }\n\n if (type === 'image' || type === 'audio' || type === 'video') {\n return hasAnyPayloadPath(record, [\n ['data'],\n ['bytes'],\n ['url'],\n ['source', 'data'],\n ['source', 'bytes'],\n ['source', 'url'],\n [type, 'data'],\n [type, 'bytes'],\n [type, 'url'],\n [type, 'source', 'data'],\n [type, 'source', 'bytes'],\n [type, 'source', 'url'],\n ]);\n }\n\n if (type === 'media') {\n const hasMimeType =\n hasString(record, 'mimeType') || hasString(record, 'mime_type');\n return (\n hasMimeType &&\n hasAnyPayloadPath(record, [\n ['data'],\n ['bytes'],\n ['fileUri'],\n ['media', 'data'],\n ['media', 'bytes'],\n ['media', 'fileUri'],\n ['media', 'source', 'bytes'],\n ])\n );\n }\n\n if (type === 'document' || type === 'file') {\n const nestedType = type;\n return (\n hasAnyPayloadPath(record, [\n ['data'],\n ['bytes'],\n ['url'],\n ['file_data'],\n ['file_id'],\n ['fileId'],\n ['fileUri'],\n ['source', 'data'],\n ['source', 'bytes'],\n ['source', 'url'],\n ['source', 'file_data'],\n ['source', 'file_id'],\n ['source', 'fileId'],\n ['source', 'fileUri'],\n [nestedType, 'data'],\n [nestedType, 'bytes'],\n [nestedType, 'url'],\n [nestedType, 'file_data'],\n [nestedType, 'file_id'],\n [nestedType, 'fileId'],\n [nestedType, 'fileUri'],\n [nestedType, 'source', 'data'],\n [nestedType, 'source', 'bytes'],\n [nestedType, 'source', 'url'],\n ]) ||\n hasPayloadPath(record, ['source', 'content'], isContentPayload) ||\n hasPayloadPath(\n record,\n [nestedType, 'source', 'content'],\n isContentPayload\n ) ||\n (readOwnEnumerableDataProperty(record, 'source_type').value === 'text' &&\n hasString(record, 'text')) ||\n (readOwnEnumerableDataProperty(record, 'source_type').value === 'id' &&\n hasString(record, 'id'))\n );\n }\n\n return false;\n}\n\nconst TOOL_BLOCK_OPAQUE = 0;\nconst TOOL_BLOCK_TEXT = 1;\nconst TOOL_BLOCK_ATOMIC = 2;\n\ntype ToolBlockClassificationContext = {\n totalRemaining: AtomicValidationWork;\n cache: WeakMap<object, number>;\n};\n\nfunction createToolBlockClassificationContext(): ToolBlockClassificationContext {\n return {\n totalRemaining: { value: MAX_STRUCTURED_SERIALIZATION_WORK },\n cache: new WeakMap<object, number>(),\n };\n}\n\nfunction classifyToolContentBlock(\n value: unknown,\n context: ToolBlockClassificationContext\n): number {\n if (isRecord(value)) {\n const cached = context.cache.get(value);\n if (cached != null) {\n return cached;\n }\n }\n const remaining = { value: MAX_ATOMIC_VALIDATION_WORK };\n let kind = TOOL_BLOCK_OPAQUE;\n try {\n if (\n hasUnsafeCallableToJSON(\n value,\n new Set<object>(),\n remaining,\n 0,\n context.totalRemaining\n )\n ) {\n kind = TOOL_BLOCK_OPAQUE;\n } else if (isAtomicToolContentBlockUnchecked(value)) {\n kind = TOOL_BLOCK_ATOMIC;\n } else {\n kind = isTextBlockUnchecked(value) ? TOOL_BLOCK_TEXT : TOOL_BLOCK_OPAQUE;\n }\n } catch {\n kind = TOOL_BLOCK_OPAQUE;\n }\n if (isRecord(value) && context.totalRemaining.value > 0) {\n context.cache.set(value, kind);\n }\n return kind;\n}\n\n/**\n * Produces the text representation providers use for structured tool results.\n * Text-only block arrays stay readable; opaque blocks use canonical JSON.\n */\nexport function serializeToolContent(content: unknown): string {\n if (typeof content === 'string') {\n return content;\n }\n if (!isArray(content)) {\n return serializeStructuredValue(content);\n }\n if (getDenseTextBlockArrayLength(content) != null) {\n return (content as TextToolContentBlock[])\n .map((block) => block.text)\n .join('\\n');\n }\n return serializeStructuredValue(content);\n}\n\nexport function getToolContentCharLength(content: unknown): number {\n if (typeof content === 'string') {\n return content.length;\n }\n if (isArray(content)) {\n const denseTextLength = getDenseTextBlockArrayLength(content);\n if (denseTextLength != null) {\n return denseTextLength;\n }\n }\n try {\n return estimateStructuredChars(content);\n } catch {\n return Number.MAX_SAFE_INTEGER;\n }\n}\n\n/**\n * Produces provider-facing tool-result text without ever exceeding `maxChars`.\n */\nexport function serializeToolContentBounded(\n content: unknown,\n maxChars: number\n): string {\n const normalizedMaxChars = normalizeCharLimit(maxChars);\n if (typeof content === 'string') {\n return truncateToolResultContent(content, normalizedMaxChars);\n }\n if (!isArray(content)) {\n return serializeStructuredValueWithinLimit(content, normalizedMaxChars);\n }\n\n const originalChars = getDenseTextBlockArrayLength(content);\n if (originalChars == null) {\n return serializeStructuredValueWithinLimit(content, normalizedMaxChars);\n }\n return serializeDenseTextBlocksWithinLimit(\n content as TextToolContentBlock[],\n originalChars,\n normalizedMaxChars\n );\n}\n\nfunction serializeDenseTextBlocksWithinLimit(\n textBlocks: readonly TextToolContentBlock[],\n originalChars: number,\n normalizedMaxChars: number\n): string {\n if (originalChars <= normalizedMaxChars) {\n return textBlocks.map((block) => block.text).join('\\n');\n }\n const indicator =\n `\\n\\n… [truncated: ${originalChars} chars exceeded ` +\n `${normalizedMaxChars} limit] …`;\n const available = Math.max(0, normalizedMaxChars - indicator.length);\n let preview = '';\n for (let i = 0; i < textBlocks.length && preview.length < available; i++) {\n if (i > 0) {\n preview += '\\n';\n }\n preview += textBlocks[i].text.slice(0, available - preview.length);\n }\n return (preview + indicator).slice(0, normalizedMaxChars);\n}\n\nexport type CompactToolContentResult = {\n content: ToolContent;\n changed: boolean;\n originalChars: number;\n};\n\nfunction isProviderImageUrl(value: unknown): value is string {\n if (typeof value !== 'string' || value === '') {\n return false;\n }\n const isDataImage = value.startsWith('data:image/');\n if (\n value.length >\n (isDataImage\n ? HARD_MAX_TOTAL_TOOL_OUTPUT_SIZE\n : MAX_PROVIDER_IMAGE_URL_CHARS)\n ) {\n return false;\n }\n for (let i = 0; i < value.length; i++) {\n const code = value.charCodeAt(i);\n if (code <= 0x20 || code === 0x7f) {\n return false;\n }\n }\n if (isDataImage) {\n const separator = value.indexOf(',');\n if (\n separator < 0 ||\n !value.slice(0, separator).toLowerCase().endsWith(';base64')\n ) {\n return false;\n }\n const payload = value.slice(separator + 1);\n return (\n payload.length > 0 &&\n payload.length % 4 === 0 &&\n /^[a-z0-9+/]+={0,2}$/i.test(payload)\n );\n }\n try {\n const url = new URL(value);\n return url.protocol === 'http:' || url.protocol === 'https:';\n } catch {\n return false;\n }\n}\n\nfunction isProviderFileId(value: unknown): value is string {\n return (\n typeof value === 'string' &&\n value.length <= MAX_PROVIDER_FILE_ID_CHARS &&\n /^file[-_][a-z0-9_-]+$/i.test(value)\n );\n}\n\nfunction hasOnlyEnumerableKeys(\n record: Record<string, unknown>,\n allowed: ReadonlySet<string>\n): boolean {\n try {\n const keys = Object.keys(record);\n return keys.every((key) => allowed.has(key));\n } catch {\n return false;\n }\n}\n\nexport type CacheControlledTextToolContent = [\n {\n type: 'text';\n text: string;\n cache_control: { type: 'ephemeral'; ttl?: '1h' };\n },\n];\n\nconst SINGLE_TEXT_TOOL_CONTENT_KEYS = new Set(['type', 'text']);\nconst CACHE_CONTROLLED_TEXT_TOOL_CONTENT_KEYS = new Set([\n 'type',\n 'text',\n 'cache_control',\n]);\nconst CACHE_CONTROL_KEYS = new Set(['type', 'ttl']);\n\nfunction hasSafePlainPrototype(value: object): boolean {\n try {\n const prototype = Object.getPrototypeOf(value) as object | null;\n return (\n (prototype === Object.prototype || prototype === null) &&\n !hasPotentiallyCallableToJSON(value)\n );\n } catch {\n return false;\n }\n}\n\nfunction readSafeArrayItem(\n content: unknown,\n expectedLength: number,\n index: number\n): OwnDataProperty {\n if (!isArray(content) || isProxy(content)) {\n return { found: false };\n }\n try {\n const length = Object.getOwnPropertyDescriptor(content, 'length');\n if (length?.value !== expectedLength) {\n return { found: false };\n }\n const prototype = Object.getPrototypeOf(content) as object | null;\n if (\n (prototype !== Array.prototype && prototype !== null) ||\n hasPotentiallyCallableToJSON(content)\n ) {\n return { found: false };\n }\n const item = Object.getOwnPropertyDescriptor(content, String(index));\n if (item?.enumerable !== true || !('value' in item)) {\n return { found: false };\n }\n return { found: true, value: item.value };\n } catch {\n return { found: false };\n }\n}\n\n/** Reads one safe text block and returns its bounded text payload. */\nexport function getBoundedSingleTextToolContent(\n content: unknown,\n maxChars: number\n): string | undefined {\n const block = readSafeArrayItem(content, 1, 0);\n if (\n !block.found ||\n !isRecord(block.value) ||\n isProxy(block.value) ||\n !hasSafePlainPrototype(block.value) ||\n !hasOnlyEnumerableKeys(block.value, SINGLE_TEXT_TOOL_CONTENT_KEYS)\n ) {\n return undefined;\n }\n const type = readOwnEnumerableDataProperty(block.value, 'type');\n const text = readOwnEnumerableDataProperty(block.value, 'text');\n if (\n !type.found ||\n type.value !== 'text' ||\n !text.found ||\n typeof text.value !== 'string'\n ) {\n return undefined;\n }\n const normalizedMaxChars = Number.isFinite(maxChars)\n ? Math.max(0, Math.floor(maxChars))\n : Number.MAX_SAFE_INTEGER;\n return truncateToolResultContent(text.value, normalizedMaxChars);\n}\n\n/**\n * Canonicalizes the single cache-decorated text block produced by tail prompt\n * caching without invoking accessors or custom serialization hooks.\n */\nexport function getBoundedCacheControlledTextToolContent(\n content: unknown,\n maxChars: number\n): CacheControlledTextToolContent | undefined {\n const block = readSafeArrayItem(content, 1, 0);\n if (\n !block.found ||\n !isRecord(block.value) ||\n isProxy(block.value) ||\n !hasSafePlainPrototype(block.value) ||\n !hasOnlyEnumerableKeys(block.value, CACHE_CONTROLLED_TEXT_TOOL_CONTENT_KEYS)\n ) {\n return undefined;\n }\n const type = readOwnEnumerableDataProperty(block.value, 'type');\n const text = readOwnEnumerableDataProperty(block.value, 'text');\n const cacheControl = readOwnEnumerableDataProperty(\n block.value,\n 'cache_control'\n );\n if (\n !type.found ||\n type.value !== 'text' ||\n !text.found ||\n typeof text.value !== 'string' ||\n !cacheControl.found ||\n !isRecord(cacheControl.value) ||\n isProxy(cacheControl.value) ||\n !hasSafePlainPrototype(cacheControl.value) ||\n !hasOnlyEnumerableKeys(cacheControl.value, CACHE_CONTROL_KEYS)\n ) {\n return undefined;\n }\n\n const cacheType = readOwnEnumerableDataProperty(cacheControl.value, 'type');\n const ttl = readOwnEnumerableDataProperty(cacheControl.value, 'ttl');\n let hasOwnTtl: boolean;\n try {\n hasOwnTtl =\n Object.getOwnPropertyDescriptor(cacheControl.value, 'ttl') != null;\n } catch {\n return undefined;\n }\n if (\n !cacheType.found ||\n cacheType.value !== 'ephemeral' ||\n (hasOwnTtl && (!ttl.found || ttl.value !== '1h'))\n ) {\n return undefined;\n }\n\n const normalizedMaxChars = Number.isFinite(maxChars)\n ? Math.max(0, Math.floor(maxChars))\n : Number.MAX_SAFE_INTEGER;\n return [\n {\n type: 'text',\n text: truncateToolResultContent(text.value, normalizedMaxChars),\n cache_control: {\n type: 'ephemeral',\n ...(ttl.found ? { ttl: '1h' as const } : {}),\n },\n },\n ];\n}\n\nexport type ComputerCallOutputScreenshot =\n | { type: 'input_image'; image_url: string; detail?: InputImageDetail }\n | { type: 'input_image'; file_id: string; detail?: InputImageDetail }\n | { type: 'computer_screenshot'; image_url: string }\n | { type: 'computer_screenshot'; file_id: string };\n\ntype InputImageDetail = 'low' | 'high' | 'auto' | 'original';\n\nconst INPUT_IMAGE_KEYS = new Set(['type', 'image_url', 'file_id', 'detail']);\nconst COMPUTER_SCREENSHOT_KEYS = new Set(['type', 'image_url', 'file_id']);\nconst IMAGE_URL_KEYS = new Set(['type', 'image_url', 'detail']);\nconst NESTED_IMAGE_URL_KEYS = new Set(['url', 'detail']);\nconst INPUT_IMAGE_DETAILS = new Set(['low', 'high', 'auto', 'original']);\n\n/**\n * Selects the exact screenshot shape accepted by LangChain's Responses\n * converter without invoking accessors or user-defined serialization hooks.\n */\nexport function getComputerCallOutputScreenshot(\n content: unknown\n): ComputerCallOutputScreenshot | undefined {\n if (isProviderImageUrl(content)) {\n return { type: 'input_image', image_url: content };\n }\n if (\n !isArray(content) ||\n hasUnsafeCallableToJSON(content) ||\n content.length !== 1\n ) {\n return undefined;\n }\n\n const descriptor = Object.getOwnPropertyDescriptor(content, '0');\n if (descriptor == null || !('value' in descriptor)) {\n return undefined;\n }\n const block = descriptor.value;\n if (!isRecord(block)) {\n return undefined;\n }\n const type = readOwnEnumerableDataProperty(block, 'type');\n if (!type.found) {\n return undefined;\n }\n const imageUrl = readOwnEnumerableDataProperty(block, 'image_url');\n const fileId = readOwnEnumerableDataProperty(block, 'file_id');\n const validImageUrl =\n imageUrl.found && isProviderImageUrl(imageUrl.value)\n ? imageUrl.value\n : undefined;\n const validFileId =\n fileId.found && isProviderFileId(fileId.value) ? fileId.value : undefined;\n const hasImageUrl = validImageUrl != null;\n const hasFileId = validFileId != null;\n\n if (\n type.value === 'input_image' &&\n hasOnlyEnumerableKeys(block, INPUT_IMAGE_KEYS)\n ) {\n if (\n (imageUrl.found && !hasImageUrl) ||\n (fileId.found && !hasFileId) ||\n hasImageUrl === hasFileId\n ) {\n return undefined;\n }\n const detail = readOwnEnumerableDataProperty(block, 'detail');\n if (\n detail.found &&\n (typeof detail.value !== 'string' ||\n !INPUT_IMAGE_DETAILS.has(detail.value))\n ) {\n return undefined;\n }\n return hasImageUrl\n ? {\n type: 'input_image',\n image_url: validImageUrl,\n ...(detail.found ? { detail: detail.value as InputImageDetail } : {}),\n }\n : {\n type: 'input_image',\n file_id: validFileId as string,\n ...(detail.found ? { detail: detail.value as InputImageDetail } : {}),\n };\n }\n if (\n type.value === 'computer_screenshot' &&\n hasOnlyEnumerableKeys(block, COMPUTER_SCREENSHOT_KEYS)\n ) {\n if (\n (imageUrl.found && !hasImageUrl) ||\n (fileId.found && !hasFileId) ||\n hasImageUrl === hasFileId\n ) {\n return undefined;\n }\n return hasImageUrl\n ? { type: 'computer_screenshot', image_url: validImageUrl }\n : {\n type: 'computer_screenshot',\n file_id: validFileId as string,\n };\n }\n if (\n type.value === 'image_url' &&\n !fileId.found &&\n hasOnlyEnumerableKeys(block, IMAGE_URL_KEYS)\n ) {\n if (hasImageUrl) {\n return { type: 'input_image', image_url: validImageUrl };\n }\n if (\n imageUrl.found &&\n isRecord(imageUrl.value) &&\n hasOnlyEnumerableKeys(imageUrl.value, NESTED_IMAGE_URL_KEYS)\n ) {\n const url = readOwnEnumerableDataProperty(imageUrl.value, 'url');\n if (url.found && isProviderImageUrl(url.value)) {\n return { type: 'input_image', image_url: url.value };\n }\n }\n }\n return undefined;\n}\n\n/** Returns the provider image URL when a screenshot is URL-backed. */\nexport function getComputerCallOutputImageUrl(\n content: unknown\n): string | undefined {\n const screenshot = getComputerCallOutputScreenshot(content);\n return screenshot != null && 'image_url' in screenshot\n ? screenshot.image_url\n : undefined;\n}\n\n/** Returns whether content can be sent as a native computer screenshot. */\nexport function isComputerCallOutputContent(\n content: unknown\n): content is ToolContent {\n return getComputerCallOutputScreenshot(content) != null;\n}\n\n/** Returns whether a ToolMessage carries the native computer-output marker. */\nexport function hasComputerCallOutputMarker(message: BaseMessage): boolean {\n try {\n if (message.getType() !== 'tool') {\n return false;\n }\n const metadata = message.additional_kwargs as unknown;\n if (!isRecord(metadata)) {\n return false;\n }\n const type = readOwnEnumerableDataProperty(metadata, 'type');\n return type.found && type.value === 'computer_call_output';\n } catch {\n return false;\n }\n}\n\n/** Native Responses computer screenshots are indivisible provider payloads. */\nexport function isComputerCallOutputMessage(message: BaseMessage): boolean {\n return (\n hasComputerCallOutputMarker(message) &&\n isComputerCallOutputContent(message.content)\n );\n}\n\n/**\n * Bounds structured tool output without slicing binary/media payloads.\n * Purely textual/structured arrays become a universally valid string tool\n * result. For mixed-media arrays, compactable blocks become one text preview\n * while atomic blocks remain intact.\n */\nexport function compactToolContent(\n content: unknown,\n maxChars: number\n): CompactToolContentResult {\n const normalizedMaxChars = Number.isFinite(maxChars)\n ? Math.max(0, Math.floor(maxChars))\n : Number.MAX_SAFE_INTEGER;\n if (typeof content === 'string') {\n return {\n content: truncateToolResultContent(content, normalizedMaxChars),\n changed: content.length > normalizedMaxChars,\n originalChars: content.length,\n };\n }\n if (!isArray(content)) {\n const serialized = serializeStructuredValueBounded(\n content,\n normalizedMaxChars\n );\n return {\n content: serialized.content,\n changed: true,\n originalChars: serialized.originalChars,\n };\n }\n if (isProxy(content)) {\n const serialized = serializeStructuredValueBounded(\n content,\n normalizedMaxChars\n );\n return {\n content: serialized.content,\n changed: true,\n originalChars: serialized.originalChars,\n };\n }\n const contentBlocks = content as ToolContentBlock[];\n\n let contentLength: number;\n try {\n contentLength = contentBlocks.length;\n } catch {\n const serialized = serializeStructuredValueBounded(\n contentBlocks,\n normalizedMaxChars\n );\n return {\n content: serialized.content,\n changed: true,\n originalChars: Number.MAX_SAFE_INTEGER,\n };\n }\n if (contentLength > MAX_STRUCTURED_SERIALIZATION_WORK) {\n const serialized = serializeStructuredValueBounded(\n contentBlocks,\n normalizedMaxChars\n );\n return {\n content: serialized.content,\n changed: true,\n originalChars: serialized.originalChars,\n };\n }\n\n try {\n const blockKinds = new Uint8Array(contentLength);\n const validation = createToolBlockClassificationContext();\n const structuredWork = createStructuredWorkState();\n const containerValidationWork = {\n value: MAX_ATOMIC_VALIDATION_WORK,\n };\n const containerPrototype = Object.getPrototypeOf(contentBlocks);\n if (\n (containerPrototype !== Array.prototype && containerPrototype !== null) ||\n hasPotentiallyCallableToJSON(\n contentBlocks,\n containerValidationWork,\n validation.totalRemaining\n )\n ) {\n const serialized = serializeStructuredValueBounded(\n contentBlocks,\n normalizedMaxChars\n );\n return {\n content: serialized.content,\n changed: true,\n originalChars: serialized.originalChars,\n };\n }\n let atomicBlockCount = 0;\n let denseTextLength = contentLength > 0 ? contentLength - 1 : undefined;\n for (let i = 0; i < contentLength; i++) {\n const descriptor = Object.getOwnPropertyDescriptor(\n contentBlocks,\n String(i)\n );\n if (\n descriptor == null ||\n typeof descriptor.get === 'function' ||\n typeof descriptor.set === 'function'\n ) {\n const serialized = serializeStructuredValueBounded(\n contentBlocks,\n normalizedMaxChars\n );\n return {\n content: serialized.content,\n changed: true,\n originalChars: serialized.originalChars,\n };\n }\n const block = descriptor.value as ToolContentBlock;\n const kind = classifyToolContentBlock(block, validation);\n if (validation.totalRemaining.value <= 0) {\n const serialized = serializeStructuredValueBounded(\n contentBlocks,\n normalizedMaxChars\n );\n return {\n content: serialized.content,\n changed: true,\n originalChars: serialized.originalChars,\n };\n }\n blockKinds[i] = kind;\n if (kind === TOOL_BLOCK_ATOMIC) {\n atomicBlockCount++;\n }\n if (denseTextLength == null) {\n continue;\n }\n if (kind !== TOOL_BLOCK_TEXT) {\n denseTextLength = undefined;\n continue;\n }\n const text = readOwnEnumerableDataProperty(block, 'text').value;\n denseTextLength += typeof text === 'string' ? text.length : 0;\n if (denseTextLength >= Number.MAX_SAFE_INTEGER) {\n denseTextLength = Number.MAX_SAFE_INTEGER;\n }\n }\n const originalChars =\n denseTextLength ??\n estimateStructuredChars(\n contentBlocks,\n Number.MAX_SAFE_INTEGER,\n [],\n structuredWork\n );\n if (atomicBlockCount === 0) {\n if (denseTextLength != null && originalChars <= normalizedMaxChars) {\n return {\n content: contentBlocks,\n changed: false,\n originalChars,\n };\n }\n const serialized =\n denseTextLength != null\n ? serializeDenseTextBlocksWithinLimit(\n contentBlocks as TextToolContentBlock[],\n denseTextLength,\n normalizedMaxChars\n )\n : serializeStructuredValueWithinLimit(\n contentBlocks,\n normalizedMaxChars,\n structuredWork\n );\n return {\n content: truncateToolResultContent(serialized, normalizedMaxChars),\n // Opaque arrays are normalized even when they are small so every\n // provider receives a universally valid tool-result string.\n changed: true,\n originalChars,\n };\n }\n\n let hasOpaqueBlocks = false;\n const normalizedBlocks: ToolContentBlock[] = [];\n const normalizedKinds: number[] = [];\n let opaqueRun: unknown[] = [];\n const flushOpaqueRun = (): void => {\n if (opaqueRun.length === 0) {\n return;\n }\n normalizedBlocks.push({\n type: 'text',\n text: serializeStructuredValueWithinLimit(\n opaqueRun,\n normalizedMaxChars,\n structuredWork\n ),\n });\n normalizedKinds.push(TOOL_BLOCK_TEXT);\n opaqueRun = [];\n };\n for (let i = 0; i < contentLength; i++) {\n const block = contentBlocks[i];\n const kind = blockKinds[i];\n if (kind !== TOOL_BLOCK_OPAQUE) {\n flushOpaqueRun();\n normalizedBlocks.push(block);\n normalizedKinds.push(kind);\n } else {\n hasOpaqueBlocks = true;\n opaqueRun.push(block);\n }\n }\n flushOpaqueRun();\n\n const normalizedLength = estimateStructuredChars(\n normalizedBlocks,\n Number.MAX_SAFE_INTEGER,\n [],\n structuredWork\n );\n if (normalizedLength <= normalizedMaxChars) {\n return {\n content: hasOpaqueBlocks ? normalizedBlocks : contentBlocks,\n changed: hasOpaqueBlocks,\n originalChars,\n };\n }\n\n // Keep small media/resource blocks intact, but never let a single inline\n // base64/blob block defeat the cap. Half of the budget is reserved for\n // compactable text so the model still receives an explanation.\n const atomicBudget = Math.floor(normalizedMaxChars / 2);\n let atomicChars = 0;\n let preservedAtomicCount = 0;\n const preservedAtomicFlags = new Uint8Array(normalizedBlocks.length);\n let omittedAtomicCount = 0;\n const omittedAtomicTypes: string[] = [];\n const compactableBlocks: ToolContentBlock[] = [];\n let compactableChars = 0;\n for (let i = 0; i < normalizedBlocks.length; i++) {\n const block = normalizedBlocks[i];\n if (normalizedKinds[i] !== TOOL_BLOCK_ATOMIC) {\n if (compactableBlocks.length > 0) {\n compactableChars++;\n }\n compactableBlocks.push(block);\n compactableChars += (block as TextToolContentBlock).text.length;\n continue;\n }\n const blockChars = estimateStructuredChars(\n block,\n atomicBudget - atomicChars,\n [],\n structuredWork\n );\n if (atomicChars + blockChars <= atomicBudget) {\n preservedAtomicFlags[i] = 1;\n preservedAtomicCount++;\n atomicChars += blockChars;\n } else {\n omittedAtomicCount++;\n const typeProperty = isRecord(block)\n ? readOwnEnumerableDataProperty(block, 'type')\n : { found: false as const };\n if (omittedAtomicTypes.length < 8) {\n const rawType =\n typeProperty.found && typeof typeProperty.value === 'string'\n ? typeProperty.value\n : 'media';\n omittedAtomicTypes.push(truncateToolResultContent(rawType, 80));\n }\n }\n }\n\n let previewSource = serializeDenseTextBlocksWithinLimit(\n compactableBlocks as TextToolContentBlock[],\n compactableChars,\n normalizedMaxChars\n );\n if (omittedAtomicCount > 0) {\n const undisplayedCount = omittedAtomicCount - omittedAtomicTypes.length;\n const omittedNotice =\n `[omitted ${omittedAtomicCount} oversized atomic tool-content ` +\n `block${omittedAtomicCount === 1 ? '' : 's'}: ` +\n `${omittedAtomicTypes.join(', ')}` +\n `${undisplayedCount > 0 ? `, +${undisplayedCount} more` : ''}]`;\n previewSource =\n previewSource.length > 0\n ? `${previewSource}\\n${omittedNotice}`\n : omittedNotice;\n }\n\n const structuralAllowance =\n preservedAtomicCount * 4 + (previewSource.length > 0 ? 32 : 2);\n const previewBudget = Math.max(\n 0,\n normalizedMaxChars - atomicChars - structuralAllowance\n );\n const preview = truncateToolResultContent(previewSource, previewBudget);\n const compacted: ToolContentBlock[] = [];\n let previewInserted = false;\n for (let i = 0; i < normalizedBlocks.length; i++) {\n const block = normalizedBlocks[i];\n if (normalizedKinds[i] === TOOL_BLOCK_ATOMIC) {\n if (preservedAtomicFlags[i] === 1) {\n compacted.push(block);\n }\n } else if (!previewInserted) {\n if (preview.length > 0) {\n compacted.push({ type: 'text', text: preview });\n }\n previewInserted = true;\n }\n }\n if (!previewInserted && preview.length > 0) {\n compacted.push({ type: 'text', text: preview });\n }\n\n // JSON framing can make the block array a few bytes larger than the\n // character budget. Fall back to bounded provider-neutral text rather than\n // leaking an oversized media payload.\n const compactedChars =\n preservedAtomicCount > 0 || compacted.length === 0\n ? estimateStructuredChars(\n compacted,\n Number.MAX_SAFE_INTEGER,\n [],\n structuredWork\n )\n : preview.length;\n if (compactedChars > normalizedMaxChars) {\n return {\n content: serializeStructuredValueWithinLimit(\n normalizedBlocks,\n normalizedMaxChars,\n structuredWork\n ),\n changed: true,\n originalChars,\n };\n }\n\n return {\n content: compacted,\n changed: true,\n originalChars,\n };\n } catch {\n const serialized = serializeStructuredValueBounded(\n contentBlocks,\n normalizedMaxChars\n );\n return {\n content: serialized.content,\n changed: true,\n originalChars: serialized.originalChars,\n };\n }\n}\n\n/** Clones a ToolMessage while retaining fields omitted by ad-hoc clones. */\nexport function cloneToolMessageWithContent(\n message: ToolMessage,\n content: ToolContent,\n artifact: unknown = message.artifact\n): ToolMessage {\n return new ToolMessage({\n content,\n tool_call_id: message.tool_call_id,\n name: message.name,\n id: message.id,\n status: message.status,\n artifact,\n metadata: message.metadata,\n additional_kwargs: message.additional_kwargs,\n response_metadata: message.response_metadata,\n });\n}\n"],"mappings":";;;;AAWA,MAAM,uBAAuB,IAAI,IAAI;CACnC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AACD,MAAM,8BAA8B;AACpC,MAAM,+BAA+B;AACrC,MAAM,6BAA6B;AAEnC,MAAM,oCAAoC,IAAI,IAAI;CAChD;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AAWD,MAAM,2BAA2B;AACjC,MAAM,qCAAqC;AAC3C,MAAM,oCAAoC;AAC1C,MAAM,gCAAgC;AACtC,MAAM,wCAAwC;AAC9C,MAAM,0BAA0B;AAChC,MAAM,6BACJ;AAWF,SAAS,4BAAiD;CACxD,OAAO;EACL,WAAW;EACX,oBAAoB;EACpB,UAAU;EACV,+BAAe,IAAI,QAAsC;EACzD,sBAAsB;CACxB;AACF;AAEA,SAAS,sBAAsB,OAAqC;CAClE,IAAI,MAAM,aAAa,GAAG;EACxB,MAAM,WAAW;EACjB,MAAM,uBAAuB;EAC7B,OAAO;CACT;CACA,MAAM;CACN,OAAO;AACT;AAEA,SAAS,+BAA+B,OAAqC;CAC3E,IAAI,MAAM,sBAAsB,GAAG;EACjC,MAAM,WAAW;EACjB,MAAM,uBAAuB;EAC7B,OAAO;CACT;CACA,MAAM;CACN,OAAO;AACT;AAEA,SAAS,0BAA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eACA,kBACF;EACA,OAAO;GACL,SAAS,WAAW;GACpB,SAAS;GACT,eAAe,WAAW;EAC5B;CACF;AACF;;AAGA,SAAgB,4BACd,SACA,SACA,WAAoB,QAAQ,UACf;CACb,OAAO,IAAI,YAAY;EACrB;EACA,cAAc,QAAQ;EACtB,MAAM,QAAQ;EACd,IAAI,QAAQ;EACZ,QAAQ,QAAQ;EAChB;EACA,UAAU,QAAQ;EAClB,mBAAmB,QAAQ;EAC3B,mBAAmB,QAAQ;CAC7B,CAAC;AACH"}
@@ -11,3 +11,21 @@ export declare const ANTHROPIC_TOOL_TOKEN_MULTIPLIER = 2.6;
11
11
  * Empirically calibrated at ~1.4× the raw JSON token count.
12
12
  */
13
13
  export declare const DEFAULT_TOOL_TOKEN_MULTIPLIER = 1.4;
14
+ /**
15
+ * Default ceiling on cooperative stream seals per run. Each seal costs one
16
+ * extra superstep, so this also sizes the recursion-limit headroom a
17
+ * preemption-enabled run reserves.
18
+ */
19
+ export declare const DEFAULT_MAX_SEALS = 8;
20
+ /**
21
+ * Per-hook timeout for `PreemptBoundary`, deliberately far above
22
+ * `DEFAULT_HOOK_TIMEOUT_MS`. A host drain has already popped its queue and
23
+ * persisted content by the time this fires, so a timeout does not cancel the
24
+ * work — it only loses the messages the run was about to inject.
25
+ */
26
+ export declare const PREEMPT_BOUNDARY_HOOK_TIMEOUT_MS = 120000;
27
+ /**
28
+ * Default LangGraph recursion limit for a run. Callers may override it via
29
+ * the stream config; a preemption-enabled run adds its seal budget on top.
30
+ */
31
+ export declare const DEFAULT_RECURSION_LIMIT = 50;
@@ -4,8 +4,8 @@ import type { UsageMetadata, BaseMessage } from '@langchain/core/messages';
4
4
  import type { ToolCall } from '@langchain/core/messages/tool';
5
5
  import type { HookRegistry } from '@/hooks';
6
6
  import type * as t from '@/types';
7
- import { ToolNode as CustomToolNode } from '@/tools/ToolNode';
8
7
  import { ToolOutputReferenceRegistry } from '@/tools/toolOutputReferences';
8
+ import { ToolNode as CustomToolNode } from '@/tools/ToolNode';
9
9
  import { AgentContext } from '@/agents/AgentContext';
10
10
  import { HandlerRegistry } from '@/events';
11
11
  export declare abstract class Graph<T extends t.BaseGraphState = t.BaseGraphState, _TNodeName extends string = string> {
@@ -46,6 +46,20 @@ export declare abstract class Graph<T extends t.BaseGraphState = t.BaseGraphStat
46
46
  reasoningStepHasDeltas: Set<string>;
47
47
  protected handlerDispatchedEventCounts: Map<string, number>;
48
48
  signal?: AbortSignal;
49
+ /**
50
+ * The abort signal the CALLER handed to the current `processStream` call,
51
+ * assigned unconditionally — including back to `undefined` — on every call.
52
+ *
53
+ * Kept separate from {@link signal} on purpose. That field is construction
54
+ * state with its own consumers (model-call config, subagent parentSignal),
55
+ * so adopting a per-call signal into it would leak one call's controller
56
+ * into the next — `clearHeavyState()` is skipped on HITL interrupts, so a
57
+ * host that aborts a finished request's controller would poison the resumed
58
+ * run's model calls and boundary drains with an already-aborted signal.
59
+ * Boundary dispatch composes the two instead; see
60
+ * `StandardGraph.dispatchPreemptBoundary`.
61
+ */
62
+ callerSignal?: AbortSignal;
49
63
  /** Set of invoked tool call IDs from non-message run steps completed mid-run, if any */
50
64
  invokedToolIds?: Set<string>;
51
65
  handlerRegistry: HandlerRegistry | undefined;
@@ -178,6 +192,8 @@ export declare class StandardGraph extends Graph<t.BaseGraphState, t.GraphNode>
178
192
  messages: BaseMessage[];
179
193
  /** Cached run messages preserved before clearHeavyState() so getRunMessages() works after cleanup. */
180
194
  private cachedRunMessages?;
195
+ /** Ids of AI turns the agent node returned THIS run; see isRunProducedMessage. */
196
+ protected runProducedAiMessageIds: Set<string>;
181
197
  /** Checkpoint scope whose messages match index-keyed tool snapshots. */
182
198
  private originalToolContentCheckpointScope?;
183
199
  runId: string | undefined;
@@ -203,9 +219,105 @@ export declare class StandardGraph extends Graph<t.BaseGraphState, t.GraphNode>
203
219
  subagentUsageSink?: t.SubagentUsageSink;
204
220
  /** See {@link t.StandardGraphInput.subagentScope}. */
205
221
  subagentScope: boolean;
206
- constructor({ runId, signal, agents, langfuse, tokenCounter, indexTokenCountMap, calibrationRatio, subagentUsageSink, subagentScope, }: t.StandardGraphInput);
222
+ /** See {@link t.StandardGraphInput.preemption}. */
223
+ preemption?: t.StreamPreemption;
224
+ /**
225
+ * Seals charged against `preemption.maxSeals`. Per-turn: cleared by both
226
+ * reset paths so a fresh turn gets a fresh budget, while a HITL resume —
227
+ * which skips `resetValues` — keeps what it had left.
228
+ */
229
+ private preemptSealBudgetUsed;
230
+ /**
231
+ * Seals honored over the graph's lifetime. Reported by
232
+ * {@link getPreemptStats}, so it deliberately SURVIVES `clearHeavyState()`
233
+ * — a host reads it after `processStream` returns, which is strictly after
234
+ * cleanup runs.
235
+ */
236
+ preemptSealCount: number;
237
+ /** Boundaries that produced nothing to inject, so the turn stopped early. */
238
+ preemptEmptyBoundaries: number;
239
+ /**
240
+ * Set between claiming a seal and resolving its boundary. `MultiAgentGraph`
241
+ * fans parallel agents through this one instance against a single host
242
+ * request, so without a one-at-a-time gate several streams would each seal
243
+ * for the same queued message and every loser would take the
244
+ * nothing-to-inject path and cut its answer short.
245
+ */
246
+ private preemptSealInFlight;
247
+ /**
248
+ * True when a seal ended the turn without a resume. The assistant turn is
249
+ * real and kept, but it is not the answer the model intended to finish —
250
+ * hosts persist it as unfinished rather than complete.
251
+ */
252
+ preemptIncomplete: boolean;
253
+ /**
254
+ * `stopReason` from a `PreemptBoundary` hook that halted the turn.
255
+ *
256
+ * Clearing the registry halt is what keeps the sealed turn alive, but the
257
+ * registry held the only copy of the reason — so it is captured here first.
258
+ * Without it `getHaltReason()` returns undefined and a host records a
259
+ * hook-halted turn as an ordinary completion.
260
+ */
261
+ preemptHaltReason: string | undefined;
262
+ /**
263
+ * Agent IDs whose next superstep must return to the agent node. Keyed by
264
+ * agent because `MultiAgentGraph` routes every parallel agent through this
265
+ * same instance, and a single field would let one agent's boundary resume
266
+ * another's turn.
267
+ */
268
+ pendingPreemptReturn: Set<string>;
269
+ constructor({ runId, signal, agents, langfuse, tokenCounter, indexTokenCountMap, calibrationRatio, subagentUsageSink, subagentScope, preemption, }: t.StandardGraphInput);
207
270
  resetValues(keepContent?: boolean, checkpointScope?: string): void;
208
271
  clearHeavyState(): void;
272
+ /**
273
+ * Per-turn seal budget and routing markers. Cleared by both reset paths so
274
+ * a new turn starts with a full budget and no stale resume marker.
275
+ *
276
+ * The REPORTED counters are deliberately not touched here — see
277
+ * {@link resetPreemptTotals}.
278
+ */
279
+ private resetPreemptTurnState;
280
+ /**
281
+ * Lifetime seal totals, cleared only when a genuinely new run starts.
282
+ * `clearHeavyState()` must NOT call this: it runs in `processStream`'s
283
+ * `finally`, so zeroing here would make {@link getPreemptStats} and
284
+ * `preemptIncomplete` unreadable for every caller of the method that just
285
+ * produced them.
286
+ */
287
+ private resetPreemptTotals;
288
+ /**
289
+ * True when the host has requested a cooperative seal AND this graph may
290
+ * honor it. Read once per streamed chunk, so it stays property reads plus
291
+ * one host callback — no I/O, no allocation.
292
+ *
293
+ * Non-mutating: a true result only means a seal is worth evaluating. The
294
+ * budget is taken by {@link claimPreemptSeal} once the accumulated chunk is
295
+ * known to be safe, so a chunk that cannot seal never spends budget.
296
+ *
297
+ * Subagent scopes never seal: a steer targets the top-level conversation,
298
+ * and a child run must finish so its parent sees a complete result.
299
+ */
300
+ /** Internal seal preconditions only — no host callback, no side effects. */
301
+ private canClaimPreemptSeal;
302
+ shouldPreemptStream(): boolean;
303
+ /**
304
+ * Takes the seal slot, or returns false if another stream already holds it.
305
+ *
306
+ * Assumes the caller already polled `shouldPreemptStream()` for THIS chunk,
307
+ * and deliberately does not poll the host again — `StreamPreemption`
308
+ * documents `shouldPreempt` as once per chunk, and a host that consumes a
309
+ * pending flag on read would lose the request to a second call.
310
+ *
311
+ * The guard and both mutations remain one synchronous body, which is what
312
+ * makes this safe under a parallel `MultiAgentGraph`: several agents share
313
+ * one graph and can each see the poll as true, but no `await` can split the
314
+ * claim, so only one takes the slot. The loser keeps streaming normally
315
+ * rather than sealing for a message it would never receive.
316
+ */
317
+ claimPreemptSeal(): boolean;
318
+ /** Releases the seal slot once its boundary has resolved, win or lose. */
319
+ releasePreemptSeal(): void;
320
+ getPreemptStats(): t.PreemptStats;
209
321
  getRunStep(stepId: string): t.RunStep | undefined;
210
322
  getAgentContext(metadata: Record<string, unknown> | undefined): AgentContext;
211
323
  getStepBaseKey(metadata: Record<string, unknown> | undefined): string;
@@ -217,6 +329,17 @@ export declare class StandardGraph extends Graph<t.BaseGraphState, t.GraphNode>
217
329
  private getBaseKeyList;
218
330
  checkKeyList(keyList: (string | number | undefined)[]): boolean;
219
331
  getRunMessages(): BaseMessage[] | undefined;
332
+ /**
333
+ * True when THIS RUN produced `message` — the provenance the handoff cue
334
+ * gate needs. Tracked as an id set rather than inferred from `startIndex`
335
+ * arithmetic: summarization's remove-all compaction rewrites the live
336
+ * array and leaves `startIndex` stale, so index-based run/host
337
+ * discrimination silently breaks right after a mid-run summarize. Ids
338
+ * survive compaction (retained messages keep theirs), host-supplied
339
+ * prefill messages are never in the set, and membership is O(1) per
340
+ * model call.
341
+ */
342
+ isRunProducedMessage(message: BaseMessage): boolean;
220
343
  getContentParts(): t.MessageContentComplex[] | undefined;
221
344
  getCalibrationRatio(): number;
222
345
  getResolvedInstructionOverhead(): number | undefined;
@@ -256,6 +379,20 @@ export declare class StandardGraph extends Graph<t.BaseGraphState, t.GraphNode>
256
379
  */
257
380
  private beginOverflowRecovery;
258
381
  createCallModel(agentId?: string): (state: t.AgentSubgraphState, config?: RunnableConfig) => Promise<Partial<t.AgentSubgraphState>>;
382
+ /**
383
+ * Fires `PreemptBoundary` after a sealed turn and returns whatever the
384
+ * hooks asked to inject, converted through the same `convertInjectedMessages`
385
+ * the tool boundary uses so the two sites cannot emit different shapes.
386
+ *
387
+ * Never throws: a drain that fails or times out costs the injection, not the
388
+ * run. The caller treats an empty result as "nothing to resume with".
389
+ *
390
+ * `preventContinuation` is surfaced alongside the messages rather than left
391
+ * to the registry halt signal, which `processStream` only polls between
392
+ * stream events — by then the self-loop it was meant to prevent has already
393
+ * issued another model call, and a direct graph consumer never polls it.
394
+ */
395
+ private dispatchPreemptBoundary;
259
396
  createAgentNode(agentId: string): t.CompiledAgentWorfklow;
260
397
  createWorkflow(): t.CompiledStateWorkflow;
261
398
  /**
@@ -120,5 +120,20 @@ export declare class HookRegistry {
120
120
  hasResultAlteringHooks(sessionId?: string): boolean;
121
121
  /** True if at least one matcher exists for `event` (global + session). */
122
122
  hasHookFor(event: HookEvent, sessionId?: string): boolean;
123
+ /**
124
+ * True when at least one matcher for `event` would actually DISPATCH on a
125
+ * query-less call — a wildcard pattern with a non-empty `hooks` array.
126
+ *
127
+ * `hasHookFor` answers "is one registered", which is not the same question:
128
+ * a matcher carrying a pattern is inert for events that supply no
129
+ * `matchQuery`, so a caller using registration as a proxy for "something
130
+ * will run" can act on a hook that never fires. Mirrors the two skips in
131
+ * `executeHooks` (pattern mismatch, empty `hooks`).
132
+ *
133
+ * Non-allocating on purpose — `StandardGraph.canClaimPreemptSeal` reads it
134
+ * once per streamed chunk, where `getMatchers`' defensive `slice()` would
135
+ * allocate on every delta.
136
+ */
137
+ hasDispatchableHookFor(event: HookEvent, sessionId?: string): boolean;
123
138
  private ensureSessionBucket;
124
139
  }
@@ -8,11 +8,22 @@ export { executeHooks, DEFAULT_HOOK_TIMEOUT_MS } from './executeHooks';
8
8
  * be consumed by an SDK version that would silently drop it.
9
9
  */
10
10
  export declare const HOOK_INJECTED_MESSAGES_CAPABLE = true;
11
+ /**
12
+ * Feature probe for hosts: this SDK dispatches `PreemptBoundary`, so a
13
+ * cooperative mid-generation seal can drain into the run.
14
+ *
15
+ * Deliberately separate from {@link HOOK_INJECTED_MESSAGES_CAPABLE} — an SDK
16
+ * version can support `injectedMessages` at the tool boundary and know
17
+ * nothing about preemption. A host that probed the wrong flag would arm an
18
+ * interrupt control whose seal request is silently ignored, which reads to
19
+ * the user as a dead button rather than as an unsupported feature.
20
+ */
21
+ export declare const HOOK_PREEMPT_BOUNDARY_CAPABLE = true;
11
22
  export { matchesQuery, hasNestedQuantifier, MAX_PATTERN_LENGTH, MAX_CACHE_SIZE, } from './matchers';
12
23
  export { createToolPolicyHook } from './createToolPolicyHook';
13
24
  export type { ToolPolicyMode, ToolPolicyConfig } from './createToolPolicyHook';
14
25
  export { createWorkspacePolicyHook } from './createWorkspacePolicyHook';
15
26
  export type { OutsideAccessPolicy, WorkspacePolicyConfig, PathExtractor, } from './createWorkspacePolicyHook';
16
27
  export { HOOK_EVENTS } from './types';
17
- export type { HookEvent, HookInput, HookOutput, HookCallback, HookMatcher, HooksByEvent, HookInputByEvent, HookOutputByEvent, BaseHookInput, BaseHookOutput, ToolDecision, StopDecision, AggregatedHookResult, RunStartHookInput, UserPromptSubmitHookInput, PreToolUseHookInput, PostToolUseHookInput, PostToolUseFailureHookInput, PostToolBatchHookInput, PostToolBatchEntry, PermissionDeniedHookInput, SubagentStartHookInput, SubagentStopHookInput, StopHookInput, StopFailureHookInput, PreCompactHookInput, PostCompactHookInput, RunStartHookOutput, UserPromptSubmitHookOutput, PreToolUseHookOutput, PostToolUseHookOutput, PostToolUseFailureHookOutput, PostToolBatchHookOutput, PermissionDeniedHookOutput, SubagentStartHookOutput, SubagentStopHookOutput, StopHookOutput, StopFailureHookOutput, PreCompactHookOutput, PostCompactHookOutput, } from './types';
28
+ export type { HookEvent, HookInput, HookOutput, HookCallback, HookMatcher, HooksByEvent, HookInputByEvent, HookOutputByEvent, BaseHookInput, BaseHookOutput, ToolDecision, StopDecision, AggregatedHookResult, RunStartHookInput, UserPromptSubmitHookInput, PreToolUseHookInput, PostToolUseHookInput, PostToolUseFailureHookInput, PostToolBatchHookInput, PostToolBatchEntry, PreemptBoundaryHookInput, PermissionDeniedHookInput, SubagentStartHookInput, SubagentStopHookInput, StopHookInput, StopFailureHookInput, PreCompactHookInput, PostCompactHookInput, RunStartHookOutput, UserPromptSubmitHookOutput, PreToolUseHookOutput, PostToolUseHookOutput, PostToolUseFailureHookOutput, PostToolBatchHookOutput, PreemptBoundaryHookOutput, PermissionDeniedHookOutput, SubagentStartHookOutput, SubagentStopHookOutput, StopHookOutput, StopFailureHookOutput, PreCompactHookOutput, PostCompactHookOutput, } from './types';
18
29
  export type { ExecuteHooksOptions } from './executeHooks';