Commit graph

34 commits

Author SHA1 Message Date
Sebastian Herrlinger
344e66c398 feat(codemode): bound incremental collector pauses with snapshot marking and chunked tracing
Replace the incremental-update barrier and its atomic finish with a
snapshot-at-the-beginning barrier: the first write to an object while
marking traces it before the write, cell writes shade the value they
overwrite, objects made while marking are black, and marking ends when
nothing is grey, with no rescan of the roots.

Count marking work in slots and trace long properties, elements and
entries a chunk at a time. Pay for no idle allocations at a cycle's
start, set the next threshold from the data live when marking ended,
and share the room between the arenas so the threshold holds.
2026-11-19 15:15:54 +01:00
Sebastian Herrlinger
34d2637981 feat(codemode): move long stretches of a run's compute to a worker thread, keeping host code on the executor 2026-11-19 03:32:56 +01:00
Sebastian Herrlinger
0e3de44007 refactor(codemode): size compile threads by a conservative nesting scan, not source size 2026-11-19 03:22:37 +01:00
Sebastian Herrlinger
c01c31121e feat(codemode): keep unpaired surrogates in namespace paths, error names, RegExp sources, bindings, metadata and durable data 2026-11-19 03:11:19 +01:00
Sebastian Herrlinger
7bddc79372 feat(codemode): keep unpaired surrogates in diagnostics and host failures 2026-11-19 03:02:33 +01:00
Sebastian Herrlinger
9257f8889f feat(codemode): keep unpaired surrogates in the result and the logs (Data, HostString) 2026-11-19 02:53:56 +01:00
Sebastian Herrlinger
6cfcfcf628 feat(codemode): cross strings to the host losslessly, unpaired surrogates included (HostString) 2026-11-19 02:41:41 +01:00
Sebastian Herrlinger
6d7e96a399 refactor(codemode): make the Rust crate the language layer only
The crate becomes the Rust implementation of the reference's language layer (`src/language/`): its public API is
the Rust form of `Language` (`Runtime::make` with `globals(run)`, modules, limits and translation; `HostFunction`
for `Host.fn` with sync, async and sync-thenable types, idempotent, constructible and takes-functions;
`DurableFunction`; `Namespace`; `Failure` for `Host.fail` and `Host.missing`; `Run` with its metadata; programs,
suspend and resume; snapshots). Code Mode (tools, schemas, the catalog, `search`, OpenAPI, hooks, max tool calls,
extensions) is removed, and the language files move from `src/language/` to `src/`.

Host calls follow the reference's language runtime: arguments cross under the runtime's translation (functions and
promises fail the call unless dropped or awaited), a function from a result crosses back only to a function that
takes functions, async and durable calls start at the next handover, sync work can block (`Returned::Block`) or
stay pending (`Returned::Pending`), and a suspend is refused while a call that can't be detached runs. Namespace
paths carry their root label, and their `keys` may fail. Snapshots save the run's metadata and its calls by global
path, and restart them by resolving that path again.

The replays define the generators' host globals (`conformance/reference.rs` shares `tools` with
`conformance/reference.ts`): the cases, `host.json`, `boundary.json` and `streaming.json`. `tests/host.rs` mirrors
the reference's `test/language.test.ts`; the API tests are ported, and the Code Mode tests are removed.
2026-11-19 01:54:11 +01:00
Sebastian Herrlinger
3cf39e761d test(codemode): record unsupported syntax at run time and acorn's parse errors from the reference
Programs in frames/core.ts record, with message and location, unsupported syntax that
runs or is never reached (classes, with, debugger, new.target, import.meta, super,
nested exports), the bindings it hides, using declarations, nested imports, names
located inside parentheses, and parse errors in acorn's words; a suspension reaches
unsupported syntax after resuming. New cases record values around it, and the api
test checks the suggestion, which the recordings do not capture. streaming.json is
to be regenerated at integration.
2026-11-19 00:28:20 +01:00
Sebastian Herrlinger
2a9405dedc refactor(codemode): keep the language layer from depending on Code Mode
The language layer reached tools in a handful of places: the run's host
state held the runtime's setup and tool context, the VM called tools and
search directly, a snapshot looked tools up to restore calls in flight,
and extension calls ran Code Mode's hooks. It now asks the layer embedding
it through one trait, Embedder: the globals it makes (search), calls into
its namespace and its blocking global, a namespace's keys, cancelling,
checking and restarting calls in flight, its natives, and the hooks around
host function calls. The runtime's Setup implements it, in
codemode/tool_host.rs, which takes the tool calls, search and the unknown
tool's suggestions from host.rs. A run's interruption, its record of calls
and its natives table are the language's.

