Repository navigation
feat(emergent): QuickJSExecutor, an isolating executor for forged code - #160
Conversation
Both packages pinned exactly, as peers marked optional and as dev dependencies for the executor's tests. A host that never builds a QuickJS executor installs neither.
…tance of its own for each call QuickJS compiled to WebAssembly from two optional peers, the variant compiled once and instantiated for every call on a memory capped at the call's memoryMB. Granted functions cross as host functions that take and return data, under a prelude that builds what the in-process context hands forged code, Intl through the host included, and refuses string code generation as the in-process context does. Per call: the result limited to 1 MB, response bodies together to memoryMB, 64 open hashes, 16 host calls in flight; a host value that does not fit the guest's memory ends the call out of memory; without a ceiling the call's requests are aborted when it ends. The corpus, the memory bound, the deadline, the stack and the escape probes run in the main suite.
|
Warning Review limit reached
This review includes 26 billable files and costs up to $6.50.
Reviews can continue after your included limit without a manual trigger. An admin must approve usage-based billing. Or wait 47 minutes for your next included review. View limit detailsLimit details: You’ve used all 4 included reviews currently available. Review configuration: ⚙️ Run configuration
⛔ Files ignored due to path filters (1)
📒 Files selected for processing (26)
Comment |
Reviewer's GuideThis PR adds an optional QuickJS 0.32.0 WebAssembly executor that runs each forged-code call in a fresh, bounded guest with data-only capability bindings, integrates executor selection and readiness into emergent forges, and supplies extensive isolation/limit tests, documentation, and CI coverage. Sequence diagram for a bounded QuickJS forged-code callsequenceDiagram
participant Caller
participant QuickJSExecutor
participant GuestRun
participant QuickJSWasm
participant HostBindings
Caller->>QuickJSExecutor: run(request)
QuickJSExecutor->>QuickJSExecutor: ready()
QuickJSExecutor->>QuickJSWasm: instantiate fresh WebAssembly.Memory
QuickJSWasm-->>QuickJSExecutor: isolated runtime and context
QuickJSExecutor->>GuestRun: execute(request, memoryBytes, ended)
GuestRun->>HostBindings: guestBindings(globals, limits)
HostBindings-->>GuestRun: data-only host bindings
GuestRun->>QuickJSWasm: evalCode(GUEST_PRELUDE)
GuestRun->>QuickJSWasm: evalCode(forged.js)
QuickJSWasm->>HostBindings: fetch, fs_readFile, crypto, Intl
HostBindings-->>QuickJSWasm: copied data or promise result
QuickJSWasm-->>GuestRun: result, timeout, or memory_exceeded
GuestRun-->>QuickJSExecutor: ExecutorRunResult
QuickJSExecutor->>QuickJSWasm: dispose runtime and context
QuickJSExecutor-->>Caller: result
State diagram for QuickJS executor availability and call lifecyclestateDiagram-v2
[*] --> Unloaded
Unloaded --> Loading: ready()
Loading --> Available: loadEngine()
Loading --> Unavailable: quickjs_unavailable
Available --> Running: run(request)
Running --> Completed: result returned
Running --> TimedOut: deadline or abort
Running --> MemoryExceeded: memory limit reached
Completed --> Disposed: runtime.dispose()
TimedOut --> Disposed: runtime.dispose()
MemoryExceeded --> Disposed: runtime.dispose()
Unavailable --> FailedCall: run(request)
Disposed --> Available
FailedCall --> Unavailable
File-Level Changes
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
… the server A guest that starts a request and returns in the same turn has it aborted before it is sent, so the server saw nothing to close. The guest now awaits an endpoint that answers once the held request has arrived, and the test then waits for that connection to close.
…length A buffer over 4 KiB returned by a binding was written into a guest buffer 64 bytes longer than itself, so TextEncoder.encode of a long string came back padded. The checked copy now allocates the buffer's own length. The call's source is checked for room before it is copied in, like any host value. Tests: a long string encoded and decoded exactly; a BigInt formatted through the host as in-process.
…ge the engine builds Absent, the engine builds its forge on the in-process executor as before. A host-built sandboxForge on another executor passed beside it fails construction with executor_conflict. An executor may offer ready(); the engine awaits it before a forge's test cases and refuses the forge with its reason. QuickJSExecutor, QuickJSUnavailableError and QUICKJS_VERSION are exported.
The Executors section compares the two executors and says what crosses into the guest, its bounds, its memory, its thread and what the isolation claim rests on. README no longer calls the in-process context hardened or forged code TypeScript with Zod schemas; the word check now covers README, the self-extension page and the executor files, and a CI step runs the executor from the built package.
Its questions are answered and its prototype is replaced by QuickJSExecutor; the main suite runs the corpus, the memory bound, the deadline, the stack and the escape probes on the shipped executor on every change.
The checked copy wrote a large buffer into what the binding layer's getArrayBuffer returned, which is a copy of the guest buffer's bytes and not a view of them, so the guest received zeros. A buffer now takes the path every other large value takes: room for it is checked with QuickJS's allocator, then it is copied in. The test added in the last commit (a long string encoded and decoded exactly) failed on this and passes with it.
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
PR Summary by QodoAdd an isolated QuickJS executor for forged tools
AI Description
Diagram
High-Level Assessment
Files changed (19)
|
## [0.12.22](v0.12.21...v0.12.22) (2026-10-08) ### feat * **emergent:** QuickJSExecutor, an isolating executor for forged code (#160) ([598d041](598d041))
Code Review by Qodo
1. Guest prelude export lacks documentation
|
| */ | ||
| (() => { | ||
|
|
||
| export const GUEST_PRELUDE = String.raw`(() => { |
There was a problem hiding this comment.
1. Guest prelude export lacks documentation 📘 Rule violation ⚙ Maintainability
GUEST_PRELUDE is exported without a symbol-level TSDoc comment; the preceding @fileoverview documents the file instead. When a reader looks up the exported constant used by QuickJSExecutor, there is no documentation attached to that declaration describing its contract.
Agent Prompt
## Issue description
`GUEST_PRELUDE` is exported without its own TSDoc comment; the file overview does not document the symbol.
## Fix Focus Areas
- src/cognition/emergent/executor/guest-prelude.ts[20-22]
## Recommended Fix
Add a TSDoc comment immediately above the export describing the prelude string and how the executor uses it.
ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools
| let values: unknown[]; | ||
| try { | ||
| values = args.map((arg) => live.context.dump(arg) as unknown); | ||
| } catch (error) { | ||
| return { error: live.context.newError({ name: 'TypeError', message: `${name} takes data only: ${message(error)}` }) }; |
There was a problem hiding this comment.
2. Guest arguments can exhaust host memory 🐞 Bug ➹ Performance
install() calls context.dump() on every guest argument without a size or depth limit before invoking a host binding. A forged tool can build a large value within its capped WebAssembly memory and pass it to an exposed binding, causing an unbounded copy into host memory outside that cap.
Agent Prompt
## Issue description
Guest arguments are copied into host objects without a size or depth bound, bypassing the per-call guest-memory ceiling.
## Fix Focus Areas
- src/cognition/emergent/executor/QuickJSExecutor.ts[448-465]
## Recommended Fix
Enforce a per-call argument byte and structural-depth limit before materializing guest values on the host. Reject arguments that exceed it without performing an unbounded dump.
ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools
| runtime = module.newRuntime(); | ||
| runtime.setMemoryLimit(maximumPages * PAGE_BYTES); | ||
| runtime.setMaxStackSize(STACK_BYTES); | ||
| guest = new GuestRun(runtime, memory, performance.now() + request.timeoutMs, request.signal); |
There was a problem hiding this comment.
3. Invalid deadlines can stall the host 🐞 Bug ☼ Reliability
run() adds request.timeoutMs to the deadline without checking that it is finite, and the interrupt handler relies on comparisons against that deadline. If a caller supplies NaN or Infinity, a synchronous infinite loop never meets the interrupt condition; the forge passes its requested timeout through without validating it.
Agent Prompt
## Issue description
Non-finite timeout values disable the interrupt deadline and let a synchronous guest loop block the host indefinitely.
## Fix Focus Areas
- src/cognition/emergent/executor/QuickJSExecutor.ts[214-238]
- src/cognition/emergent/SandboxedToolForge.ts[377-379]
## Recommended Fix
Reject or normalize non-finite and non-positive timeout values before constructing the guest deadline. Keep the interrupt and progress paths tied to a finite deadline.
ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools
| const settled: Promise<void> = result | ||
| .then( | ||
| (value) => this.settle(id, { value }), | ||
| (error: unknown) => this.settle(id, { error }), |
There was a problem hiding this comment.
4. Stalled file reads retain guest memory 🐞 Bug ☼ Reliability
bridge() attaches promise reactions that retain the GuestRun, while dispose() leaves its WebAssembly.Memory reference in place after a timeout. If an allowed fs.readFile remains pending, its binding has no abort signal, so repeated timed-out calls can retain a fresh guest memory instance for each pending read.
Agent Prompt
## Issue description
An outstanding host promise can keep a completed guest run and its WebAssembly memory reachable after timeout.
## Fix Focus Areas
- src/cognition/emergent/executor/QuickJSExecutor.ts[261-274]
- src/cognition/emergent/executor/QuickJSExecutor.ts[384-400]
- src/cognition/emergent/executor/QuickJSExecutor.ts[492-509]
- src/cognition/emergent/executor/guest-surface.ts[248-252]
## Recommended Fix
Detach outstanding host-promise reactions from the guest's memory-owning state when a call ends, and make file reads cancellable where the underlying capability permits it.
ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools
| bindings.fetch = async (input, init) => { | ||
| const options = init === null || init === undefined ? {} : (init as Record<string, unknown>); | ||
| const response = (await (fetchFn as (i: unknown, o?: unknown) => Promise<Response>)( | ||
| input, | ||
| limits.signal ? { ...options, signal: limits.signal } : init === null ? undefined : init, | ||
| )) as Response; |
There was a problem hiding this comment.
5. Forged posts with non-string bodies go out empty 🐞 Bug ≡ Correctness
The guest prelude's fetch copies init.body into the options it sends to host.fetch only when typeof init.body === 'string'. The fetch binding then forwards those options as they are, so a body given as URLSearchParams, Uint8Array, ArrayBuffer or another typed array is dropped without an error. The request still goes out with its method and headers but no payload. On the in-process executor the same tool sends the body, and nothing in the forged-tool corpus covers this case.
Agent Prompt
## Issue description
The QuickJS guest `fetch` in the prelude keeps `init.body` only when it is a string. A `URLSearchParams`, `ArrayBuffer`, `Uint8Array` or other typed-array body is dropped without an error, so the request goes out with no payload. The in-process executor sends these bodies.
## Fix Focus Areas
- src/cognition/emergent/executor/guest-prelude.ts[473-480]
- src/cognition/emergent/executor/guest-surface.ts[226-231]
## Recommended Fix
In the prelude, encode the body as data:
- a string becomes `{ s: body }`
- a `URLSearchParams` becomes `{ s: body.toString(), form: true }`
- an ArrayBuffer or typed array becomes `{ b: bytesToLatin1(toBytes(body)) }`
- any other type throws a `TypeError`; do not drop it.
In the `fetch` binding, decode it back before calling the forge's fetch:
- `{ s }` becomes a string
- `{ b }` becomes `Buffer.from(b, 'latin1')`
- for `form`, add `content-type: application/x-www-form-urlencoded;charset=UTF-8` when the guest set no content type.
Add an integration test that POSTs each body type to a local server and checks the bytes that arrive.
ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools
What this changes
QuickJSExecutor, a second executor for forged code: QuickJS compiled to WebAssembly, a new instance for each call on aWebAssembly.Memorycapped at the call'smemoryMB(never below 16 MiB, never above 2,048 MiB). It declaresisolates: true. Its engine comes from two optional peer dependencies,quickjs-emscripten-coreand@jitl/quickjs-wasmfile-release-sync, both pinned at 0.32.0; a host that never builds the executor installs neither, and one that builds it without them, or with another version, getsquickjs_unavailablenaming both (await QuickJSExecutor.create()fails fast;new QuickJSExecutor()fails at its first call).fetch,fs.readFile,crypto,TextEncoder,TextDecoder,URL,URLSearchParams,structuredClone,atob,btoa, a console that discards),Intland the locale methods formatted by the host, and the refusal of string code generation the in-process context applies.memoryMBand the deadline: the result at 1 MB of UTF-8; response bodies together atmemoryMB; 64 open hashes; 16 host calls in flight. A host value that does not fit what the guest has left ends the callmemory_exceeded. Without a ceiling, the call's requests are aborted when it ends.emergentConfig.executorpicks the executor of the forge the engine builds; absent, nothing changes. A host-builtsandboxForgeon another executor passed beside it fails construction withexecutor_conflict.ForgedCodeExecutorgains an optionalready(): the engine awaits it before a forge's test cases, so a forge on an executor that cannot load is refused with its reason before any test or review. Exported:QuickJSExecutor,QuickJSUnavailableError,QUICKJS_VERSION.Tests
tests/emergent/quickjs-executor.integration.spec.ts: the forged-tool corpus (61 fixtures, each to the expectation it meets in-process), the memory bound (at the cap, growth to the budget, the 16 MiB floor, a host value that does not fit), six ways to spin stopped at the deadline, the stack (in the guest, in a built-in), escape probes past the forge's validation (no host global, string code generation refused through nine routes, prototype changes kept in the guest, inputs copied, no state across calls), the bindings' bounds (bodies, calls in flight, the abort at the call's end, open hashes, large host values copied exactly) andIntlparity with the in-process context.tests/emergent/quickjs-unavailable.integration.spec.ts:quickjs_unavailablewithout the packages.src/cognition/emergent/__tests__/quickjs-engine.integration.test.ts: a tool forged throughforge_tooland called throughprocessToolCallruns onemergentConfig.executor, at forge time and at call time;executor_conflict; a forge on an executor that cannot run is refused before its tests and its review.🤖 Generated with Claude Code
Summary by Sourcery
Add an optional, per-call QuickJS WebAssembly executor for isolated and resource-bounded forged-code execution while retaining the in-process executor by default.
New Features:
Bug Fixes:
Enhancements:
Build:
CI:
Documentation:
Tests:
Chores: