# Lifecycle and trust tiers (https://docs.neuralisapp.com/package-system/lifecycle)

A package's `runtime.type` decides how its code executes. Most packages don't
need runtime code at all — tool schemas and markdown contributions are
discovered declaratively — but when a package needs handlers, routes, or
stateful services, it picks one of three contracts.

| Runtime | Who | How it runs |
| --- | --- | --- |
| `node` | Native builtins only | In-process: lifecycle module + per-file route/tool handlers |
| `wasm` | Project packages (JS/TS) | Extism WASM sandbox in a worker thread, single entry module |
| `mcp` | Native builtins only | Subprocess speaking MCP over stdio, as the host user |
| *(omitted)* | Declarative-only packages | No code execution at all |

**`wasm` is the only code runtime a project package can use.** `node` runs in
the host process and `mcp` spawns a child as the host user, so both require
native trust. A project package declaring either loads `partial`
(`untrusted-node` / `untrusted-mcp`): its declarative contributions still
register, nothing is spawned, and every handler call returns a clean
runtime-unavailable error.

**Its compiled code is never even loaded.** The host picks the discovery mode
from provenance it assigns itself, never from the manifest. Only a native
builtin is discovered in *full* mode, where `dist/src/{routes,tools}/*.js` and
`dist/src/lifecycle.js` are imported. Every other package root is discovered
*metadata-only*: the files are listed, so the package is catalogued accurately,
but never imported. A module's top-level code runs the moment it is imported,
so refusing to *load* it is the boundary, not refusing to call it.

## Native node lifecycle [#native-node-lifecycle]

A node package with state ships a lifecycle module (`src/lifecycle.ts`, compiled
to `dist/src/lifecycle.js`) exporting standalone functions. The module itself is
optional — a package with no routes and no tool handlers needs none — but when
it exists, `init` is required and everything else is optional.

```ts
import type { PackageInitContext } from '@neuralis/package-system';

type MyState = { store: ItemStore };
type MyApi = { getStatus: () => string };

export async function init(ctx: PackageInitContext): Promise<MyState> {
  const store = new ItemStore(ctx.data.fileStore('items'));
  return { store };
}

export function api(state: MyState): MyApi {
  return { getStatus: () => 'healthy' };
}

export async function start(state: MyState): Promise<void> { /* background work */ }
export async function stop(state: MyState): Promise<void> { /* cleanup */ }
```

The state `init` returns is captured once and handed back to every other export,
so none of them re-derive it. The recognised exports are:

| Export | Called | Purpose |
| --- | --- | --- |
| `init(ctx)` | Once at load | Create and return the package's state. That state flows to route and tool handlers as their `state` argument. |
| `api(state)` | Right after `init` | Build the public surface other packages reach through `getPackageApi()`. Omit it and the package exposes no cross-package API. |
| `start(state)` | After **all** packages initialized | Start background tasks. |
| `onBootstrapComplete(state, ctx)` | After every package's `init` and `start`, before route serving | Start work requiring the lazy `ctx.platform` facts: runtime stack, connector registries, URI policies, source declarations and host identity. |
| `onCredentialChanged(state, event)` | After a credential write/delete | Drop matching cached clients; the value-free event carries id, scope and change, and the runtime bounds each hook. |
| `drain(state)` | Before shutdown stop | Stop admitting work and finish or checkpoint in-flight work under the runtime shutdown bound. |
| `health(state)` | Runtime health query | Return structured checks with closed status/reason values; a throw, timeout or invalid report is degraded. |
| `stop(state)` | Shutdown | Cleanup. The captured state is released afterwards. |
| `provisionProject(state, ctx)` | When a project is created | Idempotent per-project data setup. |
| `deprovisionProject(state, ctx)` | When a project is permanently deleted, before any of its files | Remove everything the package keeps for `ctx.projectId` outside the project's data tree (containers, volumes, index entries). Idempotent, and it must **throw** when something is left: the delete then stops with the project still archived, names the package, and can be retried. It runs under a timeout, one package after another. |
| `onPrincipalRevoked(state, event)` | When a user is disabled, deleted or signed out everywhere, or loses a project | Close what the package holds open for `event.userId` (sockets, jobs, pollers) through its existing stops. It never decides access — the user is already refused everywhere — and it runs under a timeout. |

Nothing else in the module is treated as a lifecycle export. Tool and route
handlers are **not** declared here — they are discovered from `src/tools/*.ts`
and `src/routes/*.ts` and wired into the package automatically.

`PackageInitContext` carries package identity, scoped `data`, `host`, cross-package `packages`, the credential ports, `sessions.createProjectFactory`, `logger`, live `config`, lazy `platform` facts and trust-gated `hostPorts`. `ctx.config.get(key)` throws for an unregistered key or a caller below native trust; platform facts throw until published, so read them at use time. The optional native `hostPorts.packageDiagnostics` fails explicitly when missing or not ready, never as an empty catalogue. A native package's `data.globalDir` is its project-independent home; a project-installed package gets only its scoped `dataDir`. Project factories are lazy, coalesce concurrent builds and evict idle entries (LRU).

