Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat(society): add per-agent code sandboxes (#498)
Ruben Lütkec3fd760ada21
diff --git a/docs/agent-sandbox.md b/docs/agent-sandbox.mdnew file mode 100644index 0000000000..9a549e5938--- /dev/null+++ b/docs/agent-sandbox.md@@ -0,0 +1,35 @@+# Agent code sandbox++Choose **Code sandbox** when creating a Dodaios agent, or change its execution+environment in the agent card while it is idle. Use an API or local model.+Native coding CLIs and external agent runtimes are refused in this mode.++Docker must be running with Linux containers. The agent card checks readiness;+the explicit **Download runtime** action downloads the Python runtime image.+Missing Docker or an image never falls back to commands on the host.++The model and conversation remain in Dodaios. Its only machine-facing tool is+society_sandbox: run a command, write a UTF-8 file, read a file, or list a+directory. Other tools, plugins, desktop control and delegation are excluded.+Existing grants, denials, approval rules and read-only modes still apply.++Each identity gets a separate Docker volume. Every command gets a disposable,+unprivileged container with networking disabled, a read-only root filesystem,+no host mounts, no credentials and no Docker socket. Limits are one CPU,+512 MB memory, 128 processes, 64 MB temporary storage, 16 MB per written file,+and at most 15 minutes per command. Persistent volume storage has no aggregate+quota; this is container isolation, not a separate kernel per agent.++The chat Stop button cancels the command and removes its container. An internal+deadline also limits work if the Dodaios host crashes. Files persist separately+from the host workspace. Refresh files in the agent card and click a result to+download it (up to 1 MB). Changing back to local execution retains the sandbox+files; it does not copy them onto the host.++The existing dynamic CLI exposes the mounted society sandbox readiness, image+preparation, file listing and download routes. The OpenAPI document lists their+operation names. Image preparation is an explicit work-starting operation.++Validation: policy and schema contracts; real Docker file creation, generated+Python tests, file export, network/root-write refusal, timeout and cancellation.+The live Docker integration test is opt-in with JARVIS_SANDBOX_LIVE=1.diff --git a/docs/os-parity.md b/docs/os-parity.mdindex e77f16e504..d19baa4c90 100644--- a/docs/os-parity.md+++ b/docs/os-parity.md@@ -87,6 +87,19 @@ changes that disappear during settling do not trigger re-initialization.Regression tests use fake devices and models on Windows. Ubuntu/PipeWire,macOS audio devices and NVIDIA T600 inference have not been verified live.+## Agent code sandbox++The optional code sandbox uses the same Docker CLI and Linux image on Windows,+macOS and Linux. It is capability-probed only when used. Base installation and+startup need no Docker; unavailable or non-Linux engines return an explicit+error and never run the command on the host. Windows helper processes use the+shared no-window flag. The model/controller remains on the host, while code and+files are restricted to the container and its identity-specific volume.++Real container file/test/export, isolation, timeout and cancellation checks were+run on Windows with Docker's Linux engine. Policy/schema checks are portable.+Native macOS and Linux host execution has not been verified.+## Section windows (2026-10-08, T2)The section-window action opens Agents, Agentic IDE, Settings, Plugins, CLIs,diff --git a/dodaios/agent_chat/service.py b/dodaios/agent_chat/service.pyindex b5af542bb1..b451789672 100644--- a/dodaios/agent_chat/service.py+++ b/dodaios/agent_chat/service.py@@ -185,6 +185,18 @@ EXTERNAL_RUNTIME_RUNNERS: Final[dict[str, str]] = {}+async def society_execution_environment(session_id: str) -> str | None:+ """Where a society agent's tools execute; ``None`` when it cannot be read."""+ from dodaios.society.runtime import current_runtime+ from dodaios.society.surface import agent_id_of++ runtime = current_runtime()+ if runtime is None:+ return None+ agent = await runtime.roster.get(agent_id_of(session_id) or "")+ return None if agent is None else str(getattr(agent, "execution_environment", "local"))++def resolve_runner(provider: str, *, surface: str = "agent", runtime: str = "", account_id: str = "") -> str:@@ -1562,6 +1574,19 @@ class AgentChatService:)async def run_attempt(active_handle: TurnHandle, run_prompt: str) -> None:+ if session.surface == "society":+ environment = await society_execution_environment(session_id)+ if environment is None and runner != "brain":+ raise ValueError(+ "Agent execution environment is unavailable; native execution refused."+ )+ if environment == "sandbox" and (+ runner != "brain" or control_runner is not None or native_goal+ ):+ raise ValueError(+ "The sandbox requires a Dodaios API or local model; "+ "a native agent cannot run on the host in sandbox mode."+ )if control_runner is not None:vendor = await control_runner(active_handle, text)if vendor:diff --git a/dodaios/society/capabilities.py b/dodaios/society/capabilities.pyindex ca64c5d16e..1ad6d48d47 100644--- a/dodaios/society/capabilities.py+++ b/dodaios/society/capabilities.py@@ -164,6 +164,8 @@ def is_never_granted(tool_name: str) -> bool:def capability_id_for_tool(tool_name: str) -> str | None:"""The catalog id of a brain tool name; ``None`` for never-granted tools."""+ if tool_name == "society_sandbox":+ return "core:sandbox"if tool_name in {"society_browser", "society_browser_action"}:return "core:browser"if is_never_granted(tool_name):@@ -179,6 +181,8 @@ def capability_id_for_tool(tool_name: str) -> str | None:def tool_name_for_capability(capability_id: str) -> str | None:"""Inverse of :func:`capability_id_for_tool`; ``None`` for skills."""+ if capability_id == "core:sandbox":+ return "society_sandbox"if capability_id == "core:browser":return "society_browser"kind, _, rest = capability_id.partition(":")diff --git a/dodaios/society/events.py b/dodaios/society/events.pyindex d715ac1aeb..d5e8a7e00b 100644--- a/dodaios/society/events.py+++ b/dodaios/society/events.py@@ -131,6 +131,13 @@ class AgentApprovalMode(StrEnum):ALWAYS_ASK = "always_ask"+class ExecutionEnvironment(StrEnum):+ """Where a Dodaios agent's machine-facing tools execute."""++ LOCAL = "local"+ SANDBOX = "sandbox"++class AgentRuntime(StrEnum):"""The agent loop that executes an agent's turns (``docs/agent-runtimes.md``).diff --git a/dodaios/society/roster.py b/dodaios/society/roster.pyindex 5a689b1630..50a7af0750 100644--- a/dodaios/society/roster.py+++ b/dodaios/society/roster.py@@ -36,6 +36,7 @@ from .events import (AgentState,BrowserMode,Checkpoint,+ ExecutionEnvironment,GrantMode,KnowledgeScope,PermissionCeiling,@@ -198,6 +199,7 @@ class AgentRecord:#: The agent loop that executes turns (``AgentRuntime``); ``jarvis`` for#: every agent created before runtimes existed.runtime: AgentRuntime = AgentRuntime.JARVIS+ execution_environment: ExecutionEnvironment = ExecutionEnvironment.LOCAL@propertydef session_id(self) -> str:@@ -242,6 +244,7 @@ class AgentRecord:"browser_allowed_domains": list(self.browser_allowed_domains),"computer_id": self.computer_id,"runtime": str(self.runtime),+ "execution_environment": str(self.execution_environment),"session_id": self.session_id,"created_ms": self.created_ms,"updated_ms": self.updated_ms,@@ -293,6 +296,7 @@ class AgentRecord:],computer_id=str(row["computer_id"]) if row.get("computer_id") else None,runtime=AgentRuntime(str(row.get("runtime") or "jarvis")),+ execution_environment=ExecutionEnvironment(row.get("execution_environment") or "local"),created_ms=int(row.get("created_ms") or 0),updated_ms=int(row.get("updated_ms") or 0),)@@ -329,6 +333,7 @@ _EDITABLE: Final[frozenset[str]] = frozenset("browser_allowed_domains","computer_id","runtime",+ "execution_environment",})@@ -427,6 +432,28 @@ def _revoke_runtime_grants(agent_id: str) -> None:log.info("society: revoked %s runtime gateway grant(s) of %s", revoked, agent_id)+def _check_sandbox_placement(row: dict[str, Any]) -> None:+ if row.get("execution_environment", "local") != "sandbox":+ return+ from dodaios.agent_chat.service import resolve_runner++ if row.get("tier") == "lead" or row.get("computer_id"):+ raise RosterError(+ FailureReason.BLOCKED_BY_POLICY,+ "The code sandbox requires a local specialist or orchestrator.",+ )+ runner = resolve_runner(+ str(row.get("provider") or ""), surface="society",+ runtime=str(row.get("runtime") or "jarvis"), account_id=str(row.get("account_id") or ""),+ )+ if runner != "brain":+ raise RosterError(+ FailureReason.BLOCKED_BY_POLICY,+ "Choose a Dodaios API or local model for the code sandbox. "+ "Native CLI agents and external runtimes are not sandboxed yet.",+ )++def _check_runtime_placement(runtime: Any, computer_id: Any) -> None:"""An external runtime (Hermes, OpenClaw) runs on this computer only, for now."""if str(runtime or "jarvis") != "jarvis" and computer_id:@@ -438,6 +465,8 @@ def _check_runtime_placement(runtime: Any, computer_id: Any) -> None:def _coerce(field_name: str, value: Any) -> Any:"""Validate one editable field and return its column value."""+ if field_name == "execution_environment":+ return str(_enum(ExecutionEnvironment, value, field_name))if field_name == "name":return _validate_name(value)if field_name == "title":@@ -687,6 +716,7 @@ class Roster:if key not in _EDITABLE or key in ("title", "description", "tier"):raise RosterError(FailureReason.BLOCKED_BY_POLICY, f"unknown field {key}")row[_JSON_FIELDS.get(key, key)] = _coerce(key, value)+ _check_sandbox_placement(row)await self._store.insert_agent(row)created = await self._store.get_agent_row(agent_id)assert created is not None@@ -769,6 +799,7 @@ class Roster:columns.get("runtime", current.get("runtime")),columns.get("computer_id", current.get("computer_id")),)+ _check_sandbox_placement({**current, **columns})try:await self._store.update_agent(agent_id, columns)except sqlite3.IntegrityError as exc:diff --git a/dodaios/society/sandbox.py b/dodaios/society/sandbox.pynew file mode 100644index 0000000000..76a6d3c0fb--- /dev/null+++ b/dodaios/society/sandbox.py@@ -0,0 +1,343 @@+"""Opt-in code sandbox. Only Docker-managed volumes cross command boundaries.++The model/controller stays in Dodaios; all code runs in an unprivileged Linux+container with no host mounts, credentials, network, or Docker socket. This is+container isolation, not a separate kernel per agent. No local fallback exists.+"""++from __future__ import annotations++import asyncio+import hashlib+import json+import logging+import math+import os+import shutil+import time+import uuid+from pathlib import Path+from typing import Any++from dodaios.core.process_utils import NO_WINDOW_CREATIONFLAGS+from dodaios.core.protocols import ToolResult++log = logging.getLogger(__name__)+IMAGE = "python:3.12-slim"+MAX_FILE_BYTES = 1_000_000+OUTPUT_BYTES = 32_000+++class SandboxUnavailable(RuntimeError):+ """The requested sandbox could not execute; never retry on the host."""+++def for_agent(runtime: Any, agent_id: str) -> Sandbox:+ """Bind storage to the identity, independent of editable workspace paths."""+ return Sandbox(Path(runtime.data_dir) / "sandboxes" / agent_id)+++async def _docker(+ *args: str,+ stdin: bytes = b"",+ timeout_s: float = 30,+) -> tuple[int, bytes]:+ exe = shutil.which("docker")+ if exe is None:+ raise SandboxUnavailable(+ "Install and start Docker with Linux containers to use the sandbox."+ )+ try:+ process = await asyncio.create_subprocess_exec(+ exe,+ *args,+ stdin=asyncio.subprocess.PIPE,+ stdout=asyncio.subprocess.PIPE,+ stderr=asyncio.subprocess.STDOUT,+ creationflags=NO_WINDOW_CREATIONFLAGS,+ )+ except OSError as exc:+ raise SandboxUnavailable(f"Docker could not start: {exc}") from exc+ output = bytearray()++ async def exchange() -> None:+ assert process.stdin is not None and process.stdout is not None++ async def feed() -> None:+ try:+ process.stdin.write(stdin)+ await process.stdin.drain()+ process.stdin.close()+ except (BrokenPipeError, ConnectionResetError):+ # A rejected Docker launch can close stdin before reading it.+ log.debug("sandbox Docker stdin closed before input was consumed")++ async def read() -> None:+ while chunk := await process.stdout.read(65536):+ # Drain every byte without retaining unbounded model-controlled output.+ remaining = MAX_FILE_BYTES * 2 - len(output)+ if remaining > 0:+ output.extend(chunk[:remaining])++ await asyncio.gather(feed(), read())+ await process.wait()++ try:+ await asyncio.wait_for(exchange(), timeout_s)+ finally:+ if process.returncode is None:+ process.kill()+ await process.wait()+ return process.returncode or 0, bytes(output)+++async def status() -> dict[str, Any]:+ """Probe only on explicit feature use; never pull an image in a probe."""+ try:+ rc, out = await _docker("info", "--format", "{{.OSType}}", timeout_s=30)+ if rc or out.strip() != b"linux":+ raise SandboxUnavailable("Start Docker with Linux containers.")+ rc, _ = await _docker("image", "inspect", IMAGE, timeout_s=30)+ return {+ "available": not rc,+ "image": IMAGE,+ "needs_image": bool(rc),+ "message": "Download the sandbox image to continue." if rc else "",+ }+ except (SandboxUnavailable, TimeoutError) as exc:+ log.debug("sandbox readiness unavailable: %s", exc)+ return {+ "available": False,+ "image": IMAGE,+ "needs_image": False,+ "message": str(exc) or "Docker did not answer in time.",+ }+++async def prepare() -> dict[str, Any]:+ """Explicit user action: download the fixed runtime image."""+ rc, out = await _docker("pull", IMAGE, timeout_s=300)+ if rc:+ raise SandboxUnavailable(out.decode("utf-8", "replace")[-2000:])+ return await status()+++class Sandbox:+ """One persistent volume per agent workspace, one disposable container per call."""++ def __init__(self, workspace: Path) -> None:+ # Only the name is derived here; nothing on the host is read or created.+ namespace = os.path.abspath(workspace).encode("utf-8")+ self.volume = "jarvis-sandbox-" + hashlib.sha256(namespace).hexdigest()[:24]++ def _arguments(+ self,+ name: str,+ *,+ initialize: bool = False,+ timeout_s: float = 120,+ ) -> list[str]:+ return [+ "run",+ "--rm",+ "--init",+ "--pull=never",+ "-i",+ "--name",+ name,+ "--label",+ "personal-jarvis.sandbox=true",+ "--network",+ "none",+ "--cpus",+ "1",+ "--memory",+ "512m",+ "--memory-swap",+ "512m",+ "--pids-limit",+ "128",+ "--ulimit",+ "fsize=16777216:16777216",+ "--cap-drop",+ "ALL",+ "--security-opt",+ "no-new-privileges",+ "--read-only",+ "--tmpfs",+ "/tmp:rw,nosuid,nodev,size=64m", # noqa: S108 — private container tmpfs+ "--user",+ "0:0" if initialize else "65532:65532",+ "--mount",+ f"type=volume,src={self.volume},dst=/workspace,volume-nocopy",+ "--workdir",+ "/workspace",+ "--env",+ "HOME=/workspace",+ "--env",+ "PYTHONIOENCODING=utf-8",+ "--env",+ "PYTHONDONTWRITEBYTECODE=1",+ # An in-container deadline also ends work after a host crash.+ "--entrypoint",+ "/usr/bin/timeout",+ IMAGE,+ "--kill-after=2s",+ f"{math.ceil(timeout_s)}s",+ "/bin/sh",+ "-s",+ ]++ async def _run(+ self,+ command: bytes,+ timeout_s: float,+ *,+ initialize: bool = False,+ ) -> tuple[int, bytes]:+ name = "jarvis-sandbox-run-" + uuid.uuid4().hex+ try:+ return await _docker(+ *self._arguments(name, initialize=initialize, timeout_s=timeout_s),+ stdin=command,+ timeout_s=timeout_s + 10,+ )+ finally:+ # Killing the CLI alone leaves its container alive. Remove exactly our+ # own container on success, cancellation, disconnect and timeout.+ cleanup = asyncio.create_task(_docker("rm", "--force", name, timeout_s=15))+ try:+ await asyncio.shield(cleanup)+ except asyncio.CancelledError:+ await cleanup+ raise+ except (SandboxUnavailable, TimeoutError):+ log.warning("could not reap sandbox container %s", name, exc_info=True)++ async def execute(self, command: str, timeout_s: float = 120) -> tuple[int, bytes]:+ if not math.isfinite(timeout_s):+ timeout_s = 120+ timeout_s = max(1, min(timeout_s, 900))+ # This fixed bootstrap cannot execute workspace contents. Volumes are+ # mounted without copying image content and never bind a host directory.+ rc, out = await self._run(b"chmod 777 /workspace\n", 30, initialize=True)+ if rc:+ raise SandboxUnavailable(out.decode("utf-8", "replace")[-2000:])+ result = await self._run(command.encode("utf-8"), timeout_s)+ if result[0] == 124:+ raise TimeoutError("Sandbox command timed out.")+ return result++ async def file(self, action: str, path: str = ".", content: str = "") -> tuple[int, bytes]:+ payload = json.dumps({"action": action, "path": path, "content": content})+ # JSON is Python source only as a quoted string literal, never shell code.+ program = _FILE_PROGRAM.replace("PAYLOAD", repr(payload))+ return await self.execute(+ "python -I - <<'JARVIS_SANDBOX_FILE'\n" + program + "\nJARVIS_SANDBOX_FILE\n", 30+ )+++_FILE_PROGRAM = """import base64, json+from pathlib import Path+p = json.loads(PAYLOAD)+root = Path('/workspace')+target = (root / p['path']).resolve()+if not target.is_relative_to(root):+ raise ValueError('Path must stay inside the sandbox workspace')+if p['action'] == 'write':+ data = p['content'].encode('utf-8')+ if len(data) > 1000000:+ raise ValueError('File exceeds 1 MB')+ target.parent.mkdir(parents=True, exist_ok=True)+ target.write_bytes(data)+ print(json.dumps({'path': str(target.relative_to(root)), 'bytes': len(data)}))+elif p['action'] == 'list':+ print(json.dumps([{'name': x.name, 'directory': x.is_dir()}+ for x in sorted(target.iterdir())[:200]]))+else:+ if not target.is_file():+ raise ValueError('Choose a regular file')+ with target.open('rb') as f:+ data = f.read(1000001)+ if len(data) > 1000000:+ raise ValueError('File exceeds 1 MB')+ if p['action'] == 'download':+ print(base64.b64encode(data).decode('ascii'))+ else:+ print(data.decode('utf-8', errors='replace'))+"""+++class SandboxTool:+ """The only machine-facing hand exposed to a sandbox agent."""++ name = "society_sandbox"+ description = (+ "Run code and tests or write/read/list files in your isolated Linux sandbox. "+ "Python 3.12 is available. Files persist between calls. No network, host files, "+ "credentials, browser or plugins. Use relative paths under /workspace. "+ "Return file paths so the user can download results from the agent settings."+ )+ risk_tier = "monitor"+ schema = {+ "type": "object",+ "properties": {+ "action": {"type": "string", "enum": ["run", "write", "read", "list"]},+ "command": {"type": "string"},+ "path": {"type": "string"},+ "content": {"type": "string"},+ "timeout_s": {"type": "number"},+ },+ "required": ["action"],+ }++ def __init__(self, runtime: Any, agent_id: str, workspace: Path) -> None:+ self.runtime, self.agent_id = runtime, agent_id+ self.sandbox = for_agent(runtime, agent_id)++ def risk_tier_for_args(self, args: dict[str, Any]) -> str:+ return "safe" if args.get("action") in ("read", "list") else "monitor"++ def read_only_for_args(self, args: dict[str, Any]) -> bool:+ return args.get("action") in ("read", "list")++ async def execute(self, args: dict[str, Any], ctx: Any) -> ToolResult:+ agent = await self.runtime.roster.get(self.agent_id)+ if (+ agent is None+ or str(agent.state) != "active"+ or getattr(agent, "execution_environment", "local") != "sandbox"+ or await self.runtime.store.kill_switch()+ ):+ return ToolResult(False, None, "Sandbox execution is no longer enabled.")+ action = args.get("action")+ started = time.monotonic()+ try:+ if action == "run":+ command = str(args.get("command") or "")+ if not command.strip() or len(command) > MAX_FILE_BYTES:+ raise ValueError("Supply a command shorter than 1 MB.")+ rc, out = await self.sandbox.execute(command, float(args.get("timeout_s") or 120))+ elif action in ("read", "write", "list"):+ content = str(args.get("content") or "")+ if len(content.encode("utf-8")) > MAX_FILE_BYTES:+ raise ValueError("File exceeds 1 MB.")+ rc, out = await self.sandbox.file(+ str(action), str(args.get("path") or "."), content+ )+ else:+ raise ValueError("Unknown sandbox action.")+ except (SandboxUnavailable, TimeoutError, ValueError) as exc:+ log.info("sandbox action %s for %s failed: %s", action, self.agent_id, exc)+ return ToolResult(False, None, str(exc) or "Sandbox command timed out.")+ return ToolResult(+ rc == 0,+ {+ "output": out[:OUTPUT_BYTES].decode("utf-8", "replace"),+ "truncated": len(out) > OUTPUT_BYTES,+ "exit_code": rc,+ "seconds": round(time.monotonic() - started, 2),+ "environment": "sandbox",+ },+ None if rc == 0 else f"Sandbox exited with status {rc}.",+ )diff --git a/dodaios/society/society_schema.sql b/dodaios/society/society_schema.sqlindex 1103888d9f..cb82dd89c8 100644--- a/dodaios/society/society_schema.sql+++ b/dodaios/society/society_schema.sql@@ -49,6 +49,8 @@ CREATE TABLE IF NOT EXISTS society_agents (-- Where the agent's work executes: NULL = this computer, else the id of a-- connected machine in dodaios/computers (a VPS or a local VM, over SSH).computer_id TEXT DEFAULT NULL,+ execution_environment TEXT NOT NULL DEFAULT 'local'+ CHECK (execution_environment IN ('local', 'sandbox')),runtime TEXT NOT NULL DEFAULT 'jarvis'CHECK (runtime IN ('jarvis', 'hermes', 'openclaw')),created_ms INTEGER NOT NULL,diff --git a/dodaios/society/store.py b/dodaios/society/store.pyindex 694d693f7f..56fcdcff50 100644--- a/dodaios/society/store.py+++ b/dodaios/society/store.py@@ -171,6 +171,13 @@ class SocietyStore:"CHECK (runtime IN ('jarvis', 'hermes', 'openclaw'))")log.info("society store: migration applied — added runtime")+ if "execution_environment" not in existing:+ await self.conn.execute(+ "ALTER TABLE society_agents ADD COLUMN execution_environment "+ "TEXT NOT NULL DEFAULT 'local' "+ "CHECK (execution_environment IN ('local', 'sandbox'))"+ )+ log.info("society store: added execution_environment")await self._migrate_chat_groups()await self._migrate_checkpoint_vocabulary()diff --git a/dodaios/society/surface.py b/dodaios/society/surface.pyindex 3a5f61a378..1e055ce17f 100644--- a/dodaios/society/surface.py+++ b/dodaios/society/surface.py@@ -197,6 +197,8 @@ async def _scoped_tool_for_session(session_id: str, capability: str) -> Tool | Nagent = await rt.roster.get(agent_id)if agent is None or str(agent.state) != "active":return None+ if getattr(agent, "execution_environment", "local") == "sandbox":+ return Noneread_only = str(agent.permission_ceiling) == "safe" or session.permission_mode in ("plan", "read-only")@@ -286,6 +288,19 @@ def society_tools(cfg: Any, brain: Any, session: Any) -> dict[str, Tool]:if rt is None or agent_id is None:return {}workspace = Path(getattr(session, "cwd", "") or _workspace_fallback(cfg, agent_id))+ agent = rt.cached_agent(agent_id)+ if agent is not None and getattr(agent, "execution_environment", "local") == "sandbox":+ from .sandbox import SandboxTool++ sandbox_tools: dict[str, Tool] = {+ SandboxTool.name: cast(Tool, SandboxTool(rt, agent_id, workspace)),+ }+ session_id = str(getattr(session, "session_id", "") or "")+ if not is_routine_session(session_id):+ sandbox_tools[ASK_USER_TOOL_NAME] = cast(+ Tool, AskUserTool(rt, agent_id, session_id=session_id)+ )+ return sandbox_toolstools: dict[str, Tool] = {}# The folder tools of the chat surface, contained: on the society surface the# kit's tools REPLACE the folder tools (runner_brain.build_override), so the@@ -380,6 +395,7 @@ class _GatedTool:) -> None:self._inner = innerself._agent = agent+ self._execution_environment = getattr(agent, "execution_environment", "local")self._capability_id = capability_idself._approval_mode = approval_modeself._runtime = runtime@@ -473,6 +489,8 @@ class _GatedTool:return ToolResult(False, {"reason": "blocked_by_policy"}, "caller is not an active agent")+ if getattr(live, "execution_environment", "local") != self._execution_environment:+ return ToolResult(False, None, "Execution environment changed; start a new turn.")if self._session_id and (session is Noneor str(getattr(session, "session_id", "")) != self._session_id@@ -574,6 +592,27 @@ async def remember_always_allow(session: Any, tool_name: str, args: dict[str, Anreturn True+class _LocalReportingTool:+ """A cache miss may not expose host reporting tools to a sandbox identity."""++ def __init__(self, inner: Any, runtime: Any, agent_id: str) -> None:+ self._inner, self._runtime, self._agent_id = inner, runtime, agent_id++ def __getattr__(self, name: str) -> Any:+ return getattr(self._inner, name)++ async def execute(self, args: dict[str, Any], ctx: Any) -> ToolResult:+ agent = await self._runtime.roster.get(self._agent_id)+ if agent is None or str(agent.state) != "active":+ return ToolResult(False, None, "Agent execution environment is unavailable.")+ if (+ getattr(agent, "execution_environment", "local") == "sandbox"+ and not isinstance(self._inner, AskUserTool)+ ):+ return ToolResult(False, None, "Host tools are unavailable in the sandbox.")+ return await self._inner.execute(args, ctx)++class _ContainedTool:"""A folder tool whose path arguments must stay inside the workspace."""@@ -660,13 +699,34 @@ def society_tool_filter(session: Any) -> Callable[[dict[str, Tool]], dict[str, T# neither report back nor ask the user, and the job stalls silently# (#255).return lambda tools: {- n: t+ n: cast(Tool, _LocalReportingTool(t, rt, agent_id))for n, t in tools.items()if n.startswith(_OWN_PREFIX) and getattr(t, "risk_tier", "monitor") == "safe"}approval_mode = _effective_approval_mode(agent, session, _permission_override(rt, session))def _apply(tools: dict[str, Tool]) -> dict[str, Tool]:+ if getattr(agent, "execution_environment", "local") == "sandbox":+ from .sandbox import SandboxTool++ # Only our bound implementation and information questions cross this+ # boundary. Tool names or society prefixes cannot grant host access.+ return {+ name: cast(Tool, _GatedTool(+ tool, agent, "core:sandbox", approval_mode, rt,+ session=session, requires_grant=True,+ ))+ for name, tool in tools.items()+ if isinstance(tool, SandboxTool)+ and tool.agent_id == agent.agent_id and tool.runtime is rt+ and name in select_tools(+ {name: tool}, grant_mode=str(agent.grant_mode), grants=agent.grants,+ focus=agent.focus, denies=agent.denies,+ )+ } | {+ name: tool for name, tool in tools.items()+ if name == ASK_USER_TOOL_NAME and isinstance(tool, AskUserTool)+ }own = {n: tfor n, t in tools.items()@@ -781,6 +841,16 @@ async def society_system_extra(cfg: Any, brain: Any, session: Any) -> str:# The briefing is built once per turn: this is where the island learns that a# turn started, whoever started it (a typed message never passes the scheduler).rt.checkpoints.note_turn_started(agent.agent_id, str(getattr(session, "session_id", "")))+ if getattr(agent, "execution_environment", "local") == "sandbox":+ return (+ f"You are {agent.name}. {agent.description}\n"+ "Execution environment: isolated Linux code sandbox, Python 3.12. "+ "Use society_sandbox for ALL files and commands. No host tools, network, "+ "credentials, browser, plugins or delegation are available. "+ "Files under /workspace persist; use relative paths. Run tests and report "+ "actual results. Give output paths for download in the agent settings. "+ "Do not claim to have accessed the host. Answer in the user's language."+ )catalog = rt.catalog()roster = await rt.roster.list()browser = await asyncio.to_thread(rt.browser.status_for, agent)diff --git a/dodaios/ui/web/frontend/src/components/society/card/AgentSandboxSection.test.tsx b/dodaios/ui/web/frontend/src/components/society/card/AgentSandboxSection.test.tsxnew file mode 100644index 0000000000..893600248f--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/society/card/AgentSandboxSection.test.tsx@@ -0,0 +1,50 @@+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";+import { afterEach, expect, test, vi } from "vitest";+import type { SocietyAgent } from "../data";+import { AgentSandboxSection } from "./AgentSandboxSection";++vi.mock("@/i18n", () => ({ useT: () => (key: string) => key }));+afterEach(() => { cleanup(); vi.unstubAllGlobals(); });+const agent = { agentId: "sandbox-user", runtime: "jarvis", executionEnvironment: "sandbox" } as SocietyAgent;+function mount(value = agent) {+ return render(<QueryClientProvider client={new QueryClient({ defaultOptions: { queries: { retry: false } } })}>+ <AgentSandboxSection agent={value} />+ </QueryClientProvider>);+}++test("ready sandbox browses and downloads results from its own agent", async () => {+ const fetcher = vi.fn(async (url: string) => new Response(JSON.stringify(+ url === "/api/society/sandbox" ? { available: true }+ : { files: [{ name: "result.txt", directory: false }, { name: "sub", directory: true }] },+ )));+ vi.stubGlobal("fetch", fetcher);+ mount();+ const link = await screen.findByRole("link", { name: "result.txt" });+ expect(link.getAttribute("href")).toBe("/api/society/agents/sandbox-user/sandbox/file?path=result.txt");+ fireEvent.click(screen.getByRole("button", { name: "sub/" }));+ await waitFor(() => expect(fetcher).toHaveBeenCalledWith(+ "/api/society/agents/sandbox-user/sandbox/files?path=sub", undefined,+ ));+});++test("unavailable runtime displays the error without requesting files", async () => {+ const fetcher = vi.fn(async () => new Response(JSON.stringify({ available: false, message: "Docker is stopped" })));+ vi.stubGlobal("fetch", fetcher);+ mount();+ await screen.findByText("Docker is stopped");+ expect(fetcher.mock.calls.length).toBe(1);+});++test("rejected environment selection keeps the saved environment", async () => {+ const fetcher = vi.fn(async () => new Response(JSON.stringify({ detail: { detail: "Choose an API model" } }), { status: 409 }));+ vi.stubGlobal("fetch", fetcher);+ mount({ ...agent, executionEnvironment: "local" });+ fireEvent.click(screen.getByRole("combobox"));+ fireEvent.click(await screen.findByRole("option", { name: "society.sandbox.code" }));+ await screen.findByRole("alert");+ expect(screen.getByRole("combobox").textContent).toContain("society.sandbox.local");+ expect(fetcher).toHaveBeenCalledWith("/api/society/agents/sandbox-user", expect.objectContaining({+ method: "PATCH", body: JSON.stringify({ execution_environment: "sandbox" }),+ }));+});diff --git a/dodaios/ui/web/frontend/src/components/society/card/AgentSandboxSection.tsx b/dodaios/ui/web/frontend/src/components/society/card/AgentSandboxSection.tsxnew file mode 100644index 0000000000..0a4b109c34--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/society/card/AgentSandboxSection.tsx@@ -0,0 +1,94 @@+import { useState } from "react";+import { useQuery, useQueryClient } from "@tanstack/react-query";+import { Button } from "@/components/ui/button";+import { BrandedSelect } from "@/components/ui/select";+import { useT } from "@/i18n";+import type { SocietyAgent } from "../data";++async function json<T>(url: string, init?: RequestInit): Promise<T> {+ const response = await fetch(url, init);+ const body = await response.json();+ if (!response.ok) {+ throw new Error(typeof body.detail === "string" ? body.detail : body.detail?.detail ?? "Sandbox request failed");+ }+ return body as T;+}++export function SandboxChoice({ value, onChange, disabled = false }: {+ value: "local" | "sandbox"; onChange: (value: "local" | "sandbox") => void; disabled?: boolean;+}) {+ const t = useT();+ return <div className="flex flex-col gap-2 text-sm">+ <span className="font-medium">{t("society.sandbox.environment")}</span>+ <BrandedSelect ariaLabel={t("society.sandbox.environment")} value={value} disabled={disabled}+ onValueChange={(next) => onChange(next as "local" | "sandbox")}+ options={[+ { value: "local", label: t("society.sandbox.local") },+ { value: "sandbox", label: t("society.sandbox.code") },+ ]} />+ {value === "sandbox" ? <span className="text-xs text-muted-foreground">{t("society.sandbox.scope")}</span> : null}+ </div>;+}++export function AgentSandboxSection({ agent }: { agent: SocietyAgent }) {+ const t = useT();+ const client = useQueryClient();+ const [error, setError] = useState("");+ const [busy, setBusy] = useState(false);+ const [path, setPath] = useState(".");+ const enabled = agent.executionEnvironment === "sandbox";+ const base = `/api/society/agents/${encodeURIComponent(agent.agentId)}/sandbox`;+ const ready = useQuery({+ queryKey: ["society", "sandbox", "status"], enabled, retry: false,+ queryFn: () => json<{ available: boolean; needs_image: boolean; message: string }>("/api/society/sandbox"),+ });+ const files = useQuery({+ queryKey: ["society", "sandbox", agent.agentId, path],+ enabled: enabled && ready.data?.available === true, retry: false,+ queryFn: () => json<{ files: { name: string; directory: boolean }[] }>(`${base}/files?path=${encodeURIComponent(path)}`),+ });+ async function perform(work: () => Promise<unknown>) {+ setBusy(true); setError("");+ try { await work(); } catch (exc) { setError(exc instanceof Error ? exc.message : String(exc)); }+ finally { setBusy(false); }+ }+ return <section className="flex flex-col gap-3" data-testid="agent-sandbox">+ <SandboxChoice value={enabled ? "sandbox" : "local"} disabled={busy || agent.runtime !== "jarvis" && !!agent.runtime}+ onChange={(value) => void perform(async () => {+ await json(`/api/society/agents/${encodeURIComponent(agent.agentId)}`, {+ method: "PATCH", headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ execution_environment: value }),+ });+ await client.invalidateQueries({ queryKey: ["society", "roster"] });+ })} />+ {enabled ? <>+ <p className="text-xs text-muted-foreground">{t("society.sandbox.storage")}</p>+ {ready.isLoading ? <p role="status">{t("society.sandbox.checking")}</p> : null}+ {ready.data?.message ? <p role="status" className="text-xs">{ready.data.message}</p> : null}+ {ready.data?.needs_image ? <Button disabled={busy} onClick={() => void perform(async () => {+ await json("/api/society/sandbox/prepare", { method: "POST" });+ await ready.refetch();+ })}>{t("society.sandbox.prepare")}</Button> : null}+ <div className="flex items-center gap-2">+ <Button size="sm" disabled={busy} onClick={() => void perform(async () => {+ const result = await ready.refetch();+ if (result.data?.available) await files.refetch();+ })}>{t("society.sandbox.refresh")}</Button>+ {path !== "." ? <Button size="sm" variant="ghost" onClick={() => setPath(".")}>{t("society.sandbox.root")}</Button> : null}+ <span className="truncate text-xs text-muted-foreground">{path}</span>+ </div>+ {files.isLoading ? <p role="status">{t("society.sandbox.loading")}</p> : null}+ {files.data?.files.length === 0 ? <p className="text-xs text-muted-foreground">{t("society.sandbox.empty")}</p> : null}+ <ul className="space-y-1 text-sm">+ {files.data?.files.map((file) => {+ const child = path === "." ? file.name : `${path}/${file.name}`;+ return <li key={file.name} className="break-all">+ {file.directory ? <button className="text-accent underline" onClick={() => setPath(child)}>{file.name}/</button>+ : <a className="text-accent underline" href={`${base}/file?path=${encodeURIComponent(child)}`} download>{file.name}</a>}+ </li>;+ })}+ </ul>+ </> : null}+ {error || ready.error || files.error ? <p role="alert" className="text-xs text-destructive">{error || ready.error?.message || files.error?.message}</p> : null}+ </section>;+}diff --git a/dodaios/ui/web/frontend/src/components/society/card/AgentSpecSheet.tsx b/dodaios/ui/web/frontend/src/components/society/card/AgentSpecSheet.tsxindex 907c3344a3..27743ed0e0 100644--- a/dodaios/ui/web/frontend/src/components/society/card/AgentSpecSheet.tsx+++ b/dodaios/ui/web/frontend/src/components/society/card/AgentSpecSheet.tsx@@ -45,6 +45,7 @@ import { cn } from "@/lib/utils";import { useEventStore } from "@/store/events";import { AgentRoutinesList } from "./AgentRoutinesList";+import { AgentSandboxSection } from "./AgentSandboxSection";import { RetireButton } from "./RetireButton";import { CapabilityChip } from "../CapabilityChip";import { useAgentActivity, useAgentSkills, type AgentActivity } from "../cardData";@@ -371,7 +372,8 @@ export function AgentSpecSheet({ agent, onOpenChat, onRetired }: AgentSpecSheetP</section>) : null}- {agent.tier !== "lead" && <RunsOnSection agent={agent} />}+ {agent.tier !== "lead" && <AgentSandboxSection agent={agent} />}+ {agent.tier !== "lead" && agent.executionEnvironment !== "sandbox" && <RunsOnSection agent={agent} />}<LimitsSectionagent={agent}diff --git a/dodaios/ui/web/frontend/src/components/society/create/CreateAgentDialog.tsx b/dodaios/ui/web/frontend/src/components/society/create/CreateAgentDialog.tsxindex 8ac01b9a75..87f0eae135 100644--- a/dodaios/ui/web/frontend/src/components/society/create/CreateAgentDialog.tsx+++ b/dodaios/ui/web/frontend/src/components/society/create/CreateAgentDialog.tsx@@ -21,6 +21,7 @@ import { AgentNameTaken, RuntimeProviderUnsupported, useCreateSocietyAgent } froimport { defaultCompanion, type CompanionAppearance } from "../companion/appearance";import { randomCreature } from "../companion/creature";import { RuntimeChoice, useAgentRuntimes } from "../card/RuntimePicker";+import { SandboxChoice } from "../card/AgentSandboxSection";import { modelSeats, runtimeSeats } from "../chat/modelChoices";import { useModelMenuData } from "../chat/useModelMenuData";import { accountChoice, accountHint } from "./brainPicker";@@ -58,6 +59,7 @@ function CreateAgentDialog() {const runtimes = useAgentRuntimes();const [name, setName] = useState("");const [runtime, setRuntime] = useState<AgentRuntime>("jarvis");+ const [executionEnvironment, setExecutionEnvironment] = useState<"local" | "sandbox">("local");const [providerId, setProviderId] = useState("");const [access, rememberAccess] = useModelAccess();const [model, setModel] = useState("");@@ -120,6 +122,7 @@ function CreateAgentDialog() {const agent = await createAgent({name,runtime,+ executionEnvironment: external ? "local" : executionEnvironment,provider: option?.seat.provider.id,model: option ? modelValue : undefined,accountId: option ? accountValue || option.accountId : undefined,@@ -218,6 +221,7 @@ function CreateAgentDialog() {/>) : null}+ {!external ? <SandboxChoice value={executionEnvironment} onChange={setExecutionEnvironment} disabled={saving} /> : null}{chosen && option && accounts.length ? (<div className="flex flex-col gap-1.5 text-sm"><span className="font-medium">{t("society.create_agent.account_label")}</span>diff --git a/dodaios/ui/web/frontend/src/components/society/data.ts b/dodaios/ui/web/frontend/src/components/society/data.tsindex 8162797f3f..0f41ce6a38 100644--- a/dodaios/ui/web/frontend/src/components/society/data.ts+++ b/dodaios/ui/web/frontend/src/components/society/data.ts@@ -140,6 +140,7 @@ export interface SocietyAgent {accountId?: string;/** Where the agent runs: null/absent = this computer, else a connected computer id. */computerId?: string | null;+ executionEnvironment?: "local" | "sandbox";/** The agent loop that runs its turns (docs/agent-runtimes.md); absent = Jarvis. */runtime?: AgentRuntime;/** The character: archetype, base, parts, palette. null = the palette tile. */@@ -261,6 +262,7 @@ export function rowToAgent(row: SocietyAgentRow): SocietyAgent {model: row.model,accountId: row.account_id,computerId: row.computer_id ?? null,+ executionEnvironment: row.execution_environment ?? "local",runtime: row.runtime ?? "jarvis",effort: row.effort,figure,@@ -453,6 +455,7 @@ export function useQuickCreateAgent() {/** What the create dialog sends; every field may be left out. */export interface NewAgentChoice {+ executionEnvironment?: "local" | "sandbox";/** Empty = a placeholder name; the agent proposes its own in its first chat. */name?: string;/** Fixed for the agent's life (docs/agent-runtimes.md). */@@ -477,6 +480,7 @@ export function useCreateSocietyAgent() {const client = useQueryClient();return useCallback(async (choice: NewAgentChoice = {}): Promise<SocietyAgent> => {const body: Record<string, unknown> = { tier: "specialist" };+ if (choice.executionEnvironment) body.execution_environment = choice.executionEnvironment;if (choice.name?.trim()) body.name = choice.name.trim();if (choice.runtime && choice.runtime !== "jarvis") body.runtime = choice.runtime;if (choice.provider) {diff --git a/dodaios/ui/web/frontend/src/i18n/locales/de.json b/dodaios/ui/web/frontend/src/i18n/locales/de.jsonindex bbe1ec7df8..d61158d34a 100644--- a/dodaios/ui/web/frontend/src/i18n/locales/de.json+++ b/dodaios/ui/web/frontend/src/i18n/locales/de.json@@ -6467,6 +6467,19 @@"mode_pipeline": "Stimme rein und raus"},"society": {+ "sandbox": {+ "environment": "Ausführungsumgebung",+ "local": "Dieser Computer",+ "code": "Code-Sandbox",+ "scope": "Dodaios mit API- oder lokalem Modell. Python-Code und Dateien bleiben in einem Linux-Container. Netzwerk, Desktop, Plugins und Host-Dateien sind nicht verfügbar.",+ "storage": "Dateien bleiben in der Sandbox. Downloads sind auf 1 MB begrenzt; Befehle enden mit dem Stoppen-Knopf im Chat.",+ "checking": "Sandbox wird geprüft…",+ "prepare": "Laufzeit herunterladen",+ "refresh": "Dateien aktualisieren",+ "root": "Arbeitsverzeichnis",+ "loading": "Dateien werden geladen…",+ "empty": "Noch keine Dateien."+ },"lead": {"tab": "Leitung","loading": "Team wird geladen…",diff --git a/dodaios/ui/web/frontend/src/i18n/locales/en.json b/dodaios/ui/web/frontend/src/i18n/locales/en.jsonindex 87ad7b95a0..55ef9dd0e6 100644--- a/dodaios/ui/web/frontend/src/i18n/locales/en.json+++ b/dodaios/ui/web/frontend/src/i18n/locales/en.json@@ -6467,6 +6467,19 @@"mode_pipeline": "voice in and out"},"society": {+ "sandbox": {+ "environment": "Execution environment",+ "local": "This computer",+ "code": "Code sandbox",+ "scope": "Dodaios API and local models. Python code and files stay in a Linux container. Network, desktop, plugins and host files are unavailable.",+ "storage": "Files remain in the sandbox. Downloads are limited to 1 MB; commands stop with the chat Stop button.",+ "checking": "Checking sandbox…",+ "prepare": "Download runtime",+ "refresh": "Refresh files",+ "root": "Workspace",+ "loading": "Loading files…",+ "empty": "No files yet."+ },"lead": {"tab": "Lead","loading": "Loading the team…",diff --git a/dodaios/ui/web/frontend/src/i18n/locales/es.json b/dodaios/ui/web/frontend/src/i18n/locales/es.jsonindex e87efd6ae1..b4af009b35 100644--- a/dodaios/ui/web/frontend/src/i18n/locales/es.json+++ b/dodaios/ui/web/frontend/src/i18n/locales/es.json@@ -6467,6 +6467,19 @@"mode_pipeline": "voz de entrada y salida"},"society": {+ "sandbox": {+ "environment": "Entorno de ejecución",+ "local": "Este ordenador",+ "code": "Sandbox de código",+ "scope": "Dodaios con API o modelo local. El código Python y los archivos permanecen en un contenedor Linux. Sin red, escritorio, plugins ni archivos del equipo.",+ "storage": "Los archivos permanecen en el sandbox. Descargas de hasta 1 MB; detén los comandos con el botón Detener del chat.",+ "checking": "Comprobando sandbox…",+ "prepare": "Descargar entorno",+ "refresh": "Actualizar archivos",+ "root": "Directorio de trabajo",+ "loading": "Cargando archivos…",+ "empty": "Todavía no hay archivos."+ },"lead": {"tab": "Líder","loading": "Cargando el equipo…",diff --git a/dodaios/ui/web/frontend/src/i18n/locales/pt.json b/dodaios/ui/web/frontend/src/i18n/locales/pt.jsonindex bf6b9b64ef..518a39f9dc 100644--- a/dodaios/ui/web/frontend/src/i18n/locales/pt.json+++ b/dodaios/ui/web/frontend/src/i18n/locales/pt.json@@ -6467,6 +6467,19 @@"mode_pipeline": "voz de entrada e saída"},"society": {+ "sandbox": {+ "environment": "Ambiente de execução",+ "local": "Este computador",+ "code": "Sandbox de código",+ "scope": "Dodaios com API ou modelo local. O código Python e os ficheiros ficam num contentor Linux. Rede, ambiente de trabalho, plugins e ficheiros do computador não estão disponíveis.",+ "storage": "Os ficheiros ficam na sandbox. As transferências estão limitadas a 1 MB; os comandos param com o botão Parar do chat.",+ "checking": "A verificar a sandbox…",+ "prepare": "Transferir o runtime",+ "refresh": "Atualizar ficheiros",+ "root": "Área de trabalho",+ "loading": "A carregar ficheiros…",+ "empty": "Ainda não há ficheiros."+ },"lead": {"tab": "Líder","loading": "A carregar a equipa…",diff --git a/dodaios/ui/web/frontend/src/i18n/locales/zh.json b/dodaios/ui/web/frontend/src/i18n/locales/zh.jsonindex f56f5979c3..892df33889 100644--- a/dodaios/ui/web/frontend/src/i18n/locales/zh.json+++ b/dodaios/ui/web/frontend/src/i18n/locales/zh.json@@ -6467,6 +6467,19 @@"mode_pipeline": "语音输入和输出"},"society": {+ "sandbox": {+ "environment": "执行环境",+ "local": "此电脑",+ "code": "代码沙箱",+ "scope": "适用于 Dodaios API 或本地模型。Python 代码和文件保留在 Linux 容器中,无法使用网络、桌面、插件或主机文件。",+ "storage": "文件保留在沙箱中。下载上限为 1 MB;可用聊天中的停止按钮结束命令。",+ "checking": "正在检查沙箱…",+ "prepare": "下载运行环境",+ "refresh": "刷新文件",+ "root": "工作目录",+ "loading": "正在加载文件…",+ "empty": "暂无文件。"+ },"lead": {"tab": "负责人","loading": "正在加载团队…",diff --git a/dodaios/ui/web/frontend/src/lib/societyApi.ts b/dodaios/ui/web/frontend/src/lib/societyApi.tsindex b49f5d3119..0a12bdd39a 100644--- a/dodaios/ui/web/frontend/src/lib/societyApi.ts+++ b/dodaios/ui/web/frontend/src/lib/societyApi.ts@@ -25,6 +25,9 @@ export type MsgType = (typeof MSG_TYPES)[number];export const TIERS = ["lead", "orchestrator", "specialist"] as const;export type Tier = (typeof TIERS)[number];+export const EXECUTION_ENVIRONMENTS = ["local", "sandbox"] as const;+export type ExecutionEnvironment = (typeof EXECUTION_ENVIRONMENTS)[number];+export const AGENT_STATES = ["active", "paused", "archived"] as const;export type AgentState = (typeof AGENT_STATES)[number];@@ -182,6 +185,7 @@ export interface SocietyAgentRow {browser_allowed_domains: string[];/** Where the agent runs: null = this computer, else a connected computer id. */computer_id: string | null;+ execution_environment?: ExecutionEnvironment;/** The agent loop that runs its turns: Jarvis, Hermes or OpenClaw. */runtime: AgentRuntime;session_id: string;diff --git a/dodaios/ui/web/society_routes.py b/dodaios/ui/web/society_routes.pyindex c38eb40c75..f5e5fe56cf 100644--- a/dodaios/ui/web/society_routes.py+++ b/dodaios/ui/web/society_routes.py@@ -26,7 +26,7 @@ from starlette.requests import HTTPConnectionfrom dodaios.core.protocols import started_by_userfrom dodaios.society.companion import CompanionSkinfrom dodaios.society.display_name import display_name, display_row-from dodaios.society.events import MsgType+from dodaios.society.events import ExecutionEnvironment, MsgTypefrom dodaios.society.failure_reasons import FailureReason, retry_actionfrom dodaios.society.memory import MEMORY_SHARE_CAPABILITY, MemoryRefusedfrom dodaios.society.rooms import RoomError@@ -39,6 +39,83 @@ log = logging.getLogger(__name__)router = APIRouter(prefix="/api/society", tags=["society"])[email protected]("/sandbox")+async def sandbox_status() -> dict[str, Any]:+ """Check whether the isolated code sandbox is ready."""+ from dodaios.society.sandbox import status++ return await status()++[email protected]("/sandbox/prepare", openapi_extra={"x-jarvis-dangerous": True})+async def prepare_sandbox() -> dict[str, Any]:+ """Download the code sandbox runtime image."""+ from dodaios.society.sandbox import SandboxUnavailable, prepare++ try:+ return await prepare()+ except (SandboxUnavailable, TimeoutError) as exc:+ raise HTTPException(503, str(exc) or "Sandbox image download timed out.") from exc+++async def _agent_sandbox(request: Request, agent_id: str) -> Any:+ from dodaios.society.sandbox import for_agent++ rt = await _runtime(request)+ agent = await rt.roster.get(agent_id)+ if agent is None:+ raise HTTPException(404, "Agent not found.")+ if agent.execution_environment != "sandbox":+ raise HTTPException(409, "This agent does not use the code sandbox.")+ return for_agent(rt, agent.agent_id)++[email protected]("/agents/{agent_id}/sandbox/files")+async def list_sandbox_files(request: Request, agent_id: str, path: str = ".") -> dict[str, Any]:+ """List an agent's sandbox output files."""+ import json++ from dodaios.society.sandbox import SandboxUnavailable++ sandbox = await _agent_sandbox(request, agent_id)+ try:+ rc, out = await sandbox.file("list", path)+ if rc:+ raise HTTPException(400, out.decode("utf-8", "replace")[-1000:])+ return {"files": json.loads(out), "path": path}+ except (SandboxUnavailable, TimeoutError, ValueError) as exc:+ raise HTTPException(503, str(exc) or "Sandbox did not answer.") from exc++[email protected]("/agents/{agent_id}/sandbox/file")+async def download_sandbox_file(request: Request, agent_id: str, path: str) -> Any:+ """Download one sandbox result, up to 1 MB, without importing it onto the host."""+ import base64+ from pathlib import PurePosixPath+ from urllib.parse import quote++ from starlette.responses import Response++ from dodaios.society.sandbox import MAX_FILE_BYTES, SandboxUnavailable++ sandbox = await _agent_sandbox(request, agent_id)+ try:+ rc, out = await sandbox.file("download", path)+ if rc:+ raise HTTPException(400, out.decode("utf-8", "replace")[-1000:])+ content = base64.b64decode(out.strip(), validate=True)+ if len(content) > MAX_FILE_BYTES:+ raise HTTPException(413, "File exceeds 1 MB.")+ except (SandboxUnavailable, TimeoutError, ValueError) as exc:+ raise HTTPException(503, str(exc) or "Sandbox did not answer.") from exc+ filename = quote(PurePosixPath(path).name or "result", safe="")+ return Response(content, media_type="application/octet-stream", headers={+ "Content-Disposition": f"attachment; filename*=UTF-8''{filename}",+ "X-Content-Type-Options": "nosniff",+ "Cache-Control": "no-store",+ })++# ------------------------------------------------------------------ runtime@@ -143,6 +220,7 @@ def _validated_chat_runner(class CreateAgentBody(BaseModel):+ execution_environment: ExecutionEnvironment = ExecutionEnvironment.LOCAL#: Empty = one-click creation: placeholder name, random look, and the agent#: proposes its own identity in its first conversation.name: str | None = Field(default=None, max_length=40)@@ -182,6 +260,7 @@ class CreateAgentBody(BaseModel):class PatchAgentBody(BaseModel):+ execution_environment: ExecutionEnvironment | None = Nonename: str | None = Field(default=None, min_length=1, max_length=40)title: str | None = Nonedescription: str | None = None@@ -432,6 +511,19 @@ async def patch_agent(agent_id: str, body: PatchAgentBody, request: Request) ->fields = body.model_dump(exclude_none=True, exclude=set(BRIEF_FIELDS))brief = body.model_dump(include=set(BRIEF_FIELDS))+ if (+ "execution_environment" in fields+ and fields["execution_environment"] != agent.execution_environment+ ):+ from dodaios.society.chat_binding import agent_busy++ service = rt.chat_service()+ if rt.scheduler.active_runs(agent.agent_id) or (+ service is not None and agent_busy(service, agent)+ ):+ raise HTTPException(+ 409, "Stop this agent's active work before changing its environment."+ )if has_brief(brief):# A brief rewrites the standing instructions as a whole.fields["description"] = compose_description(body.description or "", brief)diff --git a/tests/contract/test_agent_mcp_harmony.py b/tests/contract/test_agent_mcp_harmony.pyindex 8f7960796e..930672d8d9 100644--- a/tests/contract/test_agent_mcp_harmony.py+++ b/tests/contract/test_agent_mcp_harmony.py@@ -17,8 +17,8 @@ from __future__ import annotationsfrom typing import Finalfrom dodaios.mcp.agents import TOOLS-from dodaios.ui.web.society_routes import router as society_routerfrom dodaios.ui.web.society_browser_routes import router as browser_router+from dodaios.ui.web.society_routes import router as society_router#: REST route -> the MCP tool that covers it.COVERED: Final[dict[str, str]] = {@@ -48,6 +48,19 @@ COVERED: Final[dict[str, str]] = {#: REST route -> why an MCP client does not get it. Each line is a decision.WITHHELD: Final[dict[str, str]] = {+ "GET /api/society/sandbox": (+ "Docker readiness belongs to the owner's local execution settings, "+ "not the remote MCP surface"+ ),+ "POST /api/society/sandbox/prepare": (+ "downloading a local container runtime is an explicit owner action in the app or CLI"+ ),+ "GET /api/society/agents/{agent_id}/sandbox/files": (+ "sandbox artifacts are browsed by the owner; remote MCP clients do not get raw file access"+ ),+ "GET /api/society/agents/{agent_id}/sandbox/file": (+ "binary artifact downloads belong to the owner-facing app and REST/CLI surface"+ ),"GET /api/society/designs": ("the saved companion-design library belongs to the owner's appearance ""editor; a remote client changes an agent's look through its profile"@@ -135,7 +148,9 @@ WITHHELD: Final[dict[str, str]] = {"GET /api/society/browser/status": "browser install state is local setup, not ecosystem state","POST /api/society/browser/install": "installs software on the machine — never from outside","POST /api/society/browser/repair": "repairs host software; local owner setup",- "POST /api/society/agents/{agent_id}/browser/cancel": "local browser control belongs to the owner UI",+ "POST /api/society/agents/{agent_id}/browser/cancel": (+ "local browser control belongs to the owner UI"+ ),"GET /api/society/agents/{agent_id}/browser/open": ("whether the owner UI may attach its live view; local process state"),diff --git a/tests/integration/test_society_sandbox_live.py b/tests/integration/test_society_sandbox_live.pynew file mode 100644index 0000000000..217b0c04ec--- /dev/null+++ b/tests/integration/test_society_sandbox_live.py@@ -0,0 +1,60 @@+"""Opt-in real Docker proof; no model calls or credentials."""++from __future__ import annotations++import asyncio+import base64+import json+import os++import pytest++from dodaios.society.sandbox import Sandbox, _docker, status++pytestmark = pytest.mark.skipif(+ os.environ.get("JARVIS_SANDBOX_LIVE") != "1",+ reason="requires explicitly selected local Docker",+)+++async def test_write_test_export_isolation_timeout_and_cancel(tmp_path, monkeypatch):+ readiness = await status()+ assert readiness["available"], readiness+ sandbox = Sandbox(tmp_path / "isolated-agent")+ monkeypatch.setenv("JARVIS_TEST_SECRET", "must-not-enter-container")+ try:+ code = (+ "import os, socket, unittest\nfrom pathlib import Path\n"+ "class Checks(unittest.TestCase):\n"+ " def test_isolation(self):\n"+ " self.assertEqual(os.getuid(),65532)\n"+ " self.assertNotIn('JARVIS_TEST_SECRET',os.environ)\n"+ " self.assertFalse(Path('/var/run/docker.sock').exists())\n"+ " self.assertFalse(Path('/host').exists())\n"+ " with self.assertRaises(OSError): Path('/etc/host-write').write_text('no')\n"+ " with self.assertRaises(OSError): socket.create_connection(('1.1.1.1',443),.2)\n"+ "if __name__=='__main__': unittest.main()\n"+ )+ rc, out = await sandbox.file("write", "test_generated.py", code)+ assert rc == 0, out+ rc, out = await sandbox.execute("python -m unittest -v test_generated.py")+ assert rc == 0 and b"OK" in out, out+ rc, out = await sandbox.file("download", "test_generated.py")+ assert rc == 0 and base64.b64decode(out) == code.encode()+ rc, out = await sandbox.file("read", "../../etc/passwd")+ assert rc != 0 and b"Path must stay" in out+ rc, out = await sandbox.file("list")+ assert rc == 0 and any(f["name"] == "test_generated.py" for f in json.loads(out))+ with pytest.raises(TimeoutError):+ await sandbox.execute("sleep 30", timeout_s=1)+ task = asyncio.create_task(sandbox.execute("sleep 30"))+ await asyncio.sleep(3)+ task.cancel()+ with pytest.raises(asyncio.CancelledError):+ await task+ rc, out = await _docker("ps", "-aq", "--filter", f"volume={sandbox.volume}")+ assert rc == 0 and not out.strip(), "sandbox left a running or stopped container"+ finally:+ # Exact test-owned volume only. Never sweep other agents' persistent data.+ rc, out = await _docker("volume", "rm", sandbox.volume)+ assert rc == 0, outdiff --git a/tests/unit/agent_chat/test_controls.py b/tests/unit/agent_chat/test_controls.pyindex c0a57a514b..292dddf481 100644--- a/tests/unit/agent_chat/test_controls.py+++ b/tests/unit/agent_chat/test_controls.py@@ -355,7 +355,10 @@ def test_goal_attachments_are_saved_and_read_before_work_starts() -> None:asyncio.run(scenario())-def test_message_uses_executor_exact_text_sender_and_idempotency(monkeypatch: Any) -> None:[email protected]("environment", ["local", "sandbox"])+def test_message_uses_executor_exact_text_sender_and_idempotency(+ monkeypatch: Any, environment: str,+) -> None:from types import SimpleNamespacefrom dodaios.agent_chat.service import AgentChatService@@ -394,7 +397,11 @@ def test_message_uses_executor_exact_text_sender_and_idempotency(monkeypatch: Anasync def completed(*_: Any) -> None:return None+ async def live_agent(_agent_id: str) -> Any:+ return SimpleNamespace(execution_environment=environment)+runtime = SimpleNamespace(+ roster=SimpleNamespace(get=live_agent),conversations=SimpleNamespace(checkpoint=lambda _: (0, "")),turn_completed=completed,browser=SimpleNamespace(live=SimpleNamespace(sessions={})),@@ -421,6 +428,10 @@ def test_message_uses_executor_exact_text_sender_and_idempotency(monkeypatch: Anrequest_data = request("message", '@"Drive Agent" First line\nSecond line')first = await svc.controls.execute(sid, request_data)second = await svc.controls.execute(sid, request_data)+ if environment == "sandbox":+ assert first.status == "failed" and first == second+ assert not calls, "a sandbox agent must not send host-side messages"+ returnassert first.status == "done" and first == secondassert len(calls) == 1assert calls[0][0] == "mail"diff --git a/tests/unit/agent_chat/test_questions.py b/tests/unit/agent_chat/test_questions.pyindex d5fb01719e..779088b0e8 100644--- a/tests/unit/agent_chat/test_questions.py+++ b/tests/unit/agent_chat/test_questions.py@@ -282,7 +282,7 @@ def test_routine_chats_are_not_offered_the_tool(monkeypatch: pytest.MonkeyPatch)from dodaios.society import surfacebrowser = SimpleNamespace(is_installed=lambda: False, live=SimpleNamespace(model_resolver=None))- rt = SimpleNamespace(browser=browser, chat_service=lambda: None)+ rt = SimpleNamespace(browser=browser, chat_service=lambda: None, cached_agent=lambda _: None)monkeypatch.setattr(surface, "current_runtime", lambda: rt)canonical = SimpleNamespace(session_id="society:ada", cwd="", permission_mode="")routine = SimpleNamespace(diff --git a/tests/unit/agent_chat/test_server_disconnect.py b/tests/unit/agent_chat/test_server_disconnect.pyindex c3440415e9..29de80c8b5 100644--- a/tests/unit/agent_chat/test_server_disconnect.py+++ b/tests/unit/agent_chat/test_server_disconnect.py@@ -30,6 +30,11 @@ def test_client_disconnect_reconnect_and_completed_restart(async def bind(*args, **kwargs):return session+ async def local(_session_id):+ return "local"++ # A society turn reads the agent's execution environment before any runner starts.+ monkeypatch.setattr(service_module, "society_execution_environment", local)fake = ApprovalRunner()monkeypatch.setattr(service, "bind_society_session", bind)monkeypatch.setattr(service_module, "run_cli_turn", fake)diff --git a/tests/unit/society/test_agent_credentials.py b/tests/unit/society/test_agent_credentials.pyindex 1ff43e3a55..b05acd90b4 100644--- a/tests/unit/society/test_agent_credentials.py+++ b/tests/unit/society/test_agent_credentials.py@@ -346,6 +346,11 @@ async def test_followup_finishes_before_the_token_is_saved("turn_id": handle.turn_id, "status": "done",}))+ async def local(_session_id):+ return "local"++ # A society turn reads the agent's execution environment before any runner starts.+ monkeypatch.setattr(service_module, "society_execution_environment", local)monkeypatch.setattr(svc, "bind_society_session", bind)monkeypatch.setattr(service_module, "resolve_runner", lambda *a, **k: "api")monkeypatch.setattr(service_module, "supports_api_runner", lambda _provider: True)@@ -386,7 +391,7 @@ def test_the_tool_is_offered_outside_routines(monkeypatch: pytest.MonkeyPatch) -from dodaios.society import surfacebrowser = SimpleNamespace(is_installed=lambda: False, live=SimpleNamespace(model_resolver=None))- rt = SimpleNamespace(browser=browser, chat_service=lambda: None)+ rt = SimpleNamespace(browser=browser, chat_service=lambda: None, cached_agent=lambda _: None)monkeypatch.setattr(surface, "current_runtime", lambda: rt)canonical = SimpleNamespace(session_id="society:ada", cwd="", permission_mode="")routine = SimpleNamespace(diff --git a/tests/unit/society/test_sandbox.py b/tests/unit/society/test_sandbox.pynew file mode 100644index 0000000000..3c65638455--- /dev/null+++ b/tests/unit/society/test_sandbox.py@@ -0,0 +1,154 @@+"""Sandbox identity, policy selection and persisted execution placement."""++from __future__ import annotations++from types import SimpleNamespace++import pytest++from dodaios.society.capabilities import capability_id_for_tool, tool_name_for_capability+from dodaios.society.roster import RosterError+from dodaios.society.sandbox import Sandbox, SandboxTool, for_agent+from dodaios.society.surface import society_system_extra, society_tool_filter, society_tools+from tests.unit.society.test_surface import _live_chat, _tool++pytest_plugins = ["tests.unit.society.test_surface"]+++def test_pydantic_execution_environment_parity():+ from typing import get_args++ from dodaios.society.events import ExecutionEnvironment+ from dodaios.ui.web.society_routes import CreateAgentBody, PatchAgentBody++ assert CreateAgentBody.model_fields["execution_environment"].annotation is ExecutionEnvironment+ assert ExecutionEnvironment in get_args(+ PatchAgentBody.model_fields["execution_environment"].annotation+ )+++async def test_environment_round_trip_and_refused_runners(rt):+ agent, _ = await rt.roster.create(+ name="Sandbox",+ provider="openai",+ execution_environment="sandbox",+ )+ assert (await rt.roster.get(agent.agent_id)).to_dict()["execution_environment"] == "sandbox"+ for fields in (+ {"provider": "codex"},+ {"runtime": "hermes"},+ {"execution_environment": "unknown"},+ ):+ with pytest.raises(RosterError):+ await rt.roster.update(agent.agent_id, fields)+ assert (await rt.roster.get(agent.agent_id)).execution_environment == "sandbox"+ assert (+ await rt.roster.update(agent.agent_id, {"execution_environment": "local"})+ ).execution_environment == "local"++[email protected]("provider", ["codex", "grok-build"])+async def test_cli_sandbox_cannot_be_created(rt, provider):+ with pytest.raises(RosterError):+ await rt.roster.create(name="Native", provider=provider, execution_environment="sandbox")+++async def test_only_bound_sandbox_tool_and_question_survive(rt, tmp_path):+ agent, _ = await rt.roster.create(+ name="Box", provider="openai", execution_environment="sandbox"+ )+ session = SimpleNamespace(+ session_id=agent.session_id, permission_mode="bypass", cwd=str(tmp_path)+ )+ _live_chat(rt, session)+ briefing = await society_system_extra(None, None, session)+ assert "No host tools" in briefing+ from dodaios.society.surface import browser_tool_for_session, coding_tool_for_session++ assert await browser_tool_for_session(session.session_id) is None+ assert await coding_tool_for_session(session.session_id) is None+ tools = society_tools(None, None, session)+ assert set(tools) == {"society_sandbox", "society_ask_user"}+ tools.update(+ {+ name: _tool(name)+ for name in (+ "Write",+ "RunCommand",+ "society_shell",+ "society_browser",+ "society_run_skill",+ "coding-session",+ "gmail",+ "mcp/shell",+ )+ }+ )+ selected = society_tool_filter(session)(tools)+ assert set(selected) == {"society_sandbox", "society_ask_user"}+ tools["society_sandbox"] = _tool("society_sandbox")+ assert "society_sandbox" not in society_tool_filter(session)(tools)+++async def test_denied_sandbox_and_stale_local_tools_fail_closed(rt, tmp_path):+ agent, _ = await rt.roster.create(name="Moving", provider="openai")+ session = SimpleNamespace(+ session_id=agent.session_id, permission_mode="bypass", cwd=str(tmp_path)+ )+ _live_chat(rt, session)+ await society_system_extra(None, None, session)+ selected = society_tool_filter(session)(society_tools(None, None, session))+ await rt.roster.update(agent.agent_id, {"execution_environment": "sandbox"})+ result = await selected["Write"].execute(+ {"file_path": "escape.txt", "content": "no"}, SimpleNamespace()+ )+ assert not result.success+ assert not (tmp_path / "escape.txt").exists()+ await rt.roster.update(agent.agent_id, {"denies": ["core:sandbox"]})+ await society_system_extra(None, None, session)+ assert "society_sandbox" not in society_tool_filter(session)(society_tools(None, None, session))+++def test_storage_is_per_identity_and_runtime(tmp_path):+ runtime = SimpleNamespace(data_dir=tmp_path)+ assert for_agent(runtime, "one").volume != for_agent(runtime, "two").volume+ assert for_agent(runtime, "one").volume == for_agent(runtime, "one").volume+ assert capability_id_for_tool("society_sandbox") == "core:sandbox"+ assert tool_name_for_capability("core:sandbox") == "society_sandbox"+++async def test_cache_miss_cannot_execute_a_host_reporting_tool(rt):+ agent, _ = await rt.roster.create(+ name="Uncached", provider="openai", execution_environment="sandbox",+ )+ session = SimpleNamespace(session_id=agent.session_id)+ leaked = _tool("society_conversation_recall")+ leaked.risk_tier = "safe"+ selected = society_tool_filter(session)({leaked.name: leaked})+ result = await selected[leaked.name].execute({}, None)+ assert not result.success and "sandbox" in result.error+++def test_launch_has_no_host_mount_or_network(tmp_path):+ args = Sandbox(tmp_path)._arguments("test")+ assert args[args.index("--network") + 1] == "none"+ assert args[args.index("--user") + 1] == "65532:65532"+ assert args[args.index("--mount") + 1].startswith("type=volume,")+ assert "--read-only" in args+ assert "--cap-drop" in args+ assert not any(str(tmp_path) in a or "docker.sock" in a for a in args)+++async def test_tool_unavailable_never_uses_host(rt, tmp_path, monkeypatch):+ from dodaios.society import sandbox++ agent, _ = await rt.roster.create(+ name="Offline", provider="openai", execution_environment="sandbox"+ )+ monkeypatch.setattr(sandbox.shutil, "which", lambda _: None)+ result = await SandboxTool(rt, agent.agent_id, tmp_path).execute(+ {"action": "run", "command": "echo forbidden > escaped.txt"},+ None,+ )+ assert not result.success and "Docker" in result.error+ assert not (tmp_path / "escaped.txt").exists()diff --git a/tests/unit/society/test_sandbox_routes.py b/tests/unit/society/test_sandbox_routes.pynew file mode 100644index 0000000000..87b97c5c84--- /dev/null+++ b/tests/unit/society/test_sandbox_routes.py@@ -0,0 +1,100 @@+"""Mounted sandbox routes, placement changes and binary export contracts."""+from __future__ import annotations++import base64+from types import SimpleNamespace++import httpx+from fastapi import FastAPI++from dodaios.society import sandbox+from dodaios.ui.web.society_routes import router++pytest_plugins = ["tests.unit.society.test_surface"]+++async def test_persisted_environment_route_and_binary_export(rt, monkeypatch):+ app = FastAPI()+ app.include_router(router)+ app.state.society = rt++ class Files:+ async def file(self, action, path):+ assert path == "result.txt"+ assert action == "download"+ return 0, base64.b64encode(b"verified artifact")++ monkeypatch.setattr(sandbox, "for_agent", lambda runtime, agent_id: Files())+ async with httpx.AsyncClient(+ transport=httpx.ASGITransport(app), base_url="http://test",+ ) as client:+ response = await client.post("/api/society/agents", json={+ "name": "Export Box", "provider": "openai", "execution_environment": "sandbox",+ })+ assert response.status_code == 200, response.text+ agent_id = response.json()["agent"]["agent_id"]+ assert response.json()["agent"]["execution_environment"] == "sandbox"+ response = await client.get(+ f"/api/society/agents/{agent_id}/sandbox/file", params={"path": "result.txt"},+ )+ assert response.content == b"verified artifact"+ assert response.headers["content-type"] == "application/octet-stream"+ assert response.headers["x-content-type-options"] == "nosniff"+ assert "attachment" in response.headers["content-disposition"]+ response = await client.patch(+ f"/api/society/agents/{agent_id}", json={"execution_environment": "local"},+ )+ assert response.status_code == 200, response.text+ assert response.json()["agent"]["execution_environment"] == "local"+ assert (await client.get(+ f"/api/society/agents/{agent_id}/sandbox/file", params={"path": "result.txt"},+ )).status_code == 409+++async def test_active_agent_cannot_change_execution_environment(rt):+ agent, _ = await rt.roster.create(name="Busy", provider="openai")+ app = FastAPI()+ app.include_router(router)+ app.state.society = rt+ rt._get_chat = lambda: SimpleNamespace(running_session_ids=lambda: [agent.session_id])+ async with httpx.AsyncClient(+ transport=httpx.ASGITransport(app), base_url="http://test",+ ) as client:+ response = await client.patch(+ f"/api/society/agents/{agent.agent_id}", json={"execution_environment": "sandbox"},+ )+ assert response.status_code == 409, response.text+ assert "Stop" in response.json()["detail"]+ assert (await rt.roster.get(agent.agent_id)).execution_environment == "local"+++async def test_existing_database_migrates_without_changing_agents(tmp_path):+ import asyncio+ import sqlite3+ from pathlib import Path++ from dodaios.society.roster import Roster+ from dodaios.society.store import SocietyStore++ database = tmp_path / "old.db"+ source = await asyncio.to_thread(+ Path("dodaios/society/society_schema.sql").read_text, encoding="utf-8",+ )+ source = source.replace(+ " execution_environment TEXT NOT NULL DEFAULT 'local'\n"+ " CHECK (execution_environment IN ('local', 'sandbox')),\n", "",+ )+ with sqlite3.connect(database) as conn:+ conn.executescript(source)+ conn.execute(+ "INSERT INTO society_agents (agent_id,name,tier,created_ms,updated_ms) "+ "VALUES ('existing','Existing','specialist',1,1)"+ )+ store = SocietyStore(database)+ await store.open()+ try:+ agent = await Roster(store).get("existing")+ assert agent.name == "Existing"+ assert agent.execution_environment == "local"+ finally:+ await store.close()diff --git a/tests/unit/society/test_society_enum_parity.py b/tests/unit/society/test_society_enum_parity.pyindex e1ead3b068..001609e6b4 100644--- a/tests/unit/society/test_society_enum_parity.py+++ b/tests/unit/society/test_society_enum_parity.py@@ -21,6 +21,7 @@ _TS = _ROOT / "dodaios" / "ui" / "web" / "frontend" / "src" / "lib" / "societyAp# (python enum, SQL column whose CHECK lists it, TS const name). ``state`` is# pinned in the society_agents block only — rooms and approvals have their own._PINS = [+ (events.ExecutionEnvironment, "execution_environment", "EXECUTION_ENVIRONMENTS"),(events.MsgType, "msg_type", "MSG_TYPES"),(events.Tier, "tier", "TIERS"),(events.AgentState, "society_agents.state", "AGENT_STATES"),