@illuma-ai/agents 1.5.0 → 1.5.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/agents/AgentContext.cjs +2 -2
- package/dist/cjs/agents/AgentContext.cjs.map +1 -1
- package/dist/cjs/common/enum.cjs +12 -12
- package/dist/cjs/common/enum.cjs.map +1 -1
- package/dist/cjs/graphs/Graph.cjs +5 -5
- package/dist/cjs/graphs/Graph.cjs.map +1 -1
- package/dist/cjs/graphs/MultiAgentGraph.cjs +1 -1
- package/dist/cjs/graphs/MultiAgentGraph.cjs.map +1 -1
- package/dist/cjs/graphs/phases/memoryFlushPhase.cjs +1 -1
- package/dist/cjs/graphs/phases/memoryFlushPhase.cjs.map +1 -1
- package/dist/cjs/hooks/HookRegistry.cjs +1 -1
- package/dist/cjs/hooks/HookRegistry.cjs.map +1 -1
- package/dist/cjs/hooks/matchers.cjs +2 -2
- package/dist/cjs/hooks/matchers.cjs.map +1 -1
- package/dist/cjs/hooks/types.cjs +1 -1
- package/dist/cjs/hooks/types.cjs.map +1 -1
- package/dist/cjs/llm/bedrock/cacheSupport.cjs +1 -1
- package/dist/cjs/llm/bedrock/cacheSupport.cjs.map +1 -1
- package/dist/cjs/llm/bedrock/index.cjs +2 -2
- package/dist/cjs/llm/bedrock/index.cjs.map +1 -1
- package/dist/cjs/llm/openai/index.cjs +1 -1
- package/dist/cjs/llm/openai/index.cjs.map +1 -1
- package/dist/cjs/llm/openai/utils/index.cjs +2 -2
- package/dist/cjs/llm/openai/utils/index.cjs.map +1 -1
- package/dist/cjs/memory/citations.cjs +4 -4
- package/dist/cjs/memory/citations.cjs.map +1 -1
- package/dist/cjs/memory/constants.cjs +17 -17
- package/dist/cjs/memory/constants.cjs.map +1 -1
- package/dist/cjs/memory/mmr.cjs +1 -1
- package/dist/cjs/memory/mmr.cjs.map +1 -1
- package/dist/cjs/memory/paths.cjs +1 -1
- package/dist/cjs/memory/paths.cjs.map +1 -1
- package/dist/cjs/memory/recallTracking.cjs +3 -3
- package/dist/cjs/memory/recallTracking.cjs.map +1 -1
- package/dist/cjs/memory/temporalDecay.cjs +2 -2
- package/dist/cjs/memory/temporalDecay.cjs.map +1 -1
- package/dist/cjs/messages/format.cjs +3 -3
- package/dist/cjs/messages/format.cjs.map +1 -1
- package/dist/cjs/tools/CodeExecutor.cjs +4 -3
- package/dist/cjs/tools/CodeExecutor.cjs.map +1 -1
- package/dist/cjs/tools/ToolNode.cjs +5 -5
- package/dist/cjs/tools/ToolNode.cjs.map +1 -1
- package/dist/cjs/tools/memory/memoryAppendTool.cjs +1 -1
- package/dist/cjs/tools/memory/memoryAppendTool.cjs.map +1 -1
- package/dist/cjs/tools/memory/memoryGetTool.cjs +2 -2
- package/dist/cjs/tools/memory/memoryGetTool.cjs.map +1 -1
- package/dist/cjs/tools/memory/memorySearchTool.cjs +3 -3
- package/dist/cjs/tools/memory/memorySearchTool.cjs.map +1 -1
- package/dist/cjs/tools/memory/shared.cjs +1 -1
- package/dist/cjs/tools/memory/shared.cjs.map +1 -1
- package/dist/cjs/types/agent-cache.cjs +6 -5
- package/dist/cjs/types/agent-cache.cjs.map +1 -1
- package/dist/cjs/types/graph.cjs.map +1 -1
- package/dist/esm/agents/AgentContext.mjs +2 -2
- package/dist/esm/agents/AgentContext.mjs.map +1 -1
- package/dist/esm/common/enum.mjs +12 -12
- package/dist/esm/common/enum.mjs.map +1 -1
- package/dist/esm/graphs/Graph.mjs +5 -5
- package/dist/esm/graphs/Graph.mjs.map +1 -1
- package/dist/esm/graphs/MultiAgentGraph.mjs +1 -1
- package/dist/esm/graphs/MultiAgentGraph.mjs.map +1 -1
- package/dist/esm/graphs/phases/memoryFlushPhase.mjs +1 -1
- package/dist/esm/graphs/phases/memoryFlushPhase.mjs.map +1 -1
- package/dist/esm/hooks/HookRegistry.mjs +1 -1
- package/dist/esm/hooks/HookRegistry.mjs.map +1 -1
- package/dist/esm/hooks/matchers.mjs +2 -2
- package/dist/esm/hooks/matchers.mjs.map +1 -1
- package/dist/esm/hooks/types.mjs +1 -1
- package/dist/esm/hooks/types.mjs.map +1 -1
- package/dist/esm/llm/bedrock/cacheSupport.mjs +1 -1
- package/dist/esm/llm/bedrock/cacheSupport.mjs.map +1 -1
- package/dist/esm/llm/bedrock/index.mjs +2 -2
- package/dist/esm/llm/bedrock/index.mjs.map +1 -1
- package/dist/esm/llm/openai/index.mjs +1 -1
- package/dist/esm/llm/openai/index.mjs.map +1 -1
- package/dist/esm/llm/openai/utils/index.mjs +2 -2
- package/dist/esm/llm/openai/utils/index.mjs.map +1 -1
- package/dist/esm/memory/citations.mjs +4 -4
- package/dist/esm/memory/citations.mjs.map +1 -1
- package/dist/esm/memory/constants.mjs +17 -17
- package/dist/esm/memory/constants.mjs.map +1 -1
- package/dist/esm/memory/mmr.mjs +1 -1
- package/dist/esm/memory/mmr.mjs.map +1 -1
- package/dist/esm/memory/paths.mjs +1 -1
- package/dist/esm/memory/paths.mjs.map +1 -1
- package/dist/esm/memory/recallTracking.mjs +3 -3
- package/dist/esm/memory/recallTracking.mjs.map +1 -1
- package/dist/esm/memory/temporalDecay.mjs +2 -2
- package/dist/esm/memory/temporalDecay.mjs.map +1 -1
- package/dist/esm/messages/format.mjs +3 -3
- package/dist/esm/messages/format.mjs.map +1 -1
- package/dist/esm/tools/CodeExecutor.mjs +4 -3
- package/dist/esm/tools/CodeExecutor.mjs.map +1 -1
- package/dist/esm/tools/ToolNode.mjs +5 -5
- package/dist/esm/tools/ToolNode.mjs.map +1 -1
- package/dist/esm/tools/memory/memoryAppendTool.mjs +1 -1
- package/dist/esm/tools/memory/memoryAppendTool.mjs.map +1 -1
- package/dist/esm/tools/memory/memoryGetTool.mjs +2 -2
- package/dist/esm/tools/memory/memoryGetTool.mjs.map +1 -1
- package/dist/esm/tools/memory/memorySearchTool.mjs +3 -3
- package/dist/esm/tools/memory/memorySearchTool.mjs.map +1 -1
- package/dist/esm/tools/memory/shared.mjs +1 -1
- package/dist/esm/tools/memory/shared.mjs.map +1 -1
- package/dist/esm/types/agent-cache.mjs +6 -5
- package/dist/esm/types/agent-cache.mjs.map +1 -1
- package/dist/esm/types/graph.mjs.map +1 -1
- package/dist/types/agents/AgentContext.d.ts +1 -1
- package/dist/types/common/enum.d.ts +12 -12
- package/dist/types/graphs/Graph.d.ts +2 -2
- package/dist/types/graphs/phases/memoryFlushPhase.d.ts +2 -2
- package/dist/types/hooks/HookRegistry.d.ts +1 -1
- package/dist/types/hooks/matchers.d.ts +2 -2
- package/dist/types/hooks/types.d.ts +1 -1
- package/dist/types/llm/bedrock/cacheSupport.d.ts +1 -1
- package/dist/types/llm/bedrock/index.d.ts +2 -2
- package/dist/types/llm/openai/index.d.ts +1 -1
- package/dist/types/memory/citations.d.ts +4 -4
- package/dist/types/memory/constants.d.ts +17 -17
- package/dist/types/memory/mmr.d.ts +3 -3
- package/dist/types/memory/paths.d.ts +1 -1
- package/dist/types/memory/temporalDecay.d.ts +2 -2
- package/dist/types/memory/types.d.ts +3 -3
- package/dist/types/messages/format.d.ts +1 -1
- package/dist/types/tools/ToolNode.d.ts +3 -3
- package/dist/types/tools/memory/shared.d.ts +1 -1
- package/dist/types/types/agent-cache.d.ts +6 -5
- package/dist/types/types/graph.d.ts +7 -6
- package/dist/types/types/messages.d.ts +1 -1
- package/dist/types/types/run.d.ts +1 -1
- package/dist/types/types/tools.d.ts +5 -5
- package/package.json +1 -1
- package/src/agents/AgentContext.ts +2 -2
- package/src/agents/__tests__/AgentContext.crossAgentTier1.live.test.ts +5 -3
- package/src/agents/__tests__/AgentContext.test.ts +1 -1
- package/src/common/__tests__/enum.test.ts +1 -1
- package/src/common/enum.ts +12 -12
- package/src/graphs/Graph.ts +5 -5
- package/src/graphs/MultiAgentGraph.ts +1 -1
- package/src/graphs/gapFeatures.test.ts +1 -1
- package/src/graphs/phases/__tests__/memoryFlushPhase.test.ts +1 -1
- package/src/graphs/phases/memoryFlushPhase.ts +2 -2
- package/src/hooks/HookRegistry.ts +1 -1
- package/src/hooks/index.ts +1 -1
- package/src/hooks/matchers.ts +2 -2
- package/src/hooks/types.ts +1 -1
- package/src/llm/anthropic/utils/server-tool-inputs.test.ts +7 -7
- package/src/llm/bedrock/__tests__/bedrock-caching.test.ts +2 -2
- package/src/llm/bedrock/cacheSupport.ts +1 -1
- package/src/llm/bedrock/index.ts +2 -2
- package/src/llm/openai/index.ts +2 -2
- package/src/llm/openai/utils/index.ts +2 -2
- package/src/memory/citations.ts +4 -4
- package/src/memory/constants.ts +17 -17
- package/src/memory/mmr.ts +3 -3
- package/src/memory/paths.ts +1 -1
- package/src/memory/recallTracking.ts +3 -3
- package/src/memory/temporalDecay.ts +2 -2
- package/src/memory/types.ts +3 -3
- package/src/messages/cache.test.ts +1 -1
- package/src/messages/ensureThinkingBlock.test.ts +1 -1
- package/src/messages/format.ts +4 -4
- package/src/messages/formatAgentMessages.test.ts +1 -1
- package/src/scripts/subagent-event-driven-debug.ts +2 -2
- package/src/specs/anthropic.simple.test.ts +1 -1
- package/src/specs/prune.orphans.test.ts +1 -1
- package/src/tools/CodeExecutor.ts +4 -3
- package/src/tools/ToolNode.ts +6 -6
- package/src/tools/__tests__/CodeExecutor.test.ts +3 -3
- package/src/tools/memory/memoryAppendTool.ts +1 -1
- package/src/tools/memory/memoryGetTool.ts +2 -2
- package/src/tools/memory/memorySearchTool.ts +3 -3
- package/src/tools/memory/shared.ts +1 -1
- package/src/types/agent-cache.ts +6 -5
- package/src/types/graph.ts +7 -6
- package/src/types/messages.ts +1 -1
- package/src/types/run.ts +1 -1
- package/src/types/tools.ts +5 -5
- package/dist/types/tools/search/test.d.ts +0 -1
- package/src/agents/AgentContext.js.map +0 -1
- package/src/agents/AgentContext.test.js.map +0 -1
- package/src/agents/__tests__/AgentContext.test.js.map +0 -1
- package/src/agents/__tests__/resolveStructuredOutputMode.test.js.map +0 -1
- package/src/common/enum.js.map +0 -1
- package/src/common/index.js.map +0 -1
- package/src/events.js.map +0 -1
- package/src/graphs/Graph.js.map +0 -1
- package/src/graphs/MultiAgentGraph.js.map +0 -1
- package/src/graphs/__tests__/structured-output.integration.test.js.map +0 -1
- package/src/graphs/__tests__/structured-output.test.js.map +0 -1
- package/src/graphs/contextManagement.e2e.test.js.map +0 -1
- package/src/graphs/contextManagement.test.js.map +0 -1
- package/src/graphs/handoffValidation.test.js.map +0 -1
- package/src/graphs/index.js.map +0 -1
- package/src/index.js.map +0 -1
- package/src/instrumentation.js.map +0 -1
- package/src/llm/anthropic/index.js.map +0 -1
- package/src/llm/anthropic/types.js.map +0 -1
- package/src/llm/anthropic/utils/message_inputs.js.map +0 -1
- package/src/llm/anthropic/utils/message_outputs.js.map +0 -1
- package/src/llm/anthropic/utils/output_parsers.js.map +0 -1
- package/src/llm/anthropic/utils/tools.js.map +0 -1
- package/src/llm/bedrock/__tests__/bedrock-caching.test.js.map +0 -1
- package/src/llm/bedrock/index.js.map +0 -1
- package/src/llm/bedrock/types.js.map +0 -1
- package/src/llm/bedrock/utils/index.js.map +0 -1
- package/src/llm/bedrock/utils/message_inputs.js.map +0 -1
- package/src/llm/bedrock/utils/message_outputs.js.map +0 -1
- package/src/llm/fake.js.map +0 -1
- package/src/llm/google/index.js.map +0 -1
- package/src/llm/google/types.js.map +0 -1
- package/src/llm/google/utils/common.js.map +0 -1
- package/src/llm/google/utils/tools.js.map +0 -1
- package/src/llm/google/utils/zod_to_genai_parameters.js.map +0 -1
- package/src/llm/openai/index.js.map +0 -1
- package/src/llm/openai/types.js.map +0 -1
- package/src/llm/openai/utils/index.js.map +0 -1
- package/src/llm/openai/utils/isReasoningModel.test.js.map +0 -1
- package/src/llm/openrouter/index.js.map +0 -1
- package/src/llm/openrouter/reasoning.test.js.map +0 -1
- package/src/llm/providers.js.map +0 -1
- package/src/llm/text.js.map +0 -1
- package/src/llm/vertexai/index.js.map +0 -1
- package/src/messages/__tests__/tools.test.js.map +0 -1
- package/src/messages/cache.js.map +0 -1
- package/src/messages/cache.test.js.map +0 -1
- package/src/messages/content.js.map +0 -1
- package/src/messages/content.test.js.map +0 -1
- package/src/messages/core.js.map +0 -1
- package/src/messages/ensureThinkingBlock.test.js.map +0 -1
- package/src/messages/format.js.map +0 -1
- package/src/messages/formatAgentMessages.test.js.map +0 -1
- package/src/messages/formatAgentMessages.tools.test.js.map +0 -1
- package/src/messages/formatMessage.test.js.map +0 -1
- package/src/messages/ids.js.map +0 -1
- package/src/messages/index.js.map +0 -1
- package/src/messages/labelContentByAgent.test.js.map +0 -1
- package/src/messages/prune.js.map +0 -1
- package/src/messages/reducer.js.map +0 -1
- package/src/messages/shiftIndexTokenCountMap.test.js.map +0 -1
- package/src/messages/summarize.js.map +0 -1
- package/src/messages/summarize.test.js.map +0 -1
- package/src/messages/tools.js.map +0 -1
- package/src/mockStream.js.map +0 -1
- package/src/prompts/collab.js.map +0 -1
- package/src/prompts/index.js.map +0 -1
- package/src/prompts/taskmanager.js.map +0 -1
- package/src/run.js.map +0 -1
- package/src/schemas/index.js.map +0 -1
- package/src/schemas/schema-preparation.test.js.map +0 -1
- package/src/schemas/validate.js.map +0 -1
- package/src/schemas/validate.test.js.map +0 -1
- package/src/scripts/abort.js.map +0 -1
- package/src/scripts/ant_web_search.js.map +0 -1
- package/src/scripts/ant_web_search_edge_case.js.map +0 -1
- package/src/scripts/ant_web_search_error_edge_case.js.map +0 -1
- package/src/scripts/args.js.map +0 -1
- package/src/scripts/bedrock-cache-debug.js.map +0 -1
- package/src/scripts/bedrock-content-aggregation-test.js.map +0 -1
- package/src/scripts/bedrock-merge-test.js.map +0 -1
- package/src/scripts/bedrock-parallel-tools-test.js.map +0 -1
- package/src/scripts/caching.js.map +0 -1
- package/src/scripts/cli.js.map +0 -1
- package/src/scripts/cli2.js.map +0 -1
- package/src/scripts/cli3.js.map +0 -1
- package/src/scripts/cli4.js.map +0 -1
- package/src/scripts/cli5.js.map +0 -1
- package/src/scripts/code_exec.js.map +0 -1
- package/src/scripts/code_exec_files.js.map +0 -1
- package/src/scripts/code_exec_multi_session.js.map +0 -1
- package/src/scripts/code_exec_ptc.js.map +0 -1
- package/src/scripts/code_exec_session.js.map +0 -1
- package/src/scripts/code_exec_simple.js.map +0 -1
- package/src/scripts/content.js.map +0 -1
- package/src/scripts/empty_input.js.map +0 -1
- package/src/scripts/handoff-test.js.map +0 -1
- package/src/scripts/image.js.map +0 -1
- package/src/scripts/memory.js.map +0 -1
- package/src/scripts/multi-agent-chain.js.map +0 -1
- package/src/scripts/multi-agent-conditional.js.map +0 -1
- package/src/scripts/multi-agent-document-review-chain.js.map +0 -1
- package/src/scripts/multi-agent-hybrid-flow.js.map +0 -1
- package/src/scripts/multi-agent-parallel-start.js.map +0 -1
- package/src/scripts/multi-agent-parallel.js.map +0 -1
- package/src/scripts/multi-agent-sequence.js.map +0 -1
- package/src/scripts/multi-agent-supervisor.js.map +0 -1
- package/src/scripts/multi-agent-test.js.map +0 -1
- package/src/scripts/parallel-asymmetric-tools-test.js.map +0 -1
- package/src/scripts/parallel-full-metadata-test.js.map +0 -1
- package/src/scripts/parallel-tools-test.js.map +0 -1
- package/src/scripts/programmatic_exec.js.map +0 -1
- package/src/scripts/programmatic_exec_agent.js.map +0 -1
- package/src/scripts/search.js.map +0 -1
- package/src/scripts/sequential-full-metadata-test.js.map +0 -1
- package/src/scripts/simple.js.map +0 -1
- package/src/scripts/single-agent-metadata-test.js.map +0 -1
- package/src/scripts/stream.js.map +0 -1
- package/src/scripts/test-custom-prompt-key.js.map +0 -1
- package/src/scripts/test-handoff-input.js.map +0 -1
- package/src/scripts/test-handoff-preamble.js.map +0 -1
- package/src/scripts/test-handoff-steering.js.map +0 -1
- package/src/scripts/test-multi-agent-list-handoff.js.map +0 -1
- package/src/scripts/test-parallel-agent-labeling.js.map +0 -1
- package/src/scripts/test-parallel-handoffs.js.map +0 -1
- package/src/scripts/test-thinking-handoff-bedrock.js.map +0 -1
- package/src/scripts/test-thinking-handoff.js.map +0 -1
- package/src/scripts/test-thinking-to-thinking-handoff-bedrock.js.map +0 -1
- package/src/scripts/test-tool-before-handoff-role-order.js.map +0 -1
- package/src/scripts/test-tools-before-handoff.js.map +0 -1
- package/src/scripts/test_code_api.js.map +0 -1
- package/src/scripts/thinking-bedrock.js.map +0 -1
- package/src/scripts/thinking-vertexai.js.map +0 -1
- package/src/scripts/thinking.js.map +0 -1
- package/src/scripts/tool_search.js.map +0 -1
- package/src/scripts/tools.js.map +0 -1
- package/src/specs/agent-handoffs-bedrock.integration.test.js.map +0 -1
- package/src/specs/agent-handoffs.test.js.map +0 -1
- package/src/specs/anthropic.simple.test.js.map +0 -1
- package/src/specs/azure.simple.test.js.map +0 -1
- package/src/specs/cache.simple.test.js.map +0 -1
- package/src/specs/custom-event-await.test.js.map +0 -1
- package/src/specs/deepseek.simple.test.js.map +0 -1
- package/src/specs/emergency-prune.test.js.map +0 -1
- package/src/specs/moonshot.simple.test.js.map +0 -1
- package/src/specs/observability.integration.test.js.map +0 -1
- package/src/specs/openai.simple.test.js.map +0 -1
- package/src/specs/openrouter.simple.test.js.map +0 -1
- package/src/specs/prune.test.js.map +0 -1
- package/src/specs/reasoning.test.js.map +0 -1
- package/src/specs/spec.utils.js.map +0 -1
- package/src/specs/thinking-handoff.test.js.map +0 -1
- package/src/specs/thinking-prune.test.js.map +0 -1
- package/src/specs/token-distribution-edge-case.test.js.map +0 -1
- package/src/specs/token-memoization.test.js.map +0 -1
- package/src/specs/tokens.test.js.map +0 -1
- package/src/specs/tool-error.test.js.map +0 -1
- package/src/splitStream.js.map +0 -1
- package/src/splitStream.test.js.map +0 -1
- package/src/stream.js.map +0 -1
- package/src/stream.test.js.map +0 -1
- package/src/test/mockTools.js.map +0 -1
- package/src/tools/BrowserTools.js.map +0 -1
- package/src/tools/Calculator.js.map +0 -1
- package/src/tools/Calculator.test.js.map +0 -1
- package/src/tools/CodeExecutor.js.map +0 -1
- package/src/tools/ProgrammaticToolCalling.js.map +0 -1
- package/src/tools/StreamingToolCallBuffer.js.map +0 -1
- package/src/tools/ToolNode.js.map +0 -1
- package/src/tools/ToolSearch.js.map +0 -1
- package/src/tools/__tests__/BrowserTools.test.js.map +0 -1
- package/src/tools/__tests__/ProgrammaticToolCalling.integration.test.js.map +0 -1
- package/src/tools/__tests__/ProgrammaticToolCalling.test.js.map +0 -1
- package/src/tools/__tests__/StreamingToolCallBuffer.test.js.map +0 -1
- package/src/tools/__tests__/ToolApproval.test.js.map +0 -1
- package/src/tools/__tests__/ToolNode.recovery.test.js.map +0 -1
- package/src/tools/__tests__/ToolNode.session.test.js.map +0 -1
- package/src/tools/__tests__/ToolSearch.integration.test.js.map +0 -1
- package/src/tools/__tests__/ToolSearch.test.js.map +0 -1
- package/src/tools/__tests__/handlers.test.js.map +0 -1
- package/src/tools/__tests__/truncation-recovery.integration.test.js.map +0 -1
- package/src/tools/handlers.js.map +0 -1
- package/src/tools/schema.js.map +0 -1
- package/src/tools/search/anthropic.js.map +0 -1
- package/src/tools/search/content.js.map +0 -1
- package/src/tools/search/content.test.js.map +0 -1
- package/src/tools/search/firecrawl.js.map +0 -1
- package/src/tools/search/format.js.map +0 -1
- package/src/tools/search/highlights.js.map +0 -1
- package/src/tools/search/index.js.map +0 -1
- package/src/tools/search/jina-reranker.test.js.map +0 -1
- package/src/tools/search/output.md +0 -2775
- package/src/tools/search/rerankers.js.map +0 -1
- package/src/tools/search/schema.js.map +0 -1
- package/src/tools/search/search.js.map +0 -1
- package/src/tools/search/serper-scraper.js.map +0 -1
- package/src/tools/search/test.html +0 -884
- package/src/tools/search/test.js.map +0 -1
- package/src/tools/search/test.md +0 -643
- package/src/tools/search/test.ts +0 -159
- package/src/tools/search/tool.js.map +0 -1
- package/src/tools/search/types.js.map +0 -1
- package/src/tools/search/utils.js.map +0 -1
- package/src/types/graph.js.map +0 -1
- package/src/types/graph.test.js.map +0 -1
- package/src/types/index.js.map +0 -1
- package/src/types/llm.js.map +0 -1
- package/src/types/messages.js.map +0 -1
- package/src/types/run.js.map +0 -1
- package/src/types/stream.js.map +0 -1
- package/src/types/tools.js.map +0 -1
- package/src/utils/contextAnalytics.js.map +0 -1
- package/src/utils/contextAnalytics.test.js.map +0 -1
- package/src/utils/events.js.map +0 -1
- package/src/utils/graph.js.map +0 -1
- package/src/utils/handlers.js.map +0 -1
- package/src/utils/index.js.map +0 -1
- package/src/utils/llm.js.map +0 -1
- package/src/utils/llmConfig.js.map +0 -1
- package/src/utils/logging.js.map +0 -1
- package/src/utils/misc.js.map +0 -1
- package/src/utils/run.js.map +0 -1
- package/src/utils/schema.js.map +0 -1
- package/src/utils/title.js.map +0 -1
- package/src/utils/tokens.js.map +0 -1
- package/src/utils/toonFormat.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Graph.mjs","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 this.stepKeyIds = resetIfNotEmpty(this.stepKeyIds, new Map());\n /**\n * Clear in-place instead of replacing with a new Map to preserve the\n * shared reference held by ToolNode (passed at construction time).\n * Using resetIfNotEmpty would create a new Map, leaving ToolNode with\n * a stale reference on 2nd+ processStream calls.\n */\n this.toolCallStepIds.clear();\n this.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 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":["ToolOutputReferenceRegistryClass","CustomToolNode","makeStructuredTool"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AACA;AAgHA,MAAM,EAAE,KAAK,EAAE,KAAK,EAAE,GAAG,aAAa;MAEhB,KAAK,CAAA;AA0DzB,IAAA,uBAAuB,GAAyB,IAAI,GAAG,EAAE;AACzD,IAAA,mBAAmB,GAAwB,IAAI,GAAG,EAAE;AACpD,IAAA,yBAAyB,GAAwB,IAAI,GAAG,EAAE;AAC1D,IAAA,MAAM;IACN,WAAW,GAAgB,EAAE;AAC7B,IAAA,UAAU,GAA0B,IAAI,GAAG,EAAoB;AAC/D,IAAA,eAAe,GAAwB,IAAI,GAAG,EAAE;AAChD,IAAA,eAAe,GAAwB,IAAI,GAAG,EAAE;AAChD,IAAA,MAAM;;AAEN,IAAA,cAAc;AACd,IAAA,eAAe;;AAEf,IAAA,YAAY;AACZ;;;;;;;;;;AAUG;AACH,IAAA,kBAAkB;AAClB;;;;;;AAMG;AACH,IAAA,oBAAoB;AACpB;;;;;AAKG;AACK,IAAA,mBAAmB;AAE3B;;;;;;;;;;;;AAYG;IACI,6BAA6B,GAAA;;;AAKlC,QAAA,IAAI,IAAI,CAAC,kBAAkB,IAAI,IAAI,EAAE;YACnC,OAAO,IAAI,CAAC,kBAAk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,MAAM,uBAAuB,CAAC,WAAW,CAAC,iBAAiB,EAAE,YAAY,CAAC;IAC5E;AAEA,IAAA,MAAM,oBAAoB,CAAC,EAAU,EAAE,KAAqB,EAAA;AAC1D,QAAA,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE;AAChB,YAAA,MAAM,IAAI,KAAK,CAAC,oBAAoB,CAAC;QACvC;AACA,QAAA,MAAM,YAAY,GAAwB;YACxC,EAAE;YACF,KAAK;SACN;;QAED,MAAM,uBAAuB,CAAC,WAAW,CAAC,gBAAgB,EAAE,YAAY,CAAC;IAC3E;AAEA,IAAA,sBAAsB,GAAG,OACvB,MAAc,EACd,KAAuB,KACN;AACjB,QAAA,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE;AAChB,YAAA,MAAM,IAAI,KAAK,CAAC,oBAAoB,CAAC;QACvC;AACA,QAAA,MAAM,cAAc,GAA0B;AAC5C,YAAA,EAAE,EAAE,MAAM;YACV,KAAK;SACN;;QAED,MAAM,uBAAuB,CAC3B,WAAW,CAAC,kBAAkB,EAC9B,cAAc,CACf;AACH,IAAA,CAAC;AACF;;;;"}
|
|
1
|
+
{"version":3,"file":"Graph.mjs","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 * (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 (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 this.stepKeyIds = resetIfNotEmpty(this.stepKeyIds, new Map());\n /**\n * Clear in-place instead of replacing with a new Map to preserve the\n * shared reference held by ToolNode (passed at construction time).\n * Using resetIfNotEmpty would create a new Map, leaving ToolNode with\n * a stale reference on 2nd+ processStream calls.\n */\n this.toolCallStepIds.clear();\n this.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 (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 * the 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 (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 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":["ToolOutputReferenceRegistryClass","CustomToolNode","makeStructuredTool"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AACA;AAgHA,MAAM,EAAE,KAAK,EAAE,KAAK,EAAE,GAAG,aAAa;MAEhB,KAAK,CAAA;AA0DzB,IAAA,uBAAuB,GAAyB,IAAI,GAAG,EAAE;AACzD,IAAA,mBAAmB,GAAwB,IAAI,GAAG,EAAE;AACpD,IAAA,yBAAyB,GAAwB,IAAI,GAAG,EAAE;AAC1D,IAAA,MAAM;IACN,WAAW,GAAgB,EAAE;AAC7B,IAAA,UAAU,GAA0B,IAAI,GAAG,EAAoB;AAC/D,IAAA,eAAe,GAAwB,IAAI,GAAG,EAAE;AAChD,IAAA,eAAe,GAAwB,IAAI,GAAG,EAAE;AAChD,IAAA,MAAM;;AAEN,IAAA,cAAc;AACd,IAAA,eAAe;;AAEf,IAAA,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