### Runtime provider and declared services [#runtime-provider-and-declared-services]

Exactly one builtin declares `provides: ["runtime"]` and exports `runtimeProvider` from `dist/src/runtimeProvider.js`; the host loads it natively and calls `boot` with kernel ports. `runtime.whenReady()` protects serving until bootstrap facts are published. Runtime loading, lifecycle fan-outs and realtime channel discovery remain package-owned.

Other native `provides` ids declare implementations through `PackageRuntimeApi.services` (from file-discovered `init`, expose `state.services`): `session-ticket-verifier`, `route-token-verifier`, `agent-directory`, `channel-gateway`, `package-source-roots`, and `oauth-callback:<prefix>`. The runtime and the ticket verifier are required singletons; `route-token-verifier` checks a CLI's OAuth bearer (absent ⇒ that arm denies); the others are optional singletons, and OAuth prefixes must not overlap. A non-native declaration confers no service authority; `mcp-server` is reserved.

### Realtime channels [#realtime-channels]

A native `src/channels/<name>.ts`, compiled to `dist/src/channels/<name>.js`, exports matching `channel`, non-empty `feature`, and `subscribe(session, params, emit, state)`. It returns an unsubscribe function. The shared events hub gates the feature before subscribing; the package checks its own scope and event-delivery permissions. Channels are not model tools or markdown contributions.

