# Building for WASM (https://docs.neuralisapp.com/package-system/wasm-build)

Project packages with server-side code run in an Extism WASM sandbox, never
in-process ([runtime tiers](https://docs.neuralisapp.com/package-system/lifecycle.md)). You author with
the **same node conventions** as a native package (`src/tools/*.ts`,
`src/routes/*.ts`, optional `src/lifecycle.ts`); the build **generates** the
dispatcher, compiles `dist/package.wasm` and emits the `dist/routes.json` route
manifest. Declarative-only packages need no build.

## When you need it [#when-you-need-it]

| Missing piece | Symptom |
| --- | --- |
| No `runtime.type: "wasm"` in the manifest | Treated as declarative-only; handlers never wire, even with a `.wasm` |
| No `src/tools/*` / `src/routes/*` / `src/lifecycle.ts` source | Every build trigger fails with "No buildable source" |
| Source present but not built yet | Loads `partial` (`build-missing`); tool calls return a clean error |
| `src/routes/*` present but no valid `dist/routes.json` | **Fails closed** — loads `partial`, never wiring an ungated route |

The manifest half is one line:

```json
{ "neuralis": { "runtime": { "type": "wasm" } } }
```

Do **not** add `runtime.binding: "embedded"`: it is native-only and the
loader rejects the whole package.

## The entry contract — node conventions, generated dispatch [#the-entry-contract--node-conventions-generated-dispatch]

There is **no hand-written `handleTool` / `handleRoute`**: you write per-file
handlers (the tool name is the file name, paired with `tools/<name>.json`; a
route declares `pattern` and optional `feature`), and `neuralis-build`
generates the dispatcher over the **guest PDK**.

```ts
// src/tools/echo.ts  → tool "echo" (pairs with tools/echo.json)
import type { PdkContext } from '@neuralis/package-system/pdk-guest';

export default async function (args: Record<string, unknown>, ctx: PdkContext) {
  // brain-core `POST read` AS THE CURRENT CALLER: their feature + uri-policy decide.
  const res = ctx.fs.read('data://my-pkg/note.md');
  const note = res.ok && res.status === 200
    ? (res.body as { files?: { content?: string }[] }).files?.[0]?.content
    : undefined;
  return { content: [{ type: 'text', text: String(args.msg ?? note ?? '') }] };
}
```

```ts
// src/routes/items.ts
export const pattern = 'items/:id';      // :param + '*' wildcard, same matcher as node routes
export const feature = 'my-pkg.read';    // enforced HOST-side, BEFORE the sandbox is entered

export async function GET(req: { query: Record<string, string> }, state: unknown) {
  return { status: 200, body: { id: req.query.id } };
}
```

This `ctx` is the guest PDK context, not the native
`ctx.config`/`ctx.platform`/`ctx.hostPorts`/realtime contracts — a flat surface: `ctx.data.*` (the package's own data dir), `ctx.callRoute`
(cross-package route dispatch, below), `ctx.fs.*` (sugar over brain-core's file
routes, riding `callRoute`), `ctx.context`, `ctx.log`, `ctx.config` and
`ctx.emitEvent` (both inert today — `config` returns `{}`, `emitEvent` is a
no-op), and `ctx.session` (the three ids the host forwards:
`userId`/`projectId`/`agentId`). Identity binds **per call, host-side**: a
capability captured in `init` still acts as whoever is calling now.

State is **lazy and cached**: `init(ctx)` runs on the first call, reused for
the instance's lifetime; persist durable state through `ctx.data`.

### `ctx.data` is confined to your own directory [#ctxdata-is-confined-to-your-own-directory]

All three data calls take a path **relative to your data dir** and are confined
to it: a `..` segment, an absolute path or a symlink pointing outside answers
`ok: false`. `ctx.context` carries `{ packageId, trust }` and no host path.
Results are `ok`-discriminated (`read` adds `content`, `list` adds `entries` of
`{ name, isDirectory }`); a failure carries `invalid_path`, `escape`,
`not_found`, `not_file`, `not_directory`, `too_large` (reads cap at 5 MB) or
`io_error`, never an OS message. A `list` that returns a bare array means an
older builder: rebuild.

Confined is not governed: this direct surface does not evaluate the per-path
policies of the `data://` source around your dir. Anything **outside** it goes
through `ctx.callRoute` / `ctx.fs.*`, under the target route's feature gate
and uri-policy.

## Routes are feature-gated by the host [#routes-are-feature-gated-by-the-host]

The host reads `dist/routes.json` and runs the **same feature gate, rate limit
and audit** a node route gets *before* entering the sandbox — a caller missing
the feature gets a 403 and your handler never runs ([Routes](https://docs.neuralisapp.com/package-system/routes.md)).

## The pipeline [#the-pipeline]

```text
src/tools/*.ts + src/routes/*.ts + src/lifecycle.ts
  → generate   (handleTool/handleRoute dispatcher over the guest PDK)
  → esbuild    (generated entry + your source → bundled CJS)   dist/index.js
  → extism-js  (QuickJS + Wizer snapshot + Binaryen optimize)   dist/package.wasm
  → emit       (route manifest, extracted statically)           dist/routes.json
```

extism-js gets the builder's **canonical** interface file
(`dist/plugin-interface.d.ts`); a user-authored declaration is not read.

## Calling other packages — `ctx.callRoute` [#calling-other-packages--ctxcallroute]

A **trusted** project package reaches the platform as a skill script or widget
does — through the packages' **feature-gated routes**, in-process:

```ts
const res = ctx.callRoute('@neuralis/brain-core', 'POST', 'search', {
  search_mode: 'grep', glob: '**/*.md', query: 'TODO',
});
```

The dispatch carries the **current caller's real session**, threaded host-side
per call, never named by the guest: the target route's feature gate, uri-policy
and rate limits decide deny-by-default as if the user had called it. With no
interactive-human marker on this path, guest **writes land in the review
queue** (`pending_review`). `ok: false` is a bridge failure
(`cross_package_denied` for untrusted, `route_not_bridgeable`,
`route_response_too_large`, …); `ok: true` carries the route's own
`status`/`body`, a 403 included. Route catalogs: [agent-core](https://docs.neuralisapp.com/agent-core/routes.md)
· [brain-core](https://docs.neuralisapp.com/brain-core/routes.md) · [admin](https://docs.neuralisapp.com/admin/routes.md) ·
[machine-core](https://docs.neuralisapp.com/machine-core/routes.md).

Streaming/SSE and binary bodies are **HTTP-only** and come back
`route_not_bridgeable` (agent-core `stream`, the `workflow/*` events sub-path,
brain-core `events` and `raw`, a machine-core stream proxy returning stream content). brain-core `upload`
is multipart-only and answers `ok: true, status: 400` in-process: use the JSON
`create` route.

There is **no host-function HTTP fetch**. Guest network I/O is Extism's
`Http.request` behind **two independent gates**: the sandbox's host allow-list
(empty for untrusted, unrestricted for trusted), then the platform's
SSRF-guarded fetch shared with the built-in web tools, whose refusals come back
as an ordinary status, never thrown.

<Callout type="warn" title="Only what reaches the platform fetch comes back as a status">
The sandbox's host allow-list sits **above** the platform fetch and refuses by
throwing, which terminates the plugin until it is reloaded instead of returning
`403`. That covers a non-`http(s)` scheme and any URL with an empty hostname
(`file:///etc/passwd` is both) at **every** trust tier: even a wide-open
allow-list matches no empty hostname. Validate the scheme and host in your own
code before calling `Http.request`.
</Callout>

What the fetch policy refuses:

- **Private, loopback, link-local and cloud-metadata addresses**, `localhost`
  and obfuscated spellings (`0177.0.0.1`, `2130706433`, IPv4-mapped IPv6, NAT64)
  included.
- **Any port but 80, 443, 8080 and 8443** — the most common surprise; the port
  is checked before resolution.
- **Credentials in the URL**; **more than 3 redirects** (each hop re-checked);
  responses over 5 MB (`413`); calls over 30 s in total (`504`); verbs other
  than `GET`, `HEAD`, `POST`, `PUT`, `PATCH`, `DELETE`, `OPTIONS` (`405`).
- Setting framing headers (`host`, `content-length`, `transfer-encoding`,
  `connection`, …); response headers are not exposed either.
- A refusal is a **`403` with a generic body**, its reason only in the package
  log, so the status cannot probe internal names.

Internal services are reached with `callRoute` and `ctx.fs.*`, never over HTTP.

## Build triggers [#build-triggers]

| Trigger | When |
| --- | --- |
| Filesystem UI "Build Package" button | Recommended — builds, reloads, and audits in one step |
| Package install | Automatic when the manifest declares `runtime.type: "wasm"` and source is present |
| CLI inside the container | `node /neuralis/node_modules/.bin/neuralis-build <packageRoot>` |

<Callout type="warn" title="Invoke the CLI by absolute path">
`npx neuralis-build` fails from a project's `_packages/` directory: with no
`node_modules` above the data zone, npx falls back to the public registry and
gets an E404. Call the bin under `/neuralis/node_modules/.bin/`.
</Callout>

The file watcher **reloads** but never rebuilds: after editing `src/`, build;
the watcher swaps in the new `dist/` output.

## Prerequisites and limits [#prerequisites-and-limits]

The Docker image bakes pinned, checksum-verified `extism-js`, `wasm-merge` and
`wasm-opt`; esbuild ships with `@neuralis/package-system`. The sandbox enforces
per-trust limits at runtime:

| | Untrusted | Trusted |
| --- | --- | --- |
| Call timeout | 30 s | 120 s |
| Host transfer arena | 8 MB | 32 MB |
| Worker JS heap | 32 MB | 128 MB |
| Network (`Http.request`) | refused at the empty sandbox host allow-list — a refusal that terminates the instance | any public host, through the SSRF-guarded fetch above |
| Cross-package routes (`callRoute` + the `ctx.fs.*` sugar) | denied — no outbound surface at all | allowed, as the current caller: feature-gated, uri-policy-gated, writes land `pending_review` |
| Own data dir (`ctx.data.*`) | allowed — confined to that directory | allowed — confined to that directory |

**Neither memory row caps your module**: the arena bounds one call's boundary
copy, the heap the worker's JavaScript; the module's linear memory is uncapped. Past the arena an allocation
returns a null address rather than raising, so check the offset.

**An untrusted `Http.request` terminates the instance** (see the callout) until
an admin reloads it.

## The other build mode — `neuralis-build ui` (native UI) [#the-other-build-mode--neuralis-build-ui-native-ui]

The same CLI packages a **host-assigned native** package's React UI as ONE
prebuilt browser module the host attaches at runtime:

```bash
neuralis-build ui [packageRoot]
```

It bundles `app/host.tsx` (exporting `install…HostComponents({ registry, port })`)
into `dist/app/host.js` + `chunks/`, an optional `dist/app/host.css` and
`dist/app/shared-imports.json`; declare it as
[`app.module`](https://docs.neuralisapp.com/package-system/app-surfaces.md) (the build fails if the two
disagree). React, the client library and modules other native packages publish
are never bundled (a copy fails with `BUNDLED_SHARED_MODULE`); utility classes
are compiled by the host, so keep `className` code under `app/`; fonts and
images are inlined, since only `.js`, `.mjs` and `.css` are served.

## The worked example [#the-worked-example]

`example-project` ([contract examples](https://docs.neuralisapp.com/package-system/reference-package.md)) ships
**source only**, so a drop reports `partial` / `build-missing` until built; and
it **omits** `runtime.skillScripts`, because below `trusted` only `"none"` is
allowed: its `SKILL.md` is prose the agent reads, its `scripts/` never spawn.

## Troubleshooting [#troubleshooting]

- **"No buildable source"** — see [When you need it](#when-you-need-it).
- **"embedded binding requires native trust"** — remove
  `runtime.binding: "embedded"`; project packages declare only `runtime.type`.
- **`inputSchema.$schema must be JSON Schema draft-07`** — enforced at load:
  see the `$schema` rule in [Tools](https://docs.neuralisapp.com/package-system/tools.md#root-schema-rules).
- **A route 403s for everyone / 503s after build** — 403: the caller lacks the
  route's `feature`; 503 with a "no valid routes.json" log: no manifest was
  emitted — rebuild.
- **Tool advertised but calls fail** — loaded `partial` or errored; check the
  server logs, rebuild.
- **The package builds clean but never appears in the catalog at all** (not even
  `partial` or errored) — a `tools/*.json` failed validation, which aborts the
  whole package load; check `annotations.category`, `x-neuralis.operation` and
  `transport` against [the `x-neuralis` rules](https://docs.neuralisapp.com/package-system/tools.md#the-x-neuralis-extension).
  This error currently surfaces only in the server logs.
- **Build timeout** — extism-js is capped at 30 seconds; check for circular
  dependencies, avoid bundling large libraries.

A successful build leaves `dist/index.js`, `plugin-interface.d.ts`,
`package.wasm`, `routes.json`.