Skip to Content
@package-system

Routes

Declaring HTTP route handlers with patterns and feature gates.

A package serves its own API under /api/packages/<package-id>/.... Route handlers are file-based: each file in src/routes/ (compiled to dist/src/routes/*.js for native node packages) exports a URL pattern, an optional feature gate, and named HTTP method handlers. The host's route dispatcher does the matching, gating, rate limiting, and error wrapping — the handler only contains domain logic.

import type { RouteHandler } from '@neuralis/package-system';

export const pattern = 'items';
export const feature = 'my-pkg.read';

export const GET: RouteHandler = async (req, state) => {
  const items = await state.store.list(req.session.projectId);
  return { status: 200, body: { items } };
};

export const POST: RouteHandler = async (req, state) => {
  const item = await state.store.create(req.body, req.session);
  return { status: 201, body: item };
};

A route file may export GET, POST, PUT, PATCH, DELETE, and an optional default export as a catch-all handler. state is the object the package's lifecycle init returned (see Lifecycle). WASM project packages author the same per-file route files; the build records each route's pattern and feature in dist/routes.json and the host runs the SAME feature gate before entering the sandbox — so a WASM route's feature is enforced exactly like a node route's. See WASM build.

Routes are the platform's common calling surface, and every caller class passes the same gate stack: the browser UI and widgets (HTTP with the cookie session), skill scripts (neuralis request with the session ticket), the Neuralis CLI on a person's own machine (an OAuth bearer for the <app origin>/api resource), external MCP clients, and — in-process — a trusted WASM package's ctx.callRoute, which dispatches with the current caller's real session. The host tries the cookie, then a session ticket, then an OAuth bearer; a ticket that is present but invalid is refused outright, never passed on to the next arm. The OAuth arm applies the same account checks as the cookie arm (an active account, no pending password change, live membership) and pins the token's project and agent.

req.interactive is a host-derived transport marker, not identity: true only for a browser cookie session, absent for ticketed, CLI, WASM and in-process callers, never forgeable from a body. A route may let an interactive human commit immediately while the identical agent call stays governed (pending_review); read it as strict === true.

Pattern matching

Patterns are segment-based, support :param placeholders, and may end in a * wildcard. The dispatcher tries longer patterns first, so a specific route always beats a wildcard.

PatternMatchesResult
items/api/packages/my-pkg/itemsreq.path rest is []
items/:id/api/packages/my-pkg/items/123req.query.id === '123'
items/*/api/packages/my-pkg/items/a/breq.path rest is ['a', 'b']

Matched :param captures are merged into req.query; the remaining segments after the pattern arrive as req.path.

The feature gate runs before the handler

The feature export is enforced by the dispatcher before the handler is invoked: a caller whose granted features do not include the declared feature (or the '*' wildcard) gets a 403 with Forbidden: missing feature '<id>', and the handler never runs. There is no manual check to forget. Feature ids come from package manifests' requires.providesFeatures; grants resolve from the caller's role — see Features and access.

The export is optional, and that is the one thing to be deliberate about: a route module that declares no feature is dispatched ungated — the dispatcher calls the gate only when the export is present, so the caller's authenticated identity and project membership are all that stand in front of the handler. Declare a feature on every route that reads or writes anything, and treat an omitted one as a decision rather than a default.

Identity is session-derived, never caller-supplied

Every request carries req.session — the canonical session context (userId, projectId, optional agentId, role, grantedFeatures, and related scope fields) built by the host from the caller's verified authentication: the logged-in web session, a verified per-stream skill ticket, or an authenticated MCP identity. Handlers must scope every read and write to it.

Route input never restates identity. A body or query field naming a userId or projectId is not trusted and should not exist — the same rule that bans session-context keys from tool schemas. See Sessions for the session shapes.

Responses and errors

A handler returns { status, body?, headers? }. The dispatcher never lets an exception escape:

ConditionResponse
No pattern matched404 with a safe error message
Method not exported (and no default handler)405 with an Allow header
Trust-tier rate limit exceeded429 (trusted: 300/min, untrusted: 30/min; native unlimited)
Handler threw an object with a status field, status < 500That status, with the error message
Handler threw anything else, or a status >= 500500, body { error: 'Internal server error' } — the real message goes to the server log. A host-run package's response also carries an errorId to quote; a WASM-sandboxed one does not, because a guest has no operator-readable log to correlate against

Throwing Object.assign(new Error('Not found'), { status: 404 }) from inside a handler is the idiomatic way to short-circuit with a clean client error.

Redaction is keyed on the resulting status, not on how the error was thrown: a 4xx message reaches the caller unchanged, a 5xx message never does (attaching status: 500 does not opt it out).

Every dispatch writes ONE structured line to the host's route log (app/logs/routes.jsonl): pattern, method, status, duration, the verified caller and, on a refusal, which gate refused. It never contains a request path (a no-match line carries a segment count). The level follows the status and defaults to warn, so a stock deployment records refusals, faults and slow requests (slow: true). Non-native route access is also audit-logged with the package, trust tier, path, method and caller scope.

Typed cross-package API

A route is the API for callers OUTSIDE the package process: the browser, skill scripts, the CLI, external clients. Another native package in the same process calls the provider's typed API instead, never its HTTP route and never internal MCP. A provider publishes the object as the api its lifecycle init returns; a consumer resolves it by package id:

import type { AgentCoreApi } from '@neuralis/agent-core';

const api = ctx.packages.getPackageApi<AgentCoreApi>('@neuralis/agent-core', session);

Pass the session whenever the call is made on behalf of a user or agent: the call is then trust-gated against the caller and audited, and the provider scopes it and re-checks access against that real session, so the adapter adds no authority. T is the provider's own published type wherever a dependency edge exists, so tsc checks the call. Where the edge must not exist (a cycle, a generic host), declare a small structural shape in ONE module the tests use too, and pin it with assertApiMirror (Testing → Cross-package mirror drift): an unpinned shape drifts silently, a renamed member reading undefined. Internal MCP callTool between packages is forbidden; the tool surface is for the model and external clients.

ProviderWhat consumers use it for
@neuralis/agent-coreagents, usage summaries, active streams, MCP server and connector status — see agent-core routes
@neuralis/brain-corethe per-project filesystem service and connector registry; the shell source roots (every folder source with its plane and stored permissions, not access-filtered — the consumer evaluates the policy against its own session); the access-filtered runtime source summaries the <runtime_stack> source table reads once per stream; the package-source roots the host activates source packages from; one filesystem-event subscription that authorizes each agent id deny-by-default; and upsertSourceConfig, the single validated cross-package source-config write, with the same edit gates as the sources PATCH route — see brain-core routes
@neuralis/machine-corethe stream companion mounts, managed containers on the shared network, session and driver accessors — see machine-core routes

The returned AgentCoreApi exposes, among others:

MemberWhat it gives the caller
agentStore / agentServiceRead and manage agents.
usageStoreToken and cost usage events and summaries.
verifyAgentAccess(userId, projectId, agentId)Ownership/access check for an agent.
getActiveStreams()Snapshot of currently-running agentic streams.
listMcpServers(session) / listConnectorInstances()Dashboard-grade MCP/connector signal for the session.

The host verifies skill session tickets through the required session-ticket-verifier service registered at init. It returns the real live-stream session; the verifier is separate from the public AgentCoreApi.

agent-core consumes brain-core's filesystem API the exact same way — typed, through getPackageApi(), importing nothing across the boundary.

@neuralis/admin publishes no typed API of its own: it consumes the two above. A WASM-sandboxed package has no getPackageApi(); its outbound channel is ctx.callRoute (see WASM build).

Testing without HTTP

Routes are plain functions over plain data, so they test without a server: construct a dispatcher from the route modules and dispatch a mock request.

import { RouteDispatcher } from '@neuralis/package-system';
import { createMockRouteRequest } from '@neuralis/package-system/testing';
import * as items from '../src/routes/items';

const dispatcher = new RouteDispatcher([
  { filename: 'items', pattern: items.pattern, feature: items.feature,
    handlers: { GET: items.GET, POST: items.POST } },
]);

const res = await dispatcher.dispatch(
  createMockRouteRequest({ method: 'GET', path: ['items'] }),
  state,
);

Cover the failure paths: a caller without the feature gets 403, a non-member sees no cross-project data, an unknown path stays 404. Helpers: Testing.

On this page