@librechat/agents 3.4.3 → 3.4.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. package/dist/cjs/graphs/Graph.cjs +27 -14
  2. package/dist/cjs/graphs/Graph.cjs.map +1 -1
  3. package/dist/cjs/graphs/MultiAgentGraph.cjs +1 -1
  4. package/dist/cjs/instrumentation.cjs +3 -3
  5. package/dist/cjs/langfuse.cjs +3 -3
  6. package/dist/cjs/langfuseRuntimeScope.cjs +1 -1
  7. package/dist/cjs/langfuseToolOutputTracing.cjs +2 -2
  8. package/dist/cjs/main.cjs +5 -1
  9. package/dist/cjs/messages/assistantPhase.cjs +59 -0
  10. package/dist/cjs/messages/assistantPhase.cjs.map +1 -0
  11. package/dist/cjs/messages/index.cjs +1 -0
  12. package/dist/cjs/prompts/activityLabel.cjs +76 -0
  13. package/dist/cjs/prompts/activityLabel.cjs.map +1 -1
  14. package/dist/cjs/run.cjs +200 -10
  15. package/dist/cjs/run.cjs.map +1 -1
  16. package/dist/cjs/session/AgentSession.cjs +1 -1
  17. package/dist/cjs/stream.cjs +45 -8
  18. package/dist/cjs/stream.cjs.map +1 -1
  19. package/dist/cjs/tools/ToolNode.cjs +3 -3
  20. package/dist/cjs/tools/subagent/SubagentExecutor.cjs +81 -6
  21. package/dist/cjs/tools/subagent/SubagentExecutor.cjs.map +1 -1
  22. package/dist/cjs/utils/callbacks.cjs +8 -0
  23. package/dist/cjs/utils/callbacks.cjs.map +1 -1
  24. package/dist/esm/graphs/Graph.mjs +27 -14
  25. package/dist/esm/graphs/Graph.mjs.map +1 -1
  26. package/dist/esm/graphs/MultiAgentGraph.mjs +1 -1
  27. package/dist/esm/instrumentation.mjs +3 -3
  28. package/dist/esm/langfuse.mjs +3 -3
  29. package/dist/esm/langfuseRuntimeScope.mjs +1 -1
  30. package/dist/esm/langfuseToolOutputTracing.mjs +2 -2
  31. package/dist/esm/main.mjs +3 -2
  32. package/dist/esm/messages/assistantPhase.mjs +57 -0
  33. package/dist/esm/messages/assistantPhase.mjs.map +1 -0
  34. package/dist/esm/messages/index.mjs +1 -0
  35. package/dist/esm/prompts/activityLabel.mjs +74 -1
  36. package/dist/esm/prompts/activityLabel.mjs.map +1 -1
  37. package/dist/esm/run.mjs +202 -12
  38. package/dist/esm/run.mjs.map +1 -1
  39. package/dist/esm/session/AgentSession.mjs +1 -1
  40. package/dist/esm/stream.mjs +45 -8
  41. package/dist/esm/stream.mjs.map +1 -1
  42. package/dist/esm/tools/ToolNode.mjs +3 -3
  43. package/dist/esm/tools/subagent/SubagentExecutor.mjs +81 -6
  44. package/dist/esm/tools/subagent/SubagentExecutor.mjs.map +1 -1
  45. package/dist/esm/utils/callbacks.mjs +8 -1
  46. package/dist/esm/utils/callbacks.mjs.map +1 -1
  47. package/dist/types/messages/assistantPhase.d.ts +22 -0
  48. package/dist/types/messages/index.d.ts +1 -0
  49. package/dist/types/prompts/activityLabel.d.ts +21 -1
  50. package/dist/types/run.d.ts +15 -2
  51. package/dist/types/types/activityLabel.d.ts +63 -0
  52. package/dist/types/types/assistantPhase.d.ts +6 -0
  53. package/dist/types/types/graph.d.ts +8 -1
  54. package/dist/types/types/index.d.ts +1 -0
  55. package/dist/types/types/stream.d.ts +11 -0
  56. package/dist/types/utils/callbacks.d.ts +1 -0
  57. package/package.json +1 -1
  58. package/src/graphs/Graph.ts +33 -9
  59. package/src/graphs/__tests__/Graph.reasoning.test.ts +57 -0
  60. package/src/messages/assistantPhase.test.ts +75 -0
  61. package/src/messages/assistantPhase.ts +91 -0
  62. package/src/messages/index.ts +1 -0
  63. package/src/prompts/activityLabel.ts +177 -1
  64. package/src/run.ts +403 -21
  65. package/src/specs/activity-label-prompt.test.ts +123 -1
  66. package/src/specs/activity-phase-label.test.ts +306 -0
  67. package/src/stream.ts +69 -12
  68. package/src/tools/__tests__/SubagentExecutor.test.ts +436 -0
  69. package/src/tools/subagent/SubagentExecutor.ts +160 -8
  70. package/src/types/activityLabel.ts +65 -0
  71. package/src/types/assistantPhase.ts +6 -0
  72. package/src/types/graph.ts +8 -0
  73. package/src/types/index.ts +1 -0
  74. package/src/types/stream.ts +9 -0
  75. package/src/utils/callbacks.ts +21 -0
@@ -1 +1 @@
1
- {"version":3,"file":"Graph.cjs","names":["GraphNodeKeys","HandlerRegistry","isGoogleLike","getMessageId","ToolOutputReferenceRegistry","createLocalCodingToolBundle","createCloudflareCodingToolBundle","StreamLimitExceededError","resolveStreamLimits","AgentContext","resetIfNotEmpty","messagesStateReducer","resolveMaxSeals","joinKeys","convertMessagesToContent","shouldTraceToolNodeForLangfuse","createSchemaOnlyTools","CustomToolNode","createFakeStreamingLLM","extractToolDiscoveries","resolveLocalToolsForBinding","partitionAndMarkAnthropicToolCache","makeIsDeferred","resolvePromptCacheTtl","partitionAndMarkOpenRouterToolCache","supportsBedrockToolCache","partitionAndMarkBedrockToolCache","initializeModel","createPruneMessages","isThinkingEnabled","apportionTokenCounts","shouldTriggerSummarization","ToolMessage","isSyntheticProviderContextMessage","formatContentStrings","calculateMaxToolResultChars","projectToolStreamContentForProvider","projectToolCallInputs","calculateMaxToolCallInputChars","isAnthropicLike","AIMessageChunk","ContextOverflowError","ensureThinkingBlockInMessages","foldToolBlocksForToollessAgent","appendPredecessorHandoffCue","annotateMessagesForLLM","HumanMessage","getToolContentCharLength","compactToolContent","projectAnthropicArtifactContent","isOpenAILike","projectArtifactPayload","strictAlternationProviders","coalesceAdjacentUserTurns","sanitizeOrphanToolBlocks","addTailCacheControl","addBedrockTailCacheControl","resolveBedrockPromptCacheTtl","projectMessagesForProvider","sleep","safeDispatchCustomEvent","resolveLangfuseConfig","createLangfuseTraceMetadata","composeAbortSignals","STREAM_LIMIT_EPOCH_KEY","findCallback","isLangfuseCallbackHandler","createLangfuseHandler","hasToolOutputTracingConfig","resolveToolOutputTracingConfig","appendCallbacks","withLangfuseRuntimeScope","resolveLangfuseRuntimeScope","attemptInvoke","splitAtRecencyBoundary","getFallbackErrorContext","planContextOverflowRecovery","getBlindRecoveryBudget","translateRecoveryBudget","tryFallbackProviders","resolveServingModelId","removePredecessorHandoffCue","getFallbackOverflowCandidates","disposeLangfuseHandler","handleToolCalls","executeHooks","PREEMPT_BOUNDARY_HOOK_TIMEOUT_MS","convertInjectedMessages","normalizeSubagentConfigEntries","isGraphSubagentConfig","SubagentExecutor","DEFAULT_SUBAGENT_DESCRIPTION","RUN_BREAKER_SCOPE_CONFIG_KEY","buildSubagentToolParams","SUBAGENT_REPLAY_CONTROLLER","toolsCondition","Annotation","StateGraph","createSummarizeNode","START","END","serializeToolContentBounded"],"sources":["../../../src/graphs/Graph.ts"],"sourcesContent":["/* eslint-disable no-console */\nimport { v4 } from 'uuid';\nimport { nanoid } from 'nanoid';\nimport { tool } from '@langchain/core/tools';\nimport { ToolNode } from '@langchain/langgraph/prebuilt';\nimport { ContextOverflowError } from '@langchain/core/errors';\nimport { Runnable, RunnableConfig } from '@langchain/core/runnables';\nimport { START, END, StateGraph, Annotation } from '@langchain/langgraph';\nimport {\n ToolMessage,\n HumanMessage,\n AIMessageChunk,\n} from '@langchain/core/messages';\nimport type {\n UsageMetadata,\n BaseMessage,\n MessageContent,\n} from '@langchain/core/messages';\nimport type { ToolCall } from '@langchain/core/messages/tool';\nimport type {\n ReplayableSubagentTool,\n SubagentGraphResumeState,\n SubagentResumeManifest,\n SubagentToolNodeResumeState,\n SettledSubagentToolOutput,\n} from '@/tools/subagent/SubagentReplay';\nimport type {\n ResolvedStreamLimits,\n RunBreakerScope,\n StreamedToolCallArgTally,\n StreamDeltaEventTally,\n} from '@/llm/streamLimits';\nimport type {\n GraphFactory,\n GraphFactoryDependencies,\n} from '@/graphs/graphFactory';\nimport type { OverflowRecoveryPlan } from '@/llm/contextOverflowRecovery';\nimport type { FallbackErrorContext } from '@/llm/invoke';\nimport type { HookRegistry } from '@/hooks';\nimport type * as t from '@/types';\nimport {\n projectAnthropicArtifactContent,\n ensureThinkingBlockInMessages,\n foldToolBlocksForToollessAgent,\n convertMessagesToContent,\n sanitizeOrphanToolBlocks,\n extractToolDiscoveries,\n addBedrockTailCacheControl,\n projectArtifactPayload,\n formatContentStrings,\n CALIBRATION_RATIO_MAX,\n REPLY_PRIMER_TOKENS,\n createPruneMessages,\n projectToolCallInputs,\n calculateMaxToolCallInputChars,\n projectToolStreamContentForProvider,\n syncBudgetDerivedFields,\n addTailCacheControl,\n resolvePromptCacheTtl,\n resolveBedrockPromptCacheTtl,\n supportsBedrockToolCache,\n isSyntheticProviderContextMessage,\n getMessageId,\n makeIsDeferred,\n partitionAndMarkAnthropicToolCache,\n DEFAULT_RETAIN_RECENT_TURNS,\n splitAtRecencyBoundary,\n convertInjectedMessages,\n coalesceAdjacentUserTurns,\n strictAlternationProviders,\n appendPredecessorHandoffCue,\n removePredecessorHandoffCue,\n} from '@/messages';\nimport {\n resetIfNotEmpty,\n isAnthropicLike,\n isOpenAILike,\n isGoogleLike,\n apportionTokenCounts,\n calculateMaxToolResultChars,\n composeAbortSignals,\n joinKeys,\n sleep,\n} from '@/utils';\nimport {\n attemptInvoke,\n tryFallbackProviders,\n getFallbackErrorContext,\n getFallbackOverflowCandidates,\n projectMessagesForProvider,\n resolveServingModelId,\n} from '@/llm/invoke';\nimport {\n resolveStreamLimits,\n StreamLimitExceededError,\n sweepStaleStreamLimitEntries,\n STREAM_LIMIT_EPOCH_KEY,\n RUN_BREAKER_SCOPE_CONFIG_KEY,\n} from '@/llm/streamLimits';\nimport {\n DEFAULT_SUBAGENT_DESCRIPTION,\n SubagentExecutor,\n isGraphSubagentConfig,\n normalizeSubagentConfigEntries,\n} from '@/tools/subagent';\nimport {\n Constants,\n GraphNodeKeys,\n ContentTypes,\n GraphEvents,\n Providers,\n StepTypes,\n PREEMPT_BOUNDARY_HOOK_TIMEOUT_MS,\n} from '@/common';\nimport {\n createLangfuseHandler,\n createLangfuseTraceMetadata,\n disposeLangfuseHandler,\n isLangfuseCallbackHandler,\n} from '@/langfuse';\nimport {\n getBlindRecoveryBudget,\n planContextOverflowRecovery,\n translateRecoveryBudget,\n} from '@/llm/contextOverflowRecovery';\nimport {\n hasToolOutputTracingConfig,\n resolveLangfuseConfig,\n resolveToolOutputTracingConfig,\n} from '@/langfuseConfig';\nimport {\n compactToolContent,\n getToolContentCharLength,\n serializeToolContentBounded,\n} from '@/utils/toolContent';\nimport {\n annotateMessagesForLLM,\n ToolOutputReferenceRegistry,\n} from '@/tools/toolOutputReferences';\nimport {\n resolveLangfuseRuntimeScope,\n withLangfuseRuntimeScope,\n} from '@/langfuseRuntimeScope';\nimport {\n appendCallbacks,\n findCallback,\n type CallbackEntry,\n} from '@/utils/callbacks';\nimport { partitionAndMarkOpenRouterToolCache } from '@/llm/openrouter/toolCache';\nimport { ToolNode as CustomToolNode, toolsCondition } from '@/tools/ToolNode';\nimport { shouldTraceToolNodeForLangfuse } from '@/langfuseToolOutputTracing';\nimport { createLocalCodingToolBundle } from '@/tools/local/LocalCodingTools';\nimport { SUBAGENT_REPLAY_CONTROLLER } from '@/tools/subagent/SubagentReplay';\nimport { applyGraphRuntimeConfig } from '@/graphs/applyGraphRuntimeConfig';\nimport { partitionAndMarkBedrockToolCache } from '@/llm/bedrock/toolCache';\nimport { safeDispatchCustomEvent, emitAgentLog } from '@/utils/events';\nimport { createCloudflareCodingToolBundle } from '@/tools/cloudflare';\nimport { buildSubagentToolParams } from '@/tools/SubagentTool';\nimport { initializeLangfuseTracing } from '@/instrumentation';\nimport { shouldTriggerSummarization } from '@/summarization';\nimport { resolveLocalToolsForBinding } from '@/tools/local';\nimport { createSummarizeNode } from '@/summarization/node';\nimport { messagesStateReducer } from '@/messages/reducer';\nimport { createSchemaOnlyTools } from '@/tools/schema';\nimport { AgentContext } from '@/agents/AgentContext';\nimport { createFakeStreamingLLM } from '@/llm/fake';\nimport { handleToolCalls } from '@/tools/handlers';\nimport { isThinkingEnabled } from '@/llm/request';\nimport { resolveMaxSeals } from '@/llm/preempt';\nimport { initializeModel } from '@/llm/init';\nimport { HandlerRegistry } from '@/events';\nimport { ChatOpenAI } from '@/llm/openai';\nimport { executeHooks } from '@/hooks';\n\nconst { AGENT, TOOLS, SUMMARIZE } = GraphNodeKeys;\n\n/** What a `PreemptBoundary` drain resolved to. */\ntype PreemptBoundaryResult = {\n messages: BaseMessage[];\n /** A hook asked for no further model turn; the seal must not self-loop. */\n preventContinuation: boolean;\n};\n\nconst EMPTY_PREEMPT_BOUNDARY: PreemptBoundaryResult = {\n messages: [],\n preventContinuation: false,\n};\n\n/** Minimum relative variance before calibrated toolSchemaTokens overrides current value. */\nconst CALIBRATION_VARIANCE_THRESHOLD = 0.15;\n\nfunction createChildHandlerRegistry(\n source: HandlerRegistry | undefined\n): HandlerRegistry | undefined {\n const toolHandler = source?.getHandler(GraphEvents.ON_TOOL_EXECUTE);\n const updateHandler = source?.getHandler(GraphEvents.ON_SUBAGENT_UPDATE);\n if (toolHandler == null && updateHandler == null) {\n return undefined;\n }\n const registry = new HandlerRegistry();\n if (toolHandler != null) {\n registry.register(GraphEvents.ON_TOOL_EXECUTE, toolHandler);\n }\n if (updateHandler != null) {\n registry.register(GraphEvents.ON_SUBAGENT_UPDATE, updateHandler);\n }\n return registry;\n}\n\ntype ReasoningKey = 'reasoning_content' | 'reasoning';\ntype ReasoningSummary = { summary?: Array<{ text?: string }> };\ntype ReasoningDetail = { type?: string; text?: string };\n\nfunction getHandlerDispatchedEventKey(\n eventName: string,\n stepId: string\n): string {\n return `${eventName}:${stepId}`;\n}\n\nfunction getReasoningText(\n value: string | Partial<ReasoningSummary> | null | undefined\n): string | undefined {\n if (typeof value === 'string') {\n return value !== '' ? value : undefined;\n }\n const summaryText = value?.summary\n ?.map((summary) => summary.text ?? '')\n .filter((text) => text !== '')\n .join('');\n return summaryText != null && summaryText !== '' ? summaryText : undefined;\n}\n\nfunction getReasoningDetailsText(\n value: ReasoningDetail[] | null | undefined\n): string | undefined {\n if (!Array.isArray(value)) {\n return undefined;\n }\n const reasoningText = value\n .filter((detail) => detail.type === 'reasoning.text')\n .map((detail) => detail.text ?? '')\n .filter((text) => text !== '')\n .join('');\n return reasoningText !== '' ? reasoningText : undefined;\n}\n\nfunction getResponseReasoningContent({\n responseMessage,\n reasoningKey,\n}: {\n responseMessage?: Partial<AIMessageChunk>;\n reasoningKey: ReasoningKey;\n}): string | undefined {\n const additionalKwargs = responseMessage?.additional_kwargs;\n if (additionalKwargs == null) {\n return undefined;\n }\n\n const keyedReasoning = getReasoningText(\n additionalKwargs[reasoningKey] as\n | string\n | Partial<ReasoningSummary>\n | null\n | undefined\n );\n if (keyedReasoning != null) {\n return keyedReasoning;\n }\n\n const reasoningContent = getReasoningText(\n additionalKwargs.reasoning_content as\n | string\n | Partial<ReasoningSummary>\n | null\n | undefined\n );\n if (reasoningContent != null) {\n return reasoningContent;\n }\n\n const reasoning = getReasoningText(\n additionalKwargs.reasoning as\n | string\n | Partial<ReasoningSummary>\n | null\n | undefined\n );\n if (reasoning != null) {\n return reasoning;\n }\n\n return getReasoningDetailsText(\n additionalKwargs.reasoning_details as ReasoningDetail[] | null | undefined\n );\n}\n\nfunction isTextMessageContentPart(\n contentPart: MessageContent[number] | t.MessageContentComplex\n): boolean {\n return (\n typeof contentPart === 'object' &&\n 'type' in contentPart &&\n typeof contentPart.type === 'string' &&\n contentPart.type.startsWith('text')\n );\n}\n\nfunction isGoogleServerSideToolMessageContentPart(\n contentPart: MessageContent[number] | t.MessageContentComplex\n): boolean {\n return (\n typeof contentPart === 'object' &&\n 'type' in contentPart &&\n (contentPart.type === 'toolCall' || contentPart.type === 'toolResponse')\n );\n}\n\nfunction hasGoogleServerSideToolDeltaContent(\n provider: Providers | undefined,\n content: t.MessageDelta['content']\n): content is t.MessageContentComplex[] {\n return (\n isGoogleLike(provider) &&\n Array.isArray(content) &&\n content.some((contentPart) =>\n isGoogleServerSideToolMessageContentPart(contentPart)\n )\n );\n}\n\nfunction getMessageDeltaContent(\n provider: Providers | undefined,\n content: MessageContent | undefined\n): t.MessageDelta['content'] | undefined {\n if (content == null) {\n return undefined;\n }\n if (typeof content === 'string') {\n return content !== ''\n ? [{ type: ContentTypes.TEXT, text: content }]\n : undefined;\n }\n if (content.length === 0) {\n return undefined;\n }\n\n const hasGoogleServerSideToolPart =\n isGoogleLike(provider) &&\n content.some((contentPart) =>\n isGoogleServerSideToolMessageContentPart(contentPart)\n );\n if (content.every((contentPart) => isTextMessageContentPart(contentPart))) {\n return content as t.MessageDelta['content'];\n }\n if (!hasGoogleServerSideToolPart) {\n return undefined;\n }\n const messageContent = content.filter(\n (contentPart) =>\n isTextMessageContentPart(contentPart) ||\n isGoogleServerSideToolMessageContentPart(contentPart)\n );\n return messageContent.length > 0\n ? (messageContent as t.MessageDelta['content'])\n : undefined;\n}\n\nfunction hasTextDeltaContent(\n content: t.MessageDelta['content'] | undefined\n): boolean {\n if (content == null) {\n return false;\n }\n return content.some((contentPart) => {\n if (contentPart.type?.startsWith(ContentTypes.TEXT) !== true) {\n return false;\n }\n const text = (contentPart as Partial<{ text: string }>).text;\n return typeof text === 'string' && text !== '';\n });\n}\n\nfunction hasReasoningDeltaContent(\n content: t.ReasoningDelta['content'] | undefined\n): boolean {\n if (content == null) {\n return false;\n }\n return content.some(\n (contentPart) =>\n contentPart.type === ContentTypes.THINK && contentPart.think !== ''\n );\n}\n\nfunction getCurrentStepIds({\n graph,\n metadata,\n}: {\n graph: Graph<t.BaseGraphState>;\n metadata: Record<string, unknown>;\n}): string[] {\n const baseStepKey = graph.getStepBaseKey(metadata);\n const currentStepIds: string[] = [];\n for (const [stepKey, stepIds] of graph.stepKeyIds) {\n if (stepKey !== baseStepKey && !stepKey.startsWith(`${baseStepKey}_`)) {\n continue;\n }\n currentStepIds.push(...stepIds);\n }\n return currentStepIds;\n}\n\nfunction hasCurrentTextDeltaStep({\n graph,\n metadata,\n}: {\n graph: Graph<t.BaseGraphState>;\n metadata: Record<string, unknown>;\n}): boolean {\n return getCurrentStepIds({ graph, metadata }).some((stepId) =>\n graph.messageStepHasTextDeltas.has(stepId)\n );\n}\n\nfunction hasCurrentReasoningDeltaStep({\n graph,\n metadata,\n}: {\n graph: Graph<t.BaseGraphState>;\n metadata: Record<string, unknown>;\n}): boolean {\n return getCurrentStepIds({ graph, metadata }).some((stepId) =>\n graph.reasoningStepHasDeltas.has(stepId)\n );\n}\n\nfunction clearCurrentDeltaStepMarkers({\n graph,\n metadata,\n}: {\n graph: Graph<t.BaseGraphState>;\n metadata: Record<string, unknown>;\n}): void {\n for (const stepId of getCurrentStepIds({ graph, metadata })) {\n graph.messageStepHasTextDeltas.delete(stepId);\n graph.reasoningStepHasDeltas.delete(stepId);\n }\n}\n\n/**\n * The completion allowance the caller configured, under whichever key the\n * provider's client uses. Providers count it against the same ceiling as the\n * prompt, so overflow recovery has to reserve it when the error did not\n * itemize the total.\n */\nfunction getConfiguredCompletionTokens(\n clientOptions: t.ClientOptions | undefined\n): number | undefined {\n const options = clientOptions as\n | { maxTokens?: unknown; maxOutputTokens?: unknown }\n | undefined;\n for (const value of [options?.maxTokens, options?.maxOutputTokens]) {\n if (typeof value === 'number' && Number.isFinite(value) && value > 0) {\n return value;\n }\n }\n return undefined;\n}\n\n/**\n * Our own estimate of the prompt that was actually sent, derived from the\n * pre-invoke usage snapshot. Used to corroborate ambiguous provider errors\n * and to measure how far our token accounting sits from the provider's.\n */\nfunction getEstimatedPromptTokens(\n contextUsage: t.ContextUsageEvent | null\n): number | undefined {\n const budget = contextUsage?.contextBudget;\n const remaining = contextUsage?.remainingContextTokens;\n if (\n budget == null ||\n remaining == null ||\n !Number.isFinite(budget) ||\n !Number.isFinite(remaining)\n ) {\n return undefined;\n }\n const used = budget - remaining;\n return used > 0 ? used : undefined;\n}\n\nfunction minDefined(\n left: number | undefined,\n right: number | undefined\n): number | undefined {\n if (left == null) {\n return right;\n }\n if (right == null) {\n return left;\n }\n return Math.min(left, right);\n}\n\nasync function dispatchMessageCreationStep({\n graph,\n stepKey,\n messageId,\n metadata,\n}: {\n graph: Graph<t.BaseGraphState>;\n stepKey: string;\n messageId: string;\n metadata: Record<string, unknown>;\n}): Promise<string> {\n await graph.dispatchRunStep(\n stepKey,\n {\n type: StepTypes.MESSAGE_CREATION,\n message_creation: { message_id: messageId },\n },\n metadata\n );\n return graph.getStepIdByKey(stepKey);\n}\n\nasync function dispatchTextMessageContent({\n graph,\n stepKey,\n provider,\n content,\n metadata,\n}: {\n graph: Graph<t.BaseGraphState>;\n stepKey: string;\n provider?: Providers;\n content: t.MessageDelta['content'];\n metadata: Record<string, unknown>;\n}): Promise<boolean> {\n const messageId = getMessageId(stepKey, graph) ?? '';\n if (!messageId) {\n return false;\n }\n if (hasGoogleServerSideToolDeltaContent(provider, content)) {\n for (const contentPart of content) {\n const stepId = await dispatchMessageCreationStep({\n graph,\n stepKey,\n messageId,\n metadata,\n });\n await graph.dispatchMessageDelta(\n stepId,\n { content: [contentPart] },\n metadata\n );\n }\n return true;\n }\n const stepId = await dispatchMessageCreationStep({\n graph,\n stepKey,\n messageId,\n metadata,\n });\n await graph.dispatchMessageDelta(stepId, { content }, metadata);\n return true;\n}\n\nasync function dispatchReasoningContent({\n graph,\n agentContext,\n reasoningContent,\n metadata,\n}: {\n graph: Graph<t.BaseGraphState>;\n agentContext: AgentContext;\n reasoningContent: string;\n metadata: Record<string, unknown>;\n}): Promise<boolean> {\n const previousTokenType = agentContext.currentTokenType;\n const previousTokenTypeSwitch = agentContext.tokenTypeSwitch;\n const previousTransitionCount = agentContext.reasoningTransitionCount;\n\n agentContext.currentTokenType = ContentTypes.THINK;\n agentContext.tokenTypeSwitch = 'reasoning';\n\n const stepKey = graph.getStepKey(metadata);\n const messageId = getMessageId(stepKey, graph) ?? '';\n if (!messageId) {\n agentContext.currentTokenType = previousTokenType;\n agentContext.tokenTypeSwitch = previousTokenTypeSwitch;\n agentContext.reasoningTransitionCount = previousTransitionCount;\n return false;\n }\n\n await graph.dispatchRunStep(\n stepKey,\n {\n type: StepTypes.MESSAGE_CREATION,\n message_creation: { message_id: messageId },\n },\n metadata\n );\n const stepId = graph.getStepIdByKey(stepKey);\n await graph.dispatchReasoningDelta(\n stepId,\n {\n content: [{ type: ContentTypes.THINK, think: reasoningContent }],\n },\n metadata\n );\n return true;\n}\n\nfunction markPostReasoningContent(agentContext: AgentContext): void {\n if (\n agentContext.tokenTypeSwitch !== 'reasoning' ||\n agentContext.currentTokenType === ContentTypes.TEXT\n ) {\n return;\n }\n agentContext.currentTokenType = ContentTypes.TEXT;\n agentContext.tokenTypeSwitch = 'content';\n agentContext.reasoningTransitionCount++;\n}\n\nfunction getDispatchableFinalReasoningContent({\n agentContext,\n responseReasoningContent,\n hasStreamedTextDeltaStep,\n hasStreamedReasoningDeltaStep,\n}: {\n agentContext: AgentContext;\n responseReasoningContent: string | undefined;\n hasStreamedTextDeltaStep: boolean;\n hasStreamedReasoningDeltaStep: boolean;\n}): string | undefined {\n if (responseReasoningContent == null || hasStreamedReasoningDeltaStep) {\n return undefined;\n }\n if (\n agentContext.provider === Providers.OPENROUTER &&\n hasStreamedTextDeltaStep\n ) {\n return undefined;\n }\n return responseReasoningContent;\n}\n\nexport abstract class Graph<\n T extends t.BaseGraphState = t.BaseGraphState,\n _TNodeName extends string = string,\n> {\n abstract resetValues(keepContent?: boolean, checkpointScope?: string): void;\n restoreCheckpointMessages(\n _messages: BaseMessage[],\n _pendingMessages?: BaseMessage[]\n ): void {}\n abstract initializeTools({\n currentTools,\n currentToolMap,\n }: {\n currentTools?: t.GraphTools;\n currentToolMap?: t.ToolMap;\n }): CustomToolNode<T> | ToolNode<T>;\n abstract getRunMessages(): BaseMessage[] | undefined;\n /** Returns a snapshot of deferred tools discovered by this graph. */\n getDiscoveredTools(_agentId?: string): string[] {\n return [];\n }\n abstract getContentParts(): t.MessageContentComplex[] | undefined;\n abstract generateStepId(stepKey: string): [string, number];\n abstract getKeyList(\n metadata: Record<string, unknown> | undefined\n ): (string | number | undefined)[];\n abstract getStepBaseKey(\n metadata: Record<string, unknown> | undefined\n ): string;\n abstract getStepKey(metadata: Record<string, unknown> | undefined): string;\n abstract checkKeyList(keyList: (string | number | undefined)[]): boolean;\n abstract getStepIdByKey(stepKey: string, index?: number): string;\n abstract getRunStep(stepId: string): t.RunStep | undefined;\n abstract dispatchRunStep(\n stepKey: string,\n stepDetails: t.StepDetails,\n metadata?: Record<string, unknown>\n ): Promise<string>;\n abstract dispatchRunStepDelta(\n id: string,\n delta: t.ToolCallDelta,\n metadata?: Record<string, unknown>\n ): Promise<void>;\n abstract dispatchMessageDelta(\n id: string,\n delta: t.MessageDelta,\n metadata?: Record<string, unknown>\n ): Promise<void>;\n abstract dispatchReasoningDelta(\n stepId: string,\n delta: t.ReasoningDelta,\n metadata?: Record<string, unknown>\n ): Promise<void>;\n abstract createCallModel(\n agentId?: string,\n currentModel?: t.ChatModel\n ): (\n state: t.AgentSubgraphState,\n config?: RunnableConfig\n ) => Promise<Partial<t.AgentSubgraphState>>;\n messageStepHasTextDeltas: Set<string> = new Set();\n messageStepHasToolCalls: Map<string, boolean> = new Map();\n messageIdsByStepKey: Map<string, string> = new Map();\n prelimMessageIdsByStepKey: Map<string, string> = new Map();\n config: RunnableConfig | undefined;\n contentData: t.RunStep[] = [];\n stepKeyIds: Map<string, string[]> = new Map<string, string[]>();\n contentIndexMap: Map<string, number> = new Map();\n toolCallStepIds: Map<string, string> = new Map();\n /**\n * Step IDs dispatched through the handler registry during this run.\n * Event echo suppression is tracked separately so repeated deltas for\n * the same step are scoped to the active custom event dispatch.\n */\n handlerDispatchedStepIds: Set<string> = new Set();\n reasoningStepHasDeltas: Set<string> = new Set();\n protected handlerDispatchedEventCounts: Map<string, number> = new Map();\n signal?: AbortSignal;\n /**\n * The abort signal the CALLER handed to the current `processStream` call,\n * assigned unconditionally — including back to `undefined` — on every call.\n *\n * Kept separate from {@link signal} on purpose. That field is construction\n * state with its own consumers (model-call config, subagent parentSignal),\n * so adopting a per-call signal into it would leak one call's controller\n * into the next — `clearHeavyState()` is skipped on HITL interrupts, so a\n * host that aborts a finished request's controller would poison the resumed\n * run's model calls and boundary drains with an already-aborted signal.\n * Boundary dispatch composes the two instead; see\n * `StandardGraph.dispatchPreemptBoundary`.\n */\n callerSignal?: AbortSignal;\n /** Set of invoked tool call IDs from non-message run steps completed mid-run, if any */\n invokedToolIds?: Set<string>;\n handlerRegistry: HandlerRegistry | undefined;\n /** Host registry retained only for forwarding tools from nested child graphs. */\n protected parentToolHandlerRegistry: HandlerRegistry | undefined;\n /**\n * True when event-driven tool execution can be routed through callbacks even\n * though this graph intentionally does not own the full handler registry.\n * Self-spawned subagent graphs use this shape: their callback forwarder sends\n * `ON_TOOL_EXECUTE` to the parent's handler, while child run-step events stay\n * wrapped as `ON_SUBAGENT_UPDATE` instead of leaking as parent events.\n */\n eventToolExecutionAvailable: boolean = false;\n hookRegistry: HookRegistry | undefined;\n /**\n * Run-scoped HITL configuration. When `humanInTheLoop?.enabled` is\n * `true`, `ToolNode` raises a real `interrupt()` for `PreToolUse`\n * `ask` decisions instead of treating them as a synchronous deny.\n * Threaded from `RunConfig.humanInTheLoop`.\n */\n humanInTheLoop: t.HumanInTheLoopConfig | undefined;\n /**\n * Run-scoped config for the tool output reference registry. Threaded\n * from `RunConfig.toolOutputReferences` down into every ToolNode this\n * graph compiles.\n */\n toolOutputReferences: t.ToolOutputReferencesConfig | undefined;\n /**\n * Run-scoped Langfuse defaults. Per-agent config wins when present.\n */\n langfuse: t.LangfuseConfig | undefined;\n /**\n * Run-scoped opt-in for eager event-driven tool execution. The stream\n * handler may prestart eligible event-driven tools; ToolNode later\n * consumes the settled promises while preserving final ToolMessage order.\n */\n eagerEventToolExecution: t.EagerEventToolExecutionConfig | undefined;\n codeSessionToolNames: string[] | undefined;\n /**\n * Run-scoped names of tools whose in-process body may raise a LangGraph\n * `interrupt()` (e.g. `ask_user_question`). Threaded from\n * `RunConfig.interruptingToolNames` into every ToolNode this graph\n * compiles so a mid-batch interrupt cannot double-execute non-idempotent\n * siblings on resume. See {@link t.ToolNodeOptions.interruptingToolNames}.\n */\n interruptingToolNames: string[] | undefined;\n eagerEventToolExecutions: Map<string, t.EagerEventToolExecution> = new Map();\n eagerEventToolUsageCount: Map<string, number> = new Map();\n private eagerEventToolUsageCountsByAgentId: Map<string, Map<string, number>> =\n new Map();\n eagerEventToolCallChunks: Map<string, t.EagerEventToolCallChunkState> =\n new Map();\n /**\n * Per-run eager prestart circuit breaker, shared by reference with every\n * ToolNode this graph compiles. When a prestarted execution's args turn\n * out to differ from the final request, ToolNode records the tool name\n * here and the stream handler stops prestarting that tool for the rest of\n * the run — the retry then executes normally instead of re-diverging in a\n * loop (LibreChat#14371).\n */\n eagerEventToolSuppressions: Set<string> = new Set();\n /**\n * Run-scoped execution backend for built-in code tools. Defaults to the\n * remote Code API sandbox when unset.\n */\n toolExecution: t.ToolExecutionConfig | undefined;\n /**\n * Shared registry instance used by every ToolNode compiled from this\n * graph. Lazily constructed on first access so multi-agent graphs\n * produce one registry per run (not one per agent), letting cross-\n * agent `{{tool<i>turn<n>}}` substitutions resolve.\n */\n private _toolOutputRegistry?: ToolOutputReferenceRegistry;\n /**\n * Tool session contexts for automatic state persistence across tool invocations.\n * Keyed by tool name (e.g., Constants.EXECUTE_CODE).\n * Currently supports code execution session tracking (session_id, files).\n */\n sessions: t.ToolSessionMap = new Map();\n\n /**\n * Clears heavy references to allow GC to reclaim memory held by\n * LangGraph's internal config / AsyncLocalStorage RunTree chain.\n * Call after a run completes and content has been extracted.\n */\n clearHeavyState(): void {\n this.config = undefined;\n this.signal = undefined;\n this.callerSignal = undefined;\n this.contentData = [];\n this.contentIndexMap = new Map();\n this.stepKeyIds = new Map();\n this.toolCallStepIds.clear();\n this.messageIdsByStepKey = new Map();\n this.messageStepHasTextDeltas = new Set();\n this.reasoningStepHasDeltas = new Set();\n this.messageStepHasToolCalls = new Map();\n this.prelimMessageIdsByStepKey = new Map();\n this.invokedToolIds = undefined;\n this.handlerRegistry = undefined;\n this.parentToolHandlerRegistry = undefined;\n this.hookRegistry = undefined;\n this.humanInTheLoop = undefined;\n this.toolOutputReferences = undefined;\n this.eagerEventToolExecution = undefined;\n this.codeSessionToolNames = undefined;\n this.interruptingToolNames = undefined;\n this.eagerEventToolExecutions.clear();\n this.clearEagerEventToolUsageCounts();\n this.eagerEventToolCallChunks.clear();\n this.eagerEventToolSuppressions.clear();\n this.toolExecution = undefined;\n this.handlerDispatchedEventCounts.clear();\n /**\n * ToolNodes compiled from this graph captured the registry\n * instance at construction time, so simply dropping the Graph's\n * own reference would leave their captured reference — and every\n * stored `tool<i>turn<n>` entry, plus up to `maxTotalSize` of raw\n * output — alive across subsequent `processStream()` calls. Wipe\n * the registry's contents first so subsequent runs start fresh.\n */\n this._toolOutputRegistry?.clear();\n this._toolOutputRegistry = undefined;\n // NB: `_fileCheckpointer` is intentionally NOT cleared here.\n // `Run.processStream()` calls `clearHeavyState()` in its\n // finally block on natural-completion / error paths — exactly\n // when the host is most likely to want `Run.rewindFiles()` (for\n // rollback after a failed batch). Per-Run isolation is already\n // automatic because each `Run.create()` constructs a brand-new\n // Graph instance, so the next Run gets its own checkpointer\n // without us needing to reset this field. Codex P1 #32: pre-fix\n // the checkpointer was nulled before the caller could reach it.\n // Flush each compiled ToolNode's direct-path turn cache so it\n // doesn't leak across Runs (Codex P2 #33). The cache survives\n // `run()` re-entry by design (resume-stable), but end-of-Run\n // is the right point to reset it. Retain the registrations because\n // the compiled workflow can be reused for later Runs; compilation\n // will not register these instances again.\n for (const node of this._compiledToolNodes) {\n node.clearDirectPathTurns();\n }\n // Subagent executors are likewise compiled once and reused. Clear\n // their per-Run state without dropping the registrations needed by\n // subsequent cleanup cycles.\n for (const executor of this._subagentExecutors) {\n executor.clearHeavyState();\n }\n this.sessions.clear();\n }\n\n getEagerEventToolUsageCount(agentId?: string): Map<string, number> {\n if (agentId == null || agentId === '') {\n return this.eagerEventToolUsageCount;\n }\n let usageCount = this.eagerEventToolUsageCountsByAgentId.get(agentId);\n if (usageCount == null) {\n usageCount = new Map<string, number>();\n this.eagerEventToolUsageCountsByAgentId.set(agentId, usageCount);\n }\n return usageCount;\n }\n\n protected clearEagerEventToolUsageCounts(): void {\n this.eagerEventToolUsageCount.clear();\n for (const usageCount of this.eagerEventToolUsageCountsByAgentId.values()) {\n usageCount.clear();\n }\n }\n\n markHandlerDispatchedEvent(eventName: string, stepId: string): () => void {\n const key = getHandlerDispatchedEventKey(eventName, stepId);\n this.handlerDispatchedEventCounts.set(\n key,\n (this.handlerDispatchedEventCounts.get(key) ?? 0) + 1\n );\n return () => {\n const count = this.handlerDispatchedEventCounts.get(key) ?? 0;\n if (count <= 1) {\n this.handlerDispatchedEventCounts.delete(key);\n return;\n }\n this.handlerDispatchedEventCounts.set(key, count - 1);\n };\n }\n\n hasHandlerDispatchedEvent(eventName: string, stepId: string): boolean {\n const key = getHandlerDispatchedEventKey(eventName, stepId);\n return (this.handlerDispatchedEventCounts.get(key) ?? 0) > 0;\n }\n\n /**\n * Subclass hook to register a freshly compiled ToolNode so\n * `clearHeavyState` can flush its per-Run direct-path turn cache\n * at end-of-Run. Internal — called from `initializeTools` in the\n * concrete graph subclasses.\n */\n protected registerCompiledToolNode(node: {\n clearDirectPathTurns(): void;\n createSubagentResumeState(): SubagentToolNodeResumeState;\n restoreSubagentResumeState(state: SubagentToolNodeResumeState): void;\n }): void {\n this._compiledToolNodes.add(node);\n }\n\n protected registerSubagentExecutor(executor: SubagentExecutor): void {\n this._subagentExecutors.add(executor);\n }\n\n protected resetSubagentCheckpointThreadIds(): void {\n for (const executor of this._subagentExecutors) {\n executor.resetCheckpointThreadIds();\n }\n }\n\n getChildCheckpointThreadIds(): string[] {\n const threadIds = new Set<string>();\n for (const executor of this._subagentExecutors) {\n for (const threadId of executor.getChildCheckpointThreadIds()) {\n threadIds.add(threadId);\n }\n }\n return [...threadIds];\n }\n\n createSubagentResumeState(runId: string): SubagentGraphResumeState {\n return {\n toolCallSteps: [...this.toolCallStepIds].map(([toolCallId, stepId]) => ({\n toolCallId,\n stepId,\n })),\n toolSessions: [...this.sessions].map(([toolName, context]) => ({\n toolName,\n context: {\n ...context,\n ...(context.files == null\n ? {}\n : { files: context.files.map((file) => ({ ...file })) }),\n },\n })),\n toolNodes: [...this._compiledToolNodes].map((node) =>\n node.createSubagentResumeState()\n ),\n eagerToolUsage: [\n {\n agentId: '',\n toolUsageCounts: [...this.eagerEventToolUsageCount].map(\n ([toolName, count]) => ({ toolName, count })\n ),\n },\n ...[...this.eagerEventToolUsageCountsByAgentId].map(\n ([agentId, usageCounts]) => ({\n agentId,\n toolUsageCounts: [...usageCounts].map(([toolName, count]) => ({\n toolName,\n count,\n })),\n })\n ),\n ],\n eagerToolSuppressions: [...this.eagerEventToolSuppressions],\n ...(this._toolOutputRegistry == null\n ? {}\n : {\n toolOutputReferences: this._toolOutputRegistry.snapshotState(runId),\n }),\n };\n }\n\n restoreSubagentResumeState(\n state: SubagentGraphResumeState,\n runId: string\n ): void {\n const toolNodesByKey = new Map(\n [...this._compiledToolNodes].map((node) => {\n const nodeState = node.createSubagentResumeState();\n return [nodeState.stateKey, node] as const;\n })\n );\n if (toolNodesByKey.size !== state.toolNodes.length) {\n throw new Error('Cannot restore changed subagent tool topology.');\n }\n for (const nodeState of state.toolNodes) {\n if (!toolNodesByKey.has(nodeState.stateKey)) {\n throw new Error(\n `Cannot restore subagent tool state for \"${nodeState.stateKey}\".`\n );\n }\n }\n const registry =\n state.toolOutputReferences == null\n ? undefined\n : this.getOrCreateToolOutputRegistry();\n if (state.toolOutputReferences != null && registry == null) {\n throw new Error('Cannot restore disabled tool output references.');\n }\n\n this.toolCallStepIds.clear();\n for (const { toolCallId, stepId } of state.toolCallSteps) {\n this.toolCallStepIds.set(toolCallId, stepId);\n }\n this.sessions.clear();\n for (const { toolName, context } of state.toolSessions) {\n this.sessions.set(toolName, {\n ...context,\n ...(context.files == null\n ? {}\n : { files: context.files.map((file) => ({ ...file })) }),\n });\n }\n for (const nodeState of state.toolNodes) {\n const node = toolNodesByKey.get(nodeState.stateKey)!;\n node.restoreSubagentResumeState(nodeState);\n }\n this.clearEagerEventToolUsageCounts();\n for (const usageState of state.eagerToolUsage) {\n const usageCounts = this.getEagerEventToolUsageCount(usageState.agentId);\n for (const { toolName, count } of usageState.toolUsageCounts) {\n usageCounts.set(toolName, count);\n }\n }\n this.eagerEventToolSuppressions.clear();\n for (const toolName of state.eagerToolSuppressions) {\n this.eagerEventToolSuppressions.add(toolName);\n }\n if (state.toolOutputReferences != null && registry != null) {\n registry.restoreState(runId, state.toolOutputReferences);\n }\n }\n\n /**\n * Returns the shared `ToolOutputReferenceRegistry` for this run,\n * constructing it on first access. Returns `undefined` when the\n * feature is disabled. All ToolNodes compiled from this graph share\n * this single instance so cross-agent `{{…}}` references resolve.\n *\n * @internal Public so `attemptInvoke` can read it through the typed\n * `InvokeContext` and project ToolMessages into LLM-facing annotated\n * copies right before each provider call (see\n * `annotateMessagesForLLM`). Host code should not call this directly\n * — registry mutations outside the ToolNode lifecycle break the\n * partitioning, eviction, and turn-counter invariants.\n */\n public getOrCreateToolOutputRegistry():\n | ToolOutputReferenceRegistry\n | undefined {\n if (this.toolOutputReferences?.enabled !== true) {\n return undefined;\n }\n if (this._toolOutputRegistry == null) {\n this._toolOutputRegistry = new ToolOutputReferenceRegistry({\n maxOutputSize: this.toolOutputReferences.maxOutputSize,\n maxTotalSize: this.toolOutputReferences.maxTotalSize,\n });\n }\n return this._toolOutputRegistry;\n }\n\n /**\n * Single per-Run file checkpointer shared across every ToolNode the\n * graph compiles. Lazily constructed when\n * `toolExecution.local.fileCheckpointing === true` or\n * `toolExecution.cloudflare.fileCheckpointing === true` so\n * multi-agent graphs see ONE snapshot store, not one-per-agent.\n * Returns undefined when checkpointing is disabled or a supported\n * coding-tool engine isn't selected. Exposed via\n * `Run.getFileCheckpointer()` / `Run.rewindFiles()`.\n */\n private _fileCheckpointer?: t.LocalFileCheckpointer;\n /**\n * ToolNodes compiled into this Graph's workflow. Tracked so\n * `clearHeavyState()` can flush their per-Run direct-path turn\n * cache (`directPathTurns`) at end-of-Run — that map intentionally\n * survives `run()` re-entry (resume-stable per Codex P2 #30) but\n * would otherwise grow linearly with tool calls and could collide\n * across Runs if a provider reuses call ids (Codex P2 #33).\n */\n private _compiledToolNodes: Set<{\n clearDirectPathTurns(): void;\n createSubagentResumeState(): SubagentToolNodeResumeState;\n restoreSubagentResumeState(state: SubagentToolNodeResumeState): void;\n }> = new Set();\n private _subagentExecutors = new Set<SubagentExecutor>();\n public getOrCreateFileCheckpointer(): t.LocalFileCheckpointer | undefined {\n // Return the cached instance unconditionally if one exists. The\n // toolExecution check below decides whether to *create* a new\n // one — `clearHeavyState` nulls `this.toolExecution` at end-of-\n // Run, but we want post-Run `Run.rewindFiles()` to still resolve\n // to the checkpointer that captured the writes. Codex P1 #32.\n if (this._fileCheckpointer != null) {\n return this._fileCheckpointer;\n }\n // Eagerly create via the bundle factory so the construction path\n // matches the bundle-only callers (and future bundle-internal\n // cleanup hooks fire). The bundle factory itself accepts a pre-\n // supplied checkpointer when present, so re-injecting this one\n // into every ToolNode is idempotent.\n if (\n this.toolExecution?.engine === 'local' &&\n this.toolExecution.local?.fileCheckpointing === true\n ) {\n const bundle = createLocalCodingToolBundle(\n this.toolExecution.local ?? {}\n );\n this._fileCheckpointer = bundle.checkpointer;\n return this._fileCheckpointer;\n }\n if (\n this.toolExecution?.engine === 'cloudflare-sandbox' &&\n this.toolExecution.cloudflare?.fileCheckpointing === true\n ) {\n const bundle = createCloudflareCodingToolBundle(\n this.toolExecution.cloudflare\n );\n this._fileCheckpointer = bundle.checkpointer;\n return this._fileCheckpointer;\n }\n return undefined;\n }\n}\n\nexport class StandardGraph extends Graph<t.BaseGraphState, t.GraphNode> {\n overrideModel?: t.ChatModel;\n private subagentModelOverride?: t.ChatModel;\n private readonly graphFactory: GraphFactory;\n private readonly supportsMultiAgentChildren: boolean;\n /** Optional compile options passed into workflow.compile() */\n compileOptions?: t.CompileOptions | undefined;\n /** Whether the workflow was actually compiled with a checkpointer. */\n hasCompiledCheckpointer: boolean = false;\n messages: BaseMessage[] = [];\n /** Whether a rebuilt resume seeded the message baseline from its checkpoint. */\n private hasRestoredCheckpointMessages = false;\n /** Cached run messages preserved before clearHeavyState() so getRunMessages() works after cleanup. */\n private cachedRunMessages?: BaseMessage[];\n /** Per-agent discovery snapshots preserved before contexts are reset on cleanup. */\n private cachedDiscoveredTools?: Map<string, string[]>;\n /** Ids of AI turns the agent node returned THIS run; see isRunProducedMessage. */\n protected runProducedAiMessageIds = new Set<string>();\n /** Checkpoint scope whose messages match index-keyed tool snapshots. */\n private originalToolContentCheckpointScope?: string;\n runId: string | undefined;\n /**\n * Identity used to stamp Langfuse runtime scopes and handlers (see\n * `LangfuseRuntimeContext.runId`). Carries an opaque per-instance\n * component: public run ids are unrestricted and may repeat across\n * concurrently executing runs (retries, duplicate submissions,\n * tenant-local message ids), and equal stamps would let those runs adopt\n * each other's scopes. One graph instance = one execution's stamp, shared\n * by the stream handler and every graph-level scope of that execution.\n */\n readonly langfuseScopeRunId: string;\n /**\n * Boundary between historical messages (loaded from conversation state)\n * and messages produced during the current run. Set once in the state\n * reducer when messages first arrive. Used by `getRunMessages()` and\n * multi-agent message filtering — NOT for pruner token counting (the\n * pruner maintains its own `lastTurnStartIndex` in its closure).\n */\n startIndex: number = 0;\n signal?: AbortSignal;\n /** Map of agent contexts by agent ID */\n agentContexts: Map<string, AgentContext> = new Map();\n /** Default agent ID to use */\n defaultAgentId: string;\n /**\n * Host sink for model usage emitted inside subagent child runs. Threaded\n * into each `SubagentExecutor` this graph creates (and from there into\n * child graphs, so nested subagents report too). See\n * {@link t.StandardGraphInput.subagentUsageSink}.\n */\n subagentUsageSink?: t.SubagentUsageSink;\n /** See {@link t.StandardGraphInput.subagentScope}. */\n subagentScope: boolean;\n /** See {@link t.StandardGraphInput.subagentExecutionContext}. */\n private readonly subagentExecutionContext?: t.SubagentExecutionContext;\n /** See {@link t.StandardGraphInput.preemption}. */\n preemption?: t.StreamPreemption;\n /**\n * Stream circuit breakers, resolved once from\n * {@link t.StandardGraphInput.streamLimits}. The stream handler enforces\n * these on every streamed chunk event.\n */\n streamLimits: ResolvedStreamLimits;\n /**\n * Cumulative streamed argument bytes per in-flight tool call, keyed by\n * generation key + chunk index (see `resolveGenerationKey`). Per-run\n * accumulation state, cleared by both reset paths.\n */\n streamedToolCallArgTallies: Map<string, StreamedToolCallArgTally> = new Map();\n /** Streamed chunk events per model generation, keyed by generation key. */\n streamDeltaEventCounts: Map<string, StreamDeltaEventTally> = new Map();\n /** Per-chunk-object, per-generation charge balances (lazily created; see\n * `StreamLimitState`). Reinitialized by both reset paths: a model may\n * retain and re-yield one mutable chunk object, whose nested map would\n * otherwise grow by one attempt-stamped entry per model call for the\n * graph's lifetime. */\n streamLimitChargeCredits?: WeakMap<object, Map<string, number>>;\n /** Run-scoped breaker abort: composed into every model invocation and\n * every SubagentExecutor child signal, and tripped when a stream circuit\n * breaker fires anywhere in the run, so parallel agent nodes' in-flight\n * provider calls and subagents stop consuming quota while the rejection\n * propagates. Recreated by both reset paths — the abort is one-way within\n * a run, and a reused graph must start its next run unaborted. */\n breakerAbort = new AbortController();\n\n /** Incremented whenever `breakerAbort` is replaced. Stamped into each\n * model attempt's metadata ({@link STREAM_LIMIT_EPOCH_KEY}) so the stream\n * handler's consumer-side trip binds to the run that produced the event\n * rather than whichever controller is live when a straggling chunk is\n * finally handled. */\n breakerEpoch = 0;\n\n /** Immutable snapshot of the run's breaker identity (epoch + controller),\n * replaced as ONE object whenever `resetValues` installs a fresh\n * controller. Sites that pause across awaits capture it at entry and\n * revalidate by REFERENCE afterwards — a single identity comparison\n * proves no reset happened while suspended, where separate epoch and\n * controller reads could interleave with one. */\n runScope: RunBreakerScope = Object.freeze({\n epoch: 0,\n controller: this.breakerAbort,\n });\n\n /** Generation keys of model attempts still in flight (see\n * `StreamLimitState.activeStreamLimitGenerations`). Lazily created by the\n * attempt lease; spans resets on purpose. */\n activeStreamLimitGenerations?: Set<string>;\n\n /** The stream-limit error behind an already-fired breaker, whether this\n * graph's own controller tripped or a parent run's breaker arrived through\n * the composed constructor signal (child graphs own separate controllers).\n * Providers can translate either abort into a generic error, and recovery\n * paths must not run in that state. */\n protected resolveTrippedBreakerReason(\n breakerSignal: AbortSignal = this.breakerAbort.signal\n ): StreamLimitExceededError | undefined {\n if (\n breakerSignal.aborted &&\n breakerSignal.reason instanceof StreamLimitExceededError\n ) {\n return breakerSignal.reason;\n }\n if (\n this.signal?.aborted === true &&\n this.signal.reason instanceof StreamLimitExceededError\n ) {\n return this.signal.reason;\n }\n return undefined;\n }\n /**\n * Seals charged against `preemption.maxSeals`. Per-turn: cleared by both\n * reset paths so a fresh turn gets a fresh budget, while a HITL resume —\n * which skips `resetValues` — keeps what it had left.\n */\n private preemptSealBudgetUsed = 0;\n /**\n * Seals honored over the graph's lifetime. Reported by\n * {@link getPreemptStats}, so it deliberately SURVIVES `clearHeavyState()`\n * — a host reads it after `processStream` returns, which is strictly after\n * cleanup runs.\n */\n preemptSealCount = 0;\n /** Boundaries that produced nothing to inject, so the turn stopped early. */\n preemptEmptyBoundaries = 0;\n /**\n * Set between claiming a seal and resolving its boundary. `MultiAgentGraph`\n * fans parallel agents through this one instance against a single host\n * request, so without a one-at-a-time gate several streams would each seal\n * for the same queued message and every loser would take the\n * nothing-to-inject path and cut its answer short.\n */\n private preemptSealInFlight = false;\n /**\n * True when a seal ended the turn without a resume. The assistant turn is\n * real and kept, but it is not the answer the model intended to finish —\n * hosts persist it as unfinished rather than complete.\n */\n preemptIncomplete = false;\n /**\n * `stopReason` from a `PreemptBoundary` hook that halted the turn.\n *\n * Clearing the registry halt is what keeps the sealed turn alive, but the\n * registry held the only copy of the reason — so it is captured here first.\n * Without it `getHaltReason()` returns undefined and a host records a\n * hook-halted turn as an ordinary completion.\n */\n preemptHaltReason: string | undefined;\n /**\n * Agent IDs whose next superstep must return to the agent node. Keyed by\n * agent because `MultiAgentGraph` routes every parallel agent through this\n * same instance, and a single field would let one agent's boundary resume\n * another's turn.\n */\n pendingPreemptReturn = new Set<string>();\n\n constructor(\n {\n runId,\n signal,\n agents,\n langfuse,\n tokenCounter,\n indexTokenCountMap,\n calibrationRatio,\n subagentUsageSink,\n subagentScope,\n subagentExecutionContext,\n preemption,\n streamLimits,\n }: t.StandardGraphInput,\n dependencies?: GraphFactoryDependencies\n ) {\n super();\n this.supportsMultiAgentChildren = dependencies != null;\n this.graphFactory =\n dependencies?.graphFactory ??\n ((request): StandardGraph => {\n if (request.kind !== 'standard') {\n throw new Error(\n 'A polymorphic graph factory is required for multi-agent graph construction.'\n );\n }\n return new StandardGraph(request.input);\n });\n this.runId = runId;\n this.langfuseScopeRunId = `${runId ?? 'graph'}:${nanoid()}`;\n this.signal = signal;\n this.langfuse = langfuse;\n this.subagentUsageSink = subagentUsageSink;\n this.subagentScope = subagentScope === true;\n this.subagentExecutionContext = subagentExecutionContext;\n this.preemption = preemption;\n this.streamLimits = resolveStreamLimits(streamLimits);\n\n if (agents.length === 0) {\n throw new Error('At least one agent configuration is required');\n }\n\n for (const agentConfig of agents) {\n const agentContext = AgentContext.fromConfig(\n agentConfig,\n tokenCounter,\n indexTokenCountMap\n );\n if (calibrationRatio != null && calibrationRatio > 0) {\n agentContext.calibrationRatio = calibrationRatio;\n }\n\n this.agentContexts.set(agentConfig.agentId, agentContext);\n }\n\n this.defaultAgentId = agents[0].agentId;\n }\n\n /* Init */\n\n resetValues(keepContent?: boolean, checkpointScope?: string): void {\n this.resetSubagentCheckpointThreadIds();\n this.messages = [];\n this.hasRestoredCheckpointMessages = false;\n this.cachedRunMessages = undefined;\n this.cachedDiscoveredTools = undefined;\n this.config = resetIfNotEmpty(this.config, undefined);\n if (keepContent !== true) {\n this.contentData = resetIfNotEmpty(this.contentData, []);\n this.contentIndexMap = resetIfNotEmpty(this.contentIndexMap, new Map());\n }\n this.stepKeyIds = resetIfNotEmpty(this.stepKeyIds, new Map());\n /**\n * Clear in-place instead of replacing with a new Map to preserve the\n * shared reference held by ToolNode (passed at construction time).\n * Using resetIfNotEmpty would create a new Map, leaving ToolNode with\n * a stale reference on 2nd+ processStream calls.\n */\n this.toolCallStepIds.clear();\n this.runProducedAiMessageIds.clear();\n this.eagerEventToolExecutions.clear();\n this.clearEagerEventToolUsageCounts();\n this.eagerEventToolCallChunks.clear();\n this.eagerEventToolSuppressions.clear();\n /** Grace sweep instead of a clear: producer loops of straggling\n * attempts use these maps directly and sit outside the consumer-only\n * epoch gate — clearing would hand a cancellation-ignoring provider a\n * fresh allowance at every run start. Entries from the epoch that is\n * ending survive exactly one reset so those stragglers stay on their\n * original budgets; older entries are removed. */\n sweepStaleStreamLimitEntries(\n this.streamedToolCallArgTallies,\n this.breakerEpoch,\n this.activeStreamLimitGenerations\n );\n sweepStaleStreamLimitEntries(\n this.streamDeltaEventCounts,\n this.breakerEpoch,\n this.activeStreamLimitGenerations\n );\n this.streamLimitChargeCredits = undefined;\n /** Run-start is the only safe replacement point for the breaker:\n * end-of-run cleanup must leave it in place so straggling parallel\n * children from the failed run cannot start on a fresh signal.\n * Replaced UNCONDITIONALLY here — a run that failed on an ordinary\n * error leaves the controller un-aborted, and stragglers still settling\n * hold their entry-time capture of it; a late stream-limit trip on that\n * old controller must not cancel the run starting now. */\n this.breakerAbort = new AbortController();\n this.breakerEpoch += 1;\n this.runScope = Object.freeze({\n epoch: this.breakerEpoch,\n controller: this.breakerAbort,\n });\n this.handlerDispatchedStepIds = resetIfNotEmpty(\n this.handlerDispatchedStepIds,\n new Set()\n );\n this.handlerDispatchedEventCounts = resetIfNotEmpty(\n this.handlerDispatchedEventCounts,\n new Map()\n );\n this.messageIdsByStepKey = resetIfNotEmpty(\n this.messageIdsByStepKey,\n new Map()\n );\n this.messageStepHasToolCalls = resetIfNotEmpty(\n this.messageStepHasToolCalls,\n new Map()\n );\n this.messageStepHasTextDeltas = resetIfNotEmpty(\n this.messageStepHasTextDeltas,\n new Set()\n );\n this.reasoningStepHasDeltas = resetIfNotEmpty(\n this.reasoningStepHasDeltas,\n new Set()\n );\n this.prelimMessageIdsByStepKey = resetIfNotEmpty(\n this.prelimMessageIdsByStepKey,\n new Map()\n );\n this.invokedToolIds = resetIfNotEmpty(this.invokedToolIds, undefined);\n this.resetPreemptTurnState();\n this.resetPreemptTotals();\n const hasScopedCheckpoint =\n this.hasCompiledCheckpointer &&\n checkpointScope != null &&\n checkpointScope !== '';\n const preserveOriginalToolContent =\n hasScopedCheckpoint &&\n this.originalToolContentCheckpointScope === checkpointScope;\n for (const context of this.agentContexts.values()) {\n context.reset({ preserveOriginalToolContent });\n }\n this.originalToolContentCheckpointScope = hasScopedCheckpoint\n ? checkpointScope\n : undefined;\n }\n\n /** Seeds the sidecar message view that checkpoint restoration bypasses. */\n override restoreCheckpointMessages(\n messages: BaseMessage[],\n pendingMessages?: BaseMessage[]\n ): void {\n if (this.messages.length > 0) {\n return;\n }\n this.messages =\n pendingMessages == null\n ? [...messages]\n : messagesStateReducer(messages, pendingMessages);\n this.startIndex = this.messages.length;\n this.hasRestoredCheckpointMessages = true;\n this.cachedRunMessages = undefined;\n }\n\n override clearHeavyState(): void {\n this.cachedRunMessages = this.messages.slice(this.startIndex);\n this.cachedDiscoveredTools = new Map(\n Array.from(this.agentContexts, ([agentId, context]) => [\n agentId,\n context.getDiscoveredTools(),\n ])\n );\n super.clearHeavyState();\n this.messages = [];\n this.overrideModel = undefined;\n this.subagentModelOverride = undefined;\n /** Stream-limit accounting (argument tallies, event counts, charge\n * credits) deliberately SURVIVES cleanup: this runs in `processStream`'s\n * finally, which an ordinary parallel-branch failure reaches while\n * sibling attempts are still unwinding on the retained breaker — a\n * cancellation-ignoring provider's late chunks would otherwise recreate\n * their budgets from zero and stream another full allowance. The maps\n * are bounded by in-flight call sizes and `resetValues` clears them at\n * the next run start, where the epoch bump already drops stamped\n * straggler events before accounting. */\n /** Deliberately NOT recreating a tripped breakerAbort here: this runs in\n * `processStream`'s cleanup, which a rejected parallel batch reaches\n * while sibling subagents can still be pre-invoke — a fresh controller\n * would hand them an un-aborted signal and let provider requests start\n * after the run already failed. `resetValues` recreates it when the next\n * run begins. */\n /**\n * Turn state only. The reported totals must outlive cleanup — this runs\n * in `processStream`'s `finally`, and the host reads `getPreemptStats()`\n * after that returns.\n */\n this.resetPreemptTurnState();\n const preserveOriginalToolContent =\n this.hasCompiledCheckpointer &&\n this.originalToolContentCheckpointScope != null;\n for (const context of this.agentContexts.values()) {\n context.reset({ preserveOriginalToolContent });\n }\n }\n\n /**\n * Per-turn seal budget and routing markers. Cleared by both reset paths so\n * a new turn starts with a full budget and no stale resume marker.\n *\n * The REPORTED counters are deliberately not touched here — see\n * {@link resetPreemptTotals}.\n */\n private resetPreemptTurnState(): void {\n this.preemptSealBudgetUsed = 0;\n this.preemptSealInFlight = false;\n this.pendingPreemptReturn.clear();\n }\n\n /**\n * Lifetime seal totals, cleared only when a genuinely new run starts.\n * `clearHeavyState()` must NOT call this: it runs in `processStream`'s\n * `finally`, so zeroing here would make {@link getPreemptStats} and\n * `preemptIncomplete` unreadable for every caller of the method that just\n * produced them.\n */\n private resetPreemptTotals(): void {\n this.preemptSealCount = 0;\n this.preemptEmptyBoundaries = 0;\n this.preemptIncomplete = false;\n this.preemptHaltReason = undefined;\n }\n\n /**\n * True when the host has requested a cooperative seal AND this graph may\n * honor it. Read once per streamed chunk, so it stays property reads plus\n * one host callback — no I/O, no allocation.\n *\n * Non-mutating: a true result only means a seal is worth evaluating. The\n * budget is taken by {@link claimPreemptSeal} once the accumulated chunk is\n * known to be safe, so a chunk that cannot seal never spends budget.\n *\n * Subagent scopes never seal: a steer targets the top-level conversation,\n * and a child run must finish so its parent sees a complete result.\n */\n /** Internal seal preconditions only — no host callback, no side effects. */\n private canClaimPreemptSeal(): boolean {\n /**\n * Resolved and required here with the same rule `dispatchPreemptBoundary`\n * uses. Without it a direct `StandardGraph` consumer that supplies no\n * `runId` could claim a seal on the strength of a global matcher, then hit\n * the boundary's own null-runId guard and get nothing back — truncating\n * the answer for a drain that provably could not run.\n */\n const runId =\n (this.config?.configurable?.run_id as string | undefined) ?? this.runId;\n return (\n !this.subagentScope &&\n this.preemption != null &&\n !this.preemptSealInFlight &&\n this.preemptSealBudgetUsed < resolveMaxSeals(this.preemption.maxSeals) &&\n runId != null &&\n /**\n * A seal only buys room for an injection. With no `PreemptBoundary`\n * matcher live — never registered, or a `once` matcher already\n * consumed — the boundary provably returns nothing and the answer is\n * cut short for no gain, so refuse the seal instead. Failing closed\n * lands on the documented no-preemption behavior: the model finishes\n * and the message waits for the next tool boundary.\n *\n * Same session resolution as `dispatchPreemptBoundary`, or a\n * session-scoped matcher would be visible at one site and not the other.\n */\n this.hookRegistry?.hasDispatchableHookFor('PreemptBoundary', runId) ===\n true\n );\n }\n\n shouldPreemptStream(): boolean {\n return (\n this.canClaimPreemptSeal() && this.preemption?.shouldPreempt() === true\n );\n }\n\n /**\n * Takes the seal slot, or returns false if another stream already holds it.\n *\n * Assumes the caller already polled `shouldPreemptStream()` for THIS chunk,\n * and deliberately does not poll the host again — `StreamPreemption`\n * documents `shouldPreempt` as once per chunk, and a host that consumes a\n * pending flag on read would lose the request to a second call.\n *\n * The guard and both mutations remain one synchronous body, which is what\n * makes this safe under a parallel `MultiAgentGraph`: several agents share\n * one graph and can each see the poll as true, but no `await` can split the\n * claim, so only one takes the slot. The loser keeps streaming normally\n * rather than sealing for a message it would never receive.\n */\n claimPreemptSeal(): boolean {\n if (!this.canClaimPreemptSeal()) {\n return false;\n }\n this.preemptSealInFlight = true;\n this.preemptSealBudgetUsed += 1;\n this.preemptSealCount += 1;\n return true;\n }\n\n /** Releases the seal slot once its boundary has resolved, win or lose. */\n releasePreemptSeal(): void {\n this.preemptSealInFlight = false;\n }\n\n getPreemptStats(): t.PreemptStats {\n return {\n seals: this.preemptSealCount,\n emptyBoundaries: this.preemptEmptyBoundaries,\n };\n }\n\n /* Run Step Processing */\n\n getRunStep(stepId: string): t.RunStep | undefined {\n const index = this.contentIndexMap.get(stepId);\n if (index !== undefined) {\n return this.contentData[index];\n }\n return undefined;\n }\n\n getAgentContext(metadata: Record<string, unknown> | undefined): AgentContext {\n if (!metadata) {\n throw new Error('No metadata provided to retrieve agent context');\n }\n\n const currentNode = metadata.langgraph_node as string;\n if (!currentNode) {\n throw new Error(\n 'No langgraph_node in metadata to retrieve agent context'\n );\n }\n\n let agentId: string | undefined;\n if (currentNode.startsWith(AGENT)) {\n agentId = currentNode.substring(AGENT.length);\n } else if (currentNode.startsWith(TOOLS)) {\n agentId = currentNode.substring(TOOLS.length);\n } else if (currentNode.startsWith(SUMMARIZE)) {\n agentId = currentNode.substring(SUMMARIZE.length);\n }\n\n const agentContext = this.agentContexts.get(agentId ?? '');\n if (!agentContext) {\n throw new Error(`No agent context found for agent ID ${agentId}`);\n }\n\n return agentContext;\n }\n\n getStepBaseKey(metadata: Record<string, unknown> | undefined): string {\n if (!metadata) return '';\n\n const keyList = this.getInvocationKeyList(metadata);\n if (this.checkKeyList(keyList)) {\n throw new Error('Missing metadata');\n }\n\n return joinKeys(keyList);\n }\n\n getStepKey(metadata: Record<string, unknown> | undefined): string {\n if (!metadata) return '';\n\n const keyList = this.getKeyList(metadata);\n if (this.checkKeyList(keyList)) {\n throw new Error('Missing metadata');\n }\n\n return joinKeys(keyList);\n }\n\n getStepIdByKey(stepKey: string, index?: number): string {\n const stepIds = this.stepKeyIds.get(stepKey);\n if (!stepIds) {\n throw new Error(`No step IDs found for stepKey ${stepKey}`);\n }\n\n if (index === undefined) {\n return stepIds[stepIds.length - 1];\n }\n\n return stepIds[index];\n }\n\n generateStepId(stepKey: string): [string, number] {\n const stepIds = this.stepKeyIds.get(stepKey);\n let newStepId: string | undefined;\n let stepIndex = 0;\n if (stepIds) {\n stepIndex = stepIds.length;\n newStepId = `step_${nanoid()}`;\n stepIds.push(newStepId);\n this.stepKeyIds.set(stepKey, stepIds);\n } else {\n newStepId = `step_${nanoid()}`;\n this.stepKeyIds.set(stepKey, [newStepId]);\n }\n\n return [newStepId, stepIndex];\n }\n\n getKeyList(\n metadata: Record<string, unknown> | undefined\n ): (string | number | undefined)[] {\n if (!metadata) return [];\n\n const keyList = this.getInvocationKeyList(metadata);\n const agentContext = this.getAgentContext(metadata);\n if (\n agentContext.currentTokenType === ContentTypes.THINK ||\n agentContext.currentTokenType === 'think_and_text'\n ) {\n keyList.push('reasoning');\n } else if (agentContext.tokenTypeSwitch === 'content') {\n keyList.push(`post-reasoning-${agentContext.reasoningTransitionCount}`);\n }\n\n return keyList;\n }\n\n private getInvocationKeyList(\n metadata: Record<string, unknown>\n ): (string | number | undefined)[] {\n const keyList = this.getBaseKeyList(metadata);\n if (this.invokedToolIds != null && this.invokedToolIds.size > 0) {\n keyList.push(this.invokedToolIds.size + '');\n }\n return keyList;\n }\n\n private getBaseKeyList(\n metadata: Record<string, unknown>\n ): (string | number | undefined)[] {\n const configurable = this.config?.configurable;\n const runId =\n (metadata.run_id as string | undefined) ??\n (configurable?.run_id as string | undefined) ??\n this.runId;\n const threadId =\n (metadata.thread_id as string | undefined) ??\n (configurable?.thread_id as string | undefined) ??\n runId;\n const checkpointNs =\n (metadata.checkpoint_ns as string | undefined) ??\n (metadata.langgraph_checkpoint_ns as string | undefined) ??\n '';\n const keyList = [\n runId,\n threadId,\n metadata.langgraph_node as string,\n metadata.langgraph_step as number,\n checkpointNs,\n ];\n\n return keyList;\n }\n\n checkKeyList(keyList: (string | number | undefined)[]): boolean {\n return keyList.some((key) => key === undefined);\n }\n\n /* Misc.*/\n\n getRunMessages(): BaseMessage[] | undefined {\n /** Runtime-honest widening: a disposed-but-cached graph (HITL\n * resume/reconnect through a WeakRef cache) can carry null here despite\n * the field type. */\n const messages = this.messages as BaseMessage[] | undefined;\n if (messages == null) {\n return this.cachedRunMessages;\n }\n if (messages.length === 0 && this.cachedRunMessages != null) {\n return this.cachedRunMessages;\n }\n return messages.slice(this.startIndex);\n }\n\n override getDiscoveredTools(agentId?: string): string[] {\n if (agentId != null) {\n const current =\n this.agentContexts.get(agentId)?.getDiscoveredTools() ?? [];\n if (current.length > 0 || this.cachedDiscoveredTools == null) {\n return current;\n }\n return [...(this.cachedDiscoveredTools.get(agentId) ?? [])];\n }\n\n const discoveredTools = new Set<string>();\n for (const context of this.agentContexts.values()) {\n for (const toolName of context.getDiscoveredTools()) {\n discoveredTools.add(toolName);\n }\n }\n if (discoveredTools.size === 0 && this.cachedDiscoveredTools != null) {\n for (const snapshot of this.cachedDiscoveredTools.values()) {\n for (const toolName of snapshot) {\n discoveredTools.add(toolName);\n }\n }\n }\n return Array.from(discoveredTools);\n }\n\n /**\n * True when THIS RUN produced `message` — the provenance the handoff cue\n * gate needs. Tracked as an id set rather than inferred from `startIndex`\n * arithmetic: summarization's remove-all compaction rewrites the live\n * array and leaves `startIndex` stale, so index-based run/host\n * discrimination silently breaks right after a mid-run summarize. Ids\n * survive compaction (retained messages keep theirs), host-supplied\n * prefill messages are never in the set, and membership is O(1) per\n * model call.\n */\n isRunProducedMessage(message: BaseMessage): boolean {\n const id = message.id;\n return (\n typeof id === 'string' &&\n id !== '' &&\n this.runProducedAiMessageIds.has(id)\n );\n }\n\n getContentParts(): t.MessageContentComplex[] | undefined {\n // `messages` can be null/undefined on a graph that has been disposed\n // (clearHeavyState) but is still reachable via a cache (e.g. RedisJobStore's\n // WeakRef) during a HITL resume/reconnect. Guard instead of dereferencing null.\n const messages = this.messages as BaseMessage[] | undefined;\n if (messages == null) {\n return undefined;\n }\n return convertMessagesToContent(messages.slice(this.startIndex));\n }\n\n getCalibrationRatio(): number {\n const context = this.agentContexts.get(this.defaultAgentId);\n return context?.calibrationRatio ?? 1;\n }\n\n getResolvedInstructionOverhead(): number | undefined {\n const context = this.agentContexts.get(this.defaultAgentId);\n return context?.resolvedInstructionOverhead;\n }\n\n getToolCount(): number {\n const context = this.agentContexts.get(this.defaultAgentId);\n return (\n (context?.tools?.length ?? 0) +\n (context?.toolDefinitions?.length ?? 0) +\n /**\n * Graph-managed + host-supplied direct tools (handoff, subagent,\n * `AgentInputs.graphTools`) are bound to the model and token-accounted,\n * so a count that omits them under-reports the run's tool surface\n * (Codex #289 P3).\n */\n (context?.graphTools?.length ?? 0)\n );\n }\n\n /**\n * Get all run steps, optionally filtered by agent ID\n */\n getRunSteps(agentId?: string): t.RunStep[] {\n // `contentData` can be null/undefined on a disposed-but-cached graph during a\n // HITL resume/reconnect; without this guard `[...this.contentData]` throws\n // \"this.contentData is not iterable\".\n const contentData = this.contentData as t.RunStep[] | undefined;\n if (contentData == null) {\n return [];\n }\n if (agentId == null || agentId === '') {\n return [...contentData];\n }\n return contentData.filter((step) => step.agentId === agentId);\n }\n\n /**\n * Get run steps grouped by agent ID\n */\n getRunStepsByAgent(): Map<string, t.RunStep[]> {\n const stepsByAgent = new Map<string, t.RunStep[]>();\n\n for (const step of this.contentData) {\n if (step.agentId == null || step.agentId === '') continue;\n\n const steps = stepsByAgent.get(step.agentId) ?? [];\n steps.push(step);\n stepsByAgent.set(step.agentId, steps);\n }\n\n return stepsByAgent;\n }\n\n /**\n * Get agent IDs that participated in this run\n */\n getActiveAgentIds(): string[] {\n const agentIds = new Set<string>();\n for (const step of this.contentData) {\n if (step.agentId != null && step.agentId !== '') {\n agentIds.add(step.agentId);\n }\n }\n return Array.from(agentIds);\n }\n\n /**\n * Maps contentPart indices to agent IDs for post-run analysis\n * Returns a map where key is the contentPart index and value is the agentId\n */\n getContentPartAgentMap(): Map<number, string> {\n const contentPartAgentMap = new Map<number, string>();\n\n for (const step of this.contentData) {\n if (\n step.agentId != null &&\n step.agentId !== '' &&\n Number.isFinite(step.index)\n ) {\n contentPartAgentMap.set(step.index, step.agentId);\n }\n }\n\n return contentPartAgentMap;\n }\n\n /* Graph */\n\n initializeTools({\n currentTools,\n currentToolMap,\n agentContext,\n }: {\n currentTools?: t.GraphTools;\n currentToolMap?: t.ToolMap;\n agentContext?: AgentContext;\n }): CustomToolNode<t.BaseGraphState> | ToolNode<t.BaseGraphState> {\n const toolDefinitions = agentContext?.toolDefinitions;\n const eventDrivenMode =\n toolDefinitions != null && toolDefinitions.length > 0;\n const traceToolNode = shouldTraceToolNodeForLangfuse({\n runLangfuse: this.langfuse,\n agentLangfuse: agentContext?.langfuse,\n });\n const interruptingToolNames = new Set(this.interruptingToolNames ?? []);\n if (\n this.humanInTheLoop?.enabled === true &&\n (agentContext?.subagentConfigs?.length ?? 0) > 0\n ) {\n interruptingToolNames.add(Constants.SUBAGENT);\n }\n const effectiveInterruptingToolNames =\n interruptingToolNames.size > 0 ? interruptingToolNames : undefined;\n\n if (eventDrivenMode) {\n const schemaTools = createSchemaOnlyTools(toolDefinitions);\n const toolDefMap = new Map(toolDefinitions.map((def) => [def.name, def]));\n const graphTools = agentContext?.graphTools as\n | t.GenericTool[]\n | undefined;\n\n const directToolNames = new Set<string>();\n const allTools = [...schemaTools] as t.GenericTool[];\n const allToolMap: t.ToolMap = new Map(\n schemaTools.map((tool) => [tool.name, tool])\n );\n\n if (graphTools && graphTools.length > 0) {\n for (const tool of graphTools) {\n if ('name' in tool) {\n allTools.push(tool);\n allToolMap.set(tool.name, tool);\n directToolNames.add(tool.name);\n }\n }\n }\n\n const node = new CustomToolNode<t.BaseGraphState>({\n tools: allTools,\n toolMap: allToolMap,\n trace: traceToolNode,\n runLangfuse: this.langfuse,\n agentLangfuse: agentContext?.langfuse,\n eventDrivenMode: true,\n sessions: this.sessions,\n toolDefinitions: toolDefMap,\n // `agentId` is the subagent-scope marker — set ONLY for child-run\n // graphs (hooks fire for child scopes too, via the inherited\n // run_id); `executingAgentId` always identifies the owning agent.\n agentId: this.subagentScope ? agentContext?.agentId : undefined,\n executingAgentId: agentContext?.agentId,\n toolCallStepIds: this.toolCallStepIds,\n toolRegistry: agentContext?.toolRegistry,\n hookRegistry: this.hookRegistry,\n humanInTheLoop: this.humanInTheLoop,\n eagerEventToolExecution: this.eagerEventToolExecution,\n codeSessionToolNames: this.codeSessionToolNames,\n eagerEventToolExecutions: this.eagerEventToolExecutions,\n eagerEventToolUsageCount: this.getEagerEventToolUsageCount(\n agentContext?.agentId\n ),\n eagerEventToolSuppressions: this.eagerEventToolSuppressions,\n toolExecution: this.toolExecution,\n directToolNames: directToolNames.size > 0 ? directToolNames : undefined,\n interruptingToolNames: effectiveInterruptingToolNames,\n maxContextTokens: agentContext?.maxContextTokens,\n maxToolResultChars: agentContext?.maxToolResultChars,\n toolOutputRegistry: this.getOrCreateToolOutputRegistry(),\n fileCheckpointer: this.getOrCreateFileCheckpointer(),\n getBreakerSignal: (): AbortSignal => this.breakerAbort.signal,\n getRunScope: (): RunBreakerScope => this.runScope,\n errorHandler: (data, metadata): Promise<boolean> =>\n StandardGraph.handleToolCallErrorStatic(this, data, metadata),\n });\n this.registerCompiledToolNode(node);\n return node;\n }\n\n const graphTools = agentContext?.graphTools as t.GenericTool[] | undefined;\n const baseTools = (currentTools as t.GenericTool[] | undefined) ?? [];\n const allTraditionalTools =\n graphTools && graphTools.length > 0\n ? [...baseTools, ...graphTools]\n : baseTools;\n /**\n * ToolNode treats a supplied `toolMap` as authoritative (it only derives\n * one from `tools` when the param is undefined), so when graphTools force\n * us to build a merged map here, an absent `currentToolMap` must be\n * seeded from the BASE tools first — otherwise ordinary tools stay bound\n * to the model but vanish from the execution map and every call to them\n * fails as an unknown tool (Codex #289 round 2).\n */\n const traditionalToolMap =\n graphTools && graphTools.length > 0\n ? new Map([\n ...(currentToolMap ??\n new Map(\n baseTools\n .filter(\n (t): t is t.GenericTool & { name: string } => 'name' in t\n )\n .map((t) => [t.name, t] as [string, t.GenericTool])\n )),\n ...graphTools\n .filter((t): t is t.GenericTool & { name: string } => 'name' in t)\n .map((t) => [t.name, t] as [string, t.GenericTool]),\n ])\n : currentToolMap;\n\n const node = new CustomToolNode<t.BaseGraphState>({\n tools: allTraditionalTools,\n toolMap: traditionalToolMap,\n trace: traceToolNode,\n runLangfuse: this.langfuse,\n agentLangfuse: agentContext?.langfuse,\n // `agentId` is the subagent-scope marker — set ONLY for child-run\n // graphs; `executingAgentId` always identifies the owning agent so\n // hooks can attribute the batch even at the top level.\n agentId: this.subagentScope ? agentContext?.agentId : undefined,\n executingAgentId: agentContext?.agentId,\n toolCallStepIds: this.toolCallStepIds,\n errorHandler: (data, metadata): Promise<boolean> =>\n StandardGraph.handleToolCallErrorStatic(this, data, metadata),\n toolRegistry: agentContext?.toolRegistry,\n sessions: this.sessions,\n toolExecution: this.toolExecution,\n codeSessionToolNames: this.codeSessionToolNames,\n interruptingToolNames: effectiveInterruptingToolNames,\n hookRegistry: this.hookRegistry,\n humanInTheLoop: this.humanInTheLoop,\n maxContextTokens: agentContext?.maxContextTokens,\n maxToolResultChars: agentContext?.maxToolResultChars,\n toolOutputRegistry: this.getOrCreateToolOutputRegistry(),\n fileCheckpointer: this.getOrCreateFileCheckpointer(),\n getBreakerSignal: (): AbortSignal => this.breakerAbort.signal,\n getRunScope: (): RunBreakerScope => this.runScope,\n });\n this.registerCompiledToolNode(node);\n return node;\n }\n\n overrideTestModel(\n responses: string[],\n sleep?: number,\n toolCalls?: ToolCall[]\n ): void {\n this.overrideModel = createFakeStreamingLLM({\n responses,\n sleep,\n toolCalls,\n });\n }\n\n /** Explicitly overrides the model used by isolated descendant subagent graphs. */\n setSubagentModelOverride(model: t.ChatModel): void {\n this.subagentModelOverride = model;\n }\n\n getUsageMetadata(\n finalMessage?: BaseMessage\n ): Partial<UsageMetadata> | undefined {\n if (\n finalMessage &&\n 'usage_metadata' in finalMessage &&\n finalMessage.usage_metadata != null\n ) {\n return finalMessage.usage_metadata as Partial<UsageMetadata>;\n }\n }\n\n cleanupSignalListener(currentModel?: t.ChatModel): void {\n if (!this.signal) {\n return;\n }\n const model = this.overrideModel ?? currentModel;\n if (!model) {\n return;\n }\n const client = (model as ChatOpenAI | undefined)?.exposedClient;\n if (!client?.abortHandler) {\n return;\n }\n this.signal.removeEventListener('abort', client.abortHandler);\n client.abortHandler = undefined;\n }\n\n /**\n * Applies a context-overflow recovery plan and hands control to the\n * summarize node, which compacts and then routes straight back here for a\n * retry against the corrected budget.\n *\n * Returning the detour rather than rethrowing is the whole point: the\n * caller never sees the provider's rejection, only a slightly longer turn.\n */\n private beginOverflowRecovery({\n recovery,\n agentContext,\n agentId,\n config,\n originalToolContent,\n estimatedPromptTokens,\n }: {\n recovery: OverflowRecoveryPlan;\n agentContext: AgentContext;\n agentId: string;\n config?: RunnableConfig;\n /** Masking record from the prune pass that built the rejected prompt. */\n originalToolContent?: Map<number, string>;\n /** Size of the rejected prompt, recorded to detect a correction that changed nothing. */\n estimatedPromptTokens?: number;\n }): Partial<t.AgentSubgraphState> {\n const previousBudget = agentContext.maxContextTokens;\n /**\n * Deterministic compaction first. Re-pruning against the corrected budget\n * raises context pressure, which is what drives the pruner's tool-output\n * truncation and observation masking — no model call, no cost, and no\n * message content lost. A summarization call is held back until that has\n * been tried and the provider rejected the prompt again.\n */\n const allowSummarization = agentContext.shouldSummarizeOverflow();\n\n agentContext.preserveOriginalToolContent(originalToolContent);\n agentContext.applyContextBudgetCorrection(\n recovery.budgetTokens,\n estimatedPromptTokens\n );\n agentContext.applyObservedOverflowCalibration(\n recovery.info.provider,\n recovery.observedCalibrationRatio\n );\n\n emitAgentLog(\n config,\n 'warn',\n 'graph',\n 'Provider rejected the prompt as too large — compacting and retrying',\n {\n kind: recovery.info.kind,\n previousBudget,\n recoveredBudget: recovery.budgetTokens,\n providerReportedLimit: recovery.info.limitTokens,\n providerReportedTokens: recovery.info.requestedTokens,\n providerReportedPromptTokens: recovery.info.promptTokens,\n observedCalibrationRatio: recovery.observedCalibrationRatio,\n detectedBy: recovery.info.source,\n attempt: agentContext.overflowRecoveryAttempts,\n compaction: allowSummarization ? 'summarize' : 'compress',\n },\n { runId: this.runId, agentId },\n { force: true }\n );\n\n return {\n summarizationRequest: {\n remainingContextTokens: 0,\n agentId: agentId || agentContext.agentId,\n reason: 'overflow',\n allowSummarization,\n },\n };\n }\n\n createCallModel(agentId = 'default') {\n return async (\n state: t.AgentSubgraphState,\n config?: RunnableConfig\n ): Promise<Partial<t.AgentSubgraphState>> => {\n /** Captured at node ENTRY, before any host-facing await (context-usage\n * dispatch, hooks): a sibling's trip can fail the run and a prompt\n * next run can reset the controller while this node is paused in one\n * of those awaits, and a later capture would bind this attempt to the\n * fresh controller. Trips and reason reads below stay on this\n * capture. */\n const attemptBreaker = this.breakerAbort;\n const attemptBreakerEpoch = this.breakerEpoch;\n /** Already-tripped-at-entry: a parallel sibling's breach has failed\n * the run before this node was scheduled. Rethrow before hooks or the\n * provider call — a custom provider that doesn't synchronously reject\n * an aborted signal would otherwise start another model request on a\n * failed run. */\n const entryTripReason = this.resolveTrippedBreakerReason(\n attemptBreaker.signal\n );\n if (entryTripReason != null) {\n throw entryTripReason;\n }\n const agentContext = this.agentContexts.get(agentId);\n if (!agentContext) {\n throw new Error(`Agent context not found for agentId: ${agentId}`);\n }\n\n if (!config) {\n throw new Error('No config provided');\n }\n\n /**\n * A `PreemptBoundary` hook halted this run and the sealed commit is\n * already in state. Enforced at every model node's ENTRY because that\n * is the only site that covers all of `MultiAgentGraph`'s onward\n * routing at once — static direct edges, Command fan-out, fan-in\n * wrappers, and parallel siblings' subsequent inner-loop turns — none\n * of which consult the halt (the registry signal was deliberately\n * cleared to keep the stream-cancel from destroying the sealed turn).\n * Declining the model call turns every routed-to successor into a\n * no-op, so the outer workflow drains to END without new turns or tool\n * side effects. Reset per turn in `resetPreemptTotals`, so the next\n * `processStream` call starts clean.\n */\n if (this.preemptHaltReason != null) {\n return { messages: [] };\n }\n\n const { messages } = state;\n\n const discoveredNames = extractToolDiscoveries(messages);\n if (discoveredNames.length > 0) {\n agentContext.markToolsAsDiscovered(discoveredNames);\n }\n\n const rawToolsForBinding = resolveLocalToolsForBinding({\n tools: agentContext.getToolsForBinding(),\n toolExecution: this.toolExecution,\n });\n\n /**\n * Anthropic prompt-cache breakpoint on the tool definitions.\n *\n * Without this, the (often static) tool inventory shows up as\n * fresh input on every turn — measured at ~28k tokens/turn for\n * the local engine's coding-tool bundle, dominating per-turn\n * cost even when message-level caching is on.\n *\n * Strategy: partition tools into [static, deferred] and stamp\n * `cache_control: ephemeral` on the last static tool.\n * Discovered deferred tools that arrive across turns sit *after*\n * the breakpoint and don't invalidate the prefix.\n */\n let toolsForBinding = rawToolsForBinding;\n if (\n agentContext.provider === Providers.ANTHROPIC &&\n (agentContext.clientOptions as t.AnthropicClientOptions | undefined)\n ?.promptCache === true\n ) {\n toolsForBinding =\n partitionAndMarkAnthropicToolCache(\n rawToolsForBinding,\n makeIsDeferred(agentContext.toolDefinitions),\n resolvePromptCacheTtl(\n (\n agentContext.clientOptions as\n | t.AnthropicClientOptions\n | undefined\n )?.promptCacheTtl\n )\n ) ?? rawToolsForBinding;\n } else if (\n agentContext.provider === Providers.OPENROUTER &&\n (\n agentContext.clientOptions as\n | t.ProviderOptionsMap[Providers.OPENROUTER]\n | undefined\n )?.promptCache === true\n ) {\n toolsForBinding =\n partitionAndMarkOpenRouterToolCache(\n rawToolsForBinding,\n makeIsDeferred(agentContext.toolDefinitions),\n resolvePromptCacheTtl(\n (\n agentContext.clientOptions as\n | t.ProviderOptionsMap[Providers.OPENROUTER]\n | undefined\n )?.promptCacheTtl\n )\n ) ?? rawToolsForBinding;\n } else if (\n agentContext.provider === Providers.BEDROCK &&\n (\n agentContext.clientOptions as\n | t.BedrockAnthropicClientOptions\n | undefined\n )?.promptCache === true\n ) {\n const bedrockModel = (\n agentContext.clientOptions as { model?: string } | undefined\n )?.model;\n // An omitted model falls back to LangChain's default Claude model (which\n // supports tool caching); only an explicit non-Claude model (e.g. Nova)\n // skips tool marking so its stray marker never leaks into toolConfig.\n if (bedrockModel == null || supportsBedrockToolCache(bedrockModel)) {\n toolsForBinding =\n partitionAndMarkBedrockToolCache(\n rawToolsForBinding,\n makeIsDeferred(agentContext.toolDefinitions)\n ) ?? rawToolsForBinding;\n }\n }\n\n let model =\n this.overrideModel ??\n initializeModel({\n tools: toolsForBinding,\n provider: agentContext.provider,\n clientOptions: agentContext.clientOptions,\n });\n\n if (agentContext.systemRunnable) {\n model = agentContext.systemRunnable.pipe(model as Runnable);\n }\n\n if (agentContext.tokenCalculationPromise) {\n await agentContext.tokenCalculationPromise;\n }\n if (!config.signal) {\n config.signal = this.signal;\n }\n this.config = config;\n\n let messagesToUse = messages;\n let contextUsage: t.ContextUsageEvent | null = null;\n /**\n * Held outside the prune block so overflow recovery — which detours to\n * the summarize node from the invoke catch below — can preserve the\n * same masking record the configured trigger preserves.\n */\n let prunedOriginalToolContent: Map<number, string> | undefined;\n if (\n !agentContext.pruneMessages &&\n agentContext.tokenCounter &&\n agentContext.maxContextTokens != null\n ) {\n agentContext.pruneMessages = createPruneMessages({\n startIndex:\n agentContext.indexTokenCountMap[0] != null ? this.startIndex : 0,\n provider: agentContext.provider,\n tokenCounter: agentContext.tokenCounter,\n maxTokens: agentContext.maxContextTokens,\n maxToolResultChars: agentContext.maxToolResultChars,\n thinkingEnabled: isThinkingEnabled(\n agentContext.provider,\n agentContext.clientOptions\n ),\n indexTokenCountMap: agentContext.indexTokenCountMap,\n contextPruningConfig: agentContext.contextPruningConfig,\n summarizationEnabled: agentContext.summarizationEnabled,\n reserveRatio: agentContext.summarizationConfig?.reserveRatio,\n calibrationRatio: agentContext.calibrationRatio,\n getInstructionTokens: () => agentContext.instructionTokens,\n log: (level, message, data) => {\n emitAgentLog(config, level, 'prune', message, data, {\n runId: this.runId,\n agentId,\n });\n },\n });\n }\n if (agentContext.pruneMessages) {\n const {\n context,\n indexTokenCountMap,\n messagesToRefine,\n prePruneContextTokens,\n remainingContextTokens,\n newOriginalToolContent,\n calibrationRatio,\n resolvedInstructionOverhead,\n contextBudget,\n effectiveInstructionTokens,\n } = agentContext.pruneMessages({\n messages,\n usageMetadata: agentContext.currentUsage,\n lastCallUsage: agentContext.lastCallUsage,\n totalTokensFresh: agentContext.totalTokensFresh,\n });\n prunedOriginalToolContent = newOriginalToolContent;\n /**\n * Masking rewrites tool content in `state.messages` in place, so this\n * map is the only surviving copy of the full output. Persist it on\n * every prune, not just when a summary is about to be written — the\n * pruner closure that produced it is discarded on the next reset, and\n * with it any chance of a later summary restoring the real content.\n * AgentContext bounds what accumulates.\n */\n agentContext.preserveOriginalToolContent(newOriginalToolContent);\n agentContext.indexTokenCountMap = indexTokenCountMap;\n if (calibrationRatio != null && calibrationRatio > 0) {\n agentContext.calibrationRatio = calibrationRatio;\n }\n if (resolvedInstructionOverhead != null) {\n agentContext.resolvedInstructionOverhead =\n resolvedInstructionOverhead;\n const nonToolOverhead =\n agentContext.instructionTokens - agentContext.toolSchemaTokens;\n const calibratedToolTokens = Math.max(\n 0,\n resolvedInstructionOverhead - nonToolOverhead\n );\n const currentToolTokens = agentContext.toolSchemaTokens;\n const variance =\n currentToolTokens > 0\n ? Math.abs(calibratedToolTokens - currentToolTokens) /\n currentToolTokens\n : 1;\n if (variance > CALIBRATION_VARIANCE_THRESHOLD) {\n agentContext.toolSchemaTokens = calibratedToolTokens;\n /** Largest-remainder apportionment keeps the per-tool breakdown\n * summing exactly to the calibrated aggregate */\n if (agentContext.toolTokenCounts != null && currentToolTokens > 0) {\n agentContext.toolTokenCounts = apportionTokenCounts(\n agentContext.toolTokenCounts,\n calibratedToolTokens / currentToolTokens,\n calibratedToolTokens\n );\n }\n }\n }\n messagesToUse = context;\n\n /** Dispatched right before the model invoke — a summarization\n * detour returns from this node without an LLM call, and the\n * post-summary retry produces its own snapshot.\n *\n * The breakdown describes the post-prune prompt: counts from the\n * kept context, message tokens derived from the same calibrated\n * budget math as `remainingContextTokens` (the index map is keyed\n * by pre-prune state indices, so summing it over `context` would\n * missum); `prePruneContextTokens` carries the pre-prune metric. */\n const usageBreakdown = agentContext.getTokenBudgetBreakdown(messages);\n usageBreakdown.messageCount = context.length;\n contextUsage = {\n runId: this.runId,\n agentId,\n breakdown: usageBreakdown,\n contextBudget,\n effectiveInstructionTokens,\n prePruneContextTokens,\n remainingContextTokens,\n calibrationRatio: agentContext.calibrationRatio,\n };\n syncBudgetDerivedFields(contextUsage);\n\n const hasPrunedMessages =\n agentContext.summarizationEnabled === true &&\n Array.isArray(messagesToRefine) &&\n messagesToRefine.length > 0;\n\n if (hasPrunedMessages) {\n const shouldSkip = agentContext.shouldSkipSummarization(\n messages.length\n );\n const triggerResult =\n !shouldSkip &&\n shouldTriggerSummarization({\n trigger: agentContext.summarizationConfig?.trigger,\n maxContextTokens: agentContext.maxContextTokens,\n prePruneContextTokens:\n prePruneContextTokens != null\n ? prePruneContextTokens + agentContext.instructionTokens\n : undefined,\n remainingContextTokens,\n messagesToRefineCount: messagesToRefine.length,\n });\n\n if (triggerResult) {\n emitAgentLog(\n config,\n 'info',\n 'graph',\n 'Summarization triggered',\n undefined,\n { runId: this.runId, agentId }\n );\n emitAgentLog(\n config,\n 'debug',\n 'graph',\n 'Summarization trigger details',\n {\n totalMessages: messages.length,\n remainingContextTokens: remainingContextTokens ?? 0,\n summaryVersion: agentContext.summaryVersion + 1,\n toolSchemaTokens: agentContext.toolSchemaTokens,\n instructionTokens: agentContext.instructionTokens,\n systemMessageTokens: agentContext.systemMessageTokens,\n },\n { runId: this.runId, agentId }\n );\n agentContext.markSummarizationTriggered(messages.length);\n return {\n summarizationRequest: {\n remainingContextTokens: remainingContextTokens ?? 0,\n agentId: agentId || agentContext.agentId,\n },\n };\n }\n\n if (shouldSkip) {\n emitAgentLog(\n config,\n 'debug',\n 'graph',\n 'Summarization skipped — no new messages or per-run cap reached',\n {\n messageCount: messages.length,\n messagesToRefineCount: messagesToRefine.length,\n contextLength: context.length,\n },\n { runId: this.runId, agentId }\n );\n }\n }\n }\n\n let finalMessages = messagesToUse;\n /**\n * Keep the pruner's provider-grounded aggregate as the authoritative\n * baseline, then attribute it across retained messages. Provider\n * transforms can shrink one message while expanding or adding another;\n * per-origin accounting prevents that unrelated shrink from canceling\n * the expansion. Raw counts are frozen before in-place formatters run.\n */\n let providerMessageBaseline:\n | Array<{ rawTokens: number; accountingWeight: number }>\n | undefined;\n const providerMessageOrigins = new WeakMap<BaseMessage, number>();\n if (contextUsage != null && agentContext.tokenCounter != null) {\n const sourceIndices = new WeakMap<BaseMessage, number>();\n for (let i = 0; i < messages.length; i++) {\n sourceIndices.set(messages[i], i);\n }\n providerMessageBaseline = messagesToUse.map((message, index) => {\n const rawTokens = agentContext.tokenCounter!(message);\n const sourceIndex = sourceIndices.get(message);\n const indexedTokens =\n sourceIndex != null\n ? agentContext.indexTokenCountMap[sourceIndex]\n : undefined;\n const accountingWeight =\n indexedTokens != null &&\n Number.isFinite(indexedTokens) &&\n indexedTokens >= 0\n ? indexedTokens\n : rawTokens;\n if (!providerMessageOrigins.has(message)) {\n providerMessageOrigins.set(message, index);\n }\n return { rawTokens, accountingWeight };\n });\n }\n\n const getProviderMessageOriginKey = (\n message: BaseMessage\n ): string | undefined => {\n const type = message.getType();\n if (\n message instanceof ToolMessage &&\n typeof message.tool_call_id === 'string' &&\n message.tool_call_id.length > 0\n ) {\n return `tool:call:${message.tool_call_id}`;\n }\n if (typeof message.id === 'string' && message.id.length > 0) {\n return `${type}:id:${message.id}`;\n }\n return undefined;\n };\n\n /**\n * Provider projections clone messages. Preserve their baseline origin\n * without writing tracking metadata onto the wire. Synthetic fold\n * messages intentionally remain unattributed and are charged in full.\n */\n const trackProviderMessageOrigins = (\n before: BaseMessage[],\n after: BaseMessage[]\n ): BaseMessage[] => {\n if (providerMessageBaseline == null || before === after) {\n return after;\n }\n if (before.length === after.length) {\n for (let i = 0; i < after.length; i++) {\n const origin = providerMessageOrigins.get(before[i]);\n if (\n origin != null &&\n !providerMessageOrigins.has(after[i]) &&\n before[i].getType() === after[i].getType() &&\n !isSyntheticProviderContextMessage(after[i])\n ) {\n providerMessageOrigins.set(after[i], origin);\n }\n }\n return after;\n }\n\n const keyedOrigins = new Map<string, number | null>();\n for (const message of before) {\n const origin = providerMessageOrigins.get(message);\n const key = getProviderMessageOriginKey(message);\n if (origin == null || key == null) {\n continue;\n }\n keyedOrigins.set(key, keyedOrigins.has(key) ? null : origin);\n }\n for (const message of after) {\n if (\n providerMessageOrigins.has(message) ||\n isSyntheticProviderContextMessage(message)\n ) {\n continue;\n }\n const key = getProviderMessageOriginKey(message);\n const origin = key != null ? keyedOrigins.get(key) : undefined;\n if (origin != null) {\n providerMessageOrigins.set(message, origin);\n }\n }\n return after;\n };\n\n if (agentContext.useLegacyContent) {\n const before = finalMessages;\n finalMessages = trackProviderMessageOrigins(\n before,\n formatContentStrings(before)\n );\n }\n\n const maxProviderToolResultChars =\n agentContext.maxToolResultChars ??\n calculateMaxToolResultChars(agentContext.maxContextTokens);\n const beforeToolStreamProjection = finalMessages;\n finalMessages = trackProviderMessageOrigins(\n beforeToolStreamProjection,\n projectToolStreamContentForProvider(beforeToolStreamProjection)\n );\n const beforeToolInputProjection = finalMessages;\n finalMessages = trackProviderMessageOrigins(\n beforeToolInputProjection,\n projectToolCallInputs(\n beforeToolInputProjection,\n calculateMaxToolCallInputChars(agentContext.maxContextTokens)\n )\n );\n\n const lastMessageX =\n finalMessages.length >= 2\n ? finalMessages[finalMessages.length - 2]\n : null;\n const lastMessageY =\n finalMessages.length >= 1\n ? finalMessages[finalMessages.length - 1]\n : null;\n\n const anthropicLike = isAnthropicLike(\n agentContext.provider,\n agentContext.clientOptions as { model?: string }\n );\n\n if (\n agentContext.provider === Providers.BEDROCK &&\n lastMessageX instanceof AIMessageChunk &&\n lastMessageY instanceof ToolMessage &&\n typeof lastMessageX.content === 'string'\n ) {\n const trimmed = lastMessageX.content.trim();\n finalMessages[finalMessages.length - 2].content =\n trimmed.length > 0 ? [{ type: 'text' as const, text: trimmed }] : '';\n }\n\n const localProviderOverflowMeasurements = new WeakMap<\n object,\n {\n contextBudget: number;\n estimatedPromptTokens: number;\n }\n >();\n const measureProviderPayload = (\n candidate: BaseMessage[],\n contextBudgetOverride?: number,\n forceRawRecount = false\n ): {\n fits: boolean;\n projectedMessageTokens?: number;\n availableMessageTokens?: number;\n contextBudget?: number;\n effectiveInstructionTokens?: number;\n } => {\n const contextBudget =\n contextBudgetOverride ?? contextUsage?.contextBudget;\n const effectiveInstructionTokens =\n contextUsage?.effectiveInstructionTokens ??\n (forceRawRecount ? agentContext.instructionTokens : undefined);\n if (\n agentContext.tokenCounter == null ||\n contextBudget == null ||\n effectiveInstructionTokens == null\n ) {\n return { fits: true };\n }\n const availableMessageTokens = Math.max(\n 0,\n contextBudget - effectiveInstructionTokens\n );\n let usageRatio =\n agentContext.calibrationRatio > 0 ? agentContext.calibrationRatio : 1;\n if (\n contextUsage?.calibrationRatio != null &&\n contextUsage.calibrationRatio > 0\n ) {\n usageRatio = contextUsage.calibrationRatio;\n }\n if (forceRawRecount) {\n usageRatio = Math.max(1, usageRatio);\n }\n const baselineRemaining = contextUsage?.remainingContextTokens;\n const accountedMessageTokens =\n !forceRawRecount &&\n providerMessageBaseline != null &&\n baselineRemaining != null &&\n Number.isFinite(baselineRemaining)\n ? availableMessageTokens -\n Math.min(availableMessageTokens, Math.max(0, baselineRemaining))\n : undefined;\n\n let projectedMessageTokens: number;\n if (accountedMessageTokens != null && providerMessageBaseline != null) {\n const replyPrimerTokens = Math.round(\n REPLY_PRIMER_TOKENS * usageRatio\n );\n const rawWeights: Record<string, number> = {};\n let totalWeight = 0;\n for (let i = 0; i < providerMessageBaseline.length; i++) {\n const weight = providerMessageBaseline[i].accountingWeight;\n rawWeights[i] = weight;\n totalWeight += weight;\n }\n const attributableTokens =\n totalWeight > 0\n ? Math.min(\n Math.max(0, accountedMessageTokens - replyPrimerTokens),\n Math.round(totalWeight * usageRatio)\n )\n : 0;\n const apportionedTokens =\n totalWeight > 0\n ? apportionTokenCounts(\n rawWeights,\n attributableTokens / totalWeight,\n attributableTokens\n )\n : {};\n const attributedByOrigin = providerMessageBaseline.map(\n (_, origin) => apportionedTokens[origin] || 0\n );\n projectedMessageTokens = Math.max(\n replyPrimerTokens,\n accountedMessageTokens - attributableTokens\n );\n let newRawTokens = 0;\n const usedOrigins = new Set<number>();\n for (const message of candidate) {\n const rawTokens = agentContext.tokenCounter(message);\n const origin = providerMessageOrigins.get(message);\n if (origin == null || usedOrigins.has(origin)) {\n newRawTokens += rawTokens;\n continue;\n }\n usedOrigins.add(origin);\n projectedMessageTokens += Math.max(\n 0,\n attributedByOrigin[origin] +\n Math.round(\n (rawTokens - providerMessageBaseline[origin].rawTokens) *\n usageRatio\n )\n );\n }\n projectedMessageTokens += Math.round(newRawTokens * usageRatio);\n } else {\n let rawTokens = REPLY_PRIMER_TOKENS;\n for (const message of candidate) {\n rawTokens += agentContext.tokenCounter(message);\n }\n projectedMessageTokens = Math.round(rawTokens * usageRatio);\n }\n return {\n fits: projectedMessageTokens <= availableMessageTokens,\n projectedMessageTokens,\n availableMessageTokens,\n contextBudget,\n effectiveInstructionTokens,\n };\n };\n\n const createProviderPayloadOverflowError = ({\n projection,\n provider,\n info,\n }: {\n projection: ReturnType<typeof measureProviderPayload>;\n provider?: Providers;\n info: string;\n }): ContextOverflowError => {\n const error = new ContextOverflowError(\n JSON.stringify({\n type: 'final_context_overflow',\n info,\n provider,\n projectedMessageTokens: projection.projectedMessageTokens,\n availableMessageTokens: projection.availableMessageTokens,\n })\n );\n if (\n projection.projectedMessageTokens != null &&\n projection.contextBudget != null &&\n projection.effectiveInstructionTokens != null\n ) {\n localProviderOverflowMeasurements.set(error, {\n contextBudget: projection.contextBudget,\n estimatedPromptTokens:\n projection.projectedMessageTokens +\n projection.effectiveInstructionTokens,\n });\n }\n return error;\n };\n\n const applyProviderMessageTransforms = (\n candidate: BaseMessage[]\n ): BaseMessage[] => {\n let transformed = candidate;\n if (\n isThinkingEnabled(agentContext.provider, agentContext.clientOptions)\n ) {\n /**\n * Current-run AI messages may validly omit a thinking block. The\n * boundary prevents them from being mistaken for foreign history.\n */\n const before = transformed;\n transformed = trackProviderMessageOrigins(\n before,\n ensureThinkingBlockInMessages(\n before,\n agentContext.provider,\n config,\n this.startIndex\n )\n );\n }\n\n /**\n * Tool-less destinations cannot send inherited tool blocks without a\n * tool schema, so fold those interactions into provider-valid content.\n */\n if (toolsForBinding == null || toolsForBinding.length === 0) {\n const before = transformed;\n transformed = trackProviderMessageOrigins(\n before,\n foldToolBlocksForToollessAgent(before, config)\n );\n if (agentContext.useLegacyContent) {\n const beforeLegacyFormat = transformed;\n transformed = trackProviderMessageOrigins(\n beforeLegacyFormat,\n formatContentStrings(beforeLegacyFormat)\n );\n }\n }\n /**\n * Applied HERE for the primary so the cue is part of the MEASURED\n * payload — the pre-invoke projection and overflow guard run on this\n * stage's output, and a post-measure append could push a just-fits\n * prompt over budget unreported (#346 round 2). The attemptInvoke\n * funnel re-keys per SERVING provider: it strips this cue for a\n * tolerant fallback and adds it for a Claude fallback behind a\n * tolerant primary.\n */\n if (\n isAnthropicLike(\n agentContext.provider,\n agentContext.clientOptions as { model?: string }\n )\n ) {\n const before = transformed;\n transformed = trackProviderMessageOrigins(\n before,\n appendPredecessorHandoffCue(before, (message) =>\n this.isRunProducedMessage(message)\n )\n );\n }\n return transformed;\n };\n\n const toolOutputRegistry = this.getOrCreateToolOutputRegistry();\n const providerRunId = config.configurable?.run_id as string | undefined;\n const projectProviderReferences = (\n candidate: BaseMessage[]\n ): BaseMessage[] =>\n trackProviderMessageOrigins(\n candidate,\n annotateMessagesForLLM(candidate, toolOutputRegistry, providerRunId)\n );\n\n const compactSyntheticProviderContext = (\n candidate: BaseMessage[]\n ): BaseMessage[] => {\n const synthetic: Array<{\n index: number;\n message: HumanMessage;\n chars: number;\n }> = [];\n for (let i = 0; i < candidate.length; i++) {\n const message = candidate[i];\n if (\n !(message instanceof HumanMessage) ||\n !isSyntheticProviderContextMessage(message)\n ) {\n continue;\n }\n const content = message.content;\n synthetic.push({\n index: i,\n message,\n chars: getToolContentCharLength(content),\n });\n }\n if (synthetic.length === 0) {\n return candidate;\n }\n\n const buildCandidate = (scale: number): BaseMessage[] => {\n const compacted = [...candidate];\n for (const { index, message, chars } of synthetic) {\n const content = compactToolContent(\n message.content,\n Math.floor(chars * scale)\n ).content;\n compacted[index] = new HumanMessage({\n content,\n id: message.id,\n name: message.name,\n additional_kwargs: message.additional_kwargs,\n response_metadata: message.response_metadata,\n });\n }\n return compacted;\n };\n\n let best = buildCandidate(0);\n if (!measureProviderPayload(best).fits) {\n return candidate;\n }\n let low = 0;\n let high = 1;\n for (let i = 0; i < 12; i++) {\n const scale = (low + high) / 2;\n const attempt = buildCandidate(scale);\n if (measureProviderPayload(attempt).fits) {\n best = attempt;\n low = scale;\n } else {\n high = scale;\n }\n }\n return best;\n };\n\n let artifactBaseMessages: BaseMessage[] | undefined;\n if (lastMessageY instanceof ToolMessage) {\n let artifactCandidate = finalMessages;\n if (anthropicLike) {\n artifactCandidate = trackProviderMessageOrigins(\n finalMessages,\n projectAnthropicArtifactContent(\n finalMessages,\n maxProviderToolResultChars\n )\n );\n } else if (\n (isOpenAILike(agentContext.provider) &&\n agentContext.provider !== Providers.DEEPSEEK) ||\n isGoogleLike(agentContext.provider)\n ) {\n artifactCandidate = trackProviderMessageOrigins(\n finalMessages,\n projectArtifactPayload(finalMessages, maxProviderToolResultChars)\n );\n }\n\n if (artifactCandidate !== finalMessages) {\n const projection = measureProviderPayload(artifactCandidate);\n if (projection.fits) {\n artifactBaseMessages = finalMessages;\n finalMessages = artifactCandidate;\n } else {\n emitAgentLog(\n config,\n 'warn',\n 'graph',\n 'Artifact payload omitted because it exceeds the remaining context budget',\n {\n projectedMessageTokens: projection.projectedMessageTokens,\n availableMessageTokens: projection.availableMessageTokens,\n },\n { runId: this.runId, agentId }\n );\n }\n }\n }\n\n finalMessages = projectProviderReferences(\n applyProviderMessageTransforms(finalMessages)\n );\n let finalProjection = measureProviderPayload(finalMessages);\n if (artifactBaseMessages != null) {\n if (!finalProjection.fits) {\n finalMessages = projectProviderReferences(\n applyProviderMessageTransforms(artifactBaseMessages)\n );\n finalProjection = measureProviderPayload(finalMessages);\n emitAgentLog(\n config,\n 'warn',\n 'graph',\n 'Artifact payload omitted after final provider formatting exceeded the remaining context budget',\n {\n projectedMessageTokens: finalProjection.projectedMessageTokens,\n availableMessageTokens: finalProjection.availableMessageTokens,\n },\n { runId: this.runId, agentId }\n );\n }\n }\n if (!finalProjection.fits) {\n const compacted = compactSyntheticProviderContext(finalMessages);\n if (compacted !== finalMessages) {\n finalMessages = compacted;\n finalProjection = measureProviderPayload(finalMessages);\n emitAgentLog(\n config,\n finalProjection.fits ? 'warn' : 'error',\n 'graph',\n finalProjection.fits\n ? 'Synthetic provider context compacted to fit the final payload budget'\n : 'Final provider payload still exceeds budget after synthetic context compaction',\n {\n projectedMessageTokens: finalProjection.projectedMessageTokens,\n availableMessageTokens: finalProjection.availableMessageTokens,\n },\n { runId: this.runId, agentId }\n );\n }\n }\n\n /**\n * Mistral rejects consecutive user turns outright; Bedrock's Converse\n * API documents strict user/assistant alternation across its model\n * families, with enforcement varying by family (Claude on Converse\n * currently tolerates the shape — verified live — but the payload is\n * normalized for all of them rather than betting on leniency). Four\n * sites can emit them — the `PostToolBatch` and `PreemptBoundary` hook\n * boundaries (a consolidated context message followed by one\n * `HumanMessage` per injected entry), a queue drain carrying more than\n * one steer, and `run.ts`'s pre-stream context push onto a payload that\n * already ends on a user turn.\n *\n * Normalized here, at the last provider-facing hop, rather than at any\n * one boundary: the boundaries must keep per-message identity, because\n * `additional_kwargs.source`/`skillName` drive steer rendering and the\n * trailing-steer anchor downstream. Graph state and the host's\n * persisted messages are untouched — this shapes only what goes on the\n * wire, for the providers that actually care.\n *\n * Runs AFTER synthetic-context compaction: that pass can rewrite or\n * drop messages, so coalescing has to see its output, and it is the\n * last shaping step before the cache breakpoint is chosen.\n */\n if (strictAlternationProviders.has(agentContext.provider)) {\n /**\n * Wrapped like every other provider transform: the merged message is\n * a NEW object, and without re-attachment the final pre-invoke\n * measurement would drop both source turns' calibrated shares and\n * recharge the merge at full raw estimate — enough to flip a\n * just-fits payload (the synthetic-context compaction above binary\n * searches to exactly that) into a spurious pre-invoke overflow. The\n * merge keeps the first source's id, so the keyed branch re-attaches\n * that origin; the absorbed turn's tokens are charged as new raw\n * growth, which only ever under-estimates by less than the old\n * behavior over-estimated.\n */\n const beforeCoalesce = finalMessages;\n finalMessages = trackProviderMessageOrigins(\n beforeCoalesce,\n coalesceAdjacentUserTurns(beforeCoalesce)\n );\n }\n\n // Determine the prompt-cache strategy up front. Two distinct facts:\n //\n // `providerPromptCacheEnabled` — prompt caching is on for this provider\n // at all. This drives orphan cleanup, because EVERY cached send must be\n // sanitized — including the system-runnable path, where AgentContext (not\n // this node) adds the body marker.\n //\n // `willAddTailCache` — THIS node will add the marker itself. Anthropic /\n // OpenRouter defer to the system runnable when one owns the system-prompt\n // breakpoint, so they exclude that case; Bedrock always marks here.\n const anthropicPromptCacheEnabled =\n agentContext.provider === Providers.ANTHROPIC &&\n (agentContext.clientOptions as t.AnthropicClientOptions | undefined)\n ?.promptCache === true;\n const openRouterPromptCacheEnabled =\n agentContext.provider === Providers.OPENROUTER &&\n (\n agentContext.clientOptions as\n | t.ProviderOptionsMap[Providers.OPENROUTER]\n | undefined\n )?.promptCache === true;\n // Message/system cache points work on all cache-capable Bedrock models,\n // including Nova (verified live: HTTP 200 with cacheWriteInputTokens). Only\n // the tool checkpoint is Claude-only, so this is gated on promptCache alone.\n const bedrockPromptCacheEnabled =\n agentContext.provider === Providers.BEDROCK &&\n (\n agentContext.clientOptions as\n | t.BedrockAnthropicClientOptions\n | undefined\n )?.promptCache === true;\n const providerPromptCacheEnabled =\n anthropicPromptCacheEnabled ||\n openRouterPromptCacheEnabled ||\n bedrockPromptCacheEnabled;\n\n // Intentionally broad: runs when the pruner wasn't used, when any\n // post-pruning transform (ensureThinkingBlock, etc.) reassigned\n // finalMessages, OR when this is a prompt-cached send. The last clause\n // matters because the marker is now applied AFTER this gate (and, for the\n // system-runnable path, in AgentContext entirely): without it, a cached\n // send whose pruner returned the context unchanged would skip cleanup and\n // could ship orphaned AI/tool pairs from persisted history.\n // sanitizeOrphanToolBlocks fast-paths to a Set diff check when no orphans\n // exist, so the cost is negligible.\n const needsOrphanSanitize =\n anthropicLike &&\n (!agentContext.pruneMessages ||\n finalMessages !== messagesToUse ||\n providerPromptCacheEnabled);\n if (needsOrphanSanitize) {\n const beforeSanitize = finalMessages.length;\n const beforeSanitizeMessages = finalMessages;\n finalMessages = trackProviderMessageOrigins(\n beforeSanitizeMessages,\n sanitizeOrphanToolBlocks(beforeSanitizeMessages, (source, clone) => {\n const origin = providerMessageOrigins.get(source);\n if (origin != null) {\n providerMessageOrigins.set(clone, origin);\n }\n })\n );\n if (finalMessages.length !== beforeSanitize) {\n emitAgentLog(\n config,\n 'warn',\n 'sanitize',\n 'Orphan tool blocks removed',\n {\n before: beforeSanitize,\n after: finalMessages.length,\n dropped: beforeSanitize - finalMessages.length,\n },\n { runId: this.runId, agentId }\n );\n }\n }\n\n // Place the single tail prompt-cache breakpoint LAST, after thinking\n // normalization and orphan sanitization. ensureThinkingBlockInMessages can\n // fold a trailing non-thinking AI→Tool chain into a `[Previous agent\n // context]` HumanMessage whose builder copies text but not cache_control /\n // cachePoint, and sanitizeOrphanToolBlocks can drop the anchored block — so\n // marking earlier would let the only breakpoint vanish before the model\n // call (zero message caching). Anchoring on the final message list keeps\n // the marker on a block that actually ships. The system-runnable path\n // adds its body marker in AgentContext, so this node skips it there.\n if (\n (anthropicPromptCacheEnabled || openRouterPromptCacheEnabled) &&\n !agentContext.systemRunnable\n ) {\n const beforeCacheControl = finalMessages;\n finalMessages = trackProviderMessageOrigins(\n beforeCacheControl,\n addTailCacheControl<BaseMessage>(\n beforeCacheControl,\n resolvePromptCacheTtl(\n anthropicPromptCacheEnabled\n ? (\n agentContext.clientOptions as\n | t.AnthropicClientOptions\n | undefined\n )?.promptCacheTtl\n : (\n agentContext.clientOptions as\n | t.ProviderOptionsMap[Providers.OPENROUTER]\n | undefined\n )?.promptCacheTtl\n )\n )\n );\n } else if (bedrockPromptCacheEnabled) {\n const bedrockOptions = agentContext.clientOptions as\n | t.BedrockAnthropicClientOptions\n | undefined;\n // Non-Claude models (Nova) reject the extended 1h TTL, so resolve it\n // against the model — message/system caching stays on, clamped to 5m.\n const beforeCacheControl = finalMessages;\n finalMessages = trackProviderMessageOrigins(\n beforeCacheControl,\n addBedrockTailCacheControl<BaseMessage>(\n beforeCacheControl,\n resolveBedrockPromptCacheTtl(\n bedrockOptions?.promptCacheTtl,\n (bedrockOptions as { model?: string } | undefined)?.model\n )\n )\n );\n }\n\n const fallbackBaseMessages = finalMessages;\n const beforeFinalProviderProjection = fallbackBaseMessages;\n finalMessages = trackProviderMessageOrigins(\n beforeFinalProviderProjection,\n projectMessagesForProvider({\n model: (this.overrideModel ?? model) as t.ChatModel,\n messages: beforeFinalProviderProjection,\n provider: agentContext.provider,\n maxToolResultChars: maxProviderToolResultChars,\n callOptions: config,\n })\n );\n\n /**\n * Prompt-cache placement and orphan sanitization are provider-wire\n * transforms too. Re-measure after both so no content added after the\n * earlier artifact/synthetic compaction decision can bypass the guard.\n */\n finalProjection = measureProviderPayload(finalMessages);\n const preInvokeContextOverflowError = !finalProjection.fits\n ? createProviderPayloadOverflowError({\n projection: finalProjection,\n provider: agentContext.provider,\n info: 'Provider message formatting exceeded the context budget and no safe synthetic-context compaction could make it fit.',\n })\n : undefined;\n\n if (\n agentContext.lastStreamCall != null &&\n agentContext.streamBuffer != null\n ) {\n const timeSinceLastCall = Date.now() - agentContext.lastStreamCall;\n if (timeSinceLastCall < agentContext.streamBuffer) {\n const timeToWait =\n Math.ceil((agentContext.streamBuffer - timeSinceLastCall) / 1000) *\n 1000;\n await sleep(timeToWait);\n }\n }\n\n agentContext.lastStreamCall = Date.now();\n agentContext.markTokensStale();\n\n let result: Partial<t.BaseGraphState> | undefined;\n const fallbacks =\n (agentContext.clientOptions as t.LLMConfig | undefined)?.fallbacks ??\n [];\n\n if (\n finalMessages.length === 0 &&\n !agentContext.hasPendingCompactionSummary()\n ) {\n const budgetBreakdown = agentContext.getTokenBudgetBreakdown(messages);\n const breakdown = agentContext.formatTokenBudgetBreakdown(messages);\n const instructionsExceedBudget =\n budgetBreakdown.instructionTokens > budgetBreakdown.maxContextTokens;\n\n let guidance: string;\n if (instructionsExceedBudget) {\n const toolPct =\n budgetBreakdown.toolSchemaTokens > 0\n ? Math.round(\n (budgetBreakdown.toolSchemaTokens /\n budgetBreakdown.instructionTokens) *\n 100\n )\n : 0;\n guidance =\n toolPct > 50\n ? `Tool definitions consume ${budgetBreakdown.toolSchemaTokens} tokens (${toolPct}% of instructions) across ${budgetBreakdown.toolCount} tools, exceeding maxContextTokens (${budgetBreakdown.maxContextTokens}). Reduce the number of tools or increase maxContextTokens.`\n : `Instructions (${budgetBreakdown.instructionTokens} tokens) exceed maxContextTokens (${budgetBreakdown.maxContextTokens}). Increase maxContextTokens or shorten the system prompt.`;\n if (agentContext.summarizationEnabled === true) {\n guidance +=\n ' Summarization was skipped because the summary would further increase the instruction overhead.';\n }\n } else {\n guidance =\n 'Please increase the context window size or make your message shorter.';\n }\n\n emitAgentLog(\n config,\n 'error',\n 'graph',\n 'Empty messages after pruning',\n {\n messageCount: messages.length,\n instructionsExceedBudget,\n breakdown,\n },\n { runId: this.runId, agentId }\n );\n throw new Error(\n JSON.stringify({\n type: 'empty_messages',\n info: `Message pruning removed all messages as none fit in the context window. ${guidance}\\n${breakdown}`,\n })\n );\n }\n\n /** Past the empty-prompt guard — a model call is now guaranteed */\n if (contextUsage != null) {\n if (\n finalProjection.projectedMessageTokens != null &&\n finalProjection.availableMessageTokens != null\n ) {\n contextUsage.breakdown.messageCount = finalMessages.length;\n contextUsage.remainingContextTokens = Math.max(\n 0,\n finalProjection.availableMessageTokens -\n finalProjection.projectedMessageTokens\n );\n }\n syncBudgetDerivedFields(contextUsage);\n /** Awaited so async host handlers receive the pre-invoke snapshot\n * before any model deltas are emitted */\n await safeDispatchCustomEvent(\n GraphEvents.ON_CONTEXT_USAGE,\n contextUsage,\n config\n );\n }\n\n const invokeStart = Date.now();\n const invokeMeta = { runId: this.runId, agentId };\n emitAgentLog(\n config,\n 'debug',\n 'graph',\n 'Invoking LLM',\n {\n messageCount: finalMessages.length,\n provider: agentContext.provider,\n },\n invokeMeta,\n { force: true }\n );\n\n const langfuse = resolveLangfuseConfig(\n this.langfuse,\n agentContext.langfuse\n );\n const traceMetadata = createLangfuseTraceMetadata({\n messageId: this.runId,\n parentMessageId: config.configurable?.requestBody?.parentMessageId,\n agentId,\n agentName: agentContext.name,\n });\n let langfuseHandler: CallbackEntry | undefined;\n let invokeConfig = {\n ...config,\n /** The run-scoped breaker composed in, so a stream-limit trip in one\n * parallel agent node also cancels sibling nodes' in-flight model\n * calls, not only their subagents. */\n signal: composeAbortSignals(config.signal, attemptBreaker.signal),\n metadata: {\n ...(config.metadata ?? {}),\n ...traceMetadata,\n /** Canonical agent identity, stamped OUTSIDE trace-metadata\n * filtering: `createLangfuseTraceMetadata` drops values over its\n * length cap, but scope trust (`isForeignScope`) needs the id\n * verbatim regardless of length. */\n agentId,\n [STREAM_LIMIT_EPOCH_KEY]: attemptBreakerEpoch,\n },\n };\n initializeLangfuseTracing(langfuse);\n if (findCallback(config.callbacks, isLangfuseCallbackHandler) == null) {\n langfuseHandler = createLangfuseHandler({\n langfuse,\n userId: config.configurable?.user_id as string | undefined,\n sessionId: config.configurable?.thread_id as string | undefined,\n traceMetadata,\n tags: ['librechat', 'agent'],\n traceIdSeed:\n langfuse?.deterministicTraceId === true ? this.runId : undefined,\n runId: this.langfuseScopeRunId,\n toolOutputTracing: hasToolOutputTracingConfig(\n this.langfuse,\n agentContext.langfuse\n )\n ? resolveToolOutputTracingConfig(\n this.langfuse,\n agentContext.langfuse\n )\n : undefined,\n });\n if (langfuseHandler != null) {\n invokeConfig = {\n ...invokeConfig,\n callbacks: appendCallbacks(invokeConfig.callbacks, [\n langfuseHandler,\n ]),\n };\n }\n }\n const metadata = config.metadata as Record<string, unknown>;\n\n try {\n if (preInvokeContextOverflowError != null) {\n throw preInvokeContextOverflowError;\n }\n /** Rechecked after the pre-invoke awaits (context-usage dispatch,\n * hooks): a sibling can trip the breaker while this node is paused\n * in one of them, and a provider that doesn't synchronously reject\n * an aborted signal would still start the request. */\n {\n const preInvokeTrip = this.resolveTrippedBreakerReason(\n attemptBreaker.signal\n );\n if (preInvokeTrip != null) {\n throw preInvokeTrip;\n }\n }\n result = await withLangfuseRuntimeScope(\n resolveLangfuseRuntimeScope({\n runLangfuse: this.langfuse,\n langfuseOverlay: agentContext.langfuse,\n runId: this.langfuseScopeRunId,\n agentId,\n }),\n () =>\n attemptInvoke(\n {\n model: (this.overrideModel ?? model) as t.ChatModel,\n messages: finalMessages,\n provider: agentContext.provider,\n context: this,\n },\n invokeConfig\n )\n );\n } catch (primaryError) {\n clearCurrentDeltaStepMarkers({\n graph: this,\n metadata,\n });\n /**\n * A tripped stream circuit breaker is a deliberate abort, not a\n * provider failure: entering overflow recovery or the fallback chain\n * would spend more provider work after the safety limit fired, and a\n * succeeding fallback would resolve a run the public contract says\n * must reject. Rethrow before any recovery path.\n */\n if (primaryError instanceof StreamLimitExceededError) {\n /** Tripped before rethrowing so parallel agent nodes' in-flight\n * model calls and subagents stop while the rejection propagates. */\n attemptBreaker.abort(primaryError);\n throw primaryError;\n }\n /** A sibling that tripped the shared breaker aborts this branch's\n * composed signal, and some providers surface that as a generic\n * abort error; entering overflow planning or the fallback chain\n * would start new provider work after the run-wide breaker fired.\n * Rethrow the breaker's own stream-limit reason instead. */\n {\n const trippedReason = this.resolveTrippedBreakerReason(\n attemptBreaker.signal\n );\n if (trippedReason != null) {\n throw trippedReason;\n }\n }\n /**\n * A context overflow is a deterministic consequence of the payload,\n * not a provider being unavailable — so it is answered by compacting\n * and retrying rather than by re-sending the same oversized prompt\n * down the fallback chain. Fallbacks still run for every other\n * failure, and for an overflow whose recovery budget is spent.\n */\n /**\n * Compaction has to have something to work with. Without a token\n * counter there is no pruner, and with summarization disabled the\n * summarize node deliberately no-ops — so in that combination the\n * retry would resend a byte-identical prompt. Skipping the detour\n * keeps the original error and one round trip instead of three.\n */\n const estimatedPromptTokens = getEstimatedPromptTokens(contextUsage);\n\n const canSummarizeOverflow =\n agentContext.summarizationEnabled === true &&\n splitAtRecencyBoundary(messages, {\n turns:\n agentContext.summarizationConfig?.retainRecent?.turns ??\n DEFAULT_RETAIN_RECENT_TURNS,\n tokens: agentContext.summarizationConfig?.retainRecent?.tokens,\n tokenCounter: agentContext.tokenCounter,\n }).head.length > 0;\n\n const getLocalProviderOverflowMeasurement = (\n error: unknown\n ):\n | {\n contextBudget: number;\n estimatedPromptTokens: number;\n }\n | undefined =>\n typeof error === 'object' && error !== null\n ? localProviderOverflowMeasurements.get(error)\n : undefined;\n\n const getRecoveryPromptEstimate = (\n error: unknown,\n fallbackContext?: FallbackErrorContext\n ): number | undefined => {\n const resolvedFallbackContext =\n fallbackContext ?? getFallbackErrorContext(error);\n return (\n getLocalProviderOverflowMeasurement(error)?.estimatedPromptTokens ??\n (resolvedFallbackContext == null\n ? estimatedPromptTokens\n : undefined)\n );\n };\n\n const planRecovery = (\n error: unknown,\n attributedFallbackContext?: FallbackErrorContext\n ): OverflowRecoveryPlan | null => {\n /**\n * When the rejection came from a fallback, plan against *that*\n * client: its window and output allowance are why it was configured\n * as an alternative in the first place.\n */\n const fallbackContext =\n attributedFallbackContext ?? getFallbackErrorContext(error);\n const localMeasurement = getLocalProviderOverflowMeasurement(error);\n const recoveryPromptEstimate = getRecoveryPromptEstimate(\n error,\n fallbackContext\n );\n /**\n * A previous correction that left the rejected prompt no smaller\n * proves this state has nothing left to compact. Use the fallback\n * projection when one exists so unlike provider formats are never\n * compared through the primary's cheaper pre-projection estimate.\n */\n if (agentContext.overflowRecoveryStalled(recoveryPromptEstimate)) {\n return null;\n }\n const recovery = planContextOverflowRecovery({\n error,\n provider: fallbackContext?.provider ?? agentContext.provider,\n maxContextTokens:\n localMeasurement?.contextBudget ??\n fallbackContext?.maxContextTokens ??\n agentContext.maxContextTokens,\n estimatedPromptTokens: recoveryPromptEstimate,\n calibrationRatio: agentContext.calibrationRatio,\n instructionTokens: agentContext.instructionTokens,\n canSummarize: agentContext.summarizationEnabled === true,\n configuredCompletionTokens: getConfiguredCompletionTokens(\n fallbackContext?.clientOptions ?? agentContext.clientOptions\n ),\n attemptsSoFar: agentContext.overflowRecoveryAttempts,\n });\n if (recovery == null) {\n return null;\n }\n const translatedRecovery =\n fallbackContext != null\n ? {\n ...recovery,\n budgetTokens: minDefined(\n getBlindRecoveryBudget(agentContext.maxContextTokens),\n localMeasurement != null\n ? recovery.budgetTokens\n : translateRecoveryBudget(\n recovery.budgetTokens,\n recovery.observedCalibrationRatio ??\n CALIBRATION_RATIO_MAX,\n agentContext.calibrationRatio\n )\n ),\n observedCalibrationRatio: undefined,\n }\n : recovery;\n const canReduceContext =\n canSummarizeOverflow ||\n (agentContext.tokenCounter != null &&\n translatedRecovery.budgetTokens != null);\n return canReduceContext ? translatedRecovery : null;\n };\n\n const recovery = planRecovery(primaryError);\n if (recovery != null) {\n const recoveryPromptEstimate =\n getRecoveryPromptEstimate(primaryError);\n return this.beginOverflowRecovery({\n recovery,\n agentContext,\n agentId,\n config,\n originalToolContent: prunedOriginalToolContent,\n estimatedPromptTokens: recoveryPromptEstimate,\n });\n }\n /**\n * A fallback can reject the same prompt as too large even when the\n * primary failed for an unrelated reason — a fallback with a smaller\n * window is the obvious case. Planning against the exhausted-chain\n * error keeps that path recoverable instead of surfacing it.\n */\n try {\n result = await withLangfuseRuntimeScope(\n resolveLangfuseRuntimeScope({\n runLangfuse: this.langfuse,\n langfuseOverlay: agentContext.langfuse,\n runId: this.langfuseScopeRunId,\n agentId,\n }),\n () =>\n tryFallbackProviders({\n fallbacks,\n tools: agentContext.tools,\n messages: fallbackBaseMessages,\n config: invokeConfig,\n primaryError,\n context: this,\n /**\n * Lets the chain recognise a fallback overflow whose signature\n * carries no reason of its own (Vertex AI's bare 400) and\n * surface it rather than a later unrelated failure.\n */\n overflowContext: {\n provider: agentContext.provider,\n estimatedPromptTokens: getEstimatedPromptTokens(contextUsage),\n maxContextTokens: agentContext.maxContextTokens,\n },\n prepareProviderMessages: ({\n model: fallbackModel,\n messages: fallbackMessages,\n provider: fallbackProvider,\n maxContextTokens: fallbackMaxContextTokens,\n config: fallbackConfig,\n }) => {\n const fallbackToolResultChars =\n agentContext.maxToolResultChars ??\n calculateMaxToolResultChars(\n fallbackMaxContextTokens ?? agentContext.maxContextTokens\n );\n /**\n * Serving-provider cue shaping BEFORE the fallback payload\n * is measured: a Claude fallback behind a tolerant primary\n * gains the cue inside the guarded projection (a prompt\n * within the cue's cost of the fallback budget must take\n * the recovery path, not ship oversized), and a tolerant\n * fallback behind an Anthropic primary sheds the baked cue\n * before it is measured against the tighter budget. The\n * attemptInvoke funnel pass then finds nothing to change.\n */\n const cueShapedFallbackMessages = trackProviderMessageOrigins(\n fallbackMessages,\n isAnthropicLike(fallbackProvider, {\n model: resolveServingModelId(fallbackModel),\n })\n ? appendPredecessorHandoffCue(fallbackMessages, (m) =>\n this.isRunProducedMessage(m)\n )\n : removePredecessorHandoffCue(fallbackMessages)\n );\n const projectedFallbackMessages = trackProviderMessageOrigins(\n cueShapedFallbackMessages,\n projectMessagesForProvider({\n model: fallbackModel,\n messages: cueShapedFallbackMessages,\n provider: fallbackProvider,\n maxToolResultChars: fallbackToolResultChars,\n callOptions: fallbackConfig,\n })\n );\n const primaryContextBudget = contextUsage?.contextBudget;\n const fallbackContextBudget =\n fallbackMaxContextTokens == null\n ? primaryContextBudget\n : Math.min(\n primaryContextBudget ?? fallbackMaxContextTokens,\n fallbackMaxContextTokens\n );\n const projection = measureProviderPayload(\n projectedFallbackMessages,\n fallbackContextBudget,\n true\n );\n if (!projection.fits) {\n throw createProviderPayloadOverflowError({\n projection,\n provider: fallbackProvider,\n info: 'Fallback provider message formatting exceeded the context budget before invocation.',\n });\n }\n return projectedFallbackMessages;\n },\n })\n );\n } catch (fallbackError) {\n if (fallbackError instanceof StreamLimitExceededError) {\n /** Same treatment as the primary path: a fallback stream that\n * trips the breaker must stop parallel agent nodes' model calls\n * and subagents before the rejection propagates. */\n attemptBreaker.abort(fallbackError);\n throw fallbackError;\n }\n {\n /** Same sibling-abort translation guard as the primary catch. */\n const trippedReason = this.resolveTrippedBreakerReason(\n attemptBreaker.signal\n );\n if (trippedReason != null) {\n throw trippedReason;\n }\n }\n const overflowCandidates =\n getFallbackOverflowCandidates(fallbackError);\n let fallbackRecovery: OverflowRecoveryPlan | null = null;\n let fallbackRecoveryPromptEstimate: number | undefined;\n for (const candidate of overflowCandidates) {\n fallbackRecovery = planRecovery(candidate.error, candidate.context);\n if (fallbackRecovery != null) {\n fallbackRecoveryPromptEstimate = getRecoveryPromptEstimate(\n candidate.error,\n candidate.context\n );\n break;\n }\n }\n if (overflowCandidates.length === 0) {\n fallbackRecovery = planRecovery(fallbackError);\n fallbackRecoveryPromptEstimate =\n getRecoveryPromptEstimate(fallbackError);\n }\n if (fallbackRecovery == null) {\n throw fallbackError;\n }\n return this.beginOverflowRecovery({\n recovery: fallbackRecovery,\n agentContext,\n agentId,\n config,\n originalToolContent: prunedOriginalToolContent,\n estimatedPromptTokens: fallbackRecoveryPromptEstimate,\n });\n }\n } finally {\n await disposeLangfuseHandler(langfuseHandler);\n }\n\n if (!result) {\n throw new Error('No result after model invocation');\n }\n\n /**\n * Fallback: populate toolCallStepIds in the graph execution context.\n *\n * When model.stream() is available (the common case), attemptInvoke\n * processes all chunks through a local ChatModelStreamHandler which\n * creates run steps and populates toolCallStepIds before returning.\n * The code below is a fallback for the rare case where model.stream\n * is unavailable and model.invoke() was used instead.\n *\n * Text content is dispatched FIRST so that MESSAGE_CREATION is the\n * current step when handleToolCalls runs. handleToolCalls then creates\n * TOOL_CALLS on top of it. The dedup in getMessageId and\n * toolCallStepIds.has makes this safe when attemptInvoke already\n * handled everything — both paths become no-ops.\n */\n const responseMessage = result.messages?.[0];\n /**\n * Provenance for the handoff-cue gate: recorded at the node, where the\n * produced turn is unambiguous. The public ChatModel contract does not\n * require implementations to set message ids — the reducer would\n * assign one AFTER this node returns, which is too late for the set —\n * so an id is assigned here first, the same way the reducer does it\n * (`v4()`, mirrored into `lc_kwargs`), and the reducer's\n * keep-existing-id rule makes the state message match.\n */\n if (responseMessage?.getType() === 'ai') {\n if (\n typeof responseMessage.id !== 'string' ||\n responseMessage.id === ''\n ) {\n responseMessage.id = v4();\n responseMessage.lc_kwargs.id = responseMessage.id;\n }\n this.runProducedAiMessageIds.add(responseMessage.id);\n }\n const toolCalls = (responseMessage as AIMessageChunk | undefined)\n ?.tool_calls;\n const hasToolCalls = Array.isArray(toolCalls) && toolCalls.length > 0;\n const responseReasoningContent = getResponseReasoningContent({\n responseMessage: responseMessage as Partial<AIMessageChunk> | undefined,\n reasoningKey: agentContext.reasoningKey,\n });\n const textMessageContent = getMessageDeltaContent(\n agentContext.provider,\n responseMessage?.content as MessageContent | undefined\n );\n const hasStreamedTextDeltaStep = hasCurrentTextDeltaStep({\n graph: this,\n metadata,\n });\n const hasStreamedReasoningDeltaStep = hasCurrentReasoningDeltaStep({\n graph: this,\n metadata,\n });\n const dispatchableFinalReasoningContent =\n getDispatchableFinalReasoningContent({\n agentContext,\n responseReasoningContent,\n hasStreamedTextDeltaStep,\n hasStreamedReasoningDeltaStep,\n });\n\n if (hasToolCalls) {\n const dispatchedReasoning =\n dispatchableFinalReasoningContent != null &&\n (await dispatchReasoningContent({\n graph: this,\n agentContext,\n reasoningContent: dispatchableFinalReasoningContent,\n metadata,\n }));\n if (dispatchedReasoning) {\n markPostReasoningContent(agentContext);\n }\n if (textMessageContent != null && !hasStreamedTextDeltaStep) {\n const stepKey = this.getStepKey(metadata);\n const dispatchedText = await dispatchTextMessageContent({\n graph: this,\n stepKey,\n provider: agentContext.provider,\n content: textMessageContent,\n metadata,\n });\n if (dispatchedText) {\n markPostReasoningContent(agentContext);\n }\n }\n\n await handleToolCalls(toolCalls as ToolCall[], metadata, this);\n }\n\n /**\n * When streaming events are unavailable, ChatModelStreamHandler never\n * fires. Dispatch final reasoning/text content here. getMessageId makes\n * this a no-op when the streaming path already handled the same step.\n */\n if (!hasToolCalls && responseMessage != null) {\n const dispatchedReasoning =\n dispatchableFinalReasoningContent != null &&\n (await dispatchReasoningContent({\n graph: this,\n agentContext,\n reasoningContent: dispatchableFinalReasoningContent,\n metadata,\n }));\n if (dispatchedReasoning && textMessageContent != null) {\n markPostReasoningContent(agentContext);\n }\n if (textMessageContent != null && !hasStreamedTextDeltaStep) {\n const stepKey = this.getStepKey(metadata);\n await dispatchTextMessageContent({\n graph: this,\n stepKey,\n provider: agentContext.provider,\n content: textMessageContent,\n metadata,\n });\n }\n }\n\n const invokeElapsed = ((Date.now() - invokeStart) / 1000).toFixed(2);\n agentContext.currentUsage = this.getUsageMetadata(result.messages?.[0]);\n /**\n * Synthetic usage from a sealed turn is an estimate derived from the\n * host's own counter, so feeding it to calibration would teach a ratio\n * of exactly 1.0 — self-consistent by construction, and wrong for any\n * provider whose real ratio differs. It still flows to `currentUsage`\n * for host billing; it just does not get to move the EMA.\n */\n const estimatedUsage =\n (result.messages?.[0] as AIMessageChunk | undefined)?.response_metadata\n .estimated_usage === true;\n if (agentContext.currentUsage) {\n if (!estimatedUsage) {\n agentContext.updateLastCallUsage(agentContext.currentUsage);\n }\n emitAgentLog(\n config,\n 'debug',\n 'graph',\n `LLM call complete (${invokeElapsed}s)`,\n {\n ...agentContext.currentUsage,\n elapsedSeconds: Number(invokeElapsed),\n instructionTokens: agentContext.instructionTokens,\n toolSchemaTokens: agentContext.toolSchemaTokens,\n messageCount: finalMessages.length,\n },\n invokeMeta,\n { force: true }\n );\n } else {\n emitAgentLog(\n config,\n 'debug',\n 'graph',\n `LLM call complete (${invokeElapsed}s)`,\n {\n elapsedSeconds: Number(invokeElapsed),\n messageCount: finalMessages.length,\n },\n invokeMeta,\n { force: true }\n );\n }\n if (\n (responseMessage as AIMessageChunk | undefined)?.response_metadata\n .preempted === true\n ) {\n const { messages: injected, preventContinuation } =\n await this.dispatchPreemptBoundary(agentId, config);\n /**\n * Release before branching: the slot is held only for the duration of\n * the drain, and an early return below must not strand it.\n */\n this.releasePreemptSeal();\n if (preventContinuation) {\n /**\n * A hook halted at the boundary. Commit the sealed turn and anything\n * it injected, but do NOT self-loop: `preventContinuation` promises\n * no further model turn, and the run-loop poll in `processStream`\n * only sees the halt AFTER the next call would already have started\n * — direct graph consumers never poll it at all. A trailing injected\n * HumanMessage carries no tool calls, so `toolsCondition` routes it\n * to END.\n */\n this.preemptIncomplete = true;\n /**\n * A halting boundary that ALSO injected nothing is still an empty\n * boundary by the `getPreemptStats().emptyBoundaries` contract —\n * hosts use the counter for truncated-seal telemetry, and both\n * paths end the turn with nothing to resume from.\n */\n if (injected.length === 0) {\n this.preemptEmptyBoundaries += 1;\n }\n this.cleanupSignalListener();\n return injected.length > 0\n ? { messages: [...(result.messages ?? []), ...injected] }\n : result;\n }\n if (injected.length > 0) {\n this.pendingPreemptReturn.add(agentId);\n this.cleanupSignalListener();\n return { messages: [...(result.messages ?? []), ...injected] };\n }\n /**\n * Nothing to inject — the host cancelled or already drained. Do NOT\n * self-loop: a trailing model turn with no new input is dropped by\n * some Gemini models and read as prefill by Anthropic. Do NOT pretend\n * the turn completed either; the answer really was cut short.\n */\n this.preemptEmptyBoundaries += 1;\n this.preemptIncomplete = true;\n }\n\n this.cleanupSignalListener();\n return result;\n };\n }\n\n /**\n * Fires `PreemptBoundary` after a sealed turn and returns whatever the\n * hooks asked to inject, converted through the same `convertInjectedMessages`\n * the tool boundary uses so the two sites cannot emit different shapes.\n *\n * Never throws: a drain that fails or times out costs the injection, not the\n * run. The caller treats an empty result as \"nothing to resume with\".\n *\n * `preventContinuation` is surfaced alongside the messages rather than left\n * to the registry halt signal, which `processStream` only polls between\n * stream events — by then the self-loop it was meant to prevent has already\n * issued another model call, and a direct graph consumer never polls it.\n */\n private async dispatchPreemptBoundary(\n agentId: string,\n config: RunnableConfig | undefined\n ): Promise<PreemptBoundaryResult> {\n if (this.hookRegistry == null) {\n return EMPTY_PREEMPT_BOUNDARY;\n }\n const configurable = config?.configurable;\n const runId = (configurable?.run_id as string | undefined) ?? this.runId;\n if (runId == null) {\n return EMPTY_PREEMPT_BOUNDARY;\n }\n const result = await executeHooks({\n registry: this.hookRegistry,\n input: {\n hook_event_name: 'PreemptBoundary',\n runId,\n threadId: configurable?.thread_id as string | undefined,\n agentId: this.subagentScope ? agentId : undefined,\n executingAgentId: agentId,\n sealCount: this.preemptSealCount,\n },\n sessionId: runId,\n timeoutMs: PREEMPT_BOUNDARY_HOOK_TIMEOUT_MS,\n /**\n * The host's own abort signal(s), deliberately NOT `config.signal` —\n * inside a node the latter is LangGraph's composed signal, which also\n * fires when an unrelated sibling in the same superstep throws.\n * Cancellation already returns control in milliseconds without this;\n * what it buys is that a drain does not keep running after the run it\n * belongs to died.\n *\n * Composed because the host can cancel through either channel: the\n * construction signal, or the per-call `callerConfig.signal` — the only\n * one a multi-agent run has, since `MultiAgentGraphConfig` exposes no\n * construction signal. When both exist they may be different\n * controllers, and a drain must stop when EITHER fires.\n */\n signal: composeAbortSignals(this.signal, this.callerSignal),\n }).catch((): undefined => undefined);\n if (result == null) {\n return EMPTY_PREEMPT_BOUNDARY;\n }\n /**\n * `executeHooks` raises a registry halt whenever a hook returns\n * `preventContinuation`. That halt has exactly one consumer — the poll in\n * `Run.processStream` — and its `break` cancels the stream iterator, which\n * aborts Pregel. The abort lands BEFORE the outer reducer commits\n * `StandardGraph.messages`, so honoring the halt here would destroy the\n * sealed assistant turn: the run returns empty content and the host\n * persists nothing. Measured deterministically — the commit is several\n * stream events downstream of the point the halt becomes observable.\n *\n * The `preventContinuation` branch in `createCallModel` already enforces\n * the contract locally by declining to self-loop, and a sealed chunk\n * provably carries no tool calls, so the turn routes to END after exactly\n * one model call either way. Clearing the halt therefore costs nothing it\n * was buying and saves the content the seal exists to preserve.\n *\n * Scoped to a halt this event raised, so a halt from an earlier hook in\n * the same run — `haltRun` is first-write-wins — is left alone.\n */\n const halt = this.hookRegistry.getHaltSignal(runId);\n if (\n result.preventContinuation === true &&\n halt?.source === 'PreemptBoundary'\n ) {\n this.preemptHaltReason = halt.reason;\n this.hookRegistry.clearHaltSignal(runId);\n }\n const injected: BaseMessage[] = [];\n /**\n * `PreemptBoundaryHookOutput` is `BaseHookOutput`, so `additionalContext`\n * is part of the contract here just as it is at the tool boundary. It has\n * to be materialized BEFORE the emptiness test, or a hook that returns\n * context alone would read as \"nothing to resume with\" and cut the answer\n * short. Same system-flavored `HumanMessage` convention `ToolNode` uses —\n * Anthropic and Google reject a mid-conversation `SystemMessage`.\n */\n /**\n * Whitespace-only entries are dropped for the same reason empty\n * `injectedMessages` are: `executeHooks` keeps them because their raw\n * length is nonzero, but a blank turn is not something to resume from —\n * it costs a model call and strict providers reject it outright.\n */\n const contexts = result.additionalContexts.filter(\n (context) => context.trim() !== ''\n );\n if (contexts.length > 0) {\n injected.push(\n new HumanMessage({\n content: contexts.join('\\n\\n'),\n additional_kwargs: { role: 'system', isMeta: true, source: 'hook' },\n })\n );\n }\n if (result.injectedMessages.length > 0) {\n try {\n injected.push(...convertInjectedMessages(result.injectedMessages));\n } catch (e) {\n console.warn(\n '[StandardGraph] Failed to convert PreemptBoundary injectedMessages:',\n e instanceof Error ? e.message : e\n );\n }\n }\n return {\n messages: injected,\n preventContinuation: result.preventContinuation === true,\n };\n }\n\n createAgentNode(agentId: string): t.CompiledAgentWorfklow {\n const getConfig = (): RunnableConfig | undefined => this.config;\n const agentContext = this.agentContexts.get(agentId);\n if (!agentContext) {\n throw new Error(`Agent context not found for agentId: ${agentId}`);\n }\n\n /**\n * Depth countdown across graph boundaries: the parent's `maxSubagentDepth`\n * becomes this executor's `maxDepth`. When the child graph is constructed,\n * `buildChildInputs()` decrements `maxSubagentDepth` on the child's\n * `AgentInputs` (only when `allowNested: true`; otherwise subagentConfigs\n * are stripped entirely). The child graph's own `createAgentNode()` then\n * reads the decremented value here and creates a narrower executor —\n * recursion is bounded even though each graph has its own separate\n * executor instance.\n */\n const effectiveSubagentDepth = agentContext.maxSubagentDepth ?? 1;\n if (\n agentContext.subagentConfigs != null &&\n agentContext.subagentConfigs.length > 0 &&\n effectiveSubagentDepth > 0\n ) {\n const executableConfigs = normalizeSubagentConfigEntries(\n agentContext.subagentConfigs,\n agentContext\n );\n if (executableConfigs.length > 0) {\n if (\n !this.supportsMultiAgentChildren &&\n executableConfigs.some(isGraphSubagentConfig)\n ) {\n throw new Error(\n 'Graph subagents require constructing the parent with createGraph() or an injected GraphFactory dependency.'\n );\n }\n const getParentHandlerRegistry = (): HandlerRegistry | undefined =>\n this.handlerRegistry ?? this.parentToolHandlerRegistry;\n const createConfiguredChildGraph: GraphFactory = (request) => {\n const childGraph = this.graphFactory(request);\n if (this.subagentModelOverride != null) {\n childGraph.overrideModel = this.subagentModelOverride;\n childGraph.setSubagentModelOverride(this.subagentModelOverride);\n }\n const childHandlerRegistry = createChildHandlerRegistry(\n getParentHandlerRegistry()\n );\n // Pure execution-ordering hint (unlike `humanInTheLoop`). It only\n // reorders tools already in the child's direct group; it does not\n // force a schema-only event tool onto the direct execution path.\n applyGraphRuntimeConfig(childGraph, {\n hookRegistry: this.hookRegistry,\n humanInTheLoop: this.humanInTheLoop,\n toolOutputReferences: this.toolOutputReferences,\n eagerEventToolExecution: this.eagerEventToolExecution,\n codeSessionToolNames: this.codeSessionToolNames,\n interruptingToolNames: this.interruptingToolNames,\n toolExecution: this.toolExecution,\n });\n if (this.humanInTheLoop?.enabled === true) {\n childGraph.compileOptions = {\n checkpointer: this.compileOptions?.checkpointer,\n };\n }\n childGraph.parentToolHandlerRegistry = childHandlerRegistry;\n childGraph.eventToolExecutionAvailable =\n childHandlerRegistry?.getHandler(GraphEvents.ON_TOOL_EXECUTE) !=\n null;\n return childGraph;\n };\n const executor = new SubagentExecutor({\n configs: new Map(\n executableConfigs.map((config) => [config.type, config])\n ),\n parentSignal: this.signal,\n breakerScope: {\n controller: (): AbortController => this.breakerAbort,\n },\n hookRegistry: this.hookRegistry,\n /** Lazy — Run wires the registry onto the graph AFTER\n * `createWorkflow()` runs, so a direct capture here would be\n * `undefined` at construction time. */\n parentHandlerRegistry: getParentHandlerRegistry,\n parentRunId: this.runId ?? '',\n parentAgentId: agentContext.agentId,\n executionContext: this.subagentExecutionContext,\n langfuse: this.langfuse,\n tokenCounter: agentContext.tokenCounter,\n usageSink: this.subagentUsageSink,\n streamLimits: this.streamLimits,\n humanInTheLoop: this.humanInTheLoop,\n checkpointer: this.compileOptions?.checkpointer,\n maxDepth: effectiveSubagentDepth,\n createChildGraph: (input): StandardGraph =>\n createConfiguredChildGraph({\n kind: 'standard',\n input,\n }),\n createChildGraphByKind: createConfiguredChildGraph,\n });\n this.registerSubagentExecutor(executor);\n\n const subagentTool = tool(async (rawInput, config) => {\n const input = rawInput as {\n description?: string;\n subagent_type?: string;\n };\n const description =\n typeof input.description === 'string' &&\n input.description.trim().length > 0\n ? input.description\n : DEFAULT_SUBAGENT_DESCRIPTION;\n const subagentType =\n typeof input.subagent_type === 'string' ? input.subagent_type : '';\n const threadId = config.configurable?.thread_id as string | undefined;\n /** Surface the parent call id so child checkpoints, interrupts, and\n * update events remain correlated across replay and resume. */\n const toolRuntime = config as {\n toolCallId?: string;\n toolCall?: { id?: string };\n };\n const toolCall = toolRuntime.toolCall;\n let parentToolCallId: string | undefined;\n if (\n typeof toolRuntime.toolCallId === 'string' &&\n toolRuntime.toolCallId !== ''\n ) {\n parentToolCallId = toolRuntime.toolCallId;\n } else if (typeof toolCall?.id === 'string' && toolCall.id !== '') {\n parentToolCallId = toolCall.id;\n }\n /** The parent tool batch's entry-captured scope (stamped by\n * ToolNode before PreToolUse hooks) — binds this child to the\n * run that dispatched it, not to whatever controller a reset\n * installed while the hooks were awaited. */\n const batchScope = config.configurable?.[\n RUN_BREAKER_SCOPE_CONFIG_KEY\n ] as RunBreakerScope | undefined;\n const result = await executor.execute({\n description,\n subagentType,\n threadId,\n signal: config.signal,\n parentToolCallId,\n breaker: batchScope?.controller,\n /**\n * Forward the parent's `configurable` so host-set fields\n * (`requestBody`, `user`, etc.) propagate into the child\n * workflow. The executor scrubs run-identity fields before\n * forwarding — see `SubagentExecuteParams.parentConfigurable`.\n */\n parentConfigurable: config.configurable as\n | Record<string, unknown>\n | undefined,\n });\n return result.content;\n }, buildSubagentToolParams(executableConfigs));\n const replayableSubagentTool = subagentTool as typeof subagentTool &\n ReplayableSubagentTool;\n replayableSubagentTool[SUBAGENT_REPLAY_CONTROLLER] = {\n getResumeManifest: (\n parentToolCallIds,\n config\n ): Promise<SubagentResumeManifest | undefined> =>\n executor.getResumeManifest(parentToolCallIds, config),\n getSettledOutput: (\n call,\n config\n ): Promise<SettledSubagentToolOutput | undefined> =>\n executor.getSettledToolOutput(call, config),\n persistSettledOutput: (call, config, output): Promise<void> =>\n executor.persistSettledToolOutput(call, config, output),\n };\n\n if (!agentContext.graphTools) {\n agentContext.graphTools = [];\n }\n (agentContext.graphTools as t.GenericTool[]).push(subagentTool);\n\n /**\n * Refresh toolSchemaTokens to include the subagent tool's schema.\n * `calculateInstructionTokens()` was kicked off in `fromConfig()`\n * before graphTools was populated, so its result did not count this\n * tool. Without this retrigger, token-budget/pruning logic\n * underestimates prompt overhead.\n */\n if (agentContext.tokenCounter) {\n const { tokenCounter, baseIndexTokenCountMap } = agentContext;\n agentContext.tokenCalculationPromise = agentContext\n .calculateInstructionTokens(tokenCounter)\n .then(() => {\n agentContext.updateTokenMapWithInstructions(\n baseIndexTokenCountMap\n );\n })\n .catch((err) => {\n console.error(\n 'Error recalculating instruction tokens after subagent tool injection:',\n err\n );\n });\n }\n }\n }\n\n const agentNode = `${AGENT}${agentId}` as const;\n const toolNode = `${TOOLS}${agentId}` as const;\n const summarizeNode = `${SUMMARIZE}${agentId}` as const;\n\n const routeMessage = (\n state: t.AgentSubgraphState,\n config?: RunnableConfig\n ): string => {\n this.config = config;\n /**\n * A sealed turn that injected messages resumes in the SAME pregel run:\n * back to the agent node as a new superstep, so the model continues in\n * one assistant message instead of restarting the graph.\n */\n if (this.pendingPreemptReturn.delete(agentId)) {\n return agentNode;\n }\n if (state.summarizationRequest != null) {\n return summarizeNode;\n }\n return toolsCondition(\n state as t.BaseGraphState,\n toolNode,\n this.invokedToolIds\n );\n };\n\n const StateAnnotation = Annotation.Root({\n messages: Annotation<BaseMessage[]>({\n reducer: messagesStateReducer,\n default: () => [],\n }),\n summarizationRequest: Annotation<t.SummarizationNodeInput | undefined>({\n reducer: (\n _: t.SummarizationNodeInput | undefined,\n b: t.SummarizationNodeInput | undefined\n ) => b,\n default: () => undefined,\n }),\n });\n\n const readChargeCredits = ():\n | WeakMap<object, Map<string, number>>\n | undefined => this.streamLimitChargeCredits;\n const readBreakerEpoch = (): number => this.breakerEpoch;\n const readActiveGenerations = (): Set<string> | undefined =>\n this.activeStreamLimitGenerations;\n const writeActiveGenerations = (value: Set<string> | undefined): void => {\n this.activeStreamLimitGenerations = value;\n };\n const writeChargeCredits = (\n value: WeakMap<object, Map<string, number>> | undefined\n ): void => {\n this.streamLimitChargeCredits = value;\n };\n\n const workflow = new StateGraph(StateAnnotation)\n .addNode(agentNode, this.createCallModel(agentId))\n .addNode(\n toolNode,\n this.initializeTools({\n currentTools: agentContext.tools,\n currentToolMap: agentContext.toolMap,\n agentContext,\n })\n )\n .addNode(\n summarizeNode,\n createSummarizeNode({\n agentContext,\n graph: {\n contentData: this.contentData,\n contentIndexMap: this.contentIndexMap,\n get config() {\n return getConfig();\n },\n runId: this.runId,\n isMultiAgent: this.isMultiAgentGraph(),\n hookRegistry: this.hookRegistry,\n /**\n * Live references (both maps are cleared in place, never\n * replaced), so summarization streams share the run's event\n * budget accounting under their own generation key.\n */\n streamLimits: this.streamLimits,\n streamDeltaEventCounts: this.streamDeltaEventCounts,\n streamedToolCallArgTallies: this.streamedToolCallArgTallies,\n /** Accessor pair, not a value copy: unlike the two maps above,\n * the credit map is REPLACED by graph resets rather than cleared\n * in place, and the guards' lazy `??=` must install onto the\n * graph — a copy held here would survive resets and grow one\n * attempt-stamped entry per compaction for a retained reused\n * chunk object. */\n get streamLimitChargeCredits() {\n return readChargeCredits();\n },\n set streamLimitChargeCredits(\n value: WeakMap<object, Map<string, number>> | undefined\n ) {\n writeChargeCredits(value);\n },\n /** Live epoch, so summary tallies are creation-tagged and the\n * resetValues grace sweep treats them like model-attempt\n * entries. */\n get breakerEpoch(): number {\n return readBreakerEpoch();\n },\n /** Accessor pair like the charge credits: summary attempts\n * lease their generations on the GRAPH's active set, and the\n * lazy `??=` in the lease helper must install there. */\n get activeStreamLimitGenerations(): Set<string> | undefined {\n return readActiveGenerations();\n },\n set activeStreamLimitGenerations(value: Set<string> | undefined) {\n writeActiveGenerations(value);\n },\n /** Read per attempt: a sibling branch tripping the run breaker\n * must also cancel in-flight summarization model calls. */\n getBreakerSignal: (): AbortSignal => this.breakerAbort.signal,\n /** The node captures this at entry so its own chunk handler's\n * breach trips the run that STARTED the summarization, not a\n * controller installed by a later reset. */\n getBreakerController: (): AbortController => this.breakerAbort,\n /** Captured at node entry and stamped into the summary attempt\n * metadata, so the wire consumer epoch-gates old-run summary\n * chunks exactly like model-attempt chunks. */\n getBreakerEpoch: (): number => this.breakerEpoch,\n dispatchRunStep: async (runStep, nodeConfig) => {\n const resolvedConfig = nodeConfig ?? this.config;\n if (runStep.agentId != null) {\n const groupId = this.resolveParallelGroupId(\n runStep.agentId,\n resolvedConfig?.metadata\n );\n if (groupId != null) {\n runStep.groupId = groupId;\n }\n }\n this.contentData.push(runStep);\n this.contentIndexMap.set(runStep.id, runStep.index);\n\n const handler = this.handlerRegistry?.getHandler(\n GraphEvents.ON_RUN_STEP\n );\n if (handler) {\n await handler.handle(\n GraphEvents.ON_RUN_STEP,\n runStep,\n resolvedConfig?.configurable,\n this\n );\n this.handlerDispatchedStepIds.add(runStep.id);\n }\n\n const unmarkHandlerDispatchedEvent = handler\n ? this.markHandlerDispatchedEvent(\n GraphEvents.ON_RUN_STEP,\n runStep.id\n )\n : undefined;\n try {\n if (resolvedConfig) {\n await safeDispatchCustomEvent(\n GraphEvents.ON_RUN_STEP,\n runStep,\n resolvedConfig\n );\n }\n } finally {\n unmarkHandlerDispatchedEvent?.();\n }\n },\n dispatchRunStepCompleted: async (\n stepId: string,\n result: t.StepCompleted,\n nodeConfig?: RunnableConfig\n ) => {\n const resolvedConfig = nodeConfig ?? this.config;\n const runStep = this.contentData.find((s) => s.id === stepId);\n const handler = this.handlerRegistry?.getHandler(\n GraphEvents.ON_RUN_STEP_COMPLETED\n );\n if (handler) {\n await handler.handle(\n GraphEvents.ON_RUN_STEP_COMPLETED,\n {\n result: {\n ...result,\n id: stepId,\n index: runStep?.index ?? 0,\n },\n },\n resolvedConfig?.configurable,\n this\n );\n }\n },\n },\n generateStepId: (stepKey: string) => this.generateStepId(stepKey),\n })\n )\n .addEdge(START, agentNode)\n .addConditionalEdges(agentNode, routeMessage)\n .addEdge(summarizeNode, agentNode)\n .addEdge(toolNode, agentContext.toolEnd ? END : agentNode);\n\n return workflow.compile();\n }\n\n createWorkflow(): t.CompiledStateWorkflow {\n this.hasCompiledCheckpointer = this.compileOptions?.checkpointer != null;\n const agentNode = this.createAgentNode(this.defaultAgentId);\n const StateAnnotation = Annotation.Root({\n messages: Annotation<BaseMessage[]>({\n reducer: (a, b) => {\n if (!this.messages.length && !this.hasRestoredCheckpointMessages) {\n this.startIndex = a.length + b.length;\n }\n const result = messagesStateReducer(a, b);\n this.messages = result;\n return result;\n },\n default: () => [],\n }),\n });\n const workflow = new StateGraph(StateAnnotation)\n .addNode(\n this.defaultAgentId,\n agentNode as Runnable<\n t.AgentSubgraphState,\n Partial<t.AgentSubgraphState>\n >,\n { ends: [END] }\n )\n .addEdge(START, this.defaultAgentId)\n // LangGraph compile() types are overly strict for opt-in options\n .compile(this.compileOptions as unknown as never);\n\n return workflow;\n }\n\n /**\n * Indicates if this is a multi-agent graph.\n * Override in MultiAgentGraph to return true.\n * Used to conditionally include agentId in RunStep for frontend rendering.\n */\n protected isMultiAgentGraph(): boolean {\n return false;\n }\n\n /**\n * Get the parallel group ID for an agent, if any.\n * Override in MultiAgentGraph to provide actual group IDs.\n * Group IDs are incrementing numbers (1, 2, 3...) reflecting execution order.\n * @param _agentId - The agent ID to look up\n * @returns undefined for StandardGraph (no parallel groups), or group number for MultiAgentGraph\n */\n protected getParallelGroupIdForAgent(_agentId: string): number | undefined {\n return undefined;\n }\n\n protected resolveParallelGroupId(\n agentId: string,\n metadata?: Record<string, unknown>\n ): number | undefined {\n if (\n metadata == null ||\n !Object.prototype.hasOwnProperty.call(\n metadata,\n Constants.HANDOFF_GROUP_ID\n )\n ) {\n return this.getParallelGroupIdForAgent(agentId);\n }\n const runtimeGroupId = metadata[Constants.HANDOFF_GROUP_ID];\n if (runtimeGroupId === null) {\n return undefined;\n }\n if (\n typeof runtimeGroupId === 'number' &&\n Number.isSafeInteger(runtimeGroupId) &&\n runtimeGroupId > 0\n ) {\n return runtimeGroupId;\n }\n return this.getParallelGroupIdForAgent(agentId);\n }\n\n /* Dispatchers */\n\n /**\n * Dispatches a run step to the client, returns the step ID\n */\n async dispatchRunStep(\n stepKey: string,\n stepDetails: t.StepDetails,\n metadata?: Record<string, unknown>\n ): Promise<string> {\n if (!this.config) {\n throw new Error('No config provided');\n }\n\n const [stepId, stepIndex] = this.generateStepId(stepKey);\n if (stepDetails.type === StepTypes.TOOL_CALLS && stepDetails.tool_calls) {\n for (const tool_call of stepDetails.tool_calls) {\n const toolCallId = tool_call.id ?? '';\n if (!toolCallId || this.toolCallStepIds.has(toolCallId)) {\n continue;\n }\n this.toolCallStepIds.set(toolCallId, stepId);\n }\n }\n\n const runStep: t.RunStep = {\n stepIndex,\n id: stepId,\n type: stepDetails.type,\n index: this.contentData.length,\n stepDetails,\n usage: null,\n };\n\n const runId = this.runId ?? '';\n if (runId) {\n runStep.runId = runId;\n }\n\n if (metadata) {\n try {\n const agentContext = this.getAgentContext(metadata);\n if (this.isMultiAgentGraph() && agentContext.agentId) {\n runStep.agentId = agentContext.agentId;\n const groupId = this.resolveParallelGroupId(\n agentContext.agentId,\n metadata\n );\n if (groupId != null) {\n runStep.groupId = groupId;\n }\n }\n } catch (_e) {\n /** If we can't get agent context, that's okay - agentId remains undefined */\n }\n }\n\n this.contentData.push(runStep);\n this.contentIndexMap.set(stepId, runStep.index);\n\n // Primary dispatch: handler registry (reliable, always works).\n // This mirrors how handleToolCallCompleted dispatches ON_RUN_STEP_COMPLETED\n // via the handler registry, ensuring the event always reaches the handler\n // even when LangGraph's callback system drops the custom event.\n const handler = this.handlerRegistry?.getHandler(GraphEvents.ON_RUN_STEP);\n if (handler) {\n await handler.handle(GraphEvents.ON_RUN_STEP, runStep, metadata, this);\n this.handlerDispatchedStepIds.add(stepId);\n }\n\n // Secondary dispatch: custom event for LangGraph callback chain\n // (tracing, Langfuse, external consumers). May be silently dropped\n // in some scenarios (stale run ID, subgraph callback propagation issues),\n // but the primary dispatch above guarantees the event reaches the handler.\n // The customEventCallback in run.ts skips events already dispatched above\n // to prevent double handling.\n const unmarkHandlerDispatchedEvent = handler\n ? this.markHandlerDispatchedEvent(GraphEvents.ON_RUN_STEP, stepId)\n : undefined;\n try {\n await safeDispatchCustomEvent(\n GraphEvents.ON_RUN_STEP,\n runStep,\n this.config\n );\n } finally {\n unmarkHandlerDispatchedEvent?.();\n }\n return stepId;\n }\n\n /**\n * Static version of handleToolCallError to avoid creating strong references\n * that prevent garbage collection.\n *\n * Returns whether the error completion event was actually dispatched. A\n * tool can error before this graph instance has a run step for the call —\n * on a resume pass the interrupted batch re-executes IMMEDIATELY on graph\n * re-entry, before any step replay has registered `toolCallStepIds` (a\n * fast-failing tool, e.g. a schema-validation reject, loses that race).\n * That is a caller-recoverable condition, not an invariant violation: the\n * ToolNode falls back to its normal completion dispatch for the error\n * ToolMessage when this returns `false`, so throwing here would only\n * replace a recoverable miss with a lost completion event and a scary log.\n */\n static async handleToolCallErrorStatic(\n graph: StandardGraph,\n data: t.ToolErrorData,\n metadata?: Record<string, unknown>\n ): Promise<boolean> {\n if (!data.id) {\n console.warn('No Tool ID provided for Tool Error');\n return false;\n }\n\n const stepId = graph.toolCallStepIds.get(data.id) ?? '';\n if (!stepId) {\n return false;\n }\n\n const { name, input: args, error } = data;\n const eventValueLimit = calculateMaxToolResultChars();\n const errorOutputPrefix = 'Error processing tool';\n const errorDetail =\n error?.message != null\n ? `: ${serializeToolContentBounded(\n error.message,\n Math.max(0, eventValueLimit - errorOutputPrefix.length - 2)\n )}`\n : '';\n\n const runStep = graph.getRunStep(stepId);\n if (!runStep) {\n return false;\n }\n\n const tool_call: t.ProcessedToolCall = {\n id: data.id,\n name: name || '',\n args: serializeToolContentBounded(args, eventValueLimit),\n output: `${errorOutputPrefix}${errorDetail}`,\n progress: 1,\n };\n\n // No registered ON_RUN_STEP_COMPLETED handler ⇒ nothing was dispatched.\n // Report `false` so the ToolNode runs its own fallback dispatch; returning\n // `true` here would silently drop the error completion for hosts that wire\n // completions through callback-based custom events instead of a handler.\n const handler = graph.handlerRegistry?.getHandler(\n GraphEvents.ON_RUN_STEP_COMPLETED\n );\n if (!handler) {\n return false;\n }\n\n await handler.handle(\n GraphEvents.ON_RUN_STEP_COMPLETED,\n {\n result: {\n id: stepId,\n index: runStep.index,\n type: 'tool_call',\n tool_call,\n } as t.ToolCompleteEvent,\n },\n metadata,\n graph\n );\n return true;\n }\n\n /**\n * Instance method that delegates to the static method\n * Kept for backward compatibility\n */\n async handleToolCallError(\n data: t.ToolErrorData,\n metadata?: Record<string, unknown>\n ): Promise<boolean> {\n return StandardGraph.handleToolCallErrorStatic(this, data, metadata);\n }\n\n async dispatchRunStepDelta(\n id: string,\n delta: t.ToolCallDelta,\n metadata?: Record<string, unknown>\n ): Promise<void> {\n if (!this.config) {\n throw new Error('No config provided');\n } else if (!id) {\n throw new Error('No step ID found');\n }\n const runStepDelta: t.RunStepDeltaEvent = {\n id,\n delta,\n };\n const handler = this.handlerRegistry?.getHandler(\n GraphEvents.ON_RUN_STEP_DELTA\n );\n if (handler) {\n await handler.handle(\n GraphEvents.ON_RUN_STEP_DELTA,\n runStepDelta,\n metadata,\n this\n );\n this.handlerDispatchedStepIds.add(id);\n }\n const unmarkHandlerDispatchedEvent = handler\n ? this.markHandlerDispatchedEvent(GraphEvents.ON_RUN_STEP_DELTA, id)\n : undefined;\n try {\n await safeDispatchCustomEvent(\n GraphEvents.ON_RUN_STEP_DELTA,\n runStepDelta,\n this.config\n );\n } finally {\n unmarkHandlerDispatchedEvent?.();\n }\n }\n\n async dispatchMessageDelta(\n id: string,\n delta: t.MessageDelta,\n metadata?: Record<string, unknown>\n ): Promise<void> {\n if (!this.config) {\n throw new Error('No config provided');\n }\n const messageDelta: t.MessageDeltaEvent = {\n id,\n delta,\n };\n if (hasTextDeltaContent(delta.content)) {\n this.messageStepHasTextDeltas.add(id);\n }\n const handler = this.handlerRegistry?.getHandler(\n GraphEvents.ON_MESSAGE_DELTA\n );\n if (handler) {\n await handler.handle(\n GraphEvents.ON_MESSAGE_DELTA,\n messageDelta,\n metadata,\n this\n );\n this.handlerDispatchedStepIds.add(id);\n }\n const unmarkHandlerDispatchedEvent = handler\n ? this.markHandlerDispatchedEvent(GraphEvents.ON_MESSAGE_DELTA, id)\n : undefined;\n try {\n await safeDispatchCustomEvent(\n GraphEvents.ON_MESSAGE_DELTA,\n messageDelta,\n this.config\n );\n } finally {\n unmarkHandlerDispatchedEvent?.();\n }\n }\n\n dispatchReasoningDelta = async (\n stepId: string,\n delta: t.ReasoningDelta,\n metadata?: Record<string, unknown>\n ): Promise<void> => {\n if (!this.config) {\n throw new Error('No config provided');\n }\n const reasoningDelta: t.ReasoningDeltaEvent = {\n id: stepId,\n delta,\n };\n if (hasReasoningDeltaContent(delta.content)) {\n this.reasoningStepHasDeltas.add(stepId);\n }\n const handler = this.handlerRegistry?.getHandler(\n GraphEvents.ON_REASONING_DELTA\n );\n if (handler) {\n await handler.handle(\n GraphEvents.ON_REASONING_DELTA,\n reasoningDelta,\n metadata,\n this\n );\n this.handlerDispatchedStepIds.add(stepId);\n }\n const unmarkHandlerDispatchedEvent = handler\n ? this.markHandlerDispatchedEvent(GraphEvents.ON_REASONING_DELTA, stepId)\n : undefined;\n try {\n await safeDispatchCustomEvent(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AAI,MAAM,oBAAoB;EAEtC,MAAM,iBAAwC;GAC5C,IAAI;GACJ;EACF;EACA,IAAI,yBAAyB,MAAM,OAAO,GACxC,KAAK,uBAAuB,IAAI,MAAM;EAExC,MAAM,UAAU,KAAK,iBAAiB,WAAA,oBAEtC;EACA,IAAI,SAAS;GACX,MAAM,QAAQ,OAAA,sBAEZ,gBACA,UACA,IACF;GACA,KAAK,yBAAyB,IAAI,MAAM;EAC1C;EACA,MAAM,+BAA+B,UACjC,KAAK,2BAAA,sBAA2D,MAAM,IACtE,KAAA;EACJ,IAAI;GACF,MAAMA,eAAAA,wBAAAA,sBAEJ,gBACA,KAAK,MACP;EACF,UAAU;GACR,+BAA+B;EACjC;CACF;AACF"}
1
+ {"version":3,"file":"Graph.cjs","names":["GraphNodeKeys","HandlerRegistry","isGoogleLike","getMessageCreationContentMetadata","getMessageId","splitAssistantTextContentByPhase","ToolOutputReferenceRegistry","createLocalCodingToolBundle","createCloudflareCodingToolBundle","StreamLimitExceededError","resolveStreamLimits","AgentContext","resetIfNotEmpty","messagesStateReducer","resolveMaxSeals","joinKeys","convertMessagesToContent","shouldTraceToolNodeForLangfuse","createSchemaOnlyTools","CustomToolNode","createFakeStreamingLLM","extractToolDiscoveries","resolveLocalToolsForBinding","partitionAndMarkAnthropicToolCache","makeIsDeferred","resolvePromptCacheTtl","partitionAndMarkOpenRouterToolCache","supportsBedrockToolCache","partitionAndMarkBedrockToolCache","initializeModel","createPruneMessages","isThinkingEnabled","apportionTokenCounts","shouldTriggerSummarization","ToolMessage","isSyntheticProviderContextMessage","formatContentStrings","calculateMaxToolResultChars","projectToolStreamContentForProvider","projectToolCallInputs","calculateMaxToolCallInputChars","isAnthropicLike","AIMessageChunk","ContextOverflowError","ensureThinkingBlockInMessages","foldToolBlocksForToollessAgent","appendPredecessorHandoffCue","annotateMessagesForLLM","HumanMessage","getToolContentCharLength","compactToolContent","projectAnthropicArtifactContent","isOpenAILike","projectArtifactPayload","strictAlternationProviders","coalesceAdjacentUserTurns","sanitizeOrphanToolBlocks","addTailCacheControl","addBedrockTailCacheControl","resolveBedrockPromptCacheTtl","projectMessagesForProvider","sleep","safeDispatchCustomEvent","resolveLangfuseConfig","createLangfuseTraceMetadata","composeAbortSignals","STREAM_LIMIT_EPOCH_KEY","findCallback","isLangfuseCallbackHandler","createLangfuseHandler","hasToolOutputTracingConfig","resolveToolOutputTracingConfig","appendCallbacks","withLangfuseRuntimeScope","resolveLangfuseRuntimeScope","attemptInvoke","splitAtRecencyBoundary","getFallbackErrorContext","planContextOverflowRecovery","getBlindRecoveryBudget","translateRecoveryBudget","tryFallbackProviders","resolveServingModelId","removePredecessorHandoffCue","getFallbackOverflowCandidates","disposeLangfuseHandler","handleToolCalls","executeHooks","PREEMPT_BOUNDARY_HOOK_TIMEOUT_MS","convertInjectedMessages","normalizeSubagentConfigEntries","isGraphSubagentConfig","SubagentExecutor","DEFAULT_SUBAGENT_DESCRIPTION","RUN_BREAKER_SCOPE_CONFIG_KEY","buildSubagentToolParams","SUBAGENT_REPLAY_CONTROLLER","toolsCondition","Annotation","StateGraph","createSummarizeNode","START","END","serializeToolContentBounded"],"sources":["../../../src/graphs/Graph.ts"],"sourcesContent":["/* eslint-disable no-console */\nimport { v4 } from 'uuid';\nimport { nanoid } from 'nanoid';\nimport { tool } from '@langchain/core/tools';\nimport { ToolNode } from '@langchain/langgraph/prebuilt';\nimport { ContextOverflowError } from '@langchain/core/errors';\nimport { Runnable, RunnableConfig } from '@langchain/core/runnables';\nimport { START, END, StateGraph, Annotation } from '@langchain/langgraph';\nimport {\n ToolMessage,\n HumanMessage,\n AIMessageChunk,\n} from '@langchain/core/messages';\nimport type {\n UsageMetadata,\n BaseMessage,\n MessageContent,\n} from '@langchain/core/messages';\nimport type { ToolCall } from '@langchain/core/messages/tool';\nimport type {\n ReplayableSubagentTool,\n SubagentGraphResumeState,\n SubagentResumeManifest,\n SubagentToolNodeResumeState,\n SettledSubagentToolOutput,\n} from '@/tools/subagent/SubagentReplay';\nimport type {\n ResolvedStreamLimits,\n RunBreakerScope,\n StreamedToolCallArgTally,\n StreamDeltaEventTally,\n} from '@/llm/streamLimits';\nimport type {\n GraphFactory,\n GraphFactoryDependencies,\n} from '@/graphs/graphFactory';\nimport type { OverflowRecoveryPlan } from '@/llm/contextOverflowRecovery';\nimport type { FallbackErrorContext } from '@/llm/invoke';\nimport type { HookRegistry } from '@/hooks';\nimport type * as t from '@/types';\nimport {\n projectAnthropicArtifactContent,\n ensureThinkingBlockInMessages,\n foldToolBlocksForToollessAgent,\n convertMessagesToContent,\n sanitizeOrphanToolBlocks,\n extractToolDiscoveries,\n addBedrockTailCacheControl,\n projectArtifactPayload,\n formatContentStrings,\n CALIBRATION_RATIO_MAX,\n REPLY_PRIMER_TOKENS,\n createPruneMessages,\n projectToolCallInputs,\n calculateMaxToolCallInputChars,\n projectToolStreamContentForProvider,\n syncBudgetDerivedFields,\n addTailCacheControl,\n resolvePromptCacheTtl,\n resolveBedrockPromptCacheTtl,\n supportsBedrockToolCache,\n isSyntheticProviderContextMessage,\n getMessageId,\n getMessageCreationContentMetadata,\n splitAssistantTextContentByPhase,\n makeIsDeferred,\n partitionAndMarkAnthropicToolCache,\n DEFAULT_RETAIN_RECENT_TURNS,\n splitAtRecencyBoundary,\n convertInjectedMessages,\n coalesceAdjacentUserTurns,\n strictAlternationProviders,\n appendPredecessorHandoffCue,\n removePredecessorHandoffCue,\n} from '@/messages';\nimport {\n resetIfNotEmpty,\n isAnthropicLike,\n isOpenAILike,\n isGoogleLike,\n apportionTokenCounts,\n calculateMaxToolResultChars,\n composeAbortSignals,\n joinKeys,\n sleep,\n} from '@/utils';\nimport {\n attemptInvoke,\n tryFallbackProviders,\n getFallbackErrorContext,\n getFallbackOverflowCandidates,\n projectMessagesForProvider,\n resolveServingModelId,\n} from '@/llm/invoke';\nimport {\n resolveStreamLimits,\n StreamLimitExceededError,\n sweepStaleStreamLimitEntries,\n STREAM_LIMIT_EPOCH_KEY,\n RUN_BREAKER_SCOPE_CONFIG_KEY,\n} from '@/llm/streamLimits';\nimport {\n DEFAULT_SUBAGENT_DESCRIPTION,\n SubagentExecutor,\n isGraphSubagentConfig,\n normalizeSubagentConfigEntries,\n} from '@/tools/subagent';\nimport {\n Constants,\n GraphNodeKeys,\n ContentTypes,\n GraphEvents,\n Providers,\n StepTypes,\n PREEMPT_BOUNDARY_HOOK_TIMEOUT_MS,\n} from '@/common';\nimport {\n createLangfuseHandler,\n createLangfuseTraceMetadata,\n disposeLangfuseHandler,\n isLangfuseCallbackHandler,\n} from '@/langfuse';\nimport {\n getBlindRecoveryBudget,\n planContextOverflowRecovery,\n translateRecoveryBudget,\n} from '@/llm/contextOverflowRecovery';\nimport {\n hasToolOutputTracingConfig,\n resolveLangfuseConfig,\n resolveToolOutputTracingConfig,\n} from '@/langfuseConfig';\nimport {\n compactToolContent,\n getToolContentCharLength,\n serializeToolContentBounded,\n} from '@/utils/toolContent';\nimport {\n annotateMessagesForLLM,\n ToolOutputReferenceRegistry,\n} from '@/tools/toolOutputReferences';\nimport {\n resolveLangfuseRuntimeScope,\n withLangfuseRuntimeScope,\n} from '@/langfuseRuntimeScope';\nimport {\n appendCallbacks,\n findCallback,\n type CallbackEntry,\n} from '@/utils/callbacks';\nimport { partitionAndMarkOpenRouterToolCache } from '@/llm/openrouter/toolCache';\nimport { ToolNode as CustomToolNode, toolsCondition } from '@/tools/ToolNode';\nimport { shouldTraceToolNodeForLangfuse } from '@/langfuseToolOutputTracing';\nimport { createLocalCodingToolBundle } from '@/tools/local/LocalCodingTools';\nimport { SUBAGENT_REPLAY_CONTROLLER } from '@/tools/subagent/SubagentReplay';\nimport { applyGraphRuntimeConfig } from '@/graphs/applyGraphRuntimeConfig';\nimport { partitionAndMarkBedrockToolCache } from '@/llm/bedrock/toolCache';\nimport { safeDispatchCustomEvent, emitAgentLog } from '@/utils/events';\nimport { createCloudflareCodingToolBundle } from '@/tools/cloudflare';\nimport { buildSubagentToolParams } from '@/tools/SubagentTool';\nimport { initializeLangfuseTracing } from '@/instrumentation';\nimport { shouldTriggerSummarization } from '@/summarization';\nimport { resolveLocalToolsForBinding } from '@/tools/local';\nimport { createSummarizeNode } from '@/summarization/node';\nimport { messagesStateReducer } from '@/messages/reducer';\nimport { createSchemaOnlyTools } from '@/tools/schema';\nimport { AgentContext } from '@/agents/AgentContext';\nimport { createFakeStreamingLLM } from '@/llm/fake';\nimport { handleToolCalls } from '@/tools/handlers';\nimport { isThinkingEnabled } from '@/llm/request';\nimport { resolveMaxSeals } from '@/llm/preempt';\nimport { initializeModel } from '@/llm/init';\nimport { HandlerRegistry } from '@/events';\nimport { ChatOpenAI } from '@/llm/openai';\nimport { executeHooks } from '@/hooks';\n\nconst { AGENT, TOOLS, SUMMARIZE } = GraphNodeKeys;\n\n/** What a `PreemptBoundary` drain resolved to. */\ntype PreemptBoundaryResult = {\n messages: BaseMessage[];\n /** A hook asked for no further model turn; the seal must not self-loop. */\n preventContinuation: boolean;\n};\n\nconst EMPTY_PREEMPT_BOUNDARY: PreemptBoundaryResult = {\n messages: [],\n preventContinuation: false,\n};\n\n/** Minimum relative variance before calibrated toolSchemaTokens overrides current value. */\nconst CALIBRATION_VARIANCE_THRESHOLD = 0.15;\n\nfunction createChildHandlerRegistry(\n source: HandlerRegistry | undefined\n): HandlerRegistry | undefined {\n const toolHandler = source?.getHandler(GraphEvents.ON_TOOL_EXECUTE);\n const updateHandler = source?.getHandler(GraphEvents.ON_SUBAGENT_UPDATE);\n if (toolHandler == null && updateHandler == null) {\n return undefined;\n }\n const registry = new HandlerRegistry();\n if (toolHandler != null) {\n registry.register(GraphEvents.ON_TOOL_EXECUTE, toolHandler);\n }\n if (updateHandler != null) {\n registry.register(GraphEvents.ON_SUBAGENT_UPDATE, updateHandler);\n }\n return registry;\n}\n\ntype ReasoningKey = 'reasoning_content' | 'reasoning';\ntype ReasoningSummary = { summary?: Array<{ text?: string }> };\ntype ReasoningDetail = { type?: string; text?: string };\n\nfunction getHandlerDispatchedEventKey(\n eventName: string,\n stepId: string\n): string {\n return `${eventName}:${stepId}`;\n}\n\nfunction getReasoningText(\n value: string | Partial<ReasoningSummary> | null | undefined\n): string | undefined {\n if (typeof value === 'string') {\n return value !== '' ? value : undefined;\n }\n const summaryText = value?.summary\n ?.map((summary) => summary.text ?? '')\n .filter((text) => text !== '')\n .join('');\n return summaryText != null && summaryText !== '' ? summaryText : undefined;\n}\n\nfunction getReasoningDetailsText(\n value: ReasoningDetail[] | null | undefined\n): string | undefined {\n if (!Array.isArray(value)) {\n return undefined;\n }\n const reasoningText = value\n .filter((detail) => detail.type === 'reasoning.text')\n .map((detail) => detail.text ?? '')\n .filter((text) => text !== '')\n .join('');\n return reasoningText !== '' ? reasoningText : undefined;\n}\n\nfunction getResponseReasoningContent({\n responseMessage,\n reasoningKey,\n}: {\n responseMessage?: Partial<AIMessageChunk>;\n reasoningKey: ReasoningKey;\n}): string | undefined {\n const additionalKwargs = responseMessage?.additional_kwargs;\n if (additionalKwargs == null) {\n return undefined;\n }\n\n const keyedReasoning = getReasoningText(\n additionalKwargs[reasoningKey] as\n | string\n | Partial<ReasoningSummary>\n | null\n | undefined\n );\n if (keyedReasoning != null) {\n return keyedReasoning;\n }\n\n const reasoningContent = getReasoningText(\n additionalKwargs.reasoning_content as\n | string\n | Partial<ReasoningSummary>\n | null\n | undefined\n );\n if (reasoningContent != null) {\n return reasoningContent;\n }\n\n const reasoning = getReasoningText(\n additionalKwargs.reasoning as\n | string\n | Partial<ReasoningSummary>\n | null\n | undefined\n );\n if (reasoning != null) {\n return reasoning;\n }\n\n return getReasoningDetailsText(\n additionalKwargs.reasoning_details as ReasoningDetail[] | null | undefined\n );\n}\n\nfunction isTextMessageContentPart(\n contentPart: MessageContent[number] | t.MessageContentComplex\n): boolean {\n return (\n typeof contentPart === 'object' &&\n 'type' in contentPart &&\n typeof contentPart.type === 'string' &&\n contentPart.type.startsWith('text')\n );\n}\n\nfunction isGoogleServerSideToolMessageContentPart(\n contentPart: MessageContent[number] | t.MessageContentComplex\n): boolean {\n return (\n typeof contentPart === 'object' &&\n 'type' in contentPart &&\n (contentPart.type === 'toolCall' || contentPart.type === 'toolResponse')\n );\n}\n\nfunction hasGoogleServerSideToolDeltaContent(\n provider: Providers | undefined,\n content: t.MessageDelta['content']\n): content is t.MessageContentComplex[] {\n return (\n isGoogleLike(provider) &&\n Array.isArray(content) &&\n content.some((contentPart) =>\n isGoogleServerSideToolMessageContentPart(contentPart)\n )\n );\n}\n\nfunction getMessageDeltaContent(\n provider: Providers | undefined,\n content: MessageContent | undefined\n): t.MessageDelta['content'] | undefined {\n if (content == null) {\n return undefined;\n }\n if (typeof content === 'string') {\n return content !== ''\n ? [{ type: ContentTypes.TEXT, text: content }]\n : undefined;\n }\n if (content.length === 0) {\n return undefined;\n }\n\n const hasGoogleServerSideToolPart =\n isGoogleLike(provider) &&\n content.some((contentPart) =>\n isGoogleServerSideToolMessageContentPart(contentPart)\n );\n if (content.every((contentPart) => isTextMessageContentPart(contentPart))) {\n return content as t.MessageDelta['content'];\n }\n if (!hasGoogleServerSideToolPart) {\n return undefined;\n }\n const messageContent = content.filter(\n (contentPart) =>\n isTextMessageContentPart(contentPart) ||\n isGoogleServerSideToolMessageContentPart(contentPart)\n );\n return messageContent.length > 0\n ? (messageContent as t.MessageDelta['content'])\n : undefined;\n}\n\nfunction hasTextDeltaContent(\n content: t.MessageDelta['content'] | undefined\n): boolean {\n if (content == null) {\n return false;\n }\n return content.some((contentPart) => {\n if (contentPart.type?.startsWith(ContentTypes.TEXT) !== true) {\n return false;\n }\n const text = (contentPart as Partial<{ text: string }>).text;\n return typeof text === 'string' && text !== '';\n });\n}\n\nfunction hasReasoningDeltaContent(\n content: t.ReasoningDelta['content'] | undefined\n): boolean {\n if (content == null) {\n return false;\n }\n return content.some(\n (contentPart) =>\n contentPart.type === ContentTypes.THINK && contentPart.think !== ''\n );\n}\n\nfunction getCurrentStepIds({\n graph,\n metadata,\n}: {\n graph: Graph<t.BaseGraphState>;\n metadata: Record<string, unknown>;\n}): string[] {\n const baseStepKey = graph.getStepBaseKey(metadata);\n const currentStepIds: string[] = [];\n for (const [stepKey, stepIds] of graph.stepKeyIds) {\n if (stepKey !== baseStepKey && !stepKey.startsWith(`${baseStepKey}_`)) {\n continue;\n }\n currentStepIds.push(...stepIds);\n }\n return currentStepIds;\n}\n\nfunction hasCurrentTextDeltaStep({\n graph,\n metadata,\n}: {\n graph: Graph<t.BaseGraphState>;\n metadata: Record<string, unknown>;\n}): boolean {\n return getCurrentStepIds({ graph, metadata }).some((stepId) =>\n graph.messageStepHasTextDeltas.has(stepId)\n );\n}\n\nfunction hasCurrentReasoningDeltaStep({\n graph,\n metadata,\n}: {\n graph: Graph<t.BaseGraphState>;\n metadata: Record<string, unknown>;\n}): boolean {\n return getCurrentStepIds({ graph, metadata }).some((stepId) =>\n graph.reasoningStepHasDeltas.has(stepId)\n );\n}\n\nfunction clearCurrentDeltaStepMarkers({\n graph,\n metadata,\n}: {\n graph: Graph<t.BaseGraphState>;\n metadata: Record<string, unknown>;\n}): void {\n for (const stepId of getCurrentStepIds({ graph, metadata })) {\n graph.messageStepHasTextDeltas.delete(stepId);\n graph.reasoningStepHasDeltas.delete(stepId);\n }\n}\n\n/**\n * The completion allowance the caller configured, under whichever key the\n * provider's client uses. Providers count it against the same ceiling as the\n * prompt, so overflow recovery has to reserve it when the error did not\n * itemize the total.\n */\nfunction getConfiguredCompletionTokens(\n clientOptions: t.ClientOptions | undefined\n): number | undefined {\n const options = clientOptions as\n | { maxTokens?: unknown; maxOutputTokens?: unknown }\n | undefined;\n for (const value of [options?.maxTokens, options?.maxOutputTokens]) {\n if (typeof value === 'number' && Number.isFinite(value) && value > 0) {\n return value;\n }\n }\n return undefined;\n}\n\n/**\n * Our own estimate of the prompt that was actually sent, derived from the\n * pre-invoke usage snapshot. Used to corroborate ambiguous provider errors\n * and to measure how far our token accounting sits from the provider's.\n */\nfunction getEstimatedPromptTokens(\n contextUsage: t.ContextUsageEvent | null\n): number | undefined {\n const budget = contextUsage?.contextBudget;\n const remaining = contextUsage?.remainingContextTokens;\n if (\n budget == null ||\n remaining == null ||\n !Number.isFinite(budget) ||\n !Number.isFinite(remaining)\n ) {\n return undefined;\n }\n const used = budget - remaining;\n return used > 0 ? used : undefined;\n}\n\nfunction minDefined(\n left: number | undefined,\n right: number | undefined\n): number | undefined {\n if (left == null) {\n return right;\n }\n if (right == null) {\n return left;\n }\n return Math.min(left, right);\n}\n\nasync function dispatchMessageCreationStep({\n graph,\n stepKey,\n messageId,\n content,\n contentType,\n metadata,\n}: {\n graph: Graph<t.BaseGraphState>;\n stepKey: string;\n messageId: string;\n content?: string | t.MessageContentComplex[];\n contentType?: ContentTypes.TEXT | ContentTypes.THINK;\n metadata: Record<string, unknown>;\n}): Promise<string> {\n await graph.dispatchRunStep(\n stepKey,\n {\n type: StepTypes.MESSAGE_CREATION,\n message_creation: {\n message_id: messageId,\n ...getMessageCreationContentMetadata(content, contentType),\n },\n },\n metadata\n );\n return graph.getStepIdByKey(stepKey);\n}\n\nasync function dispatchTextMessageContent({\n graph,\n stepKey,\n provider,\n content,\n metadata,\n}: {\n graph: Graph<t.BaseGraphState>;\n stepKey: string;\n provider?: Providers;\n content: t.MessageDelta['content'];\n metadata: Record<string, unknown>;\n}): Promise<boolean> {\n const messageId = getMessageId(stepKey, graph) ?? '';\n if (!messageId) {\n return false;\n }\n if (hasGoogleServerSideToolDeltaContent(provider, content)) {\n for (const contentPart of content) {\n const stepId = await dispatchMessageCreationStep({\n graph,\n stepKey,\n messageId,\n content: [contentPart],\n metadata,\n });\n await graph.dispatchMessageDelta(\n stepId,\n { content: [contentPart] },\n metadata\n );\n }\n return true;\n }\n const contentGroups = Array.isArray(content)\n ? splitAssistantTextContentByPhase(content)\n : [content];\n for (const contentGroup of contentGroups) {\n const stepId = await dispatchMessageCreationStep({\n graph,\n stepKey,\n messageId,\n content: contentGroup,\n contentType: ContentTypes.TEXT,\n metadata,\n });\n await graph.dispatchMessageDelta(\n stepId,\n { content: contentGroup },\n metadata\n );\n }\n return true;\n}\n\nasync function dispatchReasoningContent({\n graph,\n agentContext,\n reasoningContent,\n metadata,\n}: {\n graph: Graph<t.BaseGraphState>;\n agentContext: AgentContext;\n reasoningContent: string;\n metadata: Record<string, unknown>;\n}): Promise<boolean> {\n const previousTokenType = agentContext.currentTokenType;\n const previousTokenTypeSwitch = agentContext.tokenTypeSwitch;\n const previousTransitionCount = agentContext.reasoningTransitionCount;\n\n agentContext.currentTokenType = ContentTypes.THINK;\n agentContext.tokenTypeSwitch = 'reasoning';\n\n const stepKey = graph.getStepKey(metadata);\n const messageId = getMessageId(stepKey, graph) ?? '';\n if (!messageId) {\n agentContext.currentTokenType = previousTokenType;\n agentContext.tokenTypeSwitch = previousTokenTypeSwitch;\n agentContext.reasoningTransitionCount = previousTransitionCount;\n return false;\n }\n\n await graph.dispatchRunStep(\n stepKey,\n {\n type: StepTypes.MESSAGE_CREATION,\n message_creation: {\n message_id: messageId,\n content_type: ContentTypes.THINK,\n },\n },\n metadata\n );\n const stepId = graph.getStepIdByKey(stepKey);\n await graph.dispatchReasoningDelta(\n stepId,\n {\n content: [{ type: ContentTypes.THINK, think: reasoningContent }],\n },\n metadata\n );\n return true;\n}\n\nfunction markPostReasoningContent(agentContext: AgentContext): void {\n if (\n agentContext.tokenTypeSwitch !== 'reasoning' ||\n agentContext.currentTokenType === ContentTypes.TEXT\n ) {\n return;\n }\n agentContext.currentTokenType = ContentTypes.TEXT;\n agentContext.tokenTypeSwitch = 'content';\n agentContext.reasoningTransitionCount++;\n}\n\nfunction getDispatchableFinalReasoningContent({\n agentContext,\n responseReasoningContent,\n hasStreamedTextDeltaStep,\n hasStreamedReasoningDeltaStep,\n}: {\n agentContext: AgentContext;\n responseReasoningContent: string | undefined;\n hasStreamedTextDeltaStep: boolean;\n hasStreamedReasoningDeltaStep: boolean;\n}): string | undefined {\n if (responseReasoningContent == null || hasStreamedReasoningDeltaStep) {\n return undefined;\n }\n if (\n agentContext.provider === Providers.OPENROUTER &&\n hasStreamedTextDeltaStep\n ) {\n return undefined;\n }\n return responseReasoningContent;\n}\n\nexport abstract class Graph<\n T extends t.BaseGraphState = t.BaseGraphState,\n _TNodeName extends string = string,\n> {\n abstract resetValues(keepContent?: boolean, checkpointScope?: string): void;\n restoreCheckpointMessages(\n _messages: BaseMessage[],\n _pendingMessages?: BaseMessage[]\n ): void {}\n abstract initializeTools({\n currentTools,\n currentToolMap,\n }: {\n currentTools?: t.GraphTools;\n currentToolMap?: t.ToolMap;\n }): CustomToolNode<T> | ToolNode<T>;\n abstract getRunMessages(): BaseMessage[] | undefined;\n /** Returns a snapshot of deferred tools discovered by this graph. */\n getDiscoveredTools(_agentId?: string): string[] {\n return [];\n }\n abstract getContentParts(): t.MessageContentComplex[] | undefined;\n abstract generateStepId(stepKey: string): [string, number];\n abstract getKeyList(\n metadata: Record<string, unknown> | undefined\n ): (string | number | undefined)[];\n abstract getStepBaseKey(\n metadata: Record<string, unknown> | undefined\n ): string;\n abstract getStepKey(metadata: Record<string, unknown> | undefined): string;\n abstract checkKeyList(keyList: (string | number | undefined)[]): boolean;\n abstract getStepIdByKey(stepKey: string, index?: number): string;\n abstract getRunStep(stepId: string): t.RunStep | undefined;\n abstract dispatchRunStep(\n stepKey: string,\n stepDetails: t.StepDetails,\n metadata?: Record<string, unknown>\n ): Promise<string>;\n abstract dispatchRunStepDelta(\n id: string,\n delta: t.ToolCallDelta,\n metadata?: Record<string, unknown>\n ): Promise<void>;\n abstract dispatchMessageDelta(\n id: string,\n delta: t.MessageDelta,\n metadata?: Record<string, unknown>\n ): Promise<void>;\n abstract dispatchReasoningDelta(\n stepId: string,\n delta: t.ReasoningDelta,\n metadata?: Record<string, unknown>\n ): Promise<void>;\n abstract createCallModel(\n agentId?: string,\n currentModel?: t.ChatModel\n ): (\n state: t.AgentSubgraphState,\n config?: RunnableConfig\n ) => Promise<Partial<t.AgentSubgraphState>>;\n messageStepHasTextDeltas: Set<string> = new Set();\n messageStepHasToolCalls: Map<string, boolean> = new Map();\n messageIdsByStepKey: Map<string, string> = new Map();\n prelimMessageIdsByStepKey: Map<string, string> = new Map();\n config: RunnableConfig | undefined;\n contentData: t.RunStep[] = [];\n stepKeyIds: Map<string, string[]> = new Map<string, string[]>();\n contentIndexMap: Map<string, number> = new Map();\n toolCallStepIds: Map<string, string> = new Map();\n /**\n * Step IDs dispatched through the handler registry during this run.\n * Event echo suppression is tracked separately so repeated deltas for\n * the same step are scoped to the active custom event dispatch.\n */\n handlerDispatchedStepIds: Set<string> = new Set();\n reasoningStepHasDeltas: Set<string> = new Set();\n protected handlerDispatchedEventCounts: Map<string, number> = new Map();\n signal?: AbortSignal;\n /**\n * The abort signal the CALLER handed to the current `processStream` call,\n * assigned unconditionally — including back to `undefined` — on every call.\n *\n * Kept separate from {@link signal} on purpose. That field is construction\n * state with its own consumers (model-call config, subagent parentSignal),\n * so adopting a per-call signal into it would leak one call's controller\n * into the next — `clearHeavyState()` is skipped on HITL interrupts, so a\n * host that aborts a finished request's controller would poison the resumed\n * run's model calls and boundary drains with an already-aborted signal.\n * Boundary dispatch composes the two instead; see\n * `StandardGraph.dispatchPreemptBoundary`.\n */\n callerSignal?: AbortSignal;\n /** Set of invoked tool call IDs from non-message run steps completed mid-run, if any */\n invokedToolIds?: Set<string>;\n handlerRegistry: HandlerRegistry | undefined;\n /** Host registry retained only for forwarding tools from nested child graphs. */\n protected parentToolHandlerRegistry: HandlerRegistry | undefined;\n /**\n * True when event-driven tool execution can be routed through callbacks even\n * though this graph intentionally does not own the full handler registry.\n * Self-spawned subagent graphs use this shape: their callback forwarder sends\n * `ON_TOOL_EXECUTE` to the parent's handler, while child run-step events stay\n * wrapped as `ON_SUBAGENT_UPDATE` instead of leaking as parent events.\n */\n eventToolExecutionAvailable: boolean = false;\n hookRegistry: HookRegistry | undefined;\n /**\n * Run-scoped HITL configuration. When `humanInTheLoop?.enabled` is\n * `true`, `ToolNode` raises a real `interrupt()` for `PreToolUse`\n * `ask` decisions instead of treating them as a synchronous deny.\n * Threaded from `RunConfig.humanInTheLoop`.\n */\n humanInTheLoop: t.HumanInTheLoopConfig | undefined;\n /**\n * Run-scoped config for the tool output reference registry. Threaded\n * from `RunConfig.toolOutputReferences` down into every ToolNode this\n * graph compiles.\n */\n toolOutputReferences: t.ToolOutputReferencesConfig | undefined;\n /**\n * Run-scoped Langfuse defaults. Per-agent config wins when present.\n */\n langfuse: t.LangfuseConfig | undefined;\n /**\n * Run-scoped opt-in for eager event-driven tool execution. The stream\n * handler may prestart eligible event-driven tools; ToolNode later\n * consumes the settled promises while preserving final ToolMessage order.\n */\n eagerEventToolExecution: t.EagerEventToolExecutionConfig | undefined;\n codeSessionToolNames: string[] | undefined;\n /**\n * Run-scoped names of tools whose in-process body may raise a LangGraph\n * `interrupt()` (e.g. `ask_user_question`). Threaded from\n * `RunConfig.interruptingToolNames` into every ToolNode this graph\n * compiles so a mid-batch interrupt cannot double-execute non-idempotent\n * siblings on resume. See {@link t.ToolNodeOptions.interruptingToolNames}.\n */\n interruptingToolNames: string[] | undefined;\n eagerEventToolExecutions: Map<string, t.EagerEventToolExecution> = new Map();\n eagerEventToolUsageCount: Map<string, number> = new Map();\n private eagerEventToolUsageCountsByAgentId: Map<string, Map<string, number>> =\n new Map();\n eagerEventToolCallChunks: Map<string, t.EagerEventToolCallChunkState> =\n new Map();\n /**\n * Per-run eager prestart circuit breaker, shared by reference with every\n * ToolNode this graph compiles. When a prestarted execution's args turn\n * out to differ from the final request, ToolNode records the tool name\n * here and the stream handler stops prestarting that tool for the rest of\n * the run — the retry then executes normally instead of re-diverging in a\n * loop (LibreChat#14371).\n */\n eagerEventToolSuppressions: Set<string> = new Set();\n /**\n * Run-scoped execution backend for built-in code tools. Defaults to the\n * remote Code API sandbox when unset.\n */\n toolExecution: t.ToolExecutionConfig | undefined;\n /**\n * Shared registry instance used by every ToolNode compiled from this\n * graph. Lazily constructed on first access so multi-agent graphs\n * produce one registry per run (not one per agent), letting cross-\n * agent `{{tool<i>turn<n>}}` substitutions resolve.\n */\n private _toolOutputRegistry?: ToolOutputReferenceRegistry;\n /**\n * Tool session contexts for automatic state persistence across tool invocations.\n * Keyed by tool name (e.g., Constants.EXECUTE_CODE).\n * Currently supports code execution session tracking (session_id, files).\n */\n sessions: t.ToolSessionMap = new Map();\n\n /**\n * Clears heavy references to allow GC to reclaim memory held by\n * LangGraph's internal config / AsyncLocalStorage RunTree chain.\n * Call after a run completes and content has been extracted.\n */\n clearHeavyState(): void {\n this.config = undefined;\n this.signal = undefined;\n this.callerSignal = undefined;\n this.contentData = [];\n this.contentIndexMap = new Map();\n this.stepKeyIds = new Map();\n this.toolCallStepIds.clear();\n this.messageIdsByStepKey = new Map();\n this.messageStepHasTextDeltas = new Set();\n this.reasoningStepHasDeltas = new Set();\n this.messageStepHasToolCalls = new Map();\n this.prelimMessageIdsByStepKey = new Map();\n this.invokedToolIds = undefined;\n this.handlerRegistry = undefined;\n this.parentToolHandlerRegistry = undefined;\n this.hookRegistry = undefined;\n this.humanInTheLoop = undefined;\n this.toolOutputReferences = undefined;\n this.eagerEventToolExecution = undefined;\n this.codeSessionToolNames = undefined;\n this.interruptingToolNames = undefined;\n this.eagerEventToolExecutions.clear();\n this.clearEagerEventToolUsageCounts();\n this.eagerEventToolCallChunks.clear();\n this.eagerEventToolSuppressions.clear();\n this.toolExecution = undefined;\n this.handlerDispatchedEventCounts.clear();\n /**\n * ToolNodes compiled from this graph captured the registry\n * instance at construction time, so simply dropping the Graph's\n * own reference would leave their captured reference — and every\n * stored `tool<i>turn<n>` entry, plus up to `maxTotalSize` of raw\n * output — alive across subsequent `processStream()` calls. Wipe\n * the registry's contents first so subsequent runs start fresh.\n */\n this._toolOutputRegistry?.clear();\n this._toolOutputRegistry = undefined;\n // NB: `_fileCheckpointer` is intentionally NOT cleared here.\n // `Run.processStream()` calls `clearHeavyState()` in its\n // finally block on natural-completion / error paths — exactly\n // when the host is most likely to want `Run.rewindFiles()` (for\n // rollback after a failed batch). Per-Run isolation is already\n // automatic because each `Run.create()` constructs a brand-new\n // Graph instance, so the next Run gets its own checkpointer\n // without us needing to reset this field. Codex P1 #32: pre-fix\n // the checkpointer was nulled before the caller could reach it.\n // Flush each compiled ToolNode's direct-path turn cache so it\n // doesn't leak across Runs (Codex P2 #33). The cache survives\n // `run()` re-entry by design (resume-stable), but end-of-Run\n // is the right point to reset it. Retain the registrations because\n // the compiled workflow can be reused for later Runs; compilation\n // will not register these instances again.\n for (const node of this._compiledToolNodes) {\n node.clearDirectPathTurns();\n }\n // Subagent executors are likewise compiled once and reused. Clear\n // their per-Run state without dropping the registrations needed by\n // subsequent cleanup cycles.\n for (const executor of this._subagentExecutors) {\n executor.clearHeavyState();\n }\n this.sessions.clear();\n }\n\n getEagerEventToolUsageCount(agentId?: string): Map<string, number> {\n if (agentId == null || agentId === '') {\n return this.eagerEventToolUsageCount;\n }\n let usageCount = this.eagerEventToolUsageCountsByAgentId.get(agentId);\n if (usageCount == null) {\n usageCount = new Map<string, number>();\n this.eagerEventToolUsageCountsByAgentId.set(agentId, usageCount);\n }\n return usageCount;\n }\n\n protected clearEagerEventToolUsageCounts(): void {\n this.eagerEventToolUsageCount.clear();\n for (const usageCount of this.eagerEventToolUsageCountsByAgentId.values()) {\n usageCount.clear();\n }\n }\n\n markHandlerDispatchedEvent(eventName: string, stepId: string): () => void {\n const key = getHandlerDispatchedEventKey(eventName, stepId);\n this.handlerDispatchedEventCounts.set(\n key,\n (this.handlerDispatchedEventCounts.get(key) ?? 0) + 1\n );\n return () => {\n const count = this.handlerDispatchedEventCounts.get(key) ?? 0;\n if (count <= 1) {\n this.handlerDispatchedEventCounts.delete(key);\n return;\n }\n this.handlerDispatchedEventCounts.set(key, count - 1);\n };\n }\n\n hasHandlerDispatchedEvent(eventName: string, stepId: string): boolean {\n const key = getHandlerDispatchedEventKey(eventName, stepId);\n return (this.handlerDispatchedEventCounts.get(key) ?? 0) > 0;\n }\n\n /**\n * Subclass hook to register a freshly compiled ToolNode so\n * `clearHeavyState` can flush its per-Run direct-path turn cache\n * at end-of-Run. Internal — called from `initializeTools` in the\n * concrete graph subclasses.\n */\n protected registerCompiledToolNode(node: {\n clearDirectPathTurns(): void;\n createSubagentResumeState(): SubagentToolNodeResumeState;\n restoreSubagentResumeState(state: SubagentToolNodeResumeState): void;\n }): void {\n this._compiledToolNodes.add(node);\n }\n\n protected registerSubagentExecutor(executor: SubagentExecutor): void {\n this._subagentExecutors.add(executor);\n }\n\n protected resetSubagentCheckpointThreadIds(): void {\n for (const executor of this._subagentExecutors) {\n executor.resetCheckpointThreadIds();\n }\n }\n\n getChildCheckpointThreadIds(): string[] {\n const threadIds = new Set<string>();\n for (const executor of this._subagentExecutors) {\n for (const threadId of executor.getChildCheckpointThreadIds()) {\n threadIds.add(threadId);\n }\n }\n return [...threadIds];\n }\n\n createSubagentResumeState(runId: string): SubagentGraphResumeState {\n return {\n toolCallSteps: [...this.toolCallStepIds].map(([toolCallId, stepId]) => ({\n toolCallId,\n stepId,\n })),\n toolSessions: [...this.sessions].map(([toolName, context]) => ({\n toolName,\n context: {\n ...context,\n ...(context.files == null\n ? {}\n : { files: context.files.map((file) => ({ ...file })) }),\n },\n })),\n toolNodes: [...this._compiledToolNodes].map((node) =>\n node.createSubagentResumeState()\n ),\n eagerToolUsage: [\n {\n agentId: '',\n toolUsageCounts: [...this.eagerEventToolUsageCount].map(\n ([toolName, count]) => ({ toolName, count })\n ),\n },\n ...[...this.eagerEventToolUsageCountsByAgentId].map(\n ([agentId, usageCounts]) => ({\n agentId,\n toolUsageCounts: [...usageCounts].map(([toolName, count]) => ({\n toolName,\n count,\n })),\n })\n ),\n ],\n eagerToolSuppressions: [...this.eagerEventToolSuppressions],\n ...(this._toolOutputRegistry == null\n ? {}\n : {\n toolOutputReferences: this._toolOutputRegistry.snapshotState(runId),\n }),\n };\n }\n\n restoreSubagentResumeState(\n state: SubagentGraphResumeState,\n runId: string\n ): void {\n const toolNodesByKey = new Map(\n [...this._compiledToolNodes].map((node) => {\n const nodeState = node.createSubagentResumeState();\n return [nodeState.stateKey, node] as const;\n })\n );\n if (toolNodesByKey.size !== state.toolNodes.length) {\n throw new Error('Cannot restore changed subagent tool topology.');\n }\n for (const nodeState of state.toolNodes) {\n if (!toolNodesByKey.has(nodeState.stateKey)) {\n throw new Error(\n `Cannot restore subagent tool state for \"${nodeState.stateKey}\".`\n );\n }\n }\n const registry =\n state.toolOutputReferences == null\n ? undefined\n : this.getOrCreateToolOutputRegistry();\n if (state.toolOutputReferences != null && registry == null) {\n throw new Error('Cannot restore disabled tool output references.');\n }\n\n this.toolCallStepIds.clear();\n for (const { toolCallId, stepId } of state.toolCallSteps) {\n this.toolCallStepIds.set(toolCallId, stepId);\n }\n this.sessions.clear();\n for (const { toolName, context } of state.toolSessions) {\n this.sessions.set(toolName, {\n ...context,\n ...(context.files == null\n ? {}\n : { files: context.files.map((file) => ({ ...file })) }),\n });\n }\n for (const nodeState of state.toolNodes) {\n const node = toolNodesByKey.get(nodeState.stateKey)!;\n node.restoreSubagentResumeState(nodeState);\n }\n this.clearEagerEventToolUsageCounts();\n for (const usageState of state.eagerToolUsage) {\n const usageCounts = this.getEagerEventToolUsageCount(usageState.agentId);\n for (const { toolName, count } of usageState.toolUsageCounts) {\n usageCounts.set(toolName, count);\n }\n }\n this.eagerEventToolSuppressions.clear();\n for (const toolName of state.eagerToolSuppressions) {\n this.eagerEventToolSuppressions.add(toolName);\n }\n if (state.toolOutputReferences != null && registry != null) {\n registry.restoreState(runId, state.toolOutputReferences);\n }\n }\n\n /**\n * Returns the shared `ToolOutputReferenceRegistry` for this run,\n * constructing it on first access. Returns `undefined` when the\n * feature is disabled. All ToolNodes compiled from this graph share\n * this single instance so cross-agent `{{…}}` references resolve.\n *\n * @internal Public so `attemptInvoke` can read it through the typed\n * `InvokeContext` and project ToolMessages into LLM-facing annotated\n * copies right before each provider call (see\n * `annotateMessagesForLLM`). Host code should not call this directly\n * — registry mutations outside the ToolNode lifecycle break the\n * partitioning, eviction, and turn-counter invariants.\n */\n public getOrCreateToolOutputRegistry():\n | ToolOutputReferenceRegistry\n | undefined {\n if (this.toolOutputReferences?.enabled !== true) {\n return undefined;\n }\n if (this._toolOutputRegistry == null) {\n this._toolOutputRegistry = new ToolOutputReferenceRegistry({\n maxOutputSize: this.toolOutputReferences.maxOutputSize,\n maxTotalSize: this.toolOutputReferences.maxTotalSize,\n });\n }\n return this._toolOutputRegistry;\n }\n\n /**\n * Single per-Run file checkpointer shared across every ToolNode the\n * graph compiles. Lazily constructed when\n * `toolExecution.local.fileCheckpointing === true` or\n * `toolExecution.cloudflare.fileCheckpointing === true` so\n * multi-agent graphs see ONE snapshot store, not one-per-agent.\n * Returns undefined when checkpointing is disabled or a supported\n * coding-tool engine isn't selected. Exposed via\n * `Run.getFileCheckpointer()` / `Run.rewindFiles()`.\n */\n private _fileCheckpointer?: t.LocalFileCheckpointer;\n /**\n * ToolNodes compiled into this Graph's workflow. Tracked so\n * `clearHeavyState()` can flush their per-Run direct-path turn\n * cache (`directPathTurns`) at end-of-Run — that map intentionally\n * survives `run()` re-entry (resume-stable per Codex P2 #30) but\n * would otherwise grow linearly with tool calls and could collide\n * across Runs if a provider reuses call ids (Codex P2 #33).\n */\n private _compiledToolNodes: Set<{\n clearDirectPathTurns(): void;\n createSubagentResumeState(): SubagentToolNodeResumeState;\n restoreSubagentResumeState(state: SubagentToolNodeResumeState): void;\n }> = new Set();\n private _subagentExecutors = new Set<SubagentExecutor>();\n public getOrCreateFileCheckpointer(): t.LocalFileCheckpointer | undefined {\n // Return the cached instance unconditionally if one exists. The\n // toolExecution check below decides whether to *create* a new\n // one — `clearHeavyState` nulls `this.toolExecution` at end-of-\n // Run, but we want post-Run `Run.rewindFiles()` to still resolve\n // to the checkpointer that captured the writes. Codex P1 #32.\n if (this._fileCheckpointer != null) {\n return this._fileCheckpointer;\n }\n // Eagerly create via the bundle factory so the construction path\n // matches the bundle-only callers (and future bundle-internal\n // cleanup hooks fire). The bundle factory itself accepts a pre-\n // supplied checkpointer when present, so re-injecting this one\n // into every ToolNode is idempotent.\n if (\n this.toolExecution?.engine === 'local' &&\n this.toolExecution.local?.fileCheckpointing === true\n ) {\n const bundle = createLocalCodingToolBundle(\n this.toolExecution.local ?? {}\n );\n this._fileCheckpointer = bundle.checkpointer;\n return this._fileCheckpointer;\n }\n if (\n this.toolExecution?.engine === 'cloudflare-sandbox' &&\n this.toolExecution.cloudflare?.fileCheckpointing === true\n ) {\n const bundle = createCloudflareCodingToolBundle(\n this.toolExecution.cloudflare\n );\n this._fileCheckpointer = bundle.checkpointer;\n return this._fileCheckpointer;\n }\n return undefined;\n }\n}\n\nexport class StandardGraph extends Graph<t.BaseGraphState, t.GraphNode> {\n overrideModel?: t.ChatModel;\n private subagentModelOverride?: t.ChatModel;\n private readonly graphFactory: GraphFactory;\n private readonly supportsMultiAgentChildren: boolean;\n /** Optional compile options passed into workflow.compile() */\n compileOptions?: t.CompileOptions | undefined;\n /** Whether the workflow was actually compiled with a checkpointer. */\n hasCompiledCheckpointer: boolean = false;\n messages: BaseMessage[] = [];\n /** Whether a rebuilt resume seeded the message baseline from its checkpoint. */\n private hasRestoredCheckpointMessages = false;\n /** Cached run messages preserved before clearHeavyState() so getRunMessages() works after cleanup. */\n private cachedRunMessages?: BaseMessage[];\n /** Per-agent discovery snapshots preserved before contexts are reset on cleanup. */\n private cachedDiscoveredTools?: Map<string, string[]>;\n /** Ids of AI turns the agent node returned THIS run; see isRunProducedMessage. */\n protected runProducedAiMessageIds = new Set<string>();\n /** Checkpoint scope whose messages match index-keyed tool snapshots. */\n private originalToolContentCheckpointScope?: string;\n runId: string | undefined;\n /**\n * Identity used to stamp Langfuse runtime scopes and handlers (see\n * `LangfuseRuntimeContext.runId`). Carries an opaque per-instance\n * component: public run ids are unrestricted and may repeat across\n * concurrently executing runs (retries, duplicate submissions,\n * tenant-local message ids), and equal stamps would let those runs adopt\n * each other's scopes. One graph instance = one execution's stamp, shared\n * by the stream handler and every graph-level scope of that execution.\n */\n readonly langfuseScopeRunId: string;\n /**\n * Boundary between historical messages (loaded from conversation state)\n * and messages produced during the current run. Set once in the state\n * reducer when messages first arrive. Used by `getRunMessages()` and\n * multi-agent message filtering — NOT for pruner token counting (the\n * pruner maintains its own `lastTurnStartIndex` in its closure).\n */\n startIndex: number = 0;\n signal?: AbortSignal;\n /** Map of agent contexts by agent ID */\n agentContexts: Map<string, AgentContext> = new Map();\n /** Default agent ID to use */\n defaultAgentId: string;\n /**\n * Host sink for model usage emitted inside subagent child runs. Threaded\n * into each `SubagentExecutor` this graph creates (and from there into\n * child graphs, so nested subagents report too). See\n * {@link t.StandardGraphInput.subagentUsageSink}.\n */\n subagentUsageSink?: t.SubagentUsageSink;\n /** See {@link t.StandardGraphInput.subagentScope}. */\n subagentScope: boolean;\n /** See {@link t.StandardGraphInput.subagentExecutionContext}. */\n private readonly subagentExecutionContext?: t.SubagentExecutionContext;\n /** See {@link t.StandardGraphInput.preemption}. */\n preemption?: t.StreamPreemption;\n /**\n * Stream circuit breakers, resolved once from\n * {@link t.StandardGraphInput.streamLimits}. The stream handler enforces\n * these on every streamed chunk event.\n */\n streamLimits: ResolvedStreamLimits;\n /**\n * Cumulative streamed argument bytes per in-flight tool call, keyed by\n * generation key + chunk index (see `resolveGenerationKey`). Per-run\n * accumulation state, cleared by both reset paths.\n */\n streamedToolCallArgTallies: Map<string, StreamedToolCallArgTally> = new Map();\n /** Streamed chunk events per model generation, keyed by generation key. */\n streamDeltaEventCounts: Map<string, StreamDeltaEventTally> = new Map();\n /** Per-chunk-object, per-generation charge balances (lazily created; see\n * `StreamLimitState`). Reinitialized by both reset paths: a model may\n * retain and re-yield one mutable chunk object, whose nested map would\n * otherwise grow by one attempt-stamped entry per model call for the\n * graph's lifetime. */\n streamLimitChargeCredits?: WeakMap<object, Map<string, number>>;\n /** Run-scoped breaker abort: composed into every model invocation and\n * every SubagentExecutor child signal, and tripped when a stream circuit\n * breaker fires anywhere in the run, so parallel agent nodes' in-flight\n * provider calls and subagents stop consuming quota while the rejection\n * propagates. Recreated by both reset paths — the abort is one-way within\n * a run, and a reused graph must start its next run unaborted. */\n breakerAbort = new AbortController();\n\n /** Incremented whenever `breakerAbort` is replaced. Stamped into each\n * model attempt's metadata ({@link STREAM_LIMIT_EPOCH_KEY}) so the stream\n * handler's consumer-side trip binds to the run that produced the event\n * rather than whichever controller is live when a straggling chunk is\n * finally handled. */\n breakerEpoch = 0;\n\n /** Immutable snapshot of the run's breaker identity (epoch + controller),\n * replaced as ONE object whenever `resetValues` installs a fresh\n * controller. Sites that pause across awaits capture it at entry and\n * revalidate by REFERENCE afterwards — a single identity comparison\n * proves no reset happened while suspended, where separate epoch and\n * controller reads could interleave with one. */\n runScope: RunBreakerScope = Object.freeze({\n epoch: 0,\n controller: this.breakerAbort,\n });\n\n /** Generation keys of model attempts still in flight (see\n * `StreamLimitState.activeStreamLimitGenerations`). Lazily created by the\n * attempt lease; spans resets on purpose. */\n activeStreamLimitGenerations?: Set<string>;\n\n /** The stream-limit error behind an already-fired breaker, whether this\n * graph's own controller tripped or a parent run's breaker arrived through\n * the composed constructor signal (child graphs own separate controllers).\n * Providers can translate either abort into a generic error, and recovery\n * paths must not run in that state. */\n protected resolveTrippedBreakerReason(\n breakerSignal: AbortSignal = this.breakerAbort.signal\n ): StreamLimitExceededError | undefined {\n if (\n breakerSignal.aborted &&\n breakerSignal.reason instanceof StreamLimitExceededError\n ) {\n return breakerSignal.reason;\n }\n if (\n this.signal?.aborted === true &&\n this.signal.reason instanceof StreamLimitExceededError\n ) {\n return this.signal.reason;\n }\n return undefined;\n }\n /**\n * Seals charged against `preemption.maxSeals`. Per-turn: cleared by both\n * reset paths so a fresh turn gets a fresh budget, while a HITL resume —\n * which skips `resetValues` — keeps what it had left.\n */\n private preemptSealBudgetUsed = 0;\n /**\n * Seals honored over the graph's lifetime. Reported by\n * {@link getPreemptStats}, so it deliberately SURVIVES `clearHeavyState()`\n * — a host reads it after `processStream` returns, which is strictly after\n * cleanup runs.\n */\n preemptSealCount = 0;\n /** Boundaries that produced nothing to inject, so the turn stopped early. */\n preemptEmptyBoundaries = 0;\n /**\n * Set between claiming a seal and resolving its boundary. `MultiAgentGraph`\n * fans parallel agents through this one instance against a single host\n * request, so without a one-at-a-time gate several streams would each seal\n * for the same queued message and every loser would take the\n * nothing-to-inject path and cut its answer short.\n */\n private preemptSealInFlight = false;\n /**\n * True when a seal ended the turn without a resume. The assistant turn is\n * real and kept, but it is not the answer the model intended to finish —\n * hosts persist it as unfinished rather than complete.\n */\n preemptIncomplete = false;\n /**\n * `stopReason` from a `PreemptBoundary` hook that halted the turn.\n *\n * Clearing the registry halt is what keeps the sealed turn alive, but the\n * registry held the only copy of the reason — so it is captured here first.\n * Without it `getHaltReason()` returns undefined and a host records a\n * hook-halted turn as an ordinary completion.\n */\n preemptHaltReason: string | undefined;\n /**\n * Agent IDs whose next superstep must return to the agent node. Keyed by\n * agent because `MultiAgentGraph` routes every parallel agent through this\n * same instance, and a single field would let one agent's boundary resume\n * another's turn.\n */\n pendingPreemptReturn = new Set<string>();\n\n constructor(\n {\n runId,\n signal,\n agents,\n langfuse,\n tokenCounter,\n indexTokenCountMap,\n calibrationRatio,\n subagentUsageSink,\n subagentScope,\n subagentExecutionContext,\n preemption,\n streamLimits,\n }: t.StandardGraphInput,\n dependencies?: GraphFactoryDependencies\n ) {\n super();\n this.supportsMultiAgentChildren = dependencies != null;\n this.graphFactory =\n dependencies?.graphFactory ??\n ((request): StandardGraph => {\n if (request.kind !== 'standard') {\n throw new Error(\n 'A polymorphic graph factory is required for multi-agent graph construction.'\n );\n }\n return new StandardGraph(request.input);\n });\n this.runId = runId;\n this.langfuseScopeRunId = `${runId ?? 'graph'}:${nanoid()}`;\n this.signal = signal;\n this.langfuse = langfuse;\n this.subagentUsageSink = subagentUsageSink;\n this.subagentScope = subagentScope === true;\n this.subagentExecutionContext = subagentExecutionContext;\n this.preemption = preemption;\n this.streamLimits = resolveStreamLimits(streamLimits);\n\n if (agents.length === 0) {\n throw new Error('At least one agent configuration is required');\n }\n\n for (const agentConfig of agents) {\n const agentContext = AgentContext.fromConfig(\n agentConfig,\n tokenCounter,\n indexTokenCountMap\n );\n if (calibrationRatio != null && calibrationRatio > 0) {\n agentContext.calibrationRatio = calibrationRatio;\n }\n\n this.agentContexts.set(agentConfig.agentId, agentContext);\n }\n\n this.defaultAgentId = agents[0].agentId;\n }\n\n /* Init */\n\n resetValues(keepContent?: boolean, checkpointScope?: string): void {\n this.resetSubagentCheckpointThreadIds();\n this.messages = [];\n this.hasRestoredCheckpointMessages = false;\n this.cachedRunMessages = undefined;\n this.cachedDiscoveredTools = undefined;\n this.config = resetIfNotEmpty(this.config, undefined);\n if (keepContent !== true) {\n this.contentData = resetIfNotEmpty(this.contentData, []);\n this.contentIndexMap = resetIfNotEmpty(this.contentIndexMap, new Map());\n }\n this.stepKeyIds = resetIfNotEmpty(this.stepKeyIds, new Map());\n /**\n * Clear in-place instead of replacing with a new Map to preserve the\n * shared reference held by ToolNode (passed at construction time).\n * Using resetIfNotEmpty would create a new Map, leaving ToolNode with\n * a stale reference on 2nd+ processStream calls.\n */\n this.toolCallStepIds.clear();\n this.runProducedAiMessageIds.clear();\n this.eagerEventToolExecutions.clear();\n this.clearEagerEventToolUsageCounts();\n this.eagerEventToolCallChunks.clear();\n this.eagerEventToolSuppressions.clear();\n /** Grace sweep instead of a clear: producer loops of straggling\n * attempts use these maps directly and sit outside the consumer-only\n * epoch gate — clearing would hand a cancellation-ignoring provider a\n * fresh allowance at every run start. Entries from the epoch that is\n * ending survive exactly one reset so those stragglers stay on their\n * original budgets; older entries are removed. */\n sweepStaleStreamLimitEntries(\n this.streamedToolCallArgTallies,\n this.breakerEpoch,\n this.activeStreamLimitGenerations\n );\n sweepStaleStreamLimitEntries(\n this.streamDeltaEventCounts,\n this.breakerEpoch,\n this.activeStreamLimitGenerations\n );\n this.streamLimitChargeCredits = undefined;\n /** Run-start is the only safe replacement point for the breaker:\n * end-of-run cleanup must leave it in place so straggling parallel\n * children from the failed run cannot start on a fresh signal.\n * Replaced UNCONDITIONALLY here — a run that failed on an ordinary\n * error leaves the controller un-aborted, and stragglers still settling\n * hold their entry-time capture of it; a late stream-limit trip on that\n * old controller must not cancel the run starting now. */\n this.breakerAbort = new AbortController();\n this.breakerEpoch += 1;\n this.runScope = Object.freeze({\n epoch: this.breakerEpoch,\n controller: this.breakerAbort,\n });\n this.handlerDispatchedStepIds = resetIfNotEmpty(\n this.handlerDispatchedStepIds,\n new Set()\n );\n this.handlerDispatchedEventCounts = resetIfNotEmpty(\n this.handlerDispatchedEventCounts,\n new Map()\n );\n this.messageIdsByStepKey = resetIfNotEmpty(\n this.messageIdsByStepKey,\n new Map()\n );\n this.messageStepHasToolCalls = resetIfNotEmpty(\n this.messageStepHasToolCalls,\n new Map()\n );\n this.messageStepHasTextDeltas = resetIfNotEmpty(\n this.messageStepHasTextDeltas,\n new Set()\n );\n this.reasoningStepHasDeltas = resetIfNotEmpty(\n this.reasoningStepHasDeltas,\n new Set()\n );\n this.prelimMessageIdsByStepKey = resetIfNotEmpty(\n this.prelimMessageIdsByStepKey,\n new Map()\n );\n this.invokedToolIds = resetIfNotEmpty(this.invokedToolIds, undefined);\n this.resetPreemptTurnState();\n this.resetPreemptTotals();\n const hasScopedCheckpoint =\n this.hasCompiledCheckpointer &&\n checkpointScope != null &&\n checkpointScope !== '';\n const preserveOriginalToolContent =\n hasScopedCheckpoint &&\n this.originalToolContentCheckpointScope === checkpointScope;\n for (const context of this.agentContexts.values()) {\n context.reset({ preserveOriginalToolContent });\n }\n this.originalToolContentCheckpointScope = hasScopedCheckpoint\n ? checkpointScope\n : undefined;\n }\n\n /** Seeds the sidecar message view that checkpoint restoration bypasses. */\n override restoreCheckpointMessages(\n messages: BaseMessage[],\n pendingMessages?: BaseMessage[]\n ): void {\n if (this.messages.length > 0) {\n return;\n }\n this.messages =\n pendingMessages == null\n ? [...messages]\n : messagesStateReducer(messages, pendingMessages);\n this.startIndex = this.messages.length;\n this.hasRestoredCheckpointMessages = true;\n this.cachedRunMessages = undefined;\n }\n\n override clearHeavyState(): void {\n this.cachedRunMessages = this.messages.slice(this.startIndex);\n this.cachedDiscoveredTools = new Map(\n Array.from(this.agentContexts, ([agentId, context]) => [\n agentId,\n context.getDiscoveredTools(),\n ])\n );\n super.clearHeavyState();\n this.messages = [];\n this.overrideModel = undefined;\n this.subagentModelOverride = undefined;\n /** Stream-limit accounting (argument tallies, event counts, charge\n * credits) deliberately SURVIVES cleanup: this runs in `processStream`'s\n * finally, which an ordinary parallel-branch failure reaches while\n * sibling attempts are still unwinding on the retained breaker — a\n * cancellation-ignoring provider's late chunks would otherwise recreate\n * their budgets from zero and stream another full allowance. The maps\n * are bounded by in-flight call sizes and `resetValues` clears them at\n * the next run start, where the epoch bump already drops stamped\n * straggler events before accounting. */\n /** Deliberately NOT recreating a tripped breakerAbort here: this runs in\n * `processStream`'s cleanup, which a rejected parallel batch reaches\n * while sibling subagents can still be pre-invoke — a fresh controller\n * would hand them an un-aborted signal and let provider requests start\n * after the run already failed. `resetValues` recreates it when the next\n * run begins. */\n /**\n * Turn state only. The reported totals must outlive cleanup — this runs\n * in `processStream`'s `finally`, and the host reads `getPreemptStats()`\n * after that returns.\n */\n this.resetPreemptTurnState();\n const preserveOriginalToolContent =\n this.hasCompiledCheckpointer &&\n this.originalToolContentCheckpointScope != null;\n for (const context of this.agentContexts.values()) {\n context.reset({ preserveOriginalToolContent });\n }\n }\n\n /**\n * Per-turn seal budget and routing markers. Cleared by both reset paths so\n * a new turn starts with a full budget and no stale resume marker.\n *\n * The REPORTED counters are deliberately not touched here — see\n * {@link resetPreemptTotals}.\n */\n private resetPreemptTurnState(): void {\n this.preemptSealBudgetUsed = 0;\n this.preemptSealInFlight = false;\n this.pendingPreemptReturn.clear();\n }\n\n /**\n * Lifetime seal totals, cleared only when a genuinely new run starts.\n * `clearHeavyState()` must NOT call this: it runs in `processStream`'s\n * `finally`, so zeroing here would make {@link getPreemptStats} and\n * `preemptIncomplete` unreadable for every caller of the method that just\n * produced them.\n */\n private resetPreemptTotals(): void {\n this.preemptSealCount = 0;\n this.preemptEmptyBoundaries = 0;\n this.preemptIncomplete = false;\n this.preemptHaltReason = undefined;\n }\n\n /**\n * True when the host has requested a cooperative seal AND this graph may\n * honor it. Read once per streamed chunk, so it stays property reads plus\n * one host callback — no I/O, no allocation.\n *\n * Non-mutating: a true result only means a seal is worth evaluating. The\n * budget is taken by {@link claimPreemptSeal} once the accumulated chunk is\n * known to be safe, so a chunk that cannot seal never spends budget.\n *\n * Subagent scopes never seal: a steer targets the top-level conversation,\n * and a child run must finish so its parent sees a complete result.\n */\n /** Internal seal preconditions only — no host callback, no side effects. */\n private canClaimPreemptSeal(): boolean {\n /**\n * Resolved and required here with the same rule `dispatchPreemptBoundary`\n * uses. Without it a direct `StandardGraph` consumer that supplies no\n * `runId` could claim a seal on the strength of a global matcher, then hit\n * the boundary's own null-runId guard and get nothing back — truncating\n * the answer for a drain that provably could not run.\n */\n const runId =\n (this.config?.configurable?.run_id as string | undefined) ?? this.runId;\n return (\n !this.subagentScope &&\n this.preemption != null &&\n !this.preemptSealInFlight &&\n this.preemptSealBudgetUsed < resolveMaxSeals(this.preemption.maxSeals) &&\n runId != null &&\n /**\n * A seal only buys room for an injection. With no `PreemptBoundary`\n * matcher live — never registered, or a `once` matcher already\n * consumed — the boundary provably returns nothing and the answer is\n * cut short for no gain, so refuse the seal instead. Failing closed\n * lands on the documented no-preemption behavior: the model finishes\n * and the message waits for the next tool boundary.\n *\n * Same session resolution as `dispatchPreemptBoundary`, or a\n * session-scoped matcher would be visible at one site and not the other.\n */\n this.hookRegistry?.hasDispatchableHookFor('PreemptBoundary', runId) ===\n true\n );\n }\n\n shouldPreemptStream(): boolean {\n return (\n this.canClaimPreemptSeal() && this.preemption?.shouldPreempt() === true\n );\n }\n\n /**\n * Takes the seal slot, or returns false if another stream already holds it.\n *\n * Assumes the caller already polled `shouldPreemptStream()` for THIS chunk,\n * and deliberately does not poll the host again — `StreamPreemption`\n * documents `shouldPreempt` as once per chunk, and a host that consumes a\n * pending flag on read would lose the request to a second call.\n *\n * The guard and both mutations remain one synchronous body, which is what\n * makes this safe under a parallel `MultiAgentGraph`: several agents share\n * one graph and can each see the poll as true, but no `await` can split the\n * claim, so only one takes the slot. The loser keeps streaming normally\n * rather than sealing for a message it would never receive.\n */\n claimPreemptSeal(): boolean {\n if (!this.canClaimPreemptSeal()) {\n return false;\n }\n this.preemptSealInFlight = true;\n this.preemptSealBudgetUsed += 1;\n this.preemptSealCount += 1;\n return true;\n }\n\n /** Releases the seal slot once its boundary has resolved, win or lose. */\n releasePreemptSeal(): void {\n this.preemptSealInFlight = false;\n }\n\n getPreemptStats(): t.PreemptStats {\n return {\n seals: this.preemptSealCount,\n emptyBoundaries: this.preemptEmptyBoundaries,\n };\n }\n\n /* Run Step Processing */\n\n getRunStep(stepId: string): t.RunStep | undefined {\n const index = this.contentIndexMap.get(stepId);\n if (index !== undefined) {\n return this.contentData[index];\n }\n return undefined;\n }\n\n getAgentContext(metadata: Record<string, unknown> | undefined): AgentContext {\n if (!metadata) {\n throw new Error('No metadata provided to retrieve agent context');\n }\n\n const currentNode = metadata.langgraph_node as string;\n if (!currentNode) {\n throw new Error(\n 'No langgraph_node in metadata to retrieve agent context'\n );\n }\n\n let agentId: string | undefined;\n if (currentNode.startsWith(AGENT)) {\n agentId = currentNode.substring(AGENT.length);\n } else if (currentNode.startsWith(TOOLS)) {\n agentId = currentNode.substring(TOOLS.length);\n } else if (currentNode.startsWith(SUMMARIZE)) {\n agentId = currentNode.substring(SUMMARIZE.length);\n }\n\n const agentContext = this.agentContexts.get(agentId ?? '');\n if (!agentContext) {\n throw new Error(`No agent context found for agent ID ${agentId}`);\n }\n\n return agentContext;\n }\n\n getStepBaseKey(metadata: Record<string, unknown> | undefined): string {\n if (!metadata) return '';\n\n const keyList = this.getInvocationKeyList(metadata);\n if (this.checkKeyList(keyList)) {\n throw new Error('Missing metadata');\n }\n\n return joinKeys(keyList);\n }\n\n getStepKey(metadata: Record<string, unknown> | undefined): string {\n if (!metadata) return '';\n\n const keyList = this.getKeyList(metadata);\n if (this.checkKeyList(keyList)) {\n throw new Error('Missing metadata');\n }\n\n return joinKeys(keyList);\n }\n\n getStepIdByKey(stepKey: string, index?: number): string {\n const stepIds = this.stepKeyIds.get(stepKey);\n if (!stepIds) {\n throw new Error(`No step IDs found for stepKey ${stepKey}`);\n }\n\n if (index === undefined) {\n return stepIds[stepIds.length - 1];\n }\n\n return stepIds[index];\n }\n\n generateStepId(stepKey: string): [string, number] {\n const stepIds = this.stepKeyIds.get(stepKey);\n let newStepId: string | undefined;\n let stepIndex = 0;\n if (stepIds) {\n stepIndex = stepIds.length;\n newStepId = `step_${nanoid()}`;\n stepIds.push(newStepId);\n this.stepKeyIds.set(stepKey, stepIds);\n } else {\n newStepId = `step_${nanoid()}`;\n this.stepKeyIds.set(stepKey, [newStepId]);\n }\n\n return [newStepId, stepIndex];\n }\n\n getKeyList(\n metadata: Record<string, unknown> | undefined\n ): (string | number | undefined)[] {\n if (!metadata) return [];\n\n const keyList = this.getInvocationKeyList(metadata);\n const agentContext = this.getAgentContext(metadata);\n if (\n agentContext.currentTokenType === ContentTypes.THINK ||\n agentContext.currentTokenType === 'think_and_text'\n ) {\n keyList.push('reasoning');\n } else if (agentContext.tokenTypeSwitch === 'content') {\n keyList.push(`post-reasoning-${agentContext.reasoningTransitionCount}`);\n }\n\n return keyList;\n }\n\n private getInvocationKeyList(\n metadata: Record<string, unknown>\n ): (string | number | undefined)[] {\n const keyList = this.getBaseKeyList(metadata);\n if (this.invokedToolIds != null && this.invokedToolIds.size > 0) {\n keyList.push(this.invokedToolIds.size + '');\n }\n return keyList;\n }\n\n private getBaseKeyList(\n metadata: Record<string, unknown>\n ): (string | number | undefined)[] {\n const configurable = this.config?.configurable;\n const runId =\n (metadata.run_id as string | undefined) ??\n (configurable?.run_id as string | undefined) ??\n this.runId;\n const threadId =\n (metadata.thread_id as string | undefined) ??\n (configurable?.thread_id as string | undefined) ??\n runId;\n const checkpointNs =\n (metadata.checkpoint_ns as string | undefined) ??\n (metadata.langgraph_checkpoint_ns as string | undefined) ??\n '';\n const keyList = [\n runId,\n threadId,\n metadata.langgraph_node as string,\n metadata.langgraph_step as number,\n checkpointNs,\n ];\n\n return keyList;\n }\n\n checkKeyList(keyList: (string | number | undefined)[]): boolean {\n return keyList.some((key) => key === undefined);\n }\n\n /* Misc.*/\n\n getRunMessages(): BaseMessage[] | undefined {\n /** Runtime-honest widening: a disposed-but-cached graph (HITL\n * resume/reconnect through a WeakRef cache) can carry null here despite\n * the field type. */\n const messages = this.messages as BaseMessage[] | undefined;\n if (messages == null) {\n return this.cachedRunMessages;\n }\n if (messages.length === 0 && this.cachedRunMessages != null) {\n return this.cachedRunMessages;\n }\n return messages.slice(this.startIndex);\n }\n\n override getDiscoveredTools(agentId?: string): string[] {\n if (agentId != null) {\n const current =\n this.agentContexts.get(agentId)?.getDiscoveredTools() ?? [];\n if (current.length > 0 || this.cachedDiscoveredTools == null) {\n return current;\n }\n return [...(this.cachedDiscoveredTools.get(agentId) ?? [])];\n }\n\n const discoveredTools = new Set<string>();\n for (const context of this.agentContexts.values()) {\n for (const toolName of context.getDiscoveredTools()) {\n discoveredTools.add(toolName);\n }\n }\n if (discoveredTools.size === 0 && this.cachedDiscoveredTools != null) {\n for (const snapshot of this.cachedDiscoveredTools.values()) {\n for (const toolName of snapshot) {\n discoveredTools.add(toolName);\n }\n }\n }\n return Array.from(discoveredTools);\n }\n\n /**\n * True when THIS RUN produced `message` — the provenance the handoff cue\n * gate needs. Tracked as an id set rather than inferred from `startIndex`\n * arithmetic: summarization's remove-all compaction rewrites the live\n * array and leaves `startIndex` stale, so index-based run/host\n * discrimination silently breaks right after a mid-run summarize. Ids\n * survive compaction (retained messages keep theirs), host-supplied\n * prefill messages are never in the set, and membership is O(1) per\n * model call.\n */\n isRunProducedMessage(message: BaseMessage): boolean {\n const id = message.id;\n return (\n typeof id === 'string' &&\n id !== '' &&\n this.runProducedAiMessageIds.has(id)\n );\n }\n\n getContentParts(): t.MessageContentComplex[] | undefined {\n // `messages` can be null/undefined on a graph that has been disposed\n // (clearHeavyState) but is still reachable via a cache (e.g. RedisJobStore's\n // WeakRef) during a HITL resume/reconnect. Guard instead of dereferencing null.\n const messages = this.messages as BaseMessage[] | undefined;\n if (messages == null) {\n return undefined;\n }\n return convertMessagesToContent(messages.slice(this.startIndex));\n }\n\n getCalibrationRatio(): number {\n const context = this.agentContexts.get(this.defaultAgentId);\n return context?.calibrationRatio ?? 1;\n }\n\n getResolvedInstructionOverhead(): number | undefined {\n const context = this.agentContexts.get(this.defaultAgentId);\n return context?.resolvedInstructionOverhead;\n }\n\n getToolCount(): number {\n const context = this.agentContexts.get(this.defaultAgentId);\n return (\n (context?.tools?.length ?? 0) +\n (context?.toolDefinitions?.length ?? 0) +\n /**\n * Graph-managed + host-supplied direct tools (handoff, subagent,\n * `AgentInputs.graphTools`) are bound to the model and token-accounted,\n * so a count that omits them under-reports the run's tool surface\n * (Codex #289 P3).\n */\n (context?.graphTools?.length ?? 0)\n );\n }\n\n /**\n * Get all run steps, optionally filtered by agent ID\n */\n getRunSteps(agentId?: string): t.RunStep[] {\n // `contentData` can be null/undefined on a disposed-but-cached graph during a\n // HITL resume/reconnect; without this guard `[...this.contentData]` throws\n // \"this.contentData is not iterable\".\n const contentData = this.contentData as t.RunStep[] | undefined;\n if (contentData == null) {\n return [];\n }\n if (agentId == null || agentId === '') {\n return [...contentData];\n }\n return contentData.filter((step) => step.agentId === agentId);\n }\n\n /**\n * Get run steps grouped by agent ID\n */\n getRunStepsByAgent(): Map<string, t.RunStep[]> {\n const stepsByAgent = new Map<string, t.RunStep[]>();\n\n for (const step of this.contentData) {\n if (step.agentId == null || step.agentId === '') continue;\n\n const steps = stepsByAgent.get(step.agentId) ?? [];\n steps.push(step);\n stepsByAgent.set(step.agentId, steps);\n }\n\n return stepsByAgent;\n }\n\n /**\n * Get agent IDs that participated in this run\n */\n getActiveAgentIds(): string[] {\n const agentIds = new Set<string>();\n for (const step of this.contentData) {\n if (step.agentId != null && step.agentId !== '') {\n agentIds.add(step.agentId);\n }\n }\n return Array.from(agentIds);\n }\n\n /**\n * Maps contentPart indices to agent IDs for post-run analysis\n * Returns a map where key is the contentPart index and value is the agentId\n */\n getContentPartAgentMap(): Map<number, string> {\n const contentPartAgentMap = new Map<number, string>();\n\n for (const step of this.contentData) {\n if (\n step.agentId != null &&\n step.agentId !== '' &&\n Number.isFinite(step.index)\n ) {\n contentPartAgentMap.set(step.index, step.agentId);\n }\n }\n\n return contentPartAgentMap;\n }\n\n /* Graph */\n\n initializeTools({\n currentTools,\n currentToolMap,\n agentContext,\n }: {\n currentTools?: t.GraphTools;\n currentToolMap?: t.ToolMap;\n agentContext?: AgentContext;\n }): CustomToolNode<t.BaseGraphState> | ToolNode<t.BaseGraphState> {\n const toolDefinitions = agentContext?.toolDefinitions;\n const eventDrivenMode =\n toolDefinitions != null && toolDefinitions.length > 0;\n const traceToolNode = shouldTraceToolNodeForLangfuse({\n runLangfuse: this.langfuse,\n agentLangfuse: agentContext?.langfuse,\n });\n const interruptingToolNames = new Set(this.interruptingToolNames ?? []);\n if (\n this.humanInTheLoop?.enabled === true &&\n (agentContext?.subagentConfigs?.length ?? 0) > 0\n ) {\n interruptingToolNames.add(Constants.SUBAGENT);\n }\n const effectiveInterruptingToolNames =\n interruptingToolNames.size > 0 ? interruptingToolNames : undefined;\n\n if (eventDrivenMode) {\n const schemaTools = createSchemaOnlyTools(toolDefinitions);\n const toolDefMap = new Map(toolDefinitions.map((def) => [def.name, def]));\n const graphTools = agentContext?.graphTools as\n | t.GenericTool[]\n | undefined;\n\n const directToolNames = new Set<string>();\n const allTools = [...schemaTools] as t.GenericTool[];\n const allToolMap: t.ToolMap = new Map(\n schemaTools.map((tool) => [tool.name, tool])\n );\n\n if (graphTools && graphTools.length > 0) {\n for (const tool of graphTools) {\n if ('name' in tool) {\n allTools.push(tool);\n allToolMap.set(tool.name, tool);\n directToolNames.add(tool.name);\n }\n }\n }\n\n const node = new CustomToolNode<t.BaseGraphState>({\n tools: allTools,\n toolMap: allToolMap,\n trace: traceToolNode,\n runLangfuse: this.langfuse,\n agentLangfuse: agentContext?.langfuse,\n eventDrivenMode: true,\n sessions: this.sessions,\n toolDefinitions: toolDefMap,\n // `agentId` is the subagent-scope marker — set ONLY for child-run\n // graphs (hooks fire for child scopes too, via the inherited\n // run_id); `executingAgentId` always identifies the owning agent.\n agentId: this.subagentScope ? agentContext?.agentId : undefined,\n executingAgentId: agentContext?.agentId,\n toolCallStepIds: this.toolCallStepIds,\n toolRegistry: agentContext?.toolRegistry,\n hookRegistry: this.hookRegistry,\n humanInTheLoop: this.humanInTheLoop,\n eagerEventToolExecution: this.eagerEventToolExecution,\n codeSessionToolNames: this.codeSessionToolNames,\n eagerEventToolExecutions: this.eagerEventToolExecutions,\n eagerEventToolUsageCount: this.getEagerEventToolUsageCount(\n agentContext?.agentId\n ),\n eagerEventToolSuppressions: this.eagerEventToolSuppressions,\n toolExecution: this.toolExecution,\n directToolNames: directToolNames.size > 0 ? directToolNames : undefined,\n interruptingToolNames: effectiveInterruptingToolNames,\n maxContextTokens: agentContext?.maxContextTokens,\n maxToolResultChars: agentContext?.maxToolResultChars,\n toolOutputRegistry: this.getOrCreateToolOutputRegistry(),\n fileCheckpointer: this.getOrCreateFileCheckpointer(),\n getBreakerSignal: (): AbortSignal => this.breakerAbort.signal,\n getRunScope: (): RunBreakerScope => this.runScope,\n errorHandler: (data, metadata): Promise<boolean> =>\n StandardGraph.handleToolCallErrorStatic(this, data, metadata),\n });\n this.registerCompiledToolNode(node);\n return node;\n }\n\n const graphTools = agentContext?.graphTools as t.GenericTool[] | undefined;\n const baseTools = (currentTools as t.GenericTool[] | undefined) ?? [];\n const allTraditionalTools =\n graphTools && graphTools.length > 0\n ? [...baseTools, ...graphTools]\n : baseTools;\n /**\n * ToolNode treats a supplied `toolMap` as authoritative (it only derives\n * one from `tools` when the param is undefined), so when graphTools force\n * us to build a merged map here, an absent `currentToolMap` must be\n * seeded from the BASE tools first — otherwise ordinary tools stay bound\n * to the model but vanish from the execution map and every call to them\n * fails as an unknown tool (Codex #289 round 2).\n */\n const traditionalToolMap =\n graphTools && graphTools.length > 0\n ? new Map([\n ...(currentToolMap ??\n new Map(\n baseTools\n .filter(\n (t): t is t.GenericTool & { name: string } => 'name' in t\n )\n .map((t) => [t.name, t] as [string, t.GenericTool])\n )),\n ...graphTools\n .filter((t): t is t.GenericTool & { name: string } => 'name' in t)\n .map((t) => [t.name, t] as [string, t.GenericTool]),\n ])\n : currentToolMap;\n\n const node = new CustomToolNode<t.BaseGraphState>({\n tools: allTraditionalTools,\n toolMap: traditionalToolMap,\n trace: traceToolNode,\n runLangfuse: this.langfuse,\n agentLangfuse: agentContext?.langfuse,\n // `agentId` is the subagent-scope marker — set ONLY for child-run\n // graphs; `executingAgentId` always identifies the owning agent so\n // hooks can attribute the batch even at the top level.\n agentId: this.subagentScope ? agentContext?.agentId : undefined,\n executingAgentId: agentContext?.agentId,\n toolCallStepIds: this.toolCallStepIds,\n errorHandler: (data, metadata): Promise<boolean> =>\n StandardGraph.handleToolCallErrorStatic(this, data, metadata),\n toolRegistry: agentContext?.toolRegistry,\n sessions: this.sessions,\n toolExecution: this.toolExecution,\n codeSessionToolNames: this.codeSessionToolNames,\n interruptingToolNames: effectiveInterruptingToolNames,\n hookRegistry: this.hookRegistry,\n humanInTheLoop: this.humanInTheLoop,\n maxContextTokens: agentContext?.maxContextTokens,\n maxToolResultChars: agentContext?.maxToolResultChars,\n toolOutputRegistry: this.getOrCreateToolOutputRegistry(),\n fileCheckpointer: this.getOrCreateFileCheckpointer(),\n getBreakerSignal: (): AbortSignal => this.breakerAbort.signal,\n getRunScope: (): RunBreakerScope => this.runScope,\n });\n this.registerCompiledToolNode(node);\n return node;\n }\n\n overrideTestModel(\n responses: string[],\n sleep?: number,\n toolCalls?: ToolCall[]\n ): void {\n this.overrideModel = createFakeStreamingLLM({\n responses,\n sleep,\n toolCalls,\n });\n }\n\n /** Explicitly overrides the model used by isolated descendant subagent graphs. */\n setSubagentModelOverride(model: t.ChatModel): void {\n this.subagentModelOverride = model;\n }\n\n getUsageMetadata(\n finalMessage?: BaseMessage\n ): Partial<UsageMetadata> | undefined {\n if (\n finalMessage &&\n 'usage_metadata' in finalMessage &&\n finalMessage.usage_metadata != null\n ) {\n return finalMessage.usage_metadata as Partial<UsageMetadata>;\n }\n }\n\n cleanupSignalListener(currentModel?: t.ChatModel): void {\n if (!this.signal) {\n return;\n }\n const model = this.overrideModel ?? currentModel;\n if (!model) {\n return;\n }\n const client = (model as ChatOpenAI | undefined)?.exposedClient;\n if (!client?.abortHandler) {\n return;\n }\n this.signal.removeEventListener('abort', client.abortHandler);\n client.abortHandler = undefined;\n }\n\n /**\n * Applies a context-overflow recovery plan and hands control to the\n * summarize node, which compacts and then routes straight back here for a\n * retry against the corrected budget.\n *\n * Returning the detour rather than rethrowing is the whole point: the\n * caller never sees the provider's rejection, only a slightly longer turn.\n */\n private beginOverflowRecovery({\n recovery,\n agentContext,\n agentId,\n config,\n originalToolContent,\n estimatedPromptTokens,\n }: {\n recovery: OverflowRecoveryPlan;\n agentContext: AgentContext;\n agentId: string;\n config?: RunnableConfig;\n /** Masking record from the prune pass that built the rejected prompt. */\n originalToolContent?: Map<number, string>;\n /** Size of the rejected prompt, recorded to detect a correction that changed nothing. */\n estimatedPromptTokens?: number;\n }): Partial<t.AgentSubgraphState> {\n const previousBudget = agentContext.maxContextTokens;\n /**\n * Deterministic compaction first. Re-pruning against the corrected budget\n * raises context pressure, which is what drives the pruner's tool-output\n * truncation and observation masking — no model call, no cost, and no\n * message content lost. A summarization call is held back until that has\n * been tried and the provider rejected the prompt again.\n */\n const allowSummarization = agentContext.shouldSummarizeOverflow();\n\n agentContext.preserveOriginalToolContent(originalToolContent);\n agentContext.applyContextBudgetCorrection(\n recovery.budgetTokens,\n estimatedPromptTokens\n );\n agentContext.applyObservedOverflowCalibration(\n recovery.info.provider,\n recovery.observedCalibrationRatio\n );\n\n emitAgentLog(\n config,\n 'warn',\n 'graph',\n 'Provider rejected the prompt as too large — compacting and retrying',\n {\n kind: recovery.info.kind,\n previousBudget,\n recoveredBudget: recovery.budgetTokens,\n providerReportedLimit: recovery.info.limitTokens,\n providerReportedTokens: recovery.info.requestedTokens,\n providerReportedPromptTokens: recovery.info.promptTokens,\n observedCalibrationRatio: recovery.observedCalibrationRatio,\n detectedBy: recovery.info.source,\n attempt: agentContext.overflowRecoveryAttempts,\n compaction: allowSummarization ? 'summarize' : 'compress',\n },\n { runId: this.runId, agentId },\n { force: true }\n );\n\n return {\n summarizationRequest: {\n remainingContextTokens: 0,\n agentId: agentId || agentContext.agentId,\n reason: 'overflow',\n allowSummarization,\n },\n };\n }\n\n createCallModel(agentId = 'default') {\n return async (\n state: t.AgentSubgraphState,\n config?: RunnableConfig\n ): Promise<Partial<t.AgentSubgraphState>> => {\n /** Captured at node ENTRY, before any host-facing await (context-usage\n * dispatch, hooks): a sibling's trip can fail the run and a prompt\n * next run can reset the controller while this node is paused in one\n * of those awaits, and a later capture would bind this attempt to the\n * fresh controller. Trips and reason reads below stay on this\n * capture. */\n const attemptBreaker = this.breakerAbort;\n const attemptBreakerEpoch = this.breakerEpoch;\n /** Already-tripped-at-entry: a parallel sibling's breach has failed\n * the run before this node was scheduled. Rethrow before hooks or the\n * provider call — a custom provider that doesn't synchronously reject\n * an aborted signal would otherwise start another model request on a\n * failed run. */\n const entryTripReason = this.resolveTrippedBreakerReason(\n attemptBreaker.signal\n );\n if (entryTripReason != null) {\n throw entryTripReason;\n }\n const agentContext = this.agentContexts.get(agentId);\n if (!agentContext) {\n throw new Error(`Agent context not found for agentId: ${agentId}`);\n }\n\n if (!config) {\n throw new Error('No config provided');\n }\n\n /**\n * A `PreemptBoundary` hook halted this run and the sealed commit is\n * already in state. Enforced at every model node's ENTRY because that\n * is the only site that covers all of `MultiAgentGraph`'s onward\n * routing at once — static direct edges, Command fan-out, fan-in\n * wrappers, and parallel siblings' subsequent inner-loop turns — none\n * of which consult the halt (the registry signal was deliberately\n * cleared to keep the stream-cancel from destroying the sealed turn).\n * Declining the model call turns every routed-to successor into a\n * no-op, so the outer workflow drains to END without new turns or tool\n * side effects. Reset per turn in `resetPreemptTotals`, so the next\n * `processStream` call starts clean.\n */\n if (this.preemptHaltReason != null) {\n return { messages: [] };\n }\n\n const { messages } = state;\n\n const discoveredNames = extractToolDiscoveries(messages);\n if (discoveredNames.length > 0) {\n agentContext.markToolsAsDiscovered(discoveredNames);\n }\n\n const rawToolsForBinding = resolveLocalToolsForBinding({\n tools: agentContext.getToolsForBinding(),\n toolExecution: this.toolExecution,\n });\n\n /**\n * Anthropic prompt-cache breakpoint on the tool definitions.\n *\n * Without this, the (often static) tool inventory shows up as\n * fresh input on every turn — measured at ~28k tokens/turn for\n * the local engine's coding-tool bundle, dominating per-turn\n * cost even when message-level caching is on.\n *\n * Strategy: partition tools into [static, deferred] and stamp\n * `cache_control: ephemeral` on the last static tool.\n * Discovered deferred tools that arrive across turns sit *after*\n * the breakpoint and don't invalidate the prefix.\n */\n let toolsForBinding = rawToolsForBinding;\n if (\n agentContext.provider === Providers.ANTHROPIC &&\n (agentContext.clientOptions as t.AnthropicClientOptions | undefined)\n ?.promptCache === true\n ) {\n toolsForBinding =\n partitionAndMarkAnthropicToolCache(\n rawToolsForBinding,\n makeIsDeferred(agentContext.toolDefinitions),\n resolvePromptCacheTtl(\n (\n agentContext.clientOptions as\n | t.AnthropicClientOptions\n | undefined\n )?.promptCacheTtl\n )\n ) ?? rawToolsForBinding;\n } else if (\n agentContext.provider === Providers.OPENROUTER &&\n (\n agentContext.clientOptions as\n | t.ProviderOptionsMap[Providers.OPENROUTER]\n | undefined\n )?.promptCache === true\n ) {\n toolsForBinding =\n partitionAndMarkOpenRouterToolCache(\n rawToolsForBinding,\n makeIsDeferred(agentContext.toolDefinitions),\n resolvePromptCacheTtl(\n (\n agentContext.clientOptions as\n | t.ProviderOptionsMap[Providers.OPENROUTER]\n | undefined\n )?.promptCacheTtl\n )\n ) ?? rawToolsForBinding;\n } else if (\n agentContext.provider === Providers.BEDROCK &&\n (\n agentContext.clientOptions as\n | t.BedrockAnthropicClientOptions\n | undefined\n )?.promptCache === true\n ) {\n const bedrockModel = (\n agentContext.clientOptions as { model?: string } | undefined\n )?.model;\n // An omitted model falls back to LangChain's default Claude model (which\n // supports tool caching); only an explicit non-Claude model (e.g. Nova)\n // skips tool marking so its stray marker never leaks into toolConfig.\n if (bedrockModel == null || supportsBedrockToolCache(bedrockModel)) {\n toolsForBinding =\n partitionAndMarkBedrockToolCache(\n rawToolsForBinding,\n makeIsDeferred(agentContext.toolDefinitions)\n ) ?? rawToolsForBinding;\n }\n }\n\n let model =\n this.overrideModel ??\n initializeModel({\n tools: toolsForBinding,\n provider: agentContext.provider,\n clientOptions: agentContext.clientOptions,\n });\n\n if (agentContext.systemRunnable) {\n model = agentContext.systemRunnable.pipe(model as Runnable);\n }\n\n if (agentContext.tokenCalculationPromise) {\n await agentContext.tokenCalculationPromise;\n }\n if (!config.signal) {\n config.signal = this.signal;\n }\n this.config = config;\n\n let messagesToUse = messages;\n let contextUsage: t.ContextUsageEvent | null = null;\n /**\n * Held outside the prune block so overflow recovery — which detours to\n * the summarize node from the invoke catch below — can preserve the\n * same masking record the configured trigger preserves.\n */\n let prunedOriginalToolContent: Map<number, string> | undefined;\n if (\n !agentContext.pruneMessages &&\n agentContext.tokenCounter &&\n agentContext.maxContextTokens != null\n ) {\n agentContext.pruneMessages = createPruneMessages({\n startIndex:\n agentContext.indexTokenCountMap[0] != null ? this.startIndex : 0,\n provider: agentContext.provider,\n tokenCounter: agentContext.tokenCounter,\n maxTokens: agentContext.maxContextTokens,\n maxToolResultChars: agentContext.maxToolResultChars,\n thinkingEnabled: isThinkingEnabled(\n agentContext.provider,\n agentContext.clientOptions\n ),\n indexTokenCountMap: agentContext.indexTokenCountMap,\n contextPruningConfig: agentContext.contextPruningConfig,\n summarizationEnabled: agentContext.summarizationEnabled,\n reserveRatio: agentContext.summarizationConfig?.reserveRatio,\n calibrationRatio: agentContext.calibrationRatio,\n getInstructionTokens: () => agentContext.instructionTokens,\n log: (level, message, data) => {\n emitAgentLog(config, level, 'prune', message, data, {\n runId: this.runId,\n agentId,\n });\n },\n });\n }\n if (agentContext.pruneMessages) {\n const {\n context,\n indexTokenCountMap,\n messagesToRefine,\n prePruneContextTokens,\n remainingContextTokens,\n newOriginalToolContent,\n calibrationRatio,\n resolvedInstructionOverhead,\n contextBudget,\n effectiveInstructionTokens,\n } = agentContext.pruneMessages({\n messages,\n usageMetadata: agentContext.currentUsage,\n lastCallUsage: agentContext.lastCallUsage,\n totalTokensFresh: agentContext.totalTokensFresh,\n });\n prunedOriginalToolContent = newOriginalToolContent;\n /**\n * Masking rewrites tool content in `state.messages` in place, so this\n * map is the only surviving copy of the full output. Persist it on\n * every prune, not just when a summary is about to be written — the\n * pruner closure that produced it is discarded on the next reset, and\n * with it any chance of a later summary restoring the real content.\n * AgentContext bounds what accumulates.\n */\n agentContext.preserveOriginalToolContent(newOriginalToolContent);\n agentContext.indexTokenCountMap = indexTokenCountMap;\n if (calibrationRatio != null && calibrationRatio > 0) {\n agentContext.calibrationRatio = calibrationRatio;\n }\n if (resolvedInstructionOverhead != null) {\n agentContext.resolvedInstructionOverhead =\n resolvedInstructionOverhead;\n const nonToolOverhead =\n agentContext.instructionTokens - agentContext.toolSchemaTokens;\n const calibratedToolTokens = Math.max(\n 0,\n resolvedInstructionOverhead - nonToolOverhead\n );\n const currentToolTokens = agentContext.toolSchemaTokens;\n const variance =\n currentToolTokens > 0\n ? Math.abs(calibratedToolTokens - currentToolTokens) /\n currentToolTokens\n : 1;\n if (variance > CALIBRATION_VARIANCE_THRESHOLD) {\n agentContext.toolSchemaTokens = calibratedToolTokens;\n /** Largest-remainder apportionment keeps the per-tool breakdown\n * summing exactly to the calibrated aggregate */\n if (agentContext.toolTokenCounts != null && currentToolTokens > 0) {\n agentContext.toolTokenCounts = apportionTokenCounts(\n agentContext.toolTokenCounts,\n calibratedToolTokens / currentToolTokens,\n calibratedToolTokens\n );\n }\n }\n }\n messagesToUse = context;\n\n /** Dispatched right before the model invoke — a summarization\n * detour returns from this node without an LLM call, and the\n * post-summary retry produces its own snapshot.\n *\n * The breakdown describes the post-prune prompt: counts from the\n * kept context, message tokens derived from the same calibrated\n * budget math as `remainingContextTokens` (the index map is keyed\n * by pre-prune state indices, so summing it over `context` would\n * missum); `prePruneContextTokens` carries the pre-prune metric. */\n const usageBreakdown = agentContext.getTokenBudgetBreakdown(messages);\n usageBreakdown.messageCount = context.length;\n contextUsage = {\n runId: this.runId,\n agentId,\n breakdown: usageBreakdown,\n contextBudget,\n effectiveInstructionTokens,\n prePruneContextTokens,\n remainingContextTokens,\n calibrationRatio: agentContext.calibrationRatio,\n };\n syncBudgetDerivedFields(contextUsage);\n\n const hasPrunedMessages =\n agentContext.summarizationEnabled === true &&\n Array.isArray(messagesToRefine) &&\n messagesToRefine.length > 0;\n\n if (hasPrunedMessages) {\n const shouldSkip = agentContext.shouldSkipSummarization(\n messages.length\n );\n const triggerResult =\n !shouldSkip &&\n shouldTriggerSummarization({\n trigger: agentContext.summarizationConfig?.trigger,\n maxContextTokens: agentContext.maxContextTokens,\n prePruneContextTokens:\n prePruneContextTokens != null\n ? prePruneContextTokens + agentContext.instructionTokens\n : undefined,\n remainingContextTokens,\n messagesToRefineCount: messagesToRefine.length,\n });\n\n if (triggerResult) {\n emitAgentLog(\n config,\n 'info',\n 'graph',\n 'Summarization triggered',\n undefined,\n { runId: this.runId, agentId }\n );\n emitAgentLog(\n config,\n 'debug',\n 'graph',\n 'Summarization trigger details',\n {\n totalMessages: messages.length,\n remainingContextTokens: remainingContextTokens ?? 0,\n summaryVersion: agentContext.summaryVersion + 1,\n toolSchemaTokens: agentContext.toolSchemaTokens,\n instructionTokens: agentContext.instructionTokens,\n systemMessageTokens: agentContext.systemMessageTokens,\n },\n { runId: this.runId, agentId }\n );\n agentContext.markSummarizationTriggered(messages.length);\n return {\n summarizationRequest: {\n remainingContextTokens: remainingContextTokens ?? 0,\n agentId: agentId || agentContext.agentId,\n },\n };\n }\n\n if (shouldSkip) {\n emitAgentLog(\n config,\n 'debug',\n 'graph',\n 'Summarization skipped — no new messages or per-run cap reached',\n {\n messageCount: messages.length,\n messagesToRefineCount: messagesToRefine.length,\n contextLength: context.length,\n },\n { runId: this.runId, agentId }\n );\n }\n }\n }\n\n let finalMessages = messagesToUse;\n /**\n * Keep the pruner's provider-grounded aggregate as the authoritative\n * baseline, then attribute it across retained messages. Provider\n * transforms can shrink one message while expanding or adding another;\n * per-origin accounting prevents that unrelated shrink from canceling\n * the expansion. Raw counts are frozen before in-place formatters run.\n */\n let providerMessageBaseline:\n | Array<{ rawTokens: number; accountingWeight: number }>\n | undefined;\n const providerMessageOrigins = new WeakMap<BaseMessage, number>();\n if (contextUsage != null && agentContext.tokenCounter != null) {\n const sourceIndices = new WeakMap<BaseMessage, number>();\n for (let i = 0; i < messages.length; i++) {\n sourceIndices.set(messages[i], i);\n }\n providerMessageBaseline = messagesToUse.map((message, index) => {\n const rawTokens = agentContext.tokenCounter!(message);\n const sourceIndex = sourceIndices.get(message);\n const indexedTokens =\n sourceIndex != null\n ? agentContext.indexTokenCountMap[sourceIndex]\n : undefined;\n const accountingWeight =\n indexedTokens != null &&\n Number.isFinite(indexedTokens) &&\n indexedTokens >= 0\n ? indexedTokens\n : rawTokens;\n if (!providerMessageOrigins.has(message)) {\n providerMessageOrigins.set(message, index);\n }\n return { rawTokens, accountingWeight };\n });\n }\n\n const getProviderMessageOriginKey = (\n message: BaseMessage\n ): string | undefined => {\n const type = message.getType();\n if (\n message instanceof ToolMessage &&\n typeof message.tool_call_id === 'string' &&\n message.tool_call_id.length > 0\n ) {\n return `tool:call:${message.tool_call_id}`;\n }\n if (typeof message.id === 'string' && message.id.length > 0) {\n return `${type}:id:${message.id}`;\n }\n return undefined;\n };\n\n /**\n * Provider projections clone messages. Preserve their baseline origin\n * without writing tracking metadata onto the wire. Synthetic fold\n * messages intentionally remain unattributed and are charged in full.\n */\n const trackProviderMessageOrigins = (\n before: BaseMessage[],\n after: BaseMessage[]\n ): BaseMessage[] => {\n if (providerMessageBaseline == null || before === after) {\n return after;\n }\n if (before.length === after.length) {\n for (let i = 0; i < after.length; i++) {\n const origin = providerMessageOrigins.get(before[i]);\n if (\n origin != null &&\n !providerMessageOrigins.has(after[i]) &&\n before[i].getType() === after[i].getType() &&\n !isSyntheticProviderContextMessage(after[i])\n ) {\n providerMessageOrigins.set(after[i], origin);\n }\n }\n return after;\n }\n\n const keyedOrigins = new Map<string, number | null>();\n for (const message of before) {\n const origin = providerMessageOrigins.get(message);\n const key = getProviderMessageOriginKey(message);\n if (origin == null || key == null) {\n continue;\n }\n keyedOrigins.set(key, keyedOrigins.has(key) ? null : origin);\n }\n for (const message of after) {\n if (\n providerMessageOrigins.has(message) ||\n isSyntheticProviderContextMessage(message)\n ) {\n continue;\n }\n const key = getProviderMessageOriginKey(message);\n const origin = key != null ? keyedOrigins.get(key) : undefined;\n if (origin != null) {\n providerMessageOrigins.set(message, origin);\n }\n }\n return after;\n };\n\n if (agentContext.useLegacyContent) {\n const before = finalMessages;\n finalMessages = trackProviderMessageOrigins(\n before,\n formatContentStrings(before)\n );\n }\n\n const maxProviderToolResultChars =\n agentContext.maxToolResultChars ??\n calculateMaxToolResultChars(agentContext.maxContextTokens);\n const beforeToolStreamProjection = finalMessages;\n finalMessages = trackProviderMessageOrigins(\n beforeToolStreamProjection,\n projectToolStreamContentForProvider(beforeToolStreamProjection)\n );\n const beforeToolInputProjection = finalMessages;\n finalMessages = trackProviderMessageOrigins(\n beforeToolInputProjection,\n projectToolCallInputs(\n beforeToolInputProjection,\n calculateMaxToolCallInputChars(agentContext.maxContextTokens)\n )\n );\n\n const lastMessageX =\n finalMessages.length >= 2\n ? finalMessages[finalMessages.length - 2]\n : null;\n const lastMessageY =\n finalMessages.length >= 1\n ? finalMessages[finalMessages.length - 1]\n : null;\n\n const anthropicLike = isAnthropicLike(\n agentContext.provider,\n agentContext.clientOptions as { model?: string }\n );\n\n if (\n agentContext.provider === Providers.BEDROCK &&\n lastMessageX instanceof AIMessageChunk &&\n lastMessageY instanceof ToolMessage &&\n typeof lastMessageX.content === 'string'\n ) {\n const trimmed = lastMessageX.content.trim();\n finalMessages[finalMessages.length - 2].content =\n trimmed.length > 0 ? [{ type: 'text' as const, text: trimmed }] : '';\n }\n\n const localProviderOverflowMeasurements = new WeakMap<\n object,\n {\n contextBudget: number;\n estimatedPromptTokens: number;\n }\n >();\n const measureProviderPayload = (\n candidate: BaseMessage[],\n contextBudgetOverride?: number,\n forceRawRecount = false\n ): {\n fits: boolean;\n projectedMessageTokens?: number;\n availableMessageTokens?: number;\n contextBudget?: number;\n effectiveInstructionTokens?: number;\n } => {\n const contextBudget =\n contextBudgetOverride ?? contextUsage?.contextBudget;\n const effectiveInstructionTokens =\n contextUsage?.effectiveInstructionTokens ??\n (forceRawRecount ? agentContext.instructionTokens : undefined);\n if (\n agentContext.tokenCounter == null ||\n contextBudget == null ||\n effectiveInstructionTokens == null\n ) {\n return { fits: true };\n }\n const availableMessageTokens = Math.max(\n 0,\n contextBudget - effectiveInstructionTokens\n );\n let usageRatio =\n agentContext.calibrationRatio > 0 ? agentContext.calibrationRatio : 1;\n if (\n contextUsage?.calibrationRatio != null &&\n contextUsage.calibrationRatio > 0\n ) {\n usageRatio = contextUsage.calibrationRatio;\n }\n if (forceRawRecount) {\n usageRatio = Math.max(1, usageRatio);\n }\n const baselineRemaining = contextUsage?.remainingContextTokens;\n const accountedMessageTokens =\n !forceRawRecount &&\n providerMessageBaseline != null &&\n baselineRemaining != null &&\n Number.isFinite(baselineRemaining)\n ? availableMessageTokens -\n Math.min(availableMessageTokens, Math.max(0, baselineRemaining))\n : undefined;\n\n let projectedMessageTokens: number;\n if (accountedMessageTokens != null && providerMessageBaseline != null) {\n const replyPrimerTokens = Math.round(\n REPLY_PRIMER_TOKENS * usageRatio\n );\n const rawWeights: Record<string, number> = {};\n let totalWeight = 0;\n for (let i = 0; i < providerMessageBaseline.length; i++) {\n const weight = providerMessageBaseline[i].accountingWeight;\n rawWeights[i] = weight;\n totalWeight += weight;\n }\n const attributableTokens =\n totalWeight > 0\n ? Math.min(\n Math.max(0, accountedMessageTokens - replyPrimerTokens),\n Math.round(totalWeight * usageRatio)\n )\n : 0;\n const apportionedTokens =\n totalWeight > 0\n ? apportionTokenCounts(\n rawWeights,\n attributableTokens / totalWeight,\n attributableTokens\n )\n : {};\n const attributedByOrigin = providerMessageBaseline.map(\n (_, origin) => apportionedTokens[origin] || 0\n );\n projectedMessageTokens = Math.max(\n replyPrimerTokens,\n accountedMessageTokens - attributableTokens\n );\n let newRawTokens = 0;\n const usedOrigins = new Set<number>();\n for (const message of candidate) {\n const rawTokens = agentContext.tokenCounter(message);\n const origin = providerMessageOrigins.get(message);\n if (origin == null || usedOrigins.has(origin)) {\n newRawTokens += rawTokens;\n continue;\n }\n usedOrigins.add(origin);\n projectedMessageTokens += Math.max(\n 0,\n attributedByOrigin[origin] +\n Math.round(\n (rawTokens - providerMessageBaseline[origin].rawTokens) *\n usageRatio\n )\n );\n }\n projectedMessageTokens += Math.round(newRawTokens * usageRatio);\n } else {\n let rawTokens = REPLY_PRIMER_TOKENS;\n for (const message of candidate) {\n rawTokens += agentContext.tokenCounter(message);\n }\n projectedMessageTokens = Math.round(rawTokens * usageRatio);\n }\n return {\n fits: projectedMessageTokens <= availableMessageTokens,\n projectedMessageTokens,\n availableMessageTokens,\n contextBudget,\n effectiveInstructionTokens,\n };\n };\n\n const createProviderPayloadOverflowError = ({\n projection,\n provider,\n info,\n }: {\n projection: ReturnType<typeof measureProviderPayload>;\n provider?: Providers;\n info: string;\n }): ContextOverflowError => {\n const error = new ContextOverflowError(\n JSON.stringify({\n type: 'final_context_overflow',\n info,\n provider,\n projectedMessageTokens: projection.projectedMessageTokens,\n availableMessageTokens: projection.availableMessageTokens,\n })\n );\n if (\n projection.projectedMessageTokens != null &&\n projection.contextBudget != null &&\n projection.effectiveInstructionTokens != null\n ) {\n localProviderOverflowMeasurements.set(error, {\n contextBudget: projection.contextBudget,\n estimatedPromptTokens:\n projection.projectedMessageTokens +\n projection.effectiveInstructionTokens,\n });\n }\n return error;\n };\n\n const applyProviderMessageTransforms = (\n candidate: BaseMessage[]\n ): BaseMessage[] => {\n let transformed = candidate;\n if (\n isThinkingEnabled(agentContext.provider, agentContext.clientOptions)\n ) {\n /**\n * Current-run AI messages may validly omit a thinking block. The\n * boundary prevents them from being mistaken for foreign history.\n */\n const before = transformed;\n transformed = trackProviderMessageOrigins(\n before,\n ensureThinkingBlockInMessages(\n before,\n agentContext.provider,\n config,\n this.startIndex\n )\n );\n }\n\n /**\n * Tool-less destinations cannot send inherited tool blocks without a\n * tool schema, so fold those interactions into provider-valid content.\n */\n if (toolsForBinding == null || toolsForBinding.length === 0) {\n const before = transformed;\n transformed = trackProviderMessageOrigins(\n before,\n foldToolBlocksForToollessAgent(before, config)\n );\n if (agentContext.useLegacyContent) {\n const beforeLegacyFormat = transformed;\n transformed = trackProviderMessageOrigins(\n beforeLegacyFormat,\n formatContentStrings(beforeLegacyFormat)\n );\n }\n }\n /**\n * Applied HERE for the primary so the cue is part of the MEASURED\n * payload — the pre-invoke projection and overflow guard run on this\n * stage's output, and a post-measure append could push a just-fits\n * prompt over budget unreported (#346 round 2). The attemptInvoke\n * funnel re-keys per SERVING provider: it strips this cue for a\n * tolerant fallback and adds it for a Claude fallback behind a\n * tolerant primary.\n */\n if (\n isAnthropicLike(\n agentContext.provider,\n agentContext.clientOptions as { model?: string }\n )\n ) {\n const before = transformed;\n transformed = trackProviderMessageOrigins(\n before,\n appendPredecessorHandoffCue(before, (message) =>\n this.isRunProducedMessage(message)\n )\n );\n }\n return transformed;\n };\n\n const toolOutputRegistry = this.getOrCreateToolOutputRegistry();\n const providerRunId = config.configurable?.run_id as string | undefined;\n const projectProviderReferences = (\n candidate: BaseMessage[]\n ): BaseMessage[] =>\n trackProviderMessageOrigins(\n candidate,\n annotateMessagesForLLM(candidate, toolOutputRegistry, providerRunId)\n );\n\n const compactSyntheticProviderContext = (\n candidate: BaseMessage[]\n ): BaseMessage[] => {\n const synthetic: Array<{\n index: number;\n message: HumanMessage;\n chars: number;\n }> = [];\n for (let i = 0; i < candidate.length; i++) {\n const message = candidate[i];\n if (\n !(message instanceof HumanMessage) ||\n !isSyntheticProviderContextMessage(message)\n ) {\n continue;\n }\n const content = message.content;\n synthetic.push({\n index: i,\n message,\n chars: getToolContentCharLength(content),\n });\n }\n if (synthetic.length === 0) {\n return candidate;\n }\n\n const buildCandidate = (scale: number): BaseMessage[] => {\n const compacted = [...candidate];\n for (const { index, message, chars } of synthetic) {\n const content = compactToolContent(\n message.content,\n Math.floor(chars * scale)\n ).content;\n compacted[index] = new HumanMessage({\n content,\n id: message.id,\n name: message.name,\n additional_kwargs: message.additional_kwargs,\n response_metadata: message.response_metadata,\n });\n }\n return compacted;\n };\n\n let best = buildCandidate(0);\n if (!measureProviderPayload(best).fits) {\n return candidate;\n }\n let low = 0;\n let high = 1;\n for (let i = 0; i < 12; i++) {\n const scale = (low + high) / 2;\n const attempt = buildCandidate(scale);\n if (measureProviderPayload(attempt).fits) {\n best = attempt;\n low = scale;\n } else {\n high = scale;\n }\n }\n return best;\n };\n\n let artifactBaseMessages: BaseMessage[] | undefined;\n if (lastMessageY instanceof ToolMessage) {\n let artifactCandidate = finalMessages;\n if (anthropicLike) {\n artifactCandidate = trackProviderMessageOrigins(\n finalMessages,\n projectAnthropicArtifactContent(\n finalMessages,\n maxProviderToolResultChars\n )\n );\n } else if (\n (isOpenAILike(agentContext.provider) &&\n agentContext.provider !== Providers.DEEPSEEK) ||\n isGoogleLike(agentContext.provider)\n ) {\n artifactCandidate = trackProviderMessageOrigins(\n finalMessages,\n projectArtifactPayload(finalMessages, maxProviderToolResultChars)\n );\n }\n\n if (artifactCandidate !== finalMessages) {\n const projection = measureProviderPayload(artifactCandidate);\n if (projection.fits) {\n artifactBaseMessages = finalMessages;\n finalMessages = artifactCandidate;\n } else {\n emitAgentLog(\n config,\n 'warn',\n 'graph',\n 'Artifact payload omitted because it exceeds the remaining context budget',\n {\n projectedMessageTokens: projection.projectedMessageTokens,\n availableMessageTokens: projection.availableMessageTokens,\n },\n { runId: this.runId, agentId }\n );\n }\n }\n }\n\n finalMessages = projectProviderReferences(\n applyProviderMessageTransforms(finalMessages)\n );\n let finalProjection = measureProviderPayload(finalMessages);\n if (artifactBaseMessages != null) {\n if (!finalProjection.fits) {\n finalMessages = projectProviderReferences(\n applyProviderMessageTransforms(artifactBaseMessages)\n );\n finalProjection = measureProviderPayload(finalMessages);\n emitAgentLog(\n config,\n 'warn',\n 'graph',\n 'Artifact payload omitted after final provider formatting exceeded the remaining context budget',\n {\n projectedMessageTokens: finalProjection.projectedMessageTokens,\n availableMessageTokens: finalProjection.availableMessageTokens,\n },\n { runId: this.runId, agentId }\n );\n }\n }\n if (!finalProjection.fits) {\n const compacted = compactSyntheticProviderContext(finalMessages);\n if (compacted !== finalMessages) {\n finalMessages = compacted;\n finalProjection = measureProviderPayload(finalMessages);\n emitAgentLog(\n config,\n finalProjection.fits ? 'warn' : 'error',\n 'graph',\n finalProjection.fits\n ? 'Synthetic provider context compacted to fit the final payload budget'\n : 'Final provider payload still exceeds budget after synthetic context compaction',\n {\n projectedMessageTokens: finalProjection.projectedMessageTokens,\n availableMessageTokens: finalProjection.availableMessageTokens,\n },\n { runId: this.runId, agentId }\n );\n }\n }\n\n /**\n * Mistral rejects consecutive user turns outright; Bedrock's Converse\n * API documents strict user/assistant alternation across its model\n * families, with enforcement varying by family (Claude on Converse\n * currently tolerates the shape — verified live — but the payload is\n * normalized for all of them rather than betting on leniency). Four\n * sites can emit them — the `PostToolBatch` and `PreemptBoundary` hook\n * boundaries (a consolidated context message followed by one\n * `HumanMessage` per injected entry), a queue drain carrying more than\n * one steer, and `run.ts`'s pre-stream context push onto a payload that\n * already ends on a user turn.\n *\n * Normalized here, at the last provider-facing hop, rather than at any\n * one boundary: the boundaries must keep per-message identity, because\n * `additional_kwargs.source`/`skillName` drive steer rendering and the\n * trailing-steer anchor downstream. Graph state and the host's\n * persisted messages are untouched — this shapes only what goes on the\n * wire, for the providers that actually care.\n *\n * Runs AFTER synthetic-context compaction: that pass can rewrite or\n * drop messages, so coalescing has to see its output, and it is the\n * last shaping step before the cache breakpoint is chosen.\n */\n if (strictAlternationProviders.has(agentContext.provider)) {\n /**\n * Wrapped like every other provider transform: the merged message is\n * a NEW object, and without re-attachment the final pre-invoke\n * measurement would drop both source turns' calibrated shares and\n * recharge the merge at full raw estimate — enough to flip a\n * just-fits payload (the synthetic-context compaction above binary\n * searches to exactly that) into a spurious pre-invoke overflow. The\n * merge keeps the first source's id, so the keyed branch re-attaches\n * that origin; the absorbed turn's tokens are charged as new raw\n * growth, which only ever under-estimates by less than the old\n * behavior over-estimated.\n */\n const beforeCoalesce = finalMessages;\n finalMessages = trackProviderMessageOrigins(\n beforeCoalesce,\n coalesceAdjacentUserTurns(beforeCoalesce)\n );\n }\n\n // Determine the prompt-cache strategy up front. Two distinct facts:\n //\n // `providerPromptCacheEnabled` — prompt caching is on for this provider\n // at all. This drives orphan cleanup, because EVERY cached send must be\n // sanitized — including the system-runnable path, where AgentContext (not\n // this node) adds the body marker.\n //\n // `willAddTailCache` — THIS node will add the marker itself. Anthropic /\n // OpenRouter defer to the system runnable when one owns the system-prompt\n // breakpoint, so they exclude that case; Bedrock always marks here.\n const anthropicPromptCacheEnabled =\n agentContext.provider === Providers.ANTHROPIC &&\n (agentContext.clientOptions as t.AnthropicClientOptions | undefined)\n ?.promptCache === true;\n const openRouterPromptCacheEnabled =\n agentContext.provider === Providers.OPENROUTER &&\n (\n agentContext.clientOptions as\n | t.ProviderOptionsMap[Providers.OPENROUTER]\n | undefined\n )?.promptCache === true;\n // Message/system cache points work on all cache-capable Bedrock models,\n // including Nova (verified live: HTTP 200 with cacheWriteInputTokens). Only\n // the tool checkpoint is Claude-only, so this is gated on promptCache alone.\n const bedrockPromptCacheEnabled =\n agentContext.provider === Providers.BEDROCK &&\n (\n agentContext.clientOptions as\n | t.BedrockAnthropicClientOptions\n | undefined\n )?.promptCache === true;\n const providerPromptCacheEnabled =\n anthropicPromptCacheEnabled ||\n openRouterPromptCacheEnabled ||\n bedrockPromptCacheEnabled;\n\n // Intentionally broad: runs when the pruner wasn't used, when any\n // post-pruning transform (ensureThinkingBlock, etc.) reassigned\n // finalMessages, OR when this is a prompt-cached send. The last clause\n // matters because the marker is now applied AFTER this gate (and, for the\n // system-runnable path, in AgentContext entirely): without it, a cached\n // send whose pruner returned the context unchanged would skip cleanup and\n // could ship orphaned AI/tool pairs from persisted history.\n // sanitizeOrphanToolBlocks fast-paths to a Set diff check when no orphans\n // exist, so the cost is negligible.\n const needsOrphanSanitize =\n anthropicLike &&\n (!agentContext.pruneMessages ||\n finalMessages !== messagesToUse ||\n providerPromptCacheEnabled);\n if (needsOrphanSanitize) {\n const beforeSanitize = finalMessages.length;\n const beforeSanitizeMessages = finalMessages;\n finalMessages = trackProviderMessageOrigins(\n beforeSanitizeMessages,\n sanitizeOrphanToolBlocks(beforeSanitizeMessages, (source, clone) => {\n const origin = providerMessageOrigins.get(source);\n if (origin != null) {\n providerMessageOrigins.set(clone, origin);\n }\n })\n );\n if (finalMessages.length !== beforeSanitize) {\n emitAgentLog(\n config,\n 'warn',\n 'sanitize',\n 'Orphan tool blocks removed',\n {\n before: beforeSanitize,\n after: finalMessages.length,\n dropped: beforeSanitize - finalMessages.length,\n },\n { runId: this.runId, agentId }\n );\n }\n }\n\n // Place the single tail prompt-cache breakpoint LAST, after thinking\n // normalization and orphan sanitization. ensureThinkingBlockInMessages can\n // fold a trailing non-thinking AI→Tool chain into a `[Previous agent\n // context]` HumanMessage whose builder copies text but not cache_control /\n // cachePoint, and sanitizeOrphanToolBlocks can drop the anchored block — so\n // marking earlier would let the only breakpoint vanish before the model\n // call (zero message caching). Anchoring on the final message list keeps\n // the marker on a block that actually ships. The system-runnable path\n // adds its body marker in AgentContext, so this node skips it there.\n if (\n (anthropicPromptCacheEnabled || openRouterPromptCacheEnabled) &&\n !agentContext.systemRunnable\n ) {\n const beforeCacheControl = finalMessages;\n finalMessages = trackProviderMessageOrigins(\n beforeCacheControl,\n addTailCacheControl<BaseMessage>(\n beforeCacheControl,\n resolvePromptCacheTtl(\n anthropicPromptCacheEnabled\n ? (\n agentContext.clientOptions as\n | t.AnthropicClientOptions\n | undefined\n )?.promptCacheTtl\n : (\n agentContext.clientOptions as\n | t.ProviderOptionsMap[Providers.OPENROUTER]\n | undefined\n )?.promptCacheTtl\n )\n )\n );\n } else if (bedrockPromptCacheEnabled) {\n const bedrockOptions = agentContext.clientOptions as\n | t.BedrockAnthropicClientOptions\n | undefined;\n // Non-Claude models (Nova) reject the extended 1h TTL, so resolve it\n // against the model — message/system caching stays on, clamped to 5m.\n const beforeCacheControl = finalMessages;\n finalMessages = trackProviderMessageOrigins(\n beforeCacheControl,\n addBedrockTailCacheControl<BaseMessage>(\n beforeCacheControl,\n resolveBedrockPromptCacheTtl(\n bedrockOptions?.promptCacheTtl,\n (bedrockOptions as { model?: string } | undefined)?.model\n )\n )\n );\n }\n\n const fallbackBaseMessages = finalMessages;\n const beforeFinalProviderProjection = fallbackBaseMessages;\n finalMessages = trackProviderMessageOrigins(\n beforeFinalProviderProjection,\n projectMessagesForProvider({\n model: (this.overrideModel ?? model) as t.ChatModel,\n messages: beforeFinalProviderProjection,\n provider: agentContext.provider,\n maxToolResultChars: maxProviderToolResultChars,\n callOptions: config,\n })\n );\n\n /**\n * Prompt-cache placement and orphan sanitization are provider-wire\n * transforms too. Re-measure after both so no content added after the\n * earlier artifact/synthetic compaction decision can bypass the guard.\n */\n finalProjection = measureProviderPayload(finalMessages);\n const preInvokeContextOverflowError = !finalProjection.fits\n ? createProviderPayloadOverflowError({\n projection: finalProjection,\n provider: agentContext.provider,\n info: 'Provider message formatting exceeded the context budget and no safe synthetic-context compaction could make it fit.',\n })\n : undefined;\n\n if (\n agentContext.lastStreamCall != null &&\n agentContext.streamBuffer != null\n ) {\n const timeSinceLastCall = Date.now() - agentContext.lastStreamCall;\n if (timeSinceLastCall < agentContext.streamBuffer) {\n const timeToWait =\n Math.ceil((agentContext.streamBuffer - timeSinceLastCall) / 1000) *\n 1000;\n await sleep(timeToWait);\n }\n }\n\n agentContext.lastStreamCall = Date.now();\n agentContext.markTokensStale();\n\n let result: Partial<t.BaseGraphState> | undefined;\n const fallbacks =\n (agentContext.clientOptions as t.LLMConfig | undefined)?.fallbacks ??\n [];\n\n if (\n finalMessages.length === 0 &&\n !agentContext.hasPendingCompactionSummary()\n ) {\n const budgetBreakdown = agentContext.getTokenBudgetBreakdown(messages);\n const breakdown = agentContext.formatTokenBudgetBreakdown(messages);\n const instructionsExceedBudget =\n budgetBreakdown.instructionTokens > budgetBreakdown.maxContextTokens;\n\n let guidance: string;\n if (instructionsExceedBudget) {\n const toolPct =\n budgetBreakdown.toolSchemaTokens > 0\n ? Math.round(\n (budgetBreakdown.toolSchemaTokens /\n budgetBreakdown.instructionTokens) *\n 100\n )\n : 0;\n guidance =\n toolPct > 50\n ? `Tool definitions consume ${budgetBreakdown.toolSchemaTokens} tokens (${toolPct}% of instructions) across ${budgetBreakdown.toolCount} tools, exceeding maxContextTokens (${budgetBreakdown.maxContextTokens}). Reduce the number of tools or increase maxContextTokens.`\n : `Instructions (${budgetBreakdown.instructionTokens} tokens) exceed maxContextTokens (${budgetBreakdown.maxContextTokens}). Increase maxContextTokens or shorten the system prompt.`;\n if (agentContext.summarizationEnabled === true) {\n guidance +=\n ' Summarization was skipped because the summary would further increase the instruction overhead.';\n }\n } else {\n guidance =\n 'Please increase the context window size or make your message shorter.';\n }\n\n emitAgentLog(\n config,\n 'error',\n 'graph',\n 'Empty messages after pruning',\n {\n messageCount: messages.length,\n instructionsExceedBudget,\n breakdown,\n },\n { runId: this.runId, agentId }\n );\n throw new Error(\n JSON.stringify({\n type: 'empty_messages',\n info: `Message pruning removed all messages as none fit in the context window. ${guidance}\\n${breakdown}`,\n })\n );\n }\n\n /** Past the empty-prompt guard — a model call is now guaranteed */\n if (contextUsage != null) {\n if (\n finalProjection.projectedMessageTokens != null &&\n finalProjection.availableMessageTokens != null\n ) {\n contextUsage.breakdown.messageCount = finalMessages.length;\n contextUsage.remainingContextTokens = Math.max(\n 0,\n finalProjection.availableMessageTokens -\n finalProjection.projectedMessageTokens\n );\n }\n syncBudgetDerivedFields(contextUsage);\n /** Awaited so async host handlers receive the pre-invoke snapshot\n * before any model deltas are emitted */\n await safeDispatchCustomEvent(\n GraphEvents.ON_CONTEXT_USAGE,\n contextUsage,\n config\n );\n }\n\n const invokeStart = Date.now();\n const invokeMeta = { runId: this.runId, agentId };\n emitAgentLog(\n config,\n 'debug',\n 'graph',\n 'Invoking LLM',\n {\n messageCount: finalMessages.length,\n provider: agentContext.provider,\n },\n invokeMeta,\n { force: true }\n );\n\n const langfuse = resolveLangfuseConfig(\n this.langfuse,\n agentContext.langfuse\n );\n const traceMetadata = createLangfuseTraceMetadata({\n messageId: this.runId,\n parentMessageId: config.configurable?.requestBody?.parentMessageId,\n agentId,\n agentName: agentContext.name,\n });\n let langfuseHandler: CallbackEntry | undefined;\n let invokeConfig = {\n ...config,\n /** The run-scoped breaker composed in, so a stream-limit trip in one\n * parallel agent node also cancels sibling nodes' in-flight model\n * calls, not only their subagents. */\n signal: composeAbortSignals(config.signal, attemptBreaker.signal),\n metadata: {\n ...(config.metadata ?? {}),\n ...traceMetadata,\n /** Canonical agent identity, stamped OUTSIDE trace-metadata\n * filtering: `createLangfuseTraceMetadata` drops values over its\n * length cap, but scope trust (`isForeignScope`) needs the id\n * verbatim regardless of length. */\n agentId,\n [STREAM_LIMIT_EPOCH_KEY]: attemptBreakerEpoch,\n },\n };\n initializeLangfuseTracing(langfuse);\n if (findCallback(config.callbacks, isLangfuseCallbackHandler) == null) {\n langfuseHandler = createLangfuseHandler({\n langfuse,\n userId: config.configurable?.user_id as string | undefined,\n sessionId: config.configurable?.thread_id as string | undefined,\n traceMetadata,\n tags: ['librechat', 'agent'],\n traceIdSeed:\n langfuse?.deterministicTraceId === true ? this.runId : undefined,\n runId: this.langfuseScopeRunId,\n toolOutputTracing: hasToolOutputTracingConfig(\n this.langfuse,\n agentContext.langfuse\n )\n ? resolveToolOutputTracingConfig(\n this.langfuse,\n agentContext.langfuse\n )\n : undefined,\n });\n if (langfuseHandler != null) {\n invokeConfig = {\n ...invokeConfig,\n callbacks: appendCallbacks(invokeConfig.callbacks, [\n langfuseHandler,\n ]),\n };\n }\n }\n const metadata = config.metadata as Record<string, unknown>;\n\n try {\n if (preInvokeContextOverflowError != null) {\n throw preInvokeContextOverflowError;\n }\n /** Rechecked after the pre-invoke awaits (context-usage dispatch,\n * hooks): a sibling can trip the breaker while this node is paused\n * in one of them, and a provider that doesn't synchronously reject\n * an aborted signal would still start the request. */\n {\n const preInvokeTrip = this.resolveTrippedBreakerReason(\n attemptBreaker.signal\n );\n if (preInvokeTrip != null) {\n throw preInvokeTrip;\n }\n }\n result = await withLangfuseRuntimeScope(\n resolveLangfuseRuntimeScope({\n runLangfuse: this.langfuse,\n langfuseOverlay: agentContext.langfuse,\n runId: this.langfuseScopeRunId,\n agentId,\n }),\n () =>\n attemptInvoke(\n {\n model: (this.overrideModel ?? model) as t.ChatModel,\n messages: finalMessages,\n provider: agentContext.provider,\n context: this,\n },\n invokeConfig\n )\n );\n } catch (primaryError) {\n clearCurrentDeltaStepMarkers({\n graph: this,\n metadata,\n });\n /**\n * A tripped stream circuit breaker is a deliberate abort, not a\n * provider failure: entering overflow recovery or the fallback chain\n * would spend more provider work after the safety limit fired, and a\n * succeeding fallback would resolve a run the public contract says\n * must reject. Rethrow before any recovery path.\n */\n if (primaryError instanceof StreamLimitExceededError) {\n /** Tripped before rethrowing so parallel agent nodes' in-flight\n * model calls and subagents stop while the rejection propagates. */\n attemptBreaker.abort(primaryError);\n throw primaryError;\n }\n /** A sibling that tripped the shared breaker aborts this branch's\n * composed signal, and some providers surface that as a generic\n * abort error; entering overflow planning or the fallback chain\n * would start new provider work after the run-wide breaker fired.\n * Rethrow the breaker's own stream-limit reason instead. */\n {\n const trippedReason = this.resolveTrippedBreakerReason(\n attemptBreaker.signal\n );\n if (trippedReason != null) {\n throw trippedReason;\n }\n }\n /**\n * A context overflow is a deterministic consequence of the payload,\n * not a provider being unavailable — so it is answered by compacting\n * and retrying rather than by re-sending the same oversized prompt\n * down the fallback chain. Fallbacks still run for every other\n * failure, and for an overflow whose recovery budget is spent.\n */\n /**\n * Compaction has to have something to work with. Without a token\n * counter there is no pruner, and with summarization disabled the\n * summarize node deliberately no-ops — so in that combination the\n * retry would resend a byte-identical prompt. Skipping the detour\n * keeps the original error and one round trip instead of three.\n */\n const estimatedPromptTokens = getEstimatedPromptTokens(contextUsage);\n\n const canSummarizeOverflow =\n agentContext.summarizationEnabled === true &&\n splitAtRecencyBoundary(messages, {\n turns:\n agentContext.summarizationConfig?.retainRecent?.turns ??\n DEFAULT_RETAIN_RECENT_TURNS,\n tokens: agentContext.summarizationConfig?.retainRecent?.tokens,\n tokenCounter: agentContext.tokenCounter,\n }).head.length > 0;\n\n const getLocalProviderOverflowMeasurement = (\n error: unknown\n ):\n | {\n contextBudget: number;\n estimatedPromptTokens: number;\n }\n | undefined =>\n typeof error === 'object' && error !== null\n ? localProviderOverflowMeasurements.get(error)\n : undefined;\n\n const getRecoveryPromptEstimate = (\n error: unknown,\n fallbackContext?: FallbackErrorContext\n ): number | undefined => {\n const resolvedFallbackContext =\n fallbackContext ?? getFallbackErrorContext(error);\n return (\n getLocalProviderOverflowMeasurement(error)?.estimatedPromptTokens ??\n (resolvedFallbackContext == null\n ? estimatedPromptTokens\n : undefined)\n );\n };\n\n const planRecovery = (\n error: unknown,\n attributedFallbackContext?: FallbackErrorContext\n ): OverflowRecoveryPlan | null => {\n /**\n * When the rejection came from a fallback, plan against *that*\n * client: its window and output allowance are why it was configured\n * as an alternative in the first place.\n */\n const fallbackContext =\n attributedFallbackContext ?? getFallbackErrorContext(error);\n const localMeasurement = getLocalProviderOverflowMeasurement(error);\n const recoveryPromptEstimate = getRecoveryPromptEstimate(\n error,\n fallbackContext\n );\n /**\n * A previous correction that left the rejected prompt no smaller\n * proves this state has nothing left to compact. Use the fallback\n * projection when one exists so unlike provider formats are never\n * compared through the primary's cheaper pre-projection estimate.\n */\n if (agentContext.overflowRecoveryStalled(recoveryPromptEstimate)) {\n return null;\n }\n const recovery = planContextOverflowRecovery({\n error,\n provider: fallbackContext?.provider ?? agentContext.provider,\n maxContextTokens:\n localMeasurement?.contextBudget ??\n fallbackContext?.maxContextTokens ??\n agentContext.maxContextTokens,\n estimatedPromptTokens: recoveryPromptEstimate,\n calibrationRatio: agentContext.calibrationRatio,\n instructionTokens: agentContext.instructionTokens,\n canSummarize: agentContext.summarizationEnabled === true,\n configuredCompletionTokens: getConfiguredCompletionTokens(\n fallbackContext?.clientOptions ?? agentContext.clientOptions\n ),\n attemptsSoFar: agentContext.overflowRecoveryAttempts,\n });\n if (recovery == null) {\n return null;\n }\n const translatedRecovery =\n fallbackContext != null\n ? {\n ...recovery,\n budgetTokens: minDefined(\n getBlindRecoveryBudget(agentContext.maxContextTokens),\n localMeasurement != null\n ? recovery.budgetTokens\n : translateRecoveryBudget(\n recovery.budgetTokens,\n recovery.observedCalibrationRatio ??\n CALIBRATION_RATIO_MAX,\n agentContext.calibrationRatio\n )\n ),\n observedCalibrationRatio: undefined,\n }\n : recovery;\n const canReduceContext =\n canSummarizeOverflow ||\n (agentContext.tokenCounter != null &&\n translatedRecovery.budgetTokens != null);\n return canReduceContext ? translatedRecovery : null;\n };\n\n const recovery = planRecovery(primaryError);\n if (recovery != null) {\n const recoveryPromptEstimate =\n getRecoveryPromptEstimate(primaryError);\n return this.beginOverflowRecovery({\n recovery,\n agentContext,\n agentId,\n config,\n originalToolContent: prunedOriginalToolContent,\n estimatedPromptTokens: recoveryPromptEstimate,\n });\n }\n /**\n * A fallback can reject the same prompt as too large even when the\n * primary failed for an unrelated reason — a fallback with a smaller\n * window is the obvious case. Planning against the exhausted-chain\n * error keeps that path recoverable instead of surfacing it.\n */\n try {\n result = await withLangfuseRuntimeScope(\n resolveLangfuseRuntimeScope({\n runLangfuse: this.langfuse,\n langfuseOverlay: agentContext.langfuse,\n runId: this.langfuseScopeRunId,\n agentId,\n }),\n () =>\n tryFallbackProviders({\n fallbacks,\n tools: agentContext.tools,\n messages: fallbackBaseMessages,\n config: invokeConfig,\n primaryError,\n context: this,\n /**\n * Lets the chain recognise a fallback overflow whose signature\n * carries no reason of its own (Vertex AI's bare 400) and\n * surface it rather than a later unrelated failure.\n */\n overflowContext: {\n provider: agentContext.provider,\n estimatedPromptTokens: getEstimatedPromptTokens(contextUsage),\n maxContextTokens: agentContext.maxContextTokens,\n },\n prepareProviderMessages: ({\n model: fallbackModel,\n messages: fallbackMessages,\n provider: fallbackProvider,\n maxContextTokens: fallbackMaxContextTokens,\n config: fallbackConfig,\n }) => {\n const fallbackToolResultChars =\n agentContext.maxToolResultChars ??\n calculateMaxToolResultChars(\n fallbackMaxContextTokens ?? agentContext.maxContextTokens\n );\n /**\n * Serving-provider cue shaping BEFORE the fallback payload\n * is measured: a Claude fallback behind a tolerant primary\n * gains the cue inside the guarded projection (a prompt\n * within the cue's cost of the fallback budget must take\n * the recovery path, not ship oversized), and a tolerant\n * fallback behind an Anthropic primary sheds the baked cue\n * before it is measured against the tighter budget. The\n * attemptInvoke funnel pass then finds nothing to change.\n */\n const cueShapedFallbackMessages = trackProviderMessageOrigins(\n fallbackMessages,\n isAnthropicLike(fallbackProvider, {\n model: resolveServingModelId(fallbackModel),\n })\n ? appendPredecessorHandoffCue(fallbackMessages, (m) =>\n this.isRunProducedMessage(m)\n )\n : removePredecessorHandoffCue(fallbackMessages)\n );\n const projectedFallbackMessages = trackProviderMessageOrigins(\n cueShapedFallbackMessages,\n projectMessagesForProvider({\n model: fallbackModel,\n messages: cueShapedFallbackMessages,\n provider: fallbackProvider,\n maxToolResultChars: fallbackToolResultChars,\n callOptions: fallbackConfig,\n })\n );\n const primaryContextBudget = contextUsage?.contextBudget;\n const fallbackContextBudget =\n fallbackMaxContextTokens == null\n ? primaryContextBudget\n : Math.min(\n primaryContextBudget ?? fallbackMaxContextTokens,\n fallbackMaxContextTokens\n );\n const projection = measureProviderPayload(\n projectedFallbackMessages,\n fallbackContextBudget,\n true\n );\n if (!projection.fits) {\n throw createProviderPayloadOverflowError({\n projection,\n provider: fallbackProvider,\n info: 'Fallback provider message formatting exceeded the context budget before invocation.',\n });\n }\n return projectedFallbackMessages;\n },\n })\n );\n } catch (fallbackError) {\n if (fallbackError instanceof StreamLimitExceededError) {\n /** Same treatment as the primary path: a fallback stream that\n * trips the breaker must stop parallel agent nodes' model calls\n * and subagents before the rejection propagates. */\n attemptBreaker.abort(fallbackError);\n throw fallbackError;\n }\n {\n /** Same sibling-abort translation guard as the primary catch. */\n const trippedReason = this.resolveTrippedBreakerReason(\n attemptBreaker.signal\n );\n if (trippedReason != null) {\n throw trippedReason;\n }\n }\n const overflowCandidates =\n getFallbackOverflowCandidates(fallbackError);\n let fallbackRecovery: OverflowRecoveryPlan | null = null;\n let fallbackRecoveryPromptEstimate: number | undefined;\n for (const candidate of overflowCandidates) {\n fallbackRecovery = planRecovery(candidate.error, candidate.context);\n if (fallbackRecovery != null) {\n fallbackRecoveryPromptEstimate = getRecoveryPromptEstimate(\n candidate.error,\n candidate.context\n );\n break;\n }\n }\n if (overflowCandidates.length === 0) {\n fallbackRecovery = planRecovery(fallbackError);\n fallbackRecoveryPromptEstimate =\n getRecoveryPromptEstimate(fallbackError);\n }\n if (fallbackRecovery == null) {\n throw fallbackError;\n }\n return this.beginOverflowRecovery({\n recovery: fallbackRecovery,\n agentContext,\n agentId,\n config,\n originalToolContent: prunedOriginalToolContent,\n estimatedPromptTokens: fallbackRecoveryPromptEstimate,\n });\n }\n } finally {\n await disposeLangfuseHandler(langfuseHandler);\n }\n\n if (!result) {\n throw new Error('No result after model invocation');\n }\n\n /**\n * Fallback: populate toolCallStepIds in the graph execution context.\n *\n * When model.stream() is available (the common case), attemptInvoke\n * processes all chunks through a local ChatModelStreamHandler which\n * creates run steps and populates toolCallStepIds before returning.\n * The code below is a fallback for the rare case where model.stream\n * is unavailable and model.invoke() was used instead.\n *\n * Text content is dispatched FIRST so that MESSAGE_CREATION is the\n * current step when handleToolCalls runs. handleToolCalls then creates\n * TOOL_CALLS on top of it. The dedup in getMessageId and\n * toolCallStepIds.has makes this safe when attemptInvoke already\n * handled everything — both paths become no-ops.\n */\n const responseMessage = result.messages?.[0];\n /**\n * Provenance for the handoff-cue gate: recorded at the node, where the\n * produced turn is unambiguous. The public ChatModel contract does not\n * require implementations to set message ids — the reducer would\n * assign one AFTER this node returns, which is too late for the set —\n * so an id is assigned here first, the same way the reducer does it\n * (`v4()`, mirrored into `lc_kwargs`), and the reducer's\n * keep-existing-id rule makes the state message match.\n */\n if (responseMessage?.getType() === 'ai') {\n if (\n typeof responseMessage.id !== 'string' ||\n responseMessage.id === ''\n ) {\n responseMessage.id = v4();\n responseMessage.lc_kwargs.id = responseMessage.id;\n }\n this.runProducedAiMessageIds.add(responseMessage.id);\n }\n const toolCalls = (responseMessage as AIMessageChunk | undefined)\n ?.tool_calls;\n const hasToolCalls = Array.isArray(toolCalls) && toolCalls.length > 0;\n const responseReasoningContent = getResponseReasoningContent({\n responseMessage: responseMessage as Partial<AIMessageChunk> | undefined,\n reasoningKey: agentContext.reasoningKey,\n });\n const textMessageContent = getMessageDeltaContent(\n agentContext.provider,\n responseMessage?.content as MessageContent | undefined\n );\n const hasStreamedTextDeltaStep = hasCurrentTextDeltaStep({\n graph: this,\n metadata,\n });\n const hasStreamedReasoningDeltaStep = hasCurrentReasoningDeltaStep({\n graph: this,\n metadata,\n });\n const dispatchableFinalReasoningContent =\n getDispatchableFinalReasoningContent({\n agentContext,\n responseReasoningContent,\n hasStreamedTextDeltaStep,\n hasStreamedReasoningDeltaStep,\n });\n\n if (hasToolCalls) {\n const dispatchedReasoning =\n dispatchableFinalReasoningContent != null &&\n (await dispatchReasoningContent({\n graph: this,\n agentContext,\n reasoningContent: dispatchableFinalReasoningContent,\n metadata,\n }));\n if (dispatchedReasoning) {\n markPostReasoningContent(agentContext);\n }\n if (textMessageContent != null && !hasStreamedTextDeltaStep) {\n const stepKey = this.getStepKey(metadata);\n const dispatchedText = await dispatchTextMessageContent({\n graph: this,\n stepKey,\n provider: agentContext.provider,\n content: textMessageContent,\n metadata,\n });\n if (dispatchedText) {\n markPostReasoningContent(agentContext);\n }\n }\n\n await handleToolCalls(toolCalls as ToolCall[], metadata, this);\n }\n\n /**\n * When streaming events are unavailable, ChatModelStreamHandler never\n * fires. Dispatch final reasoning/text content here. getMessageId makes\n * this a no-op when the streaming path already handled the same step.\n */\n if (!hasToolCalls && responseMessage != null) {\n const dispatchedReasoning =\n dispatchableFinalReasoningContent != null &&\n (await dispatchReasoningContent({\n graph: this,\n agentContext,\n reasoningContent: dispatchableFinalReasoningContent,\n metadata,\n }));\n if (dispatchedReasoning && textMessageContent != null) {\n markPostReasoningContent(agentContext);\n }\n if (textMessageContent != null && !hasStreamedTextDeltaStep) {\n const stepKey = this.getStepKey(metadata);\n await dispatchTextMessageContent({\n graph: this,\n stepKey,\n provider: agentContext.provider,\n content: textMessageContent,\n metadata,\n });\n }\n }\n\n const invokeElapsed = ((Date.now() - invokeStart) / 1000).toFixed(2);\n agentContext.currentUsage = this.getUsageMetadata(result.messages?.[0]);\n /**\n * Synthetic usage from a sealed turn is an estimate derived from the\n * host's own counter, so feeding it to calibration would teach a ratio\n * of exactly 1.0 — self-consistent by construction, and wrong for any\n * provider whose real ratio differs. It still flows to `currentUsage`\n * for host billing; it just does not get to move the EMA.\n */\n const estimatedUsage =\n (result.messages?.[0] as AIMessageChunk | undefined)?.response_metadata\n .estimated_usage === true;\n if (agentContext.currentUsage) {\n if (!estimatedUsage) {\n agentContext.updateLastCallUsage(agentContext.currentUsage);\n }\n emitAgentLog(\n config,\n 'debug',\n 'graph',\n `LLM call complete (${invokeElapsed}s)`,\n {\n ...agentContext.currentUsage,\n elapsedSeconds: Number(invokeElapsed),\n instructionTokens: agentContext.instructionTokens,\n toolSchemaTokens: agentContext.toolSchemaTokens,\n messageCount: finalMessages.length,\n },\n invokeMeta,\n { force: true }\n );\n } else {\n emitAgentLog(\n config,\n 'debug',\n 'graph',\n `LLM call complete (${invokeElapsed}s)`,\n {\n elapsedSeconds: Number(invokeElapsed),\n messageCount: finalMessages.length,\n },\n invokeMeta,\n { force: true }\n );\n }\n if (\n (responseMessage as AIMessageChunk | undefined)?.response_metadata\n .preempted === true\n ) {\n const { messages: injected, preventContinuation } =\n await this.dispatchPreemptBoundary(agentId, config);\n /**\n * Release before branching: the slot is held only for the duration of\n * the drain, and an early return below must not strand it.\n */\n this.releasePreemptSeal();\n if (preventContinuation) {\n /**\n * A hook halted at the boundary. Commit the sealed turn and anything\n * it injected, but do NOT self-loop: `preventContinuation` promises\n * no further model turn, and the run-loop poll in `processStream`\n * only sees the halt AFTER the next call would already have started\n * — direct graph consumers never poll it at all. A trailing injected\n * HumanMessage carries no tool calls, so `toolsCondition` routes it\n * to END.\n */\n this.preemptIncomplete = true;\n /**\n * A halting boundary that ALSO injected nothing is still an empty\n * boundary by the `getPreemptStats().emptyBoundaries` contract —\n * hosts use the counter for truncated-seal telemetry, and both\n * paths end the turn with nothing to resume from.\n */\n if (injected.length === 0) {\n this.preemptEmptyBoundaries += 1;\n }\n this.cleanupSignalListener();\n return injected.length > 0\n ? { messages: [...(result.messages ?? []), ...injected] }\n : result;\n }\n if (injected.length > 0) {\n this.pendingPreemptReturn.add(agentId);\n this.cleanupSignalListener();\n return { messages: [...(result.messages ?? []), ...injected] };\n }\n /**\n * Nothing to inject — the host cancelled or already drained. Do NOT\n * self-loop: a trailing model turn with no new input is dropped by\n * some Gemini models and read as prefill by Anthropic. Do NOT pretend\n * the turn completed either; the answer really was cut short.\n */\n this.preemptEmptyBoundaries += 1;\n this.preemptIncomplete = true;\n }\n\n this.cleanupSignalListener();\n return result;\n };\n }\n\n /**\n * Fires `PreemptBoundary` after a sealed turn and returns whatever the\n * hooks asked to inject, converted through the same `convertInjectedMessages`\n * the tool boundary uses so the two sites cannot emit different shapes.\n *\n * Never throws: a drain that fails or times out costs the injection, not the\n * run. The caller treats an empty result as \"nothing to resume with\".\n *\n * `preventContinuation` is surfaced alongside the messages rather than left\n * to the registry halt signal, which `processStream` only polls between\n * stream events — by then the self-loop it was meant to prevent has already\n * issued another model call, and a direct graph consumer never polls it.\n */\n private async dispatchPreemptBoundary(\n agentId: string,\n config: RunnableConfig | undefined\n ): Promise<PreemptBoundaryResult> {\n if (this.hookRegistry == null) {\n return EMPTY_PREEMPT_BOUNDARY;\n }\n const configurable = config?.configurable;\n const runId = (configurable?.run_id as string | undefined) ?? this.runId;\n if (runId == null) {\n return EMPTY_PREEMPT_BOUNDARY;\n }\n const result = await executeHooks({\n registry: this.hookRegistry,\n input: {\n hook_event_name: 'PreemptBoundary',\n runId,\n threadId: configurable?.thread_id as string | undefined,\n agentId: this.subagentScope ? agentId : undefined,\n executingAgentId: agentId,\n sealCount: this.preemptSealCount,\n },\n sessionId: runId,\n timeoutMs: PREEMPT_BOUNDARY_HOOK_TIMEOUT_MS,\n /**\n * The host's own abort signal(s), deliberately NOT `config.signal` —\n * inside a node the latter is LangGraph's composed signal, which also\n * fires when an unrelated sibling in the same superstep throws.\n * Cancellation already returns control in milliseconds without this;\n * what it buys is that a drain does not keep running after the run it\n * belongs to died.\n *\n * Composed because the host can cancel through either channel: the\n * construction signal, or the per-call `callerConfig.signal` — the only\n * one a multi-agent run has, since `MultiAgentGraphConfig` exposes no\n * construction signal. When both exist they may be different\n * controllers, and a drain must stop when EITHER fires.\n */\n signal: composeAbortSignals(this.signal, this.callerSignal),\n }).catch((): undefined => undefined);\n if (result == null) {\n return EMPTY_PREEMPT_BOUNDARY;\n }\n /**\n * `executeHooks` raises a registry halt whenever a hook returns\n * `preventContinuation`. That halt has exactly one consumer — the poll in\n * `Run.processStream` — and its `break` cancels the stream iterator, which\n * aborts Pregel. The abort lands BEFORE the outer reducer commits\n * `StandardGraph.messages`, so honoring the halt here would destroy the\n * sealed assistant turn: the run returns empty content and the host\n * persists nothing. Measured deterministically — the commit is several\n * stream events downstream of the point the halt becomes observable.\n *\n * The `preventContinuation` branch in `createCallModel` already enforces\n * the contract locally by declining to self-loop, and a sealed chunk\n * provably carries no tool calls, so the turn routes to END after exactly\n * one model call either way. Clearing the halt therefore costs nothing it\n * was buying and saves the content the seal exists to preserve.\n *\n * Scoped to a halt this event raised, so a halt from an earlier hook in\n * the same run — `haltRun` is first-write-wins — is left alone.\n */\n const halt = this.hookRegistry.getHaltSignal(runId);\n if (\n result.preventContinuation === true &&\n halt?.source === 'PreemptBoundary'\n ) {\n this.preemptHaltReason = halt.reason;\n this.hookRegistry.clearHaltSignal(runId);\n }\n const injected: BaseMessage[] = [];\n /**\n * `PreemptBoundaryHookOutput` is `BaseHookOutput`, so `additionalContext`\n * is part of the contract here just as it is at the tool boundary. It has\n * to be materialized BEFORE the emptiness test, or a hook that returns\n * context alone would read as \"nothing to resume with\" and cut the answer\n * short. Same system-flavored `HumanMessage` convention `ToolNode` uses —\n * Anthropic and Google reject a mid-conversation `SystemMessage`.\n */\n /**\n * Whitespace-only entries are dropped for the same reason empty\n * `injectedMessages` are: `executeHooks` keeps them because their raw\n * length is nonzero, but a blank turn is not something to resume from —\n * it costs a model call and strict providers reject it outright.\n */\n const contexts = result.additionalContexts.filter(\n (context) => context.trim() !== ''\n );\n if (contexts.length > 0) {\n injected.push(\n new HumanMessage({\n content: contexts.join('\\n\\n'),\n additional_kwargs: { role: 'system', isMeta: true, source: 'hook' },\n })\n );\n }\n if (result.injectedMessages.length > 0) {\n try {\n injected.push(...convertInjectedMessages(result.injectedMessages));\n } catch (e) {\n console.warn(\n '[StandardGraph] Failed to convert PreemptBoundary injectedMessages:',\n e instanceof Error ? e.message : e\n );\n }\n }\n return {\n messages: injected,\n preventContinuation: result.preventContinuation === true,\n };\n }\n\n createAgentNode(agentId: string): t.CompiledAgentWorfklow {\n const getConfig = (): RunnableConfig | undefined => this.config;\n const agentContext = this.agentContexts.get(agentId);\n if (!agentContext) {\n throw new Error(`Agent context not found for agentId: ${agentId}`);\n }\n\n /**\n * Depth countdown across graph boundaries: the parent's `maxSubagentDepth`\n * becomes this executor's `maxDepth`. When the child graph is constructed,\n * `buildChildInputs()` decrements `maxSubagentDepth` on the child's\n * `AgentInputs` (only when `allowNested: true`; otherwise subagentConfigs\n * are stripped entirely). The child graph's own `createAgentNode()` then\n * reads the decremented value here and creates a narrower executor —\n * recursion is bounded even though each graph has its own separate\n * executor instance.\n */\n const effectiveSubagentDepth = agentContext.maxSubagentDepth ?? 1;\n if (\n agentContext.subagentConfigs != null &&\n agentContext.subagentConfigs.length > 0 &&\n effectiveSubagentDepth > 0\n ) {\n const executableConfigs = normalizeSubagentConfigEntries(\n agentContext.subagentConfigs,\n agentContext\n );\n if (executableConfigs.length > 0) {\n if (\n !this.supportsMultiAgentChildren &&\n executableConfigs.some(isGraphSubagentConfig)\n ) {\n throw new Error(\n 'Graph subagents require constructing the parent with createGraph() or an injected GraphFactory dependency.'\n );\n }\n const getParentHandlerRegistry = (): HandlerRegistry | undefined =>\n this.handlerRegistry ?? this.parentToolHandlerRegistry;\n const createConfiguredChildGraph: GraphFactory = (request) => {\n const childGraph = this.graphFactory(request);\n if (this.subagentModelOverride != null) {\n childGraph.overrideModel = this.subagentModelOverride;\n childGraph.setSubagentModelOverride(this.subagentModelOverride);\n }\n const childHandlerRegistry = createChildHandlerRegistry(\n getParentHandlerRegistry()\n );\n // Pure execution-ordering hint (unlike `humanInTheLoop`). It only\n // reorders tools already in the child's direct group; it does not\n // force a schema-only event tool onto the direct execution path.\n applyGraphRuntimeConfig(childGraph, {\n hookRegistry: this.hookRegistry,\n humanInTheLoop: this.humanInTheLoop,\n toolOutputReferences: this.toolOutputReferences,\n eagerEventToolExecution: this.eagerEventToolExecution,\n codeSessionToolNames: this.codeSessionToolNames,\n interruptingToolNames: this.interruptingToolNames,\n toolExecution: this.toolExecution,\n });\n if (this.humanInTheLoop?.enabled === true) {\n childGraph.compileOptions = {\n checkpointer: this.compileOptions?.checkpointer,\n };\n }\n childGraph.parentToolHandlerRegistry = childHandlerRegistry;\n childGraph.eventToolExecutionAvailable =\n childHandlerRegistry?.getHandler(GraphEvents.ON_TOOL_EXECUTE) !=\n null;\n return childGraph;\n };\n const executor = new SubagentExecutor({\n configs: new Map(\n executableConfigs.map((config) => [config.type, config])\n ),\n parentSignal: this.signal,\n breakerScope: {\n controller: (): AbortController => this.breakerAbort,\n },\n hookRegistry: this.hookRegistry,\n /** Lazy — Run wires the registry onto the graph AFTER\n * `createWorkflow()` runs, so a direct capture here would be\n * `undefined` at construction time. */\n parentHandlerRegistry: getParentHandlerRegistry,\n parentRunId: this.runId ?? '',\n parentAgentId: agentContext.agentId,\n executionContext: this.subagentExecutionContext,\n langfuse: this.langfuse,\n tokenCounter: agentContext.tokenCounter,\n usageSink: this.subagentUsageSink,\n streamLimits: this.streamLimits,\n humanInTheLoop: this.humanInTheLoop,\n checkpointer: this.compileOptions?.checkpointer,\n maxDepth: effectiveSubagentDepth,\n createChildGraph: (input): StandardGraph =>\n createConfiguredChildGraph({\n kind: 'standard',\n input,\n }),\n createChildGraphByKind: createConfiguredChildGraph,\n });\n this.registerSubagentExecutor(executor);\n\n const subagentTool = tool(async (rawInput, config) => {\n const input = rawInput as {\n description?: string;\n subagent_type?: string;\n };\n const description =\n typeof input.description === 'string' &&\n input.description.trim().length > 0\n ? input.description\n : DEFAULT_SUBAGENT_DESCRIPTION;\n const subagentType =\n typeof input.subagent_type === 'string' ? input.subagent_type : '';\n const threadId = config.configurable?.thread_id as string | undefined;\n /** Surface the parent call id so child checkpoints, interrupts, and\n * update events remain correlated across replay and resume. */\n const toolRuntime = config as {\n toolCallId?: string;\n toolCall?: { id?: string };\n };\n const toolCall = toolRuntime.toolCall;\n let parentToolCallId: string | undefined;\n if (\n typeof toolRuntime.toolCallId === 'string' &&\n toolRuntime.toolCallId !== ''\n ) {\n parentToolCallId = toolRuntime.toolCallId;\n } else if (typeof toolCall?.id === 'string' && toolCall.id !== '') {\n parentToolCallId = toolCall.id;\n }\n /** The parent tool batch's entry-captured scope (stamped by\n * ToolNode before PreToolUse hooks) — binds this child to the\n * run that dispatched it, not to whatever controller a reset\n * installed while the hooks were awaited. */\n const batchScope = config.configurable?.[\n RUN_BREAKER_SCOPE_CONFIG_KEY\n ] as RunBreakerScope | undefined;\n const result = await executor.execute({\n description,\n subagentType,\n threadId,\n signal: config.signal,\n parentToolCallId,\n breaker: batchScope?.controller,\n /**\n * Forward the parent's `configurable` so host-set fields\n * (`requestBody`, `user`, etc.) propagate into the child\n * workflow. The executor scrubs run-identity fields before\n * forwarding — see `SubagentExecuteParams.parentConfigurable`.\n */\n parentConfigurable: config.configurable as\n | Record<string, unknown>\n | undefined,\n });\n return result.content;\n }, buildSubagentToolParams(executableConfigs));\n const replayableSubagentTool = subagentTool as typeof subagentTool &\n ReplayableSubagentTool;\n replayableSubagentTool[SUBAGENT_REPLAY_CONTROLLER] = {\n getResumeManifest: (\n parentToolCallIds,\n config\n ): Promise<SubagentResumeManifest | undefined> =>\n executor.getResumeManifest(parentToolCallIds, config),\n getSettledOutput: (\n call,\n config\n ): Promise<SettledSubagentToolOutput | undefined> =>\n executor.getSettledToolOutput(call, config),\n persistSettledOutput: (call, config, output): Promise<void> =>\n executor.persistSettledToolOutput(call, config, output),\n };\n\n if (!agentContext.graphTools) {\n agentContext.graphTools = [];\n }\n (agentContext.graphTools as t.GenericTool[]).push(subagentTool);\n\n /**\n * Refresh toolSchemaTokens to include the subagent tool's schema.\n * `calculateInstructionTokens()` was kicked off in `fromConfig()`\n * before graphTools was populated, so its result did not count this\n * tool. Without this retrigger, token-budget/pruning logic\n * underestimates prompt overhead.\n */\n if (agentContext.tokenCounter) {\n const { tokenCounter, baseIndexTokenCountMap } = agentContext;\n agentContext.tokenCalculationPromise = agentContext\n .calculateInstructionTokens(tokenCounter)\n .then(() => {\n agentContext.updateTokenMapWithInstructions(\n baseIndexTokenCountMap\n );\n })\n .catch((err) => {\n console.error(\n 'Error recalculating instruction tokens after subagent tool injection:',\n err\n );\n });\n }\n }\n }\n\n const agentNode = `${AGENT}${agentId}` as const;\n const toolNode = `${TOOLS}${agentId}` as const;\n const summarizeNode = `${SUMMARIZE}${agentId}` as const;\n\n const routeMessage = (\n state: t.AgentSubgraphState,\n config?: RunnableConfig\n ): string => {\n this.config = config;\n /**\n * A sealed turn that injected messages resumes in the SAME pregel run:\n * back to the agent node as a new superstep, so the model continues in\n * one assistant message instead of restarting the graph.\n */\n if (this.pendingPreemptReturn.delete(agentId)) {\n return agentNode;\n }\n if (state.summarizationRequest != null) {\n return summarizeNode;\n }\n return toolsCondition(\n state as t.BaseGraphState,\n toolNode,\n this.invokedToolIds\n );\n };\n\n const StateAnnotation = Annotation.Root({\n messages: Annotation<BaseMessage[]>({\n reducer: messagesStateReducer,\n default: () => [],\n }),\n summarizationRequest: Annotation<t.SummarizationNodeInput | undefined>({\n reducer: (\n _: t.SummarizationNodeInput | undefined,\n b: t.SummarizationNodeInput | undefined\n ) => b,\n default: () => undefined,\n }),\n });\n\n const readChargeCredits = ():\n | WeakMap<object, Map<string, number>>\n | undefined => this.streamLimitChargeCredits;\n const readBreakerEpoch = (): number => this.breakerEpoch;\n const readActiveGenerations = (): Set<string> | undefined =>\n this.activeStreamLimitGenerations;\n const writeActiveGenerations = (value: Set<string> | undefined): void => {\n this.activeStreamLimitGenerations = value;\n };\n const writeChargeCredits = (\n value: WeakMap<object, Map<string, number>> | undefined\n ): void => {\n this.streamLimitChargeCredits = value;\n };\n\n const workflow = new StateGraph(StateAnnotation)\n .addNode(agentNode, this.createCallModel(agentId))\n .addNode(\n toolNode,\n this.initializeTools({\n currentTools: agentContext.tools,\n currentToolMap: agentContext.toolMap,\n agentContext,\n })\n )\n .addNode(\n summarizeNode,\n createSummarizeNode({\n agentContext,\n graph: {\n contentData: this.contentData,\n contentIndexMap: this.contentIndexMap,\n get config() {\n return getConfig();\n },\n runId: this.runId,\n isMultiAgent: this.isMultiAgentGraph(),\n hookRegistry: this.hookRegistry,\n /**\n * Live references (both maps are cleared in place, never\n * replaced), so summarization streams share the run's event\n * budget accounting under their own generation key.\n */\n streamLimits: this.streamLimits,\n streamDeltaEventCounts: this.streamDeltaEventCounts,\n streamedToolCallArgTallies: this.streamedToolCallArgTallies,\n /** Accessor pair, not a value copy: unlike the two maps above,\n * the credit map is REPLACED by graph resets rather than cleared\n * in place, and the guards' lazy `??=` must install onto the\n * graph — a copy held here would survive resets and grow one\n * attempt-stamped entry per compaction for a retained reused\n * chunk object. */\n get streamLimitChargeCredits() {\n return readChargeCredits();\n },\n set streamLimitChargeCredits(\n value: WeakMap<object, Map<string, number>> | undefined\n ) {\n writeChargeCredits(value);\n },\n /** Live epoch, so summary tallies are creation-tagged and the\n * resetValues grace sweep treats them like model-attempt\n * entries. */\n get breakerEpoch(): number {\n return readBreakerEpoch();\n },\n /** Accessor pair like the charge credits: summary attempts\n * lease their generations on the GRAPH's active set, and the\n * lazy `??=` in the lease helper must install there. */\n get activeStreamLimitGenerations(): Set<string> | undefined {\n return readActiveGenerations();\n },\n set activeStreamLimitGenerations(value: Set<string> | undefined) {\n writeActiveGenerations(value);\n },\n /** Read per attempt: a sibling branch tripping the run breaker\n * must also cancel in-flight summarization model calls. */\n getBreakerSignal: (): AbortSignal => this.breakerAbort.signal,\n /** The node captures this at entry so its own chunk handler's\n * breach trips the run that STARTED the summarization, not a\n * controller installed by a later reset. */\n getBreakerController: (): AbortController => this.breakerAbort,\n /** Captured at node entry and stamped into the summary attempt\n * metadata, so the wire consumer epoch-gates old-run summary\n * chunks exactly like model-attempt chunks. */\n getBreakerEpoch: (): number => this.breakerEpoch,\n dispatchRunStep: async (runStep, nodeConfig) => {\n const resolvedConfig = nodeConfig ?? this.config;\n if (runStep.agentId != null) {\n const groupId = this.resolveParallelGroupId(\n runStep.agentId,\n resolvedConfig?.metadata\n );\n if (groupId != null) {\n runStep.groupId = groupId;\n }\n }\n this.contentData.push(runStep);\n this.contentIndexMap.set(runStep.id, runStep.index);\n\n const handler = this.handlerRegistry?.getHandler(\n GraphEvents.ON_RUN_STEP\n );\n if (handler) {\n await handler.handle(\n GraphEvents.ON_RUN_STEP,\n runStep,\n resolvedConfig?.configurable,\n this\n );\n this.handlerDispatchedStepIds.add(runStep.id);\n }\n\n const unmarkHandlerDispatchedEvent = handler\n ? this.markHandlerDispatchedEvent(\n GraphEvents.ON_RUN_STEP,\n runStep.id\n )\n : undefined;\n try {\n if (resolvedConfig) {\n await safeDispatchCustomEvent(\n GraphEvents.ON_RUN_STEP,\n runStep,\n resolvedConfig\n );\n }\n } finally {\n unmarkHandlerDispatchedEvent?.();\n }\n },\n dispatchRunStepCompleted: async (\n stepId: string,\n result: t.StepCompleted,\n nodeConfig?: RunnableConfig\n ) => {\n const resolvedConfig = nodeConfig ?? this.config;\n const runStep = this.contentData.find((s) => s.id === stepId);\n const handler = this.handlerRegistry?.getHandler(\n GraphEvents.ON_RUN_STEP_COMPLETED\n );\n if (handler) {\n await handler.handle(\n GraphEvents.ON_RUN_STEP_COMPLETED,\n {\n result: {\n ...result,\n id: stepId,\n index: runStep?.index ?? 0,\n },\n },\n resolvedConfig?.configurable,\n this\n );\n }\n },\n },\n generateStepId: (stepKey: string) => this.generateStepId(stepKey),\n })\n )\n .addEdge(START, agentNode)\n .addConditionalEdges(agentNode, routeMessage)\n .addEdge(summarizeNode, agentNode)\n .addEdge(toolNode, agentContext.toolEnd ? END : agentNode);\n\n return workflow.compile();\n }\n\n createWorkflow(): t.CompiledStateWorkflow {\n this.hasCompiledCheckpointer = this.compileOptions?.checkpointer != null;\n const agentNode = this.createAgentNode(this.defaultAgentId);\n const StateAnnotation = Annotation.Root({\n messages: Annotation<BaseMessage[]>({\n reducer: (a, b) => {\n if (!this.messages.length && !this.hasRestoredCheckpointMessages) {\n this.startIndex = a.length + b.length;\n }\n const result = messagesStateReducer(a, b);\n this.messages = result;\n return result;\n },\n default: () => [],\n }),\n });\n const workflow = new StateGraph(StateAnnotation)\n .addNode(\n this.defaultAgentId,\n agentNode as Runnable<\n t.AgentSubgraphState,\n Partial<t.AgentSubgraphState>\n >,\n { ends: [END] }\n )\n .addEdge(START, this.defaultAgentId)\n // LangGraph compile() types are overly strict for opt-in options\n .compile(this.compileOptions as unknown as never);\n\n return workflow;\n }\n\n /**\n * Indicates if this is a multi-agent graph.\n * Override in MultiAgentGraph to return true.\n * Used to conditionally include agentId in RunStep for frontend rendering.\n */\n protected isMultiAgentGraph(): boolean {\n return false;\n }\n\n /**\n * Get the parallel group ID for an agent, if any.\n * Override in MultiAgentGraph to provide actual group IDs.\n * Group IDs are incrementing numbers (1, 2, 3...) reflecting execution order.\n * @param _agentId - The agent ID to look up\n * @returns undefined for StandardGraph (no parallel groups), or group number for MultiAgentGraph\n */\n protected getParallelGroupIdForAgent(_agentId: string): number | undefined {\n return undefined;\n }\n\n protected resolveParallelGroupId(\n agentId: string,\n metadata?: Record<string, unknown>\n ): number | undefined {\n if (\n metadata == null ||\n !Object.prototype.hasOwnProperty.call(\n metadata,\n Constants.HANDOFF_GROUP_ID\n )\n ) {\n return this.getParallelGroupIdForAgent(agentId);\n }\n const runtimeGroupId = metadata[Constants.HANDOFF_GROUP_ID];\n if (runtimeGroupId === null) {\n return undefined;\n }\n if (\n typeof runtimeGroupId === 'number' &&\n Number.isSafeInteger(runtimeGroupId) &&\n runtimeGroupId > 0\n ) {\n return runtimeGroupId;\n }\n return this.getParallelGroupIdForAgent(agentId);\n }\n\n /* Dispatchers */\n\n /**\n * Dispatches a run step to the client, returns the step ID\n */\n async dispatchRunStep(\n stepKey: string,\n stepDetails: t.StepDetails,\n metadata?: Record<string, unknown>\n ): Promise<string> {\n if (!this.config) {\n throw new Error('No config provided');\n }\n\n const [stepId, stepIndex] = this.generateStepId(stepKey);\n if (stepDetails.type === StepTypes.TOOL_CALLS && stepDetails.tool_calls) {\n for (const tool_call of stepDetails.tool_calls) {\n const toolCallId = tool_call.id ?? '';\n if (!toolCallId || this.toolCallStepIds.has(toolCallId)) {\n continue;\n }\n this.toolCallStepIds.set(toolCallId, stepId);\n }\n }\n\n const runStep: t.RunStep = {\n stepIndex,\n id: stepId,\n type: stepDetails.type,\n index: this.contentData.length,\n stepDetails,\n usage: null,\n };\n\n const runId = this.runId ?? '';\n if (runId) {\n runStep.runId = runId;\n }\n\n if (metadata) {\n try {\n const agentContext = this.getAgentContext(metadata);\n if (this.isMultiAgentGraph() && agentContext.agentId) {\n runStep.agentId = agentContext.agentId;\n const groupId = this.resolveParallelGroupId(\n agentContext.agentId,\n metadata\n );\n if (groupId != null) {\n runStep.groupId = groupId;\n }\n }\n } catch (_e) {\n /** If we can't get agent context, that's okay - agentId remains undefined */\n }\n }\n\n this.contentData.push(runStep);\n this.contentIndexMap.set(stepId, runStep.index);\n\n // Primary dispatch: handler registry (reliable, always works).\n // This mirrors how handleToolCallCompleted dispatches ON_RUN_STEP_COMPLETED\n // via the handler registry, ensuring the event always reaches the handler\n // even when LangGraph's callback system drops the custom event.\n const handler = this.handlerRegistry?.getHandler(GraphEvents.ON_RUN_STEP);\n if (handler) {\n await handler.handle(GraphEvents.ON_RUN_STEP, runStep, metadata, this);\n this.handlerDispatchedStepIds.add(stepId);\n }\n\n // Secondary dispatch: custom event for LangGraph callback chain\n // (tracing, Langfuse, external consumers). May be silently dropped\n // in some scenarios (stale run ID, subgraph callback propagation issues),\n // but the primary dispatch above guarantees the event reaches the handler.\n // The customEventCallback in run.ts skips events already dispatched above\n // to prevent double handling.\n const unmarkHandlerDispatchedEvent = handler\n ? this.markHandlerDispatchedEvent(GraphEvents.ON_RUN_STEP, stepId)\n : undefined;\n try {\n await safeDispatchCustomEvent(\n GraphEvents.ON_RUN_STEP,\n runStep,\n this.config\n );\n } finally {\n unmarkHandlerDispatchedEvent?.();\n }\n return stepId;\n }\n\n /**\n * Static version of handleToolCallError to avoid creating strong references\n * that prevent garbage collection.\n *\n * Returns whether the error completion event was actually dispatched. A\n * tool can error before this graph instance has a run step for the call —\n * on a resume pass the interrupted batch re-executes IMMEDIATELY on graph\n * re-entry, before any step replay has registered `toolCallStepIds` (a\n * fast-failing tool, e.g. a schema-validation reject, loses that race).\n * That is a caller-recoverable condition, not an invariant violation: the\n * ToolNode falls back to its normal completion dispatch for the error\n * ToolMessage when this returns `false`, so throwing here would only\n * replace a recoverable miss with a lost completion event and a scary log.\n */\n static async handleToolCallErrorStatic(\n graph: StandardGraph,\n data: t.ToolErrorData,\n metadata?: Record<string, unknown>\n ): Promise<boolean> {\n if (!data.id) {\n console.warn('No Tool ID provided for Tool Error');\n return false;\n }\n\n const stepId = graph.toolCallStepIds.get(data.id) ?? '';\n if (!stepId) {\n return false;\n }\n\n const { name, input: args, error } = data;\n const eventValueLimit = calculateMaxToolResultChars();\n const errorOutputPrefix = 'Error processing tool';\n const errorDetail =\n error?.message != null\n ? `: ${serializeToolContentBounded(\n error.message,\n Math.max(0, eventValueLimit - errorOutputPrefix.length - 2)\n )}`\n : '';\n\n const runStep = graph.getRunStep(stepId);\n if (!runStep) {\n return false;\n }\n\n const tool_call: t.ProcessedToolCall = {\n id: data.id,\n name: name || '',\n args: serializeToolContentBounded(args, eventValueLimit),\n output: `${errorOutputPrefix}${errorDetail}`,\n progress: 1,\n };\n\n // No registered ON_RUN_STEP_COMPLETED handler ⇒ nothing was dispatched.\n // Report `false` so the ToolNode runs its own fallback dispatch; returning\n // `true` here would silently drop the error completion for hosts that wire\n // completions through callback-based custom events instead of a handler.\n const handler = graph.handlerRegistry?.getHandler(\n GraphEvents.ON_RUN_STEP_COMPLETED\n );\n if (!handler) {\n return false;\n }\n\n await handler.handle(\n GraphEvents.ON_RUN_STEP_COMPLETED,\n {\n result: {\n id: stepId,\n index: runStep.index,\n type: 'tool_call',\n tool_call,\n } as t.ToolCompleteEvent,\n },\n metadata,\n graph\n );\n return true;\n }\n\n /**\n * Instance method that delegates to the static method\n * Kept for backward compatibility\n */\n async handleToolCallError(\n data: t.ToolErrorData,\n metadata?: Record<string, unknown>\n ): Promise<boolean> {\n return StandardGraph.handleToolCallErrorStatic(this, data, metadata);\n }\n\n async dispatchRunStepDelta(\n id: string,\n delta: t.ToolCallDelta,\n metadata?: Record<string, unknown>\n ): Promise<void> {\n if (!this.config) {\n throw new Error('No config provided');\n } else if (!id) {\n throw new Error('No step ID found');\n }\n const runStepDelta: t.RunStepDeltaEvent = {\n id,\n delta,\n };\n const handler = this.handlerRegistry?.getHandler(\n GraphEvents.ON_RUN_STEP_DELTA\n );\n if (handler) {\n await handler.handle(\n GraphEvents.ON_RUN_STEP_DELTA,\n runStepDelta,\n metadata,\n this\n );\n this.handlerDispatchedStepIds.add(id);\n }\n const unmarkHandlerDispatchedEvent = handler\n ? this.markHandlerDispatchedEvent(GraphEvents.ON_RUN_STEP_DELTA, id)\n : undefined;\n try {\n await safeDispatchCustomEvent(\n GraphEvents.ON_RUN_STEP_DELTA,\n runStepDelta,\n this.config\n );\n } finally {\n unmarkHandlerDispatchedEvent?.();\n }\n }\n\n async dispatchMessageDelta(\n id: string,\n delta: t.MessageDelta,\n metadata?: Record<string, unknown>\n ): Promise<void> {\n if (!this.config) {\n throw new Error('No config provided');\n }\n const messageDelta: t.MessageDeltaEvent = {\n id,\n delta,\n };\n if (hasTextDeltaContent(delta.content)) {\n this.messageStepHasTextDeltas.add(id);\n }\n const handler = this.handlerRegistry?.getHandler(\n GraphEvents.ON_MESSAGE_DELTA\n );\n if (handler) {\n await handler.handle(\n GraphEvents.ON_MESSAGE_DELTA,\n messageDelta,\n metadata,\n this\n );\n this.handlerDispatchedStepIds.add(id);\n }\n const unmarkHandlerDispatchedEvent = handler\n ? this.markHandlerDispatchedEvent(GraphEvents.ON_MESSAGE_DELTA, id)\n : undefined;\n try {\n await safeDispatchCustomEvent(\n GraphEvents.ON_MESSAGE_DELTA,\n messageDelta,\n this.config\n );\n } finally {\n unmarkHandlerDispatchedEvent?.();\n }\n }\n\n dispatchReasoningDelta = async (\n stepId: string,\n delta: t.ReasoningDelta,\n metadata?: Record<string, unknown>\n ): Promise<void> => {\n if (!this.config) {\n throw new Error('No config provided');\n }\n const reasoningDelta: t.ReasoningDeltaEvent = {\n id: stepId,\n delta,\n };\n if (hasReasoningDeltaContent(delta.content)) {\n this.reasoningStepHasDeltas.add(stepId);\n }\n const handler = this.handlerRegistry?.getHandler(\n GraphEvents.ON_REASONING_DELTA\n );\n if (handler) {\n await handler.handle(\n GraphEvents.ON_REASONING_DELTA,\n reasoningDelta,\n metadata,\n this\n );\n this.handlerDispatchedStepIds.add(stepId);\n }\n const unmarkHandlerDispatchedEvent = handler\n ? this.markHandlerDispatchedEvent(GraphEvents.ON_REASONING_DELTA, stepId)\n : undefined;\n try {\n await safeDispatchCustomEvent(\n GraphEvents.ON_REASONING_DELTA,\n reasoningDelta,\n this.config\n );\n } finally {\n unmarkHandlerDispatchedEvent?.();\n }\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgLA,MAAM,EAAE,OAAO,OAAO,cAAcA,aAAAA;AASpC,MAAM,yBAAgD;CACpD,UAAU,CAAC;CACX,qBAAqB;AACvB;;AAGA,MAAM,iCAAiC;AAEvC,SAAS,2BACP,QAC6B;CAC7B,MAAM,cAAc,QAAQ,WAAA,iBAAsC;CAClE,MAAM,gBAAgB,QAAQ,WAAA,oBAAyC;CACvE,IAAI,eAAe,QAAQ,iBAAiB,MAC1C;CAEF,MAAM,WAAW,IAAIC,iBAAAA,gBAAgB;CACrC,IAAI,eAAe,MACjB,SAAS,SAAA,mBAAsC,WAAW;CAE5D,IAAI,iBAAiB,MACnB,SAAS,SAA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