@librechat/agents 4.2.5 → 4.2.6

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 (59) hide show
  1. package/dist/cjs/harness/identity.cjs +26 -0
  2. package/dist/cjs/harness/identity.cjs.map +1 -0
  3. package/dist/cjs/harness/index.cjs +3 -15
  4. package/dist/cjs/harness/index.cjs.map +1 -1
  5. package/dist/cjs/harness/providerText.cjs +79 -0
  6. package/dist/cjs/harness/providerText.cjs.map +1 -0
  7. package/dist/cjs/llm/contextPressureMeter.cjs +1 -1
  8. package/dist/cjs/llm/contextPressureMeter.cjs.map +1 -1
  9. package/dist/cjs/llm/openai/index.cjs +21 -12
  10. package/dist/cjs/llm/openai/index.cjs.map +1 -1
  11. package/dist/cjs/llm/openai/streamMetadata.cjs +4 -1
  12. package/dist/cjs/llm/openai/streamMetadata.cjs.map +1 -1
  13. package/dist/cjs/main.cjs +5 -0
  14. package/dist/cjs/stream.cjs +4 -1
  15. package/dist/cjs/stream.cjs.map +1 -1
  16. package/dist/cjs/tools/BashExecutor.cjs +2 -1
  17. package/dist/cjs/tools/BashExecutor.cjs.map +1 -1
  18. package/dist/cjs/tools/ToolNode.cjs +141 -94
  19. package/dist/cjs/tools/ToolNode.cjs.map +1 -1
  20. package/dist/cjs/tools/toolOutputReferences.cjs +39 -17
  21. package/dist/cjs/tools/toolOutputReferences.cjs.map +1 -1
  22. package/dist/esm/harness/identity.mjs +24 -0
  23. package/dist/esm/harness/identity.mjs.map +1 -0
  24. package/dist/esm/harness/index.mjs +3 -15
  25. package/dist/esm/harness/index.mjs.map +1 -1
  26. package/dist/esm/harness/providerText.mjs +78 -0
  27. package/dist/esm/harness/providerText.mjs.map +1 -0
  28. package/dist/esm/llm/contextPressureMeter.mjs +1 -1
  29. package/dist/esm/llm/contextPressureMeter.mjs.map +1 -1
  30. package/dist/esm/llm/openai/index.mjs +21 -12
  31. package/dist/esm/llm/openai/index.mjs.map +1 -1
  32. package/dist/esm/llm/openai/streamMetadata.mjs +4 -1
  33. package/dist/esm/llm/openai/streamMetadata.mjs.map +1 -1
  34. package/dist/esm/main.mjs +3 -1
  35. package/dist/esm/stream.mjs +4 -1
  36. package/dist/esm/stream.mjs.map +1 -1
  37. package/dist/esm/tools/BashExecutor.mjs +2 -1
  38. package/dist/esm/tools/BashExecutor.mjs.map +1 -1
  39. package/dist/esm/tools/ToolNode.mjs +142 -95
  40. package/dist/esm/tools/ToolNode.mjs.map +1 -1
  41. package/dist/esm/tools/toolOutputReferences.mjs +39 -18
  42. package/dist/esm/tools/toolOutputReferences.mjs.map +1 -1
  43. package/dist/types/harness/identity.d.ts +14 -0
  44. package/dist/types/harness/index.d.ts +5 -9
  45. package/dist/types/harness/providerText.d.ts +32 -0
  46. package/dist/types/llm/openai/streamMetadata.d.ts +3 -3
  47. package/dist/types/tools/ToolNode.d.ts +7 -7
  48. package/dist/types/tools/toolOutputReferences.d.ts +16 -4
  49. package/package.json +1 -1
  50. package/src/harness/identity.ts +34 -0
  51. package/src/harness/index.ts +15 -23
  52. package/src/harness/providerText.ts +128 -0
  53. package/src/llm/contextPressureMeter.ts +2 -4
  54. package/src/llm/openai/index.ts +60 -20
  55. package/src/llm/openai/streamMetadata.ts +14 -3
  56. package/src/stream.ts +10 -1
  57. package/src/tools/BashExecutor.ts +2 -1
  58. package/src/tools/ToolNode.ts +333 -256
  59. package/src/tools/toolOutputReferences.ts +101 -32
@@ -36,7 +36,6 @@ import type {
36
36
  PreResolvedArgsMap,
37
37
  ResolvedArgsByCallId,
38
38
  ResolveResult,
39
- ResolveOptions,
40
39
  } from '@/tools/toolOutputReferences';
