@illuma-ai/agents 1.4.0-alpha.6 → 1.5.0
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/README.md +62 -0
- package/dist/cjs/agents/AgentContext.cjs +274 -67
- package/dist/cjs/agents/AgentContext.cjs.map +1 -1
- package/dist/cjs/common/enum.cjs +44 -13
- package/dist/cjs/common/enum.cjs.map +1 -1
- package/dist/cjs/graphs/Graph.cjs +182 -5
- package/dist/cjs/graphs/Graph.cjs.map +1 -1
- package/dist/cjs/graphs/MultiAgentGraph.cjs +152 -1167
- package/dist/cjs/graphs/MultiAgentGraph.cjs.map +1 -1
- package/dist/cjs/hooks/HookRegistry.cjs +162 -0
- package/dist/cjs/hooks/HookRegistry.cjs.map +1 -0
- package/dist/cjs/hooks/executeHooks.cjs +276 -0
- package/dist/cjs/hooks/executeHooks.cjs.map +1 -0
- package/dist/cjs/hooks/matchers.cjs +256 -0
- package/dist/cjs/hooks/matchers.cjs.map +1 -0
- package/dist/cjs/hooks/types.cjs +27 -0
- package/dist/cjs/hooks/types.cjs.map +1 -0
- package/dist/cjs/langchain/google-common.cjs +3 -0
- package/dist/cjs/langchain/google-common.cjs.map +1 -0
- package/dist/cjs/langchain/index.cjs +86 -0
- package/dist/cjs/langchain/index.cjs.map +1 -0
- package/dist/cjs/langchain/language_models/chat_models.cjs +3 -0
- package/dist/cjs/langchain/language_models/chat_models.cjs.map +1 -0
- package/dist/cjs/langchain/messages/tool.cjs +3 -0
- package/dist/cjs/langchain/messages/tool.cjs.map +1 -0
- package/dist/cjs/langchain/messages.cjs +51 -0
- package/dist/cjs/langchain/messages.cjs.map +1 -0
- package/dist/cjs/langchain/openai.cjs +3 -0
- package/dist/cjs/langchain/openai.cjs.map +1 -0
- package/dist/cjs/langchain/prompts.cjs +11 -0
- package/dist/cjs/langchain/prompts.cjs.map +1 -0
- package/dist/cjs/langchain/runnables.cjs +19 -0
- package/dist/cjs/langchain/runnables.cjs.map +1 -0
- package/dist/cjs/langchain/tools.cjs +23 -0
- package/dist/cjs/langchain/tools.cjs.map +1 -0
- package/dist/cjs/langchain/utils/env.cjs +11 -0
- package/dist/cjs/langchain/utils/env.cjs.map +1 -0
- package/dist/cjs/llm/anthropic/utils/message_inputs.cjs +5 -1
- package/dist/cjs/llm/anthropic/utils/message_inputs.cjs.map +1 -1
- package/dist/cjs/llm/bedrock/cacheSupport.cjs +55 -0
- package/dist/cjs/llm/bedrock/cacheSupport.cjs.map +1 -0
- package/dist/cjs/llm/bedrock/index.cjs +61 -33
- package/dist/cjs/llm/bedrock/index.cjs.map +1 -1
- package/dist/cjs/llm/openai/index.cjs +0 -3
- package/dist/cjs/llm/openai/index.cjs.map +1 -1
- package/dist/cjs/llm/openai/utils/index.cjs +27 -10
- package/dist/cjs/llm/openai/utils/index.cjs.map +1 -1
- package/dist/cjs/main.cjs +178 -127
- package/dist/cjs/main.cjs.map +1 -1
- package/dist/cjs/messages/cache.cjs +89 -0
- package/dist/cjs/messages/cache.cjs.map +1 -1
- package/dist/cjs/messages/contextPruning.cjs +156 -0
- package/dist/cjs/messages/contextPruning.cjs.map +1 -0
- package/dist/cjs/messages/contextPruningSettings.cjs +53 -0
- package/dist/cjs/messages/contextPruningSettings.cjs.map +1 -0
- package/dist/cjs/messages/format.cjs +144 -20
- package/dist/cjs/messages/format.cjs.map +1 -1
- package/dist/cjs/messages/prune.cjs +505 -4
- package/dist/cjs/messages/prune.cjs.map +1 -1
- package/dist/cjs/run.cjs +141 -1
- package/dist/cjs/run.cjs.map +1 -1
- package/dist/cjs/tools/BashExecutor.cjs +235 -0
- package/dist/cjs/tools/BashExecutor.cjs.map +1 -0
- package/dist/cjs/tools/BashProgrammaticToolCalling.cjs +297 -0
- package/dist/cjs/tools/BashProgrammaticToolCalling.cjs.map +1 -0
- package/dist/cjs/tools/CodeExecutor.cjs +44 -47
- package/dist/cjs/tools/CodeExecutor.cjs.map +1 -1
- package/dist/cjs/tools/ProgrammaticToolCalling.cjs +16 -11
- package/dist/cjs/tools/ProgrammaticToolCalling.cjs.map +1 -1
- package/dist/cjs/tools/ReadFile.cjs +44 -0
- package/dist/cjs/tools/ReadFile.cjs.map +1 -0
- package/dist/cjs/tools/SkillTool.cjs +51 -0
- package/dist/cjs/tools/SkillTool.cjs.map +1 -0
- package/dist/cjs/tools/SubagentTool.cjs +93 -0
- package/dist/cjs/tools/SubagentTool.cjs.map +1 -0
- package/dist/cjs/tools/ToolNode.cjs +450 -24
- package/dist/cjs/tools/ToolNode.cjs.map +1 -1
- package/dist/cjs/tools/search/search.cjs +11 -3
- package/dist/cjs/tools/search/search.cjs.map +1 -1
- package/dist/cjs/tools/search/tavily-scraper.cjs +189 -0
- package/dist/cjs/tools/search/tavily-scraper.cjs.map +1 -0
- package/dist/cjs/tools/search/tavily-search.cjs +372 -0
- package/dist/cjs/tools/search/tavily-search.cjs.map +1 -0
- package/dist/cjs/tools/search/tool.cjs +28 -4
- package/dist/cjs/tools/search/tool.cjs.map +1 -1
- package/dist/cjs/tools/search/utils.cjs +10 -3
- package/dist/cjs/tools/search/utils.cjs.map +1 -1
- package/dist/cjs/tools/skillCatalog.cjs +84 -0
- package/dist/cjs/tools/skillCatalog.cjs.map +1 -0
- package/dist/cjs/tools/subagent/SubagentExecutor.cjs +512 -0
- package/dist/cjs/tools/subagent/SubagentExecutor.cjs.map +1 -0
- package/dist/cjs/tools/toolOutputReferences.cjs +670 -0
- package/dist/cjs/tools/toolOutputReferences.cjs.map +1 -0
- package/dist/cjs/types/agent-cache.cjs +53 -0
- package/dist/cjs/types/agent-cache.cjs.map +1 -0
- package/dist/cjs/types/graph.cjs.map +1 -1
- package/dist/cjs/utils/truncation.cjs +135 -0
- package/dist/cjs/utils/truncation.cjs.map +1 -0
- package/dist/esm/agents/AgentContext.mjs +274 -67
- package/dist/esm/agents/AgentContext.mjs.map +1 -1
- package/dist/esm/common/enum.mjs +44 -12
- package/dist/esm/common/enum.mjs.map +1 -1
- package/dist/esm/graphs/Graph.mjs +182 -5
- package/dist/esm/graphs/Graph.mjs.map +1 -1
- package/dist/esm/graphs/MultiAgentGraph.mjs +155 -1170
- package/dist/esm/graphs/MultiAgentGraph.mjs.map +1 -1
- package/dist/esm/hooks/HookRegistry.mjs +160 -0
- package/dist/esm/hooks/HookRegistry.mjs.map +1 -0
- package/dist/esm/hooks/executeHooks.mjs +273 -0
- package/dist/esm/hooks/executeHooks.mjs.map +1 -0
- package/dist/esm/hooks/matchers.mjs +251 -0
- package/dist/esm/hooks/matchers.mjs.map +1 -0
- package/dist/esm/hooks/types.mjs +25 -0
- package/dist/esm/hooks/types.mjs.map +1 -0
- package/dist/esm/langchain/google-common.mjs +2 -0
- package/dist/esm/langchain/google-common.mjs.map +1 -0
- package/dist/esm/langchain/index.mjs +5 -0
- package/dist/esm/langchain/language_models/chat_models.mjs +2 -0
- package/dist/esm/langchain/language_models/chat_models.mjs.map +1 -0
- package/dist/esm/langchain/messages/tool.mjs +2 -0
- package/dist/esm/langchain/messages/tool.mjs.map +1 -0
- package/dist/esm/langchain/messages.mjs +2 -0
- package/dist/esm/langchain/messages.mjs.map +1 -0
- package/dist/esm/langchain/openai.mjs +2 -0
- package/dist/esm/langchain/openai.mjs.map +1 -0
- package/dist/esm/langchain/prompts.mjs +2 -0
- package/dist/esm/langchain/prompts.mjs.map +1 -0
- package/dist/esm/langchain/runnables.mjs +2 -0
- package/dist/esm/langchain/runnables.mjs.map +1 -0
- package/dist/esm/langchain/tools.mjs +2 -0
- package/dist/esm/langchain/tools.mjs.map +1 -0
- package/dist/esm/langchain/utils/env.mjs +2 -0
- package/dist/esm/langchain/utils/env.mjs.map +1 -0
- package/dist/esm/llm/anthropic/utils/message_inputs.mjs +5 -1
- package/dist/esm/llm/anthropic/utils/message_inputs.mjs.map +1 -1
- package/dist/esm/llm/bedrock/cacheSupport.mjs +52 -0
- package/dist/esm/llm/bedrock/cacheSupport.mjs.map +1 -0
- package/dist/esm/llm/bedrock/index.mjs +61 -34
- package/dist/esm/llm/bedrock/index.mjs.map +1 -1
- package/dist/esm/llm/openai/index.mjs +0 -3
- package/dist/esm/llm/openai/index.mjs.map +1 -1
- package/dist/esm/llm/openai/utils/index.mjs +27 -10
- package/dist/esm/llm/openai/utils/index.mjs.map +1 -1
- package/dist/esm/main.mjs +21 -27
- package/dist/esm/main.mjs.map +1 -1
- package/dist/esm/messages/cache.mjs +89 -0
- package/dist/esm/messages/cache.mjs.map +1 -1
- package/dist/esm/messages/contextPruning.mjs +154 -0
- package/dist/esm/messages/contextPruning.mjs.map +1 -0
- package/dist/esm/messages/contextPruningSettings.mjs +50 -0
- package/dist/esm/messages/contextPruningSettings.mjs.map +1 -0
- package/dist/esm/messages/format.mjs +136 -12
- package/dist/esm/messages/format.mjs.map +1 -1
- package/dist/esm/messages/prune.mjs +504 -7
- package/dist/esm/messages/prune.mjs.map +1 -1
- package/dist/esm/run.mjs +141 -1
- package/dist/esm/run.mjs.map +1 -1
- package/dist/esm/tools/BashExecutor.mjs +227 -0
- package/dist/esm/tools/BashExecutor.mjs.map +1 -0
- package/dist/esm/tools/BashProgrammaticToolCalling.mjs +288 -0
- package/dist/esm/tools/BashProgrammaticToolCalling.mjs.map +1 -0
- package/dist/esm/tools/CodeExecutor.mjs +44 -48
- package/dist/esm/tools/CodeExecutor.mjs.map +1 -1
- package/dist/esm/tools/ProgrammaticToolCalling.mjs +17 -12
- package/dist/esm/tools/ProgrammaticToolCalling.mjs.map +1 -1
- package/dist/esm/tools/ReadFile.mjs +39 -0
- package/dist/esm/tools/ReadFile.mjs.map +1 -0
- package/dist/esm/tools/SkillTool.mjs +46 -0
- package/dist/esm/tools/SkillTool.mjs.map +1 -0
- package/dist/esm/tools/SubagentTool.mjs +86 -0
- package/dist/esm/tools/SubagentTool.mjs.map +1 -0
- package/dist/esm/tools/ToolNode.mjs +452 -26
- package/dist/esm/tools/ToolNode.mjs.map +1 -1
- package/dist/esm/tools/search/search.mjs +11 -3
- package/dist/esm/tools/search/search.mjs.map +1 -1
- package/dist/esm/tools/search/tavily-scraper.mjs +186 -0
- package/dist/esm/tools/search/tavily-scraper.mjs.map +1 -0
- package/dist/esm/tools/search/tavily-search.mjs +370 -0
- package/dist/esm/tools/search/tavily-search.mjs.map +1 -0
- package/dist/esm/tools/search/tool.mjs +28 -4
- package/dist/esm/tools/search/tool.mjs.map +1 -1
- package/dist/esm/tools/search/utils.mjs +10 -3
- package/dist/esm/tools/search/utils.mjs.map +1 -1
- package/dist/esm/tools/skillCatalog.mjs +82 -0
- package/dist/esm/tools/skillCatalog.mjs.map +1 -0
- package/dist/esm/tools/subagent/SubagentExecutor.mjs +506 -0
- package/dist/esm/tools/subagent/SubagentExecutor.mjs.map +1 -0
- package/dist/esm/tools/toolOutputReferences.mjs +662 -0
- package/dist/esm/tools/toolOutputReferences.mjs.map +1 -0
- package/dist/esm/types/agent-cache.mjs +51 -0
- package/dist/esm/types/agent-cache.mjs.map +1 -0
- package/dist/esm/types/graph.mjs.map +1 -1
- package/dist/esm/utils/truncation.mjs +128 -0
- package/dist/esm/utils/truncation.mjs.map +1 -0
- package/dist/types/agents/AgentContext.d.ts +101 -8
- package/dist/types/common/enum.d.ts +39 -12
- package/dist/types/common/index.d.ts +0 -1
- package/dist/types/graphs/Graph.d.ts +43 -0
- package/dist/types/graphs/MultiAgentGraph.d.ts +26 -150
- package/dist/types/graphs/index.d.ts +0 -1
- package/dist/types/hooks/HookRegistry.d.ts +56 -0
- package/dist/types/hooks/executeHooks.d.ts +79 -0
- package/dist/types/hooks/index.d.ts +6 -0
- package/dist/types/hooks/matchers.d.ts +95 -0
- package/dist/types/hooks/types.d.ts +320 -0
- package/dist/types/index.d.ts +9 -9
- package/dist/types/langchain/google-common.d.ts +1 -0
- package/dist/types/langchain/index.d.ts +8 -0
- package/dist/types/langchain/language_models/chat_models.d.ts +1 -0
- package/dist/types/langchain/messages/tool.d.ts +1 -0
- package/dist/types/langchain/messages.d.ts +2 -0
- package/dist/types/langchain/openai.d.ts +1 -0
- package/dist/types/langchain/prompts.d.ts +1 -0
- package/dist/types/langchain/runnables.d.ts +2 -0
- package/dist/types/langchain/tools.d.ts +2 -0
- package/dist/types/langchain/utils/env.d.ts +1 -0
- package/dist/types/llm/bedrock/cacheSupport.d.ts +35 -0
- package/dist/types/llm/bedrock/index.d.ts +54 -1
- package/dist/types/messages/contextPruning.d.ts +42 -0
- package/dist/types/messages/contextPruningSettings.d.ts +44 -0
- package/dist/types/messages/format.d.ts +9 -1
- package/dist/types/messages/index.d.ts +2 -0
- package/dist/types/messages/prune.d.ts +91 -1
- package/dist/types/run.d.ts +2 -0
- package/dist/types/tools/BashExecutor.d.ts +76 -0
- package/dist/types/tools/BashProgrammaticToolCalling.d.ts +72 -0
- package/dist/types/tools/CodeExecutor.d.ts +8 -26
- package/dist/types/tools/ReadFile.d.ts +28 -0
- package/dist/types/tools/SkillTool.d.ts +40 -0
- package/dist/types/tools/SubagentTool.d.ts +36 -0
- package/dist/types/tools/ToolNode.d.ts +77 -5
- package/dist/types/tools/search/tavily-scraper.d.ts +19 -0
- package/dist/types/tools/search/tavily-search.d.ts +4 -0
- package/dist/types/tools/search/types.d.ts +99 -5
- package/dist/types/tools/search/utils.d.ts +2 -2
- package/dist/types/tools/skillCatalog.d.ts +19 -0
- package/dist/types/tools/subagent/SubagentExecutor.d.ts +137 -0
- package/dist/types/tools/subagent/index.d.ts +2 -0
- package/dist/types/tools/subagent/types.d.ts +84 -0
- package/dist/types/tools/toolOutputReferences.d.ts +236 -0
- package/dist/types/types/agent-cache.d.ts +70 -0
- package/dist/types/types/graph.d.ts +162 -22
- package/dist/types/types/index.d.ts +3 -0
- package/dist/types/types/messages.d.ts +26 -0
- package/dist/types/types/run.d.ts +22 -0
- package/dist/types/types/skill.d.ts +9 -0
- package/dist/types/types/tools.d.ts +111 -0
- package/dist/types/utils/index.d.ts +1 -3
- package/dist/types/utils/truncation.d.ts +70 -0
- package/package.json +57 -17
- package/src/agents/AgentContext.js.map +1 -0
- package/src/agents/AgentContext.test.js.map +1 -0
- package/src/agents/AgentContext.ts +321 -78
- package/src/agents/__tests__/AgentContext.cacheTtl.live.test.ts +259 -0
- package/src/agents/__tests__/AgentContext.crossAgentTier1.live.test.ts +264 -0
- package/src/agents/__tests__/AgentContext.crossUserCache.live.test.ts +342 -0
- package/src/agents/__tests__/AgentContext.test.js.map +1 -0
- package/src/agents/__tests__/AgentContext.test.ts +632 -0
- package/src/agents/__tests__/resolveStructuredOutputMode.test.js.map +1 -0
- package/src/common/__tests__/enum.test.ts +7 -17
- package/src/common/enum.js.map +1 -0
- package/src/common/enum.ts +43 -12
- package/src/common/index.js.map +1 -0
- package/src/common/index.ts +0 -1
- package/src/events.js.map +1 -0
- package/src/graphs/Graph.js.map +1 -0
- package/src/graphs/Graph.ts +222 -2
- package/src/graphs/MultiAgentGraph.js.map +1 -0
- package/src/graphs/MultiAgentGraph.ts +154 -1466
- package/src/graphs/__tests__/MultiAgentGraph.test.ts +91 -0
- package/src/graphs/__tests__/structured-output.integration.test.js.map +1 -0
- package/src/graphs/__tests__/structured-output.test.js.map +1 -0
- package/src/graphs/contextManagement.e2e.test.js.map +1 -0
- package/src/graphs/contextManagement.test.js.map +1 -0
- package/src/graphs/handoffValidation.test.js.map +1 -0
- package/src/graphs/index.js.map +1 -0
- package/src/graphs/index.ts +0 -1
- package/src/hooks/HookRegistry.ts +208 -0
- package/src/hooks/__tests__/HookRegistry.test.ts +190 -0
- package/src/hooks/__tests__/compactHooks.test.ts +214 -0
- package/src/hooks/__tests__/executeHooks.test.ts +1013 -0
- package/src/hooks/__tests__/integration.test.ts +337 -0
- package/src/hooks/__tests__/matchers.test.ts +238 -0
- package/src/hooks/__tests__/toolHooks.test.ts +665 -0
- package/src/hooks/executeHooks.ts +375 -0
- package/src/hooks/index.ts +57 -0
- package/src/hooks/matchers.ts +280 -0
- package/src/hooks/types.ts +404 -0
- package/src/index.js.map +1 -0
- package/src/index.ts +15 -24
- package/src/instrumentation.js.map +1 -0
- package/src/langchain/google-common.ts +1 -0
- package/src/langchain/index.ts +8 -0
- package/src/langchain/language_models/chat_models.ts +1 -0
- package/src/langchain/messages/tool.ts +5 -0
- package/src/langchain/messages.ts +21 -0
- package/src/langchain/openai.ts +1 -0
- package/src/langchain/prompts.ts +1 -0
- package/src/langchain/runnables.ts +7 -0
- package/src/langchain/tools.ts +8 -0
- package/src/langchain/utils/env.ts +1 -0
- package/src/llm/anthropic/index.js.map +1 -0
- package/src/llm/anthropic/types.js.map +1 -0
- package/src/llm/anthropic/utils/message_inputs.js.map +1 -0
- package/src/llm/anthropic/utils/message_inputs.ts +10 -1
- package/src/llm/anthropic/utils/message_outputs.js.map +1 -0
- package/src/llm/anthropic/utils/output_parsers.js.map +1 -0
- package/src/llm/anthropic/utils/server-tool-inputs.test.ts +436 -0
- package/src/llm/anthropic/utils/tools.js.map +1 -0
- package/src/llm/bedrock/__tests__/bedrock-caching.test.js.map +1 -0
- package/src/llm/bedrock/__tests__/bedrock-caching.test.ts +166 -18
- package/src/llm/bedrock/cacheSupport.test.ts +99 -0
- package/src/llm/bedrock/cacheSupport.ts +53 -0
- package/src/llm/bedrock/index.js.map +1 -0
- package/src/llm/bedrock/index.ts +116 -41
- package/src/llm/bedrock/types.js.map +1 -0
- package/src/llm/bedrock/utils/index.js.map +1 -0
- package/src/llm/bedrock/utils/message_inputs.js.map +1 -0
- package/src/llm/bedrock/utils/message_outputs.js.map +1 -0
- package/src/llm/fake.js.map +1 -0
- package/src/llm/google/index.js.map +1 -0
- package/src/llm/google/types.js.map +1 -0
- package/src/llm/google/utils/common.js.map +1 -0
- package/src/llm/google/utils/tools.js.map +1 -0
- package/src/llm/google/utils/zod_to_genai_parameters.js.map +1 -0
- package/src/llm/openai/index.js.map +1 -0
- package/src/llm/openai/types.js.map +1 -0
- package/src/llm/openai/utils/index.js.map +1 -0
- package/src/llm/openai/utils/index.ts +31 -14
- package/src/llm/openai/utils/isReasoningModel.test.js.map +1 -0
- package/src/llm/openrouter/index.js.map +1 -0
- package/src/llm/openrouter/reasoning.test.js.map +1 -0
- package/src/llm/providers.js.map +1 -0
- package/src/llm/text.js.map +1 -0
- package/src/llm/vertexai/index.js.map +1 -0
- package/src/messages/__tests__/contextPruning.test.ts +228 -0
- package/src/messages/__tests__/tools.test.js.map +1 -0
- package/src/messages/cache.js.map +1 -0
- package/src/messages/cache.test.js.map +1 -0
- package/src/messages/cache.test.ts +62 -24
- package/src/messages/cache.ts +112 -0
- package/src/messages/content.js.map +1 -0
- package/src/messages/content.test.js.map +1 -0
- package/src/messages/contextPruning.ts +191 -0
- package/src/messages/contextPruningSettings.ts +90 -0
- package/src/messages/core.js.map +1 -0
- package/src/messages/ensureThinkingBlock.test.js.map +1 -0
- package/src/messages/format.js.map +1 -0
- package/src/messages/format.ts +164 -12
- package/src/messages/formatAgentMessages.skills.test.ts +413 -0
- package/src/messages/formatAgentMessages.test.js.map +1 -0
- package/src/messages/formatAgentMessages.tools.test.js.map +1 -0
- package/src/messages/formatMessage.test.js.map +1 -0
- package/src/messages/ids.js.map +1 -0
- package/src/messages/index.js.map +1 -0
- package/src/messages/index.ts +2 -0
- package/src/messages/labelContentByAgent.test.js.map +1 -0
- package/src/messages/prune.js.map +1 -0
- package/src/messages/prune.ts +661 -4
- package/src/messages/reducer.js.map +1 -0
- package/src/messages/shiftIndexTokenCountMap.test.js.map +1 -0
- package/src/messages/summarize.js.map +1 -0
- package/src/messages/summarize.test.js.map +1 -0
- package/src/messages/tools.js.map +1 -0
- package/src/mockStream.js.map +1 -0
- package/src/prompts/collab.js.map +1 -0
- package/src/prompts/index.js.map +1 -0
- package/src/prompts/taskmanager.js.map +1 -0
- package/src/run.js.map +1 -0
- package/src/run.ts +155 -1
- package/src/schemas/index.js.map +1 -0
- package/src/schemas/schema-preparation.test.js.map +1 -0
- package/src/schemas/validate.js.map +1 -0
- package/src/schemas/validate.test.js.map +1 -0
- package/src/scripts/abort.js.map +1 -0
- package/src/scripts/ant_web_search.js.map +1 -0
- package/src/scripts/ant_web_search_edge_case.js.map +1 -0
- package/src/scripts/ant_web_search_error_edge_case.js.map +1 -0
- package/src/scripts/args.js.map +1 -0
- package/src/scripts/bedrock-cache-debug.js.map +1 -0
- package/src/scripts/bedrock-content-aggregation-test.js.map +1 -0
- package/src/scripts/bedrock-merge-test.js.map +1 -0
- package/src/scripts/bedrock-parallel-tools-test.js.map +1 -0
- package/src/scripts/caching.js.map +1 -0
- package/src/scripts/cli.js.map +1 -0
- package/src/scripts/cli2.js.map +1 -0
- package/src/scripts/cli3.js.map +1 -0
- package/src/scripts/cli4.js.map +1 -0
- package/src/scripts/cli5.js.map +1 -0
- package/src/scripts/code_exec.js.map +1 -0
- package/src/scripts/code_exec_files.js.map +1 -0
- package/src/scripts/code_exec_multi_session.js.map +1 -0
- package/src/scripts/code_exec_ptc.js.map +1 -0
- package/src/scripts/code_exec_session.js.map +1 -0
- package/src/scripts/code_exec_simple.js.map +1 -0
- package/src/scripts/content.js.map +1 -0
- package/src/scripts/empty_input.js.map +1 -0
- package/src/scripts/handoff-test.js.map +1 -0
- package/src/scripts/image.js.map +1 -0
- package/src/scripts/memory.js.map +1 -0
- package/src/scripts/multi-agent-chain.js.map +1 -0
- package/src/scripts/multi-agent-chain.ts +2 -2
- package/src/scripts/multi-agent-conditional.js.map +1 -0
- package/src/scripts/multi-agent-document-review-chain.js.map +1 -0
- package/src/scripts/multi-agent-document-review-chain.ts +2 -2
- package/src/scripts/multi-agent-hybrid-flow.js.map +1 -0
- package/src/scripts/multi-agent-hybrid-flow.ts +4 -4
- package/src/scripts/multi-agent-parallel-start.js.map +1 -0
- package/src/scripts/multi-agent-parallel.js.map +1 -0
- package/src/scripts/multi-agent-parallel.ts +3 -3
- package/src/scripts/multi-agent-sequence.js.map +1 -0
- package/src/scripts/multi-agent-sequence.ts +3 -3
- package/src/scripts/multi-agent-subagent.ts +246 -0
- package/src/scripts/multi-agent-supervisor.js.map +1 -0
- package/src/scripts/multi-agent-supervisor.ts +5 -5
- package/src/scripts/multi-agent-test.js.map +1 -0
- package/src/scripts/parallel-asymmetric-tools-test.js.map +1 -0
- package/src/scripts/parallel-full-metadata-test.js.map +1 -0
- package/src/scripts/parallel-tools-test.js.map +1 -0
- package/src/scripts/poc-multi-agent-comprehensive.ts +8 -8
- package/src/scripts/programmatic_exec.js.map +1 -0
- package/src/scripts/programmatic_exec_agent.js.map +1 -0
- package/src/scripts/search.js.map +1 -0
- package/src/scripts/sequential-full-metadata-test.js.map +1 -0
- package/src/scripts/sequential-full-metadata-test.ts +2 -2
- package/src/scripts/simple.js.map +1 -0
- package/src/scripts/single-agent-metadata-test.js.map +1 -0
- package/src/scripts/stream.js.map +1 -0
- package/src/scripts/subagent-event-driven-debug.ts +190 -0
- package/src/scripts/subagent-tools-debug.ts +160 -0
- package/src/scripts/test-custom-prompt-key.js.map +1 -0
- package/src/scripts/test-custom-prompt-key.ts +3 -3
- package/src/scripts/test-handoff-input.js.map +1 -0
- package/src/scripts/test-handoff-input.ts +1 -1
- package/src/scripts/test-handoff-preamble.js.map +1 -0
- package/src/scripts/test-handoff-steering.js.map +1 -0
- package/src/scripts/test-handoff-steering.ts +3 -3
- package/src/scripts/test-multi-agent-list-handoff.js.map +1 -0
- package/src/scripts/test-multi-agent-list-handoff.ts +1 -1
- package/src/scripts/test-parallel-agent-labeling.js.map +1 -0
- package/src/scripts/test-parallel-agent-labeling.ts +3 -3
- package/src/scripts/test-parallel-handoffs.js.map +1 -0
- package/src/scripts/test-parallel-handoffs.ts +2 -2
- package/src/scripts/test-thinking-handoff-bedrock.js.map +1 -0
- package/src/scripts/test-thinking-handoff-bedrock.ts +1 -1
- package/src/scripts/test-thinking-handoff.js.map +1 -0
- package/src/scripts/test-thinking-handoff.ts +1 -1
- package/src/scripts/test-thinking-to-thinking-handoff-bedrock.js.map +1 -0
- package/src/scripts/test-thinking-to-thinking-handoff-bedrock.ts +1 -1
- package/src/scripts/test-tool-before-handoff-role-order.js.map +1 -0
- package/src/scripts/test-tool-before-handoff-role-order.ts +1 -1
- package/src/scripts/test-tools-before-handoff.js.map +1 -0
- package/src/scripts/test-tools-before-handoff.ts +1 -1
- package/src/scripts/test_code_api.js.map +1 -0
- package/src/scripts/thinking-bedrock.js.map +1 -0
- package/src/scripts/thinking-vertexai.js.map +1 -0
- package/src/scripts/thinking.js.map +1 -0
- package/src/scripts/tool_search.js.map +1 -0
- package/src/scripts/tools.js.map +1 -0
- package/src/specs/agent-handoffs-bedrock.integration.test.js.map +1 -0
- package/src/specs/agent-handoffs.test.js.map +1 -0
- package/src/specs/agent-handoffs.test.ts +26 -483
- package/src/specs/anthropic.simple.test.js.map +1 -0
- package/src/specs/anthropic.simple.test.ts +61 -0
- package/src/specs/azure.simple.test.js.map +1 -0
- package/src/specs/cache.simple.test.js.map +1 -0
- package/src/specs/custom-event-await.test.js.map +1 -0
- package/src/specs/deepseek.simple.test.js.map +1 -0
- package/src/specs/emergency-prune.test.js.map +1 -0
- package/src/specs/moonshot.simple.test.js.map +1 -0
- package/src/specs/multi-agent-summarization.test.ts +396 -0
- package/src/specs/observability.integration.test.js.map +1 -0
- package/src/specs/openai.simple.test.js.map +1 -0
- package/src/specs/openrouter.simple.test.js.map +1 -0
- package/src/specs/prune.orphans.test.ts +248 -0
- package/src/specs/prune.test.js.map +1 -0
- package/src/specs/prune.test.ts +104 -16
- package/src/specs/reasoning.test.js.map +1 -0
- package/src/specs/spec.utils.js.map +1 -0
- package/src/specs/thinking-handoff.test.js.map +1 -0
- package/src/specs/thinking-handoff.test.ts +19 -19
- package/src/specs/thinking-prune.test.js.map +1 -0
- package/src/specs/token-distribution-edge-case.test.js.map +1 -0
- package/src/specs/token-memoization.test.js.map +1 -0
- package/src/specs/tokens.test.js.map +1 -0
- package/src/specs/tool-error.test.js.map +1 -0
- package/src/splitStream.js.map +1 -0
- package/src/splitStream.test.js.map +1 -0
- package/src/stream.js.map +1 -0
- package/src/stream.test.js.map +1 -0
- package/src/test/mockTools.js.map +1 -0
- package/src/tools/BashExecutor.ts +281 -0
- package/src/tools/BashProgrammaticToolCalling.ts +397 -0
- package/src/tools/BrowserTools.js.map +1 -0
- package/src/tools/Calculator.js.map +1 -0
- package/src/tools/Calculator.test.js.map +1 -0
- package/src/tools/CodeExecutor.js.map +1 -0
- package/src/tools/CodeExecutor.ts +62 -54
- package/src/tools/ProgrammaticToolCalling.js.map +1 -0
- package/src/tools/ProgrammaticToolCalling.ts +29 -14
- package/src/tools/ReadFile.ts +39 -0
- package/src/tools/SkillTool.ts +46 -0
- package/src/tools/StreamingToolCallBuffer.js.map +1 -0
- package/src/tools/SubagentTool.ts +100 -0
- package/src/tools/ToolNode.js.map +1 -0
- package/src/tools/ToolNode.ts +548 -26
- package/src/tools/ToolSearch.js.map +1 -0
- package/src/tools/__tests__/BashExecutor.test.ts +49 -0
- package/src/tools/__tests__/BrowserTools.test.js.map +1 -0
- package/src/tools/__tests__/CodeExecutor.test.ts +37 -36
- package/src/tools/__tests__/ProgrammaticToolCalling.integration.test.js.map +1 -0
- package/src/tools/__tests__/ProgrammaticToolCalling.test.js.map +1 -0
- package/src/tools/__tests__/ProgrammaticToolCalling.test.ts +60 -0
- package/src/tools/__tests__/ReadFile.test.ts +44 -0
- package/src/tools/__tests__/SkillTool.test.ts +442 -0
- package/src/tools/__tests__/StreamingToolCallBuffer.test.js.map +1 -0
- package/src/tools/__tests__/SubagentExecutor.test.ts +1148 -0
- package/src/tools/__tests__/SubagentTool.test.ts +149 -0
- package/src/tools/__tests__/ToolApproval.test.js.map +1 -0
- package/src/tools/__tests__/ToolNode.outputReferences.test.ts +1438 -0
- package/src/tools/__tests__/ToolNode.recovery.test.js.map +1 -0
- package/src/tools/__tests__/ToolNode.session.test.js.map +1 -0
- package/src/tools/__tests__/ToolSearch.integration.test.js.map +1 -0
- package/src/tools/__tests__/ToolSearch.test.js.map +1 -0
- package/src/tools/__tests__/annotateMessagesForLLM.test.ts +479 -0
- package/src/tools/__tests__/handlers.test.js.map +1 -0
- package/src/tools/__tests__/skillCatalog.test.ts +161 -0
- package/src/tools/__tests__/subagentHooks.test.ts +210 -0
- package/src/tools/__tests__/toolOutputReferences.test.ts +415 -0
- package/src/tools/__tests__/truncation-recovery.integration.test.js.map +1 -0
- package/src/tools/handlers.js.map +1 -0
- package/src/tools/schema.js.map +1 -0
- package/src/tools/search/anthropic.js.map +1 -0
- package/src/tools/search/content.js.map +1 -0
- package/src/tools/search/content.test.js.map +1 -0
- package/src/tools/search/firecrawl.js.map +1 -0
- package/src/tools/search/format.js.map +1 -0
- package/src/tools/search/highlights.js.map +1 -0
- package/src/tools/search/index.js.map +1 -0
- package/src/tools/search/jina-reranker.test.js.map +1 -0
- package/src/tools/search/rerankers.js.map +1 -0
- package/src/tools/search/schema.js.map +1 -0
- package/src/tools/search/search.js.map +1 -0
- package/src/tools/search/search.ts +12 -2
- package/src/tools/search/serper-scraper.js.map +1 -0
- package/src/tools/search/tavily-scraper.ts +235 -0
- package/src/tools/search/tavily-search.ts +424 -0
- package/src/tools/search/tavily.test.ts +965 -0
- package/src/tools/search/test.js.map +1 -0
- package/src/tools/search/tool.js.map +1 -0
- package/src/tools/search/tool.ts +36 -2
- package/src/tools/search/types.js.map +1 -0
- package/src/tools/search/types.ts +133 -8
- package/src/tools/search/utils.js.map +1 -0
- package/src/tools/search/utils.ts +13 -5
- package/src/tools/skillCatalog.ts +126 -0
- package/src/tools/subagent/SubagentExecutor.ts +676 -0
- package/src/tools/subagent/index.ts +13 -0
- package/src/tools/subagent/types.test.ts +70 -0
- package/src/tools/subagent/types.ts +115 -0
- package/src/tools/toolOutputReferences.ts +825 -0
- package/src/types/agent-cache.ts +73 -0
- package/src/types/graph.js.map +1 -0
- package/src/types/graph.test.js.map +1 -0
- package/src/types/graph.ts +171 -20
- package/src/types/index.js.map +1 -0
- package/src/types/index.ts +3 -0
- package/src/types/llm.js.map +1 -0
- package/src/types/messages.js.map +1 -0
- package/src/types/messages.ts +27 -0
- package/src/types/run.js.map +1 -0
- package/src/types/run.ts +22 -0
- package/src/types/skill.ts +11 -0
- package/src/types/stream.js.map +1 -0
- package/src/types/tools.js.map +1 -0
- package/src/types/tools.ts +118 -0
- package/src/utils/__tests__/truncation.test.ts +66 -0
- package/src/utils/contextAnalytics.js.map +1 -0
- package/src/utils/contextAnalytics.test.js.map +1 -0
- package/src/utils/events.js.map +1 -0
- package/src/utils/graph.js.map +1 -0
- package/src/utils/handlers.js.map +1 -0
- package/src/utils/index.js.map +1 -0
- package/src/utils/index.ts +1 -3
- package/src/utils/llm.js.map +1 -0
- package/src/utils/llmConfig.js.map +1 -0
- package/src/utils/logging.js.map +1 -0
- package/src/utils/misc.js.map +1 -0
- package/src/utils/run.js.map +1 -0
- package/src/utils/schema.js.map +1 -0
- package/src/utils/title.js.map +1 -0
- package/src/utils/tokens.js.map +1 -0
- package/src/utils/toonFormat.js.map +1 -0
- package/src/utils/truncation.ts +154 -0
- package/dist/cjs/common/spawnPath.cjs +0 -104
- package/dist/cjs/common/spawnPath.cjs.map +0 -1
- package/dist/cjs/content/ArtifactStore.cjs +0 -579
- package/dist/cjs/content/ArtifactStore.cjs.map +0 -1
- package/dist/cjs/content/ContentStore.cjs +0 -638
- package/dist/cjs/content/ContentStore.cjs.map +0 -1
- package/dist/cjs/content/contentAnalyzer.cjs +0 -91
- package/dist/cjs/content/contentAnalyzer.cjs.map +0 -1
- package/dist/cjs/content/index.cjs +0 -20
- package/dist/cjs/content/index.cjs.map +0 -1
- package/dist/cjs/content/mcpAutoCache.cjs +0 -115
- package/dist/cjs/content/mcpAutoCache.cjs.map +0 -1
- package/dist/cjs/graphs/HandoffRegistry.cjs +0 -143
- package/dist/cjs/graphs/HandoffRegistry.cjs.map +0 -1
- package/dist/cjs/providers/a2a/A2ACapabilityProvider.cjs +0 -288
- package/dist/cjs/providers/a2a/A2ACapabilityProvider.cjs.map +0 -1
- package/dist/cjs/providers/a2a/client.cjs +0 -92
- package/dist/cjs/providers/a2a/client.cjs.map +0 -1
- package/dist/cjs/providers/a2a/config.cjs +0 -38
- package/dist/cjs/providers/a2a/config.cjs.map +0 -1
- package/dist/cjs/providers/capabilityNaming.cjs +0 -43
- package/dist/cjs/providers/capabilityNaming.cjs.map +0 -1
- package/dist/cjs/providers/mcp/MCPCapabilityProvider.cjs +0 -244
- package/dist/cjs/providers/mcp/MCPCapabilityProvider.cjs.map +0 -1
- package/dist/cjs/providers/mcp/config.cjs +0 -42
- package/dist/cjs/providers/mcp/config.cjs.map +0 -1
- package/dist/cjs/providers/mcp/transport.cjs +0 -65
- package/dist/cjs/providers/mcp/transport.cjs.map +0 -1
- package/dist/cjs/providers/tools-server/ToolsServerCapabilityProvider.cjs +0 -128
- package/dist/cjs/providers/tools-server/ToolsServerCapabilityProvider.cjs.map +0 -1
- package/dist/cjs/providers/types.cjs +0 -51
- package/dist/cjs/providers/types.cjs.map +0 -1
- package/dist/cjs/tools/artifacts/schema.cjs +0 -86
- package/dist/cjs/tools/artifacts/schema.cjs.map +0 -1
- package/dist/cjs/tools/artifacts/tool.cjs +0 -219
- package/dist/cjs/tools/artifacts/tool.cjs.map +0 -1
- package/dist/cjs/tools/fileSearch/formatter.cjs +0 -93
- package/dist/cjs/tools/fileSearch/formatter.cjs.map +0 -1
- package/dist/cjs/tools/fileSearch/ragClient.cjs +0 -102
- package/dist/cjs/tools/fileSearch/ragClient.cjs.map +0 -1
- package/dist/cjs/tools/fileSearch/schema.cjs +0 -18
- package/dist/cjs/tools/fileSearch/schema.cjs.map +0 -1
- package/dist/cjs/tools/fileSearch/tool.cjs +0 -155
- package/dist/cjs/tools/fileSearch/tool.cjs.map +0 -1
- package/dist/cjs/tools/proxyTool.cjs +0 -102
- package/dist/cjs/tools/proxyTool.cjs.map +0 -1
- package/dist/cjs/utils/childAgentContext.cjs +0 -242
- package/dist/cjs/utils/childAgentContext.cjs.map +0 -1
- package/dist/cjs/utils/credentials.cjs +0 -142
- package/dist/cjs/utils/credentials.cjs.map +0 -1
- package/dist/cjs/utils/httpClient.cjs +0 -74
- package/dist/cjs/utils/httpClient.cjs.map +0 -1
- package/dist/cjs/utils/toolManifest.cjs +0 -100
- package/dist/cjs/utils/toolManifest.cjs.map +0 -1
- package/dist/esm/common/spawnPath.mjs +0 -95
- package/dist/esm/common/spawnPath.mjs.map +0 -1
- package/dist/esm/content/ArtifactStore.mjs +0 -576
- package/dist/esm/content/ArtifactStore.mjs.map +0 -1
- package/dist/esm/content/ContentStore.mjs +0 -635
- package/dist/esm/content/ContentStore.mjs.map +0 -1
- package/dist/esm/content/contentAnalyzer.mjs +0 -87
- package/dist/esm/content/contentAnalyzer.mjs.map +0 -1
- package/dist/esm/content/index.mjs +0 -5
- package/dist/esm/content/mcpAutoCache.mjs +0 -111
- package/dist/esm/content/mcpAutoCache.mjs.map +0 -1
- package/dist/esm/graphs/HandoffRegistry.mjs +0 -141
- package/dist/esm/graphs/HandoffRegistry.mjs.map +0 -1
- package/dist/esm/providers/a2a/A2ACapabilityProvider.mjs +0 -281
- package/dist/esm/providers/a2a/A2ACapabilityProvider.mjs.map +0 -1
- package/dist/esm/providers/a2a/client.mjs +0 -88
- package/dist/esm/providers/a2a/client.mjs.map +0 -1
- package/dist/esm/providers/a2a/config.mjs +0 -35
- package/dist/esm/providers/a2a/config.mjs.map +0 -1
- package/dist/esm/providers/capabilityNaming.mjs +0 -39
- package/dist/esm/providers/capabilityNaming.mjs.map +0 -1
- package/dist/esm/providers/mcp/MCPCapabilityProvider.mjs +0 -240
- package/dist/esm/providers/mcp/MCPCapabilityProvider.mjs.map +0 -1
- package/dist/esm/providers/mcp/config.mjs +0 -39
- package/dist/esm/providers/mcp/config.mjs.map +0 -1
- package/dist/esm/providers/mcp/transport.mjs +0 -63
- package/dist/esm/providers/mcp/transport.mjs.map +0 -1
- package/dist/esm/providers/tools-server/ToolsServerCapabilityProvider.mjs +0 -126
- package/dist/esm/providers/tools-server/ToolsServerCapabilityProvider.mjs.map +0 -1
- package/dist/esm/providers/types.mjs +0 -51
- package/dist/esm/providers/types.mjs.map +0 -1
- package/dist/esm/tools/artifacts/schema.mjs +0 -79
- package/dist/esm/tools/artifacts/schema.mjs.map +0 -1
- package/dist/esm/tools/artifacts/tool.mjs +0 -213
- package/dist/esm/tools/artifacts/tool.mjs.map +0 -1
- package/dist/esm/tools/fileSearch/formatter.mjs +0 -90
- package/dist/esm/tools/fileSearch/formatter.mjs.map +0 -1
- package/dist/esm/tools/fileSearch/ragClient.mjs +0 -98
- package/dist/esm/tools/fileSearch/ragClient.mjs.map +0 -1
- package/dist/esm/tools/fileSearch/schema.mjs +0 -15
- package/dist/esm/tools/fileSearch/schema.mjs.map +0 -1
- package/dist/esm/tools/fileSearch/tool.mjs +0 -152
- package/dist/esm/tools/fileSearch/tool.mjs.map +0 -1
- package/dist/esm/tools/proxyTool.mjs +0 -100
- package/dist/esm/tools/proxyTool.mjs.map +0 -1
- package/dist/esm/utils/childAgentContext.mjs +0 -237
- package/dist/esm/utils/childAgentContext.mjs.map +0 -1
- package/dist/esm/utils/credentials.mjs +0 -135
- package/dist/esm/utils/credentials.mjs.map +0 -1
- package/dist/esm/utils/httpClient.mjs +0 -70
- package/dist/esm/utils/httpClient.mjs.map +0 -1
- package/dist/esm/utils/toolManifest.mjs +0 -96
- package/dist/esm/utils/toolManifest.mjs.map +0 -1
- package/dist/types/common/spawnPath.d.ts +0 -59
- package/dist/types/content/ArtifactStore.d.ts +0 -223
- package/dist/types/content/ContentStore.d.ts +0 -140
- package/dist/types/content/contentAnalyzer.d.ts +0 -38
- package/dist/types/content/index.d.ts +0 -24
- package/dist/types/content/mcpAutoCache.d.ts +0 -89
- package/dist/types/content/types.d.ts +0 -75
- package/dist/types/graphs/HandoffRegistry.d.ts +0 -97
- package/dist/types/providers/a2a/A2ACapabilityProvider.d.ts +0 -89
- package/dist/types/providers/a2a/client.d.ts +0 -47
- package/dist/types/providers/a2a/config.d.ts +0 -18
- package/dist/types/providers/a2a/index.d.ts +0 -6
- package/dist/types/providers/a2a/types.d.ts +0 -173
- package/dist/types/providers/capabilityNaming.d.ts +0 -25
- package/dist/types/providers/index.d.ts +0 -12
- package/dist/types/providers/mcp/MCPCapabilityProvider.d.ts +0 -54
- package/dist/types/providers/mcp/config.d.ts +0 -20
- package/dist/types/providers/mcp/index.d.ts +0 -5
- package/dist/types/providers/mcp/transport.d.ts +0 -18
- package/dist/types/providers/mcp/types.d.ts +0 -112
- package/dist/types/providers/tools-server/ToolsServerCapabilityProvider.d.ts +0 -59
- package/dist/types/providers/tools-server/index.d.ts +0 -1
- package/dist/types/providers/types.d.ts +0 -184
- package/dist/types/tools/artifacts/index.d.ts +0 -3
- package/dist/types/tools/artifacts/schema.d.ts +0 -63
- package/dist/types/tools/artifacts/tool.d.ts +0 -16
- package/dist/types/tools/artifacts/types.d.ts +0 -127
- package/dist/types/tools/fileSearch/formatter.d.ts +0 -25
- package/dist/types/tools/fileSearch/index.d.ts +0 -5
- package/dist/types/tools/fileSearch/ragClient.d.ts +0 -32
- package/dist/types/tools/fileSearch/schema.d.ts +0 -13
- package/dist/types/tools/fileSearch/tool.d.ts +0 -18
- package/dist/types/tools/fileSearch/types.d.ts +0 -139
- package/dist/types/tools/proxyTool.d.ts +0 -62
- package/dist/types/utils/childAgentContext.d.ts +0 -99
- package/dist/types/utils/credentials.d.ts +0 -77
- package/dist/types/utils/httpClient.d.ts +0 -46
- package/dist/types/utils/toolManifest.d.ts +0 -49
- package/src/common/__tests__/spawnPath.test.ts +0 -110
- package/src/common/spawnPath.ts +0 -101
- package/src/content/ArtifactStore.ts +0 -782
- package/src/content/ContentStore.ts +0 -753
- package/src/content/contentAnalyzer.ts +0 -105
- package/src/content/index.ts +0 -51
- package/src/content/mcpAutoCache.ts +0 -185
- package/src/content/types.ts +0 -82
- package/src/graphs/HandoffRegistry.ts +0 -199
- package/src/graphs/__tests__/HandoffRegistry.test.ts +0 -410
- package/src/graphs/__tests__/multi-agent-delegate.test.ts +0 -458
- package/src/graphs/__tests__/multi-agent-edges.test.ts +0 -276
- package/src/graphs/__tests__/multi-agent-nested-subgraph.test.ts +0 -221
- package/src/graphs/handoffValidation.test.ts +0 -353
- package/src/providers/__tests__/ToolsServerCapabilityProvider.integration.spec.ts +0 -79
- package/src/providers/__tests__/ToolsServerCapabilityProvider.test.ts +0 -271
- package/src/providers/__tests__/types.test.ts +0 -64
- package/src/providers/a2a/A2ACapabilityProvider.ts +0 -384
- package/src/providers/a2a/__tests__/A2ACapabilityProvider.integration.spec.ts +0 -345
- package/src/providers/a2a/__tests__/A2ACapabilityProvider.test.ts +0 -460
- package/src/providers/a2a/client.ts +0 -115
- package/src/providers/a2a/config.ts +0 -40
- package/src/providers/a2a/index.ts +0 -29
- package/src/providers/a2a/types.ts +0 -191
- package/src/providers/capabilityNaming.ts +0 -42
- package/src/providers/index.ts +0 -68
- package/src/providers/mcp/MCPCapabilityProvider.ts +0 -345
- package/src/providers/mcp/__tests__/MCPCapabilityProvider.integration.spec.ts +0 -386
- package/src/providers/mcp/__tests__/MCPCapabilityProvider.test.ts +0 -371
- package/src/providers/mcp/config.ts +0 -45
- package/src/providers/mcp/index.ts +0 -21
- package/src/providers/mcp/transport.ts +0 -76
- package/src/providers/mcp/types.ts +0 -139
- package/src/providers/tools-server/ToolsServerCapabilityProvider.ts +0 -249
- package/src/providers/tools-server/index.ts +0 -1
- package/src/providers/types.ts +0 -204
- package/src/scripts/test-bedrock-handoff-autonomous.ts +0 -267
- package/src/scripts/test-handoff-preamble.ts +0 -278
- package/src/specs/agent-handoffs-bedrock.integration.test.ts +0 -415
- package/src/tools/artifacts/__tests__/tool.test.ts +0 -259
- package/src/tools/artifacts/index.ts +0 -33
- package/src/tools/artifacts/schema.ts +0 -99
- package/src/tools/artifacts/tool.ts +0 -289
- package/src/tools/artifacts/types.ts +0 -162
- package/src/tools/fileSearch/__tests__/tool.test.ts +0 -261
- package/src/tools/fileSearch/formatter.ts +0 -129
- package/src/tools/fileSearch/index.ts +0 -23
- package/src/tools/fileSearch/ragClient.ts +0 -137
- package/src/tools/fileSearch/schema.ts +0 -19
- package/src/tools/fileSearch/tool.ts +0 -207
- package/src/tools/fileSearch/types.ts +0 -149
- package/src/tools/proxyTool.ts +0 -166
- package/src/utils/__tests__/childAgentContext.test.ts +0 -217
- package/src/utils/__tests__/credentials.test.ts +0 -130
- package/src/utils/__tests__/httpClient.test.ts +0 -75
- package/src/utils/__tests__/toolManifest.test.ts +0 -116
- package/src/utils/childAgentContext.ts +0 -259
- package/src/utils/credentials.ts +0 -157
- package/src/utils/httpClient.ts +0 -92
- package/src/utils/toolManifest.ts +0 -109
- /package/dist/esm/{content → langchain}/index.mjs.map +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"toolOutputReferences.cjs","sources":["../../../src/tools/toolOutputReferences.ts"],"sourcesContent":["/**\n * Tool output reference registry.\n *\n * When enabled via `RunConfig.toolOutputReferences.enabled`, ToolNode\n * stores each successful tool output under a stable key\n * (`tool<idx>turn<turn>`) where `idx` is the tool's position within a\n * ToolNode batch and `turn` is the batch index within the run\n * (incremented once per ToolNode invocation).\n *\n * Subsequent tool calls can pipe a previous output into their args by\n * embedding `{{tool<idx>turn<turn>}}` inside any string argument;\n * {@link ToolOutputReferenceRegistry.resolve} walks the args and\n * substitutes the placeholders immediately before invocation.\n *\n * The registry stores the *raw, untruncated* tool output so a later\n * `{{…}}` substitution pipes the full payload into the next tool —\n * even when the LLM only saw a head+tail-truncated preview in\n * `ToolMessage.content`. Outputs are stored without any annotation\n * (the `_ref` key or the `[ref: ...]` prefix seen by the LLM is\n * strictly a UX signal attached to `ToolMessage.content`). Keeping the\n * registry pristine means downstream bash/jq piping receives the\n * complete, verbatim output with no injected fields.\n */\n\nimport { ToolMessage } from '@langchain/core/messages';\nimport type { BaseMessage } from '@langchain/core/messages';\nimport {\n calculateMaxTotalToolOutputSize,\n HARD_MAX_TOOL_RESULT_CHARS,\n HARD_MAX_TOTAL_TOOL_OUTPUT_SIZE,\n} from '@/utils/truncation';\n\n/**\n * Non-global matcher for a single `{{tool<i>turn<n>}}` placeholder.\n * Exported for consumers that want to detect references (e.g., syntax\n * highlighting, docs). The stateful `g` variant lives inside the\n * registry so nobody trips on `lastIndex`.\n */\nexport const TOOL_OUTPUT_REF_PATTERN = /\\{\\{(tool\\d+turn\\d+)\\}\\}/;\n\n/** Object key used when a parsed-object output has `_ref` injected. */\nexport const TOOL_OUTPUT_REF_KEY = '_ref';\n\n/**\n * Object key used to carry unresolved reference warnings on a parsed-\n * object output. Using a dedicated field instead of a trailing text\n * line keeps the annotated `ToolMessage.content` parseable as JSON for\n * downstream consumers that rely on the object shape.\n */\nexport const TOOL_OUTPUT_UNRESOLVED_KEY = '_unresolved_refs';\n\n/** Single-line prefix prepended to non-object tool outputs so the LLM sees the reference key. */\nexport function buildReferencePrefix(key: string): string {\n return `[ref: ${key}]`;\n}\n\n/** Stable registry key for a tool output. */\nexport function buildReferenceKey(toolIndex: number, turn: number): string {\n return `tool${toolIndex}turn${turn}`;\n}\n\nexport type ToolOutputReferenceRegistryOptions = {\n /** Maximum characters stored per registered output. */\n maxOutputSize?: number;\n /** Maximum total characters retained across all registered outputs. */\n maxTotalSize?: number;\n /**\n * Upper bound on the number of concurrently-tracked runs. When\n * exceeded, the oldest run bucket is evicted (FIFO). Defaults to 32.\n */\n maxActiveRuns?: number;\n};\n\n/**\n * Result of resolving placeholders in tool args.\n */\nexport type ResolveResult<T> = {\n /** Arguments with placeholders replaced. Same shape as the input. */\n resolved: T;\n /** Reference keys that were referenced but had no stored value. */\n unresolved: string[];\n};\n\n/**\n * Read-only view over a frozen registry snapshot. Returned by\n * {@link ToolOutputReferenceRegistry.snapshot} for callers that need\n * to resolve placeholders against the registry state at a specific\n * point in time, ignoring any subsequent registrations.\n */\nexport interface ToolOutputResolveView {\n resolve<T>(args: T): ResolveResult<T>;\n}\n\n/**\n * Pre-resolved arg map keyed by `toolCallId`. Used by the mixed\n * direct+event dispatch path to feed event calls' resolved args\n * (captured pre-batch) into the dispatcher without re-resolving\n * against the now-stale live registry.\n */\nexport type PreResolvedArgsMap = Map<\n string,\n { resolved: Record<string, unknown>; unresolved: string[] }\n>;\n\n/**\n * Per-call sink for resolved args, keyed by `toolCallId`. Threaded\n * as a per-batch local map so concurrent `ToolNode.run()` calls do\n * not race on shared sink state.\n */\nexport type ResolvedArgsByCallId = Map<string, Record<string, unknown>>;\n\nconst EMPTY_ENTRIES: ReadonlyMap<string, string> = new Map<string, string>();\n\n/**\n * Per-run state bucket held inside the registry. Each distinct\n * `run_id` gets its own bucket so overlapping concurrent runs on a\n * shared registry cannot leak outputs, turn counters, or warn-memos\n * into one another.\n */\nclass RunStateBucket {\n entries: Map<string, string> = new Map();\n totalSize: number = 0;\n turnCounter: number = 0;\n warnedNonStringTools: Set<string> = new Set();\n}\n\n/**\n * Anonymous (`run_id` absent) bucket key. Anonymous batches are\n * treated as fresh runs on every invocation — see `nextTurn`.\n */\nconst ANON_RUN_KEY = '\\0anon';\n\n/**\n * Default upper bound on the number of concurrently-tracked runs per\n * registry. When exceeded, the oldest run's bucket (by insertion\n * order) is evicted. Keeps memory bounded when a ToolNode is reused\n * across many runs without explicit `releaseRun` calls.\n */\nconst DEFAULT_MAX_ACTIVE_RUNS = 32;\n\n/**\n * Ordered map of reference-key → stored output, partitioned by run so\n * concurrent / interleaved runs sharing one registry cannot leak\n * outputs between each other.\n *\n * Each public method takes a `runId` which selects the run's bucket.\n * Hosts typically get one registry per run via `Graph`, in which\n * case only a single bucket is ever populated; the partitioning\n * exists so the registry also behaves correctly when a single\n * instance is reused directly.\n */\nexport class ToolOutputReferenceRegistry {\n private runStates: Map<string, RunStateBucket> = new Map();\n private readonly maxOutputSize: number;\n private readonly maxTotalSize: number;\n private readonly maxActiveRuns: number;\n /**\n * Local stateful matcher used only by `replaceInString`. Kept\n * off-module so callers of the exported `TOOL_OUTPUT_REF_PATTERN`\n * never see a stale `lastIndex`.\n */\n private static readonly PLACEHOLDER_MATCHER = /\\{\\{(tool\\d+turn\\d+)\\}\\}/g;\n\n constructor(options: ToolOutputReferenceRegistryOptions = {}) {\n /**\n * Per-output default is the same ~400 KB budget as the standard\n * tool-result truncation (`HARD_MAX_TOOL_RESULT_CHARS`). This\n * keeps a single `{{…}}` substitution at a size that is safe to\n * pass through typical shell `ARG_MAX` limits and matches what\n * the LLM would otherwise have seen. Hosts that want larger per-\n * output payloads (API consumers, long JSON streams) can raise\n * the cap explicitly up to the 5 MB total budget.\n */\n const perOutput =\n options.maxOutputSize != null && options.maxOutputSize > 0\n ? options.maxOutputSize\n : HARD_MAX_TOOL_RESULT_CHARS;\n /**\n * Clamp a caller-supplied `maxTotalSize` to\n * `HARD_MAX_TOTAL_TOOL_OUTPUT_SIZE` (5 MB) so the documented\n * absolute cap is enforced regardless of host config —\n * `calculateMaxTotalToolOutputSize` already applies the same\n * upper bound on its computed default, but the user-provided\n * branch was bypassing it.\n */\n const totalRaw =\n options.maxTotalSize != null && options.maxTotalSize > 0\n ? Math.min(options.maxTotalSize, HARD_MAX_TOTAL_TOOL_OUTPUT_SIZE)\n : calculateMaxTotalToolOutputSize(perOutput);\n this.maxTotalSize = totalRaw;\n /**\n * The per-output cap can never exceed the per-run aggregate cap:\n * if a single entry were allowed to be larger than `maxTotalSize`,\n * the eviction loop would either blow the cap (to keep the entry)\n * or self-evict a just-stored value. Clamping here turns\n * `maxTotalSize` into a hard upper bound on *any* state the\n * registry retains per run.\n */\n this.maxOutputSize = Math.min(perOutput, totalRaw);\n this.maxActiveRuns =\n options.maxActiveRuns != null && options.maxActiveRuns > 0\n ? options.maxActiveRuns\n : DEFAULT_MAX_ACTIVE_RUNS;\n }\n\n private keyFor(runId: string | undefined): string {\n return runId ?? ANON_RUN_KEY;\n }\n\n private getOrCreate(runId: string | undefined): RunStateBucket {\n const key = this.keyFor(runId);\n let state = this.runStates.get(key);\n if (state == null) {\n state = new RunStateBucket();\n this.runStates.set(key, state);\n if (this.runStates.size > this.maxActiveRuns) {\n const oldest = this.runStates.keys().next().value;\n if (oldest != null && oldest !== key) {\n this.runStates.delete(oldest);\n }\n }\n }\n return state;\n }\n\n /** Registers (or replaces) the output stored under `key` for `runId`. */\n set(runId: string | undefined, key: string, value: string): void {\n const bucket = this.getOrCreate(runId);\n const clipped =\n value.length > this.maxOutputSize\n ? value.slice(0, this.maxOutputSize)\n : value;\n const existing = bucket.entries.get(key);\n if (existing != null) {\n bucket.totalSize -= existing.length;\n bucket.entries.delete(key);\n }\n bucket.entries.set(key, clipped);\n bucket.totalSize += clipped.length;\n this.evictWithinBucket(bucket);\n }\n\n /** Returns the stored value for `key` in `runId`'s bucket, or `undefined`. */\n get(runId: string | undefined, key: string): string | undefined {\n return this.runStates.get(this.keyFor(runId))?.entries.get(key);\n }\n\n /**\n * Returns `true` when `key` is currently stored in `runId`'s bucket.\n * Used by {@link annotateMessagesForLLM} to gate transient annotation\n * on whether the registry still owns the referenced output (a stale\n * `_refKey` from a prior run silently no-ops here).\n */\n has(runId: string | undefined, key: string): boolean {\n return this.runStates.get(this.keyFor(runId))?.entries.has(key) ?? false;\n }\n\n /** Total number of registered outputs across every run bucket. */\n get size(): number {\n let n = 0;\n for (const bucket of this.runStates.values()) {\n n += bucket.entries.size;\n }\n return n;\n }\n\n /** Maximum characters retained per output (post-clip). */\n get perOutputLimit(): number {\n return this.maxOutputSize;\n }\n\n /** Maximum total characters retained *per run*. */\n get totalLimit(): number {\n return this.maxTotalSize;\n }\n\n /** Drops every run's state. */\n clear(): void {\n this.runStates.clear();\n }\n\n /**\n * Explicitly release `runId`'s state. Safe to call when a run has\n * finished. Hosts sharing one registry across runs should call this\n * to reclaim memory deterministically; otherwise LRU eviction kicks\n * in when `maxActiveRuns` runs accumulate.\n */\n releaseRun(runId: string | undefined): void {\n this.runStates.delete(this.keyFor(runId));\n }\n\n /**\n * Claims the next batch turn synchronously from `runId`'s bucket.\n *\n * Must be called once at the start of each ToolNode batch before\n * any `await`, so concurrent invocations within the same run see\n * distinct turn values (reads are effectively atomic by JS's\n * single-threaded execution of the sync prefix).\n *\n * If `runId` is missing the anonymous bucket is dropped and a\n * fresh one created so each anonymous call behaves as its own run.\n */\n nextTurn(runId: string | undefined): number {\n if (runId == null) {\n this.runStates.delete(ANON_RUN_KEY);\n }\n const bucket = this.getOrCreate(runId);\n return bucket.turnCounter++;\n }\n\n /**\n * Records that `toolName` has been warned about in `runId` (returns\n * `true` on the first call per run, `false` after). Used by\n * ToolNode to emit one log line per offending tool per run when a\n * `ToolMessage.content` isn't a string.\n */\n claimWarnOnce(runId: string | undefined, toolName: string): boolean {\n const bucket = this.getOrCreate(runId);\n if (bucket.warnedNonStringTools.has(toolName)) {\n return false;\n }\n bucket.warnedNonStringTools.add(toolName);\n return true;\n }\n\n /**\n * Walks `args` and replaces every `{{tool<i>turn<n>}}` placeholder in\n * string values with the stored output *from `runId`'s bucket*. Non-\n * string values and object keys are left untouched. Unresolved\n * references are left in-place and reported so the caller can\n * surface them to the LLM. When no placeholder appears anywhere in\n * the serialized args, the original input is returned without\n * walking the tree.\n */\n resolve<T>(runId: string | undefined, args: T): ResolveResult<T> {\n if (!hasAnyPlaceholder(args)) {\n return { resolved: args, unresolved: [] };\n }\n const bucket = this.runStates.get(this.keyFor(runId));\n return this.resolveAgainst(bucket?.entries ?? EMPTY_ENTRIES, args);\n }\n\n /**\n * Captures a frozen snapshot of `runId`'s current entries and\n * returns a view that resolves placeholders against *only* that\n * snapshot. The snapshot is decoupled from the live registry, so\n * subsequent `set()` calls (for example, same-turn direct outputs\n * registering while an event branch is still in flight) are\n * invisible to the snapshot's `resolve`. Used by the mixed\n * direct+event dispatch path to preserve same-turn isolation when\n * a `PreToolUse` hook rewrites event args after directs have\n * completed.\n */\n snapshot(runId: string | undefined): ToolOutputResolveView {\n const bucket = this.runStates.get(this.keyFor(runId));\n const entries: ReadonlyMap<string, string> = bucket\n ? new Map(bucket.entries)\n : EMPTY_ENTRIES;\n return {\n resolve: <T>(args: T): ResolveResult<T> =>\n this.resolveAgainst(entries, args),\n };\n }\n\n private resolveAgainst<T>(\n entries: ReadonlyMap<string, string>,\n args: T\n ): ResolveResult<T> {\n if (!hasAnyPlaceholder(args)) {\n return { resolved: args, unresolved: [] };\n }\n const unresolved = new Set<string>();\n const resolved = this.transform(entries, args, unresolved) as T;\n return { resolved, unresolved: Array.from(unresolved) };\n }\n\n private transform(\n entries: ReadonlyMap<string, string>,\n value: unknown,\n unresolved: Set<string>\n ): unknown {\n if (typeof value === 'string') {\n return this.replaceInString(entries, value, unresolved);\n }\n if (Array.isArray(value)) {\n return value.map((item) => this.transform(entries, item, unresolved));\n }\n if (value !== null && typeof value === 'object') {\n const source = value as Record<string, unknown>;\n const next: Record<string, unknown> = {};\n for (const [key, item] of Object.entries(source)) {\n next[key] = this.transform(entries, item, unresolved);\n }\n return next;\n }\n return value;\n }\n\n private replaceInString(\n entries: ReadonlyMap<string, string>,\n input: string,\n unresolved: Set<string>\n ): string {\n if (input.indexOf('{{tool') === -1) {\n return input;\n }\n return input.replace(\n ToolOutputReferenceRegistry.PLACEHOLDER_MATCHER,\n (match, key: string) => {\n const stored = entries.get(key);\n if (stored == null) {\n unresolved.add(key);\n return match;\n }\n return stored;\n }\n );\n }\n\n private evictWithinBucket(bucket: RunStateBucket): void {\n if (bucket.totalSize <= this.maxTotalSize) {\n return;\n }\n for (const key of bucket.entries.keys()) {\n if (bucket.totalSize <= this.maxTotalSize) {\n return;\n }\n const entry = bucket.entries.get(key);\n if (entry == null) {\n continue;\n }\n bucket.totalSize -= entry.length;\n bucket.entries.delete(key);\n }\n }\n}\n\n/**\n * Cheap pre-check: returns true if any string value in `args` contains\n * the `{{tool` substring. Lets `resolve()` skip the deep tree walk (and\n * its object allocations) for the common case of plain args.\n */\nfunction hasAnyPlaceholder(value: unknown): boolean {\n if (typeof value === 'string') {\n return value.indexOf('{{tool') !== -1;\n }\n if (Array.isArray(value)) {\n for (const item of value) {\n if (hasAnyPlaceholder(item)) {\n return true;\n }\n }\n return false;\n }\n if (value !== null && typeof value === 'object') {\n for (const item of Object.values(value as Record<string, unknown>)) {\n if (hasAnyPlaceholder(item)) {\n return true;\n }\n }\n return false;\n }\n return false;\n}\n\n/**\n * Annotates `content` with a reference key and/or unresolved-ref\n * warnings so the LLM sees both alongside the tool output.\n *\n * Behavior:\n * - If `content` parses as a plain (non-array, non-null) JSON object\n * and the object does not already have a conflicting `_ref` key,\n * the reference key and (when present) `_unresolved_refs` array\n * are injected as object fields, preserving JSON validity for\n * downstream consumers that parse the output.\n * - Otherwise (string output, JSON array/primitive, parse failure,\n * or `_ref` collision), a `[ref: <key>]\\n` prefix line is\n * prepended and unresolved refs are appended as a trailing\n * `[unresolved refs: …]` line.\n *\n * The annotated string is what the LLM sees as `ToolMessage.content`.\n * The *original* (un-annotated) value is what gets stored in the\n * registry, so downstream piping remains pristine.\n *\n * @param content Raw (post-truncation) tool output.\n * @param key Reference key for this output, or undefined when\n * there is nothing to register (errors etc.).\n * @param unresolved Reference keys that failed to resolve during\n * argument substitution. Surfaced so the LLM can\n * self-correct its next tool call.\n */\nexport function annotateToolOutputWithReference(\n content: string,\n key: string | undefined,\n unresolved: string[] = []\n): string {\n const hasRefKey = key != null;\n const hasUnresolved = unresolved.length > 0;\n if (!hasRefKey && !hasUnresolved) {\n return content;\n }\n const trimmed = content.trimStart();\n if (trimmed.startsWith('{')) {\n const annotated = tryInjectRefIntoJsonObject(content, key, unresolved);\n if (annotated != null) {\n return annotated;\n }\n }\n const prefix = hasRefKey ? `${buildReferencePrefix(key!)}\\n` : '';\n const trailer = hasUnresolved\n ? `\\n[unresolved refs: ${unresolved.join(', ')}]`\n : '';\n return `${prefix}${content}${trailer}`;\n}\n\nfunction tryInjectRefIntoJsonObject(\n content: string,\n key: string | undefined,\n unresolved: string[]\n): string | null {\n let parsed: unknown;\n try {\n parsed = JSON.parse(content);\n } catch {\n return null;\n }\n\n if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {\n return null;\n }\n\n const obj = parsed as Record<string, unknown>;\n const injectingRef = key != null;\n const injectingUnresolved = unresolved.length > 0;\n\n /**\n * Reject the JSON-injection path (fall back to prefix form) when\n * either of our keys collides with real payload data:\n * - `_ref` collision: existing value is non-null and differs from\n * the key we're about to inject.\n * - `_unresolved_refs` collision: existing value is non-null and\n * is not a deep-equal match for the array we'd inject.\n * This keeps us from silently overwriting legitimate tool output.\n */\n if (\n injectingRef &&\n TOOL_OUTPUT_REF_KEY in obj &&\n obj[TOOL_OUTPUT_REF_KEY] !== key &&\n obj[TOOL_OUTPUT_REF_KEY] != null\n ) {\n return null;\n }\n if (\n injectingUnresolved &&\n TOOL_OUTPUT_UNRESOLVED_KEY in obj &&\n obj[TOOL_OUTPUT_UNRESOLVED_KEY] != null &&\n !arraysShallowEqual(obj[TOOL_OUTPUT_UNRESOLVED_KEY], unresolved)\n ) {\n return null;\n }\n\n /**\n * Only strip the framework-owned key we're actually injecting —\n * leave everything else (including a pre-existing `_ref` on the\n * unresolved-only path, or a pre-existing `_unresolved_refs` on a\n * plain-annotation path) untouched so we annotate rather than\n * mutate downstream payload data. Our injected keys land first in\n * the serialized JSON so the LLM sees them before the body.\n */\n const omitKeys = new Set<string>();\n if (injectingRef) omitKeys.add(TOOL_OUTPUT_REF_KEY);\n if (injectingUnresolved) omitKeys.add(TOOL_OUTPUT_UNRESOLVED_KEY);\n const rest: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(obj)) {\n if (!omitKeys.has(k)) {\n rest[k] = v;\n }\n }\n const injected: Record<string, unknown> = {};\n if (injectingRef) {\n injected[TOOL_OUTPUT_REF_KEY] = key;\n }\n if (injectingUnresolved) {\n injected[TOOL_OUTPUT_UNRESOLVED_KEY] = unresolved;\n }\n Object.assign(injected, rest);\n\n const pretty = /^\\{\\s*\\n/.test(content);\n return pretty ? JSON.stringify(injected, null, 2) : JSON.stringify(injected);\n}\n\nfunction arraysShallowEqual(a: unknown, b: readonly string[]): boolean {\n if (!Array.isArray(a) || a.length !== b.length) {\n return false;\n }\n for (let i = 0; i < a.length; i++) {\n if (a[i] !== b[i]) {\n return false;\n }\n }\n return true;\n}\n\n/**\n * Lazy projection that, given a registry and a runId, returns a new\n * `messages` array where each `ToolMessage` carrying ref metadata is\n * projected into a transient copy with annotated content (when the ref\n * is live in the registry) and with the framework-owned `additional_\n * kwargs` keys (`_refKey`, `_refScope`, `_unresolvedRefs`) stripped\n * regardless of whether annotation applied. The original input array\n * and its messages are never mutated.\n *\n * Annotation is gated on registry presence: a stale `_refKey` from a\n * prior run (e.g. one that survived in persisted history) silently\n * no-ops on the *content* side. The strip-metadata side still runs so\n * stale framework keys never leak onto the wire under any custom or\n * future provider serializer that might transmit `additional_kwargs`.\n * `_unresolvedRefs` is always meaningful and is not gated.\n *\n * **Feature-disabled fast path:** when the host hasn't enabled the\n * tool-output-reference feature, the registry is `undefined` and this\n * function returns the input array reference-equal *without iterating\n * a single message*. The loop is exclusive to the feature-enabled\n * code path.\n */\nexport function annotateMessagesForLLM(\n messages: BaseMessage[],\n registry: ToolOutputReferenceRegistry | undefined,\n runId: string | undefined\n): BaseMessage[] {\n if (registry == null) return messages;\n\n /**\n * Lazy-allocate the output array so the common case (no ToolMessage\n * carries framework metadata) returns the input reference-equal with\n * zero allocations beyond the per-message predicate checks.\n */\n let out: BaseMessage[] | undefined;\n for (let i = 0; i < messages.length; i++) {\n const m = messages[i];\n if (m._getType() !== 'tool') continue;\n /**\n * `additional_kwargs` is untyped at the LangChain layer\n * (`Record<string, unknown>`), so persisted or client-supplied\n * ToolMessages can carry arbitrary shapes — including primitives\n * (a malformed serializer might write a string, or `null`).\n * Guard with a runtime object check before the `in` probes\n * because the `in` operator throws `TypeError` on primitives.\n * A single malformed message must never crash the provider call\n * path; skip its annotation/strip and continue.\n */\n const rawMeta = m.additional_kwargs as unknown;\n if (rawMeta == null || typeof rawMeta !== 'object') continue;\n const meta = rawMeta as Record<string, unknown>;\n const hasRefKey = '_refKey' in meta;\n const hasRefScope = '_refScope' in meta;\n const hasUnresolvedField = '_unresolvedRefs' in meta;\n if (!hasRefKey && !hasRefScope && !hasUnresolvedField) continue;\n\n const refKey = readRefKey(meta);\n const unresolved = readUnresolvedRefs(meta);\n\n /**\n * Prefer the message-stamped `_refScope` for the registry lookup.\n * For named runs it equals the current `runId`; for anonymous\n * invocations it carries the per-batch synthetic scope minted by\n * ToolNode (`\\0anon-<n>`), which `runId` from config cannot\n * recover. Falling back to `runId` keeps backward compatibility\n * with messages stamped before this field existed.\n */\n const lookupScope = readRefScope(meta) ?? runId;\n const liveRef =\n refKey != null && registry.has(lookupScope, refKey) ? refKey : undefined;\n const annotates = liveRef != null || unresolved.length > 0;\n\n const tm = m as ToolMessage;\n let nextContent: ToolMessage['content'] = tm.content;\n\n if (annotates && typeof tm.content === 'string') {\n nextContent = annotateToolOutputWithReference(\n tm.content,\n liveRef,\n unresolved\n );\n } else if (\n annotates &&\n Array.isArray(tm.content) &&\n unresolved.length > 0\n ) {\n const warningBlock = {\n type: 'text' as const,\n text: `[unresolved refs: ${unresolved.join(', ')}]`,\n };\n /**\n * `as unknown as ToolMessage['content']` is unavoidable here:\n * LangChain's content union (`MessageContentComplex[] |\n * DataContentBlock[] | string`) does not accept a freshly built\n * mixed array literal even though the structural shape is valid\n * at runtime. The double-cast is structurally safe — we\n * preserve every block from `tm.content` and prepend a single\n * `{ type: 'text', text }` block that all providers accept.\n */\n nextContent = [\n warningBlock,\n ...tm.content,\n ] as unknown as ToolMessage['content'];\n }\n\n /**\n * Project unconditionally: even when no annotation applies (stale\n * `_refKey` or non-annotatable content), `cloneToolMessageWithContent`\n * runs `stripFrameworkRefMetadata` on `additional_kwargs` so the\n * framework-owned keys never reach the wire.\n */\n out ??= messages.slice();\n out[i] = cloneToolMessageWithContent(tm, nextContent);\n }\n\n return out ?? messages;\n}\n\n/**\n * Reads `_refKey` defensively from untyped `additional_kwargs`. Returns\n * undefined for non-string values so a malformed field cannot poison\n * the registry lookup or downstream string operations.\n */\nfunction readRefKey(\n meta: Record<string, unknown> | undefined\n): string | undefined {\n const v = meta?._refKey;\n return typeof v === 'string' ? v : undefined;\n}\n\n/**\n * Reads `_refScope` defensively from untyped `additional_kwargs`.\n * Mirrors {@link readRefKey} — non-string scopes are dropped (the\n * caller falls back to the run-derived scope) rather than passed into\n * the registry as a malformed key.\n */\nfunction readRefScope(\n meta: Record<string, unknown> | undefined\n): string | undefined {\n const v = meta?._refScope;\n return typeof v === 'string' ? v : undefined;\n}\n\n/**\n * Reads `_unresolvedRefs` defensively from untyped `additional_kwargs`.\n * Returns an empty array for any non-array value, and filters out\n * non-string entries from a real array. Without this guard, a hydrated\n * ToolMessage carrying e.g. `_unresolvedRefs: 'tool0turn0'` would crash\n * `attemptInvoke` on the eventual `.length` / `.join(...)` call.\n */\nfunction readUnresolvedRefs(\n meta: Record<string, unknown> | undefined\n): string[] {\n const v = meta?._unresolvedRefs;\n if (!Array.isArray(v)) return [];\n const out: string[] = [];\n for (const item of v) {\n if (typeof item === 'string') out.push(item);\n }\n return out;\n}\n\n/**\n * Builds a fresh `ToolMessage` that mirrors `tm`'s identity fields with\n * the supplied `content`. Every `ToolMessage` field but `content` is\n * carried over so the projection is structurally identical to the\n * original from a LangChain serializer's perspective.\n *\n * `additional_kwargs` is rebuilt with the framework-owned ref keys\n * stripped. Defensive: LangChain's standard provider serializers do not\n * transmit `additional_kwargs` to provider HTTP APIs, but a custom\n * adapter or future LangChain change could. Stripping keeps the\n * implementation correct under any serializer behavior at the cost of a\n * shallow object spread per annotated message.\n */\nfunction cloneToolMessageWithContent(\n tm: ToolMessage,\n content: ToolMessage['content']\n): ToolMessage {\n return new ToolMessage({\n id: tm.id,\n name: tm.name,\n status: tm.status,\n artifact: tm.artifact,\n tool_call_id: tm.tool_call_id,\n response_metadata: tm.response_metadata,\n additional_kwargs: stripFrameworkRefMetadata(tm.additional_kwargs),\n content,\n });\n}\n\n/**\n * Returns a copy of `kwargs` with `_refKey`, `_refScope`, and\n * `_unresolvedRefs` removed. Returns the input reference-equal when\n * none of those keys are present so the no-strip path stays cheap;\n * returns `undefined` when stripping leaves the object empty so the\n * caller can drop the field entirely.\n */\nfunction stripFrameworkRefMetadata(\n kwargs: Record<string, unknown> | undefined\n): Record<string, unknown> | undefined {\n if (kwargs == null) return undefined;\n if (\n !('_refKey' in kwargs) &&\n !('_refScope' in kwargs) &&\n !('_unresolvedRefs' in kwargs)\n ) {\n return kwargs;\n }\n const { _refKey, _refScope, _unresolvedRefs, ...rest } = kwargs as Record<\n string,\n unknown\n > & {\n _refKey?: unknown;\n _refScope?: unknown;\n _unresolvedRefs?: unknown;\n };\n void _refKey;\n void _refScope;\n void _unresolvedRefs;\n return Object.keys(rest).length === 0 ? undefined : rest;\n}\n"],"names":["HARD_MAX_TOOL_RESULT_CHARS","HARD_MAX_TOTAL_TOOL_OUTPUT_SIZE","calculateMaxTotalToolOutputSize","ToolMessage"],"mappings":";;;;;AAAA;;;;;;;;;;;;;;;;;;;;;;AAsBG;AAkBH;AACO,MAAM,mBAAmB,GAAG;AAEnC;;;;;AAKG;AACI,MAAM,0BAA0B,GAAG;AAE1C;AACM,SAAU,oBAAoB,CAAC,GAAW,EAAA;IAC9C,OAAO,CAAA,MAAA,EAAS,GAAG,CAAA,CAAA,CAAG;AACxB;AAEA;AACM,SAAU,iBAAiB,CAAC,SAAiB,EAAE,IAAY,EAAA;AAC/D,IAAA,OAAO,CAAA,IAAA,EAAO,SAAS,CAAA,IAAA,EAAO,IAAI,EAAE;AACtC;AAoDA,MAAM,aAAa,GAAgC,IAAI,GAAG,EAAkB;AAE5E;;;;;AAKG;AACH,MAAM,cAAc,CAAA;AAClB,IAAA,OAAO,GAAwB,IAAI,GAAG,EAAE;IACxC,SAAS,GAAW,CAAC;IACrB,WAAW,GAAW,CAAC;AACvB,IAAA,oBAAoB,GAAgB,IAAI,GAAG,EAAE;AAC9C;AAED;;;AAGG;AACH,MAAM,YAAY,GAAG,QAAQ;AAE7B;;;;;AAKG;AACH,MAAM,uBAAuB,GAAG,EAAE;AAElC;;;;;;;;;;AAUG;MACU,2BAA2B,CAAA;AAC9B,IAAA,SAAS,GAAgC,IAAI,GAAG,EAAE;AACzC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EAAE,EAAE,CAAC,YAAY;QAC7B,iBAAiB,EAAE,EAAE,CAAC,iBAAiB;AACvC,QAAA,iBAAiB,EAAE,yBAAyB,CAAC,EAAE,CAAC,iBAAiB,CAAC;QAClE,OAAO;AACR,KAAA,CAAC;AACJ;AAEA;;;;;;AAMG;AACH,SAAS,yBAAyB,CAChC,MAA2C,EAAA;IAE3C,IAAI,MAAM,IAAI,IAAI;AAAE,QAAA,OAAO,SAAS;AACpC,IAAA,IACE,EAAE,SAAS,IAAI,MAAM,CAAC;AACtB,QAAA,EAAE,WAAW,IAAI,MAAM,CAAC;AACxB,QAAA,EAAE,iBAAiB,IAAI,MAAM,CAAC,EAC9B;AACA,QAAA,OAAO,MAAM;IACf;AACA,IAAA,MAAM,EAAE,OAAO,EAAE,SAAS,EAAE,eAAe,EAAE,GAAG,IAAI,EAAE,GAAG,MAOxD;AAID,IAAA,OAAO,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,MAAM,KAAK,CAAC,GAAG,SAAS,GAAG,IAAI;AAC1D;;;;;;;;;;"}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Agent system-message prompt-cache types.
|
|
5
|
+
* ==========================================
|
|
6
|
+
*
|
|
7
|
+
* `@illuma-ai/agents` exposes a generic primitive — `system_cache_blocks` —
|
|
8
|
+
* for composing a system message that gets explicit cache markers
|
|
9
|
+
* (cachePoint on Bedrock, cache_control on Anthropic) at consumer-defined
|
|
10
|
+
* boundaries. The library encodes each entry into the right wire format
|
|
11
|
+
* for the active provider; consumers decide what content to put in each
|
|
12
|
+
* block.
|
|
13
|
+
*
|
|
14
|
+
* Why this is generic rather than ranger-specific
|
|
15
|
+
* ------------------------------------------------
|
|
16
|
+
* Earlier iterations exposed `platform_instructions` and `cache_ttl:
|
|
17
|
+
* { platform, agent }` — vocabulary borrowed from a multi-tenant chat
|
|
18
|
+
* platform's mental model. That leaked a specific consumer's domain into
|
|
19
|
+
* the library and made it confusing for other consumers (CLI tools,
|
|
20
|
+
* desktop apps, gateways) which have no notion of "platforms" or "agents".
|
|
21
|
+
*
|
|
22
|
+
* The current shape lets every consumer define their own cache-tier
|
|
23
|
+
* organization without the library knowing or caring.
|
|
24
|
+
*
|
|
25
|
+
* Cache key composition
|
|
26
|
+
* ---------------------
|
|
27
|
+
* Both Anthropic and Bedrock hash the message bytes leading up to each
|
|
28
|
+
* cache marker. So entry N's cache key is the concatenation of bytes
|
|
29
|
+
* 0..N. Stable content (universal rules, framework docs) goes earlier;
|
|
30
|
+
* volatile content (per-agent identity, per-tool docs) goes later. The
|
|
31
|
+
* earlier entries get cross-tenant cache hits; the later entries get
|
|
32
|
+
* narrower hits.
|
|
33
|
+
*
|
|
34
|
+
* Provider budget
|
|
35
|
+
* ---------------
|
|
36
|
+
* Bedrock's Converse API supports up to 4 cachePoint blocks per request.
|
|
37
|
+
* The default tools-array cache strategy (see `IllumaBedrockConverse`)
|
|
38
|
+
* uses up to 2 of those. So at most 2 entries should appear in
|
|
39
|
+
* `system_cache_blocks` to leave budget for the trailing
|
|
40
|
+
* `instructions` block. The library throws on more than 2.
|
|
41
|
+
*
|
|
42
|
+
* Anthropic supports up to 4 cache breakpoints per request workspace-wide;
|
|
43
|
+
* the same constraint applies to keep tools + system within budget.
|
|
44
|
+
*/
|
|
45
|
+
/**
|
|
46
|
+
* Maximum number of `system_cache_blocks` entries the library accepts.
|
|
47
|
+
* Higher than this would exceed Bedrock's 4-cachePoint budget once the
|
|
48
|
+
* tools array and trailing `instructions` block are counted.
|
|
49
|
+
*/
|
|
50
|
+
const MAX_SYSTEM_CACHE_BLOCKS = 2;
|
|
51
|
+
|
|
52
|
+
exports.MAX_SYSTEM_CACHE_BLOCKS = MAX_SYSTEM_CACHE_BLOCKS;
|
|
53
|
+
//# sourceMappingURL=agent-cache.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"agent-cache.cjs","sources":["../../../src/types/agent-cache.ts"],"sourcesContent":["/**\n * Agent system-message prompt-cache types.\n * ==========================================\n *\n * `@illuma-ai/agents` exposes a generic primitive — `system_cache_blocks` —\n * for composing a system message that gets explicit cache markers\n * (cachePoint on Bedrock, cache_control on Anthropic) at consumer-defined\n * boundaries. The library encodes each entry into the right wire format\n * for the active provider; consumers decide what content to put in each\n * block.\n *\n * Why this is generic rather than ranger-specific\n * ------------------------------------------------\n * Earlier iterations exposed `platform_instructions` and `cache_ttl:\n * { platform, agent }` — vocabulary borrowed from a multi-tenant chat\n * platform's mental model. That leaked a specific consumer's domain into\n * the library and made it confusing for other consumers (CLI tools,\n * desktop apps, gateways) which have no notion of \"platforms\" or \"agents\".\n *\n * The current shape lets every consumer define their own cache-tier\n * organization without the library knowing or caring.\n *\n * Cache key composition\n * ---------------------\n * Both Anthropic and Bedrock hash the message bytes leading up to each\n * cache marker. So entry N's cache key is the concatenation of bytes\n * 0..N. Stable content (universal rules, framework docs) goes earlier;\n * volatile content (per-agent identity, per-tool docs) goes later. The\n * earlier entries get cross-tenant cache hits; the later entries get\n * narrower hits.\n *\n * Provider budget\n * ---------------\n * Bedrock's Converse API supports up to 4 cachePoint blocks per request.\n * The default tools-array cache strategy (see `IllumaBedrockConverse`)\n * uses up to 2 of those. So at most 2 entries should appear in\n * `system_cache_blocks` to leave budget for the trailing\n * `instructions` block. The library throws on more than 2.\n *\n * Anthropic supports up to 4 cache breakpoints per request workspace-wide;\n * the same constraint applies to keep tools + system within budget.\n */\n\n/** Provider TTL hint applied to a cachePoint / cache_control marker. */\nexport type AgentCacheTTL = '5m' | '1h';\n\n/**\n * One cacheable system content block. Each entry produces a text block\n * followed by a provider-specific cache marker in the assembled system\n * message. Entries are emitted in array order — earlier = more stable\n * = wider cache key.\n */\nexport interface SystemCacheBlock {\n /**\n * Text payload. Caller is responsible for keeping this byte-stable\n * across requests that should share a cache entry. ANY change to\n * these bytes invalidates every cache key that includes this entry.\n */\n text: string;\n /**\n * Optional TTL hint for the cache marker. Defaults to '5m' when\n * omitted. '1h' costs more to write (2× base vs 1.25×) but survives\n * longer idle, which is the right tradeoff for low-traffic blocks.\n */\n ttl?: AgentCacheTTL;\n}\n\n/**\n * Maximum number of `system_cache_blocks` entries the library accepts.\n * Higher than this would exceed Bedrock's 4-cachePoint budget once the\n * tools array and trailing `instructions` block are counted.\n */\nexport const MAX_SYSTEM_CACHE_BLOCKS = 2;\n"],"names":[],"mappings":";;AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyCG;AA0BH;;;;AAIG;AACI,MAAM,uBAAuB,GAAG;;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"graph.cjs","sources":["../../../src/types/graph.ts"],"sourcesContent":["// src/types/graph.ts\nimport type {\n START,\n StateType,\n UpdateType,\n StateGraph,\n StateGraphArgs,\n StateDefinition,\n CompiledStateGraph,\n BinaryOperatorAggregate,\n} from '@langchain/langgraph';\nimport type { BindToolsInput } from '@langchain/core/language_models/chat_models';\nimport type {\n BaseMessage,\n AIMessageChunk,\n SystemMessage,\n} from '@langchain/core/messages';\nimport type { RunnableConfig, Runnable } from '@langchain/core/runnables';\nimport type { ChatGenerationChunk } from '@langchain/core/outputs';\nimport type { GoogleAIToolType } from '@langchain/google-common';\nimport type {\n ToolMap,\n ToolEndEvent,\n GenericTool,\n LCTool,\n ToolApprovalConfig,\n} from '@/types/tools';\nimport type { Providers, Callback, GraphNodeKeys } from '@/common';\nimport type { StandardGraph, MultiAgentGraph } from '@/graphs';\nimport type { ClientOptions } from '@/types/llm';\nimport type {\n RunStep,\n RunStepDeltaEvent,\n MessageDeltaEvent,\n ReasoningDeltaEvent,\n} from '@/types/stream';\nimport type { TokenCounter } from '@/types/run';\n\n/** Interface for bound model with stream and invoke methods */\nexport interface ChatModel {\n stream?: (\n messages: BaseMessage[],\n config?: RunnableConfig\n ) => Promise<AsyncIterable<AIMessageChunk>>;\n invoke: (\n messages: BaseMessage[],\n config?: RunnableConfig\n ) => Promise<AIMessageChunk>;\n}\n\n/** Payload for ON_AGENT_TRANSITION events */\nexport type AgentTransitionEvent = {\n sourceAgentId?: string;\n sourceAgentName?: string;\n destinationAgentId: string;\n destinationAgentName: string;\n edgeType: string; // 'handoff' | 'transfer' | 'sequence'\n timestamp: number;\n /** When true, this event signals handoff completion (child → parent return) */\n isCompletion?: boolean;\n /** Duration of child agent execution in milliseconds (only on completion events) */\n durationMs?: number;\n /** Length of child agent result text in characters (only on completion events) */\n resultLength?: number;\n};\n\nexport type GraphNode = GraphNodeKeys | typeof START;\nexport type ClientCallback<T extends unknown[]> = (\n graph: StandardGraph,\n ...args: T\n) => void;\n\nexport type ClientCallbacks = {\n [Callback.TOOL_ERROR]?: ClientCallback<[Error, string]>;\n [Callback.TOOL_START]?: ClientCallback<unknown[]>;\n [Callback.TOOL_END]?: ClientCallback<unknown[]>;\n};\n\nexport type SystemCallbacks = {\n [K in keyof ClientCallbacks]: ClientCallbacks[K] extends ClientCallback<\n infer Args\n >\n ? (...args: Args) => void\n : never;\n};\n\nexport type BaseGraphState = {\n messages: BaseMessage[];\n /**\n * Structured response when using structured output mode.\n * Contains the validated JSON response conforming to the configured schema.\n */\n structuredResponse?: Record<string, unknown>;\n};\n\nexport type MultiAgentGraphState = BaseGraphState & {\n agentMessages?: BaseMessage[];\n};\n\nexport type IState = BaseGraphState;\n\nexport interface EventHandler {\n handle(\n event: string,\n data:\n | StreamEventData\n | ModelEndData\n | RunStep\n | RunStepDeltaEvent\n | MessageDeltaEvent\n | ReasoningDeltaEvent\n | { result: ToolEndEvent },\n metadata?: Record<string, unknown>,\n graph?: StandardGraph | MultiAgentGraph\n ): void | Promise<void>;\n}\n\nexport type GraphStateChannels<T extends BaseGraphState> =\n StateGraphArgs<T>['channels'];\n\nexport type Workflow<\n T extends BaseGraphState = BaseGraphState,\n U extends Partial<T> = Partial<T>,\n N extends string = string,\n> = StateGraph<T, U, N>;\n\nexport type CompiledWorkflow<\n T extends BaseGraphState = BaseGraphState,\n U extends Partial<T> = Partial<T>,\n N extends string = string,\n> = CompiledStateGraph<T, U, N>;\n\nexport type CompiledStateWorkflow = CompiledStateGraph<\n StateType<{\n messages: BinaryOperatorAggregate<BaseMessage[], BaseMessage[]>;\n }>,\n UpdateType<{\n messages: BinaryOperatorAggregate<BaseMessage[], BaseMessage[]>;\n }>,\n string,\n {\n messages: BinaryOperatorAggregate<BaseMessage[], BaseMessage[]>;\n },\n {\n messages: BinaryOperatorAggregate<BaseMessage[], BaseMessage[]>;\n },\n StateDefinition\n>;\n\nexport type CompiledMultiAgentWorkflow = CompiledStateGraph<\n StateType<{\n messages: BinaryOperatorAggregate<BaseMessage[], BaseMessage[]>;\n agentMessages: BinaryOperatorAggregate<BaseMessage[], BaseMessage[]>;\n }>,\n UpdateType<{\n messages: BinaryOperatorAggregate<BaseMessage[], BaseMessage[]>;\n agentMessages: BinaryOperatorAggregate<BaseMessage[], BaseMessage[]>;\n }>,\n string,\n {\n messages: BinaryOperatorAggregate<BaseMessage[], BaseMessage[]>;\n agentMessages: BinaryOperatorAggregate<BaseMessage[], BaseMessage[]>;\n },\n {\n messages: BinaryOperatorAggregate<BaseMessage[], BaseMessage[]>;\n agentMessages: BinaryOperatorAggregate<BaseMessage[], BaseMessage[]>;\n },\n StateDefinition\n>;\n\nexport type CompiledAgentWorfklow = CompiledStateGraph<\n {\n messages: BaseMessage[];\n },\n {\n messages?: BaseMessage[] | undefined;\n },\n '__start__' | `agent=${string}` | `tools=${string}`,\n {\n messages: BinaryOperatorAggregate<BaseMessage[], BaseMessage[]>;\n },\n {\n messages: BinaryOperatorAggregate<BaseMessage[], BaseMessage[]>;\n },\n StateDefinition,\n {\n [x: `agent=${string}`]: Partial<BaseGraphState>;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [x: `tools=${string}`]: any;\n }\n>;\n\nexport type SystemRunnable =\n | Runnable<\n BaseMessage[],\n (BaseMessage | SystemMessage)[],\n RunnableConfig<Record<string, unknown>>\n >\n | undefined;\n\n/**\n * Optional compile options passed to workflow.compile().\n * These are intentionally untyped to avoid coupling to library internals.\n */\nexport type CompileOptions = {\n // A checkpointer instance (e.g., MemorySaver, SQL saver)\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n checkpointer?: any;\n interruptBefore?: string[];\n interruptAfter?: string[];\n /**\n * Human-in-the-loop tool approval configuration.\n * When set, tools matching the policy will trigger an interrupt()\n * before execution, pausing the graph for human approval.\n * Requires a checkpointer to be set for interrupt/resume to work.\n */\n toolApprovalConfig?: ToolApprovalConfig;\n};\n\nexport type EventStreamCallbackHandlerInput =\n Parameters<CompiledWorkflow['streamEvents']>[2] extends Omit<\n infer T,\n 'autoClose'\n >\n ? T\n : never;\n\nexport type StreamChunk =\n | (ChatGenerationChunk & {\n message: AIMessageChunk;\n })\n | AIMessageChunk;\n\n/**\n * Data associated with a StreamEvent.\n */\nexport type StreamEventData = {\n /**\n * The input passed to the runnable that generated the event.\n * Inputs will sometimes be available at the *START* of the runnable, and\n * sometimes at the *END* of the runnable.\n * If a runnable is able to stream its inputs, then its input by definition\n * won't be known until the *END* of the runnable when it has finished streaming\n * its inputs.\n */\n input?: unknown;\n /**\n * The output of the runnable that generated the event.\n * Outputs will only be available at the *END* of the runnable.\n * For most runnables, this field can be inferred from the `chunk` field,\n * though there might be some exceptions for special cased runnables (e.g., like\n * chat models), which may return more information.\n */\n output?: unknown;\n /**\n * A streaming chunk from the output that generated the event.\n * chunks support addition in general, and adding them up should result\n * in the output of the runnable that generated the event.\n */\n chunk?: StreamChunk;\n /**\n * Runnable config for invoking other runnables within handlers.\n */\n config?: RunnableConfig;\n /**\n * Custom result from the runnable that generated the event.\n */\n result?: unknown;\n /**\n * Custom field to indicate the event was manually emitted, and may have been handled already\n */\n emitted?: boolean;\n};\n\n/**\n * A streaming event.\n *\n * Schema of a streaming event which is produced from the streamEvents method.\n */\nexport type StreamEvent = {\n /**\n * Event names are of the format: on_[runnable_type]_(start|stream|end).\n *\n * Runnable types are one of:\n * - llm - used by non chat models\n * - chat_model - used by chat models\n * - prompt -- e.g., ChatPromptTemplate\n * - tool -- LangChain tools\n * - chain - most Runnables are of this type\n *\n * Further, the events are categorized as one of:\n * - start - when the runnable starts\n * - stream - when the runnable is streaming\n * - end - when the runnable ends\n *\n * start, stream and end are associated with slightly different `data` payload.\n *\n * Please see the documentation for `EventData` for more details.\n */\n event: string;\n /** The name of the runnable that generated the event. */\n name: string;\n /**\n * An randomly generated ID to keep track of the execution of the given runnable.\n *\n * Each child runnable that gets invoked as part of the execution of a parent runnable\n * is assigned its own unique ID.\n */\n run_id: string;\n /**\n * Tags associated with the runnable that generated this event.\n * Tags are always inherited from parent runnables.\n */\n tags?: string[];\n /** Metadata associated with the runnable that generated this event. */\n metadata: Record<string, unknown>;\n /**\n * Event data.\n *\n * The contents of the event data depend on the event type.\n */\n data: StreamEventData;\n};\n\nexport type GraphConfig = {\n provider: string;\n thread_id?: string;\n run_id?: string;\n};\n\nexport type PartMetadata = {\n progress?: number;\n asset_pointer?: string;\n status?: string;\n action?: boolean;\n output?: string;\n};\n\nexport type ModelEndData =\n | (StreamEventData & { output: AIMessageChunk | undefined })\n | undefined;\nexport type GraphTools = GenericTool[] | BindToolsInput[] | GoogleAIToolType[];\nexport type StandardGraphInput = {\n runId?: string;\n signal?: AbortSignal;\n agents: AgentInputs[];\n tokenCounter?: TokenCounter;\n indexTokenCountMap?: Record<string, number>;\n};\n\n/**\n * Configuration for an approval gate placed on a sequence edge.\n * When present, the graph inserts an approval gate node between the source\n * and destination agents. The gate ALWAYS fires (regardless of ExecutionContext)\n * and calls interrupt() to pause the graph for human approval.\n */\nexport type ApprovalGateConfig = {\n /** Unique identifier for this gate (used as node ID suffix) */\n gateId: string;\n /**\n * Approval channel — where the approval UI is rendered.\n * - 'chat': SSE-based chat UI (default)\n * - 'outlook': MS Graph Actionable Messages\n * - 'telegram': Telegram Bot inline keyboard\n */\n channel?: 'chat' | 'outlook' | 'telegram';\n /** Optional human-readable prompt shown to the approver */\n prompt?: string;\n /** Optional approver identifier (e.g., email, user ID) */\n approver?: string;\n /** Timeout in ms before the gate auto-expires (default: 5 minutes) */\n timeoutMs?: number;\n /** What to do on denial: 'stop' ends the graph, 'skip' skips the destination agent */\n onDeny?: 'stop' | 'skip';\n};\n\nexport type GraphEdge = {\n /** Agent ID, use a list for multiple sources */\n from: string | string[];\n /** Agent ID, use a list for multiple destinations */\n to: string | string[];\n description?: string;\n /** Can return boolean or specific destination(s) */\n condition?: (state: BaseGraphState) => boolean | string | string[];\n /**\n * EdgeType.HANDOFF — true agent handoff, parent calls child inline and gets result back.\n * EdgeType.TRANSFER — one-way transfer, parent exits and child takes over.\n * EdgeType.SEQUENCE — fixed graph edges for sequential/parallel transitions.\n */\n edgeType?: import('@/common').EdgeType;\n /**\n * For sequence edges: Optional prompt to add when transitioning through this edge.\n * String prompts can include variables like {results} which will be replaced with\n * messages from startIndex onwards. When {results} is used, excludeResults defaults to true.\n *\n * For transfer edges: Description for the input parameter that the transfer tool accepts,\n * allowing the supervisor to pass specific instructions/context to the transferred agent.\n */\n prompt?:\n | string\n | ((\n messages: BaseMessage[],\n runStartIndex: number\n ) => string | Promise<string> | undefined);\n /**\n * When true, excludes messages from startIndex when adding prompt.\n * Automatically set to true when {results} variable is used in prompt.\n */\n excludeResults?: boolean;\n /**\n * For transfer edges: Customizes the parameter name for the transfer input.\n * Defaults to \"instructions\" if not specified.\n * Only applies when prompt is provided for transfer edges.\n *\n * For handoff edges: Customizes the parameter name for the handoff instruction input.\n */\n promptKey?: string;\n /**\n * For handoff edges: Maximum characters for the result returned to the parent.\n * Uses head/tail truncation (60/40 split) to preserve key findings and conclusions.\n * Defaults to DEFAULT_HANDOFF_MAX_RESULT_CHARS (32768 chars, ~8192 tokens).\n */\n maxResultChars?: number;\n /**\n * For handoff edges: When true, the child agent receives the full parent\n * conversation history plus the orchestrator's instructions appended.\n * When false (default), the child only receives the orchestrator's scoped\n * instructions — isolated from the parent conversation.\n */\n passthrough?: boolean;\n /**\n * Approval gate configuration for sequence edges.\n * When set, inserts an approval gate node between source and destination.\n * The gate ALWAYS fires regardless of ExecutionContext (unlike tool approval).\n */\n approvalGate?: ApprovalGateConfig;\n};\n\nexport type MultiAgentGraphInput = StandardGraphInput & {\n edges: GraphEdge[];\n /**\n * When set, the graph routes START to this agent instead of the default starting nodes.\n * Used for multi-turn resumption: the caller reads `lastActiveAgentId` from the\n * previous turn's metadata and passes it here so follow-up messages route to the\n * agent that last handled the conversation.\n *\n * If the agent ID is invalid (not in the graph), falls back to default starting nodes.\n */\n resumeFromAgentId?: string;\n};\n\n/**\n * Structured output mode determines how the agent returns structured data.\n * - 'tool': Uses tool calling to return structured output (works with all tool-calling models)\n * - 'provider': Uses provider-native structured output via LangChain's jsonMode (OpenAI, Anthropic, etc.)\n * - 'native': Uses provider's constrained decoding API directly for guaranteed schema compliance\n * (Anthropic output_config.format, OpenAI response_format.json_schema). Falls back to 'tool' for unsupported providers.\n * - 'auto': Automatically selects the best strategy — 'native' for supported providers, 'tool' for others\n */\nexport type StructuredOutputMode = 'tool' | 'provider' | 'native' | 'auto';\n\n/**\n * Resolved method used internally after mode resolution.\n * Maps to LangChain's withStructuredOutput method parameter plus our native path.\n */\nexport type ResolvedStructuredOutputMethod =\n | 'functionCalling'\n | 'jsonMode'\n | 'jsonSchema'\n | 'native'\n | undefined;\n\n/**\n * Error thrown when the model refuses to produce structured output due to safety policies.\n */\nexport class StructuredOutputRefusalError extends Error {\n constructor(public refusalText: string) {\n super(`Model refused to produce structured output: ${refusalText}`);\n this.name = 'StructuredOutputRefusalError';\n }\n}\n\n/**\n * Error thrown when the structured output response was truncated due to max_tokens.\n */\nexport class StructuredOutputTruncatedError extends Error {\n constructor(public stopReason: string) {\n super(\n `Structured output was truncated (stop_reason: ${stopReason}). ` +\n 'Increase max_tokens to allow the full JSON response to be generated.'\n );\n this.name = 'StructuredOutputTruncatedError';\n }\n}\n\n/**\n * Configuration for structured JSON output from agents.\n * When configured, the agent will return a validated JSON response\n * instead of streaming text.\n */\nexport interface StructuredOutputConfig {\n /**\n * JSON Schema defining the output structure.\n * The model will be forced to return data conforming to this schema.\n */\n schema: Record<string, unknown>;\n /**\n * Name for the structured output format (used in tool mode).\n * @default 'StructuredResponse'\n */\n name?: string;\n /**\n * Description of what the structured output represents.\n * Helps the model understand the expected format.\n */\n description?: string;\n /**\n * Output mode strategy.\n * @default 'auto'\n */\n mode?: StructuredOutputMode;\n /**\n * Enable strict schema validation.\n * When true, the response must exactly match the schema.\n * @default true\n */\n strict?: boolean;\n /**\n * Error handling configuration.\n * - true: Auto-retry on validation errors (default)\n * - false: Throw error on validation failure\n * - string: Custom error message for retry\n */\n handleErrors?: boolean | string;\n /**\n * Maximum number of retry attempts on validation failure.\n * @default 2\n */\n maxRetries?: number;\n /**\n * Include the raw AI message along with structured response.\n * Useful for debugging.\n * @default false\n */\n includeRaw?: boolean;\n}\n\n/**\n * Database/API structured output format (snake_case with enabled flag).\n * This matches the format stored in MongoDB and sent from frontends.\n */\nexport interface StructuredOutputInput {\n /** Whether structured output is enabled */\n enabled?: boolean;\n /** JSON Schema defining the expected response structure */\n schema?: Record<string, unknown>;\n /** Name identifier for the structured output */\n name?: string;\n /** Description of what the structured output represents */\n description?: string;\n /** Mode for structured output: 'tool' | 'provider' | 'native' | 'auto' */\n mode?: StructuredOutputMode;\n /** Whether to enforce strict schema validation */\n strict?: boolean;\n}\n\n/**\n * Trigger strategy for when summarization should activate.\n * - 'contextPercentage': Trigger when context utilization exceeds a threshold percentage\n * - 'messageCount': Trigger when pruned message count exceeds a threshold\n * - 'tokenThreshold': Trigger when total token count exceeds a raw threshold\n */\nexport type SummarizationTriggerType =\n | 'contextPercentage'\n | 'messageCount'\n | 'tokenThreshold';\n\n/**\n * Configuration for summarization behavior within the agent pipeline.\n * All fields are optional — sensible defaults are provided via constants.\n *\n * @see SUMMARIZATION_CONTEXT_THRESHOLD, SUMMARIZATION_RESERVE_RATIO, PRUNING_EMA_ALPHA\n */\nexport interface SummarizationConfig {\n /**\n * Strategy for when summarization triggers.\n * @default 'contextPercentage'\n */\n triggerType?: SummarizationTriggerType;\n\n /**\n * Threshold value interpreted based on triggerType:\n * - contextPercentage: 0-100 (percentage of context window)\n * - messageCount: absolute count of messages pruned\n * - tokenThreshold: absolute token count\n * @default 80 (for contextPercentage)\n */\n triggerThreshold?: number;\n\n /**\n * Fraction of context window (0-1) reserved for recent messages.\n * Prevents over-pruning by ensuring at least this fraction of the\n * context budget is preserved as recent conversation history.\n * @default 0.3\n */\n reserveRatio?: number;\n\n /**\n * Whether context pruning is enabled (can be disabled for debugging).\n * @default true\n */\n contextPruning?: boolean;\n\n /**\n * Initial summary text to seed across runs.\n * Different from persistedSummary: this is provided by the caller as a\n * cross-conversation seed (e.g., agent personality or recurring context),\n * while persistedSummary is loaded from the conversation's own history.\n */\n initialSummary?: string;\n}\n\n/**\n * Runtime state for EMA-based pruning calibration.\n * Maintained across iterations within a single run to smooth pruning decisions.\n */\nexport interface PruneCalibrationState {\n /** Current EMA calibration ratio */\n ratio: number;\n /** Number of calibration updates applied */\n iterations: number;\n}\n\n/**\n * Lightweight file metadata entry for conversation-level file awareness.\n * Contains only IDs and names — NOT full content — so the agent always knows\n * what files exist in the conversation even after compaction pushes old messages\n * behind the summary window. The agent can retrieve full content on-demand\n * via file_search (RAG) or content_tool read (by contentId).\n */\nexport interface FileManifestEntry {\n /** Unique file identifier (e.g., MongoDB ObjectId or UUID) */\n fileId: string;\n /** Original filename (e.g., \"quarterly-report.pdf\") */\n filename: string;\n /** Content identifier for on-demand retrieval via content_tool read */\n contentId?: string;\n /** File source (e.g., \"local\", \"sharepoint\", \"onedrive\") */\n source?: string;\n /** Index of the message that introduced this file (0-based in the original message array) */\n messageIndex?: number;\n}\n\nexport interface AgentInputs {\n agentId: string;\n /** Human-readable name for the agent (used in handoff context). Defaults to agentId if not provided. */\n name?: string;\n /** Description of what this agent does (used to enrich handoff tool descriptions). */\n description?: string;\n toolEnd?: boolean;\n toolMap?: ToolMap;\n tools?: GraphTools;\n provider: Providers;\n instructions?: string;\n streamBuffer?: number;\n maxContextTokens?: number;\n clientOptions?: ClientOptions;\n additional_instructions?: string;\n reasoningKey?: 'reasoning_content' | 'reasoning';\n /** Format content blocks as strings (for legacy compatibility i.e. Ollama/Azure Serverless) */\n useLegacyContent?: boolean;\n /**\n * Tool definitions for all tools, including deferred and programmatic.\n * Used for tool search and programmatic tool calling.\n * Maps tool name to LCTool definition.\n */\n toolRegistry?: Map<string, LCTool>;\n /**\n * Dynamic context that changes per-request (e.g., current time, user info).\n * This is injected as a user message rather than system prompt to preserve cache.\n * Keeping this separate from instructions ensures the system message stays static\n * and can be cached by Bedrock/Anthropic prompt caching.\n */\n dynamicContext?: string;\n /**\n * Structured output configuration (camelCase).\n * When set, disables streaming and returns a validated JSON response\n * conforming to the specified schema.\n */\n structuredOutput?: StructuredOutputConfig;\n /**\n * Structured output configuration (snake_case - database/API format).\n * Alternative to structuredOutput for compatibility with MongoDB/frontend.\n * Uses an `enabled` flag to control activation.\n * @deprecated Use structuredOutput instead when possible\n */\n structured_output?: StructuredOutputInput;\n /**\n * Serializable tool definitions for event-driven execution.\n * When provided, ToolNode operates in event-driven mode, dispatching\n * ON_TOOL_EXECUTE events instead of invoking tools directly.\n */\n toolDefinitions?: LCTool[];\n /**\n * Tool names discovered from previous conversation history.\n * These tools will be pre-marked as discovered so they're included\n * in tool binding without requiring tool_search.\n */\n discoveredTools?: string[];\n /**\n * Optional callback for summarizing messages that were pruned from context.\n * When provided, discarded messages are summarized by the host caller\n * using a cheap LLM call, and the summary is prepended to the context.\n */\n summarizeCallback?: (\n messagesToRefine: import('@langchain/core/messages').BaseMessage[]\n ) => Promise<string | undefined>;\n /**\n * Pre-existing summary text loaded from persistent storage (MongoDB/Redis).\n * When provided, this summary is injected into the initial message context\n * so the agent has prior conversation history even on new turns.\n * Set by the host's summary store when resuming a conversation.\n */\n persistedSummary?: string;\n /**\n * Summarization configuration controlling trigger strategy, reserve ratio,\n * and EMA calibration for pruning. When omitted, sensible defaults apply.\n * @see SummarizationConfig\n */\n summarizationConfig?: SummarizationConfig;\n /**\n * Lightweight file manifest for the conversation.\n * Contains file IDs, names, and metadata — NOT full content.\n *\n * Used by the compaction engine to inject a [Conversation Files] block\n * into the windowed view, ensuring the LLM always knows what files exist\n * even when old messages (with full file content) are behind the summary.\n *\n * The agent can retrieve full content on-demand via:\n * - file_search (RAG semantic search over embedded files)\n * - content_tool read (by contentId for exact file retrieval)\n *\n * Built by the host orchestrator from message_file_map\n * and metadata.context_files across all conversation messages.\n */\n fileManifest?: FileManifestEntry[];\n}\n"],"names":[],"mappings":";;AAwdA;;AAEG;AACG,MAAO,4BAA6B,SAAQ,KAAK,CAAA;AAClC,IAAA,WAAA;AAAnB,IAAA,WAAA,CAAmB,WAAmB,EAAA;AACpC,QAAA,KAAK,CAAC,CAAA,4CAAA,EAA+C,WAAW,CAAA,CAAE,CAAC;QADlD,IAAA,CAAA,WAAW,GAAX,WAAW;AAE5B,QAAA,IAAI,CAAC,IAAI,GAAG,8BAA8B;IAC5C;AACD;AAED;;AAEG;AACG,MAAO,8BAA+B,SAAQ,KAAK,CAAA;AACpC,IAAA,UAAA;AAAnB,IAAA,WAAA,CAAmB,UAAkB,EAAA;QACnC,KAAK,CACH,CAAA,8CAAA,EAAiD,UAAU,CAAA,GAAA,CAAK;AAC9D,YAAA,sEAAsE,CACzE;QAJgB,IAAA,CAAA,UAAU,GAAV,UAAU;AAK3B,QAAA,IAAI,CAAC,IAAI,GAAG,gCAAgC;IAC9C;AACD;;;;;"}
|
|
1
|
+
{"version":3,"file":"graph.cjs","sources":["../../../src/types/graph.ts"],"sourcesContent":["// src/types/graph.ts\nimport type {\n START,\n StateType,\n UpdateType,\n StateGraph,\n StateGraphArgs,\n StateDefinition,\n CompiledStateGraph,\n BinaryOperatorAggregate,\n} from '@langchain/langgraph';\nimport type { BindToolsInput } from '@langchain/core/language_models/chat_models';\nimport type {\n BaseMessage,\n AIMessageChunk,\n SystemMessage,\n} from '@langchain/core/messages';\nimport type { RunnableConfig, Runnable } from '@langchain/core/runnables';\nimport type { ChatGenerationChunk } from '@langchain/core/outputs';\nimport type { GoogleAIToolType } from '@langchain/google-common';\nimport type {\n ToolMap,\n ToolEndEvent,\n GenericTool,\n LCTool,\n ToolApprovalConfig,\n ToolExecuteBatchRequest,\n} from '@/types/tools';\nimport type { Providers, Callback, GraphNodeKeys } from '@/common';\nimport type { StandardGraph, MultiAgentGraph } from '@/graphs';\nimport type { ClientOptions } from '@/types/llm';\nimport type {\n RunStep,\n RunStepDeltaEvent,\n MessageDeltaEvent,\n ReasoningDeltaEvent,\n} from '@/types/stream';\nimport type { TokenCounter } from '@/types/run';\nimport type { SystemCacheBlock, AgentCacheTTL } from '@/types/agent-cache';\n\n/** Interface for bound model with stream and invoke methods */\nexport interface ChatModel {\n stream?: (\n messages: BaseMessage[],\n config?: RunnableConfig\n ) => Promise<AsyncIterable<AIMessageChunk>>;\n invoke: (\n messages: BaseMessage[],\n config?: RunnableConfig\n ) => Promise<AIMessageChunk>;\n}\n\n/** Payload for ON_AGENT_TRANSITION events */\nexport type AgentTransitionEvent = {\n sourceAgentId?: string;\n sourceAgentName?: string;\n destinationAgentId: string;\n destinationAgentName: string;\n edgeType: string; // 'handoff' | 'transfer' | 'sequence'\n timestamp: number;\n /** When true, this event signals handoff completion (child → parent return) */\n isCompletion?: boolean;\n /** Duration of child agent execution in milliseconds (only on completion events) */\n durationMs?: number;\n /** Length of child agent result text in characters (only on completion events) */\n resultLength?: number;\n};\n\nexport type GraphNode = GraphNodeKeys | typeof START;\nexport type ClientCallback<T extends unknown[]> = (\n graph: StandardGraph,\n ...args: T\n) => void;\n\nexport type ClientCallbacks = {\n [Callback.TOOL_ERROR]?: ClientCallback<[Error, string]>;\n [Callback.TOOL_START]?: ClientCallback<unknown[]>;\n [Callback.TOOL_END]?: ClientCallback<unknown[]>;\n};\n\nexport type SystemCallbacks = {\n [K in keyof ClientCallbacks]: ClientCallbacks[K] extends ClientCallback<\n infer Args\n >\n ? (...args: Args) => void\n : never;\n};\n\nexport type BaseGraphState = {\n messages: BaseMessage[];\n /**\n * Structured response when using structured output mode.\n * Contains the validated JSON response conforming to the configured schema.\n */\n structuredResponse?: Record<string, unknown>;\n};\n\nexport type MultiAgentGraphState = BaseGraphState & {\n agentMessages?: BaseMessage[];\n};\n\nexport type IState = BaseGraphState;\n\nexport interface EventHandler {\n handle(\n event: string,\n data:\n | StreamEventData\n | ModelEndData\n | RunStep\n | RunStepDeltaEvent\n | MessageDeltaEvent\n | ReasoningDeltaEvent\n | SubagentUpdateEvent\n | ToolExecuteBatchRequest\n | { result: ToolEndEvent },\n metadata?: Record<string, unknown>,\n graph?: StandardGraph | MultiAgentGraph\n ): void | Promise<void>;\n}\n\nexport type GraphStateChannels<T extends BaseGraphState> =\n StateGraphArgs<T>['channels'];\n\nexport type Workflow<\n T extends BaseGraphState = BaseGraphState,\n U extends Partial<T> = Partial<T>,\n N extends string = string,\n> = StateGraph<T, U, N>;\n\nexport type CompiledWorkflow<\n T extends BaseGraphState = BaseGraphState,\n U extends Partial<T> = Partial<T>,\n N extends string = string,\n> = CompiledStateGraph<T, U, N>;\n\nexport type CompiledStateWorkflow = CompiledStateGraph<\n StateType<{\n messages: BinaryOperatorAggregate<BaseMessage[], BaseMessage[]>;\n }>,\n UpdateType<{\n messages: BinaryOperatorAggregate<BaseMessage[], BaseMessage[]>;\n }>,\n string,\n {\n messages: BinaryOperatorAggregate<BaseMessage[], BaseMessage[]>;\n },\n {\n messages: BinaryOperatorAggregate<BaseMessage[], BaseMessage[]>;\n },\n StateDefinition\n>;\n\nexport type CompiledMultiAgentWorkflow = CompiledStateGraph<\n StateType<{\n messages: BinaryOperatorAggregate<BaseMessage[], BaseMessage[]>;\n agentMessages: BinaryOperatorAggregate<BaseMessage[], BaseMessage[]>;\n }>,\n UpdateType<{\n messages: BinaryOperatorAggregate<BaseMessage[], BaseMessage[]>;\n agentMessages: BinaryOperatorAggregate<BaseMessage[], BaseMessage[]>;\n }>,\n string,\n {\n messages: BinaryOperatorAggregate<BaseMessage[], BaseMessage[]>;\n agentMessages: BinaryOperatorAggregate<BaseMessage[], BaseMessage[]>;\n },\n {\n messages: BinaryOperatorAggregate<BaseMessage[], BaseMessage[]>;\n agentMessages: BinaryOperatorAggregate<BaseMessage[], BaseMessage[]>;\n },\n StateDefinition\n>;\n\nexport type CompiledAgentWorfklow = CompiledStateGraph<\n {\n messages: BaseMessage[];\n },\n {\n messages?: BaseMessage[] | undefined;\n },\n '__start__' | `agent=${string}` | `tools=${string}`,\n {\n messages: BinaryOperatorAggregate<BaseMessage[], BaseMessage[]>;\n },\n {\n messages: BinaryOperatorAggregate<BaseMessage[], BaseMessage[]>;\n },\n StateDefinition,\n {\n [x: `agent=${string}`]: Partial<BaseGraphState>;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [x: `tools=${string}`]: any;\n }\n>;\n\nexport type SystemRunnable =\n | Runnable<\n BaseMessage[],\n (BaseMessage | SystemMessage)[],\n RunnableConfig<Record<string, unknown>>\n >\n | undefined;\n\n/**\n * Optional compile options passed to workflow.compile().\n * These are intentionally untyped to avoid coupling to library internals.\n */\nexport type CompileOptions = {\n // A checkpointer instance (e.g., MemorySaver, SQL saver)\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n checkpointer?: any;\n interruptBefore?: string[];\n interruptAfter?: string[];\n /**\n * Human-in-the-loop tool approval configuration.\n * When set, tools matching the policy will trigger an interrupt()\n * before execution, pausing the graph for human approval.\n * Requires a checkpointer to be set for interrupt/resume to work.\n */\n toolApprovalConfig?: ToolApprovalConfig;\n};\n\nexport type EventStreamCallbackHandlerInput =\n Parameters<CompiledWorkflow['streamEvents']>[2] extends Omit<\n infer T,\n 'autoClose'\n >\n ? T\n : never;\n\nexport type StreamChunk =\n | (ChatGenerationChunk & {\n message: AIMessageChunk;\n })\n | AIMessageChunk;\n\n/**\n * Data associated with a StreamEvent.\n */\nexport type StreamEventData = {\n /**\n * The input passed to the runnable that generated the event.\n * Inputs will sometimes be available at the *START* of the runnable, and\n * sometimes at the *END* of the runnable.\n * If a runnable is able to stream its inputs, then its input by definition\n * won't be known until the *END* of the runnable when it has finished streaming\n * its inputs.\n */\n input?: unknown;\n /**\n * The output of the runnable that generated the event.\n * Outputs will only be available at the *END* of the runnable.\n * For most runnables, this field can be inferred from the `chunk` field,\n * though there might be some exceptions for special cased runnables (e.g., like\n * chat models), which may return more information.\n */\n output?: unknown;\n /**\n * A streaming chunk from the output that generated the event.\n * chunks support addition in general, and adding them up should result\n * in the output of the runnable that generated the event.\n */\n chunk?: StreamChunk;\n /**\n * Runnable config for invoking other runnables within handlers.\n */\n config?: RunnableConfig;\n /**\n * Custom result from the runnable that generated the event.\n */\n result?: unknown;\n /**\n * Custom field to indicate the event was manually emitted, and may have been handled already\n */\n emitted?: boolean;\n};\n\n/**\n * A streaming event.\n *\n * Schema of a streaming event which is produced from the streamEvents method.\n */\nexport type StreamEvent = {\n /**\n * Event names are of the format: on_[runnable_type]_(start|stream|end).\n *\n * Runnable types are one of:\n * - llm - used by non chat models\n * - chat_model - used by chat models\n * - prompt -- e.g., ChatPromptTemplate\n * - tool -- LangChain tools\n * - chain - most Runnables are of this type\n *\n * Further, the events are categorized as one of:\n * - start - when the runnable starts\n * - stream - when the runnable is streaming\n * - end - when the runnable ends\n *\n * start, stream and end are associated with slightly different `data` payload.\n *\n * Please see the documentation for `EventData` for more details.\n */\n event: string;\n /** The name of the runnable that generated the event. */\n name: string;\n /**\n * An randomly generated ID to keep track of the execution of the given runnable.\n *\n * Each child runnable that gets invoked as part of the execution of a parent runnable\n * is assigned its own unique ID.\n */\n run_id: string;\n /**\n * Tags associated with the runnable that generated this event.\n * Tags are always inherited from parent runnables.\n */\n tags?: string[];\n /** Metadata associated with the runnable that generated this event. */\n metadata: Record<string, unknown>;\n /**\n * Event data.\n *\n * The contents of the event data depend on the event type.\n */\n data: StreamEventData;\n};\n\nexport type GraphConfig = {\n provider: string;\n thread_id?: string;\n run_id?: string;\n};\n\nexport type PartMetadata = {\n progress?: number;\n asset_pointer?: string;\n status?: string;\n action?: boolean;\n output?: string;\n};\n\nexport type ModelEndData =\n | (StreamEventData & { output: AIMessageChunk | undefined })\n | undefined;\nexport type GraphTools = GenericTool[] | BindToolsInput[] | GoogleAIToolType[];\nexport type StandardGraphInput = {\n runId?: string;\n signal?: AbortSignal;\n agents: AgentInputs[];\n tokenCounter?: TokenCounter;\n indexTokenCountMap?: Record<string, number>;\n};\n\n/**\n * Configuration for an approval gate placed on a sequence edge.\n * When present, the graph inserts an approval gate node between the source\n * and destination agents. The gate ALWAYS fires (regardless of ExecutionContext)\n * and calls interrupt() to pause the graph for human approval.\n */\nexport type ApprovalGateConfig = {\n /** Unique identifier for this gate (used as node ID suffix) */\n gateId: string;\n /**\n * Approval channel — where the approval UI is rendered.\n * - 'chat': SSE-based chat UI (default)\n * - 'outlook': MS Graph Actionable Messages\n * - 'telegram': Telegram Bot inline keyboard\n */\n channel?: 'chat' | 'outlook' | 'telegram';\n /** Optional human-readable prompt shown to the approver */\n prompt?: string;\n /** Optional approver identifier (e.g., email, user ID) */\n approver?: string;\n /** Timeout in ms before the gate auto-expires (default: 5 minutes) */\n timeoutMs?: number;\n /** What to do on denial: 'stop' ends the graph, 'skip' skips the destination agent */\n onDeny?: 'stop' | 'skip';\n};\n\nexport type GraphEdge = {\n /** Agent ID, use a list for multiple sources */\n from: string | string[];\n /** Agent ID, use a list for multiple destinations */\n to: string | string[];\n description?: string;\n /** Can return boolean or specific destination(s) */\n condition?: (state: BaseGraphState) => boolean | string | string[];\n /**\n * EdgeType.HANDOFF — one-way routing: parent emits an `lc_transfer_to_*`\n * tool call and exits, child takes over and responds directly to the\n * user. Aligns with upstream's handoff semantics.\n * EdgeType.DIRECT — fixed graph edges for automatic sequential / parallel\n * transitions. Ranger preserves its enriched wiring (fan-in with prompt,\n * parallel groups, ApprovalGateNode, excludeResults / agentMessages).\n */\n edgeType?: import('@/common').EdgeType;\n /**\n * For sequence edges: Optional prompt to add when transitioning through this edge.\n * String prompts can include variables like {results} which will be replaced with\n * messages from startIndex onwards. When {results} is used, excludeResults defaults to true.\n *\n * For transfer edges: Description for the input parameter that the transfer tool accepts,\n * allowing the supervisor to pass specific instructions/context to the transferred agent.\n */\n prompt?:\n | string\n | ((\n messages: BaseMessage[],\n runStartIndex: number\n ) => string | Promise<string> | undefined);\n /**\n * When true, excludes messages from startIndex when adding prompt.\n * Automatically set to true when {results} variable is used in prompt.\n */\n excludeResults?: boolean;\n /**\n * For transfer edges: Customizes the parameter name for the transfer input.\n * Defaults to \"instructions\" if not specified.\n * Only applies when prompt is provided for transfer edges.\n *\n * For handoff edges: Customizes the parameter name for the handoff instruction input.\n */\n promptKey?: string;\n /**\n * Approval gate configuration for sequence edges.\n * When set, inserts an approval gate node between source and destination.\n * The gate ALWAYS fires regardless of ExecutionContext (unlike tool approval).\n */\n approvalGate?: ApprovalGateConfig;\n};\n\nexport type MultiAgentGraphInput = StandardGraphInput & {\n edges: GraphEdge[];\n /**\n * When set, the graph routes START to this agent instead of the default\n * starting nodes. Used for multi-turn resumption: the caller reads the\n * last active agent id from the previous turn (e.g. via\n * `Run.getLastActiveAgentId()`, which derives it from the run's content\n * data trail) and passes it here so follow-up messages route to the\n * agent that last handled the conversation.\n *\n * If the agent ID is invalid (not in the graph), falls back to default\n * starting nodes.\n */\n resumeFromAgentId?: string;\n};\n\n/**\n * Structured output mode determines how the agent returns structured data.\n * - 'tool': Uses tool calling to return structured output (works with all tool-calling models)\n * - 'provider': Uses provider-native structured output via LangChain's jsonMode (OpenAI, Anthropic, etc.)\n * - 'native': Uses provider's constrained decoding API directly for guaranteed schema compliance\n * (Anthropic output_config.format, OpenAI response_format.json_schema). Falls back to 'tool' for unsupported providers.\n * - 'auto': Automatically selects the best strategy — 'native' for supported providers, 'tool' for others\n */\nexport type StructuredOutputMode = 'tool' | 'provider' | 'native' | 'auto';\n\n/**\n * Resolved method used internally after mode resolution.\n * Maps to LangChain's withStructuredOutput method parameter plus our native path.\n */\nexport type ResolvedStructuredOutputMethod =\n | 'functionCalling'\n | 'jsonMode'\n | 'jsonSchema'\n | 'native'\n | undefined;\n\n/**\n * Error thrown when the model refuses to produce structured output due to safety policies.\n */\nexport class StructuredOutputRefusalError extends Error {\n constructor(public refusalText: string) {\n super(`Model refused to produce structured output: ${refusalText}`);\n this.name = 'StructuredOutputRefusalError';\n }\n}\n\n/**\n * Error thrown when the structured output response was truncated due to max_tokens.\n */\nexport class StructuredOutputTruncatedError extends Error {\n constructor(public stopReason: string) {\n super(\n `Structured output was truncated (stop_reason: ${stopReason}). ` +\n 'Increase max_tokens to allow the full JSON response to be generated.'\n );\n this.name = 'StructuredOutputTruncatedError';\n }\n}\n\n/**\n * Configuration for structured JSON output from agents.\n * When configured, the agent will return a validated JSON response\n * instead of streaming text.\n */\nexport interface StructuredOutputConfig {\n /**\n * JSON Schema defining the output structure.\n * The model will be forced to return data conforming to this schema.\n */\n schema: Record<string, unknown>;\n /**\n * Name for the structured output format (used in tool mode).\n * @default 'StructuredResponse'\n */\n name?: string;\n /**\n * Description of what the structured output represents.\n * Helps the model understand the expected format.\n */\n description?: string;\n /**\n * Output mode strategy.\n * @default 'auto'\n */\n mode?: StructuredOutputMode;\n /**\n * Enable strict schema validation.\n * When true, the response must exactly match the schema.\n * @default true\n */\n strict?: boolean;\n /**\n * Error handling configuration.\n * - true: Auto-retry on validation errors (default)\n * - false: Throw error on validation failure\n * - string: Custom error message for retry\n */\n handleErrors?: boolean | string;\n /**\n * Maximum number of retry attempts on validation failure.\n * @default 2\n */\n maxRetries?: number;\n /**\n * Include the raw AI message along with structured response.\n * Useful for debugging.\n * @default false\n */\n includeRaw?: boolean;\n}\n\n/**\n * Database/API structured output format (snake_case with enabled flag).\n * This matches the format stored in MongoDB and sent from frontends.\n */\nexport interface StructuredOutputInput {\n /** Whether structured output is enabled */\n enabled?: boolean;\n /** JSON Schema defining the expected response structure */\n schema?: Record<string, unknown>;\n /** Name identifier for the structured output */\n name?: string;\n /** Description of what the structured output represents */\n description?: string;\n /** Mode for structured output: 'tool' | 'provider' | 'native' | 'auto' */\n mode?: StructuredOutputMode;\n /** Whether to enforce strict schema validation */\n strict?: boolean;\n}\n\n/**\n * Trigger strategy for when summarization should activate.\n * - 'contextPercentage': Trigger when context utilization exceeds a threshold percentage\n * - 'messageCount': Trigger when pruned message count exceeds a threshold\n * - 'tokenThreshold': Trigger when total token count exceeds a raw threshold\n */\nexport type SummarizationTriggerType =\n | 'contextPercentage'\n | 'messageCount'\n | 'tokenThreshold';\n\n/**\n * Configuration for summarization behavior within the agent pipeline.\n * All fields are optional — sensible defaults are provided via constants.\n *\n * @see SUMMARIZATION_CONTEXT_THRESHOLD, SUMMARIZATION_RESERVE_RATIO, PRUNING_EMA_ALPHA\n */\nexport interface SummarizationConfig {\n /**\n * Strategy for when summarization triggers.\n * @default 'contextPercentage'\n */\n triggerType?: SummarizationTriggerType;\n\n /**\n * Threshold value interpreted based on triggerType:\n * - contextPercentage: 0-100 (percentage of context window)\n * - messageCount: absolute count of messages pruned\n * - tokenThreshold: absolute token count\n * @default 80 (for contextPercentage)\n */\n triggerThreshold?: number;\n\n /**\n * Fraction of context window (0-1) reserved for recent messages.\n * Prevents over-pruning by ensuring at least this fraction of the\n * context budget is preserved as recent conversation history.\n * @default 0.3\n */\n reserveRatio?: number;\n\n /**\n * Whether context pruning is enabled (can be disabled for debugging).\n * @default true\n */\n contextPruning?: boolean;\n\n /**\n * Initial summary text to seed across runs.\n * Different from persistedSummary: this is provided by the caller as a\n * cross-conversation seed (e.g., agent personality or recurring context),\n * while persistedSummary is loaded from the conversation's own history.\n */\n initialSummary?: string;\n\n /**\n * Upstream-aligned optional fields. When the host wants the summarization\n * pass to run on a different LLM than the agent's own (e.g. a cheaper\n * model for compaction), these provider/model overrides flow through to\n * the summarize callback.\n */\n provider?: Providers;\n model?: string;\n parameters?: Record<string, unknown>;\n prompt?: string;\n updatePrompt?: string;\n trigger?: { type: string; value: number };\n maxSummaryTokens?: number;\n}\n\n/**\n * Runtime state for EMA-based pruning calibration.\n * Maintained across iterations within a single run to smooth pruning decisions.\n */\nexport interface PruneCalibrationState {\n /** Current EMA calibration ratio */\n ratio: number;\n /** Number of calibration updates applied */\n iterations: number;\n}\n\n/**\n * Lightweight file metadata entry for conversation-level file awareness.\n * Contains only IDs and names — NOT full content — so the agent always knows\n * what files exist in the conversation even after compaction pushes old messages\n * behind the summary window. The agent can retrieve full content on-demand\n * via file_search (RAG) or content_tool read (by contentId).\n */\nexport interface FileManifestEntry {\n /** Unique file identifier (e.g., MongoDB ObjectId or UUID) */\n fileId: string;\n /** Original filename (e.g., \"quarterly-report.pdf\") */\n filename: string;\n /** Content identifier for on-demand retrieval via content_tool read */\n contentId?: string;\n /** File source (e.g., \"local\", \"sharepoint\", \"onedrive\") */\n source?: string;\n /** Index of the message that introduced this file (0-based in the original message array) */\n messageIndex?: number;\n}\n\n/** Configuration for a subagent type that can be spawned by a parent agent. */\nexport type SubagentConfig = {\n /** Identifier used in the tool's `subagent_type` enum (e.g. 'researcher', 'coder'). */\n type: string;\n /** Human-readable display name. */\n name: string;\n /** What this subagent specializes in — shown to the LLM. */\n description: string;\n /** Full agent config for the child graph. Omit when `self` is true. */\n agentInputs?: AgentInputs;\n /** When true, reuse the parent's AgentInputs (context isolation without separate config). */\n self?: boolean;\n /** Max AGENT→TOOLS cycles before forced stop (default: 25). */\n maxTurns?: number;\n /** Allow this subagent to spawn its own subagents (default: false). */\n allowNested?: boolean;\n};\n\n/** SubagentConfig with agentInputs guaranteed present (self-spawn resolved). */\nexport type ResolvedSubagentConfig = SubagentConfig & {\n agentInputs: AgentInputs;\n};\n\n/** Lifecycle phase carried on {@link SubagentUpdateEvent}. */\nexport type SubagentUpdatePhase =\n | 'start'\n | 'run_step'\n | 'run_step_delta'\n | 'run_step_completed'\n | 'message_delta'\n | 'reasoning_delta'\n | 'stop'\n | 'error';\n\n/**\n * Wrapper event emitted when a subagent's child graph dispatches activity.\n * Lets hosts show subagent progress in a UI surface separate from the parent\n * conversation without having to untangle events by agent ID.\n */\nexport interface SubagentUpdateEvent {\n /** Parent run ID. */\n runId: string;\n /** Child run ID (unique per subagent execution). */\n subagentRunId: string;\n /**\n * Parent-side `tool_call_id` for the `subagent` tool invocation that\n * triggered this run. Stable for the duration of the child; lets hosts\n * correlate updates deterministically instead of inferring by ordering.\n * Omitted when the executor was invoked outside of a tool-call context.\n */\n parentToolCallId?: string;\n /** Subagent `type` identifier from the SubagentConfig. */\n subagentType: string;\n /** Child agent ID assigned to this subagent execution. */\n subagentAgentId: string;\n /** Parent agent ID that spawned this subagent. */\n parentAgentId?: string;\n /** Lifecycle phase carried by this update. */\n phase: SubagentUpdatePhase;\n /** Underlying event payload (shape depends on phase). */\n data?: unknown;\n /** Short human-readable description. Hosts can render this directly. */\n label?: string;\n /** ISO timestamp for ordering / display. */\n timestamp: string;\n}\n\nexport interface AgentInputs {\n agentId: string;\n /** Human-readable name for the agent (used in handoff context). Defaults to agentId if not provided. */\n name?: string;\n /** Description of what this agent does (used to enrich handoff tool descriptions). */\n description?: string;\n toolEnd?: boolean;\n toolMap?: ToolMap;\n tools?: GraphTools;\n provider: Providers;\n /**\n * Ordered list of cacheable system content blocks emitted BEFORE\n * `instructions` in the system message. Each block gets its own cache\n * marker (cachePoint on Bedrock, cache_control on Anthropic) so the\n * cache key for each block includes only the bytes up to and including\n * its own marker. Entries are emitted in array order — earlier =\n * stabler = wider cache key (best for cross-tenant sharing).\n *\n * See `src/types/agent-cache.ts` for full semantics. Capped at\n * `MAX_SYSTEM_CACHE_BLOCKS` (2) entries to stay within Bedrock's\n * 4-cachePoint budget after the tools array consumes 2.\n */\n system_cache_blocks?: SystemCacheBlock[];\n /**\n * Stable/cacheable system instructions for this agent. Always emitted\n * with its own trailing cache marker (when caching is supported by\n * the provider/model). Use `instructions_cache_ttl` to override the\n * default '5m' TTL.\n */\n instructions?: string;\n /** TTL for the trailing `instructions` cache marker. Defaults to '5m'. */\n instructions_cache_ttl?: AgentCacheTTL;\n streamBuffer?: number;\n maxContextTokens?: number;\n clientOptions?: ClientOptions;\n /**\n * Dynamic system tail appended after the cacheable instructions\n * without any cache marker. Per-user / per-message context belongs\n * here so it does not invalidate the cacheable prefix.\n */\n additional_instructions?: string;\n reasoningKey?: 'reasoning_content' | 'reasoning';\n /**\n * Subagent types this agent may spawn. When non-empty, Graph injects the\n * `subagent` tool into the agent's toolset with the per-config enum and\n * description populated.\n */\n subagentConfigs?: SubagentConfig[];\n /**\n * Maximum subagent depth allowed below this agent. Used by SubagentExecutor\n * to abort runaway nesting. Defaults to a small constant.\n */\n maxSubagentDepth?: number;\n /**\n * Pre-existing summary injected into the system message via\n * AgentContext.buildInstructionsString. Populated by SubagentExecutor when\n * spawning a self-config subagent that should inherit the parent's prior\n * compaction summary; otherwise host-supplied at run time.\n */\n initialSummary?: { text: string; tokenCount: number };\n /**\n * Upstream-aligned opt-in for summarization. When false, the agent never\n * invokes the summarize callback regardless of context utilization.\n * Defaults to undefined (treated as enabled in Ranger to preserve prior\n * behaviour); hosts that want strict opt-in semantics should set it\n * explicitly.\n */\n summarizationEnabled?: boolean;\n /** Format content blocks as strings (for legacy compatibility i.e. Ollama/Azure Serverless) */\n useLegacyContent?: boolean;\n /**\n * Tool definitions for all tools, including deferred and programmatic.\n * Used for tool search and programmatic tool calling.\n * Maps tool name to LCTool definition.\n */\n toolRegistry?: Map<string, LCTool>;\n /**\n * Dynamic context that changes per-request (e.g., current time, user info).\n * This is injected as a user message rather than system prompt to preserve cache.\n * Keeping this separate from instructions ensures the system message stays static\n * and can be cached by Bedrock/Anthropic prompt caching.\n */\n dynamicContext?: string;\n /**\n * Structured output configuration (camelCase).\n * When set, disables streaming and returns a validated JSON response\n * conforming to the specified schema.\n */\n structuredOutput?: StructuredOutputConfig;\n /**\n * Structured output configuration (snake_case - database/API format).\n * Alternative to structuredOutput for compatibility with MongoDB/frontend.\n * Uses an `enabled` flag to control activation.\n * @deprecated Use structuredOutput instead when possible\n */\n structured_output?: StructuredOutputInput;\n /**\n * Serializable tool definitions for event-driven execution.\n * When provided, ToolNode operates in event-driven mode, dispatching\n * ON_TOOL_EXECUTE events instead of invoking tools directly.\n */\n toolDefinitions?: LCTool[];\n /**\n * Tool names discovered from previous conversation history.\n * These tools will be pre-marked as discovered so they're included\n * in tool binding without requiring tool_search.\n */\n discoveredTools?: string[];\n /**\n * Optional callback for summarizing messages that were pruned from context.\n * When provided, discarded messages are summarized by the host caller\n * using a cheap LLM call, and the summary is prepended to the context.\n */\n summarizeCallback?: (\n messagesToRefine: import('@langchain/core/messages').BaseMessage[]\n ) => Promise<string | undefined>;\n /**\n * Pre-existing summary text loaded from persistent storage (MongoDB/Redis).\n * When provided, this summary is injected into the initial message context\n * so the agent has prior conversation history even on new turns.\n * Set by the host's summary store when resuming a conversation.\n */\n persistedSummary?: string;\n /**\n * Summarization configuration controlling trigger strategy, reserve ratio,\n * and EMA calibration for pruning. When omitted, sensible defaults apply.\n * @see SummarizationConfig\n */\n summarizationConfig?: SummarizationConfig;\n /**\n * Lightweight file manifest for the conversation.\n * Contains file IDs, names, and metadata — NOT full content.\n *\n * Used by the compaction engine to inject a [Conversation Files] block\n * into the windowed view, ensuring the LLM always knows what files exist\n * even when old messages (with full file content) are behind the summary.\n *\n * The agent can retrieve full content on-demand via:\n * - file_search (RAG semantic search over embedded files)\n * - content_tool read (by contentId for exact file retrieval)\n *\n * Built by the host orchestrator from message_file_map\n * and metadata.context_files across all conversation messages.\n */\n fileManifest?: FileManifestEntry[];\n}\n\n/**\n * Tunable knobs for position-based content degradation.\n * See `messages/contextPruning.ts` and `messages/contextPruningSettings.ts`.\n */\nexport interface ContextPruningConfig {\n enabled?: boolean;\n keepLastAssistants?: number;\n softTrimRatio?: number;\n hardClearRatio?: number;\n minPrunableToolChars?: number;\n softTrim?: {\n maxChars?: number;\n headChars?: number;\n tailChars?: number;\n };\n hardClear?: {\n enabled?: boolean;\n placeholder?: string;\n };\n}\n"],"names":[],"mappings":";;AAqdA;;AAEG;AACG,MAAO,4BAA6B,SAAQ,KAAK,CAAA;AAClC,IAAA,WAAA;AAAnB,IAAA,WAAA,CAAmB,WAAmB,EAAA;AACpC,QAAA,KAAK,CAAC,CAAA,4CAAA,EAA+C,WAAW,CAAA,CAAE,CAAC;QADlD,IAAA,CAAA,WAAW,GAAX,WAAW;AAE5B,QAAA,IAAI,CAAC,IAAI,GAAG,8BAA8B;IAC5C;AACD;AAED;;AAEG;AACG,MAAO,8BAA+B,SAAQ,KAAK,CAAA;AACpC,IAAA,UAAA;AAAnB,IAAA,WAAA,CAAmB,UAAkB,EAAA;QACnC,KAAK,CACH,CAAA,8CAAA,EAAiD,UAAU,CAAA,GAAA,CAAK;AAC9D,YAAA,sEAAsE,CACzE;QAJgB,IAAA,CAAA,UAAU,GAAV,UAAU;AAK3B,QAAA,IAAI,CAAC,IAAI,GAAG,gCAAgC;IAC9C;AACD;;;;;"}
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Ingestion-time and pre-flight truncation utilities for tool results.
|
|
5
|
+
*
|
|
6
|
+
* Prevents oversized tool outputs from entering the message array and
|
|
7
|
+
* consuming the entire context window.
|
|
8
|
+
*/
|
|
9
|
+
/**
|
|
10
|
+
* Absolute hard cap on tool result length (characters).
|
|
11
|
+
* Even if the model has a 1M-token context, a single tool result
|
|
12
|
+
* larger than this is almost certainly a bug (e.g., dumping a binary file).
|
|
13
|
+
*/
|
|
14
|
+
const HARD_MAX_TOOL_RESULT_CHARS = 400_000;
|
|
15
|
+
/**
|
|
16
|
+
* Absolute hard cap on the aggregate size (characters) of all registered
|
|
17
|
+
* tool outputs kept for `{{tool<i>turn<n>}}` substitution. Set at 5 MB
|
|
18
|
+
* because the registry stores *raw, untruncated* tool output — full
|
|
19
|
+
* fidelity for piping into downstream bash/jq — so the budget needs
|
|
20
|
+
* enough headroom to keep a handful of large responses without
|
|
21
|
+
* ballooning unbounded.
|
|
22
|
+
*/
|
|
23
|
+
const HARD_MAX_TOTAL_TOOL_OUTPUT_SIZE = 5_000_000;
|
|
24
|
+
/**
|
|
25
|
+
* Computes the dynamic max tool result size based on the model's context window.
|
|
26
|
+
* Uses 30% of the context window (in estimated characters, ~4 chars/token)
|
|
27
|
+
* capped at HARD_MAX_TOOL_RESULT_CHARS.
|
|
28
|
+
*
|
|
29
|
+
* @param contextWindowTokens - The model's max context tokens (optional).
|
|
30
|
+
* @returns Maximum allowed characters for a single tool result.
|
|
31
|
+
*/
|
|
32
|
+
function calculateMaxToolResultChars(contextWindowTokens) {
|
|
33
|
+
if (contextWindowTokens == null || contextWindowTokens <= 0) {
|
|
34
|
+
return HARD_MAX_TOOL_RESULT_CHARS;
|
|
35
|
+
}
|
|
36
|
+
return Math.min(Math.floor(contextWindowTokens * 0.3) * 4, HARD_MAX_TOOL_RESULT_CHARS);
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Computes the default aggregate size (characters) for the tool output
|
|
40
|
+
* reference registry based on the per-output budget. Mirrors
|
|
41
|
+
* `calculateMaxToolResultChars`'s shape: a multiple of the per-output
|
|
42
|
+
* cap, clamped to `HARD_MAX_TOTAL_TOOL_OUTPUT_SIZE`.
|
|
43
|
+
*
|
|
44
|
+
* @param maxOutputSize - Per-output maximum characters (e.g., the
|
|
45
|
+
* ToolNode's `maxToolResultChars`). When omitted or non-positive,
|
|
46
|
+
* falls back to the absolute total cap.
|
|
47
|
+
* @returns Maximum total characters retained across the registry.
|
|
48
|
+
*/
|
|
49
|
+
function calculateMaxTotalToolOutputSize(maxOutputSize) {
|
|
50
|
+
if (maxOutputSize == null || maxOutputSize <= 0) {
|
|
51
|
+
return HARD_MAX_TOTAL_TOOL_OUTPUT_SIZE;
|
|
52
|
+
}
|
|
53
|
+
return Math.min(maxOutputSize * 2, HARD_MAX_TOTAL_TOOL_OUTPUT_SIZE);
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Truncates a tool-call input (the arguments/payload of a tool_use block)
|
|
57
|
+
* using head+tail strategy. Returns an object with `_truncated` (the
|
|
58
|
+
* truncated string) and `_originalChars` (for diagnostics).
|
|
59
|
+
*
|
|
60
|
+
* Accepts any type — objects are JSON-serialized before truncation.
|
|
61
|
+
*
|
|
62
|
+
* @param input - The tool input (string, object, etc.).
|
|
63
|
+
* @param maxChars - Maximum allowed characters.
|
|
64
|
+
*/
|
|
65
|
+
function truncateToolInput(input, maxChars) {
|
|
66
|
+
const serialized = typeof input === 'string' ? input : JSON.stringify(input);
|
|
67
|
+
if (serialized.length <= maxChars) {
|
|
68
|
+
return { _truncated: serialized, _originalChars: serialized.length };
|
|
69
|
+
}
|
|
70
|
+
const indicator = `\n… [truncated: ${serialized.length} chars exceeded ${maxChars} limit] …\n`;
|
|
71
|
+
const available = maxChars - indicator.length;
|
|
72
|
+
if (available < 100) {
|
|
73
|
+
return {
|
|
74
|
+
_truncated: serialized.slice(0, maxChars) + indicator.trimEnd(),
|
|
75
|
+
_originalChars: serialized.length,
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
const headSize = Math.ceil(available * 0.7);
|
|
79
|
+
const tailSize = available - headSize;
|
|
80
|
+
return {
|
|
81
|
+
_truncated: serialized.slice(0, headSize) +
|
|
82
|
+
indicator +
|
|
83
|
+
serialized.slice(serialized.length - tailSize),
|
|
84
|
+
_originalChars: serialized.length,
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* Truncates tool result content that exceeds `maxChars` using a head+tail
|
|
89
|
+
* strategy. Keeps the beginning (structure/headers) and end (return value /
|
|
90
|
+
* conclusion) of the content so the model retains both the opening context
|
|
91
|
+
* and the final outcome.
|
|
92
|
+
*
|
|
93
|
+
* Head gets ~70% of the budget, tail gets ~30%. Falls back to head-only
|
|
94
|
+
* when the budget is too small for a meaningful tail.
|
|
95
|
+
*
|
|
96
|
+
* @param content - The tool result string content.
|
|
97
|
+
* @param maxChars - Maximum allowed characters.
|
|
98
|
+
* @returns The (possibly truncated) content string.
|
|
99
|
+
*/
|
|
100
|
+
function truncateToolResultContent(content, maxChars) {
|
|
101
|
+
if (content.length <= maxChars) {
|
|
102
|
+
return content;
|
|
103
|
+
}
|
|
104
|
+
const indicator = `\n\n… [truncated: ${content.length} chars exceeded ${maxChars} limit] …\n\n`;
|
|
105
|
+
const available = maxChars - indicator.length;
|
|
106
|
+
if (available <= 0) {
|
|
107
|
+
return content.slice(0, maxChars);
|
|
108
|
+
}
|
|
109
|
+
// When budget is too small for a meaningful tail, fall back to head-only
|
|
110
|
+
if (available < 200) {
|
|
111
|
+
return content.slice(0, available) + indicator.trimEnd();
|
|
112
|
+
}
|
|
113
|
+
const headSize = Math.ceil(available * 0.7);
|
|
114
|
+
const tailSize = available - headSize;
|
|
115
|
+
// Try to break at newline boundaries for cleaner output
|
|
116
|
+
let headEnd = headSize;
|
|
117
|
+
const headNewline = content.lastIndexOf('\n', headSize);
|
|
118
|
+
if (headNewline > headSize - 200 && headNewline > 0) {
|
|
119
|
+
headEnd = headNewline;
|
|
120
|
+
}
|
|
121
|
+
let tailStart = content.length - tailSize;
|
|
122
|
+
const tailNewline = content.indexOf('\n', tailStart);
|
|
123
|
+
if (tailNewline > 0 && tailNewline < tailStart + 200) {
|
|
124
|
+
tailStart = tailNewline + 1;
|
|
125
|
+
}
|
|
126
|
+
return content.slice(0, headEnd) + indicator + content.slice(tailStart);
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
exports.HARD_MAX_TOOL_RESULT_CHARS = HARD_MAX_TOOL_RESULT_CHARS;
|
|
130
|
+
exports.HARD_MAX_TOTAL_TOOL_OUTPUT_SIZE = HARD_MAX_TOTAL_TOOL_OUTPUT_SIZE;
|
|
131
|
+
exports.calculateMaxToolResultChars = calculateMaxToolResultChars;
|
|
132
|
+
exports.calculateMaxTotalToolOutputSize = calculateMaxTotalToolOutputSize;
|
|
133
|
+
exports.truncateToolInput = truncateToolInput;
|
|
134
|
+
exports.truncateToolResultContent = truncateToolResultContent;
|
|
135
|
+
//# sourceMappingURL=truncation.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"truncation.cjs","sources":["../../../src/utils/truncation.ts"],"sourcesContent":["/**\n * Ingestion-time and pre-flight truncation utilities for tool results.\n *\n * Prevents oversized tool outputs from entering the message array and\n * consuming the entire context window.\n */\n\n/**\n * Absolute hard cap on tool result length (characters).\n * Even if the model has a 1M-token context, a single tool result\n * larger than this is almost certainly a bug (e.g., dumping a binary file).\n */\nexport const HARD_MAX_TOOL_RESULT_CHARS = 400_000;\n\n/**\n * Absolute hard cap on the aggregate size (characters) of all registered\n * tool outputs kept for `{{tool<i>turn<n>}}` substitution. Set at 5 MB\n * because the registry stores *raw, untruncated* tool output — full\n * fidelity for piping into downstream bash/jq — so the budget needs\n * enough headroom to keep a handful of large responses without\n * ballooning unbounded.\n */\nexport const HARD_MAX_TOTAL_TOOL_OUTPUT_SIZE = 5_000_000;\n\n/**\n * Computes the dynamic max tool result size based on the model's context window.\n * Uses 30% of the context window (in estimated characters, ~4 chars/token)\n * capped at HARD_MAX_TOOL_RESULT_CHARS.\n *\n * @param contextWindowTokens - The model's max context tokens (optional).\n * @returns Maximum allowed characters for a single tool result.\n */\nexport function calculateMaxToolResultChars(\n contextWindowTokens?: number\n): number {\n if (contextWindowTokens == null || contextWindowTokens <= 0) {\n return HARD_MAX_TOOL_RESULT_CHARS;\n }\n return Math.min(\n Math.floor(contextWindowTokens * 0.3) * 4,\n HARD_MAX_TOOL_RESULT_CHARS\n );\n}\n\n/**\n * Computes the default aggregate size (characters) for the tool output\n * reference registry based on the per-output budget. Mirrors\n * `calculateMaxToolResultChars`'s shape: a multiple of the per-output\n * cap, clamped to `HARD_MAX_TOTAL_TOOL_OUTPUT_SIZE`.\n *\n * @param maxOutputSize - Per-output maximum characters (e.g., the\n * ToolNode's `maxToolResultChars`). When omitted or non-positive,\n * falls back to the absolute total cap.\n * @returns Maximum total characters retained across the registry.\n */\nexport function calculateMaxTotalToolOutputSize(\n maxOutputSize?: number\n): number {\n if (maxOutputSize == null || maxOutputSize <= 0) {\n return HARD_MAX_TOTAL_TOOL_OUTPUT_SIZE;\n }\n return Math.min(maxOutputSize * 2, HARD_MAX_TOTAL_TOOL_OUTPUT_SIZE);\n}\n\n/**\n * Truncates a tool-call input (the arguments/payload of a tool_use block)\n * using head+tail strategy. Returns an object with `_truncated` (the\n * truncated string) and `_originalChars` (for diagnostics).\n *\n * Accepts any type — objects are JSON-serialized before truncation.\n *\n * @param input - The tool input (string, object, etc.).\n * @param maxChars - Maximum allowed characters.\n */\nexport function truncateToolInput(\n input: unknown,\n maxChars: number\n): { _truncated: string; _originalChars: number } {\n const serialized = typeof input === 'string' ? input : JSON.stringify(input);\n if (serialized.length <= maxChars) {\n return { _truncated: serialized, _originalChars: serialized.length };\n }\n const indicator = `\\n… [truncated: ${serialized.length} chars exceeded ${maxChars} limit] …\\n`;\n const available = maxChars - indicator.length;\n\n if (available < 100) {\n return {\n _truncated: serialized.slice(0, maxChars) + indicator.trimEnd(),\n _originalChars: serialized.length,\n };\n }\n\n const headSize = Math.ceil(available * 0.7);\n const tailSize = available - headSize;\n\n return {\n _truncated:\n serialized.slice(0, headSize) +\n indicator +\n serialized.slice(serialized.length - tailSize),\n _originalChars: serialized.length,\n };\n}\n\n/**\n * Truncates tool result content that exceeds `maxChars` using a head+tail\n * strategy. Keeps the beginning (structure/headers) and end (return value /\n * conclusion) of the content so the model retains both the opening context\n * and the final outcome.\n *\n * Head gets ~70% of the budget, tail gets ~30%. Falls back to head-only\n * when the budget is too small for a meaningful tail.\n *\n * @param content - The tool result string content.\n * @param maxChars - Maximum allowed characters.\n * @returns The (possibly truncated) content string.\n */\nexport function truncateToolResultContent(\n content: string,\n maxChars: number\n): string {\n if (content.length <= maxChars) {\n return content;\n }\n\n const indicator = `\\n\\n… [truncated: ${content.length} chars exceeded ${maxChars} limit] …\\n\\n`;\n const available = maxChars - indicator.length;\n if (available <= 0) {\n return content.slice(0, maxChars);\n }\n\n // When budget is too small for a meaningful tail, fall back to head-only\n if (available < 200) {\n return content.slice(0, available) + indicator.trimEnd();\n }\n\n const headSize = Math.ceil(available * 0.7);\n const tailSize = available - headSize;\n\n // Try to break at newline boundaries for cleaner output\n let headEnd = headSize;\n const headNewline = content.lastIndexOf('\\n', headSize);\n if (headNewline > headSize - 200 && headNewline > 0) {\n headEnd = headNewline;\n }\n\n let tailStart = content.length - tailSize;\n const tailNewline = content.indexOf('\\n', tailStart);\n if (tailNewline > 0 && tailNewline < tailStart + 200) {\n tailStart = tailNewline + 1;\n }\n\n return content.slice(0, headEnd) + indicator + content.slice(tailStart);\n}\n"],"names":[],"mappings":";;AAAA;;;;;AAKG;AAEH;;;;AAIG;AACI,MAAM,0BAA0B,GAAG;AAE1C;;;;;;;AAOG;AACI,MAAM,+BAA+B,GAAG;AAE/C;;;;;;;AAOG;AACG,SAAU,2BAA2B,CACzC,mBAA4B,EAAA;IAE5B,IAAI,mBAAmB,IAAI,IAAI,IAAI,mBAAmB,IAAI,CAAC,EAAE;AAC3D,QAAA,OAAO,0BAA0B;IACnC;AACA,IAAA,OAAO,IAAI,CAAC,GAAG,CACb,IAAI,CAAC,KAAK,CAAC,mBAAmB,GAAG,GAAG,CAAC,GAAG,CAAC,EACzC,0BAA0B,CAC3B;AACH;AAEA;;;;;;;;;;AAUG;AACG,SAAU,+BAA+B,CAC7C,aAAsB,EAAA;IAEtB,IAAI,aAAa,IAAI,IAAI,IAAI,aAAa,IAAI,CAAC,EAAE;AAC/C,QAAA,OAAO,+BAA+B;IACxC;IACA,OAAO,IAAI,CAAC,GAAG,CAAC,aAAa,GAAG,CAAC,EAAE,+BAA+B,CAAC;AACrE;AAEA;;;;;;;;;AASG;AACG,SAAU,iBAAiB,CAC/B,KAAc,EACd,QAAgB,EAAA;AAEhB,IAAA,MAAM,UAAU,GAAG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