@librechat/agents 3.2.35 → 3.2.37

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (98) hide show
  1. package/dist/cjs/agents/AgentContext.cjs +75 -2
  2. package/dist/cjs/agents/AgentContext.cjs.map +1 -1
  3. package/dist/cjs/agents/projection.cjs +25 -0
  4. package/dist/cjs/agents/projection.cjs.map +1 -0
  5. package/dist/cjs/graphs/Graph.cjs +10 -26
  6. package/dist/cjs/graphs/Graph.cjs.map +1 -1
  7. package/dist/cjs/langfuse.cjs +16 -5
  8. package/dist/cjs/langfuse.cjs.map +1 -1
  9. package/dist/cjs/langfuseToolOutputTracing.cjs +7 -0
  10. package/dist/cjs/langfuseToolOutputTracing.cjs.map +1 -1
  11. package/dist/cjs/llm/anthropic/utils/message_inputs.cjs +118 -7
  12. package/dist/cjs/llm/anthropic/utils/message_inputs.cjs.map +1 -1
  13. package/dist/cjs/llm/bedrock/utils/message_inputs.cjs +44 -4
  14. package/dist/cjs/llm/bedrock/utils/message_inputs.cjs.map +1 -1
  15. package/dist/cjs/main.cjs +7 -0
  16. package/dist/cjs/messages/budget.cjs +23 -0
  17. package/dist/cjs/messages/budget.cjs.map +1 -0
  18. package/dist/cjs/messages/cache.cjs +184 -0
  19. package/dist/cjs/messages/cache.cjs.map +1 -1
  20. package/dist/cjs/messages/index.cjs +1 -0
  21. package/dist/cjs/summarization/node.cjs +1 -1
  22. package/dist/cjs/summarization/node.cjs.map +1 -1
  23. package/dist/cjs/tools/search/format.cjs +91 -2
  24. package/dist/cjs/tools/search/format.cjs.map +1 -1
  25. package/dist/cjs/tools/search/tool.cjs +4 -3
  26. package/dist/cjs/tools/search/tool.cjs.map +1 -1
  27. package/dist/cjs/tools/toolOutputReferences.cjs +28 -14
  28. package/dist/cjs/tools/toolOutputReferences.cjs.map +1 -1
  29. package/dist/esm/agents/AgentContext.mjs +76 -3
  30. package/dist/esm/agents/AgentContext.mjs.map +1 -1
  31. package/dist/esm/agents/projection.mjs +25 -0
  32. package/dist/esm/agents/projection.mjs.map +1 -0
  33. package/dist/esm/graphs/Graph.mjs +9 -25
  34. package/dist/esm/graphs/Graph.mjs.map +1 -1
  35. package/dist/esm/langfuse.mjs +16 -5
  36. package/dist/esm/langfuse.mjs.map +1 -1
  37. package/dist/esm/langfuseToolOutputTracing.mjs +7 -0
  38. package/dist/esm/langfuseToolOutputTracing.mjs.map +1 -1
  39. package/dist/esm/llm/anthropic/utils/message_inputs.mjs +118 -7
  40. package/dist/esm/llm/anthropic/utils/message_inputs.mjs.map +1 -1
  41. package/dist/esm/llm/bedrock/utils/message_inputs.mjs +44 -4
  42. package/dist/esm/llm/bedrock/utils/message_inputs.mjs.map +1 -1
  43. package/dist/esm/main.mjs +4 -2
  44. package/dist/esm/messages/budget.mjs +23 -0
  45. package/dist/esm/messages/budget.mjs.map +1 -0
  46. package/dist/esm/messages/cache.mjs +182 -1
  47. package/dist/esm/messages/cache.mjs.map +1 -1
  48. package/dist/esm/messages/index.mjs +1 -0
  49. package/dist/esm/summarization/node.mjs +2 -2
  50. package/dist/esm/summarization/node.mjs.map +1 -1
  51. package/dist/esm/tools/search/format.mjs +91 -2
  52. package/dist/esm/tools/search/format.mjs.map +1 -1
  53. package/dist/esm/tools/search/tool.mjs +4 -3
  54. package/dist/esm/tools/search/tool.mjs.map +1 -1
  55. package/dist/esm/tools/toolOutputReferences.mjs +28 -14
  56. package/dist/esm/tools/toolOutputReferences.mjs.map +1 -1
  57. package/dist/types/agents/AgentContext.d.ts +30 -1
  58. package/dist/types/agents/projection.d.ts +26 -0
  59. package/dist/types/index.d.ts +1 -0
  60. package/dist/types/messages/budget.d.ts +11 -0
  61. package/dist/types/messages/cache.d.ts +47 -0
  62. package/dist/types/messages/index.d.ts +1 -0
  63. package/dist/types/tools/search/format.d.ts +4 -1
  64. package/dist/types/tools/search/types.d.ts +7 -0
  65. package/dist/types/types/graph.d.ts +2 -0
  66. package/package.json +2 -1
  67. package/src/agents/AgentContext.ts +105 -4
  68. package/src/agents/__tests__/AgentContext.test.ts +232 -9
  69. package/src/agents/__tests__/projection.test.ts +73 -0
  70. package/src/agents/projection.ts +46 -0
  71. package/src/graphs/Graph.ts +66 -65
  72. package/src/index.ts +3 -0
  73. package/src/langfuse.ts +38 -4
  74. package/src/langfuseToolOutputTracing.ts +18 -0
  75. package/src/llm/anthropic/utils/cross-provider-reasoning.test.ts +317 -0
  76. package/src/llm/anthropic/utils/message_inputs.ts +209 -19
  77. package/src/llm/anthropic/utils/stripPrefillCache.test.ts +111 -0
  78. package/src/llm/bedrock/utils/cross-provider-reasoning.test.ts +131 -0
  79. package/src/llm/bedrock/utils/message_inputs.test.ts +129 -0
  80. package/src/llm/bedrock/utils/message_inputs.ts +81 -4
  81. package/src/llm/bedrock/utils/toolResultCachePoint.test.ts +103 -0
  82. package/src/messages/budget.ts +32 -0
  83. package/src/messages/cache.tail.test.ts +340 -0
  84. package/src/messages/cache.ts +267 -1
  85. package/src/messages/index.ts +1 -0
  86. package/src/messages/tailCacheConversion.test.ts +161 -0
  87. package/src/scripts/bench-prompt-cache.ts +479 -0
  88. package/src/specs/langfuse-config.test.ts +69 -2
  89. package/src/specs/langfuse-metadata.test.ts +44 -0
  90. package/src/specs/langfuse-tool-output-tracing.test.ts +6 -0
  91. package/src/summarization/node.ts +2 -2
  92. package/src/tools/__tests__/annotateMessagesForLLM.test.ts +50 -0
  93. package/src/tools/search/format.test.ts +242 -0
  94. package/src/tools/search/format.ts +122 -5
  95. package/src/tools/search/tool.ts +5 -1
  96. package/src/tools/search/types.ts +7 -0
  97. package/src/tools/toolOutputReferences.ts +34 -20
  98. package/src/types/graph.ts +2 -0
@@ -466,20 +466,34 @@ function annotateMessagesForLLM(messages, registry, runId) {
466
466
  const tm = m;
467
467
  let nextContent = tm.content;
468
468
  if (annotates && typeof tm.content === "string") nextContent = annotateToolOutputWithReference(tm.content, liveRef, unresolved);
469
- else if (annotates && Array.isArray(tm.content) && unresolved.length > 0)
470
- /**
471
- * `as unknown as ToolMessage['content']` is unavoidable here:
472
- * LangChain's content union (`MessageContentComplex[] |
473
- * DataContentBlock[] | string`) does not accept a freshly built
474
- * mixed array literal even though the structural shape is valid
475
- * at runtime. The double-cast is structurally safe we
476
- * preserve every block from `tm.content` and prepend a single
477
- * `{ type: 'text', text }` block that all providers accept.
478
- */
479
- nextContent = [{
480
- type: "text",
481
- text: `[unresolved refs: ${unresolved.join(", ")}]`
482
- }, ...tm.content];
469
+ else if (annotates && Array.isArray(tm.content)) {
470
+ /**
471
+ * Array tool content. The string annotator can't run this notably
472
+ * includes a tail tool result that prompt caching rewrote from a string
473
+ * into a text-block array to host its `cache_control` / `cachePoint`
474
+ * marker (the `_refKey` survives on `additional_kwargs`). Project the
475
+ * same markers the string path would, as leading text blocks: the live
476
+ * `[ref: …]` prefix and/or the unresolved-refs warning. Without this the
477
+ * common tool-result tail loses its reference marker once cached.
478
+ *
479
+ * `as unknown as ToolMessage['content']` is unavoidable: LangChain's
480
+ * content union does not accept a freshly built mixed array literal even
481
+ * though the structural shape is valid at runtime. The double-cast is
482
+ * structurally safe — every original block is preserved and only
483
+ * `{ type: 'text', text }` blocks (which all providers accept) are
484
+ * prepended.
485
+ */
486
+ const prefixBlocks = [];
487
+ if (liveRef != null) prefixBlocks.push({
488
+ type: "text",
489
+ text: buildReferencePrefix(liveRef)
490
+ });
491
+ if (unresolved.length > 0) prefixBlocks.push({
492
+ type: "text",
493
+ text: `[unresolved refs: ${unresolved.join(", ")}]`
494
+ });
495
+ if (prefixBlocks.length > 0) nextContent = [...prefixBlocks, ...tm.content];
496
+ }
483
497
  /**
484
498
  * Project unconditionally: even when no annotation applies (stale
485
499
  * `_refKey` or non-annotatable content), `cloneToolMessageWithContent`
@@ -1 +1 @@
1
- {"version":3,"file":"toolOutputReferences.mjs","names":[],"sources":["../../../src/tools/toolOutputReferences.ts"],"sourcesContent":["/**\n * Tool output reference registry.\n *\n * When enabled via `RunConfig.toolOutputReferences.enabled`, ToolNode\n * stores each successful tool output under a stable key\n * (`tool<idx>turn<turn>`) where `idx` is the tool's position within a\n * ToolNode batch and `turn` is the batch index within the run\n * (incremented once per ToolNode invocation).\n *\n * Subsequent tool calls can pipe a previous output into their args by\n * embedding `{{tool<idx>turn<turn>}}` inside any string argument;\n * {@link ToolOutputReferenceRegistry.resolve} walks the args and\n * substitutes the placeholders immediately before invocation.\n *\n * The registry stores the *raw, untruncated* tool output so a later\n * `{{…}}` substitution pipes the full payload into the next tool —\n * even when the LLM only saw a head+tail-truncated preview in\n * `ToolMessage.content`. Outputs are stored without any annotation\n * (the `_ref` key or the `[ref: ...]` prefix seen by the LLM is\n * strictly a UX signal attached to `ToolMessage.content`). Keeping the\n * registry pristine means downstream bash/jq piping receives the\n * complete, verbatim output with no injected fields.\n */\n\nimport { ToolMessage } from '@langchain/core/messages';\nimport type { BaseMessage } from '@langchain/core/messages';\nimport {\n calculateMaxTotalToolOutputSize,\n HARD_MAX_TOOL_RESULT_CHARS,\n HARD_MAX_TOTAL_TOOL_OUTPUT_SIZE,\n} from '@/utils/truncation';\n\n/**\n * Non-global matcher for a single `{{tool<i>turn<n>}}` placeholder.\n * Exported for consumers that want to detect references (e.g., syntax\n * highlighting, docs). The stateful `g` variant lives inside the\n * registry so nobody trips on `lastIndex`.\n */\nexport const TOOL_OUTPUT_REF_PATTERN = /\\{\\{(tool\\d+turn\\d+)\\}\\}/;\n\n/** Object key used when a parsed-object output has `_ref` injected. */\nexport const TOOL_OUTPUT_REF_KEY = '_ref';\n\n/**\n * Object key used to carry unresolved reference warnings on a parsed-\n * object output. Using a dedicated field instead of a trailing text\n * line keeps the annotated `ToolMessage.content` parseable as JSON for\n * downstream consumers that rely on the object shape.\n */\nexport const TOOL_OUTPUT_UNRESOLVED_KEY = '_unresolved_refs';\n\n/** Single-line prefix prepended to non-object tool outputs so the LLM sees the reference key. */\nexport function buildReferencePrefix(key: string): string {\n return `[ref: ${key}]`;\n}\n\n/** Stable registry key for a tool output. */\nexport function buildReferenceKey(toolIndex: number, turn: number): string {\n return `tool${toolIndex}turn${turn}`;\n}\n\nexport type ToolOutputReferenceRegistryOptions = {\n /** Maximum characters stored per registered output. */\n maxOutputSize?: number;\n /** Maximum total characters retained across all registered outputs. */\n maxTotalSize?: number;\n /**\n * Upper bound on the number of concurrently-tracked runs. When\n * exceeded, the oldest run bucket is evicted (FIFO). Defaults to 32.\n */\n maxActiveRuns?: number;\n};\n\n/**\n * Result of resolving placeholders in tool args.\n */\nexport type ResolveResult<T> = {\n /** Arguments with placeholders replaced. Same shape as the input. */\n resolved: T;\n /** Reference keys that were referenced but had no stored value. */\n unresolved: string[];\n};\n\n/**\n * Read-only view over a frozen registry snapshot. Returned by\n * {@link ToolOutputReferenceRegistry.snapshot} for callers that need\n * to resolve placeholders against the registry state at a specific\n * point in time, ignoring any subsequent registrations.\n */\nexport interface ToolOutputResolveView {\n resolve<T>(args: T): ResolveResult<T>;\n}\n\n/**\n * Pre-resolved arg map keyed by `toolCallId`. Used by the mixed\n * direct+event dispatch path to feed event calls' resolved args\n * (captured pre-batch) into the dispatcher without re-resolving\n * against the now-stale live registry.\n */\nexport type PreResolvedArgsMap = Map<\n string,\n { resolved: Record<string, unknown>; unresolved: string[] }\n>;\n\n/**\n * Per-call sink for resolved args, keyed by `toolCallId`. Threaded\n * as a per-batch local map so concurrent `ToolNode.run()` calls do\n * not race on shared sink state.\n */\nexport type ResolvedArgsByCallId = Map<string, Record<string, unknown>>;\n\nconst EMPTY_ENTRIES: ReadonlyMap<string, string> = new Map<string, string>();\n\n/**\n * Per-run state bucket held inside the registry. Each distinct\n * `run_id` gets its own bucket so overlapping concurrent runs on a\n * shared registry cannot leak outputs, turn counters, or warn-memos\n * into one another.\n */\nclass RunStateBucket {\n entries: Map<string, string> = new Map();\n totalSize: number = 0;\n turnCounter: number = 0;\n warnedNonStringTools: Set<string> = new Set();\n}\n\n/**\n * Anonymous (`run_id` absent) bucket key. Anonymous batches are\n * treated as fresh runs on every invocation — see `nextTurn`.\n */\nconst ANON_RUN_KEY = '\\0anon';\n\n/**\n * Default upper bound on the number of concurrently-tracked runs per\n * registry. When exceeded, the oldest run's bucket (by insertion\n * order) is evicted. Keeps memory bounded when a ToolNode is reused\n * across many runs without explicit `releaseRun` calls.\n */\nconst DEFAULT_MAX_ACTIVE_RUNS = 32;\n\n/**\n * Ordered map of reference-key → stored output, partitioned by run so\n * concurrent / interleaved runs sharing one registry cannot leak\n * outputs between each other.\n *\n * Each public method takes a `runId` which selects the run's bucket.\n * Hosts typically get one registry per run via `Graph`, in which\n * case only a single bucket is ever populated; the partitioning\n * exists so the registry also behaves correctly when a single\n * instance is reused directly.\n */\nexport class ToolOutputReferenceRegistry {\n private runStates: Map<string, RunStateBucket> = new Map();\n private readonly maxOutputSize: number;\n private readonly maxTotalSize: number;\n private readonly maxActiveRuns: number;\n /**\n * Local stateful matcher used only by `replaceInString`. Kept\n * off-module so callers of the exported `TOOL_OUTPUT_REF_PATTERN`\n * never see a stale `lastIndex`.\n */\n private static readonly PLACEHOLDER_MATCHER = /\\{\\{(tool\\d+turn\\d+)\\}\\}/g;\n\n constructor(options: ToolOutputReferenceRegistryOptions = {}) {\n /**\n * Per-output default is the same ~400 KB budget as the standard\n * tool-result truncation (`HARD_MAX_TOOL_RESULT_CHARS`). This\n * keeps a single `{{…}}` substitution at a size that is safe to\n * pass through typical shell `ARG_MAX` limits and matches what\n * the LLM would otherwise have seen. Hosts that want larger per-\n * output payloads (API consumers, long JSON streams) can raise\n * the cap explicitly up to the 5 MB total budget.\n */\n const perOutput =\n options.maxOutputSize != null && options.maxOutputSize > 0\n ? options.maxOutputSize\n : HARD_MAX_TOOL_RESULT_CHARS;\n /**\n * Clamp a caller-supplied `maxTotalSize` to\n * `HARD_MAX_TOTAL_TOOL_OUTPUT_SIZE` (5 MB) so the documented\n * absolute cap is enforced regardless of host config —\n * `calculateMaxTotalToolOutputSize` already applies the same\n * upper bound on its computed default, but the user-provided\n * branch was bypassing it.\n */\n const totalRaw =\n options.maxTotalSize != null && options.maxTotalSize > 0\n ? Math.min(options.maxTotalSize, HARD_MAX_TOTAL_TOOL_OUTPUT_SIZE)\n : calculateMaxTotalToolOutputSize(perOutput);\n this.maxTotalSize = totalRaw;\n /**\n * The per-output cap can never exceed the per-run aggregate cap:\n * if a single entry were allowed to be larger than `maxTotalSize`,\n * the eviction loop would either blow the cap (to keep the entry)\n * or self-evict a just-stored value. Clamping here turns\n * `maxTotalSize` into a hard upper bound on *any* state the\n * registry retains per run.\n */\n this.maxOutputSize = Math.min(perOutput, totalRaw);\n this.maxActiveRuns =\n options.maxActiveRuns != null && options.maxActiveRuns > 0\n ? options.maxActiveRuns\n : DEFAULT_MAX_ACTIVE_RUNS;\n }\n\n private keyFor(runId: string | undefined): string {\n return runId ?? ANON_RUN_KEY;\n }\n\n private getOrCreate(runId: string | undefined): RunStateBucket {\n const key = this.keyFor(runId);\n let state = this.runStates.get(key);\n if (state == null) {\n state = new RunStateBucket();\n this.runStates.set(key, state);\n if (this.runStates.size > this.maxActiveRuns) {\n const oldest = this.runStates.keys().next().value;\n if (oldest != null && oldest !== key) {\n this.runStates.delete(oldest);\n }\n }\n }\n return state;\n }\n\n /** Registers (or replaces) the output stored under `key` for `runId`. */\n set(runId: string | undefined, key: string, value: string): void {\n const bucket = this.getOrCreate(runId);\n const clipped =\n value.length > this.maxOutputSize\n ? value.slice(0, this.maxOutputSize)\n : value;\n const existing = bucket.entries.get(key);\n if (existing != null) {\n bucket.totalSize -= existing.length;\n bucket.entries.delete(key);\n }\n bucket.entries.set(key, clipped);\n bucket.totalSize += clipped.length;\n this.evictWithinBucket(bucket);\n }\n\n /** Returns the stored value for `key` in `runId`'s bucket, or `undefined`. */\n get(runId: string | undefined, key: string): string | undefined {\n return this.runStates.get(this.keyFor(runId))?.entries.get(key);\n }\n\n /**\n * Returns `true` when `key` is currently stored in `runId`'s bucket.\n * Used by {@link annotateMessagesForLLM} to gate transient annotation\n * on whether the registry still owns the referenced output (a stale\n * `_refKey` from a prior run silently no-ops here).\n */\n has(runId: string | undefined, key: string): boolean {\n return this.runStates.get(this.keyFor(runId))?.entries.has(key) ?? false;\n }\n\n /** Total number of registered outputs across every run bucket. */\n get size(): number {\n let n = 0;\n for (const bucket of this.runStates.values()) {\n n += bucket.entries.size;\n }\n return n;\n }\n\n /** Maximum characters retained per output (post-clip). */\n get perOutputLimit(): number {\n return this.maxOutputSize;\n }\n\n /** Maximum total characters retained *per run*. */\n get totalLimit(): number {\n return this.maxTotalSize;\n }\n\n /** Drops every run's state. */\n clear(): void {\n this.runStates.clear();\n }\n\n /**\n * Explicitly release `runId`'s state. Safe to call when a run has\n * finished. Hosts sharing one registry across runs should call this\n * to reclaim memory deterministically; otherwise LRU eviction kicks\n * in when `maxActiveRuns` runs accumulate.\n */\n releaseRun(runId: string | undefined): void {\n this.runStates.delete(this.keyFor(runId));\n }\n\n /**\n * Claims the next batch turn synchronously from `runId`'s bucket.\n *\n * Must be called once at the start of each ToolNode batch before\n * any `await`, so concurrent invocations within the same run see\n * distinct turn values (reads are effectively atomic by JS's\n * single-threaded execution of the sync prefix).\n *\n * If `runId` is missing the anonymous bucket is dropped and a\n * fresh one created so each anonymous call behaves as its own run.\n */\n nextTurn(runId: string | undefined): number {\n if (runId == null) {\n this.runStates.delete(ANON_RUN_KEY);\n }\n const bucket = this.getOrCreate(runId);\n return bucket.turnCounter++;\n }\n\n /**\n * Records that `toolName` has been warned about in `runId` (returns\n * `true` on the first call per run, `false` after). Used by\n * ToolNode to emit one log line per offending tool per run when a\n * `ToolMessage.content` isn't a string.\n */\n claimWarnOnce(runId: string | undefined, toolName: string): boolean {\n const bucket = this.getOrCreate(runId);\n if (bucket.warnedNonStringTools.has(toolName)) {\n return false;\n }\n bucket.warnedNonStringTools.add(toolName);\n return true;\n }\n\n /**\n * Walks `args` and replaces every `{{tool<i>turn<n>}}` placeholder in\n * string values with the stored output *from `runId`'s bucket*. Non-\n * string values and object keys are left untouched. Unresolved\n * references are left in-place and reported so the caller can\n * surface them to the LLM. When no placeholder appears anywhere in\n * the serialized args, the original input is returned without\n * walking the tree.\n */\n resolve<T>(runId: string | undefined, args: T): ResolveResult<T> {\n if (!hasAnyPlaceholder(args)) {\n return { resolved: args, unresolved: [] };\n }\n const bucket = this.runStates.get(this.keyFor(runId));\n return this.resolveAgainst(bucket?.entries ?? EMPTY_ENTRIES, args);\n }\n\n /**\n * Captures a frozen snapshot of `runId`'s current entries and\n * returns a view that resolves placeholders against *only* that\n * snapshot. The snapshot is decoupled from the live registry, so\n * subsequent `set()` calls (for example, same-turn direct outputs\n * registering while an event branch is still in flight) are\n * invisible to the snapshot's `resolve`. Used by the mixed\n * direct+event dispatch path to preserve same-turn isolation when\n * a `PreToolUse` hook rewrites event args after directs have\n * completed.\n */\n snapshot(runId: string | undefined): ToolOutputResolveView {\n const bucket = this.runStates.get(this.keyFor(runId));\n const entries: ReadonlyMap<string, string> = bucket\n ? new Map(bucket.entries)\n : EMPTY_ENTRIES;\n return {\n resolve: <T>(args: T): ResolveResult<T> =>\n this.resolveAgainst(entries, args),\n };\n }\n\n private resolveAgainst<T>(\n entries: ReadonlyMap<string, string>,\n args: T\n ): ResolveResult<T> {\n if (!hasAnyPlaceholder(args)) {\n return { resolved: args, unresolved: [] };\n }\n const unresolved = new Set<string>();\n const resolved = this.transform(entries, args, unresolved) as T;\n return { resolved, unresolved: Array.from(unresolved) };\n }\n\n private transform(\n entries: ReadonlyMap<string, string>,\n value: unknown,\n unresolved: Set<string>\n ): unknown {\n if (typeof value === 'string') {\n return this.replaceInString(entries, value, unresolved);\n }\n if (Array.isArray(value)) {\n return value.map((item) => this.transform(entries, item, unresolved));\n }\n if (value !== null && typeof value === 'object') {\n const source = value as Record<string, unknown>;\n const next: Record<string, unknown> = {};\n for (const [key, item] of Object.entries(source)) {\n next[key] = this.transform(entries, item, unresolved);\n }\n return next;\n }\n return value;\n }\n\n private replaceInString(\n entries: ReadonlyMap<string, string>,\n input: string,\n unresolved: Set<string>\n ): string {\n if (input.indexOf('{{tool') === -1) {\n return input;\n }\n return input.replace(\n ToolOutputReferenceRegistry.PLACEHOLDER_MATCHER,\n (match, key: string) => {\n const stored = entries.get(key);\n if (stored == null) {\n unresolved.add(key);\n return match;\n }\n return stored;\n }\n );\n }\n\n private evictWithinBucket(bucket: RunStateBucket): void {\n if (bucket.totalSize <= this.maxTotalSize) {\n return;\n }\n for (const key of bucket.entries.keys()) {\n if (bucket.totalSize <= this.maxTotalSize) {\n return;\n }\n const entry = bucket.entries.get(key);\n if (entry == null) {\n continue;\n }\n bucket.totalSize -= entry.length;\n bucket.entries.delete(key);\n }\n }\n}\n\n/**\n * Cheap pre-check: returns true if any string value in `args` contains\n * the `{{tool` substring. Lets `resolve()` skip the deep tree walk (and\n * its object allocations) for the common case of plain args.\n */\nfunction hasAnyPlaceholder(value: unknown): boolean {\n if (typeof value === 'string') {\n return value.indexOf('{{tool') !== -1;\n }\n if (Array.isArray(value)) {\n for (const item of value) {\n if (hasAnyPlaceholder(item)) {\n return true;\n }\n }\n return false;\n }\n if (value !== null && typeof value === 'object') {\n for (const item of Object.values(value as Record<string, unknown>)) {\n if (hasAnyPlaceholder(item)) {\n return true;\n }\n }\n return false;\n }\n return false;\n}\n\n/**\n * Annotates `content` with a reference key and/or unresolved-ref\n * warnings so the LLM sees both alongside the tool output.\n *\n * Behavior:\n * - If `content` parses as a plain (non-array, non-null) JSON object\n * and the object does not already have a conflicting `_ref` key,\n * the reference key and (when present) `_unresolved_refs` array\n * are injected as object fields, preserving JSON validity for\n * downstream consumers that parse the output.\n * - Otherwise (string output, JSON array/primitive, parse failure,\n * or `_ref` collision), a `[ref: <key>]\\n` prefix line is\n * prepended and unresolved refs are appended as a trailing\n * `[unresolved refs: …]` line.\n *\n * The annotated string is what the LLM sees as `ToolMessage.content`.\n * The *original* (un-annotated) value is what gets stored in the\n * registry, so downstream piping remains pristine.\n *\n * @param content Raw (post-truncation) tool output.\n * @param key Reference key for this output, or undefined when\n * there is nothing to register (errors etc.).\n * @param unresolved Reference keys that failed to resolve during\n * argument substitution. Surfaced so the LLM can\n * self-correct its next tool call.\n */\nexport function annotateToolOutputWithReference(\n content: string,\n key: string | undefined,\n unresolved: string[] = []\n): string {\n const hasRefKey = key != null;\n const hasUnresolved = unresolved.length > 0;\n if (!hasRefKey && !hasUnresolved) {\n return content;\n }\n const trimmed = content.trimStart();\n if (trimmed.startsWith('{')) {\n const annotated = tryInjectRefIntoJsonObject(content, key, unresolved);\n if (annotated != null) {\n return annotated;\n }\n }\n const prefix = hasRefKey ? `${buildReferencePrefix(key!)}\\n` : '';\n const trailer = hasUnresolved\n ? `\\n[unresolved refs: ${unresolved.join(', ')}]`\n : '';\n return `${prefix}${content}${trailer}`;\n}\n\nfunction tryInjectRefIntoJsonObject(\n content: string,\n key: string | undefined,\n unresolved: string[]\n): string | null {\n let parsed: unknown;\n try {\n parsed = JSON.parse(content);\n } catch {\n return null;\n }\n\n if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {\n return null;\n }\n\n const obj = parsed as Record<string, unknown>;\n const injectingRef = key != null;\n const injectingUnresolved = unresolved.length > 0;\n\n /**\n * Reject the JSON-injection path (fall back to prefix form) when\n * either of our keys collides with real payload data:\n * - `_ref` collision: existing value is non-null and differs from\n * the key we're about to inject.\n * - `_unresolved_refs` collision: existing value is non-null and\n * is not a deep-equal match for the array we'd inject.\n * This keeps us from silently overwriting legitimate tool output.\n */\n if (\n injectingRef &&\n TOOL_OUTPUT_REF_KEY in obj &&\n obj[TOOL_OUTPUT_REF_KEY] !== key &&\n obj[TOOL_OUTPUT_REF_KEY] != null\n ) {\n return null;\n }\n if (\n injectingUnresolved &&\n TOOL_OUTPUT_UNRESOLVED_KEY in obj &&\n obj[TOOL_OUTPUT_UNRESOLVED_KEY] != null &&\n !arraysShallowEqual(obj[TOOL_OUTPUT_UNRESOLVED_KEY], unresolved)\n ) {\n return null;\n }\n\n /**\n * Only strip the framework-owned key we're actually injecting —\n * leave everything else (including a pre-existing `_ref` on the\n * unresolved-only path, or a pre-existing `_unresolved_refs` on a\n * plain-annotation path) untouched so we annotate rather than\n * mutate downstream payload data. Our injected keys land first in\n * the serialized JSON so the LLM sees them before the body.\n */\n const omitKeys = new Set<string>();\n if (injectingRef) omitKeys.add(TOOL_OUTPUT_REF_KEY);\n if (injectingUnresolved) omitKeys.add(TOOL_OUTPUT_UNRESOLVED_KEY);\n const rest: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(obj)) {\n if (!omitKeys.has(k)) {\n rest[k] = v;\n }\n }\n const injected: Record<string, unknown> = {};\n if (injectingRef) {\n injected[TOOL_OUTPUT_REF_KEY] = key;\n }\n if (injectingUnresolved) {\n injected[TOOL_OUTPUT_UNRESOLVED_KEY] = unresolved;\n }\n Object.assign(injected, rest);\n\n const pretty = /^\\{\\s*\\n/.test(content);\n return pretty ? JSON.stringify(injected, null, 2) : JSON.stringify(injected);\n}\n\nfunction arraysShallowEqual(a: unknown, b: readonly string[]): boolean {\n if (!Array.isArray(a) || a.length !== b.length) {\n return false;\n }\n for (let i = 0; i < a.length; i++) {\n if (a[i] !== b[i]) {\n return false;\n }\n }\n return true;\n}\n\n/**\n * Lazy projection that, given a registry and a runId, returns a new\n * `messages` array where each `ToolMessage` carrying ref metadata is\n * projected into a transient copy with annotated content (when the ref\n * is live in the registry) and with the framework-owned `additional_\n * kwargs` keys (`_refKey`, `_refScope`, `_unresolvedRefs`) stripped\n * regardless of whether annotation applied. The original input array\n * and its messages are never mutated.\n *\n * Annotation is gated on registry presence: a stale `_refKey` from a\n * prior run (e.g. one that survived in persisted history) silently\n * no-ops on the *content* side. The strip-metadata side still runs so\n * stale framework keys never leak onto the wire under any custom or\n * future provider serializer that might transmit `additional_kwargs`.\n * `_unresolvedRefs` is always meaningful and is not gated.\n *\n * **Feature-disabled fast path:** when the host hasn't enabled the\n * tool-output-reference feature, the registry is `undefined` and this\n * function returns the input array reference-equal *without iterating\n * a single message*. The loop is exclusive to the feature-enabled\n * code path.\n */\nexport function annotateMessagesForLLM(\n messages: BaseMessage[],\n registry: ToolOutputReferenceRegistry | undefined,\n runId: string | undefined\n): BaseMessage[] {\n if (registry == null) return messages;\n\n /**\n * Lazy-allocate the output array so the common case (no ToolMessage\n * carries framework metadata) returns the input reference-equal with\n * zero allocations beyond the per-message predicate checks.\n */\n let out: BaseMessage[] | undefined;\n for (let i = 0; i < messages.length; i++) {\n const m = messages[i];\n if (m._getType() !== 'tool') continue;\n /**\n * `additional_kwargs` is untyped at the LangChain layer\n * (`Record<string, unknown>`), so persisted or client-supplied\n * ToolMessages can carry arbitrary shapes — including primitives\n * (a malformed serializer might write a string, or `null`).\n * Guard with a runtime object check before the `in` probes\n * because the `in` operator throws `TypeError` on primitives.\n * A single malformed message must never crash the provider call\n * path; skip its annotation/strip and continue.\n */\n const rawMeta = m.additional_kwargs as unknown;\n if (rawMeta == null || typeof rawMeta !== 'object') continue;\n const meta = rawMeta as Record<string, unknown>;\n const hasRefKey = '_refKey' in meta;\n const hasRefScope = '_refScope' in meta;\n const hasUnresolvedField = '_unresolvedRefs' in meta;\n if (!hasRefKey && !hasRefScope && !hasUnresolvedField) continue;\n\n const refKey = readRefKey(meta);\n const unresolved = readUnresolvedRefs(meta);\n\n /**\n * Prefer the message-stamped `_refScope` for the registry lookup.\n * For named runs it equals the current `runId`; for anonymous\n * invocations it carries the per-batch synthetic scope minted by\n * ToolNode (`\\0anon-<n>`), which `runId` from config cannot\n * recover. Falling back to `runId` keeps backward compatibility\n * with messages stamped before this field existed.\n */\n const lookupScope = readRefScope(meta) ?? runId;\n const liveRef =\n refKey != null && registry.has(lookupScope, refKey) ? refKey : undefined;\n const annotates = liveRef != null || unresolved.length > 0;\n\n const tm = m as ToolMessage;\n let nextContent: ToolMessage['content'] = tm.content;\n\n if (annotates && typeof tm.content === 'string') {\n nextContent = annotateToolOutputWithReference(\n tm.content,\n liveRef,\n unresolved\n );\n } else if (\n annotates &&\n Array.isArray(tm.content) &&\n unresolved.length > 0\n ) {\n const warningBlock = {\n type: 'text' as const,\n text: `[unresolved refs: ${unresolved.join(', ')}]`,\n };\n /**\n * `as unknown as ToolMessage['content']` is unavoidable here:\n * LangChain's content union (`MessageContentComplex[] |\n * DataContentBlock[] | string`) does not accept a freshly built\n * mixed array literal even though the structural shape is valid\n * at runtime. The double-cast is structurally safe — we\n * preserve every block from `tm.content` and prepend a single\n * `{ type: 'text', text }` block that all providers accept.\n */\n nextContent = [\n warningBlock,\n ...tm.content,\n ] as unknown as ToolMessage['content'];\n }\n\n /**\n * Project unconditionally: even when no annotation applies (stale\n * `_refKey` or non-annotatable content), `cloneToolMessageWithContent`\n * runs `stripFrameworkRefMetadata` on `additional_kwargs` so the\n * framework-owned keys never reach the wire.\n */\n out ??= messages.slice();\n out[i] = cloneToolMessageWithContent(tm, nextContent);\n }\n\n return out ?? messages;\n}\n\n/**\n * Reads `_refKey` defensively from untyped `additional_kwargs`. Returns\n * undefined for non-string values so a malformed field cannot poison\n * the registry lookup or downstream string operations.\n */\nfunction readRefKey(\n meta: Record<string, unknown> | undefined\n): string | undefined {\n const v = meta?._refKey;\n return typeof v === 'string' ? v : undefined;\n}\n\n/**\n * Reads `_refScope` defensively from untyped `additional_kwargs`.\n * Mirrors {@link readRefKey} — non-string scopes are dropped (the\n * caller falls back to the run-derived scope) rather than passed into\n * the registry as a malformed key.\n */\nfunction readRefScope(\n meta: Record<string, unknown> | undefined\n): string | undefined {\n const v = meta?._refScope;\n return typeof v === 'string' ? v : undefined;\n}\n\n/**\n * Reads `_unresolvedRefs` defensively from untyped `additional_kwargs`.\n * Returns an empty array for any non-array value, and filters out\n * non-string entries from a real array. Without this guard, a hydrated\n * ToolMessage carrying e.g. `_unresolvedRefs: 'tool0turn0'` would crash\n * `attemptInvoke` on the eventual `.length` / `.join(...)` call.\n */\nfunction readUnresolvedRefs(\n meta: Record<string, unknown> | undefined\n): string[] {\n const v = meta?._unresolvedRefs;\n if (!Array.isArray(v)) return [];\n const out: string[] = [];\n for (const item of v) {\n if (typeof item === 'string') out.push(item);\n }\n return out;\n}\n\n/**\n * Builds a fresh `ToolMessage` that mirrors `tm`'s identity fields with\n * the supplied `content`. Every `ToolMessage` field but `content` is\n * carried over so the projection is structurally identical to the\n * original from a LangChain serializer's perspective.\n *\n * `additional_kwargs` is rebuilt with the framework-owned ref keys\n * stripped. Defensive: LangChain's standard provider serializers do not\n * transmit `additional_kwargs` to provider HTTP APIs, but a custom\n * adapter or future LangChain change could. Stripping keeps the\n * implementation correct under any serializer behavior at the cost of a\n * shallow object spread per annotated message.\n */\nfunction cloneToolMessageWithContent(\n tm: ToolMessage,\n content: ToolMessage['content']\n): ToolMessage {\n return new ToolMessage({\n id: tm.id,\n name: tm.name,\n status: tm.status,\n artifact: tm.artifact,\n tool_call_id: tm.tool_call_id,\n response_metadata: tm.response_metadata,\n additional_kwargs: stripFrameworkRefMetadata(tm.additional_kwargs),\n content,\n });\n}\n\n/**\n * Returns a copy of `kwargs` with `_refKey`, `_refScope`, and\n * `_unresolvedRefs` removed. Returns the input reference-equal when\n * none of those keys are present so the no-strip path stays cheap;\n * returns `undefined` when stripping leaves the object empty so the\n * caller can drop the field entirely.\n */\nfunction stripFrameworkRefMetadata(\n kwargs: Record<string, unknown> | undefined\n): Record<string, unknown> | undefined {\n if (kwargs == null) return undefined;\n if (\n !('_refKey' in kwargs) &&\n !('_refScope' in kwargs) &&\n !('_unresolvedRefs' in kwargs)\n ) {\n return kwargs;\n }\n const { _refKey, _refScope, _unresolvedRefs, ...rest } = kwargs as Record<\n string,\n unknown\n > & {\n _refKey?: unknown;\n _refScope?: unknown;\n _unresolvedRefs?: unknown;\n };\n void _refKey;\n void _refScope;\n void _unresolvedRefs;\n return Object.keys(rest).length === 0 ? undefined : rest;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsCA,MAAa,0BAA0B;;AAGvC,MAAa,sBAAsB;;;;;;;AAQnC,MAAa,6BAA6B;;AAG1C,SAAgB,qBAAqB,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O,MAAM,WAAW,IAAI,KAAA;AACrC;;;;;;;;AASA,SAAS,mBACP,MACU;CACV,MAAM,IAAI,MAAM;CAChB,IAAI,CAAC,MAAM,QAAQ,CAAC,GAAG,OAAO,CAAC;CAC/B,MAAM,MAAgB,CAAC;CACvB,KAAK,MAAM,QAAQ,GACjB,IAAI,OAAO,SAAS,UAAU,IAAI,KAAK,IAAI;CAE7C,OAAO;AACT;;;;;;;;;;;;;;AAeA,SAAS,4BACP,IACA,SACa;CACb,OAAO,IAAI,YAAY;EACrB,IAAI,GAAG;EACP,MAAM,GAAG;EACT,QAAQ,GAAG;EACX,UAAU,GAAG;EACb,cAAc,GAAG;EACjB,mBAAmB,GAAG;EACtB,mBAAmB,0BAA0B,GAAG,iBAAiB;EACjE;CACF,CAAC;AACH;;;;;;;;AASA,SAAS,0BACP,QACqC;CACrC,IAAI,UAAU,MAAM,OAAO,KAAA;CAC3B,IACE,EAAE,aAAa,WACf,EAAE,eAAe,WACjB,EAAE,qBAAqB,SAEvB,OAAO;CAET,MAAM,EAAE,SAAS,WAAW,iBAAiB,GAAG,SAAS;CAWzD,OAAO,OAAO,KAAK,IAAI,CAAC,CAAC,WAAW,IAAI,KAAA,IAAY;AACtD"}
1
+ {"version":3,"file":"toolOutputReferences.mjs","names":[],"sources":["../../../src/tools/toolOutputReferences.ts"],"sourcesContent":["/**\n * Tool output reference registry.\n *\n * When enabled via `RunConfig.toolOutputReferences.enabled`, ToolNode\n * stores each successful tool output under a stable key\n * (`tool<idx>turn<turn>`) where `idx` is the tool's position within a\n * ToolNode batch and `turn` is the batch index within the run\n * (incremented once per ToolNode invocation).\n *\n * Subsequent tool calls can pipe a previous output into their args by\n * embedding `{{tool<idx>turn<turn>}}` inside any string argument;\n * {@link ToolOutputReferenceRegistry.resolve} walks the args and\n * substitutes the placeholders immediately before invocation.\n *\n * The registry stores the *raw, untruncated* tool output so a later\n * `{{…}}` substitution pipes the full payload into the next tool —\n * even when the LLM only saw a head+tail-truncated preview in\n * `ToolMessage.content`. Outputs are stored without any annotation\n * (the `_ref` key or the `[ref: ...]` prefix seen by the LLM is\n * strictly a UX signal attached to `ToolMessage.content`). Keeping the\n * registry pristine means downstream bash/jq piping receives the\n * complete, verbatim output with no injected fields.\n */\n\nimport { ToolMessage } from '@langchain/core/messages';\nimport type { BaseMessage } from '@langchain/core/messages';\nimport {\n calculateMaxTotalToolOutputSize,\n HARD_MAX_TOOL_RESULT_CHARS,\n HARD_MAX_TOTAL_TOOL_OUTPUT_SIZE,\n} from '@/utils/truncation';\n\n/**\n * Non-global matcher for a single `{{tool<i>turn<n>}}` placeholder.\n * Exported for consumers that want to detect references (e.g., syntax\n * highlighting, docs). The stateful `g` variant lives inside the\n * registry so nobody trips on `lastIndex`.\n */\nexport const TOOL_OUTPUT_REF_PATTERN = /\\{\\{(tool\\d+turn\\d+)\\}\\}/;\n\n/** Object key used when a parsed-object output has `_ref` injected. */\nexport const TOOL_OUTPUT_REF_KEY = '_ref';\n\n/**\n * Object key used to carry unresolved reference warnings on a parsed-\n * object output. Using a dedicated field instead of a trailing text\n * line keeps the annotated `ToolMessage.content` parseable as JSON for\n * downstream consumers that rely on the object shape.\n */\nexport const TOOL_OUTPUT_UNRESOLVED_KEY = '_unresolved_refs';\n\n/** Single-line prefix prepended to non-object tool outputs so the LLM sees the reference key. */\nexport function buildReferencePrefix(key: string): string {\n return `[ref: ${key}]`;\n}\n\n/** Stable registry key for a tool output. */\nexport function buildReferenceKey(toolIndex: number, turn: number): string {\n return `tool${toolIndex}turn${turn}`;\n}\n\nexport type ToolOutputReferenceRegistryOptions = {\n /** Maximum characters stored per registered output. */\n maxOutputSize?: number;\n /** Maximum total characters retained across all registered outputs. */\n maxTotalSize?: number;\n /**\n * Upper bound on the number of concurrently-tracked runs. When\n * exceeded, the oldest run bucket is evicted (FIFO). Defaults to 32.\n */\n maxActiveRuns?: number;\n};\n\n/**\n * Result of resolving placeholders in tool args.\n */\nexport type ResolveResult<T> = {\n /** Arguments with placeholders replaced. Same shape as the input. */\n resolved: T;\n /** Reference keys that were referenced but had no stored value. */\n unresolved: string[];\n};\n\n/**\n * Read-only view over a frozen registry snapshot. Returned by\n * {@link ToolOutputReferenceRegistry.snapshot} for callers that need\n * to resolve placeholders against the registry state at a specific\n * point in time, ignoring any subsequent registrations.\n */\nexport interface ToolOutputResolveView {\n resolve<T>(args: T): ResolveResult<T>;\n}\n\n/**\n * Pre-resolved arg map keyed by `toolCallId`. Used by the mixed\n * direct+event dispatch path to feed event calls' resolved args\n * (captured pre-batch) into the dispatcher without re-resolving\n * against the now-stale live registry.\n */\nexport type PreResolvedArgsMap = Map<\n string,\n { resolved: Record<string, unknown>; unresolved: string[] }\n>;\n\n/**\n * Per-call sink for resolved args, keyed by `toolCallId`. Threaded\n * as a per-batch local map so concurrent `ToolNode.run()` calls do\n * not race on shared sink state.\n */\nexport type ResolvedArgsByCallId = Map<string, Record<string, unknown>>;\n\nconst EMPTY_ENTRIES: ReadonlyMap<string, string> = new Map<string, string>();\n\n/**\n * Per-run state bucket held inside the registry. Each distinct\n * `run_id` gets its own bucket so overlapping concurrent runs on a\n * shared registry cannot leak outputs, turn counters, or warn-memos\n * into one another.\n */\nclass RunStateBucket {\n entries: Map<string, string> = new Map();\n totalSize: number = 0;\n turnCounter: number = 0;\n warnedNonStringTools: Set<string> = new Set();\n}\n\n/**\n * Anonymous (`run_id` absent) bucket key. Anonymous batches are\n * treated as fresh runs on every invocation — see `nextTurn`.\n */\nconst ANON_RUN_KEY = '\\0anon';\n\n/**\n * Default upper bound on the number of concurrently-tracked runs per\n * registry. When exceeded, the oldest run's bucket (by insertion\n * order) is evicted. Keeps memory bounded when a ToolNode is reused\n * across many runs without explicit `releaseRun` calls.\n */\nconst DEFAULT_MAX_ACTIVE_RUNS = 32;\n\n/**\n * Ordered map of reference-key → stored output, partitioned by run so\n * concurrent / interleaved runs sharing one registry cannot leak\n * outputs between each other.\n *\n * Each public method takes a `runId` which selects the run's bucket.\n * Hosts typically get one registry per run via `Graph`, in which\n * case only a single bucket is ever populated; the partitioning\n * exists so the registry also behaves correctly when a single\n * instance is reused directly.\n */\nexport class ToolOutputReferenceRegistry {\n private runStates: Map<string, RunStateBucket> = new Map();\n private readonly maxOutputSize: number;\n private readonly maxTotalSize: number;\n private readonly maxActiveRuns: number;\n /**\n * Local stateful matcher used only by `replaceInString`. Kept\n * off-module so callers of the exported `TOOL_OUTPUT_REF_PATTERN`\n * never see a stale `lastIndex`.\n */\n private static readonly PLACEHOLDER_MATCHER = /\\{\\{(tool\\d+turn\\d+)\\}\\}/g;\n\n constructor(options: ToolOutputReferenceRegistryOptions = {}) {\n /**\n * Per-output default is the same ~400 KB budget as the standard\n * tool-result truncation (`HARD_MAX_TOOL_RESULT_CHARS`). This\n * keeps a single `{{…}}` substitution at a size that is safe to\n * pass through typical shell `ARG_MAX` limits and matches what\n * the LLM would otherwise have seen. Hosts that want larger per-\n * output payloads (API consumers, long JSON streams) can raise\n * the cap explicitly up to the 5 MB total budget.\n */\n const perOutput =\n options.maxOutputSize != null && options.maxOutputSize > 0\n ? options.maxOutputSize\n : HARD_MAX_TOOL_RESULT_CHARS;\n /**\n * Clamp a caller-supplied `maxTotalSize` to\n * `HARD_MAX_TOTAL_TOOL_OUTPUT_SIZE` (5 MB) so the documented\n * absolute cap is enforced regardless of host config —\n * `calculateMaxTotalToolOutputSize` already applies the same\n * upper bound on its computed default, but the user-provided\n * branch was bypassing it.\n */\n const totalRaw =\n options.maxTotalSize != null && options.maxTotalSize > 0\n ? Math.min(options.maxTotalSize, HARD_MAX_TOTAL_TOOL_OUTPUT_SIZE)\n : calculateMaxTotalToolOutputSize(perOutput);\n this.maxTotalSize = totalRaw;\n /**\n * The per-output cap can never exceed the per-run aggregate cap:\n * if a single entry were allowed to be larger than `maxTotalSize`,\n * the eviction loop would either blow the cap (to keep the entry)\n * or self-evict a just-stored value. Clamping here turns\n * `maxTotalSize` into a hard upper bound on *any* state the\n * registry retains per run.\n */\n this.maxOutputSize = Math.min(perOutput, totalRaw);\n this.maxActiveRuns =\n options.maxActiveRuns != null && options.maxActiveRuns > 0\n ? options.maxActiveRuns\n : DEFAULT_MAX_ACTIVE_RUNS;\n }\n\n private keyFor(runId: string | undefined): string {\n return runId ?? ANON_RUN_KEY;\n }\n\n private getOrCreate(runId: string | undefined): RunStateBucket {\n const key = this.keyFor(runId);\n let state = this.runStates.get(key);\n if (state == null) {\n state = new RunStateBucket();\n this.runStates.set(key, state);\n if (this.runStates.size > this.maxActiveRuns) {\n const oldest = this.runStates.keys().next().value;\n if (oldest != null && oldest !== key) {\n this.runStates.delete(oldest);\n }\n }\n }\n return state;\n }\n\n /** Registers (or replaces) the output stored under `key` for `runId`. */\n set(runId: string | undefined, key: string, value: string): void {\n const bucket = this.getOrCreate(runId);\n const clipped =\n value.length > this.maxOutputSize\n ? value.slice(0, this.maxOutputSize)\n : value;\n const existing = bucket.entries.get(key);\n if (existing != null) {\n bucket.totalSize -= existing.length;\n bucket.entries.delete(key);\n }\n bucket.entries.set(key, clipped);\n bucket.totalSize += clipped.length;\n this.evictWithinBucket(bucket);\n }\n\n /** Returns the stored value for `key` in `runId`'s bucket, or `undefined`. */\n get(runId: string | undefined, key: string): string | undefined {\n return this.runStates.get(this.keyFor(runId))?.entries.get(key);\n }\n\n /**\n * Returns `true` when `key` is currently stored in `runId`'s bucket.\n * Used by {@link annotateMessagesForLLM} to gate transient annotation\n * on whether the registry still owns the referenced output (a stale\n * `_refKey` from a prior run silently no-ops here).\n */\n has(runId: string | undefined, key: string): boolean {\n return this.runStates.get(this.keyFor(runId))?.entries.has(key) ?? false;\n }\n\n /** Total number of registered outputs across every run bucket. */\n get size(): number {\n let n = 0;\n for (const bucket of this.runStates.values()) {\n n += bucket.entries.size;\n }\n return n;\n }\n\n /** Maximum characters retained per output (post-clip). */\n get perOutputLimit(): number {\n return this.maxOutputSize;\n }\n\n /** Maximum total characters retained *per run*. */\n get totalLimit(): number {\n return this.maxTotalSize;\n }\n\n /** Drops every run's state. */\n clear(): void {\n this.runStates.clear();\n }\n\n /**\n * Explicitly release `runId`'s state. Safe to call when a run has\n * finished. Hosts sharing one registry across runs should call this\n * to reclaim memory deterministically; otherwise LRU eviction kicks\n * in when `maxActiveRuns` runs accumulate.\n */\n releaseRun(runId: string | undefined): void {\n this.runStates.delete(this.keyFor(runId));\n }\n\n /**\n * Claims the next batch turn synchronously from `runId`'s bucket.\n *\n * Must be called once at the start of each ToolNode batch before\n * any `await`, so concurrent invocations within the same run see\n * distinct turn values (reads are effectively atomic by JS's\n * single-threaded execution of the sync prefix).\n *\n * If `runId` is missing the anonymous bucket is dropped and a\n * fresh one created so each anonymous call behaves as its own run.\n */\n nextTurn(runId: string | undefined): number {\n if (runId == null) {\n this.runStates.delete(ANON_RUN_KEY);\n }\n const bucket = this.getOrCreate(runId);\n return bucket.turnCounter++;\n }\n\n /**\n * Records that `toolName` has been warned about in `runId` (returns\n * `true` on the first call per run, `false` after). Used by\n * ToolNode to emit one log line per offending tool per run when a\n * `ToolMessage.content` isn't a string.\n */\n claimWarnOnce(runId: string | undefined, toolName: string): boolean {\n const bucket = this.getOrCreate(runId);\n if (bucket.warnedNonStringTools.has(toolName)) {\n return false;\n }\n bucket.warnedNonStringTools.add(toolName);\n return true;\n }\n\n /**\n * Walks `args` and replaces every `{{tool<i>turn<n>}}` placeholder in\n * string values with the stored output *from `runId`'s bucket*. Non-\n * string values and object keys are left untouched. Unresolved\n * references are left in-place and reported so the caller can\n * surface them to the LLM. When no placeholder appears anywhere in\n * the serialized args, the original input is returned without\n * walking the tree.\n */\n resolve<T>(runId: string | undefined, args: T): ResolveResult<T> {\n if (!hasAnyPlaceholder(args)) {\n return { resolved: args, unresolved: [] };\n }\n const bucket = this.runStates.get(this.keyFor(runId));\n return this.resolveAgainst(bucket?.entries ?? EMPTY_ENTRIES, args);\n }\n\n /**\n * Captures a frozen snapshot of `runId`'s current entries and\n * returns a view that resolves placeholders against *only* that\n * snapshot. The snapshot is decoupled from the live registry, so\n * subsequent `set()` calls (for example, same-turn direct outputs\n * registering while an event branch is still in flight) are\n * invisible to the snapshot's `resolve`. Used by the mixed\n * direct+event dispatch path to preserve same-turn isolation when\n * a `PreToolUse` hook rewrites event args after directs have\n * completed.\n */\n snapshot(runId: string | undefined): ToolOutputResolveView {\n const bucket = this.runStates.get(this.keyFor(runId));\n const entries: ReadonlyMap<string, string> = bucket\n ? new Map(bucket.entries)\n : EMPTY_ENTRIES;\n return {\n resolve: <T>(args: T): ResolveResult<T> =>\n this.resolveAgainst(entries, args),\n };\n }\n\n private resolveAgainst<T>(\n entries: ReadonlyMap<string, string>,\n args: T\n ): ResolveResult<T> {\n if (!hasAnyPlaceholder(args)) {\n return { resolved: args, unresolved: [] };\n }\n const unresolved = new Set<string>();\n const resolved = this.transform(entries, args, unresolved) as T;\n return { resolved, unresolved: Array.from(unresolved) };\n }\n\n private transform(\n entries: ReadonlyMap<string, string>,\n value: unknown,\n unresolved: Set<string>\n ): unknown {\n if (typeof value === 'string') {\n return this.replaceInString(entries, value, unresolved);\n }\n if (Array.isArray(value)) {\n return value.map((item) => this.transform(entries, item, unresolved));\n }\n if (value !== null && typeof value === 'object') {\n const source = value as Record<string, unknown>;\n const next: Record<string, unknown> = {};\n for (const [key, item] of Object.entries(source)) {\n next[key] = this.transform(entries, item, unresolved);\n }\n return next;\n }\n return value;\n }\n\n private replaceInString(\n entries: ReadonlyMap<string, string>,\n input: string,\n unresolved: Set<string>\n ): string {\n if (input.indexOf('{{tool') === -1) {\n return input;\n }\n return input.replace(\n ToolOutputReferenceRegistry.PLACEHOLDER_MATCHER,\n (match, key: string) => {\n const stored = entries.get(key);\n if (stored == null) {\n unresolved.add(key);\n return match;\n }\n return stored;\n }\n );\n }\n\n private evictWithinBucket(bucket: RunStateBucket): void {\n if (bucket.totalSize <= this.maxTotalSize) {\n return;\n }\n for (const key of bucket.entries.keys()) {\n if (bucket.totalSize <= this.maxTotalSize) {\n return;\n }\n const entry = bucket.entries.get(key);\n if (entry == null) {\n continue;\n }\n bucket.totalSize -= entry.length;\n bucket.entries.delete(key);\n }\n }\n}\n\n/**\n * Cheap pre-check: returns true if any string value in `args` contains\n * the `{{tool` substring. Lets `resolve()` skip the deep tree walk (and\n * its object allocations) for the common case of plain args.\n */\nfunction hasAnyPlaceholder(value: unknown): boolean {\n if (typeof value === 'string') {\n return value.indexOf('{{tool') !== -1;\n }\n if (Array.isArray(value)) {\n for (const item of value) {\n if (hasAnyPlaceholder(item)) {\n return true;\n }\n }\n return false;\n }\n if (value !== null && typeof value === 'object') {\n for (const item of Object.values(value as Record<string, unknown>)) {\n if (hasAnyPlaceholder(item)) {\n return true;\n }\n }\n return false;\n }\n return false;\n}\n\n/**\n * Annotates `content` with a reference key and/or unresolved-ref\n * warnings so the LLM sees both alongside the tool output.\n *\n * Behavior:\n * - If `content` parses as a plain (non-array, non-null) JSON object\n * and the object does not already have a conflicting `_ref` key,\n * the reference key and (when present) `_unresolved_refs` array\n * are injected as object fields, preserving JSON validity for\n * downstream consumers that parse the output.\n * - Otherwise (string output, JSON array/primitive, parse failure,\n * or `_ref` collision), a `[ref: <key>]\\n` prefix line is\n * prepended and unresolved refs are appended as a trailing\n * `[unresolved refs: …]` line.\n *\n * The annotated string is what the LLM sees as `ToolMessage.content`.\n * The *original* (un-annotated) value is what gets stored in the\n * registry, so downstream piping remains pristine.\n *\n * @param content Raw (post-truncation) tool output.\n * @param key Reference key for this output, or undefined when\n * there is nothing to register (errors etc.).\n * @param unresolved Reference keys that failed to resolve during\n * argument substitution. Surfaced so the LLM can\n * self-correct its next tool call.\n */\nexport function annotateToolOutputWithReference(\n content: string,\n key: string | undefined,\n unresolved: string[] = []\n): string {\n const hasRefKey = key != null;\n const hasUnresolved = unresolved.length > 0;\n if (!hasRefKey && !hasUnresolved) {\n return content;\n }\n const trimmed = content.trimStart();\n if (trimmed.startsWith('{')) {\n const annotated = tryInjectRefIntoJsonObject(content, key, unresolved);\n if (annotated != null) {\n return annotated;\n }\n }\n const prefix = hasRefKey ? `${buildReferencePrefix(key!)}\\n` : '';\n const trailer = hasUnresolved\n ? `\\n[unresolved refs: ${unresolved.join(', ')}]`\n : '';\n return `${prefix}${content}${trailer}`;\n}\n\nfunction tryInjectRefIntoJsonObject(\n content: string,\n key: string | undefined,\n unresolved: string[]\n): string | null {\n let parsed: unknown;\n try {\n parsed = JSON.parse(content);\n } catch {\n return null;\n }\n\n if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {\n return null;\n }\n\n const obj = parsed as Record<string, unknown>;\n const injectingRef = key != null;\n const injectingUnresolved = unresolved.length > 0;\n\n /**\n * Reject the JSON-injection path (fall back to prefix form) when\n * either of our keys collides with real payload data:\n * - `_ref` collision: existing value is non-null and differs from\n * the key we're about to inject.\n * - `_unresolved_refs` collision: existing value is non-null and\n * is not a deep-equal match for the array we'd inject.\n * This keeps us from silently overwriting legitimate tool output.\n */\n if (\n injectingRef &&\n TOOL_OUTPUT_REF_KEY in obj &&\n obj[TOOL_OUTPUT_REF_KEY] !== key &&\n obj[TOOL_OUTPUT_REF_KEY] != null\n ) {\n return null;\n }\n if (\n injectingUnresolved &&\n TOOL_OUTPUT_UNRESOLVED_KEY in obj &&\n obj[TOOL_OUTPUT_UNRESOLVED_KEY] != null &&\n !arraysShallowEqual(obj[TOOL_OUTPUT_UNRESOLVED_KEY], unresolved)\n ) {\n return null;\n }\n\n /**\n * Only strip the framework-owned key we're actually injecting —\n * leave everything else (including a pre-existing `_ref` on the\n * unresolved-only path, or a pre-existing `_unresolved_refs` on a\n * plain-annotation path) untouched so we annotate rather than\n * mutate downstream payload data. Our injected keys land first in\n * the serialized JSON so the LLM sees them before the body.\n */\n const omitKeys = new Set<string>();\n if (injectingRef) omitKeys.add(TOOL_OUTPUT_REF_KEY);\n if (injectingUnresolved) omitKeys.add(TOOL_OUTPUT_UNRESOLVED_KEY);\n const rest: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(obj)) {\n if (!omitKeys.has(k)) {\n rest[k] = v;\n }\n }\n const injected: Record<string, unknown> = {};\n if (injectingRef) {\n injected[TOOL_OUTPUT_REF_KEY] = key;\n }\n if (injectingUnresolved) {\n injected[TOOL_OUTPUT_UNRESOLVED_KEY] = unresolved;\n }\n Object.assign(injected, rest);\n\n const pretty = /^\\{\\s*\\n/.test(content);\n return pretty ? JSON.stringify(injected, null, 2) : JSON.stringify(injected);\n}\n\nfunction arraysShallowEqual(a: unknown, b: readonly string[]): boolean {\n if (!Array.isArray(a) || a.length !== b.length) {\n return false;\n }\n for (let i = 0; i < a.length; i++) {\n if (a[i] !== b[i]) {\n return false;\n }\n }\n return true;\n}\n\n/**\n * Lazy projection that, given a registry and a runId, returns a new\n * `messages` array where each `ToolMessage` carrying ref metadata is\n * projected into a transient copy with annotated content (when the ref\n * is live in the registry) and with the framework-owned `additional_\n * kwargs` keys (`_refKey`, `_refScope`, `_unresolvedRefs`) stripped\n * regardless of whether annotation applied. The original input array\n * and its messages are never mutated.\n *\n * Annotation is gated on registry presence: a stale `_refKey` from a\n * prior run (e.g. one that survived in persisted history) silently\n * no-ops on the *content* side. The strip-metadata side still runs so\n * stale framework keys never leak onto the wire under any custom or\n * future provider serializer that might transmit `additional_kwargs`.\n * `_unresolvedRefs` is always meaningful and is not gated.\n *\n * **Feature-disabled fast path:** when the host hasn't enabled the\n * tool-output-reference feature, the registry is `undefined` and this\n * function returns the input array reference-equal *without iterating\n * a single message*. The loop is exclusive to the feature-enabled\n * code path.\n */\nexport function annotateMessagesForLLM(\n messages: BaseMessage[],\n registry: ToolOutputReferenceRegistry | undefined,\n runId: string | undefined\n): BaseMessage[] {\n if (registry == null) return messages;\n\n /**\n * Lazy-allocate the output array so the common case (no ToolMessage\n * carries framework metadata) returns the input reference-equal with\n * zero allocations beyond the per-message predicate checks.\n */\n let out: BaseMessage[] | undefined;\n for (let i = 0; i < messages.length; i++) {\n const m = messages[i];\n if (m._getType() !== 'tool') continue;\n /**\n * `additional_kwargs` is untyped at the LangChain layer\n * (`Record<string, unknown>`), so persisted or client-supplied\n * ToolMessages can carry arbitrary shapes — including primitives\n * (a malformed serializer might write a string, or `null`).\n * Guard with a runtime object check before the `in` probes\n * because the `in` operator throws `TypeError` on primitives.\n * A single malformed message must never crash the provider call\n * path; skip its annotation/strip and continue.\n */\n const rawMeta = m.additional_kwargs as unknown;\n if (rawMeta == null || typeof rawMeta !== 'object') continue;\n const meta = rawMeta as Record<string, unknown>;\n const hasRefKey = '_refKey' in meta;\n const hasRefScope = '_refScope' in meta;\n const hasUnresolvedField = '_unresolvedRefs' in meta;\n if (!hasRefKey && !hasRefScope && !hasUnresolvedField) continue;\n\n const refKey = readRefKey(meta);\n const unresolved = readUnresolvedRefs(meta);\n\n /**\n * Prefer the message-stamped `_refScope` for the registry lookup.\n * For named runs it equals the current `runId`; for anonymous\n * invocations it carries the per-batch synthetic scope minted by\n * ToolNode (`\\0anon-<n>`), which `runId` from config cannot\n * recover. Falling back to `runId` keeps backward compatibility\n * with messages stamped before this field existed.\n */\n const lookupScope = readRefScope(meta) ?? runId;\n const liveRef =\n refKey != null && registry.has(lookupScope, refKey) ? refKey : undefined;\n const annotates = liveRef != null || unresolved.length > 0;\n\n const tm = m as ToolMessage;\n let nextContent: ToolMessage['content'] = tm.content;\n\n if (annotates && typeof tm.content === 'string') {\n nextContent = annotateToolOutputWithReference(\n tm.content,\n liveRef,\n unresolved\n );\n } else if (annotates && Array.isArray(tm.content)) {\n /**\n * Array tool content. The string annotator can't run — this notably\n * includes a tail tool result that prompt caching rewrote from a string\n * into a text-block array to host its `cache_control` / `cachePoint`\n * marker (the `_refKey` survives on `additional_kwargs`). Project the\n * same markers the string path would, as leading text blocks: the live\n * `[ref: …]` prefix and/or the unresolved-refs warning. Without this the\n * common tool-result tail loses its reference marker once cached.\n *\n * `as unknown as ToolMessage['content']` is unavoidable: LangChain's\n * content union does not accept a freshly built mixed array literal even\n * though the structural shape is valid at runtime. The double-cast is\n * structurally safe — every original block is preserved and only\n * `{ type: 'text', text }` blocks (which all providers accept) are\n * prepended.\n */\n const prefixBlocks: Array<{ type: 'text'; text: string }> = [];\n if (liveRef != null) {\n prefixBlocks.push({\n type: 'text',\n text: buildReferencePrefix(liveRef),\n });\n }\n if (unresolved.length > 0) {\n prefixBlocks.push({\n type: 'text',\n text: `[unresolved refs: ${unresolved.join(', ')}]`,\n });\n }\n if (prefixBlocks.length > 0) {\n nextContent = [\n ...prefixBlocks,\n ...tm.content,\n ] as unknown as ToolMessage['content'];\n }\n }\n\n /**\n * Project unconditionally: even when no annotation applies (stale\n * `_refKey` or non-annotatable content), `cloneToolMessageWithContent`\n * runs `stripFrameworkRefMetadata` on `additional_kwargs` so the\n * framework-owned keys never reach the wire.\n */\n out ??= messages.slice();\n out[i] = cloneToolMessageWithContent(tm, nextContent);\n }\n\n return out ?? messages;\n}\n\n/**\n * Reads `_refKey` defensively from untyped `additional_kwargs`. Returns\n * undefined for non-string values so a malformed field cannot poison\n * the registry lookup or downstream string operations.\n */\nfunction readRefKey(\n meta: Record<string, unknown> | undefined\n): string | undefined {\n const v = meta?._refKey;\n return typeof v === 'string' ? v : undefined;\n}\n\n/**\n * Reads `_refScope` defensively from untyped `additional_kwargs`.\n * Mirrors {@link readRefKey} — non-string scopes are dropped (the\n * caller falls back to the run-derived scope) rather than passed into\n * the registry as a malformed key.\n */\nfunction readRefScope(\n meta: Record<string, unknown> | undefined\n): string | undefined {\n const v = meta?._refScope;\n return typeof v === 'string' ? v : undefined;\n}\n\n/**\n * Reads `_unresolvedRefs` defensively from untyped `additional_kwargs`.\n * Returns an empty array for any non-array value, and filters out\n * non-string entries from a real array. Without this guard, a hydrated\n * ToolMessage carrying e.g. `_unresolvedRefs: 'tool0turn0'` would crash\n * `attemptInvoke` on the eventual `.length` / `.join(...)` call.\n */\nfunction readUnresolvedRefs(\n meta: Record<string, unknown> | undefined\n): string[] {\n const v = meta?._unresolvedRefs;\n if (!Array.isArray(v)) return [];\n const out: string[] = [];\n for (const item of v) {\n if (typeof item === 'string') out.push(item);\n }\n return out;\n}\n\n/**\n * Builds a fresh `ToolMessage` that mirrors `tm`'s identity fields with\n * the supplied `content`. Every `ToolMessage` field but `content` is\n * carried over so the projection is structurally identical to the\n * original from a LangChain serializer's perspective.\n *\n * `additional_kwargs` is rebuilt with the framework-owned ref keys\n * stripped. Defensive: LangChain's standard provider serializers do not\n * transmit `additional_kwargs` to provider HTTP APIs, but a custom\n * adapter or future LangChain change could. Stripping keeps the\n * implementation correct under any serializer behavior at the cost of a\n * shallow object spread per annotated message.\n */\nfunction cloneToolMessageWithContent(\n tm: ToolMessage,\n content: ToolMessage['content']\n): ToolMessage {\n return new ToolMessage({\n id: tm.id,\n name: tm.name,\n status: tm.status,\n artifact: tm.artifact,\n tool_call_id: tm.tool_call_id,\n response_metadata: tm.response_metadata,\n additional_kwargs: stripFrameworkRefMetadata(tm.additional_kwargs),\n content,\n });\n}\n\n/**\n * Returns a copy of `kwargs` with `_refKey`, `_refScope`, and\n * `_unresolvedRefs` removed. Returns the input reference-equal when\n * none of those keys are present so the no-strip path stays cheap;\n * returns `undefined` when stripping leaves the object empty so the\n * caller can drop the field entirely.\n */\nfunction stripFrameworkRefMetadata(\n kwargs: Record<string, unknown> | undefined\n): Record<string, unknown> | undefined {\n if (kwargs == null) return undefined;\n if (\n !('_refKey' in kwargs) &&\n !('_refScope' in kwargs) &&\n !('_unresolvedRefs' in kwargs)\n ) {\n return kwargs;\n }\n const { _refKey, _refScope, _unresolvedRefs, ...rest } = kwargs as Record<\n string,\n unknown\n > & {\n _refKey?: unknown;\n _refScope?: unknown;\n _unresolvedRefs?: unknown;\n };\n void _refKey;\n void _refScope;\n void _unresolvedRefs;\n return Object.keys(rest).length === 0 ? undefined : rest;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsCA,MAAa,0BAA0B;;AAGvC,MAAa,sBAAsB;;;;;;;AAQnC,MAAa,6BAA6B;;AAG1C,SAAgB,qBAAqB,KAAqB;CACxD,OAAO,SAAS,IAAI;AACtB;;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SAAS,WACP,MACoB;CACpB,MAAM,IAAI,MAAM;CAChB,OAAO,OAAO,MAAM,WAAW,IAAI,KAAA;AACrC;;;;;;;AAQA,SAAS,aACP,MACoB;CACpB,MAAM,IAAI,MAAM;CAChB,OAAO,OAAO,MAAM,WAAW,IAAI,KAAA;AACrC;;;;;;;;AASA,SAAS,mBACP,MACU;CACV,MAAM,IAAI,MAAM;CAChB,IAAI,CAAC,MAAM,QAAQ,CAAC,GAAG,OAAO,CAAC;CAC/B,MAAM,MAAgB,CAAC;CACvB,KAAK,MAAM,QAAQ,GACjB,IAAI,OAAO,SAAS,UAAU,IAAI,KAAK,IAAI;CAE7C,OAAO;AACT;;;;;;;;;;;;;;AAeA,SAAS,4BACP,IACA,SACa;CACb,OAAO,IAAI,YAAY;EACrB,IAAI,GAAG;EACP,MAAM,GAAG;EACT,QAAQ,GAAG;EACX,UAAU,GAAG;EACb,cAAc,GAAG;EACjB,mBAAmB,GAAG;EACtB,mBAAmB,0BAA0B,GAAG,iBAAiB;EACjE;CACF,CAAC;AACH;;;;;;;;AASA,SAAS,0BACP,QACqC;CACrC,IAAI,UAAU,MAAM,OAAO,KAAA;CAC3B,IACE,EAAE,aAAa,WACf,EAAE,eAAe,WACjB,EAAE,qBAAqB,SAEvB,OAAO;CAET,MAAM,EAAE,SAAS,WAAW,iBAAiB,GAAG,SAAS;CAWzD,OAAO,OAAO,KAAK,IAAI,CAAC,CAAC,WAAW,IAAI,KAAA,IAAY;AACtD"}
@@ -1,9 +1,9 @@
1
1
  import { SystemMessage } from '@langchain/core/messages';
2
2
  import type { UsageMetadata, BaseMessage } from '@langchain/core/messages';
3
3
  import type { RunnableConfig, Runnable } from '@langchain/core/runnables';
4
- import type { createPruneMessages } from '@/messages';
5
4
  import type * as t from '@/types';
6
5
  import { ContentTypes, Providers } from '@/common';
6
+ import { createPruneMessages } from '@/messages';
7
7
  /**
8
8
  * Encapsulates agent-specific state that can vary between agents in a multi-agent system
9
9
  */
@@ -344,6 +344,35 @@ export declare class AgentContext {
344
344
  * for inclusion in error messages and diagnostics.
345
345
  */
346
346
  formatTokenBudgetBreakdown(messages?: BaseMessage[]): string;
347
+ /**
348
+ * Projects the context-usage snapshot for an arbitrary message set WITHOUT
349
+ * invoking the model — the pre-send / page-load / window-switch counterpart to
350
+ * the live `ON_CONTEXT_USAGE` snapshot. Runs the same pruner + budget math the
351
+ * graph uses (`createPruneMessages` → `getTokenBudgetBreakdown` →
352
+ * `syncBudgetDerivedFields`) so projected numbers match a real call. Returns
353
+ * null when the context lacks the tokenizer or window needed to prune. Omits
354
+ * the live post-format reconciliation (provider-specific, invoke-time) — a
355
+ * small, acceptable delta for a pre-send estimate.
356
+ *
357
+ * Safe to call off the hot path: the supplied `messages` are never mutated
358
+ * (each is passed as a clone — the pruner both replaces tool-result slots and
359
+ * unshifts reasoning blocks into AI content arrays in place), and this
360
+ * context's own state is untouched apart from refreshing stale instruction
361
+ * counts (idempotent, exactly what a real call does). Token counts are
362
+ * recounted for the supplied messages (the context's `indexTokenCountMap` is
363
+ * keyed to the live run's branch and would missum an arbitrary branch) unless
364
+ * the caller passes a map it guarantees matches. Calibration is NOT re-derived
365
+ * from this context's live usage (a fresh pruner would compare the prior
366
+ * call's provider input against the whole projected branch); the learned
367
+ * `calibrationRatio` is applied as a static seed, and callers may override it
368
+ * with a persisted ratio via `opts.calibrationRatio`.
369
+ */
370
+ projectContextUsage(messages: BaseMessage[], opts?: {
371
+ runId?: string;
372
+ agentId?: string;
373
+ calibrationRatio?: number;
374
+ indexTokenCountMap?: Record<string, number | undefined>;
375
+ }): t.ContextUsageEvent | null;
347
376
  /**
348
377
  * Updates the last-call usage with data from the most recent LLM response.
349
378
  * Unlike `currentUsage` which accumulates, this captures only the single call.
@@ -0,0 +1,26 @@
1
+ import type { BaseMessage } from '@langchain/core/messages';
2
+ import type * as t from '@/types';
3
+ export interface ProjectAgentContextUsageParams {
4
+ /** Same `AgentInputs` a run is built from (instructions, tools, model, window). */
5
+ agent: t.AgentInputs;
6
+ /** Branch messages to project, in send order (no leading system message). */
7
+ messages: BaseMessage[];
8
+ tokenCounter: t.TokenCounter;
9
+ /** Per-message counts aligned to `messages` (e.g. from `formatAgentMessages`).
10
+ * When omitted, counts are recounted via `tokenCounter`. */
11
+ indexTokenCountMap?: Record<string, number>;
12
+ /** Provider-calibrated ratio from a prior snapshot, applied as a static seed. */
13
+ calibrationRatio?: number;
14
+ runId?: string;
15
+ agentId?: string;
16
+ }
17
+ /**
18
+ * Projects a pre-send context-usage snapshot for a branch under an agent config
19
+ * WITHOUT invoking the model — the host-side (page-load / branch-switch /
20
+ * window-switch) counterpart to the live `ON_CONTEXT_USAGE` event. Builds a
21
+ * throwaway `AgentContext` from the same `AgentInputs` a run uses, awaits its
22
+ * instruction/tool token accounting, then runs the shared pruner + budget math
23
+ * via `AgentContext.projectContextUsage` (which never mutates the supplied
24
+ * messages). Returns null when the config has no tokenizer or context window.
25
+ */
26
+ export declare function projectAgentContextUsage({ agent, messages, tokenCounter, indexTokenCountMap, calibrationRatio, runId, agentId, }: ProjectAgentContextUsageParams): Promise<t.ContextUsageEvent | null>;
@@ -4,6 +4,7 @@ export * from './splitStream';
4
4
  export * from './events';
5
5
  export * from './messages';
6
6
  export * from './graphs';
7
+ export * from './agents/projection';
7
8
  export * from './summarization';
8
9
  export * from './tools/Calculator';
9
10
  export * from './tools/CodeExecutor';
@@ -0,0 +1,11 @@
1
+ import type * as t from '@/types';
2
+ /**
3
+ * Reconciles a context-usage breakdown's instruction/available/message fields
4
+ * from the pruner's budget metrics. `messageTokens` and `availableForMessages`
5
+ * are DERIVED from `contextBudget` / `effectiveInstructionTokens` /
6
+ * `remainingContextTokens` rather than summed from the index map — that map is
7
+ * keyed by pre-prune indices, so summing it over the kept context would missum.
8
+ * Shared by the live snapshot path (`Graph.createCallModel`) and the pre-send
9
+ * projection (`AgentContext.projectContextUsage`) so both yield identical numbers.
10
+ */
11
+ export declare function syncBudgetDerivedFields(usage: t.ContextUsageEvent): void;
@@ -3,6 +3,13 @@ import type { AnthropicMessage } from '@/types/messages';
3
3
  type MessageWithContent = {
4
4
  content?: string | MessageContentComplex[];
5
5
  };
6
+ /**
7
+ * Clones a message with new content. For LangChain BaseMessage instances,
8
+ * constructs a proper class instance so that `instanceof` checks are preserved
9
+ * in downstream code (e.g., ensureThinkingBlockInMessages).
10
+ * For plain objects (AnthropicMessage), uses object spread.
11
+ */
12
+ export declare function cloneMessage<T extends MessageWithContent>(message: T, content: string | MessageContentComplex[]): T;
6
13
  /**
7
14
  * Anthropic API: Adds cache control to the appropriate user messages in the payload.
8
15
  * Strips ALL existing cache control (both Anthropic and Bedrock formats) from all messages,
@@ -13,6 +20,25 @@ type MessageWithContent = {
13
20
  * @returns - A new array of message objects with cache control added.
14
21
  */
15
22
  export declare function addCacheControl<T extends AnthropicMessage | BaseMessage>(messages: T[]): T[];
23
+ /**
24
+ * Anthropic API: single tail cache breakpoint (default strategy).
25
+ *
26
+ * Places exactly ONE `cache_control` marker on the last cacheable block of the
27
+ * final non-synthetic message, mirroring the Claude Code strategy
28
+ * (`markerIndex = messages.length - 1`). Because the marker always rides the
29
+ * true tail, the entire conversation prefix is written once and read back on
30
+ * the next turn as the history grows append-only — instead of the rolling
31
+ * "last two user messages" markers, which leave freshly appended tool/assistant
32
+ * turns outside the cached prefix and re-write large spans every step.
33
+ *
34
+ * Stale markers (Anthropic `cache_control` and Bedrock cache points) are
35
+ * stripped from every message in a single backward pass so exactly one marker
36
+ * survives. Synthetic skill/meta messages are skipped as anchors (their volatile
37
+ * content must not pin the cache) but still have stale markers removed.
38
+ *
39
+ * Returns a new array; only messages that require modification are cloned.
40
+ */
41
+ export declare function addTailCacheControl<T extends AnthropicMessage | BaseMessage>(messages: T[]): T[];
16
42
  export declare function addCacheControlToStablePrefixMessages<T extends AnthropicMessage | BaseMessage>(messages: T[], maxCachePoints: number): T[];
17
43
  /**
18
44
  * Removes all Anthropic cache_control fields from messages
@@ -41,4 +67,25 @@ export declare function addBedrockCacheControl<T extends MessageWithContent & {
41
67
  getType?: () => string;
42
68
  role?: string;
43
69
  }>(messages: T[]): T[];
70
+ /**
71
+ * Bedrock Converse API: single tail cache breakpoint (default strategy).
72
+ *
73
+ * The Bedrock counterpart of {@link addTailCacheControl}. Strips ALL existing
74
+ * cache control (Bedrock cache points and Anthropic `cache_control`) from every
75
+ * message, then inserts exactly ONE `{ cachePoint: { type: 'default' } }` block
76
+ * immediately after the last non-empty text block of the most recent
77
+ * non-synthetic, non-system message. Anchoring on the rolling tail keeps the
78
+ * cached prefix append-only as the conversation grows, instead of re-writing
79
+ * large spans every turn with the legacy "last two user messages" cache points.
80
+ *
81
+ * System messages are sanitized (Anthropic `cache_control` stripped) but never
82
+ * anchored. Synthetic skill/meta messages are skipped as anchors so their
83
+ * volatile content cannot pin the cache.
84
+ *
85
+ * Returns a new array - only clones messages that require modification.
86
+ */
87
+ export declare function addBedrockTailCacheControl<T extends MessageWithContent & {
88
+ getType?: () => string;
89
+ role?: string;
90
+ }>(messages: T[]): T[];
44
91
  export {};
@@ -1,6 +1,7 @@
1
1
  export * from './core';
2
2
  export * from './ids';
3
3
  export * from './prune';
4
+ export * from './budget';
4
5
  export * from './format';
5
6
  export * from './cache';
6
7
  export * from './anthropicToolCache';
@@ -1,5 +1,8 @@
1
1
  import type * as t from './types';
2
- export declare function formatResultsForLLM(turn: number, results: t.SearchResultData): {
2
+ /** Resolves the per-search highlight budget from config, the
3
+ * `SEARCH_MAX_LLM_OUTPUT_CHARS` env var, or the default (50,000 chars). */
4
+ export declare function resolveMaxLLMOutputChars(maxOutputChars?: number): number;
5
+ export declare function formatResultsForLLM(turn: number, results: t.SearchResultData, maxOutputChars?: number): {
3
6
  output: string;
4
7
  references: t.ResultReference[];
5
8
  };
@@ -189,6 +189,13 @@ export type SafeSearchLevel = 0 | 1 | 2;
189
189
  export type Logger = WinstonLogger;
190
190
  export interface SearchToolConfig extends SearchConfig, ProcessSourcesConfig, FirecrawlConfig {
191
191
  tavilyScraperOptions?: TavilyScraperConfig;
192
+ /** Max chars of highlight content this tool feeds the MODEL per search (the
193
+ * dominant, otherwise-unbounded part of the output). Distinct from
194
+ * `maxContentLength`, which caps scraped/reranked content per source — full
195
+ * content always remains in the `WEB_SEARCH` artifact. Defaults to 50,000;
196
+ * also configurable via the `SEARCH_MAX_LLM_OUTPUT_CHARS` env var. Hosts that
197
+ * know the context window (e.g. LibreChat) pass a window-relative value. */
198
+ maxOutputChars?: number;
192
199
  logger?: Logger;
193
200
  safeSearch?: SafeSearchLevel;
194
201
  jinaApiKey?: string;
@@ -407,6 +407,8 @@ export interface LangfuseConfig {
407
407
  publicKey?: string;
408
408
  secretKey?: string;
409
409
  baseUrl?: string;
410
+ metadata?: Record<string, string | number | boolean | null | undefined>;
411
+ tags?: string[];
410
412
  toolNodeTracing?: LangfuseToolNodeTracingConfig;
411
413
  toolOutputTracing?: LangfuseToolOutputTracingConfig;
412
414
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@librechat/agents",
3
- "version": "3.2.35",
3
+ "version": "3.2.37",
4
4
  "main": "./dist/cjs/main.cjs",
5
5
  "module": "./dist/esm/main.mjs",
6
6
  "types": "./dist/types/index.d.ts",
@@ -139,6 +139,7 @@
139
139
  "tool": "node --trace-warnings -r dotenv/config --loader ./tsconfig-paths-bootstrap.mjs --experimental-specifier-resolution=node ./src/scripts/tools.ts --provider 'bedrock' --name 'Jo' --location 'New York, NY'",
140
140
  "search": "node -r dotenv/config --loader ./tsconfig-paths-bootstrap.mjs --experimental-specifier-resolution=node ./src/scripts/search.ts --provider 'bedrock' --name 'Jo' --location 'New York, NY'",
141
141
  "tool_search": "node -r dotenv/config --loader ./tsconfig-paths-bootstrap.mjs --experimental-specifier-resolution=node ./src/scripts/tool_search.ts",
142
+ "bench:cache": "node --loader ./tsconfig-paths-bootstrap.mjs --experimental-specifier-resolution=node ./src/scripts/bench-prompt-cache.ts",
142
143
  "subagent": "node -r dotenv/config --loader ./tsconfig-paths-bootstrap.mjs --experimental-specifier-resolution=node ./src/scripts/multi-agent-subagent.ts",
143
144
  "subagent:events": "node -r dotenv/config --loader ./tsconfig-paths-bootstrap.mjs --experimental-specifier-resolution=node ./src/scripts/subagent-event-driven-debug.ts",
144
145
  "subagent:tools": "node -r dotenv/config --loader ./tsconfig-paths-bootstrap.mjs --experimental-specifier-resolution=node ./src/scripts/subagent-tools-debug.ts",
@@ -7,7 +7,6 @@ import type {
7
7
  BaseMessageFields,
8
8
  } from '@langchain/core/messages';
9
9
  import type { RunnableConfig, Runnable } from '@langchain/core/runnables';
10
- import type { createPruneMessages } from '@/messages';
11
10
  import type * as t from '@/types';
12
11
  import {
13
12
  ANTHROPIC_TOOL_TOKEN_MULTIPLIER,
@@ -17,12 +16,18 @@ import {
17
16
  Providers,
18
17
  } from '@/common';
19
18
  import {
20
- addCacheControl,
19
+ addTailCacheControl,
21
20
  addCacheControlToStablePrefixMessages,
21
+ cloneMessage,
22
22
  } from '@/messages/cache';
23
23
  import { createSchemaOnlyTools } from '@/tools/schema';
24
24
  import { apportionTokenCounts } from '@/utils/tokens';
25
- import { DEFAULT_RESERVE_RATIO } from '@/messages';
25
+ import {
26
+ DEFAULT_RESERVE_RATIO,
27
+ createPruneMessages,
28
+ syncBudgetDerivedFields,
29
+ } from '@/messages';
30
+ import { isThinkingEnabled } from '@/llm/request';
26
31
  import { toJsonSchema } from '@/utils/schema';
27
32
 
28
33
  type AgentSystemTextBlock = {
@@ -684,7 +689,7 @@ export class AgentContext {
684
689
  dynamicTail.length === 0 &&
685
690
  body.length >= 2
686
691
  ) {
687
- body = addCacheControl(body);
692
+ body = addTailCacheControl(body);
688
693
  }
689
694
  return [...prefix, ...body];
690
695
  }).withConfig({ runName: 'prompt' });
@@ -1330,6 +1335,102 @@ export class AgentContext {
1330
1335
  return lines.join('\n');
1331
1336
  }
1332
1337
 
1338
+ /**
1339
+ * Projects the context-usage snapshot for an arbitrary message set WITHOUT
1340
+ * invoking the model — the pre-send / page-load / window-switch counterpart to
1341
+ * the live `ON_CONTEXT_USAGE` snapshot. Runs the same pruner + budget math the
1342
+ * graph uses (`createPruneMessages` → `getTokenBudgetBreakdown` →
1343
+ * `syncBudgetDerivedFields`) so projected numbers match a real call. Returns
1344
+ * null when the context lacks the tokenizer or window needed to prune. Omits
1345
+ * the live post-format reconciliation (provider-specific, invoke-time) — a
1346
+ * small, acceptable delta for a pre-send estimate.
1347
+ *
1348
+ * Safe to call off the hot path: the supplied `messages` are never mutated
1349
+ * (each is passed as a clone — the pruner both replaces tool-result slots and
1350
+ * unshifts reasoning blocks into AI content arrays in place), and this
1351
+ * context's own state is untouched apart from refreshing stale instruction
1352
+ * counts (idempotent, exactly what a real call does). Token counts are
1353
+ * recounted for the supplied messages (the context's `indexTokenCountMap` is
1354
+ * keyed to the live run's branch and would missum an arbitrary branch) unless
1355
+ * the caller passes a map it guarantees matches. Calibration is NOT re-derived
1356
+ * from this context's live usage (a fresh pruner would compare the prior
1357
+ * call's provider input against the whole projected branch); the learned
1358
+ * `calibrationRatio` is applied as a static seed, and callers may override it
1359
+ * with a persisted ratio via `opts.calibrationRatio`.
1360
+ */
1361
+ projectContextUsage(
1362
+ messages: BaseMessage[],
1363
+ opts?: {
1364
+ runId?: string;
1365
+ agentId?: string;
1366
+ calibrationRatio?: number;
1367
+ indexTokenCountMap?: Record<string, number | undefined>;
1368
+ }
1369
+ ): t.ContextUsageEvent | null {
1370
+ const tokenCounter = this.tokenCounter;
1371
+ if (tokenCounter == null || this.maxContextTokens == null) {
1372
+ return null;
1373
+ }
1374
+ /** Refresh stale system overhead (handoff/summary changes) so instruction
1375
+ * tokens match the prompt a real call would send. */
1376
+ this.initializeSystemRunnable();
1377
+ /** Clone array-content messages: the pruner unshifts reasoning blocks into
1378
+ * AI content arrays in place, which would otherwise corrupt the caller's
1379
+ * history. (Slot replacements land on the mapped array, not the caller's.) */
1380
+ const projected = messages.map((message) =>
1381
+ Array.isArray(message.content)
1382
+ ? cloneMessage(message, [...message.content])
1383
+ : message
1384
+ );
1385
+ let indexTokenCountMap = opts?.indexTokenCountMap;
1386
+ if (indexTokenCountMap == null) {
1387
+ indexTokenCountMap = {};
1388
+ for (let i = 0; i < messages.length; i++) {
1389
+ indexTokenCountMap[String(i)] = tokenCounter(messages[i]);
1390
+ }
1391
+ }
1392
+ const prune = createPruneMessages({
1393
+ startIndex: 0,
1394
+ provider: this.provider,
1395
+ tokenCounter,
1396
+ maxTokens: this.maxContextTokens,
1397
+ thinkingEnabled: isThinkingEnabled(this.provider, this.clientOptions),
1398
+ indexTokenCountMap,
1399
+ contextPruningConfig: this.contextPruningConfig,
1400
+ summarizationEnabled: this.summarizationEnabled,
1401
+ reserveRatio: this.summarizationConfig?.reserveRatio,
1402
+ calibrationRatio: opts?.calibrationRatio ?? this.calibrationRatio,
1403
+ getInstructionTokens: () => this.instructionTokens,
1404
+ });
1405
+ const {
1406
+ context,
1407
+ prePruneContextTokens,
1408
+ remainingContextTokens,
1409
+ contextBudget,
1410
+ effectiveInstructionTokens,
1411
+ calibrationRatio,
1412
+ } = prune({
1413
+ messages: projected,
1414
+ usageMetadata: undefined,
1415
+ lastCallUsage: undefined,
1416
+ totalTokensFresh: false,
1417
+ });
1418
+ const breakdown = this.getTokenBudgetBreakdown(messages);
1419
+ breakdown.messageCount = context.length;
1420
+ const usage: t.ContextUsageEvent = {
1421
+ runId: opts?.runId,
1422
+ agentId: opts?.agentId,
1423
+ breakdown,
1424
+ contextBudget,
1425
+ effectiveInstructionTokens,
1426
+ prePruneContextTokens,
1427
+ remainingContextTokens,
1428
+ calibrationRatio,
1429
+ };
1430
+ syncBudgetDerivedFields(usage);
1431
+ return usage;
1432
+ }
1433
+
1333
1434
  /**
1334
1435
  * Updates the last-call usage with data from the most recent LLM response.
1335
1436
  * Unlike `currentUsage` which accumulates, this captures only the single call.