JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.
Python
feat(agents): add /agents command with custom agent management and @agent-xxx invocation
ldstyle8f1ffb3396536
diff --git a/jiuwenswarm/agents/harness/team/config_loader.py b/jiuwenswarm/agents/harness/team/config_loader.pyindex 7f919a03a5..6afe6b0152 100644--- a/jiuwenswarm/agents/harness/team/config_loader.py+++ b/jiuwenswarm/agents/harness/team/config_loader.py@@ -178,9 +178,29 @@ def _build_agents_config(team_raw: dict[str, Any], config_base: dict[str, Any])logger.warning("[TeamConfigLoader] agents config is empty, using default leader/teammate")agents_raw = {"leader": {}, "teammate": {}}+ top_agents = config_base.get("agents", {})+ if not isinstance(top_agents, dict):+ top_agents = {}+agents: dict[str, Any] = {}for agent_key, raw_agent_config in agents_raw.items():- agent_config = dict(raw_agent_config) if isinstance(raw_agent_config, dict) else {}+ if isinstance(raw_agent_config, str) and raw_agent_config.startswith("$"):+ ref_name = raw_agent_config[1:]+ if ref_name in top_agents:+ agent_config = deepcopy(top_agents[ref_name])+ logger.debug(+ "[TeamConfigLoader] resolved agent reference $%s -> agents.%s",+ ref_name,+ ref_name,+ )+ else:+ logger.warning(+ "[TeamConfigLoader] agent reference '$%s' not found in top-level agents, using defaults",+ ref_name,+ )+ agent_config = {}+ else:+ agent_config = dict(raw_agent_config) if isinstance(raw_agent_config, dict) else {}# No longer auto-fill all skills from global into each member by default.# On spawn, team-shared skills are synced into member workspace/skills/.# ensure_team_shared_skills_initialized also mirrors team-shared skills to agent global.diff --git a/jiuwenswarm/channels/tui/frontend/src/core/attachments.ts b/jiuwenswarm/channels/tui/frontend/src/core/attachments.tsindex 38c093e969..a9b419570e 100644--- a/jiuwenswarm/channels/tui/frontend/src/core/attachments.ts+++ b/jiuwenswarm/channels/tui/frontend/src/core/attachments.ts@@ -125,6 +125,10 @@ export function extractAttachmentsFromText(for (const match of matches) {const rawPath = match[2] ?? match[3] ?? "";+ // Skip @agent-xxx and @"xxx (agent)" mentions — they're agent references, not files+ if (rawPath.startsWith("agent-") || rawPath.endsWith(" (agent)")) {+ continue;+ }const candidate = buildAttachmentCandidate(rawPath, options);if (!candidate) {continue;@@ -139,6 +143,33 @@ export function extractAttachmentsFromText(return attachments;}+/**+ * Extract agent type names from @agent-xxx and @"xxx (agent)" mentions.+ * Returns deduplicated list of agent type names (without "agent-" prefix).+ */+export function extractAgentMentions(content: string): string[] {+ if (!content) return [];++ const results: string[] = [];++ // Match quoted format: @"<type> (agent)"+ const quotedAgentRegex = /(^|[\t ])@"([\w:.@-]+) \(agent\)"/gm;+ let match;+ while ((match = quotedAgentRegex.exec(content)) !== null) {+ if (match[2]) {+ results.push(match[2]);+ }+ }++ // Match unquoted format: @agent-<type>+ const unquotedAgentRegex = /(^|[\t ])@(agent-[\w:.@-]+)/gm;+ while ((match = unquotedAgentRegex.exec(content)) !== null) {+ results.push(match[2].slice("agent-".length));+ }++ return [...new Set(results)];+}+export function extractFilePathsFromPaste(text: string,options: Omit<AttachmentExtractionOptions, "classifyAttachment"> = {},diff --git a/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/agents.ts b/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/agents.tsnew file mode 100644index 0000000000..5eb0f69a6a--- /dev/null+++ b/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/agents.ts@@ -0,0 +1,413 @@+import { flattenArrayPayload, makeItem } from "../helpers.js";+import { CommandKind, type SlashCommand } from "../types.js";++interface AgentDef {+ name: string;+ description: string;+ prompt: string;+ source: string;+ file_path: string | null;+ model: string | null;+ tools: string[];+ disallowed_tools: string[];+ color: string | null;+ permission_mode: string | null;+ memory_scope: string | null;+ shadowed_by: string | null;+ enabled: boolean | null;+ when_to_use: string | null;+ max_iterations: number | null;+ skills: string[] | null;+}++const SOURCE_LABELS: Record<string, string> = {+ builtin: "内置",+ user: "用户 (~)",+ project: "项目",+ local: "本地",+};++function formatSource(agent: AgentDef): string {+ const label = SOURCE_LABELS[agent.source] || agent.source;+ if (agent.shadowed_by) {+ const shadow = SOURCE_LABELS[agent.shadowed_by] || agent.shadowed_by;+ return `${label} (被 ${shadow} 覆盖)`;+ }+ return label;+}++async function listAgents(ctx: import("../types.js").CommandContext): Promise<void> {+ const payload = await ctx.request<{ agents?: AgentDef[] }>("agents.list", {});+ const agents = payload.agents || [];++ if (agents.length === 0) {+ ctx.addItem(makeItem(ctx.sessionId, "info", "没有配置的 Agent", "*"));+ return;+ }++ const items = agents.map((a) => {+ let status = "";+ if (a.enabled === true) status = "[启用] ";+ else if (a.enabled === false) status = "[禁用] ";+ return {+ label: a.name,+ description: `${status}${formatSource(a)} | ${a.description || "无描述"}`,+ };+ });++ ctx.addItem(+ makeItem(ctx.sessionId, "info", `Agent 列表 (${agents.length})`, "*", {+ view: "list",+ title: "Agents",+ items,+ }),+ );+}++async function getAgent(+ ctx: import("../types.js").CommandContext,+ name: string,+): Promise<void> {+ const payload = await ctx.request<{ agent?: AgentDef; error?: string }>(+ "agents.get",+ { name },+ );+ if (payload.error) {+ ctx.addItem(makeItem(ctx.sessionId, "error", payload.error));+ return;+ }+ const a = payload.agent;+ if (!a) {+ ctx.addItem(makeItem(ctx.sessionId, "error", `Agent 不存在: ${name}`));+ return;+ }++ const lines = [+ `名称: ${a.name}`,+ `描述: ${a.description || "无"}`,+ `状态: ${a.enabled === true ? "已启用" : a.enabled === false ? "已禁用" : "内置"}`,+ `来源: ${formatSource(a)}`,+ `调用时机: ${a.when_to_use || a.description || "无"}`,+ `模型: ${a.model || "默认"}`,+ `颜色: ${a.color || "默认"}`,+ `权限模式: ${a.permission_mode || "默认"}`,+ `记忆范围: ${a.memory_scope || "默认"}`,+ `最大迭代: ${a.max_iterations ?? "默认(200)"}`,+ `工具: ${a.tools.length > 0 ? a.tools.join(", ") : "无"}`,+ `禁用工具: ${a.disallowed_tools.length > 0 ? a.disallowed_tools.join(", ") : "无"}`,+ `技能: ${a.skills && a.skills.length > 0 ? a.skills.join(", ") : "无"}`,+ `文件路径: ${a.file_path || "内置"}`,+ ``,+ `--- System Prompt ---`,+ a.prompt,+ ];++ ctx.addItem(makeItem(ctx.sessionId, "info", lines.join("\n"), "*"));+}++export function createAgentsCommand(): SlashCommand {+ async function agentNameCompletion(ctx: import("../types.js").CommandContext): Promise<string[]> {+ try {+ const payload = await ctx.request<{ agents?: AgentDef[] }>("agents.list", {});+ return (payload.agents || []).map((a) => a.name);+ } catch {+ return [];+ }+ }++ return {+ name: "agents",+ description: "管理 Agent 配置 (list, get, create, update, enable, disable, delete)",+ usage: "/agents [list|get|create|update|enable|disable|delete]",+ example: "/agents list | /agents get Explore",+ kind: CommandKind.BUILT_IN,+ action: async (ctx) => {+ await listAgents(ctx);+ },+ subCommands: [+ {+ name: "list",+ description: "列出所有 Agent",+ usage: "/agents list",+ example: "/agents list",+ kind: CommandKind.BUILT_IN,+ takesArgs: false,+ action: async (ctx) => {+ await listAgents(ctx);+ },+ },+ {+ name: "get",+ description: "查看指定 Agent 详情",+ usage: "/agents get <name>",+ example: "/agents get Explore",+ kind: CommandKind.BUILT_IN,+ takesArgs: true,+ completion: agentNameCompletion,+ action: async (ctx, args) => {+ const name = args.trim().split(/\s+/)[0] || "";+ if (!name) {+ ctx.addItem(makeItem(ctx.sessionId, "error", "用法: /agents get <name>"));+ return;+ }+ await getAgent(ctx, name);+ },+ },+ {+ name: "create",+ description: "创建自定义 Agent(LLM 生成 prompt,可选 --project/--local)",+ usage: "/agents create [--project|--local] <名称> <描述>",+ example: "/agents create bug-hunter 根因分析专家 | /agents create --project proj-agent 项目级",+ kind: CommandKind.BUILT_IN,+ takesArgs: true,+ action: async (ctx, args) => {+ let trimmed = args.trim();+ if (!trimmed) {+ ctx.addItem(+ makeItem(ctx.sessionId, "error", "用法: /agents create [--project|--local] <名称> <描述>"),+ );+ return;+ }++ // 解析 --project / --local 位置标志+ let location = "user";+ if (trimmed.startsWith("--project ")) {+ location = "project";+ trimmed = trimmed.slice("--project ".length).trim();+ } else if (trimmed.startsWith("--local ")) {+ location = "local";+ trimmed = trimmed.slice("--local ".length).trim();+ }++ const spaceIdx = trimmed.indexOf(" ");+ const rawName = spaceIdx > 0 ? trimmed.slice(0, spaceIdx).trim() : trimmed;+ const name = rawName.replace(/[,,]+$/, "").trim();+ const desc = spaceIdx > 0 ? trimmed.slice(spaceIdx + 1).trim() : (name || "");++ // 模板 prompt 作为 LLM 生成的 fallback+ const defaultPrompt = [+ `你是 ${name},专注于:${desc}。你的职责是端到端完成任务,不只是分析和建议——利用所有可用工具实际执行。`,+ "",+ "## 工作流程",+ "1. 理解任务:明确输入、目标和约束条件",+ "2. 收集信息:利用搜索和文件读取工具获取必要的上下文",+ "3. 分析处理:基于收集的信息进行系统性分析",+ "4. 执行操作:根据用户要求和分析结果,完成任务",+ "5. 验证结果:确认操作已成功完成,结果符合预期",+ "",+ "## 核心原则",+ "- 先理解再行动,不盲目猜测",+ "- 用代码和证据说话,不做空洞判断",+ "- 不确定时主动说明,标注假设和风险",+ "- 复杂问题分步骤推进,每步确认结果",+ "",+ "## 输出规范",+ "- 报告已完成的实际操作(修改了哪些文件、运行了什么命令、结果如何)",+ "- 使用结构化格式(列表、表格、代码块)",+ "- 引用具体文件路径和行号",+ "- 区分已完成的操作和仍需人工处理的事项",+ ].join("\n");++ const payload = await ctx.request<{+ agent?: AgentDef;+ error?: string;+ generated?: boolean;+ applied?: boolean;+ reload_error?: string | null;+ }>(+ "agents.create",+ {+ name,+ description: desc,+ when_to_use: `当你需要${desc}时使用`,+ prompt: defaultPrompt,+ location,+ tools: ["*"],+ generate: true,+ },+ 60000,+ );+ if (payload.error) {+ ctx.addItem(makeItem(ctx.sessionId, "error", `创建失败: ${payload.error}`));+ } else {+ const generated = payload.generated ? " (LLM 生成)" : "";+ const locLabel = location !== "user" ? ` (${location})` : "";+ ctx.addItem(makeItem(ctx.sessionId, "info", `Agent 已创建: ${name}${generated}${locLabel}\n文件: ${payload.agent?.file_path ?? `~/.jiuwenswarm/agents/${name}.md`}\n使用 /agents get ${name} 查看详情`));+ }+ },+ },+ {+ name: "update",+ description: "更新 Agent(加 --generate 由 LLM 生成 prompt)",+ usage: "/agents update <name> [--generate] <新描述>",+ example: "/agents update bug-hunter 更好的描述 | /agents update bug-hunter --generate 重写",+ kind: CommandKind.BUILT_IN,+ takesArgs: true,+ completion: agentNameCompletion,+ action: async (ctx, args) => {+ let trimmed = args.trim();+ const spaceIdx = trimmed.indexOf(" ");+ const name = spaceIdx > 0 ? trimmed.slice(0, spaceIdx).trim() : trimmed;+ let desc = spaceIdx > 0 ? trimmed.slice(spaceIdx + 1).trim() : "";+ if (!name) {+ ctx.addItem(+ makeItem(ctx.sessionId, "error", "用法: /agents update <name> [--generate] <新描述>"),+ );+ return;+ }++ // 解析 --generate 标志+ let generate = false;+ if (desc.startsWith("--generate ")) {+ generate = true;+ desc = desc.slice("--generate ".length).trim();+ } else if (desc === "--generate") {+ generate = true;+ desc = "";+ }++ if (!desc) {+ // 无参数时展示当前配置+ const payload = await ctx.request<{ agent?: AgentDef; error?: string }>(+ "agents.get",+ { name },+ );+ if (payload.error || !payload.agent) {+ ctx.addItem(makeItem(ctx.sessionId, "error", payload.error || `Agent 不存在: ${name}`));+ return;+ }+ await getAgent(ctx, name);+ ctx.addItem(makeItem(ctx.sessionId, "info", "用法: /agents update <name> [--generate] <新描述>"));+ return;+ }++ // 模板 prompt 作为 LLM 生成的 fallback+ const defaultPrompt = [+ `你是 ${name},专注于:${desc}。你的职责是端到端完成任务,不只是分析和建议——利用所有可用工具实际执行。`,+ "",+ "## 工作流程",+ "1. 理解任务:明确输入、目标和约束条件",+ "2. 收集信息:利用搜索和文件读取工具获取必要的上下文",+ "3. 分析处理:基于收集的信息进行系统性分析",+ "4. 执行操作:利用可用工具实际完成任务,不只是输出方案或建议",+ "5. 验证结果:确认操作已成功完成,结果符合预期",+ "",+ "## 核心原则",+ "- 你是执行者,不是顾问——利用工具完成任务,不只是口头建议",+ "- 先理解再行动,不盲目猜测",+ "- 用代码和证据说话,不做空洞判断",+ "- 不确定时主动说明,标注假设和风险",+ "- 复杂问题分步骤推进,每步确认结果",+ "",+ "## 输出规范",+ "- 报告已完成的实际操作(修改了哪些文件、运行了什么命令、结果如何)",+ "- 使用结构化格式(列表、表格、代码块)",+ "- 引用具体文件路径和行号",+ "- 区分已完成的操作和仍需人工处理的事项",+ ].join("\n");++ const payload = await ctx.request<{+ agent?: AgentDef;+ error?: string;+ generated?: boolean;+ applied?: boolean;+ reload_error?: string | null;+ }>(+ "agents.update",+ {+ name,+ description: desc,+ when_to_use: `当你需要${desc}时使用`,+ prompt: defaultPrompt,+ generate,+ },+ 60000,+ );+ if (payload.error) {+ ctx.addItem(makeItem(ctx.sessionId, "error", `更新失败: ${payload.error}`));+ } else {+ const generated = payload.generated ? " (LLM 生成)" : "";+ ctx.addItem(makeItem(ctx.sessionId, "info", `Agent 已更新: ${name}${generated}`));+ }+ },+ },+ {+ name: "enable",+ description: "启用自定义 Agent",+ usage: "/agents enable <name>",+ example: "/agents enable bug-hunter",+ kind: CommandKind.BUILT_IN,+ takesArgs: true,+ completion: agentNameCompletion,+ action: async (ctx, args) => {+ const name = args.trim().split(/\s+/)[0] || "";+ if (!name) {+ ctx.addItem(makeItem(ctx.sessionId, "error", "用法: /agents enable <name>"));+ return;+ }+ const payload = await ctx.request<{ enabled?: boolean; error?: string }>(+ "agents.enable",+ { name },+ );+ if (payload.error) {+ ctx.addItem(makeItem(ctx.sessionId, "error", `启用失败: ${payload.error}`));+ } else {+ ctx.addItem(makeItem(ctx.sessionId, "info", `Agent 已启用: ${name}`));+ }+ },+ },+ {+ name: "disable",+ description: "禁用自定义 Agent",+ usage: "/agents disable <name>",+ example: "/agents disable bug-hunter",+ kind: CommandKind.BUILT_IN,+ takesArgs: true,+ completion: agentNameCompletion,+ action: async (ctx, args) => {+ const name = args.trim().split(/\s+/)[0] || "";+ if (!name) {+ ctx.addItem(makeItem(ctx.sessionId, "error", "用法: /agents disable <name>"));+ return;+ }+ const payload = await ctx.request<{ enabled?: boolean; error?: string }>(+ "agents.disable",+ { name },+ );+ if (payload.error) {+ ctx.addItem(makeItem(ctx.sessionId, "error", `禁用失败: ${payload.error}`));+ } else {+ ctx.addItem(makeItem(ctx.sessionId, "info", `Agent 已禁用: ${name}`));+ }+ },+ },+ {+ name: "delete",+ description: "删除自定义 Agent",+ usage: "/agents delete <name>",+ example: "/agents delete my-agent",+ kind: CommandKind.BUILT_IN,+ takesArgs: true,+ completion: agentNameCompletion,+ action: async (ctx, args) => {+ const name = args.trim().split(/\s+/)[0] || "";+ if (!name) {+ ctx.addItem(makeItem(ctx.sessionId, "error", "用法: /agents delete <name>"));+ return;+ }+ const payload = await ctx.request<{ ok?: boolean; error?: string }>(+ "agents.delete",+ { name },+ );+ if (payload.error) {+ ctx.addItem(makeItem(ctx.sessionId, "error", `删除失败: ${payload.error}`));+ } else if (payload.ok === false) {+ ctx.addItem(makeItem(ctx.sessionId, "error", `Agent 不存在: ${name}`));+ } else {+ ctx.addItem(makeItem(ctx.sessionId, "info", `Agent 已删除: ${name}`));+ }+ },+ },+ ],+ };+}\ No newline at end of filediff --git a/jiuwenswarm/channels/tui/frontend/src/core/commands/registry.ts b/jiuwenswarm/channels/tui/frontend/src/core/commands/registry.tsindex ded53462d4..5e8f0a6ef5 100644--- a/jiuwenswarm/channels/tui/frontend/src/core/commands/registry.ts+++ b/jiuwenswarm/channels/tui/frontend/src/core/commands/registry.ts@@ -35,6 +35,7 @@ import { createStatusCommand } from "./builtins/status.js";import { createStatusLineCommand } from "./builtins/statusline.js";import { createSkillsCommand } from "./builtins/skills.js";import { createTeamSkillsCommand } from "./builtins/teamskills.js";+import { createAgentsCommand } from "./builtins/agents.js";import { createAutoHarnessCommand } from "./builtins/auto-harness.js";import { createThemeCommand } from "./builtins/theme.js";import { createWorkspaceCommand } from "./builtins/workspace-dir.js";@@ -42,6 +43,7 @@ import { createUsageCommand } from "./builtins/usage.js";export function createBuiltinCommands(): SlashCommand[] {const commands: SlashCommand[] = [+ createAgentsCommand(),createHelpCommand(() => commands),createBranchCommand(),createClearCommand(),diff --git a/jiuwenswarm/channels/tui/frontend/src/ui/app-screen.ts b/jiuwenswarm/channels/tui/frontend/src/ui/app-screen.tsindex edf0feb761..8a2e1ff8ef 100644--- a/jiuwenswarm/channels/tui/frontend/src/ui/app-screen.ts+++ b/jiuwenswarm/channels/tui/frontend/src/ui/app-screen.ts@@ -33,6 +33,7 @@ import {} from "../core/commands/CommandService.js";import type { SlashCommand } from "../core/commands/types.js";import { addCommandEcho, addError, addInfo } from "../core/commands/helpers.js";+import { CheckboxList, CheckboxGroup as CheckboxGroupType } from "./components/checkbox-list.js";import type { FileAttachment } from "../core/protocol.js";import {type ModelListPayload,@@ -110,6 +111,16 @@ type ModelListState = {current: string;};+type ToolSelectorState = {+ list: CheckboxList;+ name: string;+ description: string;+ when_to_use: string;+ defaultPrompt: string;+ location: string;+ generate: boolean;+};+type ThemeListState = {list: SelectList;current: string;@@ -496,6 +507,7 @@ export class AppScreen implements Component, Focusable {private ctrlCPendingForQuestionTimer: ReturnType<typeof setTimeout> | null = null;private resumeSessionList: ResumeSessionListState | null = null;private modelList: ModelListState | null = null;+ private toolSelector: ToolSelectorState | null = null;private mcpList: McpListState | null = null;private mcpDetail: McpDetailState | null = null;private mcpTools: McpToolsState | null = null;@@ -787,6 +799,7 @@ export class AppScreen implements Component, Focusable {this.mcpList !== null ||this.mcpTools !== null ||this.modelList !== null ||+ this.toolSelector !== null ||this.themeList !== null ||this.configEditorState !== null;@@ -1041,6 +1054,12 @@ export class AppScreen implements Component, Focusable {return;}+ if (!snapshot.pendingQuestion && this.toolSelector !== null) {+ this.toolSelector.list.handleInput(data);+ this.tui.requestRender();+ return;+ }+if (!snapshot.pendingQuestion && this.mcpList !== null) {this.mcpList.list.handleInput(data);this.tui.requestRender();@@ -1178,6 +1197,7 @@ export class AppScreen implements Component, Focusable {...(!this.statusViewState ? this.buildConfigEditorLines(width) : []),...this.buildResumeSessionListLines(width),...this.buildModelListLines(width),+ ...this.buildToolSelectorLines(width),...this.buildMcpListLines(width),...this.buildMcpDetailLines(width),...this.buildMcpToolsLines(width),@@ -1268,6 +1288,62 @@ export class AppScreen implements Component, Focusable {return;}+ // Intercept /agents create to show tool selector+ if (/^\/agents\s+create/.test(text)) {+ const args = text.replace(/^\/agents\s+create\s*/, "").trim();+ let location = "user";+ let trimmed = args;+ if (trimmed.startsWith("--project ")) {+ location = "project";+ trimmed = trimmed.slice("--project ".length).trim();+ } else if (trimmed.startsWith("--local ")) {+ location = "local";+ trimmed = trimmed.slice("--local ".length).trim();+ }++ if (!trimmed) {+ this.state.addItem(+ addError(snapshot.sessionId, "用法: /agents create [--project|--local] <名称> <描述>"),+ );+ this.tui.requestRender();+ return;+ }++ const spaceIdx = trimmed.indexOf(" ");+ const rawName = spaceIdx > 0 ? trimmed.slice(0, spaceIdx).trim() : trimmed;+ const name = rawName.replace(/[,,]+$/, "").trim();+ const desc = spaceIdx > 0 ? trimmed.slice(spaceIdx + 1).trim() : (name || "");++ const when_to_use = `当你需要${desc}时使用`;+ const defaultPrompt = [+ `你是 ${name},专注于:${desc}。`,+ "",+ "## 工作流程",+ "1. 理解任务:明确输入、目标和约束条件",+ "2. 收集信息:利用搜索和文件读取工具获取必要的上下文",+ "3. 分析处理:基于收集的信息进行系统性分析",+ "4. 输出结果:提供清晰、可执行的结论或方案",+ "",+ "## 核心原则",+ "- 先理解再行动,不盲目猜测",+ "- 用代码和证据说话,不做空洞判断",+ "- 不确定时主动说明,标注假设和风险",+ "- 复杂问题分步骤推进,每步确认结果",+ "",+ "## 输出规范",+ "- 关键结论前置,细节在后",+ "- 使用结构化格式(列表、表格、代码块)",+ "- 引用具体文件路径和行号",+ "- 区分事实结论和推测判断",+ ].join("\n");++ await this.openToolSelector(name, desc, when_to_use, defaultPrompt, location, true);+ this.editor.addToHistory(text);+ this.editor.setText("");+ this.state.addItem(addCommandEcho(snapshot.sessionId, text));+ return;+ }+if (text.startsWith("/")) {if (/^\/(?:resume|continue)\s*$/.test(text)) {this.editor.addToHistory(text);@@ -1728,6 +1804,85 @@ export class AppScreen implements Component, Focusable {}}+ private async openToolSelector(+ name: string,+ description: string,+ when_to_use: string,+ defaultPrompt: string,+ location: string,+ generate: boolean,+ ): Promise<void> {+ const snapshot = this.state.getSnapshot();+ try {+ const payload = await this.state.request<{+ tools?: Array<{ name: string; internal_name: string; description: string; group: string }>;+ groups?: string[];+ disallowed_for_subagents?: string[];+ }>("agents.tools_list", {});++ const toolDefs = payload.tools || [];+ const groupsOrder = payload.groups || [];+ const disallowed = new Set(payload.disallowed_for_subagents || []);++ // Default checked groups: 核心, 搜索, 代码智能+ const defaultCheckedGroups = new Set(["核心", "搜索", "代码智能"]);++ // Build CheckboxGroups+ const groups: CheckboxGroupType[] = [];+ const groupMap = new Map<string, Array<{ label: string; value: string; checked: boolean; description?: string }>>();++ for (const group of groupsOrder) {+ groupMap.set(group, []);+ }++ for (const t of toolDefs) {+ // Skip tools that are disallowed for subagents+ if (disallowed.has(t.name) || disallowed.has(t.internal_name)) continue;++ const items = groupMap.get(t.group) || groupMap.get("高级") || [];+ items.push({+ label: t.name,+ value: t.name,+ checked: defaultCheckedGroups.has(t.group),+ description: t.description,+ });+ groupMap.set(t.group, items);+ }++ for (const group of groupsOrder) {+ const items = groupMap.get(group) || [];+ if (items.length > 0) {+ groups.push({ name: group, items });+ }+ }++ const list = new CheckboxList(groups, 10);+ list.onSelect = (selectedTools) => {+ this.handleToolSelection(selectedTools, name, description, when_to_use, defaultPrompt, location, generate);+ };+ list.onCancel = () => {+ this.toolSelector = null;+ this.tui.requestRender();+ };++ this.toolSelector = {+ list,+ name,+ description,+ when_to_use,+ defaultPrompt,+ location,+ generate,+ };+ this.tui.requestRender();+ } catch (e) {+ this.state.addItem(+ addError(snapshot.sessionId, `获取工具列表失败: ${e}`),+ );+ this.tui.requestRender();+ }+ }+private async handleModelSelection(modelName: string): Promise<void> {if (!modelName) {return;@@ -1765,6 +1920,63 @@ export class AppScreen implements Component, Focusable {}}+ private async handleToolSelection(+ selectedTools: string[],+ name: string,+ description: string,+ when_to_use: string,+ defaultPrompt: string,+ location: string,+ generate: boolean,+ ): Promise<void> {+ this.toolSelector = null;+ this.tui.requestRender();++ try {+ const payload = await this.state.request<{+ agent?: { file_path?: string };+ error?: string;+ generated?: boolean;+ applied?: boolean;+ reload_error?: string | null;+ }>(+ "agents.create",+ {+ name,+ description,+ when_to_use,+ prompt: defaultPrompt,+ location,+ tools: selectedTools.length > 0 ? selectedTools : ["*"],+ generate,+ },+ 60000,+ );++ const snapshot = this.state.getSnapshot();+ if (payload.error) {+ this.state.addItem(+ addError(snapshot.sessionId, `创建失败: ${payload.error}`),+ );+ } else {+ const generated = payload.generated ? " (LLM 生成)" : "";+ const locLabel = location !== "user" ? ` (${location})` : "";+ const toolsLabel = selectedTools.length > 0 ? ` | 工具: ${selectedTools.join(", ")}` : " | 工具: *";+ this.state.addItem(+ addInfo(+ snapshot.sessionId,+ `Agent 已创建: ${name}${generated}${locLabel}${toolsLabel}\n文件: ${payload.agent?.file_path ?? `~/.jiuwenswarm/agents/${name}.md`}\n使用 /agents get ${name} 查看详情`,+ ),+ );+ }+ } catch (e) {+ this.state.addItem(+ addError(this.state.getSnapshot().sessionId, `创建失败: ${e}`),+ );+ }+ this.tui.requestRender();+ }+private buildModelListLines(width: number): string[] {if (!this.modelList) {return [];@@ -1779,6 +1991,11 @@ export class AppScreen implements Component, Focusable {];}+ private buildToolSelectorLines(width: number): string[] {+ if (this.toolSelector === null) return [];+ return this.toolSelector.list.render(width);+ }+private async openMcpList(): Promise<void> {const snapshot = this.state.getSnapshot();try {diff --git a/jiuwenswarm/channels/tui/frontend/src/ui/components/checkbox-list.ts b/jiuwenswarm/channels/tui/frontend/src/ui/components/checkbox-list.tsnew file mode 100644index 0000000000..7fbcd1c575--- /dev/null+++ b/jiuwenswarm/channels/tui/frontend/src/ui/components/checkbox-list.ts@@ -0,0 +1,237 @@+import chalk from "chalk";+import { matchesKey } from "@mariozechner/pi-tui/dist/keys.js";++/**+ * CheckboxList — pi-tui Component for grouped multi-select with checkbox items.+ *+ * Navigation: ↑/↓ moves focus, Space toggles checked state, Enter confirms, Esc cancels.+ * Group headers are non-selectable separator lines.+ */+export interface CheckboxItem {+ label: string;+ value: string;+ checked: boolean;+ description?: string;+}++export interface CheckboxGroup {+ name: string;+ items: CheckboxItem[];+}++interface FlatItem {+ type: "header" | "item";+ groupIndex: number;+ itemIndex?: number;+ label: string;+ value?: string;+ checked?: boolean;+ description?: string;+}++interface CheckboxTheme {+ header: (text: string) => string;+ checkedMark: string;+ uncheckedMark: string;+ focusMarker: string;+ focus: (text: string) => string;+ dim: (text: string) => string;+ hint: (text: string) => string;+}++const defaultTheme: CheckboxTheme = {+ header: (t) => chalk.bold.cyan(`── ${t} ──`),+ checkedMark: "x",+ uncheckedMark: " ",+ focusMarker: "›",+ focus: (t) => chalk.bold(t),+ dim: (t) => chalk.dim(t),+ hint: (t) => chalk.dim(t),+};++export class CheckboxList {+ private groups: CheckboxGroup[];+ private flatItems: FlatItem[];+ private selectedIndex: number = 0;+ private maxVisible: number;+ private theme: CheckboxTheme;++ onSelect: (selectedValues: string[]) => void = () => {};+ onCancel: () => void = () => {};++ constructor(groups: CheckboxGroup[], maxVisible: number = 10, theme?: CheckboxTheme) {+ this.groups = groups;+ this.maxVisible = maxVisible;+ this.theme = theme ?? defaultTheme;++ // Flatten groups into a flat list of selectable items + header separators+ this.flatItems = [];+ for (let gi = 0; gi < groups.length; gi++) {+ this.flatItems.push({+ type: "header",+ groupIndex: gi,+ label: groups[gi].name,+ });+ for (let ii = 0; ii < groups[gi].items.length; ii++) {+ this.flatItems.push({+ type: "item",+ groupIndex: gi,+ itemIndex: ii,+ label: groups[gi].items[ii].label,+ value: groups[gi].items[ii].value,+ checked: groups[gi].items[ii].checked,+ description: groups[gi].items[ii].description,+ });+ }+ }++ // Set initial focus to first selectable item+ for (let i = 0; i < this.flatItems.length; i++) {+ if (this.flatItems[i].type === "item") {+ this.selectedIndex = i;+ break;+ }+ }+ }++ render(width: number): string[] {+ const lines: string[] = [];++ // Calculate visible range with scrolling+ const selectableIndices = this.flatItems+ .map((_, i) => i)+ .filter((i) => this.flatItems[i].type === "item");++ const totalSelectable = selectableIndices.length;+ const halfVisible = Math.floor(this.maxVisible / 2);++ let startIdx = 0;+ let endIdx = this.flatItems.length;++ if (totalSelectable > this.maxVisible) {+ const currentSelectableIdx = selectableIndices.indexOf(this.selectedIndex);+ const scrollStart = Math.max(0, currentSelectableIdx - halfVisible);+ const scrollEnd = Math.min(totalSelectable, scrollStart + this.maxVisible);++ const firstVisible = selectableIndices[scrollStart];+ const lastVisible = selectableIndices[scrollEnd - 1];++ startIdx = firstVisible;+ endIdx = lastVisible + 1;+ }++ for (let i = startIdx; i < endIdx; i++) {+ const item = this.flatItems[i];++ if (item.type === "header") {+ lines.push(this.theme.header(item.label));+ continue;+ }++ const isFocused = i === this.selectedIndex;+ const marker = isFocused ? this.theme.focusMarker : " ";+ const checkMark = item.checked+ ? this.theme.checkedMark+ : this.theme.uncheckedMark;++ let line: string;+ if (item.description) {+ const labelWidth = 14;+ const paddedLabel = item.label.padEnd(labelWidth);+ line = ` ${marker}[${checkMark}] ${paddedLabel}${item.description}`;+ } else {+ line = ` ${marker}[${checkMark}] ${item.label}`;+ }++ if (isFocused) {+ line = this.theme.focus(line);+ } else if (!item.checked) {+ line = this.theme.dim(line);+ }++ lines.push(line);+ }++ // Scroll indicator+ if (totalSelectable > this.maxVisible) {+ const currentSelectableIdx = selectableIndices.indexOf(this.selectedIndex);+ lines.push(this.theme.hint(` (${currentSelectableIdx + 1}/${totalSelectable})`));+ }++ // Hint line+ lines.push(this.theme.hint("↑/↓ 导航 · 空格切换 · Enter 确认 · Esc 取消"));++ return lines;+ }++ handleInput(data: string): void {+ if (matchesKey(data, "up") || data === "k") {+ this._moveUp();+ } else if (matchesKey(data, "down") || data === "j") {+ this._moveDown();+ } else if (matchesKey(data, "space")) {+ this._toggleChecked();+ } else if (matchesKey(data, "enter") || matchesKey(data, "return")) {+ this._confirm();+ } else if (matchesKey(data, "escape")) {+ this.onCancel();+ }+ }++ invalidate(): void {+ // No-op (pi-tui Component interface)+ }++ getCheckedValues(): string[] {+ return this.flatItems+ .filter((item) => item.type === "item" && item.checked)+ .map((item) => item.value!);+ }++ private _moveUp(): void {+ for (let i = this.selectedIndex - 1; i >= 0; i--) {+ if (this.flatItems[i].type === "item") {+ this.selectedIndex = i;+ return;+ }+ }+ // Wrap to bottom+ for (let i = this.flatItems.length - 1; i > this.selectedIndex; i--) {+ if (this.flatItems[i].type === "item") {+ this.selectedIndex = i;+ return;+ }+ }+ }++ private _moveDown(): void {+ for (let i = this.selectedIndex + 1; i < this.flatItems.length; i++) {+ if (this.flatItems[i].type === "item") {+ this.selectedIndex = i;+ return;+ }+ }+ // Wrap to top+ for (let i = 0; i < this.selectedIndex; i++) {+ if (this.flatItems[i].type === "item") {+ this.selectedIndex = i;+ return;+ }+ }+ }++ private _toggleChecked(): void {+ const item = this.flatItems[this.selectedIndex];+ if (item.type === "item") {+ item.checked = !item.checked;+ // Also update the backing group data+ if (item.groupIndex !== undefined && item.itemIndex !== undefined) {+ this.groups[item.groupIndex].items[item.itemIndex].checked = item.checked;+ }+ }+ }++ private _confirm(): void {+ this.onSelect(this.getCheckedValues());+ }+}\ No newline at end of filediff --git a/jiuwenswarm/common/config.py b/jiuwenswarm/common/config.pyindex 6f738902c2..ec2e41e8c6 100644--- a/jiuwenswarm/common/config.py+++ b/jiuwenswarm/common/config.py@@ -18,7 +18,7 @@ from ruamel.yaml import YAMLfrom jiuwenswarm.common.utils import get_config_dir, get_config_file_CONFIG_MODULE_DIR = Path(__file__).parent-_CONFIG_YAML_PATH = get_config_file()+CONFIG_YAML_PATH = get_config_file()# Check if user workspace exists and use it if configured via env_user_config = os.getenv("JIUWENSWARM_CONFIG_DIR")@@ -114,16 +114,16 @@ def get_config():def get_config_raw():"""读 config.yaml 原始内容(不解析环境变量),供局部更新后写回。"""- with open(_CONFIG_YAML_PATH, "r", encoding="utf-8") as f:+ with open(CONFIG_YAML_PATH, "r", encoding="utf-8") as f:return yaml.safe_load(f) or {}def set_config(config):- with open(_CONFIG_YAML_PATH, "w", encoding="utf-8") as f:+ with open(CONFIG_YAML_PATH, "w", encoding="utf-8") as f:yaml.safe_dump(config, f, allow_unicode=True, sort_keys=False)-def _load_yaml_round_trip(config_path: Path):+def load_yaml_round_trip(config_path: Path):"""ruamel 加载 config,保留注释与格式。"""rt = YAML()rt.preserve_quotes = True@@ -131,7 +131,7 @@ def _load_yaml_round_trip(config_path: Path):return rt.load(f)-def _dump_yaml_round_trip(config_path: Path, data: Any) -> None:+def dump_yaml_round_trip(config_path: Path, data: Any) -> None:"""ruamel 写回 config,保留注释与格式。"""rt = YAML()rt.preserve_quotes = True@@ -143,9 +143,15 @@ def _dump_yaml_round_trip(config_path: Path, data: Any) -> None:rt.dump(data, f)+# Backward-compat aliases — downstream modules import the underscore-prefixed names+_CONFIG_YAML_PATH = CONFIG_YAML_PATH+_load_yaml_round_trip = load_yaml_round_trip+_dump_yaml_round_trip = dump_yaml_round_trip++def update_heartbeat_in_config(payload: dict[str, Any]) -> None:"""只更新 heartbeat 段并写回。"""- data = _load_yaml_round_trip(_CONFIG_YAML_PATH)+ data = load_yaml_round_trip(CONFIG_YAML_PATH)if "heartbeat" not in data:data["heartbeat"] = {}hb = data["heartbeat"]@@ -155,12 +161,12 @@ def update_heartbeat_in_config(payload: dict[str, Any]) -> None:hb["target"] = payload["target"]if "active_hours" in payload:hb["active_hours"] = payload["active_hours"]- _dump_yaml_round_trip(_CONFIG_YAML_PATH, data)+ dump_yaml_round_trip(CONFIG_YAML_PATH, data)def update_channel_in_config(channel_id: str, conf: dict[str, Any]) -> None:"""只更新 channels[channel_id] 并写回。"""- data = _load_yaml_round_trip(_CONFIG_YAML_PATH)+ data = load_yaml_round_trip(CONFIG_YAML_PATH)if "channels" not in data:data["channels"] = {}channels = data["channels"]@@ -169,7 +175,7 @@ def update_channel_in_config(channel_id: str, conf: dict[str, Any]) -> None:section = channels[channel_id]for k, v in conf.items():section[k] = v- _dump_yaml_round_trip(_CONFIG_YAML_PATH, data)+ dump_yaml_round_trip(CONFIG_YAML_PATH, data)def update_channel_subsection_in_config(@@ -178,7 +184,7 @@ def update_channel_subsection_in_config(conf: dict[str, Any],) -> None:"""更新 channels[channel_id][subsection_id] 并写回。"""- data = _load_yaml_round_trip(_CONFIG_YAML_PATH)+ data = load_yaml_round_trip(CONFIG_YAML_PATH)if "channels" not in data:data["channels"] = {}channels = data["channels"]@@ -190,7 +196,7 @@ def update_channel_subsection_in_config(subsection = section[subsection_id]for k, v in conf.items():subsection[k] = v- _dump_yaml_round_trip(_CONFIG_YAML_PATH, data)+ dump_yaml_round_trip(CONFIG_YAML_PATH, data)def update_preferred_language_in_config(lang: str) -> None:@@ -198,9 +204,9 @@ def update_preferred_language_in_config(lang: str) -> None:normalized = str(lang or "zh").strip().lower()if normalized not in ("zh", "en"):normalized = "zh"- data = _load_yaml_round_trip(_CONFIG_YAML_PATH)+ data = load_yaml_round_trip(CONFIG_YAML_PATH)data["preferred_language"] = normalized- _dump_yaml_round_trip(_CONFIG_YAML_PATH, data)+ dump_yaml_round_trip(CONFIG_YAML_PATH, data)def set_preferred_language_in_config_file(config_path: Path, lang: str) -> None:@@ -210,64 +216,64 @@ def set_preferred_language_in_config_file(config_path: Path, lang: str) -> None:lang = "zh"if not config_path.exists():return- data = _load_yaml_round_trip(config_path)+ data = load_yaml_round_trip(config_path)data["preferred_language"] = lang- _dump_yaml_round_trip(config_path, data)+ dump_yaml_round_trip(config_path, data)def update_browser_in_config(updates: dict[str, Any]) -> None:"""只更新 browser 段(如 chrome_path)并写回。"""- data = _load_yaml_round_trip(_CONFIG_YAML_PATH)+ data = load_yaml_round_trip(CONFIG_YAML_PATH)if "browser" not in data:data["browser"] = {}section = data["browser"]for k, v in updates.items():section[k] = v- _dump_yaml_round_trip(_CONFIG_YAML_PATH, data)+ dump_yaml_round_trip(CONFIG_YAML_PATH, data)def update_context_engine_enabled_in_config(value: bool) -> None:"""更新 react.context_engine_config.enabled(上下文压缩开关)并写回。"""- data = _load_yaml_round_trip(_CONFIG_YAML_PATH)+ data = load_yaml_round_trip(CONFIG_YAML_PATH)if "react" not in data:data["react"] = {}react = data["react"]if "context_engine_config" not in react:react["context_engine_config"] = {}react["context_engine_config"]["enabled"] = value- _dump_yaml_round_trip(_CONFIG_YAML_PATH, data)+ dump_yaml_round_trip(CONFIG_YAML_PATH, data)def update_kv_cache_affinity_enabled_in_config(value: bool) -> None:"""更新 react.context_engine_config.enable_kv_cache_release(算力/KV 亲和释放)并写回。"""- data = _load_yaml_round_trip(_CONFIG_YAML_PATH)+ data = load_yaml_round_trip(CONFIG_YAML_PATH)if "react" not in data:data["react"] = {}react = data["react"]if "context_engine_config" not in react:react["context_engine_config"] = {}react["context_engine_config"]["enable_kv_cache_release"] = value- _dump_yaml_round_trip(_CONFIG_YAML_PATH, data)+ dump_yaml_round_trip(CONFIG_YAML_PATH, data)def update_permissions_enabled_in_config(value: bool) -> None:"""更新 permissions.enabled(工具安全护栏开关)并写回。"""- data = _load_yaml_round_trip(_CONFIG_YAML_PATH)+ data = load_yaml_round_trip(CONFIG_YAML_PATH)if "permissions" not in data:data["permissions"] = {}data["permissions"]["enabled"] = value- _dump_yaml_round_trip(_CONFIG_YAML_PATH, data)+ dump_yaml_round_trip(CONFIG_YAML_PATH, data)def update_updater_in_config(updates: dict[str, Any]) -> None:"""只更新 updater 段并写回。"""- data = _load_yaml_round_trip(_CONFIG_YAML_PATH)+ data = load_yaml_round_trip(CONFIG_YAML_PATH)if "updater" not in data:data["updater"] = {}section = data["updater"]for key, value in updates.items():section[key] = value- _dump_yaml_round_trip(_CONFIG_YAML_PATH, data)+ dump_yaml_round_trip(CONFIG_YAML_PATH, data)def update_memory_enabled_in_config(mode: str, value: bool) -> None:@@ -281,7 +287,7 @@ def update_proactive_memory_in_config(mode: str, value: bool) -> None:def _update_memory_in_modes_config(mode: str, item: str, value: bool) -> None:- data = _load_yaml_round_trip(_CONFIG_YAML_PATH)+ data = load_yaml_round_trip(CONFIG_YAML_PATH)if "modes" not in data:data["modes"] = {}if "claw" not in data["modes"]:@@ -291,7 +297,7 @@ def _update_memory_in_modes_config(mode: str, item: str, value: bool) -> None:if "memory" not in data["modes"]["claw"][mode]:data["modes"]["claw"][mode]["memory"] = {}data["modes"]["claw"][mode]["memory"][item] = value- _dump_yaml_round_trip(_CONFIG_YAML_PATH, data)+ dump_yaml_round_trip(CONFIG_YAML_PATH, data)# ---------- 数字分身相关配置 ----------@@ -311,13 +317,13 @@ def update_permissions_owner_scopes_in_config(deny_guidance_message: str | None = None,) -> None:"""更新 permissions.owner_scopes(及可选 deny_guidance_message)并写回。"""- data = _load_yaml_round_trip(_CONFIG_YAML_PATH)+ data = load_yaml_round_trip(CONFIG_YAML_PATH)if "permissions" not in data:data["permissions"] = {}data["permissions"]["owner_scopes"] = owner_scopesif deny_guidance_message is not None:data["permissions"]["deny_guidance_message"] = deny_guidance_message- _dump_yaml_round_trip(_CONFIG_YAML_PATH, data)+ dump_yaml_round_trip(CONFIG_YAML_PATH, data)def get_permissions_deny_guidance() -> str:@@ -328,11 +334,11 @@ def get_permissions_deny_guidance() -> str:def update_permissions_deny_guidance_in_config(msg: str) -> None:"""更新 permissions.deny_guidance_message 并写回。"""- data = _load_yaml_round_trip(_CONFIG_YAML_PATH)+ data = load_yaml_round_trip(CONFIG_YAML_PATH)if "permissions" not in data:data["permissions"] = {}data["permissions"]["deny_guidance_message"] = msg- _dump_yaml_round_trip(_CONFIG_YAML_PATH, data)+ dump_yaml_round_trip(CONFIG_YAML_PATH, data)# ---------- Web UI:permissions.tools / rules / approval_overrides ----------@@ -354,11 +360,11 @@ def get_permissions_tools() -> dict[str, Any]:def replace_permissions_tools_in_config(tools: Any) -> None:"""整表替换 ``permissions.tools``;值仅允许 ``allow|ask|deny``(或 legacy ``{\"*\": level}``)。"""normalized = _validate_tools_map(tools)- data = _load_yaml_round_trip(_CONFIG_YAML_PATH)+ data = load_yaml_round_trip(CONFIG_YAML_PATH)if "permissions" not in data:data["permissions"] = {}data["permissions"]["tools"] = normalized- _dump_yaml_round_trip(_CONFIG_YAML_PATH, data)+ dump_yaml_round_trip(CONFIG_YAML_PATH, data)def update_permissions_tool_in_config(tool_name: str, level: Any) -> dict[str, Any]:@@ -375,7 +381,7 @@ def update_permissions_tool_in_config(tool_name: str, level: Any) -> dict[str, Aif not name:raise ValueError("tool name must be non-empty")piece = _validate_tools_map({name: level})- data = _load_yaml_round_trip(_CONFIG_YAML_PATH)+ data = load_yaml_round_trip(CONFIG_YAML_PATH)if "permissions" not in data:data["permissions"] = {}existing = data["permissions"].get("tools")@@ -384,7 +390,7 @@ def update_permissions_tool_in_config(tool_name: str, level: Any) -> dict[str, Amerged = {str(k): v for k, v in existing.items()}merged[name] = piece[name]data["permissions"]["tools"] = merged- _dump_yaml_round_trip(_CONFIG_YAML_PATH, data)+ dump_yaml_round_trip(CONFIG_YAML_PATH, data)return {"tools": dict(merged)}@@ -393,7 +399,7 @@ def delete_permissions_tool_in_config(tool_name: str) -> bool:name = str(tool_name).strip()if not name:raise ValueError("tool name must be non-empty")- data = _load_yaml_round_trip(_CONFIG_YAML_PATH)+ data = load_yaml_round_trip(CONFIG_YAML_PATH)if "permissions" not in data:return Falsetools = data["permissions"].get("tools")@@ -408,7 +414,7 @@ def delete_permissions_tool_in_config(tool_name: str) -> bool:return Falsenew_tools = {k: v for k, v in tools.items() if k != key_to_drop}data["permissions"]["tools"] = new_tools- _dump_yaml_round_trip(_CONFIG_YAML_PATH, data)+ dump_yaml_round_trip(CONFIG_YAML_PATH, data)return True@@ -469,7 +475,7 @@ def create_permissions_rule_in_config(rule: dict[str, Any]) -> dict[str, Any]:raise ValueError("pattern must be non-empty")_normalize_rule_severity_action(stored)- data = _load_yaml_round_trip(_CONFIG_YAML_PATH)+ data = load_yaml_round_trip(CONFIG_YAML_PATH)if "permissions" not in data:data["permissions"] = {}rules = data["permissions"].get("rules")@@ -479,7 +485,7 @@ def create_permissions_rule_in_config(rule: dict[str, Any]) -> dict[str, Any]:raise ValueError(f"rule id already exists: {rid}")rules.append(stored)data["permissions"]["rules"] = rules- _dump_yaml_round_trip(_CONFIG_YAML_PATH, data)+ dump_yaml_round_trip(CONFIG_YAML_PATH, data)return stored@@ -491,7 +497,7 @@ def update_permissions_rule_in_config(rule_id: str, patch: dict[str, Any]) -> diif not isinstance(patch, dict):raise ValueError("patch must be an object")- data = _load_yaml_round_trip(_CONFIG_YAML_PATH)+ data = load_yaml_round_trip(CONFIG_YAML_PATH)if "permissions" not in data:data["permissions"] = {}rules = data["permissions"].get("rules")@@ -527,7 +533,7 @@ def update_permissions_rule_in_config(rule_id: str, patch: dict[str, Any]) -> di_normalize_rule_severity_action(merged)rules[idx] = mergeddata["permissions"]["rules"] = rules- _dump_yaml_round_trip(_CONFIG_YAML_PATH, data)+ dump_yaml_round_trip(CONFIG_YAML_PATH, data)return merged@@ -536,7 +542,7 @@ def delete_permissions_rule_in_config(rule_id: str) -> bool:rid = str(rule_id or "").strip()if not rid:raise ValueError("id is required")- data = _load_yaml_round_trip(_CONFIG_YAML_PATH)+ data = load_yaml_round_trip(CONFIG_YAML_PATH)if "permissions" not in data:return Falserules = data["permissions"].get("rules")@@ -546,7 +552,7 @@ def delete_permissions_rule_in_config(rule_id: str) -> bool:if len(new_rules) == len(rules):return Falsedata["permissions"]["rules"] = new_rules- _dump_yaml_round_trip(_CONFIG_YAML_PATH, data)+ dump_yaml_round_trip(CONFIG_YAML_PATH, data)return True@@ -555,7 +561,7 @@ def delete_permissions_approval_override_in_config(override_id: str) -> bool:oid = str(override_id or "").strip()if not oid:raise ValueError("id is required")- data = _load_yaml_round_trip(_CONFIG_YAML_PATH)+ data = load_yaml_round_trip(CONFIG_YAML_PATH)if "permissions" not in data:return Falseov = data["permissions"].get("approval_overrides")@@ -565,7 +571,7 @@ def delete_permissions_approval_override_in_config(override_id: str) -> bool:if len(new_ov) == len(ov):return Falsedata["permissions"]["approval_overrides"] = new_ov- _dump_yaml_round_trip(_CONFIG_YAML_PATH, data)+ dump_yaml_round_trip(CONFIG_YAML_PATH, data)return True@@ -727,13 +733,13 @@ def get_default_models(config: dict[str, Any] | None = None) -> list[dict[str, Adef update_default_models_in_config(models_list: list[dict[str, Any]]) -> None:"""将默认模型列表写入 config.yaml 的 models.defaults 段。"""- data = _load_yaml_round_trip(_CONFIG_YAML_PATH)+ data = load_yaml_round_trip(CONFIG_YAML_PATH)if "models" not in data:data["models"] = {}data["models"]["defaults"] = models_listif "default" in data["models"]:del data["models"]["default"]- _dump_yaml_round_trip(_CONFIG_YAML_PATH, data)+ dump_yaml_round_trip(CONFIG_YAML_PATH, data)def ensure_defaults_list_in_config() -> list[dict[str, Any]]:@@ -742,7 +748,7 @@ def ensure_defaults_list_in_config() -> list[dict[str, Any]]:如果不存在,将 models.default 单对象迁移为列表条目,并删除冗余的 models.default key。返回 defaults 列表。"""- data = _load_yaml_round_trip(_CONFIG_YAML_PATH)+ data = load_yaml_round_trip(CONFIG_YAML_PATH)models = data.get("models") or {}defaults = models.get("defaults")if isinstance(defaults, list) and defaults:@@ -769,7 +775,7 @@ def ensure_defaults_list_in_config() -> list[dict[str, Any]]:data["models"]["defaults"] = defaults_listif "default" in data["models"]:del data["models"]["default"]- _dump_yaml_round_trip(_CONFIG_YAML_PATH, data)+ dump_yaml_round_trip(CONFIG_YAML_PATH, data)return defaults_list@@ -993,6 +999,8 @@ def replace_teams_in_config(front_payload: dict[str, Any]) -> None:teams_raw = front_payload.get("team")data = _load_yaml_round_trip(_CONFIG_YAML_PATH)+ panel_cfg_modified = False+ agent_registry = Noneif "agents" in front_payload:agent_registry = _build_front_agent_registry(front_payload)panel_cfg = data.get("web_config_panel")@@ -1003,6 +1011,7 @@ def replace_teams_in_config(front_payload: dict[str, Any]) -> None:panel_cfg["agent_team_agents"] = agent_registryelse:panel_cfg.pop("agent_team_agents", None)+ panel_cfg_modified = True# 空数组:删除 modes.team 配置项if isinstance(teams_raw, list) and not teams_raw:@@ -1014,10 +1023,19 @@ def replace_teams_in_config(front_payload: dict[str, Any]) -> None:# 非空数组:正常构建并保存team_mapping = _build_modes_team_mapping(front_payload)+ data = load_yaml_round_trip(CONFIG_YAML_PATH)+ # Merge web_config_panel back into reloaded data (it was written earlier in this function)+ if panel_cfg_modified:+ if "web_config_panel" not in data or not isinstance(data.get("web_config_panel"), dict):+ data["web_config_panel"] = {}+ if agent_registry:+ data["web_config_panel"]["agent_team_agents"] = agent_registry+ else:+ data.get("web_config_panel", {}).pop("agent_team_agents", None)if "modes" not in data or not isinstance(data["modes"], dict):data["modes"] = {}data["modes"]["team"] = team_mapping- _dump_yaml_round_trip(_CONFIG_YAML_PATH, data)+ dump_yaml_round_trip(CONFIG_YAML_PATH, data)def get_mcp_servers() -> list[dict[str, Any]]:@@ -1037,7 +1055,7 @@ def upsert_mcp_server_in_config(server: dict[str, Any]) -> tuple[dict[str, Any],name = str(server.get("name", "")).strip()if not name:raise ValueError("MCP server name is required")- data = _load_yaml_round_trip(_CONFIG_YAML_PATH)+ data = load_yaml_round_trip(CONFIG_YAML_PATH)if "mcp" not in data or not isinstance(data["mcp"], dict):data["mcp"] = {}mcp_cfg = data["mcp"]@@ -1057,7 +1075,7 @@ def upsert_mcp_server_in_config(server: dict[str, Any]) -> tuple[dict[str, Any],breakelse:servers.append(server)- _dump_yaml_round_trip(_CONFIG_YAML_PATH, data)+ dump_yaml_round_trip(CONFIG_YAML_PATH, data)return server, created@@ -1066,7 +1084,7 @@ def set_mcp_server_enabled_in_config(name: str, enabled: bool) -> dict[str, Any]target = str(name or "").strip()if not target:raise ValueError("MCP server name is required")- data = _load_yaml_round_trip(_CONFIG_YAML_PATH)+ data = load_yaml_round_trip(CONFIG_YAML_PATH)if "mcp" not in data or not isinstance(data["mcp"], dict):raise KeyError(f"MCP server '{target}' not found")servers = data["mcp"].get("servers", [])@@ -1078,7 +1096,7 @@ def set_mcp_server_enabled_in_config(name: str, enabled: bool) -> dict[str, Any]if str(item.get("name", "")).strip() != target:continueitem["enabled"] = bool(enabled)- _dump_yaml_round_trip(_CONFIG_YAML_PATH, data)+ dump_yaml_round_trip(CONFIG_YAML_PATH, data)return dict(item)raise KeyError(f"MCP server '{target}' not found")@@ -1099,7 +1117,7 @@ def remove_mcp_server_in_config(name: str) -> dict[str, Any]:target = str(name or "").strip()if not target:raise ValueError("MCP server name is required")- data = _load_yaml_round_trip(_CONFIG_YAML_PATH)+ data = load_yaml_round_trip(CONFIG_YAML_PATH)mcp_cfg = data.get("mcp")if not isinstance(mcp_cfg, dict):raise KeyError(f"MCP server '{target}' not found")@@ -1113,25 +1131,76 @@ def remove_mcp_server_in_config(name: str) -> dict[str, Any]:continueremoved = dict(item)del servers[idx]- _dump_yaml_round_trip(_CONFIG_YAML_PATH, data)+ dump_yaml_round_trip(CONFIG_YAML_PATH, data)return removedraise KeyError(f"MCP server '{target}' not found")+# ---------------------------------------------------------------------------+# react.subagents 段操作+# ---------------------------------------------------------------------------+++def upsert_subagent_in_config(name: str, enabled: bool = True) -> None:+ """在 react.subagents.<name> 中添加或更新 agent 启用状态。++ 自动创建不存在的 react / subagents 段。+ 保留已有的其他 subagent 配置键(如 max_iterations 等)。+ """+ target = str(name or "").strip()+ if not target:+ raise ValueError("subagent name is required")+ data = load_yaml_round_trip(CONFIG_YAML_PATH)+ if "react" not in data or not isinstance(data["react"], dict):+ data["react"] = {}+ react = data["react"]+ if "subagents" not in react or not isinstance(react["subagents"], dict):+ react["subagents"] = {}+ subagents = react["subagents"]+ if target not in subagents or not isinstance(subagents[target], dict):+ subagents[target] = {}+ subagents[target]["enabled"] = bool(enabled)+ dump_yaml_round_trip(CONFIG_YAML_PATH, data)+++def remove_subagent_from_config(name: str) -> bool:+ """从 react.subagents.<name> 中删除 agent 条目。++ Returns:+ True: 找到并删除+ False: 条目不存在+ """+ target = str(name or "").strip()+ if not target:+ raise ValueError("subagent name is required")+ data = load_yaml_round_trip(CONFIG_YAML_PATH)+ react = data.get("react")+ if not isinstance(react, dict):+ return False+ subagents = react.get("subagents")+ if not isinstance(subagents, dict):+ return False+ if target not in subagents:+ return False+ del subagents[target]+ dump_yaml_round_trip(CONFIG_YAML_PATH, data)+ return True++def update_memory_forbidden_enabled_in_config(value: bool) -> None:"""更新 memory.forbidden_memory_definition.enabled(记忆系统敏感信息过滤开关)并写回。"""- data = _load_yaml_round_trip(_CONFIG_YAML_PATH)+ data = load_yaml_round_trip(CONFIG_YAML_PATH)if "memory" not in data:data["memory"] = {}if "forbidden_memory_definition" not in data["memory"]:data["memory"]["forbidden_memory_definition"] = {}data["memory"]["forbidden_memory_definition"]["enabled"] = value- _dump_yaml_round_trip(_CONFIG_YAML_PATH, data)+ dump_yaml_round_trip(CONFIG_YAML_PATH, data)def update_memory_forbidden_description_in_config(description: dict[str, str]) -> None:"""更新 memory.forbidden_memory_definition.description(禁止记忆内容描述)并写回。"""- data = _load_yaml_round_trip(_CONFIG_YAML_PATH)+ data = load_yaml_round_trip(CONFIG_YAML_PATH)if "memory" not in data:data["memory"] = {}if "forbidden_memory_definition" not in data["memory"]:@@ -1144,12 +1213,12 @@ def update_memory_forbidden_description_in_config(description: dict[str, str]) -data["memory"]["forbidden_memory_definition"]["description"] = {**current_desc, **description}else:data["memory"]["forbidden_memory_definition"]["description"] = description- _dump_yaml_round_trip(_CONFIG_YAML_PATH, data)+ dump_yaml_round_trip(CONFIG_YAML_PATH, data)def update_memory_forbidden_in_config(updates: dict[str, Any]) -> None:"""更新 memory.forbidden_memory_definition 并写回。"""- data = _load_yaml_round_trip(_CONFIG_YAML_PATH)+ data = load_yaml_round_trip(CONFIG_YAML_PATH)if "memory" not in data:data["memory"] = {}if "forbidden_memory_definition" not in data["memory"]:@@ -1160,7 +1229,7 @@ def update_memory_forbidden_in_config(updates: dict[str, Any]) -> None:section["description"] = {**section["description"], **v}else:section[k] = v- _dump_yaml_round_trip(_CONFIG_YAML_PATH, data)+ dump_yaml_round_trip(CONFIG_YAML_PATH, data)def _deep_merge(@@ -1229,8 +1298,8 @@ def migrate_config_from_template(if not template_path.exists():return False- template_data = _load_yaml_round_trip(template_path)- user_data = _load_yaml_round_trip(user_config_path)+ template_data = load_yaml_round_trip(template_path)+ user_data = load_yaml_round_trip(user_config_path)if not isinstance(template_data, dict):return False@@ -1247,7 +1316,7 @@ def migrate_config_from_template(# Only write if there are actual changesif merged_data != user_data:- _dump_yaml_round_trip(user_config_path, merged_data)+ dump_yaml_round_trip(user_config_path, merged_data)return Truereturn False@@ -1284,7 +1353,7 @@ def get_model_names() -> list[str]:def add_or_update_model_in_config(name: str, model_config: dict[str, Any]) -> None:"""新增或更新一个模型配置,写入 config.yaml 的 models.<name> 节点。"""- data = _load_yaml_round_trip(_CONFIG_YAML_PATH)+ data = load_yaml_round_trip(CONFIG_YAML_PATH)if "models" not in data:data["models"] = {}if name not in data["models"]:@@ -1296,7 +1365,7 @@ def add_or_update_model_in_config(name: str, model_config: dict[str, Any]) -> Nodel existing[k]else:existing[k] = v- _dump_yaml_round_trip(_CONFIG_YAML_PATH, data)+ dump_yaml_round_trip(CONFIG_YAML_PATH, data)def get_model_config(name: str, index: int | None = None) -> dict[str, Any] | None:@@ -1607,7 +1676,7 @@ def resolve_sandbox_policy_path(value: str | None) -> Path | None:- ``None`` / 空字符串 → 返回 None, 由调用方决定是否落到 jiuwenbox 自身默认 policy;- 仅文件名 (不含路径分隔符) → 在 ``jiuwenbox/configs/`` 下拼接;``configs/`` 探测不到时返回 None (调用方应当报错并提示给绝对路径);- - 含 ``/`` ``\`` 或绝对路径 → 展开 ``~`` / ``$VAR`` 后按整路径返回 (不强校验是否存在,+ - 含 ``/`` ``\\`` 或绝对路径 → 展开 ``~`` / ``$VAR`` 后按整路径返回 (不强校验是否存在,留给上游 ``_load_policy_file`` / jiuwenbox 自己做存在性检查并给出明确错误)。"""if not value:diff --git a/jiuwenswarm/common/schema/message.py b/jiuwenswarm/common/schema/message.pyindex 669e6074e0..7cba027183 100644--- a/jiuwenswarm/common/schema/message.py+++ b/jiuwenswarm/common/schema/message.py@@ -61,6 +61,15 @@ class ReqMethod(Enum):FILES_GET = "files.get"TTS_SYNTHESIZE = "tts.synthesize"+ AGENTS_LIST = "agents.list"+ AGENTS_GET = "agents.get"+ AGENTS_CREATE = "agents.create"+ AGENTS_UPDATE = "agents.update"+ AGENTS_DELETE = "agents.delete"+ AGENTS_ENABLE = "agents.enable"+ AGENTS_DISABLE = "agents.disable"+ AGENTS_TOOLS_LIST = "agents.tools_list"+SKILLS_MARKETPLACE_LIST = "skills.marketplace.list"SKILLS_LIST = "skills.list"SKILLS_INSTALLED = "skills.installed"diff --git a/jiuwenswarm/gateway/channel_manager/tui/tui_connect.py b/jiuwenswarm/gateway/channel_manager/tui/tui_connect.pyindex a6092803e4..b97d83c6b3 100644--- a/jiuwenswarm/gateway/channel_manager/tui/tui_connect.py+++ b/jiuwenswarm/gateway/channel_manager/tui/tui_connect.py@@ -219,6 +219,15 @@ CLI_FORWARD_REQ_METHODS = frozenset("extensions.delete","extensions.toggle","session.fork",+ # Agent configuration+ "agents.list",+ "agents.get",+ "agents.create",+ "agents.update",+ "agents.delete",+ "agents.enable",+ "agents.disable",+ "agents.tools_list",# Schedule task management"schedule.check_config","schedule.update_config",@@ -286,6 +295,15 @@ CLI_FORWARD_NO_LOCAL_HANDLER_METHODS = frozenset("extensions.delete","extensions.toggle","session.fork",+ # Agent configuration+ "agents.list",+ "agents.get",+ "agents.create",+ "agents.update",+ "agents.delete",+ "agents.enable",+ "agents.disable",+ "agents.tools_list",# Schedule task management"schedule.check_config","schedule.update_config",diff --git a/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py b/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.pyindex 605fa86ea3..2e7e9df342 100644--- a/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py+++ b/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py@@ -217,6 +217,15 @@ _FORWARD_REQ_METHODS = frozenset({"extensions.delete","extensions.toggle","team.snapshot",+ # Agent configuration+ "agents.list",+ "agents.get",+ "agents.create",+ "agents.update",+ "agents.delete",+ "agents.enable",+ "agents.disable",+ "agents.tools_list",# Schedule task management"schedule.check_config","schedule.update_config",@@ -271,6 +280,15 @@ _FORWARD_NO_LOCAL_HANDLER_METHODS = frozenset({"extensions.import","extensions.delete","extensions.toggle",+ # Agent configuration+ "agents.list",+ "agents.get",+ "agents.create",+ "agents.update",+ "agents.delete",+ "agents.enable",+ "agents.disable",+ "agents.tools_list",})# 配置信息:config.get 返回、config.set 可修改的键(前端 param 名 -> 环境变量名)diff --git a/jiuwenswarm/gateway/message_handler/command_parser/slash_command.py b/jiuwenswarm/gateway/message_handler/command_parser/slash_command.pyindex adc65f4b8a..a027fb9d19 100644--- a/jiuwenswarm/gateway/message_handler/command_parser/slash_command.py+++ b/jiuwenswarm/gateway/message_handler/command_parser/slash_command.py@@ -291,6 +291,13 @@ FIRST_BATCH_REGISTRY: tuple[SlashCommandEntry, ...] = (req_method="command.recap",notes="客户端命令,生成会话快速回顾(read-only);TUI → Gateway → AgentServer。",),+ SlashCommandEntry(+ id="agents",+ canonical_text="/agents",+ scope="client",+ req_method="agents.list",+ notes="TUI agent 配置管理菜单;TUI 通过 agents.* 方法与后端交互。",+ ),)diff --git a/jiuwenswarm/gateway/message_handler/message_handler.py b/jiuwenswarm/gateway/message_handler/message_handler.pyindex 8112f941b8..c5dd652e9f 100644--- a/jiuwenswarm/gateway/message_handler/message_handler.py+++ b/jiuwenswarm/gateway/message_handler/message_handler.py@@ -1307,7 +1307,7 @@ class MessageHandler(ABC):return sid@staticmethod- def _resolve_at_file_references(+ def resolve_at_file_references(content: str,cwd: str | None = None,max_file_size: int | None = _DEFAULT_INLINE_FILE_SIZE_LIMIT,@@ -1338,6 +1338,10 @@ class MessageHandler(ABC):if not raw:return m.group(0)+ # Skip @agent-xxx mentions (not file references)+ if raw.startswith("agent-") or raw.startswith("agent:"):+ return m.group(0)+# Resolve pathif raw.startswith("~/"):home = os.path.expanduser("~")@@ -1373,6 +1377,35 @@ class MessageHandler(ABC):return pattern.sub(_replacer, content)+ @staticmethod+ def extract_agent_mentions(content: str) -> list[str]:+ """Parse ``@agent-xxx`` and ``@"xxx (agent)"`` mentions from content.++ Returns list of agent type names (without "agent-" prefix), deduplicated.+ """+ if not content:+ return []++ results: list[str] = []++ # Match quoted format: @"<type> (agent)"+ for m in re.finditer(r'(^|\s)@"([\w:.@-]+)\s+\(agent\)"', content):+ results.append(m.group(2))++ # Match unquoted format: @agent-<type>+ for m in re.finditer(r'(^|\s)@(agent-[\w:.@-]+)', content):+ full = m.group(2)+ results.append(full[len("agent-"):])++ # Deduplicate preserving order+ seen: set[str] = set()+ unique: list[str] = []+ for name in results:+ if name not in seen:+ seen.add(name)+ unique.append(name)+ return unique+@staticmethoddef _is_absolute_reference_path(raw: str) -> bool:return raw.startswith("/") or (len(raw) >= 3 and raw[1] == ":" and raw[2] == "\\")@@ -1417,7 +1450,7 @@ class MessageHandler(ABC):return normalized@classmethod- def _strip_attached_mentions(+ def strip_attached_mentions(cls,content: str,attachments: list[dict[str, Any]],@@ -1442,6 +1475,9 @@ class MessageHandler(ABC):raw = match.group("quoted") or match.group("plain") or ""if not raw:return match.group(0)+ # Skip @agent-xxx mentions (not file references)+ if raw.startswith("agent-") or raw.startswith("agent:"):+ return match.group(0)resolved = cls._resolve_reference_path(raw, cwd)if resolved not in attached_paths:return match.group(0)@@ -1461,9 +1497,9 @@ class MessageHandler(ABC):return contentprefix = " ".join(f'@"{item["path"]}"' for item in normalized)- cleaned_content = cls._strip_attached_mentions(content, normalized, cwd)+ cleaned_content = cls.strip_attached_mentions(content, normalized, cwd)merged_content = f"{prefix} {cleaned_content}".strip()- return cls._resolve_at_file_references(merged_content, cwd=cwd)+ return cls.resolve_at_file_references(merged_content, cwd=cwd)@staticmethoddef message_to_e2a(msg: "Message") -> "E2AEnvelope":@@ -2389,14 +2425,36 @@ class MessageHandler(ABC):cwd=cwd,)elif content and "@" in content:- enriched = self._resolve_at_file_references(content, cwd=cwd)+ enriched = self.resolve_at_file_references(content, cwd=cwd)++ # ---- Resolve @agent-xxx mentions ----+ agent_mentions = self.extract_agent_mentions(content)+ if agent_mentions:+ hint_parts = []+ for agent_name in agent_mentions:+ hint_parts.append(+ f"用户表达了调用智能体 \"{agent_name}\" 的意图。"+ f"请按需调用该智能体,并向其传递所需的上下文。"+ )+ agent_hint = "\n".join(hint_parts)+ enriched = (+ enriched+ + "\n\n<system-reminder>\n"+ + agent_hint+ + "\n</system-reminder>"+ )+ logger.info(+ "[MessageHandler] Agent mentions detected: %s",+ agent_mentions,+ )+if enriched != content:msg.params = dict(msg.params)msg.params["query"] = enrichedif "content" in msg.params:msg.params["content"] = enrichedlogger.info(- "[MessageHandler] attachments resolved in chat.send: id=%s",+ "[MessageHandler] attachments/agent-mentions resolved in chat.send: id=%s",msg.id,)diff --git a/jiuwenswarm/resources/config.yaml b/jiuwenswarm/resources/config.yamlindex 5139f98b91..ee57841106 100644--- a/jiuwenswarm/resources/config.yaml+++ b/jiuwenswarm/resources/config.yaml@@ -176,6 +176,56 @@ acp_agents:env:OPENAI_API_KEY: ${OPENAI_API_KEY} # 仅由此 env 注入子进程(不读 workspace .env / 父进程)+# ============================================================+# Agent 配置(可被 team.agents / modes.team.<name>.agents 引用)+# ============================================================+# 每个 agent 定义一个可复用的 agent 配置模板,支持以下字段(均可选):+#+# model: # 不配则继承 models.default+# model_client_config:+# client_provider: OpenAI+# api_base: https://api.deepseek.com+# api_key: sk-xxx+# timeout: 1800+# verify_ssl: false+# custom_headers: {}+# model_request_config:+# model: deepseek-chat+# skills: # 不配则不自动填充+# - skill_a+# - skill_b+# workspace: # 默认 {"stable_base": true}+# stable_base: true+# max_iterations: 200 # 默认 200+# completion_timeout: 600.0 # 默认 600.0+#+# 示例:给不同 agent 配置不同模型和技能+# agent_coder:+# model:+# model_client_config:+# client_provider: OpenAI+# api_base: https://api.deepseek.com+# api_key: sk-xxx+# model_request_config:+# model: deepseek-chat+# skills:+# - code_review+# - unit_test+# max_iterations: 300+#+agents:+ agent_leader:+ workspace:+ stable_base: true+ max_iterations: 200+ completion_timeout: 600.0++ agent_teammate:+ workspace:+ stable_base: true+ max_iterations: 200+ completion_timeout: 600.0+telemetry:enabled: false # 总开关(环境变量 OTEL_ENABLED 优先)exporter: otlp # otlp / console / none@@ -670,16 +720,8 @@ team:persona: "天才项目管理专家,擅长任务分解和团队协调"agents:- leader:- workspace:- stable_base: true- max_iterations: 200- completion_timeout: 600.0- teammate:- workspace:- stable_base: true- max_iterations: 200- completion_timeout: 600.0+ leader: $agent_leader+ teammate: $agent_teammateworkspace:enabled: true@@ -765,11 +807,7 @@ modes:persona: "天才项目管理专家,擅长任务分解和团队协调"agents:- leader:- workspace:- stable_base: true- max_iterations: 200- completion_timeout: 600.0+ leader: $agent_leaderworkspace:enabled: truediff --git a/jiuwenswarm/server/agent_ws_server.py b/jiuwenswarm/server/agent_ws_server.pyindex 9400461534..17633a63d1 100644--- a/jiuwenswarm/server/agent_ws_server.py+++ b/jiuwenswarm/server/agent_ws_server.py@@ -62,10 +62,10 @@ from jiuwenswarm.common.config import (remove_mcp_server_in_config,resolve_preserve_file_sharing_mode_default,resolve_sandbox_policy_path,+ remove_subagent_from_config,set_mcp_server_enabled_in_config,- update_sandbox_endpoint,- update_sandbox_runtime,upsert_mcp_server_in_config,+ upsert_subagent_in_config,)from jiuwenswarm.server.sandbox.jiuwenbox_runner import JiuwenBoxRunnerfrom jiuwenswarm.common.security.ws_origin import (@@ -96,6 +96,39 @@ _HISTORY_RESTORABLE_ASSISTANT_EVENT_TYPES = frozenset(})+# System prompt for LLM-based agent generation+_AGENT_CREATION_SYSTEM_PROMPT = """\+You are an elite AI agent architect. When given an agent name and description, your job is to design a high-performance agent that EXECUTES tasks to completion — not just analyzes and reports.++The agent will have access to tools (Read, Write, Edit, Bash, etc.) to complete tasks. Design it as an autonomous expert capable of handling its designated tasks with minimal additional guidance. The system prompt you write is the agent's complete operational manual.++1. **whenToUse**: A precise description of when the main assistant should dispatch to this agent.+ - Start with "Use this agent when..."+ - Include concrete triggering conditions+ - Add 2-3 <example> blocks showing specific scenarios where the assistant uses the Agent tool to fully delegate the task+ - Each <example> should show: user says X → assistant dispatches to this agent with the Agent tool, passing the complete task+ - Write in the same language as the agent description (Chinese description → Chinese whenToUse)++2. **systemPrompt**: The complete system prompt governing the agent's behavior.+ - Define expert persona and role+ - Specify workflow and methodology — end-to-end, from analysis through execution+ - Establish clear behavioral boundaries and operational parameters+ - Provide specific methodologies and best practices for task execution+ - Define output format expectations when relevant+ - Include self-verification steps+ - Write in the same language as the agent description++Key principles:+- Be specific rather than generic — avoid vague instructions+- Include concrete examples when they would clarify behavior+- Balance comprehensiveness with clarity — every instruction should add value+- Ensure the agent has enough context to handle variations of the core task+- Build in quality assurance and self-correction mechanisms++Return ONLY a JSON object:+{"whenToUse": "...", "systemPrompt": "..."}+"""+def _extract_compact_summary_processor(summary: str) -> str:for line in str(summary or "").splitlines():@@ -914,6 +947,30 @@ class AgentWebSocketServer:if request.req_method == ReqMethod.SCHEDULE_DELETE:await self._handle_schedule_request(ws, request, send_lock, "delete")return+ if request.req_method == ReqMethod.AGENTS_LIST:+ await self._handle_agents_list(ws, request, send_lock)+ return+ if request.req_method == ReqMethod.AGENTS_GET:+ await self._handle_agents_get(ws, request, send_lock)+ return+ if request.req_method == ReqMethod.AGENTS_CREATE:+ await self._handle_agents_create(ws, request, send_lock)+ return+ if request.req_method == ReqMethod.AGENTS_UPDATE:+ await self._handle_agents_update(ws, request, send_lock)+ return+ if request.req_method == ReqMethod.AGENTS_DELETE:+ await self._handle_agents_delete(ws, request, send_lock)+ return+ if request.req_method == ReqMethod.AGENTS_ENABLE:+ await self._handle_agents_set_enabled(ws, request, send_lock, True)+ return+ if request.req_method == ReqMethod.AGENTS_DISABLE:+ await self._handle_agents_set_enabled(ws, request, send_lock, False)+ return+ if request.req_method == ReqMethod.AGENTS_TOOLS_LIST:+ await self._handle_agents_tools_list(ws, request, send_lock)+ returnif request.req_method == ReqMethod.CHAT_CANCEL:# 中断请求:根据 intent 决定是否取消流式任务sid = request.session_id or "default"@@ -3540,7 +3597,7 @@ class AgentWebSocketServer:settings_sources.append(f"env:JIUWENSWARM_CONFIG_DIR={config_dir}")settings_sources.append(config_path)- # Memory diagnostics — use the actual workspace dir (trusted_dir or cwd),+ # Memory diagnostics — use the actual workspace dir (trusted_dir or cwd),# same as ProjectMemoryRail, so we detect JIUWESWARM.md where /init creates it.params = request.params or {}workspace_dir = str(params.get("cwd", "") or os.getcwd())@@ -3651,6 +3708,371 @@ class AgentWebSocketServer:async with send_lock:await ws.send(json.dumps(wire, ensure_ascii=False))+ async def _handle_agents_list(self, ws: Any, request: AgentRequest, send_lock: asyncio.Lock) -> None:+ from dataclasses import asdict as dataclass_asdict+ from jiuwenswarm.server.runtime.agent_config_service import AgentConfigService++ try:+ workspace_dir = request.params.get("workspace_dir") if request.params else None+ service = AgentConfigService(workspace_dir)+ agents = service.list_agents()+ resp = AgentResponse(+ request_id=request.request_id,+ channel_id=request.channel_id,+ ok=True,+ payload={"agents": [dataclass_asdict(a) for a in agents]},+ )+ except Exception as e:+ logger.exception("[AgentWebSocketServer] agents.list failed: %s", e)+ resp = AgentResponse(+ request_id=request.request_id,+ channel_id=request.channel_id,+ ok=False,+ payload={"error": str(e)},+ )++ wire = encode_agent_response_for_wire(resp, response_id=request.request_id)+ async with send_lock:+ await ws.send(json.dumps(wire, ensure_ascii=False))++ async def _handle_agents_get(self, ws: Any, request: AgentRequest, send_lock: asyncio.Lock) -> None:+ from dataclasses import asdict as dataclass_asdict+ from jiuwenswarm.server.runtime.agent_config_service import AgentConfigService++ try:+ params = request.params or {}+ name = params.get("name", "")+ workspace_dir = params.get("workspace_dir")+ service = AgentConfigService(workspace_dir)+ agent = service.get_agent(name)+ if agent is None:+ resp = AgentResponse(+ request_id=request.request_id,+ channel_id=request.channel_id,+ ok=False,+ payload={"error": f"Agent 不存在: {name}"},+ )+ else:+ resp = AgentResponse(+ request_id=request.request_id,+ channel_id=request.channel_id,+ ok=True,+ payload={"agent": dataclass_asdict(agent)},+ )+ except Exception as e:+ logger.exception("[AgentWebSocketServer] agents.get failed: %s", e)+ resp = AgentResponse(+ request_id=request.request_id,+ channel_id=request.channel_id,+ ok=False,+ payload={"error": str(e)},+ )++ wire = encode_agent_response_for_wire(resp, response_id=request.request_id)+ async with send_lock:+ await ws.send(json.dumps(wire, ensure_ascii=False))++ async def _generate_agent_with_llm(+ self, name: str, description: str+ ) -> tuple[str, str] | None:+ """调用 LLM 生成 agent 的 whenToUse 和 systemPrompt。++ Returns:+ (when_to_use, system_prompt) 或 None(生成失败时回退到模板)+ """+ model = self._resolve_model(None)+ if model is None:+ logger.warning("[agents.create] no model available for LLM generation")+ return None++ from openjiuwen.core.foundation.llm.schema.message import UserMessage++ full_prompt = f"""{_AGENT_CREATION_SYSTEM_PROMPT}++---+请为以下 agent 生成配置:++名称: {name}+描述: {description}++返回 JSON 对象,包含 whenToUse 和 systemPrompt 两个字段。不要返回其他内容。"""++ try:+ result = await model.invoke(+ [UserMessage(content=full_prompt)],+ max_tokens=2000,+ temperature=0.3,+ )+ text = getattr(result, "content", None) or str(result)+ except Exception:+ logger.exception("[agents.create] LLM generation failed")+ return None++ # 解析 JSON 响应+ import re as _re++ import json as _json+ try:+ data = _json.loads(text.strip())+ except _json.JSONDecodeError:+ match = _re.search(r"\{[\s\S]*\}", text)+ if not match:+ logger.warning("[agents.create] no JSON found in LLM response: %s", text[:200])+ return None+ try:+ data = _json.loads(match.group(0))+ except _json.JSONDecodeError:+ logger.warning("[agents.create] JSON parse failed: %s", text[:200])+ return None++ when_to_use = (data.get("whenToUse") or "").strip()+ system_prompt = (data.get("systemPrompt") or "").strip()++ if not when_to_use or not system_prompt:+ logger.warning("[agents.create] incomplete LLM response: %s", data)+ return None++ return when_to_use, system_prompt++ async def _handle_agents_create(self, ws: Any, request: AgentRequest, send_lock: asyncio.Lock) -> None:+ from dataclasses import asdict as dataclass_asdict+ from jiuwenswarm.server.runtime.agent_config_service import AgentConfigService, CreateAgentParams++ try:+ params = dict(request.params or {})+ workspace_dir = params.pop("workspace_dir", None)+ generate = params.pop("generate", True)++ # LLM 生成 when_to_use 和 prompt(失败时回退到请求中的模板值)+ generated = False+ if generate:+ name = params.get("name", "")+ description = params.get("description", "")+ if name and description:+ llm_result = await self._generate_agent_with_llm(name, description)+ if llm_result:+ params["when_to_use"] = llm_result[0]+ params["prompt"] = llm_result[1]+ generated = True++ p = CreateAgentParams(**{k: v for k, v in params.items()+ if k in CreateAgentParams.__dataclass_fields__})+ service = AgentConfigService(workspace_dir)+ agent = service.create_agent(p)+ # 自动在 config.yaml 中启用新创建的 agent+ applied = True+ reload_error = ""+ try:+ upsert_subagent_in_config(agent.name, enabled=True)+ await self._agent_manager.reload_agents_config(get_config(), None)+ except Exception as reload_exc:+ applied = False+ reload_error = str(reload_exc)+ logger.warning("[AgentWebSocketServer] agents.create reload failed: %s", reload_exc)+ resp = AgentResponse(+ request_id=request.request_id,+ channel_id=request.channel_id,+ ok=True,+ payload={+ "agent": dataclass_asdict(agent),+ "generated": generated,+ "applied": applied,+ "reload_error": reload_error or None,+ },+ )+ except Exception as e:+ logger.exception("[AgentWebSocketServer] agents.create failed: %s", e)+ resp = AgentResponse(+ request_id=request.request_id,+ channel_id=request.channel_id,+ ok=False,+ payload={"error": str(e)},+ )++ wire = encode_agent_response_for_wire(resp, response_id=request.request_id)+ async with send_lock:+ await ws.send(json.dumps(wire, ensure_ascii=False))++ async def _handle_agents_update(self, ws: Any, request: AgentRequest, send_lock: asyncio.Lock) -> None:+ from dataclasses import asdict as dataclass_asdict+ from jiuwenswarm.server.runtime.agent_config_service import AgentConfigService, UpdateAgentParams++ try:+ params = dict(request.params or {})+ name = params.pop("name", "")+ workspace_dir = params.pop("workspace_dir", None)+ generate = params.pop("generate", False)++ # LLM 生成 when_to_use 和 prompt(默认不生成,需显式 --generate)+ generated = False+ if generate and name and params.get("description"):+ llm_result = await self._generate_agent_with_llm(name, params["description"])+ if llm_result:+ params["when_to_use"] = llm_result[0]+ params["prompt"] = llm_result[1]+ generated = True++ p = UpdateAgentParams(**{k: v for k, v in params.items()+ if k in UpdateAgentParams.__dataclass_fields__})+ service = AgentConfigService(workspace_dir)+ agent = service.update_agent(name, p)++ # 更新后热加载(对齐 create/delete 的模式)+ applied = True+ reload_error = ""+ try:+ await self._agent_manager.reload_agents_config(get_config(), None)+ except Exception as reload_exc:+ applied = False+ reload_error = str(reload_exc)+ logger.warning("[AgentWebSocketServer] agents.update reload failed: %s", reload_exc)++ resp = AgentResponse(+ request_id=request.request_id,+ channel_id=request.channel_id,+ ok=True,+ payload={+ "agent": dataclass_asdict(agent),+ "generated": generated,+ "applied": applied,+ "reload_error": reload_error or None,+ },+ )+ except Exception as e:+ logger.exception("[AgentWebSocketServer] agents.update failed: %s", e)+ resp = AgentResponse(+ request_id=request.request_id,+ channel_id=request.channel_id,+ ok=False,+ payload={"error": str(e)},+ )++ wire = encode_agent_response_for_wire(resp, response_id=request.request_id)+ async with send_lock:+ await ws.send(json.dumps(wire, ensure_ascii=False))++ async def _handle_agents_delete(self, ws: Any, request: AgentRequest, send_lock: asyncio.Lock) -> None:+ from jiuwenswarm.server.runtime.agent_config_service import AgentConfigService++ try:+ params = request.params or {}+ name = params.get("name", "")+ workspace_dir = params.get("workspace_dir")+ service = AgentConfigService(workspace_dir)+ ok = service.delete_agent(name)+ # 自动从 config.yaml 中移除被删除的 agent+ applied = True+ reload_error = ""+ try:+ remove_subagent_from_config(name)+ await self._agent_manager.reload_agents_config(get_config(), None)+ except Exception as reload_exc:+ applied = False+ reload_error = str(reload_exc)+ logger.warning("[AgentWebSocketServer] agents.delete reload failed: %s", reload_exc)+ resp = AgentResponse(+ request_id=request.request_id,+ channel_id=request.channel_id,+ ok=True,+ payload={"ok": ok, "applied": applied, "reload_error": reload_error or None},+ )+ except Exception as e:+ logger.exception("[AgentWebSocketServer] agents.delete failed: %s", e)+ resp = AgentResponse(+ request_id=request.request_id,+ channel_id=request.channel_id,+ ok=False,+ payload={"error": str(e)},+ )++ wire = encode_agent_response_for_wire(resp, response_id=request.request_id)+ async with send_lock:+ await ws.send(json.dumps(wire, ensure_ascii=False))++ async def _handle_agents_set_enabled(+ self,+ ws: Any,+ request: AgentRequest,+ send_lock: asyncio.Lock,+ enabled: bool+ ) -> None:+ from jiuwenswarm.server.runtime.agent_config_service import AgentConfigService++ action = "enable" if enabled else "disable"+ try:+ params = request.params or {}+ name = str(params.get("name", "")).strip()+ if not name:+ raise ValueError("agent name is required")+ workspace_dir = params.get("workspace_dir")+ service = AgentConfigService(workspace_dir)+ agent = service.get_agent(name)+ if agent is None:+ raise ValueError(f"Agent 不存在: {name}")+ if agent.source == "builtin":+ raise ValueError(f"不能启用/禁用内置 agent: {name}")++ upsert_subagent_in_config(name, enabled=enabled)+ applied = True+ reload_error = ""+ try:+ await self._agent_manager.reload_agents_config(get_config(), None)+ except Exception as reload_exc:+ applied = False+ reload_error = str(reload_exc)+ logger.warning("[AgentWebSocketServer] agents.%s reload failed: %s", action, reload_exc)++ resp = AgentResponse(+ request_id=request.request_id,+ channel_id=request.channel_id,+ ok=True,+ payload={+ "name": name,+ "enabled": enabled,+ "applied": applied,+ "reload_error": reload_error or None,+ },+ )+ except Exception as e:+ logger.exception("[AgentWebSocketServer] agents.%s failed: %s", action, e)+ resp = AgentResponse(+ request_id=request.request_id,+ channel_id=request.channel_id,+ ok=False,+ payload={"error": str(e)},+ )++ wire = encode_agent_response_for_wire(resp, response_id=request.request_id)+ async with send_lock:+ await ws.send(json.dumps(wire, ensure_ascii=False))++ async def _handle_agents_tools_list(self, ws: Any, request: AgentRequest, send_lock: asyncio.Lock) -> None:+ from jiuwenswarm.server.runtime.agent_config_service import AgentConfigService++ try:+ params = request.params or {}+ workspace_dir = params.get("workspace_dir")+ service = AgentConfigService(workspace_dir)+ result = service.list_available_tools()+ resp = AgentResponse(+ request_id=request.request_id,+ channel_id=request.channel_id,+ ok=True,+ payload=result,+ )+ except Exception as e:+ logger.exception("[AgentWebSocketServer] agents.tools_list failed: %s", e)+ resp = AgentResponse(+ request_id=request.request_id,+ channel_id=request.channel_id,+ ok=False,+ payload={"error": str(e)},+ )++ wire = encode_agent_response_for_wire(resp, response_id=request.request_id)+ async with send_lock:+ await ws.send(json.dumps(wire, ensure_ascii=False))+async def _handle_config_cache_clear(self, ws: Any, request: AgentRequest, send_lock: asyncio.Lock) -> None:try:from jiuwenswarm.agents.harness.common.memory.config import clear_config_cachediff --git a/jiuwenswarm/server/runtime/agent_adapter/code_agent_rail.py b/jiuwenswarm/server/runtime/agent_adapter/code_agent_rail.pynew file mode 100644index 0000000000..ac8b8a4ae6--- /dev/null+++ b/jiuwenswarm/server/runtime/agent_adapter/code_agent_rail.py@@ -0,0 +1,428 @@+# coding: utf-8+"""CodeAgentRail — 管理 /agents 创建的自定义子智能体。++与 SubagentRail 共存:SubagentRail 管理内置 agent(explore/plan/code/browser),+CodeAgentRail 只管理自定义 agent。+"""++from __future__ import annotations++import asyncio+import uuid+from typing import TYPE_CHECKING++from openjiuwen.core.common.exception.codes import StatusCode+from openjiuwen.core.common.exception.errors import build_error+from openjiuwen.core.common.logging import logger+from openjiuwen.core.foundation.tool import Tool, ToolCard+from openjiuwen.core.runner import Runner+from openjiuwen.harness.rails.base import DeepAgentRail+from openjiuwen.harness.tools.base_tool import ToolOutput+from openjiuwen.harness.workspace.workspace import Workspace++if TYPE_CHECKING:+ from openjiuwen.core.session.agent import Session+ from openjiuwen.harness.deep_agent import DeepAgent++# ── Tool names that must never be delegated to a sub-agent ──────────────+DISALLOWED_FOR_SUBAGENTS: set[str] = {+ "Agent", "task", "enter_plan_mode", "exit_plan_mode",+ "ask_user_question", "task_stop", "switch_mode",+}++# ── User-facing tool groups for agent-definition UI ────────────────────+TOOL_GROUPS: dict[str, list[str]] = {+ "核心": ["Read", "Write", "Edit", "Bash", "LS"],+ "搜索": ["Grep", "Glob", "WebSearch", "WebFetch"],+ "代码智能": ["LSP", "TodoWrite", "TodoList"],+ "高级": ["MemorySearch", "MemoryGet", "WriteMemory", "EditMemory",+ "CronCreate", "CronList", "CronDelete", "SkillTool"],+ "可视化": ["VisionQA", "ImageOCR", "AudioTranscribe"],+}++# ── Helper: display-name → internal-name mapping ─────────────────────+++# Display name → internal SDK name mapping (mirrors openjiuwen.harness.cli.ui.tool_display).+# Defined locally to avoid triggering prompt_toolkit import via cli.ui.__init__ → repl.py.+_DISPLAY_TO_INTERNAL: dict[str, str] = {+ "Read": "read_file",+ "Write": "write_file",+ "Edit": "edit_file",+ "Bash": "bash",+ "Grep": "grep",+ "Glob": "glob",+ "LS": "ls",+ "ListDir": "ls",+ "TodoWrite": "todo_create",+ "TodoList": "todo_list",+ "WebSearch": "web_search",+ "WebFetch": "web_fetch",+ "ImageOCR": "image_ocr",+ "VisionQA": "visual_question_answering",+ "AudioTranscribe": "audio_transcription",+ "AudioQA": "audio_question_answering",+ "AudioMetadata": "audio_metadata",+}+++def _build_display_to_internal_mapping() -> dict[str, str]:+ """Build reverse mapping: display name → internal name.++ Uses a local mapping instead of importing from openjiuwen.harness.cli.ui.tool_display+ to avoid triggering prompt_toolkit import via cli.ui.__init__ → repl.py.+ """+ return _DISPLAY_TO_INTERNAL+++def _filter_tool_cards(+ all_tool_cards: list[ToolCard],+ allowed_tools: list[str],+ disallowed_tools: list[str] | None = None,+) -> list[ToolCard]:+ """Filter ToolCards based on agent definition's tools/disallowed_tools fields.++ Args:+ all_tool_cards: Parent agent's ToolCards (already excluding DISALLOWED_FOR_SUBAGENTS).+ allowed_tools: Agent definition's tools field. ``["*"]`` means all; specific names filter.+ disallowed_tools: Agent definition's disallowed_tools field. ``None`` or ``[]`` means no extra removal.++ Returns:+ Filtered list of ToolCards to pass to sub-agent.+ """+ if allowed_tools == ["*"]:+ result = list(all_tool_cards)+ else:+ display_to_internal = _build_display_to_internal_mapping()+ target_names: set[str] = set()+ for name in allowed_tools:+ # accept both display names ("Read") and internal names ("read_file")+ target_names.add(display_to_internal.get(name, name))+ target_names.add(name)+ result = [tc for tc in all_tool_cards if tc.name in target_names]++ if disallowed_tools:+ display_to_internal = _build_display_to_internal_mapping()+ disallowed_internal: set[str] = set()+ for name in disallowed_tools:+ disallowed_internal.add(display_to_internal.get(name, name))+ disallowed_internal.add(name)+ result = [tc for tc in result if tc.name not in disallowed_internal]++ return result+++def _build_agent_tool_card(custom_agents: list, agent_id: str | None = None) -> ToolCard:+ """动态构建 Agent 工具卡片,只列出自定义 agent。"""+ lines = ["Launch a new agent to handle complex, multi-step tasks autonomously."]+ lines.append("")+ lines.append("Available custom agents (created via /agents):")+ for agent_def in custom_agents:+ desc = agent_def.when_to_use or agent_def.description+ tools_desc = ", ".join(agent_def.tools) if agent_def.tools else "*"+ lines.append(f"- {agent_def.name}: {desc} (Tools: {tools_desc})")+ lines.append("")+ lines.append("Usage notes:")+ lines.append("- Each agent starts fresh — provide complete context in the prompt")+ lines.append("- Clearly tell the agent whether you expect it to write code or just to do research")+ lines.append("- Never delegate understanding — write prompts that prove you understood the task")+ lines.append("- Delegate the COMPLETE task, not just the analysis portion")+ lines.append("- Use background=True for independent parallel work")+ lines.append("- You can also invoke agents via @agent-<name> syntax in user messages")++ tool_id = f"agent_tool_{agent_id}" if agent_id else f"agent_tool_{uuid.uuid4().hex}"++ return ToolCard(+ id=tool_id,+ name="Agent",+ description="\n".join(lines),+ input_params={+ "type": "object",+ "properties": {+ "description": {+ "type": "string",+ "description": "A short (3-5 word) description of the task",+ },+ "prompt": {+ "type": "string",+ "description": "The task for the agent to perform",+ },+ "subagent_type": {+ "type": "string",+ "description": "The name of the custom agent to use",+ },+ "model": {+ "type": "string",+ "enum": ["sonnet", "opus", "haiku"],+ "description": "Optional model override",+ },+ "background": {+ "type": "boolean",+ "description": "Run in background. You will be notified when complete.",+ "default": False,+ },+ },+ "required": ["description", "prompt", "subagent_type"],+ },+ )+++class AgentTool(Tool):+ """自定义 agent 调度工具。++ 直接使用 create_deep_agent() 创建子 agent,不依赖 deep_config.subagents。+ """++ def __init__(self, card: ToolCard, parent_agent: DeepAgent, custom_agents: list):+ super().__init__(card)+ self._parent_agent = parent_agent+ self._custom_agents: dict[str, object] = {a.name: a for a in custom_agents}++ def _build_sub_session_id(self, parent_session_id: str, subagent_type: str) -> str:+ return f"{parent_session_id}_custom_{subagent_type}_{uuid.uuid4().hex[:8]}"++ def _create_sub_agent(self, agent_def, sub_session_id: str) -> DeepAgent:+ """从 AgentDefinition 直接创建子 DeepAgent,绕过 deep_config.subagents。"""+ from openjiuwen.harness.factory import create_deep_agent+ from openjiuwen.harness.schema.config import SubAgentConfig+ from openjiuwen.core.single_agent import AgentCard as OJAgentCard+ from jiuwenswarm.server.runtime.agent_adapter.interface_deep import _agent_def_to_subagent_config++ parent_config = getattr(self._parent_agent, "deep_config", None)++ # 将 AgentDefinition 转为 SubAgentConfig+ spec = _agent_def_to_subagent_config(+ agent_def,+ parent_config.model,+ parent_config.workspace.root_path if parent_config.workspace else "./",+ getattr(self._parent_agent, "_model_cache", None),+ )++ # 子 agent 工具集:继承父 agent 的 ToolCard,过滤 disallowed 工具+ # AbilityManager.list() 返回 ToolCard/WorkflowCard/AgentCard/McpServerConfig,+ # 不是 Tool 实例,所以直接 isinstance 检查,不要用 getattr(.card)。+ all_tool_cards: list[ToolCard] = []+ if hasattr(self._parent_agent, "ability_manager"):+ for ability in self._parent_agent.ability_manager.list():+ if isinstance(ability, ToolCard) and ability.name not in DISALLOWED_FOR_SUBAGENTS:+ all_tool_cards.append(ability)++ # 根据 agent 定义的 tools 字段进一步过滤+ # 注意:_agent_def_to_subagent_config() 已将 disallowed_tools 合并进 spec.tools,+ # 所以这里的 disallowed_tools 传 None。+ parent_tool_cards = _filter_tool_cards(+ all_tool_cards,+ allowed_tools=list(spec.tools) if spec.tools else ["*"],+ disallowed_tools=None,+ )++ # 构建 workspace(对齐 DeepAgent.create_subagent 的逻辑)+ if parent_config.workspace and isinstance(parent_config.workspace, Workspace):+ workspace = Workspace(+ root_path=str(parent_config.workspace.root_path),+ language=parent_config.language,+ )+ else:+ workspace_path = (+ f"{parent_config.workspace}/{sub_session_id}"+ if parent_config.workspace+ else f"./{sub_session_id}"+ )+ workspace = Workspace(root_path=workspace_path, language=parent_config.language)++ # 构建 create_kwargs(对齐 DeepAgent.create_subagent 的字段映射)+ create_kwargs = {+ "model": spec.model or parent_config.model,+ "card": spec.agent_card,+ "system_prompt": spec.system_prompt,+ "tools": parent_tool_cards,+ "mcps": spec.mcps,+ "enable_task_loop": spec.enable_task_loop,+ "max_iterations": spec.max_iterations if spec.max_iterations is not None else parent_config.max_iterations,+ "workspace": spec.workspace if spec.workspace is not None else workspace,+ "skills": spec.skills,+ "backend": spec.backend if spec.backend is not None else parent_config.backend,+ "sys_operation": None, # 子 agent 不继承 sys_operation+ "language": spec.language if spec.language is not None else parent_config.language,+ "prompt_mode": spec.prompt_mode if spec.prompt_mode is not None else parent_config.prompt_mode,+ "subagents": None,+ "enable_async_subagent": False,+ "add_general_purpose_agent": False,+ "restrict_to_work_dir": spec.restrict_to_work_dir,+ }++ factory_kwargs = dict(spec.factory_kwargs or {})++ sub_agent = create_deep_agent(**create_kwargs, **factory_kwargs)+ logger.info("[AgentTool] Created sub-agent for '%s' via create_deep_agent()", agent_def.name)+ return sub_agent++ async def invoke(self, inputs, **kwargs):+ from openjiuwen.core.session.agent import Session++ parent_session = kwargs.get("session")+ if not isinstance(parent_session, Session):+ raise build_error(+ StatusCode.TOOL_TASK_TOOL_INVOKED,+ reason="Agent tool requires a valid session in kwargs",+ )++ if isinstance(inputs, dict):+ subagent_type = inputs.get("subagent_type")+ prompt = inputs.get("prompt")+ background = inputs.get("background", False)+ else:+ subagent_type = getattr(inputs, "subagent_type", None)+ prompt = getattr(inputs, "prompt", None)+ background = getattr(inputs, "background", False)++ if not subagent_type or not prompt:+ raise build_error(+ StatusCode.TOOL_TASK_TOOL_INVOKED,+ reason="Both 'subagent_type' and 'prompt' are required",+ )++ agent_def = self._custom_agents.get(subagent_type)+ if agent_def is None:+ available = ", ".join(sorted(self._custom_agents.keys()))+ raise build_error(+ StatusCode.TOOL_TASK_TOOL_INVOKED,+ reason=f"Agent type '{subagent_type}' not found. Available custom agents: {available}",+ )++ parent_session_id = parent_session.get_session_id()+ sub_session_id = self._build_sub_session_id(parent_session_id, subagent_type)++ try:+ subagent = self._create_sub_agent(agent_def, sub_session_id)+ except Exception as exc:+ logger.error(f"[AgentTool] Subagent creation failed: type={subagent_type}, error={exc}")+ raise build_error(+ StatusCode.TOOL_TASK_TOOL_INVOKED,+ reason=f"Custom agent '{subagent_type}' creation failed: {exc}",+ ) from exc++ if background:+ asyncio.create_task(self._run_async(subagent, prompt, sub_session_id, subagent_type, parent_session))+ return ToolOutput(+ success=True,+ data={+ "status": "async_launched",+ "agent_id": subagent_type,+ "prompt": prompt,+ },+ )+ else:+ try:+ result = await subagent.invoke(+ {"query": prompt, "conversation_id": sub_session_id},+ session=parent_session,+ )+ output = result.get("output", "")+ return ToolOutput(+ success=True,+ data={"output": output, "agent_id": subagent_type},+ )+ except Exception as exc:+ logger.error(f"[AgentTool] Subagent execution failed: type={subagent_type}, error={exc}")+ raise build_error(+ StatusCode.TOOL_TASK_TOOL_INVOKED,+ reason=f"Custom agent '{subagent_type}' execution failed: {exc}",+ ) from exc++ async def _run_async(+ self, subagent: DeepAgent, prompt: str, sub_session_id: str,+ subagent_type: str, parent_session: Session,+ ) -> None:+ try:+ await subagent.invoke(+ {"query": prompt, "conversation_id": sub_session_id},+ session=parent_session,+ )+ except Exception as exc:+ logger.error(+ "[AgentTool] Async subagent '%s' failed: %s", subagent_type, exc+ )++ async def stream(self, inputs, **kwargs):+ pass+++class CodeAgentRail(DeepAgentRail):+ """Code 模式下的自定义 agent rail。++ 与 SubagentRail 共存,只管理 /agents 创建的自定义 agent。+ 不触碰内置 agent(explore/plan/code/browser)。+ """++ priority = 90 # 略低于 SubagentRail(95),避免冲突++ def __init__(self, workspace_dir: str):+ super().__init__()+ self._workspace_dir = workspace_dir+ self._agent: DeepAgent | None = None+ self._agent_tool: AgentTool | None = None++ def init(self, agent: DeepAgent) -> None:+ self._agent = agent+ self._register_agent_tool()++ def uninit(self, agent: DeepAgent) -> None:+ self._unregister_agent_tool(agent)+ self._agent = None++ def _register_agent_tool(self) -> None:+ custom_agents = self._load_custom_agents()+ if not custom_agents:+ logger.info("[CodeAgentRail] No custom agents found, Agent tool not registered")+ return++ agent_id = getattr(getattr(self._agent, "card", None), "id", None)+ card = _build_agent_tool_card(custom_agents, agent_id)+ self._agent_tool = AgentTool(+ card=card,+ parent_agent=self._agent,+ custom_agents=custom_agents,+ )+ Runner.resource_mgr.add_tool([self._agent_tool])+ self._agent.ability_manager.add(self._agent_tool.card)+ logger.info(+ "[CodeAgentRail] Agent tool registered with %d custom agent(s): %s",+ len(custom_agents),+ ", ".join(a.name for a in custom_agents),+ )++ def _unregister_agent_tool(self, agent: DeepAgent) -> None:+ if self._agent_tool is None:+ return+ if hasattr(agent, "ability_manager"):+ name = getattr(self._agent_tool.card, "name", None)+ if name:+ try:+ agent.ability_manager.remove(name)+ except Exception as e:+ logger.debug("Failed to remove agent tool '%s' from ability_manager: %s", name, e)+ tool_id = self._agent_tool.card.id+ if tool_id:+ try:+ Runner.resource_mgr.remove_tool(tool_id)+ except Exception as e:+ logger.debug("Failed to remove tool '%s' from resource_mgr: %s", tool_id, e)+ self._agent_tool = None++ def _load_custom_agents(self) -> list:+ """从 AgentConfigService 加载启用的自定义 agent。"""+ from jiuwenswarm.server.runtime.agent_config_service import AgentConfigService++ try:+ service = AgentConfigService(self._workspace_dir)+ return [+ a for a in service.list_agents()+ if a.source != "builtin" and a.enabled == True+ ]+ except Exception:+ logger.warning("[CodeAgentRail] Failed to load custom agents", exc_info=True)+ return []+++__all__ = ["CodeAgentRail", "AgentTool", "DISALLOWED_FOR_SUBAGENTS", "TOOL_GROUPS", "_filter_tool_cards"]\ No newline at end of filediff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_code.py b/jiuwenswarm/server/runtime/agent_adapter/interface_code.pyindex 499df85759..a1ea7c4161 100644--- a/jiuwenswarm/server/runtime/agent_adapter/interface_code.py+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_code.py@@ -46,6 +46,7 @@ from openjiuwen.harness.workspace.workspace import Workspacefrom jiuwenswarm.server.runtime.agent_adapter.interface_deep import (JiuWenClawDeepAdapter,_CRON_TOOL_CHANNEL_ID,+ _agent_def_to_subagent_config,parse_int,)from jiuwenswarm.agents.harness.common.rails.interrupt.interrupt_helpers import build_permission_rail@@ -61,6 +62,7 @@ from jiuwenswarm.agents.harness.common.tools import SkillToolkitfrom jiuwenswarm.agents.harness.common.tools.acp_chat import acp_chatfrom jiuwenswarm.common.config import get_configfrom jiuwenswarm.common.utils import get_agent_workspace_dir+from jiuwenswarm.server.runtime.agent_adapter.code_agent_rail import CodeAgentRaillogger = logging.getLogger(__name__)@@ -81,6 +83,7 @@ _RAIL_BUILD_NAMES: dict[str, str] = {"ProjectMemoryRail": "_build_project_memory_rail","CodingMemoryRail": "_build_coding_memory_rail","WorktreeRail": "_build_worktree_rail_via_config",+ "CodeAgentRail": "_build_code_agent_rail",}_TOOL_BUILD_NAMES: dict[str, str] = {@@ -373,6 +376,7 @@ class JiuwenClawCodeAdapter(JiuWenClawDeepAdapter):{"tool_names": ["switch_mode"]},),_RailBuildInfo("_context_processor_rail", self._build_context_processor_rail),+ _RailBuildInfo("_code_agent_rail", self._build_code_agent_rail),]# 动态 Rails — 从 config.yaml::modes.code.rails 读取@@ -737,6 +741,11 @@ class JiuwenClawCodeAdapter(JiuWenClawDeepAdapter):browser_spec.factory_kwargs = {"auto_create_workspace": False}subagents.append(browser_spec)+ # ── 自定义 agent 不加入 deep_config.subagents ──+ # Code 模式下,自定义 agent 由 CodeAgentRail 的 Agent 工具管理,+ # 不走 SubagentRail 的 task_tool 路径。+ # (agent.plan / agent.fast 模式仍由 interface_deep.py 的 _load_custom_subagents 管理)+return subagents or None, False# ─── Rail 生命周期(mode切换) ───────────────────@@ -797,6 +806,30 @@ class JiuwenClawCodeAdapter(JiuWenClawDeepAdapter):mode,)+ def _build_code_agent_rail(self) -> CodeAgentRail | None:+ """构建 CodeAgentRail,管理 /agents 创建的自定义 agent。"""+ try:+ rail = CodeAgentRail(workspace_dir=self._workspace_dir)+ logger.info("[JiuwenClawCodeAdapter] CodeAgentRail created")+ return rail+ except Exception as exc:+ logger.warning("[JiuwenClawCodeAdapter] CodeAgentRail create failed: %s", exc)+ return None++ def _get_current_agent_rails(+ self, config: dict[str, Any], config_base: dict[str, Any] | None = None+ ) -> list[Any]:+ """扩展父类方法,将 CodeAgentRail 纳入热重载范围。++ 父类 _get_current_agent_rails 只返回 skill/context/memory 等 rail,+ CodeAgentRail 不在其中。覆盖此方法确保 config reload 时+ CodeAgentRail 被正确重新初始化。+ """+ rails_list = super()._get_current_agent_rails(config, config_base)+ if self._code_agent_rail is not None:+ rails_list.append(self._code_agent_rail)+ return rails_list+# ─── Runtime config ──────────────────────────async def _update_runtime_config(self, runtime_config: "JiuWenClawDeepAdapter._RuntimeConfig") -> None:diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.pyindex db2cc03383..9ef0ed4efa 100644--- a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py@@ -944,6 +944,20 @@ class JiuWenClawDeepAdapter:"skipping browser subagent registration")+ # ── 加载自定义 agent(.jiuwenclaw/agents/*.md)──+ try:+ subagents.extend(+ _load_custom_subagents(+ self._workspace_dir, subagents_cfg, model, workspace,+ __name__, model_cache=self._model_cache,+ )+ )+ except Exception:+ logger.warning(+ "[JiuWenClawDeepAdapter] failed to load custom agents",+ exc_info=True,+ )+return subagents or None, should_add_general_purpose@staticmethod@@ -5921,3 +5935,85 @@ class JiuWenClawDeepAdapter:self._dreaming_started = Falseexcept Exception as exc:logger.warning("[JiuWenClawDeepAdapter] stop_dreaming failed: %s", exc)+++def _agent_def_to_subagent_config(+ agent_def: AgentDefinition,+ model: Any,+ workspace: str,+ model_cache: dict[str, Any] | None = None,+) -> SubAgentConfig:+ """将 AgentDefinition 转换为 SubAgentConfig,用于 SubagentRail 注册。++ Args:+ agent_def: 自定义 agent 定义(来自 .jiuwenswarm/agents/*.md)+ model: 父 agent 的 Model 实例(作为默认模型)+ workspace: 工作空间路径+ model_cache: 模型缓存字典(用于按名称查找指定模型)+ """+ from openjiuwen.harness.schema.config import SubAgentConfig++ # Resolve model: if agent_def specifies a model name, look it up in cache+ resolved_model = model+ if agent_def.model and isinstance(model_cache, dict):+ resolved_model = model_cache.get(agent_def.model, model)++ # Build tool list: merge allowed tools and disallowed_tools+ tools: list[str] = list(agent_def.tools) if agent_def.tools else ["*"]+ if agent_def.disallowed_tools and tools != ["*"]:+ tools = [t for t in tools if t not in agent_def.disallowed_tools]++ card = AgentCard(+ name=agent_def.name,+ description=agent_def.description,+ )++ return SubAgentConfig(+ agent_card=card,+ system_prompt=agent_def.prompt,+ tools=tools,+ model=resolved_model,+ skills=agent_def.skills,+ max_iterations=agent_def.max_iterations,+ enable_task_loop=True,+ )+++def _load_custom_subagents(+ workspace_dir: str,+ subagents_cfg: dict | None,+ model: Any,+ workspace: str,+ logger_name: str,+ **kwargs: Any,+) -> list[Any]:+ """从 AgentConfigService 加载自定义 agent 并转换为 SubAgentConfig 列表。++ 通用逻辑,同时被 JiuWenClawDeepAdapter 和 JiuWenClawCodeAdapter 使用。++ Args:+ workspace_dir: 工作空间目录路径+ subagents_cfg: 子 agent 配置字典+ model: 模型配置+ workspace: 工作空间路径+ logger_name: 日志记录器名称+ **kwargs: 额外参数,支持 model_cache 等+ """+ from jiuwenswarm.server.runtime.agent_config_service import AgentConfigService++ _logger = logging.getLogger(logger_name)+ agent_service = AgentConfigService(workspace_dir)+ model_cache: dict | None = kwargs.get("model_cache")+ result: list[Any] = []+ for agent_def in agent_service.list_agents():+ if agent_def.source == "builtin":+ continue+ subagent_cfg = subagents_cfg.get(agent_def.name) if isinstance(subagents_cfg, dict) else None+ # 只有显式 enabled: true 才加载+ if not (isinstance(subagent_cfg, dict) and bool(subagent_cfg.get("enabled", False))):+ continue+ custom_spec = _agent_def_to_subagent_config(agent_def, model, workspace, model_cache)+ custom_spec.factory_kwargs = {"auto_create_workspace": False}+ result.append(custom_spec)+ _logger.info("loaded custom agent '%s' from %s", agent_def.name, agent_def.source)+ return resultdiff --git a/jiuwenswarm/server/runtime/agent_config_service.py b/jiuwenswarm/server/runtime/agent_config_service.pynew file mode 100644index 0000000000..01d7d1e8dc--- /dev/null+++ b/jiuwenswarm/server/runtime/agent_config_service.py@@ -0,0 +1,521 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""Agent 配置管理服务 — 管理内置和自定义 agent 定义的 CRUD 操作.++Agent 定义来源(优先级从高到低):+- project: <workspace>/.jiuwenswarm/agents/*.md+- user: ~/.jiuwenswarm/agents/*.md+- local: <workspace>/.jiuwenswarm/agents-local/*.md+- builtin: 代码内置++文件格式为 YAML frontmatter + Markdown body。+"""++from __future__ import annotations++import logging+from dataclasses import dataclass, field+from pathlib import Path+from typing import Literal++import yaml++from jiuwenswarm.common.utils import get_user_workspace_dir++logger = logging.getLogger(__name__)+++_TOOL_DESCRIPTIONS: dict[str, str] = {+ "Read": "读取文件内容",+ "Write": "写入文件",+ "Edit": "编辑文件(精准替换)",+ "Bash": "执行 shell 命令",+ "LS": "列出目录内容",+ "Grep": "搜索文件内容",+ "Glob": "按模式搜索文件名",+ "WebSearch": "网络搜索",+ "WebFetch": "获取网页内容",+ "LSP": "代码智能(定义跳转、引用查找)",+ "TodoWrite": "创建/更新任务列表",+ "TodoList": "查看任务列表",+ "MemorySearch": "搜索记忆",+ "MemoryGet": "获取记忆条目",+ "WriteMemory": "写入记忆",+ "EditMemory": "编辑记忆",+ "CronCreate": "创建定时任务",+ "CronList": "列出定时任务",+ "CronDelete": "删除定时任务",+ "SkillTool": "调用 Skill",+ "VisionQA": "视觉问答",+ "ImageOCR": "图片文字识别",+ "AudioTranscribe": "音频转录",+}+++# ---------------------------------------------------------------------------+# 数据模型+# ---------------------------------------------------------------------------+++AgentSource = Literal["builtin", "user", "project", "local"]+++@dataclass+class AgentDefinition:+ """Agent 定义数据模型。"""++ name: str+ description: str+ prompt: str+ source: AgentSource+ file_path: str | None = None+ model: str | None = None+ tools: list[str] = field(default_factory=lambda: ["*"])+ disallowed_tools: list[str] = field(default_factory=list)+ color: str | None = None+ permission_mode: str | None = None+ memory_scope: str | None = None+ shadowed_by: AgentSource | None = None+ enabled: bool | None = None # None = 不在 config.yaml 中(内置 agent 默认 None)+ when_to_use: str | None = None # 告诉 LLM 何时调度此 agent+ max_iterations: int | None = None # 子 agent 最大迭代次数(openjiuwen SubAgentConfig.max_iterations)+ skills: list[str] | None = None # 子 agent 启动时预加载的 skill 名称+++@dataclass+class CreateAgentParams:+ """创建 agent 的请求参数。"""++ name: str+ description: str+ prompt: str+ location: AgentSource+ model: str | None = None+ tools: list[str] | None = None+ color: str | None = None+ permission_mode: str | None = None+ memory_scope: str | None = None+ disallowed_tools: list[str] | None = None+ when_to_use: str | None = None+ max_iterations: int | None = None+ skills: list[str] | None = None+++@dataclass+class UpdateAgentParams:+ """更新 agent 的请求参数(所有字段可选,None 表示不修改)。"""++ description: str | None = None+ when_to_use: str | None = None+ prompt: str | None = None+ model: str | None = None+ tools: list[str] | None = None+ color: str | None = None+ permission_mode: str | None = None+ memory_scope: str | None = None+ disallowed_tools: list[str] | None = None+ max_iterations: int | None = None+ skills: list[str] | None = None+++# ---------------------------------------------------------------------------+# 内置 Agent 定义+# ---------------------------------------------------------------------------++BUILTIN_AGENTS: list[AgentDefinition] = [+ AgentDefinition(+ name="general-purpose",+ description="通用多步任务 agent,适用于没有专用 agent 的各类任务",+ prompt=(+ "你是一个通用任务 agent。使用可用工具完成用户委派的任务。\n\n"+ "工作原则:\n"+ "1. 将复杂任务分解为可管理的步骤\n"+ "2. 在每个步骤完成后汇报进展\n"+ "3. 遇到阻塞时主动说明需要什么信息"+ ),+ source="builtin",+ tools=["*"],+ ),+ AgentDefinition(+ name="Explore",+ description="快速只读代码库探索 agent,用于定位代码、搜索符号、查找文件",+ prompt=(+ "你是代码库探索专家。你的职责是快速定位代码、搜索符号和查找文件。\n\n"+ "工作原则:\n"+ "1. 只进行只读操作(搜索、读取、列出文件)\n"+ "2. 通过多种搜索策略(文件名模式、grep 符号、目录遍历)确保覆盖全面\n"+ "3. 返回精确的文件路径和行号\n"+ "4. 当结果过多时,缩小搜索范围而不是截断输出"+ ),+ source="builtin",+ tools=["Read", "Bash", "Grep", "Glob"],+ ),+ AgentDefinition(+ name="Plan",+ description="软件架构设计 agent,用于规划实现方案",+ prompt=(+ "你是软件架构师。分析代码库模式和约定,提供完整的实现蓝图。\n\n"+ "工作原则:\n"+ "1. 先理解现有代码库的架构模式和约定\n"+ "2. 设计变更时考虑副作用和依赖关系\n"+ "3. 输出包含:需要创建/修改的文件、组件设计、数据流和构建顺序\n"+ "4. 不写实现代码,只提供设计蓝图"+ ),+ source="builtin",+ tools=["Read", "Bash", "Grep", "Glob"],+ ),+]++_SOURCE_SORT_ORDER: dict[str, int] = {"builtin": 0, "local": 1, "user": 2, "project": 3}+++def _source_sort_key(agent: AgentDefinition) -> int:+ return _SOURCE_SORT_ORDER.get(agent.source, 99)+++# ---------------------------------------------------------------------------+# AgentConfigService+# ---------------------------------------------------------------------------+++class AgentConfigService:+ """管理 agent 定义的 CRUD 操作。++ 支持四个来源的 agent 定义:内置、用户级、项目级、本地级。+ 同名 agent 按 project > user > local > builtin 优先级覆盖。+ """++ def __init__(self, workspace_dir: Path | str | None = None):+ self._workspace_dir = Path(workspace_dir) if workspace_dir else Path.cwd()++ # ---- 路径 ----++ @staticmethod+ def _get_user_agents_dir() -> Path:+ return get_user_workspace_dir() / "agents"++ def _get_project_agents_dir(self) -> Path:+ return self._workspace_dir / ".jiuwenswarm" / "agents"++ def _get_local_agents_dir(self) -> Path:+ return self._workspace_dir / ".jiuwenswarm" / "agents-local"++ # ---- CRUD ----++ def list_agents(self) -> list[AgentDefinition]:+ """列出所有 agent(内置 + 自定义),按优先级合并。++ 加载顺序决定优先级:后加载的覆盖先加载的,因此+ project > user > local > builtin。被覆盖的同名 agent 标记 shadowed_by。+ 同时从 config.yaml 的 react.subagents 读取 enabled 状态。+ """+ sources: list[tuple[list[AgentDefinition], AgentSource]] = [+ (list(BUILTIN_AGENTS), "builtin"),+ (self._load_from_dir(self._get_local_agents_dir(), "local"), "local"),+ (self._load_from_dir(self._get_user_agents_dir(), "user"), "user"),+ (self._load_from_dir(self._get_project_agents_dir(), "project"), "project"),+ ]++ # 读取 config.yaml 中的 react.subagents enabled 状态+ subagent_states: dict[str, bool] = {}+ try:+ from jiuwenswarm.common.config import get_config++ config = get_config()+ react = config.get("react") if isinstance(config, dict) else None+ subagents_cfg = react.get("subagents") if isinstance(react, dict) else None+ if isinstance(subagents_cfg, dict):+ for name, cfg in subagents_cfg.items():+ if isinstance(cfg, dict) and "enabled" in cfg:+ subagent_states[name] = bool(cfg["enabled"])+ except Exception as e:+ logger.debug("Failed to load subagent states from config: %s", e)++ # 按名字分组,保持所有来源的 agent(包括被 shadow 的)+ grouped: dict[str, list[AgentDefinition]] = {}+ for agents, _ in sources:+ for agent in agents:+ grouped.setdefault(agent.name, []).append(agent)++ # 每组的最后一个为 active(最高优先级),之前的标记 shadowed_by+ result: list[AgentDefinition] = []+ for _name, group in grouped.items():+ active = group[-1]+ active.shadowed_by = None+ for agent in group[:-1]:+ agent.shadowed_by = active.source+ result.append(agent)+ result.append(active)++ # 注入 enabled 状态+ for agent in result:+ if agent.name in subagent_states:+ agent.enabled = subagent_states[agent.name]++ return sorted(result, key=_source_sort_key)++ def get_agent(self, name: str) -> AgentDefinition | None:+ """获取单个 agent 完整定义(含 system prompt 正文)。++ 返回活跃版本(未被 shadow 的),与 list_agents 保持一致的优先级语义。+ """+ agents = self.list_agents()+ for a in agents:+ if a.name == name and a.shadowed_by is None:+ return a+ return None++ def create_agent(self, params: CreateAgentParams) -> AgentDefinition:+ """创建新的自定义 agent,写入 markdown 文件。++ Raises:+ ValueError: 同名内置 agent 已存在时,或名称格式不符合要求+ """+ import re+ name = params.name.strip()+ if not re.match(r'^[a-zA-Z0-9_-]{3,50}$', name):+ raise ValueError(+ f"Agent 名称格式无效: '{name}'。要求 3-50 字符,仅允许字母、数字、连字符、下划线"+ )++ existing = self.get_agent(params.name)+ if existing is not None and existing.source == "builtin":+ raise ValueError(f"不能覆盖内置 agent: {params.name}")++ target_dir = self._resolve_location_dir(params.location)+ target_dir.mkdir(parents=True, exist_ok=True)+ file_path = target_dir / f"{params.name}.md"++ content = _format_agent_file(params)+ file_path.write_text(content, encoding="utf-8")++ logger.info("Created agent '%s' at %s", params.name, file_path)++ return AgentDefinition(+ name=params.name,+ description=params.description,+ prompt=params.prompt,+ source=params.location,+ file_path=str(file_path),+ model=params.model,+ tools=params.tools or ["*"],+ color=params.color,+ permission_mode=params.permission_mode,+ memory_scope=params.memory_scope,+ max_iterations=params.max_iterations,+ skills=params.skills,+ )++ def update_agent(self, name: str, params: UpdateAgentParams) -> AgentDefinition:+ """更新自定义 agent 定义,覆盖写入文件。++ Raises:+ ValueError: agent 不存在或为内置 agent+ """+ agent = self.get_agent(name)+ if agent is None:+ raise ValueError(f"Agent 不存在: {name}")+ if agent.source == "builtin":+ raise ValueError(f"不能修改内置 agent: {name}")+ if not agent.file_path:+ raise ValueError(f"Agent 无文件路径: {name}")++ _apply_update_params(agent, params)++ content = _format_agent_file(agent)+ Path(agent.file_path).write_text(content, encoding="utf-8")++ logger.info("Updated agent '%s' at %s", name, agent.file_path)+ return agent++ def delete_agent(self, name: str) -> bool:+ """删除自定义 agent 定义文件。++ Raises:+ ValueError: agent 为内置 agent+ """+ agent = self.get_agent(name)+ if agent is None:+ return False+ if agent.source == "builtin":+ raise ValueError(f"不能删除内置 agent: {name}")+ if agent.file_path:+ p = Path(agent.file_path)+ if p.exists():+ p.unlink()+ logger.info("Deleted agent '%s' at %s", name, agent.file_path)+ return True+ return False++ @staticmethod+ def list_available_tools() -> dict:+ """Return available tools with display names, internal names, descriptions, and groups."""+ from jiuwenswarm.server.runtime.agent_adapter.code_agent_rail import TOOL_GROUPS, DISALLOWED_FOR_SUBAGENTS+ from openjiuwen.harness.cli.ui.tool_display import _TOOL_DISPLAY_NAMES++ # Build internal → display mapping (deduplicated)+ internal_to_display: dict[str, str] = {}+ for internal_name, display_name in _TOOL_DISPLAY_NAMES.items():+ if internal_name not in internal_to_display:+ internal_to_display[internal_name] = display_name++ # Build display → group mapping from TOOL_GROUPS+ display_to_group: dict[str, str] = {}+ for group_name, display_names in TOOL_GROUPS.items():+ for dn in display_names:+ display_to_group[dn] = group_name++ # Build tool list from known internal names (deduplicated)+ tools = []+ seen_display = set()+ for internal_name, display_name in internal_to_display.items():+ if display_name in seen_display:+ continue+ seen_display.add(display_name)+ group = display_to_group.get(display_name, "高级")+ description = _TOOL_DESCRIPTIONS.get(display_name, display_name)+ tools.append({+ "name": display_name,+ "internal_name": internal_name,+ "description": description,+ "group": group,+ })++ # Add tools referenced in TOOL_GROUPS but not in _TOOL_DISPLAY_NAMES+ # (e.g., "LSP" whose internal name is "lsp")+ for group_name, display_names in TOOL_GROUPS.items():+ for dn in display_names:+ if dn not in seen_display:+ seen_display.add(dn)+ tools.append({+ "name": dn,+ "internal_name": dn.lower(),+ "description": _TOOL_DESCRIPTIONS.get(dn, dn),+ "group": group_name,+ })++ return {+ "tools": tools,+ "groups": list(TOOL_GROUPS.keys()),+ "disallowed_for_subagents": list(DISALLOWED_FOR_SUBAGENTS),+ }++ # ---- 内部方法 ----++ def _resolve_location_dir(self, location: str) -> Path:+ mapping = {+ "user": self._get_user_agents_dir(),+ "project": self._get_project_agents_dir(),+ "local": self._get_local_agents_dir(),+ }+ if location not in mapping:+ raise ValueError(f"无效的 location: {location},有效值: user, project, local")+ return mapping[location]++ @staticmethod+ def _load_from_dir(dir_path: Path, source: AgentSource) -> list[AgentDefinition]:+ """从目录加载所有 .md agent 定义文件。"""+ if not dir_path.exists():+ return []+ agents: list[AgentDefinition] = []+ for md_file in sorted(dir_path.glob("*.md")):+ try:+ agent = _parse_agent_file(md_file, source)+ if agent is not None:+ agents.append(agent)+ except Exception:+ logger.warning("Failed to parse agent file: %s", md_file, exc_info=True)+ return agents+++# ---------------------------------------------------------------------------+# 文件解析 / 生成+# ---------------------------------------------------------------------------+++def _parse_agent_file(file_path: Path, source: AgentSource) -> AgentDefinition | None:+ """解析 YAML frontmatter + Markdown body 格式的 agent 文件。"""+ content = file_path.read_text(encoding="utf-8")+ if not content.startswith("---"):+ return None+ parts = content.split("---", 2)+ if len(parts) < 3:+ return None+ frontmatter = yaml.safe_load(parts[1])+ prompt = parts[2].strip()+ if not frontmatter or "name" not in frontmatter:+ return None+ return AgentDefinition(+ name=frontmatter["name"],+ description=frontmatter.get("description", ""),+ when_to_use=frontmatter.get("when_to_use"),+ prompt=prompt,+ source=source,+ file_path=str(file_path),+ model=frontmatter.get("model"),+ tools=frontmatter.get("tools", ["*"]),+ disallowed_tools=frontmatter.get("disallowed_tools", []),+ color=frontmatter.get("color"),+ permission_mode=frontmatter.get("permission_mode"),+ memory_scope=frontmatter.get("memory_scope"),+ max_iterations=frontmatter.get("max_iterations"),+ skills=frontmatter.get("skills"),+ )+++def _format_agent_file(params: CreateAgentParams | AgentDefinition) -> str:+ """生成 YAML frontmatter + Markdown body 格式的 agent 文件内容。"""+ frontmatter: dict = {+ "name": params.name,+ "description": params.description,+ }+ prompt: str = params.prompt if hasattr(params, "prompt") else ""++ if hasattr(params, "when_to_use") and params.when_to_use:+ frontmatter["when_to_use"] = params.when_to_use+ if params.model:+ frontmatter["model"] = params.model+ if params.tools and params.tools != ["*"]:+ frontmatter["tools"] = params.tools+ if hasattr(params, "color") and params.color:+ frontmatter["color"] = params.color+ if hasattr(params, "permission_mode") and params.permission_mode:+ frontmatter["permission_mode"] = params.permission_mode+ if hasattr(params, "memory_scope") and params.memory_scope:+ frontmatter["memory_scope"] = params.memory_scope++ if hasattr(params, "disallowed_tools") and params.disallowed_tools:+ frontmatter["disallowed_tools"] = params.disallowed_tools+ if hasattr(params, "max_iterations") and params.max_iterations is not None:+ frontmatter["max_iterations"] = params.max_iterations+ if hasattr(params, "skills") and params.skills:+ frontmatter["skills"] = params.skills++ yaml_str = yaml.dump(frontmatter, allow_unicode=True, default_flow_style=False).strip()+ return f"---\n{yaml_str}\n---\n\n{prompt}\n"+++def _apply_update_params(agent: AgentDefinition, params: UpdateAgentParams) -> None:+ """将 UpdateAgentParams 的非 None 字段应用到 AgentDefinition。"""+ if params.description is not None:+ agent.description = params.description+ if params.when_to_use is not None:+ agent.when_to_use = params.when_to_use+ if params.prompt is not None:+ agent.prompt = params.prompt+ if params.model is not None:+ agent.model = params.model+ if params.tools is not None:+ agent.tools = params.tools+ if params.color is not None:+ agent.color = params.color+ if params.permission_mode is not None:+ agent.permission_mode = params.permission_mode+ if params.memory_scope is not None:+ agent.memory_scope = params.memory_scope+ if params.disallowed_tools is not None:+ agent.disallowed_tools = params.disallowed_tools+ if params.max_iterations is not None:+ agent.max_iterations = params.max_iterations+ if params.skills is not None:+ agent.skills = params.skills\ No newline at end of filediff --git a/tests/unit_tests/agentserver/test_agent_config_service.py b/tests/unit_tests/agentserver/test_agent_config_service.pynew file mode 100644index 0000000000..9c8df8950a--- /dev/null+++ b/tests/unit_tests/agentserver/test_agent_config_service.py@@ -0,0 +1,457 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""AgentConfigService 单元测试."""++from __future__ import annotations++import tempfile+from pathlib import Path++import pytest++import yaml++from jiuwenswarm.server.runtime.agent_config_service import (+ BUILTIN_AGENTS,+ AgentConfigService,+ CreateAgentParams,+ UpdateAgentParams,+)+from jiuwenswarm.common.config import (+ remove_subagent_from_config,+ upsert_subagent_in_config,+)+++class TestAgentConfigService:+ """AgentConfigService CRUD 操作测试."""++ @pytest.fixture+ def tmp_workspace(self):+ with tempfile.TemporaryDirectory() as d:+ yield Path(d)++ @pytest.fixture+ def service(self, tmp_workspace):+ """Create AgentConfigService with mocked get_user_workspace_dir."""+ import jiuwenswarm.server.runtime.agent_config_service as svc_mod+ orig = svc_mod.get_user_workspace_dir++ def mock_get_user_workspace_dir():+ return tmp_workspace++ svc_mod.get_user_workspace_dir = mock_get_user_workspace_dir+ try:+ return AgentConfigService(tmp_workspace)+ finally:+ svc_mod.get_user_workspace_dir = orig++ # ---- list_agents ----++ @staticmethod+ def test_list_agents_includes_builtins(service):+ agents = service.list_agents()+ builtin_names = {a.name for a in agents if a.source == "builtin"}+ assert "general-purpose" in builtin_names+ assert "Explore" in builtin_names+ assert "Plan" in builtin_names++ @staticmethod+ def test_list_agents_merges_custom_from_project_dir(service, tmp_workspace):+ agents_dir = tmp_workspace / ".jiuwenswarm" / "agents"+ agents_dir.mkdir(parents=True)+ (agents_dir / "my-agent.md").write_text(+ "---\nname: my-agent\ndescription: 测试 agent\n---\n\n这是一个测试 agent。\n",+ encoding="utf-8",+ )++ agents = service.list_agents()+ names = {a.name for a in agents}+ assert "my-agent" in names++ my_agent = next(a for a in agents if a.name == "my-agent")+ assert my_agent.source == "project"+ assert my_agent.description == "测试 agent"+ assert my_agent.prompt == "这是一个测试 agent。"++ @staticmethod+ def test_list_agents_priority_project_overrides_user(tmp_workspace):+ """project 级同名 agent 覆盖 user 级,user 级标记 shadowed_by。"""+ # 在同一个 workspace 下同时创建 project 和 local 同名 agent+ project_dir = tmp_workspace / ".jiuwenswarm" / "agents"+ project_dir.mkdir(parents=True)+ (project_dir / "my-agent.md").write_text(+ "---\nname: my-agent\ndescription: project 级\n---\n\nproject 级 prompt。\n",+ encoding="utf-8",+ )++ local_dir = tmp_workspace / ".jiuwenswarm" / "agents-local"+ local_dir.mkdir(parents=True)+ (local_dir / "my-agent.md").write_text(+ "---\nname: my-agent\ndescription: local 级\n---\n\nlocal 级 prompt。\n",+ encoding="utf-8",+ )++ service = AgentConfigService(tmp_workspace)+ agents = service.list_agents()+ project_agent = next(a for a in agents if a.name == "my-agent" and a.source == "project")+ local_agent = next(a for a in agents if a.name == "my-agent" and a.source == "local")+ assert project_agent.shadowed_by is None+ assert local_agent.shadowed_by == "project"++ @staticmethod+ def test_list_agents_sorts_by_source_order(service):+ agents = service.list_agents()+ sources = [a.source for a in agents]+ # builtin 应排在前面(sort key 最小)+ for src in sources:+ if src == "builtin":+ continue+ # 一旦出现非 builtin,之前的都应是 builtin+ break++ # ---- get_agent ----++ @staticmethod+ def test_get_agent_returns_builtin(service):+ agent = service.get_agent("Explore")+ assert agent is not None+ assert agent.source == "builtin"+ assert agent.prompt # 有 prompt 正文++ @staticmethod+ def test_get_agent_returns_none_for_unknown(service):+ assert service.get_agent("nonexistent") is None++ # ---- create_agent ----++ @staticmethod+ def test_create_agent_rejects_invalid_name(service, tmp_workspace):+ for invalid_name in ["ab", "bad-name!", "name with spaces", "x" * 51, ""]:+ with pytest.raises(ValueError, match="名称格式无效|name is required"):+ service.create_agent(CreateAgentParams(+ name=invalid_name, description="test", prompt="test prompt", location="user",+ ))++ @staticmethod+ def test_create_agent_writes_markdown_file(service, tmp_workspace):+ params = CreateAgentParams(+ name="test-agent",+ description="测试用 agent",+ prompt="你是一个测试 agent。",+ location="project",+ model="test-model",+ tools=["Read", "Bash"],+ max_iterations=50,+ skills=["daily-report"],+ )+ agent = service.create_agent(params)+ assert agent.name == "test-agent"+ assert agent.source == "project"+ assert agent.model == "test-model"+ assert agent.tools == ["Read", "Bash"]+ assert agent.max_iterations == 50+ assert agent.skills == ["daily-report"]++ # 验证文件写入+ md_file = tmp_workspace / ".jiuwenswarm" / "agents" / "test-agent.md"+ assert md_file.exists()+ content = md_file.read_text(encoding="utf-8")+ assert "name: test-agent" in content+ assert "你是一个测试 agent。" in content+ assert "max_iterations: 50" in content+ assert "daily-report" in content++ @staticmethod+ def test_create_agent_rejects_builtin_name(service):+ params = CreateAgentParams(+ name="Explore",+ description="覆盖内置 agent",+ prompt="test",+ location="project",+ )+ with pytest.raises(ValueError, match="不能覆盖内置 agent"):+ service.create_agent(params)++ @staticmethod+ def test_create_agent_overwrites_existing_custom(service, tmp_workspace):+ """创建同名自定义 agent 时覆盖已有文件。"""+ agents_dir = tmp_workspace / ".jiuwenswarm" / "agents"+ agents_dir.mkdir(parents=True)+ (agents_dir / "my-agent.md").write_text(+ "---\nname: my-agent\ndescription: old\n---\n\nold prompt\n",+ encoding="utf-8",+ )++ params = CreateAgentParams(+ name="my-agent",+ description="new description",+ prompt="new prompt",+ location="project",+ )+ agent = service.create_agent(params)+ assert agent.description == "new description"+ assert agent.prompt == "new prompt"++ # ---- update_agent ----++ @staticmethod+ def test_update_agent_modifies_fields(service, tmp_workspace):+ agents_dir = tmp_workspace / ".jiuwenswarm" / "agents"+ agents_dir.mkdir(parents=True)+ (agents_dir / "my-agent.md").write_text(+ "---\nname: my-agent\ndescription: original\n---\n\noriginal prompt\n",+ encoding="utf-8",+ )++ params = UpdateAgentParams(description="updated", model="new-model")+ agent = service.update_agent("my-agent", params)+ assert agent.description == "updated"+ assert agent.model == "new-model"+ assert agent.prompt == "original prompt" # 未修改++ @staticmethod+ def test_update_agent_rejects_builtin(service):+ params = UpdateAgentParams(description="hack")+ with pytest.raises(ValueError, match="不能修改内置 agent"):+ service.update_agent("Explore", params)++ @staticmethod+ def test_update_agent_rejects_nonexistent(service):+ params = UpdateAgentParams(description="x")+ with pytest.raises(ValueError, match="Agent 不存在"):+ service.update_agent("nonexistent", params)++ # ---- delete_agent ----++ @staticmethod+ def test_delete_agent_removes_file(service, tmp_workspace):+ agents_dir = tmp_workspace / ".jiuwenswarm" / "agents"+ agents_dir.mkdir(parents=True)+ md_file = agents_dir / "my-agent.md"+ md_file.write_text(+ "---\nname: my-agent\ndescription: test\n---\n\nprompt\n",+ encoding="utf-8",+ )++ assert service.delete_agent("my-agent") is True+ assert not md_file.exists()++ @staticmethod+ def test_delete_agent_rejects_builtin(service):+ with pytest.raises(ValueError, match="不能删除内置 agent"):+ service.delete_agent("general-purpose")++ @staticmethod+ def test_delete_agent_returns_false_for_unknown(service):+ assert service.delete_agent("nonexistent") is False++ # ---- 文件解析 ----++ @staticmethod+ def test_parse_agent_file_with_full_frontmatter(service, tmp_workspace):+ agents_dir = tmp_workspace / ".jiuwenswarm" / "agents"+ agents_dir.mkdir(parents=True)+ (agents_dir / "full.md").write_text(+ "---\n"+ "name: full-agent\n"+ "description: 完整配置的 agent\n"+ "model: claude-sonnet\n"+ "tools:\n"+ " - Read\n"+ " - Bash\n"+ "color: blue\n"+ "permission_mode: accept_edits\n"+ "memory_scope: project\n"+ "---\n\n"+ "完整的 system prompt 正文。\n",+ encoding="utf-8",+ )++ agents = service.list_agents()+ agent = next(a for a in agents if a.name == "full-agent")+ assert agent.description == "完整配置的 agent"+ assert agent.model == "claude-sonnet"+ assert agent.tools == ["Read", "Bash"]+ assert agent.color == "blue"+ assert agent.permission_mode == "accept_edits"+ assert agent.memory_scope == "project"+ assert agent.prompt == "完整的 system prompt 正文。"++ @staticmethod+ def test_parse_agent_file_with_minimal_frontmatter(service, tmp_workspace):+ agents_dir = tmp_workspace / ".jiuwenswarm" / "agents"+ agents_dir.mkdir(parents=True)+ (agents_dir / "minimal.md").write_text(+ "---\nname: minimal-agent\ndescription: 最小配置\n---\n\n只有必要字段。\n",+ encoding="utf-8",+ )++ agents = service.list_agents()+ agent = next(a for a in agents if a.name == "minimal-agent")+ assert agent.tools == ["*"] # 默认+ assert agent.model is None+ assert agent.color is None++ # ---- BUILTIN_AGENTS ----++ @staticmethod+ def test_builtin_agents_are_well_formed():+ for agent in BUILTIN_AGENTS:+ assert agent.name+ assert agent.description+ assert agent.prompt+ assert agent.source == "builtin"+ assert agent.tools++ @staticmethod+ def test_builtin_agents_have_unique_names():+ names = [a.name for a in BUILTIN_AGENTS]+ assert len(names) == len(set(names))+++class TestSubagentConfigMutation:+ """upsert_subagent_in_config / remove_subagent_from_config 测试."""++ @pytest.fixture+ def tmp_config(self, tmp_path):+ """创建临时 config.yaml 用于测试 round-trip 读写."""+ import jiuwenswarm.common.config as config_mod++ config_file = tmp_path / "config.yaml"+ config_file.write_text("{}\n", encoding="utf-8")+ orig = config_mod.CONFIG_YAML_PATH+ config_mod.CONFIG_YAML_PATH = config_file+ try:+ yield config_file+ finally:+ config_mod.CONFIG_YAML_PATH = orig++ @staticmethod+ def test_upsert_creates_new_entry(tmp_config):+ upsert_subagent_in_config("my-agent", enabled=True)+ data = yaml.safe_load(tmp_config.read_text(encoding="utf-8"))+ assert data["react"]["subagents"]["my-agent"]["enabled"] is True++ @staticmethod+ def test_upsert_updates_existing_entry(tmp_config):+ upsert_subagent_in_config("my-agent", enabled=True)+ upsert_subagent_in_config("my-agent", enabled=False)+ data = yaml.safe_load(tmp_config.read_text(encoding="utf-8"))+ assert data["react"]["subagents"]["my-agent"]["enabled"] is False++ @staticmethod+ def test_upsert_preserves_other_keys(tmp_config):+ upsert_subagent_in_config("my-agent", enabled=True)+ # 手动添加额外的 key 模拟已有配置+ import jiuwenswarm.common.config as config_mod++ roundtrip = config_mod.load_yaml_round_trip(config_mod.CONFIG_YAML_PATH)+ roundtrip["react"]["subagents"]["my-agent"]["max_iterations"] = 50+ config_mod.dump_yaml_round_trip(config_mod.CONFIG_YAML_PATH, roundtrip)+ # 再次 upsert,不应丢失 max_iterations+ upsert_subagent_in_config("my-agent", enabled=False)+ data = yaml.safe_load(tmp_config.read_text(encoding="utf-8"))+ assert data["react"]["subagents"]["my-agent"]["enabled"] is False+ assert data["react"]["subagents"]["my-agent"]["max_iterations"] == 50++ @staticmethod+ def test_remove_existing_entry(tmp_config):+ upsert_subagent_in_config("my-agent", enabled=True)+ removed = remove_subagent_from_config("my-agent")+ assert removed is True+ data = yaml.safe_load(tmp_config.read_text(encoding="utf-8"))+ assert "my-agent" not in data.get("react", {}).get("subagents", {})++ @staticmethod+ def test_remove_nonexistent_returns_false(tmp_config):+ assert remove_subagent_from_config("nonexistent") is False++ @staticmethod+ def test_upsert_empty_name_raises():+ with pytest.raises(ValueError, match="subagent name is required"):+ upsert_subagent_in_config("")++ @staticmethod+ def test_remove_empty_name_raises():+ with pytest.raises(ValueError, match="subagent name is required"):+ remove_subagent_from_config("")+++class TestAgentLLMGeneration:+ """_generate_agent_with_llm JSON 解析逻辑测试。++ 不导入 AgentWebSocketServer(避免 auto_harness 导入链问题),+ 直接测试 _generate_agent_with_llm 中的 JSON 解析逻辑。+ """++ @staticmethod+ def _parse_llm_response(text: str) -> tuple[str, str] | None:+ """复制 _generate_agent_with_llm 的 JSON 解析逻辑."""+ import re as _re+ import json as _json++ try:+ data = _json.loads(text.strip())+ except _json.JSONDecodeError:+ match = _re.search(r"\{[\s\S]*\}", text)+ if not match:+ return None+ try:+ data = _json.loads(match.group(0))+ except _json.JSONDecodeError:+ return None++ when_to_use = (data.get("whenToUse") or "").strip()+ system_prompt = (data.get("systemPrompt") or "").strip()++ if not when_to_use or not system_prompt:+ return None++ return when_to_use, system_prompt++ def test_parse_valid_json(self):+ result = self._parse_llm_response(+ '{"whenToUse": "Use this agent when...", "systemPrompt": "You are a helpful agent."}'+ )+ assert result is not None+ assert result[0] == "Use this agent when..."+ assert result[1] == "You are a helpful agent."++ def test_parse_json_with_extra_fields(self):+ result = self._parse_llm_response(+ '{"whenToUse": "use me", "systemPrompt": "hello", "extra": "ignored"}'+ )+ assert result == ("use me", "hello")++ def test_parse_missing_when_to_use(self):+ result = self._parse_llm_response('{"systemPrompt": "only prompt"}')+ assert result is None++ def test_parse_missing_system_prompt(self):+ result = self._parse_llm_response('{"whenToUse": "only when"}')+ assert result is None++ def test_parse_empty_strings(self):+ result = self._parse_llm_response('{"whenToUse": "", "systemPrompt": ""}')+ assert result is None++ def test_parse_bad_json(self):+ result = self._parse_llm_response("this is not json at all")+ assert result is None++ def test_parse_json_in_markdown_code_block(self):+ result = self._parse_llm_response(+ '```json\n{"whenToUse": "when condition", "systemPrompt": "system prompt"}\n```'+ )+ assert result == ("when condition", "system prompt")++ def test_parse_json_with_surrounding_text(self):+ result = self._parse_llm_response(+ 'Here is the config:\n{"whenToUse": "use me", "systemPrompt": "be helpful"}\nHope this helps!'+ )+ assert result == ("use me", "be helpful")++ def test_parse_empty_response(self):+ result = self._parse_llm_response("")+ assert result is None\ No newline at end of filediff --git a/tests/unit_tests/agentserver/test_code_agent_rail.py b/tests/unit_tests/agentserver/test_code_agent_rail.pynew file mode 100644index 0000000000..a5bca54cd7--- /dev/null+++ b/tests/unit_tests/agentserver/test_code_agent_rail.py@@ -0,0 +1,431 @@+"""Tests for CodeAgentRail and AgentTool."""+from __future__ import annotations++import pytest+from unittest.mock import AsyncMock, MagicMock, patch++from openjiuwen.core.session.agent import Session+from openjiuwen.core.foundation.tool import ToolCard+from jiuwenswarm.server.runtime.agent_adapter.code_agent_rail import (+ AgentTool,+ CodeAgentRail,+ DISALLOWED_FOR_SUBAGENTS,+ TOOL_GROUPS,+ _build_agent_tool_card,+ _filter_tool_cards,+)+++class TestBuildAgentToolCard:+ def test_empty_agents_returns_description_with_available_header(self):+ card = _build_agent_tool_card([])+ assert card.name == "Agent"+ assert "Available custom agents (created via /agents):" in card.description++ def test_lists_agent_with_description_and_tools(self):+ agent = _make_agent_def(+ name="reviewer", when_to_use="review code", tools=["Read", "Bash"]+ )+ card = _build_agent_tool_card([agent])+ assert "reviewer: review code (Tools: Read, Bash)" in card.description++ def test_input_params_require_subagent_type(self):+ card = _build_agent_tool_card([])+ assert "subagent_type" in card.input_params["required"]+++class TestAgentTool:+ @pytest.mark.asyncio+ async def test_invoke_missing_subagent_type_raises(self):+ tool = _make_agent_tool()+ session = MagicMock(spec=Session)+ with pytest.raises(Exception) as exc:+ await tool.invoke({"prompt": "do X"}, session=session)+ assert "subagent_type" in str(exc.value).lower()++ @pytest.mark.asyncio+ async def test_invoke_missing_prompt_raises(self):+ tool = _make_agent_tool()+ session = MagicMock(spec=Session)+ with pytest.raises(Exception) as exc:+ await tool.invoke({"subagent_type": "reviewer"}, session=session)+ assert "prompt" in str(exc.value).lower()++ @pytest.mark.asyncio+ async def test_invoke_missing_session_kwarg_raises(self):+ """When session kwarg is missing or not a Session instance, raise."""+ tool = _make_agent_tool()+ with pytest.raises(Exception) as exc:+ await tool.invoke({"subagent_type": "reviewer", "prompt": "do X"})+ assert "session" in str(exc.value).lower()++ @pytest.mark.asyncio+ async def test_invoke_unknown_agent_type_raises(self):+ tool = _make_agent_tool()+ session = MagicMock(spec=Session)+ with pytest.raises(Exception) as exc:+ await tool.invoke(+ {"subagent_type": "nonexistent", "prompt": "do X"},+ session=session,+ )+ assert "not found" in str(exc.value).lower()++ @pytest.mark.asyncio+ async def test_invoke_sync_creates_and_runs_subagent(self):+ mock_subagent = MagicMock()+ mock_subagent.invoke = AsyncMock(return_value={"output": "done"})++ parent = MagicMock()+ agent_def = _make_agent_def(+ name="reviewer", when_to_use="review", tools=["Read"]+ )+ tool = _make_agent_tool(parent=parent, custom_agents=[agent_def])++ session = MagicMock(spec=Session)+ session.get_session_id.return_value = "session_123"++ with patch.object(tool, "_create_sub_agent", return_value=mock_subagent):+ result = await tool.invoke(+ {"subagent_type": "reviewer", "prompt": "review this"},+ session=session,+ )++ mock_subagent.invoke.assert_called_once()+ assert result.success is True+ assert result.data["output"] == "done"+ assert result.data["agent_id"] == "reviewer"++ @pytest.mark.asyncio+ async def test_invoke_background_returns_async_launched(self):+ mock_subagent = MagicMock()++ parent = MagicMock()+ agent_def = _make_agent_def(name="reviewer")+ tool = _make_agent_tool(parent=parent, custom_agents=[agent_def])++ session = MagicMock(spec=Session)+ session.get_session_id.return_value = "session_123"++ with patch.object(tool, "_create_sub_agent", return_value=mock_subagent):+ result = await tool.invoke(+ {"subagent_type": "reviewer", "prompt": "do X", "background": True},+ session=session,+ )++ assert result.data["status"] == "async_launched"+ assert result.data["agent_id"] == "reviewer"+ assert result.data["prompt"] == "do X"++ @pytest.mark.asyncio+ async def test_invoke_with_subagent_creation_failure_raises(self):+ parent = MagicMock()+ agent_def = _make_agent_def(name="reviewer")+ tool = _make_agent_tool(parent=parent, custom_agents=[agent_def])++ session = MagicMock(spec=Session)+ session.get_session_id.return_value = "session_123"++ with patch.object(tool, "_create_sub_agent", side_effect=RuntimeError("creation failed")):+ with pytest.raises(Exception) as exc:+ await tool.invoke(+ {"subagent_type": "reviewer", "prompt": "do X"},+ session=session,+ )+ assert "creation failed" in str(exc.value)++ @pytest.mark.asyncio+ async def test_invoke_with_subagent_execution_failure_raises(self):+ mock_subagent = MagicMock()+ mock_subagent.invoke = AsyncMock(+ side_effect=RuntimeError("execution failed")+ )++ parent = MagicMock()+ agent_def = _make_agent_def(name="reviewer")+ tool = _make_agent_tool(parent=parent, custom_agents=[agent_def])++ session = MagicMock(spec=Session)+ session.get_session_id.return_value = "session_123"++ with patch.object(tool, "_create_sub_agent", return_value=mock_subagent):+ with pytest.raises(Exception) as exc:+ await tool.invoke(+ {"subagent_type": "reviewer", "prompt": "do X"},+ session=session,+ )+ assert "execution failed" in str(exc.value)+++class TestCodeAgentRail:+ def test_init_no_custom_agents_skips_tool_registration(self):+ rail = CodeAgentRail(workspace_dir="/tmp")+ agent = MagicMock()+ with patch.object(rail, "_load_custom_agents", return_value=[]):+ rail.init(agent)+ assert rail._agent_tool is None++ def test_init_with_custom_agents_registers_tool(self):+ rail = CodeAgentRail(workspace_dir="/tmp")+ agent = MagicMock()+ agent_def = _make_agent_def(name="reviewer")+ with (+ patch.object(rail, "_load_custom_agents", return_value=[agent_def]),+ patch(+ "jiuwenswarm.server.runtime.agent_adapter.code_agent_rail.Runner.resource_mgr"+ ) as mock_mgr,+ ):+ rail.init(agent)+ assert rail._agent_tool is not None++ def test_uninit_removes_tool(self):+ rail = CodeAgentRail(workspace_dir="/tmp")+ agent = MagicMock()+ agent_def = _make_agent_def(name="reviewer")+ with (+ patch.object(rail, "_load_custom_agents", return_value=[agent_def]),+ patch(+ "jiuwenswarm.server.runtime.agent_adapter.code_agent_rail.Runner.resource_mgr"+ ) as mock_mgr,+ ):+ rail.init(agent)+ assert rail._agent_tool is not None+ rail.uninit(agent)+ assert rail._agent_tool is None+ assert rail._agent is None++ def test_init_twice_replaces_tool(self):+ """Initializing twice should create a new AgentTool each time."""+ rail = CodeAgentRail(workspace_dir="/tmp")+ agent = MagicMock()+ agent_def = _make_agent_def(name="reviewer")+ with (+ patch.object(rail, "_load_custom_agents", return_value=[agent_def]),+ patch(+ "jiuwenswarm.server.runtime.agent_adapter.code_agent_rail.Runner.resource_mgr"+ ),+ ):+ rail.init(agent)+ first_tool = rail._agent_tool+ rail.init(agent)+ assert rail._agent_tool is not first_tool++ def test_load_custom_agents_filters_builtin_and_disabled(self):+ """_load_custom agents should only include non-builtin enabled agents."""+ from jiuwenswarm.server.runtime.agent_config_service import AgentDefinition++ rail = CodeAgentRail(workspace_dir="/tmp")+ # Mock the AgentConfigService to return a mix of agents+ builtin = AgentDefinition(+ name="explore", description="", prompt="",+ source="builtin", enabled=None,+ )+ project_disabled = AgentDefinition(+ name="disabled-agent", description="", prompt="",+ source="project", enabled=False,+ )+ project_enabled = AgentDefinition(+ name="enabled-agent", description="", prompt="",+ source="project", enabled=True,+ )++ with patch(+ "jiuwenswarm.server.runtime.agent_config_service.AgentConfigService"+ ) as mock_svc_cls:+ mock_svc = mock_svc_cls.return_value+ mock_svc.list_agents.return_value = [+ builtin, project_disabled, project_enabled,+ ]+ result = rail._load_custom_agents()++ assert len(result) == 1+ assert result[0].name == "enabled-agent"++ def test_priority_set_correctly(self):+ rail = CodeAgentRail(workspace_dir="/tmp")+ assert rail.priority == 90+++class TestFilterToolCards:+ """Tests for _filter_tool_cards() — tool filtering by agent definition."""++ @pytest.fixture(autouse=True)+ def _mock_display_mapping(self):+ """Mock _build_display_to_internal_mapping to avoid importing prompt_toolkit in CI."""+ mapping = {"Read": "read_file", "Bash": "bash", "Edit": "edit_file",+ "Grep": "grep", "Write": "write_file", "LS": "ls"}+ with patch(+ "jiuwenswarm.server.runtime.agent_adapter.code_agent_rail._build_display_to_internal_mapping",+ return_value=mapping,+ ):+ yield++ def test_wildcard_returns_all_cards(self):+ cards = [+ ToolCard(id="t1", name="read_file", description="Read file"),+ ToolCard(id="t2", name="bash", description="Run bash"),+ ToolCard(id="t3", name="edit_file", description="Edit file"),+ ]+ result = _filter_tool_cards(cards, allowed_tools=["*"])+ assert result == cards++ def test_specific_display_names_filter_cards(self):+ cards = [+ ToolCard(id="t1", name="read_file", description="Read file"),+ ToolCard(id="t2", name="bash", description="Run bash"),+ ToolCard(id="t3", name="edit_file", description="Edit file"),+ ToolCard(id="t4", name="grep", description="Search files"),+ ]+ result = _filter_tool_cards(cards, allowed_tools=["Read", "Bash"])+ assert len(result) == 2+ assert {tc.name for tc in result} == {"read_file", "bash"}++ def test_internal_names_also_accepted(self):+ cards = [+ ToolCard(id="t1", name="read_file", description="Read file"),+ ToolCard(id="t2", name="bash", description="Run bash"),+ ]+ result = _filter_tool_cards(cards, allowed_tools=["read_file"])+ assert len(result) == 1+ assert result[0].name == "read_file"++ def test_disallowed_tools_removes_from_result(self):+ cards = [+ ToolCard(id="t1", name="read_file", description="Read file"),+ ToolCard(id="t2", name="bash", description="Run bash"),+ ToolCard(id="t3", name="edit_file", description="Edit file"),+ ]+ result = _filter_tool_cards(+ cards, allowed_tools=["*"], disallowed_tools=["Edit"]+ )+ assert len(result) == 2+ assert all(tc.name != "edit_file" for tc in result)++ def test_disallowed_tools_with_internal_name(self):+ cards = [+ ToolCard(id="t1", name="read_file", description="Read file"),+ ToolCard(id="t2", name="bash", description="Run bash"),+ ]+ result = _filter_tool_cards(+ cards, allowed_tools=["*"], disallowed_tools=["read_file"]+ )+ assert len(result) == 1+ assert result[0].name == "bash"++ def test_empty_allowed_list_returns_empty(self):+ cards = [ToolCard(id="t1", name="read_file", description="Read file")]+ result = _filter_tool_cards(cards, allowed_tools=[])+ assert result == []++ def test_no_matching_tools_returns_empty(self):+ cards = [ToolCard(id="t1", name="read_file", description="Read file")]+ result = _filter_tool_cards(cards, allowed_tools=["WebSearch"])+ assert result == []++ def test_mixed_display_and_internal_names(self):+ """When allowed_tools contains both display and internal names, both match."""+ cards = [+ ToolCard(id="t1", name="read_file", description="Read file"),+ ToolCard(id="t2", name="bash", description="Run bash"),+ ToolCard(id="t3", name="grep", description="Search"),+ ]+ result = _filter_tool_cards(cards, allowed_tools=["Read", "bash"])+ assert len(result) == 2+ assert {tc.name for tc in result} == {"read_file", "bash"}++ def test_does_not_modify_original_list(self):+ cards = [+ ToolCard(id="t1", name="read_file", description="Read file"),+ ToolCard(id="t2", name="bash", description="Run bash"),+ ]+ original = list(cards)+ _ = _filter_tool_cards(cards, allowed_tools=["*"])+ assert cards == original++ def test_disallowed_tools_none_does_nothing(self):+ cards = [+ ToolCard(id="t1", name="read_file", description="Read file"),+ ToolCard(id="t2", name="bash", description="Run bash"),+ ]+ result = _filter_tool_cards(cards, allowed_tools=["*"], disallowed_tools=None)+ assert result == cards++ def test_disallowed_tools_empty_list_does_nothing(self):+ cards = [+ ToolCard(id="t1", name="read_file", description="Read file"),+ ]+ result = _filter_tool_cards(cards, allowed_tools=["*"], disallowed_tools=[])+ assert result == cards+++class TestModuleConstants:+ """Verify module-level constants have expected values."""++ def test_disallowed_for_subagents_contains_key_tools(self):+ assert "Agent" in DISALLOWED_FOR_SUBAGENTS+ assert "task" in DISALLOWED_FOR_SUBAGENTS+ assert "enter_plan_mode" in DISALLOWED_FOR_SUBAGENTS+ assert "switch_mode" in DISALLOWED_FOR_SUBAGENTS++ def test_tool_groups_has_expected_categories(self):+ assert "核心" in TOOL_GROUPS+ assert "搜索" in TOOL_GROUPS+ assert "代码智能" in TOOL_GROUPS+ assert "高级" in TOOL_GROUPS+ assert "可视化" in TOOL_GROUPS++ def test_tool_groups_use_display_names(self):+ """TOOL_GROUPS values should use display names, not internal names."""+ assert "Read" in TOOL_GROUPS["核心"]+ assert "Bash" in TOOL_GROUPS["核心"]+ assert "WebSearch" in TOOL_GROUPS["搜索"]+++# ─── helpers ─────────────────────────────────────────+++def _make_agent_def(+ name="test-agent",+ when_to_use="test agent",+ tools=None,+ prompt="You are a test agent.",+):+ from jiuwenswarm.server.runtime.agent_config_service import AgentDefinition++ return AgentDefinition(+ name=name,+ description="test",+ prompt=prompt,+ source="project",+ tools=tools or ["*"],+ when_to_use=when_to_use,+ )+++def _build_tool_card() -> ToolCard:+ return ToolCard(+ id="agent_tool_test123",+ name="Agent",+ description="Launch a custom agent",+ input_params={+ "type": "object",+ "properties": {+ "subagent_type": {"type": "string"},+ "prompt": {"type": "string"},+ "description": {"type": "string"},+ "model": {"type": "string", "enum": ["sonnet", "opus", "haiku"]},+ "background": {"type": "boolean", "default": False},+ },+ "required": ["subagent_type", "prompt", "description"],+ },+ )+++def _make_agent_tool(+ parent: MagicMock | None = None,+ custom_agents: list | None = None,+) -> AgentTool:+ return AgentTool(+ card=_build_tool_card(),+ parent_agent=parent or MagicMock(),+ custom_agents=custom_agents or [],+ )\ No newline at end of filediff --git a/tests/unit_tests/gateway/test_agent_mentions.py b/tests/unit_tests/gateway/test_agent_mentions.pynew file mode 100644index 0000000000..93f20e4c53--- /dev/null+++ b/tests/unit_tests/gateway/test_agent_mentions.py@@ -0,0 +1,93 @@+"""Tests for @agent-mention parsing and @file exclusion."""++import os+import tempfile++from jiuwenswarm.gateway.message_handler.message_handler import MessageHandler+++class TestAtFileExcludesAgentPrefix:+ """@agent-xxx mentions should NOT be resolved as file paths."""++ @staticmethod+ def test_skips_agent_hyphen_prefix():+ content = "@agent-reviewer some text"+ result = MessageHandler.resolve_at_file_references(content, cwd="/tmp")+ assert "<file-content" not in result+ assert "@agent-reviewer" in result++ @staticmethod+ def test_skips_agent_colon_prefix():+ content = "@agent:plugin-name some text"+ result = MessageHandler.resolve_at_file_references(content, cwd="/tmp")+ assert "<file-content" not in result+ assert "@agent:plugin-name" in result++ @staticmethod+ def test_agent_and_file_in_same_message():+ """@agent-xxx and @file.py should coexist — only file resolved."""+ with tempfile.NamedTemporaryFile(+ mode="w", suffix=".py", delete=False, dir="/tmp"+ ) as f:+ f.write("print('hello')")+ fname = os.path.basename(f.name)+ try:+ content = f"@agent-reviewer @{fname} some text"+ result = MessageHandler.resolve_at_file_references(content, cwd="/tmp")+ assert "@agent-reviewer" in result+ assert "<file-content" in result+ finally:+ os.unlink(f.name)++ @staticmethod+ def test_strip_attached_mentions_skips_agent_prefix():+ """strip_attached_mentions should not strip @agent-xxx."""+ content = "@agent-reviewer @/tmp/test.py hello"+ attachments = [{"path": "/tmp/test.py", "type": "file"}]+ result = MessageHandler.strip_attached_mentions(content, attachments, cwd="/tmp")+ assert "@agent-reviewer" in result+++class TestExtractAgentMentions:+ """Test extract_agent_mentions() parsing logic."""++ @staticmethod+ def test_basic():+ result = MessageHandler.extract_agent_mentions("@agent-reviewer please review")+ assert result == ["reviewer"]++ @staticmethod+ def test_multiple():+ result = MessageHandler.extract_agent_mentions("@agent-reviewer @agent-tester check")+ assert result == ["reviewer", "tester"]++ @staticmethod+ def test_quoted_format():+ result = MessageHandler.extract_agent_mentions('@"code-reviewer (agent)" check')+ assert result == ["code-reviewer"]++ @staticmethod+ def test_plugin_scoped():+ result = MessageHandler.extract_agent_mentions("@agent-asana:project-status")+ assert result == ["asana:project-status"]++ @staticmethod+ def test_dedup():+ result = MessageHandler.extract_agent_mentions("@agent-reviewer @agent-reviewer again")+ assert result == ["reviewer"]++ @staticmethod+ def test_empty():+ result = MessageHandler.extract_agent_mentions("no mentions here")+ assert result == []++ @staticmethod+ def test_mixed_with_file():+ result = MessageHandler.extract_agent_mentions("@agent-reviewer @src/main.py review this")+ assert result == ["reviewer"]++ @staticmethod+ def test_at_agent_without_hyphen_ignored():+ """@agent (without suffix) should NOT be treated as agent mention."""+ result = MessageHandler.extract_agent_mentions("@agent is cool")+ assert result == []\ No newline at end of filediff --git a/tests/unit_tests/gateway/test_slash_command.py b/tests/unit_tests/gateway/test_slash_command.pyindex c936ed187d..827ef866bf 100644--- a/tests/unit_tests/gateway/test_slash_command.py+++ b/tests/unit_tests/gateway/test_slash_command.py@@ -144,4 +144,8 @@ def test_format_skills_list_for_notice() -> None:def test_first_batch_registry_ids() -> None:ids = {e.id for e in FIRST_BATCH_REGISTRY}- assert ids == {"new_session", "mode", "switch", "skills", "resume", "workspace_dir", "branch", "rewind", "recap"}+ expected = {+ "new_session", "mode", "switch", "skills", "resume",+ "workspace_dir", "branch", "rewind", "recap", "agents",+ }+ assert ids == expecteddiff --git a/tests/unit_tests/test_config.py b/tests/unit_tests/test_config.pyindex 572f5e2c7a..c4ce2034cd 100644--- a/tests/unit_tests/test_config.py+++ b/tests/unit_tests/test_config.py@@ -223,7 +223,7 @@ modes:""",encoding="utf-8",)- monkeypatch.setattr("jiuwenswarm.common.config._CONFIG_YAML_PATH", temp_config_file)+ monkeypatch.setattr("jiuwenswarm.common.config.CONFIG_YAML_PATH", temp_config_file)replace_teams_in_config(TestTeamModesConfig._front_payload(["alpha_team"]))@@ -267,7 +267,7 @@ modes:""",encoding="utf-8",)- monkeypatch.setattr("jiuwenswarm.common.config._CONFIG_YAML_PATH", temp_config_file)+ monkeypatch.setattr("jiuwenswarm.common.config.CONFIG_YAML_PATH", temp_config_file)replace_teams_in_config(TestTeamModesConfig._front_payload(["alpha_team"], include_teammate=True))@@ -315,7 +315,7 @@ modes:monkeypatch: pytest.MonkeyPatch,temp_config_file: Path,):- monkeypatch.setattr("jiuwenswarm.common.config._CONFIG_YAML_PATH", temp_config_file)+ monkeypatch.setattr("jiuwenswarm.common.config.CONFIG_YAML_PATH", temp_config_file)replace_teams_in_config(TestTeamModesConfig._front_payload(["alpha_team"]))@@ -329,7 +329,7 @@ modes:monkeypatch: pytest.MonkeyPatch,temp_config_file: Path,):- monkeypatch.setattr("jiuwenswarm.common.config._CONFIG_YAML_PATH", temp_config_file)+ monkeypatch.setattr("jiuwenswarm.common.config.CONFIG_YAML_PATH", temp_config_file)with pytest.raises(ValueError, match="duplicate team_name"):replace_teams_in_config(TestTeamModesConfig._front_payload(["alpha_team", "alpha_team"]))@@ -339,7 +339,7 @@ modes:monkeypatch: pytest.MonkeyPatch,temp_config_file: Path,):- monkeypatch.setattr("jiuwenswarm.common.config._CONFIG_YAML_PATH", temp_config_file)+ monkeypatch.setattr("jiuwenswarm.common.config.CONFIG_YAML_PATH", temp_config_file)payload = TestTeamModesConfig._front_payload(["alpha_team"])payload["team"][0]["predefined_members"][1]["agent_key"] = "missing_agent"@@ -351,7 +351,7 @@ modes:monkeypatch: pytest.MonkeyPatch,temp_config_file: Path,):- monkeypatch.setattr("jiuwenswarm.common.config._CONFIG_YAML_PATH", temp_config_file)+ monkeypatch.setattr("jiuwenswarm.common.config.CONFIG_YAML_PATH", temp_config_file)payload = TestTeamModesConfig._front_payload(["alpha_team"], include_teammate=True)payload["team"][0]["teammate"]["agent_key"] = "missing_agent"@@ -363,7 +363,7 @@ modes:monkeypatch: pytest.MonkeyPatch,temp_config_file: Path,):- monkeypatch.setattr("jiuwenswarm.common.config._CONFIG_YAML_PATH", temp_config_file)+ monkeypatch.setattr("jiuwenswarm.common.config.CONFIG_YAML_PATH", temp_config_file)replace_teams_in_config(TestTeamModesConfig._front_payload(["alpha_team", "beta_team"]))replace_teams_in_config(TestTeamModesConfig._front_payload(["gamma_team"]))@@ -376,7 +376,7 @@ modes:monkeypatch: pytest.MonkeyPatch,temp_config_file: Path,):- monkeypatch.setattr("jiuwenswarm.common.config._CONFIG_YAML_PATH", temp_config_file)+ monkeypatch.setattr("jiuwenswarm.common.config.CONFIG_YAML_PATH", temp_config_file)payload = TestTeamModesConfig._front_payload(["alpha_team"])payload["team"][0]["predefined_members"][1]["member_name"] = "analyst"