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
fix: sandbox support yuanrong type
zhaozixuan5593b121f861
diff --git a/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/sandbox.ts b/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/sandbox.tsindex 64e603d605..c022981a28 100644--- a/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/sandbox.ts+++ b/jiuwenswarm/channels/tui/frontend/src/core/commands/builtins/sandbox.ts@@ -1,5 +1,5 @@import { addError, addInfo } from "../helpers.js";-import { CommandKind, type SlashCommand } from "../types.js";+import { CommandKind, type CommandContext, type SlashCommand } from "../types.js";type SandboxFileEntry =| string@@ -16,7 +16,17 @@ type SandboxEffectiveFiles = {deny_write?: SandboxFileEntry[];};+type SandboxMount = {+ source?: string;+ target?: string;+ readonly?: boolean;+};+type SandboxResponse = {+ type?: string;+ enabled?: boolean;+ executor?: string;+ mounts?: SandboxMount[];runtime?: SandboxRuntime;excluded_commands?: string[];files?: { allow?: SandboxFileEntry[]; deny?: SandboxFileEntry[] };@@ -26,6 +36,11 @@ type SandboxResponse = {jiuwenbox_stopped?: boolean;};+type SandboxProviderType = "yuanrong" | "jiuwenbox" | "unknown";++let cachedProviderType: SandboxProviderType = "unknown";+let sandboxCommandRef: SlashCommand | null = null;+function tokenize(raw: string): string[] {const re = /"([^"]*)"|'([^']*)'|(\S+)/g;const out: string[] = [];@@ -50,6 +65,37 @@ function formatFileEntry(entry: SandboxFileEntry, defaultAccess?: string): strinreturn String(entry);}+function formatMount(mount: SandboxMount): string {+ const source = String(mount.source ?? "").trim();+ const target = String(mount.target ?? source).trim();+ const access = mount.readonly ? "ro" : "rw";+ if (!source) return "";+ return `${source} -> ${target} (${access})`;+}++function showYuanrongRuntime(+ ctx: Parameters<SlashCommand["action"]>[0],+ payload: SandboxResponse,+): void {+ const mounts = payload.mounts ?? [];+ const mountText = mounts+ .map(formatMount)+ .filter(Boolean)+ .join(", ");+ const items = [+ { label: "enabled", value: formatBool(payload.enabled) },+ { label: "executor", value: String(payload.executor ?? "(unset)") },+ { label: "mounts", value: mountText || "(empty)" },+ ];+ ctx.addItem(+ addInfo(ctx.sessionId, "Sandbox status", "s", {+ view: "kv",+ title: "Sandbox Runtime",+ items,+ }),+ );+}+function showRuntime(ctx: Parameters<SlashCommand["action"]>[0],runtime: SandboxRuntime | undefined,@@ -87,7 +133,7 @@ function showRuntime();}-function usageText(): string {+function jiuwenboxUsageText(): string {const lines = ["/sandbox show current runtime status","/sandbox enable enter sandbox mode (spawns jiuwenbox + recreates agent)",@@ -103,28 +149,100 @@ function usageText(): string {return lines.map((line, i) => (i === 0 ? line : ` ${line}`)).join("\n");}+function yuanrongUsageText(): string {+ return "sandbox.type=yuanrong: only /sandbox (view config: enabled, executor, mounts); no subcommands";+}++function applySandboxCommandPresentation(type: SandboxProviderType): void {+ cachedProviderType = type;+ const cmd = sandboxCommandRef;+ if (!cmd) return;+ if (type === "yuanrong") {+ cmd.description = "View YuanRong sandbox config (enabled / executor / mounts)";+ cmd.usage = "/sandbox";+ cmd.example = "/sandbox";+ cmd.takesArgs = false;+ cmd.argGuide = undefined;+ } else {+ cmd.description = "Manage jiuwenbox sandbox mode";+ cmd.usage = "/sandbox <enable|disable|exclude|files> ...";+ cmd.example = "/sandbox enable";+ cmd.takesArgs = true;+ }+}++function providerTypeFromPayload(payload: SandboxResponse): SandboxProviderType {+ return payload.type === "yuanrong" ? "yuanrong" : "jiuwenbox";+}++/**+ * Probe sandbox.type once WS is connected so inline `/sandbox` hints hide+ * jiuwenbox subcommands when type=yuanrong.+ */+export async function refreshSandboxCommandPresentation(+ ctx: Pick<CommandContext, "request">,+): Promise<SandboxProviderType> {+ try {+ const payload = await ctx.request<SandboxResponse>("command.sandbox", { sub: "status" });+ const type = providerTypeFromPayload(payload);+ applySandboxCommandPresentation(type);+ return type;+ } catch {+ return cachedProviderType;+ }+}+export function createSandboxCommand(): SlashCommand {- return {+ const command: SlashCommand = {name: "sandbox",description: "Manage jiuwenbox sandbox mode",usage: "/sandbox <enable|disable|exclude|files> ...",example: "/sandbox enable",kind: CommandKind.BUILT_IN,takesArgs: true,+ completion: async () => {+ // YuanRong has no subcommands — never suggest enable/disable/files/….+ if (cachedProviderType === "yuanrong") {+ return [];+ }+ return ["enable", "disable", "exclude", "files", "help", "status"];+ },action: async (ctx, args) => {const raw = (args ?? "").trim();const tokens = tokenize(raw);const sub = (tokens[0] ?? "").toLowerCase();try {+ // Ensure presentation/meta matches server config before handling args.+ if (cachedProviderType === "unknown") {+ await refreshSandboxCommandPresentation(ctx);+ }++ if (cachedProviderType === "yuanrong") {+ // Bare /sandbox only — no status/help/enable/… tokens.+ if (raw) {+ ctx.addItem(addError(ctx.sessionId, yuanrongUsageText()));+ return;+ }+ const payload = await ctx.request<SandboxResponse>("command.sandbox", { sub: "status" });+ applySandboxCommandPresentation(providerTypeFromPayload(payload));+ showYuanrongRuntime(ctx, payload);+ return;+ }+if (!sub || sub === "status" || sub === "show") {const payload = await ctx.request<SandboxResponse>("command.sandbox", { sub: "status" });+ applySandboxCommandPresentation(providerTypeFromPayload(payload));+ if (payload.type === "yuanrong") {+ showYuanrongRuntime(ctx, payload);+ return;+ }showRuntime(ctx, payload.runtime, payload.effective_files);return;}if (sub === "help") {- ctx.addItem(addInfo(ctx.sessionId, usageText(), "s"));+ ctx.addItem(addInfo(ctx.sessionId, jiuwenboxUsageText(), "s"));return;}@@ -279,11 +397,17 @@ export function createSandboxCommand(): SlashCommand {return;}- ctx.addItem(addError(ctx.sessionId, `Unknown sub-command: ${sub}\n${usageText()}`));+ ctx.addItem(addError(ctx.sessionId, `Unknown sub-command: ${sub}\n${jiuwenboxUsageText()}`));} catch (error) {const message = error instanceof Error ? error.message : String(error);ctx.addItem(addError(ctx.sessionId, `sandbox failed: ${message}`));}},};++ sandboxCommandRef = command;+ if (cachedProviderType !== "unknown") {+ applySandboxCommandPresentation(cachedProviderType);+ }+ return command;}diff --git a/jiuwenswarm/channels/tui/frontend/src/ui/app-screen.ts b/jiuwenswarm/channels/tui/frontend/src/ui/app-screen.tsindex f24a834b12..47d2803f4f 100644--- a/jiuwenswarm/channels/tui/frontend/src/ui/app-screen.ts+++ b/jiuwenswarm/channels/tui/frontend/src/ui/app-screen.ts@@ -1590,6 +1590,7 @@ export class AppScreen implements Component, Focusable {private runningStoppedAtMs: number | null = null;/** Whether the eager skill-cache fetch on first WebSocket connection has already been fired. */private didEagerFetchSkills = false;+ private didEagerFetchSandboxMeta = false;private pendingSubmittedInput: string | null = null;private pendingSubmittedBaseline = 0;private pendingSubmittedSessionId: string | null = null;@@ -3477,6 +3478,21 @@ export class AppScreen implements Component, Focusable {this.didEagerFetchSkills = true;void this.commands.refreshSkills(this.state.getCommandContext());}+ // Hide /sandbox subcommand inline hints when sandbox.type=yuanrong.+ if (!this.didEagerFetchSandboxMeta && snapshot.connectionStatus === "connected") {+ this.didEagerFetchSandboxMeta = true;+ void import("../core/commands/builtins/sandbox.js")+ .then(({ refreshSandboxCommandPresentation }) =>+ refreshSandboxCommandPresentation(this.state.getCommandContext()),+ )+ .then(() => {+ this.composerAutocompleteProvider = this.rebuildAutocompleteProvider();+ this.editor.setAutocompleteProvider(this.composerAutocompleteProvider);+ })+ .catch(() => {+ // Best-effort; /sandbox action still probes on use.+ });+ }if (this.pendingSubmittedInput &&(snapshot.sessionId !== this.pendingSubmittedSessionId ||diff --git a/jiuwenswarm/common/config.py b/jiuwenswarm/common/config.pyindex 8253cddca1..5b9523a45f 100644--- a/jiuwenswarm/common/config.py+++ b/jiuwenswarm/common/config.py@@ -2104,11 +2104,36 @@ _VALID_SANDBOX_STARTUP_MODES = ("internal", "external")_DEFAULT_SANDBOX_STARTUP_MODE = "internal"_DEFAULT_SANDBOX_POLICY_FILE = "code-agent-policy.yaml"+# YuanRong sandbox knobs under flat ``sandbox:`` (see get_sandbox_endpoint).+_VALID_YUANRONG_EXECUTORS = ("default", "docker")+_DEFAULT_YUANRONG_EXECUTOR = "docker"+_DEFAULT_YUANRONG_URL = "http://yuanrong.local"+_YUANRONG_ENDPOINT_OPTIONAL_KEYS: tuple[str, ...] = (+ "image",+ "workdir",+ "mounts",+ "cpu",+ "cpu_limit",+ "memory",+ "mem_limit",+ "rootfs",+)+# Public re-exports for callers that need to fall back to / advertise defaults# (e.g. agent_ws_server 把缺省值持久化到 config.yaml, 让重启后 get_sandbox_endpoint# 能直接读到, 而不必每次再走一遍 fallback 逻辑)。DEFAULT_SANDBOX_STARTUP_MODE = _DEFAULT_SANDBOX_STARTUP_MODEDEFAULT_SANDBOX_POLICY_FILE = _DEFAULT_SANDBOX_POLICY_FILE+DEFAULT_YUANRONG_SANDBOX_URL = _DEFAULT_YUANRONG_URL+DEFAULT_YUANRONG_EXECUTOR = _DEFAULT_YUANRONG_EXECUTOR+++def _normalize_yuanrong_executor(value: Any) -> str:+ """归一化 ``sandbox.executor``; 非法或空值回落到默认 ``docker``."""+ text = str(value or "").strip().lower()+ if text not in _VALID_YUANRONG_EXECUTORS:+ return _DEFAULT_YUANRONG_EXECUTOR+ return textdef _normalize_sandbox_startup_mode(value: Any) -> str:@@ -2270,12 +2295,18 @@ def update_sandbox_policy_file(value: str) -> str:def get_sandbox_endpoint() -> dict[str, Any]:"""返回 ``sandbox.url`` / ``sandbox.type`` / ``sandbox.preserve_file_sharing_mode``- / ``sandbox.startup_mode`` / ``sandbox.policy_file``.+ / ``sandbox.startup_mode`` / ``sandbox.policy_file``, 以及 yuanrong 可选 knobs。``preserve_file_sharing_mode`` 缺省或为空时返回空串, 由调用方决定默认值(当前只有 ``"mount"``)。 ``startup_mode`` 未配置时回落到 ``internal``;``policy_file`` 未配置时返回空串 (由调用方决定默认 policy)。+ 当 ``type=yuanrong`` 时额外返回:+ - ``executor`` (缺省 ``docker``)+ - 若 yaml 中存在: ``image`` / ``workdir`` / ``mounts`` / ``cpu`` /+ ``cpu_limit`` / ``memory`` / ``mem_limit`` / ``rootfs``+ - ``url`` 为空时回落占位 ``http://yuanrong.local`` (仅作 cache key)+Raises:ValueError: yaml 里 ``preserve_file_sharing_mode`` 写了非法值时, 直接把 :func:`_normalize_preserve_file_sharing_mode` 的异常向上抛, 由@@ -2284,13 +2315,22 @@ def get_sandbox_endpoint() -> dict[str, Any]:cfg = get_config() or {}sandbox = cfg.get("sandbox") or {}mode = _normalize_preserve_file_sharing_mode(sandbox.get("preserve_file_sharing_mode"))- return {- "url": str(sandbox.get("url") or "").strip(),- "type": str(sandbox.get("type") or "").strip(),+ sandbox_type = str(sandbox.get("type") or "").strip()+ url = str(sandbox.get("url") or "").strip()+ result: dict[str, Any] = {+ "url": url,+ "type": sandbox_type,"preserve_file_sharing_mode": mode or "","startup_mode": _normalize_sandbox_startup_mode(sandbox.get("startup_mode")),"policy_file": str(sandbox.get("policy_file") or "").strip(),}+ if sandbox_type == "yuanrong":+ result["url"] = url or _DEFAULT_YUANRONG_URL+ result["executor"] = _normalize_yuanrong_executor(sandbox.get("executor"))+ for key in _YUANRONG_ENDPOINT_OPTIONAL_KEYS:+ if key in sandbox:+ result[key] = sandbox[key]+ return resultdef update_sandbox_endpoint(@@ -2300,10 +2340,20 @@ def update_sandbox_endpoint(preserve_file_sharing_mode: str | None = None,startup_mode: str | None = None,policy_file: str | None = None,+ executor: str | None = None,+ image: str | None = None,+ workdir: str | None = None,+ mounts: list | None = None,+ cpu: int | None = None,+ cpu_limit: int | None = None,+ memory: int | None = None,+ mem_limit: int | None = None,+ rootfs: dict | None = None,) -> dict[str, Any]:"""写入 ``sandbox.url`` / ``sandbox.type`` 以及可选的``preserve_file_sharing_mode`` / ``startup_mode`` / ``policy_file``- 到 config.yaml; 返回实际写入的字段集合 (没有改动的字段不在返回里)。+ / yuanrong knobs 到 config.yaml; 返回实际写入的字段集合+ (没有改动的字段不在返回里)。所有 ``None`` 入参表示"本次不修改该字段, 保留 config.yaml 中既有值",以方便 ``_handle_sandbox_enable`` 在不同阶段分批落盘。@@ -2331,6 +2381,10 @@ def update_sandbox_endpoint(raise ValueError("policy_file must be non-empty when provided")policy_value = policy_text+ executor_value: str | None = None+ if executor is not None:+ executor_value = _normalize_yuanrong_executor(executor)+data = _load_yaml_round_trip(_CONFIG_YAML_PATH)if "sandbox" not in data or not isinstance(data.get("sandbox"), dict):data["sandbox"] = {}@@ -2342,6 +2396,33 @@ def update_sandbox_endpoint(data["sandbox"]["startup_mode"] = startup_valueif policy_value is not None:data["sandbox"]["policy_file"] = policy_value+ if executor_value is not None:+ data["sandbox"]["executor"] = executor_value++ optional_writes: dict[str, Any] = {}+ if image is not None:+ optional_writes["image"] = str(image).strip()+ if workdir is not None:+ optional_writes["workdir"] = str(workdir).strip()+ if mounts is not None:+ if not isinstance(mounts, list):+ raise ValueError("mounts must be a list")+ optional_writes["mounts"] = mounts+ if cpu is not None:+ optional_writes["cpu"] = int(cpu)+ if cpu_limit is not None:+ optional_writes["cpu_limit"] = int(cpu_limit)+ if memory is not None:+ optional_writes["memory"] = int(memory)+ if mem_limit is not None:+ optional_writes["mem_limit"] = int(mem_limit)+ if rootfs is not None:+ if not isinstance(rootfs, dict):+ raise ValueError("rootfs must be a dict")+ optional_writes["rootfs"] = rootfs+ for key, value in optional_writes.items():+ data["sandbox"][key] = value+_dump_yaml_round_trip(_CONFIG_YAML_PATH, data)result: dict[str, Any] = {"url": url_value, "type": type_value}if mode_value is not None:@@ -2350,6 +2431,9 @@ def update_sandbox_endpoint(result["startup_mode"] = startup_valueif policy_value is not None:result["policy_file"] = policy_value+ if executor_value is not None:+ result["executor"] = executor_value+ result.update(optional_writes)return resultdiff --git a/jiuwenswarm/server/agent_ws_server.py b/jiuwenswarm/server/agent_ws_server.pyindex bb6b241dc5..20795862e0 100644--- a/jiuwenswarm/server/agent_ws_server.py+++ b/jiuwenswarm/server/agent_ws_server.py@@ -67,6 +67,7 @@ from jiuwenswarm.server.runtime.session.session_history import ()from jiuwenswarm.server.runtime.agent_adapter.sysop_builder import (build_filesystem_policy,+ build_yuanrong_sandbox_status_view,effective_files_from_policy,find_auto_managed_match,find_nested_files_conflict,@@ -1001,6 +1002,13 @@ class AgentWebSocketServer:endpoint = get_sandbox_endpoint()url = endpoint.get("url") or "http://127.0.0.1:8321"sandbox_type = endpoint.get("type") or "jiuwenbox"+ # yuanrong 不需要本机 jiuwenbox 进程; 仅通过 config 启用 SysOperation。+ if str(sandbox_type).strip().lower() == "yuanrong":+ logger.info(+ "[AgentWebSocketServer] sandbox.type=yuanrong, skipping "+ "jiuwenbox auto-start (YuanRong uses YR_* env + yr.init)"+ )+ returnraw_policy = endpoint.get("policy_file") or ""effective_policy_file = raw_policy or DEFAULT_SANDBOX_POLICY_FILEpolicy_path = resolve_sandbox_policy_path(effective_policy_file)@@ -4908,46 +4916,73 @@ class AgentWebSocketServer:``enable``/``disable`` 走 ``agent_manager.recreate_agent`` (重建 sys_operation 类型);其他写动作通过 ``adapter.apply_sandbox_runtime_patch()`` 立即热更,不重建 agent.++ 当 ``sandbox.type=yuanrong`` 时仅允许 ``status`` (裸 ``/sandbox`` 查看+ enabled/executor/mounts); 任意子指令一律拒绝。"""params = request.params or {}- sub = str(params.get("sub", "status")).strip().lower()+ sub = str(params.get("sub", "status")).strip().lower() or "status"channel_id = request.channel_id or "default"try:# 平台守卫: ``/sandbox`` 全家桶仅在 Linux 上可用。 放在 try 内部是# 故意的, 让 ValueError 命中下方 ``except ValueError`` 分支转成# ``SANDBOX_BAD_REQUEST`` 回执, 跟其它入参校验失败的处理一致。_require_sandbox_supported()- validate_sandbox_files_runtime(get_sandbox_runtime().get("files"))- if sub == "status":- payload = {"runtime": get_sandbox_runtime()}- elif sub == "enable":- payload = await self._handle_sandbox_enable(channel_id)- elif sub == "disable":- payload = await self._handle_sandbox_disable(channel_id)- elif sub == "exclude.add":- payload = await self._handle_sandbox_exclude_add(channel_id, params)- elif sub == "exclude.remove":- payload = await self._handle_sandbox_exclude_remove(channel_id, params)- elif sub == "exclude.list":- payload = {"excluded_commands": list(get_sandbox_runtime().get("excluded_commands") or [])}- elif sub == "files.allow":- payload = await self._handle_sandbox_files_set(channel_id, params, bucket="allow")- elif sub == "files.deny":- payload = await self._handle_sandbox_files_set(channel_id, params, bucket="deny")- elif sub == "files.remove":- payload = await self._handle_sandbox_files_remove(channel_id, params)- elif sub == "files.list":- payload = {"files": dict(get_sandbox_runtime().get("files") or {})}+ endpoint = get_sandbox_endpoint()+ sandbox_type = str(endpoint.get("type") or "").strip().lower()+ if sandbox_type == "yuanrong":+ if sub != "status":+ raise ValueError(+ "sandbox.type=yuanrong: only /sandbox (view config) is "+ "supported; subcommands are disabled"+ )+ payload = build_yuanrong_sandbox_status_view()+ resp = AgentResponse(+ request_id=request.request_id,+ channel_id=request.channel_id,+ ok=True,+ payload=payload,+ )else:- raise ValueError(f"unknown sub: {sub!r}")- self._attach_effective_sandbox_files(payload, channel_id, params)- await self._attach_landlock_status(payload)- resp = AgentResponse(- request_id=request.request_id,- channel_id=request.channel_id,- ok=True,- payload=payload,- )+ validate_sandbox_files_runtime(get_sandbox_runtime().get("files"))+ if sub == "status":+ payload = {"runtime": get_sandbox_runtime()}+ elif sub == "enable":+ payload = await self._handle_sandbox_enable(channel_id)+ elif sub == "disable":+ payload = await self._handle_sandbox_disable(channel_id)+ elif sub == "exclude.add":+ payload = await self._handle_sandbox_exclude_add(channel_id, params)+ elif sub == "exclude.remove":+ payload = await self._handle_sandbox_exclude_remove(channel_id, params)+ elif sub == "exclude.list":+ payload = {+ "excluded_commands": list(+ get_sandbox_runtime().get("excluded_commands") or []+ )+ }+ elif sub == "files.allow":+ payload = await self._handle_sandbox_files_set(+ channel_id, params, bucket="allow"+ )+ elif sub == "files.deny":+ payload = await self._handle_sandbox_files_set(+ channel_id, params, bucket="deny"+ )+ elif sub == "files.remove":+ payload = await self._handle_sandbox_files_remove(channel_id, params)+ elif sub == "files.list":+ payload = {"files": dict(get_sandbox_runtime().get("files") or {})}+ else:+ raise ValueError(f"unknown sub: {sub!r}")+ self._attach_effective_sandbox_files(payload, channel_id, params)+ await self._attach_landlock_status(payload)+ resp = AgentResponse(+ request_id=request.request_id,+ channel_id=request.channel_id,+ ok=True,+ payload=payload,+ )except ValueError as exc:resp = AgentResponse(request_id=request.request_id,diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.pyindex 8ea321612c..82d6ad9412 100644--- a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py@@ -265,6 +265,7 @@ from jiuwenswarm.common.config import (get_evolution_review_trigger_enabled,get_evolution_auto_save_enabled,get_evolution_signal_trigger_enabled,+ get_sandbox_endpoint,get_sandbox_runtime,get_sandbox_startup_mode,get_skill_create_enabled,@@ -3105,16 +3106,16 @@ class JiuWenSwarmDeepAdapter:分别写入 ``launcher_config.extra_params`` 与 ``launcher_config`` 上的同名字段。- 注意: 每次都从 ``get_config()`` 读最新 sandbox.url/type, 因为- ``/sandbox enable`` 会动态写入这两个字段。+ 注意: 每次都从 ``get_sandbox_endpoint()`` 读最新 sandbox.url/type, 因为+ ``/sandbox enable`` 会动态写入这两个字段; yuanrong 也会填默认占位 url。副作用: 在 ``self._sys_operation_card`` 保存生成或复用的 SysOperationCard,供 ``apply_sandbox_runtime_patch`` 等运行时热更使用。"""try:- sandbox_cfg = (get_config() or {}).get("sandbox") or {}- sandbox_url = sandbox_cfg.get("url", None)- sandbox_type = sandbox_cfg.get("type", None)+ endpoint = get_sandbox_endpoint()+ sandbox_url = endpoint.get("url") or None+ sandbox_type = endpoint.get("type") or Noneruntime = get_sandbox_runtime()sysop_card: SysOperationCard | Noneif runtime.get("enabled") and sandbox_url and sandbox_type:@@ -3175,9 +3176,9 @@ class JiuWenSwarmDeepAdapter:- 通过 mutate 已构建 SysOperationCard 的 ``launcher_config.extra_params``字典让 provider 下次 exec 时读到新值(provider 持 dict 引用)。- - ``files_changed=True`` 时额外调用 ``force_recreate_jiuwenbox_sandbox``,- 清除共享 sandbox_id 缓存并立即在 jiuwenbox 服务端新建 sandbox 实例,- 把新 ID 写回 ``extra_params["sandbox_id"]``。+ - ``files_changed=True`` 时:+ - jiuwenbox: 调用 ``force_recreate_jiuwenbox_sandbox``+ - yuanrong: 调用 ``delete_yuanrong_sandbox``,下次 op 懒创建新实例Args:runtime: ``get_sandbox_runtime()`` 当前完整 runtime。@@ -3198,6 +3199,56 @@ class JiuWenSwarmDeepAdapter:)return+ sandbox_type = str(getattr(launcher, "sandbox_type", "") or "").strip().lower()+ if sandbox_type == "yuanrong":+ logger.info(+ "[JiuWenSwarmDeepAdapter] yuanrong runtime patch "+ "(files_changed=%s; policy/exclude ignored)",+ files_changed,+ )+ if files_changed:+ try:+ from openjiuwen.extensions.sys_operation.sandbox.providers.yuanrong import (+ build_yuanrong_shared_scope_key,+ delete_yuanrong_sandbox,+ )+ except Exception as exc:+ logger.warning(+ "[JiuWenSwarmDeepAdapter] delete_yuanrong_sandbox import "+ "failed: %s",+ exc,+ )+ return+ try:+ isolation_key = self._sys_operation_isolation_key(card)+ shared_key = (+ build_yuanrong_shared_scope_key(+ str(launcher.base_url), str(isolation_key)+ )+ if isolation_key+ else None+ )+ deleted = await delete_yuanrong_sandbox(+ shared_key=shared_key,+ base_url=(+ str(launcher.base_url)+ if launcher.base_url and not shared_key+ else None+ ),+ reason="files_changed",+ )+ logger.info(+ "[JiuWenSwarmDeepAdapter] yuanrong sandbox deleted for "+ "recreate: %s",+ deleted,+ )+ except Exception as exc:+ logger.warning(+ "[JiuWenSwarmDeepAdapter] delete_yuanrong_sandbox failed: %s",+ exc,+ )+ return+extra = launcher.extra_params or {}extra["excluded_commands"] = list(runtime.get("excluded_commands") or [])extra["fallback_on_failure"] = bool(runtime.get("fallback_on_failure", False))diff --git a/jiuwenswarm/server/runtime/agent_adapter/sysop_builder.py b/jiuwenswarm/server/runtime/agent_adapter/sysop_builder.pyindex 1f511a3798..5c0d0441ea 100644--- a/jiuwenswarm/server/runtime/agent_adapter/sysop_builder.py+++ b/jiuwenswarm/server/runtime/agent_adapter/sysop_builder.py@@ -20,8 +20,13 @@ from openjiuwen.core.sys_operation.config import (SandboxIsolationConfig,)-from jiuwenswarm.common.config import get_sandbox_startup_mode+from jiuwenswarm.common.config import (+ get_sandbox_endpoint,+ get_sandbox_runtime,+ get_sandbox_startup_mode,+)from jiuwenswarm.common.utils import (+ get_agent_root_dir,get_agent_workspace_dir,get_config_file,)@@ -242,6 +247,149 @@ def _sandbox_isolation_custom_id(project_dir: str | Path | None) -> str:return f"project_{digest}"+def _resolve_agent_root_dir() -> Path | None:+ """Resolve agent_root for yuanrong identity mount (enterprise_dev-style)."""+ try:+ agent_root = Path(get_agent_root_dir()).expanduser().resolve()+ except OSError as exc:+ logger.debug("[sysop_builder] agent_root resolve failed: %s", exc)+ return None+ if agent_root == Path(agent_root.anchor):+ logger.warning(+ "[sysop_builder] refusing to mount filesystem root %s as agent_root",+ agent_root,+ )+ return None+ try:+ agent_root.mkdir(parents=True, exist_ok=True)+ except OSError as exc:+ logger.warning(+ "[sysop_builder] could not ensure agent_root %s: %s",+ agent_root,+ exc,+ )+ return None+ if not agent_root.is_dir():+ logger.warning(+ "[sysop_builder] agent_root %s is not a directory; skipping mount",+ agent_root,+ )+ return None+ return agent_root+++def _merge_yuanrong_mounts(+ agent_root_mount: dict[str, Any],+ config_mounts: list[Any] | None,+) -> list[dict[str, Any]]:+ """Merge forced agent_root mount with optional yaml mounts; dedupe by source+target."""+ merged: list[dict[str, Any]] = [dict(agent_root_mount)]+ seen = {+ (+ str(agent_root_mount.get("source") or ""),+ str(agent_root_mount.get("target") or ""),+ )+ }+ for entry in config_mounts or []:+ if not isinstance(entry, dict):+ continue+ source = str(entry.get("source") or "").strip()+ target = str(entry.get("target") or source).strip()+ if not source or not target:+ continue+ key = (source, target)+ if key in seen:+ continue+ seen.add(key)+ mount = {+ "source": source,+ "target": target,+ "readonly": bool(entry.get("readonly", False)),+ }+ merged.append(mount)+ return merged+++def _build_yuanrong_extra_params() -> dict[str, Any]:+ """Assemble yuanrong provider extra_params; always identity-mount agent_root."""+ endpoint = get_sandbox_endpoint()+ executor = str(endpoint.get("executor") or "docker").strip().lower() or "docker"+ agent_root = _resolve_agent_root_dir()+ if agent_root is None:+ raise ValueError("yuanrong sandbox requires a resolvable agent_root directory")++ agent_root_str = str(agent_root)+ agent_root_mount = {+ "source": agent_root_str,+ "target": agent_root_str,+ "readonly": False,+ }+ config_mounts = endpoint.get("mounts")+ if not isinstance(config_mounts, list):+ config_mounts = None++ extra_params: dict[str, Any] = {+ "executor": executor,+ "mounts": _merge_yuanrong_mounts(agent_root_mount, config_mounts),+ }++ workdir = endpoint.get("workdir")+ if workdir is not None and str(workdir).strip():+ extra_params["workdir"] = str(workdir).strip()+ else:+ extra_params["workdir"] = agent_root_str++ for key in ("image", "cpu", "cpu_limit", "memory", "mem_limit", "rootfs"):+ if key not in endpoint:+ continue+ value = endpoint[key]+ if key == "rootfs":+ if isinstance(value, dict):+ rootfs = dict(value)+ existing = rootfs.get("mounts")+ rootfs["mounts"] = _merge_yuanrong_mounts(+ agent_root_mount,+ existing if isinstance(existing, list) else None,+ )+ if "workdir" not in rootfs or not str(rootfs.get("workdir") or "").strip():+ rootfs["workdir"] = extra_params["workdir"]+ extra_params["rootfs"] = rootfs+ continue+ if value is not None:+ extra_params[key] = value+ return extra_params+++def build_yuanrong_sandbox_status_view() -> dict[str, Any]:+ """Read-only yuanrong status for TUI ``/sandbox`` (enabled / executor / mounts)."""+ runtime = get_sandbox_runtime()+ endpoint = get_sandbox_endpoint()+ executor = str(endpoint.get("executor") or "docker").strip().lower() or "docker"+ try:+ mounts = list(_build_yuanrong_extra_params().get("mounts") or [])+ except Exception as exc: # noqa: BLE001+ logger.warning(+ "[sysop_builder] yuanrong status mounts fallback: %s",+ exc,+ )+ config_mounts = endpoint.get("mounts")+ mounts = [+ {+ "source": str(entry.get("source") or "").strip(),+ "target": str(entry.get("target") or entry.get("source") or "").strip(),+ "readonly": bool(entry.get("readonly", False)),+ }+ for entry in (config_mounts if isinstance(config_mounts, list) else [])+ if isinstance(entry, dict) and str(entry.get("source") or "").strip()+ ]+ return {+ "type": "yuanrong",+ "enabled": bool(runtime.get("enabled")),+ "executor": executor,+ "mounts": mounts,+ }++def build_filesystem_policy(files_runtime: dict[str, Any] | None,*,@@ -433,18 +581,56 @@ def create_sandbox_sysop_card(is_code_agent: bool = False,startup_mode: str | None = None,) -> SysOperationCard | None:- """create jiuwenbox SysOperationCard."""- # 触发 jiuwenbox provider 注册(@SandboxRegistry.provider 装饰器副作用)+ """Create sandbox SysOperationCard (jiuwenbox or yuanrong)."""+ # 触发 sandbox provider 注册(@SandboxRegistry.provider 装饰器副作用)import openjiuwen.extensions.sys_operation.sandbox.providers # noqa: F401+ normalized_type = str(sandbox_type or "").strip().lower()try:+ if normalized_type == "yuanrong":+ extra_params = _build_yuanrong_extra_params()+ isolation_custom_id = _sandbox_isolation_custom_id(project_dir)+ gateway_config = SandboxGatewayConfig(+ isolation=SandboxIsolationConfig(+ container_scope=ContainerScope.CUSTOM,+ custom_id=isolation_custom_id,+ ),+ launcher_config=PreDeployLauncherConfig(+ base_url=sandbox_url,+ sandbox_type="yuanrong",+ idle_ttl_seconds=idle_ttl_seconds,+ extra_params=extra_params,+ ),+ )+ sysop_card = SysOperationCard(+ mode=OperationMode.SANDBOX,+ work_config=LocalWorkConfig(shell_allowlist=None),+ gateway_config=gateway_config,+ )+ logger.info(+ "[sysop_builder] yuanrong SysOperationCard created:\n"+ " base_url=%s sandbox_type=yuanrong\n"+ " isolation_custom_id=%s\n"+ " idle_ttl=%s\n"+ " executor=%s workdir=%s\n"+ " mounts(%d)=%s",+ sandbox_url,+ isolation_custom_id,+ idle_ttl_seconds,+ extra_params.get("executor"),+ extra_params.get("workdir"),+ len(extra_params.get("mounts") or []),+ extra_params.get("mounts") or [],+ )+ return sysop_card+policy, upload_list = build_filesystem_policy(files_runtime,project_dir=project_dir,is_code_agent=is_code_agent,startup_mode=startup_mode,)- extra_params: dict[str, Any] = {+ extra_params = {"policy": policy,"policy_mode": "append","excluded_commands": list(excluded_commands or []),@@ -791,6 +977,7 @@ def find_auto_managed_match(__all__ = ["PreserveFileSharingMode","build_filesystem_policy",+ "build_yuanrong_sandbox_status_view","create_sandbox_sysop_card","create_local_sysop_card","effective_files_from_policy",