codemode-mcp 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,131 @@
1
+ """Local web dashboard for Code Mode token savings (``codemode-mcp dashboard``)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import time
6
+ from typing import Any
7
+
8
+ from starlette.applications import Starlette
9
+ from starlette.requests import Request
10
+ from starlette.responses import HTMLResponse, JSONResponse
11
+ from starlette.routing import Route
12
+
13
+ from .usage import UsageStore
14
+
15
+ RANGES = {"1d": 86_400, "7d": 7 * 86_400, "30d": 30 * 86_400, "all": None}
16
+
17
+
18
+ def _since(request: Request) -> float | None:
19
+ seconds = RANGES.get(request.query_params.get("range", "7d"), RANGES["7d"])
20
+ return None if seconds is None else time.time() - seconds
21
+
22
+
23
+ def dashboard_routes(store: UsageStore, prefix: str = "") -> list[Route]:
24
+ async def page(request: Request) -> HTMLResponse:
25
+ return HTMLResponse(_PAGE.replace("__PREFIX__", prefix))
26
+
27
+ async def summary(request: Request) -> JSONResponse:
28
+ return JSONResponse(store.summary(since=_since(request)))
29
+
30
+ async def events(request: Request) -> JSONResponse:
31
+ limit = min(int(request.query_params.get("limit", "50")), 500)
32
+ return JSONResponse(store.recent(limit))
33
+
34
+ routes = [
35
+ Route(f"{prefix}/", page),
36
+ Route(f"{prefix}/api/summary", summary),
37
+ Route(f"{prefix}/api/events", events),
38
+ ]
39
+ if prefix:
40
+ routes.append(Route(prefix, page))
41
+ return routes
42
+
43
+
44
+ def dashboard_app(store: UsageStore) -> Starlette:
45
+ return Starlette(routes=dashboard_routes(store))
46
+
47
+
48
+ def dashboard_server(store: UsageStore, host: str = "127.0.0.1", port: int = 8765) -> Any:
49
+ import uvicorn
50
+
51
+ config = uvicorn.Config(dashboard_app(store), host=host, port=port, log_level="warning", lifespan="off")
52
+ return uvicorn.Server(config)
53
+
54
+
55
+ async def serve_dashboard(store: UsageStore, host: str = "127.0.0.1", port: int = 8765) -> None:
56
+ await dashboard_server(store, host, port).serve()
57
+
58
+
59
+ _PAGE = r"""<!doctype html>
60
+ <html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
61
+ <title>codemode-mcp · token savings</title>
62
+ <style>
63
+ :root{--bg:#0d1117;--panel:#161b22;--border:#30363d;--fg:#e6edf3;--muted:#8b949e;--cm:#3fb950;--cl:#f85149;--accent:#58a6ff}
64
+ @media (prefers-color-scheme: light){:root{--bg:#f6f8fa;--panel:#fff;--border:#d0d7de;--fg:#1f2328;--muted:#656d76}}
65
+ *{box-sizing:border-box}body{margin:0;font:14px/1.5 -apple-system,Segoe UI,Helvetica,Arial,sans-serif;background:var(--bg);color:var(--fg)}
66
+ header{display:flex;align-items:center;justify-content:space-between;padding:16px 24px;border-bottom:1px solid var(--border)}
67
+ h1{font-size:18px;margin:0}h2{font-size:15px;margin:0 0 12px}main{padding:20px 24px;max-width:1200px;margin:auto}
68
+ .grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(170px,1fr));gap:12px;margin-bottom:16px}
69
+ .card,.panel{background:var(--panel);border:1px solid var(--border);border-radius:8px;padding:14px}
70
+ .panel{margin-bottom:16px;overflow-x:auto}.k{color:var(--muted);font-size:12px}.v{font-size:24px;font-weight:600;margin-top:2px}
71
+ .good{color:var(--cm)}.bad{color:var(--cl)}table{border-collapse:collapse;width:100%}th,td{text-align:left;padding:6px 8px;border-bottom:1px solid var(--border);white-space:nowrap}
72
+ th{color:var(--muted);font-weight:500;font-size:12px}td.n,th.n{text-align:right;font-variant-numeric:tabular-nums}
73
+ select,button{background:var(--panel);color:var(--fg);border:1px solid var(--border);border-radius:6px;padding:4px 8px}
74
+ .legend span{display:inline-block;width:10px;height:10px;border-radius:2px;margin:0 4px 0 12px}
75
+ .note{color:var(--muted);font-size:12px}.two{display:grid;grid-template-columns:1fr 1fr;gap:16px}@media(max-width:800px){.two{grid-template-columns:1fr}}
76
+ svg text{fill:var(--muted);font-size:11px}
77
+ </style></head><body>
78
+ <header><h1>codemode-mcp · token savings</h1>
79
+ <div><select id="range"><option value="1d">Last 24h</option><option value="7d" selected>Last 7 days</option>
80
+ <option value="30d">Last 30 days</option><option value="all">All time</option></select>
81
+ <button id="refresh">Refresh</button></div></header>
82
+ <main>
83
+ <div class="grid" id="kpis"></div>
84
+ <div class="panel"><h2>Tokens per day <span class="legend"><span style="background:var(--cl)"></span>classic MCP (estimate)<span style="background:var(--cm)"></span>Code Mode</span></h2><div id="chart"></div></div>
85
+ <div class="two">
86
+ <div class="panel"><h2>By call type</h2><table id="kinds"></table></div>
87
+ <div class="panel"><h2>Most used upstream tools</h2><table id="tools"></table></div>
88
+ </div>
89
+ <div class="panel"><h2>Benchmarks (measured with a real LLM)</h2><table id="bench"></table>
90
+ <p class="note">Run <code>codemode-mcp benchmark -c mcp.json -m MODEL "your task"</code> to add one. Both styles run the same prompt; token counts come from the provider.</p></div>
91
+ <div class="panel"><h2>Recent activity</h2><table id="events"></table></div>
92
+ <p class="note"><b>How estimates work.</b> Code Mode tokens = Code Mode tool definitions + code/query + output returned to the model.
93
+ Classic MCP estimate = for every upstream tool call, one LLM turn with all classic tool definitions + arguments + the full raw result.
94
+ History re-sent on later turns is not counted, so real classic usage is usually higher. Only counts and tool names are stored — never code, arguments or results.</p>
95
+ </main>
96
+ <script>
97
+ const P="__PREFIX__";const $=id=>document.getElementById(id);
98
+ const fmt=n=>(n||0).toLocaleString();
99
+ const esc=s=>String(s??"").replace(/[&<>"']/g,c=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"}[c]));
100
+ function table(el,head,rows){el.innerHTML="<tr>"+head.map(h=>`<th class="${h[1]||""}">${esc(h[0])}</th>`).join("")+"</tr>"+
101
+ (rows.length?rows.map(r=>"<tr>"+r.map((c,i)=>`<td class="${head[i][1]||""}">${c}</td>`).join("")+"</tr>").join(""):`<tr><td colspan="${head.length}" class="note">No data yet</td></tr>`);}
102
+ function kpi(label,value,cls=""){return `<div class="card"><div class="k">${esc(label)}</div><div class="v ${cls}">${value}</div></div>`;}
103
+ function chart(days){
104
+ const el=$("chart");if(!days.length){el.innerHTML='<p class="note">No data yet</p>';return;}
105
+ const W=Math.max(600,el.clientWidth||900),H=220,pad=50,bw=Math.min(28,(W-pad*2)/days.length/2.5);
106
+ const max=Math.max(1,...days.map(d=>Math.max(d.cl||0,d.cm||0)));const step=(W-pad*2)/days.length;
107
+ let s=`<svg width="${W}" height="${H+30}" role="img" aria-label="tokens per day">`;
108
+ for(let i=0;i<=4;i++){const y=H-(H-20)*i/4;s+=`<line x1="${pad}" x2="${W-10}" y1="${y}" y2="${y}" stroke="var(--border)"/><text x="${pad-6}" y="${y+4}" text-anchor="end">${fmt(Math.round(max*i/4))}</text>`;}
109
+ days.forEach((d,i)=>{const x=pad+i*step+step/2;const h1=(H-20)*(d.cl||0)/max,h2=(H-20)*(d.cm||0)/max;
110
+ s+=`<rect x="${x-bw-1}" y="${H-h1}" width="${bw}" height="${h1}" fill="var(--cl)"><title>classic ≈ ${fmt(d.cl)}</title></rect>`;
111
+ s+=`<rect x="${x+1}" y="${H-h2}" width="${bw}" height="${h2}" fill="var(--cm)"><title>Code Mode ${fmt(d.cm)}</title></rect>`;
112
+ s+=`<text x="${x}" y="${H+16}" text-anchor="middle">${esc(d.day.slice(5))}</text>`;});
113
+ el.innerHTML=s+"</svg>";}
114
+ async function load(){
115
+ const r=$("range").value;const [s,ev]=await Promise.all([fetch(`${P}/api/summary?range=${r}`).then(x=>x.json()),fetch(`${P}/api/events?limit=25`).then(x=>x.json())]);
116
+ $("kpis").innerHTML=kpi("Tokens saved (est.)",fmt(s.saved_tokens),s.saved_tokens>=0?"good":"bad")+kpi("Saved",`${s.saved_pct}%`,s.saved_pct>=0?"good":"bad")+
117
+ kpi("Code Mode tokens",fmt(s.codemode_tokens))+kpi("Classic MCP estimate",fmt(s.classic_tokens_estimate))+
118
+ kpi("Code Mode calls",fmt(s.calls))+kpi("Upstream tool calls",fmt(s.upstream_calls))+kpi("Errors",fmt(s.errors),s.errors?"bad":"");
119
+ chart(s.by_day);
120
+ table($("kinds"),[["Type"],["Calls","n"],["Code Mode","n"],["Classic est.","n"],["Saved","n"]],s.by_kind.map(k=>[esc(k.kind),fmt(k.n),fmt(k.cm),fmt(k.cl),k.cl?`${(100*(k.cl-k.cm)/k.cl).toFixed(1)}%`:"–"]));
121
+ table($("tools"),[["Tool"],["Calls","n"]],s.top_tools.map(t=>[esc(t[0]),fmt(t[1])]));
122
+ table($("bench"),[["When"],["Task"],["Model"],["Classic","n"],["Code Mode","n"],["Saved","n"],["Turns (classic→CM)","n"]],
123
+ s.benchmarks.map(b=>[new Date(b.ts*1000).toLocaleString(),esc((b.prompt||"").slice(0,60)),esc(b.model),fmt(b.classic_tokens),fmt(b.codemode_tokens),
124
+ `<span class="${b.saved_pct>=0?"good":"bad"}">${b.saved_pct}%</span>`,`${b.classic_turns??"?"} → ${b.codemode_turns??"?"}`]));
125
+ table($("events"),[["Time"],["Type"],["Tools"],["Upstream calls","n"],["Code Mode","n"],["Classic est.","n"],["ms","n"],["OK"]],
126
+ ev.map(e=>[new Date(e.ts*1000).toLocaleTimeString(),esc(e.kind)+(e.measured?" (measured)":""),esc(e.tools.slice(0,3).join(", ")+(e.tools.length>3?" …":"")),
127
+ fmt(e.upstream_calls),fmt(e.codemode_tokens),e.kind==="llm"?"–":fmt(e.classic_tokens),fmt(e.duration_ms),e.ok?"✓":'<span class="bad">✗</span>']));
128
+ }
129
+ $("range").onchange=load;$("refresh").onclick=load;load();setInterval(load,10000);
130
+ </script></body></html>
131
+ """
codemode_mcp/oauth.py ADDED
@@ -0,0 +1,216 @@
1
+ """OAuth 2.1 (authorization code + PKCE) for remote MCP servers.
2
+
3
+ Uses the MCP SDK's ``OAuthClientProvider`` with:
4
+
5
+ * a file-backed token store under ``~/.codemode-mcp/oauth/<server>.json`` (refresh tokens
6
+ are reused, so the browser only opens on first login or after revocation);
7
+ * a one-shot localhost callback server to receive the authorization code;
8
+ * dynamic client registration by default, or a pre-registered ``client_id``.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import asyncio
14
+ import contextlib
15
+ import hashlib
16
+ import json
17
+ import logging
18
+ import os
19
+ import sys
20
+ import webbrowser
21
+ from pathlib import Path
22
+ from typing import Any
23
+ from urllib.parse import parse_qs, urlparse
24
+
25
+ from mcp.client.auth import AuthorizationCodeResult, OAuthClientProvider
26
+ from mcp.shared.auth import OAuthClientInformationFull, OAuthClientMetadata, OAuthToken
27
+
28
+ from .config import ServerConfig
29
+ from .usage import codemode_home
30
+
31
+ log = logging.getLogger("codemode_mcp")
32
+
33
+ DEFAULT_REDIRECT_PORT = 33418
34
+ _SUCCESS_PAGE = (
35
+ b"<!doctype html><title>codemode-mcp</title><body style='font-family:sans-serif;padding:3em'>"
36
+ b"<h2>Signed in &#10003;</h2><p>You can close this window and return to your app.</p></body>"
37
+ )
38
+
39
+
40
+ def token_path(cfg: ServerConfig) -> Path:
41
+ digest = hashlib.sha256((cfg.url or "").encode()).hexdigest()[:10]
42
+ safe = "".join(ch if ch.isalnum() or ch in "-_" else "_" for ch in cfg.name)
43
+ return codemode_home() / "oauth" / f"{safe}-{digest}.json"
44
+
45
+
46
+ class FileTokenStorage:
47
+ """``TokenStorage`` implementation persisting tokens and client registration as JSON."""
48
+
49
+ def __init__(self, path: Path):
50
+ self.path = path
51
+
52
+ def _load(self) -> dict[str, Any]:
53
+ try:
54
+ return json.loads(self.path.read_text(encoding="utf-8"))
55
+ except (FileNotFoundError, json.JSONDecodeError):
56
+ return {}
57
+
58
+ def _save(self, data: dict[str, Any]) -> None:
59
+ self.path.parent.mkdir(parents=True, exist_ok=True)
60
+ tmp = self.path.with_suffix(".tmp")
61
+ tmp.write_text(json.dumps(data, indent=2), encoding="utf-8")
62
+ with contextlib.suppress(OSError):
63
+ os.chmod(tmp, 0o600)
64
+ os.replace(tmp, self.path)
65
+
66
+ async def get_tokens(self) -> OAuthToken | None:
67
+ raw = self._load().get("tokens")
68
+ return OAuthToken.model_validate(raw) if raw else None
69
+
70
+ async def set_tokens(self, tokens: OAuthToken) -> None:
71
+ data = self._load()
72
+ data["tokens"] = tokens.model_dump(mode="json", exclude_none=True)
73
+ self._save(data)
74
+
75
+ async def get_client_info(self) -> OAuthClientInformationFull | None:
76
+ raw = self._load().get("client_info")
77
+ return OAuthClientInformationFull.model_validate(raw) if raw else None
78
+
79
+ async def set_client_info(self, client_info: OAuthClientInformationFull) -> None:
80
+ data = self._load()
81
+ data["client_info"] = client_info.model_dump(mode="json", exclude_none=True)
82
+ self._save(data)
83
+
84
+ def clear(self) -> None:
85
+ with contextlib.suppress(FileNotFoundError):
86
+ self.path.unlink()
87
+
88
+
89
+ class CallbackServer:
90
+ """Minimal one-shot HTTP server on localhost that captures ``?code=...&state=...``."""
91
+
92
+ def __init__(self, port: int):
93
+ self.port = port
94
+ self._server: asyncio.base_events.Server | None = None
95
+ self._result: asyncio.Future[AuthorizationCodeResult] | None = None
96
+
97
+ async def start(self) -> None:
98
+ if self._server is not None:
99
+ return
100
+ self._result = asyncio.get_running_loop().create_future()
101
+ self._server = await asyncio.start_server(self._handle, "127.0.0.1", self.port)
102
+
103
+ async def _handle(self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None:
104
+ try:
105
+ request_line = (await reader.readline()).decode(errors="replace")
106
+ while (await reader.readline()) not in (b"\r\n", b"\n", b""):
107
+ pass
108
+ parts = request_line.split(" ")
109
+ query = parse_qs(urlparse(parts[1]).query) if len(parts) > 1 else {}
110
+ if "code" in query or "error" in query:
111
+ status, body = (
112
+ (b"200 OK", _SUCCESS_PAGE)
113
+ if "code" in query
114
+ else (b"400 Bad Request", b"Authorization failed: " + query.get("error", ["unknown"])[0].encode())
115
+ )
116
+ if self._result and not self._result.done():
117
+ if "code" in query:
118
+ self._result.set_result(
119
+ AuthorizationCodeResult(
120
+ code=query["code"][0],
121
+ state=(query.get("state") or [None])[0],
122
+ iss=(query.get("iss") or [None])[0],
123
+ )
124
+ )
125
+ else:
126
+ self._result.set_exception(
127
+ RuntimeError(
128
+ f"OAuth authorization failed: {query.get('error_description', query['error'])[0]}"
129
+ )
130
+ )
131
+ else:
132
+ status, body = b"404 Not Found", b"Not found"
133
+ writer.write(
134
+ b"HTTP/1.1 "
135
+ + status
136
+ + b"\r\nContent-Type: text/html; charset=utf-8\r\nContent-Length: "
137
+ + str(len(body)).encode()
138
+ + b"\r\nConnection: close\r\n\r\n"
139
+ + body
140
+ )
141
+ await writer.drain()
142
+ finally:
143
+ writer.close()
144
+
145
+ async def wait(self, timeout: float) -> AuthorizationCodeResult:
146
+ assert self._result is not None
147
+ try:
148
+ return await asyncio.wait_for(self._result, timeout)
149
+ finally:
150
+ await self.stop()
151
+
152
+ async def stop(self) -> None:
153
+ server, self._server = self._server, None
154
+ if server is not None:
155
+ server.close()
156
+ with contextlib.suppress(Exception):
157
+ await server.wait_closed()
158
+
159
+
160
+ def build_oauth_provider(
161
+ cfg: ServerConfig, *, open_browser: bool = True, timeout: float = 300.0
162
+ ) -> OAuthClientProvider:
163
+ opts = dict(cfg.oauth or {})
164
+ port = int(opts.get("redirect_port") or DEFAULT_REDIRECT_PORT)
165
+ redirect_uri = f"http://localhost:{port}/callback"
166
+ scopes = opts.get("scopes")
167
+ scope = " ".join(scopes) if isinstance(scopes, list) else scopes
168
+ storage = FileTokenStorage(token_path(cfg))
169
+ if opts.get("client_id"):
170
+ # Pre-registered client: seed the store so dynamic registration is skipped.
171
+ info = {
172
+ "client_id": opts["client_id"],
173
+ "redirect_uris": [redirect_uri],
174
+ "grant_types": ["authorization_code", "refresh_token"],
175
+ "response_types": ["code"],
176
+ }
177
+ if opts.get("client_secret"):
178
+ info["client_secret"] = opts["client_secret"]
179
+ info["token_endpoint_auth_method"] = opts.get("token_endpoint_auth_method", "client_secret_post")
180
+ else:
181
+ info["token_endpoint_auth_method"] = "none"
182
+ if scope:
183
+ info["scope"] = scope
184
+ data = storage._load()
185
+ if data.get("client_info", {}).get("client_id") != opts["client_id"]:
186
+ data["client_info"] = info
187
+ storage._save(data)
188
+
189
+ callback = CallbackServer(port)
190
+
191
+ async def redirect_handler(url: str) -> None:
192
+ await callback.start()
193
+ print(f"\n[codemode-mcp] Sign in to MCP server {cfg.name!r}:\n {url}\n", file=sys.stderr, flush=True)
194
+ if open_browser:
195
+ with contextlib.suppress(Exception):
196
+ webbrowser.open(url)
197
+
198
+ async def callback_handler() -> AuthorizationCodeResult:
199
+ await callback.start()
200
+ return await callback.wait(timeout)
201
+
202
+ metadata = OAuthClientMetadata(
203
+ client_name=opts.get("client_name") or "codemode-mcp",
204
+ redirect_uris=[redirect_uri], # type: ignore[list-item]
205
+ grant_types=["authorization_code", "refresh_token"],
206
+ response_types=["code"],
207
+ token_endpoint_auth_method="client_secret_post" if opts.get("client_secret") else "none",
208
+ scope=scope,
209
+ )
210
+ return OAuthClientProvider(
211
+ server_url=cfg.url or "",
212
+ client_metadata=metadata,
213
+ storage=storage,
214
+ redirect_handler=redirect_handler,
215
+ callback_handler=callback_handler,
216
+ )
codemode_mcp/py.typed ADDED
File without changes
@@ -0,0 +1,315 @@
1
+ """Host side of the Deno + Pyodide sandbox."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import contextlib
7
+ import itertools
8
+ import json
9
+ import logging
10
+ import os
11
+ import shutil
12
+ import subprocess
13
+ from collections.abc import Awaitable, Callable
14
+ from dataclasses import dataclass, field
15
+ from importlib import resources
16
+ from pathlib import Path
17
+ from typing import Any
18
+
19
+ log = logging.getLogger("codemode_mcp")
20
+
21
+ ToolHandler = Callable[[str, str, dict[str, Any]], Awaitable[Any]]
22
+
23
+
24
+ class SandboxError(RuntimeError):
25
+ pass
26
+
27
+
28
+ @dataclass
29
+ class ToolCallRecord:
30
+ server: str
31
+ tool: str
32
+ args: dict[str, Any]
33
+ ok: bool
34
+ error: str | None = None
35
+
36
+
37
+ @dataclass
38
+ class ExecResult:
39
+ ok: bool
40
+ stdout: str = ""
41
+ result: Any = None
42
+ has_result: bool = False
43
+ error: str | None = None
44
+ calls: list[ToolCallRecord] = field(default_factory=list)
45
+
46
+
47
+ def find_deno(explicit: str | None = None) -> str:
48
+ candidates = [explicit, os.environ.get("CODEMODE_DENO")]
49
+ for c in candidates:
50
+ if c:
51
+ return c
52
+ try:
53
+ import deno # the `deno` wheel from PyPI ships the binary
54
+
55
+ return deno.find_deno_bin()
56
+ except Exception: # pragma: no cover - fall back to PATH
57
+ pass
58
+ found = shutil.which("deno")
59
+ if not found:
60
+ raise SandboxError("Deno executable not found. Run `pip install deno` or set CODEMODE_DENO.")
61
+ return found
62
+
63
+
64
+ def _npm_cache_dir(deno: str) -> str:
65
+ out = subprocess.run([deno, "info", "--json"], capture_output=True, text=True, timeout=60, check=True)
66
+ path = json.loads(out.stdout)["npmCache"]
67
+ # Fresh machines have no cache yet; it must exist to be the working dir / read allow-list.
68
+ os.makedirs(path, exist_ok=True)
69
+ return path
70
+
71
+
72
+ def _runner_path() -> Path:
73
+ return Path(str(resources.files("codemode_mcp").joinpath("sandbox_runner.ts")))
74
+
75
+
76
+ class DenoSandbox:
77
+ """A warm Pyodide interpreter in a locked-down Deno process.
78
+
79
+ Each ``execute`` gets a fresh Python namespace. If an execution exceeds its timeout the
80
+ process is killed and transparently restarted on the next call.
81
+ """
82
+
83
+ def __init__(self, *, deno_path: str | None = None, memory_mb: int = 512, startup_timeout: float = 120.0):
84
+ self.deno = find_deno(deno_path)
85
+ self.memory_mb = memory_mb
86
+ self.startup_timeout = startup_timeout
87
+ self._proc: asyncio.subprocess.Process | None = None
88
+ self._reader: asyncio.Task[None] | None = None
89
+ self._stderr_task: asyncio.Task[None] | None = None
90
+ self._specs: list[dict[str, Any]] = []
91
+ self._ready: asyncio.Future[None] | None = None
92
+ self._installed: asyncio.Future[dict[str, Any]] | None = None
93
+ self._done: dict[str, asyncio.Future[dict[str, Any]]] = {}
94
+ self._handler: ToolHandler | None = None
95
+ self._records: list[ToolCallRecord] = []
96
+ self._max_calls = 0
97
+ self._current_exec: str | None = None
98
+ self._call_tasks: set[asyncio.Task[None]] = set()
99
+ self._ids = itertools.count(1)
100
+ self._lock = asyncio.Lock()
101
+ self._write_lock = asyncio.Lock()
102
+ self._npm_cache: str | None = None
103
+ self._paused_total = 0.0
104
+ self._pausing = 0
105
+
106
+ def command(self) -> list[str]:
107
+ if self._npm_cache is None:
108
+ self._npm_cache = _npm_cache_dir(self.deno)
109
+ return [
110
+ self.deno,
111
+ "run",
112
+ "--quiet",
113
+ "--no-prompt",
114
+ "--no-config",
115
+ "--no-lock",
116
+ f"--allow-read={self._npm_cache}",
117
+ "--deny-net",
118
+ "--deny-env",
119
+ "--deny-run",
120
+ "--deny-write",
121
+ "--deny-ffi",
122
+ "--deny-sys",
123
+ f"--v8-flags=--max-old-space-size={self.memory_mb}",
124
+ str(_runner_path()),
125
+ ]
126
+
127
+ async def start(self, specs: list[dict[str, Any]] | None = None) -> None:
128
+ if specs is not None:
129
+ self._specs = specs
130
+ if self._proc is not None and self._proc.returncode is None:
131
+ return
132
+ loop = asyncio.get_running_loop()
133
+ cmd = await asyncio.to_thread(self.command)
134
+ self._proc = await asyncio.create_subprocess_exec(
135
+ *cmd,
136
+ stdin=asyncio.subprocess.PIPE,
137
+ stdout=asyncio.subprocess.PIPE,
138
+ stderr=asyncio.subprocess.PIPE,
139
+ limit=64 * 1024 * 1024,
140
+ cwd=self._npm_cache,
141
+ )
142
+ self._ready = loop.create_future()
143
+ self._reader = asyncio.create_task(self._read_loop(self._proc))
144
+ self._stderr_task = asyncio.create_task(self._drain_stderr(self._proc))
145
+ try:
146
+ await asyncio.wait_for(asyncio.shield(self._ready), self.startup_timeout)
147
+ self._installed = loop.create_future()
148
+ await self._send({"type": "install", "specs": self._specs})
149
+ installed = await asyncio.wait_for(asyncio.shield(self._installed), self.startup_timeout)
150
+ if installed.get("error"):
151
+ raise SandboxError(f"Failed to install tool stubs: {installed['error']}")
152
+ except BaseException:
153
+ await self._kill()
154
+ raise
155
+
156
+ async def _drain_stderr(self, proc: asyncio.subprocess.Process) -> None:
157
+ assert proc.stderr is not None
158
+ chunks: list[str] = []
159
+ while line := await proc.stderr.readline():
160
+ text = line.decode(errors="replace").rstrip()
161
+ chunks.append(text)
162
+ log.debug("sandbox stderr: %s", text)
163
+ self._last_stderr = "\n".join(chunks[-20:])
164
+
165
+ async def _read_loop(self, proc: asyncio.subprocess.Process) -> None:
166
+ assert proc.stdout is not None
167
+ try:
168
+ while line := await proc.stdout.readline():
169
+ try:
170
+ msg = json.loads(line)
171
+ except json.JSONDecodeError:
172
+ log.debug("sandbox noise: %r", line[:200])
173
+ continue
174
+ kind = msg.get("type")
175
+ if kind == "ready" and self._ready and not self._ready.done():
176
+ self._ready.set_result(None)
177
+ elif kind == "installed" and self._installed and not self._installed.done():
178
+ self._installed.set_result(msg)
179
+ elif kind == "call":
180
+ task = asyncio.create_task(self._handle_call(msg))
181
+ self._call_tasks.add(task)
182
+ task.add_done_callback(self._call_tasks.discard)
183
+ elif kind == "done":
184
+ fut = self._done.get(msg.get("id"))
185
+ if fut and not fut.done():
186
+ fut.set_result(msg)
187
+ finally:
188
+ await proc.wait()
189
+ stderr_task = self._stderr_task
190
+ if stderr_task is not None:
191
+ with contextlib.suppress(Exception):
192
+ await asyncio.wait_for(stderr_task, 2)
193
+ err = SandboxError(
194
+ f"sandbox process exited (code {proc.returncode})"
195
+ + (f": {getattr(self, '_last_stderr', '')[-2000:]}" if getattr(self, "_last_stderr", "") else "")
196
+ )
197
+ for fut in [self._ready, self._installed, *self._done.values()]:
198
+ if fut is not None and not fut.done():
199
+ fut.set_exception(err)
200
+
201
+ async def _handle_call(self, msg: dict[str, Any]) -> None:
202
+ server, tool, args = msg.get("server", ""), msg.get("tool", ""), msg.get("args") or {}
203
+ reply: dict[str, Any] = {"type": "call_result", "call_id": msg.get("call_id")}
204
+ if msg.get("exec_id") != self._current_exec or self._handler is None:
205
+ reply.update(ok=False, error="no active execution")
206
+ elif len(self._records) >= self._max_calls:
207
+ reply.update(ok=False, error=f"tool call limit ({self._max_calls}) reached for this execution")
208
+ else:
209
+ record = ToolCallRecord(server, tool, args, ok=True)
210
+ self._records.append(record)
211
+ try:
212
+ value = await self._handler(server, tool, args)
213
+ json.dumps(value)
214
+ reply.update(ok=True, value=value)
215
+ except Exception as e:
216
+ record.ok, record.error = False, str(e)
217
+ reply.update(ok=False, error=str(e))
218
+ with contextlib.suppress(Exception):
219
+ await self._send(reply)
220
+
221
+ async def _send(self, msg: dict[str, Any]) -> None:
222
+ proc = self._proc
223
+ if proc is None or proc.stdin is None or proc.returncode is not None:
224
+ raise SandboxError("sandbox is not running")
225
+ data = (json.dumps(msg, ensure_ascii=False, default=str) + "\n").encode()
226
+ async with self._write_lock:
227
+ proc.stdin.write(data)
228
+ await proc.stdin.drain()
229
+
230
+ async def execute(
231
+ self, code: str, handler: ToolHandler, *, timeout: float = 30.0, max_calls: int = 200, persist: bool = False
232
+ ) -> ExecResult:
233
+ async with self._lock:
234
+ await self.start()
235
+ exec_id = f"e{next(self._ids)}"
236
+ fut: asyncio.Future[dict[str, Any]] = asyncio.get_running_loop().create_future()
237
+ self._done[exec_id] = fut
238
+ self._handler, self._records, self._max_calls = handler, [], max_calls
239
+ self._current_exec = exec_id
240
+ loop = asyncio.get_running_loop()
241
+ self._paused_total, self._pausing = 0.0, 0
242
+ deadline = loop.time() + timeout
243
+ try:
244
+ await self._send({"type": "exec", "id": exec_id, "code": code, "persist": persist})
245
+ while True:
246
+ remaining = deadline + self._paused_total - loop.time()
247
+ if remaining <= 0 and not self._pausing:
248
+ raise TimeoutError
249
+ done, _ = await asyncio.wait({fut}, timeout=1.0 if self._pausing else remaining)
250
+ if done:
251
+ msg = fut.result()
252
+ break
253
+ except TimeoutError:
254
+ await self._kill()
255
+ note = " Persistent state was lost." if persist else ""
256
+ return ExecResult(
257
+ ok=False,
258
+ error=f"Execution timed out after {timeout:g}s (sandbox was reset).{note}",
259
+ calls=self._records,
260
+ )
261
+ except SandboxError as e:
262
+ await self._kill()
263
+ return ExecResult(ok=False, error=str(e), calls=self._records)
264
+ finally:
265
+ self._done.pop(exec_id, None)
266
+ self._current_exec = None
267
+ self._handler = None
268
+ raw = msg.get("result")
269
+ return ExecResult(
270
+ ok=bool(msg.get("ok")),
271
+ stdout=msg.get("stdout") or "",
272
+ result=json.loads(raw) if raw is not None else None,
273
+ has_result=raw is not None,
274
+ error=msg.get("error"),
275
+ calls=self._records,
276
+ )
277
+
278
+ @contextlib.asynccontextmanager
279
+ async def paused(self) -> Any:
280
+ """Stop the execution clock (e.g. while a human approves a tool call)."""
281
+ loop = asyncio.get_running_loop()
282
+ start = loop.time()
283
+ self._pausing += 1
284
+ try:
285
+ yield
286
+ finally:
287
+ self._pausing -= 1
288
+ self._paused_total += loop.time() - start
289
+
290
+ async def reset_state(self) -> None:
291
+ """Drop persistent Python variables (no-op if the sandbox isn't running)."""
292
+ async with self._lock:
293
+ if self._proc is not None and self._proc.returncode is None:
294
+ await self._send({"type": "reset"})
295
+
296
+ async def _kill(self) -> None:
297
+ proc, self._proc = self._proc, None
298
+ if proc is not None and proc.returncode is None:
299
+ with contextlib.suppress(ProcessLookupError):
300
+ proc.kill()
301
+ with contextlib.suppress(Exception):
302
+ await asyncio.wait_for(proc.wait(), 5)
303
+ for task in list(self._call_tasks):
304
+ task.cancel()
305
+ if self._reader is not None:
306
+ with contextlib.suppress(BaseException):
307
+ await asyncio.wait_for(self._reader, 5)
308
+ self._reader = None
309
+
310
+ async def close(self) -> None:
311
+ proc = self._proc
312
+ if proc is not None and proc.stdin is not None:
313
+ with contextlib.suppress(Exception):
314
+ proc.stdin.close()
315
+ await self._kill()