Code Mode's modules are no longer named at the crate root, and
tests/language_boundary.rs fails when a language file names a path through
codemode or an item the root takes from it, as the reference's
test/language-boundary.test.ts does. The public API is unchanged.
2026-11-18 22:21:34 +01:00
Sebastian Herrlinger
e941709ea3 test(codemode): mirror the reference's host-call argument tests
tools.rs mirrors codemode.test.ts: a tool's arguments leave a function (a
toJSON included) out and await a promise, pending ones too, and a rejection
fails the call before the tool runs. extensions.rs mirrors extensions.test.ts
and language.test.ts: a host function from a result arrives back as itself
wherever it sits, a program function or a global's function is left out, a
promise that never settles waits until the timeout, and a result holding
functions is handed to a tool as its data. The host-args-promise case mirrors
promise.test.ts: a tool's promise inside another call's arguments is awaited.
2026-11-18 21:29:00 +01:00
Sebastian Herrlinger
5e7afe14fd fix(codemode): cross host-call arguments as the reference's toHost does
The reference now converts the arguments of every host call (tools, search,
extension functions) with toHost under Code Mode's translation: a function is
left out (an object's key is skipped, an array's item is null, an argument is
undefined, a Map's or Set's entry is undefined), a fulfilled promise is its
value, and a call whose arguments hold a promise that hasn't fulfilled waits for
each in turn and then calls again ($vmHostWait). A tool's or search's arguments
then become JSON through the tool runtime's toJson, so a toJSON of the
program's is no longer called, Date and URL cross as their ISO string and href
whatever their prototype's toJSON is, and a Uint8Array fails a known tool's
call once it starts.

Tool and search arguments now cross in one pass that fuses toHost and toJson
(cross::tool_args); extension arguments cross through to_host, which also hands
a function from a host result back as the host function itself. An async host
function's wait keeps its state in an array resumed through Reaction::Cross,
spending the job and the loop's back-edge, then nothing for a tool's namespace
call or fifty for a native; a synchronous one's wait is a native frame that
parks its caller's frames as an await does. An async extension function now
rejects its promise when its arguments can't cross, instead of throwing.

The walk that crossed tool and search arguments (its tool and search targets,
the parking search walk and answer_search) goes; the program's result still
crosses through the JSON walk. The streaming harness records a suspend that
came after the run ended with the run's outcome, as the reference does.
2026-11-18 21:29:00 +01:00
Sebastian Herrlinger
b0407dc45f test(codemode): resume a run with the extensions it picked
Mirrors the reference's suspend test: a run started with some of the
runtime's extensions is refused by a resume with all of them or with
fewer, and resumes with the same ones picked in another order and with a
repeat. Picking an extension the runtime wasn't made with panics with the
reference's message.
2026-11-18 21:10:49 +01:00
Sebastian Herrlinger
beda44806f test(codemode): record extension configuration from the reference
catalog.ts now records an extensions section: runtimes made from a fixed
library of extensions, runs that pick some of them, constructible globals
called with and without new, an extension's module names loaded through
import, require and import(), and imports that can't be resolved with
their reasons, each with its outcome and what the host functions
received. It mirrors the reference's new tests for per-run extensions,
constructible globals, module names and import errors. tests/extensions.rs
replays it with the same library built in Rust.
2026-11-18 21:10:49 +01:00
Sebastian Herrlinger
94cdd6f13d fix(codemode): say why an import can't be resolved
An import that resolves to nothing now says why, as the reference does: a
relative, absolute or file: specifier is a local file that can't be
imported, a node:, bun or Node core module name is one this runtime
doesn't provide, and anything else is a package that can't be installed.
The list of core modules is the reference's, fixed so every host gives
the same answer.
2026-11-18 21:10:49 +01:00
Sebastian Herrlinger
25d921550d test(codemode): record tool calls with invalid input from the reference
conformance/tools.ts records, next to valid, denied and failing calls, how a
call with invalid input settles against other jobs, its message, the
tool.before and tool.after hooks it runs (none), toolCalls (not listed) and
max_tool_calls (not counted). tests/tool_input.rs replays it; CI regenerates
it with the other recordings.
2026-11-18 18:56:12 +01:00
Sebastian Herrlinger
36a9080b98 fix(codemode): enter promise handlers at the reference's cost
The reference enters a promise reaction's handler, a finally cleanup, a
thenable job's then, an executor and a Promise.try callback without a call
(enterSettlingCall): a plain function's frame costs nothing beyond the job,
and a promise's resolve function nothing; anything else goes through
$vmSettleCall, so an async or generator function costs a call and a native
fifty. Rust charged every closure a call and every native nothing, so a busy
loop through rejected tool calls, or any then, refilled fuel at another step.
Promise.try spends its fifty before the callback runs, as the native returns
first.

