Skip to content

Phase 2: Widget, the Pyodide runtime and execute_code - #448

Merged
neuromechanist merged 43 commits into
feature/issue-429-epic-browser-executionfrom
feature/issue-431-phase2-pyodide-runtime
Sep 23, 2026
Merged

neuromechanist merged 43 commits into
feature/issue-429-epic-browser-executionfrom
feature/issue-431-phase2-pyodide-runtime

Conversation

@neuromechanist

@neuromechanist neuromechanist commented Sep 22, 2026 •

Copy link
Copy Markdown
Member

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_browser recipe runs exactly as nemar_read_window hands 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

  • A sealed runtime (frontend/osa-runtime.js, osa-worker-core.js, osa-egress.js, osa-output.js).
    • One blob worker per community per tab. Its boot is bounded, because a CSP refusal never resolves and never errors.
    • An egress guard is installed before the loader is fetched. It is sealed to the community's fetch_allow before any executed code exists, and it fails closed.
    • A Python namespace seal removes micropip, js, pyodide and ctypes, and osa.fetch_bytes, osa.fetch_text and osa.fetch are the one sanctioned network route.
    • An import gate denies packages nobody installed.
    • Output capture and a deterministic summary: arrays by facts, errors by type and line, figures in words.
    • A host-side deadline, cancellation that recycles the worker, and out-of-memory handling.
  • The widget (frontend/osa-chat-widget.js).
    • The runtime is one SRI-pinned bundle, loaded lazily.
    • A permission gate shows the description and highlighted code, with Run, Don't run, and "run without asking until I reload".
    • The continuation loop streams run 2 into the same reply, and citation numbering is carried across the runs.
    • Stop, and a per-reply cap of 20 browser runs, which the server enforces too.
    • Retries on per-minute 429s.
    • Run records persist without their images.
  • Community-owned environments.
    • runtime.python.lockfile names 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 at GET /{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.
    • The browser merges the overlay into the stock lock of the pinned Pyodide version, so preload resolves overlay packages with the browser enforcing each digest, and there is no micropip in this path.
    • runtime.python.prelude runs after the seal with executed code's privileges.
  • NEMAR enabled.
    • execute_code behind the gate, on Pyodide 0.29.5, with zarr 3.4.0 and eegprep-lean 0.1.0.dev1 in its overlay, reaching only https://zarr.nemar.org/.
    • Its prelude registers eegprep-lean's transport over 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

  • In Chrome, a fresh instance spends about 4.3 s importing matplotlib and pyplot, against 0.9 s under Bun. The static harness limit is 10 s for that reason.
  • Pyodide's Node loader resolves a lock file_name with path.resolve, so an absolute URL does not load, and it ignores the digest entirely. frontend/test-data-lane.js therefore 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.
  • Bun's native fetch rejection is an object Pyodide's future helper refuses, so a Python await on it never settles. A browser rejects with an ordinary TypeError.
  • eegprep-lean draws on its own figure rather than pyplot's, so a plot reaches the model only through display(...). The tool description says so.

Test plan

  • uv run pytest -> 2623 passed, 58 skipped. uv run ruff check . and uv run ruff format --check . are clean. tests/test_assistants/test_shipped_runtimes.py verifies every shipped overlay against its wheels.
  • Every bun suite, in CI:
    • frontend/test-worker-core.js and frontend/test-data-lane.js run 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.js drives the widget on happy-dom with the bundle as built.
    • workers/osa-worker/test-routing.js covers the new wheel route, including the hourly exemption through a KV stand-in and the edge cache through a caches.default stand-in.
    • frontend/browser-harness/chrome.js runs 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 --check keeps the bundle and its SRI hash current.
  • Chrome by hand, recorded in frontend/browser-harness/README.md and on Phase 2: Widget, the Pyodide runtime and execute_code #431:
    • widget_e2e.py for the widget with the real router;
    • widget_e2e.py --nemar against the live archive, with --tamper-wheel as the integrity control and --widget-open for eager boot.
  • Mutation-checked throughout: each new guard was loosened or removed in turn, and each change failed a test. That includes turning off checkIntegrity in loadPackage, which fails chrome.js.
  • Reviewed locally by seven Sonnet agents. How each finding was addressed is in the PR comments.

Not verifiable before the epic merges: the worker's wheel route on the edge, since the worker deploys only from main or develop.

Known, not caused here

Closes #431.
Part of epic #429.

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.
@github-actions

github-actions Bot commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor

Preview Deployment

Name Link
Preview URL https://feature-issue-431-phase2-pyo-demo.osc.earth
Branch feature/issue-431-phase2-pyodide-runtime
Commit 0f289cc

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.
@neuromechanist

neuromechanist commented Sep 23, 2026 •

Copy link
Copy Markdown
Member Author

Local review, and what was done with each finding

Six Sonnet reviewers covered step 8 (53076d1..6825135): code, tests, errors, types, comments and docs, and simplification. A seventh reviewed seams across the whole phase.
None found a runtime bug in what ships.
Every finding is addressed below, in commits be9c100..f759237.
The two not taken as proposed are explained.

The largest gap: the browser's integrity check had no CI coverage

Under Bun, Pyodide loads a lock entry from a local path and ignores its sha256.
So the one property the lock overlay rests on was checked only by hand, in Chrome.

  • frontend/browser-harness/chrome.js now runs the harness in headless Chrome, in CI, over the DevTools protocol, with no new dependency.
    nemarlike must pass every check, and control, which has no wasm grant, must fail to boot.
  • serve.js replaces serve.py. It serves NEMAR's wheels as the API does.
    The harness boots NEMAR's runtime from its overlay by URL, imports eegprep-lean and zarr, and checks that the prelude made osa.fetch their transport.
  • The tampered wheel is now a valid wheel, with the extra byte written as the zip's comment.
    The first mutation run showed why this matters: with a bare byte appended, turning integrity off still failed the boot, because the zip was broken.
    With a valid tampered wheel, checkIntegrity: false in loadPackage fails chrome.js on exactly that check ("it booted").
    widget_e2e.py --tamper-wheel now tampers the same way.
  • loadPackage passes checkIntegrity: true explicitly.

Code

  • A failed verification was not cached, so a broken overlay was re-hashed on every request. Now a success and a refusal are cached alike. The reason is cached, not the exception, whose traceback would grow on every re-raise. be9c100
  • The wheel route now follows the same client-tools gate as /config: a community that offers no client tools serves no wheels. be9c100

Errors

  • The route served bytes re-read from disk after they had been verified. Now the verified bytes are held and served, so a file changed after the check cannot go out under the entry's name. be9c100
  • An overlay that does not verify returns 503, not 404. The worker turns that into a 502 and does not cache it. The two call sites share one log line. be9c100, 4ac6d52
  • osa.fetch catches only JsException, and header marshaling moved out of the try. The message now lists what "no response" can mean: a network failure, a refused redirect, a host without CORS, or a URL outside fetch_allow. A Bun test covers this path through a host refused the way a browser refuses one. c165aa9
  • A stock lock that cannot be read and an overlay that cannot be merged now fail as kind: 'lock', before Pyodide loads, with messages naming which. The host reads only the message, so the message is the fix that matters. c165aa9
  • cache.put rejections are logged. 4ac6d52
  • build_runtime_lock.py: an unreadable wheel, METADATA without Name or Version, and a malformed depends.toml or committed overlay each raise a LockBuildError that names the cause. A depends value that is a string would have been sorted into characters; it is now refused. 1f19b3d
  • Skipped: a metric beside the log line. OSA has no counter facility. The verdict is cached, so the line is logged on every request that meets it without a re-hash, and a broken deployment keeps saying so.

Tests

  • The route's no-lockfile 404 and no-client-tools 404. be9c100
  • The edge cache, with a Map standing in for caches.default: a repeat request skips the backend, carries CORS for the embedder asking now, and a 503 is not cached. 4ac6d52
  • The cache key: two communities with the same lockfile name stay apart. be9c100
  • All the build script's error branches. 1f19b3d
  • mergeLock on a lock with no packages. c165aa9
  • The worker's stock-lock read is now createWorkerEnv, embedded by value like the core and run by a test against a real server, including its HTTP-error branch. c165aa9
  • The widget reports a malformed lock as setup-failed and declares nothing. c165aa9
  • The prelude cap at exactly 4000 and 4001 characters, and explicit nulls. 009406b
  • Each new guard was mutation-checked, and each mutation was confirmed to apply. The narrowed except in osa.fetch is the exception: no natural input reaches it with a non-JS error.

Types

  • RuntimeLockPackage and RuntimeLockOverlay are frozen, and load_runtime_lock returns a deep copy. be9c100
  • The browser's wheel-name pattern is now -py3-none-any.whl, matching the server's. The worker's pattern stays a coarse filter, and its comment says the backend owns the exact rule. c165aa9, 4ac6d52
  • Every community with runtime.python must pin the Pyodide CI runs, and its overlay's depends and preload must resolve in that lock. c3bb01e

Comments and docs

  • "A test loads every shipped overlay" was true only because NEMAR is the only community with one. tests/test_assistants/test_shipped_runtimes.py now verifies and --checks every overlay, so the docstring holds by construction. 1f19b3d
  • The design note's micropip execution path, its wire examples, its caps table, its configuration example (Pyodide 314.0.6 and analysis_engine, neither valid) and its Pyodide references each have an "As built" note naming what ships. f759237
  • allow_install now names micropip's default index. 009406b
  • The dated "measured" claims record real Chrome runs from this step, and chrome.js now re-measures them on every CI run.

Simplification

  • One helper decides which lockfile applies, shared by /config and the route. be9c100
  • from scripts import build_runtime_lock replaces the importlib loader. hashlib and json are now module-level imports in the router tests. 1f19b3d, be9c100
  • Both byte-range test hosts share frontend/test-support/byte-range.js. c165aa9

Phase seams

  • The client_tools.py docstring said no community declares a client tool. It now says NEMAR does, and that the kill switch is the incident control. 009406b
  • The design note's configuration example and wire shapes: see above. f759237
  • A seam checked and found consistent: community-admin-pr-merge.yml lets a community's maintainers merge changes under src/assistants/<id>/, which now includes wheels, the overlay and the prelude. That matches the trust model. The community already owns its prompt and fetch_allow, the prelude and wheels run sealed with executed code's privileges, and CI verifies the overlay against its wheels before any such merge.

Gates

  • uv run pytest: 2623 passed, 58 skipped. The one failure is test_version_shows_version fails locally and passes in CI, because rich colorizes on a TTY #434, the version test on a color terminal, which passes in CI. Ruff check and format are clean.
  • Every bun suite and build-runtime-bundle.js --check pass. chrome.js passes locally and on the GitHub runner: 40 checks on nemarlike, and control fails to boot.
  • CI run 35801562919, dispatched on f759237, is green in every job, integration included.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant