@librechat/agents 3.1.70 → 3.1.71-dev.1

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 (66) hide show
  1. package/dist/cjs/graphs/Graph.cjs +52 -0
  2. package/dist/cjs/graphs/Graph.cjs.map +1 -1
  3. package/dist/cjs/llm/invoke.cjs +13 -2
  4. package/dist/cjs/llm/invoke.cjs.map +1 -1
  5. package/dist/cjs/main.cjs +4 -0
  6. package/dist/cjs/main.cjs.map +1 -1
  7. package/dist/cjs/messages/prune.cjs +9 -2
  8. package/dist/cjs/messages/prune.cjs.map +1 -1
  9. package/dist/cjs/run.cjs +4 -0
  10. package/dist/cjs/run.cjs.map +1 -1
  11. package/dist/cjs/tools/BashExecutor.cjs +43 -0
  12. package/dist/cjs/tools/BashExecutor.cjs.map +1 -1
  13. package/dist/cjs/tools/ToolNode.cjs +482 -45
  14. package/dist/cjs/tools/ToolNode.cjs.map +1 -1
  15. package/dist/cjs/tools/toolOutputReferences.cjs +657 -0
  16. package/dist/cjs/tools/toolOutputReferences.cjs.map +1 -0
  17. package/dist/cjs/utils/truncation.cjs +28 -0
  18. package/dist/cjs/utils/truncation.cjs.map +1 -1
  19. package/dist/esm/graphs/Graph.mjs +52 -0
  20. package/dist/esm/graphs/Graph.mjs.map +1 -1
  21. package/dist/esm/llm/invoke.mjs +13 -2
  22. package/dist/esm/llm/invoke.mjs.map +1 -1
  23. package/dist/esm/main.mjs +2 -2
  24. package/dist/esm/messages/prune.mjs +9 -2
  25. package/dist/esm/messages/prune.mjs.map +1 -1
  26. package/dist/esm/run.mjs +4 -0
  27. package/dist/esm/run.mjs.map +1 -1
  28. package/dist/esm/tools/BashExecutor.mjs +42 -1
  29. package/dist/esm/tools/BashExecutor.mjs.map +1 -1
  30. package/dist/esm/tools/ToolNode.mjs +482 -45
  31. package/dist/esm/tools/ToolNode.mjs.map +1 -1
  32. package/dist/esm/tools/toolOutputReferences.mjs +649 -0
  33. package/dist/esm/tools/toolOutputReferences.mjs.map +1 -0
  34. package/dist/esm/utils/truncation.mjs +27 -1
  35. package/dist/esm/utils/truncation.mjs.map +1 -1
  36. package/dist/types/graphs/Graph.d.ts +28 -0
  37. package/dist/types/llm/invoke.d.ts +9 -0
  38. package/dist/types/run.d.ts +1 -0
  39. package/dist/types/tools/BashExecutor.d.ts +31 -0
  40. package/dist/types/tools/ToolNode.d.ts +84 -3
  41. package/dist/types/tools/toolOutputReferences.d.ts +236 -0
  42. package/dist/types/types/index.d.ts +1 -0
  43. package/dist/types/types/messages.d.ts +26 -0
  44. package/dist/types/types/run.d.ts +9 -1
  45. package/dist/types/types/tools.d.ts +70 -0
  46. package/dist/types/utils/truncation.d.ts +21 -0
  47. package/package.json +1 -1
  48. package/src/graphs/Graph.ts +55 -0
  49. package/src/llm/invoke.test.ts +442 -0
  50. package/src/llm/invoke.ts +23 -2
  51. package/src/messages/prune.ts +9 -2
  52. package/src/run.ts +4 -0
  53. package/src/specs/prune.test.ts +413 -0
  54. package/src/tools/BashExecutor.ts +45 -0
  55. package/src/tools/ToolNode.ts +631 -55
  56. package/src/tools/__tests__/BashExecutor.test.ts +36 -0
  57. package/src/tools/__tests__/ToolNode.outputReferences.test.ts +1438 -0
  58. package/src/tools/__tests__/annotateMessagesForLLM.test.ts +419 -0
  59. package/src/tools/__tests__/toolOutputReferences.test.ts +415 -0
  60. package/src/tools/toolOutputReferences.ts +813 -0
  61. package/src/types/index.ts +1 -0
  62. package/src/types/messages.ts +27 -0
  63. package/src/types/run.ts +9 -1
  64. package/src/types/tools.ts +71 -0
  65. package/src/utils/__tests__/truncation.test.ts +66 -0
  66. package/src/utils/truncation.ts +30 -0
@@ -0,0 +1 @@
1
+ {"version":3,"file":"toolOutputReferences.mjs","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 under our framework\n * keys. Treat them as untrusted input and coerce defensively\n * before any array operation — a malformed field on a single\n * hydrated message must not crash `attemptInvoke` before the\n * provider call.\n */\n const meta = m.additional_kwargs as Record<string, unknown> | undefined;\n const hasRefKey = meta != null && '_refKey' in meta;\n const hasRefScope = meta != null && '_refScope' in meta;\n const hasUnresolvedField = meta != null && '_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 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"],"names":[],"mappings":";;;AAAA;;;;;;;;;;;;;;;;;;;;;;AAsBG;AAkBH;AACO,MAAM,mBAAmB,GAAG;AAEnC;;;;;AAKG;AACI,MAAM,0BAA0B,GAAG;AAE1C;AACM,SAAU,oBAAoB,CAAC,GAAW,EAAA;IAC9C,OAAO,CAAA,MAAA,EAAS,GAAG,CAAA,CAAA,CAAG;AACxB;AAEA;AACM,SAAU,iBAAiB,CAAC,SAAiB,EAAE,IAAY,EAAA;AAC/D,IAAA,OAAO,CAAA,IAAA,EAAO,SAAS,CAAA,IAAA,EAAO,IAAI,EAAE;AACtC;AAoDA,MAAM,aAAa,GAAgC,IAAI,GAAG,EAAkB;AAE5E;;;;;AAKG;AACH,MAAM,cAAc,CAAA;A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;;;;;AAYG;AACH,SAAS,2BAA2B,CAClC,EAAe,EACf,OAA+B,EAAA;IAE/B,OAAO,IAAI,WAAW,CAAC;QACrB,EAAE,EAAE,EAAE,CAAC,EAAE;QACT,IAAI,EAAE,EAAE,CAAC,IAAI;QACb,MAAM,EAAE,EAAE,CAAC,MAAM;QACjB,QAAQ,EAAE,EAAE,CAAC,QAAQ;QACrB,YAAY,EAAE,EAAE,CAAC,YAAY;QAC7B,iBAAiB,EAAE,EAAE,CAAC,iBAAiB;AACvC,QAAA,iBAAiB,EAAE,yBAAyB,CAAC,EAAE,CAAC,iBAAiB,CAAC;QAClE,OAAO;AACR,KAAA,CAAC;AACJ;AAEA;;;;;;AAMG;AACH,SAAS,yBAAyB,CAChC,MAA2C,EAAA;IAE3C,IAAI,MAAM,IAAI,IAAI;AAAE,QAAA,OAAO,SAAS;AACpC,IAAA,IACE,EAAE,SAAS,IAAI,MAAM,CAAC;AACtB,QAAA,EAAE,WAAW,IAAI,MAAM,CAAC;AACxB,QAAA,EAAE,iBAAiB,IAAI,MAAM,CAAC,EAC9B;AACA,QAAA,OAAO,MAAM;IACf;AACA,IAAA,MAAM,EAAE,OAAO,EAAE,SAAS,EAAE,eAAe,EAAE,GAAG,IAAI,EAAE,GAAG,MAOxD;AAID,IAAA,OAAO,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,MAAM,KAAK,CAAC,GAAG,SAAS,GAAG,IAAI;AAC1D;;;;"}
@@ -10,6 +10,15 @@
10
10
  * larger than this is almost certainly a bug (e.g., dumping a binary file).
11
11
  */
12
12
  const HARD_MAX_TOOL_RESULT_CHARS = 400_000;
13
+ /**
14
+ * Absolute hard cap on the aggregate size (characters) of all registered
15
+ * tool outputs kept for `{{tool<i>turn<n>}}` substitution. Set at 5 MB
16
+ * because the registry stores *raw, untruncated* tool output — full
17
+ * fidelity for piping into downstream bash/jq — so the budget needs
18
+ * enough headroom to keep a handful of large responses without
19
+ * ballooning unbounded.
20
+ */
21
+ const HARD_MAX_TOTAL_TOOL_OUTPUT_SIZE = 5_000_000;
13
22
  /**
14
23
  * Computes the dynamic max tool result size based on the model's context window.
15
24
  * Uses 30% of the context window (in estimated characters, ~4 chars/token)
@@ -24,6 +33,23 @@ function calculateMaxToolResultChars(contextWindowTokens) {
24
33
  }
25
34
  return Math.min(Math.floor(contextWindowTokens * 0.3) * 4, HARD_MAX_TOOL_RESULT_CHARS);
26
35
  }
36
+ /**
37
+ * Computes the default aggregate size (characters) for the tool output
38
+ * reference registry based on the per-output budget. Mirrors
39
+ * `calculateMaxToolResultChars`'s shape: a multiple of the per-output
40
+ * cap, clamped to `HARD_MAX_TOTAL_TOOL_OUTPUT_SIZE`.
41
+ *
42
+ * @param maxOutputSize - Per-output maximum characters (e.g., the
43
+ * ToolNode's `maxToolResultChars`). When omitted or non-positive,
44
+ * falls back to the absolute total cap.
45
+ * @returns Maximum total characters retained across the registry.
46
+ */
47
+ function calculateMaxTotalToolOutputSize(maxOutputSize) {
48
+ if (maxOutputSize == null || maxOutputSize <= 0) {
49
+ return HARD_MAX_TOTAL_TOOL_OUTPUT_SIZE;
50
+ }
51
+ return Math.min(maxOutputSize * 2, HARD_MAX_TOTAL_TOOL_OUTPUT_SIZE);
52
+ }
27
53
  /**
28
54
  * Truncates a tool-call input (the arguments/payload of a tool_use block)
29
55
  * using head+tail strategy. Returns an object with `_truncated` (the
@@ -98,5 +124,5 @@ function truncateToolResultContent(content, maxChars) {
98
124
  return content.slice(0, headEnd) + indicator + content.slice(tailStart);
99
125
  }
100
126
 
101
- export { HARD_MAX_TOOL_RESULT_CHARS, calculateMaxToolResultChars, truncateToolInput, truncateToolResultContent };
127
+ export { HARD_MAX_TOOL_RESULT_CHARS, HARD_MAX_TOTAL_TOOL_OUTPUT_SIZE, calculateMaxToolResultChars, calculateMaxTotalToolOutputSize, truncateToolInput, truncateToolResultContent };
102
128
  //# sourceMappingURL=truncation.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"truncation.mjs","sources":["../../../src/utils/truncation.ts"],"sourcesContent":["/**\n * Ingestion-time and pre-flight truncation utilities for tool results.\n *\n * Prevents oversized tool outputs from entering the message array and\n * consuming the entire context window.\n */\n\n/**\n * Absolute hard cap on tool result length (characters).\n * Even if the model has a 1M-token context, a single tool result\n * larger than this is almost certainly a bug (e.g., dumping a binary file).\n */\nexport const HARD_MAX_TOOL_RESULT_CHARS = 400_000;\n\n/**\n * Computes the dynamic max tool result size based on the model's context window.\n * Uses 30% of the context window (in estimated characters, ~4 chars/token)\n * capped at HARD_MAX_TOOL_RESULT_CHARS.\n *\n * @param contextWindowTokens - The model's max context tokens (optional).\n * @returns Maximum allowed characters for a single tool result.\n */\nexport function calculateMaxToolResultChars(\n contextWindowTokens?: number\n): number {\n if (contextWindowTokens == null || contextWindowTokens <= 0) {\n return HARD_MAX_TOOL_RESULT_CHARS;\n }\n return Math.min(\n Math.floor(contextWindowTokens * 0.3) * 4,\n HARD_MAX_TOOL_RESULT_CHARS\n );\n}\n\n/**\n * Truncates a tool-call input (the arguments/payload of a tool_use block)\n * using head+tail strategy. Returns an object with `_truncated` (the\n * truncated string) and `_originalChars` (for diagnostics).\n *\n * Accepts any type — objects are JSON-serialized before truncation.\n *\n * @param input - The tool input (string, object, etc.).\n * @param maxChars - Maximum allowed characters.\n */\nexport function truncateToolInput(\n input: unknown,\n maxChars: number\n): { _truncated: string; _originalChars: number } {\n const serialized = typeof input === 'string' ? input : JSON.stringify(input);\n if (serialized.length <= maxChars) {\n return { _truncated: serialized, _originalChars: serialized.length };\n }\n const indicator = `\\n… [truncated: ${serialized.length} chars exceeded ${maxChars} limit] …\\n`;\n const available = maxChars - indicator.length;\n\n if (available < 100) {\n return {\n _truncated: serialized.slice(0, maxChars) + indicator.trimEnd(),\n _originalChars: serialized.length,\n };\n }\n\n const headSize = Math.ceil(available * 0.7);\n const tailSize = available - headSize;\n\n return {\n _truncated:\n serialized.slice(0, headSize) +\n indicator +\n serialized.slice(serialized.length - tailSize),\n _originalChars: serialized.length,\n };\n}\n\n/**\n * Truncates tool result content that exceeds `maxChars` using a head+tail\n * strategy. Keeps the beginning (structure/headers) and end (return value /\n * conclusion) of the content so the model retains both the opening context\n * and the final outcome.\n *\n * Head gets ~70% of the budget, tail gets ~30%. Falls back to head-only\n * when the budget is too small for a meaningful tail.\n *\n * @param content - The tool result string content.\n * @param maxChars - Maximum allowed characters.\n * @returns The (possibly truncated) content string.\n */\nexport function truncateToolResultContent(\n content: string,\n maxChars: number\n): string {\n if (content.length <= maxChars) {\n return content;\n }\n\n const indicator = `\\n\\n… [truncated: ${content.length} chars exceeded ${maxChars} limit] …\\n\\n`;\n const available = maxChars - indicator.length;\n if (available <= 0) {\n return content.slice(0, maxChars);\n }\n\n // When budget is too small for a meaningful tail, fall back to head-only\n if (available < 200) {\n return content.slice(0, available) + indicator.trimEnd();\n }\n\n const headSize = Math.ceil(available * 0.7);\n const tailSize = available - headSize;\n\n // Try to break at newline boundaries for cleaner output\n let headEnd = headSize;\n const headNewline = content.lastIndexOf('\\n', headSize);\n if (headNewline > headSize - 200 && headNewline > 0) {\n headEnd = headNewline;\n }\n\n let tailStart = content.length - tailSize;\n const tailNewline = content.indexOf('\\n', tailStart);\n if (tailNewline > 0 && tailNewline < tailStart + 200) {\n tailStart = tailNewline + 1;\n }\n\n return content.slice(0, headEnd) + indicator + content.slice(tailStart);\n}\n"],"names":[],"mappings":"AAAA;;;;;AAKG;AAEH;;;;AAIG;AACI,MAAM,0BAA0B,GAAG;AAE1C;;;;;;;AAOG;AACG,SAAU,2BAA2B,CACzC,mBAA4B,EAAA;IAE5B,IAAI,mBAAmB,IAAI,IAAI,IAAI,mBAAmB,IAAI,CAAC,EAAE;AAC3D,QAAA,OAAO,0BAA0B;IACnC;AACA,IAAA,OAAO,IAAI,CAAC,GAAG,CACb,IAAI,CAAC,KAAK,CAAC,mBAAmB,GAAG,GAAG,CAAC,GAAG,CAAC,EACzC,0BAA0B,CAC3B;AACH;AAEA;;;;;;;;;AASG;AACG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,gBAAA,EAAmB,QAAQ,CAAA,aAAA,CAAe;AAC/F,IAAA,MAAM,SAAS,GAAG,QAAQ,GAAG,SAAS,CAAC,MAAM;AAC7C,IAAA,IAAI,SAAS,IAAI,CAAC,EAAE;QAClB,OAAO,OAAO,CAAC,KAAK,CAAC,CAAC,EAAE,QAAQ,CAAC;IACnC;;AAGA,IAAA,IAAI,SAAS,GAAG,GAAG,EAAE;AACnB,QAAA,OAAO,OAAO,CAAC,KAAK,CAAC,CAAC,EAAE,SAAS,CAAC,GAAG,SAAS,CAAC,OAAO,EAAE;IAC1D;IAEA,MAAM,QAAQ,GAAG,IAAI,CAAC,IAAI,CAAC,SAAS,GAAG,GAAG,CAAC;AAC3C,IAAA,MAAM,QAAQ,GAAG,SAAS,GAAG,QAAQ;;IAGrC,IAAI,OAAO,GAAG,QAAQ;IACtB,MAAM,WAAW,GAAG,OAAO,CAAC,WAAW,CAAC,IAAI,EAAE,QAAQ,CAAC;IACvD,IAAI,WAAW,GAAG,QAAQ,GAAG,GAAG,IAAI,WAAW,GAAG,CAAC,EAAE;QACnD,OAAO,GAAG,WAAW;IACvB;AAEA,IAAA,IAAI,SAAS,GAAG,OAAO,CAAC,MAAM,GAAG,QAAQ;IACzC,MAAM,WAAW,GAAG,OAAO,CAAC,OAAO,CAAC,IAAI,EAAE,SAAS,CAAC;IACpD,IAAI,WAAW,GAAG,CAAC,IAAI,WAAW,GAAG,SAAS,GAAG,GAAG,EAAE;AACpD,QAAA,SAAS,GAAG,WAAW,GAAG,CAAC;IAC7B;AAEA,IAAA,OAAO,OAAO,CAAC,KAAK,CAAC,CAAC,EAAE,OAAO,CAAC,GAAG,SAAS,GAAG,OAAO,CAAC,KAAK,CAAC,SAAS,CAAC;AACzE;;;;"}
1
+ {"version":3,"file":"truncation.mjs","sources":["../../../src/utils/truncation.ts"],"sourcesContent":["/**\n * Ingestion-time and pre-flight truncation utilities for tool results.\n *\n * Prevents oversized tool outputs from entering the message array and\n * consuming the entire context window.\n */\n\n/**\n * Absolute hard cap on tool result length (characters).\n * Even if the model has a 1M-token context, a single tool result\n * larger than this is almost certainly a bug (e.g., dumping a binary file).\n */\nexport const HARD_MAX_TOOL_RESULT_CHARS = 400_000;\n\n/**\n * Absolute hard cap on the aggregate size (characters) of all registered\n * tool outputs kept for `{{tool<i>turn<n>}}` substitution. Set at 5 MB\n * because the registry stores *raw, untruncated* tool output — full\n * fidelity for piping into downstream bash/jq — so the budget needs\n * enough headroom to keep a handful of large responses without\n * ballooning unbounded.\n */\nexport const HARD_MAX_TOTAL_TOOL_OUTPUT_SIZE = 5_000_000;\n\n/**\n * Computes the dynamic max tool result size based on the model's context window.\n * Uses 30% of the context window (in estimated characters, ~4 chars/token)\n * capped at HARD_MAX_TOOL_RESULT_CHARS.\n *\n * @param contextWindowTokens - The model's max context tokens (optional).\n * @returns Maximum allowed characters for a single tool result.\n */\nexport function calculateMaxToolResultChars(\n contextWindowTokens?: number\n): number {\n if (contextWindowTokens == null || contextWindowTokens <= 0) {\n return HARD_MAX_TOOL_RESULT_CHARS;\n }\n return Math.min(\n Math.floor(contextWindowTokens * 0.3) * 4,\n HARD_MAX_TOOL_RESULT_CHARS\n );\n}\n\n/**\n * Computes the default aggregate size (characters) for the tool output\n * reference registry based on the per-output budget. Mirrors\n * `calculateMaxToolResultChars`'s shape: a multiple of the per-output\n * cap, clamped to `HARD_MAX_TOTAL_TOOL_OUTPUT_SIZE`.\n *\n * @param maxOutputSize - Per-output maximum characters (e.g., the\n * ToolNode's `maxToolResultChars`). When omitted or non-positive,\n * falls back to the absolute total cap.\n * @returns Maximum total characters retained across the registry.\n */\nexport function calculateMaxTotalToolOutputSize(\n maxOutputSize?: number\n): number {\n if (maxOutputSize == null || maxOutputSize <= 0) {\n return HARD_MAX_TOTAL_TOOL_OUTPUT_SIZE;\n }\n return Math.min(maxOutputSize * 2, HARD_MAX_TOTAL_TOOL_OUTPUT_SIZE);\n}\n\n/**\n * Truncates a tool-call input (the arguments/payload of a tool_use block)\n * using head+tail strategy. Returns an object with `_truncated` (the\n * truncated string) and `_originalChars` (for diagnostics).\n *\n * Accepts any type — objects are JSON-serialized before truncation.\n *\n * @param input - The tool input (string, object, etc.).\n * @param maxChars - Maximum allowed characters.\n */\nexport function truncateToolInput(\n input: unknown,\n maxChars: number\n): { _truncated: string; _originalChars: number } {\n const serialized = typeof input === 'string' ? input : JSON.stringify(input);\n if (serialized.length <= maxChars) {\n return { _truncated: serialized, _originalChars: serialized.length };\n }\n const indicator = `\\n… [truncated: ${serialized.length} chars exceeded ${maxChars} limit] …\\n`;\n const available = maxChars - indicator.length;\n\n if (available < 100) {\n return {\n _truncated: serialized.slice(0, maxChars) + indicator.trimEnd(),\n _originalChars: serialized.length,\n };\n }\n\n const headSize = Math.ceil(available * 0.7);\n const tailSize = available - headSize;\n\n return {\n _truncated:\n serialized.slice(0, headSize) +\n indicator +\n serialized.slice(serialized.length - tailSize),\n _originalChars: serialized.length,\n };\n}\n\n/**\n * Truncates tool result content that exceeds `maxChars` using a head+tail\n * strategy. Keeps the beginning (structure/headers) and end (return value /\n * conclusion) of the content so the model retains both the opening context\n * and the final outcome.\n *\n * Head gets ~70% of the budget, tail gets ~30%. Falls back to head-only\n * when the budget is too small for a meaningful tail.\n *\n * @param content - The tool result string content.\n * @param maxChars - Maximum allowed characters.\n * @returns The (possibly truncated) content string.\n */\nexport function truncateToolResultContent(\n content: string,\n maxChars: number\n): string {\n if (content.length <= maxChars) {\n return content;\n }\n\n const indicator = `\\n\\n… [truncated: ${content.length} chars exceeded ${maxChars} limit] …\\n\\n`;\n const available = maxChars - indicator.length;\n if (available <= 0) {\n return content.slice(0, maxChars);\n }\n\n // When budget is too small for a meaningful tail, fall back to head-only\n if (available < 200) {\n return content.slice(0, available) + indicator.trimEnd();\n }\n\n const headSize = Math.ceil(available * 0.7);\n const tailSize = available - headSize;\n\n // Try to break at newline boundaries for cleaner output\n let headEnd = headSize;\n const headNewline = content.lastIndexOf('\\n', headSize);\n if (headNewline > headSize - 200 && headNewline > 0) {\n headEnd = headNewline;\n }\n\n let tailStart = content.length - tailSize;\n const tailNewline = content.indexOf('\\n', tailStart);\n if (tailNewline > 0 && tailNewline < tailStart + 200) {\n tailStart = tailNewline + 1;\n }\n\n return content.slice(0, headEnd) + indicator + content.slice(tailStart);\n}\n"],"names":[],"mappings":"AAAA;;;;;AAKG;AAEH;;;;AAIG;AACI,MAAM,0BAA0B,GAAG;AAE1C;;;;;;;AAOG;AACI,MAAM,+BAA+B,GAAG;AAE/C;;;;;;;AAOG;AACG,SAAU,2BAA2B,CACzC,mBAA4B,EAAA;IAE5B,IAAI,mBAAmB,IAAI,IAAI,IAAI,mBAAmB,IAAI,CAAC,EAAE;AAC3D,QAAA,OAAO,0BAA0B;IACnC;AACA,IAAA,OAAO,IAAI,CAAC,GAAG,CACb,IAAI,CAAC,KAAK,CAAC,mBAAmB,GAAG,GAAG,CAAC,GAAG,CAAC,EACzC,0BAA0B,CAC3B;AACH;AAEA;;;;;;;;;;AAUG;AACG,SAAU,+BAA+B,CAC7C,aAAsB,EAAA;IAEtB,IAAI,aAAa,IAAI,IAAI,IAAI,aAAa,IAAI,CAAC,EAAE;AAC/C,QAAA,OAAO,+BAA+B;IACxC;IACA,OAAO,IAAI,CAAC,GAAG,CAAC,aAAa,GAAG,CAAC,EAAE,+BAA+B,CAAC;AACrE;AAEA;;;;;;;;;AASG;AACG,SAAU,iBAAiB,CAC/B,KAAc,EACd,QAAgB,EAAA;AAEhB,IAAA,MAAM,UAAU,GAAG,OAAO,KAAK,KAAK,QAAQ,GAAG,KAAK,GAAG,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC;AAC5E,IAAA,IAAI,UAAU,CAAC,MAAM,IAAI,QAAQ,EAAE;QACjC,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,cAAc,EAAE,UAAU,CAAC,MAAM,EAAE;IACtE;IACA,MAAM,SAAS,GAAG,CAAA,gBAAA,EAAmB,UAAU,CAAC,MAAM,CAAA,gBAAA,E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AAQ,GAAG,IAAI,CAAC,IAAI,CAAC,SAAS,GAAG,GAAG,CAAC;AAC3C,IAAA,MAAM,QAAQ,GAAG,SAAS,GAAG,QAAQ;;IAGrC,IAAI,OAAO,GAAG,QAAQ;IACtB,MAAM,WAAW,GAAG,OAAO,CAAC,WAAW,CAAC,IAAI,EAAE,QAAQ,CAAC;IACvD,IAAI,WAAW,GAAG,QAAQ,GAAG,GAAG,IAAI,WAAW,GAAG,CAAC,EAAE;QACnD,OAAO,GAAG,WAAW;IACvB;AAEA,IAAA,IAAI,SAAS,GAAG,OAAO,CAAC,MAAM,GAAG,QAAQ;IACzC,MAAM,WAAW,GAAG,OAAO,CAAC,OAAO,CAAC,IAAI,EAAE,SAAS,CAAC;IACpD,IAAI,WAAW,GAAG,CAAC,IAAI,WAAW,GAAG,SAAS,GAAG,GAAG,EAAE;AACpD,QAAA,SAAS,GAAG,WAAW,GAAG,CAAC;IAC7B;AAEA,IAAA,OAAO,OAAO,CAAC,KAAK,CAAC,CAAC,EAAE,OAAO,CAAC,GAAG,SAAS,GAAG,OAAO,CAAC,KAAK,CAAC,SAAS,CAAC;AACzE;;;;"}
@@ -4,6 +4,7 @@ import type { UsageMetadata, BaseMessage } from '@langchain/core/messages';
4
4
  import type { ToolCall } from '@langchain/core/messages/tool';
5
5
  import type * as t from '@/types';
6
6
  import { ToolNode as CustomToolNode } from '@/tools/ToolNode';
7
+ import { ToolOutputReferenceRegistry } from '@/tools/toolOutputReferences';
7
8
  import { AgentContext } from '@/agents/AgentContext';
8
9
  import { HandlerRegistry } from '@/events';
9
10
  import type { HookRegistry } from '@/hooks';
@@ -45,6 +46,19 @@ export declare abstract class Graph<T extends t.BaseGraphState = t.BaseGraphStat
45
46
  invokedToolIds?: Set<string>;
46
47
  handlerRegistry: HandlerRegistry | undefined;
47
48
  hookRegistry: HookRegistry | undefined;
49
+ /**
50
+ * Run-scoped config for the tool output reference registry. Threaded
51
+ * from `RunConfig.toolOutputReferences` down into every ToolNode this
52
+ * graph compiles.
53
+ */
54
+ toolOutputReferences: t.ToolOutputReferencesConfig | undefined;
55
+ /**
56
+ * Shared registry instance used by every ToolNode compiled from this
57
+ * graph. Lazily constructed on first access so multi-agent graphs
58
+ * produce one registry per run (not one per agent), letting cross-
59
+ * agent `{{tool<i>turn<n>}}` substitutions resolve.
60
+ */
61
+ private _toolOutputRegistry?;
48
62
  /**
49
63
  * Tool session contexts for automatic state persistence across tool invocations.
50
64
  * Keyed by tool name (e.g., Constants.EXECUTE_CODE).
@@ -57,6 +71,20 @@ export declare abstract class Graph<T extends t.BaseGraphState = t.BaseGraphStat
57
71
  * Call after a run completes and content has been extracted.
58
72
  */
59
73
  clearHeavyState(): void;
74
+ /**
75
+ * Returns the shared `ToolOutputReferenceRegistry` for this run,
76
+ * constructing it on first access. Returns `undefined` when the
77
+ * feature is disabled. All ToolNodes compiled from this graph share
78
+ * this single instance so cross-agent `{{…}}` references resolve.
79
+ *
80
+ * @internal Public so `attemptInvoke` can read it through the typed
81
+ * `InvokeContext` and project ToolMessages into LLM-facing annotated
82
+ * copies right before each provider call (see
83
+ * `annotateMessagesForLLM`). Host code should not call this directly
84
+ * — registry mutations outside the ToolNode lifecycle break the
85
+ * partitioning, eviction, and turn-counter invariants.
86
+ */
87
+ getOrCreateToolOutputRegistry(): ToolOutputReferenceRegistry | undefined;
60
88
  }
