@illuma-ai/agents 1.1.25 → 1.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/agents/AgentContext.cjs +20 -3
- package/dist/cjs/agents/AgentContext.cjs.map +1 -1
- package/dist/cjs/common/spawnPath.cjs +104 -0
- package/dist/cjs/common/spawnPath.cjs.map +1 -0
- package/dist/cjs/graphs/Graph.cjs +87 -31
- package/dist/cjs/graphs/Graph.cjs.map +1 -1
- package/dist/cjs/graphs/HandoffRegistry.cjs +143 -0
- package/dist/cjs/graphs/HandoffRegistry.cjs.map +1 -0
- package/dist/cjs/graphs/MultiAgentGraph.cjs +587 -184
- package/dist/cjs/graphs/MultiAgentGraph.cjs.map +1 -1
- package/dist/cjs/graphs/phases/flushLoop.cjs +214 -0
- package/dist/cjs/graphs/phases/flushLoop.cjs.map +1 -0
- package/dist/cjs/graphs/phases/memoryFlushPhase.cjs +102 -0
- package/dist/cjs/graphs/phases/memoryFlushPhase.cjs.map +1 -0
- package/dist/cjs/llm/bedrock/index.cjs +4 -3
- package/dist/cjs/llm/bedrock/index.cjs.map +1 -1
- package/dist/cjs/main.cjs +115 -0
- package/dist/cjs/main.cjs.map +1 -1
- package/dist/cjs/memory/citations.cjs +69 -0
- package/dist/cjs/memory/citations.cjs.map +1 -0
- package/dist/cjs/memory/compositeBackend.cjs +60 -0
- package/dist/cjs/memory/compositeBackend.cjs.map +1 -0
- package/dist/cjs/memory/constants.cjs +232 -0
- package/dist/cjs/memory/constants.cjs.map +1 -0
- package/dist/cjs/memory/embeddings.cjs +151 -0
- package/dist/cjs/memory/embeddings.cjs.map +1 -0
- package/dist/cjs/memory/factory.cjs +95 -0
- package/dist/cjs/memory/factory.cjs.map +1 -0
- package/dist/cjs/memory/migrate.cjs +81 -0
- package/dist/cjs/memory/migrate.cjs.map +1 -0
- package/dist/cjs/memory/mmr.cjs +138 -0
- package/dist/cjs/memory/mmr.cjs.map +1 -0
- package/dist/cjs/memory/paths.cjs +217 -0
- package/dist/cjs/memory/paths.cjs.map +1 -0
- package/dist/cjs/memory/pgvectorStore.cjs +225 -0
- package/dist/cjs/memory/pgvectorStore.cjs.map +1 -0
- package/dist/cjs/memory/recallTracking.cjs +98 -0
- package/dist/cjs/memory/recallTracking.cjs.map +1 -0
- package/dist/cjs/memory/schema.sql +51 -0
- package/dist/cjs/memory/temporalDecay.cjs +118 -0
- package/dist/cjs/memory/temporalDecay.cjs.map +1 -0
- package/dist/cjs/nodes/ApprovalGateNode.cjs +1 -1
- package/dist/cjs/nodes/ApprovalGateNode.cjs.map +1 -1
- package/dist/cjs/prompts/memoryFlushPrompt.cjs +49 -0
- package/dist/cjs/prompts/memoryFlushPrompt.cjs.map +1 -0
- package/dist/cjs/run.cjs +16 -3
- package/dist/cjs/run.cjs.map +1 -1
- package/dist/cjs/stream.cjs +4 -4
- package/dist/cjs/stream.cjs.map +1 -1
- package/dist/cjs/tools/AskUser.cjs +6 -1
- package/dist/cjs/tools/AskUser.cjs.map +1 -1
- package/dist/cjs/tools/BrowserTools.cjs +1 -1
- package/dist/cjs/tools/BrowserTools.cjs.map +1 -1
- package/dist/cjs/tools/ToolNode.cjs +127 -10
- package/dist/cjs/tools/ToolNode.cjs.map +1 -1
- package/dist/cjs/tools/approval/constants.cjs +2 -2
- package/dist/cjs/tools/approval/constants.cjs.map +1 -1
- package/dist/cjs/tools/memory/index.cjs +58 -0
- package/dist/cjs/tools/memory/index.cjs.map +1 -0
- package/dist/cjs/tools/memory/memoryAppendTool.cjs +69 -0
- package/dist/cjs/tools/memory/memoryAppendTool.cjs.map +1 -0
- package/dist/cjs/tools/memory/memoryGetTool.cjs +49 -0
- package/dist/cjs/tools/memory/memoryGetTool.cjs.map +1 -0
- package/dist/cjs/tools/memory/memorySearchTool.cjs +65 -0
- package/dist/cjs/tools/memory/memorySearchTool.cjs.map +1 -0
- package/dist/cjs/tools/memory/shared.cjs +106 -0
- package/dist/cjs/tools/memory/shared.cjs.map +1 -0
- package/dist/cjs/types/graph.cjs.map +1 -1
- package/dist/cjs/utils/childAgentContext.cjs +242 -0
- package/dist/cjs/utils/childAgentContext.cjs.map +1 -0
- package/dist/cjs/utils/events.cjs +36 -4
- package/dist/cjs/utils/events.cjs.map +1 -1
- package/dist/cjs/utils/finishReasons.cjs +44 -0
- package/dist/cjs/utils/finishReasons.cjs.map +1 -0
- package/dist/cjs/utils/llm.cjs.map +1 -1
- package/dist/cjs/utils/logging.cjs +34 -0
- package/dist/cjs/utils/logging.cjs.map +1 -0
- package/dist/cjs/utils/toolCallNormalization.cjs +250 -0
- package/dist/cjs/utils/toolCallNormalization.cjs.map +1 -0
- package/dist/esm/agents/AgentContext.mjs +20 -3
- package/dist/esm/agents/AgentContext.mjs.map +1 -1
- package/dist/esm/common/spawnPath.mjs +95 -0
- package/dist/esm/common/spawnPath.mjs.map +1 -0
- package/dist/esm/graphs/Graph.mjs +87 -31
- package/dist/esm/graphs/Graph.mjs.map +1 -1
- package/dist/esm/graphs/HandoffRegistry.mjs +141 -0
- package/dist/esm/graphs/HandoffRegistry.mjs.map +1 -0
- package/dist/esm/graphs/MultiAgentGraph.mjs +587 -184
- package/dist/esm/graphs/MultiAgentGraph.mjs.map +1 -1
- package/dist/esm/graphs/phases/flushLoop.mjs +209 -0
- package/dist/esm/graphs/phases/flushLoop.mjs.map +1 -0
- package/dist/esm/graphs/phases/memoryFlushPhase.mjs +99 -0
- package/dist/esm/graphs/phases/memoryFlushPhase.mjs.map +1 -0
- package/dist/esm/llm/bedrock/index.mjs +4 -3
- package/dist/esm/llm/bedrock/index.mjs.map +1 -1
- package/dist/esm/main.mjs +21 -0
- package/dist/esm/main.mjs.map +1 -1
- package/dist/esm/memory/citations.mjs +64 -0
- package/dist/esm/memory/citations.mjs.map +1 -0
- package/dist/esm/memory/compositeBackend.mjs +58 -0
- package/dist/esm/memory/compositeBackend.mjs.map +1 -0
- package/dist/esm/memory/constants.mjs +198 -0
- package/dist/esm/memory/constants.mjs.map +1 -0
- package/dist/esm/memory/embeddings.mjs +148 -0
- package/dist/esm/memory/embeddings.mjs.map +1 -0
- package/dist/esm/memory/factory.mjs +93 -0
- package/dist/esm/memory/factory.mjs.map +1 -0
- package/dist/esm/memory/migrate.mjs +78 -0
- package/dist/esm/memory/migrate.mjs.map +1 -0
- package/dist/esm/memory/mmr.mjs +130 -0
- package/dist/esm/memory/mmr.mjs.map +1 -0
- package/dist/esm/memory/paths.mjs +207 -0
- package/dist/esm/memory/paths.mjs.map +1 -0
- package/dist/esm/memory/pgvectorStore.mjs +223 -0
- package/dist/esm/memory/pgvectorStore.mjs.map +1 -0
- package/dist/esm/memory/recallTracking.mjs +94 -0
- package/dist/esm/memory/recallTracking.mjs.map +1 -0
- package/dist/esm/memory/schema.sql +51 -0
- package/dist/esm/memory/temporalDecay.mjs +110 -0
- package/dist/esm/memory/temporalDecay.mjs.map +1 -0
- package/dist/esm/nodes/ApprovalGateNode.mjs +1 -1
- package/dist/esm/nodes/ApprovalGateNode.mjs.map +1 -1
- package/dist/esm/prompts/memoryFlushPrompt.mjs +44 -0
- package/dist/esm/prompts/memoryFlushPrompt.mjs.map +1 -0
- package/dist/esm/run.mjs +16 -3
- package/dist/esm/run.mjs.map +1 -1
- package/dist/esm/stream.mjs +4 -4
- package/dist/esm/stream.mjs.map +1 -1
- package/dist/esm/tools/AskUser.mjs +6 -1
- package/dist/esm/tools/AskUser.mjs.map +1 -1
- package/dist/esm/tools/BrowserTools.mjs +1 -1
- package/dist/esm/tools/BrowserTools.mjs.map +1 -1
- package/dist/esm/tools/ToolNode.mjs +128 -11
- package/dist/esm/tools/ToolNode.mjs.map +1 -1
- package/dist/esm/tools/approval/constants.mjs +2 -2
- package/dist/esm/tools/approval/constants.mjs.map +1 -1
- package/dist/esm/tools/memory/index.mjs +46 -0
- package/dist/esm/tools/memory/index.mjs.map +1 -0
- package/dist/esm/tools/memory/memoryAppendTool.mjs +67 -0
- package/dist/esm/tools/memory/memoryAppendTool.mjs.map +1 -0
- package/dist/esm/tools/memory/memoryGetTool.mjs +47 -0
- package/dist/esm/tools/memory/memoryGetTool.mjs.map +1 -0
- package/dist/esm/tools/memory/memorySearchTool.mjs +63 -0
- package/dist/esm/tools/memory/memorySearchTool.mjs.map +1 -0
- package/dist/esm/tools/memory/shared.mjs +98 -0
- package/dist/esm/tools/memory/shared.mjs.map +1 -0
- package/dist/esm/types/graph.mjs.map +1 -1
- package/dist/esm/utils/childAgentContext.mjs +237 -0
- package/dist/esm/utils/childAgentContext.mjs.map +1 -0
- package/dist/esm/utils/events.mjs +36 -5
- package/dist/esm/utils/events.mjs.map +1 -1
- package/dist/esm/utils/finishReasons.mjs +41 -0
- package/dist/esm/utils/finishReasons.mjs.map +1 -0
- package/dist/esm/utils/llm.mjs.map +1 -1
- package/dist/esm/utils/logging.mjs +31 -0
- package/dist/esm/utils/logging.mjs.map +1 -0
- package/dist/esm/utils/toolCallNormalization.mjs +247 -0
- package/dist/esm/utils/toolCallNormalization.mjs.map +1 -0
- package/dist/types/common/index.d.ts +1 -0
- package/dist/types/common/spawnPath.d.ts +59 -0
- package/dist/types/graphs/HandoffRegistry.d.ts +97 -0
- package/dist/types/graphs/MultiAgentGraph.d.ts +58 -18
- package/dist/types/graphs/index.d.ts +1 -0
- package/dist/types/graphs/phases/flushLoop.d.ts +106 -0
- package/dist/types/graphs/phases/memoryFlushPhase.d.ts +100 -0
- package/dist/types/index.d.ts +7 -0
- package/dist/types/memory/__tests__/mockBackend.d.ts +40 -0
- package/dist/types/memory/citations.d.ts +39 -0
- package/dist/types/memory/compositeBackend.d.ts +30 -0
- package/dist/types/memory/constants.d.ts +121 -0
- package/dist/types/memory/embeddings.d.ts +15 -0
- package/dist/types/memory/factory.d.ts +23 -0
- package/dist/types/memory/index.d.ts +21 -0
- package/dist/types/memory/migrate.d.ts +14 -0
- package/dist/types/memory/mmr.d.ts +50 -0
- package/dist/types/memory/paths.d.ts +107 -0
- package/dist/types/memory/pgvectorStore.d.ts +56 -0
- package/dist/types/memory/recallTracking.d.ts +30 -0
- package/dist/types/memory/temporalDecay.d.ts +53 -0
- package/dist/types/memory/types.d.ts +182 -0
- package/dist/types/prompts/memoryFlushPrompt.d.ts +54 -0
- package/dist/types/run.d.ts +1 -0
- package/dist/types/tools/AskUser.d.ts +1 -1
- package/dist/types/tools/BrowserTools.d.ts +2 -2
- package/dist/types/tools/approval/constants.d.ts +2 -2
- package/dist/types/tools/memory/index.d.ts +39 -0
- package/dist/types/tools/memory/memoryAppendTool.d.ts +27 -0
- package/dist/types/tools/memory/memoryGetTool.d.ts +22 -0
- package/dist/types/tools/memory/memorySearchTool.d.ts +22 -0
- package/dist/types/tools/memory/shared.d.ts +106 -0
- package/dist/types/types/graph.d.ts +16 -3
- package/dist/types/utils/childAgentContext.d.ts +99 -0
- package/dist/types/utils/events.d.ts +21 -0
- package/dist/types/utils/finishReasons.d.ts +32 -0
- package/dist/types/utils/logging.d.ts +2 -0
- package/dist/types/utils/toolCallNormalization.d.ts +44 -0
- package/package.json +6 -4
- package/src/agents/AgentContext.ts +26 -3
- package/src/common/__tests__/enum.test.ts +4 -2
- package/src/common/__tests__/spawnPath.test.ts +110 -0
- package/src/common/index.ts +1 -0
- package/src/common/spawnPath.ts +101 -0
- package/src/graphs/Graph.ts +94 -43
- package/src/graphs/HandoffRegistry.ts +199 -0
- package/src/graphs/MultiAgentGraph.ts +694 -226
- package/src/graphs/__tests__/HandoffRegistry.test.ts +410 -0
- package/src/graphs/__tests__/multi-agent-delegate.test.ts +61 -16
- package/src/graphs/__tests__/multi-agent-edges.test.ts +4 -2
- package/src/graphs/__tests__/multi-agent-nested-subgraph.test.ts +221 -0
- package/src/graphs/__tests__/structured-output.integration.test.ts +212 -118
- package/src/graphs/contextManagement.e2e.test.ts +1 -1
- package/src/graphs/index.ts +1 -0
- package/src/graphs/phases/__tests__/flushLoop.test.ts +264 -0
- package/src/graphs/phases/__tests__/memoryFlushPhase.test.ts +37 -0
- package/src/graphs/phases/__tests__/runMemoryFlush.test.ts +150 -0
- package/src/graphs/phases/flushLoop.ts +303 -0
- package/src/graphs/phases/memoryFlushPhase.ts +209 -0
- package/src/index.ts +30 -1
- package/src/llm/bedrock/index.ts +4 -5
- package/src/memory/__tests__/citations.test.ts +61 -0
- package/src/memory/__tests__/compositeBackend.test.ts +79 -0
- package/src/memory/__tests__/isolation.test.ts +206 -0
- package/src/memory/__tests__/mmr.test.ts +148 -0
- package/src/memory/__tests__/mockBackend.ts +161 -0
- package/src/memory/__tests__/paths.test.ts +168 -0
- package/src/memory/__tests__/recallTracking.test.ts +96 -0
- package/src/memory/__tests__/temporalDecay.test.ts +151 -0
- package/src/memory/citations.ts +80 -0
- package/src/memory/compositeBackend.ts +99 -0
- package/src/memory/constants.ts +229 -0
- package/src/memory/embeddings.ts +188 -0
- package/src/memory/factory.ts +111 -0
- package/src/memory/index.ts +46 -0
- package/src/memory/migrate.ts +116 -0
- package/src/memory/mmr.ts +161 -0
- package/src/memory/paths.ts +258 -0
- package/src/memory/pgvectorStore.ts +324 -0
- package/src/memory/recallTracking.ts +127 -0
- package/src/memory/schema.sql +51 -0
- package/src/memory/temporalDecay.ts +134 -0
- package/src/memory/types.ts +185 -0
- package/src/nodes/ApprovalGateNode.ts +4 -10
- package/src/nodes/__tests__/ApprovalGateNode.test.ts +11 -20
- package/src/prompts/memoryFlushPrompt.ts +78 -0
- package/src/run.ts +17 -6
- package/src/scripts/test-bedrock-handoff-autonomous.ts +56 -20
- package/src/specs/agent-handoffs-bedrock.integration.test.ts +8 -5
- package/src/specs/agent-handoffs.test.ts +8 -2
- package/src/stream.ts +4 -6
- package/src/tools/AskUser.ts +7 -2
- package/src/tools/BrowserTools.ts +3 -5
- package/src/tools/ToolNode.ts +150 -13
- package/src/tools/__tests__/ToolApproval.test.ts +22 -9
- package/src/tools/approval/__tests__/constants.test.ts +4 -4
- package/src/tools/approval/constants.ts +2 -2
- package/src/tools/memory/__tests__/memoryTools.test.ts +205 -0
- package/src/tools/memory/index.ts +96 -0
- package/src/tools/memory/memoryAppendTool.ts +101 -0
- package/src/tools/memory/memoryGetTool.ts +53 -0
- package/src/tools/memory/memorySearchTool.ts +80 -0
- package/src/tools/memory/shared.ts +169 -0
- package/src/tools/search/search.test.ts +6 -1
- package/src/types/graph.ts +16 -3
- package/src/utils/__tests__/childAgentContext.test.ts +217 -0
- package/src/utils/__tests__/finishReasons.test.ts +55 -0
- package/src/utils/__tests__/toolCallNormalization.test.ts +181 -0
- package/src/utils/childAgentContext.ts +259 -0
- package/src/utils/events.ts +37 -4
- package/src/utils/finishReasons.ts +40 -0
- package/src/utils/llm.ts +0 -1
- package/src/utils/logging.ts +45 -8
- package/src/utils/toolCallNormalization.ts +271 -0
|
@@ -7,13 +7,18 @@ var langgraph = require('@langchain/langgraph');
|
|
|
7
7
|
require('../messages/core.cjs');
|
|
8
8
|
require('nanoid');
|
|
9
9
|
var _enum = require('../common/enum.cjs');
|
|
10
|
+
var spawnPath = require('../common/spawnPath.cjs');
|
|
10
11
|
require('../tools/approval/constants.cjs');
|
|
11
12
|
require('../utils/toonFormat.cjs');
|
|
12
13
|
var summarize = require('../messages/summarize.cjs');
|
|
13
14
|
var Graph = require('./Graph.cjs');
|
|
14
15
|
var events = require('../utils/events.cjs');
|
|
16
|
+
var logging = require('../utils/logging.cjs');
|
|
17
|
+
var childAgentContext = require('../utils/childAgentContext.cjs');
|
|
15
18
|
var ApprovalGateNode = require('../nodes/ApprovalGateNode.cjs');
|
|
16
19
|
|
|
20
|
+
// HandoffRegistry no longer needed — handoff tools use synchronous
|
|
21
|
+
// browser-tool callback pattern (spawn → wait → return result)
|
|
17
22
|
/** Pattern to extract instructions from transfer ToolMessage content */
|
|
18
23
|
const TRANSFER_INSTRUCTIONS_PATTERN = /(?:Instructions?|Context):\s*(.+)/is;
|
|
19
24
|
/**
|
|
@@ -60,6 +65,12 @@ class MultiAgentGraph extends Graph.StandardGraph {
|
|
|
60
65
|
* Used by auto-continuation to know which agent's context to preserve after handoff.
|
|
61
66
|
*/
|
|
62
67
|
lastActiveAgentId;
|
|
68
|
+
/**
|
|
69
|
+
* Registry for async handoff execution.
|
|
70
|
+
* Enables autonomous orchestration: spawn children non-blocking,
|
|
71
|
+
* orchestrator stays alive to reason and collect results when ready.
|
|
72
|
+
*/
|
|
73
|
+
// HandoffRegistry removed — handoff tools are synchronous (callback pattern)
|
|
63
74
|
/**
|
|
64
75
|
* When set, the graph routes START to this agent instead of the default starting nodes.
|
|
65
76
|
* Enables multi-turn resumption: follow-up messages go to the agent that last handled
|
|
@@ -74,7 +85,7 @@ class MultiAgentGraph extends Graph.StandardGraph {
|
|
|
74
85
|
this.analyzeGraph();
|
|
75
86
|
this.createTransferTools();
|
|
76
87
|
this.createHandoffTools();
|
|
77
|
-
|
|
88
|
+
logging.mlog(`[MultiAgentGraph] Constructor complete: ${this.agentContexts.size} agents, ${this.edges.length} edges`);
|
|
78
89
|
}
|
|
79
90
|
/**
|
|
80
91
|
* Categorize edges into handoff, transfer, and sequence types
|
|
@@ -87,7 +98,8 @@ class MultiAgentGraph extends Graph.StandardGraph {
|
|
|
87
98
|
else if (edge.edgeType === _enum.EdgeType.SEQUENCE) {
|
|
88
99
|
this.sequenceEdges.push(edge);
|
|
89
100
|
}
|
|
90
|
-
else if (edge.edgeType === _enum.EdgeType.TRANSFER ||
|
|
101
|
+
else if (edge.edgeType === _enum.EdgeType.TRANSFER ||
|
|
102
|
+
edge.condition != null) {
|
|
91
103
|
this.transferEdges.push(edge);
|
|
92
104
|
}
|
|
93
105
|
else {
|
|
@@ -104,7 +116,7 @@ class MultiAgentGraph extends Graph.StandardGraph {
|
|
|
104
116
|
}
|
|
105
117
|
}
|
|
106
118
|
}
|
|
107
|
-
|
|
119
|
+
logging.mlog(`[MultiAgentGraph] Edge categorization: ${this.handoffEdges.length} handoff, ${this.transferEdges.length} transfer, ${this.sequenceEdges.length} sequence (of ${this.edges.length} total)`);
|
|
108
120
|
}
|
|
109
121
|
/**
|
|
110
122
|
* Analyze graph structure to determine starting nodes and connections
|
|
@@ -126,7 +138,7 @@ class MultiAgentGraph extends Graph.StandardGraph {
|
|
|
126
138
|
if (this.startingNodes.size === 0 && this.agentContexts.size > 0) {
|
|
127
139
|
this.startingNodes.add(this.agentContexts.keys().next().value);
|
|
128
140
|
}
|
|
129
|
-
|
|
141
|
+
logging.mlog(`[MultiAgentGraph] Starting nodes identified: [${Array.from(this.startingNodes).join(', ')}]`);
|
|
130
142
|
// Determine if graph has parallel execution capability
|
|
131
143
|
this.computeParallelCapability();
|
|
132
144
|
}
|
|
@@ -261,7 +273,22 @@ class MultiAgentGraph extends Graph.StandardGraph {
|
|
|
261
273
|
agentContext.graphTools = [];
|
|
262
274
|
}
|
|
263
275
|
agentContext.graphTools.push(...transferTools);
|
|
264
|
-
|
|
276
|
+
logging.mlog(`[MultiAgentGraph] Transfer tools for "${agentId}": [${transferTools.map((t) => t.name).join(', ')}]`);
|
|
277
|
+
// Inject orchestration guidance for agents with transfer tools
|
|
278
|
+
const childDescs = edges.flatMap((e) => {
|
|
279
|
+
const dests = Array.isArray(e.to) ? e.to : [e.to];
|
|
280
|
+
return dests.map((d) => {
|
|
281
|
+
const ctx = this.agentContexts.get(d);
|
|
282
|
+
const name = ctx?.name ?? d;
|
|
283
|
+
const desc = ctx?.description ? ` — ${ctx.description}` : '';
|
|
284
|
+
return `${name}${desc}`;
|
|
285
|
+
});
|
|
286
|
+
});
|
|
287
|
+
const guidance = this.buildOrchestratorGuidance(childDescs, transferTools.length);
|
|
288
|
+
const existing = agentContext.additionalInstructions ?? '';
|
|
289
|
+
agentContext.additionalInstructions = existing
|
|
290
|
+
? `${existing}\n\n${guidance}`
|
|
291
|
+
: guidance;
|
|
265
292
|
}
|
|
266
293
|
}
|
|
267
294
|
/**
|
|
@@ -280,7 +307,9 @@ class MultiAgentGraph extends Graph.StandardGraph {
|
|
|
280
307
|
const toolDescription = edge.description ?? 'Conditionally transfer control based on state';
|
|
281
308
|
/** Check if we have a prompt for handoff input */
|
|
282
309
|
const hasTransferInput = edge.prompt != null && typeof edge.prompt === 'string';
|
|
283
|
-
const transferInputDescription = hasTransferInput
|
|
310
|
+
const transferInputDescription = hasTransferInput
|
|
311
|
+
? edge.prompt
|
|
312
|
+
: undefined;
|
|
284
313
|
const promptKey = edge.promptKey ?? 'instructions';
|
|
285
314
|
tools$1.push(tools.tool(async (rawInput, config) => {
|
|
286
315
|
const input = rawInput;
|
|
@@ -455,6 +484,83 @@ class MultiAgentGraph extends Graph.StandardGraph {
|
|
|
455
484
|
}
|
|
456
485
|
return tools$1;
|
|
457
486
|
}
|
|
487
|
+
/**
|
|
488
|
+
* Builds orchestration guidance injected into the system message of agents
|
|
489
|
+
* that have handoff or transfer tools (i.e., orchestrator agents).
|
|
490
|
+
*
|
|
491
|
+
* Implements two orchestration primitives:
|
|
492
|
+
* - Execution bias guidance injected into the system prompt
|
|
493
|
+
* - Multi-round autonomous execution for dependent tasks
|
|
494
|
+
*
|
|
495
|
+
* Handoff tools are synchronous (browser-tool callback pattern): spawn the
|
|
496
|
+
* child, await completion, return the real text as the tool output. Parallel
|
|
497
|
+
* handoff tool calls in one turn run concurrently via LangGraph's ToolNode,
|
|
498
|
+
* so independent children run in parallel without explicit orchestration.
|
|
499
|
+
*
|
|
500
|
+
* @param childDescs - Display names (with optional descriptions) of child agents
|
|
501
|
+
* @param toolCount - Number of handoff/transfer tools available
|
|
502
|
+
*/
|
|
503
|
+
buildOrchestratorGuidance(childDescs, toolCount) {
|
|
504
|
+
return [
|
|
505
|
+
'## Agent Orchestration',
|
|
506
|
+
'',
|
|
507
|
+
`You have ${toolCount} specialist agent(s) available for delegation:`,
|
|
508
|
+
...childDescs.map((d) => `- ${d}`),
|
|
509
|
+
'',
|
|
510
|
+
'## Execution Bias',
|
|
511
|
+
'If the user asks you to do the work, start doing it in the same turn.',
|
|
512
|
+
'Use a real tool call or concrete action first when the task is actionable; do not stop at a plan or promise-to-act reply.',
|
|
513
|
+
'Commentary-only turns are incomplete when tools are available and the next action is clear.',
|
|
514
|
+
'If the work will take multiple steps or a while to finish, send one short progress update before or while acting.',
|
|
515
|
+
'',
|
|
516
|
+
'## How Delegation Works',
|
|
517
|
+
'Each handoff tool call spawns a sub-agent, waits for it to complete, and returns the real result directly — like a function call.',
|
|
518
|
+
'Independent tasks MAY be called in parallel (multiple handoff tool calls in one turn). They run concurrently and all results return together.',
|
|
519
|
+
'Dependent tasks MUST be sequential: call one agent, get the result, then call the next agent using that real data.',
|
|
520
|
+
'',
|
|
521
|
+
'## Agent Isolation',
|
|
522
|
+
"Sub-agents CANNOT see your conversation or the user's original message. They ONLY see what you write in the `instructions` parameter.",
|
|
523
|
+
"When writing instructions, include ALL data the agent needs. Copy exact values from the user's message — email addresses, names, URLs, dates, numbers.",
|
|
524
|
+
'When delegating follow-up work, include the real data from prior agent results directly in the instructions text.',
|
|
525
|
+
'Do NOT re-delegate a task that was already completed. If you have the data, pass it directly.',
|
|
526
|
+
].join('\n');
|
|
527
|
+
}
|
|
528
|
+
/**
|
|
529
|
+
* Builds subagent context instructions injected into child agents that are
|
|
530
|
+
* handoff destinations. This tells the child agent it is a subagent with
|
|
531
|
+
* a focused task.
|
|
532
|
+
*
|
|
533
|
+
* @param orchestratorName - Display name of the parent orchestrator agent
|
|
534
|
+
*/
|
|
535
|
+
buildChildAgentContext(orchestratorName) {
|
|
536
|
+
return [
|
|
537
|
+
'# Subagent Context',
|
|
538
|
+
'',
|
|
539
|
+
`You are a **subagent** spawned by the ${orchestratorName} for a specific task.`,
|
|
540
|
+
'',
|
|
541
|
+
'## Your Role',
|
|
542
|
+
"- Complete this task. That's your entire purpose.",
|
|
543
|
+
`- You are NOT the ${orchestratorName}. Don't try to be.`,
|
|
544
|
+
'',
|
|
545
|
+
'## Rules',
|
|
546
|
+
'1. **Stay focused** - Do your assigned task, nothing else',
|
|
547
|
+
`2. **Complete the task** - Your final message will be automatically reported to the ${orchestratorName}`,
|
|
548
|
+
"3. **Don't initiate** - No heartbeats, no proactive actions, no side quests",
|
|
549
|
+
"4. **Be ephemeral** - You may be terminated after task completion. That's fine.",
|
|
550
|
+
'',
|
|
551
|
+
'## Output Format',
|
|
552
|
+
'When complete, your final response should include:',
|
|
553
|
+
'- What you accomplished or found',
|
|
554
|
+
`- Any relevant details the ${orchestratorName} should know`,
|
|
555
|
+
'- Keep it concise but informative',
|
|
556
|
+
'',
|
|
557
|
+
"## What You DON'T Do",
|
|
558
|
+
`- NO user conversations (that's ${orchestratorName}'s job)`,
|
|
559
|
+
'- NO external messages (email, tweets, etc.) unless explicitly tasked with a specific recipient/channel',
|
|
560
|
+
'- NO cron jobs or persistent state',
|
|
561
|
+
`- NO pretending to be the ${orchestratorName}`,
|
|
562
|
+
].join('\n');
|
|
563
|
+
}
|
|
458
564
|
/**
|
|
459
565
|
* Builds a meaningful default description for a transfer tool when no explicit
|
|
460
566
|
* edge.description is provided. Uses the destination agent's name and description
|
|
@@ -502,14 +608,53 @@ class MultiAgentGraph extends Graph.StandardGraph {
|
|
|
502
608
|
agentContext.graphTools = [];
|
|
503
609
|
}
|
|
504
610
|
agentContext.graphTools.push(...handoffTools);
|
|
505
|
-
|
|
611
|
+
// No collect_results tool needed — handoff tools use the browser-tool
|
|
612
|
+
// callback pattern: spawn child, wait for completion, return real result.
|
|
613
|
+
// The LLM naturally gets child results as tool return values.
|
|
614
|
+
logging.mlog(`[MultiAgentGraph] Handoff tools for "${agentId}": [${handoffTools.map((t) => t.name).join(', ')}]`);
|
|
615
|
+
// Inject autonomous orchestration guidance for agents with handoff tools.
|
|
616
|
+
const childDescs = edges.flatMap((e) => {
|
|
617
|
+
const dests = Array.isArray(e.to) ? e.to : [e.to];
|
|
618
|
+
return dests.map((d) => {
|
|
619
|
+
const ctx = this.agentContexts.get(d);
|
|
620
|
+
const name = ctx?.name ?? d;
|
|
621
|
+
const desc = ctx?.description ? ` — ${ctx.description}` : '';
|
|
622
|
+
return `${name}${desc}`;
|
|
623
|
+
});
|
|
624
|
+
});
|
|
625
|
+
const orchestrationGuidance = this.buildOrchestratorGuidance(childDescs, handoffTools.length);
|
|
626
|
+
const existing = agentContext.additionalInstructions ?? '';
|
|
627
|
+
agentContext.additionalInstructions = existing
|
|
628
|
+
? `${existing}\n\n${orchestrationGuidance}`
|
|
629
|
+
: orchestrationGuidance;
|
|
630
|
+
// Inject subagent context into each child/destination agent.
|
|
631
|
+
// This tells child agents they are subagents with a focused task — stay focused,
|
|
632
|
+
// execute (don't plan), and return results to the orchestrator.
|
|
633
|
+
const orchestratorName = agentContext.name ?? agentId;
|
|
634
|
+
const childAgentContext = this.buildChildAgentContext(orchestratorName);
|
|
635
|
+
for (const edge of edges) {
|
|
636
|
+
const dests = Array.isArray(edge.to) ? edge.to : [edge.to];
|
|
637
|
+
for (const destId of dests) {
|
|
638
|
+
const destCtx = this.agentContexts.get(destId);
|
|
639
|
+
if (!destCtx)
|
|
640
|
+
continue;
|
|
641
|
+
const existingChild = destCtx.additionalInstructions ?? '';
|
|
642
|
+
// Avoid duplicate injection if agent is destination of multiple edges
|
|
643
|
+
if (existingChild.includes('# Subagent Context'))
|
|
644
|
+
continue;
|
|
645
|
+
destCtx.additionalInstructions = existingChild
|
|
646
|
+
? `${existingChild}\n\n${childAgentContext}`
|
|
647
|
+
: childAgentContext;
|
|
648
|
+
}
|
|
649
|
+
}
|
|
506
650
|
}
|
|
507
651
|
}
|
|
508
652
|
/**
|
|
509
653
|
* Create handoff tools for an edge (handles multiple destinations).
|
|
510
|
-
* Each handoff tool
|
|
511
|
-
*
|
|
512
|
-
*
|
|
654
|
+
* Each handoff tool spawns the child agent's compiled subgraph asynchronously
|
|
655
|
+
* and returns immediately. The orchestrator uses `collect_results` to retrieve
|
|
656
|
+
* outputs and `check_agents` to monitor status — a push-based autonomous
|
|
657
|
+
* orchestration pattern.
|
|
513
658
|
*
|
|
514
659
|
* @param edge - The graph edge defining the handoff
|
|
515
660
|
* @param sourceAgentId - The ID of the parent/supervisor agent
|
|
@@ -523,81 +668,235 @@ class MultiAgentGraph extends Graph.StandardGraph {
|
|
|
523
668
|
const destContext = this.agentContexts.get(destination);
|
|
524
669
|
const toolDescription = edge.description ??
|
|
525
670
|
this.buildDefaultHandoffDescription(destContext, destination);
|
|
526
|
-
|
|
527
|
-
|
|
671
|
+
/**
|
|
672
|
+
* Always include an instructions parameter so the orchestrator can
|
|
673
|
+
* pass scoped task descriptions to each child agent. Without this,
|
|
674
|
+
* the child gets no context about what to do.
|
|
675
|
+
*/
|
|
528
676
|
const promptKey = edge.promptKey ?? 'instructions';
|
|
677
|
+
const destDesc = destContext?.description;
|
|
678
|
+
const promptInputDescription = edge.prompt ??
|
|
679
|
+
(destDesc
|
|
680
|
+
? `Task instructions for this agent (${destDesc}). Describe exactly what it should do.`
|
|
681
|
+
: 'Specific task instructions for this agent. Describe exactly what it should do and what data to use.');
|
|
529
682
|
/** Capture registry reference — Map populated in createWorkflow() */
|
|
530
|
-
const
|
|
683
|
+
const subgraphReg = this.subgraphRegistry;
|
|
531
684
|
tools$1.push(tools.tool(async (rawInput, config) => {
|
|
532
685
|
const input = rawInput;
|
|
533
|
-
const subgraph =
|
|
686
|
+
const subgraph = subgraphReg.get(destination);
|
|
534
687
|
if (!subgraph) {
|
|
535
688
|
throw new Error(`Handoff target "${destination}" subgraph not found in registry. ` +
|
|
536
689
|
'This is a bug: createWorkflow() should have populated the subgraph registry.');
|
|
537
690
|
}
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
691
|
+
/**
|
|
692
|
+
* Per-spawn unique key = the orchestrator's tool_call.id.
|
|
693
|
+
* LangChain's ToolNode passes `config.toolCall.id` to the tool
|
|
694
|
+
* function; this is the same id the frontend sees on the parent's
|
|
695
|
+
* handoff content part, so the UI can match each AgentHandoff
|
|
696
|
+
* indicator to its own sidebar task without collision when the
|
|
697
|
+
* same agent is invoked multiple times.
|
|
698
|
+
*/
|
|
699
|
+
const toolCallCfg = config?.toolCall;
|
|
700
|
+
const spawnKey = toolCallCfg?.id ??
|
|
701
|
+
`${destination}_${Date.now()}_${Math.random().toString(36).slice(2, 10)}`;
|
|
702
|
+
/**
|
|
703
|
+
* Hierarchical spawnPath: parent's spawnPath (from metadata) + this spawnKey.
|
|
704
|
+
* Root invocations have empty parentSpawnPath. Threaded through childConfig
|
|
705
|
+
* so nested handoffs/sequences inherit the full ancestry.
|
|
706
|
+
* See docs/multi-agent-nesting-architecture.md §4.
|
|
707
|
+
*/
|
|
708
|
+
const parentMetadata = config?.metadata;
|
|
709
|
+
const parentSpawnPath = typeof parentMetadata?.spawnPath === 'string'
|
|
710
|
+
? parentMetadata.spawnPath
|
|
711
|
+
: '';
|
|
712
|
+
const childSpawnPath = spawnPath.buildSpawnPath(parentSpawnPath, spawnKey);
|
|
713
|
+
const childDepth = spawnPath.spawnPathDepth(childSpawnPath);
|
|
714
|
+
/**
|
|
715
|
+
* Child agent message construction — three modes:
|
|
716
|
+
*
|
|
717
|
+
* 1. Default (isolated-session pattern): Child gets ONLY the orchestrator's
|
|
718
|
+
* task instructions as a single HumanMessage. No parent conversation
|
|
719
|
+
* leaks. Orchestrator controls exactly what context the child sees.
|
|
720
|
+
*
|
|
721
|
+
* 2. Passthrough (edge.passthrough = true): Child gets the full parent
|
|
722
|
+
* conversation + orchestrator's instructions appended. Use this when
|
|
723
|
+
* the child needs the full user context (e.g., a transfer-like handoff).
|
|
724
|
+
*
|
|
725
|
+
* 3. Fallback: If no instructions provided AND not passthrough, child
|
|
726
|
+
* gets the agent's description as its task.
|
|
727
|
+
*/
|
|
728
|
+
const taskDescription = promptKey in input && input[promptKey] != null
|
|
729
|
+
? String(input[promptKey])
|
|
730
|
+
: '';
|
|
731
|
+
let childMessages;
|
|
732
|
+
if (edge.passthrough) {
|
|
733
|
+
// Passthrough: full parent context + instructions appended
|
|
734
|
+
const state = langgraph.getCurrentTaskInput();
|
|
735
|
+
childMessages = MultiAgentGraph.prepareHandoffMessages([
|
|
736
|
+
...state.messages,
|
|
737
|
+
]);
|
|
738
|
+
if (taskDescription) {
|
|
739
|
+
childMessages.push(new messages.HumanMessage(taskDescription));
|
|
740
|
+
}
|
|
741
|
+
}
|
|
742
|
+
else {
|
|
743
|
+
// Default: isolated — only orchestrator's instructions
|
|
744
|
+
const fallbackTask = destContext?.description ?? 'Complete your assigned task.';
|
|
544
745
|
childMessages = [
|
|
545
|
-
|
|
546
|
-
new messages.HumanMessage(String(input[promptKey])),
|
|
746
|
+
new messages.HumanMessage(taskDescription || fallbackTask),
|
|
547
747
|
];
|
|
548
748
|
}
|
|
549
749
|
const childState = {
|
|
550
750
|
messages: childMessages,
|
|
551
751
|
};
|
|
552
|
-
|
|
553
|
-
|
|
752
|
+
const childContext = this.agentContexts.get(destination);
|
|
753
|
+
const destName = destContext?.name ?? destination;
|
|
754
|
+
logging.mlog(`[MultiAgentGraph] Handoff "${sourceAgentId}" -> "${destination}" SPAWN (async)\n` +
|
|
755
|
+
` messages: ${childMessages.length}\n` +
|
|
756
|
+
` childTools: ${childContext?.tools?.length ?? 0} instances\n` +
|
|
757
|
+
` childToolDefs: ${childContext?.toolDefinitions?.length ?? 0} definitions`);
|
|
758
|
+
/**
|
|
759
|
+
* Dispatch transition BEFORE spawning the child subgraph so that
|
|
760
|
+
* callbacks.js sets multiAgentTrace.isMultiAgent = true before the
|
|
761
|
+
* child's ON_RUN_STEP events fire. spawnKey lets the UI create a
|
|
762
|
+
* distinct sidebar task for this specific invocation.
|
|
763
|
+
*/
|
|
764
|
+
logging.mlog(`[MultiAgentGraph] Handoff SPAWN "${sourceAgentId}" -> "${destination}" spawnKey=${spawnKey}`);
|
|
765
|
+
await events.safeDispatchCustomEvent(_enum.GraphEvents.ON_AGENT_TRANSITION, {
|
|
766
|
+
sourceAgentId: sourceAgentId,
|
|
767
|
+
sourceAgentName: this.agentContexts.get(sourceAgentId)?.name ?? sourceAgentId,
|
|
768
|
+
destinationAgentId: destination,
|
|
769
|
+
destinationAgentName: destName,
|
|
770
|
+
edgeType: _enum.EdgeType.HANDOFF,
|
|
771
|
+
timestamp: Date.now(),
|
|
772
|
+
spawnKey,
|
|
773
|
+
spawnPath: childSpawnPath,
|
|
774
|
+
parentSpawnPath: parentSpawnPath || null,
|
|
775
|
+
spawnDepth: childDepth,
|
|
776
|
+
}, config);
|
|
777
|
+
/**
|
|
778
|
+
* Child events need to carry spawnKey so callbacks.js can route
|
|
779
|
+
* them to the correct child aggregator. LangChain propagates
|
|
780
|
+
* `metadata` and `tags` from the parent config to all descendants,
|
|
781
|
+
* so everything dispatched inside subgraph.invoke will have
|
|
782
|
+
* metadata.spawnKey populated on the event's runtime metadata.
|
|
783
|
+
*/
|
|
784
|
+
const childConfig = {
|
|
785
|
+
...(config ?? {}),
|
|
786
|
+
metadata: {
|
|
787
|
+
...(config?.metadata ?? {}),
|
|
788
|
+
spawnKey,
|
|
789
|
+
spawnAgentId: destination,
|
|
790
|
+
/** Hierarchical identity — see spawnPath.ts */
|
|
791
|
+
spawnPath: childSpawnPath,
|
|
792
|
+
parentSpawnPath: parentSpawnPath || null,
|
|
793
|
+
spawnDepth: childDepth,
|
|
794
|
+
},
|
|
795
|
+
tags: [
|
|
796
|
+
...(config?.tags ?? []),
|
|
797
|
+
`spawn:${spawnKey}`,
|
|
798
|
+
`depth:${childDepth}`,
|
|
799
|
+
],
|
|
800
|
+
};
|
|
801
|
+
/**
|
|
802
|
+
* Callback pattern: spawn child, WAIT for completion, return real
|
|
803
|
+
* result. The parent naturally sees child results in its tool
|
|
804
|
+
* return, so no manual "collect_results" step is needed.
|
|
805
|
+
*
|
|
806
|
+
* Parallelism still works: when the LLM emits multiple handoff
|
|
807
|
+
* tool calls in one response, LangGraph runs all tool functions
|
|
808
|
+
* concurrently. Each waits for its child. All results land in
|
|
809
|
+
* the LLM's next turn together.
|
|
810
|
+
*/
|
|
811
|
+
const spawnedAt = Date.now();
|
|
554
812
|
try {
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
813
|
+
const result = await subgraph.invoke(childState, childConfig);
|
|
814
|
+
const durationMs = Date.now() - spawnedAt;
|
|
815
|
+
const resultText = MultiAgentGraph.extractHandoffResult(result.messages, destination);
|
|
816
|
+
const truncated = MultiAgentGraph.truncateHandoffResult(resultText, maxResultChars);
|
|
817
|
+
logging.mlog(`[MultiAgentGraph] Handoff COMPLETED "${sourceAgentId}" -> "${destination}" ` +
|
|
818
|
+
`spawnKey=${spawnKey} (${durationMs}ms, ${truncated.length} chars)`);
|
|
819
|
+
/** Dispatch completion event for UI update — carries spawnKey so
|
|
820
|
+
* the frontend can mark the correct sidebar task as completed. */
|
|
821
|
+
events.safeDispatchCustomEvent(_enum.GraphEvents.ON_AGENT_TRANSITION, {
|
|
822
|
+
sourceAgentId: destination,
|
|
823
|
+
sourceAgentName: destName,
|
|
824
|
+
destinationAgentId: sourceAgentId,
|
|
825
|
+
destinationAgentName: this.agentContexts.get(sourceAgentId)?.name ??
|
|
826
|
+
sourceAgentId,
|
|
566
827
|
edgeType: _enum.EdgeType.HANDOFF,
|
|
567
828
|
timestamp: Date.now(),
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
`${truncatedResult.length < resultText.length ? `, truncated to ${truncatedResult.length}` : ''})`);
|
|
580
|
-
return truncatedResult;
|
|
829
|
+
isCompletion: true,
|
|
830
|
+
durationMs,
|
|
831
|
+
resultLength: truncated.length,
|
|
832
|
+
spawnKey,
|
|
833
|
+
spawnPath: childSpawnPath,
|
|
834
|
+
parentSpawnPath: parentSpawnPath || null,
|
|
835
|
+
spawnDepth: childDepth,
|
|
836
|
+
}, config).catch(() => {
|
|
837
|
+
/* best-effort event dispatch */
|
|
838
|
+
});
|
|
839
|
+
return truncated;
|
|
581
840
|
}
|
|
582
841
|
catch (err) {
|
|
583
|
-
const
|
|
584
|
-
|
|
585
|
-
|
|
842
|
+
const durationMs = Date.now() - spawnedAt;
|
|
843
|
+
const errMsg = err instanceof Error ? err.message : String(err);
|
|
844
|
+
// EPIPE from console.debug is non-fatal
|
|
845
|
+
if (errMsg.includes('EPIPE')) {
|
|
846
|
+
logging.mwarn(`[MultiAgentGraph] Child "${destination}" hit EPIPE (non-fatal) spawnKey=${spawnKey}`);
|
|
847
|
+
events.safeDispatchCustomEvent(_enum.GraphEvents.ON_AGENT_TRANSITION, {
|
|
848
|
+
sourceAgentId: destination,
|
|
849
|
+
sourceAgentName: destName,
|
|
850
|
+
destinationAgentId: sourceAgentId,
|
|
851
|
+
destinationAgentName: this.agentContexts.get(sourceAgentId)?.name ??
|
|
852
|
+
sourceAgentId,
|
|
853
|
+
edgeType: _enum.EdgeType.HANDOFF,
|
|
854
|
+
timestamp: Date.now(),
|
|
855
|
+
isCompletion: true,
|
|
856
|
+
durationMs,
|
|
857
|
+
spawnKey,
|
|
858
|
+
spawnPath: childSpawnPath,
|
|
859
|
+
parentSpawnPath: parentSpawnPath || null,
|
|
860
|
+
spawnDepth: childDepth,
|
|
861
|
+
}, config).catch(() => {
|
|
862
|
+
/* best-effort */
|
|
863
|
+
});
|
|
864
|
+
return `Agent "${destName}" completed but output was lost due to stream closure.`;
|
|
865
|
+
}
|
|
866
|
+
console.error(`[MultiAgentGraph] Handoff FAILED "${sourceAgentId}" -> "${destination}" ` +
|
|
867
|
+
`spawnKey=${spawnKey} (${durationMs}ms): ${errMsg}`);
|
|
868
|
+
events.safeDispatchCustomEvent(_enum.GraphEvents.ON_AGENT_TRANSITION, {
|
|
869
|
+
sourceAgentId: destination,
|
|
870
|
+
sourceAgentName: destName,
|
|
871
|
+
destinationAgentId: sourceAgentId,
|
|
872
|
+
destinationAgentName: this.agentContexts.get(sourceAgentId)?.name ??
|
|
873
|
+
sourceAgentId,
|
|
874
|
+
edgeType: _enum.EdgeType.HANDOFF,
|
|
875
|
+
timestamp: Date.now(),
|
|
876
|
+
isCompletion: true,
|
|
877
|
+
durationMs,
|
|
878
|
+
spawnKey,
|
|
879
|
+
spawnPath: childSpawnPath,
|
|
880
|
+
parentSpawnPath: parentSpawnPath || null,
|
|
881
|
+
spawnDepth: childDepth,
|
|
882
|
+
error: errMsg,
|
|
883
|
+
}, config).catch(() => {
|
|
884
|
+
/* best-effort */
|
|
885
|
+
});
|
|
886
|
+
return `Agent "${destName}" failed after ${durationMs}ms: ${errMsg}`;
|
|
586
887
|
}
|
|
587
888
|
}, {
|
|
588
889
|
name: toolName,
|
|
589
|
-
schema:
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
description: promptInputDescription,
|
|
596
|
-
},
|
|
890
|
+
schema: {
|
|
891
|
+
type: 'object',
|
|
892
|
+
properties: {
|
|
893
|
+
[promptKey]: {
|
|
894
|
+
type: 'string',
|
|
895
|
+
description: promptInputDescription,
|
|
597
896
|
},
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
897
|
+
},
|
|
898
|
+
required: [promptKey],
|
|
899
|
+
},
|
|
601
900
|
description: toolDescription,
|
|
602
901
|
}));
|
|
603
902
|
}
|
|
@@ -639,7 +938,7 @@ class MultiAgentGraph extends Graph.StandardGraph {
|
|
|
639
938
|
/**
|
|
640
939
|
* Truncate handoff result using head/tail strategy (60/40 split).
|
|
641
940
|
* Preserves the beginning (key findings) and end (conclusions).
|
|
642
|
-
* Matches the TaskTool.truncateResult pattern
|
|
941
|
+
* Matches the TaskTool.truncateResult pattern used by host orchestrators.
|
|
643
942
|
* @param result - The full result text
|
|
644
943
|
* @param maxChars - Maximum allowed characters
|
|
645
944
|
*/
|
|
@@ -675,8 +974,140 @@ class MultiAgentGraph extends Graph.StandardGraph {
|
|
|
675
974
|
* Create a complete agent subgraph (similar to createReactAgent)
|
|
676
975
|
*/
|
|
677
976
|
createAgentSubgraph(agentId) {
|
|
678
|
-
/**
|
|
679
|
-
|
|
977
|
+
/**
|
|
978
|
+
* Scoped subgraph build for handoff targets.
|
|
979
|
+
*
|
|
980
|
+
* If the handoff target has outgoing sequence/transfer edges (e.g. a
|
|
981
|
+
* "researcher" agent with its own sequence `[researcher → prod_assistant]`),
|
|
982
|
+
* we compile a mini-StateGraph containing the agent and all agents reachable
|
|
983
|
+
* from it via non-handoff edges. This way, when the parent hands off to
|
|
984
|
+
* researcher via `subgraph.invoke()`, the nested sequence runs to completion
|
|
985
|
+
* before the result is returned to the parent.
|
|
986
|
+
*
|
|
987
|
+
* Fast path: if no downstream agents are reachable, fall back to the
|
|
988
|
+
* previous single-node behavior (`createAgentNode`).
|
|
989
|
+
*
|
|
990
|
+
* See docs/multi-agent-nesting-architecture.md §6.
|
|
991
|
+
*/
|
|
992
|
+
const reachable = this.computeReachableViaNonHandoff(agentId);
|
|
993
|
+
if (reachable.size === 1) {
|
|
994
|
+
return this.createAgentNode(agentId);
|
|
995
|
+
}
|
|
996
|
+
logging.mlog(`[MultiAgentGraph] Scoped subgraph for "${agentId}": ${reachable.size} nodes [${Array.from(reachable).join(', ')}]`);
|
|
997
|
+
return this.buildScopedSubgraph(agentId, reachable);
|
|
998
|
+
}
|
|
999
|
+
/**
|
|
1000
|
+
* BFS from `rootAgentId` across sequence + transfer edges (NOT handoff edges).
|
|
1001
|
+
* Returns the set of agents reachable in this agent's "local workflow".
|
|
1002
|
+
*/
|
|
1003
|
+
computeReachableViaNonHandoff(rootAgentId) {
|
|
1004
|
+
const reachable = new Set([rootAgentId]);
|
|
1005
|
+
const queue = [rootAgentId];
|
|
1006
|
+
const localEdges = [...this.sequenceEdges, ...this.transferEdges];
|
|
1007
|
+
while (queue.length > 0) {
|
|
1008
|
+
const current = queue.shift();
|
|
1009
|
+
for (const edge of localEdges) {
|
|
1010
|
+
const sources = Array.isArray(edge.from) ? edge.from : [edge.from];
|
|
1011
|
+
if (!sources.includes(current))
|
|
1012
|
+
continue;
|
|
1013
|
+
const dests = Array.isArray(edge.to) ? edge.to : [edge.to];
|
|
1014
|
+
for (const dest of dests) {
|
|
1015
|
+
if (!reachable.has(dest) && this.agentContexts.has(dest)) {
|
|
1016
|
+
reachable.add(dest);
|
|
1017
|
+
queue.push(dest);
|
|
1018
|
+
}
|
|
1019
|
+
}
|
|
1020
|
+
}
|
|
1021
|
+
}
|
|
1022
|
+
return reachable;
|
|
1023
|
+
}
|
|
1024
|
+
/**
|
|
1025
|
+
* Build a compiled scoped StateGraph containing `agentIds` as nodes, rooted
|
|
1026
|
+
* at `rootAgentId`. Linear sequence edges where both endpoints are in scope
|
|
1027
|
+
* are wired directly; nodes with no outgoing in-scope edges route to END.
|
|
1028
|
+
*
|
|
1029
|
+
* Each node is wrapped around the per-agent `createAgentNode` compiled
|
|
1030
|
+
* workflow (agent + tools loop) to preserve isolated tool context.
|
|
1031
|
+
*/
|
|
1032
|
+
buildScopedSubgraph(rootAgentId, agentIds) {
|
|
1033
|
+
const StateAnnotation = langgraph.Annotation.Root({
|
|
1034
|
+
messages: langgraph.Annotation({
|
|
1035
|
+
reducer: langgraph.messagesStateReducer,
|
|
1036
|
+
default: () => [],
|
|
1037
|
+
}),
|
|
1038
|
+
});
|
|
1039
|
+
const builder = new langgraph.StateGraph(StateAnnotation);
|
|
1040
|
+
// Precompile each scoped agent's inner workflow and wrap as a node.
|
|
1041
|
+
//
|
|
1042
|
+
// Two different isolation strategies depending on position:
|
|
1043
|
+
//
|
|
1044
|
+
// • ROOT node (the handoff target itself): receives the parent
|
|
1045
|
+
// orchestrator's handoff frame. Use `prepareHandoffMessages` — drops
|
|
1046
|
+
// orphaned tool_use, compacts paired tool calls, guarantees trailing
|
|
1047
|
+
// HumanMessage for Bedrock/VertexAI compatibility. The root needs
|
|
1048
|
+
// orchestrator context because it's responding to the handoff.
|
|
1049
|
+
//
|
|
1050
|
+
// • DOWNSTREAM nodes (sequence targets of the root): run as FULLY
|
|
1051
|
+
// ISOLATED child sessions. They receive only:
|
|
1052
|
+
// [original user request, synthetic HumanMessage describing what
|
|
1053
|
+
// the upstream agent produced and asking them to act]
|
|
1054
|
+
// No raw tool_use / tool_result blocks from the upstream agent —
|
|
1055
|
+
// prevents schema confusion when a downstream agent sees noisy
|
|
1056
|
+
// upstream context and produces malformed tool_use JSON.
|
|
1057
|
+
//
|
|
1058
|
+
// Each wrapper returns only the DELTA (new messages produced by the
|
|
1059
|
+
// inner invoke), not the prepared input — otherwise messagesStateReducer
|
|
1060
|
+
// would double-append the synthetic instruction into the scoped state.
|
|
1061
|
+
for (const aid of agentIds) {
|
|
1062
|
+
const inner = this.createAgentNode(aid);
|
|
1063
|
+
const isRoot = aid === rootAgentId;
|
|
1064
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
1065
|
+
builder.addNode(aid, async (state, config) => {
|
|
1066
|
+
const prepared = isRoot
|
|
1067
|
+
? MultiAgentGraph.prepareHandoffMessages(state.messages)
|
|
1068
|
+
: MultiAgentGraph.prepareIsolatedChildMessages(state.messages);
|
|
1069
|
+
logging.mlog(`[MultiAgentGraph] scoped node "${aid}" entering (isRoot=${isRoot}, stateMessages=${state.messages.length}, prepared=${prepared.length})`);
|
|
1070
|
+
const result = await inner.invoke({ ...state, messages: prepared }, config);
|
|
1071
|
+
// Return only the messages the inner node appended beyond its input,
|
|
1072
|
+
// so messagesStateReducer doesn't duplicate the synthetic wrapper
|
|
1073
|
+
// prompt into the scoped state.
|
|
1074
|
+
const delta = result.messages.length > prepared.length
|
|
1075
|
+
? result.messages.slice(prepared.length)
|
|
1076
|
+
: result.messages;
|
|
1077
|
+
return { messages: delta };
|
|
1078
|
+
});
|
|
1079
|
+
}
|
|
1080
|
+
// START → root
|
|
1081
|
+
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
|
1082
|
+
// @ts-ignore — LangGraph string typing is too strict for dynamic agent ids
|
|
1083
|
+
builder.addEdge(langgraph.START, rootAgentId);
|
|
1084
|
+
// Wire sequence edges in scope (linear chain support)
|
|
1085
|
+
const hasOutgoing = new Set();
|
|
1086
|
+
for (const edge of this.sequenceEdges) {
|
|
1087
|
+
const sources = Array.isArray(edge.from) ? edge.from : [edge.from];
|
|
1088
|
+
const dests = Array.isArray(edge.to) ? edge.to : [edge.to];
|
|
1089
|
+
for (const source of sources) {
|
|
1090
|
+
if (!agentIds.has(source))
|
|
1091
|
+
continue;
|
|
1092
|
+
for (const dest of dests) {
|
|
1093
|
+
if (!agentIds.has(dest))
|
|
1094
|
+
continue;
|
|
1095
|
+
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
|
1096
|
+
// @ts-ignore
|
|
1097
|
+
builder.addEdge(source, dest);
|
|
1098
|
+
hasOutgoing.add(source);
|
|
1099
|
+
}
|
|
1100
|
+
}
|
|
1101
|
+
}
|
|
1102
|
+
// Leaves (no outgoing in-scope edges) route to END
|
|
1103
|
+
for (const aid of agentIds) {
|
|
1104
|
+
if (!hasOutgoing.has(aid)) {
|
|
1105
|
+
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
|
1106
|
+
// @ts-ignore
|
|
1107
|
+
builder.addEdge(aid, langgraph.END);
|
|
1108
|
+
}
|
|
1109
|
+
}
|
|
1110
|
+
return builder.compile(this.compileOptions);
|
|
680
1111
|
}
|
|
681
1112
|
/**
|
|
682
1113
|
* Detects if the current agent is receiving a handoff and processes the messages accordingly.
|
|
@@ -691,108 +1122,20 @@ class MultiAgentGraph extends Graph.StandardGraph {
|
|
|
691
1122
|
* @returns Object with filtered messages, extracted instructions, source agent, and parallel siblings
|
|
692
1123
|
*/
|
|
693
1124
|
/**
|
|
694
|
-
* Prepare messages for a handoff child agent.
|
|
695
|
-
*
|
|
696
|
-
*
|
|
697
|
-
*
|
|
698
|
-
* for the handoff tool itself, with no matching `tool_result`. Providers
|
|
699
|
-
* (Bedrock/Anthropic) reject this.
|
|
700
|
-
* 2. **Paired tool_use/tool_result in history**: The child may not have the same
|
|
701
|
-
* tools as the parent. Bedrock requires `toolConfig` when tool_use/tool_result
|
|
702
|
-
* blocks exist in the message history. Compacting these into text summaries
|
|
703
|
-
* avoids the requirement and reduces context bloat.
|
|
704
|
-
*
|
|
705
|
-
* Strategy:
|
|
706
|
-
* - Remove orphaned tool_use blocks (no matching tool_result)
|
|
707
|
-
* - Compact paired tool_use/tool_result interactions into text summaries
|
|
1125
|
+
* Prepare messages for a handoff child agent. See
|
|
1126
|
+
* {@link prepareHandoffMessagesUtil} for the full implementation and
|
|
1127
|
+
* semantics — this static method is a thin delegate preserved for
|
|
1128
|
+
* backward compatibility with existing call sites and unit tests.
|
|
708
1129
|
*/
|
|
709
|
-
static prepareHandoffMessages(messages
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
pairedToolCallIds.add(tm.tool_call_id);
|
|
719
|
-
}
|
|
720
|
-
}
|
|
721
|
-
}
|
|
722
|
-
/**
|
|
723
|
-
* Pass 1: Remove orphaned tool_use blocks (no matching tool_result).
|
|
724
|
-
* Also skip ToolMessages since we'll compact paired ones in pass 2.
|
|
725
|
-
*/
|
|
726
|
-
const cleaned = [];
|
|
727
|
-
for (const msg of messages$1) {
|
|
728
|
-
/** Skip all ToolMessages — paired ones will be compacted in pass 2 */
|
|
729
|
-
if (msg.getType() === 'tool') {
|
|
730
|
-
continue;
|
|
731
|
-
}
|
|
732
|
-
if (msg.getType() !== 'ai') {
|
|
733
|
-
cleaned.push(msg);
|
|
734
|
-
continue;
|
|
735
|
-
}
|
|
736
|
-
const aiMsg = msg;
|
|
737
|
-
const toolCalls = aiMsg.tool_calls ?? [];
|
|
738
|
-
if (toolCalls.length === 0) {
|
|
739
|
-
cleaned.push(msg);
|
|
740
|
-
continue;
|
|
741
|
-
}
|
|
742
|
-
/** Extract text content from the AI message */
|
|
743
|
-
const textContent = typeof aiMsg.content === 'string'
|
|
744
|
-
? aiMsg.content
|
|
745
|
-
: Array.isArray(aiMsg.content)
|
|
746
|
-
? aiMsg.content
|
|
747
|
-
.filter((b) => b.type === 'text' && 'text' in b)
|
|
748
|
-
.map((b) => b.text ?? '')
|
|
749
|
-
.join('\n')
|
|
750
|
-
: '';
|
|
751
|
-
/** Build text summaries of paired tool calls */
|
|
752
|
-
const toolSummaries = [];
|
|
753
|
-
for (const tc of toolCalls) {
|
|
754
|
-
if (tc.id != null && pairedToolCallIds.has(tc.id)) {
|
|
755
|
-
/** Find the matching ToolMessage result */
|
|
756
|
-
const toolResult = messages$1.find((m) => m.getType() === 'tool' && m.tool_call_id === tc.id);
|
|
757
|
-
const resultContent = toolResult
|
|
758
|
-
? typeof toolResult.content === 'string'
|
|
759
|
-
? toolResult.content.slice(0, 500)
|
|
760
|
-
: '[complex result]'
|
|
761
|
-
: '[no result]';
|
|
762
|
-
toolSummaries.push(`[Tool "${tc.name}": ${resultContent}]`);
|
|
763
|
-
}
|
|
764
|
-
// Orphaned tool_use blocks (no matching result) are silently dropped
|
|
765
|
-
}
|
|
766
|
-
/** Reconstruct as plain text AI message (no tool_calls) */
|
|
767
|
-
const parts = [textContent, ...toolSummaries].filter(Boolean);
|
|
768
|
-
if (parts.length > 0) {
|
|
769
|
-
cleaned.push(new messages.AIMessage({
|
|
770
|
-
content: parts.join('\n\n'),
|
|
771
|
-
id: aiMsg.id,
|
|
772
|
-
}));
|
|
773
|
-
}
|
|
774
|
-
}
|
|
775
|
-
/**
|
|
776
|
-
* Ensure messages end with a HumanMessage.
|
|
777
|
-
* After stripping tool artifacts, the last message may be an AIMessage
|
|
778
|
-
* (orchestrator's reasoning before the handoff). Some providers (Bedrock,
|
|
779
|
-
* Google/VertexAI) reject conversations ending with an assistant message.
|
|
780
|
-
* Convert the trailing AIMessage to a HumanMessage to preserve any useful
|
|
781
|
-
* context (e.g., compacted tool summaries) while satisfying the API requirement.
|
|
782
|
-
*/
|
|
783
|
-
if (cleaned.length > 0 && cleaned[cleaned.length - 1].getType() === 'ai') {
|
|
784
|
-
const lastAI = cleaned[cleaned.length - 1];
|
|
785
|
-
const content = typeof lastAI.content === 'string'
|
|
786
|
-
? lastAI.content
|
|
787
|
-
: '';
|
|
788
|
-
if (content.trim()) {
|
|
789
|
-
cleaned[cleaned.length - 1] = new messages.HumanMessage(`[Context from orchestrator]: ${content}`);
|
|
790
|
-
}
|
|
791
|
-
else {
|
|
792
|
-
cleaned.pop();
|
|
793
|
-
}
|
|
794
|
-
}
|
|
795
|
-
return cleaned;
|
|
1130
|
+
static prepareHandoffMessages(messages) {
|
|
1131
|
+
return childAgentContext.prepareHandoffMessages(messages);
|
|
1132
|
+
}
|
|
1133
|
+
/**
|
|
1134
|
+
* Build an isolated message context for a downstream scoped-subgraph
|
|
1135
|
+
* node. See {@link prepareIsolatedChildMessagesUtil} for details.
|
|
1136
|
+
*/
|
|
1137
|
+
static prepareIsolatedChildMessages(messages) {
|
|
1138
|
+
return childAgentContext.prepareIsolatedChildMessages(messages);
|
|
796
1139
|
}
|
|
797
1140
|
processTransferReception(messages$1, agentId) {
|
|
798
1141
|
if (messages$1.length === 0)
|
|
@@ -824,7 +1167,8 @@ class MultiAgentGraph extends Graph.StandardGraph {
|
|
|
824
1167
|
}
|
|
825
1168
|
else if (isConditionalTransfer) {
|
|
826
1169
|
const transferDest = candidateMsg.additional_kwargs.handoff_destination;
|
|
827
|
-
destinationAgent =
|
|
1170
|
+
destinationAgent =
|
|
1171
|
+
typeof transferDest === 'string' ? transferDest : null;
|
|
828
1172
|
}
|
|
829
1173
|
/** Check if this transfer targets our agent */
|
|
830
1174
|
if (destinationAgent === agentId) {
|
|
@@ -1065,8 +1409,35 @@ class MultiAgentGraph extends Graph.StandardGraph {
|
|
|
1065
1409
|
for (const startNode of this.startingNodes) {
|
|
1066
1410
|
handoffOnlyDestinations.delete(startNode);
|
|
1067
1411
|
}
|
|
1412
|
+
/**
|
|
1413
|
+
* Nested-sequence expansion: for each handoff-only target, its downstream
|
|
1414
|
+
* sequence/transfer agents MUST also become handoff-only — they exist only
|
|
1415
|
+
* inside the target's scoped subgraph, not at top level. Without this,
|
|
1416
|
+
* those downstream nodes would be added as top-level orphans and LangGraph
|
|
1417
|
+
* would fail compilation (UNREACHABLE_NODE).
|
|
1418
|
+
*
|
|
1419
|
+
* See docs/multi-agent-nesting-architecture.md §6.
|
|
1420
|
+
*/
|
|
1421
|
+
const nestedHandoffOnly = new Set();
|
|
1422
|
+
for (const target of handoffOnlyDestinations) {
|
|
1423
|
+
const reachable = this.computeReachableViaNonHandoff(target);
|
|
1424
|
+
for (const agent of reachable) {
|
|
1425
|
+
if (agent === target)
|
|
1426
|
+
continue;
|
|
1427
|
+
// Skip if this agent is legitimately a top-level starting node
|
|
1428
|
+
if (this.startingNodes.has(agent))
|
|
1429
|
+
continue;
|
|
1430
|
+
nestedHandoffOnly.add(agent);
|
|
1431
|
+
}
|
|
1432
|
+
}
|
|
1433
|
+
for (const agent of nestedHandoffOnly) {
|
|
1434
|
+
handoffOnlyDestinations.add(agent);
|
|
1435
|
+
}
|
|
1436
|
+
if (nestedHandoffOnly.size > 0) {
|
|
1437
|
+
logging.mlog(`[MultiAgentGraph] Nested handoff-only (scoped subgraph downstream): [${Array.from(nestedHandoffOnly).join(', ')}]`);
|
|
1438
|
+
}
|
|
1068
1439
|
if (handoffOnlyDestinations.size > 0) {
|
|
1069
|
-
|
|
1440
|
+
logging.mlog(`[MultiAgentGraph] Handoff-only children (subgraph only, no top-level node): [${Array.from(handoffOnlyDestinations).join(', ')}]`);
|
|
1070
1441
|
}
|
|
1071
1442
|
// Add agents as nodes — skip handoff-only children (they exist as subgraphs only)
|
|
1072
1443
|
for (const [agentId] of this.agentContexts) {
|
|
@@ -1115,7 +1486,7 @@ class MultiAgentGraph extends Graph.StandardGraph {
|
|
|
1115
1486
|
}
|
|
1116
1487
|
/** Wrapper function that handles agentMessages channel, handoff reception, and conditional routing */
|
|
1117
1488
|
const agentWrapper = async (state, config) => {
|
|
1118
|
-
|
|
1489
|
+
logging.mlog(`[MultiAgentGraph] Agent "${agentId}" wrapper ENTRY (messages: ${state.messages.length}, needsCommandRouting: ${needsCommandRouting})`);
|
|
1119
1490
|
let result;
|
|
1120
1491
|
/**
|
|
1121
1492
|
* Check if this agent is receiving a transfer.
|
|
@@ -1126,7 +1497,7 @@ class MultiAgentGraph extends Graph.StandardGraph {
|
|
|
1126
1497
|
const transferContext = this.processTransferReception(state.messages, agentId);
|
|
1127
1498
|
if (transferContext !== null) {
|
|
1128
1499
|
const { filteredMessages, instructions, sourceAgentName, parallelSiblings, } = transferContext;
|
|
1129
|
-
|
|
1500
|
+
logging.mlog(`[MultiAgentGraph] Agent "${agentId}" receiving transfer from "${sourceAgentName}" (instructions: ${instructions != null}, parallelSiblings: ${parallelSiblings.length})`);
|
|
1130
1501
|
/**
|
|
1131
1502
|
* Set handoff context on the receiving agent.
|
|
1132
1503
|
* Uses pre-computed graph position for depth and parallel info.
|
|
@@ -1242,7 +1613,7 @@ class MultiAgentGraph extends Graph.StandardGraph {
|
|
|
1242
1613
|
}
|
|
1243
1614
|
/** Track the last agent that produced output for continuation support */
|
|
1244
1615
|
this.lastActiveAgentId = agentId;
|
|
1245
|
-
|
|
1616
|
+
logging.mlog(`[MultiAgentGraph] Agent "${agentId}" wrapper EXIT (result messages: ${result.messages.length})`);
|
|
1246
1617
|
/** If agent has both transfer and sequence edges, use Command for exclusive routing */
|
|
1247
1618
|
if (needsCommandRouting) {
|
|
1248
1619
|
/** Check if a transfer occurred */
|
|
@@ -1253,7 +1624,7 @@ class MultiAgentGraph extends Graph.StandardGraph {
|
|
|
1253
1624
|
lastMessage.name.startsWith(_enum.Constants.LC_TRANSFER_TO_)) {
|
|
1254
1625
|
/** Transfer occurred - extract destination and navigate there exclusively */
|
|
1255
1626
|
const transferDest = lastMessage.name.replace(_enum.Constants.LC_TRANSFER_TO_, '');
|
|
1256
|
-
|
|
1627
|
+
logging.mlog(`[MultiAgentGraph] Command routing: "${agentId}" -> transfer to "${transferDest}" (sequence edges skipped: [${Array.from(sequenceDestinations).join(', ')}])`);
|
|
1257
1628
|
/** Validate destination agent exists */
|
|
1258
1629
|
if (!this.agentContexts.has(transferDest)) {
|
|
1259
1630
|
const availableAgents = Array.from(this.agentContexts.keys()).join(', ');
|
|
@@ -1281,7 +1652,7 @@ class MultiAgentGraph extends Graph.StandardGraph {
|
|
|
1281
1652
|
}
|
|
1282
1653
|
const receiverBudget = receiverContext.maxContextTokens;
|
|
1283
1654
|
if (currentSize > receiverBudget * 0.7) {
|
|
1284
|
-
|
|
1655
|
+
logging.mwarn(`[MultiAgentGraph] Pre-handoff compaction: context (${currentSize} tokens) exceeds ` +
|
|
1285
1656
|
`70% of receiver "${transferDest}" budget (${receiverBudget} tokens)`);
|
|
1286
1657
|
/** Generate handoff briefing */
|
|
1287
1658
|
const senderName = senderContext.name ?? agentId;
|
|
@@ -1346,7 +1717,7 @@ class MultiAgentGraph extends Graph.StandardGraph {
|
|
|
1346
1717
|
}
|
|
1347
1718
|
else {
|
|
1348
1719
|
/** No transfer - proceed with sequence edges */
|
|
1349
|
-
|
|
1720
|
+
logging.mlog(`[MultiAgentGraph] Command routing: "${agentId}" -> no transfer, following sequence edges: [${Array.from(sequenceDestinations).join(', ')}]`);
|
|
1350
1721
|
const directDests = Array.from(sequenceDestinations);
|
|
1351
1722
|
for (const dest of directDests) {
|
|
1352
1723
|
await events.safeDispatchCustomEvent(_enum.GraphEvents.ON_AGENT_TRANSITION, {
|
|
@@ -1373,7 +1744,30 @@ class MultiAgentGraph extends Graph.StandardGraph {
|
|
|
1373
1744
|
}
|
|
1374
1745
|
}
|
|
1375
1746
|
}
|
|
1376
|
-
/**
|
|
1747
|
+
/**
|
|
1748
|
+
* No Command routing needed — dispatch ON_AGENT_TRANSITION for all
|
|
1749
|
+
* destinations so callbacks.js can register child agents for event
|
|
1750
|
+
* isolation BEFORE they start streaming.
|
|
1751
|
+
*/
|
|
1752
|
+
const allDests = new Set([
|
|
1753
|
+
...transferDestinations,
|
|
1754
|
+
...sequenceDestinations,
|
|
1755
|
+
]);
|
|
1756
|
+
if (allDests.size > 0) {
|
|
1757
|
+
const edgeType = hasTransferEdges
|
|
1758
|
+
? _enum.EdgeType.TRANSFER
|
|
1759
|
+
: _enum.EdgeType.SEQUENCE;
|
|
1760
|
+
for (const dest of allDests) {
|
|
1761
|
+
await events.safeDispatchCustomEvent(_enum.GraphEvents.ON_AGENT_TRANSITION, {
|
|
1762
|
+
sourceAgentId: agentId,
|
|
1763
|
+
sourceAgentName: this.agentContexts.get(agentId)?.name ?? agentId,
|
|
1764
|
+
destinationAgentId: dest,
|
|
1765
|
+
destinationAgentName: this.agentContexts.get(dest)?.name ?? dest,
|
|
1766
|
+
edgeType,
|
|
1767
|
+
timestamp: Date.now(),
|
|
1768
|
+
}, config);
|
|
1769
|
+
}
|
|
1770
|
+
}
|
|
1377
1771
|
return result;
|
|
1378
1772
|
};
|
|
1379
1773
|
/** Wrapped agent as a node with its possible destinations */
|
|
@@ -1395,16 +1789,13 @@ class MultiAgentGraph extends Graph.StandardGraph {
|
|
|
1395
1789
|
this.agentContexts.has(this.resumeFromAgentId);
|
|
1396
1790
|
if (validResumeAgent) {
|
|
1397
1791
|
const resumeAgentId = this.resumeFromAgentId;
|
|
1398
|
-
|
|
1792
|
+
logging.mlog(`[MultiAgentGraph] Multi-turn resumption: routing START → "${resumeAgentId}" (skipping default starting nodes: [${Array.from(this.startingNodes).join(', ')}])`);
|
|
1399
1793
|
/**
|
|
1400
1794
|
* Build route map containing both the resume agent and default starting
|
|
1401
1795
|
* nodes. This is required by LangGraph — all possible destinations must
|
|
1402
1796
|
* be declared even if the router always picks one.
|
|
1403
1797
|
*/
|
|
1404
|
-
const allPossibleStarts = new Set([
|
|
1405
|
-
...this.startingNodes,
|
|
1406
|
-
resumeAgentId,
|
|
1407
|
-
]);
|
|
1798
|
+
const allPossibleStarts = new Set([...this.startingNodes, resumeAgentId]);
|
|
1408
1799
|
const routeMap = {};
|
|
1409
1800
|
for (const nodeId of allPossibleStarts) {
|
|
1410
1801
|
routeMap[nodeId] = nodeId;
|
|
@@ -1413,7 +1804,7 @@ class MultiAgentGraph extends Graph.StandardGraph {
|
|
|
1413
1804
|
}
|
|
1414
1805
|
else {
|
|
1415
1806
|
if (this.resumeFromAgentId != null) {
|
|
1416
|
-
|
|
1807
|
+
logging.mwarn(`[MultiAgentGraph] resumeFromAgentId "${this.resumeFromAgentId}" not found in graph — falling back to default starting nodes`);
|
|
1417
1808
|
}
|
|
1418
1809
|
for (const startNode of this.startingNodes) {
|
|
1419
1810
|
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
|
@@ -1477,8 +1868,19 @@ class MultiAgentGraph extends Graph.StandardGraph {
|
|
|
1477
1868
|
if (gatedEdges.has(edge)) {
|
|
1478
1869
|
continue;
|
|
1479
1870
|
}
|
|
1480
|
-
|
|
1481
|
-
|
|
1871
|
+
/**
|
|
1872
|
+
* Skip sequence edges where either endpoint lives only inside a scoped
|
|
1873
|
+
* handoff subgraph. Those edges are wired inside `buildScopedSubgraph`,
|
|
1874
|
+
* not at the top level — adding them here would reference non-existent
|
|
1875
|
+
* top-level nodes and fail compilation.
|
|
1876
|
+
*/
|
|
1877
|
+
const sources = Array.isArray(edge.from) ? edge.from : [edge.from];
|
|
1878
|
+
const dests = Array.isArray(edge.to) ? edge.to : [edge.to];
|
|
1879
|
+
const anyEndpointHandoffOnly = [...sources, ...dests].some((n) => handoffOnlyDestinations.has(n));
|
|
1880
|
+
if (anyEndpointHandoffOnly) {
|
|
1881
|
+
continue;
|
|
1882
|
+
}
|
|
1883
|
+
for (const destination of dests) {
|
|
1482
1884
|
if (!edgesByDestination.has(destination)) {
|
|
1483
1885
|
edgesByDestination.set(destination, []);
|
|
1484
1886
|
}
|
|
@@ -1575,7 +1977,8 @@ class MultiAgentGraph extends Graph.StandardGraph {
|
|
|
1575
1977
|
return eSources.includes(source);
|
|
1576
1978
|
});
|
|
1577
1979
|
/** Skip adding edge if source uses Command routing (has both types) */
|
|
1578
|
-
if (sourceTransferEdges.length > 0 &&
|
|
1980
|
+
if (sourceTransferEdges.length > 0 &&
|
|
1981
|
+
sourceSequenceEdges.length > 0) {
|
|
1579
1982
|
continue;
|
|
1580
1983
|
}
|
|
1581
1984
|
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|