oficina / equipo Public

specs: Equipo Connections, accounts added in-app, any provider per role

Design spec for connections: Claude (Claude Code), Codex (app-server),
local and metered OpenAI-compatible providers through Pi (TensorX,
Mistral API, OpenRouter, Ollama), Mistral Vibe for the subscription,
Command Code last; Gemini and Muse parked. Covers in-app flows (device
code, the Claude binary's own loopback OAuth, sealed API keys,
endpoints), a no-paste OAuth table with Anthropic's terms, headroom and
limit signals per provider, selection and failover, hybrid routing with
cheap-first escalation, a Usage page with recording from slice 1, API
v1 and wire changes with fixtures, five slices, two decisions for Paul.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
claude 28f84559fe3d8ff26c116aa4125e09689f783323 parent 2d1edaf
1 file changed, +964 −0
  • docs/superpowers/specs/2026-11-08-equipo-connections.md +964 −0

CI failed — run details

diff --git a/docs/superpowers/specs/2026-11-08-equipo-connections.md b/docs/superpowers/specs/2026-11-08-equipo-connections.md
new file mode 100644
index 00000000..d18e5ef3
--- /dev/null
+++ b/docs/superpowers/specs/2026-11-08-equipo-connections.md
@@ -0,0 +1,964 @@
+# Equipo Connections: accounts added from the app, any provider for any role
+
+Status: design for Paul's review, 2026-11-08. 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`.
+`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 and names the window only when
+the reset time makes it obvious. 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`. 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; OpenRouter, TensorX 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. Verdict: not a
+coordinator (no live relay, no long-lived mode); possible for
+Engineering and Review behind BYOK, proprietary, and nothing it does
+is unavailable in Pi. It stays in the plan as Paul asked, last, and
+is marked "Engineering and Review only" in the matrix.
+
+**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 is also a candidate for the single OpenAI-compatible harness
+(§5): it has the headless mode, streaming JSON, MCP, resume, hooks and
+custom providers that §1.4 asks of Pi and OpenCode, with the drawback
+of being Mistral's product driving other people's models. The matrix
+in §5 scores it beside them.
+### 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` grows into this record (§7); `accounts` as a word
+stays in the wire for compatibility and in copy as "accounts" where it
+reads better than "connections".
+
+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. **Last resort, `setup-token`.** A person who runs
+ `claude setup-token` on any machine gets a one-year token. Equipo
+ does not accept it in the app (holding it on the instance even in
+ transit is storing a session token). The runner's terminal command
+ `equipo-runner login claude --token` can read it from the terminal
+ into the account's home as `CLAUDE_CODE_OAUTH_TOKEN` for that home's
+ launches; it is marked `kind: subscription, method: token`, shown
+ with its expiry, and excluded from `--bare` launches. Documented,
+ not promoted.
+
+**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 that this one needs a terminal there. 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. The runner already holds an ed25519 identity key from
+enrolment (`internal/runner/enrol.go`); `hello` adds a `seal_key`, an
+X25519 public key derived for this purpose, and the instance republishes
+it on the `Runner` resource. The app seals the key with libsodium's
+`crypto_box_seal` (NaCl sealed boxes: ephemeral sender key, X25519,
+XSalsa20-Poly1305; one call in Swift, Kotlin, Go and the browser's
+libsodium build) and POSTs `{provider, kind: api_key, sealed}`. The
+instance copies the opaque bytes into the `connect` frame, keeps them
+only in the durable mailbox until the runner acks, then deletes the
+payload column and keeps the frame id. The runner opens the box, writes
+the key into the home (`ANTHROPIC_API_KEY` in a 0600 env file for
+Claude; `codex login --with-api-key` on stdin for Codex; the harness's
+own auth file for an endpoint), zeroes the buffer, makes one test call
+(`/v1/models` or the harness's cheapest request), and reports `healthy`
+or `provider_refused`. A sealed payload is capped at 4 KB and never
+logged; the mailbox table's payload column is excluded from every
+diagnostic dump, as credential bytes already are. The instance can read
+nothing, a database export carries nothing, and a replayed frame to a
+different runner cannot be opened. Rotation is "sign out, add again".
+
+### 2.5 Endpoints, with a test call
+
+An endpoint connection is `{base_url, label, sealed key or none,
+harness}`. The runner resolves the host, refuses loopback and LAN
+addresses unless the connection is marked `local` (a local Ollama is the
+point, so `local` is allowed and the egress relay for that connection
+admits exactly that host and port), fetches `/v1/models`, makes a
+one-token completion with the first model, records the model list and
+the latency, and reports `healthy` with `models[]`. The card shows the
+models and lets the person pick a default; the router (§4) may use any
+of them. 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 | CLI's own loopback OAuth, app shows the link | No | Runner, by the CLI | Runner home (`.credentials.json`, or Keychain on a Mac) |
+| Claude (subscription), runner remote | Terminal at the runner: `equipo-runner login claude` | Yes, into the CLI, never into Equipo | Runner, by the CLI | Runner home |
+| Claude (`setup-token`) | Terminal at the runner, `--token` | Yes, into the terminal | n/a | Runner home, one year |
+| 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 them the
+redirect lands on the app and the exchange still happens on the runner,
+with the verifier sealed so the instance sees an opaque box. OpenRouter
+publishes "localhost callbacks are supported on any port"; whether a
+custom scheme is accepted is unconfirmed, so the native apps use an
+https app link to the Equipo web origin until that is checked. 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 paste 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, a `/v1/models` call for an endpoint) checked on
+start, hourly, and before any turn that needs a fresh copy, as today.
+`sign_in_again` is set when refresh fails or reports a different
+identity (thin v1 §2). **Limited** is new: a connection whose provider
+said no to the last request on quota, with `resets_at` when the provider
+gave one. Sources: Claude `rate_limit_event {status: rejected,
+resetsAt}` and `api_retry {error: rate_limit}`; Codex
+`account/rateLimits/updated` with a window at `usedPercent` 100 or
+`rateLimitReachedType` set, and `turn/failed` on quota; endpoints and
+OpenRouter an HTTP 429, with `Retry-After` or the provider's reset
+header when present and otherwise a fifteen-minute cool-off that doubles
+to an hour. Headroom is whatever the provider reports and nothing else:
+Claude's single `utilization` and `resetsAt`, Codex's two windows, an
+endpoint's nothing (shown as "unknown"). A connection leaves `limited`
+when `resets_at` passes or a probe succeeds; the runner probes with the
+cheapest request the harness has, 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 from the
+person's own connections on the runner that holds the session or task,
+in this order: capable of the role (the matrix in §5); not `limited`,
+`sign_in_again`, `error` or `signed_out`; the role's preference if the
+person set one (§3, last paragraph); then the router's class (§4); then
+the most headroom, where a subscription's headroom is the provider's
+reported figure, a metered connection's is "unlimited at a price", and a
+local endpoint's is "unlimited and free" but slow and small. Ties go to
+the connection that ran this session or task last, so sessions do not
+hop for nothing. The function stays small and pure: inputs are the
+connection list, the role, the class, the preference and the current
+binding; the output is one connection id and a reason code. It is unit-tested with a table and it is the only place that chooses: it
+replaces `pickReviewer` in `internal/runner/thin/judge.go` and the
+coordinator's binding choice, and it returns a `runner.AccountBinding`
+as they do.
+
+**Coordinator failover mid-conversation.** A turn fails on quota
+(§2.7's signals) or on a provider error the retry policy gives up on.
+The runner marks the connection `limited` with `resets_at`, picks again,
+and if a connection remains it starts a **new session** there (thin v1
+§2: a fresh process, the notebook, the house rule, the 50-message tail
+and a short summary of the current turn written by the runner from the
+tail, not by a model), replays the turn's frame, and the person sees the
+reply arrive with one quiet line under it: "Switched to Codex; Claude's
+weekly limit resets Mon 10:00" (`chat.switched`, with `resets_at`
+rendered in the person's zone, or "Switched to Codex" when there is no
+reset time). The old `sessions` row stays for resume when its
+connection is healthy again; whether the coordinator moves back is the
+same choice function at the next turn start, so a preferred connection
+returns on its own once it has headroom, with a line only when the
+switch happens. The draft deltas of the failed attempt are discarded as
+on cancel; the turn's `attempt` increments; the SSE client sees
+`turn{state: running, attempt: 2}` then deltas, never a failure.
+
+**Engineering mid-step.** A step whose harness dies on quota is a
+failed attempt, as any crash is today: the runner waits for the
+termination proof (pidfd exit of the namespace, thin v1 §4), commits
+nothing (the worktree is discarded; an attempt's partial work is not a
+candidate), picks another connection avoiding the one that failed
+(`avoid_account` already exists on review dispatch and becomes a list
+on every dispatch), and starts attempt n+1 on it with the same brief.
+The step row records both attempts and their connections; the task
+card shows "Engineering on Codex (Claude was limited)". If no
+connection can run Engineering the step waits in `queued` with reason
+`no_connection` and the task shows what to add; it resumes without a
+retry when a connection becomes healthy.
+
+**Review across families.** Thin v1 §3's rule stands and gets its
+third option: Review runs on another family if a healthy, capable
+connection exists (`other_family`), else another connection of the same
+family with fresh context (`same_family`), else a fresh session on
+Engineering's connection (`same_account`). The label is recorded on the
+step and shown, as today. With Codex and an endpoint in the mix,
+`other_family` becomes the common case.
+
+**Ask the implementer** stays bound to the step's own session and
+connection (slice 4b); if that connection is `limited` the question
+fails `account_unavailable` with the reset time in the card, because a
+different model reading the transcript is not the implementer.
+
+**"No connection can answer."** When the choice function returns
+nothing for the coordinator, the turn ends `failed` with the new reason
+`no_connection` and the chat shows a card instead of `chat.failed`:
+"Nothing can answer right now. Claude resets Mon 10:00; Codex is signed
+out." with one action, **Add a connection**, and the message stays
+queued to be sent when a connection returns (the person can delete it).
+The old line "Send your message again to retry" is removed; retrying
+was never the person's job. `wire.Reasons` gains `no_connection`;
+`Task.NeedsYou` gains `no_connection`.
+
+**The preference.** Settings gains one quiet row per role, "Coordinator
+prefers", "Engineering prefers", "Review prefers", each a picker over
+the person's connections plus "Automatic" (the default). A preference is
+the first tie-breaker after capability and health, never a requirement:
+a preferred connection that is limited is skipped with the switched
+line, and a preference for a connection the role cannot use (the matrix)
+is refused in the picker. `PUT /api/v1/preferences {role, connection_id
+| null, revision}`. Per task, the task page offers "Run on …" before the
+first step starts and "Retry on …" at a failed step.
+
+## 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.
+
+**The policy.** A table, shipped as defaults and never edited by the
+person in v1: a class maps to a **tier** (`cheap`, `standard`,
+`strong`) per role. Engineering: `small` and `low` risk start `cheap`;
+`medium` or `normal` start `standard`; `large` or `high` start
+`strong`. Review: one tier above Engineering's, minimum `standard`,
+and another family where possible. Coordinator: always `standard` or
+above (it holds the person's context; a cheap coordinator is a false
+economy). Ask: the step's own connection. Each connection carries a
+tier from a static map the runner ships (Claude and Codex
+subscriptions `strong`; TensorX kimi-k3.1-pro and Mistral Large 4
+`standard`; glm-5.3-flash, deepseek-v4-flash, Small 4 and any local
+model `cheap`, with a local model's tier capped by its parameter count
+when the endpoint reports it) and a **cost signal**: `subscription`
+(headroom is the cost: free until limited), `metered` (a price per
+million tokens from the connection's price table, so dollars), or
+`free` (local). The choice function of §3 takes the tier as a filter
+(a `cheap` job may run on anything at or above `cheap`, preferring the
+cheapest cost signal with headroom; a `strong` job runs only on
+`strong`) and then applies preference, headroom and stickiness as
+before. 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 `cheap` or `standard` first pass that
+fails checks or gets `changes_requested` is retried one tier up on the
+first fix round, on a different family if one is available; 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`; there is nowhere to go, and the
+fix-round cap already ends it at Needs you.
+
+**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,
+connection, reason (`preference`, `headroom`, `cheapest`,
+`escalated`, `failover`, `only_option`, `same_family_review`), so the
+line and the sum are read from data, not reconstructed. 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. 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; `cheap` tier, so chosen only by preference | Yes, `cheap` tier | Yes, read-only tool allowlist, `same_family` never (it is its own 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 | **No** in v1: `-p --output streaming` has no stdin-held long-lived mode documented, and headless 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` | **No**: no long-lived mode, 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 already receives per-turn and
+per-step usage from each harness: Claude's `result.usage` and
+`result.modelUsage` (with `costUSD` as a cross-check, never shown),
+Codex's `thread/tokenUsage/updated` (the `last` breakdown per turn,
+`total` as the check), and the endpoint harness's equivalent (OpenAI
+`usage` on the final chunk with `stream_options.include_usage`, or the
+harness's own usage event, §1.4). It writes one `usage` row per turn or
+step attempt: person, connection, harness, model, role, project, task,
+step, turn, input, cached input, cache write, output, reasoning output,
+estimated cost in micro-dollars (null for subscriptions and free
+endpoints), recorded at, and sends it in the existing `reply` and
+`step` frames as a `usage` object, which already exists on `reply` as
+`wire.Usage` ("without cost data", today) and gains the same fields. The instance stores it as a
+`usage` table and serves sums; raw rows are kept 90 days, daily sums
+indefinitely. 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 |
+|---|---|---|---|
+| 1 Several accounts, Codex coordinator, in-app Codex and second Claude | `Connection` rows and homes, `connect` and `connection` frames, the Codex device-code flow, the Claude same-machine flow and the honest remote card, `hello.connections` and `seal_key`; the choice function over several connections with health and headroom; coordinator failover with the switched line and the new session seeded from the notebook; Engineering retry on another connection after termination; `no_connection` card; `fakecodex` with device-code login, `account/rateLimits`, `thread/tokenUsage/updated` and `turn/failed` on quota; **usage recording** from Claude `result` and Codex `tokenUsage` into the `usage` table and frames, no page; `routing` rows with reason `headroom`, `failover`, `only_option` only (no classes yet) | Headless: C1 two Claude accounts, first hits a fake weekly limit mid-turn, reply arrives from the second with the switched line, no duplicate; C2 Codex coordinator end to end (hello, tools, a task); C3 in-app Codex device code against `fakecodex`, card shows code, turns healthy; C4 add a second Claude in the same-machine case against `fakeclaude` (loopback callback simulated), and the remote case shows the terminal card; C5 Engineering step fails on quota, termination proof, retried on Codex, card shows both; C6 nothing available, `no_connection` card, message queued, connection returns, reply arrives; C7 guard: no secret-shaped field anywhere, `sealed` never in a report. 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, three coordinator turns across the switch | 4 days |
+| 2 Local models and metered endpoints through Pi | Pi probes P1 to P4 (RPC session across 100 fake turns; `extension_ui_request` relay for a blocked tool; MCP pinning; `abort` termination), `fakepi`, Pi containment profile in `policy.go`, endpoint connections with the test call and `local` hosts, sealed API keys (`seal_key`, sealed box in the web app and the Go client), OpenRouter PKCE on the web app, TensorX and Mistral API as endpoints with their price tables and 429 parsing, Pi usage into `usage`, tiers from the static map (no classes yet: an endpoint is chosen by preference or when nothing else is healthy) | Headless: P1 to P4 as tests; E1 add an Ollama endpoint, model list shown, a Review step runs on it with `other_family`; E2 sealed key round trip, instance database contains no plaintext (grep the SQLite file), replay to another runner fails to open; E3 TensorX 429 with `retry-after` marks `limited` with the right time; E4 OpenRouter PKCE callback to the web app, exchange on the runner against a fake. Staging: a real Ollama on docs-t1 or Tito Studio running one Review step and one small Engineering step; one real TensorX test call | 4 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 is the one that unblocks Paul: with two Claude accounts or one
+Claude and one Codex connected, the coordinator keeps answering through
+a weekly limit, and both can be added from the app (Codex entirely;
+Claude at the machine or by the terminal card).
+
+## 9. Decisions for Paul
+
+1. **Claude on a remote runner stays a terminal step.** Anthropic's
+ terms forbid Equipo intermediating the code or token, so when the
+ browser is not on the runner's machine the app shows the honest
+ card and the paste happens in `equipo-runner login claude` there,
+ never in Equipo. The alternative, a device-side bridge in the native
+ apps, is technically possible and is not built. Confirm, or say the
+ risk is acceptable and the bridge goes on the list.
+2. **Pi is the single OpenAI-compatible harness**, with OpenCode as the
+ fallback if the slice 2 probes fail, Vibe for the Mistral
+ subscription only, and Command Code last and never a coordinator.
+ 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. The word count is
+above the brief because three sections were added on the way; nothing
+in them is optional for the design to hold together.