# Equipo Connections: accounts added from the app, any provider for any role

Status: design for Paul's review, 2026-11-08, revision 3 after Astra's
rounds 1 and 2 (NOT READY at 28f8455 and eaf2f38). Drafted by Claude (Fable 5.1)
on `design-connections` from `thin-v1-slice4c` (2d1edaf). Builds on the
approved thin v1 spec (`2026-11-06-equipo-thin-v1.md`, §§2, 3, 5, 6, 8) and
the accepted Mac runners spec (`2026-11-07-equipo-mac-runners.md`). Not
implemented. Every provider claim below was checked against the official
documentation or source on 2026-11-08; where a claim could not be confirmed
it says so.

## 0. Why, and the shape of the answer

Paul's staging coordinator stopped answering on 2026-11-08 because the one
Claude account it runs on hit its weekly limit, and the chat said "The
coordinator could not answer. Send your message again to retry." Retrying
could not help: there was nothing else to run on. Paul's ask is that
accounts be added from the app, that the coordinator and the specialists
run on whichever connected provider has room, and that he can quietly
prefer one. This spec supersedes the terminal-only part of §6 of thin v1
(`equipo-runner login claude|codex`); the command stays as a fallback.

The shape, in one paragraph. A **connection** is one signed-in account or
one API key or one endpoint, on one runner, owned by one person, living in
its own home under `~/.local/share/equipo/accounts/<provider>-<n>` exactly
as accounts do today. Credentials never leave the runner; the instance
holds a record (provider, label, health, headroom, limit reset time, usage)
and never a secret. A **harness** is the program that drives a model with
tools: Claude Code, the Codex app-server, and one OpenAI-compatible harness
for everything else. A **role** is what a run is for: coordinator,
Engineering, Review, ask. Selection is still the 30-line function thin v1
promised, now over several connections with a preference and a router's
class on top (§§3, 4). Failover is automatic and quiet. Usage is recorded
from day one and shown on one page (§6).

Four rulings of Paul's frame everything: magic, not setup; a preference,
not a requirement; the notebook is the memory, so a provider change is a
new session seeded from the notebook and a short summary while a thread
stays with the account that started it (thin v1 §3); and credentials stay
on the runner. Containment is unchanged: bubblewrap on Linux for every
harness (thin v1 §5), the harness's own sandbox trusted on the owner's Mac
(Mac runners §4). Each person connects their own accounts; a teammate's
connection is never selectable for another person's work.

## 1. Providers and harnesses, and what each needs

### 1.1 Claude, through Claude Code

**Sign-in.** The CLI's OAuth is the only subscription path: `claude`
opens `https://claude.ai/oauth/authorize` with PKCE and a
`redirect_uri` of `http://localhost:<port>/callback`; when the browser
cannot reach that loopback it shows a code on
`https://platform.claude.com/oauth/code/callback` for the person to paste
at the CLI's "Paste code here if prompted" prompt (docs: authentication;
issue #29983 for the two redirect URIs). There is no device-code flow.
`claude setup-token` runs the same browser flow and prints a one-year
OAuth token, saved nowhere, for `CLAUDE_CODE_OAUTH_TOKEN`; it can only
make model requests and is ignored in `--bare` mode. `claude auth status`
returns JSON with `authMethod` and exits 1 when signed out. API keys:
`ANTHROPIC_API_KEY` (always used in `-p` mode when set), or
`ANTHROPIC_AUTH_TOKEN` as a bearer, or an `apiKeyHelper` in settings;
`ANTHROPIC_BASE_URL` points the CLI at any endpoint that speaks the
Anthropic Messages API. Anthropic does not support non-Claude models
through a gateway, and the CLI has no chat-completions mode.

**Policy, which binds the design.** Anthropic's Claude Code legal page
says third parties may not "offer Claude.ai login into their own
applications", may not "route requests through Free, Pro, Max, or Ultra
plan credentials on behalf of their users", and "may not collect, store,
or intermediate Claude.ai credentials or session tokens"; sign-in "must
complete through Anthropic's own flow". The same page allows "an end user
… signing in to the unmodified Claude Code binary with their own Claude
subscription, including where a platform hosts Claude Code", provided the
binary is unmodified and each end user authenticates with their own plan.
Equipo runs the unmodified binary, one person per account, so the
permitted shape is: the `claude` binary performs the sign-in in the
account's home on the runner, and Equipo never sees the code or the
token. That rules out relaying a pasted code through the instance (§2.3)
and rules out a `setup-token` value typed into the app. It also means a
person's Claude connection does Equipo work only for that person, which
the multiplayer rule already requires.

**Headless and tools.** Everything the coordinator uses today exists:
`-p --input-format stream-json --output-format stream-json
--include-partial-messages --verbose`, `--resume <id>`, `--mcp-config`
with `--strict-mcp-config`, `--permission-prompt-tool mcp__…`,
`--allowedTools`, `--permission-mode`, `--max-turns`, `--max-budget-usd`,
and `--bare` (recommended for scripts; skips OAuth and the keychain, so
it is for API-key connections only).

**Limits.** In stream-json the CLI emits `rate_limit_event` with
`rate_limit_info {status: allowed | allowed_warning | rejected,
resetsAt, utilization}` (the Agent SDK's `SDKRateLimitEvent`), derived
from the `anthropic-ratelimit-unified-*` response headers; retries show
as `system/api_retry` with `error: "rate_limit"` and `retry_delay_ms`.
Both `resetsAt` and `utilization` are optional, and `utilization` is a
single number; per-window (five-hour versus weekly) figures are
requested in issues #50518 and #91857 but not documented, so Equipo
shows the one figure the CLI gives, never names a window, and copes with
either field missing. Each `result` message carries `usage`
(`input_tokens`, `output_tokens`, `cache_creation_input_tokens`,
`cache_read_input_tokens`), `modelUsage` per model (`inputTokens`,
`outputTokens`, `cacheReadInputTokens`, `cacheCreationInputTokens`,
`costUSD`, `contextWindow`) and `total_cost_usd`, all client-side
estimates. Credentials live in `~/.claude/.credentials.json` (0600) on
Linux and in the Keychain on macOS, falling back to the file when the
Keychain is locked; the CLI refreshes OAuth itself and warns three days
before a login expires.

### 1.2 ChatGPT or Codex, through the Codex app-server

**Sign-in.** `codex login --device-auth` (beta) prints a URL
(`<issuer>/codex/device`) and a user code that expires in fifteen
minutes, then polls `/api/accounts/deviceauth/token`; nothing is typed
back into the CLI (`codex-rs/login/src/device_code_auth.rs`). The person
must first enable device code login in ChatGPT security settings
(personal) or workspace permissions (team). The browser flow binds
`127.0.0.1:1455` (fallback 1457) and redirects to `/auth/callback`, no
paste fallback. API keys: `codex login --with-api-key` reading stdin.
Storage: `auth.json` under `CODEX_HOME`, or the OS keyring when
`cli_auth_credentials_store` says so; Codex refreshes tokens itself.
The app-server exposes all of this as JSON-RPC: `account/login/start`
with `type: chatgptDeviceCode` returns `loginId`, `verificationUrl` and
`userCode`; `account/login/completed` fires with `success`;
`account/read` (`refreshToken: true` forces a refresh); `account/logout`;
`account/updated` carries `authMode` and `planType`.

**Policy.** OpenAI's docs say to "use API key authentication for
programmatic Codex CLI workflows, such as CI/CD jobs" and document a
ChatGPT-managed path with "use this path only if you specifically need to
run as your Codex account". Driving `codex app-server` with a ChatGPT
sign-in is documented, not forbidden, and the person's own account does
only the person's work, which is the same shape as Claude. The separate
"Sign in with ChatGPT" programme for third-party apps requires loopback
`127.0.0.1` callbacks and partner approval for hosted apps, so it is not
a route for Equipo.

**Headless and tools.** The path thin v1 §3 already designed:
`initialize`, `thread/start` or `thread/resume`, `turn/start`,
`item/agentMessage/delta`, the four approval requests answered deny or
relayed as `ask_person`, `turn/interrupt`; a turn ends on
`turn/completed` whose `status` is `completed`, `failed` or
`interrupted` (there is no separate `turn/failed`; the decoder in
`provider/codex/events.go` already switches on these). Codex remains an
MCP client
(`codex mcp`; `codex mcp-server` was removed in favour of the app-server,
which is not an MCP server). Custom providers in `config.toml` take
`base_url`, `env_key`, `http_headers` and `wire_api`, and **`responses`
is the only supported value**: the chat wire API was deprecated in
December 2025 and became an error in February 2026. The Linux sandbox is
now bubblewrap plus seccomp ("the first `bwrap` on `PATH`", else a
bundled helper needing unprivileged user namespaces); nesting it inside
Equipo's bubblewrap is undocumented, so Equipo keeps `sandbox_mode =
danger-full-access` inside its own namespace, as the Codex step path
already assumes, and the outer namespace is the containment.

**Limits and usage.** `account/rateLimits/read` and the notification
`account/rateLimits/updated` carry `rateLimits` with `primary` and
`secondary` windows, each `{usedPercent, windowDurationMins, resetsAt}`
(Unix seconds), plus `planType`, `limitId`, `limitName` and
`rateLimitReachedType`. Token use arrives as `thread/tokenUsage/updated
{threadId, turnId, tokenUsage {total, last, modelContextWindow}}`, each
breakdown `{inputTokens, cachedInputTokens, outputTokens,
reasoningOutputTokens, totalTokens, cacheWriteInputTokens}`
(`ThreadTokenUsageUpdatedNotification.json` in the codex repo).
`account/usage/read` adds lifetime and daily token buckets. The Codex
provider in `internal/runner/provider/codex` already decodes
`account/rateLimits/updated` and `thread/tokenUsage/updated` (its
`rate_notice` and `resume_usage` tests), so slice 1 extends, rather than
adds, that parsing. Codex is the
one provider that reports both windows with a reset time, so its row in
Usage is the fullest.

### 1.3 Everything OpenAI-compatible, through one harness

Local models (Ollama, vLLM, LM Studio on Tito Studio or a person's own
machine), TensorX, the Mistral API, OpenRouter and, when it ships, the
CARLOS inference gateway (spec rev 6, chat completions and `/v1/models`
only, not yet built) all present an OpenAI-compatible HTTP endpoint with
an API key or none. Paul asked for one harness across them if one works
for every role, rather than one per provider. Two existing harnesses can
already do some of it, which sets the bar:

- **Codex as the harness** works wherever the endpoint serves the
  Responses API: Ollama (`/v1/responses`, non-stateful only), vLLM
  (`/v1/responses`), OpenRouter (`/responses`, stateless). It fails for
  chat-completions-only endpoints (the CARLOS gateway as specified, and
  any provider without Responses).
- **Claude Code as the harness** works only against the Anthropic
  Messages API. Ollama and vLLM now serve `/v1/messages` natively
  (`ANTHROPIC_BASE_URL=http://localhost:11434`,
  `ANTHROPIC_AUTH_TOKEN=ollama`), so local models can run under the
  Claude harness with no proxy, and TensorX documents the same route
  (§1.5); OpenRouter and Mistral cannot without a translating proxy,
  and Anthropic says it does not support routing Claude Code to
  non-Claude models.