A finally cleanup's outcome now passes through one more promise, a job
later, as the reference chains finallyCleaned and finallyOutcome.

Recorded: busy loops through invalid and failing tool calls, an unknown
tool, and each kind of handler, and the order of finally against other jobs.
2026-11-18 18:56:12 +01:00
Sebastian Herrlinger
6f7986e591 feat(codemode): await promises nested in what crosses to the host
A tool's or search's arguments and the program's result cross to the host
as the reference's boundary crosses them. Plain data takes the fast path,
now a port of the reference's: it throws at depth 32, and gives up on a
promise, a toJSON of the program's, or the 2,048th revisit of an object. The
rest crosses through the reference's internal walk, a heap object here
(Kind::Cross), which awaits each promise it meets, calls toJSON as bytecode
calls it, and spends what $vmCross and its visit generators spend.

A tool call returns its promise at once; its arguments' walk runs inside the
call until it awaits, and the call starts once they have crossed, or its
promise rejects with the walk's error. The result is crossed in the VM
before the run ends, a thenable result awaited first. search(...) from
bytecode parks the frames from the nearest async function up to the call
while its walk awaits, as the reference parks them, then answers or throws
into them; a search that cannot wait there, inside a built-in's callback or
a generator, fails instead. A pending walk or parked search is saved with
the run and continues on resume.

Crossing failures reject or throw the reference's error itself instead of
"Invalid input for tool ...". Recorded from the reference in
streaming.json: values, errors, ordering, fuel, and suspends while a walk
awaits.
2026-11-18 18:56:12 +01:00
kommander
54f0d1e41a feat(codemode): hold huge sparse arrays
The reference keeps an array's elements in a host JavaScript array, which
JavaScriptCore stores sparsely, so a[4294967294] = x works and makes the
length 4294967295. Here a write that far failed with 'Invalid array length'.

An array now turns sparse when a write lands past the longest dense array
(MAX_ARRAY_LEN): its items keep the dense prefix, the SPARSE object flag is
set, and its other elements and its length are its own properties, so
snapshots and reachability carry them unchanged. Element reads and writes,
in, hasOwnProperty, delete, keys, for-in, length (which makes it dense again
once short enough), push, pop, at, slice, includes, indexOf and lastIndexOf
work on it as in the reference, and the callback methods, reduce, flat and
flatMap visit only the elements it holds. Code that walks every element
makes the array dense first and fails with the reference's errors when it
is too long ('Invalid array length', 'Out of memory' for sort), where the
reference either fails or runs on for minutes. Logs show its first
elements. Arrays at most MAX_ARRAY_LEN long, every one the benchmarks make
among them, stay dense and take the same paths as before.

Setting length out of range and spreading too many values now say
'Invalid array length' without a period, as the reference does. Touches
object.rs (SPARSE), ops.rs (element and length paths, define, iteration),
convert.rs, host.rs, web.rs (structured clone), object.rs, buffer.rs.

The last nine test262 files leave rust-skipped.txt, which is now empty.
2026-11-18 18:56:11 +01:00
kommander
85ad9512cb fix(codemode): start streaming reads where the reference's fuel runs out
The reference hands queued host calls over whenever its interpreter returns
to its driver loop: at a job, after a synchronous extension call, when a throw
unwinds, and when its fuel runs out. The fuel is a fixed step count (10,000:
one per back-edge, function call and job, fifty per native call, including
the Symbol.iterator, next and return calls of iterators it does not walk
itself), not a time slice, so a busy loop sees locked and bodyUsed change at
a fixed iteration. The VM now counts the same fuel; its own clock check shares
the one hot step budget, so no step pays for two counters.

streaming.ts records busy loops of every shape, and a suspend while a fetch
result waits undelivered: the reference saves it and fails the resume on the
response's bodyUsed accessor, as Rust already did.
2026-11-18 18:56:11 +01:00
kommander
d0ea5e8e79 feat(codemode): keep lone surrogates in strings
Strings are UTF-8, which cannot hold a lone surrogate, so every one became
U+FFFD: '\ud800' === '\udc00' was true and s[0] + s.slice(1) lost the pair.
A string that is not well-formed UTF-16 now keeps its code units behind a
flag (Strings::wtf), and its text is a canonical carrier: UTF-8 in which
each lone surrogate is U+10FFFF followed by a private-use character that
encodes it, and a real U+10FFFF is doubled. Text equality stays string
equality, so comparisons, Map and Set keys and property keys need nothing
new, and every allocation decodes the carrier, so a high and a low
surrogate brought together by concatenation, repeat, padding or
replacement become their character.

