# Sessions and identity (https://docs.neuralisapp.com/package-system/sessions)

Neuralis carries caller identity in exactly one shape. Whether a request
arrives from the web UI, a cross-package API call, a background job, or a
skill script calling back into the host, the receiving code sees the same
session vocabulary — and every new boundary reuses it instead of declaring a
parallel "caller" type that restates the same fields.

## `SessionContext` — the canonical identity [#sessioncontext--the-canonical-identity]

`SessionContext` (from `@neuralis/package-system/contracts`) is the shape
route handlers and tool handlers receive on every request:

```ts
type SessionContext = {
  userId: string;
  projectId: string;
  agentId?: string;
  conversationId?: string;
  requestId?: string;
  toolUseId?: string;          // model-initiated tool calls only
  delegateRunId?: string;      // a subagent child's own tool calls
  delegateMode?: 'foreground' | 'background';
  role?: string;               // a label, never an authority source
  priority?: number;           // lower = stronger; undefined ⇒ system session
  rolePriorities?: Record<string, number>; // the project's role → priority map
  grantedFeatures?: string[];  // ['*'] = all features
  spendLimits?: { /* projectTotal, byRole, byUser, byAgent */ };
  llmRateLimitRpm?: number | null;
  agentAccess?: '*' | 'own' | 'view';
  agentOwnership?: Record<string, { createdBy: string; assignedTo: string[] }>;
  displayName?: string;        // for showing only
};
```

The fields that carry authorization are `priority`, `grantedFeatures`, and
`agentAccess` — they feed the shared predicates described in
[Features and access](https://docs.neuralisapp.com/package-system/features.md). `role` is a
cosmetic **label**, never an authority source: no gate reads the string, so a
custom role named anything behaves exactly as its declared priority and grants
say it should. A role name still selects behaviour in exactly two places of a
[URI policy](https://docs.neuralisapp.com/package-system/uri-policies.md): the `byRole` axis, and a project's
own stored path rules that name its roles (a manifest names a subject by
strength, `priority`).
Session context is **never** sourced from tool input: every `SessionContext`
field name (plus the bundled `session`) is rejected as a **top-level** input
property of a tool schema. The ban is root-only by design — nested occurrences
are legitimate domain fields, and identity is always read from the verified
session, never from arguments (see [Tools](https://docs.neuralisapp.com/package-system/tools.md)).

## `CrossPackageSession` — package-to-package calls [#crosspackagesession--package-to-package-calls]

A `getPackageApi()` call made on behalf of a user or agent carries a
`CrossPackageSession`; the call is then trust-gated against `callerTrust` and
audited. A call without one is direct in-process access, reachable only between
the host's built-in native packages, so it carries no more authority than the
caller already holds; it is not an external boundary (that gate sits at the
HTTP and MCP edge).

| Field | Purpose |
| --- | --- |
| `userId`, `projectId` | The scope the call operates in |
| `agentId?` | Agent context, when the call is agent-scoped |
| `callerId` | The calling package's id — for auditing and target-side policy |
| `callerTrust` | `'native' \| 'trusted' \| 'untrusted'` |
| `grantedFeatures?` | Caller's grants, for target-side feature checks |

## System sessions and sentinel identities [#system-sessions-and-sentinel-identities]

Native background work runs under a `SystemSession`: a
`CrossPackageSession` extended with `isSystem: true` and a `systemReason`. The
reason is a closed set of exactly three values — `sync-scheduler`,
`mcp-api-key`, and `bootstrap` — so the envelope can never be opened for an
unnamed purpose. It is a **permission envelope, not an identity**: only
native packages may construct one, via
`createSystemSession(reason, callerId, scope?)`.

When the work targets a real project, the session carries the real
`userId`/`projectId`. When there is no project context at all, the fields hold
the sentinel constant `'__system__'` (`SYSTEM_USER_ID`, `SYSTEM_PROJECT_ID`,
`SYSTEM_AGENT_ID`). Sentinels are process-internal only and must never be
persisted or accepted from outside:

- Stores and path resolvers refuse to create files under a sentinel id.
- Every session built from external input (HTTP headers, MCP bearer tokens,
  cookies) passes through `assertNotSentinel()`, which throws a structured
  `SentinelIdentityError` when any identity field carries a sentinel.
- The external MCP boundary rejects sentinel-identity claims before dispatch.

A fourth synthetic constant, `SKILL_USER_ID` (`'__skill__'`), is the audit
principal of a skill-originated call whose real user is not yet resolved. It is
an audit label, not a scope, so it is deliberately outside the sentinel set and
carries its own refusal: a skill cannot mint a ticket from it.

User work never borrows system identity.

## The per-stream session ticket [#the-per-stream-session-ticket]

Skill scripts run as child shell processes, yet their calls back into the
host's `/api/packages/*` routes must carry the **real** user identity — not a
service account. The session ticket is the single mechanism for this:

```text
nrs1.<requestId>.<secret>
```

1. **Mint.** At every skill activation, the agent runtime mints a ticket from
   the stream's live `SessionContext` (`SessionTokenMinter.mint(session)`).
   The secret is a 32-byte random value pinned to the stream's scope; minting
   refuses sentinel and synthetic identities.
2. **Inject.** The ticket is projected into the script's environment as
   `NEURALIS_SESSION_TOKEN`. The model never reads the value — it travels
   through the credential pipeline like any other secret.
3. **Verify.** The host's package route catch-all recognises the `nrs1.`
   prefix, looks up the live stream scope by `requestId`, and compares the
   secret in constant time. There is no signing key: the route handler and the
   stream orchestration share one process, so an opaque lookup is both
   simpler and instantly revocable.
4. **Rebuild.** Verification yields the original `SessionContext`. The route
   derives `projectId` and `agentId` from it — never from caller-supplied
   parameters — and the package route dispatcher gates the request on the
   caller's real role and granted features, deny-by-default.

Ticket lifetime equals stream lifetime: when the stream ends and its scope is
deleted, every ticket bound to it becomes invalid. Parallel calls within one
stream are first-class (no single-use limitation), and the ticket is
**re-minted on every shell call**, so multi-turn skill workflows keep a valid
ticket across turns. Each verified call is audited as a skill session call.

<Callout type="warn" title="One identity path">
There is no platform-bearer or synthetic-owner shortcut for skills: every
skill-to-route call carries the session ticket with the real session, and
routes gate on that real role and feature set. Never accept identity fields
from a request body as a substitute.
</Callout>

## Where sessions come from [#where-sessions-come-from]

Host [routes](https://docs.neuralisapp.com/package-system/routes.md) build the session from the authenticated
caller and project membership; [tool calls](https://docs.neuralisapp.com/package-system/lifecycle.md) receive
it in the tool-call context; [skill scripts](https://docs.neuralisapp.com/package-system/skills.md) use the
ticket above; [tests](https://docs.neuralisapp.com/package-system/testing.md) build one with
`createMockSession`, `createDeniedSession` and the other factories.