# HarnessServer (/docs/server)



`HarnessServer` is one surface in the **frontend integration**
[thematic island](/docs/concept-clusters#what-lives-outside-the-cluster-pattern) —
siblings of [react](/docs/react), [api-routes](/docs/api-routes),
[query](/docs/query), and [devtools](/docs/devtools). Wiring
surfaces, not concept triplets.

`HarnessServer` is a set of pure request-to-response handlers that
wrap a `SessionRuntime`. It does not bind a port. Each handler
mounts into whatever HTTP framework already owns your transport —
Next.js route segments, Express middleware, Hono routes, raw
`node:http`.

<Callout type="info">
  Most consumers don't touch `HarnessServer` directly. To mount the
  whole hosted-agent route family from an exported subpath, use
  [`createPleachRoutes`](#the-whole-family-createpleachroutes) or the
  higher-level [`createPleachAgent`](#the-standalone-agent-createpleachagent)
  façade — both from `@pleach/core/quickstart`. The `HarnessServer` +
  `ROUTES` handler set described further down is the substrate those
  factories run on. It isn't a public import; mount it through the
  route factories, which hand you `fetch`, Next.js, and `node:http`
  shapes for any framework.
</Callout>

## The whole family: `createPleachRoutes` [#the-whole-family-createpleachroutes]

`createPleachRoutes` mounts every route the runtime speaks — sessions
CRUD, execute+SSE, interrupts, checkpoints, rollback, events-recall,
sync, and fork — behind one dispatcher. It comes from the exported
`@pleach/core/quickstart` subpath.

```typescript
// app/api/harness/[...path]/route.ts (Next.js)
import { createPleachRoutes } from "@pleach/core/quickstart";

const routes = createPleachRoutes({ basePath: "/api/harness" });
export const { GET, POST, PUT, DELETE } = routes.nextRouteHandlers();
```

`basePath` is stripped from the request path before the dispatcher
matches a route. It defaults to `""`, which suits a handler that sees
paths like `/sessions/:id` directly; a Next.js catch-all sees the full
URL, so set it to the segment's mount path.

The factory returns three mount shapes off one shared storage /
checkpointer / event-store:

| Method                       | Returns                                                      |
| ---------------------------- | ------------------------------------------------------------ |
| `routes.fetch(req)`          | A Web-standard `(Request) => Promise<Response>` handler      |
| `routes.nextRouteHandlers()` | `{ GET, POST, PUT, DELETE }` for a Next.js catch-all segment |
| `routes.nodeHttp()`          | A `(req, res)` handler for `node:http` / Express             |

The execute leg is delegated to
[`createPleachRoute`](/docs/api-routes) unmodified, so streaming,
provider detection, and the error contract match the single-POST
handler exactly.

### Opting out of legs [#opting-out-of-legs]

Pass `routes: { <leg>: false }` to omit a leg — for example if fork
and rollback aren't part of your product surface:

```typescript
const routes = createPleachRoutes({
  routes: { fork: false, rollback: false },
});
```

### Supplying a durable interrupt resolver [#supplying-a-durable-interrupt-resolver]

The default interrupt resolver binds the session's live runtime: the
runtime of its latest turn in this process, kept while that turn runs.
Its in-process `InterruptManager` isn't rehydrated from storage. A
resolve that reaches a process with no live runtime for the session
(another instance, a restart, or an eviction) answers
`409 {"error":"no_live_runtime"}`. The default is correct only when the
pause and the resolve reach the same process while the turn is live.
See [Live runtimes per session](/docs/api-routes#live-runtimes-per-session).

A durable, multi-request deployment supplies its own resolver via
`capabilities.interruptResolver`, backed by a store the resolve path
can consult:

```typescript
const routes = createPleachRoutes({
  capabilities: {
    interruptResolver: myDurableInterruptResolver, // a DurableInterruptResolver
  },
});
```

`capabilities.interruptResolver` overrides the live-runtime default
binding. Its `resolve` receives the `sessionId`, so it can key a
cross-request store by `(sessionId, interruptId)`.

`events` reads through the shared store and works across requests
without an override. `sync` and `fork` on a session with no live
runtime rebuild a short-lived runtime from the stored session (see
[Sync and fork without a live runtime](/docs/api-routes#sync-and-fork-without-a-live-runtime)).

### The approval authority (on by default) [#the-approval-authority-on-by-default]

<Callout type="warn" title="Breaking: approvals need a principal and a nonce">
  `createPleachRoutes` and `createPleachAgent` build an approval
  authority unless you pass `approvalAuthority: false`. A paused call is
  answered only by the turn's principal (your `resolveUserId` user),
  presenting the `approvalNonce` from the turn's own
  `interrupt.requested` frame. Without your own `resolveUserId`, every
  turn is headless and its `interruptBefore` tools are refused.
</Callout>

One authority serves both legs, so the nonce the execute stream
carries is the one the resolve must present. The family picks it in
this order:

1. `approvalAuthority: false`: none. A resolve is decided by the
   resolver alone and reaches a host `interruptResolver` marked
   `approvalAuthority: "opted-out"`.
2. Your own `approvalAuthority` (from `createApprovalAuthority`).
3. The authority that guards `capabilities.interruptResolver`, when
   you built it with `authority.guardResolver(resolver)`
   (`guardingAuthorityOf(resolver)` returns it).
4. Otherwise a default one, built here.

The rules for nonces, headless turns and opting out are in
[Interrupts → Who can decide](/docs/interrupts#who-can-decide).

### Approval nonces across a restart [#approval-nonces-across-a-restart]

The default authority keeps unanswered nonces in this process. To
answer one after a restart, give it a store and the approver key:

```typescript
import { createPleachAgent } from "@pleach/core/quickstart";
import { createSqliteDurableStore } from "@pleach/core/store";
import { loadOrCreateApproverKey } from "@pleach/core/audit/permission-ledger";

const db = createSqliteDurableStore("./agent.db");
const agent = createPleachAgent({
  context: { provider: "anthropic" },
  db,
  resolveUserId: (req) => myAuth.userIdFrom(req),
  approvalNonceStore: db.approvalNonces,
  approverKey: () => loadOrCreateApproverKey("./keys"),
});
```

| Option               | On                                        | Rule                                                                                                                                                                                     |
| -------------------- | ----------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `approvalNonceStore` | `createPleachRoutes`, `createPleachAgent` | An `ApprovalNonceStore` for the default authority. Throws at construction beside your own `approvalAuthority`, beside `false`, or beside an `interruptResolver` another authority guards |
| `approverKey`        | `createPleachRoutes`, `createPleachAgent` | Required with `approvalNonceStore`. A key state from `loadOrCreateApproverKey(dir)`, or a loader asked again until it gives a usable key                                                 |

The SQLite store's `approvalNonces` is one such store. With your own
store, `remove` must return exactly `true` or `false`, synchronously:
anything else throws `APPROVAL_NONCE_STORE_REMOVE_UNANSWERED` when the
authority is built. While the approver key is unusable, no nonce is
issued, so each gated call is refused as on a headless turn.

## The standalone agent: `createPleachAgent` [#the-standalone-agent-createpleachagent]

`createPleachAgent` is the three-arm façade over `createPleachRoutes`.
A consumer brings exactly three things — `context` (provider, model,
system prompt, plugins), `tools` (base tools included by default),
and `db` (one durable binding) — and gets the whole route family
back.

```typescript
// app/api/harness/[...path]/route.ts (Next.js)
import { createPleachAgent } from "@pleach/core/quickstart";

const agent = createPleachAgent({
  context: { provider: "anthropic", systemPrompt: "You are a helpful assistant." },
  // tools defaults to the base-tools bundle
  // db omitted → in-memory durable store (recall works, no Supabase)
});

export const { GET, POST, PUT, DELETE } = agent.nextRoutes();
```

The return value carries the same three mount shapes as
`createPleachRoutes` (`fetch`, `nextRoutes()`, `nodeHttp()`) plus
`agent.store` — the resolved `DurableStore` for direct reads.

When `db` is omitted the agent uses
[`createMemoryDurableStore()`](/docs/storage), a zero-dependency
in-memory store. Recall, checkpoints, and the audit ledger all work
with no Supabase — state is lost on process restart, which is the
expected trade for a demo, a test harness, or a single-node dev loop.
Pass a `db` to persist.

The same per-request interrupt-resolver limitation applies. For a
durable multi-request deployment, pass `interruptResolver` to
`createPleachAgent`, which forwards it to the route family.

<Callout type="warn">
  **`@pleach/core/server` is not an exported subpath.** `HarnessServer`,
  `ROUTES`, and `createHarnessServer` are real, but the `./server`
  export key isn't in `@pleach/core`'s `package.json`, so they aren't
  public imports. Two narrower subpaths are exported:
  `@pleach/core/server/turns` (`createPleachTurnRoutes`, the server half
  of a remote turn) and `@pleach/core/client` (`createRemoteTurnSource`,
  the client half). [useRemoteTurn](/docs/use-remote-turn) covers both.
  Everything an external consumer needs to mount the
  route family is exported from `@pleach/core/quickstart`: the two
  factories above. The rest of this page describes the handler set
  those factories run on, so you know what each route does.
</Callout>

`HarnessServer` is the substrate-level handler set, and
`createPleachRoutes` is its exported mount. The route paths and
shapes on [`/docs/api-routes`](/docs/api-routes) are what the
dispatcher serves.



## Configuration [#configuration]

`createPleachRoutes` builds this config for you from its own options.
It's shown here so the route behavior below has a reference point.

```typescript
interface HarnessServerConfig {
  provider:      ServerProvider;       // executes messages, yields stream events
  storage:       ServerStorage;        // session CRUD
  checkpointer?: ServerCheckpointer;   // enables checkpoints + rollback routes
  auth?:         ServerAuthProvider;   // caller identity for the owner gate; surfaces on /health features map
  tools?:        ToolRegistry;         // enables /tools + /tools/:name
  port?:         number;               // informational only
  hostname?:     string;               // informational only
  cors?:         { origins, methods?, headers? };
}
```

`auth.getUserId()` is the fallback caller identity for every
session-scoped handler when a call passes no `userId` of its own. It
must be request-scoped. See
[Direct `HarnessServer` wiring](/docs/api-routes#direct-harnessserver-wiring).

`provider` is the seam the execute routes call into — typically a thin
adapter that calls `runtime.executeMessage(...)` and yields each
stream event. `storage` mirrors the `StorageAdapter` shape but with
loosened types so the server stays decoupled from the full
`SessionState` envelope.

Calling `start()` flips an `isRunning()` flag and nothing else; it's
useful for health-check gating but binds no socket.

### The caller credential on server turns [#the-caller-credential-on-server-turns]

A root turn's tools now see the caller's credential. The orchestrator config's `authToken` and `authTokenProvider` reach the per-turn tool setup, each only when it is set.

A tool that needs the credential gets one answer. A direct `authToken` wins. Otherwise `authTokenProvider` is awaited, which suits a signed-in turn whose token is minted per call. A provider that throws or returns nothing falls back to the API key. Before this change a route-forwarded bearer or a minting provider reached no tool, and tools that gate on the credential answered `no-credential`.

### Tool introspection: `createPluginToolRegistry` [#tool-introspection-createplugintoolregistry]

The `tools?` field wants a registry that answers `/tools` and
`/tools/:name`, not a raw tool array. `createPluginToolRegistry`
adapts a live tool-definition snapshot into that shape.
`createPleachRoutes` wires one for `GET /tools` automatically. The
factory is also exported from `@pleach/core/quickstart` for a host
that answers `/tools` from its own handler.

```typescript
import { createPluginToolRegistry } from "@pleach/core/quickstart";

const tools = createPluginToolRegistry(() => runtime.resolvedTools());
// tools.listTools()      → every tool as a ServerToolDefinition
// tools.getTool(name)    → one tool, or null
```

It takes a getter rather than a fixed array, so `/tools` reflects the
tool set as it stands per request — a plugin that registers a tool
mid-session shows up without rebuilding the registry.

### Auto-binding from a runtime [#auto-binding-from-a-runtime]

`createPleachRoutes` binds the route capabilities from the live runtime
of the session named in the request: `interrupts` to
`runtime.interrupts.resolve`, `sync` to `runtime.sync.execute`, `fork`
to `runtime.timeTravel.api.fork`, and `events` from its shared event
store. It never falls back to another session's runtime. The number of
live runtimes is bounded by `sessionRuntimeCapacity` and
`sessionRuntimePerPrincipal`; see
[Live runtimes per session](/docs/api-routes#live-runtimes-per-session). It does this through an internal
`createHarnessServer`, which isn't a public import.

To replace one of those bindings, pass it under `capabilities`:

```typescript
import { createPleachRoutes } from "@pleach/core/quickstart";

const routes = createPleachRoutes({
  basePath: "/api/harness",
  capabilities: {
    events: myDurableEventReader, // replaces the default in-memory reader
  },
});
```

`capabilities` also accepts `verify`, `attest`, `memory`,
`interrupts`, `interruptResolver`, `sync`, and `timeTravel`.

With `resolveUserId` configured, `memory` is called with
`{ userId }` and must return only that user's memory. A closure that
ignores it hands every caller the same dump. See
[Skills and memory per caller](/docs/api-routes#skills-and-memory-per-caller).

### `createInMemorySharedInterruptResolver` — process-local reference resolver [#createinmemorysharedinterruptresolver--process-local-reference-resolver]

The [durable interrupt resolver](#supplying-a-durable-interrupt-resolver)
above is a seam (`DurableInterruptResolver`) — you supply the store.
`createInMemorySharedInterruptResolver()` is the reference implementation
of that seam for a single-process host: it holds pending interrupts in a
process-shared `Map` keyed by `(sessionId, interruptId)`, so a resolve
issued in a later request finds the interrupt an earlier request registered.
Pass it as `capabilities.interruptResolver` on `createPleachRoutes`, or
as `interruptResolver` on `createPleachAgent`.

```typescript
import {
  createInMemorySharedInterruptResolver,
  createPleachRoutes,
} from "@pleach/core/quickstart";

const interruptResolver = createInMemorySharedInterruptResolver();
const routes = createPleachRoutes({
  basePath: "/api/harness",
  capabilities: { interruptResolver },
});

// From the code that raises the pause, register a callback that hands the
// decision, and the caller who sent it, to the runtime:
interruptResolver.register(sessionId, interruptId, (decision, caller) =>
  runtime.interrupts.resolve(interruptId, decision, sessionId, caller),
);
```

| Method                                               | Purpose                                                                                                                                                     |
| ---------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `register(sessionId, interruptId, onResolve?)`       | Record a pending interrupt; `onResolve` fires when a later `resolve` matches. Idempotent per key.                                                           |
| `resolve(sessionId, interruptId, decision, caller?)` | The `DurableInterruptResolver.resolve` seam. Matches a pending pair, fires its callback with the server's `caller`, and returns a `SharedInterruptReceipt`. |
| `isPending(sessionId, interruptId)`                  | Whether a pending interrupt is registered for the pair.                                                                                                     |
| `pendingCount()`                                     | Count of currently-pending interrupts.                                                                                                                      |
| `unregister(sessionId, interruptId)`                 | Drop a pending interrupt without firing its callback — the reclaim path for an abandoned pause.                                                             |

The decision is `SharedInterruptDecision` (`{ approved, note?, modifiedArguments? }`);
`resolve` returns `SharedInterruptReceipt` (`{ handled, interruptId, resolvedDecision? }`)
where `handled: false` produces the same 404 "not pending" the default binding does.
`SharedInterruptOnResolve` is the callback type
`(decision, caller?) => SharedInterruptOnResolveResult`, possibly async.
`caller` (`SharedInterruptCaller`, `{ actorId? }`) is the authenticated
caller the resolve request presented: pass it on as the fourth argument
of `runtime.interrupts.resolve`, because a gate bound to an actor
settles only for that actor (see
[Interrupts → Who can decide](/docs/interrupts#who-can-decide)). Return
the runtime's receipt or `false` when the callback did not settle the
pause: the registration is then kept for the rightful caller, and the
resolve answers `handled: false`. A callback that throws also keeps the
registration. Any other return counts as settled. A
kept registration may never settle (the gate may have timed out), so
`unregister` it when the pause ends.

This is process-**local**, not durable: the `Map` is heap-only, so it does
not survive a restart and does not share across instances or serverless
invocations that do not share a heap. A truly durable multi-instance host
supplies its own resolver over the same `DurableInterruptResolver` seam,
backed by a store both the pause and the resolve path consult. A host that
observes session teardown should `unregister` abandoned pauses to keep the
shared map from growing unbounded.

## The `ROUTES` constant [#the-routes-constant]

`ROUTES` is the path table the dispatcher matches, relative to
`basePath`. It isn't exported publicly; the table below lists the
paths so a client can target them.

| Constant                | Path                                           | Handler                                                            |
| ----------------------- | ---------------------------------------------- | ------------------------------------------------------------------ |
| `ROUTES.HEALTH`         | `/health`                                      | `handleHealth`                                                     |
| `ROUTES.SESSIONS`       | `/sessions`                                    | `handleCreateSession` / `handleListSessions`                       |
| `ROUTES.SESSION`        | `/sessions/:sessionId`                         | `handleGetSession` / `handleUpdateSession` / `handleDeleteSession` |
| `ROUTES.EXECUTE`        | `/sessions/:sessionId/execute`                 | `handleExecuteMessage` (SSE)                                       |
| `ROUTES.EXECUTE_SYNC`   | `/sessions/:sessionId/execute/sync`            | `handleExecuteMessageSync` (buffered JSON)                         |
| `ROUTES.CONTINUE_TURN`  | `/sessions/:sessionId/turns/:token/continue`   | continue a parked turn                                             |
| `ROUTES.TURN_STREAM`    | `/sessions/:sessionId/turns/:turnId/stream`    | re-attach to a turn's stream                                       |
| `ROUTES.TURN_STOP`      | `/sessions/:sessionId/turns/:turnId/stop`      | stop a turn                                                        |
| `ROUTES.INTERRUPT`      | `/sessions/:sessionId/interrupts/:interruptId` | `handleResolveInterrupt`                                           |
| `ROUTES.CHECKPOINTS`    | `/sessions/:sessionId/checkpoints`             | `handleListCheckpoints`                                            |
| `ROUTES.ROLLBACK`       | `/sessions/:sessionId/rollback`                | `handleRollback`                                                   |
| `ROUTES.FORK`           | `/sessions/:sessionId/fork`                    | `handleFork`                                                       |
| `ROUTES.EVENTS`         | `/sessions/:sessionId/events`                  | session event log                                                  |
| `ROUTES.LINEAGE`        | `/sessions/:sessionId/lineage`                 | session lineage                                                    |
| `ROUTES.VERIFY`         | `/sessions/:sessionId/verify`                  | verify the hash chain                                              |
| `ROUTES.ATTEST`         | `/sessions/:sessionId/attest`                  | attest the chain                                                   |
| `ROUTES.SYNC`           | `/sessions/:sessionId/sync`                    | `handleSync`                                                       |
| `ROUTES.TOOLS`          | `/tools`                                       | `handleListTools`                                                  |
| `ROUTES.TOOL`           | `/tools/:toolName`                             | `handleGetTool`                                                    |
| `ROUTES.INSPECT`        | `/inspect`                                     | runtime inspection                                                 |
| `ROUTES.MEMORY`         | `/memory`                                      | memory capability                                                  |
| `ROUTES.MODELS`         | `/models`                                      | model list                                                         |
| `ROUTES.SKILLS`         | `/skills`                                      | skill list                                                         |
| `ROUTES.SKILL_ACTIVATE` | `/skills/:name/activate`                       | activate a skill                                                   |

### Turn transport: frame ids, re-attach and stop [#turn-transport-frame-ids-re-attach-and-stop]

Every SSE frame on the execute and continue routes carries an `id:` line, the turn's stream ordinal. It starts at 1 and grows by one per frame across every segment of the turn, so a continuation's `turn.continued` frame is the parked segment's last id plus one. `event: done` and refusal bodies carry no id. The ordinal isn't the event log's sequence number.

`GET /sessions/:sessionId/turns/:turnId/stream` (`ROUTES.TURN_STREAM`, `handleReattachTurn`) re-attaches. It replays frames after the `Last-Event-ID` header, or `?after=`, then tails the live turn until it ends or parks. A client keeps frames whose id is above the last one it holds. The route is authorised like execute: the owner gate first, then the turn's actor. It refuses instead of returning a gapped replay:

| Status | Code               | Meaning                                                                     |
| ------ | ------------------ | --------------------------------------------------------------------------- |
| `404`  | `turn-not-held`    | This instance doesn't hold the turn, including one live on another instance |
| `409`  | `cursor-ahead`     | The cursor is past the last frame this server holds                         |
| `409`  | `replay-truncated` | Retention dropped frames after the cursor                                   |
| `400`  | `invalid-cursor`   | The cursor isn't a non-negative integer                                     |

A re-attached client is a reader. Leaving never stops the turn. A client that sends `x-pleach-on-disconnect: detach` keeps its turn running after a hang-up, and the turn stays re-attachable. `turnStreamRetention` bounds the per-instance frame record by turns, frames per turn and settled TTL.

`POST /sessions/:sessionId/turns/:turnId/stop` (`ROUTES.TURN_STOP`, `handleStopTurn`) stops a turn from any client, so a second tab can stop a turn it re-attached to. It's authorised like continue. A hang-up is never a stop.

* **Live on this instance.** The turn aborts with reason `"user"` and the route answers `202 stopping`. The verdict arrives on the stream as `turn.completed { abortedByUser: true }`. A turn opened without a request view answers `409 not-stoppable`.
* **Parked on this instance.** The route cancels it through the provider's optional `cancelParkedTurn` and answers `200 cancelled` with `abortedByUser`. Without that method it answers `501`. A turn another instance parked is cancelled from the client's `turn.parked` token, and a token that names another turn answers `400 token-turn-mismatch`.
* **Held elsewhere.** The optional `turnControl.requestStop` hook, backed by your own bus, answers `202 stop-requested`. Without it, or when delivery fails, the route answers `404 not-here`. The instance that holds the turn applies a bus-delivered stop with `stopHeldTurn`, with the same actor check.

### Durable parked frames [#durable-parked-frames]

By default a parked turn's frame lives in process memory, so only that process can continue it. `SupabaseTurnFrameStore` from `@pleach/core/checkpointing` keeps frames in Postgres, so a turn parked in one request continues in another. Build it with `new SupabaseSaver(...).createTurnFrameStore()`, which shares the saver's client.

Every state change is one database function call, so the claim and each fenced write run under a row lock, and the database clock decides lease expiry. The functions come from a schema your database owner reviews and applies. `checkAvailable()` reports whether they're callable, so you can leave continuation off until they are.

The adapter hashes each frame over its canonical JSON and re-derives the hash on every read. A mismatch, or a body that names another session or turn than the one asked for, throws `TurnFrameIntegrityError`. A frame is stored only with an owner: the turn's actor, or what `resolveOwner` returns. `turnLeaseTtlMs` is validated to between 1 second and 24 hours.

### Turn deadline and the hard end [#turn-deadline-and-the-hard-end]

`PleachTurnDeadline` takes an optional `hardAtMs`, the epoch-millisecond instant by which in-superstep work must settle. Set it to your function's real lifetime less a finalize reserve. The park gate still reads `atMs` only, so `hardAtMs` never changes when a turn parks.

With `hardAtMs` set, `NodeRunConfig.segmentRemainingMs()` returns the time left. Without it the method is absent and nothing is clamped. The synthesizer's converse fallback uses it: it runs for the lesser of 90 seconds and the time left, and skips the call when under 15 seconds remain. The turn then still ends with an answer.

### Settled outcome: `keyFailed` [#settled-outcome-keyfailed]

`PleachTurnSettledOutcome`, the argument to `onTurnSettled`, has an optional `keyFailed: true`. The route sets it when it replaced the turn's `ok` `turn.completed` frame with the key-unavailable error frame. It's set whatever kind the segment then settles as (`completed`, `stopped`, `failed` or `parked`), so a host can keep that message id settled even when the turn was stopped or failed after the replacement. It's absent when no frame was replaced.

`HarnessServer` serves `sync` itself, through `ROUTES.SYNC`. It
answers `501` when no sync engine is wired, and `409` when the sync
reports conflicts.

## Handler signatures [#handler-signatures]

These are the internal handlers the dispatcher calls. They describe
what each route returns; you reach them over HTTP, not by import.
Every handler returns one of two shapes:

```typescript
interface HandlerResponse {
  status:   number;
  body:     unknown;
  headers?: Record<string, string>;
}

interface SSEResponse {
  status:  number;
  headers: Record<string, string>;
  stream:  AsyncIterable<string>;   // already-formatted SSE frames
}
```

`HandlerResponse` is for buffered JSON; `SSEResponse` is the streaming
path. The frame format the server emits is one of:

```
event: <type>
data: <json>

event: done
data: {}
```

`event: done` is yielded at end-of-stream so a client can distinguish
clean close from disconnect without inspecting the underlying socket.

### Session handlers [#session-handlers]

| Handler                                              | Input         | Returns                             |
| ---------------------------------------------------- | ------------- | ----------------------------------- |
| `handleCreateSession({ userId, config? }, request?)` | body          | 201 + seeded `SessionState`, or 400 |
| `handleGetSession({ sessionId }, request?)`          | params        | 200 + state, or 404                 |
| `handleUpdateSession({ sessionId }, body, request?)` | params + body | 200 + state, 400, or 404            |
| `handleListSessions({ userId?, limit? }, request?)`  | query         | 200 + array                         |
| `handleDeleteSession({ sessionId }, request?)`       | params        | 204, or 404                         |

Every session-scoped handler takes an optional last argument,
`request?: { userId?: string }`, the caller for the owner gate. A
gated handler answers `401 {"error":"unauthenticated"}` for no caller
and `404 {"error":"Session not found"}` for a session the caller
doesn't own. See
[Direct `HarnessServer` wiring](/docs/api-routes#direct-harnessserver-wiring).

`handleCreateSession` seeds the envelope (`id`, `version: 1`, empty
arrays for messages / tool calls / jobs / artifacts, default
`provider`, `model` and `tools`). It then applies only the allowed
`config` keys (`title`, `provider`, `model`, `tools`) and refuses any
other key with `400`. The id is always a fresh `crypto.randomUUID()`.
When a caller is resolved, the caller is the owner and `body.userId`
is overridden. `handleUpdateSession` accepts only `title`.

### Execution handlers [#execution-handlers]

| Handler                    | Response                                          |
| -------------------------- | ------------------------------------------------- |
| `handleExecuteMessage`     | SSE stream of events from `provider.execute`      |
| `handleExecuteMessageSync` | Buffered JSON: `{ events, message, toolResults }` |

`handleExecuteMessage(params, body, request?)` takes an optional third
argument — the transport's view of the HTTP request:

```typescript
interface ExecuteRequestContext {
  signal?:  AbortSignal | null;   // aborts when the client disconnects
  headers?: Headers | Record<string, string | string[] | undefined> | null;
  url?:     string | URL | null;
  userId?:  string;               // the caller for the owner gate
}
```

Pass it and a client disconnect aborts the turn, classified by the
intent the client declared in `headers` or `url` (see
[Stopping a streamed turn from the client](/docs/session-runtime#stopping-a-streamed-turn-from-the-client)).
The turn gets a request-scoped `abortSignal`; a caller-supplied
`options.abortSignal` is composed in, not replaced. The disconnect
binding is released when the stream finishes, is cancelled, or the
request aborts, so a close after the turn ends is not a stop. Omit
`request` and nothing changes: no signal is injected.

`handleExecuteMessageSync` drains the provider stream and extracts the
`message.complete` event into `message` and every `tool.completed`
event into `toolResults`.

Through `createPleachRoutes`, neither handler serves the execute leg.
Both `POST /sessions/:id/execute` and `POST /sessions/:id/execute/sync`
go to [`createPleachRoute`](/docs/api-routes), so a non-streaming
client reads that route's stream to the end.

### Checkpoint handlers [#checkpoint-handlers]

Both checkpoint routes return `501` when `checkpointer` is not
configured — the body is `{ error: "Checkpointer not configured" }`,
not a generic 500.

| Handler                                           | Notes                                                                           |
| ------------------------------------------------- | ------------------------------------------------------------------------------- |
| `handleListCheckpoints({ sessionId })`            | Drains the checkpointer's `list` async iterable into an array                   |
| `handleRollback({ sessionId }, { checkpointId })` | Reads the checkpoint, writes `checkpoint.state` back to `storage.updateSession` |

The rollback here is the wire-level operation — it replays the stored
state without the in-process bookkeeping (version-vector bump,
`source: "rollback"` checkpoint write) that
`runtime.checkpoints.rollback` does. If you need that bookkeeping,
mount the Next.js handler or call the runtime method directly behind
your own route.

### Events handler [#events-handler]

`handleQueryEvents(params, query?, request?)` reads the session's
append-only event ledger (the recall surface). Through
`createPleachRoutes` it serves `GET /sessions/:sessionId/events`, and
`query` is read from the query string. It returns `501` with
`{ error: "Event query not configured" }` when no event reader is
bound, and applies the same owner gate as the other session handlers.

| `query` field | Effect                                                                                                 |
| ------------- | ------------------------------------------------------------------------------------------------------ |
| `types`       | Restrict to these event types (a comma-separated list in the query string)                             |
| `limit`       | Maximum rows returned. `0` returns none                                                                |
| `sinceSeq`    | A last-seen sequence-number cursor: return only events with a sequence number strictly greater than it |

Rows come back oldest-first. `sinceSeq` is a cursor, so a client that
resumes from the last sequence number it has seen can ask for what it
missed. Every reader treats it the same way: the boundary row itself
is not returned, only rows strictly after it, so pass the last sequence
number you hold, not the next one you want.

With `sinceSeq`, `limit` keeps the first N rows from the cursor.
Without it, `limit` keeps the newest N, still oldest-first. A
`sinceSeq` or `limit` that is not a non-negative integer returns `400`
with `sinceSeq must be a non-negative integer` or
`limit must be a non-negative integer`.

## Mounting examples [#mounting-examples]

Each example mounts the whole family from `@pleach/core/quickstart`.

### Next.js App Router [#nextjs-app-router]

```typescript
// app/api/harness/[...path]/route.ts
import { createPleachRoutes } from "@pleach/core/quickstart";

const routes = createPleachRoutes({ basePath: "/api/harness" });
export const { GET, POST, PUT, DELETE } = routes.nextRouteHandlers();
```

### Express [#express]

```typescript
import express from "express";
import { createPleachRoutes } from "@pleach/core/quickstart";

const app = express();
// Express strips the mount path from req.url, so leave basePath unset.
const routes = createPleachRoutes();

// Mount before any body-parsing middleware: the handler reads the raw body.
app.use("/api/harness", routes.nodeHttp());
```

`routes.nodeHttp()` pipes the execute stream chunk by chunk, so
streaming works through Express unchanged.

### Hono [#hono]

```typescript
import { Hono } from "hono";
import { createPleachRoutes } from "@pleach/core/quickstart";

const routes = createPleachRoutes({ basePath: "/api/harness" });

const app = new Hono();
app.all("/api/harness/*", (c) => routes.fetch(c.req.raw));
```

The pattern is the same in every framework: hand the request to
`routes.fetch` (Web-standard `Request` → `Response`) or
`routes.nodeHttp()` (`node:http` `req`/`res`), with `basePath` set to
whatever prefix the handler still sees.

## Where to go next [#where-to-go-next]

<Cards>
  <Card title="API routes" href="/docs/api-routes" description="The Next.js reference handlers with the full route catalog and SSE wire format." />

  <Card title="React" href="/docs/react" description="The client-side hooks that consume these handlers over HTTP + SSE." />

  <Card title="Query" href="/docs/query" description="Server-side read API over persisted harness data — pairs with these write-path handlers." />

  <Card title="DevTools" href="/docs/devtools" description="Browser-console surface for inspecting what the server returns." />
</Cards>
