Repository navigation
Phase 2: Widget, the Pyodide runtime and execute_code - #448
Merged
neuromechanist merged 43 commits intoSep 23, 2026
Merged
neuromechanist merged 43 commits into
neuromechanist merged 43 commits into
Conversation
Step 1 of phase 2 (#431). The host half of the executor: one Pyodide worker per community per tab, booted lazily or eagerly per preload_on, kept warm across turns, torn down for cancellation. Execution is step 3 and is deliberately not here. Every boot is bounded by a deadline, and expiry is a FAILED state naming script-src 'wasm-unsafe-eval' and worker-src blob:. This is not defensive padding. Measured in Chrome on 2026-09-22 and recorded on #431: under a policy with no wasm grant, loadPyodide never resolves, never rejects and logs nothing, so a blocked runtime is indistinguishable from a slow one. Without a deadline the widget shows a spinner forever and nobody learns the policy is wrong. The worker is a blob because nemar.org grants worker-src 'self' blob:, and 'self' is nemar.org, so a worker served from widget.osc.earth would be refused. A blob worker also inherits the page CSP, which is what makes connect-src a real egress ceiling; the per-community boundary is step 2. terminate() is cancellation. Cooperative interruption needs a SharedArrayBuffer and therefore cross-origin isolation on every embedding page, which this epic declined to require. A terminated runtime does not self-heal: boot() rejects and reboot() is explicit, because silently restarting turns "stop" into "stop, then quietly start again". Tests drive the real class against REAL Bun workers over the real message protocol, including one worker that boots and then says nothing, which is what a CSP refusal actually looks like. Mutation-verified: removing the deadline, breaking boot() idempotence, or letting a terminated runtime restart each fail the suite. The suite carries its own watchdog for the same reason the runtime does. Mutation testing showed the first two of those defects made the suite HANG rather than fail, because an awaited boot that never settles never reaches an assertion, and in CI a hang reads as a stuck job rather than a broken change. Tested: 37 lifecycle, 102 routing, 10 mounted-hosts, 13 endpoint.
Step 2 of phase 2 (#431), and the security-critical one. Measured on #431: a blob worker inherits the page's Content-Security-Policy, so connect-src really is enforced on the worker across every transport. But that policy is the EMBEDDER's. It cannot vary per community, and an embedder serving connect-src * leaves no browser-enforced boundary at all. The CSP is therefore a ceiling we do not control, and this is the boundary we do. The allow decision compares parsed ORIGIN plus a path prefix that must end on a segment boundary. Raw string matching is wrong twice over: it lets https://zarr.nemar.org.evil.com through when the allowed entry is written without a trailing slash, and it lets /datasets-private through when /datasets is allowed. Both are easy to hit by accident and easy to exploit on purpose. fetch and XMLHttpRequest are shimmed with credentials forced off, so a same-origin request cannot carry the embedding page's cookies into reach of executed code. WebSocket and EventSource are refused outright rather than allowlisted: nothing needs a persistent channel, and a long-lived socket fits badly with a per-request allowlist. That is the deliberately strict default; relaxing it later is a config change, tightening it later breaks working embeds. The allowlist is wide during boot so packages can install from the wheel origin, then SEALED one-way to the community's fetch_allow before any model-written code runs, so executed code does not inherit the reach that installing needed. micropip, pyodide_js, pyodide_http and the js bridge are dropped from the execution namespace. micropip is the one that matters: left reachable, it turns allow_install into a suggestion. Dropping js is what stops js.fetch routing around the shimmed self.fetch. Two defects the tests found in their own right: A real-worker probe, added because string assertions about generated source prove nothing, showed EventSource was never shimmed when the global did not already exist. The blockers are now defined unconditionally, which also means a test can no longer confuse "absent" with "allowed". Mutation testing showed a naive string-prefix matcher passed all 41 assertions, because every allowlist entry in the suite happened to end in "/". That is an accident of how they were written, not a property of the code. Added the no-trailing-slash cases, which are ordinary config and are exactly where string matching breaks. Mutation-verified: naive prefix matching, accepting URL credentials, a seal that widens rather than replaces, and dropping credentials: omit each fail. Tested: 46 egress, 37 lifecycle, 102 routing, 10 mounted-hosts, 13 endpoint.
The guard was generated but never installed: buildWorkerSource now encloses it with the worker body in one function scope, installs it before the loader is fetched (importScripts is one of the transports it shims), and seals down to fetch_allow at the end of boot. Security findings, each previously a proven bypass: - nothing the guard declares reaches global scope; a top-level function in a classic worker became a property of the global object, which made the sealing function publicly callable - fetch normalizes to a Request once, so the checked URL is the dispatched URL, and sets redirect: 'error' - importScripts is shimmed and caches denied - sealing is one-shot - allowlist entries containing dot segments are refused, since URL parsing collapses them and would silently grant the whole origin - the namespace seal uses a sys.meta_path finder, which importlib cannot bypass, rather than popping sys.modules Test findings: the TOCTOU case now watches what a local server actually received, because which coercion a runtime picks is not the property under test and Bun and browsers differ. Adds runtime coverage for XHR, WebSocket and EventSource, target-side path normalization, worker disposal on a failed boot, that the deadline is the configured value, and that the assembled worker source parses. Every new assertion was verified by mutation.
Step 3 of phase 2. The worker gains an execute path and the host gains execute(), correlated by the server-minted call_id. Packages are installed entirely during boot, never on demand, which is what lets the egress allowlist narrow to fetch_allow before the first executable statement exists. Every allow_install entry installs with deps false, so the list is complete and ordered rather than a resolver seed: zarr cannot resolve in Pyodide at all, and a resolver that picks the package set at runtime breaks the byte-identical results the prompt cache depends on. loadPackagesFromImports is deliberately not used, because it fetches from the CDN and would turn an unavailable package into an egress error naming the wrong cause. Instead find_imports plus find_spec decide before anything runs, from a namespace executed code cannot reach, so the gate cannot be redefined to approve the next execution. Phase 1's ResultStatus has no denied_import member, so the status is denied and the reason travels in stderr. User code runs in its own namespace that persists across turns, so a reader can compute in one message and plot in the next. Fixes a race found while testing: execute() registers after awaiting boot(), so a terminate() on the same turn surfaced as a TypeError about a null worker instead of as cancellation. The Python half needs real Pyodide and is verified in a browser, not here; the worker in these tests speaks the protocol and nothing more.
Measured against real Pyodide 0.28.3 in Chrome under nemar.org's production CSP, which found two things no bun test could. First, the namespace seal on its own leaves executed code with NO network route at all: js, pyodide and micropip are gone and urllib fails with "unknown url type: https" because Pyodide ships no socket transport. A runtime that cannot read the archive cannot do the thing this feature exists for, so the seal is now paired with osa.fetch_bytes and osa.fetch_text, installed before the seal and closing over the shimmed fetch. The module carries a real __spec__, without which find_spec raises and the import gate would deny "import osa". Second, a nested Worker gets a fresh global with the native fetch intact, which defeats every shim at once. Worker and SharedWorker are now blocked, as is sendBeacon where it exists. The seal's one shared message told someone importing ctypes that network access goes through the runtime's client, which is not why ctypes is blocked. Each root now explains itself. Adds frontend/browser-harness/, the manual check behind all of this: 18 checks, including the one that isolates this runtime's allowlist from the browser's connect-src by refusing a sibling path on an origin the CSP allows, and a negative control that must fail. The control confirms a CSP refusal is silent and that the boot deadline is what turns it into an actionable message.
Step 4 of phase 2. Execution without capture returns nothing a reader or a model can use; this is the half that turns a run into a result. stdout and stderr are captured and restored on both paths, so a failed run still returns what it printed first, which is usually what explains the exception. MPLBACKEND is set before anything can import matplotlib, because Pyodide's default backend draws into the page's DOM and a worker has no DOM: the import succeeds and the first plot fails somewhere unrelated. Figures left open are attached as PNG and then closed, so one run's plot cannot be attributed to the next. display() takes PNG bytes, a figure, _repr_png_ or _repr_html_. Determinism is treated as a precondition rather than tidiness: prompt caching is a byte-exact prefix match, so captured text has heap addresses stripped, artifacts are sorted and de-duplicated, and the JSON is emitted with sorted keys. Two runs of the same code are byte identical in two separate interpreters. The caps are applied in the browser as well as on the server, not out of trust but because ClientToolResult is extra="forbid" and refuses a result WHOLE: a figure a little too large would otherwise cost the run its stdout too. Nothing is dropped silently, since a figure that vanishes reads as the plotting code being wrong and the model then rewrites working code. Bytes that are not a readable PNG are refused here rather than sent as 0x0, which the server's ge=1 validator would reject. The mirrored server caps are compared against src/core/limits.py by a test, since a comment has never kept two constants in sync. Adds a template-hygiene test: a bare escape or an unescaped backtick inside the worker template is consumed by the template itself, which cost four separate debugging rounds and does not always produce invalid syntax. Verified in the browser as well: 23 checks, including a real 543x433 matplotlib PNG under nemar.org's production CSP.
Step 5 of phase 2. The deadline is enforced by the host, not the worker, because Pyodide cannot interrupt its own Python: cooperative interruption needs setInterruptBuffer, which needs a SharedArrayBuffer, which needs cross-origin isolation on every embedding page. Issue #431 rules that out, so terminating the worker is the only way to stop a runaway loop and only the host can terminate. A timeout RESOLVES with a status rather than rejecting. The server expects a ClientToolResult for every call_id it minted, and a rejection would leave the model with a tool_use and no tool_result, which the provider refuses outright: that breaks the session rather than the run. oom is a separate status because a wasm memory abort takes the instance down with no exception to catch and no deadline fired. Both the worker-reported form and the worker simply dying are handled; the latter previously left a promise nobody would ever settle, which looks exactly like code still running. Adds _recycle, distinct from terminate. Terminate is a person saying stop and deliberately does not self-heal. A timed-out or out-of-memory instance is one the runtime can no longer trust while the runtime itself is fine, so it returns to IDLE and the next execution boots a fresh worker. One runaway loop must not cost the rest of the conversation. memory_mb is carried for reporting only, and says so: wasm32 grows memory from inside the instance, so there is no moment at which a byte count could be checked and enforced. Verified in the browser against a real infinite loop: stopped at 3009ms against a 3-second limit, then rebooted and ran the next execution. 26 harness checks.
Step 6 of phase 2, browser side, plus a structural change that made it testable. The worker's boot and execute logic moves out of a template string into createWorkerRuntime, which buildWorkerSource embeds by value with Function.prototype.toString. Pyodide 0.28.3 boots under Bun from its npm package, so the Python half of the runtime (import gate, namespace seal, data client, execution harness) now runs in CI against the interpreter that ships, through the STRINGIFIED core, which is what catches a reference to a module-level name. It also ends the template-escape bugs for that code: an interpolated value is inserted verbatim. A result now carries structured facts rather than bulk: the variables the run created or rebound, arrays by dtype, shape, min, max, mean and NaN count; figures by title, labels, series and data range, which is all the model keeps once history strips the image; and an exception as type, message and the offending line in the run's own code. The untruncated streams and the full traceback stay in the browser behind getFullOutput, bounded by count and size, and outlive the instance that produced them. Results handed to callers are cut to exactly ClientToolResult's fields, checked against the Python model. The worker protocol's own type field was reaching callers and would have cost the first forwarded result a 422. Also: a trailing expression is shown as a notebook would, and a trailing semicolon suppresses it; SystemExit is caught inside the harness; a package that fails to load fails the boot instead of surfacing later as a denial; the import gate checks roots only, since find_spec on a submodule imports its package; a figure passed to display() is no longer collected twice; plt.show() no longer leaves an Agg warning in stderr; display() prints text rather than HTML, which has no channel in the result and costs the model tokens as markup. numpy's default integer on wasm32 is int32, because a C long is 32 bits there. The summary shows it, which is where a model can see that code written for a laptop overflows in the browser. Verified: 65 worker-core assertions against real Pyodide, 115 lifecycle, 52 harness, every new behavior mutation-checked; 32 browser checks under nemar.org's production CSP.
Step 6 of phase 2, server side. The conversation carries clipped streams and a summary; the rest stays in the reader's browser. This is how the model asks for it. get_full_output is derived, not configured. It is bound only beside a python-runtime tool, since without one there is no browser output to read, and only when the caller declares it, since an older cached widget that cannot answer it would otherwise park the call and leave the reply hanging. It carries requires_permission false: it reads output the person's own browser already holds and runs nothing. That flag reaches the widget on the tool_request event, which is where the test asserts it. The name is reserved at config load. A community tool configured under it would sit beside the derived one, and the model would see two tools with one name and different arguments. The constant lives in the config module because that module must import without the server extra. Tested: binding conditions, the kill switch, the schema's bounds, the reserved name, and a scripted model's call reaching the wire ungated; each mutation-checked. Full suite 2517 passed, coverage 78%.
From the review of phase 2 steps 3-6. The client_tools node parked the model's arguments as they came, and the provider does not enforce a tool's input schema. A call missing description rendered a blank permission gate; a get_full_output call with a negative offset or an oversized call_id reached the browser. Each client call is now validated against its bound schema. An invalid one is answered with an error ToolMessage the model can act on, and the parked arguments carry their defaults so the browser never re-derives them. That exposed a dead end phase 1 already had. The node's only exit was an unconditional edge to END, so a message whose client calls were all refused (an unknown name, now invalid arguments) ended the turn on an error ToolMessage with no reply: the person saw nothing and the model never read what it was told. The node now returns to the agent when it parked nothing. The stream guard that catches LangGraph event-shape drift read "the client_tools node ran" as "a call was parked", which is no longer implied. It now asks whether the run ended on that node, tracked from node names alone, the same dependency it had before. Its original target, a parked call missing from the final state, is still caught. Six phase 1 streaming tests used execute_code arguments without description and passed only because nothing validated them. Tested at the node, through a full graph turn, and at the wire; each change mutation-checked.
From the review of phase 2 steps 3-6. The guard swallowed both ways it could fail to lock a transport. A native member it could not delete from the prototype stayed reachable as Object.getPrototypeOf(self).fetch, and a defineProperty that threw fell back to plain assignment, leaving a shim executed code could reassign. caches and sendBeacon had the same silent fallback. A partial seal with nothing saying so is the failure this module exists to prevent, so every lock is now verified and a failure throws at the worker's top level, where the host sees a worker error and the boot fails visibly. Testing that found two more holes. The prototype walk stopped short of Object.prototype, which is the only prototype a Bun worker global has, so a transport defined there was never examined and stayed reachable from any plain object. And caches was shadowed with an own getter but never removed from the prototype, so the native getter was still one lookup away. The walk now covers the whole chain and caches and sendBeacon go through the same lock as everything else. Both failure modes are forced in a real worker and must stop the guard; each fix mutation-checked.
From the review of phase 2 steps 3-6, runtime and harness side. toClientToolResult now enforces the server's field sizes as well as its field list. Several results are built on the host from values the model chose (a get_full_output call_id or stream, the names in a denied import, a worker's error text), each once reflected unbounded, and ClientToolResult refuses a result whole on one oversized field. Sizing at each call site was one forgotten site away from a 422; now it cannot happen. The messages themselves are also bounded so they stay readable. get_full_output returns stderr and the traceback in stderr rather than stdout, paged by the stderr cap, so the fence labels them as what they are. The summary sees updates made in place. Identity alone missed signal[3] = nan and signal -= 1, the most common update in data code; module-level assignment targets, including through a subscript or an attribute, are now read from the code. Function bodies are not entered, and a mutating method call such as append is a pinned, known limit. Silent paths now say what happened: a figure registry that cannot be enumerated is reported rather than returning a clean, empty success; the import gate no longer reports its own failure as a missing package, and a cached module with no spec is importable rather than denied. resolveLimits applies RuntimeLimits' floors as well as the server's ceilings, from a table drift-tested against the Python: below the floor the default is used, since clamping a zero deadline up to one second would time out every run. _clip's small-limit branch, which had no test and could return text many times over its cap, is now checked across every limit up to 89, and the image byte cap has its first test. RuntimeLimits.stdout_bytes and stderr_bytes are renamed *_chars. Every consumer counts characters, and the byte names told a community author that multibyte output costs more than it does. Neither is on develop or main, so nothing released reads the old names. Also: the worker core validates its configuration and names the bad field before loading anything; FullOutputStore's state is private, so its size accounting cannot be desynchronized from outside; and two JSDoc blocks stranded by an earlier refactor sit on their own methods again. Tested against real Pyodide and in real workers; every change mutation-checked. Python: 2529 passed, coverage 78%.
Timeout and oom results differed only in status, message and elapsed time. Lifecycle suite 131/131.
The widget reads which client tools a community runs, and the runtime section, from GET /config; the kill switch empties both. pytest green.
It is serialized into the worker by toString, and a minified reference to the module's reason table was a ReferenceError on every request, which the probe reported as a network error. The table is now local, an isolation test runs the stringified copy, and the probe classifies a guard failure separately. Egress suite 80/80.
scripts/build-runtime-bundle.js builds frontend/osa-runtime.bundle.js with the Bun that package.json pins and writes its sha384 into the widget, which will inject it with an integrity attribute. CI installs that Bun, fails on a stale bundle or hash, and runs the bundle as built on real Pyodide. Bundle suite 18/18.
The widget declares every configured tool plus get_full_output, and a request declaring more than eight is refused whole, so a community with eight tools would 422 on every message. The config cap is now derived from the request cap. The config response also carries each tool's runtime, so the widget declares only what it can run. pytest green.
PyodideRuntime.cancel() resolves the call with status cancelled and recycles the instance, as a timeout does. A call still waiting on a cold boot is answered at once and never reaches the worker, while the boot carries on. Lifecycle suite 151/151, bundle rebuilt.
ClientToolController turns each tool_request into exactly one result: the gate unless auto-run is on or both the request and the config waive it, then execute; get_full_output without asking; an error result for an unknown tool, missing code, a failed gate or a runtime that cannot start. Deny posts denied; Stop while asked declines, Stop while running cancels. highlightPython tokenizes raw code and escapes each token. Both ship in the bundle. Controller suite 77/77, bundle 25/25.
Run 1 and run 2 each numbered sources from [1], so a reply citing one source before the browser call and another after showed two [1]s. The parked call now carries run 1's citation marks and run 2's assembler continues from them. tool_request also carries run 1's normalized text and citations, as done does for a finished run. pytest green.
The widget loads the SRI-pinned runtime bundle for a community with client tools and declares them only once it has loaded. A tool_request is answered through the controller behind a highlighted permission gate, posted to /chat/resume, and run 2 streams into the same reply, which records what ran and shows its figures without storing them. Stop, deny and auto-run for the page are wired. A reply that ran code is no longer dropped when the model adds no text. Streaming suite 72/72; verified in Chrome under the production CSP.
Serves the widget beside the real community router for a synthetic community that runs Python, with a streaming scripted model standing in for the LLM. Records the Chrome measurements, including the tampered bundle negative control.
Review of step 7. A reply may request at most 10 browser runs: the parked call carries its run count, and the run with no budget left refuses a further call in writing. /chat/resume is exempt from the hourly rate limit, so this bound has to live on the server. Also: build the citation assembler inside the stream's handlers, so a malformed carried citation is logged with an error id instead of ending the stream silently. from_state takes the carried state. The tool_request payload and the tool runtime are typed. Comments no longer assume a reply has exactly two runs. Budget, third-run and error-path tests added, each mutation-checked. pytest green.
Review of step 7. The gate always resolves, even when rendering throws; before this, a render error froze the widget and left the server's call parked. The tool panel cannot outlive its answer. The gate strings and the full-output tool name come from the loaded runtime. One field-limit table serves both writing and reloading a run record. The tool_request loop is its own function, noting a stopped reply inside the reply. A runtime that fails to load logs a fixed reason= line, is reported by getBrowserRuntimeStatus(), and is retried once when the chat is next opened. frontend/test-widget-tools.js runs the widget on happy-dom (a dev dependency, pinned exactly) and covers: escaping, parsed back against an allowlist; persistence bounds; the run cap; the shared deadline; bundle load failures; the real bundle answering through the gate while rendering fails; and continuations. 86/86, mutation-checked. Also fixes the placeholder-guard test that failed CI on 3a0c208. Re-verified in Chrome under the production CSP.
Raise MAX_BROWSER_RUNS_PER_REPLY from 10 to 20, on the server and in the widget. A reply chaining that many runs can meet the worker's per-minute limit on /chat/resume, after the code has already run, so the widget now waits that limit out (twice, 30 s then 35 s) and re-sends the same result instead of dropping it. An hourly refusal still fails at once and names the limit. Corrects the comment that called resume exempt from the hourly limit: it has its own budget. Widget suite 94/94, pytest green.
zarr 3.4.0 imports google_crc32c, which 0.28.3 does not ship, so the NEMAR data lane needs 0.29.5. The worker core test now reads the version from the installed package. The Chrome harness passes every check on 0.29.5 under the nemar policy, and the control still fails; its limit is 10 s because a first figure spends about 4.3 s importing matplotlib in a fresh instance.
osa.fetch(url, headers={'Range': ...}) returns (status, body) rather
than raising on a status, which is what a host transport such as
eegprep-lean's FetchTransport needs; Range is the only header it will
send. fetch_bytes is now built on it. Tested on real Pyodide 0.29.5
under Bun and in Chrome under the nemar policy.
lockfile now names a Pyodide lock overlay in the community's folder:
pure-Python wheels the runtime adds to its Pyodide version, each with
its sha256, verified against the committed wheel when loaded. /config
carries the entries, GET /{community}/runtime/{file_name} serves only
the listed wheels as immutable, and an overlay that does not verify
fails closed with no client tools. prelude is Python the runtime runs
after its seal, compiled at config load. Full suite passes.
GET /:community/runtime/:file takes a bare wheel name, answers repeats from the edge cache, and on a miss spends per-minute budget but none of the hourly chat budget. A backend failure is a 502, distinct from the backend's own 404. Routing tests cover the route, the bytes and headers returned, and the hourly exemption with a KV stand-in.
The worker merges the lock overlay from /config into the stock lock of its Pyodide version, refusing any entry that would replace one, and hands it to loadPyodide, so preload resolves overlay packages and their dependencies with Pyodide checking every wheel's sha256. Each wheel is allowed at boot by its exact URL on the API. A prelude runs after the seal, and a failing one fails the boot. Tested on real Pyodide under Bun.
zarr 3.4.0 (PyPI's own bytes) and eegprep-lean 0.1.0.dev1 (built from sccn/eegprep 67670f5b) with the Pyodide lock overlay that pins them. scripts/build_runtime_lock.py regenerates an overlay from its wheels and depends.toml, checks it with --check, and refuses new bytes under a committed wheel name.
execute_code behind the gate, on Pyodide 0.29.5 with the overlay's zarr and eegprep-lean, reaching only zarr.nemar.org. The prelude makes the runtime's own client eegprep-lean's transport, so the python_browser recipe runs as nemar_read_window hands it out. The data-lane test boots NEMAR's real config on real Pyodide and reads a sharded store over HTTP; it runs in CI.
widget_e2e.py serves NEMAR's own config with --nemar, and can corrupt every wheel (--tamper-wheel) or boot on open (--widget-open). Measured against the live archive: read_window and the python_browser recipe both run, wheels load with their integrity, a tampered wheel is refused by the browser, and widget_open boots with nothing sent.
Contributor
Preview Deployment
This preview will be updated automatically when you push new commits. |
The lock verification now caches the verified bytes and a refusal alike, so the route serves exactly what was hashed and a broken overlay is hashed once rather than per request. The wheel route follows the same client-tools gate as /config and answers 503, not 404, for an overlay that does not verify. The models are frozen and handed out as copies. Tested: pytest runtime lock and router suites, each new guard mutation-checked.
A test now verifies and --check-s the overlay of every community that names one, which the fail-closed path's docstring relied on. The builder maps an unreadable wheel, METADATA without Name or Version, malformed depends.toml and a committed overlay that does not load to its own error, and refuses a depends value that is not a list. Tested: pytest test_nemar_runtime and test_shipped_runtimes, with mutation checks on the new guards.
allow_install names micropip's default index, and client_tools.py no longer says no community declares a client tool. Tested: pytest test_community.
A cache.put that rejects is logged instead of lost. test-routing.js supplies a Map for caches.default and checks that a repeat request skips the backend, carries CORS for the embedder asking now, and that the backend's 503 is a 502 that is not cached. Tested: bun workers/osa-worker/test-routing.js, each cache path mutation-checked.
osa.fetch catches only the browser's rejection and says what "no response" can mean. A stock lock that cannot be read and an overlay that cannot be merged fail the boot as kind lock, before Pyodide loads. The worker's platform glue is createWorkerEnv, embedded by value and now run by a test against a real server. Wheel names in the lock must be -py3-none-any, as the server requires. A malformed lock in the widget is reported as setup-failed. Both byte-range test hosts share test-support/byte-range.js. Tested: every bun frontend suite, bundle --check, mutation checks on the new lock-failure paths.
Every community with runtime.python must pin the Pyodide CI runs, and its overlay's depends and preload must resolve in that lock. Tested: bun frontend/test-data-lane.js.
chrome.js drives the harness over the DevTools protocol with no new dependency: nemarlike must pass every check and control must fail to boot. serve.js replaces serve.py and serves NEMAR's wheels as the API does, with a tampered copy that is a valid wheel (the extra byte is the zip's comment), so only the digest can refuse it. The harness now boots NEMAR's runtime from its overlay by URL and checks the prelude. widget_e2e.py tampers the same way. Tested: chrome.js passes locally (40 checks, control fails); with checkIntegrity off in loadPackage it fails on the tampered wheel.
Pyodide's default, written out because the lock overlay rests on it. Tested: bun frontend suites, bundle --check, chrome.js.
The micropip execution path, the proposed wire shapes, the caps table, the configuration example and the Pyodide references each get an As built note naming what ships and where it is declared. Not tested: documentation only.
Member
Author
Local review, and what was done with each findingSix Sonnet reviewers covered step 8 ( The largest gap: the browser's integrity check had no CI coverageUnder Bun, Pyodide loads a lock entry from a local path and ignores its sha256.
Code
Errors
Tests
Types
Comments and docs
Simplification
Phase seams
Gates
|
neuromechanist
merged commit Sep 23, 2026
4fbc5db
into
feature/issue-429-epic-browser-execution
14 checks passed
This was referenced Sep 23, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Phase 2 of the browser-execution epic: the widget executes what phase 1 taught the server to ask for.
Model-written Python runs in the reader's own browser, in a sealed Pyodide worker, only after the reader approves it. The result, figures included, goes back to the model through the two-run continuation.
NEMAR is the first community to offer it. Its
python_browserrecipe runs exactly asnemar_read_windowhands it out, and it was verified in Chrome against the live archive under nemar.org's production policy.Implements
.context/browser-execution-tool-design.md, phase 2 (#431). Step-by-step measurements are recorded on #431.What ships
frontend/osa-runtime.js,osa-worker-core.js,osa-egress.js,osa-output.js).fetch_allowbefore any executed code exists, and it fails closed.micropip,js,pyodideandctypes, andosa.fetch_bytes,osa.fetch_textandosa.fetchare the one sanctioned network route.frontend/osa-chat-widget.js).runtime.python.lockfilenames a Pyodide lock overlay in the community's folder. The server verifies every wheel against its sha256 once per process, sends the entries in/config, and serves the verified bytes atGET /{community}/runtime/{file}as immutable. An overlay that does not verify withdraws the community's client tools and answers the route with a 503. The worker route caches the wheels and exempts them from the hourly budget.preloadresolves overlay packages with the browser enforcing each digest, and there is no micropip in this path.runtime.python.preluderuns after the seal with executed code's privileges.execute_codebehind the gate, on Pyodide 0.29.5, with zarr 3.4.0 and eegprep-lean 0.1.0.dev1 in its overlay, reaching onlyhttps://zarr.nemar.org/.osa.fetch. The upstream half is eegprep-lean: let the host choose the transport sccn/eegprep#414, merged.Decisions worth reviewing rather than skimming
Wheels live with the community and are served by this API, not beside the widget. The server that sends the hashes serves the bytes, so a lock and its wheels cannot come from different releases, and an eegprep-lean bump is a server deploy with no widget release and no nemar.org re-pin. A wheel's name is its identity, cached for a year, so the generator refuses new bytes under a committed name.
The prelude runs without the gate. The gate exists for code a model wrote, which fetched content can steer. A prelude is community code, reviewed in a pull request like the config it lives in. It still gets exactly executed code's privileges, because it runs after the seal. It is compiled at config load, and a failing prelude fails the boot rather than every later run.
The egress guard is the boundary; the namespace seal is not. Nothing in Pyodide can be a Python-to-JavaScript boundary, since any proxy reaches JavaScript through its own
constructor. So the fetch shim is non-writable and non-configurable, with the native fetch deleted from the prototype chain, and nested workers are blocked. The seal removes the obvious routes so a model does not stumble onto one.Pyodide 0.29.5. zarr 3.4.0 imports
google_crc32c, which 0.28.3 does not ship. The seal, the guard and a boot were re-verified in Chrome on 0.29.5.Measured, and worth knowing
file_namewithpath.resolve, so an absolute URL does not load, and it ignores the digest entirely.frontend/test-data-lane.jstherefore names the committed wheels by path. The browser harness, now in CI, proves URL loading and integrity. Its tampered wheel has to be a valid wheel, one byte longer with the byte as the zip's comment: a bare appended byte breaks the zip, and the boot then fails even with integrity off.TypeError.display(...). The tool description says so.Test plan
uv run pytest-> 2623 passed, 58 skipped.uv run ruff check .anduv run ruff format --check .are clean.tests/test_assistants/test_shipped_runtimes.pyverifies every shipped overlay against its wheels.bunsuite, in CI:frontend/test-worker-core.jsandfrontend/test-data-lane.jsrun the real core against the real Pyodide 0.29.5 from npm. The data-lane test loads NEMAR's real config, overlay and wheels, and reads a sharded store built by the same zarr over HTTP with byte ranges.test-widget-tools.jsdrives the widget on happy-dom with the bundle as built.workers/osa-worker/test-routing.jscovers the new wheel route, including the hourly exemption through a KV stand-in and the edge cache through acaches.defaultstand-in.frontend/browser-harness/chrome.jsruns the browser harness in headless Chrome: the seal, the egress guard, the deadline and output capture under nemar.org's policy, then NEMAR's runtime booted from its overlay by URL, and a tampered wheel refused. The no-wasm control must fail to boot.bun scripts/build-runtime-bundle.js --checkkeeps the bundle and its SRI hash current.frontend/browser-harness/README.mdand on Phase 2: Widget, the Pyodide runtime and execute_code #431:widget_e2e.pyfor the widget with the real router;widget_e2e.py --nemaragainst the live archive, with--tamper-wheelas the integrity control and--widget-openfor eager boot.checkIntegrityinloadPackage, which failschrome.js.Not verifiable before the epic merges: the worker's wheel route on the edge, since the worker deploys only from
mainordevelop.Known, not caused here
tests/test_integration/test_anthropic_platform.py::TestToolResultImagesfailed once on this head: claude-haiku-4-5 named the tallest bar oftallest_thirdcorrectly and the shortest wrongly. The image arrived, and a rerun of the job passed (run 35797535085, attempt 2). Filed as Flaky: haiku misreads a bar chart in TestToolResultImages #447, beside Flaky: test_the_summary_survives_the_fencing, Haiku sometimes ignores a fenced tool result #445.Closes #431.
Part of epic #429.