Neither covers every endpoint, which is why §1.4 verifies Pi and
OpenCode as the dedicated OpenAI-compatible harness. The verdict and the
capability matrix are in §5. Whichever wins, the connection shape is the
same: `kind: endpoint`, a base URL, an optional key sealed to the runner
(§2.4), a model list fetched from `/v1/models` on connect, and a
one-token test call before the connection is marked healthy.

### 1.4 The OpenAI-compatible harness: Pi, with OpenCode in reserve

Three candidates were verified against their current docs and source
on 2026-11-08.

**Pi** (`earendil-works/pi`, MIT, npm `@earendil-works/pi-coding-agent`
1.5.0, Node 22.19 or later; the `@mariozechner` package is deprecated
in its favour). Headless is `pi -p` with `--mode json` (JSONL events
`agent_start`, `turn_start`, `message_start`, `message_update`,
`message_end`, `tool_execution_start`, `tool_execution_end`,
`agent_end`, `auto_retry_start`, …) or `--mode rpc`, which reads JSONL
commands on stdin (`prompt`, `steer`, `follow_up`, `abort`,
`get_state`, `set_model`, `compact`, `switch_session`, `fork`) with
id-correlated responses: a long-lived process with stdin held open,
which is what the coordinator needs. Sessions are JSONL files under
`~/.pi/agent/sessions/`, movable with `--session-dir`, resumed with
`--session <id>` or `--continue`, forked with `--fork`. MCP is built in
(the project's earlier no-MCP stance was reversed): `mcpServers` in
`~/.pi/agent/mcp.json` or `.pi/mcp.json` over stdio or HTTP, tools
named `mcp__<server>__<tool>`, pinned with `--tools 'mcp__x__*'` and
`--exclude-tools`, and a per-tool `toolExposure` map. Pi has no
permission modes; gating is a TypeScript extension (`-e file.ts`) whose
`tool_call` hook returns `{block, reason}` or calls `ctx.ui.confirm()`,
which in RPC mode surfaces as `extension_ui_request {confirm | select |
input, timeout}` answered by the host with `extension_ui_response`: a
real relay channel, equivalent to Claude's `--permission-prompt-tool`
and Codex's `requestApproval`. Read-only is `--tools read,grep,find,ls`
(an allowlist replaces the defaults). Providers: forty built in by API
key (Anthropic, OpenAI, Mistral, OpenRouter, Groq, …), ChatGPT
subscription sign-in named, Claude subscription not named (a community
extension reuses Claude Code credentials and itself warns Anthropic
forbids it; Equipo will not use it); custom endpoints in
`~/.pi/agent/models.json` with `baseUrl`, `apiKey` and `api:
"openai-completions" | "openai-responses"`, so both wire shapes work.
Credentials in `~/.pi/agent/auth.json`. No sandbox of its own
(Docker recommended, which is Equipo's namespace). Startup network is
a version check, a model catalogue refresh and telemetry headers, all
off with `--offline` (`PI_OFFLINE=1`) plus `PI_SKIP_VERSION_CHECK` and
`PI_TELEMETRY=0`; project trust is `--approve` or `--no-approve`.
Usage arrives on `message_update` and `message_end` as `usage {input,
output, cacheRead, cacheWrite, totalTokens, cost}`. No provider
rate-limit headers are surfaced, so limit detection for Pi
connections is the runner's HTTP-level observation (§2.7).

**OpenCode** (`anomalyco/opencode`, MIT; two live majors with
different config keys and SDK packages: v1 `opencode-ai` 1.19.5 with
`provider`, `agent`, `permission`, `plugin`, and v2 `@opencode/cli`
2.2.6 with `providers`, `agents`, `permissions`, `plugins`).
`opencode run --format json` is coarse (`tool_use`, `step_start`,
`step_finish`, `text`, `error`) and auto-rejects asks unless `--auto`;
the real driving surface is `opencode serve` on `127.0.0.1` plus the
SDK, with `GET /event` SSE and `POST /session/:id/permissions/:id`
to answer `permission.asked`, or a plugin's `permission.ask` (v1) or
`permission.hook("evaluate")` (v2). MCP with per-agent tool pinning;
a read-only agent needs explicit `edit` and `shell` denies because the
built-in `plan` agent leaves shell open. Sessions in a SQLite file
(`~/.local/share/opencode/opencode.db`). Anthropic by API key only
(the docs quote Anthropic's prohibition on subscription plugins);
ChatGPT subscription login offered; custom OpenAI-compatible providers
documented, Ollama, LM Studio, llama.cpp and vLLM included; TensorX
has an official recipe. No sandbox. Startup network: update check,
models.dev catalogue refresh, on-demand provider package downloads
into `~/.cache/opencode`, and in v2 a shared background service to
disable (`--standalone`). Verdict: workable, with more moving parts
than Pi (an HTTP server inside the namespace, package downloads to
pre-cache, two majors to track).

**Command Code** (`commandcode.ai`, npm `command-code` 1.88.5,
`UNLICENSED`, Node 22; made by Command Code, not Cohere, the name is a
coincidence). `cmd -p --output-format json` emits NDJSON with only
`tool_running` documented plus a final `result {usage, stopReason}`;
no serve or RPC mode; `--continue`, `--resume`, sessions under
`~/.commandcode/projects/`; MCP client; permission modes `plan`
(read-only) and `dont-ask`, a `PreToolUse` hook that can allow or deny
but cannot ask a person; default provider is its own metered backend
(browser OAuth or `COMMAND_CODE_API_KEY`), with ChatGPT and Copilot
subscription logins and a BYOK file for Ollama, vLLM and OpenRouter
behind `--local-only`; no sandbox; auto-update, telemetry, a remote
model catalogue and credit checks to switch off. It also documents `cmd acp` (ACP over stdio), which
is a long-lived, prompt-and-permission protocol; whether its permission
requests reach the host and whether MCP tools are callable under it is
unprobed. Verdict: proprietary and backend-tied, nothing it does is
unavailable in Pi, so it comes last; its coordinator cell is "probe
`cmd acp` before deciding", not "no".

**Decision.** Pi is the one OpenAI-compatible harness for local
models, TensorX (chat wire), the Mistral API, OpenRouter and the CARLOS
gateway when it exists. OpenCode is the named fallback if Pi's RPC
mode fails the probes in §8. Mistral's Vibe runs only Mistral's
subscription; Command Code comes last. Claude Code against TensorX's
`/v1/messages` is a documented, tempting shortcut and is not used:
the point of one harness is one permission relay, one usage parser,
one containment profile and one fake CLI to test.
### 1.5 TensorX: a metered open-weight provider

TensorX Ltd (Dublin; `api.tensorx.ai`, docs at `docs.tensorx.ai`) hosts
open-weight models in the EU with zero retention, prepaid credits and
pay as you go. Verified from its docs: OpenAI-compatible
`POST /v1/chat/completions` with streaming and OpenAI-style tool
calling, `GET /v1/models` and `GET /v1/model/info` (capability flags such
as `supports_function_calling`, `max_input_tokens`); an
Anthropic-compatible `/v1/messages` with a documented Claude Code recipe
(`ANTHROPIC_BASE_URL=https://api.tensorx.ai`, `ANTHROPIC_API_KEY`, and
every `ANTHROPIC_*_MODEL` variable set to a TensorX model id, otherwise
the CLI asks for Anthropic ids that 404); **no Responses API**, so Codex
cannot be its harness; an official OpenCode provider recipe (`tensorx`,
`@ai-sdk/openai-compatible`, `{env:TENSORX_API_KEY}`); a community Pi
package only. Auth is `Authorization: Bearer`, keys shown once, env
`TENSORX_API_KEY`. Limits are per key (60 requests and 2M tokens a
minute by default, raised by spend tier); a 429 carries `retry-after`
and `x-ratelimit-reset` with `error.reason` of `rate_limit_requests`,
`rate_limit_tokens` or `rate_limit_concurrent`, and successes carry
`x-ratelimit-remaining-*` headers, so TensorX is the one metered
provider that gives Equipo live headroom. Prices (per million, in and
out): glm-5.3-flash $0.20 and $0.50, deepseek-v4-flash $0.25 and $0.30,
glm-5.3 $1.75 and $4.50, kimi-k3.1-pro $3.00 and $15.00. Usage is a
dashboard, no API, so Equipo's spend figure is computed from recorded
tokens and a price table the connection carries (§6). Unverified and
for the builder to probe: streamed tool-call chunk shape under the
chat API, and whether `/v1/messages` honours prompt caching and the
`tool_choice` Claude Code sends.

### 1.6 Mistral: a subscription that covers a real CLI

Mistral's coding product is now **Vibe** (Le Chat renamed), and the
CLI is open source (`mistralai/mistral-vibe`, Apache 2.0, Python with
a Rust TUI). Verified: sign-in is browser-based to the Mistral account
by default, or `MISTRAL_API_KEY` from env, `~/.vibe/.env` or the
keyring; headless is `vibe -p "…" --output streaming` (one JSON object
per message), with `--max-turns`, `--max-price`, `--time-limit`,
`--continue` and `--resume <id>`; MCP servers over stdio and HTTP in
`[[mcp_servers]]`; permissions `ask`, `accept-edits`, `smart-approve`
and `auto-approve`, with headless denying anything that needs approval
unless `--auto-approve`, per-tool `permission` keys and `pre_tool` and
`post_tool` hooks; `outside_workdir = "deny"`; custom providers with
`api_style = "openai"` and `api_base`, including a `llamacpp` preset
and a vLLM example; **no OS sandbox** (the docs say run auto-approve
in a disposable container, which is what Equipo's namespace is).
Exit codes 0 to 3. The only built-in Mistral model is
`mistral-medium-3.5`, itself deprecated from 2026-10-31 with Mistral
Large 4 as the named successor; Devstral 2 retires 2026-07-31.

What the subscription covers, from Mistral's billing docs: "each
Mistral plan includes monthly usage that is shared across Studio, the
API, and Vibe Code", Pro at $14.99 a month, with pay as you go as
prepaid overflow at API rates. A plan key made under Code, Vibe CLI
draws on that budget; the help centre says API automation should use a
pay-as-you-go key, not a plan key. The budget's size is not published,
and a support reply seen only on Reddit says the allowance applies
inside official Vibe clients; running the official CLI is inside that
line, driving the API from Pi or OpenCode with a plan key may not be.
So Paul's subscription reaches Equipo as **Vibe CLI, a subscription
connection on its own harness** (`provider: mistral_cli`), and the
Mistral API reaches it as an ordinary metered endpoint
(`api.mistral.ai/v1`, chat completions, a preview Responses API, no
Anthropic-compatible route) with its own key. Mistral API limits are
per workspace with `Retry-After` on 429 and no remaining headers;
usage is in the admin panel, the usage API being Enterprise only, so
spend is computed from tokens and the price table (Large 4 $0.70 in
and $2.10 out, Small 4 $0.15 and $0.60, Codestral 25.08 $0.30 and
$0.90).

Vibe also documents an experimental `run-server` mode, so a long-lived
coordinator process is not ruled out; whether it relays approvals to a
host is unprobed, and the matrix marks its coordinator cell "probe
`run-server` before deciding". It is a candidate for the single
OpenAI-compatible harness too (headless mode, streaming JSON, MCP,
resume, hooks, custom providers), with the drawback of being Mistral's
product driving other people's models; §5 scores it beside Pi.
### 1.7 Later: Gemini and Muse

Both are parked, with the facts that decided it. Gemini CLI was
replaced by Antigravity CLI for unpaid and Google One tiers on
2026-06-18 and is now aimed at Code Assist Standard and Enterprise; its
Google OAuth client is fixed in source with loopback-only redirects, its
`NO_BROWSER` flow needs a pasted code, Google's terms forbid reaching
the Code Assist service through third-party software, and it has no
container-free Linux sandbox. Its API-key path (`GEMINI_API_KEY`) works
headlessly with `--output-format stream-json`, MCP servers and
`--approval-mode`, so a Gemini API key could later be a metered
connection under its own harness; not designed here. "Muse" is Meta's
Muse Code (beta 2026-08-05, stable 2026-08-31): a real harness with
`muse exec`, `muse serve` over stdio, MCP, approvals and an OS sandbox,
but locked to Meta's Muse Spark models with plans from $5 a month and no
documented limit reporting. Paul has neither account. Both get a row in
the matrix marked "later" and nothing else.

## 2. Connecting from the app

### 2.1 What a connection is

A **connection** row on the instance: `id`, `person`, `runner_id`,
`provider` (`claude`, `codex`, `endpoint`, later `mistral_cli`,
`command_code`), `harness`, `kind` (`subscription`, `api_key`,
`endpoint`), `label` (the observed email, or a name the person typed),
`state` (`connecting`, `healthy`, `limited`, `sign_in_again`, `error`,
`signed_out`), `headroom` (`{utilization, resets_at, windows[]}`, null
when the provider reports nothing), `plan` (`planType` from Codex,
nothing from Claude), `models[]` for endpoints, `preference_rank`,
`created_at`, `checked_at`, `revision`. No secret, no path, no raw CLI
output; a guard test checks every field, as the Mac runners spec does
for `capabilities`. On the runner, the same connection is a dedicated
home `~/.local/share/equipo/accounts/<provider>-<n>` (today's layout),
a `connections` table row with the same id, and whatever the harness
keeps there. The existing `wire.Account {id, provider, email, healthy,
headroom}` in `hello` is **replaced** by this record under
`hello.connections` (§7), with the runner protocol version bumped as the
Mac spec does; `accounts` leaves the wire. In copy the word "account"
survives only where it names the provider's own thing ("your Claude
account").

Every flow below is a **connection attempt**: the app POSTs
`/api/v1/connections` with `{provider, kind, runner_id}`, the instance
writes the row in `connecting` and a durable `connect{connection,
provider, kind, step}` frame to that runner (the mailbox of thin v1 §4
and the runner-addressed mailbox of the Mac spec), and the runner
answers with `connection{id, state, headroom, label, prompt}` frames as
it progresses. The app shows one card, **Connecting Codex**, with
whatever the `prompt` says (a code and a link, a field, a spinner) and
replaces it with the connection line when `state` turns `healthy`. The
card dies with the attempt: ten minutes with no progress, or the
person's Cancel (`POST /connections/{id}/cancel`), ends it `error` with
one of a fixed list of reasons (`timed_out`, `cancelled`,
`provider_refused`, `runner_offline`, `identity_mismatch`,
`already_connected`), never provider text.

### 2.2 Device code: Codex

The runner starts `codex app-server` in the new account's home with the
containment of a converse action (egress to the provider hosts only;
the login hosts are allowed for this one action and denied to runtime
copies as today), sends `account/login/start {type: chatgptDeviceCode}`,
and relays `verificationUrl` and `userCode` in the `prompt`. The card
shows "Go to chatgpt.com/codex/device and enter **XXXX-XXXX**" with the
link tappable. The app-server polls; `account/login/completed {success}`
arrives; the runner calls `account/read` for the email and plan,
`account/rateLimits/read` for headroom, records the identity, and
reports `healthy`. Nothing moves from the app to the runner but the
request to begin, and nothing moves back but a code OpenAI generated
for display. If the person has not enabled device login the app-server
reports an error and the card says so with the settings link; the
reason is `provider_refused`. One real staged device-code sign-in is
the witness for slice 1, together with the one real staged refresh
thin v1 §3 already owes.

### 2.3 Claude subscription: the binary's own flow, nothing relayed

The policy in §1.1 fixes this flow: the unmodified `claude` performs
the sign-in in the account's home, and Equipo neither forwards the
code nor holds the token. What the app can do is start it, show the
link, and detect the outcome. Three cases, decided by where the
person's browser is relative to the runner:

1. **Browser on the runner's machine** (a Mac runner, or Paul at
   Tito Studio with the runner local). The runner starts `claude auth
   login` in the new home with a pseudo-terminal, reads the authorize
   URL from its output (the URL is not a secret; the code is), and
   sends it in `prompt`. The app shows "Sign in to Claude" with the
   link; the native app or the browser opens it on the same machine;
   claude.ai redirects to `http://localhost:<port>/callback`, which the
   CLI is listening on; no paste. The runner sees the CLI exit 0, runs
   `claude auth status` in the home, records the email, reports
   `healthy`. The runner knows it is this case when the app's request
   carries `same_machine: true`, which the native app sets when it is
   running on the runner's host (Mac spec §1.1 gives both a stable
   identity) and the web app sets when the person taps "I am at this
   machine".
2. **Browser elsewhere, runner remote** (Paul on his phone, runner on
   docs-t1). The loopback redirect cannot reach the CLI. A bridge was
   considered: a listener on the person's device forwarding the
   callback to the runner over Equipo's channel. That is possible only
   with a native app on the device (a web page cannot listen on
   localhost, and claude.ai redirects to `localhost`, not to a URL
   Equipo controls), and even then the authorization code would pass
   through Equipo's software, which is the intermediation Anthropic's
   terms name. So Equipo does not build it. The card instead says
   "Claude sign-in finishes on the machine that runs your runner" and
   offers the two permitted ways: finish at that machine (case 1 later),
   or in a terminal there run `equipo-runner login claude` and paste
   the code where the CLI asks. The paste goes into the CLI, on the
   runner, never into Equipo.
3. **No token importer.** `claude setup-token` prints a one-year token;
   a person could type it into a terminal on the runner, but Equipo's
   command reading it would be Equipo handling a subscription token,
   which is the intermediation the terms forbid. There is no `--token`
   path. Claude is signed in only directly to the unmodified binary:
   loopback on the runner's machine, or finish signing in on the
   runner. A Claude **API key** connection (§2.4) is the way to use
   Claude without a browser on that machine.

**Adding a second Claude account in the app** is therefore: tap Add,
choose Claude, and either finish on the runner's machine (no paste) or
be told plainly to finish signing in on the runner. On Linux every
Claude account gets its own home and the copy cycle of thin v1 §2
applies unchanged; the Mac's Keychain question (Mac spec §3.4, probe P3)
decides whether a Mac runner can hold more than one Claude account.

### 2.4 API keys, sealed to the runner

The app never sends a key to the instance in the clear, and the instance
never stores one it can read. The runner holds an ed25519 identity key
from enrolment (`internal/runner/enrol.go`), whose fingerprint the owner
checked on the approval page (`runner.fingerprint`). The **seal key** is
the X25519 key derived from that same ed25519 key (the standard
birational map, as libsodium's `crypto_sign_ed25519_pk_to_curve25519`),
so the public key the instance republishes on `Runner.seal_key` is
verifiable by the app against the fingerprint approved at enrolment,
and a substituted key would not match it. The native apps compare and
refuse; the web app trusts the instance it is served by, which is
already true of everything it shows, and that limit is stated in the
Connections screen's help text.

**The trust assumption, as built (2026-11-10, Claude setup tokens).** The
runner sends its seal key in every hello over its authenticated
connection, and the instance republishes it as received. The instance
keeps only a hash of the enrolment key, so it cannot itself check the
seal key against it, and the runner does not sign the seal key: the
web app seals to whatever key the instance it is served by publishes.
An attacker who controls the instance can therefore substitute a key
and read a secret pasted afterwards; such an attacker can already serve
a page that reads the field, so the seal adds nothing against it and
protects against everything else (the instance's database, logs,
backups, its operators reading rows, and other runners). When the native
apps arrive (slice 4) the runner also publishes its ed25519 public key
and the apps check both its fingerprint against the one approved at
enrolment and the seal key against its birational map, refusing on a
mismatch.

**A pasted Claude token on the runner, as built.** The token lives only
in `.oauth-token` (0600) in the connection's own home, outside every
model-readable path, and reaches each Claude launch as
`CLAUDE_CODE_OAUTH_TOKEN` through bubblewrap's `--args` pipe, never in
argv, a manifest or a record. Inside the namespace two processes hold
it in their environment: the namespace helper (PID 1), which makes
itself non-dumpable before the CLI starts, so the CLI's descendants,
which have no capabilities, cannot read its `/proc/1/environ`; and the
unmodified CLI. The model reaches the CLI's process only through tools:
- Bash: every command runs in the CLI's own sandbox. The policy sets
  `sandbox.enabled`, `failIfUnavailable`, `allowUnsandboxedCommands:
  false` and no `excludedCommands`, and the launcher refuses any other
  settings, so `enableWeakerNestedSandbox` stays at its default, false
  (it is not written out: that would change the certified policy
  hashes). In the pinned 2.1.312 (read from the binary's sandbox
  builder) that sandbox is a nested bubblewrap with a new user, PID and
  mount namespace and a fresh `/proc` (`--unshare-user --unshare-pid
  --proc /proc`); only `enableWeakerNestedSandbox: true` makes it bind
  the inherited `/proc`, and there is no automatic fallback.
  So a command cannot name the CLI or any ancestor. A second barrier
  holds on its own: a process in a child user namespace has no ptrace
  rights over the CLI, so even an inherited `/proc` refuses its
  `environ`. `CLAUDE_CODE_SUBPROCESS_ENV_SCRUB=1` keeps the variable
  out of the command's own environment.
- Read, Glob, Grep: native rules deny `/proc` and `/dev/fd` (and the
  sandbox denies them too).
`TestToolCannotReadCLIEnvironment` (containment) runs a stand-in CLI
holding a canary token inside the real namespace and starts a probe the
way the CLI starts a Bash command. Run directly, the probe reads the
token; in the sandbox it reads `/proc/<pid>/environ` for the stand-in's
PID, its parent, PID 1 and every visible process, each thread's
`/proc/<pid>/task/<tid>/environ`, `/proc/self/../<pid>/environ` and
`/proc/<pid>/root/proc/<pid>/environ` (through itself, its parent and
PID 1), and every read fails and the stand-in is not visible at all.
Binding the inherited `/proc`, or dropping the PID namespace, makes
the test fail, and so does a readable `/proc/1/environ` even from a
direct child. What the test cannot show is the real CLI: on the first
live paste, check from the model's Bash that `ls /proc` lists only the
sandbox's own processes and that no `/proc/*/environ` contains
`CLAUDE_CODE_OAUTH_TOKEN`; and recheck the sandbox builder at every CLI
version bump. The containment's egress reaches only the provider's
hosts, and a leaked token is revoked by running `claude setup-token`
again and signing the old connection out. Also to check on the first
live paste: `claude auth status --json` reports `loggedIn: true` with
only the variable set; the CLI writes no `.credentials.json` into the
home; and the variable is absent from the model's Bash environment.

**Claude's sign-in by a link, as built (2026-11-10).** Paul, looking at
the token card: "Can you not run this on the server and get a link to
give to the browser? We're trying to avoid the round-trip over SSH
here." Ruling: the one-time sign-in code is relayed through Equipo,
sealed, the same category of risk accepted for the pasted token. This
replaces §2.3 case 2's terminal card (and its watcher) as the way to
add Claude with the browser elsewhere, and case 1's loopback sign-in
"at this machine" too: the app refuses `same_machine` and the runner
ignores it. A token row's Sign in again and the renewal line start
this sign-in, the paste offered second. The runner runs the unmodified
`claude setup-token` itself, on a pseudo-terminal, contained like every
provider launch (the `signin-v1` policy, `provider.BuildSignInPolicy`):
its own bubblewrap namespace, recorded before anything forks, whose
only writable places, its home and /tmp, are the namespace's own memory
(tmpfs capped at 64 MiB each, gone with it; nothing the CLI writes
during the exchange reaches a disk), the connection's dedicated home
and the runner's state not mounted (the runner writes the token into
the home itself, from the CLI's output), no workspace or tool socket,
`BROWSER` a program that opens nothing, and egress through the relay to
`platform.claude.com` and `api.anthropic.com` only. Those hosts were
read from the pinned CLI 2.1.312 statically: its production OAuth
config has `TOKEN_URL` `https://platform.claude.com/v1/oauth/token`
(the code exchange) and `BASE_API_URL` `https://api.anthropic.com`;
setup-token fetches no profile and stores no credential, prints the
token and exits after half a second. Stopping the CLI kills its whole
namespace and waits for the exit to be proven, children included;
after a runner crash the next start recovers the attempt's namespace
(killed if it survived, its exit verified) before deleting its home.
The runner reads the authorize URL the CLI prints (through ANSI and OSC
8 escapes and redraws, only once the link's end has arrived; only https
on claude.com or claude.ai whose redirect is
`platform.claude.com/oauth/code/callback`). The card
(prompt kind `authorize_link`) shows Open Anthropic and Copy link, then
"Paste the code Anthropic shows you". The page seals the code exactly
as it seals a token, bound to `endpoint`
`https://platform.claude.com/oauth/code/callback` and to the card's
`attempt`; the instance relays one box per card. The runner checks the
box as it checks a token's, records `(connection, attempt)` in
`seen_seals` in one transaction with the attempt still running, and
types the code into the waiting CLI; the code is never written to
disk. The token the CLI prints is kept exactly as a pasted one (the
0600 `.oauth-token`, committed with the attempt turned kind `token`),
then probed, bound and checked with one real request; healthy only
then. A wrong code is said on the card with the next attempt: the same
link while the CLI asks again, else the CLI is started again and the
card shows its new link. The CLI exiting on its own starts it again
with a new link (at most four runs, five codes). Cancel and the
attempt's time limit kill the CLI's process group and remove the home.
A stop before the token is committed loses the CLI with the process:
the restart ends the attempt `runner_offline` and deletes its home;
after the commit the restart carries it on as a token attempt. To
confirm on the first live use, since only the start was observed (CLI
2.1.321): what the CLI prints after a right code (the runner takes the
first whole `sk-ant-oat` token in its output) and after a wrong one
(the runner looks for error, invalid, failed, expired or wrong; the
static read says "OAuth error: ..." then Enter to retry, the same link
for a code it cannot read and a new sign-in for one the exchange
refuses, and the runner presses Enter once), that a typed code followed
by a separate carriage return is taken as entered, that the CLI honours
the relay's proxy for the exchange, and that what it writes fits the
in-memory home.

**Sealing.** The app seals with libsodium `crypto_box_seal` over a
payload `{secret, runner_id, connection_id, provider, endpoint,
attempt, expires_at}`, where `endpoint` is the full origin, scheme,
host and port (`https://api.tensorx.ai:443`); the instance-visible
fields (`runner_id`, `connection_id`, `provider`, `endpoint`,
`attempt`, `expires_at`)
travel beside the box in the clear and the runner **rejects the box if
any of them differs from the plaintext inside**, if `expires_at`
(ten minutes from sealing) has passed, if the connection attempt is
not the one it is currently running, or if the `(connection_id,
attempt)` pair has been seen before (a `seen_seals` table kept for a
day). The instance copies the opaque box into the durable `connect`
frame. **Delivery on the runner is a small state machine** with one
durable step at a time: (i) `received`: the frame id is in the inbox,
nothing written; (ii) `staged`: the secret is written to
`<home>/.secret.tmp` (0600) and fsynced, together with the directory;
(iii) `committed`: in one SQLite transaction the `seen_seals` row
`(connection_id, attempt, frame_id)` and the connection's state
`credential_present` are written, and the temp file is renamed to its
final name (`ANTHROPIC_API_KEY` env file for Claude, the harness's
auth file for an endpoint; for Codex the rename is replaced by
`codex login --with-api-key` reading the temp file, run before the
transaction and verified by `account/read` inside it) with the
directory fsynced; (iv) `acked`: the ack is sent. Recovery after a
crash: a temp file with no `seen_seals` row is deleted and the frame
reprocessed from `received`; a `seen_seals` row with the final file
present is `committed`, so the resend only needs the ack; a
`seen_seals` row with neither file is impossible by construction (same
transaction) and is treated as `committed` with the connection marked
`error`. A resend of a frame whose `(connection_id, attempt)` is in
`seen_seals` is answered with an ack and nothing else. The buffer is
zeroed after (ii). The instance then
deletes the payload column. Honesty about that deletion: the
ciphertext may persist in SQLite's WAL and in backups until they
rotate. It is useless without the runner's private key, it names an
attempt that cannot be replayed, and it expires in ten minutes, so the
design accepts that residue and says so; it does not claim erasure.
**Cancel** during `connecting` writes a `cancelled` marker the runner
checks before writing the secret; a late success report for a
cancelled attempt is dropped by the instance (`Attempt` and state
checks as `chat/runner.go` does for turns) and the runner deletes the
home. A sealed payload is capped at 4 KB and never logged; the mailbox
payload column is excluded from every diagnostic dump, as credential
bytes already are. Rotation is "sign out, add again". Sealed keys land
in slice 2 with the endpoints; slice 1 has no key entry.

### 2.5 Endpoints, with a test call (slice 2)

An endpoint connection is `{base_url, label, sealed key or none,
harness, local}`. Two transports, because the existing egress relay
cannot carry the local case: `egress/proxy.go` accepts one bounded
CONNECT to a public DNS name on port 443, and the namespace's
`localhost` is not the host's, so an Ollama on the runner's machine is
unreachable through it by design. **Public endpoints** (TensorX,
Mistral, OpenRouter, the CARLOS gateway) use the existing relay with
the connection's host added to its allow list for that connection's
actions, HTTPS only. **Local endpoints** use a second, narrower
listener the runner opens outside the namespace and binds into it on a
fixed loopback port: it forwards plain HTTP to exactly one `host:port`
recorded on the connection (the host's loopback or a LAN address the
person typed), resolves the name once at connect time and pins the
address, refuses redirects (`3xx` is returned to the harness as an
error, never followed), admits only the HTTP methods and paths an
OpenAI-compatible client uses, and is mounted only for actions on that
connection. The harness is pointed at the loopback port, not at the
host. On connect the runner fetches `/v1/models`, makes a one-token
completion with the first model, records the model list and latency,
and reports `healthy` with `models[]`; the card shows the models and
lets the person pick a default. Probes before this ships (slice 2):
the local listener is unreachable from a step whose connection is not
local; a redirect from the endpoint is refused; a DNS change after
connect does not move the pinned address; the listener dies with the
namespace. For OpenRouter the key can arrive by its PKCE flow (§2.6)
instead of typing.

### 2.6 OAuth without a paste: what each provider allows

Paul's question was whether the app can do "proper OAuth handoff
without pasting a code". The answer per provider, from the official
sources in §1:

| Provider | Flow Equipo uses | Paste needed | Code exchanged where | Tokens rest where |
|---|---|---|---|---|
| Codex (ChatGPT plan) | Device code via `account/login/start` | No | Runner, by the app-server polling OpenAI | Runner home (`auth.json`) |
| Codex (API key) | Sealed key | No | n/a | Runner home |
| Claude (subscription), browser on runner's machine | Removed 2026-11-10: the same sign-in by a link as below | n/a | n/a | n/a |
| Claude (subscription), runner remote | The runner's own `claude setup-token`; the app shows its link (as built 2026-11-10, §2.4) | Yes, the code, sealed to the runner and typed into the CLI | Runner, by the CLI | Runner home (`.oauth-token`) |
| Claude (`setup-token`) | A pasted token, sealed to the runner (as built 2026-11-09, §2.4) | Yes, sealed | n/a | Runner home (`.oauth-token`) |
| Claude (API key) | Sealed key | No | n/a | Runner home |
| OpenRouter | PKCE: app opens `openrouter.ai/auth?callback_url=…&code_challenge=…`; the callback lands on Equipo's web app or the native app's link; the app seals `code` plus `code_verifier` to the runner, which POSTs `/api/v1/auth/keys` and keeps the returned key | No | Runner | Runner home |
| Local or other endpoint | Sealed key or none, test call | No | n/a | Runner home |
| Hugging Face (not designed) | Has registered-app OAuth with loopback, custom-scheme and device-code flows | No | would be runner | would be runner |
| Gemini (later) | Fixed Google client, loopback only; `NO_BROWSER` pastes a code; third-party use of the Code Assist service forbidden | Yes | CLI | CLI home |

Only OpenRouter (and Hugging Face) let a third party register or skip
a client and receive the redirect at a URL Equipo controls. For
OpenRouter the flow is hardened as follows: the app generates the
verifier and uses `S256`; the `callback_url` is an instance route that
carries the connection attempt id in its path and serves a page with
`Referrer-Policy: no-referrer` whose first act is to read `code` from
the query, replace the URL without the query (`history.replaceState`)
and seal `{code, code_verifier}` to the runner bound to that attempt
(§2.4); the instance's access log for that route omits the query
string; a code older than ten minutes (OpenRouter's own expiry) or for
an attempt that is not `connecting` is refused by the runner, which
does the exchange at `/api/v1/auth/keys` and keeps the returned key.
The instance sees the code for the duration of one request and
never stores it; that is a weaker guarantee than for typed keys and
the spec says so. Whether OpenRouter accepts a custom scheme is
unconfirmed, so the native apps use an https app link to the Equipo
origin. Codex needs no paste because device code is its own protocol.
Claude is the one subscription where the loopback is the only no-paste
path, and the terms make the sign-in belong to the CLI; Equipo's job is
to make the same-machine case recognisable and the remote case honest.

### 2.7 Health, headroom, limits, refresh, sign out

**Health** is what the runner can prove: a `healthy` connection has a
valid credential (the CLI refresh under the source lock for Claude,
`account/read` for Codex, the harness's cheapest request for an
endpoint) checked on start, hourly, and before any turn that needs a
fresh copy, as today. `connecting` is not healthy and is never chosen.
`sign_in_again` is set on an `auth` failure (§3) or when refresh reports
a different identity (thin v1 §2). **Limited** is set on a `quota`
failure, with `resets_at` when the provider reported one. **All
telemetry comes from the harness side**: Claude's stream-json
(`rate_limit_event`, `api_retry`, `result`), the Codex app-server's
notifications (`account/rateLimits/updated`, `thread/tokenUsage/updated`,
`turn/completed`), and in slice 2 Pi's JSONL events. The egress relay
is a CONNECT tunnel (`egress/proxy.go`: one bounded CONNECT, port 443,
public addresses only) and cannot see upstream headers, so no design
here reads `Retry-After` or `x-ratelimit-*` off the wire; a metered
endpoint's limit is whatever its harness reports, and where the harness
reports nothing the connection becomes `limited` on the harness's
error event with no reset time and a cool-off of fifteen minutes,
doubling to an hour. Headroom is whatever the provider reports and
nothing more: Claude's optional `utilization` and `resetsAt` (one
figure, never labelled "weekly" or "session" because the SDK does not
say which window it describes), Codex's `primary` and `secondary`
windows when present, an endpoint's nothing ("unknown"). The Codex
decoder today validates and discards rate notices (`rate_notice_test`);
keeping them as state is slice 1 work. A connection leaves `limited`
when `resets_at` passes or a probe succeeds; the probe is the harness's
cheapest request, never a model turn, at most once per fifteen minutes.
**Sign out** is `DELETE /connections/{id}`: the runner runs the
harness's own logout (`claude auth logout`, `account/logout`, or
nothing for a key), deletes the home, ends sessions on that connection
(their rows stay, marked `connection_removed`), and reports
`signed_out`; the instance keeps the row thirty days for Usage history
and then deletes it.

## 3. Selection and failover

**The choice.** For each run the runner picks a **connection and model
pair** from the person's own connections on the runner that holds the
session or task. Eligible pairs are those whose matrix cell (§5) says
yes for the role and whose connection is `healthy` (not `connecting`,
`limited`, `sign_in_again`, `error` or `signed_out`). Among eligible
pairs the order is: the current binding, if the session or step already
has one and it is eligible (stickiness is a rule, not a tie-breaker:
a session leaves its connection only on a `quota` or `auth` failure,
an explicit override, or the preference exception stated in the
failover list below); then the tier floor the router set (§4); then the person's
preference for the role (§3, last paragraph); then headroom, where a
subscription's headroom is the provider's reported figure, a metered
connection with no report is "unknown" and ranks below any connection
with a reported figure, and a local endpoint is "unknown" too, chosen
by tier and preference rather than by a claim of being unlimited. The
function is small and pure: inputs are the connection list with their
models and matrix cells, the role, the tier floor, the preference and
the current binding; the output is one `(connection, model)` and a
reason code. It replaces `pickReviewer` in `internal/runner/thin/judge.go`
and the coordinator's binding choice, returns a `runner.AccountBinding`
as they do, and is unit-tested with a table.

**Failure kinds.** The runner classifies every provider failure before
it decides anything: `quota` (Claude `rate_limit_event {status:
rejected}` or `api_retry {error: rate_limit}` exhausting its retries;
Codex `account/rateLimits/updated` with a window at `usedPercent` 100
or `rateLimitReachedType` set, or `turn/completed {status: failed}`
whose error the decoder recognises as a usage limit); `auth`
(`authentication_failed`, `oauth_org_not_allowed`, `account_on_hold`,
`billing_error`; Codex `account/updated` to signed out or a 401 class
error): the connection becomes `sign_in_again`; `transient`
(`overloaded`, `server_error`, no response): retried on the same
connection by the existing retry policy, never a failover. Only
`quota` makes a connection `limited`; only `quota` and `auth` trigger
failover. Fields are optional everywhere: `resetsAt` and `utilization`
may be absent, Codex windows may be absent; a `limited` connection
without a reset time shows "Limited, no reset time reported" and is
re-probed on the §2.7 schedule.

**Coordinator failover, with exactly-once effects.** Today a tool call
id is `turn/attempt/useID` (`thin/bridge.go`), so simply replaying the
turn on a new attempt would execute `start_task`, `add_project` or
`ask_person` again under new ids. Failover therefore runs in this
order, each step durable before the next:

1. The failed attempt is **terminated**: the runner kills the
   namespace and waits for the pidfd exit proof (thin v1 §4), as it
   does for cancel. No new attempt exists until then.
2. The turn enters a new nonterminal state **`waiting`**
   (`turn{state: waiting, reason: limited | sign_in_again}`), added to
   the turn state machine beside `queued` and `running`; `wire.Terminal`
   stays false for it, so `chat/runner.go` keeps accepting reports. The
   draft deltas are discarded as on cancel. If no eligible pair exists
   the turn stays `waiting` and the chat shows the card in the last
   paragraph; queued messages join the waiting turn.
3. The runner chooses a new pair and **advances the attempt** in its
   `runs` row and in a `turn{state: running, attempt: n+1}` report,
   which the instance accepts only as a forward transition from
   `waiting` for that turn.
4. Before the new process gets the frame, the runner **reconciles
   effects through the turn's mutation ledger**. Matching on arguments
   is not used: a paraphrased `ask_person` would defeat it. Instead the
   instance keeps a per-turn **ledger** of the designated mutating
   tools, written in the same transaction as the effect: `add_project`
   (kind `project`, target the repository name), `create_project`
   (kind `project_create`, target the name), `set_project_home` (kind
   `home`, target the person), `record_task` (kind `task_record`,
   target the task id it created), `start_task` (kind `task_start`,
   target the task id), `cancel_task` (kind `task_cancel`, target the
   task), `add_finding` (kind `finding`, target task and finding id),
   `ask_person` (kind `ask`, target the card id). The runner asks for
   the ledger (`tool_calls{turn}`, answered with the ledger entries and
   their recorded results) and the new attempt's frame is the person's
   messages plus a runner-written summary that lists each completed
   operation by kind and target ("oficina/sample is already added; task
   tk_… is recorded and started; the person was asked and answered Y").
   The instance then **enforces per-kind rules on any later call in the
   same turn, whatever the model's wording**: `ask` opens at most one
   card per turn, so a second `ask_person` in the turn returns the open
   card (or its answer) rather than creating one; `task_start` is
   idempotent per task id; `task_record` within a turn that already
   recorded a task attaches the call to that task and returns it
   instead of creating another; `project` and `project_create` are
   idempotent per name; `home` is idempotent per person and still
   needs the person's own words (slice 2b); `finding` is idempotent per
   task and normalised text; `task_cancel` is idempotent per task. A
   call the rules fold into an earlier operation returns the stored
   result with `replayed: true`. **Reads are never deduplicated**:
   `status`, `read_task` and every other read run fresh on every
   attempt, so `status`, `start_task`, `status` sees the started task.
   The designated list is a constant in `wire` and the ledger refuses a
   kind it does not know.
5. The frame goes to the new session, seeded from the notebook, the
   house rule and the tail as thin v1 §2, and the reply arrives with one
   quiet line under it: "Switched to Codex; Claude resets Mon 10:00"
   (`chat.switched`), or "Switched to Codex" when no reset time was
   reported. **The one exception to stickiness**: when a connection the
   person prefers has recovered, the coordinator returns to it only at
   a natural boundary, the start of a new turn after the current
   session's turn has ended and no messages are queued, never mid-turn
   and never for a step or an ask in flight; the line is shown only
   when the switch happens, and the old session is resumed with a fresh
   notebook and tail injection (thin v1 §2's daily reset rule covers
   staleness).

A cancel during `waiting` ends the turn `cancelled` and voids the
pending frame; a cancel that arrives after step 3 targets attempt n+1
and ignores stale reports for attempt n (`chat/runner.go` already drops
reports for `Attempt < r.Attempt`).

**Engineering mid-step.** A step whose harness fails on `quota` or
`auth` is a failed attempt as any crash is: termination proof first,
nothing committed (the worktree is discarded; partial work is not a
candidate), then a new attempt on another eligible pair avoiding the
connections that failed (`avoid_connections[]` on dispatch replaces
`avoid_account`), same brief. The step records both attempts and their
pairs; the card shows "Engineering on Codex (Claude was limited)".
With no eligible pair the step waits in `queued` with reason
`no_connection` and resumes on its own when a connection returns.

**Review across families.** Thin v1 §3's rule stands, with the family
read from the pair actually chosen, not from the connection: an
endpoint that serves several model families is `other_family` only
when the chosen model's family differs from Engineering's. `other_family`
first, then `same_family` with fresh context, then `same_account`; the
label is recorded on the step.

**Ask the implementer** keeps its exact binding: the kept session on
the connection and model that ran the step (slice 4b). It never moves;
if that connection is not `healthy` the question fails
`account_unavailable` with the reset time in the card.

**"Nothing can answer."** When no eligible pair exists for the
coordinator the turn is `waiting` with reason `no_connection`, and the
chat shows a card in place of `chat.failed`: "Nothing can answer right
now. Claude resets Mon 10:00; Codex is signed out." with one action,
**Add a connection**. The message is not lost and is not resent by the
person; when a connection becomes eligible the runner advances the
attempt and the reply arrives. The person may cancel the turn.
`wire.Reasons` gains `limited` and `no_connection`; `Task.NeedsYou`
gains `no_connection`; the old "Send your message again to retry" line
goes.

**The preference.** Settings gains one quiet row per role, "Coordinator
prefers", "Engineering prefers", "Review prefers", each a picker over
the person's connections and, for endpoints, a model, plus "Automatic"
(the default). It sits after the tier floor in the order above, so a
preference cannot put a `strong` job on a `cheap` model, and it never
overrides health. `PUT /api/v1/preferences {role, connection_id,
model | null, revision}`. Per task, the task page offers "Run on …"
before the first step starts and "Retry on …" at a failed step; a
per-task choice is a tier override as well, recorded as such.

## 4. Routing: who does what

Paul's framing: the coordinator "would probably use a specialist or
some technique to decide who to delegate jobs to", balancing cost and
model choice. Three options were weighed.

A **routing specialist**, a model turn that reads the brief and picks
a connection, costs a turn per task (on the very connection it is
trying to save), is hard to test (its choices are text), and its
reasons would be its own words rather than facts. A **deterministic
policy** alone cannot see what the job is: a README typo and a
migration of the payments module look the same to a function over
headroom. The **hybrid** takes the one thing a model is good at here,
reading the brief, and leaves the arithmetic to a function. Recommended.

**Classification.** When the coordinator calls `record_task` or
`start_task` it adds three fields it already knows from the
conversation: `size` (`small`, `medium`, `large`), `risk` (`low`,
`normal`, `high`: touches auth, payments, deploy, data migration, or
the person said "careful"), and `kind` (`fix`, `feature`, `refactor`,
`docs`, `test`, `investigate`). The tool schema makes them required
enums with one-line definitions; a missing or invalid class defaults
to `medium`, `normal`, `feature` and is recorded as defaulted. The
coordinator does not choose a connection; it describes the job.

**Models, not connections, have tiers and families.** A connection
offers one or more models (a subscription offers the provider's
current models; an endpoint offers its `models[]`). The runner ships a
static **model map**: for each known model id, its family (`claude`,
`gpt`, `glm`, `deepseek`, `kimi`, `qwen`, `mistral`, `llama`, …), its
tier (`cheap`, `standard`, `strong`) and, for metered connections, a
price per million tokens with a `price_version`; an unknown model is
`cheap`, family `unknown`, and is reported so the map can be extended.
Two endpoints serving the same model are two pairs with the same
family and tier; one endpoint serving several families is several
pairs. Every step and turn records the pair that ran and its family,
and Review's `other_family` is judged on recorded families (§3).

**The policy.** A table, shipped as defaults and never edited by the
person in v1: a class maps to a **tier floor** per role. Engineering:
`small` and `low` risk floor at `cheap`; `medium` or `normal` at
`standard`; `large` or `high` at `strong`. Review: one tier above
Engineering's actual tier, minimum `standard`, another family where an
eligible pair exists. Coordinator: `standard` or above. Ask: pinned to
the step's pair. A pair's **cost signal** is `subscription` (within
plan: no marginal cost until limited, overage priced if the person
typed one), `metered` (price from the model map), or `free` (local).
The choice function of §3 applies, in its fixed order: eligibility,
stickiness, the tier floor as a filter, the preference, then headroom
with the cheapest cost signal first among equals. Nothing here needs
setup: with one Claude account every job lands there, exactly as
today; add a local Ollama and small fixes start moving to it; add
Codex and Review becomes cross-family.

**Cheap-first escalation.** A first pass whose pair is below `strong`
and that fails checks or gets `changes_requested` is retried one tier
up on the first fix round, on a different family if an eligible pair
exists; the second fix round (thin v1's `MaxFixRounds` 2) stays on the
escalated tier. Escalation is recorded on the step as `escalated_from`.
A `strong` first pass that fails stays `strong`.

**What the person sees.** One quiet line on the task card and in the
timeline: "Engineering on Codex, local model for the first pass" or
"Engineering on Claude (Paul prefers Claude)". The Usage page (§6)
sums it: "3 tasks moved to Codex while Claude was limited". Every
decision is a `routing` row: task, step, role, class, tier floor,
connection, model, family, reason (`sticky`, `preference`, `headroom`,
`cheapest`, `escalated`, `failover`, `only_option`,
`same_family_review`), so the line and the sum are read from data.
Override is per task ("Run on …", §3) or standing (the preference),
and an override is a `reason: preference` row like any other.

## 5. Tools and safety per harness, and the capability matrix

Every role has three needs the harness must meet, or it is marked
unsupported for that role: the **coordinator's MCP tools** (`status`,
`add_project`, `record_task`, `start_task`, `read_task`,
`cancel_task`, `ask_person`, and the slice 2 to 4c additions) over the
existing `equipo-tool-proxy` socket; the **permission relay** (a tool
call the harness will not make without an answer becomes `ask_person`
or a deny by policy); and the **tool shape per role**: read-only for
Review and ask, write plus shell for Engineering, no filesystem for
the coordinator.

**Containment** is identical for every harness on Linux: the same
bubblewrap namespace, egress relay with the connection's hosts only
(and, for `local` endpoints, the one local host and port), the
credential home mounted to the harness and denied to model tools,
pidfd termination proofs, `provider/policy.go`'s effective-policy
check extended with a Pi profile (exact argv, `--offline`,
`--no-approve`, `--session-dir`, `--tools`, the extension file's hash,
`mcp.json` and `models.json` contents, no inherited environment). Pi's
and Codex's own sandboxes are off inside the namespace (Codex
`danger-full-access`, Pi has none), as Codex's row already assumes; the
namespace is the containment. On the owner's Mac (Mac spec §4) Claude
Code's `sandbox.enabled` profile is trusted for Claude steps; Codex and
Pi on the Mac are parked until probe P5 shows Codex's Seatbelt nests
under `srt`, and Pi, having no sandbox, would run under an `srt`
profile of Equipo's own, which is slice F work there, not here. **Termination comes from the namespace, never from the harness**: Pi's
`abort` waits for the session to go idle and keeps the process alive
(its RPC docs), Codex's `turn/interrupt` ends a turn, Claude's SIGINT
ends a turn; Equipo kills the namespace and waits for the pidfd proof,
as today. Before any harness earns a "yes" cell it passes the same
**containment proofs** in CI and once on staging: it works through the
CONNECT relay with no direct network (proxy support); a model tool
cannot read the credential home or the runner's state (credential-read
denial, tried by a hostile prompt in the fake and a `cat` in staging);
shell is absent or restricted in the read-only roles; MCP tools are
exactly the pinned set and nothing else is callable; and killing the
namespace ends every descendant, including the harness's subprocesses
(descendant termination). Claude passes these today; Codex and Pi get
them as the first task of their slices. Each
harness gets a **fake CLI** in CI reproducing its pinned protocol from
recordings: `fakeclaude` exists, `fakecodex` is slice 1 here (the
app-server JSON-RPC including device-code login, `account/rateLimits`
and `thread/tokenUsage/updated`), `fakepi` is the local-models slice
(RPC mode, `extension_ui_request`, usage on `message_end`).

| Provider, harness | Coordinator | Engineering | Review | Ask | Limit and headroom signal | Slice |
|---|---|---|---|---|---|---|
| Claude subscription or API key, Claude Code | Yes (today) | Yes (today) | Yes (today) | Yes (today) | `rate_limit_event {utilization, resetsAt}`, one figure | Live; multi-account in 1 |
| ChatGPT plan or OpenAI key, Codex app-server | Yes: `turn/start`, MCP via `codex mcp`, approvals relayed | Yes: thin v1 §3 path | Yes: `sandbox_mode = read-only`, no write tools | Yes: `thread/resume` | `account/rateLimits` two windows with `resetsAt`, `thread/tokenUsage/updated` | 1 |
| Local model (Ollama, vLLM, LM Studio), Pi | Yes, if the model handles tool calls and the containment proofs pass; tier from the model map | Yes, tier from the model map | Yes, read-only tool allowlist; its family is the model's recorded family, so a local Llama reviewing a Claude step is `other_family` and a local model reviewing the same model elsewhere is `same_family` | Yes | None reported; HTTP 429 observation only | 2 |
| TensorX, Pi (chat wire) | Yes, `standard` tier for the larger models | Yes | Yes | Yes | 429 `retry-after`, `x-ratelimit-reset`, `x-ratelimit-remaining-*` | 2 |
| Mistral API or OpenRouter, Pi | Yes, `standard` | Yes | Yes | Yes | 429 `Retry-After`; OpenRouter key info endpoint later | 2 |
| Mistral subscription, Vibe CLI | Probe `run-server` before deciding; `-p` alone denies asks rather than relaying them | Yes: `--auto-approve` inside the namespace, MCP, `--resume` | Yes: tool `permission` denies for edit and shell | Yes: `--resume <id>` | 429 `Retry-After`; plan budget not reported | 3 |
| Command Code, BYOK `--local-only` | Probe `cmd acp` before deciding; `-p` hooks cannot ask | Yes, `--yolo` inside the namespace | Yes, `--permission-mode plan` | Yes, `--resume` | Exit code 5 on rate limit only | 5 |
| Gemini, Muse | Later | Later | Later | Later | | |

"Yes" in the Pi rows is conditional on the probes in §8 passing: RPC
mode holding a session across a hundred turns, `extension_ui_request`
reaching the host for a blocked tool, MCP tools pinned and callable,
and a clean exit under `turn/interrupt`'s equivalent (`abort`). A
harness that fails a probe keeps its row with the failing cell marked
`No` and the reason, and the choice function reads the matrix, so an
unsupported pair is never chosen.
## 6. Usage: one page for availability, spend and tokens

**Name.** "Usage". It is what the page shows, it reads as a noun in
the sidebar beside Tasks, Projects and Needs you, and it avoids both
"Cost management" and the slightly pompous "Capacity". The sidebar
entry carries a small dot only when something needs attention: a
connection `limited` or `sign_in_again`, or month-to-date spend over
the soft ceiling. Quiet otherwise.

**The page**, top to bottom. *Availability now*: one row per
connection, the label, the state in words ("Healthy", "Limited until
Mon 10:00", "Signed out"), and the provider's own headroom where it
reports one: Codex's two windows as two thin meters with "resets in 3 h
12 m" and "resets Thu", Claude's one `utilization` figure as one meter
with its `resetsAt`, TensorX's remaining requests and tokens from the
last response headers with the minute they refer to, a local endpoint
"Unknown, no limit reported". Never a percentage the provider did not
send. *Spend this month*: metered connections only, the sum of recorded
tokens times the connection's price table, labelled "estimated from
tokens" (TensorX and Mistral publish no usage API; OpenRouter's
`/api/v1/key` or generation endpoint can later replace the estimate
with the real figure), next to the soft ceiling with the 80% line and
Pause from thin v1 slice 6, now per person across all metered
connections. Subscriptions show as a flat plan line ("Claude Max,
$200 a month" typed once by the person, or blank) with their token use
beside it, never a fake dollar figure; local endpoints show "Free" and
their tokens. *Token use*: a table with day, week and month tabs, rows
by connection, by role, by project and by task (the four groupings are
tabs over one dataset), columns input, cached input, output, and the
estimate where there is one. *Routing*: the sum lines from §4 for the
period ("3 tasks moved to Codex while Claude was limited", "12 small
fixes ran on the local model", "2 escalations after review").

**Recording, from day one.** The runner writes one `usage` row per
**attempt** of a turn, step or question, whether it replied, failed,
was cancelled or is still waiting for a reconnect: person, connection,
model, harness, role, project, task, step, turn, attempt, outcome
(`replied | failed | cancelled | superseded`), input, cached input,
cache write, output, reasoning output (each nullable: a harness that
did not report a figure leaves null, never zero), `complete` (true
only when the harness's final usage message for that attempt was
seen), estimated cost in micro-dollars with `price_version` (the id of
the price-table revision used; null for a subscription within plan and
for a local endpoint), and recorded at. Per harness: Claude's `result`
message gives `usage` and `modelUsage` once per attempt, and
`modelUsage` is kept per model (one row per model when a turn used
several); Codex sends several `thread/tokenUsage/updated` notices within
one turn and across a resume, and the first notice after a resume can
already include new consumption (the local fixtures in
`provider/codex/testdata` show totals of 14,054 then 28,254 input
tokens within one turn), so the runner never subtracts a post-resume
notice. It captures a **verified pre-turn baseline**: the `total` from
the last notice of the previous attempt on that thread, stored on the
thread's `sessions` row when that attempt completed, and confirmed
before `turn/start` by the first notice carrying the previous `turnId`
or by a thread whose stored baseline is zero for a new thread. The
attempt's figure is the last `total` of this turn minus that baseline;
`last` is a consistency check; a notice whose `turnId` or `threadId`
does not match the attempt is dropped. When no verified baseline
exists (a resume with no stored total, a thread Equipo did not create)
the row records the turn's `last` values summed where they can be and
`complete: false`, never a subtraction; Pi's `message_end.usage`
(slice 2) is summed over the attempt's messages. Rows travel in the
existing `reply`, `step` and `answer` frames as a `usage` array (the
present `wire.Usage` "without cost data" becomes this shape), and a
`usage` frame of its own carries rows for attempts that produced no
reply. The instance stores them as a `usage` table keyed by
`(turn or step or question, attempt, model)`, so a resent frame is a
no-op; raw rows are kept 90 days, daily sums indefinitely. A
subscription is not free past its plan: Claude's `rate_limit_info`
carries `overageStatus` and `isUsingOverage`, and Codex's
`rateLimitReachedType` and `credits` say when paid credits are being
consumed; a row recorded under overage carries `overage: true` and is
counted in Spend at the connection's typed overage price, labelled as
such. Slice 1 records every field it can and shows nothing new; the
page comes later and finds the data waiting.

**Resources.** `GET /api/v1/usage?period=day|week|month&by=connection|
role|project|task` returns `UsageReport {period, from, to, rows[{key,
label, input, cached_input, output, reasoning_output, estimated_cost,
turns, steps}], spend {estimated, ceiling, paused}, routing[{line,
count}], revision}`; `GET /api/v1/connections` is the availability
list; `PUT /api/v1/usage/ceiling {monthly, paused, revision}` sets the
soft ceiling. Event `usage` fires once per committed `usage` row with
`{resource: usage, id, revision}` so the open page updates its sums;
`connection` events carry the availability changes. Fixtures:
`api/connections.json`, `api/usage-month.json`, `api/usage-ceiling.json`,
`api/event-usage.json`, `frames/reply-usage.json`,
`frames/step-usage.json`. The Snapshot gains `connections` and a
`usage_summary {limited, signed_out, over_ceiling}` for the sidebar dot.
## 7. API v1, wire and fixtures

**Resources.** `Connection` as in §2.1; `ConnectionList` at
`GET /api/v1/connections` (the person's own, every runner);
`POST /api/v1/connections {provider, kind, runner_id, label?, base_url?,
local?, sealed?, same_machine?}` returns `202` with the `Connection` in
`connecting`; `POST /connections/{id}/cancel`; `DELETE /connections/{id}`
(sign out); `GET /connections/{id}`; `PUT /api/v1/preferences {role,
connection_id | null, revision}` and `GET /api/v1/preferences`;
`UsageReport` and the ceiling as in §6. `Runner` gains `seal_key`.
`Step` gains `connection_id`, `tier`, `class {size, risk, kind}`,
`escalated_from`, `routing_reason`; `Task` gains `class` and
`connections[]` (what ran it). `Turn` gains `connection_id`. `Snapshot`
gains `connections`, `preferences`, `usage_summary`. Reasons:
`wire.Reasons` adds `no_connection`, `limited`, `connection_removed`;
`Task.NeedsYou` adds `no_connection`; connection attempt reasons are
their own list (§2.1). Events: `connection` (every state change and
headroom change, throttled to one per connection per minute for
headroom), `usage`, `preference`. The sidebar dot is computed by every
client from `usage_summary`, so the web and native apps agree.

**Frames.** Instance to runner: `connect{connection, provider, kind,
label, base_url, local, sealed, same_machine}` (durable; `sealed`
deleted after ack), `disconnect{connection}` (durable),
`cancel_connect{connection}`, `preference{role, connection}` (durable,
so the runner's choice function has it offline). Runner to instance:
`connection{id, state, label, plan, headroom, models, prompt {kind:
device_code | link | none, url, code}, reason}` (durable),
`routing{task, step, role, class, tier, connection, reason}` (durable,
with the `step` report), and `usage` objects on `reply`, `step` and
`answer`. `hello.accounts` becomes `hello.connections` with the full
record, `hello.seal_key` is added, and `sync` adds `connections` so a
reconnect reconciles state. `dispatch` carries `class`, `tier`,
`avoid_connections[]` (replacing `avoid_account`) and an optional
`connection` for a per-task override. `message` carries nothing new:
the runner chooses. The tool `record_task` and `start_task` schemas
add `size`, `risk`, `kind`.

**Fixtures** under `internal/wire/wiretest/testdata`:
`api/connections.json`, `api/connection-connecting-codex.json` (with
the device-code prompt), `api/connection-limited.json`,
`api/connect-request-sealed.json`, `api/preferences.json`,
`api/usage-month.json`, `api/usage-ceiling.json`,
`api/event-connection.json`, `api/event-usage.json`,
`api/needs-you-no-connection.json`, `api/step-routed.json`;
`frames/connect.json`, `frames/connection.json`,
`frames/disconnect.json`, `frames/preference.json`,
`frames/routing.json`, `frames/hello-connections.json`,
`frames/reply-usage.json`, `frames/step-usage.json`,
`frames/dispatch-class.json`. A guard test asserts no fixture or frame
type has a field whose name contains `key`, `token`, `secret`,
`credential` or `path` except `seal_key` (public) and `sealed`
(ciphertext), and that `sealed` never appears in a runner-to-instance
frame or an API response.

**Copy for review** (marker as before, Luna's pass later):
"Connections", "Add a connection", "Connecting %s", "Go to %s and
enter %s", "Sign in to Claude", "Claude sign-in finishes on the machine
that runs your runner", "I am at this machine", "Switched to %s; %s
resets %s", "Switched to %s", "Nothing can answer right now. %s",
"Usage", "Limited until %s", "Signed out", "Healthy", "Unknown, no
limit reported", "Estimated from tokens", "Coordinator prefers",
"Engineering prefers", "Review prefers", "Automatic", "Run on …",
"Retry on …", "Engineering on %s, %s for the first pass", "%d tasks
moved to %s while %s was limited". Removed: `chat.failed` "The
coordinator could not answer. Send your message again to retry."

## 8. Slices

Each slice lands headless first (contracts, runner, fake-CLI scenario
green in CI under the two-minute budget), then staging with real CLIs,
then UI, then deploy, as thin v1 §8. Sizes are agent days.

| Slice | Content | Tests | Size |
|---|---|---|---|
| 1a Fake Codex and usage recording | `fakecodex` reproducing the pinned app-server protocol from recordings: `initialize`, `thread/start` and `thread/resume`, `turn/start`, items, `turn/completed` with `status: completed | failed | interrupted`, `account/login/start {chatgptDeviceCode}` and `account/login/completed`, `account/read`, `account/rateLimits/read` and `/updated` with and without windows, several `thread/tokenUsage/updated` per turn; the `usage` table, rows and frames of §6 for Claude and Codex, including failed and cancelled attempts; Codex rate notices kept as state rather than discarded | Unit: usage aggregation over the recorded fixtures (verified pre-turn baseline from the stored previous total, a resume whose first notice already includes new tokens counted in full, no baseline gives `complete: false` and no subtraction, dedup of a resent frame, nullable fields, `complete` false when the final notice is missing); property test that sums over random rows match by every grouping. Headless: U1 a Claude turn and a Codex turn each produce one row with `complete: true`; U2 a cancelled turn produces a row with `outcome: cancelled` | 1 day |
| 1b Protocol and auth | `Connection` rows and homes, `connect`, `connection`, `disconnect` frames, `hello.connections`, `sync.connections`; Codex device code in the app; Claude same-machine loopback and the finish-on-runner card; health, `limited`, `sign_in_again` and the failure classifier of §3; Claude and Codex only, over the existing egress relay, no endpoints and no sealed keys | Headless: A1 device code against `fakecodex`, card shows the code, connection turns `healthy` with plan and windows; A2 device code refused (not enabled), `provider_refused`; A3 Claude same-machine against `fakeclaude` with a simulated loopback callback, `healthy` with the observed email; A4 remote case shows the finish-on-runner card and nothing else; A5 cancel during `connecting` defeats a late success (the runner's late `healthy` report for a cancelled attempt is dropped and the home deleted); A6 `rate_limit_event {rejected}` with and without `resetsAt` marks `limited` correctly; A7 an `auth` failure marks `sign_in_again`, never `limited`; A8 guard: no secret-shaped field in any frame, fixture or report | 1 day |
| 1c Failover and continuity | The choice function over pairs with stickiness; the `waiting` turn state; termination before failover; durable attempt advancement; the per-turn mutation ledger and its per-kind rules (`tool_calls{turn}` answered from the ledger, designated mutations only, reads always fresh, the resumed-attempt summary); the switched line; Engineering retry on another pair after termination; `no_connection` waiting card; pinned ask | Headless: F1 two Claude accounts, the first hits a fake limit mid-turn, reply from the second with the switched line, no duplicate message; F2 quota failure immediately after each designated mutation in turn (`add_project`, `create_project`, `record_task`, `start_task`, `cancel_task`, `add_finding`, `ask_person`, `set_project_home`), the new attempt's summary names the effect, and a call of the same kind **with changed arguments** (a paraphrased question, a reworded brief, a different step list) is folded by the per-kind rule and answered `replayed: true` with no second project, task, finding or card; F2b `status`, `start_task`, quota failure, new attempt calls `status` and gets the started task, not the first status; F3 runner crash between termination and attempt advancement, restart recovers the turn in `waiting` and advances once; F4 ack loss on the `turn{running, attempt: 2}` report, resend is a no-op; F5 cancel during `waiting` ends `cancelled`, cancel after advancement targets attempt 2 and a stale attempt-1 report is dropped; F6 Engineering step fails on quota, termination proof, attempt 2 on Codex, card shows both; F7 nothing eligible, `waiting` with `no_connection`, the card, then a connection returns and the reply arrives without the person resending; F8 the preferred connection returns during a turn, nothing moves until that turn ends and the queue is empty, then the next turn switches back with the line and resumes the old session with a fresh notebook injection; F9 ask on a step whose connection is `limited` fails `account_unavailable` and never moves. Staging witness: one real Codex device-code sign-in in the app, one real Codex refresh (thin v1's debt), one real Claude limit observed or injected by a `rate_limit_event` replay against the real CLI, three coordinator turns across the switch, one of them straight after `start_task` | 1.5 days |
| 1d UI | Connections list and Add in Settings, the connecting card, the switched line, the waiting card, the finish-on-runner card; no Usage page | Browser suite on A1, A4, F1, F7 | 0.5 day |
| 2 Local models and metered endpoints through Pi | Pi containment proofs and probes P1 to P5 (RPC session across 100 fake turns; `extension_ui_request` relay for a blocked tool; MCP pinning; credential-read denial; descendant termination under namespace kill), `fakepi`, Pi profile in `policy.go`; the local transport of §2.5 with its four probes; public endpoints over the relay; sealed keys with the §2.4 lifecycle (`seal_key` derived from the enrolment key, bound payload, `seen_seals`, ack after fsync, cancel marker); OpenRouter PKCE hardened as §2.6; TensorX and Mistral API as endpoints with the model map's prices and their harness-side 429 events; Pi usage into `usage`; tiers from the model map, no classes yet | Headless: P1 to P5 as tests; E1 add a local endpoint through the local listener, model list shown, a Review step runs on it with `other_family` by recorded family; E2 sealed key round trip, the instance database and its WAL contain no plaintext (grep the files), a box with a changed `connection_id`, a changed `endpoint` port or scheme, an expired `expires_at` or a repeated attempt is refused, a replay to another runner fails to open; E2b crash tests at each delivery boundary (after the temp-file fsync, inside the `seen_seals` transaction, after commit before the ack) end with exactly one secret file, one `seen_seals` row and one ack, and the connection `healthy`; E3 a step on a non-local connection cannot reach the local listener; E4 a redirecting endpoint is refused; E5 OpenRouter callback to the instance route, query stripped from the URL and the access log, exchange on the runner against a fake; E6 Pi reports a 429 as an error event, connection `limited` without a reset time, probe clears it. Staging: a real Ollama on docs-t1 or Tito Studio running one Review step and one small Engineering step; one real TensorX test call | 5 days (OpenCode fallback adds 2) |
| 3 Routing and Usage page | `size`, `risk`, `kind` on `record_task` and `start_task`; the class-to-tier table; cheap-first escalation; routing lines on the task card; preferences per role and per task override; the Usage page with availability, spend, token tabs and routing lines; soft ceiling, 80% line and Pause (thin v1 slice 6's item, moved here); the sidebar dot; Mistral Vibe CLI as an Engineering and Review harness (`fakevibe`), subscription connection by the CLI's browser sign-in in the same-machine case and `MISTRAL_API_KEY` sealed otherwise | Headless: R1 a small, low-risk fix lands on the local model, fails checks, escalates to `standard` on another family, passes; R2 a high-risk task goes `strong` straight away; R3 preference set, switched line only on failover; R4 Usage sums equal the `usage` rows for each grouping and period (property test over random rows); R5 ceiling crossed, dot appears, Pause stops new metered steps and never the coordinator; V1 Vibe Engineering step with a fake. Staging: three routed tasks on the mix, page checked against the rows | 4 days |
| 4 Native apps and polish | Fixtures published, sealed box in Swift and Kotlin, `same_machine` detection on the Mac app, Connections and Usage screens | Contract fixtures replayed by the apps' own tests | app teams |
| 5 Command Code | BYOK `--local-only` Engineering and Review rows, `fakecmd`, containment profile with its network switches | One headless Engineering step, one Review step | 1.5 days |

Slice 1 (gates 1a to 1d, four days) is the one that unblocks Paul:
with two Claude accounts or one Claude and one Codex connected, the
coordinator keeps answering through a limit, and both can be added from
the app (Codex entirely; Claude at the machine, or finished on the
runner). Each gate is green in CI before the next starts, and 1c's
staging witness runs before 1d.

## 9. Decisions for Paul

1. **Claude signs in only to the unmodified binary.** On the runner's
   machine by loopback, otherwise "finish signing in on the runner"
   (`equipo-runner login claude` there, the paste going into the CLI).
   No token importer and no device-side bridge, because Anthropic's
   terms forbid Equipo handling the code or token and an owner's
   acceptance cannot waive a provider's terms. Confirm; the
   alternative is a Claude API-key connection for remote machines.
2. **Pi is the single OpenAI-compatible harness**, with OpenCode as the
   fallback if the slice 2 probes fail, Vibe for the Mistral
   subscription with `run-server` probed before it is given a
   coordinator cell, and Command Code last with `cmd acp` probed the
   same way. Confirm, or name a different order.

## 10. Risks

Pi's RPC mode is verified from its docs and source, not yet from a
hundred-turn run in bubblewrap; slice 2 starts with the probes and the
OpenCode fallback costs two days. Headroom is still best effort: Claude
reports one figure, endpoints report nothing, and `limited` for them
rests on observing a 429. A coordinator that switches family loses its
in-context memory and keeps only the notebook, the tail and a
runner-written summary; the switched line makes that visible and the
preference pulls it back. Codex's own sandbox needs user namespaces
Equipo's namespace does not grant, so Codex runs unsandboxed inside
the container, as the design already assumed. Spend is an estimate
from tokens and a price table that someone must keep current, labelled
as such. TensorX's and Mistral's quieter corners (streamed tool-call
chunks, prompt caching, whether a plan key may be used from Pi) are
marked unverified above and are probed, not assumed. Exactly-once effects rest on
the mutation ledger's per-kind rules on the instance, not on the
model's wording or cooperation; the designated list must stay complete
as tools are added, and a guard test fails when a tool that writes is
not in it.
Sealed-box residue in WAL and backups is accepted and labelled, not
erased. The word count is above the brief because four sections were
added on the way; nothing in them is optional for the design to hold
together.
