oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1# Equipo Connections: accounts added from the app, any provider for any role
2
3Status: design for Paul's review, 2026-11-08, revision 3 after Astra's
4rounds 1 and 2 (NOT READY at 28f8455 and eaf2f38). Drafted by Claude (Fable 5.1)
5on `design-connections` from `thin-v1-slice4c` (2d1edaf). Builds on the
6approved thin v1 spec (`2026-11-06-equipo-thin-v1.md`, §§2, 3, 5, 6, 8) and
7the accepted Mac runners spec (`2026-11-07-equipo-mac-runners.md`). Not
8implemented. Every provider claim below was checked against the official
9documentation or source on 2026-11-08; where a claim could not be confirmed
10it says so.
11
12## 0. Why, and the shape of the answer
13
14Paul's staging coordinator stopped answering on 2026-11-08 because the one
15Claude account it runs on hit its weekly limit, and the chat said "The
16coordinator could not answer. Send your message again to retry." Retrying
17could not help: there was nothing else to run on. Paul's ask is that
18accounts be added from the app, that the coordinator and the specialists
19run on whichever connected provider has room, and that he can quietly
20prefer one. This spec supersedes the terminal-only part of §6 of thin v1
21(`equipo-runner login claude|codex`); the command stays as a fallback.
22
23The shape, in one paragraph. A **connection** is one signed-in account or
24one API key or one endpoint, on one runner, owned by one person, living in
25its own home under `~/.local/share/equipo/accounts/<provider>-<n>` exactly
26as accounts do today. Credentials never leave the runner; the instance
27holds a record (provider, label, health, headroom, limit reset time, usage)
28and never a secret. A **harness** is the program that drives a model with
29tools: Claude Code, the Codex app-server, and one OpenAI-compatible harness
30for everything else. A **role** is what a run is for: coordinator,
31Engineering, Review, ask. Selection is still the 30-line function thin v1
32promised, now over several connections with a preference and a router's
33class on top (§§3, 4). Failover is automatic and quiet. Usage is recorded
34from day one and shown on one page (§6).
35
36Four rulings of Paul's frame everything: magic, not setup; a preference,
37not a requirement; the notebook is the memory, so a provider change is a
38new session seeded from the notebook and a short summary while a thread
39stays with the account that started it (thin v1 §3); and credentials stay
40on the runner. Containment is unchanged: bubblewrap on Linux for every
41harness (thin v1 §5), the harness's own sandbox trusted on the owner's Mac
42(Mac runners §4). Each person connects their own accounts; a teammate's
43connection is never selectable for another person's work.
44
45## 1. Providers and harnesses, and what each needs
46
47### 1.1 Claude, through Claude Code
48
49**Sign-in.** The CLI's OAuth is the only subscription path: `claude`
50opens `https://claude.ai/oauth/authorize` with PKCE and a
51`redirect_uri` of `http://localhost:<port>/callback`; when the browser
52cannot reach that loopback it shows a code on
53`https://platform.claude.com/oauth/code/callback` for the person to paste
54at the CLI's "Paste code here if prompted" prompt (docs: authentication;
55issue #29983 for the two redirect URIs). There is no device-code flow.
56`claude setup-token` runs the same browser flow and prints a one-year
57OAuth token, saved nowhere, for `CLAUDE_CODE_OAUTH_TOKEN`; it can only
58make model requests and is ignored in `--bare` mode. `claude auth status`
59returns JSON with `authMethod` and exits 1 when signed out. API keys:
60`ANTHROPIC_API_KEY` (always used in `-p` mode when set), or
61`ANTHROPIC_AUTH_TOKEN` as a bearer, or an `apiKeyHelper` in settings;
62`ANTHROPIC_BASE_URL` points the CLI at any endpoint that speaks the
63Anthropic Messages API. Anthropic does not support non-Claude models
64through a gateway, and the CLI has no chat-completions mode.
65
66**Policy, which binds the design.** Anthropic's Claude Code legal page
67says third parties may not "offer Claude.ai login into their own
68applications", may not "route requests through Free, Pro, Max, or Ultra
69plan credentials on behalf of their users", and "may not collect, store,
70or intermediate Claude.ai credentials or session tokens"; sign-in "must
71complete through Anthropic's own flow". The same page allows "an end user
72… signing in to the unmodified Claude Code binary with their own Claude
73subscription, including where a platform hosts Claude Code", provided the
74binary is unmodified and each end user authenticates with their own plan.
75Equipo runs the unmodified binary, one person per account, so the
76permitted shape is: the `claude` binary performs the sign-in in the
77account's home on the runner, and Equipo never sees the code or the
78token. That rules out relaying a pasted code through the instance (§2.3)
79and rules out a `setup-token` value typed into the app. It also means a
80person's Claude connection does Equipo work only for that person, which
81the multiplayer rule already requires.
82
83**Headless and tools.** Everything the coordinator uses today exists:
84`-p --input-format stream-json --output-format stream-json
85--include-partial-messages --verbose`, `--resume <id>`, `--mcp-config`
86with `--strict-mcp-config`, `--permission-prompt-tool mcp__…`,
87`--allowedTools`, `--permission-mode`, `--max-turns`, `--max-budget-usd`,
88and `--bare` (recommended for scripts; skips OAuth and the keychain, so
89it is for API-key connections only).
90
91**Limits.** In stream-json the CLI emits `rate_limit_event` with
92`rate_limit_info {status: allowed | allowed_warning | rejected,
93resetsAt, utilization}` (the Agent SDK's `SDKRateLimitEvent`), derived
94from the `anthropic-ratelimit-unified-*` response headers; retries show
95as `system/api_retry` with `error: "rate_limit"` and `retry_delay_ms`.
96Both `resetsAt` and `utilization` are optional, and `utilization` is a
97single number; per-window (five-hour versus weekly) figures are
98requested in issues #50518 and #91857 but not documented, so Equipo
99shows the one figure the CLI gives, never names a window, and copes with
100either field missing. Each `result` message carries `usage`
101(`input_tokens`, `output_tokens`, `cache_creation_input_tokens`,
102`cache_read_input_tokens`), `modelUsage` per model (`inputTokens`,
103`outputTokens`, `cacheReadInputTokens`, `cacheCreationInputTokens`,
104`costUSD`, `contextWindow`) and `total_cost_usd`, all client-side
105estimates. Credentials live in `~/.claude/.credentials.json` (0600) on
106Linux and in the Keychain on macOS, falling back to the file when the
107Keychain is locked; the CLI refreshes OAuth itself and warns three days
108before a login expires.
109
110### 1.2 ChatGPT or Codex, through the Codex app-server
111
112**Sign-in.** `codex login --device-auth` (beta) prints a URL
113(`<issuer>/codex/device`) and a user code that expires in fifteen
114minutes, then polls `/api/accounts/deviceauth/token`; nothing is typed
115back into the CLI (`codex-rs/login/src/device_code_auth.rs`). The person
116must first enable device code login in ChatGPT security settings
117(personal) or workspace permissions (team). The browser flow binds
118`127.0.0.1:1455` (fallback 1457) and redirects to `/auth/callback`, no
119paste fallback. API keys: `codex login --with-api-key` reading stdin.
120Storage: `auth.json` under `CODEX_HOME`, or the OS keyring when
121`cli_auth_credentials_store` says so; Codex refreshes tokens itself.
122The app-server exposes all of this as JSON-RPC: `account/login/start`
123with `type: chatgptDeviceCode` returns `loginId`, `verificationUrl` and
124`userCode`; `account/login/completed` fires with `success`;
125`account/read` (`refreshToken: true` forces a refresh); `account/logout`;
126`account/updated` carries `authMode` and `planType`.
127
128**Policy.** OpenAI's docs say to "use API key authentication for
129programmatic Codex CLI workflows, such as CI/CD jobs" and document a
130ChatGPT-managed path with "use this path only if you specifically need to
131run as your Codex account". Driving `codex app-server` with a ChatGPT
132sign-in is documented, not forbidden, and the person's own account does
133only the person's work, which is the same shape as Claude. The separate
134"Sign in with ChatGPT" programme for third-party apps requires loopback
135`127.0.0.1` callbacks and partner approval for hosted apps, so it is not
136a route for Equipo.
137
138**Headless and tools.** The path thin v1 §3 already designed:
139`initialize`, `thread/start` or `thread/resume`, `turn/start`,
140`item/agentMessage/delta`, the four approval requests answered deny or
141relayed as `ask_person`, `turn/interrupt`; a turn ends on
142`turn/completed` whose `status` is `completed`, `failed` or
143`interrupted` (there is no separate `turn/failed`; the decoder in
144`provider/codex/events.go` already switches on these). Codex remains an
145MCP client
146(`codex mcp`; `codex mcp-server` was removed in favour of the app-server,
147which is not an MCP server). Custom providers in `config.toml` take
148`base_url`, `env_key`, `http_headers` and `wire_api`, and **`responses`
149is the only supported value**: the chat wire API was deprecated in
150December 2025 and became an error in February 2026. The Linux sandbox is
151now bubblewrap plus seccomp ("the first `bwrap` on `PATH`", else a
152bundled helper needing unprivileged user namespaces); nesting it inside
153Equipo's bubblewrap is undocumented, so Equipo keeps `sandbox_mode =
154danger-full-access` inside its own namespace, as the Codex step path
155already assumes, and the outer namespace is the containment.
156
157**Limits and usage.** `account/rateLimits/read` and the notification
158`account/rateLimits/updated` carry `rateLimits` with `primary` and
159`secondary` windows, each `{usedPercent, windowDurationMins, resetsAt}`
160(Unix seconds), plus `planType`, `limitId`, `limitName` and
161`rateLimitReachedType`. Token use arrives as `thread/tokenUsage/updated
162{threadId, turnId, tokenUsage {total, last, modelContextWindow}}`, each
163breakdown `{inputTokens, cachedInputTokens, outputTokens,
164reasoningOutputTokens, totalTokens, cacheWriteInputTokens}`
165(`ThreadTokenUsageUpdatedNotification.json` in the codex repo).
166`account/usage/read` adds lifetime and daily token buckets. The Codex
167provider in `internal/runner/provider/codex` already decodes
168`account/rateLimits/updated` and `thread/tokenUsage/updated` (its
169`rate_notice` and `resume_usage` tests), so slice 1 extends, rather than
170adds, that parsing. Codex is the
171one provider that reports both windows with a reset time, so its row in
172Usage is the fullest.
173
174### 1.3 Everything OpenAI-compatible, through one harness
175
176Local models (Ollama, vLLM, LM Studio on Tito Studio or a person's own
177machine), TensorX, the Mistral API, OpenRouter and, when it ships, the
178CARLOS inference gateway (spec rev 6, chat completions and `/v1/models`
179only, not yet built) all present an OpenAI-compatible HTTP endpoint with
180an API key or none. Paul asked for one harness across them if one works
181for every role, rather than one per provider. Two existing harnesses can
182already do some of it, which sets the bar:
183
184- **Codex as the harness** works wherever the endpoint serves the
185 Responses API: Ollama (`/v1/responses`, non-stateful only), vLLM
186 (`/v1/responses`), OpenRouter (`/responses`, stateless). It fails for
187 chat-completions-only endpoints (the CARLOS gateway as specified, and
188 any provider without Responses).
189- **Claude Code as the harness** works only against the Anthropic
190 Messages API. Ollama and vLLM now serve `/v1/messages` natively
191 (`ANTHROPIC_BASE_URL=http://localhost:11434`,
192 `ANTHROPIC_AUTH_TOKEN=ollama`), so local models can run under the
193 Claude harness with no proxy, and TensorX documents the same route
194 (§1.5); OpenRouter and Mistral cannot without a translating proxy,
195 and Anthropic says it does not support routing Claude Code to
196 non-Claude models.
197
198Neither covers every endpoint, which is why §1.4 verifies Pi and
199OpenCode as the dedicated OpenAI-compatible harness. The verdict and the
200capability matrix are in §5. Whichever wins, the connection shape is the
201same: `kind: endpoint`, a base URL, an optional key sealed to the runner
202(§2.4), a model list fetched from `/v1/models` on connect, and a
203one-token test call before the connection is marked healthy.
204
205### 1.4 The OpenAI-compatible harness: Pi, with OpenCode in reserve
206
207Three candidates were verified against their current docs and source
208on 2026-11-08.
209
210**Pi** (`earendil-works/pi`, MIT, npm `@earendil-works/pi-coding-agent`
2111.5.0, Node 22.19 or later; the `@mariozechner` package is deprecated
212in its favour). Headless is `pi -p` with `--mode json` (JSONL events
213`agent_start`, `turn_start`, `message_start`, `message_update`,
214`message_end`, `tool_execution_start`, `tool_execution_end`,
215`agent_end`, `auto_retry_start`, …) or `--mode rpc`, which reads JSONL
216commands on stdin (`prompt`, `steer`, `follow_up`, `abort`,
217`get_state`, `set_model`, `compact`, `switch_session`, `fork`) with
218id-correlated responses: a long-lived process with stdin held open,
219which is what the coordinator needs. Sessions are JSONL files under
220`~/.pi/agent/sessions/`, movable with `--session-dir`, resumed with
221`--session <id>` or `--continue`, forked with `--fork`. MCP is built in
222(the project's earlier no-MCP stance was reversed): `mcpServers` in
223`~/.pi/agent/mcp.json` or `.pi/mcp.json` over stdio or HTTP, tools
224named `mcp__<server>__<tool>`, pinned with `--tools 'mcp__x__*'` and
225`--exclude-tools`, and a per-tool `toolExposure` map. Pi has no
226permission modes; gating is a TypeScript extension (`-e file.ts`) whose
227`tool_call` hook returns `{block, reason}` or calls `ctx.ui.confirm()`,
228which in RPC mode surfaces as `extension_ui_request {confirm | select |
229input, timeout}` answered by the host with `extension_ui_response`: a
230real relay channel, equivalent to Claude's `--permission-prompt-tool`
231and Codex's `requestApproval`. Read-only is `--tools read,grep,find,ls`
232(an allowlist replaces the defaults). Providers: forty built in by API
233key (Anthropic, OpenAI, Mistral, OpenRouter, Groq, …), ChatGPT
234subscription sign-in named, Claude subscription not named (a community
235extension reuses Claude Code credentials and itself warns Anthropic
236forbids it; Equipo will not use it); custom endpoints in
237`~/.pi/agent/models.json` with `baseUrl`, `apiKey` and `api:
238"openai-completions" | "openai-responses"`, so both wire shapes work.
239Credentials in `~/.pi/agent/auth.json`. No sandbox of its own
240(Docker recommended, which is Equipo's namespace). Startup network is
241a version check, a model catalogue refresh and telemetry headers, all
242off with `--offline` (`PI_OFFLINE=1`) plus `PI_SKIP_VERSION_CHECK` and
243`PI_TELEMETRY=0`; project trust is `--approve` or `--no-approve`.
244Usage arrives on `message_update` and `message_end` as `usage {input,
245output, cacheRead, cacheWrite, totalTokens, cost}`. No provider
246rate-limit headers are surfaced, so limit detection for Pi
247connections is the runner's HTTP-level observation (§2.7).
248
249**OpenCode** (`anomalyco/opencode`, MIT; two live majors with
250different config keys and SDK packages: v1 `opencode-ai` 1.19.5 with
251`provider`, `agent`, `permission`, `plugin`, and v2 `@opencode/cli`
2522.2.6 with `providers`, `agents`, `permissions`, `plugins`).
253`opencode run --format json` is coarse (`tool_use`, `step_start`,
254`step_finish`, `text`, `error`) and auto-rejects asks unless `--auto`;
255the real driving surface is `opencode serve` on `127.0.0.1` plus the
256SDK, with `GET /event` SSE and `POST /session/:id/permissions/:id`
257to answer `permission.asked`, or a plugin's `permission.ask` (v1) or
258`permission.hook("evaluate")` (v2). MCP with per-agent tool pinning;
259a read-only agent needs explicit `edit` and `shell` denies because the
260built-in `plan` agent leaves shell open. Sessions in a SQLite file
261(`~/.local/share/opencode/opencode.db`). Anthropic by API key only
262(the docs quote Anthropic's prohibition on subscription plugins);
263ChatGPT subscription login offered; custom OpenAI-compatible providers
264documented, Ollama, LM Studio, llama.cpp and vLLM included; TensorX
265has an official recipe. No sandbox. Startup network: update check,
266models.dev catalogue refresh, on-demand provider package downloads
267into `~/.cache/opencode`, and in v2 a shared background service to
268disable (`--standalone`). Verdict: workable, with more moving parts
269than Pi (an HTTP server inside the namespace, package downloads to
270pre-cache, two majors to track).
271
272**Command Code** (`commandcode.ai`, npm `command-code` 1.88.5,
273`UNLICENSED`, Node 22; made by Command Code, not Cohere, the name is a
274coincidence). `cmd -p --output-format json` emits NDJSON with only
275`tool_running` documented plus a final `result {usage, stopReason}`;
276no serve or RPC mode; `--continue`, `--resume`, sessions under
277`~/.commandcode/projects/`; MCP client; permission modes `plan`
278(read-only) and `dont-ask`, a `PreToolUse` hook that can allow or deny
279but cannot ask a person; default provider is its own metered backend
280(browser OAuth or `COMMAND_CODE_API_KEY`), with ChatGPT and Copilot
281subscription logins and a BYOK file for Ollama, vLLM and OpenRouter
282behind `--local-only`; no sandbox; auto-update, telemetry, a remote
283model catalogue and credit checks to switch off. It also documents `cmd acp` (ACP over stdio), which
284is a long-lived, prompt-and-permission protocol; whether its permission
285requests reach the host and whether MCP tools are callable under it is
286unprobed. Verdict: proprietary and backend-tied, nothing it does is
287unavailable in Pi, so it comes last; its coordinator cell is "probe
288`cmd acp` before deciding", not "no".
289
290**Decision.** Pi is the one OpenAI-compatible harness for local
291models, TensorX (chat wire), the Mistral API, OpenRouter and the CARLOS
292gateway when it exists. OpenCode is the named fallback if Pi's RPC
293mode fails the probes in §8. Mistral's Vibe runs only Mistral's
294subscription; Command Code comes last. Claude Code against TensorX's
295`/v1/messages` is a documented, tempting shortcut and is not used:
296the point of one harness is one permission relay, one usage parser,
297one containment profile and one fake CLI to test.
298### 1.5 TensorX: a metered open-weight provider
299
300TensorX Ltd (Dublin; `api.tensorx.ai`, docs at `docs.tensorx.ai`) hosts
301open-weight models in the EU with zero retention, prepaid credits and
302pay as you go. Verified from its docs: OpenAI-compatible
303`POST /v1/chat/completions` with streaming and OpenAI-style tool
304calling, `GET /v1/models` and `GET /v1/model/info` (capability flags such
305as `supports_function_calling`, `max_input_tokens`); an
306Anthropic-compatible `/v1/messages` with a documented Claude Code recipe
307(`ANTHROPIC_BASE_URL=https://api.tensorx.ai`, `ANTHROPIC_API_KEY`, and
308every `ANTHROPIC_*_MODEL` variable set to a TensorX model id, otherwise
309the CLI asks for Anthropic ids that 404); **no Responses API**, so Codex
310cannot be its harness; an official OpenCode provider recipe (`tensorx`,
311`@ai-sdk/openai-compatible`, `{env:TENSORX_API_KEY}`); a community Pi
312package only. Auth is `Authorization: Bearer`, keys shown once, env
313`TENSORX_API_KEY`. Limits are per key (60 requests and 2M tokens a
314minute by default, raised by spend tier); a 429 carries `retry-after`
315and `x-ratelimit-reset` with `error.reason` of `rate_limit_requests`,
316`rate_limit_tokens` or `rate_limit_concurrent`, and successes carry
317`x-ratelimit-remaining-*` headers, so TensorX is the one metered
318provider that gives Equipo live headroom. Prices (per million, in and
319out): glm-5.3-flash $0.20 and $0.50, deepseek-v4-flash $0.25 and $0.30,
320glm-5.3 $1.75 and $4.50, kimi-k3.1-pro $3.00 and $15.00. Usage is a
321dashboard, no API, so Equipo's spend figure is computed from recorded
322tokens and a price table the connection carries (§6). Unverified and
323for the builder to probe: streamed tool-call chunk shape under the
324chat API, and whether `/v1/messages` honours prompt caching and the
325`tool_choice` Claude Code sends.
326
327### 1.6 Mistral: a subscription that covers a real CLI
328
329Mistral's coding product is now **Vibe** (Le Chat renamed), and the
330CLI is open source (`mistralai/mistral-vibe`, Apache 2.0, Python with
331a Rust TUI). Verified: sign-in is browser-based to the Mistral account
332by default, or `MISTRAL_API_KEY` from env, `~/.vibe/.env` or the
333keyring; headless is `vibe -p "…" --output streaming` (one JSON object
334per message), with `--max-turns`, `--max-price`, `--time-limit`,
335`--continue` and `--resume <id>`; MCP servers over stdio and HTTP in
336`[[mcp_servers]]`; permissions `ask`, `accept-edits`, `smart-approve`
337and `auto-approve`, with headless denying anything that needs approval
338unless `--auto-approve`, per-tool `permission` keys and `pre_tool` and
339`post_tool` hooks; `outside_workdir = "deny"`; custom providers with
340`api_style = "openai"` and `api_base`, including a `llamacpp` preset
341and a vLLM example; **no OS sandbox** (the docs say run auto-approve
342in a disposable container, which is what Equipo's namespace is).
343Exit codes 0 to 3. The only built-in Mistral model is
344`mistral-medium-3.5`, itself deprecated from 2026-10-31 with Mistral
345Large 4 as the named successor; Devstral 2 retires 2026-07-31.
346
347What the subscription covers, from Mistral's billing docs: "each
348Mistral plan includes monthly usage that is shared across Studio, the
349API, and Vibe Code", Pro at $14.99 a month, with pay as you go as
350prepaid overflow at API rates. A plan key made under Code, Vibe CLI
351draws on that budget; the help centre says API automation should use a
352pay-as-you-go key, not a plan key. The budget's size is not published,
353and a support reply seen only on Reddit says the allowance applies
354inside official Vibe clients; running the official CLI is inside that
355line, driving the API from Pi or OpenCode with a plan key may not be.
356So Paul's subscription reaches Equipo as **Vibe CLI, a subscription
357connection on its own harness** (`provider: mistral_cli`), and the
358Mistral API reaches it as an ordinary metered endpoint
359(`api.mistral.ai/v1`, chat completions, a preview Responses API, no
360Anthropic-compatible route) with its own key. Mistral API limits are
361per workspace with `Retry-After` on 429 and no remaining headers;
362usage is in the admin panel, the usage API being Enterprise only, so
363spend is computed from tokens and the price table (Large 4 $0.70 in
364and $2.10 out, Small 4 $0.15 and $0.60, Codestral 25.08 $0.30 and
365$0.90).
366
367Vibe also documents an experimental `run-server` mode, so a long-lived
368coordinator process is not ruled out; whether it relays approvals to a
369host is unprobed, and the matrix marks its coordinator cell "probe
370`run-server` before deciding". It is a candidate for the single
371OpenAI-compatible harness too (headless mode, streaming JSON, MCP,
372resume, hooks, custom providers), with the drawback of being Mistral's
373product driving other people's models; §5 scores it beside Pi.
374### 1.7 Later: Gemini and Muse
375
376Both are parked, with the facts that decided it. Gemini CLI was
377replaced by Antigravity CLI for unpaid and Google One tiers on
3782026-06-18 and is now aimed at Code Assist Standard and Enterprise; its
379Google OAuth client is fixed in source with loopback-only redirects, its
380`NO_BROWSER` flow needs a pasted code, Google's terms forbid reaching
381the Code Assist service through third-party software, and it has no
382container-free Linux sandbox. Its API-key path (`GEMINI_API_KEY`) works
383headlessly with `--output-format stream-json`, MCP servers and
384`--approval-mode`, so a Gemini API key could later be a metered
385connection under its own harness; not designed here. "Muse" is Meta's
386Muse Code (beta 2026-08-05, stable 2026-08-31): a real harness with
387`muse exec`, `muse serve` over stdio, MCP, approvals and an OS sandbox,
388but locked to Meta's Muse Spark models with plans from $5 a month and no
389documented limit reporting. Paul has neither account. Both get a row in
390the matrix marked "later" and nothing else.
391
392## 2. Connecting from the app
393
394### 2.1 What a connection is
395
396A **connection** row on the instance: `id`, `person`, `runner_id`,
397`provider` (`claude`, `codex`, `endpoint`, later `mistral_cli`,
398`command_code`), `harness`, `kind` (`subscription`, `api_key`,
399`endpoint`), `label` (the observed email, or a name the person typed),
400`state` (`connecting`, `healthy`, `limited`, `sign_in_again`, `error`,
401`signed_out`), `headroom` (`{utilization, resets_at, windows[]}`, null
402when the provider reports nothing), `plan` (`planType` from Codex,
403nothing from Claude), `models[]` for endpoints, `preference_rank`,
404`created_at`, `checked_at`, `revision`. No secret, no path, no raw CLI
405output; a guard test checks every field, as the Mac runners spec does
406for `capabilities`. On the runner, the same connection is a dedicated
407home `~/.local/share/equipo/accounts/<provider>-<n>` (today's layout),
408a `connections` table row with the same id, and whatever the harness
409keeps there. The existing `wire.Account {id, provider, email, healthy,
410headroom}` in `hello` is **replaced** by this record under
411`hello.connections` (§7), with the runner protocol version bumped as the
412Mac spec does; `accounts` leaves the wire. In copy the word "account"
413survives only where it names the provider's own thing ("your Claude
414account").
415
416Every flow below is a **connection attempt**: the app POSTs
417`/api/v1/connections` with `{provider, kind, runner_id}`, the instance
418writes the row in `connecting` and a durable `connect{connection,
419provider, kind, step}` frame to that runner (the mailbox of thin v1 §4
420and the runner-addressed mailbox of the Mac spec), and the runner
421answers with `connection{id, state, headroom, label, prompt}` frames as
422it progresses. The app shows one card, **Connecting Codex**, with
423whatever the `prompt` says (a code and a link, a field, a spinner) and
424replaces it with the connection line when `state` turns `healthy`. The
425card dies with the attempt: ten minutes with no progress, or the
426person's Cancel (`POST /connections/{id}/cancel`), ends it `error` with
427one of a fixed list of reasons (`timed_out`, `cancelled`,
428`provider_refused`, `runner_offline`, `identity_mismatch`,
429`already_connected`), never provider text.
430
431### 2.2 Device code: Codex
432
433The runner starts `codex app-server` in the new account's home with the
434containment of a converse action (egress to the provider hosts only;
435the login hosts are allowed for this one action and denied to runtime
436copies as today), sends `account/login/start {type: chatgptDeviceCode}`,
437and relays `verificationUrl` and `userCode` in the `prompt`. The card
438shows "Go to chatgpt.com/codex/device and enter **XXXX-XXXX**" with the
439link tappable. The app-server polls; `account/login/completed {success}`
440arrives; the runner calls `account/read` for the email and plan,
441`account/rateLimits/read` for headroom, records the identity, and
442reports `healthy`. Nothing moves from the app to the runner but the
443request to begin, and nothing moves back but a code OpenAI generated
444for display. If the person has not enabled device login the app-server
445reports an error and the card says so with the settings link; the
446reason is `provider_refused`. One real staged device-code sign-in is
447the witness for slice 1, together with the one real staged refresh
448thin v1 §3 already owes.
449
450### 2.3 Claude subscription: the binary's own flow, nothing relayed
451
452The policy in §1.1 fixes this flow: the unmodified `claude` performs
453the sign-in in the account's home, and Equipo neither forwards the
454code nor holds the token. What the app can do is start it, show the
455link, and detect the outcome. Three cases, decided by where the
456person's browser is relative to the runner:
457
4581. **Browser on the runner's machine** (a Mac runner, or Paul at
459 Tito Studio with the runner local). The runner starts `claude auth
460 login` in the new home with a pseudo-terminal, reads the authorize
461 URL from its output (the URL is not a secret; the code is), and
462 sends it in `prompt`. The app shows "Sign in to Claude" with the
463 link; the native app or the browser opens it on the same machine;
464 claude.ai redirects to `http://localhost:<port>/callback`, which the
465 CLI is listening on; no paste. The runner sees the CLI exit 0, runs
466 `claude auth status` in the home, records the email, reports
467 `healthy`. The runner knows it is this case when the app's request
468 carries `same_machine: true`, which the native app sets when it is
469 running on the runner's host (Mac spec §1.1 gives both a stable
470 identity) and the web app sets when the person taps "I am at this
471 machine".
4722. **Browser elsewhere, runner remote** (Paul on his phone, runner on
473 docs-t1). The loopback redirect cannot reach the CLI. A bridge was
474 considered: a listener on the person's device forwarding the
475 callback to the runner over Equipo's channel. That is possible only
476 with a native app on the device (a web page cannot listen on
477 localhost, and claude.ai redirects to `localhost`, not to a URL
478 Equipo controls), and even then the authorization code would pass
479 through Equipo's software, which is the intermediation Anthropic's
480 terms name. So Equipo does not build it. The card instead says
481 "Claude sign-in finishes on the machine that runs your runner" and
482 offers the two permitted ways: finish at that machine (case 1 later),
483 or in a terminal there run `equipo-runner login claude` and paste
484 the code where the CLI asks. The paste goes into the CLI, on the
485 runner, never into Equipo.
4863. **No token importer.** `claude setup-token` prints a one-year token;
487 a person could type it into a terminal on the runner, but Equipo's
488 command reading it would be Equipo handling a subscription token,
489 which is the intermediation the terms forbid. There is no `--token`
490 path. Claude is signed in only directly to the unmodified binary:
491 loopback on the runner's machine, or finish signing in on the
492 runner. A Claude **API key** connection (§2.4) is the way to use
493 Claude without a browser on that machine.
494
495**Adding a second Claude account in the app** is therefore: tap Add,
496choose Claude, and either finish on the runner's machine (no paste) or
497be told plainly to finish signing in on the runner. On Linux every
498Claude account gets its own home and the copy cycle of thin v1 §2
499applies unchanged; the Mac's Keychain question (Mac spec §3.4, probe P3)
500decides whether a Mac runner can hold more than one Claude account.
501
502### 2.4 API keys, sealed to the runner
503
504The app never sends a key to the instance in the clear, and the instance
505never stores one it can read. The runner holds an ed25519 identity key
506from enrolment (`internal/runner/enrol.go`), whose fingerprint the owner
507checked on the approval page (`runner.fingerprint`). The **seal key** is
508the X25519 key derived from that same ed25519 key (the standard
509birational map, as libsodium's `crypto_sign_ed25519_pk_to_curve25519`),
510so the public key the instance republishes on `Runner.seal_key` is
511verifiable by the app against the fingerprint approved at enrolment,
512and a substituted key would not match it. The native apps compare and
513refuse; the web app trusts the instance it is served by, which is
514already true of everything it shows, and that limit is stated in the
515Connections screen's help text.
516
517**The trust assumption, as built (2026-11-10, Claude setup tokens).** The
518runner sends its seal key in every hello over its authenticated
519connection, and the instance republishes it as received. The instance
520keeps only a hash of the enrolment key, so it cannot itself check the
521seal key against it, and the runner does not sign the seal key: the
522web app seals to whatever key the instance it is served by publishes.
523An attacker who controls the instance can therefore substitute a key
524and read a secret pasted afterwards; such an attacker can already serve
525a page that reads the field, so the seal adds nothing against it and
526protects against everything else (the instance's database, logs,
527backups, its operators reading rows, and other runners). When the native
528apps arrive (slice 4) the runner also publishes its ed25519 public key
529and the apps check both its fingerprint against the one approved at
530enrolment and the seal key against its birational map, refusing on a
531mismatch.
532
533**A pasted Claude token on the runner, as built.** The token lives only
534in `.oauth-token` (0600) in the connection's own home, outside every
535model-readable path, and reaches each Claude launch as
536`CLAUDE_CODE_OAUTH_TOKEN` through bubblewrap's `--args` pipe, never in
537argv, a manifest or a record. Inside the namespace two processes hold
538it in their environment: the namespace helper (PID 1), which makes
539itself non-dumpable before the CLI starts, so the CLI's descendants,
540which have no capabilities, cannot read its `/proc/1/environ`; and the
541unmodified CLI. The model reaches the CLI's process only through tools:
542- Bash: every command runs in the CLI's own sandbox. The policy sets
543 `sandbox.enabled`, `failIfUnavailable`, `allowUnsandboxedCommands:
544 false` and no `excludedCommands`, and the launcher refuses any other
545 settings, so `enableWeakerNestedSandbox` stays at its default, false
546 (it is not written out: that would change the certified policy
547 hashes). In the pinned 2.1.312 (read from the binary's sandbox
548 builder) that sandbox is a nested bubblewrap with a new user, PID and
549 mount namespace and a fresh `/proc` (`--unshare-user --unshare-pid
550 --proc /proc`); only `enableWeakerNestedSandbox: true` makes it bind
551 the inherited `/proc`, and there is no automatic fallback.
552 So a command cannot name the CLI or any ancestor. A second barrier
553 holds on its own: a process in a child user namespace has no ptrace
554 rights over the CLI, so even an inherited `/proc` refuses its
555 `environ`. `CLAUDE_CODE_SUBPROCESS_ENV_SCRUB=1` keeps the variable
556 out of the command's own environment.
557- Read, Glob, Grep: native rules deny `/proc` and `/dev/fd` (and the
558 sandbox denies them too).
559`TestToolCannotReadCLIEnvironment` (containment) runs a stand-in CLI
560holding a canary token inside the real namespace and starts a probe the
561way the CLI starts a Bash command. Run directly, the probe reads the
562token; in the sandbox it reads `/proc/<pid>/environ` for the stand-in's
563PID, its parent, PID 1 and every visible process, each thread's
564`/proc/<pid>/task/<tid>/environ`, `/proc/self/../<pid>/environ` and
565`/proc/<pid>/root/proc/<pid>/environ` (through itself, its parent and
566PID 1), and every read fails and the stand-in is not visible at all.
567Binding the inherited `/proc`, or dropping the PID namespace, makes
568the test fail, and so does a readable `/proc/1/environ` even from a
569direct child. What the test cannot show is the real CLI: on the first
570live paste, check from the model's Bash that `ls /proc` lists only the
571sandbox's own processes and that no `/proc/*/environ` contains
572`CLAUDE_CODE_OAUTH_TOKEN`; and recheck the sandbox builder at every CLI
573version bump. The containment's egress reaches only the provider's
574hosts, and a leaked token is revoked by running `claude setup-token`
575again and signing the old connection out. Also to check on the first
576live paste: `claude auth status --json` reports `loggedIn: true` with
577only the variable set; the CLI writes no `.credentials.json` into the
578home; and the variable is absent from the model's Bash environment.
579
580**Claude's sign-in by a link, as built (2026-11-10).** Paul, looking at
581the token card: "Can you not run this on the server and get a link to
582give to the browser? We're trying to avoid the round-trip over SSH
583here." Ruling: the one-time sign-in code is relayed through Equipo,
584sealed, the same category of risk accepted for the pasted token. This
585replaces §2.3 case 2's terminal card (and its watcher) as the way to
586add Claude with the browser elsewhere, and case 1's loopback sign-in
587"at this machine" too: the app refuses `same_machine` and the runner
588ignores it. A token row's Sign in again and the renewal line start
589this sign-in, the paste offered second. The runner runs the unmodified
590`claude setup-token` itself, on a pseudo-terminal, contained like every
591provider launch (the `signin-v1` policy, `provider.BuildSignInPolicy`):
592its own bubblewrap namespace, recorded before anything forks, whose
593only writable places, its home and /tmp, are the namespace's own memory
594(tmpfs capped at 64 MiB each, gone with it; nothing the CLI writes
595during the exchange reaches a disk), the connection's dedicated home
596and the runner's state not mounted (the runner writes the token into
597the home itself, from the CLI's output), no workspace or tool socket,
598`BROWSER` a program that opens nothing, and egress through the relay to
599`platform.claude.com` and `api.anthropic.com` only. Those hosts were
600read from the pinned CLI 2.1.312 statically: its production OAuth
601config has `TOKEN_URL` `https://platform.claude.com/v1/oauth/token`
602(the code exchange) and `BASE_API_URL` `https://api.anthropic.com`;
603setup-token fetches no profile and stores no credential, prints the
604token and exits after half a second. Stopping the CLI kills its whole
605namespace and waits for the exit to be proven, children included;
606after a runner crash the next start recovers the attempt's namespace
607(killed if it survived, its exit verified) before deleting its home.
608The runner reads the authorize URL the CLI prints (through ANSI and OSC
6098 escapes and redraws, only once the link's end has arrived; only https
610on claude.com or claude.ai whose redirect is
611`platform.claude.com/oauth/code/callback`). The card
612(prompt kind `authorize_link`) shows Open Anthropic and Copy link, then
613"Paste the code Anthropic shows you". The page seals the code exactly
614as it seals a token, bound to `endpoint`
615`https://platform.claude.com/oauth/code/callback` and to the card's
616`attempt`; the instance relays one box per card. The runner checks the
617box as it checks a token's, records `(connection, attempt)` in
618`seen_seals` in one transaction with the attempt still running, and
619types the code into the waiting CLI; the code is never written to
620disk. The token the CLI prints is kept exactly as a pasted one (the
6210600 `.oauth-token`, committed with the attempt turned kind `token`),
622then probed, bound and checked with one real request; healthy only
623then. A wrong code is said on the card with the next attempt: the same
624link while the CLI asks again, else the CLI is started again and the
625card shows its new link. The CLI exiting on its own starts it again
626with a new link (at most four runs, five codes). Cancel and the
627attempt's time limit kill the CLI's process group and remove the home.
628A stop before the token is committed loses the CLI with the process:
629the restart ends the attempt `runner_offline` and deletes its home;
630after the commit the restart carries it on as a token attempt. To
631confirm on the first live use, since only the start was observed (CLI
6322.1.321): what the CLI prints after a right code (the runner takes the
633first whole `sk-ant-oat` token in its output) and after a wrong one
634(the runner looks for error, invalid, failed, expired or wrong; the
635static read says "OAuth error: ..." then Enter to retry, the same link
636for a code it cannot read and a new sign-in for one the exchange
637refuses, and the runner presses Enter once), that a typed code followed
638by a separate carriage return is taken as entered, that the CLI honours
639the relay's proxy for the exchange, and that what it writes fits the
640in-memory home.
641
642**Sealing.** The app seals with libsodium `crypto_box_seal` over a
643payload `{secret, runner_id, connection_id, provider, endpoint,
644attempt, expires_at}`, where `endpoint` is the full origin, scheme,
645host and port (`https://api.tensorx.ai:443`); the instance-visible
646fields (`runner_id`, `connection_id`, `provider`, `endpoint`,
647`attempt`, `expires_at`)
648travel beside the box in the clear and the runner **rejects the box if
649any of them differs from the plaintext inside**, if `expires_at`
650(ten minutes from sealing) has passed, if the connection attempt is
651not the one it is currently running, or if the `(connection_id,
652attempt)` pair has been seen before (a `seen_seals` table kept for a
653day). The instance copies the opaque box into the durable `connect`
654frame. **Delivery on the runner is a small state machine** with one
655durable step at a time: (i) `received`: the frame id is in the inbox,
656nothing written; (ii) `staged`: the secret is written to
657`<home>/.secret.tmp` (0600) and fsynced, together with the directory;
658(iii) `committed`: in one SQLite transaction the `seen_seals` row
659`(connection_id, attempt, frame_id)` and the connection's state
660`credential_present` are written, and the temp file is renamed to its
661final name (`ANTHROPIC_API_KEY` env file for Claude, the harness's
662auth file for an endpoint; for Codex the rename is replaced by
663`codex login --with-api-key` reading the temp file, run before the
664transaction and verified by `account/read` inside it) with the
665directory fsynced; (iv) `acked`: the ack is sent. Recovery after a
666crash: a temp file with no `seen_seals` row is deleted and the frame
667reprocessed from `received`; a `seen_seals` row with the final file
668present is `committed`, so the resend only needs the ack; a
669`seen_seals` row with neither file is impossible by construction (same
670transaction) and is treated as `committed` with the connection marked
671`error`. A resend of a frame whose `(connection_id, attempt)` is in
672`seen_seals` is answered with an ack and nothing else. The buffer is
673zeroed after (ii). The instance then
674deletes the payload column. Honesty about that deletion: the
675ciphertext may persist in SQLite's WAL and in backups until they
676rotate. It is useless without the runner's private key, it names an
677attempt that cannot be replayed, and it expires in ten minutes, so the
678design accepts that residue and says so; it does not claim erasure.
679**Cancel** during `connecting` writes a `cancelled` marker the runner
680checks before writing the secret; a late success report for a
681cancelled attempt is dropped by the instance (`Attempt` and state
682checks as `chat/runner.go` does for turns) and the runner deletes the
683home. A sealed payload is capped at 4 KB and never logged; the mailbox
684payload column is excluded from every diagnostic dump, as credential
685bytes already are. Rotation is "sign out, add again". Sealed keys land
686in slice 2 with the endpoints; slice 1 has no key entry.
687
688### 2.5 Endpoints, with a test call (slice 2)
689
690An endpoint connection is `{base_url, label, sealed key or none,
691harness, local}`. Two transports, because the existing egress relay
692cannot carry the local case: `egress/proxy.go` accepts one bounded
693CONNECT to a public DNS name on port 443, and the namespace's
694`localhost` is not the host's, so an Ollama on the runner's machine is
695unreachable through it by design. **Public endpoints** (TensorX,
696Mistral, OpenRouter, the CARLOS gateway) use the existing relay with
697the connection's host added to its allow list for that connection's
698actions, HTTPS only. **Local endpoints** use a second, narrower
699listener the runner opens outside the namespace and binds into it on a
700fixed loopback port: it forwards plain HTTP to exactly one `host:port`
701recorded on the connection (the host's loopback or a LAN address the
702person typed), resolves the name once at connect time and pins the
703address, refuses redirects (`3xx` is returned to the harness as an
704error, never followed), admits only the HTTP methods and paths an
705OpenAI-compatible client uses, and is mounted only for actions on that
706connection. The harness is pointed at the loopback port, not at the
707host. On connect the runner fetches `/v1/models`, makes a one-token
708completion with the first model, records the model list and latency,
709and reports `healthy` with `models[]`; the card shows the models and
710lets the person pick a default. Probes before this ships (slice 2):
711the local listener is unreachable from a step whose connection is not
712local; a redirect from the endpoint is refused; a DNS change after
713connect does not move the pinned address; the listener dies with the
714namespace. For OpenRouter the key can arrive by its PKCE flow (§2.6)
715instead of typing.
716
717### 2.6 OAuth without a paste: what each provider allows
718
719Paul's question was whether the app can do "proper OAuth handoff
720without pasting a code". The answer per provider, from the official
721sources in §1:
722
723| Provider | Flow Equipo uses | Paste needed | Code exchanged where | Tokens rest where |
724|---|---|---|---|---|
725| Codex (ChatGPT plan) | Device code via `account/login/start` | No | Runner, by the app-server polling OpenAI | Runner home (`auth.json`) |
726| Codex (API key) | Sealed key | No | n/a | Runner home |
727| 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 |
728| 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`) |
729| 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`) |
730| Claude (API key) | Sealed key | No | n/a | Runner home |
731| 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 |
732| Local or other endpoint | Sealed key or none, test call | No | n/a | Runner home |
733| Hugging Face (not designed) | Has registered-app OAuth with loopback, custom-scheme and device-code flows | No | would be runner | would be runner |
734| 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 |
735
736Only OpenRouter (and Hugging Face) let a third party register or skip
737a client and receive the redirect at a URL Equipo controls. For
738OpenRouter the flow is hardened as follows: the app generates the
739verifier and uses `S256`; the `callback_url` is an instance route that
740carries the connection attempt id in its path and serves a page with
741`Referrer-Policy: no-referrer` whose first act is to read `code` from
742the query, replace the URL without the query (`history.replaceState`)
743and seal `{code, code_verifier}` to the runner bound to that attempt
744(§2.4); the instance's access log for that route omits the query
745string; a code older than ten minutes (OpenRouter's own expiry) or for
746an attempt that is not `connecting` is refused by the runner, which
747does the exchange at `/api/v1/auth/keys` and keeps the returned key.
748The instance sees the code for the duration of one request and
749never stores it; that is a weaker guarantee than for typed keys and
750the spec says so. Whether OpenRouter accepts a custom scheme is
751unconfirmed, so the native apps use an https app link to the Equipo
752origin. Codex needs no paste because device code is its own protocol.
753Claude is the one subscription where the loopback is the only no-paste
754path, and the terms make the sign-in belong to the CLI; Equipo's job is
755to make the same-machine case recognisable and the remote case honest.
756
757### 2.7 Health, headroom, limits, refresh, sign out
758
759**Health** is what the runner can prove: a `healthy` connection has a
760valid credential (the CLI refresh under the source lock for Claude,
761`account/read` for Codex, the harness's cheapest request for an
762endpoint) checked on start, hourly, and before any turn that needs a
763fresh copy, as today. `connecting` is not healthy and is never chosen.
764`sign_in_again` is set on an `auth` failure (§3) or when refresh reports
765a different identity (thin v1 §2). **Limited** is set on a `quota`
766failure, with `resets_at` when the provider reported one. **All
767telemetry comes from the harness side**: Claude's stream-json
768(`rate_limit_event`, `api_retry`, `result`), the Codex app-server's
769notifications (`account/rateLimits/updated`, `thread/tokenUsage/updated`,
770`turn/completed`), and in slice 2 Pi's JSONL events. The egress relay
771is a CONNECT tunnel (`egress/proxy.go`: one bounded CONNECT, port 443,
772public addresses only) and cannot see upstream headers, so no design
773here reads `Retry-After` or `x-ratelimit-*` off the wire; a metered
774endpoint's limit is whatever its harness reports, and where the harness
775reports nothing the connection becomes `limited` on the harness's
776error event with no reset time and a cool-off of fifteen minutes,
777doubling to an hour. Headroom is whatever the provider reports and
778nothing more: Claude's optional `utilization` and `resetsAt` (one
779figure, never labelled "weekly" or "session" because the SDK does not
780say which window it describes), Codex's `primary` and `secondary`
781windows when present, an endpoint's nothing ("unknown"). The Codex
782decoder today validates and discards rate notices (`rate_notice_test`);
783keeping them as state is slice 1 work. A connection leaves `limited`
784when `resets_at` passes or a probe succeeds; the probe is the harness's
785cheapest request, never a model turn, at most once per fifteen minutes.
786**Sign out** is `DELETE /connections/{id}`: the runner runs the
787harness's own logout (`claude auth logout`, `account/logout`, or
788nothing for a key), deletes the home, ends sessions on that connection
789(their rows stay, marked `connection_removed`), and reports
790`signed_out`; the instance keeps the row thirty days for Usage history
791and then deletes it.
792
793## 3. Selection and failover
794
795**The choice.** For each run the runner picks a **connection and model
796pair** from the person's own connections on the runner that holds the
797session or task. Eligible pairs are those whose matrix cell (§5) says
798yes for the role and whose connection is `healthy` (not `connecting`,
799`limited`, `sign_in_again`, `error` or `signed_out`). Among eligible
800pairs the order is: the current binding, if the session or step already
801has one and it is eligible (stickiness is a rule, not a tie-breaker:
802a session leaves its connection only on a `quota` or `auth` failure,
803an explicit override, or the preference exception stated in the
804failover list below); then the tier floor the router set (§4); then the person's
805preference for the role (§3, last paragraph); then headroom, where a
806subscription's headroom is the provider's reported figure, a metered
807connection with no report is "unknown" and ranks below any connection
808with a reported figure, and a local endpoint is "unknown" too, chosen
809by tier and preference rather than by a claim of being unlimited. The
810function is small and pure: inputs are the connection list with their
811models and matrix cells, the role, the tier floor, the preference and
812the current binding; the output is one `(connection, model)` and a
813reason code. It replaces `pickReviewer` in `internal/runner/thin/judge.go`
814and the coordinator's binding choice, returns a `runner.AccountBinding`
815as they do, and is unit-tested with a table.
816
817**Failure kinds.** The runner classifies every provider failure before
818it decides anything: `quota` (Claude `rate_limit_event {status:
819rejected}` or `api_retry {error: rate_limit}` exhausting its retries;
820Codex `account/rateLimits/updated` with a window at `usedPercent` 100
821or `rateLimitReachedType` set, or `turn/completed {status: failed}`
822whose error the decoder recognises as a usage limit); `auth`
823(`authentication_failed`, `oauth_org_not_allowed`, `account_on_hold`,
824`billing_error`; Codex `account/updated` to signed out or a 401 class
825error): the connection becomes `sign_in_again`; `transient`
826(`overloaded`, `server_error`, no response): retried on the same
827connection by the existing retry policy, never a failover. Only
828`quota` makes a connection `limited`; only `quota` and `auth` trigger
829failover. Fields are optional everywhere: `resetsAt` and `utilization`
830may be absent, Codex windows may be absent; a `limited` connection
831without a reset time shows "Limited, no reset time reported" and is
832re-probed on the §2.7 schedule.
833
834**Coordinator failover, with exactly-once effects.** Today a tool call
835id is `turn/attempt/useID` (`thin/bridge.go`), so simply replaying the
836turn on a new attempt would execute `start_task`, `add_project` or
837`ask_person` again under new ids. Failover therefore runs in this
838order, each step durable before the next:
839
8401. The failed attempt is **terminated**: the runner kills the
841 namespace and waits for the pidfd exit proof (thin v1 §4), as it
842 does for cancel. No new attempt exists until then.
8432. The turn enters a new nonterminal state **`waiting`**
844 (`turn{state: waiting, reason: limited | sign_in_again}`), added to
845 the turn state machine beside `queued` and `running`; `wire.Terminal`
846 stays false for it, so `chat/runner.go` keeps accepting reports. The
847 draft deltas are discarded as on cancel. If no eligible pair exists
848 the turn stays `waiting` and the chat shows the card in the last
849 paragraph; queued messages join the waiting turn.
8503. The runner chooses a new pair and **advances the attempt** in its
851 `runs` row and in a `turn{state: running, attempt: n+1}` report,
852 which the instance accepts only as a forward transition from
853 `waiting` for that turn.
8544. Before the new process gets the frame, the runner **reconciles
855 effects through the turn's mutation ledger**. Matching on arguments
856 is not used: a paraphrased `ask_person` would defeat it. Instead the
857 instance keeps a per-turn **ledger** of the designated mutating
858 tools, written in the same transaction as the effect: `add_project`
859 (kind `project`, target the repository name), `create_project`
860 (kind `project_create`, target the name), `set_project_home` (kind
861 `home`, target the person), `record_task` (kind `task_record`,
862 target the task id it created), `start_task` (kind `task_start`,
863 target the task id), `cancel_task` (kind `task_cancel`, target the
864 task), `add_finding` (kind `finding`, target task and finding id),
865 `ask_person` (kind `ask`, target the card id). The runner asks for
866 the ledger (`tool_calls{turn}`, answered with the ledger entries and
867 their recorded results) and the new attempt's frame is the person's
868 messages plus a runner-written summary that lists each completed
869 operation by kind and target ("oficina/sample is already added; task
870 tk_… is recorded and started; the person was asked and answered Y").
871 The instance then **enforces per-kind rules on any later call in the
872 same turn, whatever the model's wording**: `ask` opens at most one
873 card per turn, so a second `ask_person` in the turn returns the open
874 card (or its answer) rather than creating one; `task_start` is
875 idempotent per task id; `task_record` within a turn that already
876 recorded a task attaches the call to that task and returns it
877 instead of creating another; `project` and `project_create` are
878 idempotent per name; `home` is idempotent per person and still
879 needs the person's own words (slice 2b); `finding` is idempotent per
880 task and normalised text; `task_cancel` is idempotent per task. A
881 call the rules fold into an earlier operation returns the stored
882 result with `replayed: true`. **Reads are never deduplicated**:
883 `status`, `read_task` and every other read run fresh on every
884 attempt, so `status`, `start_task`, `status` sees the started task.
885 The designated list is a constant in `wire` and the ledger refuses a
886 kind it does not know.
8875. The frame goes to the new session, seeded from the notebook, the
888 house rule and the tail as thin v1 §2, and the reply arrives with one
889 quiet line under it: "Switched to Codex; Claude resets Mon 10:00"
890 (`chat.switched`), or "Switched to Codex" when no reset time was
891 reported. **The one exception to stickiness**: when a connection the
892 person prefers has recovered, the coordinator returns to it only at
893 a natural boundary, the start of a new turn after the current
894 session's turn has ended and no messages are queued, never mid-turn
895 and never for a step or an ask in flight; the line is shown only
896 when the switch happens, and the old session is resumed with a fresh
897 notebook and tail injection (thin v1 §2's daily reset rule covers
898 staleness).
899
900A cancel during `waiting` ends the turn `cancelled` and voids the
901pending frame; a cancel that arrives after step 3 targets attempt n+1
902and ignores stale reports for attempt n (`chat/runner.go` already drops
903reports for `Attempt < r.Attempt`).
904
905**Engineering mid-step.** A step whose harness fails on `quota` or
906`auth` is a failed attempt as any crash is: termination proof first,
907nothing committed (the worktree is discarded; partial work is not a
908candidate), then a new attempt on another eligible pair avoiding the
909connections that failed (`avoid_connections[]` on dispatch replaces
910`avoid_account`), same brief. The step records both attempts and their
911pairs; the card shows "Engineering on Codex (Claude was limited)".
912With no eligible pair the step waits in `queued` with reason
913`no_connection` and resumes on its own when a connection returns.
914
915**Review across families.** Thin v1 §3's rule stands, with the family
916read from the pair actually chosen, not from the connection: an
917endpoint that serves several model families is `other_family` only
918when the chosen model's family differs from Engineering's. `other_family`
919first, then `same_family` with fresh context, then `same_account`; the
920label is recorded on the step.
921
922**Ask the implementer** keeps its exact binding: the kept session on
923the connection and model that ran the step (slice 4b). It never moves;
924if that connection is not `healthy` the question fails
925`account_unavailable` with the reset time in the card.
926
927**"Nothing can answer."** When no eligible pair exists for the
928coordinator the turn is `waiting` with reason `no_connection`, and the
929chat shows a card in place of `chat.failed`: "Nothing can answer right
930now. Claude resets Mon 10:00; Codex is signed out." with one action,
931**Add a connection**. The message is not lost and is not resent by the
932person; when a connection becomes eligible the runner advances the
933attempt and the reply arrives. The person may cancel the turn.
934`wire.Reasons` gains `limited` and `no_connection`; `Task.NeedsYou`
935gains `no_connection`; the old "Send your message again to retry" line
936goes.
937
938**The preference.** Settings gains one quiet row per role, "Coordinator
939prefers", "Engineering prefers", "Review prefers", each a picker over
940the person's connections and, for endpoints, a model, plus "Automatic"
941(the default). It sits after the tier floor in the order above, so a
942preference cannot put a `strong` job on a `cheap` model, and it never
943overrides health. `PUT /api/v1/preferences {role, connection_id,
944model | null, revision}`. Per task, the task page offers "Run on …"
945before the first step starts and "Retry on …" at a failed step; a
946per-task choice is a tier override as well, recorded as such.
947
948## 4. Routing: who does what
949
950Paul's framing: the coordinator "would probably use a specialist or
951some technique to decide who to delegate jobs to", balancing cost and
952model choice. Three options were weighed.
953
954A **routing specialist**, a model turn that reads the brief and picks
955a connection, costs a turn per task (on the very connection it is
956trying to save), is hard to test (its choices are text), and its
957reasons would be its own words rather than facts. A **deterministic
958policy** alone cannot see what the job is: a README typo and a
959migration of the payments module look the same to a function over
960headroom. The **hybrid** takes the one thing a model is good at here,
961reading the brief, and leaves the arithmetic to a function. Recommended.
962
963**Classification.** When the coordinator calls `record_task` or
964`start_task` it adds three fields it already knows from the
965conversation: `size` (`small`, `medium`, `large`), `risk` (`low`,
966`normal`, `high`: touches auth, payments, deploy, data migration, or
967the person said "careful"), and `kind` (`fix`, `feature`, `refactor`,
968`docs`, `test`, `investigate`). The tool schema makes them required
969enums with one-line definitions; a missing or invalid class defaults
970to `medium`, `normal`, `feature` and is recorded as defaulted. The
971coordinator does not choose a connection; it describes the job.
972
973**Models, not connections, have tiers and families.** A connection
974offers one or more models (a subscription offers the provider's
975current models; an endpoint offers its `models[]`). The runner ships a
976static **model map**: for each known model id, its family (`claude`,
977`gpt`, `glm`, `deepseek`, `kimi`, `qwen`, `mistral`, `llama`, …), its
978tier (`cheap`, `standard`, `strong`) and, for metered connections, a
979price per million tokens with a `price_version`; an unknown model is
980`cheap`, family `unknown`, and is reported so the map can be extended.
981Two endpoints serving the same model are two pairs with the same
982family and tier; one endpoint serving several families is several
983pairs. Every step and turn records the pair that ran and its family,
984and Review's `other_family` is judged on recorded families (§3).
985
986**The policy.** A table, shipped as defaults and never edited by the
987person in v1: a class maps to a **tier floor** per role. Engineering:
988`small` and `low` risk floor at `cheap`; `medium` or `normal` at
989`standard`; `large` or `high` at `strong`. Review: one tier above
990Engineering's actual tier, minimum `standard`, another family where an
991eligible pair exists. Coordinator: `standard` or above. Ask: pinned to
992the step's pair. A pair's **cost signal** is `subscription` (within
993plan: no marginal cost until limited, overage priced if the person
994typed one), `metered` (price from the model map), or `free` (local).
995The choice function of §3 applies, in its fixed order: eligibility,
996stickiness, the tier floor as a filter, the preference, then headroom
997with the cheapest cost signal first among equals. Nothing here needs
998setup: with one Claude account every job lands there, exactly as
999today; add a local Ollama and small fixes start moving to it; add
1000Codex and Review becomes cross-family.
1001
1002**Cheap-first escalation.** A first pass whose pair is below `strong`
1003and that fails checks or gets `changes_requested` is retried one tier
1004up on the first fix round, on a different family if an eligible pair
1005exists; the second fix round (thin v1's `MaxFixRounds` 2) stays on the
1006escalated tier. Escalation is recorded on the step as `escalated_from`.
1007A `strong` first pass that fails stays `strong`.
1008
1009**What the person sees.** One quiet line on the task card and in the
1010timeline: "Engineering on Codex, local model for the first pass" or
1011"Engineering on Claude (Paul prefers Claude)". The Usage page (§6)
1012sums it: "3 tasks moved to Codex while Claude was limited". Every
1013decision is a `routing` row: task, step, role, class, tier floor,
1014connection, model, family, reason (`sticky`, `preference`, `headroom`,
1015`cheapest`, `escalated`, `failover`, `only_option`,
1016`same_family_review`), so the line and the sum are read from data.
1017Override is per task ("Run on …", §3) or standing (the preference),
1018and an override is a `reason: preference` row like any other.
1019
1020## 5. Tools and safety per harness, and the capability matrix
1021
1022Every role has three needs the harness must meet, or it is marked
1023unsupported for that role: the **coordinator's MCP tools** (`status`,
1024`add_project`, `record_task`, `start_task`, `read_task`,
1025`cancel_task`, `ask_person`, and the slice 2 to 4c additions) over the
1026existing `equipo-tool-proxy` socket; the **permission relay** (a tool
1027call the harness will not make without an answer becomes `ask_person`
1028or a deny by policy); and the **tool shape per role**: read-only for
1029Review and ask, write plus shell for Engineering, no filesystem for
1030the coordinator.
1031
1032**Containment** is identical for every harness on Linux: the same
1033bubblewrap namespace, egress relay with the connection's hosts only
1034(and, for `local` endpoints, the one local host and port), the
1035credential home mounted to the harness and denied to model tools,
1036pidfd termination proofs, `provider/policy.go`'s effective-policy
1037check extended with a Pi profile (exact argv, `--offline`,
1038`--no-approve`, `--session-dir`, `--tools`, the extension file's hash,
1039`mcp.json` and `models.json` contents, no inherited environment). Pi's
1040and Codex's own sandboxes are off inside the namespace (Codex
1041`danger-full-access`, Pi has none), as Codex's row already assumes; the
1042namespace is the containment. On the owner's Mac (Mac spec §4) Claude
1043Code's `sandbox.enabled` profile is trusted for Claude steps; Codex and
1044Pi on the Mac are parked until probe P5 shows Codex's Seatbelt nests
1045under `srt`, and Pi, having no sandbox, would run under an `srt`
1046profile of Equipo's own, which is slice F work there, not here. **Termination comes from the namespace, never from the harness**: Pi's
1047`abort` waits for the session to go idle and keeps the process alive
1048(its RPC docs), Codex's `turn/interrupt` ends a turn, Claude's SIGINT
1049ends a turn; Equipo kills the namespace and waits for the pidfd proof,
1050as today. Before any harness earns a "yes" cell it passes the same
1051**containment proofs** in CI and once on staging: it works through the
1052CONNECT relay with no direct network (proxy support); a model tool
1053cannot read the credential home or the runner's state (credential-read
1054denial, tried by a hostile prompt in the fake and a `cat` in staging);
1055shell is absent or restricted in the read-only roles; MCP tools are
1056exactly the pinned set and nothing else is callable; and killing the
1057namespace ends every descendant, including the harness's subprocesses
1058(descendant termination). Claude passes these today; Codex and Pi get
1059them as the first task of their slices. Each
1060harness gets a **fake CLI** in CI reproducing its pinned protocol from
1061recordings: `fakeclaude` exists, `fakecodex` is slice 1 here (the
1062app-server JSON-RPC including device-code login, `account/rateLimits`
1063and `thread/tokenUsage/updated`), `fakepi` is the local-models slice
1064(RPC mode, `extension_ui_request`, usage on `message_end`).
1065
1066| Provider, harness | Coordinator | Engineering | Review | Ask | Limit and headroom signal | Slice |
1067|---|---|---|---|---|---|---|
1068| 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 |
1069| 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 |
1070| 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 |
1071| TensorX, Pi (chat wire) | Yes, `standard` tier for the larger models | Yes | Yes | Yes | 429 `retry-after`, `x-ratelimit-reset`, `x-ratelimit-remaining-*` | 2 |
1072| Mistral API or OpenRouter, Pi | Yes, `standard` | Yes | Yes | Yes | 429 `Retry-After`; OpenRouter key info endpoint later | 2 |
1073| 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 |
1074| 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 |
1075| Gemini, Muse | Later | Later | Later | Later | | |
1076
1077"Yes" in the Pi rows is conditional on the probes in §8 passing: RPC
1078mode holding a session across a hundred turns, `extension_ui_request`
1079reaching the host for a blocked tool, MCP tools pinned and callable,
1080and a clean exit under `turn/interrupt`'s equivalent (`abort`). A
1081harness that fails a probe keeps its row with the failing cell marked
1082`No` and the reason, and the choice function reads the matrix, so an
1083unsupported pair is never chosen.
1084## 6. Usage: one page for availability, spend and tokens
1085
1086**Name.** "Usage". It is what the page shows, it reads as a noun in
1087the sidebar beside Tasks, Projects and Needs you, and it avoids both
1088"Cost management" and the slightly pompous "Capacity". The sidebar
1089entry carries a small dot only when something needs attention: a
1090connection `limited` or `sign_in_again`, or month-to-date spend over
1091the soft ceiling. Quiet otherwise.
1092
1093**The page**, top to bottom. *Availability now*: one row per
1094connection, the label, the state in words ("Healthy", "Limited until
1095Mon 10:00", "Signed out"), and the provider's own headroom where it
1096reports one: Codex's two windows as two thin meters with "resets in 3 h
109712 m" and "resets Thu", Claude's one `utilization` figure as one meter
1098with its `resetsAt`, TensorX's remaining requests and tokens from the
1099last response headers with the minute they refer to, a local endpoint
1100"Unknown, no limit reported". Never a percentage the provider did not
1101send. *Spend this month*: metered connections only, the sum of recorded
1102tokens times the connection's price table, labelled "estimated from
1103tokens" (TensorX and Mistral publish no usage API; OpenRouter's
1104`/api/v1/key` or generation endpoint can later replace the estimate
1105with the real figure), next to the soft ceiling with the 80% line and
1106Pause from thin v1 slice 6, now per person across all metered
1107connections. Subscriptions show as a flat plan line ("Claude Max,
1108$200 a month" typed once by the person, or blank) with their token use
1109beside it, never a fake dollar figure; local endpoints show "Free" and
1110their tokens. *Token use*: a table with day, week and month tabs, rows
1111by connection, by role, by project and by task (the four groupings are
1112tabs over one dataset), columns input, cached input, output, and the
1113estimate where there is one. *Routing*: the sum lines from §4 for the
1114period ("3 tasks moved to Codex while Claude was limited", "12 small
1115fixes ran on the local model", "2 escalations after review").
1116
1117**Recording, from day one.** The runner writes one `usage` row per
1118**attempt** of a turn, step or question, whether it replied, failed,
1119was cancelled or is still waiting for a reconnect: person, connection,
1120model, harness, role, project, task, step, turn, attempt, outcome
1121(`replied | failed | cancelled | superseded`), input, cached input,
1122cache write, output, reasoning output (each nullable: a harness that
1123did not report a figure leaves null, never zero), `complete` (true
1124only when the harness's final usage message for that attempt was
1125seen), estimated cost in micro-dollars with `price_version` (the id of
1126the price-table revision used; null for a subscription within plan and
1127for a local endpoint), and recorded at. Per harness: Claude's `result`
1128message gives `usage` and `modelUsage` once per attempt, and
1129`modelUsage` is kept per model (one row per model when a turn used
1130several); Codex sends several `thread/tokenUsage/updated` notices within
1131one turn and across a resume, and the first notice after a resume can
1132already include new consumption (the local fixtures in
1133`provider/codex/testdata` show totals of 14,054 then 28,254 input
1134tokens within one turn), so the runner never subtracts a post-resume
1135notice. It captures a **verified pre-turn baseline**: the `total` from
1136the last notice of the previous attempt on that thread, stored on the
1137thread's `sessions` row when that attempt completed, and confirmed
1138before `turn/start` by the first notice carrying the previous `turnId`
1139or by a thread whose stored baseline is zero for a new thread. The
1140attempt's figure is the last `total` of this turn minus that baseline;
1141`last` is a consistency check; a notice whose `turnId` or `threadId`
1142does not match the attempt is dropped. When no verified baseline
1143exists (a resume with no stored total, a thread Equipo did not create)
1144the row records the turn's `last` values summed where they can be and
1145`complete: false`, never a subtraction; Pi's `message_end.usage`
1146(slice 2) is summed over the attempt's messages. Rows travel in the
1147existing `reply`, `step` and `answer` frames as a `usage` array (the
1148present `wire.Usage` "without cost data" becomes this shape), and a
1149`usage` frame of its own carries rows for attempts that produced no
1150reply. The instance stores them as a `usage` table keyed by
1151`(turn or step or question, attempt, model)`, so a resent frame is a
1152no-op; raw rows are kept 90 days, daily sums indefinitely. A
1153subscription is not free past its plan: Claude's `rate_limit_info`
1154carries `overageStatus` and `isUsingOverage`, and Codex's
1155`rateLimitReachedType` and `credits` say when paid credits are being
1156consumed; a row recorded under overage carries `overage: true` and is
1157counted in Spend at the connection's typed overage price, labelled as
1158such. Slice 1 records every field it can and shows nothing new; the
1159page comes later and finds the data waiting.
1160
1161**Resources.** `GET /api/v1/usage?period=day|week|month&by=connection|
1162role|project|task` returns `UsageReport {period, from, to, rows[{key,
1163label, input, cached_input, output, reasoning_output, estimated_cost,
1164turns, steps}], spend {estimated, ceiling, paused}, routing[{line,
1165count}], revision}`; `GET /api/v1/connections` is the availability
1166list; `PUT /api/v1/usage/ceiling {monthly, paused, revision}` sets the
1167soft ceiling. Event `usage` fires once per committed `usage` row with
1168`{resource: usage, id, revision}` so the open page updates its sums;
1169`connection` events carry the availability changes. Fixtures:
1170`api/connections.json`, `api/usage-month.json`, `api/usage-ceiling.json`,
1171`api/event-usage.json`, `frames/reply-usage.json`,
1172`frames/step-usage.json`. The Snapshot gains `connections` and a
1173`usage_summary {limited, signed_out, over_ceiling}` for the sidebar dot.
1174## 7. API v1, wire and fixtures
1175
1176**Resources.** `Connection` as in §2.1; `ConnectionList` at
1177`GET /api/v1/connections` (the person's own, every runner);
1178`POST /api/v1/connections {provider, kind, runner_id, label?, base_url?,
1179local?, sealed?, same_machine?}` returns `202` with the `Connection` in
1180`connecting`; `POST /connections/{id}/cancel`; `DELETE /connections/{id}`
1181(sign out); `GET /connections/{id}`; `PUT /api/v1/preferences {role,
1182connection_id | null, revision}` and `GET /api/v1/preferences`;
1183`UsageReport` and the ceiling as in §6. `Runner` gains `seal_key`.
1184`Step` gains `connection_id`, `tier`, `class {size, risk, kind}`,
1185`escalated_from`, `routing_reason`; `Task` gains `class` and
1186`connections[]` (what ran it). `Turn` gains `connection_id`. `Snapshot`
1187gains `connections`, `preferences`, `usage_summary`. Reasons:
1188`wire.Reasons` adds `no_connection`, `limited`, `connection_removed`;
1189`Task.NeedsYou` adds `no_connection`; connection attempt reasons are
1190their own list (§2.1). Events: `connection` (every state change and
1191headroom change, throttled to one per connection per minute for
1192headroom), `usage`, `preference`. The sidebar dot is computed by every
1193client from `usage_summary`, so the web and native apps agree.
1194
1195**Frames.** Instance to runner: `connect{connection, provider, kind,
1196label, base_url, local, sealed, same_machine}` (durable; `sealed`
1197deleted after ack), `disconnect{connection}` (durable),
1198`cancel_connect{connection}`, `preference{role, connection}` (durable,
1199so the runner's choice function has it offline). Runner to instance:
1200`connection{id, state, label, plan, headroom, models, prompt {kind:
1201device_code | link | none, url, code}, reason}` (durable),
1202`routing{task, step, role, class, tier, connection, reason}` (durable,
1203with the `step` report), and `usage` objects on `reply`, `step` and
1204`answer`. `hello.accounts` becomes `hello.connections` with the full
1205record, `hello.seal_key` is added, and `sync` adds `connections` so a
1206reconnect reconciles state. `dispatch` carries `class`, `tier`,
1207`avoid_connections[]` (replacing `avoid_account`) and an optional
1208`connection` for a per-task override. `message` carries nothing new:
1209the runner chooses. The tool `record_task` and `start_task` schemas
1210add `size`, `risk`, `kind`.
1211
1212**Fixtures** under `internal/wire/wiretest/testdata`:
1213`api/connections.json`, `api/connection-connecting-codex.json` (with
1214the device-code prompt), `api/connection-limited.json`,
1215`api/connect-request-sealed.json`, `api/preferences.json`,
1216`api/usage-month.json`, `api/usage-ceiling.json`,
1217`api/event-connection.json`, `api/event-usage.json`,
1218`api/needs-you-no-connection.json`, `api/step-routed.json`;
1219`frames/connect.json`, `frames/connection.json`,
1220`frames/disconnect.json`, `frames/preference.json`,
1221`frames/routing.json`, `frames/hello-connections.json`,
1222`frames/reply-usage.json`, `frames/step-usage.json`,
1223`frames/dispatch-class.json`. A guard test asserts no fixture or frame
1224type has a field whose name contains `key`, `token`, `secret`,
1225`credential` or `path` except `seal_key` (public) and `sealed`
1226(ciphertext), and that `sealed` never appears in a runner-to-instance
1227frame or an API response.
1228
1229**Copy for review** (marker as before, Luna's pass later):
1230"Connections", "Add a connection", "Connecting %s", "Go to %s and
1231enter %s", "Sign in to Claude", "Claude sign-in finishes on the machine
1232that runs your runner", "I am at this machine", "Switched to %s; %s
1233resets %s", "Switched to %s", "Nothing can answer right now. %s",
1234"Usage", "Limited until %s", "Signed out", "Healthy", "Unknown, no
1235limit reported", "Estimated from tokens", "Coordinator prefers",
1236"Engineering prefers", "Review prefers", "Automatic", "Run on …",
1237"Retry on …", "Engineering on %s, %s for the first pass", "%d tasks
1238moved to %s while %s was limited". Removed: `chat.failed` "The
1239coordinator could not answer. Send your message again to retry."
1240
1241## 8. Slices
1242
1243Each slice lands headless first (contracts, runner, fake-CLI scenario
1244green in CI under the two-minute budget), then staging with real CLIs,
1245then UI, then deploy, as thin v1 §8. Sizes are agent days.
1246
1247| Slice | Content | Tests | Size |
1248|---|---|---|---|
1249| 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 |
1250| 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 |
1251| 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 |
1252| 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 |
1253| 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) |
1254| 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 |
1255| 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 |
1256| 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 |
1257
1258Slice 1 (gates 1a to 1d, four days) is the one that unblocks Paul:
1259with two Claude accounts or one Claude and one Codex connected, the
1260coordinator keeps answering through a limit, and both can be added from
1261the app (Codex entirely; Claude at the machine, or finished on the
1262runner). Each gate is green in CI before the next starts, and 1c's
1263staging witness runs before 1d.
1264
1265## 9. Decisions for Paul
1266
12671. **Claude signs in only to the unmodified binary.** On the runner's
1268 machine by loopback, otherwise "finish signing in on the runner"
1269 (`equipo-runner login claude` there, the paste going into the CLI).
1270 No token importer and no device-side bridge, because Anthropic's
1271 terms forbid Equipo handling the code or token and an owner's
1272 acceptance cannot waive a provider's terms. Confirm; the
1273 alternative is a Claude API-key connection for remote machines.
12742. **Pi is the single OpenAI-compatible harness**, with OpenCode as the
1275 fallback if the slice 2 probes fail, Vibe for the Mistral
1276 subscription with `run-server` probed before it is given a
1277 coordinator cell, and Command Code last with `cmd acp` probed the
1278 same way. Confirm, or name a different order.
1279
1280## 10. Risks
1281
1282Pi's RPC mode is verified from its docs and source, not yet from a
1283hundred-turn run in bubblewrap; slice 2 starts with the probes and the
1284OpenCode fallback costs two days. Headroom is still best effort: Claude
1285reports one figure, endpoints report nothing, and `limited` for them
1286rests on observing a 429. A coordinator that switches family loses its
1287in-context memory and keeps only the notebook, the tail and a
1288runner-written summary; the switched line makes that visible and the
1289preference pulls it back. Codex's own sandbox needs user namespaces
1290Equipo's namespace does not grant, so Codex runs unsandboxed inside
1291the container, as the design already assumed. Spend is an estimate
1292from tokens and a price table that someone must keep current, labelled
1293as such. TensorX's and Mistral's quieter corners (streamed tool-call
1294chunks, prompt caching, whether a plan key may be used from Pi) are
1295marked unverified above and are probed, not assumed. Exactly-once effects rest on
1296the mutation ledger's per-kind rules on the instance, not on the
1297model's wording or cooperation; the designated list must stay complete
1298as tools are added, and a guard test fails when a tool that writes is
1299not in it.
1300Sealed-box residue in WAL and backups is accepted and labelled, not
1301erased. The word count is above the brief because four sections were
1302added on the way; nothing in them is optional for the design to hold
1303together.
1304