Code that counts or cuts code units reads them through StrRef (length,
charCodeAt, slice, comparison, search, split); iteration, String.raw,
fromCharCode, JSON.parse escapes, literals and regex matches produce lone
surrogates; JSON.stringify and RegExp.escape write them as \u escapes;
isWellFormed, toWellFormed, encodeURI (URIError, with the reference's
message) and localeCompare see them. localeCompare weighs them as the
reference's ICU does, where ICU4X would weigh them as U+FFFD. URL,
URLSearchParams, TextEncoder and Buffer's UTF-8 take USVStrings, so a lone
surrogate becomes U+FFFD there, as in the reference; Buffer's latin1 and
utf16le take the code units.

At the host boundary the reference hands its strings over as they are; a
Rust host value is UTF-8, so results, tool arguments, logs and diagnostics
carry U+FFFD for a lone surrogate, the bytes the reference's own
TextEncoder writes for them. Text from the host has a real U+10FFFF
doubled on the way in. Snapshots save the carrier and restore it exactly.

Instructions (5 iterations) stay within 0.1% on all nine programs; JSON
round-trip 1922M -> 1923M, Map/Set 1021M -> 1017M, string building
717M -> 713M. Touches strings.rs, compiler.rs (literals), convert.rs
(JSON, host values), host.rs (host values), ops.rs (string iteration),
run.rs (diagnostics) and vm.rs (char_str).

Eight test262 files leave rust-skipped.txt.
2026-11-18 18:56:11 +01:00
kommander
03066b4ba3 fix(codemode): delete, arguments, await names and iterator errors match the reference
- delete: optional and parenthesized targets delete; an identifier fails when it runs; built-in constants and prototypes refuse; a function's name and length can be deleted; strings and nullish bases get the reference's errors; tool references refuse.
- arguments: delete leaves a hole, length is a hidden writable property, the binding can be reassigned, and iterating it reads its enumerable own values.
- await is a plain name at the top level unless an expression starts with it, and an escaped await is a label.
- A named function expression's own name is bound before its parameters, so their defaults see it read-only.
- Iterators that break the protocol get the reference's errors everywhere they are opened, stepped or closed, including async yield* over a non-iterable.
- Promise.all, allSettled, any and race reject when their input is not iterable or iterating it fails.
- An accessor in an object literal fails when the literal runs, and export is a parse error, as in the reference.

Drops 77 files from rust-skipped.txt.
2026-11-18 18:56:10 +01:00
kommander
a5b41a572c feat(codemode): stream HTTP responses to programs through extensions
HostValue::Response carries a StreamingResponse whose body the host streams
through the HttpBody trait (poll_chunk, cancel), with no HTTP crate. The
program gets what the reference's fromHost makes of Extension.StreamingResponse:
the response fields, a live bodyUsed, text/json/bytes/arrayBuffer, and a body
with a live locked, cancel, getReader and async iteration. Reading, locking,
cancelling and json() follow the reference's host runtime, its error messages
included. Reads and cancels take effect where the reference starts queued
calls: at the next job or after a synchronous extension call.

Live accessors are a small Kind::Live hook: own, read-only, non-enumerable
and deletable, and otherwise an ordinary object. A snapshot keeps them only
while the run can reach them, and then the resume fails as in the reference;
reach.rs marks what is reachable. A lost host function now throws at the call
with its location, naming an unnamed one (anonymous).

conformance/streaming.ts records the reference with a fake streaming fetch,
since it has no tests of its own here; tests/streaming.rs replays it.
2026-11-18 18:56:10 +01:00
kommander
b8f7c5a117 feat(codemode): suspend and resume runs from snapshots
Program::suspender stops a run at a job boundary or loop back-edge and saves its state; Runtime::resume and resume_bytes continue it in a fresh runtime after checking the build, host globals and source. Idempotent tools rerun and durable tools wait on their saved data on resume; extensions may encode and decode the values they return. PSYCHOSCRIPT_ROUNDTRIP=1 saves and restores at every host stop and every 64 back-edges.
2026-11-18 18:56:10 +01:00
kommander
5c40e4ab45 feat(codemode): carry dates, URLs, headers, bytes and RegExps across the extension boundary
HostValue gains Date, RegExp, Url, SearchParams, Headers, Bytes and Buffer,
and both directions convert them as the reference's toHost and fromHost do:
program values arrive as copies of the host types, and host values become
the stdlib's Date, RegExp, URL, URLSearchParams, Headers, Uint8Array and
Buffer. Every other object crosses as a copy of its own fields, and only
interpreter machinery (functions, promises, generators, iterators) is
refused, with the reference's descriptions.

