@cotal-ai/connector-core 0.122.0 → 0.123.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
1
  import type { DocsBundle } from "./docs.js";
2
2
  /** The installed Cotal version, for stamping the orientation card and other surfaces. */
3
- export declare const DOCS_VERSION = "0.122.0";
3
+ export declare const DOCS_VERSION = "0.123.0";
4
4
  export declare function loadDocsBundle(): DocsBundle;
5
5
  //# sourceMappingURL=docs-bundle.generated.d.ts.map
@@ -1,8 +1,8 @@
1
1
  /** The installed Cotal version, for stamping the orientation card and other surfaces. */
2
- export const DOCS_VERSION = "0.122.0";
2
+ export const DOCS_VERSION = "0.123.0";
3
3
  export function loadDocsBundle() {
4
4
  return {
5
- "version": "0.122.0",
5
+ "version": "0.123.0",
6
6
  "generatedFrom": "docs/*.md + SPEC.md + spec/cotal-lang.md + spec/cotal.schema.json",
7
7
  "pages": [
8
8
  {
@@ -51,7 +51,7 @@ export function loadDocsBundle() {
51
51
  "kind": "Concept (informative)",
52
52
  "category": "Concept",
53
53
  "summary": "Who can do what on a mesh, and how it is enforced.",
54
- "body": "# Identity\n\n> **Concept** (informative) · **For:** operators and implementers · **Normative:** [SPEC §2](../SPEC.md#2-identity), [§9](../SPEC.md#9-nats--jetstream-security-and-authorization), [§10](../SPEC.md#10-connection-and-onboarding), [Appendix B](../SPEC.md#appendix-b-profile-acls)\n\nWho can do what on a mesh, and how it is enforced. The design goal: the mesh is a **real\nboundary against untrusted peers in a shared space**; an agent can only speak as itself\nand only where its declared permissions allow, enforced by the broker, not by agent\ngoodwill. What that boundary does and does not protect is the\n[security model](security.md); the exact ACLs are\n[SPEC Appendix B](../SPEC.md#appendix-b-profile-acls).\n\n## On by default\n\n`cotal up` provisions a JWT-authed space; `cotal up --open` runs an unauthenticated dev\nmesh instead. Both bind loopback by default. `--host 0.0.0.0` widens the bind\nindependently, so \"network-reachable\" never silently means \"unauthenticated\". Open mode\nis for quick local experiments and sits outside every security claim\n([SPEC §9](../SPEC.md#9-nats--jetstream-security-and-authorization)).\n\n## Shared identity\n\nAn agent's wire identity is a **principal**: an `owner.actor` pair, where the owner is\nthe account (a human, or an organization) the agent acts on behalf of, and the actor is\nthe agent's own handle under that owner ([SPEC §2](../SPEC.md#2-identity)). The same pair\nis the card id, the sender tokens in every subject it publishes, the presence key, and\nits durable-consumer names. On an open dev mesh the owner is the literal `local`; on a\nper-user-auth mesh it is a derived token (`u_` plus 26 characters, so no PII rides the\nwire). The connection still authenticates with an **nkey**, generated locally (the signer\nonly ever sees the public half), but the nkey is the transport credential, not the\nidentity: it scopes only the per-connection reply inbox.\n\n**The sender is encoded in the subject.** Every publish carries the sender's owner and\nactor in positions the broker's permissions pin to that connection, so an agent *cannot*\nemit as anyone else: not as another owner, and not as a sibling actor under its own\nowner. Receivers verify the payload's `from.id` against the subject sender and reject\nmismatches; sender authenticity is broker-enforced end to end\n([SPEC §3](../SPEC.md#3-subject-layout), [§5](../SPEC.md#5-envelopes)).\n\n**Account = space, user = agent.** A space is one NATS account, a server-enforced\nisolation boundary. An operator signs the account; an account **signing key** mints\nper-agent user JWTs.\n\n## Provisioner\n\nThe **provisioner** is whoever holds the account signing key. It mints profile-scoped\ncredentials and pre-creates the durables agents may only *bind* (their DM inbox, their\nrole's task queue). The manager hosts it today, but nothing is manager-special about it;\nprivilege attaches to the signer, and a space can run without a manager.\n\nUser-credential and auth-callout JWT signing uses Node's native Ed25519 implementation. NATS\nlibraries still encode keys and JWTs. The signer produces the same signature bytes for the same key\nand payload; permissions, expiry and issuer checks are unchanged. The auth callout also verifies\nthe broker's signed request with Node's Ed25519 rather than the NATS library's JavaScript curve,\nwhich cost several milliseconds per connect. It makes the same checks: a NATS JWT header, a public\nnkey issuer with a valid checksum, and that issuer's signature.\n\nThe temporary native provisioner can request `$SYS.REQ.USER.INFO` for its own connection.\nThe broker's configured system account maps the service to that requester. The reply can bind\nits public user/account and serving server to the local pins without a system credential.\nIt is not an effective permission ceiling, issued generation, lifecycle or apply authorization.\nAn unavailable or denied service does not trigger another credential or server fallback.\n`cotal auth mint <name> --profile <agent|observer|admin>` is the out-of-band path; spawn calls\nthe same library ([CLI](cli.md)). The out-of-band profiles last 24 hours unless\n`--expires-in <seconds>` or `--expires-at` sets another lifetime, and a standing-renewal consumer\nrequires a bounded credential. `--no-expiry` issues one with no expiry, which `cotal doctor auth`\nreports as a warning; it reports any other unbounded credential as a finding. `--replace` replaces a\nlabel's credential once it has expired, when it has no expiry, or when `auth revoke-credential`\nrevoked its key. `--identity <creds>` reuses a file's nkey and principal,\nbut the out-of-band agent mint allocates a new lifecycle UID. It does not reuse the old\nbind-only inboxes; clients must use the UID in the receipt and explicitly provision it when\nneeded. Minting static creds is a\n**static-auth** surface: a\nper-user-auth space refuses it, because agents there join under a logged-in user, never\nvia a handed-out file (see *Per-user auth* below).\n\nAgent-profile minting resolves one mesh root for the persona ACL, account signer and default\ncredential storage. If the current folder holds trust for a different space or account, mint\nrefuses and names both roots. It never signs one root's persona policy with another root's authority.\n\n## Profiles\n\nEvery credential is a profile: an explicit allow-list built from the same\nsubject/stream/durable builders as the wire layout, so ACLs cannot drift from it. The\nnormative shapes are [SPEC Appendix B](../SPEC.md#appendix-b-profile-acls); in brief:\n\n| Profile | Is |\n|---|---|\n| **agent** | The ordinary peer: publishes as itself to its declared channels, reads within its read ACL + its own DM/task inboxes. It reads the roster on demand with a Direct Get of the presence bucket, which binds no consumer. Its channel-registry watch, and the presence watch older seats hold, create and inspect client-managed ordered consumers but cannot delete any consumer on those streams; the broker removes a finished watch's consumer five minutes after its last interest. |\n| **observer** | Read-only chat + presence; DMs invisible. What `cotal console` runs. Its only consumer deletes name its own history readers (`hist_<readerId>_<n>` on CHAT, keyed on its nkey or on the connection the server assigned), so each history read removes its consumers when it ends, and it cannot remove another principal's watch or the delivery daemon's fan-out consumer. The broker removes its finished watch consumers. |\n| **admin** | Elevated *read-only* god-view: sees DMs and anycast live, still writes nothing. A deliberate opt-in for elevated operator observation. Deletes its own history readers on CHAT and DM, and no other consumer. |\n| operator-side | Narrow single-purpose creds for the machinery (supervising, provisioning, teardown, delivery); the reference implementation splits these so no one connection can read every DM *and* delete every stream ([security model](security.md)). |\n| **run-driver** | One workflow run and takeover attempt: its journal subject, replay durable and run-owned record writes. Store reads and effects go through the host. |\n| **run-mediator** | The trusted hosting process's separate connection for workflow effects and leader reads. It exposes journal-checked, run-bound operations and never hands its credential to the driver. |\n| **run-operator** | One served run read, or one half of an answer, minted per call: a read holds the records walk, one run's replay and the admission read; the answering half is minted for one checkpoint token and holds that pause's answer record and settle alone. |\n| **issuer** | One issuance window: the party holding the space signer mints it for a few minutes to stage and release a credential's evidence, retire the issuances a lifecycle terminal leaves behind, or resolve the evidence a request rides. The auth service, and each callout replica, holds one of its own for the issuance its callout makes on a user-auth connect. It replaces that session before its five-minute credential expires and closes it with the service. |\n| **run-admitter** | One run's admission record or revocation marker, minted per run for a minute: two exact keys in the admission store and nothing else. |\n\n**An agent's channel scope is three verbs**: `subscribe` (reads at boot),\n`allowSubscribe` (read ACL), `allowPublish` (post ACL, default-deny), declared in its\n[agent file](agent-files.md) or [manifest](manifest.md), minted into its cred. One card\nwith the recipes: [Channels & permissions](channels-and-permissions.md).\n\n**DM confidentiality** holds against peers by construction: deliveries ride per-identity\ninbox prefixes, and the DM/task consumers are provisioner-pre-created and bind-only, so an\nagent cannot create a consumer filtered to someone else's inbox\n([SPEC §9](../SPEC.md#9-nats--jetstream-security-and-authorization) items 1–5).\n\n## Issued authority\n\nA credential says who is calling. It does not, by itself, say what the caller was granted, and a\nhost that acts on a caller's behalf (a workflow run, [workflows](workflows.md)) needs that from\nthe issuer, not from a ledger that may have changed since. So a static agent credential is an\n**issuance** ([SPEC §13.15](../SPEC.md#1315-issued-authority)): before the material is handed\nout, the issuer records the credential's final permission ceiling, as evidence keyed by a fresh\n**generation**, in `cotal_issued_<space>`. That store is append-only at the broker until a row's\nown TTL ends it, and the evidence is read as the first message on its key, so nothing written later\non the same key, by anyone, changes what a resolver sees. The credential's endpoint rows then ride a versioned\nrail, `cotal.<space>.ep.v1.…`, with that generation pinned beside the caller triple, so the\nbroker binds every request to the ceiling the issuer accepted. The legacy `ep.` rail and the\n`ep.v1.` rail are disjoint subject spaces; a credential holds rows on one of them, and every\nendpoint serves both.\n\nA connected client learns its generation by reading one row in `cotal_accepted_<space>` under a\ntoken the launching party chose at mint time, through a per-key read grant its own ceiling carries. It never trusts\nwhat the file says. A renewal keeps the generation only while the ceiling is byte-identical to the\nevidence; a changed scope is a fresh issuance on a fresh generation, adopted by a new connection.\nA static agent's evidence names its credential ledger family as the source it depends on, and the\nlifecycle terminal that retires that family retires its issuances with it.\n\nIssued rows do not last forever. A generation carries its **horizon**, the second from which it\nauthorizes nothing: the bearer's expiry for a user-auth `manager-caller` view, the instrument's\nfive-minute expiry for a control-caller instrument, the assignment expiry for a platform\nsupervisor, and 30 days after spawn for a static agent. Every row of a generation in both stores\nis written with a NATS per-message TTL that removes it 60 seconds after the horizon, so the stores\nhold the generations that can still be used, not every exchange ever made. Every host refuses a\ngeneration at or after its horizon before it reads the store, so a row the broker removed, and\nanything written on its key since, is never read. A static agent's credential renewals stop at its\nhorizon, and the agent is then respawned; rotating it onto a new generation instead is\n[#4942](https://github.com/Cotal-AI/Cotal/issues/4942). On a user-auth space the auth service is\nthe only issuer, so that cap does not apply there.\n\nA space whose issued stores were created before this retention existed is refused by every service\nthat binds them, with the remedy in the error. Stop the space's auth service, its callout replicas\nand every manager, then start the space with `cotal up --space <space> --recreate-issued-stores\n<backup-dir>`. It backs up `KV_cotal_issued_<space>` and `KV_cotal_accepted_<space>` into\n`<backup-dir>`, deletes them, and the start creates them again in the current shape. An embedder\nwhose spaces `cotal up` does not start runs the same step ([Embedding](embedding.md)). Generations\nissued before the upgrade refuse afterwards, and static agents started before it are respawned. The\norder and the rollback limits are in [Upgrading](UPGRADING.md#issued-authority-stores-after-01110).\n\nThe manager, `cotal spawn`, and the CLI's control-caller instruments all mint through an `issuer`\nsession. The deployer instrument does not: it is the one instrument with no default expiry, and an\nissuance with no lifecycle gate must carry one, so a deploy rides the legacy rail under its own\nlifecycle uid. Only workflow `run-start` and the keyed `run-start-keyed` and `run-submission-status`\nrequire the binding today: a request for one of them on the legacy rail is refused with\n`permission-denied` and the detail `ai.cotal.ep.unbound-caller-authority` naming the caller.\nEvery other command serves both rails.\n\nA user-auth `manager-caller` view is issued at the auth callout for an interactive row, or for a\nmanaged seat whose current persona-derived scope contains `run` and whose direct parent's fresh\nsame-owner grant also contains `run`. An admin parent's containment bypass does not count. The\nsingle source is the child's own actor row and lifecycle, and evidence records the signed ceiling\nwithout adding capabilities. Same-nonce renewal requires the same triple and byte-identical ceiling.\nThe existing view policy and manager instance gate are unchanged, with no new request kind. A seat\nmissing either `run` input keeps ordinary legacy commands. Without signed `run`, the broker refuses\n`run-start`; with signed `run` but no eligible parent, the manager refuses with\n`ai.cotal.ep.unbound-caller-authority`. A failed issuance never retries on that rail.\n\n## Declared capabilities\n\nControl-plane power is a **declared capability**, not a default. An agent file carrying\n`capabilities: [spawn]` gets the privileged control subject minted into its cred: spawn,\nplus stop/despawn of its *own* children, plus persona definition. On a static or open mesh its own\nchildren include what it launches with `cotal spawn --detach` from its own shell, since that\ncommand runs as the seat. Without it, an agent can\nonly self-despawn and pull or yield the run turns addressed to it. `capabilities: [run]` mints\nthe manager's workflow-run commands (start, resume, answer, status, list) together with the spawn\nset, since a program the agent starts may spawn; the manager drives the run under a per-run\n`run-driver` credential of its own, never the caller's. The tool surface mirrors the grant:\n`cotal_spawn` / `cotal_persona` / `cotal_personas` are injected only for `spawn`, and `cotal_run`\nonly for `run` ([agent files](agent-files.md)). Destructive\noperator ops (history purge, cross-agent stop) live on a third tier no agent credential\nreaches. Persona redefinition separates content from policy; the write path takes only\n`model`/`persona`, so a peer cannot grant itself a capability by redefining a file.\n\n## Per-user authentication\n\n`cotal up --user-auth --idp <auth base URL>` (or manifest `broker.auth: \"user\"`) puts a\n**human identity plane** above the per-agent one: people sign in to an external IdP once,\nand every connect is authorized live against the operator's **actor ledger**. No creds\nfiles to hand out, and revoking a grant actually bites.\n\nThe first enable pins the space to that IdP. A later `--idp` naming a different IdP is refused,\nbecause the IdP is part of every derived owner. Two first enables that race on one state dir leave\none pin: the other caller adopts it when it names the same IdP and is refused when it does not.\n\n**The flow.** Each person runs `cotal login --idp <url>` once per machine. The IdP URL, the JWKS\nURL pinned from it and the catalog link below must use HTTPS. Plain HTTP is accepted only on a\nloopback IP literal such as `127.0.0.1`, never on `localhost`, whose resolution would choose the\nkeys the mesh trusts. After that,\nany command works: cached IdP session → IdP proof, fetched per connect and reused in memory for\nat most a minute (so IdP-side revocation bites within a minute) → the configured exchange turns it\ninto a short-lived Cotal bearer →\nthe broker's **auth callout** checks the bearer and the ledger at connect time and mints\na scoped credential on the spot. Every bearer also names a **root credential** row in the\nspace's credential ledger, proved live at each connect, so revoking that one credential\nbites at the very next connect. The operator grants access with\n`cotal actor grant <actor> --sub <their id> --full` for the full envelope (all\nchannels; scope `spawn,role:default`, so it may spawn and may delegate the default role), or names\n`--scope`, `--allow-subscribe` and `--allow-publish` for a narrow row. A grant with any of the\nthree left off and no `--full` is refused.\nNo ledger row, no access; there is no allow-by-default.\n\nManaged grants record who holds the lifecycle: a local manager's persisted logical instance ID,\nan authorized remote manager's instance ID, or a foreground launch with no manager. The trusted\nwriter supplies this custody record. Ledger reads, decisions and writes share one synchronous\ntransaction; broker provisioning and retirement run outside it. A grant that found no row refuses with\n`CONFLICT` when another grant for the same actor lands while it waits for the ledger lock. A re-grant\nor revoke whose actor row changes or disappears while its lifecycle retires ends `partial` (exit 4)\nwhen the auth service reports that this call retired the lifecycle: the lifecycle stays retired, the\ncommand writes and deletes nothing, and the error names the retired lifecycle under `changed`. When\nthe service reports that the lifecycle never started or was already retired, the same race refuses\nwith `CONFLICT`. A retirement answer without a readable result ends `unknown` before anything is\nwritten. Re-read `cotal actor list` before trying again. Old rows remain readable without\ncustody, but a custody-pinned operation refuses them rather than adopting them. This field does\nnot authorize recovery over another manager's or an unknown lifecycle.\n\nThe auth ledger also reserves a closed `chat-sessions/` row space. An interactive or managed\ngrant cannot reuse an alias present there, and a principal found in both spaces refuses.\nA pending chat row authorizes nothing.\n\n**User-mode chat sessions.** In a user-auth space the auth service can open chat sessions, the only\nidentities it creates on its own. A signed-in person opens a session with their IdP proof and the hash of a\nholder secret that stays in the client's memory. The service picks the session's actor\n(`chat_` and 26 base32 characters) and a fresh lifecycle UID. It pins the person's own `cli`\ngrant, keeps the session's read and post lists inside that grant, and fixes its lifetime at up to\n8 hours with no extension. Each bearer lasts at most 15 minutes, and never past the IdP proof or\nthe session. The service checks the session, the holder index and the pinned grant before and\nafter it signs one. A session connects as a plain agent with its own lists and no role, capability\nor view. A change to the person's `cli` grant refuses each open session's next bearer and connect.\nClosing a session retires its lifecycle before its quota slot is freed. The service also sweeps\nexpired and abandoned sessions and keeps a retired row for 24 hours after its expiry. A provider\nwithout the optional chat methods cannot open a user-mode session, and the client refuses with no\nother identity tried.\n\n**Static-mode chat sessions.** On a static-auth mesh the local manager admits a chat session\ninstead: it mints the session's own leaf under a fresh nkey and retires it through the static\nterminal, which cannot end the leaf at the broker before its expiry\n([control-surface.md](control-surface.md#static-chat-sessions)).\nThe participant presentation carries the resolved space in its session identity and shows that\nmesh in its human header and connection report. The session label does not choose the target.\nAn output-stream error stops new stdio input and requests session closure through the input-close\npath. A failed stdout cannot deliver the end record. When returned, the close report records the\nobserved connection status.\n\n**Space catalogs.** A successful authenticated `GET <idp>/token` may advertise one catalog with:\n\n```http\nLink: <https://idp.example/spaces>; rel=\"https://cotal.ai/relations/space-catalog\"\n```\n\nThe target must use HTTPS and the same origin as the normalized IdP URL. Loopback IP literals may\nuse HTTP for local development. A missing, foreign-origin, or insecure link records that this account\nhas no catalog. The client never guesses a path.\n\nThe catalog request carries the opaque cached session as its bearer and returns a complete snapshot:\n\n```json\n{\n \"v\": 1,\n \"account\": { \"idpUrl\": \"https://idp.example/api/auth\", \"issuer\": \"https://idp.example\", \"sub\": \"user-id\" },\n \"spaces\": [\n { \"id\": \"space-id\", \"slug\": \"shared_project\", \"name\": \"Shared project\", \"kind\": \"hosted\", \"role\": \"owner\", \"registration\": {} }\n ]\n}\n```\n\nThe client checks every `registration` with `checkBundleDocument`, the object checks `checkUserBundle`\nruns after it parses a file for `cotal meshes add`. The catalog already holds the value, so it is not\nserialised back to text: a missing `registration` is a missing field, and the not-JSON sentence stays\nwith a file or a discovery body that does not parse. One invalid entry refuses the whole candidate\nsnapshot. Conditional refresh uses the\ncatalog's `ETag`; a transport error, non-success response, or invalid candidate leaves the prior\nsnapshot intact and reports the failure. Only a 401 response for the saved session recommends signing\nin again. Transport errors and server failures report that account's refresh error without discarding\nthe session. The registry is reconciled under the provider's catalog lock, and a snapshot whose\nreconciliation was interrupted is reconciled again by the next refresh before it counts as fresh or\nnot modified.\n\nThe user-auth registration document may include one closed policy object:\n\n```json\n{ \"policy\": { \"events\": \"required\" } }\n```\n\nNo other key under `policy` and no other value for `policy.events` is accepted. The registry preserves\nthis field for manual, discovered, and enrollment-created entries. A pre-policy manual entry is\nrefreshed from its own pinned exchange origin by the command that consumes the policy, a spawn, a\njoin, or a manager start, after that command's own local refusals; the returned space, broker,\ntransport, IdP, issuer, audience, and exchange pins must all match before only the policy is added.\nA failed expired refresh refuses that operation. Read-only commands such as `status` and `meshes`\nnever refresh. The five-second warm window makes no request.\n\nEvery registration is also bound to the proved account. Its IdP URL must match the account and its\nissuer must match the exact JWT `iss` pin. Its exchange, provisioning, and manager-authority\nendpoints must be same-origin with that IdP. One foreign pin or endpoint refuses the whole\ncandidate snapshot.\n\nThe `slug` is the space identity resolved by `--space`, `use`, registry roots, and collisions. The\n`name` is a display label only.\n\nDiscovered registry entries are owned by the normalized IdP origin plus the proved `sub`. That key is\nstored as an opaque digest, so accounts on one machine never union their spaces and the registry does\nnot persist the subject. A manual or locally started record with the same name is never overwritten.\nLogout removes only the entries owned by the account whose session was revoked. Local teardown,\ncleanup, and liveness pruning do not remove discovered entries.\n\nAn account that previously advertised no catalog is checked again by explicit `cotal sync`. The\nordinary lazy path checks again after its five-second capability window, so an IdP can enable the\nLink for an existing login without making the person sign in again.\n\n**One auth service per space** hosts both halves: the NATS auth callout and the token\nexchange. One process may host the services of several spaces, one lane each (below). Its default HTTP listener remains loopback-only and requires the per-start capability\nstored in the owner-only `auth-service.json` file. An operator may add a second listener with\n`cotal up --user-auth ... --exchange-public-port <port> --exchange-public-url https://auth.example`.\nThat listener still binds `127.0.0.1`; put a reverse proxy in front of it and terminate TLS there.\nIn-process TLS is deliberately not another deployment mode: it would duplicate certificate renewal\nand fork proxy-based deployments.\n\n**Callout replicas.** `cotal auth-service --callout-only --space <s> --server <url>` runs one more\nmember of the space's callout queue group. `cotal auth-service` is a deprecated entry kept for\nexisting units and scripts; new setups use the `auth-service` service preset\n([deprecated daemon entries](UPGRADING.md#deprecated-daemon-entries)). The broker hands each connect to one member, so a\nreplica keeps connects answered while the full auth service restarts or crashes, and adds capacity.\nA replica runs the same connect checks as the full service and holds nothing else: no HTTP\nlistener, no `auth-service.json`, no plane claim, service registration, barrier, scanner or sweep,\nso it never competes with the full service for any of them. Its store connection reads\nthe auth, records and sessions stores and creates each connect's issuance row; it creates no store,\nmints no credential and writes no gate. Like the full service, it holds its own issuer session for\nthe connects that need issued authority. A replica reads the actor ledger in the space's state dir\nand the same secret entries the full service's callout reads, the bearer issuer key among them, so\nit runs only on a host trusted like the full service's. A replica that loses a store connection or\nthe broker stops answering and exits non-zero, and the broker sends later connects to the other\nmembers; restart it with the unit that runs it. It refuses the HTTP flags and `--service-endpoints`.\nA replica cannot issue a service-endpoint connection, so it refuses to start in a space that admits\nservice endpoints: one whose full service has run with `--service-endpoints`, or as a lane whose\nmanifest entry sets `serviceEndpoints`. That first run opens the space's admission and nothing closes\nit, so the refusal stays after the setting is dropped. A callout host serving several spaces names\nsuch a space, retries it every 5 seconds and keeps answering for the others;\n`admitsServiceEndpoints` from `@cotal-ai/auth` answers the same check for a manifest writer.\n\nThe loopback face also serves four host-only doors, all capability-gated and never on the public\nface. Two retire a lifecycle: `/interactive-lifecycle/retire` (used by `cotal actor grant/revoke`)\nand `/managed-lifecycle/retire`, which finishes a managed agent's terminal retirement after its\nremote manager is gone. The interactive door answers every refusal it makes before the retirement\nbarrier with `outcome: \"not-executed\"`. An error without that outcome may follow a barrier that had\nbegun, so `cotal actor grant` and `cotal actor revoke` report it as unknown. The third decides one:\n`POST /manager-service-authority/verify-enrollment` answers whether a remote manager may have a\nmanaged agent enrolled or released under its authenticated owner. The body is\n`{ owner, request }` and nothing else. The caller's capability scope is read from this machine's\nledger, never taken from the body, so a host that forwarded a participant-supplied scope could not\ngrant itself `supervise`. The door reads the manager gate and checks the registration proof inside\nthe service process, so no signing material reaches the caller, and it returns\n`{ authorized: true, owner, actor, instanceId, serveEpoch }` or maps its refusal to 400, 401, 403,\n409, or 412. It decides only. A platform that intercepts these requests owns every write, and stock\n`dispatchManagerAuthorityRequest` refuses both request kinds with `unimplemented` rather than\nanswering a manager-lifecycle phase for an agent-lifecycle request. The same door decides the hosted\nruntime create and status kinds. For those it reads the manager actor's ledger row itself and returns\n`{ authorized: true, owner, instanceId, actor, target }`.\nThe fourth, `POST /tool-result-human-proof/verify`, decides a pinned password proof for the\nhost's authenticated session subject without issuing consent or credentials.\nThe opt-in `POST /tool-result-consent/issue` door signs and records a same-owner consent\nunder a host-custodied scoped anchor. It returns no result content, private key or capability.\n[embedding.md](embedding.md) documents these host doors' contracts.\n\nThe public listener has a closed surface: `GET /health`, `GET /jwks`, `POST /exchange`,\n`POST /manager-service-authority`, `POST /manager-instances`, the three `/chat-session/open`,\n`/chat-session/bearer` and `/chat-session/retire` routes, and `GET /.well-known/cotal-mesh`. A space\nwhose auth service runs with `--service-endpoints` also serves `/service-endpoint-authority` and\n`/service-endpoint-host` there ([embedding.md](embedding.md)); without it they answer 404. Every\nother path is 404. It\ndoes **not** require the loopback\ncapability. That capability proves same-uid access to a 0600 local file and has no remote meaning;\non the public face the credential is the proof. A human presents an EdDSA IdP JWT checked against\nthe pinned JWKS, issuer, and audience. An agent presents its spawn-time actor token, whose hash must\nmatch a fresh managed-ledger row. The public face mints three elevated views, all still gated on\nledger scope `admin`: `channel-writer` (`cotal channel set` and `cotal channel defaults`), `channel-purger` (the\ndashboard's per-click channel delete) and the one-object `transfer-writer` (below). It also mints\nthe scope-free `session-caller` view (below) and the narrowing `manager-caller` view for humans\nor managed agents. That view binds the bearer to one live registered manager instance. It adds no\ncapability, except that a `spawn` holder's view may read that manager's `status`, `models` and\n`resolve-cwd`, which a host-local launch there needs. A manager using a delegated runtime refuses\nhost cwd resolution before filesystem lookup because its seats execute outside that host.\nGod-view (`admin`), space-history `purger`, `deployer`, and `manager-service` stay\nloopback-only. A managed-agent secret exchange refuses every other view. This is not full remote\nchannel management. The older embedded dashboard path needs a startup admin view even when a later\ndelete could use `channel-purger`. The new dashboard service currently accepts only an explicit\nstatic credential with read-only intent; it does not substitute that older operator login path.\n\nThe well-known response contains the IdP pins and the actual deny-all sentinel credential remote\nagents need before the bearer-driven auth callout. The pins ride a `userAuth` arm that names the\nauth provider, and that name is the same one the local arm registers under. A document naming a\ndifferent provider than the one serving it would register an entry nothing can resolve, so both read\none constant. Treat it as bootstrap material: the sentinel cannot publish or subscribe, but\nconsumers must still take the bundle only from the intended HTTPS origin and must verify TLS.\n`--exchange-trusted-proxy` opts into peer attribution by the **last** `X-Forwarded-For` hop; use it\nonly when the listener is reachable solely through a proxy you control.\nWithout it, forwarded headers are ignored and the socket address is the peer key. Public failure\nbuckets are per-source and separate from loopback exchange budgets. The in-process LRU retains at\nmost 1024 peer buckets: that bounds memory and isolates ordinary sources, but an attacker cycling\nmore than 1024 trusted-proxy last hops can evict earlier 429 state. It is not a mint bypass; a valid\ncredential is still required, so use upstream reverse-proxy rate limiting when that throttle-escape\nmatters to the deployment. A refusal at `POST /manager-service-authority` counts against the same\nbudget as one at `/exchange` on that face, so after 30 refusals in a minute either route answers a\nfurther refusal with 429. On the public face, a `manager-caller` `/exchange` request whose\ncredential and ledger actor grant have already verified (IdP JWT plus interactive actor grant on the\nhuman arm, actor secret plus managed ledger row on the agent arm) checks two per-principal\nselection-refusal windows (`30/min` each, keyed by principal (derived owner for human exchanges,\n`owner.actor` for agent exchanges) and request class: `pinned` when `managerInstanceId` is named,\n`unpinned` when it is omitted, never by the requested instance id) before running manager\nselection. While under its class limit, a selection failure returns `401` with its actionable\nreason without spending the per-peer probing budget or being masked by a peer's `429`. Once a\nprincipal's `unpinned` or `pinned` window is full, the public face sheds manager selection for that\nclass (refusing requests of that class, including ones that would have succeeded, while leaving the\nother class open) and returns `429` with that class's remedy (`--on` / `--manager-instance` /\n`cotal supervise` for `unpinned`; checking that the pinned manager instance is live and registered\nto the caller for `pinned`) until the window drains. Those principal-class windows share one bounded\n1024-key LRU of the same kind as the peer buckets: because one principal owns both its `pinned` and\n`unpinned` class keys, rotating 512 other verified principals (1024 keys, where each principal\nrequires its own verified credential and ledger grant, and one owner's managed agent rows count as\nseparate `${owner}.${actor}` principals) can evict an earlier full window and reopen it. On the\nloopback face, an authenticated unpinned refusal caused by no live manager or ambiguous candidates\nkeeps its actionable reason without spending the shared probing budget.\n\n### Callout deadlines\n\nnats-server waits for the auth callout's answer for its `authorization { timeout }`, two seconds\nunless the broker config sets it. From 2.15 a connect with no answer by then is refused; 2.14 leaves\nit waiting for the client's own connect timeout. The callout answers inside that window. A request's\ndeadline is the broker timeout less 250 ms, counted from when the callout received it. A request\nstill unanswered then gets a signed denial with the reason\n`timeout: the auth callout could not answer inside the broker's authorization timeout`, and its work\nstops at its next step. While the oldest request still waiting for a slot has waited more than half\nthat budget, the queue is not draining in time, and a new request gets the same denial at once\ninstead of joining it. Requests start oldest first, at most `maxInFlight` at a time.\n\nThe client sees `Authorization Violation` for this denial as for any other, because nats-server does\nnot pass a callout's reason to the client. The broker logs the reason after\n`Auth callout service returned an error`, and the callout logs it on its own line.\n\nEach answered request writes one line to the auth service's standard error:\n\n```\nauth callout: level=info outcome=minted space=<space> req=<user nkey> cid=<broker client id> owner=<owner> actor=<actor> queue_ms=0 verify_ms=1 ledger_ms=2 policy_ms=0 sign_ms=1 total_ms=4\n```\n\n`outcome` is `minted`, `denied`, `timeout` when the deadline passed, or `shed` when admission\nrefused the request. `space` is the space the connect was for, which a process serving several\nspaces needs and a process serving one still writes, so operators parse one format. `req` is the\nuser key the broker generated for this connect. `cid` is the broker's client id,\nwhich the broker's own log lines carry as `cid:<n>`. `queue_ms` is the time spent waiting for a slot. `verify_ms` covers the request and bearer checks, `ledger_ms` the actor\ncheck and the issuance record, `policy_ms` the permission build, and `sign_ms` signing the user JWT\nand the response. A `denied` line adds `reason=\"<message>\"`, a `timeout` line adds `at=<step>` for\nthe step it was in, and a `shed` line adds `waited_ms=<ms> ahead=<n>`: how long the oldest waiting\nrequest had waited, and how many requests were queued or in progress. The line logs at `level=warn`\nwhen the request took longer than 500 ms or its outcome is `timeout` or `shed`. A request that fails\nthe provenance checks still gets no answer and logs why it was dropped.\n\nA hosted context sets its limits with `startAuthService({ ..., calloutLimits })`, where\n`calloutLimits` is `{ authTimeoutMs, maxInFlight, slowMs }`. `authTimeoutMs` (default 2000) must\nmatch the broker's `authorization { timeout }` in milliseconds: against a broker set to 10 seconds,\nthe default refuses at 1.75 seconds connects the broker would still wait for. `maxInFlight` (default\n32) bounds the requests in progress, and `slowMs` (default 500) sets when a line logs at warn.\n\n`cotal up --auth-timeout <seconds>` sets both sides for a CLI stack from one value. It renders the\nbroker's `authorization { timeout }` and starts the space's auth service with that timeout as its\ncallout deadline. The value is recorded with the root's broker policy, so a later `cotal up`\nrenders it again and passes it to the auth service again. Without it the broker config has no\n`authorization` block and the auth service uses the defaults, which match nats-server's. `cotal up`\ndoes not start callout replicas, so start each one with the same `--auth-timeout <seconds>` as the\nbroker config.\n\nA replica serves one space. `cotal auth-service --callout-only --spaces <manifest>` instead serves\nevery space a manifest names from one process, one callout lane each, which is how a host runs one\ncallout process rather than one per space. A lane holds its own connections, its own connect limits\nand its own signing keys, so one space's key never signs another space's response and one space\nlosing its store connection leaves the other lanes answering. The broker decides which lane sees a\nrequest: a lane's callout connection authenticates as its space's auth account, and a NATS account\nis a disjoint subject namespace, so another space's request cannot be delivered on it. See\n[`auth-service`](cli.md#server-daemons) for the manifest and how a space is added or removed while\nthe process runs.\n\nThe full auth service can be hosted the same way. `cotal auth-service --spaces <manifest>`, without\n`--callout-only`, holds one full service per space in one process: each lane holds its space's plane\nclaim, callout, connections, connect limits and capability, and serves that space's exchange and JWKS\non listeners of its own, so one space's request never reaches another space's keys. A lane hosts\nservice endpoints only when its manifest entry sets `serviceEndpoints`. A fence or a lost\nbroker connection stops that space's lane alone. Callout replica hosts listing the same spaces add\nevent loops for connect bursts, since one process answers callouts on one thread. Removing a space\nfrom every host's manifest and waiting for each host's `<manifest>.applied` stops all minting and\nconnect authorization for it while the other spaces keep serving.\n\n### Connect limits\n\nThe auth service limits how often each principal may connect, so one client stuck in a reconnect\nloop cannot spend the callout for everyone else in the space. It keeps a token bucket in memory for\neach actor (`owner.actor`), each owner and each client host. A bucket holds a minute's allowance and\nrefills at that rate. The defaults are 60 connects a minute per actor and 600 per owner. A bearer\nwhose signature verifies is charged to its actor and its owner, even after it expires. A bearer that\ndoes not verify is charged to the client host the broker reports, at 60 a minute. A connect passes\nonly when every bucket it draws on has one left, and a refused connect spends nothing. Each auth\nservice process keeps its own buckets for each space it serves, callout replicas included, so a\nspace served by several processes allows up to that many times each limit. A process serving\nseveral spaces keeps a separate set per space, so one space never spends another's allowance. A\nreplica limits at the defaults.\n\nThe callout checks the limits before it reads the ledger or records an issuance. A limited connect\ngets a signed denial whose reason starts with `RATE_LIMITED retry-after <n>s`, followed by the actor\nand owner or the host. Its `outcome=denied` line carries that reason with the `owner` and `actor`\nfields. The broker tells the client only `Authorization Violation`, so the exchange carries the typed\nanswer. While an actor or its owner is limited, `POST /exchange` for that actor answers 429 with\n`{\"code\": \"RATE_LIMITED\", \"retryAfterSeconds\": <n>, \"limit\": \"<bucket>\", \"error\": \"<sentence>\"}` and a\n`Retry-After` header of the same seconds. `limit` names the bucket that ran out: `actor` for that\nactor's own, or `owner` for its owner's, which every actor of the owner draws on. Both faces and\nboth arms answer it, and it does not count as a refused exchange. Only the full service serves the\nexchange, so only it answers 429. A callout replica refuses limited connects at the default limits\nfrom its own buckets. A hosted composition passes other limits to `startAuthService` as\n`connectLimits`. No flag sets them.\n\nThe clients read that 429 as a rate limit. A CLI command prints the service's sentence and exits 2\nunder `DEPENDENCY_UNAVAILABLE`. Its remedy names the same bucket as `limit`: only that actor is\nlimited, or the whole account is. Its `--json` error carries `RATE_LIMITED`, the seconds and the\n`limit` in `error.cause`. `cotal agent-bearer` prints the sentence and that remedy on stderr and\n`retry-after <n>` on stdout, and exits 2. The agent's endpoint runs it again when those seconds have\npassed, not before.\n\n### Enrollment redeem\n\nA remote owner may pre-mint a one-time enrollment for a seat that has no browser, TTY, or cached\nIdP login. The enrollment is a secret-bearing URL. The client performs one request:\n\n```http\nGET <enrollment URL>\n```\n\nIt sends no `Authorization` header and no request body. The URL must be HTTPS, except for plain HTTP\nto a loopback IP literal. The client redeems only an enrollment URL that is already in canonical\nform and contains none of `\\ @ ? #`. That is checked on the raw string before parsing, so every\nrewrite a URL parser would perform, backslash folding, userinfo erasure, scheme or host case\nfolding, default-port removal, dot-segment resolution, and short-host canonicalization, is a refusal\nrather than a redeem of a URL the owner never minted. Redirects are refused. The client never\nretries because a successful claim deletes the server-side token row. The token expires five minutes\nafter mint.\n\nSuccess is `200` with this JSON object:\n\n```text\nspace\nbrokerAccess { kind, ... }\nowner\nactor\nlifecycleUid\nactorToken\nsentinelCreds\nauthServiceUrl\nidp { url, issuer, audience }\nsubscribe[]\nallowSubscribe[]\nallowPublish[]\n```\n\nThe grant arrays are informational; the broker row remains authoritative. A stock-dialable\ndeployment also includes `server`, `tlsRequired`, `userAuth`, and optional `policy`, forming the same user-bundle\nsuperset that `cotal meshes add --user-auth-file` accepts. That lets a bare seat register the mesh\nfrom the enrollment response before launch. For `brokerAccess.kind: \"direct\"`, the stock `server`\nmust equal `brokerAccess.url` byte for byte or the client refuses the bundle before registration. A\ntunnel kind carries no dial address, so its `brokerAccess` is not compared to the operator-asserted\nstock `server` face.\n\nUnknown, expired, revoked, and already-used enrollments are intentionally indistinguishable. They\nall return `404 {\"error\":\"unknown, expired, or already-used enrollment\"}`. The client reports only\n`enrollment refused: unknown, expired, or already-used; ask the owner for a fresh one`. It does not\nguess which case occurred.\n\nAfter redeem, the seat stores only the normal remote user-mesh and agent material. The actor token\nis exchanged at `authServiceUrl` through the existing `agent-bearer --exchange-url` path. The\nenrollment URL is not logged, persisted, or forwarded into any child process, including the bearer\npreflight and harness.\n\nThe service starts with the broker, is torn down by `cotal down`, and holds the\ndata-account signing key for the callout (a running manager is the other standing holder, for\nthe creds it mints); the operator seed never enters it. It also owns the space's two authority\nstores (lifecycle records and the credential ledger), provisions them at boot, and refuses\nconnects it cannot credential-check against them; there is no fallback path. If it\ndies while the broker lives, re-running `cotal up` heals it, and a boot whose auth\nservice never became ready exits non-zero, so automation never reads a dead identity\nplane as success. Changing any public-listener flag requires `cotal down` followed by `cotal up`\nwith the new values; a refresh adopts an already-running auth service rather than silently replacing\nits listener policy. \"One per space\" is enforced, not assumed (SPEC §13.13): at boot the\nservice takes a broker-backed ownership claim, so a second same-space auth process refuses\nwith instructions instead of silently splitting the plane, and a crashed one's claim is\nreclaimed only once the broker confirms its connections are gone. That verdict is trusted only\non a standalone broker (a clustered one refuses the reclaim, since a partitioned member\ncould still hold them). If the claim's connections die mid-run, the service downs itself\nloudly instead of serving from a half-dead plane.\n\nThe service's own broker connections renew their credentials before they expire, at a random\npoint between half and four fifths of each credential's lifetime and at least a second apart\nwithin a space. Each reconnects onto its new credential at a moment with no request in flight.\nThe connect-credential reader opens a new connection instead, proves its stores on it, and only\nthen switches to it, so a renewal never denies a connect. The service also removes expired\nnative-key issuance evidence on a timer. A pass that fails because the store did not answer, as can\nhappen while a connection reconnects under load, is retried with growing waits and logged once, and\nthe service keeps serving. Evidence that does not parse stops the service and refuses its next start.\n\nCtrl-C on a foreground `up`, and a broker that exits under it, stop the service with the same stop\nbare `cotal down` uses for it. It holds the reservation `down` takes, so the auth stop of a\nconcurrent `cotal down` is refused while it runs, and it sends SIGKILL to a service that has not\nexited 15 seconds after SIGTERM. A legacy stack has no command that stops only the auth service.\n\n**Your agents are yours.** `cotal spawn` on a user mesh grants a managed actor under the\n*spawning operator's* owner and launches the agent with a bearer command instead of a\ncreds file. The agent exchanges its spawn-time secret for short bearers (five minutes or\nless). It renews each one at a random point between half and four fifths of its lifetime and\nmoves its connection onto the new bearer, so the broker never closes the connection for an\nexpired one. Agents started together draw different points, and two connections in one process\nfor the same space renew at least a second apart. An agent never presents an expired bearer: it\nrenews first. While renewal fails it retries with growing, randomized waits of up to a minute,\nand reports the failure once until renewal works again. A locally provisioned foreground launch\nrefuses an existing actor rather than rotating another launch's secret. Its exit and failed-start cleanup\nrevoke only the grant matching the launch's token and lifecycle. Broker-footprint deletion follows\na successful owned revoke; credential files are removed only while they still hold this launch's\nmaterial. Cleanup reports failures without deleting a successor's state. A crashed launcher can\nleave a grant that needs operator recovery. Remote foreground launches remove their own local\nmaterial but leave revocation to the issuer. Managed despawn follows the retirement sequence below.\nManifest deploys (`up -f`) stamp the logged-in owner into the launch, so those agents are yours too.\n\n**Despawn tears the lifecycle down, then frees the name.** When you despawn an agent, the manager\ndrives the *full* teardown of that lifecycle: it shreds the local credential files, revokes the\nagent's standing mint authority (its ledger row, so a copied token can no longer mint a fresh\ncredential), deletes its broker footprint (the lifecycle-keyed durables + read-ACL row), and asks\nthe auth service to *retire* the lifecycle (settle in-flight work, evict the departed credentials,\nrecord it retired). The name is held *reserved pending retirement* until **all** of that completes,\nthe broker-footprint cleanup, the standing-authority revoke, **and** the lifecycle retirement, not the\nretirement alone, so a same-name respawn in the gap is refused with\na plain reason and a retry hint rather than quietly handing the alias to a new agent while\nthe old lifecycle's teardown is still running. Only once the broker footprint is gone, the standing\nauthority is revoked, and the retirement is confirmed does the name free, and `cotal spawn <same-name>`\ngives you a fresh agent cleanly. This is what makes reusing an agent's name safe: the old lifecycle is\nfully torn down before the new one takes the alias. A local file that cannot be removed does not\nstop the rest of the teardown: the broker footprint is still deleted, the failure is reported, and\nthe name stays held. If the auth service is unreachable or the standing-authority revoke fails,\nthe despawn still stops the agent and *holds* the name. **A\nsame-name `cotal spawn` re-drives the whole teardown** and finishes it. Retrying the despawn has no\neffect because the agent is already stopped. The operator copy tells you to recover the stack\n(`cotal supervise`) rather than reusing the name over an unretired predecessor.\n\nA failed spawn can also retire an orphan lifecycle without holding its name. Its retirement\nfailure names the lifecycle and reports that no hold reserves the name for it. A same-name\nspawn does not retry that orphan's teardown. A refusal from the auth service keeps its reason.\n\n**A crash mid-retirement resumes at the next boot.** The retirement's last two steps (recording the\nissuance gate terminal, then the lifecycle head terminal) are separate durable writes, and a crash\nbetween them leaves the gate retired while the head is still `retiring`: an alias that can neither\nmint nor be replaced. The auth service's boot crash-resume decides what it owes across *both*\nobjects (the gate *and* the alias head), so the next boot finishes that tail from the durable\noperation intent: nothing is re-revoked or re-drained, and a completed retirement (its head terminal\nlanded, or a successor already took the alias) is left skipped. A retry of the despawn converges on\nthe same recovery.\n\n**Delegation only narrows (the envelope rule).** A user's grant is their envelope:\neverything under their owner (their CLI, every agent they spawn, every agent those\nspawn) stays within its channel lists and its capability scope. Handing a role to a\nspawned agent needs the matching `role:<r>` capability in the spawner's scope. The whole\ndelegation chain is checked, not just the last link, and re-checked at every bearer\nexchange, so narrowing a user's grant reaches their agents within minutes, and revoking\nthe user revokes everything under them, grandchildren included. A spawn beyond the\nenvelope is refused with the exact widening re-grant to ask the operator for. One post entry is\nnot taken from the spawner's lists: a spawner whose grant covers its own event channel may hand each\nchild that child's own event channel, `events.<owner>.<child>`, and no other. It names the child, so\nit reaches nothing the spawner holds, and the spawner's own event channel is still checked against\nits parent.\n\n**Control ops ride your own login**, gated by ledger scope. `spawn` covers launching,\n`ps`, and stop/attach of the agents under **your own owner**: the owner is the\nadministrative boundary of its own subtree, so you (and your agents) manage what you own\nwithout any extra grant. `admin` is the explicit opt-in for touching **other owners'**\nagents; it is never part of a default grant and never accepted from a manifest.\n\n**Elevated operator surfaces ride the same login** through a short-lived *view*: the\nexchange stamps a server-authored view claim into the bearer, and the callout mints that\nconnection as the matching non-agent profile instead of `agent`. The older embedded dashboard\npath and `cotal console` ask for the read-only admin view, `clean history` for the purger,\n`channels set/default` for the channel-writer (all gated on ledger scope `admin`);\n`up -f` deploys over the deployer view, gated on `spawn`, because deploying your own team\nis spawn-grade (the manager still refuses a manifest claiming another owner). Elevated views exist\nonly on a signed-in human exchange. The `manager-caller` view is the one managed-exchange exception\nbecause it narrows the agent's existing manager command set to one server-selected instance and adds\nno capability. All views are authorized against the fresh ledger row at every connect and expire\nwith the bearer, so narrowing or revoking a grant bites within minutes here too. On the public\nexchange face only `channel-writer`, `channel-purger`, `manager-caller`, `session-caller`, and\n`transfer-writer` are served; `admin`, `purger`, `deployer`, and `manager-service` remain loopback-only.\n\nThe `session-caller` view is how `cotal attach` opens a seat's session on a user-auth mesh. It needs\nno ledger scope, because the session grant is the authority. The exchange takes the grant with the\nlogin proof and leader-reads the redeemed `session.<id>` row. It issues the bearer only when the row\nis active and unexpired, its signature equals the presented grant's, its holder is this owner and\nactor at this lifecycle, its endpoint and serving epoch match, and the serving manager's gate is open\nat that epoch. The callout repeats the same check at connect and mints the session's caller rails\nwith the grant's expiry instead of the bearer's.\n\nThe `transfer-writer` view is how `cotal spawn --resume <id> --detach --on <instance>` uploads a\nsession this host holds on a user-auth mesh. It needs scope `admin`, as the `transcript-receive`\ncall it serves does, and names one object: the target instance and the transcript's SHA-256. The\ncallout mints writes to that object of that instance's transfer bucket and nothing else. The bearer,\nand with it the broker connection, lives at most five minutes, the lifetime of the static\n`transfer-writer` credential, and never past the login proof it was exchanged for.\n\nThe `dm-reader` view lets an embedding read one user's own DMs while that user's app is closed,\nfor example to send a content-free push. The callout mints three publish rows on the user's own\n`dm_` durable (consumer info, next message and its ack subtree) plus the connection inbox, and\nnothing else. The view needs no ledger scope and is loopback-only.\n\nIt rides only a purpose-bound proof from the same IdP. Set `dmReaderAudience` in the space's IdP\npin to an audience the IdP mints only for these proofs. It must differ from `audience`, and nothing\nderives it. The proof carries `purpose: \"dm-reader\"`, `actor`, `lifecycle` and `space`. The\nexchange accepts it only for `view: \"dm-reader\"` with the same actor, the actor's current\nlifecycle and this space. Every other door that takes a human proof refuses it, and the ordinary\nverifier now refuses any token that carries a `purpose` claim. The issue that proposed this listed\nfive verifier call sites; this release has eight routes that take the proof, and all of them are\ncovered. The bearer and its connection expire no later than the proof, so set the proof's lifetime\nto cover your own grant and session expiry.\n\n### Remote manager authority\n\nA registered user remains an ordinary `agent` bearer by default. Running a detached manager\non a remote user-auth mesh needs the closed server-authored **`manager-service`** view, which\nis distinct from every general-purpose profile. The operator grants it only by adding\n`supervise` to that user's actor-ledger scope. `supervise` is deliberately distinct from\n`spawn` and `admin`: spawn controls your agents, admin permits the separate cross-owner\noperations, and neither grants persistent manager registration authority.\n\nOnly a signed-in human may request this view from the loopback/operator exchange. The public\nexchange and every managed-agent secret exchange refuse it. At exchange and each connection,\nthe auth service re-reads the actor row; revoking or removing `supervise` therefore denies the\nnext view exchange and connection. A grant must carry the whole requested row just like every\nother actor update, so re-grant its channel envelope, role, and all wanted scope tokens, not\nonly `supervise`.\n\nThe service is one opaque manager instance for the user's derived owner and a fixed\nserver-selected manager actor. Its authority is limited to that instance's manager\nregistration, contracts, status, endpoint rails, gate and credential family; it cannot read or\nwrite another owner or instance. It never exposes a signer, static provisioner credential, owner\nsecret, raw stream/KV/consumer authority, or a generic credential-mint API. The host creates the\npublic-nkey JWT material through the typed lifecycle-bound protocol: **prepare → activate →\nrenew**, plus host-owned **evict-family-principal** and **reconcile-registration** maintenance\noperations and a one-shot **retire** phase for one exact managed lifecycle. Each request is replay-safe and idempotent at its lifecycle/instance operation\ncoordinate; the host writes its credential ledger row and finalizes the gate before it releases\nusable material. The retire phase fresh-checks the current manager instance, server-derived serve\nprincipal, serve epoch, same-owner target and lifecycle UID. It returns only a short-lived requester\ncredential pinned to that target. The manager invokes the registered `auth` endpoint's\n`retire-lifecycle` command through the generic client, resolving the service and calling it with\nan exact target and the operation id derived from the target lifecycle UID. The endpoint\nrecomputes that id from the broker-pinned target before any durable access. A caller cannot\nsubstitute another valid operation identity for the same target, and retries plus auth-service\nboot recovery finish the same terminal barrier. It never exposes the barrier executor or a general mint surface.\n\nRegistration maintenance stays on the host. One eviction request carries up to 256 holders, and the\nhost accepts it only when its single sealed scan of the caller instance's\n`epcred.manager.<instanceId>.*` family finds every one of them. Reconciliation may\ntarget a foreign manager slot holder in the same space, but it runs only after the delivery daemon\nproves the frozen gate's holder gone under a complete sweep. The participant receives neither an\nevictor credential nor authority over another instance's records or gate. A clean stop refreshes an\nunhealthy executor before deregistration. A restart verify-evicts its old family, and a manager\nblocked by a foreign governance slot whose holder's gate is still frozen at the slot's stamp asks\nthe host to reconcile that holder and retries the registration once. The goal-writer and session-ledger\ncredentials carry a random `issuance:` tag, so a restart that re-mints them within the second of an\nearlier issuance gets new ledger rows and never re-signs a credential its barrier revoked.\n\nA remote manager can provision only descendants of the same derived owner, and the host\nvalidates that relation and the current manager grant for every provision. It cannot broaden the\nuser's envelope or provision a sibling owner's agent. Renewals are bounded. If login, the\n`supervise` grant, or the host manager authority service is unavailable, the manager reports a\ndegraded state and refuses new agents, restarts, or replacement credentials rather than\nsubstituting local/static authority. Existing live agents remain running only while their own\nvalid authority permits it; recovery requires the host service and a fresh successful renewal.\n\nThe manager-authority protocol is closed, so a host whose auth service predates a field the\nmanager sends refuses the whole request. The manager reports that refusal as version skew after the\nhost's reason: it names its own Cotal version and the refused field, and says it needs a host at\nthat version or later. It never drops the field to fit the older host. Upgrade the host first;\n[Upgrading](UPGRADING.md) promises no rolling upgrade between versions.\n\nA manager on remote authority mints from that authority alone; it consults the local root's\nrecords only to refuse a conflict, and only the supervised space's own trust records count as\none. A workspace that hosts an unrelated static space beside the participant sign-in is a\nnormal configuration.\n\n**User authentication has one path.** On a user-auth space, commands never fall back to\nstatic minting or credless connects: a missing login or a down auth service is one\nsentence naming the exact recovery, and static agent/observer/admin minting is refused\noutright. The refusal is deny-new: a static cred signed before the space flipped stays\nbroker-valid until the signing key is rotated ([security model](security.md)).\n\n### Held agent names\n\nA host answers a managed enrollment or an agent provisioning for a name another lifecycle holds\nwith HTTP 409, and nothing is enrolled or provisioned. The stock auth service answers\n`{ \"error\": \"<reason>\" }`. A host that knows more answers a typed body:\n\n```json\n{ \"error\": \"<reason>\", \"code\": \"AGENT_LIFECYCLE_HELD\",\n \"held\": { \"agentId\": \"<registration id>\", \"lifecycleUid\": \"<uid>\",\n \"custody\": { \"state\": \"known\", \"kind\": \"remote-manager\", \"managerInstanceId\": \"<instance>\" },\n \"presence\": \"offline\" } }\n```\n\n`custody.state` is `known`, `absent` or `unavailable`, and `custody.kind` is `foreground` or\n`remote-manager`. `presence` is `online`, `offline` when the agent is known to be absent, or\n`unavailable` when the host cannot tell. The client keeps that answer verbatim and passes it to the\nspawn as a `details` entry of kind `ai.cotal.auth.agent-lifecycle-held`, with the actor it was for.\n\nA mesh's agent-provisioning endpoint also releases one lifecycle, with the same login bearer.\n`GET <endpoint>` lists the caller's registrations as\n`{ \"agents\": [{ \"id\", \"lifecycleUid\", \"actor\", \"revoked\", \"connection\", ... }] }`, and\n`DELETE <endpoint>/<id>` revokes one: `{ \"ok\": true, \"removed\": true }`, or\n`{ \"ok\": true, \"removed\": false, \"alreadyRevoked\": true }` for one already revoked. A 404 is a\nregistration it does not have and a 503 is a release it could not confirm. The client releases only\nthe unrevoked registration at the one lifecycle it was asked for, and refuses when the list holds\nmore than one. A revoked registration may still be retiring, so the name it held can stay refused\nfor a while after the release. [`cotal spawn`](cli.md#spawn) and `cotal auth retire` use this\nrelease.\n\n## The IdP callout contract\n\nAny OIDC identity provider that issues **EdDSA/Ed25519** JWTs plugs in here directly; a provider that\nissues RS256 or ES256 tokens (many managed OIDC services do) needs a host-side normalization or\nre-issuance adapter first, because the reference bridge pins the token algorithm to EdDSA. The\nreference implementation ships **Better Auth** as a\ndev and test fixture only (it is a `devDependency` of `@cotal-ai/auth`; the only code that imports\nit is the `dev-idp.ts` harness and the smoke tests, never the runtime `src`). The one runtime\ncoupling to an IdP is the `idp.ts` bridge plus the `auth-provider` extension. The bridge core\n(`createIdpBridge`) is IdP-generic for **EdDSA** tokens (issuer, audience, JWKS as configuration).\nThe stock end-to-end flow around it, though, is **Better-Auth-shaped**: `cotalAuthProvider` pins\n`<base>/jwks` and issuer/audience to the IdP origin, and the login client speaks Better Auth's\ndevice-code endpoints (`/device/code`, `/device/token`, `/token`) with an opaque revocable session.\nSo a Better-Auth-shaped EdDSA IdP uses the stock flow directly; **any other production IdP is a\nhosted-composability gap, not a configuration change**. A host integrates it by building its own\nlogin and provider wiring on the low-level primitives (`createIdpBridge`, `createUserTokenIssuer`),\nnot by reusing the stock provider. Note that importing `@cotal-ai/auth` self-registers\n`cotalAuthProvider`, and `resolveAuthProvider()` throws when two providers are registered, so a host\non the registry-resolution path must not also register its own. Whatever the path, never loosen the\nissuer/audience/JWKS pins to force-fit an IdP.\n\nA provider participating in reviewed local identity reset declares its secret\nkeys through the optional offline `deprovisionSecretKeys(space)` inventory.\nThe stock provider shares that list with `deprovisionSecrets`. The inventory\nreturns keys only and performs no deletion or secret read. A provider without\nit, or with keys outside the selected space's secret segments, cannot use that\nreset route. Hosted deprovisioning remains a separate composition.\n\nThe bridge (`createIdpBridge`) exchanges a verified IdP token for a Cotal bearer in three steps:\n\n1. **Bearer validation.** Verify the IdP's JWT offline against its **pinned JWKS**, with the token\n algorithm pinned to EdDSA. Keys resolve only through the pinned JWKS: a token carrying embedded\n key material (`jku`/`jwk`/`x5u`/`x5c`) is rejected, so the token can never influence key\n resolution. Issuer and audience are checked. The minted Cotal bearer never expires after the\n upstream proof: the issuer signs the earlier of the requested lifetime and the proof's `exp`,\n read when it signs, and refuses once the proof has expired. Time spent in the bridge's hooks\n shortens the bearer instead of extending it.\n2. **Owner derivation.** The opaque per-space owner derives deterministically from the JSON-array\n encoding of `[idp issuer, sub]`, namespaced by issuer so no issuer/sub pair can straddle a\n delimiter, and re-login re-lands the same person in the same lanes. The owner-token *format*\n (`u_` followed by 26 base32-lower characters) is normative\n ([SPEC section 2](../SPEC.md#2-identity)). At the contract level the *derivation* from an\n identity is a pluggable edge, but the reference `createIdpBridge` fixes it\n (`deriveOwnerForIdpSubject`) and takes no derivation callback, so what a host configures is the\n IdP, not the derivation. **The encoding is frozen:** changing it, or changing the IdP issuer\n string, re-keys every owner in the space, which is a migration on the order of rotating the space\n secret.\n3. **Actor authorization and mint.** The operator's ledger hook authorizes the `(owner, actor)` pair\n and is the only source of the bearer's `scope`/`parent`; the issuer then mints the Cotal bearer,\n re-asserting every claim shape.\n\nA host wires this with the IdP's own coordinates and nothing from `@cotal-ai/auth` changes:\n\n```ts\nimport { createIdpBridge, pinnedJwksResolver, createUserTokenIssuer } from \"@cotal-ai/auth\";\nconst bridge = createIdpBridge({\n idp: { issuer: idpIssuer, audience, key: pinnedJwksResolver(jwksUri) }, // your production IdP\n space,\n spaceSecret, // identity-plane owner-derivation secret (>=32 bytes), held by the auth service at runtime\n issuer: createUserTokenIssuer({ issuer: cotalIssuer, key: signingKey }), // mints the Cotal bearer\n authorizeActor: (owner, actor) => grantFromLedger(owner, actor), // your ledger, returns an ActorGrant\n});\n```\n\nFor private-result consent, `verifyToolResultHumanProof` applies the separate password-freshness\nrule to the same pinned signature check. A signed integer-second `auth_time` must be no later\nthan the decision and at most 300 seconds old, and signed `amr` must contain `pwd`. Neither a\nrecent JWT `iat` nor a session's creation time supplies password provenance. Missing, malformed,\nfuture or stale provenance refuses this decision without changing ordinary bearer exchange.\nThe host-only proof door and the remaining activation limits are documented under\n[private tool results](embedding.md#private-tool-results).\n\n## Joining\n\nA single **join link** carries server, auth, and space\n([SPEC §10](../SPEC.md#10-connection-and-onboarding)):\n\n```\ncotals://<token>@host:4222/<space>?channel=general # cotals:// = TLS required; cotal:// = TLS not required (downgrade-tolerant)\n```\n\nHumans: `cotal join --link …`. Agents: `COTAL_LINK=… ` in the environment. The connector\nexpands it and auto-joins. Token/user-pass links are the open-mode path; the default\nauthed path threads a minted creds file, and the endpoint adopts the credential's identity\nas its card id. A seat the manager spawned reaches that file through its **launch\nmaterial** rather than through `COTAL_CREDS` in an environment every descendant process\ninherits (see [Configuration](config.md#launch-material)); a session you drive by hand\nstill sets `COTAL_CREDS` itself.\n\n## Honest limitations (v0)\n\n- **The signing key is hot** on the mint/manager box of a static-auth mesh; the \"real\n boundary\" holds given operator-controlled cred distribution. On a per-user-auth mesh\n the data-account signing key is held by the auth service (the callout stage) and by any\n running manager, which loads the trust bundle and self-mints its supervisor cred and\n renewals from it; a copied signing *seed* still stays valid for its identity until the\n signing key is rotated. Rotation remains the revocation lever for trust material.\n- **The two `$SYS` creds renew through rotation.** `membership-observer` and\n `connection-evictor` are signed by the system-account seed. The trust record is written without\n it; the root keeps the seed in its own secret-store record for own-broker caller issuance only,\n and no running process re-signs these two creds in place: they carry a 30-day expiry and are renewed by issuing a new\n system account (`cotal down` then `cotal up --rotate-sys`), which leaves the data account,\n every agent cred and the store untouched but does invalidate earlier full backups (they bind to\n the operator JWT and system account they were taken under, so re-run `cotal backup` after). Past that horizon the mesh keeps delivering, but the\n membership feed and live eviction stop; `cotal doctor auth` and the manager warn from the 75%\n point onward. A host that keeps a registered system signer can re-mint the observer into the\n delivery daemon's secret store instead: the feed reads it again at 75% of its lifetime, proves it\n on a throwaway connection, and adopts it only when its issuer and permission scope match the\n cred it started with.\n- **A copied static agent cred outlives its session.** One-shot command creds expire in\n minutes and the standing daemon creds in 24h with the manager renewing them (`cotal doctor\n auth` is the one diagnosis and repair surface). A manager-spawned agent cred also expires\n after 24h, the manager renews it only while the agent is live, and despawn retires it. A\n static mesh has no auth callout, so a compromised agent that copied its creds can still\n reconnect until they expire. An out-of-band `cotal auth mint` cred lasts 24 hours unless a\n lifetime flag says otherwise, and one minted with `--no-expiry` stays valid until its key is\n revoked or the signing key is rotated ([security](security.md)). Per-user-auth spaces\n close this: bearers live minutes, `cotal actor revoke` denies the next exchange and the next\n connect and evicts the principal's live connections immediately.\n- **Not non-repudiation.** Authenticity is broker-enforced, not portable proof; it does\n not survive an untrusted relay. Signed envelopes are reserved\n ([SPEC §11](../SPEC.md#11-versioning-and-extensibility)).\n- **Chat metadata leaks in-space.** Content reads are ACL-bounded; stream metadata\n (channel names, per-subject counts) is not yet ([security model](security.md)).\n\n**Denials are loud, never silent.** A publish outside an ACL surfaces as a logged denial\n(\"denied, not absent\") on the endpoint's error path; an over-tight ACL never looks like a\nmissing peer ([run a mesh](run-a-mesh.md)).\n\n## Standalone endpoint callers\n\n`auth mint <name> --endpoint <class> --out <private-file>` provisions the ordinary native agent\nfootprint with explicit endpoint request rows from a fresh digest-verified surface. This route\nrequires the selected local static signing authority and retains the registered broker TLS policy.\nOnly untargeted synchronous ephemeral surfaces are supported; targeted, journaled and action\nsurfaces refuse instead of receiving guessed or incomplete authority. The native baseline remains,\nbut no spawn, run or admin capability is added. Explicit channels enter both read and post ACLs.\n\nA private create-only issuance intent precedes native footprint work and blocks blind replay after\ninterruption. The intent contains no credential and proves no submission/completion. The resulting\ncredential is private and is not a managed seat. The endpoint describe/invoke routes consume\nits paired private intent only after native signature/current-issuer, user-key, time-window,\npermission-builder and principal-tag checks. Broker admission remains a separate requirement.\nThe intent selects coordinates; it is no wire grant, accepted-generation proof or live lifecycle\ncheck. Arbitrary raw files, different profiles and issued-generation files are not reinterpreted.\nUser-auth issuance and managed launch remain unsupported. See\n[the CLI limits](cli.md#endpoint-caller-credentials).\n"
54
+ "body": "# Identity\n\n> **Concept** (informative) · **For:** operators and implementers · **Normative:** [SPEC §2](../SPEC.md#2-identity), [§9](../SPEC.md#9-nats--jetstream-security-and-authorization), [§10](../SPEC.md#10-connection-and-onboarding), [Appendix B](../SPEC.md#appendix-b-profile-acls)\n\nWho can do what on a mesh, and how it is enforced. The design goal: the mesh is a **real\nboundary against untrusted peers in a shared space**; an agent can only speak as itself\nand only where its declared permissions allow, enforced by the broker, not by agent\ngoodwill. What that boundary does and does not protect is the\n[security model](security.md); the exact ACLs are\n[SPEC Appendix B](../SPEC.md#appendix-b-profile-acls).\n\n## On by default\n\n`cotal up` provisions a JWT-authed space; `cotal up --open` runs an unauthenticated dev\nmesh instead. Both bind loopback by default. `--host 0.0.0.0` widens the bind\nindependently, so \"network-reachable\" never silently means \"unauthenticated\". Open mode\nis for quick local experiments and sits outside every security claim\n([SPEC §9](../SPEC.md#9-nats--jetstream-security-and-authorization)).\n\n## Shared identity\n\nAn agent's wire identity is a **principal**: an `owner.actor` pair, where the owner is\nthe account (a human, or an organization) the agent acts on behalf of, and the actor is\nthe agent's own handle under that owner ([SPEC §2](../SPEC.md#2-identity)). The same pair\nis the card id, the sender tokens in every subject it publishes, the presence key, and\nits durable-consumer names. On an open dev mesh the owner is the literal `local`; on a\nper-user-auth mesh it is a derived token (`u_` plus 26 characters, so no PII rides the\nwire). The connection still authenticates with an **nkey**, generated locally (the signer\nonly ever sees the public half), but the nkey is the transport credential, not the\nidentity: it scopes only the per-connection reply inbox.\n\n**The sender is encoded in the subject.** Every publish carries the sender's owner and\nactor in positions the broker's permissions pin to that connection, so an agent *cannot*\nemit as anyone else: not as another owner, and not as a sibling actor under its own\nowner. Receivers verify the payload's `from.id` against the subject sender and reject\nmismatches; sender authenticity is broker-enforced end to end\n([SPEC §3](../SPEC.md#3-subject-layout), [§5](../SPEC.md#5-envelopes)).\n\n**Account = space, user = agent.** A space is one NATS account, a server-enforced\nisolation boundary. An operator signs the account; an account **signing key** mints\nper-agent user JWTs.\n\n## Provisioner\n\nThe **provisioner** is whoever holds the account signing key. It mints profile-scoped\ncredentials and pre-creates the durables agents may only *bind* (their DM inbox, their\nrole's task queue). The manager hosts it today, but nothing is manager-special about it;\nprivilege attaches to the signer, and a space can run without a manager.\n\nUser-credential and auth-callout JWT signing uses Node's native Ed25519 implementation. NATS\nlibraries still encode keys and JWTs. The signer produces the same signature bytes for the same key\nand payload; permissions, expiry and issuer checks are unchanged. The auth callout also verifies\nthe broker's signed request with Node's Ed25519 rather than the NATS library's JavaScript curve,\nwhich cost several milliseconds per connect. It makes the same checks: a NATS JWT header, a public\nnkey issuer with a valid checksum, and that issuer's signature.\n\nThe temporary native provisioner can request `$SYS.REQ.USER.INFO` for its own connection.\nThe broker's configured system account maps the service to that requester. The reply can bind\nits public user/account and serving server to the local pins without a system credential.\nIt is not an effective permission ceiling, issued generation, lifecycle or apply authorization.\nAn unavailable or denied service does not trigger another credential or server fallback.\n`cotal auth mint <name> --profile <agent|observer|admin>` is the out-of-band path; spawn calls\nthe same library ([CLI](cli.md)). The out-of-band profiles last 24 hours unless\n`--expires-in <seconds>` or `--expires-at` sets another lifetime, and a standing-renewal consumer\nrequires a bounded credential. `--no-expiry` issues one with no expiry, which `cotal doctor auth`\nreports as a warning; it reports any other unbounded credential as a finding. `--replace` replaces a\nlabel's credential once it has expired, when it has no expiry, or when `auth revoke-credential`\nrevoked its key. `--identity <creds>` reuses a file's nkey and principal,\nbut the out-of-band agent mint allocates a new lifecycle UID. It does not reuse the old\nbind-only inboxes; clients must use the UID in the receipt and explicitly provision it when\nneeded. Minting static creds is a\n**static-auth** surface: a\nper-user-auth space refuses it, because agents there join under a logged-in user, never\nvia a handed-out file (see *Per-user auth* below).\n\nAgent-profile minting resolves one mesh root for the persona ACL, account signer and default\ncredential storage. If the current folder holds trust for a different space or account, mint\nrefuses and names both roots. It never signs one root's persona policy with another root's authority.\n\n## Profiles\n\nEvery credential is a profile: an explicit allow-list built from the same\nsubject/stream/durable builders as the wire layout, so ACLs cannot drift from it. The\nnormative shapes are [SPEC Appendix B](../SPEC.md#appendix-b-profile-acls); in brief:\n\n| Profile | Is |\n|---|---|\n| **agent** | The ordinary peer: publishes as itself to its declared channels, reads within its read ACL + its own DM/task inboxes. It reads the roster on demand with a Direct Get of the presence bucket, which binds no consumer. Its channel-registry watch, and the presence watch older seats hold, create and inspect client-managed ordered consumers but cannot delete any consumer on those streams; the broker removes a finished watch's consumer five minutes after its last interest. |\n| **observer** | Read-only chat + presence; DMs invisible. What `cotal console` runs. Its only consumer deletes name its own history readers (`hist_<readerId>_<n>` on CHAT, keyed on its nkey or on the connection the server assigned), so each history read removes its consumers when it ends, and it cannot remove another principal's watch or the delivery daemon's fan-out consumer. The broker removes its finished watch consumers. |\n| **admin** | Elevated *read-only* god-view: sees DMs and anycast live, still writes nothing. A deliberate opt-in for elevated operator observation. Deletes its own history readers on CHAT and DM, and no other consumer. |\n| operator-side | Narrow single-purpose creds for the machinery (supervising, provisioning, teardown, delivery); the reference implementation splits these so no one connection can read every DM *and* delete every stream ([security model](security.md)). |\n| **run-driver** | One workflow run and takeover attempt: its journal subject, replay durable and run-owned record writes. Store reads and effects go through the host. |\n| **run-mediator** | The trusted hosting process's separate connection for workflow effects and leader reads. It exposes journal-checked, run-bound operations and never hands its credential to the driver. |\n| **run-operator** | One served run read, or one half of an answer, minted per call: a read holds the records walk, one run's replay and the admission read; the answering half is minted for one checkpoint token and holds that pause's answer record and settle alone. |\n| **issuer** | One issuance window: the party holding the space signer mints it for a few minutes to stage and release a credential's evidence, retire the issuances a lifecycle terminal leaves behind, or resolve the evidence a request rides. The auth service, and each callout replica, holds one of its own for the issuance its callout makes on a user-auth connect. It replaces that session before its five-minute credential expires and closes it with the service. |\n| **run-admitter** | One run's admission record or revocation marker, minted per run for a minute: two exact keys in the admission store and nothing else. |\n\n**An agent's channel scope is three verbs**: `subscribe` (reads at boot),\n`allowSubscribe` (read ACL), `allowPublish` (post ACL, default-deny), declared in its\n[agent file](agent-files.md) or [manifest](manifest.md), minted into its cred. One card\nwith the recipes: [Channels & permissions](channels-and-permissions.md).\n\n**DM confidentiality** holds against peers by construction: deliveries ride per-identity\ninbox prefixes, and the DM/task consumers are provisioner-pre-created and bind-only, so an\nagent cannot create a consumer filtered to someone else's inbox\n([SPEC §9](../SPEC.md#9-nats--jetstream-security-and-authorization) items 1–5).\n\n## Issued authority\n\nA credential says who is calling. It does not, by itself, say what the caller was granted, and a\nhost that acts on a caller's behalf (a workflow run, [workflows](workflows.md)) needs that from\nthe issuer, not from a ledger that may have changed since. So a static agent credential is an\n**issuance** ([SPEC §13.15](../SPEC.md#1315-issued-authority)): before the material is handed\nout, the issuer records the credential's final permission ceiling, as evidence keyed by a fresh\n**generation**, in `cotal_issued_<space>`. That store is append-only at the broker until a row's\nown TTL ends it, and the evidence is read as the first message on its key, so nothing written later\non the same key, by anyone, changes what a resolver sees. The credential's endpoint rows then ride a versioned\nrail, `cotal.<space>.ep.v1.…`, with that generation pinned beside the caller triple, so the\nbroker binds every request to the ceiling the issuer accepted. The legacy `ep.` rail and the\n`ep.v1.` rail are disjoint subject spaces; a credential holds rows on one of them, and every\nendpoint serves both.\n\nA connected client learns its generation by reading one row in `cotal_accepted_<space>` under a\ntoken the launching party chose at mint time, through a per-key read grant its own ceiling carries. It never trusts\nwhat the file says. A renewal keeps the generation only while the ceiling is byte-identical to the\nevidence; a changed scope is a fresh issuance on a fresh generation, adopted by a new connection.\nA static agent's evidence names its credential ledger family as the source it depends on, and the\nlifecycle terminal that retires that family retires its issuances with it.\n\nIssued rows do not last forever. A generation carries its **horizon**, the second from which it\nauthorizes nothing: the bearer's expiry for a user-auth `manager-caller` view, the instrument's\nfive-minute expiry for a control-caller instrument, the assignment expiry for a platform\nsupervisor, and 30 days after spawn for a static agent. Every row of a generation in both stores\nis written with a NATS per-message TTL that removes it 60 seconds after the horizon, so the stores\nhold the generations that can still be used, not every exchange ever made. Every host refuses a\ngeneration at or after its horizon before it reads the store, so a row the broker removed, and\nanything written on its key since, is never read. A static agent's credential renewals stop at its\nhorizon, and the agent is then respawned; rotating it onto a new generation instead is\n[#4942](https://github.com/Cotal-AI/Cotal/issues/4942). On a user-auth space the auth service is\nthe only issuer, so that cap does not apply there.\n\nA space whose issued stores were created before this retention existed is refused by every service\nthat binds them, with the remedy in the error. Stop the space's auth service, its callout replicas\nand every manager, then start the space with `cotal up --space <space> --recreate-issued-stores\n<backup-dir>`. It backs up `KV_cotal_issued_<space>` and `KV_cotal_accepted_<space>` into\n`<backup-dir>`, deletes them, and the start creates them again in the current shape. An embedder\nwhose spaces `cotal up` does not start runs the same step ([Embedding](embedding.md)). Generations\nissued before the upgrade refuse afterwards, and static agents started before it are respawned. The\norder and the rollback limits are in [Upgrading](UPGRADING.md#issued-authority-stores-after-01110).\n\nThe manager, `cotal spawn`, and the CLI's control-caller instruments all mint through an `issuer`\nsession. The deployer instrument does not: it is the one instrument with no default expiry, and an\nissuance with no lifecycle gate must carry one, so a deploy rides the legacy rail under its own\nlifecycle uid. Only workflow `run-start` and the keyed `run-start-keyed` and `run-submission-status`\nrequire the binding today: a request for one of them on the legacy rail is refused with\n`permission-denied` and the detail `ai.cotal.ep.unbound-caller-authority` naming the caller.\nEvery other command serves both rails.\n\nA user-auth `manager-caller` view is issued at the auth callout for an interactive row, or for a\nmanaged seat whose current persona-derived scope contains `run` and whose direct parent's fresh\nsame-owner grant also contains `run`. An admin parent's containment bypass does not count. The\nsingle source is the child's own actor row and lifecycle, and evidence records the signed ceiling\nwithout adding capabilities. Same-nonce renewal requires the same triple and byte-identical ceiling.\nThe existing view policy and manager instance gate are unchanged, with no new request kind. A seat\nmissing either `run` input keeps ordinary legacy commands. Without signed `run`, the broker refuses\n`run-start`; with signed `run` but no eligible parent, the manager refuses with\n`ai.cotal.ep.unbound-caller-authority`. A failed issuance never retries on that rail.\n\n## Declared capabilities\n\nControl-plane power is a **declared capability**, not a default. An agent file carrying\n`capabilities: [spawn]` gets the privileged control subject minted into its cred: spawn,\nplus stop/despawn of its *own* children, plus persona definition. On a static or open mesh its own\nchildren include what it launches with `cotal spawn --detach` from its own shell, since that\ncommand runs as the seat. Without it, an agent can\nonly self-despawn and pull or yield the run turns addressed to it. `capabilities: [run]` mints\nthe manager's workflow-run commands (start, resume, answer, status, list) together with the spawn\nset, since a program the agent starts may spawn; the manager drives the run under a per-run\n`run-driver` credential of its own, never the caller's. The tool surface mirrors the grant:\n`cotal_spawn` / `cotal_persona` / `cotal_personas` are injected only for `spawn`, and `cotal_run`\nonly for `run` ([agent files](agent-files.md)). Destructive\noperator ops (history purge, cross-agent stop) live on a third tier no agent credential\nreaches. Persona redefinition separates content from policy; the write path takes only\n`model`/`persona`, so a peer cannot grant itself a capability by redefining a file.\n\n## Per-user authentication\n\n`cotal up --user-auth --idp <auth base URL>` (or manifest `broker.auth: \"user\"`) puts a\n**human identity plane** above the per-agent one: people sign in to an external IdP once,\nand every connect is authorized live against the operator's **actor ledger**. No creds\nfiles to hand out, and revoking a grant actually bites.\n\nThe first enable pins the space to that IdP. A later `--idp` naming a different IdP is refused,\nbecause the IdP is part of every derived owner. Two first enables that race on one state dir leave\none pin: the other caller adopts it when it names the same IdP and is refused when it does not.\n\n**The flow.** Each person runs `cotal login --idp <url>` once per machine. The IdP URL, the JWKS\nURL pinned from it and the catalog link below must use HTTPS. Plain HTTP is accepted only on a\nloopback IP literal such as `127.0.0.1`, never on `localhost`, whose resolution would choose the\nkeys the mesh trusts. After that,\nany command works: cached IdP session → IdP proof, fetched per connect and reused in memory for\nat most a minute (so IdP-side revocation bites within a minute) → the configured exchange turns it\ninto a short-lived Cotal bearer →\nthe broker's **auth callout** checks the bearer and the ledger at connect time and mints\na scoped credential on the spot. Every bearer also names a **root credential** row in the\nspace's credential ledger, proved live at each connect, so revoking that one credential\nbites at the very next connect. The operator grants access with\n`cotal actor grant <actor> --sub <their id> --full` for the full envelope (all\nchannels; scope `spawn,role:default`, so it may spawn and may delegate the default role), or names\n`--scope`, `--allow-subscribe` and `--allow-publish` for a narrow row. A grant with any of the\nthree left off and no `--full` is refused.\nNo ledger row, no access; there is no allow-by-default.\n\nManaged grants record who holds the lifecycle: a local manager's persisted logical instance ID,\nan authorized remote manager's instance ID, or a foreground launch with no manager. The trusted\nwriter supplies this custody record. Ledger reads, decisions and writes share one synchronous\ntransaction; broker provisioning and retirement run outside it. A grant that found no row refuses with\n`CONFLICT` when another grant for the same actor lands while it waits for the ledger lock. A re-grant\nor revoke whose actor row changes or disappears while its lifecycle retires ends `partial` (exit 4)\nwhen the auth service reports that this call retired the lifecycle: the lifecycle stays retired, the\ncommand writes and deletes nothing, and the error names the retired lifecycle under `changed`. When\nthe service reports that the lifecycle never started or was already retired, the same race refuses\nwith `CONFLICT`. A retirement answer without a readable result ends `unknown` before anything is\nwritten. Re-read `cotal actor list` before trying again. Old rows remain readable without\ncustody, but a custody-pinned operation refuses them rather than adopting them. This field does\nnot authorize recovery over another manager's or an unknown lifecycle.\n\nThe auth ledger also reserves a closed `chat-sessions/` row space. An interactive or managed\ngrant cannot reuse an alias present there, and a principal found in both spaces refuses.\nA pending chat row authorizes nothing.\n\n**User-mode chat sessions.** In a user-auth space the auth service can open chat sessions, the only\nidentities it creates on its own. A signed-in person opens a session with their IdP proof and the hash of a\nholder secret that stays in the client's memory. The service picks the session's actor\n(`chat_` and 26 base32 characters) and a fresh lifecycle UID. It pins the person's own `cli`\ngrant, keeps the session's read and post lists inside that grant, and fixes its lifetime at up to\n8 hours with no extension. Each bearer lasts at most 15 minutes, and never past the IdP proof or\nthe session. The service checks the session, the holder index and the pinned grant before and\nafter it signs one. A session connects as a plain agent with its own lists and no role, capability\nor view. A change to the person's `cli` grant refuses each open session's next bearer and connect.\nClosing a session retires its lifecycle before its quota slot is freed. The service also sweeps\nexpired and abandoned sessions and keeps a retired row for 24 hours after its expiry. A provider\nwithout the optional chat methods cannot open a user-mode session, and the client refuses with no\nother identity tried.\n\n**Static-mode chat sessions.** On a static-auth mesh the local manager admits a chat session\ninstead: it mints the session's own leaf under a fresh nkey and retires it through the static\nterminal, which cannot end the leaf at the broker before its expiry\n([control-surface.md](control-surface.md#static-chat-sessions)).\nThe participant presentation carries the resolved space in its session identity and shows that\nmesh in its human header and connection report. The session label does not choose the target.\nAn output-stream error stops new stdio input and requests session closure through the input-close\npath. A failed stdout cannot deliver the end record. When returned, the close report records the\nobserved connection status.\n\n**Space catalogs.** A successful authenticated `GET <idp>/token` may advertise one catalog with:\n\n```http\nLink: <https://idp.example/spaces>; rel=\"https://cotal.ai/relations/space-catalog\"\n```\n\nThe target must use HTTPS and the same origin as the normalized IdP URL. Loopback IP literals may\nuse HTTP for local development. A missing, foreign-origin, or insecure link records that this account\nhas no catalog. The client never guesses a path.\n\nThe catalog request carries the opaque cached session as its bearer and returns a complete snapshot:\n\n```json\n{\n \"v\": 1,\n \"account\": { \"idpUrl\": \"https://idp.example/api/auth\", \"issuer\": \"https://idp.example\", \"sub\": \"user-id\" },\n \"spaces\": [\n { \"id\": \"space-id\", \"slug\": \"shared_project\", \"name\": \"Shared project\", \"kind\": \"hosted\", \"role\": \"owner\", \"registration\": {} }\n ]\n}\n```\n\nThe client checks every `registration` with `checkBundleDocument`, the object checks `checkUserBundle`\nruns after it parses a file for `cotal meshes add`. The catalog already holds the value, so it is not\nserialised back to text: a missing `registration` is a missing field, and the not-JSON sentence stays\nwith a file or a discovery body that does not parse. One invalid entry refuses the whole candidate\nsnapshot. Conditional refresh uses the\ncatalog's `ETag`; a transport error, non-success response, or invalid candidate leaves the prior\nsnapshot intact and reports the failure. Only a 401 response for the saved session recommends signing\nin again. Transport errors and server failures report that account's refresh error without discarding\nthe session. The registry is reconciled under the provider's catalog lock, and a snapshot whose\nreconciliation was interrupted is reconciled again by the next refresh before it counts as fresh or\nnot modified.\n\nThe user-auth registration document may include one closed policy object:\n\n```json\n{ \"policy\": { \"events\": \"required\" } }\n```\n\nNo other key under `policy` and no other value for `policy.events` is accepted. The registry preserves\nthis field for manual, discovered, and enrollment-created entries. A pre-policy manual entry is\nrefreshed from its own pinned exchange origin by the command that consumes the policy, a spawn, a\njoin, or a manager start, after that command's own local refusals; the returned space, broker,\ntransport, IdP, issuer, audience, and exchange pins must all match before only the policy is added.\nA failed expired refresh refuses that operation. Read-only commands such as `status` and `meshes`\nnever refresh. The five-second warm window makes no request.\n\nEvery registration is also bound to the proved account. Its IdP URL must match the account and its\nissuer must match the exact JWT `iss` pin. Its exchange, provisioning, and manager-authority\nendpoints must be same-origin with that IdP. One foreign pin or endpoint refuses the whole\ncandidate snapshot.\n\nThe `slug` is the space identity resolved by `--space`, `use`, registry roots, and collisions. The\n`name` is a display label only.\n\nDiscovered registry entries are owned by the normalized IdP origin plus the proved `sub`. That key is\nstored as an opaque digest, so accounts on one machine never union their spaces and the registry does\nnot persist the subject. A manual or locally started record with the same name is never overwritten.\nLogout removes only the entries owned by the account whose session was revoked. Local teardown,\ncleanup, and liveness pruning do not remove discovered entries.\n\nAn account that previously advertised no catalog is checked again by explicit `cotal sync`. The\nordinary lazy path checks again after its five-second capability window, so an IdP can enable the\nLink for an existing login without making the person sign in again.\n\n**One auth service per space** hosts both halves: the NATS auth callout and the token\nexchange. One process may host the services of several spaces, one lane each (below). Its default HTTP listener remains loopback-only and requires the per-start capability\nstored in the owner-only `auth-service.json` file. An operator may add a second listener with\n`cotal up --user-auth ... --exchange-public-port <port> --exchange-public-url https://auth.example`.\nThat listener still binds `127.0.0.1`; put a reverse proxy in front of it and terminate TLS there.\nIn-process TLS is deliberately not another deployment mode: it would duplicate certificate renewal\nand fork proxy-based deployments.\n\n**Callout replicas.** `cotal auth-service --callout-only --space <s> --server <url>` runs one more\nmember of the space's callout queue group. `cotal auth-service` is a deprecated entry kept for\nexisting units and scripts; new setups use the `auth-service` service preset\n([deprecated daemon entries](UPGRADING.md#deprecated-daemon-entries)). The broker hands each connect to one member, so a\nreplica keeps connects answered while the full auth service restarts or crashes, and adds capacity.\nA replica runs the same connect checks as the full service and holds nothing else: no HTTP\nlistener, no `auth-service.json`, no plane claim, service registration, barrier, scanner or sweep,\nso it never competes with the full service for any of them. Its store connection reads\nthe auth, records and sessions stores and creates each connect's issuance row; it creates no store,\nmints no credential and writes no gate. Like the full service, it holds its own issuer session for\nthe connects that need issued authority. A replica reads the actor ledger in the space's state dir\nand the same secret entries the full service's callout reads, the bearer issuer key among them, so\nit runs only on a host trusted like the full service's. A replica that loses a store connection or\nthe broker stops answering and exits non-zero, and the broker sends later connects to the other\nmembers; restart it with the unit that runs it. It refuses the HTTP flags and `--service-endpoints`.\nA replica cannot issue a service-endpoint connection, so it refuses to start in a space that admits\nservice endpoints: one whose full service has run with `--service-endpoints`, or as a lane whose\nmanifest entry sets `serviceEndpoints`. That first run opens the space's admission and nothing closes\nit, so the refusal stays after the setting is dropped. A callout host serving several spaces names\nsuch a space, retries it every 5 seconds and keeps answering for the others;\n`admitsServiceEndpoints` from `@cotal-ai/auth` answers the same check for a manifest writer.\n\nThe loopback face also serves host-only doors, all capability-gated and never on the public face.\n`/managed-lifecycle/activate` asks this exact assigned account authority to activate one\n`{ owner, actor, lifecycleUid }`; its closed body also repeats `accountPublicKey`, which must equal\nthe context's assigned data account. It is served by an ordinary full auth service, including one in\na separate process, and does not require the optional in-process `platformControl` composition.\nTwo routes retire a lifecycle: `/interactive-lifecycle/retire` (used by `cotal actor grant/revoke`)\nand `/managed-lifecycle/retire`, which finishes a managed agent's terminal retirement after its\nremote manager is gone. The interactive door answers every refusal it makes before the retirement\nbarrier with `outcome: \"not-executed\"`. An error without that outcome may follow a barrier that had\nbegun, so `cotal actor grant` and `cotal actor revoke` report it as unknown. The third decides one:\n`POST /manager-service-authority/verify-enrollment` answers whether a remote manager may have a\nmanaged agent enrolled or released under its authenticated owner. The body is\n`{ owner, request }` and nothing else. The caller's capability scope is read from this machine's\nledger, never taken from the body, so a host that forwarded a participant-supplied scope could not\ngrant itself `supervise`. The door reads the manager gate and checks the registration proof inside\nthe service process, so no signing material reaches the caller, and it returns\n`{ authorized: true, owner, actor, instanceId, serveEpoch }` or maps its refusal to 400, 401, 403,\n409, or 412. It decides only. A platform that intercepts these requests owns every write, and stock\n`dispatchManagerAuthorityRequest` refuses both request kinds with `unimplemented` rather than\nanswering a manager-lifecycle phase for an agent-lifecycle request. The same door decides the hosted\nruntime create and status kinds. For those it reads the manager actor's ledger row itself and returns\n`{ authorized: true, owner, instanceId, actor, target }`.\nThe fourth, `POST /tool-result-human-proof/verify`, decides a pinned password proof for the\nhost's authenticated session subject without issuing consent or credentials.\nThe opt-in `POST /tool-result-consent/issue` door signs and records a same-owner consent\nunder a host-custodied scoped anchor. It returns no result content, private key or capability.\n[embedding.md](embedding.md) documents these host doors' contracts.\n\nThe public listener has a closed surface: `GET /health`, `GET /jwks`, `POST /exchange`,\n`POST /manager-service-authority`, `POST /manager-instances`, the three `/chat-session/open`,\n`/chat-session/bearer` and `/chat-session/retire` routes, and `GET /.well-known/cotal-mesh`. A space\nwhose auth service runs with `--service-endpoints` also serves `/service-endpoint-authority` and\n`/service-endpoint-host` there ([embedding.md](embedding.md)); without it they answer 404. Every\nother path is 404. It\ndoes **not** require the loopback\ncapability. That capability proves same-uid access to a 0600 local file and has no remote meaning;\non the public face the credential is the proof. A human presents an EdDSA IdP JWT checked against\nthe pinned JWKS, issuer, and audience. An agent presents its spawn-time actor token, whose hash must\nmatch a fresh managed-ledger row. The public face mints three elevated views, all still gated on\nledger scope `admin`: `channel-writer` (`cotal channel set` and `cotal channel defaults`), `channel-purger` (the\ndashboard's per-click channel delete) and the one-object `transfer-writer` (below). It also mints\nthe scope-free `session-caller` view (below) and the narrowing `manager-caller` view for humans\nor managed agents. That view binds the bearer to one live registered manager instance. It adds no\ncapability, except that a `spawn` holder's view may read that manager's `status`, `models` and\n`resolve-cwd`, which a host-local launch there needs. A manager using a delegated runtime refuses\nhost cwd resolution before filesystem lookup because its seats execute outside that host.\nGod-view (`admin`), space-history `purger`, `deployer`, and `manager-service` stay\nloopback-only. A managed-agent secret exchange refuses every other view. This is not full remote\nchannel management. The older embedded dashboard path needs a startup admin view even when a later\ndelete could use `channel-purger`. The new dashboard service currently accepts only an explicit\nstatic credential with read-only intent; it does not substitute that older operator login path.\n\nThe well-known response contains the IdP pins and the actual deny-all sentinel credential remote\nagents need before the bearer-driven auth callout. The pins ride a `userAuth` arm that names the\nauth provider, and that name is the same one the local arm registers under. A document naming a\ndifferent provider than the one serving it would register an entry nothing can resolve, so both read\none constant. Treat it as bootstrap material: the sentinel cannot publish or subscribe, but\nconsumers must still take the bundle only from the intended HTTPS origin and must verify TLS.\n`--exchange-trusted-proxy` opts into peer attribution by the **last** `X-Forwarded-For` hop; use it\nonly when the listener is reachable solely through a proxy you control.\nWithout it, forwarded headers are ignored and the socket address is the peer key. Public failure\nbuckets are per-source and separate from loopback exchange budgets. The in-process LRU retains at\nmost 1024 peer buckets: that bounds memory and isolates ordinary sources, but an attacker cycling\nmore than 1024 trusted-proxy last hops can evict earlier 429 state. It is not a mint bypass; a valid\ncredential is still required, so use upstream reverse-proxy rate limiting when that throttle-escape\nmatters to the deployment. A refusal at `POST /manager-service-authority` counts against the same\nbudget as one at `/exchange` on that face, so after 30 refusals in a minute either route answers a\nfurther refusal with 429. On the public face, a `manager-caller` `/exchange` request whose\ncredential and ledger actor grant have already verified (IdP JWT plus interactive actor grant on the\nhuman arm, actor secret plus managed ledger row on the agent arm) checks two per-principal\nselection-refusal windows (`30/min` each, keyed by principal (derived owner for human exchanges,\n`owner.actor` for agent exchanges) and request class: `pinned` when `managerInstanceId` is named,\n`unpinned` when it is omitted, never by the requested instance id) before running manager\nselection. While under its class limit, a selection failure returns `401` with its actionable\nreason without spending the per-peer probing budget or being masked by a peer's `429`. Once a\nprincipal's `unpinned` or `pinned` window is full, the public face sheds manager selection for that\nclass (refusing requests of that class, including ones that would have succeeded, while leaving the\nother class open) and returns `429` with that class's remedy (`--on` / `--manager-instance` /\n`cotal supervise` for `unpinned`; checking that the pinned manager instance is live and registered\nto the caller for `pinned`) until the window drains. Those principal-class windows share one bounded\n1024-key LRU of the same kind as the peer buckets: because one principal owns both its `pinned` and\n`unpinned` class keys, rotating 512 other verified principals (1024 keys, where each principal\nrequires its own verified credential and ledger grant, and one owner's managed agent rows count as\nseparate `${owner}.${actor}` principals) can evict an earlier full window and reopen it. On the\nloopback face, an authenticated unpinned refusal caused by no live manager or ambiguous candidates\nkeeps its actionable reason without spending the shared probing budget.\n\n### Callout deadlines\n\nnats-server waits for the auth callout's answer for its `authorization { timeout }`, two seconds\nunless the broker config sets it. From 2.15 a connect with no answer by then is refused; 2.14 leaves\nit waiting for the client's own connect timeout. The callout answers inside that window. A request's\ndeadline is the broker timeout less 250 ms, counted from when the callout received it. A request\nstill unanswered then gets a signed denial with the reason\n`timeout: the auth callout could not answer inside the broker's authorization timeout`, and its work\nstops at its next step. While the oldest request still waiting for a slot has waited more than half\nthat budget, the queue is not draining in time, and a new request gets the same denial at once\ninstead of joining it. Requests start oldest first, at most `maxInFlight` at a time.\n\nThe client sees `Authorization Violation` for this denial as for any other, because nats-server does\nnot pass a callout's reason to the client. The broker logs the reason after\n`Auth callout service returned an error`, and the callout logs it on its own line.\n\nEach answered request writes one line to the auth service's standard error:\n\n```\nauth callout: level=info outcome=minted space=<space> req=<user nkey> cid=<broker client id> owner=<owner> actor=<actor> queue_ms=0 verify_ms=1 ledger_ms=2 policy_ms=0 sign_ms=1 total_ms=4\n```\n\n`outcome` is `minted`, `denied`, `timeout` when the deadline passed, or `shed` when admission\nrefused the request. `space` is the space the connect was for, which a process serving several\nspaces needs and a process serving one still writes, so operators parse one format. `req` is the\nuser key the broker generated for this connect. `cid` is the broker's client id,\nwhich the broker's own log lines carry as `cid:<n>`. `queue_ms` is the time spent waiting for a slot. `verify_ms` covers the request and bearer checks, `ledger_ms` the actor\ncheck and the issuance record, `policy_ms` the permission build, and `sign_ms` signing the user JWT\nand the response. A `denied` line adds `reason=\"<message>\"`, a `timeout` line adds `at=<step>` for\nthe step it was in, and a `shed` line adds `waited_ms=<ms> ahead=<n>`: how long the oldest waiting\nrequest had waited, and how many requests were queued or in progress. The line logs at `level=warn`\nwhen the request took longer than 500 ms or its outcome is `timeout` or `shed`. A request that fails\nthe provenance checks still gets no answer and logs why it was dropped.\n\nA hosted context sets its limits with `startAuthService({ ..., calloutLimits })`, where\n`calloutLimits` is `{ authTimeoutMs, maxInFlight, slowMs }`. `authTimeoutMs` (default 2000) must\nmatch the broker's `authorization { timeout }` in milliseconds: against a broker set to 10 seconds,\nthe default refuses at 1.75 seconds connects the broker would still wait for. `maxInFlight` (default\n32) bounds the requests in progress, and `slowMs` (default 500) sets when a line logs at warn.\n\n`cotal up --auth-timeout <seconds>` sets both sides for a CLI stack from one value. It renders the\nbroker's `authorization { timeout }` and starts the space's auth service with that timeout as its\ncallout deadline. The value is recorded with the root's broker policy, so a later `cotal up`\nrenders it again and passes it to the auth service again. Without it the broker config has no\n`authorization` block and the auth service uses the defaults, which match nats-server's. `cotal up`\ndoes not start callout replicas, so start each one with the same `--auth-timeout <seconds>` as the\nbroker config.\n\nA replica serves one space. `cotal auth-service --callout-only --spaces <manifest>` instead serves\nevery space a manifest names from one process, one callout lane each, which is how a host runs one\ncallout process rather than one per space. A lane holds its own connections, its own connect limits\nand its own signing keys, so one space's key never signs another space's response and one space\nlosing its store connection leaves the other lanes answering. The broker decides which lane sees a\nrequest: a lane's callout connection authenticates as its space's auth account, and a NATS account\nis a disjoint subject namespace, so another space's request cannot be delivered on it. See\n[`auth-service`](cli.md#server-daemons) for the manifest and how a space is added or removed while\nthe process runs.\n\nThe full auth service can be hosted the same way. `cotal auth-service --spaces <manifest>`, without\n`--callout-only`, holds one full service per space in one process: each lane holds its space's plane\nclaim, callout, connections, connect limits and capability, and serves that space's exchange and JWKS\non listeners of its own, so one space's request never reaches another space's keys. A lane hosts\nservice endpoints only when its manifest entry sets `serviceEndpoints`. A fence or a lost\nbroker connection stops that space's lane alone. Callout replica hosts listing the same spaces add\nevent loops for connect bursts, since one process answers callouts on one thread. Removing a space\nfrom every host's manifest and waiting for each host's `<manifest>.applied` stops all minting and\nconnect authorization for it while the other spaces keep serving.\n\n### Connect limits\n\nThe auth service limits how often each principal may connect, so one client stuck in a reconnect\nloop cannot spend the callout for everyone else in the space. It keeps a token bucket in memory for\neach actor (`owner.actor`), each owner and each client host. A bucket holds a minute's allowance and\nrefills at that rate. The defaults are 60 connects a minute per actor and 600 per owner. A bearer\nwhose signature verifies is charged to its actor and its owner, even after it expires. A bearer that\ndoes not verify is charged to the client host the broker reports, at 60 a minute. A connect passes\nonly when every bucket it draws on has one left, and a refused connect spends nothing. Each auth\nservice process keeps its own buckets for each space it serves, callout replicas included, so a\nspace served by several processes allows up to that many times each limit. A process serving\nseveral spaces keeps a separate set per space, so one space never spends another's allowance. A\nreplica limits at the defaults.\n\nThe callout checks the limits before it reads the ledger or records an issuance. A limited connect\ngets a signed denial whose reason starts with `RATE_LIMITED retry-after <n>s`, followed by the actor\nand owner or the host. Its `outcome=denied` line carries that reason with the `owner` and `actor`\nfields. The broker tells the client only `Authorization Violation`, so the exchange carries the typed\nanswer. While an actor or its owner is limited, `POST /exchange` for that actor answers 429 with\n`{\"code\": \"RATE_LIMITED\", \"retryAfterSeconds\": <n>, \"limit\": \"<bucket>\", \"error\": \"<sentence>\"}` and a\n`Retry-After` header of the same seconds. `limit` names the bucket that ran out: `actor` for that\nactor's own, or `owner` for its owner's, which every actor of the owner draws on. Both faces and\nboth arms answer it, and it does not count as a refused exchange. Only the full service serves the\nexchange, so only it answers 429. A callout replica refuses limited connects at the default limits\nfrom its own buckets. A hosted composition passes other limits to `startAuthService` as\n`connectLimits`. No flag sets them.\n\nThe clients read that 429 as a rate limit. A CLI command prints the service's sentence and exits 2\nunder `DEPENDENCY_UNAVAILABLE`. Its remedy names the same bucket as `limit`: only that actor is\nlimited, or the whole account is. Its `--json` error carries `RATE_LIMITED`, the seconds and the\n`limit` in `error.cause`. `cotal agent-bearer` prints the sentence and that remedy on stderr and\n`retry-after <n>` on stdout, and exits 2. The agent's endpoint runs it again when those seconds have\npassed, not before.\n\n### Enrollment redeem\n\nA remote owner may pre-mint a one-time enrollment for a seat that has no browser, TTY, or cached\nIdP login. The enrollment is a secret-bearing URL. The client performs one request:\n\n```http\nGET <enrollment URL>\n```\n\nIt sends no `Authorization` header and no request body. The URL must be HTTPS, except for plain HTTP\nto a loopback IP literal. The client redeems only an enrollment URL that is already in canonical\nform and contains none of `\\ @ ? #`. That is checked on the raw string before parsing, so every\nrewrite a URL parser would perform, backslash folding, userinfo erasure, scheme or host case\nfolding, default-port removal, dot-segment resolution, and short-host canonicalization, is a refusal\nrather than a redeem of a URL the owner never minted. Redirects are refused. The client never\nretries because a successful claim deletes the server-side token row. The token expires five minutes\nafter mint.\n\nSuccess is `200` with this JSON object:\n\n```text\nspace\nbrokerAccess { kind, ... }\nowner\nactor\nlifecycleUid\nactorToken\nsentinelCreds\nauthServiceUrl\nidp { url, issuer, audience }\nsubscribe[]\nallowSubscribe[]\nallowPublish[]\n```\n\nThe grant arrays are informational; the broker row remains authoritative. A stock-dialable\ndeployment also includes `server`, `tlsRequired`, `userAuth`, and optional `policy`, forming the same user-bundle\nsuperset that `cotal meshes add --user-auth-file` accepts. That lets a bare seat register the mesh\nfrom the enrollment response before launch. For `brokerAccess.kind: \"direct\"`, the stock `server`\nmust equal `brokerAccess.url` byte for byte or the client refuses the bundle before registration. A\ntunnel kind carries no dial address, so its `brokerAccess` is not compared to the operator-asserted\nstock `server` face.\n\nUnknown, expired, revoked, and already-used enrollments are intentionally indistinguishable. They\nall return `404 {\"error\":\"unknown, expired, or already-used enrollment\"}`. The client reports only\n`enrollment refused: unknown, expired, or already-used; ask the owner for a fresh one`. It does not\nguess which case occurred.\n\nAfter redeem, the seat stores only the normal remote user-mesh and agent material. The actor token\nis exchanged at `authServiceUrl` through the existing `agent-bearer --exchange-url` path. The\nenrollment URL is not logged, persisted, or forwarded into any child process, including the bearer\npreflight and harness.\n\nThe service starts with the broker, is torn down by `cotal down`, and holds the\ndata-account signing key for the callout (a running manager is the other standing holder, for\nthe creds it mints); the operator seed never enters it. It also owns the space's two authority\nstores (lifecycle records and the credential ledger), provisions them at boot, and refuses\nconnects it cannot credential-check against them; there is no fallback path. If it\ndies while the broker lives, re-running `cotal up` heals it, and a boot whose auth\nservice never became ready exits non-zero, so automation never reads a dead identity\nplane as success. Changing any public-listener flag requires `cotal down` followed by `cotal up`\nwith the new values; a refresh adopts an already-running auth service rather than silently replacing\nits listener policy. \"One per space\" is enforced, not assumed (SPEC §13.13): at boot the\nservice takes a broker-backed ownership claim, so a second same-space auth process refuses\nwith instructions instead of silently splitting the plane, and a crashed one's claim is\nreclaimed only once the broker confirms its connections are gone. That verdict is trusted only\non a standalone broker (a clustered one refuses the reclaim, since a partitioned member\ncould still hold them). If the claim's connections die mid-run, the service downs itself\nloudly instead of serving from a half-dead plane.\n\nThe service's own broker connections renew their credentials before they expire, at a random\npoint between half and four fifths of each credential's lifetime and at least a second apart\nwithin a space. Each reconnects onto its new credential at a moment with no request in flight.\nThe connect-credential reader opens a new connection instead, proves its stores on it, and only\nthen switches to it, so a renewal never denies a connect. The service also removes expired\nnative-key issuance evidence on a timer. A pass that fails because the store did not answer, as can\nhappen while a connection reconnects under load, is retried with growing waits and logged once, and\nthe service keeps serving. Evidence that does not parse stops the service and refuses its next start.\n\nCtrl-C on a foreground `up`, and a broker that exits under it, stop the service with the same stop\nbare `cotal down` uses for it. It holds the reservation `down` takes, so the auth stop of a\nconcurrent `cotal down` is refused while it runs, and it sends SIGKILL to a service that has not\nexited 15 seconds after SIGTERM. A legacy stack has no command that stops only the auth service.\n\n**Your agents are yours.** `cotal spawn` on a user mesh grants a managed actor under the\n*spawning operator's* owner and launches the agent with a bearer command instead of a\ncreds file. The agent exchanges its spawn-time secret for short bearers (five minutes or\nless). It renews each one at a random point between half and four fifths of its lifetime and\nmoves its connection onto the new bearer, so the broker never closes the connection for an\nexpired one. Agents started together draw different points, and two connections in one process\nfor the same space renew at least a second apart. An agent never presents an expired bearer: it\nrenews first. While renewal fails it retries with growing, randomized waits of up to a minute,\nand reports the failure once until renewal works again. A locally provisioned foreground launch\nrefuses an existing actor rather than rotating another launch's secret. Its exit and failed-start cleanup\nrevoke only the grant matching the launch's token and lifecycle. Broker-footprint deletion follows\na successful owned revoke; credential files are removed only while they still hold this launch's\nmaterial. Cleanup reports failures without deleting a successor's state. A crashed launcher can\nleave a grant that needs operator recovery. Remote foreground launches remove their own local\nmaterial but leave revocation to the issuer. Managed despawn follows the retirement sequence below.\nManifest deploys (`up -f`) stamp the logged-in owner into the launch, so those agents are yours too.\n\n**Despawn tears the lifecycle down, then frees the name.** When you despawn an agent, the manager\ndrives the *full* teardown of that lifecycle: it shreds the local credential files, revokes the\nagent's standing mint authority (its ledger row, so a copied token can no longer mint a fresh\ncredential), deletes its broker footprint (the lifecycle-keyed durables + read-ACL row), and asks\nthe auth service to *retire* the lifecycle (settle in-flight work, evict the departed credentials,\nrecord it retired). The name is held *reserved pending retirement* until **all** of that completes,\nthe broker-footprint cleanup, the standing-authority revoke, **and** the lifecycle retirement, not the\nretirement alone, so a same-name respawn in the gap is refused with\na plain reason and a retry hint rather than quietly handing the alias to a new agent while\nthe old lifecycle's teardown is still running. Only once the broker footprint is gone, the standing\nauthority is revoked, and the retirement is confirmed does the name free, and `cotal spawn <same-name>`\ngives you a fresh agent cleanly. This is what makes reusing an agent's name safe: the old lifecycle is\nfully torn down before the new one takes the alias. A local file that cannot be removed does not\nstop the rest of the teardown: the broker footprint is still deleted, the failure is reported, and\nthe name stays held. If the auth service is unreachable or the standing-authority revoke fails,\nthe despawn still stops the agent and *holds* the name. **A\nsame-name `cotal spawn` re-drives the whole teardown** and finishes it. Retrying the despawn has no\neffect because the agent is already stopped. The operator copy tells you to recover the stack\n(`cotal supervise`) rather than reusing the name over an unretired predecessor.\n\nA failed spawn can also retire an orphan lifecycle without holding its name. Its retirement\nfailure names the lifecycle and reports that no hold reserves the name for it. A same-name\nspawn does not retry that orphan's teardown. A refusal from the auth service keeps its reason.\n\n**A crash mid-retirement resumes at the next boot.** The retirement's last two steps (recording the\nissuance gate terminal, then the lifecycle head terminal) are separate durable writes, and a crash\nbetween them leaves the gate retired while the head is still `retiring`: an alias that can neither\nmint nor be replaced. The auth service's boot crash-resume decides what it owes across *both*\nobjects (the gate *and* the alias head), so the next boot finishes that tail from the durable\noperation intent: nothing is re-revoked or re-drained, and a completed retirement (its head terminal\nlanded, or a successor already took the alias) is left skipped. A retry of the despawn converges on\nthe same recovery.\n\n**Delegation only narrows (the envelope rule).** A user's grant is their envelope:\neverything under their owner (their CLI, every agent they spawn, every agent those\nspawn) stays within its channel lists and its capability scope. Handing a role to a\nspawned agent needs the matching `role:<r>` capability in the spawner's scope. The whole\ndelegation chain is checked, not just the last link, and re-checked at every bearer\nexchange, so narrowing a user's grant reaches their agents within minutes, and revoking\nthe user revokes everything under them, grandchildren included. A spawn beyond the\nenvelope is refused with the exact widening re-grant to ask the operator for. One post entry is\nnot taken from the spawner's lists: a spawner whose grant covers its own event channel may hand each\nchild that child's own event channel, `events.<owner>.<child>`, and no other. It names the child, so\nit reaches nothing the spawner holds, and the spawner's own event channel is still checked against\nits parent.\n\n**Control ops ride your own login**, gated by ledger scope. `spawn` covers launching,\n`ps`, and stop/attach of the agents under **your own owner**: the owner is the\nadministrative boundary of its own subtree, so you (and your agents) manage what you own\nwithout any extra grant. `admin` is the explicit opt-in for touching **other owners'**\nagents; it is never part of a default grant and never accepted from a manifest.\n\n**Elevated operator surfaces ride the same login** through a short-lived *view*: the\nexchange stamps a server-authored view claim into the bearer, and the callout mints that\nconnection as the matching non-agent profile instead of `agent`. The older embedded dashboard\npath and `cotal console` ask for the read-only admin view, `clean history` for the purger,\n`channels set/default` for the channel-writer (all gated on ledger scope `admin`);\n`up -f` deploys over the deployer view, gated on `spawn`, because deploying your own team\nis spawn-grade (the manager still refuses a manifest claiming another owner). Elevated views exist\nonly on a signed-in human exchange. The `manager-caller` view is the one managed-exchange exception\nbecause it narrows the agent's existing manager command set to one server-selected instance and adds\nno capability. All views are authorized against the fresh ledger row at every connect and expire\nwith the bearer, so narrowing or revoking a grant bites within minutes here too. On the public\nexchange face only `channel-writer`, `channel-purger`, `manager-caller`, `session-caller`, and\n`transfer-writer` are served; `admin`, `purger`, `deployer`, and `manager-service` remain loopback-only.\n\nThe `session-caller` view is how `cotal attach` opens a seat's session on a user-auth mesh. It needs\nno ledger scope, because the session grant is the authority. The exchange takes the grant with the\nlogin proof and leader-reads the redeemed `session.<id>` row. It issues the bearer only when the row\nis active and unexpired, its signature equals the presented grant's, its holder is this owner and\nactor at this lifecycle, its endpoint and serving epoch match, and the serving manager's gate is open\nat that epoch. The callout repeats the same check at connect and mints the session's caller rails\nwith the grant's expiry instead of the bearer's.\n\nThe `transfer-writer` view is how `cotal spawn --resume <id> --detach --on <instance>` uploads a\nsession this host holds on a user-auth mesh. It needs scope `admin`, as the `transcript-receive`\ncall it serves does, and names one object: the target instance and the transcript's SHA-256. The\ncallout mints writes to that object of that instance's transfer bucket and nothing else. The bearer,\nand with it the broker connection, lives at most five minutes, the lifetime of the static\n`transfer-writer` credential, and never past the login proof it was exchanged for.\n\nThe `dm-reader` view lets an embedding read one user's own DMs while that user's app is closed,\nfor example to send a content-free push. The callout mints three publish rows on the user's own\n`dm_` durable (consumer info, next message and its ack subtree) plus the connection inbox, and\nnothing else. The view needs no ledger scope and is loopback-only.\n\nIt rides only a purpose-bound proof from the same IdP. Set `dmReaderAudience` in the space's IdP\npin to an audience the IdP mints only for these proofs. It must differ from `audience`, and nothing\nderives it. The proof carries `purpose: \"dm-reader\"`, `actor`, `lifecycle` and `space`. The\nexchange accepts it only for `view: \"dm-reader\"` with the same actor, the actor's current\nlifecycle and this space. Every other door that takes a human proof refuses it, and the ordinary\nverifier now refuses any token that carries a `purpose` claim. The issue that proposed this listed\nfive verifier call sites; this release has eight routes that take the proof, and all of them are\ncovered. The bearer and its connection expire no later than the proof, so set the proof's lifetime\nto cover your own grant and session expiry.\n\n### Remote manager authority\n\nA registered user remains an ordinary `agent` bearer by default. Running a detached manager\non a remote user-auth mesh needs the closed server-authored **`manager-service`** view, which\nis distinct from every general-purpose profile. The operator grants it only by adding\n`supervise` to that user's actor-ledger scope. `supervise` is deliberately distinct from\n`spawn` and `admin`: spawn controls your agents, admin permits the separate cross-owner\noperations, and neither grants persistent manager registration authority.\n\nOnly a signed-in human may request this view from the loopback/operator exchange. The public\nexchange and every managed-agent secret exchange refuse it. At exchange and each connection,\nthe auth service re-reads the actor row; revoking or removing `supervise` therefore denies the\nnext view exchange and connection. A grant must carry the whole requested row just like every\nother actor update, so re-grant its channel envelope, role, and all wanted scope tokens, not\nonly `supervise`.\n\nThe service is one opaque manager instance for the user's derived owner and a fixed\nserver-selected manager actor. Its authority is limited to that instance's manager\nregistration, contracts, status, endpoint rails, gate and credential family; it cannot read or\nwrite another owner or instance. It never exposes a signer, static provisioner credential, owner\nsecret, raw stream/KV/consumer authority, or a generic credential-mint API. The host creates the\npublic-nkey JWT material through the typed lifecycle-bound protocol: **prepare → activate →\nrenew**, plus host-owned **evict-family-principal** and **reconcile-registration** maintenance\noperations and a one-shot **retire** phase for one exact managed lifecycle. Each request is replay-safe and idempotent at its lifecycle/instance operation\ncoordinate; the host writes its credential ledger row and finalizes the gate before it releases\nusable material. The retire phase fresh-checks the current manager instance, server-derived serve\nprincipal, serve epoch, same-owner target and lifecycle UID. It returns only a short-lived requester\ncredential pinned to that target. The manager invokes the registered `auth` endpoint's\n`retire-lifecycle` command through the generic client, resolving the service and calling it with\nan exact target and the operation id derived from the target lifecycle UID. The endpoint\nrecomputes that id from the broker-pinned target before any durable access. A caller cannot\nsubstitute another valid operation identity for the same target, and retries plus auth-service\nboot recovery finish the same terminal barrier. It never exposes the barrier executor or a general mint surface.\n\nRegistration maintenance stays on the host. One eviction request carries up to 256 holders, and the\nhost accepts it only when its single sealed scan of the caller instance's\n`epcred.manager.<instanceId>.*` family finds every one of them. Reconciliation may\ntarget a foreign manager slot holder in the same space, but it runs only after the delivery daemon\nproves the frozen gate's holder gone under a complete sweep. The participant receives neither an\nevictor credential nor authority over another instance's records or gate. A clean stop refreshes an\nunhealthy executor before deregistration. A restart verify-evicts its old family, and a manager\nblocked by a foreign governance slot whose holder's gate is still frozen at the slot's stamp asks\nthe host to reconcile that holder and retries the registration once. The goal-writer and session-ledger\ncredentials carry a random `issuance:` tag, so a restart that re-mints them within the second of an\nearlier issuance gets new ledger rows and never re-signs a credential its barrier revoked.\n\nA remote manager can provision only descendants of the same derived owner, and the host\nvalidates that relation and the current manager grant for every provision. It cannot broaden the\nuser's envelope or provision a sibling owner's agent. Renewals are bounded. If login, the\n`supervise` grant, or the host manager authority service is unavailable, the manager reports a\ndegraded state and refuses new agents, restarts, or replacement credentials rather than\nsubstituting local/static authority. Existing live agents remain running only while their own\nvalid authority permits it; recovery requires the host service and a fresh successful renewal.\n\nThe manager-authority protocol is closed, so a host whose auth service predates a field the\nmanager sends refuses the whole request. The manager reports that refusal as version skew after the\nhost's reason: it names its own Cotal version and the refused field, and says it needs a host at\nthat version or later. It never drops the field to fit the older host. Upgrade the host first;\n[Upgrading](UPGRADING.md) promises no rolling upgrade between versions.\n\nA manager on remote authority mints from that authority alone; it consults the local root's\nrecords only to refuse a conflict, and only the supervised space's own trust records count as\none. A workspace that hosts an unrelated static space beside the participant sign-in is a\nnormal configuration.\n\n**User authentication has one path.** On a user-auth space, commands never fall back to\nstatic minting or credless connects: a missing login or a down auth service is one\nsentence naming the exact recovery, and static agent/observer/admin minting is refused\noutright. The refusal is deny-new: a static cred signed before the space flipped stays\nbroker-valid until the signing key is rotated ([security model](security.md)).\n\n### Held agent names\n\nA host answers a managed enrollment or an agent provisioning for a name another lifecycle holds\nwith HTTP 409, and nothing is enrolled or provisioned. The stock auth service answers\n`{ \"error\": \"<reason>\" }`. A host that knows more answers a typed body:\n\n```json\n{ \"error\": \"<reason>\", \"code\": \"AGENT_LIFECYCLE_HELD\",\n \"held\": { \"agentId\": \"<registration id>\", \"lifecycleUid\": \"<uid>\",\n \"custody\": { \"state\": \"known\", \"kind\": \"remote-manager\", \"managerInstanceId\": \"<instance>\" },\n \"presence\": \"offline\" } }\n```\n\n`custody.state` is `known`, `absent` or `unavailable`, and `custody.kind` is `foreground` or\n`remote-manager`. `presence` is `online`, `offline` when the agent is known to be absent, or\n`unavailable` when the host cannot tell. The client keeps that answer verbatim and passes it to the\nspawn as a `details` entry of kind `ai.cotal.auth.agent-lifecycle-held`, with the actor it was for.\n\nA mesh's agent-provisioning endpoint also releases one lifecycle, with the same login bearer.\n`GET <endpoint>` lists the caller's registrations as\n`{ \"agents\": [{ \"id\", \"lifecycleUid\", \"actor\", \"revoked\", \"connection\", ... }] }`, and\n`DELETE <endpoint>/<id>` revokes one: `{ \"ok\": true, \"removed\": true }`, or\n`{ \"ok\": true, \"removed\": false, \"alreadyRevoked\": true }` for one already revoked. A 404 is a\nregistration it does not have and a 503 is a release it could not confirm. The client releases only\nthe unrevoked registration at the one lifecycle it was asked for, and refuses when the list holds\nmore than one. A revoked registration may still be retiring, so the name it held can stay refused\nfor a while after the release. [`cotal spawn`](cli.md#spawn) and `cotal auth retire` use this\nrelease.\n\n## The IdP callout contract\n\nAny OIDC identity provider that issues **EdDSA/Ed25519** JWTs plugs in here directly; a provider that\nissues RS256 or ES256 tokens (many managed OIDC services do) needs a host-side normalization or\nre-issuance adapter first, because the reference bridge pins the token algorithm to EdDSA. The\nreference implementation ships **Better Auth** as a\ndev and test fixture only (it is a `devDependency` of `@cotal-ai/auth`; the only code that imports\nit is the `dev-idp.ts` harness and the smoke tests, never the runtime `src`). The one runtime\ncoupling to an IdP is the `idp.ts` bridge plus the `auth-provider` extension. The bridge core\n(`createIdpBridge`) is IdP-generic for **EdDSA** tokens (issuer, audience, JWKS as configuration).\nThe stock end-to-end flow around it, though, is **Better-Auth-shaped**: `cotalAuthProvider` pins\n`<base>/jwks` and issuer/audience to the IdP origin, and the login client speaks Better Auth's\ndevice-code endpoints (`/device/code`, `/device/token`, `/token`) with an opaque revocable session.\nSo a Better-Auth-shaped EdDSA IdP uses the stock flow directly; **any other production IdP is a\nhosted-composability gap, not a configuration change**. A host integrates it by building its own\nlogin and provider wiring on the low-level primitives (`createIdpBridge`, `createUserTokenIssuer`),\nnot by reusing the stock provider. Note that importing `@cotal-ai/auth` self-registers\n`cotalAuthProvider`, and `resolveAuthProvider()` throws when two providers are registered, so a host\non the registry-resolution path must not also register its own. Whatever the path, never loosen the\nissuer/audience/JWKS pins to force-fit an IdP.\n\nA provider participating in reviewed local identity reset declares its secret\nkeys through the optional offline `deprovisionSecretKeys(space)` inventory.\nThe stock provider shares that list with `deprovisionSecrets`. The inventory\nreturns keys only and performs no deletion or secret read. A provider without\nit, or with keys outside the selected space's secret segments, cannot use that\nreset route. Hosted deprovisioning remains a separate composition.\n\nThe bridge (`createIdpBridge`) exchanges a verified IdP token for a Cotal bearer in three steps:\n\n1. **Bearer validation.** Verify the IdP's JWT offline against its **pinned JWKS**, with the token\n algorithm pinned to EdDSA. Keys resolve only through the pinned JWKS: a token carrying embedded\n key material (`jku`/`jwk`/`x5u`/`x5c`) is rejected, so the token can never influence key\n resolution. Issuer and audience are checked. The minted Cotal bearer never expires after the\n upstream proof: the issuer signs the earlier of the requested lifetime and the proof's `exp`,\n read when it signs, and refuses once the proof has expired. Time spent in the bridge's hooks\n shortens the bearer instead of extending it.\n2. **Owner derivation.** The opaque per-space owner derives deterministically from the JSON-array\n encoding of `[idp issuer, sub]`, namespaced by issuer so no issuer/sub pair can straddle a\n delimiter, and re-login re-lands the same person in the same lanes. The owner-token *format*\n (`u_` followed by 26 base32-lower characters) is normative\n ([SPEC section 2](../SPEC.md#2-identity)). At the contract level the *derivation* from an\n identity is a pluggable edge, but the reference `createIdpBridge` fixes it\n (`deriveOwnerForIdpSubject`) and takes no derivation callback, so what a host configures is the\n IdP, not the derivation. **The encoding is frozen:** changing it, or changing the IdP issuer\n string, re-keys every owner in the space, which is a migration on the order of rotating the space\n secret.\n3. **Actor authorization and mint.** The operator's ledger hook authorizes the `(owner, actor)` pair\n and is the only source of the bearer's `scope`/`parent`; the issuer then mints the Cotal bearer,\n re-asserting every claim shape.\n\nA host wires this with the IdP's own coordinates and nothing from `@cotal-ai/auth` changes:\n\n```ts\nimport { createIdpBridge, pinnedJwksResolver, createUserTokenIssuer } from \"@cotal-ai/auth\";\nconst bridge = createIdpBridge({\n idp: { issuer: idpIssuer, audience, key: pinnedJwksResolver(jwksUri) }, // your production IdP\n space,\n spaceSecret, // identity-plane owner-derivation secret (>=32 bytes), held by the auth service at runtime\n issuer: createUserTokenIssuer({ issuer: cotalIssuer, key: signingKey }), // mints the Cotal bearer\n authorizeActor: (owner, actor) => grantFromLedger(owner, actor), // your ledger, returns an ActorGrant\n});\n```\n\nFor private-result consent, `verifyToolResultHumanProof` applies the separate password-freshness\nrule to the same pinned signature check. A signed integer-second `auth_time` must be no later\nthan the decision and at most 300 seconds old, and signed `amr` must contain `pwd`. Neither a\nrecent JWT `iat` nor a session's creation time supplies password provenance. Missing, malformed,\nfuture or stale provenance refuses this decision without changing ordinary bearer exchange.\nThe host-only proof door and the remaining activation limits are documented under\n[private tool results](embedding.md#private-tool-results).\n\n## Joining\n\nA single **join link** carries server, auth, and space\n([SPEC §10](../SPEC.md#10-connection-and-onboarding)):\n\n```\ncotals://<token>@host:4222/<space>?channel=general # cotals:// = TLS required; cotal:// = TLS not required (downgrade-tolerant)\n```\n\nHumans: `cotal join --link …`. Agents: `COTAL_LINK=… ` in the environment. The connector\nexpands it and auto-joins. Token/user-pass links are the open-mode path; the default\nauthed path threads a minted creds file, and the endpoint adopts the credential's identity\nas its card id. A seat the manager spawned reaches that file through its **launch\nmaterial** rather than through `COTAL_CREDS` in an environment every descendant process\ninherits (see [Configuration](config.md#launch-material)); a session you drive by hand\nstill sets `COTAL_CREDS` itself.\n\n## Honest limitations (v0)\n\n- **The signing key is hot** on the mint/manager box of a static-auth mesh; the \"real\n boundary\" holds given operator-controlled cred distribution. On a per-user-auth mesh\n the data-account signing key is held by the auth service (the callout stage) and by any\n running manager, which loads the trust bundle and self-mints its supervisor cred and\n renewals from it; a copied signing *seed* still stays valid for its identity until the\n signing key is rotated. Rotation remains the revocation lever for trust material.\n- **The two `$SYS` creds renew through rotation.** `membership-observer` and\n `connection-evictor` are signed by the system-account seed. The trust record is written without\n it; the root keeps the seed in its own secret-store record for own-broker caller issuance only,\n and no running process re-signs these two creds in place: they carry a 30-day expiry and are renewed by issuing a new\n system account (`cotal down` then `cotal up --rotate-sys`), which leaves the data account,\n every agent cred and the store untouched but does invalidate earlier full backups (they bind to\n the operator JWT and system account they were taken under, so re-run `cotal backup` after). Past that horizon the mesh keeps delivering, but the\n membership feed and live eviction stop; `cotal doctor auth` and the manager warn from the 75%\n point onward. A host that keeps a registered system signer can re-mint the observer into the\n delivery daemon's secret store instead: the feed reads it again at 75% of its lifetime, proves it\n on a throwaway connection, and adopts it only when its issuer and permission scope match the\n cred it started with.\n- **A copied static agent cred outlives its session.** One-shot command creds expire in\n minutes and the standing daemon creds in 24h with the manager renewing them (`cotal doctor\n auth` is the one diagnosis and repair surface). A manager-spawned agent cred also expires\n after 24h, the manager renews it only while the agent is live, and despawn retires it. A\n static mesh has no auth callout, so a compromised agent that copied its creds can still\n reconnect until they expire. An out-of-band `cotal auth mint` cred lasts 24 hours unless a\n lifetime flag says otherwise, and one minted with `--no-expiry` stays valid until its key is\n revoked or the signing key is rotated ([security](security.md)). Per-user-auth spaces\n close this: bearers live minutes, `cotal actor revoke` denies the next exchange and the next\n connect and evicts the principal's live connections immediately.\n- **Not non-repudiation.** Authenticity is broker-enforced, not portable proof; it does\n not survive an untrusted relay. Signed envelopes are reserved\n ([SPEC §11](../SPEC.md#11-versioning-and-extensibility)).\n- **Chat metadata leaks in-space.** Content reads are ACL-bounded; stream metadata\n (channel names, per-subject counts) is not yet ([security model](security.md)).\n\n**Denials are loud, never silent.** A publish outside an ACL surfaces as a logged denial\n(\"denied, not absent\") on the endpoint's error path; an over-tight ACL never looks like a\nmissing peer ([run a mesh](run-a-mesh.md)).\n\n## Standalone endpoint callers\n\n`auth mint <name> --endpoint <class> --out <private-file>` provisions the ordinary native agent\nfootprint with explicit endpoint request rows from a fresh digest-verified surface. This route\nrequires the selected local static signing authority and retains the registered broker TLS policy.\nOnly untargeted synchronous ephemeral surfaces are supported; targeted, journaled and action\nsurfaces refuse instead of receiving guessed or incomplete authority. The native baseline remains,\nbut no spawn, run or admin capability is added. Explicit channels enter both read and post ACLs.\n\nA private create-only issuance intent precedes native footprint work and blocks blind replay after\ninterruption. The intent contains no credential and proves no submission/completion. The resulting\ncredential is private and is not a managed seat. The endpoint describe/invoke routes consume\nits paired private intent only after native signature/current-issuer, user-key, time-window,\npermission-builder and principal-tag checks. Broker admission remains a separate requirement.\nThe intent selects coordinates; it is no wire grant, accepted-generation proof or live lifecycle\ncheck. Arbitrary raw files, different profiles and issued-generation files are not reinterpreted.\nUser-auth issuance and managed launch remain unsupported. See\n[the CLI limits](cli.md#endpoint-caller-credentials).\n"
55
55
  },
56
56
  {
57
57
  "slug": "agent-files",
@@ -211,7 +211,7 @@ export function loadDocsBundle() {
211
211
  "kind": "Guide (informative)",
212
212
  "category": "Guide",
213
213
  "summary": "The cotal binary in this repo is one composition root: an operator CLI.",
214
- "body": "# Embedding Cotal\n\n> **Guide** (informative) · **For:** implementers building a service on top of Cotal · **Prereqs:** [Architecture](architecture.md), [Identity and auth](identity-and-auth.md), [Delivery daemon](delivery-daemon.md)\n\nThe `cotal` binary in this repo is one composition root: an operator CLI. A separate service\n(for example a hosted, multi-tenant Cotal) does not fork this repo. It writes its **own**\ncomposition root that depends on the published `@cotal-ai/*` packages and imports the surfaces it\nwants. `bin/cotal.ts` uses the same composition pattern. This page is the contract for that: what is a real library\nexport you can build against, how to boot the server-side daemons from those exports, and where the\ncurrent export surface stops short of a fully hosted composition.\n\nThis is the \"guarded substrate\" boundary in practice. Nothing here reveals or assumes a specific\nhost; it documents the public seams any embedder composes.\n\nFor CLI automation, agent tools and wire clients, see the [API reference](api-reference.md).\n\n## What you embed\n\nThe supported reference shape here is **one broker operator serving one space** (one tenant: a\ndedicated data account, under an operator that also holds the system account and a quarantined\nauth-callout account) plus three standalone processes. The trust layer itself composes many spaces\nunder one broker operator today (`createBrokerAuth` + `createSpaceAccountAuth` + N-space\n`serverConfig`); what does not exist yet is the per-space **lifecycle** on a shared broker (see\n[Known gaps](#hosted-composition-gaps)). The three processes:\n\n| daemon | package | what it is |\n|---|---|---|\n| auth-service | `@cotal-ai/auth` | the NATS auth callout, the IdP token exchange, and JWKS. Plane 1 to Plane 2. |\n| delivery | `@cotal-ai/delivery` | the Plane-3 durable backstop: fan-out writer plus trusted reader, per space. |\n| supervise | `@cotal-ai/manager` | the per-machine agent lifecycle (spawn/despawn/attach), per space. |\n\n`mint`, `deliver`, and `auth-service` expose their behavior as direct library primitives, and the\nsupported one-space bootstrap below re-composes from exported low-level primitives. `supervise` and\nthe full `up` orchestration are **not** public runners: `up` also does broker bring-up, restore,\nprocess and registry management, and lifecycle work, and `supervise`'s orchestration is private (see\n[Supervisor signing authority](#supervisor-signing-authority)).\n\n## Workspace registry liveness\n\n`@cotal-ai/workspace` exports `pruneStaleMeshes()` for a liveness sweep. It keeps every\nregistration and returns a `MeshSweep` containing only `offline: string[]`; catalog entries\nare not probed. The former always-empty `pruned` field is removed.\n\nCall `pruneMesh(space)` only after a credentials, mode, or on-disk space mismatch. It removes\nan `up` or pre-origin record and returns whether it was removed. Manual and catalog records\nstay registered. The reason argument and `PruneReason` type are removed. Callers that passed\n`\"gone\"` must report the target offline without calling `pruneMesh`; callers that passed\n`\"mismatch\"` omit the argument.\n\n## Interactive Manager primary\n\nA trusted composition can pass `{ interactiveManagerSelection: \"local-primary\" }` as the third\nargument of `runAuthService(args, store, options)`. `AuthServiceRuntimeOptions` is exported by\n`@cotal-ai/auth`. The third argument still accepts the native daemon lifecycle hooks. No CLI\nflag or exchange field sets the policy, and unsupported runtime values refuse before startup effects. `openAuthAuthorityPlane` accepts the same option beside its fresh\n`localManager` reader; `OpenAuthAuthorityPlaneOptions` is exported too.\n\nThe opt-in chooses the genuine local Manager up front for an unpinned human `manager-caller`\nexchange. It reads the persisted local identity and requires the existing open gate, serve\nprincipal, registration revision and status epoch checks. An absent, unreadable or noncandidate\nlocal Manager refuses without scanning or substituting remote Managers. Explicit selectors win,\nand managed-secret exchanges and launching or issued instance bindings keep their existing rules.\nThe option adds no scopes, registry reads or inventory rows.\n\nThis routes all unpinned interactive Manager control, not only `ps`: slot reads, stop, attach,\ninput, spawn, models, hosted run verbs and generic Manager describe/invoke share the view. It\nchooses local even when the person has a live remote Manager. A host must decide whether that\nrouting is appropriate; a local Manager without execution cannot forward a spawn or run to the\nperson's remote Manager. The person selects that Manager explicitly for those operations.\n\nAbsent the option, selection is unchanged. `startAuthService` still has no local Manager and\nkeeps its remote-only composition. Supplying this programmatic option does not enable it in stock\n`up`, restart or recovery paths; a host must compose those paths separately after adopting the\npublished API. `ps` still lists only the selected Manager's managed seats, not HTTP-hosted sessions.\n\n## User credential authority\n\n`AuthProvider.userCredentials` returns the bearer and sentinel credential. A provider may also\nreturn `authority`, containing the owner and the current `scope`, `allowSubscribe`,\n`allowPublish` and `dmHistory` grant that its issuer authorized for that mint. The stock provider\nreturns this from the exchange response on local and remote user-auth spaces. It does not decode\nthe bearer to reconstruct access.\n\nThe field is optional for provider compatibility. Its absence means the caller has no\nauthoritative grant answer. A status surface must preserve unknown or unavailable instead of\ninferring broad access from a bearer, successful exchange or broker ping.\n\n## Login confirmation\n\n`AuthProvider.confirmLogin` asks the space's IdP whether this machine's cached login still holds.\nIt mints nothing. It answers `confirmed`, `signed-out` when no login is cached, or `rejected` when\nthe IdP refused the cached one, and throws on any other failure. `cotal manager start` and\n`restart` call it on a user-auth space before they save or launch anything, and refuse\n`UNSUPPORTED` when the provider does not implement it.\n\n## Account connection census\n\n`mintAccountCensusCreds` creates a host-only SYS user with at most five minutes of authority.\nIt can request CONNZ for one DATA account and subscribe only to an account-qualified reply prefix.\nIt grants neither KICK nor account events. The host supplies a registered SYS signer; the helper\ndoes not find, persist or renew that signer, and the broker verifies its authority on connection.\n`observeAccountCensusWithCreds` requires this narrow scope and a pinned server key. It reads one\nbounded page. Malformed, incomplete, multiple-server or cluster-declared replies are unknown,\nwith no connection list. A complete result describes only that server's observed account page.\nThe host still needs independent topology and restore guarantees, deny-new, a fixed cutoff and\nlifecycle fencing before using an observation for retirement. These helpers do not grant service\nregistration or terminal retirement.\n\n## Service authority contracts\n\n`@cotal-ai/core` exports closed service-authority request, proof and result types and their\nruntime parsers. The parsers bind a result to the submitted request and registration witness.\n`AuthProvider.serviceEndpointAuthority` is an optional provider hook for this protocol. A provider\nwithout the hook must refuse service setup. The user-auth provider implements the HTTP client,\nincluding `serviceEndpointInfo` for the DATA-account binding. It uses the pinned exchange origin,\nrefuses redirects and does not retry an unknown mutation outcome. Server-side HTTP failures\nremain unconfirmed even when their bodies resemble a protocol denial. A registered snapshot must\nname the submitted closure set. Inline artifacts include each closure manifest as well as its\ndocuments, within the envelope byte limit; native per-closure walk limits still apply. The client does not transmit\nthe local host capability or read callout signing material. Local setup needs the client sentinel\nprojection written by `prepareServer`; a missing projection refuses rather than reading server secrets.\n\n`@cotal-ai/auth` exports host request and view types with `parseServiceHostRequest`. Parsing checks\nstructure only, not owner consent, current grants or admission state. The host handlers and complete native\nservice lifecycle are not implemented yet, so these interfaces do not enable service registration.\nThe native endpoint gate also carries service approval and activation fields. Registration and\nserving guards retain those fields and refuse expired or revoked approval; these guards are not\na replacement for the missing host lifecycle. Internal host gate transitions bind approval to a\ncurrent native root and make activation monotonic. Registration completion is stamped in the\nreopen CAS; a definite abort preserves the previous stamp. They do not provide consent, public handlers\nor terminal retirement. Pre-activation registration requires an empty issuance family, including\ndeleted records, and release rechecks fixed expiry after asynchronous work.\n\n`UserTokenIssuer.issueServiceRenewal` signs a separate registration-bound renewal proof.\n`validateServiceRenewalProof` checks its signature, fixed expiry and full witness binding.\nIt is not a connect bearer. These primitives do not authenticate a current approval or native root;\nthe host must do that before issuing or accepting authority. No client refresh loop is provided yet.\n\n`UserTokenIssuer.issueServiceAccess` signs a serve-only user bearer with the full registration\nwitness and a fixed deadline of at most 60 seconds. Validation requires empty scope and rejects\nordinary parent, manager, session and transfer claims. Ordinary exchange and permission construction\nrefuse this view before actor lookup. Callout\nrefuses it unless a sealed native service authority is configured. The private composition binds\nthe current assignment, native root, registered serving grant and receipt before an encrypted\nresponse. Normal authority-plane startup does not enable it yet; public registration, restore\nreadiness and coordinated root retirement remain required.\n\nInternal service-access reads retain native credential-root authorization and check the activated\nregistration, assignment, current name and fixed expiry. They do not create a serving grant or\nrelease a native JWT. The private callout composition performs native issuance and final\nauthorization when explicitly configured.\n\nService serving-issuance evidence binds the authenticated broker user key, server key and client id.\nThe native release fence rechecks that record and the gate after its CAS. Ordinary serving and\ncredential-root records cannot use this service binding. This is not proof of broker acceptance;\nproduction authority-plane wiring and terminal retirement remain unfinished.\n\n`mintServiceCalloutJwt` is a host-only mint seam. It uses the native serving grant, the actual\nprincipal name and tags, the authenticated broker user key and a separate client inbox nonce.\nExpiry stays bounded by the original admission and access deadline. It does not authenticate the\ncallout request, record natkey evidence or release an encrypted response; the host must do those.\n\nNative service receipts bind the same epcred connection and registration witness to the broker user\nkey. Recording rechecks the evidence, receipt, native authority and fixed expiry. Expired service\nreceipts are retained, not pruned on elapsed JWT time. Qualified retirement and production\nauthority-plane wiring are still required before enabling the service path for clients.\n\nInternal service-name bindings are create-only and return owner and revision from one native read.\nThe trusted host must authenticate the operator and verify the namespace claim before writing.\nNative auth, delivery and manager names keep their existing authority; they cannot be application\nservice bindings. No transfer, release or public name-binding handler is implemented yet.\n\nInternal caller-policy storage uses the sealed native registry and binds each row to one account,\nspace and grantee UID. Grant ids are immutable; an append cannot replace or reactivate one.\nInitial writes require no prior native key history. A deletion arriving after an absence read\ncannot recreate a policy or a pending service gate.\nRevocation begins with a revision-pinned deny-new intent that unrelated appends preserve.\nThese are storage operations, not entitlement checks; the service endpoint host below is their only\nwriter. The effective resolver and native caller issuance are described under the service endpoint\nhost below. Receipts and terminal caller revocation remain unsupported.\n\nScoped Describe callbacks also receive an optional immutable local context with the actual subject,\ncomplete-envelope fingerprint, serving identity and receive-relative deadline information.\n`parseDescribeObservation` shares native syntax and full-JSON fingerprint checks with trusted observers.\nNeither the context nor a fingerprint proves broker receipt to a remote authority. The remote\nobserver and policy projection are not implemented yet. The client contract admits an explicit\nread-only `describe-view` operation using only service-access proof. It checks witness, observation,\nprincipal-policy basis and remaining validity, requires no-store responses, and bounds preparation,\nHTTP streaming and validation by the same local deadline. Cancellation cannot restart that deadline.\nThe native handler and serving adapter are still required before this can authorize a remote view.\n\n`parseEndpointCapabilities` normalizes the native caller capability shape. `endpointCapabilitiesWithin`\nchecks route, instance, target and journal containment using the native grant builders. The host\nstill authenticates the granter and checks current grantee, parent and approval records.\nCross-principal relative-target comparisons refuse when containment is unproved.\n\n`authorizeServeGrant` accepts a read-only `ServiceSpecReader`. A trusted provider can supply\nverified registration and contract reads without constructing a writable KV adapter. The function\nstill derives the complete serving surface and creates the process-local grant.\n\n## Owner-bound platform supervisors\n\nA host can start one user's supervisor without retaining that user's login. Pass\n`platformSupervisor: { authorizePlatformAdmin, observeAssignment }` to `startAuthService`, then call\n`handle.platformSupervisorAuthority(owner)` inside the trusted authority process. The first callback\nmust authenticate the platform's administrative caller through the host's own authority. The second\nreads that owner's recorded `PlatformSupervisorAssignment` fresh on every call. An absent,\nended, expired, foreign-account or wrong-revision assignment refuses issuance.\n\nTo end a supervisor, record its assignment `ended` and call\n`handle.endPlatformSupervisorAssignment(owner)`. It rechecks platform-admin authority and refuses\nunless your record already reads `ended`. It retires the manager gate and the issued supervisor and\nexecutor generations. After that, registration, activation and renewal refuse material returned\nearlier, even before it expires, with `platform supervisor assignment for owner <owner> has ended`\nor the retired-gate refusal. Stop the worker as well: an open broker connection lives until its\ncredential's capped expiry.\n\nThe assignment has `kind: \"platform-supervisor\"`, `scope: [\"supervise\"]`, one derived owner,\none manager instance, one lifecycle UID, a revision and a finite `expiresAt` in Unix seconds. It is\nnot an interactive or managed-agent ledger row and grants no `admin`. The returned door is bound to\nthat owner and accepts `PlatformSupervisorAuthorityRequest` with the same owner, assignment revision\nand an existing `RemoteManagerAuthorityRequest`. It serves only `prepare`, `activate`, `renew` and\n`renewStandingBundle`. Unknown fields, generic profiles, mint, human exchange and another owner\nare refused before issuance. Do not give the worker the auth handle, loopback capability or signer.\nThe host carries only the bound door over its authenticated worker channel.\n\nUse `remoteManagerClient` and `registerRemoteManagerAuthority` from `@cotal-ai/manager` for the\nexisting registration ceremony. The result keeps the stock manager material shape and five nkeys.\nAll returned credentials expire no later than the assignment. The supervisor and executor ceilings\nare recorded in the native issued store. The recorded permission set must be byte-identical to the\nauthority plane's signed native permission set at issuance and every renewal, and must never widen.\nThese JWTs are signed by the authority plane, not returned by the user-token callout. The door\nadds no human bearer, callout view, owner ledger grant or enrollment authority. Run admission,\nhost-backed enrollment and shutdown maintenance need their own host composition.\n\nSee [the issuance design](design/user-auth-run-start.md#platform-supervisor-registration).\n\n## The export surface\n\nEverything below is a real export of a published package, reachable from the package root (each\npackage publishes `.` via `dist/index.{js,d.ts}` and ships `files: [\"dist\"]`).\n`@cotal-ai/connector-claude-code` also publishes `./mcp`, which hosts managed Claude Code sessions\nin one process ([Connect Claude](connect-claude.md#host-sessions-in-one-process)).\n`@cotal-ai/core` also publishes `./browser-control` and `./browser-validators-build`\n([Browser control](#browser-control)). Type-only names are marked; import them with `import type`.\n\n`CotalEndpoint` accepts `environment` as an explicit presence label. Pass `null` to omit the label\nwithout reading `COTAL_ENVIRONMENT`. Omitting the option preserves the process environment default.\n\nShared connector sessions report `card.meta.host` and `card.meta.cwd` from the connector process\nwhen the session is constructed. They override agent-file values and are advisory display data.\nThe directory is a startup snapshot, not a model harness's later shell directory. Neither field\nchanges routing or access, and the connector reads no command-line arguments or environment dump\nfor these values. A connector whose process can host several sessions passes\n`{ withholdProcessCwd: true }` as `MeshAgent`'s third argument and reports each session's directory\nwith `setCwd` (`CotalEndpoint.setCardCwd`) once the harness supplies it; until then the field is\nabsent. The reported path is kept byte for byte, whitespace included; an empty string leaves it unchanged. Claude Code sessions do this from their `SessionStart` hook.\n\n**Daemon runners and lifecycle**\n\n| symbol | package | purpose |\n|---|---|---|\n| `runAuthService(args, store?, options?)` | `@cotal-ai/auth` | boot the auth-service daemon; `store` injects the secret material, and `options` takes the daemon lifecycle hooks or [`interactiveManagerSelection`](#interactive-manager-primary). |\n| `runDelivery(args, store?, onStarted?)` | `@cotal-ai/delivery` | boot the delivery daemon; `store` injects the scoped `delivery` cred, and `onStarted` receives a `status()`/`close()` handle once it serves. |\n| `startAuthService(inputs)` | `@cotal-ai/auth` | start one account-scoped auth-service context and return an `AuthServiceHandle` with the loopback `url`, the per-start `cap`, `readiness`, `drain`, and idempotent `close`. `close` rejects when the context did not release its plane claim: the claim row was no longer its own, or the release write failed. The row then stays held, and the next start reclaims it through the liveness oracle. With the optional `publicFace` input it also serves the public exchange face and carries `publicUrl`. The optional `calloutLimits` input sets the auth callout's deadline, concurrency and slow-line limits ([callout deadlines](identity-and-auth.md#callout-deadlines)). With the optional `platformControl` input the handle also has `platformControlAuthority`, the in-process platform control door, `platformControlReadiness`, its read-only readiness read, `observeManagerGate`, the manager gate read a host composing the delegated user intent decisions passes them, and `activateManagedLifecycle`, the activation that host runs at a delegated launch's pinned lifecycle UID. With `platformControl.host` it also has `registerHostIncarnation`, which registers the host process's own endpoint instance and returns the incarnation a delegated execution pins, `observeHostGate`, the read of that endpoint's issuance gate, and `awaitHostFence`, which resolves once a later registration or barrier fences an incarnation. `runAuthService` remains the CLI entry. |\n| `PlatformControlAuthorityRequest`, `PlatformControlInnerRequest`, `PlatformControlAuthorityResult`, `PlatformControlAssignment` *(types)* | `@cotal-ai/core` | the closed envelope, its inner request union, its result and the backend's assignment row for `platformControlAuthority`. `platformControlOwner` in `@cotal-ai/auth` derives the `p_` owner the door issues under. |\n| `startDeliveryService(inputs)` | `@cotal-ai/delivery` | start one account-scoped delivery instance and return a `HostedServiceHandle` with `readiness`, `drain`, and idempotent `close`. `close` rejects when its lease release does not commit or cannot be confirmed, or when another holder's lease row is still there after it. The process runner remains the CLI entry. |\n| `deliveryCredsKey(space, composition)`, `membershipRwCredsKey(space, composition)` | `@cotal-ai/workspace` | build the secret-store keys the delivery cred and the membership feed's rw cred are read/re-signed under. Keys are **per-space**: `space.<hex>/<kind>`. A hosted composition passes `{ injected: true }`. |\n| `retireManagerInstanceIdentity(root, space, expected)` | `@cotal-ai/workspace` | remove a persisted manager identity only if its complete instance id and serve identity still match `expected`. Returns `removed` or `absent`; refuses malformed, nonregular, and changed records. `absent` is not proof of ownership or successful teardown. The caller must separately prove stop and retirement ownership before using it. |\n| `DELIVERY_CREDS_KIND`, `MEMBERSHIP_RW_CREDS_KIND` | `@cotal-ai/workspace` | the operator-facing KIND names (`delivery.creds`, `membership-rw.creds`) those keys are built from, and what renewal results report. A kind is **not** a key: putting a cred under the bare kind writes the pre-0.4 flat location, which nothing reads. |\n| `Manager`, `ManagerOptions` *(type)* | `@cotal-ai/manager` | construct and run a supervisor in-process; `ManagerOptions.secretStore` injects the one store it reads/writes every secret through. `ManagerOptions.remoteAuthority` is the hosted manager-service authority bundle, including host-owned release, retained-validation, goal-index, and serve-time admin-authorization callbacks. |\n| `ManagerOptions.pooled` | `@cotal-ai/manager` | require signerless remote authority and either an explicit non-custodial runtime or `execution: \"none\"`. A pooled composition must supply the assigned account key and all-duty renewal callback; the CLI's default remains unchanged. A signed-in human's manager gets that material from `managerServiceAuthority`. A platform-run control manager gets it from `AuthServiceHandle.platformControlAuthority` with the shipped `remoteManagerClient` builders, as the [platform control authority](design/platform-pooled-control-authority.md) design describes. |\n| `ManagerStatus` *(type)* | `@cotal-ai/manager` | verified status payload, including optional advisory `host` and `version` from the answering Manager. Older payloads may omit them. |\n| `ManagerOptions.execution` | `@cotal-ai/manager` | omitted or `\"runtime\"` keeps runtime execution. Explicit `\"none\"` accepts a genuine hosting user-auth root, or pooled complete signerless authority, with no `runtime` option. It constructs no Runtime and performs no connector inspection, seat launch or workflow hosting. |\n| `createRuntime`, `Runtime` *(type)* | `@cotal-ai/manager` | resolve the spawn backend (pty built in). |\n| `liveKvEntries(kv, filterOrOptions?, options?)`, `LiveKvEntriesOptions` *(type)* | `@cotal-ai/core` | read live KV entries in one finite scan. Pass `{ signal }` as the second argument or after a key filter to cancel. An interrupted scan throws `IncompleteKvScan`; cancellation throws the signal reason, including during an empty-bucket bind. The scan deletes only its owned consumers, including each one nats.js rebuilt from it, after the broker has answered every create those rebuilds sent. A not-found delete counts as gone, a refused one leaves the consumers to broker inactivity expiry (which also covers a crash), and any other delete failure is thrown, as is a not-found delete of a consumer whose create got no reply from the broker before a timeout or a closed connection. A cleanup failure is thrown only when the scan would otherwise return; the scan's own error, its cancellation reason and `IncompleteKvScan` take precedence. |\n\nThe remote manager authority parser accepts `renewStandingBundle` and `renewRunDriver` only with\nan assigned account nkey, the current manager process epoch, and a host-authenticated registration\nproof. A run renewal also names its active holder, takeover, epoch, fencing token, and the two\nexisting nkeys. The host must fresh-check those coordinates against its registration gate and run\njournal before issuing server-selected profiles. A host without that renewal authorization refuses\nthe request. Until the host issuer wires the operations and validates them on real connections,\nthe presence of these types is not an operational pooled renewal guarantee.\n\nAn execution-free control Manager retains native registration, goal recovery, session-ledger,\nrenewal and maintenance duties. Its status reports `execution: \"none\"`, `runtime: \"none\"`,\n`custody: \"none\"`, no children or connectors, and false `classSpawn`, `runHosting` and\n`terminalSessions`. Local NONE uses this existing status schema without a new wire field.\nExecution is recorded per instance. An incompatible record, retained seat/turn inventory or an\nolder unclassified instance refuses boot before recovery. NONE refuses caller-driven writes,\nincluding persona definition, purge, transcript transfer, preservation and resume, and resolves\nno model adapter. It starts no transcript receiver or sweep. Autonomous registration, lease,\nrenewal, session-ledger and goal maintenance still write their native control state.\n\nSelect the genuine participant Manager with a host-issued, instance-pinned `manager-caller`\nview for workflow and terminal operations. That Manager retains the children, workflow journal\nand terminal sessions. The control instance neither adopts roster peers nor proxies user runs.\nMissing participant selection or authority refuses. This capability adds no application routing.\n\nFor a genuine local control instance, pass `execution: \"none\"` without `pooled`, `remoteAuthority`\nor `runtime`. Startup requires that space's local signing trust, provider pin and user-mode mesh\nrecord. It keeps the native persisted local instance and serve identity; local-primary selection\nuses the existing gate. An existing unclassified identity, including a preclaimed identity with no\nexecution record, is refused. A NONE record cannot restart as runtime. Retained seat or turn\ninventory refuses before recovery. Do not remove identity or capability files to change modes.\n\nThe public `cotal supervise --execution none --space <space>` composition supports the same local\nmode. It validates arguments before connector seeding, resolves no Runtime, and rejects startup\nworkload flags and participant registrations. Omitted execution keeps the ordinary PTY behavior.\nThis does not opt an auth service into local-primary, change scopes or broaden native ps.\n\nRuntime remains the default, but local startup now claims its native identity and execution\nrecord during admission, before later authentication and registration checks. A failed start\ncan leave those files classified as runtime. Malformed identity or capability files also refuse\nearlier. These lifecycle timing changes do not change the instance's identity format or authority.\n\nWith `renewStandingBundle` configured, the manager renews all five standing credentials together.\nIt checks every returned credential for the held nkey and assigned account, test-connects each one,\nand adopts them only if the serve epoch has not moved. A refused or failed candidate leaves the\ncurrent credentials in place and records the refusal as cleanup debt until a later renewal succeeds.\nOn shutdown, after the standing context is drained, an expired maintenance executor is renewed\nthrough the existing scoped host operation so deregistration can finish without restarting duties.\n\nIssued-authority references, source coordinates and stores accept nonempty space tokens in\n`[A-Za-z0-9_-]`, including underscores. These boundaries reject input that would be rewritten by\nthe subject-token sanitizer. Endpoint names still use the separate DNS-label grammar.\n\n**Provisioning and minting** (all `@cotal-ai/core`)\n\n| symbol | purpose |\n|---|---|\n| `createBrokerAuth(label)` | mint BROKER trust: the operator and system account one nats-server trusts. One per broker, shared by every space on it. |\n| `createSpaceAccountAuth(broker, space)` | mint one space's own data account, signed by that broker's operator: the add-a-tenant primitive. |\n| `createSpaceAuth(space)` | the one-space convenience: broker trust + one account in a single composed bundle. |\n| `setupSpaceStreams({ servers, space, creds })` | create the space's JetStream streams. |\n| `ensureDefaultDeliveryClass({ servers, space, creds?, deliveryClass })` | write the space's default delivery class at creation so it is wire-discoverable (SPEC section 4). |\n| `serverConfig(broker, spaces, { storeDir, maxFileStore?, maxPayload?, authTimeout?, extraAccounts?, port?, host? })` | render the broker config: one operator, N space accounts. `storeDir` is required, `maxFileStore` caps JetStream file storage in bytes (omitted, nats-server's dynamic default applies), `maxPayload` sets the broker's `max_payload` in bytes (omitted, nats-server's 1 MiB default), `authTimeout` renders `authorization { timeout }` in whole seconds for the auth callout (omitted, no block and nats-server's default), and `extraAccounts` preloads the auth-callout account. |\n| `mintCreds(auth, identity, profile, opts?)` | mint a scoped cred for any `Profile`. |\n| `mintMembershipObserverCreds`, `mintConnectionEvictorCreds` | mint the membership/eviction scoped creds. |\n| `provisionAgent`, `provisionAgentDurables` | create a principal's bind-only durables. |\n| `newIdentity`, `stripSpaceAuth` | a fresh nkey identity; a stripped signer bundle (data signing seed only). |\n| `Profile`, `CredentialKind`, `MintOpts`, `SpaceAuth` *(types)*, `CREDENTIAL_LIFETIMES` | the profile matrix and cred lifetime policy. |\n\n**Auth building blocks** (all `@cotal-ai/auth`)\n\n| symbol | purpose |\n|---|---|\n| `createCalloutAuth`, `startAuthCallout` | the NATS auth-callout responder. It requires an awaited `recordIssuance`, which must durably record each success's broker user key before the response; the authority plane's `recordIssuance` is the stock one. |\n| `createUserTokenIssuer`, `pinnedJwksResolver` | mint and verify the Cotal user bearer. |\n| `createIdpBridge` | exchange a verified IdP JWT for a Cotal bearer (see [the callout contract](identity-and-auth.md#the-idp-callout-contract)). |\n| `deriveOwnerToken`, `validateUserToken` | owner derivation; strict bearer validation. |\n| `cotalAuthProvider` | the self-registering `auth-provider` extension. |\n| `ensureCalloutAuth`/`loadCalloutAuth`, `ensureIssuer`/`loadIssuer`, `ensureOwnerSecret`/`loadOwnerSecret` | read/write the auth secret kinds through a `SecretStore`. Each `ensure*` writes its first value with `create`, so concurrent first calls on one space return the one value the store holds. |\n| `PLANE_CLAIM_REFUSED`, `planeClaimRefusal`, `PlaneClaimRefusal` *(type)* | every plane-claim refusal carries a `PLANE_CLAIM_REFUSED` detail, and `planeClaimRefusal(err)` reads its `reason`: `corrupt`, `live-peer`, `unknown`, `concurrent`, `fenced`, `released` or `lost`. Only `unknown`, an inconclusive liveness observation, is coded `unavailable`. A host can retry contention and stop on a corrupt row without matching message text. |\n\n`startAuthCallout` processes up to 32 connections concurrently. Its hooks must support overlapping\ncalls for different connections. A slow authority check or recorder occupies one slot; other\nconnections can still authenticate. Each response waits for that connection's authority checks,\ndurable issuance and final expiry check. Work beyond the bound waits and can still reach the\nbroker's authorization deadline. The returned `done` waits for admitted hooks when the subscription\nends and rejects an unexpected worker failure after those hooks settle.\n\n**Seams and the wire** (all `@cotal-ai/core` unless noted)\n\n| symbol | purpose |\n|---|---|\n| `SecretStore` *(type)* | the durable hosted-secret seam (get/put/create/delete). `create` writes only while the key is absent and reports whether it did, so it must be one atomic step in the backend. `get()` returns raw seeds/keys into process memory, so it is a blob seam, not HSM/KMS signing. |\n| `FsSecretStore`, `workspaceSecretStore(root)` | the filesystem default. **These live in `@cotal-ai/workspace`, not core.** |\n| `AuthProvider` *(type)*, `Connector` *(type)*, `Runtime` *(type)*, `Command` *(type)* | the extension contracts; implementations self-register on import. |\n| `registry` | the shared registry a composition root pulls surfaces into. |\n| `CotalEndpoint`, subjects, message types | the wire client and shapes. |\n| `ParsedArgs` *(type)* | the shape the daemon runners take (see below). |\n\nFor a Linux Unix-socket adapter, `peerCredentials(socket)` from `@cotal-ai/seat` returns\nkernel-observed peer `pid`, `uid` and `gid`. Compare these against the host's authorization\npolicy; request-supplied identity and process liveness do not replace that policy or a\nlifecycle fence. The helper starts no custodian and refuses unsupported platforms or a\nmissing native helper.\n\nThe runners take a CLI-shaped `ParsedArgs`, not a typed options object, so a host fabricates one:\n\n```ts\nconst args: ParsedArgs = { values: { space, server, port: \"0\" }, positionals: [], raw: [] };\n```\n\nFor an embedded delivery instance, use `startDeliveryService` instead. Its `HostedContextInputs`\ninclude the account public key and lifecycle UID, space, broker URL, injected store, stable\n`storeIdentity`, and an explicit `stateDir`. The store must declare that same injected identity.\nThe initial delivery credential must belong to the assigned account. The function returns only\nafter the delivery responder is bound. `close()` withdraws serving and releases only the lease\nowned by that instance. It closes both membership connections even when a disconnected drain\nfails, so they cannot reconnect after closure. It rejects when its release does not commit or\nthe broker cannot confirm it, or when another instance's lease row is still there afterwards.\nIf the delivery connection drops or is down while the release is in\nflight, `close()` waits up to the broker-gone window (`COTAL_DELIVERY_BROKER_GONE_MS`, 15 seconds\nby default) from the drop for it to reconnect, and repeats the release once on the reconnected\nconnection before it decides. `drain()` returns the same promise. A successor is refused while such\na row lives, and the bucket TTL expires a row the instance left. Credential-expiry health state clears after\nsuccessful broker-verified adoption through the existing `reloadCreds` rail. A failed start\nrefuses locally without exiting the host process or stopping another account's delivery service.\nIf a health fault occurs during an asynchronous store read, startup rejects when the read returns\nand closes any resources created by that late completion.\n\n`startAuthService` takes the same `HostedContextInputs`. The store must declare the assigned\ninjected identity, and its data account must be the assigned account. The IdP pin and ledger live\nunder the explicit `stateDir`. The auth plane's instance identity holds its private serve seed, so it\nlives in the store under `authInstanceKey(space)`. A record an earlier release kept under `stateDir`\nmoves into the store on the first start.\nThe context never resolves a workspace root from the working directory and has no local manager, so\nonly remote manager gates can be selected. It returns after\nthe authority plane, the callout subscription and the loopback listener are bound. A start that\nfails closes the connections it opened and releases its plane claim, so a retry on the same space\ncan claim it. A fenced plane or\na lost broker connection makes that context `unavailable` and closes it without exiting the process.\nThe host writes no discovery file for it. The handle carries what `auth-service.json` holds for a\nCLI start: the loopback `url`, `publicUrl` when a public face runs, and the per-start `cap`. The cap\nalone authorizes the loopback host actions, lifecycle retirement and managed-agent enrollment\nverification, so keep it in the authority process. `publicFace` takes the CLI's public face inputs\n(`port`, `url`, `trustedProxy`, `advertisedServer`, `agentProvisioningUrl`) under the same rules,\nand a face without a port refuses to start.\n\nTwo optional inputs serve a platform composition. `platformControl: { observeAssignment }` adds\n`platformControlAuthority` to the handle. It is a typed in-process method, served on no listener,\nthat issues the manager-service request family for the one control manager the backend assigned to\nthis account, under a derived `p_` owner. It reads the assignment fresh on every call and refuses\nan IdP token, another account, a stale revision, another instance or lifecycle, and an instance\nanother owner registered. It refuses `prepare` and `activate` while the assignment's named\npredecessor is still registered or frozen. The same input adds `platformControlReadiness(instanceId)`,\nthe route for a host that needs to know whether its assigned control manager is serving. It returns\nthat instance's attributed `status` reply and refuses any instance the current assignment does not\nname, or one whose gate another owner holds. It reads over the context's own connection, whose\ngrant is the assigned instance's `describe` and `status` and its own reply rail. That connection\nrenews in process like the context's other connections and never leaves it, so the host lends no\nhuman or operator credential to a worker, mints no control instrument per read, and does not read\nliveness off the manager process. Without the input both members are `undefined`.\n`standingRenewableTtlSeconds` is forwarded unchanged to the authority plane, which bounds it to 5\nto 86400 seconds. It is a trusted-host input for the renewal rehearsal, and no request or CLI flag\nsets it. `issuerSessionTtlSeconds` sets the credential lifetime of the plane's held issuer session\nthe same way, bounded to 5 to 300 seconds, with the five-minute `issuer` lifetime as the default. SPEC §13.1 and §13.6 define the view.\n\nThe auth plane can renew a registered manager's five standing credentials from the current\nservice registration. Run-driver renewal reads the hosted run attempt and checks its active\nfence as well as the manager's open issuance gate and process epoch. A moved gate or run\nfence refuses issuance. These primitives do not establish a complete pooled deployment.\nA fresh auth plane can initialize without a delivery-admin responder. Reclaiming a held claim from a dead predecessor needs the delivery\ninstance first: its admin rail must complete the broker connection-liveness sweep before the\nauth plane takes the claim. An absent or inconclusive oracle refuses the reclaim.\n\n### Remote MCP gateway\n\n`@cotal-ai/connector-core` exports `registerCotalGatewayTools(server, host, source?, options?)` for\na service that serves Cotal to a hosted MCP client over HTTP. A hosted client can send many\nconversations through one bearer and one MCP session, so a request does not say which conversation\nsent it. Each conversation calls `cotal_connect` and passes the `connection_id` it returns on every\nother tool call. A missing, unknown or other-account handle returns `CONNECTION_REQUIRED` and runs\nnothing. No call falls back to another connection of the account.\n\nThe host implements `GatewayHost`:\n\n- `account(auth)` returns the account the request authenticated as, read from the SDK's `AuthInfo`.\n It throws when the request has none, and the tool then runs nothing.\n- `open(account, name, context?, selection?, approvalId?)` starts a connection only after the person\n approves its permissions. `selection` is a proposal. Throw `ApprovalRequired` with the request ID,\n approval page, expiry and proposal while they decide. The tool returns a structured pending result\n and a readable link, with no connection handle. `approvalId` resumes one unchanged request when\n `options.approvalResume` is enabled. It conveys no authority. Bind it to the authenticated account,\n space, name and request generation. An issued approval cannot grant a replacement connection.\n Throw `NameTaken` only for an authoritative name collision. A new request tries `name_2` and later\n variants up to `GATEWAY_NAME_ATTEMPTS`; a resumed approval never renames. The collision check and\n issue must be atomic. Other errors reach the caller without renaming and must not carry secrets.\n- `find(account, id)` and `close(account, id)` act only on a connection that account owns.\n\n`cotal_connect` refuses a name `assertValidName` rejects before it calls `open`. Its reply names\nthe channels the new connection reads, may join and may post to, from the configuration its grant\nproduced. `GATEWAY_TOOLS` names the mesh tools the gateway offers, `cotal_docs` included. A native\nembedder whose host issues each conversation its own grant may pass `options.tools` from\n`NATIVE_GATEWAY_TOOLS`, which adds spawn, despawn, persona, run and reconnect but not yield.\nRegistering a tool offers it to no connection by itself: a connection calls only the tools its\nhost lists in `GatewayConnection.tools`, default `GATEWAY_TOOLS`, and only those its credential's\ncapabilities allow. With `options.selection`, `cotal_connect` takes channels, a role and capabilities,\nbuilds a canonical proposal with core's `conversationSelection`, and hands it to `open`. Its\ndescription tells the agent to ask in that first call for the channels, role and capabilities it\nalready knows it needs, so the person approves one request. Only the\nperson's decision in the authority's authenticated UI is consent. The approved selection may differ\nfrom the proposal and must stay within their current authority. The empty approved selection still\nincludes direct-message send and receive and own activity publication; disclose these before\napproval. A model flag, API bearer or ordinary tool approval cannot approve the request. Unsupported\napproval paths refuse before issuing a grant. One tool list serves every connection, so no\nadvertised text names one connection's channels. Each call runs against that connection's own\nconfiguration. Authentication, credential issuance and revocation and durable connection records\nstay with the host.\n\nA remote MCP client gives the server no way to start a turn, so the gateway adds `cotal_wait`. It\nreturns at once when a message that should wake the agent is buffered, and otherwise as soon as one\narrives, with the same reply `cotal_inbox` gives. Wake-worthy follows the agent's attention: direct\nmessages, role requests and @mentions always, other channel traffic only in `open`. With none, it\nreturns after `options.waitSeconds`, which defaults to `GATEWAY_WAIT_SECONDS` (50). Keep it under\nevery proxy and client timeout in front of the service. The reply is one JSON body, so nothing is\nsent until the wait ends: Claude Code gives a remote server 60 seconds to the first byte, Cloudflare\nends an origin response after about 100 seconds and claude.ai ends a tool call after 240. A wait\nwhose client closes the request stops listening, and a read whose client is gone by the time it\nwould clear messages clears nothing, so neither takes a message it cannot deliver. A wait ends\nwhen its connection closes, also while the broker is unreachable; it listens for `MeshAgent`'s\n`stopping` event. In `focus` an @mention is not buffered, so the gateway counts the ones\nsince the last read, and a wait that starts after one returns it at once. Every other routed tool\nexcept `cotal_inbox` adds a line to its result when wake-worthy messages are waiting.\n\n`handleGatewayRequest(host, { req, res, body?, auth?, source?, instructions?, approvalResume?, selection?, waitSeconds? })`\nserves one HTTP request to the endpoint with the package's own MCP server, so the embedding service\nnever imports an MCP SDK or a zod version of its own. The service authenticates the request, answers\n401 itself when that fails, and passes the result as `auth`. A framework that already parsed the JSON body passes it\nas `body`. `selection` turns on the permission request described above for a hosted endpoint. The endpoint is stateless: each POST gets a fresh server and a JSON response, and every\nother method answers 405. A `cotal_wait` call holds its POST open for up to `waitSeconds`.\n`GATEWAY_INSTRUCTIONS` is the server instructions text sent when `instructions` is omitted.\n\n`serveGatewayStdio(host, { input?, output?, source?, instructions?, waitSeconds?, wake? })` serves the same\nsurface over stdio, for a local client such as Claude Desktop that launches one process for all of\nits conversations. A stdio request carries no authentication, so `host.account` receives `undefined`\nand names the local user. A client that cancels a call aborts its signal, so a cancelled wait stops\nlistening. The streams default to the process's own, and stdout then carries only MCP.\n\nAn embedder whose client can be woken passes `wake`, to `serveGatewayStdio` or in the options of\n`registerCotalGatewayTools`. The gateway calls `wake.signal(connection, preview)` when a connection\ngets something that would end a `cotal_wait` while no wait holds it. A true result means a reader\nheard the signal, not that it received complete message content. The preview never consumes mail.\n`cotal_connect` adds `wake.listening(connection)` to its reply. An embedder delivering full content\ncan return false from `wake.inboxNotice(connection)` to omit competing inbox-read advice from other\ntool results. Notification-only clients retain that advice.\n\n`wake.attach` receives a rearm callback. Call it without arguments when a replacement reader starts\nlistening. Call it with one connection after confirmed inline delivery to reoffer that connection's\nremaining work. Pass `false` as its second argument to clear the latch without immediately retrying\na refused handoff. Ordinary inbox reads and waits also clear the latch. An adapter offering complete\ninline messages can use `prepareInlineDelivery`: hold whole automatic messages, validate the final\ntransport size, recheck the batch before admission, then settle it with the native result. A failed\nor unknown admission releases the hold without committing. Never settle successfully on a preview,\nsocket write or queued native call. `GATEWAY_INSTRUCTIONS` combines `GATEWAY_CONNECTING` and\n`GATEWAY_LISTENING`, so an embedder can supply its own listening instructions.\n\n### Private tool results\n\n[SPEC §13.19](../SPEC.md#1319-private-tool-results) accepts a private, consent-bound read path for\nmanaged-agent tool results. It is not served or enabled. Core exports the closed\n`ToolResultConsent`, `ToolResultRevocation` and `ToolResultServingMaterial` contracts, their\nparsers, and the frozen `TOOL_RESULTS_CLUSTER` declaration. These parse structure and static\nbindings only. They do not verify a consent signature, establish human proof or read current\nrevocation and lifecycle state. The serving material's grant coordinates are not a branded\n`EpServeGrant` and confer no authority. `parseToolResultAnswer` also checks the UTF-8 byte count;\na schema's character limit alone is not the byte bound.\n\n`@cotal-ai/auth` exports `verifyToolResultHumanProof` for the consent prerequisite. It verifies\nan EdDSA IdP JWT against the existing issuer, audience and key pins, then requires integer-second\n`auth_time` no later than the decision and at most 300 seconds old, plus a signed `amr` array\ncontaining `pwd`. The host compares elapsed milliseconds without rounding its clock to seconds.\nJWT clock tolerance does not widen this window. Ordinary bearer exchange does\nnot require these claims or turn them into consent authority.\n\nThe loopback-only `POST /tool-result-human-proof/verify` takes only `{ idpToken, subject }` with\nthe host's current capability and no Origin header. The host supplies its authenticated session\nsubject. Success returns `{ authorized: true, sub, owner, authTime, exp }`; the owner derives from\nthe verified subject, which must match the session. The door verifies proof only. It does not\nsign consent, issue credentials, register a service or serve private content. A host must still\nrefuse platform keys and check current membership and lifecycle at consent admission.\n\nA host may opt into consent issuance with `startAuthService({ ..., toolResultConsents: { keyId,\nresolveAnchor } })`. Provision its Ed25519 nkey seed under `toolResultConsentKey(space)` in the\ninjected private store as `{ ver: 1, keyId, seed }`. The resolver reads that space's current\n`consents` anchor with scope `tool-results`. Missing, corrupt, revoked or mismatched signing\nmaterial refuses. Neither the private store nor the resolver belongs in a worker or client.\n\nThe loopback-only `POST /tool-result-consent/issue` requires the current host capability and no\nOrigin header. Its closed input is `{ id, idpToken, subject, accountPublicKey, holder, target,\nttlMs }`. The host resolves those coordinates from its current authenticated membership and\naccount assignment. `holder` carries `{ actor, lifecycleUid }`; `target` carries `{ owner,\nactor, lifecycleUid }`. Auth verifies the signed password proof and derives the owner itself,\nrequires a current same-owner interactive holder and managed target, and caps the window at\n24 hours. It returns only `{ consent }`, after a create-only `consent.<id>` auth-store write.\nDuplicate ids refuse. A failed or lost acknowledgement returns no consent and never retries.\nThe host must not label an unknown outcome completed or resubmit it automatically.\nOnly the auth mint writer holds consent-KV publish authority. The environment admission writer\nand remote manager issuer do not inherit that grant. Create-only enforcement remains in the recorder.\n\nThis door is absent from the public face. Without the opt-in signer it answers unavailable.\nIt installs no serving material, revocation store, caller view, capture or result reader.\n\nPublic tool arguments and results remain withheld. Auth and host issuance, Manager material,\nconnector capture and the browser caller must each be landed and qualified in the\n[design's owner order](design/private-tool-results.md#9-owner-order), then carried by a stock\nrelease before activation. Without a complete authoritative revocation snapshot and an established,\nenforced clock-skew bound, the serving commands must answer `unavailable`.\n\n### Browser control\n\n`@cotal-ai/core/browser-control` describes and invokes an endpoint from a strict-CSP page. The page\ncompiles no code: the host passes validators it generated at build time with\n`generateBrowserContracts` from `@cotal-ai/core/browser-validators-build` (Node only). The generator\ntakes each cluster document with its recorded digest and schema roots, recomputes every digest and\nrefuses a mismatch or a missing root before writing anything. It supports single-document closures\nonly, so a command whose closure spans several documents refuses. The generated module imports\nAjv's runtime helpers (`ajv/dist/runtime/*.js`), so the host's bundler must resolve `ajv` from\nwhere the host writes that module.\n\n`openBrowserManagerCaller` opens a Manager caller for ONE instance the person selected; there is no\nimplicit selection. It takes the broker's websocket URL, the space, the principal and lifecycle the\nbearer is bound to, the instance, and the Manager's contracts generated from\n`managerBrowserContractSource()` (`@cotal-ai/manager`). Authority comes from an `acquire` callback\nthat returns the person's own `manager-caller` bearer and the space's sentinel credential; an\nembedding's backend obtains the bearer from the stock exchange with the person's IdP proof. The\nbearer's space, principal, lifecycle and instance are checked before anything is dialled, and the\ndescribe is pinned to that instance. The view carries only the commands the person's ledger scope\ngrants. `spawn`, for example, carries `spawn`, `despawn`, `inspect`, the persona commands and\n`goal-result`, plus the launch reads `status`, `models` and `resolve-cwd` on that one instance,\nwhile operator reads such as `ps` and `slots` come only with `admin`; the broker\nrefuses a command the view does not carry. The connection never reconnects on its own; `reopen`\nacquires again and re-checks every pin.\n\n`followGoal` submits a goal command once under an envelope id the host persisted before calling\nit, and follows the goal to its terminal with the stock goal follow. Live progress settles the goal\nonly when it comes from the instance and epoch that accepted it; any other terminal settles nothing\nand prompts a read of the goal's own record. `reconcileGoal` reads an\naccepted goal back through the Manager's `goal-result` command, and `verifyGoalResultFact` checks\nthe returned fact, including its outcome digest, through Web Crypto. Nothing here retries. Three\noutcomes stay distinct: an error reply is a refusal; a goal accepted but not seen to finish answers\noutcome `unknown` and is read back, never submitted again; a request no instance answered throws\nthe stock unanswered error (`unansweredRequest`).\n\n`POST /manager-instances` on the auth service lists the signed-in person's own Manager instances. It\ntakes `{ idpToken }`, verifies it as the human exchange does and answers\n`{ v: 1, owner, complete: true, instances: [{ instanceId, placement, state }] }`. `placement` is\n`remote` or `local`; `state` is the verdict the `manager-caller` exchange selects on (`candidate`,\n`not open`, `not registered`, `not this owner's`, `unknown`). A `candidate` is registration\nevidence, not proof that the instance answers; a describe pinned to it is. The route refuses\nbrowser-origin requests like every exchange route, so a page reaches it through its own backend,\nand a failed gate read answers 503, never an empty list.\n\n### Remote manager client composition\n\n`@cotal-ai/manager` exports the `remoteManagerClient` namespace, containing the stock remote\nrequest builders and response validators, and `registerRemoteManagerAuthority` for registration\nwith a host-issued prepare credential. It returns the process epoch and registration revision its\nown registration committed. When a later start of the same instance registers before this start\nauthorizes its serve grant, this start is refused with `expired`.\n`RemoteManagerIdentityState` describes the five private\nmanager identities stored under an explicit account-local root. Use these public exports when\ncomposing `ManagerOptions.remoteAuthority`; do not copy CLI validators or import private modules.\n`managerClusterArtifacts()` returns the canonical document, manifest and their digests used by\nregistration. Pass its `[document, manifest]` pair as `contractArtifacts` to both\n`remoteManagerRegistrationProof(owner, state, contractArtifacts)` from `@cotal-ai/core` and\n`remoteManagerClient.remoteManagerAuthorityRequest(state, actor, \"activate\", { registrationProof, contractArtifacts })`.\nThe request builder takes each operation's coordinates as named fields of its last argument.\nThe host still validates the artifact closure and current registration before activation.\n`managerBrowserContractSource()` returns the same document with its closure digest and each\ndistinct schema root, the input `generateBrowserContracts` from\n`@cotal-ai/core/browser-validators-build` takes at a host's build. Its closure manifests are left\nout because they are not schemas; the generator recomputes every digest and refuses a mismatch.\nThe namespace includes closed standing/run renewal, admission, maintenance, enrollment,\nretirement and goal-index scan helpers. `publicIdentities(state)` returns the `identities` record every request\ncarries: the five public ids, in the order the host echoes them. `remoteManagerClient.remoteRunHosting` builds the four `runHosting` callbacks from the registration\nand the transport you supply for the host's run admission, run attempt and authority requests, so\nyour manager sends the run requests the stock manager sends. The namespace provides no signer or\nnew grant. The host still owns authenticated issuance, current registration and activated-run\nobservations, and any guarded foreign-holder repair.\nAn embedding must preserve those checks and supply a supported runtime; the client exports alone\ndo not provide a pooled runtime, an authority service or a complete hosted context.\n\n### Long-lived endpoints take a bearer function\n\n`EndpointOptions.bearer` accepts either a string or a function, and the difference is not stylistic.\nA string is minted once, so when it expires (which it will: callout bearers live minutes) the\nendpoint has nothing to renew with. It will not present the dead token to the broker, since that is\na guaranteed denial that still costs a full auth-callout round trip. It refuses to reconnect, emits\n`warning` saying which case it is in, and retries on a widening backoff until the process\nre-authenticates and rebuilds it. Retry notices use `warning` rather than `error` because Node\nrethrows an unhandled `error` event and would kill a host the endpoint is still trying to recover.\n\nWhen the broker refuses a bearer at connect, the `warning` says the broker refused this endpoint's\nbearer and that the auth service logs why, because nats-server passes the client no reason. The\nendpoint then retries on its capped backoff. Each wait is a random point in the upper half of its\nstep, so endpoints refused together, after a broker restart or by an auth limit, do not retry\ntogether. A bearer source that throws an error with a numeric `retryAfterSeconds` is called again\nwhen those seconds have passed, not before, and a reconnect inside that wait dials on the bearer it\nholds. The auth provider's rate-limited exchange throws that way, and `agentBearerCommand` prints\n`retry-after <seconds>` for it.\n\nPass a **function** for anything that outlives one bearer. That is a renewal source: it is called\nahead of each expiry and again whenever a reconnect finds the cached bearer dead, and it requires\nexplicit `card.owner` and `card.actor`. The first-party surfaces already do this\n(`UserViewAuth.source`, the connector's `agentBearerCommand`). A string bearer is for a short\none-shot connection.\n\nA `MeshAgent` a host runs in its own process takes the same kind of source. Pass\n`userAuth.bearer`, a function returning a fresh bearer, instead of `userAuth.bearerCmd`, the argv a\nlaunched seat execs. Such an agent has no manager-call bearer, so its spawn, despawn, persona and\nrun calls return a refusal without reaching a manager.\n\nLong-lived hosts must also subscribe to the endpoint's `warning` event. It carries conditions the\nendpoint is surviving, including failed credential renewal, reconnect retries, its own DM inbox\nmissing from the broker while the connection is up, a durable leave\nit keeps retrying after the broker refuses a durable channel's live subscription, and a channel\nregistry entry that does not decode to a valid config, such as a raw put of an unknown delivery\nclass or of `null` on the defaults key. The endpoint drops that entry from its cache and applies the\ndefault policy until a valid entry is written. The DM inbox warning comes once, after the broker\nhas reported the inbox missing twice. The endpoint does not recreate the inbox. It keeps checking\nand receives again if its provisioner creates the inbox again. A host may choose\nto ignore warnings for a one-shot endpoint whose awaited operation owns the verdict, but that choice\nshould be explicit. An unhandled warning is nonfatal and silent.\n\nThe `error` event carries a fault the endpoint cannot return from a call, such as a refused\nsubscription or a refused publish that no request was waiting on. Attach a listener before `start()`,\nsince Node throws on an unhandled `error`. A denial the broker returns to a request, such as an\nobserver's read of the DM stream, reaches only that call, which decides what it means, and is not\nemitted again as an `error`.\n\n## Booting the daemons\n\n### auth-service\n\n`runAuthService(args, store?, options?)` reads its provisioned long-lived secret kinds (service keys, callout\naccount, issuer keys, owner secret) through the injected `SecretStore`; a host provisions those into\nthe store first. It is a **signer and identity authority**, not a scoped daemon: at runtime it holds\nthe data-account and callout-account signing seeds, the issuer's private JWKs, and the\nowner-derivation secret in process memory (`SecretStore.get` exports raw values). The IdP pin and the\nactor ledger are **not** store-injected: `runAuthService` resolves them under\n`userAuthStateDir(findCotalRoot(), space)`, a path relative to the process working directory, so a\nhost provisions those into that exact directory (neither `store` nor `COTAL_HOME` selects it). It\nalso writes an ephemeral `auth-service.json` discovery file there that carries the live exchange\ncapability. That file appears only after every plane is bound, so waiting on it is the readiness\nsignal: a host that also passes the daemon's pid to the provider's `ready()` gets a process-bound\nwait. The wait extends past the base timeout while that pid is alive, up to a fixed bound, and it\nends at once when the pid exits.\n\n```ts\nimport { runAuthService } from \"@cotal-ai/auth\";\n// store implements SecretStore over your secret backend; get() returns raw seeds into memory.\n// Provision the auth secret kinds into the store, AND the IdP pin + actor ledger under\n// userAuthStateDir(findCotalRoot(), space), before this call.\nawait runAuthService(\n { values: { space, server: brokerUrl, port: \"8081\" }, positionals: [], raw: [] },\n store,\n);\n```\n\n### delivery\n\n`runDelivery(args, store?, onStarted?)` runs from a **pre-minted scoped `delivery` cred** and never loads the\nsigner. Provide the cred either through the injected store (under\n`deliveryCredsKey(space, { injected: true })`) or with a\n`--creds` file; the two are mutually exclusive. The daemon re-fetches the cred from the store at 75%\nof its JWT lifetime and fails loud rather than riding to expiry, so **something must re-sign a fresh\ncred into that same store**. When that read finds the previous generation still there, the daemon\nreports the missed remint and retries in 60 seconds. The current cred stays live until its expiry,\nand the store is read once per retry rather than once per second.\n\n```ts\nimport { runDelivery } from \"@cotal-ai/delivery\";\nawait runDelivery({ values: { space, server: brokerUrl }, positionals: [], raw: [] }, store);\n```\n\nThat renewal is a **signer** operation, not the delivery daemon's:\n`remintDaemonCreds(root, space, store?, { preflight? })` (`@cotal-ai/workspace`) reads the `SpaceAuth`\nsigner **through the same resolved `store`** (`getSpaceAuth(store ?? workspaceSecretStore(root), space)`,\nkeys `auth/broker.json` + `auth/account.<key>.json`; the pre-split `auth/auth.json` monolith is\nmigration input and the container signer mount only) and re-signs the daemon creds (`delivery.creds` and the membership feed's\n`membership-rw.creds`) back into that store. The injected `store` is both the signer source and the\ncredential destination, never a split. `space` is **required** and validated against the store's signer, so a\nstore swapped to a different space cannot re-sign over the wrong broker's creds. `preflight` is a\ncaller-supplied proof that the broker accepts the credential. The reference `Manager` passes a\n`probeConnect` over its `servers`. It gates **every** candidate before overwriting the last-good,\nwhether the signer is a full bundle or a stripped projection: a bundle's JWT chain proves only that\nit is self-consistent and\nnamed the space, NOT that its account is the broker's *current* account for that space (two\n`createSpaceAuth(space)` calls yield same-named, different-account chains), so a same-label alternate\nsigner would otherwise mint a broker-dead cred and clobber the good one. The offline local repair (`doctor auth --fix`) has no preflight. It permits the overwrite only\nunder **authority continuity**: the candidate must be signed by the same account signing key (`iss`) as the current\n(already broker-accepted) cred. A same-label alternate account breaks continuity and is refused, full or\nstripped; a legitimate local re-sign is continuous and proceeds without a network. The reference\n`Manager` runs it on a schedule against its **own**\n`secretStore` (see below), so passing the manager and the delivery daemon the *same* store closes the\nrenewal loop end-to-end on an injected backend: the manager reads the signer from the store, re-signs\ninto it, and the daemon adopts each generation on a preflight-proven 75% timer. The stock\ncross-host composition cannot satisfy that by writing one filesystem and fingerprinting another:\n`Manager.start()` and every later remint challenge the daemon's `reloadStoreIdentity` and a\ndivergent pair is refused naming both stores. The identity is the store the daemon actually\nreloads: an injected coordinate, the workstation root only when `--creds` is\n`<root>/.cotal/<spaceSegment(space)>/delivery.creds` (matching the canonical arm), the\nfile's own directory for any other `--creds` path, or the workstation root. A filesystem\nstore is also named by a random id it records in `store.id` inside its own directory, so two\nhosts that use the same root path are two stores. No key and no `--creds` file may be that\nfile under any name, and a `store.id` that is a symbolic link or holds anything but a lowercase UUID is refused. Uninjected\n`--creds` that names one real workstation while process cwd resolves another is refused\nat start, naming both, because membership-rw still uses `findCotalRoot`. A `--creds`\npath that is not under any `.cotal` tree is not that case and is not refused here. It never\nwalks ancestors with `findCotalRoot`. No bound daemon is not a named\nstore, so start proceeds; a later daemon on a foreign store is refused on the next remint.\nThe first-party filesystem adapter declares its workspace-root identity on the store itself. Other\ninjected adapters declare their stable coordinate on `SecretStore.identity`, or name it in\n`COTAL_SECRET_STORE` on both processes. It never throws: it\nreturns per-file results (`skipped: \"no-auth\"` when the store holds no signer records),\nso the caller must check them or the cred still rides to expiry. A composition whose signer lives in\nKMS/Vault simply injects that store; no bespoke renewal is needed. A `--creds` file path must be\nreplaced atomically before the 75% read. The signer can now be injected behind the store seam, which\nresolves custody. The remaining hosted gap is signer **isolation**. The seed is still decrypted\nin-process at the manager's uid, so it needs an OS sandbox or remote signer.\n\n### Supervisor signing authority\n\n`@cotal-ai/manager` exports the `Manager` class; there is **no** `runSupervise(opts)` runner. The\nprivate CLI `runManager` also does broker-reachability checks, space/default resolution,\nroster/launch parsing and materialization, installed-extension resolution, signal handling, staged\npre-spawn, and the forever wait. A host composes that lifecycle itself around `Manager`:\n\n```ts\nimport { Manager } from \"@cotal-ai/manager\";\nconst mgr = new Manager({ space, servers: brokerUrl, workspaceRoot });\nawait mgr.start(); // then wire your own SIGINT/SIGTERM -> mgr.stop()\n```\n\n`stop()` runs once. A later call joins the stop in progress and settles with it, and a call that\nasks for a different `withAgents` than the running stop is refused.\n\nUnlike delivery, the manager is **not** a pre-minted-scoped-cred daemon (auth-service is also a\nsigner: it holds fewer artifacts than the full trust bundle, but its data-account signing seed still\ngrants complete data-account mint authority on compromise, so this is not least-privilege). On `start()`\nthe manager reads its space's full trust chain **through its `secretStore`** (`getSpaceAuth(this.secrets,\nthis.space)`, composed from `auth/broker.json` + `auth/account.<key>.json`; a container may instead\nmount a stripped signer bundle at the legacy `auth/auth.json` key) and **self-mints** its supervisor cred and renewals from the\ndata-account signing seed. In static mode it also mints every per-agent cred from that seed; in user\nmode agents instead receive callout-minted bearers, but the manager still holds the signing seed for\nits own creds and renewal. So a hosted supervisor is a **trusted per-tenant account-signer process**,\nnot a least-privilege connect client. It additionally requires a `~/.cotal/meshes/space.<key>.json`\nregistry record and the workspace user-auth marker to start in user mode. `ManagerOptions.secretStore`\ninjects the one `SecretStore` the manager uses for **the signer itself (the split trust\nrecords)**, daemon-credential renewal (`remintDaemonCreds`), and per-agent secrets,\ndefaulting to the workspace filesystem store; pass the delivery daemon the *same* store for end-to-end\nhosted renewal. The store declares the same identity on both processes, or both set\n`COTAL_SECRET_STORE` to the same coordinate. The manager\nremints no daemon credential when the daemon names a different store, including a daemon that binds\nafter start; it keeps running and serving its own agents, so one space can carry a manager on more\nthan one workspace root. That manager also stays off the space's renewal lease, so a manager or a\n`cotal doctor auth --fix` on the daemon's store can still take it. Pointing several managers at one coordinate is safe: the store identity\nalone cannot pick an owner (it carries no holder and no tiebreak, so every manager sharing the store\nmatches), so the manager that also holds the space's renewal lease is the one that remints and the\nrest skip it. Without that lease two owners would remint on independent timers with no ordering\nbetween them, and one write would land between the other's re-sign and its fingerprint-only\n`reloadCreds`. `cotal doctor auth --fix` takes the same lease before it re-signs, so a live manager\nand a local repair never race each other either. The signer IS now injectable: a hosted composition injects a KMS/Vault store and no\nsigning seed lands on the hosted disk. What remains is signer **isolation**. The seed is decrypted\nin-process at the manager's uid. That issue needs an OS sandbox or remote signer; it is no longer a\ncustody problem. The other knobs are `workspaceRoot` and the process-global `COTAL_HOME`.\n\nA store, runtime, extension or host callback the manager calls may reject with any value, including\n`null`. The manager logs or refuses with that value's `message`, or with the value itself as text\nwhen it has none, and keeps serving. A value it cannot read reports as `an unreadable rejection`.\n\n> Scope note: the **static-auth** operator paths (`cotal spawn`/`join`/`status`/`web`, via\n> `mesh-target` → `connect`/`preflight`) still read the signer from the local split records (sync\n> `loadSpaceAuth`). That is the single-machine composition, where the signer is on local disk by the\n> static-auth model; multi-tenant hosting runs **user mode**, which never mints from on-disk trust. The\n> store-injectable signer path is the hosted-server set: the manager, `remintDaemonCreds`, and delivery.\n\nThe typed remote-manager authority contract includes a one-shot terminal phase. A host implements\n`remoteAuthority.prepareAgentRetirement` to revoke the managed grant and finish its resumable\nrelease while preserving the UID, then `remoteAuthority.mintRetirementRequester` returns the\nhost-signed JWT for a fresh participant-owned nkey. The credential is pinned to the authenticated\nowner, server-derived manager serve principal, current instance epoch, and exact target lifecycle.\nThe manager then uses the existing auth `retireLifecycle` rail with the operation id derived by\n`managedRetirementOpId(target.lifecycleUid)`. This derivation is the reference remote-Manager\ncomposition's closed contract, not a rule for every retirement entry point; interactive retirement\nkeeps its existing operation identity and remains compatible. The `retireLifecycle` rail independently\nrecomputes the managed id from its broker-pinned target before any gate, head, intent, or barrier\naccess, so mint-time validation is not the terminal boundary. A failure keeps\nthe alias held. This does not expose the auth barrier or give the participant signer authority.\n\nIf the participant disappears after prepare, the host finishes the retirement itself on the auth\nservice's loopback face: `POST /managed-lifecycle/retire` (exported as `MANAGED_RETIRE_PATH` from\n`@cotal-ai/auth`) with the `Bearer <cap>` from `auth-service.json` and only\n`{ owner, actor, lifecycleUid }`. It has the interactive door's guards (POST only, no `Origin`, JSON,\ncapability, closed body) and is never served on the public face. The managed grant must already be\nrevoked at that uid, or it answers 409. It runs the same `managedRetirementOpId(uid)` operation as\nthe rail, and the rail and the door share one in-process flight, so a late participant request and\nthe host call converge on one barrier.\n\n| lifecycle head | answer |\n| --- | --- |\n| absent, or `retired` at another uid | `200 { retired: false, lifecycleUid, notStarted: true }` |\n| `active`/`retiring` at another uid | `409` |\n| `retired` at this uid | `200 { retired: true, lifecycleUid, alreadyRetired: true }` |\n| `active`/`retiring` at this uid | the barrier runs, then `200 { retired: true, lifecycleUid }` |\n\nDeprovisioning durables stays with `deprovisionAgent` and a `deprovisioner` credential. Pass `memberChannels` to both to also purge the retired lifecycle's durable membership rows on those concrete channels. The manager fills that list from the launch's concrete read channels and the delivery daemon's read-only `lifecycleMemberships` admin verb. Before it reads that verb, it calls `fenceLifecycleAcl` under a deprovisioner credential for the same lifecycle with no member channels. That narrows the lifecycle's read-ACL row to no reads, and a durable join the inventory does not see then removes its own row. When that verb cannot answer, rows on other channels stay retained, the teardown logs the inventory as incomplete, and retirement remains held pending retry rather than releasing the alias. Each teardown examines two exact consumers, one ACL key and the named member keys. KV deletion uses a native revision condition; a lost condition with a live replacement refuses rather than claiming absence. Consumer INFO checks before and after DELETE distinguish verified prior absence from disappearance. `acknowledged` counts native DELETE success replies. `disappeared` counts observed live-to-absent consumers and live KV rows whose conditional purge lost to a competing deletion. These KV rows were present at the first read, so they never count as prior `absent` or as this caller's `deleted`. The ACL and membership subtotals preserve that distinction. Neither establishes which concurrent caller uniquely removed a consumer, so `consumers.deleted` and the total `deleted` are `null` when a consumer disappears without a winner token. A repeat after verified absence reports zero, not an invented deletion. `refused` counts slots whose cleanup or state remains uncertain. A partial failure raises `DeprovisionError` carrying these bounded observations. The Manager's static sweep preserves unknown uniqueness rather than adding acknowledged requests as physical removals; its slot totals remain separate.\n\nA host that resumes retained managed actors also implements\n`remoteAuthority.validateRetainedAgent`. The participant sends back the actor token and sentinel it\nalready holds, plus the `nextRegistrationProof` returned by the activation response. That proof is\nhost-issued after registration and binds the manager owner, actor, lifecycle, identity nkeys, current\nregistration revision, and serving epoch. The host checks it against the current open manager gate,\nvalidates the retained secrets against its current managed row, and returns only the non-secret\nauthority shape. The manager binds every result coordinate and the returned authority back to its\ninventory before use. Do not copy the provider's `issuer.json` or `callout.json` into the participant\nstore. Both contain private signing or exchange authority.\n\nThe same composition supplies `remoteAuthority.agentBearerExchangeUrl`, the pinned public auth-service\nbase used by retained children. Remote adoption launches `agent-bearer --exchange-url <base>`; it must\nnot select the local `--dir` arm, which depends on a host-only auth-service process record.\n\nA host that lets a remote participant spawn FRESH managed agents implements\n`remoteAuthority.enrollManagedAgent`. The participant generates the standing actor token, writes it\nat mode 0600, and passes only its SHA-256 digest with the requested actor, label, role,\ncapabilities, and channel lists, so the plaintext secret never leaves the participant machine. There\nis deliberately no `lifecycleUid` input: the host selects the UID, because only the host sees the\nretirement tombstones that make a UID permanently unusable, and a participant-chosen UID could aim a\nfresh grant at a dead incarnation. The host authors the ledger grant, pre-creates the lifecycle-keyed\ndurables, clamps the requested lists to what the spawning owner already holds, and returns the owner,\nactor, chosen `lifecycleUid`, the space sentinel credentials, the effective lists, and\n`agentBearerExchangeUrl`. The manager binds every returned coordinate, re-keys the secret family onto\nthe returned UID, and launches `agent-bearer --exchange-url <base>`. When the hook is absent a\nsignerless manager refuses the user-mode spawn rather than authoring a local grant the host knows\nnothing about.\n\nBoth managed-agent operations ride the one verified `POST /manager-service-authority` transport as\n`kind: \"manager-managed-agent-enrollment\"` and `kind: \"manager-managed-agent-prepare-retirement\"`.\nStock `cotal auth-service` answers both itself, because it owns the actor ledger and the space's\nprovisioning authority. An enrollment writes the managed grant at a fresh UID with the supervising\nactor as its parent, provisions that UID's durables, and returns the daemon's public exchange URL as\n`agentBearerExchangeUrl`; a daemon started without `--exchange-public-port` refuses enrollment. A\nretry with the same token digest answers the same UID while the supervising actor's current grant\ncovers it, and a fresh enrollment's refusal otherwise. While the agent's grant stands, an enrollment\nwith another digest is refused with `conflict` until that lifecycle's retirement is prepared. A\nprepare-retirement releases the target UID's broker footprint and then revokes its grant, so the\nmanager's terminal rail finds the grant gone. A platform that keeps these writers in its own storage\nintercepts both kinds instead. It terminates its own public route, authenticates the human there,\nand asks the auth service for the decision at\n`POST /manager-service-authority/verify-enrollment` (exported as `VERIFY_ENROLLMENT_PATH` from\n`@cotal-ai/auth`) with the `Bearer <cap>` from `auth-service.json` and only `{ owner, request }`. That\ndoor has the managed retirement door's guards, derives the caller's scope from the local ledger rather\nthan the body, checks the manager gate and registration proof in-process, and answers\n`{ authorized: true, owner, actor, instanceId, serveEpoch }`. `authorizeRemoteManagedAgentEnrollment`\nand `authorizeRemoteManagedAgentPrepareRetirement` are exported too, for a host that composes the\ndecision without the HTTP hop. Both require ledger scope `supervise`; `spawn` and `admin` do not\nimply it.\n\nA host that runs managed agents on its own hosted runtime adds two more kinds on the same transport.\n`kind: \"manager-managed-agent-runtime-create\"` asks the host to create the runtime for one agent it\nalready enrolled, and `kind: \"manager-managed-agent-runtime-status\"` reads that runtime's state. Both\ncarry the manager envelope plus `target: { owner, actor, lifecycleUid }`, the coordinate the\nenrollment returned. Both schemas are closed. An unknown top-level or target field, including\n`providerRef`, `handle`, or `name`, is refused as `bad-request`, because the host alone issues and\nholds provider references. There is no stop, adopt, or probe kind: stop goes through\nprepare-retirement. Stock dispatch refuses both kinds with `unimplemented`, and the verify-enrollment\ndoor decides them. `authorizeRemoteManagedAgentRuntimeCreate` and\n`authorizeRemoteManagedAgentRuntimeStatus` apply the enrollment door's checks: host space, a target\nowner equal to the authenticated owner, the manager actor's own ledger row with `supervise`, the open\ngate, the current serve epoch, and the registration proof. Each returns only\n`{ owner, instanceId, actor, target }`. The door touches no provider and writes nothing. The host\nmatches the decision to its own intent record and performs the create afterwards. The host answers\nwith `state` (`reserved`, `creating`, `bound`, `create-unknown`, `closing`, or `closed`), `readiness`\n(`ready`, `bound-not-ready`, or `none`), and an optional `retirementPhase`. A manager builds requests\nwith `remoteManagerClient.remoteManagedAgentRuntimeRequest` and binds the answer with\n`remoteManagedAgentRuntimeState`.\n\nAn enrollment result may also carry `runtimeIntent: { state: \"reserved\" }` when the host reserved a\nhosted runtime for the agent. It is display-only. Older hosts omit it, the manager binds both shapes\nto the same material, and nothing reads it as authority.\n\nNo stock door lets a platform control holder launch or retire an agent for a signed-in user. The\nmanaged-agent kinds above act only under the authenticated owner and refuse a caller that is not\nthat user, so a platform could only run a user's agent by holding the user's login or by enrolling\nthe agent under its own owner. Both are refused. The\n[delegated user launch intent](design/delegated-user-launch-intent.md)\ndesign and SPEC §13.16 define the smallest addition. The user admits one launch or one retirement\non the host's authenticated route. The holder consumes that intent once, from its current\nregistration, epoch and lifecycle. The host then enrolls the agent under the user's `u_` owner with\nthe user's own actor as its ledger parent, so the envelope walk, membership and channel lists match\nwhat the user's own manager would produce. Retirement keeps the prepare, provider closure and\nterminal barrier order, and the host finishes it when the holder is gone. A launch the host had to\nundo keeps its agent name held until the host process that ran it confirms it has stopped, and\nwhile the name is held the host also refuses it to the user's own manager. `@cotal-ai/auth` ships the\ntwo decisions, `authorizeDelegatedUserIntentAdmission` and `authorizeDelegatedUserIntentExecution`,\nfor a host that owns an intent store and those writers to compose on its own routes. Both read the\nholder's gate through the handle's `observeManagerGate`, present with `platformControl`, which reads\nover the context's own connection, so the host opens no second data-account connection. It is an\nobservation for the decision: the consuming CAS and the writers still apply their own checks. The\nconsuming CAS pins the incarnation of the host process that runs the flight as the executor, never\nthe auth plane's, because the two can restart independently. `platformControl.host` names that\nprocess's reverse-DNS endpoint, the closure digest of its §13.7 cluster and the contract artifacts\nregistration reads, and the auth plane self-authorizes that one name. Registration reads the closure\nmanifest `{ v: 1, root, members }` at `clusterDigest`, then the cluster document at the manifest's\n`root`, and verifies each against its digest. `artifacts` therefore carries both, and `clusterDigest`\nis the digest of the manifest. `members` stays empty: SPEC §13.7 lists every reachable artifact\nthere, but this implementation registers single-document clusters only and refuses a manifest that\nlists members. A manifest with any field beyond `v`, `root` and `members` is refused too, as the\ncontract store refuses it. `singleDocumentClosure(document)` returns that manifest and its closure\ndigest. The instance id is a lifecycle token, `[a-z0-9]{26,32}`. The minimal construction below has\none command over the void schema. A host copies it, replaces `document` with its real cluster, and\npasses `host` as `platformControl: { observeAssignment, host }`.\n\n```ts\nimport { mintLifecycleUid, singleDocumentClosure, VOID_SCHEMA_DIGEST } from \"@cotal-ai/core\";\n\nconst document = {\n urn: \"com.example.host\",\n revision: 1,\n attributes: [],\n events: [],\n commands: [{\n name: \"ping\", class: \"ephemeral\", targeted: false, capability: \"host.ping\",\n inputDigest: VOID_SCHEMA_DIGEST, outputDigest: VOID_SCHEMA_DIGEST,\n }],\n};\nconst { manifest, closureDigest } = singleDocumentClosure(document);\nconst host = { endpoint: \"com.example.host\", clusterDigest: closureDigest, artifacts: [document, manifest] };\nconst instanceId = mintLifecycleUid(); // first start only; later starts reuse the persisted id\n```\n\n`registerHostIncarnation(instanceId)` publishes the artifacts, registers that instance through the\nceremony the plane runs for itself, and returns `{ instanceId, processEpoch }` with the epoch that\nregistration committed. The host calls it at every start with its persisted instance id, before it\nadmits or recovers any flight, so a restart fences its predecessor. The first registration of an\ninstance commits epoch 0, which is open and serving like any later epoch, and each later start of\nthat instance commits the previous epoch plus one. A consumer compares epochs for equality and never\nreads 0 as absent or not ready. A start\nwhose confirming read of the gate finds that a later start of the same instance registered is\nrefused with `conflict`. The returned epoch is a committed coordinate and stays current only until\nthe next start registers, which can happen before the call returns. `observeHostGate(instanceId)`\nis a point-in-time read of an executor's gate, and answers null for an absent gate; a sweeper\ndecides on it. `awaitHostFence(instanceId, processEpoch)` resolves with the gate once it is no\nlonger open at that epoch, and with null once it is absent. It takes any non-negative safe integer\nepoch, 0 included, and refuses any other value with `bad-request`. The host arms it with its returned\nincarnation before it admits or recovers any flight, and stops serving when it resolves. It polls\nthe gate, because no runtime credential may watch the auth bucket. The\nhost's launch writer first activates the agent's lifecycle at the pinned UID through the handle's\n`activateManagedLifecycle`, before any ledger row or durable, and its compensation runs the same\ncall before the terminal barrier, so a launch whose agent never exchanged its bearer still reaches\nthe terminal barrier at that UID. The launched agent exchanges its bearer on the context's public\nface, so the host starts it with `publicFace`, and its retirement writer ends at\n`POST /managed-lifecycle/retire` with the handle's `cap`. Stock dispatch refuses both kinds as\n`unimplemented`. The holder's composition passes\n`remoteAuthority.executeDelegatedUserIntent`, which posts the execution request and binds the answer\nwith `parseRemoteDelegatedUserIntentExecutionResult`. It then starts the agent with\n`startAgent({ ..., delegatedIntent: { intentId, owner, parent } })` and retires it with\n`retireDelegatedAgent(name, intentId)`, which stops the agent and removes its local secret family\nonly after the host confirms `retired: true` for its exact target. A delegated agent's stop, exit or\nfailed launch keeps its name held until that retirement confirms, and a secret file the retirement\nfails to remove keeps it held too.\n\nRemote user-mode managers must also supply `remoteAuthority.authorizeAdmin`. The manager builds each\nrequest only from the caller tuple parsed from the broker-authenticated endpoint subject, then relays\nthat tuple over the current registered manager lifecycle. HTTPS does not separately authenticate the\nrelayed caller. The host authenticates the manager operator, binds the request to the current open\nmanager gate, registration proof, serving epoch, and identity nkeys, then reads the caller's unified\nauthoritative row fresh. It returns only the manager owner and `authorized: boolean`, with every request\ncoordinate echoed. Missing, revoked, narrowed, foreign-owner, and stale-lifecycle callers all return\n`false`; malformed coordinates or corrupt and unavailable authority state fail the operation. The\nparticipant never reads or mirrors the host ledger, and the remote branch has no local fallback. The\nsame callback gates all `manager.admin` handlers, any-mode cross-owner control, and `ps` or `inspect`\ncross-owner visibility. Launch keeps its owner-equality policy.\n\nThe remote authority's instance executor remains the scoped maintenance credential for clean service\nderegistration and exact instance registration operations. It carries no records-stream consumer\nlifecycle authority. The manager's boot `goalidx` sweep uses the authenticated host operation, which\nreturns parsed `goalidx.manager.<owner>.>` entries for that owner only. The host keeps the sealed\nconsumer connection and its create/delete rights. The five-minute executor already renews through\n`remoteAuthority.renewExecutor`. The signerless supervisor, serve, goal-writer, session-ledger and\nper-run driver credentials do not yet have a complete remote renewal and adoption path. The\n[hosted runtime contract](design/hosted-runtime-contracts.md) records the bounded additions and\ntheir ownership; it is not a shipped pooled service.\n\n**Signer isolation needs an OS sandbox.** The default pty runtime\nruns agent children under the *same* OS uid and the *same* `workspaceRoot`, so mode-0600 on\nthe trust records does not stop a hostile same-uid agent from reading their absolute paths. The reference\n[deploy](deploy.md) tree does not solve this: it mounts the signer into the agent's own container, so\nits phase-1 boundary isolates agents from each other, not the signer from the agent. A hosted\ncomposition must run the manager/minter that holds the signer in a different uid, container, or mount\nnamespace from the agent children, which mount no signer at all; that split is future\nhosted-composition work, so until it (or a remote/injected minter) exists, do not run untrusted\nagents under this manager.\n\n### Delegated seats outside the manager's filesystem\n\nThe [portable lifecycle bootstrap](design/portable-lifecycle-bootstrap.md)\ndesign and SPEC §13.17 define how a managed agent that `enrollManagedAgent` already enrolled starts\nin a child that cannot see the manager's filesystem. The ordinary `spawn` path writes the token and\nsentinel under the manager's workspace root and hands the runtime a launch whose bearer command and\nmaterial file are paths on that filesystem, so such a child needs this path instead.\n\nThe delegation boundary is one optional runtime method. A runtime that implements\n`Runtime.spawnDelegated(launch, handoff)` receives two values and no paths: a `DelegatedSeatLaunch`\n(connector name, persona text, `managerInstanceId`, model and the other launch choices) and a `ManagedLifecycleHandoff`\n(space, owner, actor, the host-chosen `lifecycleUid`, broker and IdP pins, the pinned exchange base,\nthe sentinel, the channel lists, and the raw actor token). The manager enrolls once, as it does\ntoday, and builds the handoff from what it holds. It never sends the token to the host, never copies\na file from its workspace or secret store, and never builds a local launch for that seat. No signer,\nissuer or callout record, loopback capability, provisioner or manager credential, control token, or\nmanager path crosses. A spawn choice that only the manager's host can honour is refused before\nenrollment: `--resume`, a manifest agent's `continuity: exact`, `--cwd`, and any shared MCP server,\nwhether from `--share-tools` or the config default (`--share-tools none` passes).\n\nA delegated manager also refuses a caller-supplied persona `config` override in `resolve-agent`,\n`spawn` and direct `Manager.startAgent` calls. The shared persona resolver refuses before checking\nor reading that path, with `failed-precondition` on the wire and one fixed execution-mode message.\nPass a named catalog persona instead. This does not change locally executing managers. A resolved\nmanifest can still use its own validated, host-materialized persona resource. The wire schemas\naccept no internal `resolved` field that could bypass the config refusal.\n\nThe runtime creates one provider resource under `managedRuntimeKey(target)`, writes the handoff into\nit as one 0600 file and the persona beside it, and runs the stock bootstrap there:\n`cotal spawn --config <persona-file> --space <space> --name <actor> --expect-owner <owner> --expect-lifecycle-uid <uid>`\nwith `COTAL_MANAGED_HANDOFF_FILE` naming the file and `COTAL_MANAGER_INSTANCE` naming the launching\nmanager. `delegatedSeatCommand` builds that argv and `env`.\n`cotal spawn` reads the file into memory, deletes it and drops the variable before it parses flags,\nprints help or loads extensions, so every outcome, a refusal of its own flags included, leaves no\nfile. It refuses before any broker connection or exchange request when `COTAL_MANAGER_INSTANCE` is absent (`COTAL_MANAGED_HANDOFF_FILE requires COTAL_MANAGER_INSTANCE`; `DelegatedSeatLaunch.managerInstanceId` is required and a newer CLI child under an older manager or runtime refuses every delegated launch, so managers and the CLI must be upgraded together) or malformed, or when the\nspace, owner, actor, or lifecycle UID differ from the expected values, and then runs the\nenrollment-redeem consumer: it registers the mesh in its own home, writes the token to its own 0600\nfile, and exchanges it through `agent-bearer --exchange-url` unchanged. It never enrolls, redeems, or\nmints a token or UID.\n\nReadiness is still mesh presence. A create whose answer is lost leaves the handle running, so the\nlaunch settles uncertain and stays held; the manager never retries it. A provider read that finds no\nresource under the key is not an exit, because the create may still land. Every close by\n`managedRuntimeKey` is fenced: it completes only once the create was answered or the provider refuses\nany later create under the key. A provider that names its own resources may run the create as a\ndurable operation keyed by `managedRuntimeKey` and close through the identifier its authenticated\ncreate response returned, kept where the host can read it without the manager. Only that response\nbinds an identifier to the key; one derived from the key or found by name or listing is never closed\nor adopted, and while the response is unknown the launch stays held. Every stop, the reap of a child\nwhose parent exited and `Manager.stop({ withAgents: true })` included, runs `prepareAgentRetirement`\nfor the UID-exact target, then `stop()` on the handle `spawnDelegated` returned, then the terminal\nbarrier. `preparePreservation` refuses a cut that holds a delegated seat, and a `Manager.stop()` after\na refused cut retires the seat through the same steps. After the manager is gone\nthe host runs the same steps, makes the same fenced close by `managedRuntimeKey`, and finishes at\n`MANAGED_RETIRE_PATH`. Supply `spawnDelegated` only from a runtime whose host can make that fenced\nclose without the manager. The enrollment redeem\n(`COTAL_ENROLLMENT_FILE`) stays for lifecycles whose token the host generated itself; a host cannot\nmint one for a manager-enrolled lifecycle because it holds only the digest.\n\n### Delegated recovery contracts\n\nCore exports `RemoteDelegatedRecoveryRequest`, `RemoteDelegatedRecoveryResult`,\n`RemoteDelegatedRecoveryLaunchRequest`, their closed parsers, and\n`parseDelegatedRecoveryDescriptor`. `Runtime.rebindDelegated` describes an optional same-child\nrebind. These are contracts for SPEC §13.18, not an enabled recovery path. The current Manager\ndoes not call the new method or reconstruct delegated rows. Its public `adoptRuntimeHandle`\nreturns a native handle without inserting a managed row.\n\nA supporting host retains the descriptor in the original user-intent consuming CAS, binds each\nclaim to the original instance and current registration, and supplies complete fenced scans.\nThe manager needs its original persistent secret store and a runtime that can verify the same\nchild execution after process loss. It must retain held aliases before reconciling accepted goals.\nMissing storage or unverified child identity keeps recovery held; neither permits another launch.\nThe request parsers validate data, not fresh host authority or durable transactions. Existing\nhosts continue to refuse the opt-in launch extension rather than silently ignore it.\n\n## Provisioning a space (one-space reference shape)\n\n```ts\nimport { createSpaceAuth, setupSpaceStreams, ensureDefaultDeliveryClass, mintCreds, newIdentity } from \"@cotal-ai/core\";\nconst auth = await createSpaceAuth(space); // trust bundle (in-memory seeds)\nconst provisionerCreds = await mintCreds(auth, newIdentity(), \"provisioner\");\nawait setupSpaceStreams({ servers: brokerUrl, space, creds: provisionerCreds });\n// SPEC section 4: write the default delivery class at space creation so it is wire-discoverable,\n// never inferred from the resolution fallback. A daemon-backed space is \"durable\".\nawait ensureDefaultDeliveryClass({ servers: brokerUrl, space, creds: provisionerCreds, deliveryClass: \"durable\" });\nconst deliveryCreds = await mintCreds(auth, newIdentity(), \"delivery\");\n// put deliveryCreds into your SecretStore under deliveryCredsKey(space, { injected: true })\n// (@cotal-ai/workspace) before booting delivery — the key is per-space, not the bare kind.\n```\n\nRendering the broker config for a user-auth space is `serverConfig(broker, spaces, { storeDir,\nmaxFileStore?, extraAccounts })`, where `extraAccounts` must include the callout account from\n`createCalloutAuth` so the auth-service has a broker account to answer on. That account never shares\nthe data account. `maxFileStore` is an optional positive integer byte cap; any other value throws.\n\nBroker trust and space accounts are separate authorities: `createBrokerAuth` mints the one\noperator + system account a broker trusts, `createSpaceAccountAuth(broker, space)` signs each\ntenant's data account under it, and `serverConfig(broker, spaces, opts)` renders them all into one\nconfig. A host composition can therefore provision several spaces on one broker today. `cotal up`\nrenders that config from every tenant the root's auth directory holds, so booting one space keeps\nthe broker trusting its siblings, and it refuses to render at all while any account record is\nunreadable. The rest of the CLI lifecycle is still broker-wide: `down`, `clean` and `backup` refuse\non a multi-space root rather than scoping to one tenant, and the per-space lifecycle is the\nremaining multi-space operator layer. See\n[Known gaps](#hosted-composition-gaps).\n\n## Issued-authority stores from before 0.111.0\n\nA space whose `KV_cotal_issued_<space>` and `KV_cotal_accepted_<space>` were created before\n0.111.0 is refused by every issuer and resolver that binds them. `cotal up\n--recreate-issued-stores` fixes the spaces `cotal up` starts. For a space your own composition\nprovisions, stop its issuers and resolvers (auth service, callout replicas, managers) and run the\nsame step yourself:\n\n```ts\nimport { connect } from \"@nats-io/transport-node\";\nimport { mintCreds, newIdentity, removeIssuedStoresBeforeRetention, setupSpaceStreams, standaloneConnectOpts } from \"@cotal-ai/core\";\nconst identity = newIdentity();\nconst inboxPrefix = `_INBOX_${identity.id}`; // the one inbox the credential may receive on\nconst creds = await mintCreds(auth, identity, \"issued-store-recreate\"); // one-shot, 30 minutes\nconst nc = await connect({ servers: brokerUrl, ...standaloneConnectOpts({ creds, tls: false }), inboxPrefix });\ntry {\n // backupDir must not exist yet; it is created 0700 with a `nats stream backup` layout per stream\n await removeIssuedStoresBeforeRetention(nc, { space, backupDir, inboxPrefix });\n} finally { await nc.drain(); }\nawait setupSpaceStreams({ servers: brokerUrl, space, creds: provisionerCreds }); // creates both again\n```\n\nThe credential can read, snapshot and delete those two streams and nothing else. The step backs\nup every store that predates bounded retention, checks each backup against its stream's message\ncount and last sequence, and deletes nothing unless every check passes. It throws\n`IssuedStoreRecreateRefusal` before writing anything when neither store predates bounded\nretention. The order, the refusals and what a rollback can do are in\n[Upgrading](UPGRADING.md#issued-authority-stores-after-01110).\n\n## Hazardous provisioning primitives\n\n`mintCreds`, the full `Profile`/`CredentialKind` matrix, `createSpaceAuth`, and `stripSpaceAuth` are\nlow-level operator primitives. Handle them as account-authority material:\n\n- A holder of a `SpaceAuth` (or a `stripSpaceAuth` bundle, which **keeps** the data signing seed) is\n a fully-trusted tenant-account authority: it can mint `admin`, `provisioner`, and destructive\n profiles, not merely `supervisor`, and mint a DM-reading identity. `createSpaceAuth`'s full result\n holds operator, system, and account seeds in memory.\n- Choose `profile` and `MintOpts` from **server-side constants**, never from tenant input. `MintOpts`\n can widen the bounded TTL defaults; cap it at your boundary. `CREDENTIAL_LIFETIMES` is a policy\n record, not an authorization boundary.\n- Never log signer material or export it into env. Do not co-locate signer access with an untrusted\n connector/runtime process at the same OS uid (file permissions do not contain a same-uid reader;\n see the manager's isolation note). Segregate per tenant; rotate on compromise\n (`rotateDataAccountSigningKey`).\n\n## Hosted composition gaps\n\nThree composition limits remain. A host must supply the missing isolation or integration,\nor leave the affected capability unavailable.\n\nMembership and live eviction already read their credentials through `SecretStore`.\n`startMembership` reads the data-account writer and system-account observer there; eviction\nreads the observer and evictor pair on each operation. Both use per-space keys and check\nthat the observer names the daemon's account. The feed derives that account from the\ndaemon's credential, without `membership.json`. The host still owns provisioning and\nrotation. An absent observer leaves the feed traffic-only; missing eviction authority\nrefuses eviction. The membership reader can adopt a host-renewed observer with the same\nissuer and scope at 75% of its lifetime.\n\n1. **Supervisor signer isolation.** `ManagerOptions.secretStore` now injects the one `SecretStore` the\n manager reads/writes every secret through, including the composed `SpaceAuth`\n signer (the split trust records), its daemon-cred renewal, and its per-agent kinds. What remains is process\n isolation: the manager still decrypts the signer in-process at its uid, so untrusted agent children\n must run under a different uid/container/mount namespace or behind a future remote signer.\n2. **Per-space lifecycle on a shared broker.** The trust layer is multi-space\n (`createBrokerAuth` + `createSpaceAccountAuth` + N-space `serverConfig`, persisted as\n `broker.json` + `account.<key>.json`) and `cotal up` renders the whole tenant list. The CLI\n still lacks tenant-account provisioning and per-space teardown/backup/restore on that\n broker. Its broker-wide lifecycle verbs refuse on a multi-space root, naming the tenants.\n The existing `cotal space add` registers a connection, and `space delete` removes a\n space's streams; neither supplies that tenant-account lifecycle.\n3. **A non-Better-Auth production IdP.** The exchange core (`createIdpBridge`) is EdDSA-generic, but\n the stock provider and login client are Better-Auth-endpoint-shaped, `cotalAuthProvider`\n self-registers on import (colliding with a host-owned provider under `resolveAuthProvider`), and\n the login flow speaks Better Auth's device-code endpoints. A different IdP is a host-built auth\n composition on the low-level primitives, not a configuration change (see\n [the IdP callout contract](identity-and-auth.md#the-idp-callout-contract)).\n\n## Hosted durability\n\nSpace-durable **coordination** state (chat/DM/task history, live presence, membership runtime, the\ndurable ACL registry, leases) lives in **JetStream**, written by the delivery daemon and the\nendpoints. It is broker-resident and needs no host-side durable path.\n\nWhat is **not** in JetStream, and is hosting-critical, is trust and authorization state a host must\nplace and keep:\n\n| state | class | where today | hosted injection |\n|---|---|---|---|\n| full `SpaceAuth` trust chain (`auth/broker.json` + `auth/account.<key>.json`, composed; a stripped signer bundle may instead be mounted at the legacy `auth/auth.json` key) | signing authority | `SecretStore` | `SecretStore` (manager + renewal) |\n| auth kinds: callout account/creds/xkey, issuer private keys, owner-derivation secret, data-signer projection | signing/identity authority | four `SecretStore` kinds | `SecretStore` (auth-service) |\n| auth plane instance identity (instance id + serve nkey seed) | restart identity | root `.cotal/space.<hex>/auth-instance.json` | `SecretStore` (`startAuthService`) |\n| `delivery.creds` | standing scoped cred | `SecretStore` or `--creds` | `SecretStore` (delivery) |\n| actor ledger, IdP pin | authorization + trust config | ambient `userAuthStateDir(findCotalRoot(), space)` | none (root-relative; not `store`/`COTAL_HOME`) |\n| `membership-rw.creds` | standing scoped cred | `SecretStore` | `SecretStore` (delivery + manager renewal) |\n| membership-observer / connection-evictor creds | scoped $SYS creds | per-space `SecretStore` keys | injected `SecretStore`; account identity is checked against the daemon credential, not `membership.json` |\n| manager agent creds, actor tokens, sentinel creds | lifecycle authority | `SecretStore` | `SecretStore` (manager `secretStore`) |\n| `~/.cotal/meshes/space.<key>.json` record (holds IdP trust pins/root pointers) | non-secret, integrity-critical | machine home | process-global `COTAL_HOME` only |\n| auth-health, renewal records | non-secret diagnostics | workspace filesystem | `workspaceRoot` |\n\nThe `SpaceAuth` trust chain and the auth-service store kinds are **separate** identities/projections,\nnever parts of one document. `auth-service.json` (the live exchange capability) is ephemeral runtime\nstate, not durable, but is sensitive while the daemon runs. `@cotal-ai/workspace` is machine-local\noperator tooling by design; personas, PID files, and the `current-mesh` pointer are truly local and\nmust **not** sit on a hosted durable path. Everything classed above as an authority is what a hosted\ncomposition must provision and persist: signer-bearing server secrets now have `SecretStore` seams;\nthe remaining non-injectable rows are the explicit ambient `workspaceRoot`/cwd paths above.\n\n## See also\n\n- [Substrate stability](stability.md): what v0.3 and the 0.x packages guarantee, and the projected v0.4 break.\n- [Identity and auth](identity-and-auth.md): the profile matrix, the signer, and the IdP callout contract.\n- [Delivery daemon](delivery-daemon.md): the Plane-3 durable backstop.\n- [Deploy](deploy.md): the reference container against an external broker.\n\n## Hosted run revocation\n\nThe authenticated manager-service authority door accepts `manager-run-revoke` with the registered\nmanager envelope and `revoke: { runId, reason }`. The issuing host reads the admission's recorded\nowner and requires the verified requester to be that owner or to hold `admin` in its fresh actor\nledger row. It verifies the current manager registration proof, space, account and epoch. It accepts\nno owner or attribution from the body.\n\n`AuthAuthorityPlane.revokeManagerRun` implements the operation. `AuthProvider.requestRemoteRunRevoke`\ntransports it, and `remoteManagerClient.remoteRunHosting` supplies `RunHostingContext.revokeRun` for a signerless\nmanager. The callback returns the stored `RunRevocation`, including on repeats. A host composing\nits own remote authority must supply that callback to revoke. No signer reaches the participant.\nCLI and MCP revoke verbs are a follow-up described in the [run-start design](design/user-auth-run-start.md).\n\n### Private tool-result prerequisites (not serving)\n\n`@cotal-ai/auth` exports `createToolResultRevocationCustody`,\n`recordToolResultRevocation`, `snapshotToolResultRevocations` and one-shot\n`consumeToolResultSnapshot`. These are host-only prerequisites, not material issuance,\nservice registration or a browser/private-result path. `requireToolResultClockPrerequisite`\nalways refuses `unavailable`: no native runtime clock-domain/generation/suspension proof\nexists, and no numeric delta is invented.\n\nCustody exclusively creates a **fresh** auth store after a private fsynced intent/generation.\nExisting stores or journals are never adopted. Only a standalone broker and owner-private local ext4 journal parent are supported. Only the creating process may use its sealed,\nnon-reconnecting reader/writer custody. Unknown writes, missing/changed journals, stream\nidentity/configuration drift or connection loss invalidate it. Crash/rebind recovery stays\nunavailable. Routine broker restart, upgrade, network loss or process restart therefore leaves\ngate 1 permanently unavailable for that space. Recognize this as `revocation custody lost; no reopen from current INFO`.\nNo retirement/reprovision recovery protocol exists in this increment. Gate 2 cannot assume\ncustody survives broker maintenance. The trusted composition supplies current authenticated consent/target authorizers\nand exclusively holds account/provisioning keys. Independently running privileged provisioners,\nuncontrolled legacy writers and existing roots have no qualified custody and are unsupported.\nThis is not protection from a malicious host administrator or copied signing keys.\nThe separate internal custody profile uses two non-expiring, non-reconnecting credentials,\nwithout planeCandidate or a renewal timer. With the two sealed scanners this is four standing\nconnections across three profiles. The CREATE provisioner still expires and closes after CREATE.\nA leaked custody JWT plus user seed no longer has a 900-second expiry bound. Stopping the\nservice closes its own sockets, not copied credentials. Signing-key removal invalidates copied\ncredentials as well. This remains inside the trusted-process/account-signer residual.\n\nRevocation creates only `revocation.<targetDigest>.<consentId>` with native expected-last-subject\nsequence zero, no operation/TTL headers and independently fsynced acknowledgement receipts.\nConsent bytes must match the recorded target and expiry. Persistence uncertainty reports effect\noutcome `unknown`. Acknowledged writes report `executed` even if receipt or later custody checks\nfail. Refusals before publication report `not-executed`. No automatic repeat follows uncertainty.\nMarkers persist indefinitely in this\nslice. A separate bounded-retention successor must prove consent expiry plus\n`EP_AUTH_MARKER_TTL_MS` and snapshot safety before a pruner/TTL may exist.\n\nA snapshot fixes T0 before IO and a leader W once, walks only through W, bounds count/bytes/time,\nand compares exact native sequence/subject/payload evidence to custody receipts. The committed-W\nartifact is a process-private invocation seal binding that evidence, account, generation and\nnative created/config identity. It cannot be parsed, copied, reused or used after custody loss.\nNo current INFO equality or operator safe flag establishes historical integrity. Journals are\nexclusive 0600 files with file and directory fsync, checked before/after IO, not adopted on restart.\nClustered brokers and leader failover are unsupported. Any connection loss refuses; current INFO cannot restore custody.\n\nA short-lived create-only provisioner holds API discovery and exact auth-stream CREATE, then closes.\nSeparate package-internal grants split revocation-only publish from INFO/MSG.GET reader authority.\nRetained issuance writers **already can enumerate** auth metadata. Raw ACLs cannot enforce CAS,\nDEL/TTL/schema/target conventions. Every raw MSG.GET profile carries SPEC13.9's caller-selected\nreply **foreign-subject response-injection** residual, even with only its own inbox subscription.\nRoutine PR CI runs `smoke:tool-result-prerequisites`: bounded fixtures, broker-observed\nnon-expiring exact grants, a no-renewal timer probe, census and actual KICK/key-removal\nrefusals. It does not wait for credential expiry and is not serving acceptance.\n`pnpm smoke:tool-result-custody-lifetime` additionally waits `AUTHORITY_CLIENT_TTL_SEC + 15`\nseconds and checks unchanged identities plus record/snapshot success. Run it explicitly or\nthrough the manual/weekly Custody lifetime workflow. Historical lifetime receipts remain\nsource-pinned evidence, not a grade for a composed successor.\n\n\n## Native service custody guards\n\nOrdinary lifecycle executors refuse a UID reservation carrying `kind: \"native-service-uid\"`.\nThe reservation has closed `native`, `assignment` and `creation` objects. It is not an ordinary\n`{ owner, actor, mintedBy }` audit, and a reader must not project it into one. Its assignment\nbinds the full account, space, owner, endpoint, instance and serve-duty tuple. The actor is derived\nfrom that tuple, and the creation operation and request digest remain fixed.\n\nThese guards run before ordinary root reuse, activation, gate and head changes, mint finalization,\nand native retirement. Ordinary connect and currency reads also refuse service custody, including\nrows whose head or credential mirror is missing. Existing ordinary reservation bytes are unchanged.\nClosed head, gate and credential parsers continue to reject service markers. Without\n`serviceEndpoints`, no product path writes a service reservation or mints a marked root. The service\naccess-view contract and the sealed native access/callout composition are shipped; only a context\nopened with `serviceEndpoints` composes them, with the service host's approval and registration\ndescribed below. Lifecycle retirement and restore remain unwired.\n\nThe package-internal service prerequisite reader is separate from ordinary connect and lifecycle\ncurrency readers. It leader-reads immutable UID custody, the exact active service head, native\n`gate.<uid>` open at generation1, and the exact active root credential. All three custody mirrors\nmust match the full reservation digest. Service head `managerInstance` equals immutable assignment\n`instanceId`, and native `processEpoch` is fixed at1. These are not ordinary enrollment coordinates\nor the separate endpoint gate/witness registration epochs. Creating/cancelling heads and their\nRootPlan recovery obligations remain outside this read-only active path. Missing or malformed\nnative gate evidence cannot be replaced by an endpoint gate. This is no writer, bootstrap, root\nmint/abort, rotation, cancellation or terminal-retirement authority, and not an atomic multi-key\nsnapshot. Positive fixtures raw-seed synthetic marked records, not production service admission.\nThe account is trusted host configuration. Sealed readers do not attest the broker account or\ndetect a cross-account pair of legitimately constructed handles. The authority plane constructs the\nservice callout's registry, reader and contract reads from its own data account.\n\nA package-internal custody writer is not exported; in the product only the service endpoint host's\ndecide and revoke reach it, and the proposals they act on come only from the owner-proved public\nauthority route of a context opened with `serviceEndpoints`. Bootstrap\nwrites the reservation, the pending-root endpoint gate, a creating head, a frozen activation native\ngate opened at generation1, a RootPlan fixed once by head CAS, the planned active root, an\nidentical-bytes native gate touch and the active head stamp. It rechecks the endpoint gate at open\nand before the plan, root and stamp writes. Cancellation denies the endpoint gate first, then\nwrites the cancelling head and freezes the native gate under the cancel operation. An unstamped\nplanned root is fenced by a create of revoked bytes or by CAS of the exact active row. A stamped\nroot is retained, and every cancellation result is nonterminal. An absent reservation leaves\nendpoint deny residue and reports unconfirmed; a foreign or deleted reservation refuses without a\nwrite. Each write is a per-key create or revision CAS under a sealed host whose genuine plane-claim\nhold is re-read before and after the write, plus a fatal latch. That is local readiness control,\nnot broker writer exclusion, so a paused writer can still land one late conditional write. Each\nrequest is bounded by the remaining original deadline. In bootstrap, once the plan step has fixed\nor read the RootPlan, requests are also bounded by its expiry. Cancellation keeps only its own\ndeadline, so an accepted cancellation can still proceed after the root expires. At its bound the\nwriter stops waiting for a request but does not cancel it at the broker. The writer issues every\nendpoint-gate request itself, so no endpoint-gate request starts after an invocation returns, and\nit re-reads the endpoint gate before every plan, root and stamp write attempt. Bootstrap's final\nactive-root proof is several read-only reads behind one bounded wait. If that wait ends at its\nbound, the remaining reads can still run after the invocation returns; none of them writes.\nBootstrap holds instead of reporting an active root whose expiry its final synchronous check\nobserves, with no await between that check and the return. The result can still be stale by the\ntime the caller acts on it. The caller supplies that deadline and the\nreservation; nothing here authenticates a host, approves serving, retires terminally, releases an\nalias or rotates a root.\n\nA second package-internal module builds service host operations on that writer: register\nadmission, decide (approve or refuse), revoke, a create-only name binding, and the operation and\nproposal reads. It shares the\nwriter's sealed host, plane-claim hold check and fatal latch, and each invocation opens its own\ncustody host over a per-invocation effect registry. That host writes only the invocation's scope,\nthe exact keys discovery located before the effect registry opened, and the effect registry is\nhanded the same key set so a broker grant can match it. A step that needs a key outside the scope\nholds as `scope-mismatch` before anything is issued; replaying the same request discovers what is\nstored and scopes it. Each effect registry rides its own connection, whose credential may publish\nonly on that key set's subjects (subject confinement, not operation confinement; the engine itself\nonly creates and CASes those keys), never renews or reconnects, and expires at the invocation's original deadline\nrounded up to the whole second. With agreeing clocks and timely scheduling the broker's\nwhole-second timer closes it within about 1999 ms after that deadline; that is granularity, not a\nguaranteed close time, and no close proves an earlier write cannot still settle. Losing the\nconnection fences the invocation. Discovery's credential has no write at all. The module's records and their write order are in SPEC §13.1. Results name their operation once a binding exists or may exist: `pending`, `held` and\n`refused` all carry `operationId`. A result can carry `debt`, the capacity releases its operation\nstill owed as far as that invocation observed. A result without `debt` does not mean nothing is\nowed; the operation read is the authoritative view of the debt. A `held` result by itself implies\nneither a binding nor an authorized granter: a tripped engine, or a granter without a current\ninteractive row, gets one `held` answer for a register, decide or revoke before any read of the\nrequest's keys. `denied` means the invocation wrote nothing, and either the request can never bind\nor the invocation's own read found no binding. That read is point-in-time; another invocation of the\nsame request already in flight can still bind it later. A revoke result reports `denyNew` when it\nhas evidence: an endpoint-gate read, which gives `unknown` when the read failed or found another\nassignment's gate row, or an assignment that is already fenced, which gives `landed`. The early `held` answers of a tripped engine and of a\ngranter without a current interactive row carry no `denyNew`, and a result without `denyNew` says\nnothing about deny-new. Completed results\nsay whether this invocation applied them or returned a stored record. A stored approval returns\nunchanged, and its `approvedGateRevision` is null unless its own gate CAS was observed. The index\ndoes not export this module; the typed request, result and view parsers in the service host contract\nare public.\n\n`openAuthAuthorityPlane` and `startAuthService` take `serviceEndpoints: { startup: { kind: \"normal\" } }`\nto host these operations; it is off by default. `cotal up --user-auth --service-endpoints` sets it\non the stock auth service, and a lane of `auth-service --spaces` sets it when its manifest entry has\n`\"serviceEndpoints\": true`. With it, the plane and the\nhosted handle gain `serviceEndpointHost(request)`, which answers `decide`, `revoke`, `name-bind`, the\nfour caller-policy operations and the instance, proposal, operation and name reads in process.\n`instance-read` returns the current `ServiceInstanceView` for the proved owner's selector, including\nits approval digest and registration state. `instance-list` walks the native assignment subjects with\na cursor and returns only that owner's instances. Missing and foreign selectors both read absent.\nA hosted context rejects it as\n`unavailable` while it is not ready. The host authenticates no caller: the embedder must\nauthenticate the operator or owner granter it passes. The stock service does that on\n`POST /service-endpoint-host`: the body is `{ idpToken, request }` with no granter, and the route\nverifies the token and derives the granter. A decision, an `owner-request` revoke, the four\ncaller-policy operations and the reads run as the proved owner on either face; `name-bind`, any\nother revoke and the admission operations are the operator's, served on the loopback face under the\nexchange capability only, with the proved subject as the audit id (the admission operations have no\nengine handler yet and answer `unsupported`). Mint requestIds unpredictably: they share one\nspace-wide namespace. `cotal service-endpoint` drives that route as the signed-in user\n([docs/cli.md](cli.md#service-endpoint)). Register admission is reachable only through the public\nroute below. `name-bind` needs an operator granter and `expectedRevision: 0`. It creates\nthe endpoint's name binding once, with your `claimReference`, and only the identical request recovers\nit; nothing updates, transfers or releases a name. The host checks no domain control, so verify the\nclaim, or delegate a namespace you control, before you bind. The host runs over the plane's claim hold, data account and\nactor ledger directory. A restore or missing startup refuses the plane open, which unwinds and\nreleases the claim. If that unwind cannot close an effect connection, it stops there: the claim\nstays held, the plane's clients, scanners and cleanup timer stay live, and there is no handle to\nretry. Only the process exiting ends them, after which the existing crash reclaim applies. Its discovery connection is an ordinary renewing read-only client: a broker loss\nfails its reads until the stock client reconnects, and those calls answer `unavailable` with nothing\nwritten. A renewal failure closes it permanently, and the host stays unavailable until the plane is\nopened again. Both plane fatal paths trip the host, and either one trips it even while the\nplane closes, without making the plane fatal. Plane close refuses new host calls from the\nmoment it is called, waits for every call that already entered, from entry through discovery and\neffect open, closes discovery and then releases the claim. An effect connection that failed to\nclose stays owned past its call: close closes it again first, and rejects with the claim still held\nwhile it stays open, so you can retry close. Until a retry succeeds or the process exits, discovery,\nthe administrative rail, both scanners and the remaining clients stay live, so no successor can\ntake over the claim.\n\nOn a multi-space host the setting is per space. The manifest entry's `serviceEndpoints` is the only\nplace it is set, and `--service-endpoints` refuses beside `--spaces`\n([server daemons](cli.md#server-daemons)). Check a manifest you write with\n`parseAuthHostManifest(text)` from `@cotal-ai/auth` before you rename it into place: it is the parser\nthe host applies. A callout replica cannot issue a service-endpoint connection, so it refuses a space\nwhose admission is open: a single-space replica refuses to start, and a callout host names the space\nand retries it every 5 seconds while it answers for the others. The first open with service endpoints\nopens the admission and nothing closes it, so keep every space that has ever run with service\nendpoints off replica manifests, also after its entry drops the field. `admitsServiceEndpoints({ space,\nserver, secrets })` from `@cotal-ai/auth` tells you which: it resolves `true` for the spaces a\ncallout lane refuses for their admission, with the read the lane makes on the lane's own store grant,\nand throws when the space's service keys are missing or its stores cannot be read. Nothing turns a\n`true` answer back to `false`. To turn service endpoints on for a space a replica lists, remove it from\nevery replica manifest and wait for each `<manifest>.applied` first: a lane checks at open, so a lane\nalready open keeps answering and denies the service connects the broker hands it.\n\nWith `serviceEndpoints`, both faces also serve `/service-endpoint-authority`, and without it that\nroute answers 404. `GET` returns the receiver's account and space, the exact `iss` its service\naccess bearers carry, and the public Ed25519 keys `GET /jwks` publishes. `POST` takes a `{request, proof}`\nenvelope of at most 2 MiB. An IdP proof derives the owner, who needs a current interactive cli or web\nrow; register needs one, and so may activate. A service's renewal proof authorizes activate, renew\nand status, and its access bearer authorizes ready and status; neither is owner authority. A typical\nsequence: the service registers and gets `approval-required`; you bind its name with an operator\n`name-bind`; the owner approves with `decide`; the service replays the same register and gets\n`registered` with its witness and snapshot; it activates and gets a `credential` with an access bearer\nof at most 60 s and a renewal proof of at most 24 h, neither outliving the native root or approval;\nit connects to the broker with the bearer through the composed native service callout, binds its\nresponder, calls `ready`, and renews before the bearer expires. The auth provider's\n`serviceEndpointInfo` and `serviceEndpointAuthority` hooks are the client, and accept a service proof\nas well as the signed-in login.\n\nThe `credential` answer carries no store access and no serve grant, so a service turns it into the\nprocess-local grant `serveEndpoint` consumes with `authorizeGuestServeGrant({ accountPublicKey,\nresult, registration, authenticity })`: the parsed result, the service's own embedded closure, and\nthe pinned issuer's `iss` and published keys. The issuer and keys come from the registered\nspace's authority URL the service already pins, tenant path included: the auth provider's\n`serviceEndpointInfo` answer carries them, and a service passes `serveAuthenticityOf(info)` as\n`authenticity`; an authority that does not publish them yet makes that call refuse, so the\nservice does not serve on a bearer it cannot verify.\nIt verifies the access bearer's EdDSA signature under the published key its `kid` names and the\nsame closed claims the host's token validator checks, so a bearer the issuer did not sign for\nthis witness brands nothing; the closure is bound to the service's own embedded contract, not to\nthe bearer. It refuses\nanother account, a bearer from another issuer, space, subject or key, one that names another\nwitness or no serve duty, a closure set or artifact that is not the embedded one, and a closure\nthat does not read at its digest. `authorizeTrustedServeSnapshot` stays the host's.\n\nFor a serving connection, the auth provider's `serviceEndpointRenewal({ store, dir, witness })` hook\nreturns that loop as a bearer function. It is an `AuthProvider` method, not a package export. Pass\nits `bearer` as `EndpointOptions.bearer` and its `sentinelCreds` with it. The\nfirst pull activates on the signed-in login and every later pull renews on the stored renewal proof.\nIf that proof has expired, as after a machine was off for more than a day, the next pull replays the\nsame activate request on the signed-in login, which mints again while the root and the approval stand.\nIt keeps one activate and one renew requestId per witness, written to `store` before the first send,\nand replays them, with fresh material each time, for as long as the root and the approval allow.\nConcurrent pulls share one request. `credential()` is that same pull answering the validated\n`credential` result without its renewal proof, which never leaves the source, as a copy per caller;\nit is what `authorizeGuestServeGrant` takes. `bearer()` and `credential()` share one pull, so the\ntwo in flight together send one request under the same persisted ids, and an ended or closed\nsource refuses both the same way. It owns no timer. A transport failure, `rate-limited`, a missing\nor rejected sign-in, or a store failure leaves it `unavailable`, and the next pull replays the same\nrequest; any other denial from the space ends it, and later pulls send nothing. `state()` reports\nexpiries only, errors are fixed sentences, and `close()` aborts a pull in flight.\n\nEvery effectful request is keyed by its requestId and body. Keep one requestId per operation and\nwitness, store it with the witness and the renewal material before you send it, and reuse it with\nthe same body after a restart: a replay is safe, a changed body under the same requestId is a\n`conflict`, and one instance accepts at most 64 distinct requests, so fresh keys per refresh or\nrestart exhaust it. A register requestId stays bound to the body and proposal its first answer\nadmitted: after approval, replay that exact request, and after a refusal or expiry, propose again\nunder a new requestId. A 503 means the request may be bound: replay the same request, or read its\nstatus with `target: { kind: \"operation\", operation, requestId }`; the selector names the operation\nsince this release, and the old `{ kind: \"operation\", requestId }` no longer parses. An owner reads\nstatus only while it holds an interactive row, and a service proof reads only its own instance.\n`registered` and `ready` in a status mean only that the request's registration is current. A\npre-activation re-registration sends `expected: { state: \"registered\", witness }` and yields a new\nwitness; a register that another request overtakes before its barrier freezes answers `conflict`,\nso read the instance and expect its current witness. A register whose gate moved under it without a\nnew registration, such as a freeze another barrier then aborted, also answers `conflict` with the\nwitness unchanged: if the instance still shows the witness you sent, replay the same request. A\nregister held inside the native barrier, or while another invocation of the same request is still\nrunning, answers 503; replay the same request. Once a service has activated, its registration\ncan no longer change. Commands must be ephemeral and declare\nno governed trait.\n\n`caller-grant` takes an owner granter with an interactive row who holds the approved instance, and a\ngrantee is a current exact owner, actor and lifecycle UID. A managed grantee also needs its actual\nsame-owner parent chain, with each current ancestor holding active covering grants for the same\nservice approval. The operation records those immutable grant ids and lifecycle UIDs in `parentRefs`\nand rechecks them before append. An admin scope never substitutes for endpoint caller rights. Every\ncapability must name that instance with `instanceOnly: true`, carry no journal access and no `any` or\n`ledger` target, and sit within the approval's caller ceiling. The answer is `granted` with the grant\nas stored. Ordinary user-auth agent connects now derive their endpoint rows from this policy through\ncore's native grant builder, including reserved Describe for each authorized exact instance. An unpinned\n`invokeService` or `invokeCommand` whose class publish the broker refuses is re-sent once on the rail of\nthe instance that answered its describe, so a granted caller reaches the service without naming the instance. The\ncallout rechecks grantee lifecycle, named ancestor grants, current name, assignment, root, activation,\napproval and ceiling, then checks the policy evidence again after signing and native-key recording.\nThe original connection expiry is at most 60 seconds from issuance, and capped by root and approval\nexpiry. These are fresh leader reads,\nnot a linearized revoke fence. Existing issued connections keep their original expiry, and caller\nrevocation remains deny-new, not terminal absence proof.\nOne instance indexes at most 256 grants over its life, including attempts refused after indexing, and\na full index answers `resource-exhausted`; a new instance is the remedy. `caller-revoke` admits the\ngrant's source owner, its grantee owner and an operator. It answers `pending` with\n`denyNew: \"landed\"` and `notBefore`, in epoch seconds, 71 s after the broker time of the grant's\ncutoff marker. It never answers `revoked`, and the result parser refuses that arm.\n`caller-policy-read` gives an owner its own grantees, and another owner's grantee only filtered to a\nservice it holds; `caller-policy-list` needs a service selector.\n\nCaller grants need `max_payload >= 2098176` (`SERVICE_CALLER_PAYLOAD_FLOOR`: 2 MiB plus 1 KiB),\n`max_control_line >= 4096`, and an auth stream with `max_msg_size: -1`. Broker generation accepts an\nexplicit `serverConfig(broker, accounts, { ...options, maxPayload: SERVICE_CALLER_PAYLOAD_FLOOR })`;\nomission leaves the native 1 MiB default unchanged. No startup path raises limits automatically. The\nstock root sets it with [`cotal up --max-payload <bytes>`](cli.md#up), which records the value in\n`.cotal/broker-policy.json`; a renderer outside `up` reads it back with\n`readBrokerPolicy(root)?.maxPayload` so every render of that broker carries the same limit.\n\nFor a **standalone broker only**, pass `serviceEndpoints.callerPayload.observerCreds` to\n`startAuthService` (or the corresponding authority-plane option). The callback returns fresh\nhost-private credentials from the broker owner's\n`mintServiceCallerPayloadObserverCreds({ pub: broker.sys.pub, signingSeed: broker.sys.signingSeed })`.\nKeep that registered SYS signer with the broker owner, never in the data account, a sandbox or a\nparticipant client. The helper returns an in-memory, at-most-60-second VARZ-only credential.\nThe stock root does this itself: `cotal up` retains the system-account signing seed in the root's\nsecret store at space creation and at `--rotate-sys`, and the auth service started with\n`--service-endpoints` composes `callerPayload` from it when the record names the trust record's\nsystem account and the seed derives it; a root with no retained seed opens the engine and door\nwithout caller issuance and logs why.\nThe callback only supplies credentials, owns no authority resource, and may finish after its\n10-second observation deadline has refused the operation. It is not a cancellation callback.\n\nStartup authenticates native VARZ, matches the observer and data connection's broker incarnation,\nchecks config/system-account evidence and live stream limits, then writes an exact-key assertion\nbound to that broker, configuration and genuine plane claim. Configured clusters, gateways and\nleaf links refuse, regardless of connected peer count. This is not multi-broker proof. A default\n1 MiB broker fails startup with the required byte limit and creates no assertion.\n\nPositive caller issuance repeats the observation and checks the exact assertion revision, complete\nplane hold and effective authority again before native JWT release. Withdrawal or claim loss refuse\nnew issuance. A broker RELOAD, which keeps the same incarnation serving and moves its\n`config_digest`, does not: when the fresh observation proves the same incarnation, the same auth\nstore, and every limit above again, the record is re-asserted under the held claim by CAS on the\nexact prior row and issuance continues. A reload that breaks any of those, a `max_payload` below the\nfloor included, still refuses, and a withdrawn record is never overwritten. A RESTART is a new\nincarnation and refuses. Reopening needs an explicit bootstrap to reassert for the new claim;\na prior-plane broker-bound assertion cannot authorize another append. Legacy assertion syntax still\nparses for existing trusted storage fixtures but alone never enables production caller issuance.\nShutdown drains in-flight observations and closes their owned connections before releasing the claim.\nReads and revokes do not need a positive assertion. A revoke whose policy row would not fit holds\n`payload-precondition` without writing it, and a failed live-limit check withdraws the assertion.\n\nGive each caller operation a fresh random requestId, record it with the exact body before you send\nit, and replay that body after a lost reply, a 503 or a `held` answer. Never switch to a new requestId\nwhile an earlier answer is unknown. A settled `refused` or `expired` ends the attempt, and a grant\nreplayed after its 10-minute window adopts a grant that landed and otherwise answers `expired`.\n\nCaller issuance is generic, not tied to Linear: the same provider-independent contract discovery and\ninvoke path works for ordinary and managed user-auth callers. Controlled policy append currently\nrequires the application's approved service-host instance. Native control endpoints retain their\nexisting ledger/scope and typed authority contracts, not fabricated application approvals. Scoped\nDescribe is not available, and complete terminal retirement and restore remain unsupported. A host revoke refuses new activation, renewal, readiness\nand connections, but a connection already open keeps its original expiry of at most 60 s. Approval\nruns service bootstrap and revoke runs cancellation, while complete observer evidence and writer\nexclusion remain unavailable. Do not seed service reservations in an existing space, adopt old\nservice-shaped rows, or use ordinary retirement to make them terminal. A signing-key or raw-store\nholder can bypass helper guards, so schema rejection alone does not make mixed-version writers safe.\nRestore must quarantine service work until a separately supported reconciliation protocol is\navailable.\n"
214
+ "body": "# Embedding Cotal\n\n> **Guide** (informative) · **For:** implementers building a service on top of Cotal · **Prereqs:** [Architecture](architecture.md), [Identity and auth](identity-and-auth.md), [Delivery daemon](delivery-daemon.md)\n\nThe `cotal` binary in this repo is one composition root: an operator CLI. A separate service\n(for example a hosted, multi-tenant Cotal) does not fork this repo. It writes its **own**\ncomposition root that depends on the published `@cotal-ai/*` packages and imports the surfaces it\nwants. `bin/cotal.ts` uses the same composition pattern. This page is the contract for that: what is a real library\nexport you can build against, how to boot the server-side daemons from those exports, and where the\ncurrent export surface stops short of a fully hosted composition.\n\nThis is the \"guarded substrate\" boundary in practice. Nothing here reveals or assumes a specific\nhost; it documents the public seams any embedder composes.\n\nFor CLI automation, agent tools and wire clients, see the [API reference](api-reference.md).\n\n## What you embed\n\nThe supported reference shape here is **one broker operator serving one space** (one tenant: a\ndedicated data account, under an operator that also holds the system account and a quarantined\nauth-callout account) plus three standalone processes. The trust layer itself composes many spaces\nunder one broker operator today (`createBrokerAuth` + `createSpaceAccountAuth` + N-space\n`serverConfig`); what does not exist yet is the per-space **lifecycle** on a shared broker (see\n[Known gaps](#hosted-composition-gaps)). The three processes:\n\n| daemon | package | what it is |\n|---|---|---|\n| auth-service | `@cotal-ai/auth` | the NATS auth callout, the IdP token exchange, and JWKS. Plane 1 to Plane 2. |\n| delivery | `@cotal-ai/delivery` | the Plane-3 durable backstop: fan-out writer plus trusted reader, per space. |\n| supervise | `@cotal-ai/manager` | the per-machine agent lifecycle (spawn/despawn/attach), per space. |\n\n`mint`, `deliver`, and `auth-service` expose their behavior as direct library primitives, and the\nsupported one-space bootstrap below re-composes from exported low-level primitives. `supervise` and\nthe full `up` orchestration are **not** public runners: `up` also does broker bring-up, restore,\nprocess and registry management, and lifecycle work, and `supervise`'s orchestration is private (see\n[Supervisor signing authority](#supervisor-signing-authority)).\n\n## Workspace registry liveness\n\n`@cotal-ai/workspace` exports `pruneStaleMeshes()` for a liveness sweep. It keeps every\nregistration and returns a `MeshSweep` containing only `offline: string[]`; catalog entries\nare not probed. The former always-empty `pruned` field is removed.\n\nCall `pruneMesh(space)` only after a credentials, mode, or on-disk space mismatch. It removes\nan `up` or pre-origin record and returns whether it was removed. Manual and catalog records\nstay registered. The reason argument and `PruneReason` type are removed. Callers that passed\n`\"gone\"` must report the target offline without calling `pruneMesh`; callers that passed\n`\"mismatch\"` omit the argument.\n\n## Interactive Manager primary\n\nA trusted composition can pass `{ interactiveManagerSelection: \"local-primary\" }` as the third\nargument of `runAuthService(args, store, options)`. `AuthServiceRuntimeOptions` is exported by\n`@cotal-ai/auth`. The third argument still accepts the native daemon lifecycle hooks. No CLI\nflag or exchange field sets the policy, and unsupported runtime values refuse before startup effects. `openAuthAuthorityPlane` accepts the same option beside its fresh\n`localManager` reader; `OpenAuthAuthorityPlaneOptions` is exported too.\n\nThe opt-in chooses the genuine local Manager up front for an unpinned human `manager-caller`\nexchange. It reads the persisted local identity and requires the existing open gate, serve\nprincipal, registration revision and status epoch checks. An absent, unreadable or noncandidate\nlocal Manager refuses without scanning or substituting remote Managers. Explicit selectors win,\nand managed-secret exchanges and launching or issued instance bindings keep their existing rules.\nThe option adds no scopes, registry reads or inventory rows.\n\nThis routes all unpinned interactive Manager control, not only `ps`: slot reads, stop, attach,\ninput, spawn, models, hosted run verbs and generic Manager describe/invoke share the view. It\nchooses local even when the person has a live remote Manager. A host must decide whether that\nrouting is appropriate; a local Manager without execution cannot forward a spawn or run to the\nperson's remote Manager. The person selects that Manager explicitly for those operations.\n\nAbsent the option, selection is unchanged. `startAuthService` still has no local Manager and\nkeeps its remote-only composition. Supplying this programmatic option does not enable it in stock\n`up`, restart or recovery paths; a host must compose those paths separately after adopting the\npublished API. `ps` still lists only the selected Manager's managed seats, not HTTP-hosted sessions.\n\n## User credential authority\n\n`AuthProvider.userCredentials` returns the bearer and sentinel credential. A provider may also\nreturn `authority`, containing the owner and the current `scope`, `allowSubscribe`,\n`allowPublish` and `dmHistory` grant that its issuer authorized for that mint. The stock provider\nreturns this from the exchange response on local and remote user-auth spaces. It does not decode\nthe bearer to reconstruct access.\n\nThe field is optional for provider compatibility. Its absence means the caller has no\nauthoritative grant answer. A status surface must preserve unknown or unavailable instead of\ninferring broad access from a bearer, successful exchange or broker ping.\n\n## Login confirmation\n\n`AuthProvider.confirmLogin` asks the space's IdP whether this machine's cached login still holds.\nIt mints nothing. It answers `confirmed`, `signed-out` when no login is cached, or `rejected` when\nthe IdP refused the cached one, and throws on any other failure. `cotal manager start` and\n`restart` call it on a user-auth space before they save or launch anything, and refuse\n`UNSUPPORTED` when the provider does not implement it.\n\n## Account connection census\n\n`mintAccountCensusCreds` creates a host-only SYS user with at most five minutes of authority.\nIt can request CONNZ for one DATA account and subscribe only to an account-qualified reply prefix.\nIt grants neither KICK nor account events. The host supplies a registered SYS signer; the helper\ndoes not find, persist or renew that signer, and the broker verifies its authority on connection.\n`observeAccountCensusWithCreds` requires this narrow scope and a pinned server key. It reads one\nbounded page. Malformed, incomplete, multiple-server or cluster-declared replies are unknown,\nwith no connection list. A complete result describes only that server's observed account page.\nThe host still needs independent topology and restore guarantees, deny-new, a fixed cutoff and\nlifecycle fencing before using an observation for retirement. These helpers do not grant service\nregistration or terminal retirement.\n\n## Service authority contracts\n\n`@cotal-ai/core` exports closed service-authority request, proof and result types and their\nruntime parsers. The parsers bind a result to the submitted request and registration witness.\n`AuthProvider.serviceEndpointAuthority` is an optional provider hook for this protocol. A provider\nwithout the hook must refuse service setup. The user-auth provider implements the HTTP client,\nincluding `serviceEndpointInfo` for the DATA-account binding. It uses the pinned exchange origin,\nrefuses redirects and does not retry an unknown mutation outcome. Server-side HTTP failures\nremain unconfirmed even when their bodies resemble a protocol denial. A registered snapshot must\nname the submitted closure set. Inline artifacts include each closure manifest as well as its\ndocuments, within the envelope byte limit; native per-closure walk limits still apply. The client does not transmit\nthe local host capability or read callout signing material. Local setup needs the client sentinel\nprojection written by `prepareServer`; a missing projection refuses rather than reading server secrets.\n\n`@cotal-ai/auth` exports host request and view types with `parseServiceHostRequest`. Parsing checks\nstructure only, not owner consent, current grants or admission state. The host handlers and complete native\nservice lifecycle are not implemented yet, so these interfaces do not enable service registration.\nThe native endpoint gate also carries service approval and activation fields. Registration and\nserving guards retain those fields and refuse expired or revoked approval; these guards are not\na replacement for the missing host lifecycle. Internal host gate transitions bind approval to a\ncurrent native root and make activation monotonic. Registration completion is stamped in the\nreopen CAS; a definite abort preserves the previous stamp. They do not provide consent, public handlers\nor terminal retirement. Pre-activation registration requires an empty issuance family, including\ndeleted records, and release rechecks fixed expiry after asynchronous work.\n\n`UserTokenIssuer.issueServiceRenewal` signs a separate registration-bound renewal proof.\n`validateServiceRenewalProof` checks its signature, fixed expiry and full witness binding.\nIt is not a connect bearer. These primitives do not authenticate a current approval or native root;\nthe host must do that before issuing or accepting authority. No client refresh loop is provided yet.\n\n`UserTokenIssuer.issueServiceAccess` signs a serve-only user bearer with the full registration\nwitness and a fixed deadline of at most 60 seconds. Validation requires empty scope and rejects\nordinary parent, manager, session and transfer claims. Ordinary exchange and permission construction\nrefuse this view before actor lookup. Callout\nrefuses it unless a sealed native service authority is configured. The private composition binds\nthe current assignment, native root, registered serving grant and receipt before an encrypted\nresponse. Normal authority-plane startup does not enable it yet; public registration, restore\nreadiness and coordinated root retirement remain required.\n\nInternal service-access reads retain native credential-root authorization and check the activated\nregistration, assignment, current name and fixed expiry. They do not create a serving grant or\nrelease a native JWT. The private callout composition performs native issuance and final\nauthorization when explicitly configured.\n\nService serving-issuance evidence binds the authenticated broker user key, server key and client id.\nThe native release fence rechecks that record and the gate after its CAS. Ordinary serving and\ncredential-root records cannot use this service binding. This is not proof of broker acceptance;\nproduction authority-plane wiring and terminal retirement remain unfinished.\n\n`mintServiceCalloutJwt` is a host-only mint seam. It uses the native serving grant, the actual\nprincipal name and tags, the authenticated broker user key and a separate client inbox nonce.\nExpiry stays bounded by the original admission and access deadline. It does not authenticate the\ncallout request, record natkey evidence or release an encrypted response; the host must do those.\n\nNative service receipts bind the same epcred connection and registration witness to the broker user\nkey. Recording rechecks the evidence, receipt, native authority and fixed expiry. Expired service\nreceipts are retained, not pruned on elapsed JWT time. Qualified retirement and production\nauthority-plane wiring are still required before enabling the service path for clients.\n\nInternal service-name bindings are create-only and return owner and revision from one native read.\nThe trusted host must authenticate the operator and verify the namespace claim before writing.\nNative auth, delivery and manager names keep their existing authority; they cannot be application\nservice bindings. No transfer, release or public name-binding handler is implemented yet.\n\nInternal caller-policy storage uses the sealed native registry and binds each row to one account,\nspace and grantee UID. Grant ids are immutable; an append cannot replace or reactivate one.\nInitial writes require no prior native key history. A deletion arriving after an absence read\ncannot recreate a policy or a pending service gate.\nRevocation begins with a revision-pinned deny-new intent that unrelated appends preserve.\nThese are storage operations, not entitlement checks; the service endpoint host below is their only\nwriter. The effective resolver and native caller issuance are described under the service endpoint\nhost below. Receipts and terminal caller revocation remain unsupported.\n\nScoped Describe callbacks also receive an optional immutable local context with the actual subject,\ncomplete-envelope fingerprint, serving identity and receive-relative deadline information.\n`parseDescribeObservation` shares native syntax and full-JSON fingerprint checks with trusted observers.\nNeither the context nor a fingerprint proves broker receipt to a remote authority. The remote\nobserver and policy projection are not implemented yet. The client contract admits an explicit\nread-only `describe-view` operation using only service-access proof. It checks witness, observation,\nprincipal-policy basis and remaining validity, requires no-store responses, and bounds preparation,\nHTTP streaming and validation by the same local deadline. Cancellation cannot restart that deadline.\nThe native handler and serving adapter are still required before this can authorize a remote view.\n\n`parseEndpointCapabilities` normalizes the native caller capability shape. `endpointCapabilitiesWithin`\nchecks route, instance, target and journal containment using the native grant builders. The host\nstill authenticates the granter and checks current grantee, parent and approval records.\nCross-principal relative-target comparisons refuse when containment is unproved.\n\n`authorizeServeGrant` accepts a read-only `ServiceSpecReader`. A trusted provider can supply\nverified registration and contract reads without constructing a writable KV adapter. The function\nstill derives the complete serving surface and creates the process-local grant.\n\n## Owner-bound platform supervisors\n\nA host can start one user's supervisor without retaining that user's login. Pass\n`platformSupervisor: { authorizePlatformAdmin, observeAssignment }` to `startAuthService`, then call\n`handle.platformSupervisorAuthority(owner)` inside the trusted authority process. The first callback\nmust authenticate the platform's administrative caller through the host's own authority. The second\nreads that owner's recorded `PlatformSupervisorAssignment` fresh on every call. An absent,\nended, expired, foreign-account or wrong-revision assignment refuses issuance.\n\nTo end a supervisor, record its assignment `ended` and call\n`handle.endPlatformSupervisorAssignment(owner)`. It rechecks platform-admin authority and refuses\nunless your record already reads `ended`. It retires the manager gate and the issued supervisor and\nexecutor generations. After that, registration, activation and renewal refuse material returned\nearlier, even before it expires, with `platform supervisor assignment for owner <owner> has ended`\nor the retired-gate refusal. Stop the worker as well: an open broker connection lives until its\ncredential's capped expiry.\n\nThe assignment has `kind: \"platform-supervisor\"`, `scope: [\"supervise\"]`, one derived owner,\none manager instance, one lifecycle UID, a revision and a finite `expiresAt` in Unix seconds. It is\nnot an interactive or managed-agent ledger row and grants no `admin`. The returned door is bound to\nthat owner and accepts `PlatformSupervisorAuthorityRequest` with the same owner, assignment revision\nand an existing `RemoteManagerAuthorityRequest`. It serves only `prepare`, `activate`, `renew` and\n`renewStandingBundle`. Unknown fields, generic profiles, mint, human exchange and another owner\nare refused before issuance. Do not give the worker the auth handle, loopback capability or signer.\nThe host carries only the bound door over its authenticated worker channel.\n\nUse `remoteManagerClient` and `registerRemoteManagerAuthority` from `@cotal-ai/manager` for the\nexisting registration ceremony. The result keeps the stock manager material shape and five nkeys.\nAll returned credentials expire no later than the assignment. The supervisor and executor ceilings\nare recorded in the native issued store. The recorded permission set must be byte-identical to the\nauthority plane's signed native permission set at issuance and every renewal, and must never widen.\nThese JWTs are signed by the authority plane, not returned by the user-token callout. The door\nadds no human bearer, callout view, owner ledger grant or enrollment authority. Run admission,\nhost-backed enrollment and shutdown maintenance need their own host composition.\n\nSee [the issuance design](design/user-auth-run-start.md#platform-supervisor-registration).\n\n## The export surface\n\nEverything below is a real export of a published package, reachable from the package root (each\npackage publishes `.` via `dist/index.{js,d.ts}` and ships `files: [\"dist\"]`).\n`@cotal-ai/connector-claude-code` also publishes `./mcp`, which hosts managed Claude Code sessions\nin one process ([Connect Claude](connect-claude.md#host-sessions-in-one-process)).\n`@cotal-ai/core` also publishes `./browser-control` and `./browser-validators-build`\n([Browser control](#browser-control)). Type-only names are marked; import them with `import type`.\n\n`CotalEndpoint` accepts `environment` as an explicit presence label. Pass `null` to omit the label\nwithout reading `COTAL_ENVIRONMENT`. Omitting the option preserves the process environment default.\n\nShared connector sessions report `card.meta.host` and `card.meta.cwd` from the connector process\nwhen the session is constructed. They override agent-file values and are advisory display data.\nThe directory is a startup snapshot, not a model harness's later shell directory. Neither field\nchanges routing or access, and the connector reads no command-line arguments or environment dump\nfor these values. A connector whose process can host several sessions passes\n`{ withholdProcessCwd: true }` as `MeshAgent`'s third argument and reports each session's directory\nwith `setCwd` (`CotalEndpoint.setCardCwd`) once the harness supplies it; until then the field is\nabsent. The reported path is kept byte for byte, whitespace included; an empty string leaves it unchanged. Claude Code sessions do this from their `SessionStart` hook.\n\n**Daemon runners and lifecycle**\n\n| symbol | package | purpose |\n|---|---|---|\n| `runAuthService(args, store?, options?)` | `@cotal-ai/auth` | boot the auth-service daemon; `store` injects the secret material, and `options` takes the daemon lifecycle hooks or [`interactiveManagerSelection`](#interactive-manager-primary). |\n| `runDelivery(args, store?, onStarted?)` | `@cotal-ai/delivery` | boot the delivery daemon; `store` injects the scoped `delivery` cred, and `onStarted` receives a `status()`/`close()` handle once it serves. |\n| `startAuthService(inputs)` | `@cotal-ai/auth` | start one account-scoped auth-service context and return an `AuthServiceHandle` with the loopback `url`, the per-start `cap`, `readiness`, `drain`, and idempotent `close`. `close` rejects when the context did not release its plane claim: the claim row was no longer its own, or the release write failed. The row then stays held, and the next start reclaims it through the liveness oracle. With the optional `publicFace` input it also serves the public exchange face and carries `publicUrl`. The optional `calloutLimits` input sets the auth callout's deadline, concurrency and slow-line limits ([callout deadlines](identity-and-auth.md#callout-deadlines)). Every full hosted context serves the capability-gated `MANAGED_ACTIVATE_PATH` below, including a separate process with no `platformControl`. With the optional `platformControl` input the handle also has `platformControlAuthority`, the in-process platform control door, `platformControlReadiness`, its read-only readiness read, `observeManagerGate`, the manager gate read a host composing the delegated user intent decisions passes them, and `activateManagedLifecycle`, the same native activation used by the loopback door. With `platformControl.host` it also has `registerHostIncarnation`, which registers the host process's own endpoint instance and returns the incarnation a delegated execution pins, `observeHostGate`, the read of that endpoint's issuance gate, and `awaitHostFence`, which resolves once a later registration or barrier fences an incarnation. `runAuthService` remains the CLI entry. |\n| `MANAGED_ACTIVATE_PATH`, `ManagedLifecycleActivationRequest`, `ManagedLifecycleActivationResult` | `@cotal-ai/auth` | `POST /managed-lifecycle/activate` on the full auth service's loopback face. A separately hosted account authority accepts only `{ accountPublicKey, owner, actor, lifecycleUid }` with its per-start `Bearer <cap>`. The account key must equal that context's assigned data account. Success means the exact UID is active and returns the same coordinates plus `activated: true`. The public face and callout-only replicas do not serve it. |\n| `PlatformControlAuthorityRequest`, `PlatformControlInnerRequest`, `PlatformControlAuthorityResult`, `PlatformControlAssignment` *(types)* | `@cotal-ai/core` | the closed envelope, its inner request union, its result and the backend's assignment row for `platformControlAuthority`. `platformControlOwner` in `@cotal-ai/auth` derives the `p_` owner the door issues under. |\n| `startDeliveryService(inputs)` | `@cotal-ai/delivery` | start one account-scoped delivery instance and return a `HostedServiceHandle` with `readiness`, `drain`, and idempotent `close`. `close` rejects when its lease release does not commit or cannot be confirmed, or when another holder's lease row is still there after it. The process runner remains the CLI entry. |\n| `deliveryCredsKey(space, composition)`, `membershipRwCredsKey(space, composition)` | `@cotal-ai/workspace` | build the secret-store keys the delivery cred and the membership feed's rw cred are read/re-signed under. Keys are **per-space**: `space.<hex>/<kind>`. A hosted composition passes `{ injected: true }`. |\n| `retireManagerInstanceIdentity(root, space, expected)` | `@cotal-ai/workspace` | remove a persisted manager identity only if its complete instance id and serve identity still match `expected`. Returns `removed` or `absent`; refuses malformed, nonregular, and changed records. `absent` is not proof of ownership or successful teardown. The caller must separately prove stop and retirement ownership before using it. |\n| `DELIVERY_CREDS_KIND`, `MEMBERSHIP_RW_CREDS_KIND` | `@cotal-ai/workspace` | the operator-facing KIND names (`delivery.creds`, `membership-rw.creds`) those keys are built from, and what renewal results report. A kind is **not** a key: putting a cred under the bare kind writes the pre-0.4 flat location, which nothing reads. |\n| `Manager`, `ManagerOptions` *(type)* | `@cotal-ai/manager` | construct and run a supervisor in-process; `ManagerOptions.secretStore` injects the one store it reads/writes every secret through. `ManagerOptions.remoteAuthority` is the hosted manager-service authority bundle, including host-owned release, retained-validation, goal-index, and serve-time admin-authorization callbacks. |\n| `ManagerOptions.pooled` | `@cotal-ai/manager` | require signerless remote authority and either an explicit non-custodial runtime or `execution: \"none\"`. A pooled composition must supply the assigned account key and all-duty renewal callback; the CLI's default remains unchanged. A signed-in human's manager gets that material from `managerServiceAuthority`. A platform-run control manager gets it from `AuthServiceHandle.platformControlAuthority` with the shipped `remoteManagerClient` builders, as the [platform control authority](design/platform-pooled-control-authority.md) design describes. |\n| `ManagerStatus` *(type)* | `@cotal-ai/manager` | verified status payload, including optional advisory `host` and `version` from the answering Manager. Older payloads may omit them. |\n| `ManagerOptions.execution` | `@cotal-ai/manager` | omitted or `\"runtime\"` keeps runtime execution. Explicit `\"none\"` accepts a genuine hosting user-auth root, or pooled complete signerless authority, with no `runtime` option. It constructs no Runtime and performs no connector inspection, seat launch or workflow hosting. |\n| `createRuntime`, `Runtime` *(type)* | `@cotal-ai/manager` | resolve the spawn backend (pty built in). |\n| `liveKvEntries(kv, filterOrOptions?, options?)`, `LiveKvEntriesOptions` *(type)* | `@cotal-ai/core` | read live KV entries in one finite scan. Pass `{ signal }` as the second argument or after a key filter to cancel. An interrupted scan throws `IncompleteKvScan`; cancellation throws the signal reason, including during an empty-bucket bind. The scan deletes only its owned consumers, including each one nats.js rebuilt from it, after the broker has answered every create those rebuilds sent. A not-found delete counts as gone, a refused one leaves the consumers to broker inactivity expiry (which also covers a crash), and any other delete failure is thrown, as is a not-found delete of a consumer whose create got no reply from the broker before a timeout or a closed connection. A cleanup failure is thrown only when the scan would otherwise return; the scan's own error, its cancellation reason and `IncompleteKvScan` take precedence. |\n\nThe remote manager authority parser accepts `renewStandingBundle` and `renewRunDriver` only with\nan assigned account nkey, the current manager process epoch, and a host-authenticated registration\nproof. A run renewal also names its active holder, takeover, epoch, fencing token, and the two\nexisting nkeys. The host must fresh-check those coordinates against its registration gate and run\njournal before issuing server-selected profiles. A host without that renewal authorization refuses\nthe request. Until the host issuer wires the operations and validates them on real connections,\nthe presence of these types is not an operational pooled renewal guarantee.\n\nAn execution-free control Manager retains native registration, goal recovery, session-ledger,\nrenewal and maintenance duties. Its status reports `execution: \"none\"`, `runtime: \"none\"`,\n`custody: \"none\"`, no children or connectors, and false `classSpawn`, `runHosting` and\n`terminalSessions`. Local NONE uses this existing status schema without a new wire field.\nExecution is recorded per instance. An incompatible record, retained seat/turn inventory or an\nolder unclassified instance refuses boot before recovery. NONE refuses caller-driven writes,\nincluding persona definition, purge, transcript transfer, preservation and resume, and resolves\nno model adapter. It starts no transcript receiver or sweep. Autonomous registration, lease,\nrenewal, session-ledger and goal maintenance still write their native control state.\n\nSelect the genuine participant Manager with a host-issued, instance-pinned `manager-caller`\nview for workflow and terminal operations. That Manager retains the children, workflow journal\nand terminal sessions. The control instance neither adopts roster peers nor proxies user runs.\nMissing participant selection or authority refuses. This capability adds no application routing.\n\nFor a genuine local control instance, pass `execution: \"none\"` without `pooled`, `remoteAuthority`\nor `runtime`. Startup requires that space's local signing trust, provider pin and user-mode mesh\nrecord. It keeps the native persisted local instance and serve identity; local-primary selection\nuses the existing gate. An existing unclassified identity, including a preclaimed identity with no\nexecution record, is refused. A NONE record cannot restart as runtime. Retained seat or turn\ninventory refuses before recovery. Do not remove identity or capability files to change modes.\n\nThe public `cotal supervise --execution none --space <space>` composition supports the same local\nmode. It validates arguments before connector seeding, resolves no Runtime, and rejects startup\nworkload flags and participant registrations. Omitted execution keeps the ordinary PTY behavior.\nThis does not opt an auth service into local-primary, change scopes or broaden native ps.\n\nRuntime remains the default, but local startup now claims its native identity and execution\nrecord during admission, before later authentication and registration checks. A failed start\ncan leave those files classified as runtime. Malformed identity or capability files also refuse\nearlier. These lifecycle timing changes do not change the instance's identity format or authority.\n\nWith `renewStandingBundle` configured, the manager renews all five standing credentials together.\nIt checks every returned credential for the held nkey and assigned account, test-connects each one,\nand adopts them only if the serve epoch has not moved. A refused or failed candidate leaves the\ncurrent credentials in place and records the refusal as cleanup debt until a later renewal succeeds.\nOn shutdown, after the standing context is drained, an expired maintenance executor is renewed\nthrough the existing scoped host operation so deregistration can finish without restarting duties.\n\nIssued-authority references, source coordinates and stores accept nonempty space tokens in\n`[A-Za-z0-9_-]`, including underscores. These boundaries reject input that would be rewritten by\nthe subject-token sanitizer. Endpoint names still use the separate DNS-label grammar.\n\n**Provisioning and minting** (all `@cotal-ai/core`)\n\n| symbol | purpose |\n|---|---|\n| `createBrokerAuth(label)` | mint BROKER trust: the operator and system account one nats-server trusts. One per broker, shared by every space on it. |\n| `createSpaceAccountAuth(broker, space)` | mint one space's own data account, signed by that broker's operator: the add-a-tenant primitive. |\n| `createSpaceAuth(space)` | the one-space convenience: broker trust + one account in a single composed bundle. |\n| `setupSpaceStreams({ servers, space, creds })` | create the space's JetStream streams. |\n| `ensureDefaultDeliveryClass({ servers, space, creds?, deliveryClass })` | write the space's default delivery class at creation so it is wire-discoverable (SPEC section 4). |\n| `serverConfig(broker, spaces, { storeDir, maxFileStore?, maxPayload?, authTimeout?, extraAccounts?, port?, host? })` | render the broker config: one operator, N space accounts. `storeDir` is required, `maxFileStore` caps JetStream file storage in bytes (omitted, nats-server's dynamic default applies), `maxPayload` sets the broker's `max_payload` in bytes (omitted, nats-server's 1 MiB default), `authTimeout` renders `authorization { timeout }` in whole seconds for the auth callout (omitted, no block and nats-server's default), and `extraAccounts` preloads the auth-callout account. |\n| `mintCreds(auth, identity, profile, opts?)` | mint a scoped cred for any `Profile`. |\n| `mintMembershipObserverCreds`, `mintConnectionEvictorCreds` | mint the membership/eviction scoped creds. |\n| `provisionAgent`, `provisionAgentDurables` | create a principal's bind-only durables. |\n| `newIdentity`, `stripSpaceAuth` | a fresh nkey identity; a stripped signer bundle (data signing seed only). |\n| `Profile`, `CredentialKind`, `MintOpts`, `SpaceAuth` *(types)*, `CREDENTIAL_LIFETIMES` | the profile matrix and cred lifetime policy. |\n\n**Auth building blocks** (all `@cotal-ai/auth`)\n\n| symbol | purpose |\n|---|---|\n| `createCalloutAuth`, `startAuthCallout` | the NATS auth-callout responder. It requires an awaited `recordIssuance`, which must durably record each success's broker user key before the response; the authority plane's `recordIssuance` is the stock one. |\n| `createUserTokenIssuer`, `pinnedJwksResolver` | mint and verify the Cotal user bearer. |\n| `createIdpBridge` | exchange a verified IdP JWT for a Cotal bearer (see [the callout contract](identity-and-auth.md#the-idp-callout-contract)). |\n| `deriveOwnerToken`, `validateUserToken` | owner derivation; strict bearer validation. |\n| `cotalAuthProvider` | the self-registering `auth-provider` extension. |\n| `ensureCalloutAuth`/`loadCalloutAuth`, `ensureIssuer`/`loadIssuer`, `ensureOwnerSecret`/`loadOwnerSecret` | read/write the auth secret kinds through a `SecretStore`. Each `ensure*` writes its first value with `create`, so concurrent first calls on one space return the one value the store holds. |\n| `PLANE_CLAIM_REFUSED`, `planeClaimRefusal`, `PlaneClaimRefusal` *(type)* | every plane-claim refusal carries a `PLANE_CLAIM_REFUSED` detail, and `planeClaimRefusal(err)` reads its `reason`: `corrupt`, `live-peer`, `unknown`, `concurrent`, `fenced`, `released` or `lost`. Only `unknown`, an inconclusive liveness observation, is coded `unavailable`. A host can retry contention and stop on a corrupt row without matching message text. |\n\n`startAuthCallout` processes up to 32 connections concurrently. Its hooks must support overlapping\ncalls for different connections. A slow authority check or recorder occupies one slot; other\nconnections can still authenticate. Each response waits for that connection's authority checks,\ndurable issuance and final expiry check. Work beyond the bound waits and can still reach the\nbroker's authorization deadline. The returned `done` waits for admitted hooks when the subscription\nends and rejects an unexpected worker failure after those hooks settle.\n\n**Seams and the wire** (all `@cotal-ai/core` unless noted)\n\n| symbol | purpose |\n|---|---|\n| `SecretStore` *(type)* | the durable hosted-secret seam (get/put/create/delete). `create` writes only while the key is absent and reports whether it did, so it must be one atomic step in the backend. `get()` returns raw seeds/keys into process memory, so it is a blob seam, not HSM/KMS signing. |\n| `FsSecretStore`, `workspaceSecretStore(root)` | the filesystem default. **These live in `@cotal-ai/workspace`, not core.** |\n| `AuthProvider` *(type)*, `Connector` *(type)*, `Runtime` *(type)*, `Command` *(type)* | the extension contracts; implementations self-register on import. |\n| `registry` | the shared registry a composition root pulls surfaces into. |\n| `CotalEndpoint`, subjects, message types | the wire client and shapes. |\n| `ParsedArgs` *(type)* | the shape the daemon runners take (see below). |\n\nFor a Linux Unix-socket adapter, `peerCredentials(socket)` from `@cotal-ai/seat` returns\nkernel-observed peer `pid`, `uid` and `gid`. Compare these against the host's authorization\npolicy; request-supplied identity and process liveness do not replace that policy or a\nlifecycle fence. The helper starts no custodian and refuses unsupported platforms or a\nmissing native helper.\n\nThe runners take a CLI-shaped `ParsedArgs`, not a typed options object, so a host fabricates one:\n\n```ts\nconst args: ParsedArgs = { values: { space, server, port: \"0\" }, positionals: [], raw: [] };\n```\n\nFor an embedded delivery instance, use `startDeliveryService` instead. Its `HostedContextInputs`\ninclude the account public key and lifecycle UID, space, broker URL, injected store, stable\n`storeIdentity`, and an explicit `stateDir`. The store must declare that same injected identity.\nThe initial delivery credential must belong to the assigned account. The function returns only\nafter the delivery responder is bound. `close()` withdraws serving and releases only the lease\nowned by that instance. It closes both membership connections even when a disconnected drain\nfails, so they cannot reconnect after closure. It rejects when its release does not commit or\nthe broker cannot confirm it, or when another instance's lease row is still there afterwards.\nIf the delivery connection drops or is down while the release is in\nflight, `close()` waits up to the broker-gone window (`COTAL_DELIVERY_BROKER_GONE_MS`, 15 seconds\nby default) from the drop for it to reconnect, and repeats the release once on the reconnected\nconnection before it decides. `drain()` returns the same promise. A successor is refused while such\na row lives, and the bucket TTL expires a row the instance left. Credential-expiry health state clears after\nsuccessful broker-verified adoption through the existing `reloadCreds` rail. A failed start\nrefuses locally without exiting the host process or stopping another account's delivery service.\nIf a health fault occurs during an asynchronous store read, startup rejects when the read returns\nand closes any resources created by that late completion.\n\n`startAuthService` takes the same `HostedContextInputs`. The store must declare the assigned\ninjected identity, and its data account must be the assigned account. The IdP pin and ledger live\nunder the explicit `stateDir`. The auth plane's instance identity holds its private serve seed, so it\nlives in the store under `authInstanceKey(space)`. A record an earlier release kept under `stateDir`\nmoves into the store on the first start.\nThe context never resolves a workspace root from the working directory and has no local manager, so\nonly remote manager gates can be selected. It returns after\nthe authority plane, the callout subscription and the loopback listener are bound. A start that\nfails closes the connections it opened and releases its plane claim, so a retry on the same space\ncan claim it. A fenced plane or\na lost broker connection makes that context `unavailable` and closes it without exiting the process.\nThe host writes no discovery file for it. The handle carries what `auth-service.json` holds for a\nCLI start: the loopback `url`, `publicUrl` when a public face runs, and the per-start `cap`. The cap\nalone authorizes the loopback host actions, lifecycle retirement and managed-agent enrollment\nverification, so keep it in the authority process. `publicFace` takes the CLI's public face inputs\n(`port`, `url`, `trustedProxy`, `advertisedServer`, `agentProvisioningUrl`) under the same rules,\nand a face without a port refuses to start.\n\nTwo optional inputs serve a platform composition. `platformControl: { observeAssignment }` adds\n`platformControlAuthority` to the handle. It is a typed in-process method, served on no listener,\nthat issues the manager-service request family for the one control manager the backend assigned to\nthis account, under a derived `p_` owner. It reads the assignment fresh on every call and refuses\nan IdP token, another account, a stale revision, another instance or lifecycle, and an instance\nanother owner registered. It refuses `prepare` and `activate` while the assignment's named\npredecessor is still registered or frozen. The same input adds `platformControlReadiness(instanceId)`,\nthe route for a host that needs to know whether its assigned control manager is serving. It returns\nthat instance's attributed `status` reply and refuses any instance the current assignment does not\nname, or one whose gate another owner holds. It reads over the context's own connection, whose\ngrant is the assigned instance's `describe` and `status` and its own reply rail. That connection\nrenews in process like the context's other connections and never leaves it, so the host lends no\nhuman or operator credential to a worker, mints no control instrument per read, and does not read\nliveness off the manager process. Without the input both members are `undefined`.\n`standingRenewableTtlSeconds` is forwarded unchanged to the authority plane, which bounds it to 5\nto 86400 seconds. It is a trusted-host input for the renewal rehearsal, and no request or CLI flag\nsets it. `issuerSessionTtlSeconds` sets the credential lifetime of the plane's held issuer session\nthe same way, bounded to 5 to 300 seconds, with the five-minute `issuer` lifetime as the default. SPEC §13.1 and §13.6 define the view.\n\nThe auth plane can renew a registered manager's five standing credentials from the current\nservice registration. Run-driver renewal reads the hosted run attempt and checks its active\nfence as well as the manager's open issuance gate and process epoch. A moved gate or run\nfence refuses issuance. These primitives do not establish a complete pooled deployment.\nA fresh auth plane can initialize without a delivery-admin responder. Reclaiming a held claim from a dead predecessor needs the delivery\ninstance first: its admin rail must complete the broker connection-liveness sweep before the\nauth plane takes the claim. An absent or inconclusive oracle refuses the reclaim.\n\n### Remote MCP gateway\n\n`@cotal-ai/connector-core` exports `registerCotalGatewayTools(server, host, source?, options?)` for\na service that serves Cotal to a hosted MCP client over HTTP. A hosted client can send many\nconversations through one bearer and one MCP session, so a request does not say which conversation\nsent it. Each conversation calls `cotal_connect` and passes the `connection_id` it returns on every\nother tool call. A missing, unknown or other-account handle returns `CONNECTION_REQUIRED` and runs\nnothing. No call falls back to another connection of the account.\n\nThe host implements `GatewayHost`:\n\n- `account(auth)` returns the account the request authenticated as, read from the SDK's `AuthInfo`.\n It throws when the request has none, and the tool then runs nothing.\n- `open(account, name, context?, selection?, approvalId?)` starts a connection only after the person\n approves its permissions. `selection` is a proposal. Throw `ApprovalRequired` with the request ID,\n approval page, expiry and proposal while they decide. The tool returns a structured pending result\n and a readable link, with no connection handle. `approvalId` resumes one unchanged request when\n `options.approvalResume` is enabled. It conveys no authority. Bind it to the authenticated account,\n space, name and request generation. An issued approval cannot grant a replacement connection.\n Throw `NameTaken` only for an authoritative name collision. A new request tries `name_2` and later\n variants up to `GATEWAY_NAME_ATTEMPTS`; a resumed approval never renames. The collision check and\n issue must be atomic. Other errors reach the caller without renaming and must not carry secrets.\n- `find(account, id)` and `close(account, id)` act only on a connection that account owns.\n\n`cotal_connect` refuses a name `assertValidName` rejects before it calls `open`. Its reply names\nthe channels the new connection reads, may join and may post to, from the configuration its grant\nproduced. `GATEWAY_TOOLS` names the mesh tools the gateway offers, `cotal_docs` included. A native\nembedder whose host issues each conversation its own grant may pass `options.tools` from\n`NATIVE_GATEWAY_TOOLS`, which adds spawn, despawn, persona, run and reconnect but not yield.\nRegistering a tool offers it to no connection by itself: a connection calls only the tools its\nhost lists in `GatewayConnection.tools`, default `GATEWAY_TOOLS`, and only those its credential's\ncapabilities allow. With `options.selection`, `cotal_connect` takes channels, a role and capabilities,\nbuilds a canonical proposal with core's `conversationSelection`, and hands it to `open`. Its\ndescription tells the agent to ask in that first call for the channels, role and capabilities it\nalready knows it needs, so the person approves one request. Only the\nperson's decision in the authority's authenticated UI is consent. The approved selection may differ\nfrom the proposal and must stay within their current authority. The empty approved selection still\nincludes direct-message send and receive and own activity publication; disclose these before\napproval. A model flag, API bearer or ordinary tool approval cannot approve the request. Unsupported\napproval paths refuse before issuing a grant. One tool list serves every connection, so no\nadvertised text names one connection's channels. Each call runs against that connection's own\nconfiguration. Authentication, credential issuance and revocation and durable connection records\nstay with the host.\n\nA remote MCP client gives the server no way to start a turn, so the gateway adds `cotal_wait`. It\nreturns at once when a message that should wake the agent is buffered, and otherwise as soon as one\narrives, with the same reply `cotal_inbox` gives. Wake-worthy follows the agent's attention: direct\nmessages, role requests and @mentions always, other channel traffic only in `open`. With none, it\nreturns after `options.waitSeconds`, which defaults to `GATEWAY_WAIT_SECONDS` (50). Keep it under\nevery proxy and client timeout in front of the service. The reply is one JSON body, so nothing is\nsent until the wait ends: Claude Code gives a remote server 60 seconds to the first byte, Cloudflare\nends an origin response after about 100 seconds and claude.ai ends a tool call after 240. A wait\nwhose client closes the request stops listening, and a read whose client is gone by the time it\nwould clear messages clears nothing, so neither takes a message it cannot deliver. A wait ends\nwhen its connection closes, also while the broker is unreachable; it listens for `MeshAgent`'s\n`stopping` event. In `focus` an @mention is not buffered, so the gateway counts the ones\nsince the last read, and a wait that starts after one returns it at once. Every other routed tool\nexcept `cotal_inbox` adds a line to its result when wake-worthy messages are waiting.\n\n`handleGatewayRequest(host, { req, res, body?, auth?, source?, instructions?, approvalResume?, selection?, waitSeconds? })`\nserves one HTTP request to the endpoint with the package's own MCP server, so the embedding service\nnever imports an MCP SDK or a zod version of its own. The service authenticates the request, answers\n401 itself when that fails, and passes the result as `auth`. A framework that already parsed the JSON body passes it\nas `body`. `selection` turns on the permission request described above for a hosted endpoint. The endpoint is stateless: each POST gets a fresh server and a JSON response, and every\nother method answers 405. A `cotal_wait` call holds its POST open for up to `waitSeconds`.\n`GATEWAY_INSTRUCTIONS` is the server instructions text sent when `instructions` is omitted.\n\n`serveGatewayStdio(host, { input?, output?, source?, instructions?, waitSeconds?, wake? })` serves the same\nsurface over stdio, for a local client such as Claude Desktop that launches one process for all of\nits conversations. A stdio request carries no authentication, so `host.account` receives `undefined`\nand names the local user. A client that cancels a call aborts its signal, so a cancelled wait stops\nlistening. The streams default to the process's own, and stdout then carries only MCP.\n\nAn embedder whose client can be woken passes `wake`, to `serveGatewayStdio` or in the options of\n`registerCotalGatewayTools`. The gateway calls `wake.signal(connection, preview)` when a connection\ngets something that would end a `cotal_wait` while no wait holds it. A true result means a reader\nheard the signal, not that it received complete message content. The preview never consumes mail.\n`cotal_connect` adds `wake.listening(connection)` to its reply. An embedder delivering full content\ncan return false from `wake.inboxNotice(connection)` to omit competing inbox-read advice from other\ntool results. Notification-only clients retain that advice.\n\n`wake.attach` receives a rearm callback. Call it without arguments when a replacement reader starts\nlistening. Call it with one connection after confirmed inline delivery to reoffer that connection's\nremaining work. Pass `false` as its second argument to clear the latch without immediately retrying\na refused handoff. Ordinary inbox reads and waits also clear the latch. An adapter offering complete\ninline messages can use `prepareInlineDelivery`: hold whole automatic messages, validate the final\ntransport size, recheck the batch before admission, then settle it with the native result. A failed\nor unknown admission releases the hold without committing. Never settle successfully on a preview,\nsocket write or queued native call. `GATEWAY_INSTRUCTIONS` combines `GATEWAY_CONNECTING` and\n`GATEWAY_LISTENING`, so an embedder can supply its own listening instructions.\n\n### Private tool results\n\n[SPEC §13.19](../SPEC.md#1319-private-tool-results) accepts a private, consent-bound read path for\nmanaged-agent tool results. It is not served or enabled. Core exports the closed\n`ToolResultConsent`, `ToolResultRevocation` and `ToolResultServingMaterial` contracts, their\nparsers, and the frozen `TOOL_RESULTS_CLUSTER` declaration. These parse structure and static\nbindings only. They do not verify a consent signature, establish human proof or read current\nrevocation and lifecycle state. The serving material's grant coordinates are not a branded\n`EpServeGrant` and confer no authority. `parseToolResultAnswer` also checks the UTF-8 byte count;\na schema's character limit alone is not the byte bound.\n\n`@cotal-ai/auth` exports `verifyToolResultHumanProof` for the consent prerequisite. It verifies\nan EdDSA IdP JWT against the existing issuer, audience and key pins, then requires integer-second\n`auth_time` no later than the decision and at most 300 seconds old, plus a signed `amr` array\ncontaining `pwd`. The host compares elapsed milliseconds without rounding its clock to seconds.\nJWT clock tolerance does not widen this window. Ordinary bearer exchange does\nnot require these claims or turn them into consent authority.\n\nThe loopback-only `POST /tool-result-human-proof/verify` takes only `{ idpToken, subject }` with\nthe host's current capability and no Origin header. The host supplies its authenticated session\nsubject. Success returns `{ authorized: true, sub, owner, authTime, exp }`; the owner derives from\nthe verified subject, which must match the session. The door verifies proof only. It does not\nsign consent, issue credentials, register a service or serve private content. A host must still\nrefuse platform keys and check current membership and lifecycle at consent admission.\n\nA host may opt into consent issuance with `startAuthService({ ..., toolResultConsents: { keyId,\nresolveAnchor } })`. Provision its Ed25519 nkey seed under `toolResultConsentKey(space)` in the\ninjected private store as `{ ver: 1, keyId, seed }`. The resolver reads that space's current\n`consents` anchor with scope `tool-results`. Missing, corrupt, revoked or mismatched signing\nmaterial refuses. Neither the private store nor the resolver belongs in a worker or client.\n\nThe loopback-only `POST /tool-result-consent/issue` requires the current host capability and no\nOrigin header. Its closed input is `{ id, idpToken, subject, accountPublicKey, holder, target,\nttlMs }`. The host resolves those coordinates from its current authenticated membership and\naccount assignment. `holder` carries `{ actor, lifecycleUid }`; `target` carries `{ owner,\nactor, lifecycleUid }`. Auth verifies the signed password proof and derives the owner itself,\nrequires a current same-owner interactive holder and managed target, and caps the window at\n24 hours. It returns only `{ consent }`, after a create-only `consent.<id>` auth-store write.\nDuplicate ids refuse. A failed or lost acknowledgement returns no consent and never retries.\nThe host must not label an unknown outcome completed or resubmit it automatically.\nOnly the auth mint writer holds consent-KV publish authority. The environment admission writer\nand remote manager issuer do not inherit that grant. Create-only enforcement remains in the recorder.\n\nThis door is absent from the public face. Without the opt-in signer it answers unavailable.\nIt installs no serving material, revocation store, caller view, capture or result reader.\n\nPublic tool arguments and results remain withheld. Auth and host issuance, Manager material,\nconnector capture and the browser caller must each be landed and qualified in the\n[design's owner order](design/private-tool-results.md#9-owner-order), then carried by a stock\nrelease before activation. Without a complete authoritative revocation snapshot and an established,\nenforced clock-skew bound, the serving commands must answer `unavailable`.\n\n### Browser control\n\n`@cotal-ai/core/browser-control` describes and invokes an endpoint from a strict-CSP page. The page\ncompiles no code: the host passes validators it generated at build time with\n`generateBrowserContracts` from `@cotal-ai/core/browser-validators-build` (Node only). The generator\ntakes each cluster document with its recorded digest and schema roots, recomputes every digest and\nrefuses a mismatch or a missing root before writing anything. It supports single-document closures\nonly, so a command whose closure spans several documents refuses. The generated module imports\nAjv's runtime helpers (`ajv/dist/runtime/*.js`), so the host's bundler must resolve `ajv` from\nwhere the host writes that module.\n\n`openBrowserManagerCaller` opens a Manager caller for ONE instance the person selected; there is no\nimplicit selection. It takes the broker's websocket URL, the space, the principal and lifecycle the\nbearer is bound to, the instance, and the Manager's contracts generated from\n`managerBrowserContractSource()` (`@cotal-ai/manager`). Authority comes from an `acquire` callback\nthat returns the person's own `manager-caller` bearer and the space's sentinel credential; an\nembedding's backend obtains the bearer from the stock exchange with the person's IdP proof. The\nbearer's space, principal, lifecycle and instance are checked before anything is dialled, and the\ndescribe is pinned to that instance. The view carries only the commands the person's ledger scope\ngrants. `spawn`, for example, carries `spawn`, `despawn`, `inspect`, the persona commands and\n`goal-result`, plus the launch reads `status`, `models` and `resolve-cwd` on that one instance,\nwhile operator reads such as `ps` and `slots` come only with `admin`; the broker\nrefuses a command the view does not carry. The connection never reconnects on its own; `reopen`\nacquires again and re-checks every pin.\n\n`followGoal` submits a goal command once under an envelope id the host persisted before calling\nit, and follows the goal to its terminal with the stock goal follow. Live progress settles the goal\nonly when it comes from the instance and epoch that accepted it; any other terminal settles nothing\nand prompts a read of the goal's own record. `reconcileGoal` reads an\naccepted goal back through the Manager's `goal-result` command, and `verifyGoalResultFact` checks\nthe returned fact, including its outcome digest, through Web Crypto. Nothing here retries. Three\noutcomes stay distinct: an error reply is a refusal; a goal accepted but not seen to finish answers\noutcome `unknown` and is read back, never submitted again; a request no instance answered throws\nthe stock unanswered error (`unansweredRequest`).\n\n`POST /manager-instances` on the auth service lists the signed-in person's own Manager instances. It\ntakes `{ idpToken }`, verifies it as the human exchange does and answers\n`{ v: 1, owner, complete: true, instances: [{ instanceId, placement, state }] }`. `placement` is\n`remote` or `local`; `state` is the verdict the `manager-caller` exchange selects on (`candidate`,\n`not open`, `not registered`, `not this owner's`, `unknown`). A `candidate` is registration\nevidence, not proof that the instance answers; a describe pinned to it is. The route refuses\nbrowser-origin requests like every exchange route, so a page reaches it through its own backend,\nand a failed gate read answers 503, never an empty list.\n\n### Remote manager client composition\n\n`@cotal-ai/manager` exports the `remoteManagerClient` namespace, containing the stock remote\nrequest builders and response validators, and `registerRemoteManagerAuthority` for registration\nwith a host-issued prepare credential. It returns the process epoch and registration revision its\nown registration committed. When a later start of the same instance registers before this start\nauthorizes its serve grant, this start is refused with `expired`.\n`RemoteManagerIdentityState` describes the five private\nmanager identities stored under an explicit account-local root. Use these public exports when\ncomposing `ManagerOptions.remoteAuthority`; do not copy CLI validators or import private modules.\n`managerClusterArtifacts()` returns the canonical document, manifest and their digests used by\nregistration. Pass its `[document, manifest]` pair as `contractArtifacts` to both\n`remoteManagerRegistrationProof(owner, state, contractArtifacts)` from `@cotal-ai/core` and\n`remoteManagerClient.remoteManagerAuthorityRequest(state, actor, \"activate\", { registrationProof, contractArtifacts })`.\nThe request builder takes each operation's coordinates as named fields of its last argument.\nThe host still validates the artifact closure and current registration before activation.\n`managerBrowserContractSource()` returns the same document with its closure digest and each\ndistinct schema root, the input `generateBrowserContracts` from\n`@cotal-ai/core/browser-validators-build` takes at a host's build. Its closure manifests are left\nout because they are not schemas; the generator recomputes every digest and refuses a mismatch.\nThe namespace includes closed standing/run renewal, admission, maintenance, enrollment,\nretirement and goal-index scan helpers. `publicIdentities(state)` returns the `identities` record every request\ncarries: the five public ids, in the order the host echoes them. `remoteManagerClient.remoteRunHosting` builds the four `runHosting` callbacks from the registration\nand the transport you supply for the host's run admission, run attempt and authority requests, so\nyour manager sends the run requests the stock manager sends. The namespace provides no signer or\nnew grant. The host still owns authenticated issuance, current registration and activated-run\nobservations, and any guarded foreign-holder repair.\nAn embedding must preserve those checks and supply a supported runtime; the client exports alone\ndo not provide a pooled runtime, an authority service or a complete hosted context.\n\n### Long-lived endpoints take a bearer function\n\n`EndpointOptions.bearer` accepts either a string or a function, and the difference is not stylistic.\nA string is minted once, so when it expires (which it will: callout bearers live minutes) the\nendpoint has nothing to renew with. It will not present the dead token to the broker, since that is\na guaranteed denial that still costs a full auth-callout round trip. It refuses to reconnect, emits\n`warning` saying which case it is in, and retries on a widening backoff until the process\nre-authenticates and rebuilds it. Retry notices use `warning` rather than `error` because Node\nrethrows an unhandled `error` event and would kill a host the endpoint is still trying to recover.\n\nWhen the broker refuses a bearer at connect, the `warning` says the broker refused this endpoint's\nbearer and that the auth service logs why, because nats-server passes the client no reason. The\nendpoint then retries on its capped backoff. Each wait is a random point in the upper half of its\nstep, so endpoints refused together, after a broker restart or by an auth limit, do not retry\ntogether. A bearer source that throws an error with a numeric `retryAfterSeconds` is called again\nwhen those seconds have passed, not before, and a reconnect inside that wait dials on the bearer it\nholds. The auth provider's rate-limited exchange throws that way, and `agentBearerCommand` prints\n`retry-after <seconds>` for it.\n\nPass a **function** for anything that outlives one bearer. That is a renewal source: it is called\nahead of each expiry and again whenever a reconnect finds the cached bearer dead, and it requires\nexplicit `card.owner` and `card.actor`. The first-party surfaces already do this\n(`UserViewAuth.source`, the connector's `agentBearerCommand`). A string bearer is for a short\none-shot connection.\n\nA `MeshAgent` a host runs in its own process takes the same kind of source. Pass\n`userAuth.bearer`, a function returning a fresh bearer, instead of `userAuth.bearerCmd`, the argv a\nlaunched seat execs. Such an agent has no manager-call bearer, so its spawn, despawn, persona and\nrun calls return a refusal without reaching a manager.\n\nLong-lived hosts must also subscribe to the endpoint's `warning` event. It carries conditions the\nendpoint is surviving, including failed credential renewal, reconnect retries, its own DM inbox\nmissing from the broker while the connection is up, a durable leave\nit keeps retrying after the broker refuses a durable channel's live subscription, and a channel\nregistry entry that does not decode to a valid config, such as a raw put of an unknown delivery\nclass or of `null` on the defaults key. The endpoint drops that entry from its cache and applies the\ndefault policy until a valid entry is written. The DM inbox warning comes once, after the broker\nhas reported the inbox missing twice. The endpoint does not recreate the inbox. It keeps checking\nand receives again if its provisioner creates the inbox again. A host may choose\nto ignore warnings for a one-shot endpoint whose awaited operation owns the verdict, but that choice\nshould be explicit. An unhandled warning is nonfatal and silent.\n\nThe `error` event carries a fault the endpoint cannot return from a call, such as a refused\nsubscription or a refused publish that no request was waiting on. Attach a listener before `start()`,\nsince Node throws on an unhandled `error`. A denial the broker returns to a request, such as an\nobserver's read of the DM stream, reaches only that call, which decides what it means, and is not\nemitted again as an `error`.\n\n## Booting the daemons\n\n### auth-service\n\n`runAuthService(args, store?, options?)` reads its provisioned long-lived secret kinds (service keys, callout\naccount, issuer keys, owner secret) through the injected `SecretStore`; a host provisions those into\nthe store first. It is a **signer and identity authority**, not a scoped daemon: at runtime it holds\nthe data-account and callout-account signing seeds, the issuer's private JWKs, and the\nowner-derivation secret in process memory (`SecretStore.get` exports raw values). The IdP pin and the\nactor ledger are **not** store-injected: `runAuthService` resolves them under\n`userAuthStateDir(findCotalRoot(), space)`, a path relative to the process working directory, so a\nhost provisions those into that exact directory (neither `store` nor `COTAL_HOME` selects it). It\nalso writes an ephemeral `auth-service.json` discovery file there that carries the live exchange\ncapability. That file appears only after every plane is bound, so waiting on it is the readiness\nsignal: a host that also passes the daemon's pid to the provider's `ready()` gets a process-bound\nwait. The wait extends past the base timeout while that pid is alive, up to a fixed bound, and it\nends at once when the pid exits.\n\n```ts\nimport { runAuthService } from \"@cotal-ai/auth\";\n// store implements SecretStore over your secret backend; get() returns raw seeds into memory.\n// Provision the auth secret kinds into the store, AND the IdP pin + actor ledger under\n// userAuthStateDir(findCotalRoot(), space), before this call.\nawait runAuthService(\n { values: { space, server: brokerUrl, port: \"8081\" }, positionals: [], raw: [] },\n store,\n);\n```\n\n### delivery\n\n`runDelivery(args, store?, onStarted?)` runs from a **pre-minted scoped `delivery` cred** and never loads the\nsigner. Provide the cred either through the injected store (under\n`deliveryCredsKey(space, { injected: true })`) or with a\n`--creds` file; the two are mutually exclusive. The daemon re-fetches the cred from the store at 75%\nof its JWT lifetime and fails loud rather than riding to expiry, so **something must re-sign a fresh\ncred into that same store**. When that read finds the previous generation still there, the daemon\nreports the missed remint and retries in 60 seconds. The current cred stays live until its expiry,\nand the store is read once per retry rather than once per second.\n\n```ts\nimport { runDelivery } from \"@cotal-ai/delivery\";\nawait runDelivery({ values: { space, server: brokerUrl }, positionals: [], raw: [] }, store);\n```\n\nThat renewal is a **signer** operation, not the delivery daemon's:\n`remintDaemonCreds(root, space, store?, { preflight? })` (`@cotal-ai/workspace`) reads the `SpaceAuth`\nsigner **through the same resolved `store`** (`getSpaceAuth(store ?? workspaceSecretStore(root), space)`,\nkeys `auth/broker.json` + `auth/account.<key>.json`; the pre-split `auth/auth.json` monolith is\nmigration input and the container signer mount only) and re-signs the daemon creds (`delivery.creds` and the membership feed's\n`membership-rw.creds`) back into that store. The injected `store` is both the signer source and the\ncredential destination, never a split. `space` is **required** and validated against the store's signer, so a\nstore swapped to a different space cannot re-sign over the wrong broker's creds. `preflight` is a\ncaller-supplied proof that the broker accepts the credential. The reference `Manager` passes a\n`probeConnect` over its `servers`. It gates **every** candidate before overwriting the last-good,\nwhether the signer is a full bundle or a stripped projection: a bundle's JWT chain proves only that\nit is self-consistent and\nnamed the space, NOT that its account is the broker's *current* account for that space (two\n`createSpaceAuth(space)` calls yield same-named, different-account chains), so a same-label alternate\nsigner would otherwise mint a broker-dead cred and clobber the good one. The offline local repair (`doctor auth --fix`) has no preflight. It permits the overwrite only\nunder **authority continuity**: the candidate must be signed by the same account signing key (`iss`) as the current\n(already broker-accepted) cred. A same-label alternate account breaks continuity and is refused, full or\nstripped; a legitimate local re-sign is continuous and proceeds without a network. The reference\n`Manager` runs it on a schedule against its **own**\n`secretStore` (see below), so passing the manager and the delivery daemon the *same* store closes the\nrenewal loop end-to-end on an injected backend: the manager reads the signer from the store, re-signs\ninto it, and the daemon adopts each generation on a preflight-proven 75% timer. The stock\ncross-host composition cannot satisfy that by writing one filesystem and fingerprinting another:\n`Manager.start()` and every later remint challenge the daemon's `reloadStoreIdentity` and a\ndivergent pair is refused naming both stores. The identity is the store the daemon actually\nreloads: an injected coordinate, the workstation root only when `--creds` is\n`<root>/.cotal/<spaceSegment(space)>/delivery.creds` (matching the canonical arm), the\nfile's own directory for any other `--creds` path, or the workstation root. A filesystem\nstore is also named by a random id it records in `store.id` inside its own directory, so two\nhosts that use the same root path are two stores. No key and no `--creds` file may be that\nfile under any name, and a `store.id` that is a symbolic link or holds anything but a lowercase UUID is refused. Uninjected\n`--creds` that names one real workstation while process cwd resolves another is refused\nat start, naming both, because membership-rw still uses `findCotalRoot`. A `--creds`\npath that is not under any `.cotal` tree is not that case and is not refused here. It never\nwalks ancestors with `findCotalRoot`. No bound daemon is not a named\nstore, so start proceeds; a later daemon on a foreign store is refused on the next remint.\nThe first-party filesystem adapter declares its workspace-root identity on the store itself. Other\ninjected adapters declare their stable coordinate on `SecretStore.identity`, or name it in\n`COTAL_SECRET_STORE` on both processes. It never throws: it\nreturns per-file results (`skipped: \"no-auth\"` when the store holds no signer records),\nso the caller must check them or the cred still rides to expiry. A composition whose signer lives in\nKMS/Vault simply injects that store; no bespoke renewal is needed. A `--creds` file path must be\nreplaced atomically before the 75% read. The signer can now be injected behind the store seam, which\nresolves custody. The remaining hosted gap is signer **isolation**. The seed is still decrypted\nin-process at the manager's uid, so it needs an OS sandbox or remote signer.\n\n### Supervisor signing authority\n\n`@cotal-ai/manager` exports the `Manager` class; there is **no** `runSupervise(opts)` runner. The\nprivate CLI `runManager` also does broker-reachability checks, space/default resolution,\nroster/launch parsing and materialization, installed-extension resolution, signal handling, staged\npre-spawn, and the forever wait. A host composes that lifecycle itself around `Manager`:\n\n```ts\nimport { Manager } from \"@cotal-ai/manager\";\nconst mgr = new Manager({ space, servers: brokerUrl, workspaceRoot });\nawait mgr.start(); // then wire your own SIGINT/SIGTERM -> mgr.stop()\n```\n\n`stop()` runs once. A later call joins the stop in progress and settles with it, and a call that\nasks for a different `withAgents` than the running stop is refused.\n\nUnlike delivery, the manager is **not** a pre-minted-scoped-cred daemon (auth-service is also a\nsigner: it holds fewer artifacts than the full trust bundle, but its data-account signing seed still\ngrants complete data-account mint authority on compromise, so this is not least-privilege). On `start()`\nthe manager reads its space's full trust chain **through its `secretStore`** (`getSpaceAuth(this.secrets,\nthis.space)`, composed from `auth/broker.json` + `auth/account.<key>.json`; a container may instead\nmount a stripped signer bundle at the legacy `auth/auth.json` key) and **self-mints** its supervisor cred and renewals from the\ndata-account signing seed. In static mode it also mints every per-agent cred from that seed; in user\nmode agents instead receive callout-minted bearers, but the manager still holds the signing seed for\nits own creds and renewal. So a hosted supervisor is a **trusted per-tenant account-signer process**,\nnot a least-privilege connect client. It additionally requires a `~/.cotal/meshes/space.<key>.json`\nregistry record and the workspace user-auth marker to start in user mode. `ManagerOptions.secretStore`\ninjects the one `SecretStore` the manager uses for **the signer itself (the split trust\nrecords)**, daemon-credential renewal (`remintDaemonCreds`), and per-agent secrets,\ndefaulting to the workspace filesystem store; pass the delivery daemon the *same* store for end-to-end\nhosted renewal. The store declares the same identity on both processes, or both set\n`COTAL_SECRET_STORE` to the same coordinate. The manager\nremints no daemon credential when the daemon names a different store, including a daemon that binds\nafter start; it keeps running and serving its own agents, so one space can carry a manager on more\nthan one workspace root. That manager also stays off the space's renewal lease, so a manager or a\n`cotal doctor auth --fix` on the daemon's store can still take it. Pointing several managers at one coordinate is safe: the store identity\nalone cannot pick an owner (it carries no holder and no tiebreak, so every manager sharing the store\nmatches), so the manager that also holds the space's renewal lease is the one that remints and the\nrest skip it. Without that lease two owners would remint on independent timers with no ordering\nbetween them, and one write would land between the other's re-sign and its fingerprint-only\n`reloadCreds`. `cotal doctor auth --fix` takes the same lease before it re-signs, so a live manager\nand a local repair never race each other either. The signer IS now injectable: a hosted composition injects a KMS/Vault store and no\nsigning seed lands on the hosted disk. What remains is signer **isolation**. The seed is decrypted\nin-process at the manager's uid. That issue needs an OS sandbox or remote signer; it is no longer a\ncustody problem. The other knobs are `workspaceRoot` and the process-global `COTAL_HOME`.\n\nA store, runtime, extension or host callback the manager calls may reject with any value, including\n`null`. The manager logs or refuses with that value's `message`, or with the value itself as text\nwhen it has none, and keeps serving. A value it cannot read reports as `an unreadable rejection`.\n\n> Scope note: the **static-auth** operator paths (`cotal spawn`/`join`/`status`/`web`, via\n> `mesh-target` → `connect`/`preflight`) still read the signer from the local split records (sync\n> `loadSpaceAuth`). That is the single-machine composition, where the signer is on local disk by the\n> static-auth model; multi-tenant hosting runs **user mode**, which never mints from on-disk trust. The\n> store-injectable signer path is the hosted-server set: the manager, `remintDaemonCreds`, and delivery.\n\nThe typed remote-manager authority contract includes a one-shot terminal phase. A host implements\n`remoteAuthority.prepareAgentRetirement` to revoke the managed grant and finish its resumable\nrelease while preserving the UID, then `remoteAuthority.mintRetirementRequester` returns the\nhost-signed JWT for a fresh participant-owned nkey. The credential is pinned to the authenticated\nowner, server-derived manager serve principal, current instance epoch, and exact target lifecycle.\nThe manager then uses the existing auth `retireLifecycle` rail with the operation id derived by\n`managedRetirementOpId(target.lifecycleUid)`. This derivation is the reference remote-Manager\ncomposition's closed contract, not a rule for every retirement entry point; interactive retirement\nkeeps its existing operation identity and remains compatible. The `retireLifecycle` rail independently\nrecomputes the managed id from its broker-pinned target before any gate, head, intent, or barrier\naccess, so mint-time validation is not the terminal boundary. A failure keeps\nthe alias held. This does not expose the auth barrier or give the participant signer authority.\n\nIf the participant disappears after prepare, the host finishes the retirement itself on the auth\nservice's loopback face: `POST /managed-lifecycle/retire` (exported as `MANAGED_RETIRE_PATH` from\n`@cotal-ai/auth`) with the `Bearer <cap>` from `auth-service.json` and only\n`{ owner, actor, lifecycleUid }`. It has the interactive door's guards (POST only, no `Origin`, JSON,\ncapability, closed body) and is never served on the public face. The managed grant must already be\nrevoked at that uid, or it answers 409. It runs the same `managedRetirementOpId(uid)` operation as\nthe rail, and the rail and the door share one in-process flight, so a late participant request and\nthe host call converge on one barrier.\n\n| lifecycle head | answer |\n| --- | --- |\n| absent, or `retired` at another uid | `200 { retired: false, lifecycleUid, notStarted: true }` |\n| `active`/`retiring` at another uid | `409` |\n| `retired` at this uid | `200 { retired: true, lifecycleUid, alreadyRetired: true }` |\n| `active`/`retiring` at this uid | the barrier runs, then `200 { retired: true, lifecycleUid }` |\n\nDeprovisioning durables stays with `deprovisionAgent` and a `deprovisioner` credential. Pass `memberChannels` to both to also purge the retired lifecycle's durable membership rows on those concrete channels. The manager fills that list from the launch's concrete read channels and the delivery daemon's read-only `lifecycleMemberships` admin verb. Before it reads that verb, it calls `fenceLifecycleAcl` under a deprovisioner credential for the same lifecycle with no member channels. That narrows the lifecycle's read-ACL row to no reads, and a durable join the inventory does not see then removes its own row. When that verb cannot answer, rows on other channels stay retained, the teardown logs the inventory as incomplete, and retirement remains held pending retry rather than releasing the alias. Each teardown examines two exact consumers, one ACL key and the named member keys. KV deletion uses a native revision condition; a lost condition with a live replacement refuses rather than claiming absence. Consumer INFO checks before and after DELETE distinguish verified prior absence from disappearance. `acknowledged` counts native DELETE success replies. `disappeared` counts observed live-to-absent consumers and live KV rows whose conditional purge lost to a competing deletion. These KV rows were present at the first read, so they never count as prior `absent` or as this caller's `deleted`. The ACL and membership subtotals preserve that distinction. Neither establishes which concurrent caller uniquely removed a consumer, so `consumers.deleted` and the total `deleted` are `null` when a consumer disappears without a winner token. A repeat after verified absence reports zero, not an invented deletion. `refused` counts slots whose cleanup or state remains uncertain. A partial failure raises `DeprovisionError` carrying these bounded observations. The Manager's static sweep preserves unknown uniqueness rather than adding acknowledged requests as physical removals; its slot totals remain exact.\n\nA separate host activates one exact managed lifecycle through the same full account auth service:\n`POST /managed-lifecycle/activate` (exported as `MANAGED_ACTIVATE_PATH`) with the `Bearer <cap>` from\nthat account's `auth-service.json` and the closed body\n`{ accountPublicKey, owner, actor, lifecycleUid }`. This route is present on an ordinary separately\nhosted full auth service. It does not require `platformControl`; that option adds the equivalent\nin-process handle for a composition sharing the process. A callout-only replica has no HTTP listener\nor authority plane and cannot serve it.\n\nThe repeated account key prevents a host routing error from asking one account authority to act on\nanother account's target. It must equal the service's assigned data account before lifecycle work.\nThe route is POST-only, refuses `Origin`, requires JSON and the per-start capability, rejects unknown\nfields, and is absent from the public exchange face. Parser and authority-selection refusals state\n`outcome: \"not-executed\"`. After dispatch, the native activation code, details and outcome are\nreturned. A non-native failure reports `outcome: \"unknown\"`, never activation success.\n\nThe operation calls the authority plane's existing fence before `activateLifecycleAtUid`. Success\nreturns `{ accountPublicKey, owner, actor, lifecycleUid, activated: true }` only after the head is\nactive at that UID and its issuance gate is open. The native lifecycle contract remains unchanged:\n\n| lifecycle state | answer |\n| --- | --- |\n| absent, or `retired` at another UID | activate this UID |\n| `active` at this UID with an open gate | idempotent success |\n| `active` at another UID | `already-exists` refusal |\n| `retiring` | lifecycle-blocked `failed-precondition` |\n| this UID frozen by retirement, or terminally retired | lifecycle-blocked refusal |\n| authority fenced or unavailable | `unavailable`; no success result |\n\nA host that resumes retained managed actors also implements\n`remoteAuthority.validateRetainedAgent`. The participant sends back the actor token and sentinel it\nalready holds, plus the `nextRegistrationProof` returned by the activation response. That proof is\nhost-issued after registration and binds the manager owner, actor, lifecycle, identity nkeys, current\nregistration revision, and serving epoch. The host checks it against the current open manager gate,\nvalidates the retained secrets against its current managed row, and returns only the non-secret\nauthority shape. The manager binds every result coordinate and the returned authority back to its\ninventory before use. Do not copy the provider's `issuer.json` or `callout.json` into the participant\nstore. Both contain private signing or exchange authority.\n\nThe same composition supplies `remoteAuthority.agentBearerExchangeUrl`, the pinned public auth-service\nbase used by retained children. Remote adoption launches `agent-bearer --exchange-url <base>`; it must\nnot select the local `--dir` arm, which depends on a host-only auth-service process record.\n\nA host that lets a remote participant spawn FRESH managed agents implements\n`remoteAuthority.enrollManagedAgent`. The participant generates the standing actor token, writes it\nat mode 0600, and passes only its SHA-256 digest with the requested actor, label, role,\ncapabilities, and channel lists, so the plaintext secret never leaves the participant machine. There\nis deliberately no `lifecycleUid` input: the host selects the UID, because only the host sees the\nretirement tombstones that make a UID permanently unusable, and a participant-chosen UID could aim a\nfresh grant at a dead incarnation. The host authors the ledger grant, pre-creates the lifecycle-keyed\ndurables, clamps the requested lists to what the spawning owner already holds, and returns the owner,\nactor, chosen `lifecycleUid`, the space sentinel credentials, the effective lists, and\n`agentBearerExchangeUrl`. The manager binds every returned coordinate, re-keys the secret family onto\nthe returned UID, and launches `agent-bearer --exchange-url <base>`. When the hook is absent a\nsignerless manager refuses the user-mode spawn rather than authoring a local grant the host knows\nnothing about.\n\nBoth managed-agent operations ride the one verified `POST /manager-service-authority` transport as\n`kind: \"manager-managed-agent-enrollment\"` and `kind: \"manager-managed-agent-prepare-retirement\"`.\nStock `cotal auth-service` answers both itself, because it owns the actor ledger and the space's\nprovisioning authority. An enrollment writes the managed grant at a fresh UID with the supervising\nactor as its parent, provisions that UID's durables, and returns the daemon's public exchange URL as\n`agentBearerExchangeUrl`; a daemon started without `--exchange-public-port` refuses enrollment. A\nretry with the same token digest answers the same UID while the supervising actor's current grant\ncovers it, and a fresh enrollment's refusal otherwise. While the agent's grant stands, an enrollment\nwith another digest is refused with `conflict` until that lifecycle's retirement is prepared. A\nprepare-retirement releases the target UID's broker footprint and then revokes its grant, so the\nmanager's terminal rail finds the grant gone. A platform that keeps these writers in its own storage\nintercepts both kinds instead. It terminates its own public route, authenticates the human there,\nand asks the auth service for the decision at\n`POST /manager-service-authority/verify-enrollment` (exported as `VERIFY_ENROLLMENT_PATH` from\n`@cotal-ai/auth`) with the `Bearer <cap>` from `auth-service.json` and only `{ owner, request }`. That\ndoor has the managed retirement door's guards, derives the caller's scope from the local ledger rather\nthan the body, checks the manager gate and registration proof in-process, and answers\n`{ authorized: true, owner, actor, instanceId, serveEpoch }`. `authorizeRemoteManagedAgentEnrollment`\nand `authorizeRemoteManagedAgentPrepareRetirement` are exported too, for a host that composes the\ndecision without the HTTP hop. Both require ledger scope `supervise`; `spawn` and `admin` do not\nimply it.\n\nA host that runs managed agents on its own hosted runtime adds two more kinds on the same transport.\n`kind: \"manager-managed-agent-runtime-create\"` asks the host to create the runtime for one agent it\nalready enrolled, and `kind: \"manager-managed-agent-runtime-status\"` reads that runtime's state. Both\ncarry the manager envelope plus `target: { owner, actor, lifecycleUid }`, the coordinate the\nenrollment returned. Both schemas are closed. An unknown top-level or target field, including\n`providerRef`, `handle`, or `name`, is refused as `bad-request`, because the host alone issues and\nholds provider references. There is no stop, adopt, or probe kind: stop goes through\nprepare-retirement. Stock dispatch refuses both kinds with `unimplemented`, and the verify-enrollment\ndoor decides them. `authorizeRemoteManagedAgentRuntimeCreate` and\n`authorizeRemoteManagedAgentRuntimeStatus` apply the enrollment door's checks: host space, a target\nowner equal to the authenticated owner, the manager actor's own ledger row with `supervise`, the open\ngate, the current serve epoch, and the registration proof. Each returns only\n`{ owner, instanceId, actor, target }`. The door touches no provider and writes nothing. The host\nmatches the decision to its own intent record and performs the create afterwards. The host answers\nwith `state` (`reserved`, `creating`, `bound`, `create-unknown`, `closing`, or `closed`), `readiness`\n(`ready`, `bound-not-ready`, or `none`), and an optional `retirementPhase`. A manager builds requests\nwith `remoteManagerClient.remoteManagedAgentRuntimeRequest` and binds the answer with\n`remoteManagedAgentRuntimeState`.\n\nAn enrollment result may also carry `runtimeIntent: { state: \"reserved\" }` when the host reserved a\nhosted runtime for the agent. It is display-only. Older hosts omit it, the manager binds both shapes\nto the same material, and nothing reads it as authority.\n\nNo stock door lets a platform control holder launch or retire an agent for a signed-in user. The\nmanaged-agent kinds above act only under the authenticated owner and refuse a caller that is not\nthat user, so a platform could only run a user's agent by holding the user's login or by enrolling\nthe agent under its own owner. Both are refused. The\n[delegated user launch intent](design/delegated-user-launch-intent.md)\ndesign and SPEC §13.16 define the smallest addition. The user admits one launch or one retirement\non the host's authenticated route. The holder consumes that intent once, from its current\nregistration, epoch and lifecycle. The host then enrolls the agent under the user's `u_` owner with\nthe user's own actor as its ledger parent, so the envelope walk, membership and channel lists match\nwhat the user's own manager would produce. Retirement keeps the prepare, provider closure and\nterminal barrier order, and the host finishes it when the holder is gone. A launch the host had to\nundo keeps its agent name held until the host process that ran it confirms it has stopped, and\nwhile the name is held the host also refuses it to the user's own manager. `@cotal-ai/auth` ships the\ntwo decisions, `authorizeDelegatedUserIntentAdmission` and `authorizeDelegatedUserIntentExecution`,\nfor a host that owns an intent store and those writers to compose on its own routes. Both read the\nholder's gate through the handle's `observeManagerGate`, present with `platformControl`, which reads\nover the context's own connection, so the host opens no second data-account connection. It is an\nobservation for the decision: the consuming CAS and the writers still apply their own checks. The\nconsuming CAS pins the incarnation of the host process that runs the flight as the executor, never\nthe auth plane's, because the two can restart independently. `platformControl.host` names that\nprocess's reverse-DNS endpoint, the closure digest of its §13.7 cluster and the contract artifacts\nregistration reads, and the auth plane self-authorizes that one name. Registration reads the closure\nmanifest `{ v: 1, root, members }` at `clusterDigest`, then the cluster document at the manifest's\n`root`, and verifies each against its digest. `artifacts` therefore carries both, and `clusterDigest`\nis the digest of the manifest. `members` stays empty: SPEC §13.7 lists every reachable artifact\nthere, but this implementation registers single-document clusters only and refuses a manifest that\nlists members. A manifest with any field beyond `v`, `root` and `members` is refused too, as the\ncontract store refuses it. `singleDocumentClosure(document)` returns that manifest and its closure\ndigest. The instance id is a lifecycle token, `[a-z0-9]{26,32}`. The minimal construction below has\none command over the void schema. A host copies it, replaces `document` with its real cluster, and\npasses `host` as `platformControl: { observeAssignment, host }`.\n\n```ts\nimport { mintLifecycleUid, singleDocumentClosure, VOID_SCHEMA_DIGEST } from \"@cotal-ai/core\";\n\nconst document = {\n urn: \"com.example.host\",\n revision: 1,\n attributes: [],\n events: [],\n commands: [{\n name: \"ping\", class: \"ephemeral\", targeted: false, capability: \"host.ping\",\n inputDigest: VOID_SCHEMA_DIGEST, outputDigest: VOID_SCHEMA_DIGEST,\n }],\n};\nconst { manifest, closureDigest } = singleDocumentClosure(document);\nconst host = { endpoint: \"com.example.host\", clusterDigest: closureDigest, artifacts: [document, manifest] };\nconst instanceId = mintLifecycleUid(); // first start only; later starts reuse the persisted id\n```\n\n`registerHostIncarnation(instanceId)` publishes the artifacts, registers that instance through the\nceremony the plane runs for itself, and returns `{ instanceId, processEpoch }` with the epoch that\nregistration committed. The host calls it at every start with its persisted instance id, before it\nadmits or recovers any flight, so a restart fences its predecessor. The first registration of an\ninstance commits epoch 0, which is open and serving like any later epoch, and each later start of\nthat instance commits the previous epoch plus one. A consumer compares epochs for equality and never\nreads 0 as absent or not ready. A start\nwhose confirming read of the gate finds that a later start of the same instance registered is\nrefused with `conflict`. The returned epoch is a committed coordinate and stays current only until\nthe next start registers, which can happen before the call returns. `observeHostGate(instanceId)`\nis a point-in-time read of an executor's gate, and answers null for an absent gate; a sweeper\ndecides on it. `awaitHostFence(instanceId, processEpoch)` resolves with the gate once it is no\nlonger open at that epoch, and with null once it is absent. It takes any non-negative safe integer\nepoch, 0 included, and refuses any other value with `bad-request`. The host arms it with its returned\nincarnation before it admits or recovers any flight, and stops serving when it resolves. It polls\nthe gate, because no runtime credential may watch the auth bucket. The\nhost's launch writer first activates the agent's lifecycle at the pinned UID through the handle's\n`activateManagedLifecycle`, before any ledger row or durable, and its compensation runs the same\ncall before the terminal barrier, so a launch whose agent never exchanged its bearer still reaches\nthe terminal barrier at that UID. The launched agent exchanges its bearer on the context's public\nface, so the host starts it with `publicFace`, and its retirement writer ends at\n`POST /managed-lifecycle/retire` with the handle's `cap`. Stock dispatch refuses both kinds as\n`unimplemented`. The holder's composition passes\n`remoteAuthority.executeDelegatedUserIntent`, which posts the execution request and binds the answer\nwith `parseRemoteDelegatedUserIntentExecutionResult`. It then starts the agent with\n`startAgent({ ..., delegatedIntent: { intentId, owner, parent } })` and retires it with\n`retireDelegatedAgent(name, intentId)`, which stops the agent and removes its local secret family\nonly after the host confirms `retired: true` for its exact target. A delegated agent's stop, exit or\nfailed launch keeps its name held until that retirement confirms, and a secret file the retirement\nfails to remove keeps it held too.\n\nRemote user-mode managers must also supply `remoteAuthority.authorizeAdmin`. The manager builds each\nrequest only from the caller tuple parsed from the broker-authenticated endpoint subject, then relays\nthat tuple over the current registered manager lifecycle. HTTPS does not separately authenticate the\nrelayed caller. The host authenticates the manager operator, binds the request to the current open\nmanager gate, registration proof, serving epoch, and identity nkeys, then reads the caller's unified\nauthoritative row fresh. It returns only the manager owner and `authorized: boolean`, with every request\ncoordinate echoed. Missing, revoked, narrowed, foreign-owner, and stale-lifecycle callers all return\n`false`; malformed coordinates or corrupt and unavailable authority state fail the operation. The\nparticipant never reads or mirrors the host ledger, and the remote branch has no local fallback. The\nsame callback gates all `manager.admin` handlers, any-mode cross-owner control, and `ps` or `inspect`\ncross-owner visibility. Launch keeps its owner-equality policy.\n\nThe remote authority's instance executor remains the scoped maintenance credential for clean service\nderegistration and exact instance registration operations. It carries no records-stream consumer\nlifecycle authority. The manager's boot `goalidx` sweep uses the authenticated host operation, which\nreturns parsed `goalidx.manager.<owner>.>` entries for that owner only. The host keeps the sealed\nconsumer connection and its create/delete rights. The five-minute executor already renews through\n`remoteAuthority.renewExecutor`. The signerless supervisor, serve, goal-writer, session-ledger and\nper-run driver credentials do not yet have a complete remote renewal and adoption path. The\n[hosted runtime contract](design/hosted-runtime-contracts.md) records the bounded additions and\ntheir ownership; it is not a shipped pooled service.\n\n**Signer isolation needs an OS sandbox.** The default pty runtime\nruns agent children under the *same* OS uid and the *same* `workspaceRoot`, so mode-0600 on\nthe trust records does not stop a hostile same-uid agent from reading their absolute paths. The reference\n[deploy](deploy.md) tree does not solve this: it mounts the signer into the agent's own container, so\nits phase-1 boundary isolates agents from each other, not the signer from the agent. A hosted\ncomposition must run the manager/minter that holds the signer in a different uid, container, or mount\nnamespace from the agent children, which mount no signer at all; that split is future\nhosted-composition work, so until it (or a remote/injected minter) exists, do not run untrusted\nagents under this manager.\n\n### Delegated seats outside the manager's filesystem\n\nThe [portable lifecycle bootstrap](design/portable-lifecycle-bootstrap.md)\ndesign and SPEC §13.17 define how a managed agent that `enrollManagedAgent` already enrolled starts\nin a child that cannot see the manager's filesystem. The ordinary `spawn` path writes the token and\nsentinel under the manager's workspace root and hands the runtime a launch whose bearer command and\nmaterial file are paths on that filesystem, so such a child needs this path instead.\n\nThe delegation boundary is one optional runtime method. A runtime that implements\n`Runtime.spawnDelegated(launch, handoff)` receives two values and no paths: a `DelegatedSeatLaunch`\n(connector name, persona text, `managerInstanceId`, model and the other launch choices) and a `ManagedLifecycleHandoff`\n(space, owner, actor, the host-chosen `lifecycleUid`, broker and IdP pins, the pinned exchange base,\nthe sentinel, the channel lists, and the raw actor token). The manager enrolls once, as it does\ntoday, and builds the handoff from what it holds. It never sends the token to the host, never copies\na file from its workspace or secret store, and never builds a local launch for that seat. No signer,\nissuer or callout record, loopback capability, provisioner or manager credential, control token, or\nmanager path crosses. A spawn choice that only the manager's host can honour is refused before\nenrollment: `--resume`, a manifest agent's `continuity: exact`, `--cwd`, and any shared MCP server,\nwhether from `--share-tools` or the config default (`--share-tools none` passes).\n\nA delegated manager also refuses a caller-supplied persona `config` override in `resolve-agent`,\n`spawn` and direct `Manager.startAgent` calls. The shared persona resolver refuses before checking\nor reading that path, with `failed-precondition` on the wire and one fixed execution-mode message.\nPass a named catalog persona instead. This does not change locally executing managers. A resolved\nmanifest can still use its own validated, host-materialized persona resource. The wire schemas\naccept no internal `resolved` field that could bypass the config refusal.\n\nThe runtime creates one provider resource under `managedRuntimeKey(target)`, writes the handoff into\nit as one 0600 file and the persona beside it, and runs the stock bootstrap there:\n`cotal spawn --config <persona-file> --space <space> --name <actor> --expect-owner <owner> --expect-lifecycle-uid <uid>`\nwith `COTAL_MANAGED_HANDOFF_FILE` naming the file and `COTAL_MANAGER_INSTANCE` naming the launching\nmanager. `delegatedSeatCommand` builds that argv and `env`.\n`cotal spawn` reads the file into memory, deletes it and drops the variable before it parses flags,\nprints help or loads extensions, so every outcome, a refusal of its own flags included, leaves no\nfile. It refuses before any broker connection or exchange request when `COTAL_MANAGER_INSTANCE` is absent (`COTAL_MANAGED_HANDOFF_FILE requires COTAL_MANAGER_INSTANCE`; `DelegatedSeatLaunch.managerInstanceId` is required and a newer CLI child under an older manager or runtime refuses every delegated launch, so managers and the CLI must be upgraded together) or malformed, or when the\nspace, owner, actor, or lifecycle UID differ from the expected values, and then runs the\nenrollment-redeem consumer: it registers the mesh in its own home, writes the token to its own 0600\nfile, and exchanges it through `agent-bearer --exchange-url` unchanged. It never enrolls, redeems, or\nmints a token or UID.\n\nReadiness is still mesh presence. A create whose answer is lost leaves the handle running, so the\nlaunch settles uncertain and stays held; the manager never retries it. A provider read that finds no\nresource under the key is not an exit, because the create may still land. Every close by\n`managedRuntimeKey` is fenced: it completes only once the create was answered or the provider refuses\nany later create under the key. A provider that names its own resources may run the create as a\ndurable operation keyed by `managedRuntimeKey` and close through the identifier its authenticated\ncreate response returned, kept where the host can read it without the manager. Only that response\nbinds an identifier to the key; one derived from the key or found by name or listing is never closed\nor adopted, and while the response is unknown the launch stays held. Every stop, the reap of a child\nwhose parent exited and `Manager.stop({ withAgents: true })` included, runs `prepareAgentRetirement`\nfor the UID-exact target, then `stop()` on the handle `spawnDelegated` returned, then the terminal\nbarrier. `preparePreservation` refuses a cut that holds a delegated seat, and a `Manager.stop()` after\na refused cut retires the seat through the same steps. After the manager is gone\nthe host runs the same steps, makes the same fenced close by `managedRuntimeKey`, and finishes at\n`MANAGED_RETIRE_PATH`. Supply `spawnDelegated` only from a runtime whose host can make that fenced\nclose without the manager. The enrollment redeem\n(`COTAL_ENROLLMENT_FILE`) stays for lifecycles whose token the host generated itself; a host cannot\nmint one for a manager-enrolled lifecycle because it holds only the digest.\n\n### Delegated recovery contracts\n\nCore exports `RemoteDelegatedRecoveryRequest`, `RemoteDelegatedRecoveryResult`,\n`RemoteDelegatedRecoveryLaunchRequest`, their closed parsers, and\n`parseDelegatedRecoveryDescriptor`. `Runtime.rebindDelegated` describes an optional same-child\nrebind. These are contracts for SPEC §13.18, not an enabled recovery path. The current Manager\ndoes not call the new method or reconstruct delegated rows. Its public `adoptRuntimeHandle`\nreturns a native handle without inserting a managed row.\n\nA supporting host retains the descriptor in the original user-intent consuming CAS, binds each\nclaim to the original instance and current registration, and supplies complete fenced scans.\nThe manager needs its original persistent secret store and a runtime that can verify the same\nchild execution after process loss. It must retain held aliases before reconciling accepted goals.\nMissing storage or unverified child identity keeps recovery held; neither permits another launch.\nThe request parsers validate data, not fresh host authority or durable transactions. Existing\nhosts continue to refuse the opt-in launch extension rather than silently ignore it.\n\n## Provisioning a space (one-space reference shape)\n\n```ts\nimport { createSpaceAuth, setupSpaceStreams, ensureDefaultDeliveryClass, mintCreds, newIdentity } from \"@cotal-ai/core\";\nconst auth = await createSpaceAuth(space); // trust bundle (in-memory seeds)\nconst provisionerCreds = await mintCreds(auth, newIdentity(), \"provisioner\");\nawait setupSpaceStreams({ servers: brokerUrl, space, creds: provisionerCreds });\n// SPEC section 4: write the default delivery class at space creation so it is wire-discoverable,\n// never inferred from the resolution fallback. A daemon-backed space is \"durable\".\nawait ensureDefaultDeliveryClass({ servers: brokerUrl, space, creds: provisionerCreds, deliveryClass: \"durable\" });\nconst deliveryCreds = await mintCreds(auth, newIdentity(), \"delivery\");\n// put deliveryCreds into your SecretStore under deliveryCredsKey(space, { injected: true })\n// (@cotal-ai/workspace) before booting delivery — the key is per-space, not the bare kind.\n```\n\nRendering the broker config for a user-auth space is `serverConfig(broker, spaces, { storeDir,\nmaxFileStore?, extraAccounts })`, where `extraAccounts` must include the callout account from\n`createCalloutAuth` so the auth-service has a broker account to answer on. That account never shares\nthe data account. `maxFileStore` is an optional positive integer byte cap; any other value throws.\n\nBroker trust and space accounts are separate authorities: `createBrokerAuth` mints the one\noperator + system account a broker trusts, `createSpaceAccountAuth(broker, space)` signs each\ntenant's data account under it, and `serverConfig(broker, spaces, opts)` renders them all into one\nconfig. A host composition can therefore provision several spaces on one broker today. `cotal up`\nrenders that config from every tenant the root's auth directory holds, so booting one space keeps\nthe broker trusting its siblings, and it refuses to render at all while any account record is\nunreadable. The rest of the CLI lifecycle is still broker-wide: `down`, `clean` and `backup` refuse\non a multi-space root rather than scoping to one tenant, and the per-space lifecycle is the\nremaining multi-space operator layer. See\n[Known gaps](#hosted-composition-gaps).\n\n## Issued-authority stores from before 0.111.0\n\nA space whose `KV_cotal_issued_<space>` and `KV_cotal_accepted_<space>` were created before\n0.111.0 is refused by every issuer and resolver that binds them. `cotal up\n--recreate-issued-stores` fixes the spaces `cotal up` starts. For a space your own composition\nprovisions, stop its issuers and resolvers (auth service, callout replicas, managers) and run the\nsame step yourself:\n\n```ts\nimport { connect } from \"@nats-io/transport-node\";\nimport { mintCreds, newIdentity, removeIssuedStoresBeforeRetention, setupSpaceStreams, standaloneConnectOpts } from \"@cotal-ai/core\";\nconst identity = newIdentity();\nconst inboxPrefix = `_INBOX_${identity.id}`; // the one inbox the credential may receive on\nconst creds = await mintCreds(auth, identity, \"issued-store-recreate\"); // one-shot, 30 minutes\nconst nc = await connect({ servers: brokerUrl, ...standaloneConnectOpts({ creds, tls: false }), inboxPrefix });\ntry {\n // backupDir must not exist yet; it is created 0700 with a `nats stream backup` layout per stream\n await removeIssuedStoresBeforeRetention(nc, { space, backupDir, inboxPrefix });\n} finally { await nc.drain(); }\nawait setupSpaceStreams({ servers: brokerUrl, space, creds: provisionerCreds }); // creates both again\n```\n\nThe credential can read, snapshot and delete those two streams and nothing else. The step backs\nup every store that predates bounded retention, checks each backup against its stream's message\ncount and last sequence, and deletes nothing unless every check passes. It throws\n`IssuedStoreRecreateRefusal` before writing anything when neither store predates bounded\nretention. The order, the refusals and what a rollback can do are in\n[Upgrading](UPGRADING.md#issued-authority-stores-after-01110).\n\n## Hazardous provisioning primitives\n\n`mintCreds`, the full `Profile`/`CredentialKind` matrix, `createSpaceAuth`, and `stripSpaceAuth` are\nlow-level operator primitives. Handle them as account-authority material:\n\n- A holder of a `SpaceAuth` (or a `stripSpaceAuth` bundle, which **keeps** the data signing seed) is\n a fully-trusted tenant-account authority: it can mint `admin`, `provisioner`, and destructive\n profiles, not merely `supervisor`, and mint a DM-reading identity. `createSpaceAuth`'s full result\n holds operator, system, and account seeds in memory.\n- Choose `profile` and `MintOpts` from **server-side constants**, never from tenant input. `MintOpts`\n can widen the bounded TTL defaults; cap it at your boundary. `CREDENTIAL_LIFETIMES` is a policy\n record, not an authorization boundary.\n- Never log signer material or export it into env. Do not co-locate signer access with an untrusted\n connector/runtime process at the same OS uid (file permissions do not contain a same-uid reader;\n see the manager's isolation note). Segregate per tenant; rotate on compromise\n (`rotateDataAccountSigningKey`).\n\n## Hosted composition gaps\n\nThree composition limits remain. A host must supply the missing isolation or integration,\nor leave the affected capability unavailable.\n\nMembership and live eviction already read their credentials through `SecretStore`.\n`startMembership` reads the data-account writer and system-account observer there; eviction\nreads the observer and evictor pair on each operation. Both use per-space keys and check\nthat the observer names the daemon's account. The feed derives that account from the\ndaemon's credential, without `membership.json`. The host still owns provisioning and\nrotation. An absent observer leaves the feed traffic-only; missing eviction authority\nrefuses eviction. The membership reader can adopt a host-renewed observer with the same\nissuer and scope at 75% of its lifetime.\n\n1. **Supervisor signer isolation.** `ManagerOptions.secretStore` now injects the one `SecretStore` the\n manager reads/writes every secret through, including the composed `SpaceAuth`\n signer (the split trust records), its daemon-cred renewal, and its per-agent kinds. What remains is process\n isolation: the manager still decrypts the signer in-process at its uid, so untrusted agent children\n must run under a different uid/container/mount namespace or behind a future remote signer.\n2. **Per-space lifecycle on a shared broker.** The trust layer is multi-space\n (`createBrokerAuth` + `createSpaceAccountAuth` + N-space `serverConfig`, persisted as\n `broker.json` + `account.<key>.json`) and `cotal up` renders the whole tenant list. The CLI\n still lacks tenant-account provisioning and per-space teardown/backup/restore on that\n broker. Its broker-wide lifecycle verbs refuse on a multi-space root, naming the tenants.\n The existing `cotal space add` registers a connection, and `space delete` removes a\n space's streams; neither supplies that tenant-account lifecycle.\n3. **A non-Better-Auth production IdP.** The exchange core (`createIdpBridge`) is EdDSA-generic, but\n the stock provider and login client are Better-Auth-endpoint-shaped, `cotalAuthProvider`\n self-registers on import (colliding with a host-owned provider under `resolveAuthProvider`), and\n the login flow speaks Better Auth's device-code endpoints. A different IdP is a host-built auth\n composition on the low-level primitives, not a configuration change (see\n [the IdP callout contract](identity-and-auth.md#the-idp-callout-contract)).\n\n## Hosted durability\n\nSpace-durable **coordination** state (chat/DM/task history, live presence, membership runtime, the\ndurable ACL registry, leases) lives in **JetStream**, written by the delivery daemon and the\nendpoints. It is broker-resident and needs no host-side durable path.\n\nWhat is **not** in JetStream, and is hosting-critical, is trust and authorization state a host must\nplace and keep:\n\n| state | class | where today | hosted injection |\n|---|---|---|---|\n| full `SpaceAuth` trust chain (`auth/broker.json` + `auth/account.<key>.json`, composed; a stripped signer bundle may instead be mounted at the legacy `auth/auth.json` key) | signing authority | `SecretStore` | `SecretStore` (manager + renewal) |\n| auth kinds: callout account/creds/xkey, issuer private keys, owner-derivation secret, data-signer projection | signing/identity authority | four `SecretStore` kinds | `SecretStore` (auth-service) |\n| auth plane instance identity (instance id + serve nkey seed) | restart identity | root `.cotal/space.<hex>/auth-instance.json` | `SecretStore` (`startAuthService`) |\n| `delivery.creds` | standing scoped cred | `SecretStore` or `--creds` | `SecretStore` (delivery) |\n| actor ledger, IdP pin | authorization + trust config | ambient `userAuthStateDir(findCotalRoot(), space)` | none (root-relative; not `store`/`COTAL_HOME`) |\n| `membership-rw.creds` | standing scoped cred | `SecretStore` | `SecretStore` (delivery + manager renewal) |\n| membership-observer / connection-evictor creds | scoped $SYS creds | per-space `SecretStore` keys | injected `SecretStore`; account identity is checked against the daemon credential, not `membership.json` |\n| manager agent creds, actor tokens, sentinel creds | lifecycle authority | `SecretStore` | `SecretStore` (manager `secretStore`) |\n| `~/.cotal/meshes/space.<key>.json` record (holds IdP trust pins/root pointers) | non-secret, integrity-critical | machine home | process-global `COTAL_HOME` only |\n| auth-health, renewal records | non-secret diagnostics | workspace filesystem | `workspaceRoot` |\n\nThe `SpaceAuth` trust chain and the auth-service store kinds are **separate** identities/projections,\nnever parts of one document. `auth-service.json` (the live exchange capability) is ephemeral runtime\nstate, not durable, but is sensitive while the daemon runs. `@cotal-ai/workspace` is machine-local\noperator tooling by design; personas, PID files, and the `current-mesh` pointer are truly local and\nmust **not** sit on a hosted durable path. Everything classed above as an authority is what a hosted\ncomposition must provision and persist: signer-bearing server secrets now have `SecretStore` seams;\nthe remaining non-injectable rows are the explicit ambient `workspaceRoot`/cwd paths above.\n\n## See also\n\n- [Substrate stability](stability.md): what v0.3 and the 0.x packages guarantee, and the projected v0.4 break.\n- [Identity and auth](identity-and-auth.md): the profile matrix, the signer, and the IdP callout contract.\n- [Delivery daemon](delivery-daemon.md): the Plane-3 durable backstop.\n- [Deploy](deploy.md): the reference container against an external broker.\n\n## Hosted run revocation\n\nThe authenticated manager-service authority door accepts `manager-run-revoke` with the registered\nmanager envelope and `revoke: { runId, reason }`. The issuing host reads the admission's recorded\nowner and requires the verified requester to be that owner or to hold `admin` in its fresh actor\nledger row. It verifies the current manager registration proof, space, account and epoch. It accepts\nno owner or attribution from the body.\n\n`AuthAuthorityPlane.revokeManagerRun` implements the operation. `AuthProvider.requestRemoteRunRevoke`\ntransports it, and `remoteManagerClient.remoteRunHosting` supplies `RunHostingContext.revokeRun` for a signerless\nmanager. The callback returns the stored `RunRevocation`, including on repeats. A host composing\nits own remote authority must supply that callback to revoke. No signer reaches the participant.\nCLI and MCP revoke verbs are a follow-up described in the [run-start design](design/user-auth-run-start.md).\n\n### Private tool-result prerequisites (not serving)\n\n`@cotal-ai/auth` exports `createToolResultRevocationCustody`,\n`recordToolResultRevocation`, `snapshotToolResultRevocations` and one-shot\n`consumeToolResultSnapshot`. These are host-only prerequisites, not material issuance,\nservice registration or a browser/private-result path. `requireToolResultClockPrerequisite`\nalways refuses `unavailable`: no native runtime clock-domain/generation/suspension proof\nexists, and no numeric delta is invented.\n\nCustody exclusively creates a **fresh** auth store after a private fsynced intent/generation.\nExisting stores or journals are never adopted. Only a standalone broker and owner-private local ext4 journal parent are supported. Only the creating process may use its sealed,\nnon-reconnecting reader/writer custody. Unknown writes, missing/changed journals, stream\nidentity/configuration drift or connection loss invalidate it. Crash/rebind recovery stays\nunavailable. Routine broker restart, upgrade, network loss or process restart therefore leaves\ngate 1 permanently unavailable for that space. Recognize this as `revocation custody lost; no reopen from current INFO`.\nNo retirement/reprovision recovery protocol exists in this increment. Gate 2 cannot assume\ncustody survives broker maintenance. The trusted composition supplies current authenticated consent/target authorizers\nand exclusively holds account/provisioning keys. Independently running privileged provisioners,\nuncontrolled legacy writers and existing roots have no qualified custody and are unsupported.\nThis is not protection from a malicious host administrator or copied signing keys.\nThe separate internal custody profile uses two non-expiring, non-reconnecting credentials,\nwithout planeCandidate or a renewal timer. With the two sealed scanners this is four standing\nconnections across three profiles. The CREATE provisioner still expires and closes after CREATE.\nA leaked custody JWT plus user seed no longer has a 900-second expiry bound. Stopping the\nservice closes its own sockets, not copied credentials. Signing-key removal invalidates copied\ncredentials as well. This remains inside the trusted-process/account-signer residual.\n\nRevocation creates only `revocation.<targetDigest>.<consentId>` with native expected-last-subject\nsequence zero, no operation/TTL headers and independently fsynced acknowledgement receipts.\nConsent bytes must match the recorded target and expiry. Persistence uncertainty reports effect\noutcome `unknown`. Acknowledged writes report `executed` even if receipt or later custody checks\nfail. Refusals before publication report `not-executed`. No automatic repeat follows uncertainty.\nMarkers persist indefinitely in this\nslice. A separate bounded-retention successor must prove consent expiry plus\n`EP_AUTH_MARKER_TTL_MS` and snapshot safety before a pruner/TTL may exist.\n\nA snapshot fixes T0 before IO and a leader W once, walks only through W, bounds count/bytes/time,\nand compares exact native sequence/subject/payload evidence to custody receipts. The committed-W\nartifact is a process-private invocation seal binding that evidence, account, generation and\nnative created/config identity. It cannot be parsed, copied, reused or used after custody loss.\nNo current INFO equality or operator safe flag establishes historical integrity. Journals are\nexclusive 0600 files with file and directory fsync, checked before/after IO, not adopted on restart.\nClustered brokers and leader failover are unsupported. Any connection loss refuses; current INFO cannot restore custody.\n\nA short-lived create-only provisioner holds API discovery and exact auth-stream CREATE, then closes.\nSeparate package-internal grants split revocation-only publish from INFO/MSG.GET reader authority.\nRetained issuance writers **already can enumerate** auth metadata. Raw ACLs cannot enforce CAS,\nDEL/TTL/schema/target conventions. Every raw MSG.GET profile carries SPEC13.9's caller-selected\nreply **foreign-subject response-injection** residual, even with only its own inbox subscription.\nRoutine PR CI runs `smoke:tool-result-prerequisites`: bounded fixtures, broker-observed\nnon-expiring exact grants, a no-renewal timer probe, census and actual KICK/key-removal\nrefusals. It does not wait for credential expiry and is not serving acceptance.\n`pnpm smoke:tool-result-custody-lifetime` additionally waits `AUTHORITY_CLIENT_TTL_SEC + 15`\nseconds and checks unchanged identities plus record/snapshot success. Run it explicitly or\nthrough the manual/weekly Custody lifetime workflow. Historical lifetime receipts remain\nsource-pinned evidence, not a grade for a composed successor.\n\n\n## Native service custody guards\n\nOrdinary lifecycle executors refuse a UID reservation carrying `kind: \"native-service-uid\"`.\nThe reservation has closed `native`, `assignment` and `creation` objects. It is not an ordinary\n`{ owner, actor, mintedBy }` audit, and a reader must not project it into one. Its assignment\nbinds the full account, space, owner, endpoint, instance and serve-duty tuple. The actor is derived\nfrom that tuple, and the creation operation and request digest remain fixed.\n\nThese guards run before ordinary root reuse, activation, gate and head changes, mint finalization,\nand native retirement. Ordinary connect and currency reads also refuse service custody, including\nrows whose head or credential mirror is missing. Existing ordinary reservation bytes are unchanged.\nClosed head, gate and credential parsers continue to reject service markers. Without\n`serviceEndpoints`, no product path writes a service reservation or mints a marked root. The service\naccess-view contract and the sealed native access/callout composition are shipped; only a context\nopened with `serviceEndpoints` composes them, with the service host's approval and registration\ndescribed below. Lifecycle retirement and restore remain unwired.\n\nThe package-internal service prerequisite reader is separate from ordinary connect and lifecycle\ncurrency readers. It leader-reads immutable UID custody, the exact active service head, native\n`gate.<uid>` open at generation1, and the exact active root credential. All three custody mirrors\nmust match the full reservation digest. Service head `managerInstance` equals immutable assignment\n`instanceId`, and native `processEpoch` is fixed at1. These are not ordinary enrollment coordinates\nor the separate endpoint gate/witness registration epochs. Creating/cancelling heads and their\nRootPlan recovery obligations remain outside this read-only active path. Missing or malformed\nnative gate evidence cannot be replaced by an endpoint gate. This is no writer, bootstrap, root\nmint/abort, rotation, cancellation or terminal-retirement authority, and not an atomic multi-key\nsnapshot. Positive fixtures raw-seed synthetic marked records, not production service admission.\nThe account is trusted host configuration. Sealed readers do not attest the broker account or\ndetect a cross-account pair of legitimately constructed handles. The authority plane constructs the\nservice callout's registry, reader and contract reads from its own data account.\n\nA package-internal custody writer is not exported; in the product only the service endpoint host's\ndecide and revoke reach it, and the proposals they act on come only from the owner-proved public\nauthority route of a context opened with `serviceEndpoints`. Bootstrap\nwrites the reservation, the pending-root endpoint gate, a creating head, a frozen activation native\ngate opened at generation1, a RootPlan fixed once by head CAS, the planned active root, an\nidentical-bytes native gate touch and the active head stamp. It rechecks the endpoint gate at open\nand before the plan, root and stamp writes. Cancellation denies the endpoint gate first, then\nwrites the cancelling head and freezes the native gate under the cancel operation. An unstamped\nplanned root is fenced by a create of revoked bytes or by CAS of the exact active row. A stamped\nroot is retained, and every cancellation result is nonterminal. An absent reservation leaves\nendpoint deny residue and reports unconfirmed; a foreign or deleted reservation refuses without a\nwrite. Each write is a per-key create or revision CAS under a sealed host whose genuine plane-claim\nhold is re-read before and after the write, plus a fatal latch. That is local readiness control,\nnot broker writer exclusion, so a paused writer can still land one late conditional write. Each\nrequest is bounded by the remaining original deadline. In bootstrap, once the plan step has fixed\nor read the RootPlan, requests are also bounded by its expiry. Cancellation keeps only its own\ndeadline, so an accepted cancellation can still proceed after the root expires. At its bound the\nwriter stops waiting for a request but does not cancel it at the broker. The writer issues every\nendpoint-gate request itself, so no endpoint-gate request starts after an invocation returns, and\nit re-reads the endpoint gate before every plan, root and stamp write attempt. Bootstrap's final\nactive-root proof is several read-only reads behind one bounded wait. If that wait ends at its\nbound, the remaining reads can still run after the invocation returns; none of them writes.\nBootstrap holds instead of reporting an active root whose expiry its final synchronous check\nobserves, with no await between that check and the return. The result can still be stale by the\ntime the caller acts on it. The caller supplies that deadline and the\nreservation; nothing here authenticates a host, approves serving, retires terminally, releases an\nalias or rotates a root.\n\nA second package-internal module builds service host operations on that writer: register\nadmission, decide (approve or refuse), revoke, a create-only name binding, and the operation and\nproposal reads. It shares the\nwriter's sealed host, plane-claim hold check and fatal latch, and each invocation opens its own\ncustody host over a per-invocation effect registry. That host writes only the invocation's scope,\nthe exact keys discovery located before the effect registry opened, and the effect registry is\nhanded the same key set so a broker grant can match it. A step that needs a key outside the scope\nholds as `scope-mismatch` before anything is issued; replaying the same request discovers what is\nstored and scopes it. Each effect registry rides its own connection, whose credential may publish\nonly on that key set's subjects (subject confinement, not operation confinement; the engine itself\nonly creates and CASes those keys), never renews or reconnects, and expires at the invocation's original deadline\nrounded up to the whole second. With agreeing clocks and timely scheduling the broker's\nwhole-second timer closes it within about 1999 ms after that deadline; that is granularity, not a\nguaranteed close time, and no close proves an earlier write cannot still settle. Losing the\nconnection fences the invocation. Discovery's credential has no write at all. The module's records and their write order are in SPEC §13.1. Results name their operation once a binding exists or may exist: `pending`, `held` and\n`refused` all carry `operationId`. A result can carry `debt`, the capacity releases its operation\nstill owed as far as that invocation observed. A result without `debt` does not mean nothing is\nowed; the operation read is the authoritative view of the debt. A `held` result by itself implies\nneither a binding nor an authorized granter: a tripped engine, or a granter without a current\ninteractive row, gets one `held` answer for a register, decide or revoke before any read of the\nrequest's keys. `denied` means the invocation wrote nothing, and either the request can never bind\nor the invocation's own read found no binding. That read is point-in-time; another invocation of the\nsame request already in flight can still bind it later. A revoke result reports `denyNew` when it\nhas evidence: an endpoint-gate read, which gives `unknown` when the read failed or found another\nassignment's gate row, or an assignment that is already fenced, which gives `landed`. The early `held` answers of a tripped engine and of a\ngranter without a current interactive row carry no `denyNew`, and a result without `denyNew` says\nnothing about deny-new. Completed results\nsay whether this invocation applied them or returned a stored record. A stored approval returns\nunchanged, and its `approvedGateRevision` is null unless its own gate CAS was observed. The index\ndoes not export this module; the typed request, result and view parsers in the service host contract\nare public.\n\n`openAuthAuthorityPlane` and `startAuthService` take `serviceEndpoints: { startup: { kind: \"normal\" } }`\nto host these operations; it is off by default. `cotal up --user-auth --service-endpoints` sets it\non the stock auth service, and a lane of `auth-service --spaces` sets it when its manifest entry has\n`\"serviceEndpoints\": true`. With it, the plane and the\nhosted handle gain `serviceEndpointHost(request)`, which answers `decide`, `revoke`, `name-bind`, the\nfour caller-policy operations and the instance, proposal, operation and name reads in process.\n`instance-read` returns the current `ServiceInstanceView` for the proved owner's selector, including\nits approval digest and registration state. `instance-list` walks the native assignment subjects with\na cursor and returns only that owner's instances. Missing and foreign selectors both read absent.\nA hosted context rejects it as\n`unavailable` while it is not ready. The host authenticates no caller: the embedder must\nauthenticate the operator or owner granter it passes. The stock service does that on\n`POST /service-endpoint-host`: the body is `{ idpToken, request }` with no granter, and the route\nverifies the token and derives the granter. A decision, an `owner-request` revoke, the four\ncaller-policy operations and the reads run as the proved owner on either face; `name-bind`, any\nother revoke and the admission operations are the operator's, served on the loopback face under the\nexchange capability only, with the proved subject as the audit id (the admission operations have no\nengine handler yet and answer `unsupported`). Mint requestIds unpredictably: they share one\nspace-wide namespace. `cotal service-endpoint` drives that route as the signed-in user\n([docs/cli.md](cli.md#service-endpoint)). Register admission is reachable only through the public\nroute below. `name-bind` needs an operator granter and `expectedRevision: 0`. It creates\nthe endpoint's name binding once, with your `claimReference`, and only the identical request recovers\nit; nothing updates, transfers or releases a name. The host checks no domain control, so verify the\nclaim, or delegate a namespace you control, before you bind. The host runs over the plane's claim hold, data account and\nactor ledger directory. A restore or missing startup refuses the plane open, which unwinds and\nreleases the claim. If that unwind cannot close an effect connection, it stops there: the claim\nstays held, the plane's clients, scanners and cleanup timer stay live, and there is no handle to\nretry. Only the process exiting ends them, after which the existing crash reclaim applies. Its discovery connection is an ordinary renewing read-only client: a broker loss\nfails its reads until the stock client reconnects, and those calls answer `unavailable` with nothing\nwritten. A renewal failure closes it permanently, and the host stays unavailable until the plane is\nopened again. Both plane fatal paths trip the host, and either one trips it even while the\nplane closes, without making the plane fatal. Plane close refuses new host calls from the\nmoment it is called, waits for every call that already entered, from entry through discovery and\neffect open, closes discovery and then releases the claim. An effect connection that failed to\nclose stays owned past its call: close closes it again first, and rejects with the claim still held\nwhile it stays open, so you can retry close. Until a retry succeeds or the process exits, discovery,\nthe administrative rail, both scanners and the remaining clients stay live, so no successor can\ntake over the claim.\n\nOn a multi-space host the setting is per space. The manifest entry's `serviceEndpoints` is the only\nplace it is set, and `--service-endpoints` refuses beside `--spaces`\n([server daemons](cli.md#server-daemons)). Check a manifest you write with\n`parseAuthHostManifest(text)` from `@cotal-ai/auth` before you rename it into place: it is the parser\nthe host applies. A callout replica cannot issue a service-endpoint connection, so it refuses a space\nwhose admission is open: a single-space replica refuses to start, and a callout host names the space\nand retries it every 5 seconds while it answers for the others. The first open with service endpoints\nopens the admission and nothing closes it, so keep every space that has ever run with service\nendpoints off replica manifests, also after its entry drops the field. `admitsServiceEndpoints({ space,\nserver, secrets })` from `@cotal-ai/auth` tells you which: it resolves `true` for the spaces a\ncallout lane refuses for their admission, with the read the lane makes on the lane's own store grant,\nand throws when the space's service keys are missing or its stores cannot be read. Nothing turns a\n`true` answer back to `false`. To turn service endpoints on for a space a replica lists, remove it from\nevery replica manifest and wait for each `<manifest>.applied` first: a lane checks at open, so a lane\nalready open keeps answering and denies the service connects the broker hands it.\n\nWith `serviceEndpoints`, both faces also serve `/service-endpoint-authority`, and without it that\nroute answers 404. `GET` returns the receiver's account and space, the exact `iss` its service\naccess bearers carry, and the public Ed25519 keys `GET /jwks` publishes. `POST` takes a `{request, proof}`\nenvelope of at most 2 MiB. An IdP proof derives the owner, who needs a current interactive cli or web\nrow; register needs one, and so may activate. A service's renewal proof authorizes activate, renew\nand status, and its access bearer authorizes ready and status; neither is owner authority. A typical\nsequence: the service registers and gets `approval-required`; you bind its name with an operator\n`name-bind`; the owner approves with `decide`; the service replays the same register and gets\n`registered` with its witness and snapshot; it activates and gets a `credential` with an access bearer\nof at most 60 s and a renewal proof of at most 24 h, neither outliving the native root or approval;\nit connects to the broker with the bearer through the composed native service callout, binds its\nresponder, calls `ready`, and renews before the bearer expires. The auth provider's\n`serviceEndpointInfo` and `serviceEndpointAuthority` hooks are the client, and accept a service proof\nas well as the signed-in login.\n\nThe `credential` answer carries no store access and no serve grant, so a service turns it into the\nprocess-local grant `serveEndpoint` consumes with `authorizeGuestServeGrant({ accountPublicKey,\nresult, registration, authenticity })`: the parsed result, the service's own embedded closure, and\nthe pinned issuer's `iss` and published keys. The issuer and keys come from the registered\nspace's authority URL the service already pins, tenant path included: the auth provider's\n`serviceEndpointInfo` answer carries them, and a service passes `serveAuthenticityOf(info)` as\n`authenticity`; an authority that does not publish them yet makes that call refuse, so the\nservice does not serve on a bearer it cannot verify.\nIt verifies the access bearer's EdDSA signature under the published key its `kid` names and the\nsame closed claims the host's token validator checks, so a bearer the issuer did not sign for\nthis witness brands nothing; the closure is bound to the service's own embedded contract, not to\nthe bearer. It refuses\nanother account, a bearer from another issuer, space, subject or key, one that names another\nwitness or no serve duty, a closure set or artifact that is not the embedded one, and a closure\nthat does not read at its digest. `authorizeTrustedServeSnapshot` stays the host's.\n\nFor a serving connection, the auth provider's `serviceEndpointRenewal({ store, dir, witness })` hook\nreturns that loop as a bearer function. It is an `AuthProvider` method, not a package export. Pass\nits `bearer` as `EndpointOptions.bearer` and its `sentinelCreds` with it. The\nfirst pull activates on the signed-in login and every later pull renews on the stored renewal proof.\nIf that proof has expired, as after a machine was off for more than a day, the next pull replays the\nsame activate request on the signed-in login, which mints again while the root and the approval stand.\nIt keeps one activate and one renew requestId per witness, written to `store` before the first send,\nand replays them, with fresh material each time, for as long as the root and the approval allow.\nConcurrent pulls share one request. `credential()` is that same pull answering the validated\n`credential` result without its renewal proof, which never leaves the source, as a copy per caller;\nit is what `authorizeGuestServeGrant` takes. `bearer()` and `credential()` share one pull, so the\ntwo in flight together send one request under the same persisted ids, and an ended or closed\nsource refuses both the same way. It owns no timer. A transport failure, `rate-limited`, a missing\nor rejected sign-in, or a store failure leaves it `unavailable`, and the next pull replays the same\nrequest; any other denial from the space ends it, and later pulls send nothing. `state()` reports\nexpiries only, errors are fixed sentences, and `close()` aborts a pull in flight.\n\nEvery effectful request is keyed by its requestId and body. Keep one requestId per operation and\nwitness, store it with the witness and the renewal material before you send it, and reuse it with\nthe same body after a restart: a replay is safe, a changed body under the same requestId is a\n`conflict`, and one instance accepts at most 64 distinct requests, so fresh keys per refresh or\nrestart exhaust it. A register requestId stays bound to the body and proposal its first answer\nadmitted: after approval, replay that exact request, and after a refusal or expiry, propose again\nunder a new requestId. A 503 means the request may be bound: replay the same request, or read its\nstatus with `target: { kind: \"operation\", operation, requestId }`; the selector names the operation\nsince this release, and the old `{ kind: \"operation\", requestId }` no longer parses. An owner reads\nstatus only while it holds an interactive row, and a service proof reads only its own instance.\n`registered` and `ready` in a status mean only that the request's registration is current. A\npre-activation re-registration sends `expected: { state: \"registered\", witness }` and yields a new\nwitness; a register that another request overtakes before its barrier freezes answers `conflict`,\nso read the instance and expect its current witness. A register whose gate moved under it without a\nnew registration, such as a freeze another barrier then aborted, also answers `conflict` with the\nwitness unchanged: if the instance still shows the witness you sent, replay the same request. A\nregister held inside the native barrier, or while another invocation of the same request is still\nrunning, answers 503; replay the same request. Once a service has activated, its registration\ncan no longer change. Commands must be ephemeral and declare\nno governed trait.\n\n`caller-grant` takes an owner granter with an interactive row who holds the approved instance, and a\ngrantee is a current exact owner, actor and lifecycle UID. A managed grantee also needs its actual\nsame-owner parent chain, with each current ancestor holding active covering grants for the same\nservice approval. The operation records those immutable grant ids and lifecycle UIDs in `parentRefs`\nand rechecks them before append. An admin scope never substitutes for endpoint caller rights. Every\ncapability must name that instance with `instanceOnly: true`, carry no journal access and no `any` or\n`ledger` target, and sit within the approval's caller ceiling. The answer is `granted` with the grant\nas stored. Ordinary user-auth agent connects now derive their endpoint rows from this policy through\ncore's native grant builder, including reserved Describe for each authorized exact instance. An unpinned\n`invokeService` or `invokeCommand` whose class publish the broker refuses is re-sent once on the rail of\nthe instance that answered its describe, so a granted caller reaches the service without naming the instance. The\ncallout rechecks grantee lifecycle, named ancestor grants, current name, assignment, root, activation,\napproval and ceiling, then checks the policy evidence again after signing and native-key recording.\nThe original connection expiry is at most 60 seconds from issuance, and capped by root and approval\nexpiry. These are fresh leader reads,\nnot a linearized revoke fence. Existing issued connections keep their original expiry, and caller\nrevocation remains deny-new, not terminal absence proof.\nOne instance indexes at most 256 grants over its life, including attempts refused after indexing, and\na full index answers `resource-exhausted`; a new instance is the remedy. `caller-revoke` admits the\ngrant's source owner, its grantee owner and an operator. It answers `pending` with\n`denyNew: \"landed\"` and `notBefore`, in epoch seconds, 71 s after the broker time of the grant's\ncutoff marker. It never answers `revoked`, and the result parser refuses that arm.\n`caller-policy-read` gives an owner its own grantees, and another owner's grantee only filtered to a\nservice it holds; `caller-policy-list` needs a service selector.\n\nCaller grants need `max_payload >= 2098176` (`SERVICE_CALLER_PAYLOAD_FLOOR`: 2 MiB plus 1 KiB),\n`max_control_line >= 4096`, and an auth stream with `max_msg_size: -1`. Broker generation accepts an\nexplicit `serverConfig(broker, accounts, { ...options, maxPayload: SERVICE_CALLER_PAYLOAD_FLOOR })`;\nomission leaves the native 1 MiB default unchanged. No startup path raises limits automatically. The\nstock root sets it with [`cotal up --max-payload <bytes>`](cli.md#up), which records the value in\n`.cotal/broker-policy.json`; a renderer outside `up` reads it back with\n`readBrokerPolicy(root)?.maxPayload` so every render of that broker carries the same limit.\n\nFor a **standalone broker only**, pass `serviceEndpoints.callerPayload.observerCreds` to\n`startAuthService` (or the corresponding authority-plane option). The callback returns fresh\nhost-private credentials from the broker owner's\n`mintServiceCallerPayloadObserverCreds({ pub: broker.sys.pub, signingSeed: broker.sys.signingSeed })`.\nKeep that registered SYS signer with the broker owner, never in the data account, a sandbox or a\nparticipant client. The helper returns an in-memory, at-most-60-second VARZ-only credential.\nThe stock root does this itself: `cotal up` retains the system-account signing seed in the root's\nsecret store at space creation and at `--rotate-sys`, and the auth service started with\n`--service-endpoints` composes `callerPayload` from it when the record names the trust record's\nsystem account and the seed derives it; a root with no retained seed opens the engine and door\nwithout caller issuance and logs why.\nThe callback only supplies credentials, owns no authority resource, and may finish after its\n10-second observation deadline has refused the operation. It is not a cancellation callback.\n\nStartup authenticates native VARZ, matches the observer and data connection's broker incarnation,\nchecks config/system-account evidence and live stream limits, then writes an exact-key assertion\nbound to that broker, configuration and genuine plane claim. Configured clusters, gateways and\nleaf links refuse, regardless of connected peer count. This is not multi-broker proof. A default\n1 MiB broker fails startup with the required byte limit and creates no assertion.\n\nPositive caller issuance repeats the observation and checks the exact assertion revision, complete\nplane hold and effective authority again before native JWT release. Withdrawal or claim loss refuse\nnew issuance. A broker RELOAD, which keeps the same incarnation serving and moves its\n`config_digest`, does not: when the fresh observation proves the same incarnation, the same auth\nstore, and every limit above again, the record is re-asserted under the held claim by CAS on the\nexact prior row and issuance continues. A reload that breaks any of those, a `max_payload` below the\nfloor included, still refuses, and a withdrawn record is never overwritten. A RESTART is a new\nincarnation and refuses. Reopening needs an explicit bootstrap to reassert for the new claim;\na prior-plane broker-bound assertion cannot authorize another append. Legacy assertion syntax still\nparses for existing trusted storage fixtures but alone never enables production caller issuance.\nShutdown drains in-flight observations and closes their owned connections before releasing the claim.\nReads and revokes do not need a positive assertion. A revoke whose policy row would not fit holds\n`payload-precondition` without writing it, and a failed live-limit check withdraws the assertion.\n\nGive each caller operation a fresh random requestId, record it with the exact body before you send\nit, and replay that body after a lost reply, a 503 or a `held` answer. Never switch to a new requestId\nwhile an earlier answer is unknown. A settled `refused` or `expired` ends the attempt, and a grant\nreplayed after its 10-minute window adopts a grant that landed and otherwise answers `expired`.\n\nCaller issuance is generic, not tied to Linear: the same provider-independent contract discovery and\ninvoke path works for ordinary and managed user-auth callers. Controlled policy append currently\nrequires the application's approved service-host instance. Native control endpoints retain their\nexisting ledger/scope and typed authority contracts, not fabricated application approvals. Scoped\nDescribe is not available, and complete terminal retirement and restore remain unsupported. A host revoke refuses new activation, renewal, readiness\nand connections, but a connection already open keeps its original expiry of at most 60 s. Approval\nruns service bootstrap and revoke runs cancellation, while complete observer evidence and writer\nexclusion remain unavailable. Do not seed service reservations in an existing space, adopt old\nservice-shaped rows, or use ordinary retirement to make them terminal. A signing-key or raw-store\nholder can bypass helper guards, so schema rejection alone does not make mixed-version writers safe.\nRestore must quarantine service work until a separately supported reconciliation protocol is\navailable.\n"
215
215
  },
216
216
  {
217
217
  "slug": "examples",
@@ -1 +1 @@
1
- {"version":3,"file":"docs-bundle.generated.js","sourceRoot":"","sources":["../src/docs-bundle.generated.ts"],"names":[],"mappings":"AAKA,yFAAyF;AACzF,MAAM,CAAC,MAAM,YAAY,GAAG,SAAS,CAAC;AAEtC,MAAM,UAAU,cAAc;IAC5B,OAAO;QACP,SAAS,EAAE,SAAS;QACpB,eAAe,EAAE,mEAAmE;QACpF,OAAO,EAAE;YACP;gBACE,MAAM,EAAE,eAAe;gBACvB,OAAO,EAAE,eAAe;gBACxB,MAAM,EAAE,0BAA0B;gBAClC,UAAU,EAAE,YAAY;gBACxB,SAAS,EAAE,yFAAyF;gBACpG,MAAM,EAAE,6rKAA6rK;aACtsK;YACD;gBACE,MAAM,EAAE,iBAAiB;gBACzB,OAAO,EAAE,YAAY;gBACrB,MAAM,EAAE,0BAA0B;gBAClC,UAAU,EAAE,YAAY;gBACxB,SAAS,EAAE,gHAAgH;gBAC3H,MAAM,EAAE,kqfAAkqf;aAC3qf;YACD;gBACE,MAAM,EAAE,cAAc;gBACtB,OAAO,EAAE,cAAc;gBACvB,MAAM,EAAE,uBAAuB;gBAC/B,UAAU,EAAE,SAAS;gBACrB,SAAS,EAAE,wMAAwM;gBACnN,MAAM,EAAE,0otBAA0otB;aACnptB;YACD;gBACE,MAAM,EAAE,WAAW;gBACnB,OAAO,EAAE,kBAAkB;gBAC3B,MAAM,EAAE,mEAAmE;gBAC3E,UAAU,EAAE,WAAW;gBACvB,SAAS,EAAE,wMAAwM;gBACnN,MAAM,EAAE,wk+CAAwk+C;aACjl+C;YACD;gBACE,MAAM,EAAE,0BAA0B;gBAClC,OAAO,EAAE,qBAAqB;gBAC9B,MAAM,EAAE,mCAAmC;gBAC3C,UAAU,EAAE,WAAW;gBACvB,SAAS,EAAE,gGAAgG;gBAC3G,MAAM,EAAE,4sNAA4sN;aACrtN;YACD;gBACE,MAAM,EAAE,mBAAmB;gBAC3B,OAAO,EAAE,UAAU;gBACnB,MAAM,EAAE,uBAAuB;gBAC/B,UAAU,EAAE,SAAS;gBACrB,SAAS,EAAE,oDAAoD;gBAC/D,MAAM,EAAE,mwzEAAmwzE;aAC5wzE;YACD;gBACE,MAAM,EAAE,aAAa;gBACrB,OAAO,EAAE,aAAa;gBACtB,MAAM,EAAE,yFAAyF;gBACjG,UAAU,EAAE,WAAW;gBACvB,SAAS,EAAE,gJAAgJ;gBAC3J,MAAM,EAAE,2+YAA2+Y;aACp/Y;YACD;gBACE,MAAM,EAAE,eAAe;gBACvB,OAAO,EAAE,eAAe;gBACxB,MAAM,EAAE,yBAAyB;gBACjC,UAAU,EAAE,WAAW;gBACvB,SAAS,EAAE,oFAAoF;gBAC/F,MAAM,EAAE,iqLAAiqL;aAC1qL;YACD;gBACE,MAAM,EAAE,UAAU;gBAClB,OAAO,EAAE,eAAe;gBACxB,MAAM,EAAE,yBAAyB;gBACjC,UAAU,EAAE,WAAW;gBACvB,SAAS,EAAE,+EAA+E;gBAC1F,MAAM,EAAE,gpiFAAgpiF;aACzpiF;YACD;gBACE,MAAM,EAAE,uBAAuB;gBAC/B,OAAO,EAAE,uBAAuB;gBAChC,MAAM,EAAE,sFAAsF;gBAC9F,UAAU,EAAE,WAAW;gBACvB,SAAS,EAAE,6GAA6G;gBACxH,MAAM,EAAE,ukUAAukU;aAChlU;YACD;gBACE,MAAM,EAAE,gBAAgB;gBACxB,OAAO,EAAE,sBAAsB;gBAC/B,MAAM,EAAE,qBAAqB;gBAC7B,UAAU,EAAE,OAAO;gBACnB,SAAS,EAAE,sMAAsM;gBACjN,MAAM,EAAE,koTAAkoT;aAC3oT;YACD;gBACE,MAAM,EAAE,KAAK;gBACb,OAAO,EAAE,uBAAuB;gBAChC,MAAM,EAAE,wGAAwG;gBAChH,UAAU,EAAE,WAAW;gBACvB,SAAS,EAAE,iKAAiK;gBAC5K,MAAM,EAAE,4s3wBAA4s3wB;aACrt3wB;YACD;gBACE,MAAM,EAAE,QAAQ;gBAChB,OAAO,EAAE,eAAe;gBACxB,MAAM,EAAE,uHAAuH;gBAC/H,UAAU,EAAE,WAAW;gBACvB,SAAS,EAAE,wMAAwM;gBACnN,MAAM,EAAE,m78CAAm78C;aAC578C;YACD;gBACE,MAAM,EAAE,gBAAgB;gBACxB,OAAO,EAAE,gBAAgB;gBACzB,MAAM,EAAE,qBAAqB;gBAC7B,UAAU,EAAE,OAAO;gBACnB,SAAS,EAAE,+EAA+E;gBAC1F,MAAM,EAAE,+xpFAA+xpF;aACxypF;YACD;gBACE,MAAM,EAAE,eAAe;gBACvB,OAAO,EAAE,sBAAsB;gBAC/B,MAAM,EAAE,qBAAqB;gBAC7B,UAAU,EAAE,OAAO;gBACnB,SAAS,EAAE,wMAAwM;gBACnN,MAAM,EAAE,20tBAA20tB;aACp1tB;YACD;gBACE,MAAM,EAAE,gBAAgB;gBACxB,OAAO,EAAE,wBAAwB;gBACjC,MAAM,EAAE,qBAAqB;gBAC7B,UAAU,EAAE,OAAO;gBACnB,SAAS,EAAE,kJAAkJ;gBAC7J,MAAM,EAAE,q+eAAq+e;aAC9+e;YACD;gBACE,MAAM,EAAE,eAAe;gBACvB,OAAO,EAAE,sBAAsB;gBAC/B,MAAM,EAAE,qBAAqB;gBAC7B,UAAU,EAAE,OAAO;gBACnB,SAAS,EAAE,6CAA6C;gBACxD,MAAM,EAAE,mg8BAAmg8B;aAC5g8B;YACD;gBACE,MAAM,EAAE,kBAAkB;gBAC1B,OAAO,EAAE,yBAAyB;gBAClC,MAAM,EAAE,qBAAqB;gBAC7B,UAAU,EAAE,OAAO;gBACnB,SAAS,EAAE,wJAAwJ;gBACnK,MAAM,EAAE,80dAA80d;aACv1d;YACD;gBACE,MAAM,EAAE,YAAY;gBACpB,OAAO,EAAE,oBAAoB;gBAC7B,MAAM,EAAE,qBAAqB;gBAC7B,UAAU,EAAE,OAAO;gBACnB,SAAS,EAAE,8DAA8D;gBACzE,MAAM,EAAE,wqRAAwqR;aACjrR;YACD;gBACE,MAAM,EAAE,YAAY;gBACpB,OAAO,EAAE,YAAY;gBACrB,MAAM,EAAE,qBAAqB;gBAC7B,UAAU,EAAE,OAAO;gBACnB,SAAS,EAAE,4HAA4H;gBACvI,MAAM,EAAE,yiOAAyiO;aACljO;YACD;gBACE,MAAM,EAAE,iBAAiB;gBACzB,OAAO,EAAE,qBAAqB;gBAC9B,MAAM,EAAE,uBAAuB;gBAC/B,UAAU,EAAE,SAAS;gBACrB,SAAS,EAAE,oIAAoI;gBAC/I,MAAM,EAAE,gngDAAgngD;aACzngD;YACD;gBACE,MAAM,EAAE,eAAe;gBACvB,OAAO,EAAE,oBAAoB;gBAC7B,MAAM,EAAE,yBAAyB;gBACjC,UAAU,EAAE,WAAW;gBACvB,SAAS,EAAE,+DAA+D;gBAC1E,MAAM,EAAE,wj1BAAwj1B;aACjk1B;YACD;gBACE,MAAM,EAAE,eAAe;gBACvB,OAAO,EAAE,eAAe;gBACxB,MAAM,EAAE,qBAAqB;gBAC7B,UAAU,EAAE,OAAO;gBACnB,SAAS,EAAE,uMAAuM;gBAClN,MAAM,EAAE,m7eAAm7e;aAC57e;YACD;gBACE,MAAM,EAAE,iBAAiB;gBACzB,OAAO,EAAE,+BAA+B;gBACxC,MAAM,EAAE,uBAAuB;gBAC/B,UAAU,EAAE,SAAS;gBACrB,SAAS,EAAE,6HAA6H;gBACxI,MAAM,EAAE,wjpBAAwjpB;aACjkpB;YACD;gBACE,MAAM,EAAE,QAAQ;gBAChB,OAAO,EAAE,uBAAuB;gBAChC,MAAM,EAAE,qBAAqB;gBAC7B,UAAU,EAAE,OAAO;gBACnB,SAAS,EAAE,6GAA6G;gBACxH,MAAM,EAAE,0tOAA0tO;aACnuO;YACD;gBACE,MAAM,EAAE,WAAW;gBACnB,OAAO,EAAE,iBAAiB;gBAC1B,MAAM,EAAE,qBAAqB;gBAC7B,UAAU,EAAE,OAAO;gBACnB,SAAS,EAAE,yEAAyE;gBACpF,MAAM,EAAE,u12IAAu12I;aACh22I;YACD;gBACE,MAAM,EAAE,UAAU;gBAClB,OAAO,EAAE,UAAU;gBACnB,MAAM,EAAE,qBAAqB;gBAC7B,UAAU,EAAE,OAAO;gBACnB,SAAS,EAAE,6DAA6D;gBACxE,MAAM,EAAE,gtHAAgtH;aACztH;YACD;gBACE,MAAM,EAAE,UAAU;gBAClB,OAAO,EAAE,UAAU;gBACnB,MAAM,EAAE,yBAAyB;gBACjC,UAAU,EAAE,WAAW;gBACvB,SAAS,EAAE,wEAAwE;gBACnF,MAAM,EAAE,0zQAA0zQ;aACn0Q;YACD;gBACE,MAAM,EAAE,WAAW;gBACnB,OAAO,EAAE,qBAAqB;gBAC9B,MAAM,EAAE,yBAAyB;gBACjC,UAAU,EAAE,WAAW;gBACvB,SAAS,EAAE,+CAA+C;gBAC1D,MAAM,EAAE,2jQAA2jQ;aACpkQ;YACD;gBACE,MAAM,EAAE,UAAU;gBAClB,OAAO,EAAE,8BAA8B;gBACvC,MAAM,EAAE,8CAA8C;gBACtD,UAAU,EAAE,WAAW;gBACvB,SAAS,EAAE,qIAAqI;gBAChJ,MAAM,EAAE,mhWAAmhW;aAC5hW;YACD;gBACE,MAAM,EAAE,WAAW;gBACnB,OAAO,EAAE,UAAU;gBACnB,MAAM,EAAE,sDAAsD;gBAC9D,UAAU,EAAE,WAAW;gBACvB,SAAS,EAAE,mFAAmF;gBAC9F,MAAM,EAAE,i6ZAAi6Z;aAC16Z;YACD;gBACE,MAAM,EAAE,uBAAuB;gBAC/B,OAAO,EAAE,cAAc;gBACvB,MAAM,EAAE,uBAAuB;gBAC/B,UAAU,EAAE,SAAS;gBACrB,SAAS,EAAE,0IAA0I;gBACrJ,MAAM,EAAE,i6tBAAi6tB;aAC16tB;YACD;gBACE,MAAM,EAAE,SAAS;gBACjB,OAAO,EAAE,sBAAsB;gBAC/B,MAAM,EAAE,0CAA0C;gBAClD,UAAU,EAAE,SAAS;gBACrB,SAAS,EAAE,8DAA8D;gBACzE,MAAM,EAAE,i8QAAi8Q;aAC18Q;YACD;gBACE,MAAM,EAAE,SAAS;gBACjB,OAAO,EAAE,SAAS;gBAClB,MAAM,EAAE,yBAAyB;gBACjC,UAAU,EAAE,SAAS;gBACrB,SAAS,EAAE,mLAAmL;gBAC9L,MAAM,EAAE,68MAA68M;aACt9M;YACD;gBACE,MAAM,EAAE,YAAY;gBACpB,OAAO,EAAE,YAAY;gBACrB,MAAM,EAAE,qBAAqB;gBAC7B,UAAU,EAAE,OAAO;gBACnB,SAAS,EAAE,wMAAwM;gBACnN,MAAM,EAAE,u0tDAAu0tD;aACh1tD;YACD;gBACE,MAAM,EAAE,UAAU;gBAClB,OAAO,EAAE,gBAAgB;gBACzB,MAAM,EAAE,oCAAoC;gBAC5C,UAAU,EAAE,SAAS;gBACrB,SAAS,EAAE,kGAAkG;gBAC7G,MAAM,EAAE,8gcAA8gc;aACvhc;YACD;gBACE,MAAM,EAAE,iBAAiB;gBACzB,OAAO,EAAE,oCAAoC;gBAC7C,MAAM,EAAE,0CAA0C;gBAClD,UAAU,EAAE,SAAS;gBACrB,SAAS,EAAE,wLAAwL;gBACnM,MAAM,EAAE,0/6BAA0/6B;aACng7B;YACD;gBACE,MAAM,EAAE,QAAQ;gBAChB,OAAO,EAAE,QAAQ;gBACjB,MAAM,EAAE,uBAAuB;gBAC/B,UAAU,EAAE,SAAS;gBACrB,SAAS,EAAE,2DAA2D;gBACtE,MAAM,EAAE,+9KAA+9K;aACx+K;YACD;gBACE,MAAM,EAAE,WAAW;gBACnB,OAAO,EAAE,qBAAqB;gBAC9B,MAAM,EAAE,uBAAuB;gBAC/B,UAAU,EAAE,SAAS;gBACrB,SAAS,EAAE,uDAAuD;gBAClE,MAAM,EAAE,w1KAAw1K;aACj2K;YACD;gBACE,MAAM,EAAE,WAAW;gBACnB,OAAO,EAAE,WAAW;gBACpB,MAAM,EAAE,WAAW;gBACnB,UAAU,EAAE,WAAW;gBACvB,SAAS,EAAE,wEAAwE;gBACnF,MAAM,EAAE,qtTAAqtT;aAC9tT;YACD;gBACE,MAAM,EAAE,WAAW;gBACnB,OAAO,EAAE,uBAAuB;gBAChC,MAAM,EAAE,uBAAuB;gBAC/B,UAAU,EAAE,SAAS;gBACrB,SAAS,EAAE,kGAAkG;gBAC7G,MAAM,EAAE,o8SAAo8S;aAC78S;YACD;gBACE,MAAM,EAAE,WAAW;gBACnB,OAAO,EAAE,gCAAgC;gBACzC,MAAM,EAAE,qBAAqB;gBAC7B,UAAU,EAAE,OAAO;gBACnB,SAAS,EAAE,iEAAiE;gBAC5E,MAAM,EAAE,gsyKAAgsyK;aACzsyK;YACD;gBACE,MAAM,EAAE,aAAa;gBACrB,OAAO,EAAE,mBAAmB;gBAC5B,MAAM,EAAE,qBAAqB;gBAC7B,UAAU,EAAE,OAAO;gBACnB,SAAS,EAAE,iGAAiG;gBAC5G,MAAM,EAAE,s8NAAs8N;aAC/8N;YACD;gBACE,MAAM,EAAE,cAAc;gBACtB,OAAO,EAAE,cAAc;gBACvB,MAAM,EAAE,qBAAqB;gBAC7B,UAAU,EAAE,OAAO;gBACnB,SAAS,EAAE,2HAA2H;gBACtI,MAAM,EAAE,q7rBAAq7rB;aAC97rB;YACD;gBACE,MAAM,EAAE,WAAW;gBACnB,OAAO,EAAE,eAAe;gBACxB,MAAM,EAAE,uBAAuB;gBAC/B,UAAU,EAAE,SAAS;gBACrB,SAAS,EAAE,kHAAkH;gBAC7H,MAAM,EAAE,g0iEAAg0iE;aACz0iE;SACF;QACD,MAAM,EAAE;YACN,OAAO,EAAE,0BAA0B;YACnC,MAAM,EAAE,24mqBAA24mqB;SACp5mqB;QACD,MAAM,EAAE;YACN,OAAO,EAAE,mCAAmC;YAC5C,MAAM,EAAE,g9tGAAg9tG;SACz9tG;QACD,QAAQ,EAAE;YACR,OAAO,EAAE,oCAAoC;YAC7C,MAAM,EAAE,s8tBAAs8tB;SAC/8tB;KACF,CAAC;AACF,CAAC"}
1
+ {"version":3,"file":"docs-bundle.generated.js","sourceRoot":"","sources":["../src/docs-bundle.generated.ts"],"names":[],"mappings":"AAKA,yFAAyF;AACzF,MAAM,CAAC,MAAM,YAAY,GAAG,SAAS,CAAC;AAEtC,MAAM,UAAU,cAAc;IAC5B,OAAO;QACP,SAAS,EAAE,SAAS;QACpB,eAAe,EAAE,mEAAmE;QACpF,OAAO,EAAE;YACP;gBACE,MAAM,EAAE,eAAe;gBACvB,OAAO,EAAE,eAAe;gBACxB,MAAM,EAAE,0BAA0B;gBAClC,UAAU,EAAE,YAAY;gBACxB,SAAS,EAAE,yFAAyF;gBACpG,MAAM,EAAE,6rKAA6rK;aACtsK;YACD;gBACE,MAAM,EAAE,iBAAiB;gBACzB,OAAO,EAAE,YAAY;gBACrB,MAAM,EAAE,0BAA0B;gBAClC,UAAU,EAAE,YAAY;gBACxB,SAAS,EAAE,gHAAgH;gBAC3H,MAAM,EAAE,kqfAAkqf;aAC3qf;YACD;gBACE,MAAM,EAAE,cAAc;gBACtB,OAAO,EAAE,cAAc;gBACvB,MAAM,EAAE,uBAAuB;gBAC/B,UAAU,EAAE,SAAS;gBACrB,SAAS,EAAE,wMAAwM;gBACnN,MAAM,EAAE,0otBAA0otB;aACnptB;YACD;gBACE,MAAM,EAAE,WAAW;gBACnB,OAAO,EAAE,kBAAkB;gBAC3B,MAAM,EAAE,mEAAmE;gBAC3E,UAAU,EAAE,WAAW;gBACvB,SAAS,EAAE,wMAAwM;gBACnN,MAAM,EAAE,wk+CAAwk+C;aACjl+C;YACD;gBACE,MAAM,EAAE,0BAA0B;gBAClC,OAAO,EAAE,qBAAqB;gBAC9B,MAAM,EAAE,mCAAmC;gBAC3C,UAAU,EAAE,WAAW;gBACvB,SAAS,EAAE,gGAAgG;gBAC3G,MAAM,EAAE,4sNAA4sN;aACrtN;YACD;gBACE,MAAM,EAAE,mBAAmB;gBAC3B,OAAO,EAAE,UAAU;gBACnB,MAAM,EAAE,uBAAuB;gBAC/B,UAAU,EAAE,SAAS;gBACrB,SAAS,EAAE,oDAAoD;gBAC/D,MAAM,EAAE,2o0EAA2o0E;aACpp0E;YACD;gBACE,MAAM,EAAE,aAAa;gBACrB,OAAO,EAAE,aAAa;gBACtB,MAAM,EAAE,yFAAyF;gBACjG,UAAU,EAAE,WAAW;gBACvB,SAAS,EAAE,gJAAgJ;gBAC3J,MAAM,EAAE,2+YAA2+Y;aACp/Y;YACD;gBACE,MAAM,EAAE,eAAe;gBACvB,OAAO,EAAE,eAAe;gBACxB,MAAM,EAAE,yBAAyB;gBACjC,UAAU,EAAE,WAAW;gBACvB,SAAS,EAAE,oFAAoF;gBAC/F,MAAM,EAAE,iqLAAiqL;aAC1qL;YACD;gBACE,MAAM,EAAE,UAAU;gBAClB,OAAO,EAAE,eAAe;gBACxB,MAAM,EAAE,yBAAyB;gBACjC,UAAU,EAAE,WAAW;gBACvB,SAAS,EAAE,+EAA+E;gBAC1F,MAAM,EAAE,gpiFAAgpiF;aACzpiF;YACD;gBACE,MAAM,EAAE,uBAAuB;gBAC/B,OAAO,EAAE,uBAAuB;gBAChC,MAAM,EAAE,sFAAsF;gBAC9F,UAAU,EAAE,WAAW;gBACvB,SAAS,EAAE,6GAA6G;gBACxH,MAAM,EAAE,ukUAAukU;aAChlU;YACD;gBACE,MAAM,EAAE,gBAAgB;gBACxB,OAAO,EAAE,sBAAsB;gBAC/B,MAAM,EAAE,qBAAqB;gBAC7B,UAAU,EAAE,OAAO;gBACnB,SAAS,EAAE,sMAAsM;gBACjN,MAAM,EAAE,koTAAkoT;aAC3oT;YACD;gBACE,MAAM,EAAE,KAAK;gBACb,OAAO,EAAE,uBAAuB;gBAChC,MAAM,EAAE,wGAAwG;gBAChH,UAAU,EAAE,WAAW;gBACvB,SAAS,EAAE,iKAAiK;gBAC5K,MAAM,EAAE,4s3wBAA4s3wB;aACrt3wB;YACD;gBACE,MAAM,EAAE,QAAQ;gBAChB,OAAO,EAAE,eAAe;gBACxB,MAAM,EAAE,uHAAuH;gBAC/H,UAAU,EAAE,WAAW;gBACvB,SAAS,EAAE,wMAAwM;gBACnN,MAAM,EAAE,m78CAAm78C;aAC578C;YACD;gBACE,MAAM,EAAE,gBAAgB;gBACxB,OAAO,EAAE,gBAAgB;gBACzB,MAAM,EAAE,qBAAqB;gBAC7B,UAAU,EAAE,OAAO;gBACnB,SAAS,EAAE,+EAA+E;gBAC1F,MAAM,EAAE,+xpFAA+xpF;aACxypF;YACD;gBACE,MAAM,EAAE,eAAe;gBACvB,OAAO,EAAE,sBAAsB;gBAC/B,MAAM,EAAE,qBAAqB;gBAC7B,UAAU,EAAE,OAAO;gBACnB,SAAS,EAAE,wMAAwM;gBACnN,MAAM,EAAE,20tBAA20tB;aACp1tB;YACD;gBACE,MAAM,EAAE,gBAAgB;gBACxB,OAAO,EAAE,wBAAwB;gBACjC,MAAM,EAAE,qBAAqB;gBAC7B,UAAU,EAAE,OAAO;gBACnB,SAAS,EAAE,kJAAkJ;gBAC7J,MAAM,EAAE,q+eAAq+e;aAC9+e;YACD;gBACE,MAAM,EAAE,eAAe;gBACvB,OAAO,EAAE,sBAAsB;gBAC/B,MAAM,EAAE,qBAAqB;gBAC7B,UAAU,EAAE,OAAO;gBACnB,SAAS,EAAE,6CAA6C;gBACxD,MAAM,EAAE,mg8BAAmg8B;aAC5g8B;YACD;gBACE,MAAM,EAAE,kBAAkB;gBAC1B,OAAO,EAAE,yBAAyB;gBAClC,MAAM,EAAE,qBAAqB;gBAC7B,UAAU,EAAE,OAAO;gBACnB,SAAS,EAAE,wJAAwJ;gBACnK,MAAM,EAAE,80dAA80d;aACv1d;YACD;gBACE,MAAM,EAAE,YAAY;gBACpB,OAAO,EAAE,oBAAoB;gBAC7B,MAAM,EAAE,qBAAqB;gBAC7B,UAAU,EAAE,OAAO;gBACnB,SAAS,EAAE,8DAA8D;gBACzE,MAAM,EAAE,wqRAAwqR;aACjrR;YACD;gBACE,MAAM,EAAE,YAAY;gBACpB,OAAO,EAAE,YAAY;gBACrB,MAAM,EAAE,qBAAqB;gBAC7B,UAAU,EAAE,OAAO;gBACnB,SAAS,EAAE,4HAA4H;gBACvI,MAAM,EAAE,yiOAAyiO;aACljO;YACD;gBACE,MAAM,EAAE,iBAAiB;gBACzB,OAAO,EAAE,qBAAqB;gBAC9B,MAAM,EAAE,uBAAuB;gBAC/B,UAAU,EAAE,SAAS;gBACrB,SAAS,EAAE,oIAAoI;gBAC/I,MAAM,EAAE,gngDAAgngD;aACzngD;YACD;gBACE,MAAM,EAAE,eAAe;gBACvB,OAAO,EAAE,oBAAoB;gBAC7B,MAAM,EAAE,yBAAyB;gBACjC,UAAU,EAAE,WAAW;gBACvB,SAAS,EAAE,+DAA+D;gBAC1E,MAAM,EAAE,wj1BAAwj1B;aACjk1B;YACD;gBACE,MAAM,EAAE,eAAe;gBACvB,OAAO,EAAE,eAAe;gBACxB,MAAM,EAAE,qBAAqB;gBAC7B,UAAU,EAAE,OAAO;gBACnB,SAAS,EAAE,uMAAuM;gBAClN,MAAM,EAAE,m7eAAm7e;aAC57e;YACD;gBACE,MAAM,EAAE,iBAAiB;gBACzB,OAAO,EAAE,+BAA+B;gBACxC,MAAM,EAAE,uBAAuB;gBAC/B,UAAU,EAAE,SAAS;gBACrB,SAAS,EAAE,6HAA6H;gBACxI,MAAM,EAAE,wjpBAAwjpB;aACjkpB;YACD;gBACE,MAAM,EAAE,QAAQ;gBAChB,OAAO,EAAE,uBAAuB;gBAChC,MAAM,EAAE,qBAAqB;gBAC7B,UAAU,EAAE,OAAO;gBACnB,SAAS,EAAE,6GAA6G;gBACxH,MAAM,EAAE,0tOAA0tO;aACnuO;YACD;gBACE,MAAM,EAAE,WAAW;gBACnB,OAAO,EAAE,iBAAiB;gBAC1B,MAAM,EAAE,qBAAqB;gBAC7B,UAAU,EAAE,OAAO;gBACnB,SAAS,EAAE,yEAAyE;gBACpF,MAAM,EAAE,447IAA447I;aACr57I;YACD;gBACE,MAAM,EAAE,UAAU;gBAClB,OAAO,EAAE,UAAU;gBACnB,MAAM,EAAE,qBAAqB;gBAC7B,UAAU,EAAE,OAAO;gBACnB,SAAS,EAAE,6DAA6D;gBACxE,MAAM,EAAE,gtHAAgtH;aACztH;YACD;gBACE,MAAM,EAAE,UAAU;gBAClB,OAAO,EAAE,UAAU;gBACnB,MAAM,EAAE,yBAAyB;gBACjC,UAAU,EAAE,WAAW;gBACvB,SAAS,EAAE,wEAAwE;gBACnF,MAAM,EAAE,0zQAA0zQ;aACn0Q;YACD;gBACE,MAAM,EAAE,WAAW;gBACnB,OAAO,EAAE,qBAAqB;gBAC9B,MAAM,EAAE,yBAAyB;gBACjC,UAAU,EAAE,WAAW;gBACvB,SAAS,EAAE,+CAA+C;gBAC1D,MAAM,EAAE,2jQAA2jQ;aACpkQ;YACD;gBACE,MAAM,EAAE,UAAU;gBAClB,OAAO,EAAE,8BAA8B;gBACvC,MAAM,EAAE,8CAA8C;gBACtD,UAAU,EAAE,WAAW;gBACvB,SAAS,EAAE,qIAAqI;gBAChJ,MAAM,EAAE,mhWAAmhW;aAC5hW;YACD;gBACE,MAAM,EAAE,WAAW;gBACnB,OAAO,EAAE,UAAU;gBACnB,MAAM,EAAE,sDAAsD;gBAC9D,UAAU,EAAE,WAAW;gBACvB,SAAS,EAAE,mFAAmF;gBAC9F,MAAM,EAAE,i6ZAAi6Z;aAC16Z;YACD;gBACE,MAAM,EAAE,uBAAuB;gBAC/B,OAAO,EAAE,cAAc;gBACvB,MAAM,EAAE,uBAAuB;gBAC/B,UAAU,EAAE,SAAS;gBACrB,SAAS,EAAE,0IAA0I;gBACrJ,MAAM,EAAE,i6tBAAi6tB;aAC16tB;YACD;gBACE,MAAM,EAAE,SAAS;gBACjB,OAAO,EAAE,sBAAsB;gBAC/B,MAAM,EAAE,0CAA0C;gBAClD,UAAU,EAAE,SAAS;gBACrB,SAAS,EAAE,8DAA8D;gBACzE,MAAM,EAAE,i8QAAi8Q;aAC18Q;YACD;gBACE,MAAM,EAAE,SAAS;gBACjB,OAAO,EAAE,SAAS;gBAClB,MAAM,EAAE,yBAAyB;gBACjC,UAAU,EAAE,SAAS;gBACrB,SAAS,EAAE,mLAAmL;gBAC9L,MAAM,EAAE,68MAA68M;aACt9M;YACD;gBACE,MAAM,EAAE,YAAY;gBACpB,OAAO,EAAE,YAAY;gBACrB,MAAM,EAAE,qBAAqB;gBAC7B,UAAU,EAAE,OAAO;gBACnB,SAAS,EAAE,wMAAwM;gBACnN,MAAM,EAAE,u0tDAAu0tD;aACh1tD;YACD;gBACE,MAAM,EAAE,UAAU;gBAClB,OAAO,EAAE,gBAAgB;gBACzB,MAAM,EAAE,oCAAoC;gBAC5C,UAAU,EAAE,SAAS;gBACrB,SAAS,EAAE,kGAAkG;gBAC7G,MAAM,EAAE,8gcAA8gc;aACvhc;YACD;gBACE,MAAM,EAAE,iBAAiB;gBACzB,OAAO,EAAE,oCAAoC;gBAC7C,MAAM,EAAE,0CAA0C;gBAClD,UAAU,EAAE,SAAS;gBACrB,SAAS,EAAE,wLAAwL;gBACnM,MAAM,EAAE,0/6BAA0/6B;aACng7B;YACD;gBACE,MAAM,EAAE,QAAQ;gBAChB,OAAO,EAAE,QAAQ;gBACjB,MAAM,EAAE,uBAAuB;gBAC/B,UAAU,EAAE,SAAS;gBACrB,SAAS,EAAE,2DAA2D;gBACtE,MAAM,EAAE,+9KAA+9K;aACx+K;YACD;gBACE,MAAM,EAAE,WAAW;gBACnB,OAAO,EAAE,qBAAqB;gBAC9B,MAAM,EAAE,uBAAuB;gBAC/B,UAAU,EAAE,SAAS;gBACrB,SAAS,EAAE,uDAAuD;gBAClE,MAAM,EAAE,w1KAAw1K;aACj2K;YACD;gBACE,MAAM,EAAE,WAAW;gBACnB,OAAO,EAAE,WAAW;gBACpB,MAAM,EAAE,WAAW;gBACnB,UAAU,EAAE,WAAW;gBACvB,SAAS,EAAE,wEAAwE;gBACnF,MAAM,EAAE,qtTAAqtT;aAC9tT;YACD;gBACE,MAAM,EAAE,WAAW;gBACnB,OAAO,EAAE,uBAAuB;gBAChC,MAAM,EAAE,uBAAuB;gBAC/B,UAAU,EAAE,SAAS;gBACrB,SAAS,EAAE,kGAAkG;gBAC7G,MAAM,EAAE,o8SAAo8S;aAC78S;YACD;gBACE,MAAM,EAAE,WAAW;gBACnB,OAAO,EAAE,gCAAgC;gBACzC,MAAM,EAAE,qBAAqB;gBAC7B,UAAU,EAAE,OAAO;gBACnB,SAAS,EAAE,iEAAiE;gBAC5E,MAAM,EAAE,gsyKAAgsyK;aACzsyK;YACD;gBACE,MAAM,EAAE,aAAa;gBACrB,OAAO,EAAE,mBAAmB;gBAC5B,MAAM,EAAE,qBAAqB;gBAC7B,UAAU,EAAE,OAAO;gBACnB,SAAS,EAAE,iGAAiG;gBAC5G,MAAM,EAAE,s8NAAs8N;aAC/8N;YACD;gBACE,MAAM,EAAE,cAAc;gBACtB,OAAO,EAAE,cAAc;gBACvB,MAAM,EAAE,qBAAqB;gBAC7B,UAAU,EAAE,OAAO;gBACnB,SAAS,EAAE,2HAA2H;gBACtI,MAAM,EAAE,q7rBAAq7rB;aAC97rB;YACD;gBACE,MAAM,EAAE,WAAW;gBACnB,OAAO,EAAE,eAAe;gBACxB,MAAM,EAAE,uBAAuB;gBAC/B,UAAU,EAAE,SAAS;gBACrB,SAAS,EAAE,kHAAkH;gBAC7H,MAAM,EAAE,g0iEAAg0iE;aACz0iE;SACF;QACD,MAAM,EAAE;YACN,OAAO,EAAE,0BAA0B;YACnC,MAAM,EAAE,24mqBAA24mqB;SACp5mqB;QACD,MAAM,EAAE;YACN,OAAO,EAAE,mCAAmC;YAC5C,MAAM,EAAE,g9tGAAg9tG;SACz9tG;QACD,QAAQ,EAAE;YACR,OAAO,EAAE,oCAAoC;YAC7C,MAAM,EAAE,s8tBAAs8tB;SAC/8tB;KACF,CAAC;AACF,CAAC"}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@cotal-ai/connector-core",
3
3
  "description": "Shared MCP-bridge runtime for Cotal connectors: the mesh agent, cotal_* tools, and hook relay.",
4
- "version": "0.122.0",
4
+ "version": "0.123.0",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
7
7
  "type": "git",
@@ -41,11 +41,11 @@
41
41
  "@cotal-ai/core": ">=0.1.0"
42
42
  },
43
43
  "devDependencies": {
44
- "@cotal-ai/auth": "0.122.0",
44
+ "@cotal-ai/auth": "0.123.0",
45
45
  "jose": "^6.2.3",
46
46
  "@cotal-ai/smoke-kit": "0.0.0",
47
47
  "@ag-ui/core": "0.0.57",
48
- "@cotal-ai/core": "0.122.0",
48
+ "@cotal-ai/core": "0.123.0",
49
49
  "@nats-io/jetstream": "^3.4.0",
50
50
  "@nats-io/transport-node": "^3.4.0"
51
51
  },