@cotal-ai/connector-codex 0.47.1 → 0.48.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.
package/dist/host.js CHANGED
@@ -40143,6 +40143,7 @@ var CREDENTIAL_LIFETIMES = {
40143
40143
  "session-serving": { class: "one-shot", defaultTtlSeconds: 24 * 60 * 60, note: "per-session SERVING cred (P2 item 6): rails-only for ONE \xA713.6 session, the mirror of session-caller with the directions swapped; minted at redemption and TTL-BOUND to the session (the 24h default is the SESSION_GRANT_MAX_TTL ceiling, never a standing lifetime); NEVER renewed - a new session mints a new cred, and the session's terminal revokes this one by name" },
40144
40144
  "session-ledger": { class: "standing-renewable", defaultTtlSeconds: STANDING_RENEWABLE_TTL_SEC, renewalOwner: "manager", note: "manager's session LEDGER (P2 item 6): the dedicated sessions-bucket `session.<id>` rows and NOTHING else - no session rail of any shape. Standing because SPEC 13.6 makes it the durable revocation authority that must survive the serving endpoint; the manager re-mints for the SAME nkey on the half-TTL loop (the goal-writer precedent)" },
40145
40145
  "run-driver": { class: "standing-renewable", defaultTtlSeconds: STANDING_RENEWABLE_TTL_SEC, renewalOwner: "manager", note: "one workflow run's driver, per takeover attempt (SPEC 14.6): the hosting manager mints it when it takes the run over and re-mints for the SAME nkey on renewal; a new takeover mints a new one" },
40146
+ "run-mediator": { class: "standing-renewable", defaultTtlSeconds: STANDING_RENEWABLE_TTL_SEC, renewalOwner: "manager", note: "trusted workflow host operations, bound to one run and attempt; kept on the hosting process's connection" },
40146
40147
  "run-operator": { class: "one-shot", defaultTtlSeconds: 60, note: "one served run-status / run-ps / run-answer call (SPEC 14.3): the hosting manager mints it per call on its own connection, never the serve rails; 60s bounds a copied cred to a minute" },
40147
40148
  "endpoint-evictor": { class: "one-shot", defaultTtlSeconds: 60, note: "one re-registration's verify-evict window (P2 item 3): a scoped delivery-admin caller that kicks+verifies the SUPERSEDED serve family before the epoch advances; 60s bounds a copied cred to a minute" },
40148
40149
  "remote-manager": { class: "standing-renewable", defaultTtlSeconds: STANDING_RENEWABLE_TTL_SEC, renewalOwner: "auth-service", note: "the scoped remote manager lifecycle: own lease/presence plus same-owner agent provisioning; issued only by the typed supervise protocol, never by cotal mint or a raw view/profile string" },
@@ -63185,7 +63186,7 @@ config(en_default());
63185
63186
 
63186
63187
  // ../connector-core/dist/docs-bundle.generated.js
63187
63188
  var DOCS_BUNDLE = {
63188
- "version": "0.47.1",
63189
+ "version": "0.48.0",
63189
63190
  "generatedFrom": "docs/*.md + SPEC.md + spec/cotal-lang.md + spec/cotal.schema.json",
63190
63191
  "pages": [
63191
63192
  {
@@ -63228,7 +63229,7 @@ var DOCS_BUNDLE = {
63228
63229
  "title": "Identity",
63229
63230
  "kind": "Concept (informative)",
63230
63231
  "summary": "Who can do what on a mesh, and how it is enforced.",
63231
- "body": "# Identity\n\n> **Concept** (informative) \xB7 **For:** operators and implementers \xB7 **Normative:** [SPEC \xA72](../SPEC.md#2-identity), [\xA79](../SPEC.md#9-nats--jetstream-security-and-authorization), [\xA710](../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 \xA79](../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 \xA72](../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 \xA73](../SPEC.md#3-subject-layout), [\xA75](../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`cotal mint <name> --profile <agent|observer|admin>` is the out-of-band path; spawn calls\nthe same library ([CLI](cli.md)). Minting static creds is a **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. Its read-only presence and channel-registry watches may create, inspect, and delete only their own client-managed ordered consumers; those cleanup grants cannot delete KV records or streams. |\n| **observer** | Read-only chat + presence; DMs invisible. What `cotal console` runs. |\n| **admin** | Elevated *read-only* god-view: sees DMs and anycast live, still writes nothing. A deliberate opt-in (`cotal web`). |\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's driver, minted per takeover attempt: its own journal subject and replay durable, its run's records, the timer schedule at its own coordinates, and the manager's lifecycle commands as the run's caller; endpoint-wide on the checkpoint plane and the store reads, which [workflows](workflows.md#what-is-on-the-wire) names as its residual. |\n| **run-operator** | One served run read, or one half of an answer, minted per call: a read holds the records walk and one run's replay; the answering half is minted for one checkpoint token and holds that pause's answer record and settle alone. |\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 \xA79](../SPEC.md#9-nats--jetstream-security-and-authorization) items 1\u20135).\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. 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\n**The flow.** Each person runs `cotal login --idp <url>` once per machine. After that,\nany command works: cached IdP session \u2192 fresh IdP proof per connect (so IdP-side\nrevocation bites here too) \u2192 the configured exchange turns it into a short-lived Cotal bearer \u2192\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>`; a bare grant is the full envelope (all\nchannels, may spawn), and `--allow-subscribe` / `--allow-publish` / `--scope` narrow it.\nNo ledger row, no access; there is no allow-by-default.\n\n**One auth service per space** hosts both halves: the NATS auth callout and the token\nexchange. 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\nThe public listener has a closed surface: `GET /health`, `GET /jwks`, `POST /exchange`, and\n`GET /.well-known/cotal-mesh`; every other path is 404. It does **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. Elevated `view` exchanges stay loopback-only.\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.\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 \xA713.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\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) and refreshes ahead of each expiry. Rows are runtime grants: every start rotates\nthe secret, every stop or despawn revokes the row, so a non-running agent holds no\nstanding authority. Manifest deploys (`up -f`) stamp the logged-in owner into the launch,\nso 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. If the auth service is unreachable or the\nstanding-authority revoke fails, the 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\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.\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`. `cotal web` and\n`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). Views exist\nonly on a signed-in human exchange (an agent's managed exchange never mints one), are\nauthorized against the fresh ledger row at every connect, and expire with the bearer, so\nnarrowing or revoking a grant bites within minutes here too.\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 \u2192 activate \u2192\nrenew**. 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.\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\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## 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\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, and the minted Cotal bearer is capped to the\n upstream proof's remaining lifetime.\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\n## Joining\n\nA single **join link** carries server, auth, and space\n([SPEC \xA710](../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 \u2026`. Agents: `COTAL_LINK=\u2026 ` 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, which is never persisted, so no\n running process re-signs them: 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.\n- **Static agent creds are long-lived; the machinery's are not.** One-shot command creds\n expire in minutes and the standing daemon creds in 24h with the manager renewing them\n (`cotal doctor auth` is the one diagnosis and repair surface). But a static *agent*\n cred has no TTL yet: `cotal_despawn` cuts a session, not a credential, and a\n compromised agent that copied its creds can reconnect until the signing key is\n rotated. Per-user-auth spaces close this: bearers live minutes, `cotal actor revoke`\n denies the next exchange and the next connect and evicts the principal's live\n 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 \xA711](../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"
63232
+ "body": "# Identity\n\n> **Concept** (informative) \xB7 **For:** operators and implementers \xB7 **Normative:** [SPEC \xA72](../SPEC.md#2-identity), [\xA79](../SPEC.md#9-nats--jetstream-security-and-authorization), [\xA710](../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 \xA79](../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 \xA72](../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 \xA73](../SPEC.md#3-subject-layout), [\xA75](../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`cotal mint <name> --profile <agent|observer|admin>` is the out-of-band path; spawn calls\nthe same library ([CLI](cli.md)). Minting static creds is a **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. Its read-only presence and channel-registry watches may create, inspect, and delete only their own client-managed ordered consumers; those cleanup grants cannot delete KV records or streams. |\n| **observer** | Read-only chat + presence; DMs invisible. What `cotal console` runs. |\n| **admin** | Elevated *read-only* god-view: sees DMs and anycast live, still writes nothing. A deliberate opt-in (`cotal web`). |\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 and one run's replay; the answering half is minted for one checkpoint token and holds that pause's answer record and settle alone. |\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 \xA79](../SPEC.md#9-nats--jetstream-security-and-authorization) items 1\u20135).\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. 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\n**The flow.** Each person runs `cotal login --idp <url>` once per machine. After that,\nany command works: cached IdP session \u2192 fresh IdP proof per connect (so IdP-side\nrevocation bites here too) \u2192 the configured exchange turns it into a short-lived Cotal bearer \u2192\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>`; a bare grant is the full envelope (all\nchannels, may spawn), and `--allow-subscribe` / `--allow-publish` / `--scope` narrow it.\nNo ledger row, no access; there is no allow-by-default.\n\n**One auth service per space** hosts both halves: the NATS auth callout and the token\nexchange. 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\nThe public listener has a closed surface: `GET /health`, `GET /jwks`, `POST /exchange`, and\n`GET /.well-known/cotal-mesh`; every other path is 404. It does **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. Elevated `view` exchanges stay loopback-only.\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.\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 \xA713.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\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) and refreshes ahead of each expiry. Rows are runtime grants: every start rotates\nthe secret, every stop or despawn revokes the row, so a non-running agent holds no\nstanding authority. Manifest deploys (`up -f`) stamp the logged-in owner into the launch,\nso 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. If the auth service is unreachable or the\nstanding-authority revoke fails, the 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\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.\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`. `cotal web` and\n`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). Views exist\nonly on a signed-in human exchange (an agent's managed exchange never mints one), are\nauthorized against the fresh ledger row at every connect, and expire with the bearer, so\nnarrowing or revoking a grant bites within minutes here too.\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 \u2192 activate \u2192\nrenew**. 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.\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\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## 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\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, and the minted Cotal bearer is capped to the\n upstream proof's remaining lifetime.\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\n## Joining\n\nA single **join link** carries server, auth, and space\n([SPEC \xA710](../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 \u2026`. Agents: `COTAL_LINK=\u2026 ` 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, which is never persisted, so no\n running process re-signs them: 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.\n- **Static agent creds are long-lived; the machinery's are not.** One-shot command creds\n expire in minutes and the standing daemon creds in 24h with the manager renewing them\n (`cotal doctor auth` is the one diagnosis and repair surface). But a static *agent*\n cred has no TTL yet: `cotal_despawn` cuts a session, not a credential, and a\n compromised agent that copied its creds can reconnect until the signing key is\n rotated. Per-user-auth spaces close this: bearers live minutes, `cotal actor revoke`\n denies the next exchange and the next connect and evicts the principal's live\n 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 \xA711](../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"
63232
63233
  },
63233
63234
  {
63234
63235
  "slug": "agent-files",
@@ -63459,7 +63460,7 @@ var DOCS_BUNDLE = {
63459
63460
  "title": "Workflow runs",
63460
63461
  "kind": "Concept (informative)",
63461
63462
  "summary": "A workflow run is a program that coordinates agents over hours or days and survives the process that started it.",
63462
- "body": "# Workflow runs\n\n> **Concept** (informative) \xB7 **For:** people writing a durable multi-agent workflow, and implementers hosting one \xB7 **Normative:** [SPEC \xA714](../SPEC.md#14-workflow-runs-v05) and the language reference [`spec/cotal-lang.md`](../spec/cotal-lang.md)\n\nA **workflow run** is a program that coordinates agents over hours or days and survives the\nprocess that started it. The program is written in **Cotal Lang**, a small subset of JavaScript in\nwhich every interaction with the world is one of a dozen **effects** (`spawn`, `turn`, `ask`,\n`checkpoint`, `sleep`, `wait`, `notify`, `monitor`, and the four concurrency scopes) and everything\nelse is ordinary, pure JavaScript. Every effect is written into the run's **step journal** before\nit is performed and settled after, keyed by where in the program it happened rather than by when,\nso a run that dies is resumed on any host by **re-running the program from the top** with recorded\neffects returning their recorded results. Nothing about the interpreter is ever serialized: the\njournal and the program are the whole state.\n\n## A first program\n\n```js\nconst planner = await spawn(\"planner\")\nconst builder = await spawn(\"builder\", { worktree: \"wt-1\" })\n\nconst plan = await ask(planner, { name: \"plan\", schema: { steps: \"array\" } })\nconst ok = await checkpoint(\"approve-plan\", \"Approve the plan?\", { timeout: \"4h\", onExpiry: \"proceed\" })\nif (ok.status !== \"resolved\") {\n await notify([planner], { decision: \"approve-plan\", outcome: \"expired\" })\n}\n\nconst r = await turn(builder, { name: \"build\", deadline: \"30m\" })\nif (r.status === \"blocked\") {\n await turn(planner, { name: \"unblock\" })\n}\n\nconst outcome = await race({\n reply: () => wait(replied(builder), { timeout: \"20m\" }),\n giveUp: () => sleep(\"1h\"),\n}, { name: \"await-or-move-on\" })\nlog(\"outcome\", outcome.index)\n```\n\nRead it as the flowchart it is. `spawn` brings agents in; `ask` is the narrow case where the\nprogram itself needs a value (`schema` is a record the program hands the handler unchanged; the\nlanguage hashes it and gives it no meaning, and the handlers in this repository enforce it as the\nshorthand of the language reference \xA76.5);\n`checkpoint` is a durable pause a human resolves from anywhere, raced against a durable timer; `turn`\nwakes an agent for one turn and returns how it yielded; `race` runs two branches and keeps the one\nwhose recorded clock is earliest. Agents talk to each other in channels as they always do; the\nprogram never speaks in a channel, and the one thing it can put in front of an agent (`notify`) is a\nbounded decision record, not prose.\n\n## The mental model\n\n- **Pure code is JavaScript.** Loops, records, arrays, closures, template literals, destructuring,\n `try`/`catch`, arithmetic, `switch`, compound assignment, optional chaining, spread and rest: what\n you would write anyway, with the parts that hide effects or make meaning depend on the host removed\n (`class`, `this`, `new`, `for...in`, `==`, labels, regex literals, `Math`/`Date`/`JSON`, promises,\n generators). Every refusal names its code and the edit that fixes it. The builtins are a short list\n (`keys`, `map`, `sort`, `json.stringify`, `now()`, `random()`), and arrays, strings and numbers\n answer their usual methods (`xs.map`, `s.trim()`, `n.toFixed()`) and nothing outside that table.\n Records and arrays you build are yours to change until they cross an effect boundary; a member you\n do not own, a host prototype, or a value another branch built is refused with a code, never a\n surprise.\n- **Every effect is journalled and hashed.** A step is keyed `(scope path, kind, name, occurrence)`\n and its inputs are hashed. Reorder your program, add a step, rename a variable: recorded steps\n still match. Change what a step asks (a checkpoint's prompt, a sleep's duration, a turn's\n deadline) and the resume stops with a **divergence** naming the step, rather than replaying an\n answer to a question the program no longer asks.\n- **Concurrency is visible.** `parallel`, `race`, `fanOut` and `conclave` are the only ways to do\n two things at once, each branch gets its own journal namespace, and the scope writes its own\n entry saying how it settled: which arm won a race is a recorded fact, decided by the arms'\n recorded clocks and declaration order, never by a scheduler. A branch may not write to anything\n declared outside it; return the value and read it out of the scope's result.\n- **Time and randomness are tamed.** `now()` is the branch's run clock, the end of the last effect\n it awaited; `random()` is a seeded stream derived per scope. Both replay identically.\n- **Values freeze at the boundary.** What crossed into or out of an effect is what the journal\n recorded, and it cannot change afterwards; build a new value.\n- **The journal is the debugger.** Every entry carries its key, its inputs' hash, its outcome and\n its timing, and every error is in the program's own coordinates. A run can be **simulated** with a\n scripted handler and **dry-run** to a plan before it touches an agent. The simulator is\n discrete-event: timed effects park at their wake times and are delivered in wake order on one\n virtual clock, so concurrent branches accumulate the durations they wrote and a simulated `race`\n is decided by the same rule a live handler produces (least recorded clock, ties by declaration\n order). A `sleep(\"1m\")` arm beats a `sleep(\"1h\")` arm whatever their declaration order.\n\nFull rules, with every code: [`spec/cotal-lang.md`](../spec/cotal-lang.md).\n\n## Continuing a run\n\n**Resume** is re-execution: the driver replays the journal, the program runs from the top, recorded\nsteps return instantly, and the first unrecorded step is performed live. It refuses a journal that\nbelongs to another run, a pin that differs from the recorded ones, and a different language version.\n\n**Migrate** moves a run onto edited source. A dry walk of the new program over the recorded journal\nfinds every recorded step the edit changed (a divergence) and every one it no longer reaches (an\norphan), and the orphan table says what each means: a removed `sleep` is nothing, a removed `turn`\nalready happened, a removed `spawn` is a live agent you must adopt or release, a removed resolved\n`checkpoint` is a human decision you must explicitly discard. The decision is filed as a\n`migration` record with the actor's name on it. An adopted seat (`--adopt <name>#<uid>`) goes to\nthe edited program's next `spawn` of that persona, which returns the recorded handle and mints\nnothing, so the agent keeps its identity, its worktree and its turn history across the edit. A\nreleased seat (`--release <name>#<uid>`) is despawned when the migration commits, through the same\ndischarge a cancelled branch's seat leaves by, so the record never claims a release nothing did.\nThe spawn that adopts a seat binds the orphaned spawn's goal as its own, so a resume of that step\nreads the same seat back and a cancellation of it despawns the seat it holds.\n\n**Fork** starts a new run from a named step of an old one, copying the prefix under the parent's\npins (seed included, so the copied history's pure draws are the same draws). The child is a new run\nunder a new id whose record names the parent and the cut step (`forkedFrom`); the parent is\nuntouched. A spawn inside the copied prefix is honoured by its `onFork`: `\"adopt\"` copies it, and\nthe child shares the parent's agent (the manager shows that seat one turn at a time across both\nruns); `\"respawn\"`, the default, would mint a fresh identity the copied turns do not address, so\nthis host refuses that cut (L5019) rather than rewriting the parent's history.\n\n## Operating a run\n\nThe manager hosts runs. `cotal run start` hands the program to the manager of the resolved mesh\n(the usual `--space` / `--server` / `--creds` flags), which validates it, mints the run id, drives\nit in its own process, and answers with the id once the run is recorded. The terminal is free the\nmoment the id prints; the run continues on the manager through every pause, and a manager restart\ntakes back every run it had recorded running, from the journal, under the next epoch. `resume`\nnames a run the manager recorded and is refused while the manager is already driving it. `ps` and\n`journal` read; `answer` resolves an open checkpoint, or an open `ask` attempt, from any terminal\nor agent that holds the `run` capability.\n\n```bash\ncotal run start --file build.cotal.js # the manager starts it; the minted id is printed\ncotal run ps # list run records: state, holder, lineage\ncotal run journal run-3f2a90c41b7e0d5a6c884e19b02df4a1 # print the durable step journal\ncotal run resume run-3f2a90c41b7e0d5a6c884e19b02df4a1 # the manager takes the run back\ncotal run answer run-3f2a90c41b7e0d5a6c884e19b02df4a1 \"/checkpoint:approve#0\" --value '\"yes\"'\n```\n\nA program that does not validate is refused before anything is recorded, with every problem in the\nanswer as the validator would print it. The driver records the program beside the run, so `resume`\ntakes the run id alone and the manager reads the source back; an edited program is a `migrate` or a\n`fork`, never a resume. An answer is recorded under the answerer the manager knows from the\ncaller's credential: a managed agent by its name, anyone else by their principal. The request\ncarries no name. An agent with `capabilities: [run]` has the same five verbs as the `cotal_run`\ntool ([MCP tools](mcp-tools.md)), so a program can be written and started from inside a session.\nA `start` or `resume` answers once the run's record is written, within a bounded wait; a manager\nthat is still taking back a predecessor's runs at boot refuses both with `unavailable`, and a\nretry a moment later is the whole remedy.\n\n`--local` drives the run in this process instead: `start`, `resume` and `answer` exit when the\ndrive settles, `--by <who>` names the answerer, and `cotal run resume <runId> --local --file\n<program>` is how a run with no recorded program, or a run on a bare broker with no manager, is\ncontinued. On a static mesh the local drive mints the run's own credential from the folder's\ntrust material, so it runs from the mesh's project folder. A user-auth mesh runs no programs\nyet, hosted or local: the manager refuses the family by name, since a hosted run's seats would be\nspawned under the static owner, which a user mesh refuses, and a user bearer holds no run rows.\nA run whose step was refused (L5016) stays held; a\nresume on a host that can perform the step performs it live and continues from there.\n`journal` prints what an open pause asks beneath its step key, which is the address `answer` takes\nback. Checkpoint expiry rides the mediated timer writer, which the delivery daemon pumps on a live\nmesh; on a bare broker a pause still resolves, it just cannot expire.\n\n## What is on the wire\n\nThe run's wire footprint is [SPEC \xA714](../SPEC.md#14-workflow-runs-v05):\n\n| Thing | Where | What it is |\n| --- | --- | --- |\n| the run | `run.<endpoint>.<runId>` record | the resolved **pins** (seed, logical epoch, budgets, language version) on the immutable half; holder, lease and `journalHigh` on the status half |\n| the program | `program.<endpoint>.<runId>` record | the source the run was started from, verbatim, written once by the driver that pinned the run; what a resume reads and what a migration is measured against |\n| the step journal | `WFJ_<space>` stream, one subject per run | append-only, no age eviction, no Direct Get; every append fenced by the run subject's own sequence; takeover is replay-then-activate |\n| a checkpoint answer | `answer.<endpoint>.<token>.<answerId>` | the payload beside the one-use settle fact; the settle names the answer it accepted |\n| a notice | `notice.<endpoint>.<runId>.<addresseeId>.<noticeId>` | one bounded decision told to one agent, rendered ahead of its next turn |\n| a migration | `migration.<endpoint>.<runId>.<migrationId>` | the report and who applied it, keyed by the report's own digest |\n\nA run's **driver** connects on a credential of its own, the `run-driver` profile, minted for one\nrun and one takeover attempt. Pinned to the run: publish on its own journal subject and its own\nreplay durable, its `run`, `program`, `notice` and `migration` records, the timer schedule at its\nown instance and epoch, and the manager's lifecycle commands as the run's own caller. Wider than\nthe run, and named as the profile's residual: the checkpoint records and settle facts of the whole\nendpoint (a pause is keyed by a token that does not exist at mint), the point reads of the records,\nfact, timer and chat stores (a KV read is one verb on the whole backing stream, and a matched\nmessage is re-read by sequence the same way), a wait's own durable on the chat stream (named per\nstep, so the consumer rows are stream-scoped), and the channel and membership registries a\nconclave writes. It holds no consumer on the records store, so it lists its\nnotices and migrations by walking the store one message at a time, and it cannot speak on a\nchannel, read another run's journal, or file an answer. A served read rides a one-shot\n`run-operator` credential minted for that one call, holding the records walk and the named run's\nreplay and nothing it can write. An answer is two such calls: the read that finds the open pause,\nthen a second credential minted for that pause's token alone, holding its answer record and its\ncheckpoint settle and no other pause's. `cotal run --local` mints the same profiles for itself on\na static mesh, one per connection.\n\n## What ships today\n\nThe language, its validator, interpreter, simulator and dry run are `@cotal-ai/lang`\n(`packages/lang`), usable in-process with your own effect handler and with no broker: `validate(src)`,\nthen `run(src, { runId, handler })`, and `resume(src, journal, { runId, pins, handler })` to pick a\nrun up from its journal (the package README has the snippet, with `SimHandler` as the handler). That\nis the in-process route, yours to drive with your own handler; a run the driver starts executes on\nthe compiled engine, as the engine paragraph below says. The wire\nsubstrate of \xA714 (the `WFJ_<space>` stream, the five record kinds, the activation barrier, the\nper-run grants) is in `@cotal-ai/core`, and the run driver, journal store, migrate and fork are\n`@cotal-ai/runtime` (`implementations/runtime`). On the mesh handler, `sleep`, `checkpoint`,\n`wait(message(...))`, `wait(idle(...))`, `wait(down(...))`, `wait(replied(...))`, `notify`,\n`spawn`, `conclave`, `ask`, `monitor` and `turn` are durable.\n`spawn` is\nthe manager's spawn action submitted under the step's own identity: the goal binds under the step's\nrequest id, so a resumed run re-attaches to the same seat instead of allocating a second one, a\nfailed or refused spawn is catchable as L4002 with the manager's recorded reason, and a spawn on a\nrace branch that loses is despawned by the run's own cancellation sweep. `permits` are the budgets\nthis host meters: `turns`, how many turns the run may dispatch to the agent, and `wallClock`, a\nduration from the spawn after which no turn is admitted. The turn that would exceed one is the\ncatchable L4001 (kind `permit-turns` or `permit-wall-clock`; a deadline the remaining wall clock\ncannot hold counts as exceeding it), an adopted run counts the turns its journal recorded, and a\nbudget the host has no meter for, such as `tokens` or `spend`, is refused at the spawn rather than\naccepted and ignored. `supervise` is the restart policy this host asks the manager to enforce:\n`restarts`, how many in-window process deaths may come back under the same handle, and `window`,\nthe duration those deaths are counted in (default `10m`). The manager restarts the process in\nplace under the same name, lifecycle uid, persona, worktree and permits; `monitor` does not fire\nfor a restart, and `wait(down)` fires only when the seat is gone for good. Spending the budget\nretires the seat, and the next `turn` is the catchable L4002. A policy this host cannot enforce\n(an unknown key, a user-mode seat, or a runtime that cannot respawn a name in place) is refused\nat the spawn rather than accepted and ignored. `conclave` joins its\nmembers to a real channel as durable membership rows: the channel derives from the step's own\nrequest id when the program names none (a program-named channel is borrowed, never torn down, and\na membership that predates the conclave survives its close), each member handle resolves to its\nprincipal through the seat's own presence row (an absent member is catchable as L4002), and a\nconclave cancelled on a losing branch is released by the same cancellation sweep. `ask` parks one\ncheckpoint-plane pause per attempt, answered through `cotal run answer` as a checkpoint is, and\ntells the agent through the same relay `turn` uses: one relay per attempt under the attempt's own\ntoken, carrying the schema, the attempt count, the deadline and the previous refusal, which the\nseat's connector renders as the record wanted and the command that answers it. An ask addresses\nan agent the run spawned (anything else refuses before an attempt opens), a resumed attempt tells\nthe seat nothing twice, and a seat gone at the relay is L4002. On the pause itself:\nthe shorthand of the language reference \xA76.5 is enforced (an unreadable schema is L4022), a\nnon-conforming answer costs one attempt and its refusal reason is recorded on the entry for the\nanswerer to read, exhausted attempts (default one) are the catchable L4006, and so is the one\nabsolute deadline for the whole ask passing with no conforming record (its kind is `ask-deadline`).\n`checkpoint` binds what it asks on its own entry, so `cotal run journal` prints the question under\nthe step key an answer is addressed by while the pause is open: the address alone left whoever was\nasked reading the source to find out what \"approve\" meant. An `escalate` addressed to an agent this\nrun spawned is relayed to that seat through the same turn relay an `ask` uses, carrying the prompt\nand the token to answer under; a `to` naming anyone else is a person, and their pause stays the\none anybody can answer, with the addressee recorded and rendered beside the question.\n`monitor` registers interest in an agent, and the\nregistration is the journal entry itself, carrying the handle it registered: monitoring an agent\nthat is already dead succeeds, and the death is the wait's to observe. `wait(down(...))` observes\na monitored agent, and refuses one the run never performed `monitor` on. It reads the death off presence liveness, the\nsame witness a conclave join resolves members through: the value carries the handle, the reason\n(`lapsed` when nothing live holds the name any more, `superseded` when a live row holds it under\na different incarnation) and the time of observation, a wait that begins after the death resolves\nat once, and a timeout resolves null on one absolute deadline a resumed run re-attaches to.\n`turn` wakes one seat for one host turn through the manager as a pull-shaped relay: the run\nsubmits the turn under the step's own identity, the manager holds it as a goal pinned to the\nseat's incarnation, and the seat pulls it under its own reach ahead of its next host turn, so\nnothing is pushed into a session mid-thought. The payload the seat reads names the run and the\nstep and carries the rendered run context, plus any pending notices addressed to it, which the\nturn consumes. The seat yields through `cotal_yield` (`done`, `blocked`, or `handoff` with an\naddressee), and ending its host turn yields `done` for every turn it was shown. A `handoff` names\nanother seat the same run spawned: the next `turn` in the same scope to that seat records the\nlink, a handoff to a name the run never spawned is the catchable L4005, and one to a seat bound\nto a different worktree is L4004. The deadline elapsing before any yield is the catchable L4003:\nthe acceptance names the instant, the manager's goal-bound hold denies at it, and the run arms its\nown pause on that same instant, so either side outliving the other still converges on the same\nanswer. A seat that dies mid-turn is read off its own presence row by the run itself and is the\ncatchable L4002, and a death the manager marked on the deadline terminal reads the same way. Two\nturns on one seat, from two branches or from two runs, reach it one at a time: the language\ndispatches the second when the first settles, and the manager shows a seat the oldest unsettled\nturn alone. On an auth mesh the relay needs no extra grant: every spawned seat's baseline\ncredential carries its own pull and yield rows, the run driver's operator instrument carries the\nturn request, and the manager arms the deadline hold over its own serve grant and expires it\nitself once due. An accept the manager cannot finish is unwound to a failed terminal on the goal\nit bound, and a retry of that submission is refused naming the terminal rather than accepted a\nsecond time.\n`wait(replied(...))` observes those turns from another branch: a completed turn is a reply, and\nthe wait resolves with the observation record (the handle, the yield's status and note, the\nyield's own stamp). It reads as a level, the way `wait(down)` does: a reply that already exists\nresolves the wait at once, and two replies resolve to the latest by the yield's stamp. A denied\nor cancelled turn is never a reply, so an unanswered wait rides its own mediated timeout to\n`null`, and a handle the run never spawned or turned refuses loudly, since only this run's turns\nare observable. A turn the run itself ended without an accepted yield (its deadline, a\ncancellation, a refused handoff) is never a reply, whatever the seat yields to the relay later.\nA `spawn` may bind its agent to a **logical worktree** (`spawn(\"builder\", { worktree: \"wt-1\" })`):\nthe handle carries the id, and the run enforces the one rule the language states about it: two\nagents never share a worktree concurrently. The validator rejects the literal case up front\n(L3022: two branches of one concurrent scope spawning into one literal worktree, named branch\nfunctions included), and the runtime guards the rest, computed ids included: a spawn claims its\ntree before it submits, so a second spawn into a tree held by a live seat or by a spawn still\nbringing one up is the catchable L4008, a spawn that ends without a handle gives the tree back,\nand the tree is reusable the moment a holder's presence row is gone, so a discharged race loser\nor a crashed seat releases its tree with no bookkeeping. A spawn the endpoint refuses at accept\nis the catchable L4000 (L4001 when the refusal is the endpoint's seat capacity), and one whose\nseat never came up is L4002. A turn handoff across worktrees is the L4004 described above. Recovery keeps these honest: a resumed run\nreseeds its roster, holders and handoff memos from its own journal, and the driver re-issues any\nrecorded-but-undischarged cancellation at adoption, before the engine performs a new step, so a\nloser a crash left alive does not keep its seat or its tree while the resumed run works on. The\nsame sweep withdraws a cancelled branch's undelivered notices: a notice waits on the run for its\naddressee's next turn, so a decision the run cancelled would otherwise arrive at an agent with\nnothing to distinguish it from one that stood.\n\nEvery effect the language defines performs on the mesh handler; nothing is refused as\nnot-yet-durable any more. The operator surface over the driver is `cotal run`; the section above has the verbs.\n\n**Two engines, and which one runs your program.** The tree-walker is language version `1` and the\ncompiled engine is version `2`, two languages rather than two speeds of one (`spec/cotal-lang.md`\n\xA78.4 lists what differs). The driver hosts both: **every run a driver starts is stamped `2` and\nexecuted by the compiled engine**. The program runs in its own locked-down worker thread with\nnothing in its global scope, while the effects and the durable journal stay in the driver's process,\nbridged over a message port. No socket or credential enters the isolate holding the program,\nand **every version-`1` record keeps replaying on the walker**, which is the walker's job. The\ndriver serves a declared set of versions, and a record whose version it does not serve is refused\nby name (**L5023**) with the run left untouched, instead of being replayed by whichever engine\nhappens to be present. Records do not cross between versions in either direction; the repair is to\nresume on the recorded version, or to fork.\n\n**The engine needs node 22 or newer** and refuses below it as `EngineUnavailable`, which is an\nimplementation limit and not a language error: it carries no `L` code, so there is nothing to look\nup in the catalog. It is a floor rather than a warning because the engine's frame plumbing rests on\n`AsyncLocalStorage`, and 22 is the lowest node it has been measured on. The walker has no such floor.\n"
63463
+ "body": "# Workflow runs\n\n> **Concept** (informative) \xB7 **For:** people writing a durable multi-agent workflow, and implementers hosting one \xB7 **Normative:** [SPEC \xA714](../SPEC.md#14-workflow-runs-v05) and the language reference [`spec/cotal-lang.md`](../spec/cotal-lang.md)\n\nA **workflow run** is a program that coordinates agents over hours or days and survives the\nprocess that started it. The program is written in **Cotal Lang**, a small subset of JavaScript in\nwhich every interaction with the world is one of a dozen **effects** (`spawn`, `turn`, `ask`,\n`checkpoint`, `sleep`, `wait`, `notify`, `monitor`, and the four concurrency scopes) and everything\nelse is ordinary, pure JavaScript. Every effect is written into the run's **step journal** before\nit is performed and settled after, keyed by where in the program it happened rather than by when,\nso a run that dies is resumed on any host by **re-running the program from the top** with recorded\neffects returning their recorded results. Nothing about the interpreter is ever serialized: the\njournal and the program are the whole state.\n\n## A first program\n\n```js\nconst planner = await spawn(\"planner\")\nconst builder = await spawn(\"builder\", { worktree: \"wt-1\" })\n\nconst plan = await ask(planner, { name: \"plan\", schema: { steps: \"array\" } })\nconst ok = await checkpoint(\"approve-plan\", \"Approve the plan?\", { timeout: \"4h\", onExpiry: \"proceed\" })\nif (ok.status !== \"resolved\") {\n await notify([planner], { decision: \"approve-plan\", outcome: \"expired\" })\n}\n\nconst r = await turn(builder, { name: \"build\", deadline: \"30m\" })\nif (r.status === \"blocked\") {\n await turn(planner, { name: \"unblock\" })\n}\n\nconst outcome = await race({\n reply: () => wait(replied(builder), { timeout: \"20m\" }),\n giveUp: () => sleep(\"1h\"),\n}, { name: \"await-or-move-on\" })\nlog(\"outcome\", outcome.index)\n```\n\nRead it as the flowchart it is. `spawn` brings agents in; `ask` is the narrow case where the\nprogram itself needs a value (`schema` is a record the program hands the handler unchanged; the\nlanguage hashes it and gives it no meaning, and the handlers in this repository enforce it as the\nshorthand of the language reference \xA76.5);\n`checkpoint` is a durable pause a human resolves from anywhere, raced against a durable timer; `turn`\nwakes an agent for one turn and returns how it yielded; `race` runs two branches and keeps the one\nwhose recorded clock is earliest. Agents talk to each other in channels as they always do; the\nprogram never speaks in a channel, and the one thing it can put in front of an agent (`notify`) is a\nbounded decision record, not prose.\n\n## The mental model\n\n- **Pure code is JavaScript.** Loops, records, arrays, closures, template literals, destructuring,\n `try`/`catch`, arithmetic, `switch`, compound assignment, optional chaining, spread and rest: what\n you would write anyway, with the parts that hide effects or make meaning depend on the host removed\n (`class`, `this`, `new`, `for...in`, `==`, labels, regex literals, `Math`/`Date`/`JSON`, promises,\n generators). Every refusal names its code and the edit that fixes it. The builtins are a short list\n (`keys`, `map`, `sort`, `json.stringify`, `now()`, `random()`), and arrays, strings and numbers\n answer their usual methods (`xs.map`, `s.trim()`, `n.toFixed()`) and nothing outside that table.\n Records and arrays you build are yours to change until they cross an effect boundary; a member you\n do not own, a host prototype, or a value another branch built is refused with a code, never a\n surprise.\n- **Every effect is journalled and hashed.** A step is keyed `(scope path, kind, name, occurrence)`\n and its inputs are hashed. Reorder your program, add a step, rename a variable: recorded steps\n still match. Change what a step asks (a checkpoint's prompt, a sleep's duration, a turn's\n deadline) and the resume stops with a **divergence** naming the step, rather than replaying an\n answer to a question the program no longer asks.\n- **Concurrency is visible.** `parallel`, `race`, `fanOut` and `conclave` are the only ways to do\n two things at once, each branch gets its own journal namespace, and the scope writes its own\n entry saying how it settled: which arm won a race is a recorded fact, decided by the arms'\n recorded clocks and declaration order, never by a scheduler. A branch may not write to anything\n declared outside it; return the value and read it out of the scope's result.\n- **Time and randomness are tamed.** `now()` is the branch's run clock, the end of the last effect\n it awaited; `random()` is a seeded stream derived per scope. Both replay identically.\n- **Values freeze at the boundary.** What crossed into or out of an effect is what the journal\n recorded, and it cannot change afterwards; build a new value.\n- **The journal is the debugger.** Every entry carries its key, its inputs' hash, its outcome and\n its timing, and every error is in the program's own coordinates. A run can be **simulated** with a\n scripted handler and **dry-run** to a plan before it touches an agent. The simulator is\n discrete-event: timed effects park at their wake times and are delivered in wake order on one\n virtual clock, so concurrent branches accumulate the durations they wrote and a simulated `race`\n is decided by the same rule a live handler produces (least recorded clock, ties by declaration\n order). A `sleep(\"1m\")` arm beats a `sleep(\"1h\")` arm whatever their declaration order.\n\nFull rules, with every code: [`spec/cotal-lang.md`](../spec/cotal-lang.md).\n\n## Continuing a run\n\n**Resume** is re-execution: the driver replays the journal, the program runs from the top, recorded\nsteps return instantly, and the first unrecorded step is performed live. It refuses a journal that\nbelongs to another run, a pin that differs from the recorded ones, and a different language version.\n\n**Migrate** moves a run onto edited source. A dry walk of the new program over the recorded journal\nfinds every recorded step the edit changed (a divergence) and every one it no longer reaches (an\norphan), and the orphan table says what each means: a removed `sleep` is nothing, a removed `turn`\nalready happened, a removed `spawn` is a live agent you must adopt or release, a removed resolved\n`checkpoint` is a human decision you must explicitly discard. The decision is filed as a\n`migration` record with the actor's name on it. An adopted seat (`--adopt <name>#<uid>`) goes to\nthe edited program's next `spawn` of that persona, which returns the recorded handle and mints\nnothing, so the agent keeps its identity, its worktree and its turn history across the edit. A\nreleased seat (`--release <name>#<uid>`) is despawned when the migration commits, through the same\ndischarge a cancelled branch's seat leaves by, so the record never claims a release nothing did.\nThe spawn that adopts a seat binds the orphaned spawn's goal as its own, so a resume of that step\nreads the same seat back and a cancellation of it despawns the seat it holds.\n\n**Fork** starts a new run from a named step of an old one, copying the prefix under the parent's\npins (seed included, so the copied history's pure draws are the same draws). The child is a new run\nunder a new id whose record names the parent and the cut step (`forkedFrom`); the parent is\nuntouched. A spawn inside the copied prefix is honoured by its `onFork`: `\"adopt\"` copies it, and\nthe child shares the parent's agent (the manager shows that seat one turn at a time across both\nruns); `\"respawn\"`, the default, would mint a fresh identity the copied turns do not address, so\nthis host refuses that cut (L5019) rather than rewriting the parent's history.\n\n## Operating a run\n\nThe manager hosts runs. `cotal run start` hands the program to the manager of the resolved mesh\n(the usual `--space` / `--server` / `--creds` flags), which validates it, mints the run id, drives\nit in its own process, and answers with the id once the run is recorded. The terminal is free the\nmoment the id prints; the run continues on the manager through every pause, and a manager restart\ntakes back every run it had recorded running, from the journal, under the next epoch. `resume`\nnames a run the manager recorded and is refused while the manager is already driving it. `ps` and\n`journal` read; `answer` resolves an open checkpoint, or an open `ask` attempt, from any terminal\nor agent that holds the `run` capability.\n\n```bash\ncotal run start --file build.cotal.js # the manager starts it; the minted id is printed\ncotal run ps # list run records: state, holder, lineage\ncotal run journal run-3f2a90c41b7e0d5a6c884e19b02df4a1 # print the durable step journal\ncotal run resume run-3f2a90c41b7e0d5a6c884e19b02df4a1 # the manager takes the run back\ncotal run answer run-3f2a90c41b7e0d5a6c884e19b02df4a1 \"/checkpoint:approve#0\" --value '\"yes\"'\n```\n\nA program that does not validate is refused before anything is recorded, with every problem in the\nanswer as the validator would print it. The driver records the program beside the run, so `resume`\ntakes the run id alone and the manager reads the source back; an edited program is a `migrate` or a\n`fork`, never a resume. An answer is recorded under the answerer the manager knows from the\ncaller's credential: a managed agent by its name, anyone else by their principal. The request\ncarries no name. An agent with `capabilities: [run]` has the same five verbs as the `cotal_run`\ntool ([MCP tools](mcp-tools.md)), so a program can be written and started from inside a session.\nA `start` or `resume` answers once the run's record is written, within a bounded wait; a manager\nthat is still taking back a predecessor's runs at boot refuses both with `unavailable`, and a\nretry a moment later is the whole remedy.\n\n`--local` drives the run in this process instead: `start`, `resume` and `answer` exit when the\ndrive settles, `--by <who>` names the answerer, and `cotal run resume <runId> --local --file\n<program>` is how a run with no recorded program, or a run on a bare broker with no manager, is\ncontinued. On a static mesh the local drive mints the run's own credential from the folder's\ntrust material, so it runs from the mesh's project folder. A user-auth mesh runs no programs\nyet, hosted or local: the manager refuses the family by name, since a hosted run's seats would be\nspawned under the static owner, which a user mesh refuses, and a user bearer holds no run rows.\nA run whose step was refused (L5016) stays held; a\nresume on a host that can perform the step performs it live and continues from there.\n`journal` prints what an open pause asks beneath its step key, which is the address `answer` takes\nback. Checkpoint expiry rides the mediated timer writer, which the delivery daemon pumps on a live\nmesh; on a bare broker a pause still resolves, it just cannot expire.\n\n## What is on the wire\n\nThe run's wire footprint is [SPEC \xA714](../SPEC.md#14-workflow-runs-v05):\n\n| Thing | Where | What it is |\n| --- | --- | --- |\n| the run | `run.<endpoint>.<runId>` record | the resolved **pins** (seed, logical epoch, budgets, language version) on the immutable half; holder, lease and `journalHigh` on the status half |\n| the program | `program.<endpoint>.<runId>` record | the source the run was started from, verbatim, written once by the driver that pinned the run; what a resume reads and what a migration is measured against |\n| the step journal | `WFJ_<space>` stream, one subject per run | append-only, no age eviction, no Direct Get; every append fenced by the run subject's own sequence; takeover is replay-then-activate |\n| a checkpoint answer | `answer.<endpoint>.<token>.<answerId>` | the payload beside the one-use settle fact; the settle names the answer it accepted |\n| a notice | `notice.<endpoint>.<runId>.<addresseeId>.<noticeId>` | one bounded decision told to one agent, rendered ahead of its next turn |\n| a migration | `migration.<endpoint>.<runId>.<migrationId>` | the report and who applied it, keyed by the report's own digest |\n\nA run's **driver** connects on a `run-driver` credential minted for one run and takeover\nattempt. It can append to its journal, use its replay durable, and write its own `run`, `program`,\n`notice` and `migration` records. It has no store point reads, checkpoint writes, chat consumers,\nor channel and membership registry grants.\n\nThe hosting process keeps a separate `run-mediator` connection for effects and reads. The driver\nreceives methods and data from that host; it never receives the mediator credential or connection.\nThe host checks the journal's current activation and step identity before dispatch, and checks\npause and wait authority again at each operation. Cancellation cleanup also admits losing steps\nnamed by a settled parent whose `cancel.issued` is still false. That permission allows cleanup;\nit cannot mint or rearm a cancelled pause. Wait acknowledgements consume host-held delivery\nreceipts. A recorded match can be reread only at its bound sequence and channel. A conclave's\nrecorded ownership flag must match its step-derived channel before registry writes or cleanup.\n\nThe mediator retains endpoint-wide checkpoint rights and stream-wide leader reads as trusted\nhost authority. Record reads exposed to the driver are restricted to its own run's keys. Reads\nthat decide writes remain leader-served. A read of the journal uses the run's filtered replay\ndurable, including the diagnostic for a journal with no run record.\n\nA served read uses a one-shot `run-operator` credential. An answer uses a read to find the open\npause, then a second credential pinned to that token for the answer and settlement.\n`cotal run --local` uses the same driver/mediator split. On an authenticated mesh it needs the\nlocally recorded space signer to mint both credentials; a single `--creds` file is refused.\nDirect library users supplying broker clients to `MeshHandler` are constructing a trusted effect\nhost. A hosted driver receives its closed effect interface instead.\n\nThis split confines broker credentials; it is not process isolation for injected host code.\nThe runtime and its effect host share the manager process. Workflow channel access still follows\nthe program's requested channels, without inheriting the starting caller's channel ACL. Treat\n`run` as trusted program-execution authority. The host's journal checks enforce current run and\nstep identity; they do not provide caller-scoped channel delegation.\n\nA version-1 fork can replay its settled parent history through the host. Inherited checkpoint\nidentifiers carry no authority to read, rearm or claim the parent's pauses. New child effects use\nchild-derived identifiers. The fork planner still uses the version-1 walker; planning a fork from\na version-2 run currently fails on its language-version pin and needs a separate engine-aware\nplanning implementation.\n\n\n## What ships today\n\nThe language, its validator, interpreter, simulator and dry run are `@cotal-ai/lang`\n(`packages/lang`), usable in-process with your own effect handler and with no broker: `validate(src)`,\nthen `run(src, { runId, handler })`, and `resume(src, journal, { runId, pins, handler })` to pick a\nrun up from its journal (the package README has the snippet, with `SimHandler` as the handler). That\nis the in-process route, yours to drive with your own handler; a run the driver starts executes on\nthe compiled engine, as the engine paragraph below says. The wire\nsubstrate of \xA714 (the `WFJ_<space>` stream, the five record kinds, the activation barrier, the\nper-run grants) is in `@cotal-ai/core`, and the run driver, journal store, migrate and fork are\n`@cotal-ai/runtime` (`implementations/runtime`). On the mesh handler, `sleep`, `checkpoint`,\n`wait(message(...))`, `wait(idle(...))`, `wait(down(...))`, `wait(replied(...))`, `notify`,\n`spawn`, `conclave`, `ask`, `monitor` and `turn` are durable.\n`spawn` is\nthe manager's spawn action submitted under the step's own identity: the goal binds under the step's\nrequest id, so a resumed run re-attaches to the same seat instead of allocating a second one, a\nfailed or refused spawn is catchable as L4002 with the manager's recorded reason, and a spawn on a\nrace branch that loses is despawned by the run's own cancellation sweep. `permits` are the budgets\nthis host meters: `turns`, how many turns the run may dispatch to the agent, and `wallClock`, a\nduration from the spawn after which no turn is admitted. The turn that would exceed one is the\ncatchable L4001 (kind `permit-turns` or `permit-wall-clock`; a deadline the remaining wall clock\ncannot hold counts as exceeding it), an adopted run counts the turns its journal recorded, and a\nbudget the host has no meter for, such as `tokens` or `spend`, is refused at the spawn rather than\naccepted and ignored. `supervise` is the restart policy this host asks the manager to enforce:\n`restarts`, how many in-window process deaths may come back under the same handle, and `window`,\nthe duration those deaths are counted in (default `10m`). The manager restarts the process in\nplace under the same name, lifecycle uid, persona, worktree and permits; `monitor` does not fire\nfor a restart, and `wait(down)` fires only when the seat is gone for good. Spending the budget\nretires the seat, and the next `turn` is the catchable L4002. A policy this host cannot enforce\n(an unknown key, a user-mode seat, or a runtime that cannot respawn a name in place) is refused\nat the spawn rather than accepted and ignored. `conclave` joins its\nmembers to a real channel as durable membership rows: the channel derives from the step's own\nrequest id when the program names none (a program-named channel is borrowed, never torn down, and\na membership that predates the conclave survives its close), each member handle resolves to its\nprincipal through the seat's own presence row (an absent member is catchable as L4002), and a\nconclave cancelled on a losing branch is released by the same cancellation sweep. `ask` parks one\ncheckpoint-plane pause per attempt, answered through `cotal run answer` as a checkpoint is, and\ntells the agent through the same relay `turn` uses: one relay per attempt under the attempt's own\ntoken, carrying the schema, the attempt count, the deadline and the previous refusal, which the\nseat's connector renders as the record wanted and the command that answers it. An ask addresses\nan agent the run spawned (anything else refuses before an attempt opens), a resumed attempt tells\nthe seat nothing twice, and a seat gone at the relay is L4002. On the pause itself:\nthe shorthand of the language reference \xA76.5 is enforced (an unreadable schema is L4022), a\nnon-conforming answer costs one attempt and its refusal reason is recorded on the entry for the\nanswerer to read, exhausted attempts (default one) are the catchable L4006, and so is the one\nabsolute deadline for the whole ask passing with no conforming record (its kind is `ask-deadline`).\n`checkpoint` binds what it asks on its own entry, so `cotal run journal` prints the question under\nthe step key an answer is addressed by while the pause is open: the address alone left whoever was\nasked reading the source to find out what \"approve\" meant. An `escalate` addressed to an agent this\nrun spawned is relayed to that seat through the same turn relay an `ask` uses, carrying the prompt\nand the token to answer under; a `to` naming anyone else is a person, and their pause stays the\none anybody can answer, with the addressee recorded and rendered beside the question.\n`monitor` registers interest in an agent, and the\nregistration is the journal entry itself, carrying the handle it registered: monitoring an agent\nthat is already dead succeeds, and the death is the wait's to observe. `wait(down(...))` observes\na monitored agent, and refuses one the run never performed `monitor` on. It reads the death off presence liveness, the\nsame witness a conclave join resolves members through: the value carries the handle, the reason\n(`lapsed` when nothing live holds the name any more, `superseded` when a live row holds it under\na different incarnation) and the time of observation, a wait that begins after the death resolves\nat once, and a timeout resolves null on one absolute deadline a resumed run re-attaches to.\n`turn` wakes one seat for one host turn through the manager as a pull-shaped relay: the run\nsubmits the turn under the step's own identity, the manager holds it as a goal pinned to the\nseat's incarnation, and the seat pulls it under its own reach ahead of its next host turn, so\nnothing is pushed into a session mid-thought. The payload the seat reads names the run and the\nstep and carries the rendered run context, plus any pending notices addressed to it, which the\nturn consumes. The seat yields through `cotal_yield` (`done`, `blocked`, or `handoff` with an\naddressee), and ending its host turn yields `done` for every turn it was shown. A `handoff` names\nanother seat the same run spawned: the next `turn` in the same scope to that seat records the\nlink, a handoff to a name the run never spawned is the catchable L4005, and one to a seat bound\nto a different worktree is L4004. The deadline elapsing before any yield is the catchable L4003:\nthe acceptance names the instant, the manager's goal-bound hold denies at it, and the run arms its\nown pause on that same instant, so either side outliving the other still converges on the same\nanswer. A seat that dies mid-turn is read off its own presence row by the run itself and is the\ncatchable L4002, and a death the manager marked on the deadline terminal reads the same way. Two\nturns on one seat, from two branches or from two runs, reach it one at a time: the language\ndispatches the second when the first settles, and the manager shows a seat the oldest unsettled\nturn alone. On an auth mesh the relay needs no extra grant: every spawned seat's baseline\ncredential carries its own pull and yield rows, the run driver's operator instrument carries the\nturn request, and the manager arms the deadline hold over its own serve grant and expires it\nitself once due. An accept the manager cannot finish is unwound to a failed terminal on the goal\nit bound, and a retry of that submission is refused naming the terminal rather than accepted a\nsecond time.\n`wait(replied(...))` observes those turns from another branch: a completed turn is a reply, and\nthe wait resolves with the observation record (the handle, the yield's status and note, the\nyield's own stamp). It reads as a level, the way `wait(down)` does: a reply that already exists\nresolves the wait at once, and two replies resolve to the latest by the yield's stamp. A denied\nor cancelled turn is never a reply, so an unanswered wait rides its own mediated timeout to\n`null`, and a handle the run never spawned or turned refuses loudly, since only this run's turns\nare observable. A turn the run itself ended without an accepted yield (its deadline, a\ncancellation, a refused handoff) is never a reply, whatever the seat yields to the relay later.\nA `spawn` may bind its agent to a **logical worktree** (`spawn(\"builder\", { worktree: \"wt-1\" })`):\nthe handle carries the id, and the run enforces the one rule the language states about it: two\nagents never share a worktree concurrently. The validator rejects the literal case up front\n(L3022: two branches of one concurrent scope spawning into one literal worktree, named branch\nfunctions included), and the runtime guards the rest, computed ids included: a spawn claims its\ntree before it submits, so a second spawn into a tree held by a live seat or by a spawn still\nbringing one up is the catchable L4008, a spawn that ends without a handle gives the tree back,\nand the tree is reusable the moment a holder's presence row is gone, so a discharged race loser\nor a crashed seat releases its tree with no bookkeeping. A spawn the endpoint refuses at accept\nis the catchable L4000 (L4001 when the refusal is the endpoint's seat capacity), and one whose\nseat never came up is L4002. A turn handoff across worktrees is the L4004 described above. Recovery keeps these honest: a resumed run\nreseeds its roster, holders and handoff memos from its own journal, and the driver re-issues any\nrecorded-but-undischarged cancellation at adoption, before the engine performs a new step, so a\nloser a crash left alive does not keep its seat or its tree while the resumed run works on. The\nsame sweep withdraws a cancelled branch's undelivered notices: a notice waits on the run for its\naddressee's next turn, so a decision the run cancelled would otherwise arrive at an agent with\nnothing to distinguish it from one that stood.\n\nEvery effect the language defines performs on the mesh handler; nothing is refused as\nnot-yet-durable any more. The operator surface over the driver is `cotal run`; the section above has the verbs.\n\n**Two engines, and which one runs your program.** The tree-walker is language version `1` and the\ncompiled engine is version `2`, two languages rather than two speeds of one (`spec/cotal-lang.md`\n\xA78.4 lists what differs). The driver hosts both: **every run a driver starts is stamped `2` and\nexecuted by the compiled engine**. The program runs in its own locked-down worker thread with\nnothing in its global scope, while the effects and the durable journal stay in the driver's process,\nbridged over a message port. No socket or credential enters the isolate holding the program,\nand **every version-`1` record keeps replaying on the walker**, which is the walker's job. The\ndriver serves a declared set of versions, and a record whose version it does not serve is refused\nby name (**L5023**) with the run left untouched, instead of being replayed by whichever engine\nhappens to be present. Records do not cross between versions in either direction; the repair is to\nresume on the recorded version, or to fork.\n\n**The engine needs node 22 or newer** and refuses below it as `EngineUnavailable`, which is an\nimplementation limit and not a language error: it carries no `L` code, so there is nothing to look\nup in the catalog. It is a floor rather than a warning because the engine's frame plumbing rests on\n`AsyncLocalStorage`, and 22 is the lowest node it has been measured on. The walker has no such floor.\n"
63463
63464
  }
63464
63465
  ],
63465
63466
  "spec": {
package/dist/index.js CHANGED
@@ -14821,7 +14821,7 @@ import { isConcreteChannel as isConcreteChannel3, channelInAllow as channelInAll
14821
14821
 
14822
14822
  // ../connector-core/dist/docs-bundle.generated.js
14823
14823
  var DOCS_BUNDLE = {
14824
- "version": "0.47.1",
14824
+ "version": "0.48.0",
14825
14825
  "generatedFrom": "docs/*.md + SPEC.md + spec/cotal-lang.md + spec/cotal.schema.json",
14826
14826
  "pages": [
14827
14827
  {
@@ -14864,7 +14864,7 @@ var DOCS_BUNDLE = {
14864
14864
  "title": "Identity",
14865
14865
  "kind": "Concept (informative)",
14866
14866
  "summary": "Who can do what on a mesh, and how it is enforced.",
14867
- "body": "# Identity\n\n> **Concept** (informative) \xB7 **For:** operators and implementers \xB7 **Normative:** [SPEC \xA72](../SPEC.md#2-identity), [\xA79](../SPEC.md#9-nats--jetstream-security-and-authorization), [\xA710](../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 \xA79](../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 \xA72](../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 \xA73](../SPEC.md#3-subject-layout), [\xA75](../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`cotal mint <name> --profile <agent|observer|admin>` is the out-of-band path; spawn calls\nthe same library ([CLI](cli.md)). Minting static creds is a **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. Its read-only presence and channel-registry watches may create, inspect, and delete only their own client-managed ordered consumers; those cleanup grants cannot delete KV records or streams. |\n| **observer** | Read-only chat + presence; DMs invisible. What `cotal console` runs. |\n| **admin** | Elevated *read-only* god-view: sees DMs and anycast live, still writes nothing. A deliberate opt-in (`cotal web`). |\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's driver, minted per takeover attempt: its own journal subject and replay durable, its run's records, the timer schedule at its own coordinates, and the manager's lifecycle commands as the run's caller; endpoint-wide on the checkpoint plane and the store reads, which [workflows](workflows.md#what-is-on-the-wire) names as its residual. |\n| **run-operator** | One served run read, or one half of an answer, minted per call: a read holds the records walk and one run's replay; the answering half is minted for one checkpoint token and holds that pause's answer record and settle alone. |\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 \xA79](../SPEC.md#9-nats--jetstream-security-and-authorization) items 1\u20135).\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. 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\n**The flow.** Each person runs `cotal login --idp <url>` once per machine. After that,\nany command works: cached IdP session \u2192 fresh IdP proof per connect (so IdP-side\nrevocation bites here too) \u2192 the configured exchange turns it into a short-lived Cotal bearer \u2192\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>`; a bare grant is the full envelope (all\nchannels, may spawn), and `--allow-subscribe` / `--allow-publish` / `--scope` narrow it.\nNo ledger row, no access; there is no allow-by-default.\n\n**One auth service per space** hosts both halves: the NATS auth callout and the token\nexchange. 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\nThe public listener has a closed surface: `GET /health`, `GET /jwks`, `POST /exchange`, and\n`GET /.well-known/cotal-mesh`; every other path is 404. It does **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. Elevated `view` exchanges stay loopback-only.\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.\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 \xA713.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\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) and refreshes ahead of each expiry. Rows are runtime grants: every start rotates\nthe secret, every stop or despawn revokes the row, so a non-running agent holds no\nstanding authority. Manifest deploys (`up -f`) stamp the logged-in owner into the launch,\nso 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. If the auth service is unreachable or the\nstanding-authority revoke fails, the 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\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.\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`. `cotal web` and\n`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). Views exist\nonly on a signed-in human exchange (an agent's managed exchange never mints one), are\nauthorized against the fresh ledger row at every connect, and expire with the bearer, so\nnarrowing or revoking a grant bites within minutes here too.\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 \u2192 activate \u2192\nrenew**. 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.\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\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## 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\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, and the minted Cotal bearer is capped to the\n upstream proof's remaining lifetime.\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\n## Joining\n\nA single **join link** carries server, auth, and space\n([SPEC \xA710](../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 \u2026`. Agents: `COTAL_LINK=\u2026 ` 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, which is never persisted, so no\n running process re-signs them: 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.\n- **Static agent creds are long-lived; the machinery's are not.** One-shot command creds\n expire in minutes and the standing daemon creds in 24h with the manager renewing them\n (`cotal doctor auth` is the one diagnosis and repair surface). But a static *agent*\n cred has no TTL yet: `cotal_despawn` cuts a session, not a credential, and a\n compromised agent that copied its creds can reconnect until the signing key is\n rotated. Per-user-auth spaces close this: bearers live minutes, `cotal actor revoke`\n denies the next exchange and the next connect and evicts the principal's live\n 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 \xA711](../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"
14867
+ "body": "# Identity\n\n> **Concept** (informative) \xB7 **For:** operators and implementers \xB7 **Normative:** [SPEC \xA72](../SPEC.md#2-identity), [\xA79](../SPEC.md#9-nats--jetstream-security-and-authorization), [\xA710](../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 \xA79](../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 \xA72](../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 \xA73](../SPEC.md#3-subject-layout), [\xA75](../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`cotal mint <name> --profile <agent|observer|admin>` is the out-of-band path; spawn calls\nthe same library ([CLI](cli.md)). Minting static creds is a **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. Its read-only presence and channel-registry watches may create, inspect, and delete only their own client-managed ordered consumers; those cleanup grants cannot delete KV records or streams. |\n| **observer** | Read-only chat + presence; DMs invisible. What `cotal console` runs. |\n| **admin** | Elevated *read-only* god-view: sees DMs and anycast live, still writes nothing. A deliberate opt-in (`cotal web`). |\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 and one run's replay; the answering half is minted for one checkpoint token and holds that pause's answer record and settle alone. |\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 \xA79](../SPEC.md#9-nats--jetstream-security-and-authorization) items 1\u20135).\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. 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\n**The flow.** Each person runs `cotal login --idp <url>` once per machine. After that,\nany command works: cached IdP session \u2192 fresh IdP proof per connect (so IdP-side\nrevocation bites here too) \u2192 the configured exchange turns it into a short-lived Cotal bearer \u2192\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>`; a bare grant is the full envelope (all\nchannels, may spawn), and `--allow-subscribe` / `--allow-publish` / `--scope` narrow it.\nNo ledger row, no access; there is no allow-by-default.\n\n**One auth service per space** hosts both halves: the NATS auth callout and the token\nexchange. 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\nThe public listener has a closed surface: `GET /health`, `GET /jwks`, `POST /exchange`, and\n`GET /.well-known/cotal-mesh`; every other path is 404. It does **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. Elevated `view` exchanges stay loopback-only.\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.\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 \xA713.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\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) and refreshes ahead of each expiry. Rows are runtime grants: every start rotates\nthe secret, every stop or despawn revokes the row, so a non-running agent holds no\nstanding authority. Manifest deploys (`up -f`) stamp the logged-in owner into the launch,\nso 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. If the auth service is unreachable or the\nstanding-authority revoke fails, the 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\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.\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`. `cotal web` and\n`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). Views exist\nonly on a signed-in human exchange (an agent's managed exchange never mints one), are\nauthorized against the fresh ledger row at every connect, and expire with the bearer, so\nnarrowing or revoking a grant bites within minutes here too.\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 \u2192 activate \u2192\nrenew**. 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.\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\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## 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\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, and the minted Cotal bearer is capped to the\n upstream proof's remaining lifetime.\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\n## Joining\n\nA single **join link** carries server, auth, and space\n([SPEC \xA710](../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 \u2026`. Agents: `COTAL_LINK=\u2026 ` 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, which is never persisted, so no\n running process re-signs them: 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.\n- **Static agent creds are long-lived; the machinery's are not.** One-shot command creds\n expire in minutes and the standing daemon creds in 24h with the manager renewing them\n (`cotal doctor auth` is the one diagnosis and repair surface). But a static *agent*\n cred has no TTL yet: `cotal_despawn` cuts a session, not a credential, and a\n compromised agent that copied its creds can reconnect until the signing key is\n rotated. Per-user-auth spaces close this: bearers live minutes, `cotal actor revoke`\n denies the next exchange and the next connect and evicts the principal's live\n 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 \xA711](../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"
14868
14868
  },
14869
14869
  {
14870
14870
  "slug": "agent-files",
@@ -15095,7 +15095,7 @@ var DOCS_BUNDLE = {
15095
15095
  "title": "Workflow runs",
15096
15096
  "kind": "Concept (informative)",
15097
15097
  "summary": "A workflow run is a program that coordinates agents over hours or days and survives the process that started it.",
15098
- "body": "# Workflow runs\n\n> **Concept** (informative) \xB7 **For:** people writing a durable multi-agent workflow, and implementers hosting one \xB7 **Normative:** [SPEC \xA714](../SPEC.md#14-workflow-runs-v05) and the language reference [`spec/cotal-lang.md`](../spec/cotal-lang.md)\n\nA **workflow run** is a program that coordinates agents over hours or days and survives the\nprocess that started it. The program is written in **Cotal Lang**, a small subset of JavaScript in\nwhich every interaction with the world is one of a dozen **effects** (`spawn`, `turn`, `ask`,\n`checkpoint`, `sleep`, `wait`, `notify`, `monitor`, and the four concurrency scopes) and everything\nelse is ordinary, pure JavaScript. Every effect is written into the run's **step journal** before\nit is performed and settled after, keyed by where in the program it happened rather than by when,\nso a run that dies is resumed on any host by **re-running the program from the top** with recorded\neffects returning their recorded results. Nothing about the interpreter is ever serialized: the\njournal and the program are the whole state.\n\n## A first program\n\n```js\nconst planner = await spawn(\"planner\")\nconst builder = await spawn(\"builder\", { worktree: \"wt-1\" })\n\nconst plan = await ask(planner, { name: \"plan\", schema: { steps: \"array\" } })\nconst ok = await checkpoint(\"approve-plan\", \"Approve the plan?\", { timeout: \"4h\", onExpiry: \"proceed\" })\nif (ok.status !== \"resolved\") {\n await notify([planner], { decision: \"approve-plan\", outcome: \"expired\" })\n}\n\nconst r = await turn(builder, { name: \"build\", deadline: \"30m\" })\nif (r.status === \"blocked\") {\n await turn(planner, { name: \"unblock\" })\n}\n\nconst outcome = await race({\n reply: () => wait(replied(builder), { timeout: \"20m\" }),\n giveUp: () => sleep(\"1h\"),\n}, { name: \"await-or-move-on\" })\nlog(\"outcome\", outcome.index)\n```\n\nRead it as the flowchart it is. `spawn` brings agents in; `ask` is the narrow case where the\nprogram itself needs a value (`schema` is a record the program hands the handler unchanged; the\nlanguage hashes it and gives it no meaning, and the handlers in this repository enforce it as the\nshorthand of the language reference \xA76.5);\n`checkpoint` is a durable pause a human resolves from anywhere, raced against a durable timer; `turn`\nwakes an agent for one turn and returns how it yielded; `race` runs two branches and keeps the one\nwhose recorded clock is earliest. Agents talk to each other in channels as they always do; the\nprogram never speaks in a channel, and the one thing it can put in front of an agent (`notify`) is a\nbounded decision record, not prose.\n\n## The mental model\n\n- **Pure code is JavaScript.** Loops, records, arrays, closures, template literals, destructuring,\n `try`/`catch`, arithmetic, `switch`, compound assignment, optional chaining, spread and rest: what\n you would write anyway, with the parts that hide effects or make meaning depend on the host removed\n (`class`, `this`, `new`, `for...in`, `==`, labels, regex literals, `Math`/`Date`/`JSON`, promises,\n generators). Every refusal names its code and the edit that fixes it. The builtins are a short list\n (`keys`, `map`, `sort`, `json.stringify`, `now()`, `random()`), and arrays, strings and numbers\n answer their usual methods (`xs.map`, `s.trim()`, `n.toFixed()`) and nothing outside that table.\n Records and arrays you build are yours to change until they cross an effect boundary; a member you\n do not own, a host prototype, or a value another branch built is refused with a code, never a\n surprise.\n- **Every effect is journalled and hashed.** A step is keyed `(scope path, kind, name, occurrence)`\n and its inputs are hashed. Reorder your program, add a step, rename a variable: recorded steps\n still match. Change what a step asks (a checkpoint's prompt, a sleep's duration, a turn's\n deadline) and the resume stops with a **divergence** naming the step, rather than replaying an\n answer to a question the program no longer asks.\n- **Concurrency is visible.** `parallel`, `race`, `fanOut` and `conclave` are the only ways to do\n two things at once, each branch gets its own journal namespace, and the scope writes its own\n entry saying how it settled: which arm won a race is a recorded fact, decided by the arms'\n recorded clocks and declaration order, never by a scheduler. A branch may not write to anything\n declared outside it; return the value and read it out of the scope's result.\n- **Time and randomness are tamed.** `now()` is the branch's run clock, the end of the last effect\n it awaited; `random()` is a seeded stream derived per scope. Both replay identically.\n- **Values freeze at the boundary.** What crossed into or out of an effect is what the journal\n recorded, and it cannot change afterwards; build a new value.\n- **The journal is the debugger.** Every entry carries its key, its inputs' hash, its outcome and\n its timing, and every error is in the program's own coordinates. A run can be **simulated** with a\n scripted handler and **dry-run** to a plan before it touches an agent. The simulator is\n discrete-event: timed effects park at their wake times and are delivered in wake order on one\n virtual clock, so concurrent branches accumulate the durations they wrote and a simulated `race`\n is decided by the same rule a live handler produces (least recorded clock, ties by declaration\n order). A `sleep(\"1m\")` arm beats a `sleep(\"1h\")` arm whatever their declaration order.\n\nFull rules, with every code: [`spec/cotal-lang.md`](../spec/cotal-lang.md).\n\n## Continuing a run\n\n**Resume** is re-execution: the driver replays the journal, the program runs from the top, recorded\nsteps return instantly, and the first unrecorded step is performed live. It refuses a journal that\nbelongs to another run, a pin that differs from the recorded ones, and a different language version.\n\n**Migrate** moves a run onto edited source. A dry walk of the new program over the recorded journal\nfinds every recorded step the edit changed (a divergence) and every one it no longer reaches (an\norphan), and the orphan table says what each means: a removed `sleep` is nothing, a removed `turn`\nalready happened, a removed `spawn` is a live agent you must adopt or release, a removed resolved\n`checkpoint` is a human decision you must explicitly discard. The decision is filed as a\n`migration` record with the actor's name on it. An adopted seat (`--adopt <name>#<uid>`) goes to\nthe edited program's next `spawn` of that persona, which returns the recorded handle and mints\nnothing, so the agent keeps its identity, its worktree and its turn history across the edit. A\nreleased seat (`--release <name>#<uid>`) is despawned when the migration commits, through the same\ndischarge a cancelled branch's seat leaves by, so the record never claims a release nothing did.\nThe spawn that adopts a seat binds the orphaned spawn's goal as its own, so a resume of that step\nreads the same seat back and a cancellation of it despawns the seat it holds.\n\n**Fork** starts a new run from a named step of an old one, copying the prefix under the parent's\npins (seed included, so the copied history's pure draws are the same draws). The child is a new run\nunder a new id whose record names the parent and the cut step (`forkedFrom`); the parent is\nuntouched. A spawn inside the copied prefix is honoured by its `onFork`: `\"adopt\"` copies it, and\nthe child shares the parent's agent (the manager shows that seat one turn at a time across both\nruns); `\"respawn\"`, the default, would mint a fresh identity the copied turns do not address, so\nthis host refuses that cut (L5019) rather than rewriting the parent's history.\n\n## Operating a run\n\nThe manager hosts runs. `cotal run start` hands the program to the manager of the resolved mesh\n(the usual `--space` / `--server` / `--creds` flags), which validates it, mints the run id, drives\nit in its own process, and answers with the id once the run is recorded. The terminal is free the\nmoment the id prints; the run continues on the manager through every pause, and a manager restart\ntakes back every run it had recorded running, from the journal, under the next epoch. `resume`\nnames a run the manager recorded and is refused while the manager is already driving it. `ps` and\n`journal` read; `answer` resolves an open checkpoint, or an open `ask` attempt, from any terminal\nor agent that holds the `run` capability.\n\n```bash\ncotal run start --file build.cotal.js # the manager starts it; the minted id is printed\ncotal run ps # list run records: state, holder, lineage\ncotal run journal run-3f2a90c41b7e0d5a6c884e19b02df4a1 # print the durable step journal\ncotal run resume run-3f2a90c41b7e0d5a6c884e19b02df4a1 # the manager takes the run back\ncotal run answer run-3f2a90c41b7e0d5a6c884e19b02df4a1 \"/checkpoint:approve#0\" --value '\"yes\"'\n```\n\nA program that does not validate is refused before anything is recorded, with every problem in the\nanswer as the validator would print it. The driver records the program beside the run, so `resume`\ntakes the run id alone and the manager reads the source back; an edited program is a `migrate` or a\n`fork`, never a resume. An answer is recorded under the answerer the manager knows from the\ncaller's credential: a managed agent by its name, anyone else by their principal. The request\ncarries no name. An agent with `capabilities: [run]` has the same five verbs as the `cotal_run`\ntool ([MCP tools](mcp-tools.md)), so a program can be written and started from inside a session.\nA `start` or `resume` answers once the run's record is written, within a bounded wait; a manager\nthat is still taking back a predecessor's runs at boot refuses both with `unavailable`, and a\nretry a moment later is the whole remedy.\n\n`--local` drives the run in this process instead: `start`, `resume` and `answer` exit when the\ndrive settles, `--by <who>` names the answerer, and `cotal run resume <runId> --local --file\n<program>` is how a run with no recorded program, or a run on a bare broker with no manager, is\ncontinued. On a static mesh the local drive mints the run's own credential from the folder's\ntrust material, so it runs from the mesh's project folder. A user-auth mesh runs no programs\nyet, hosted or local: the manager refuses the family by name, since a hosted run's seats would be\nspawned under the static owner, which a user mesh refuses, and a user bearer holds no run rows.\nA run whose step was refused (L5016) stays held; a\nresume on a host that can perform the step performs it live and continues from there.\n`journal` prints what an open pause asks beneath its step key, which is the address `answer` takes\nback. Checkpoint expiry rides the mediated timer writer, which the delivery daemon pumps on a live\nmesh; on a bare broker a pause still resolves, it just cannot expire.\n\n## What is on the wire\n\nThe run's wire footprint is [SPEC \xA714](../SPEC.md#14-workflow-runs-v05):\n\n| Thing | Where | What it is |\n| --- | --- | --- |\n| the run | `run.<endpoint>.<runId>` record | the resolved **pins** (seed, logical epoch, budgets, language version) on the immutable half; holder, lease and `journalHigh` on the status half |\n| the program | `program.<endpoint>.<runId>` record | the source the run was started from, verbatim, written once by the driver that pinned the run; what a resume reads and what a migration is measured against |\n| the step journal | `WFJ_<space>` stream, one subject per run | append-only, no age eviction, no Direct Get; every append fenced by the run subject's own sequence; takeover is replay-then-activate |\n| a checkpoint answer | `answer.<endpoint>.<token>.<answerId>` | the payload beside the one-use settle fact; the settle names the answer it accepted |\n| a notice | `notice.<endpoint>.<runId>.<addresseeId>.<noticeId>` | one bounded decision told to one agent, rendered ahead of its next turn |\n| a migration | `migration.<endpoint>.<runId>.<migrationId>` | the report and who applied it, keyed by the report's own digest |\n\nA run's **driver** connects on a credential of its own, the `run-driver` profile, minted for one\nrun and one takeover attempt. Pinned to the run: publish on its own journal subject and its own\nreplay durable, its `run`, `program`, `notice` and `migration` records, the timer schedule at its\nown instance and epoch, and the manager's lifecycle commands as the run's own caller. Wider than\nthe run, and named as the profile's residual: the checkpoint records and settle facts of the whole\nendpoint (a pause is keyed by a token that does not exist at mint), the point reads of the records,\nfact, timer and chat stores (a KV read is one verb on the whole backing stream, and a matched\nmessage is re-read by sequence the same way), a wait's own durable on the chat stream (named per\nstep, so the consumer rows are stream-scoped), and the channel and membership registries a\nconclave writes. It holds no consumer on the records store, so it lists its\nnotices and migrations by walking the store one message at a time, and it cannot speak on a\nchannel, read another run's journal, or file an answer. A served read rides a one-shot\n`run-operator` credential minted for that one call, holding the records walk and the named run's\nreplay and nothing it can write. An answer is two such calls: the read that finds the open pause,\nthen a second credential minted for that pause's token alone, holding its answer record and its\ncheckpoint settle and no other pause's. `cotal run --local` mints the same profiles for itself on\na static mesh, one per connection.\n\n## What ships today\n\nThe language, its validator, interpreter, simulator and dry run are `@cotal-ai/lang`\n(`packages/lang`), usable in-process with your own effect handler and with no broker: `validate(src)`,\nthen `run(src, { runId, handler })`, and `resume(src, journal, { runId, pins, handler })` to pick a\nrun up from its journal (the package README has the snippet, with `SimHandler` as the handler). That\nis the in-process route, yours to drive with your own handler; a run the driver starts executes on\nthe compiled engine, as the engine paragraph below says. The wire\nsubstrate of \xA714 (the `WFJ_<space>` stream, the five record kinds, the activation barrier, the\nper-run grants) is in `@cotal-ai/core`, and the run driver, journal store, migrate and fork are\n`@cotal-ai/runtime` (`implementations/runtime`). On the mesh handler, `sleep`, `checkpoint`,\n`wait(message(...))`, `wait(idle(...))`, `wait(down(...))`, `wait(replied(...))`, `notify`,\n`spawn`, `conclave`, `ask`, `monitor` and `turn` are durable.\n`spawn` is\nthe manager's spawn action submitted under the step's own identity: the goal binds under the step's\nrequest id, so a resumed run re-attaches to the same seat instead of allocating a second one, a\nfailed or refused spawn is catchable as L4002 with the manager's recorded reason, and a spawn on a\nrace branch that loses is despawned by the run's own cancellation sweep. `permits` are the budgets\nthis host meters: `turns`, how many turns the run may dispatch to the agent, and `wallClock`, a\nduration from the spawn after which no turn is admitted. The turn that would exceed one is the\ncatchable L4001 (kind `permit-turns` or `permit-wall-clock`; a deadline the remaining wall clock\ncannot hold counts as exceeding it), an adopted run counts the turns its journal recorded, and a\nbudget the host has no meter for, such as `tokens` or `spend`, is refused at the spawn rather than\naccepted and ignored. `supervise` is the restart policy this host asks the manager to enforce:\n`restarts`, how many in-window process deaths may come back under the same handle, and `window`,\nthe duration those deaths are counted in (default `10m`). The manager restarts the process in\nplace under the same name, lifecycle uid, persona, worktree and permits; `monitor` does not fire\nfor a restart, and `wait(down)` fires only when the seat is gone for good. Spending the budget\nretires the seat, and the next `turn` is the catchable L4002. A policy this host cannot enforce\n(an unknown key, a user-mode seat, or a runtime that cannot respawn a name in place) is refused\nat the spawn rather than accepted and ignored. `conclave` joins its\nmembers to a real channel as durable membership rows: the channel derives from the step's own\nrequest id when the program names none (a program-named channel is borrowed, never torn down, and\na membership that predates the conclave survives its close), each member handle resolves to its\nprincipal through the seat's own presence row (an absent member is catchable as L4002), and a\nconclave cancelled on a losing branch is released by the same cancellation sweep. `ask` parks one\ncheckpoint-plane pause per attempt, answered through `cotal run answer` as a checkpoint is, and\ntells the agent through the same relay `turn` uses: one relay per attempt under the attempt's own\ntoken, carrying the schema, the attempt count, the deadline and the previous refusal, which the\nseat's connector renders as the record wanted and the command that answers it. An ask addresses\nan agent the run spawned (anything else refuses before an attempt opens), a resumed attempt tells\nthe seat nothing twice, and a seat gone at the relay is L4002. On the pause itself:\nthe shorthand of the language reference \xA76.5 is enforced (an unreadable schema is L4022), a\nnon-conforming answer costs one attempt and its refusal reason is recorded on the entry for the\nanswerer to read, exhausted attempts (default one) are the catchable L4006, and so is the one\nabsolute deadline for the whole ask passing with no conforming record (its kind is `ask-deadline`).\n`checkpoint` binds what it asks on its own entry, so `cotal run journal` prints the question under\nthe step key an answer is addressed by while the pause is open: the address alone left whoever was\nasked reading the source to find out what \"approve\" meant. An `escalate` addressed to an agent this\nrun spawned is relayed to that seat through the same turn relay an `ask` uses, carrying the prompt\nand the token to answer under; a `to` naming anyone else is a person, and their pause stays the\none anybody can answer, with the addressee recorded and rendered beside the question.\n`monitor` registers interest in an agent, and the\nregistration is the journal entry itself, carrying the handle it registered: monitoring an agent\nthat is already dead succeeds, and the death is the wait's to observe. `wait(down(...))` observes\na monitored agent, and refuses one the run never performed `monitor` on. It reads the death off presence liveness, the\nsame witness a conclave join resolves members through: the value carries the handle, the reason\n(`lapsed` when nothing live holds the name any more, `superseded` when a live row holds it under\na different incarnation) and the time of observation, a wait that begins after the death resolves\nat once, and a timeout resolves null on one absolute deadline a resumed run re-attaches to.\n`turn` wakes one seat for one host turn through the manager as a pull-shaped relay: the run\nsubmits the turn under the step's own identity, the manager holds it as a goal pinned to the\nseat's incarnation, and the seat pulls it under its own reach ahead of its next host turn, so\nnothing is pushed into a session mid-thought. The payload the seat reads names the run and the\nstep and carries the rendered run context, plus any pending notices addressed to it, which the\nturn consumes. The seat yields through `cotal_yield` (`done`, `blocked`, or `handoff` with an\naddressee), and ending its host turn yields `done` for every turn it was shown. A `handoff` names\nanother seat the same run spawned: the next `turn` in the same scope to that seat records the\nlink, a handoff to a name the run never spawned is the catchable L4005, and one to a seat bound\nto a different worktree is L4004. The deadline elapsing before any yield is the catchable L4003:\nthe acceptance names the instant, the manager's goal-bound hold denies at it, and the run arms its\nown pause on that same instant, so either side outliving the other still converges on the same\nanswer. A seat that dies mid-turn is read off its own presence row by the run itself and is the\ncatchable L4002, and a death the manager marked on the deadline terminal reads the same way. Two\nturns on one seat, from two branches or from two runs, reach it one at a time: the language\ndispatches the second when the first settles, and the manager shows a seat the oldest unsettled\nturn alone. On an auth mesh the relay needs no extra grant: every spawned seat's baseline\ncredential carries its own pull and yield rows, the run driver's operator instrument carries the\nturn request, and the manager arms the deadline hold over its own serve grant and expires it\nitself once due. An accept the manager cannot finish is unwound to a failed terminal on the goal\nit bound, and a retry of that submission is refused naming the terminal rather than accepted a\nsecond time.\n`wait(replied(...))` observes those turns from another branch: a completed turn is a reply, and\nthe wait resolves with the observation record (the handle, the yield's status and note, the\nyield's own stamp). It reads as a level, the way `wait(down)` does: a reply that already exists\nresolves the wait at once, and two replies resolve to the latest by the yield's stamp. A denied\nor cancelled turn is never a reply, so an unanswered wait rides its own mediated timeout to\n`null`, and a handle the run never spawned or turned refuses loudly, since only this run's turns\nare observable. A turn the run itself ended without an accepted yield (its deadline, a\ncancellation, a refused handoff) is never a reply, whatever the seat yields to the relay later.\nA `spawn` may bind its agent to a **logical worktree** (`spawn(\"builder\", { worktree: \"wt-1\" })`):\nthe handle carries the id, and the run enforces the one rule the language states about it: two\nagents never share a worktree concurrently. The validator rejects the literal case up front\n(L3022: two branches of one concurrent scope spawning into one literal worktree, named branch\nfunctions included), and the runtime guards the rest, computed ids included: a spawn claims its\ntree before it submits, so a second spawn into a tree held by a live seat or by a spawn still\nbringing one up is the catchable L4008, a spawn that ends without a handle gives the tree back,\nand the tree is reusable the moment a holder's presence row is gone, so a discharged race loser\nor a crashed seat releases its tree with no bookkeeping. A spawn the endpoint refuses at accept\nis the catchable L4000 (L4001 when the refusal is the endpoint's seat capacity), and one whose\nseat never came up is L4002. A turn handoff across worktrees is the L4004 described above. Recovery keeps these honest: a resumed run\nreseeds its roster, holders and handoff memos from its own journal, and the driver re-issues any\nrecorded-but-undischarged cancellation at adoption, before the engine performs a new step, so a\nloser a crash left alive does not keep its seat or its tree while the resumed run works on. The\nsame sweep withdraws a cancelled branch's undelivered notices: a notice waits on the run for its\naddressee's next turn, so a decision the run cancelled would otherwise arrive at an agent with\nnothing to distinguish it from one that stood.\n\nEvery effect the language defines performs on the mesh handler; nothing is refused as\nnot-yet-durable any more. The operator surface over the driver is `cotal run`; the section above has the verbs.\n\n**Two engines, and which one runs your program.** The tree-walker is language version `1` and the\ncompiled engine is version `2`, two languages rather than two speeds of one (`spec/cotal-lang.md`\n\xA78.4 lists what differs). The driver hosts both: **every run a driver starts is stamped `2` and\nexecuted by the compiled engine**. The program runs in its own locked-down worker thread with\nnothing in its global scope, while the effects and the durable journal stay in the driver's process,\nbridged over a message port. No socket or credential enters the isolate holding the program,\nand **every version-`1` record keeps replaying on the walker**, which is the walker's job. The\ndriver serves a declared set of versions, and a record whose version it does not serve is refused\nby name (**L5023**) with the run left untouched, instead of being replayed by whichever engine\nhappens to be present. Records do not cross between versions in either direction; the repair is to\nresume on the recorded version, or to fork.\n\n**The engine needs node 22 or newer** and refuses below it as `EngineUnavailable`, which is an\nimplementation limit and not a language error: it carries no `L` code, so there is nothing to look\nup in the catalog. It is a floor rather than a warning because the engine's frame plumbing rests on\n`AsyncLocalStorage`, and 22 is the lowest node it has been measured on. The walker has no such floor.\n"
15098
+ "body": "# Workflow runs\n\n> **Concept** (informative) \xB7 **For:** people writing a durable multi-agent workflow, and implementers hosting one \xB7 **Normative:** [SPEC \xA714](../SPEC.md#14-workflow-runs-v05) and the language reference [`spec/cotal-lang.md`](../spec/cotal-lang.md)\n\nA **workflow run** is a program that coordinates agents over hours or days and survives the\nprocess that started it. The program is written in **Cotal Lang**, a small subset of JavaScript in\nwhich every interaction with the world is one of a dozen **effects** (`spawn`, `turn`, `ask`,\n`checkpoint`, `sleep`, `wait`, `notify`, `monitor`, and the four concurrency scopes) and everything\nelse is ordinary, pure JavaScript. Every effect is written into the run's **step journal** before\nit is performed and settled after, keyed by where in the program it happened rather than by when,\nso a run that dies is resumed on any host by **re-running the program from the top** with recorded\neffects returning their recorded results. Nothing about the interpreter is ever serialized: the\njournal and the program are the whole state.\n\n## A first program\n\n```js\nconst planner = await spawn(\"planner\")\nconst builder = await spawn(\"builder\", { worktree: \"wt-1\" })\n\nconst plan = await ask(planner, { name: \"plan\", schema: { steps: \"array\" } })\nconst ok = await checkpoint(\"approve-plan\", \"Approve the plan?\", { timeout: \"4h\", onExpiry: \"proceed\" })\nif (ok.status !== \"resolved\") {\n await notify([planner], { decision: \"approve-plan\", outcome: \"expired\" })\n}\n\nconst r = await turn(builder, { name: \"build\", deadline: \"30m\" })\nif (r.status === \"blocked\") {\n await turn(planner, { name: \"unblock\" })\n}\n\nconst outcome = await race({\n reply: () => wait(replied(builder), { timeout: \"20m\" }),\n giveUp: () => sleep(\"1h\"),\n}, { name: \"await-or-move-on\" })\nlog(\"outcome\", outcome.index)\n```\n\nRead it as the flowchart it is. `spawn` brings agents in; `ask` is the narrow case where the\nprogram itself needs a value (`schema` is a record the program hands the handler unchanged; the\nlanguage hashes it and gives it no meaning, and the handlers in this repository enforce it as the\nshorthand of the language reference \xA76.5);\n`checkpoint` is a durable pause a human resolves from anywhere, raced against a durable timer; `turn`\nwakes an agent for one turn and returns how it yielded; `race` runs two branches and keeps the one\nwhose recorded clock is earliest. Agents talk to each other in channels as they always do; the\nprogram never speaks in a channel, and the one thing it can put in front of an agent (`notify`) is a\nbounded decision record, not prose.\n\n## The mental model\n\n- **Pure code is JavaScript.** Loops, records, arrays, closures, template literals, destructuring,\n `try`/`catch`, arithmetic, `switch`, compound assignment, optional chaining, spread and rest: what\n you would write anyway, with the parts that hide effects or make meaning depend on the host removed\n (`class`, `this`, `new`, `for...in`, `==`, labels, regex literals, `Math`/`Date`/`JSON`, promises,\n generators). Every refusal names its code and the edit that fixes it. The builtins are a short list\n (`keys`, `map`, `sort`, `json.stringify`, `now()`, `random()`), and arrays, strings and numbers\n answer their usual methods (`xs.map`, `s.trim()`, `n.toFixed()`) and nothing outside that table.\n Records and arrays you build are yours to change until they cross an effect boundary; a member you\n do not own, a host prototype, or a value another branch built is refused with a code, never a\n surprise.\n- **Every effect is journalled and hashed.** A step is keyed `(scope path, kind, name, occurrence)`\n and its inputs are hashed. Reorder your program, add a step, rename a variable: recorded steps\n still match. Change what a step asks (a checkpoint's prompt, a sleep's duration, a turn's\n deadline) and the resume stops with a **divergence** naming the step, rather than replaying an\n answer to a question the program no longer asks.\n- **Concurrency is visible.** `parallel`, `race`, `fanOut` and `conclave` are the only ways to do\n two things at once, each branch gets its own journal namespace, and the scope writes its own\n entry saying how it settled: which arm won a race is a recorded fact, decided by the arms'\n recorded clocks and declaration order, never by a scheduler. A branch may not write to anything\n declared outside it; return the value and read it out of the scope's result.\n- **Time and randomness are tamed.** `now()` is the branch's run clock, the end of the last effect\n it awaited; `random()` is a seeded stream derived per scope. Both replay identically.\n- **Values freeze at the boundary.** What crossed into or out of an effect is what the journal\n recorded, and it cannot change afterwards; build a new value.\n- **The journal is the debugger.** Every entry carries its key, its inputs' hash, its outcome and\n its timing, and every error is in the program's own coordinates. A run can be **simulated** with a\n scripted handler and **dry-run** to a plan before it touches an agent. The simulator is\n discrete-event: timed effects park at their wake times and are delivered in wake order on one\n virtual clock, so concurrent branches accumulate the durations they wrote and a simulated `race`\n is decided by the same rule a live handler produces (least recorded clock, ties by declaration\n order). A `sleep(\"1m\")` arm beats a `sleep(\"1h\")` arm whatever their declaration order.\n\nFull rules, with every code: [`spec/cotal-lang.md`](../spec/cotal-lang.md).\n\n## Continuing a run\n\n**Resume** is re-execution: the driver replays the journal, the program runs from the top, recorded\nsteps return instantly, and the first unrecorded step is performed live. It refuses a journal that\nbelongs to another run, a pin that differs from the recorded ones, and a different language version.\n\n**Migrate** moves a run onto edited source. A dry walk of the new program over the recorded journal\nfinds every recorded step the edit changed (a divergence) and every one it no longer reaches (an\norphan), and the orphan table says what each means: a removed `sleep` is nothing, a removed `turn`\nalready happened, a removed `spawn` is a live agent you must adopt or release, a removed resolved\n`checkpoint` is a human decision you must explicitly discard. The decision is filed as a\n`migration` record with the actor's name on it. An adopted seat (`--adopt <name>#<uid>`) goes to\nthe edited program's next `spawn` of that persona, which returns the recorded handle and mints\nnothing, so the agent keeps its identity, its worktree and its turn history across the edit. A\nreleased seat (`--release <name>#<uid>`) is despawned when the migration commits, through the same\ndischarge a cancelled branch's seat leaves by, so the record never claims a release nothing did.\nThe spawn that adopts a seat binds the orphaned spawn's goal as its own, so a resume of that step\nreads the same seat back and a cancellation of it despawns the seat it holds.\n\n**Fork** starts a new run from a named step of an old one, copying the prefix under the parent's\npins (seed included, so the copied history's pure draws are the same draws). The child is a new run\nunder a new id whose record names the parent and the cut step (`forkedFrom`); the parent is\nuntouched. A spawn inside the copied prefix is honoured by its `onFork`: `\"adopt\"` copies it, and\nthe child shares the parent's agent (the manager shows that seat one turn at a time across both\nruns); `\"respawn\"`, the default, would mint a fresh identity the copied turns do not address, so\nthis host refuses that cut (L5019) rather than rewriting the parent's history.\n\n## Operating a run\n\nThe manager hosts runs. `cotal run start` hands the program to the manager of the resolved mesh\n(the usual `--space` / `--server` / `--creds` flags), which validates it, mints the run id, drives\nit in its own process, and answers with the id once the run is recorded. The terminal is free the\nmoment the id prints; the run continues on the manager through every pause, and a manager restart\ntakes back every run it had recorded running, from the journal, under the next epoch. `resume`\nnames a run the manager recorded and is refused while the manager is already driving it. `ps` and\n`journal` read; `answer` resolves an open checkpoint, or an open `ask` attempt, from any terminal\nor agent that holds the `run` capability.\n\n```bash\ncotal run start --file build.cotal.js # the manager starts it; the minted id is printed\ncotal run ps # list run records: state, holder, lineage\ncotal run journal run-3f2a90c41b7e0d5a6c884e19b02df4a1 # print the durable step journal\ncotal run resume run-3f2a90c41b7e0d5a6c884e19b02df4a1 # the manager takes the run back\ncotal run answer run-3f2a90c41b7e0d5a6c884e19b02df4a1 \"/checkpoint:approve#0\" --value '\"yes\"'\n```\n\nA program that does not validate is refused before anything is recorded, with every problem in the\nanswer as the validator would print it. The driver records the program beside the run, so `resume`\ntakes the run id alone and the manager reads the source back; an edited program is a `migrate` or a\n`fork`, never a resume. An answer is recorded under the answerer the manager knows from the\ncaller's credential: a managed agent by its name, anyone else by their principal. The request\ncarries no name. An agent with `capabilities: [run]` has the same five verbs as the `cotal_run`\ntool ([MCP tools](mcp-tools.md)), so a program can be written and started from inside a session.\nA `start` or `resume` answers once the run's record is written, within a bounded wait; a manager\nthat is still taking back a predecessor's runs at boot refuses both with `unavailable`, and a\nretry a moment later is the whole remedy.\n\n`--local` drives the run in this process instead: `start`, `resume` and `answer` exit when the\ndrive settles, `--by <who>` names the answerer, and `cotal run resume <runId> --local --file\n<program>` is how a run with no recorded program, or a run on a bare broker with no manager, is\ncontinued. On a static mesh the local drive mints the run's own credential from the folder's\ntrust material, so it runs from the mesh's project folder. A user-auth mesh runs no programs\nyet, hosted or local: the manager refuses the family by name, since a hosted run's seats would be\nspawned under the static owner, which a user mesh refuses, and a user bearer holds no run rows.\nA run whose step was refused (L5016) stays held; a\nresume on a host that can perform the step performs it live and continues from there.\n`journal` prints what an open pause asks beneath its step key, which is the address `answer` takes\nback. Checkpoint expiry rides the mediated timer writer, which the delivery daemon pumps on a live\nmesh; on a bare broker a pause still resolves, it just cannot expire.\n\n## What is on the wire\n\nThe run's wire footprint is [SPEC \xA714](../SPEC.md#14-workflow-runs-v05):\n\n| Thing | Where | What it is |\n| --- | --- | --- |\n| the run | `run.<endpoint>.<runId>` record | the resolved **pins** (seed, logical epoch, budgets, language version) on the immutable half; holder, lease and `journalHigh` on the status half |\n| the program | `program.<endpoint>.<runId>` record | the source the run was started from, verbatim, written once by the driver that pinned the run; what a resume reads and what a migration is measured against |\n| the step journal | `WFJ_<space>` stream, one subject per run | append-only, no age eviction, no Direct Get; every append fenced by the run subject's own sequence; takeover is replay-then-activate |\n| a checkpoint answer | `answer.<endpoint>.<token>.<answerId>` | the payload beside the one-use settle fact; the settle names the answer it accepted |\n| a notice | `notice.<endpoint>.<runId>.<addresseeId>.<noticeId>` | one bounded decision told to one agent, rendered ahead of its next turn |\n| a migration | `migration.<endpoint>.<runId>.<migrationId>` | the report and who applied it, keyed by the report's own digest |\n\nA run's **driver** connects on a `run-driver` credential minted for one run and takeover\nattempt. It can append to its journal, use its replay durable, and write its own `run`, `program`,\n`notice` and `migration` records. It has no store point reads, checkpoint writes, chat consumers,\nor channel and membership registry grants.\n\nThe hosting process keeps a separate `run-mediator` connection for effects and reads. The driver\nreceives methods and data from that host; it never receives the mediator credential or connection.\nThe host checks the journal's current activation and step identity before dispatch, and checks\npause and wait authority again at each operation. Cancellation cleanup also admits losing steps\nnamed by a settled parent whose `cancel.issued` is still false. That permission allows cleanup;\nit cannot mint or rearm a cancelled pause. Wait acknowledgements consume host-held delivery\nreceipts. A recorded match can be reread only at its bound sequence and channel. A conclave's\nrecorded ownership flag must match its step-derived channel before registry writes or cleanup.\n\nThe mediator retains endpoint-wide checkpoint rights and stream-wide leader reads as trusted\nhost authority. Record reads exposed to the driver are restricted to its own run's keys. Reads\nthat decide writes remain leader-served. A read of the journal uses the run's filtered replay\ndurable, including the diagnostic for a journal with no run record.\n\nA served read uses a one-shot `run-operator` credential. An answer uses a read to find the open\npause, then a second credential pinned to that token for the answer and settlement.\n`cotal run --local` uses the same driver/mediator split. On an authenticated mesh it needs the\nlocally recorded space signer to mint both credentials; a single `--creds` file is refused.\nDirect library users supplying broker clients to `MeshHandler` are constructing a trusted effect\nhost. A hosted driver receives its closed effect interface instead.\n\nThis split confines broker credentials; it is not process isolation for injected host code.\nThe runtime and its effect host share the manager process. Workflow channel access still follows\nthe program's requested channels, without inheriting the starting caller's channel ACL. Treat\n`run` as trusted program-execution authority. The host's journal checks enforce current run and\nstep identity; they do not provide caller-scoped channel delegation.\n\nA version-1 fork can replay its settled parent history through the host. Inherited checkpoint\nidentifiers carry no authority to read, rearm or claim the parent's pauses. New child effects use\nchild-derived identifiers. The fork planner still uses the version-1 walker; planning a fork from\na version-2 run currently fails on its language-version pin and needs a separate engine-aware\nplanning implementation.\n\n\n## What ships today\n\nThe language, its validator, interpreter, simulator and dry run are `@cotal-ai/lang`\n(`packages/lang`), usable in-process with your own effect handler and with no broker: `validate(src)`,\nthen `run(src, { runId, handler })`, and `resume(src, journal, { runId, pins, handler })` to pick a\nrun up from its journal (the package README has the snippet, with `SimHandler` as the handler). That\nis the in-process route, yours to drive with your own handler; a run the driver starts executes on\nthe compiled engine, as the engine paragraph below says. The wire\nsubstrate of \xA714 (the `WFJ_<space>` stream, the five record kinds, the activation barrier, the\nper-run grants) is in `@cotal-ai/core`, and the run driver, journal store, migrate and fork are\n`@cotal-ai/runtime` (`implementations/runtime`). On the mesh handler, `sleep`, `checkpoint`,\n`wait(message(...))`, `wait(idle(...))`, `wait(down(...))`, `wait(replied(...))`, `notify`,\n`spawn`, `conclave`, `ask`, `monitor` and `turn` are durable.\n`spawn` is\nthe manager's spawn action submitted under the step's own identity: the goal binds under the step's\nrequest id, so a resumed run re-attaches to the same seat instead of allocating a second one, a\nfailed or refused spawn is catchable as L4002 with the manager's recorded reason, and a spawn on a\nrace branch that loses is despawned by the run's own cancellation sweep. `permits` are the budgets\nthis host meters: `turns`, how many turns the run may dispatch to the agent, and `wallClock`, a\nduration from the spawn after which no turn is admitted. The turn that would exceed one is the\ncatchable L4001 (kind `permit-turns` or `permit-wall-clock`; a deadline the remaining wall clock\ncannot hold counts as exceeding it), an adopted run counts the turns its journal recorded, and a\nbudget the host has no meter for, such as `tokens` or `spend`, is refused at the spawn rather than\naccepted and ignored. `supervise` is the restart policy this host asks the manager to enforce:\n`restarts`, how many in-window process deaths may come back under the same handle, and `window`,\nthe duration those deaths are counted in (default `10m`). The manager restarts the process in\nplace under the same name, lifecycle uid, persona, worktree and permits; `monitor` does not fire\nfor a restart, and `wait(down)` fires only when the seat is gone for good. Spending the budget\nretires the seat, and the next `turn` is the catchable L4002. A policy this host cannot enforce\n(an unknown key, a user-mode seat, or a runtime that cannot respawn a name in place) is refused\nat the spawn rather than accepted and ignored. `conclave` joins its\nmembers to a real channel as durable membership rows: the channel derives from the step's own\nrequest id when the program names none (a program-named channel is borrowed, never torn down, and\na membership that predates the conclave survives its close), each member handle resolves to its\nprincipal through the seat's own presence row (an absent member is catchable as L4002), and a\nconclave cancelled on a losing branch is released by the same cancellation sweep. `ask` parks one\ncheckpoint-plane pause per attempt, answered through `cotal run answer` as a checkpoint is, and\ntells the agent through the same relay `turn` uses: one relay per attempt under the attempt's own\ntoken, carrying the schema, the attempt count, the deadline and the previous refusal, which the\nseat's connector renders as the record wanted and the command that answers it. An ask addresses\nan agent the run spawned (anything else refuses before an attempt opens), a resumed attempt tells\nthe seat nothing twice, and a seat gone at the relay is L4002. On the pause itself:\nthe shorthand of the language reference \xA76.5 is enforced (an unreadable schema is L4022), a\nnon-conforming answer costs one attempt and its refusal reason is recorded on the entry for the\nanswerer to read, exhausted attempts (default one) are the catchable L4006, and so is the one\nabsolute deadline for the whole ask passing with no conforming record (its kind is `ask-deadline`).\n`checkpoint` binds what it asks on its own entry, so `cotal run journal` prints the question under\nthe step key an answer is addressed by while the pause is open: the address alone left whoever was\nasked reading the source to find out what \"approve\" meant. An `escalate` addressed to an agent this\nrun spawned is relayed to that seat through the same turn relay an `ask` uses, carrying the prompt\nand the token to answer under; a `to` naming anyone else is a person, and their pause stays the\none anybody can answer, with the addressee recorded and rendered beside the question.\n`monitor` registers interest in an agent, and the\nregistration is the journal entry itself, carrying the handle it registered: monitoring an agent\nthat is already dead succeeds, and the death is the wait's to observe. `wait(down(...))` observes\na monitored agent, and refuses one the run never performed `monitor` on. It reads the death off presence liveness, the\nsame witness a conclave join resolves members through: the value carries the handle, the reason\n(`lapsed` when nothing live holds the name any more, `superseded` when a live row holds it under\na different incarnation) and the time of observation, a wait that begins after the death resolves\nat once, and a timeout resolves null on one absolute deadline a resumed run re-attaches to.\n`turn` wakes one seat for one host turn through the manager as a pull-shaped relay: the run\nsubmits the turn under the step's own identity, the manager holds it as a goal pinned to the\nseat's incarnation, and the seat pulls it under its own reach ahead of its next host turn, so\nnothing is pushed into a session mid-thought. The payload the seat reads names the run and the\nstep and carries the rendered run context, plus any pending notices addressed to it, which the\nturn consumes. The seat yields through `cotal_yield` (`done`, `blocked`, or `handoff` with an\naddressee), and ending its host turn yields `done` for every turn it was shown. A `handoff` names\nanother seat the same run spawned: the next `turn` in the same scope to that seat records the\nlink, a handoff to a name the run never spawned is the catchable L4005, and one to a seat bound\nto a different worktree is L4004. The deadline elapsing before any yield is the catchable L4003:\nthe acceptance names the instant, the manager's goal-bound hold denies at it, and the run arms its\nown pause on that same instant, so either side outliving the other still converges on the same\nanswer. A seat that dies mid-turn is read off its own presence row by the run itself and is the\ncatchable L4002, and a death the manager marked on the deadline terminal reads the same way. Two\nturns on one seat, from two branches or from two runs, reach it one at a time: the language\ndispatches the second when the first settles, and the manager shows a seat the oldest unsettled\nturn alone. On an auth mesh the relay needs no extra grant: every spawned seat's baseline\ncredential carries its own pull and yield rows, the run driver's operator instrument carries the\nturn request, and the manager arms the deadline hold over its own serve grant and expires it\nitself once due. An accept the manager cannot finish is unwound to a failed terminal on the goal\nit bound, and a retry of that submission is refused naming the terminal rather than accepted a\nsecond time.\n`wait(replied(...))` observes those turns from another branch: a completed turn is a reply, and\nthe wait resolves with the observation record (the handle, the yield's status and note, the\nyield's own stamp). It reads as a level, the way `wait(down)` does: a reply that already exists\nresolves the wait at once, and two replies resolve to the latest by the yield's stamp. A denied\nor cancelled turn is never a reply, so an unanswered wait rides its own mediated timeout to\n`null`, and a handle the run never spawned or turned refuses loudly, since only this run's turns\nare observable. A turn the run itself ended without an accepted yield (its deadline, a\ncancellation, a refused handoff) is never a reply, whatever the seat yields to the relay later.\nA `spawn` may bind its agent to a **logical worktree** (`spawn(\"builder\", { worktree: \"wt-1\" })`):\nthe handle carries the id, and the run enforces the one rule the language states about it: two\nagents never share a worktree concurrently. The validator rejects the literal case up front\n(L3022: two branches of one concurrent scope spawning into one literal worktree, named branch\nfunctions included), and the runtime guards the rest, computed ids included: a spawn claims its\ntree before it submits, so a second spawn into a tree held by a live seat or by a spawn still\nbringing one up is the catchable L4008, a spawn that ends without a handle gives the tree back,\nand the tree is reusable the moment a holder's presence row is gone, so a discharged race loser\nor a crashed seat releases its tree with no bookkeeping. A spawn the endpoint refuses at accept\nis the catchable L4000 (L4001 when the refusal is the endpoint's seat capacity), and one whose\nseat never came up is L4002. A turn handoff across worktrees is the L4004 described above. Recovery keeps these honest: a resumed run\nreseeds its roster, holders and handoff memos from its own journal, and the driver re-issues any\nrecorded-but-undischarged cancellation at adoption, before the engine performs a new step, so a\nloser a crash left alive does not keep its seat or its tree while the resumed run works on. The\nsame sweep withdraws a cancelled branch's undelivered notices: a notice waits on the run for its\naddressee's next turn, so a decision the run cancelled would otherwise arrive at an agent with\nnothing to distinguish it from one that stood.\n\nEvery effect the language defines performs on the mesh handler; nothing is refused as\nnot-yet-durable any more. The operator surface over the driver is `cotal run`; the section above has the verbs.\n\n**Two engines, and which one runs your program.** The tree-walker is language version `1` and the\ncompiled engine is version `2`, two languages rather than two speeds of one (`spec/cotal-lang.md`\n\xA78.4 lists what differs). The driver hosts both: **every run a driver starts is stamped `2` and\nexecuted by the compiled engine**. The program runs in its own locked-down worker thread with\nnothing in its global scope, while the effects and the durable journal stay in the driver's process,\nbridged over a message port. No socket or credential enters the isolate holding the program,\nand **every version-`1` record keeps replaying on the walker**, which is the walker's job. The\ndriver serves a declared set of versions, and a record whose version it does not serve is refused\nby name (**L5023**) with the run left untouched, instead of being replayed by whichever engine\nhappens to be present. Records do not cross between versions in either direction; the repair is to\nresume on the recorded version, or to fork.\n\n**The engine needs node 22 or newer** and refuses below it as `EngineUnavailable`, which is an\nimplementation limit and not a language error: it carries no `L` code, so there is nothing to look\nup in the catalog. It is a floor rather than a warning because the engine's frame plumbing rests on\n`AsyncLocalStorage`, and 22 is the lowest node it has been measured on. The walker has no such floor.\n"
15099
15099
  }
15100
15100
  ],
15101
15101
  "spec": {
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@cotal-ai/connector-codex",
3
3
  "description": "Cotal connector for OpenAI Codex: a host-mode peer driving codex app-server, with Codex's own TUI attached and the cotal_* tools served over a loopback MCP endpoint.",
4
- "version": "0.47.1",
4
+ "version": "0.48.0",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
7
7
  "type": "git",
@@ -27,9 +27,9 @@
27
27
  "tsx": "^4.22.4",
28
28
  "ws": "^8.21.0",
29
29
  "zod": "^4.4.3",
30
- "@cotal-ai/connector-core": "0.47.1",
30
+ "@cotal-ai/connector-core": "0.48.0",
31
31
  "@cotal-ai/smoke-kit": "0.0.0",
32
- "@cotal-ai/core": "0.47.1"
32
+ "@cotal-ai/core": "0.48.0"
33
33
  },
34
34
  "files": [
35
35
  "dist"