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(cli):新增/model命令,支持模型查看、新增、切换
openJiuwen-bot9f272e32e38a
diff --git a/jiuwenclaw/agentserver/agent_ws_server.py b/jiuwenclaw/agentserver/agent_ws_server.pyindex 144a24898f..4c2bfee3b5 100644--- a/jiuwenclaw/agentserver/agent_ws_server.py+++ b/jiuwenclaw/agentserver/agent_ws_server.py@@ -8,6 +8,7 @@ import loggingimport asyncioimport jsonimport math+import osfrom pathlib import Pathfrom typing import Any, ClassVar@@ -775,19 +776,73 @@ class AgentWebSocketServer:async def _handle_command_model(self, ws: Any, request: AgentRequest, send_lock: asyncio.Lock) -> None:try:params = request.params or {}- requested = params.get("model")- current = requested if isinstance(requested, str) and requested.strip() else "default-model"- resp = AgentResponse(- request_id=request.request_id,- channel_id=request.channel_id,- ok=True,- payload={- "current": current,- "requested": requested if isinstance(requested, str) and requested.strip() else None,- "applied": bool(isinstance(requested, str) and requested.strip()),- "available": ["default-model", "planner-model", "coder-model"],- },- )+ action = params.get("action")++ if action == "add_model":+ target = str(params.get("target", "")).strip()+ logger.info("[command.model] add_model: target=%s", target)+ resp = AgentResponse(+ request_id=request.request_id,+ channel_id=request.channel_id,+ ok=True,+ payload={"type": "model_added", "name": target},+ )++ elif action == "switch_model":+ target = str(params.get("model", "")).strip()+ env_updates = params.get("env_updates", {})+ logger.info(+ "[command.model] switch_model: target=%s, env_updates=%s",+ target,+ {k: (v if k != "API_KEY" else "***") for k, v in env_updates.items()},+ )++ if not env_updates:+ resp = AgentResponse(+ request_id=request.request_id,+ channel_id=request.channel_id,+ ok=False,+ payload={"error": "No env_updates provided"},+ )+ else:+ for k, v in env_updates.items():+ os.environ[k] = v+ logger.info("[command.model] os.environ 已更新, MODEL_NAME=%s", os.getenv("MODEL_NAME", "unknown"))++ try:+ from jiuwenclaw.agentserver.memory.config import clear_config_cache+ clear_config_cache()+ logger.info("[command.model] config cache 已清除")+ except Exception as e:+ logger.debug("[command.model] clear_config_cache skipped: %s", e)++ try:+ await self._agent_manager.reload_agents_config(None, env_updates)+ logger.info("[command.model] agent config 已重载")+ except Exception as e:+ logger.debug("[command.model] reload_agents_config skipped: %s", e)++ resp = AgentResponse(+ request_id=request.request_id,+ channel_id=request.channel_id,+ ok=True,+ payload={+ "current": os.getenv("MODEL_NAME", "unknown"),+ "requested": target,+ "type": "switched",+ "applied": True,+ },+ )+ logger.info("[command.model] 切换完成: current=%s", os.getenv("MODEL_NAME", "unknown"))++ else:+ resp = AgentResponse(+ request_id=request.request_id,+ channel_id=request.channel_id,+ ok=True,+ payload={"current": os.getenv("MODEL_NAME", "unknown"), "available": ["default-model"]},+ )+except Exception as e: # noqa: BLE001logger.exception("[AgentWebSocketServer] command.model failed: %s", e)resp = AgentResponse(diff --git a/jiuwenclaw/channel/cli_channel.py b/jiuwenclaw/channel/cli_channel.pyindex 1592c77427..83e853b632 100644--- a/jiuwenclaw/channel/cli_channel.py+++ b/jiuwenclaw/channel/cli_channel.py@@ -16,6 +16,9 @@ from jiuwenclaw.config import (get_config_raw,update_context_engine_enabled_in_config,update_permissions_enabled_in_config,+ get_model_names,+ get_model_config,+ add_or_update_model_in_config,)from jiuwenclaw.gateway.route_binding import GatewayRouteBindingfrom jiuwenclaw.version import __version__@@ -30,7 +33,6 @@ CLI_FORWARD_REQ_METHODS = frozenset("command.chrome","command.compact","command.diff",- "command.model","command.resume","command.session","chat.send",@@ -73,7 +75,6 @@ CLI_FORWARD_NO_LOCAL_HANDLER_METHODS = frozenset("command.chrome","command.compact","command.diff",- "command.model","command.resume","command.session","browser.start",@@ -210,6 +211,29 @@ def _persist_env_updates(updates: dict[str, str]) -> None:logger.warning("[cli config.set] 写回 .env 失败: %s", e)+def _load_env_from_file() -> dict[str, str]:+ """从 .env 文件读取环境变量值(不从当前 os.environ 读取)。"""+ from jiuwenclaw.utils import get_env_file++ env_path = get_env_file()+ result = {}+ if not env_path.is_file():+ return result+ try:+ with open(env_path, "r", encoding="utf-8") as f:+ for line in f:+ stripped = line.strip()+ if not stripped or stripped.startswith("#"):+ continue+ if "=" in stripped:+ key, _, val = stripped.partition("=")+ val = val.strip('"').strip("'")+ result[key] = val+ except OSError:+ pass+ return result++def register_cli_handlers(bind: CliHandlersBindParams) -> None:channel = bind.channelagent_client = bind.agent_client@@ -460,6 +484,306 @@ def register_cli_handlers(bind: CliHandlersBindParams) -> None:payload["page_idx"] = params.get("page_idx")await channel.send_response(ws, req_id, ok=True, payload=payload)+ async def _command_model(ws, req_id, params, session_id):+ import time+ from jiuwenclaw.e2a.gateway_normalize import e2a_from_agent_fields+ from jiuwenclaw.schema.message import ReqMethod++ if not isinstance(params, dict):+ params = {}+ action = params.get("action")+ model_name = params.get("model")++ real_client = (+ agent_client.get("value")+ if isinstance(agent_client, dict)+ else agent_client+ )+ if real_client is None:+ await channel.send_response(+ ws, req_id, ok=False, error="agent client not available"+ )+ return++ if action == "add_model":+ target = str(params.get("target", "")).strip()+ configs = params.get("config", {})+ if not target:+ await channel.send_response(+ ws, req_id, ok=False, error="Target model name (target) is required"+ )+ return+ client_cfg = {}+ key_map = {+ "model": "model_name",+ "provider": "client_provider",+ "api_key": "api_key",+ "api_base": "api_base",+ "url": "api_base",+ "base_url": "api_base",+ "timeout": "timeout",+ "verify_ssl": "verify_ssl",+ "ssl_cert": "ssl_cert",+ }+ for k, v in configs.items():+ mapped_k = key_map.get(k.lower(), k)+ client_cfg[mapped_k] = v+ if "verify_ssl" not in client_cfg:+ client_cfg["verify_ssl"] = False+ if "timeout" not in client_cfg:+ client_cfg["timeout"] = 1800+ model_cfg_obj = configs.get("model_config_obj", {})+ if not model_cfg_obj:+ model_cfg_obj = {"temperature": 0.95}+ try:+ add_or_update_model_in_config(+ target,+ {+ "model_client_config": client_cfg,+ "model_config_obj": model_cfg_obj,+ },+ )+ logger.info(+ "[cli command.model] 新增模型: name=%s, client_cfg=%s, model_config_obj=%s",+ target,+ client_cfg,+ model_cfg_obj,+ )+ except Exception as e:+ await channel.send_response(ws, req_id, ok=False, error=str(e))+ return+ env = e2a_from_agent_fields(+ request_id=req_id,+ channel_id="cli",+ session_id=session_id,+ req_method=ReqMethod.COMMAND_MODEL,+ params={"action": "add_model", "target": target, "config": configs},+ is_stream=False,+ timestamp=time.time(),+ )+ resp = await real_client.send_request(env)+ await channel.send_response(+ ws,+ req_id,+ ok=resp.ok,+ payload=resp.payload if resp.ok else None,+ error=resp.error if not resp.ok else None,+ )+ return++ if not model_name or not str(model_name).strip():+ names = get_model_names()+ logger.info(+ "[cli command.model] 列出模型: names=%s, current=%s",+ names,+ os.getenv("MODEL_NAME", "unknown"),+ )+ env = e2a_from_agent_fields(+ request_id=req_id,+ channel_id="cli",+ session_id=session_id,+ req_method=ReqMethod.COMMAND_MODEL,+ params={},+ is_stream=False,+ timestamp=time.time(),+ )+ resp = await real_client.send_request(env)+ payload = resp.payload if resp.ok else {}+ payload["available_models"] = names+ payload["current"] = os.getenv("MODEL_NAME", "unknown")+ await channel.send_response(ws, req_id, ok=True, payload=payload)+ return++ target = str(model_name).strip()+ logger.info("[cli command.model] 切换模型: target=%s", target)+ if target not in get_model_names():+ logger.warning(+ "[cli command.model] 模型不存在: %s, 可用: %s",+ target,+ get_model_names(),+ )+ await channel.send_response(+ ws,+ req_id,+ ok=False,+ error=f"Model '{target}' not found. Available: {', '.join(get_model_names())}",+ )+ return++ env_from_file = _load_env_from_file()+ raw_model_cfg = get_model_config(target)+ logger.info("[cli command.model] 模型 '%s' 原始配置: %s", target, raw_model_cfg)+ if not raw_model_cfg:+ await channel.send_response(+ ws, req_id, ok=False, error=f"Model '{target}' config not found"+ )+ return+ raw_client_cfg = raw_model_cfg.get("model_client_config", {})+ raw_model_config_obj = raw_model_cfg.get("model_config_obj", {})+ if not raw_client_cfg:+ await channel.send_response(+ ws,+ req_id,+ ok=False,+ error=f"Model '{target}' has no model_client_config",+ )+ return++ import re as _re++ pattern = _re.compile(r"\$\{([^:}]+)(?::-([^}]*))?\}")+ resolved_cfg = {}+ unresolved_env_vars = {}+ for key, raw_val in raw_client_cfg.items():+ if not isinstance(raw_val, str):+ resolved_cfg[key] = raw_val+ continue++ def _replace(match):+ var_name = match.group(1)+ default = match.group(2)+ if var_name in env_from_file:+ return env_from_file[var_name]+ if default is not None:+ return default+ unresolved_env_vars[var_name] = True+ return ""++ resolved_cfg[key] = pattern.sub(_replace, raw_val)++ logger.info("[cli command.model] 解析后的配置: %s", resolved_cfg)++ required_keys = {+ "api_base": "API_BASE",+ "api_key": "API_KEY",+ "model_name": "MODEL_NAME",+ "client_provider": "MODEL_PROVIDER",+ }+ missing = []+ for yaml_key, env_key in required_keys.items():+ val = resolved_cfg.get(yaml_key, "")+ if not val:+ is_env_ref = (+ yaml_key in raw_client_cfg+ and isinstance(raw_client_cfg[yaml_key], str)+ and raw_client_cfg[yaml_key].startswith("${")+ )+ if is_env_ref:+ env_var_in_raw = raw_client_cfg[yaml_key]+ var_names_in_val = _re.findall(+ r"\$\{([^:}]+)(?::-([^}]*))?\}", env_var_in_raw+ )+ for vn, vd in var_names_in_val:+ env_file_val = env_from_file.get(vn, "")+ if not env_file_val and (vd is None or vd == ""):+ missing.append(f"{yaml_key} (env var {vn} not set)")+ else:+ missing.append(yaml_key)+ if missing:+ logger.error("[cli command.model] 必要配置缺失: %s, 无法切换", missing)+ await channel.send_response(+ ws,+ req_id,+ ok=False,+ error=(+ f"Model '{target}' missing required config: {', '.join(missing)}. "+ "Please set the corresponding environment variables."+ ),+ )+ return++ switch_env_map = {+ "model_name": "MODEL_NAME",+ "client_provider": "MODEL_PROVIDER",+ "api_key": "API_KEY",+ "api_base": "API_BASE",+ }+ env_updates = {}+ for yaml_key, env_key in switch_env_map.items():+ if yaml_key in resolved_cfg and resolved_cfg[yaml_key]:+ env_updates[env_key] = str(resolved_cfg[yaml_key])+ if not env_updates:+ await channel.send_response(ws, req_id, ok=False, error="No valid config to switch")+ return++ logger.info(+ "[cli command.model] 写入环境变量: %s",+ {k: (v if k != "API_KEY" else "***") for k, v in env_updates.items()},+ )++ env = e2a_from_agent_fields(+ request_id=req_id,+ channel_id="cli",+ session_id=session_id,+ req_method=ReqMethod.COMMAND_MODEL,+ params={+ "action": "switch_model",+ "model": target,+ "env_updates": env_updates,+ },+ is_stream=False,+ timestamp=time.time(),+ )+ resp = await real_client.send_request(env)++ if resp.ok:+ for k, v in env_updates.items():+ os.environ[k] = v+ _persist_env_updates(env_updates)+ try:+ config_templates = {+ "api_base": "${API_BASE}",+ "api_key": "${API_KEY}",+ "model_name": "${MODEL_NAME}",+ "client_provider": "${MODEL_PROVIDER}",+ }+ config_templates["verify_ssl"] = resolved_cfg.get("verify_ssl", False)+ if "timeout" in resolved_cfg:+ config_templates["timeout"] = resolved_cfg["timeout"]+ add_or_update_model_in_config(+ "default",+ {"model_client_config": config_templates, "model_config_obj": raw_model_config_obj},+ )+ logger.info("[cli command.model] 已重置 models.default 为环境变量引用")+ except Exception as e:+ logger.warning("[cli command.model] 更新 config.yaml 失败: %s", e)+ if on_config_saved:+ config_payload = get_config()+ try:+ callback_result = on_config_saved(+ set(env_updates.keys()),+ env_updates=dict(env_updates),+ config_payload=config_payload,+ )+ if inspect.isawaitable(callback_result):+ await callback_result+ except Exception as e:+ logger.warning("[cli model.switch] on_config_saved failed: %s", e)+ logger.info(+ "[cli command.model] 切换完成: current=%s, requested=%s",+ env_updates.get("MODEL_NAME", target),+ target,+ )+ await channel.send_response(+ ws,+ req_id,+ ok=True,+ payload={+ "current": env_updates.get("MODEL_NAME", target),+ "requested": target,+ "type": "switched",+ "applied": True,+ },+ )+ else:+ logger.error("[cli command.model] agentserver 切换失败: %s", resp.error)+ await channel.send_response(+ ws,+ req_id,+ ok=False,+ error=resp.error or "Model switch failed on agent server",+ )+channel.register_local_handler(path, "config.get", _config_get)channel.register_local_handler(path, "config.set", _config_set)channel.register_local_handler(path, "session.list", _session_list)@@ -470,6 +794,7 @@ def register_cli_handlers(bind: CliHandlersBindParams) -> None:channel.register_local_handler(path, "chat.interrupt", _chat_interrupt)channel.register_local_handler(path, "chat.user_answer", _chat_user_answer)channel.register_local_handler(path, "history.get", _history_get)+ channel.register_local_handler(path, "command.model", _command_model)def build_cli_route_binding(bind: CliRouteBindParams) -> GatewayRouteBinding:diff --git a/jiuwenclaw/cli/src/core/commands/builtins/model.ts b/jiuwenclaw/cli/src/core/commands/builtins/model.tsindex b7fb8770aa..d757f3f44b 100644--- a/jiuwenclaw/cli/src/core/commands/builtins/model.ts+++ b/jiuwenclaw/cli/src/core/commands/builtins/model.ts@@ -1,42 +1,136 @@import { addError, addInfo } from "../helpers.js";import { CommandKind, type SlashCommand } from "../types.js";+export interface ModelMeta {+ name: string;+ model_name?: string;+ client_provider?: string;+ api_base?: string;+}++export interface ModelListPayload {+ current?: string;+ available_models?: string[];+ models?: ModelMeta[];+}+export function createModelCommand(): SlashCommand {return {name: "model",- description: "Set the active AI model",- usage: "/model [model]",- example: "/model sonnet",+ description: "View, add, or switch AI models defined in config.yaml",+ usage: "/model [name] | /model add <name> <key=value>...",+ example: "/model work (switch)\n/model add work model=gpt-4 api_key=xxx",kind: CommandKind.BUILT_IN,takesArgs: true,action: async (ctx, args) => {- const value = args.trim();+ const raw = args.trim();++ // 1. Handle Add Model: /model add <name> <key=value> ...+ if (raw.match(/^add\s+\S+/)) {+ const parts = raw.split(/\s+/);+ if (parts.length < 3) {+ ctx.addItem(+ addInfo(+ ctx.sessionId,+ "Usage: /model add <name> key=value ...",+ "m",+ ),+ );+ return;+ }++ const target = parts[1];+ const settings: Record<string, string> = {};+ for (let i = 2; i < parts.length; i++) {+ const eqIdx = parts[i].indexOf("=");+ if (eqIdx > 0) {+ const key = parts[i].substring(0, eqIdx);+ const val = parts[i].substring(eqIdx + 1);+ settings[key] = val;+ }+ }++ try {+ await ctx.request("command.model", {+ action: "add_model",+ target: target,+ config: settings,+ });+ ctx.addItem(+ addInfo(ctx.sessionId, `Added/Updated model config: ${target}`, "m", {+ view: "kv",+ items: Object.entries(settings).map(([k, v]) => ({+ label: k,+ value: k.toLowerCase().includes("key") || k.toLowerCase().includes("token") ? "****" : v,+ })),+ }),+ );+ } catch (error) {+ const message = error instanceof Error ? error.message : String(error);+ ctx.addItem(addError(ctx.sessionId, `Failed to add model: ${message}`));+ }+ return;+ }++ // 2. Handle View and Switch+ const value = raw;try {+ // If no arg or "list", show selectable model list+ if (value === "" || value === "list") {+ const payload = await ctx.request<ModelListPayload>("command.model", {});+ const models = payload.available_models ?? [];+ const current = payload.current ?? "unknown";+ if (models.length === 0) {+ ctx.addItem(addInfo(ctx.sessionId, "No models configured", "m"));+ return;+ }+ const items = models.map((m, i) => {+ const isCurrent = m === current;+ return {+ label: String(i + 1),+ value: `${m}${isCurrent ? " (current)" : ""}`,+ };+ });+ ctx.addItem(+ addInfo(ctx.sessionId, `Available models (${models.length} total)`, "m", {+ view: "list",+ title: "Switch Model",+ items,+ }),+ );+ return;+ }++ // Switch to specific modelconst payload = await ctx.request<{current?: string;requested?: string;applied?: boolean;- available?: string[];- }>("command.model", value ? { model: value } : {});+ type?: string;+ }>("command.model", { model: value });++ const isSwitch = !!payload.requested;+ const title = isSwitch+ ? `Switched to: ${payload.requested}`+ : "Model Configuration";+ const icon = isSwitch ? "m" : "c";+ctx.addItem(addInfo(ctx.sessionId,payload.requested- ? `Requested model: ${payload.requested}`+ ? `Switched model config to: ${payload.requested}`: `Current model: ${payload.current ?? "unknown"}`,- "m",+ icon,{view: "kv",- title: "Model",+ title,items: [{ label: "current", value: payload.current ?? "unknown" },- ...(payload.requested ? [{ label: "requested", value: payload.requested }] : []),+ ...(payload.type ? [{ label: "type", value: payload.type }] : []),...(typeof payload.applied === "boolean"? [{ label: "applied", value: String(payload.applied) }]: []),- ...(payload.available?.length- ? [{ label: "available", value: payload.available.join(", ") }]- : []),],},),diff --git a/jiuwenclaw/cli/src/ui/app-screen.ts b/jiuwenclaw/cli/src/ui/app-screen.tsindex 093cad0e84..ec7f28ca39 100644--- a/jiuwenclaw/cli/src/ui/app-screen.ts+++ b/jiuwenclaw/cli/src/ui/app-screen.ts@@ -17,6 +17,7 @@ import type { CliPiAppState } from "../app-state.js";import { CommandService, parseSlashCommand } from "../core/commands/CommandService.js";import { addError, addInfo } from "../core/commands/helpers.js";import type { SessionListPayload, SessionMeta } from "../core/commands/builtins/resume.js";+import type { ModelListPayload } from "../core/commands/builtins/model.js";import { handleAppScreenKeyInput } from "./keymap.js";import { buildAppScreenLines } from "./screen-layout.js";import {@@ -55,6 +56,12 @@ type ResumeSessionListState = {total: number;};+type ModelListState = {+ list: SelectList;+ models: string[];+ current: string;+};+const IMAGE_MIME_TYPES: Record<string, string> = {".png": "image/png",".jpg": "image/jpeg",@@ -449,6 +456,7 @@ export class AppScreen implements Component, Focusable {private pendingQuestionAnswers = new Map<number, string>();private questionList: SelectList | null = null;private resumeSessionList: ResumeSessionListState | null = null;+ private modelList: ModelListState | null = null;private showTodos = true;private showTeamPanel = false;private selectedTeamMemberId: string | null = null;@@ -608,6 +616,12 @@ export class AppScreen implements Component, Focusable {return;}+ if (!snapshot.pendingQuestion && this.modelList !== null) {+ this.modelList.list.handleInput(data);+ this.tui.requestRender();+ return;+ }+if (!snapshot.pendingQuestion && this.showTeamPanel) {if (matchesKey(data, "left")) {this.viewedTeamMemberId = null;@@ -673,6 +687,7 @@ export class AppScreen implements Component, Focusable {const composerPreviewLines: string[] = [];const questionLines = [...this.buildResumeSessionListLines(width),+ ...this.buildModelListLines(width),...this.buildPendingQuestionLines(snapshot, width),];return buildAppScreenLines(snapshot, {@@ -722,6 +737,17 @@ export class AppScreen implements Component, Focusable {await this.openResumeSessionList();return;}+ if (/^\/model\s*$/.test(text)) {+ this.editor.addToHistory(text);+ this.editor.setText("");+ this.composerAttachments = [];+ await this.openModelList();+ return;+ }+ await this.commands.execute(text, {+ ...this.state.getCommandContext(),+ exitApp: this.exit,+ });this.beginPendingSubmittedInput(text, snapshot);this.editor.addToHistory(text);this.editor.setText("");@@ -928,6 +954,83 @@ export class AppScreen implements Component, Focusable {];}+ async openModelList(): Promise<void> {+ const snapshot = this.state.getSnapshot();+ try {+ const payload = await this.state.request<ModelListPayload>("command.model", {});+ const models = payload.available_models ?? [];+ const current = payload.current ?? "unknown";+ if (models.length === 0) {+ this.modelList = null;+ this.state.addItem(addInfo(snapshot.sessionId, "No models configured", "m"));+ return;+ }++ const items = models.map((m, i) => {+ const isCurrent = m === current;+ return {+ label: `${i + 1}. ${m}${isCurrent ? " (current)" : ""}`,+ value: m,+ };+ });+ const list = new SelectList(items, Math.min(Math.max(items.length, 1), 8), selectListTheme, {+ minPrimaryColumnWidth: 24,+ maxPrimaryColumnWidth: 42,+ });+ list.onSelect = (item) => {+ void this.handleModelSelection(item.value);+ };+ list.onCancel = () => {+ this.modelList = null;+ this.tui.requestRender();+ };+ this.modelList = { list, models, current };+ this.tui.requestRender();+ } catch (error) {+ const message = error instanceof Error ? error.message : String(error);+ this.modelList = null;+ this.state.addItem(addError(snapshot.sessionId, `Failed to load models: ${message}`));+ }+ }++ private async handleModelSelection(modelName: string): Promise<void> {+ if (!modelName) {+ return;+ }+ this.modelList = null;+ try {+ const payload = await this.state.request<{+ current?: string;+ requested?: string;+ applied?: boolean;+ }>("command.model", { model: modelName });+ const nextModel = payload.current ?? modelName;+ this.state.clearEntries();+ this.state.addItem(+ addInfo(this.state.getSnapshot().sessionId, `Switched model to: ${nextModel}`, "m"),+ );+ this.tui.requestRender();+ } catch (error) {+ const message = error instanceof Error ? error.message : String(error);+ this.state.addItem(addError(this.state.getSnapshot().sessionId, `Failed to switch model: ${message}`));+ this.tui.requestRender();+ }+ }++ private buildModelListLines(width: number): string[] {+ if (!this.modelList) {+ return [];+ }+ return [+ padToWidth(+ palette.status.warning(`Available models (${this.modelList.models.length} total)`),+ width,+ ),+ ...this.modelList.list.render(width),+ padToWidth(palette.text.dim("↑/↓ choose · Enter switch · Esc cancel"), width),+ ];+ }+private syncComposerAttachmentsFromEditor(): void {if (this.syncingComposerInput) {return;diff --git a/jiuwenclaw/config.py b/jiuwenclaw/config.pyindex 4cb0c61624..21fa993bd6 100644--- a/jiuwenclaw/config.py+++ b/jiuwenclaw/config.py@@ -688,3 +688,35 @@ def migrate_config_from_template(return Truereturn False+++# ---------- 模型配置管理 ----------+def get_model_names() -> list[str]:+ """获取 models 下定义的模型名称列表。"""+ data = _load_yaml_round_trip(_CONFIG_YAML_PATH)+ models = data.get("models", {})+ return list(models.keys()) if models else []+++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)+ if "models" not in data:+ data["models"] = {}+ if name not in data["models"]:+ data["models"][name] = model_config+ else:+ existing = data["models"][name]+ for k, v in model_config.items():+ if v is None and k in existing:+ del existing[k]+ else:+ existing[k] = v+ _dump_yaml_round_trip(_CONFIG_YAML_PATH, data)+++def get_model_config(name: str) -> dict[str, Any] | None:+ """获取指定模型的原始配置(不解析环境变量)。"""+ data = _load_yaml_round_trip(_CONFIG_YAML_PATH)+ models = data.get("models", {})+ return models.get(name) if name in models else Nonediff --git a/tests/unit_tests/agentserver/test_agentserver_cli_commands.py b/tests/unit_tests/agentserver/test_agentserver_cli_commands.pyindex 9aaa412fec..c640487bde 100644--- a/tests/unit_tests/agentserver/test_agentserver_cli_commands.py+++ b/tests/unit_tests/agentserver/test_agentserver_cli_commands.py@@ -64,7 +64,9 @@ def patch_wire_encoder(monkeypatch):@pytest.mark.asyncio-async def test_handle_command_add_dir_returns_path_and_remember(server, fake_ws, monkeypatch):+async def test_handle_command_add_dir_returns_path_and_remember(+ server, fake_ws, monkeypatch+):persist_stub = {"ok": True,"normalized": "/tmp/demo",@@ -147,12 +149,16 @@ async def test_handle_command_diff_returns_summary_payload(server, fake_ws):@pytest.mark.asyncio-async def test_handle_command_model_returns_current_and_requested_model(server, fake_ws):+async def test_handle_command_model_no_action_shows_current(+ server, fake_ws, monkeypatch+):+ """No action → returns current model from os.environ and available list."""+ monkeypatch.setenv("MODEL_NAME", "test-model")request = AgentRequest(request_id="req-model",channel_id="tui",req_method=ReqMethod.COMMAND_MODEL,- params={"model": "planner-model"},+ params={},)await server.handle_command_model_for_test(fake_ws, request, asyncio.Lock())@@ -161,16 +167,35 @@ async def test_handle_command_model_returns_current_and_requested_model(server,{"response_id": "req-model","payload": {- "current": "planner-model",- "requested": "planner-model",- "applied": True,- "available": ["default-model", "planner-model", "coder-model"],+ "current": "test-model",+ "available": ["default-model"],},"ok": True,}]+async def test_handle_command_model_add_model(server, fake_ws):+ """action=add_model → returns model_added confirmation."""+ request = AgentRequest(+ request_id="req-add",+ channel_id="cli",+ req_method=ReqMethod.COMMAND_MODEL,+ params={"action": "add_model", "target": "my-model", "config": {}},+ )++ await server.handle_command_model_for_test(fake_ws, request, asyncio.Lock())++ assert fake_ws.sent == [+ {+ "response_id": "req-add",+ "payload": {"type": "model_added", "name": "my-model"},+ "ok": True,+ }+ ]++@pytest.mark.asyncioasync def test_handle_command_resume_returns_mock_session(server, fake_ws):request = AgentRequest(