catalog.ts records host samples and programs through a probe extension; the
Rust test replays them from those descriptions.
2026-11-18 18:56:10 +01:00
kommander
014d0d9cee fix(codemode): match the reference on 3.0 keywords, moved references and key order
- An OpenAPI 3.0 schema with a keyword only JSON Schema 2020-12 defines
  (const, $id, examples, if, ...) fails openapi::from_spec with the error
  the reference throws; from_spec now returns Result<Generated, SpecError>.
- The 3.0 converter records where each schema lands, so references into a
  nullable allOf that becomes anyOf follow it, as Effect's converter does.
- Specs and tool schemas take JavaScript's key order, integer-like keys
  first, so signatures and generated schemas render in the reference's
  order.

catalog.ts covers each with documents written as JSON text, and the OpenAPI
test now compares generated schemas key order included.
2026-11-18 18:56:09 +01:00
kommander
efc462d007 test(codemode): cover the warnings output budget 2026-11-18 18:56:09 +01:00
kommander
87ea80e59a feat(codemode): report unhandled rejections as warnings
A rejected promise nothing handles by the end of a successful run becomes a
warning in Outcome.warnings, in promise creation order, as in the reference,
after completed host calls settle. Warnings get their own output budget and
a Truncated marker. The VM side is two hooks in promise.rs: a rejection with
no reactions, and a reaction attached to a rejected promise.
2026-11-18 18:56:09 +01:00
kommander
01a9a97512 fix(codemode): word the timeout diagnostic as the reference does 2026-11-18 18:56:09 +01:00
kommander
005e4807b4 feat(codemode): let a tool interrupt its whole run
A tool returning ToolError::interrupt() stops the run, as a tool interrupting
its fiber does in the reference: Program::run, run_async and execute_async
end with Interrupted instead of an outcome, calls still running are
interrupted with it, and tool.after sees the call as interrupted. The
blocking execute keeps its signature and reports an ExecutionFailure.
2026-11-18 18:56:09 +01:00
kommander
5880f791a6 feat(codemode): add OpenAPI tools to the Rust port
openapi::from_spec ports OpenAPI.fromSpec: one tool per representable
operation with dotted operationIds as namespaces, the reference's skip
reasons, readOnly/writeOnly projection solved over reference cycles, OpenAPI
3.0 and 3.1 schema normalization, host-side auth resolution, and request
building over an HttpClient trait the host implements.

conformance/catalog.ts now also runs the documents of the reference's
openapi.test.ts and its fixtures, recording signatures, schemas, skipped
operations, and each call's requests, credentials and result; the Rust test
replays them with a fake client.
2026-11-18 18:56:09 +01:00
kommander
b7ebfb4b48 test(codemode): cover extensions and tool calls against the reference
Adds host- conformance cases for invalid input, unknown tools, namespaces,
search browsing, chaining, validation and counting, and missing modules, with
expectations generated from the reference, and Rust tests mirroring the
reference's extension tests. HostValue::to_json keeps integral numbers as
integers.
2026-11-18 18:54:15 +01:00
kommander
e336bbafd1 feat(codemode): add schema tools, search, hooks, async host calls and extensions to the Rust port
Tools take validating or render-only JSON Schemas (the Rust form of Effect
Schemas and the reference's JsonSchema), render byte-identical TypeScript
signatures, and report InvalidToolInput and InvalidToolOutput. Namespaces,
freeform tools, the catalog, toolExpression, searchSignature and the BM25
search built-in follow tool-runtime.ts; conformance/catalog.ts regenerates
the expectations from the reference.

Tools and extension globals may return futures. execute_async runs on any
executor; execute drives it with a small built-in block_on, and a shared
timer thread enforces timeouts while host work is pending. Dropping a run
cancels its calls, which after hooks see as interrupted.

Extensions cross values as copies both ways, including functions in results,
errors, maps and sets, and programs load them with import, require and
import() by Node module name. Runtime::program adds the reference's
program API with run ids.
2026-11-18 18:54:08 +01:00
Sebastian
f71cdee242 feat(codemode): add embeddable Rust port 2026-11-18 18:53:56 +01:00