41
40
  import type {
42
41
  ReplayableSubagentTool,
@@ -116,13 +115,14 @@ import {
116
115
  outcomeFieldsFromResult,
117
116
  } from '@/tools/intentArg';
118
117
  import {
119
- resolveLangfuseRuntimeScope,
120
- withLangfuseRuntimeScope,
121
- } from '@/langfuseRuntimeScope';
122
- import {
118
+ snapshotResolvedArgs,
123
119
  buildReferenceKey,
124
120
  ToolOutputReferenceRegistry,
125
121
  } from '@/tools/toolOutputReferences';
122
+ import {
123
+ resolveLangfuseRuntimeScope,
124
+ withLangfuseRuntimeScope,
125
+ } from '@/langfuseRuntimeScope';
126
126
  import {
127
127
  calculateMaxToolResultChars,
128
128
  truncateToolResultContent,
@@ -188,7 +188,10 @@ function stripHostExecutionConfig(
188
188
  }
189
189
  import { convertInjectedMessages } from '@/messages/injected';
190
190
  import { stampSyntheticProviderMessage } from '@/messages/provenance';
191
- import { createToolCallsDispatchedEvent, safeDispatchCustomEvent } from '@/utils/events';
191
+ import {
192
+ createToolCallsDispatchedEvent,
193
+ safeDispatchCustomEvent,
194
+ } from '@/utils/events';
192
195
  import { RunnableCallable, composeAbortSignals } from '@/utils';
193
196
  import {
194
197
  executeHooks,
@@ -241,6 +244,7 @@ type RunToolBatchContext<T = unknown> = {
241
244
  batchScopeId?: string;
242
245
  /** Batch-local sink for post-substitution args. */
243
246
  resolvedArgsByCallId?: ResolvedArgsByCallId;
247
+ resolvedInput?: ResolveResult<ToolCall['args']>;
244
248
  /** File identities actually injected into each direct code call. */
245
249
  codeSessionBaselineByCallId?: Map<string, ReadonlyMap<string, string>>;
246
250
  /**
@@ -1078,7 +1082,12 @@ export class ToolNode<T = any> extends RunnableCallable<T, T> {
1078
1082
  config,
1079
1083
  this.executingAgentId ?? this.agentId ?? ''
1080
1084
  );
1081
- config = getToolReplayConfig(config, replayOwner, activeReplayKey, assistantBatch?.message.id);
1085
+ config = getToolReplayConfig(
1086
+ config,
1087
+ replayOwner,
1088
+ activeReplayKey,
1089
+ assistantBatch?.message.id
1090
+ );
1082
1091
  let reviewEvidence = getToolApprovalReviewEvidence(config);
1083
1092
  const replayState = getToolBatchReplayState(config.configurable);
1084
1093
  const ownsParentBatch =
@@ -1135,18 +1144,40 @@ export class ToolNode<T = any> extends RunnableCallable<T, T> {
1135
1144
  );
1136
1145
  }
1137
1146
  const checkpointPending = getCheckpointPendingApproval(config);
1138
- const pendingBatch = checkpointPending != null && (
1139
- replayState?.records.some((record) => matchesToolReplayBatch(record.batch, activeReplayKey, assistantBatch?.message.id)) === true || ((replayState?.records.length ?? 0) === 0 &&
1140
- assistantBatch?.message.tool_calls?.some((call) =>
1141
- getReviewedToolApproval(checkpointPending.payload, call.id) != null
1142
- ) === true)
1143
- );
1144
- if (pendingBatch && checkpointPending.owner != null && checkpointPending.owner !== replayOwner && !isChildReplay) {
1145
- throw new Error('Tool approval execution owner changed before resume — failing closed');
1147
+ const pendingBatch =
1148
+ checkpointPending != null &&
1149
+ (replayState?.records.some((record) =>
1150
+ matchesToolReplayBatch(
1151
+ record.batch,
1152
+ activeReplayKey,
1153
+ assistantBatch?.message.id
1154
+ )
1155
+ ) === true ||
1156
+ ((replayState?.records.length ?? 0) === 0 &&
1157
+ assistantBatch?.message.tool_calls?.some(
1158
+ (call) =>
1159
+ getReviewedToolApproval(checkpointPending.payload, call.id) !=
1160
+ null
1161
+ ) === true));
1162
+ if (
1163
+ pendingBatch &&
1164
+ checkpointPending.owner != null &&
1165
+ checkpointPending.owner !== replayOwner &&
1166
+ !isChildReplay
1167
+ ) {
1168
+ throw new Error(
1169
+ 'Tool approval execution owner changed before resume — failing closed'
1170
+ );
1146
1171
  }
1147
- if (pendingBatch && checkpointPending.owner === replayOwner &&
1148
- (replayState?.records.length ?? 0) > 0 && !ownsParentBatch) {
1149
- throw new Error('Tool batch proposal changed before approval replay — failing closed');
1172
+ if (
1173
+ pendingBatch &&
1174
+ checkpointPending.owner === replayOwner &&
1175
+ (replayState?.records.length ?? 0) > 0 &&
1176
+ !ownsParentBatch
1177
+ ) {
1178
+ throw new Error(
1179
+ 'Tool batch proposal changed before approval replay — failing closed'
1180
+ );
1150
1181
  }
1151
1182
  if (replayResumeStatus === 'stale') {
1152
1183
  const configurable = { ...config.configurable };
@@ -1155,7 +1186,8 @@ export class ToolNode<T = any> extends RunnableCallable<T, T> {
1155
1186
  replayOwner,
1156
1187
  activeReplayKey
1157
1188
  );
1158
- if (pendingBatch) configurable[TOOL_PENDING_APPROVAL_KEY] = checkpointPending;
1189
+ if (pendingBatch)
1190
+ configurable[TOOL_PENDING_APPROVAL_KEY] = checkpointPending;
1159
1191
  config = {
1160
1192
  ...config,
1161
1193
  configurable,
@@ -1728,7 +1760,11 @@ export class ToolNode<T = any> extends RunnableCallable<T, T> {
1728
1760
  void safeDispatchCustomEvent(
1729
1761
  GraphEvents.ON_TOOL_CALLS_DISPATCHED,
1730
1762
  createToolCallsDispatchedEvent(config, [
1731
- { id: call.id, name: call.name, stepId: this.toolCallStepIds?.get(call.id) },
1763
+ {
1764
+ id: call.id,
1765
+ name: call.name,
1766
+ stepId: this.toolCallStepIds?.get(call.id),
1767
+ },
1732
1768
  ]),
1733
1769
  config
1734
1770
  );
@@ -1901,13 +1937,6 @@ export class ToolNode<T = any> extends RunnableCallable<T, T> {
1901
1937
  registry != null && batchIndex != null && turn != null
1902
1938
  ? buildReferenceKey(batchIndex, turn)
1903
1939
  : undefined;
1904
- /**
1905
- * Hoisted outside the try so the catch branch can append
1906
- * `[unresolved refs: …]` to error messages — otherwise the LLM
1907
- * only sees a generic error when it references a bad key, losing
1908
- * the self-correction signal this feature is meant to provide.
1909
- */
1910
- let unresolvedRefs: string[] = [];
1911
1940
  /**
1912
1941
  * Use the caller-provided `batchScopeId` when threaded from
1913
1942
  * `run()` (so anonymous batches get their own unique scope).
@@ -1955,9 +1984,15 @@ export class ToolNode<T = any> extends RunnableCallable<T, T> {
1955
1984
  }
1956
1985
  let args = call.args;
1957
1986
  if (resolveFn != null) {
1958
- const { resolved, unresolved } = resolveFn(runId, args);
1987
+ const resolution = batchContext.resolvedInput ?? resolveFn(runId, args);
1988
+ const { resolved } = resolution;
1959
1989
  args = resolved;
1960
- unresolvedRefs = unresolved;
1990
+ const referenceError = this.unresolvedReferenceMessage(
1991
+ call,
1992
+ resolution,
1993
+ preBatchSnapshot ?? registry?.snapshot(runId)
1994
+ );
1995
+ if (referenceError != null) return referenceError;
1961
1996
  /**
1962
1997
  * Expose the post-substitution args to downstream completion
1963
1998
  * events so audit logs / host-side `ON_RUN_STEP_COMPLETED`
@@ -2011,8 +2046,7 @@ export class ToolNode<T = any> extends RunnableCallable<T, T> {
2011
2046
  // they dispatch — including HITL gates on `write_file` / `edit_file`.
2012
2047
  hookContext: {
2013
2048
  registry: this.hookRegistry,
2014
- failClosedOnHookError:
2015
- isBackgroundDenyMode(this.humanInTheLoop),
2049
+ failClosedOnHookError: isBackgroundDenyMode(this.humanInTheLoop),
2016
2050
  runId: (config.configurable?.run_id as string | undefined) ?? '',
2017
2051
  threadId: config.configurable?.thread_id as string | undefined,
2018
2052
  agentId: this.agentId,
@@ -2099,30 +2133,17 @@ export class ToolNode<T = any> extends RunnableCallable<T, T> {
2099
2133
  }
2100
2134
  const isError = toolMsg.status === 'error';
2101
2135
  if (isError) {
2102
- /**
2103
- * Error ToolMessages bypass registration but still stamp the
2104
- * unresolved-refs hint into `additional_kwargs` so the lazy
2105
- * annotation transform surfaces it to the LLM, letting the
2106
- * model self-correct when its reference key caused the
2107
- * failure. Persisted `content` stays clean.
2108
- */
2109
- if (unresolvedRefs.length > 0) {
2110
- toolMsg.additional_kwargs = {
2111
- ...toolMsg.additional_kwargs,
2112
- _unresolvedRefs: unresolvedRefs,
2113
- };
2114
- }
2136
+ /** Error ToolMessages are never registered under a reference key. */
2115
2137
  return toolMsg;
2116
2138
  }
2117
- if (this.toolOutputRegistry != null || unresolvedRefs.length > 0) {
2139
+ if (this.toolOutputRegistry != null) {
2118
2140
  if (typeof originalContent === 'string') {
2119
2141
  const rawContent = originalContent;
2120
2142
  const registryContent = stripCodeSessionFileSummary(rawContent);
2121
2143
  const refMeta = this.recordOutputReference(
2122
2144
  runId,
2123
2145
  registryContent,
2124
- refKey,
2125
- unresolvedRefs
2146
+ refKey
2126
2147
  );
2127
2148
  if (refMeta != null) {
2128
2149
  toolMsg.additional_kwargs = {
@@ -2136,20 +2157,11 @@ export class ToolNode<T = any> extends RunnableCallable<T, T> {
2136
2157
  * image). It is now bounded for the LLM, but cannot register under a
2137
2158
  * reference key because there's no canonical serialized
2138
2159
  * form. Warn once per tool per run when the caller
2139
- * intended to register. The unresolved-refs hint is still
2140
- * stamped as metadata; the lazy transform prepends a text
2141
- * block at request time so the LLM gets the self-correction
2142
- * signal.
2160
+ * intended to register.
2143
2161
  */
2144
- if (unresolvedRefs.length > 0) {
2145
- toolMsg.additional_kwargs = {
2146
- ...toolMsg.additional_kwargs,
2147
- _unresolvedRefs: unresolvedRefs,
2148
- };
2149
- }
2150
2162
  if (
2151
2163
  refKey != null &&
2152
- this.toolOutputRegistry!.claimWarnOnce(runId, call.name)
2164
+ this.toolOutputRegistry.claimWarnOnce(runId, call.name)
2153
2165
  ) {
2154
2166
  // eslint-disable-next-line no-console
2155
2167
  console.warn(
@@ -2171,8 +2183,7 @@ export class ToolNode<T = any> extends RunnableCallable<T, T> {
2171
2183
  const refMeta = this.recordOutputReference(
2172
2184
  runId,
2173
2185
  stripCodeSessionFileSummary(serialized.registryContent),
2174
- refKey,
2175
- unresolvedRefs
2186
+ refKey
2176
2187
  );
2177
2188
  return new ToolMessage({
2178
2189
  status: 'success',
@@ -2273,27 +2284,40 @@ export class ToolNode<T = any> extends RunnableCallable<T, T> {
2273
2284
  config.signal,
2274
2285
  e
2275
2286
  );
2276
- const refMeta =
2277
- unresolvedRefs.length > 0
2278
- ? this.recordOutputReference(
2279
- runId,
2280
- errorContent,
2281
- undefined,
2282
- unresolvedRefs
2283
- )
2284
- : undefined;
2285
2287
  return new ToolMessage({
2286
2288
  status: 'error',
2287
2289
  content: errorContent,
2288
2290
  name: call.name,
2289
2291
  tool_call_id: call.id ?? '',
2290
- ...(refMeta != null && {
2291
- additional_kwargs: refMeta as Record<string, unknown>,
2292
- }),
2293
2292
  });
2294
2293
  }
2295
2294
  }
2296
2295
 
2296
+ private unresolvedReferenceMessage(
2297
+ call: ToolCall,
2298
+ resolution: Pick<ResolveResult<ToolCall['args']>, 'unresolved'>,
2299
+ view?: ToolOutputResolveView
2300
+ ): ToolMessage | undefined {
2301
+ if (resolution.unresolved.length === 0) return undefined;
2302
+ const missing = [
2303
+ ...new Set(
2304
+ resolution.unresolved.slice(0, 10).map((key) => key.slice(0, 80))
2305
+ ),
2306
+ ];
2307
+ const available = [
2308
+ ...new Set(
2309
+ (view?.availableKeys ?? []).slice(0, 10).map((key) => key.slice(0, 80))
2310
+ ),
2311
+ ];
2312
+ return new ToolMessage({
2313
+ status: 'error',
2314
+ name: call.name,
2315
+ tool_call_id: call.id ?? '',
2316
+ content: `Unknown tool output references: ${missing.join(', ')}${resolution.unresolved.length > missing.length ? ', …' : ''}; nothing was run. Available keys (most recent, up to 10): ${available.join(', ') || '(none)'}. Use a prior batch's key, fetch the output again, or prefix a literal placeholder with a backslash.`,
2317
+ additional_kwargs: { _unresolvedRefs: missing },
2318
+ });
2319
+ }
2320
+
2297
2321
  /**
2298
2322
  * Runs a single in-process tool call with the same lifecycle hooks
2299
2323
  * the event-dispatch path fires (`PreToolUse`, `PermissionDenied`,
@@ -2327,8 +2351,8 @@ export class ToolNode<T = any> extends RunnableCallable<T, T> {
2327
2351
  * the rest of the SDK's HITL-disabled default). One-time
2328
2352
  * warning logged so hosts notice the gap.
2329
2353
  * - `PreToolUse.updatedInput` is applied to the call before
2330
- * `runTool` runs; placeholder resolution inside `runTool` is
2331
- * idempotent on already-resolved args.
2354
+ * `runTool` runs; the resolution result is carried to invocation so
2355
+ * substituted output and escaped literals are never expanded twice.
2332
2356
  * - `PostToolUse.updatedOutput` replaces the returned
2333
2357
  * `ToolMessage` content (preserving id/name/status).
2334
2358
  * - `PostToolUseFailure` fires when `runTool` returns a
@@ -2461,13 +2485,25 @@ export class ToolNode<T = any> extends RunnableCallable<T, T> {
2461
2485
  approvalReplaySessionId,
2462
2486
  approvalReplayKey
2463
2487
  );
2464
- const replayOwner = getToolBatchReplayOwner(config, this.executingAgentId ?? this.agentId ?? '');
2465
- const approvalReviewEvidence = getToolApprovalReviewEvidence(config, replayOwner);
2488
+ const replayOwner = getToolBatchReplayOwner(
2489
+ config,
2490
+ this.executingAgentId ?? this.agentId ?? ''
2491
+ );
2492
+ const approvalReviewEvidence = getToolApprovalReviewEvidence(
2493
+ config,
2494
+ replayOwner
2495
+ );
2466
2496
  const checkpointPending = getCheckpointPendingApproval(config);
2467
- if (approvalReviewEvidence == null && checkpointPending != null &&
2468
- (checkpointPending.owner == null || checkpointPending.owner === replayOwner) &&
2469
- getReviewedToolApproval(checkpointPending.payload, call.id) != null) {
2470
- throw new GraphInterrupt([{ id: checkpointPending.interruptId, value: checkpointPending.value }]);
2497
+ if (
2498
+ approvalReviewEvidence == null &&
2499
+ checkpointPending != null &&
2500
+ (checkpointPending.owner == null ||
2501
+ checkpointPending.owner === replayOwner) &&
2502
+ getReviewedToolApproval(checkpointPending.payload, call.id) != null
2503
+ ) {
2504
+ throw new GraphInterrupt([
2505
+ { id: checkpointPending.interruptId, value: checkpointPending.value },
2506
+ ]);
2471
2507
  }
2472
2508
  const reviewedApproval = getReviewedToolApproval(
2473
2509
  approvalReviewEvidence?.payload,
@@ -2545,25 +2581,34 @@ export class ToolNode<T = any> extends RunnableCallable<T, T> {
2545
2581
  const hookResolveOptions = {
2546
2582
  substituteIntentKey: this.toolDeclaresBusinessIntent(call.name),
2547
2583
  };
2584
+ const referenceView =
2585
+ batchContext.preBatchSnapshot ??
2586
+ this.toolOutputRegistry?.snapshot(registryRunId);
2587
+ let inputResolution: ResolveResult<ToolCall['args']> = {
2588
+ resolved: {},
2589
+ unresolved: [],
2590
+ };
2548
2591
  const resolveDirectArgs = (
2549
- args: Record<string, unknown>
2592
+ args: Record<string, unknown>,
2593
+ previouslyResolved?: Record<string, unknown>
2550
2594
  ): Record<string, unknown> => {
2551
- if (batchContext.preBatchSnapshot != null) {
2552
- return batchContext.preBatchSnapshot.resolve(args, hookResolveOptions)
2553
- .resolved as Record<string, unknown>;
2554
- }
2555
- if (this.toolOutputRegistry != null) {
2556
- return this.toolOutputRegistry.resolve(
2557
- registryRunId,
2558
- args,
2559
- hookResolveOptions
2560
- ).resolved as Record<string, unknown>;
2561
- }
2562
- return args;
2595
+ inputResolution = referenceView?.resolve(args, {
2596
+ ...hookResolveOptions,
2597
+ previouslyResolved,
2598
+ }) ?? {
2599
+ resolved: args,
2600
+ unresolved: [],
2601
+ };
2602
+ return inputResolution.resolved;
2563
2603
  };
2564
- const originalResolvedArgs = resolveDirectArgs(
2565
- call.args as Record<string, unknown>
2604
+ const originalResolvedArgs = resolveDirectArgs(call.args);
2605
+ const originalReferenceError = this.unresolvedReferenceMessage(
2606
+ call,
2607
+ inputResolution,
2608
+ referenceView
2566
2609
  );
2610
+ if (originalReferenceError != null)
2611
+ return persistOutput(originalReferenceError);
2567
2612
  /** Reusable and pending hooks must replay from the original proposal so
2568
2613
  * non-idempotent rewrites are applied exactly once. A rebuilt runtime
2569
2614
  * without that policy instead falls back to the resolved arguments the
@@ -2573,13 +2618,18 @@ export class ToolNode<T = any> extends RunnableCallable<T, T> {
2573
2618
  ? originalResolvedArgs
2574
2619
  : (reviewedApproval?.request.arguments ?? originalResolvedArgs);
2575
2620
 
2576
- let effectiveCall = call;
2621
+ if (resolvedArgs !== originalResolvedArgs) {
2622
+ inputResolution = { resolved: resolvedArgs, unresolved: [] };
2623
+ }
2624
+ let effectiveCall = { ...call, args: resolvedArgs };
2577
2625
  if (
2578
2626
  hasPreHook ||
2579
2627
  pendingApproval != null ||
2580
2628
  reviewedApproval != null ||
2581
2629
  approvalReviewEvidence != null
2582
2630
  ) {
2631
+ const hookBaseline =
2632
+ referenceView == null ? undefined : snapshotResolvedArgs(resolvedArgs);
2583
2633
  const preResult: AggregatedHookResult | undefined =
2584
2634
  hookRegistry == null
2585
2635
  ? {
@@ -2608,14 +2658,13 @@ export class ToolNode<T = any> extends RunnableCallable<T, T> {
2608
2658
  onceReplaySessionId: approvalReplaySessionId,
2609
2659
  }).catch((): AggregatedHookResult | undefined =>
2610
2660
  approvalReviewEvidence == null &&
2611
- !isBackgroundDenyMode(this.humanInTheLoop)
2661
+ !isBackgroundDenyMode(this.humanInTheLoop)
2612
2662
  ? undefined
2613
2663
  : {
2614
2664
  decision: 'deny',
2615
- reason:
2616
- isBackgroundDenyMode(this.humanInTheLoop)
2617
- ? 'Approval policy could not be evaluated'
2618
- : 'Approval policy could not be evaluated on resume',
2665
+ reason: isBackgroundDenyMode(this.humanInTheLoop)
2666
+ ? 'Approval policy could not be evaluated'
2667
+ : 'Approval policy could not be evaluated on resume',
2619
2668
  ...(isBackgroundDenyMode(this.humanInTheLoop)
2620
2669
  ? { hasHookFailures: true }
2621
2670
  : {}),
@@ -2625,36 +2674,32 @@ export class ToolNode<T = any> extends RunnableCallable<T, T> {
2625
2674
  }
2626
2675
  );
2627
2676
 
2628
- if (preResult != null) {
2629
- // Forward any additionalContext strings hooks returned into
2630
- // the per-batch sink so the caller materializes them as a
2631
- // HumanMessage for the next model turn — same shape as the
2632
- // event-driven path's `injected[]`. Codex P2 #39.
2633
- if (preResult.additionalContexts.length > 0) {
2634
- replayAdditionalContexts.push(...preResult.additionalContexts);
2635
- batchContext.additionalContextsSink?.push(
2636
- ...preResult.additionalContexts
2637
- );
2638
- }
2639
- // Apply any input rewrite first — `ask`-with-`updatedInput` is
2640
- // a valid combination (one matcher sanitises args, another asks
2641
- // for approval); the reviewer should see the sanitised args.
2642
- if (preResult.updatedInput != null) {
2643
- resolvedArgs = resolveDirectArgs(
2644
- preResult.updatedInput as Record<string, unknown>
2645
- );
2646
- effectiveCall = {
2647
- ...call,
2648
- args: resolvedArgs,
2649
- };
2650
- } else if (reviewedApproval != null) {
2651
- resolvedArgs = reviewedApproval.request.arguments;
2652
- effectiveCall = {
2653
- ...call,
2654
- args: resolvedArgs,
2655
- };
2656
- }
2677
+ if (preResult != null && preResult.additionalContexts.length > 0) {
2678
+ replayAdditionalContexts.push(...preResult.additionalContexts);
2679
+ batchContext.additionalContextsSink?.push(
2680
+ ...preResult.additionalContexts
2681
+ );
2682
+ }
2657
2683
 
2684
+ if (preResult?.updatedInput != null) {
2685
+ resolvedArgs = resolveDirectArgs(preResult.updatedInput, hookBaseline);
2686
+ effectiveCall = { ...call, args: resolvedArgs };
2687
+ } else if (preResult != null && reviewedApproval != null) {
2688
+ resolvedArgs = reviewedApproval.request.arguments;
2689
+ inputResolution = { resolved: resolvedArgs, unresolved: [] };
2690
+ effectiveCall = { ...call, args: resolvedArgs };
2691
+ } else if (referenceView != null) {
2692
+ resolvedArgs = resolveDirectArgs(resolvedArgs, hookBaseline);
2693
+ effectiveCall = { ...call, args: resolvedArgs };
2694
+ }
2695
+ const referenceError = this.unresolvedReferenceMessage(
2696
+ call,
2697
+ inputResolution,
2698
+ referenceView
2699
+ );
2700
+ if (referenceError != null) return persistOutput(referenceError);
2701
+
2702
+ if (preResult != null) {
2658
2703
  if (
2659
2704
  preResult.hasHookFailures === true &&
2660
2705
  isBackgroundDenyMode(this.humanInTheLoop)
@@ -2715,13 +2760,12 @@ export class ToolNode<T = any> extends RunnableCallable<T, T> {
2715
2760
  if (preResult.decision === 'ask' || reviewedApproval != null) {
2716
2761
  if (this.humanInTheLoop?.enabled !== true) {
2717
2762
  // Fail closed when there is no foreground approval channel.
2718
- const reason =
2719
- isBackgroundDenyMode(this.humanInTheLoop)
2720
- ? this.backgroundApprovalReason(call.name, preResult.reason)
2721
- : this.resolveAskDecisionForDirectTool(
2722
- preResult.reason,
2723
- call.name
2724
- );
2763
+ const reason = isBackgroundDenyMode(this.humanInTheLoop)
2764
+ ? this.backgroundApprovalReason(call.name, preResult.reason)
2765
+ : this.resolveAskDecisionForDirectTool(
2766
+ preResult.reason,
2767
+ call.name
2768
+ );
2725
2769
  return persistOutput(
2726
2770
  this.blockDirectCall({
2727
2771
  call,
@@ -2773,9 +2817,6 @@ export class ToolNode<T = any> extends RunnableCallable<T, T> {
2773
2817
  preResult.decision === 'ask'
2774
2818
  ? preResult.reason
2775
2819
  : reviewedApproval?.request.description;
2776
- if (effectiveCall === call) {
2777
- effectiveCall = { ...call, args: resolvedArgs };
2778
- }
2779
2820
  const askEntry: AskEntry = {
2780
2821
  entry: {
2781
2822
  call: effectiveCall,
@@ -2786,8 +2827,15 @@ export class ToolNode<T = any> extends RunnableCallable<T, T> {
2786
2827
  allowedDecisions,
2787
2828
  };
2788
2829
  const payload = buildToolApprovalInterruptPayload(
2789
- [askEntry], runId, this.executionContext, this.executingAgentId
2830
+ [askEntry],
2831
+ runId,
2832
+ this.executionContext,
2833
+ this.executingAgentId
2790
2834
  );
2835
+ const approvalBaseline =
2836
+ referenceView == null
2837
+ ? undefined
2838
+ : snapshotResolvedArgs(effectiveCall.args);
2791
2839
  const resumeValue = AsyncLocalStorageProviderSingleton.runWithConfig(
2792
2840
  config,
2793
2841
  () =>
@@ -2923,7 +2971,10 @@ export class ToolNode<T = any> extends RunnableCallable<T, T> {
2923
2971
  }
2924
2972
  effectiveCall = {
2925
2973
  ...call,
2926
- args: updatedInput as Record<string, unknown>,
2974
+ args: resolveDirectArgs(
2975
+ updatedInput as Record<string, unknown>,
2976
+ approvalBaseline
2977
+ ),
2927
2978
  };
2928
2979
  // fall through to executing the edited call
2929
2980
  }
@@ -2948,16 +2999,13 @@ export class ToolNode<T = any> extends RunnableCallable<T, T> {
2948
2999
  }
2949
3000
 
2950
3001
  /**
2951
- * A hook (`PreToolUse.updatedInput`) or HITL `edit` decision rewrote the
2952
- * args: expose the EFFECTIVE args to downstream completion handling
2953
- * (`handleRunToolCompletions` reads this sink), so the emitted
2954
- * `tool_call.args` — and any intent/outcome label resolved from them —
2955
- * reflect what the tool actually ran with. `runTool`'s own placeholder
2956
- * substitution may overwrite this entry with the post-substitution args,
2957
- * which is strictly more accurate.
3002
+ * Expose the EFFECTIVE args (references substituted, plus any
3003
+ * `PreToolUse.updatedInput` or HITL `edit` rewrite) to downstream
3004
+ * completion handling (`handleRunToolCompletions` reads this sink), so
3005
+ * the emitted `tool_call.args` — and any intent/outcome label resolved
3006
+ * from them — reflect what the tool actually ran with.
2958
3007
  */
2959
3008
  if (
2960
- effectiveCall !== call &&
2961
3009
  batchContext.resolvedArgsByCallId != null &&
2962
3010
  call.id != null &&
2963
3011
  call.id !== ''
@@ -2971,6 +3019,8 @@ export class ToolNode<T = any> extends RunnableCallable<T, T> {
2971
3019
  const output = await this.runTool(effectiveCall, replayConfig, {
2972
3020
  ...batchContext,
2973
3021
  usageCount,
3022
+ preBatchSnapshot: referenceView,
3023
+ resolvedInput: inputResolution,
2974
3024
  });
2975
3025
 
2976
3026
  if (!(output instanceof ToolMessage)) {
@@ -3186,37 +3236,28 @@ export class ToolNode<T = any> extends RunnableCallable<T, T> {
3186
3236
  * @param refKey Precomputed `tool<i>turn<n>` key, or undefined when
3187
3237
  * the output is not to be registered (errors, disabled feature,
3188
3238
  * unavailable batch/turn).
3189
- * @param unresolved Placeholder keys that did not resolve; surfaced
3190
- * to the LLM lazily so it can self-correct.
3191
- * @returns A `ToolMessageRefMetadata` object when there is anything
3192
- * to stamp, otherwise `undefined`.
3239
+ * @returns A `ToolMessageRefMetadata` object when the output was
3240
+ * registered, otherwise `undefined`.
3193
3241
  */
3194
3242
  private recordOutputReference(
3195
3243
  runId: string | undefined,
3196
3244
  registryContent: string,
3197
- refKey: string | undefined,
3198
- unresolved: string[]
3245
+ refKey: string | undefined
3199
3246
  ): t.ToolMessageRefMetadata | undefined {
3200
- if (this.toolOutputRegistry != null && refKey != null) {
3201
- this.toolOutputRegistry.set(runId, refKey, registryContent);
3202
- }
3203
- if (refKey == null && unresolved.length === 0) return undefined;
3204
- const meta: t.ToolMessageRefMetadata = {};
3205
- if (refKey != null) {
3206
- meta._refKey = refKey;
3207
- /**
3208
- * Stamp the registry scope alongside the key so the lazy
3209
- * annotation transform can look up the right bucket. Anonymous
3210
- * invocations get a synthetic per-batch scope (`\0anon-<n>`)
3211
- * that `attemptInvoke` cannot derive from
3212
- * `config.configurable.run_id` — without this, anonymous-run
3213
- * refs would silently fail registry lookup and the LLM would
3214
- * never see `[ref: …]` markers for outputs that were registered.
3215
- */
3216
- if (runId != null) meta._refScope = runId;
3217
- }
3218
- if (unresolved.length > 0) meta._unresolvedRefs = unresolved;
3219
- return meta;
3247
+ if (refKey == null) return undefined;
3248
+ this.toolOutputRegistry?.set(runId, refKey, registryContent);
3249
+ /**
3250
+ * Stamp the registry scope alongside the key so the lazy
3251
+ * annotation transform can look up the right bucket. Anonymous
3252
+ * invocations get a synthetic per-batch scope (`\0anon-<n>`)
3253
+ * that `attemptInvoke` cannot derive from
3254
+ * `config.configurable.run_id` — without this, anonymous-run
3255
+ * refs would silently fail registry lookup and the LLM would
3256
+ * never see `[ref: …]` markers for outputs that were registered.
3257
+ */
3258
+ return runId == null
3259
+ ? { _refKey: refKey }
3260
+ : { _refKey: refKey, _refScope: runId };
3220
3261
  }
3221
3262
 
3222
3263
  /**
@@ -3575,8 +3616,9 @@ export class ToolNode<T = any> extends RunnableCallable<T, T> {
3575
3616
  const threadId = config.configurable?.thread_id as string | undefined;
3576
3617
  const registry = this.toolOutputRegistry;
3577
3618
  const unresolvedByCallId = new Map<string, string[]>();
3619
+ const referenceView = preBatchSnapshot ?? registry?.snapshot(registryRunId);
3578
3620
 
3579
- const preToolCalls = toolCalls.map((call, i) => {
3621
+ let preToolCalls = toolCalls.map((call, i) => {
3580
3622
  const originalArgs = call.args as Record<string, unknown>;
3581
3623
  let resolvedArgs = originalArgs;
3582
3624
  /**
@@ -3597,10 +3639,10 @@ export class ToolNode<T = any> extends RunnableCallable<T, T> {
3597
3639
  const options = {
3598
3640
  substituteIntentKey: this.toolDeclaresBusinessIntent(call.name),
3599
3641
  };
3600
- const { resolved, unresolved } =
3601
- preBatchSnapshot != null
3602
- ? preBatchSnapshot.resolve(originalArgs, options)
3603
- : registry.resolve(registryRunId, originalArgs, options);
3642
+ const { resolved, unresolved } = referenceView!.resolve(
3643
+ originalArgs,
3644
+ options
3645
+ );
3604
3646
  resolvedArgs = resolved as Record<string, unknown>;
3605
3647
  if (unresolved.length > 0 && call.id != null) {
3606
3648
  unresolvedByCallId.set(call.id, unresolved);
@@ -3643,18 +3685,62 @@ export class ToolNode<T = any> extends RunnableCallable<T, T> {
3643
3685
  errors: [] as string[],
3644
3686
  });
3645
3687
 
3688
+ const referenceFailures: typeof preToolCalls = [];
3689
+ const rejectReferences = (
3690
+ entry: (typeof preToolCalls)[number]
3691
+ ): boolean => {
3692
+ const error = this.unresolvedReferenceMessage(
3693
+ entry.call,
3694
+ {
3695
+ unresolved: unresolvedByCallId.get(entry.call.id ?? '') ?? [],
3696
+ },
3697
+ referenceView
3698
+ );
3699
+ if (error == null) return false;
3700
+ messageByCallId.set(entry.call.id ?? '', error);
3701
+ referenceFailures.push(entry);
3702
+ this.eagerEventToolExecutions?.delete(entry.call.id ?? '');
3703
+ postToolBatchEntryByCallId.set(entry.call.id ?? '', {
3704
+ toolName: entry.call.name,
3705
+ toolInput: entry.args,
3706
+ toolUseId: entry.call.id ?? '',
3707
+ stepId: entry.stepId,
3708
+ turn: this.toolUsageCount.get(entry.call.name) ?? 0,
3709
+ status: 'error',
3710
+ error: String(error.content),
3711
+ });
3712
+ return true;
3713
+ };
3714
+ preToolCalls = preToolCalls.filter((entry) => !rejectReferences(entry));
3715
+
3646
3716
  const hookRegistry = this.hookRegistry;
3647
3717
  const approvalReplaySessionId = getToolApprovalReplaySessionId(
3648
3718
  config,
3649
3719
  runId
3650
3720
  );
3651
- const replayOwner = getToolBatchReplayOwner(config, this.executingAgentId ?? this.agentId ?? '');
3652
- const approvalReviewEvidence = getToolApprovalReviewEvidence(config, replayOwner);
3721
+ const replayOwner = getToolBatchReplayOwner(
3722
+ config,
3723
+ this.executingAgentId ?? this.agentId ?? ''
3724
+ );
3725
+ const approvalReviewEvidence = getToolApprovalReviewEvidence(
3726
+ config,
3727
+ replayOwner
3728
+ );
3653
3729
  const checkpointPending = getCheckpointPendingApproval(config);
3654
- if (approvalReviewEvidence == null && checkpointPending != null &&
3655
- (checkpointPending.owner == null || checkpointPending.owner === replayOwner) &&
3656
- preToolCalls.some((entry) => getReviewedToolApproval(checkpointPending.payload, entry.call.id) != null)) {
3657
- throw new GraphInterrupt([{ id: checkpointPending.interruptId, value: checkpointPending.value }]);
3730
+ if (
3731
+ approvalReviewEvidence == null &&
3732
+ checkpointPending != null &&
3733
+ (checkpointPending.owner == null ||
3734
+ checkpointPending.owner === replayOwner) &&
3735
+ preToolCalls.some(
3736
+ (entry) =>
3737
+ getReviewedToolApproval(checkpointPending.payload, entry.call.id) !=
3738
+ null
3739
+ )
3740
+ ) {
3741
+ throw new GraphInterrupt([
3742
+ { id: checkpointPending.interruptId, value: checkpointPending.value },
3743
+ ]);
3658
3744
  }
3659
3745
  const hasPendingApproval = preToolCalls.some(
3660
3746
  (entry) =>
@@ -3699,6 +3785,15 @@ export class ToolNode<T = any> extends RunnableCallable<T, T> {
3699
3785
  }
3700
3786
  }
3701
3787
  }
3788
+ const referenceBaselines =
3789
+ referenceView == null
3790
+ ? undefined
3791
+ : new Map(
3792
+ preToolCalls.map((entry) => [
3793
+ entry,
3794
+ snapshotResolvedArgs(entry.args),
3795
+ ])
3796
+ );
3702
3797
  const preResults =
3703
3798
  hookRegistry == null
3704
3799
  ? preToolCalls.map(() => HOOK_FALLBACK)
@@ -3732,10 +3827,11 @@ export class ToolNode<T = any> extends RunnableCallable<T, T> {
3732
3827
  matchQuery: entry.call.name,
3733
3828
  onceReplayKey: approvalReplayKey,
3734
3829
  onceReplaySessionId: approvalReplaySessionId,
3735
- }).catch((): AggregatedHookResult =>
3736
- isBackgroundDenyMode(this.humanInTheLoop)
3737
- ? { ...HOOK_FALLBACK, hasHookFailures: true }
3738
- : HOOK_FALLBACK
3830
+ }).catch(
3831
+ (): AggregatedHookResult =>
3832
+ isBackgroundDenyMode(this.humanInTheLoop)
3833
+ ? { ...HOOK_FALLBACK, hasHookFailures: true }
3834
+ : HOOK_FALLBACK
3739
3835
  );
3740
3836
  })
3741
3837
  );
@@ -3844,29 +3940,14 @@ export class ToolNode<T = any> extends RunnableCallable<T, T> {
3844
3940
  deferredBlockedSideEffects.length = 0;
3845
3941
  };
3846
3942
 
3847
- /**
3848
- * Apply a hook-supplied or host-supplied input override to a pending
3849
- * entry, re-running the `{{tool<i>turn<n>}}` resolver so any new
3850
- * placeholders introduced by the override are substituted (and any
3851
- * formerly-unresolved refs cleared from the unresolved set).
3852
- *
3853
- * Mixed direct+event batches must use the pre-batch snapshot so a
3854
- * hook-introduced placeholder cannot accidentally resolve to a
3855
- * same-turn direct output that has just registered. Pure event
3856
- * batches don't have a snapshot and resolve against the live
3857
- * registry — safe because no event-side registrations have happened
3858
- * yet.
3859
- */
3943
+ /** Validate edits against the batch snapshot and detached input baseline. */
3860
3944
  const applyInputOverride = (
3861
3945
  entry: PendingEntry,
3862
3946
  nextArgs: Record<string, unknown>
3863
3947
  ): void => {
3864
3948
  if (registry != null) {
3865
- const view: ToolOutputResolveView = preBatchSnapshot ?? {
3866
- resolve: <T>(args: T, options?: ResolveOptions) =>
3867
- registry.resolve(registryRunId, args, options),
3868
- };
3869
- const { resolved, unresolved } = view.resolve(nextArgs, {
3949
+ const { resolved, unresolved } = referenceView!.resolve(nextArgs, {
3950
+ previouslyResolved: referenceBaselines?.get(entry),
3870
3951
  substituteIntentKey: this.toolDeclaresBusinessIntent(
3871
3952
  entry.call.name
3872
3953
  ),
@@ -3922,6 +4003,11 @@ export class ToolNode<T = any> extends RunnableCallable<T, T> {
3922
4003
  continue;
3923
4004
  }
3924
4005
 
4006
+ if (hookResult.updatedInput != null || referenceView != null) {
4007
+ applyInputOverride(entry, hookResult.updatedInput ?? entry.args);
4008
+ if (rejectReferences(entry)) continue;
4009
+ }
4010
+
3925
4011
  if (hookResult.decision === 'ask') {
3926
4012
  /**
3927
4013
  * HITL is OFF by default — hosts must explicitly opt in via
@@ -3954,9 +4040,7 @@ export class ToolNode<T = any> extends RunnableCallable<T, T> {
3954
4040
  * reviewer AND the post-approve execution would run with
3955
4041
  * the original args, silently dropping the hook's rewrite.
3956
4042
  */
3957
- if (hookResult.updatedInput != null) {
3958
- applyInputOverride(entry, hookResult.updatedInput);
3959
- } else {
4043
+ if (hookResult.updatedInput == null) {
3960
4044
  const reviewed = getReviewedToolApproval(
3961
4045
  approvalReviewEvidence?.payload,
3962
4046
  entry.call.id
@@ -3966,9 +4050,6 @@ export class ToolNode<T = any> extends RunnableCallable<T, T> {
3966
4050
  entry.call.name,
3967
4051
  reviewed.request.arguments
3968
4052
  );
3969
- if (entry.call.id != null) {
3970
- unresolvedByCallId.delete(entry.call.id);
3971
- }
3972
4053
  }
3973
4054
  }
3974
4055
  askEntries.push({
@@ -3979,9 +4060,6 @@ export class ToolNode<T = any> extends RunnableCallable<T, T> {
3979
4060
  continue;
3980
4061
  }
3981
4062
 
3982
- if (hookResult.updatedInput != null) {
3983
- applyInputOverride(entry, hookResult.updatedInput);
3984
- }
3985
4063
  const reviewedApproval = getReviewedToolApproval(
3986
4064
  approvalReviewEvidence?.payload,
3987
4065
  entry.call.id
@@ -3996,9 +4074,6 @@ export class ToolNode<T = any> extends RunnableCallable<T, T> {
3996
4074
  entry.call.name,
3997
4075
  reviewedApproval.request.arguments
3998
4076
  );
3999
- if (entry.call.id != null) {
4000
- unresolvedByCallId.delete(entry.call.id);
4001
- }
4002
4077
  }
4003
4078
  askEntries.push({
4004
4079
  entry,
@@ -4026,8 +4101,16 @@ export class ToolNode<T = any> extends RunnableCallable<T, T> {
4026
4101
  * consumed one-shot hooks replay their pending approval aggregate.
4027
4102
  */
4028
4103
  if (askEntries.length > 0) {
4104
+ if (referenceBaselines != null) {
4105
+ for (const { entry } of askEntries) {
4106
+ referenceBaselines.set(entry, snapshotResolvedArgs(entry.args));
4107
+ }
4108
+ }
4029
4109
  const payload = buildToolApprovalInterruptPayload(
4030
- askEntries, runId, this.executionContext, this.executingAgentId
4110
+ askEntries,
4111
+ runId,
4112
+ this.executionContext,
4113
+ this.executingAgentId
4031
4114
  );
4032
4115
 
4033
4116
  /**
@@ -4234,6 +4317,7 @@ export class ToolNode<T = any> extends RunnableCallable<T, T> {
4234
4317
  continue;
4235
4318
  }
4236
4319
  applyInputOverride(entry, updatedInput as Record<string, unknown>);
4320
+ if (rejectReferences(entry)) continue;
4237
4321
  approvedEntries.push(entry);
4238
4322
  continue;
4239
4323
  }
@@ -4287,6 +4371,15 @@ export class ToolNode<T = any> extends RunnableCallable<T, T> {
4287
4371
  approvedEntries.push(...preToolCalls);
4288
4372
  }
4289
4373
 
4374
+ for (const entry of referenceFailures) {
4375
+ await this.dispatchStepCompleted(
4376
+ entry.call.id ?? '',
4377
+ entry.call.name,
4378
+ entry.args,
4379
+ String(messageByCallId.get(entry.call.id ?? '')!.content),
4380
+ config
4381
+ );
4382
+ }
4290
4383
  const injected: BaseMessage[] = [];
4291
4384
 
4292
4385
  const batchIndexByCallId = new Map<string, number>();
@@ -4426,7 +4519,11 @@ export class ToolNode<T = any> extends RunnableCallable<T, T> {
4426
4519
  earlyCompletionDispatchedIds.add(result.toolCallId);
4427
4520
  receivedAtById.set(result.toolCallId, receivedAt);
4428
4521
  earlyCompletionDispatches.push(
4429
- this.dispatchEarlyToolCompletion({ ...result, received_at: receivedAt }, request, config).then(
4522
+ this.dispatchEarlyToolCompletion(
4523
+ { ...result, received_at: receivedAt },
4524
+ request,
4525
+ config
4526
+ ).then(
4430
4527
  (dispatched) => {
4431
4528
  if (!dispatched) {
4432
4529
  earlyCompletionDispatchedIds.delete(result.toolCallId);
@@ -4481,7 +4578,10 @@ export class ToolNode<T = any> extends RunnableCallable<T, T> {
4481
4578
  const receivedAt = Date.now();
4482
4579
  for (const result of results) {
4483
4580
  if (dispatchRequestById.has(result.toolCallId)) {
4484
- receivedAtById.set(result.toolCallId, result.received_at ?? receivedAt);
4581
+ receivedAtById.set(
4582
+ result.toolCallId,
4583
+ result.received_at ?? receivedAt
4584
+ );
4485
4585
  }
4486
4586
  }
4487
4587
  resultSettled = true;
@@ -4621,31 +4721,12 @@ export class ToolNode<T = any> extends RunnableCallable<T, T> {
4621
4721
  this.maxToolResultChars,
4622
4722
  config.signal
4623
4723
  );
4624
- /**
4625
- * Error results bypass registration but stamp the
4626
- * unresolved-refs hint into `additional_kwargs` so the lazy
4627
- * annotation transform surfaces it to the LLM at request
4628
- * time, letting the model self-correct when its reference
4629
- * key caused the failure. Persisted `content` stays clean.
4630
- */
4631
- const unresolved = unresolvedByCallId.get(result.toolCallId) ?? [];
4632
- const errorRefMeta =
4633
- unresolved.length > 0
4634
- ? this.recordOutputReference(
4635
- registryRunId,
4636
- contentString,
4637
- undefined,
4638
- unresolved
4639
- )
4640
- : undefined;
4724
+ /** Error results are never registered under a reference key. */
4641
4725
  toolMessage = new ToolMessage({
4642
4726
  status: 'error',
4643
4727
  content: contentString,
4644
4728
  name: toolName,
4645
4729
  tool_call_id: result.toolCallId,
4646
- ...(errorRefMeta != null && {
4647
- additional_kwargs: errorRefMeta as Record<string, unknown>,
4648
- }),
4649
4730
  });
4650
4731
 
4651
4732
  if (hasFailureHook) {
@@ -4749,12 +4830,10 @@ export class ToolNode<T = any> extends RunnableCallable<T, T> {
4749
4830
  }
4750
4831
  }
4751
4832
 
4752
- const unresolved = unresolvedByCallId.get(result.toolCallId) ?? [];
4753
4833
  const successRefMeta = this.recordOutputReference(
4754
4834
  registryRunId,
4755
4835
  stripCodeSessionFileSummary(registryRaw),
4756
- refKey,
4757
- unresolved
4836
+ refKey
4758
4837
  );
4759
4838
 
4760
4839
  toolMessage = new ToolMessage({
@@ -5570,6 +5649,8 @@ export class ToolNode<T = any> extends RunnableCallable<T, T> {
5570
5649
  batchScopeId,
5571
5650
  resumedReferenceState
5572
5651
  );
5652
+ const batchReferenceSnapshot =
5653
+ replayInputSnapshot ?? this.toolOutputRegistry?.snapshot(batchScopeId);
5573
5654
  referenceReplay.state =
5574
5655
  resumedReferenceState ??
5575
5656
  this.toolOutputRegistry?.snapshotState(batchScopeId);
@@ -5594,7 +5675,7 @@ export class ToolNode<T = any> extends RunnableCallable<T, T> {
5594
5675
  batchIndices: [0],
5595
5676
  turn,
5596
5677
  batchScopeId,
5597
- preBatchSnapshot: replayInputSnapshot,
5678
+ preBatchSnapshot: batchReferenceSnapshot,
5598
5679
  });
5599
5680
  }
5600
5681
  // Same per-batch sink the message-state branches use so
@@ -5625,7 +5706,7 @@ export class ToolNode<T = any> extends RunnableCallable<T, T> {
5625
5706
  batchIndex: 0,
5626
5707
  turn,
5627
5708
  batchScopeId,
5628
- preBatchSnapshot: replayInputSnapshot,
5709
+ preBatchSnapshot: batchReferenceSnapshot,
5629
5710
  resolvedArgsByCallId,
5630
5711
  codeSessionBaselineByCallId,
5631
5712
  errorOwnership,
@@ -5841,7 +5922,7 @@ export class ToolNode<T = any> extends RunnableCallable<T, T> {
5841
5922
  batchIndices: eventEntries.map((entry) => entry.batchIndex),
5842
5923
  turn,
5843
5924
  batchScopeId,
5844
- preBatchSnapshot: replayInputSnapshot,
5925
+ preBatchSnapshot: batchReferenceSnapshot,
5845
5926
  });
5846
5927
  }
5847
5928
 
@@ -5877,9 +5958,7 @@ export class ToolNode<T = any> extends RunnableCallable<T, T> {
5877
5958
  * cross-batch (against prior runs) without ever picking up
5878
5959
  * same-turn direct outputs.
5879
5960
  */
5880
- const preBatchSnapshot =
5881
- replayInputSnapshot ??
5882
- this.toolOutputRegistry?.snapshot(batchScopeId);
5961
+ const preBatchSnapshot = batchReferenceSnapshot;
5883
5962
  if (preBatchSnapshot != null) {
5884
5963
  for (const entry of eventEntries) {
5885
5964
  if (entry.call.id != null) {
@@ -6013,9 +6092,7 @@ export class ToolNode<T = any> extends RunnableCallable<T, T> {
6013
6092
  // the all-direct case so `Promise.all`-induced ordering can't
6014
6093
  // leak a sibling's just-registered output into a sister
6015
6094
  // call's args mid-await (Codex P1 #18).
6016
- const preBatchSnapshot =
6017
- replayInputSnapshot ??
6018
- this.toolOutputRegistry?.snapshot(batchScopeId);
6095
+ const preBatchSnapshot = batchReferenceSnapshot;
6019
6096
  const directAdditionalContexts: string[] = [];
6020
6097
  const approvalScopeCallIds = new Set(
6021
6098
  filteredCalls.flatMap((call) => (call.id == null ? [] : [call.id]))