Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

♻️ refactor: add builtin tools

arvinxx26e73cc4388d
diff --git a/src/store/chat/agents/GeneralChatAgent.ts b/packages/agent-runtime/src/agents/GeneralChatAgent.ts
similarity index 89%
rename from src/store/chat/agents/GeneralChatAgent.ts
rename to packages/agent-runtime/src/agents/GeneralChatAgent.ts
index 05fcf6eaae9..7f14d009587 100644
--- a/src/store/chat/agents/GeneralChatAgent.ts
+++ b/packages/agent-runtime/src/agents/GeneralChatAgent.ts
@@ -1,9 +1,11 @@
+import type { ChatToolPayload, HumanInterventionConfig } from '@lobechat/types';
+
+import { DEFAULT_SECURITY_BLACKLIST, InterventionChecker } from '../core';
import {
Agent,
AgentInstruction,
AgentRuntimeContext,
AgentState,
- DEFAULT_SECURITY_BLACKLIST,
GeneralAgentCallLLMInstructionPayload,
GeneralAgentCallLLMResultPayload,
GeneralAgentCallToolResultPayload,
@@ -11,9 +13,7 @@ import {
GeneralAgentCallingToolInstructionPayload,
GeneralAgentConfig,
HumanAbortPayload,
- InterventionChecker,
-} from '@lobechat/agent-runtime';
-import type { ChatToolPayload, HumanInterventionConfig } from '@lobechat/types';
+} from '../types';
/**
* ChatAgent - The "Brain" of the chat agent
@@ -94,13 +94,43 @@ export class GeneralChatAgent implements Agent {
continue;
}
- // Priority 1: User config is 'auto-run', all tools execute directly
+ // Priority 1: Check 'always' policy - overrides auto-run mode
+ // Some sensitive operations (e.g., installPlugin) must always require user confirmation
+ const config = this.getToolInterventionConfig(toolCalling, state);
+ const hasAlwaysPolicy =
+ config === 'always' ||
+ (Array.isArray(config) &&
+ config.some((rule) => {
+ // Check if the 'always' rule matches current tool args
+ if (rule.policy !== 'always') return false;
+ // If rule has match criteria, check if it matches
+ if (rule.match) {
+ return Object.entries(rule.match).every(([paramName, matcher]) => {
+ const paramValue = toolArgs[paramName];
+ if (paramValue === undefined) return false;
+ // Simple string comparison for basic matching
+ if (typeof matcher === 'string') {
+ return String(paramValue).includes(matcher) || matcher.includes('*');
+ }
+ return true;
+ });
+ }
+ // No match criteria means it's a default 'always' rule
+ return true;
+ }));
+
+ if (hasAlwaysPolicy) {
+ toolsNeedingIntervention.push(toolCalling);
+ continue;
+ }
+
+ // Priority 2: User config is 'auto-run', all tools execute directly
if (approvalMode === 'auto-run') {
toolsToExecute.push(toolCalling);
continue;
}
- // Priority 2: User config is 'allow-list', check if tool is in whitelist
+ // Priority 3: User config is 'allow-list', check if tool is in whitelist
if (approvalMode === 'allow-list') {
if (allowList.includes(toolKey)) {
toolsToExecute.push(toolCalling);
@@ -110,9 +140,8 @@ export class GeneralChatAgent implements Agent {
continue;
}
- // Priority 3: User config is 'manual' (default), use tool's own config
- const config = this.getToolInterventionConfig(toolCalling, state);
-
+ // Priority 4: User config is 'manual' (default), use tool's own config
+ // Note: config is already retrieved above for 'always' policy check
const policy = InterventionChecker.shouldIntervene({
config,
securityBlacklist,
diff --git a/src/store/chat/agents/__tests__/GeneralChatAgent.test.ts b/packages/agent-runtime/src/agents/__tests__/GeneralChatAgent.test.ts
similarity index 80%
rename from src/store/chat/agents/__tests__/GeneralChatAgent.test.ts
rename to packages/agent-runtime/src/agents/__tests__/GeneralChatAgent.test.ts
index 07da4a07765..2846773cf36 100644
--- a/src/store/chat/agents/__tests__/GeneralChatAgent.test.ts
+++ b/packages/agent-runtime/src/agents/__tests__/GeneralChatAgent.test.ts
@@ -1,7 +1,7 @@
-import { AgentRuntimeContext, AgentState } from '@lobechat/agent-runtime';
import { ChatToolPayload } from '@lobechat/types';
import { describe, expect, it } from 'vitest';
+import { AgentRuntimeContext, AgentState } from '../../types';
import { GeneralChatAgent } from '../GeneralChatAgent';
describe('GeneralChatAgent', () => {
@@ -11,7 +11,7 @@ describe('GeneralChatAgent', () => {
};
const createMockState = (overrides?: Partial<AgentState>): AgentState => ({
- sessionId: 'test-session',
+ operationId: 'test-session',
status: 'running',
messages: [],
toolManifestMap: {},
@@ -45,6 +45,7 @@ describe('GeneralChatAgent', () => {
phase,
payload,
session: {
+ // Note: AgentRuntimeContext.session uses sessionId for backward compatibility
sessionId: 'test-session',
messageCount: 0,
status: 'running',
@@ -56,7 +57,7 @@ describe('GeneralChatAgent', () => {
it('should return call_llm instruction for init phase', async () => {
const agent = new GeneralChatAgent({
agentConfig: { maxSteps: 100 },
- sessionId: 'test-session',
+ operationId: 'test-session',
modelRuntimeConfig: mockModelRuntimeConfig,
});
@@ -80,7 +81,7 @@ describe('GeneralChatAgent', () => {
it('should return call_llm instruction for user_input phase', async () => {
const agent = new GeneralChatAgent({
agentConfig: { maxSteps: 100 },
- sessionId: 'test-session',
+ operationId: 'test-session',
modelRuntimeConfig: mockModelRuntimeConfig,
});
@@ -107,7 +108,7 @@ describe('GeneralChatAgent', () => {
it('should return finish when no tool calls', async () => {
const agent = new GeneralChatAgent({
agentConfig: { maxSteps: 100 },
- sessionId: 'test-session',
+ operationId: 'test-session',
modelRuntimeConfig: mockModelRuntimeConfig,
});
@@ -130,7 +131,7 @@ describe('GeneralChatAgent', () => {
it('should return call_tool for single tool that does not need intervention', async () => {
const agent = new GeneralChatAgent({
agentConfig: { maxSteps: 100 },
- sessionId: 'test-session',
+ operationId: 'test-session',
modelRuntimeConfig: mockModelRuntimeConfig,
});
@@ -173,7 +174,7 @@ describe('GeneralChatAgent', () => {
it('should return call_tools_batch for multiple tools that do not need intervention', async () => {
const agent = new GeneralChatAgent({
agentConfig: { maxSteps: 100 },
- sessionId: 'test-session',
+ operationId: 'test-session',
modelRuntimeConfig: mockModelRuntimeConfig,
});
@@ -223,7 +224,7 @@ describe('GeneralChatAgent', () => {
it('should handle invalid JSON in tool arguments gracefully', async () => {
const agent = new GeneralChatAgent({
agentConfig: { maxSteps: 100 },
- sessionId: 'test-session',
+ operationId: 'test-session',
modelRuntimeConfig: mockModelRuntimeConfig,
});
@@ -267,7 +268,7 @@ describe('GeneralChatAgent', () => {
it('should return request_human_approve for tools requiring intervention', async () => {
const agent = new GeneralChatAgent({
agentConfig: { maxSteps: 100 },
- sessionId: 'test-session',
+ operationId: 'test-session',
modelRuntimeConfig: mockModelRuntimeConfig,
});
@@ -308,7 +309,7 @@ describe('GeneralChatAgent', () => {
it('should return both call_tools_batch and request_human_approve for mixed tools', async () => {
const agent = new GeneralChatAgent({
agentConfig: { maxSteps: 100 },
- sessionId: 'test-session',
+ operationId: 'test-session',
modelRuntimeConfig: mockModelRuntimeConfig,
});
@@ -370,7 +371,7 @@ describe('GeneralChatAgent', () => {
it('should return call_llm when no pending tools', async () => {
const agent = new GeneralChatAgent({
agentConfig: { maxSteps: 100 },
- sessionId: 'test-session',
+ operationId: 'test-session',
modelRuntimeConfig: mockModelRuntimeConfig,
});
@@ -404,7 +405,7 @@ describe('GeneralChatAgent', () => {
it('should return request_human_approve when there are pending tools', async () => {
const agent = new GeneralChatAgent({
agentConfig: { maxSteps: 100 },
- sessionId: 'test-session',
+ operationId: 'test-session',
modelRuntimeConfig: mockModelRuntimeConfig,
});
@@ -450,7 +451,7 @@ describe('GeneralChatAgent', () => {
it('should return call_llm when no pending tools', async () => {
const agent = new GeneralChatAgent({
agentConfig: { maxSteps: 100 },
- sessionId: 'test-session',
+ operationId: 'test-session',
modelRuntimeConfig: mockModelRuntimeConfig,
});
@@ -484,7 +485,7 @@ describe('GeneralChatAgent', () => {
it('should return request_human_approve when there are pending tools', async () => {
const agent = new GeneralChatAgent({
agentConfig: { maxSteps: 100 },
- sessionId: 'test-session',
+ operationId: 'test-session',
modelRuntimeConfig: mockModelRuntimeConfig,
});
@@ -531,7 +532,7 @@ describe('GeneralChatAgent', () => {
it('should return finish instruction with error details', async () => {
const agent = new GeneralChatAgent({
agentConfig: { maxSteps: 100 },
- sessionId: 'test-session',
+ operationId: 'test-session',
modelRuntimeConfig: mockModelRuntimeConfig,
});
@@ -553,7 +554,7 @@ describe('GeneralChatAgent', () => {
it('should handle error without message', async () => {
const agent = new GeneralChatAgent({
agentConfig: { maxSteps: 100 },
- sessionId: 'test-session',
+ operationId: 'test-session',
modelRuntimeConfig: mockModelRuntimeConfig,
});
@@ -574,7 +575,7 @@ describe('GeneralChatAgent', () => {
it('should handle abort at llm_result phase when state is interrupted', async () => {
const agent = new GeneralChatAgent({
agentConfig: { maxSteps: 100 },
- sessionId: 'test-session',
+ operationId: 'test-session',
modelRuntimeConfig: mockModelRuntimeConfig,
});
@@ -613,7 +614,7 @@ describe('GeneralChatAgent', () => {
it('should handle abort at tool_result phase when state is interrupted', async () => {
const agent = new GeneralChatAgent({
agentConfig: { maxSteps: 100 },
- sessionId: 'test-session',
+ operationId: 'test-session',
modelRuntimeConfig: mockModelRuntimeConfig,
});
@@ -663,7 +664,7 @@ describe('GeneralChatAgent', () => {
it('should return finish when state is interrupted with no tools', async () => {
const agent = new GeneralChatAgent({
agentConfig: { maxSteps: 100 },
- sessionId: 'test-session',
+ operationId: 'test-session',
modelRuntimeConfig: mockModelRuntimeConfig,
});
@@ -690,7 +691,7 @@ describe('GeneralChatAgent', () => {
it('should continue normal flow when state is not interrupted', async () => {
const agent = new GeneralChatAgent({
agentConfig: { maxSteps: 100 },
- sessionId: 'test-session',
+ operationId: 'test-session',
modelRuntimeConfig: mockModelRuntimeConfig,
});
@@ -733,7 +734,7 @@ describe('GeneralChatAgent', () => {
it('should handle abort at human_abort phase when state is interrupted', async () => {
const agent = new GeneralChatAgent({
agentConfig: { maxSteps: 100 },
- sessionId: 'test-session',
+ operationId: 'test-session',
modelRuntimeConfig: mockModelRuntimeConfig,
});
@@ -776,7 +777,7 @@ describe('GeneralChatAgent', () => {
it('should return resolve_aborted_tools when there are pending tool calls', async () => {
const agent = new GeneralChatAgent({
agentConfig: { maxSteps: 100 },
- sessionId: 'test-session',
+ operationId: 'test-session',
modelRuntimeConfig: mockModelRuntimeConfig,
});
@@ -820,7 +821,7 @@ describe('GeneralChatAgent', () => {
it('should return finish when there are no tool calls', async () => {
const agent = new GeneralChatAgent({
agentConfig: { maxSteps: 100 },
- sessionId: 'test-session',
+ operationId: 'test-session',
modelRuntimeConfig: mockModelRuntimeConfig,
});
@@ -845,7 +846,7 @@ describe('GeneralChatAgent', () => {
it('should return finish when toolsCalling is undefined', async () => {
const agent = new GeneralChatAgent({
agentConfig: { maxSteps: 100 },
- sessionId: 'test-session',
+ operationId: 'test-session',
modelRuntimeConfig: mockModelRuntimeConfig,
});
@@ -869,7 +870,7 @@ describe('GeneralChatAgent', () => {
it('should return finish when toolsCalling is empty array', async () => {
const agent = new GeneralChatAgent({
agentConfig: { maxSteps: 100 },
- sessionId: 'test-session',
+ operationId: 'test-session',
modelRuntimeConfig: mockModelRuntimeConfig,
});
@@ -896,7 +897,7 @@ describe('GeneralChatAgent', () => {
it('should return finish instruction for unknown phase', async () => {
const agent = new GeneralChatAgent({
agentConfig: { maxSteps: 100 },
- sessionId: 'test-session',
+ operationId: 'test-session',
modelRuntimeConfig: mockModelRuntimeConfig,
});
@@ -917,7 +918,7 @@ describe('GeneralChatAgent', () => {
it('should check intervention at API level when configured', async () => {
const agent = new GeneralChatAgent({
agentConfig: { maxSteps: 100 },
- sessionId: 'test-session',
+ operationId: 'test-session',
modelRuntimeConfig: mockModelRuntimeConfig,
});
@@ -971,7 +972,7 @@ describe('GeneralChatAgent', () => {
it('should execute all tools when user approvalMode is auto-run', async () => {
const agent = new GeneralChatAgent({
agentConfig: { maxSteps: 100 },
- sessionId: 'test-session',
+ operationId: 'test-session',
modelRuntimeConfig: mockModelRuntimeConfig,
});
@@ -1019,7 +1020,7 @@ describe('GeneralChatAgent', () => {
it('should respect allowList when approvalMode is allow-list', async () => {
const agent = new GeneralChatAgent({
agentConfig: { maxSteps: 100 },
- sessionId: 'test-session',
+ operationId: 'test-session',
modelRuntimeConfig: mockModelRuntimeConfig,
});
@@ -1080,7 +1081,7 @@ describe('GeneralChatAgent', () => {
it('should use tool config when approvalMode is manual', async () => {
const agent = new GeneralChatAgent({
agentConfig: { maxSteps: 100 },
- sessionId: 'test-session',
+ operationId: 'test-session',
modelRuntimeConfig: mockModelRuntimeConfig,
});
@@ -1140,5 +1141,224 @@ describe('GeneralChatAgent', () => {
},
]);
});
+
+ it('should always require intervention for tools with "always" policy even in auto-run mode', async () => {
+ const agent = new GeneralChatAgent({
+ agentConfig: { maxSteps: 100 },
+ operationId: 'test-session',
+ modelRuntimeConfig: mockModelRuntimeConfig,
+ });
+
+ const alwaysTool: ChatToolPayload = {
+ id: 'call-1',
+ identifier: 'agent-builder',
+ apiName: 'installPlugin',
+ arguments: '{"identifier":"some-plugin","source":"market"}',
+ type: 'builtin',
+ };
+
+ const state = createMockState({
+ toolManifestMap: {
+ 'agent-builder': {
+ identifier: 'agent-builder',
+ api: [
+ {
+ name: 'installPlugin',
+ humanIntervention: 'always', // Always requires intervention
+ },
+ ],
+ },
+ },
+ userInterventionConfig: {
+ approvalMode: 'auto-run', // User has auto-run enabled
+ allowList: [],
+ },
+ });
+
+ const context = createMockContext('llm_result', {
+ hasToolsCalling: true,
+ toolsCalling: [alwaysTool],
+ parentMessageId: 'msg-1',
+ });
+
+ const result = await agent.runner(context, state);
+
+ // Should still require approval despite auto-run mode
+ expect(result).toEqual([
+ {
+ type: 'request_human_approve',
+ pendingToolsCalling: [alwaysTool],
+ reason: 'human_intervention_required',
+ },
+ ]);
+ });
+
+ it('should always require intervention for tools with tool-level "always" policy', async () => {
+ const agent = new GeneralChatAgent({
+ agentConfig: { maxSteps: 100 },
+ operationId: 'test-session',
+ modelRuntimeConfig: mockModelRuntimeConfig,
+ });
+
+ const alwaysTool: ChatToolPayload = {
+ id: 'call-1',
+ identifier: 'sensitive-plugin',
+ apiName: 'sensitiveAction',
+ arguments: '{}',
+ type: 'default',
+ };
+
+ const state = createMockState({
+ toolManifestMap: {
+ 'sensitive-plugin': {
+ identifier: 'sensitive-plugin',
+ humanIntervention: 'always', // Tool-level always policy
+ },
+ },
+ userInterventionConfig: {
+ approvalMode: 'auto-run',
+ allowList: [],
+ },
+ });
+
+ const context = createMockContext('llm_result', {
+ hasToolsCalling: true,
+ toolsCalling: [alwaysTool],
+ parentMessageId: 'msg-1',
+ });
+
+ const result = await agent.runner(context, state);
+
+ // Should require approval despite auto-run mode
+ expect(result).toEqual([
+ {
+ type: 'request_human_approve',
+ pendingToolsCalling: [alwaysTool],
+ reason: 'human_intervention_required',
+ },
+ ]);
+ });
+
+ it('should handle mixed tools with "always" and regular policies in auto-run mode', async () => {
+ const agent = new GeneralChatAgent({
+ agentConfig: { maxSteps: 100 },
+ operationId: 'test-session',
+ modelRuntimeConfig: mockModelRuntimeConfig,
+ });
+
+ const regularTool: ChatToolPayload = {
+ id: 'call-1',
+ identifier: 'web-search',
+ apiName: 'search',
+ arguments: '{}',
+ type: 'default',
+ };
+
+ const alwaysTool: ChatToolPayload = {
+ id: 'call-2',
+ identifier: 'agent-builder',
+ apiName: 'installPlugin',
+ arguments: '{}',
+ type: 'builtin',
+ };
+
+ const state = createMockState({
+ toolManifestMap: {
+ 'web-search': {
+ identifier: 'web-search',
+ humanIntervention: 'required', // Would be bypassed by auto-run
+ },
+ 'agent-builder': {
+ identifier: 'agent-builder',
+ api: [
+ {
+ name: 'installPlugin',
+ humanIntervention: 'always', // Cannot be bypassed
+ },
+ ],
+ },
+ },
+ userInterventionConfig: {
+ approvalMode: 'auto-run',
+ allowList: [],
+ },
+ });
+
+ const context = createMockContext('llm_result', {
+ hasToolsCalling: true,
+ toolsCalling: [regularTool, alwaysTool],
+ parentMessageId: 'msg-1',
+ });
+
+ const result = await agent.runner(context, state);
+
+ // regularTool should execute (auto-run), alwaysTool should require approval
+ expect(result).toEqual([
+ {
+ type: 'call_tool',
+ payload: {
+ parentMessageId: 'msg-1',
+ toolCalling: regularTool,
+ },
+ },
+ {
+ type: 'request_human_approve',
+ pendingToolsCalling: [alwaysTool],
+ reason: 'human_intervention_required',
+ },
+ ]);
+ });
+
+ it('should handle "always" policy with rule-based configuration', async () => {
+ const agent = new GeneralChatAgent({
+ agentConfig: { maxSteps: 100 },
+ operationId: 'test-session',
+ modelRuntimeConfig: mockModelRuntimeConfig,
+ });
+
+ const toolCall: ChatToolPayload = {
+ id: 'call-1',
+ identifier: 'file-system',
+ apiName: 'writeFile',
+ arguments: '{"path":"/etc/passwd"}',
+ type: 'builtin',
+ };
+
+ const state = createMockState({
+ toolManifestMap: {
+ 'file-system': {
+ identifier: 'file-system',
+ api: [
+ {
+ name: 'writeFile',
+ // Rule-based config with 'always' policy
+ humanIntervention: [{ policy: 'always' }],
+ },
+ ],
+ },
+ },
+ userInterventionConfig: {
+ approvalMode: 'auto-run',
+ allowList: [],
+ },
+ });
+
+ const context = createMockContext('llm_result', {
+ hasToolsCalling: true,
+ toolsCalling: [toolCall],
+ parentMessageId: 'msg-1',
+ });
+
+ const result = await agent.runner(context, state);
+
+ // Should require approval due to 'always' rule
+ expect(result).toEqual([
+ {
+ type: 'request_human_approve',
+ pendingToolsCalling: [toolCall],
+ reason: 'human_intervention_required',
+ },
+ ]);
+ });
});
});
diff --git a/packages/agent-runtime/src/agents/index.ts b/packages/agent-runtime/src/agents/index.ts
new file mode 100644
index 00000000000..6a774928223
--- /dev/null
+++ b/packages/agent-runtime/src/agents/index.ts
@@ -0,0 +1 @@
+export * from './GeneralChatAgent';
diff --git a/packages/agent-runtime/src/core/__tests__/runtime.test.ts b/packages/agent-runtime/src/core/__tests__/runtime.test.ts
index 3274a421ddc..45cf781fea1 100644
--- a/packages/agent-runtime/src/core/__tests__/runtime.test.ts
+++ b/packages/agent-runtime/src/core/__tests__/runtime.test.ts
@@ -46,13 +46,14 @@ class MockAgent implements Agent {
function createTestContext(
phase: AgentRuntimeContext['phase'],
payload?: any,
- sessionId: string = 'test-session',
+ operationId: string = 'test-session',
): AgentRuntimeContext {
return {
phase,
payload,
session: {
- sessionId,
+ // Note: AgentRuntimeContext.session uses sessionId for backward compatibility
+ sessionId: operationId,
messageCount: 1,
status: 'idle',
stepCount: 0,
@@ -116,7 +117,7 @@ describe('AgentRuntime', () => {
};
const runtime = new AgentRuntime(agent);
- const state = AgentRuntime.createInitialState({ sessionId: 'test-session' });
+ const state = AgentRuntime.createInitialState({ operationId: 'test-session' });
const toolCall = {
id: 'call_123',
@@ -142,7 +143,7 @@ describe('AgentRuntime', () => {
const agent = new MockAgent();
const runtime = new AgentRuntime(agent);
const state = AgentRuntime.createInitialState({
- sessionId: 'test-session',
+ operationId: 'test-session',
messages: [{ role: 'user', content: 'Hello' }],
});
@@ -159,7 +160,7 @@ describe('AgentRuntime', () => {
agent.runner = vi.fn().mockImplementation(() => Promise.reject(new Error('Agent error')));
const runtime = new AgentRuntime(agent);
- const state = AgentRuntime.createInitialState({ sessionId: 'test-session' });
+ const state = AgentRuntime.createInitialState({ operationId: 'test-session' });
const result = await runtime.step(state);
@@ -179,7 +180,7 @@ describe('AgentRuntime', () => {
const agent = new MockAgent();
const runtime = new AgentRuntime(agent);
const state = AgentRuntime.createInitialState({
- sessionId: 'test-session',
+ operationId: 'test-session',
messages: [{ role: 'user', content: 'Hello' }],
});
@@ -204,7 +205,7 @@ describe('AgentRuntime', () => {
const runtime = new AgentRuntime(agent);
const state = AgentRuntime.createInitialState({
- sessionId: 'test-session',
+ operationId: 'test-session',
messages: [{ role: 'user', content: 'Hello' }],
});
@@ -252,7 +253,7 @@ describe('AgentRuntime', () => {
const runtime = new AgentRuntime(agent);
const state = AgentRuntime.createInitialState({
- sessionId: 'test-session',
+ operationId: 'test-session',
messages: [{ role: 'user', content: 'Hello' }],
});
@@ -286,7 +287,7 @@ describe('AgentRuntime', () => {
};
const runtime = new AgentRuntime(agent);
- const state = AgentRuntime.createInitialState({ sessionId: 'test-session' });
+ const state = AgentRuntime.createInitialState({ operationId: 'test-session' });
const toolCall = {
id: 'call_123',
@@ -317,7 +318,7 @@ describe('AgentRuntime', () => {
it('should throw error for unknown tool', async () => {
const agent = new MockAgent();
const runtime = new AgentRuntime(agent);
- const state = AgentRuntime.createInitialState({ sessionId: 'test-session' });
+ const state = AgentRuntime.createInitialState({ operationId: 'test-session' });
const toolCall = {
id: 'call_123',
@@ -356,14 +357,14 @@ describe('AgentRuntime', () => {
);
const runtime = new AgentRuntime(agent);
- const state = AgentRuntime.createInitialState({ sessionId: 'test-session' });
+ const state = AgentRuntime.createInitialState({ operationId: 'test-session' });
const result = await runtime.step(state);
expect(result.events).toHaveLength(1);
expect(result.events[0]).toMatchObject({
type: 'human_approve_required',
- sessionId: 'test-session',
+ operationId: 'test-session',
});
expect(result.newState.status).toBe('waiting_for_human');
@@ -381,7 +382,7 @@ describe('AgentRuntime', () => {
);
const runtime = new AgentRuntime(agent);
- const state = AgentRuntime.createInitialState({ sessionId: 'test-session' });
+ const state = AgentRuntime.createInitialState({ operationId: 'test-session' });
const result = await runtime.step(state);
@@ -390,7 +391,7 @@ describe('AgentRuntime', () => {
type: 'human_prompt_required',
prompt: 'Please provide input',
metadata: { key: 'value' },
- sessionId: 'test-session',
+ operationId: 'test-session',
});
expect(result.newState.status).toBe('waiting_for_human');
@@ -415,7 +416,7 @@ describe('AgentRuntime', () => {
);
const runtime = new AgentRuntime(agent);
- const state = AgentRuntime.createInitialState({ sessionId: 'test-session' });
+ const state = AgentRuntime.createInitialState({ operationId: 'test-session' });
const result = await runtime.step(state);
@@ -428,7 +429,7 @@ describe('AgentRuntime', () => {
{ label: 'Option 2', value: 'opt2' },
],
multi: false,
- sessionId: 'test-session',
+ operationId: 'test-session',
});
expect(result.newState.status).toBe('waiting_for_human');
@@ -447,7 +448,7 @@ describe('AgentRuntime', () => {
);
const runtime = new AgentRuntime(agent);
- const state = AgentRuntime.createInitialState({ sessionId: 'test-session' });
+ const state = AgentRuntime.createInitialState({ operationId: 'test-session' });
const result = await runtime.step(state);
@@ -468,10 +469,10 @@ describe('AgentRuntime', () => {
describe('createInitialState', () => {
it('should create initial state without message', () => {
- const state = AgentRuntime.createInitialState({ sessionId: 'test-session' });
+ const state = AgentRuntime.createInitialState({ operationId: 'test-session' });
expect(state).toMatchObject({
- sessionId: 'test-session',
+ operationId: 'test-session',
status: 'idle',
messages: [],
stepCount: 0,
@@ -482,7 +483,7 @@ describe('AgentRuntime', () => {
it('should create initial state with message', () => {
const state = AgentRuntime.createInitialState({
- sessionId: 'test-session',
+ operationId: 'test-session',
messages: [{ role: 'user', content: 'Hello world' }],
});
@@ -496,7 +497,7 @@ describe('AgentRuntime', () => {
it('should create initial state with custom stepCount', () => {
const state = AgentRuntime.createInitialState({
- sessionId: 'test-session',
+ operationId: 'test-session',
stepCount: 5,
});
@@ -505,7 +506,7 @@ describe('AgentRuntime', () => {
it('should create initial state with maxSteps limit', () => {
const state = AgentRuntime.createInitialState({
- sessionId: 'test-session',
+ operationId: 'test-session',
maxSteps: 10,
});
@@ -519,7 +520,7 @@ describe('AgentRuntime', () => {
const agent = new MockAgent();
const runtime = new AgentRuntime(agent);
- let state = AgentRuntime.createInitialState({ sessionId: 'test-session' });
+ let state = AgentRuntime.createInitialState({ operationId: 'test-session' });
expect(state.stepCount).toBe(0);
// First step
@@ -540,7 +541,7 @@ describe('AgentRuntime', () => {
const runtime = new AgentRuntime(agent);
const state = AgentRuntime.createInitialState({
- sessionId: 'test-session',
+ operationId: 'test-session',
maxSteps: 3, // 允许 3 步
});
@@ -580,7 +581,7 @@ describe('AgentRuntime', () => {
const runtime = new AgentRuntime(agent);
const state = AgentRuntime.createInitialState({
- sessionId: 'test-session',
+ operationId: 'test-session',
stepCount: 5, // Start with step 5
messages: [{ role: 'user', content: 'test' }],
});
@@ -606,7 +607,7 @@ describe('AgentRuntime', () => {
const runtime = new AgentRuntime(agent);
const state = AgentRuntime.createInitialState({
- sessionId: 'test-session',
+ operationId: 'test-session',
stepCount: 3,
});
@@ -638,7 +639,7 @@ describe('AgentRuntime', () => {
const runtime = new AgentRuntime(agent);
// Create interrupted state
- let state = AgentRuntime.createInitialState({ sessionId: 'test-session' });
+ let state = AgentRuntime.createInitialState({ operationId: 'test-session' });
const interruptResult = runtime.interrupt(state, 'Test interruption');
// Resume execution
@@ -659,7 +660,7 @@ describe('AgentRuntime', () => {
const agent = new MockAgent();
const runtime = new AgentRuntime(agent);
- let state = AgentRuntime.createInitialState({ sessionId: 'test-session' });
+ let state = AgentRuntime.createInitialState({ operationId: 'test-session' });
const interruptResult = runtime.interrupt(state, 'Fatal error', false);
await expect(runtime.resume(interruptResult.newState)).rejects.toThrow(
@@ -671,7 +672,7 @@ describe('AgentRuntime', () => {
const agent = new MockAgent();
const runtime = new AgentRuntime(agent);
- const state = AgentRuntime.createInitialState({ sessionId: 'test-session' });
+ const state = AgentRuntime.createInitialState({ operationId: 'test-session' });
await expect(runtime.resume(state)).rejects.toThrow(
'Cannot resume: state is not interrupted',
@@ -686,7 +687,7 @@ describe('AgentRuntime', () => {
const runtime = new AgentRuntime(agent);
let state = AgentRuntime.createInitialState({
- sessionId: 'test-session',
+ operationId: 'test-session',
messages: [{ role: 'user', content: 'Hello' }],
});
const interruptResult = runtime.interrupt(state, 'Test interruption');
@@ -695,6 +696,7 @@ describe('AgentRuntime', () => {
phase: 'user_input',
payload: { message: { role: 'user', content: 'Hello' } },
session: {
+ // Note: AgentRuntimeContext.session uses sessionId for backward compatibility
sessionId: 'test-session',
messageCount: 1,
status: 'interrupted',
@@ -720,7 +722,7 @@ describe('AgentRuntime', () => {
describe('Usage and Cost Tracking', () => {
it('should initialize with zero usage and cost', () => {
- const state = AgentRuntime.createInitialState({ sessionId: 'test-session' });
+ const state = AgentRuntime.createInitialState({ operationId: 'test-session' });
expect(state.usage).toMatchObject({
llm: {
@@ -816,7 +818,7 @@ describe('AgentRuntime', () => {
const runtime = new AgentRuntime(agent);
const state = AgentRuntime.createInitialState({
- sessionId: 'test-session',
+ operationId: 'test-session',
messages: [{ role: 'user', content: 'Hello' }],
});
@@ -864,7 +866,7 @@ describe('AgentRuntime', () => {
};
const state = AgentRuntime.createInitialState({
- sessionId: 'test-session',
+ operationId: 'test-session',
messages: [{ role: 'user', content: 'Hello' }],
costLimit,
});
@@ -909,7 +911,7 @@ describe('AgentRuntime', () => {
};
const state = AgentRuntime.createInitialState({
- sessionId: 'test-session',
+ operationId: 'test-session',
messages: [{ role: 'user', content: 'Hello' }],
costLimit,
});
@@ -1004,7 +1006,7 @@ describe('AgentRuntime', () => {
// Step 1: User asks question
let state = AgentRuntime.createInitialState({
- sessionId: 'test-session',
+ operationId: 'test-session',
messages: [{ role: 'user', content: "What's the weather in Beijing?" }],
});
let result = await runtime.step(state);
@@ -1105,7 +1107,7 @@ describe('AgentRuntime', () => {
const agent = new BatchToolAgent();
const runtime = new AgentRuntime(agent);
const state = AgentRuntime.createInitialState({
- sessionId: 'batch-test',
+ operationId: 'batch-test',
messages: [{ role: 'user', content: 'Execute tools' }],
});
@@ -1175,7 +1177,7 @@ describe('AgentRuntime', () => {
const agent = new ArrayReturnAgent();
const runtime = new AgentRuntime(agent);
const state = AgentRuntime.createInitialState({
- sessionId: 'array-test',
+ operationId: 'array-test',
messages: [{ role: 'user', content: 'Execute tools' }],
});
@@ -1238,7 +1240,7 @@ describe('AgentRuntime', () => {
const agent = new BlockingAgent();
const runtime = new AgentRuntime(agent);
const state = AgentRuntime.createInitialState({
- sessionId: 'blocking-test',
+ operationId: 'blocking-test',
messages: [{ role: 'user', content: 'Execute' }],
});
@@ -1319,7 +1321,7 @@ describe('AgentRuntime', () => {
const agent = new UsageTrackingAgent();
const runtime = new AgentRuntime(agent);
const state = AgentRuntime.createInitialState({
- sessionId: 'merge-test',
+ operationId: 'merge-test',
messages: [{ role: 'user', content: 'Execute' }],
});
@@ -1334,13 +1336,480 @@ describe('AgentRuntime', () => {
});
});
+ describe('Multi-Round Batch Tool Execution (LOBE-1657)', () => {
+ /**
+ * This test verifies the fix for LOBE-1657:
+ * When executing multiple rounds of batch tool calls, tool messages should not be duplicated.
+ *
+ * Root cause: The mergeToolResults method was extracting ALL tool messages from each result,
+ * but since each result.newState was cloned from baseState, it contained old tool messages
+ * that would get re-added.
+ *
+ * Fix: Track existing tool_call_ids and only merge NEW tool messages.
+ */
+ it('should not duplicate tool messages across multiple batch executions', async () => {
+ // Track execution order for debugging
+ const executionLog: string[] = [];
+
+ // Agent that simulates multi-round tool execution like the real scenario:
+ // Step 0: user_input -> call_llm
+ // Step 1: llm_result (has tools) -> call_tools_batch (2 tools)
+ // Step 2: tools_batch_result -> call_llm
+ // Step 3: llm_result (has tools) -> call_tools_batch (2 tools)
+ // Step 4: tools_batch_result -> call_llm -> finish
+ class MultiRoundBatchAgent implements Agent {
+ private roundCount = 0;
+
+ tools = {
+ search_tool: vi.fn().mockImplementation(async (args: { query: string }) => {
+ executionLog.push(`search_tool(${args.query})`);
+ return { result: `search result for ${args.query}` };
+ }),
+ crawl_tool: vi.fn().mockImplementation(async (args: { url: string }) => {
+ executionLog.push(`crawl_tool(${args.url})`);
+ return { content: `content from ${args.url}` };
+ }),
+ };
+
+ async runner(context: AgentRuntimeContext, state: AgentState) {
+ executionLog.push(`runner(${context.phase})`);
+
+ switch (context.phase) {
+ case 'user_input':
+ return { type: 'call_llm' as const, payload: { messages: state.messages } };
+
+ case 'llm_result': {
+ const llmPayload = context.payload as { result: any; hasToolCalls: boolean };
+ if (llmPayload.hasToolCalls) {
+ this.roundCount++;
+ // Convert tool_calls to batch instruction
+ const toolsCalling = llmPayload.result.tool_calls.map((tc: any) => ({
+ id: tc.id,
+ type: 'default' as const,
+ apiName: tc.function.name,
+ identifier: tc.function.name,
+ arguments: tc.function.arguments,
+ }));
+
+ return {
+ type: 'call_tools_batch' as const,
+ payload: {
+ parentMessageId: 'assistant-msg',
+ toolsCalling,
+ },
+ };
+ }
+ return { type: 'finish' as const, reason: 'completed' as const };
+ }
+
+ case 'tools_batch_result':
+ // After tools complete, call LLM again
+ return { type: 'call_llm' as const, payload: { messages: state.messages } };
+
+ default:
+ return { type: 'finish' as const, reason: 'completed' as const };
+ }
+ }
+
+ // Mock LLM that returns tool calls for first 2 rounds, then finishes
+ modelRuntime = async function* (this: MultiRoundBatchAgent, payload: any) {
+ const toolMessages = payload.messages.filter((m: any) => m.role === 'tool');
+ executionLog.push(`modelRuntime(tool_messages=${toolMessages.length})`);
+
+ if (this.roundCount < 2) {
+ // First 2 rounds: return tool calls
+ yield { content: `Round ${this.roundCount + 1}: I will use tools.` };
+ yield {
+ tool_calls: [
+ {
+ id: `call_search_${this.roundCount + 1}`,
+ type: 'function' as const,
+ function: {
+ name: 'search_tool',
+ arguments: JSON.stringify({ query: `query_${this.roundCount + 1}` }),
+ },
+ },
+ {
+ id: `call_crawl_${this.roundCount + 1}`,
+ type: 'function' as const,
+ function: {
+ name: 'crawl_tool',
+ arguments: JSON.stringify({ url: `url_${this.roundCount + 1}` }),
+ },
+ },
+ ],
+ };
+ } else {
+ // Third round: finish
+ yield { content: 'All done!' };
+ }
+ }.bind(this);
+ }
+
+ const agent = new MultiRoundBatchAgent();
+ const runtime = new AgentRuntime(agent);
+
+ // Start with user message
+ let state = AgentRuntime.createInitialState({
+ operationId: 'multi-round-test',
+ messages: [{ role: 'user', content: 'Please search and crawl some pages' }],
+ });
+
+ // Execute the full conversation flow
+ let result = await runtime.step(state); // Step 0: user_input -> call_llm
+ expect(result.newState.status).toBe('running');
+
+ // Process LLM result (has tool calls)
+ result = await runtime.step(result.newState, result.nextContext); // Step 1: llm_result -> call_tools_batch
+ expect(result.events.filter((e) => e.type === 'tool_result')).toHaveLength(2);
+
+ // First batch done - should have 2 tool messages
+ let toolMessages = result.newState.messages.filter((m) => m.role === 'tool');
+ expect(toolMessages).toHaveLength(2);
+ expect(toolMessages.map((m) => m.tool_call_id).sort()).toEqual([
+ 'call_crawl_1',
+ 'call_search_1',
+ ]);
+
+ // Continue with LLM
+ result = await runtime.step(result.newState, result.nextContext); // Step 2: tools_batch_result -> call_llm
+
+ // Process second LLM result (has tool calls)
+ result = await runtime.step(result.newState, result.nextContext); // Step 3: llm_result -> call_tools_batch
+ expect(result.events.filter((e) => e.type === 'tool_result')).toHaveLength(2);
+
+ // Second batch done - should have 4 tool messages total (NOT 6 or more due to duplicates)
+ toolMessages = result.newState.messages.filter((m) => m.role === 'tool');
+ expect(toolMessages).toHaveLength(4); // This was the bug: was 6+ due to duplicates
+
+ // Verify all tool_call_ids are unique
+ const toolCallIds = toolMessages.map((m) => m.tool_call_id);
+ const uniqueToolCallIds = [...new Set(toolCallIds)];
+ expect(toolCallIds).toHaveLength(uniqueToolCallIds.length); // No duplicates
+
+ // Verify expected tool_call_ids
+ expect(toolCallIds.sort()).toEqual([
+ 'call_crawl_1',
+ 'call_crawl_2',
+ 'call_search_1',
+ 'call_search_2',
+ ]);
+
+ // Continue to finish
+ result = await runtime.step(result.newState, result.nextContext); // Step 4: tools_batch_result -> call_llm
+ result = await runtime.step(result.newState, result.nextContext); // Step 5: llm_result -> finish
+
+ expect(result.newState.status).toBe('done');
+
+ // Final check: still 4 tool messages, no duplicates
+ toolMessages = result.newState.messages.filter((m) => m.role === 'tool');
+ expect(toolMessages).toHaveLength(4);
+ });
+
+ it('should handle mixed scenarios: existing tool messages + new batch execution', async () => {
+ // This tests a scenario where we execute two separate batch tool calls
+ // The second batch should not re-add the tool messages from the first batch
+ class TwoBatchAgent implements Agent {
+ private batchCount = 0;
+
+ tools = {
+ tool_a: vi.fn().mockResolvedValue({ result: 'a' }),
+ tool_b: vi.fn().mockResolvedValue({ result: 'b' }),
+ };
+
+ async runner(context: AgentRuntimeContext, _state: AgentState) {
+ if (context.phase === 'user_input' || context.phase === 'tools_batch_result') {
+ this.batchCount++;
+ if (this.batchCount === 1) {
+ // First batch
+ return {
+ type: 'call_tools_batch' as const,
+ payload: {
+ parentMessageId: 'msg',
+ toolsCalling: [
+ {
+ id: 'batch1_call_a',
+ type: 'default' as const,
+ apiName: 'tool_a',
+ identifier: 'tool_a',
+ arguments: '{}',
+ },
+ ],
+ },
+ };
+ } else if (this.batchCount === 2) {
+ // Second batch - should not duplicate first batch's tool messages
+ return {
+ type: 'call_tools_batch' as const,
+ payload: {
+ parentMessageId: 'msg',
+ toolsCalling: [
+ {
+ id: 'batch2_call_a',
+ type: 'default' as const,
+ apiName: 'tool_a',
+ identifier: 'tool_a',
+ arguments: '{}',
+ },
+ {
+ id: 'batch2_call_b',
+ type: 'default' as const,
+ apiName: 'tool_b',
+ identifier: 'tool_b',
+ arguments: '{}',
+ },
+ ],
+ },
+ };
+ }
+ }
+ return { type: 'finish' as const, reason: 'completed' as const };
+ }
+ }
+
+ const agent = new TwoBatchAgent();
+ const runtime = new AgentRuntime(agent);
+
+ const state = AgentRuntime.createInitialState({
+ operationId: 'two-batch-test',
+ messages: [{ role: 'user', content: 'test' }],
+ });
+
+ // First batch execution
+ let result = await runtime.step(state);
+ let toolMessages = result.newState.messages.filter((m) => m.role === 'tool');
+ expect(toolMessages).toHaveLength(1);
+ expect(toolMessages[0].tool_call_id).toBe('batch1_call_a');
+
+ // Second batch execution - should have 3 total (1 from first + 2 from second)
+ result = await runtime.step(result.newState, result.nextContext);
+ toolMessages = result.newState.messages.filter((m) => m.role === 'tool');
+ expect(toolMessages).toHaveLength(3);
+
+ // Verify no duplicates
+ const toolCallIds = toolMessages.map((m) => m.tool_call_id);
+ expect(new Set(toolCallIds).size).toBe(3);
+ expect(toolCallIds.sort()).toEqual(['batch1_call_a', 'batch2_call_a', 'batch2_call_b']);
+ });
+ });
+
+ describe('StepContext Passing', () => {
+ it('should pass stepContext to agent runner', async () => {
+ const agent = new MockAgent();
+ const runnerSpy = vi.spyOn(agent, 'runner');
+
+ const runtime = new AgentRuntime(agent);
+ const state = AgentRuntime.createInitialState({
+ operationId: 'test-session',
+ messages: [{ role: 'user', content: 'Hello' }],
+ });
+
+ const stepContext = {
+ todos: {
+ items: [
+ { text: 'Buy milk', completed: false },
+ { text: 'Call mom', completed: true },
+ ],
+ updatedAt: '2024-06-01T00:00:00.000Z',
+ },
+ };
+
+ const context: AgentRuntimeContext = {
+ phase: 'user_input',
+ payload: { message: { role: 'user', content: 'Hello' } },
+ session: {
+ sessionId: 'test-session',
+ messageCount: 1,
+ status: 'idle',
+ stepCount: 0,
+ },
+ stepContext,
+ };
+
+ await runtime.step(state, context);
+
+ // Verify agent runner received the stepContext
+ expect(runnerSpy).toHaveBeenCalledWith(
+ expect.objectContaining({
+ stepContext: expect.objectContaining({
+ todos: expect.objectContaining({
+ items: expect.arrayContaining([
+ expect.objectContaining({ text: 'Buy milk', completed: false }),
+ ]),
+ }),
+ }),
+ }),
+ expect.any(Object),
+ );
+ });
+
+ it('should pass stepContext to custom executors', async () => {
+ const customExecutor = vi.fn().mockResolvedValue({
+ events: [{ type: 'done', finalState: {}, reason: 'completed' }],
+ newState: { status: 'done' },
+ });
+
+ const agent = new MockAgent();
+ agent.runner = vi.fn().mockResolvedValue({
+ type: 'finish',
+ reason: 'completed',
+ });
+
+ const config: RuntimeConfig = {
+ executors: {
+ finish: customExecutor,
+ },
+ };
+
+ const runtime = new AgentRuntime(agent, config);
+ const state = AgentRuntime.createInitialState({ operationId: 'test-session' });
+
+ const stepContext = {
+ todos: {
+ items: [{ text: 'Task 1', completed: false }],
+ updatedAt: '2024-06-01T00:00:00.000Z',
+ },
+ };
+
+ const context: AgentRuntimeContext = {
+ phase: 'init',
+ session: {
+ sessionId: 'test-session',
+ messageCount: 0,
+ status: 'idle',
+ stepCount: 0,
+ },
+ stepContext,
+ };
+
+ await runtime.step(state, context);
+
+ // Verify custom executor received the context with stepContext
+ expect(customExecutor).toHaveBeenCalledWith(
+ expect.any(Object), // instruction
+ expect.any(Object), // state
+ expect.objectContaining({
+ stepContext: expect.objectContaining({
+ todos: expect.objectContaining({
+ items: expect.arrayContaining([expect.objectContaining({ text: 'Task 1' })]),
+ }),
+ }),
+ }),
+ );
+ });
+
+ it('should pass stepContext to batch tool execution', async () => {
+ const toolASpy = vi.fn().mockResolvedValue({ result: 'a' });
+ const toolBSpy = vi.fn().mockResolvedValue({ result: 'b' });
+
+ class BatchToolAgent implements Agent {
+ tools = {
+ tool_a: toolASpy,
+ tool_b: toolBSpy,
+ };
+
+ async runner(context: AgentRuntimeContext, _state: AgentState) {
+ if (context.phase === 'user_input') {
+ return {
+ type: 'call_tools_batch' as const,
+ payload: {
+ parentMessageId: 'msg',
+ toolsCalling: [
+ {
+ id: 'call_a',
+ type: 'default' as const,
+ apiName: 'tool_a',
+ identifier: 'tool_a',
+ arguments: '{}',
+ },
+ {
+ id: 'call_b',
+ type: 'default' as const,
+ apiName: 'tool_b',
+ identifier: 'tool_b',
+ arguments: '{}',
+ },
+ ],
+ },
+ };
+ }
+ return { type: 'finish' as const, reason: 'completed' as const };
+ }
+ }
+
+ const agent = new BatchToolAgent();
+ const runtime = new AgentRuntime(agent);
+ const state = AgentRuntime.createInitialState({
+ operationId: 'batch-test',
+ messages: [{ role: 'user', content: 'Execute tools' }],
+ });
+
+ const stepContext = {
+ todos: {
+ items: [{ text: 'Batch task', completed: false }],
+ updatedAt: '2024-06-01T00:00:00.000Z',
+ },
+ };
+
+ const context: AgentRuntimeContext = {
+ phase: 'user_input',
+ payload: { message: { role: 'user', content: 'Execute tools' } },
+ session: {
+ sessionId: 'batch-test',
+ messageCount: 1,
+ status: 'idle',
+ stepCount: 0,
+ },
+ stepContext,
+ };
+
+ const result = await runtime.step(state, context);
+
+ // Both tools should have been executed
+ expect(toolASpy).toHaveBeenCalled();
+ expect(toolBSpy).toHaveBeenCalled();
+
+ // nextContext should preserve stepContext-related phase info
+ expect(result.nextContext?.phase).toBe('tools_batch_result');
+ });
+
+ it('should handle undefined stepContext gracefully', async () => {
+ const agent = new MockAgent();
+ agent.runner = vi.fn().mockResolvedValue({
+ type: 'finish',
+ reason: 'completed',
+ });
+
+ const runtime = new AgentRuntime(agent);
+ const state = AgentRuntime.createInitialState({ operationId: 'test-session' });
+
+ // Context without stepContext
+ const context: AgentRuntimeContext = {
+ phase: 'init',
+ session: {
+ sessionId: 'test-session',
+ messageCount: 0,
+ status: 'idle',
+ stepCount: 0,
+ },
+ // No stepContext
+ };
+
+ const result = await runtime.step(state, context);
+
+ // Should complete without errors
+ expect(result.newState.status).toBe('done');
+ expect(result.events[0].type).toBe('done');
+ });
+ });
+
describe('Edge Cases and Error Handling', () => {
it('should handle unknown instruction type', async () => {
const agent = new MockAgent();
agent.runner = vi.fn().mockResolvedValue({ type: 'unknown_instruction_type' as any });
const runtime = new AgentRuntime(agent);
- const state = AgentRuntime.createInitialState({ sessionId: 'test-session' });
+ const state = AgentRuntime.createInitialState({ operationId: 'test-session' });
const result = await runtime.step(state);
@@ -1359,7 +1828,7 @@ describe('AgentRuntime', () => {
const runtime = new AgentRuntime(agent);
const state = AgentRuntime.createInitialState({
messages: [{ role: 'user', content: 'test' }],
- sessionId: 'test-session',
+ operationId: 'test-session',
});
const result = await runtime.step(state);
@@ -1401,7 +1870,7 @@ describe('AgentRuntime', () => {
const state = AgentRuntime.createInitialState({
costLimit,
messages: [{ role: 'user', content: 'test' }],
- sessionId: 'test-session',
+ operationId: 'test-session',
});
const result = await runtime.step(state);
@@ -1463,7 +1932,7 @@ describe('AgentRuntime', () => {
const state = AgentRuntime.createInitialState({
costLimit,
messages: [{ role: 'user', content: 'test' }],
- sessionId: 'test-session',
+ operationId: 'test-session',
});
const result = await runtime.step(state);
@@ -1536,7 +2005,7 @@ describe('AgentRuntime', () => {
const runtime = new AgentRuntime(agent);
const state = AgentRuntime.createInitialState({
messages: [{ role: 'user', content: 'Execute' }],
- sessionId: 'cost-merge-test',
+ operationId: 'cost-merge-test',
});
const result = await runtime.step(state);
@@ -1616,7 +2085,7 @@ describe('AgentRuntime', () => {
const runtime = new AgentRuntime(agent);
const state = AgentRuntime.createInitialState({
messages: [{ role: 'user', content: 'Execute' }],
- sessionId: 'usage-merge-test',
+ operationId: 'usage-merge-test',
});
const result = await runtime.step(state);
diff --git a/packages/agent-runtime/src/core/runtime.ts b/packages/agent-runtime/src/core/runtime.ts
index 3a70fc572c4..c7d00c9597a 100644
--- a/packages/agent-runtime/src/core/runtime.ts
+++ b/packages/agent-runtime/src/core/runtime.ts
@@ -170,13 +170,14 @@ export class AgentRuntime {
// Special handling for batch tool execution
if (instruction.type === 'call_tools_batch') {
- result = await this.executeToolsBatch(instruction as any, currentState);
+ result = await this.executeToolsBatch(instruction as any, currentState, runtimeContext);
} else {
const executor = this.executors[instruction.type as keyof typeof this.executors];
if (!executor) {
throw new Error(`No executor found for instruction type: ${instruction.type}`);
}
- result = await executor(instruction, currentState);
+ // Pass runtimeContext to executor so it can access stepContext
+ result = await executor(instruction, currentState, runtimeContext);
}
// Accumulate events
@@ -379,7 +380,7 @@ export class AgentRuntime {
* @returns Complete AgentState with defaults filled in
*/
static createInitialState(
- partialState?: Partial<AgentState> & { sessionId: string },
+ partialState?: Partial<AgentState> & { operationId: string },
): AgentState {
const now = new Date().toISOString();
@@ -394,7 +395,7 @@ export class AgentRuntime {
toolManifestMap: {},
usage: AgentRuntime.createDefaultUsage(),
// User provided values override defaults
- ...(partialState || { sessionId: '' }),
+ ...(partialState || { operationId: '' }),
};
}
@@ -570,8 +571,8 @@ export class AgentRuntime {
const events: AgentEvent[] = [
{
+ operationId: newState.operationId,
pendingToolsCalling,
- sessionId: newState.sessionId,
type: 'human_approve_required',
},
];
@@ -596,8 +597,8 @@ export class AgentRuntime {
const events: AgentEvent[] = [
{
metadata,
+ operationId: newState.operationId,
prompt,
- sessionId: newState.sessionId,
type: 'human_prompt_required',
},
];
@@ -623,9 +624,9 @@ export class AgentRuntime {
{
metadata,
multi,
+ operationId: newState.operationId,
options,
prompt,
- sessionId: newState.sessionId,
type: 'human_select_required',
},
];
@@ -663,6 +664,7 @@ export class AgentRuntime {
private async executeToolsBatch(
instruction: AgentInstructionCallToolsBatch,
baseState: AgentState,
+ context?: AgentRuntimeContext,
): Promise<{
events: AgentEvent[];
newState: AgentState;
@@ -678,6 +680,7 @@ export class AgentRuntime {
type: 'call_tool',
} as AgentInstructionCallTool,
structuredClone(baseState), // Each tool starts from the same base state
+ context, // Pass context to each tool call
),
);
@@ -707,9 +710,16 @@ export class AgentRuntime {
const allEvents: AgentEvent[] = [];
// Merge all tool messages in order
+ // Get the set of tool_call_ids that already exist in baseState to avoid duplicates
+ const existingToolCallIds = new Set(
+ baseState.messages.filter((m) => m.role === 'tool').map((m) => m.tool_call_id),
+ );
+
for (const result of results) {
- // Extract tool role messages
- const toolMessages = result.newState.messages.filter((m) => m.role === 'tool');
+ // Extract only NEW tool role messages (not already in baseState)
+ const toolMessages = result.newState.messages.filter(
+ (m) => m.role === 'tool' && !existingToolCallIds.has(m.tool_call_id),
+ );
newState.messages.push(...toolMessages);
// Merge events
@@ -836,11 +846,12 @@ export class AgentRuntime {
/**
* Create session context metadata - reusable helper
+ * Note: Uses sessionId in context for backwards compatibility with AgentRuntimeContext
*/
private createSessionContext(state: AgentState) {
return {
messageCount: state.messages.length,
- sessionId: state.sessionId,
+ sessionId: state.operationId,
status: state.status,
stepCount: state.stepCount,
};
diff --git a/packages/agent-runtime/src/groupOrchestration/GroupOrchestrationRuntime.ts b/packages/agent-runtime/src/groupOrchestration/GroupOrchestrationRuntime.ts
new file mode 100644
index 00000000000..95b6f8d4e02
--- /dev/null
+++ b/packages/agent-runtime/src/groupOrchestration/GroupOrchestrationRuntime.ts
@@ -0,0 +1,194 @@
+import type { AgentState } from '../types/state';
+import type {
+ ExecutorResult,
+ GroupOrchestrationExecutor,
+ GroupOrchestrationExecutorOutput,
+ GroupOrchestrationRuntimeConfig,
+ IGroupOrchestrationSupervisor,
+ SupervisorInstruction,
+} from './types';
+
+/**
+ * GroupOrchestrationRuntime - Specialized Runtime for Multi-Agent collaboration
+ *
+ * Architecture:
+ * - Supervisor (State Machine): Receives ExecutorResult → Returns SupervisorInstruction
+ * - Executor (Execution Layer): Receives SupervisorInstruction → Returns ExecutorResult
+ * - Runtime: Orchestrates the loop between Supervisor and Executor
+ *
+ * Flow:
+ * 1. Start with 'init' result
+ * 2. Supervisor decides next instruction based on result
+ * 3. Executor executes the instruction
+ * 4. Executor returns result
+ * 5. Repeat from step 2 until Supervisor returns 'finish' instruction
+ */
+export class GroupOrchestrationRuntime {
+ private executors: Partial<Record<SupervisorInstruction['type'], GroupOrchestrationExecutor>>;
+ private operationId?: string;
+ private getOperation?: GroupOrchestrationRuntimeConfig['getOperation'];
+
+ constructor(
+ private supervisor: IGroupOrchestrationSupervisor,
+ private config: GroupOrchestrationRuntimeConfig,
+ ) {
+ this.operationId = config.operationId;
+ this.getOperation = config.getOperation;
+ this.executors = config.executors;
+ }
+
+ /**
+ * Execute a single step of the orchestration loop
+ *
+ * @param state - Current agent state
+ * @param result - The result from the previous step (or 'init' for the first step)
+ * @returns The executor output containing new state and next result
+ */
+ async step(state: AgentState, result: ExecutorResult): Promise<GroupOrchestrationExecutorOutput> {
+ // 1. Increment step count
+ const newState = structuredClone(state);
+ newState.stepCount = (newState.stepCount || 0) + 1;
+ newState.lastModified = new Date().toISOString();
+
+ // 2. Check max steps limit
+ if (newState.maxSteps && newState.stepCount > newState.maxSteps) {
+ newState.status = 'done';
+ return {
+ events: [
+ {
+ reason: `Maximum steps exceeded: ${newState.maxSteps}`,
+ type: 'done',
+ },
+ ],
+ newState,
+ result: undefined,
+ };
+ }
+
+ // 3. Get instruction from supervisor based on result
+ const instruction = await this.supervisor.decide(result, newState);
+
+ // 4. Check if we should finish
+ if (instruction.type === 'finish') {
+ newState.status = 'done';
+ return {
+ events: [
+ {
+ reason: instruction.reason,
+ type: 'done',
+ },
+ ],
+ newState,
+ result: undefined,
+ };
+ }
+
+ // 5. Get executor for instruction type
+ const executor = this.executors[instruction.type];
+ if (!executor) {
+ throw new Error(`No executor found for instruction type: ${instruction.type}`);
+ }
+
+ // 6. Execute instruction
+ const executorOutput = await executor(instruction, newState);
+
+ // 7. Preserve step count and lastModified
+ executorOutput.newState.stepCount = newState.stepCount;
+ executorOutput.newState.lastModified = newState.lastModified;
+
+ return executorOutput;
+ }
+
+ /**
+ * Run the full orchestration loop until completion
+ *
+ * @param initialState - Initial agent state
+ * @param groupId - Optional group ID for the orchestration
+ * @returns Final agent state after orchestration completes
+ */
+ async run(initialState: AgentState, groupId?: string): Promise<AgentState> {
+ let state = initialState;
+ let result: ExecutorResult | undefined = {
+ payload: { groupId },
+ type: 'init',
+ };
+
+ while (result) {
+ const output = await this.step(state, result);
+ state = output.newState;
+ result = output.result;
+
+ // Check for abort
+ const abortController = this.getAbortController();
+ if (abortController?.signal.aborted) {
+ state.status = 'done';
+ break;
+ }
+ }
+
+ return state;
+ }
+
+ /**
+ * Get operation context
+ */
+ getContext(): Record<string, unknown> | undefined {
+ if (!this.operationId || !this.getOperation) {
+ return undefined;
+ }
+ return this.getOperation(this.operationId).context;
+ }
+
+ /**
+ * Get operation abort controller
+ */
+ getAbortController(): AbortController | undefined {
+ if (!this.operationId || !this.getOperation) {
+ return undefined;
+ }
+ return this.getOperation(this.operationId).abortController;
+ }
+
+ /**
+ * Create initial state for group orchestration
+ */
+ static createInitialState(
+ partialState?: Partial<AgentState> & { operationId: string },
+ ): AgentState {
+ const now = new Date().toISOString();
+ return {
+ cost: {
+ calculatedAt: now,
+ currency: 'USD',
+ llm: { byModel: [], currency: 'USD', total: 0 },
+ tools: { byTool: [], currency: 'USD', total: 0 },
+ total: 0,
+ },
+ createdAt: now,
+ lastModified: now,
+ messages: [],
+ status: 'idle',
+ stepCount: 0,
+ toolManifestMap: {},
+ usage: {
+ humanInteraction: {
+ approvalRequests: 0,
+ promptRequests: 0,
+ selectRequests: 0,
+ totalWaitingTimeMs: 0,
+ },
+ llm: {
+ apiCalls: 0,
+ processingTimeMs: 0,
+ tokens: { input: 0, output: 0, total: 0 },
+ },
+ tools: {
+ byTool: [],
+ totalCalls: 0,
+ totalTimeMs: 0,
+ },
+ },
+ ...(partialState || { operationId: '' }),
+ };
+ }
+}
diff --git a/packages/agent-runtime/src/groupOrchestration/GroupOrchestrationSupervisor.ts b/packages/agent-runtime/src/groupOrchestration/GroupOrchestrationSupervisor.ts
new file mode 100644
index 00000000000..8137f795ca6
--- /dev/null
+++ b/packages/agent-runtime/src/groupOrchestration/GroupOrchestrationSupervisor.ts
@@ -0,0 +1,153 @@
+import type { AgentState } from '../types/state';
+import type {
+ ExecutorResult,
+ IGroupOrchestrationSupervisor,
+ SupervisorInstruction,
+ SupervisorInstructionCallAgent,
+ SupervisorInstructionCallSupervisor,
+ SupervisorInstructionDelegate,
+ SupervisorInstructionExecAsyncTask,
+ SupervisorInstructionFinish,
+ SupervisorInstructionParallelCallAgents,
+} from './types';
+
+export interface GroupOrchestrationSupervisorConfig {
+ maxRounds: number;
+ supervisorAgentId: string;
+}
+
+/**
+ * GroupOrchestrationSupervisor - State machine for Multi-Agent Group Orchestration
+ *
+ * This is the "Brain" for Multi-Agent Group Orchestration.
+ * It receives ExecutorResults and decides the next SupervisorInstruction.
+ *
+ * Decision Logic:
+ * - init → call_supervisor (start the orchestration)
+ * - supervisor_decided(speak) → call_agent
+ * - supervisor_decided(broadcast) → parallel_call_agents
+ * - supervisor_decided(delegate) → delegate
+ * - supervisor_decided(execute_task) → exec_async_task
+ * - supervisor_decided(finish) → finish
+ * - agent_spoke / agents_broadcasted / task_completed / tasks_completed → call_supervisor OR finish
+ * - delegated → finish
+ */
+export class GroupOrchestrationSupervisor implements IGroupOrchestrationSupervisor {
+ private round = 0;
+ private skipCallSupervisor = false;
+
+ constructor(private config: GroupOrchestrationSupervisorConfig) {}
+
+ /**
+ * Decide the next instruction based on the executor result
+ */
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ async decide(result: ExecutorResult, _state: AgentState): Promise<SupervisorInstruction> {
+ switch (result.type) {
+ case 'init': {
+ this.round = 0;
+ this.skipCallSupervisor = false;
+ return {
+ payload: {
+ groupId: result.payload.groupId,
+ round: this.round,
+ supervisorAgentId: this.config.supervisorAgentId,
+ },
+ type: 'call_supervisor',
+ } as SupervisorInstructionCallSupervisor;
+ }
+
+ case 'supervisor_decided': {
+ const { decision, params, skipCallSupervisor } = result.payload;
+ this.skipCallSupervisor = skipCallSupervisor ?? false;
+
+ switch (decision) {
+ case 'speak': {
+ return {
+ payload: {
+ agentId: params.agentId as string,
+ instruction: params.instruction as string | undefined,
+ },
+ type: 'call_agent',
+ } as SupervisorInstructionCallAgent;
+ }
+
+ case 'broadcast': {
+ return {
+ payload: {
+ agentIds: params.agentIds as string[],
+ instruction: params.instruction as string | undefined,
+ toolMessageId: params.toolMessageId as string,
+ },
+ type: 'parallel_call_agents',
+ } as SupervisorInstructionParallelCallAgents;
+ }
+
+ case 'delegate': {
+ return {
+ payload: {
+ agentId: params.agentId as string,
+ reason: params.reason as string | undefined,
+ },
+ type: 'delegate',
+ } as SupervisorInstructionDelegate;
+ }
+
+ case 'execute_task': {
+ return {
+ payload: {
+ agentId: params.agentId as string,
+ task: params.task as string,
+ timeout: params.timeout as number | undefined,
+ toolMessageId: params.toolMessageId as string,
+ },
+ type: 'exec_async_task',
+ } as SupervisorInstructionExecAsyncTask;
+ }
+
+ case 'finish': {
+ return {
+ reason: (params.reason as string) || 'supervisor_finished',
+ type: 'finish',
+ } as SupervisorInstructionFinish;
+ }
+
+ default: {
+ return { reason: `unknown_decision: ${decision}`, type: 'finish' };
+ }
+ }
+ }
+
+ // These results all follow the same logic: check skip/maxRounds, then call_supervisor or finish
+ case 'agent_spoke':
+ case 'agents_broadcasted':
+ case 'task_completed':
+ case 'tasks_completed': {
+ if (this.skipCallSupervisor) {
+ return { reason: 'skip_call_supervisor', type: 'finish' };
+ }
+
+ this.round++;
+ if (this.round >= this.config.maxRounds) {
+ return { reason: 'max_rounds_exceeded', type: 'finish' };
+ }
+
+ return {
+ payload: {
+ round: this.round,
+ supervisorAgentId: this.config.supervisorAgentId,
+ },
+ type: 'call_supervisor',
+ } as SupervisorInstructionCallSupervisor;
+ }
+
+ case 'delegated': {
+ return { reason: `delegated_to_${result.payload.agentId}`, type: 'finish' };
+ }
+
+ default: {
+ return { reason: 'unknown_result_type', type: 'finish' };
+ }
+ }
+ }
+}
diff --git a/packages/agent-runtime/src/groupOrchestration/__tests__/GroupOrchestrationSupervisor.test.ts b/packages/agent-runtime/src/groupOrchestration/__tests__/GroupOrchestrationSupervisor.test.ts
new file mode 100644
index 00000000000..ca31979440d
--- /dev/null
+++ b/packages/agent-runtime/src/groupOrchestration/__tests__/GroupOrchestrationSupervisor.test.ts
@@ -0,0 +1,449 @@
+import { describe, expect, it } from 'vitest';
+
+import type { AgentState } from '../../types/state';
+import {
+ GroupOrchestrationSupervisor,
+ type GroupOrchestrationSupervisorConfig,
+} from '../GroupOrchestrationSupervisor';
+import type { ExecutorResult } from '../types';
+
+// Helper to create mock AgentState
+const createMockState = (): AgentState => ({
+ cost: {
+ calculatedAt: new Date().toISOString(),
+ currency: 'USD',
+ llm: { byModel: [], currency: 'USD', total: 0 },
+ tools: { byTool: [], currency: 'USD', total: 0 },
+ total: 0,
+ },
+ createdAt: new Date().toISOString(),
+ lastModified: new Date().toISOString(),
+ messages: [],
+ operationId: 'test-operation',
+ status: 'running',
+ stepCount: 0,
+ toolManifestMap: {},
+ usage: {
+ humanInteraction: {
+ approvalRequests: 0,
+ promptRequests: 0,
+ selectRequests: 0,
+ totalWaitingTimeMs: 0,
+ },
+ llm: { apiCalls: 0, processingTimeMs: 0, tokens: { input: 0, output: 0, total: 0 } },
+ tools: { byTool: [], totalCalls: 0, totalTimeMs: 0 },
+ },
+});
+
+describe('GroupOrchestrationSupervisor', () => {
+ const defaultConfig: GroupOrchestrationSupervisorConfig = {
+ maxRounds: 10,
+ supervisorAgentId: 'supervisor-agent-1',
+ };
+
+ describe('constructor', () => {
+ it('should create instance with config', () => {
+ const supervisor = new GroupOrchestrationSupervisor(defaultConfig);
+ expect(supervisor).toBeInstanceOf(GroupOrchestrationSupervisor);
+ });
+ });
+
+ describe('decide - init result', () => {
+ it('should return call_supervisor instruction on init', async () => {
+ const supervisor = new GroupOrchestrationSupervisor(defaultConfig);
+ const state = createMockState();
+
+ const result: ExecutorResult = {
+ type: 'init',
+ payload: { groupId: 'group-1' },
+ };
+
+ const instruction = await supervisor.decide(result, state);
+
+ expect(instruction).toEqual({
+ type: 'call_supervisor',
+ payload: {
+ groupId: 'group-1',
+ round: 0,
+ supervisorAgentId: 'supervisor-agent-1',
+ },
+ });
+ });
+ });
+
+ describe('decide - supervisor_decided result', () => {
+ it('should return call_agent instruction for speak decision', async () => {
+ const supervisor = new GroupOrchestrationSupervisor(defaultConfig);
+ const state = createMockState();
+
+ const result: ExecutorResult = {
+ type: 'supervisor_decided',
+ payload: {
+ decision: 'speak',
+ params: { agentId: 'agent-1', instruction: 'Please respond' },
+ skipCallSupervisor: false,
+ },
+ };
+
+ const instruction = await supervisor.decide(result, state);
+
+ expect(instruction).toEqual({
+ type: 'call_agent',
+ payload: {
+ agentId: 'agent-1',
+ instruction: 'Please respond',
+ },
+ });
+ });
+
+ it('should return parallel_call_agents instruction for broadcast decision', async () => {
+ const supervisor = new GroupOrchestrationSupervisor(defaultConfig);
+ const state = createMockState();
+
+ const result: ExecutorResult = {
+ type: 'supervisor_decided',
+ payload: {
+ decision: 'broadcast',
+ params: {
+ agentIds: ['agent-1', 'agent-2'],
+ instruction: 'Discuss',
+ toolMessageId: 'tool-msg-1',
+ },
+ skipCallSupervisor: false,
+ },
+ };
+
+ const instruction = await supervisor.decide(result, state);
+
+ expect(instruction).toEqual({
+ type: 'parallel_call_agents',
+ payload: {
+ agentIds: ['agent-1', 'agent-2'],
+ instruction: 'Discuss',
+ toolMessageId: 'tool-msg-1',
+ },
+ });
+ });
+
+ it('should return delegate instruction for delegate decision', async () => {
+ const supervisor = new GroupOrchestrationSupervisor(defaultConfig);
+ const state = createMockState();
+
+ const result: ExecutorResult = {
+ type: 'supervisor_decided',
+ payload: {
+ decision: 'delegate',
+ params: { agentId: 'specialist-agent', reason: 'Expert needed' },
+ skipCallSupervisor: false,
+ },
+ };
+
+ const instruction = await supervisor.decide(result, state);
+
+ expect(instruction).toEqual({
+ type: 'delegate',
+ payload: {
+ agentId: 'specialist-agent',
+ reason: 'Expert needed',
+ },
+ });
+ });
+
+ it('should return exec_async_task instruction for execute_task decision', async () => {
+ const supervisor = new GroupOrchestrationSupervisor(defaultConfig);
+ const state = createMockState();
+
+ const result: ExecutorResult = {
+ type: 'supervisor_decided',
+ payload: {
+ decision: 'execute_task',
+ params: {
+ agentId: 'agent-1',
+ task: 'Analyze data',
+ timeout: 30000,
+ toolMessageId: 'tool-msg-1',
+ },
+ skipCallSupervisor: false,
+ },
+ };
+
+ const instruction = await supervisor.decide(result, state);
+
+ expect(instruction).toEqual({
+ type: 'exec_async_task',
+ payload: {
+ agentId: 'agent-1',
+ task: 'Analyze data',
+ timeout: 30000,
+ toolMessageId: 'tool-msg-1',
+ },
+ });
+ });
+
+ it('should return finish instruction for finish decision', async () => {
+ const supervisor = new GroupOrchestrationSupervisor(defaultConfig);
+ const state = createMockState();
+
+ const result: ExecutorResult = {
+ type: 'supervisor_decided',
+ payload: {
+ decision: 'finish',
+ params: { reason: 'Task complete' },
+ skipCallSupervisor: false,
+ },
+ };
+
+ const instruction = await supervisor.decide(result, state);
+
+ expect(instruction).toEqual({
+ type: 'finish',
+ reason: 'Task complete',
+ });
+ });
+ });
+
+ describe('decide - agent_spoke result', () => {
+ it('should return call_supervisor instruction when skipCallSupervisor is false', async () => {
+ const supervisor = new GroupOrchestrationSupervisor(defaultConfig);
+ const state = createMockState();
+
+ // First, set up the supervisor state by processing a supervisor_decided result
+ await supervisor.decide(
+ {
+ type: 'supervisor_decided',
+ payload: {
+ decision: 'speak',
+ params: { agentId: 'agent-1' },
+ skipCallSupervisor: false,
+ },
+ },
+ state,
+ );
+
+ // Now process agent_spoke
+ const result: ExecutorResult = {
+ type: 'agent_spoke',
+ payload: { agentId: 'agent-1', completed: true },
+ };
+
+ const instruction = await supervisor.decide(result, state);
+
+ expect(instruction.type).toBe('call_supervisor');
+ expect((instruction as any).payload.round).toBe(1);
+ });
+
+ it('should return finish instruction when skipCallSupervisor is true', async () => {
+ const supervisor = new GroupOrchestrationSupervisor(defaultConfig);
+ const state = createMockState();
+
+ // Set up with skipCallSupervisor: true
+ await supervisor.decide(
+ {
+ type: 'supervisor_decided',
+ payload: {
+ decision: 'speak',
+ params: { agentId: 'agent-1' },
+ skipCallSupervisor: true,
+ },
+ },
+ state,
+ );
+
+ // Now process agent_spoke
+ const result: ExecutorResult = {
+ type: 'agent_spoke',
+ payload: { agentId: 'agent-1', completed: true },
+ };
+
+ const instruction = await supervisor.decide(result, state);
+
+ expect(instruction).toEqual({
+ type: 'finish',
+ reason: 'skip_call_supervisor',
+ });
+ });
+
+ it('should return finish instruction when max rounds exceeded', async () => {
+ const config: GroupOrchestrationSupervisorConfig = {
+ maxRounds: 2,
+ supervisorAgentId: 'supervisor-agent-1',
+ };
+ const supervisor = new GroupOrchestrationSupervisor(config);
+ const state = createMockState();
+
+ // Process two rounds
+ await supervisor.decide(
+ {
+ type: 'supervisor_decided',
+ payload: { decision: 'speak', params: { agentId: 'agent-1' }, skipCallSupervisor: false },
+ },
+ state,
+ );
+ await supervisor.decide(
+ { type: 'agent_spoke', payload: { agentId: 'agent-1', completed: true } },
+ state,
+ );
+
+ await supervisor.decide(
+ {
+ type: 'supervisor_decided',
+ payload: { decision: 'speak', params: { agentId: 'agent-1' }, skipCallSupervisor: false },
+ },
+ state,
+ );
+ const instruction = await supervisor.decide(
+ { type: 'agent_spoke', payload: { agentId: 'agent-1', completed: true } },
+ state,
+ );
+
+ expect(instruction).toEqual({
+ type: 'finish',
+ reason: 'max_rounds_exceeded',
+ });
+ });
+ });
+
+ describe('decide - agents_broadcasted result', () => {
+ it('should return call_supervisor instruction when skipCallSupervisor is false', async () => {
+ const supervisor = new GroupOrchestrationSupervisor(defaultConfig);
+ const state = createMockState();
+
+ // Set up with skipCallSupervisor: false
+ await supervisor.decide(
+ {
+ type: 'supervisor_decided',
+ payload: {
+ decision: 'broadcast',
+ params: { agentIds: ['agent-1', 'agent-2'], toolMessageId: 'tool-1' },
+ skipCallSupervisor: false,
+ },
+ },
+ state,
+ );
+
+ const result: ExecutorResult = {
+ type: 'agents_broadcasted',
+ payload: { agentIds: ['agent-1', 'agent-2'], completed: true },
+ };
+
+ const instruction = await supervisor.decide(result, state);
+
+ expect(instruction.type).toBe('call_supervisor');
+ });
+
+ it('should return finish instruction when skipCallSupervisor is true', async () => {
+ const supervisor = new GroupOrchestrationSupervisor(defaultConfig);
+ const state = createMockState();
+
+ // Set up with skipCallSupervisor: true
+ await supervisor.decide(
+ {
+ type: 'supervisor_decided',
+ payload: {
+ decision: 'broadcast',
+ params: { agentIds: ['agent-1', 'agent-2'], toolMessageId: 'tool-1' },
+ skipCallSupervisor: true,
+ },
+ },
+ state,
+ );
+
+ const result: ExecutorResult = {
+ type: 'agents_broadcasted',
+ payload: { agentIds: ['agent-1', 'agent-2'], completed: true },
+ };
+
+ const instruction = await supervisor.decide(result, state);
+
+ expect(instruction).toEqual({
+ type: 'finish',
+ reason: 'skip_call_supervisor',
+ });
+ });
+ });
+
+ describe('decide - task_completed result', () => {
+ it('should return call_supervisor instruction when skipCallSupervisor is false', async () => {
+ const supervisor = new GroupOrchestrationSupervisor(defaultConfig);
+ const state = createMockState();
+
+ // Set up with skipCallSupervisor: false
+ await supervisor.decide(
+ {
+ type: 'supervisor_decided',
+ payload: {
+ decision: 'execute_task',
+ params: { agentId: 'agent-1', task: 'Do something', toolMessageId: 'tool-1' },
+ skipCallSupervisor: false,
+ },
+ },
+ state,
+ );
+
+ const result: ExecutorResult = {
+ type: 'task_completed',
+ payload: { agentId: 'agent-1', success: true },
+ };
+
+ const instruction = await supervisor.decide(result, state);
+
+ expect(instruction.type).toBe('call_supervisor');
+ });
+ });
+
+ describe('decide - delegated result', () => {
+ it('should always return finish instruction', async () => {
+ const supervisor = new GroupOrchestrationSupervisor(defaultConfig);
+ const state = createMockState();
+
+ const result: ExecutorResult = {
+ type: 'delegated',
+ payload: { agentId: 'specialist-agent', completed: true },
+ };
+
+ const instruction = await supervisor.decide(result, state);
+
+ expect(instruction).toEqual({
+ type: 'finish',
+ reason: 'delegated_to_specialist-agent',
+ });
+ });
+ });
+
+ describe('decide - unknown result type', () => {
+ it('should return finish instruction with unknown_result_type reason', async () => {
+ const supervisor = new GroupOrchestrationSupervisor(defaultConfig);
+ const state = createMockState();
+
+ const result = { type: 'unknown_type', payload: {} } as any;
+
+ const instruction = await supervisor.decide(result, state);
+
+ expect(instruction).toEqual({
+ type: 'finish',
+ reason: 'unknown_result_type',
+ });
+ });
+ });
+
+ describe('IGroupOrchestrationSupervisor interface compliance', () => {
+ it('should implement decide method that returns Promise<SupervisorInstruction>', async () => {
+ const supervisor = new GroupOrchestrationSupervisor(defaultConfig);
+ const state = createMockState();
+
+ const result: ExecutorResult = {
+ type: 'init',
+ payload: { groupId: 'g1' },
+ };
+
+ const promise = supervisor.decide(result, state);
+
+ // Should return a Promise
+ expect(promise).toBeInstanceOf(Promise);
+
+ // Should resolve to an instruction
+ const instruction = await promise;
+ expect(instruction).toHaveProperty('type');
+ });
+ });
+});
diff --git a/packages/agent-runtime/src/groupOrchestration/index.ts b/packages/agent-runtime/src/groupOrchestration/index.ts
new file mode 100644
index 00000000000..8fe83fb0f9c
--- /dev/null
+++ b/packages/agent-runtime/src/groupOrchestration/index.ts
@@ -0,0 +1,6 @@
+export { GroupOrchestrationRuntime } from './GroupOrchestrationRuntime';
+export {
+ GroupOrchestrationSupervisor,
+ type GroupOrchestrationSupervisorConfig,
+} from './GroupOrchestrationSupervisor';
+export * from './types';
diff --git a/packages/agent-runtime/src/groupOrchestration/types.ts b/packages/agent-runtime/src/groupOrchestration/types.ts
new file mode 100644
index 00000000000..e2c18ebac8b
--- /dev/null
+++ b/packages/agent-runtime/src/groupOrchestration/types.ts
@@ -0,0 +1,354 @@
+import type { AgentState } from '../types/state';
+
+// ==================== Supervisor Instructions (Output) ====================
+// These are the commands that the Supervisor decides to execute
+
+/**
+ * Instruction to call the supervisor agent to make a decision
+ */
+export interface SupervisorInstructionCallSupervisor {
+ payload: {
+ groupId?: string;
+ round: number;
+ supervisorAgentId: string;
+ };
+ type: 'call_supervisor';
+}
+
+/**
+ * Instruction to call a single agent to respond
+ */
+export interface SupervisorInstructionCallAgent {
+ payload: {
+ agentId: string;
+ instruction?: string;
+ };
+ type: 'call_agent';
+}
+
+/**
+ * Instruction to call multiple agents in parallel (broadcast)
+ */
+export interface SupervisorInstructionParallelCallAgents {
+ payload: {
+ agentIds: string[];
+ instruction?: string;
+ /**
+ * The tool message ID that triggered the broadcast
+ * Used as parentId for agent responses to build correct message tree
+ */
+ toolMessageId: string;
+ };
+ type: 'parallel_call_agents';
+}
+
+/**
+ * Instruction to execute an async task for an agent
+ */
+export interface SupervisorInstructionExecAsyncTask {
+ payload: {
+ agentId: string;
+ task: string;
+ timeout?: number;
+ toolMessageId: string;
+ };
+ type: 'exec_async_task';
+}
+
+/**
+ * Instruction to execute multiple async tasks in parallel
+ */
+export interface SupervisorInstructionBatchExecAsyncTasks {
+ payload: {
+ tasks: Array<{
+ agentId: string;
+ task: string;
+ timeout?: number;
+ }>;
+ toolMessageId: string;
+ };
+ type: 'batch_exec_async_tasks';
+}
+
+/**
+ * Instruction to delegate control to another agent
+ */
+export interface SupervisorInstructionDelegate {
+ payload: {
+ agentId: string;
+ reason?: string;
+ };
+ type: 'delegate';
+}
+
+/**
+ * Instruction to end the orchestration loop
+ */
+export interface SupervisorInstructionFinish {
+ reason: string;
+ type: 'finish';
+}
+
+/**
+ * Union type of all Supervisor Instructions
+ */
+export type SupervisorInstruction =
+ | SupervisorInstructionCallSupervisor
+ | SupervisorInstructionCallAgent
+ | SupervisorInstructionParallelCallAgents
+ | SupervisorInstructionExecAsyncTask
+ | SupervisorInstructionBatchExecAsyncTasks
+ | SupervisorInstructionDelegate
+ | SupervisorInstructionFinish;
+
+// ==================== Executor Results (Input to Supervisor) ====================
+// These are the outcomes that Executors report back
+
+/**
+ * Result when supervisor made a decision (called a tool like speak/broadcast/delegate)
+ */
+export interface ExecutorResultSupervisorDecided {
+ payload: {
+ /**
+ * The decision made by the supervisor
+ * - 'speak': Call a single agent
+ * - 'broadcast': Call multiple agents in parallel
+ * - 'delegate': Delegate to another agent
+ * - 'execute_task': Execute an async task
+ * - 'finish': End the orchestration
+ */
+ decision: 'speak' | 'broadcast' | 'delegate' | 'execute_task' | 'finish';
+ /**
+ * Parameters for the decision
+ */
+ params: Record<string, unknown>;
+ /**
+ * If true, the orchestration will end after the action completes,
+ * without calling the supervisor again.
+ */
+ skipCallSupervisor?: boolean;
+ };
+ type: 'supervisor_decided';
+}
+
+/**
+ * Result when a single agent has finished responding
+ */
+export interface ExecutorResultAgentSpoke {
+ payload: {
+ agentId: string;
+ /**
+ * Whether the agent response completed successfully
+ */
+ completed: boolean;
+ };
+ type: 'agent_spoke';
+}
+
+/**
+ * Result when all parallel agents have finished responding
+ */
+export interface ExecutorResultAgentsBroadcasted {
+ payload: {
+ agentIds: string[];
+ /**
+ * Whether all agent responses completed successfully
+ */
+ completed: boolean;
+ };
+ type: 'agents_broadcasted';
+}
+
+/**
+ * Result when an async task has completed
+ */
+export interface ExecutorResultTaskCompleted {
+ payload: {
+ agentId: string;
+ error?: string;
+ result?: string;
+ /**
+ * Whether the task completed successfully
+ */
+ success: boolean;
+ };
+ type: 'task_completed';
+}
+
+/**
+ * Result when all batch async tasks have completed
+ */
+export interface ExecutorResultTasksCompleted {
+ payload: {
+ results: Array<{
+ agentId: string;
+ error?: string;
+ result?: string;
+ success: boolean;
+ }>;
+ };
+ type: 'tasks_completed';
+}
+
+/**
+ * Result when delegation completed
+ */
+export interface ExecutorResultDelegated {
+ payload: {
+ agentId: string;
+ completed: boolean;
+ };
+ type: 'delegated';
+}
+
+/**
+ * Initial result to start the orchestration loop
+ */
+export interface ExecutorResultInit {
+ payload: {
+ groupId?: string;
+ };
+ type: 'init';
+}
+
+/**
+ * Union type of all Executor Results
+ */
+export type ExecutorResult =
+ | ExecutorResultInit
+ | ExecutorResultSupervisorDecided
+ | ExecutorResultAgentSpoke
+ | ExecutorResultAgentsBroadcasted
+ | ExecutorResultTaskCompleted
+ | ExecutorResultTasksCompleted
+ | ExecutorResultDelegated;
+
+// ==================== Runtime Types ====================
+
+/**
+ * Group Orchestration Executor Output
+ * Contains the execution result and next context for the runtime loop
+ */
+export interface GroupOrchestrationExecutorOutput {
+ /**
+ * Events that occurred during execution
+ */
+ events: GroupOrchestrationEvent[];
+ /**
+ * Updated state after execution
+ */
+ newState: AgentState;
+ /**
+ * The result to be passed to the Supervisor for the next decision
+ * If undefined, the orchestration loop should end
+ */
+ result?: ExecutorResult;
+}
+
+/**
+ * Group Orchestration Executor Type
+ * Receives a SupervisorInstruction and returns an ExecutorResult
+ */
+export type GroupOrchestrationExecutor = (
+ instruction: SupervisorInstruction,
+ state: AgentState,
+) => Promise<GroupOrchestrationExecutorOutput>;
+
+/**
+ * Group Orchestration Supervisor Interface
+ * Receives an ExecutorResult and returns a SupervisorInstruction
+ */
+export interface IGroupOrchestrationSupervisor {
+ /**
+ * Decide the next instruction based on the executor result
+ * @param result - The result from the last executor
+ * @param state - Current agent state
+ * @returns The next instruction to execute
+ */
+ decide(result: ExecutorResult, state: AgentState): Promise<SupervisorInstruction>;
+}
+
+/**
+ * Group Orchestration Runtime Config
+ */
+export interface GroupOrchestrationRuntimeConfig {
+ executors: Partial<Record<SupervisorInstruction['type'], GroupOrchestrationExecutor>>;
+ getOperation?: (operationId: string) => {
+ abortController: AbortController;
+ context: Record<string, unknown>;
+ };
+ operationId?: string;
+}
+
+// ==================== Event Types ====================
+
+/**
+ * Group Orchestration Event Types
+ */
+export interface GroupOrchestrationEventSupervisorFinished {
+ type: 'supervisor_finished';
+}
+
+export interface GroupOrchestrationEventAgentSpoke {
+ agentId: string;
+ type: 'agent_spoke';
+}
+
+export interface GroupOrchestrationEventAgentsBroadcasted {
+ agentIds: string[];
+ type: 'agents_broadcasted';
+}
+
+export interface GroupOrchestrationEventMaxRoundsExceeded {
+ type: 'max_rounds_exceeded';
+}
+
+export interface GroupOrchestrationEventDone {
+ reason: string;
+ type: 'done';
+}
+
+export type GroupOrchestrationEvent =
+ | GroupOrchestrationEventAgentSpoke
+ | GroupOrchestrationEventAgentsBroadcasted
+ | GroupOrchestrationEventDone
+ | GroupOrchestrationEventMaxRoundsExceeded
+ | GroupOrchestrationEventSupervisorFinished;
+
+// ==================== Legacy Types (for backward compatibility) ====================
+// TODO: Remove these after migration is complete
+
+/**
+ * @deprecated Use ExecutorResult instead
+ */
+export type GroupOrchestrationPhase =
+ | 'call_supervisor'
+ | 'speak'
+ | 'broadcast'
+ | 'delegate'
+ | 'agent_spoke'
+ | 'agents_broadcasted'
+ | 'execute_task';
+
+/**
+ * @deprecated Use ExecutorResult instead
+ */
+export interface GroupOrchestrationContext {
+ operationId?: string;
+ payload?: Record<string, unknown>;
+ phase: GroupOrchestrationPhase | string;
+}
+
+/**
+ * @deprecated Use SupervisorInstruction instead
+ */
+export type GroupOrchestrationInstruction = SupervisorInstruction;
+
+/**
+ * @deprecated Use GroupOrchestrationExecutorOutput instead
+ */
+export interface GroupOrchestrationExecutorResult {
+ events: GroupOrchestrationEvent[];
+ newState: AgentState;
+ nextContext?: GroupOrchestrationContext;
+}
diff --git a/packages/agent-runtime/src/index.ts b/packages/agent-runtime/src/index.ts
index a5a9e053576..a25f0c93279 100644
--- a/packages/agent-runtime/src/index.ts
+++ b/packages/agent-runtime/src/index.ts
@@ -1,2 +1,5 @@
+export * from './agents';
export * from './core';
+export * from './groupOrchestration';
export * from './types';
+export * from './utils';
diff --git a/packages/agent-runtime/src/types/event.ts b/packages/agent-runtime/src/types/event.ts
index ffbd42218e8..6825c6c05bc 100644
--- a/packages/agent-runtime/src/types/event.ts
+++ b/packages/agent-runtime/src/types/event.ts
@@ -36,14 +36,14 @@ export interface AgentEventToolResult {
export interface AgentEventHumanApproveRequired {
type: 'human_approve_required';
pendingToolsCalling: ChatToolPayload[];
- sessionId: string;
+ operationId: string;
}
export interface AgentEventHumanPromptRequired {
type: 'human_prompt_required';
metadata?: Record<string, unknown>;
prompt: string;
- sessionId: string;
+ operationId: string;
}
export interface AgentEventHumanSelectRequired {
@@ -52,7 +52,7 @@ export interface AgentEventHumanSelectRequired {
multi?: boolean;
options: { label: string; value: string }[];
prompt?: string;
- sessionId: string;
+ operationId: string;
}
/**
@@ -98,6 +98,16 @@ export interface AgentEventResumed {
metadata?: Record<string, unknown>;
}
+export interface AgentEventCompressionComplete {
+ type: 'compression_complete';
+ groupId: string;
+}
+
+export interface AgentEventCompressionError {
+ type: 'compression_error';
+ error: unknown;
+}
+
/**
* Events emitted by the AgentRuntime during execution
*/
@@ -121,4 +131,7 @@ export type AgentEvent =
| AgentEventHumanSelectRequired
// Interruption and resumption
| AgentEventInterrupted
- | AgentEventResumed;
+ | AgentEventResumed
+ // Context compression
+ | AgentEventCompressionComplete
+ | AgentEventCompressionError;
diff --git a/packages/agent-runtime/src/types/generalAgent.ts b/packages/agent-runtime/src/types/generalAgent.ts
index 64b5236034a..72d2ddaf27d 100644
--- a/packages/agent-runtime/src/types/generalAgent.ts
+++ b/packages/agent-runtime/src/types/generalAgent.ts
@@ -63,10 +63,37 @@ export interface GeneralAgentConfig {
[key: string]: any;
maxSteps?: number;
};
+ /**
+ * Context compression configuration
+ * Note: Compression checking is always enabled to prevent context overflow.
+ * This config only controls the compression parameters.
+ */
+ compressionConfig?: {
+ /** Number of recent messages to keep uncompressed (default: 10) */
+ keepRecentCount?: number;
+ /** Model's max context window token count (default: 128k) */
+ maxWindowToken?: number;
+ };
modelRuntimeConfig?: {
model: string;
provider: string;
};
- sessionId: string;
+ operationId: string;
userId?: string;
}
+
+/**
+ * Payload for compression_result phase
+ */
+export interface GeneralAgentCompressionResultPayload {
+ /** Compressed messages (summary + pinned + recent) */
+ compressedMessages: any[];
+ /** Token count after compression */
+ compressedTokenCount: number;
+ /** Compression group ID in database */
+ groupId: string;
+ /** Token count before compression */
+ originalTokenCount: number;
+ /** Whether compression was skipped (no messages to compress) */
+ skipped?: boolean;
+}
diff --git a/packages/agent-runtime/src/types/instruction.ts b/packages/agent-runtime/src/types/instruction.ts
index 90a45650acf..753447d1cdd 100644
--- a/packages/agent-runtime/src/types/instruction.ts
+++ b/packages/agent-runtime/src/types/instruction.ts
@@ -1,4 +1,4 @@
-import { ChatToolPayload, ModelUsage } from '@lobechat/types';
+import { ChatToolPayload, ModelUsage, RuntimeStepContext } from '@lobechat/types';
import type { FinishReason } from './event';
import { AgentState, ToolRegistry } from './state';
@@ -15,6 +15,7 @@ export interface AgentRuntimeContext {
/** Phase-specific payload/context */
payload?: unknown;
+
/** Current execution phase */
phase:
| 'init'
@@ -25,6 +26,7 @@ export interface AgentRuntimeContext {
| 'human_response'
| 'human_approved_tool'
| 'human_abort'
+ | 'compression_result'
| 'error';
/** Session info (kept for backward compatibility, will be optional in the future) */
@@ -34,6 +36,14 @@ export interface AgentRuntimeContext {
status: AgentState['status'];
stepCount: number;
};
+
+ /**
+ * Step context computed at the beginning of each step
+ * Contains dynamic state like GTD todos that changes between steps
+ * Computed by AgentRuntime and passed to Context Engine and Tool Executors
+ */
+ stepContext?: RuntimeStepContext;
+
/** Usage statistics from the current step (if applicable) */
stepUsage?: ModelUsage | unknown;
}
@@ -183,6 +193,25 @@ export interface AgentInstructionResolveAbortedTools {
type: 'resolve_aborted_tools';
}
+/**
+ * Instruction to execute context compression
+ */
+export interface AgentInstructionCompressContext {
+ payload: {
+ /** Current token count before compression */
+ currentTokenCount: number;
+ /** Existing summary to incorporate (for incremental compression) */
+ existingSummary?: string;
+ /** Number of recent messages to keep uncompressed */
+ keepRecentCount: number;
+ /** Messages to compress */
+ messages: any[];
+ /** Topic ID for the conversation */
+ topicId: string;
+ };
+ type: 'compress_context';
+}
+
/**
* A serializable instruction object that the "Agent" (Brain) returns
* to the "AgentRuntime" (Engine) to execute.
@@ -195,4 +224,5 @@ export type AgentInstruction =
| AgentInstructionRequestHumanSelect
| AgentInstructionRequestHumanApprove
| AgentInstructionResolveAbortedTools
+ | AgentInstructionCompressContext
| AgentInstructionFinish;
diff --git a/packages/agent-runtime/src/types/runtime.ts b/packages/agent-runtime/src/types/runtime.ts
index ab8bfc6adfa..3b7bc5a37b9 100644
--- a/packages/agent-runtime/src/types/runtime.ts
+++ b/packages/agent-runtime/src/types/runtime.ts
@@ -5,6 +5,11 @@ import { AgentState } from './state';
export type InstructionExecutor = (
instruction: AgentInstruction,
state: AgentState,
+ /**
+ * Runtime context for this step
+ * Contains stepContext with dynamic state like GTD todos
+ */
+ context?: AgentRuntimeContext,
) => Promise<{
events: AgentEvent[];
newState: AgentState;
diff --git a/packages/agent-runtime/src/types/state.ts b/packages/agent-runtime/src/types/state.ts
index fc6d9ea9b84..20f5826f8a3 100644
--- a/packages/agent-runtime/src/types/state.ts
+++ b/packages/agent-runtime/src/types/state.ts
@@ -8,7 +8,7 @@ import type { Cost, CostLimit, Usage } from './usage';
* This is the "passport" that can be persisted and transferred.
*/
export interface AgentState {
- sessionId: string;
+ operationId: string;
// --- State Machine ---
status: 'idle' | 'running' | 'waiting_for_human' | 'done' | 'error' | 'interrupted';
@@ -18,6 +18,15 @@ export interface AgentState {
systemRole?: string;
toolManifestMap: Record<string, any>;
+ /**
+ * Model runtime configuration
+ * Used as fallback when call_llm instruction doesn't specify model/provider
+ */
+ modelRuntimeConfig?: {
+ model: string;
+ provider: string;
+ };
+
/**
* User's global intervention configuration
* Controls how tools requiring approval are handled
diff --git a/packages/agent-runtime/src/utils/index.ts b/packages/agent-runtime/src/utils/index.ts
new file mode 100644
index 00000000000..0d7f7628898
--- /dev/null
+++ b/packages/agent-runtime/src/utils/index.ts
@@ -0,0 +1,2 @@
+export * from './stepContextComputer';
+export * from './tokenCounter';
diff --git a/packages/agent-runtime/src/utils/stepContextComputer.test.ts b/packages/agent-runtime/src/utils/stepContextComputer.test.ts
new file mode 100644
index 00000000000..b54bd964901
--- /dev/null
+++ b/packages/agent-runtime/src/utils/stepContextComputer.test.ts
@@ -0,0 +1,54 @@
+import { describe, expect, it } from 'vitest';
+
+import { computeStepContext } from './stepContextComputer';
+
+describe('computeStepContext', () => {
+ describe('assembles stepContext from pre-computed values', () => {
+ it('should include todos when provided', () => {
+ const todos = {
+ items: [
+ { text: 'Buy milk', completed: false },
+ { text: 'Call mom', completed: true },
+ ],
+ updatedAt: '2024-06-01T00:00:00.000Z',
+ };
+
+ const result = computeStepContext({ todos });
+
+ expect(result.todos).toBeDefined();
+ expect(result.todos?.items).toHaveLength(2);
+ expect(result.todos?.items[0].text).toBe('Buy milk');
+ expect(result.todos?.items[0].completed).toBe(false);
+ expect(result.todos?.items[1].text).toBe('Call mom');
+ expect(result.todos?.items[1].completed).toBe(true);
+ });
+
+ it('should not include todos key when undefined', () => {
+ const result = computeStepContext({});
+
+ expect(result.todos).toBeUndefined();
+ expect('todos' in result).toBe(false);
+ });
+
+ it('should return empty object when no params provided', () => {
+ const result = computeStepContext({});
+
+ expect(result).toEqual({});
+ });
+ });
+
+ describe('object parameter extensibility', () => {
+ it('should accept object parameter for future extensibility', () => {
+ // This should compile and work - object param allows future extensions
+ const result = computeStepContext({
+ todos: {
+ items: [{ text: 'Task', completed: false }],
+ updatedAt: '2024-01-01T00:00:00.000Z',
+ },
+ });
+
+ expect(result).toBeDefined();
+ expect(result.todos).toBeDefined();
+ });
+ });
+});
diff --git a/packages/agent-runtime/src/utils/stepContextComputer.ts b/packages/agent-runtime/src/utils/stepContextComputer.ts
new file mode 100644
index 00000000000..9f1b7b9d4a7
--- /dev/null
+++ b/packages/agent-runtime/src/utils/stepContextComputer.ts
@@ -0,0 +1,32 @@
+import type { RuntimeStepContext, StepContextTodos } from '@lobechat/types';
+
+/**
+ * Input parameters for computeStepContext
+ * Using object parameter for future extensibility
+ */
+export interface ComputeStepContextParams {
+ /**
+ * Pre-computed todos state from message selector
+ * Should be computed using selectTodosFromMessages in chat store selectors
+ */
+ todos?: StepContextTodos;
+}
+
+/**
+ * Compute the Step Context from pre-computed values
+ *
+ * Called in internal_execAgentRuntime while loop before each runtime.step() call.
+ * The stepContext is then passed through AgentRuntimeContext to Tool Executors.
+ *
+ * Note: The actual data (like todos) should be computed using selectors in the UI layer
+ * (e.g., selectTodosFromMessages in chat store) and passed here.
+ * This separation allows the selector logic to be reused for UI display.
+ *
+ * @param params - Object containing pre-computed state values
+ * @returns RuntimeStepContext assembled from the provided values
+ */
+export const computeStepContext = ({ todos }: ComputeStepContextParams): RuntimeStepContext => {
+ return {
+ ...(todos && { todos }),
+ };
+};
diff --git a/packages/agent-runtime/src/utils/tokenCounter.test.ts b/packages/agent-runtime/src/utils/tokenCounter.test.ts
new file mode 100644
index 00000000000..c2e3913cb5b
--- /dev/null
+++ b/packages/agent-runtime/src/utils/tokenCounter.test.ts
@@ -0,0 +1,208 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ DEFAULT_MAX_CONTEXT,
+ DEFAULT_THRESHOLD_RATIO,
+ calculateMessageTokens,
+ estimateTokens,
+ getCompressionThreshold,
+ shouldCompress,
+} from './tokenCounter';
+
+describe('tokenCounter', () => {
+ describe('estimateTokens', () => {
+ it('should estimate tokens for string content', () => {
+ const tokens = estimateTokens('Hello, world!');
+ expect(tokens).toBeGreaterThan(0);
+ });
+
+ it('should return 0 for empty string', () => {
+ expect(estimateTokens('')).toBe(0);
+ });
+
+ it('should handle null/undefined content', () => {
+ expect(estimateTokens(null)).toBe(0);
+ expect(estimateTokens(undefined)).toBe(0);
+ });
+
+ it('should handle object content by JSON stringifying', () => {
+ const tokens = estimateTokens({ key: 'value', nested: { a: 1 } });
+ expect(tokens).toBeGreaterThan(0);
+ });
+
+ it('should handle array content', () => {
+ const tokens = estimateTokens(['item1', 'item2', 'item3']);
+ expect(tokens).toBeGreaterThan(0);
+ });
+ });
+
+ describe('calculateMessageTokens', () => {
+ it('should use totalOutputTokens for assistant messages when available', () => {
+ const messages = [
+ {
+ content: 'This content should be ignored',
+ metadata: { usage: { totalOutputTokens: 100 } },
+ role: 'assistant',
+ },
+ ];
+ expect(calculateMessageTokens(messages)).toBe(100);
+ });
+
+ it('should estimate tokens for assistant messages without usage data', () => {
+ const messages = [{ content: 'Hello from assistant', role: 'assistant' }];
+ const tokens = calculateMessageTokens(messages);
+ expect(tokens).toBeGreaterThan(0);
+ // Should be estimated, not 0
+ expect(tokens).not.toBe(100);
+ });
+
+ it('should estimate tokens for user messages', () => {
+ const messages = [{ content: 'Hello from user', role: 'user' }];
+ const tokens = calculateMessageTokens(messages);
+ expect(tokens).toBeGreaterThan(0);
+ });
+
+ it('should estimate tokens for system messages', () => {
+ const messages = [{ content: 'System prompt', role: 'system' }];
+ const tokens = calculateMessageTokens(messages);
+ expect(tokens).toBeGreaterThan(0);
+ });
+
+ it('should sum tokens from multiple messages', () => {
+ const messages = [
+ { content: 'Hello', role: 'user' },
+ { content: 'Hi there!', metadata: { usage: { totalOutputTokens: 50 } }, role: 'assistant' },
+ { content: 'How are you?', role: 'user' },
+ ];
+ const tokens = calculateMessageTokens(messages);
+ // Should be 50 (assistant) + estimated tokens for user messages
+ expect(tokens).toBeGreaterThan(50);
+ });
+
+ it('should handle empty messages array', () => {
+ expect(calculateMessageTokens([])).toBe(0);
+ });
+
+ it('should handle messages with empty content', () => {
+ const messages = [
+ { content: '', role: 'user' },
+ { content: undefined, role: 'assistant' },
+ ];
+ expect(calculateMessageTokens(messages)).toBe(0);
+ });
+
+ it('should skip assistant usage with 0 tokens and estimate instead', () => {
+ const messages = [
+ {
+ content: 'Some content',
+ metadata: { usage: { totalOutputTokens: 0 } },
+ role: 'assistant',
+ },
+ ];
+ const tokens = calculateMessageTokens(messages);
+ // Should estimate since totalOutputTokens is 0
+ expect(tokens).toBeGreaterThan(0);
+ });
+ });
+
+ describe('getCompressionThreshold', () => {
+ it('should use default values', () => {
+ const threshold = getCompressionThreshold();
+ expect(threshold).toBe(Math.floor(DEFAULT_MAX_CONTEXT * DEFAULT_THRESHOLD_RATIO));
+ expect(threshold).toBe(96_000); // 128k * 0.75
+ });
+
+ it('should use custom maxWindowToken', () => {
+ const threshold = getCompressionThreshold({ maxWindowToken: 200_000 });
+ expect(threshold).toBe(150_000); // 200k * 0.75
+ });
+
+ it('should use custom thresholdRatio', () => {
+ const threshold = getCompressionThreshold({ thresholdRatio: 0.5 });
+ expect(threshold).toBe(64_000); // 128k * 0.5
+ });
+
+ it('should use both custom values', () => {
+ const threshold = getCompressionThreshold({
+ maxWindowToken: 100_000,
+ thresholdRatio: 0.8,
+ });
+ expect(threshold).toBe(80_000); // 100k * 0.8
+ });
+
+ it('should floor the result', () => {
+ const threshold = getCompressionThreshold({
+ maxWindowToken: 100,
+ thresholdRatio: 0.33,
+ });
+ expect(threshold).toBe(33); // floor(100 * 0.33) = 33
+ });
+ });
+
+ describe('shouldCompress', () => {
+ it('should return needsCompression=false when under threshold', () => {
+ const messages = [{ content: 'Hi', role: 'user' }];
+ const result = shouldCompress(messages);
+
+ expect(result.needsCompression).toBe(false);
+ expect(result.currentTokenCount).toBeGreaterThan(0);
+ expect(result.threshold).toBe(96_000);
+ });
+
+ it('should return needsCompression=true when over threshold', () => {
+ // Create a message with usage that exceeds threshold
+ const messages = [
+ {
+ content: '',
+ metadata: { usage: { totalOutputTokens: 100_000 } },
+ role: 'assistant',
+ },
+ ];
+ const result = shouldCompress(messages);
+
+ expect(result.needsCompression).toBe(true);
+ expect(result.currentTokenCount).toBe(100_000);
+ expect(result.threshold).toBe(96_000);
+ });
+
+ it('should return needsCompression=false when exactly at threshold', () => {
+ const messages = [
+ {
+ content: '',
+ metadata: { usage: { totalOutputTokens: 96_000 } },
+ role: 'assistant',
+ },
+ ];
+ const result = shouldCompress(messages);
+
+ // Exactly at threshold should not trigger compression
+ expect(result.needsCompression).toBe(false);
+ expect(result.currentTokenCount).toBe(96_000);
+ });
+
+ it('should use custom options', () => {
+ const messages = [
+ {
+ content: '',
+ metadata: { usage: { totalOutputTokens: 50_000 } },
+ role: 'assistant',
+ },
+ ];
+ const result = shouldCompress(messages, {
+ maxWindowToken: 60_000,
+ thresholdRatio: 0.75,
+ });
+
+ // threshold = 60k * 0.75 = 45k, current = 50k > 45k
+ expect(result.needsCompression).toBe(true);
+ expect(result.threshold).toBe(45_000);
+ });
+
+ it('should handle empty messages', () => {
+ const result = shouldCompress([]);
+
+ expect(result.needsCompression).toBe(false);
+ expect(result.currentTokenCount).toBe(0);
+ });
+ });
+});
diff --git a/packages/agent-runtime/src/utils/tokenCounter.ts b/packages/agent-runtime/src/utils/tokenCounter.ts
new file mode 100644
index 00000000000..111df47087a
--- /dev/null
+++ b/packages/agent-runtime/src/utils/tokenCounter.ts
@@ -0,0 +1,110 @@
+import { estimateTokenCount } from 'tokenx';
+
+/**
+ * Options for token counting and compression threshold calculation
+ */
+export interface TokenCountOptions {
+ /** Model's max context window token count */
+ maxWindowToken?: number;
+ /** Threshold ratio for triggering compression, default 0.75 */
+ thresholdRatio?: number;
+}
+
+/** Default max context window (128k tokens) */
+export const DEFAULT_MAX_CONTEXT = 128_000;
+
+/** Default threshold ratio (75% of max context) */
+export const DEFAULT_THRESHOLD_RATIO = 0.75;
+
+/**
+ * Message interface for token counting
+ */
+export interface TokenCountMessage {
+ content?: string | unknown;
+ metadata?: {
+ usage?: {
+ totalOutputTokens?: number;
+ };
+ } | null;
+ role: string;
+}
+
+/**
+ * Estimate token count for text content using tokenx
+ * @param content - Text content or object to estimate tokens for
+ * @returns Estimated token count
+ */
+export function estimateTokens(content: string | unknown): number {
+ // Handle null/undefined early
+ if (content === null || content === undefined) return 0;
+
+ const text = typeof content === 'string' ? content : JSON.stringify(content);
+ if (!text) return 0;
+ return estimateTokenCount(text);
+}
+
+/**
+ * Calculate total token count for a list of messages
+ * - Assistant messages: Use metadata.usage.totalOutputTokens if available (exact value)
+ * - User/System messages: Use tokenx estimation
+ *
+ * @param messages - List of messages to count tokens for
+ * @returns Total token count
+ */
+export function calculateMessageTokens(messages: TokenCountMessage[]): number {
+ return messages.reduce((total, msg) => {
+ // For assistant messages, prefer the recorded token count from usage metadata
+ if (msg.role === 'assistant') {
+ const outputTokens = msg.metadata?.usage?.totalOutputTokens;
+ if (outputTokens && outputTokens > 0) {
+ return total + outputTokens;
+ }
+ }
+
+ // For user/system messages or assistant messages without usage data, estimate tokens
+ return total + estimateTokens(msg.content);
+ }, 0);
+}
+
+/**
+ * Calculate the compression threshold based on max context window
+ * @param options - Token count options
+ * @returns Compression threshold in tokens
+ */
+export function getCompressionThreshold(options: TokenCountOptions = {}): number {
+ const maxContext = options.maxWindowToken ?? DEFAULT_MAX_CONTEXT;
+ const ratio = options.thresholdRatio ?? DEFAULT_THRESHOLD_RATIO;
+ return Math.floor(maxContext * ratio);
+}
+
+/**
+ * Result of compression check
+ */
+export interface CompressionCheckResult {
+ /** Current total token count */
+ currentTokenCount: number;
+ /** Whether compression is needed */
+ needsCompression: boolean;
+ /** Compression threshold */
+ threshold: number;
+}
+
+/**
+ * Check if messages need compression based on token count
+ * @param messages - List of messages to check
+ * @param options - Token count options
+ * @returns Compression check result
+ */
+export function shouldCompress(
+ messages: TokenCountMessage[],
+ options: TokenCountOptions = {},
+): CompressionCheckResult {
+ const currentTokenCount = calculateMessageTokens(messages);
+ const threshold = getCompressionThreshold(options);
+
+ return {
+ currentTokenCount,
+ needsCompression: currentTokenCount > threshold,
+ threshold,
+ };
+}
diff --git a/packages/builtin-tool-group-management/package.json b/packages/builtin-tool-group-management/package.json
new file mode 100644
index 00000000000..455b8d47e62
--- /dev/null
+++ b/packages/builtin-tool-group-management/package.json
@@ -0,0 +1,14 @@
+{
+ "name": "@lobechat/builtin-tool-group-management",
+ "version": "1.0.0",
+ "private": true,
+ "exports": {
+ ".": "./src/index.ts",
+ "./client": "./src/client/index.ts",
+ "./executor": "./src/executor.ts"
+ },
+ "main": "./src/index.ts",
+ "dependencies": {
+ "@lobechat/types": "workspace:*"
+ }
+}
diff --git a/packages/builtin-tool-group-management/src/client/Intervention/ExecuteTask.tsx b/packages/builtin-tool-group-management/src/client/Intervention/ExecuteTask.tsx
new file mode 100644
index 00000000000..f5d1947e6c6
--- /dev/null
+++ b/packages/builtin-tool-group-management/src/client/Intervention/ExecuteTask.tsx
@@ -0,0 +1,174 @@
+'use client';
+
+import { BuiltinInterventionProps } from '@lobechat/types';
+import { Avatar } from '@lobehub/ui';
+import { Input, InputNumber, Tooltip } from 'antd';
+import { createStyles } from 'antd-style';
+import isEqual from 'fast-deep-equal';
+import { Clock } from 'lucide-react';
+import { ChangeEvent, memo, useCallback, useEffect, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import { Flexbox } from 'react-layout-kit';
+
+import { useAgentGroupStore } from '@/store/agentGroup';
+import { agentGroupSelectors } from '@/store/agentGroup/selectors';
+
+import type { ExecuteTaskParams } from '../../types';
+
+const useStyles = createStyles(({ css, token }) => ({
+ agentCard: css`
+ padding: 4px;
+ border-radius: ${token.borderRadius}px;
+ background: ${token.colorFillTertiary};
+ `,
+ agentDescription: css`
+ overflow: hidden;
+ display: -webkit-box;
+ -webkit-box-orient: vertical;
+ -webkit-line-clamp: 2;
+
+ font-size: 12px;
+ line-height: 1.4;
+ color: ${token.colorTextSecondary};
+ `,
+ agentTitle: css`
+ font-size: 14px;
+ font-weight: 600;
+ color: ${token.colorText};
+ `,
+ container: css`
+ padding-block: 12px;
+ border-radius: ${token.borderRadius}px;
+ `,
+ header: css`
+ font-size: 14px;
+ font-weight: 600;
+ `,
+ icon: css`
+ display: flex;
+ align-items: center;
+ justify-content: center;
+
+ width: 32px;
+ height: 32px;
+ border-radius: ${token.borderRadius}px;
+
+ color: ${token.colorPrimary};
+
+ background: ${token.colorPrimaryBg};
+ `,
+ timeoutInput: css`
+ width: 100px;
+ `,
+}));
+
+const DEFAULT_TIMEOUT = 1_800_000; // 30 minutes
+
+/**
+ * ExecuteTask Intervention Component
+ *
+ * Allows users to review and modify the task description before execution.
+ */
+const ExecuteTaskIntervention = memo<BuiltinInterventionProps<ExecuteTaskParams>>(
+ ({ args, onArgsChange, registerBeforeApprove }) => {
+ const { styles } = useStyles();
+ const { t } = useTranslation('tool');
+
+ // Get agent info from store
+ const activeGroupId = useAgentGroupStore(agentGroupSelectors.activeGroupId);
+ const agent = useAgentGroupStore((s) =>
+ args?.agentId && activeGroupId
+ ? agentGroupSelectors.getAgentByIdFromGroup(activeGroupId, args.agentId)(s)
+ : undefined,
+ );
+
+ // Local state
+ const [task, setTask] = useState(args?.task || '');
+ const [timeout, setTimeout] = useState(args?.timeout ?? DEFAULT_TIMEOUT);
+ const [hasChanges, setHasChanges] = useState(false);
+
+ // Sync local state when args change externally
+ useEffect(() => {
+ if (!hasChanges) {
+ setTask(args?.task || '');
+ setTimeout(args?.timeout ?? DEFAULT_TIMEOUT);
+ }
+ }, [args?.task, args?.timeout, hasChanges]);
+
+ // Handle task change
+ const handleTaskChange = useCallback((e: ChangeEvent<HTMLTextAreaElement>) => {
+ setTask(e.target.value);
+ setHasChanges(true);
+ }, []);
+
+ // Handle timeout change (minutes to milliseconds)
+ const handleTimeoutChange = useCallback((value: number | null) => {
+ if (value !== null) {
+ setTimeout(value * 60 * 1000); // Convert minutes to milliseconds
+ setHasChanges(true);
+ }
+ }, []);
+
+ // Save changes before approval
+ useEffect(() => {
+ if (!registerBeforeApprove) return;
+
+ const cleanup = registerBeforeApprove('executeTask', async () => {
+ if (hasChanges && onArgsChange) {
+ await onArgsChange({ ...args, task, timeout });
+ }
+ });
+
+ return cleanup;
+ }, [registerBeforeApprove, hasChanges, task, timeout, args, onArgsChange]);
+
+ return (
+ <Flexbox className={styles.container} gap={12}>
+ {/* Header: Agent info + Timeout */}
+ <Flexbox align={'center'} gap={12} horizontal justify={'space-between'}>
+ <Flexbox align={'center'} flex={1} gap={12} horizontal style={{ minWidth: 0 }}>
+ <Avatar
+ avatar={agent?.avatar || '🤖'}
+ background={agent?.backgroundColor || undefined}
+ size={24}
+ style={{ borderRadius: 8, flexShrink: 0 }}
+ />
+ <Flexbox flex={1} gap={4} style={{ minWidth: 0 }}>
+ <span className={styles.agentTitle}>
+ {agent?.title || t('agentGroupManagement.executeTask.intervention.unknownAgent')}
+ </span>
+ </Flexbox>
+ </Flexbox>
+ <Flexbox align="center" gap={8} horizontal style={{ flexShrink: 0 }}>
+ <Tooltip title={t('agentGroupManagement.executeTask.intervention.timeout')}>
+ <Clock size={14} />
+ </Tooltip>
+ <InputNumber
+ className={styles.timeoutInput}
+ max={120}
+ min={1}
+ onChange={handleTimeoutChange}
+ size={'small'}
+ suffix={t('agentGroupManagement.executeTask.intervention.timeoutUnit')}
+ value={Math.round(timeout / 60_000)}
+ variant={'filled'}
+ />
+ </Flexbox>
+ </Flexbox>
+
+ {/* Task input */}
+ <Input.TextArea
+ autoSize={{ maxRows: 10, minRows: 6 }}
+ onChange={handleTaskChange}
+ placeholder={t('agentGroupManagement.executeTask.intervention.taskPlaceholder')}
+ value={task}
+ />
+ </Flexbox>
+ );
+ },
+ isEqual,
+);
+
+ExecuteTaskIntervention.displayName = 'ExecuteTaskIntervention';
+
+export default ExecuteTaskIntervention;
diff --git a/packages/builtin-tool-group-management/src/client/Intervention/index.ts b/packages/builtin-tool-group-management/src/client/Intervention/index.ts
new file mode 100644
index 00000000000..4a494bed1e1
--- /dev/null
+++ b/packages/builtin-tool-group-management/src/client/Intervention/index.ts
@@ -0,0 +1,16 @@
+import { BuiltinIntervention } from '@lobechat/types';
+
+import { GroupManagementApiName } from '../../types';
+import ExecuteTaskIntervention from './ExecuteTask';
+
+/**
+ * Group Management Tool Intervention Components Registry
+ *
+ * Intervention components allow users to review and modify tool parameters
+ * before the tool is executed.
+ */
+export const GroupManagementInterventions: Record<string, BuiltinIntervention> = {
+ [GroupManagementApiName.executeTask]: ExecuteTaskIntervention as BuiltinIntervention,
+};
+
+export { default as ExecuteTaskIntervention } from './ExecuteTask';
diff --git a/packages/builtin-tool-group-management/src/client/Render/ExecuteTask/index.tsx b/packages/builtin-tool-group-management/src/client/Render/ExecuteTask/index.tsx
new file mode 100644
index 00000000000..678628ae9ab
--- /dev/null
+++ b/packages/builtin-tool-group-management/src/client/Render/ExecuteTask/index.tsx
@@ -0,0 +1,91 @@
+'use client';
+
+import { BuiltinRenderProps } from '@lobechat/types';
+import { Avatar, Text } from '@lobehub/ui';
+import { createStyles } from 'antd-style';
+import { Clock } from 'lucide-react';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+import { Flexbox } from 'react-layout-kit';
+
+import { useAgentGroupStore } from '@/store/agentGroup';
+import { agentGroupSelectors } from '@/store/agentGroup/selectors';
+
+import type { ExecuteTaskParams, ExecuteTaskState } from '../../../types';
+
+const useStyles = createStyles(({ css, token }) => ({
+ agentTitle: css`
+ color: ${token.colorTextSecondary};
+ `,
+ container: css`
+ padding-block: 12px;
+ border-radius: ${token.borderRadius}px;
+ `,
+ taskContent: css`
+ padding-block: 8px;
+ padding-inline: 12px;
+ border-radius: ${token.borderRadius}px;
+ background: ${token.colorFillTertiary};
+ `,
+ timeout: css`
+ font-size: 12px;
+ color: ${token.colorTextTertiary};
+ `,
+}));
+
+/**
+ * ExecuteTask Render component for Group Management tool
+ * Read-only display of the task execution request
+ */
+const ExecuteTaskRender = memo<BuiltinRenderProps<ExecuteTaskParams, ExecuteTaskState>>(
+ ({ args }) => {
+ const { styles } = useStyles();
+ const { t } = useTranslation('tool');
+
+ // Get agent info from store
+ const activeGroupId = useAgentGroupStore(agentGroupSelectors.activeGroupId);
+ const agent = useAgentGroupStore((s) =>
+ args?.agentId && activeGroupId
+ ? agentGroupSelectors.getAgentByIdFromGroup(activeGroupId, args.agentId)(s)
+ : undefined,
+ );
+
+ const timeoutMinutes = args?.timeout ? Math.round(args.timeout / 60_000) : 30;
+
+ return (
+ <Flexbox className={styles.container} gap={12}>
+ {/* Header: Agent info + Timeout */}
+ <Flexbox align={'center'} gap={12} horizontal justify={'space-between'}>
+ <Flexbox align={'center'} flex={1} gap={12} horizontal style={{ minWidth: 0 }}>
+ <Avatar
+ avatar={agent?.avatar || '🤖'}
+ background={agent?.backgroundColor || undefined}
+ size={24}
+ style={{ borderRadius: 8, flexShrink: 0 }}
+ />
+ <span className={styles.agentTitle}>
+ {agent?.title || t('agentGroupManagement.executeTask.intervention.unknownAgent')}
+ </span>
+ </Flexbox>
+ <Flexbox align="center" className={styles.timeout} gap={4} horizontal>
+ <Clock size={14} />
+ <span>
+ {timeoutMinutes} {t('agentGroupManagement.executeTask.intervention.timeoutUnit')}
+ </span>
+ </Flexbox>
+ </Flexbox>
+
+ {/* Task content (read-only) */}
+ {args?.task && (
+ <Text className={styles.taskContent} style={{ margin: 0 }}>
+ {args.task}
+ </Text>
+ )}
+ </Flexbox>
+ );
+ },
+);
+
+ExecuteTaskRender.displayName = 'ExecuteTaskRender';
+
+export default ExecuteTaskRender;
diff --git a/packages/builtin-tool-group-management/src/client/Render/index.ts b/packages/builtin-tool-group-management/src/client/Render/index.ts
new file mode 100644
index 00000000000..d44908394ba
--- /dev/null
+++ b/packages/builtin-tool-group-management/src/client/Render/index.ts
@@ -0,0 +1,11 @@
+import { GroupManagementApiName } from '../../types';
+import ExecuteTaskRender from './ExecuteTask';
+
+/**
+ * Group Management Tool Render Components Registry
+ */
+export const GroupManagementRenders = {
+ [GroupManagementApiName.executeTask]: ExecuteTaskRender,
+};
+
+export { default as ExecuteTaskRender } from './ExecuteTask';
diff --git a/packages/builtin-tool-group-management/src/client/index.ts b/packages/builtin-tool-group-management/src/client/index.ts
new file mode 100644
index 00000000000..19f270de540
--- /dev/null
+++ b/packages/builtin-tool-group-management/src/client/index.ts
@@ -0,0 +1,9 @@
+// Render components (read-only snapshots)
+export { ExecuteTaskRender, GroupManagementRenders } from './Render';
+
+// Intervention components (interactive editing)
+export { ExecuteTaskIntervention, GroupManagementInterventions } from './Intervention';
+
+// Re-export types and manifest for convenience
+export { GroupManagementManifest } from '../manifest';
+export * from '../types';
diff --git a/packages/builtin-tool-group-management/src/executor.test.ts b/packages/builtin-tool-group-management/src/executor.test.ts
new file mode 100644
index 00000000000..8ff62871e33
--- /dev/null
+++ b/packages/builtin-tool-group-management/src/executor.test.ts
@@ -0,0 +1,738 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type {
+ AfterCompletionCallback,
+ BuiltinToolContext,
+ GroupOrchestrationCallbacks,
+} from '../../types';
+import { groupManagementExecutor } from './executor';
+
+// Mock agentGroupStore
+const mockAddAgentsToGroup = vi.fn();
+const mockRemoveAgentFromGroup = vi.fn();
+
+vi.mock('@/store/agentGroup', () => ({
+ agentGroupSelectors: {
+ getAgentByIdFromGroup: vi.fn(() => () => undefined),
+ },
+ useAgentGroupStore: {
+ getState: () => ({
+ addAgentsToGroup: mockAddAgentsToGroup,
+ removeAgentFromGroup: mockRemoveAgentFromGroup,
+ }),
+ },
+}));
+
+// Mock agentService
+const mockQueryAgents = vi.fn();
+const mockCreateAgent = vi.fn();
+
+vi.mock('@/services/agent', () => ({
+ agentService: {
+ createAgent: (...args: any[]) => mockCreateAgent(...args),
+ queryAgents: (...args: any[]) => mockQueryAgents(...args),
+ },
+}));
+
+// Mock lambdaClient for Task APIs
+const mockExecGroupSubAgentTask = vi.fn();
+const mockGetTaskStatus = vi.fn();
+const mockInterruptTask = vi.fn();
+
+vi.mock('@/libs/trpc/client', () => ({
+ lambdaClient: {
+ aiAgent: {
+ execGroupSubAgentTask: { mutate: (...args: any[]) => mockExecGroupSubAgentTask(...args) },
+ getGroupSubAgentTaskStatus: { query: (...args: any[]) => mockGetTaskStatus(...args) },
+ interruptTask: { mutate: (...args: any[]) => mockInterruptTask(...args) },
+ },
+ },
+}));
+
+describe('GroupManagementExecutor', () => {
+ const createMockContext = (
+ groupOrchestration?: GroupOrchestrationCallbacks,
+ agentId?: string,
+ registerAfterCompletion?: (callback: AfterCompletionCallback) => void,
+ ): BuiltinToolContext => ({
+ agentId,
+ groupOrchestration,
+ messageId: 'test-message-id',
+ operationId: 'test-operation-id',
+ registerAfterCompletion,
+ });
+
+ describe('speak', () => {
+ it('should return stop=true to terminate supervisor execution', async () => {
+ const ctx = createMockContext();
+
+ const result = await groupManagementExecutor.speak(
+ { agentId: 'agent-1', instruction: 'Please respond' },
+ ctx,
+ );
+
+ expect(result.success).toBe(true);
+ expect(result.stop).toBe(true);
+ expect(result.state).toEqual({
+ agentId: 'agent-1',
+ instruction: 'Please respond',
+ type: 'speak',
+ });
+ });
+
+ it('should register afterCompletion callback that triggers groupOrchestration.triggerSpeak', async () => {
+ const triggerSpeak = vi.fn();
+ const registeredCallbacks: AfterCompletionCallback[] = [];
+ const registerAfterCompletion = vi.fn((cb: AfterCompletionCallback) => {
+ registeredCallbacks.push(cb);
+ });
+
+ const ctx = createMockContext(
+ {
+ triggerBroadcast: vi.fn(),
+ triggerDelegate: vi.fn(),
+ triggerExecuteTask: vi.fn(),
+ triggerSpeak,
+ },
+ 'supervisor-agent',
+ registerAfterCompletion,
+ );
+
+ await groupManagementExecutor.speak(
+ { agentId: 'agent-1', instruction: 'Please respond' },
+ ctx,
+ );
+
+ // Verify registerAfterCompletion was called
+ expect(registerAfterCompletion).toHaveBeenCalled();
+ expect(registeredCallbacks.length).toBe(1);
+
+ // Execute the registered callback (simulating AgentRuntime completion)
+ await registeredCallbacks[0]();
+
+ // Now triggerSpeak should have been called
+ expect(triggerSpeak).toHaveBeenCalledWith({
+ agentId: 'agent-1',
+ instruction: 'Please respond',
+ supervisorAgentId: 'supervisor-agent',
+ });
+ });
+
+ it('should not fail when groupOrchestration is not available', async () => {
+ const ctx = createMockContext(); // No groupOrchestration
+
+ const result = await groupManagementExecutor.speak({ agentId: 'agent-1' }, ctx);
+
+ expect(result.success).toBe(true);
+ expect(result.stop).toBe(true);
+ });
+
+ it('should handle undefined instruction in afterCompletion callback', async () => {
+ const triggerSpeak = vi.fn();
+ const registeredCallbacks: AfterCompletionCallback[] = [];
+ const registerAfterCompletion = vi.fn((cb: AfterCompletionCallback) => {
+ registeredCallbacks.push(cb);
+ });
+
+ const ctx = createMockContext(
+ {
+ triggerBroadcast: vi.fn(),
+ triggerDelegate: vi.fn(),
+ triggerExecuteTask: vi.fn(),
+ triggerSpeak,
+ },
+ 'supervisor-agent',
+ registerAfterCompletion,
+ );
+
+ await groupManagementExecutor.speak({ agentId: 'agent-2' }, ctx);
+
+ // Execute the registered callback
+ await registeredCallbacks[0]();
+
+ expect(triggerSpeak).toHaveBeenCalledWith({
+ agentId: 'agent-2',
+ instruction: undefined,
+ supervisorAgentId: 'supervisor-agent',
+ });
+ });
+ });
+
+ describe('broadcast', () => {
+ it('should return stop=true to terminate supervisor execution', async () => {
+ const ctx = createMockContext();
+
+ const result = await groupManagementExecutor.broadcast(
+ { agentIds: ['agent-1', 'agent-2'], instruction: 'Discuss' },
+ ctx,
+ );
+
+ expect(result.success).toBe(true);
+ expect(result.stop).toBe(true);
+ expect(result.state).toEqual({
+ agentIds: ['agent-1', 'agent-2'],
+ instruction: 'Discuss',
+ type: 'broadcast',
+ });
+ });
+
+ it('should register afterCompletion callback that triggers groupOrchestration.triggerBroadcast', async () => {
+ const triggerBroadcast = vi.fn();
+ const registeredCallbacks: AfterCompletionCallback[] = [];
+ const registerAfterCompletion = vi.fn((cb: AfterCompletionCallback) => {
+ registeredCallbacks.push(cb);
+ });
+
+ const ctx = createMockContext(
+ {
+ triggerBroadcast,
+ triggerDelegate: vi.fn(),
+ triggerExecuteTask: vi.fn(),
+ triggerSpeak: vi.fn(),
+ },
+ 'supervisor-agent',
+ registerAfterCompletion,
+ );
+
+ await groupManagementExecutor.broadcast(
+ { agentIds: ['agent-1', 'agent-2'], instruction: 'Discuss together' },
+ ctx,
+ );
+
+ // Verify registerAfterCompletion was called
+ expect(registerAfterCompletion).toHaveBeenCalled();
+ expect(registeredCallbacks.length).toBe(1);
+
+ // Execute the registered callback (simulating AgentRuntime completion)
+ await registeredCallbacks[0]();
+
+ // Now triggerBroadcast should have been called
+ expect(triggerBroadcast).toHaveBeenCalledWith({
+ agentIds: ['agent-1', 'agent-2'],
+ instruction: 'Discuss together',
+ supervisorAgentId: 'supervisor-agent',
+ toolMessageId: 'test-message-id',
+ });
+ });
+
+ it('should not fail when groupOrchestration is not available', async () => {
+ const ctx = createMockContext();
+
+ const result = await groupManagementExecutor.broadcast({ agentIds: ['agent-1'] }, ctx);
+
+ expect(result.success).toBe(true);
+ expect(result.stop).toBe(true);
+ });
+ });
+
+ describe('delegate', () => {
+ it('should return stop=true to terminate supervisor execution', async () => {
+ const ctx = createMockContext();
+
+ const result = await groupManagementExecutor.delegate(
+ { agentId: 'agent-1', reason: 'User requested' },
+ ctx,
+ );
+
+ expect(result.success).toBe(true);
+ expect(result.stop).toBe(true);
+ expect(result.state).toEqual({
+ agentId: 'agent-1',
+ reason: 'User requested',
+ type: 'delegate',
+ });
+ });
+
+ it('should register afterCompletion callback that triggers groupOrchestration.triggerDelegate', async () => {
+ const triggerDelegate = vi.fn();
+ const registeredCallbacks: AfterCompletionCallback[] = [];
+ const registerAfterCompletion = vi.fn((cb: AfterCompletionCallback) => {
+ registeredCallbacks.push(cb);
+ });
+
+ const ctx = createMockContext(
+ {
+ triggerBroadcast: vi.fn(),
+ triggerDelegate,
+ triggerExecuteTask: vi.fn(),
+ triggerSpeak: vi.fn(),
+ },
+ 'supervisor-agent',
+ registerAfterCompletion,
+ );
+
+ await groupManagementExecutor.delegate({ agentId: 'agent-3', reason: 'Expert needed' }, ctx);
+
+ // Verify registerAfterCompletion was called
+ expect(registerAfterCompletion).toHaveBeenCalled();
+ expect(registeredCallbacks.length).toBe(1);
+
+ // Execute the registered callback (simulating AgentRuntime completion)
+ await registeredCallbacks[0]();
+
+ // Now triggerDelegate should have been called
+ expect(triggerDelegate).toHaveBeenCalledWith({
+ agentId: 'agent-3',
+ reason: 'Expert needed',
+ supervisorAgentId: 'supervisor-agent',
+ });
+ });
+
+ it('should not fail when groupOrchestration is not available', async () => {
+ const ctx = createMockContext();
+
+ const result = await groupManagementExecutor.delegate({ agentId: 'agent-1' }, ctx);
+
+ expect(result.success).toBe(true);
+ expect(result.stop).toBe(true);
+ });
+ });
+
+ describe('searchAgent', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it('should return community not supported message when source is community', async () => {
+ const ctx = createMockContext();
+
+ const result = await groupManagementExecutor.searchAgent(
+ { query: 'test', source: 'community' },
+ ctx,
+ );
+
+ expect(result.success).toBe(true);
+ expect(result.content).toContain('Community agent search is not yet supported');
+ expect(result.state).toEqual({ agents: [], source: 'community', total: 0 });
+ });
+
+ it('should search user agents and return formatted results', async () => {
+ mockQueryAgents.mockResolvedValue([
+ { id: 'agent-1', title: 'Code Assistant', description: 'Helps with coding', avatar: '🤖' },
+ { id: 'agent-2', title: 'Writer', description: null, avatar: null },
+ ]);
+
+ const ctx = createMockContext();
+ const result = await groupManagementExecutor.searchAgent({ query: 'test' }, ctx);
+
+ expect(result.success).toBe(true);
+ expect(mockQueryAgents).toHaveBeenCalledWith({ keyword: 'test', limit: 10 });
+ expect(result.content).toContain('Found 2 agents');
+ expect(result.content).toContain('Code Assistant');
+ expect(result.content).toContain('Writer');
+ expect(result.state.agents).toHaveLength(2);
+ expect(result.state.total).toBe(2);
+ });
+
+ it('should return no results message when no agents found', async () => {
+ mockQueryAgents.mockResolvedValue([]);
+
+ const ctx = createMockContext();
+ const result = await groupManagementExecutor.searchAgent({ query: 'nonexistent' }, ctx);
+
+ expect(result.success).toBe(true);
+ expect(result.content).toContain('No agents found matching "nonexistent"');
+ expect(result.state).toEqual({ agents: [], query: 'nonexistent', total: 0 });
+ });
+
+ it('should pass limit to queryAgents', async () => {
+ mockQueryAgents.mockResolvedValue([
+ { id: 'agent-1', title: 'Agent 1' },
+ { id: 'agent-2', title: 'Agent 2' },
+ ]);
+
+ const ctx = createMockContext();
+ const result = await groupManagementExecutor.searchAgent({ query: 'test', limit: 2 }, ctx);
+
+ expect(result.success).toBe(true);
+ expect(mockQueryAgents).toHaveBeenCalledWith({ keyword: 'test', limit: 2 });
+ expect(result.state.agents).toHaveLength(2);
+ });
+
+ it('should handle errors gracefully', async () => {
+ mockQueryAgents.mockRejectedValue(new Error('Network error'));
+
+ const ctx = createMockContext();
+ const result = await groupManagementExecutor.searchAgent({ query: 'test' }, ctx);
+
+ expect(result.success).toBe(false);
+ expect(result.content).toBe('Failed to search agents: Network error');
+ });
+ });
+
+ describe('getAgentInfo', () => {
+ it('should return error when no groupId in context', async () => {
+ const ctx = createMockContext();
+
+ const result = await groupManagementExecutor.getAgentInfo({ agentId: 'agent-1' }, ctx);
+
+ // No groupId means we can't get agent info
+ expect(result.success).toBe(false);
+ expect(result.stop).toBeUndefined();
+ });
+ });
+
+ describe('inviteAgent', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it('should return error when no groupId in context', async () => {
+ const ctx = createMockContext();
+
+ const result = await groupManagementExecutor.inviteAgent({ agentId: 'agent-1' }, ctx);
+
+ expect(result.success).toBe(false);
+ expect(result.content).toBe('No group context available');
+ });
+
+ it('should successfully invite agent when groupId is available', async () => {
+ mockAddAgentsToGroup.mockResolvedValue(undefined);
+
+ const ctx: BuiltinToolContext = {
+ ...createMockContext(),
+ groupId: 'test-group-id',
+ };
+
+ const result = await groupManagementExecutor.inviteAgent({ agentId: 'agent-1' }, ctx);
+
+ expect(result.success).toBe(true);
+ expect(mockAddAgentsToGroup).toHaveBeenCalledWith('test-group-id', ['agent-1']);
+ expect(result.content).toBe('Agent "agent-1" has been invited to the group.');
+ expect(result.state).toEqual({ agentId: 'agent-1', type: 'inviteAgent' });
+ });
+
+ it('should handle errors during invitation', async () => {
+ mockAddAgentsToGroup.mockRejectedValue(new Error('Database error'));
+
+ const ctx: BuiltinToolContext = {
+ ...createMockContext(),
+ groupId: 'test-group-id',
+ };
+
+ const result = await groupManagementExecutor.inviteAgent({ agentId: 'agent-1' }, ctx);
+
+ expect(result.success).toBe(false);
+ expect(result.content).toBe('Failed to invite agent "agent-1": Database error');
+ });
+ });
+
+ describe('removeAgent', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it('should return error when no groupId in context', async () => {
+ const ctx = createMockContext();
+
+ const result = await groupManagementExecutor.removeAgent({ agentId: 'agent-1' }, ctx);
+
+ expect(result.success).toBe(false);
+ expect(result.content).toBe('No group context available');
+ });
+
+ it('should successfully remove agent when groupId is available', async () => {
+ mockRemoveAgentFromGroup.mockResolvedValue(undefined);
+
+ const ctx: BuiltinToolContext = {
+ ...createMockContext(),
+ groupId: 'test-group-id',
+ };
+
+ const result = await groupManagementExecutor.removeAgent({ agentId: 'agent-1' }, ctx);
+
+ expect(result.success).toBe(true);
+ expect(mockRemoveAgentFromGroup).toHaveBeenCalledWith('test-group-id', 'agent-1');
+ expect(result.content).toBe('Agent "agent-1" has been removed from the group.');
+ expect(result.state).toEqual({ agentId: 'agent-1', type: 'removeAgent' });
+ });
+
+ it('should handle errors during removal', async () => {
+ mockRemoveAgentFromGroup.mockRejectedValue(new Error('Agent not found'));
+
+ const ctx: BuiltinToolContext = {
+ ...createMockContext(),
+ groupId: 'test-group-id',
+ };
+
+ const result = await groupManagementExecutor.removeAgent({ agentId: 'agent-1' }, ctx);
+
+ expect(result.success).toBe(false);
+ expect(result.content).toBe('Failed to remove agent "agent-1": Agent not found');
+ });
+ });
+
+ describe('createAgent', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it('should return error when no groupId in context', async () => {
+ const ctx = createMockContext();
+
+ const result = await groupManagementExecutor.createAgent(
+ { title: 'New Agent', systemRole: 'You are a helpful assistant' },
+ ctx,
+ );
+
+ expect(result.success).toBe(false);
+ expect(result.content).toBe('No group context available');
+ });
+
+ it('should successfully create a virtual agent and add to group', async () => {
+ mockCreateAgent.mockResolvedValue({
+ agentId: 'new-agent-id',
+ sessionId: 'new-session-id',
+ });
+
+ const ctx: BuiltinToolContext = {
+ ...createMockContext(),
+ groupId: 'test-group-id',
+ };
+
+ const result = await groupManagementExecutor.createAgent(
+ {
+ avatar: '🤖',
+ description: 'A helpful coding assistant',
+ systemRole: 'You are a coding expert',
+ title: 'Code Helper',
+ },
+ ctx,
+ );
+
+ expect(result.success).toBe(true);
+ expect(mockCreateAgent).toHaveBeenCalledWith({
+ config: {
+ avatar: '🤖',
+ description: 'A helpful coding assistant',
+ systemRole: 'You are a coding expert',
+ title: 'Code Helper',
+ virtual: true,
+ },
+ groupId: 'test-group-id',
+ });
+ expect(result.content).toBe('Agent "Code Helper" has been created and added to the group.');
+ expect(result.state).toEqual({
+ agentId: 'new-agent-id',
+ title: 'Code Helper',
+ type: 'createAgent',
+ });
+ });
+
+ it('should handle case when agentId is not returned', async () => {
+ mockCreateAgent.mockResolvedValue({
+ sessionId: 'new-session-id',
+ // No agentId returned
+ });
+
+ const ctx: BuiltinToolContext = {
+ ...createMockContext(),
+ groupId: 'test-group-id',
+ };
+
+ const result = await groupManagementExecutor.createAgent(
+ { title: 'New Agent', systemRole: 'Test' },
+ ctx,
+ );
+
+ expect(result.success).toBe(false);
+ expect(result.content).toBe('Failed to create agent: No agent ID returned');
+ });
+
+ it('should handle errors during creation', async () => {
+ mockCreateAgent.mockRejectedValue(new Error('Database connection failed'));
+
+ const ctx: BuiltinToolContext = {
+ ...createMockContext(),
+ groupId: 'test-group-id',
+ };
+
+ const result = await groupManagementExecutor.createAgent(
+ { title: 'New Agent', systemRole: 'Test' },
+ ctx,
+ );
+
+ expect(result.success).toBe(false);
+ expect(result.content).toBe('Failed to create agent: Database connection failed');
+ });
+
+ it('should create agent with minimal params (only required fields)', async () => {
+ mockCreateAgent.mockResolvedValue({
+ agentId: 'minimal-agent-id',
+ sessionId: 'minimal-session-id',
+ });
+
+ const ctx: BuiltinToolContext = {
+ ...createMockContext(),
+ groupId: 'test-group-id',
+ };
+
+ const result = await groupManagementExecutor.createAgent(
+ { title: 'Minimal Agent', systemRole: 'Basic assistant' },
+ ctx,
+ );
+
+ expect(result.success).toBe(true);
+ expect(mockCreateAgent).toHaveBeenCalledWith({
+ config: {
+ avatar: undefined,
+ description: undefined,
+ systemRole: 'Basic assistant',
+ title: 'Minimal Agent',
+ virtual: true,
+ },
+ groupId: 'test-group-id',
+ });
+ });
+ });
+
+ describe('executeTask', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it('should return stop=true to terminate supervisor execution', async () => {
+ const ctx = createMockContext();
+
+ const result = await groupManagementExecutor.executeTask(
+ { agentId: 'agent-1', task: 'Do something' },
+ ctx,
+ );
+
+ expect(result.success).toBe(true);
+ expect(result.stop).toBe(true);
+ expect(result.content).toBe('Triggered async task for agent "agent-1".');
+ expect(result.state).toEqual({
+ agentId: 'agent-1',
+ task: 'Do something',
+ timeout: undefined,
+ type: 'executeTask',
+ });
+ });
+
+ it('should register afterCompletion callback that triggers groupOrchestration.triggerExecuteTask', async () => {
+ const triggerExecuteTask = vi.fn();
+ const registeredCallbacks: AfterCompletionCallback[] = [];
+ const registerAfterCompletion = vi.fn((cb: AfterCompletionCallback) => {
+ registeredCallbacks.push(cb);
+ });
+
+ const ctx = createMockContext(
+ {
+ triggerBroadcast: vi.fn(),
+ triggerDelegate: vi.fn(),
+ triggerExecuteTask,
+ triggerSpeak: vi.fn(),
+ },
+ 'supervisor-agent',
+ registerAfterCompletion,
+ );
+
+ await groupManagementExecutor.executeTask(
+ { agentId: 'agent-1', task: 'Do something', timeout: 30000 },
+ ctx,
+ );
+
+ // Verify registerAfterCompletion was called
+ expect(registerAfterCompletion).toHaveBeenCalled();
+ expect(registeredCallbacks.length).toBe(1);
+
+ // Execute the registered callback (simulating AgentRuntime completion)
+ await registeredCallbacks[0]();
+
+ // Now triggerExecuteTask should have been called
+ expect(triggerExecuteTask).toHaveBeenCalledWith({
+ agentId: 'agent-1',
+ supervisorAgentId: 'supervisor-agent',
+ task: 'Do something',
+ timeout: 30000,
+ toolMessageId: 'test-message-id',
+ });
+ });
+
+ it('should not fail when groupOrchestration is not available', async () => {
+ const ctx = createMockContext();
+
+ const result = await groupManagementExecutor.executeTask(
+ { agentId: 'agent-1', task: 'Do something' },
+ ctx,
+ );
+
+ expect(result.success).toBe(true);
+ expect(result.stop).toBe(true);
+ });
+
+ it('should include timeout in state when provided', async () => {
+ const ctx = createMockContext();
+
+ const result = await groupManagementExecutor.executeTask(
+ { agentId: 'agent-1', task: 'Do something', timeout: 60000 },
+ ctx,
+ );
+
+ expect(result.success).toBe(true);
+ expect(result.state).toEqual({
+ agentId: 'agent-1',
+ task: 'Do something',
+ timeout: 60000,
+ type: 'executeTask',
+ });
+ });
+ });
+
+ describe('interrupt', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it('should successfully interrupt a running task', async () => {
+ mockInterruptTask.mockResolvedValue({
+ operationId: 'op-123',
+ success: true,
+ });
+
+ const ctx = createMockContext();
+
+ const result = await groupManagementExecutor.interrupt({ taskId: 'thread-123' }, ctx);
+
+ expect(result.success).toBe(true);
+ expect(result.content).toBe('Task thread-123 has been cancelled successfully');
+ expect(result.state).toEqual({
+ cancelled: true,
+ operationId: 'op-123',
+ taskId: 'thread-123',
+ });
+ expect(mockInterruptTask).toHaveBeenCalledWith({
+ threadId: 'thread-123',
+ });
+ });
+
+ it('should handle failed interrupt attempt', async () => {
+ mockInterruptTask.mockResolvedValue({
+ success: false,
+ });
+
+ const ctx = createMockContext();
+
+ const result = await groupManagementExecutor.interrupt({ taskId: 'thread-123' }, ctx);
+
+ expect(result.success).toBe(false);
+ expect(result.content).toBe('Failed to cancel task thread-123');
+ expect(result.state).toEqual({
+ cancelled: false,
+ taskId: 'thread-123',
+ });
+ });
+
+ it('should handle API errors gracefully', async () => {
+ mockInterruptTask.mockRejectedValue(new Error('Task not found'));
+
+ const ctx = createMockContext();
+
+ const result = await groupManagementExecutor.interrupt({ taskId: 'thread-123' }, ctx);
+
+ expect(result.success).toBe(false);
+ expect(result.content).toBe('Failed to interrupt task: Task not found');
+ });
+ });
+});
diff --git a/packages/builtin-tool-group-management/src/executor.ts b/packages/builtin-tool-group-management/src/executor.ts
new file mode 100644
index 00000000000..a9f5e4ee0fe
--- /dev/null
+++ b/packages/builtin-tool-group-management/src/executor.ts
@@ -0,0 +1,423 @@
+/* eslint-disable @typescript-eslint/no-unused-vars */
+/**
+ * Lobe Group Management Executor
+ *
+ * Handles all group management tool calls for multi-agent orchestration.
+ */
+import {
+ BroadcastParams,
+ CreateAgentParams,
+ CreateWorkflowParams,
+ DelegateParams,
+ ExecuteTaskParams,
+ GetAgentInfoParams,
+ GroupManagementApiName,
+ GroupManagementIdentifier,
+ InterruptParams,
+ InviteAgentParams,
+ RemoveAgentParams,
+ SearchAgentParams,
+ SpeakParams,
+ SummarizeParams,
+ VoteParams,
+} from '@lobechat/builtin-tool-group-management';
+import { formatAgentProfile } from '@lobechat/prompts';
+import { BaseExecutor, type BuiltinToolContext, type BuiltinToolResult } from '@lobechat/types';
+
+import { agentService } from '@/services/agent';
+import { agentGroupSelectors, useAgentGroupStore } from '@/store/agentGroup';
+
+class GroupManagementExecutor extends BaseExecutor<typeof GroupManagementApiName> {
+ readonly identifier = GroupManagementIdentifier;
+ protected readonly apiEnum = GroupManagementApiName;
+
+ // ==================== Member Management ====================
+
+ searchAgent = async (
+ params: SearchAgentParams,
+ _ctx: BuiltinToolContext,
+ ): Promise<BuiltinToolResult> => {
+ const { query, limit = 10, source = 'user' } = params;
+
+ // Currently only support searching user's own agents
+ // Community search can be added in the future
+ if (source === 'community') {
+ return {
+ content:
+ 'Community agent search is not yet supported. Please use source="user" to search your own agents.',
+ state: { agents: [], source, total: 0 },
+ success: true,
+ };
+ }
+
+ try {
+ const results = await agentService.queryAgents({ keyword: query, limit });
+
+ const agents = results.map((agent) => ({
+ avatar: agent.avatar,
+ description: agent.description,
+ id: agent.id,
+ title: agent.title,
+ }));
+
+ const total = agents.length;
+
+ if (total === 0) {
+ return {
+ content: query
+ ? `No agents found matching "${query}".`
+ : 'No agents found. You can create a new agent or search with different keywords.',
+ state: { agents: [], query, total: 0 },
+ success: true,
+ };
+ }
+
+ // Format agents list for LLM consumption
+ const agentList = agents
+ .map(
+ (a, i) =>
+ `${i + 1}. ${a.title || 'Untitled'} (ID: ${a.id})${a.description ? ` - ${a.description}` : ''}`,
+ )
+ .join('\n');
+
+ return {
+ content: `Found ${total} agent${total > 1 ? 's' : ''} matching "${query}":\n${agentList}`,
+ state: { agents, query, total },
+ success: true,
+ };
+ } catch (error) {
+ return {
+ content: `Failed to search agents: ${error instanceof Error ? error.message : 'Unknown error'}`,
+ success: false,
+ };
+ }
+ };
+
+ inviteAgent = async (
+ params: InviteAgentParams,
+ ctx: BuiltinToolContext,
+ ): Promise<BuiltinToolResult> => {
+ const { groupId } = ctx;
+
+ if (!groupId) {
+ return { content: 'No group context available', success: false };
+ }
+
+ try {
+ await useAgentGroupStore.getState().addAgentsToGroup(groupId, [params.agentId]);
+
+ return {
+ content: `Agent "${params.agentId}" has been invited to the group.`,
+ state: { agentId: params.agentId, type: 'inviteAgent' },
+ success: true,
+ };
+ } catch (error) {
+ return {
+ content: `Failed to invite agent "${params.agentId}": ${error instanceof Error ? error.message : 'Unknown error'}`,
+ success: false,
+ };
+ }
+ };
+
+ createAgent = async (
+ params: CreateAgentParams,
+ ctx: BuiltinToolContext,
+ ): Promise<BuiltinToolResult> => {
+ const { groupId } = ctx;
+
+ if (!groupId) {
+ return { content: 'No group context available', success: false };
+ }
+
+ try {
+ // Create a virtual agent (agents created by supervisor are virtual)
+ const result = await agentService.createAgent({
+ config: {
+ avatar: params.avatar,
+ description: params.description,
+ systemRole: params.systemRole,
+ title: params.title,
+ virtual: true,
+ },
+ groupId,
+ });
+
+ if (!result.agentId) {
+ return { content: 'Failed to create agent: No agent ID returned', success: false };
+ }
+
+ return {
+ content: `Agent "${params.title}" has been created and added to the group.`,
+ state: { agentId: result.agentId, title: params.title, type: 'createAgent' },
+ success: true,
+ };
+ } catch (error) {
+ return {
+ content: `Failed to create agent: ${error instanceof Error ? error.message : 'Unknown error'}`,
+ success: false,
+ };
+ }
+ };
+
+ removeAgent = async (
+ params: RemoveAgentParams,
+ ctx: BuiltinToolContext,
+ ): Promise<BuiltinToolResult> => {
+ const { groupId } = ctx;
+
+ if (!groupId) {
+ return { content: 'No group context available', success: false };
+ }
+
+ try {
+ await useAgentGroupStore.getState().removeAgentFromGroup(groupId, params.agentId);
+
+ return {
+ content: `Agent "${params.agentId}" has been removed from the group.`,
+ state: { agentId: params.agentId, type: 'removeAgent' },
+ success: true,
+ };
+ } catch (error) {
+ return {
+ content: `Failed to remove agent "${params.agentId}": ${error instanceof Error ? error.message : 'Unknown error'}`,
+ success: false,
+ };
+ }
+ };
+
+ getAgentInfo = async (
+ params: GetAgentInfoParams,
+ ctx: BuiltinToolContext,
+ ): Promise<BuiltinToolResult> => {
+ const { groupId } = ctx;
+
+ if (!groupId) {
+ return {
+ content: JSON.stringify({ error: 'No group context available', success: false }),
+ success: false,
+ };
+ }
+
+ const agent = agentGroupSelectors.getAgentByIdFromGroup(
+ groupId,
+ params.agentId,
+ )(useAgentGroupStore.getState());
+
+ if (!agent) {
+ return { content: `Agent "${params.agentId}" not found in this group`, success: false };
+ }
+
+ // Return formatted agent profile for the supervisor
+ return { content: formatAgentProfile(agent), state: agent, success: true };
+ };
+
+ // ==================== Communication Coordination ====================
+
+ speak = async (params: SpeakParams, ctx: BuiltinToolContext): Promise<BuiltinToolResult> => {
+ // Register afterCompletion callback to trigger orchestration after AgentRuntime completes
+ // This avoids race conditions with message updates
+ if (ctx.groupOrchestration && ctx.agentId && ctx.registerAfterCompletion) {
+ ctx.registerAfterCompletion(() =>
+ ctx.groupOrchestration!.triggerSpeak({
+ agentId: params.agentId,
+ instruction: params.instruction,
+ skipCallSupervisor: params.skipCallSupervisor,
+ supervisorAgentId: ctx.agentId!,
+ }),
+ );
+ }
+
+ // Returns stop: true to indicate the supervisor should stop and let agent respond
+ return {
+ content: `Triggered agent "${params.agentId}" to respond.`,
+ state: {
+ agentId: params.agentId,
+ instruction: params.instruction,
+ skipCallSupervisor: params.skipCallSupervisor,
+ type: 'speak',
+ },
+ stop: true,
+ success: true,
+ };
+ };
+
+ broadcast = async (
+ params: BroadcastParams,
+ ctx: BuiltinToolContext,
+ ): Promise<BuiltinToolResult> => {
+ // Register afterCompletion callback to trigger orchestration after AgentRuntime completes
+ // This avoids race conditions with message updates
+ if (ctx.groupOrchestration && ctx.agentId && ctx.registerAfterCompletion) {
+ ctx.registerAfterCompletion(() =>
+ ctx.groupOrchestration!.triggerBroadcast({
+ agentIds: params.agentIds,
+ instruction: params.instruction,
+ skipCallSupervisor: params.skipCallSupervisor,
+ supervisorAgentId: ctx.agentId!,
+ toolMessageId: ctx.messageId, // Pass tool message ID for correct parent-child relationship
+ }),
+ );
+ }
+
+ // Returns stop: true to trigger multiple agents to respond in parallel
+ // metadata.agentCouncil marks this tool message for parallel display in conversation-flow
+ return {
+ content: `Triggered broadcast to agents: ${params.agentIds.join(', ')}.`,
+ metadata: { agentCouncil: true },
+ state: {
+ agentIds: params.agentIds,
+ instruction: params.instruction,
+ skipCallSupervisor: params.skipCallSupervisor,
+ type: 'broadcast',
+ },
+ stop: true,
+ success: true,
+ };
+ };
+
+ delegate = async (
+ params: DelegateParams,
+ ctx: BuiltinToolContext,
+ ): Promise<BuiltinToolResult> => {
+ // Register afterCompletion callback to trigger orchestration after AgentRuntime completes
+ // This avoids race conditions with message updates
+ if (ctx.groupOrchestration && ctx.agentId && ctx.registerAfterCompletion) {
+ ctx.registerAfterCompletion(() =>
+ ctx.groupOrchestration!.triggerDelegate({
+ agentId: params.agentId,
+ reason: params.reason,
+ supervisorAgentId: ctx.agentId!,
+ }),
+ );
+ }
+
+ // The supervisor exits and delegated agent takes control
+ return {
+ content: `Delegated conversation control to agent "${params.agentId}".`,
+ state: {
+ agentId: params.agentId,
+ reason: params.reason,
+ type: 'delegate',
+ },
+ stop: true,
+ success: true,
+ };
+ };
+
+ // ==================== Task Execution ====================
+
+ executeTask = async (
+ params: ExecuteTaskParams,
+ ctx: BuiltinToolContext,
+ ): Promise<BuiltinToolResult> => {
+ // Register afterCompletion callback to trigger async task execution after AgentRuntime completes
+ // This follows the same pattern as speak/broadcast - trigger mode, not blocking
+ if (ctx.groupOrchestration && ctx.agentId && ctx.registerAfterCompletion) {
+ ctx.registerAfterCompletion(() =>
+ ctx.groupOrchestration!.triggerExecuteTask({
+ agentId: params.agentId,
+ skipCallSupervisor: params.skipCallSupervisor,
+ supervisorAgentId: ctx.agentId!,
+ task: params.task,
+ timeout: params.timeout,
+ toolMessageId: ctx.messageId,
+ }),
+ );
+ }
+
+ // Returns stop: true to indicate the supervisor should stop and let the task execute
+ return {
+ content: `Triggered async task for agent "${params.agentId}".`,
+ state: {
+ agentId: params.agentId,
+ skipCallSupervisor: params.skipCallSupervisor,
+ task: params.task,
+ timeout: params.timeout,
+ type: 'executeTask',
+ },
+ stop: true,
+ success: true,
+ };
+ };
+
+ interrupt = async (
+ params: InterruptParams,
+ _ctx: BuiltinToolContext,
+ ): Promise<BuiltinToolResult> => {
+ const { taskId } = params;
+
+ try {
+ const { aiAgentService } = await import('@/services/aiAgent');
+ const result = await aiAgentService.interruptTask({
+ threadId: taskId,
+ });
+
+ if (result.success) {
+ return {
+ content: `Task ${taskId} has been cancelled successfully`,
+ state: { cancelled: true, operationId: result.operationId, taskId },
+ success: true,
+ };
+ }
+
+ return {
+ content: `Failed to cancel task ${taskId}`,
+ state: { cancelled: false, taskId },
+ success: false,
+ };
+ } catch (error) {
+ return {
+ content: `Failed to interrupt task: ${error instanceof Error ? error.message : 'Unknown error'}`,
+ success: false,
+ };
+ }
+ };
+
+ // ==================== Context Management ====================
+
+ summarize = async (
+ params: SummarizeParams,
+ _ctx: BuiltinToolContext,
+ ): Promise<BuiltinToolResult> => {
+ // TODO: Implement conversation summarization
+ return {
+ content: JSON.stringify({
+ focus: params.focus,
+ message: 'Summarization not yet implemented',
+ preserveRecent: params.preserveRecent,
+ }),
+ success: true,
+ };
+ };
+
+ // ==================== Flow Control ====================
+
+ createWorkflow = async (
+ params: CreateWorkflowParams,
+ _ctx: BuiltinToolContext,
+ ): Promise<BuiltinToolResult> => {
+ // TODO: Implement workflow creation
+ return {
+ content: JSON.stringify({
+ message: 'Workflow creation not yet implemented',
+ name: params.name,
+ steps: params.steps,
+ }),
+ success: true,
+ };
+ };
+
+ vote = async (params: VoteParams, _ctx: BuiltinToolContext): Promise<BuiltinToolResult> => {
+ // TODO: Implement voting mechanism
+ return {
+ content: JSON.stringify({
+ message: 'Voting not yet implemented',
+ options: params.options,
+ question: params.question,
+ }),
+ success: true,
+ };
+ };
+}
+
+export const groupManagementExecutor = new GroupManagementExecutor();
diff --git a/packages/builtin-tool-group-management/src/index.ts b/packages/builtin-tool-group-management/src/index.ts
new file mode 100644
index 00000000000..95ce02e077d
--- /dev/null
+++ b/packages/builtin-tool-group-management/src/index.ts
@@ -0,0 +1,3 @@
+export * from './manifest';
+export * from './systemRole';
+export * from './types';
diff --git a/packages/builtin-tool-group-management/src/manifest.ts b/packages/builtin-tool-group-management/src/manifest.ts
new file mode 100644
index 00000000000..b0538483891
--- /dev/null
+++ b/packages/builtin-tool-group-management/src/manifest.ts
@@ -0,0 +1,371 @@
+import type { BuiltinToolManifest } from '@lobechat/types';
+
+import { systemPrompt } from './systemRole';
+import { GroupManagementApiName } from './types';
+
+export const GroupManagementIdentifier = 'lobe-group-management';
+
+export const GroupManagementManifest: BuiltinToolManifest = {
+ /* eslint-disable sort-keys-fix/sort-keys-fix */
+ api: [
+ // ==================== Member Management ====================
+ {
+ description:
+ "Search for agents that can be invited to the group. Returns agents from both the user's collection and the community marketplace. Use this to find suitable agents before inviting them.",
+ name: GroupManagementApiName.searchAgent,
+ parameters: {
+ properties: {
+ query: {
+ description:
+ 'Search query to find agents by name, description, or capabilities. Leave empty to browse all available agents.',
+ type: 'string',
+ },
+ source: {
+ description:
+ 'Filter by agent source: "user" for user\'s own agents, "community" for marketplace agents, or omit for all sources.',
+ enum: ['user', 'community'],
+ type: 'string',
+ },
+ limit: {
+ default: 10,
+ description: 'Maximum number of results to return (default: 10, max: 20).',
+ maximum: 20,
+ minimum: 1,
+ type: 'number',
+ },
+ },
+ required: [],
+ type: 'object',
+ },
+ },
+ {
+ description:
+ 'Invite an agent to join the current group. The agent must be found via searchAgent first. Once invited, the agent becomes available for orchestration.',
+ name: GroupManagementApiName.inviteAgent,
+ humanIntervention: 'always',
+ parameters: {
+ properties: {
+ agentId: {
+ description: 'The ID of the agent to invite. Get this from searchAgent results.',
+ type: 'string',
+ },
+ },
+ required: ['agentId'],
+ type: 'object',
+ },
+ },
+ {
+ description:
+ 'Create a new agent dynamically based on user requirements and add it to the group. Use this when no existing agent matches the needed expertise.',
+ humanIntervention: 'always',
+ name: GroupManagementApiName.createAgent,
+ parameters: {
+ properties: {
+ title: {
+ description: 'The display name for the new agent.',
+ type: 'string',
+ },
+ description: {
+ description: 'A brief description of what this agent does and its expertise.',
+ type: 'string',
+ },
+ systemRole: {
+ description:
+ "The system prompt that defines the agent's behavior, personality, and capabilities.",
+ type: 'string',
+ },
+ avatar: {
+ description: "An emoji or image URL for the agent's avatar (optional).",
+ type: 'string',
+ },
+ },
+ required: ['title', 'systemRole'],
+ type: 'object',
+ },
+ },
+ {
+ description:
+ 'Remove an agent from the current group. The agent will no longer be available for orchestration but is not deleted from the system.',
+ name: GroupManagementApiName.removeAgent,
+ humanIntervention: 'always',
+ parameters: {
+ properties: {
+ agentId: {
+ description: 'The ID of the agent to remove from the group.',
+ type: 'string',
+ },
+ },
+ required: ['agentId'],
+ type: 'object',
+ },
+ },
+ {
+ description:
+ 'Get detailed information about a specific agent, including their capabilities, available tools, and configuration.',
+ name: GroupManagementApiName.getAgentInfo,
+ parameters: {
+ properties: {
+ agentId: {
+ description: 'The ID of the agent to get information about.',
+ type: 'string',
+ },
+ },
+ required: ['agentId'],
+ type: 'object',
+ },
+ },
+
+ // ==================== Communication Coordination ====================
+ {
+ description:
+ "Let a specific agent speak in the conversation. This is synchronous and waits for the agent's response. Use this for focused, single-agent interactions.",
+ name: GroupManagementApiName.speak,
+ parameters: {
+ properties: {
+ agentId: {
+ description: 'The ID of the agent who should respond.',
+ type: 'string',
+ },
+ instruction: {
+ description:
+ "Optional instruction or context to guide the agent's response. If omitted, the agent responds based on conversation context.",
+ type: 'string',
+ },
+ skipCallSupervisor: {
+ default: false,
+ description:
+ 'If true, the orchestration will end after this agent responds, without calling the supervisor again. Use this when the user explicitly requests a specific agent (e.g., "@Designer, help me review this UI") and no further orchestration is needed.',
+ type: 'boolean',
+ },
+ },
+ required: ['agentId'],
+ type: 'object',
+ },
+ },
+ {
+ description:
+ 'Let multiple agents respond simultaneously. All specified agents will generate responses in parallel, providing multiple perspectives. Use this when diverse viewpoints are valuable.',
+ name: GroupManagementApiName.broadcast,
+ parameters: {
+ properties: {
+ agentIds: {
+ description: 'Array of agent IDs who should respond.',
+ items: { type: 'string' },
+ type: 'array',
+ },
+ instruction: {
+ description:
+ 'Optional shared instruction for all agents. Each agent interprets it based on their role.',
+ type: 'string',
+ },
+ skipCallSupervisor: {
+ default: false,
+ description:
+ 'If true, the orchestration will end after all agents respond, without calling the supervisor again. Use this when the user explicitly requests specific agents and no further orchestration is needed.',
+ type: 'boolean',
+ },
+ },
+ required: ['agentIds'],
+ type: 'object',
+ },
+ },
+ // {
+ // description:
+ // 'Delegate the conversation entirely to a specific agent. The supervisor exits orchestration mode and the delegated agent takes full control until explicitly recalled.',
+ // name: GroupManagementApiName.delegate,
+ // parameters: {
+ // properties: {
+ // agentId: {
+ // description: 'The ID of the agent to delegate the conversation to.',
+ // type: 'string',
+ // },
+ // reason: {
+ // description:
+ // 'Brief explanation of why delegation is appropriate. Helps maintain conversation continuity.',
+ // type: 'string',
+ // },
+ // },
+ // required: ['agentId'],
+ // type: 'object',
+ // },
+ // },
+
+ // ==================== Task Execution ====================
+ {
+ description:
+ 'Assign an asynchronous task to an agent. The task runs in the background and results are returned to the conversation context upon completion. Ideal for longer operations.',
+ name: GroupManagementApiName.executeTask,
+ humanIntervention: 'always',
+ parameters: {
+ properties: {
+ agentId: {
+ description: 'The ID of the agent to execute the task.',
+ type: 'string',
+ },
+ task: {
+ description:
+ 'Clear description of the task to perform. Be specific about expected deliverables.',
+ type: 'string',
+ },
+ timeout: {
+ default: 1_800_000,
+ description:
+ 'Maximum time in milliseconds to wait for task completion (default: 1800000, 30 minutes).',
+ type: 'number',
+ },
+ skipCallSupervisor: {
+ default: false,
+ description:
+ 'If true, the orchestration will end after the task completes, without calling the supervisor again. Use this when the task is the final action needed.',
+ type: 'boolean',
+ },
+ },
+ required: ['agentId', 'task'],
+ type: 'object',
+ },
+ },
+ {
+ description:
+ 'Interrupt a running agent task. Use this to stop a task that is taking too long or is no longer needed.',
+ humanIntervention: 'always',
+ name: GroupManagementApiName.interrupt,
+ parameters: {
+ properties: {
+ taskId: {
+ description: 'The ID of the task to interrupt (returned by executeTask).',
+ type: 'string',
+ },
+ },
+ required: ['taskId'],
+ type: 'object',
+ },
+ },
+
+ // ==================== Context Management ====================
+ // {
+ // description:
+ // 'Summarize the current conversation and compress the context. Useful for long conversations to maintain relevant information while reducing token usage.',
+ // name: GroupManagementApiName.summarize,
+ // parameters: {
+ // properties: {
+ // focus: {
+ // description:
+ // 'Optional focus area for the summary (e.g., "decisions made", "action items", "key points").',
+ // type: 'string',
+ // },
+ // preserveRecent: {
+ // default: 5,
+ // description: 'Number of recent messages to preserve in full detail (default: 5).',
+ // minimum: 0,
+ // type: 'number',
+ // },
+ // },
+ // required: [],
+ // type: 'object',
+ // },
+ // },
+
+ // ==================== Flow Control ====================
+ // {
+ // description:
+ // 'Define a multi-agent collaboration workflow. Creates a structured sequence of agent interactions for complex tasks.',
+ // name: GroupManagementApiName.createWorkflow,
+ // parameters: {
+ // properties: {
+ // name: {
+ // description: 'A descriptive name for this workflow.',
+ // type: 'string',
+ // },
+ // steps: {
+ // description: 'Array of workflow steps defining agent participation order.',
+ // items: {
+ // properties: {
+ // agentId: {
+ // description: 'The ID of the agent for this step.',
+ // type: 'string',
+ // },
+ // instruction: {
+ // description: 'Specific instruction for this step.',
+ // type: 'string',
+ // },
+ // waitForCompletion: {
+ // default: true,
+ // description: 'Whether to wait for this step before proceeding (default: true).',
+ // type: 'boolean',
+ // },
+ // },
+ // required: ['agentId'],
+ // type: 'object',
+ // },
+ // type: 'array',
+ // },
+ // autoExecute: {
+ // default: false,
+ // description:
+ // 'Whether to immediately execute the workflow after creation (default: false).',
+ // type: 'boolean',
+ // },
+ // },
+ // required: ['name', 'steps'],
+ // type: 'object',
+ // },
+ // },
+ {
+ description:
+ 'Initiate a vote among agents on a specific question or decision. Each agent provides their choice and reasoning.',
+ name: GroupManagementApiName.vote,
+ parameters: {
+ properties: {
+ question: {
+ description: 'The question or decision to vote on.',
+ type: 'string',
+ },
+ options: {
+ description: 'Array of voting options.',
+ items: {
+ properties: {
+ id: {
+ description: 'Unique identifier for this option.',
+ type: 'string',
+ },
+ label: {
+ description: 'Display label for this option.',
+ type: 'string',
+ },
+ description: {
+ description: 'Optional description explaining this option.',
+ type: 'string',
+ },
+ },
+ required: ['id', 'label'],
+ type: 'object',
+ },
+ type: 'array',
+ },
+ voterAgentIds: {
+ description: 'Array of agent IDs who should vote. If omitted, all group members vote.',
+ items: { type: 'string' },
+ type: 'array',
+ },
+ requireReasoning: {
+ default: true,
+ description: 'Whether agents must provide reasoning for their vote (default: true).',
+ type: 'boolean',
+ },
+ },
+ required: ['question', 'options'],
+ type: 'object',
+ },
+ },
+ ],
+ identifier: GroupManagementIdentifier,
+ meta: {
+ avatar: '👥',
+ description: 'Orchestrate and manage multi-agent group conversations',
+ title: 'Group Management',
+ },
+ systemRole: systemPrompt,
+ type: 'builtin',
+};
+
+export { GroupManagementApiName } from './types';
diff --git a/packages/builtin-tool-group-management/src/systemRole.ts b/packages/builtin-tool-group-management/src/systemRole.ts
new file mode 100644
index 00000000000..22ccc5f2ca2
--- /dev/null
+++ b/packages/builtin-tool-group-management/src/systemRole.ts
@@ -0,0 +1,199 @@
+/**
+ * System role for Group Management tool
+ *
+ * This provides guidance for the Group Supervisor on how to effectively use
+ * the group management tools to orchestrate multi-agent conversations.
+ */
+export const systemPrompt = `You have a Group Management tool with capabilities to orchestrate multi-agent group conversations. You can manage group members, coordinate communication, execute tasks, and control conversation flow.
+
+<user_intent_analysis>
+Before responding, analyze the user's intent to determine if agent participation is appropriate:
+
+**Signals for Group Discussion (PROACTIVELY invoke agents):**
+- Open-ended questions: "What do you think about...", "Any ideas for...", "How should we..."
+- Requests for multiple perspectives: "I want to hear different opinions", "Let's discuss..."
+- Creative/brainstorming tasks: "Let's brainstorm...", "Help me come up with..."
+- Complex problems that benefit from diverse expertise
+- Implicit collaboration cues: questions in a multi-agent group context generally expect group participation
+- Ambiguous questions where multiple agents have relevant expertise
+
+**Signals for Single Agent or No Agent (be selective):**
+- Explicit single agent request: "Ask [Agent Name] to...", "Let [Agent Name] answer..."
+- Simple factual questions you can answer directly
+- Follow-up questions to a specific agent's previous response
+- Administrative requests (add/remove agents, etc.)
+
+**Default Behavior:**
+- When in doubt in a group context, LEAN TOWARDS invoking relevant agents
+- Users created a group specifically for collaborative discussions - respect that intent
+- A brief group response is better than no response when the topic is relevant to group members
+</user_intent_analysis>
+
+<core_capabilities>
+You have access to a set of tools to manage and orchestrate the agent group:
+
+**Member Management:**
+1. **searchAgent**: Search for agents that can be invited to the group. Returns agents from user's collection and community marketplace.
+2. **inviteAgent**: Invite an agent to join the current group. The agent must be found via searchAgent first.
+3. **createAgent**: Dynamically create a new agent based on requirements and add it to the group.
+4. **removeAgent**: Remove an agent from the current group. The agent is not deleted, just removed from this group.
+5. **getAgentInfo**: Get detailed information about an agent, including capabilities, tools, and configuration.
+
+**Communication Coordination:**
+6. **speak**: Let a specific agent respond. Synchronous and waits for the agent's response.
+7. **broadcast**: Let multiple agents respond simultaneously in parallel.
+
+**Task Execution:**
+8. **executeTask**: Assign an asynchronous task to an agent. Results return to context upon completion.
+9. **interrupt**: Stop a running agent task by its task ID.
+
+**Context Management:**
+10. **summarize**: Summarize and compress the current conversation context.
+
+**Flow Control:**
+11. **vote**: Initiate a vote among agents on a specific question or decision.
+</core_capabilities>
+
+<workflow_analysis>
+Before orchestrating agent responses, analyze the task to determine the optimal execution pattern:
+
+## Task Pattern Recognition
+
+**Parallel Pattern (use \`broadcast\`)** - When order doesn't matter and diverse perspectives are valuable:
+- **Brainstorming**: Generate ideas from multiple angles simultaneously
+ - Example: "Let's brainstorm marketing strategies" → broadcast to Marketing, Product, Design agents
+- **Independent Review**: Multiple experts review the same artifact
+ - Example: "Review this code" → broadcast to Security, Performance, Architecture agents
+- **Gathering Opinions**: Collect viewpoints without sequential influence
+ - Example: "What do you think about this proposal?" → broadcast to all relevant agents
+- **Parallel Analysis**: Analyze different aspects of a problem simultaneously
+ - Example: "Analyze this business plan" → broadcast to Finance, Legal, Operations agents
+
+**Sequential Pattern (use \`speak\`)** - When there's logical dependency or build-upon relationship:
+- **Expert Chain**: Each expert builds on previous expert's output
+ - Example: AI Expert proposes algorithm → Product Manager analyzes feasibility → Designer creates UX → Engineer estimates effort
+- **Refinement Flow**: Iteratively improve a solution
+ - Example: Writer drafts → Editor refines → Proofreader finalizes
+- **Validation Pipeline**: Each step validates/extends previous
+ - Example: Architect designs → Security reviews → DevOps validates deployment
+- **Decision Funnel**: Progressively narrow down options
+ - Example: Researcher provides options → Analyst evaluates → Decision-maker selects
+
+**Hybrid Pattern** - Complex tasks may need both:
+1. First \`broadcast\` to gather diverse inputs
+2. Then sequential \`speak\` to synthesize and refine
+3. Finally \`vote\` if consensus is needed
+
+## Decision Framework
+
+Ask yourself:
+1. **Does output from Agent A inform Agent B's response?** → Sequential (speak)
+2. **Are agents analyzing the same thing independently?** → Parallel (broadcast)
+3. **Is there a natural workflow order (design→implement→test)?** → Sequential
+4. **Do we need diverse perspectives without cross-influence?** → Parallel
+5. **Is the task creative/generative with no single right answer?** → Parallel
+6. **Does quality depend on building upon previous work?** → Sequential
+</workflow_analysis>
+
+<workflow_examples>
+## Example 1: Product Feature Discussion (Hybrid)
+User: "We need to design a new notification system"
+
+Analysis: Creative task requiring multiple perspectives, then synthesis.
+Workflow:
+1. \`broadcast\` to [Product, Design, Engineering]: "Share your initial thoughts on requirements and constraints"
+2. \`speak\` to Design: "Based on the inputs, propose a UX approach"
+3. \`speak\` to Engineering: "Evaluate the technical feasibility of the design proposal"
+4. \`speak\` to Product: "Synthesize the discussion into a final recommendation"
+
+## Example 2: Code Review (Parallel)
+User: "Review this authentication implementation"
+
+Analysis: Independent expert reviews, order doesn't matter.
+Workflow:
+\`broadcast\` to [Security, Architecture, Performance]: "Review this code from your expertise perspective"
+
+## Example 3: Technical Solution Design (Sequential)
+User: "Design a recommendation algorithm for our e-commerce platform"
+
+Analysis: Clear dependency chain - algorithm design → product fit → implementation plan.
+Workflow:
+1. \`speak\` to AI Expert: "Propose recommendation algorithm approaches"
+2. \`speak\` to Product Manager: "Analyze which approach best fits our user needs and business goals"
+3. \`speak\` to Data Engineer: "Design the data pipeline for the selected approach"
+4. \`speak\` to Backend Engineer: "Outline the implementation architecture"
+
+## Example 4: Research Task (Parallel then Sequential)
+User: "Research best practices for microservices migration"
+
+Analysis: Gather independent research, then synthesize.
+Workflow:
+1. \`broadcast\` to [Architect, DevOps, Security]: "Research best practices from your domain"
+2. \`speak\` to Architect: "Synthesize findings into a unified migration strategy"
+
+## Example 5: Decision Making (Sequential then Vote)
+User: "Should we use PostgreSQL or MongoDB for this project?"
+
+Analysis: Need informed opinions, then democratic decision.
+Workflow:
+1. \`speak\` to Database Expert: "Compare PostgreSQL vs MongoDB for our use case"
+2. \`speak\` to Backend Engineer: "Add implementation perspective"
+3. \`vote\` with question: "Which database should we use?" options: [PostgreSQL, MongoDB]
+</workflow_examples>
+
+<tool_usage_guidelines>
+- For finding agents to invite: Use 'searchAgent'. Provide:
+ - 'query' (Optional): Search keywords to find agents by name, description, or capabilities.
+ - 'source' (Optional): Filter by "user" (user's agents) or "community" (marketplace).
+ - 'limit' (Optional): Maximum results to return (default: 10, max: 20).
+- For inviting agents: Use 'inviteAgent'. Provide:
+ - 'agentId': The ID of the agent from searchAgent results.
+- For creating new agents: Use 'createAgent'. Provide:
+ - 'title': Display name for the new agent.
+ - 'systemRole': The system prompt defining the agent's behavior and capabilities.
+ - 'description' (Optional): Brief description of what the agent does.
+ - 'avatar' (Optional): Emoji or image URL for the agent's avatar.
+- For removing agents: Use 'removeAgent'. Provide:
+ - 'agentId': The ID of the agent to remove.
+- For agent details: Use 'getAgentInfo'. Provide:
+ - 'agentId': The ID of the agent to get information about.
+- For single agent response: Use 'speak'. Provide:
+ - 'agentId': The ID of the agent who should respond.
+ - 'instruction' (Optional): Guidance for the agent's response.
+- For parallel responses: Use 'broadcast'. Provide:
+ - 'agentIds': Array of agent IDs who should respond.
+ - 'instruction' (Optional): Shared instruction for all agents.
+- For async tasks: Use 'executeTask'. Provide:
+ - 'agentId': The ID of the agent to execute the task.
+ - 'task': Clear description of the task with expected deliverables.
+ - 'timeout' (Optional): Maximum time in milliseconds (default: 60000).
+- For stopping tasks: Use 'interrupt'. Provide:
+ - 'taskId': The ID of the task to interrupt (from executeTask).
+- For context compression: Use 'summarize'. Provide:
+ - 'focus' (Optional): Focus area like "decisions made", "action items", "key points".
+ - 'preserveRecent' (Optional): Number of recent messages to keep in full (default: 5).
+- For voting: Use 'vote'. Provide:
+ - 'question': The question or decision to vote on.
+ - 'options': Array of option objects with 'id', 'label', and optional 'description'.
+ - 'voterAgentIds' (Optional): Specific agents to vote. If omitted, all members vote.
+ - 'requireReasoning' (Optional): Whether agents must explain their vote (default: true).
+</tool_usage_guidelines>
+
+<orchestration_best_practices>
+- **Analyze before acting**: Always determine the task pattern (parallel/sequential/hybrid) before calling tools.
+- **Match expertise to queries**: Use getAgentInfo to understand agent capabilities before selecting.
+- **Respect dependencies**: If Agent B needs Agent A's output, always use sequential speak, never broadcast.
+- **Preserve independence**: For brainstorming and opinion gathering, use broadcast to avoid anchoring bias.
+- **Consolidate requests**: Combine related queries rather than multiple separate calls.
+- **Proactive summarization**: Use summarize before context grows too large.
+- **Balanced participation**: Ensure no single agent dominates unless the task requires it.
+- **Explain your orchestration**: Briefly tell the user why you chose a particular pattern.
+</orchestration_best_practices>
+
+<response_format>
+- When starting orchestration, briefly explain your analysis: "This is a [parallel/sequential/hybrid] task because..."
+- When referencing agents in responses, use clear identification: "Agent [Name] (ID: [agentId])".
+- When reporting task status, include the taskId for reference.
+- When presenting vote results, show each agent's choice and reasoning.
+- After all agents respond, synthesize the key points and actionable conclusions.
+</response_format>`;
diff --git a/packages/builtin-tool-group-management/src/types.ts b/packages/builtin-tool-group-management/src/types.ts
new file mode 100644
index 00000000000..bd41573e890
--- /dev/null
+++ b/packages/builtin-tool-group-management/src/types.ts
@@ -0,0 +1,200 @@
+/* eslint-disable sort-keys-fix/sort-keys-fix */
+
+/**
+ * API names for Group Management tool
+ */
+export const GroupManagementApiName = {
+ // ==================== Member Management ====================
+ /** Search for agents that can be invited to the group */
+ searchAgent: 'searchAgent',
+ /** Invite an agent to join the group */
+ inviteAgent: 'inviteAgent',
+ /** Create a new agent and add it to the group */
+ createAgent: 'createAgent',
+ /** Remove an agent from the group */
+ removeAgent: 'removeAgent',
+ /** Get detailed information about an agent */
+ getAgentInfo: 'getAgentInfo',
+
+ // ==================== Communication Coordination ====================
+ /** Let a specific agent speak (synchronous, immediate response) */
+ speak: 'speak',
+ /** Let multiple agents speak simultaneously (parallel responses) */
+ broadcast: 'broadcast',
+ /** Delegate the conversation to a specific agent (supervisor exits) */
+ delegate: 'delegate',
+
+ // ==================== Task Execution ====================
+ /** Let an agent execute a task asynchronously */
+ executeTask: 'executeTask',
+ /** Interrupt a running agent task */
+ interrupt: 'interrupt',
+
+ // ==================== Context Management ====================
+ /** Summarize and compress the current conversation context */
+ summarize: 'summarize',
+
+ // ==================== Flow Control ====================
+ /** Define a multi-agent collaboration workflow */
+ createWorkflow: 'createWorkflow',
+ /** Let multiple agents vote on a decision */
+ vote: 'vote',
+} as const;
+
+export type GroupManagementApiNameType =
+ (typeof GroupManagementApiName)[keyof typeof GroupManagementApiName];
+
+// ==================== Member Management Params ====================
+
+export interface SearchAgentParams {
+ limit?: number;
+ query?: string;
+ source?: 'user' | 'community';
+}
+
+export interface InviteAgentParams {
+ agentId: string;
+}
+
+export interface CreateAgentParams {
+ avatar?: string;
+ description?: string;
+ systemRole: string;
+ title: string;
+}
+
+export interface RemoveAgentParams {
+ agentId: string;
+}
+
+export interface GetAgentInfoParams {
+ agentId: string;
+}
+
+// ==================== Communication Params ====================
+
+export interface SpeakParams {
+ agentId: string;
+ instruction?: string;
+ /**
+ * If true, the orchestration will end after this agent responds,
+ * without calling the supervisor again.
+ * Use this when the user explicitly requests a specific agent
+ * and no further orchestration is needed.
+ */
+ skipCallSupervisor?: boolean;
+}
+
+export interface BroadcastParams {
+ agentIds: string[];
+ instruction?: string;
+ /**
+ * If true, the orchestration will end after agents respond,
+ * without calling the supervisor again.
+ * Use this when the user explicitly requests specific agents
+ * and no further orchestration is needed.
+ */
+ skipCallSupervisor?: boolean;
+}
+
+export interface DelegateParams {
+ agentId: string;
+ reason?: string;
+}
+
+// ==================== Task Execution Params ====================
+
+export interface ExecuteTaskParams {
+ agentId: string;
+ /**
+ * If true, the orchestration will end after the task completes,
+ * without calling the supervisor again.
+ * Use this when the task is the final action needed.
+ */
+ skipCallSupervisor?: boolean;
+ task: string;
+ timeout?: number;
+}
+
+export interface InterruptParams {
+ taskId: string;
+}
+
+// ==================== Context Management Params ====================
+
+export interface SummarizeParams {
+ focus?: string;
+ preserveRecent?: number;
+}
+
+// ==================== Flow Control Params ====================
+
+export interface WorkflowStep {
+ agentId: string;
+ instruction?: string;
+ waitForCompletion?: boolean;
+}
+
+export interface CreateWorkflowParams {
+ autoExecute?: boolean;
+ name: string;
+ steps: WorkflowStep[];
+}
+
+export interface VoteOption {
+ description?: string;
+ id: string;
+ label: string;
+}
+
+export interface VoteParams {
+ options: VoteOption[];
+ question: string;
+ requireReasoning?: boolean;
+ voterAgentIds?: string[];
+}
+
+// ==================== Result Types ====================
+
+export interface AgentSearchResult {
+ avatar?: string;
+ description?: string;
+ id: string;
+ source: 'user' | 'community';
+ title: string;
+}
+
+export interface VoteResult {
+ agentId: string;
+ reasoning?: string;
+ selectedOptionId: string;
+}
+
+// ==================== State Types for UI Rendering ====================
+
+export type ExecuteTaskStatus =
+ | 'processing'
+ | 'completed'
+ | 'failed'
+ | 'cancelled'
+ | 'timeout'
+ | 'interrupted';
+
+export interface ExecuteTaskState {
+ cost?: { total: number };
+ error?: string;
+ status: ExecuteTaskStatus;
+ stepCount?: number;
+ threadId: string;
+ usage?: {
+ completion_tokens?: number;
+ prompt_tokens?: number;
+ total_tokens?: number;
+ };
+}
+
+export interface InterruptState {
+ cancelled: boolean;
+ operationId?: string;
+ taskId: string;
+}
diff --git a/packages/builtin-tool-gtd/package.json b/packages/builtin-tool-gtd/package.json
new file mode 100644
index 00000000000..b9dd36fe37a
--- /dev/null
+++ b/packages/builtin-tool-gtd/package.json
@@ -0,0 +1,23 @@
+{
+ "name": "@lobechat/builtin-tool-gtd",
+ "version": "1.0.0",
+ "private": true,
+ "exports": {
+ ".": "./src/index.ts",
+ "./executor": "./src/executor/index.ts",
+ "./client": "./src/client/index.ts"
+ },
+ "main": "./src/index.ts",
+ "dependencies": {
+ "@lobechat/prompts": "workspace:*",
+ "@lobechat/types": "workspace:*",
+ "lucide-react": "*",
+ "react": "*",
+ "react-layout-kit": "*"
+ },
+ "peerDependencies": {
+ "@lobehub/ui": "*",
+ "antd": "*",
+ "antd-style": "*"
+ }
+}
diff --git a/packages/builtin-tool-gtd/src/client/Intervention/AddTodo.tsx b/packages/builtin-tool-gtd/src/client/Intervention/AddTodo.tsx
new file mode 100644
index 00000000000..41f82c75640
--- /dev/null
+++ b/packages/builtin-tool-gtd/src/client/Intervention/AddTodo.tsx
@@ -0,0 +1,56 @@
+'use client';
+
+import { BuiltinInterventionProps } from '@lobechat/types';
+import { createStyles } from 'antd-style';
+import isEqual from 'fast-deep-equal';
+import { memo, useCallback } from 'react';
+import { Flexbox } from 'react-layout-kit';
+
+import type { CreateTodosParams, TodoItem } from '../../types';
+import { SortableTodoList } from '../components';
+
+const useStyles = createStyles(({ css, token }) => ({
+ container: css`
+ padding-block: 12px;
+ padding-inline: 4px;
+ border-radius: ${token.borderRadius}px;
+ background: ${token.colorFillQuaternary};
+ `,
+}));
+
+const AddTodoIntervention = memo<BuiltinInterventionProps<CreateTodosParams>>(
+ ({ args, onArgsChange, registerBeforeApprove }) => {
+ const { styles } = useStyles();
+
+ // Handle both formats:
+ // - Initial AI input: { adds: string[] } (from AI)
+ // - After user edit: { items: TodoItem[] } (saved format)
+ const defaultItems: TodoItem[] =
+ args?.items || args?.adds?.map((text) => ({ completed: false, text })) || [];
+
+ const handleSave = useCallback(
+ async (items: TodoItem[]) => {
+ console.log('[AddTodoIntervention] handleSave called with', items.length, 'items');
+ await onArgsChange?.({ items });
+ console.log('[AddTodoIntervention] onArgsChange completed');
+ },
+ [onArgsChange],
+ );
+
+ return (
+ <Flexbox className={styles.container}>
+ <SortableTodoList
+ defaultItems={defaultItems}
+ onSave={handleSave}
+ placeholder="Add a todo item..."
+ registerBeforeApprove={registerBeforeApprove}
+ />
+ </Flexbox>
+ );
+ },
+ isEqual,
+);
+
+AddTodoIntervention.displayName = 'AddTodoIntervention';
+
+export default AddTodoIntervention;
diff --git a/packages/builtin-tool-gtd/src/client/Intervention/ClearTodos.tsx b/packages/builtin-tool-gtd/src/client/Intervention/ClearTodos.tsx
new file mode 100644
index 00000000000..6e98dd20969
--- /dev/null
+++ b/packages/builtin-tool-gtd/src/client/Intervention/ClearTodos.tsx
@@ -0,0 +1,79 @@
+'use client';
+
+import { BuiltinInterventionProps } from '@lobechat/types';
+import { Radio, RadioChangeEvent } from 'antd';
+import { createStyles } from 'antd-style';
+import { Trash2 } from 'lucide-react';
+import { memo, useCallback, useState } from 'react';
+import { Flexbox } from 'react-layout-kit';
+
+import type { ClearTodosParams } from '../../types';
+
+const useStyles = createStyles(({ css, token }) => ({
+ container: css`
+ padding: 12px;
+ border-radius: ${token.borderRadius}px;
+ background: ${token.colorFillTertiary};
+ `,
+ dangerText: css`
+ font-size: 13px;
+ color: ${token.colorError};
+ `,
+ header: css`
+ color: ${token.colorWarning};
+ `,
+ label: css`
+ font-size: 13px;
+ color: ${token.colorTextSecondary};
+ `,
+ normalText: css`
+ font-size: 13px;
+ `,
+}));
+
+/**
+ * ClearTodos Intervention component
+ * Allows users to choose between clearing completed items or all items
+ */
+const ClearTodosIntervention = memo<BuiltinInterventionProps<ClearTodosParams>>(
+ ({ args, onArgsChange }) => {
+ const { styles } = useStyles();
+ const [mode, setMode] = useState<ClearTodosParams['mode']>(args?.mode || 'completed');
+
+ const handleModeChange = useCallback(
+ async (e: RadioChangeEvent) => {
+ const newMode = e.target.value as ClearTodosParams['mode'];
+ setMode(newMode);
+ await onArgsChange?.({ mode: newMode });
+ },
+ [onArgsChange],
+ );
+
+ return (
+ <Flexbox gap={12}>
+ <Flexbox align="center" className={styles.header} gap={8} horizontal>
+ <Trash2 size={16} />
+ <span style={{ fontSize: 14, fontWeight: 500 }}>Clear Todo Items</span>
+ </Flexbox>
+
+ <Flexbox className={styles.container} gap={8}>
+ <span className={styles.label}>Choose what to clear:</span>
+ <Radio.Group onChange={handleModeChange} value={mode}>
+ <Flexbox gap={8}>
+ <Radio value="completed">
+ <span className={styles.normalText}>Clear completed items only</span>
+ </Radio>
+ <Radio value="all">
+ <span className={styles.dangerText}>Clear all items (including pending)</span>
+ </Radio>
+ </Flexbox>
+ </Radio.Group>
+ </Flexbox>
+ </Flexbox>
+ );
+ },
+);
+
+ClearTodosIntervention.displayName = 'ClearTodosIntervention';
+
+export default ClearTodosIntervention;
diff --git a/packages/builtin-tool-gtd/src/client/Intervention/index.ts b/packages/builtin-tool-gtd/src/client/Intervention/index.ts
new file mode 100644
index 00000000000..8bc91ec374e
--- /dev/null
+++ b/packages/builtin-tool-gtd/src/client/Intervention/index.ts
@@ -0,0 +1,19 @@
+import { BuiltinIntervention } from '@lobechat/types';
+
+import { GTDApiName } from '../../types';
+import AddTodoIntervention from './AddTodo';
+import ClearTodosIntervention from './ClearTodos';
+
+/**
+ * GTD Tool Intervention Components Registry
+ *
+ * Intervention components allow users to review and modify tool parameters
+ * before the tool is executed.
+ */
+export const GTDInterventions: Record<string, BuiltinIntervention> = {
+ [GTDApiName.createTodos]: AddTodoIntervention as BuiltinIntervention,
+ [GTDApiName.clearTodos]: ClearTodosIntervention as BuiltinIntervention,
+};
+
+export { default as AddTodoIntervention } from './AddTodo';
+export { default as ClearTodosIntervention } from './ClearTodos';
diff --git a/packages/builtin-tool-gtd/src/client/Render/TodoList.tsx b/packages/builtin-tool-gtd/src/client/Render/TodoList.tsx
new file mode 100644
index 00000000000..82a6bf5d60d
--- /dev/null
+++ b/packages/builtin-tool-gtd/src/client/Render/TodoList.tsx
@@ -0,0 +1,124 @@
+'use client';
+
+import { BuiltinRenderProps } from '@lobechat/types';
+import { createStyles } from 'antd-style';
+import { CheckCircle2, Circle } from 'lucide-react';
+import { memo } from 'react';
+import { Flexbox } from 'react-layout-kit';
+
+import type { TodoItem, TodoList as TodoListType } from '../../types';
+
+export interface TodoListRenderState {
+ todos?: TodoListType;
+}
+
+// Styles matching TodoItemRow in SortableTodoList
+const useStyles = createStyles(({ css, token }) => ({
+ checkbox: css`
+ flex-shrink: 0;
+ color: ${token.colorTextQuaternary};
+ `,
+ checkboxChecked: css`
+ color: ${token.colorSuccess};
+ `,
+ // Outer container - matches AddTodoIntervention container style
+ container: css`
+ padding-block: 12px;
+ padding-inline: 4px;
+ border-radius: ${token.borderRadius}px;
+ background: ${token.colorFillQuaternary};
+ `,
+ // Placeholder to match DragHandle width
+ dragHandlePlaceholder: css`
+ flex-shrink: 0;
+ width: 16px;
+ height: 24px;
+ `,
+ // Item row - matches TodoItemRow itemRow style
+ itemRow: css`
+ padding-block: 2px;
+ border-block-end: 1px solid ${token.colorBorderSecondary};
+
+ &:last-child {
+ border-block-end: none;
+ }
+ `,
+ text: css`
+ flex: 1;
+ font-size: 14px;
+ line-height: 32px;
+ `,
+ textChecked: css`
+ color: ${token.colorTextQuaternary};
+ text-decoration: line-through;
+ `,
+}));
+
+interface ReadOnlyTodoItemProps {
+ completed: boolean;
+ text: string;
+}
+
+/**
+ * Read-only todo item row, matching the style of TodoItemRow in SortableTodoList
+ */
+const ReadOnlyTodoItem = memo<ReadOnlyTodoItemProps>(({ text, completed }) => {
+ const { styles, cx } = useStyles();
+
+ const CheckIcon = completed ? CheckCircle2 : Circle;
+
+ return (
+ <Flexbox align="center" className={styles.itemRow} gap={8} horizontal width="100%">
+ <div className={styles.dragHandlePlaceholder} />
+ <CheckIcon className={cx(styles.checkbox, completed && styles.checkboxChecked)} size={16} />
+ <span className={cx(styles.text, completed && styles.textChecked)}>{text}</span>
+ </Flexbox>
+ );
+});
+
+ReadOnlyTodoItem.displayName = 'ReadOnlyTodoItem';
+
+interface TodoListUIProps {
+ items: TodoItem[];
+}
+
+/**
+ * Read-only TodoList UI component
+ * Displays todo items in a style matching the editable SortableTodoList
+ */
+const TodoListUI = memo<TodoListUIProps>(({ items }) => {
+ const { styles } = useStyles();
+
+ if (items.length === 0) {
+ return null;
+ }
+
+ return (
+ // Outer container with background - matches AddTodoIntervention
+ <Flexbox className={styles.container}>
+ <Flexbox width="100%">
+ {items.map((item, index) => (
+ <ReadOnlyTodoItem completed={item.completed} key={index} text={item.text} />
+ ))}
+ </Flexbox>
+ </Flexbox>
+ );
+});
+
+TodoListUI.displayName = 'TodoListUI';
+
+/**
+ * TodoList Render component for GTD tool
+ * Read-only display of todo items matching the style of AddTodoIntervention
+ */
+const TodoListRender = memo<BuiltinRenderProps<unknown, TodoListRenderState>>(({ pluginState }) => {
+ const todos = pluginState?.todos;
+ const items: TodoItem[] = todos?.items || [];
+
+ return <TodoListUI items={items} />;
+});
+
+TodoListRender.displayName = 'TodoListRender';
+
+export default TodoListRender;
+export { TodoListUI };
diff --git a/packages/builtin-tool-gtd/src/client/Render/index.ts b/packages/builtin-tool-gtd/src/client/Render/index.ts
new file mode 100644
index 00000000000..0df13cc6cf9
--- /dev/null
+++ b/packages/builtin-tool-gtd/src/client/Render/index.ts
@@ -0,0 +1,20 @@
+import { GTDApiName } from '../../types';
+import TodoListRender from './TodoList';
+
+/**
+ * GTD Tool Render Components Registry
+ *
+ * All todo operations use the same TodoList render component
+ * which displays the current state of the todo list.
+ */
+export const GTDRenders = {
+ // All todo operations render the same TodoList UI
+ [GTDApiName.createTodos]: TodoListRender,
+ [GTDApiName.updateTodos]: TodoListRender,
+ [GTDApiName.completeTodos]: TodoListRender,
+ [GTDApiName.removeTodos]: TodoListRender,
+ [GTDApiName.clearTodos]: TodoListRender,
+};
+
+export type { TodoListRenderState } from './TodoList';
+export { default as TodoListRender, TodoListUI } from './TodoList';
diff --git a/packages/builtin-tool-gtd/src/client/components/SortableTodoList/AddItemRow.tsx b/packages/builtin-tool-gtd/src/client/components/SortableTodoList/AddItemRow.tsx
new file mode 100644
index 00000000000..dca8d9f2d1f
--- /dev/null
+++ b/packages/builtin-tool-gtd/src/client/components/SortableTodoList/AddItemRow.tsx
@@ -0,0 +1,116 @@
+'use client';
+
+import { ActionIcon } from '@lobehub/ui';
+import { Input, InputRef } from 'antd';
+import { createStyles } from 'antd-style';
+import { Circle, Plus } from 'lucide-react';
+import { ChangeEvent, KeyboardEvent, memo, useCallback, useEffect, useRef } from 'react';
+import { Flexbox } from 'react-layout-kit';
+
+import { ADD_ITEM_ID, useTodoListStore } from './store';
+
+const useStyles = createStyles(({ css, token }) => ({
+ addRow: css`
+ padding-block: 6px;
+ `,
+ circle: css`
+ flex-shrink: 0;
+ color: ${token.colorTextQuaternary};
+ `,
+ // Placeholder to match DragHandle width (28px from SortableList.DragHandle small size)
+ dragHandlePlaceholder: css`
+ flex-shrink: 0;
+ width: 16px;
+ height: 24px;
+ `,
+}));
+
+interface AddItemRowProps {
+ className?: string;
+ placeholder?: string;
+ showDragHandle?: boolean;
+}
+
+const AddItemRow = memo<AddItemRowProps>(
+ ({ placeholder = 'Add a todo item...', showDragHandle = true, className }) => {
+ const { styles, cx } = useStyles();
+ const inputRef = useRef<InputRef>(null);
+
+ const newItemText = useTodoListStore((s) => s.newItemText);
+ const focusedId = useTodoListStore((s) => s.focusedId);
+ const cursorPosition = useTodoListStore((s) => s.cursorPosition);
+ const setNewItemText = useTodoListStore((s) => s.setNewItemText);
+ const addItem = useTodoListStore((s) => s.addItem);
+ const focusPrevItem = useTodoListStore((s) => s.focusPrevItem);
+ const setFocusedId = useTodoListStore((s) => s.setFocusedId);
+
+ // Focus input when focusedId changes to this input and restore cursor position
+ const prevFocusedIdRef = useRef<string | null>(null);
+ useEffect(() => {
+ // Only restore cursor when focus changes TO this input (not on every cursorPosition change)
+ if (focusedId === ADD_ITEM_ID && prevFocusedIdRef.current !== ADD_ITEM_ID) {
+ const input = inputRef.current?.input;
+ if (input) {
+ input.focus();
+ // Clamp cursor position to text length
+ const pos = Math.min(cursorPosition, newItemText.length);
+ input.setSelectionRange(pos, pos);
+ }
+ }
+ prevFocusedIdRef.current = focusedId;
+ }, [focusedId, cursorPosition, newItemText.length]);
+
+ const handleChange = useCallback(
+ (e: ChangeEvent<HTMLInputElement>) => {
+ setNewItemText(e.target.value);
+ },
+ [setNewItemText],
+ );
+
+ const handleKeyDown = useCallback(
+ (e: KeyboardEvent<HTMLInputElement>) => {
+ const input = e.currentTarget;
+ const cursorPos = input.selectionStart ?? 0;
+
+ if (e.key === 'Enter') {
+ e.preventDefault();
+ addItem();
+ } else if (e.key === 'ArrowUp' || (e.key === 'Tab' && e.shiftKey)) {
+ e.preventDefault();
+ focusPrevItem(ADD_ITEM_ID, cursorPos);
+ } else if (e.key === 'Tab' && !e.shiftKey) {
+ // Prevent default tab behavior to keep focus in the todo list
+ e.preventDefault();
+ }
+ },
+ [addItem, focusPrevItem],
+ );
+
+ const handleFocus = useCallback(() => {
+ setFocusedId(ADD_ITEM_ID);
+ }, [setFocusedId]);
+
+ return (
+ <Flexbox align="center" className={cx(styles.addRow, className)} gap={4} horizontal>
+ {showDragHandle && <div className={styles.dragHandlePlaceholder} />}
+ <Circle className={styles.circle} size={16} />
+ <Input
+ onChange={handleChange}
+ onFocus={handleFocus}
+ onKeyDown={handleKeyDown}
+ placeholder={placeholder}
+ ref={inputRef}
+ size="small"
+ style={{ flex: 1 }}
+ value={newItemText}
+ variant="borderless"
+ />
+ <ActionIcon icon={Plus} onClick={addItem} size="small" tabIndex={-1} />
+ </Flexbox>
+ );
+ },
+);
+
+AddItemRow.displayName = 'AddItemRow';
+
+export default AddItemRow;
diff --git a/packages/builtin-tool-gtd/src/client/components/SortableTodoList/SortableItem.tsx b/packages/builtin-tool-gtd/src/client/components/SortableTodoList/SortableItem.tsx
new file mode 100644
index 00000000000..f578e371e39
--- /dev/null
+++ b/packages/builtin-tool-gtd/src/client/components/SortableTodoList/SortableItem.tsx
@@ -0,0 +1,23 @@
+'use client';
+
+import { SortableList } from '@lobehub/ui';
+import { memo } from 'react';
+
+import TodoItemRow from './TodoItemRow';
+
+interface SortableItemProps {
+ id: string;
+ placeholder?: string;
+}
+
+const SortableItem = memo<SortableItemProps>(({ id, placeholder }) => {
+ return (
+ <SortableList.Item id={id} style={{ padding: 0 }}>
+ <TodoItemRow id={id} placeholder={placeholder} />
+ </SortableList.Item>
+ );
+});
+
+SortableItem.displayName = 'SortableItem';
+
+export default SortableItem;
diff --git a/packages/builtin-tool-gtd/src/client/components/SortableTodoList/TodoItemRow.tsx b/packages/builtin-tool-gtd/src/client/components/SortableTodoList/TodoItemRow.tsx
new file mode 100644
index 00000000000..6c699c024e0
--- /dev/null
+++ b/packages/builtin-tool-gtd/src/client/components/SortableTodoList/TodoItemRow.tsx
@@ -0,0 +1,176 @@
+'use client';
+
+import { ActionIcon, SortableList } from '@lobehub/ui';
+import { Input, InputRef } from 'antd';
+import { createStyles } from 'antd-style';
+import { CheckCircle2, Circle, Trash2 } from 'lucide-react';
+import { ChangeEvent, KeyboardEvent, memo, useCallback, useEffect, useRef } from 'react';
+import { Flexbox } from 'react-layout-kit';
+
+import { useTodoListStore } from './store';
+
+const useStyles = createStyles(({ css, token }) => ({
+ checkbox: css`
+ cursor: pointer;
+ flex-shrink: 0;
+ color: ${token.colorTextQuaternary};
+ transition: color 0.2s;
+
+ &:hover {
+ color: ${token.colorPrimary};
+ }
+ `,
+ checkboxChecked: css`
+ color: ${token.colorSuccess};
+
+ &:hover {
+ color: ${token.colorSuccessHover};
+ }
+ `,
+ deleteIcon: css`
+ flex-shrink: 0;
+ opacity: 0;
+ transition: opacity 0.2s;
+ `,
+ dragHandle: css`
+ flex-shrink: 0;
+ width: 16px !important;
+ opacity: 0;
+ transition: opacity 0.2s;
+ `,
+ itemRow: css`
+ padding-block: 2px;
+ border-block-end: 1px solid ${token.colorBorderSecondary};
+
+ &:last-child {
+ border-block-end: none;
+ }
+
+ &:hover {
+ .drag-handle,
+ .delete-icon {
+ opacity: 1;
+ }
+ }
+ `,
+ textChecked: css`
+ color: ${token.colorTextQuaternary};
+ text-decoration: line-through;
+ `,
+}));
+
+interface TodoItemRowProps {
+ id: string;
+ placeholder?: string;
+}
+
+const TodoItemRow = memo<TodoItemRowProps>(({ id, placeholder = 'Enter todo item...' }) => {
+ const { styles, cx } = useStyles();
+ const inputRef = useRef<InputRef>(null);
+
+ // Find item by stable id
+ const item = useTodoListStore((s) => s.items.find((item) => item.id === id));
+ const text = item?.text ?? '';
+ const completed = item?.completed ?? false;
+
+ const focusedId = useTodoListStore((s) => s.focusedId);
+ const cursorPosition = useTodoListStore((s) => s.cursorPosition);
+ const updateItem = useTodoListStore((s) => s.updateItem);
+ const deleteItem = useTodoListStore((s) => s.deleteItem);
+ const toggleItem = useTodoListStore((s) => s.toggleItem);
+ const focusPrevItem = useTodoListStore((s) => s.focusPrevItem);
+ const focusNextItem = useTodoListStore((s) => s.focusNextItem);
+ const setFocusedId = useTodoListStore((s) => s.setFocusedId);
+
+ // Focus input when focusedId changes to this item and restore cursor position
+ const prevFocusedIdRef = useRef<string | null>(null);
+ useEffect(() => {
+ // Only restore cursor when focus changes TO this item (not on every cursorPosition change)
+ if (focusedId === id && prevFocusedIdRef.current !== id) {
+ const input = inputRef.current?.input;
+ if (input) {
+ input.focus();
+ // Clamp cursor position to text length
+ const pos = Math.min(cursorPosition, text.length);
+ input.setSelectionRange(pos, pos);
+ }
+ }
+ prevFocusedIdRef.current = focusedId;
+ }, [focusedId, id, cursorPosition, text.length]);
+
+ const handleChange = useCallback(
+ (e: ChangeEvent<HTMLInputElement>) => {
+ updateItem(id, e.target.value);
+ },
+ [id, updateItem],
+ );
+
+ const handleKeyDown = useCallback(
+ (e: KeyboardEvent<HTMLInputElement>) => {
+ const input = e.currentTarget;
+ const cursorPos = input.selectionStart ?? 0;
+
+ if (e.key === 'Backspace' && text === '') {
+ e.preventDefault();
+ focusPrevItem(id, cursorPos);
+ deleteItem(id);
+ } else if (e.key === 'ArrowUp' || (e.key === 'Tab' && e.shiftKey)) {
+ e.preventDefault();
+ focusPrevItem(id, cursorPos);
+ } else if (e.key === 'ArrowDown' || (e.key === 'Tab' && !e.shiftKey)) {
+ e.preventDefault();
+ focusNextItem(id, cursorPos);
+ }
+ },
+ [id, text, deleteItem, focusPrevItem, focusNextItem],
+ );
+
+ const handleFocus = useCallback(() => {
+ setFocusedId(id);
+ }, [id, setFocusedId]);
+
+ const handleDelete = useCallback(() => {
+ focusPrevItem(id, 0);
+ deleteItem(id);
+ }, [id, deleteItem, focusPrevItem]);
+
+ const handleToggle = useCallback(() => {
+ toggleItem(id);
+ }, [id, toggleItem]);
+
+ const CheckIcon = completed ? CheckCircle2 : Circle;
+
+ return (
+ <Flexbox align="center" className={styles.itemRow} gap={4} horizontal width="100%">
+ <SortableList.DragHandle className={cx(styles.dragHandle, 'drag-handle')} size="small" />
+ <CheckIcon
+ className={cx(styles.checkbox, completed && styles.checkboxChecked)}
+ onClick={handleToggle}
+ size={16}
+ />
+ <Input
+ className={cx(completed && styles.textChecked)}
+ onChange={handleChange}
+ onFocus={handleFocus}
+ onKeyDown={handleKeyDown}
+ placeholder={placeholder}
+ ref={inputRef}
+ size="small"
+ style={{ flex: 1 }}
+ value={text}
+ variant="borderless"
+ />
+ <ActionIcon
+ className={cx(styles.deleteIcon, 'delete-icon')}
+ icon={Trash2}
+ onClick={handleDelete}
+ size="small"
+ tabIndex={-1}
+ />
+ </Flexbox>
+ );
+});
+
+TodoItemRow.displayName = 'TodoItemRow';
+
+export default TodoItemRow;
diff --git a/packages/builtin-tool-gtd/src/client/components/SortableTodoList/TodoList.tsx b/packages/builtin-tool-gtd/src/client/components/SortableTodoList/TodoList.tsx
new file mode 100644
index 00000000000..755e56a3503
--- /dev/null
+++ b/packages/builtin-tool-gtd/src/client/components/SortableTodoList/TodoList.tsx
@@ -0,0 +1,71 @@
+'use client';
+
+import { SortableList } from '@lobehub/ui';
+import { createStyles } from 'antd-style';
+import { memo, useCallback } from 'react';
+import { Flexbox } from 'react-layout-kit';
+
+import AddItemRow from './AddItemRow';
+import SortableItem from './SortableItem';
+import { TodoListItem, useTodoListStore } from './store';
+
+const useStyles = createStyles(({ css }) => ({
+ container: css`
+ width: 100%;
+ `,
+}));
+
+interface TodoListProps {
+ placeholder?: string;
+}
+
+const TodoList = memo<TodoListProps>(({ placeholder }) => {
+ const { styles } = useStyles();
+
+ const items = useTodoListStore((s) => s.items);
+ const sortItems = useTodoListStore((s) => s.sortItems);
+
+ const handleSortEnd = useCallback(
+ (sorted: unknown[]) => {
+ sortItems(sorted as TodoListItem[]);
+ },
+ [sortItems],
+ );
+
+ const renderItem = useCallback(
+ (item: TodoListItem) => {
+ return <SortableItem id={item.id} placeholder={placeholder} />;
+ },
+ [placeholder],
+ );
+
+ // Empty state
+ if (items.length === 0) {
+ return (
+ <Flexbox className={styles.container} gap={0}>
+ <AddItemRow placeholder={placeholder} showDragHandle={false} />
+ </Flexbox>
+ );
+ }
+
+ // Use items length as key to force remount when items change structure
+ // This fixes DragOverlay position issues after drag operations
+ const listKey = items.map((i) => i.id).join('-');
+
+ return (
+ <Flexbox paddingBlock={8} paddingInline={4} width={'100%'}>
+ <SortableList
+ items={items}
+ key={listKey}
+ onChange={handleSortEnd}
+ renderItem={renderItem}
+ style={{ marginBottom: 0 }}
+ />
+ <AddItemRow placeholder={placeholder} />
+ </Flexbox>
+ );
+});
+
+TodoList.displayName = 'TodoList';
+
+export default TodoList;
diff --git a/packages/builtin-tool-gtd/src/client/components/SortableTodoList/index.tsx b/packages/builtin-tool-gtd/src/client/components/SortableTodoList/index.tsx
new file mode 100644
index 00000000000..9f940ef617c
--- /dev/null
+++ b/packages/builtin-tool-gtd/src/client/components/SortableTodoList/index.tsx
@@ -0,0 +1,69 @@
+'use client';
+
+import { useUnmount } from 'ahooks';
+import { memo, useEffect, useMemo } from 'react';
+
+import type { TodoItem } from '../../../types';
+import TodoList from './TodoList';
+import { TodoListStoreContext, createTodoListStore } from './store';
+
+export type { TodoListItem } from './store';
+
+export interface SortableTodoListProps {
+ /**
+ * Default items for initialization (TodoItem array)
+ */
+ defaultItems?: TodoItem[];
+ /**
+ * Callback when items change (debounced, 3s after last change)
+ * This is called automatically after content changes
+ */
+ onSave?: (items: TodoItem[]) => void | Promise<void>;
+ /**
+ * Placeholder text for inputs
+ */
+ placeholder?: string;
+ /**
+ * Register a callback to flush pending saves before approval
+ * Used by intervention components to ensure all edits are saved before approve action
+ * @param id - Unique identifier for the callback
+ * @param callback - The callback to execute
+ * @returns Cleanup function to unregister
+ */
+ registerBeforeApprove?: (id: string, callback: () => void | Promise<void>) => () => void;
+}
+
+const SortableTodoList = memo<SortableTodoListProps>(
+ ({ defaultItems = [], placeholder = 'Enter todo item...', onSave, registerBeforeApprove }) => {
+ // Create store instance once with onSave callback
+ const store = useMemo(() => createTodoListStore(defaultItems, onSave), []);
+
+ // Register saveNow as beforeApprove callback (async, waits for save to complete)
+ useEffect(() => {
+ if (registerBeforeApprove) {
+ const unregister = registerBeforeApprove('sortable-todo-list', async () => {
+ console.log('trigger save');
+ await store.getState().saveNow();
+ console.log('trigger save successful');
+ });
+ // Cleanup: unregister on unmount
+ return unregister;
+ }
+ }, [registerBeforeApprove, store]);
+
+ // Flush pending saves on unmount to ensure no data loss
+ useUnmount(() => {
+ store.getState().flushSave();
+ });
+
+ return (
+ <TodoListStoreContext.Provider value={store}>
+ <TodoList placeholder={placeholder} />
+ </TodoListStoreContext.Provider>
+ );
+ },
+);
+
+SortableTodoList.displayName = 'SortableTodoList';
+
+export default SortableTodoList;
diff --git a/packages/builtin-tool-gtd/src/client/components/SortableTodoList/store/actions.ts b/packages/builtin-tool-gtd/src/client/components/SortableTodoList/store/actions.ts
new file mode 100644
index 00000000000..aabdfa40ad2
--- /dev/null
+++ b/packages/builtin-tool-gtd/src/client/components/SortableTodoList/store/actions.ts
@@ -0,0 +1,177 @@
+import { debounce } from 'es-toolkit/compat';
+
+import type { TodoItem } from '../../../../types';
+import { AUTO_SAVE_DELAY, AUTO_SAVE_MAX_WAIT, initialState } from './initialState';
+import type { StoreInternals, TodoListItem, TodoListStore } from './types';
+import { ADD_ITEM_ID } from './types';
+
+let idCounter = 0;
+export const generateId = () => `todo-${Date.now()}-${idCounter++}`;
+
+// Reset counter for testing
+export const resetIdCounter = () => {
+ idCounter = 0;
+};
+
+type SetState = (
+ partial: Partial<TodoListStore> | ((state: TodoListStore) => Partial<TodoListStore>),
+) => void;
+type GetState = () => TodoListStore;
+
+export const createActions = (
+ set: SetState,
+ get: GetState,
+ internals: StoreInternals,
+ defaultItems: TodoItem[],
+): TodoListStore => {
+ // Save implementation (used by both debounced and immediate save)
+ const performSave = async () => {
+ console.log('[performSave] called, onSave:', !!internals.onSave);
+ if (!internals.onSave) return;
+
+ const { items, isDirty } = get();
+ console.log('[performSave] isDirty:', isDirty, 'items:', items.length);
+ if (!isDirty) return;
+
+ set({ saveStatus: 'saving' });
+
+ try {
+ // Convert TodoListItem[] to TodoItem[] (remove id)
+ const todoItems: TodoItem[] = items.map(({ completed, text }) => ({ completed, text }));
+ console.log('[performSave] calling onSave with', todoItems.length, 'items');
+ await internals.onSave(todoItems);
+ console.log('[performSave] onSave completed');
+ set({ isDirty: false, saveStatus: 'saved' });
+ } catch {
+ set({ saveStatus: 'error' });
+ }
+ };
+
+ internals.debouncedSave = debounce(performSave, AUTO_SAVE_DELAY, {
+ leading: false,
+ maxWait: AUTO_SAVE_MAX_WAIT,
+ trailing: true,
+ });
+
+ // Helper to mark dirty and trigger debounced save
+ const markDirtyAndSave = () => {
+ set({ isDirty: true });
+ internals.debouncedSave?.();
+ };
+
+ return {
+ ...initialState,
+ items: defaultItems.map((item) => ({ ...item, id: generateId() })),
+
+ /* eslint-disable sort-keys-fix/sort-keys-fix */
+ addItem: () => {
+ const { items, newItemText } = get();
+ if (!newItemText.trim()) return;
+
+ set({
+ items: [...items, { completed: false, id: generateId(), text: newItemText.trim() }],
+ newItemText: '',
+ });
+ markDirtyAndSave();
+ },
+
+ deleteItem: (id: string) => {
+ const { items } = get();
+ set({
+ items: items.filter((item) => item.id !== id),
+ });
+ markDirtyAndSave();
+ },
+
+ flushSave: () => {
+ internals.debouncedSave?.flush();
+ },
+
+ saveNow: async () => {
+ // Cancel pending debounced save to avoid double-save
+ internals.debouncedSave?.cancel();
+ // Force save current items (skip isDirty check)
+ if (!internals.onSave) return;
+
+ const { items } = get();
+ set({ saveStatus: 'saving' });
+
+ try {
+ const todoItems: TodoItem[] = items.map(({ completed, text }) => ({ completed, text }));
+ console.log('[saveNow] force saving', todoItems.length, 'items');
+ await internals.onSave(todoItems);
+ console.log('[saveNow] save completed');
+ set({ isDirty: false, saveStatus: 'saved' });
+
+ setTimeout(() => {
+ set((state) => (state.saveStatus === 'saved' ? { saveStatus: 'idle' } : {}));
+ }, 1500);
+ } catch {
+ set({ saveStatus: 'error' });
+ }
+ },
+
+ focusNextItem: (currentId: string | null, cursorPos: number) => {
+ const { items } = get();
+ if (currentId === null) return;
+
+ if (currentId === ADD_ITEM_ID) return; // Already at the end
+
+ const currentIndex = items.findIndex((item) => item.id === currentId);
+ if (currentIndex === -1) return;
+
+ if (currentIndex < items.length - 1) {
+ set({ cursorPosition: cursorPos, focusedId: items[currentIndex + 1].id });
+ } else {
+ // At last item, go to add input
+ set({ cursorPosition: cursorPos, focusedId: ADD_ITEM_ID });
+ }
+ },
+
+ focusPrevItem: (currentId: string | null, cursorPos: number) => {
+ const { items } = get();
+ if (items.length === 0) return;
+
+ if (currentId === ADD_ITEM_ID) {
+ // From add input, go to last item
+ set({ cursorPosition: cursorPos, focusedId: items.at(-1)?.id ?? null });
+ } else if (currentId) {
+ const currentIndex = items.findIndex((item) => item.id === currentId);
+ if (currentIndex > 0) {
+ set({ cursorPosition: cursorPos, focusedId: items[currentIndex - 1].id });
+ }
+ }
+ },
+
+ setFocusedId: (id: string | null) => {
+ set({ focusedId: id });
+ },
+
+ setNewItemText: (text: string) => {
+ set({ newItemText: text });
+ },
+
+ sortItems: (sortedItems: TodoListItem[]) => {
+ set({ items: sortedItems });
+ markDirtyAndSave();
+ },
+
+ toggleItem: (id: string) => {
+ const { items } = get();
+ set({
+ items: items.map((item) =>
+ item.id === id ? { ...item, completed: !item.completed } : item,
+ ),
+ });
+ markDirtyAndSave();
+ },
+
+ updateItem: (id: string, text: string) => {
+ const { items } = get();
+ set({
+ items: items.map((item) => (item.id === id ? { ...item, text } : item)),
+ });
+ markDirtyAndSave();
+ },
+ };
+};
diff --git a/packages/builtin-tool-gtd/src/client/components/SortableTodoList/store/index.ts b/packages/builtin-tool-gtd/src/client/components/SortableTodoList/store/index.ts
new file mode 100644
index 00000000000..e8edcc0a1a9
--- /dev/null
+++ b/packages/builtin-tool-gtd/src/client/components/SortableTodoList/store/index.ts
@@ -0,0 +1,38 @@
+import { createContext, useContext } from 'react';
+import { StoreApi, createStore, useStore } from 'zustand';
+
+import type { TodoItem } from '../../../../types';
+import { createActions } from './actions';
+import type { StoreInternals, TodoListStore } from './types';
+
+export type { TodoListItem, TodoListStore } from './types';
+export { ADD_ITEM_ID } from './types';
+
+export const createTodoListStore = (
+ defaultItems: TodoItem[] = [],
+ onSave?: (items: TodoItem[]) => void | Promise<void>,
+) => {
+ // Internal state for debounce (not part of zustand state)
+ const internals: StoreInternals = {
+ debouncedSave: null,
+ onSave: onSave ?? null,
+ };
+
+ const store = createStore<TodoListStore>((set, get) => {
+ return createActions(set, get, internals, defaultItems);
+ });
+
+ return store;
+};
+
+// Context for the store
+export const TodoListStoreContext = createContext<StoreApi<TodoListStore> | null>(null);
+
+// Hook to use the store
+export const useTodoListStore = <T>(selector: (state: TodoListStore) => T): T => {
+ const store = useContext(TodoListStoreContext);
+ if (!store) {
+ throw new Error('useTodoListStore must be used within TodoListStoreContext.Provider');
+ }
+ return useStore(store, selector);
+};
diff --git a/packages/builtin-tool-gtd/src/client/components/SortableTodoList/store/initialState.ts b/packages/builtin-tool-gtd/src/client/components/SortableTodoList/store/initialState.ts
new file mode 100644
index 00000000000..16b0c5ab0ea
--- /dev/null
+++ b/packages/builtin-tool-gtd/src/client/components/SortableTodoList/store/initialState.ts
@@ -0,0 +1,13 @@
+import type { TodoListState } from './types';
+
+export const initialState: Omit<TodoListState, 'items'> = {
+ cursorPosition: 0,
+ focusedId: null,
+ isDirty: false,
+ newItemText: '',
+ saveStatus: 'idle',
+};
+
+// Auto-save configuration
+export const AUTO_SAVE_DELAY = 3000; // 3 seconds after last change
+export const AUTO_SAVE_MAX_WAIT = 10_000; // Maximum 10 seconds between saves
diff --git a/packages/builtin-tool-gtd/src/client/components/SortableTodoList/store/store.test.ts b/packages/builtin-tool-gtd/src/client/components/SortableTodoList/store/store.test.ts
new file mode 100644
index 00000000000..ca380e0840d
--- /dev/null
+++ b/packages/builtin-tool-gtd/src/client/components/SortableTodoList/store/store.test.ts
@@ -0,0 +1,520 @@
+import { act } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type { TodoItem } from '../../../../types';
+import { resetIdCounter } from './actions';
+import { createTodoListStore } from './index';
+import { ADD_ITEM_ID } from './types';
+
+// Helper to create TodoItem array from text strings
+const toTodoItems = (...texts: string[]): TodoItem[] =>
+ texts.map((text) => ({ completed: false, text }));
+
+describe('TodoListStore', () => {
+ beforeEach(() => {
+ vi.useFakeTimers();
+ resetIdCounter();
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ describe('createTodoListStore', () => {
+ it('should create store with empty items by default', () => {
+ const store = createTodoListStore();
+ const state = store.getState();
+
+ expect(state.items).toEqual([]);
+ expect(state.newItemText).toBe('');
+ expect(state.focusedId).toBeNull();
+ expect(state.cursorPosition).toBe(0);
+ expect(state.isDirty).toBe(false);
+ expect(state.saveStatus).toBe('idle');
+ });
+
+ it('should create store with default items', () => {
+ const store = createTodoListStore(toTodoItems('Task 1', 'Task 2'));
+ const state = store.getState();
+
+ expect(state.items).toHaveLength(2);
+ expect(state.items[0].text).toBe('Task 1');
+ expect(state.items[0].completed).toBe(false);
+ expect(state.items[1].text).toBe('Task 2');
+ });
+
+ it('should generate unique IDs for items', () => {
+ const store = createTodoListStore(toTodoItems('Task 1', 'Task 2'));
+ const state = store.getState();
+
+ expect(state.items[0].id).not.toBe(state.items[1].id);
+ });
+ });
+
+ describe('addItem', () => {
+ it('should add a new item when newItemText is not empty', () => {
+ const store = createTodoListStore();
+
+ act(() => {
+ store.getState().setNewItemText('New Task');
+ store.getState().addItem();
+ });
+
+ const state = store.getState();
+ expect(state.items).toHaveLength(1);
+ expect(state.items[0].text).toBe('New Task');
+ expect(state.items[0].completed).toBe(false);
+ expect(state.newItemText).toBe('');
+ });
+
+ it('should not add item when newItemText is empty', () => {
+ const store = createTodoListStore();
+
+ act(() => {
+ store.getState().setNewItemText(' ');
+ store.getState().addItem();
+ });
+
+ expect(store.getState().items).toHaveLength(0);
+ });
+
+ it('should trim whitespace from new item text', () => {
+ const store = createTodoListStore();
+
+ act(() => {
+ store.getState().setNewItemText(' Trimmed Task ');
+ store.getState().addItem();
+ });
+
+ expect(store.getState().items[0].text).toBe('Trimmed Task');
+ });
+
+ it('should mark store as dirty after adding item', () => {
+ const store = createTodoListStore();
+
+ act(() => {
+ store.getState().setNewItemText('New Task');
+ store.getState().addItem();
+ });
+
+ expect(store.getState().isDirty).toBe(true);
+ });
+ });
+
+ describe('deleteItem', () => {
+ it('should delete item by id', () => {
+ const store = createTodoListStore(toTodoItems('Task 1', 'Task 2'));
+ const itemId = store.getState().items[0].id;
+
+ act(() => {
+ store.getState().deleteItem(itemId);
+ });
+
+ const state = store.getState();
+ expect(state.items).toHaveLength(1);
+ expect(state.items[0].text).toBe('Task 2');
+ });
+
+ it('should mark store as dirty after deleting item', () => {
+ const store = createTodoListStore(toTodoItems('Task 1'));
+ const itemId = store.getState().items[0].id;
+
+ act(() => {
+ store.getState().deleteItem(itemId);
+ });
+
+ expect(store.getState().isDirty).toBe(true);
+ });
+ });
+
+ describe('updateItem', () => {
+ it('should update item text by id', () => {
+ const store = createTodoListStore(toTodoItems('Task 1'));
+ const itemId = store.getState().items[0].id;
+
+ act(() => {
+ store.getState().updateItem(itemId, 'Updated Task');
+ });
+
+ expect(store.getState().items[0].text).toBe('Updated Task');
+ });
+
+ it('should mark store as dirty after updating item', () => {
+ const store = createTodoListStore(toTodoItems('Task 1'));
+ const itemId = store.getState().items[0].id;
+
+ act(() => {
+ store.getState().updateItem(itemId, 'Updated Task');
+ });
+
+ expect(store.getState().isDirty).toBe(true);
+ });
+ });
+
+ describe('toggleItem', () => {
+ it('should toggle item completed state', () => {
+ const store = createTodoListStore(toTodoItems('Task 1'));
+ const itemId = store.getState().items[0].id;
+
+ expect(store.getState().items[0].completed).toBe(false);
+
+ act(() => {
+ store.getState().toggleItem(itemId);
+ });
+
+ expect(store.getState().items[0].completed).toBe(true);
+
+ act(() => {
+ store.getState().toggleItem(itemId);
+ });
+
+ expect(store.getState().items[0].completed).toBe(false);
+ });
+
+ it('should mark store as dirty after toggling item', () => {
+ const store = createTodoListStore(toTodoItems('Task 1'));
+ const itemId = store.getState().items[0].id;
+
+ act(() => {
+ store.getState().toggleItem(itemId);
+ });
+
+ expect(store.getState().isDirty).toBe(true);
+ });
+ });
+
+ describe('sortItems', () => {
+ it('should update items order', () => {
+ const store = createTodoListStore(toTodoItems('Task 1', 'Task 2', 'Task 3'));
+ const items = store.getState().items;
+ const reversed = [...items].reverse();
+
+ act(() => {
+ store.getState().sortItems(reversed);
+ });
+
+ const state = store.getState();
+ expect(state.items[0].text).toBe('Task 3');
+ expect(state.items[1].text).toBe('Task 2');
+ expect(state.items[2].text).toBe('Task 1');
+ });
+
+ it('should mark store as dirty after sorting', () => {
+ const store = createTodoListStore(toTodoItems('Task 1', 'Task 2'));
+ const items = store.getState().items;
+
+ act(() => {
+ store.getState().sortItems([...items].reverse());
+ });
+
+ expect(store.getState().isDirty).toBe(true);
+ });
+ });
+
+ describe('focus navigation', () => {
+ describe('focusNextItem', () => {
+ it('should focus next item in list', () => {
+ const store = createTodoListStore(toTodoItems('Task 1', 'Task 2', 'Task 3'));
+ const items = store.getState().items;
+
+ act(() => {
+ store.getState().focusNextItem(items[0].id, 5);
+ });
+
+ expect(store.getState().focusedId).toBe(items[1].id);
+ expect(store.getState().cursorPosition).toBe(5);
+ });
+
+ it('should focus ADD_ITEM_ID when at last item', () => {
+ const store = createTodoListStore(toTodoItems('Task 1', 'Task 2'));
+ const items = store.getState().items;
+
+ act(() => {
+ store.getState().focusNextItem(items[1].id, 3);
+ });
+
+ expect(store.getState().focusedId).toBe(ADD_ITEM_ID);
+ });
+
+ it('should not change focus when already at ADD_ITEM_ID', () => {
+ const store = createTodoListStore(toTodoItems('Task 1'));
+
+ act(() => {
+ store.getState().setFocusedId(ADD_ITEM_ID);
+ store.getState().focusNextItem(ADD_ITEM_ID, 0);
+ });
+
+ expect(store.getState().focusedId).toBe(ADD_ITEM_ID);
+ });
+
+ it('should not change focus when currentId is null', () => {
+ const store = createTodoListStore(toTodoItems('Task 1'));
+
+ act(() => {
+ store.getState().focusNextItem(null, 0);
+ });
+
+ expect(store.getState().focusedId).toBeNull();
+ });
+ });
+
+ describe('focusPrevItem', () => {
+ it('should focus previous item in list', () => {
+ const store = createTodoListStore(toTodoItems('Task 1', 'Task 2', 'Task 3'));
+ const items = store.getState().items;
+
+ act(() => {
+ store.getState().focusPrevItem(items[2].id, 5);
+ });
+
+ expect(store.getState().focusedId).toBe(items[1].id);
+ expect(store.getState().cursorPosition).toBe(5);
+ });
+
+ it('should not change focus when at first item', () => {
+ const store = createTodoListStore(toTodoItems('Task 1', 'Task 2'));
+ const items = store.getState().items;
+
+ act(() => {
+ store.getState().setFocusedId(items[0].id);
+ store.getState().focusPrevItem(items[0].id, 0);
+ });
+
+ expect(store.getState().focusedId).toBe(items[0].id);
+ });
+
+ it('should focus last item when at ADD_ITEM_ID', () => {
+ const store = createTodoListStore(toTodoItems('Task 1', 'Task 2'));
+ const items = store.getState().items;
+
+ act(() => {
+ store.getState().focusPrevItem(ADD_ITEM_ID, 3);
+ });
+
+ expect(store.getState().focusedId).toBe(items[1].id);
+ });
+
+ it('should not change focus when items list is empty', () => {
+ const store = createTodoListStore();
+
+ act(() => {
+ store.getState().focusPrevItem(ADD_ITEM_ID, 0);
+ });
+
+ expect(store.getState().focusedId).toBeNull();
+ });
+ });
+ });
+
+ describe('setFocusedId', () => {
+ it('should set focused id', () => {
+ const store = createTodoListStore(toTodoItems('Task 1'));
+ const itemId = store.getState().items[0].id;
+
+ act(() => {
+ store.getState().setFocusedId(itemId);
+ });
+
+ expect(store.getState().focusedId).toBe(itemId);
+ });
+
+ it('should set focused id to null', () => {
+ const store = createTodoListStore(toTodoItems('Task 1'));
+ const itemId = store.getState().items[0].id;
+
+ act(() => {
+ store.getState().setFocusedId(itemId);
+ store.getState().setFocusedId(null);
+ });
+
+ expect(store.getState().focusedId).toBeNull();
+ });
+ });
+
+ describe('setNewItemText', () => {
+ it('should set new item text', () => {
+ const store = createTodoListStore();
+
+ act(() => {
+ store.getState().setNewItemText('New Task');
+ });
+
+ expect(store.getState().newItemText).toBe('New Task');
+ });
+ });
+
+ describe('auto-save functionality', () => {
+ it('should call onSave after debounce delay', async () => {
+ const onSave = vi.fn();
+ const store = createTodoListStore(toTodoItems('Task 1'), onSave);
+
+ act(() => {
+ store.getState().updateItem(store.getState().items[0].id, 'Updated');
+ });
+
+ expect(onSave).not.toHaveBeenCalled();
+ expect(store.getState().isDirty).toBe(true);
+
+ // Fast-forward past debounce delay
+ await act(async () => {
+ vi.advanceTimersByTime(3000);
+ });
+
+ expect(onSave).toHaveBeenCalledTimes(1);
+ // onSave receives TodoItem[] (without id), not TodoListItem[]
+ expect(onSave).toHaveBeenCalledWith([{ completed: false, text: 'Updated' }]);
+ });
+
+ it('should set saveStatus to saving during save', async () => {
+ const onSave = vi
+ .fn()
+ .mockImplementation(() => new Promise((resolve) => setTimeout(resolve, 100)));
+ const store = createTodoListStore(toTodoItems('Task 1'), onSave);
+
+ act(() => {
+ store.getState().updateItem(store.getState().items[0].id, 'Updated');
+ });
+
+ await act(async () => {
+ vi.advanceTimersByTime(3000);
+ });
+
+ expect(store.getState().saveStatus).toBe('saving');
+ });
+
+ it('should set saveStatus to saved after successful save', async () => {
+ const onSave = vi.fn().mockResolvedValue(undefined);
+ const store = createTodoListStore(toTodoItems('Task 1'), onSave);
+
+ act(() => {
+ store.getState().updateItem(store.getState().items[0].id, 'Updated');
+ });
+
+ await act(async () => {
+ vi.advanceTimersByTime(3000);
+ await Promise.resolve();
+ });
+
+ expect(store.getState().saveStatus).toBe('saved');
+ expect(store.getState().isDirty).toBe(false);
+ });
+
+ it('should set saveStatus to error on save failure', async () => {
+ const onSave = vi.fn().mockRejectedValue(new Error('Save failed'));
+ const store = createTodoListStore(toTodoItems('Task 1'), onSave);
+
+ act(() => {
+ store.getState().updateItem(store.getState().items[0].id, 'Updated');
+ });
+
+ await act(async () => {
+ vi.advanceTimersByTime(3000);
+ await Promise.resolve();
+ });
+
+ expect(store.getState().saveStatus).toBe('error');
+ });
+
+ it('should debounce multiple rapid changes', async () => {
+ const onSave = vi.fn().mockResolvedValue(undefined);
+ const store = createTodoListStore(toTodoItems('Task 1'), onSave);
+ const itemId = store.getState().items[0].id;
+
+ act(() => {
+ store.getState().updateItem(itemId, 'Update 1');
+ });
+
+ await act(async () => {
+ vi.advanceTimersByTime(1000);
+ });
+
+ act(() => {
+ store.getState().updateItem(itemId, 'Update 2');
+ });
+
+ await act(async () => {
+ vi.advanceTimersByTime(1000);
+ });
+
+ act(() => {
+ store.getState().updateItem(itemId, 'Update 3');
+ });
+
+ expect(onSave).not.toHaveBeenCalled();
+
+ await act(async () => {
+ vi.advanceTimersByTime(3000);
+ await Promise.resolve();
+ });
+
+ expect(onSave).toHaveBeenCalledTimes(1);
+ });
+
+ it('should flush save immediately when flushSave is called', async () => {
+ const onSave = vi.fn().mockResolvedValue(undefined);
+ const store = createTodoListStore(toTodoItems('Task 1'), onSave);
+
+ act(() => {
+ store.getState().updateItem(store.getState().items[0].id, 'Updated');
+ });
+
+ expect(onSave).not.toHaveBeenCalled();
+
+ await act(async () => {
+ store.getState().flushSave();
+ await Promise.resolve();
+ });
+
+ expect(onSave).toHaveBeenCalledTimes(1);
+ });
+
+ it('should not call onSave if not dirty', async () => {
+ const onSave = vi.fn();
+ const store = createTodoListStore(toTodoItems('Task 1'), onSave);
+
+ await act(async () => {
+ store.getState().flushSave();
+ await Promise.resolve();
+ });
+
+ expect(onSave).not.toHaveBeenCalled();
+ });
+
+ it('should not call onSave if no onSave callback provided', async () => {
+ const store = createTodoListStore(toTodoItems('Task 1'));
+
+ act(() => {
+ store.getState().updateItem(store.getState().items[0].id, 'Updated');
+ });
+
+ await act(async () => {
+ vi.advanceTimersByTime(3000);
+ });
+
+ // Should not throw or cause issues
+ expect(store.getState().isDirty).toBe(true);
+ });
+
+ it('should reset saveStatus to idle after showing saved', async () => {
+ const onSave = vi.fn().mockResolvedValue(undefined);
+ const store = createTodoListStore(toTodoItems('Task 1'), onSave);
+
+ act(() => {
+ store.getState().updateItem(store.getState().items[0].id, 'Updated');
+ });
+
+ await act(async () => {
+ vi.advanceTimersByTime(3000);
+ await Promise.resolve();
+ });
+
+ expect(store.getState().saveStatus).toBe('saved');
+
+ await act(async () => {
+ vi.advanceTimersByTime(1500);
+ });
+
+ expect(store.getState().saveStatus).toBe('idle');
+ });
+ });
+});
diff --git a/packages/builtin-tool-gtd/src/client/components/SortableTodoList/store/types.ts b/packages/builtin-tool-gtd/src/client/components/SortableTodoList/store/types.ts
new file mode 100644
index 00000000000..820dd14f962
--- /dev/null
+++ b/packages/builtin-tool-gtd/src/client/components/SortableTodoList/store/types.ts
@@ -0,0 +1,49 @@
+import { DebouncedFunc } from 'es-toolkit/compat';
+
+import type { TodoItem } from '../../../../types';
+
+export interface TodoListItem extends TodoItem {
+ id: string;
+}
+
+export interface TodoListState {
+ cursorPosition: number;
+ focusedId: string | null;
+ isDirty: boolean;
+ items: TodoListItem[];
+ newItemText: string;
+ saveStatus: 'idle' | 'saving' | 'saved' | 'error';
+}
+
+export interface TodoListActions {
+ addItem: () => void;
+ deleteItem: (id: string) => void;
+ /**
+ * Immediately trigger pending debounced save (fire-and-forget, sync)
+ * Used on unmount to ensure data is not lost
+ */
+ flushSave: () => void;
+ focusNextItem: (currentId: string | null, cursorPos: number) => void;
+ focusPrevItem: (currentId: string | null, cursorPos: number) => void;
+ /**
+ * Immediately save current items if dirty (async)
+ * Use this before approval to ensure all edits are persisted
+ */
+ saveNow: () => Promise<void>;
+ setFocusedId: (id: string | null) => void;
+ setNewItemText: (text: string) => void;
+ sortItems: (sortedItems: TodoListItem[]) => void;
+ toggleItem: (id: string) => void;
+ updateItem: (id: string, text: string) => void;
+}
+
+export type TodoListStore = TodoListState & TodoListActions;
+
+// Store internal state for debounce function
+export interface StoreInternals {
+ debouncedSave: DebouncedFunc<() => void> | null;
+ onSave: ((items: TodoItem[]) => void | Promise<void>) | null;
+}
+
+// Special ID for the "add new item" input
+export const ADD_ITEM_ID = '__add_item__';
diff --git a/packages/builtin-tool-gtd/src/client/components/index.ts b/packages/builtin-tool-gtd/src/client/components/index.ts
new file mode 100644
index 00000000000..904f5e2c5f1
--- /dev/null
+++ b/packages/builtin-tool-gtd/src/client/components/index.ts
@@ -0,0 +1,2 @@
+export type { SortableTodoListProps, TodoListItem } from './SortableTodoList';
+export { default as SortableTodoList } from './SortableTodoList';
diff --git a/packages/builtin-tool-gtd/src/client/index.ts b/packages/builtin-tool-gtd/src/client/index.ts
new file mode 100644
index 00000000000..42e87db6fee
--- /dev/null
+++ b/packages/builtin-tool-gtd/src/client/index.ts
@@ -0,0 +1,14 @@
+// Render components (read-only snapshots)
+export type { TodoListRenderState } from './Render';
+export { GTDRenders, TodoListRender, TodoListUI } from './Render';
+
+// Intervention components (interactive editing)
+export { AddTodoIntervention, ClearTodosIntervention, GTDInterventions } from './Intervention';
+
+// Reusable components
+export type { SortableTodoListProps, TodoListItem } from './components';
+export { SortableTodoList } from './components';
+
+// Re-export types and manifest for convenience
+export { GTDManifest } from '../manifest';
+export * from '../types';
diff --git a/packages/builtin-tool-gtd/src/executor/helper.ts b/packages/builtin-tool-gtd/src/executor/helper.ts
new file mode 100644
index 00000000000..7f6a27cc282
--- /dev/null
+++ b/packages/builtin-tool-gtd/src/executor/helper.ts
@@ -0,0 +1,40 @@
+import { type BuiltinToolContext } from '@lobechat/types';
+
+import { type TodoItem } from '../types';
+
+/**
+ * Helper to get todos from step context or fallback to plugin state
+ *
+ * Priority:
+ * 1. ctx.stepContext.todos - Dynamic state computed from messages at step start
+ * 2. ctx.pluginState.todos - Fallback for backward compatibility
+ *
+ * Handles both old format ({ todos: TodoItem[] }) and new format ({ todos: { items: TodoItem[] } })
+ */
+export const getTodosFromContext = (ctx: BuiltinToolContext): TodoItem[] => {
+ // Priority 1: stepContext.todos (computed from messages at step start)
+ const stepTodos = ctx.stepContext?.todos;
+ if (stepTodos?.items) {
+ return stepTodos.items as TodoItem[];
+ }
+
+ // Priority 2: pluginState.todos (as if there is a new todo list)
+ const state = ctx.pluginState;
+ if (!state) return [];
+
+ const todos = state.todos;
+ if (!todos) return [];
+
+ // New format: { todos: { items: TodoItem[] } }
+ if (typeof todos === 'object' && 'items' in (todos as Record<string, unknown>)) {
+ const items = (todos as Record<string, unknown>).items;
+ return Array.isArray(items) ? (items as TodoItem[]) : [];
+ }
+
+ // Old format: { todos: TodoItem[] }
+ if (Array.isArray(todos)) {
+ return todos as TodoItem[];
+ }
+
+ return [];
+};
diff --git a/packages/builtin-tool-gtd/src/executor/index.test.ts b/packages/builtin-tool-gtd/src/executor/index.test.ts
new file mode 100644
index 00000000000..ba16695a8e7
--- /dev/null
+++ b/packages/builtin-tool-gtd/src/executor/index.test.ts
@@ -0,0 +1,600 @@
+import type { BuiltinToolContext } from '@lobechat/types';
+import { describe, expect, it } from 'vitest';
+
+import { gtdExecutor } from './index';
+
+describe('GTDExecutor', () => {
+ const createMockContext = (pluginState?: Record<string, unknown>): BuiltinToolContext => ({
+ messageId: 'test-message-id',
+ operationId: 'test-operation-id',
+ pluginState,
+ });
+
+ describe('createTodos', () => {
+ it('should add items to empty todo list using adds (AI input)', async () => {
+ const ctx = createMockContext();
+
+ const result = await gtdExecutor.createTodos({ adds: ['Buy milk', 'Call mom'] }, ctx);
+
+ expect(result.success).toBe(true);
+ expect(result.content).toContain('Added 2 items');
+ expect(result.content).toContain('Buy milk');
+ expect(result.content).toContain('Call mom');
+ expect(result.state?.todos.items).toHaveLength(2);
+ expect(result.state?.todos.items[0].text).toBe('Buy milk');
+ expect(result.state?.todos.items[0].completed).toBe(false);
+ expect(result.state?.todos.items[1].text).toBe('Call mom');
+ });
+
+ it('should add items using items (user-edited format)', async () => {
+ const ctx = createMockContext();
+
+ const result = await gtdExecutor.createTodos(
+ {
+ items: [
+ { text: 'Buy milk', completed: false },
+ { text: 'Call mom', completed: true },
+ ],
+ },
+ ctx,
+ );
+
+ expect(result.success).toBe(true);
+ expect(result.content).toContain('Added 2 items');
+ expect(result.state?.todos.items).toHaveLength(2);
+ expect(result.state?.todos.items[0].text).toBe('Buy milk');
+ expect(result.state?.todos.items[0].completed).toBe(false);
+ expect(result.state?.todos.items[1].text).toBe('Call mom');
+ expect(result.state?.todos.items[1].completed).toBe(true);
+ });
+
+ it('should append items to existing todo list', async () => {
+ const ctx = createMockContext({
+ todos: {
+ items: [{ text: 'Existing task', completed: false }],
+ updatedAt: '2024-01-01T00:00:00.000Z',
+ },
+ });
+
+ const result = await gtdExecutor.createTodos({ adds: ['New task'] }, ctx);
+
+ expect(result.success).toBe(true);
+ expect(result.state?.todos.items).toHaveLength(2);
+ expect(result.state?.todos.items[0].text).toBe('Existing task');
+ expect(result.state?.todos.items[1].text).toBe('New task');
+ });
+
+ it('should return error when no items provided', async () => {
+ const ctx = createMockContext();
+
+ const result = await gtdExecutor.createTodos({ adds: [] }, ctx);
+
+ expect(result.success).toBe(false);
+ expect(result.content).toContain('No items provided');
+ });
+
+ it('should add single item with correct singular grammar', async () => {
+ const ctx = createMockContext();
+
+ const result = await gtdExecutor.createTodos({ adds: ['Single task'] }, ctx);
+
+ expect(result.success).toBe(true);
+ expect(result.content).toContain('Added 1 item');
+ expect(result.content).not.toContain('items');
+ });
+
+ it('should prioritize items over adds when both provided', async () => {
+ const ctx = createMockContext();
+
+ const result = await gtdExecutor.createTodos(
+ {
+ adds: ['AI task'],
+ items: [{ text: 'User edited task', completed: true }],
+ },
+ ctx,
+ );
+
+ expect(result.success).toBe(true);
+ expect(result.state?.todos.items).toHaveLength(1);
+ expect(result.state?.todos.items[0].text).toBe('User edited task');
+ expect(result.state?.todos.items[0].completed).toBe(true);
+ });
+ });
+
+ describe('updateTodos', () => {
+ it('should add new items via operations', async () => {
+ const ctx = createMockContext({
+ todos: {
+ items: [{ text: 'Existing task', completed: false }],
+ updatedAt: '2024-01-01T00:00:00.000Z',
+ },
+ });
+
+ const result = await gtdExecutor.updateTodos(
+ {
+ operations: [{ type: 'add', text: 'New task' }],
+ },
+ ctx,
+ );
+
+ expect(result.success).toBe(true);
+ expect(result.state?.todos.items).toHaveLength(2);
+ expect(result.state?.todos.items[1].text).toBe('New task');
+ });
+
+ it('should update item text via operations', async () => {
+ const ctx = createMockContext({
+ todos: {
+ items: [{ text: 'Old task', completed: false }],
+ updatedAt: '2024-01-01T00:00:00.000Z',
+ },
+ });
+
+ const result = await gtdExecutor.updateTodos(
+ {
+ operations: [{ type: 'update', index: 0, newText: 'Updated task' }],
+ },
+ ctx,
+ );
+
+ expect(result.success).toBe(true);
+ expect(result.state?.todos.items[0].text).toBe('Updated task');
+ });
+
+ it('should complete items via operations', async () => {
+ const ctx = createMockContext({
+ todos: {
+ items: [{ text: 'Task', completed: false }],
+ updatedAt: '2024-01-01T00:00:00.000Z',
+ },
+ });
+
+ const result = await gtdExecutor.updateTodos(
+ {
+ operations: [{ type: 'complete', index: 0 }],
+ },
+ ctx,
+ );
+
+ expect(result.success).toBe(true);
+ expect(result.state?.todos.items[0].completed).toBe(true);
+ });
+
+ it('should remove items via operations', async () => {
+ const ctx = createMockContext({
+ todos: {
+ items: [
+ { text: 'Task 1', completed: false },
+ { text: 'Task 2', completed: false },
+ ],
+ updatedAt: '2024-01-01T00:00:00.000Z',
+ },
+ });
+
+ const result = await gtdExecutor.updateTodos(
+ {
+ operations: [{ type: 'remove', index: 0 }],
+ },
+ ctx,
+ );
+
+ expect(result.success).toBe(true);
+ expect(result.state?.todos.items).toHaveLength(1);
+ expect(result.state?.todos.items[0].text).toBe('Task 2');
+ });
+
+ it('should return error when no operations provided', async () => {
+ const ctx = createMockContext();
+
+ const result = await gtdExecutor.updateTodos({ operations: [] }, ctx);
+
+ expect(result.success).toBe(false);
+ expect(result.content).toContain('No operations provided');
+ });
+
+ it('should handle complete operations with out-of-range indices gracefully', async () => {
+ // Test case: 5 items (indices 0-4), operations reference index 5 (out of range) and index 2 (valid)
+ const ctx = createMockContext({
+ createdItems: ['Task A', 'Task B', 'Task C', 'Task D', 'Task E'],
+ todos: {
+ items: [
+ { completed: false, text: 'Task A' },
+ { completed: false, text: 'Task B' },
+ { completed: false, text: 'Task C' },
+ { completed: false, text: 'Task D' },
+ { completed: false, text: 'Task E' },
+ ],
+ updatedAt: '2025-01-01T00:00:00.000Z',
+ },
+ });
+
+ const result = await gtdExecutor.updateTodos(
+ {
+ operations: [
+ { completed: true, index: 5, newText: '', text: '', type: 'complete' }, // out of range
+ { completed: true, index: 2, newText: '', text: '', type: 'complete' }, // valid
+ ],
+ },
+ ctx,
+ );
+
+ expect(result.success).toBe(true);
+ // Should have all 5 items preserved
+ expect(result.state?.todos.items).toHaveLength(5);
+ // Index 5 is out of range (0-4), so should be skipped
+ // Index 2 should be completed
+ expect(result.state?.todos.items[2].completed).toBe(true);
+ // Other items should remain uncompleted
+ expect(result.state?.todos.items[0].completed).toBe(false);
+ expect(result.state?.todos.items[1].completed).toBe(false);
+ expect(result.state?.todos.items[3].completed).toBe(false);
+ expect(result.state?.todos.items[4].completed).toBe(false);
+ });
+ });
+
+ describe('completeTodos', () => {
+ it('should mark items as done by indices', async () => {
+ const ctx = createMockContext({
+ todos: {
+ items: [
+ { text: 'Task 1', completed: false },
+ { text: 'Task 2', completed: false },
+ { text: 'Task 3', completed: false },
+ ],
+ updatedAt: '2024-01-01T00:00:00.000Z',
+ },
+ });
+
+ const result = await gtdExecutor.completeTodos({ indices: [0, 2] }, ctx);
+
+ expect(result.success).toBe(true);
+ expect(result.content).toContain('Completed 2 items');
+ expect(result.state?.todos.items[0].completed).toBe(true);
+ expect(result.state?.todos.items[1].completed).toBe(false);
+ expect(result.state?.todos.items[2].completed).toBe(true);
+ });
+
+ it('should return error when no indices provided', async () => {
+ const ctx = createMockContext();
+
+ const result = await gtdExecutor.completeTodos({ indices: [] }, ctx);
+
+ expect(result.success).toBe(false);
+ expect(result.content).toContain('No indices provided');
+ });
+
+ it('should handle empty todo list', async () => {
+ const ctx = createMockContext({
+ todos: { items: [], updatedAt: '2024-01-01T00:00:00.000Z' },
+ });
+
+ const result = await gtdExecutor.completeTodos({ indices: [0] }, ctx);
+
+ expect(result.success).toBe(true);
+ expect(result.content).toContain('No todos to complete');
+ });
+
+ it('should return error when all indices are invalid', async () => {
+ const ctx = createMockContext({
+ todos: {
+ items: [{ text: 'Task 1', completed: false }],
+ updatedAt: '2024-01-01T00:00:00.000Z',
+ },
+ });
+
+ const result = await gtdExecutor.completeTodos({ indices: [5, 10] }, ctx);
+
+ expect(result.success).toBe(false);
+ expect(result.content).toContain('Invalid indices');
+ });
+
+ it('should complete valid indices and warn about invalid ones', async () => {
+ const ctx = createMockContext({
+ todos: {
+ items: [
+ { text: 'Task 1', completed: false },
+ { text: 'Task 2', completed: false },
+ ],
+ updatedAt: '2024-01-01T00:00:00.000Z',
+ },
+ });
+
+ const result = await gtdExecutor.completeTodos({ indices: [0, 99] }, ctx);
+
+ expect(result.success).toBe(true);
+ expect(result.content).toContain('Completed 1 item');
+ expect(result.content).toContain('Ignored invalid indices');
+ expect(result.state?.todos.items[0].completed).toBe(true);
+ expect(result.state?.todos.items[1].completed).toBe(false);
+ });
+
+ it('should handle single item completion with correct grammar', async () => {
+ const ctx = createMockContext({
+ todos: {
+ items: [{ text: 'Task 1', completed: false }],
+ updatedAt: '2024-01-01T00:00:00.000Z',
+ },
+ });
+
+ const result = await gtdExecutor.completeTodos({ indices: [0] }, ctx);
+
+ expect(result.success).toBe(true);
+ expect(result.content).toContain('Completed 1 item');
+ expect(result.content).not.toContain('items');
+ });
+ });
+
+ describe('removeTodos', () => {
+ it('should remove items by indices', async () => {
+ const ctx = createMockContext({
+ todos: {
+ items: [
+ { text: 'Task 1', completed: false },
+ { text: 'Task 2', completed: false },
+ { text: 'Task 3', completed: false },
+ ],
+ updatedAt: '2024-01-01T00:00:00.000Z',
+ },
+ });
+
+ const result = await gtdExecutor.removeTodos({ indices: [0, 2] }, ctx);
+
+ expect(result.success).toBe(true);
+ expect(result.content).toContain('Removed 2 items');
+ expect(result.state?.todos.items).toHaveLength(1);
+ expect(result.state?.todos.items[0].text).toBe('Task 2');
+ });
+
+ it('should return error when no indices provided', async () => {
+ const ctx = createMockContext();
+
+ const result = await gtdExecutor.removeTodos({ indices: [] }, ctx);
+
+ expect(result.success).toBe(false);
+ expect(result.content).toContain('No indices provided');
+ });
+
+ it('should handle empty todo list', async () => {
+ const ctx = createMockContext({
+ todos: { items: [], updatedAt: '2024-01-01T00:00:00.000Z' },
+ });
+
+ const result = await gtdExecutor.removeTodos({ indices: [0] }, ctx);
+
+ expect(result.success).toBe(true);
+ expect(result.content).toContain('No todos to remove');
+ });
+ });
+
+ describe('clearTodos', () => {
+ it('should clear all items when mode is "all"', async () => {
+ const ctx = createMockContext({
+ todos: {
+ items: [
+ { text: 'Task 1', completed: false },
+ { text: 'Task 2', completed: true },
+ ],
+ updatedAt: '2024-01-01T00:00:00.000Z',
+ },
+ });
+
+ const result = await gtdExecutor.clearTodos({ mode: 'all' }, ctx);
+
+ expect(result.success).toBe(true);
+ expect(result.content).toContain('Cleared all 2 items');
+ expect(result.state?.todos.items).toHaveLength(0);
+ });
+
+ it('should clear only completed items when mode is "completed"', async () => {
+ const ctx = createMockContext({
+ todos: {
+ items: [
+ { text: 'Task 1', completed: false },
+ { text: 'Task 2', completed: true },
+ { text: 'Task 3', completed: true },
+ ],
+ updatedAt: '2024-01-01T00:00:00.000Z',
+ },
+ });
+
+ const result = await gtdExecutor.clearTodos({ mode: 'completed' }, ctx);
+
+ expect(result.success).toBe(true);
+ expect(result.content).toContain('Cleared 2 completed items');
+ // New format shows "1 pending" instead of "1 item remaining"
+ expect(result.content).toContain('1 pending');
+ expect(result.state?.todos.items).toHaveLength(1);
+ expect(result.state?.todos.items[0].text).toBe('Task 1');
+ });
+
+ it('should handle empty todo list', async () => {
+ const ctx = createMockContext({
+ todos: { items: [], updatedAt: '2024-01-01T00:00:00.000Z' },
+ });
+
+ const result = await gtdExecutor.clearTodos({ mode: 'all' }, ctx);
+
+ expect(result.success).toBe(true);
+ expect(result.content).toContain('already empty');
+ });
+
+ it('should handle no completed items to clear', async () => {
+ const ctx = createMockContext({
+ todos: {
+ items: [{ text: 'Task 1', completed: false }],
+ updatedAt: '2024-01-01T00:00:00.000Z',
+ },
+ });
+
+ const result = await gtdExecutor.clearTodos({ mode: 'completed' }, ctx);
+
+ expect(result.success).toBe(true);
+ expect(result.content).toContain('No completed items to clear');
+ expect(result.state?.todos.items).toHaveLength(1);
+ });
+ });
+
+ describe('stepContext priority', () => {
+ it('should prioritize stepContext.todos over pluginState.todos', async () => {
+ // Create context with both stepContext and pluginState
+ const ctx: BuiltinToolContext = {
+ messageId: 'test-message-id',
+ operationId: 'test-operation-id',
+ pluginState: {
+ todos: {
+ items: [{ text: 'Old task from pluginState', completed: false }],
+ updatedAt: '2024-01-01T00:00:00.000Z',
+ },
+ },
+ stepContext: {
+ todos: {
+ items: [{ text: 'New task from stepContext', completed: true }],
+ updatedAt: '2024-06-01T00:00:00.000Z',
+ },
+ },
+ };
+
+ // createTodos should use stepContext.todos as base
+ const result = await gtdExecutor.createTodos({ adds: ['Another task'] }, ctx);
+
+ expect(result.success).toBe(true);
+ expect(result.state?.todos.items).toHaveLength(2);
+ // First item should be from stepContext, not pluginState
+ expect(result.state?.todos.items[0].text).toBe('New task from stepContext');
+ expect(result.state?.todos.items[0].completed).toBe(true);
+ expect(result.state?.todos.items[1].text).toBe('Another task');
+ });
+
+ it('should fallback to pluginState.todos when stepContext.todos is undefined', async () => {
+ const ctx: BuiltinToolContext = {
+ messageId: 'test-message-id',
+ operationId: 'test-operation-id',
+ pluginState: {
+ todos: {
+ items: [{ text: 'Task from pluginState', completed: false }],
+ updatedAt: '2024-01-01T00:00:00.000Z',
+ },
+ },
+ stepContext: {
+ // No todos in stepContext
+ },
+ };
+
+ const result = await gtdExecutor.createTodos({ adds: ['New task'] }, ctx);
+
+ expect(result.success).toBe(true);
+ expect(result.state?.todos.items).toHaveLength(2);
+ expect(result.state?.todos.items[0].text).toBe('Task from pluginState');
+ expect(result.state?.todos.items[1].text).toBe('New task');
+ });
+
+ it('should start with empty todos when both stepContext and pluginState are empty', async () => {
+ const ctx: BuiltinToolContext = {
+ messageId: 'test-message-id',
+ operationId: 'test-operation-id',
+ stepContext: {},
+ };
+
+ const result = await gtdExecutor.createTodos({ adds: ['First task'] }, ctx);
+
+ expect(result.success).toBe(true);
+ expect(result.state?.todos.items).toHaveLength(1);
+ expect(result.state?.todos.items[0].text).toBe('First task');
+ });
+
+ it('should work with stepContext.todos for completeTodos', async () => {
+ const ctx: BuiltinToolContext = {
+ messageId: 'test-message-id',
+ operationId: 'test-operation-id',
+ stepContext: {
+ todos: {
+ items: [
+ { text: 'Task 1', completed: false },
+ { text: 'Task 2', completed: false },
+ ],
+ updatedAt: '2024-06-01T00:00:00.000Z',
+ },
+ },
+ };
+
+ const result = await gtdExecutor.completeTodos({ indices: [0] }, ctx);
+
+ expect(result.success).toBe(true);
+ expect(result.state?.todos.items[0].completed).toBe(true);
+ expect(result.state?.todos.items[1].completed).toBe(false);
+ });
+
+ it('should work with stepContext.todos for removeTodos', async () => {
+ const ctx: BuiltinToolContext = {
+ messageId: 'test-message-id',
+ operationId: 'test-operation-id',
+ stepContext: {
+ todos: {
+ items: [
+ { text: 'Task 1', completed: false },
+ { text: 'Task 2', completed: false },
+ ],
+ updatedAt: '2024-06-01T00:00:00.000Z',
+ },
+ },
+ };
+
+ const result = await gtdExecutor.removeTodos({ indices: [0] }, ctx);
+
+ expect(result.success).toBe(true);
+ expect(result.state?.todos.items).toHaveLength(1);
+ expect(result.state?.todos.items[0].text).toBe('Task 2');
+ });
+
+ it('should work with stepContext.todos for clearTodos', async () => {
+ const ctx: BuiltinToolContext = {
+ messageId: 'test-message-id',
+ operationId: 'test-operation-id',
+ stepContext: {
+ todos: {
+ items: [
+ { text: 'Task 1', completed: true },
+ { text: 'Task 2', completed: false },
+ ],
+ updatedAt: '2024-06-01T00:00:00.000Z',
+ },
+ },
+ };
+
+ const result = await gtdExecutor.clearTodos({ mode: 'completed' }, ctx);
+
+ expect(result.success).toBe(true);
+ expect(result.state?.todos.items).toHaveLength(1);
+ expect(result.state?.todos.items[0].text).toBe('Task 2');
+ });
+ });
+
+ describe('executor metadata', () => {
+ it('should have correct identifier', () => {
+ expect(gtdExecutor.identifier).toBe('lobe-gtd');
+ });
+
+ it('should support all MVP APIs', () => {
+ expect(gtdExecutor.hasApi('createTodos')).toBe(true);
+ expect(gtdExecutor.hasApi('updateTodos')).toBe(true);
+ expect(gtdExecutor.hasApi('completeTodos')).toBe(true);
+ expect(gtdExecutor.hasApi('removeTodos')).toBe(true);
+ expect(gtdExecutor.hasApi('clearTodos')).toBe(true);
+ });
+
+ it('should not support non-MVP APIs', () => {
+ expect(gtdExecutor.hasApi('createPlan')).toBe(false);
+ expect(gtdExecutor.hasApi('updatePlan')).toBe(false);
+ });
+
+ it('should return correct API names', () => {
+ const apiNames = gtdExecutor.getApiNames();
+ expect(apiNames).toContain('createTodos');
+ expect(apiNames).toContain('updateTodos');
+ expect(apiNames).toContain('completeTodos');
+ expect(apiNames).toContain('removeTodos');
+ expect(apiNames).toContain('clearTodos');
+ expect(apiNames).toHaveLength(5);
+ });
+ });
+});
diff --git a/packages/builtin-tool-gtd/src/executor/index.ts b/packages/builtin-tool-gtd/src/executor/index.ts
new file mode 100644
index 00000000000..2686530fe55
--- /dev/null
+++ b/packages/builtin-tool-gtd/src/executor/index.ts
@@ -0,0 +1,359 @@
+/**
+ * Lobe GTD (Getting Things Done) Executor
+ *
+ * Handles GTD tool calls for task management.
+ * MVP: Only implements Todo functionality.
+ *
+ * Todo data flow:
+ * - Todo items are stored in messagePlugins.state.todos
+ * - The executor receives current state via ctx and returns updated state in result
+ * - The framework handles persisting state to the database
+ */
+import { formatTodoStateSummary } from '@lobechat/prompts';
+import { BaseExecutor, type BuiltinToolContext, type BuiltinToolResult } from '@lobechat/types';
+
+import { GTDIdentifier } from '../manifest';
+import {
+ type ClearTodosParams,
+ type CompleteTodosParams,
+ type CreateTodosParams,
+ GTDApiName,
+ type RemoveTodosParams,
+ type TodoItem,
+ type UpdateTodosParams,
+} from '../types';
+import { getTodosFromContext } from './helper';
+
+// API enum for MVP (Todo only)
+const GTDApiNameMVP = {
+ clearTodos: GTDApiName.clearTodos,
+ completeTodos: GTDApiName.completeTodos,
+ createTodos: GTDApiName.createTodos,
+ removeTodos: GTDApiName.removeTodos,
+ updateTodos: GTDApiName.updateTodos,
+} as const;
+
+/**
+ * GTD Tool Executor
+ */
+class GTDExecutor extends BaseExecutor<typeof GTDApiNameMVP> {
+ readonly identifier = GTDIdentifier;
+ protected readonly apiEnum = GTDApiNameMVP;
+
+ // ==================== Todo APIs ====================
+
+ /**
+ * Create new todo items
+ * Handles both formats:
+ * - AI input: { adds: string[] }
+ * - User-edited: { items: TodoItem[] }
+ */
+ createTodos = async (
+ params: CreateTodosParams,
+ ctx: BuiltinToolContext,
+ ): Promise<BuiltinToolResult> => {
+ // Handle both formats: items (user-edited) takes priority over adds (AI input)
+ const itemsToAdd: TodoItem[] = params.items
+ ? params.items
+ : params.adds
+ ? params.adds.map((text) => ({ completed: false, text }))
+ : [];
+
+ if (itemsToAdd.length === 0) {
+ return {
+ content: 'No items provided to add.',
+ success: false,
+ };
+ }
+
+ // Get current todos from step context (priority) or plugin state (fallback)
+ const existingTodos = getTodosFromContext(ctx);
+
+ // Add new items
+ const now = new Date().toISOString();
+ const updatedTodos = [...existingTodos, ...itemsToAdd];
+
+ // Format response: action summary + todo state
+ const addedList = itemsToAdd.map((item) => `- ${item.text}`).join('\n');
+ const actionSummary = `✅ Added ${itemsToAdd.length} item${itemsToAdd.length > 1 ? 's' : ''}:\n${addedList}`;
+
+ return {
+ content: actionSummary + '\n\n' + formatTodoStateSummary(updatedTodos, now),
+ state: {
+ createdItems: itemsToAdd.map((item) => item.text),
+ todos: { items: updatedTodos, updatedAt: now },
+ },
+ success: true,
+ };
+ };
+
+ /**
+ * Update todo items with batch operations
+ */
+ updateTodos = async (
+ params: UpdateTodosParams,
+ ctx: BuiltinToolContext,
+ ): Promise<BuiltinToolResult> => {
+ const { operations } = params;
+
+ if (!operations || operations.length === 0) {
+ return {
+ content: 'No operations provided.',
+ success: false,
+ };
+ }
+
+ const existingTodos = getTodosFromContext(ctx);
+ let updatedTodos = [...existingTodos];
+ const results: string[] = [];
+
+ for (const op of operations) {
+ switch (op.type) {
+ case 'add': {
+ if (op.text) {
+ updatedTodos.push({ completed: false, text: op.text });
+ results.push(`Added: "${op.text}"`);
+ }
+ break;
+ }
+ case 'update': {
+ if (op.index !== undefined && op.index >= 0 && op.index < updatedTodos.length) {
+ const item = updatedTodos[op.index];
+ if (op.newText !== undefined) {
+ item.text = op.newText;
+ }
+ if (op.completed !== undefined) {
+ item.completed = op.completed;
+ }
+ results.push(`Updated item ${op.index + 1}`);
+ }
+ break;
+ }
+ case 'remove': {
+ if (op.index !== undefined && op.index >= 0 && op.index < updatedTodos.length) {
+ const removed = updatedTodos.splice(op.index, 1)[0];
+ results.push(`Removed: "${removed.text}"`);
+ }
+ break;
+ }
+ case 'complete': {
+ if (op.index !== undefined && op.index >= 0 && op.index < updatedTodos.length) {
+ updatedTodos[op.index].completed = true;
+ results.push(`Completed: "${updatedTodos[op.index].text}"`);
+ }
+ break;
+ }
+ }
+ }
+
+ const now = new Date().toISOString();
+
+ // Format response: action summary + todo state
+ const actionSummary =
+ results.length > 0
+ ? `🔄 Applied ${results.length} operation${results.length > 1 ? 's' : ''}:\n${results.map((r) => `- ${r}`).join('\n')}`
+ : 'No operations applied.';
+
+ return {
+ content: actionSummary + '\n\n' + formatTodoStateSummary(updatedTodos, now),
+ state: {
+ todos: { items: updatedTodos, updatedAt: now },
+ },
+ success: true,
+ };
+ };
+
+ /**
+ * Mark todo items as done by their indices
+ */
+ completeTodos = async (
+ params: CompleteTodosParams,
+ ctx: BuiltinToolContext,
+ ): Promise<BuiltinToolResult> => {
+ const { indices } = params;
+
+ if (!indices || indices.length === 0) {
+ return {
+ content: 'No indices provided to complete.',
+ success: false,
+ };
+ }
+
+ const existingTodos = getTodosFromContext(ctx);
+
+ if (existingTodos.length === 0) {
+ const now = new Date().toISOString();
+ return {
+ content: 'No todos to complete. The list is empty.\n\n' + formatTodoStateSummary([], now),
+ state: {
+ completedIndices: [],
+ todos: { items: [], updatedAt: now },
+ },
+ success: true,
+ };
+ }
+
+ // Validate indices
+ const validIndices = indices.filter((i: number) => i >= 0 && i < existingTodos.length);
+ const invalidIndices = indices.filter((i: number) => i < 0 || i >= existingTodos.length);
+
+ if (validIndices.length === 0) {
+ return {
+ content: `Invalid indices: ${indices.join(', ')}. Valid range is 0-${existingTodos.length - 1}.`,
+ success: false,
+ };
+ }
+
+ // Mark items as completed
+ const updatedTodos = existingTodos.map((todo, index) => {
+ if (validIndices.includes(index)) {
+ return { ...todo, completed: true };
+ }
+ return todo;
+ });
+
+ const completedItems = validIndices.map((i: number) => existingTodos[i].text);
+ const now = new Date().toISOString();
+
+ // Format response: action summary + todo state
+ let actionSummary = `✔️ Completed ${validIndices.length} item${validIndices.length > 1 ? 's' : ''}:\n`;
+ actionSummary += completedItems.map((text: string) => `- ${text}`).join('\n');
+
+ if (invalidIndices.length > 0) {
+ actionSummary += `\n\nNote: Ignored invalid indices: ${invalidIndices.join(', ')}`;
+ }
+
+ return {
+ content: actionSummary + '\n\n' + formatTodoStateSummary(updatedTodos, now),
+ state: {
+ completedIndices: validIndices,
+ todos: { items: updatedTodos, updatedAt: now },
+ },
+ success: true,
+ };
+ };
+
+ /**
+ * Remove todo items by indices
+ */
+ removeTodos = async (
+ params: RemoveTodosParams,
+ ctx: BuiltinToolContext,
+ ): Promise<BuiltinToolResult> => {
+ const { indices } = params;
+
+ if (!indices || indices.length === 0) {
+ return {
+ content: 'No indices provided to remove.',
+ success: false,
+ };
+ }
+
+ const existingTodos = getTodosFromContext(ctx);
+
+ if (existingTodos.length === 0) {
+ const now = new Date().toISOString();
+ return {
+ content: 'No todos to remove. The list is empty.\n\n' + formatTodoStateSummary([], now),
+ state: {
+ removedIndices: [],
+ todos: { items: [], updatedAt: now },
+ },
+ success: true,
+ };
+ }
+
+ // Validate indices
+ const validIndices = indices.filter((i: number) => i >= 0 && i < existingTodos.length);
+ const invalidIndices = indices.filter((i: number) => i < 0 || i >= existingTodos.length);
+
+ if (validIndices.length === 0) {
+ return {
+ content: `Invalid indices: ${indices.join(', ')}. Valid range is 0-${existingTodos.length - 1}.`,
+ success: false,
+ };
+ }
+
+ // Remove items
+ const removedItems = validIndices.map((i: number) => existingTodos[i].text);
+ const updatedTodos = existingTodos.filter((_, index) => !validIndices.includes(index));
+ const now = new Date().toISOString();
+
+ // Format response: action summary + todo state
+ let actionSummary = `🗑️ Removed ${validIndices.length} item${validIndices.length > 1 ? 's' : ''}:\n`;
+ actionSummary += removedItems.map((text: string) => `- ${text}`).join('\n');
+
+ if (invalidIndices.length > 0) {
+ actionSummary += `\n\nNote: Ignored invalid indices: ${invalidIndices.join(', ')}`;
+ }
+
+ return {
+ content: actionSummary + '\n\n' + formatTodoStateSummary(updatedTodos, now),
+ state: {
+ removedIndices: validIndices,
+ todos: { items: updatedTodos, updatedAt: now },
+ },
+ success: true,
+ };
+ };
+
+ /**
+ * Clear todo items
+ */
+ clearTodos = async (
+ params: ClearTodosParams,
+ ctx: BuiltinToolContext,
+ ): Promise<BuiltinToolResult> => {
+ const { mode } = params;
+
+ const existingTodos = getTodosFromContext(ctx);
+
+ if (existingTodos.length === 0) {
+ const now = new Date().toISOString();
+ return {
+ content: 'Todo list is already empty.\n\n' + formatTodoStateSummary([], now),
+ state: {
+ clearedCount: 0,
+ mode,
+ todos: { items: [], updatedAt: now },
+ },
+ success: true,
+ };
+ }
+
+ let updatedTodos: TodoItem[];
+ let clearedCount: number;
+ let actionSummary: string;
+
+ if (mode === 'all') {
+ clearedCount = existingTodos.length;
+ updatedTodos = [];
+ actionSummary = `🧹 Cleared all ${clearedCount} item${clearedCount > 1 ? 's' : ''} from todo list.`;
+ } else {
+ // mode === 'completed'
+ updatedTodos = existingTodos.filter((todo) => !todo.completed);
+ clearedCount = existingTodos.length - updatedTodos.length;
+
+ if (clearedCount === 0) {
+ actionSummary = 'No completed items to clear.';
+ } else {
+ actionSummary = `🧹 Cleared ${clearedCount} completed item${clearedCount > 1 ? 's' : ''}.`;
+ }
+ }
+
+ const now = new Date().toISOString();
+
+ return {
+ content: actionSummary + '\n\n' + formatTodoStateSummary(updatedTodos, now),
+ state: {
+ clearedCount,
+ mode,
+ todos: { items: updatedTodos, updatedAt: now },
+ },
+ success: true,
+ };
+ };
+}
+
+// Export the executor instance for registration
+export const gtdExecutor = new GTDExecutor();
diff --git a/packages/builtin-tool-gtd/src/index.ts b/packages/builtin-tool-gtd/src/index.ts
new file mode 100644
index 00000000000..95ce02e077d
--- /dev/null
+++ b/packages/builtin-tool-gtd/src/index.ts
@@ -0,0 +1,3 @@
+export * from './manifest';
+export * from './systemRole';
+export * from './types';
diff --git a/packages/builtin-tool-gtd/src/manifest.ts b/packages/builtin-tool-gtd/src/manifest.ts
new file mode 100644
index 00000000000..3c886aa7657
--- /dev/null
+++ b/packages/builtin-tool-gtd/src/manifest.ts
@@ -0,0 +1,183 @@
+import type { BuiltinToolManifest } from '@lobechat/types';
+
+import { systemPrompt } from './systemRole';
+import { GTDApiName } from './types';
+
+export const GTDIdentifier = 'lobe-gtd';
+
+export const GTDManifest: BuiltinToolManifest = {
+ /* eslint-disable sort-keys-fix/sort-keys-fix */
+ api: [
+ // ==================== Quick Todo ====================
+ {
+ description: 'Create new todo items. Pass an array of text strings.',
+ name: GTDApiName.createTodos,
+ humanIntervention: 'always',
+ renderDisplayControl: 'expand',
+ parameters: {
+ properties: {
+ adds: {
+ description: 'Array of todo item texts to create.',
+ items: { type: 'string' },
+ type: 'array',
+ },
+ },
+ required: ['items'],
+ type: 'object',
+ },
+ },
+ {
+ description:
+ 'Update todo items with batch operations. Each operation specifies a type (add, update, remove, complete) and the relevant data.',
+ name: GTDApiName.updateTodos,
+ renderDisplayControl: 'expand',
+ parameters: {
+ properties: {
+ operations: {
+ description: 'Array of update operations to apply.',
+ items: {
+ properties: {
+ type: {
+ description: 'Operation type: add, update, remove, or complete.',
+ enum: ['add', 'update', 'remove', 'complete'],
+ type: 'string',
+ },
+ text: {
+ description: 'For "add": the text to add.',
+ type: 'string',
+ },
+ index: {
+ description:
+ 'For "update", "remove", "complete": the index of the item (0-based).',
+ type: 'number',
+ },
+ newText: {
+ description: 'For "update": the new text.',
+ type: 'string',
+ },
+ completed: {
+ description: 'For "update": the new completed status.',
+ type: 'boolean',
+ },
+ },
+ required: ['type'],
+ type: 'object',
+ },
+ type: 'array',
+ },
+ },
+ required: ['operations'],
+ type: 'object',
+ },
+ },
+ {
+ description: 'Mark todo items as completed by their indices (0-based).',
+ name: GTDApiName.completeTodos,
+ renderDisplayControl: 'expand',
+ parameters: {
+ properties: {
+ indices: {
+ description: 'Array of item indices (0-based) to mark as completed.',
+ items: { type: 'number' },
+ type: 'array',
+ },
+ },
+ required: ['indices'],
+ type: 'object',
+ },
+ },
+ {
+ description: 'Remove todo items by their indices (0-based).',
+ name: GTDApiName.removeTodos,
+ humanIntervention: 'always',
+ renderDisplayControl: 'expand',
+ parameters: {
+ properties: {
+ indices: {
+ description: 'Array of item indices (0-based) to remove.',
+ items: { type: 'number' },
+ type: 'array',
+ },
+ },
+ required: ['indices'],
+ type: 'object',
+ },
+ },
+ {
+ description: 'Clear todo items. Can clear only completed items or all items.',
+ name: GTDApiName.clearTodos,
+ humanIntervention: 'always',
+ renderDisplayControl: 'expand',
+ parameters: {
+ properties: {
+ mode: {
+ description: '"completed" clears only done items, "all" clears the entire list.',
+ enum: ['completed', 'all'],
+ type: 'string',
+ },
+ },
+ required: ['mode'],
+ type: 'object',
+ },
+ },
+
+ // ==================== Planning ====================
+ {
+ description:
+ 'Create a high-level plan document describing a goal and its context. Plans define the strategic direction (the "what" and "why"), while todos handle the actionable steps.',
+ name: GTDApiName.createPlan,
+ parameters: {
+ properties: {
+ goal: {
+ description: 'The main goal or objective to achieve.',
+ type: 'string',
+ },
+ context: {
+ description:
+ 'Additional context, constraints, background information, or strategic considerations relevant to the goal.',
+ type: 'string',
+ },
+ },
+ required: ['goal'],
+ type: 'object',
+ },
+ },
+ {
+ description:
+ 'Update an existing plan document. Use this to modify the goal, context, or mark the plan as completed.',
+ name: GTDApiName.updatePlan,
+ parameters: {
+ properties: {
+ planId: {
+ description: 'The ID of the plan to update.',
+ type: 'string',
+ },
+ goal: {
+ description: 'Updated goal description.',
+ type: 'string',
+ },
+ context: {
+ description: 'Updated context information.',
+ type: 'string',
+ },
+ completed: {
+ description: 'Mark the plan as completed.',
+ type: 'boolean',
+ },
+ },
+ required: ['planId'],
+ type: 'object',
+ },
+ },
+ ],
+ identifier: GTDIdentifier,
+ meta: {
+ avatar: '✅',
+ description: 'Plan goals and track progress with GTD methodology',
+ title: 'GTD Tools',
+ },
+ systemRole: systemPrompt,
+ type: 'builtin',
+};
+
+export { GTDApiName } from './types';
diff --git a/packages/builtin-tool-gtd/src/systemRole.ts b/packages/builtin-tool-gtd/src/systemRole.ts
new file mode 100644
index 00000000000..d4fb63b5cc6
--- /dev/null
+++ b/packages/builtin-tool-gtd/src/systemRole.ts
@@ -0,0 +1,65 @@
+export const systemPrompt = `You have GTD (Getting Things Done) tools to help manage plans and todos effectively. These tools support two levels of task management:
+
+- **Plan**: A high-level strategic document describing goals, context, and overall direction. Plans do NOT contain actionable steps - they define the "what" and "why".
+- **Todo**: The concrete execution list with actionable items. Todos define the "how" - specific tasks to accomplish the plan.
+
+<tool_overview>
+**Planning Tools** - For high-level goal documentation:
+- \`createPlan\`: Create a strategic plan document with goal and context
+- \`updatePlan\`: Update plan details or mark as completed
+
+**Todo Tools** - For actionable execution items:
+- \`createTodos\`: Create new todo items from text array
+- \`updateTodos\`: Batch update todos (add, update, remove, complete operations)
+- \`completeTodos\`: Mark items as done by indices
+- \`removeTodos\`: Remove items by indices
+- \`clearTodos\`: Clear completed or all items
+</tool_overview>
+
+<when_to_use>
+**Use Plans when:**
+- Documenting high-level goals and objectives
+- Capturing context, constraints, and background information
+- Defining the strategic direction before execution
+- Recording the "why" behind a project or initiative
+
+**Use Todos when:**
+- Breaking down a plan into actionable steps
+- Capturing specific tasks to execute
+- Tracking progress on concrete deliverables
+- Managing day-to-day action items
+</when_to_use>
+
+<workflow_patterns>
+**Pattern 1: Plan-First Approach**
+1. User states a goal → Use \`createPlan\` to document the goal and context
+2. Break down the plan into todos using \`createTodos\`
+3. Execute and track with \`completeTodos\`
+4. Mark plan completed with \`updatePlan\` when all todos are done
+
+**Pattern 2: Quick Capture**
+1. Capture action items directly with \`createTodos\`
+2. Track progress with \`completeTodos\`
+3. Clean up with \`clearTodos\` mode: "completed"
+
+**Pattern 3: Plan + Todo Combined**
+1. Create a plan to document the high-level goal and context
+2. Use todos as the execution checklist derived from the plan
+3. Update plan status when execution is complete
+</workflow_patterns>
+
+<best_practices>
+- **Separate concerns**: Plans describe goals; Todos list actions
+- **Actionable todos**: Each todo should be a concrete, completable task
+- **Context in plans**: Use plan's context field to capture constraints and background
+- **Regular cleanup**: Clear completed todos to keep the list focused
+- **Track progress**: Use todo completion to measure plan progress
+</best_practices>
+
+<response_format>
+When working with GTD tools:
+- Confirm actions: "Created plan: [goal]" or "Added [n] todo items"
+- Show progress: "Completed [n] items, [m] remaining"
+- Be concise: Brief confirmations, not verbose explanations
+- **NEVER repeat the todo list in your response** - Users can already see the todos in the UI component. Do not list or enumerate the todo items in your text output.
+</response_format>`;
diff --git a/packages/builtin-tool-gtd/src/types.ts b/packages/builtin-tool-gtd/src/types.ts
new file mode 100644
index 00000000000..69fe63f0ab9
--- /dev/null
+++ b/packages/builtin-tool-gtd/src/types.ts
@@ -0,0 +1,203 @@
+/**
+ * API names for GTD (Getting Things Done) tool
+ *
+ * GTD Tools help users and agents manage tasks effectively.
+ * These tools can be used by:
+ * - LobeAI default assistant for user task management
+ * - Group Supervisor for multi-agent task orchestration
+ *
+ * MVP version focuses on Plan and Todo functionality.
+ * Task management will be added in future iterations.
+ */
+export const GTDApiName = {
+ // ==================== Quick Todo ====================
+ /** Clear completed or all todos */
+ clearTodos: 'clearTodos',
+
+ /** Mark todo items as done by indices */
+ completeTodos: 'completeTodos',
+
+ // ==================== Planning ====================
+ /** Create a structured plan by breaking down a goal into actionable steps */
+ createPlan: 'createPlan',
+
+ /** Create new todo items */
+ createTodos: 'createTodos',
+
+ /** Remove todo items by indices */
+ removeTodos: 'removeTodos',
+
+ /** Update an existing plan */
+ updatePlan: 'updatePlan',
+
+ /** Update todo items with batch operations (add, update, remove, complete) */
+ updateTodos: 'updateTodos',
+} as const;
+
+export type GTDApiNameType = (typeof GTDApiName)[keyof typeof GTDApiName];
+
+// ==================== Todo Item ====================
+
+export interface TodoItem {
+ /** Whether the item is completed */
+ completed: boolean;
+ /** The todo item text */
+ text: string;
+}
+
+export interface TodoList {
+ items: TodoItem[];
+ updatedAt: string;
+}
+
+// ==================== Todo Params ====================
+
+/**
+ * Create new todo items
+ * - AI input: { adds: string[] } - array of text strings from AI
+ * - After user edit: { items: TodoItem[] } - saved format with TodoItem objects
+ */
+export interface CreateTodosParams {
+ /** Array of text strings from AI */
+ adds?: string[];
+ /** Array of TodoItem objects (saved format after user edit) */
+ items?: TodoItem[];
+}
+
+/**
+ * Update operation types for batch updates
+ */
+export type TodoUpdateOperationType = 'add' | 'update' | 'remove' | 'complete';
+
+/**
+ * Single update operation
+ */
+export interface TodoUpdateOperation {
+ /** For 'update': the new completed status */
+ completed?: boolean;
+ /** For 'update', 'remove', 'complete': the index of the item (0-based) */
+ index?: number;
+ /** For 'update': the new text */
+ newText?: string;
+ /** For 'add': the text to add */
+ text?: string;
+ /** Operation type */
+ type: TodoUpdateOperationType;
+}
+
+/**
+ * Update todo list with batch operations
+ * Supports: add, update, remove, complete
+ */
+export interface UpdateTodosParams {
+ /** Array of update operations to apply */
+ operations: TodoUpdateOperation[];
+}
+
+/**
+ * Mark todo items as completed by indices
+ */
+export interface CompleteTodosParams {
+ /** Indices of items to mark as completed (0-based) */
+ indices: number[];
+}
+
+/**
+ * Remove todo items by indices
+ */
+export interface RemoveTodosParams {
+ /** Indices of items to remove (0-based) */
+ indices: number[];
+}
+
+/**
+ * Clear todo items
+ */
+export interface ClearTodosParams {
+ /** Clear mode: 'completed' only clears done items, 'all' clears everything */
+ mode: 'completed' | 'all';
+}
+
+// ==================== Todo State Types for Render ====================
+
+export interface CreateTodosState {
+ /** Items that were created */
+ createdItems: string[];
+ /** Current todo list after creation */
+ todos: TodoList;
+}
+
+export interface UpdateTodosState {
+ /** Operations that were applied */
+ appliedOperations: TodoUpdateOperation[];
+ /** Current todo list after update */
+ todos: TodoList;
+}
+
+export interface CompleteTodosState {
+ /** Indices that were completed */
+ completedIndices: number[];
+ /** Current todo list after completion */
+ todos: TodoList;
+}
+
+export interface RemoveTodosState {
+ /** Indices that were removed */
+ removedIndices: number[];
+ /** Current todo list after removal */
+ todos: TodoList;
+}
+
+export interface ClearTodosState {
+ /** Number of items cleared */
+ clearedCount: number;
+ /** Mode used for clearing */
+ mode: 'completed' | 'all';
+ /** Current todo list after clearing */
+ todos: TodoList;
+}
+
+// ==================== Planning Params ====================
+
+/**
+ * Create a high-level plan document
+ * Plans define the strategic direction (what and why), not actionable steps
+ */
+export interface CreatePlanParams {
+ /** Additional context, constraints, or strategic considerations */
+ context?: string;
+ /** The main goal or objective to achieve */
+ goal: string;
+}
+
+export interface UpdatePlanParams {
+ /** Mark plan as completed */
+ completed?: boolean;
+ /** Updated context information */
+ context?: string;
+ /** Updated goal */
+ goal?: string;
+ /** Plan ID to update */
+ planId: string;
+}
+
+// ==================== Plan Result Types ====================
+
+/**
+ * A high-level plan document
+ * Contains goal and context, but no steps (steps are managed via Todos)
+ */
+export interface Plan {
+ /** Whether the plan is completed */
+ completed: boolean;
+ /** Additional context and strategic information */
+ context?: string;
+ /** Creation timestamp */
+ createdAt: string;
+ /** The main goal or objective */
+ goal: string;
+ /** Unique plan identifier */
+ id: string;
+ /** Last update timestamp */
+ updatedAt: string;
+}
diff --git a/packages/builtin-tool-knowledge-base/package.json b/packages/builtin-tool-knowledge-base/package.json
new file mode 100644
index 00000000000..33e03dc2373
--- /dev/null
+++ b/packages/builtin-tool-knowledge-base/package.json
@@ -0,0 +1,24 @@
+{
+ "name": "@lobechat/builtin-tool-knowledge-base",
+ "version": "1.0.0",
+ "private": true,
+ "exports": {
+ ".": "./src/index.ts",
+ "./client": "./src/client/index.ts",
+ "./executionRuntime": "./src/ExecutionRuntime/index.ts"
+ },
+ "main": "./src/index.ts",
+ "dependencies": {
+ "@lobechat/prompts": "workspace:*",
+ "@lobechat/types": "workspace:*"
+ },
+ "peerDependencies": {
+ "@lobehub/ui": "*",
+ "antd": "^5",
+ "antd-style": "*",
+ "polished": "*",
+ "react": "*",
+ "react-i18next": "*",
+ "react-layout-kit": "*"
+ }
+}
diff --git a/packages/builtin-tool-knowledge-base/src/ExecutionRuntime/index.ts b/packages/builtin-tool-knowledge-base/src/ExecutionRuntime/index.ts
new file mode 100644
index 00000000000..1b657612969
--- /dev/null
+++ b/packages/builtin-tool-knowledge-base/src/ExecutionRuntime/index.ts
@@ -0,0 +1,119 @@
+import { formatSearchResults, promptFileContents, promptNoSearchResults } from '@lobechat/prompts';
+import { BuiltinServerRuntimeOutput } from '@lobechat/types';
+
+import {
+ ReadKnowledgeArgs,
+ ReadKnowledgeState,
+ SearchKnowledgeBaseArgs,
+ SearchKnowledgeBaseState,
+} from '../types';
+
+interface FileContentResult {
+ content: string;
+ error?: string;
+ fileId: string;
+ filename: string;
+ preview?: string;
+ totalCharCount?: number;
+ totalLineCount?: number;
+}
+
+interface RagService {
+ getFileContents: (fileIds: string[], signal?: AbortSignal) => Promise<FileContentResult[]>;
+ semanticSearchForChat: (
+ params: { knowledgeIds?: string[]; query: string; topK: number },
+ signal?: AbortSignal,
+ ) => Promise<{ chunks: any[]; fileResults: any[] }>;
+}
+
+export class KnowledgeBaseExecutionRuntime {
+ private ragService: RagService;
+
+ constructor(ragService: RagService) {
+ this.ragService = ragService;
+ }
+
+ /**
+ * Search knowledge base and return file summaries with relevant chunks
+ */
+ async searchKnowledgeBase(
+ args: SearchKnowledgeBaseArgs,
+ options?: {
+ knowledgeBaseIds?: string[];
+ messageId?: string;
+ signal?: AbortSignal;
+ },
+ ): Promise<BuiltinServerRuntimeOutput> {
+ try {
+ const { query, topK = 20 } = args;
+
+ // Only search in knowledge bases, not agent files
+ // Agent files will be injected as full content in context-engine
+ const { chunks, fileResults } = await this.ragService.semanticSearchForChat(
+ { knowledgeIds: options?.knowledgeBaseIds, query, topK },
+ options?.signal,
+ );
+
+ if (chunks.length === 0) {
+ const state: SearchKnowledgeBaseState = { chunks: [], fileResults: [], totalResults: 0 };
+
+ return { content: promptNoSearchResults(query), state, success: true };
+ }
+
+ // Format search results for AI
+ const formattedContent = formatSearchResults(fileResults, query);
+
+ const state: SearchKnowledgeBaseState = { chunks, fileResults, totalResults: chunks.length };
+
+ return { content: formattedContent, state, success: true };
+ } catch (e) {
+ return {
+ content: `Error searching knowledge base: ${(e as Error).message}`,
+ error: e,
+ success: false,
+ };
+ }
+ }
+
+ /**
+ * Read full content of specific files from knowledge base
+ */
+ async readKnowledge(
+ args: ReadKnowledgeArgs,
+ options?: { signal?: AbortSignal },
+ ): Promise<BuiltinServerRuntimeOutput> {
+ try {
+ const { fileIds } = args;
+
+ if (!fileIds || fileIds.length === 0) {
+ return {
+ content: 'Error: No file IDs provided',
+ success: false,
+ };
+ }
+
+ const fileContents = await this.ragService.getFileContents(fileIds, options?.signal);
+
+ const formattedContent = promptFileContents(fileContents);
+
+ const state: ReadKnowledgeState = {
+ files: fileContents.map((file) => ({
+ error: file.error,
+ fileId: file.fileId,
+ filename: file.filename,
+ preview: file.preview,
+ totalCharCount: file.totalCharCount,
+ totalLineCount: file.totalLineCount,
+ })),
+ };
+
+ return { content: formattedContent, state, success: true };
+ } catch (e) {
+ return {
+ content: `Error reading knowledge: ${(e as Error).message}`,
+ error: e,
+ success: false,
+ };
+ }
+ }
+}
diff --git a/src/tools/knowledge-base/Render/ReadKnowledge/FileCard.tsx b/packages/builtin-tool-knowledge-base/src/client/Render/ReadKnowledge/FileCard.tsx
similarity index 88%
rename from src/tools/knowledge-base/Render/ReadKnowledge/FileCard.tsx
rename to packages/builtin-tool-knowledge-base/src/client/Render/ReadKnowledge/FileCard.tsx
index e9ff6f1d2f0..5dfa822ccec 100644
--- a/src/tools/knowledge-base/Render/ReadKnowledge/FileCard.tsx
+++ b/packages/builtin-tool-knowledge-base/src/client/Render/ReadKnowledge/FileCard.tsx
@@ -3,13 +3,10 @@
import { Alert, Text } from '@lobehub/ui';
import { Descriptions } from 'antd';
import { createStyles } from 'antd-style';
-import { memo } from 'react';
-import { useTranslation } from 'react-i18next';
+import { ComponentType, memo } from 'react';
import { Flexbox } from 'react-layout-kit';
-import FileIcon from '@/components/FileIcon';
-
-import { FileContentDetail } from '../../type';
+import { FileContentDetail } from '../../../types';
const useStyles = createStyles(({ token, css }) => {
return {
@@ -72,11 +69,15 @@ const useStyles = createStyles(({ token, css }) => {
});
interface FileCardProps {
+ FileIcon: ComponentType<{ fileName: string; size: number }>;
file: FileContentDetail;
+ labels: {
+ chars: string;
+ lines: string;
+ };
}
-const FileCard = memo<FileCardProps>(({ file }) => {
- const { t } = useTranslation('tool');
+const FileCard = memo<FileCardProps>(({ file, FileIcon, labels }) => {
const { styles } = useStyles();
if (file.error) {
@@ -118,11 +119,11 @@ const FileCard = memo<FileCardProps>(({ file }) => {
items={[
{
children: file.totalCharCount?.toLocaleString(),
- label: t('lobe-knowledge-base.readKnowledge.meta.chars'),
+ label: labels.chars,
},
{
children: file.totalLineCount?.toLocaleString(),
- label: t('lobe-knowledge-base.readKnowledge.meta.lines'),
+ label: labels.lines,
},
]}
size="small"
diff --git a/packages/builtin-tool-knowledge-base/src/client/Render/ReadKnowledge/index.tsx b/packages/builtin-tool-knowledge-base/src/client/Render/ReadKnowledge/index.tsx
new file mode 100644
index 00000000000..01cc7c1142f
--- /dev/null
+++ b/packages/builtin-tool-knowledge-base/src/client/Render/ReadKnowledge/index.tsx
@@ -0,0 +1,37 @@
+'use client';
+
+import { BuiltinRenderProps } from '@lobechat/types';
+import { ComponentType, memo } from 'react';
+import { Flexbox } from 'react-layout-kit';
+
+import { ReadKnowledgeArgs, ReadKnowledgeState } from '../../../types';
+import FileCard from './FileCard';
+
+export interface ReadKnowledgeRenderProps extends Pick<
+ BuiltinRenderProps<ReadKnowledgeArgs, ReadKnowledgeState>,
+ 'pluginState'
+> {
+ FileIcon: ComponentType<{ fileName: string; size: number }>;
+ labels: {
+ chars: string;
+ lines: string;
+ };
+}
+
+const ReadKnowledge = memo<ReadKnowledgeRenderProps>(({ pluginState, FileIcon, labels }) => {
+ const { files } = pluginState || {};
+
+ if (!files || files.length === 0) {
+ return null;
+ }
+
+ return (
+ <Flexbox gap={12} horizontal style={{ flexWrap: 'wrap' }}>
+ {files.map((file) => (
+ <FileCard FileIcon={FileIcon} file={file} key={file.fileId} labels={labels} />
+ ))}
+ </Flexbox>
+ );
+});
+
+export default ReadKnowledge;
diff --git a/packages/builtin-tool-knowledge-base/src/client/Render/SearchKnowledgeBase/Item/index.tsx b/packages/builtin-tool-knowledge-base/src/client/Render/SearchKnowledgeBase/Item/index.tsx
new file mode 100644
index 00000000000..bf139914411
--- /dev/null
+++ b/packages/builtin-tool-knowledge-base/src/client/Render/SearchKnowledgeBase/Item/index.tsx
@@ -0,0 +1,58 @@
+'use client';
+
+import { FileSearchResult } from '@lobechat/types';
+import { Text, Tooltip } from '@lobehub/ui';
+import { ComponentType, memo } from 'react';
+import { Center, Flexbox } from 'react-layout-kit';
+
+import { useStyles } from './style';
+
+export interface FileItemProps extends FileSearchResult {
+ FileIcon: ComponentType<{
+ fileName: string;
+ size: number;
+ variant?: 'raw' | 'file' | 'folder';
+ }>;
+ index: number;
+ isMobile?: boolean;
+ onFileClick?: (params: { chunkId: string; chunkText: string; fileId: string }) => void;
+}
+
+const FileItem = memo<FileItemProps>(
+ ({ fileId, fileName, relevanceScore, topChunks, FileIcon, isMobile, onFileClick }) => {
+ const { styles, cx } = useStyles();
+
+ // Use the first chunk for preview
+ const firstChunk = topChunks[0];
+
+ return (
+ <Flexbox
+ align={'center'}
+ className={cx(styles.container, isMobile && styles.mobile)}
+ gap={4}
+ horizontal
+ key={fileId}
+ onClick={(e) => {
+ e.stopPropagation();
+ if (firstChunk && onFileClick) {
+ onFileClick({
+ chunkId: firstChunk.id,
+ chunkText: firstChunk.text,
+ fileId,
+ });
+ }
+ }}
+ >
+ <FileIcon fileName={fileName} size={20} variant={'raw'} />
+ <Flexbox gap={12} horizontal justify={'space-between'} style={{ maxWidth: 200 }}>
+ <Text ellipsis>{fileName}</Text>
+ <Tooltip title={`Relevance: ${(relevanceScore * 100).toFixed(1)}%`}>
+ <Center className={styles.badge}>{relevanceScore.toFixed(2)}</Center>
+ </Tooltip>
+ </Flexbox>
+ </Flexbox>
+ );
+ },
+);
+
+export default FileItem;
diff --git a/src/features/ChatList/Messages/Assistant/FileChunks/Item/style.ts b/packages/builtin-tool-knowledge-base/src/client/Render/SearchKnowledgeBase/Item/style.ts
similarity index 100%
rename from src/features/ChatList/Messages/Assistant/FileChunks/Item/style.ts
rename to packages/builtin-tool-knowledge-base/src/client/Render/SearchKnowledgeBase/Item/style.ts
diff --git a/packages/builtin-tool-knowledge-base/src/client/Render/SearchKnowledgeBase/index.tsx b/packages/builtin-tool-knowledge-base/src/client/Render/SearchKnowledgeBase/index.tsx
new file mode 100644
index 00000000000..927e14114a6
--- /dev/null
+++ b/packages/builtin-tool-knowledge-base/src/client/Render/SearchKnowledgeBase/index.tsx
@@ -0,0 +1,42 @@
+'use client';
+
+import { BuiltinRenderProps } from '@lobechat/types';
+import { ComponentType, memo } from 'react';
+import { Flexbox } from 'react-layout-kit';
+
+import { SearchKnowledgeBaseArgs, SearchKnowledgeBaseState } from '../../../types';
+import FileItem from './Item';
+
+export interface SearchKnowledgeBaseRenderProps extends Pick<
+ BuiltinRenderProps<SearchKnowledgeBaseArgs, SearchKnowledgeBaseState>,
+ 'pluginState'
+> {
+ FileIcon: ComponentType<{ fileName: string; size: number; variant?: 'raw' | 'file' | 'folder' }>;
+ isMobile?: boolean;
+ onFileClick?: (params: { chunkId: string; chunkText: string; fileId: string }) => void;
+}
+
+const SearchKnowledgeBase = memo<SearchKnowledgeBaseRenderProps>(
+ ({ pluginState, FileIcon, isMobile, onFileClick }) => {
+ const { fileResults } = pluginState || {};
+
+ return (
+ <Flexbox gap={8} horizontal wrap={'wrap'}>
+ {fileResults?.map((file, index) => {
+ return (
+ <FileItem
+ FileIcon={FileIcon}
+ index={index}
+ isMobile={isMobile}
+ key={file.fileId}
+ onFileClick={onFileClick}
+ {...file}
+ />
+ );
+ })}
+ </Flexbox>
+ );
+ },
+);
+
+export default SearchKnowledgeBase;
diff --git a/packages/builtin-tool-knowledge-base/src/client/Render/index.ts b/packages/builtin-tool-knowledge-base/src/client/Render/index.ts
new file mode 100644
index 00000000000..6838f29a44a
--- /dev/null
+++ b/packages/builtin-tool-knowledge-base/src/client/Render/index.ts
@@ -0,0 +1,12 @@
+import ReadKnowledge from './ReadKnowledge';
+import SearchKnowledgeBase from './SearchKnowledgeBase';
+
+export const KnowledgeBaseRenders = {
+ readKnowledge: ReadKnowledge,
+ searchKnowledgeBase: SearchKnowledgeBase,
+};
+
+
+
+export {default as ReadKnowledge} from './ReadKnowledge';
+export {default as SearchKnowledgeBase} from './SearchKnowledgeBase';
\ No newline at end of file
diff --git a/packages/builtin-tool-knowledge-base/src/client/index.ts b/packages/builtin-tool-knowledge-base/src/client/index.ts
new file mode 100644
index 00000000000..992fe6c1c31
--- /dev/null
+++ b/packages/builtin-tool-knowledge-base/src/client/index.ts
@@ -0,0 +1,5 @@
+export { KnowledgeBaseRenders, ReadKnowledge, SearchKnowledgeBase } from './Render';
+
+// Re-export types and manifest for convenience
+export { KnowledgeBaseManifest } from '../manifest';
+export * from '../types';
diff --git a/packages/builtin-tool-knowledge-base/src/index.ts b/packages/builtin-tool-knowledge-base/src/index.ts
new file mode 100644
index 00000000000..0fdfdaf8f7b
--- /dev/null
+++ b/packages/builtin-tool-knowledge-base/src/index.ts
@@ -0,0 +1,11 @@
+export { KnowledgeBaseManifest } from './manifest';
+export { systemPrompt } from './systemRole';
+export {
+ type FileContentDetail,
+ KnowledgeBaseApiName,
+ KnowledgeBaseIdentifier,
+ type ReadKnowledgeArgs,
+ type ReadKnowledgeState,
+ type SearchKnowledgeBaseArgs,
+ type SearchKnowledgeBaseState,
+} from './types';
diff --git a/packages/builtin-tool-knowledge-base/src/manifest.ts b/packages/builtin-tool-knowledge-base/src/manifest.ts
new file mode 100644
index 00000000000..f62d61e9f43
--- /dev/null
+++ b/packages/builtin-tool-knowledge-base/src/manifest.ts
@@ -0,0 +1,60 @@
+import { BuiltinToolManifest } from '@lobechat/types';
+
+import { systemPrompt } from './systemRole';
+import { KnowledgeBaseApiName, KnowledgeBaseIdentifier } from './types';
+
+export const KnowledgeBaseManifest: BuiltinToolManifest = {
+ api: [
+ {
+ description:
+ 'Search through knowledge base using semantic vector search to find relevant files and chunks. Returns a summary of matching files with their relevance scores and brief excerpts. Use this first to discover which files contain relevant information. IMPORTANT: Since this uses vector-based search, always resolve pronouns and references to concrete entities (e.g., use "authentication system" instead of "it").',
+ name: KnowledgeBaseApiName.searchKnowledgeBase,
+ parameters: {
+ properties: {
+ query: {
+ description:
+ 'The search query to find relevant information. Be specific and use concrete entities. IMPORTANT: Resolve all pronouns and references (like "it", "that", "this") to actual entity names before searching, as this uses semantic vector search which works best with concrete terms.',
+ type: 'string',
+ },
+ topK: {
+ default: 15,
+ description:
+ 'Number of top relevant chunks to return (default: 15). Each file will include the most relevant chunks.',
+ maximum: 100,
+ minimum: 5,
+ type: 'number',
+ },
+ },
+ required: ['query'],
+ type: 'object',
+ },
+ },
+ {
+ description:
+ 'Read the full content of specific files from the knowledge base. Use this after searchKnowledgeBase to get complete information from relevant files. You can read multiple files at once.',
+ name: KnowledgeBaseApiName.readKnowledge,
+ parameters: {
+ properties: {
+ fileIds: {
+ description:
+ 'Array of file IDs to read. Get these IDs from searchKnowledgeBase results.',
+ items: {
+ type: 'string',
+ },
+ type: 'array',
+ },
+ },
+ required: ['fileIds'],
+ type: 'object',
+ },
+ },
+ ],
+ identifier: KnowledgeBaseIdentifier,
+ meta: {
+ avatar: '📚',
+ description: 'Search and retrieve information from knowledge bases',
+ title: 'Knowledge Base',
+ },
+ systemRole: systemPrompt,
+ type: 'builtin',
+};
diff --git a/src/tools/knowledge-base/systemRole.ts b/packages/builtin-tool-knowledge-base/src/systemRole.ts
similarity index 100%
rename from src/tools/knowledge-base/systemRole.ts
rename to packages/builtin-tool-knowledge-base/src/systemRole.ts
diff --git a/src/tools/knowledge-base/type.ts b/packages/builtin-tool-knowledge-base/src/types.ts
similarity index 68%
rename from src/tools/knowledge-base/type.ts
rename to packages/builtin-tool-knowledge-base/src/types.ts
index f98b600c95b..9ba46da4403 100644
--- a/src/tools/knowledge-base/type.ts
+++ b/packages/builtin-tool-knowledge-base/src/types.ts
@@ -1,5 +1,11 @@
import { ChatSemanticSearchChunk, FileSearchResult } from '@lobechat/types';
+export const KnowledgeBaseIdentifier = 'lobe-knowledge-base';
+
+export const KnowledgeBaseApiName = {
+ readKnowledge: 'readKnowledge',
+ searchKnowledgeBase: 'searchKnowledgeBase',
+};
export interface SearchKnowledgeBaseArgs {
query: string;
@@ -11,6 +17,10 @@ export interface SearchKnowledgeBaseState {
totalResults: number;
}
+export interface ReadKnowledgeArgs {
+ fileIds: string[];
+}
+
export interface FileContentDetail {
error?: string;
fileId: string;
diff --git a/packages/context-engine/package.json b/packages/context-engine/package.json
index 4dd05e99e82..e28dc848562 100644
--- a/packages/context-engine/package.json
+++ b/packages/context-engine/package.json
@@ -22,12 +22,14 @@
"@lobechat/types": "workspace:*",
"@lobechat/utils": "workspace:*",
"debug": "^4.4.3",
+ "es-toolkit": "^1.43.0",
"immer": "^10.2.0",
- "lodash-es": "^4.17.21",
- "ts-md5": "^2.0.1"
+ "ts-md5": "^2.0.1",
+ "unist-builder": "^4.0.0",
+ "xast-util-to-xml": "^4.0.0",
+ "xastscript": "^4.0.0"
},
"devDependencies": {
- "@types/debug": "^4.1.12",
- "@types/lodash-es": "^4.17.12"
+ "@types/debug": "^4.1.12"
}
}
diff --git a/packages/context-engine/src/base/BaseLastUserContentProvider.ts b/packages/context-engine/src/base/BaseLastUserContentProvider.ts
new file mode 100644
index 00000000000..0e9b8040996
--- /dev/null
+++ b/packages/context-engine/src/base/BaseLastUserContentProvider.ts
@@ -0,0 +1,174 @@
+import type { Message, PipelineContext, ProcessorOptions } from '../types';
+import { BaseProcessor } from './BaseProcessor';
+
+const SYSTEM_CONTEXT_START = '<!-- SYSTEM CONTEXT (NOT PART OF USER QUERY) -->';
+const SYSTEM_CONTEXT_END = '<!-- END SYSTEM CONTEXT -->';
+const CONTEXT_INSTRUCTION = `<context.instruction>following part contains context information injected by the system. Please follow these instructions:
+
+1. Always prioritize handling user-visible content.
+2. the context is only required when user's queries rely on it.
+</context.instruction>`;
+
+/**
+ * Base Provider for appending content to the last user message
+ * Used for injecting real-time context that should reflect the current state
+ */
+export abstract class BaseLastUserContentProvider extends BaseProcessor {
+ constructor(options: ProcessorOptions = {}) {
+ super(options);
+ }
+
+ /**
+ * Find the index of the last user message
+ */
+ protected findLastUserMessageIndex(messages: Message[]): number {
+ for (let i = messages.length - 1; i >= 0; i--) {
+ if (messages[i].role === 'user') {
+ return i;
+ }
+ }
+ return -1;
+ }
+
+ /**
+ * Get the text content from a message (handles both string and array content)
+ */
+ private getTextContent(content: string | any[]): string {
+ if (typeof content === 'string') {
+ return content;
+ }
+ if (Array.isArray(content)) {
+ const lastTextPart = content.findLast((part: any) => part.type === 'text');
+ return lastTextPart?.text || '';
+ }
+ return '';
+ }
+
+ /**
+ * Check if the content already has a system context wrapper
+ */
+ private hasSystemContextWrapper(content: string | any[]): boolean {
+ const textContent = this.getTextContent(content);
+ return textContent.includes(SYSTEM_CONTEXT_START) && textContent.includes(SYSTEM_CONTEXT_END);
+ }
+
+ /**
+ * Insert content into existing system context wrapper (before the END marker)
+ */
+ private insertIntoExistingWrapper(existingContent: string, newContextBlock: string): string {
+ const endMarkerIndex = existingContent.lastIndexOf(SYSTEM_CONTEXT_END);
+ if (endMarkerIndex === -1) {
+ return existingContent + '\n\n' + newContextBlock;
+ }
+
+ const beforeEnd = existingContent.slice(0, endMarkerIndex);
+ const afterEnd = existingContent.slice(endMarkerIndex);
+
+ return beforeEnd + newContextBlock + '\n' + afterEnd;
+ }
+
+ /**
+ * Check if the last user message already has a system context wrapper
+ */
+ protected hasExistingSystemContext(context: PipelineContext): boolean {
+ const lastUserIndex = this.findLastUserMessageIndex(context.messages);
+ if (lastUserIndex === -1) return false;
+
+ const content = context.messages[lastUserIndex].content;
+ return this.hasSystemContextWrapper(content);
+ }
+
+ /**
+ * Append content to the last user message
+ * Handles both string and array content types
+ * If system context wrapper already exists, inserts new content into it
+ */
+ protected appendToLastUserMessage(
+ context: PipelineContext,
+ contentToAppend: string,
+ ): PipelineContext {
+ const lastUserIndex = this.findLastUserMessageIndex(context.messages);
+
+ if (lastUserIndex === -1) {
+ return context;
+ }
+
+ const lastUserMessage = context.messages[lastUserIndex];
+ const currentContent = lastUserMessage.content;
+
+ // Handle string content
+ if (typeof currentContent === 'string') {
+ let newContent: string;
+
+ if (this.hasSystemContextWrapper(currentContent)) {
+ // Insert into existing wrapper
+ newContent = this.insertIntoExistingWrapper(currentContent, contentToAppend);
+ } else {
+ // Append normally
+ newContent = currentContent + '\n\n' + contentToAppend;
+ }
+
+ context.messages[lastUserIndex] = {
+ ...lastUserMessage,
+ content: newContent,
+ };
+ }
+ // Handle array content (multimodal messages)
+ else if (Array.isArray(currentContent)) {
+ const lastTextIndex = currentContent.findLastIndex((part: any) => part.type === 'text');
+
+ if (lastTextIndex !== -1) {
+ const newContent = [...currentContent];
+ const existingText = newContent[lastTextIndex].text;
+ let updatedText: string;
+
+ if (this.hasSystemContextWrapper(existingText)) {
+ // Insert into existing wrapper
+ updatedText = this.insertIntoExistingWrapper(existingText, contentToAppend);
+ } else {
+ // Append normally
+ updatedText = existingText + '\n\n' + contentToAppend;
+ }
+
+ newContent[lastTextIndex] = {
+ ...newContent[lastTextIndex],
+ text: updatedText,
+ };
+ context.messages[lastUserIndex] = {
+ ...lastUserMessage,
+ content: newContent,
+ };
+ } else {
+ // No text part found, add a new one
+ context.messages[lastUserIndex] = {
+ ...lastUserMessage,
+ content: [...currentContent, { text: contentToAppend, type: 'text' }],
+ };
+ }
+ }
+
+ return context;
+ }
+
+ /**
+ * Wrap content with system context markers
+ * Following the format from @lobechat/prompts files/index.ts
+ */
+ protected wrapWithSystemContext(content: string, contextType: string): string {
+ return `${SYSTEM_CONTEXT_START}
+${CONTEXT_INSTRUCTION}
+<${contextType}>
+${content}
+</${contextType}>
+${SYSTEM_CONTEXT_END}`;
+ }
+
+ /**
+ * Create a context block without the full wrapper (for inserting into existing wrapper)
+ */
+ protected createContextBlock(content: string, contextType: string): string {
+ return `<${contextType}>
+${content}
+</${contextType}>`;
+ }
+}
diff --git a/packages/context-engine/src/base/__tests__/BaseLastUserContentProvider.test.ts b/packages/context-engine/src/base/__tests__/BaseLastUserContentProvider.test.ts
new file mode 100644
index 00000000000..4bdd7825f2c
--- /dev/null
+++ b/packages/context-engine/src/base/__tests__/BaseLastUserContentProvider.test.ts
@@ -0,0 +1,388 @@
+import { describe, expect, it } from 'vitest';
+
+import type { PipelineContext } from '../../types';
+import { BaseLastUserContentProvider } from '../BaseLastUserContentProvider';
+
+class TestLastUserContentProvider extends BaseLastUserContentProvider {
+ readonly name = 'TestLastUserContentProvider';
+
+ protected async doProcess(context: PipelineContext): Promise<PipelineContext> {
+ const cloned = this.cloneContext(context);
+ const hasExistingWrapper = this.hasExistingSystemContext(cloned);
+ const contentToAppend = hasExistingWrapper
+ ? this.createContextBlock('Test content', 'test_context')
+ : this.wrapWithSystemContext('Test content', 'test_context');
+ this.appendToLastUserMessage(cloned, contentToAppend);
+ return cloned;
+ }
+
+ // Expose protected methods for testing
+ testFindLastUserMessageIndex(messages: any[]) {
+ return this.findLastUserMessageIndex(messages);
+ }
+
+ testAppendToLastUserMessage(context: PipelineContext, content: string) {
+ return this.appendToLastUserMessage(context, content);
+ }
+
+ testWrapWithSystemContext(content: string, contextType: string) {
+ return this.wrapWithSystemContext(content, contextType);
+ }
+
+ testCreateContextBlock(content: string, contextType: string) {
+ return this.createContextBlock(content, contextType);
+ }
+
+ testHasExistingSystemContext(context: PipelineContext) {
+ return this.hasExistingSystemContext(context);
+ }
+}
+
+// Second provider for testing multiple injections
+class SecondLastUserContentProvider extends BaseLastUserContentProvider {
+ readonly name = 'SecondLastUserContentProvider';
+
+ protected async doProcess(context: PipelineContext): Promise<PipelineContext> {
+ const cloned = this.cloneContext(context);
+ const hasExistingWrapper = this.hasExistingSystemContext(cloned);
+ const contentToAppend = hasExistingWrapper
+ ? this.createContextBlock('Second content', 'second_context')
+ : this.wrapWithSystemContext('Second content', 'second_context');
+ this.appendToLastUserMessage(cloned, contentToAppend);
+ return cloned;
+ }
+}
+
+describe('BaseLastUserContentProvider', () => {
+ const createContext = (messages: any[] = []): PipelineContext => ({
+ initialState: {
+ messages: [],
+ model: 'test-model',
+ provider: 'test-provider',
+ },
+ isAborted: false,
+ messages,
+ metadata: {
+ maxTokens: 4000,
+ model: 'test-model',
+ },
+ });
+
+ describe('findLastUserMessageIndex', () => {
+ it('should find the last user message in a simple conversation', () => {
+ const provider = new TestLastUserContentProvider();
+ const messages = [
+ { content: 'Hello', role: 'user' },
+ { content: 'Hi there', role: 'assistant' },
+ { content: 'How are you?', role: 'user' },
+ { content: 'I am fine', role: 'assistant' },
+ ];
+
+ const index = provider.testFindLastUserMessageIndex(messages);
+ expect(index).toBe(2);
+ });
+
+ it('should find the last user message when it is at the end', () => {
+ const provider = new TestLastUserContentProvider();
+ const messages = [
+ { content: 'Hello', role: 'user' },
+ { content: 'Hi there', role: 'assistant' },
+ { content: 'Tell me more', role: 'user' },
+ ];
+
+ const index = provider.testFindLastUserMessageIndex(messages);
+ expect(index).toBe(2);
+ });
+
+ it('should return -1 when no user messages exist', () => {
+ const provider = new TestLastUserContentProvider();
+ const messages = [
+ { content: 'System prompt', role: 'system' },
+ { content: 'Assistant response', role: 'assistant' },
+ ];
+
+ const index = provider.testFindLastUserMessageIndex(messages);
+ expect(index).toBe(-1);
+ });
+
+ it('should return -1 for empty messages array', () => {
+ const provider = new TestLastUserContentProvider();
+ const index = provider.testFindLastUserMessageIndex([]);
+ expect(index).toBe(-1);
+ });
+
+ it('should find the only user message', () => {
+ const provider = new TestLastUserContentProvider();
+ const messages = [{ content: 'Only user message', role: 'user' }];
+
+ const index = provider.testFindLastUserMessageIndex(messages);
+ expect(index).toBe(0);
+ });
+ });
+
+ describe('appendToLastUserMessage', () => {
+ it('should append content to string message content', () => {
+ const provider = new TestLastUserContentProvider();
+ const context = createContext([
+ { content: 'Hello', role: 'user' },
+ { content: 'Hi', role: 'assistant' },
+ { content: 'Tell me more', role: 'user' },
+ ]);
+
+ const result = provider.testAppendToLastUserMessage(context, 'Appended content');
+
+ expect(result.messages[2].content).toBe('Tell me more\n\nAppended content');
+ });
+
+ it('should append content to array message content with text part', () => {
+ const provider = new TestLastUserContentProvider();
+ const context = createContext([
+ {
+ content: [
+ { text: 'Hello', type: 'text' },
+ { image_url: { url: 'http://example.com/image.png' }, type: 'image_url' },
+ ],
+ role: 'user',
+ },
+ ]);
+
+ const result = provider.testAppendToLastUserMessage(context, 'Appended content');
+
+ expect(result.messages[0].content[0].text).toBe('Hello\n\nAppended content');
+ expect(result.messages[0].content[1].type).toBe('image_url');
+ });
+
+ it('should add new text part when array content has no text part', () => {
+ const provider = new TestLastUserContentProvider();
+ const context = createContext([
+ {
+ content: [{ image_url: { url: 'http://example.com/image.png' }, type: 'image_url' }],
+ role: 'user',
+ },
+ ]);
+
+ const result = provider.testAppendToLastUserMessage(context, 'Appended content');
+
+ expect(result.messages[0].content).toHaveLength(2);
+ expect(result.messages[0].content[1]).toEqual({
+ text: 'Appended content',
+ type: 'text',
+ });
+ });
+
+ it('should not modify context when no user messages exist', () => {
+ const provider = new TestLastUserContentProvider();
+ const context = createContext([{ content: 'System message', role: 'system' }]);
+
+ const result = provider.testAppendToLastUserMessage(context, 'Appended content');
+
+ expect(result.messages).toHaveLength(1);
+ expect(result.messages[0].content).toBe('System message');
+ });
+
+ it('should append to last text part in multimodal message', () => {
+ const provider = new TestLastUserContentProvider();
+ const context = createContext([
+ {
+ content: [
+ { image_url: { url: 'http://example.com/image1.png' }, type: 'image_url' },
+ { text: 'First text', type: 'text' },
+ { image_url: { url: 'http://example.com/image2.png' }, type: 'image_url' },
+ { text: 'Last text', type: 'text' },
+ ],
+ role: 'user',
+ },
+ ]);
+
+ const result = provider.testAppendToLastUserMessage(context, 'Appended content');
+
+ // Should append to the last text part (index 3)
+ expect(result.messages[0].content[3].text).toBe('Last text\n\nAppended content');
+ expect(result.messages[0].content[1].text).toBe('First text');
+ });
+ });
+
+ describe('wrapWithSystemContext', () => {
+ it('should wrap content with system context markers', () => {
+ const provider = new TestLastUserContentProvider();
+ const result = provider.testWrapWithSystemContext('Test content', 'test_type');
+
+ expect(result).toContain('<!-- SYSTEM CONTEXT (NOT PART OF USER QUERY) -->');
+ expect(result).toContain('<context.instruction>');
+ expect(result).toContain('</context.instruction>');
+ expect(result).toContain('<test_type>');
+ expect(result).toContain('Test content');
+ expect(result).toContain('</test_type>');
+ expect(result).toContain('<!-- END SYSTEM CONTEXT -->');
+ });
+
+ it('should include instruction text', () => {
+ const provider = new TestLastUserContentProvider();
+ const result = provider.testWrapWithSystemContext('Content', 'type');
+
+ expect(result).toContain(
+ 'following part contains context information injected by the system',
+ );
+ expect(result).toContain('Always prioritize handling user-visible content');
+ expect(result).toContain('the context is only required when user');
+ });
+
+ it('should handle different context types', () => {
+ const provider = new TestLastUserContentProvider();
+
+ const result1 = provider.testWrapWithSystemContext('Content 1', 'current_page_context');
+ expect(result1).toContain('<current_page_context>');
+ expect(result1).toContain('</current_page_context>');
+
+ const result2 = provider.testWrapWithSystemContext('Content 2', 'files_info');
+ expect(result2).toContain('<files_info>');
+ expect(result2).toContain('</files_info>');
+ });
+ });
+
+ describe('process integration', () => {
+ it('should process and append content to last user message', async () => {
+ const provider = new TestLastUserContentProvider();
+ const context = createContext([
+ { content: 'Hello', role: 'user' },
+ { content: 'Hi', role: 'assistant' },
+ { content: 'Question', role: 'user' },
+ ]);
+
+ const result = await provider.process(context);
+
+ expect(result.messages[2].content).toContain('Question');
+ expect(result.messages[2].content).toContain('<!-- SYSTEM CONTEXT');
+ expect(result.messages[2].content).toContain('<test_context>');
+ expect(result.messages[2].content).toContain('Test content');
+ });
+
+ it('should not modify messages when no user messages exist', async () => {
+ class NoOpProvider extends BaseLastUserContentProvider {
+ readonly name = 'NoOpProvider';
+
+ protected async doProcess(context: PipelineContext): Promise<PipelineContext> {
+ const cloned = this.cloneContext(context);
+ const lastUserIndex = this.findLastUserMessageIndex(cloned.messages);
+
+ if (lastUserIndex === -1) {
+ return cloned;
+ }
+
+ this.appendToLastUserMessage(cloned, 'Content');
+ return cloned;
+ }
+ }
+
+ const provider = new NoOpProvider();
+ const context = createContext([{ content: 'System', role: 'system' }]);
+
+ const result = await provider.process(context);
+
+ expect(result.messages).toHaveLength(1);
+ expect(result.messages[0].content).toBe('System');
+ });
+ });
+
+ describe('multiple providers injection', () => {
+ it('should have only one SYSTEM CONTEXT wrapper when two providers inject content', async () => {
+ const provider1 = new TestLastUserContentProvider();
+ const provider2 = new SecondLastUserContentProvider();
+
+ const context = createContext([{ content: 'User question', role: 'user' }]);
+
+ // First provider injects
+ const result1 = await provider1.process(context);
+ // Second provider injects into the result of first
+ const result2 = await provider2.process(result1);
+
+ const finalContent = result2.messages[0].content as string;
+
+ // Verify exact content structure
+ expect(finalContent).toBe(`User question
+
+<!-- SYSTEM CONTEXT (NOT PART OF USER QUERY) -->
+<context.instruction>following part contains context information injected by the system. Please follow these instructions:
+
+1. Always prioritize handling user-visible content.
+2. the context is only required when user's queries rely on it.
+</context.instruction>
+<test_context>
+Test content
+</test_context>
+<second_context>
+Second content
+</second_context>
+<!-- END SYSTEM CONTEXT -->`);
+ });
+
+ it('should correctly detect existing system context', () => {
+ const provider = new TestLastUserContentProvider();
+
+ const contextWithWrapper = createContext([
+ {
+ content: `Question
+
+<!-- SYSTEM CONTEXT (NOT PART OF USER QUERY) -->
+<context.instruction>...</context.instruction>
+<existing_context>content</existing_context>
+<!-- END SYSTEM CONTEXT -->`,
+ role: 'user',
+ },
+ ]);
+
+ const contextWithoutWrapper = createContext([{ content: 'Simple question', role: 'user' }]);
+
+ expect(provider.testHasExistingSystemContext(contextWithWrapper)).toBe(true);
+ expect(provider.testHasExistingSystemContext(contextWithoutWrapper)).toBe(false);
+ });
+
+ it('should work with array content when multiple providers inject', async () => {
+ const provider1 = new TestLastUserContentProvider();
+ const provider2 = new SecondLastUserContentProvider();
+
+ const context = createContext([
+ {
+ content: [
+ { text: 'User question with image', type: 'text' },
+ { image_url: { url: 'http://example.com/img.png' }, type: 'image_url' },
+ ],
+ role: 'user',
+ },
+ ]);
+
+ const result1 = await provider1.process(context);
+ const result2 = await provider2.process(result1);
+
+ const textContent = result2.messages[0].content[0].text;
+
+ // Verify exact content structure for array content
+ expect(textContent).toBe(`User question with image
+
+<!-- SYSTEM CONTEXT (NOT PART OF USER QUERY) -->
+<context.instruction>following part contains context information injected by the system. Please follow these instructions:
+
+1. Always prioritize handling user-visible content.
+2. the context is only required when user's queries rely on it.
+</context.instruction>
+<test_context>
+Test content
+</test_context>
+<second_context>
+Second content
+</second_context>
+<!-- END SYSTEM CONTEXT -->`);
+ });
+ });
+
+ describe('createContextBlock', () => {
+ it('should create context block without wrapper', () => {
+ const provider = new TestLastUserContentProvider();
+ const result = provider.testCreateContextBlock('Block content', 'block_type');
+
+ expect(result).toBe(`<block_type>
+Block content
+</block_type>`);
+ });
+ });
+});
diff --git a/packages/context-engine/src/engine/index.ts b/packages/context-engine/src/engine/index.ts
new file mode 100644
index 00000000000..740cf65fceb
--- /dev/null
+++ b/packages/context-engine/src/engine/index.ts
@@ -0,0 +1,4 @@
+// Tools Engine
+export * from './tools';
+// Messages Engine
+export * from './messages';
diff --git a/packages/context-engine/src/engine/messages/MessagesEngine.ts b/packages/context-engine/src/engine/messages/MessagesEngine.ts
new file mode 100644
index 00000000000..8a5bd96adf6
--- /dev/null
+++ b/packages/context-engine/src/engine/messages/MessagesEngine.ts
@@ -0,0 +1,270 @@
+/* eslint-disable sort-keys-fix/sort-keys-fix */
+import debug from 'debug';
+
+import type { OpenAIChatMessage } from '@/types/index';
+
+import { ContextEngine } from '../../pipeline';
+import {
+ AgentCouncilFlattenProcessor,
+ GroupMessageFlattenProcessor,
+ GroupMessageSenderProcessor,
+ HistoryTruncateProcessor,
+ InputTemplateProcessor,
+ MessageCleanupProcessor,
+ MessageContentProcessor,
+ PlaceholderVariablesProcessor,
+ SupervisorRoleRestoreProcessor,
+ TaskMessageProcessor,
+ ToolCallProcessor,
+ ToolMessageReorder,
+} from '../../processors';
+import {
+ AgentBuilderContextInjector,
+ GroupAgentBuilderContextInjector,
+ GroupContextInjector,
+ HistorySummaryProvider,
+ KnowledgeInjector,
+ SystemRoleInjector,
+ ToolSystemRoleProvider,
+ UserMemoryInjector,
+} from '../../providers';
+import type { ContextProcessor } from '../../types';
+import { ToolNameResolver } from '../tools';
+import type { MessagesEngineParams, MessagesEngineResult } from './types';
+
+const log = debug('context-engine:MessagesEngine');
+
+/**
+ * MessagesEngine - High-level message processing engine
+ *
+ * This is a convenience wrapper around ContextEngine that provides
+ * a pre-configured pipeline for common message processing scenarios.
+ * It can be used by both frontend and backend through dependency injection.
+ *
+ * @example
+ * ```typescript
+ * const engine = new MessagesEngine({
+ * messages,
+ * model: 'gpt-4',
+ * provider: 'openai',
+ * systemRole: 'You are a helpful assistant',
+ * capabilities: {
+ * isCanUseFC: (m, p) => true,
+ * isCanUseVision: (m, p) => true,
+ * },
+ * });
+ *
+ * const result = await engine.process();
+ * console.log(result.messages);
+ * ```
+ */
+export class MessagesEngine {
+ private params: MessagesEngineParams;
+ private toolNameResolver: ToolNameResolver;
+
+ constructor(params: MessagesEngineParams) {
+ this.params = params;
+ this.toolNameResolver = new ToolNameResolver();
+ }
+
+ /**
+ * Process messages and return OpenAI-compatible format
+ */
+ async process(): Promise<MessagesEngineResult> {
+ const pipeline = this.buildPipeline();
+ const result = await pipeline.process({ messages: this.params.messages });
+
+ return {
+ messages: result.messages as OpenAIChatMessage[],
+ metadata: result.metadata,
+ stats: result.stats,
+ };
+ }
+
+ /**
+ * Process messages and return only the messages array
+ * This is a convenience method for simpler use cases
+ */
+ async processMessages(): Promise<OpenAIChatMessage[]> {
+ const result = await this.process();
+ return result.messages;
+ }
+
+ /**
+ * Build the processing pipeline based on configuration
+ */
+ private buildPipeline(): ContextEngine {
+ const processors = this.buildProcessors();
+ log(`Built pipeline with ${processors.length} processors`);
+ return new ContextEngine({ pipeline: processors });
+ }
+
+ /**
+ * Build the list of processors based on configuration
+ */
+ private buildProcessors(): ContextProcessor[] {
+ const {
+ model,
+ provider,
+ systemRole,
+ inputTemplate,
+ enableHistoryCount,
+ historyCount,
+ historySummary,
+ formatHistorySummary,
+ knowledge,
+ toolsConfig,
+ capabilities,
+ variableGenerators,
+ fileContext,
+ agentBuilderContext,
+ groupAgentBuilderContext,
+ agentGroup,
+ userMemory,
+ } = this.params;
+
+ const isAgentBuilderEnabled = !!agentBuilderContext;
+ const isGroupAgentBuilderEnabled = !!groupAgentBuilderContext;
+ const isAgentGroupEnabled = agentGroup?.agentMap && Object.keys(agentGroup.agentMap).length > 0;
+ const isGroupContextEnabled =
+ isAgentGroupEnabled || !!agentGroup?.currentAgentId || !!agentGroup?.members;
+ const isUserMemoryEnabled = userMemory?.enabled && userMemory?.memories;
+
+ return [
+ // =============================================
+ // Phase 1: History Management
+ // =============================================
+
+ // 1. History truncation (MUST be first, before any message injection)
+ new HistoryTruncateProcessor({
+ enableHistoryCount,
+ historyCount,
+ }),
+
+ // =============================================
+ // Phase 2: System Role Injection
+ // =============================================
+
+ // 2. System role injection (agent's system role)
+ new SystemRoleInjector({ systemRole }),
+
+ // 3. Group context injection (agent identity and group info for multi-agent chat)
+ new GroupContextInjector({
+ currentAgentId: agentGroup?.currentAgentId,
+ currentAgentName: agentGroup?.currentAgentName,
+ currentAgentRole: agentGroup?.currentAgentRole,
+ enabled: isGroupContextEnabled,
+ groupTitle: agentGroup?.groupTitle,
+ members: agentGroup?.members,
+ systemPrompt: agentGroup?.systemPrompt,
+ }),
+
+ // 4. Knowledge injection (full content for agent files + metadata for knowledge bases)
+ new KnowledgeInjector({
+ fileContents: knowledge?.fileContents,
+ knowledgeBases: knowledge?.knowledgeBases,
+ }),
+
+ // 5. Agent Builder context injection (current agent config/meta for editing)
+ new AgentBuilderContextInjector({
+ enabled: isAgentBuilderEnabled,
+ agentContext: agentBuilderContext,
+ }),
+
+ // 6. Group Agent Builder context injection (current group config/members for editing)
+ new GroupAgentBuilderContextInjector({
+ enabled: isGroupAgentBuilderEnabled,
+ groupContext: groupAgentBuilderContext,
+ }),
+
+ // 7. Tool system role injection (conditionally added)
+ ...(toolsConfig?.tools && toolsConfig.tools.length > 0
+ ? [
+ new ToolSystemRoleProvider({
+ getToolSystemRoles: toolsConfig.getToolSystemRoles || (() => undefined),
+ isCanUseFC: capabilities?.isCanUseFC || (() => true),
+ model,
+ provider,
+ tools: toolsConfig.tools,
+ }),
+ ]
+ : []),
+
+ // 8. History summary injection
+ new HistorySummaryProvider({
+ formatHistorySummary,
+ historySummary,
+ }),
+
+ // 9. User memory injection (conditionally added)
+ ...(isUserMemoryEnabled
+ ? [
+ new UserMemoryInjector({
+ fetchedAt: userMemory.fetchedAt,
+ memories: userMemory.memories,
+ }),
+ ]
+ : []),
+
+ // =============================================
+ // Phase 3: Message Transformation
+ // =============================================
+
+ // 10. Input template processing
+ new InputTemplateProcessor({ inputTemplate }),
+
+ // 11. Placeholder variables processing
+ new PlaceholderVariablesProcessor({
+ variableGenerators: variableGenerators || {},
+ }),
+
+ // 12. AgentCouncil message flatten (convert role=agentCouncil to standard assistant + tool messages)
+ new AgentCouncilFlattenProcessor(),
+
+ // 13. Group message flatten (convert role=assistantGroup to standard assistant + tool messages)
+ new GroupMessageFlattenProcessor(),
+
+ // 14. Task message processing (convert role=task to assistant with instruction + content)
+ new TaskMessageProcessor(),
+
+ // 15. Supervisor role restore (convert role=supervisor back to role=assistant for model)
+ new SupervisorRoleRestoreProcessor(),
+
+ // 16. Group message sender identity injection (for multi-agent chat)
+ ...(isAgentGroupEnabled
+ ? [
+ new GroupMessageSenderProcessor({
+ agentMap: agentGroup.agentMap!,
+ }),
+ ]
+ : []),
+
+ // =============================================
+ // Phase 4: Content Processing
+ // =============================================
+
+ // 17. Message content processing (image encoding, etc.)
+ new MessageContentProcessor({
+ fileContext: fileContext || { enabled: true, includeFileUrl: true },
+ isCanUseVideo: capabilities?.isCanUseVideo || (() => false),
+ isCanUseVision: capabilities?.isCanUseVision || (() => true),
+ model,
+ provider,
+ }),
+
+ // 18. Tool call processing
+ new ToolCallProcessor({
+ genToolCallingName: this.toolNameResolver.generate.bind(this.toolNameResolver),
+ isCanUseFC: capabilities?.isCanUseFC || (() => true),
+ model,
+ provider,
+ }),
+
+ // 19. Tool message reordering
+ new ToolMessageReorder(),
+
+ // 20. Message cleanup (final step, keep only necessary fields)
+ new MessageCleanupProcessor(),
+ ];
+ }
+}
diff --git a/packages/context-engine/src/engine/messages/__tests__/MessagesEngine.test.ts b/packages/context-engine/src/engine/messages/__tests__/MessagesEngine.test.ts
new file mode 100644
index 00000000000..29c63e5635a
--- /dev/null
+++ b/packages/context-engine/src/engine/messages/__tests__/MessagesEngine.test.ts
@@ -0,0 +1,419 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import type { UIChatMessage } from '@/types/index';
+
+import { MessagesEngine } from '../MessagesEngine';
+import type { MessagesEngineParams } from '../types';
+
+describe('MessagesEngine', () => {
+ const createBasicMessages = (): UIChatMessage[] => [
+ {
+ content: 'Hello',
+ createdAt: Date.now(),
+ id: 'msg-1',
+ role: 'user',
+ updatedAt: Date.now(),
+ } as UIChatMessage,
+ {
+ content: 'Hi there!',
+ createdAt: Date.now(),
+ id: 'msg-2',
+ role: 'assistant',
+ updatedAt: Date.now(),
+ } as UIChatMessage,
+ ];
+
+ const createBasicParams = (overrides?: Partial<MessagesEngineParams>): MessagesEngineParams => ({
+ messages: createBasicMessages(),
+ model: 'gpt-4',
+ provider: 'openai',
+ ...overrides,
+ });
+
+ describe('constructor', () => {
+ it('should initialize with required parameters', () => {
+ const params = createBasicParams();
+ const engine = new MessagesEngine(params);
+ expect(engine).toBeInstanceOf(MessagesEngine);
+ });
+
+ it('should initialize with all optional parameters', () => {
+ const params = createBasicParams({
+ agentBuilderContext: { config: { model: 'gpt-4' } },
+ capabilities: {
+ isCanUseFC: () => true,
+ isCanUseVideo: () => false,
+ isCanUseVision: () => true,
+ },
+ enableHistoryCount: true,
+ fileContext: { enabled: true, includeFileUrl: false },
+ formatHistorySummary: (s) => `<summary>${s}</summary>`,
+ historyCount: 10,
+ historySummary: 'Previous conversation summary',
+ inputTemplate: '{{text}}',
+ knowledge: {
+ fileContents: [{ content: 'test', fileId: 'f1', filename: 'test.txt' }],
+ knowledgeBases: [{ id: 'kb1', name: 'Knowledge Base 1' }],
+ },
+ systemRole: 'You are a helpful assistant',
+ toolsConfig: {
+ getToolSystemRoles: () => undefined,
+ tools: ['tool1'],
+ },
+ variableGenerators: {
+ date: () => '2024-01-01',
+ },
+ });
+
+ const engine = new MessagesEngine(params);
+ expect(engine).toBeInstanceOf(MessagesEngine);
+ });
+ });
+
+ describe('process', () => {
+ it('should process messages and return result with stats', async () => {
+ const params = createBasicParams();
+ const engine = new MessagesEngine(params);
+
+ const result = await engine.process();
+
+ expect(result.messages).toBeDefined();
+ expect(Array.isArray(result.messages)).toBe(true);
+ expect(result.metadata).toBeDefined();
+ expect(result.stats).toBeDefined();
+ expect(result.stats.processedCount).toBeGreaterThan(0);
+ expect(result.stats.totalDuration).toBeGreaterThanOrEqual(0);
+ });
+
+ it('should clean up messages to OpenAI format', async () => {
+ const params = createBasicParams();
+ const engine = new MessagesEngine(params);
+
+ const result = await engine.process();
+
+ // Messages should be cleaned up
+ result.messages.forEach((msg) => {
+ expect(msg).toHaveProperty('role');
+ expect(msg).toHaveProperty('content');
+ // Should not have extra fields like createdAt, updatedAt after cleanup
+ expect(msg).not.toHaveProperty('createdAt');
+ expect(msg).not.toHaveProperty('updatedAt');
+ });
+ });
+
+ it('should inject system role when provided', async () => {
+ const systemRole = 'You are a helpful assistant';
+ const params = createBasicParams({ systemRole });
+ const engine = new MessagesEngine(params);
+
+ const result = await engine.process();
+
+ // First message should be system role
+ expect(result.messages[0].role).toBe('system');
+ expect(result.messages[0].content).toBe(systemRole);
+ });
+
+ it('should truncate history when enabled', async () => {
+ const messages: UIChatMessage[] = [];
+ for (let i = 0; i < 20; i++) {
+ messages.push({
+ content: `Message ${i}`,
+ createdAt: Date.now(),
+ id: `msg-${i}`,
+ role: i % 2 === 0 ? 'user' : 'assistant',
+ updatedAt: Date.now(),
+ } as UIChatMessage);
+ }
+
+ const params = createBasicParams({
+ enableHistoryCount: true,
+ historyCount: 5,
+ messages,
+ });
+ const engine = new MessagesEngine(params);
+
+ const result = await engine.process();
+
+ // Should have truncated to 5 messages
+ expect(result.messages.length).toBeLessThanOrEqual(5);
+ });
+
+ it('should inject history summary when provided', async () => {
+ const historySummary = 'We discussed AI and machine learning';
+ const params = createBasicParams({ historySummary });
+ const engine = new MessagesEngine(params);
+
+ const result = await engine.process();
+
+ // Should contain history summary in system message
+ const systemMessages = result.messages.filter((m) => m.role === 'system');
+ const hasHistorySummary = systemMessages.some(
+ (m) => typeof m.content === 'string' && m.content.includes(historySummary),
+ );
+ expect(hasHistorySummary).toBe(true);
+ });
+
+ it('should use custom formatHistorySummary when provided', async () => {
+ const historySummary = 'test summary';
+ const formatHistorySummary = vi.fn((s: string) => `<custom>${s}</custom>`);
+
+ const params = createBasicParams({
+ formatHistorySummary,
+ historySummary,
+ });
+ const engine = new MessagesEngine(params);
+
+ await engine.process();
+
+ expect(formatHistorySummary).toHaveBeenCalledWith(historySummary);
+ });
+
+ it('should handle empty messages', async () => {
+ const params = createBasicParams({ messages: [] });
+ const engine = new MessagesEngine(params);
+
+ const result = await engine.process();
+
+ expect(result.messages).toEqual([]);
+ });
+ });
+
+ describe('processMessages', () => {
+ it('should return only messages array', async () => {
+ const params = createBasicParams();
+ const engine = new MessagesEngine(params);
+
+ const messages = await engine.processMessages();
+
+ expect(Array.isArray(messages)).toBe(true);
+ messages.forEach((msg) => {
+ expect(msg).toHaveProperty('role');
+ expect(msg).toHaveProperty('content');
+ });
+ });
+ });
+
+ describe('capabilities injection', () => {
+ it('should use provided isCanUseFC', async () => {
+ const isCanUseFC = vi.fn().mockReturnValue(true);
+ const params = createBasicParams({
+ capabilities: { isCanUseFC },
+ toolsConfig: { tools: ['tool1'] },
+ });
+ const engine = new MessagesEngine(params);
+
+ await engine.process();
+
+ // isCanUseFC should be called during tool processing
+ expect(isCanUseFC).toHaveBeenCalled();
+ });
+
+ it('should use provided isCanUseVision', async () => {
+ const isCanUseVision = vi.fn().mockReturnValue(true);
+ const messages: UIChatMessage[] = [
+ {
+ content: 'Check this image',
+ createdAt: Date.now(),
+ id: 'msg-1',
+ imageList: [{ id: 'img-1', url: 'https://example.com/image.png' }],
+ role: 'user',
+ updatedAt: Date.now(),
+ } as unknown as UIChatMessage,
+ ];
+
+ const params = createBasicParams({
+ capabilities: { isCanUseVision },
+ messages,
+ });
+ const engine = new MessagesEngine(params);
+
+ await engine.process();
+
+ expect(isCanUseVision).toHaveBeenCalled();
+ });
+
+ it('should default to true for isCanUseFC when not provided', async () => {
+ const params = createBasicParams({
+ toolsConfig: { tools: ['tool1'] },
+ });
+ const engine = new MessagesEngine(params);
+
+ // Should not throw
+ const result = await engine.process();
+ expect(result).toBeDefined();
+ });
+ });
+
+ describe('variable generators', () => {
+ it('should replace placeholders with generated values', async () => {
+ const messages: UIChatMessage[] = [
+ {
+ content: 'Today is {{date}}',
+ createdAt: Date.now(),
+ id: 'msg-1',
+ role: 'user',
+ updatedAt: Date.now(),
+ } as UIChatMessage,
+ ];
+
+ const params = createBasicParams({
+ messages,
+ variableGenerators: {
+ date: () => '2024-01-01',
+ },
+ });
+ const engine = new MessagesEngine(params);
+
+ const result = await engine.process();
+
+ const userMessage = result.messages.find((m) => m.role === 'user');
+ expect(userMessage?.content).toBe('Today is 2024-01-01');
+ });
+ });
+
+ describe('knowledge injection', () => {
+ it('should inject file contents', async () => {
+ const params = createBasicParams({
+ knowledge: {
+ fileContents: [
+ {
+ content: 'File content here',
+ fileId: 'file-1',
+ filename: 'test.txt',
+ },
+ ],
+ },
+ });
+ const engine = new MessagesEngine(params);
+
+ const result = await engine.process();
+
+ // Should have knowledge injected
+ expect(result.metadata.knowledgeInjected).toBe(true);
+ });
+
+ it('should inject knowledge bases', async () => {
+ const params = createBasicParams({
+ knowledge: {
+ knowledgeBases: [
+ {
+ description: 'Test knowledge base',
+ id: 'kb-1',
+ name: 'Test KB',
+ },
+ ],
+ },
+ });
+ const engine = new MessagesEngine(params);
+
+ const result = await engine.process();
+
+ expect(result.metadata.knowledgeInjected).toBe(true);
+ });
+ });
+
+ describe('Agent Builder context', () => {
+ it('should inject Agent Builder context when provided', async () => {
+ const params = createBasicParams({
+ agentBuilderContext: {
+ config: { model: 'gpt-4', systemRole: 'Test role' },
+ meta: { description: 'Test agent', title: 'Test' },
+ },
+ });
+ const engine = new MessagesEngine(params);
+
+ const result = await engine.process();
+
+ expect(result.metadata.agentBuilderContextInjected).toBe(true);
+ });
+
+ it('should not inject Agent Builder context when not provided', async () => {
+ const params = createBasicParams();
+ const engine = new MessagesEngine(params);
+
+ const result = await engine.process();
+
+ expect(result.metadata.agentBuilderContextInjected).toBeUndefined();
+ });
+ });
+
+ describe('file context', () => {
+ it('should use provided file context config', async () => {
+ const params = createBasicParams({
+ fileContext: {
+ enabled: true,
+ includeFileUrl: false,
+ },
+ });
+ const engine = new MessagesEngine(params);
+
+ // Should not throw
+ const result = await engine.process();
+ expect(result).toBeDefined();
+ });
+
+ it('should default to enabled with includeFileUrl true', async () => {
+ const params = createBasicParams();
+ const engine = new MessagesEngine(params);
+
+ // Should not throw
+ const result = await engine.process();
+ expect(result).toBeDefined();
+ });
+ });
+
+ describe('tools config', () => {
+ it('should handle tools configuration', async () => {
+ const getToolSystemRoles = vi.fn().mockReturnValue('Tool system role');
+
+ const params = createBasicParams({
+ capabilities: { isCanUseFC: () => true },
+ toolsConfig: {
+ getToolSystemRoles,
+ tools: ['tool1', 'tool2'],
+ },
+ });
+ const engine = new MessagesEngine(params);
+
+ await engine.process();
+
+ expect(getToolSystemRoles).toHaveBeenCalled();
+ });
+
+ it('should skip tool system role provider when no tools', async () => {
+ const params = createBasicParams({
+ toolsConfig: { tools: [] },
+ });
+ const engine = new MessagesEngine(params);
+
+ // Should not throw
+ const result = await engine.process();
+ expect(result).toBeDefined();
+ });
+ });
+
+ describe('input template', () => {
+ it('should apply input template to user messages', async () => {
+ const messages: UIChatMessage[] = [
+ {
+ content: 'user input',
+ createdAt: Date.now(),
+ id: 'msg-1',
+ role: 'user',
+ updatedAt: Date.now(),
+ } as UIChatMessage,
+ ];
+
+ const params = createBasicParams({
+ inputTemplate: 'Please respond to: {{text}}',
+ messages,
+ });
+ const engine = new MessagesEngine(params);
+
+ const result = await engine.process();
+
+ const userMessage = result.messages.find((m) => m.role === 'user');
+ expect(userMessage?.content).toBe('Please respond to: user input');
+ });
+ });
+});
diff --git a/packages/context-engine/src/engine/messages/index.ts b/packages/context-engine/src/engine/messages/index.ts
new file mode 100644
index 00000000000..ae64e48a5e9
--- /dev/null
+++ b/packages/context-engine/src/engine/messages/index.ts
@@ -0,0 +1,22 @@
+export { MessagesEngine } from './MessagesEngine';
+export type {
+ AgentBuilderContext,
+ AgentGroupConfig,
+ AgentInfo,
+ FileContent,
+ FileContextConfig,
+ KnowledgeBaseInfo,
+ KnowledgeConfig,
+ MessagesEngineParams,
+ MessagesEngineResult,
+ ModelCapabilityChecker,
+ OpenAIChatMessage,
+ ToolsConfig,
+ UIChatMessage,
+ UserMemoryConfig,
+ UserMemoryContextItem,
+ UserMemoryData,
+ UserMemoryExperienceItem,
+ UserMemoryPreferenceItem,
+ VariableGenerators,
+} from './types';
diff --git a/packages/context-engine/src/engine/messages/types.ts b/packages/context-engine/src/engine/messages/types.ts
new file mode 100644
index 00000000000..d12863d474d
--- /dev/null
+++ b/packages/context-engine/src/engine/messages/types.ts
@@ -0,0 +1,210 @@
+/* eslint-disable typescript-sort-keys/interface */
+import type { FileContent, KnowledgeBaseInfo } from '@lobechat/prompts';
+
+import type { OpenAIChatMessage, UIChatMessage } from '@/types/index';
+
+import type { AgentInfo } from '../../processors/GroupMessageSender';
+import type { AgentBuilderContext } from '../../providers/AgentBuilderContextInjector';
+import type { GroupAgentBuilderContext } from '../../providers/GroupAgentBuilderContextInjector';
+import type { GroupMemberInfo } from '../../providers/GroupContextInjector';
+
+/**
+ * Model capability checker
+ * Injected by caller to check if model supports specific capabilities
+ */
+export interface ModelCapabilityChecker {
+ /** Check if function calling is supported */
+ isCanUseFC?: (model: string, provider: string) => boolean;
+ /** Check if video is supported */
+ isCanUseVideo?: (model: string, provider: string) => boolean;
+ /** Check if vision is supported */
+ isCanUseVision?: (model: string, provider: string) => boolean;
+}
+
+/**
+ * Knowledge configuration
+ */
+export interface KnowledgeConfig {
+ /** File contents to inject */
+ fileContents?: FileContent[];
+ /** Knowledge base metadata to inject */
+ knowledgeBases?: KnowledgeBaseInfo[];
+}
+
+/**
+ * Tools configuration
+ */
+export interface ToolsConfig {
+ /** Function to get tool system roles */
+ getToolSystemRoles?: (tools: string[]) => string | undefined;
+ /** Enabled tool IDs */
+ tools?: string[];
+}
+
+/**
+ * Variable generators for placeholder replacement
+ * Used to replace {{variable}} placeholders in messages
+ */
+export type VariableGenerators = Record<string, () => string>;
+
+/**
+ * File context configuration
+ */
+export interface FileContextConfig {
+ /** Whether to enable file context injection */
+ enabled: boolean;
+ /** Whether to include file URLs (desktop typically uses false) */
+ includeFileUrl: boolean;
+}
+
+/**
+ * User memory item interfaces
+ * Uses index signature to allow additional properties from database models
+ * Note: Properties can be null (from database) or undefined
+ */
+export interface UserMemoryContextItem {
+ description?: string | null;
+ id?: string;
+ title?: string | null;
+ [key: string]: unknown;
+}
+
+export interface UserMemoryExperienceItem {
+ id?: string;
+ keyLearning?: string | null;
+ situation?: string | null;
+ [key: string]: unknown;
+}
+
+export interface UserMemoryPreferenceItem {
+ conclusionDirectives?: string | null;
+ id?: string;
+ [key: string]: unknown;
+}
+
+/**
+ * User memory data structure
+ * Compatible with SearchMemoryResult from @lobechat/types
+ */
+export interface UserMemoryData {
+ contexts: UserMemoryContextItem[];
+ experiences: UserMemoryExperienceItem[];
+ preferences: UserMemoryPreferenceItem[];
+}
+
+/**
+ * User memory configuration
+ */
+export interface UserMemoryConfig {
+ /** Whether user memory is enabled */
+ enabled?: boolean;
+ /** When the memories were fetched */
+ fetchedAt?: number;
+ /** User memories data */
+ memories?: UserMemoryData;
+}
+
+/**
+ * Agent group configuration
+ * Used to inject sender identity into assistant messages in multi-agent scenarios
+ */
+export interface AgentGroupConfig {
+ /** Mapping from agentId to agent info (name, role) */
+ agentMap?: Record<string, AgentInfo>;
+
+ // ========== Group context injection (for current agent's identity) ==========
+ /** Current agent's ID (the one who will respond) */
+ currentAgentId?: string;
+ /** Current agent's name */
+ currentAgentName?: string;
+ /** Current agent's role */
+ currentAgentRole?: 'supervisor' | 'participant';
+ /** Group title/name */
+ groupTitle?: string;
+ /** List of group members for context injection */
+ members?: GroupMemberInfo[];
+ /** Custom system prompt/role description for the group */
+ systemPrompt?: string;
+}
+
+/**
+ * MessagesEngine main parameters
+ */
+export interface MessagesEngineParams {
+ // ========== Required parameters ==========
+ /** Original message list */
+ messages: UIChatMessage[];
+ /** Model ID */
+ model: string;
+ /** Provider ID */
+ provider: string;
+
+ // ========== Agent configuration ==========
+ /** Whether to enable history message count limit */
+ enableHistoryCount?: boolean;
+ /** Function to format history summary */
+ formatHistorySummary?: (summary: string) => string;
+ /** History message count limit */
+ historyCount?: number;
+ /** History summary content */
+ historySummary?: string;
+ /** Input template */
+ inputTemplate?: string;
+ /** System role */
+ systemRole?: string;
+
+ // ========== Capability injection (dependency injection) ==========
+ /** Model capability checker */
+ capabilities?: ModelCapabilityChecker;
+ /** Variable generators for placeholder replacement */
+ variableGenerators?: VariableGenerators;
+
+ // ========== Knowledge ==========
+ /** Knowledge configuration */
+ knowledge?: KnowledgeConfig;
+
+ // ========== Tools ==========
+ /** Tools configuration */
+ toolsConfig?: ToolsConfig;
+
+ // ========== File handling ==========
+ /** File context configuration */
+ fileContext?: FileContextConfig;
+
+ // ========== Extended contexts (both frontend and backend) ==========
+ /** Agent Builder context */
+ agentBuilderContext?: AgentBuilderContext;
+ /** Agent group configuration for multi-agent scenarios */
+ agentGroup?: AgentGroupConfig;
+ /** Group Agent Builder context */
+ groupAgentBuilderContext?: GroupAgentBuilderContext;
+ /** User memory configuration */
+ userMemory?: UserMemoryConfig;
+}
+
+/**
+ * MessagesEngine result
+ */
+export interface MessagesEngineResult {
+ /** Processed messages in OpenAI format */
+ messages: OpenAIChatMessage[];
+ /** Processing metadata */
+ metadata: Record<string, any>;
+ /** Processing statistics */
+ stats: {
+ /** Number of processors executed */
+ processedCount: number;
+ /** Execution time for each processor */
+ processorDurations: Record<string, number>;
+ /** Total processing time in ms */
+ totalDuration: number;
+ };
+}
+
+// Re-export types for convenience
+
+export { type AgentInfo } from '../../processors/GroupMessageSender';
+export { type AgentBuilderContext } from '../../providers/AgentBuilderContextInjector';
+export { type GroupAgentBuilderContext } from '../../providers/GroupAgentBuilderContextInjector';
+export { type OpenAIChatMessage, type UIChatMessage } from '@/types/index';
+export { type FileContent, type KnowledgeBaseInfo } from '@lobechat/prompts';
diff --git a/packages/context-engine/src/tools/ToolNameResolver.ts b/packages/context-engine/src/engine/tools/ToolNameResolver.ts
similarity index 98%
rename from packages/context-engine/src/tools/ToolNameResolver.ts
rename to packages/context-engine/src/engine/tools/ToolNameResolver.ts
index 684a0178000..f86286fed4b 100644
--- a/packages/context-engine/src/tools/ToolNameResolver.ts
+++ b/packages/context-engine/src/engine/tools/ToolNameResolver.ts
@@ -1,6 +1,7 @@
-import { ChatToolPayload, MessageToolCall } from '@lobechat/types';
import { Md5 } from 'ts-md5';
+import { ChatToolPayload, MessageToolCall } from '@/types/index';
+
import { LobeChatPluginApi, LobeToolManifest } from './types';
// Tool naming constants
diff --git a/packages/context-engine/src/tools/ToolsEngine.ts b/packages/context-engine/src/engine/tools/ToolsEngine.ts
similarity index 100%
rename from packages/context-engine/src/tools/ToolsEngine.ts
rename to packages/context-engine/src/engine/tools/ToolsEngine.ts
diff --git a/packages/context-engine/src/tools/__tests__/ToolNameResolver.test.ts b/packages/context-engine/src/engine/tools/__tests__/ToolNameResolver.test.ts
similarity index 100%
rename from packages/context-engine/src/tools/__tests__/ToolNameResolver.test.ts
rename to packages/context-engine/src/engine/tools/__tests__/ToolNameResolver.test.ts
diff --git a/packages/context-engine/src/tools/__tests__/ToolsEngine.test.ts b/packages/context-engine/src/engine/tools/__tests__/ToolsEngine.test.ts
similarity index 100%
rename from packages/context-engine/src/tools/__tests__/ToolsEngine.test.ts
rename to packages/context-engine/src/engine/tools/__tests__/ToolsEngine.test.ts
diff --git a/packages/context-engine/src/tools/__tests__/utils.test.ts b/packages/context-engine/src/engine/tools/__tests__/utils.test.ts
similarity index 100%
rename from packages/context-engine/src/tools/__tests__/utils.test.ts
rename to packages/context-engine/src/engine/tools/__tests__/utils.test.ts
diff --git a/packages/context-engine/src/tools/index.ts b/packages/context-engine/src/engine/tools/index.ts
similarity index 100%
rename from packages/context-engine/src/tools/index.ts
rename to packages/context-engine/src/engine/tools/index.ts
diff --git a/packages/context-engine/src/tools/types.ts b/packages/context-engine/src/engine/tools/types.ts
similarity index 98%
rename from packages/context-engine/src/tools/types.ts
rename to packages/context-engine/src/engine/tools/types.ts
index abdfd6dc394..92e2c605549 100644
--- a/packages/context-engine/src/tools/types.ts
+++ b/packages/context-engine/src/engine/tools/types.ts
@@ -1,4 +1,4 @@
-import type { HumanInterventionConfig } from '@lobechat/types';
+import type { HumanInterventionConfig } from '@/types/index';
export interface LobeChatPluginApi {
description: string;
diff --git a/packages/context-engine/src/tools/utils.ts b/packages/context-engine/src/engine/tools/utils.ts
similarity index 87%
rename from packages/context-engine/src/tools/utils.ts
rename to packages/context-engine/src/engine/tools/utils.ts
index defc993e3fb..4fc031d741d 100644
--- a/packages/context-engine/src/tools/utils.ts
+++ b/packages/context-engine/src/engine/tools/utils.ts
@@ -22,10 +22,10 @@ export const generateToolName = (
export function validateManifest(manifest: any): manifest is LobeToolManifest {
return Boolean(
manifest &&
- typeof manifest === 'object' &&
- typeof manifest.identifier === 'string' &&
- Array.isArray(manifest.api) &&
- manifest.api.length > 0,
+ typeof manifest === 'object' &&
+ typeof manifest.identifier === 'string' &&
+ Array.isArray(manifest.api) &&
+ manifest.api.length > 0,
);
}
diff --git a/packages/context-engine/src/index.ts b/packages/context-engine/src/index.ts
index a1386e8cb2b..a593095ff72 100644
--- a/packages/context-engine/src/index.ts
+++ b/packages/context-engine/src/index.ts
@@ -2,37 +2,29 @@
export * from './types';
// Base classes
+export { BaseLastUserContentProvider } from './base/BaseLastUserContentProvider';
export { BaseProcessor } from './base/BaseProcessor';
export { BaseProvider } from './base/BaseProvider';
// Context Engine
+export * from './engine';
export type { ContextEngineConfig } from './pipeline';
export { ContextEngine } from './pipeline';
// Context Providers
export * from './providers';
-
// Processors
+export type { PlaceholderValue, PlaceholderValueMap } from './processors';
export {
+ buildPlaceholderGenerators,
+ formatPlaceholderValues,
GroupMessageFlattenProcessor,
HistoryTruncateProcessor,
InputTemplateProcessor,
MessageCleanupProcessor,
MessageContentProcessor,
PlaceholderVariablesProcessor,
+ renderPlaceholderTemplate,
ToolCallProcessor,
ToolMessageReorder,
} from './processors';
-
-// Tools Engine
-export type {
- FunctionCallChecker,
- GenerateToolsParams,
- LobeToolManifest,
- PluginEnableChecker,
- ToolNameGenerator,
- ToolsEngineOptions,
- ToolsGenerationContext,
- ToolsGenerationResult,
-} from './tools';
-export { filterValidManifests, ToolNameResolver, ToolsEngine, validateManifest } from './tools';
diff --git a/packages/context-engine/src/processors/AgentCouncilFlatten.ts b/packages/context-engine/src/processors/AgentCouncilFlatten.ts
new file mode 100644
index 00000000000..a6aedce3864
--- /dev/null
+++ b/packages/context-engine/src/processors/AgentCouncilFlatten.ts
@@ -0,0 +1,260 @@
+import debug from 'debug';
+
+import { BaseProcessor } from '../base/BaseProcessor';
+import type { PipelineContext, ProcessorOptions } from '../types';
+
+const log = debug('context-engine:processor:AgentCouncilFlattenProcessor');
+
+/**
+ * Agent Council Flatten Processor
+ * Responsible for flattening role=agentCouncil messages into standard assistant + tool message sequences
+ *
+ * AgentCouncil messages are created when multiple agents respond in parallel (broadcast scenario).
+ * This processor converts them back to a flat structure that AI models can understand.
+ *
+ * Structure:
+ * - agentCouncil message has `members: Message[]` array
+ * - Each member can be a regular assistant message or an assistantGroup message
+ * - If member is assistantGroup, it needs further flattening (assistant + tool messages)
+ */
+export class AgentCouncilFlattenProcessor extends BaseProcessor {
+ readonly name = 'AgentCouncilFlattenProcessor';
+
+ constructor(options: ProcessorOptions = {}) {
+ super(options);
+ }
+
+ protected async doProcess(context: PipelineContext): Promise<PipelineContext> {
+ const clonedContext = this.cloneContext(context);
+
+ let processedCount = 0;
+ let agentCouncilMessagesFlattened = 0;
+ let assistantMessagesCreated = 0;
+ let toolMessagesCreated = 0;
+
+ const newMessages: any[] = [];
+
+ // Process each message
+ for (const message of clonedContext.messages) {
+ // Check if this is an agentCouncil message with members field
+ if (message.role === 'agentCouncil' && message.members) {
+ // If members array is empty, skip this message entirely (no content to flatten)
+ if (message.members.length === 0) {
+ continue;
+ }
+
+ processedCount++;
+ agentCouncilMessagesFlattened++;
+
+ log(`Flattening agentCouncil message ${message.id} with ${message.members.length} members`);
+
+ // Flatten each member
+ for (const member of message.members) {
+ // Check if member is an assistantGroup (needs further flattening)
+ if (member.role === 'assistantGroup' && member.children) {
+ // Flatten assistantGroup into assistant + tool messages
+ const flattenedMessages = this.flattenAssistantGroup(member, message);
+ newMessages.push(...flattenedMessages);
+ assistantMessagesCreated += flattenedMessages.filter(
+ (m: any) => m.role === 'assistant',
+ ).length;
+ toolMessagesCreated += flattenedMessages.filter((m: any) => m.role === 'tool').length;
+ } else {
+ // Regular assistant message - transform to assistant role
+ const assistantMsg: any = {
+ content: member.content || '',
+ createdAt: member.createdAt || message.createdAt,
+ id: member.id,
+ meta: member.meta || message.meta,
+ role: 'assistant',
+ updatedAt: member.updatedAt || message.updatedAt,
+ };
+
+ // Preserve agent-related fields
+ if (member.agentId) assistantMsg.agentId = member.agentId;
+ if (member.model) assistantMsg.model = member.model;
+ if (member.provider) assistantMsg.provider = member.provider;
+
+ // Add tools if present
+ if (member.tools && member.tools.length > 0) {
+ assistantMsg.tools = member.tools.map((tool: any) => ({
+ apiName: tool.apiName,
+ arguments: tool.arguments,
+ id: tool.id,
+ identifier: tool.identifier,
+ type: tool.type,
+ }));
+ }
+
+ // Add reasoning if present
+ if (member.reasoning) {
+ assistantMsg.reasoning = member.reasoning;
+ }
+
+ // Add error if present
+ if (member.error) {
+ assistantMsg.error = member.error;
+ }
+
+ // Add imageList if present
+ if (member.imageList && member.imageList.length > 0) {
+ assistantMsg.imageList = member.imageList;
+ }
+
+ // Preserve parent/thread/group/topic IDs from the agentCouncil message
+ if (message.extra?.parentMessageId)
+ assistantMsg.parentId = message.extra.parentMessageId;
+ if (member.parentId) assistantMsg.parentId = member.parentId;
+ if (member.threadId) assistantMsg.threadId = member.threadId;
+ if (member.groupId) assistantMsg.groupId = member.groupId;
+ if (member.topicId) assistantMsg.topicId = member.topicId;
+
+ newMessages.push(assistantMsg);
+ assistantMessagesCreated++;
+
+ log(`Created assistant message ${assistantMsg.id} from member`);
+
+ // Create tool messages if member has tools with results
+ if (member.tools) {
+ for (const tool of member.tools) {
+ if (tool.result) {
+ const toolMsg = this.createToolMessage(tool, member, message);
+ newMessages.push(toolMsg);
+ toolMessagesCreated++;
+ log(`Created tool message ${toolMsg.id} for tool call ${tool.id}`);
+ }
+ }
+ }
+ }
+ }
+ } else {
+ // Non-agentCouncil message, keep as-is
+ newMessages.push(message);
+ }
+ }
+
+ clonedContext.messages = newMessages;
+
+ // Update metadata
+ clonedContext.metadata.agentCouncilFlattenProcessed = processedCount;
+ clonedContext.metadata.agentCouncilMessagesFlattened = agentCouncilMessagesFlattened;
+ clonedContext.metadata.agentCouncilAssistantMessagesCreated = assistantMessagesCreated;
+ clonedContext.metadata.agentCouncilToolMessagesCreated = toolMessagesCreated;
+
+ log(
+ `AgentCouncil message flatten processing completed: ${agentCouncilMessagesFlattened} councils flattened, ${assistantMessagesCreated} assistant messages created, ${toolMessagesCreated} tool messages created`,
+ );
+
+ return this.markAsExecuted(clonedContext);
+ }
+
+ /**
+ * Flatten an assistantGroup member into assistant + tool messages
+ */
+ private flattenAssistantGroup(groupMember: any, parentMessage: any): any[] {
+ const result: any[] = [];
+
+ if (!groupMember.children || groupMember.children.length === 0) {
+ return result;
+ }
+
+ for (const child of groupMember.children) {
+ // Create assistant message from child
+ const assistantMsg: any = {
+ content: child.content || '',
+ createdAt: groupMember.createdAt || parentMessage.createdAt,
+ id: child.id,
+ meta: groupMember.meta || parentMessage.meta,
+ role: 'assistant',
+ updatedAt: groupMember.updatedAt || parentMessage.updatedAt,
+ };
+
+ // Preserve agent-related fields from group member
+ if (groupMember.agentId) assistantMsg.agentId = groupMember.agentId;
+ if (groupMember.model) assistantMsg.model = groupMember.model;
+ if (groupMember.provider) assistantMsg.provider = groupMember.provider;
+
+ // Add tools if present (excluding result, which will be separate tool messages)
+ if (child.tools && child.tools.length > 0) {
+ assistantMsg.tools = child.tools.map((tool: any) => ({
+ apiName: tool.apiName,
+ arguments: tool.arguments,
+ id: tool.id,
+ identifier: tool.identifier,
+ type: tool.type,
+ }));
+ }
+
+ // Add reasoning if present
+ if (child.reasoning) {
+ assistantMsg.reasoning = child.reasoning;
+ }
+
+ // Add error if present
+ if (child.error) {
+ assistantMsg.error = child.error;
+ }
+
+ // Add imageList if present
+ if (child.imageList && child.imageList.length > 0) {
+ assistantMsg.imageList = child.imageList;
+ }
+
+ // Preserve parent/thread/group/topic IDs
+ if (parentMessage.extra?.parentMessageId)
+ assistantMsg.parentId = parentMessage.extra.parentMessageId;
+ if (groupMember.parentId) assistantMsg.parentId = groupMember.parentId;
+ if (groupMember.threadId) assistantMsg.threadId = groupMember.threadId;
+ if (groupMember.groupId) assistantMsg.groupId = groupMember.groupId;
+ if (groupMember.topicId) assistantMsg.topicId = groupMember.topicId;
+
+ result.push(assistantMsg);
+
+ // Create tool messages for each tool that has a result
+ if (child.tools) {
+ for (const tool of child.tools) {
+ if (tool.result) {
+ const toolMsg = this.createToolMessage(tool, groupMember, parentMessage);
+ result.push(toolMsg);
+ }
+ }
+ }
+ }
+
+ return result;
+ }
+
+ /**
+ * Create a tool message from tool data
+ */
+ private createToolMessage(tool: any, member: any, parentMessage: any): any {
+ const toolMsg: any = {
+ content: tool.result.content,
+ createdAt: member.createdAt || parentMessage.createdAt,
+ id: tool.result.id,
+ meta: member.meta || parentMessage.meta,
+ plugin: {
+ apiName: tool.apiName,
+ arguments: tool.arguments,
+ id: tool.id,
+ identifier: tool.identifier,
+ type: tool.type,
+ },
+ pluginError: tool.result.error || undefined,
+ pluginState: tool.result.state || undefined,
+ role: 'tool',
+ tool_call_id: tool.id,
+ updatedAt: member.updatedAt || parentMessage.updatedAt,
+ };
+
+ // Preserve parent message references
+ if (parentMessage.extra?.parentMessageId)
+ toolMsg.parentId = parentMessage.extra.parentMessageId;
+ if (member.parentId) toolMsg.parentId = member.parentId;
+ if (member.threadId) toolMsg.threadId = member.threadId;
+ if (member.groupId) toolMsg.groupId = member.groupId;
+ if (member.topicId) toolMsg.topicId = member.topicId;
+
+ return toolMsg;
+ }
+}
diff --git a/packages/context-engine/src/processors/GroupMessageSender.ts b/packages/context-engine/src/processors/GroupMessageSender.ts
new file mode 100644
index 00000000000..7d513856c28
--- /dev/null
+++ b/packages/context-engine/src/processors/GroupMessageSender.ts
@@ -0,0 +1,138 @@
+import debug from 'debug';
+
+import { BaseProcessor } from '../base/BaseProcessor';
+import type { Message, PipelineContext, ProcessorOptions } from '../types';
+
+const log = debug('context-engine:processor:GroupMessageSenderProcessor');
+
+/**
+ * Agent info for message sender identification
+ */
+export interface AgentInfo {
+ name: string;
+ role: 'supervisor' | 'participant';
+}
+
+/**
+ * Configuration for GroupMessageSenderProcessor
+ */
+export interface GroupMessageSenderConfig {
+ /**
+ * Mapping from agentId to agent info
+ * Used to look up agent name and role for each message
+ */
+ agentMap: Record<string, AgentInfo>;
+}
+
+/**
+ * Group Message Sender Processor
+ *
+ * Responsible for injecting sender identity information into assistant messages
+ * in group chat scenarios. This helps the model understand which agent sent
+ * each message in a multi-agent conversation.
+ *
+ * The processor appends a system context block at the end of each assistant
+ * message that has an agentId, containing:
+ * - Agent name
+ * - Agent role (supervisor or agent)
+ * - Agent ID (with instruction not to expose it in responses)
+ *
+ * @example
+ * ```typescript
+ * const processor = new GroupMessageSenderProcessor({
+ * agentMap: {
+ * 'agt_xxx': { name: 'Weather Expert', role: 'agent' },
+ * 'agt_yyy': { name: 'Supervisor', role: 'supervisor' },
+ * }
+ * });
+ * ```
+ */
+export class GroupMessageSenderProcessor extends BaseProcessor {
+ readonly name = 'GroupMessageSenderProcessor';
+
+ constructor(
+ private config: GroupMessageSenderConfig,
+ options: ProcessorOptions = {},
+ ) {
+ super(options);
+ }
+
+ protected async doProcess(context: PipelineContext): Promise<PipelineContext> {
+ const clonedContext = this.cloneContext(context);
+
+ // Skip if no agentMap provided
+ if (!this.config.agentMap || Object.keys(this.config.agentMap).length === 0) {
+ log('No agentMap provided, skipping processing');
+ return this.markAsExecuted(clonedContext);
+ }
+
+ let processedCount = 0;
+
+ clonedContext.messages = clonedContext.messages.map((msg: Message) => {
+ // Only process assistant messages with agentId
+ if (msg.role === 'assistant' && msg.agentId) {
+ const agentInfo = this.config.agentMap[msg.agentId];
+
+ if (agentInfo) {
+ // Build the sender tag
+ const senderTag = this.buildSenderContext(msg.agentId, agentInfo);
+
+ // Prepend to message content (at the beginning)
+ if (typeof msg.content === 'string') {
+ processedCount++;
+ log(
+ `Injecting sender info for message from agent: ${agentInfo.name} (${agentInfo.role})`,
+ );
+
+ return {
+ ...msg,
+ content: senderTag + msg.content,
+ };
+ }
+ // Handle array content (multimodal messages)
+ else if (Array.isArray(msg.content)) {
+ const firstTextIndex = msg.content.findIndex((part: any) => part.type === 'text');
+
+ if (firstTextIndex !== -1) {
+ processedCount++;
+ log(
+ `Injecting sender info for multimodal message from agent: ${agentInfo.name} (${agentInfo.role})`,
+ );
+
+ const newContent = [...msg.content];
+ newContent[firstTextIndex] = {
+ ...newContent[firstTextIndex],
+ text: senderTag + newContent[firstTextIndex].text,
+ };
+
+ return {
+ ...msg,
+ content: newContent,
+ };
+ }
+ }
+ }
+ }
+
+ return msg;
+ });
+
+ // Update metadata
+ clonedContext.metadata.groupMessageSenderProcessed = processedCount;
+
+ log(`Group message sender processing completed: ${processedCount} messages processed`);
+
+ return this.markAsExecuted(clonedContext);
+ }
+
+ /**
+ * Build the sender tag to prepend to assistant messages.
+ *
+ * Uses a self-closing XML tag at the beginning:
+ * - Placed at start so model sees "who is speaking" before the content
+ * - Self-closing tag is less likely to be reproduced as it's not a "wrapper"
+ */
+ private buildSenderContext(_agentId: string, agentInfo: AgentInfo): string {
+ return `<speaker name="${agentInfo.name}" />\n`;
+ }
+}
diff --git a/packages/context-engine/src/processors/InputTemplate.ts b/packages/context-engine/src/processors/InputTemplate.ts
index cd2bc0ff0f8..9b52e5d5e36 100644
--- a/packages/context-engine/src/processors/InputTemplate.ts
+++ b/packages/context-engine/src/processors/InputTemplate.ts
@@ -1,5 +1,5 @@
import debug from 'debug';
-import { template } from 'lodash-es';
+import { template } from 'es-toolkit/compat';
import { BaseProcessor } from '../base/BaseProcessor';
import type { PipelineContext, ProcessorOptions } from '../types';
diff --git a/packages/context-engine/src/processors/PlaceholderVariables.ts b/packages/context-engine/src/processors/PlaceholderVariables.ts
index 57843c7c177..b372dcb3036 100644
--- a/packages/context-engine/src/processors/PlaceholderVariables.ts
+++ b/packages/context-engine/src/processors/PlaceholderVariables.ts
@@ -7,6 +7,50 @@ const log = debug('context-engine:processor:PlaceholderVariablesProcessor');
const placeholderVariablesRegex = /{{(.*?)}}/g;
+export type PlaceholderValue = unknown | (() => unknown);
+export type PlaceholderValueMap = Record<string, PlaceholderValue>;
+
+const formatPlaceholderPrimitive = (value: unknown): string => {
+ if (value === undefined || value === null) return '';
+ if (Array.isArray(value)) {
+ return value
+ .map((item) => formatPlaceholderPrimitive(item))
+ .filter((item) => item.length > 0)
+ .join(', ');
+ }
+
+ if (typeof value === 'object') {
+ try {
+ return JSON.stringify(value);
+ } catch {
+ return '';
+ }
+ }
+
+ return String(value);
+};
+
+const resolvePlaceholderValue = (value: PlaceholderValue): string => {
+ try {
+ const resolved = typeof value === 'function' ? value() : value;
+ return formatPlaceholderPrimitive(resolved);
+ } catch {
+ return '';
+ }
+};
+
+export const buildPlaceholderGenerators = (
+ values: PlaceholderValueMap,
+): Record<string, () => string> =>
+ Object.fromEntries(
+ Object.entries(values).map(([key, value]) => [key, () => resolvePlaceholderValue(value)]),
+ );
+
+export const formatPlaceholderValues = (values: PlaceholderValueMap): Record<string, string> =>
+ Object.fromEntries(
+ Object.entries(values).map(([key, value]) => [key, resolvePlaceholderValue(value)]),
+ );
+
export interface PlaceholderVariablesConfig {
/** Recursive parsing depth, default is 2 */
depth?: number;
@@ -51,7 +95,7 @@ export const parsePlaceholderVariables = (
// Only perform replacement when there are available variables
if (Object.keys(availableVariables).length === 0) break;
- // Replace variables one by one to avoid lodash template's error handling for undefined variables
+ // Replace variables one by one to avoid es-toolkit template's error handling for undefined variables
let tempResult = result;
for (const [key, value] of Object.entries(availableVariables)) {
const regex = new RegExp(
@@ -72,6 +116,18 @@ export const parsePlaceholderVariables = (
return result;
};
+/**
+ * Convenience helper to render a template string with placeholder values
+ * @param template Template string containing {{variable}} tokens
+ * @param values Key-value map or generator map used for replacement
+ * @param depth Recursive depth
+ */
+export const renderPlaceholderTemplate = (
+ template: string,
+ values: PlaceholderValueMap,
+ depth = 2,
+): string => parsePlaceholderVariables(template, buildPlaceholderGenerators(values), depth);
+
/**
* Parse message content and replace placeholder variables
* @param messages Original messages array
diff --git a/packages/context-engine/src/processors/SupervisorRoleRestore.ts b/packages/context-engine/src/processors/SupervisorRoleRestore.ts
new file mode 100644
index 00000000000..36b2f03748e
--- /dev/null
+++ b/packages/context-engine/src/processors/SupervisorRoleRestore.ts
@@ -0,0 +1,60 @@
+import debug from 'debug';
+
+import { BaseProcessor } from '../base/BaseProcessor';
+import type { Message, PipelineContext, ProcessorOptions } from '../types';
+
+const log = debug('context-engine:processor:SupervisorRoleRestoreProcessor');
+
+/**
+ * Supervisor Role Restore Processor
+ *
+ * Restores messages with role='supervisor' back to role='assistant' before
+ * sending to the model. The 'supervisor' role is used for UI rendering in
+ * group orchestration scenarios, but models don't understand this role.
+ *
+ * Flow:
+ * 1. DB stores assistant messages with metadata.isSupervisor=true
+ * 2. conversation-flow transforms them to role='supervisor' for UI
+ * 3. This processor restores role='assistant' before model API call
+ *
+ * @example
+ * ```typescript
+ * const processor = new SupervisorRoleRestoreProcessor();
+ * const result = await processor.process(context);
+ * // All supervisor messages are now assistant messages
+ * ```
+ */
+export class SupervisorRoleRestoreProcessor extends BaseProcessor {
+ readonly name = 'SupervisorRoleRestoreProcessor';
+
+ constructor(options: ProcessorOptions = {}) {
+ super(options);
+ }
+
+ protected async doProcess(context: PipelineContext): Promise<PipelineContext> {
+ const clonedContext = this.cloneContext(context);
+
+ let processedCount = 0;
+
+ clonedContext.messages = clonedContext.messages.map((msg: Message) => {
+ if (msg.role === 'supervisor') {
+ processedCount++;
+ log(`Restoring supervisor message to assistant role`);
+
+ return {
+ ...msg,
+ role: 'assistant',
+ };
+ }
+
+ return msg;
+ });
+
+ // Update metadata
+ clonedContext.metadata.supervisorRoleRestoreProcessed = processedCount;
+
+ log(`Supervisor role restore completed: ${processedCount} messages processed`);
+
+ return this.markAsExecuted(clonedContext);
+ }
+}
diff --git a/packages/context-engine/src/processors/TaskMessage.ts b/packages/context-engine/src/processors/TaskMessage.ts
new file mode 100644
index 00000000000..7d16c4af674
--- /dev/null
+++ b/packages/context-engine/src/processors/TaskMessage.ts
@@ -0,0 +1,112 @@
+import debug from 'debug';
+
+import { BaseProcessor } from '../base/BaseProcessor';
+import type { PipelineContext, ProcessorOptions } from '../types';
+
+const log = debug('context-engine:processor:TaskMessageProcessor');
+
+/**
+ * Default template for combining instruction and result
+ */
+const DEFAULT_TEMPLATE = `[Task Result from {{agentName}}]
+
+**Task Instruction:**
+{{instruction}}
+
+**Task Result:**
+{{content}}`;
+
+export interface TaskMessageConfig {
+ /**
+ * Custom template for formatting task messages
+ * Available placeholders: {{agentName}}, {{instruction}}, {{content}}
+ */
+ template?: string;
+}
+
+/**
+ * Task Message Processor
+ *
+ * Processes role='task' messages by combining the instruction (from metadata)
+ * and the result content into a single assistant message format.
+ *
+ * This transformation helps LLMs understand the context of task execution results
+ * in group agent conversations.
+ */
+export class TaskMessageProcessor extends BaseProcessor {
+ readonly name = 'TaskMessageProcessor';
+
+ constructor(
+ private config: TaskMessageConfig = {},
+ options: ProcessorOptions = {},
+ ) {
+ super(options);
+ }
+
+ protected async doProcess(context: PipelineContext): Promise<PipelineContext> {
+ const clonedContext = this.cloneContext(context);
+
+ let processedCount = 0;
+ const template = this.config.template || DEFAULT_TEMPLATE;
+
+ for (let i = 0; i < clonedContext.messages.length; i++) {
+ const message = clonedContext.messages[i];
+
+ // Only process task messages
+ if (message.role !== 'task') continue;
+
+ const instruction = message.metadata?.instruction;
+ const content = message.content || '';
+ const agentName = message.agentName || message.meta?.avatar || 'Sub Agent';
+
+ // If no instruction, just convert to assistant role with original content
+ if (!instruction) {
+ clonedContext.messages[i] = {
+ ...message,
+ content: content,
+ role: 'assistant',
+ };
+ processedCount++;
+ log(`Converted task message ${message.id} to assistant (no instruction)`);
+ continue;
+ }
+
+ // Apply template
+ const formattedContent = this.applyTemplate(template, {
+ agentName: String(agentName),
+ content: String(content),
+ instruction: String(instruction),
+ });
+
+ // Convert to assistant message with formatted content
+ clonedContext.messages[i] = {
+ ...message,
+ content: formattedContent,
+ role: 'assistant',
+ };
+
+ processedCount++;
+ log(`Processed task message ${message.id} with instruction`);
+ }
+
+ // Update metadata
+ clonedContext.metadata.taskMessagesProcessed = processedCount;
+
+ log(`Task message processing completed, processed ${processedCount} messages`);
+
+ return this.markAsExecuted(clonedContext);
+ }
+
+ /**
+ * Apply template with placeholders
+ */
+ private applyTemplate(
+ template: string,
+ values: { agentName: string; content: string; instruction: string },
+ ): string {
+ return template
+ .replaceAll('{{agentName}}', values.agentName)
+ .replaceAll('{{instruction}}', values.instruction)
+ .replaceAll('{{content}}', values.content);
+ }
+}
diff --git a/packages/context-engine/src/processors/__tests__/AgentCouncilFlatten.test.ts b/packages/context-engine/src/processors/__tests__/AgentCouncilFlatten.test.ts
new file mode 100644
index 00000000000..73e0b1f9636
--- /dev/null
+++ b/packages/context-engine/src/processors/__tests__/AgentCouncilFlatten.test.ts
@@ -0,0 +1,629 @@
+import { describe, expect, it } from 'vitest';
+
+import { PipelineContext } from '../../types';
+import { AgentCouncilFlattenProcessor } from '../AgentCouncilFlatten';
+
+describe('AgentCouncilFlattenProcessor', () => {
+ const createContext = (messages: any[]): PipelineContext => ({
+ initialState: { messages: [] },
+ isAborted: false,
+ messages,
+ metadata: {},
+ });
+
+ describe('Basic Scenarios', () => {
+ it('should flatten agentCouncil message with multiple simple members', async () => {
+ const processor = new AgentCouncilFlattenProcessor();
+
+ const input: any[] = [
+ {
+ content: '',
+ createdAt: 1704067205000,
+ extra: {
+ parentMessageId: 'msg-broadcast-tool-1',
+ },
+ id: 'agentCouncil-msg-1',
+ members: [
+ {
+ id: 'msg-agent-backend-1',
+ role: 'assistant',
+ agentId: 'agent-backend',
+ content: 'Backend perspective content',
+ parentId: 'msg-broadcast-tool-1',
+ model: 'gpt-4',
+ provider: 'openai',
+ createdAt: 1704067205000,
+ updatedAt: 1704067205000,
+ meta: {
+ avatar: 'backend-dev',
+ title: 'Backend Developer',
+ },
+ },
+ {
+ id: 'msg-agent-devops-1',
+ role: 'assistant',
+ agentId: 'agent-devops',
+ content: 'DevOps perspective content',
+ parentId: 'msg-broadcast-tool-1',
+ model: 'claude-3-5-sonnet-20241022',
+ provider: 'anthropic',
+ createdAt: 1704067205500,
+ updatedAt: 1704067205500,
+ meta: {
+ avatar: 'devops',
+ title: 'DevOps Engineer',
+ },
+ },
+ ],
+ meta: {},
+ role: 'agentCouncil',
+ updatedAt: 1704067206000,
+ },
+ ];
+
+ const context = createContext(input);
+ const result = await processor.process(context);
+
+ // Should create 2 assistant messages
+ expect(result.messages).toHaveLength(2);
+
+ // Check first assistant message
+ const assistantMsg1 = result.messages[0];
+ expect(assistantMsg1.role).toBe('assistant');
+ expect(assistantMsg1.id).toBe('msg-agent-backend-1');
+ expect(assistantMsg1.content).toBe('Backend perspective content');
+ expect(assistantMsg1.agentId).toBe('agent-backend');
+ expect(assistantMsg1.model).toBe('gpt-4');
+ expect(assistantMsg1.provider).toBe('openai');
+ expect(assistantMsg1.meta.title).toBe('Backend Developer');
+
+ // Check second assistant message
+ const assistantMsg2 = result.messages[1];
+ expect(assistantMsg2.role).toBe('assistant');
+ expect(assistantMsg2.id).toBe('msg-agent-devops-1');
+ expect(assistantMsg2.content).toBe('DevOps perspective content');
+ expect(assistantMsg2.agentId).toBe('agent-devops');
+ expect(assistantMsg2.model).toBe('claude-3-5-sonnet-20241022');
+ expect(assistantMsg2.provider).toBe('anthropic');
+
+ // Check metadata
+ expect(result.metadata.agentCouncilMessagesFlattened).toBe(1);
+ expect(result.metadata.agentCouncilAssistantMessagesCreated).toBe(2);
+ expect(result.metadata.agentCouncilToolMessagesCreated).toBe(0);
+ });
+
+ it('should flatten agentCouncil message with member having tools', async () => {
+ const processor = new AgentCouncilFlattenProcessor();
+
+ const input: any[] = [
+ {
+ content: '',
+ createdAt: 1704067205000,
+ extra: {
+ parentMessageId: 'msg-broadcast-tool-1',
+ },
+ id: 'agentCouncil-msg-1',
+ members: [
+ {
+ id: 'msg-agent-1',
+ role: 'assistant',
+ agentId: 'agent-1',
+ content: 'Let me search for that',
+ parentId: 'msg-broadcast-tool-1',
+ createdAt: 1704067205000,
+ updatedAt: 1704067205000,
+ meta: {},
+ tools: [
+ {
+ id: 'tool-1',
+ type: 'builtin',
+ apiName: 'search',
+ arguments: '{"query":"test"}',
+ identifier: 'web-browsing',
+ result: {
+ id: 'msg-tool-1',
+ content: 'Search result',
+ error: null,
+ state: { cached: true },
+ },
+ },
+ ],
+ },
+ ],
+ meta: {},
+ role: 'agentCouncil',
+ updatedAt: 1704067206000,
+ },
+ ];
+
+ const context = createContext(input);
+ const result = await processor.process(context);
+
+ // Should create 2 messages: 1 assistant + 1 tool
+ expect(result.messages).toHaveLength(2);
+
+ // Check assistant message
+ const assistantMsg = result.messages[0];
+ expect(assistantMsg.role).toBe('assistant');
+ expect(assistantMsg.tools).toHaveLength(1);
+ expect(assistantMsg.tools[0].id).toBe('tool-1');
+
+ // Check tool message
+ const toolMsg = result.messages[1];
+ expect(toolMsg.role).toBe('tool');
+ expect(toolMsg.id).toBe('msg-tool-1');
+ expect(toolMsg.content).toBe('Search result');
+ expect(toolMsg.tool_call_id).toBe('tool-1');
+ expect(toolMsg.plugin.identifier).toBe('web-browsing');
+ expect(toolMsg.pluginState).toEqual({ cached: true });
+
+ expect(result.metadata.agentCouncilAssistantMessagesCreated).toBe(1);
+ expect(result.metadata.agentCouncilToolMessagesCreated).toBe(1);
+ });
+
+ it('should flatten agentCouncil with assistantGroup member', async () => {
+ const processor = new AgentCouncilFlattenProcessor();
+
+ const input: any[] = [
+ {
+ content: '',
+ createdAt: 1704067205000,
+ extra: {
+ parentMessageId: 'msg-broadcast-tool-1',
+ },
+ id: 'agentCouncil-msg-1',
+ members: [
+ {
+ // assistantGroup member (agent that used tools)
+ id: 'msg-agent-group-1',
+ role: 'assistantGroup',
+ agentId: 'agent-with-tools',
+ content: '',
+ parentId: 'msg-broadcast-tool-1',
+ createdAt: 1704067205000,
+ updatedAt: 1704067205000,
+ meta: { title: 'Agent with Tools' },
+ children: [
+ {
+ id: 'child-1',
+ content: 'Checking something',
+ tools: [
+ {
+ id: 'tool-1',
+ type: 'builtin',
+ apiName: 'search',
+ arguments: '{}',
+ identifier: 'web-browsing',
+ result: {
+ id: 'msg-tool-1',
+ content: 'Result 1',
+ error: null,
+ state: {},
+ },
+ },
+ ],
+ },
+ ],
+ },
+ ],
+ meta: {},
+ role: 'agentCouncil',
+ updatedAt: 1704067206000,
+ },
+ ];
+
+ const context = createContext(input);
+ const result = await processor.process(context);
+
+ // Should create 2 messages: 1 assistant + 1 tool
+ expect(result.messages).toHaveLength(2);
+
+ const assistantMsg = result.messages[0];
+ expect(assistantMsg.role).toBe('assistant');
+ expect(assistantMsg.id).toBe('child-1');
+ expect(assistantMsg.content).toBe('Checking something');
+ expect(assistantMsg.agentId).toBe('agent-with-tools');
+
+ const toolMsg = result.messages[1];
+ expect(toolMsg.role).toBe('tool');
+ expect(toolMsg.id).toBe('msg-tool-1');
+ });
+ });
+
+ describe('Mixed Messages', () => {
+ it('should preserve non-agentCouncil messages and flatten agentCouncil messages', async () => {
+ const processor = new AgentCouncilFlattenProcessor();
+
+ const input: any[] = [
+ {
+ id: 'msg-user-1',
+ role: 'user',
+ content: 'Ask everyone about this topic',
+ },
+ {
+ content: '',
+ createdAt: 1704067205000,
+ extra: {
+ parentMessageId: 'msg-broadcast-tool-1',
+ },
+ id: 'agentCouncil-msg-1',
+ members: [
+ {
+ id: 'msg-agent-1',
+ role: 'assistant',
+ content: 'Response from agent 1',
+ meta: {},
+ },
+ {
+ id: 'msg-agent-2',
+ role: 'assistant',
+ content: 'Response from agent 2',
+ meta: {},
+ },
+ ],
+ meta: {},
+ role: 'agentCouncil',
+ updatedAt: 1704067206000,
+ },
+ {
+ id: 'msg-user-2',
+ role: 'user',
+ content: 'Thanks for the responses!',
+ },
+ ];
+
+ const context = createContext(input);
+ const result = await processor.process(context);
+
+ // 1 user + 2 assistants + 1 user = 4 messages
+ expect(result.messages).toHaveLength(4);
+ expect(result.messages[0].role).toBe('user');
+ expect(result.messages[0].id).toBe('msg-user-1');
+ expect(result.messages[1].role).toBe('assistant');
+ expect(result.messages[1].id).toBe('msg-agent-1');
+ expect(result.messages[2].role).toBe('assistant');
+ expect(result.messages[2].id).toBe('msg-agent-2');
+ expect(result.messages[3].role).toBe('user');
+ expect(result.messages[3].id).toBe('msg-user-2');
+ });
+ });
+
+ describe('Edge Cases', () => {
+ it('should handle agentCouncil message with empty members array', async () => {
+ const processor = new AgentCouncilFlattenProcessor();
+
+ const input: any[] = [
+ {
+ content: '',
+ id: 'agentCouncil-msg-1',
+ members: [],
+ meta: {},
+ role: 'agentCouncil',
+ },
+ ];
+
+ const context = createContext(input);
+ const result = await processor.process(context);
+
+ // Empty members means no messages created
+ expect(result.messages).toHaveLength(0);
+ });
+
+ it('should handle agentCouncil message without members field', async () => {
+ const processor = new AgentCouncilFlattenProcessor();
+
+ const input: any[] = [
+ {
+ content: '',
+ id: 'agentCouncil-msg-1',
+ meta: {},
+ role: 'agentCouncil',
+ // No members field
+ },
+ ];
+
+ const context = createContext(input);
+ const result = await processor.process(context);
+
+ // Should keep the message as-is (though this is invalid data)
+ expect(result.messages).toHaveLength(1);
+ expect(result.messages[0].id).toBe('agentCouncil-msg-1');
+ });
+
+ it('should preserve reasoning field from member', async () => {
+ const processor = new AgentCouncilFlattenProcessor();
+
+ const input: any[] = [
+ {
+ content: '',
+ id: 'agentCouncil-msg-1',
+ members: [
+ {
+ id: 'msg-1',
+ role: 'assistant',
+ content: 'Result',
+ reasoning: {
+ content: 'Thinking about the query...',
+ signature: 'sig-123',
+ },
+ meta: {},
+ },
+ ],
+ meta: {},
+ role: 'agentCouncil',
+ },
+ ];
+
+ const context = createContext(input);
+ const result = await processor.process(context);
+
+ expect(result.messages).toHaveLength(1);
+ expect(result.messages[0].reasoning).toEqual({
+ content: 'Thinking about the query...',
+ signature: 'sig-123',
+ });
+ });
+
+ it('should preserve error field from member', async () => {
+ const processor = new AgentCouncilFlattenProcessor();
+
+ const input: any[] = [
+ {
+ content: '',
+ id: 'agentCouncil-msg-1',
+ members: [
+ {
+ id: 'msg-1',
+ role: 'assistant',
+ content: 'Error occurred',
+ error: {
+ type: 'InvalidAPIKey',
+ message: 'API key is invalid',
+ },
+ meta: {},
+ },
+ ],
+ meta: {},
+ role: 'agentCouncil',
+ },
+ ];
+
+ const context = createContext(input);
+ const result = await processor.process(context);
+
+ expect(result.messages).toHaveLength(1);
+ expect(result.messages[0].error).toEqual({
+ type: 'InvalidAPIKey',
+ message: 'API key is invalid',
+ });
+ });
+
+ it('should preserve imageList field from member', async () => {
+ const processor = new AgentCouncilFlattenProcessor();
+
+ const input: any[] = [
+ {
+ content: '',
+ id: 'agentCouncil-msg-1',
+ members: [
+ {
+ id: 'msg-1',
+ role: 'assistant',
+ content: 'Here are the images',
+ imageList: [
+ { id: 'img-1', url: 'https://example.com/img1.jpg', alt: 'Image 1' },
+ { id: 'img-2', url: 'https://example.com/img2.jpg', alt: 'Image 2' },
+ ],
+ meta: {},
+ },
+ ],
+ meta: {},
+ role: 'agentCouncil',
+ },
+ ];
+
+ const context = createContext(input);
+ const result = await processor.process(context);
+
+ expect(result.messages).toHaveLength(1);
+ expect(result.messages[0].imageList).toEqual([
+ { id: 'img-1', url: 'https://example.com/img1.jpg', alt: 'Image 1' },
+ { id: 'img-2', url: 'https://example.com/img2.jpg', alt: 'Image 2' },
+ ]);
+ });
+
+ it('should preserve parent/thread/group/topic IDs from member', async () => {
+ const processor = new AgentCouncilFlattenProcessor();
+
+ const input: any[] = [
+ {
+ content: '',
+ id: 'agentCouncil-msg-1',
+ members: [
+ {
+ id: 'msg-1',
+ role: 'assistant',
+ content: '',
+ parentId: 'parent-1',
+ threadId: 'thread-1',
+ groupId: 'group-1',
+ topicId: 'topic-1',
+ meta: {},
+ },
+ ],
+ meta: {},
+ role: 'agentCouncil',
+ },
+ ];
+
+ const context = createContext(input);
+ const result = await processor.process(context);
+
+ const assistantMsg = result.messages[0];
+ expect(assistantMsg.parentId).toBe('parent-1');
+ expect(assistantMsg.threadId).toBe('thread-1');
+ expect(assistantMsg.groupId).toBe('group-1');
+ expect(assistantMsg.topicId).toBe('topic-1');
+ });
+
+ it('should handle assistantGroup member with empty children', async () => {
+ const processor = new AgentCouncilFlattenProcessor();
+
+ const input: any[] = [
+ {
+ content: '',
+ id: 'agentCouncil-msg-1',
+ members: [
+ {
+ id: 'msg-group-1',
+ role: 'assistantGroup',
+ content: '',
+ children: [],
+ meta: {},
+ },
+ ],
+ meta: {},
+ role: 'agentCouncil',
+ },
+ ];
+
+ const context = createContext(input);
+ const result = await processor.process(context);
+
+ // Empty children in assistantGroup means no messages from that member
+ expect(result.messages).toHaveLength(0);
+ });
+ });
+
+ describe('Real-world Test Case', () => {
+ it('should flatten the agentCouncil message from broadcast scenario', async () => {
+ const processor = new AgentCouncilFlattenProcessor();
+
+ // Based on the fixture from conversation-flow
+ const input: any[] = [
+ {
+ content: '',
+ createdAt: 1704067205000,
+ extra: {
+ parentMessageId: 'msg-broadcast-tool-1',
+ },
+ id: 'agentCouncil-msg-broadcast-tool-1-msg-agent-backend-1-msg-agent-devops-1-msg-agent-architect-1',
+ members: [
+ {
+ id: 'msg-agent-backend-1',
+ role: 'assistant',
+ agentId: 'agent-backend',
+ content:
+ "**From a Backend Developer's Perspective:**\n\n**Pros:**\n- Independent deployment of services\n- Technology flexibility per service\n- Better fault isolation\n- Easier to scale specific services\n\n**Cons:**\n- Increased complexity in service communication\n- Data consistency challenges\n- More complex debugging and monitoring\n- Network latency between services",
+ parentId: 'msg-broadcast-tool-1',
+ model: 'gpt-4',
+ provider: 'openai',
+ createdAt: 1704067205000,
+ updatedAt: 1704067205000,
+ meta: {
+ avatar: 'backend-dev',
+ title: 'Backend Developer',
+ },
+ metadata: {
+ totalInputTokens: 50,
+ totalOutputTokens: 120,
+ totalTokens: 170,
+ tps: 45,
+ ttft: 350,
+ duration: 2667,
+ latency: 3017,
+ },
+ },
+ {
+ id: 'msg-agent-devops-1',
+ role: 'assistant',
+ agentId: 'agent-devops',
+ content:
+ "**From a DevOps Engineer's Perspective:**\n\n**Pros:**\n- CI/CD pipelines can be service-specific\n- Container orchestration fits naturally\n- Auto-scaling at service level\n- Blue-green deployments are easier\n\n**Cons:**\n- Complex infrastructure management\n- More services = more monitoring overhead\n- Configuration management complexity\n- Increased resource consumption (each service needs its own runtime)",
+ parentId: 'msg-broadcast-tool-1',
+ model: 'claude-3-5-sonnet-20241022',
+ provider: 'anthropic',
+ createdAt: 1704067205500,
+ updatedAt: 1704067205500,
+ meta: {
+ avatar: 'devops',
+ title: 'DevOps Engineer',
+ },
+ metadata: {
+ totalInputTokens: 50,
+ totalOutputTokens: 130,
+ totalTokens: 180,
+ tps: 52,
+ ttft: 280,
+ duration: 2500,
+ latency: 2780,
+ },
+ },
+ {
+ id: 'msg-agent-architect-1',
+ role: 'assistant',
+ agentId: 'agent-architect',
+ content:
+ "**From a Software Architect's Perspective:**\n\n**Pros:**\n- Clear service boundaries and ownership\n- Supports domain-driven design\n- Teams can work independently\n- Easier to understand individual services\n\n**Cons:**\n- Requires careful API versioning strategy\n- Cross-cutting concerns need special handling\n- Service discovery and load balancing complexity\n- Initial design requires significant upfront investment",
+ parentId: 'msg-broadcast-tool-1',
+ model: 'gpt-4',
+ provider: 'openai',
+ createdAt: 1704067206000,
+ updatedAt: 1704067206000,
+ meta: {
+ avatar: 'architect',
+ title: 'Software Architect',
+ },
+ metadata: {
+ totalInputTokens: 50,
+ totalOutputTokens: 125,
+ totalTokens: 175,
+ tps: 48,
+ ttft: 320,
+ duration: 2604,
+ latency: 2924,
+ },
+ },
+ ],
+ meta: {},
+ role: 'agentCouncil',
+ updatedAt: 1704067206000,
+ },
+ ];
+
+ const context = createContext(input);
+ const result = await processor.process(context);
+
+ // Should create 3 assistant messages (one from each agent)
+ expect(result.messages).toHaveLength(3);
+
+ // Verify all messages have correct role
+ expect(result.messages.every((m: any) => m.role === 'assistant')).toBe(true);
+
+ // Check first agent (Backend Developer)
+ expect(result.messages[0].id).toBe('msg-agent-backend-1');
+ expect(result.messages[0].agentId).toBe('agent-backend');
+ expect(result.messages[0].model).toBe('gpt-4');
+ expect(result.messages[0].provider).toBe('openai');
+ expect(result.messages[0].meta.title).toBe('Backend Developer');
+ expect(result.messages[0].content).toContain('Backend Developer');
+
+ // Check second agent (DevOps Engineer)
+ expect(result.messages[1].id).toBe('msg-agent-devops-1');
+ expect(result.messages[1].agentId).toBe('agent-devops');
+ expect(result.messages[1].model).toBe('claude-3-5-sonnet-20241022');
+ expect(result.messages[1].provider).toBe('anthropic');
+ expect(result.messages[1].meta.title).toBe('DevOps Engineer');
+
+ // Check third agent (Software Architect)
+ expect(result.messages[2].id).toBe('msg-agent-architect-1');
+ expect(result.messages[2].agentId).toBe('agent-architect');
+ expect(result.messages[2].meta.title).toBe('Software Architect');
+
+ // Check metadata
+ expect(result.metadata.agentCouncilMessagesFlattened).toBe(1);
+ expect(result.metadata.agentCouncilAssistantMessagesCreated).toBe(3);
+ expect(result.metadata.agentCouncilToolMessagesCreated).toBe(0);
+ });
+ });
+});
diff --git a/packages/context-engine/src/processors/__tests__/GroupMessageSender.test.ts b/packages/context-engine/src/processors/__tests__/GroupMessageSender.test.ts
new file mode 100644
index 00000000000..36271604b15
--- /dev/null
+++ b/packages/context-engine/src/processors/__tests__/GroupMessageSender.test.ts
@@ -0,0 +1,274 @@
+import { describe, expect, it } from 'vitest';
+
+import { PipelineContext } from '../../types';
+import { GroupMessageSenderProcessor } from '../GroupMessageSender';
+
+describe('GroupMessageSenderProcessor', () => {
+ const createContext = (messages: any[]): PipelineContext => ({
+ initialState: { messages: [] },
+ isAborted: false,
+ messages,
+ metadata: {},
+ });
+
+ describe('Basic Scenarios', () => {
+ it('should inject sender info into assistant message with agentId', async () => {
+ const processor = new GroupMessageSenderProcessor({
+ agentMap: {
+ agt_weather: { name: 'Weather Expert', role: 'participant' },
+ },
+ });
+
+ const input: any[] = [
+ { role: 'user', content: 'What is the weather?' },
+ { role: 'assistant', content: 'The weather is sunny.', agentId: 'agt_weather' },
+ ];
+
+ const context = createContext(input);
+ const result = await processor.process(context);
+
+ expect(result.messages).toHaveLength(2);
+
+ // User message should be unchanged
+ expect(result.messages[0].content).toBe('What is the weather?');
+
+ // Assistant message should have speaker tag prepended
+ const assistantContent = result.messages[1].content;
+ expect(assistantContent).toMatch(/^<speaker name="Weather Expert" \/>/);
+ expect(assistantContent).toContain('The weather is sunny.');
+
+ // Check metadata
+ expect(result.metadata.groupMessageSenderProcessed).toBe(1);
+ });
+
+ it('should inject sender info for supervisor role', async () => {
+ const processor = new GroupMessageSenderProcessor({
+ agentMap: {
+ agt_supervisor: { name: 'Group Supervisor', role: 'supervisor' },
+ },
+ });
+
+ const input: any[] = [
+ { role: 'assistant', content: 'I will coordinate the agents.', agentId: 'agt_supervisor' },
+ ];
+
+ const context = createContext(input);
+ const result = await processor.process(context);
+
+ const assistantContent = result.messages[0].content;
+ expect(assistantContent).toMatch(/^<speaker name="Group Supervisor" \/>/);
+ });
+
+ it('should not modify assistant message without agentId', async () => {
+ const processor = new GroupMessageSenderProcessor({
+ agentMap: {
+ agt_weather: { name: 'Weather Expert', role: 'participant' },
+ },
+ });
+
+ const input: any[] = [{ role: 'assistant', content: 'Hello from assistant.' }];
+
+ const context = createContext(input);
+ const result = await processor.process(context);
+
+ // Should be unchanged
+ expect(result.messages[0].content).toBe('Hello from assistant.');
+ expect(result.metadata.groupMessageSenderProcessed).toBe(0);
+ });
+
+ it('should not modify assistant message with unknown agentId', async () => {
+ const processor = new GroupMessageSenderProcessor({
+ agentMap: {
+ agt_weather: { name: 'Weather Expert', role: 'participant' },
+ },
+ });
+
+ const input: any[] = [{ role: 'assistant', content: 'Hello.', agentId: 'agt_unknown' }];
+
+ const context = createContext(input);
+ const result = await processor.process(context);
+
+ // Should be unchanged because agentId not in map
+ expect(result.messages[0].content).toBe('Hello.');
+ expect(result.metadata.groupMessageSenderProcessed).toBe(0);
+ });
+
+ it('should not modify user or tool messages', async () => {
+ const processor = new GroupMessageSenderProcessor({
+ agentMap: {
+ agt_weather: { name: 'Weather Expert', role: 'participant' },
+ },
+ });
+
+ const input: any[] = [
+ { role: 'user', content: 'Hello', agentId: 'agt_weather' },
+ { role: 'tool', content: 'Tool result', agentId: 'agt_weather' },
+ ];
+
+ const context = createContext(input);
+ const result = await processor.process(context);
+
+ expect(result.messages[0].content).toBe('Hello');
+ expect(result.messages[1].content).toBe('Tool result');
+ expect(result.metadata.groupMessageSenderProcessed).toBe(0);
+ });
+ });
+
+ describe('Multiple Messages', () => {
+ it('should process multiple assistant messages from different agents', async () => {
+ const processor = new GroupMessageSenderProcessor({
+ agentMap: {
+ agt_weather: { name: 'Weather Expert', role: 'participant' },
+ agt_news: { name: 'News Reporter', role: 'participant' },
+ agt_supervisor: { name: 'Supervisor', role: 'supervisor' },
+ },
+ });
+
+ const input: any[] = [
+ { role: 'user', content: 'Give me updates' },
+ { role: 'assistant', content: 'Weather is sunny.', agentId: 'agt_weather' },
+ { role: 'assistant', content: 'Top news today.', agentId: 'agt_news' },
+ { role: 'assistant', content: 'Summary complete.', agentId: 'agt_supervisor' },
+ ];
+
+ const context = createContext(input);
+ const result = await processor.process(context);
+
+ expect(result.messages).toHaveLength(4);
+
+ // Check each assistant message has correct speaker tag prepended
+ expect(result.messages[1].content).toMatch(/^<speaker name="Weather Expert" \/>/);
+ expect(result.messages[2].content).toMatch(/^<speaker name="News Reporter" \/>/);
+ expect(result.messages[3].content).toMatch(/^<speaker name="Supervisor" \/>/);
+
+ expect(result.metadata.groupMessageSenderProcessed).toBe(3);
+ });
+ });
+
+ describe('Multimodal Messages', () => {
+ it('should handle array content (multimodal messages)', async () => {
+ const processor = new GroupMessageSenderProcessor({
+ agentMap: {
+ agt_weather: { name: 'Weather Expert', role: 'participant' },
+ },
+ });
+
+ const input: any[] = [
+ {
+ role: 'assistant',
+ content: [
+ { type: 'text', text: 'Here is the weather chart.' },
+ { type: 'image_url', image_url: { url: 'https://example.com/chart.png' } },
+ ],
+ agentId: 'agt_weather',
+ },
+ ];
+
+ const context = createContext(input);
+ const result = await processor.process(context);
+
+ const content = result.messages[0].content as any[];
+ expect(Array.isArray(content)).toBe(true);
+
+ // The first text part should have speaker tag prepended
+ const textPart = content.find((p: any) => p.type === 'text');
+ expect(textPart.text).toMatch(/^<speaker name="Weather Expert" \/>/);
+ expect(textPart.text).toContain('Here is the weather chart.');
+
+ // Image part should be unchanged
+ const imagePart = content.find((p: any) => p.type === 'image_url');
+ expect(imagePart.image_url.url).toBe('https://example.com/chart.png');
+
+ expect(result.metadata.groupMessageSenderProcessed).toBe(1);
+ });
+
+ it('should append to the last text part in multimodal content', async () => {
+ const processor = new GroupMessageSenderProcessor({
+ agentMap: {
+ agt_weather: { name: 'Weather Expert', role: 'participant' },
+ },
+ });
+
+ const input: any[] = [
+ {
+ role: 'assistant',
+ content: [
+ { type: 'text', text: 'First text.' },
+ { type: 'image_url', image_url: { url: 'https://example.com/img.png' } },
+ { type: 'text', text: 'Last text.' },
+ ],
+ agentId: 'agt_weather',
+ },
+ ];
+
+ const context = createContext(input);
+ const result = await processor.process(context);
+
+ const content = result.messages[0].content;
+
+ // First text part should have speaker tag prepended
+ expect(content[0].text).toMatch(/^<speaker name="Weather Expert" \/>/);
+ expect(content[0].text).toContain('First text.');
+
+ // Last text should be unchanged
+ expect(content[2].text).toBe('Last text.');
+ });
+ });
+
+ describe('Edge Cases', () => {
+ it('should skip processing with empty agentMap', async () => {
+ const processor = new GroupMessageSenderProcessor({
+ agentMap: {},
+ });
+
+ const input: any[] = [{ role: 'assistant', content: 'Hello', agentId: 'agt_weather' }];
+
+ const context = createContext(input);
+ const result = await processor.process(context);
+
+ expect(result.messages[0].content).toBe('Hello');
+ });
+
+ it('should handle empty messages array', async () => {
+ const processor = new GroupMessageSenderProcessor({
+ agentMap: {
+ agt_weather: { name: 'Weather Expert', role: 'participant' },
+ },
+ });
+
+ const context = createContext([]);
+ const result = await processor.process(context);
+
+ expect(result.messages).toHaveLength(0);
+ expect(result.metadata.groupMessageSenderProcessed).toBe(0);
+ });
+
+ it('should preserve original message properties', async () => {
+ const processor = new GroupMessageSenderProcessor({
+ agentMap: {
+ agt_weather: { name: 'Weather Expert', role: 'participant' },
+ },
+ });
+
+ const input: any[] = [
+ {
+ role: 'assistant',
+ content: 'Weather info.',
+ agentId: 'agt_weather',
+ id: 'msg-123',
+ createdAt: '2025-01-01T00:00:00Z',
+ customField: 'custom value',
+ },
+ ];
+
+ const context = createContext(input);
+ const result = await processor.process(context);
+
+ const msg = result.messages[0];
+ expect(msg.id).toBe('msg-123');
+ expect(msg.createdAt).toBe('2025-01-01T00:00:00Z');
+ expect(msg.customField).toBe('custom value');
+ expect(msg.agentId).toBe('agt_weather');
+ });
+ });
+});
diff --git a/packages/context-engine/src/processors/__tests__/PlaceholderVariables.test.ts b/packages/context-engine/src/processors/__tests__/PlaceholderVariables.test.ts
index dd4385e0c3d..5802ce4caa1 100644
--- a/packages/context-engine/src/processors/__tests__/PlaceholderVariables.test.ts
+++ b/packages/context-engine/src/processors/__tests__/PlaceholderVariables.test.ts
@@ -2,8 +2,10 @@ import { describe, expect, it } from 'vitest';
import {
PlaceholderVariablesProcessor,
+ formatPlaceholderValues,
parsePlaceholderVariables,
parsePlaceholderVariablesMessages,
+ renderPlaceholderTemplate,
} from '../PlaceholderVariables';
describe('PlaceholderVariablesProcessor', () => {
@@ -331,4 +333,30 @@ describe('PlaceholderVariablesProcessor', () => {
expect(result.metadata.placeholderVariablesProcessed).toBe(0);
});
});
+
+ describe('formatPlaceholderValues & renderPlaceholderTemplate', () => {
+ it('formats nested structures into strings', () => {
+ const formatted = formatPlaceholderValues({
+ empty: undefined,
+ list: ['work', 'personal'],
+ nested: ['alpha', ['beta']],
+ number: 42,
+ });
+
+ expect(formatted.empty).toBe('');
+ expect(formatted.list).toBe('work, personal');
+ expect(formatted.nested).toBe('alpha, beta');
+ expect(formatted.number).toBe('42');
+ });
+
+ it('renders template strings using provided values', () => {
+ const template = 'Hello {{ name }}! Categories: {{ categories }}';
+ const result = renderPlaceholderTemplate(template, {
+ categories: ['work', 'personal'],
+ name: 'World',
+ });
+
+ expect(result).toBe('Hello World! Categories: work, personal');
+ });
+ });
});
diff --git a/packages/context-engine/src/processors/__tests__/SupervisorRoleRestore.test.ts b/packages/context-engine/src/processors/__tests__/SupervisorRoleRestore.test.ts
new file mode 100644
index 00000000000..9c7605d3f22
--- /dev/null
+++ b/packages/context-engine/src/processors/__tests__/SupervisorRoleRestore.test.ts
@@ -0,0 +1,122 @@
+import { describe, expect, it } from 'vitest';
+
+import type { PipelineContext } from '../../types';
+import { SupervisorRoleRestoreProcessor } from '../SupervisorRoleRestore';
+
+describe('SupervisorRoleRestoreProcessor', () => {
+ const createContext = (messages: any[]): PipelineContext => ({
+ initialState: { messages: [] },
+ isAborted: false,
+ messages,
+ metadata: {},
+ });
+
+ it('should restore supervisor role to assistant', async () => {
+ const processor = new SupervisorRoleRestoreProcessor();
+ const context = createContext([
+ { content: 'Hello', role: 'user' },
+ { content: 'I am the supervisor', role: 'supervisor' },
+ ]);
+
+ const result = await processor.process(context);
+
+ expect(result.messages).toHaveLength(2);
+ expect(result.messages[0].role).toBe('user');
+ expect(result.messages[1].role).toBe('assistant');
+ expect(result.messages[1].content).toBe('I am the supervisor');
+ });
+
+ it('should NOT modify non-supervisor messages', async () => {
+ const processor = new SupervisorRoleRestoreProcessor();
+ const context = createContext([
+ { content: 'Hello', role: 'user' },
+ { content: 'Hi there', role: 'assistant' },
+ { content: 'Tool result', role: 'tool' },
+ ]);
+
+ const result = await processor.process(context);
+
+ expect(result.messages).toHaveLength(3);
+ expect(result.messages[0].role).toBe('user');
+ expect(result.messages[1].role).toBe('assistant');
+ expect(result.messages[2].role).toBe('tool');
+ });
+
+ it('should handle multiple supervisor messages', async () => {
+ const processor = new SupervisorRoleRestoreProcessor();
+ const context = createContext([
+ { content: 'User message', role: 'user' },
+ { content: 'Supervisor first', role: 'supervisor' },
+ { content: 'Agent response', role: 'assistant' },
+ { content: 'Supervisor second', role: 'supervisor' },
+ ]);
+
+ const result = await processor.process(context);
+
+ expect(result.messages).toHaveLength(4);
+ expect(result.messages[0].role).toBe('user');
+ expect(result.messages[1].role).toBe('assistant');
+ expect(result.messages[1].content).toBe('Supervisor first');
+ expect(result.messages[2].role).toBe('assistant');
+ expect(result.messages[2].content).toBe('Agent response');
+ expect(result.messages[3].role).toBe('assistant');
+ expect(result.messages[3].content).toBe('Supervisor second');
+ });
+
+ it('should track processed count in metadata', async () => {
+ const processor = new SupervisorRoleRestoreProcessor();
+ const context = createContext([
+ { content: 'User', role: 'user' },
+ { content: 'Supervisor 1', role: 'supervisor' },
+ { content: 'Supervisor 2', role: 'supervisor' },
+ ]);
+
+ const result = await processor.process(context);
+
+ expect(result.metadata.supervisorRoleRestoreProcessed).toBe(2);
+ });
+
+ it('should preserve other message properties', async () => {
+ const processor = new SupervisorRoleRestoreProcessor();
+ const context = createContext([
+ {
+ agentId: 'agt_supervisor',
+ content: 'Supervisor response',
+ metadata: { isSupervisor: true },
+ model: 'gpt-4',
+ role: 'supervisor',
+ },
+ ]);
+
+ const result = await processor.process(context);
+
+ expect(result.messages[0].role).toBe('assistant');
+ expect(result.messages[0].agentId).toBe('agt_supervisor');
+ expect(result.messages[0].metadata).toEqual({ isSupervisor: true });
+ expect(result.messages[0].model).toBe('gpt-4');
+ expect(result.messages[0].content).toBe('Supervisor response');
+ });
+
+ it('should handle empty messages array', async () => {
+ const processor = new SupervisorRoleRestoreProcessor();
+ const context = createContext([]);
+
+ const result = await processor.process(context);
+
+ expect(result.messages).toHaveLength(0);
+ expect(result.metadata.supervisorRoleRestoreProcessed).toBe(0);
+ });
+
+ it('should handle messages with no supervisor role', async () => {
+ const processor = new SupervisorRoleRestoreProcessor();
+ const context = createContext([
+ { content: 'User', role: 'user' },
+ { content: 'Assistant', role: 'assistant' },
+ ]);
+
+ const result = await processor.process(context);
+
+ expect(result.messages).toHaveLength(2);
+ expect(result.metadata.supervisorRoleRestoreProcessed).toBe(0);
+ });
+});
diff --git a/packages/context-engine/src/processors/__tests__/TaskMessage.test.ts b/packages/context-engine/src/processors/__tests__/TaskMessage.test.ts
new file mode 100644
index 00000000000..963d8523e4d
--- /dev/null
+++ b/packages/context-engine/src/processors/__tests__/TaskMessage.test.ts
@@ -0,0 +1,247 @@
+import { describe, expect, it } from 'vitest';
+
+import { PipelineContext } from '../../types';
+import { TaskMessageProcessor } from '../TaskMessage';
+
+describe('TaskMessageProcessor', () => {
+ const createContext = (messages: any[]): PipelineContext => ({
+ initialState: { messages: [] },
+ isAborted: false,
+ messages,
+ metadata: {},
+ });
+
+ describe('basic functionality', () => {
+ it('should convert task message with instruction to assistant message', async () => {
+ const processor = new TaskMessageProcessor();
+ const context = createContext([
+ {
+ id: 'msg-1',
+ role: 'task',
+ content: 'Task completed successfully',
+ metadata: {
+ instruction: 'Search for information about AI',
+ },
+ agentName: 'Research Agent',
+ },
+ ]);
+
+ const result = await processor.process(context);
+
+ expect(result.messages).toHaveLength(1);
+ expect(result.messages[0].role).toBe('assistant');
+ expect(result.messages[0].content).toContain('Research Agent');
+ expect(result.messages[0].content).toContain('Search for information about AI');
+ expect(result.messages[0].content).toContain('Task completed successfully');
+ expect(result.metadata.taskMessagesProcessed).toBe(1);
+ });
+
+ it('should convert task message without instruction to assistant message', async () => {
+ const processor = new TaskMessageProcessor();
+ const context = createContext([
+ {
+ id: 'msg-1',
+ role: 'task',
+ content: 'Simple result',
+ },
+ ]);
+
+ const result = await processor.process(context);
+
+ expect(result.messages).toHaveLength(1);
+ expect(result.messages[0].role).toBe('assistant');
+ expect(result.messages[0].content).toBe('Simple result');
+ expect(result.metadata.taskMessagesProcessed).toBe(1);
+ });
+
+ it('should not modify non-task messages', async () => {
+ const processor = new TaskMessageProcessor();
+ const context = createContext([
+ { id: 'msg-1', role: 'user', content: 'Hello' },
+ { id: 'msg-2', role: 'assistant', content: 'Hi there' },
+ {
+ id: 'msg-3',
+ role: 'task',
+ content: 'Task result',
+ metadata: { instruction: 'Do something' },
+ agentName: 'Test Agent',
+ },
+ ]);
+
+ const result = await processor.process(context);
+
+ expect(result.messages).toHaveLength(3);
+ expect(result.messages[0].role).toBe('user');
+ expect(result.messages[0].content).toBe('Hello');
+ expect(result.messages[1].role).toBe('assistant');
+ expect(result.messages[1].content).toBe('Hi there');
+ expect(result.messages[2].role).toBe('assistant');
+ expect(result.messages[2].content).toContain('Test Agent');
+ expect(result.metadata.taskMessagesProcessed).toBe(1);
+ });
+ });
+
+ describe('template formatting', () => {
+ it('should use default template format', async () => {
+ const processor = new TaskMessageProcessor();
+ const context = createContext([
+ {
+ id: 'msg-1',
+ role: 'task',
+ content: 'Result content here',
+ metadata: { instruction: 'Instruction content here' },
+ agentName: 'My Agent',
+ },
+ ]);
+
+ const result = await processor.process(context);
+
+ expect(result.messages[0].content).toBe(
+ `[Task Result from My Agent]
+
+**Task Instruction:**
+Instruction content here
+
+**Task Result:**
+Result content here`,
+ );
+ });
+
+ it('should use custom template', async () => {
+ const customTemplate = '# {{agentName}}\nInstruction: {{instruction}}\nResult: {{content}}';
+ const processor = new TaskMessageProcessor({ template: customTemplate });
+ const context = createContext([
+ {
+ id: 'msg-1',
+ role: 'task',
+ content: 'Done',
+ metadata: { instruction: 'Do it' },
+ agentName: 'Agent X',
+ },
+ ]);
+
+ const result = await processor.process(context);
+
+ expect(result.messages[0].content).toBe('# Agent X\nInstruction: Do it\nResult: Done');
+ });
+
+ it('should use meta.avatar as fallback for agentName', async () => {
+ const processor = new TaskMessageProcessor();
+ const context = createContext([
+ {
+ id: 'msg-1',
+ role: 'task',
+ content: 'Result',
+ metadata: { instruction: 'Task' },
+ meta: { avatar: 'Avatar Name' },
+ },
+ ]);
+
+ const result = await processor.process(context);
+
+ expect(result.messages[0].content).toContain('Avatar Name');
+ });
+
+ it('should use default "Sub Agent" when no name available', async () => {
+ const processor = new TaskMessageProcessor();
+ const context = createContext([
+ {
+ id: 'msg-1',
+ role: 'task',
+ content: 'Result',
+ metadata: { instruction: 'Task' },
+ },
+ ]);
+
+ const result = await processor.process(context);
+
+ expect(result.messages[0].content).toContain('[Task Result from Sub Agent]');
+ });
+ });
+
+ describe('multiple task messages', () => {
+ it('should process multiple task messages', async () => {
+ const processor = new TaskMessageProcessor();
+ const context = createContext([
+ {
+ id: 'msg-1',
+ role: 'task',
+ content: 'Result 1',
+ metadata: { instruction: 'Task 1' },
+ agentName: 'Agent 1',
+ },
+ { id: 'msg-2', role: 'user', content: 'User message' },
+ {
+ id: 'msg-3',
+ role: 'task',
+ content: 'Result 2',
+ metadata: { instruction: 'Task 2' },
+ agentName: 'Agent 2',
+ },
+ ]);
+
+ const result = await processor.process(context);
+
+ expect(result.messages).toHaveLength(3);
+ expect(result.messages[0].role).toBe('assistant');
+ expect(result.messages[0].content).toContain('Agent 1');
+ expect(result.messages[1].role).toBe('user');
+ expect(result.messages[2].role).toBe('assistant');
+ expect(result.messages[2].content).toContain('Agent 2');
+ expect(result.metadata.taskMessagesProcessed).toBe(2);
+ });
+ });
+
+ describe('edge cases', () => {
+ it('should handle empty content', async () => {
+ const processor = new TaskMessageProcessor();
+ const context = createContext([
+ {
+ id: 'msg-1',
+ role: 'task',
+ content: '',
+ metadata: { instruction: 'Do something' },
+ agentName: 'Agent',
+ },
+ ]);
+
+ const result = await processor.process(context);
+
+ expect(result.messages[0].role).toBe('assistant');
+ expect(result.messages[0].content).toContain('Do something');
+ expect(result.messages[0].content).toContain('**Task Result:**\n');
+ });
+
+ it('should handle empty messages array', async () => {
+ const processor = new TaskMessageProcessor();
+ const context = createContext([]);
+
+ const result = await processor.process(context);
+
+ expect(result.messages).toHaveLength(0);
+ expect(result.metadata.taskMessagesProcessed).toBe(0);
+ });
+
+ it('should preserve other message properties', async () => {
+ const processor = new TaskMessageProcessor();
+ const context = createContext([
+ {
+ id: 'msg-1',
+ role: 'task',
+ content: 'Result',
+ metadata: { instruction: 'Task', customField: 'value' },
+ agentName: 'Agent',
+ createdAt: 1234567890,
+ extra: { foo: 'bar' },
+ },
+ ]);
+
+ const result = await processor.process(context);
+
+ expect(result.messages[0].id).toBe('msg-1');
+ expect(result.messages[0].createdAt).toBe(1234567890);
+ expect(result.messages[0].extra).toEqual({ foo: 'bar' });
+ expect(result.messages[0].metadata.customField).toBe('value');
+ });
+ });
+});
diff --git a/packages/context-engine/src/processors/index.ts b/packages/context-engine/src/processors/index.ts
index 39e384886ee..496a92ab2b8 100644
--- a/packages/context-engine/src/processors/index.ts
+++ b/packages/context-engine/src/processors/index.ts
@@ -1,16 +1,31 @@
// Transformer processors
+export { AgentCouncilFlattenProcessor } from './AgentCouncilFlatten';
export { GroupMessageFlattenProcessor } from './GroupMessageFlatten';
+export { GroupMessageSenderProcessor } from './GroupMessageSender';
export { HistoryTruncateProcessor } from './HistoryTruncate';
export { InputTemplateProcessor } from './InputTemplate';
export { MessageCleanupProcessor } from './MessageCleanup';
export { MessageContentProcessor } from './MessageContent';
-export { PlaceholderVariablesProcessor } from './PlaceholderVariables';
+export {
+ buildPlaceholderGenerators,
+ formatPlaceholderValues,
+ PlaceholderVariablesProcessor,
+ renderPlaceholderTemplate,
+} from './PlaceholderVariables';
+export { SupervisorRoleRestoreProcessor } from './SupervisorRoleRestore';
+export { TaskMessageProcessor } from './TaskMessage';
export { ToolCallProcessor } from './ToolCall';
export { ToolMessageReorder } from './ToolMessageReorder';
// Re-export types
+export type { AgentInfo, GroupMessageSenderConfig } from './GroupMessageSender';
export type { HistoryTruncateConfig } from './HistoryTruncate';
export type { InputTemplateConfig } from './InputTemplate';
export type { MessageContentConfig, UserMessageContentPart } from './MessageContent';
-export type { PlaceholderVariablesConfig } from './PlaceholderVariables';
+export type {
+ PlaceholderValue,
+ PlaceholderValueMap,
+ PlaceholderVariablesConfig,
+} from './PlaceholderVariables';
+export type { TaskMessageConfig } from './TaskMessage';
export type { ToolCallConfig } from './ToolCall';
diff --git a/packages/context-engine/src/providers/AgentBuilderContextInjector.ts b/packages/context-engine/src/providers/AgentBuilderContextInjector.ts
new file mode 100644
index 00000000000..b3a3eea0999
--- /dev/null
+++ b/packages/context-engine/src/providers/AgentBuilderContextInjector.ts
@@ -0,0 +1,253 @@
+import debug from 'debug';
+
+import { BaseProvider } from '../base/BaseProvider';
+import type { PipelineContext, ProcessorOptions } from '../types';
+
+const log = debug('context-engine:provider:AgentBuilderContextInjector');
+
+/**
+ * Escape XML special characters
+ */
+const escapeXml = (str: string): string => {
+ return str
+ .replaceAll('&', '&amp;')
+ .replaceAll('<', '&lt;')
+ .replaceAll('>', '&gt;')
+ .replaceAll('"', '&quot;')
+ .replaceAll("'", '&apos;');
+};
+
+/**
+ * Official tool item for Agent Builder context
+ */
+export interface OfficialToolItem {
+ /** Tool description */
+ description?: string;
+ /** Whether the tool is enabled for current agent */
+ enabled?: boolean;
+ /** Tool identifier */
+ identifier: string;
+ /** Whether the tool is installed/connected */
+ installed?: boolean;
+ /** Tool display name */
+ name: string;
+ /** Tool type: 'builtin' for built-in tools, 'klavis' for LobeHub Mcp servers */
+ type: 'builtin' | 'klavis';
+}
+
+/**
+ * Agent context for Agent Builder
+ */
+export interface AgentBuilderContext {
+ /** Agent configuration */
+ config?: {
+ chatConfig?: Record<string, any>;
+ model?: string;
+ openingMessage?: string;
+ openingQuestions?: string[];
+ params?: Record<string, any>;
+ plugins?: string[];
+ provider?: string;
+ systemRole?: string;
+ };
+ /** Agent metadata */
+ meta?: {
+ avatar?: string;
+ backgroundColor?: string;
+ description?: string;
+ tags?: string[];
+ title?: string;
+ };
+ /** Available official tools (builtin tools and Klavis integrations) */
+ officialTools?: OfficialToolItem[];
+}
+
+export interface AgentBuilderContextInjectorConfig {
+ /** Agent context to inject */
+ agentContext?: AgentBuilderContext;
+ /** Whether Agent Builder is enabled */
+ enabled?: boolean;
+ /** Function to format agent context */
+ formatAgentContext?: (context: AgentBuilderContext) => string;
+}
+
+/**
+ * Format agent context as XML for injection
+ */
+const defaultFormatAgentContext = (context: AgentBuilderContext): string => {
+ const parts: string[] = [];
+
+ // Add meta section
+ if (context.meta) {
+ const metaFields: string[] = [];
+ if (context.meta.title) metaFields.push(` <title>${escapeXml(context.meta.title)}</title>`);
+ if (context.meta.description)
+ metaFields.push(` <description>${escapeXml(context.meta.description)}</description>`);
+ if (context.meta.avatar)
+ metaFields.push(` <avatar>${escapeXml(context.meta.avatar)}</avatar>`);
+ if (context.meta.backgroundColor)
+ metaFields.push(` <backgroundColor>${context.meta.backgroundColor}</backgroundColor>`);
+ if (context.meta.tags && context.meta.tags.length > 0)
+ metaFields.push(` <tags>${context.meta.tags.join(', ')}</tags>`);
+
+ if (metaFields.length > 0) {
+ parts.push(`<agent_meta>\n${metaFields.join('\n')}\n</agent_meta>`);
+ }
+ }
+
+ // Add config section
+ if (context.config) {
+ const configFields: string[] = [];
+ if (context.config.model)
+ configFields.push(
+ ` <model provider="${context.config.provider || 'unknown'}">${context.config.model}</model>`,
+ );
+ if (context.config.plugins && context.config.plugins.length > 0)
+ configFields.push(
+ ` <enabled_plugins>${context.config.plugins.join(', ')}</enabled_plugins>`,
+ );
+ if (context.config.openingMessage)
+ configFields.push(
+ ` <openingMessage>${escapeXml(context.config.openingMessage)}</openingMessage>`,
+ );
+ if (context.config.openingQuestions && context.config.openingQuestions.length > 0) {
+ const questions = context.config.openingQuestions
+ .map((q) => ` <question>${escapeXml(q)}</question>`)
+ .join('\n');
+ configFields.push(` <openingQuestions>\n${questions}\n </openingQuestions>`);
+ }
+ if (context.config.systemRole) {
+ // For system role, show preview (first 500 chars) to avoid too long context
+ const preview =
+ context.config.systemRole.length > 500
+ ? context.config.systemRole.slice(0, 500) + '...'
+ : context.config.systemRole;
+ configFields.push(
+ ` <systemRole length="${context.config.systemRole.length}">${escapeXml(preview)}</systemRole>`,
+ );
+ }
+
+ if (configFields.length > 0) {
+ parts.push(`<agent_config>\n${configFields.join('\n')}\n</agent_config>`);
+ }
+ }
+
+ // Add official tools section
+ if (context.officialTools && context.officialTools.length > 0) {
+ const builtinTools = context.officialTools.filter((t) => t.type === 'builtin');
+ const klavisTools = context.officialTools.filter((t) => t.type === 'klavis');
+
+ const toolsSections: string[] = [];
+
+ if (builtinTools.length > 0) {
+ const builtinItems = builtinTools
+ .map((t) => {
+ const attrs = [`id="${t.identifier}"`, `enabled="${t.enabled ? 'true' : 'false'}"`].join(
+ ' ',
+ );
+ const desc = t.description ? ` - ${escapeXml(t.description)}` : '';
+ return ` <tool ${attrs}>${escapeXml(t.name)}${desc}</tool>`;
+ })
+ .join('\n');
+ toolsSections.push(` <builtin_tools>\n${builtinItems}\n </builtin_tools>`);
+ }
+
+ if (klavisTools.length > 0) {
+ const klavisItems = klavisTools
+ .map((t) => {
+ const attrs = [
+ `id="${t.identifier}"`,
+ `installed="${t.installed ? 'true' : 'false'}"`,
+ `enabled="${t.enabled ? 'true' : 'false'}"`,
+ ].join(' ');
+ const desc = t.description ? ` - ${escapeXml(t.description)}` : '';
+ return ` <tool ${attrs}>${escapeXml(t.name)}${desc}</tool>`;
+ })
+ .join('\n');
+ toolsSections.push(` <klavis_tools>\n${klavisItems}\n </klavis_tools>`);
+ }
+
+ if (toolsSections.length > 0) {
+ parts.push(
+ `<available_official_tools>\n${toolsSections.join('\n')}\n</available_official_tools>`,
+ );
+ }
+ }
+
+ if (parts.length === 0) {
+ return '';
+ }
+
+ return `<current_agent_context>
+<instruction>This is the current agent's configuration context. Use this information when the user asks about or wants to modify agent settings. Use togglePlugin to enable/disable tools, or installPlugin to install new tools.</instruction>
+${parts.join('\n')}
+</current_agent_context>`;
+};
+
+/**
+ * Agent Builder Context Injector
+ * Responsible for injecting current agent context when Agent Builder tool is enabled
+ */
+export class AgentBuilderContextInjector extends BaseProvider {
+ readonly name = 'AgentBuilderContextInjector';
+
+ constructor(
+ private config: AgentBuilderContextInjectorConfig,
+ options: ProcessorOptions = {},
+ ) {
+ super(options);
+ }
+
+ protected async doProcess(context: PipelineContext): Promise<PipelineContext> {
+ const clonedContext = this.cloneContext(context);
+
+ // Skip if Agent Builder is not enabled
+ if (!this.config.enabled) {
+ log('Agent Builder not enabled, skipping injection');
+ return this.markAsExecuted(clonedContext);
+ }
+
+ // Skip if no agent context
+ if (!this.config.agentContext) {
+ log('No agent context provided, skipping injection');
+ return this.markAsExecuted(clonedContext);
+ }
+
+ // Format agent context
+ const formatFn = this.config.formatAgentContext || defaultFormatAgentContext;
+ const formattedContent = formatFn(this.config.agentContext);
+
+ // Skip if no content to inject
+ if (!formattedContent) {
+ log('No content to inject after formatting');
+ return this.markAsExecuted(clonedContext);
+ }
+
+ // Find the first user message index
+ const firstUserIndex = clonedContext.messages.findIndex((msg) => msg.role === 'user');
+
+ if (firstUserIndex === -1) {
+ log('No user messages found, skipping injection');
+ return this.markAsExecuted(clonedContext);
+ }
+
+ // Insert a new user message with agent context before the first user message
+ const agentContextMessage = {
+ content: formattedContent,
+ createdAt: Date.now(),
+ id: `agent-builder-context-${Date.now()}`,
+ meta: { injectType: 'agent-builder-context', systemInjection: true },
+ role: 'user' as const,
+ updatedAt: Date.now(),
+ };
+
+ clonedContext.messages.splice(firstUserIndex, 0, agentContextMessage);
+
+ // Update metadata
+ clonedContext.metadata.agentBuilderContextInjected = true;
+
+ log('Agent Builder context injected as new user message');
+
+ return this.markAsExecuted(clonedContext);
+ }
+}
diff --git a/packages/context-engine/src/providers/GroupAgentBuilderContextInjector.ts b/packages/context-engine/src/providers/GroupAgentBuilderContextInjector.ts
new file mode 100644
index 00000000000..3c1ed7ef9ad
--- /dev/null
+++ b/packages/context-engine/src/providers/GroupAgentBuilderContextInjector.ts
@@ -0,0 +1,312 @@
+import debug from 'debug';
+
+import { BaseProvider } from '../base/BaseProvider';
+import type { PipelineContext, ProcessorOptions } from '../types';
+
+const log = debug('context-engine:provider:GroupAgentBuilderContextInjector');
+
+/**
+ * Escape XML special characters
+ */
+const escapeXml = (str: string): string => {
+ return str
+ .replaceAll('&', '&amp;')
+ .replaceAll('<', '&lt;')
+ .replaceAll('>', '&gt;')
+ .replaceAll('"', '&quot;')
+ .replaceAll("'", '&apos;');
+};
+
+/**
+ * Group member info for Group Agent Builder context
+ */
+export interface GroupMemberItem {
+ /** Member's avatar */
+ avatar?: string;
+ /** Member's description */
+ description?: string;
+ /** Member ID */
+ id: string;
+ /** Whether this member is the supervisor */
+ isSupervisor?: boolean;
+ /** Member's display name */
+ title: string;
+}
+
+/**
+ * Official tool item for Group Agent Builder context
+ */
+export interface GroupOfficialToolItem {
+ /** Tool description */
+ description?: string;
+ /** Whether the tool is enabled for supervisor agent */
+ enabled?: boolean;
+ /** Tool identifier */
+ identifier: string;
+ /** Whether the tool is installed/connected */
+ installed?: boolean;
+ /** Tool display name */
+ name: string;
+ /** Tool type: 'builtin' for built-in tools, 'klavis' for LobeHub Mcp servers */
+ type: 'builtin' | 'klavis';
+}
+
+/**
+ * Group context for Group Agent Builder
+ */
+export interface GroupAgentBuilderContext {
+ /** Group configuration */
+ config?: {
+ /** Whether the supervisor is enabled */
+ enableSupervisor?: boolean;
+ /** Opening message shown when starting a new conversation */
+ openingMessage?: string;
+ /** Suggested opening questions */
+ openingQuestions?: string[];
+ /** Scene type */
+ scene?: string;
+ /** Group's system prompt */
+ systemPrompt?: string;
+ };
+ /** Group ID */
+ groupId?: string;
+ /** Group title */
+ groupTitle?: string;
+ /** Group members */
+ members?: GroupMemberItem[];
+ /** Available official tools (builtin tools and Klavis integrations) */
+ officialTools?: GroupOfficialToolItem[];
+ /** Supervisor agent configuration */
+ supervisorConfig?: {
+ /** Model being used */
+ model?: string;
+ /** Enabled plugins */
+ plugins?: string[];
+ /** Provider being used */
+ provider?: string;
+ };
+}
+
+export interface GroupAgentBuilderContextInjectorConfig {
+ /** Whether Group Agent Builder is enabled */
+ enabled?: boolean;
+ /** Function to format group context */
+ formatGroupContext?: (context: GroupAgentBuilderContext) => string;
+ /** Group context to inject */
+ groupContext?: GroupAgentBuilderContext;
+}
+
+/**
+ * Format group context as XML for injection
+ */
+const defaultFormatGroupContext = (context: GroupAgentBuilderContext): string => {
+ const parts: string[] = [];
+
+ // Add group meta section
+ if (context.groupId || context.groupTitle) {
+ const metaFields: string[] = [];
+ if (context.groupId) metaFields.push(` <id>${escapeXml(context.groupId)}</id>`);
+ if (context.groupTitle) metaFields.push(` <title>${escapeXml(context.groupTitle)}</title>`);
+
+ if (metaFields.length > 0) {
+ parts.push(`<group_meta>\n${metaFields.join('\n')}\n</group_meta>`);
+ }
+ }
+
+ // Add group config section
+ if (context.config) {
+ const configFields: string[] = [];
+ if (context.config.scene) {
+ configFields.push(` <scene>${escapeXml(context.config.scene)}</scene>`);
+ }
+ if (context.config.enableSupervisor !== undefined) {
+ configFields.push(
+ ` <enableSupervisor>${context.config.enableSupervisor ? 'true' : 'false'}</enableSupervisor>`,
+ );
+ }
+ if (context.config.systemPrompt) {
+ // For system prompt, show preview (first 500 chars) to avoid too long context
+ const preview =
+ context.config.systemPrompt.length > 500
+ ? context.config.systemPrompt.slice(0, 500) + '...'
+ : context.config.systemPrompt;
+ configFields.push(
+ ` <systemPrompt length="${context.config.systemPrompt.length}">${escapeXml(preview)}</systemPrompt>`,
+ );
+ }
+ if (context.config.openingMessage) {
+ configFields.push(
+ ` <openingMessage>${escapeXml(context.config.openingMessage)}</openingMessage>`,
+ );
+ }
+ if (context.config.openingQuestions && context.config.openingQuestions.length > 0) {
+ const questionsXml = context.config.openingQuestions
+ .map((q) => ` <question>${escapeXml(q)}</question>`)
+ .join('\n');
+ configFields.push(
+ ` <openingQuestions count="${context.config.openingQuestions.length}">\n${questionsXml}\n </openingQuestions>`,
+ );
+ }
+
+ if (configFields.length > 0) {
+ parts.push(`<group_config>\n${configFields.join('\n')}\n</group_config>`);
+ }
+ }
+
+ // Add supervisor config section
+ if (context.supervisorConfig) {
+ const supervisorFields: string[] = [];
+ if (context.supervisorConfig.model) {
+ supervisorFields.push(
+ ` <model provider="${context.supervisorConfig.provider || 'unknown'}">${context.supervisorConfig.model}</model>`,
+ );
+ }
+ if (context.supervisorConfig.plugins && context.supervisorConfig.plugins.length > 0) {
+ supervisorFields.push(
+ ` <enabled_plugins>${context.supervisorConfig.plugins.join(', ')}</enabled_plugins>`,
+ );
+ }
+
+ if (supervisorFields.length > 0) {
+ parts.push(
+ `<supervisor_agent_config>\n${supervisorFields.join('\n')}\n</supervisor_agent_config>`,
+ );
+ }
+ }
+
+ // Add members section
+ if (context.members && context.members.length > 0) {
+ const memberItems = context.members
+ .map((m) => {
+ const attrs = [
+ `id="${m.id}"`,
+ m.isSupervisor ? 'role="supervisor"' : 'role="participant"',
+ ].join(' ');
+ const desc = m.description ? ` - ${escapeXml(m.description)}` : '';
+ return ` <member ${attrs}>${escapeXml(m.title)}${desc}</member>`;
+ })
+ .join('\n');
+ parts.push(
+ `<group_members count="${context.members.length}">\n${memberItems}\n</group_members>`,
+ );
+ }
+
+ // Add official tools section
+ if (context.officialTools && context.officialTools.length > 0) {
+ const builtinTools = context.officialTools.filter((t) => t.type === 'builtin');
+ const klavisTools = context.officialTools.filter((t) => t.type === 'klavis');
+
+ const toolsSections: string[] = [];
+
+ if (builtinTools.length > 0) {
+ const builtinItems = builtinTools
+ .map((t) => {
+ const attrs = [`id="${t.identifier}"`, `enabled="${t.enabled ? 'true' : 'false'}"`].join(
+ ' ',
+ );
+ const desc = t.description ? ` - ${escapeXml(t.description)}` : '';
+ return ` <tool ${attrs}>${escapeXml(t.name)}${desc}</tool>`;
+ })
+ .join('\n');
+ toolsSections.push(` <builtin_tools>\n${builtinItems}\n </builtin_tools>`);
+ }
+
+ if (klavisTools.length > 0) {
+ const klavisItems = klavisTools
+ .map((t) => {
+ const attrs = [
+ `id="${t.identifier}"`,
+ `installed="${t.installed ? 'true' : 'false'}"`,
+ `enabled="${t.enabled ? 'true' : 'false'}"`,
+ ].join(' ');
+ const desc = t.description ? ` - ${escapeXml(t.description)}` : '';
+ return ` <tool ${attrs}>${escapeXml(t.name)}${desc}</tool>`;
+ })
+ .join('\n');
+ toolsSections.push(` <klavis_tools>\n${klavisItems}\n </klavis_tools>`);
+ }
+
+ if (toolsSections.length > 0) {
+ parts.push(
+ `<available_official_tools>\n${toolsSections.join('\n')}\n</available_official_tools>`,
+ );
+ }
+ }
+
+ if (parts.length === 0) {
+ return '';
+ }
+
+ return `<current_group_context>
+<instruction>This is the current group's configuration context. Use this information when the user asks about or wants to modify group settings. Use inviteAgent/removeAgent to manage members, updatePrompt to modify the group's system prompt, or updateGroupConfig to set opening message and opening questions.</instruction>
+${parts.join('\n')}
+</current_group_context>`;
+};
+
+/**
+ * Group Agent Builder Context Injector
+ * Responsible for injecting current group context when Group Agent Builder tool is enabled
+ */
+export class GroupAgentBuilderContextInjector extends BaseProvider {
+ readonly name = 'GroupAgentBuilderContextInjector';
+
+ constructor(
+ private config: GroupAgentBuilderContextInjectorConfig,
+ options: ProcessorOptions = {},
+ ) {
+ super(options);
+ }
+
+ protected async doProcess(context: PipelineContext): Promise<PipelineContext> {
+ const clonedContext = this.cloneContext(context);
+
+ // Skip if Group Agent Builder is not enabled
+ if (!this.config.enabled) {
+ log('Group Agent Builder not enabled, skipping injection');
+ return this.markAsExecuted(clonedContext);
+ }
+
+ // Skip if no group context
+ if (!this.config.groupContext) {
+ log('No group context provided, skipping injection');
+ return this.markAsExecuted(clonedContext);
+ }
+
+ // Format group context
+ const formatFn = this.config.formatGroupContext || defaultFormatGroupContext;
+ const formattedContent = formatFn(this.config.groupContext);
+
+ // Skip if no content to inject
+ if (!formattedContent) {
+ log('No content to inject after formatting');
+ return this.markAsExecuted(clonedContext);
+ }
+
+ // Find the first user message index
+ const firstUserIndex = clonedContext.messages.findIndex((msg) => msg.role === 'user');
+
+ if (firstUserIndex === -1) {
+ log('No user messages found, skipping injection');
+ return this.markAsExecuted(clonedContext);
+ }
+
+ // Insert a new user message with group context before the first user message
+ const groupContextMessage = {
+ content: formattedContent,
+ createdAt: Date.now(),
+ id: `group-agent-builder-context-${Date.now()}`,
+ meta: { injectType: 'group-agent-builder-context', systemInjection: true },
+ role: 'user' as const,
+ updatedAt: Date.now(),
+ };
+
+ clonedContext.messages.splice(firstUserIndex, 0, groupContextMessage);
+
+ // Update metadata
+ clonedContext.metadata.groupAgentBuilderContextInjected = true;
+
+ log('Group Agent Builder context injected as new user message');
+
+ return this.markAsExecuted(clonedContext);
+ }
+}
diff --git a/packages/context-engine/src/providers/GroupContextInjector.ts b/packages/context-engine/src/providers/GroupContextInjector.ts
new file mode 100644
index 00000000000..028d5ec9afe
--- /dev/null
+++ b/packages/context-engine/src/providers/GroupContextInjector.ts
@@ -0,0 +1,168 @@
+import {
+ type GroupContextMemberInfo,
+ formatGroupMembers,
+ groupContextTemplate,
+} from '@lobechat/prompts';
+import debug from 'debug';
+
+import { BaseProvider } from '../base/BaseProvider';
+import type { PipelineContext, ProcessorOptions } from '../types';
+
+const log = debug('context-engine:provider:GroupContextInjector');
+
+/**
+ * Group member info for context injection
+ * Re-export from @lobechat/prompts for convenience
+ */
+export type GroupMemberInfo = GroupContextMemberInfo;
+
+/**
+ * Configuration for GroupContextInjector
+ */
+export interface GroupContextInjectorConfig {
+ /**
+ * Current agent's ID (the one who will respond)
+ */
+ currentAgentId?: string;
+
+ /**
+ * Current agent's name
+ */
+ currentAgentName?: string;
+
+ /**
+ * Current agent's role
+ */
+ currentAgentRole?: 'supervisor' | 'participant';
+
+ /**
+ * Whether this is a group chat context
+ */
+ enabled?: boolean;
+
+ /**
+ * Group title/name
+ */
+ groupTitle?: string;
+
+ /**
+ * List of group members
+ */
+ members?: GroupMemberInfo[];
+
+ /**
+ * Custom system prompt/role description for the group
+ */
+ systemPrompt?: string;
+}
+
+/**
+ * Group Context Injector
+ *
+ * Responsible for injecting group context information into the system role
+ * for multi-agent group chat scenarios. This helps the model understand:
+ * - Its own identity within the group
+ * - The group composition and other members
+ * - Rules for handling system metadata
+ *
+ * The injector appends a GROUP CONTEXT block at the end of the system message,
+ * containing:
+ * - Agent's identity (name, role, ID)
+ * - Group info (name, member list)
+ * - Important rules about system metadata handling
+ *
+ * @example
+ * ```typescript
+ * const injector = new GroupContextInjector({
+ * enabled: true,
+ * currentAgentId: 'agt_xxx',
+ * currentAgentName: 'Weather Expert',
+ * currentAgentRole: 'participant',
+ * groupTitle: 'Writing Team',
+ * systemPrompt: 'A collaborative writing team for creating articles',
+ * members: [
+ * { id: 'agt_xxx', name: 'Weather Expert', role: 'participant' },
+ * { id: 'agt_yyy', name: 'Supervisor', role: 'supervisor' },
+ * ],
+ * });
+ * ```
+ */
+export class GroupContextInjector extends BaseProvider {
+ readonly name = 'GroupContextInjector';
+
+ constructor(
+ private config: GroupContextInjectorConfig,
+ options: ProcessorOptions = {},
+ ) {
+ super(options);
+ }
+
+ protected async doProcess(context: PipelineContext): Promise<PipelineContext> {
+ const clonedContext = this.cloneContext(context);
+
+ // Skip if not enabled or missing required config
+ if (!this.config.enabled) {
+ log('Group context injection disabled, skipping');
+ return this.markAsExecuted(clonedContext);
+ }
+
+ // Find the system message to append to
+ const systemMessageIndex = clonedContext.messages.findIndex((msg) => msg.role === 'system');
+
+ if (systemMessageIndex === -1) {
+ log('No system message found, skipping group context injection');
+ return this.markAsExecuted(clonedContext);
+ }
+
+ const systemMessage = clonedContext.messages[systemMessageIndex];
+ const groupContext = this.buildGroupContextBlock();
+
+ // Append group context to system message content
+ if (typeof systemMessage.content === 'string') {
+ clonedContext.messages[systemMessageIndex] = {
+ ...systemMessage,
+ content: systemMessage.content + groupContext,
+ };
+
+ log('Group context injected into system message');
+ }
+
+ // Update metadata
+ clonedContext.metadata.groupContextInjected = true;
+
+ return this.markAsExecuted(clonedContext);
+ }
+
+ /**
+ * Build the group context block to append to system message
+ * Uses template from @lobechat/prompts with direct variable replacement
+ */
+ private buildGroupContextBlock(): string {
+ const {
+ currentAgentId,
+ currentAgentName,
+ currentAgentRole,
+ groupTitle,
+ members,
+ systemPrompt,
+ } = this.config;
+
+ // Use formatGroupMembers from @lobechat/prompts
+ const membersText = members ? formatGroupMembers(members, currentAgentId) : '';
+
+ // Direct variable replacement on template
+ const groupContextContent = groupContextTemplate
+ .replace('{{AGENT_NAME}}', currentAgentName || '')
+ .replace('{{AGENT_ROLE}}', currentAgentRole || '')
+ .replace('{{AGENT_ID}}', currentAgentId || '')
+ .replace('{{GROUP_TITLE}}', groupTitle || '')
+ .replace('{{SYSTEM_PROMPT}}', systemPrompt || '')
+ .replace('{{GROUP_MEMBERS}}', membersText);
+
+ return `
+
+<group_context>
+${groupContextContent}
+</group_context>`;
+ }
+}
diff --git a/packages/context-engine/src/providers/PageEditorContextInjector.ts b/packages/context-engine/src/providers/PageEditorContextInjector.ts
new file mode 100644
index 00000000000..624328f6085
--- /dev/null
+++ b/packages/context-engine/src/providers/PageEditorContextInjector.ts
@@ -0,0 +1,360 @@
+import debug from 'debug';
+
+import { BaseLastUserContentProvider } from '../base/BaseLastUserContentProvider';
+import type { PipelineContext, ProcessorOptions } from '../types';
+
+const log = debug('context-engine:provider:PageEditorContextInjector');
+
+/**
+ * Escape XML special characters
+ */
+const escapeXml = (str: string): string => {
+ return str
+ .replaceAll('&', '&amp;')
+ .replaceAll('<', '&lt;')
+ .replaceAll('>', '&gt;')
+ .replaceAll('"', '&quot;')
+ .replaceAll("'", '&apos;');
+};
+
+/**
+ * Generate path-based node ID
+ */
+const generateNodeId = (path: number[]): string => {
+ return `node_${path.join('_')}`;
+};
+
+/**
+ * Convert Lexical JSON format to XML format with node IDs
+ * @param node - The Lexical node to convert
+ * @param depth - Current depth in the tree (for indentation)
+ * @param path - Path to this node (array of indices from root)
+ */
+const convertLexicalToXml = (node: any, depth = 0, path: number[] = []): string => {
+ if (!node) return '';
+
+ const indent = ' '.repeat(depth);
+
+ // Handle text nodes
+ if (node.type === 'text') {
+ const nodeId = generateNodeId(path);
+ const text = escapeXml(node.text || '');
+ return `${indent}<span id="${nodeId}">${text}</span>`;
+ }
+
+ // Handle root node
+ if (node.type === 'root') {
+ const children =
+ node.children
+ ?.map((child: any, index: number) => convertLexicalToXml(child, depth, [index]))
+ .join('\n') || '';
+ return `<root>\n${children}\n</root>`;
+ }
+
+ // Handle heading nodes
+ if (node.type === 'heading') {
+ const nodeId = generateNodeId(path);
+ const tag = node.tag || 'h1';
+ const children =
+ node.children
+ ?.map((child: any, index: number) =>
+ convertLexicalToXml(child, depth + 1, [...path, index]),
+ )
+ .join('\n') || '';
+ return `${indent}<${tag} id="${nodeId}">\n${children}\n${indent}</${tag}>`;
+ }
+
+ // Handle paragraph nodes
+ if (node.type === 'paragraph') {
+ const nodeId = generateNodeId(path);
+ const children =
+ node.children
+ ?.map((child: any, index: number) =>
+ convertLexicalToXml(child, depth + 1, [...path, index]),
+ )
+ .join('\n') || '';
+ return `${indent}<p id="${nodeId}">\n${children}\n${indent}</p>`;
+ }
+
+ // Handle list nodes
+ if (node.type === 'list') {
+ const nodeId = generateNodeId(path);
+ const tag = node.listType === 'bullet' || node.tag === 'ul' ? 'ul' : 'ol';
+ const children =
+ node.children
+ ?.map((child: any, index: number) =>
+ convertLexicalToXml(child, depth + 1, [...path, index]),
+ )
+ .join('\n') || '';
+ return `${indent}<${tag} id="${nodeId}">\n${children}\n${indent}</${tag}>`;
+ }
+
+ // Handle list item nodes
+ if (node.type === 'listitem') {
+ const nodeId = generateNodeId(path);
+ const children =
+ node.children
+ ?.map((child: any, index: number) =>
+ convertLexicalToXml(child, depth + 1, [...path, index]),
+ )
+ .join('\n') || '';
+ return `${indent}<li id="${nodeId}">\n${children}\n${indent}</li>`;
+ }
+
+ // Handle blockquote nodes
+ if (node.type === 'quote') {
+ const nodeId = generateNodeId(path);
+ const children =
+ node.children
+ ?.map((child: any, index: number) =>
+ convertLexicalToXml(child, depth + 1, [...path, index]),
+ )
+ .join('\n') || '';
+ return `${indent}<blockquote id="${nodeId}">\n${children}\n${indent}</blockquote>`;
+ }
+
+ // Handle code block nodes
+ if (node.type === 'code') {
+ const nodeId = generateNodeId(path);
+ const text = escapeXml(node.children?.map((c: any) => c.text || '').join('') || '');
+ return `${indent}<pre id="${nodeId}"><code>${text}</code></pre>`;
+ }
+
+ // Handle link nodes
+ if (node.type === 'link') {
+ const nodeId = generateNodeId(path);
+ const href = escapeXml(node.url || '');
+ const children =
+ node.children
+ ?.map((child: any, index: number) => convertLexicalToXml(child, depth, [...path, index]))
+ .join('') || '';
+ return `<a id="${nodeId}" href="${href}">${children}</a>`;
+ }
+
+ // Handle image nodes
+ if (node.type === 'image') {
+ const nodeId = generateNodeId(path);
+ const src = escapeXml(node.src || '');
+ const alt = escapeXml(node.altText || '');
+ return `${indent}<img id="${nodeId}" src="${src}" alt="${alt}" />`;
+ }
+
+ // Handle table nodes
+ if (node.type === 'table') {
+ const nodeId = generateNodeId(path);
+ const children =
+ node.children
+ ?.map((child: any, index: number) =>
+ convertLexicalToXml(child, depth + 1, [...path, index]),
+ )
+ .join('\n') || '';
+ return `${indent}<table id="${nodeId}">\n${children}\n${indent}</table>`;
+ }
+
+ // Handle table row nodes
+ if (node.type === 'tablerow') {
+ const nodeId = generateNodeId(path);
+ const children =
+ node.children
+ ?.map((child: any, index: number) =>
+ convertLexicalToXml(child, depth + 1, [...path, index]),
+ )
+ .join('\n') || '';
+ return `${indent}<tr id="${nodeId}">\n${children}\n${indent}</tr>`;
+ }
+
+ // Handle table cell nodes
+ if (node.type === 'tablecell') {
+ const nodeId = generateNodeId(path);
+ const children =
+ node.children
+ ?.map((child: any, index: number) =>
+ convertLexicalToXml(child, depth + 1, [...path, index]),
+ )
+ .join('\n') || '';
+ return `${indent}<td id="${nodeId}">\n${children}\n${indent}</td>`;
+ }
+
+ // Fallback for unknown nodes - just process children
+ if (node.children) {
+ return node.children
+ .map((child: any, index: number) => convertLexicalToXml(child, depth, [...path, index]))
+ .join('\n');
+ }
+
+ return '';
+};
+
+/**
+ * Page context for Page Editor
+ */
+export interface PageEditorContext {
+ /** Plain text content (for reference) */
+ content?: string;
+ /** Document/Page metadata */
+ document?: {
+ /** File type */
+ fileType?: string;
+ /** Document unique identifier */
+ id: string;
+ /** URL slug */
+ slug?: string;
+ /** Document title */
+ title?: string;
+ /** Total character count */
+ totalCharCount?: number;
+ /** Total line count */
+ totalLineCount?: number;
+ };
+ /** Editor data - the XML document structure */
+ editorData?: Record<string, any>;
+}
+
+export interface PageEditorContextInjectorConfig {
+ /** Whether Page Editor/Agent is enabled */
+ enabled?: boolean;
+ /** Function to format page context */
+ formatPageContext?: (context: PageEditorContext) => string;
+ /** Page context to inject */
+ pageContext?: PageEditorContext;
+}
+
+/**
+ * Format page context as XML for injection
+ */
+const defaultFormatPageContext = (context: PageEditorContext): string => {
+ const parts: string[] = [];
+
+ // Add document metadata section
+ if (context.document) {
+ const metaFields: string[] = [];
+ if (context.document.id) metaFields.push(` <id>${escapeXml(context.document.id)}</id>`);
+ if (context.document.title)
+ metaFields.push(` <title>${escapeXml(context.document.title)}</title>`);
+ if (context.document.slug)
+ metaFields.push(` <slug>${escapeXml(context.document.slug)}</slug>`);
+ if (context.document.fileType)
+ metaFields.push(` <fileType>${escapeXml(context.document.fileType)}</fileType>`);
+ if (context.document.totalCharCount !== undefined)
+ metaFields.push(` <totalCharCount>${context.document.totalCharCount}</totalCharCount>`);
+ if (context.document.totalLineCount !== undefined)
+ metaFields.push(` <totalLineCount>${context.document.totalLineCount}</totalLineCount>`);
+
+ if (metaFields.length > 0) {
+ parts.push(`<document_metadata>\n${metaFields.join('\n')}\n</document_metadata>`);
+ }
+ }
+
+ // Add editor data section (the XML document structure)
+ if (context.editorData) {
+ try {
+ // Convert Lexical JSON to XML format with node IDs
+ const xmlStructure = convertLexicalToXml(context.editorData.root);
+
+ // Log the conversion for debugging
+ const nodeCount = context.editorData.root?.children?.length || 0;
+ console.log(
+ '[PageEditorContextInjector] Converted Lexical to XML, root children count:',
+ nodeCount,
+ );
+ console.log('[PageEditorContextInjector] XML preview:', xmlStructure.slice(0, 500));
+
+ // Don't escape the XML since it's already properly formatted XML
+ // Just include it directly (not escaped) so the model can parse the structure
+ parts.push(`<document_structure>\n${xmlStructure}\n</document_structure>`);
+ } catch (error) {
+ log('Error converting editorData to XML:', error);
+ console.error('[PageEditorContextInjector] Error converting editorData:', error);
+ }
+ }
+
+ // Add content preview section (if available)
+ if (context.content) {
+ // Show preview (first 1000 chars) to avoid too long context
+ const preview =
+ context.content.length > 1000 ? context.content.slice(0, 1000) + '...' : context.content;
+ parts.push(
+ `<content_preview length="${context.content.length}">${escapeXml(preview)}</content_preview>`,
+ );
+ }
+
+ if (parts.length === 0) {
+ return '';
+ }
+
+ return `<instruction>This is the current page/document context. The document uses an XML-based structure with unique node IDs. Use the Document tools (initPage, editTitle, etc.) to read and modify the page content when the user asks.</instruction>
+${parts.join('\n')}`;
+};
+
+/**
+ * Page Editor Context Injector
+ * Responsible for injecting current page context at the end of the last user message
+ * This ensures the model receives the most up-to-date page/document state
+ */
+export class PageEditorContextInjector extends BaseLastUserContentProvider {
+ readonly name = 'PageEditorContextInjector';
+
+ constructor(
+ private config: PageEditorContextInjectorConfig,
+ options: ProcessorOptions = {},
+ ) {
+ super(options);
+ }
+
+ protected async doProcess(context: PipelineContext): Promise<PipelineContext> {
+ log('doProcess called');
+ log('config.enabled:', this.config.enabled);
+
+ const clonedContext = this.cloneContext(context);
+
+ // Skip if Page Editor is not enabled
+ if (!this.config.enabled) {
+ log('Page Editor not enabled, skipping injection');
+ return this.markAsExecuted(clonedContext);
+ }
+
+ // Skip if no page context
+ if (!this.config.pageContext) {
+ log('No page context provided, skipping injection');
+ return this.markAsExecuted(clonedContext);
+ }
+
+ // Format page context
+ const formatFn = this.config.formatPageContext || defaultFormatPageContext;
+ const formattedContent = formatFn(this.config.pageContext);
+
+ log('Formatted content length:', formattedContent.length);
+
+ // Skip if no content to inject
+ if (!formattedContent) {
+ log('No content to inject after formatting');
+ return this.markAsExecuted(clonedContext);
+ }
+
+ // Find the last user message index
+ const lastUserIndex = this.findLastUserMessageIndex(clonedContext.messages);
+
+ log('Last user message index:', lastUserIndex);
+
+ if (lastUserIndex === -1) {
+ log('No user messages found, skipping injection');
+ return this.markAsExecuted(clonedContext);
+ }
+
+ // Check if system context wrapper already exists
+ // If yes, only insert context block; if no, use full wrapper
+ const hasExistingWrapper = this.hasExistingSystemContext(clonedContext);
+ const contentToAppend = hasExistingWrapper
+ ? this.createContextBlock(formattedContent, 'current_page_context')
+ : this.wrapWithSystemContext(formattedContent, 'current_page_context');
+
+ this.appendToLastUserMessage(clonedContext, contentToAppend);
+
+ // Update metadata
+ clonedContext.metadata.pageEditorContextInjected = true;
+
+ log('Page Editor context appended to last user message');
+
+ return this.markAsExecuted(clonedContext);
+ }
+}
diff --git a/packages/context-engine/src/providers/UserMemoryInjector.ts b/packages/context-engine/src/providers/UserMemoryInjector.ts
new file mode 100644
index 00000000000..6fc534f8422
--- /dev/null
+++ b/packages/context-engine/src/providers/UserMemoryInjector.ts
@@ -0,0 +1,95 @@
+import { u } from 'unist-builder';
+import { toXml } from 'xast-util-to-xml';
+import type { Child } from 'xastscript';
+import { x } from 'xastscript';
+
+import { BaseProvider } from '../base/BaseProvider';
+import type { UserMemoryData } from '../engine/messages/types';
+import type { PipelineContext, ProcessorOptions } from '../types';
+
+export interface UserMemoryInjectorConfig {
+ /** When the memories were fetched */
+ fetchedAt?: number;
+ /** User memories data */
+ memories?: UserMemoryData;
+}
+
+export class UserMemoryInjector extends BaseProvider {
+ readonly name = 'UserMemoryInjector';
+
+ constructor(
+ private config: UserMemoryInjectorConfig,
+ options: ProcessorOptions = {},
+ ) {
+ super(options);
+ }
+
+ protected async doProcess(context: PipelineContext): Promise<PipelineContext> {
+ const { memories } = this.config;
+ if (!memories) return context;
+
+ const contextsCount = memories.contexts?.length || 0;
+ const experiencesCount = memories.experiences?.length || 0;
+ const preferencesCount = memories.preferences?.length || 0;
+ if (contextsCount + experiencesCount + preferencesCount === 0) return context;
+
+ const userMemoriesChildren: Child[] = [];
+ if (memories.contexts) {
+ memories.contexts.forEach((ctx) => {
+ userMemoriesChildren.push(
+ x('user_memories_context', { id: ctx.id || '' }, [
+ x('context_title', ctx.title || ''),
+ x('context_description', ctx.description || ''),
+ ]),
+ );
+ });
+ }
+ if (memories.experiences) {
+ memories.experiences.forEach((experience) => {
+ userMemoriesChildren.push(
+ x('user_memories_experience', { id: experience.id || '' }, [
+ x('experience_situation', experience.situation || ''),
+ x('experience_key_learning', experience.keyLearning || ''),
+ ]),
+ );
+ });
+ }
+ if (memories.preferences) {
+ memories.preferences.forEach((preference) => {
+ userMemoriesChildren.push(
+ x('user_memories_preference', { id: preference.id || '' }, [
+ x('preference_conclusion_directives', preference.conclusionDirectives || ''),
+ ]),
+ );
+ });
+ }
+
+ const memoryMessage = {
+ content: toXml(
+ u('root', [
+ x(
+ 'user_memories',
+ {
+ contexts: contextsCount.toString(),
+ experiences: experiencesCount.toString(),
+ memory_fetched_at: new Date(this.config.fetchedAt || Date.now()).toISOString(),
+ preferences: preferencesCount.toString(),
+ },
+ ...userMemoriesChildren,
+ ),
+ ]),
+ ),
+ createdAt: Date.now(),
+ id: `user-memory-${Date.now()}`,
+ meta: { source: 'userMemory' },
+ role: 'system' as const,
+ updatedAt: Date.now(),
+ };
+
+ const clonedContext = this.cloneContext(context);
+ clonedContext.messages.unshift(memoryMessage);
+ clonedContext.metadata.userMemoryInjected = true;
+
+ return this.markAsExecuted(clonedContext);
+ }
+}
diff --git a/packages/context-engine/src/providers/__tests__/GroupContextInjector.test.ts b/packages/context-engine/src/providers/__tests__/GroupContextInjector.test.ts
new file mode 100644
index 00000000000..d941e368e00
--- /dev/null
+++ b/packages/context-engine/src/providers/__tests__/GroupContextInjector.test.ts
@@ -0,0 +1,225 @@
+import { describe, expect, it } from 'vitest';
+
+import type { PipelineContext } from '../../types';
+import { GroupContextInjector } from '../GroupContextInjector';
+
+describe('GroupContextInjector', () => {
+ const createContext = (messages: any[]): PipelineContext => ({
+ initialState: { messages: [] },
+ isAborted: false,
+ messages,
+ metadata: {},
+ });
+
+ describe('Basic Scenarios', () => {
+ it('should inject group context into system message', async () => {
+ const injector = new GroupContextInjector({
+ currentAgentId: 'agt_editor',
+ currentAgentName: 'Editor',
+ currentAgentRole: 'participant',
+ enabled: true,
+ groupTitle: 'Writing Team',
+ members: [
+ { id: 'agt_supervisor', name: 'Supervisor', role: 'supervisor' },
+ { id: 'agt_writer', name: 'Writer', role: 'participant' },
+ { id: 'agt_editor', name: 'Editor', role: 'participant' },
+ ],
+ systemPrompt: 'A team for collaborative writing',
+ });
+
+ const input: any[] = [
+ { role: 'system', content: 'You are a helpful editor.' },
+ { role: 'user', content: 'Please review this.' },
+ ];
+
+ const context = createContext(input);
+ const result = await injector.process(context);
+
+ const systemContent = result.messages[0].content;
+
+ // Original content should be preserved
+ expect(systemContent).toContain('You are a helpful editor.');
+
+ // Agent identity (plain text, no wrapper)
+ expect(systemContent).toContain('You are "Editor"');
+ expect(systemContent).toContain('acting as a participant');
+ expect(systemContent).toContain('"Writing Team"');
+ expect(systemContent).toContain('agt_editor');
+ expect(systemContent).not.toContain('<agent_identity>');
+
+ // Group context section with system prompt
+ expect(systemContent).toContain('<group_context>');
+ expect(systemContent).toContain('A team for collaborative writing');
+
+ // Participants section with XML format
+ expect(systemContent).toContain('<group_participants>');
+ expect(systemContent).toContain('<member name="Supervisor" id="agt_supervisor" />');
+ expect(systemContent).toContain('<member name="Writer" id="agt_writer" />');
+ expect(systemContent).toContain('<member name="Editor" id="agt_editor" you="true" />');
+
+ // Output rules section (important for LOBE-1866)
+ expect(systemContent).toContain('<critical_output_rules>');
+ expect(systemContent).toContain('<group_context>');
+ expect(systemContent).toContain('NEVER start your response with');
+
+ // Identity rules
+ expect(systemContent).toContain('<identity_rules>');
+ expect(systemContent).toContain('NEVER expose or display agent IDs');
+
+ // Metadata should be updated
+ expect(result.metadata.groupContextInjected).toBe(true);
+ });
+
+ it('should skip injection when disabled', async () => {
+ const injector = new GroupContextInjector({
+ currentAgentId: 'agt_editor',
+ currentAgentName: 'Editor',
+ enabled: false, // Disabled
+ });
+
+ const input: any[] = [{ role: 'system', content: 'You are a helpful editor.' }];
+
+ const context = createContext(input);
+ const result = await injector.process(context);
+
+ // Should be unchanged
+ expect(result.messages[0].content).toBe('You are a helpful editor.');
+ expect(result.metadata.groupContextInjected).toBeUndefined();
+ });
+
+ it('should skip injection when no system message exists', async () => {
+ const injector = new GroupContextInjector({
+ currentAgentId: 'agt_editor',
+ currentAgentName: 'Editor',
+ enabled: true,
+ });
+
+ const input: any[] = [
+ { role: 'user', content: 'Hello' },
+ { role: 'assistant', content: 'Hi there!' },
+ ];
+
+ const context = createContext(input);
+ const result = await injector.process(context);
+
+ // Messages should be unchanged
+ expect(result.messages[0].content).toBe('Hello');
+ expect(result.messages[1].content).toBe('Hi there!');
+ expect(result.metadata.groupContextInjected).toBeUndefined();
+ });
+ });
+
+ describe('Variable Replacement', () => {
+ it('should handle config with only identity info', async () => {
+ const injector = new GroupContextInjector({
+ currentAgentId: 'agt_editor',
+ currentAgentName: 'Editor',
+ currentAgentRole: 'participant',
+ enabled: true,
+ });
+
+ const input: any[] = [{ content: 'You are an editor.', role: 'system' }];
+
+ const context = createContext(input);
+ const result = await injector.process(context);
+
+ expect(result.messages[0].content).toMatchSnapshot();
+ });
+
+ it('should handle config with only group info', async () => {
+ const injector = new GroupContextInjector({
+ enabled: true,
+ groupTitle: 'Test Group',
+ members: [{ id: 'agt_1', name: 'Agent 1', role: 'participant' }],
+ systemPrompt: 'Test group description',
+ });
+
+ const input: any[] = [{ content: 'System prompt.', role: 'system' }];
+
+ const context = createContext(input);
+ const result = await injector.process(context);
+
+ expect(result.messages[0].content).toMatchSnapshot();
+ });
+
+ it('should handle empty config', async () => {
+ const injector = new GroupContextInjector({
+ enabled: true,
+ });
+
+ const input: any[] = [{ content: 'Base prompt.', role: 'system' }];
+
+ const context = createContext(input);
+ const result = await injector.process(context);
+
+ expect(result.messages[0].content).toMatchSnapshot();
+ });
+ });
+
+ describe('Output Rules Section (LOBE-1866)', () => {
+ it('should always include critical output rules', async () => {
+ const injector = new GroupContextInjector({
+ enabled: true,
+ // Minimal config
+ });
+
+ const input: any[] = [{ role: 'system', content: 'Base prompt.' }];
+
+ const context = createContext(input);
+ const result = await injector.process(context);
+
+ const systemContent = result.messages[0].content;
+
+ // Even with minimal config, critical output rules should be present
+ expect(systemContent).toContain('<critical_output_rules>');
+ expect(systemContent).toContain('Your responses must contain ONLY your actual reply content');
+ expect(systemContent).toContain('NEVER start your response with');
+ expect(systemContent).toContain('<speaker');
+
+ // Identity rules should also be present
+ expect(systemContent).toContain('<identity_rules>');
+ expect(systemContent).toContain('NEVER expose or display agent IDs');
+ });
+ });
+
+ describe('Edge Cases', () => {
+ it('should handle empty members array', async () => {
+ const injector = new GroupContextInjector({
+ enabled: true,
+ groupTitle: 'Empty Group',
+ members: [],
+ systemPrompt: 'Empty group description',
+ });
+
+ const input: any[] = [{ content: 'Prompt.', role: 'system' }];
+
+ const context = createContext(input);
+ const result = await injector.process(context);
+
+ expect(result.messages[0].content).toMatchSnapshot();
+ });
+
+ it('should preserve other messages unchanged', async () => {
+ const injector = new GroupContextInjector({
+ currentAgentId: 'agt_1',
+ currentAgentName: 'Agent 1',
+ enabled: true,
+ groupTitle: 'Test Group',
+ });
+
+ const input: any[] = [
+ { role: 'system', content: 'System prompt.' },
+ { role: 'user', content: 'User message.' },
+ { role: 'assistant', content: 'Assistant response.' },
+ ];
+
+ const context = createContext(input);
+ const result = await injector.process(context);
+
+ // Only system message should be modified
+ expect(result.messages[0].content).toContain('<group_context>');
+ expect(result.messages[1].content).toBe('User message.');
+ expect(result.messages[2].content).toBe('Assistant response.');
+ });
+ });
+});
diff --git a/packages/context-engine/src/providers/__tests__/PageEditorContextInjector.test.ts b/packages/context-engine/src/providers/__tests__/PageEditorContextInjector.test.ts
new file mode 100644
index 00000000000..d6ce133c525
--- /dev/null
+++ b/packages/context-engine/src/providers/__tests__/PageEditorContextInjector.test.ts
@@ -0,0 +1,292 @@
+import { describe, expect, it } from 'vitest';
+
+import type { PipelineContext } from '../../types';
+import { type PageEditorContext, PageEditorContextInjector } from '../PageEditorContextInjector';
+
+describe('PageEditorContextInjector', () => {
+ const createContext = (messages: any[] = []): PipelineContext => ({
+ initialState: {
+ messages: [],
+ model: 'test-model',
+ provider: 'test-provider',
+ },
+ isAborted: false,
+ messages,
+ metadata: {
+ maxTokens: 4000,
+ model: 'test-model',
+ },
+ });
+
+ // Minimal page context for predictable output
+ const createMinimalPageContext = (): PageEditorContext => ({
+ content: 'Doc content',
+ });
+
+ describe('injection position', () => {
+ it('should append context to the last user message', async () => {
+ const injector = new PageEditorContextInjector({
+ enabled: true,
+ pageContext: createMinimalPageContext(),
+ });
+
+ const context = createContext([
+ { content: 'First question', role: 'user' },
+ { content: 'First answer', role: 'assistant' },
+ { content: 'Second question', role: 'user' },
+ ]);
+
+ const result = await injector.process(context);
+
+ expect(result.messages).toHaveLength(3);
+ expect(result.messages[0].content).toBe('First question');
+ expect(result.messages[1].content).toBe('First answer');
+ expect(result.messages[2].content).toBe(`Second question
+
+<!-- SYSTEM CONTEXT (NOT PART OF USER QUERY) -->
+<context.instruction>following part contains context information injected by the system. Please follow these instructions:
+
+1. Always prioritize handling user-visible content.
+2. the context is only required when user's queries rely on it.
+</context.instruction>
+<current_page_context>
+<instruction>This is the current page/document context. The document uses an XML-based structure with unique node IDs. Use the Document tools (initPage, editTitle, etc.) to read and modify the page content when the user asks.</instruction>
+<content_preview length="11">Doc content</content_preview>
+</current_page_context>
+<!-- END SYSTEM CONTEXT -->`);
+ });
+
+ it('should append to the only user message when there is just one', async () => {
+ const injector = new PageEditorContextInjector({
+ enabled: true,
+ pageContext: createMinimalPageContext(),
+ });
+
+ const context = createContext([{ content: 'Only question', role: 'user' }]);
+
+ const result = await injector.process(context);
+
+ expect(result.messages).toHaveLength(1);
+ expect(result.messages[0].content).toBe(`Only question
+
+<!-- SYSTEM CONTEXT (NOT PART OF USER QUERY) -->
+<context.instruction>following part contains context information injected by the system. Please follow these instructions:
+
+1. Always prioritize handling user-visible content.
+2. the context is only required when user's queries rely on it.
+</context.instruction>
+<current_page_context>
+<instruction>This is the current page/document context. The document uses an XML-based structure with unique node IDs. Use the Document tools (initPage, editTitle, etc.) to read and modify the page content when the user asks.</instruction>
+<content_preview length="11">Doc content</content_preview>
+</current_page_context>
+<!-- END SYSTEM CONTEXT -->`);
+ });
+ });
+
+ describe('injection format with document metadata', () => {
+ it('should include document metadata in injection', async () => {
+ const injector = new PageEditorContextInjector({
+ enabled: true,
+ pageContext: {
+ document: {
+ id: 'doc-456',
+ title: 'My Title',
+ },
+ },
+ });
+
+ const context = createContext([{ content: 'Question', role: 'user' }]);
+ const result = await injector.process(context);
+
+ expect(result.messages[0].content).toBe(`Question
+
+<!-- SYSTEM CONTEXT (NOT PART OF USER QUERY) -->
+<context.instruction>following part contains context information injected by the system. Please follow these instructions:
+
+1. Always prioritize handling user-visible content.
+2. the context is only required when user's queries rely on it.
+</context.instruction>
+<current_page_context>
+<instruction>This is the current page/document context. The document uses an XML-based structure with unique node IDs. Use the Document tools (initPage, editTitle, etc.) to read and modify the page content when the user asks.</instruction>
+<document_metadata>
+ <id>doc-456</id>
+ <title>My Title</title>
+</document_metadata>
+</current_page_context>
+<!-- END SYSTEM CONTEXT -->`);
+ });
+
+ it('should include full document metadata', async () => {
+ const injector = new PageEditorContextInjector({
+ enabled: true,
+ pageContext: {
+ document: {
+ id: 'doc-123',
+ title: 'Test',
+ slug: 'test-slug',
+ fileType: 'md',
+ totalCharCount: 100,
+ totalLineCount: 10,
+ },
+ },
+ });
+
+ const context = createContext([{ content: 'Q', role: 'user' }]);
+ const result = await injector.process(context);
+
+ expect(result.messages[0].content).toBe(`Q
+
+<!-- SYSTEM CONTEXT (NOT PART OF USER QUERY) -->
+<context.instruction>following part contains context information injected by the system. Please follow these instructions:
+
+1. Always prioritize handling user-visible content.
+2. the context is only required when user's queries rely on it.
+</context.instruction>
+<current_page_context>
+<instruction>This is the current page/document context. The document uses an XML-based structure with unique node IDs. Use the Document tools (initPage, editTitle, etc.) to read and modify the page content when the user asks.</instruction>
+<document_metadata>
+ <id>doc-123</id>
+ <title>Test</title>
+ <slug>test-slug</slug>
+ <fileType>md</fileType>
+ <totalCharCount>100</totalCharCount>
+ <totalLineCount>10</totalLineCount>
+</document_metadata>
+</current_page_context>
+<!-- END SYSTEM CONTEXT -->`);
+ });
+ });
+
+ describe('skip conditions', () => {
+ it('should skip injection when disabled', async () => {
+ const injector = new PageEditorContextInjector({
+ enabled: false,
+ pageContext: createMinimalPageContext(),
+ });
+
+ const context = createContext([{ content: 'Question', role: 'user' }]);
+ const result = await injector.process(context);
+
+ expect(result.messages[0].content).toBe('Question');
+ expect(result.metadata.pageEditorContextInjected).toBeUndefined();
+ });
+
+ it('should skip injection when pageContext is not provided', async () => {
+ const injector = new PageEditorContextInjector({
+ enabled: true,
+ });
+
+ const context = createContext([{ content: 'Question', role: 'user' }]);
+ const result = await injector.process(context);
+
+ expect(result.messages[0].content).toBe('Question');
+ expect(result.metadata.pageEditorContextInjected).toBeUndefined();
+ });
+
+ it('should skip injection when no user messages exist', async () => {
+ const injector = new PageEditorContextInjector({
+ enabled: true,
+ pageContext: createMinimalPageContext(),
+ });
+
+ const context = createContext([{ content: 'System message', role: 'system' }]);
+ const result = await injector.process(context);
+
+ expect(result.messages).toHaveLength(1);
+ expect(result.messages[0].content).toBe('System message');
+ });
+
+ it('should skip injection when pageContext is empty', async () => {
+ const injector = new PageEditorContextInjector({
+ enabled: true,
+ pageContext: {},
+ });
+
+ const context = createContext([{ content: 'Question', role: 'user' }]);
+ const result = await injector.process(context);
+
+ expect(result.messages[0].content).toBe('Question');
+ });
+ });
+
+ describe('metadata', () => {
+ it('should set pageEditorContextInjected metadata to true', async () => {
+ const injector = new PageEditorContextInjector({
+ enabled: true,
+ pageContext: createMinimalPageContext(),
+ });
+
+ const context = createContext([{ content: 'Question', role: 'user' }]);
+ const result = await injector.process(context);
+
+ expect(result.metadata.pageEditorContextInjected).toBe(true);
+ });
+ });
+
+ describe('multimodal messages', () => {
+ it('should append to array content with text parts', async () => {
+ const injector = new PageEditorContextInjector({
+ enabled: true,
+ pageContext: createMinimalPageContext(),
+ });
+
+ const context = createContext([
+ {
+ content: [
+ { text: 'User question', type: 'text' },
+ { image_url: { url: 'http://example.com/image.png' }, type: 'image_url' },
+ ],
+ role: 'user',
+ },
+ ]);
+
+ const result = await injector.process(context);
+
+ expect(result.messages[0].content[0].text).toBe(`User question
+
+<!-- SYSTEM CONTEXT (NOT PART OF USER QUERY) -->
+<context.instruction>following part contains context information injected by the system. Please follow these instructions:
+
+1. Always prioritize handling user-visible content.
+2. the context is only required when user's queries rely on it.
+</context.instruction>
+<current_page_context>
+<instruction>This is the current page/document context. The document uses an XML-based structure with unique node IDs. Use the Document tools (initPage, editTitle, etc.) to read and modify the page content when the user asks.</instruction>
+<content_preview length="11">Doc content</content_preview>
+</current_page_context>
+<!-- END SYSTEM CONTEXT -->`);
+ expect(result.messages[0].content[1]).toEqual({
+ image_url: { url: 'http://example.com/image.png' },
+ type: 'image_url',
+ });
+ });
+ });
+
+ describe('custom formatPageContext', () => {
+ it('should use custom format function when provided', async () => {
+ const customFormat = (ctx: PageEditorContext) => `Custom: ${ctx.document?.title}`;
+
+ const injector = new PageEditorContextInjector({
+ enabled: true,
+ formatPageContext: customFormat,
+ pageContext: { document: { id: '1', title: 'Custom Title' } },
+ });
+
+ const context = createContext([{ content: 'Question', role: 'user' }]);
+ const result = await injector.process(context);
+
+ expect(result.messages[0].content).toBe(`Question
+
+<!-- SYSTEM CONTEXT (NOT PART OF USER QUERY) -->
+<context.instruction>following part contains context information injected by the system. Please follow these instructions:
+
+1. Always prioritize handling user-visible content.
+2. the context is only required when user's queries rely on it.
+</context.instruction>
+<current_page_context>
+Custom: Custom Title
+</current_page_context>
+<!-- END SYSTEM CONTEXT -->`);
+ });
+ });
+});
diff --git a/packages/context-engine/src/providers/__tests__/__snapshots__/GroupContextInjector.test.ts.snap b/packages/context-engine/src/providers/__tests__/__snapshots__/GroupContextInjector.test.ts.snap
new file mode 100644
index 00000000000..6a0b1af77af
--- /dev/null
+++ b/packages/context-engine/src/providers/__tests__/__snapshots__/GroupContextInjector.test.ts.snap
@@ -0,0 +1,121 @@
+// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
+
+exports[`GroupContextInjector > Edge Cases > should handle empty members array 1`] = `
+"Prompt.
+
+<group_context>
+You are "", acting as a in the multi-agent group "Empty Group".
+Your internal agent ID is (for system use only, never expose to users).
+
+<critical_output_rules>
+IMPORTANT: Your responses must contain ONLY your actual reply content.
+- Messages in conversation history start with '<speaker name="..." />' - this identifies who sent each message
+- NEVER start your response with '<speaker' tag - the system adds this automatically
+- Just output your actual response content directly
+</critical_output_rules>
+
+<group_description>The following describes the purpose and goals of this agent group:
+
+Empty group description
+</group_description>
+
+<group_participants>The following agents are available in this group:
+
+
+</group_participants>
+
+<identity_rules>
+- NEVER expose or display agent IDs to users - always refer to agents by their names
+</identity_rules>
+</group_context>"
+`;
+
+exports[`GroupContextInjector > Variable Replacement > should handle config with only group info 1`] = `
+"System prompt.
+
+<group_context>
+You are "", acting as a in the multi-agent group "Test Group".
+Your internal agent ID is (for system use only, never expose to users).
+
+<critical_output_rules>
+IMPORTANT: Your responses must contain ONLY your actual reply content.
+- Messages in conversation history start with '<speaker name="..." />' - this identifies who sent each message
+- NEVER start your response with '<speaker' tag - the system adds this automatically
+- Just output your actual response content directly
+</critical_output_rules>
+
+<group_description>The following describes the purpose and goals of this agent group:
+
+Test group description
+</group_description>
+
+<group_participants>The following agents are available in this group:
+
+ <member name="Agent 1" id="agt_1" />
+</group_participants>
+
+<identity_rules>
+- NEVER expose or display agent IDs to users - always refer to agents by their names
+</identity_rules>
+</group_context>"
+`;
+
+exports[`GroupContextInjector > Variable Replacement > should handle config with only identity info 1`] = `
+"You are an editor.
+
+<group_context>
+You are "Editor", acting as a participant in the multi-agent group "".
+Your internal agent ID is agt_editor (for system use only, never expose to users).
+
+<critical_output_rules>
+IMPORTANT: Your responses must contain ONLY your actual reply content.
+- Messages in conversation history start with '<speaker name="..." />' - this identifies who sent each message
+- NEVER start your response with '<speaker' tag - the system adds this automatically
+- Just output your actual response content directly
+</critical_output_rules>
+
+<group_description>The following describes the purpose and goals of this agent group:
+
+
+</group_description>
+
+<group_participants>The following agents are available in this group:
+
+
+</group_participants>
+
+<identity_rules>
+- NEVER expose or display agent IDs to users - always refer to agents by their names
+</identity_rules>
+</group_context>"
+`;
+
+exports[`GroupContextInjector > Variable Replacement > should handle empty config 1`] = `
+"Base prompt.
+
+<group_context>
+You are "", acting as a in the multi-agent group "".
+Your internal agent ID is (for system use only, never expose to users).
+
+<critical_output_rules>
+IMPORTANT: Your responses must contain ONLY your actual reply content.
+- Messages in conversation history start with '<speaker name="..." />' - this identifies who sent each message
+- NEVER start your response with '<speaker' tag - the system adds this automatically
+- Just output your actual response content directly
+</critical_output_rules>
+
+<group_description>The following describes the purpose and goals of this agent group:
+
+
+</group_description>
+
+<group_participants>The following agents are available in this group:
+
+
+</group_participants>
+
+<identity_rules>
+- NEVER expose or display agent IDs to users - always refer to agents by their names
+</identity_rules>
+</group_context>"
+`;
diff --git a/packages/context-engine/src/providers/index.ts b/packages/context-engine/src/providers/index.ts
index fc8c2b5fc03..5d9c31f101f 100644
--- a/packages/context-engine/src/providers/index.ts
+++ b/packages/context-engine/src/providers/index.ts
@@ -1,11 +1,36 @@
// Context Provider exports
+export { AgentBuilderContextInjector } from './AgentBuilderContextInjector';
+export { GroupAgentBuilderContextInjector } from './GroupAgentBuilderContextInjector';
+export { GroupContextInjector } from './GroupContextInjector';
export { HistorySummaryProvider } from './HistorySummary';
export { KnowledgeInjector } from './KnowledgeInjector';
+export { PageEditorContextInjector } from './PageEditorContextInjector';
export { SystemRoleInjector } from './SystemRoleInjector';
export { ToolSystemRoleProvider } from './ToolSystemRole';
+export { UserMemoryInjector } from './UserMemoryInjector';
// Re-export types
+export type {
+ AgentBuilderContext,
+ AgentBuilderContextInjectorConfig,
+ OfficialToolItem,
+} from './AgentBuilderContextInjector';
+export type {
+ GroupAgentBuilderContext,
+ GroupAgentBuilderContextInjectorConfig,
+ GroupMemberItem,
+ GroupOfficialToolItem,
+} from './GroupAgentBuilderContextInjector';
+export type {
+ GroupContextInjectorConfig,
+ GroupMemberInfo as GroupContextMemberInfo,
+} from './GroupContextInjector';
export type { HistorySummaryConfig } from './HistorySummary';
export type { KnowledgeInjectorConfig } from './KnowledgeInjector';
+export type {
+ PageEditorContext,
+ PageEditorContextInjectorConfig,
+} from './PageEditorContextInjector';
export type { SystemRoleInjectorConfig } from './SystemRoleInjector';
export type { ToolSystemRoleConfig } from './ToolSystemRole';
+export type { UserMemoryInjectorConfig } from './UserMemoryInjector';
diff --git a/packages/conversation-flow/src/__tests__/fixtures/index.ts b/packages/conversation-flow/src/__tests__/fixtures/index.ts
index 67d012be6ac..19411b3213a 100644
--- a/packages/conversation-flow/src/__tests__/fixtures/index.ts
+++ b/packages/conversation-flow/src/__tests__/fixtures/index.ts
@@ -1,11 +1,15 @@
import type { Message, ParseResult } from '../../types';
// Input fixtures
+import { agentCouncil as agentCouncilInputs } from './inputs/agentCouncil';
+import { agentGroup as agentGroupInputs } from './inputs/agentGroup';
import assistantChainWithFollowupInput from './inputs/assistant-chain-with-followup.json';
import { assistantGroup as assistantGroupInputs } from './inputs/assistantGroup';
import { branch as branchInputs } from './inputs/branch';
import { compare as compareInputs } from './inputs/compare';
import linearConversationInput from './inputs/linear-conversation.json';
// Output fixtures
+import { agentCouncil as agentCouncilOutputs } from './outputs/agentCouncil';
+import { agentGroup as agentGroupOutputs } from './outputs/agentGroup';
import assistantChainWithFollowupOutput from './outputs/assistant-chain-with-followup.json';
import { assistantGroup as assistantGroupOutputs } from './outputs/assistantGroup';
import { branch as branchOutputs } from './outputs/branch';
@@ -25,6 +29,8 @@ export interface SerializedParseResult {
* Test input fixtures - raw messages from database
*/
export const inputs = {
+ agentCouncil: agentCouncilInputs,
+ agentGroup: agentGroupInputs,
assistantChainWithFollowup: assistantChainWithFollowupInput as Message[],
assistantGroup: assistantGroupInputs,
branch: branchInputs,
@@ -36,6 +42,8 @@ export const inputs = {
* Test output fixtures - expected parse results
*/
export const outputs = {
+ agentCouncil: agentCouncilOutputs,
+ agentGroup: agentGroupOutputs,
assistantChainWithFollowup: assistantChainWithFollowupOutput as unknown as SerializedParseResult,
assistantGroup: assistantGroupOutputs,
branch: branchOutputs,
diff --git a/packages/conversation-flow/src/__tests__/fixtures/inputs/agentCouncil/index.ts b/packages/conversation-flow/src/__tests__/fixtures/inputs/agentCouncil/index.ts
new file mode 100644
index 00000000000..7406b4fab14
--- /dev/null
+++ b/packages/conversation-flow/src/__tests__/fixtures/inputs/agentCouncil/index.ts
@@ -0,0 +1,8 @@
+import type { Message } from '../../../../types';
+import simple from './simple.json';
+import withSupervisorReply from './with-supervisor-reply.json';
+
+export const agentCouncil = {
+ simple: simple as Message[],
+ withSupervisorReply: withSupervisorReply as Message[],
+};
diff --git a/packages/conversation-flow/src/__tests__/fixtures/inputs/agentCouncil/simple.json b/packages/conversation-flow/src/__tests__/fixtures/inputs/agentCouncil/simple.json
new file mode 100644
index 00000000000..a5eae40a056
--- /dev/null
+++ b/packages/conversation-flow/src/__tests__/fixtures/inputs/agentCouncil/simple.json
@@ -0,0 +1,118 @@
+[
+ {
+ "id": "msg-user-1",
+ "role": "user",
+ "content": "Please have everyone discuss the pros and cons of microservices architecture.",
+ "parentId": null,
+ "createdAt": 1704067200000,
+ "updatedAt": 1704067200000,
+ "meta": {}
+ },
+ {
+ "id": "msg-supervisor-1",
+ "role": "assistant",
+ "agentId": "supervisor",
+ "content": "",
+ "parentId": "msg-user-1",
+ "createdAt": 1704067201000,
+ "updatedAt": 1704067201000,
+ "meta": {},
+ "tools": [
+ {
+ "id": "call_broadcast_1",
+ "type": "function",
+ "function": {
+ "name": "broadcast",
+ "arguments": "{\"agentIds\": [\"agent-backend\", \"agent-devops\", \"agent-architect\"], \"instruction\": \"Discuss the pros and cons of microservices architecture from your perspective.\"}"
+ },
+ "identifier": "lobe-group-management",
+ "apiName": "broadcast"
+ }
+ ]
+ },
+ {
+ "id": "msg-broadcast-tool-1",
+ "role": "tool",
+ "content": "Broadcasting to 3 agents...",
+ "parentId": "msg-supervisor-1",
+ "tool_call_id": "call_broadcast_1",
+ "createdAt": 1704067202000,
+ "updatedAt": 1704067202000,
+ "meta": {},
+ "metadata": {
+ "agentCouncil": true
+ }
+ },
+ {
+ "id": "msg-agent-backend-1",
+ "role": "assistant",
+ "agentId": "agent-backend",
+ "content": "**From a Backend Developer's Perspective:**\n\n**Pros:**\n- Independent deployment of services\n- Technology flexibility per service\n- Better fault isolation\n- Easier to scale specific services\n\n**Cons:**\n- Increased complexity in service communication\n- Data consistency challenges\n- More complex debugging and monitoring\n- Network latency between services",
+ "parentId": "msg-broadcast-tool-1",
+ "model": "gpt-4",
+ "provider": "openai",
+ "createdAt": 1704067205000,
+ "updatedAt": 1704067205000,
+ "meta": {
+ "avatar": "backend-dev",
+ "title": "Backend Developer"
+ },
+ "metadata": {
+ "totalInputTokens": 50,
+ "totalOutputTokens": 120,
+ "totalTokens": 170,
+ "tps": 45.0,
+ "ttft": 350,
+ "duration": 2667,
+ "latency": 3017
+ }
+ },
+ {
+ "id": "msg-agent-devops-1",
+ "role": "assistant",
+ "agentId": "agent-devops",
+ "content": "**From a DevOps Engineer's Perspective:**\n\n**Pros:**\n- CI/CD pipelines can be service-specific\n- Container orchestration fits naturally\n- Auto-scaling at service level\n- Blue-green deployments are easier\n\n**Cons:**\n- Complex infrastructure management\n- More services = more monitoring overhead\n- Configuration management complexity\n- Increased resource consumption (each service needs its own runtime)",
+ "parentId": "msg-broadcast-tool-1",
+ "model": "claude-3-5-sonnet-20241022",
+ "provider": "anthropic",
+ "createdAt": 1704067205500,
+ "updatedAt": 1704067205500,
+ "meta": {
+ "avatar": "devops",
+ "title": "DevOps Engineer"
+ },
+ "metadata": {
+ "totalInputTokens": 50,
+ "totalOutputTokens": 130,
+ "totalTokens": 180,
+ "tps": 52.0,
+ "ttft": 280,
+ "duration": 2500,
+ "latency": 2780
+ }
+ },
+ {
+ "id": "msg-agent-architect-1",
+ "role": "assistant",
+ "agentId": "agent-architect",
+ "content": "**From a Software Architect's Perspective:**\n\n**Pros:**\n- Clear service boundaries and ownership\n- Supports domain-driven design\n- Teams can work independently\n- Easier to understand individual services\n\n**Cons:**\n- Requires careful API versioning strategy\n- Cross-cutting concerns need special handling\n- Service discovery and load balancing complexity\n- Initial design requires significant upfront investment",
+ "parentId": "msg-broadcast-tool-1",
+ "model": "gpt-4",
+ "provider": "openai",
+ "createdAt": 1704067206000,
+ "updatedAt": 1704067206000,
+ "meta": {
+ "avatar": "architect",
+ "title": "Software Architect"
+ },
+ "metadata": {
+ "totalInputTokens": 50,
+ "totalOutputTokens": 125,
+ "totalTokens": 175,
+ "tps": 48.0,
+ "ttft": 320,
+ "duration": 2604,
+ "latency": 2924
+ }
+ }
+]
diff --git a/packages/conversation-flow/src/__tests__/fixtures/inputs/agentCouncil/with-supervisor-reply.json b/packages/conversation-flow/src/__tests__/fixtures/inputs/agentCouncil/with-supervisor-reply.json
new file mode 100644
index 00000000000..9e11ae69e55
--- /dev/null
+++ b/packages/conversation-flow/src/__tests__/fixtures/inputs/agentCouncil/with-supervisor-reply.json
@@ -0,0 +1,106 @@
+[
+ {
+ "id": "msg-user-1",
+ "role": "user",
+ "content": "Please have everyone discuss the pros and cons of microservices architecture.",
+ "parentId": null,
+ "createdAt": 1704067200000,
+ "updatedAt": 1704067200000,
+ "meta": {}
+ },
+ {
+ "id": "msg-supervisor-1",
+ "role": "assistant",
+ "agentId": "supervisor",
+ "content": "",
+ "parentId": "msg-user-1",
+ "createdAt": 1704067201000,
+ "updatedAt": 1704067201000,
+ "meta": {},
+ "tools": [
+ {
+ "id": "call_broadcast_1",
+ "type": "function",
+ "function": {
+ "name": "broadcast",
+ "arguments": "{\"agentIds\": [\"agent-backend\", \"agent-devops\", \"agent-architect\"], \"instruction\": \"Discuss the pros and cons of microservices architecture from your perspective.\"}"
+ },
+ "identifier": "lobe-group-management",
+ "apiName": "broadcast"
+ }
+ ]
+ },
+ {
+ "id": "msg-broadcast-tool-1",
+ "role": "tool",
+ "content": "Broadcasting to 3 agents...",
+ "parentId": "msg-supervisor-1",
+ "tool_call_id": "call_broadcast_1",
+ "createdAt": 1704067202000,
+ "updatedAt": 1704067202000,
+ "meta": {},
+ "metadata": {
+ "agentCouncil": true
+ }
+ },
+ {
+ "id": "msg-agent-backend-1",
+ "role": "assistant",
+ "agentId": "agent-backend",
+ "content": "**From a Backend Developer's Perspective:**\n\n**Pros:**\n- Independent deployment\n- Technology flexibility\n\n**Cons:**\n- Service communication complexity\n- Data consistency challenges",
+ "parentId": "msg-broadcast-tool-1",
+ "model": "gpt-4",
+ "provider": "openai",
+ "createdAt": 1704067205000,
+ "updatedAt": 1704067205000,
+ "meta": {
+ "avatar": "backend-dev",
+ "title": "Backend Developer"
+ }
+ },
+ {
+ "id": "msg-agent-devops-1",
+ "role": "assistant",
+ "agentId": "agent-devops",
+ "content": "**From a DevOps Engineer's Perspective:**\n\n**Pros:**\n- CI/CD pipelines can be service-specific\n- Auto-scaling at service level\n\n**Cons:**\n- Complex infrastructure management\n- More monitoring overhead",
+ "parentId": "msg-broadcast-tool-1",
+ "model": "claude-3-5-sonnet-20241022",
+ "provider": "anthropic",
+ "createdAt": 1704067205500,
+ "updatedAt": 1704067205500,
+ "meta": {
+ "avatar": "devops",
+ "title": "DevOps Engineer"
+ }
+ },
+ {
+ "id": "msg-agent-architect-1",
+ "role": "assistant",
+ "agentId": "agent-architect",
+ "content": "**From a Software Architect's Perspective:**\n\n**Pros:**\n- Clear service boundaries\n- Teams can work independently\n\n**Cons:**\n- API versioning complexity\n- Service discovery challenges",
+ "parentId": "msg-broadcast-tool-1",
+ "model": "gpt-4",
+ "provider": "openai",
+ "createdAt": 1704067206000,
+ "updatedAt": 1704067206000,
+ "meta": {
+ "avatar": "architect",
+ "title": "Software Architect"
+ }
+ },
+ {
+ "id": "msg-supervisor-summary",
+ "role": "assistant",
+ "agentId": "supervisor",
+ "content": "## Summary\n\nBased on the discussion from our team:\n\n**Key Pros:**\n- Independent deployment and scaling\n- Technology flexibility\n- Clear service boundaries\n\n**Key Cons:**\n- Increased complexity in communication and infrastructure\n- Data consistency and monitoring challenges\n\nI recommend starting with a modular monolith and gradually extracting services as needed.",
+ "parentId": "msg-agent-architect-1",
+ "model": "gpt-4",
+ "provider": "openai",
+ "createdAt": 1704067210000,
+ "updatedAt": 1704067210000,
+ "meta": {
+ "avatar": "supervisor",
+ "title": "Supervisor"
+ }
+ }
+]
diff --git a/packages/conversation-flow/src/__tests__/fixtures/inputs/agentGroup/index.ts b/packages/conversation-flow/src/__tests__/fixtures/inputs/agentGroup/index.ts
new file mode 100644
index 00000000000..f53437750fe
--- /dev/null
+++ b/packages/conversation-flow/src/__tests__/fixtures/inputs/agentGroup/index.ts
@@ -0,0 +1,6 @@
+import type { Message } from '../../../../types';
+import speakDifferentAgent from './speak-different-agent.json';
+
+export const agentGroup = {
+ speakDifferentAgent: speakDifferentAgent as Message[],
+};
diff --git a/packages/conversation-flow/src/__tests__/fixtures/inputs/agentGroup/speak-different-agent.json b/packages/conversation-flow/src/__tests__/fixtures/inputs/agentGroup/speak-different-agent.json
new file mode 100644
index 00000000000..8118cefa5c2
--- /dev/null
+++ b/packages/conversation-flow/src/__tests__/fixtures/inputs/agentGroup/speak-different-agent.json
@@ -0,0 +1,61 @@
+[
+ {
+ "id": "msg-user-1",
+ "role": "user",
+ "content": "Can you ask the backend developer about the API design?",
+ "parentId": null,
+ "createdAt": 1704067200000,
+ "updatedAt": 1704067200000,
+ "meta": {}
+ },
+ {
+ "id": "msg-supervisor-1",
+ "role": "assistant",
+ "agentId": "supervisor",
+ "content": "I'll ask the backend developer to explain the API design.",
+ "parentId": "msg-user-1",
+ "tools": [
+ {
+ "id": "call_speak_1",
+ "type": "function",
+ "function": {
+ "name": "speak",
+ "arguments": "{\"agentId\": \"agent-backend\", \"instruction\": \"Please explain the API design.\"}"
+ },
+ "identifier": "lobe-group-management",
+ "apiName": "speak"
+ }
+ ],
+ "createdAt": 1704067201000,
+ "updatedAt": 1704067201000,
+ "meta": {
+ "avatar": "supervisor",
+ "title": "Supervisor"
+ }
+ },
+ {
+ "id": "msg-speak-tool-1",
+ "role": "tool",
+ "content": "Triggered agent \"agent-backend\" to respond.",
+ "parentId": "msg-supervisor-1",
+ "tool_call_id": "call_speak_1",
+ "createdAt": 1704067202000,
+ "updatedAt": 1704067202000,
+ "meta": {}
+ },
+ {
+ "id": "msg-agent-backend-1",
+ "role": "assistant",
+ "agentId": "agent-backend",
+ "content": "The API follows RESTful design principles. We have endpoints for users, products, and orders. Each endpoint supports CRUD operations with proper HTTP methods.",
+ "parentId": "msg-speak-tool-1",
+ "model": "gpt-4",
+ "provider": "openai",
+ "createdAt": 1704067205000,
+ "updatedAt": 1704067205000,
+ "meta": {
+ "avatar": "backend-dev",
+ "title": "Backend Developer"
+ }
+ }
+]
diff --git a/packages/conversation-flow/src/__tests__/fixtures/inputs/index.ts b/packages/conversation-flow/src/__tests__/fixtures/inputs/index.ts
index 8d7848c310d..a7c34c5760e 100644
--- a/packages/conversation-flow/src/__tests__/fixtures/inputs/index.ts
+++ b/packages/conversation-flow/src/__tests__/fixtures/inputs/index.ts
@@ -1,10 +1,16 @@
import type { Message } from '../../../types';
+import { agentCouncil } from './agentCouncil';
+import { agentGroup } from './agentGroup';
+import assistantChainWithFollowup from './assistant-chain-with-followup.json';
import { assistantGroup } from './assistantGroup';
import { branch } from './branch';
import { compare } from './compare';
import linearConversation from './linear-conversation.json';
export const inputs = {
+ agentCouncil,
+ agentGroup,
+ assistantChainWithFollowup: assistantChainWithFollowup as Message[],
assistantGroup,
branch,
compare,
diff --git a/packages/conversation-flow/src/__tests__/fixtures/outputs/agentCouncil/index.ts b/packages/conversation-flow/src/__tests__/fixtures/outputs/agentCouncil/index.ts
new file mode 100644
index 00000000000..a54d8c26e8f
--- /dev/null
+++ b/packages/conversation-flow/src/__tests__/fixtures/outputs/agentCouncil/index.ts
@@ -0,0 +1,8 @@
+import type { SerializedParseResult } from '../../index';
+import simple from './simple.json';
+import withSupervisorReply from './with-supervisor-reply.json';
+
+export const agentCouncil = {
+ simple: simple as unknown as SerializedParseResult,
+ withSupervisorReply: withSupervisorReply as unknown as SerializedParseResult,
+};
diff --git a/packages/conversation-flow/src/__tests__/fixtures/outputs/agentCouncil/simple.json b/packages/conversation-flow/src/__tests__/fixtures/outputs/agentCouncil/simple.json
new file mode 100644
index 00000000000..cafd562df19
--- /dev/null
+++ b/packages/conversation-flow/src/__tests__/fixtures/outputs/agentCouncil/simple.json
@@ -0,0 +1,285 @@
+{
+ "contextTree": [
+ {
+ "id": "msg-user-1",
+ "type": "message"
+ },
+ {
+ "id": "msg-supervisor-1",
+ "type": "assistantGroup",
+ "children": [
+ {
+ "id": "msg-supervisor-1",
+ "type": "message",
+ "tools": ["msg-broadcast-tool-1"]
+ }
+ ]
+ },
+ {
+ "members": [
+ {
+ "id": "msg-agent-backend-1",
+ "type": "message"
+ },
+ {
+ "id": "msg-agent-devops-1",
+ "type": "message"
+ },
+ {
+ "id": "msg-agent-architect-1",
+ "type": "message"
+ }
+ ],
+ "id": "agentCouncil-msg-broadcast-tool-1-msg-agent-backend-1-msg-agent-devops-1-msg-agent-architect-1",
+ "messageId": "msg-broadcast-tool-1",
+ "type": "agentCouncil"
+ }
+ ],
+ "flatList": [
+ {
+ "id": "msg-user-1",
+ "role": "user",
+ "content": "Please have everyone discuss the pros and cons of microservices architecture.",
+ "parentId": null,
+ "createdAt": 1704067200000,
+ "updatedAt": 1704067200000,
+ "meta": {}
+ },
+ {
+ "id": "msg-supervisor-1",
+ "role": "assistantGroup",
+ "agentId": "supervisor",
+ "content": "",
+ "parentId": "msg-user-1",
+ "createdAt": 1704067201000,
+ "updatedAt": 1704067201000,
+ "meta": {},
+ "children": [
+ {
+ "id": "msg-supervisor-1",
+ "content": "",
+ "tools": [
+ {
+ "id": "call_broadcast_1",
+ "type": "function",
+ "function": {
+ "name": "broadcast",
+ "arguments": "{\"agentIds\": [\"agent-backend\", \"agent-devops\", \"agent-architect\"], \"instruction\": \"Discuss the pros and cons of microservices architecture from your perspective.\"}"
+ },
+ "identifier": "lobe-group-management",
+ "apiName": "broadcast",
+ "result": {
+ "id": "msg-broadcast-tool-1",
+ "content": "Broadcasting to 3 agents..."
+ },
+ "result_msg_id": "msg-broadcast-tool-1"
+ }
+ ]
+ }
+ ]
+ },
+ {
+ "content": "",
+ "createdAt": 1704067205000,
+ "extra": {
+ "parentMessageId": "msg-broadcast-tool-1"
+ },
+ "id": "agentCouncil-msg-broadcast-tool-1-msg-agent-backend-1-msg-agent-devops-1-msg-agent-architect-1",
+ "members": [
+ {
+ "id": "msg-agent-backend-1",
+ "role": "assistant",
+ "agentId": "agent-backend",
+ "content": "**From a Backend Developer's Perspective:**\n\n**Pros:**\n- Independent deployment of services\n- Technology flexibility per service\n- Better fault isolation\n- Easier to scale specific services\n\n**Cons:**\n- Increased complexity in service communication\n- Data consistency challenges\n- More complex debugging and monitoring\n- Network latency between services",
+ "parentId": "msg-broadcast-tool-1",
+ "model": "gpt-4",
+ "provider": "openai",
+ "createdAt": 1704067205000,
+ "updatedAt": 1704067205000,
+ "meta": {
+ "avatar": "backend-dev",
+ "title": "Backend Developer"
+ },
+ "metadata": {
+ "totalInputTokens": 50,
+ "totalOutputTokens": 120,
+ "totalTokens": 170,
+ "tps": 45,
+ "ttft": 350,
+ "duration": 2667,
+ "latency": 3017
+ }
+ },
+ {
+ "id": "msg-agent-devops-1",
+ "role": "assistant",
+ "agentId": "agent-devops",
+ "content": "**From a DevOps Engineer's Perspective:**\n\n**Pros:**\n- CI/CD pipelines can be service-specific\n- Container orchestration fits naturally\n- Auto-scaling at service level\n- Blue-green deployments are easier\n\n**Cons:**\n- Complex infrastructure management\n- More services = more monitoring overhead\n- Configuration management complexity\n- Increased resource consumption (each service needs its own runtime)",
+ "parentId": "msg-broadcast-tool-1",
+ "model": "claude-3-5-sonnet-20241022",
+ "provider": "anthropic",
+ "createdAt": 1704067205500,
+ "updatedAt": 1704067205500,
+ "meta": {
+ "avatar": "devops",
+ "title": "DevOps Engineer"
+ },
+ "metadata": {
+ "totalInputTokens": 50,
+ "totalOutputTokens": 130,
+ "totalTokens": 180,
+ "tps": 52,
+ "ttft": 280,
+ "duration": 2500,
+ "latency": 2780
+ }
+ },
+ {
+ "id": "msg-agent-architect-1",
+ "role": "assistant",
+ "agentId": "agent-architect",
+ "content": "**From a Software Architect's Perspective:**\n\n**Pros:**\n- Clear service boundaries and ownership\n- Supports domain-driven design\n- Teams can work independently\n- Easier to understand individual services\n\n**Cons:**\n- Requires careful API versioning strategy\n- Cross-cutting concerns need special handling\n- Service discovery and load balancing complexity\n- Initial design requires significant upfront investment",
+ "parentId": "msg-broadcast-tool-1",
+ "model": "gpt-4",
+ "provider": "openai",
+ "createdAt": 1704067206000,
+ "updatedAt": 1704067206000,
+ "meta": {
+ "avatar": "architect",
+ "title": "Software Architect"
+ },
+ "metadata": {
+ "totalInputTokens": 50,
+ "totalOutputTokens": 125,
+ "totalTokens": 175,
+ "tps": 48,
+ "ttft": 320,
+ "duration": 2604,
+ "latency": 2924
+ }
+ }
+ ],
+ "meta": {},
+ "role": "agentCouncil",
+ "updatedAt": 1704067206000
+ }
+ ],
+ "messageMap": {
+ "msg-user-1": {
+ "id": "msg-user-1",
+ "role": "user",
+ "content": "Please have everyone discuss the pros and cons of microservices architecture.",
+ "parentId": null,
+ "createdAt": 1704067200000,
+ "updatedAt": 1704067200000,
+ "meta": {}
+ },
+ "msg-supervisor-1": {
+ "id": "msg-supervisor-1",
+ "role": "assistant",
+ "agentId": "supervisor",
+ "content": "",
+ "parentId": "msg-user-1",
+ "createdAt": 1704067201000,
+ "updatedAt": 1704067201000,
+ "meta": {},
+ "tools": [
+ {
+ "id": "call_broadcast_1",
+ "type": "function",
+ "function": {
+ "name": "broadcast",
+ "arguments": "{\"agentIds\": [\"agent-backend\", \"agent-devops\", \"agent-architect\"], \"instruction\": \"Discuss the pros and cons of microservices architecture from your perspective.\"}"
+ },
+ "identifier": "lobe-group-management",
+ "apiName": "broadcast"
+ }
+ ]
+ },
+ "msg-broadcast-tool-1": {
+ "id": "msg-broadcast-tool-1",
+ "role": "tool",
+ "content": "Broadcasting to 3 agents...",
+ "parentId": "msg-supervisor-1",
+ "tool_call_id": "call_broadcast_1",
+ "createdAt": 1704067202000,
+ "updatedAt": 1704067202000,
+ "meta": {},
+ "metadata": {
+ "agentCouncil": true
+ }
+ },
+ "msg-agent-backend-1": {
+ "id": "msg-agent-backend-1",
+ "role": "assistant",
+ "agentId": "agent-backend",
+ "content": "**From a Backend Developer's Perspective:**\n\n**Pros:**\n- Independent deployment of services\n- Technology flexibility per service\n- Better fault isolation\n- Easier to scale specific services\n\n**Cons:**\n- Increased complexity in service communication\n- Data consistency challenges\n- More complex debugging and monitoring\n- Network latency between services",
+ "parentId": "msg-broadcast-tool-1",
+ "model": "gpt-4",
+ "provider": "openai",
+ "createdAt": 1704067205000,
+ "updatedAt": 1704067205000,
+ "meta": {
+ "avatar": "backend-dev",
+ "title": "Backend Developer"
+ },
+ "metadata": {
+ "totalInputTokens": 50,
+ "totalOutputTokens": 120,
+ "totalTokens": 170,
+ "tps": 45,
+ "ttft": 350,
+ "duration": 2667,
+ "latency": 3017
+ }
+ },
+ "msg-agent-devops-1": {
+ "id": "msg-agent-devops-1",
+ "role": "assistant",
+ "agentId": "agent-devops",
+ "content": "**From a DevOps Engineer's Perspective:**\n\n**Pros:**\n- CI/CD pipelines can be service-specific\n- Container orchestration fits naturally\n- Auto-scaling at service level\n- Blue-green deployments are easier\n\n**Cons:**\n- Complex infrastructure management\n- More services = more monitoring overhead\n- Configuration management complexity\n- Increased resource consumption (each service needs its own runtime)",
+ "parentId": "msg-broadcast-tool-1",
+ "model": "claude-3-5-sonnet-20241022",
+ "provider": "anthropic",
+ "createdAt": 1704067205500,
+ "updatedAt": 1704067205500,
+ "meta": {
+ "avatar": "devops",
+ "title": "DevOps Engineer"
+ },
+ "metadata": {
+ "totalInputTokens": 50,
+ "totalOutputTokens": 130,
+ "totalTokens": 180,
+ "tps": 52,
+ "ttft": 280,
+ "duration": 2500,
+ "latency": 2780
+ }
+ },
+ "msg-agent-architect-1": {
+ "id": "msg-agent-architect-1",
+ "role": "assistant",
+ "agentId": "agent-architect",
+ "content": "**From a Software Architect's Perspective:**\n\n**Pros:**\n- Clear service boundaries and ownership\n- Supports domain-driven design\n- Teams can work independently\n- Easier to understand individual services\n\n**Cons:**\n- Requires careful API versioning strategy\n- Cross-cutting concerns need special handling\n- Service discovery and load balancing complexity\n- Initial design requires significant upfront investment",
+ "parentId": "msg-broadcast-tool-1",
+ "model": "gpt-4",
+ "provider": "openai",
+ "createdAt": 1704067206000,
+ "updatedAt": 1704067206000,
+ "meta": {
+ "avatar": "architect",
+ "title": "Software Architect"
+ },
+ "metadata": {
+ "totalInputTokens": 50,
+ "totalOutputTokens": 125,
+ "totalTokens": 175,
+ "tps": 48,
+ "ttft": 320,
+ "duration": 2604,
+ "latency": 2924
+ }
+ }
+ }
+}
diff --git a/packages/conversation-flow/src/__tests__/fixtures/outputs/agentCouncil/with-supervisor-reply.json b/packages/conversation-flow/src/__tests__/fixtures/outputs/agentCouncil/with-supervisor-reply.json
new file mode 100644
index 00000000000..bdc332e34b2
--- /dev/null
+++ b/packages/conversation-flow/src/__tests__/fixtures/outputs/agentCouncil/with-supervisor-reply.json
@@ -0,0 +1,265 @@
+{
+ "contextTree": [
+ {
+ "id": "msg-user-1",
+ "type": "message"
+ },
+ {
+ "id": "msg-supervisor-1",
+ "type": "assistantGroup",
+ "children": [
+ {
+ "id": "msg-supervisor-1",
+ "type": "message",
+ "tools": ["msg-broadcast-tool-1"]
+ }
+ ]
+ },
+ {
+ "members": [
+ {
+ "id": "msg-agent-backend-1",
+ "type": "message"
+ },
+ {
+ "id": "msg-agent-devops-1",
+ "type": "message"
+ },
+ {
+ "id": "msg-agent-architect-1",
+ "type": "message"
+ }
+ ],
+ "id": "agentCouncil-msg-broadcast-tool-1-msg-agent-backend-1-msg-agent-devops-1-msg-agent-architect-1",
+ "messageId": "msg-broadcast-tool-1",
+ "type": "agentCouncil"
+ },
+ {
+ "id": "msg-supervisor-summary",
+ "type": "message"
+ }
+ ],
+ "flatList": [
+ {
+ "id": "msg-user-1",
+ "role": "user",
+ "content": "Please have everyone discuss the pros and cons of microservices architecture.",
+ "parentId": null,
+ "createdAt": 1704067200000,
+ "updatedAt": 1704067200000,
+ "meta": {}
+ },
+ {
+ "id": "msg-supervisor-1",
+ "role": "assistantGroup",
+ "agentId": "supervisor",
+ "content": "",
+ "parentId": "msg-user-1",
+ "createdAt": 1704067201000,
+ "updatedAt": 1704067201000,
+ "meta": {},
+ "children": [
+ {
+ "id": "msg-supervisor-1",
+ "content": "",
+ "tools": [
+ {
+ "id": "call_broadcast_1",
+ "type": "function",
+ "function": {
+ "name": "broadcast",
+ "arguments": "{\"agentIds\": [\"agent-backend\", \"agent-devops\", \"agent-architect\"], \"instruction\": \"Discuss the pros and cons of microservices architecture from your perspective.\"}"
+ },
+ "identifier": "lobe-group-management",
+ "apiName": "broadcast",
+ "result": {
+ "id": "msg-broadcast-tool-1",
+ "content": "Broadcasting to 3 agents..."
+ },
+ "result_msg_id": "msg-broadcast-tool-1"
+ }
+ ]
+ }
+ ]
+ },
+ {
+ "content": "",
+ "createdAt": 1704067205000,
+ "extra": {
+ "parentMessageId": "msg-broadcast-tool-1"
+ },
+ "id": "agentCouncil-msg-broadcast-tool-1-msg-agent-backend-1-msg-agent-devops-1-msg-agent-architect-1",
+ "members": [
+ {
+ "id": "msg-agent-backend-1",
+ "role": "assistant",
+ "agentId": "agent-backend",
+ "content": "**From a Backend Developer's Perspective:**\n\n**Pros:**\n- Independent deployment\n- Technology flexibility\n\n**Cons:**\n- Service communication complexity\n- Data consistency challenges",
+ "parentId": "msg-broadcast-tool-1",
+ "model": "gpt-4",
+ "provider": "openai",
+ "createdAt": 1704067205000,
+ "updatedAt": 1704067205000,
+ "meta": {
+ "avatar": "backend-dev",
+ "title": "Backend Developer"
+ }
+ },
+ {
+ "id": "msg-agent-devops-1",
+ "role": "assistant",
+ "agentId": "agent-devops",
+ "content": "**From a DevOps Engineer's Perspective:**\n\n**Pros:**\n- CI/CD pipelines can be service-specific\n- Auto-scaling at service level\n\n**Cons:**\n- Complex infrastructure management\n- More monitoring overhead",
+ "parentId": "msg-broadcast-tool-1",
+ "model": "claude-3-5-sonnet-20241022",
+ "provider": "anthropic",
+ "createdAt": 1704067205500,
+ "updatedAt": 1704067205500,
+ "meta": {
+ "avatar": "devops",
+ "title": "DevOps Engineer"
+ }
+ },
+ {
+ "id": "msg-agent-architect-1",
+ "role": "assistant",
+ "agentId": "agent-architect",
+ "content": "**From a Software Architect's Perspective:**\n\n**Pros:**\n- Clear service boundaries\n- Teams can work independently\n\n**Cons:**\n- API versioning complexity\n- Service discovery challenges",
+ "parentId": "msg-broadcast-tool-1",
+ "model": "gpt-4",
+ "provider": "openai",
+ "createdAt": 1704067206000,
+ "updatedAt": 1704067206000,
+ "meta": {
+ "avatar": "architect",
+ "title": "Software Architect"
+ }
+ }
+ ],
+ "meta": {},
+ "role": "agentCouncil",
+ "updatedAt": 1704067206000
+ },
+ {
+ "id": "msg-supervisor-summary",
+ "role": "assistant",
+ "agentId": "supervisor",
+ "content": "## Summary\n\nBased on the discussion from our team:\n\n**Key Pros:**\n- Independent deployment and scaling\n- Technology flexibility\n- Clear service boundaries\n\n**Key Cons:**\n- Increased complexity in communication and infrastructure\n- Data consistency and monitoring challenges\n\nI recommend starting with a modular monolith and gradually extracting services as needed.",
+ "parentId": "msg-agent-architect-1",
+ "model": "gpt-4",
+ "provider": "openai",
+ "createdAt": 1704067210000,
+ "updatedAt": 1704067210000,
+ "meta": {
+ "avatar": "supervisor",
+ "title": "Supervisor"
+ }
+ }
+ ],
+ "messageMap": {
+ "msg-user-1": {
+ "id": "msg-user-1",
+ "role": "user",
+ "content": "Please have everyone discuss the pros and cons of microservices architecture.",
+ "parentId": null,
+ "createdAt": 1704067200000,
+ "updatedAt": 1704067200000,
+ "meta": {}
+ },
+ "msg-supervisor-1": {
+ "id": "msg-supervisor-1",
+ "role": "assistant",
+ "agentId": "supervisor",
+ "content": "",
+ "parentId": "msg-user-1",
+ "createdAt": 1704067201000,
+ "updatedAt": 1704067201000,
+ "meta": {},
+ "tools": [
+ {
+ "id": "call_broadcast_1",
+ "type": "function",
+ "function": {
+ "name": "broadcast",
+ "arguments": "{\"agentIds\": [\"agent-backend\", \"agent-devops\", \"agent-architect\"], \"instruction\": \"Discuss the pros and cons of microservices architecture from your perspective.\"}"
+ },
+ "identifier": "lobe-group-management",
+ "apiName": "broadcast"
+ }
+ ]
+ },
+ "msg-broadcast-tool-1": {
+ "id": "msg-broadcast-tool-1",
+ "role": "tool",
+ "content": "Broadcasting to 3 agents...",
+ "parentId": "msg-supervisor-1",
+ "tool_call_id": "call_broadcast_1",
+ "createdAt": 1704067202000,
+ "updatedAt": 1704067202000,
+ "meta": {},
+ "metadata": {
+ "agentCouncil": true
+ }
+ },
+ "msg-agent-backend-1": {
+ "id": "msg-agent-backend-1",
+ "role": "assistant",
+ "agentId": "agent-backend",
+ "content": "**From a Backend Developer's Perspective:**\n\n**Pros:**\n- Independent deployment\n- Technology flexibility\n\n**Cons:**\n- Service communication complexity\n- Data consistency challenges",
+ "parentId": "msg-broadcast-tool-1",
+ "model": "gpt-4",
+ "provider": "openai",
+ "createdAt": 1704067205000,
+ "updatedAt": 1704067205000,
+ "meta": {
+ "avatar": "backend-dev",
+ "title": "Backend Developer"
+ }
+ },
+ "msg-agent-devops-1": {
+ "id": "msg-agent-devops-1",
+ "role": "assistant",
+ "agentId": "agent-devops",
+ "content": "**From a DevOps Engineer's Perspective:**\n\n**Pros:**\n- CI/CD pipelines can be service-specific\n- Auto-scaling at service level\n\n**Cons:**\n- Complex infrastructure management\n- More monitoring overhead",
+ "parentId": "msg-broadcast-tool-1",
+ "model": "claude-3-5-sonnet-20241022",
+ "provider": "anthropic",
+ "createdAt": 1704067205500,
+ "updatedAt": 1704067205500,
+ "meta": {
+ "avatar": "devops",
+ "title": "DevOps Engineer"
+ }
+ },
+ "msg-agent-architect-1": {
+ "id": "msg-agent-architect-1",
+ "role": "assistant",
+ "agentId": "agent-architect",
+ "content": "**From a Software Architect's Perspective:**\n\n**Pros:**\n- Clear service boundaries\n- Teams can work independently\n\n**Cons:**\n- API versioning complexity\n- Service discovery challenges",
+ "parentId": "msg-broadcast-tool-1",
+ "model": "gpt-4",
+ "provider": "openai",
+ "createdAt": 1704067206000,
+ "updatedAt": 1704067206000,
+ "meta": {
+ "avatar": "architect",
+ "title": "Software Architect"
+ }
+ },
+ "msg-supervisor-summary": {
+ "id": "msg-supervisor-summary",
+ "role": "assistant",
+ "agentId": "supervisor",
+ "content": "## Summary\n\nBased on the discussion from our team:\n\n**Key Pros:**\n- Independent deployment and scaling\n- Technology flexibility\n- Clear service boundaries\n\n**Key Cons:**\n- Increased complexity in communication and infrastructure\n- Data consistency and monitoring challenges\n\nI recommend starting with a modular monolith and gradually extracting services as needed.",
+ "parentId": "msg-agent-architect-1",
+ "model": "gpt-4",
+ "provider": "openai",
+ "createdAt": 1704067210000,
+ "updatedAt": 1704067210000,
+ "meta": {
+ "avatar": "supervisor",
+ "title": "Supervisor"
+ }
+ }
+ }
+}
diff --git a/packages/conversation-flow/src/__tests__/fixtures/outputs/agentGroup/index.ts b/packages/conversation-flow/src/__tests__/fixtures/outputs/agentGroup/index.ts
new file mode 100644
index 00000000000..4d04ff1c69e
--- /dev/null
+++ b/packages/conversation-flow/src/__tests__/fixtures/outputs/agentGroup/index.ts
@@ -0,0 +1,6 @@
+import type { SerializedParseResult } from '../..';
+import speakDifferentAgent from './speak-different-agent.json';
+
+export const agentGroup = {
+ speakDifferentAgent: speakDifferentAgent as unknown as SerializedParseResult,
+};
diff --git a/packages/conversation-flow/src/__tests__/fixtures/outputs/agentGroup/speak-different-agent.json b/packages/conversation-flow/src/__tests__/fixtures/outputs/agentGroup/speak-different-agent.json
new file mode 100644
index 00000000000..56e9504b865
--- /dev/null
+++ b/packages/conversation-flow/src/__tests__/fixtures/outputs/agentGroup/speak-different-agent.json
@@ -0,0 +1,146 @@
+{
+ "contextTree": [
+ {
+ "id": "msg-user-1",
+ "type": "message"
+ },
+ {
+ "id": "msg-supervisor-1",
+ "type": "assistantGroup",
+ "children": [
+ {
+ "id": "msg-supervisor-1",
+ "type": "message",
+ "tools": ["msg-speak-tool-1"]
+ }
+ ]
+ },
+ {
+ "id": "msg-agent-backend-1",
+ "type": "message"
+ }
+ ],
+ "flatList": [
+ {
+ "id": "msg-user-1",
+ "role": "user",
+ "content": "Can you ask the backend developer about the API design?",
+ "parentId": null,
+ "createdAt": 1704067200000,
+ "updatedAt": 1704067200000,
+ "meta": {}
+ },
+ {
+ "id": "msg-supervisor-1",
+ "role": "assistantGroup",
+ "agentId": "supervisor",
+ "content": "",
+ "parentId": "msg-user-1",
+ "createdAt": 1704067201000,
+ "updatedAt": 1704067201000,
+ "meta": {
+ "avatar": "supervisor",
+ "title": "Supervisor"
+ },
+ "children": [
+ {
+ "id": "msg-supervisor-1",
+ "content": "I'll ask the backend developer to explain the API design.",
+ "tools": [
+ {
+ "apiName": "speak",
+ "function": {
+ "arguments": "{\"agentId\": \"agent-backend\", \"instruction\": \"Please explain the API design.\"}",
+ "name": "speak"
+ },
+ "id": "call_speak_1",
+ "identifier": "lobe-group-management",
+ "result": {
+ "content": "Triggered agent \"agent-backend\" to respond.",
+ "id": "msg-speak-tool-1"
+ },
+ "result_msg_id": "msg-speak-tool-1",
+ "type": "function"
+ }
+ ]
+ }
+ ]
+ },
+ {
+ "id": "msg-agent-backend-1",
+ "role": "assistant",
+ "agentId": "agent-backend",
+ "content": "The API follows RESTful design principles. We have endpoints for users, products, and orders. Each endpoint supports CRUD operations with proper HTTP methods.",
+ "parentId": "msg-speak-tool-1",
+ "model": "gpt-4",
+ "provider": "openai",
+ "createdAt": 1704067205000,
+ "updatedAt": 1704067205000,
+ "meta": {
+ "avatar": "backend-dev",
+ "title": "Backend Developer"
+ }
+ }
+ ],
+ "messageMap": {
+ "msg-user-1": {
+ "id": "msg-user-1",
+ "role": "user",
+ "content": "Can you ask the backend developer about the API design?",
+ "parentId": null,
+ "createdAt": 1704067200000,
+ "updatedAt": 1704067200000,
+ "meta": {}
+ },
+ "msg-supervisor-1": {
+ "id": "msg-supervisor-1",
+ "role": "assistant",
+ "agentId": "supervisor",
+ "content": "I'll ask the backend developer to explain the API design.",
+ "parentId": "msg-user-1",
+ "tools": [
+ {
+ "id": "call_speak_1",
+ "type": "function",
+ "function": {
+ "name": "speak",
+ "arguments": "{\"agentId\": \"agent-backend\", \"instruction\": \"Please explain the API design.\"}"
+ },
+ "identifier": "lobe-group-management",
+ "apiName": "speak"
+ }
+ ],
+ "createdAt": 1704067201000,
+ "updatedAt": 1704067201000,
+ "meta": {
+ "avatar": "supervisor",
+ "title": "Supervisor"
+ }
+ },
+ "msg-speak-tool-1": {
+ "id": "msg-speak-tool-1",
+ "role": "tool",
+ "content": "Triggered agent \"agent-backend\" to respond.",
+ "parentId": "msg-supervisor-1",
+ "tool_call_id": "call_speak_1",
+ "createdAt": 1704067202000,
+ "updatedAt": 1704067202000,
+ "meta": {}
+ },
+ "msg-agent-backend-1": {
+ "id": "msg-agent-backend-1",
+ "role": "assistant",
+ "agentId": "agent-backend",
+ "content": "The API follows RESTful design principles. We have endpoints for users, products, and orders. Each endpoint supports CRUD operations with proper HTTP methods.",
+ "parentId": "msg-speak-tool-1",
+ "model": "gpt-4",
+ "provider": "openai",
+ "createdAt": 1704067205000,
+ "updatedAt": 1704067205000,
+ "meta": {
+ "avatar": "backend-dev",
+ "title": "Backend Developer"
+ }
+ }
+ }
+}
diff --git a/packages/conversation-flow/src/__tests__/fixtures/outputs/assistantGroup/tools-with-branches.json b/packages/conversation-flow/src/__tests__/fixtures/outputs/assistantGroup/tools-with-branches.json
index 2e0a1574d4d..1a6158c273a 100644
--- a/packages/conversation-flow/src/__tests__/fixtures/outputs/assistantGroup/tools-with-branches.json
+++ b/packages/conversation-flow/src/__tests__/fixtures/outputs/assistantGroup/tools-with-branches.json
@@ -122,11 +122,7 @@
"parentId": "msg-504",
"createdAt": 1704067210000,
"updatedAt": 1704067210000,
- "meta": {},
- "branch": {
- "activeBranchIndex": 0,
- "count": 2
- }
+ "meta": {}
},
{
"id": "msg-506",
@@ -141,6 +137,10 @@
"totalOutputTokens": 89,
"totalTokens": 245,
"cost": 0.000735
+ },
+ "branch": {
+ "activeBranchIndex": 0,
+ "count": 2
}
}
],
diff --git a/packages/conversation-flow/src/__tests__/fixtures/outputs/branch/active-index-1.json b/packages/conversation-flow/src/__tests__/fixtures/outputs/branch/active-index-1.json
index 5a4f731de41..be6437067c1 100644
--- a/packages/conversation-flow/src/__tests__/fixtures/outputs/branch/active-index-1.json
+++ b/packages/conversation-flow/src/__tests__/fixtures/outputs/branch/active-index-1.json
@@ -66,10 +66,6 @@
"meta": {},
"metadata": {
"activeBranchIndex": 1
- },
- "branch": {
- "activeBranchIndex": 1,
- "count": 3
}
},
{
@@ -85,6 +81,10 @@
"totalOutputTokens": 24,
"totalTokens": 36,
"cost": 0.000108
+ },
+ "branch": {
+ "activeBranchIndex": 1,
+ "count": 3
}
},
{
diff --git a/packages/conversation-flow/src/__tests__/fixtures/outputs/branch/assistant-branch.json b/packages/conversation-flow/src/__tests__/fixtures/outputs/branch/assistant-branch.json
index 9ee8c8ba26e..83be28076a4 100644
--- a/packages/conversation-flow/src/__tests__/fixtures/outputs/branch/assistant-branch.json
+++ b/packages/conversation-flow/src/__tests__/fixtures/outputs/branch/assistant-branch.json
@@ -82,6 +82,10 @@
"totalOutputTokens": 52,
"totalTokens": 82,
"cost": 0.00025
+ },
+ "branch": {
+ "activeBranchIndex": 1,
+ "count": 3
}
},
{
diff --git a/packages/conversation-flow/src/__tests__/fixtures/outputs/branch/assistant-group-branches.json b/packages/conversation-flow/src/__tests__/fixtures/outputs/branch/assistant-group-branches.json
index a2c0212664f..ec9b7182c3b 100644
--- a/packages/conversation-flow/src/__tests__/fixtures/outputs/branch/assistant-group-branches.json
+++ b/packages/conversation-flow/src/__tests__/fixtures/outputs/branch/assistant-group-branches.json
@@ -124,11 +124,7 @@
"fileList": [],
"imageList": [],
"meta": {},
- "videoList": [],
- "branch": {
- "activeBranchIndex": 1,
- "count": 3
- }
+ "videoList": []
},
{
"id": "msg_eEAXz3HLKeAmEQ",
@@ -162,7 +158,11 @@
"meta": {},
"model": "deepseek-chat",
"provider": "deepseek",
- "videoList": []
+ "videoList": [],
+ "branch": {
+ "activeBranchIndex": 1,
+ "count": 3
+ }
},
{
"id": "msg_nSG0QuSDSmYlXj",
diff --git a/packages/conversation-flow/src/__tests__/fixtures/outputs/branch/assistant-user-branch.json b/packages/conversation-flow/src/__tests__/fixtures/outputs/branch/assistant-user-branch.json
index d08d39eda8a..5567555c10d 100644
--- a/packages/conversation-flow/src/__tests__/fixtures/outputs/branch/assistant-user-branch.json
+++ b/packages/conversation-flow/src/__tests__/fixtures/outputs/branch/assistant-user-branch.json
@@ -81,6 +81,10 @@
},
{
"id": "msg-507",
+ "branch": {
+ "activeBranchIndex": 1,
+ "count": 2
+ },
"role": "user",
"content": "Can you explain the technical implementation details?",
"parentId": "msg-502",
diff --git a/packages/conversation-flow/src/__tests__/fixtures/outputs/branch/conversation.json b/packages/conversation-flow/src/__tests__/fixtures/outputs/branch/conversation.json
index 9ed1d3ea0ca..3f8bd95ca55 100644
--- a/packages/conversation-flow/src/__tests__/fixtures/outputs/branch/conversation.json
+++ b/packages/conversation-flow/src/__tests__/fixtures/outputs/branch/conversation.json
@@ -63,11 +63,7 @@
"parentId": null,
"createdAt": 1704067200000,
"updatedAt": 1704067200000,
- "meta": {},
- "branch": {
- "activeBranchIndex": 0,
- "count": 3
- }
+ "meta": {}
},
{
"id": "msg-202",
@@ -82,6 +78,10 @@
"totalOutputTokens": 28,
"totalTokens": 40,
"cost": 0.00012
+ },
+ "branch": {
+ "activeBranchIndex": 0,
+ "count": 3
}
},
{
diff --git a/packages/conversation-flow/src/__tests__/fixtures/outputs/branch/multi-assistant-group.json b/packages/conversation-flow/src/__tests__/fixtures/outputs/branch/multi-assistant-group.json
index 7ad2965bb0c..fef68d9a203 100644
--- a/packages/conversation-flow/src/__tests__/fixtures/outputs/branch/multi-assistant-group.json
+++ b/packages/conversation-flow/src/__tests__/fixtures/outputs/branch/multi-assistant-group.json
@@ -80,11 +80,7 @@
},
"parentId": null,
"role": "user",
- "updatedAt": 1704067200000,
- "branch": {
- "activeBranchIndex": 2,
- "count": 3
- }
+ "updatedAt": 1704067200000
},
{
"id": "msg-assistant-6",
@@ -94,6 +90,10 @@
"createdAt": 1704067240000,
"updatedAt": 1704067240000,
"meta": {},
+ "branch": {
+ "activeBranchIndex": 2,
+ "count": 3
+ },
"children": [
{
"content": "",
diff --git a/packages/conversation-flow/src/__tests__/fixtures/outputs/branch/nested.json b/packages/conversation-flow/src/__tests__/fixtures/outputs/branch/nested.json
index 3a4e72826c3..f7fc106e6db 100644
--- a/packages/conversation-flow/src/__tests__/fixtures/outputs/branch/nested.json
+++ b/packages/conversation-flow/src/__tests__/fixtures/outputs/branch/nested.json
@@ -111,11 +111,7 @@
"parentId": null,
"createdAt": 1704067200000,
"updatedAt": 1704067200000,
- "meta": {},
- "branch": {
- "activeBranchIndex": 0,
- "count": 3
- }
+ "meta": {}
},
{
"id": "msg-302",
@@ -130,6 +126,10 @@
"totalOutputTokens": 15,
"totalTokens": 25,
"cost": 0.00008
+ },
+ "branch": {
+ "activeBranchIndex": 0,
+ "count": 3
}
},
{
@@ -142,10 +142,6 @@
"meta": {},
"metadata": {
"activeBranchIndex": 1
- },
- "branch": {
- "activeBranchIndex": 1,
- "count": 2
}
},
{
@@ -161,6 +157,10 @@
"totalOutputTokens": 22,
"totalTokens": 52,
"cost": 0.00016
+ },
+ "branch": {
+ "activeBranchIndex": 1,
+ "count": 2
}
},
{
@@ -170,11 +170,7 @@
"parentId": "msg-307",
"createdAt": 1704067220000,
"updatedAt": 1704067220000,
- "meta": {},
- "branch": {
- "activeBranchIndex": 0,
- "count": 2
- }
+ "meta": {}
},
{
"id": "msg-311",
@@ -189,6 +185,10 @@
"totalOutputTokens": 16,
"totalTokens": 71,
"cost": 0.00021
+ },
+ "branch": {
+ "activeBranchIndex": 0,
+ "count": 2
}
},
{
@@ -201,10 +201,6 @@
"meta": {},
"metadata": {
"activeBranchIndex": 1
- },
- "branch": {
- "activeBranchIndex": 1,
- "count": 2
}
},
{
@@ -220,6 +216,10 @@
"totalOutputTokens": 42,
"totalTokens": 117,
"cost": 0.00035
+ },
+ "branch": {
+ "activeBranchIndex": 1,
+ "count": 2
}
}
],
diff --git a/packages/conversation-flow/src/__tests__/parse.test.ts b/packages/conversation-flow/src/__tests__/parse.test.ts
index 01fc11c1e8e..1e6bc40c166 100644
--- a/packages/conversation-flow/src/__tests__/parse.test.ts
+++ b/packages/conversation-flow/src/__tests__/parse.test.ts
@@ -99,6 +99,32 @@ describe('parse', () => {
});
});
+ describe('AgentCouncil Mode', () => {
+ it('should parse simple agentCouncil (broadcast) correctly', () => {
+ const result = parse(inputs.agentCouncil.simple);
+
+ expect(serializeParseResult(result)).toEqual(outputs.agentCouncil.simple);
+ });
+
+ it('should parse agentCouncil with supervisor final reply correctly', () => {
+ const result = parse(inputs.agentCouncil.withSupervisorReply);
+
+ // The critical assertions:
+ // 1. flatList should have 4 items: user, assistantGroup(supervisor+tool), agentCouncil(3 agents), supervisor-summary
+ expect(result.flatList).toHaveLength(4);
+ expect(result.flatList[0].role).toBe('user');
+ expect(result.flatList[1].role).toBe('assistantGroup');
+ expect(result.flatList[2].role).toBe('agentCouncil');
+ expect(result.flatList[3].role).toBe('assistant'); // supervisor final reply
+ expect(result.flatList[3].id).toBe('msg-supervisor-summary');
+
+ // 2. agentCouncil should have 3 members (not 4, supervisor summary is separate)
+ expect((result.flatList[2] as any).members).toHaveLength(3);
+
+ expect(serializeParseResult(result)).toEqual(outputs.agentCouncil.withSupervisorReply);
+ });
+ });
+
describe('Assistant Group Scenarios', () => {
it('should handle tools with assistant branches correctly', () => {
const result = parse(inputs.assistantGroup.toolsWithBranches);
@@ -107,6 +133,28 @@ describe('parse', () => {
});
});
+ describe('Agent Group Scenarios', () => {
+ it('should not aggregate messages from different agents into same AssistantGroup', () => {
+ const result = parse(inputs.agentGroup.speakDifferentAgent);
+
+ // The critical assertions:
+ // 1. flatList should have 3 items: user, assistantGroup(supervisor+tool), agent-backend response
+ expect(result.flatList).toHaveLength(3);
+ expect(result.flatList[0].role).toBe('user');
+ expect(result.flatList[1].role).toBe('assistantGroup');
+ expect(result.flatList[2].role).toBe('assistant');
+
+ // 2. The agent-backend response should be separate (different agentId)
+ expect(result.flatList[2].id).toBe('msg-agent-backend-1');
+ expect((result.flatList[2] as any).agentId).toBe('agent-backend');
+
+ // 3. The supervisor's assistantGroup should only contain supervisor messages
+ expect((result.flatList[1] as any).agentId).toBe('supervisor');
+
+ expect(serializeParseResult(result)).toEqual(outputs.agentGroup.speakDifferentAgent);
+ });
+ });
+
describe('Performance', () => {
it('should parse 10000 items within 50ms', () => {
// Generate 10000 messages as flat siblings (no deep nesting to avoid stack overflow)
diff --git a/packages/conversation-flow/src/transformation/ContextTreeBuilder.ts b/packages/conversation-flow/src/transformation/ContextTreeBuilder.ts
index 6143f1d239a..215344c9636 100644
--- a/packages/conversation-flow/src/transformation/ContextTreeBuilder.ts
+++ b/packages/conversation-flow/src/transformation/ContextTreeBuilder.ts
@@ -1,4 +1,5 @@
import type {
+ AgentCouncilNode,
AssistantGroupNode,
BranchNode,
CompareNode,
@@ -16,7 +17,7 @@ import type { MessageCollector } from './MessageCollector';
*
* Handles:
* 1. Tree traversal with priority-based node type detection
- * 2. Creating different types of ContextNodes (Message, Branch, Compare, AssistantGroup)
+ * 2. Creating different types of ContextNodes (Message, Branch, Compare, AssistantGroup, AgentCouncil)
* 3. Linear array output of the tree structure
*/
export class ContextTreeBuilder {
@@ -93,7 +94,23 @@ export class ContextTreeBuilder {
return;
}
- // Priority 3: AssistantGroup (assistant + tools)
+ // Priority 3: AgentCouncil mode (from message metadata, typically on tool messages)
+ if (this.isAgentCouncilMode(message) && idNode.children.length > 1) {
+ // Create agent council node with children
+ const agentCouncilNode = this.createAgentCouncilNodeFromChildren(message, idNode);
+ contextTree.push(agentCouncilNode);
+
+ // Continue processing children of the last member (for supervisor final reply)
+ // The supervisor's reply has parentId pointing to the last agent's message
+ const lastChild = idNode.children.at(-1);
+ if (lastChild && lastChild.children.length > 0) {
+ // Process the first child of the last agent (supervisor's reply)
+ this.transformToLinear(lastChild.children[0], contextTree);
+ }
+ return;
+ }
+
+ // Priority 4: AssistantGroup (assistant + tools)
if (this.isAssistantGroupNode(message, idNode)) {
const assistantGroupNode = this.createAssistantGroupNode(message, idNode);
contextTree.push(assistantGroupNode);
@@ -106,7 +123,7 @@ export class ContextTreeBuilder {
return;
}
- // Priority 4: Branch (multiple children)
+ // Priority 6: Branch (multiple children)
if (idNode.children.length > 1) {
// Add current message node
const messageNode = this.createMessageNode(message);
@@ -120,7 +137,7 @@ export class ContextTreeBuilder {
return;
}
- // Priority 5: Regular message
+ // Priority 7: Regular message
const messageNode = this.createMessageNode(message);
contextTree.push(messageNode);
@@ -137,6 +154,14 @@ export class ContextTreeBuilder {
return (message.metadata as any)?.compare === true;
}
+ /**
+ * Check if message has agentCouncil mode in metadata
+ * Used for multi-agent parallel responses (broadcast scenario)
+ */
+ private isAgentCouncilMode(message: Message): boolean {
+ return (message.metadata as any)?.agentCouncil === true;
+ }
+
/**
* Check if this is Assistant + Tools pattern
*/
@@ -294,4 +319,32 @@ export class ContextTreeBuilder {
type: 'compare',
};
}
+
+ /**
+ * Create AgentCouncilNode from children messages
+ * Similar to CompareNode but without activeColumnId (all members enter context)
+ */
+ private createAgentCouncilNodeFromChildren(message: Message, idNode: IdNode): AgentCouncilNode {
+ // Each child is a member - process to handle potential AssistantGroup
+ const members = idNode.children.map((child) => {
+ const childMessage = this.messageMap.get(child.id);
+ if (!childMessage) {
+ return { id: child.id, type: 'message' } as MessageNode;
+ }
+
+ // Check if this member should be an AssistantGroup (agent with tool calls)
+ if (this.isAssistantGroupNode(childMessage, child)) {
+ return this.createAssistantGroupNode(childMessage, child);
+ }
+
+ // Otherwise, just a simple MessageNode
+ return { id: child.id, type: 'message' } as MessageNode;
+ });
+
+ // Generate ID by joining parent message id and all member message ids
+ const memberIds = idNode.children.map((child) => child.id).join('-');
+ const agentCouncilId = `agentCouncil-${message.id}-${memberIds}`;
+
+ return { id: agentCouncilId, members, messageId: message.id, type: 'agentCouncil' };
+ }
}
diff --git a/packages/conversation-flow/src/transformation/FlatListBuilder.ts b/packages/conversation-flow/src/transformation/FlatListBuilder.ts
index 23e207c2680..f8fc05ab107 100644
--- a/packages/conversation-flow/src/transformation/FlatListBuilder.ts
+++ b/packages/conversation-flow/src/transformation/FlatListBuilder.ts
@@ -48,6 +48,30 @@ export class FlatListBuilder {
): void {
const children = this.childrenMap.get(parentId) ?? [];
+ // Pre-loop check: AgentCouncil mode on parent (tool message with multiple assistant children)
+ // This handles the case when we continue from a tool message that triggered broadcast
+ if (parentId) {
+ const parentMessage = this.messageMap.get(parentId);
+ if (parentMessage && this.isAgentCouncilMode(parentMessage) && children.length > 1) {
+ // Create agentCouncil virtual message from the parent tool message
+ const agentCouncilMessage = this.createAgentCouncilMessageFromChildIds(
+ parentMessage,
+ children,
+ allMessages,
+ processedIds,
+ );
+ flatList.push(agentCouncilMessage);
+
+ // Continue processing children of the last member (for supervisor final reply)
+ // The last member's children should be processed next
+ const lastMemberId = children.at(-1);
+ if (lastMemberId) {
+ this.buildFlatListRecursive(lastMemberId, flatList, processedIds, allMessages);
+ }
+ return;
+ }
+ }
+
for (const childId of children) {
if (processedIds.has(childId)) continue;
@@ -158,7 +182,24 @@ export class FlatListBuilder {
continue;
}
- // Priority 3b: User message with branches
+ // Priority 3b: AgentCouncil mode (from message metadata, typically on tool messages)
+ if (this.isAgentCouncilMode(message) && childMessages.length > 1) {
+ // Create agentCouncil virtual message with proper handling of AssistantGroups
+ const agentCouncilMessage = this.createAgentCouncilMessageFromChildIds(
+ message,
+ childMessages,
+ allMessages,
+ processedIds,
+ );
+ flatList.push(agentCouncilMessage);
+
+ // AgentCouncil doesn't continue - all columns are parallel endpoints
+ // The conversation continues after the supervisor completes orchestration
+ continue;
+ }
+
+ // Priority 3d: User message with branches (multiple assistant children)
+ // Branch indicator should be on the active assistant child message
if (message.role === 'user' && childMessages.length > 1) {
const activeBranchId = this.branchResolver.getActiveBranchIdFromMetadata(
message,
@@ -174,15 +215,12 @@ export class FlatListBuilder {
continue;
}
- const activeBranchIndex = childMessages.indexOf(activeBranchId);
- const userWithBranches = this.createUserMessageWithBranches(
- message,
- childMessages.length,
- activeBranchIndex,
- );
- flatList.push(userWithBranches);
+ // Add user message without branch (branch goes on the child)
+ flatList.push(message);
processedIds.add(message.id);
+ const activeBranchIndex = childMessages.indexOf(activeBranchId);
+
// Continue with active branch - check if it's an assistantGroup
const activeBranchMsg = this.messageMap.get(activeBranchId);
if (activeBranchMsg) {
@@ -203,13 +241,19 @@ export class FlatListBuilder {
processedIds,
);
- // Create assistantGroup virtual message
+ // Create assistantGroup virtual message with branch metadata
const groupMessage = this.createAssistantGroupMessage(
assistantChain[0],
assistantChain,
allToolMessages,
);
- flatList.push(groupMessage);
+ // Add branch info to the assistantGroup message
+ const groupMessageWithBranches = this.createMessageWithBranches(
+ groupMessage,
+ childMessages.length,
+ activeBranchIndex,
+ );
+ flatList.push(groupMessageWithBranches);
// Mark all as processed
assistantChain.forEach((m) => processedIds.add(m.id));
@@ -235,8 +279,13 @@ export class FlatListBuilder {
}
}
} else {
- // Regular message (not assistantGroup)
- flatList.push(activeBranchMsg);
+ // Regular assistant message (not assistantGroup) - add branch info
+ const activeBranchWithBranches = this.createMessageWithBranches(
+ activeBranchMsg,
+ childMessages.length,
+ activeBranchIndex,
+ );
+ flatList.push(activeBranchWithBranches);
processedIds.add(activeBranchId);
// Continue with active branch's children
@@ -246,27 +295,39 @@ export class FlatListBuilder {
continue;
}
- // Priority 3c: Assistant message with branches
+ // Priority 3e: Assistant message with branches (multiple user children)
+ // Branch indicator should be on the active user child message
if (message.role === 'assistant' && childMessages.length > 1) {
const activeBranchId = this.branchResolver.getActiveBranchIdFromMetadata(
message,
childMessages,
this.childrenMap,
);
- // Add the assistant message itself
- flatList.push(message);
- processedIds.add(message.id);
// Optimistic update: activeBranchId is undefined when branch is being created
- // In this case, just add assistant message and continue (no active branch yet)
+ // In this case, just add assistant message without branch info and continue
if (!activeBranchId) {
+ flatList.push(message);
+ processedIds.add(message.id);
continue;
}
- // Continue with active branch and process its message
+ // Add the assistant message without branch (branch goes on the child)
+ flatList.push(message);
+ processedIds.add(message.id);
+
+ const activeBranchIndex = childMessages.indexOf(activeBranchId);
+
+ // Continue with active branch and add branch info to the user child
const activeBranchMsg = this.messageMap.get(activeBranchId);
if (activeBranchMsg) {
- flatList.push(activeBranchMsg);
+ // Add branch info to the active user child message
+ const activeBranchWithBranches = this.createMessageWithBranches(
+ activeBranchMsg,
+ childMessages.length,
+ activeBranchIndex,
+ );
+ flatList.push(activeBranchWithBranches);
processedIds.add(activeBranchId);
// Continue with active branch's children
@@ -291,6 +352,14 @@ export class FlatListBuilder {
return (message.metadata as any)?.compare === true;
}
+ /**
+ * Check if message has agentCouncil mode in metadata
+ * Used for multi-agent parallel responses (broadcast scenario)
+ */
+ private isAgentCouncilMode(message: Message): boolean {
+ return (message.metadata as any)?.agentCouncil === true;
+ }
+
/**
* Create compare virtual message from child IDs with AssistantGroup support
*/
@@ -384,6 +453,94 @@ export class FlatListBuilder {
} as Message;
}
+ /**
+ * Create agentCouncil virtual message from child IDs with AssistantGroup support
+ * Each member is a single message (not an array)
+ */
+ private createAgentCouncilMessageFromChildIds(
+ parentMessage: Message,
+ childIds: string[],
+ allMessages: Message[],
+ processedIds: Set<string>,
+ ): Message {
+ const members: Message[] = [];
+ const memberIds: string[] = [];
+
+ // Process each child (member)
+ for (const childId of childIds) {
+ const childMessage = this.messageMap.get(childId);
+ if (!childMessage) continue;
+
+ memberIds.push(childId);
+
+ // Check if this child is an AssistantGroup (agent with tool calls)
+ if (
+ childMessage.role === 'assistant' &&
+ childMessage.tools &&
+ childMessage.tools.length > 0
+ ) {
+ // Collect the entire assistant group chain for this member
+ const assistantChain: Message[] = [];
+ const allToolMessages: Message[] = [];
+ const memberProcessedIds = new Set<string>();
+
+ this.messageCollector.collectAssistantChain(
+ childMessage,
+ allMessages,
+ assistantChain,
+ allToolMessages,
+ memberProcessedIds,
+ );
+
+ // Create assistantGroup virtual message for this member
+ const groupMessage = this.createAssistantGroupMessage(
+ assistantChain[0],
+ assistantChain,
+ allToolMessages,
+ );
+
+ members.push(groupMessage);
+
+ // Mark all as processed
+ assistantChain.forEach((m) => processedIds.add(m.id));
+ allToolMessages.forEach((m) => processedIds.add(m.id));
+ } else {
+ // Regular message (not an AssistantGroup)
+ members.push(childMessage);
+ processedIds.add(childId);
+ }
+ }
+
+ // Generate ID with all member message IDs
+ const memberIdsStr = memberIds.join('-');
+ const agentCouncilId = `agentCouncil-${parentMessage.id}-${memberIdsStr}`;
+
+ // Calculate timestamps from all member messages
+ const allMemberMessages = childIds.map((id) => this.messageMap.get(id)).filter(Boolean);
+ const createdAt =
+ allMemberMessages.length > 0
+ ? Math.min(...allMemberMessages.map((m) => m!.createdAt))
+ : parentMessage.createdAt;
+ const updatedAt =
+ allMemberMessages.length > 0
+ ? Math.max(...allMemberMessages.map((m) => m!.updatedAt))
+ : parentMessage.updatedAt;
+
+ return {
+ content: '',
+ createdAt,
+ extra: {
+ parentMessageId: parentMessage.id,
+ },
+ id: agentCouncilId,
+ // members is a flat array of messages (not nested arrays)
+ members: members as any,
+ meta: parentMessage.meta || {},
+ role: 'agentCouncil' as any,
+ updatedAt,
+ } as Message;
+ }
+
/**
* Create compare virtual message (for group-based compare)
*/
@@ -500,6 +657,8 @@ export class FlatListBuilder {
} as AssistantContentBlock;
if (assistant.error) childBlock.error = assistant.error;
+ if (assistant.fileList && assistant.fileList.length > 0)
+ childBlock.fileList = assistant.fileList;
if (assistant.imageList && assistant.imageList.length > 0)
childBlock.imageList = assistant.imageList;
if (msgPerformance) childBlock.performance = msgPerformance;
@@ -563,15 +722,16 @@ export class FlatListBuilder {
}
/**
- * Create user message with branch metadata
+ * Create message with branch metadata
+ * Used for both user and assistant messages that have multiple branches
*/
- private createUserMessageWithBranches(
- user: Message,
+ private createMessageWithBranches(
+ message: Message,
count: number,
activeBranchIndex: number,
): Message {
return {
- ...user,
+ ...message,
branch: {
activeBranchIndex,
count,
diff --git a/packages/conversation-flow/src/transformation/MessageCollector.ts b/packages/conversation-flow/src/transformation/MessageCollector.ts
index e9ea1c301f7..b6c6aa85516 100644
--- a/packages/conversation-flow/src/transformation/MessageCollector.ts
+++ b/packages/conversation-flow/src/transformation/MessageCollector.ts
@@ -35,6 +35,7 @@ export class MessageCollector {
/**
* Recursively collect the entire assistant chain
* (assistant -> tools -> assistant -> tools -> ...)
+ * Only collects messages from the SAME agent (matching agentId)
*/
collectAssistantChain(
currentAssistant: Message,
@@ -48,17 +49,34 @@ export class MessageCollector {
// Add current assistant to chain
assistantChain.push(currentAssistant);
+ // Get the agentId of the first assistant in the chain (the group owner)
+ const groupAgentId = assistantChain[0].agentId;
+
// Collect its tool messages
const toolMessages = this.collectToolMessages(currentAssistant, allMessages);
allToolMessages.push(...toolMessages);
// Find next assistant after tools
for (const toolMsg of toolMessages) {
+ // Stop if tool message has agentCouncil mode - its children belong to AgentCouncil
+ if ((toolMsg.metadata as any)?.agentCouncil === true) {
+ continue;
+ }
+
const nextMessages = allMessages.filter((m) => m.parentId === toolMsg.id);
for (const nextMsg of nextMessages) {
- if (nextMsg.role === 'assistant' && nextMsg.tools && nextMsg.tools.length > 0) {
- // Continue the chain
+ // Only continue if the next assistant has the SAME agentId
+ // Different agentId means it's a different agent responding (e.g., via speak tool)
+ const isSameAgent = nextMsg.agentId === groupAgentId;
+
+ if (
+ nextMsg.role === 'assistant' &&
+ nextMsg.tools &&
+ nextMsg.tools.length > 0 &&
+ isSameAgent
+ ) {
+ // Continue the chain only for same agent
this.collectAssistantChain(
nextMsg,
allMessages,
@@ -67,23 +85,29 @@ export class MessageCollector {
processedIds,
);
return;
- } else if (nextMsg.role === 'assistant') {
- // Final assistant without tools
+ } else if (nextMsg.role === 'assistant' && isSameAgent) {
+ // Final assistant without tools (same agent)
assistantChain.push(nextMsg);
return;
}
+ // If different agentId, don't add to chain - let it be processed separately
}
}
}
/**
* Recursively collect assistant messages for an AssistantGroup (contextTree version)
+ * Only collects messages from the SAME agent (matching agentId)
*/
collectAssistantGroupMessages(
message: Message,
idNode: IdNode,
children: ContextNode[],
+ groupAgentId?: string,
): void {
+ // Get the agentId of the first assistant in the group (the group owner)
+ const agentId = groupAgentId ?? message.agentId;
+
// Get tool message IDs if this assistant has tools
const toolIds = idNode.children
.filter((child) => {
@@ -107,14 +131,20 @@ export class MessageCollector {
const toolMsg = this.messageMap.get(toolNode.id);
if (toolMsg?.role !== 'tool') continue;
+ // Stop if tool message has agentCouncil mode - its children belong to AgentCouncil
+ if ((toolMsg.metadata as any)?.agentCouncil === true) {
+ continue;
+ }
+
// Check if tool has an assistant child
if (toolNode.children.length > 0) {
const nextChild = toolNode.children[0];
const nextMsg = this.messageMap.get(nextChild.id);
- if (nextMsg?.role === 'assistant') {
- // Recursively collect this assistant and its descendants
- this.collectAssistantGroupMessages(nextMsg, nextChild, children);
+ // Only continue if the next assistant has the SAME agentId
+ if (nextMsg?.role === 'assistant' && nextMsg.agentId === agentId) {
+ // Recursively collect this assistant and its descendants (same agent only)
+ this.collectAssistantGroupMessages(nextMsg, nextChild, children, agentId);
return; // Only follow one path
}
}
@@ -125,9 +155,19 @@ export class MessageCollector {
* Find next message after tools in an assistant group
*/
findNextAfterTools(assistantMsg: Message, idNode: IdNode): IdNode | null {
- // Recursively find the last message in the assistant group
- const lastNode = this.findLastNodeInAssistantGroup(idNode);
- if (lastNode && lastNode.children.length > 0) {
+ // Recursively find the last message in the assistant group (same agentId only)
+ const lastNode = this.findLastNodeInAssistantGroup(idNode, assistantMsg.agentId);
+ if (!lastNode) return null;
+
+ // Check if lastNode is a tool with agentCouncil mode
+ // In this case, return the tool node itself so ContextTreeBuilder can process it
+ const lastMsg = this.messageMap.get(lastNode.id);
+ if (lastMsg?.role === 'tool' && (lastMsg.metadata as any)?.agentCouncil === true) {
+ return lastNode;
+ }
+
+ // Otherwise, return the first child of the last node
+ if (lastNode.children.length > 0) {
return lastNode.children[0];
}
return null;
@@ -135,8 +175,9 @@ export class MessageCollector {
/**
* Find the last node in an AssistantGroup sequence
+ * Only follows messages from the SAME agent (matching agentId)
*/
- findLastNodeInAssistantGroup(idNode: IdNode): IdNode | null {
+ findLastNodeInAssistantGroup(idNode: IdNode, groupAgentId?: string): IdNode | null {
// Check if has tool children
const toolChildren = idNode.children.filter((child) => {
const childMsg = this.messageMap.get(child.id);
@@ -147,20 +188,28 @@ export class MessageCollector {
return idNode;
}
- // Check if any tool has an assistant child
+ // Check if any tool has an assistant child with the same agentId
for (const toolNode of toolChildren) {
+ const toolMsg = this.messageMap.get(toolNode.id);
+
+ // Stop if tool message has agentCouncil mode - its children belong to AgentCouncil
+ if ((toolMsg?.metadata as any)?.agentCouncil === true) {
+ continue;
+ }
+
if (toolNode.children.length > 0) {
const nextChild = toolNode.children[0];
const nextMsg = this.messageMap.get(nextChild.id);
- if (nextMsg?.role === 'assistant') {
- // Continue following the assistant chain
- return this.findLastNodeInAssistantGroup(nextChild);
+ // Only continue if the next assistant has the SAME agentId
+ if (nextMsg?.role === 'assistant' && nextMsg.agentId === groupAgentId) {
+ // Continue following the assistant chain (same agent only)
+ return this.findLastNodeInAssistantGroup(nextChild, groupAgentId);
}
}
}
- // No more assistant messages, return the last tool node
+ // No more assistant messages from the same agent, return the last tool node
return toolChildren.at(-1) ?? null;
}
}
diff --git a/packages/conversation-flow/src/transformation/MessageTransformer.ts b/packages/conversation-flow/src/transformation/MessageTransformer.ts
index 799012c47a8..89297869614 100644
--- a/packages/conversation-flow/src/transformation/MessageTransformer.ts
+++ b/packages/conversation-flow/src/transformation/MessageTransformer.ts
@@ -20,6 +20,7 @@ export class MessageTransformer {
return {
content: message.content || '',
error: message.error,
+ fileList: message.fileList,
id: message.id,
imageList: message.imageList,
performance,
diff --git a/packages/conversation-flow/src/types/contextTree.ts b/packages/conversation-flow/src/types/contextTree.ts
index e027d97a0d9..71a600455f5 100644
--- a/packages/conversation-flow/src/types/contextTree.ts
+++ b/packages/conversation-flow/src/types/contextTree.ts
@@ -12,7 +12,7 @@ interface BaseNode {
/** Unique identifier for this node */
id: string;
/** Type discriminator */
- type: 'message' | 'assistantGroup' | 'compare' | 'branch';
+ type: 'message' | 'assistantGroup' | 'compare' | 'branch' | 'agentCouncil';
}
/**
@@ -59,7 +59,24 @@ export interface BranchNode extends BaseNode {
type: 'branch';
}
+/**
+ * Agent Council node - renders multiple agent responses in parallel
+ * Unlike CompareNode, all responses enter LLM context (no selection needed)
+ */
+export interface AgentCouncilNode extends BaseNode {
+ /** Each member represents a single agent's response (simple ContextNode, not array) */
+ members: ContextNode[];
+ /** The message that triggered the council (typically a tool message) */
+ messageId: string;
+ type: 'agentCouncil';
+}
+
/**
* Union type of all display nodes
*/
-export type ContextNode = MessageNode | AssistantGroupNode | CompareNode | BranchNode;
+export type ContextNode =
+ | MessageNode
+ | AssistantGroupNode
+ | CompareNode
+ | BranchNode
+ | AgentCouncilNode;
diff --git a/packages/conversation-flow/src/types/flatMessageList.ts b/packages/conversation-flow/src/types/flatMessageList.ts
index 79436c2a6da..d0c177e9cb5 100644
--- a/packages/conversation-flow/src/types/flatMessageList.ts
+++ b/packages/conversation-flow/src/types/flatMessageList.ts
@@ -21,6 +21,7 @@ import type { UIChatMessage } from '@lobechat/types';
* - 'assistantGroup': Assistant message + tool calls aggregation
* - 'messageGroup': Generic message group (manual/summary)
* - 'compare': Compare mode for parallel model outputs
+ * - 'agentCouncil': Multi-agent parallel responses (all enter context)
*/
export type FlatMessageRole =
| 'user'
@@ -30,7 +31,8 @@ export type FlatMessageRole =
| 'supervisor'
| 'assistantGroup'
| 'messageGroup'
- | 'compare';
+ | 'compare'
+ | 'agentCouncil';
/**
* Message in flat list
diff --git a/packages/conversation-flow/src/types/index.ts b/packages/conversation-flow/src/types/index.ts
index 4b9a5781449..6922e855453 100644
--- a/packages/conversation-flow/src/types/index.ts
+++ b/packages/conversation-flow/src/types/index.ts
@@ -11,6 +11,7 @@
// Context Tree Types
export type {
+ AgentCouncilNode,
AssistantGroupNode,
BranchNode,
CompareNode,
diff --git a/src/tools/knowledge-base/ExecutionRuntime/index.ts b/src/tools/knowledge-base/ExecutionRuntime/index.ts
index f702c82f972..32cb320c86d 100644
--- a/src/tools/knowledge-base/ExecutionRuntime/index.ts
+++ b/src/tools/knowledge-base/ExecutionRuntime/index.ts
@@ -1,96 +1,25 @@
-import { formatSearchResults, promptFileContents, promptNoSearchResults } from '@lobechat/prompts';
-import { BuiltinServerRuntimeOutput } from '@lobechat/types';
+import { KnowledgeBaseExecutionRuntime as BaseKnowledgeBaseExecutionRuntime } from '@lobechat/builtin-tool-knowledge-base/executionRuntime';
+import type { ReadKnowledgeArgs, SearchKnowledgeBaseArgs } from '@lobechat/builtin-tool-knowledge-base';
import { ragService } from '@/services/rag';
-import { ReadKnowledgeState, SearchKnowledgeBaseArgs, SearchKnowledgeBaseState } from '../type';
-
-export interface ReadKnowledgeArgs {
- fileIds: string[];
-}
+// Create a factory that returns an instance with ragService injected
+export class KnowledgeBaseExecutionRuntime extends BaseKnowledgeBaseExecutionRuntime {
+ constructor() {
+ super(ragService);
+ }
-export class KnowledgeBaseExecutionRuntime {
- /**
- * Search knowledge base and return file summaries with relevant chunks
- */
- async searchKnowledgeBase(
+ searchKnowledgeBase(
args: SearchKnowledgeBaseArgs,
- options?: {
- knowledgeBaseIds?: string[];
- messageId?: string;
- signal?: AbortSignal;
- },
- ): Promise<BuiltinServerRuntimeOutput> {
- try {
- const { query, topK = 20 } = args;
-
- // Only search in knowledge bases, not agent files
- // Agent files will be injected as full content in context-engine
- const { chunks, fileResults } = await ragService.semanticSearchForChat(
- { knowledgeIds: options?.knowledgeBaseIds, query, topK },
- options?.signal,
- );
-
- if (chunks.length === 0) {
- const state: SearchKnowledgeBaseState = { chunks: [], fileResults: [], totalResults: 0 };
-
- return { content: promptNoSearchResults(query), state, success: true };
- }
-
- // Format search results for AI
- const formattedContent = formatSearchResults(fileResults, query);
-
- const state: SearchKnowledgeBaseState = { chunks, fileResults, totalResults: chunks.length };
-
- return { content: formattedContent, state, success: true };
- } catch (e) {
- return {
- content: `Error searching knowledge base: ${(e as Error).message}`,
- error: e,
- success: false,
- };
- }
+ options?: Parameters<BaseKnowledgeBaseExecutionRuntime['searchKnowledgeBase']>[1],
+ ) {
+ return super.searchKnowledgeBase(args, options);
}
- /**
- * Read full content of specific files from knowledge base
- */
- async readKnowledge(
- args: ReadKnowledgeArgs,
- options?: { signal?: AbortSignal },
- ): Promise<BuiltinServerRuntimeOutput> {
- try {
- const { fileIds } = args;
-
- if (!fileIds || fileIds.length === 0) {
- return {
- content: 'Error: No file IDs provided',
- success: false,
- };
- }
-
- const fileContents = await ragService.getFileContents(fileIds, options?.signal);
-
- const formattedContent = promptFileContents(fileContents);
-
- const state: ReadKnowledgeState = {
- files: fileContents.map((file) => ({
- error: file.error,
- fileId: file.fileId,
- filename: file.filename,
- preview: file.preview,
- totalCharCount: file.totalCharCount,
- totalLineCount: file.totalLineCount,
- })),
- };
-
- return { content: formattedContent, state, success: true };
- } catch (e) {
- return {
- content: `Error reading knowledge: ${(e as Error).message}`,
- error: e,
- success: false,
- };
- }
+ readKnowledge(args: ReadKnowledgeArgs, options?: Parameters<BaseKnowledgeBaseExecutionRuntime['readKnowledge']>[1]) {
+ return super.readKnowledge(args, options);
}
}
+
+// Re-export types for convenience
+export type { ReadKnowledgeArgs, SearchKnowledgeBaseArgs } from '@lobechat/builtin-tool-knowledge-base';
diff --git a/src/tools/knowledge-base/Render/ReadKnowledge/index.tsx b/src/tools/knowledge-base/Render/ReadKnowledge/index.tsx
index 4b2a11df15a..79dbf8499c0 100644
--- a/src/tools/knowledge-base/Render/ReadKnowledge/index.tsx
+++ b/src/tools/knowledge-base/Render/ReadKnowledge/index.tsx
@@ -1,25 +1,27 @@
+'use client';
+
+import { ReadKnowledge as BaseReadKnowledge } from '@lobechat/builtin-tool-knowledge-base/client';
import { BuiltinRenderProps } from '@lobechat/types';
import { memo } from 'react';
-import { Flexbox } from 'react-layout-kit';
+import { useTranslation } from 'react-i18next';
+
+import FileIcon from '@/components/FileIcon';
-import { ReadKnowledgeArgs } from '../../ExecutionRuntime';
-import { ReadKnowledgeState } from '../../type';
-import FileCard from './FileCard';
+import type { ReadKnowledgeArgs, ReadKnowledgeState } from '../../index';
const ReadKnowledge = memo<BuiltinRenderProps<ReadKnowledgeArgs, ReadKnowledgeState>>(
({ pluginState }) => {
- const { files } = pluginState || {};
-
- if (!files || files.length === 0) {
- return null;
- }
+ const { t } = useTranslation('tool');
return (
- <Flexbox gap={12} horizontal style={{ flexWrap: 'wrap' }}>
- {files.map((file) => (
- <FileCard file={file} key={file.fileId} />
- ))}
- </Flexbox>
+ <BaseReadKnowledge
+ FileIcon={FileIcon}
+ labels={{
+ chars: t('lobe-knowledge-base.readKnowledge.meta.chars'),
+ lines: t('lobe-knowledge-base.readKnowledge.meta.lines'),
+ }}
+ pluginState={pluginState}
+ />
);
},
);
diff --git a/src/tools/knowledge-base/Render/SearchKnowledgeBase/Item/index.tsx b/src/tools/knowledge-base/Render/SearchKnowledgeBase/Item/index.tsx
deleted file mode 100644
index 19ba51b2280..00000000000
--- a/src/tools/knowledge-base/Render/SearchKnowledgeBase/Item/index.tsx
+++ /dev/null
@@ -1,54 +0,0 @@
-import { FileSearchResult } from '@lobechat/types';
-import { Text, Tooltip } from '@lobehub/ui';
-import { memo } from 'react';
-import { Center, Flexbox } from 'react-layout-kit';
-
-import FileIcon from '@/components/FileIcon';
-import { useIsMobile } from '@/hooks/useIsMobile';
-import { useChatStore } from '@/store/chat';
-
-import { useStyles } from './style';
-
-export interface FileItemProps extends FileSearchResult {
- index: number;
-}
-
-const FileItem = memo<FileItemProps>(({ fileId, fileName, relevanceScore, topChunks }) => {
- const { styles, cx } = useStyles();
- const openFilePreview = useChatStore((s) => s.openFilePreview);
-
- const isMobile = useIsMobile();
-
- // Use the first chunk for preview
- const firstChunk = topChunks[0];
-
- return (
- <Flexbox
- align={'center'}
- className={cx(styles.container, isMobile && styles.mobile)}
- gap={4}
- horizontal
- key={fileId}
- onClick={(e) => {
- e.stopPropagation();
- if (firstChunk) {
- openFilePreview({
- chunkId: firstChunk.id,
- chunkText: firstChunk.text,
- fileId,
- });
- }
- }}
- >
- <FileIcon fileName={fileName} size={20} variant={'raw'} />
- <Flexbox gap={12} horizontal justify={'space-between'} style={{ maxWidth: 200 }}>
- <Text ellipsis>{fileName}</Text>
- <Tooltip title={`Relevance: ${(relevanceScore * 100).toFixed(1)}%`}>
- <Center className={styles.badge}>{relevanceScore.toFixed(2)}</Center>
- </Tooltip>
- </Flexbox>
- </Flexbox>
- );
-});
-
-export default FileItem;
diff --git a/src/tools/knowledge-base/Render/SearchKnowledgeBase/index.tsx b/src/tools/knowledge-base/Render/SearchKnowledgeBase/index.tsx
index b056c9c3e13..e49c462286a 100644
--- a/src/tools/knowledge-base/Render/SearchKnowledgeBase/index.tsx
+++ b/src/tools/knowledge-base/Render/SearchKnowledgeBase/index.tsx
@@ -1,22 +1,28 @@
+'use client';
+
+import { SearchKnowledgeBase as BaseSearchKnowledgeBase } from '@lobechat/builtin-tool-knowledge-base/client';
import { BuiltinRenderProps } from '@lobechat/types';
import { memo } from 'react';
-import { Flexbox } from 'react-layout-kit';
-import { SearchKnowledgeBaseArgs, SearchKnowledgeBaseState } from '@/tools/knowledge-base/type';
+import FileIcon from '@/components/FileIcon';
+import { useIsMobile } from '@/hooks/useIsMobile';
+import { useChatStore } from '@/store/chat';
-import FileItem from './Item';
+import type { SearchKnowledgeBaseArgs, SearchKnowledgeBaseState } from '../../index';
const SearchKnowledgeBase = memo<
BuiltinRenderProps<SearchKnowledgeBaseArgs, SearchKnowledgeBaseState>
>(({ pluginState }) => {
- const { fileResults } = pluginState || {};
+ const openFilePreview = useChatStore((s) => s.openFilePreview);
+ const isMobile = useIsMobile();
return (
- <Flexbox gap={8} horizontal wrap={'wrap'}>
- {fileResults?.map((file, index) => {
- return <FileItem index={index} key={file.fileId} {...file} />;
- })}
- </Flexbox>
+ <BaseSearchKnowledgeBase
+ FileIcon={FileIcon}
+ isMobile={isMobile}
+ onFileClick={openFilePreview}
+ pluginState={pluginState}
+ />
);
});
diff --git a/src/tools/knowledge-base/index.ts b/src/tools/knowledge-base/index.ts
index b68d386241c..868cdc9895a 100644
--- a/src/tools/knowledge-base/index.ts
+++ b/src/tools/knowledge-base/index.ts
@@ -1,64 +1,12 @@
-import { BuiltinToolManifest } from '@lobechat/types';
-
-import { systemPrompt } from './systemRole';
-
-export const KnowledgeBaseApiName = {
- readKnowledge: 'readKnowledge',
- searchKnowledgeBase: 'searchKnowledgeBase',
-};
-
-export const KnowledgeBaseManifest: BuiltinToolManifest = {
- api: [
- {
- description:
- 'Search through knowledge base using semantic vector search to find relevant files and chunks. Returns a summary of matching files with their relevance scores and brief excerpts. Use this first to discover which files contain relevant information. IMPORTANT: Since this uses vector-based search, always resolve pronouns and references to concrete entities (e.g., use "authentication system" instead of "it").',
- name: KnowledgeBaseApiName.searchKnowledgeBase,
- parameters: {
- properties: {
- query: {
- description:
- 'The search query to find relevant information. Be specific and use concrete entities. IMPORTANT: Resolve all pronouns and references (like "it", "that", "this") to actual entity names before searching, as this uses semantic vector search which works best with concrete terms.',
- type: 'string',
- },
- topK: {
- default: 15,
- description:
- 'Number of top relevant chunks to return (default: 15). Each file will include the most relevant chunks.',
- maximum: 100,
- minimum: 5,
- type: 'number',
- },
- },
- required: ['query'],
- type: 'object',
- },
- },
- {
- description:
- 'Read the full content of specific files from the knowledge base. Use this after searchKnowledgeBase to get complete information from relevant files. You can read multiple files at once.',
- name: KnowledgeBaseApiName.readKnowledge,
- parameters: {
- properties: {
- fileIds: {
- description:
- 'Array of file IDs to read. Get these IDs from searchKnowledgeBase results.',
- items: {
- type: 'string',
- },
- type: 'array',
- },
- },
- required: ['fileIds'],
- type: 'object',
- },
- },
- ],
- identifier: 'lobe-knowledge-base',
- meta: {
- avatar: '📚',
- description: 'Search and retrieve information from knowledge bases',
- title: 'Knowledge Base',
- },
- systemRole: systemPrompt,
- type: 'builtin',
-};
+// Re-export from the package for backward compatibility
+export {
+ type FileContentDetail,
+ KnowledgeBaseApiName,
+ KnowledgeBaseIdentifier,
+ KnowledgeBaseManifest,
+ type ReadKnowledgeArgs,
+ type ReadKnowledgeState,
+ type SearchKnowledgeBaseArgs,
+ type SearchKnowledgeBaseState,
+ systemPrompt,
+} from '@lobechat/builtin-tool-knowledge-base';