{"version":3,"file":"Graph.cjs","sources":["../../../src/graphs/Graph.ts"],"sourcesContent":["/* eslint-disable no-console */\n// src/graphs/Graph.ts\nimport { nanoid } from 'nanoid';\nimport { concat } from '@langchain/core/utils/stream';\nimport { ToolNode } from '@langchain/langgraph/prebuilt';\nimport { ChatVertexAI } from '@langchain/google-vertexai';\nimport {\n  START,\n  END,\n  Command,\n  StateGraph,\n  Annotation,\n  messagesStateReducer,\n} from '@langchain/langgraph';\nimport {\n  Runnable,\n  RunnableConfig,\n  RunnableLambda,\n} from '@langchain/core/runnables';\nimport {\n  ToolMessage,\n  SystemMessage,\n  AIMessageChunk,\n  HumanMessage,\n} from '@langchain/core/messages';\nimport type {\n  BaseMessageFields,\n  MessageContent,\n  UsageMetadata,\n  BaseMessage,\n} from '@langchain/core/messages';\nimport type { ToolCall } from '@langchain/core/messages/tool';\nimport type * as t from '@/types';\nimport {\n  formatAnthropicArtifactContent,\n  ensureThinkingBlockInMessages,\n  deduplicateSystemMessages,\n  getContextUtilization,\n  convertMessagesToContent,\n  addBedrockCacheControl,\n  modifyDeltaProperties,\n  formatArtifactPayload,\n  formatContentStrings,\n  createPruneMessages,\n  addCacheControl,\n  getMessageId,\n} from '@/messages';\nimport {\n  GraphNodeKeys,\n  ContentTypes,\n  GraphEvents,\n  Providers,\n  StepTypes,\n  MessageTypes,\n  Constants,\n  TOOL_TURN_THINKING_BUDGET,\n  SUMMARIZATION_CONTEXT_THRESHOLD,\n  PROACTIVE_SUMMARY_THRESHOLD,\n  COMPACTION_RECENT_ROUNDS,\n} from '@/common';\nimport {\n  ToolDiscoveryCache,\n  resetIfNotEmpty,\n  isOpenAILike,\n  isGoogleLike,\n  joinKeys,\n  sleep,\n  createPruneCalibration,\n  updatePruneCalibration,\n  applyCalibration,\n} from '@/utils';\nimport type { PruneCalibrationState } from '@/types/graph';\nimport { buildFileManifestBlock } from '@/utils/fileManifest';\nimport {\n  buildContextAnalytics,\n  type ContextAnalytics,\n} from '@/utils/contextAnalytics';\nimport { getChatModelClass, manualToolStreamProviders } from '@/llm/providers';\nimport { ToolNode as CustomToolNode, toolsCondition } from '@/tools/ToolNode';\nimport { tool as makeStructuredTool } from '@langchain/core/tools';\nimport { SubagentExecutor, resolveSubagentConfigs } from '@/tools/subagent';\nimport { buildSubagentToolParams } from '@/tools/SubagentTool';\nimport {\n  annotateMessagesForLLM,\n  ToolOutputReferenceRegistry as ToolOutputReferenceRegistryClass,\n} from '@/tools/toolOutputReferences';\nimport { executeHooks } from '@/hooks';\nimport { ChatOpenAI, AzureChatOpenAI } from '@/llm/openai';\nimport { safeDispatchCustomEvent } from '@/utils/events';\nimport { mlog, mwarn } from '@/utils/logging';\nimport { normalizeMessageToolCalls } from '@/utils/toolCallNormalization';\nimport { isTruncationReason } from '@/utils/finishReasons';\nimport { isLikelyContextOverflowError } from '@/utils/errors';\nimport {\n  detectDocuments,\n  shouldInjectMultiDocHint,\n  buildMultiDocHintContent,\n  buildPostPruneNote,\n  hasTaskTool,\n} from '@/utils/contextPressure';\nimport { createSchemaOnlyTools } from '@/tools/schema';\nimport { prepareSchemaForProvider } from '@/schemas/validate';\nimport { AgentContext } from '@/agents/AgentContext';\nimport {\n  StructuredOutputRefusalError,\n  StructuredOutputTruncatedError,\n} from '@/types/graph';\nimport { createFakeStreamingLLM } from '@/llm/fake';\nimport { handleToolCalls } from '@/tools/handlers';\nimport { ChatModelStreamHandler } from '@/stream';\nimport { HandlerRegistry } from '@/events';\nimport { StreamingToolCallBuffer } from '@/tools/StreamingToolCallBuffer';\n\nconst { AGENT, TOOLS } = GraphNodeKeys;\n\nexport abstract class Graph<\n  T extends t.BaseGraphState = t.BaseGraphState,\n  _TNodeName extends string = string,\n> {\n  abstract resetValues(): void;\n  abstract initializeTools({\n    currentTools,\n    currentToolMap,\n  }: {\n    currentTools?: t.GraphTools;\n    currentToolMap?: t.ToolMap;\n  }): CustomToolNode<T> | ToolNode<T>;\n  abstract initializeModel({\n    currentModel,\n    tools,\n    clientOptions,\n  }: {\n    currentModel?: t.ChatModel;\n    tools?: t.GraphTools;\n    clientOptions?: t.ClientOptions;\n  }): Runnable;\n  abstract getRunMessages(): BaseMessage[] | undefined;\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 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  ): Promise<void>;\n  abstract dispatchMessageDelta(\n    id: string,\n    delta: t.MessageDelta\n  ): Promise<void>;\n  abstract dispatchReasoningDelta(\n    stepId: string,\n    delta: t.ReasoningDelta\n  ): Promise<void>;\n  abstract handleToolCallCompleted(\n    data: t.ToolEndData,\n    metadata?: Record<string, unknown>,\n    omitOutput?: boolean\n  ): Promise<void>;\n\n  abstract createCallModel(\n    agentId?: string,\n    currentModel?: t.ChatModel\n  ): (state: T, config?: RunnableConfig) => Promise<Partial<T>>;\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  signal?: 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  /** Optional hook registry threaded down from Run; consumed by ToolNode for tool-lifecycle hooks. */\n  hookRegistry?: import('@/hooks').HookRegistry;\n  /**\n   * Optional tool-output reference registry threaded down from Run\n   * (upstream PR #114). When set, every ToolNode built by this graph\n   * stores successful outputs here and resolves `{{tool<i>turn<n>}}`\n   * placeholders in args before invoking the tool.\n   *\n   * @deprecated Prefer `toolOutputReferences` config + the lazy\n   * `getOrCreateToolOutputRegistry()` accessor — keeps the registry\n   * lifecycle explicit (cleared in `clearHeavyState()`). Existing\n   * direct-set callers still work for backwards compat.\n   */\n  toolOutputRegistry?: import('@/tools/toolOutputReferences').ToolOutputReferenceRegistry;\n  /**\n   * Run-scoped tool output reference configuration (upstream PR #117).\n   * When `enabled` is true, the graph lazily allocates a single\n   * `ToolOutputReferenceRegistry` on first `getOrCreateToolOutputRegistry()`\n   * call and shares it with every ToolNode the graph compiles, so\n   * cross-agent `{{tool<i>turn<n>}}` substitutions resolve.\n   */\n  toolOutputReferences?: import('@/types/tools').ToolOutputReferencesConfig;\n  /**\n   * Lazy single-instance registry for the run. Constructed on first\n   * `getOrCreateToolOutputRegistry()` call when\n   * `toolOutputReferences.enabled` is true. Cleared (and recreated on\n   * next access) by `clearHeavyState()`.\n   */\n  private _toolOutputRegistry?: import('@/tools/toolOutputReferences').ToolOutputReferenceRegistry;\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 `annotateMessagesForLLM`).\n   * Host code should not call this directly — registry mutations outside\n   * the ToolNode lifecycle break the partitioning, eviction, and\n   * turn-counter invariants.\n   */\n  public getOrCreateToolOutputRegistry():\n    | import('@/tools/toolOutputReferences').ToolOutputReferenceRegistry\n    | undefined {\n    // Direct-set instance (legacy path) takes precedence so existing\n    // Run plumbing keeps working.\n    if (this.toolOutputRegistry != null) {\n      return this.toolOutputRegistry;\n    }\n    if (this.toolOutputReferences?.enabled !== true) {\n      return undefined;\n    }\n    if (this._toolOutputRegistry == null) {\n      this._toolOutputRegistry = new ToolOutputReferenceRegistryClass({\n        maxOutputSize: this.toolOutputReferences.maxOutputSize,\n        maxTotalSize: this.toolOutputReferences.maxTotalSize,\n      });\n    }\n    return this._toolOutputRegistry;\n  }\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   * Streaming tool call buffer — accumulates raw arg strings during streaming\n   * so that truncated tool call content can be recovered by the ToolNode.\n   * Fed by handleToolCallChunks, consumed by ToolNode.run when args are incomplete.\n   */\n  streamingToolCallBuffer: StreamingToolCallBuffer =\n    new StreamingToolCallBuffer();\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.contentData = [];\n    this.contentIndexMap = new Map();\n    this.stepKeyIds = new Map();\n    this.toolCallStepIds.clear();\n    this.messageIdsByStepKey = new Map();\n    this.messageStepHasToolCalls = new Map();\n    this.prelimMessageIdsByStepKey = new Map();\n    this.invokedToolIds = undefined;\n    this.handlerRegistry = undefined;\n    this.sessions.clear();\n    this.streamingToolCallBuffer.clearAll();\n  }\n}\n\nexport class StandardGraph extends Graph<t.BaseGraphState, t.GraphNode> {\n  overrideModel?: t.ChatModel;\n  /** Optional compile options passed into workflow.compile() */\n  compileOptions?: t.CompileOptions | undefined;\n  messages: BaseMessage[] = [];\n  runId: string | undefined;\n  startIndex: number = 0;\n  signal?: AbortSignal;\n  /** Cached summary from the first prune in this run.\n   * Reused for subsequent prunes to avoid blocking LLM calls on every tool iteration. */\n  private _cachedRunSummary: string | undefined;\n  /** EMA-based pruning calibration state — smooths token budget adjustments across iterations */\n  private _pruneCalibration: PruneCalibrationState;\n  /** Run-scoped tool discovery cache — avoids re-parsing conversation history on every iteration */\n  private _toolDiscoveryCache: ToolDiscoveryCache;\n  /**\n   * SCALE: Tracks whether a summary call is already in-flight for this Graph instance.\n   * Prevents multiple concurrent summary LLM calls when rapid tool iterations each\n   * trigger pruning. At 2000 users with 3+ tool calls per turn, this prevents\n   * 6000+ summary calls/turn from becoming 2000.\n   */\n  private _summaryInFlight: boolean = false;\n  /** Messages accumulated across tool iterations while a summary call is in-flight */\n  private _pendingMessagesToRefine: BaseMessage[] = [];\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  /** Normalized finish/stop reason from the last LLM invocation */\n  lastFinishReason: string | undefined;\n\n  constructor({\n    // parent-level graph inputs\n    runId,\n    signal,\n    agents,\n    tokenCounter,\n    indexTokenCountMap,\n  }: t.StandardGraphInput) {\n    super();\n    this.runId = runId;\n    this.signal = signal;\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\n      this.agentContexts.set(agentConfig.agentId, agentContext);\n    }\n\n    this.defaultAgentId = agents[0].agentId;\n\n    // Seed cached summary from persisted storage so the first prune in a\n    // resumed conversation can also skip the synchronous LLM summarization call\n    const primaryContext = this.agentContexts.get(this.defaultAgentId);\n    if (primaryContext?.persistedSummary) {\n      this._cachedRunSummary = primaryContext.persistedSummary;\n    }\n\n    // Initialize EMA pruning calibration\n    this._pruneCalibration = createPruneCalibration();\n\n    // Initialize tool discovery cache, seeded with any pre-existing discoveries\n    this._toolDiscoveryCache = new ToolDiscoveryCache();\n    if (primaryContext?.discoveredToolNames.size) {\n      this._toolDiscoveryCache.seed([...primaryContext.discoveredToolNames]);\n    }\n  }\n\n  /* Init */\n\n  resetValues(keepContent?: boolean): void {\n    this.messages = [];\n    this.lastFinishReason = 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       * 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       * Gated by `keepContent` because HITL resume calls processStream a\n       * second time (`Command({resume})`) with `keepContent: true` to\n       * preserve the in-progress message's contentParts. The toolCallId →\n       * stepId map must survive the same boundary so that when LangGraph\n       * replays the interrupted ToolNode, `handleRunToolCompletions` can\n       * still resolve the resumed tool call's stepId and dispatch\n       * ON_RUN_STEP_COMPLETED with the tool's output. Without this guard,\n       * HITL tools (e.g. `ask_user`) lose their `output` field on every\n       * persisted message — the result is in the LLM context but never\n       * makes it into the saved tool_call entry.\n       */\n      this.toolCallStepIds.clear();\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.prelimMessageIdsByStepKey = resetIfNotEmpty(\n      this.prelimMessageIdsByStepKey,\n      new Map()\n    );\n    this.invokedToolIds = resetIfNotEmpty(this.invokedToolIds, undefined);\n    // Reset EMA calibration, tool discovery cache, and summary debounce for fresh run\n    this._pruneCalibration = createPruneCalibration();\n    this._toolDiscoveryCache.reset();\n    this._summaryInFlight = false;\n    this._pendingMessagesToRefine = [];\n    for (const context of this.agentContexts.values()) {\n      context.reset();\n    }\n  }\n\n  override clearHeavyState(): void {\n    super.clearHeavyState();\n    this.messages = [];\n    this.overrideModel = undefined;\n    for (const context of this.agentContexts.values()) {\n      context.reset();\n    }\n  }\n\n  /**\n   * Returns clientOptions with a reduced thinking budget for subsequent\n   * ReAct loop iterations (tool-result turns).\n   *\n   * **Rationale:** The first LLM call in a conversation processes the user's\n   * original query and may benefit from deep extended thinking. Subsequent\n   * iterations — where the model receives tool results and decides whether\n   * to call another tool or produce a final response — require minimal\n   * reasoning. Reducing the thinking budget from the user's configured\n   * value to TOOL_TURN_THINKING_BUDGET (1024 tokens) cuts wall-clock\n   * latency by ~15-20s per iteration, compounding across multi-tool flows.\n   *\n   * Provider handling:\n   * - **Anthropic (direct):** Reduces `thinking.budget_tokens` if > threshold\n   * - **Bedrock (Anthropic models):** Reduces `additionalModelRequestFields.thinking.budget_tokens`\n   * - **VertexAI / Google:** Reduces `thinkingConfig.thinkingBudget` if > threshold\n   * - **All others:** Returns clientOptions unchanged (no-op)\n   *\n   * @param clientOptions - The original client options from AgentContext\n   * @param provider - The LLM provider enum value\n   * @returns Shallow-cloned clientOptions with reduced thinking budget, or the original if no reduction needed\n   */\n  getAdaptiveClientOptions(\n    clientOptions: t.ClientOptions,\n    provider: Providers\n  ): t.ClientOptions {\n    if (provider === Providers.ANTHROPIC) {\n      const anthropicOpts = clientOptions as t.AnthropicClientOptions;\n      if (\n        anthropicOpts.thinking != null &&\n        typeof anthropicOpts.thinking === 'object' &&\n        'type' in anthropicOpts.thinking &&\n        (anthropicOpts.thinking.type === 'enabled' ||\n          anthropicOpts.thinking.type === 'adaptive') &&\n        'budget_tokens' in anthropicOpts.thinking &&\n        (anthropicOpts.thinking.budget_tokens as number) >\n          TOOL_TURN_THINKING_BUDGET\n      ) {\n        return {\n          ...anthropicOpts,\n          thinking: {\n            ...anthropicOpts.thinking,\n            budget_tokens: TOOL_TURN_THINKING_BUDGET,\n          },\n        } as t.AnthropicClientOptions;\n      }\n    }\n\n    if (provider === Providers.BEDROCK) {\n      const bedrockOpts = clientOptions as t.BedrockAnthropicClientOptions;\n      const thinkingField = bedrockOpts.additionalModelRequestFields?.thinking;\n      if (\n        thinkingField != null &&\n        typeof thinkingField === 'object' &&\n        'budget_tokens' in thinkingField &&\n        (thinkingField.budget_tokens as number) > TOOL_TURN_THINKING_BUDGET\n      ) {\n        return {\n          ...bedrockOpts,\n          additionalModelRequestFields: {\n            ...((bedrockOpts.additionalModelRequestFields ?? {}) as Record<\n              string,\n              unknown\n            >),\n            thinking: {\n              ...thinkingField,\n              budget_tokens: TOOL_TURN_THINKING_BUDGET,\n            },\n          },\n        } as t.BedrockAnthropicClientOptions;\n      }\n    }\n\n    if (provider === Providers.VERTEXAI || provider === Providers.GOOGLE) {\n      const googleOpts = clientOptions as t.GoogleClientOptions;\n      if (\n        googleOpts.thinkingConfig?.thinkingBudget != null &&\n        googleOpts.thinkingConfig.thinkingBudget > TOOL_TURN_THINKING_BUDGET\n      ) {\n        return {\n          ...googleOpts,\n          thinkingConfig: {\n            ...googleOpts.thinkingConfig,\n            thinkingBudget: TOOL_TURN_THINKING_BUDGET,\n          },\n        } as t.GoogleClientOptions;\n      }\n    }\n\n    return clientOptions;\n  }\n\n  /**\n   * Determines whether summarization should trigger based on SummarizationConfig.\n   *\n   * Supports three trigger strategies:\n   * - contextPercentage (default): Trigger when context utilization >= threshold%\n   * - messageCount: Trigger when pruned message count >= threshold\n   * - tokenThreshold: Trigger when total estimated tokens >= threshold\n   *\n   * When no config is provided, always triggers (preserves backward compatibility).\n   *\n   * @param prunedMessageCount - Number of messages that were pruned\n   * @param maxContextTokens - Maximum context token budget\n   * @param indexTokenCountMap - Token count map by message index\n   * @param instructionTokens - Token count for instructions/system message\n   * @param config - Optional SummarizationConfig\n   * @returns Whether summarization should be triggered\n   */\n  private shouldTriggerSummarization(\n    prunedMessageCount: number,\n    maxContextTokens: number,\n    indexTokenCountMap: Record<string, number | undefined>,\n    instructionTokens: number,\n    config?: t.SummarizationConfig\n  ): boolean {\n    // No pruned messages means nothing to summarize\n    if (prunedMessageCount === 0) {\n      return false;\n    }\n\n    // No config = backward compatible (always summarize when messages are pruned)\n    if (!config || !config.triggerType) {\n      return true;\n    }\n\n    const threshold = config.triggerThreshold;\n\n    switch (config.triggerType) {\n      case 'contextPercentage': {\n        if (maxContextTokens <= 0) return true;\n        const effectiveThreshold = threshold ?? SUMMARIZATION_CONTEXT_THRESHOLD;\n        let totalTokens = instructionTokens;\n        for (const key in indexTokenCountMap) {\n          totalTokens += indexTokenCountMap[key] ?? 0;\n        }\n        const utilization = (totalTokens / maxContextTokens) * 100;\n        return utilization >= effectiveThreshold;\n      }\n      case 'messageCount': {\n        const effectiveThreshold = threshold ?? 5;\n        return prunedMessageCount >= effectiveThreshold;\n      }\n      case 'tokenThreshold': {\n        if (threshold == null) return true;\n        let totalTokens = instructionTokens;\n        for (const key in indexTokenCountMap) {\n          totalTokens += indexTokenCountMap[key] ?? 0;\n        }\n        return totalTokens >= threshold;\n      }\n      default:\n        return true;\n    }\n  }\n\n  /**\n   * Returns the normalized finish/stop reason from the last LLM invocation.\n   * Used by callers to detect when the response was truncated due to max_tokens.\n   */\n  getLastFinishReason(): string | undefined {\n    return this.lastFinishReason;\n  }\n\n  /**\n   * Estimates a human-friendly description of the conversation timeframe based on message count.\n   * Uses rough heuristics to provide context about how much history is available.\n   *\n   * @param messageCount - Number of messages in the remaining context\n   * @returns A friendly description like \"the last few minutes\", \"the past hour\", etc.\n   */\n  getContextTimeframeDescription(messageCount: number): string {\n    // Rough heuristics based on typical conversation patterns:\n    // - Very active chat: ~20-30 messages per hour\n    // - Normal chat: ~10-15 messages per hour\n    // - Slow/thoughtful chat: ~5-8 messages per hour\n    // We use a middle estimate of ~12 messages per hour\n\n    if (messageCount <= 5) {\n      return 'just the last few exchanges';\n    } else if (messageCount <= 15) {\n      return 'the last several minutes';\n    } else if (messageCount <= 30) {\n      return 'roughly the past hour';\n    } else if (messageCount <= 60) {\n      return 'the past couple of hours';\n    } else if (messageCount <= 150) {\n      return 'the past few hours';\n    } else if (messageCount <= 300) {\n      return \"roughly a day's worth\";\n    } else if (messageCount <= 700) {\n      return 'the past few days';\n    } else {\n      return 'about a week or more';\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    }\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  getStepKey(metadata: Record<string, unknown> | undefined): string {\n    if (!metadata) return '';\n\n    const keyList = this.getKeyList(metadata);\n    if (this.checkKeyList(keyList)) {\n      /**\n       * Missing metadata fields can occur in child subgraphs invoked via\n       * subgraph.invoke() (e.g., handoff children). These don't have the\n       * full LangGraph metadata (checkpoint_ns, langgraph_node, etc.)\n       * because they run outside the parent graph's stream pipeline.\n       * Return a fallback key instead of throwing.\n       */\n      const available = keyList.filter((k) => k !== undefined);\n      if (available.length === 0) {\n        return '';\n      }\n      return joinKeys(available as (string | number)[]);\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 = [\n      metadata.run_id as string,\n      metadata.thread_id as string,\n      metadata.langgraph_node as string,\n      metadata.langgraph_step as number,\n      metadata.checkpoint_ns as string,\n    ];\n\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    if (this.invokedToolIds != null && this.invokedToolIds.size > 0) {\n      keyList.push(this.invokedToolIds.size + '');\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    const result = this.messages.slice(this.startIndex);\n    return result;\n  }\n\n  getContentParts(): t.MessageContentComplex[] | undefined {\n    return convertMessagesToContent(this.messages.slice(this.startIndex));\n  }\n\n  /**\n   * Get all run steps, optionally filtered by agent ID\n   */\n  getRunSteps(agentId?: string): t.RunStep[] {\n    if (agentId == null || agentId === '') {\n      return [...this.contentData];\n    }\n    return this.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  /**\n   * Get the context breakdown from the primary agent for admin token tracking.\n   * Returns detailed token counts for instructions, tools, etc.\n   */\n  getContextBreakdown(): {\n    instructions: number;\n    artifacts: number;\n    tools: number;\n    toolCount: number;\n    toolContext: number;\n    total: number;\n    toolsDetail: Array<{ name: string; tokens: number }>;\n    toolContextDetail: Array<{ name: string; tokens: number }>;\n  } | null {\n    const primaryContext = this.agentContexts.get(this.defaultAgentId);\n    if (!primaryContext) {\n      return null;\n    }\n    return primaryContext.getContextBreakdown();\n  }\n\n  /**\n   * Get the latest context analytics from the graph.\n   * Returns metrics like utilization %, TOON stats, message breakdown.\n   */\n  getContextAnalytics(): ContextAnalytics | null {\n    return this.lastContextAnalytics ?? null;\n  }\n\n  /** Store the latest context analytics for retrieval after run */\n  private lastContextAnalytics: ContextAnalytics | null = null;\n\n  /* Graph */\n\n  createSystemRunnable({\n    provider,\n    clientOptions,\n    instructions,\n    additional_instructions,\n  }: {\n    provider?: Providers;\n    clientOptions?: t.ClientOptions;\n    instructions?: string;\n    additional_instructions?: string;\n  }): t.SystemRunnable | undefined {\n    let finalInstructions: string | BaseMessageFields | undefined =\n      instructions;\n    if (additional_instructions != null && additional_instructions !== '') {\n      finalInstructions =\n        finalInstructions != null && finalInstructions\n          ? `${finalInstructions}\\n\\n${additional_instructions}`\n          : additional_instructions;\n    }\n\n    if (\n      finalInstructions != null &&\n      finalInstructions &&\n      provider === Providers.ANTHROPIC &&\n      (clientOptions as t.AnthropicClientOptions).promptCache === true\n    ) {\n      finalInstructions = {\n        content: [\n          {\n            type: 'text',\n            text: instructions,\n            cache_control: { type: 'ephemeral' },\n          },\n        ],\n      };\n    }\n\n    if (finalInstructions != null && finalInstructions !== '') {\n      const systemMessage = new SystemMessage(finalInstructions);\n      return RunnableLambda.from((messages: BaseMessage[]) => {\n        return [systemMessage, ...messages];\n      }).withConfig({ runName: 'prompt' });\n    }\n  }\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\n    // Extract HITL tool approval config from compile options (if configured)\n    const toolApprovalConfig = this.compileOptions?.toolApprovalConfig;\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      /**\n       * Include built-in tools (task, content, project, askUser, etc.) as direct tools.\n       * These have full instances and don't need on-demand loading via ON_TOOL_EXECUTE.\n       * Without this, event-driven mode would only have schema stubs + graph tools,\n       * causing \"Tool not found\" errors when the LLM calls any built-in tool.\n       */\n      const builtInTools = (currentTools as t.GenericTool[] | undefined) ?? [];\n      for (const tool of builtInTools) {\n        if ('name' in tool) {\n          allTools.push(tool);\n          allToolMap.set(tool.name, tool);\n          directToolNames.add(tool.name);\n        }\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      return new CustomToolNode<t.BaseGraphState>({\n        tools: allTools,\n        toolMap: allToolMap,\n        eventDrivenMode: true,\n        sessions: this.sessions,\n        toolDefinitions: toolDefMap,\n        agentId: agentContext?.agentId,\n        toolCallStepIds: this.toolCallStepIds,\n        toolRegistry: agentContext?.toolRegistry,\n        directToolNames: directToolNames.size > 0 ? directToolNames : undefined,\n        streamingToolCallBuffer: this.streamingToolCallBuffer,\n        errorHandler: (data, metadata) =>\n          StandardGraph.handleToolCallErrorStatic(this, data, metadata),\n        toolApprovalConfig,\n        hookRegistry: this.hookRegistry,\n        toolOutputRegistry: this.toolOutputRegistry,\n      });\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     * Build tool map from all sources: agent's toolMap, agent's tools array, and graph tools.\n     * Previously, baseTools were missing from the map when no explicit toolMap was provided,\n     * causing ToolNode to not find agent-defined tools (e.g., custom DynamicStructuredTools).\n     */\n    const traditionalToolMap =\n      graphTools && graphTools.length > 0\n        ? new Map([\n            ...(currentToolMap ?? new Map()),\n            ...baseTools\n              .filter((t): t is t.GenericTool & { name: string } => 'name' in t)\n              .map((t) => [t.name, t] as [string, t.GenericTool]),\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    /** Build directToolNames from graph-managed tools (handoff/transfer) so HITL can bypass them */\n    let directToolNames: Set<string> | undefined;\n    if (graphTools && graphTools.length > 0) {\n      directToolNames = new Set<string>();\n      for (const tool of graphTools) {\n        if ('name' in tool) {\n          directToolNames.add(tool.name);\n        }\n      }\n      if (directToolNames.size === 0) {\n        directToolNames = undefined;\n      }\n    }\n\n    return new CustomToolNode<t.BaseGraphState>({\n      tools: allTraditionalTools,\n      toolMap: traditionalToolMap,\n      toolCallStepIds: this.toolCallStepIds,\n      streamingToolCallBuffer: this.streamingToolCallBuffer,\n      errorHandler: (data, metadata) =>\n        StandardGraph.handleToolCallErrorStatic(this, data, metadata),\n      toolRegistry: agentContext?.toolRegistry,\n      sessions: this.sessions,\n      directToolNames,\n      toolApprovalConfig,\n      hookRegistry: this.hookRegistry,\n      toolOutputRegistry: this.toolOutputRegistry,\n    });\n  }\n\n  initializeModel({\n    provider,\n    tools,\n    clientOptions,\n  }: {\n    provider: Providers;\n    tools?: t.GraphTools;\n    clientOptions?: t.ClientOptions;\n  }): Runnable {\n    const ChatModelClass = getChatModelClass(provider);\n    const model = new ChatModelClass(clientOptions ?? {});\n\n    if (\n      isOpenAILike(provider) &&\n      (model instanceof ChatOpenAI || model instanceof AzureChatOpenAI)\n    ) {\n      model.temperature = (clientOptions as t.OpenAIClientOptions)\n        .temperature as number;\n      model.topP = (clientOptions as t.OpenAIClientOptions).topP as number;\n      model.frequencyPenalty = (clientOptions as t.OpenAIClientOptions)\n        .frequencyPenalty as number;\n      model.presencePenalty = (clientOptions as t.OpenAIClientOptions)\n        .presencePenalty as number;\n      model.n = (clientOptions as t.OpenAIClientOptions).n as number;\n    } else if (\n      provider === Providers.VERTEXAI &&\n      model instanceof ChatVertexAI\n    ) {\n      model.temperature = (clientOptions as t.VertexAIClientOptions)\n        .temperature as number;\n      model.topP = (clientOptions as t.VertexAIClientOptions).topP as number;\n      model.topK = (clientOptions as t.VertexAIClientOptions).topK as number;\n      model.topLogprobs = (clientOptions as t.VertexAIClientOptions)\n        .topLogprobs as number;\n      model.frequencyPenalty = (clientOptions as t.VertexAIClientOptions)\n        .frequencyPenalty as number;\n      model.presencePenalty = (clientOptions as t.VertexAIClientOptions)\n        .presencePenalty as number;\n      model.maxOutputTokens = (clientOptions as t.VertexAIClientOptions)\n        .maxOutputTokens as number;\n    }\n\n    if (!tools || tools.length === 0) {\n      return model as unknown as Runnable;\n    }\n\n    return (model as t.ModelWithTools).bindTools(tools);\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  getNewModel({\n    provider,\n    clientOptions,\n  }: {\n    provider: Providers;\n    clientOptions?: t.ClientOptions;\n  }): t.ChatModelInstance {\n    const ChatModelClass = getChatModelClass(provider);\n    return new ChatModelClass(clientOptions ?? {});\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  /** Execute model invocation with streaming support */\n  private async attemptInvoke(\n    {\n      currentModel,\n      finalMessages,\n      provider,\n      tools: _tools,\n    }: {\n      currentModel?: t.ChatModel;\n      finalMessages: BaseMessage[];\n      provider: Providers;\n      tools?: t.GraphTools;\n    },\n    config?: RunnableConfig\n  ): Promise<Partial<t.BaseGraphState>> {\n    const model = this.overrideModel ?? currentModel;\n    if (!model) {\n      throw new Error('No model found');\n    }\n\n    /**\n     * Lazy tool-output reference annotation (upstream PR #117). Right\n     * before the message array hits the provider, walk it and apply\n     * `[ref: tool<i>turn<n>]` prefixes / `_ref` JSON fields to a\n     * transient copy. The persisted ToolMessages stay clean — only what\n     * the LLM sees gets the annotation, and only when the registry\n     * actually has the referenced output. No-op when the registry is\n     * absent (the common case until a host opts in).\n     */\n    const annotatedRunId = (\n      config?.configurable as { run_id?: string } | undefined\n    )?.run_id;\n    finalMessages = annotateMessagesForLLM(\n      finalMessages,\n      this.toolOutputRegistry,\n      annotatedRunId\n    );\n\n    if (model.stream) {\n      /**\n       * Process all model output through a local ChatModelStreamHandler in the\n       * graph execution context. Each chunk is awaited before the next one is\n       * consumed, so by the time the stream is exhausted every run step\n       * (MESSAGE_CREATION, TOOL_CALLS) has been created and toolCallStepIds is\n       * fully populated — the graph will not transition to ToolNode until this\n       * is done.\n       *\n       * This replaces the previous pattern where ChatModelStreamHandler lived\n       * in the for-await stream consumer (handler registry). That consumer\n       * runs concurrently with graph execution, so the graph could advance to\n       * ToolNode before the consumer had processed all events. By handling\n       * chunks here, inside the agent node, the race is eliminated.\n       *\n       * The for-await consumer no longer needs a ChatModelStreamHandler; its\n       * on_chat_model_stream events are simply ignored (no handler registered).\n       * The dispatched custom events (ON_RUN_STEP, ON_MESSAGE_DELTA, etc.)\n       * still reach the content aggregator and SSE handlers through the custom\n       * event callback in Run.createCustomEventCallback.\n       */\n      const metadata = config?.metadata as Record<string, unknown> | undefined;\n      const streamHandler = new ChatModelStreamHandler();\n      const stream = await model.stream(finalMessages, config);\n      let finalChunk: AIMessageChunk | undefined;\n      for await (const chunk of stream) {\n        await streamHandler.handle(\n          GraphEvents.CHAT_MODEL_STREAM,\n          { chunk },\n          metadata,\n          this\n        );\n        finalChunk = finalChunk ? concat(finalChunk, chunk) : chunk;\n      }\n\n      if (manualToolStreamProviders.has(provider)) {\n        finalChunk = modifyDeltaProperties(provider, finalChunk);\n      }\n\n      if ((finalChunk?.tool_calls?.length ?? 0) > 0) {\n        finalChunk!.tool_calls = finalChunk!.tool_calls?.filter(\n          (tool_call: ToolCall) => !!tool_call.name\n        );\n      }\n\n      return { messages: [finalChunk as AIMessageChunk] };\n    } else {\n      /** Fallback for models without stream support. */\n      const finalMessage = await model.invoke(finalMessages, config);\n      if ((finalMessage.tool_calls?.length ?? 0) > 0) {\n        finalMessage.tool_calls = finalMessage.tool_calls?.filter(\n          (tool_call: ToolCall) => !!tool_call.name\n        );\n      }\n      return { messages: [finalMessage] };\n    }\n  }\n\n  /**\n   * Execute model invocation with structured output.\n   * Uses native constrained decoding (jsonSchema method) for supported providers,\n   * or falls back to withStructuredOutput with functionCalling/jsonMode.\n   *\n   * Native mode uses provider APIs directly:\n   * - Anthropic: output_config.format via LangChain's method: 'json_schema'\n   * - OpenAI/Azure: response_format.json_schema via LangChain's method: 'jsonSchema'\n   * - Bedrock: falls back to functionCalling (LangChain doesn't support native yet)\n   */\n  private async attemptStructuredInvoke(\n    {\n      currentModel,\n      finalMessages,\n      schema,\n      structuredOutputConfig,\n      provider,\n      agentContext,\n    }: {\n      currentModel: t.ChatModelInstance;\n      finalMessages: BaseMessage[];\n      schema: Record<string, unknown>;\n      structuredOutputConfig: t.StructuredOutputConfig;\n      provider?: Providers;\n      agentContext?: AgentContext;\n    },\n    config?: RunnableConfig\n  ): Promise<{\n    structuredResponse: Record<string, unknown>;\n    rawMessage?: AIMessageChunk;\n  }> {\n    const model = this.overrideModel ?? currentModel;\n\n    // Check if model supports withStructuredOutput\n    // eslint-disable-next-line @typescript-eslint/no-explicit-any\n    if (typeof (model as any).withStructuredOutput !== 'function') {\n      throw new Error(\n        'The selected model does not support structured output. ' +\n          'Please use a model that supports JSON schema output (e.g., OpenAI GPT-4, Anthropic Claude, Google Gemini) ' +\n          'or disable structured output for this agent.'\n      );\n    }\n\n    const {\n      name = 'StructuredResponse',\n      includeRaw: _includeRaw = false,\n      handleErrors = true,\n      maxRetries = 2,\n    } = structuredOutputConfig;\n\n    // Resolve the structured output method using AgentContext's provider-aware logic\n    let method: t.ResolvedStructuredOutputMethod;\n    if (agentContext) {\n      const resolved = agentContext.resolveStructuredOutputMode();\n      method = resolved.method;\n      if (resolved.warnings.length > 0) {\n        mwarn('[Graph] Structured output mode warnings:', resolved.warnings);\n      }\n    } else {\n      // Legacy fallback: use the old mode-based resolution\n      const mode = structuredOutputConfig.mode ?? 'auto';\n      if (mode === 'tool') {\n        method = 'functionCalling';\n      } else if (mode === 'provider') {\n        method =\n          provider === Providers.BEDROCK ? 'functionCalling' : 'jsonMode';\n      } else {\n        method = undefined;\n      }\n    }\n\n    // Prepare schema for provider-specific constraints when using native/jsonSchema mode\n    let preparedSchema = schema;\n    if (method === 'jsonSchema' && provider != null) {\n      const { schema: prepared, warnings } = prepareSchemaForProvider(\n        schema,\n        provider,\n        structuredOutputConfig.strict !== false\n      );\n      preparedSchema = prepared;\n      if (warnings.length > 0) {\n        mwarn('[Graph] Schema preparation warnings:', warnings);\n      }\n    }\n\n    // Use withStructuredOutput to bind the schema\n    // Always use includeRaw: true internally so we can debug what's returned\n    // eslint-disable-next-line @typescript-eslint/no-explicit-any\n    const structuredModel = (model as any).withStructuredOutput(\n      preparedSchema,\n      {\n        name,\n        method: method === 'native' ? undefined : method,\n        includeRaw: true, // Always true internally for debugging\n        strict: structuredOutputConfig.strict !== false,\n      }\n    );\n\n    let lastError: Error | undefined;\n    let attempts = 0;\n\n    while (attempts <= maxRetries) {\n      try {\n        // Note: We pass the original config here. The stream aggregator will filter out\n        // the synthetic \"response\" tool call events from withStructuredOutput()\n        const result = await structuredModel.invoke(finalMessages, config);\n\n        // Check for refusal or truncation in the raw message\n        if (result?.raw != null) {\n          const rawMsg = result.raw as AIMessageChunk;\n\n          // Check stop reason for refusal or truncation\n          const responseMetadata = rawMsg.response_metadata;\n          const stopReason =\n            responseMetadata.stop_reason ?? // Anthropic\n            responseMetadata.finish_reason ?? // OpenAI\n            responseMetadata.stopReason; // Bedrock\n\n          if (stopReason === 'max_tokens' || stopReason === 'length') {\n            throw new StructuredOutputTruncatedError(stopReason);\n          }\n\n          // Check for Anthropic refusal (stop_reason won't be 'refusal' but content may indicate it)\n          // OpenAI uses message.refusal field\n          const refusal = (rawMsg as AIMessageChunk & { refusal?: string })\n            .refusal;\n          if (refusal != null && refusal !== '') {\n            throw new StructuredOutputRefusalError(refusal);\n          }\n        }\n\n        // Handle response - we always use includeRaw internally\n        if (result?.raw != null && result?.parsed !== undefined) {\n          return {\n            structuredResponse: result.parsed as Record<string, unknown>,\n            rawMessage: result.raw as AIMessageChunk,\n          };\n        }\n\n        // Fallback for models that don't support includeRaw\n        return {\n          structuredResponse: result as Record<string, unknown>,\n        };\n      } catch (error) {\n        // Don't retry on refusal or truncation errors — they need user action\n        if (\n          error instanceof StructuredOutputRefusalError ||\n          error instanceof StructuredOutputTruncatedError\n        ) {\n          throw error;\n        }\n\n        lastError = error as Error;\n        attempts++;\n\n        // If error handling is disabled, throw immediately\n        if (handleErrors === false) {\n          throw error;\n        }\n\n        // If we've exhausted retries, throw\n        if (attempts > maxRetries) {\n          throw new Error(\n            `Structured output failed after ${maxRetries + 1} attempts: ${lastError.message}`\n          );\n        }\n\n        // Add error message to conversation for retry\n        const errorMessage =\n          typeof handleErrors === 'string'\n            ? handleErrors\n            : `The response did not match the expected schema. Error: ${lastError.message}. Please try again with a valid response.`;\n\n        mwarn(\n          `[Graph] Structured output attempt ${attempts} failed: ${lastError.message}. Retrying...`\n        );\n\n        // Add the error as a human message for context\n        finalMessages = [\n          ...finalMessages,\n          new HumanMessage({\n            content: `[VALIDATION ERROR]\\n${errorMessage}`,\n          }),\n        ];\n      }\n    }\n\n    throw lastError ?? new Error('Structured output failed');\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   * Perform structured output invocation: creates a fresh model without tools bound,\n   * removes thinking configuration, invokes with the schema, emits the event,\n   * and returns a clean AIMessageChunk without tool_calls.\n   *\n   * Used by both the immediate path (no tools) and the deferred path (after tool use).\n   */\n  private async performStructuredOutput({\n    agentContext,\n    finalMessages,\n    config,\n  }: {\n    agentContext: AgentContext;\n    finalMessages: BaseMessage[];\n    config: RunnableConfig;\n  }): Promise<Partial<t.BaseGraphState>> {\n    const schema = agentContext.getStructuredOutputSchema();\n    if (!schema) {\n      throw new Error('Structured output schema is not configured');\n    }\n\n    // Get a fresh model WITHOUT tools bound\n    // bindTools() returns RunnableBinding which lacks withStructuredOutput\n    // Also disable thinking mode - Anthropic/Bedrock doesn't allow tool_choice with thinking enabled\n    const structuredClientOptions = {\n      ...agentContext.clientOptions,\n    } as t.ClientOptions;\n\n    // Determine if streaming is possible for this structured output mode\n    // Native/jsonSchema modes can stream; tool/functionCalling modes cannot (synthetic tool calls break UX)\n    const resolved = agentContext.resolveStructuredOutputMode();\n    const canStream =\n      resolved.method === 'jsonSchema' || resolved.method === 'jsonMode';\n    if (!canStream) {\n      // Disable streaming for function calling mode (synthetic tool calls break streaming UX)\n      // eslint-disable-next-line @typescript-eslint/no-explicit-any\n      (structuredClientOptions as any).streaming = false;\n    }\n\n    // For native/jsonSchema mode, Anthropic's constrained decoding works with thinking enabled\n    // (grammar only applies to final output, not thinking blocks). For function calling mode,\n    // thinking must be disabled because forced tool_choice is incompatible with thinking.\n    const needsThinkingDisabled = resolved.method !== 'jsonSchema';\n\n    if (needsThinkingDisabled) {\n      // Remove thinking configuration for Bedrock\n      if (agentContext.provider === Providers.BEDROCK) {\n        const bedrockOpts =\n          structuredClientOptions as t.BedrockAnthropicClientOptions;\n        if (bedrockOpts.additionalModelRequestFields != null) {\n          const additionalFields = Object.assign(\n            {},\n            bedrockOpts.additionalModelRequestFields\n          ) as Record<string, unknown>;\n          delete additionalFields.thinking;\n          delete additionalFields.budgetTokens;\n          bedrockOpts.additionalModelRequestFields =\n            additionalFields as t.BedrockAnthropicInput['additionalModelRequestFields'];\n        }\n      }\n\n      // Remove thinking configuration for Anthropic direct API\n      if (agentContext.provider === Providers.ANTHROPIC) {\n        const anthropicOpts =\n          structuredClientOptions as t.AnthropicClientOptions;\n        if (anthropicOpts.thinking) {\n          delete anthropicOpts.thinking;\n        }\n      }\n    }\n\n    const structuredModel = this.getNewModel({\n      provider: agentContext.provider,\n      clientOptions: structuredClientOptions,\n    });\n\n    const { structuredResponse, rawMessage } =\n      await this.attemptStructuredInvoke(\n        {\n          currentModel: structuredModel,\n          finalMessages,\n          schema,\n          structuredOutputConfig: agentContext.structuredOutput!,\n          provider: agentContext.provider,\n          agentContext,\n        },\n        config\n      );\n\n    // Emit structured output event\n    await safeDispatchCustomEvent(\n      GraphEvents.ON_STRUCTURED_OUTPUT,\n      {\n        structuredResponse,\n        schema,\n        raw: rawMessage,\n      },\n      config\n    );\n\n    // Create a clean message WITHOUT tool_calls for structured output.\n    // The rawMessage contains a tool_call for the structured output schema (e.g., \"response\"),\n    // which would cause the graph router to send it to the tool node.\n    // We return a clean AI message that ends the graph.\n    let cleanMessage: AIMessageChunk | undefined;\n    if (rawMessage) {\n      cleanMessage = new AIMessageChunk({\n        content: JSON.stringify(structuredResponse, null, 2),\n        id: rawMessage.id,\n        response_metadata: rawMessage.response_metadata,\n        usage_metadata: rawMessage.usage_metadata,\n      });\n    }\n\n    return {\n      messages: cleanMessage ? [cleanMessage] : [],\n      structuredResponse,\n    };\n  }\n\n  createCallModel(agentId = 'default') {\n    return async (\n      state: t.BaseGraphState,\n      config?: RunnableConfig\n    ): Promise<Partial<t.BaseGraphState>> => {\n      /**\n       * Get agent context - it must exist by this point\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      let { messages } = state;\n\n      // CACHE OPTIMIZATION: Inject dynamicContext as a HumanMessage at the start of conversation\n      // This keeps the system message static (cacheable) while providing dynamic context\n      // (timestamps, user info, tool context) as conversation content instead.\n      // Only inject on the first turn when messages don't already have the context marker.\n      if (\n        agentContext.dynamicContext != null &&\n        agentContext.dynamicContext !== '' &&\n        messages.length > 0 &&\n        !messages.some(\n          (m) =>\n            m instanceof HumanMessage &&\n            typeof m.content === 'string' &&\n            m.content.startsWith('[SESSION_CONTEXT]')\n        )\n      ) {\n        const dynamicContextMessage = new HumanMessage({\n          content: `[SESSION_CONTEXT]\\n${agentContext.dynamicContext}`,\n        });\n        const ackMessage = new AIMessageChunk({\n          content:\n            'Understood. I have noted the session context including the current date/time (CST) and will apply it appropriately.',\n        });\n        messages = [dynamicContextMessage, ackMessage, ...messages];\n      }\n\n      // Tool discovery caching: only scan new messages since last iteration\n      // instead of re-parsing the full history via extractToolDiscoveries()\n      const cachedDiscoveries =\n        this._toolDiscoveryCache.getNewDiscoveries(messages);\n      if (cachedDiscoveries.length > 0) {\n        agentContext.markToolsAsDiscovered(cachedDiscoveries);\n        mlog(\n          `[Graph:ToolDiscovery] Cached ${cachedDiscoveries.length} new tools (total: ${this._toolDiscoveryCache.size})`\n        );\n      }\n\n      const toolsForBinding = agentContext.getToolsForBinding();\n\n      // PERF: Detect subsequent ReAct iterations (tool results present in messages)\n      // and reduce thinking budget to minimize per-iteration latency.\n      // First iteration gets the user's configured budget; follow-up turns\n      // use TOOL_TURN_THINKING_BUDGET (1024) since they only need to route\n      // \"call next tool\" or \"produce final response\".\n      const isSubsequentIteration = messages.some(\n        (m) => m._getType() === 'tool'\n      );\n      const effectiveClientOptions =\n        isSubsequentIteration && agentContext.clientOptions\n          ? this.getAdaptiveClientOptions(\n              agentContext.clientOptions,\n              agentContext.provider\n            )\n          : agentContext.clientOptions;\n      let model =\n        this.overrideModel ??\n        this.initializeModel({\n          tools: toolsForBinding,\n          provider: agentContext.provider,\n          clientOptions: effectiveClientOptions,\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      // First-writer-wins: `this.config` is used ONLY as a \"has a run started\"\n      // existence flag by the dispatch* methods (they never read its value —\n      // they read the current RunnableConfig from LangChain AsyncLocalStorage).\n      // Unconditionally reassigning here races across concurrent child\n      // subgraph.invoke() calls under parallel multi-agent handoffs; the last\n      // writer wins, and any dispatch firing between writes would historically\n      // have been tagged with the wrong child's metadata. Keeping the first\n      // write pinned makes this a true flag, eliminating the race.\n      this.config ??= config;\n\n      let messagesToUse = messages;\n\n      // ====================================================================\n      // PRE-PRUNING DELEGATION CHECK\n      // ====================================================================\n      // Context management is now fully mechanical:\n      // - Pruning always runs when needed (no delegation-based skip)\n      // - Auto-continuation in client.js handles max_tokens finish reason\n      // - LLM never sees raw token numbers (prevents voluntary bail-out)\n      // ====================================================================\n\n      if (\n        !agentContext.pruneMessages &&\n        agentContext.tokenCounter &&\n        agentContext.maxContextTokens != null &&\n        agentContext.indexTokenCountMap[0] != null\n      ) {\n        const isAnthropicWithThinking =\n          (agentContext.provider === Providers.ANTHROPIC &&\n            (agentContext.clientOptions as t.AnthropicClientOptions).thinking !=\n              null) ||\n          (agentContext.provider === Providers.BEDROCK &&\n            (agentContext.clientOptions as t.BedrockAnthropicInput)\n              .additionalModelRequestFields?.['thinking'] != null) ||\n          (agentContext.provider === Providers.OPENAI &&\n            (\n              (agentContext.clientOptions as t.OpenAIClientOptions).modelKwargs\n                ?.thinking as t.AnthropicClientOptions['thinking']\n            )?.type === 'enabled');\n\n        // Apply EMA calibration to max token budget — smooths pruning across iterations\n        const calibratedMaxTokens = applyCalibration(\n          agentContext.maxContextTokens,\n          this._pruneCalibration\n        );\n\n        agentContext.pruneMessages = createPruneMessages({\n          startIndex: this.startIndex,\n          provider: agentContext.provider,\n          tokenCounter: agentContext.tokenCounter,\n          maxTokens: calibratedMaxTokens,\n          thinkingEnabled: isAnthropicWithThinking,\n          indexTokenCountMap: agentContext.indexTokenCountMap,\n        });\n      }\n\n      // Update EMA calibration with actual token usage from API response\n      if (\n        agentContext.currentUsage?.input_tokens &&\n        agentContext.maxContextTokens\n      ) {\n        const estimatedTokens = Object.values(\n          agentContext.indexTokenCountMap\n        ).reduce((sum, v) => (sum ?? 0) + (v ?? 0), 0) as number;\n        if (estimatedTokens > 0) {\n          this._pruneCalibration = updatePruneCalibration(\n            this._pruneCalibration,\n            agentContext.currentUsage.input_tokens,\n            estimatedTokens\n          );\n        }\n      }\n\n      // ── Proactive summarization at context pressure ───────────────────\n      // Inspired by VS Code Copilot Chat's 3-tier strategy:\n      //   80% → fire proactive background summary (BEFORE pruning needed)\n      //   90% → pruning kicks in (summary already cached from 80% trigger)\n      //  100% → graceful: use existing summary + recent messages, NEVER block\n      //\n      // This ensures the summary is READY by the time pruning actually occurs,\n      // so the user never waits and never sees a context cliff.\n      if (\n        agentContext.maxContextTokens != null &&\n        agentContext.maxContextTokens > 0 &&\n        agentContext.summarizeCallback &&\n        !this._summaryInFlight &&\n        !this._cachedRunSummary\n      ) {\n        const utilization = getContextUtilization(\n          agentContext.indexTokenCountMap,\n          agentContext.instructionTokens,\n          agentContext.maxContextTokens\n        );\n        const threshold =\n          agentContext.summarizationConfig?.triggerThreshold ??\n          PROACTIVE_SUMMARY_THRESHOLD * 100;\n\n        if (utilization >= threshold) {\n          // Identify older messages to summarize proactively.\n          // Keep the last N messages (recent turns) intact — only summarize older history.\n          // This is incremental: the callback checks for existing summary and updates it.\n          const recentTurnCount = Math.max(\n            4,\n            Math.floor(messages.length * 0.3)\n          );\n          const oldMessages = messages.slice(\n            messages[0]?.getType() === 'system' ? 1 : 0,\n            Math.max(1, messages.length - recentTurnCount)\n          );\n\n          if (oldMessages.length > 0) {\n            this._summaryInFlight = true;\n            mlog(\n              `[Graph:ProactiveSummary] Context at ${utilization.toFixed(1)}% (threshold ${threshold}%) — summarizing ${oldMessages.length} older msgs in background`\n            );\n\n            /**\n             * Fire PreCompact (#103) before the LLM call. Observational —\n             * hosts may use the input to schedule auxiliary work, but a\n             * deny/ask decision does NOT block compaction here because\n             * Ranger's summarizer runs in the background and a refusal\n             * has nowhere to go: pruning still needs to happen at 100%\n             * regardless. Errors are swallowed so a hook bug cannot\n             * masquerade as a context-overflow failure.\n             */\n            const sessionId = this.runId ?? '';\n            const preCompactPromise =\n              this.hookRegistry?.hasHookFor('PreCompact', sessionId) === true\n                ? executeHooks({\n                    registry: this.hookRegistry,\n                    input: {\n                      hook_event_name: 'PreCompact',\n                      runId: sessionId,\n                      agentId: agentContext.agentId,\n                      messagesBeforeCount: oldMessages.length,\n                      trigger:\n                        agentContext.summarizationConfig?.trigger?.type ??\n                        agentContext.summarizationConfig?.triggerType ??\n                        'default',\n                    },\n                    sessionId,\n                  }).catch(() => undefined)\n                : Promise.resolve(undefined);\n\n            preCompactPromise\n              .then(() => agentContext.summarizeCallback!(oldMessages))\n              .then((updated) => {\n                if (updated != null && updated !== '') {\n                  this._cachedRunSummary = updated;\n                  mlog(\n                    `[Graph:ProactiveSummary] Background summary ready (len=${updated.length})`\n                  );\n                  if (\n                    this.hookRegistry?.hasHookFor('PostCompact', sessionId) ===\n                    true\n                  ) {\n                    void executeHooks({\n                      registry: this.hookRegistry,\n                      input: {\n                        hook_event_name: 'PostCompact',\n                        runId: sessionId,\n                        agentId: agentContext.agentId,\n                        summary: updated,\n                        messagesAfterCount: 0,\n                      },\n                      sessionId,\n                    }).catch(() => {\n                      /* PostCompact is observational — swallow errors */\n                    });\n                  }\n                }\n              })\n              .catch((err) => {\n                console.error(\n                  '[Graph:ProactiveSummary] Background summary failed (non-fatal):',\n                  err\n                );\n              })\n              .finally(() => {\n                this._summaryInFlight = false;\n              });\n          }\n        }\n      }\n\n      if (agentContext.pruneMessages) {\n        // ── Context Compaction (Copilot-style: never delete messages) ─────\n        //\n        // DESIGN: Original messages are NEVER removed from the array.\n        // Instead, we build a \"windowed view\" for the LLM:\n        //   [system prompt] + [summary of older turns] + [recent turns that fit]\n        //\n        // This ensures:\n        //   - No context is ever lost (summary covers older turns)\n        //   - We can always re-summarize from originals if summary is stale\n        //   - Conversation chaining works naturally across turns\n        //\n        // Flow:\n        //   1. Resolve best available summary (cached > persisted > seed)\n        //   2. Calculate token budget available for recent messages\n        //   3. Walk newest→oldest, build view of messages that fit\n        //   4. Assemble: [system] + [summary] + [recent window]\n        //   5. Fire background summary update for messages outside the window\n\n        const sumConfig = agentContext.summarizationConfig;\n        const tokenCounter = agentContext.tokenCounter;\n        const maxTokens = agentContext.maxContextTokens ?? 0;\n\n        // Step 1: Resolve best available summary\n        let summary: string | undefined;\n\n        if (this._cachedRunSummary != null) {\n          summary = this._cachedRunSummary;\n        } else if (\n          agentContext.persistedSummary != null &&\n          agentContext.persistedSummary !== ''\n        ) {\n          summary = agentContext.persistedSummary;\n          this._cachedRunSummary = summary;\n        } else if (\n          sumConfig?.initialSummary != null &&\n          sumConfig.initialSummary !== ''\n        ) {\n          summary = sumConfig.initialSummary;\n          this._cachedRunSummary = summary;\n        }\n\n        // Step 2: Calculate token budget\n        // Apply EMA calibration for accuracy across iterations\n        const calibratedMax = applyCalibration(\n          maxTokens,\n          this._pruneCalibration\n        );\n        const systemMsg =\n          messages[0]?.getType() === 'system' ? messages[0] : null;\n        const systemTokens =\n          systemMsg != null ? (agentContext.indexTokenCountMap[0] ?? 0) : 0;\n        const summaryMsg =\n          summary != null && summary !== ''\n            ? new SystemMessage(`[Conversation Summary]\\n${summary}`)\n            : null;\n        const summaryTokens =\n          summaryMsg != null && tokenCounter != null\n            ? tokenCounter(summaryMsg)\n            : 0;\n\n        // Budget for recent messages = total - system - summary - 3 (assistant priming)\n        const recentBudget = calibratedMax - systemTokens - summaryTokens - 3;\n\n        // Step 3: Determine window of recent messages to include.\n        //\n        // Two modes:\n        // A) No summary available → fill the budget (all messages that fit)\n        // B) Summary available → keep last 2 conversation rounds (H+A pairs)\n        //    + any trailing tool messages. The summary covers everything else.\n        //    This avoids wasting tokens on raw messages the summary already covers.\n        //\n        // A \"round\" = one human message + one AI response (+ any tool messages between).\n        const contentStart = systemMsg != null ? 1 : 0;\n        let usedTokens = 0;\n        let windowStart = messages.length; // index where the recent window begins\n        let fileManifestTokens = 0; // populated in Step 4 if file manifest is injected\n\n        if (summary == null || summary === '') {\n          // Mode A: No summary — include as many recent messages as fit in budget\n          for (let i = messages.length - 1; i >= contentStart; i--) {\n            const msgTokens = agentContext.indexTokenCountMap[i] ?? 0;\n            if (usedTokens + msgTokens > recentBudget) {\n              break;\n            }\n            usedTokens += msgTokens;\n            windowStart = i;\n          }\n        } else {\n          // Mode B: Summary exists — keep last 2 rounds (4 core messages: H+A+H+A)\n          // Walk backward counting human messages as round boundaries.\n          const MAX_RECENT_ROUNDS = COMPACTION_RECENT_ROUNDS;\n          let roundsSeen = 0;\n          for (let i = messages.length - 1; i >= contentStart; i--) {\n            const msgType = messages[i]?.getType();\n            const msgTokens = agentContext.indexTokenCountMap[i] ?? 0;\n\n            // Budget guard — even in round-limited mode, don't exceed budget\n            if (usedTokens + msgTokens > recentBudget) {\n              break;\n            }\n            usedTokens += msgTokens;\n            windowStart = i;\n\n            // Count a human message as a round boundary\n            if (msgType === 'human') {\n              roundsSeen++;\n              if (roundsSeen >= MAX_RECENT_ROUNDS) {\n                break;\n              }\n            }\n          }\n        }\n\n        // Ensure we don't split tool-call / tool-result pairs.\n        // If windowStart lands on a ToolMessage, walk back to include its AI message.\n        while (\n          windowStart > contentStart &&\n          messages[windowStart]?.getType() === 'tool'\n        ) {\n          windowStart--;\n          usedTokens += agentContext.indexTokenCountMap[windowStart] ?? 0;\n        }\n\n        const recentMessages = messages.slice(windowStart);\n        const compactedMessages = messages.slice(contentStart, windowStart);\n        const hasSummary = summaryMsg != null;\n\n        // Step 4: Assemble the windowed view\n        // [system] + [summary] + [file manifest] + [recent window]\n        //\n        // File manifest is injected ONLY when compaction is active (messages behind summary).\n        // It provides the LLM with awareness of all conversation files so it can\n        // retrieve content on demand via file_search or content_tool read.\n        const viewParts: BaseMessage[] = [];\n        if (systemMsg != null) {\n          viewParts.push(systemMsg);\n        }\n        if (summaryMsg != null) {\n          viewParts.push(summaryMsg);\n        }\n\n        // Inject file manifest when files exist and messages are being compacted\n        const fileManifest = agentContext.fileManifest;\n        if (\n          fileManifest &&\n          fileManifest.length > 0 &&\n          compactedMessages.length > 0\n        ) {\n          const manifestBlock = buildFileManifestBlock(fileManifest);\n          if (manifestBlock) {\n            const manifestMsg = new SystemMessage(manifestBlock);\n            viewParts.push(manifestMsg);\n            // Account for manifest tokens in the view token map\n            const manifestTokens =\n              tokenCounter != null ? tokenCounter(manifestMsg) : 0;\n            // Will be inserted at the correct index when rebuilding viewTokenMap below\n            fileManifestTokens = manifestTokens;\n          }\n        }\n\n        viewParts.push(...recentMessages);\n        messagesToUse = viewParts;\n\n        // Rebuild indexTokenCountMap for the windowed view so downstream\n        // analytics and summarization triggers see accurate token counts.\n        const viewTokenMap: Record<string, number | undefined> = {};\n        let viewIdx = 0;\n        if (systemMsg != null) {\n          viewTokenMap[viewIdx] = systemTokens;\n          viewIdx++;\n        }\n        if (summaryMsg != null) {\n          viewTokenMap[viewIdx] = summaryTokens;\n          viewIdx++;\n        }\n        if (fileManifestTokens > 0) {\n          viewTokenMap[viewIdx] = fileManifestTokens;\n          viewIdx++;\n        }\n        for (let i = windowStart; i < messages.length; i++) {\n          viewTokenMap[viewIdx] = agentContext.indexTokenCountMap[i];\n          viewIdx++;\n        }\n        agentContext.indexTokenCountMap = viewTokenMap;\n\n        // Step 5: Fire background summary update (non-blocking)\n        // Summarize messages outside the window so next iteration has a fresh summary.\n        // Only trigger if there are compacted messages worth summarizing.\n        if (compactedMessages.length > 0 && agentContext.summarizeCallback) {\n          const shouldSummarize = this.shouldTriggerSummarization(\n            compactedMessages.length,\n            maxTokens,\n            agentContext.indexTokenCountMap,\n            agentContext.instructionTokens,\n            sumConfig\n          );\n\n          if (shouldSummarize) {\n            if (this._summaryInFlight) {\n              this._pendingMessagesToRefine.push(...compactedMessages);\n              mlog(\n                `[Graph:Compaction] Summary in-flight, queued ${compactedMessages.length} msgs (pending=${this._pendingMessagesToRefine.length})`\n              );\n            } else {\n              this._summaryInFlight = true;\n              const allMessages =\n                this._pendingMessagesToRefine.length > 0\n                  ? [...this._pendingMessagesToRefine, ...compactedMessages]\n                  : compactedMessages;\n              this._pendingMessagesToRefine = [];\n\n              agentContext\n                .summarizeCallback(allMessages)\n                .then((updated) => {\n                  if (updated != null && updated !== '') {\n                    this._cachedRunSummary = updated;\n                  }\n                })\n                .catch((err) => {\n                  console.error(\n                    '[Graph:Compaction] Background summary update failed (non-fatal):',\n                    err\n                  );\n                })\n                .finally(() => {\n                  this._summaryInFlight = false;\n                });\n            }\n          }\n        }\n\n        // Post-compaction context note for task-tool-enabled agents\n        if (compactedMessages.length > 0 && hasTaskTool(agentContext.tools)) {\n          const postPruneNote = buildPostPruneNote(\n            compactedMessages.length,\n            hasSummary\n          );\n          if (postPruneNote) {\n            messagesToUse = [\n              ...messagesToUse,\n              new SystemMessage(postPruneNote),\n            ];\n          }\n        }\n      }\n\n      // Deduplicate system messages — ALWAYS runs, not just during compaction.\n      // Duplicate system messages accumulate from repeated tool iterations,\n      // summary injections, and context notes across turns.\n      const { messages: dedupedMessages, removedCount } =\n        deduplicateSystemMessages(messagesToUse);\n      if (removedCount > 0) {\n        messagesToUse = dedupedMessages;\n        mlog(\n          `[Graph:Dedup] Removed ${removedCount} duplicate system message(s)`\n        );\n      }\n\n      let finalMessages = messagesToUse;\n      if (agentContext.useLegacyContent) {\n        finalMessages = formatContentStrings(finalMessages);\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      if (\n        agentContext.provider === Providers.BEDROCK &&\n        lastMessageX instanceof AIMessageChunk &&\n        lastMessageY?.getType() === MessageTypes.TOOL &&\n        typeof lastMessageX.content === 'string'\n      ) {\n        finalMessages[finalMessages.length - 2].content = '';\n      }\n\n      // Use getType() instead of instanceof to avoid module mismatch issues\n      const isLatestToolMessage = lastMessageY?.getType() === MessageTypes.TOOL;\n\n      if (\n        isLatestToolMessage &&\n        agentContext.provider === Providers.ANTHROPIC\n      ) {\n        formatAnthropicArtifactContent(finalMessages);\n      } else if (\n        isLatestToolMessage &&\n        ((isOpenAILike(agentContext.provider) &&\n          agentContext.provider !== Providers.DEEPSEEK) ||\n          isGoogleLike(agentContext.provider))\n      ) {\n        formatArtifactPayload(finalMessages);\n      }\n\n      /**\n       * Handle edge case: when switching from a non-thinking agent to a thinking-enabled agent,\n       * convert AI messages with tool calls to HumanMessages to avoid thinking block requirements.\n       * This is required by Anthropic/Bedrock when thinking is enabled.\n       *\n       * IMPORTANT: This MUST happen BEFORE cache control is applied.\n       * If we add cachePoint to an AI message first, then convert that AI message to a HumanMessage,\n       * the cachePoint is lost. By converting first, we ensure cache control is applied to the\n       * final message structure that will be sent to the API.\n       */\n      const isAnthropicWithThinking =\n        (agentContext.provider === Providers.ANTHROPIC &&\n          (agentContext.clientOptions as t.AnthropicClientOptions).thinking !=\n            null) ||\n        (agentContext.provider === Providers.BEDROCK &&\n          (agentContext.clientOptions as t.BedrockAnthropicInput)\n            .additionalModelRequestFields?.['thinking'] != null);\n\n      if (isAnthropicWithThinking) {\n        finalMessages = ensureThinkingBlockInMessages(\n          finalMessages,\n          agentContext.provider\n        );\n      }\n\n      // Apply cache control AFTER thinking block handling to ensure cachePoints aren't lost\n      // when AI messages are converted to HumanMessages\n      if (agentContext.provider === Providers.ANTHROPIC) {\n        const anthropicOptions = agentContext.clientOptions as\n          | t.AnthropicClientOptions\n          | undefined;\n        if (anthropicOptions?.promptCache === true) {\n          finalMessages = addCacheControl<BaseMessage>(finalMessages);\n        }\n      } else if (agentContext.provider === Providers.BEDROCK) {\n        const bedrockOptions = agentContext.clientOptions as\n          | t.BedrockAnthropicClientOptions\n          | undefined;\n        // Both Claude and Nova models support cachePoint in system and messages\n        // (Llama, Titan, and other models do NOT support cachePoint)\n        const modelId = bedrockOptions?.model?.toLowerCase() ?? '';\n        const supportsCaching =\n          modelId.includes('claude') ||\n          modelId.includes('anthropic') ||\n          modelId.includes('nova');\n        if (bedrockOptions?.promptCache === true && supportsCaching) {\n          finalMessages = addBedrockCacheControl<BaseMessage>(finalMessages);\n        }\n      }\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\n      let result: Partial<t.BaseGraphState> | undefined;\n      const fallbacks =\n        (agentContext.clientOptions as t.LLMConfig | undefined)?.fallbacks ??\n        [];\n\n      if (finalMessages.length === 0) {\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. Please increase the context window size or make your message shorter.',\n          })\n        );\n      }\n\n      // Get model info for analytics\n      const bedrockOpts = agentContext.clientOptions as\n        | t.BedrockAnthropicClientOptions\n        | undefined;\n      const modelId =\n        bedrockOpts?.model ??\n        (agentContext.clientOptions as t.AnthropicClientOptions | undefined)\n          ?.modelName;\n      const thinkingConfig =\n        bedrockOpts?.additionalModelRequestFields?.['thinking'] ??\n        (agentContext.clientOptions as t.AnthropicClientOptions | undefined)\n          ?.thinking;\n\n      // Build and emit context analytics for traces\n      const contextAnalytics = buildContextAnalytics(finalMessages, {\n        tokenCounter: agentContext.tokenCounter,\n        maxContextTokens: agentContext.maxContextTokens,\n        instructionTokens: agentContext.instructionTokens,\n        indexTokenCountMap: agentContext.indexTokenCountMap,\n      });\n\n      // Store for retrieval via getContextAnalytics() after run completes\n      this.lastContextAnalytics = contextAnalytics;\n\n      await safeDispatchCustomEvent(\n        GraphEvents.ON_CONTEXT_ANALYTICS,\n        {\n          provider: agentContext.provider,\n          model: modelId,\n          thinkingEnabled: thinkingConfig != null,\n          cacheEnabled: bedrockOpts?.promptCache === true,\n          analytics: contextAnalytics,\n        },\n        config\n      );\n\n      // ====================================================================\n      // MULTI-DOCUMENT DELEGATION (task-driven, not budget-driven)\n      //\n      // Token-based pressure hints have been removed — the LLM never sees\n      // raw token numbers. Context overflow is handled mechanically by\n      // pruning (Graph) + auto-continuation (client.js max_tokens detection).\n      // See: docs/context-overflow-architecture.md\n      // ====================================================================\n      if (hasTaskTool(agentContext.tools)) {\n        const { count: documentCount, names: documentNames } =\n          detectDocuments(finalMessages);\n\n        // Multi-document delegation: first iteration only (before AI has responded)\n        const hasAiResponse = finalMessages.some(\n          (m) => m._getType() === 'ai' || m._getType() === 'tool'\n        );\n        if (shouldInjectMultiDocHint(documentCount, hasAiResponse)) {\n          const pressureMsg = new HumanMessage({\n            content: buildMultiDocHintContent(documentCount, documentNames),\n          });\n          finalMessages = [...finalMessages, pressureMsg];\n          console.info(\n            `[Graph] Multi-document delegation hint injected for ${documentCount} documents: ` +\n              `${documentNames.join(', ')}`\n          );\n        }\n      }\n\n      // Structured output mode: when the agent has NO tools, produce structured JSON immediately.\n      // When the agent HAS tools, we defer structured output until after tool use completes\n      // (see the deferred structured output block after attemptInvoke below).\n      const hasTools = (toolsForBinding?.length ?? 0) > 0;\n      if (\n        agentContext.isStructuredOutputMode &&\n        agentContext.structuredOutput &&\n        !hasTools\n      ) {\n        try {\n          const structuredResult = await this.performStructuredOutput({\n            agentContext,\n            finalMessages,\n            config,\n          });\n          agentContext.currentUsage = this.getUsageMetadata(\n            structuredResult.messages?.[0]\n          );\n          this.cleanupSignalListener();\n          return structuredResult;\n        } catch (structuredError) {\n          console.error('[Graph] Structured output failed:', structuredError);\n          throw structuredError;\n        }\n      }\n\n      try {\n        result = await this.attemptInvoke(\n          {\n            currentModel: model,\n            finalMessages,\n            provider: agentContext.provider,\n            tools: agentContext.tools,\n          },\n          config\n        );\n      } catch (primaryError) {\n        const errorMessage = (primaryError as Error).message;\n        const isInputTooLongError = isLikelyContextOverflowError(errorMessage);\n\n        // Log when we detect the error\n        if (isInputTooLongError) {\n          mwarn(\n            '[Graph] Detected input too long error:',\n            errorMessage.substring(0, 200)\n          );\n          mwarn('[Graph] Checking emergency pruning conditions:', {\n            hasPruneMessages: !!agentContext.pruneMessages,\n            hasTokenCounter: !!agentContext.tokenCounter,\n            maxContextTokens: agentContext.maxContextTokens,\n            indexTokenMapKeys: Object.keys(agentContext.indexTokenCountMap)\n              .length,\n          });\n        }\n\n        // If input too long and we have pruning capability OR tokenCounter, retry with progressively more aggressive pruning\n        // Note: We can create emergency pruneMessages dynamically if we have tokenCounter and maxContextTokens\n        const canPrune =\n          agentContext.tokenCounter != null &&\n          agentContext.maxContextTokens != null &&\n          agentContext.maxContextTokens > 0;\n        if (isInputTooLongError && canPrune) {\n          // Progressive reduction: 50% -> 25% -> 10% of original context\n          const reductionLevels = [0.5, 0.25, 0.1];\n\n          for (const reductionFactor of reductionLevels) {\n            if (result) break; // Exit if we got a result\n\n            const reducedMaxTokens = Math.floor(\n              agentContext.maxContextTokens! * reductionFactor\n            );\n            mwarn(\n              `[Graph] Input too long. Retrying with ${reductionFactor * 100}% context (${reducedMaxTokens} tokens)...`\n            );\n\n            // Build fresh indexTokenCountMap if missing/incomplete\n            // This is needed when messages were dynamically added without updating the token map\n            let tokenMapForPruning = agentContext.indexTokenCountMap;\n            if (Object.keys(tokenMapForPruning).length < messages.length) {\n              mwarn(\n                '[Graph] Building fresh token count map for emergency pruning...'\n              );\n              tokenMapForPruning = {};\n              for (let i = 0; i < messages.length; i++) {\n                tokenMapForPruning[i] = agentContext.tokenCounter!(messages[i]);\n              }\n            }\n\n            const emergencyPrune = createPruneMessages({\n              startIndex: this.startIndex,\n              provider: agentContext.provider,\n              tokenCounter: agentContext.tokenCounter!,\n              maxTokens: reducedMaxTokens,\n              thinkingEnabled: false, // Disable thinking for emergency prune\n              indexTokenCountMap: tokenMapForPruning,\n            });\n\n            const { context: reducedMessages } = emergencyPrune({\n              messages,\n              usageMetadata: agentContext.currentUsage,\n            });\n\n            // Skip if we can't fit any messages\n            if (reducedMessages.length === 0) {\n              mwarn(\n                `[Graph] Cannot fit any messages at ${reductionFactor * 100}% reduction, trying next level...`\n              );\n              continue;\n            }\n\n            // Calculate how many messages were pruned and estimate context timeframe\n            const prunedCount = finalMessages.length - reducedMessages.length;\n            const remainingCount = reducedMessages.length;\n            const estimatedContextDescription =\n              this.getContextTimeframeDescription(remainingCount);\n\n            // Inject a personalized context message to inform the agent about pruning\n            const pruneNoticeMessage = new HumanMessage({\n              content: `[CONTEXT NOTICE]\nOur conversation has grown quite long, so I've focused on ${estimatedContextDescription} of our chat (${remainingCount} recent messages). ${prunedCount} earlier messages are no longer in my immediate memory.\n\nIf I seem to be missing something we discussed earlier, just give me a quick reminder and I'll pick right back up! I'm still fully engaged and ready to help with whatever you need.`,\n            });\n\n            // Insert the notice after the system message (if any) but before conversation\n            const hasSystemMessage = reducedMessages[0]?.getType() === 'system';\n            const insertIndex = hasSystemMessage ? 1 : 0;\n\n            // Create new array with the pruning notice\n            const messagesWithNotice = [\n              ...reducedMessages.slice(0, insertIndex),\n              pruneNoticeMessage,\n              ...reducedMessages.slice(insertIndex),\n            ];\n\n            let retryMessages = agentContext.useLegacyContent\n              ? formatContentStrings(messagesWithNotice)\n              : messagesWithNotice;\n\n            // Apply thinking block handling first (before cache control)\n            // This ensures AI+Tool sequences are converted to HumanMessages\n            // before we add cache points that could be lost in the conversion\n            if (isAnthropicWithThinking) {\n              retryMessages = ensureThinkingBlockInMessages(\n                retryMessages,\n                agentContext.provider\n              );\n            }\n\n            // Apply Bedrock cache control if needed (after thinking block handling)\n            if (agentContext.provider === Providers.BEDROCK) {\n              const bedrockOptions = agentContext.clientOptions as\n                | t.BedrockAnthropicClientOptions\n                | undefined;\n              const modelId = bedrockOptions?.model?.toLowerCase() ?? '';\n              const supportsCaching =\n                modelId.includes('claude') ||\n                modelId.includes('anthropic') ||\n                modelId.includes('nova');\n              if (bedrockOptions?.promptCache === true && supportsCaching) {\n                retryMessages =\n                  addBedrockCacheControl<BaseMessage>(retryMessages);\n              }\n            }\n\n            try {\n              result = await this.attemptInvoke(\n                {\n                  currentModel: model,\n                  finalMessages: retryMessages,\n                  provider: agentContext.provider,\n                  tools: agentContext.tools,\n                },\n                config\n              );\n              // Success with reduced context\n              console.info(\n                `[Graph] ✅ Retry successful at ${reductionFactor * 100}% with ${reducedMessages.length} messages (reduced from ${finalMessages.length})`\n              );\n            } catch (retryError) {\n              const retryErrorMsg = (retryError as Error).message;\n              const stillTooLong = isLikelyContextOverflowError(retryErrorMsg);\n\n              if (stillTooLong && reductionFactor > 0.1) {\n                mwarn(\n                  `[Graph] Still too long at ${reductionFactor * 100}%, trying more aggressive pruning...`\n                );\n              } else {\n                console.error(\n                  `[Graph] Retry at ${reductionFactor * 100}% failed:`,\n                  (retryError as Error).message\n                );\n              }\n            }\n          }\n        }\n\n        // If we got a result from retry, skip fallbacks\n        if (result) {\n          // result already set from retry\n        } else {\n          let lastError: unknown = primaryError;\n          for (const fb of fallbacks) {\n            try {\n              let model = this.getNewModel({\n                provider: fb.provider,\n                clientOptions: fb.clientOptions,\n              });\n              const bindableTools = agentContext.tools;\n              model = (\n                !bindableTools || bindableTools.length === 0\n                  ? model\n                  : model.bindTools(bindableTools)\n              ) as t.ChatModelInstance;\n              result = await this.attemptInvoke(\n                {\n                  currentModel: model,\n                  finalMessages,\n                  provider: fb.provider,\n                  tools: agentContext.tools,\n                },\n                config\n              );\n              lastError = undefined;\n              break;\n            } catch (e) {\n              lastError = e;\n              continue;\n            }\n          }\n          if (lastError !== undefined) {\n            throw lastError;\n          }\n        }\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      // Tool-call name normalization — catches LLM output that names tools\n      // with wrong delimiters (outlook/operations), prefixes\n      // (functions.outlook_operations), case drift, counter suffixes, or\n      // empty names recoverable from the tool_call id. Mutates in place so\n      // the downstream ToolNode dispatch sees the corrected names.\n      if (responseMessage && agentContext.toolMap) {\n        const allowedNames = new Set(Object.keys(agentContext.toolMap));\n        if (allowedNames.size > 0) {\n          const rewrote = normalizeMessageToolCalls(\n            responseMessage,\n            allowedNames\n          );\n          if (rewrote) {\n            mlog(\n              `[Graph] normalized tool_call names on agent \"${agentId}\" response`\n            );\n          }\n        }\n      }\n\n      const toolCalls = (responseMessage as AIMessageChunk | undefined)\n        ?.tool_calls;\n      const hasToolCalls = Array.isArray(toolCalls) && toolCalls.length > 0;\n\n      if (hasToolCalls) {\n        const metadata = config.metadata as Record<string, unknown>;\n        const stepKey = this.getStepKey(metadata);\n        const content = responseMessage?.content as MessageContent | undefined;\n        const hasTextContent =\n          content != null &&\n          (typeof content === 'string'\n            ? content !== ''\n            : Array.isArray(content) && content.length > 0);\n\n        /**\n         * Dispatch text content BEFORE creating TOOL_CALLS steps.\n         * getMessageId returns a new ID only on the first call for a step key;\n         * if the for-await consumer already claimed it, this is a no-op.\n         */\n        if (hasTextContent) {\n          const messageId = getMessageId(stepKey, this) ?? '';\n          if (messageId) {\n            await this.dispatchRunStep(\n              stepKey,\n              {\n                type: StepTypes.MESSAGE_CREATION,\n                message_creation: { message_id: messageId },\n              },\n              metadata\n            );\n            const stepId = this.getStepIdByKey(stepKey);\n            if (typeof content === 'string') {\n              await this.dispatchMessageDelta(stepId, {\n                content: [{ type: ContentTypes.TEXT, text: content }],\n              });\n            } else if (\n              Array.isArray(content) &&\n              content.every(\n                (c) =>\n                  typeof c === 'object' &&\n                  'type' in c &&\n                  typeof c.type === 'string' &&\n                  c.type.startsWith('text')\n              )\n            ) {\n              await this.dispatchMessageDelta(stepId, {\n                content: content as t.MessageDelta['content'],\n              });\n            }\n          }\n        }\n\n        await handleToolCalls(toolCalls as ToolCall[], metadata, this);\n      }\n\n      /**\n       * When streaming is disabled, on_chat_model_stream events are never\n       * emitted so ChatModelStreamHandler never fires. Dispatch the text\n       * content as MESSAGE_CREATION + MESSAGE_DELTA here.\n       */\n      const disableStreaming =\n        (agentContext.clientOptions as t.OpenAIClientOptions | undefined)\n          ?.disableStreaming === true;\n\n      if (\n        disableStreaming &&\n        !hasToolCalls &&\n        responseMessage != null &&\n        (responseMessage.content as MessageContent | undefined) != null\n      ) {\n        const metadata = config.metadata as Record<string, unknown>;\n        const stepKey = this.getStepKey(metadata);\n        const messageId = getMessageId(stepKey, this) ?? '';\n        if (messageId) {\n          await this.dispatchRunStep(\n            stepKey,\n            {\n              type: StepTypes.MESSAGE_CREATION,\n              message_creation: { message_id: messageId },\n            },\n            metadata\n          );\n          const stepId = this.getStepIdByKey(stepKey);\n          const content = responseMessage.content;\n          if (typeof content === 'string') {\n            await this.dispatchMessageDelta(stepId, {\n              content: [{ type: ContentTypes.TEXT, text: content }],\n            });\n          } else if (\n            Array.isArray(content) &&\n            content.every(\n              (c) =>\n                typeof c === 'object' &&\n                'type' in c &&\n                typeof c.type === 'string' &&\n                c.type.startsWith('text')\n            )\n          ) {\n            await this.dispatchMessageDelta(stepId, {\n              content: content as t.MessageDelta['content'],\n            });\n          }\n        }\n      }\n\n      agentContext.currentUsage = this.getUsageMetadata(result.messages?.[0]);\n\n      // Extract and normalize the LLM's finish/stop reason for auto-continuation support\n      const finalMsg = result.messages?.[0];\n      if (finalMsg && 'response_metadata' in finalMsg) {\n        const meta = finalMsg.response_metadata as Record<string, unknown>;\n        // Bedrock streaming nests stopReason inside messageStop: { stopReason: '...' }\n        const messageStop = meta.messageStop as\n          | Record<string, unknown>\n          | undefined;\n        const nextReason =\n          (meta.finish_reason as string | undefined) ?? // OpenAI/Azure\n          (meta.stop_reason as string | undefined) ?? // Anthropic direct API\n          (meta.stopReason as string | undefined) ?? // Bedrock invoke (non-streaming)\n          (messageStop?.stopReason as string | undefined) ?? // Bedrock streaming\n          (meta.finishReason as string | undefined); // VertexAI/Google\n\n        // Sticky on truncation: a single Graph instance is reused across\n        // every scoped-subgraph inner node invocation (see MultiAgentGraph\n        // buildScopedSubgraph). If an earlier inner node hit max_tokens\n        // but a later inner node finished cleanly, the host's continuation layer\n        // would miss the truncation signal unless we preserve it. Keep the\n        // truncation reason pinned so the outer caller can retry.\n        if (!isTruncationReason(this.lastFinishReason)) {\n          this.lastFinishReason = nextReason;\n        }\n      }\n\n      this.cleanupSignalListener();\n\n      // DEFERRED STRUCTURED OUTPUT: When the agent has tools AND structured output configured,\n      // we let the agent use tools normally via attemptInvoke(). Once the agent's response\n      // has NO tool_calls (it's done with tools), we produce the final structured JSON response.\n      if (\n        agentContext.isStructuredOutputMode &&\n        agentContext.structuredOutput != null\n      ) {\n        const lastMessage = result.messages?.[0];\n        const resultHasToolCalls =\n          lastMessage != null &&\n          'tool_calls' in lastMessage &&\n          ((lastMessage as AIMessageChunk).tool_calls?.length ?? 0) > 0;\n\n        if (resultHasToolCalls !== true) {\n          try {\n            // Build messages for structured output: include the full conversation\n            // plus the agent's text response from attemptInvoke, so the structured\n            // output model has full context (tool results + agent reasoning).\n            const messagesForStructured = [...finalMessages];\n            if (lastMessage) {\n              messagesForStructured.push(lastMessage);\n            }\n\n            const structuredResult = await this.performStructuredOutput({\n              agentContext,\n              finalMessages: messagesForStructured,\n              config,\n            });\n\n            // Accumulate token usage from both API calls\n            const structuredUsage = this.getUsageMetadata(\n              structuredResult.messages?.[0]\n            );\n            if (structuredUsage && agentContext.currentUsage) {\n              agentContext.currentUsage = {\n                input_tokens:\n                  (agentContext.currentUsage.input_tokens ?? 0) +\n                  (structuredUsage.input_tokens ?? 0),\n                output_tokens:\n                  (agentContext.currentUsage.output_tokens ?? 0) +\n                  (structuredUsage.output_tokens ?? 0),\n                total_tokens:\n                  (agentContext.currentUsage.total_tokens ?? 0) +\n                  (structuredUsage.total_tokens ?? 0),\n              };\n            } else if (structuredUsage) {\n              agentContext.currentUsage = structuredUsage;\n            }\n\n            return structuredResult;\n          } catch (structuredError) {\n            // Graceful fallback: the agent completed its work with tools,\n            // but we couldn't format the output as structured JSON.\n            // Return the unstructured text response from attemptInvoke.\n            console.error(\n              '[Graph] Deferred structured output failed after successful tool use:',\n              structuredError\n            );\n            mwarn(\n              '[Graph] Falling back to unstructured response from tool-use phase'\n            );\n            return result;\n          }\n        }\n      }\n\n      return result;\n    };\n  }\n\n  createAgentNode(agentId: string): t.CompiledAgentWorfklow {\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     * Subagent injection (upstream Tier 5): when the agent has SubagentConfig\n     * entries and depth budget remaining, inject a `subagent` DynamicStructuredTool\n     * into graphTools. The tool's executor receives this graph's hookRegistry and\n     * a lazy handler-registry getter (Run wires handlerRegistry AFTER createWorkflow,\n     * so direct capture would be undefined at construction time).\n     */\n    const effectiveSubagentDepth = agentContext.maxSubagentDepth ?? 1;\n    if (\n      agentContext.subagentConfigs != null &&\n      agentContext.subagentConfigs.length > 0 &&\n      effectiveSubagentDepth > 0\n    ) {\n      const resolvedConfigs = resolveSubagentConfigs(\n        agentContext.subagentConfigs,\n        agentContext\n      );\n      if (resolvedConfigs.length > 0) {\n        const getParentHandlerRegistry = (): HandlerRegistry | undefined =>\n          this.handlerRegistry;\n        const executor = new SubagentExecutor({\n          configs: new Map(resolvedConfigs.map((c) => [c.type, c])),\n          parentSignal: this.signal,\n          hookRegistry: this.hookRegistry,\n          parentHandlerRegistry: getParentHandlerRegistry,\n          parentRunId: this.runId ?? '',\n          parentAgentId: agentContext.agentId,\n          tokenCounter: agentContext.tokenCounter,\n          maxDepth: effectiveSubagentDepth,\n          createChildGraph: (input): StandardGraph =>\n            new StandardGraph(input as t.StandardGraphInput),\n        });\n\n        const subagentTool = makeStructuredTool(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              : 'No task description provided';\n          const subagentType =\n            typeof input.subagent_type === 'string' ? input.subagent_type : '';\n          const threadId = config.configurable?.thread_id as string | undefined;\n          const toolCall = (config as { toolCall?: { id?: string } }).toolCall;\n          const parentToolCallId =\n            typeof toolCall?.id === 'string' ? toolCall.id : undefined;\n          const result = await executor.execute({\n            description,\n            subagentType,\n            threadId,\n            parentToolCallId,\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(resolvedConfigs));\n\n        if (!agentContext.graphTools) {\n          agentContext.graphTools = [];\n        }\n        (agentContext.graphTools as t.GenericTool[]).push(subagentTool);\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\n    const routeMessage = (\n      state: t.BaseGraphState,\n      config?: RunnableConfig\n    ): string => {\n      // First-writer-wins — see note in createCallModel. `this.config` is an\n      // existence flag only; assigning unconditionally would race under\n      // parallel child subgraph.invoke().\n      this.config ??= config;\n      return toolsCondition(state, toolNode, this.invokedToolIds);\n    };\n\n    const StateAnnotation = Annotation.Root({\n      messages: Annotation<BaseMessage[]>({\n        reducer: messagesStateReducer,\n        default: () => [],\n      }),\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      .addEdge(START, agentNode)\n      .addConditionalEdges(agentNode, routeMessage)\n      .addEdge(toolNode, agentContext.toolEnd ? END : agentNode);\n\n    // Cast to unknown to avoid tight coupling to external types; options are opt-in\n    return workflow.compile(this.compileOptions as unknown as never);\n  }\n\n  createWorkflow(): t.CompiledStateWorkflow {\n    /** Use the default (first) agent for now */\n    const agentNode = this.createAgentNode(this.defaultAgentId);\n    const StateAnnotation = Annotation.Root({\n      messages: Annotation<BaseMessage[]>({\n        reducer: (a, b) => {\n          if (!a.length) {\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    // Pass compileOptions (including the HITL checkpointer) to the OUTER\n    // workflow — not just the inner agent subgraph. hasInterrupts() calls\n    // getState() on the outer compiled graph; without a checkpointer here,\n    // getState reports zero tasks and the HITL interrupt/resume loop breaks\n    // out immediately even though interrupt() fired correctly inside the\n    // agent subgraph.\n    const workflow = new StateGraph(StateAnnotation)\n      .addNode(this.defaultAgentId, agentNode, { ends: [END] })\n      .addEdge(START, this.defaultAgentId)\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  /* 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    /**\n     * Extract agentId and parallelGroupId from metadata\n     * Only set agentId for MultiAgentGraph (so frontend knows when to show agent labels)\n     */\n    if (metadata) {\n      try {\n        const agentContext = this.getAgentContext(metadata);\n        if (this.isMultiAgentGraph() && agentContext.agentId) {\n          // Only include agentId for MultiAgentGraph - enables frontend to show agent labels\n          runStep.agentId = agentContext.agentId;\n          // Set group ID if this agent is part of a parallel group\n          // Group IDs are incrementing numbers (1, 2, 3...) reflecting execution order\n          const groupId = this.getParallelGroupIdForAgent(agentContext.agentId);\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        mlog(\n          `[dispatchRunStep] Could not resolve agentId from metadata.langgraph_node=\"${(metadata as Record<string, unknown>).langgraph_node}\": ${(_e as Error).message}`\n        );\n      }\n    }\n\n    this.contentData.push(runStep);\n    this.contentIndexMap.set(stepId, runStep.index);\n    // Pass undefined so safeDispatchCustomEvent resolves the runnable config\n    // from LangChain's AsyncLocalStorage. Using the shared `this.config` would\n    // race across concurrent child subgraph.invoke calls under parallel\n    // multi-agent handoffs and tag events with the wrong child's spawnKey.\n    await safeDispatchCustomEvent(GraphEvents.ON_RUN_STEP, runStep);\n    return stepId;\n  }\n\n  async handleToolCallCompleted(\n    data: t.ToolEndData,\n    metadata?: Record<string, unknown>,\n    omitOutput?: boolean\n  ): Promise<void> {\n    if (!this.config) {\n      throw new Error('No config provided');\n    }\n\n    if (!data.output) {\n      return;\n    }\n\n    const { input, output: _output } = data;\n    if ((_output as Command | undefined)?.lg_name === 'Command') {\n      return;\n    }\n    const output = _output as ToolMessage;\n    const { tool_call_id } = output;\n    const stepId = this.toolCallStepIds.get(tool_call_id) ?? '';\n    if (!stepId) {\n      throw new Error(`No stepId found for tool_call_id ${tool_call_id}`);\n    }\n\n    const runStep = this.getRunStep(stepId);\n    if (!runStep) {\n      throw new Error(`No run step found for stepId ${stepId}`);\n    }\n\n    /**\n     * Extract and store code execution session context from artifacts.\n     * Each file is stamped with its source session_id to support multi-session file tracking.\n     * When the same filename appears in a later execution, the newer version replaces the old.\n     */\n    const toolName = output.name;\n    if (\n      toolName === Constants.EXECUTE_CODE ||\n      toolName === Constants.PROGRAMMATIC_TOOL_CALLING\n    ) {\n      const artifact = output.artifact as t.CodeExecutionArtifact | undefined;\n      const newFiles = artifact?.files ?? [];\n      const hasNewFiles = newFiles.length > 0;\n\n      if (artifact?.session_id != null && artifact.session_id !== '') {\n        const existingSession = this.sessions.get(Constants.EXECUTE_CODE) as\n          | t.CodeSessionContext\n          | undefined;\n        const existingFiles = existingSession?.files ?? [];\n\n        if (hasNewFiles) {\n          /**\n           * Stamp each new file with its source session_id.\n           * This enables files from different executions (parallel or sequential)\n           * to be tracked and passed to subsequent calls.\n           */\n          const filesWithSession: t.FileRefs = newFiles.map((file) => ({\n            ...file,\n            session_id: artifact.session_id,\n          }));\n\n          /**\n           * Merge files, preferring latest versions by name.\n           * If a file with the same name exists, replace it with the new version.\n           * This handles cases where files are edited/recreated in subsequent executions.\n           */\n          const newFileNames = new Set(filesWithSession.map((f) => f.name));\n          const filteredExisting = existingFiles.filter(\n            (f) => !newFileNames.has(f.name)\n          );\n\n          this.sessions.set(Constants.EXECUTE_CODE, {\n            /** Keep latest session_id for reference/fallback */\n            session_id: artifact.session_id,\n            /** Accumulated files with latest versions preferred */\n            files: [...filteredExisting, ...filesWithSession],\n            lastUpdated: Date.now(),\n          });\n        } else {\n          /**\n           * Even when execution produces no files (e.g., error or print-only),\n           * store the session_id so retries can reuse the same workspace\n           * and access any files written to disk during the failed execution.\n           */\n          this.sessions.set(Constants.EXECUTE_CODE, {\n            session_id: artifact.session_id,\n            files: existingFiles,\n            lastUpdated: Date.now(),\n          });\n        }\n      }\n    }\n\n    const dispatchedOutput =\n      typeof output.content === 'string'\n        ? output.content\n        : JSON.stringify(output.content);\n\n    const args = typeof input === 'string' ? input : input.input;\n    const tool_call = {\n      args: typeof args === 'string' ? args : JSON.stringify(args),\n      name: output.name ?? '',\n      id: output.tool_call_id,\n      output: omitOutput === true ? '' : dispatchedOutput,\n      progress: 1,\n    };\n\n    await this.handlerRegistry\n      ?.getHandler(GraphEvents.ON_RUN_STEP_COMPLETED)\n      ?.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        this\n      );\n  }\n\n  /**\n   * Static version of handleToolCallError to avoid creating strong references\n   * that prevent garbage collection\n   */\n  static async handleToolCallErrorStatic(\n    graph: StandardGraph,\n    data: t.ToolErrorData,\n    metadata?: Record<string, unknown>\n  ): Promise<void> {\n    if (!graph.config) {\n      throw new Error('No config provided');\n    }\n\n    if (!data.id) {\n      mwarn('No Tool ID provided for Tool Error');\n      return;\n    }\n\n    const stepId = graph.toolCallStepIds.get(data.id) ?? '';\n    if (!stepId) {\n      throw new Error(`No stepId found for tool_call_id ${data.id}`);\n    }\n\n    const { name, input: args, error } = data;\n\n    const runStep = graph.getRunStep(stepId);\n    if (!runStep) {\n      throw new Error(`No run step found for stepId ${stepId}`);\n    }\n\n    const tool_call: t.ProcessedToolCall = {\n      id: data.id,\n      name: name || '',\n      args: typeof args === 'string' ? args : JSON.stringify(args),\n      output: `Error processing tool${error?.message != null ? `: ${error.message}` : ''}`,\n      progress: 1,\n    };\n\n    await graph.handlerRegistry\n      ?.getHandler(GraphEvents.ON_RUN_STEP_COMPLETED)\n      ?.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  }\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<void> {\n    await StandardGraph.handleToolCallErrorStatic(this, data, metadata);\n  }\n\n  async dispatchRunStepDelta(\n    id: string,\n    delta: t.ToolCallDelta\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    // See dispatchRunStep note: do not pass `this.config`. The implicit\n    // AsyncLocalStorage config is the correct per-async-branch source under\n    // parallel handoffs.\n    await safeDispatchCustomEvent(GraphEvents.ON_RUN_STEP_DELTA, runStepDelta);\n  }\n\n  async dispatchMessageDelta(id: string, delta: t.MessageDelta): 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    // See dispatchRunStep note.\n    await safeDispatchCustomEvent(GraphEvents.ON_MESSAGE_DELTA, messageDelta);\n  }\n\n  dispatchReasoningDelta = async (\n    stepId: string,\n    delta: t.ReasoningDelta\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    // See dispatchRunStep note.\n    await safeDispatchCustomEvent(\n      GraphEvents.ON_REASONING_DELTA,\n      reasoningDelta\n    );\n  };\n}\n"],"names":["GraphNodeKeys","ToolOutputReferenceRegistryClass","StreamingToolCallBuffer","AgentContext","createPruneCalibration","ToolDiscoveryCache","resetIfNotEmpty","Providers","TOOL_TURN_THINKING_BUDGET","SUMMARIZATION_CONTEXT_THRESHOLD","joinKeys","nanoid","ContentTypes","convertMessagesToContent","SystemMessage","RunnableLambda","createSchemaOnlyTools","CustomToolNode","getChatModelClass","isOpenAILike","ChatOpenAI","AzureChatOpenAI","ChatVertexAI","createFakeStreamingLLM","annotateMessagesForLLM","ChatModelStreamHandler","stream","GraphEvents","concat","manualToolStreamProviders","modifyDeltaProperties","mwarn","prepareSchemaForProvider","StructuredOutputTruncatedError","StructuredOutputRefusalError","HumanMessage","safeDispatchCustomEvent","AIMessageChunk","messages","mlog","applyCalibration","createPruneMessages","updatePruneCalibration","getContextUtilization","PROACTIVE_SUMMARY_THRESHOLD","executeHooks","COMPACTION_RECENT_ROUNDS","fileManifest","buildFileManifestBlock","hasTaskTool","buildPostPruneNote","deduplicateSystemMessages","formatContentStrings","MessageTypes","formatAnthropicArtifactContent","isGoogleLike","formatArtifactPayload","ensureThinkingBlockInMessages","addCacheControl","addBedrockCacheControl","sleep","contextAnalytics","buildContextAnalytics","detectDocuments","shouldInjectMultiDocHint","buildMultiDocHintContent","isLikelyContextOverflowError","normalizeMessageToolCalls","getMessageId","StepTypes","handleToolCalls","isTruncationReason","resolveSubagentConfigs","SubagentExecutor","makeStructuredTool","buildSubagentToolParams","toolsCondition","Annotation","messagesStateReducer","StateGraph","START","END","Constants"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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