@illuma-ai/agents 1.5.0 → 2.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +0 -62
- package/dist/cjs/agents/AgentContext.cjs +159 -258
- package/dist/cjs/agents/AgentContext.cjs.map +1 -1
- package/dist/cjs/graphs/Graph.cjs +25 -8
- package/dist/cjs/graphs/Graph.cjs.map +1 -1
- package/dist/cjs/llm/anthropic/utils/message_inputs.cjs +1 -5
- package/dist/cjs/llm/anthropic/utils/message_inputs.cjs.map +1 -1
- package/dist/cjs/llm/bedrock/index.cjs +33 -61
- package/dist/cjs/llm/bedrock/index.cjs.map +1 -1
- package/dist/cjs/llm/openai/utils/index.cjs +10 -27
- package/dist/cjs/llm/openai/utils/index.cjs.map +1 -1
- package/dist/cjs/main.cjs +3 -84
- package/dist/cjs/main.cjs.map +1 -1
- package/dist/cjs/messages/cache.cjs +0 -89
- package/dist/cjs/messages/cache.cjs.map +1 -1
- package/dist/cjs/messages/format.cjs +10 -68
- package/dist/cjs/messages/format.cjs.map +1 -1
- package/dist/cjs/tools/BashExecutor.cjs +11 -21
- package/dist/cjs/tools/BashExecutor.cjs.map +1 -1
- package/dist/cjs/tools/CodeExecutor.cjs +10 -37
- package/dist/cjs/tools/CodeExecutor.cjs.map +1 -1
- package/dist/cjs/tools/ProgrammaticToolCalling.cjs +11 -16
- package/dist/cjs/tools/ProgrammaticToolCalling.cjs.map +1 -1
- package/dist/cjs/tools/ToolNode.cjs +73 -8
- package/dist/cjs/tools/ToolNode.cjs.map +1 -1
- package/dist/cjs/tools/search/search.cjs +3 -11
- package/dist/cjs/tools/search/search.cjs.map +1 -1
- package/dist/cjs/tools/search/tool.cjs +4 -28
- package/dist/cjs/tools/search/tool.cjs.map +1 -1
- package/dist/cjs/tools/search/utils.cjs +3 -10
- package/dist/cjs/tools/search/utils.cjs.map +1 -1
- package/dist/cjs/tools/subagent/SubagentExecutor.cjs +48 -0
- package/dist/cjs/tools/subagent/SubagentExecutor.cjs.map +1 -1
- package/dist/cjs/types/graph.cjs.map +1 -1
- package/dist/esm/agents/AgentContext.mjs +159 -258
- package/dist/esm/agents/AgentContext.mjs.map +1 -1
- package/dist/esm/graphs/Graph.mjs +25 -8
- package/dist/esm/graphs/Graph.mjs.map +1 -1
- package/dist/esm/llm/anthropic/utils/message_inputs.mjs +1 -5
- package/dist/esm/llm/anthropic/utils/message_inputs.mjs.map +1 -1
- package/dist/esm/llm/bedrock/index.mjs +34 -61
- package/dist/esm/llm/bedrock/index.mjs.map +1 -1
- package/dist/esm/llm/openai/utils/index.mjs +10 -27
- package/dist/esm/llm/openai/utils/index.mjs.map +1 -1
- package/dist/esm/main.mjs +1 -5
- package/dist/esm/main.mjs.map +1 -1
- package/dist/esm/messages/cache.mjs +0 -89
- package/dist/esm/messages/cache.mjs.map +1 -1
- package/dist/esm/messages/format.mjs +10 -68
- package/dist/esm/messages/format.mjs.map +1 -1
- package/dist/esm/tools/BashExecutor.mjs +12 -22
- package/dist/esm/tools/BashExecutor.mjs.map +1 -1
- package/dist/esm/tools/CodeExecutor.mjs +11 -37
- package/dist/esm/tools/CodeExecutor.mjs.map +1 -1
- package/dist/esm/tools/ProgrammaticToolCalling.mjs +12 -17
- package/dist/esm/tools/ProgrammaticToolCalling.mjs.map +1 -1
- package/dist/esm/tools/ToolNode.mjs +73 -8
- package/dist/esm/tools/ToolNode.mjs.map +1 -1
- package/dist/esm/tools/search/search.mjs +3 -11
- package/dist/esm/tools/search/search.mjs.map +1 -1
- package/dist/esm/tools/search/tool.mjs +4 -28
- package/dist/esm/tools/search/tool.mjs.map +1 -1
- package/dist/esm/tools/search/utils.mjs +3 -10
- package/dist/esm/tools/search/utils.mjs.map +1 -1
- package/dist/esm/tools/subagent/SubagentExecutor.mjs +48 -0
- package/dist/esm/tools/subagent/SubagentExecutor.mjs.map +1 -1
- package/dist/esm/types/graph.mjs.map +1 -1
- package/dist/types/agents/AgentContext.d.ts +25 -95
- package/dist/types/index.d.ts +0 -1
- package/dist/types/llm/bedrock/index.d.ts +1 -54
- package/dist/types/messages/format.d.ts +1 -4
- package/dist/types/tools/CodeExecutor.d.ts +0 -6
- package/dist/types/tools/search/types.d.ts +5 -99
- package/dist/types/tools/search/utils.d.ts +2 -2
- package/dist/types/tools/subagent/SubagentExecutor.d.ts +29 -0
- package/dist/types/types/graph.d.ts +24 -27
- package/dist/types/types/index.d.ts +0 -1
- package/dist/types/types/run.d.ts +0 -2
- package/dist/types/types/tools.d.ts +0 -9
- package/package.json +1 -61
- package/src/agents/AgentContext.test.ts +176 -0
- package/src/agents/AgentContext.ts +178 -304
- package/src/agents/__tests__/AgentContext.test.ts +0 -632
- package/src/graphs/Graph.ts +27 -8
- package/src/index.ts +0 -6
- package/src/llm/anthropic/utils/message_inputs.ts +1 -10
- package/src/llm/bedrock/__tests__/bedrock-caching.test.ts +18 -166
- package/src/llm/bedrock/index.ts +41 -116
- package/src/llm/openai/utils/index.ts +14 -31
- package/src/messages/cache.test.ts +24 -62
- package/src/messages/cache.ts +0 -112
- package/src/messages/format.ts +10 -89
- package/src/scripts/subagent-configurable-inheritance.ts +263 -0
- package/src/specs/anthropic.simple.test.ts +0 -61
- package/src/tools/BashExecutor.ts +13 -37
- package/src/tools/CodeExecutor.ts +11 -55
- package/src/tools/ProgrammaticToolCalling.ts +14 -29
- package/src/tools/ToolNode.ts +69 -8
- package/src/tools/__tests__/ProgrammaticToolCalling.test.ts +0 -60
- package/src/tools/__tests__/SubagentExecutor.test.ts +157 -0
- package/src/tools/search/search.ts +2 -12
- package/src/tools/search/tool.ts +2 -36
- package/src/tools/search/types.ts +8 -133
- package/src/tools/search/utils.ts +5 -13
- package/src/tools/subagent/SubagentExecutor.ts +78 -0
- package/src/types/graph.ts +21 -27
- package/src/types/index.ts +0 -1
- package/src/types/run.ts +0 -2
- package/src/types/tools.ts +0 -9
- package/dist/cjs/langchain/google-common.cjs +0 -3
- package/dist/cjs/langchain/google-common.cjs.map +0 -1
- package/dist/cjs/langchain/index.cjs +0 -86
- package/dist/cjs/langchain/index.cjs.map +0 -1
- package/dist/cjs/langchain/language_models/chat_models.cjs +0 -3
- package/dist/cjs/langchain/language_models/chat_models.cjs.map +0 -1
- package/dist/cjs/langchain/messages/tool.cjs +0 -3
- package/dist/cjs/langchain/messages/tool.cjs.map +0 -1
- package/dist/cjs/langchain/messages.cjs +0 -51
- package/dist/cjs/langchain/messages.cjs.map +0 -1
- package/dist/cjs/langchain/openai.cjs +0 -3
- package/dist/cjs/langchain/openai.cjs.map +0 -1
- package/dist/cjs/langchain/prompts.cjs +0 -11
- package/dist/cjs/langchain/prompts.cjs.map +0 -1
- package/dist/cjs/langchain/runnables.cjs +0 -19
- package/dist/cjs/langchain/runnables.cjs.map +0 -1
- package/dist/cjs/langchain/tools.cjs +0 -23
- package/dist/cjs/langchain/tools.cjs.map +0 -1
- package/dist/cjs/langchain/utils/env.cjs +0 -11
- package/dist/cjs/langchain/utils/env.cjs.map +0 -1
- package/dist/cjs/llm/bedrock/cacheSupport.cjs +0 -55
- package/dist/cjs/llm/bedrock/cacheSupport.cjs.map +0 -1
- package/dist/cjs/tools/search/tavily-scraper.cjs +0 -189
- package/dist/cjs/tools/search/tavily-scraper.cjs.map +0 -1
- package/dist/cjs/tools/search/tavily-search.cjs +0 -372
- package/dist/cjs/tools/search/tavily-search.cjs.map +0 -1
- package/dist/cjs/types/agent-cache.cjs +0 -53
- package/dist/cjs/types/agent-cache.cjs.map +0 -1
- package/dist/esm/langchain/google-common.mjs +0 -2
- package/dist/esm/langchain/google-common.mjs.map +0 -1
- package/dist/esm/langchain/index.mjs +0 -5
- package/dist/esm/langchain/index.mjs.map +0 -1
- package/dist/esm/langchain/language_models/chat_models.mjs +0 -2
- package/dist/esm/langchain/language_models/chat_models.mjs.map +0 -1
- package/dist/esm/langchain/messages/tool.mjs +0 -2
- package/dist/esm/langchain/messages/tool.mjs.map +0 -1
- package/dist/esm/langchain/messages.mjs +0 -2
- package/dist/esm/langchain/messages.mjs.map +0 -1
- package/dist/esm/langchain/openai.mjs +0 -2
- package/dist/esm/langchain/openai.mjs.map +0 -1
- package/dist/esm/langchain/prompts.mjs +0 -2
- package/dist/esm/langchain/prompts.mjs.map +0 -1
- package/dist/esm/langchain/runnables.mjs +0 -2
- package/dist/esm/langchain/runnables.mjs.map +0 -1
- package/dist/esm/langchain/tools.mjs +0 -2
- package/dist/esm/langchain/tools.mjs.map +0 -1
- package/dist/esm/langchain/utils/env.mjs +0 -2
- package/dist/esm/langchain/utils/env.mjs.map +0 -1
- package/dist/esm/llm/bedrock/cacheSupport.mjs +0 -52
- package/dist/esm/llm/bedrock/cacheSupport.mjs.map +0 -1
- package/dist/esm/tools/search/tavily-scraper.mjs +0 -186
- package/dist/esm/tools/search/tavily-scraper.mjs.map +0 -1
- package/dist/esm/tools/search/tavily-search.mjs +0 -370
- package/dist/esm/tools/search/tavily-search.mjs.map +0 -1
- package/dist/esm/types/agent-cache.mjs +0 -51
- package/dist/esm/types/agent-cache.mjs.map +0 -1
- package/dist/types/langchain/google-common.d.ts +0 -1
- package/dist/types/langchain/index.d.ts +0 -8
- package/dist/types/langchain/language_models/chat_models.d.ts +0 -1
- package/dist/types/langchain/messages/tool.d.ts +0 -1
- package/dist/types/langchain/messages.d.ts +0 -2
- package/dist/types/langchain/openai.d.ts +0 -1
- package/dist/types/langchain/prompts.d.ts +0 -1
- package/dist/types/langchain/runnables.d.ts +0 -2
- package/dist/types/langchain/tools.d.ts +0 -2
- package/dist/types/langchain/utils/env.d.ts +0 -1
- package/dist/types/llm/bedrock/cacheSupport.d.ts +0 -35
- package/dist/types/tools/search/tavily-scraper.d.ts +0 -19
- package/dist/types/tools/search/tavily-search.d.ts +0 -4
- package/dist/types/tools/subagent/types.d.ts +0 -84
- package/dist/types/types/agent-cache.d.ts +0 -70
- package/src/agents/AgentContext.js.map +0 -1
- package/src/agents/AgentContext.test.js.map +0 -1
- package/src/agents/__tests__/AgentContext.cacheTtl.live.test.ts +0 -259
- package/src/agents/__tests__/AgentContext.crossAgentTier1.live.test.ts +0 -264
- package/src/agents/__tests__/AgentContext.crossUserCache.live.test.ts +0 -342
- package/src/agents/__tests__/AgentContext.test.js.map +0 -1
- package/src/agents/__tests__/resolveStructuredOutputMode.test.js.map +0 -1
- package/src/common/enum.js.map +0 -1
- package/src/common/index.js.map +0 -1
- package/src/events.js.map +0 -1
- package/src/graphs/Graph.js.map +0 -1
- package/src/graphs/MultiAgentGraph.js.map +0 -1
- package/src/graphs/__tests__/structured-output.integration.test.js.map +0 -1
- package/src/graphs/__tests__/structured-output.test.js.map +0 -1
- package/src/graphs/contextManagement.e2e.test.js.map +0 -1
- package/src/graphs/contextManagement.test.js.map +0 -1
- package/src/graphs/handoffValidation.test.js.map +0 -1
- package/src/graphs/index.js.map +0 -1
- package/src/index.js.map +0 -1
- package/src/instrumentation.js.map +0 -1
- package/src/langchain/google-common.ts +0 -1
- package/src/langchain/index.ts +0 -8
- package/src/langchain/language_models/chat_models.ts +0 -1
- package/src/langchain/messages/tool.ts +0 -5
- package/src/langchain/messages.ts +0 -21
- package/src/langchain/openai.ts +0 -1
- package/src/langchain/prompts.ts +0 -1
- package/src/langchain/runnables.ts +0 -7
- package/src/langchain/tools.ts +0 -8
- package/src/langchain/utils/env.ts +0 -1
- package/src/llm/anthropic/index.js.map +0 -1
- package/src/llm/anthropic/types.js.map +0 -1
- package/src/llm/anthropic/utils/message_inputs.js.map +0 -1
- package/src/llm/anthropic/utils/message_outputs.js.map +0 -1
- package/src/llm/anthropic/utils/output_parsers.js.map +0 -1
- package/src/llm/anthropic/utils/server-tool-inputs.test.ts +0 -436
- package/src/llm/anthropic/utils/tools.js.map +0 -1
- package/src/llm/bedrock/__tests__/bedrock-caching.test.js.map +0 -1
- package/src/llm/bedrock/cacheSupport.test.ts +0 -99
- package/src/llm/bedrock/cacheSupport.ts +0 -53
- package/src/llm/bedrock/index.js.map +0 -1
- package/src/llm/bedrock/types.js.map +0 -1
- package/src/llm/bedrock/utils/index.js.map +0 -1
- package/src/llm/bedrock/utils/message_inputs.js.map +0 -1
- package/src/llm/bedrock/utils/message_outputs.js.map +0 -1
- package/src/llm/fake.js.map +0 -1
- package/src/llm/google/index.js.map +0 -1
- package/src/llm/google/types.js.map +0 -1
- package/src/llm/google/utils/common.js.map +0 -1
- package/src/llm/google/utils/tools.js.map +0 -1
- package/src/llm/google/utils/zod_to_genai_parameters.js.map +0 -1
- package/src/llm/openai/index.js.map +0 -1
- package/src/llm/openai/types.js.map +0 -1
- package/src/llm/openai/utils/index.js.map +0 -1
- package/src/llm/openai/utils/isReasoningModel.test.js.map +0 -1
- package/src/llm/openrouter/index.js.map +0 -1
- package/src/llm/openrouter/reasoning.test.js.map +0 -1
- package/src/llm/providers.js.map +0 -1
- package/src/llm/text.js.map +0 -1
- package/src/llm/vertexai/index.js.map +0 -1
- package/src/messages/__tests__/tools.test.js.map +0 -1
- package/src/messages/cache.js.map +0 -1
- package/src/messages/cache.test.js.map +0 -1
- package/src/messages/content.js.map +0 -1
- package/src/messages/content.test.js.map +0 -1
- package/src/messages/core.js.map +0 -1
- package/src/messages/ensureThinkingBlock.test.js.map +0 -1
- package/src/messages/format.js.map +0 -1
- package/src/messages/formatAgentMessages.test.js.map +0 -1
- package/src/messages/formatAgentMessages.tools.test.js.map +0 -1
- package/src/messages/formatMessage.test.js.map +0 -1
- package/src/messages/ids.js.map +0 -1
- package/src/messages/index.js.map +0 -1
- package/src/messages/labelContentByAgent.test.js.map +0 -1
- package/src/messages/prune.js.map +0 -1
- package/src/messages/reducer.js.map +0 -1
- package/src/messages/shiftIndexTokenCountMap.test.js.map +0 -1
- package/src/messages/summarize.js.map +0 -1
- package/src/messages/summarize.test.js.map +0 -1
- package/src/messages/tools.js.map +0 -1
- package/src/mockStream.js.map +0 -1
- package/src/prompts/collab.js.map +0 -1
- package/src/prompts/index.js.map +0 -1
- package/src/prompts/taskmanager.js.map +0 -1
- package/src/run.js.map +0 -1
- package/src/schemas/index.js.map +0 -1
- package/src/schemas/schema-preparation.test.js.map +0 -1
- package/src/schemas/validate.js.map +0 -1
- package/src/schemas/validate.test.js.map +0 -1
- package/src/scripts/abort.js.map +0 -1
- package/src/scripts/ant_web_search.js.map +0 -1
- package/src/scripts/ant_web_search_edge_case.js.map +0 -1
- package/src/scripts/ant_web_search_error_edge_case.js.map +0 -1
- package/src/scripts/args.js.map +0 -1
- package/src/scripts/bedrock-cache-debug.js.map +0 -1
- package/src/scripts/bedrock-content-aggregation-test.js.map +0 -1
- package/src/scripts/bedrock-merge-test.js.map +0 -1
- package/src/scripts/bedrock-parallel-tools-test.js.map +0 -1
- package/src/scripts/caching.js.map +0 -1
- package/src/scripts/cli.js.map +0 -1
- package/src/scripts/cli2.js.map +0 -1
- package/src/scripts/cli3.js.map +0 -1
- package/src/scripts/cli4.js.map +0 -1
- package/src/scripts/cli5.js.map +0 -1
- package/src/scripts/code_exec.js.map +0 -1
- package/src/scripts/code_exec_files.js.map +0 -1
- package/src/scripts/code_exec_multi_session.js.map +0 -1
- package/src/scripts/code_exec_ptc.js.map +0 -1
- package/src/scripts/code_exec_session.js.map +0 -1
- package/src/scripts/code_exec_simple.js.map +0 -1
- package/src/scripts/content.js.map +0 -1
- package/src/scripts/empty_input.js.map +0 -1
- package/src/scripts/handoff-test.js.map +0 -1
- package/src/scripts/image.js.map +0 -1
- package/src/scripts/memory.js.map +0 -1
- package/src/scripts/multi-agent-chain.js.map +0 -1
- package/src/scripts/multi-agent-conditional.js.map +0 -1
- package/src/scripts/multi-agent-document-review-chain.js.map +0 -1
- package/src/scripts/multi-agent-hybrid-flow.js.map +0 -1
- package/src/scripts/multi-agent-parallel-start.js.map +0 -1
- package/src/scripts/multi-agent-parallel.js.map +0 -1
- package/src/scripts/multi-agent-sequence.js.map +0 -1
- package/src/scripts/multi-agent-supervisor.js.map +0 -1
- package/src/scripts/multi-agent-test.js.map +0 -1
- package/src/scripts/parallel-asymmetric-tools-test.js.map +0 -1
- package/src/scripts/parallel-full-metadata-test.js.map +0 -1
- package/src/scripts/parallel-tools-test.js.map +0 -1
- package/src/scripts/programmatic_exec.js.map +0 -1
- package/src/scripts/programmatic_exec_agent.js.map +0 -1
- package/src/scripts/search.js.map +0 -1
- package/src/scripts/sequential-full-metadata-test.js.map +0 -1
- package/src/scripts/simple.js.map +0 -1
- package/src/scripts/single-agent-metadata-test.js.map +0 -1
- package/src/scripts/stream.js.map +0 -1
- package/src/scripts/test-custom-prompt-key.js.map +0 -1
- package/src/scripts/test-handoff-input.js.map +0 -1
- package/src/scripts/test-handoff-preamble.js.map +0 -1
- package/src/scripts/test-handoff-steering.js.map +0 -1
- package/src/scripts/test-multi-agent-list-handoff.js.map +0 -1
- package/src/scripts/test-parallel-agent-labeling.js.map +0 -1
- package/src/scripts/test-parallel-handoffs.js.map +0 -1
- package/src/scripts/test-thinking-handoff-bedrock.js.map +0 -1
- package/src/scripts/test-thinking-handoff.js.map +0 -1
- package/src/scripts/test-thinking-to-thinking-handoff-bedrock.js.map +0 -1
- package/src/scripts/test-tool-before-handoff-role-order.js.map +0 -1
- package/src/scripts/test-tools-before-handoff.js.map +0 -1
- package/src/scripts/test_code_api.js.map +0 -1
- package/src/scripts/thinking-bedrock.js.map +0 -1
- package/src/scripts/thinking-vertexai.js.map +0 -1
- package/src/scripts/thinking.js.map +0 -1
- package/src/scripts/tool_search.js.map +0 -1
- package/src/scripts/tools.js.map +0 -1
- package/src/specs/agent-handoffs-bedrock.integration.test.js.map +0 -1
- package/src/specs/agent-handoffs.test.js.map +0 -1
- package/src/specs/anthropic.simple.test.js.map +0 -1
- package/src/specs/azure.simple.test.js.map +0 -1
- package/src/specs/cache.simple.test.js.map +0 -1
- package/src/specs/custom-event-await.test.js.map +0 -1
- package/src/specs/deepseek.simple.test.js.map +0 -1
- package/src/specs/emergency-prune.test.js.map +0 -1
- package/src/specs/moonshot.simple.test.js.map +0 -1
- package/src/specs/observability.integration.test.js.map +0 -1
- package/src/specs/openai.simple.test.js.map +0 -1
- package/src/specs/openrouter.simple.test.js.map +0 -1
- package/src/specs/prune.test.js.map +0 -1
- package/src/specs/reasoning.test.js.map +0 -1
- package/src/specs/spec.utils.js.map +0 -1
- package/src/specs/thinking-handoff.test.js.map +0 -1
- package/src/specs/thinking-prune.test.js.map +0 -1
- package/src/specs/token-distribution-edge-case.test.js.map +0 -1
- package/src/specs/token-memoization.test.js.map +0 -1
- package/src/specs/tokens.test.js.map +0 -1
- package/src/specs/tool-error.test.js.map +0 -1
- package/src/splitStream.js.map +0 -1
- package/src/splitStream.test.js.map +0 -1
- package/src/stream.js.map +0 -1
- package/src/stream.test.js.map +0 -1
- package/src/test/mockTools.js.map +0 -1
- package/src/tools/BrowserTools.js.map +0 -1
- package/src/tools/Calculator.js.map +0 -1
- package/src/tools/Calculator.test.js.map +0 -1
- package/src/tools/CodeExecutor.js.map +0 -1
- package/src/tools/ProgrammaticToolCalling.js.map +0 -1
- package/src/tools/StreamingToolCallBuffer.js.map +0 -1
- package/src/tools/ToolNode.js.map +0 -1
- package/src/tools/ToolSearch.js.map +0 -1
- package/src/tools/__tests__/BrowserTools.test.js.map +0 -1
- package/src/tools/__tests__/ProgrammaticToolCalling.integration.test.js.map +0 -1
- package/src/tools/__tests__/ProgrammaticToolCalling.test.js.map +0 -1
- package/src/tools/__tests__/StreamingToolCallBuffer.test.js.map +0 -1
- package/src/tools/__tests__/ToolApproval.test.js.map +0 -1
- package/src/tools/__tests__/ToolNode.recovery.test.js.map +0 -1
- package/src/tools/__tests__/ToolNode.session.test.js.map +0 -1
- package/src/tools/__tests__/ToolSearch.integration.test.js.map +0 -1
- package/src/tools/__tests__/ToolSearch.test.js.map +0 -1
- package/src/tools/__tests__/handlers.test.js.map +0 -1
- package/src/tools/__tests__/truncation-recovery.integration.test.js.map +0 -1
- package/src/tools/handlers.js.map +0 -1
- package/src/tools/schema.js.map +0 -1
- package/src/tools/search/anthropic.js.map +0 -1
- package/src/tools/search/content.js.map +0 -1
- package/src/tools/search/content.test.js.map +0 -1
- package/src/tools/search/firecrawl.js.map +0 -1
- package/src/tools/search/format.js.map +0 -1
- package/src/tools/search/highlights.js.map +0 -1
- package/src/tools/search/index.js.map +0 -1
- package/src/tools/search/jina-reranker.test.js.map +0 -1
- package/src/tools/search/rerankers.js.map +0 -1
- package/src/tools/search/schema.js.map +0 -1
- package/src/tools/search/search.js.map +0 -1
- package/src/tools/search/serper-scraper.js.map +0 -1
- package/src/tools/search/tavily-scraper.ts +0 -235
- package/src/tools/search/tavily-search.ts +0 -424
- package/src/tools/search/tavily.test.ts +0 -965
- package/src/tools/search/test.js.map +0 -1
- package/src/tools/search/tool.js.map +0 -1
- package/src/tools/search/types.js.map +0 -1
- package/src/tools/search/utils.js.map +0 -1
- package/src/tools/subagent/types.test.ts +0 -70
- package/src/tools/subagent/types.ts +0 -115
- package/src/types/agent-cache.ts +0 -73
- package/src/types/graph.js.map +0 -1
- package/src/types/graph.test.js.map +0 -1
- package/src/types/index.js.map +0 -1
- package/src/types/llm.js.map +0 -1
- package/src/types/messages.js.map +0 -1
- package/src/types/run.js.map +0 -1
- package/src/types/stream.js.map +0 -1
- package/src/types/tools.js.map +0 -1
- package/src/utils/contextAnalytics.js.map +0 -1
- package/src/utils/contextAnalytics.test.js.map +0 -1
- package/src/utils/events.js.map +0 -1
- package/src/utils/graph.js.map +0 -1
- package/src/utils/handlers.js.map +0 -1
- package/src/utils/index.js.map +0 -1
- package/src/utils/llm.js.map +0 -1
- package/src/utils/llmConfig.js.map +0 -1
- package/src/utils/logging.js.map +0 -1
- package/src/utils/misc.js.map +0 -1
- package/src/utils/run.js.map +0 -1
- package/src/utils/schema.js.map +0 -1
- package/src/utils/title.js.map +0 -1
- package/src/utils/tokens.js.map +0 -1
- package/src/utils/toonFormat.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"SubagentExecutor.mjs","sources":["../../../../src/tools/subagent/SubagentExecutor.ts"],"sourcesContent":["import { nanoid } from 'nanoid';\nimport { BaseCallbackHandler } from '@langchain/core/callbacks/base';\nimport { HumanMessage } from '@langchain/core/messages';\nimport type { BaseMessage } from '@langchain/core/messages';\nimport type { Callbacks } from '@langchain/core/callbacks/manager';\nimport type {\n AgentInputs,\n StandardGraphInput,\n ResolvedSubagentConfig,\n SubagentConfig,\n SubagentUpdateEvent,\n SubagentUpdatePhase,\n ToolExecuteBatchRequest,\n TokenCounter,\n} from '@/types';\nimport type { AggregatedHookResult, HookRegistry } from '@/hooks';\nimport type { AgentContext } from '@/agents/AgentContext';\nimport type { StandardGraph } from '@/graphs/Graph';\nimport { GraphEvents, Callback } from '@/common';\nimport type { HandlerRegistry } from '@/events';\nimport { executeHooks } from '@/hooks';\n\nconst DEFAULT_MAX_TURNS = 25;\nconst RECURSION_MULTIPLIER = 3;\nconst ERROR_MESSAGE_MAX_CHARS = 200;\n\nconst HOOK_FALLBACK: AggregatedHookResult = Object.freeze({\n additionalContexts: [] as string[],\n errors: [] as string[],\n});\n\nexport type SubagentExecuteParams = {\n description: string;\n subagentType: string;\n threadId?: string;\n /**\n * Parent-side `tool_call_id` of the `subagent` tool invocation that\n * triggered this execution. Surfaced on {@link SubagentUpdateEvent} so\n * hosts can correlate child updates back to the originating tool call\n * without relying on event ordering heuristics.\n */\n parentToolCallId?: string;\n};\n\nexport type SubagentExecuteResult = {\n content: string;\n messages: BaseMessage[];\n};\n\n/**\n * Factory that constructs a child graph for subagent execution. Injected\n * rather than imported so that `SubagentExecutor` does not have a runtime\n * dependency on `StandardGraph` — this avoids a circular dependency between\n * `src/graphs/Graph.ts` and `src/tools/subagent/` that would otherwise break\n * Rollup's chunking under `preserveModules`.\n */\nexport type ChildGraphFactory = (input: StandardGraphInput) => StandardGraph;\n\nexport type SubagentExecutorOptions = {\n configs: Map<string, ResolvedSubagentConfig>;\n parentSignal?: AbortSignal;\n hookRegistry?: HookRegistry;\n parentRunId: string;\n parentAgentId?: string;\n tokenCounter?: TokenCounter;\n /** Remaining nesting budget. 0 or negative blocks execution. */\n maxDepth?: number;\n /**\n * Factory for constructing the isolated child graph. Callers pass\n * `(input) => new StandardGraph(input)` — injected to break a circular\n * module dependency.\n */\n createChildGraph: ChildGraphFactory;\n /**\n * Parent's event handler registry. When provided, child-graph events are\n * forwarded through this registry so hosts can:\n * (a) execute event-driven tools (`ON_TOOL_EXECUTE` routed to parent's handler),\n * (b) surface child activity to a UI via wrapped {@link GraphEvents.ON_SUBAGENT_UPDATE}.\n * When omitted, the child runs fully isolated (legacy behavior).\n *\n * Can be a direct `HandlerRegistry` or a zero-arg getter — use the getter\n * form when the registry is assigned to the graph AFTER the executor is\n * constructed (the current `Run.create` flow sets `handlerRegistry`\n * post-`createWorkflow`, so `createAgentNode` must capture lazily).\n */\n parentHandlerRegistry?: HandlerRegistry | (() => HandlerRegistry | undefined);\n};\n\nexport class SubagentExecutor {\n private readonly configs: Map<string, ResolvedSubagentConfig>;\n private readonly parentSignal?: AbortSignal;\n private readonly hookRegistry?: HookRegistry;\n private readonly parentRunId: string;\n private readonly parentAgentId?: string;\n private readonly tokenCounter?: TokenCounter;\n private readonly maxDepth: number;\n private readonly createChildGraph: ChildGraphFactory;\n private readonly resolveParentHandlerRegistry?: () =>\n | HandlerRegistry\n | undefined;\n\n constructor(options: SubagentExecutorOptions) {\n this.configs = options.configs;\n this.parentSignal = options.parentSignal;\n this.hookRegistry = options.hookRegistry;\n this.parentRunId = options.parentRunId;\n this.parentAgentId = options.parentAgentId;\n this.tokenCounter = options.tokenCounter;\n this.maxDepth = options.maxDepth ?? 1;\n this.createChildGraph = options.createChildGraph;\n const rawRegistry = options.parentHandlerRegistry;\n if (typeof rawRegistry === 'function') {\n this.resolveParentHandlerRegistry = rawRegistry;\n } else if (rawRegistry != null) {\n this.resolveParentHandlerRegistry = (): HandlerRegistry => rawRegistry;\n }\n }\n\n /** Snapshot of the parent's registry at the moment a subagent is dispatched. */\n private getParentHandlerRegistry(): HandlerRegistry | undefined {\n return this.resolveParentHandlerRegistry?.();\n }\n\n async execute(params: SubagentExecuteParams): Promise<SubagentExecuteResult> {\n const { description, subagentType, threadId, parentToolCallId } = params;\n const config = this.configs.get(subagentType);\n\n if (!config) {\n const available = [...this.configs.keys()].join(', ');\n return {\n content: `Error: Unknown subagent type \"${subagentType}\". Available types: ${available}`,\n messages: [],\n };\n }\n\n if (this.maxDepth <= 0) {\n return {\n content: 'Error: Maximum subagent nesting depth exceeded.',\n messages: [],\n };\n }\n\n const childAgentId =\n config.agentInputs.agentId ||\n `${this.parentAgentId ?? 'agent'}_sub_${nanoid(8)}`;\n\n if (\n this.hookRegistry?.hasHookFor('SubagentStart', this.parentRunId) === true\n ) {\n const hookResult = await executeHooks({\n registry: this.hookRegistry,\n input: {\n hook_event_name: 'SubagentStart',\n runId: this.parentRunId,\n threadId,\n parentAgentId: this.parentAgentId,\n agentId: childAgentId,\n agentType: subagentType,\n inputs: [new HumanMessage(description)],\n },\n sessionId: this.parentRunId,\n matchQuery: subagentType,\n }).catch((): AggregatedHookResult => HOOK_FALLBACK);\n\n /**\n * `ask` is treated identically to `deny` in the subagent context:\n * subagents are non-interactive, so there is no prompt path for `ask`.\n * Both decisions block execution and return a \"Blocked\" tool result.\n */\n if (hookResult.decision === 'deny' || hookResult.decision === 'ask') {\n return {\n content: `Blocked: ${hookResult.reason ?? 'Blocked by hook'}`,\n messages: [],\n };\n }\n }\n\n const parentRegistry = this.getParentHandlerRegistry();\n const forwardingEnabled = parentRegistry != null;\n /**\n * Keep `toolDefinitions` only when the host has actually wired an\n * `ON_TOOL_EXECUTE` handler. `Run` always constructs a `HandlerRegistry`,\n * so treating any registry as \"forwarding enabled\" would leak\n * `toolDefinitions` into children whose hosts cannot execute them — the\n * child's `ToolNode` batch promise would hang forever with no handler to\n * resolve/reject. Gating on the tool-execute handler preserves the\n * recoverable \"no tools\" path for registry-but-no-handler configs.\n */\n const hasToolExecuteHandler =\n parentRegistry?.getHandler(GraphEvents.ON_TOOL_EXECUTE) != null;\n const childInputs = buildChildInputs(\n config,\n childAgentId,\n this.maxDepth,\n /* keepToolDefinitions */ hasToolExecuteHandler\n );\n const childRunId = `${this.parentRunId}_sub_${nanoid(8)}`;\n const maxTurns = config.maxTurns ?? DEFAULT_MAX_TURNS;\n\n const childGraph = this.createChildGraph({\n runId: childRunId,\n signal: this.parentSignal,\n agents: [childInputs],\n tokenCounter: this.tokenCounter,\n });\n\n const forwarder = forwardingEnabled\n ? this.createForwarderCallback({\n parentRegistry: parentRegistry!,\n subagentType,\n subagentAgentId: childAgentId,\n childRunId,\n parentToolCallId,\n })\n : undefined;\n\n if (forwarder) {\n await this.emitSubagentUpdate(parentRegistry!, {\n childRunId,\n subagentType,\n subagentAgentId: childAgentId,\n parentToolCallId,\n phase: 'start',\n label: `Subagent \"${subagentType}\" started`,\n });\n }\n\n let result: { messages: BaseMessage[] };\n try {\n const workflow = childGraph.createWorkflow();\n /**\n * When `parentHandlerRegistry` is provided (forwarding mode), attach a\n * lightweight callback that intercepts the child's `on_custom_event`\n * dispatches and routes them to the parent's registry — either as\n * operational events (ON_TOOL_EXECUTE) or wrapped ON_SUBAGENT_UPDATE\n * envelopes. Native LangChain streaming events (on_chat_model_stream,\n * etc.) still do NOT propagate to the parent's outer streamEvents\n * iterator — the `callbacks` array REPLACES the inherited chain, so\n * parent handlers won't receive child stream chunks and raise \"No\n * agent context found\" lookups on the parent's agentContexts map.\n *\n * When no registry is provided (legacy isolation), `callbacks: []`\n * fully detaches the child.\n *\n * `runName` gives the child a distinct LangSmith trace root (avoids\n * nested trace pollution).\n */\n const callbacks: Callbacks = forwarder ? [forwarder] : [];\n result = await workflow.invoke(\n { messages: [new HumanMessage(description)] },\n {\n recursionLimit: maxTurns * RECURSION_MULTIPLIER,\n signal: this.parentSignal,\n callbacks,\n runName: `subagent:${subagentType}`,\n configurable: {\n thread_id: childRunId,\n },\n }\n );\n } catch (error) {\n const errorMessage = truncateErrorMessage(error);\n if (forwarder) {\n await this.emitSubagentUpdate(parentRegistry!, {\n childRunId,\n subagentType,\n subagentAgentId: childAgentId,\n parentToolCallId,\n phase: 'error',\n label: `Subagent \"${subagentType}\" errored: ${errorMessage}`,\n data: { message: errorMessage },\n });\n }\n childGraph.clearHeavyState();\n return {\n content: `Subagent error: ${errorMessage}`,\n messages: [],\n };\n }\n\n const filteredContent = filterSubagentResult(result.messages);\n\n if (\n this.hookRegistry?.hasHookFor('SubagentStop', this.parentRunId) === true\n ) {\n /**\n * Awaited (not fire-and-forget) for deterministic test synchronization\n * and consistency with PostCompact. The parent is already waiting on the\n * tool result, so the small extra latency is acceptable. Errors are\n * swallowed — SubagentStop is observational.\n */\n await executeHooks({\n registry: this.hookRegistry,\n input: {\n hook_event_name: 'SubagentStop',\n runId: this.parentRunId,\n threadId,\n agentId: childAgentId,\n agentType: subagentType,\n messages: result.messages,\n },\n sessionId: this.parentRunId,\n matchQuery: subagentType,\n }).catch(() => {\n /* SubagentStop is observational — swallow errors */\n });\n }\n\n if (forwarder) {\n await this.emitSubagentUpdate(parentRegistry!, {\n childRunId,\n subagentType,\n subagentAgentId: childAgentId,\n parentToolCallId,\n phase: 'stop',\n label: `Subagent \"${subagentType}\" finished`,\n });\n }\n\n childGraph.clearHeavyState();\n\n return { content: filteredContent, messages: result.messages };\n }\n\n /**\n * Emits a single {@link GraphEvents.ON_SUBAGENT_UPDATE} envelope through the\n * parent's handler registry. Silent no-op when no parent registry is set.\n * Errors are swallowed — update events are observational.\n */\n private async emitSubagentUpdate(\n parentRegistry: HandlerRegistry,\n args: {\n childRunId: string;\n subagentType: string;\n subagentAgentId: string;\n parentToolCallId?: string;\n phase: SubagentUpdatePhase;\n data?: unknown;\n label?: string;\n }\n ): Promise<void> {\n const handler = parentRegistry.getHandler(GraphEvents.ON_SUBAGENT_UPDATE);\n if (!handler) {\n return;\n }\n const event: SubagentUpdateEvent = {\n runId: this.parentRunId,\n subagentRunId: args.childRunId,\n subagentType: args.subagentType,\n subagentAgentId: args.subagentAgentId,\n parentAgentId: this.parentAgentId,\n parentToolCallId: args.parentToolCallId,\n phase: args.phase,\n data: args.data,\n label: args.label,\n timestamp: new Date().toISOString(),\n };\n try {\n await handler.handle(GraphEvents.ON_SUBAGENT_UPDATE, event);\n } catch {\n /* observational — swallow */\n }\n }\n\n /**\n * Builds a BaseCallbackHandler that intercepts the child graph's custom\n * events. Routing rules:\n * - `ON_TOOL_EXECUTE` → forwarded as-is to the parent's ON_TOOL_EXECUTE\n * handler (so event-driven tools work identically for child and parent).\n * - `ON_RUN_STEP` / `ON_RUN_STEP_DELTA` / `ON_RUN_STEP_COMPLETED` /\n * `ON_MESSAGE_DELTA` / `ON_REASONING_DELTA` → wrapped in a\n * {@link GraphEvents.ON_SUBAGENT_UPDATE} envelope with a human-readable\n * label, delivered to the parent's subagent-update handler.\n * - Everything else → ignored (keeps parent's UI scoped to the events it\n * cares about; host apps can extend by registering more phases).\n */\n private createForwarderCallback(args: {\n parentRegistry: HandlerRegistry;\n subagentType: string;\n subagentAgentId: string;\n childRunId: string;\n parentToolCallId?: string;\n }): BaseCallbackHandler {\n const {\n parentRegistry,\n subagentType,\n subagentAgentId,\n childRunId,\n parentToolCallId,\n } = args;\n const parentRunId = this.parentRunId;\n const parentAgentId = this.parentAgentId;\n\n const wrap = async (\n eventName: string,\n phase: SubagentUpdatePhase,\n data: unknown\n ): Promise<void> => {\n const handler = parentRegistry.getHandler(GraphEvents.ON_SUBAGENT_UPDATE);\n if (!handler) {\n return;\n }\n const event: SubagentUpdateEvent = {\n runId: parentRunId,\n subagentRunId: childRunId,\n subagentType,\n subagentAgentId,\n parentAgentId,\n parentToolCallId,\n phase,\n data,\n label: summarizeEvent(eventName, data),\n timestamp: new Date().toISOString(),\n };\n try {\n await handler.handle(GraphEvents.ON_SUBAGENT_UPDATE, event);\n } catch {\n /* observational — swallow */\n }\n };\n\n const handler = BaseCallbackHandler.fromMethods({\n [Callback.CUSTOM_EVENT]: async (\n eventName: string,\n data: unknown\n ): Promise<void> => {\n if (eventName === GraphEvents.ON_TOOL_EXECUTE) {\n const toolHandler = parentRegistry.getHandler(\n GraphEvents.ON_TOOL_EXECUTE\n );\n if (toolHandler) {\n await toolHandler.handle(\n GraphEvents.ON_TOOL_EXECUTE,\n data as ToolExecuteBatchRequest\n );\n }\n /**\n * We also surface a short notice in the subagent-update stream so\n * the UI can show \"calling <tool>\" for each tool the child spawns.\n */\n await wrap(eventName, 'run_step', data);\n return;\n }\n\n if (eventName === GraphEvents.ON_RUN_STEP) {\n await wrap(eventName, 'run_step', data);\n return;\n }\n if (eventName === GraphEvents.ON_RUN_STEP_DELTA) {\n await wrap(eventName, 'run_step_delta', data);\n return;\n }\n if (eventName === GraphEvents.ON_RUN_STEP_COMPLETED) {\n await wrap(eventName, 'run_step_completed', data);\n return;\n }\n if (eventName === GraphEvents.ON_MESSAGE_DELTA) {\n await wrap(eventName, 'message_delta', data);\n return;\n }\n if (eventName === GraphEvents.ON_REASONING_DELTA) {\n await wrap(eventName, 'reasoning_delta', data);\n return;\n }\n },\n });\n /**\n * `awaitHandlers = true` is required so the child's `ToolNode` actually\n * blocks on the parent's `ON_TOOL_EXECUTE` handler until it resolves\n * the batch request. The same flag applies to observational events\n * (message_delta, run_step, …), which means a slow\n * `ON_SUBAGENT_UPDATE` handler on the host serializes the child\n * stream. If host-side latency becomes a concern, a future\n * refinement could split operational and observational events into\n * separate callback handlers with distinct await semantics.\n */\n handler.awaitHandlers = true;\n return handler;\n }\n}\n\n/**\n * Produces a short single-line label for an arbitrary forwarded child event.\n * Used to populate {@link SubagentUpdateEvent.label} so the host UI can show\n * a compact status ticker without parsing the raw payload.\n */\nexport function summarizeEvent(eventName: string, data: unknown): string {\n if (eventName === GraphEvents.ON_TOOL_EXECUTE) {\n const req = data as { toolCalls?: Array<{ name?: string }> };\n const names = (req.toolCalls ?? [])\n .map((c) => c.name)\n .filter((n): n is string => typeof n === 'string');\n return names.length > 0 ? `Calling ${names.join(', ')}` : 'Calling tool';\n }\n if (eventName === GraphEvents.ON_RUN_STEP) {\n const step = data as {\n type?: string;\n stepDetails?: { type?: string; tool_calls?: Array<{ name?: string }> };\n };\n const detailType = step.stepDetails?.type ?? step.type ?? 'step';\n if (detailType === 'tool_calls') {\n const names = (step.stepDetails?.tool_calls ?? [])\n .map((c) => c.name)\n .filter((n): n is string => typeof n === 'string');\n return names.length > 0\n ? `Using tool: ${names.join(', ')}`\n : 'Planning tool call';\n }\n if (detailType === 'message_creation') {\n return 'Thinking…';\n }\n return `Step: ${detailType}`;\n }\n if (eventName === GraphEvents.ON_RUN_STEP_COMPLETED) {\n const step = data as {\n result?: {\n type?: string;\n tool_call?: { name?: string; output?: string };\n };\n };\n const tool = step.result?.tool_call;\n if (tool?.name != null && tool.name !== '') {\n return `Tool ${tool.name} complete`;\n }\n return 'Step complete';\n }\n if (eventName === GraphEvents.ON_MESSAGE_DELTA) {\n return 'Streaming…';\n }\n return eventName;\n}\n\n/**\n * Walk messages from last to first, returning the text content of the most\n * recent AIMessage that has any. Non-text blocks (tool_use, thinking,\n * redacted_thinking, tool_result) are stripped. If the last AIMessage is\n * pure tool_use (e.g. the subagent hit `maxTurns` mid-tool-call), the walk\n * continues to earlier AIMessages so partial progress is salvaged — this\n * matches Claude Code's behavior in `agentToolUtils.finalizeAgentTool`.\n * Returns \"Task completed\" only when no AIMessage in the history contains\n * any text.\n */\nexport function filterSubagentResult(messages: BaseMessage[]): string {\n for (let i = messages.length - 1; i >= 0; i--) {\n if (messages[i]._getType() !== 'ai') {\n continue;\n }\n\n const content = messages[i].content;\n\n if (typeof content === 'string') {\n if (content) return content;\n continue;\n }\n\n if (!Array.isArray(content)) {\n continue;\n }\n\n const textParts: string[] = [];\n for (const block of content) {\n if (typeof block === 'string') {\n textParts.push(block);\n } else if ('type' in block && block.type === 'text' && 'text' in block) {\n textParts.push(block.text as string);\n }\n }\n\n if (textParts.length > 0) {\n return textParts.join('\\n');\n }\n }\n\n return 'Task completed';\n}\n\n/**\n * Resolve self-spawn configs by filling in agentInputs from the parent context.\n * Returns configs with agentInputs guaranteed present. Throws on duplicate\n * `type` values to prevent silent config shadowing.\n */\nexport function resolveSubagentConfigs(\n configs: SubagentConfig[],\n parentContext: AgentContext\n): ResolvedSubagentConfig[] {\n const resolved = configs\n .map((config) => {\n if (config.agentInputs != null) {\n return config as ResolvedSubagentConfig;\n }\n if (config.self !== true || parentContext._sourceInputs == null) {\n return null;\n }\n return {\n ...config,\n agentInputs: { ...parentContext._sourceInputs },\n } as ResolvedSubagentConfig;\n })\n .filter((c): c is ResolvedSubagentConfig => c != null);\n\n const seenTypes = new Set<string>();\n for (const config of resolved) {\n if (seenTypes.has(config.type)) {\n throw new Error(\n `Duplicate subagent type \"${config.type}\". Each SubagentConfig must have a unique \"type\" field.`\n );\n }\n seenTypes.add(config.type);\n }\n\n return resolved;\n}\n\n/**\n * Build child AgentInputs from a resolved config, stripping nesting and\n * (optionally) event-driven fields. When `allowNested: true`, the child's\n * `maxSubagentDepth` is decremented so that depth is consumed as the call\n * chain deepens across graph boundaries — the parent's executor-level check\n * alone cannot see into the child graph's separate executor.\n *\n * When `keepToolDefinitions` is `true`, the child retains the parent's\n * `toolDefinitions` so event-driven tools remain usable. This is only safe\n * when the caller has wired a forwarder for `ON_TOOL_EXECUTE` to a\n * registered handler — otherwise the child will hang on tool dispatch.\n *\n * @remarks Advanced utility: exported primarily for testing and by\n * {@link SubagentExecutor}. Host applications configuring subagents should\n * not need to call this directly — it is invoked internally when a subagent\n * tool is dispatched. The depth-countdown contract (parent's `maxDepth` in,\n * child's decremented `maxSubagentDepth` on the returned inputs) is the\n * mechanism that bounds nesting across graph boundaries; callers must\n * respect it.\n */\nexport function buildChildInputs(\n config: ResolvedSubagentConfig,\n childAgentId: string,\n parentMaxDepth: number,\n keepToolDefinitions: boolean = false\n): AgentInputs {\n const { agentInputs } = config;\n const childInputs: AgentInputs = {\n ...agentInputs,\n agentId: childAgentId,\n toolDefinitions: keepToolDefinitions\n ? agentInputs.toolDefinitions\n : undefined,\n /**\n * Subagents run in an isolated context by contract. Parent-run-scoped\n * fields that would otherwise survive the shallow-spread clone — the\n * cross-run conversation summary and the prior-turn tool-discovery\n * set — are cleared here so the child starts fresh. Host applications\n * that want a subagent to see parent context must thread it in\n * explicitly (e.g. via the `description` argument to the subagent\n * tool), not via inherited state.\n */\n initialSummary: undefined,\n discoveredTools: undefined,\n };\n\n if (config.allowNested === true) {\n childInputs.maxSubagentDepth = Math.max(0, parentMaxDepth - 1);\n } else {\n childInputs.subagentConfigs = undefined;\n childInputs.maxSubagentDepth = undefined;\n }\n\n return childInputs;\n}\n\nfunction truncateErrorMessage(error: unknown): string {\n const message = error instanceof Error ? error.message : String(error);\n if (message.length <= ERROR_MESSAGE_MAX_CHARS) {\n return message;\n }\n return `${message.slice(0, ERROR_MESSAGE_MAX_CHARS)}...`;\n}\n"],"names":[],"mappings":";;;;;;;AAsBA,MAAM,iBAAiB,GAAG,EAAE;AAC5B,MAAM,oBAAoB,GAAG,CAAC;AAC9B,MAAM,uBAAuB,GAAG,GAAG;AAEnC,MAAM,aAAa,GAAyB,MAAM,CAAC,MAAM,CAAC;AACxD,IAAA,kBAAkB,EAAE,EAAc;AAClC,IAAA,MAAM,EAAE,EAAc;AACvB,CAAA,CAAC;MA2DW,gBAAgB,CAAA;AACV,IAAA,OAAO;AACP,IAAA,YAAY;AACZ,IAAA,YAAY;AACZ,IAAA,WAAW;AACX,IAAA,aAAa;AACb,IAAA,YAAY;AACZ,IAAA,QAAQ;AACR,IAAA,gBAAgB;AAChB,IAAA,4BAA4B;AAI7C,IAAA,WAAA,CAAY,OAAgC,EAAA;AAC1C,QAAA,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC,OAAO;AAC9B,QAAA,IAAI,CAAC,YAAY,GAAG,OAAO,CAAC,YAAY;AACxC,QAAA,IAAI,CAAC,YAAY,GAAG,OAAO,CAAC,YAAY;AACxC,QAAA,IAAI,CAAC,WAAW,GAAG,OAAO,CAAC,WAAW;AACtC,QAAA,IAAI,CAAC,aAAa,GAAG,OAAO,CAAC,aAAa;AAC1C,QAAA,I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AG,CAAC,CAAC,EAAE,cAAc,GAAG,CAAC,CAAC;IAChE;SAAO;AACL,QAAA,WAAW,CAAC,eAAe,GAAG,SAAS;AACvC,QAAA,WAAW,CAAC,gBAAgB,GAAG,SAAS;IAC1C;AAEA,IAAA,OAAO,WAAW;AACpB;AAEA,SAAS,oBAAoB,CAAC,KAAc,EAAA;AAC1C,IAAA,MAAM,OAAO,GAAG,KAAK,YAAY,KAAK,GAAG,KAAK,CAAC,OAAO,GAAG,MAAM,CAAC,KAAK,CAAC;AACtE,IAAA,IAAI,OAAO,CAAC,MAAM,IAAI,uBAAuB,EAAE;AAC7C,QAAA,OAAO,OAAO;IAChB;IACA,OAAO,CAAA,EAAG,OAAO,CAAC,KAAK,CAAC,CAAC,EAAE,uBAAuB,CAAC,CAAA,GAAA,CAAK;AAC1D;;;;"}
|
|
1
|
+
{"version":3,"file":"SubagentExecutor.mjs","sources":["../../../../src/tools/subagent/SubagentExecutor.ts"],"sourcesContent":["import { nanoid } from 'nanoid';\nimport { BaseCallbackHandler } from '@langchain/core/callbacks/base';\nimport { HumanMessage } from '@langchain/core/messages';\nimport type { BaseMessage } from '@langchain/core/messages';\nimport type { Callbacks } from '@langchain/core/callbacks/manager';\nimport type {\n AgentInputs,\n StandardGraphInput,\n ResolvedSubagentConfig,\n SubagentConfig,\n SubagentUpdateEvent,\n SubagentUpdatePhase,\n ToolExecuteBatchRequest,\n TokenCounter,\n} from '@/types';\nimport type { AggregatedHookResult, HookRegistry } from '@/hooks';\nimport type { AgentContext } from '@/agents/AgentContext';\nimport type { StandardGraph } from '@/graphs/Graph';\nimport { GraphEvents, Callback } from '@/common';\nimport type { HandlerRegistry } from '@/events';\nimport { executeHooks } from '@/hooks';\n\nconst DEFAULT_MAX_TURNS = 25;\nconst RECURSION_MULTIPLIER = 3;\nconst ERROR_MESSAGE_MAX_CHARS = 200;\n\nconst HOOK_FALLBACK: AggregatedHookResult = Object.freeze({\n additionalContexts: [] as string[],\n errors: [] as string[],\n});\n\nexport type SubagentExecuteParams = {\n description: string;\n subagentType: string;\n threadId?: string;\n /**\n * Parent-side `tool_call_id` of the `subagent` tool invocation that\n * triggered this execution. Surfaced on {@link SubagentUpdateEvent} so\n * hosts can correlate child updates back to the originating tool call\n * without relying on event ordering heuristics.\n */\n parentToolCallId?: string;\n /**\n * Snapshot of the parent invocation's `config.configurable` at the\n * spawn-tool call site. Inherited verbatim into the child workflow's\n * `configurable` so host-set fields (`requestBody`, `user`,\n * `userMCPAuthMap`, etc.) propagate — fixing MCP body-placeholder\n * substitution and per-user lookups for subagent tool calls.\n *\n * Inheritance details (verified empirically against LangGraph):\n * - host-set keys propagate as-is into the child's tool dispatches;\n * - `thread_id` propagates (with `childRunId` as a fallback when\n * parent did not supply one) — matches the \"subagent is part of\n * the same conversation\" mental model and aligns with the\n * `sessionId: this.parentRunId` convention this executor already\n * uses for `SubagentStart` / `SubagentStop` hooks;\n * - `parent_run_id` propagates when the host put it on parent's\n * configurable;\n * - `run_id` is *overwritten by the LangGraph runtime* at child\n * invoke time regardless of what we forward — child's tool\n * dispatches see the child graph's runtime runId in\n * `configurable.run_id`, not the parent's. Hosts that need\n * parent-scoped run identity for downstream consumers should\n * plumb it via a host-defined key (e.g. `requestBody.messageId`),\n * not `run_id`.\n *\n * A future revision will likely make this inheritance configurable\n * per spawn type — background / async subagents may want isolation\n * rather than sharing parent's host context.\n */\n parentConfigurable?: Record<string, unknown>;\n};\n\nexport type SubagentExecuteResult = {\n content: string;\n messages: BaseMessage[];\n};\n\n/**\n * Factory that constructs a child graph for subagent execution. Injected\n * rather than imported so that `SubagentExecutor` does not have a runtime\n * dependency on `StandardGraph` — this avoids a circular dependency between\n * `src/graphs/Graph.ts` and `src/tools/subagent/` that would otherwise break\n * Rollup's chunking under `preserveModules`.\n */\nexport type ChildGraphFactory = (input: StandardGraphInput) => StandardGraph;\n\nexport type SubagentExecutorOptions = {\n configs: Map<string, ResolvedSubagentConfig>;\n parentSignal?: AbortSignal;\n hookRegistry?: HookRegistry;\n parentRunId: string;\n parentAgentId?: string;\n tokenCounter?: TokenCounter;\n /** Remaining nesting budget. 0 or negative blocks execution. */\n maxDepth?: number;\n /**\n * Factory for constructing the isolated child graph. Callers pass\n * `(input) => new StandardGraph(input)` — injected to break a circular\n * module dependency.\n */\n createChildGraph: ChildGraphFactory;\n /**\n * Parent's event handler registry. When provided, child-graph events are\n * forwarded through this registry so hosts can:\n * (a) execute event-driven tools (`ON_TOOL_EXECUTE` routed to parent's handler),\n * (b) surface child activity to a UI via wrapped {@link GraphEvents.ON_SUBAGENT_UPDATE}.\n * When omitted, the child runs fully isolated (legacy behavior).\n *\n * Can be a direct `HandlerRegistry` or a zero-arg getter — use the getter\n * form when the registry is assigned to the graph AFTER the executor is\n * constructed (the current `Run.create` flow sets `handlerRegistry`\n * post-`createWorkflow`, so `createAgentNode` must capture lazily).\n */\n parentHandlerRegistry?: HandlerRegistry | (() => HandlerRegistry | undefined);\n};\n\nexport class SubagentExecutor {\n private readonly configs: Map<string, ResolvedSubagentConfig>;\n private readonly parentSignal?: AbortSignal;\n private readonly hookRegistry?: HookRegistry;\n private readonly parentRunId: string;\n private readonly parentAgentId?: string;\n private readonly tokenCounter?: TokenCounter;\n private readonly maxDepth: number;\n private readonly createChildGraph: ChildGraphFactory;\n private readonly resolveParentHandlerRegistry?: () =>\n | HandlerRegistry\n | undefined;\n\n constructor(options: SubagentExecutorOptions) {\n this.configs = options.configs;\n this.parentSignal = options.parentSignal;\n this.hookRegistry = options.hookRegistry;\n this.parentRunId = options.parentRunId;\n this.parentAgentId = options.parentAgentId;\n this.tokenCounter = options.tokenCounter;\n this.maxDepth = options.maxDepth ?? 1;\n this.createChildGraph = options.createChildGraph;\n const rawRegistry = options.parentHandlerRegistry;\n if (typeof rawRegistry === 'function') {\n this.resolveParentHandlerRegistry = rawRegistry;\n } else if (rawRegistry != null) {\n this.resolveParentHandlerRegistry = (): HandlerRegistry => rawRegistry;\n }\n }\n\n /** Snapshot of the parent's registry at the moment a subagent is dispatched. */\n private getParentHandlerRegistry(): HandlerRegistry | undefined {\n return this.resolveParentHandlerRegistry?.();\n }\n\n async execute(params: SubagentExecuteParams): Promise<SubagentExecuteResult> {\n const { description, subagentType, threadId, parentToolCallId } = params;\n const config = this.configs.get(subagentType);\n\n if (!config) {\n const available = [...this.configs.keys()].join(', ');\n return {\n content: `Error: Unknown subagent type \"${subagentType}\". Available types: ${available}`,\n messages: [],\n };\n }\n\n if (this.maxDepth <= 0) {\n return {\n content: 'Error: Maximum subagent nesting depth exceeded.',\n messages: [],\n };\n }\n\n const childAgentId =\n config.agentInputs.agentId ||\n `${this.parentAgentId ?? 'agent'}_sub_${nanoid(8)}`;\n\n if (\n this.hookRegistry?.hasHookFor('SubagentStart', this.parentRunId) === true\n ) {\n const hookResult = await executeHooks({\n registry: this.hookRegistry,\n input: {\n hook_event_name: 'SubagentStart',\n runId: this.parentRunId,\n threadId,\n parentAgentId: this.parentAgentId,\n agentId: childAgentId,\n agentType: subagentType,\n inputs: [new HumanMessage(description)],\n },\n sessionId: this.parentRunId,\n matchQuery: subagentType,\n }).catch((): AggregatedHookResult => HOOK_FALLBACK);\n\n /**\n * `ask` is treated identically to `deny` in the subagent context:\n * subagents are non-interactive, so there is no prompt path for `ask`.\n * Both decisions block execution and return a \"Blocked\" tool result.\n */\n if (hookResult.decision === 'deny' || hookResult.decision === 'ask') {\n return {\n content: `Blocked: ${hookResult.reason ?? 'Blocked by hook'}`,\n messages: [],\n };\n }\n }\n\n const parentRegistry = this.getParentHandlerRegistry();\n const forwardingEnabled = parentRegistry != null;\n /**\n * Keep `toolDefinitions` only when the host has actually wired an\n * `ON_TOOL_EXECUTE` handler. `Run` always constructs a `HandlerRegistry`,\n * so treating any registry as \"forwarding enabled\" would leak\n * `toolDefinitions` into children whose hosts cannot execute them — the\n * child's `ToolNode` batch promise would hang forever with no handler to\n * resolve/reject. Gating on the tool-execute handler preserves the\n * recoverable \"no tools\" path for registry-but-no-handler configs.\n */\n const hasToolExecuteHandler =\n parentRegistry?.getHandler(GraphEvents.ON_TOOL_EXECUTE) != null;\n const childInputs = buildChildInputs(\n config,\n childAgentId,\n this.maxDepth,\n /* keepToolDefinitions */ hasToolExecuteHandler\n );\n const childRunId = `${this.parentRunId}_sub_${nanoid(8)}`;\n const maxTurns = config.maxTurns ?? DEFAULT_MAX_TURNS;\n\n const childGraph = this.createChildGraph({\n runId: childRunId,\n signal: this.parentSignal,\n agents: [childInputs],\n tokenCounter: this.tokenCounter,\n });\n\n const forwarder = forwardingEnabled\n ? this.createForwarderCallback({\n parentRegistry: parentRegistry!,\n subagentType,\n subagentAgentId: childAgentId,\n childRunId,\n parentToolCallId,\n })\n : undefined;\n\n if (forwarder) {\n await this.emitSubagentUpdate(parentRegistry!, {\n childRunId,\n subagentType,\n subagentAgentId: childAgentId,\n parentToolCallId,\n phase: 'start',\n label: `Subagent \"${subagentType}\" started`,\n });\n }\n\n let result: { messages: BaseMessage[] };\n try {\n const workflow = childGraph.createWorkflow();\n /**\n * When `parentHandlerRegistry` is provided (forwarding mode), attach a\n * lightweight callback that intercepts the child's `on_custom_event`\n * dispatches and routes them to the parent's registry — either as\n * operational events (ON_TOOL_EXECUTE) or wrapped ON_SUBAGENT_UPDATE\n * envelopes. Native LangChain streaming events (on_chat_model_stream,\n * etc.) still do NOT propagate to the parent's outer streamEvents\n * iterator — the `callbacks` array REPLACES the inherited chain, so\n * parent handlers won't receive child stream chunks and raise \"No\n * agent context found\" lookups on the parent's agentContexts map.\n *\n * When no registry is provided (legacy isolation), `callbacks: []`\n * fully detaches the child.\n *\n * `runName` gives the child a distinct LangSmith trace root (avoids\n * nested trace pollution).\n */\n const callbacks: Callbacks = forwarder ? [forwarder] : [];\n /**\n * Inherit the parent's `configurable` verbatim — host-set fields\n * (`requestBody`, `user`, `userMCPAuthMap`, etc.) AND the run-\n * identity fields (`run_id`, `parent_run_id`, `thread_id`) all\n * propagate.\n *\n * Run-identity propagation is intentional and matches the\n * convention this executor itself already uses for `SubagentStart`\n * / `SubagentStop` hooks (`sessionId: this.parentRunId`): the\n * subagent runs under the parent's session scope, not its own.\n * Forwarding `run_id` / `parent_run_id` / `thread_id` makes\n * `ToolNode`'s hook lookups (`hasHookFor(eventName, runId)`),\n * `ToolOutputReferenceRegistry` keying, and trace lineage all\n * resolve to the parent's session for tools dispatched from the\n * subagent — so `PreToolUse` / `PostToolUse` hooks the host\n * registered against the parent's run fire for subagent tool\n * calls too. \"Same run\" matches the user-perceptual mental model.\n *\n * `thread_id` falls back to `childRunId` only when the parent\n * didn't supply one (legacy behavior preserved for hosts that\n * never set thread_id).\n *\n * NOTE: a future revision will likely make this configurable per\n * spawn type — e.g. a background / async subagent that runs after\n * the parent's run completes wants isolation, not inheritance.\n * For now the inheritance path matches LibreChat's primary use\n * case (synchronous subagents within a single user turn).\n */\n const inheritedConfigurable: Record<string, unknown> =\n params.parentConfigurable ?? {};\n /**\n * Surface the parent's `subagent` tool_call.id to the child's run\n * metadata so host-side artifact handlers (e.g. ranger's\n * `resolveUiToolCallId`) can re-key child-emitted attachments to\n * the parent's bubble. Without this, files produced by tools\n * inside a subagent (execute_code .docx, image_gen, etc.) get\n * attached to the child's inner tool_call_id — which the parent\n * message has no record of — and orphan in the chat UI.\n */\n const inheritedMetadata: Record<string, unknown> = {\n ...((inheritedConfigurable as { metadata?: Record<string, unknown> })\n .metadata ?? {}),\n parentToolCallId,\n subagentAgentId: childAgentId,\n subagentType,\n };\n result = await workflow.invoke(\n { messages: [new HumanMessage(description)] },\n {\n recursionLimit: maxTurns * RECURSION_MULTIPLIER,\n signal: this.parentSignal,\n callbacks,\n runName: `subagent:${subagentType}`,\n configurable: {\n thread_id: childRunId,\n ...inheritedConfigurable,\n parentToolCallId,\n },\n metadata: inheritedMetadata,\n }\n );\n } catch (error) {\n const errorMessage = truncateErrorMessage(error);\n if (forwarder) {\n await this.emitSubagentUpdate(parentRegistry!, {\n childRunId,\n subagentType,\n subagentAgentId: childAgentId,\n parentToolCallId,\n phase: 'error',\n label: `Subagent \"${subagentType}\" errored: ${errorMessage}`,\n data: { message: errorMessage },\n });\n }\n childGraph.clearHeavyState();\n return {\n content: `Subagent error: ${errorMessage}`,\n messages: [],\n };\n }\n\n const filteredContent = filterSubagentResult(result.messages);\n\n if (\n this.hookRegistry?.hasHookFor('SubagentStop', this.parentRunId) === true\n ) {\n /**\n * Awaited (not fire-and-forget) for deterministic test synchronization\n * and consistency with PostCompact. The parent is already waiting on the\n * tool result, so the small extra latency is acceptable. Errors are\n * swallowed — SubagentStop is observational.\n */\n await executeHooks({\n registry: this.hookRegistry,\n input: {\n hook_event_name: 'SubagentStop',\n runId: this.parentRunId,\n threadId,\n agentId: childAgentId,\n agentType: subagentType,\n messages: result.messages,\n },\n sessionId: this.parentRunId,\n matchQuery: subagentType,\n }).catch(() => {\n /* SubagentStop is observational — swallow errors */\n });\n }\n\n if (forwarder) {\n await this.emitSubagentUpdate(parentRegistry!, {\n childRunId,\n subagentType,\n subagentAgentId: childAgentId,\n parentToolCallId,\n phase: 'stop',\n label: `Subagent \"${subagentType}\" finished`,\n });\n }\n\n childGraph.clearHeavyState();\n\n return { content: filteredContent, messages: result.messages };\n }\n\n /**\n * Emits a single {@link GraphEvents.ON_SUBAGENT_UPDATE} envelope through the\n * parent's handler registry. Silent no-op when no parent registry is set.\n * Errors are swallowed — update events are observational.\n */\n private async emitSubagentUpdate(\n parentRegistry: HandlerRegistry,\n args: {\n childRunId: string;\n subagentType: string;\n subagentAgentId: string;\n parentToolCallId?: string;\n phase: SubagentUpdatePhase;\n data?: unknown;\n label?: string;\n }\n ): Promise<void> {\n const handler = parentRegistry.getHandler(GraphEvents.ON_SUBAGENT_UPDATE);\n if (!handler) {\n return;\n }\n const event: SubagentUpdateEvent = {\n runId: this.parentRunId,\n subagentRunId: args.childRunId,\n subagentType: args.subagentType,\n subagentAgentId: args.subagentAgentId,\n parentAgentId: this.parentAgentId,\n parentToolCallId: args.parentToolCallId,\n phase: args.phase,\n data: args.data,\n label: args.label,\n timestamp: new Date().toISOString(),\n };\n try {\n await handler.handle(GraphEvents.ON_SUBAGENT_UPDATE, event);\n } catch {\n /* observational — swallow */\n }\n }\n\n /**\n * Builds a BaseCallbackHandler that intercepts the child graph's custom\n * events. Routing rules:\n * - `ON_TOOL_EXECUTE` → forwarded as-is to the parent's ON_TOOL_EXECUTE\n * handler (so event-driven tools work identically for child and parent).\n * - `ON_RUN_STEP` / `ON_RUN_STEP_DELTA` / `ON_RUN_STEP_COMPLETED` /\n * `ON_MESSAGE_DELTA` / `ON_REASONING_DELTA` → wrapped in a\n * {@link GraphEvents.ON_SUBAGENT_UPDATE} envelope with a human-readable\n * label, delivered to the parent's subagent-update handler.\n * - Everything else → ignored (keeps parent's UI scoped to the events it\n * cares about; host apps can extend by registering more phases).\n */\n private createForwarderCallback(args: {\n parentRegistry: HandlerRegistry;\n subagentType: string;\n subagentAgentId: string;\n childRunId: string;\n parentToolCallId?: string;\n }): BaseCallbackHandler {\n const {\n parentRegistry,\n subagentType,\n subagentAgentId,\n childRunId,\n parentToolCallId,\n } = args;\n const parentRunId = this.parentRunId;\n const parentAgentId = this.parentAgentId;\n\n const wrap = async (\n eventName: string,\n phase: SubagentUpdatePhase,\n data: unknown\n ): Promise<void> => {\n const handler = parentRegistry.getHandler(GraphEvents.ON_SUBAGENT_UPDATE);\n if (!handler) {\n return;\n }\n const event: SubagentUpdateEvent = {\n runId: parentRunId,\n subagentRunId: childRunId,\n subagentType,\n subagentAgentId,\n parentAgentId,\n parentToolCallId,\n phase,\n data,\n label: summarizeEvent(eventName, data),\n timestamp: new Date().toISOString(),\n };\n try {\n await handler.handle(GraphEvents.ON_SUBAGENT_UPDATE, event);\n } catch {\n /* observational — swallow */\n }\n };\n\n const handler = BaseCallbackHandler.fromMethods({\n [Callback.CUSTOM_EVENT]: async (\n eventName: string,\n data: unknown\n ): Promise<void> => {\n if (eventName === GraphEvents.ON_TOOL_EXECUTE) {\n const toolHandler = parentRegistry.getHandler(\n GraphEvents.ON_TOOL_EXECUTE\n );\n if (toolHandler) {\n await toolHandler.handle(\n GraphEvents.ON_TOOL_EXECUTE,\n data as ToolExecuteBatchRequest\n );\n }\n /**\n * We also surface a short notice in the subagent-update stream so\n * the UI can show \"calling <tool>\" for each tool the child spawns.\n */\n await wrap(eventName, 'run_step', data);\n return;\n }\n\n if (eventName === GraphEvents.ON_RUN_STEP) {\n await wrap(eventName, 'run_step', data);\n return;\n }\n if (eventName === GraphEvents.ON_RUN_STEP_DELTA) {\n await wrap(eventName, 'run_step_delta', data);\n return;\n }\n if (eventName === GraphEvents.ON_RUN_STEP_COMPLETED) {\n await wrap(eventName, 'run_step_completed', data);\n return;\n }\n if (eventName === GraphEvents.ON_MESSAGE_DELTA) {\n await wrap(eventName, 'message_delta', data);\n return;\n }\n if (eventName === GraphEvents.ON_REASONING_DELTA) {\n await wrap(eventName, 'reasoning_delta', data);\n return;\n }\n },\n });\n /**\n * `awaitHandlers = true` is required so the child's `ToolNode` actually\n * blocks on the parent's `ON_TOOL_EXECUTE` handler until it resolves\n * the batch request. The same flag applies to observational events\n * (message_delta, run_step, …), which means a slow\n * `ON_SUBAGENT_UPDATE` handler on the host serializes the child\n * stream. If host-side latency becomes a concern, a future\n * refinement could split operational and observational events into\n * separate callback handlers with distinct await semantics.\n */\n handler.awaitHandlers = true;\n return handler;\n }\n}\n\n/**\n * Produces a short single-line label for an arbitrary forwarded child event.\n * Used to populate {@link SubagentUpdateEvent.label} so the host UI can show\n * a compact status ticker without parsing the raw payload.\n */\nexport function summarizeEvent(eventName: string, data: unknown): string {\n if (eventName === GraphEvents.ON_TOOL_EXECUTE) {\n const req = data as { toolCalls?: Array<{ name?: string }> };\n const names = (req.toolCalls ?? [])\n .map((c) => c.name)\n .filter((n): n is string => typeof n === 'string');\n return names.length > 0 ? `Calling ${names.join(', ')}` : 'Calling tool';\n }\n if (eventName === GraphEvents.ON_RUN_STEP) {\n const step = data as {\n type?: string;\n stepDetails?: { type?: string; tool_calls?: Array<{ name?: string }> };\n };\n const detailType = step.stepDetails?.type ?? step.type ?? 'step';\n if (detailType === 'tool_calls') {\n const names = (step.stepDetails?.tool_calls ?? [])\n .map((c) => c.name)\n .filter((n): n is string => typeof n === 'string');\n return names.length > 0\n ? `Using tool: ${names.join(', ')}`\n : 'Planning tool call';\n }\n if (detailType === 'message_creation') {\n return 'Thinking…';\n }\n return `Step: ${detailType}`;\n }\n if (eventName === GraphEvents.ON_RUN_STEP_COMPLETED) {\n const step = data as {\n result?: {\n type?: string;\n tool_call?: { name?: string; output?: string };\n };\n };\n const tool = step.result?.tool_call;\n if (tool?.name != null && tool.name !== '') {\n return `Tool ${tool.name} complete`;\n }\n return 'Step complete';\n }\n if (eventName === GraphEvents.ON_MESSAGE_DELTA) {\n return 'Streaming…';\n }\n return eventName;\n}\n\n/**\n * Walk messages from last to first, returning the text content of the most\n * recent AIMessage that has any. Non-text blocks (tool_use, thinking,\n * redacted_thinking, tool_result) are stripped. If the last AIMessage is\n * pure tool_use (e.g. the subagent hit `maxTurns` mid-tool-call), the walk\n * continues to earlier AIMessages so partial progress is salvaged — this\n * matches Claude Code's behavior in `agentToolUtils.finalizeAgentTool`.\n * Returns \"Task completed\" only when no AIMessage in the history contains\n * any text.\n */\nexport function filterSubagentResult(messages: BaseMessage[]): string {\n for (let i = messages.length - 1; i >= 0; i--) {\n if (messages[i]._getType() !== 'ai') {\n continue;\n }\n\n const content = messages[i].content;\n\n if (typeof content === 'string') {\n if (content) return content;\n continue;\n }\n\n if (!Array.isArray(content)) {\n continue;\n }\n\n const textParts: string[] = [];\n for (const block of content) {\n if (typeof block === 'string') {\n textParts.push(block);\n } else if ('type' in block && block.type === 'text' && 'text' in block) {\n textParts.push(block.text as string);\n }\n }\n\n if (textParts.length > 0) {\n return textParts.join('\\n');\n }\n }\n\n return 'Task completed';\n}\n\n/**\n * Resolve self-spawn configs by filling in agentInputs from the parent context.\n * Returns configs with agentInputs guaranteed present. Throws on duplicate\n * `type` values to prevent silent config shadowing.\n */\nexport function resolveSubagentConfigs(\n configs: SubagentConfig[],\n parentContext: AgentContext\n): ResolvedSubagentConfig[] {\n const resolved = configs\n .map((config) => {\n if (config.agentInputs != null) {\n return config as ResolvedSubagentConfig;\n }\n if (config.self !== true || parentContext._sourceInputs == null) {\n return null;\n }\n return {\n ...config,\n agentInputs: { ...parentContext._sourceInputs },\n } as ResolvedSubagentConfig;\n })\n .filter((c): c is ResolvedSubagentConfig => c != null);\n\n const seenTypes = new Set<string>();\n for (const config of resolved) {\n if (seenTypes.has(config.type)) {\n throw new Error(\n `Duplicate subagent type \"${config.type}\". Each SubagentConfig must have a unique \"type\" field.`\n );\n }\n seenTypes.add(config.type);\n }\n\n return resolved;\n}\n\n/**\n * Build child AgentInputs from a resolved config, stripping nesting and\n * (optionally) event-driven fields. When `allowNested: true`, the child's\n * `maxSubagentDepth` is decremented so that depth is consumed as the call\n * chain deepens across graph boundaries — the parent's executor-level check\n * alone cannot see into the child graph's separate executor.\n *\n * When `keepToolDefinitions` is `true`, the child retains the parent's\n * `toolDefinitions` so event-driven tools remain usable. This is only safe\n * when the caller has wired a forwarder for `ON_TOOL_EXECUTE` to a\n * registered handler — otherwise the child will hang on tool dispatch.\n *\n * @remarks Advanced utility: exported primarily for testing and by\n * {@link SubagentExecutor}. Host applications configuring subagents should\n * not need to call this directly — it is invoked internally when a subagent\n * tool is dispatched. The depth-countdown contract (parent's `maxDepth` in,\n * child's decremented `maxSubagentDepth` on the returned inputs) is the\n * mechanism that bounds nesting across graph boundaries; callers must\n * respect it.\n */\nexport function buildChildInputs(\n config: ResolvedSubagentConfig,\n childAgentId: string,\n parentMaxDepth: number,\n keepToolDefinitions: boolean = false\n): AgentInputs {\n const { agentInputs } = config;\n const childInputs: AgentInputs = {\n ...agentInputs,\n agentId: childAgentId,\n toolDefinitions: keepToolDefinitions\n ? agentInputs.toolDefinitions\n : undefined,\n /**\n * Subagents run in an isolated context by contract. Parent-run-scoped\n * fields that would otherwise survive the shallow-spread clone — the\n * cross-run conversation summary and the prior-turn tool-discovery\n * set — are cleared here so the child starts fresh. Host applications\n * that want a subagent to see parent context must thread it in\n * explicitly (e.g. via the `description` argument to the subagent\n * tool), not via inherited state.\n */\n initialSummary: undefined,\n discoveredTools: undefined,\n };\n\n if (config.allowNested === true) {\n childInputs.maxSubagentDepth = Math.max(0, parentMaxDepth - 1);\n } else {\n childInputs.subagentConfigs = undefined;\n childInputs.maxSubagentDepth = undefined;\n }\n\n return childInputs;\n}\n\nfunction truncateErrorMessage(error: unknown): string {\n const message = error instanceof Error ? error.message : String(error);\n if (message.length <= ERROR_MESSAGE_MAX_CHARS) {\n return message;\n }\n return `${message.slice(0, ERROR_MESSAGE_MAX_CHARS)}...`;\n}\n"],"names":[],"mappings":";;;;;;;AAsBA,MAAM,iBAAiB,GAAG,EAAE;AAC5B,MAAM,oBAAoB,GAAG,CAAC;AAC9B,MAAM,uBAAuB,GAAG,GAAG;AAEnC,MAAM,aAAa,GAAyB,MAAM,CAAC,MAAM,CAAC;AACxD,IAAA,kBAAkB,EAAE,EAAc;AAClC,IAAA,MAAM,EAAE,EAAc;AACvB,CAAA,CAAC;MAwFW,gBAAgB,CAAA;AACV,IAAA,OAAO;AACP,IAAA,YAAY;AACZ,IAAA,YAAY;AACZ,IAAA,WAAW;AACX,IAAA,aAAa;AACb,IAAA,YAAY;AACZ,IAAA,QAAQ;AACR,IAAA,gBAAgB;AAChB,IAAA,4BAA4B;AAI7C,IAAA,WAAA,CAAY,OAAgC,EAAA;AAC1C,QAAA,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC,OAAO;AAC9B,QAAA,IAAI,CAAC,YAAY,GAAG,OAAO,CAAC,YAAY;AACxC,QAAA,IAAI,CAAC,YAAY,GAAG,OAAO,CAAC,YAAY;AACxC,QAAA,IAAI,CAAC,WAAW,GAAG,OAAO,CAAC,WAAW;AACtC,QAAA,IAAI,CAAC,aAAa,GAAG,OAAO,CAAC,aAAa;AAC1C,QAAA,IAAI,CAAC,YAAY,GAAG,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9B,IAAA,MAAM,WAAW,GAAgB;AAC/B,QAAA,GAAG,WAAW;AACd,QAAA,OAAO,EAAE,YAAY;AACrB,QAAA,eAAe,EAAE;cACb,WAAW,CAAC;AACd,cAAE,SAAS;AACb;;;;;;;;AAQG;AACH,QAAA,cAAc,EAAE,SAAS;AACzB,QAAA,eAAe,EAAE,SAAS;KAC3B;AAED,IAAA,IAAI,MAAM,CAAC,WAAW,KAAK,IAAI,EAAE;AAC/B,QAAA,WAAW,CAAC,gBAAgB,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,cAAc,GAAG,CAAC,CAAC;IAChE;SAAO;AACL,QAAA,WAAW,CAAC,eAAe,GAAG,SAAS;AACvC,QAAA,WAAW,CAAC,gBAAgB,GAAG,SAAS;IAC1C;AAEA,IAAA,OAAO,WAAW;AACpB;AAEA,SAAS,oBAAoB,CAAC,KAAc,EAAA;AAC1C,IAAA,MAAM,OAAO,GAAG,KAAK,YAAY,KAAK,GAAG,KAAK,CAAC,OAAO,GAAG,MAAM,CAAC,KAAK,CAAC;AACtE,IAAA,IAAI,OAAO,CAAC,MAAM,IAAI,uBAAuB,EAAE;AAC7C,QAAA,OAAO,OAAO;IAChB;IACA,OAAO,CAAA,EAAG,OAAO,CAAC,KAAK,CAAC,CAAC,EAAE,uBAAuB,CAAC,CAAA,GAAA,CAAK;AAC1D;;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"graph.mjs","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;;;;"}
|
|
1
|
+
{"version":3,"file":"graph.mjs","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';\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 instructions?: string;\n streamBuffer?: number;\n maxContextTokens?: number;\n clientOptions?: ClientOptions;\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 * Workspace-shared system-message tiers. Each entry becomes a separate\n * text block in the SystemMessage with its own cachePoint / cache_control\n * marker, allowing the platform-tier bytes (e.g. shared branding, tool\n * routing rules, code-executor instructions) to be hashed independently\n * from the per-agent `instructions` block. Hosts that don't use tiered\n * caching can leave this undefined; behavior falls back to the legacy\n * single SystemMessage.\n *\n * Anthropic / Bedrock prompt-cache lookups are forward-prefix-hash, so\n * blocks are emitted in array order BEFORE `instructions`. Up to 4 blocks\n * are supported (the LLM cap on cache breakpoints).\n */\n system_cache_blocks?: Array<{ text: string; ttl?: '5m' | '1h' }>;\n /**\n * TTL hint for the per-agent `instructions` block's cache marker.\n * Defaults to '5m' (matching addCacheControl message-level behavior).\n * Only consulted when `system_cache_blocks` is set; otherwise the\n * legacy SystemMessage path is unchanged.\n */\n instructions_cache_ttl?: '5m' | '1h';\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":"AAodA;;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;;;;"}
|
|
@@ -58,18 +58,9 @@ export declare class AgentContext {
|
|
|
58
58
|
toolDefinitions?: t.LCTool[];
|
|
59
59
|
/** Set of tool names discovered via tool search (to be loaded) */
|
|
60
60
|
discoveredToolNames: Set<string>;
|
|
61
|
-
/**
|
|
62
|
-
* Cacheable system content blocks emitted before `instructions`. Each
|
|
63
|
-
* gets its own cache marker (cachePoint on Bedrock, cache_control on
|
|
64
|
-
* Anthropic). Earlier entries = wider cache key (best for cross-tenant
|
|
65
|
-
* sharing). See `src/types/agent-cache.ts`.
|
|
66
|
-
*/
|
|
67
|
-
systemCacheBlocks?: t.SystemCacheBlock[];
|
|
68
|
-
/** Stable/cacheable instructions for this agent (gets trailing marker). */
|
|
61
|
+
/** Instructions for this agent */
|
|
69
62
|
instructions?: string;
|
|
70
|
-
/**
|
|
71
|
-
instructionsCacheTtl?: t.AgentCacheTTL;
|
|
72
|
-
/** Dynamic system tail (per-user / per-message — never cached). */
|
|
63
|
+
/** Additional instructions for this agent */
|
|
73
64
|
additionalInstructions?: string;
|
|
74
65
|
/**
|
|
75
66
|
* Dynamic context that changes per-request (e.g., current time, user info).
|
|
@@ -129,13 +120,25 @@ export declare class AgentContext {
|
|
|
129
120
|
summarizationConfig?: t.SummarizationConfig;
|
|
130
121
|
/** Lightweight file manifest for file-aware compaction (IDs and names only, no content) */
|
|
131
122
|
fileManifest?: t.FileManifestEntry[];
|
|
123
|
+
/**
|
|
124
|
+
* Workspace-shared system-message tiers. When set, each entry becomes a
|
|
125
|
+
* separate text block in the SystemMessage with its own cachePoint /
|
|
126
|
+
* cache_control marker, BEFORE the per-agent `instructions` block.
|
|
127
|
+
* See {@link t.AgentInputs.system_cache_blocks} for full semantics.
|
|
128
|
+
*/
|
|
129
|
+
systemCacheBlocks?: Array<{
|
|
130
|
+
text: string;
|
|
131
|
+
ttl?: '5m' | '1h';
|
|
132
|
+
}>;
|
|
133
|
+
/** TTL hint for the per-agent instructions cache marker. Defaults to '5m'. */
|
|
134
|
+
instructionsCacheTtl?: '5m' | '1h';
|
|
132
135
|
/** Original AgentInputs used to create this context — used for self-spawn subagent resolution. */
|
|
133
136
|
_sourceInputs?: t.AgentInputs;
|
|
134
137
|
/** Subagent configurations for hierarchical delegation. */
|
|
135
138
|
subagentConfigs?: t.SubagentConfig[];
|
|
136
139
|
/** Maximum subagent nesting depth. */
|
|
137
140
|
maxSubagentDepth?: number;
|
|
138
|
-
constructor({ agentId, name, description, provider, clientOptions, maxContextTokens, streamBuffer, tokenCounter, tools, toolMap, toolRegistry, toolDefinitions,
|
|
141
|
+
constructor({ agentId, name, description, provider, clientOptions, maxContextTokens, streamBuffer, tokenCounter, tools, toolMap, toolRegistry, toolDefinitions, instructions, additionalInstructions, dynamicContext, reasoningKey, toolEnd, instructionTokens, useLegacyContent, structuredOutput, discoveredTools, summarizeCallback, persistedSummary, summarizationConfig, fileManifest, systemCacheBlocks, instructionsCacheTtl, }: {
|
|
139
142
|
agentId: string;
|
|
140
143
|
name?: string;
|
|
141
144
|
description?: string;
|
|
@@ -148,9 +151,7 @@ export declare class AgentContext {
|
|
|
148
151
|
toolMap?: t.ToolMap;
|
|
149
152
|
toolRegistry?: t.LCToolRegistry;
|
|
150
153
|
toolDefinitions?: t.LCTool[];
|
|
151
|
-
systemCacheBlocks?: t.SystemCacheBlock[];
|
|
152
154
|
instructions?: string;
|
|
153
|
-
instructionsCacheTtl?: t.AgentCacheTTL;
|
|
154
155
|
additionalInstructions?: string;
|
|
155
156
|
dynamicContext?: string;
|
|
156
157
|
reasoningKey?: 'reasoning_content' | 'reasoning';
|
|
@@ -163,6 +164,11 @@ export declare class AgentContext {
|
|
|
163
164
|
persistedSummary?: string;
|
|
164
165
|
summarizationConfig?: t.SummarizationConfig;
|
|
165
166
|
fileManifest?: t.FileManifestEntry[];
|
|
167
|
+
systemCacheBlocks?: Array<{
|
|
168
|
+
text: string;
|
|
169
|
+
ttl?: '5m' | '1h';
|
|
170
|
+
}>;
|
|
171
|
+
instructionsCacheTtl?: '5m' | '1h';
|
|
166
172
|
});
|
|
167
173
|
/**
|
|
168
174
|
* Checks if structured output mode is enabled for this agent.
|
|
@@ -213,75 +219,18 @@ export declare class AgentContext {
|
|
|
213
219
|
*/
|
|
214
220
|
initializeSystemRunnable(): void;
|
|
215
221
|
/**
|
|
216
|
-
* Builds the
|
|
217
|
-
* Includes agent identity preamble
|
|
218
|
-
* programmatic-only tool documentation. This is the part of the system
|
|
219
|
-
* message that stays byte-stable across turns and across users for the
|
|
220
|
-
* same agent — the prompt cache prefix.
|
|
221
|
-
*
|
|
222
|
-
* Per-user/per-message dynamic context belongs in
|
|
223
|
-
* `buildDynamicInstructionsString()` so it does not invalidate the cache
|
|
224
|
-
* marker. (See `feedback_cache_stability_invariant` for the rule.)
|
|
222
|
+
* Builds the raw instructions string (without creating SystemMessage).
|
|
223
|
+
* Includes agent identity preamble and handoff context when available.
|
|
225
224
|
*/
|
|
226
|
-
private
|
|
227
|
-
/**
|
|
228
|
-
* Builds the dynamic system-tail string (without creating SystemMessage).
|
|
229
|
-
* Keep this out of prompt-cache-marked content so volatile per-call
|
|
230
|
-
* context does not invalidate the stable prefix.
|
|
231
|
-
*
|
|
232
|
-
* `additional_instructions` is treated as dynamic (per-user/per-message
|
|
233
|
-
* memory, runtime context, etc.) and intentionally excluded from the
|
|
234
|
-
* cacheable prefix.
|
|
235
|
-
*/
|
|
236
|
-
private buildDynamicInstructionsString;
|
|
225
|
+
private buildInstructionsString;
|
|
237
226
|
/**
|
|
238
227
|
* Builds the agent identity preamble including handoff context if present.
|
|
239
228
|
* This helps the agent understand its role in the multi-agent workflow.
|
|
240
229
|
*/
|
|
241
230
|
private buildIdentityPreamble;
|
|
242
231
|
/**
|
|
243
|
-
*
|
|
244
|
-
*
|
|
245
|
-
* marker on the stable instructions prefix.
|
|
246
|
-
*/
|
|
247
|
-
private hasAnthropicPromptCache;
|
|
248
|
-
/**
|
|
249
|
-
* True when Bedrock prompt caching is enabled for this agent AND the
|
|
250
|
-
* configured model supports `cachePoint` blocks. Only Claude (and Nova)
|
|
251
|
-
* models on Bedrock honour cachePoint — Llama / Titan reject it.
|
|
252
|
-
*
|
|
253
|
-
* Used by `buildSystemRunnable` to inline a `cachePoint` block right
|
|
254
|
-
* after the stable system text so the system prefix is cached at the
|
|
255
|
-
* AWS account level (cross-user, cross-conversation).
|
|
256
|
-
*/
|
|
257
|
-
private hasBedrockPromptCache;
|
|
258
|
-
/**
|
|
259
|
-
* Build system runnable from cacheable blocks + the trailing
|
|
260
|
-
* `instructions` block + optional dynamic tail.
|
|
261
|
-
*
|
|
262
|
-
* ┌──────────────────────────────────────────┐
|
|
263
|
-
* │ system_cache_blocks[0].text │ ← consumer-defined block 0
|
|
264
|
-
* ├──── cache marker (TTL = blocks[0].ttl) ──┤
|
|
265
|
-
* │ system_cache_blocks[1].text │ ← consumer-defined block 1
|
|
266
|
-
* ├──── cache marker (TTL = blocks[1].ttl) ──┤
|
|
267
|
-
* │ instructions │ ← per-agent stable
|
|
268
|
-
* ├──── cache marker (TTL = instructionsCacheTtl) ┤
|
|
269
|
-
* │ additional_instructions │ ← dynamic (uncached)
|
|
270
|
-
* └──────────────────────────────────────────┘
|
|
271
|
-
*
|
|
272
|
-
* If `system_cache_blocks` is empty, behavior reduces to the 2-tier
|
|
273
|
-
* (instructions + dynamic) path used by simpler consumers.
|
|
274
|
-
*
|
|
275
|
-
* Provider-specific cache marker:
|
|
276
|
-
* - Anthropic: `cache_control: { type: 'ephemeral', ttl?: '1h'|'5m' }` on
|
|
277
|
-
* each cacheable text block. Up to 4 cache breakpoints per workspace.
|
|
278
|
-
* - Bedrock (Claude/Nova): a `{ cachePoint: { type: 'default', ttl?: '1h'|'5m' } }`
|
|
279
|
-
* block inserted after each cacheable section. Up to 4 cachePoints per
|
|
280
|
-
* request, of which the tools array can consume up to 2.
|
|
281
|
-
*
|
|
282
|
-
* Cache key composition: every byte from message start to a given cache
|
|
283
|
-
* marker forms that marker's cache key. Earlier blocks = wider cache key
|
|
284
|
-
* = more cross-tenant share. Place the most stable content first.
|
|
232
|
+
* Build system runnable from pre-built instructions string.
|
|
233
|
+
* Only called when content has actually changed.
|
|
285
234
|
*/
|
|
286
235
|
private buildSystemRunnable;
|
|
287
236
|
/**
|
|
@@ -292,25 +241,6 @@ export declare class AgentContext {
|
|
|
292
241
|
* Update the token count map with instruction tokens
|
|
293
242
|
*/
|
|
294
243
|
updateTokenMapWithInstructions(baseTokenMap: Record<string, number>): void;
|
|
295
|
-
/** Active tool definitions for token accounting (excludes deferred-and-undiscovered entries
|
|
296
|
-
* and definitions whose `allowed_callers` exclude `'direct'`). Mirrors the gate
|
|
297
|
-
* `getEventDrivenToolsForBinding` applies so accounting and binding stay aligned. */
|
|
298
|
-
private getActiveToolDefinitions;
|
|
299
|
-
/**
|
|
300
|
-
* Single source of truth for "which entries of `this.tools` should be
|
|
301
|
-
* treated as actually bound". Callers:
|
|
302
|
-
* - `getToolsForBinding` (non-event-driven branch)
|
|
303
|
-
* - `getEventDrivenToolsForBinding` (appends instance tools alongside
|
|
304
|
-
* schema-only definitions)
|
|
305
|
-
* - `calculateInstructionTokens` (counts schema bytes for accounting)
|
|
306
|
-
*
|
|
307
|
-
* In event-driven mode (`toolDefinitions` present) instance tools are
|
|
308
|
-
* appended unfiltered; outside event-driven mode they pass through
|
|
309
|
-
* `filterToolsForBinding`. Centralizing the decision here prevents the
|
|
310
|
-
* accounting/binding paths from drifting apart, which was the root
|
|
311
|
-
* cause of the original miscount (Fixes upstream #121).
|
|
312
|
-
*/
|
|
313
|
-
private getEffectiveInstanceTools;
|
|
314
244
|
/**
|
|
315
245
|
* Calculate tool tokens and add to instruction tokens
|
|
316
246
|
* Note: System message tokens are calculated during systemRunnable creation
|
package/dist/types/index.d.ts
CHANGED
|
@@ -35,7 +35,6 @@ export * from './nodes';
|
|
|
35
35
|
export * from './common';
|
|
36
36
|
export * from './utils';
|
|
37
37
|
export type * from './types';
|
|
38
|
-
export * from './langchain';
|
|
39
38
|
export { CustomOpenAIClient } from './llm/openai';
|
|
40
39
|
export { ChatOpenRouter } from './llm/openrouter';
|
|
41
40
|
export type { OpenRouterReasoning, OpenRouterReasoningEffort, ChatOpenRouterCallOptions, } from './llm/openrouter';
|
|
@@ -41,65 +41,18 @@ import type { ChatBedrockConverseInput } from '@langchain/aws';
|
|
|
41
41
|
* @see https://docs.aws.amazon.com/bedrock/latest/userguide/service-tiers-inference.html
|
|
42
42
|
*/
|
|
43
43
|
export type ServiceTierType = 'priority' | 'default' | 'flex' | 'reserved';
|
|
44
|
-
/**
|
|
45
|
-
* Tool cachePoint allocation strategy.
|
|
46
|
-
*
|
|
47
|
-
* - 'single': one cachePoint at the END of the tools array (whole array
|
|
48
|
-
* cached as one unit). Lightest budget use (1 cachePoint).
|
|
49
|
-
* - 'split': split tools into groups via `toolGroupSelector`. Each
|
|
50
|
-
* non-empty group gets its own cachePoint. Use when groups
|
|
51
|
-
* have different volatility (e.g. stable core tools vs
|
|
52
|
-
* volatile MCP tools). Costs more cachePoint budget.
|
|
53
|
-
* - 'none': no cachePoint on tools array. Use when tool definitions
|
|
54
|
-
* change every request anyway.
|
|
55
|
-
*/
|
|
56
|
-
export type ToolCacheStrategy = 'single' | 'split' | 'none';
|
|
57
|
-
/**
|
|
58
|
-
* Group selector for `toolCacheStrategy: 'split'`. Receives the tool name
|
|
59
|
-
* and returns a stable group key — tools with the same key are grouped
|
|
60
|
-
* together. Group order in the output array follows first-encounter order.
|
|
61
|
-
*/
|
|
62
|
-
export type ToolGroupSelector = (toolName: string) => string;
|
|
63
|
-
/**
|
|
64
|
-
* Default group selector — puts all tools in a single group named 'core'.
|
|
65
|
-
* Equivalent to 'single' strategy but explicit. Consumers override this
|
|
66
|
-
* to enable per-source grouping (e.g. ranger uses `_mcp_` substring to
|
|
67
|
-
* separate core from MCP tools).
|
|
68
|
-
*/
|
|
69
|
-
export declare const DEFAULT_TOOL_GROUP_SELECTOR: ToolGroupSelector;
|
|
70
44
|
/**
|
|
71
45
|
* Extended input interface with additional features:
|
|
72
46
|
* - promptCache: Enable Bedrock prompt caching for tool definitions
|
|
73
47
|
* - applicationInferenceProfile: Use an inference profile ARN instead of model ID
|
|
74
48
|
* - serviceTier: Specify service tier (Priority, Standard, Flex, Reserved)
|
|
75
|
-
* - toolCacheStrategy: How to allocate cachePoints across tools array
|
|
76
|
-
* - toolGroupSelector: Group key resolver for the 'split' strategy
|
|
77
49
|
*/
|
|
78
50
|
export interface IllumaBedrockConverseInput extends ChatBedrockConverseInput {
|
|
79
51
|
/**
|
|
80
52
|
* Enable Bedrock prompt caching for tool definitions.
|
|
81
|
-
* When true, adds cachePoint
|
|
82
|
-
* `toolCacheStrategy`. Defaults to 'single'.
|
|
53
|
+
* When true, adds cachePoint markers to tools array.
|
|
83
54
|
*/
|
|
84
55
|
promptCache?: boolean;
|
|
85
|
-
/**
|
|
86
|
-
* Tool cachePoint allocation. Defaults to 'single' — one cachePoint at
|
|
87
|
-
* the end of the tools array. Set to 'split' (with `toolGroupSelector`)
|
|
88
|
-
* when different tool groups have different volatility.
|
|
89
|
-
*/
|
|
90
|
-
toolCacheStrategy?: ToolCacheStrategy;
|
|
91
|
-
/**
|
|
92
|
-
* Group selector for 'split' strategy. Receives a tool name, returns
|
|
93
|
-
* a stable group key. Defaults to a one-group selector (equivalent
|
|
94
|
-
* to 'single').
|
|
95
|
-
*/
|
|
96
|
-
toolGroupSelector?: ToolGroupSelector;
|
|
97
|
-
/**
|
|
98
|
-
* Additional model ID patterns to consider Bedrock-cache-supported.
|
|
99
|
-
* Defaults are in `src/llm/bedrock/cacheSupport.ts`. Use this when
|
|
100
|
-
* AWS adds a new model family before the next library release.
|
|
101
|
-
*/
|
|
102
|
-
bedrockCacheModelPatterns?: readonly RegExp[];
|
|
103
56
|
/**
|
|
104
57
|
* Application Inference Profile ARN to use for the model.
|
|
105
58
|
* For example, "arn:aws:bedrock:eu-west-1:123456789102:application-inference-profile/fm16bt65tzgx"
|
|
@@ -137,12 +90,6 @@ export declare class IllumaBedrockConverse extends ChatBedrockConverse {
|
|
|
137
90
|
applicationInferenceProfile?: string;
|
|
138
91
|
/** Service tier for model invocation */
|
|
139
92
|
serviceTier?: ServiceTierType;
|
|
140
|
-
/** Tool cachePoint allocation strategy. */
|
|
141
|
-
toolCacheStrategy: ToolCacheStrategy;
|
|
142
|
-
/** Group selector for 'split' strategy. */
|
|
143
|
-
toolGroupSelector: ToolGroupSelector;
|
|
144
|
-
/** Optional consumer extensions to the cache-supported model allowlist. */
|
|
145
|
-
bedrockCacheModelPatterns?: readonly RegExp[];
|
|
146
93
|
constructor(fields?: IllumaBedrockConverseInput);
|
|
147
94
|
static lc_name(): string;
|
|
148
95
|
/**
|