API routes
The HTTP + SSE wire contract — the routes any runtime client speaks, with request/response shapes for the core session routes.
API routes are one surface in the frontend integration thematic island — siblings of react, server, query, and devtools.
The routes below are the canonical HTTP + SSE wire protocol
that runtime clients speak. GET /doc serves the full route contract as OpenAPI 3.1. The Next.js handlers in @pleach/core
are the reference implementation, but the shapes are
language-agnostic — an independent native client consumes them in
production, which is what keeps the wire honest.
Mount the routes under /api/harness/* (the path prefix is
convention, not contract — re-mount wherever you like; the
relative shapes are what matters).
Two exported factories from @pleach/core/quickstart mount these
routes. createPleachRoute is a Web-standard POST handler for the
execute leg alone; createPleachRoutes mounts the whole family
behind one dispatcher. Both come from the same exported subpath.
// app/api/harness/sessions/[id]/execute/route.ts (Next.js)
import { createPleachRoute } from "@pleach/core/quickstart";
// Provider auto-detected from the environment; pass
// { provider, plugins, tools, storage } to override.
export const POST = createPleachRoute();To mount every route below — sessions CRUD, execute+SSE, interrupts,
checkpoints, rollback, events-recall, sync, and fork — from one
catch-all segment, use createPleachRoutes:
// 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 the prefix the dispatcher strips before matching a
route; a Next.js catch-all sees the full URL, so set it to the mount
path.
createPleachRoutes shares one storage / checkpointer / event-store
across the family and delegates the execute leg to createPleachRoute
unmodified. See Standalone agent
for the higher-level createPleachAgent({ context, tools, db })
façade over the same surface.
The lower-level HarnessServer + ROUTES handler set described on
Server isn't a public import: the
@pleach/core/server subpath isn't exported (its
@pleach/core/server/turns and @pleach/core/client subpaths are, for
remote turns). createPleachRoutes
mounts the same family from @pleach/core/quickstart, and its
fetch and nodeHttp() shapes cover frameworks without a dedicated
adapter.
Route catalog
| Route | Method | Purpose |
|---|---|---|
/api/harness/health | GET | Liveness probe with a feature map |
/api/harness/sessions | GET | List sessions for the authenticated user |
/api/harness/sessions | POST | Create a new session |
/api/harness/sessions/[id] | GET | Retrieve session state |
/api/harness/sessions/[id] | PUT | Rename a session (title only) |
/api/harness/sessions/[id] | DELETE | Delete a session |
/api/harness/sessions/[id]/sync | POST | Version-vector sync (conflict detection) |
/api/harness/sessions/[id]/execute | POST | Execute a message (SSE streaming response) |
These are the core session routes. HarnessServer matches more paths
(relative to its basePath): /sessions/:sessionId/execute/sync,
/turns/:token/continue, /turns/:turnId/stream, /turns/:turnId/stop,
/interrupts/:interruptId, /checkpoints, /rollback, /fork,
/events, /lineage, /verify, /attest, and /sync, plus the
session-independent /tools, /tools/:toolName, /inspect, /memory,
/models, /skills and /skills/:name/activate. Which legs a host
mounts depends on the capabilities it wires. The
HarnessServer page lists each path.
Session ownership
When the host configures resolveUserId, every
/sessions route acts for the authenticated user:
POST /sessionscreates a session owned by that user.userIdand owner fields in the body are ignored.GET /sessionslists only your sessions.?userId=is ignored, andlimitcounts your sessions.GET,PUTandDELETE /sessions/:id, and every/sessions/:id/*route (checkpoints, events, lineage, verify, attest, rollback, sync, fork, interrupts), answer404 {"error":"Session not found"}for a session you don't own, the same as for an id that doesn't exist.POST /sessions/:id/executenever resumes another user's session.POST /sessions/:id/forkstamps the new session with the caller as its owner, not the source session's owner. This is visible when your gate admits callers other than the owner (admins, shared readers): their forks belong to them.- A client can't write the owner stamp through
config.extensions. - A request with no authenticated user gets
401 {"error":"unauthenticated"}. - The resolved user is the turn's actor. Every approval a turn raises
is bound to it, and
POST /sessions/:id/interrupts/:interruptIdsettles a gate only for that same user. Another user's resolve answers404, like an interrupt that is not pending. See Interrupts § Who can decide. - With the approval authority on (the default), the resolve must also
present the
approvalNoncefrom the turn's owninterrupt.requestedframe, in its JSON body besideapproved. A missing or wrong nonce answers the same404.
Without resolveUserId (single-user local or sidecar), sessions are
not owner-scoped, and with the approval authority on every turn is
headless: its gated tool calls are refused at once. Pass
approvalAuthority: false to let a resolve answer them without a
nonce (see
Who can decide).
Direct HarnessServer wiring
Hosts that build a HarnessServer themselves (see
HarnessServer) get the same gate on every
session-scoped handler: execute, execute-sync, interrupts,
checkpoints, rollback, sync, fork, events, lineage, and
get, update, delete, list, verify and attest. Each handler resolves
its caller in this order:
- The per-call
userId, passed in the handler's request context. - Otherwise
auth.getUserId()from the server config. A null or empty result means unauthenticated and gets401. - Otherwise there is no gate, which is the behavior before this release.
A session not stamped to the caller answers exactly like a missing
one (404), and the handler's work never runs. A refused execute
returns its status with Content-Type: application/json and a stream
that yields the JSON error once; the provider isn't called.
- A host that already set
authnow gates. A legacy session with no owner stamp answers404to every caller until you stamp it. getUserId()must name the current request's caller. UseAsyncLocalStorageor one server per request. A multi-user host should passuserIdper call: a mutable global races between concurrent users.- Direct execute on an unknown or foreign id returns
404when gated. ThecreatePleachRoutesexecute route keeps first-touch create instead: an unknown or foreign path id starts a fresh session owned by the caller.
Breaking for hosts that configure `resolveUserId`
A session is yours when the server stamped you as its owner. Sessions
created before this release carry no stamp, so once a resolver is
configured they answer 404 for every user and can't be resumed, and
a stamped session with an empty userId is missing from
GET /sessions. Backfill both fields in your store:
extensions["pleach.ownerUserId"] and userId, each set to the
owner's id.
Live runtimes per session
createPleachRoutes keeps one live runtime per session: the runtime
of the session's latest turn in this process. Interrupts, sync, fork,
and the ?sessionId= forms of GET /tools and GET /inspect act on
the runtime of the session named in their own request, never another
session's.
The map is bounded by two options:
| Option | Default | Bounds |
|---|---|---|
sessionRuntimeCapacity | 64 | Live runtimes in this process, across every principal |
sessionRuntimePerPrincipal | 16 | Live runtimes one principal may hold |
A principal is the resolveUserId user. Every session with no resolved
user shares one bucket. When a principal goes over its sub-cap,
admitting another turn evicts that principal's own least-recently-used
idle session first. It never evicts another principal's session, one
with a running turn, or the one just admitted. sessionRuntimeCapacity
still bounds the total after that pass.
const routes = createPleachRoutes({
basePath: "/api/harness",
sessionRuntimeCapacity: 64,
sessionRuntimePerPrincipal: 64, // restore the earlier single-user ceiling
});A single-user host now keeps at most 16 idle live runtimes
All of a single-user host's sessions belong to one principal: the
shared bucket without resolveUserId, or createPleachAgent's one
local identity. The 16 sub-cap binds before the 64 total. Raise
sessionRuntimePerPrincipal to keep 64. A session with a pending
approval has a running turn, so it is never evicted.
Sync and fork without a live runtime
POST /sessions/:id/sync and POST /sessions/:id/fork on a session
with no live runtime here (evicted, never run in this process, or
after a restart) run on a short-lived runtime built for the caller
from the session's stored state.
- The build goes through the execute leg's own request path: the same
provider resolution,
resolveUserId/resolveTenantIdidentity, plugins, storage, checkpointer and event writer as a turn, and the same owner gate. Another user's session still answers404. - It runs no turn and composes no prompt. It isn't recorded as the session's live runtime, and it is released when its request ends.
- Each principal may have at most 4 of these runtimes in flight. Every
unresolved caller shares one budget. A fifth leg answers
429 {"error":"too_many_session_rebuilds"}withretry-after: 1. - It needs stored state.
createPleachRoutesalways shares one storage and one checkpointer, so after an eviction this works in-process even with the memory defaults. After a restart it works whenstorageandcheckpointerare durable. - A session with no stored row still answers
409 {"error":"no_live_runtime"}. So does a route that can't build a runtime: no provider resolved. Acapabilities.syncorcapabilities.timeTraveloverride is used as before and needs no live runtime.
Resolvers on a rebuilt sync or fork. resolveUserId runs more than
once for one such request (the owner gate, then the build), and
resolveTenantId runs once for the build. Both must be deterministic
for one request and must not read the request body, which has been
consumed by then. The rebuilt runtime takes the caller's current
resolveTenantId tenant, not the tenant the session was created
under, exactly as a turn that resumes a session does.
Interrupts and session-scoped reads need the live runtime
Resolving an interrupt needs the live runtime that holds it. A session
with no live runtime in this process answers
409 {"error":"no_live_runtime"} on POST /sessions/:id/interrupts/:iid,
and so do GET /tools?sessionId=<id> and GET /inspect?sessionId=<id>.
Without ?sessionId=, /tools and /inspect serve the configured
catalog, which needs no runtime.
The 409 is per process. A runtime lives only in the instance that ran
the turn, so multi-instance and serverless hosts supply
capabilities.interruptResolver to resolve from another instance (see
Supplying a durable interrupt resolver).
Breaking for hosts that keep a runtime
The routes release every runtime they let go: the short-lived sync or
fork runtime, an evicted session's runtime, and a superseded runtime
once its turn ends. Releasing calls
SessionRuntime.releaseProcessRegistrations() (experimental). It
writes no session.ended row and aborts nothing. A released runtime
runs no turn: executeMessage, resumeStream and resume throw
SessionRuntimeReleasedError (code: "session_runtime_released") on
the first pull. A host that keeps a runtime it got from onRuntime or
onTurnAdmitted and runs another turn on it after the routes released
it gets this error. Build a new runtime instead.
onTurnAdmitted also receives userId?: string: the non-empty user
resolveUserId resolved for the request, else undefined.
Running each turn inside your own frame (wrapTurn)
wrapTurn runs each admitted turn's body inside a frame you open, such as
an AsyncLocalStorage.run or a span, so every await of the turn sees it.
It runs after onTurnAdmitted and gets the same turn object.
import { AsyncLocalStorage } from "node:async_hooks";
import { createPleachRoute } from "@pleach/core/quickstart";
const turnScope = new AsyncLocalStorage<{ userId?: string }>();
export const POST = createPleachRoute({
wrapTurn: (turn, run) => turnScope.run({ userId: turn.userId }, run),
});runstarts the body at most once. A second or late call rejects withWrapTurnRerunError(codePLEACH_WRAP_TURN_RERUN) and runs nothing.- Once
runis called, the body's own result or error is the turn's. - A hook that throws before calling
rungets the body run once outside it. - A hook that resolves without calling
runends the turn with anerrorevent (codePLEACH_WRAP_TURN_NOT_RUN). onTurnAdmitted's release still runs once on every path. Without the hook, a turn runs as before.
A route takes one hook, so compose several wrappers yourself. A host that
loads the package at run time checks ROUTE_WRAP_TURN_CAPABILITY first,
because an older build ignores the option. The hook's type is
WrapTurnHook<PleachAdmittedTurn>.
Skills and memory per caller
With resolveUserId configured, GET /skills,
POST /skills/:name/activate and GET /memory act for the calling
user.
GET /skillscallsskillLoader.loadAll(orgId, <caller>). It lists the builtins, the org's skills and the caller's own, never another user's. With no skill source wired it still answers200 [].POST /skills/:name/activatewrites[skillOwner.orgId || "default", <caller>, "skills"]. A caller can adopt only their own skills; another user's skill answers404. With noskillStoreit still answers501.GET /memorycalls thememorycapability with{ userId }.createPleachAgentwithresolveUserIdand a durabledb.memorywires this route, and its dump holds only the caller's namespaces.- A request with no caller, or a caller id that can't key user storage
(
anonymousin any case, a reserved__id, or anything that isn't one namespace component), is refused401. This set is stricter than the session routes', which refuse only an empty caller, because these routes key user storage by the caller id.
Without resolveUserId nothing changes: activation writes
skillOwner, the listing is loadAll(), and GET /memory dumps the
whole store.
Set skillOwner.orgId to the runtime's organizationId. A turn's
create_skill writes under [organizationId, <caller>, "skills"]. If
skillOwner.orgId differs, the skills routes neither list nor activate
the skills the agent created. An unset or empty orgId falls back to
"default", exported as DEFAULT_IDENTITY_ORG from
@pleach/core/quickstart. createPleachAgent sets both to that
constant.
import { createPleachRoutes } from "@pleach/core/quickstart";
const routes = createPleachRoutes({
basePath: "/api/harness",
resolveUserId: (req) => myAuth.userIdFrom(req), // your auth; deterministic, no body read
skillLoader,
skillStore,
// orgId must equal the runtime's organizationId ("default" = DEFAULT_IDENTITY_ORG).
// userId is used only without a resolver.
skillOwner: { orgId: "default", userId: "" },
capabilities: {
// Takes the caller ctx and returns only that user's memory.
memory: async (ctx) => myMemoryDump(ctx?.userId),
},
});Action required for custom memory and skills closures
On a host with a user resolver, a custom capabilities.memory closure
must return only ctx.userId's memory. The route can't check the
answer, so a closure that ignores ctx gives every caller the same
dump. The same holds for the memory, skills and activateSkill
capabilities of a HarnessServer with an auth provider or a
per-call userId. The server warns once per capability when a closure
declares no parameter for the caller (memory or skills with zero
parameters, activateSkill with fewer than two). The call still
proceeds.
Moving a single-user agent to multi-user on the same durable store.
The single-user data lives under the local identity
["default", <PLEACH_USER or the OS login name>, …]. A host user id
equal to that name would inherit it. Prefix or hash host ids (for
example u_<id>), or migrate or clear those namespaces before
switching.
A malformed POST /skills/:name/activate name (a bad percent-escape)
returns 400 {"error":"bad_request"}, not 500.
GET /api/harness/health
Liveness probe. It always answers 200, never checks a dependency,
and is cheap enough for a load balancer.
Response 200
{
"status": "ok",
"running": true,
"timestamp": "2026-11-16T12:00:00.000Z",
"features": {
"checkpointer": true,
"auth": false,
"tools": true
}
}running is whether the server has started. Each features flag says
whether that capability is wired. The route runs no component probe and
has no 503 case.
GET /api/harness/sessions
List sessions owned by the authenticated user. With resolveUserId
configured, a ?userId= param is ignored and limit counts only your
sessions (see Session ownership).
Query params
| Param | Type | Purpose |
|---|---|---|
userId | string | Filter by owner. Ignored when a user resolver is configured |
limit | number | Cap on returned sessions. No default cap, no maximum |
The route has no cursor and no archive filter.
Response 200 — a bare array of session summaries.
[
{ "id": "018f...", "createdAt": "...", "lastActiveAt": "...", "title": "..." }
]POST /api/harness/sessions
Create a new session.
Request body
{
"config": {
"title": "Quarterly report draft",
"provider": "anthropic",
"model": "claude-sonnet-4-5",
"tools": { "enabled": ["search", "calculator"] }
}
}config and every key in it are optional. The server always mints the
session id.
The client config accepts four keys, on every server, with or
without a user resolver:
| Key | Type | Limit |
|---|---|---|
title | string | At most 256 characters |
provider | string | Non-empty, at most 128 characters |
model | string | Non-empty, at most 128 characters |
tools | { enabled: string[], disabled?: string[], maxConcurrent?: number } | At most 256 names of at most 128 characters each; maxConcurrent is an integer from 1 to 64 |
The server stores provider and model as { type } and { id }.
It doesn't validate the provider family; the host does.
Any other key is refused with 400, and nothing is stored. That
covers messages, tool and job state, artifacts, organizationId,
projectId, userId, extensions, id, and unknown keys. So does
the object form of provider and model ({ "type": … },
{ "id": … }): send strings. A top-level body.userId is unchanged.
Response 400
{
"error": "…",
"allowed": ["title", "provider", "model", "tools"],
"rejected": ["messages"]
}Breaking for clients that seed a session through config
Earlier versions spread config into the new session, so a client
could seed a transcript or name another tenant's scope, and owner
keys were overridden silently. Both are now a 400. To seed a
session from the server, write through the storage adapter instead
of this route.
Response 201
The body is the session object itself, not a wrapper.
{ "id": "018f...", "createdAt": "...", "..." : "..." }GET /api/harness/sessions/[id]
Retrieve a session's full state.
Response 200 — the SessionState shape (messages,
pendingToolCalls, completedToolCalls, pendingJobs, artifacts,
versionVector, etc.).
Response 404 — session not found or not visible to the
authenticated user. The body is { "error": "Session not found" }.
PUT /api/harness/sessions/[id]
Renames a session. The body is {"title": "<string>"}, and title
is the only field it accepts, on every server.
Request body
{ "title": "Quarterly report draft" }Response 200 — the updated session.
Response 400 — any other key in the body. A non-string title
also gets 400.
{
"error": "field not updatable",
"allowed": ["title"],
"rejected": ["messages"]
}PUT no longer accepts a full SessionState. To change messages or
other state, run a turn through execute; to reconcile clients, use
sync.
DELETE /api/harness/sessions/[id]
Delete the stored session. The route does not touch the checkpointer;
the checkpointer cascade runs only through runtime.sessions.delete.
Response 204 — no content.
POST /api/harness/sessions/[id]/sync
Runs a sync for the session through runtime.sync.execute. The
body is { force? }; force: true overrides a conflict.
Request body
{ "force": false }Response 200
{
"applied": true,
"conflicts": [],
"versionVector": { "client_abc": 5, "server": 3 },
"status": "success",
"newVersion": 6
}Response 409 — the sync reported conflicts. The body has the same
shape, with applied: false and the conflicts array filled.
Response 501 — no sync engine is configured.
POST /api/harness/sessions/[id]/execute
Execute a message. Server-Sent Events (SSE) streaming response by
default. Each event from runtime.executeMessage becomes one frame:
event: <type> then data: <json> and a blank line.
The framing follows the request's Accept header:
text/event-stream,*/*,application/jsonor noAcceptat all gets SSE.- NDJSON (
application/x-ndjson, one JSON object per line) is sent only when the client names it with a higher q thantext/event-stream, for exampleAccept: application/x-ndjson. A tie goes to SSE. - An NDJSON response carries
Deprecation: true. NDJSON is deprecated and will be removed at 1.0.
Every response sets Vary: Accept. The bundled clients (useChat, the
Go transport) send STREAM_ACCEPT
(text/event-stream, application/x-ndjson;q=0.9) and parse either
framing, using readStreamEvents(body, contentType) from
@pleach/core/quickstart.
These frames are unnumbered, so a dropped connection can't resume from
where it left off. To re-attach with Last-Event-ID, mount
createPleachTurnRoutes from @pleach/core/server/turns instead. Its
POST /sessions/:sessionId/execute takes the same { message } body
and answers numbered SSE frames (event: / id: / data:). See
useRemoteTurn.
Request body
{
"message": "Summarize the latest changelog entries.",
"fileReferences": []
}message is required and must be a non-empty string. A body without
it gets 400 with error: "missing_message".
Response 200 — Content-Type: text/event-stream. Each frame:
event: message.delta
data: {"type":"message.delta","delta":"The"}
event: tool.started
data: {"type":"tool.started","toolCall":{...}}
event: message.complete
data: {"type":"message.complete","message":{...}}With NDJSON negotiated (Content-Type: application/x-ndjson), each
event is the same JSON object on its own line.
See Stream events for the full event catalog.
Aborting mid-stream
Close the stream (AbortController.abort() on the fetch). The runtime cancels in-flight
provider calls and flushes a final ledger row with
outcome.status: "user-aborted".
There's no separate stop endpoint. For the close to count as a
user Stop (runtime.wasLastTurnAbortedByUser()), the client
declares its disconnect intent when it opens the stream — a request
header, or a query param for EventSource. A client that declares
nothing gets the "error" classification. The header, the values,
and the classification rules are on
SessionRuntime → Stopping a streamed turn from the client.
Reconnection
stream.reconnecting and stream.disconnected are produced by the
client, not the server: the fetch client (useChat) synthesizes them
and the route never sends them. When a request fails to connect and
the client has evidence it is offline, useChat re-sends it under
bounded backoff, announces each re-send with stream.reconnecting,
and sends the same x-pleach-request-id header on every attempt so a
server can recognise a duplicate. When the re-send budget is spent, or
the client has no evidence it was offline, it yields
stream.disconnected instead. A stream that was already established
and then drops is never re-sent and is not replayed: no live rejoin
exists, so the client yields stream.disconnected and leaves the next
step to the caller. See useChat for the
options. The server is idempotent on messageId —
re-submitting the same message after a reconnect doesn't fork
the turn. The route keys each message on the resolved user, the
session and the message id (the body's messageId, else the
x-pleach-request-id header) before it creates or resumes the
session. A re-submit while the first turn runs, or within
messageIdempotency.ttlMs of its answer (10 minutes by default), gets
409 with error: "duplicate_message" and
code: "PLEACH_DUPLICATE_MESSAGE", plus the first turn's turnId
when known. useChat surfaces it as UseChatDuplicateMessageError. A
turn that ends without an answer frees its key, so re-submitting it
runs it again.
A route on another origin must list the client's two custom request
headers in its CORS preflight response:
Access-Control-Allow-Headers: content-type, x-pleach-on-disconnect, x-pleach-request-id,
plus any headers the host adds through useChat's headers option.
A preflight that omits either header fails the POST before it is
sent. A same-origin route needs nothing.
A route on another origin must list the client's two custom request
headers in its CORS preflight response:
Access-Control-Allow-Headers: content-type, x-pleach-on-disconnect, x-pleach-request-id,
plus any headers the host adds through useChat's headers option.
A preflight that omits either header fails the POST before it is
sent. A same-origin route needs nothing.
Model and session-effect routes
These are session-independent unless noted, read-only unless noted, and are
listed in the machine-readable contract at GET /doc (OpenAPI 3.1).
| Route | Answers |
|---|---|
GET /models | The static transport-filtered family/rung catalog. |
GET /providers | LIVE per-provider model lists. Each entry is live, unconfigured (no key), refused (air-gap) or error; one dead provider never fails the listing. |
GET /providers/:id | One provider's list; 404 for an id this build does not ask. |
GET /sessions/:id/diff | Edit-tool changes projected from the event ledger: {files, added, removed, unknown, truncated}. Shell-made workspace changes are not visible here (use the sidecar's /sidecar/vcs/diff). |
GET /sessions/:id/todo | The latest todo_write state ({items, updatedAt, malformed?}). |
POST /sessions/:id/revert | Restore a checkpoint; body {checkpointId?}; newest when omitted. This is checkpoint time-travel, not a per-message undo. |
POST /sessions/:id/compact | Manual compaction only when the host wires a compactor; otherwise 501. The runtime otherwise compacts itself at its threshold. |
A provider you pass
createPleachRoute({ agentProvider, model? }) runs every turn on a provider you already built. The route pins that provider's model and never pivots to another. A per-request model or family is refused with 400 and { "error": "model_override_unsupported" }. On createPleachRoutes, GET /models for such a route lists only that one model. Its transport is "agent-provider" unless you label it with provider.
Event-log session ids
A route stamps session_id on its own event-log rows only when your storage adapter declares sessionRowsAreEventLogParents: true. The declaration says the adapter's session rows live in the table, and the database, that the event log's session_id references. SupabaseAdapter and PgStorageAdapter declare it for their default table only. Without it, including the default in-memory adapter, rows carry the chat id and no session_id. A host schema with a session_id foreign key would otherwise reject the whole flush batch with Postgres 23503.
Naming the agent
createPleachRoute({ agentName }) sets the name the model is told it has. The default is "Hazel", and null names nobody. A name: line in the heartwood file wins over the option. See Heartwood and Quickstart.
The local sidecar additionally serves workspace routes — /sidecar/vcs/status,
/sidecar/vcs/diff, and a gated POST /sidecar/vcs/apply (off unless
PLEACH_VCS_APPLY=1). They are sidecar-only because a remote server may have no
workspace. /sidecar/schedules POST creates a task through the model's own
validated schedule tool; /sidecar/processes (and /:id/log, /:id/kill)
reaches the one process backend the process tool uses.
GET /sidecar/events/stream?sessionId=&sinceSeq= pushes the durable
ledger as SSE (the last id is the resume cursor). /sidecar/tui/* is a bounded
intent queue another bearer-authenticated client can post to; the TUI polls
/sidecar/tui/next and applies each intent on its own loop, so remote control
never answers an approval or races the composer. Saved session approvals are
likewise sidecar-local:
GET /sidecar/permissions lists the grants in force and
POST /sidecar/revoke ends one. The host-agnostic family does not bind them
because the approval ledger only exists in the sidecar process.
Identity
Core reads no Authorization, X-Organization-Id or X-Client-Id
header. The host decides who the caller is. Pass resolveUserId and
resolveTenantId callbacks; they read whatever the request carries
(a bearer token, a cookie, a gateway header) and return the user and
tenant. See Session ownership and
Tenant binding.
Tenant binding
A server is bound to one tenant. On a store shared by several tenants, the routes act only for that tenant and never take it from the request.
- Verify and attest.
GET /sessions/:id/verifyandPOST /sessions/:id/attestact only for the server's bound tenant: the host'sresolveTenantIdtenant and the chain store's own bound tenant, which must agree. With neither set, the tenant isdefault. A?tenantId=naming another tenant gets403. A query that names the bound tenant, or no query, keeps working. The attest body names no tenant. - Local SQLite store.
createSqliteDurableStore(path, { tenant })from@pleach/core/storescopes sessions, checkpoints and event-log reads to its tenant (defaultdefault). A row of another tenant reads as a miss: not found, left out of lists, untouched by updates and deletes. Creating a session with an id another tenant owns is refused rather than overwriting that tenant's row. - Local sidecar. The sidecar opens its store under
PLEACH_TENANT_ID, and/sidecar/replayreplays that tenant's event log.
A host that supplies its own verify or attest capability on a
multi-tenant store must bind the tenant itself: wire
resolveTenantId, or have the verifier expose boundTenantId.
Re-submitting a message
createPleachRoute doesn't run a turn twice when a client re-sends a
message it already sent: a double click, a re-send after a connect
failure, a reconnect that replays the POST. It is a best-effort
protection, on by default. By default it is per process; pass a shared
messageIdempotency.store to cover every instance.
A request names its message by the body's messageId, or else by the
x-pleach-request-id header that useChat sends. The route claims
that id under the request's resolved user and its session before it
creates or resumes the session. A repeat gets 409, and no turn
starts and no provider is called:
{
"error": "duplicate_message",
"code": "PLEACH_DUPLICATE_MESSAGE",
"state": "in_flight",
"turnId": "…",
"detail": "This message's turn is still running; no second turn was started."
}state is "in_flight" while the first turn runs and "settled"
for a repeat within 10 minutes of an answered turn. The duplicate is
refused, not attached to the first request's stream, and an answered
turn is not replayed; read that turn by its turnId instead. The
route resolves the turn's id before it claims the message, so the
turnId names the owning turn from the claim on, even while the first
request is still resuming its session. (With a shared store this holds
when the adapter stores the turn id passed to claim; otherwise it
holds once setTurnId has landed.)
Only an answered turn keeps refusing. A turn counts as answered
when it ends ok, with no abort and no error, and adds a non-empty
answer of its own that is not a canned stub. Any other ending frees
the id, so a re-submit runs the turn again:
- an error, a stop or a disconnect;
- no answer from this turn (on a resumed session, an earlier turn's answer doesn't count);
- a canned provider-terminal answer (an outage, out of credits, a usage or rate limit, a guard halt, a "switch to another model family" notice, raw provider-error text) or a canned no-answer stub;
- a request refused before its turn starts.
A stopped or disconnected turn whose graph run keeps executing frees its id only once that run settles, so a re-submit never runs beside it. A caller-credential terminal on its own still counts as answered, because a re-run on the same refused key can't succeed.
Scope. The key always carries the resolved user, so one user's
ids never collide with another's, and the same id on another session
proceeds. A request is not keyed, and runs as before, when it has no
message id, a malformed one (empty or longer than 128 characters), or
neither a resolveUserId user nor a sessionId. Without
resolveUserId, the first message of a new session is therefore
never keyed.
Per process by default, and never a billing guarantee
Unless you pass a store, the claims live in each route instance's
memory. Re-sends that reach different processes or instances are not
deduplicated, and a restart forgets every claim. A shared store fails
open (see below). Neither is a billing control.
Bounds. Pass messageIdempotency: false to turn it off, or an
object to tune it:
| Field | Default | Meaning |
|---|---|---|
maxEntries | 1024 | Claims held across the route. Over it, the principal holding the most entries loses its oldest (a settled one first); a principal with fewer entries never loses one to this bound |
maxEntriesPerPrincipal | 64 | Claims one principal holds: the user, or the session for a request with no user. Over it, only that principal's oldest entry is evicted |
ttlMs | 10 minutes | How long an answered id keeps refusing |
inFlightMaxAgeMs | 1 hour | How long an in-flight claim stands if its turn never reports ending. A claim whose turn's run is still executing is kept past it (see Long turns) |
store | in memory | A shared claim store, so a re-submit that reaches another instance is refused too. See Sharing claims across instances |
claimTimeoutMs | 2000 | How long the route waits for the shared store's claim, and for each renew, before it fails open. Ignored without store |
keepAliveMaxMs | 30 minutes | The longest time, from the claim, that a claim whose turn is still running is kept past inFlightMaxAgeMs. Infinity turns the cap off. See Long turns |
A zero, negative or non-numeric value falls back to the default; a
fractional count is rounded down, never below 1. maxEntries and
maxEntriesPerPrincipal bound the in-memory store only; a shared store
bounds itself by expiry. useChat surfaces the 409 as a
UseChatDuplicateMessageError, and
DUPLICATE_MESSAGE_CODE, MessageIdempotencyOptions,
MessageIdempotencyClaimStore, MessageIdempotencyStoreClaim and
MessageClaimState are exported from @pleach/core/quickstart.
Sharing claims across instances
Pass messageIdempotency.store to dedupe across every process or
instance that serves the route. When set, it replaces the in-memory
store: each claim, settle and release goes to it, with ttlMs and
inFlightMaxAgeMs passed as the entries' lifetimes. Core ships no
adapter and depends on no vendor; you write one over your own Redis,
SQL database or KV.
import {
createPleachRoute,
type MessageIdempotencyClaimStore,
} from "@pleach/core/quickstart";
declare const store: MessageIdempotencyClaimStore; // your adapter
export const POST = createPleachRoute({
messageIdempotency: { store, claimTimeoutMs: 2000 },
});The store implements four methods:
| Method | Called when |
|---|---|
claim(key, ttlMs, turnId?) | A request with a usable message id arrives. Resolves to { claimed: true, token } for the one winner, or { claimed: false, state, turnId? } for a duplicate. The route passes the claimant's turnId; storing it in the same atomic step lets a duplicate that arrives at once read the owning turn |
setTurnId(key, token, turnId) | The claimed request's turn id is known |
settle(key, token, ttlMs) | The turn was answered. The entry now expires ttlMs later |
release(key, token) | No answer was delivered. The key is freed so a retry runs |
renew(key, token, ttlMs) | Optional. While the claimed turn's run is still executing, about every third of inFlightMaxAgeMs (at least one second apart, one call outstanding at a time) |
An adapter must guarantee:
- One winner.
claimcreates the entry only if no live entry holds the key, in one atomic step visible to every instance. A read followed by a write is not atomic. In Redis that isSET key value NX PX ttl; in SQL, anINSERT ... ON CONFLICT DO NOTHINGthat counts the inserted rows. - Expiry in the store. The entry a
claimmakes expires after thettlMsit was given (the route passesinFlightMaxAgeMs), andsettleresets it to thettlMsit was given. A process that dies mid-turn never releases its claim, so the store must expire entries itself, on its own clock.setTurnIdmust not change the expiry. renewresets only an in-flight entry. If you implement it,renew(key, token, ttlMs)resets the expiry of an entry that still carries thetokenand is still in flight tottlMsfrom now (the route passesinFlightMaxAgeMs), on the store's clock. It must leave a settled entry, and another claim's entry, alone; finding neither is a no-op. Arenewthat timed out can still reach the store after thesettle, which is why it must not touch a settled entry. In Redis that is a script that checks the token and state, thenPEXPIRE; in SQL, anUPDATEthat setsexpires_atwhere the key and token match and the state is in flight.- Fenced writes.
setTurnId,settleandreleaseact only while the entry still carries thetokenitsclaimreturned. A call that finds no matching entry does nothing and does not throw. - A duplicate reads the holder.
claimed: falsecarries the entry'sstate("in_flight"untilsettle, then"settled") and itsturnIdonce one was stored. The route refuses with the same409as above. Astateother than"settled"is read as"in_flight". - Opaque keys. The key is already scoped to the user and session. An adapter may prefix or hash it into its own namespace but must not merge two distinct keys.
A failing store fails open
When claim throws, rejects, answers something malformed (a
claimed: true without a string token counts), or doesn't answer
within claimTimeoutMs, that request is not deduplicated. Its turn
runs, and the route logs one warning line. A claim that wins after the
deadline is released at once. A store outage never refuses a user's
message; it only loses the re-submit protection for that request, so it
is not a billing control. Errors from setTurnId, settle and
release are logged and swallowed; the entry then lives out its
expiry. A renew fails open the same way: one that throws, rejects or
doesn't answer within claimTimeoutMs is logged, the turn keeps
running, and the entry keeps its current expiry.
Long turns
A claim whose turn's run is still executing stays in place past
inFlightMaxAgeMs, so a long turn keeps refusing re-submits. This
includes a run that outlived a stop: its claim is held until that run
settles. With the in-memory store the claim is simply not dropped.
With a shared store it is renewed through renew; a shared store
without renew expires the entry inFlightMaxAgeMs after the claim
even while the turn runs, and a re-submit after that starts a second
turn. Keep inFlightMaxAgeMs well above 1.5 seconds with a shared
store, since renewals are at least one second apart. Once nothing is
running for a whole inFlightMaxAgeMs, renewal stops and the backstop
applies again.
The keep-alive is capped by keepAliveMaxMs (default 30
minutes, measured from the claim). Past it the claim is no longer
extended: the in-memory store stops keeping it, and a shared store's
renew is no longer called. The claim then lapses at its in-flight
lifetime, so with the defaults a turn that never settles holds its
message id for about 1.5 hours at most (keepAliveMaxMs plus
inFlightMaxAgeMs). A shared store stops at its first renewal past
the cap, so its entry can lapse up to one renewal interval earlier.
After that, a re-submit of the same message id starts a new turn. The
running turn is not aborted; the route logs one warning per claim when
the cap stops its keep-alive. Pass Infinity to turn the cap off, and
a run that never settles then keeps its message id in flight until it
does. The client can always re-send under a new message id.
On a route without a per-request runtime scope, the route's
one-request gate is held while the claim waits, so a slow store delays
the next request for up to claimTimeoutMs.
Routes on a runtime without AsyncLocalStorage
On Node.js, createPleachRoute() keeps each route's state in its own
scope, so routes in one process never share it. A runtime without
AsyncLocalStorage (a browser) can't carry that scope across await,
so routes there share process-wide slots: the standard loaders, the
tool executor, the audit row sink and the process audit ledger. A
process gate lets one route use them at a time:
- A request is admitted to the gate only after the route's own checks
pass: method, body, provider, model override, your
resolveUserId/resolveTenantIdhooks and the stored-session owner gate. A refusal (405,400,501) never takes the gate, and admission follows what your hooks allow. The route does no authentication of its own. - While an admitted request of one route is in flight, a request of a
different route answers
503with{ "error": "route_overlap", "code": "PLEACH_ROUTE_OVERLAP" }andretry-after: 1. Overlapping requests of the same route still run. - A request holds the gate until its turn has finished, including a cancelled turn whose graph run is still winding down. There is no hold bound and no fairness, so a turn that never ends keeps other routes refused.
- If the gate's slot on
globalThisholds a foreign value, requests answer500withPLEACH_ROUTE_GATE_UNAVAILABLE. - A route that contributes no plugin tools fails closed on any tool name it didn't offer.
A late audit row from work a timed-out step left behind may be attributed to the next route's request. It is still recorded once. Both codes are in Error codes.
Host deadline and parked turns
A route that passes turnDeadline bounds one segment, not the task.
When the deadline arrives the graph run stops between supersteps, the
runtime writes a single-use continuation token, and the stream ends with
turn.parked { turnId, messageId, token, segment, reason, nextStep } instead of turn.completed.
The store frame is claimed compare-and-set, so exactly one continuation
runs; a second attempt is refused (already-claimed, cancelled,
completed, stale-token, superseded), and a continuation after the
client sent a newer message is refused too.
Both route families can continue it:
| Route family | Continue | Stop |
|---|---|---|
createPleachRoutes | POST /sessions/:id/turns/:token/continue → the execute leg's framing (SSE, or NDJSON if negotiated) | POST /sessions/:id/turns/:turnId/stop with { "token": "..." } |
SSE turn routes (createPleachTurnRoutes) | POST /sessions/:id/turns/:token/continue → numbered SSE frames | same |
The createPleachRoutes continuation opens with turn.continued and keeps the
original turn id; it does not re-add the user message or re-run model
selection, family routing or the per-request auth gate (the execute leg
already did). Pass a fresh turnDeadline if you want the segment bound
to apply to the next segment too. Billing rows travel in the parked
frame and roll up per message id, so every segment is billed exactly
once even when nobody continues. A continuation on a runtime that was
released or disposed is refused rather than replayed.
Clients that do not handle turn.parked see a truncated answer, not an
error, so treat it as a protocol event: continue with the token, or stop
the turn explicitly to write its durable turn.aborted row. The local
sidecar defaults PLEACH_TURN_DEADLINE_MS to 10 minutes and the TUI
continues automatically.
Error response shape
A route error body carries error, a short string. Some add detail
with the underlying message.
{ "error": "Session not found" }{ "error": "turn_continue_refused", "detail": "token expired" }Structured codes appear on stream error events, not on route error
bodies. See Stream events and
Error codes for the catalog.
Where to go next
HarnessServer
Framework-agnostic handlers behind these routes — mount into Express, Hono, or raw node:http.
React
The client hooks that speak this wire contract.
Query
Server-side read API over the same persisted data these routes write.
DevTools
Browser-console surface for inspecting session state these routes return.
HarnessServer
The route family behind createPleachRoutes — mount it into Next.js, Express, Hono, or node:http, and read what each HarnessServer handler returns.
Query
Server-only read API over persisted harness data — usage, transcripts, events, jobs, assets, tools, analytics. Uses a service-role Supabase client and bypasses RLS; never import into browser bundles.