@ai-ecoverse/slicc-kernel
v1.196.28
Published
SLICC's wasm-realm kernel: run Emscripten programs in the browser against OPFS, with fork, spawn, pipes and waitpid
Readme
slicc-kernel
SLICC's wasm-realm kernel as a standalone package. It runs Emscripten programs built for SLICC in the browser, directly against the Origin Private File System, with fork, spawn, pipes, waitpid, signals and job control. The first target is GNU bash from @ai-ecoverse/wasm-bash; anything else that follows the SLICC toolchain conventions (for example @ai-ecoverse/wasm-coreutils) runs too.
import { createKernel } from './node_modules/@ai-ecoverse/slicc-kernel/dist/index.js';
const kernel = await createKernel({ root: await navigator.storage.getDirectory() });
const { status, stdout, stderr } = await kernel.run(['bash', '-c', 'echo hi > hello.txt; cat hello.txt'], {
cwd: '/os',
});Requirements
- The page must be cross-origin isolated: serve it with
Cross-Origin-Opener-Policy: same-originandCross-Origin-Embedder-Policy: require-corp(orcredentialless). Processes block onAtomics.waitover aSharedArrayBuffer, which only exists in isolated contexts.createKernelthrows ifcrossOriginIsolatedis false. - The kernel lives in a dedicated worker owned by the page. A
SharedWorkeris never cross-origin isolated in Chromium (and has noWorkerconstructor), so it cannot host the kernel.createKernelstartsdist/kernel-worker.js; that worker owns OPFS and starts one nested dedicated worker (dist/process-worker.js) per process. The kernel worker readsprocess-worker.jsonce when it starts and runs every process and thread from that copy (ablob:URL), so updating the package in place while a kernel runs does not mix versions: the next page load switches both. - The page's CSP must allow
eval, since each process evaluates its program's Emscripten glue withnew Function, andblob:workers (worker-src 'self' blob:, or thescript-srcit falls back to), since processes run from the kernel's pinned copy ofprocess-worker.js.
TypeScript declarations ship in dist/types/, and each entry (., ./node, ./driver, ./testing, ./meta) names its own in exports under types, so a TypeScript consumer gets the API's types with moduleResolution NodeNext or Bundler. The ./node entry's types need @types/node. dist/ is plain ESM with no bare imports, and the workers are referenced with new URL('./….js', import.meta.url), so the files work when served as-is (for example from OPFS through a service worker). Whatever serves them must send the COOP/COEP headers on the page and a compatible Cross-Origin-Resource-Policy on the scripts.
API
createKernel(options?) → Promise<Kernel>
| option | default | |
| --- | --- | --- |
| root | navigator.storage.getDirectory() | the FileSystemDirectoryHandle that becomes /. WebKit cannot clone a handle, so there it must lie in OPFS, and the kernel worker reopens it by path |
| modules | '/node_modules' | where installed packages are scanned for commands |
| commands | none | { append: ['/opt/user/node_modules'] }: more node_modules directories scanned for commands after all the others, so they never shadow one (see Commands) |
| env | {} | environment added to every run |
| metadata | 'slicc-kernel' for the origin's OPFS root, 'slicc-kernel:<root id>' for any other root | the IndexedDB database for POSIX metadata (see Metadata); false keeps it in memory for the kernel's lifetime. Kernels share metadata, and count each other as peers on one root, exactly when they use the same database. So the default gives every root its own: the origin's own root (navigator.storage.getDirectory()) keeps slicc-kernel, and any other directory passed as root gets an id, which the kernel keeps with the directory's handle in the IndexedDB database slicc-kernel-roots (#1120). Until #1120 every root used slicc-kernel, so records of two roots with a file at the same path were mixed there, and the kernel can't split them again. So that an upgrade loses nothing, a root that isn't empty when it's first registered starts with a copy of the slicc-kernel records, if that database exists, and from then on its records are its own: they never mix with another root's. The copy is of the whole slicc-kernel store, once per root, so on a long-used origin the first boot of such a root takes longer; it logs one console line naming the new database and how many records it copied (never paths or contents), and later boots log nothing. An empty root starts with no records. A moved root, or one whose registry entry was cleared, is registered again: its old records don't follow it. Registering is done under the Web Lock slicc-kernel-roots, so tabs booting one new root at once agree on its id. A name given here is used as is |
| ca | '<metadata>-ca', or 'slicc-kernel-ca' | the IndexedDB database for the proxy's CA (see Network); false keeps it in memory |
| media | '<metadata>:media' | the IndexedDB database for the folder handles of fsa drives (see Removable media); false keeps them in memory, as metadata: false does |
| worker | new URL('./kernel-worker.js', import.meta.url) | the kernel worker script |
| network | none | { transport, uplink, doh }: how programs reach the outside world (see Network, Uplink and DNS) |
| requestDirectory | none | () => Promise<FileSystemDirectoryHandle>, typically showDirectoryPicker: how an fsa mount gets its folder (see Removable media) |
| hostfs | none | (source, { readonly }) => Promise<{ url, token, capabilities? } \| { port, token?, capabilities? }>: a grant for a hostfs mount from a host that serves the folder over HTTP, or a MessagePort the page serves the folder on (see Host folders) |
| onMountPending | none | ({ target, source, insert }) => void: an fsa mount needs a folder; call insert() from a user gesture |
| processMounts | true | whether programs may call mount(2) and umount2(2): false, or (req) => boolean \| Promise<boolean> to decide each call (see Mounting from a program) |
| hostname | 'slicc' | the kernel's node name (see Node name) |
| timeZone | the browser's (Intl.DateTimeFormat().resolvedOptions().timeZone) | the system time zone, an IANA name such as 'Europe/Berlin': TZ in every environment, and the zone cron reads schedules in (see Time zone). A name Intl doesn't know rejects. createNodeKernel takes it too |
| users | 'enforce' | 'off', 'report' or 'enforce': whether files have owners and their modes are checked (see File owners and Permissions), and whether sudo elevates (see Sudo). 'off' behaves exactly as kernels before owners did; any other value rejects. createNodeKernel takes it too, with the same default. Kernels up to 1.73 defaulted to 'off' |
| onDenial | none | ({ pid, uid, op, path, errno, tag? }) => void: called for every permission check that fails, under 'report' and 'enforce' (see Permissions). createNodeKernel takes it too |
| sealed | none | (req, { signal }) => Promise<object>, or { request, fetch? } with that function as request: request answers requests written to /dev/sealed, and fetch fills requests that carry a sealed placeholder (see The fetch hook under /dev/sealed). createNodeKernel takes it too. An exported SEALED_FETCH_VERSION, the number 1, says that this kernel takes the object |
| clipboard | none | { read(stamp) => Promise<string>, write(text, stamp) => Promise<void> }: the clipboard behind /dev/clipboard. createNodeKernel takes it too |
| requests | none | { kinds, handle(request) }: the page's answers to /dev/embedder for the processes it starts. createNodeKernel takes it too |
| devices | none | { open(request) }: the page's answers for the serial device nodes it adds with kernel.devices (see Embedder devices). createNodeKernel takes it too |
| approve | none | (req, { signal }) => 'once' \| 'always' \| 'deny' (or a promise of one), or { answer: 'once' \| 'always', timestamp: true } when a person approved: decides a sudo request that needs approval (see Sudo and Sudo timestamps); without it, such a request is denied. createNodeKernel takes it too |
| cdp | none | ({ runtime, stamp }) => Promise<CdpConnection>: a browser-level DevTools connection for programs that drive a browser (see Browser automation) |
| facades | none | { link: { port, hook? } }: kernel-only loopback ports whose connections a hook on the page serves, with the connecting program's identity (see Page facades) |
| protect | none | { paths, writers? }: directories no process may change, root included, in every users mode, except processes with one of the writers tags (see Protected paths). createNodeKernel takes it too |
kernel.run(argv, options?) → Promise<{ status, signal, stdout, stderr }>
Runs argv[0] with argv as its arguments and resolves when it exits. stdout and stderr are decoded as UTF-8; status is the exit status, masked to 8 bits as on Linux (a program's exit(-1) is 255, exit(263) is 7, for kernel.run, openTerminal's exited and spawn alike), 128 + n for a process killed by signal n, and 127 when argv[0] cannot be found. signal is there only when a signal ended the process, named as 'SIGKILL', so a kill -9 (status: 137, signal: 'SIGKILL') can be told from an exit 137 (status: 137, no signal).
| option | |
| --- | --- |
| cwd | working directory, default /; created in OPFS if missing. Under users: 'enforce', a cwd the user can't search rejects with code: 'EACCES' (cannot change to <cwd>: Permission denied) and starts nothing, as a chdir there fails on Linux; openTerminal does the same. A program's spawn with its own cwd (ctx.spawn, ctx.sync.run, a WASIX posix_spawn chdir action) is checked the same way and fails with EACCES, while a child that inherits its parent's cwd keeps it unchecked, as on Linux |
| cwdMissing | 'create' (the default) or 'error': what happens when cwd doesn't exist. 'create' creates it, with its parents, as described for cwd. 'error' rejects with code: 'ENOENT' (cannot change to <cwd>: No such file or directory) and starts nothing, as a chdir there fails on Linux. A caller that keeps directories in a list to run commands in, and so may name one that was removed since, should pass 'error': with 'create', its next command brings the removed directory back, empty (#1808). Any other value rejects with a TypeError; openTerminal takes it too |
| user | the user to run as, by name or uid (see Users); default root. An unknown user rejects with code: 'ENOENT' |
| tag | a string the kernel keeps with the process and every process it starts (fork, spawn and exec), and hands to approve with a sudo request, so the embedder knows which agent asks; nothing a program does changes it. Anything but a string rejects with a TypeError |
| env | extra environment, over the user's defaults: HOME, USER, LOGNAME, PNPM_HOME and PATH=$PNPM_HOME/bin:/usr/local/bin:/usr/bin:/bin (see Users), TZ=<system time zone> (see Time zone), and PWD=<cwd> |
| stdin | a string or Uint8Array; without it stdin is /dev/null |
| onStdout, onStderr | called with each chunk of text as it is written |
kernel.openTerminal(argv, options?) → Promise<Terminal>
Starts argv as the session leader on a new terminal and resolves once it is running, or rejects if argv[0] cannot be found. Its stdin, stdout and stderr are the terminal, which has a line discipline with echo, canonical mode and ISIG, and supports job control, so kernel.openTerminal(['bash', '-i']) gives an interactive shell. The API was designed with slicc-spectrum, a terminal web component, and these names are kept stable.
| option | |
| --- | --- |
| cwd, cwdMissing, user, tag, env | as for run; TERM=xterm-256color and COLORTERM=truecolor are added |
| cols, rows | initial size, default 80 × 24, so $COLUMNS and $LINES are right before the first prompt |
| onData | called with each chunk of output as raw bytes (escape sequences included) |
| Terminal | |
| --- | --- |
| pid | the session leader's pid |
| onData | the output listener; output that arrives while it is null is kept and delivered when one is set |
| write(data) | types a string or bytes into the terminal; with ISIG on, ^C, ^Z and ^\ signal the foreground process group. A key typed while a child of that group is still setting up is held until the child has finished, then sent to the group in the foreground at that point; this applies only to children of a job-control shell (a process that ignores SIGTTOU, as interactive shells do) and to the programs those children exec, so a program that starts a child without job control (Python's subprocess) gets the key at once. Setting up means the child's calls before its first other one: setpgid, tcsetpgrp, signal masks, and starting the program it execs (which then sets itself up too). The hold ends 2 s after the child's first call at the latest. A key typed while the foreground group is busy, not reading the terminal (a shell between reading a command line and starting it), goes to that group and also to the job the group starts next, once that job has taken the terminal; the second copy is dropped when the group reads the terminal again. So ^C or ^Z right after a command line reaches the new job, as it does on Linux, where starting a job takes microseconds rather than a worker start. For the same reason, a child that is still setting up cannot give the terminal to its own group once its parent has already given the terminal to that group and taken it back: on Linux the child's tcsetpgrp would have landed first, so the parent's later choice stands. Otherwise tcsetpgrp behaves as before. A ^C, ^\ or ^Z that a program with a handler for it takes between two system calls, rather than while waiting, ends the program's next wait in the kernel that would block (reading nothing yet, select or poll with a timeout, a blocking write, waitpid) with EINTR, once, as if the key had come during that wait. A zero-timeout select or poll does not use it up. Without this, an interactive shell whose ^C landed while it was taking in the key before it would wait for the next key before showing a new prompt: readline acts on ^C only when a read ends with EINTR. On Linux that window is the microseconds between two reads; here it is a few kernel calls per key. A signal sent with kill does not do this. |
| resize(cols, rows) | sets the window size (TIOCGWINSZ) and sends SIGWINCH to the foreground process group. As on Linux, setting the size the terminal already has, here or with a program's TIOCSWINSZ, sends no SIGWINCH. A program's TIOCSWINSZ that writes back the size it last read with TIOCGWINSZ is left out, so it can't undo a resize that came in between. Readline does that write-back every time it starts reading a line; on Linux the gap between the two calls is microseconds, here it's two kernel calls, wide enough for a resize to land in it and the shell to keep the old size (#740). Limit: Linux has the same race and applies the stale write-back, only in a far shorter gap; leaving it out is a deliberate difference, so a program that really means to set the size it just read, after a resize it hasn't seen, keeps the newer size. |
| signal(name) | sends a signal ('SIGINT', 'SIGTSTP', 'SIGQUIT', 'SIGHUP', …) to the foreground process group, regardless of termios |
| exited | resolves with the session leader's exit status (128 + n if killed by signal n) |
| ended | resolves with { status, signal } at the same time: status as exited, and signal named ('SIGKILL') only when a signal ended it |
| close() | hangs up: SIGHUP to the foreground process group, and reads from the terminal return end-of-file |
kernel.terminate()
Stops the kernel worker and every process. Pending and later calls reject.
kernel.connect({ user, tag, requests }?) → Promise<MessagePort>
Makes a port for another client of the same kernel. Hand it to a dedicated worker, or through a SharedWorker to another tab: it can be transferred any number of times. All clients share one process table, so a terminal on the page can ps and kill what a worker started.
requests binds the port's /dev/embedder requests when the port is made: a hook ({ kinds, handle }, as createKernel's) answers for every process the port's client starts, in the embedder's own realm, so a worker client (an agent) never answers or registers requests itself. 'attach' lets the client that attaches to the port bring its own hook (attachKernel(port, { requests }), protocol 1.13); without it, an attach with requests fails with EPERM. A port with neither answers nothing: its processes' requests are ENOTSUP.
devices binds a devices hook the same way (protocol 1.18): a hook ({ open }) answers the opens of the nodes the page adds for the port (kernel.devices.add({ client: port, … })), in the embedder's own realm, and 'attach' lets the client that attaches to the port bring its own (attachKernel(port, { devices })); without it, an attach with devices fails with EPERM, and a node added for a port with no hook is ENOTSUP.
user (a name or uid) binds the client to that user; without it the client is root. The binding is a capability: the client's spawn, run and openTerminal run as that user, its ps lists only that user's processes, and its kill follows POSIX permission. A bound client can't run anything as another user (code: 'EPERM'). A root client may pass user to spawn, run or openTerminal to run one command as any user. An unknown user rejects with code: 'ENOENT'. tag is the tag (see kernel.run) of every process the client starts; its own spawn, run and openTerminal cannot name another. They may add one with their own tag option (protocol 1.12; an older kernel answers ENOSYS): the process then has both tags, the connection's first, and so does everything it starts. The option may also be a list of at most 8 tags, added in order (protocol 1.15; against an older kernel the client rejects with code: 'ENOSYS' before sending anything), so a caller can mark one call's tree with a tag of its own for trace beside a tag that means something else. A per-spawn tag only adds; no client, program or child can remove or replace a tag (#1380).
kernel.sudoRun(request, { stdout, stderr, tag }?) → Promise<{ pid, pgid, ended }>
Runs a sudo request that nobody answered in time (or that was denied or withdrawn) as if the answer were 'once', after checking that what was asked still holds, detached from any terminal or process: see Running a request later. An attached root client has the same call, client.sudoRun (protocol 1.16).
kernel.users
The user database, /etc/passwd and /etc/group (see Users):
| | |
| --- | --- |
| mode | the users option the kernel was created with |
| add({ name, home?, groups?, umask?, homeGroup?, homeMode? }) | adds a user and resolves with { name, uid, gid, home, shell, groups, umask? }. It's idempotent: an existing name resolves with its entry, keeps its ids and home, joins the groups in groups it isn't in yet (it never leaves one), remembers umask, creates a missing pnpm home or config.yaml (an existing pnpm home keeps its mode with users: 'off'), and, with owners on, gives the home to the user again. The new user gets the lowest free id from 1000 up, a private group of the same id and name, membership of users and of each group in groups (such as sudo), home (default /home/<name>, created; stored normalised, so /srv/../srv/cone/ becomes /srv/cone), its pnpm home ~/.local/share/pnpm (0700, 0750 for a scoop- user) and ~/.config/pnpm/config.yaml with minimumReleaseAge: 1440 (pnpm skips releases less than a day old), each only if missing (with owners on, the directories it makes on the way, ~/.config and ~/.local included, get 0777 less the user's umask, the file 0666 less it, and in a home with homeGroup they belong to that group and have the setgid bit, as new directories in a setgid directory do), which an add of an existing user also does, and /bin/bash. umask is the umask its processes start with; the kernel keeps it in memory, so pass it again after a reload. With owners on, every add, of a new or an existing user, also gives a home under /home/<dir> to the user and sets its pnpm home to 0700 (0750 for a scoop- user) again (see File owners). homeGroup names the group the home belongs to instead of the user's own, without making the user a member (groups does that), and its mode is then 2750. homeMode sets the home's mode instead (setgid included, so 0o2750 makes new files in it take the home's group); like the owner, it is set again by every add with owners on, on the home itself only. A name must match [a-z_][a-z0-9_.-]*; a group that doesn't exist, in groups or homeGroup, rejects with ENOENT |
| remove(name, { keepHome }?) | removes the user, its private group and its group memberships, and deletes its home unless keepHome is set. A home outside /home/<dir> is never deleted. Resolves false for an unknown name; system accounts (ids below 1000 or above 60000) reject with EPERM |
| list() | every user, as add returns them |
kernel.groups
The groups of /etc/group, on the page and the Node entry (not on attached clients):
| | |
| --- | --- |
| list() | every group as { name, gid, members }, members being the users listed in it (a user's own group lists nobody) |
| add(name, { gid }) | adds a system group with no members to /etc/group and resolves with it. A name that exists resolves with that group unchanged, whatever its gid, so an embedder calls it at every boot to bring an older /etc/group up to date: kernel.groups.add('dialout', { gid: 20 }). A gid another group has rejects with EEXIST; a name that doesn't match [a-z_][a-z0-9_.-]* or a gid that isn't an integer from 0 to 4294967294 with EINVAL |
| addMember(group, user) | adds user to group's members and resolves with the group; a member already in it changes nothing |
| removeMember(group, user) | removes user from group's members, the same way |
For addMember and removeMember, an unknown group or user rejects with ENOENT, and a user's own (primary) group with EINVAL. Every user has an own group with its name and its uid as gid, which is how a cone shares with its scoops: the scoops join the cone's group. As on Linux, a change counts from the user's next process (and the next client connected for it): processes already running keep the groups they started with, and so does a client already connected. The embedder's recipe, which bios and slicc-agent share, run at every boot:
await kernel.users.add({ name: 'cone', groups: ['sudo'], homeMode: 0o710, umask: 0o077 });
await kernel.users.add({ name: 'scoop-site', groups: ['cone'], homeGroup: 'cone', homeMode: 0o2750, umask: 0o027 });The cone's home lets its group in only to pass through (0710), and the cone opens what it shares with chmod g+r. A scoop's home belongs to the cone's group, so the cone reads it, and new files there take that group. Change /etc/passwd and /etc/group through kernel.users and kernel.groups, which keep the two consistent and serialize their writes.
kernel.devices
Serial device nodes the embedder backs, on the page and the Node entry (not on attached clients); see Embedder devices:
| | |
| --- | --- |
| add({ path, owner?, group?, mode?, links?, sys?, client? }) | adds a character device directly under /dev and resolves with { remove() }. path is ttyUSB<n> or ttyACM<n> (with or without /dev/, n from 0 to 255); owner and group are names or ids (default 0), mode the permission bits (default 0o600), links names of symlinks the kernel makes to the node in /dev/serial/by-id/ (a bare name or the full path), sys the USB device behind the node, { idVendor?, idProduct?, manufacturer?, product?, serial? }, which /sys shows (the ids as numbers from 0 to 0xffff or as one to four hex digits, with or without 0x, default 0000; the strings printable, at most 255 characters), and client the port from kernel.connect({ devices }) whose hook answers the node's opens (default: the page's own devices hook). A name, a link, a sys or a client that doesn't fit, or an unknown owner or group, rejects with EINVAL; a name or a link that exists with EEXIST; a client without a devices hook with ENOTSUP |
| remove() | deletes the node and its links. Descriptors still open on it fail every call with EIO from then on, and poll reports POLLHUP and POLLERR, as on Linux when a USB serial adapter is unplugged. A second remove() does nothing |
When the client whose hook answers a node goes away (its port closes), its nodes are removed the same way.
const kernel = await createKernel({ devices: { open: ({ path, flags, stamp, signal }) => port(path) } });
await kernel.groups.add('dialout', { gid: 20 });
const node = await kernel.devices.add({
path: 'ttyUSB0', owner: 0, group: 'dialout', mode: 0o640, links: ['usb-0403_6001-if00'],
sys: { idVendor: 0x0403, idProduct: 0x6001, manufacturer: 'FTDI', product: 'FT232R USB UART', serial: 'A50285BI' },
});kernel.chmod(path, mode) → Promise<void>
Sets a file's permission bits (0 to 0o7777, EINVAL otherwise) as root, through the mounts, as the processes see them, for a file the page wrote some other way. For files the page writes straight to OPFS before any kernel runs, see writeMetadata under Metadata.
kernel.integrity.revoke(path?) → Promise<void>
Drops what integrity verified for path (absolute), or for everything under it, or for every path, so the next start asks lookup again. Call it when lookup's answers change; see Revoking under Protected paths.
kernel.setRoutes({ prefixes, exit }) → Promise<void>
Replaces the uplink's route table: prefixes are addresses or CIDR prefixes (100.64.0.0/10, fd7a:115c:a1e0::/48), and exit: true routes every address, as an exit node does. A prefix that does not parse rejects the whole table and keeps the old one.
kernel.updateTransportTraits() → Promise<boolean>
Re-reads the network transport's traits (createKernel({ network: { transport } })), which the kernel otherwise reads once, at boot, and whose later changes (a link, a tray or Tailscale coming up, traits.exit) it can't see. Make traits a getter on the transport, and call this when the value may have changed. If the value differs (compared as JSON), the kernel takes it for its programs and its proxy, and sends it to every attached client, which updates client.transport.traits and calls its onTraits listeners. A client that attaches later gets the new value in its handshake. It resolves true when something changed and was sent, and false otherwise, with nothing sent. Without a transport it resolves false. The Node entry has the same call. A transport's redirectHops and manualRedirects are still decided at boot. Clients older than protocol 1.10 ignore the message.
kernel.dial({ port, host? }) and kernel.loopbackFetch(input, { port, host?, signal? })
Reach a server a program runs on the kernel's loopback (a dev server, python -m http.server) from the page, a service worker or an attached client, which have both calls too (protocol 1.4).
dialconnects to127.0.0.1:<port>inside the kernel (hostmay also belocalhostor::1) and resolves with{ readable, writable, close() }: aReadableStreamand aWritableStreamof bytes.writable.close()half-closes the connection, asshutdown(SHUT_WR)does, andclose()closes it. Each connection has aMessagePortof its own, and an attached client's connections close when it detaches; the other end then readsECONNRESET.loopbackFetchsends an HTTP/1.1 request overdialand resolves with aResponseas soon as the headers arrive. The body streams (chunked, counted, or until the connection closes), so server-sent events and long polls work; cancelling the body or abortingsignalcloses the connection. The request is routed byport, not by the URL, whose host is sent asHost; a request body is sent withContent-Length, and every request uses a connection of its own (Connection: close).- Errors reject with an
Errorwhosecodeis the errno:ECONNREFUSEDwhen nothing listens on the port or the port is kernel-only (9222, the CDP facade),ENETUNREACHfor a host that is not the loopback,EINVALfor a port outside 1–65535. - Names: a page reaches the kernel's loopback as
<port>.kernel.localhost, which is the loopback and a secure context, so a request no service worker routes lands on port 80 of the real machine instead of a real server on that port; the service worker routes the name toloopbackFetchwith that port. Programs find the name inSLICC_PAGE_LOOPBACK(kernel.localhost) andSLICC_PAGE_LOOPBACK_URL(http://{port}.kernel.localhost), to print or inject the right URL. - No per-user isolation: as on Linux, any user's process can connect to any listener on
127.0.0.1, and the page reaches every one as<port>.kernel.localhost, so the loopback is no privilege boundary; a service that needs one must authenticate its clients.
kernel.attest(path) and kernel.watch(paths, onChange)
Neither is on an attached client (attachKernel, connect()), so no process or client can ask for them. watch is page-only; attest is on createNodeKernel's kernel too. They are for a page that has to trust a root-owned file, such as a policy file that only sudo may change.
attest(path)resolves with exactly{ path, bytes, uid, gid, mode, ino, mtimeMs, sha256, users, onRootFs, parents }.pathis the canonical absolute path.bytesis aUint8Arrayof its own, holding the file's contents.sha256is the lowercase hex digest of exactly those bytes.modeincludes the type bits.usersis the kernel'susersmode.onRootFsis alwaystrue.parentslists{ path, uid, gid, mode }for every directory from/down to the file's own.- The kernel answers it itself, over the root file system without permission checks, and lstats every component. It reads the file between two lstats and accepts the read only when the inode, the modification time and the size are unchanged and the bytes match the size. Otherwise it reads once more, then fails with
EAGAIN. - It refuses with an
Errorwhosecodeis:EACCESfor a symlink at the path or in any parent, for a path at or under a mount (any mount, one at/included; a mount that failed and isn't installed doesn't count), and for a parent that isn't owned by uid 0 or that group or others may write;EISDIRfor a directory;EINVALfor another kind of file or a path that isn't absolute;ENOTDIRfor a parent that isn't a directory;ENOENTfor a missing one; andEFBIGfor a file over 1 MiB. - Under
users: 'off'there are no owners, so the parent check is skipped and the answer shows what the file system shows (uid and gid 1000, as processes see them). A consumer should accept onlyusers: 'enforce'. attest(path, { absent: 'allow' })answers the same for a file that exists. When the path itself is missing, and every directory from/to its parent exists and passes the checks above (no symlink, owned by uid 0 and not writable by group or others unlessusersis'off', not at or under a mount), it resolves with exactly{ path, absent: true, users, onRootFs: true, parents }: a trusted statement that the file isn't there, with no ids, hash or bytes. A missing parent, a symlink, a directory, another kind of file, an untrusted parent, a mount or a file that's too big rejects as without the option, and any other value ofabsentisEINVAL.
watch(paths, onChange)resolves with an unsubscribe function.onChange(path)is called once per burst of changes, 50 ms after the last one, for each watched file that changed.- A change is a write, a truncate, a rename, a removal, or a change of mode, owner or times of the file or of any directory above it. A change to a parent directory's own metadata counts too, and creating or removing a sibling changes it when the change comes from another kernel.
- It sees changes made through any slicc kernel on the origin, in this tab or another one: the kernels tell each other which files are watched and report writes to those.
watchresolves once every other live kernel on the origin has the watch (a kernel that doesn't answer within 500 ms is not waited for), so a write made after it resolves is reported. A kernel that ends with watches still on is forgotten (by its Web Lock) at the next reported write or unanswered announcement. This needs the shared metadata (the default): withmetadata: falsea kernel sees only its own changes. It doesn't see writes made with the OPFS API outside a kernel, such as a page script or an installer writing the root directly. After such a write the page should attest again itself (and may also attest on tab focus, as a safety net). - The cost when no kernel on the origin watches anything is one empty-set check per write.
- A kernel that starts late: a kernel learns the other kernels' watched files only when they answer its greeting, one message round trip (usually milliseconds) after it starts. A write it makes before then isn't reported. A consumer that must not miss a change checks again (attests) after its first report.
- Trust: the kernels coordinate over a
BroadcastChannel, which every same-origin context can post to. A script on the origin can fake an acknowledgement, sowatchresolves before another kernel really has it, clear a kernel's watched files, or report changes that didn't happen. That is the same boundary as a direct OPFS write, whichwatchdoesn't see either. Treatwatchas an invalidation signal only, never as proof: attest again before each use that matters, as the vault and bios do.
attachKernel(port, options?) → Promise<KernelClient>
Attaches to a kernel over a port from kernel.connect(), in any realm: a worker, another tab, or Node. options.timeoutMs (10 s by default) bounds the handshake: a port with no kernel behind it rejects with KernelGoneError. options.requests ({ kinds, handle }) answers the /dev/embedder requests of the client's processes, when the port was made with connect({ requests: 'attach' }). options.devices ({ open }) answers the opens of the embedder devices the page added for this client (kernel.devices.add({ client: port })), when the port was made with connect({ devices: 'attach' }) (protocol 1.18; an older kernel ignores it).
| Client | |
|---|---|
| spawn(argv, { cwd, cwdMissing, user, env, stdin, pgid, onStdout, onStderr }) | runs over pipes and resolves with { pid, pgid, exited, ended, signal(name) } once the process has started; ended resolves with { status, signal }, signal named only when a signal ended the process, as for kernel.run (an older kernel never names one); output arrives in chunks, as bytes, and the kernel keeps no copy; every spawn leads its own process group, which signal (default SIGTERM) signals, unless pgid names an existing group to join (protocol 1.3): the process then joins that group and that group's session, as setpgid would (a client has no session of its own: each of its spawns and terminals leads one, and setpgid cannot cross sessions), and signal signals the whole group. The group must have been started by this client (a spawn or a terminal it opened), even if its leader has exited; an unknown group rejects with code: 'ESRCH', another session's with code: 'EPERM', and against a 1.2 kernel the client rejects with code: 'ENOSYS' before sending anything, as an older kernel would ignore the option; a program that cannot start rejects with code: 'ENOENT'. user runs it as another user, which only a root client may (see kernel.connect); against a 1.7 kernel the client rejects with code: 'ENOSYS'. cwdMissing is as for kernel.run (protocol 1.14); run and openTerminal take it too, and with 'error' against a 1.13 kernel, which would create the directory, the client rejects with code: 'ENOSYS' before sending anything |
| run(argv, options?) | spawn and wait: { pid, status, signal, stdout, stderr } as text, with onStdout/onStderr streaming text; signal as for kernel.run |
| openTerminal(argv, options?) | a pty session, as kernel.openTerminal, ended included |
| ps() | the kernel's processes: { pid, ppid, pgid, sid, argv, tty, started, state, rss, utime, stime, uid, gid }, state being 'S', 'T' (stopped) or 'Z', rss the process's resident memory in bytes (the size of its wasm memory, what /proc/<pid>/status shows as VmRSS; absent from kernels before 1.61), utime/stime the CPU time it has used, in milliseconds, in its program and in the kernel's calls (see /proc; absent for a JS program and from kernels before 1.63) and uid/gid the effective ids (absent from a 1.7 kernel), and tag the process's tag (see kernel.run), when it has one, with tags, all of them in order, when a spawn added one (see kernel.connect), on rows the client's user may see as root or as the same uid. A client bound to a user sees only that user's processes |
| kill(pid, signal?) | a process, or a process group with a negative pid; no such process rejects with code: 'ESRCH', and one the client's user may not signal with code: 'EPERM' |
| fs | readFile, readText, writeFile(path, string \| bytes), stat, lstat, readdir, mkdir (with parents), rm(path, { force }) (recursive), rename, realpath, symlink(target, path), readlink, exists, on the processes' file system, mounts included (a path under a tmpfs, fsa or hostfs mount reads and writes the mounted file system, as cat in a process would); failures reject with KernelCallError and a POSIX code |
| fetch({ url, method, headers, body, redirect, signal }) | through the kernel's network transport (the one the page passed to createKernel), with a streaming body; redirect is the per-request policy (see Network); transport is the same as a NetworkTransport |
| fs.watch(paths, { recursive }, onChange) | resolves with { close() }; onChange gets { paths }, the changed paths at, below (or, without recursive, directly in) the watched ones, batched per task, or { overflow: true } when there were too many to list, to rescan; it covers every change made through this kernel, by its processes and its clients, and a removal or rename that failed or found nothing to do is none. It also covers what another kernel on the same OPFS root changes (another tab, a worker page) and what a writer outside the kernel reports with postFsNotice, as those notices name them: a directory another kernel creates, removes or renames, the file it writes back, and the records of its symlinks, modes, owners and times, and a notice's trees as their roots. A peer's notices come only once the kernels share the root (/proc/sys/kernel/slicc_shared_root reads 1 from the join handshake on) and only with the shared metadata (not with metadata: false), and a writer outside the kernel that posts no notice is never heard. So a client that has to catch a page writing OPFS directly needs that page to call postFsNotice after each write. Kernels before this one didn't pass peer and outside changes to a client's watch; they reached only ctx.fs.watch. A watch is on names, not files: a watched path need not exist, nor its directories, and one under a regular file is a watch too (every kernel with watch does this, protocol 1.1 on), so its creation, by any mkdir -p above it, a write or a rename to it, is reported as its path, and so are a removal or rename of it or of a directory above it; the watch goes on hearing the name after that. So a client that waits for a directory to appear watches it, rather than polling stat and readdir. Under users, a watched path the client may not read is EACCES, and so is a missing one under a directory the client may not search. Changes are reported by the name they were made under (a file written through a symlink also by its real path), so a client that watches a path under a symlink watches its real path too, for a missing path the real path of its nearest existing directory with the rest of the path after it |
| serveCdp(hook, { runtime }) | offers this client's browser to the kernel's programs (protocol 1.5): hook is the cdp hook of createKernel, asked once per program connection with its runtime and the connecting process's stamp (protocol 1.17); resolves with { close() }, and closing or detaching takes the offer back and closes its connections (see Browser automation) |
| serveFacade(name, hook) → { close() } | serves a facade that createKernel({ facades }) declared, the same way as its hook (protocol 1.11); the latest registration wins, over the embedder's hook too, and close() hands it back. An undeclared name is EINVAL |
| trace(tag, onEvents, { limit }?) | reports, as events, every program that a process carrying tag runs and every such process's end, with nothing missed (protocol 1.15; against an older kernel the client rejects with code: 'ENOSYS'); resolves with { close() } (see below) |
| sudoRun(request, { stdout, stderr, tag }?) | runs a sudo request again, as kernel.sudoRun does, and resolves with { pid, pgid, ended } once it has started (protocol 1.16; against an older kernel the client rejects with code: 'ENOSYS' before sending anything). Only a root client may: a client bound to a user rejects with code: 'EPERM' (sudo: only a root client may run a sudo request). ended is tied to the client, as spawn's is, while the process is not (see Running a request later) |
| onTraits(listener) → () => void | calls listener(traits) each time the kernel announces new transport traits (kernel.updateTransportTraits(), protocol 1.10), after client.transport.traits has been updated; the function it returns removes the listener |
| close({ kill }) | detaches: the client's processes keep running unless kill is set, which ends their process groups with SIGKILL; its terminals are hung up |
| closed | resolves with the error that ended the client |
| users | the kernel's users mode, 'off', 'report' or 'enforce'; 'off' from kernels that don't say |
When the kernel goes away (the page closed or reloaded, terminate()), pending calls and exited reject with KernelGoneError, and so do later calls. Each side holds a Web Lock and waits on the other's, since a MessagePort reports no close in browsers; in Node, the port's close event does the same. The first message is a handshake on the protocol version, 1.17 (1.0 had no watch, 1.1 no mounts, 1.2 no spawn into a group, 1.3 no dial and 1.4 no serveCdp, which reject with code: 'ENOSYS' on such a kernel; a 1.5 kernel has no uplink, a 1.6 kernel resolves names through one but connects nothing to it, a 1.7 kernel has no users, a 1.8 kernel has no sudo and no tags, a 1.9 kernel never announces new transport traits, a 1.11 kernel has no per-spawn tag, a 1.12 kernel takes no requests at attach, a 1.13 kernel has no cwdMissing, a 1.14 kernel has no trace and takes one tag per spawn, not a list, a 1.15 kernel has no sudoRun, which the client rejects with code: 'ENOSYS' before sending anything, and a 1.16 kernel asks a serveCdp hook with no stamp): a client or kernel of another major version is refused with an error naming both.
client.trace(tag, onEvents, { limit }?) → Promise<{ close() }>
Tells a client which programs a command really ran, without polling ps(), which misses a seq or a head that lives for a millisecond. The kernel runs real bash, so builtins and keywords (cd, for, printf, echo) never start a program, and what does is what the command was about (seq, sed, node, the program behind timeout). Give each call a tag of its own (the spawn's tag, which may be a list, see kernel.connect), subscribe to it before the spawn, and onEvents gets every process that carries the tag, in its whole tree, background jobs that outlive the command included:
exec{ type, seq, pid, ppid, pgid, argv, exe, uid, at, replaced? }: a program started, for the first image of a spawn, a child a program spawned (posix_spawn, astimeoutruns its command) and each successfulexecve.replaced: truemarks anexecve, whose program keeps thepidof the image it replaced (bash runs its last command that way, sobash -c '…; node x'ends with anexecofnodeunder bash's pid). Anexecvethat fails (command not found) has no event.fork{ type, seq, pid, ppid, pgid, argv, exe, uid, at }: afork(). Itsargvandexeare the parent's, a forked bash for a subshell, a pipeline element or a command it is about to run. A fork that then runs a program has anexecwith the samepidnext; one that never has anexecran only builtins, sotypetells a forkedbashfrom a real program.exit{ type, seq, pid, status, signal?, utime?, stime?, at }: a process ended, once perpid, after its last image:statusaswaitpidwould report it (127 for a command that wasn't found, 141 for an unhandledSIGPIPE),signalthe name of the signal that killed it ('SIGKILL'),utime/stimethe milliseconds of CPU it used, its images together, as inps()(absent for a JS program).
pid, ppid and pgid are the ids ps() shows, ppid 1 for a spawn's first process; uid is the effective uid; at is the time in ms since the epoch. The kernel reports from the path every process takes to start and end, so a process that execs and exits within a millisecond is reported like any other. Events come in order: seq is one kernel-wide counter, increasing in the order the kernel saw the events (with gaps for events only other subscriptions got), so it orders the execs and exits across a tree more finely than at, and for one pid the fork or exec comes before its exit. A process that started before the subscription reports only its exit.
A client bound to a user sees only the processes of that user it would see in ps() (its own real or effective uid; root sees all), so another user's processes with the same tag never reach it, and a program that sudo runs as root drops out of its view. A tag matches exactly, any of a process's tags.
Batches and overflow: onEvents gets { events, dropped }, the events since the last batch. The next batch waits until the call returns, or, when it returns a promise, until that settles, so a slow consumer holds the kernel back instead of piling up messages. While it waits, at most limit events (4096 by default, at most 65536) wait in the kernel for that subscription; any more are dropped and counted, and the next batch says how many in dropped (0 otherwise), so a fork bomb costs a bounded amount of memory, and a consumer that sees dropped > 0 knows its list is incomplete. close() ends the subscription, and so does closing the client. An empty tag or a bad limit rejects with code: 'EINVAL'.
Headless in Node, for tests
@ai-ecoverse/slicc-kernel/node runs the same kernel in Node without a browser, so packages built for SLICC can test against it. It is a testing entry, not a supported runtime: there is no OPFS, JS programs get the same guard as in the page but no sandbox (see JS programs), and nothing beyond what its tests use is promised.
Node 26 or later (#1129): engines asks for Node >=26. V8 in Node 24 sometimes crashed the whole Node process with a jit_page check failure while a process worker started or was torn down; slicc-cli measured 15 crashes in 1,600 runs on Node 24 and none in 1,600 on Node 26. The kernel's CI and release run on 26.
import { createNodeKernel, nodeTransport } from '@ai-ecoverse/slicc-kernel/node';
const kernel = await createNodeKernel({ network: { transport: nodeTransport() } });
await kernel.writeFile('/node_modules/@ai-ecoverse/wasm-bash/package.json', manifest);
const { status, stdout } = await kernel.run(['bash', '-c', 'echo hi'], { cwd: '/home' });
kernel.terminate();createNodeKernel({ root, modules, commands, env, network, worker, facades, processMounts, fstabRetries, cdp, hostfs, hostfsOrigin, hostfsFetch, users, onDenial, approve, compileCache, warmWorker, warmWorkers }) takes the options of createKernel except metadata, and fstabRetries, the delays in ms between tries of a failing /etc/fstab line (default [1000, 4000, 16000]). root is an in-memory directory by default (memoryRoot() makes another), which keeps each file in 1 MiB chunks, and POSIX metadata stays in memory. Processes and threads run on worker_threads. The kernel has run, openTerminal, users, setRoutes, updateTransportTraits and terminate as above, plus integrity.revoke(path?), root, writeFile(path, data, { mode }?) (creating the parent directories; mode sets the permission bits, 0 to 0o7777, before the data is written), chmod(path, mode) and readFile(path) to put files in place and read results; like the fs of an attached client, they go through the mounts, as the processes see them. nodeTransport() is fetchTransport() with Node's fetch, which no CORS binds (crossOrigin: 'any'). connect({ user }) and attachKernel work as in the browser: the port is a worker_threads MessagePort, which a worker thread can attach with, and terminate() ends every attached client.
compileCache (#1285, slicc-jsh#566) is where each process worker keeps the compiled code of the JS programs it imports (module.enableCompileCache), so the next spawn of the same program skips V8's compile. By default a Node kernel writes a private directory of its own (#1597): <pid>-<random> in a per-user parent slicc-kernel-cc-u<uid> under the host's temp directory (os.tmpdir()), both mode 0700, removed by terminate(). A parent that isn't a real directory of this user closed to others (a symlink, another user's, or group- or world-accessible) isn't used, and the kernel runs without a cache. The first kernel in a host process also removes the parent's directories whose process is gone, so a crashed host leaves none behind for good; it lists only that parent, never the temp directory itself, which can hold tens of thousands of entries (1.160.3 listed it, costing a host about 15 MB of RSS and 30 ms at start, slicc-jsh#566). Measured on Node 26 with a 2 MB module, the default takes a spawn from about 21 to 8 ms and adds no measurable RSS per process. compileCache: false turns it off, and an absolute host directory uses that one instead, shared by every kernel given it. It stores V8's code cache, keyed and checksummed by the module's source, one file per program (about 7 MB for a 2.4 MB bundle), shared by every kernel given the same directory; programs can't reach or write it (the worker hands it to Node before the lockdown, and node:worker_threads stays refused). Measured on a 2.4 MB bundle, a spawn went from about 54 to 39 ms; a trivial program costs about 1 ms more. The directory must be private to the embedder: V8's code cache is trusted bytecode that Node only checksums, so whoever can write it can plant code that runs inside a process worker past the lockdown. Never make it reachable from inside the kernel (no hostfs mount of it or of a parent), and don't share one between kernels of different trust. A host's own NODE_COMPILE_CACHE is never handed to the process workers, with or without the option, so programs never land in a host-wide cache. If a host preload (--import or --require) has already enabled another compile cache in the workers, a kernel given a compileCache directory refuses to run programs there instead of caching them in the host's directory; a kernel on its default private directory leaves it to the host's, as it did before the default.
warmWorker (on by default; false turns it off; #1341, slicc-jsh#566) keeps one process worker booted ahead of the next spawn, fork or thread on the Node entry, so the spawn skips the worker's boot: it has loaded the process worker module and nothing else, no pid, credentials, environment, cwd, descriptors, lockdown or program, all of which arrive with its init message, and every worker still serves exactly one process or thread and is then terminated. Its own process.env is a snapshot taken when the spare is created rather than at the spawn, but a program never sees it (process is withheld, and a program's environment is the one its spawn gives it). The spare never keeps the host alive, is replaced after each spawn off the critical path, is dropped if it errors or exits while idle, and is released after 30 s without a spawn; terminate() ends it. It costs about 11 MB of host RSS while it waits. warmWorkers: n (opt-in; #1361, slicc-jsh#566) keeps up to n spares instead of one (an integer from 0 to 64; warmWorker: false still means none), so a burst of starts, as worker pools make, finds a spare for each: all are refilled after each take off the critical path, and all are released together after 30 s without a spawn and ended by terminate(). Each costs about 7–11 MB of host RSS while it waits. It pays off for bursts of Worker threads (jsh measured about 13 ms less per start in a burst of 8); for bursts of child processes that boot a large runtime of their own, the refills compete for CPU with the children and the gain is small or none.
By default nodeTransport() refuses destinations on the host itself, because Node can reach them and a page can't: local DevTools on 9222–9229, dev servers, local admin APIs, and the cloud metadata address.
- What it refuses: loopback (
127.0.0.0/8,::1, and their IPv4-mapped forms), unspecified addresses (0.0.0.0/8,::),localhostand*.localhost, and link-local addresses (169.254.0.0/16,fe80::/10), plus AWS's IPv6 metadata addressfd00:ec2::254. - How it checks: it matches on the addresses the name resolves to, so a public name that resolves to
127.0.0.1is refused too. It checks every request and WebSocket open,host.slicc.internaland each redirect hop included. - What a refusal looks like: a
403whose body names the option, andEACCESfor a WebSocket, before any connection is made. - The opt-in:
nodeTransport({ hostLoopback: true })allows the host's loopback except ports 9222–9229.nodeTransport({ hostLoopback: [8080, 9222] })allows exactly the listed ports, so DevTools ports are reachable only when named. Link-local stays refused either way. - Connect-time enforcement: the kernel also checks the address each connection actually reaches, before anything is sent, so a name whose DNS answer changes after the check is still refused. A keep-alive connection opened outside this kernel's policy (by the host application, or by another kernel in the same process whose
hostLoopbackallows it) to the same origin could be reused without a new check. When a proxy is in use (HTTP_PROXY/HTTPS_PROXYwith--use-env-proxyorNODE_USE_ENV_PROXY=1), a connection opened to the proxy's own host and port is allowed even on the host's loopback, and so is any request later tunnelled over that same live TCP connection (matched by its local and remote address and port, and forgotten when it closes), so only the pre-check applies to the target; a direct connection, aNO_PROXYhost's included, is checked as usual, and a proxy that resolves names itself closes the rebinding window on its side.
In a Cloudflare Durable Object
@ai-ecoverse/slicc-kernel/cloudflare runs the kernel inside a Durable Object, with its processes in Dynamic Workers. It is experimental: the API can change, and the limits below are real.
import { DurableObject } from 'cloudflare:workers';
import { createCloudflareKernel } from '@ai-ecoverse/slicc-kernel/cloudflare';
export class Kernel extends DurableObject {
kernel() {
const { storage } = this.ctx;
this.booting ??= createCloudflareKernel({
loader: this.env.LOADER,
sql: storage.sql,
sqlite: { transaction: (fn) => storage.transactionSync(fn) },
});
return this.booting;
}
async fetch() {
const kernel = await this.kernel();
return Response.json(await kernel.run(['bash', '-c', 'ls / | head -3'], { cwd: '/root' }));
}
}The Worker needs a Worker Loader binding (worker_loaders) and a SQLite-backed Durable Object class. Packages are installed as on Node, with kernel.writeFile under /node_modules; examples/cloudflare bundles bash and coreutils with the Worker and installs them on first boot, and examples/cloudflare-computer adds a Cloudflare Computer Workspace, and curl and jq with the network.
createCloudflareKernel(options) returns a kernel with run, openTerminal, writeFile, readFile, chmod, connect, users, groups, setRoutes, mount, umount, mounts and terminate, as createNodeKernel does. Its own options:
| option | default | |
| --- | --- | --- |
| loader | required | the Worker Loader binding |
| sql, sqlite | none | the Durable Object's ctx.storage.sql, and { transaction, writeBehind }: the root file system and its POSIX metadata live in tables prefixed slicc_ |
| root, meta, ranged | memoryRoot() | a root of your own in place of sql |
| clock | a timer of 0 ms | awaited before every timed wait, so that the object's clock has moved on when the kernel reads it: a Workers clock stands still while code computes, and a timer moves it. Don't pass a call into the object's own namespace (this.env.KERNEL.get(this.ctx.id).now()), as this table used to say: on Cloudflare each such call raises the subrequest depth of the request it is made in, for the rest of that request, so after about 14 timed waits in one request (a git clone, eight curls, a loop of sleeps) the clock fails, and so does every later call of the object that loops back into the Workers runtime: an R2 get with Unspecified error (0), which a program that reads a file from such a mount sees as EIO, and a Durable Object stub with Subrequest depth limit exceeded. Local workerd has no such limit |
| isolates | { max: 8, waitMs: 10000, memory: 64 MiB, perInstance: 8 MiB } | how many Dynamic Workers run at once, how long a spawn waits for one, and the memory budget per Dynamic Worker |
| commands | none | { append }: more command roots, as for createKernel; one can be a mount (see A file system the Durable Object serves) |
| network | none | { transport, tlsEngine, uplink, doh }: the transport programs reach the outside world through, and the TLS engine for their https:// requests (see The network) |
| cdp | none | a CdpHook that offers programs a browser, as createKernel's cdp does (see Browser automation); a relay to Cloudflare Browser Run, say, without a client of its own and its serveCdp |
How it works. Workers has no Worker, refuses Atomics.wait, and does not share memory between isolates, so a process cannot block the way it does in a page. Here a process is a wasm instance in a Dynamic Worker, parked with JSPI (WebAssembly.Suspending) while its system call is answered by the Durable Object over Workers RPC.
- The kernel side is the same code as in the page. A proxy in the Durable Object speaks the kernel's shared-memory protocol on behalf of each remote process (
src/async/remote-worker.ts). - The process side is derived at build time.
tools/derive-asyncturns the synchronous process runtime (src/process/wasi,src/process/emscripten) into an async one,dist/async-process.js: functions that can reach a kernel call becomeasync, and wasm is entered throughWebAssembly.promising. The build fails where it cannot (a kernel call in a constructor, a getter, or a callback passed to a synchronous built-in). - Emscripten programs run without their glue. Workers refuses
eval, and Emscripten's JavaScript file system layer cannot be suspended by JSPI. So the kernel implements the Emscripten import ABI itself (src/process/emscripten).createNodeKernel({ emscripten: 'kernel' })selects the same on Node; the default there and in the page stays the package's glue. - Programs are Worker modules. Workers also refuses
WebAssembly.compileat run time, so each program's wasm is handed to the Worker Loader, one Dynamic Worker per program, with many processes in it. A fork's memory snapshot stays inside that Dynamic Worker. - Threads are further instances in the process's Dynamic Worker. A Dynamic Worker has no second thread and shares no memory with another isolate, so a WASI or WASIX thread (
wasi.thread-spawn, which wasix-libc'spthread_createcalls) is another instance of the program on the process's sharedWebAssembly.Memory, started in the same Dynamic Worker and run through JSPI like the main thread. The threads take turns: one runs until it makes a kernel call or waits on a futex, and those suspend it while the others go on. Each thread has its own channel to the kernel, carried over its process's link, so the kernel sees it as on the page: blocking calls, signals sent to it (pthread_kill, a process-directed signal its siblings block) andEINTRare its own. A futex wait (futex_wait, which wasix-libc's mutexes, condition variables,pthread_joinand semaphores use) is answered inside the Dynamic Worker by afutex_wakefrom another thread; one with a timeout also waits in the kernel, for its time and for signals, and a wake ends that wait.sched_yieldlets the other threads run, so a spin lock that yields gets its turn.
createNodeKernel({ blocking: 'async', emscripten: 'kernel' }) runs the same async runtime on Node, for tests.
Limits.
- Emscripten programs linked with pthreads run on one thread. An Emscripten program built with
-pthreadimports a shared memory and Emscripten's thread functions, even when it never starts a thread (jq does, for its thread-local storage). The kernel gives it that memory and sets up its main thread, so it runs as any other program does, but itspthread_createfails withEAGAIN.createNodeKernel({ emscripten: 'kernel' })does the same. WASI and WASIX programs do start threads (above): BIND'sdig,hostandnslookupfrom@ai-ecoverse/wasix-bind, which start threads for their event loops, run as on the page. - Threads take turns. They never run at the same time, so threads don't make a program faster, and a thread that computes without a kernel call holds up the others. A thread waits on a futex only through wasix-libc's
futex_wait: a program whose own code blocks with wasm'smemory.atomic.wait32instruction (Rust's std, so tokio's runtime and astd::threadthat parks) traps there withAtomics.wait cannot be called in this context(status 134); on Node'sblocking: 'async', where that instruction is allowed, i