A native `src/events/<subject>.ts` beside it exports matching `subject`, a required `visible(event, session, state)` that answers per recipient, and an optional `bridge(publish, state)` that starts once the package has booted and returns its unsubscribe; the package stops the bridge when it unloads. The declarations live in [`events[]`](https://docs.neuralisapp.com/package-system/events.md).

### Writing to your own data directory [#writing-to-your-own-data-directory]

`data` is scoped to your package by the type system: `jsonlAppender()` takes a
**resolved path**, which only `dataPath(relative)` produces:

```ts
const events = ctx.data.jsonlAppender<MyEvent>();
await events.append(ctx.data.dataPath('runs/today.jsonl'), { kind: 'ran' });
```

`dataPath` refuses an absolute path or one that climbs out of your data
directory; it resolves a path without touching the disk. The appender creates
missing intermediate directories; your own `fs` calls must. Hold **one**
appender for the life of the package: write ordering is per instance.

`fileStore(subdir)` is the record-shaped sibling (one JSON file per entity:
`get`, `list`, `put`, `delete`, `exists`). **Use `update(id, fn)` whenever the
next value depends on the current one:** a `get` → modify → `put` reads outside
the write ordering, so the second of two writers erases the first. `fn` is
synchronous, gets the on-disk record (or `null`) and returns the next one, or
`undefined` to write nothing. A corrupt record or read failure is raised, never
overwritten.

A WASM package's `ctx.data` calls take the same relative paths but return
`{ ok: false, error }` (a fixed code, never a filesystem path) instead of
throwing — see [WASM build](https://docs.neuralisapp.com/package-system/wasm-build.md#ctxdata-is-confined-to-your-own-directory).

### Logging from a package [#logging-from-a-package]

The injected `logger` writes structured JSONL under `{dataDir}/logs/`
(`{globalDir}/logs/` for a native package). It resolves its level at every
call: the operator's `packageLogLevelOverrides` entry for your `pkg` first, then
the global `packageLogLevel`, then `debug` — platform keys, so the manifest
declares nothing. Never cache `logger.level` in a constructor: the lifecycle runs
before the host installs the config source. Logs are oldest-first; read the
newest N with `JsonlAppender.readNewest(path, n)`, which also walks the rotated
`.1`, `.2` … generations.

### Reading a credential at runtime [#reading-a-credential-at-runtime]

`ctx.credentials` is the `CredentialResolver` the loader injects into **every**
package — the way a package reads a SECRET. There is no raw-environment escape
hatch (`resolveEnv` does not exist); boot-critical infrastructure values arrive
as typed config (a `configSettings[]` entry with an `envFallback`).

```ts
// most-specific-wins: agent → project → user → global; undefined when unset, never throws
const key = await ctx.credentials.resolveCredential('acme.apiKey', { projectId });
if (!key) throw new Error('acme.apiKey is not configured');
```

- **Resolve per call, not once at `init`:** values rotate, and the winning
  scope depends on who is calling.
- **Declare the id** in [`credentials[]`](https://docs.neuralisapp.com/package-system/credentials.md): an
  undeclared id never appears in the admin catalog, so nobody can set it.
- **`resolveForKind(kind, scope)` is a stub** that answers an empty object; use
  `resolveCredential`.

A connector factory closes over this same port; its context carries no
credentials map.

### Cross-package calls are typed APIs, not MCP [#cross-package-calls-are-typed-apis-not-mcp]

The public object `api(state)` returns is what other packages reach through
`getPackageApi()`; internal MCP between packages is forbidden. The calling
convention, the session and the drift guard are on
[Routes → Typed cross-package API](https://docs.neuralisapp.com/package-system/routes.md#typed-cross-package-api).

## WASM sandbox (project packages) [#wasm-sandbox-project-packages]

A project package with `runtime.type: "wasm"` is authored with the **same
per-file conventions** as a native one (`src/tools/*.ts`, `src/routes/*.ts`, an
optional `src/lifecycle.ts`); `neuralis-build` generates the dispatcher and
compiles `dist/package.wasm` + `dist/routes.json`. The host runs a route's
feature gate BEFORE entering the sandbox. The sandbox is **stateless across
calls** (`init` runs lazily once per instance; persist through `ctx.data`), and a
trusted package reaches other packages through `ctx.callRoute`, as the current
caller. Pipeline and guest PDK: [WASM build](https://docs.neuralisapp.com/package-system/wasm-build.md).

## MCP runtime (non-JS native packages) [#mcp-runtime-non-js-native-packages]

A package with `runtime.type: "mcp"` declares `entry.command` (plus optional
`args`); the host spawns it as a subprocess speaking MCP over stdio — the path
for a Python, Go or other non-JS implementation of the same contract. **It
requires native trust:** the child runs as the host user with the host's reach,
so it is a *language* escape hatch, not a sandbox. Its environment is built for
it — secret-shaped names, provider-prefixed variables and platform keys are
stripped — but that is a denylist, defence in depth only; keep secrets in the
credential store.

### If you just want to use an existing MCP server [#if-you-just-want-to-use-an-existing-mcp-server]

Declare a connector instead (`connectors[]` with `"type": "mcp"`, a `url`, and
an explicit HTTP `transport` — an omitted `transport` defaults to `stdio`): once
connected, its tools join the agent's MCP session with no code of your own. **A
local stdio server (`command`) has no path today, at any tier**: in-host stdio
is refused by the transport factory; the intended shape is a managed sidecar, which is not built yet. See [Connectors](https://docs.neuralisapp.com/package-system/connectors.md).

## Dispatch: trust-tier enforcement [#dispatch-trust-tier-enforcement]

Both dispatchers — tools and [routes](https://docs.neuralisapp.com/package-system/routes.md) — enforce
trust limits before any handler runs, keyed per package over a one-minute
window:

| Trust | Tool timeout | Tool calls/min | Route calls/min |
| --- | --- | --- | --- |
| `native` | none enforced | unlimited | unlimited |
| `trusted` | 120 s | 100 | 300 |
| `untrusted` | 30 s | 10 | 30 |

Tool dispatch also validates input against the tool's JSON Schema and **fails
closed** when the validator is unavailable — but a tool with **no**
`inputSchema` skips validation entirely, so ship a strict `tools/*.json` for
every tool. Results are normalized to MCP shape (`text`, `image`, `audio` and
`resource` blocks kept, every other block type dropped; `structuredContent` and
the UI-only `_meta` kept), errors come back as `isError: true`, and one size
bound applies at the host's tool-call funnel for every package type (see
[Tools](https://docs.neuralisapp.com/package-system/tools.md)). Non-native route access is audit-logged.

## Hot-reload & package sources [#hot-reload--package-sources]

Project packages **hot-reload on edit**: a drop or an edit re-applies its
tools, skills and contributions within seconds, with no manual rescan. Every
change (a watcher overflow too) triggers one debounced rescan of all the
project's package directories together, keeping every load guard (packages stay
`untrusted`, reserved ids are rejected, trust never escalates on reload). Only a
package whose manifest or built WASM module changed is reloaded.

A project loads runtime packages from two kinds of directory:

- **`_packages/`** — the default drop-zone, loaded while the project's
  `packages` source is on.
- **Any package folder of a source** — a `host` source can opt
  in by listing folders in `packageFolders` in its source config (relative to its
  root; `''` is the whole source). Each folder is scanned and hot-reloaded like
  `_packages/`, and a saved source change applies without a restart. This is
  **additive** to the source's markdown contributions for
  [source packages](https://docs.neuralisapp.com/package-system/source-packages.md), with a dedup so one
  package never appears twice. Flagging a folder is a code-load surface, so the
  write is owner/admin gated. A user- or agent-scoped source advertises its
  packages to that user or agent alone; per-owner runtime isolation of the code
  is not built yet. A package folder on a **paired device** loads too: files are
  read over the device's link and never copied, its code never runs in the
  server process (a WASM module, at most 1 MB, runs in the sandbox), its skill
  scripts run on the device, and activating a skill needs the device online;
  offline, its packages show as *Not available*.

A source that is switched off loads none of its package folders, `_packages/`
included. The project's package list still shows them, greyed out and without
actions, to a caller who may read that source and the folder's manifest.

When contributions change, connected MCP clients get `tools/list_changed` +
`prompts/list_changed`; the re-list applies the same feature/role gating, so a
notification never widens what a caller sees.