61
89
  export declare class StandardGraph extends Graph<t.BaseGraphState, t.GraphNode> {
62
90
  overrideModel?: t.ChatModel;
@@ -7,6 +7,15 @@ import { Providers } from '@/common';
7
7
  /**
8
8
  * Context passed to `attemptInvoke` for the default stream handler.
9
9
  * Matches the subset of Graph that `ChatModelStreamHandler.handle` needs.
10
+ *
11
+ * `attemptInvoke` additionally calls `context?.getOrCreateToolOutputRegistry?.()`
12
+ * (if defined) to pull the run-scoped tool output registry off the graph
13
+ * so it can project each relevant `ToolMessage` into a transient
14
+ * annotated copy right before sending to the provider — annotations
15
+ * never persist back into graph state.
16
+ *
17
+ * Callers without a registry (e.g. summarization) simply pass no
18
+ * `context` and the transform safely no-ops.
10
19
  */
11
20
  export type InvokeContext = Parameters<ChatModelStreamHandler['handle']>[3];
12
21
  /**
@@ -10,6 +10,7 @@ export declare class Run<_T extends t.BaseGraphState> {
10
10
  private tokenCounter?;
11
11
  private handlerRegistry?;
12
12
  private hookRegistry?;
13
+ private toolOutputReferences?;
13
14
  private indexTokenCountMap?;
14
15
  calibrationRatio: number;
15
16
  graphRunnable?: t.CompiledStateWorkflow;
@@ -19,7 +19,38 @@ export declare const BashExecutionToolSchema: {
19
19
  readonly required: readonly ["command"];
20
20
  };
21
21
  export declare const BashExecutionToolDescription: string;
22
+ /**
23
+ * Supplemental prompt documenting the tool-output reference feature.
24
+ *
25
+ * Hosts should append this (separated by a blank line) to the base
26
+ * {@link BashExecutionToolDescription} only when
27
+ * `RunConfig.toolOutputReferences.enabled` is `true`. When the feature
28
+ * is disabled, including this text would tell the LLM to emit
29
+ * `{{tool0turn0}}` placeholders that pass through unsubstituted and
30
+ * leak into the shell.
31
+ */
32
+ export declare const BashToolOutputReferencesGuide: string;
33
+ /**
34
+ * Composes the bash tool description, optionally appending the
35
+ * tool-output references guide. Hosts that enable
36
+ * `RunConfig.toolOutputReferences` should pass `enableToolOutputReferences: true`
37
+ * when registering the tool so the LLM learns the `{{…}}` syntax it
38
+ * will actually be able to use.
39
+ */
40
+ export declare function buildBashExecutionToolDescription(options?: {
41
+ enableToolOutputReferences?: boolean;
42
+ }): string;
22
43
  export declare const BashExecutionToolName = Constants.BASH_TOOL;
44
+ /**
45
+ * Default bash tool definition using the base description.
46
+ *
47
+ * When `RunConfig.toolOutputReferences.enabled` is `true`, build a
48
+ * reference-aware description with
49
+ * {@link buildBashExecutionToolDescription}
50
+ * (`{ enableToolOutputReferences: true }`) and construct a custom
51
+ * definition using it — using this constant as-is leaves the LLM
52
+ * unaware of the `{{tool<i>turn<n>}}` syntax.
53
+ */
23
54
  export declare const BashExecutionToolDefinition: {
24
55
  readonly name: Constants.BASH_TOOL;
25
56
  readonly description: string;
@@ -2,8 +2,25 @@ import { ToolCall } from '@langchain/core/messages/tool';
2
2
  import { END, Command, MessagesAnnotation } from '@langchain/langgraph';
3
3
  import type { RunnableConfig } from '@langchain/core/runnables';
4
4
  import type { BaseMessage } from '@langchain/core/messages';
5
+ import type { ResolvedArgsByCallId } from '@/tools/toolOutputReferences';
5
6
  import type * as t from '@/types';
6
7
  import { RunnableCallable } from '@/utils';
8
+ import { ToolOutputReferenceRegistry } from '@/tools/toolOutputReferences';
9
+ /**
10
+ * Per-call batch context for `runTool`. Bundles every optional
11
+ * batch-scoped value the method needs so the signature stays at
12
+ * three positional parameters even as new context fields are added.
13
+ */
14
+ type RunToolBatchContext = {
15
+ /** Position of this call within the parent ToolNode batch. */
16
+ batchIndex?: number;
17
+ /** Batch turn shared across every call in the batch. */
18
+ turn?: number;
19
+ /** Registry partition scope (run id or anonymous batch id). */
20
+ batchScopeId?: string;
21
+ /** Batch-local sink for post-substitution args. */
22
+ resolvedArgsByCallId?: ResolvedArgsByCallId;
23
+ };
7
24
  export declare class ToolNode<T = any> extends RunnableCallable<T, T> {
8
25
  private toolMap;
9
26
  private loadRuntimeTools?;
@@ -30,7 +47,36 @@ export declare class ToolNode<T = any> extends RunnableCallable<T, T> {
30
47
  private maxToolResultChars;
31
48
  /** Hook registry for PreToolUse/PostToolUse lifecycle hooks */
32
49
  private hookRegistry?;
33
- constructor({ tools, toolMap, name, tags, errorHandler, toolCallStepIds, handleToolErrors, loadRuntimeTools, toolRegistry, sessions, eventDrivenMode, agentId, directToolNames, maxContextTokens, maxToolResultChars, hookRegistry, }: t.ToolNodeConstructorParams);
50
+ /**
51
+ * Registry of tool outputs keyed by `tool<idx>turn<turn>`.
52
+ *
53
+ * Populated only when `toolOutputReferences.enabled` is true. The
54
+ * registry owns the run-scoped state (turn counter, last-seen runId,
55
+ * warn-once memo, stored outputs), so sharing a single instance
56
+ * across multiple ToolNodes in a run lets cross-agent `{{…}}`
57
+ * references resolve — which is why multi-agent graphs pass the
58
+ * *same* instance to every ToolNode they compile rather than each
59
+ * ToolNode building its own.
60
+ */
61
+ private toolOutputRegistry?;
62
+ /**
63
+ * Monotonic counter used to mint a unique scope id for anonymous
64
+ * batches (ones invoked without a `run_id` in
65
+ * `config.configurable`). Each such batch gets its own registry
66
+ * partition so concurrent anonymous invocations can't delete each
67
+ * other's in-flight state.
68
+ */
69
+ private anonBatchCounter;
70
+ constructor({ tools, toolMap, name, tags, errorHandler, toolCallStepIds, handleToolErrors, loadRuntimeTools, toolRegistry, sessions, eventDrivenMode, agentId, directToolNames, maxContextTokens, maxToolResultChars, hookRegistry, toolOutputReferences, toolOutputRegistry, }: t.ToolNodeConstructorParams);
71
+ /**
72
+ * Returns the run-scoped tool output registry, or `undefined` when
73
+ * the feature is disabled.
74
+ *
75
+ * @internal Exposed for test observation only. Host code should rely
76
+ * on `{{tool<i>turn<n>}}` substitution at tool-invocation time and
77
+ * not mutate the registry directly.
78
+ */
79
+ _unsafeGetToolOutputRegistry(): ToolOutputReferenceRegistry | undefined;
34
80
  /**
35
81
  * Returns cached programmatic tools, computing once on first access.
36
82
  * Single iteration builds both toolMap and toolDefs simultaneously.
@@ -42,9 +88,34 @@ export declare class ToolNode<T = any> extends RunnableCallable<T, T> {
42
88
  */
43
89
  getToolUsageCounts(): ReadonlyMap<string, number>;
44
90
  /**
45
- * Runs a single tool call with error handling
91
+ * Runs a single tool call with error handling.
92
+ *
93
+ * `batchIndex` is the tool's position within the current ToolNode
94
+ * batch and, together with `this.currentTurn`, forms the key used to
95
+ * register the output for future `{{tool<idx>turn<turn>}}`
96
+ * substitutions. Omit when no registration should occur.
46
97
  */
47
- protected runTool(call: ToolCall, config: RunnableConfig): Promise<BaseMessage | Command>;
98
+ protected runTool(call: ToolCall, config: RunnableConfig, batchContext?: RunToolBatchContext): Promise<BaseMessage | Command>;
99
+ /**
100
+ * Registers the full, raw output under `refKey` (when provided) and
101
+ * builds the per-message ref metadata stamped onto the resulting
102
+ * `ToolMessage.additional_kwargs`. The metadata is read at LLM-
103
+ * request time by `annotateMessagesForLLM` to produce a transient
104
+ * annotated copy of the message — the persisted `content` itself
105
+ * stays clean.
106
+ *
107
+ * @param registryContent The full, untruncated output to store in
108
+ * the registry so `{{tool<i>turn<n>}}` substitutions deliver the
109
+ * complete payload. Ignored when `refKey` is undefined.
110
+ * @param refKey Precomputed `tool<i>turn<n>` key, or undefined when
111
+ * the output is not to be registered (errors, disabled feature,
112
+ * unavailable batch/turn).
113
+ * @param unresolved Placeholder keys that did not resolve; surfaced
114
+ * to the LLM lazily so it can self-correct.
115
+ * @returns A `ToolMessageRefMetadata` object when there is anything
116
+ * to stamp, otherwise `undefined`.
117
+ */
118
+ private recordOutputReference;
48
119
  /**
49
120
  * Builds code session context for injection into event-driven tool calls.
50
121
  * Mirrors the session injection logic in runTool() for direct execution.
@@ -63,6 +134,10 @@ export declare class ToolNode<T = any> extends RunnableCallable<T, T> {
63
134
  * By handling completions here in graph context (rather than in the
64
135
  * stream consumer via ToolEndHandler), the race between the stream
65
136
  * consumer and graph execution is eliminated.
137
+ *
138
+ * @param resolvedArgsByCallId Per-batch resolved-args sink populated
139
+ * by `runTool`. Threaded as a local map (instead of instance state)
140
+ * so concurrent batches cannot read each other's entries.
66
141
  */
67
142
  private handleRunToolCompletions;
68
143
  /**
@@ -93,6 +168,11 @@ export declare class ToolNode<T = any> extends RunnableCallable<T, T> {
93
168
  * Injected messages are placed AFTER ToolMessages to respect provider
94
169
  * message ordering (AIMessage tool_calls must be immediately followed
95
170
  * by their ToolMessage results).
171
+ *
172
+ * `batchIndices` mirrors `toolCalls` and carries each call's position
173
+ * within the parent batch. `turn` is the per-`run()` batch index
174
+ * captured locally by the caller. Both are threaded so concurrent
175
+ * invocations cannot race on shared mutable state.
96
176
  */
97
177
  private executeViaEvent;
98
178
  protected run(input: any, config: RunnableConfig): Promise<T>;
@@ -100,3 +180,4 @@ export declare class ToolNode<T = any> extends RunnableCallable<T, T> {
100
180
  private isMessagesState;
101
181
  }
102
182
  export declare function toolsCondition<T extends string>(state: BaseMessage[] | typeof MessagesAnnotation.State, toolNode: T, invokedToolIds?: Set<string>): T | typeof END;
183
+ export {};