@librechat/agents 3.3.3 → 3.3.4
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.
- package/dist/cjs/agents/AgentContext.cjs +2 -1
- package/dist/cjs/agents/AgentContext.cjs.map +1 -1
- package/dist/cjs/graphs/Graph.cjs +342 -109
- package/dist/cjs/graphs/Graph.cjs.map +1 -1
- package/dist/cjs/graphs/MultiAgentGraph.cjs +3 -1
- package/dist/cjs/graphs/MultiAgentGraph.cjs.map +1 -1
- package/dist/cjs/llm/anthropic/utils/message_inputs.cjs +79 -6
- package/dist/cjs/llm/anthropic/utils/message_inputs.cjs.map +1 -1
- package/dist/cjs/llm/bedrock/utils/message_inputs.cjs +37 -10
- package/dist/cjs/llm/bedrock/utils/message_inputs.cjs.map +1 -1
- package/dist/cjs/llm/google/utils/common.cjs +19 -7
- package/dist/cjs/llm/google/utils/common.cjs.map +1 -1
- package/dist/cjs/llm/invoke.cjs +64 -3
- package/dist/cjs/llm/invoke.cjs.map +1 -1
- package/dist/cjs/llm/openai/index.cjs +41 -5
- package/dist/cjs/llm/openai/index.cjs.map +1 -1
- package/dist/cjs/llm/openai/utils/index.cjs +25 -4
- package/dist/cjs/llm/openai/utils/index.cjs.map +1 -1
- package/dist/cjs/llm/openrouter/index.cjs +4 -1
- package/dist/cjs/llm/openrouter/index.cjs.map +1 -1
- package/dist/cjs/main.cjs +19 -2
- package/dist/cjs/messages/cache.cjs +54 -33
- package/dist/cjs/messages/cache.cjs.map +1 -1
- package/dist/cjs/messages/contextPruning.cjs +17 -43
- package/dist/cjs/messages/contextPruning.cjs.map +1 -1
- package/dist/cjs/messages/core.cjs +315 -23
- package/dist/cjs/messages/core.cjs.map +1 -1
- package/dist/cjs/messages/format.cjs +218 -60
- package/dist/cjs/messages/format.cjs.map +1 -1
- package/dist/cjs/messages/index.cjs +1 -1
- package/dist/cjs/messages/prune.cjs +503 -127
- package/dist/cjs/messages/prune.cjs.map +1 -1
- package/dist/cjs/stream.cjs +7 -3
- package/dist/cjs/stream.cjs.map +1 -1
- package/dist/cjs/summarization/node.cjs +28 -14
- package/dist/cjs/summarization/node.cjs.map +1 -1
- package/dist/cjs/tools/ToolNode.cjs +54 -41
- package/dist/cjs/tools/ToolNode.cjs.map +1 -1
- package/dist/cjs/tools/toolOutputReferences.cjs +6 -0
- package/dist/cjs/tools/toolOutputReferences.cjs.map +1 -1
- package/dist/cjs/utils/index.cjs +1 -1
- package/dist/cjs/utils/llm.cjs +1 -1
- package/dist/cjs/utils/llm.cjs.map +1 -1
- package/dist/cjs/utils/tokens.cjs +307 -20
- package/dist/cjs/utils/tokens.cjs.map +1 -1
- package/dist/cjs/utils/toolContent.cjs +1514 -0
- package/dist/cjs/utils/toolContent.cjs.map +1 -0
- package/dist/esm/agents/AgentContext.mjs +2 -1
- package/dist/esm/agents/AgentContext.mjs.map +1 -1
- package/dist/esm/graphs/Graph.mjs +349 -116
- package/dist/esm/graphs/Graph.mjs.map +1 -1
- package/dist/esm/graphs/MultiAgentGraph.mjs +3 -1
- package/dist/esm/graphs/MultiAgentGraph.mjs.map +1 -1
- package/dist/esm/llm/anthropic/utils/message_inputs.mjs +79 -6
- package/dist/esm/llm/anthropic/utils/message_inputs.mjs.map +1 -1
- package/dist/esm/llm/bedrock/utils/message_inputs.mjs +37 -10
- package/dist/esm/llm/bedrock/utils/message_inputs.mjs.map +1 -1
- package/dist/esm/llm/google/utils/common.mjs +19 -7
- package/dist/esm/llm/google/utils/common.mjs.map +1 -1
- package/dist/esm/llm/invoke.mjs +65 -5
- package/dist/esm/llm/invoke.mjs.map +1 -1
- package/dist/esm/llm/openai/index.mjs +41 -5
- package/dist/esm/llm/openai/index.mjs.map +1 -1
- package/dist/esm/llm/openai/utils/index.mjs +25 -4
- package/dist/esm/llm/openai/utils/index.mjs.map +1 -1
- package/dist/esm/llm/openrouter/index.mjs +4 -1
- package/dist/esm/llm/openrouter/index.mjs.map +1 -1
- package/dist/esm/main.mjs +7 -7
- package/dist/esm/messages/cache.mjs +55 -34
- package/dist/esm/messages/cache.mjs.map +1 -1
- package/dist/esm/messages/contextPruning.mjs +17 -43
- package/dist/esm/messages/contextPruning.mjs.map +1 -1
- package/dist/esm/messages/core.mjs +305 -24
- package/dist/esm/messages/core.mjs.map +1 -1
- package/dist/esm/messages/format.mjs +218 -61
- package/dist/esm/messages/format.mjs.map +1 -1
- package/dist/esm/messages/index.mjs +1 -1
- package/dist/esm/messages/prune.mjs +500 -128
- package/dist/esm/messages/prune.mjs.map +1 -1
- package/dist/esm/stream.mjs +7 -3
- package/dist/esm/stream.mjs.map +1 -1
- package/dist/esm/summarization/node.mjs +28 -14
- package/dist/esm/summarization/node.mjs.map +1 -1
- package/dist/esm/tools/ToolNode.mjs +54 -41
- package/dist/esm/tools/ToolNode.mjs.map +1 -1
- package/dist/esm/tools/toolOutputReferences.mjs +6 -0
- package/dist/esm/tools/toolOutputReferences.mjs.map +1 -1
- package/dist/esm/utils/index.mjs +1 -1
- package/dist/esm/utils/llm.mjs +1 -1
- package/dist/esm/utils/llm.mjs.map +1 -1
- package/dist/esm/utils/tokens.mjs +307 -21
- package/dist/esm/utils/tokens.mjs.map +1 -1
- package/dist/esm/utils/toolContent.mjs +1503 -0
- package/dist/esm/utils/toolContent.mjs.map +1 -0
- package/dist/types/graphs/Graph.d.ts +1 -1
- package/dist/types/llm/invoke.d.ts +27 -1
- package/dist/types/llm/openai/index.d.ts +4 -0
- package/dist/types/llm/openai/utils/index.d.ts +2 -0
- package/dist/types/llm/openrouter/index.d.ts +5 -0
- package/dist/types/messages/contextPruning.d.ts +2 -1
- package/dist/types/messages/core.d.ts +36 -0
- package/dist/types/messages/format.d.ts +6 -0
- package/dist/types/messages/prune.d.ts +16 -12
- package/dist/types/types/stream.d.ts +1 -1
- package/dist/types/utils/tokens.d.ts +7 -0
- package/dist/types/utils/toolContent.d.ts +107 -0
- package/package.json +1 -1
- package/src/__tests__/stream.eagerEventExecution.test.ts +74 -0
- package/src/agents/AgentContext.ts +1 -0
- package/src/graphs/Graph.ts +698 -200
- package/src/graphs/MultiAgentGraph.ts +6 -1
- package/src/graphs/__tests__/Graph.contextOverflow.test.ts +1128 -4
- package/src/llm/anthropic/utils/message_inputs.ts +158 -12
- package/src/llm/anthropic/utils/tool-id-normalization.test.ts +109 -0
- package/src/llm/bedrock/utils/message_inputs.test.ts +49 -1
- package/src/llm/bedrock/utils/message_inputs.ts +86 -13
- package/src/llm/google/utils/common.test.ts +75 -9
- package/src/llm/google/utils/common.ts +34 -3
- package/src/llm/invoke.test.ts +488 -0
- package/src/llm/invoke.ts +196 -2
- package/src/llm/openai/index.ts +106 -6
- package/src/llm/openai/utils/index.ts +109 -53
- package/src/llm/openai/utils/messages.test.ts +330 -1
- package/src/llm/openrouter/index.ts +12 -2
- package/src/llm/openrouter/reasoning.test.ts +314 -0
- package/src/messages/__tests__/observationMasking.test.ts +93 -2
- package/src/messages/cache.tail.test.ts +193 -0
- package/src/messages/cache.test.ts +113 -0
- package/src/messages/cache.ts +92 -60
- package/src/messages/contextPruning.test.ts +184 -0
- package/src/messages/contextPruning.ts +49 -42
- package/src/messages/core.ts +653 -40
- package/src/messages/ensureThinkingBlock.test.ts +49 -1
- package/src/messages/foldToollessToolBlocks.test.ts +163 -5
- package/src/messages/format.ts +363 -91
- package/src/messages/formatAgentMessages.test.ts +604 -14
- package/src/messages/formatAgentMessages.tools.test.ts +103 -0
- package/src/messages/prune.ts +996 -183
- package/src/specs/prune.test.ts +1083 -6
- package/src/specs/summarization-unit.test.ts +105 -0
- package/src/specs/tokens.test.ts +609 -32
- package/src/stream.ts +23 -15
- package/src/summarization/__tests__/node.test.ts +77 -0
- package/src/summarization/node.ts +46 -18
- package/src/tools/ToolNode.ts +147 -68
- package/src/tools/__tests__/ToolNode.onResultCompletion.test.ts +148 -1
- package/src/tools/__tests__/ToolNode.outputReferences.test.ts +112 -3
- package/src/tools/__tests__/annotateMessagesForLLM.test.ts +32 -0
- package/src/tools/__tests__/directToolHooks.test.ts +255 -7
- package/src/tools/toolOutputReferences.ts +6 -0
- package/src/types/stream.ts +1 -1
- package/src/utils/llm.test.ts +18 -0
- package/src/utils/llm.ts +4 -1
- package/src/utils/tokens.ts +586 -31
- package/src/utils/toolContent.test.ts +1432 -0
- package/src/utils/toolContent.ts +2707 -0
|
@@ -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;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AgB,KAAK,IACzB,GACA,qBAAqB,cAAc,mBACrC;EACA,MAAM,UAAU,0BAA0B,eAAe,aAAa;EACtE,MAAM,YAAgC,CAAC;EACvC,IAAI,kBAAkB;EACtB,KAAK,IAAI,IAAI,GAAG,IAAI,iBAAiB,QAAQ,KAAK;GAChD,MAAM,QAAQ,iBAAiB;GAC/B,IAAI,gBAAgB,OAAO;QACrB,qBAAqB,OAAO,GAC9B,UAAU,KAAK,KAAK;GAAA,OAEjB,IAAI,CAAC,iBAAiB;IAC3B,IAAI,QAAQ,SAAS,GACnB,UAAU,KAAK;KAAE,MAAM;KAAQ,MAAM;IAAQ,CAAC;IAEhD,kBAAkB;GACpB;EACF;EACA,IAAI,CAAC,mBAAmB,QAAQ,SAAS,GACvC,UAAU,KAAK;GAAE,MAAM;GAAQ,MAAM;EAAQ,CAAC;EAehD,KARE,uBAAuB,KAAK,UAAU,WAAW,IAC7C,wBACA,WACA,OAAO,kBACP,CAAC,GACD,cACF,IACE,QAAQ,UACO,oBACnB,OAAO;GACL,SAAS,oCACP,kBACA,oBACA,cACF;GACA,SAAS;GACT;EACF;EAGF,OAAO;GACL,SAAS;GACT,SAAS;GACT;EACF;CACF,QAAQ;EACN,MAAM,aAAa,gCACjB,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"}
|
|
@@ -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> {
|
|
@@ -41,6 +41,19 @@ export type InvokeContext = NonNullable<Parameters<ChatModelStreamHandler['handl
|
|
|
41
41
|
* When provided, replaces the default `ChatModelStreamHandler`.
|
|
42
42
|
*/
|
|
43
43
|
export type OnChunk = (chunk: AIMessageChunk) => void | Promise<void>;
|
|
44
|
+
export declare function usesNativeOpenAIResponses(model: t.ChatModel, provider: Providers, callOptions?: unknown): boolean;
|
|
45
|
+
/**
|
|
46
|
+
* Produces the exact provider-facing message representation before a model
|
|
47
|
+
* adapter serializes it. This is shared by invocation and Graph's final budget
|
|
48
|
+
* guard so structured tool output cannot grow after the payload was measured.
|
|
49
|
+
*/
|
|
50
|
+
export declare function projectMessagesForProvider({ model, messages, provider, maxToolResultChars, callOptions, }: {
|
|
51
|
+
model: t.ChatModel;
|
|
52
|
+
messages: BaseMessage[];
|
|
53
|
+
provider: Providers;
|
|
54
|
+
maxToolResultChars?: number;
|
|
55
|
+
callOptions?: unknown;
|
|
56
|
+
}): BaseMessage[];
|
|
44
57
|
/**
|
|
45
58
|
* Invokes a chat model with the given messages, handling both streaming and
|
|
46
59
|
* non-streaming paths.
|
|
@@ -85,7 +98,7 @@ export declare function getFallbackOverflowCandidates(error: unknown): FallbackO
|
|
|
85
98
|
* behind a later unrelated error would surface a dead end instead. Ordinary
|
|
86
99
|
* failures still throw last-error-wins.
|
|
87
100
|
*/
|
|
88
|
-
export declare function tryFallbackProviders({ fallbacks, tools, messages, config, primaryError, context, onChunk, overflowContext, }: {
|
|
101
|
+
export declare function tryFallbackProviders({ fallbacks, tools, messages, config, primaryError, context, onChunk, overflowContext, prepareProviderMessages, }: {
|
|
89
102
|
fallbacks: t.FallbackConfig[];
|
|
90
103
|
tools?: t.GraphTools;
|
|
91
104
|
messages: BaseMessage[];
|
|
@@ -100,4 +113,17 @@ export declare function tryFallbackProviders({ fallbacks, tools, messages, confi
|
|
|
100
113
|
* be dropped in favour of whichever failure came last.
|
|
101
114
|
*/
|
|
102
115
|
overflowContext?: ContextOverflowContext;
|
|
116
|
+
/**
|
|
117
|
+
* Optional final payload guard used by Graph. It receives the initialized,
|
|
118
|
+
* tool-bound fallback model so Responses-vs-Chat projection is exact before
|
|
119
|
+
* the fallback request is measured and sent.
|
|
120
|
+
*/
|
|
121
|
+
prepareProviderMessages?: (input: {
|
|
122
|
+
model: t.ChatModel;
|
|
123
|
+
messages: BaseMessage[];
|
|
124
|
+
provider: Providers;
|
|
125
|
+
clientOptions?: t.ClientOptions;
|
|
126
|
+
maxContextTokens?: number;
|
|
127
|
+
config?: RunnableConfig;
|
|
128
|
+
}) => BaseMessage[] | Promise<BaseMessage[]>;
|
|
103
129
|
}): Promise<Partial<t.BaseGraphState> | undefined>;
|
|
@@ -11,6 +11,7 @@ import type { ChatResult } from '@langchain/core/outputs';
|
|
|
11
11
|
import type { ChatXAIInput } from '@langchain/xai';
|
|
12
12
|
import type * as t from '@langchain/openai';
|
|
13
13
|
import type { HeaderValue, HeadersLike } from './types';
|
|
14
|
+
import type { PromptCacheTtl } from '@/messages/cache';
|
|
14
15
|
export declare function isHeaders(headers: unknown): headers is Headers;
|
|
15
16
|
export declare function normalizeHeaders(headers: HeadersLike): Record<string, HeaderValue | readonly HeaderValue[]>;
|
|
16
17
|
type OpenAICoreRequestOptions = OpenAIClient.RequestOptions;
|
|
@@ -20,6 +21,9 @@ type LibreChatOpenAIFields = t.ChatOpenAIFields & {
|
|
|
20
21
|
includeReasoningContent?: boolean;
|
|
21
22
|
includeReasoningDetails?: boolean;
|
|
22
23
|
convertReasoningDetailsToContent?: boolean;
|
|
24
|
+
preserveToolCacheControl?: boolean;
|
|
25
|
+
responsesPromptCache?: boolean;
|
|
26
|
+
responsesPromptCacheTtl?: PromptCacheTtl;
|
|
23
27
|
promptCacheExplicit?: boolean;
|
|
24
28
|
safety_identifier?: string;
|
|
25
29
|
};
|
|
@@ -22,6 +22,8 @@ export interface ConvertMessagesOptions {
|
|
|
22
22
|
includeReasoningDetails?: boolean;
|
|
23
23
|
/** Convert reasoning_details to content blocks for Claude (requires content array format) */
|
|
24
24
|
convertReasoningDetailsToContent?: boolean;
|
|
25
|
+
/** Preserve OpenRouter's canonical cache-decorated tool text block. */
|
|
26
|
+
preserveToolCacheControl?: boolean;
|
|
25
27
|
}
|
|
26
28
|
export declare function _convertMessagesToOpenAIParams(messages: BaseMessage[], model?: string, options?: ConvertMessagesOptions): OpenAICompletionParam[];
|
|
27
29
|
export declare function _convertMessagesToOpenAIResponsesParams(messages: BaseMessage[], model?: string, zdrEnabled?: boolean): ResponsesInputItem[];
|
|
@@ -16,6 +16,7 @@ export interface ChatOpenRouterCallOptions extends Omit<ChatOpenAICallOptions, '
|
|
|
16
16
|
include_reasoning?: boolean;
|
|
17
17
|
reasoning?: OpenRouterReasoning;
|
|
18
18
|
modelKwargs?: OpenAIChatInput['modelKwargs'];
|
|
19
|
+
useResponsesApi?: boolean;
|
|
19
20
|
promptCache?: boolean;
|
|
20
21
|
/**
|
|
21
22
|
* Prompt-cache breakpoint TTL. Defaults to `'1h'` (extended cache) when
|
|
@@ -29,6 +30,10 @@ export type ChatOpenRouterInput = Partial<ChatOpenRouterCallOptions & OpenAIChat
|
|
|
29
30
|
/** invocationParams return type extended with OpenRouter reasoning */
|
|
30
31
|
export type OpenRouterInvocationParams = Omit<OpenAIClient.Chat.ChatCompletionCreateParams, 'messages'> & {
|
|
31
32
|
reasoning?: OpenRouterReasoning;
|
|
33
|
+
cache_control?: {
|
|
34
|
+
type: 'ephemeral';
|
|
35
|
+
ttl?: '1h';
|
|
36
|
+
};
|
|
32
37
|
};
|
|
33
38
|
type InvocationParamsExtra = {
|
|
34
39
|
streaming?: boolean;
|
|
@@ -9,7 +9,8 @@
|
|
|
9
9
|
* - Hard-clear: Replace entire content with a placeholder.
|
|
10
10
|
*
|
|
11
11
|
* Messages in the "protected zone" (recent assistant turns, system/pre-first-human
|
|
12
|
-
* messages
|
|
12
|
+
* messages) are never pruned. Atomic media/resource blocks are preserved when
|
|
13
|
+
* they fit; oversized inline payloads are replaced with bounded placeholders.
|
|
13
14
|
*/
|
|
14
15
|
import { type BaseMessage } from '@langchain/core/messages';
|
|
15
16
|
import type { ContextPruningSettings } from './contextPruningSettings';
|
|
@@ -9,6 +9,42 @@ export declare function getConverseOverrideMessage({ userMessage, lastMessageX,
|
|
|
9
9
|
export declare function modifyDeltaProperties(provider: Providers, obj?: AIMessageChunk): AIMessageChunk | undefined;
|
|
10
10
|
export declare function formatAnthropicMessage(message: AIMessageChunk): AIMessage;
|
|
11
11
|
export declare function convertMessagesToContent(messages: BaseMessage[]): t.MessageContentComplex[];
|
|
12
|
+
/**
|
|
13
|
+
* Drops incomplete streamed text-input fragments that some providers retain
|
|
14
|
+
* beside the assembled parsed tool call. They are neither user-visible text
|
|
15
|
+
* nor valid content blocks for a subsequent provider.
|
|
16
|
+
*/
|
|
17
|
+
export declare function projectToolStreamContentForProvider(messages: BaseMessage[]): BaseMessage[];
|
|
18
|
+
/** Projects OpenAI-compatible tool content without changing parsed call parents. */
|
|
19
|
+
export declare function projectOpenAIToolMessageContent(messages: BaseMessage[], maxChars?: number): BaseMessage[];
|
|
20
|
+
/** Projects an actual OpenAI-compatible Chat attempt and removes cache metadata. */
|
|
21
|
+
export declare function projectOpenAIChatToolMessageContent(messages: BaseMessage[], maxChars?: number): BaseMessage[];
|
|
22
|
+
/** Preserves OpenRouter's cache-decorated text blocks for a Chat attempt. */
|
|
23
|
+
export declare function projectOpenRouterToolMessageContent(messages: BaseMessage[], maxChars?: number): BaseMessage[];
|
|
24
|
+
/** Projects Responses tool content and collapses parsed/raw computer-call mirrors. */
|
|
25
|
+
export declare function projectOpenAIResponsesToolMessageContent(messages: BaseMessage[], maxChars?: number): BaseMessage[];
|
|
26
|
+
/** Removes Anthropic/OpenRouter cache metadata before unsupported providers run. */
|
|
27
|
+
export declare function projectCacheControlledToolOutputsToText(messages: BaseMessage[], maxChars?: number): BaseMessage[];
|
|
28
|
+
/** Unwraps a canonical single text block after provider cache markers are removed. */
|
|
29
|
+
export declare function projectSingleTextToolOutputsToText(messages: BaseMessage[], maxChars?: number): BaseMessage[];
|
|
30
|
+
/** Serializes provider-neutral structured tool outputs without media pairing. */
|
|
31
|
+
export declare function projectStructuredToolOutputsToText(messages: BaseMessage[], maxChars?: number): BaseMessage[];
|
|
32
|
+
/**
|
|
33
|
+
* Non-Responses providers cannot consume native computer screenshots. Keep
|
|
34
|
+
* the tool-call structure intact, but replace screenshot bytes with a bounded
|
|
35
|
+
* text marker at the actual invocation boundary.
|
|
36
|
+
*/
|
|
37
|
+
export declare function projectComputerCallOutputsToText(messages: BaseMessage[]): BaseMessage[];
|
|
38
|
+
export declare function projectAnthropicArtifactContent(messages: BaseMessage[], maxChars?: number): BaseMessage[];
|
|
39
|
+
/**
|
|
40
|
+
* Mutating compatibility wrapper retained for existing package consumers.
|
|
41
|
+
* New provider-call paths should use `projectAnthropicArtifactContent`.
|
|
42
|
+
*/
|
|
12
43
|
export declare function formatAnthropicArtifactContent(messages: BaseMessage[]): void;
|
|
44
|
+
export declare function projectArtifactPayload(messages: BaseMessage[], maxChars?: number): BaseMessage[];
|
|
45
|
+
/**
|
|
46
|
+
* Mutating compatibility wrapper retained for existing package consumers.
|
|
47
|
+
* New provider-call paths should use `projectArtifactPayload`.
|
|
48
|
+
*/
|
|
13
49
|
export declare function formatArtifactPayload(messages: BaseMessage[]): void;
|
|
14
50
|
export declare function findLastIndex<T>(array: T[], predicate: (value: T) => boolean): number;
|
|
@@ -151,6 +151,12 @@ export declare const formatAgentMessages: (payload: TPayload, indexTokenCountMap
|
|
|
151
151
|
* @returns A new map with the system message at index 0 and all other indices shifted by 1
|
|
152
152
|
*/
|
|
153
153
|
export declare function shiftIndexTokenCountMap(indexTokenCountMap: Record<number, number>, instructionsTokenCount: number): Record<number, number>;
|
|
154
|
+
/**
|
|
155
|
+
* Identifies provider-context placeholders created by this module without
|
|
156
|
+
* trusting user-controlled content prefixes or leaking marker metadata onto
|
|
157
|
+
* the provider wire.
|
|
158
|
+
*/
|
|
159
|
+
export declare function isSyntheticProviderContextMessage(message: BaseMessage): boolean;
|
|
154
160
|
/**
|
|
155
161
|
* Ensures compatibility when switching from a non-thinking agent to a thinking-enabled agent.
|
|
156
162
|
* Converts AI messages with tool calls (that lack thinking/reasoning blocks) into buffer strings,
|
|
@@ -4,6 +4,8 @@ import type { TokenCounter } from '@/types/run';
|
|
|
4
4
|
import { ContentTypes, Providers } from '@/common';
|
|
5
5
|
/** Default fraction of the token budget reserved as headroom (5 %). */
|
|
6
6
|
export declare const DEFAULT_RESERVE_RATIO = 0.05;
|
|
7
|
+
/** Provider framing reserved for the assistant reply label. */
|
|
8
|
+
export declare const REPLY_PRIMER_TOKENS = 3;
|
|
7
9
|
/** Hard cap for the originalToolContent store (~2 MB estimated from char length). */
|
|
8
10
|
export declare const ORIGINAL_CONTENT_MAX_CHARS = 2000000;
|
|
9
11
|
/**
|
|
@@ -25,6 +27,8 @@ export declare function clampCalibrationRatio(ratio: number): number;
|
|
|
25
27
|
export type PruneMessagesFactoryParams = {
|
|
26
28
|
provider?: Providers;
|
|
27
29
|
maxTokens: number;
|
|
30
|
+
/** Per-tool-result character cap applied while reconciling cached counts. */
|
|
31
|
+
maxToolResultChars?: number;
|
|
28
32
|
startIndex: number;
|
|
29
33
|
tokenCounter: TokenCounter;
|
|
30
34
|
indexTokenCountMap: Record<string, number | undefined>;
|
|
@@ -113,7 +117,7 @@ export declare function repairOrphanedToolMessages({ context, allMessages, token
|
|
|
113
117
|
* Includes a fast-path: if every tool_call has a matching tool_result and
|
|
114
118
|
* vice-versa, the original array is returned immediately with zero allocation.
|
|
115
119
|
*/
|
|
116
|
-
export declare function sanitizeOrphanToolBlocks(messages: BaseMessage[]): BaseMessage[];
|
|
120
|
+
export declare function sanitizeOrphanToolBlocks(messages: BaseMessage[], onMessageCloned?: (source: BaseMessage, clone: BaseMessage) => void): BaseMessage[];
|
|
117
121
|
/**
|
|
118
122
|
* Calculates the total tokens from a single usage object
|
|
119
123
|
*
|
|
@@ -200,18 +204,18 @@ export declare function preFlightTruncateToolResults(params: {
|
|
|
200
204
|
tokenCounter: TokenCounter;
|
|
201
205
|
}): number;
|
|
202
206
|
/**
|
|
203
|
-
*
|
|
204
|
-
*
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
*
|
|
211
|
-
*
|
|
212
|
-
*
|
|
213
|
-
* @returns The number of AI messages that had tool_use inputs truncated.
|
|
207
|
+
* Serializes one structured tool-call input as valid, bounded JSON without
|
|
208
|
+
* invoking user-defined accessors or `toJSON`.
|
|
209
|
+
*/
|
|
210
|
+
export declare function serializeToolCallInput(input: unknown, maxChars?: number): string;
|
|
211
|
+
/** Per-input cap: 15% of context at ~4 chars/token, never above 200K chars. */
|
|
212
|
+
export declare function calculateMaxToolCallInputChars(maxContextTokens?: number): number;
|
|
213
|
+
/**
|
|
214
|
+
* Projects historical tool-call inputs into a provider-safe bounded form.
|
|
215
|
+
* Returns the original array when no message changes and otherwise clones only
|
|
216
|
+
* the array and AI messages whose inline input or `tool_calls` args changed.
|
|
214
217
|
*/
|
|
218
|
+
export declare function projectToolCallInputs(messages: BaseMessage[], maxInputChars: number): BaseMessage[];
|
|
215
219
|
export declare function preFlightTruncateToolCallInputs(params: {
|
|
216
220
|
messages: BaseMessage[];
|
|
217
221
|
maxContextTokens: number;
|
|
@@ -265,7 +265,7 @@ export type ToolCallPart = {
|
|
|
265
265
|
/** If provided, an identifier associated with the tool call */
|
|
266
266
|
id?: string;
|
|
267
267
|
/** If provided, the output of the tool call */
|
|
268
|
-
output?:
|
|
268
|
+
output?: ToolResultContent['content'];
|
|
269
269
|
/** Auth URL */
|
|
270
270
|
auth?: string;
|
|
271
271
|
/** Expiration time */
|
|
@@ -44,6 +44,13 @@ export declare function estimateDocumentBlockTokens(block: Record<string, unknow
|
|
|
44
44
|
*/
|
|
45
45
|
export declare function estimateTimedMediaBlockTokens(block: Record<string, unknown>): number;
|
|
46
46
|
export declare function encodingForModel(model: string): EncodingName;
|
|
47
|
+
/**
|
|
48
|
+
* Detects values whose native JSON representation can differ after local
|
|
49
|
+
* measurement. Accessor properties and `toJSON` hooks are deliberately not
|
|
50
|
+
* invoked; values too large to inspect within bounded work are treated as
|
|
51
|
+
* unsafe so the caller can normalize or reject them conservatively.
|
|
52
|
+
*/
|
|
53
|
+
export declare function hasUnsafeStructuredSerialization(value: unknown): boolean;
|
|
47
54
|
export declare function getTokenCountForMessage(message: BaseMessage, getTokenCount: (text: string) => number, encoding?: EncodingName): number;
|
|
48
55
|
/**
|
|
49
56
|
* Largest-remainder apportionment: scales each count by `multiplier` and
|