π€― 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
π fix: fix group manage tools and supervisor config resolve (#11586)
Arvin Xu51d2eae0dccb
diff --git a/packages/builtin-agents/src/agents/group-supervisor/index.ts b/packages/builtin-agents/src/agents/group-supervisor/index.tsindex 42cf5dc4df6..319eaac5342 100644--- a/packages/builtin-agents/src/agents/group-supervisor/index.ts+++ b/packages/builtin-agents/src/agents/group-supervisor/index.ts@@ -1,6 +1,5 @@import { GroupAgentBuilderIdentifier } from '@lobechat/builtin-tool-group-agent-builder';import { GroupManagementIdentifier } from '@lobechat/builtin-tool-group-management';-import { GTDIdentifier } from '@lobechat/builtin-tool-gtd';import type { BuiltinAgentDefinition } from '../../types';import { BUILTIN_AGENT_SLUGS } from '../../types';@@ -41,12 +40,7 @@ export const GROUP_SUPERVISOR: BuiltinAgentDefinition = {chatConfig: {enableHistoryCount: false,},- plugins: [- GroupManagementIdentifier,- GroupAgentBuilderIdentifier,- GTDIdentifier,- ...(ctx.plugins || []),- ],+ plugins: [GroupManagementIdentifier, GroupAgentBuilderIdentifier, ...(ctx.plugins || [])],systemRole: resolveSystemRole(groupSupervisorContext),};},diff --git a/packages/builtin-tool-group-agent-builder/src/ExecutionRuntime/index.ts b/packages/builtin-tool-group-agent-builder/src/ExecutionRuntime/index.tsindex 31f864dfa49..cb093f9000f 100644--- a/packages/builtin-tool-group-agent-builder/src/ExecutionRuntime/index.ts+++ b/packages/builtin-tool-group-agent-builder/src/ExecutionRuntime/index.ts@@ -1,3 +1,4 @@+import { formatAgentProfile } from '@lobechat/prompts';import type { BuiltinServerRuntimeOutput } from '@lobechat/types';import { agentService } from '@/services/agent';@@ -11,6 +12,7 @@ import type {BatchCreateAgentsState,CreateAgentParams,CreateAgentState,+ GetAgentInfoParams,InviteAgentParams,InviteAgentState,RemoveAgentParams,@@ -30,6 +32,33 @@ import type {* Extends AgentBuilder functionality with group-specific operations*/export class GroupAgentBuilderExecutionRuntime {+ // ==================== Agent Info ====================++ /**+ * Get detailed information about a specific agent+ */+ async getAgentInfo(+ groupId: string | undefined,+ args: GetAgentInfoParams,+ ): Promise<BuiltinServerRuntimeOutput> {+ if (!groupId) {+ return {+ content: 'No group context available',+ success: false,+ };+ }++ const state = getChatGroupStoreState();+ const agent = agentGroupSelectors.getAgentByIdFromGroup(groupId, args.agentId)(state);++ if (!agent) {+ return { content: `Agent "${args.agentId}" not found in this group`, success: false };+ }++ // Return formatted agent profile for the supervisor+ return { content: formatAgentProfile(agent), state: agent, success: true };+ }+// ==================== Group Member Management ====================/**diff --git a/packages/builtin-tool-group-agent-builder/src/executor.ts b/packages/builtin-tool-group-agent-builder/src/executor.tsindex fe1917984db..81a2c34fb99 100644--- a/packages/builtin-tool-group-agent-builder/src/executor.ts+++ b/packages/builtin-tool-group-agent-builder/src/executor.ts@@ -16,6 +16,7 @@ import { GroupAgentBuilderExecutionRuntime } from './ExecutionRuntime';import {type BatchCreateAgentsParams,type CreateAgentParams,+ type GetAgentInfoParams,GroupAgentBuilderApiName,GroupAgentBuilderIdentifier,type InviteAgentParams,@@ -34,6 +35,23 @@ class GroupAgentBuilderExecutor extends BaseExecutor<typeof GroupAgentBuilderApireadonly identifier = GroupAgentBuilderIdentifier;protected readonly apiEnum = GroupAgentBuilderApiName;+ // ==================== Agent Info ====================++ getAgentInfo = async (+ params: GetAgentInfoParams,+ ctx: BuiltinToolContext,+ ): Promise<BuiltinToolResult> => {+ const result = await groupAgentBuilderRuntime.getAgentInfo(ctx.groupId, params);+ return {+ content: result.content,+ error: result.error+ ? { body: result.error, message: String(result.error), type: 'RuntimeError' }+ : undefined,+ state: result.state,+ success: result.success,+ };+ };+// ==================== Group Member Management ====================searchAgent = async (params: SearchAgentParams): Promise<BuiltinToolResult> => {diff --git a/packages/builtin-tool-group-agent-builder/src/manifest.ts b/packages/builtin-tool-group-agent-builder/src/manifest.tsindex 739dd10b564..e5a8ced9079 100644--- a/packages/builtin-tool-group-agent-builder/src/manifest.ts+++ b/packages/builtin-tool-group-agent-builder/src/manifest.ts@@ -5,6 +5,23 @@ import { GroupAgentBuilderApiName, GroupAgentBuilderIdentifier } from './types';export const GroupAgentBuilderManifest: BuiltinToolManifest = {api: [+ // ==================== Agent Info ====================+ {+ description:+ 'Get detailed information about a specific agent, including their capabilities, available tools, and configuration. Use this to check if an agent has tools before deciding between speak vs executeAgentTask.',+ name: GroupAgentBuilderApiName.getAgentInfo,+ parameters: {+ properties: {+ agentId: {+ description: 'The ID of the agent to get information about.',+ type: 'string',+ },+ },+ required: ['agentId'],+ type: 'object',+ },+ },+// ==================== Group Member Management ===================={description:diff --git a/packages/builtin-tool-group-agent-builder/src/types.ts b/packages/builtin-tool-group-agent-builder/src/types.tsindex 84e49b19cf2..3b9b8fae87f 100644--- a/packages/builtin-tool-group-agent-builder/src/types.ts+++ b/packages/builtin-tool-group-agent-builder/src/types.ts@@ -14,6 +14,9 @@ export const GroupAgentBuilderApiName = {batchCreateAgents: 'batchCreateAgents',createAgent: 'createAgent',+ // Agent info+ getAgentInfo: 'getAgentInfo',+// Read operations (inherited from AgentBuilder)getAvailableModels: 'getAvailableModels',@@ -40,6 +43,13 @@ export type GroupAgentBuilderApiNameType =// ============== Group-specific Parameter Types ==============+export interface GetAgentInfoParams {+ /**+ * The ID of the agent to get information about+ */+ agentId: string;+}+export interface SearchAgentParams {/*** Maximum number of results to returndiff --git a/packages/builtin-tool-group-management/src/executor.test.ts b/packages/builtin-tool-group-management/src/executor.test.tsindex 33b53d35cd4..3e16d10694a 100644--- a/packages/builtin-tool-group-management/src/executor.test.ts+++ b/packages/builtin-tool-group-management/src/executor.test.ts@@ -271,18 +271,6 @@ describe('GroupManagementExecutor', () => {});});- 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('executeAgentTask', () => {beforeEach(() => {vi.clearAllMocks();diff --git a/packages/builtin-tool-group-management/src/executor.ts b/packages/builtin-tool-group-management/src/executor.tsindex a8ab98b39f6..381f09cce89 100644--- a/packages/builtin-tool-group-management/src/executor.ts+++ b/packages/builtin-tool-group-management/src/executor.ts@@ -11,7 +11,6 @@ import {CreateWorkflowParams,DelegateParams,ExecuteTaskParams,- GetAgentInfoParams,GroupManagementApiName,GroupManagementIdentifier,InterruptParams,@@ -19,43 +18,12 @@ import {SummarizeParams,VoteParams,} from '@lobechat/builtin-tool-group-management';-import { formatAgentProfile } from '@lobechat/prompts';import { BaseExecutor, type BuiltinToolContext, type BuiltinToolResult } from '@lobechat/types';-import { agentGroupSelectors, useAgentGroupStore } from '@/store/agentGroup';-class GroupManagementExecutor extends BaseExecutor<typeof GroupManagementApiName> {readonly identifier = GroupManagementIdentifier;protected readonly apiEnum = GroupManagementApiName;- // ==================== Agent Info ====================-- 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> => {@@ -225,12 +193,12 @@ class GroupManagementExecutor extends BaseExecutor<typeof GroupManagementApiName_ctx: BuiltinToolContext,): Promise<BuiltinToolResult> => {// TODO: Implement conversation summarization+ const focusInfo = params.focus ? ` with focus on "${params.focus}"` : '';+ const preserveInfo = params.preserveRecent+ ? ` (preserving ${params.preserveRecent} recent messages)`+ : '';return {- content: JSON.stringify({- focus: params.focus,- message: 'Summarization not yet implemented',- preserveRecent: params.preserveRecent,- }),+ content: `Summarization not yet implemented${focusInfo}${preserveInfo}`,success: true,};};@@ -243,23 +211,16 @@ class GroupManagementExecutor extends BaseExecutor<typeof GroupManagementApiName): Promise<BuiltinToolResult> => {// TODO: Implement workflow creationreturn {- content: JSON.stringify({- message: 'Workflow creation not yet implemented',- name: params.name,- steps: params.steps,- }),+ content: `Workflow creation not yet implemented for "${params.name}" with ${params.steps.length} steps`,success: true,};};vote = async (params: VoteParams, _ctx: BuiltinToolContext): Promise<BuiltinToolResult> => {// TODO: Implement voting mechanism+ const optionLabels = params.options.map((o) => o.label).join(', ');return {- content: JSON.stringify({- message: 'Voting not yet implemented',- options: params.options,- question: params.question,- }),+ content: `Voting not yet implemented for question: "${params.question}" with options: ${optionLabels}`,success: true,};};diff --git a/packages/builtin-tool-group-management/src/manifest.ts b/packages/builtin-tool-group-management/src/manifest.tsindex 0a6db844063..365e46dae3c 100644--- a/packages/builtin-tool-group-management/src/manifest.ts+++ b/packages/builtin-tool-group-management/src/manifest.ts@@ -8,23 +8,6 @@ export const GroupManagementIdentifier = 'lobe-group-management';export const GroupManagementManifest: BuiltinToolManifest = {/* eslint-disable sort-keys-fix/sort-keys-fix */api: [- // ==================== Agent Info ====================- {- description:- 'Get detailed information about a specific agent, including their capabilities, available tools, and configuration. Use this to check if an agent has tools before deciding between speak vs executeAgentTask.',- 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:diff --git a/packages/builtin-tool-group-management/src/systemRole.ts b/packages/builtin-tool-group-management/src/systemRole.tsindex 1ad6735939d..d3be0f91a6d 100644--- a/packages/builtin-tool-group-management/src/systemRole.ts+++ b/packages/builtin-tool-group-management/src/systemRole.ts@@ -150,9 +150,6 @@ When a user's request is broad or unclear, ask 1-2 focused questions to understa<core_capabilities>## Tool Categories-**Agent Info:**-- **getAgentInfo**: Get agent details including their tools and capabilities - **Use this to check if an agent has tools before deciding speak vs executeAgentTask**-**Speaking (Shared Context, No Tools):**- **speak**: Single agent responds synchronously in group context- **broadcast**: Multiple agents respond in parallel in group context@@ -241,9 +238,6 @@ Action: executeAgentTasks({</workflow_patterns><tool_usage_guidelines>-**Agent Info:**-- getAgentInfo: \`agentId\` - **Use this to check if an agent has tools before deciding speak vs executeAgentTask**-**Speaking:**- speak: \`agentId\`, \`instruction\` (optional guidance)- broadcast: \`agentIds\` (array), \`instruction\` (optional shared guidance)@@ -259,8 +253,7 @@ Action: executeAgentTasks({</tool_usage_guidelines><best_practices>-1. **Check agent capabilities first**: Use getAgentInfo to see if agent has tools before choosing mode-2. **Don't over-engineer**: Simple questions β speak; Complex tasks requiring tools β executeAgentTask+1. **Don't over-engineer**: Simple questions β speak; Complex tasks requiring tools β executeAgentTask3. **Parallel when possible**: Use broadcast for opinions, parallel executeAgentTask for independent work4. **Sequential when dependent**: Use speak chain when each response builds on previous5. **Be explicit with task instructions**: For executeAgentTask, clearly describe expected deliverablesdiff --git a/packages/builtin-tool-group-management/src/types.ts b/packages/builtin-tool-group-management/src/types.tsindex 565526d6d6d..3c03aa6e1fe 100644--- a/packages/builtin-tool-group-management/src/types.ts+++ b/packages/builtin-tool-group-management/src/types.ts@@ -7,10 +7,6 @@* are handled by group-agent-builder tool. This tool focuses on orchestration.*/export const GroupManagementApiName = {- // ==================== Agent Info ====================- /** Get detailed information about an agent */- getAgentInfo: 'getAgentInfo',-// ==================== Communication Coordination ====================/** Let a specific agent speak (synchronous, immediate response) */speak: 'speak',@@ -41,12 +37,6 @@ export const GroupManagementApiName = {export type GroupManagementApiNameType =(typeof GroupManagementApiName)[keyof typeof GroupManagementApiName];-// ==================== Agent Info Params ====================--export interface GetAgentInfoParams {- agentId: string;-}-// ==================== Communication Params ====================export interface SpeakParams {diff --git a/packages/builtin-tool-local-system/src/ExecutionRuntime/index.ts b/packages/builtin-tool-local-system/src/ExecutionRuntime/index.tsindex a5e2ee58d64..566a5e13b50 100644--- a/packages/builtin-tool-local-system/src/ExecutionRuntime/index.ts+++ b/packages/builtin-tool-local-system/src/ExecutionRuntime/index.ts@@ -71,8 +71,14 @@ export class LocalSystemExecutionRuntime {const state: LocalFileListState = { listResults: result };+ const fileList = result.map((f) => ` ${f.isDirectory ? '[D]' : '[F]'} ${f.name}`).join('\n');+ const content =+ result.length > 0+ ? `Found ${result.length} item(s) in ${args.path}:\n${fileList}`+ : `Directory ${args.path} is empty`;+return {- content: JSON.stringify(result),+ content,state,success: true,};@@ -91,8 +97,11 @@ export class LocalSystemExecutionRuntime {const state: LocalReadFileState = { fileContent: result };+ const lineInfo = args.loc ? ` (lines ${args.loc[0]}-${args.loc[1]})` : '';+ const content = `File: ${args.path}${lineInfo}\n\n${result.content}`;+return {- content: JSON.stringify(result),+ content,state,success: true,};@@ -111,8 +120,11 @@ export class LocalSystemExecutionRuntime {const state: LocalReadFilesState = { filesContent: results };+ const fileContents = results.map((r) => `=== ${r.filename} ===\n${r.content}`).join('\n\n');+ const content = `Read ${results.length} file(s):\n\n${fileContents}`;+return {- content: JSON.stringify(results),+ content,state,success: true,};@@ -131,8 +143,12 @@ export class LocalSystemExecutionRuntime {const state: LocalFileSearchState = { searchResults: result };+ const fileList = result.map((f) => ` ${f.path}`).join('\n');+ const content =+ result.length > 0 ? `Found ${result.length} file(s):\n${fileList}` : 'No files found';+return {- content: JSON.stringify(result),+ content,state,success: true,};@@ -154,14 +170,14 @@ export class LocalSystemExecutionRuntime {const successCount = results.filter((r) => r.success).length;const failedCount = results.length - successCount;- let message = '';+ let content = '';if (allSucceeded) {- message = `Successfully moved ${results.length} item(s).`;+ content = `Successfully moved ${results.length} item(s).`;} else if (someFailed) {- message = `Moved ${successCount} item(s) successfully. Failed to move ${failedCount} item(s).`;+ content = `Moved ${successCount} item(s) successfully. Failed to move ${failedCount} item(s).`;} else {- message = `Failed to move all ${results.length} item(s).`;+ content = `Failed to move all ${results.length} item(s).`;}const state: LocalMoveFilesState = {@@ -171,7 +187,7 @@ export class LocalSystemExecutionRuntime {};return {- content: JSON.stringify({ message, results }),+ content,state,success: true,};@@ -197,7 +213,7 @@ export class LocalSystemExecutionRuntime {};return {- content: JSON.stringify({ message: result.error, success: false }),+ content: `Failed to rename file: ${result.error}`,state,success: false,};@@ -210,10 +226,7 @@ export class LocalSystemExecutionRuntime {};return {- content: JSON.stringify({- message: `Successfully renamed file ${args.path} to ${args.newName}.`,- success: true,- }),+ content: `Successfully renamed file ${args.path} to ${args.newName}`,state,success: true,};@@ -232,20 +245,14 @@ export class LocalSystemExecutionRuntime {if (!result.success) {return {- content: JSON.stringify({- message: result.error || 'εε ₯ζδ»Άε€±θ΄₯',- success: false,- }),+ content: `Failed to write file: ${result.error || 'Unknown error'}`,error: result.error,success: false,};}return {- content: JSON.stringify({- message: `ζεεε ₯ζδ»Ά ${args.path}`,- success: true,- }),+ content: `Successfully wrote to ${args.path}`,success: true,};} catch (error) {@@ -301,22 +308,28 @@ export class LocalSystemExecutionRuntime {try {const result: RunCommandResult = await this.localFileService.runCommand(args);- let message: string;+ const parts: string[] = [];if (result.success) {if (result.shell_id) {- message = `Command started in background with shell_id: ${result.shell_id}`;+ parts.push(`Command started in background with shell_id: ${result.shell_id}`);} else {- message = `Command completed successfully.`;+ parts.push('Command completed successfully.');}} else {- message = `Command failed: ${result.error}`;+ parts.push(`Command failed: ${result.error}`);}+ if (result.stdout) parts.push(`Output:\n${result.stdout}`);+ if (result.stderr) parts.push(`Stderr:\n${result.stderr}`);+ if (result.exit_code !== undefined) parts.push(`Exit code: ${result.exit_code}`);++ const message = parts[0];+ const content = parts.join('\n\n');const state: RunCommandState = { message, result };return {- content: JSON.stringify(result),+ content,state,success: result.success,};@@ -337,10 +350,14 @@ export class LocalSystemExecutionRuntime {? `Output retrieved. Running: ${result.running}`: `Failed: ${result.error}`;+ const parts: string[] = [message];+ if (result.output) parts.push(`Output:\n${result.output}`);+ if (result.error) parts.push(`Error: ${result.error}`);+const state: GetCommandOutputState = { message, result };return {- content: JSON.stringify(result),+ content: parts.join('\n\n'),state,success: result.success,};@@ -364,7 +381,7 @@ export class LocalSystemExecutionRuntime {const state: KillCommandState = { message, result };return {- content: JSON.stringify(result),+ content: message,state,success: result.success,};@@ -389,8 +406,19 @@ export class LocalSystemExecutionRuntime {const state: GrepContentState = { message, result };+ let content = message;+ if (result.success && result.matches.length > 0) {+ const matchList = result.matches+ .slice(0, 20)+ .map((m) => ` ${m}`)+ .join('\n');+ const moreInfo =+ result.matches.length > 20 ? `\n ... and ${result.matches.length - 20} more` : '';+ content = `${message}:\n${matchList}${moreInfo}`;+ }+return {- content: JSON.stringify(result),+ content,state,success: result.success,};@@ -411,8 +439,19 @@ export class LocalSystemExecutionRuntime {const state: GlobFilesState = { message, result };+ let content = message;+ if (result.success && result.files.length > 0) {+ const fileList = result.files+ .slice(0, 50)+ .map((f) => ` ${f}`)+ .join('\n');+ const moreInfo =+ result.files.length > 50 ? `\n ... and ${result.files.length - 50} more` : '';+ content = `${message}:\n${fileList}${moreInfo}`;+ }+return {- content: JSON.stringify(result),+ content,state,success: result.success,};diff --git a/packages/builtin-tool-local-system/src/executor/index.ts b/packages/builtin-tool-local-system/src/executor/index.tsindex e2c2f0b46f8..ae46d8eccee 100644--- a/packages/builtin-tool-local-system/src/executor/index.ts+++ b/packages/builtin-tool-local-system/src/executor/index.ts@@ -23,6 +23,21 @@ import type {RunCommandResult,WriteLocalFileParams,} from '@lobechat/electron-client-ipc';+import {+ formatCommandOutput,+ formatCommandResult,+ formatEditResult,+ formatFileContent,+ formatFileList,+ formatFileSearchResults,+ formatGlobResults,+ formatGrepResults,+ formatKillResult,+ formatMoveResults,+ formatMultipleFiles,+ formatRenameResult,+ formatWriteResult,+} from '@lobechat/prompts';import { BaseExecutor, type BuiltinToolResult } from '@lobechat/types';import { localFileService } from '@/services/electron/localFileService';@@ -76,8 +91,10 @@ class LocalSystemExecutor extends BaseExecutor<typeof LocalSystemApiEnum> {const state: LocalFileListState = { listResults: result };+ const content = formatFileList(result, params.path);+return {- content: JSON.stringify(result),+ content,state,success: true,};@@ -96,8 +113,14 @@ class LocalSystemExecutor extends BaseExecutor<typeof LocalSystemApiEnum> {const state: LocalReadFileState = { fileContent: result };+ const content = formatFileContent({+ content: result.content,+ lineRange: params.loc,+ path: params.path,+ });+return {- content: JSON.stringify(result),+ content,state,success: true,};@@ -116,8 +139,10 @@ class LocalSystemExecutor extends BaseExecutor<typeof LocalSystemApiEnum> {const state: LocalReadFilesState = { filesContent: results };+ const content = formatMultipleFiles(results);+return {- content: JSON.stringify(results),+ content,state,success: true,};@@ -136,8 +161,10 @@ class LocalSystemExecutor extends BaseExecutor<typeof LocalSystemApiEnum> {const state: LocalFileSearchState = { searchResults: result };+ const content = formatFileSearchResults(result);+return {- content: JSON.stringify(result),+ content,state,success: true,};@@ -154,20 +181,9 @@ class LocalSystemExecutor extends BaseExecutor<typeof LocalSystemApiEnum> {try {const results: LocalMoveFilesResultItem[] = await localFileService.moveLocalFiles(params);- const allSucceeded = results.every((r) => r.success);- const someFailed = results.some((r) => !r.success);const successCount = results.filter((r) => r.success).length;- const failedCount = results.length - successCount;- let message = '';-- if (allSucceeded) {- message = `Successfully moved ${results.length} item(s).`;- } else if (someFailed) {- message = `Moved ${successCount} item(s) successfully. Failed to move ${failedCount} item(s).`;- } else {- message = `Failed to move all ${results.length} item(s).`;- }+ const content = formatMoveResults(results);const state: LocalMoveFilesState = {results,@@ -176,7 +192,7 @@ class LocalSystemExecutor extends BaseExecutor<typeof LocalSystemApiEnum> {};return {- content: JSON.stringify({ message, results }),+ content,state,success: true,};@@ -202,7 +218,12 @@ class LocalSystemExecutor extends BaseExecutor<typeof LocalSystemApiEnum> {};return {- content: JSON.stringify({ message: result.error, success: false }),+ content: formatRenameResult({+ error: result.error,+ newName: params.newName,+ oldPath: params.path,+ success: false,+ }),state,success: false,};@@ -215,8 +236,9 @@ class LocalSystemExecutor extends BaseExecutor<typeof LocalSystemApiEnum> {};return {- content: JSON.stringify({- message: `Successfully renamed file ${params.path} to ${params.newName}.`,+ content: formatRenameResult({+ newName: params.newName,+ oldPath: params.path,success: true,}),state,@@ -237,8 +259,9 @@ class LocalSystemExecutor extends BaseExecutor<typeof LocalSystemApiEnum> {if (!result.success) {return {- content: JSON.stringify({- message: result.error || 'Failed to write file',+ content: formatWriteResult({+ error: result.error,+ path: params.path,success: false,}),error: { message: result.error || 'Failed to write file', type: 'PluginServerError' },@@ -247,8 +270,8 @@ class LocalSystemExecutor extends BaseExecutor<typeof LocalSystemApiEnum> {}return {- content: JSON.stringify({- message: `Successfully wrote file ${params.path}`,+ content: formatWriteResult({+ path: params.path,success: true,}),success: true,@@ -273,11 +296,12 @@ class LocalSystemExecutor extends BaseExecutor<typeof LocalSystemApiEnum> {};}- const statsText =- result.linesAdded || result.linesDeleted- ? ` (+${result.linesAdded || 0} -${result.linesDeleted || 0})`- : '';- const message = `Successfully replaced ${result.replacements} occurrence(s) in ${params.file_path}${statsText}`;+ const content = formatEditResult({+ filePath: params.file_path,+ linesAdded: result.linesAdded,+ linesDeleted: result.linesDeleted,+ replacements: result.replacements,+ });const state: EditLocalFileState = {diffText: result.diffText,@@ -287,7 +311,7 @@ class LocalSystemExecutor extends BaseExecutor<typeof LocalSystemApiEnum> {};return {- content: message,+ content,state,success: true,};@@ -306,22 +330,19 @@ class LocalSystemExecutor extends BaseExecutor<typeof LocalSystemApiEnum> {try {const result: RunCommandResult = await localFileService.runCommand(params);- let message: string;-- if (result.success) {- if (result.shell_id) {- message = `Command started in background with shell_id: ${result.shell_id}`;- } else {- message = `Command completed successfully.`;- }- } else {- message = `Command failed: ${result.error}`;- }+ const content = formatCommandResult({+ error: result.error,+ exitCode: result.exit_code,+ shellId: result.shell_id,+ stderr: result.stderr,+ stdout: result.stdout,+ success: result.success,+ });- const state: RunCommandState = { message, result };+ const state: RunCommandState = { message: content.split('\n\n')[0], result };return {- content: JSON.stringify(result),+ content,state,success: result.success,};@@ -338,14 +359,17 @@ class LocalSystemExecutor extends BaseExecutor<typeof LocalSystemApiEnum> {try {const result: GetCommandOutputResult = await localFileService.getCommandOutput(params);- const message = result.success- ? `Output retrieved. Running: ${result.running}`- : `Failed: ${result.error}`;+ const content = formatCommandOutput({+ error: result.error,+ output: result.output,+ running: result.running,+ success: result.success,+ });- const state: GetCommandOutputState = { message, result };+ const state: GetCommandOutputState = { message: content.split('\n\n')[0], result };return {- content: JSON.stringify(result),+ content,state,success: result.success,};@@ -362,14 +386,16 @@ class LocalSystemExecutor extends BaseExecutor<typeof LocalSystemApiEnum> {try {const result: KillCommandResult = await localFileService.killCommand(params);- const message = result.success- ? `Successfully killed shell: ${params.shell_id}`- : `Failed to kill shell: ${result.error}`;+ const content = formatKillResult({+ error: result.error,+ shellId: params.shell_id,+ success: result.success,+ });- const state: KillCommandState = { message, result };+ const state: KillCommandState = { message: content, result };return {- content: JSON.stringify(result),+ content,state,success: result.success,};@@ -388,14 +414,17 @@ class LocalSystemExecutor extends BaseExecutor<typeof LocalSystemApiEnum> {try {const result: GrepContentResult = await localFileService.grepContent(params);- const message = result.success- ? `Found ${result.total_matches} matches in ${result.matches.length} locations`+ const content = result.success+ ? formatGrepResults({+ matches: result.matches,+ totalMatches: result.total_matches,+ }): 'Search failed';- const state: GrepContentState = { message, result };+ const state: GrepContentState = { message: content.split('\n')[0], result };return {- content: JSON.stringify(result),+ content,state,success: result.success,};@@ -412,12 +441,17 @@ class LocalSystemExecutor extends BaseExecutor<typeof LocalSystemApiEnum> {try {const result: GlobFilesResult = await localFileService.globFiles(params);- const message = result.success ? `Found ${result.total_files} files` : 'Glob search failed';+ const content = result.success+ ? formatGlobResults({+ files: result.files,+ totalFiles: result.total_files,+ })+ : 'Glob search failed';- const state: GlobFilesState = { message, result };+ const state: GlobFilesState = { message: content.split('\n')[0], result };return {- content: JSON.stringify(result),+ content,state,success: result.success,};diff --git a/packages/prompts/src/prompts/fileSystem/formatCommandOutput.test.ts b/packages/prompts/src/prompts/fileSystem/formatCommandOutput.test.tsnew file mode 100644index 00000000000..74f01222be1--- /dev/null+++ b/packages/prompts/src/prompts/fileSystem/formatCommandOutput.test.ts@@ -0,0 +1,61 @@+import { describe, expect, it } from 'vitest';++import { formatCommandOutput } from './formatCommandOutput';++describe('formatCommandOutput', () => {+ it('should format successful output while running', () => {+ const result = formatCommandOutput({+ running: true,+ success: true,+ });+ expect(result).toMatchInlineSnapshot(`"Output retrieved. Running: true"`);+ });++ it('should format successful output when not running', () => {+ const result = formatCommandOutput({+ running: false,+ success: true,+ });+ expect(result).toMatchInlineSnapshot(`"Output retrieved. Running: false"`);+ });++ it('should format successful output with content', () => {+ const result = formatCommandOutput({+ output: 'Process output here',+ running: true,+ success: true,+ });+ expect(result).toMatchInlineSnapshot(`+ "Output retrieved. Running: true++ Output:+ Process output here"+ `);+ });++ it('should format failed output', () => {+ const result = formatCommandOutput({+ error: 'Process not found',+ running: false,+ success: false,+ });+ expect(result).toMatchInlineSnapshot(`"Failed: Process not found"`);+ });++ it('should format successful output with error info', () => {+ const result = formatCommandOutput({+ error: 'Warning message',+ output: 'Some output',+ running: false,+ success: true,+ });+ expect(result).toMatchInlineSnapshot(`+ "Output retrieved. Running: false++ Output:+ Some output++ Error: Warning message"+ `);+ });+});diff --git a/packages/prompts/src/prompts/fileSystem/formatCommandOutput.ts b/packages/prompts/src/prompts/fileSystem/formatCommandOutput.tsnew file mode 100644index 00000000000..fbca330f385--- /dev/null+++ b/packages/prompts/src/prompts/fileSystem/formatCommandOutput.ts@@ -0,0 +1,21 @@+export interface FormatCommandOutputParams {+ error?: string;+ output?: string;+ running: boolean;+ success: boolean;+}++export const formatCommandOutput = ({+ success,+ running,+ output,+ error,+}: FormatCommandOutputParams): string => {+ const message = success ? `Output retrieved. Running: ${running}` : `Failed: ${error}`;++ const parts: string[] = [message];+ if (output) parts.push(`Output:\n${output}`);+ if (error && success) parts.push(`Error: ${error}`);++ return parts.join('\n\n');+};diff --git a/packages/prompts/src/prompts/fileSystem/formatCommandResult.test.ts b/packages/prompts/src/prompts/fileSystem/formatCommandResult.test.tsnew file mode 100644index 00000000000..0333e1d2574--- /dev/null+++ b/packages/prompts/src/prompts/fileSystem/formatCommandResult.test.ts@@ -0,0 +1,87 @@+import { describe, expect, it } from 'vitest';++import { formatCommandResult } from './formatCommandResult';++describe('formatCommandResult', () => {+ it('should format successful command without output', () => {+ const result = formatCommandResult({ success: true });+ expect(result).toMatchInlineSnapshot(`"Command completed successfully."`);+ });++ it('should format successful background command', () => {+ const result = formatCommandResult({+ shellId: 'shell-123',+ success: true,+ });+ expect(result).toMatchInlineSnapshot(+ `"Command started in background with shell_id: shell-123"`,+ );+ });++ it('should format successful command with stdout', () => {+ const result = formatCommandResult({+ stdout: 'Hello World',+ success: true,+ });+ expect(result).toMatchInlineSnapshot(`+ "Command completed successfully.++ Output:+ Hello World"+ `);+ });++ it('should format successful command with stderr', () => {+ const result = formatCommandResult({+ stderr: 'Warning: deprecated',+ success: true,+ });+ expect(result).toMatchInlineSnapshot(`+ "Command completed successfully.++ Stderr:+ Warning: deprecated"+ `);+ });++ it('should format successful command with exit code', () => {+ const result = formatCommandResult({+ exitCode: 0,+ success: true,+ });+ expect(result).toMatchInlineSnapshot(`+ "Command completed successfully.++ Exit code: 0"+ `);+ });++ it('should format failed command', () => {+ const result = formatCommandResult({+ error: 'Permission denied',+ success: false,+ });+ expect(result).toMatchInlineSnapshot(`"Command failed: Permission denied"`);+ });++ it('should format command with all fields', () => {+ const result = formatCommandResult({+ error: 'Command error',+ exitCode: 1,+ stderr: 'Error occurred',+ stdout: 'Some output',+ success: false,+ });+ expect(result).toMatchInlineSnapshot(`+ "Command failed: Command error++ Output:+ Some output++ Stderr:+ Error occurred++ Exit code: 1"+ `);+ });+});diff --git a/packages/prompts/src/prompts/fileSystem/formatCommandResult.ts b/packages/prompts/src/prompts/fileSystem/formatCommandResult.tsnew file mode 100644index 00000000000..29e3d314f9e--- /dev/null+++ b/packages/prompts/src/prompts/fileSystem/formatCommandResult.ts@@ -0,0 +1,35 @@+export interface FormatCommandResultParams {+ error?: string;+ exitCode?: number;+ shellId?: string;+ stderr?: string;+ stdout?: string;+ success: boolean;+}++export const formatCommandResult = ({+ success,+ shellId,+ error,+ stdout,+ stderr,+ exitCode,+}: FormatCommandResultParams): string => {+ const parts: string[] = [];++ if (success) {+ if (shellId) {+ parts.push(`Command started in background with shell_id: ${shellId}`);+ } else {+ parts.push('Command completed successfully.');+ }+ } else {+ parts.push(`Command failed: ${error}`);+ }++ if (stdout) parts.push(`Output:\n${stdout}`);+ if (stderr) parts.push(`Stderr:\n${stderr}`);+ if (exitCode !== undefined) parts.push(`Exit code: ${exitCode}`);++ return parts.join('\n\n');+};diff --git a/packages/prompts/src/prompts/fileSystem/formatEditResult.test.ts b/packages/prompts/src/prompts/fileSystem/formatEditResult.test.tsnew file mode 100644index 00000000000..b48d337b1cd--- /dev/null+++ b/packages/prompts/src/prompts/fileSystem/formatEditResult.test.ts@@ -0,0 +1,57 @@+import { describe, expect, it } from 'vitest';++import { formatEditResult } from './formatEditResult';++describe('formatEditResult', () => {+ it('should format edit result without line stats', () => {+ const result = formatEditResult({+ filePath: '/src/index.ts',+ replacements: 3,+ });+ expect(result).toMatchInlineSnapshot(+ `"Successfully replaced 3 occurrence(s) in /src/index.ts"`,+ );+ });++ it('should format edit result with lines added', () => {+ const result = formatEditResult({+ filePath: '/src/index.ts',+ linesAdded: 5,+ replacements: 1,+ });+ expect(result).toMatchInlineSnapshot(+ `"Successfully replaced 1 occurrence(s) in /src/index.ts (+5 -0)"`,+ );+ });++ it('should format edit result with lines deleted', () => {+ const result = formatEditResult({+ filePath: '/src/index.ts',+ linesDeleted: 3,+ replacements: 2,+ });+ expect(result).toMatchInlineSnapshot(+ `"Successfully replaced 2 occurrence(s) in /src/index.ts (+0 -3)"`,+ );+ });++ it('should format edit result with both lines added and deleted', () => {+ const result = formatEditResult({+ filePath: '/src/utils.ts',+ linesAdded: 10,+ linesDeleted: 5,+ replacements: 4,+ });+ expect(result).toMatchInlineSnapshot(+ `"Successfully replaced 4 occurrence(s) in /src/utils.ts (+10 -5)"`,+ );+ });++ it('should handle zero replacements', () => {+ const result = formatEditResult({+ filePath: '/test.txt',+ replacements: 0,+ });+ expect(result).toMatchInlineSnapshot(`"Successfully replaced 0 occurrence(s) in /test.txt"`);+ });+});diff --git a/packages/prompts/src/prompts/fileSystem/formatEditResult.ts b/packages/prompts/src/prompts/fileSystem/formatEditResult.tsnew file mode 100644index 00000000000..c72b0dedb3d--- /dev/null+++ b/packages/prompts/src/prompts/fileSystem/formatEditResult.ts@@ -0,0 +1,17 @@+export interface FormatEditResultParams {+ filePath: string;+ linesAdded?: number;+ linesDeleted?: number;+ replacements: number;+}++export const formatEditResult = ({+ replacements,+ filePath,+ linesAdded,+ linesDeleted,+}: FormatEditResultParams): string => {+ const statsText =+ linesAdded || linesDeleted ? ` (+${linesAdded || 0} -${linesDeleted || 0})` : '';+ return `Successfully replaced ${replacements} occurrence(s) in ${filePath}${statsText}`;+};diff --git a/packages/prompts/src/prompts/fileSystem/formatFileContent.test.ts b/packages/prompts/src/prompts/fileSystem/formatFileContent.test.tsnew file mode 100644index 00000000000..ddac02fcc35--- /dev/null+++ b/packages/prompts/src/prompts/fileSystem/formatFileContent.test.ts@@ -0,0 +1,59 @@+import { describe, expect, it } from 'vitest';++import { formatFileContent } from './formatFileContent';++describe('formatFileContent', () => {+ it('should format file content without line range', () => {+ const result = formatFileContent({+ content: 'console.log("hello");',+ path: '/src/index.ts',+ });+ expect(result).toMatchInlineSnapshot(`+ "File: /src/index.ts++ console.log("hello");"+ `);+ });++ it('should format file content with line range', () => {+ const result = formatFileContent({+ content: 'function test() {\n return true;\n}',+ lineRange: [10, 12],+ path: '/src/utils.ts',+ });+ expect(result).toMatchInlineSnapshot(`+ "File: /src/utils.ts (lines 10-12)++ function test() {+ return true;+ }"+ `);+ });++ it('should handle empty content', () => {+ const result = formatFileContent({+ content: '',+ path: '/empty.txt',+ });+ expect(result).toMatchInlineSnapshot(`+ "File: /empty.txt++ "+ `);+ });++ it('should handle multiline content', () => {+ const content = 'line 1\nline 2\nline 3';+ const result = formatFileContent({+ content,+ path: '/test.txt',+ });+ expect(result).toMatchInlineSnapshot(`+ "File: /test.txt++ line 1+ line 2+ line 3"+ `);+ });+});diff --git a/packages/prompts/src/prompts/fileSystem/formatFileContent.ts b/packages/prompts/src/prompts/fileSystem/formatFileContent.tsnew file mode 100644index 00000000000..f29a5371a82--- /dev/null+++ b/packages/prompts/src/prompts/fileSystem/formatFileContent.ts@@ -0,0 +1,14 @@+export interface FormatFileContentParams {+ content: string;+ lineRange?: [number, number];+ path: string;+}++export const formatFileContent = ({+ path,+ content,+ lineRange,+}: FormatFileContentParams): string => {+ const lineInfo = lineRange ? ` (lines ${lineRange[0]}-${lineRange[1]})` : '';+ return `File: ${path}${lineInfo}\n\n${content}`;+};diff --git a/packages/prompts/src/prompts/fileSystem/formatFileList.test.ts b/packages/prompts/src/prompts/fileSystem/formatFileList.test.tsnew file mode 100644index 00000000000..a124ec19a40--- /dev/null+++ b/packages/prompts/src/prompts/fileSystem/formatFileList.test.ts@@ -0,0 +1,62 @@+import { describe, expect, it } from 'vitest';++import { formatFileList } from './formatFileList';++describe('formatFileList', () => {+ it('should format empty directory', () => {+ const result = formatFileList([], '/home/user');+ expect(result).toMatchInlineSnapshot(`"Directory /home/user is empty"`);+ });++ it('should format directory with files only', () => {+ const files = [+ { isDirectory: false, name: 'file1.txt' },+ { isDirectory: false, name: 'file2.js' },+ ];+ const result = formatFileList(files, '/home/user');+ expect(result).toMatchInlineSnapshot(`+ "Found 2 item(s) in /home/user:+ [F] file1.txt+ [F] file2.js"+ `);+ });++ it('should format directory with directories only', () => {+ const files = [+ { isDirectory: true, name: 'src' },+ { isDirectory: true, name: 'dist' },+ ];+ const result = formatFileList(files, '/project');+ expect(result).toMatchInlineSnapshot(`+ "Found 2 item(s) in /project:+ [D] src+ [D] dist"+ `);+ });++ it('should format directory with mixed content', () => {+ const files = [+ { isDirectory: true, name: 'src' },+ { isDirectory: false, name: 'package.json' },+ { isDirectory: true, name: 'node_modules' },+ { isDirectory: false, name: 'README.md' },+ ];+ const result = formatFileList(files, '/project');+ expect(result).toMatchInlineSnapshot(`+ "Found 4 item(s) in /project:+ [D] src+ [F] package.json+ [D] node_modules+ [F] README.md"+ `);+ });++ it('should format single item', () => {+ const files = [{ isDirectory: false, name: 'index.ts' }];+ const result = formatFileList(files, '/src');+ expect(result).toMatchInlineSnapshot(`+ "Found 1 item(s) in /src:+ [F] index.ts"+ `);+ });+});diff --git a/packages/prompts/src/prompts/fileSystem/formatFileList.ts b/packages/prompts/src/prompts/fileSystem/formatFileList.tsnew file mode 100644index 00000000000..192850b0459--- /dev/null+++ b/packages/prompts/src/prompts/fileSystem/formatFileList.ts@@ -0,0 +1,13 @@+export interface FileListItem {+ isDirectory: boolean;+ name: string;+}++export const formatFileList = (files: FileListItem[], directory: string): string => {+ if (files.length === 0) {+ return `Directory ${directory} is empty`;+ }++ const fileList = files.map((f) => ` ${f.isDirectory ? '[D]' : '[F]'} ${f.name}`).join('\n');+ return `Found ${files.length} item(s) in ${directory}:\n${fileList}`;+};diff --git a/packages/prompts/src/prompts/fileSystem/formatFileSearchResults.test.ts b/packages/prompts/src/prompts/fileSystem/formatFileSearchResults.test.tsnew file mode 100644index 00000000000..48583ee56d8--- /dev/null+++ b/packages/prompts/src/prompts/fileSystem/formatFileSearchResults.test.ts@@ -0,0 +1,34 @@+import { describe, expect, it } from 'vitest';++import { formatFileSearchResults } from './formatFileSearchResults';++describe('formatFileSearchResults', () => {+ it('should format empty results', () => {+ const result = formatFileSearchResults([]);+ expect(result).toMatchInlineSnapshot(`"No files found"`);+ });++ it('should format single result', () => {+ const results = [{ path: '/src/index.ts' }];+ const result = formatFileSearchResults(results);+ expect(result).toMatchInlineSnapshot(`+ "Found 1 file(s):+ /src/index.ts"+ `);+ });++ it('should format multiple results', () => {+ const results = [+ { path: '/src/index.ts' },+ { path: '/src/utils.ts' },+ { path: '/src/types.ts' },+ ];+ const result = formatFileSearchResults(results);+ expect(result).toMatchInlineSnapshot(`+ "Found 3 file(s):+ /src/index.ts+ /src/utils.ts+ /src/types.ts"+ `);+ });+});diff --git a/packages/prompts/src/prompts/fileSystem/formatFileSearchResults.ts b/packages/prompts/src/prompts/fileSystem/formatFileSearchResults.tsnew file mode 100644index 00000000000..50351de60f7--- /dev/null+++ b/packages/prompts/src/prompts/fileSystem/formatFileSearchResults.ts@@ -0,0 +1,12 @@+export interface FileSearchResultItem {+ path: string;+}++export const formatFileSearchResults = (results: FileSearchResultItem[]): string => {+ if (results.length === 0) {+ return 'No files found';+ }++ const fileList = results.map((f) => ` ${f.path}`).join('\n');+ return `Found ${results.length} file(s):\n${fileList}`;+};diff --git a/packages/prompts/src/prompts/fileSystem/formatGlobResults.test.ts b/packages/prompts/src/prompts/fileSystem/formatGlobResults.test.tsnew file mode 100644index 00000000000..e918ba57e8f--- /dev/null+++ b/packages/prompts/src/prompts/fileSystem/formatGlobResults.test.ts@@ -0,0 +1,64 @@+import { describe, expect, it } from 'vitest';++import { formatGlobResults } from './formatGlobResults';++describe('formatGlobResults', () => {+ it('should format empty results', () => {+ const result = formatGlobResults({+ files: [],+ totalFiles: 0,+ });+ expect(result).toMatchInlineSnapshot(`"Found 0 files"`);+ });++ it('should format single file', () => {+ const result = formatGlobResults({+ files: ['/src/index.ts'],+ totalFiles: 1,+ });+ expect(result).toMatchInlineSnapshot(`+ "Found 1 files:+ /src/index.ts"+ `);+ });++ it('should format multiple files', () => {+ const result = formatGlobResults({+ files: ['/src/index.ts', '/src/utils.ts', '/src/types.ts'],+ totalFiles: 3,+ });+ expect(result).toMatchInlineSnapshot(`+ "Found 3 files:+ /src/index.ts+ /src/utils.ts+ /src/types.ts"+ `);+ });++ it('should truncate files exceeding maxDisplay (default 50)', () => {+ const files = Array.from({ length: 55 }, (_, i) => `/file${i + 1}.ts`);+ const result = formatGlobResults({+ files,+ totalFiles: 55,+ });+ expect(result).toContain('Found 55 files:');+ expect(result).toContain('... and 5 more');+ expect(result).not.toContain('file51');+ });++ it('should respect custom maxDisplay', () => {+ const files = ['/a.ts', '/b.ts', '/c.ts', '/d.ts', '/e.ts'];+ const result = formatGlobResults({+ files,+ maxDisplay: 3,+ totalFiles: 5,+ });+ expect(result).toMatchInlineSnapshot(`+ "Found 5 files:+ /a.ts+ /b.ts+ /c.ts+ ... and 2 more"+ `);+ });+});diff --git a/packages/prompts/src/prompts/fileSystem/formatGlobResults.ts b/packages/prompts/src/prompts/fileSystem/formatGlobResults.tsnew file mode 100644index 00000000000..7a63fdf826a--- /dev/null+++ b/packages/prompts/src/prompts/fileSystem/formatGlobResults.ts@@ -0,0 +1,23 @@+export interface FormatGlobResultsParams {+ files: string[];+ maxDisplay?: number;+ totalFiles: number;+}++export const formatGlobResults = ({+ totalFiles,+ files,+ maxDisplay = 50,+}: FormatGlobResultsParams): string => {+ const message = `Found ${totalFiles} files`;++ if (files.length === 0) {+ return message;+ }++ const displayFiles = files.slice(0, maxDisplay);+ const fileList = displayFiles.map((f) => ` ${f}`).join('\n');+ const moreInfo = files.length > maxDisplay ? `\n ... and ${files.length - maxDisplay} more` : '';++ return `${message}:\n${fileList}${moreInfo}`;+};diff --git a/packages/prompts/src/prompts/fileSystem/formatGrepResults.test.ts b/packages/prompts/src/prompts/fileSystem/formatGrepResults.test.tsnew file mode 100644index 00000000000..16f130c4d32--- /dev/null+++ b/packages/prompts/src/prompts/fileSystem/formatGrepResults.test.ts@@ -0,0 +1,85 @@+import { describe, expect, it } from 'vitest';++import { formatGrepResults } from './formatGrepResults';++describe('formatGrepResults', () => {+ it('should format empty results', () => {+ const result = formatGrepResults({+ matches: [],+ totalMatches: 0,+ });+ expect(result).toMatchInlineSnapshot(`"Found 0 matches in 0 locations"`);+ });++ it('should format single match', () => {+ const result = formatGrepResults({+ matches: ['/src/index.ts:10: const foo = "bar"'],+ totalMatches: 1,+ });+ expect(result).toMatchInlineSnapshot(`+ "Found 1 matches in 1 locations:+ /src/index.ts:10: const foo = "bar""+ `);+ });++ it('should format multiple matches', () => {+ const result = formatGrepResults({+ matches: ['/src/index.ts:10: match1', '/src/utils.ts:20: match2', '/src/types.ts:30: match3'],+ totalMatches: 5,+ });+ expect(result).toMatchInlineSnapshot(`+ "Found 5 matches in 3 locations:+ /src/index.ts:10: match1+ /src/utils.ts:20: match2+ /src/types.ts:30: match3"+ `);+ });++ it('should truncate matches exceeding maxDisplay', () => {+ const matches = Array.from({ length: 25 }, (_, i) => `match${i + 1}`);+ const result = formatGrepResults({+ matches,+ totalMatches: 100,+ });+ expect(result).toMatchInlineSnapshot(`+ "Found 100 matches in 25 locations:+ match1+ match2+ match3+ match4+ match5+ match6+ match7+ match8+ match9+ match10+ match11+ match12+ match13+ match14+ match15+ match16+ match17+ match18+ match19+ match20+ ... and 5 more"+ `);+ });++ it('should respect custom maxDisplay', () => {+ const matches = ['match1', 'match2', 'match3', 'match4', 'match5'];+ const result = formatGrepResults({+ matches,+ maxDisplay: 3,+ totalMatches: 10,+ });+ expect(result).toMatchInlineSnapshot(`+ "Found 10 matches in 5 locations:+ match1+ match2+ match3+ ... and 2 more"+ `);+ });+});diff --git a/packages/prompts/src/prompts/fileSystem/formatGrepResults.ts b/packages/prompts/src/prompts/fileSystem/formatGrepResults.tsnew file mode 100644index 00000000000..ad2e142b676--- /dev/null+++ b/packages/prompts/src/prompts/fileSystem/formatGrepResults.ts@@ -0,0 +1,24 @@+export interface FormatGrepResultsParams {+ matches: string[];+ maxDisplay?: number;+ totalMatches: number;+}++export const formatGrepResults = ({+ totalMatches,+ matches,+ maxDisplay = 20,+}: FormatGrepResultsParams): string => {+ const message = `Found ${totalMatches} matches in ${matches.length} locations`;++ if (matches.length === 0) {+ return message;+ }++ const displayMatches = matches.slice(0, maxDisplay);+ const matchList = displayMatches.map((m) => ` ${m}`).join('\n');+ const moreInfo =+ matches.length > maxDisplay ? `\n ... and ${matches.length - maxDisplay} more` : '';++ return `${message}:\n${matchList}${moreInfo}`;+};diff --git a/packages/prompts/src/prompts/fileSystem/formatKillResult.test.ts b/packages/prompts/src/prompts/fileSystem/formatKillResult.test.tsnew file mode 100644index 00000000000..3841a846b9f--- /dev/null+++ b/packages/prompts/src/prompts/fileSystem/formatKillResult.test.ts@@ -0,0 +1,30 @@+import { describe, expect, it } from 'vitest';++import { formatKillResult } from './formatKillResult';++describe('formatKillResult', () => {+ it('should format successful kill', () => {+ const result = formatKillResult({+ shellId: 'shell-123',+ success: true,+ });+ expect(result).toMatchInlineSnapshot(`"Successfully killed shell: shell-123"`);+ });++ it('should format failed kill', () => {+ const result = formatKillResult({+ error: 'Process not found',+ shellId: 'shell-456',+ success: false,+ });+ expect(result).toMatchInlineSnapshot(`"Failed to kill shell: Process not found"`);+ });++ it('should format failed kill without error message', () => {+ const result = formatKillResult({+ shellId: 'shell-789',+ success: false,+ });+ expect(result).toMatchInlineSnapshot(`"Failed to kill shell: undefined"`);+ });+});diff --git a/packages/prompts/src/prompts/fileSystem/formatKillResult.ts b/packages/prompts/src/prompts/fileSystem/formatKillResult.tsnew file mode 100644index 00000000000..04307036441--- /dev/null+++ b/packages/prompts/src/prompts/fileSystem/formatKillResult.ts@@ -0,0 +1,9 @@+export interface FormatKillResultParams {+ error?: string;+ shellId: string;+ success: boolean;+}++export const formatKillResult = ({ success, shellId, error }: FormatKillResultParams): string => {+ return success ? `Successfully killed shell: ${shellId}` : `Failed to kill shell: ${error}`;+};diff --git a/packages/prompts/src/prompts/fileSystem/formatMoveResults.test.ts b/packages/prompts/src/prompts/fileSystem/formatMoveResults.test.tsnew file mode 100644index 00000000000..ae7520d5f96--- /dev/null+++ b/packages/prompts/src/prompts/fileSystem/formatMoveResults.test.ts@@ -0,0 +1,37 @@+import { describe, expect, it } from 'vitest';++import { formatMoveResults } from './formatMoveResults';++describe('formatMoveResults', () => {+ it('should format all successful moves', () => {+ const results = [{ success: true }, { success: true }, { success: true }];+ const result = formatMoveResults(results);+ expect(result).toMatchInlineSnapshot(`"Successfully moved 3 item(s)."`);+ });++ it('should format all failed moves', () => {+ const results = [{ success: false }, { success: false }];+ const result = formatMoveResults(results);+ expect(result).toMatchInlineSnapshot(`"Failed to move all 2 item(s)."`);+ });++ it('should format partial success', () => {+ const results = [{ success: true }, { success: false }, { success: true }];+ const result = formatMoveResults(results);+ expect(result).toMatchInlineSnapshot(+ `"Moved 2 item(s) successfully. Failed to move 1 item(s)."`,+ );+ });++ it('should handle single item success', () => {+ const results = [{ success: true }];+ const result = formatMoveResults(results);+ expect(result).toMatchInlineSnapshot(`"Successfully moved 1 item(s)."`);+ });++ it('should handle single item failure', () => {+ const results = [{ success: false }];+ const result = formatMoveResults(results);+ expect(result).toMatchInlineSnapshot(`"Failed to move all 1 item(s)."`);+ });+});diff --git a/packages/prompts/src/prompts/fileSystem/formatMoveResults.ts b/packages/prompts/src/prompts/fileSystem/formatMoveResults.tsnew file mode 100644index 00000000000..9562a398709--- /dev/null+++ b/packages/prompts/src/prompts/fileSystem/formatMoveResults.ts@@ -0,0 +1,20 @@+export interface MoveResultItem {+ success: boolean;+}++export const formatMoveResults = (results: MoveResultItem[]): string => {+ const successCount = results.filter((r) => r.success).length;+ const failedCount = results.length - successCount;+ const allSucceeded = failedCount === 0;+ const allFailed = successCount === 0;++ if (allSucceeded) {+ return `Successfully moved ${results.length} item(s).`;+ }++ if (allFailed) {+ return `Failed to move all ${results.length} item(s).`;+ }++ return `Moved ${successCount} item(s) successfully. Failed to move ${failedCount} item(s).`;+};diff --git a/packages/prompts/src/prompts/fileSystem/formatMultipleFiles.test.ts b/packages/prompts/src/prompts/fileSystem/formatMultipleFiles.test.tsnew file mode 100644index 00000000000..9c871700741--- /dev/null+++ b/packages/prompts/src/prompts/fileSystem/formatMultipleFiles.test.ts@@ -0,0 +1,54 @@+import { describe, expect, it } from 'vitest';++import { formatMultipleFiles } from './formatMultipleFiles';++describe('formatMultipleFiles', () => {+ it('should format single file', () => {+ const files = [{ content: 'hello world', filename: 'test.txt' }];+ const result = formatMultipleFiles(files);+ expect(result).toMatchInlineSnapshot(`+ "Read 1 file(s):++ === test.txt ===+ hello world"+ `);+ });++ it('should format multiple files', () => {+ const files = [+ { content: 'content 1', filename: 'file1.txt' },+ { content: 'content 2', filename: 'file2.txt' },+ ];+ const result = formatMultipleFiles(files);+ expect(result).toMatchInlineSnapshot(`+ "Read 2 file(s):++ === file1.txt ===+ content 1++ === file2.txt ===+ content 2"+ `);+ });++ it('should handle empty files array', () => {+ const result = formatMultipleFiles([]);+ expect(result).toMatchInlineSnapshot(`+ "Read 0 file(s):++ "+ `);+ });++ it('should handle files with multiline content', () => {+ const files = [{ content: 'line 1\nline 2', filename: 'multi.txt' }];+ const result = formatMultipleFiles(files);+ expect(result).toMatchInlineSnapshot(`+ "Read 1 file(s):++ === multi.txt ===+ line 1+ line 2"+ `);+ });+});diff --git a/packages/prompts/src/prompts/fileSystem/formatMultipleFiles.ts b/packages/prompts/src/prompts/fileSystem/formatMultipleFiles.tsnew file mode 100644index 00000000000..2fd8131f9c9--- /dev/null+++ b/packages/prompts/src/prompts/fileSystem/formatMultipleFiles.ts@@ -0,0 +1,9 @@+export interface FileContentItem {+ content: string;+ filename: string;+}++export const formatMultipleFiles = (files: FileContentItem[]): string => {+ const fileContents = files.map((f) => `=== ${f.filename} ===\n${f.content}`).join('\n\n');+ return `Read ${files.length} file(s):\n\n${fileContents}`;+};diff --git a/packages/prompts/src/prompts/fileSystem/formatRenameResult.test.ts b/packages/prompts/src/prompts/fileSystem/formatRenameResult.test.tsnew file mode 100644index 00000000000..97d455a39a5--- /dev/null+++ b/packages/prompts/src/prompts/fileSystem/formatRenameResult.test.ts@@ -0,0 +1,35 @@+import { describe, expect, it } from 'vitest';++import { formatRenameResult } from './formatRenameResult';++describe('formatRenameResult', () => {+ it('should format successful rename', () => {+ const result = formatRenameResult({+ newName: 'newFile.ts',+ oldPath: '/src/oldFile.ts',+ success: true,+ });+ expect(result).toMatchInlineSnapshot(+ `"Successfully renamed file /src/oldFile.ts to newFile.ts"`,+ );+ });++ it('should format failed rename', () => {+ const result = formatRenameResult({+ error: 'File already exists',+ newName: 'existing.ts',+ oldPath: '/src/file.ts',+ success: false,+ });+ expect(result).toMatchInlineSnapshot(`"Failed to rename file: File already exists"`);+ });++ it('should format failed rename without error message', () => {+ const result = formatRenameResult({+ newName: 'newName.ts',+ oldPath: '/src/file.ts',+ success: false,+ });+ expect(result).toMatchInlineSnapshot(`"Failed to rename file: undefined"`);+ });+});diff --git a/packages/prompts/src/prompts/fileSystem/formatRenameResult.ts b/packages/prompts/src/prompts/fileSystem/formatRenameResult.tsnew file mode 100644index 00000000000..2c4c9fa3257--- /dev/null+++ b/packages/prompts/src/prompts/fileSystem/formatRenameResult.ts@@ -0,0 +1,17 @@+export interface FormatRenameResultParams {+ error?: string;+ newName: string;+ oldPath: string;+ success: boolean;+}++export const formatRenameResult = ({+ success,+ oldPath,+ newName,+ error,+}: FormatRenameResultParams): string => {+ return success+ ? `Successfully renamed file ${oldPath} to ${newName}`+ : `Failed to rename file: ${error}`;+};diff --git a/packages/prompts/src/prompts/fileSystem/formatWriteResult.test.ts b/packages/prompts/src/prompts/fileSystem/formatWriteResult.test.tsnew file mode 100644index 00000000000..d743d8caff9--- /dev/null+++ b/packages/prompts/src/prompts/fileSystem/formatWriteResult.test.ts@@ -0,0 +1,30 @@+import { describe, expect, it } from 'vitest';++import { formatWriteResult } from './formatWriteResult';++describe('formatWriteResult', () => {+ it('should format successful write', () => {+ const result = formatWriteResult({+ path: '/src/newFile.ts',+ success: true,+ });+ expect(result).toMatchInlineSnapshot(`"Successfully wrote to /src/newFile.ts"`);+ });++ it('should format failed write with error', () => {+ const result = formatWriteResult({+ error: 'Permission denied',+ path: '/protected/file.ts',+ success: false,+ });+ expect(result).toMatchInlineSnapshot(`"Failed to write file: Permission denied"`);+ });++ it('should format failed write without error message', () => {+ const result = formatWriteResult({+ path: '/some/path.ts',+ success: false,+ });+ expect(result).toMatchInlineSnapshot(`"Failed to write file: Unknown error"`);+ });+});diff --git a/packages/prompts/src/prompts/fileSystem/formatWriteResult.ts b/packages/prompts/src/prompts/fileSystem/formatWriteResult.tsnew file mode 100644index 00000000000..ae255d5ba3b--- /dev/null+++ b/packages/prompts/src/prompts/fileSystem/formatWriteResult.ts@@ -0,0 +1,11 @@+export interface FormatWriteResultParams {+ error?: string;+ path: string;+ success: boolean;+}++export const formatWriteResult = ({ success, path, error }: FormatWriteResultParams): string => {+ return success+ ? `Successfully wrote to ${path}`+ : `Failed to write file: ${error || 'Unknown error'}`;+};diff --git a/packages/prompts/src/prompts/fileSystem/index.ts b/packages/prompts/src/prompts/fileSystem/index.tsnew file mode 100644index 00000000000..46a3b46c324--- /dev/null+++ b/packages/prompts/src/prompts/fileSystem/index.ts@@ -0,0 +1,13 @@+export * from './formatCommandOutput';+export * from './formatCommandResult';+export * from './formatEditResult';+export * from './formatFileContent';+export * from './formatFileList';+export * from './formatFileSearchResults';+export * from './formatGlobResults';+export * from './formatGrepResults';+export * from './formatKillResult';+export * from './formatMoveResults';+export * from './formatMultipleFiles';+export * from './formatRenameResult';+export * from './formatWriteResult';diff --git a/packages/prompts/src/prompts/index.ts b/packages/prompts/src/prompts/index.tsindex 43fcf40faad..c42510c0c12 100644--- a/packages/prompts/src/prompts/index.ts+++ b/packages/prompts/src/prompts/index.ts@@ -2,6 +2,7 @@ export * from './agentBuilder';export * from './agentGroup';export * from './chatMessages';export * from './files';+export * from './fileSystem';export * from './groupChat';export * from './gtd';export * from './knowledgeBaseQA';diff --git a/src/services/chat/index.ts b/src/services/chat/index.tsindex e7f3c3c46ed..6e3d9733d58 100644--- a/src/services/chat/index.ts+++ b/src/services/chat/index.ts@@ -138,6 +138,7 @@ class ChatService {plugins: pluginIds,} = resolveAgentConfig({agentId: targetAgentId,+ groupId, // Pass groupId for supervisor detectionmodel: payload.model,plugins: enabledPlugins,provider: payload.provider,diff --git a/src/services/chat/mecha/agentConfigResolver.test.ts b/src/services/chat/mecha/agentConfigResolver.test.tsindex 79839ad2716..1e0a788d5a1 100644--- a/src/services/chat/mecha/agentConfigResolver.test.ts+++ b/src/services/chat/mecha/agentConfigResolver.test.ts@@ -627,7 +627,7 @@ describe('resolveAgentConfig', () => {});});- describe('supervisor agent (slug from agentGroup store)', () => {+ describe('supervisor agent (detected via groupId)', () => {const mockGroupStoreState = { groupMap: {} };const mockGroupWithSupervisor = {agents: [@@ -651,18 +651,11 @@ describe('resolveAgentConfig', () => {);});- it('should detect supervisor agent from agentGroup store when not found in agent store', () => {- // Mock: supervisor agent is found in agentGroup store- vi.spyOn(- agentGroupSelectors.agentGroupByIdSelectors,- 'groupBySupervisorAgentId',- ).mockReturnValue(() => mockGroupWithSupervisor as any);-- // Mock: getGroupBySupervisorAgentId for building groupSupervisorContext- vi.spyOn(- agentGroupSelectors.agentGroupSelectors,- 'getGroupBySupervisorAgentId',- ).mockReturnValue(() => mockGroupWithSupervisor as any);+ it('should detect supervisor agent using groupId for direct lookup', () => {+ // Mock: groupById returns the group+ vi.spyOn(agentGroupSelectors.agentGroupByIdSelectors, 'groupById').mockReturnValue(+ () => mockGroupWithSupervisor as any,+ );// Mock: getGroupMembers returns non-supervisor agentsvi.spyOn(agentGroupSelectors.agentGroupSelectors, 'getGroupMembers').mockReturnValue(@@ -680,7 +673,10 @@ describe('resolveAgentConfig', () => {systemRole: 'You are a group supervisor...',});- const result = resolveAgentConfig({ agentId: 'supervisor-agent-id' });+ const result = resolveAgentConfig({+ agentId: 'supervisor-agent-id',+ groupId: 'group-123',+ });expect(result.isBuiltinAgent).toBe(true);expect(result.slug).toBe('group-supervisor');@@ -689,17 +685,10 @@ describe('resolveAgentConfig', () => {});it('should pass groupSupervisorContext to getAgentRuntimeConfig', () => {- // Mock: supervisor agent is found in agentGroup store- vi.spyOn(- agentGroupSelectors.agentGroupByIdSelectors,- 'groupBySupervisorAgentId',- ).mockReturnValue(() => mockGroupWithSupervisor as any);-- // Mock: getGroupBySupervisorAgentId for building groupSupervisorContext- vi.spyOn(- agentGroupSelectors.agentGroupSelectors,- 'getGroupBySupervisorAgentId',- ).mockReturnValue(() => mockGroupWithSupervisor as any);+ // Mock: groupById returns the group+ vi.spyOn(agentGroupSelectors.agentGroupByIdSelectors, 'groupById').mockReturnValue(+ () => mockGroupWithSupervisor as any,+ );// Mock: getGroupMembers returns non-supervisor agentsvi.spyOn(agentGroupSelectors.agentGroupSelectors, 'getGroupMembers').mockReturnValue(@@ -718,7 +707,10 @@ describe('resolveAgentConfig', () => {systemRole: 'You are a group supervisor...',});- resolveAgentConfig({ agentId: 'supervisor-agent-id' });+ resolveAgentConfig({+ agentId: 'supervisor-agent-id',+ groupId: 'group-123',+ });expect(getAgentRuntimeConfigSpy).toHaveBeenCalledWith('group-supervisor',@@ -736,31 +728,53 @@ describe('resolveAgentConfig', () => {);});- it('should treat as regular agent when supervisor is not found in agentGroup store', () => {- // Mock: supervisor agent is NOT found in agentGroup store- vi.spyOn(- agentGroupSelectors.agentGroupByIdSelectors,- 'groupBySupervisorAgentId',- ).mockReturnValue(() => undefined);-- const result = resolveAgentConfig({ agentId: 'some-other-agent' });+ it('should treat as regular agent when groupId is not provided', () => {+ // Without groupId, cannot detect supervisor+ const result = resolveAgentConfig({ agentId: 'supervisor-agent-id' });expect(result.isBuiltinAgent).toBe(false);expect(result.slug).toBeUndefined();expect(result.plugins).toEqual(['plugin-a', 'plugin-b']); // Falls back to agent config plugins});- it('should work correctly when regenerating supervisor message', () => {- // This simulates the regenerate flow where agentId is the supervisor agent ID- vi.spyOn(- agentGroupSelectors.agentGroupByIdSelectors,- 'groupBySupervisorAgentId',- ).mockReturnValue(() => mockGroupWithSupervisor as any);+ it('should treat as regular agent when agentId does not match group supervisorAgentId', () => {+ // Mock: groupById returns the group+ vi.spyOn(agentGroupSelectors.agentGroupByIdSelectors, 'groupById').mockReturnValue(+ () => mockGroupWithSupervisor as any,+ );- vi.spyOn(- agentGroupSelectors.agentGroupSelectors,- 'getGroupBySupervisorAgentId',- ).mockReturnValue(() => mockGroupWithSupervisor as any);+ // Pass a different agentId that is not the supervisor+ const result = resolveAgentConfig({+ agentId: 'some-other-agent',+ groupId: 'group-123',+ });++ expect(result.isBuiltinAgent).toBe(false);+ expect(result.slug).toBeUndefined();+ expect(result.plugins).toEqual(['plugin-a', 'plugin-b']);+ });++ it('should treat as regular agent when group is not found', () => {+ // Mock: groupById returns undefined+ vi.spyOn(agentGroupSelectors.agentGroupByIdSelectors, 'groupById').mockReturnValue(+ () => undefined,+ );++ const result = resolveAgentConfig({+ agentId: 'supervisor-agent-id',+ groupId: 'non-existent-group',+ });++ expect(result.isBuiltinAgent).toBe(false);+ expect(result.slug).toBeUndefined();+ expect(result.plugins).toEqual(['plugin-a', 'plugin-b']);+ });++ it('should work correctly when regenerating supervisor message with groupId', () => {+ // This simulates the regenerate flow where both agentId and groupId are provided+ vi.spyOn(agentGroupSelectors.agentGroupByIdSelectors, 'groupById').mockReturnValue(+ () => mockGroupWithSupervisor as any,+ );vi.spyOn(agentGroupSelectors.agentGroupSelectors, 'getGroupMembers').mockReturnValue(() => [{ id: 'member-agent-1', title: 'Agent 1' }] as any,@@ -772,7 +786,10 @@ describe('resolveAgentConfig', () => {systemRole: 'Supervisor system role',});- const result = resolveAgentConfig({ agentId: 'supervisor-agent-id' });+ const result = resolveAgentConfig({+ agentId: 'supervisor-agent-id',+ groupId: 'group-123',+ });// Should correctly identify as builtin supervisor agentexpect(result.isBuiltinAgent).toBe(true);diff --git a/src/services/chat/mecha/agentConfigResolver.ts b/src/services/chat/mecha/agentConfigResolver.tsindex 5826d5c0514..a7a46b93f0c 100644--- a/src/services/chat/mecha/agentConfigResolver.ts+++ b/src/services/chat/mecha/agentConfigResolver.ts@@ -55,6 +55,12 @@ export interface AgentConfigResolverContext {/** Document content for page-agent */documentContent?: string;+ /**+ * Group ID for supervisor detection.+ * When provided, used for direct lookup instead of iterating all groups.+ */+ groupId?: string;+/** Current model being used (for template variables) */model?: string;/** Plugins enabled for the agent */@@ -114,30 +120,19 @@ export const resolveAgentConfig = (ctx: AgentConfigResolverContext): ResolvedAgeconst basePlugins = agentConfig.plugins ?? [];// Check if this is a builtin agent- // First check agent store, then check if this is a supervisor agent in agentGroup store+ // First check agent store, then check if this is a supervisor agent via groupIdlet slug = agentSelectors.getAgentSlugById(agentId)(agentStoreState);log('slug from agentStore: %s (agentId: %s)', slug, agentId);- // If not found in agent store, check if this is a supervisor agent in any group- // Supervisor agents have their slug stored in agentGroup store, not agent store- if (!slug) {+ // If not found in agent store, check if this is a supervisor agent using groupId+ // This is more reliable than iterating all groups to find a match+ if (!slug && ctx.groupId) {const groupStoreState = getChatGroupStoreState();- const groupMap = groupStoreState.groupMap;- const groupMapKeys = Object.keys(groupMap);- log(- 'checking groupStore for supervisor - groupMap has %d groups: %o',- groupMapKeys.length,- groupMapKeys.map((key) => ({- groupId: key,- supervisorAgentId: groupMap[key]?.supervisorAgentId,- title: groupMap[key]?.title,- })),- );+ const group = agentGroupByIdSelectors.groupById(ctx.groupId)(groupStoreState);- const group = agentGroupByIdSelectors.groupBySupervisorAgentId(agentId)(groupStoreState);log(- 'groupBySupervisorAgentId result for agentId %s: %o',- agentId,+ 'checking supervisor via groupId %s: group=%o',+ ctx.groupId,group? {groupId: group.id,@@ -147,10 +142,15 @@ export const resolveAgentConfig = (ctx: AgentConfigResolverContext): ResolvedAge: null,);- if (group) {- // This is a supervisor agent - use the builtin slug+ // Check if this agent is the supervisor of the specified group+ if (group?.supervisorAgentId === agentId) {slug = BUILTIN_AGENT_SLUGS.groupSupervisor;- log('agentId %s identified as group supervisor, assigned slug: %s', agentId, slug);+ log(+ 'agentId %s identified as group supervisor for group %s, assigned slug: %s',+ agentId,+ ctx.groupId,+ slug,+ );}}@@ -213,15 +213,17 @@ export const resolveAgentConfig = (ctx: AgentConfigResolverContext): ResolvedAge}// Build groupSupervisorContext if this is a group-supervisor agent+ // Use groupId for direct lookup instead of reverse lookup by supervisorAgentIdlet groupSupervisorContext;- if (slug === BUILTIN_AGENT_SLUGS.groupSupervisor) {- log('building groupSupervisorContext for agentId: %s', agentId);+ if (slug === BUILTIN_AGENT_SLUGS.groupSupervisor && ctx.groupId) {+ log('building groupSupervisorContext for agentId: %s, groupId: %s', agentId, ctx.groupId);const groupStoreState = getChatGroupStoreState();- // Find the group by supervisor agent ID- const group = agentGroupSelectors.getGroupBySupervisorAgentId(agentId)(groupStoreState);+ // Direct lookup using groupId+ const group = agentGroupByIdSelectors.groupById(ctx.groupId)(groupStoreState);log(- 'getGroupBySupervisorAgentId result: %o',+ 'groupById result for %s: %o',+ ctx.groupId,group? {agentsCount: group.agents?.length,@@ -253,7 +255,7 @@ export const resolveAgentConfig = (ctx: AgentConfigResolverContext): ResolvedAgehasSystemPrompt: !!groupSupervisorContext.systemPrompt,});} else {- log('WARNING: group not found for supervisor agentId: %s', agentId);+ log('WARNING: group not found for groupId: %s', ctx.groupId);}}diff --git a/src/store/chat/slices/aiChat/actions/streamingExecutor.ts b/src/store/chat/slices/aiChat/actions/streamingExecutor.tsindex d15734c488c..4d426e38002 100644--- a/src/store/chat/slices/aiChat/actions/streamingExecutor.ts+++ b/src/store/chat/slices/aiChat/actions/streamingExecutor.ts@@ -160,14 +160,16 @@ export const streamingExecutor: StateCreator<// - agentId is used for session ID (message storage location)const effectiveAgentId = paramSubAgentId || agentId;- // Get scope from operation context if available+ // Get scope and groupId from operation context if availableconst operation = operationId ? get().operations[operationId] : undefined;const scope = operation?.context.scope;+ const groupId = operation?.context.groupId;// Resolve agent config with builtin agent runtime config merged// This ensures runtime plugins (e.g., 'lobe-agent-builder' for Agent Builder) are includedconst { agentConfig: agentConfigData, plugins: pluginIds } = resolveAgentConfig({agentId: effectiveAgentId || '',+ groupId, // Pass groupId for supervisor detectionscope, // Pass scope from operation context});@@ -341,6 +343,7 @@ export const streamingExecutor: StateCreator<// - max_tokens/reasoning_effort based on chatConfig settingsconst resolved = resolveAgentConfig({agentId: effectiveAgentId,+ groupId, // Pass groupId for supervisor detectionscope, // scope is already available from line 329});const finalAgentConfig = agentConfig || resolved.agentConfig;@@ -594,7 +597,8 @@ export const streamingExecutor: StateCreator<// - max_tokens/reasoning_effort based on chatConfig settingsconst { agentConfig: agentConfigData } = resolveAgentConfig({agentId: effectiveAgentId || '',- scope: context.scope, // Pass scope from context parameter (available at line 883)+ groupId, // Pass groupId for supervisor detection+ scope: context.scope, // Pass scope from context parameter});// Use agent config from agentId