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
在cli模式下增加code.team模式
weichenhao237301df9d08
diff --git a/jiuwenclaw/agents/harness/team/team_manager.py b/jiuwenclaw/agents/harness/team/team_manager.pyindex 667ea5e7f6..2be37db127 100644--- a/jiuwenclaw/agents/harness/team/team_manager.py+++ b/jiuwenclaw/agents/harness/team/team_manager.py@@ -640,6 +640,9 @@ class TeamManager:logger.debug("[TeamManager] member workspace.root_path=%s", agent_ws.root_path)else:logger.warning("[TeamManager] agent deep_config.workspace is None")+ parent_adapter_mode = str(+ getattr(deep_agent, "_jiuwenclaw_adapter_mode", "") or ""+ ).lower()inheritable_cards = filter_inheritable_ability_cards(deep_agent)existing_ability_ids = {card.id for card in agent.ability_manager.list() or []}@@ -659,6 +662,7 @@ class TeamManager:member_workspace = agent.deep_config.workspace if agent.deep_config else Nonemember_skills_dir_resolved: Path | None = None+ member_skill_manager: Any | None = Noneif member_workspace and member_workspace.root_path:member_skills_dir = Path(member_workspace.root_path) / "skills"member_skills_dir_resolved = member_skills_dir@@ -676,6 +680,11 @@ class TeamManager:except Exception as exc:logger.warning("[TeamManager] skill copy failed: %s", exc)+ try:+ member_skill_manager = SkillManager(workspace_dir=str(member_workspace.root_path))+ except Exception as exc:+ logger.warning("[TeamManager] member SkillManager setup failed: %s", exc)+# Create independent SkillManager and SkillToolkit for membertry:agent.add_rail(@@ -690,6 +699,37 @@ class TeamManager:except Exception as exc:logger.warning("[TeamManager] MemberSkillToolkitRail setup failed: %s", exc)+ if parent_adapter_mode == "code":+ try:+ from jiuwenclaw.server.runtime.agent_adapter.interface_code import (+ configure_code_team_member_agent,+ )++ parent_workspace = (+ deep_agent.deep_config.workspace if deep_agent.deep_config else None+ )+ configure_code_team_member_agent(+ agent,+ parent_agent=deep_agent,+ skill_manager=member_skill_manager,+ member_name=member_name,+ role=role,+ session_id=session_id,+ channel_id=resolved_channel,+ project_dir=(+ str(parent_workspace.root_path)+ if parent_workspace and parent_workspace.root_path+ else None+ ),+ )+ except Exception as exc:+ logger.warning(+ "[TeamManager] code team member adapter setup failed: member=%s role=%s error=%s",+ member_name,+ role,+ exc,+ )+# Build all member rails (common + skill rails via role).try:member_rails = build_member_rails(diff --git a/jiuwenclaw/channels/tui/frontend/src/app-state.ts b/jiuwenclaw/channels/tui/frontend/src/app-state.tsindex 7f1684f96a..069fe8a5ac 100644--- a/jiuwenclaw/channels/tui/frontend/src/app-state.ts+++ b/jiuwenclaw/channels/tui/frontend/src/app-state.ts@@ -22,6 +22,7 @@ import {type PendingQuestionItem,type UserAnswer,} from "./core/event-handlers.js";+import { isTeamMode, type ClientMode } from "./core/modes.js";import { isEventFrame, type EventFrame, type FileAttachment } from "./core/protocol.js";import {StreamingState,@@ -72,7 +73,7 @@ export interface SessionUsageSummary {export interface AppSnapshot {connectionStatus: ConnectionStatus;sessionId: string;- mode: "agent.plan" | "agent.fast" | "code.plan" | "code.normal" | "code.team" | "team";+ mode: ClientMode;themeName: ThemeName;accentColor: AccentColorName;transcriptMode: "compact" | "detailed";@@ -112,8 +113,7 @@ export class CliPiAppState {private connectionStatus: ConnectionStatus = "idle";private sessionId: string;private sessionTitle: string = "";- private mode: "agent.plan" | "agent.fast" | "code.plan" | "code.normal" | "code.team" | "team" =- "code.normal";+ private mode: ClientMode = "code.normal";private themeName: ThemeName = getCurrentThemeName();private accentColor: AccentColorName = getCurrentAccentColor();private transcriptMode: "compact" | "detailed" = "compact";@@ -368,7 +368,8 @@ export class CliPiAppState {hasRunningTools ||hasActiveSubtasks ||this.evolutionStatus === "running" ||- (this.mode === "team" && isTeamWorking(this.teamMemberEvents, this.teamMessageEvents));+ (isTeamMode(this.mode) &&+ isTeamWorking(this.teamMemberEvents, this.teamMessageEvents));return {connectionStatus: this.connectionStatus,sessionId: this.sessionId,@@ -574,9 +575,7 @@ readonly request = async <T = Record<string, unknown>>(this.emitChange();};- readonly setMode = (- mode: "agent.plan" | "agent.fast" | "code.plan" | "code.normal" | "team",- ): void => {+ readonly setMode = (mode: ClientMode): void => {if (this.mode !== mode) {this.mode = mode;this.emitChange();@@ -662,7 +661,7 @@ readonly request = async <T = Record<string, unknown>>(readonly sendMessage = (content: string,attachments?: FileAttachment[],- modeOverride?: "agent.plan" | "agent.fast" | "code.plan" | "code.normal" | "team",+ modeOverride?: ClientMode,options?: { logAsUser?: boolean },): string | null => {if (this.connectionStatus !== "connected") return null;diff --git a/jiuwenclaw/channels/tui/frontend/src/core/commands/builtins/init.ts b/jiuwenclaw/channels/tui/frontend/src/core/commands/builtins/init.tsindex 0fd5eab877..99ad994d86 100644--- a/jiuwenclaw/channels/tui/frontend/src/core/commands/builtins/init.ts+++ b/jiuwenclaw/channels/tui/frontend/src/core/commands/builtins/init.ts@@ -91,8 +91,8 @@ export function createInitCommand(): SlashCommand {return;}- // ---- Guard 2: code.plan blocks Write/Edit; auto-switch to code.normal ----- if (ctx.mode === "code.plan") {+ // ---- Guard 2: /init runs in code.normal; keep UI mode and request mode aligned ----+ if (ctx.mode !== "code.normal") {ctx.setMode("code.normal");ctx.addItem(addInfo(diff --git a/jiuwenclaw/channels/tui/frontend/src/core/commands/builtins/mode.ts b/jiuwenclaw/channels/tui/frontend/src/core/commands/builtins/mode.tsindex 24279bb15d..66248c7536 100644--- a/jiuwenclaw/channels/tui/frontend/src/core/commands/builtins/mode.ts+++ b/jiuwenclaw/channels/tui/frontend/src/core/commands/builtins/mode.ts@@ -1,4 +1,5 @@import type { AutocompleteItem } from "@mariozechner/pi-tui";+import type { ClientMode } from "../../modes.js";import { makeItem } from "../helpers.js";import { CommandKind, type SlashCommand } from "../types.js";@@ -28,10 +29,7 @@ export function createModeCommand(): SlashCommand {"team",] as const;/** 用户输入的简写 → 实际会话模式(/mode agent → agent.plan,/mode code → code.normal)。 */- const modeAlias: Record<- string,- "agent.plan" | "agent.fast" | "code.plan" | "code.normal" | "code.team" | "team"- > = {+ const modeAlias: Record<string, ClientMode> = {plan: "agent.plan",agent: "agent.plan",code: "code.normal",@@ -46,8 +44,8 @@ export function createModeCommand(): SlashCommand {return {name: "mode",description: "Switch chat mode",- usage: "/mode <agent|code|team>",- example: "/mode agent",+ usage: "/mode <agent|code|code.team|team>",+ example: "/mode code.team",kind: CommandKind.BUILT_IN,takesArgs: true,completion: async () => [...directModes],@@ -72,7 +70,7 @@ export function createModeCommand(): SlashCommand {makeItem(ctx.sessionId,"error",- "usage: /mode <agent|code|team>",+ "usage: /mode <agent|code|code.team|team>",),);return;diff --git a/jiuwenclaw/channels/tui/frontend/src/core/commands/builtins/switch.ts b/jiuwenclaw/channels/tui/frontend/src/core/commands/builtins/switch.tsindex 76a8075c49..279de3cd39 100644--- a/jiuwenclaw/channels/tui/frontend/src/core/commands/builtins/switch.ts+++ b/jiuwenclaw/channels/tui/frontend/src/core/commands/builtins/switch.ts@@ -1,13 +1,13 @@+import type { ClientMode } from "../../modes.js";import { makeItem } from "../helpers.js";import { CommandKind, type SlashCommand } from "../types.js";-type ClientMode = "agent.plan" | "agent.fast" | "code.plan" | "code.normal" | "code.team" | "team";type SwitchArg = "plan" | "fast" | "normal" | "team";const AGENT_MODES = new Set<ClientMode>(["agent.plan", "agent.fast"]);const CODE_MODES = new Set<ClientMode>(["code.plan", "code.normal", "code.team"]);-function resolveRequestedMode(currentMode: ClientMode, switchArg: SwitchArg): string | null {+function resolveRequestedMode(currentMode: ClientMode, switchArg: SwitchArg): ClientMode | null {if (switchArg === "plan") {if (AGENT_MODES.has(currentMode)) return "agent.plan";if (CODE_MODES.has(currentMode)) return "code.plan";@@ -53,7 +53,7 @@ export function createSwitchCommand(): SlashCommand {// Some backends still accept mode only on chat.send.}- ctx.setMode(requestedMode as ClientMode);+ ctx.setMode(requestedMode);ctx.addItem(makeItem(ctx.sessionId, "info", `Mode switched to ${requestedMode}`, "s"));},};diff --git a/jiuwenclaw/channels/tui/frontend/src/core/commands/types.ts b/jiuwenclaw/channels/tui/frontend/src/core/commands/types.tsindex cd8de948b6..ce831cc8c8 100644--- a/jiuwenclaw/channels/tui/frontend/src/core/commands/types.ts+++ b/jiuwenclaw/channels/tui/frontend/src/core/commands/types.ts@@ -3,6 +3,7 @@ import type { AccentColorName, ThemeName } from "../../ui/theme.js";import type { PendingQuestionItem, UserAnswer } from "../event-handlers.js";import type { FileAttachment } from "../protocol.js";import type { ConfigItemSchema } from "./builtins/config.js";+import type { ClientMode } from "../modes.js";import type { SessionUsageSummary } from "../../app-state.js";export type ConnectionStatus = "idle" | "connecting" | "connected" | "reconnecting" | "auth_failed";@@ -37,7 +38,7 @@ export interface CommandContext {sendMessage: (content: string,attachments?: FileAttachment[],- mode?: "agent.plan" | "agent.fast" | "code.plan" | "code.normal" | "code.team" | "team",+ mode?: ClientMode,options?: { logAsUser?: boolean },) => string | null;sessionId: string;@@ -51,8 +52,8 @@ export interface CommandContext {exitApp: () => void;isProcessing: boolean;connectionStatus: ConnectionStatus;- mode: "agent.plan" | "agent.fast" | "code.plan" | "code.normal" | "code.team" | "team";- setMode: (mode: "agent.plan" | "agent.fast" | "code.plan" | "code.normal" | "code.team" | "team") => void;+ mode: ClientMode;+ setMode: (mode: ClientMode) => void;setModel: (name: string) => void;setThemeName: (theme: ThemeName) => void;setAccentColor: (color: AccentColorName) => void;diff --git a/jiuwenclaw/channels/tui/frontend/src/core/event-handlers.ts b/jiuwenclaw/channels/tui/frontend/src/core/event-handlers.tsindex 9b7ec5a029..173b65b9ee 100644--- a/jiuwenclaw/channels/tui/frontend/src/core/event-handlers.ts+++ b/jiuwenclaw/channels/tui/frontend/src/core/event-handlers.ts@@ -21,6 +21,7 @@ import {} from "./types.js";import type { ConnectionStatus } from "./ws-client.js";import { createId, findLastIndex, isIgnorableHistoryRestoreError } from "./app-state-helpers.js";+import { isClientMode, type ClientMode } from "./modes.js";export interface PendingQuestion {requestId: string;@@ -49,8 +50,8 @@ export interface AppEventDelegate {getConnectionStatus(): ConnectionStatus;getSessionId(): string;setSessionId(sessionId: string): void;- setMode(mode: "agent.plan" | "agent.fast" | "code.plan" | "code.normal" | "code.team" | "team"): void;- getMode(): "agent.plan" | "agent.fast" | "code.plan" | "code.normal" | "code.team" | "team";+ setMode(mode: ClientMode): void;+ getMode(): ClientMode;getEntries(): HistoryItem[];setEntries(entries: HistoryItem[]): void;setStreamingState(state: StreamingState): void;@@ -140,7 +141,7 @@ function _handleSwitchModeToolResult(if (!subMode) return;const existingMode = delegate.getMode();- let newMode: string | null = null;+ let newMode: ClientMode | null = null;if (existingMode.startsWith("code.")) {newMode =subMode === "plan"@@ -153,7 +154,7 @@ function _handleSwitchModeToolResult(}if (newMode && newMode !== existingMode) {- delegate.setMode(newMode as "agent.plan" | "agent.fast" | "code.plan" | "code.normal" | "code.team" | "team");+ delegate.setMode(newMode);}}@@ -879,14 +880,8 @@ export function handleIncomingFrame(delegate: AppEventDelegate, frame: EventFramcase "session.updated": {const mode = typeof payload.mode === "string" ? payload.mode : "";- if (- mode === "agent.plan" ||- mode === "agent.fast" ||- mode === "code.plan" ||- mode === "code.normal" ||- mode === "team"- ) {- delegate.setMode(mode as "agent.plan" | "agent.fast" | "code.plan" | "code.normal" | "team");+ if (isClientMode(mode)) {+ delegate.setMode(mode);}if (typeof payload.title === "string") {delegate.setSessionTitle(payload.title);diff --git a/jiuwenclaw/channels/tui/frontend/src/core/modes.ts b/jiuwenclaw/channels/tui/frontend/src/core/modes.tsnew file mode 100644index 0000000000..ad344f9d4f--- /dev/null+++ b/jiuwenclaw/channels/tui/frontend/src/core/modes.ts@@ -0,0 +1,22 @@+export type ClientMode =+ | "agent.plan"+ | "agent.fast"+ | "code.plan"+ | "code.normal"+ | "code.team"+ | "team";++export function isClientMode(value: string): value is ClientMode {+ return (+ value === "agent.plan" ||+ value === "agent.fast" ||+ value === "code.plan" ||+ value === "code.normal" ||+ value === "code.team" ||+ value === "team"+ );+}++export function isTeamMode(mode: ClientMode): boolean {+ return mode === "team" || mode === "code.team";+}diff --git a/jiuwenclaw/channels/tui/frontend/src/ui/app-screen.ts b/jiuwenclaw/channels/tui/frontend/src/ui/app-screen.tsindex b4e60258ff..35105d8b4c 100644--- a/jiuwenclaw/channels/tui/frontend/src/ui/app-screen.ts+++ b/jiuwenclaw/channels/tui/frontend/src/ui/app-screen.ts@@ -35,6 +35,7 @@ import type { SessionListPayload, SessionMeta } from "../core/commands/builtins/import type { ConfigItemSchema } from "../core/commands/builtins/config.js";import type { McpListItem, McpListPayload } from "../core/commands/builtins/mcp.js";import { buildModeAutocompleteItems } from "../core/commands/builtins/mode.js";+import { isTeamMode } from "../core/modes.js";import { addTrustedDir, getTrustedDirs, isTrustedDir } from "../core/tui-trusted-dirs-store.js";import { handleAppScreenKeyInput } from "./keymap.js";import { buildAppScreenLines } from "./screen-layout.js";@@ -893,7 +894,7 @@ export class AppScreen implements Component, Focusable {render(width: number): string[] {const snapshot = this.state.getSnapshot();const teamWorking =- snapshot.mode === "team" &&+ isTeamMode(snapshot.mode) &&isTeamWorking(snapshot.teamMemberEvents, snapshot.teamMessageEvents);this.editor.borderColor = snapshot.pendingQuestion? palette.border.question@@ -2387,7 +2388,7 @@ export class AppScreen implements Component, Focusable {(execution) => execution.tool.status === "running",);const teamWorking =- snapshot.mode === "team" &&+ isTeamMode(snapshot.mode) &&isTeamWorking(snapshot.teamMemberEvents, snapshot.teamMessageEvents);const teamStartedAt = teamWorkingStartedAtMs(snapshot.teamMemberEvents,diff --git a/jiuwenclaw/channels/tui/frontend/src/ui/screen-layout.ts b/jiuwenclaw/channels/tui/frontend/src/ui/screen-layout.tsindex c32080803a..63a98ef172 100644--- a/jiuwenclaw/channels/tui/frontend/src/ui/screen-layout.ts+++ b/jiuwenclaw/channels/tui/frontend/src/ui/screen-layout.ts@@ -1,4 +1,5 @@import type { AppSnapshot } from "../app-state.js";+import { isTeamMode } from "../core/modes.js";import { renderMiniTeamTree, renderTeamPanel } from "./components/team-panel.js";import { isTeamWorking } from "./components/team-shared.js";import { renderTeamStatusPill } from "./components/team-status-pill.js";@@ -110,7 +111,7 @@ function buildStatusLines(if (snapshot.mode !== "agent.plan") left.push(`mode:${snapshot.mode}`);if (snapshot.transcriptFoldMode !== "none") left.push(`fold:${snapshot.transcriptFoldMode}`);const teamWorking =- snapshot.mode === "team" &&+ isTeamMode(snapshot.mode) &&isTeamWorking(snapshot.teamMemberEvents, snapshot.teamMessageEvents);const right = snapshot.lastError@@ -180,11 +181,13 @@ export function buildAppScreenLines(snapshot: AppSnapshot, options: ScreenLayoutoptions.pendingInputBaseline,);const todoLines = options.showTodos ? renderTodoList(snapshot.todos, options.width) : [];- const teamStatusLines =- snapshot.mode === "team" ||+ const hasTeamActivity =+ isTeamMode(snapshot.mode) ||snapshot.teamMemberEvents.length > 0 ||snapshot.teamTaskEvents.length > 0 ||- snapshot.teamMessageEvents.length > 0+ snapshot.teamMessageEvents.length > 0;+ const teamStatusLines =+ hasTeamActivity? renderTeamStatusPill(snapshot.teamMemberEvents,snapshot.teamTaskEvents,@@ -193,11 +196,7 @@ export function buildAppScreenLines(snapshot: AppSnapshot, options: ScreenLayout): [];const teamPanelLines =- options.showTeamPanel &&- (snapshot.mode === "team" ||- snapshot.teamMemberEvents.length > 0 ||- snapshot.teamTaskEvents.length > 0 ||- snapshot.teamMessageEvents.length > 0)+ options.showTeamPanel && hasTeamActivity? renderTeamPanel(snapshot.teamMemberEvents,snapshot.teamTaskEvents,@@ -208,11 +207,7 @@ export function buildAppScreenLines(snapshot: AppSnapshot, options: ScreenLayout): [];const miniTeamTreeLines =- !options.showTeamPanel &&- (snapshot.mode === "team" ||- snapshot.teamMemberEvents.length > 0 ||- snapshot.teamTaskEvents.length > 0 ||- snapshot.teamMessageEvents.length > 0)+ !options.showTeamPanel && hasTeamActivity? renderMiniTeamTree(snapshot.teamMemberEvents,snapshot.teamTaskEvents,diff --git a/jiuwenclaw/server/runtime/agent_adapter/interface.py b/jiuwenclaw/server/runtime/agent_adapter/interface.pyindex 0e7fae8352..59a00b1b00 100644--- a/jiuwenclaw/server/runtime/agent_adapter/interface.py+++ b/jiuwenclaw/server/runtime/agent_adapter/interface.py@@ -273,7 +273,7 @@ class JiuWenClaw:config_base: 可选的完整配置快照;传入时优先使用它而不是读取本地 config.yaml。env_overrides: 可选的环境变量增量;仅覆盖请求中出现的 key。"""- adapter = self._ensure_adapter(mode=self._adapter_mode_for_request(request))+ adapter = self._ensure_adapter()await adapter.reload_agent_config(config_base, env_overrides)logger.info("[JiuWenClaw] Agent config reloaded: sdk=%s", self._sdk_name)@@ -734,7 +734,7 @@ class JiuWenClaw:)return- adapter = self._ensure_adapter()+ adapter = self._ensure_adapter(mode=self._adapter_mode_for_request(request))session_id = self._session_manager.get_session_id(request.session_id)query = request.params.get("query", "")diff --git a/jiuwenclaw/server/runtime/agent_adapter/interface_code.py b/jiuwenclaw/server/runtime/agent_adapter/interface_code.pyindex 711a5ea587..a6597907f0 100644--- a/jiuwenclaw/server/runtime/agent_adapter/interface_code.py+++ b/jiuwenclaw/server/runtime/agent_adapter/interface_code.py@@ -202,13 +202,19 @@ class JiuwenClawCodeAdapter(JiuWenClawDeepAdapter):enable_task_planning=True,auto_create_workspace=False)+ setattr(self._instance, "_jiuwenclaw_adapter_mode", "code")+ setattr(+ self._instance,+ "_jiuwenclaw_code_project_dir",+ self._project_dir or self._workspace_dir,+ )_project_name = os.path.basename(self._project_dir) if self._project_dir else "default"- coding_memory_abs_path = os.path.join(self._agent_workspace_dir, "coding_memory", _project_name)+ coding_memory_workspace_path = os.path.join("coding_memory", _project_name)self._instance.deep_config.workspace.set_directory({"name": "coding_memory","description": "Coding Agent 记忆模块",- "path": coding_memory_abs_path,+ "path": coding_memory_workspace_path,"children": [{"name": "MEMORY.md",@@ -734,6 +740,9 @@ class JiuwenClawCodeAdapter(JiuWenClawDeepAdapter):# ─── Tools 构建 ──────────────────────────async def _get_tool_cards(self, agent_id: str) -> list[Any]:+ return self.build_code_tool_cards(agent_id)++ def build_code_tool_cards(self, agent_id: str) -> list[Any]:"""Get tool cards for code mode — from config.yaml::modes.code.tools."""tool_cards = []@@ -835,3 +844,271 @@ class JiuwenClawCodeAdapter(JiuWenClawDeepAdapter):except Exception as exc:logger.warning("[JiuwenClawCodeAdapter] skill_toolkit build failed: %s", exc)return None++ def merge_member_mcp_configs(self, agent: Any, config_base: dict[str, Any]) -> int:+ """Merge enabled code-mode MCP configs into a team member agent."""+ deep_config = getattr(agent, "deep_config", None)+ if deep_config is None:+ return 0++ configured_mcps = list(getattr(deep_config, "mcps", None) or [])+ configured_ids = {+ str(getattr(cfg, "server_id", "") or getattr(cfg, "server_name", "") or "")+ for cfg in configured_mcps+ }+ added = 0+ for entry in self._extract_enabled_mcp_server_entries(config_base):+ cfg = self._build_mcp_server_config(entry)+ if cfg is None:+ logger.warning(+ "[JiuwenClawCodeAdapter] skip invalid member mcp server entry: %s",+ entry.get("name", "<unknown>"),+ )+ continue+ server_id = str(getattr(cfg, "server_id", "") or getattr(cfg, "server_name", "") or "")+ if not server_id or server_id in configured_ids:+ continue+ configured_mcps.append(cfg)+ configured_ids.add(server_id)+ added += 1+ deep_config.mcps = configured_mcps+ return added++ def configure_team_member_agent(+ self,+ agent: Any,+ *,+ parent_agent: Any | None = None,+ skill_manager: Any | None = None,+ member_name: str | None = None,+ role: str | None = None,+ session_id: str | None = None,+ channel_id: str | None = None,+ project_dir: str | None = None,+ ) -> None:+ """Apply the code runtime profile to a team member DeepAgent."""+ if skill_manager is not None and hasattr(self, "set_skill_manager"):+ self.set_skill_manager(skill_manager)++ config_base = get_config()+ self._refresh_multimodal_configs(config_base)+ react_config = (config_base.get("react") or {}).copy()+ self._config_cache = react_config.copy()+ self._instance = agent++ card = getattr(agent, "card", None)+ agent_id = str(getattr(card, "id", "") or member_name or "team_member")+ self._agent_name = str(getattr(card, "name", "") or member_name or role or "team_member")++ parent_project_dir = (+ project_dir+ or str(getattr(parent_agent, "_jiuwenclaw_code_project_dir", "") or "")+ or _resolve_member_workspace_root(parent_agent)+ )+ member_workspace_root = _resolve_member_workspace_root(agent)+ self._project_dir = parent_project_dir or member_workspace_root or react_config.get("project_dir")+ self._workspace_dir = (+ self._project_dir+ or member_workspace_root+ or react_config.get("workspace_dir")+ or str(get_agent_workspace_dir())+ )+ self._agent_workspace_dir = member_workspace_root or str(get_agent_workspace_dir())+ self._instance_overrides = {+ "agent_name": self._agent_name,+ "project_dir": self._project_dir,+ "channel_id": channel_id,+ }++ model = self._create_model(config_base)+ deep_config = getattr(agent, "deep_config", None)+ if deep_config is not None and getattr(deep_config, "model", None) is None:+ deep_config.model = model+ if deep_config is not None and getattr(deep_config, "sys_operation", None) is None:+ deep_config.sys_operation = self._create_sys_operation()++ tool_cards = self.build_code_tool_cards(agent_id)+ added_tools = _merge_tool_cards(agent, tool_cards)++ rails = self._build_agent_rails(react_config, config_base, mode="code")+ added_rails = sum(1 for rail in rails if _queue_rail_if_missing(agent, rail))++ subagents, _should_add_general = self._build_configured_subagents(model, react_config, config_base)+ added_subagents = _merge_subagents(agent, subagents)+ added_mcps = self.merge_member_mcp_configs(agent, config_base)+ if getattr(deep_config, "subagents", None):+ subagent_rail = self._build_subagent_rail()+ if _queue_rail_if_missing(agent, subagent_rail):+ added_rails += 1++ _set_coding_memory_directory(agent, self._project_dir)+ setattr(agent, "_jiuwenclaw_adapter_mode", "code")+ setattr(agent, "_jiuwenclaw_code_project_dir", self._project_dir or self._workspace_dir)+ setattr(agent, "_jiuwenclaw_code_team_member", True)++ logger.info(+ "[JiuwenClawCodeAdapter] configured team member as code profile: "+ "member=%s role=%s session=%s channel=%s tools=%d rails=%d subagents=%d mcps=%d project_dir=%s",+ member_name,+ role,+ session_id,+ channel_id,+ added_tools,+ added_rails,+ added_subagents,+ added_mcps,+ self._project_dir,+ )+++def _tool_card_identity(card: Any) -> tuple[str, str]:+ return (+ str(getattr(card, "id", "") or ""),+ str(getattr(card, "name", "") or ""),+ )+++def _subagent_name(spec: Any) -> str:+ if isinstance(spec, SubAgentConfig):+ return str(getattr(spec.agent_card, "name", "") or "")+ card = getattr(spec, "card", None)+ return str(getattr(card, "name", "") or "")+++def _iter_agent_rails(agent: Any) -> list[Any]:+ rails: list[Any] = []+ for attr_name in ("_pending_rails", "_registered_rails"):+ value = getattr(agent, attr_name, None)+ if isinstance(value, list):+ rails.extend(value)+ return rails+++def _agent_has_rail_type(agent: Any, rail: Any) -> bool:+ return any(isinstance(existing, type(rail)) for existing in _iter_agent_rails(agent))+++def _queue_rail_if_missing(agent: Any, rail: Any) -> bool:+ add_rail = getattr(agent, "add_rail", None)+ if rail is None or not callable(add_rail) or _agent_has_rail_type(agent, rail):+ return False+ add_rail(rail)+ return True+++def _merge_tool_cards(agent: Any, tool_cards: list[Any]) -> int:+ ability_manager = getattr(agent, "ability_manager", None)+ add_ability = getattr(ability_manager, "add", None)+ list_abilities = getattr(ability_manager, "list", None)++ existing_keys: set[tuple[str, str]] = set()+ if callable(list_abilities):+ existing_keys = {+ _tool_card_identity(card)+ for card in (list_abilities() or [])+ }++ added = 0+ for card in tool_cards:+ key = _tool_card_identity(card)+ if key in existing_keys:+ continue+ if callable(add_ability):+ add_ability(card)+ existing_keys.add(key)+ added += 1++ deep_config = getattr(agent, "deep_config", None)+ if deep_config is not None:+ configured_tools = list(getattr(deep_config, "tools", None) or [])+ configured_keys = {_tool_card_identity(card) for card in configured_tools}+ for card in tool_cards:+ key = _tool_card_identity(card)+ if key not in configured_keys:+ configured_tools.append(card)+ configured_keys.add(key)+ deep_config.tools = configured_tools+ return added+++def _merge_subagents(agent: Any, subagents: list[Any] | None) -> int:+ if not subagents:+ return 0++ deep_config = getattr(agent, "deep_config", None)+ if deep_config is None:+ return 0++ configured_subagents = list(getattr(deep_config, "subagents", None) or [])+ configured_names = {_subagent_name(spec) for spec in configured_subagents}+ added = 0+ for spec in subagents:+ name = _subagent_name(spec)+ if not name or name in configured_names:+ continue+ configured_subagents.append(spec)+ configured_names.add(name)+ added += 1+ deep_config.subagents = configured_subagents+ return added+++def _resolve_member_workspace_root(agent: Any) -> str | None:+ deep_config = getattr(agent, "deep_config", None)+ workspace = getattr(deep_config, "workspace", None)+ root_path = getattr(workspace, "root_path", None)+ if root_path:+ return str(root_path)+ return None+++def _set_coding_memory_directory(agent: Any, project_dir: str | None) -> None:+ deep_config = getattr(agent, "deep_config", None)+ workspace = getattr(deep_config, "workspace", None)+ set_directory = getattr(workspace, "set_directory", None)+ if not callable(set_directory):+ return++ project_name = os.path.basename(project_dir) if project_dir else "default"+ coding_memory_workspace_path = os.path.join("coding_memory", project_name)+ set_directory({+ "name": "coding_memory",+ "description": "Coding Agent memory",+ "path": coding_memory_workspace_path,+ "children": [+ {+ "name": "MEMORY.md",+ "description": "Coding memory",+ "path": "MEMORY.md",+ "children": [],+ "is_file": True,+ "default_content": "",+ },+ ],+ })+++def configure_code_team_member_agent(+ agent: Any,+ *,+ parent_agent: Any | None = None,+ skill_manager: Any | None = None,+ member_name: str | None = None,+ role: str | None = None,+ session_id: str | None = None,+ channel_id: str | None = None,+ project_dir: str | None = None,+) -> None:+ """Apply JiuwenClawCodeAdapter's runtime profile to a team member DeepAgent."""++ adapter = JiuwenClawCodeAdapter()+ adapter.configure_team_member_agent(+ agent,+ parent_agent=parent_agent,+ skill_manager=skill_manager,+ member_name=member_name,+ role=role,+ session_id=session_id,+ channel_id=channel_id,+ project_dir=project_dir,+ )diff --git a/tests/unit_tests/agentserver/test_team_manager_skill_state.py b/tests/unit_tests/agentserver/test_team_manager_skill_state.pyindex ca1cd958f7..1aa4cf336a 100644--- a/tests/unit_tests/agentserver/test_team_manager_skill_state.py+++ b/tests/unit_tests/agentserver/test_team_manager_skill_state.py@@ -4,6 +4,7 @@import jsonfrom pathlib import Path+from types import SimpleNamespacefrom openjiuwen.agent_teams.schema.blueprint import TeamAgentSpec@@ -116,3 +117,204 @@ def test_member_skill_state_inherits_marketplaces_and_rebuilds_installed_skills(assert [plugin["name"] for plugin in state["installed_plugins"]] == ["skill-a"]assert [skill["name"] for skill in state["local_skills"]] == ["skill-a"]assert Path(state["local_skills"][0]["origin"]).name == "skill-a"+++def test_code_team_customizer_applies_code_profile_to_member(monkeypatch, tmp_path):+ """code.team parent agents should make each team member use the code profile."""+ global_skills_dir = tmp_path / "global_skills"+ global_skills_dir.mkdir(parents=True)+ (global_skills_dir / "skills_state.json").write_text(+ json.dumps({"marketplaces": [], "installed_plugins": [], "local_skills": []}),+ encoding="utf-8",+ )+ monkeypatch.setattr(+ "jiuwenclaw.agents.harness.team.team_manager.get_agent_skills_dir",+ lambda: global_skills_dir,+ )+ monkeypatch.setattr(+ "jiuwenclaw.agents.harness.team.team_manager.build_member_rails",+ lambda **kwargs: [],+ )+ monkeypatch.setattr(+ "jiuwenclaw.agents.harness.common.plugins.rail_manager.get_rail_manager",+ lambda: type(+ "_DummyRailManager",+ (),+ {+ "get_registered_rail_names": lambda self: [],+ "load_rail_instance_without_enabled_check": lambda self, name: None,+ },+ )(),+ )++ calls = []++ def fake_configure_code_member(agent, **kwargs):+ calls.append({"agent": agent, **kwargs})++ monkeypatch.setattr(+ "jiuwenclaw.server.runtime.agent_adapter.interface_code.configure_code_team_member_agent",+ fake_configure_code_member,+ )++ spec = TeamAgentSpec.model_validate(+ {+ "team_name": "demo_team",+ "agents": {+ "leader": {},+ "member_a": {},+ },+ }+ )+ parent_project = tmp_path / "project"+ parent_project.mkdir()+ parent_agent = SimpleNamespace(+ _jiuwenclaw_adapter_mode="code",+ _jiuwenclaw_code_project_dir=str(parent_project),+ deep_config=SimpleNamespace(+ workspace=SimpleNamespace(root_path=str(parent_project)),+ sys_operation=None,+ ),+ ability_manager=SimpleNamespace(list=lambda: []),+ )+ customizer = TeamManager.build_agent_customizer(+ spec=spec,+ deep_agent=parent_agent,+ session_id="session-1",+ request_id="request-1",+ channel_id="tui",+ request_metadata={"source": "test"},+ )++ class AbilityManager:+ def __init__(self):+ self.cards = []++ def list(self):+ return list(self.cards)++ def add(self, card):+ self.cards.append(card)++ class Agent:+ def __init__(self):+ self.deep_config = SimpleNamespace(+ workspace=SimpleNamespace(root_path=str(tmp_path / "member_workspace")),+ sys_operation=None,+ )+ self.ability_manager = AbilityManager()+ self.card = SimpleNamespace(id="member_a", name="member")+ self.rails = []++ def add_rail(self, rail):+ self.rails.append(rail)++ agent = Agent()++ customizer(agent, member_name="member_a", role="teammate")++ assert len(calls) == 1+ assert calls[0]["agent"] is agent+ assert calls[0]["parent_agent"] is parent_agent+ assert calls[0]["member_name"] == "member_a"+ assert calls[0]["role"] == "teammate"+ assert calls[0]["session_id"] == "session-1"+ assert calls[0]["channel_id"] == "tui"+ assert calls[0]["project_dir"] == str(parent_project)+ assert calls[0]["skill_manager"] is not None+++def test_configure_code_team_member_uses_relative_coding_memory_path(monkeypatch, tmp_path):+ """code.team members should register workspace directories with relative paths."""+ from jiuwenclaw.server.runtime.agent_adapter import interface_code++ global_workspace = tmp_path / "global_agent_workspace"+ member_workspace = tmp_path / "member_workspace"+ parent_project = tmp_path / "project"+ global_workspace.mkdir()+ member_workspace.mkdir()+ parent_project.mkdir()++ monkeypatch.setattr(interface_code, "get_config", lambda: {"react": {}})+ monkeypatch.setattr(interface_code, "get_agent_workspace_dir", lambda: global_workspace)+ monkeypatch.setattr(+ interface_code.JiuwenClawCodeAdapter,+ "_refresh_multimodal_configs",+ lambda self, config: None,+ )+ monkeypatch.setattr(+ interface_code.JiuwenClawCodeAdapter,+ "_create_model",+ lambda self, config: object(),+ )+ monkeypatch.setattr(+ interface_code.JiuwenClawCodeAdapter,+ "_create_sys_operation",+ lambda self: object(),+ )+ monkeypatch.setattr(+ interface_code.JiuwenClawCodeAdapter,+ "build_code_tool_cards",+ lambda self, agent_id: [],+ )+ monkeypatch.setattr(+ interface_code.JiuwenClawCodeAdapter,+ "_build_agent_rails",+ lambda self, react_config, config_base, mode: [],+ )+ monkeypatch.setattr(+ interface_code.JiuwenClawCodeAdapter,+ "_build_configured_subagents",+ lambda self, model, react_config, config_base: ([], False),+ )+ monkeypatch.setattr(+ interface_code.JiuwenClawCodeAdapter,+ "_extract_enabled_mcp_server_entries",+ lambda self, config_base: [],+ )++ class Workspace:+ def __init__(self, root_path):+ self.root_path = str(root_path)+ self.directories = []++ def set_directory(self, directory):+ self.directories.append(directory)++ class AbilityManager:+ @staticmethod+ def list():+ return []++ @staticmethod+ def add(card):+ raise AssertionError("no tool cards should be added in this test")++ workspace = Workspace(member_workspace)+ agent = SimpleNamespace(+ card=SimpleNamespace(id="counter-1", name="Counter 1"),+ deep_config=SimpleNamespace(+ workspace=workspace,+ model=None,+ sys_operation=None,+ subagents=[],+ mcps=[],+ ),+ ability_manager=AbilityManager(),+ add_rail=lambda rail: None,+ )+ parent_agent = SimpleNamespace(+ _jiuwenclaw_code_project_dir=str(parent_project),+ deep_config=SimpleNamespace(workspace=SimpleNamespace(root_path=str(parent_project))),+ )++ interface_code.configure_code_team_member_agent(+ agent,+ parent_agent=parent_agent,+ member_name="counter-1",+ role="counter",+ )++ coding_memory_path = Path(workspace.directories[0]["path"])+ assert not coding_memory_path.is_absolute()+ assert coding_memory_path.parts == ("coding_memory", parent_project.name)