oficina / equipo Public

spec: connectors and token scheduling rev 2 (Astra round 1 folded in)

Astra's round 1 said NOT READY. Revision 2 cuts scope instead of
spinning: every new connector reaches its provider only through a
metering gateway on the runner, which holds the key, reserves each
request's worst case against a hard cap, and allows only inference
paths. Sign-in is the sealed paste only. The Command Code CLI, Mac,
coordinator cells, calibration and account advice move to later.
Section 15 maps all 25 findings.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by paul@keymail.dev 6591b3351815c2d96ba65a39cd08d2feb3f3247d parent 732d7d6
1 file changed, +686 −789
  • docs/superpowers/specs/2026-11-12-equipo-connectors-and-token-scheduling.md +686 −789

CI failed — run details

diff --git a/docs/superpowers/specs/2026-11-12-equipo-connectors-and-token-scheduling.md b/docs/superpowers/specs/2026-11-12-equipo-connectors-and-token-scheduling.md
index 56cc78a6..021af434 100644
--- a/docs/superpowers/specs/2026-11-12-equipo-connectors-and-token-scheduling.md
+++ b/docs/superpowers/specs/2026-11-12-equipo-connectors-and-token-scheduling.md
@@ -1,56 +1,78 @@
# Equipo connectors and token-aware scheduling
-Status: design for Paul's review, 2026-11-12, revision 1. Spec only,
+Status: design for Paul's review, 2026-11-12, **revision 2**. Spec only,
nothing built. Drafted by Claude (Opus 5.5) on `connections-slice2-design`
-from main 1d7b4e4. Builds on Connections rev 3
-(`2026-11-08-equipo-connections.md`, "rev 3" below) as built in
-`CONN1-PROGRESS.md`, the spend lines (`chat_usage` with `round` and
-`turns`, migration 0059), the housekeeping budgets
-(`2026-11-08-equipo-housekeeping.md` §4) and the merge authority's
-ask-with-a-recommendation pattern (`2026-11-11-equipo-merge-authority.md`
-§4). Provider facts were read from official docs on 2026-11-12 (§14).
+from main 1d7b4e4.
+
+Revision 1 (732d7d6) drew **NOT READY** from Astra's one round
+(`CODEX-FINDINGS-CONNECTORS-SCHEDULING.md`). Per the brief, revision 2
+cuts scope rather than spinning. The central change is that every new
+connector reaches its provider only through a **metering gateway on the
+runner**. The gateway holds the key, prices and caps every request
+before forwarding it, and allows only inference paths. §15 maps each
+finding to its fix or cut.
+
+This builds on:
+
+- Connections rev 3 (`2026-11-08-equipo-connections.md`, "rev 3"), as
+ built in `CONN1-PROGRESS.md`;
+- the spend lines (`chat_usage`, migration 0059);
+- the housekeeping budgets (`2026-11-08-equipo-housekeeping.md` §4);
+- merge authority (`2026-11-11-equipo-merge-authority.md`): a
+ deterministic gate, the coordinator can only tighten, and asks come
+ with a recommendation.
+
+Provider facts were read from official docs and source on 2026-11-12
+(§14).
## 0. Decisions for Paul
Each has a recommendation. Nothing is built until these are answered.
1. **"Pi" means Pi as the harness, with TensorX as the paid
- connection.** Pi has no subscription of its own. Your Pi connector
- is TensorX through Pi, capped. *Recommend: yes.* Other API-key
- providers (Mistral API, OpenRouter) can follow on the same path later.
-2. **When subscriptions run out, which work may spend TensorX money?**
- *Recommend:* only tasks you marked `urgent`, and only by your tap,
- never the coordinator's. `normal` and `low` work waits for the
- reset. A deadline that waiting would miss asks you, with "I'd run it
- on TensorX: about $0.40". The "cheap and short" rule (Review or
- explore steps under $0.02 go to TensorX to save subscription room)
- ships **off**. Alternative: allow `normal` to spill as well.
-3. **Default caps for a new TensorX connection**, pre-filled on the
+ connection.** Pi has no subscription of its own. *Recommend: yes.*
+2. **Command Code arrives as a provider behind Pi, not as its own
+ harness yet.** You already use Command Code's models through Pi, and
+ its Provider API (`api.commandcode.ai/provider/v1`) fits the
+ gateway. Its own CLI has undocumented hosts and stream, so it waits
+ for a later design. Please check in Command Code Studio whether
+ Provider API calls draw on your plan's 5-hour and weekly windows or
+ on pay-as-you-go credits. Until that is known, Equipo treats it as
+ metered and capped. *Recommend: yes.*
+3. **When subscriptions run out, which work may spend metered money?**
+ *Recommend:* only tasks you marked `urgent`. Only your tap sets
+ urgent, never the coordinator's. `normal` and `low` work waits for
+ the reset. A deadline that waiting would miss asks you first, with
+ "I'd run it on TensorX: at most $0.40".
+4. **Default caps for a new metered connection**, pre-filled on the
connect card and required before first use. *Recommend: $1 a day and
- $10 a month.* Equipo refuses to dispatch past either, and kills a
- step that reaches the cap mid-run.
-4. **The reserve ladder.** `low` work stops at 70% of a subscription
- window, and `normal` at 90%. Above that, only `urgent` work and your
- chat with the coordinator go on. *Recommend: these numbers*, changed
- later from data.
-5. **Command Code.** Its hosts and headless stream are undocumented, and
- it is proprietary. It goes last, over ACP, after a host discovery
- probe. Please check in Command Code Studio whether a Studio API key
- draws on your plan or on pay-as-you-go credits. If it is credits,
- the connection is metered and capped like TensorX. *Recommend: keep
- it, last.*
-6. **OpenCode Go can overflow into Console credit** when a Go limit is
- hit, and Equipo may not see it. *Recommend:* keep your OpenCode
- Console credit balance at zero (or switch the fallback off, if the
- Console offers that), so overflow fails instead of billing.
-7. **The coordinator stays on Claude and Codex** in this design. The new
- connectors take Engineering, Review and Ask, which is where tokens
- go. *Recommend: yes.* A coordinator cell for Pi or OpenCode is a
- later slice after rev 3's probes.
-8. **Order.** *Recommend:* metered base and caps, Pi on TensorX, the
- scheduler, Usage and advice, OpenCode, Vibe, Command Code, then Mac.
- Alternative: the scheduler first, if holding work matters more to you
- right now than TensorX.
+ $10 a month.* The cap is hard: the gateway refuses any request whose
+ worst-case price does not fit.
+5. **The reserve ladder.** `low` work starts only below 60% of a
+ subscription window, and `normal` below 80%. Above that, only
+ `urgent` work and your chat with the coordinator go on. *Recommend:
+ these numbers*, revisited once Equipo has recorded readings.
+6. **Subscriptions that can overflow into paid credit** (OpenCode Go
+ into Console credit, a Mistral plan into pay-as-you-go). The gateway
+ stops such a connection at the first sign of paid billing, and treats
+ it as metered and capped whenever the provider gives no reading.
+ *Recommend:* also keep pay-as-you-go off (or the balance at zero) on
+ both accounts. Then the worst case is one refused request, not a
+ bill.
+7. **The coordinator stays on Claude and Codex.** The new connectors
+ take Engineering, Review and Ask, which is where tokens go.
+ *Recommend: yes.*
+8. **Order, and what is later.** *Recommend:*
+ 1. the gateway and caps;
+ 2. Pi on TensorX;
+ 3. the scheduler;
+ 4. Usage and advice;
+ 5. OpenCode Go;
+ 6. Mistral Vibe;
+ 7. the Command Code provider.
+
+ Mac runners, the Command Code CLI, coordinator cells and sign-in by
+ link are later designs.
## 1. Why, and the shape
@@ -60,797 +82,637 @@ advice on how to handle tokens", and "can I get connectors for my
Mistral, Pi, Opencode and Command Code subscriptions? … Pi I guess would
then use… my TensorX? But I don't want to run that down too much."
-Part A adds four harnesses behind the existing `provider.Launcher`
-contract, each with sign-in from the app, the Linux bubblewrap and Mac
-srt containment, a digest pin, honest usage readings and a row in the
-capability matrix. It adds hard spend caps for pay-per-token
-connections, enforced by the runner that owns the connection. Part B
-adds a deterministic scheduler on the runner that holds, routes or runs
-each step from recorded facts, and an advice function on the instance
-that turns the same facts into quiet cards. No model decides anything
-in either part; models only describe a task (as rev 3 §4 already has the
-coordinator do).
-
-What exists and is reused, not redesigned: connections, homes and
-`connect.Choose` (`internal/runner/connect/choose.go`); sealed secrets
-(`internal/sealbox`, rev 3 §2.4, built for Claude tokens); the egress
-relay, one bounded CONNECT to a public name on 443 per allowed host
-(`internal/runner/egress`); usage rows per attempt (`wire.Usage`,
-`chat_usage`); the step deferral (`stepDeferred` in
-`internal/runner/thin/engineer.go`); the housekeeping reservation ledger
-(`chat/housekeeping.go`); the policy and manifest digests
-(`internal/runner/provider/policy.go`, `check_policy.go`); and the pinned
-srt lockfile on the Mac (`internal/runner/mac`, every npm package by
-integrity).
+**Part A** adds three harnesses (Pi, OpenCode, Mistral Vibe) and four
+provider accounts behind them: TensorX, the Command Code Provider API,
+OpenCode Go and the Mistral plan. Every request goes through the
+runner's gateway, which makes spend caps hard and keeps every key out of
+the harness's namespace.
+
+**Part B** adds `schedule.Decide`, a pure function the runner uses to
+run, hold or route each step, and `advice.Compute`, a pure function the
+instance uses to turn the same recorded facts into quiet cards. No model
+decides anything; models only describe a task.
+
+**Reused, not redesigned:**
+
+- connections, homes and `connect.Choose`;
+- the sealed paste (`sealbox`, `seen_seals` and the delivery state
+ machine of rev 3 §2.4, built for Claude tokens);
+- the egress relay's public-address checks (`internal/runner/egress`);
+- usage rows (`wire.Usage`, `chat_usage`);
+- the step deferral (`stepDeferred` in `thin/engineer.go`);
+- the policy and manifest digests (`provider/policy.go`,
+ `check_policy.go`);
+- the committed-digest pinning of srt (`internal/runner/mac`).
# Part A: connectors
-## 2. What every connector must have
-
-A connector is one harness adapter, one sign-in kind, one containment
-profile, one pin, one usage parser, one fake CLI and one row in the
-matrix (§5). No harness earns a "yes" cell until it passes rev 3 §5's
-containment proofs in CI, with its fake, and once on staging with the
-real pinned binary:
-
-- proxy support through the relay, with no direct network;
-- the credential home unreadable from model tools;
-- shell absent in the read-only roles;
-- exactly the pinned MCP tools;
-- descendant termination when the namespace is killed.
-
-**Sign-in, never a terminal.** There are three kinds, all built or
-designed already:
-
-- (a) a **sealed paste** of an API key, into the rev 3 §2.4 sealed path
- as built for Claude tokens (`sealbox`, `seen_seals`, the delivery
- state machine), generalised from `KindToken` to `KindAPIKey` with an
- `endpoint` origin per provider;
-- (b) a **device code** relayed as a card, as Codex does;
-- (c) a **provider link whose one-time code comes back sealed**, as
- Claude's sign-in by a link does.
-
-The runner then makes one cheap authenticated request (a model list or
-a one-token call) before it reports `healthy`. A connector whose only
-subscription sign-in is a browser loopback on the runner's machine
-offers the API-key paste instead. A connector is never signed in by
-Equipo handling a provider's OAuth refresh token outside the
-provider's own CLI.
-
-**Containment, Linux.** Each connector runs in the existing bubblewrap
-namespace. It has the credential home mounted to the harness and denied
-to model tools, the runtime copy, no inherited environment, and pidfd
-termination proofs. The harness's own approval layer is set to "allow
-inside the namespace", because the namespace is the containment, as
-Codex's `danger-full-access` already is. Egress goes through the relay
-with an allowlist per provider host. `egress.ProviderPolicy` and
-`Policy.Hash` today accept only `claude` and `codex`. They become a
-table keyed by `(harness, provider)`, so a Pi connection to TensorX
-allows exactly `api.tensorx.ai`. Sign-in hosts are allowed only to the
-sign-in action, as `SignInPolicy` does for Claude. Every startup
-side-channel (update check, telemetry, model catalogue, package
-download) is switched off by flag or environment and then denied by the
-relay anyway. A connector whose hosts are undocumented starts its slice
-with a **host discovery probe**: the pinned binary on staging, with the
-relay in record-and-deny mode, a throwaway prompt, and the hosts it
-tried written down and reviewed. Only after that does the allowlist go
-into the policy table.
-
-**Containment, Mac.** srt 0.0.81 (pinned, Mac runners spec §4.4) with a
-profile of Equipo's own for each connector: `network.allowedDomains`
-set to the same host table, `filesystem.denyRead` set to the runner's
-state and every other connection's home, and writes only to the task
-tree and the attempt's scratch. This is new: today only Checks run under
-srt on a Mac, and Claude's own sandbox is trusted for Claude. Each
-connector on a Mac therefore needs the Mac spec's probe pattern
-(P2-style "denied" proven on every path) before its Mac cell turns
-yes. Linux comes first, and the Mac cells say "after probe".
-
-**Pinning.** Claude and Codex are pinned by the SHA-256 of the binary
-per architecture (`provider/claude/pins.go`, `codex/pins.go`). The new
-harnesses ship in three forms:
-
-- **npm** (Pi, OpenCode, Command Code): pinned as srt is, a committed
- `package-lock.json` with every package's `integrity`, installed by
- `npm ci --ignore-scripts` into a versioned directory with the pinned
- Node. The runner then records the SHA-256 of the installed tree's
- manifest (`provider.ManifestDigest` over a sorted file list and
- digests) and refuses to launch on any drift. Where the package pulls
- platform binaries (OpenCode), the binary's own SHA-256 is pinned too.
-- **PyPI** (Vibe): `uv pip install --require-hashes` from a committed
- lock into a versioned virtualenv, with a pinned `uv`-managed Python
- (SHA-256 of the archive). The same tree digest is taken at launch.
-- **A standalone release binary**, where one exists: SHA-256 per
- architecture, like Codex.
-
-Auto-update is switched off by flag, the install directory is mounted
-read-only, and the version check is denied by the relay.
-
-**Usage.** Each adapter maps its stream to `wire.Usage` rows (one per
-attempt and model, nullable figures, `complete` only when the final
-usage message was seen). Each reports headroom only as the provider
-reports it. "Not reported" is a state the Usage page shows in words,
-never a 0% or 100% meter.
-
-**Mapping to turns and steps.** The adapter's `Decode` turns the
-harness's stream into Equipo's events:
-
-- `delta` for assistant text;
-- `tool_call` for a tool request;
-- `tool_result` for its result;
-- `ask` for a permission the harness wants answered;
-- `usage`;
-- `done` with `completed | failed | interrupted`;
-- `limit` or `auth` failures for the classifier.
-
-These are the kinds the Claude and Codex adapters already produce
-(`provider/claude`, `provider/codex/events.go`). An event the adapter
-does not recognise is logged and dropped, never shown.
-
-**Model families.** The model map of rev 3 §4 (family, tier, price,
-`price_version`) gains the models these connectors serve. Review's
-`other_family` is judged on the model that actually ran, so one
-connector serving several families (Command Code, OpenCode Zen, Pi on
-TensorX) can review its own Engineering only with a different family.
-
-## 3. Command Code
-
-Command Code is a proprietary agent CLI, npm package `command-code`,
-1.88.5 on 2026-11-07, Node 22 or later, `UNLICENSED`. It has a hosted
-backend that sells credits under plans: Go $1, GOAT $10, Pro $20, Max
-$100 and $200 a month. Each plan has a monthly dollar allowance and
-5-hour and weekly caps, also in dollars. [CC1, CC4]
-
-- **Sign-in:** a sealed paste of a Command Code API key from Studio
- (kind (a)). Headless runs take `COMMAND_CODE_API_KEY`, which
- overrides saved credentials, and `cmd status` names the source in
- use. [CC3] `cmd login` uses a browser with a temporary loopback
- callback, the shape Equipo does not relay. Whether a Studio key draws
- on the plan or on pay-as-you-go credits is **unconfirmed** and is a
- Paul decision (§0). It is checked on first live use by `/usage`
- before and after one call, run by hand in Studio, not by Equipo.
-- **Containment:** `--yolo` inside the namespace for Engineering,
- because headless blocks writes and shell without it, and
- `--permission-mode plan` for Review. Its own rules
- (`permissions.deny` for `Shell(*)` and `Edit(*)`, and `disableBypass`)
- are written into the home's `settings.json` for Review as a second
- layer. [CC5] The hosts are **undocumented**: only
- `api.commandcode.ai` is named, and only for the separate Provider API.
- [CC6] The slice therefore starts with the host discovery probe. The
- side-channels are switched off with:
- - `DO_NOT_TRACK=1`, plus `"telemetry": false` in `config.json`;
- - `CMD_DISABLE_REMOTE_MODEL_CATALOG=1`;
- - `COMMANDCODE_SKIP_UPDATES` and `--no-auto-update`;
- - `CMD_ZDR=1`.
-
- It has no OS sandbox of its own. [CC5, CC6]
-- **Pinning:** npm lockfile by integrity. The registry gives a sha512
- `dist.integrity` and registry signatures, but no provenance and no
- release binaries. [CC1]
-- **Usage:** headless gives token totals on the final `result` line,
- with no named fields and no cost. [CC2] The plan's 5-hour and weekly
- meters exist only in the interactive `/usage` and on the Studio site.
- [CC4] So headroom is **not reported**. Exit 5 (rate limited) is
- `limited` with no reset and the rev 3 cool-off; exit 10 (out of
- credits) is `limited` until a probe succeeds, at most hourly; exit 3
- is `auth`. [CC2]
-- **Mapping:** `-p --output-format json` emits NDJSON. Only
- `tool_running` and the final `result {subtype, usage, finalText,
- sessionId, stopReason}` are documented. [CC2] That is too thin to map
- text, tool calls and results, or to relay a permission. The adapter
- therefore targets `cmd acp`, the Agent Client Protocol over stdio, as
- rev 3 already suggested. Its `session/update` notifications carry
- message chunks, tool calls and tool-call updates, and
- `session/request_permission` is a real relay. Whether Command Code's
- ACP mode reports usage and honours MCP servers is **unprobed**, and
- probe CC-P1 decides it. If ACP fails, Command Code gets Engineering
- and Review cells through `-p` only (no relay, final text only), and no
- coordinator cell.
-- **Families:** many. The default is `deepseek/deepseek-v4.1-flash`, and
- `-m` takes Anthropic, OpenAI, Gemini, xAI, DeepSeek, Qwen, Kimi, GLM
- and MiniMax models. [CC7] Equipo always passes `-m` and records the
- family from it. That makes Command Code useful for a cross-family
- Review of a Claude or Codex step, for example with GLM or Kimi.
-
-**One ACP adapter for two connectors.** Command Code (`cmd acp`) and
-Mistral Vibe (`vibe-acp`) both speak the Agent Client Protocol. Equipo
-therefore writes one `provider/acp` adapter, with one fake (`fakeacp`)
-and one permission relay (`session/request_permission` becomes an
-`ask_person` or a deny by policy, as Claude's `--permission-prompt-tool`
-does). Each connector adds only its pin, hosts, sign-in and usage
-reading. That is the same economy rev 3 sought with "one
-OpenAI-compatible harness".
-
-## 4. Mistral Vibe
-
-Vibe is Mistral's open-source CLI (Apache 2.0), 3.1.2 on PyPI
-(2026-11-10). The `vibe` command is now a Rust binary that drives a
-Python app server. [V1, V2]
-
-- **Sign-in:**
- - **Preferred:** a link, if probe V-P1 passes. The CLI's default
- browser sign-in is PKCE plus polling: it POSTs `{api_base}/vibe/sign-in`,
- opens a browser, polls, then exchanges. It ends with an API key, and
- nothing listens on localhost. [V3] So the unmodified CLI can run in
- a sign-in containment on the runner, as Claude's sign-in by a link
- does. `BROWSER` is set to a recorder, and the runner shows the URL
- as a card; Paul signs in on any device while the CLI polls. Nothing
- comes back through Equipo, which makes it closer to Codex's device
- code than to Claude's link. Whether the browser may be on another
- device is **unconfirmed**, and V-P1 is that check. The second, OIDC
- flow (loopback 127.0.0.1:8766) is off by default and stays off. [V4]
- - **Fallback**, and always offered: a sealed paste of a key from
- chat.mistral.ai/code/extensions. The docs say the key "works in Free
- mode, with a paid plan, or with pay-as-you-go enabled". [V5]
- Mistral's help centre says API automation should use a
- pay-as-you-go key rather than a plan key, which rev 3 §1.6 noted.
- Running the official CLI with the plan key is the use the plan
- covers. Using that key from Pi or OpenCode is not, and Equipo
- refuses it: a Vibe connection's key is mounted only into Vibe
- launches.
-- **Containment:** the home is `VIBE_HOME` (config, `.env`, logs). [V6]
- `config.toml` sets:
- - `enable_telemetry = false`, which also stops crash reporting;
- - `enable_update_checks = false`;
- - `outside_workdir = "deny"`. [V7, V8]
-
- Telemetry would otherwise post to `api.mistral.ai/v1/datalake/events`,
- and the Sentry host is unconfirmed. [V9] The runtime allowlist is
- `api.mistral.ai` only. The sign-in action adds the hosts V-P1 records.
- It honours `HTTPS_PROXY`. [V10] Engineering runs with `--auto-approve`
- inside the namespace, because headless denies anything that needs
- approval without it. Review runs with `--enabled-tools` set to the
- read tools and `permission = "never"` for write and bash. [V8]
-- **Pinning:** PyPI wheels with SHA-256 per platform (the Linux x86_64
- wheel of 3.1.2 is `f4318943…df235`), no signatures, no provenance.
- [V2] The install is `uv pip install --require-hashes` with a pinned
- Python 3.12 or later. The `vibe-acp` binaries are GitHub release
- assets with SHA-256 digests for 3.1.1, and 3.1.2 has none, so the
- adapter pins whichever version ships both the CLI wheel and a
- matching `vibe-acp`. [V11]
-- **Usage:** usage is not in the `streaming` output. `--output-dir DIR`
- writes `export.json` with token usage, cost and the outcome at the end
- of a run. [V12] The adapter reads it after exit, and `complete` is
- true only when the file is present and whole. For in-flight spend on
- a pay-as-you-go key, `--max-price` set to the reservation is the
- guard, and Vibe ends with exit 3 when it is reached. [V12]
- - **Headroom:** the plan's monthly usage is shared across Studio, the
- API and Vibe, and Mistral publishes no figures. [V13, V14] The app
- server reads `/v1/billing/budget` (`usage_percentage`,
- `initial_budget`, `reset_at`). That is visible in its source and
- undocumented. [V15] Probe V-P3 checks it with the connection's own
- key. If it works, it is the headroom reading, refreshed by the rev 3
- §2.7 probe at most every 15 minutes and labelled "from Mistral's
- billing". If it does not, headroom is "not reported".
-- **Mapping:** the target is ACP (`vibe-acp`). Without ACP it falls back
- to `-p --output streaming`, whose lines are completed history entries
- (`id`, `turnId`, `generationStatus`, `outcome`, tool calls as
- `type: "effect"`). The full schema is **unconfirmed**. [V16] The exit
- codes are 0 done, 1 config, 2 infrastructure, 3 limit (turns, tokens,
- price, time), 4 aborted. [V12] Exit 3 with `export.json` naming price
- is `spend_cap`. A 429 is `limited` with no reset.
-- **Families:** `mistral-large-4-0` and `mistral-medium-latest` are
- family `mistral`, and `zai-glm-5-3` and `-flash` are family `glm`.
- [V6] Vibe is the natural cross-family Review for Claude or Codex
- Engineering.
-
-## 5. Pi and OpenCode
-
-### 5.1 Pi, the harness for TensorX
+## 2. The metering gateway
+
+Rev 1 relied on harnesses reporting their own usage. Astra's first
+Critical finding showed why that is not enough: billing happens before
+the event arrives, and a harness can stay silent. So each metered or
+overflow-capable connection gets a gateway in the runner process,
+outside the namespace.
+
+**Shape.**
+
+- The gateway listens on a loopback port bound into the attempt's
+ namespace, the transport rev 3 §2.5 designed for local endpoints. The
+ harness's provider config points at `http://127.0.0.1:<port>/v1` with
+ a placeholder key.
+- The gateway forwards over TLS to exactly one upstream origin recorded
+ on the connection (`https://api.tensorx.ai`, `https://opencode.ai`,
+ `https://api.mistral.ai`, `https://api.commandcode.ai`). It resolves
+ that origin to public addresses only, with the relay's checks, refuses
+ redirects, and injects `Authorization: Bearer <key>`.
+- The key lives in the runner's state, never in the connection home, the
+ namespace, argv or an environment the harness can see.
+- These connectors get **no egress relay at all**. The gateway is their
+ only way out.
+
+**Allowed requests only.** A per-upstream table of method and path:
+
+- `POST /v1/chat/completions`;
+- `GET /v1/models`;
+- for Mistral, the budget read of §4;
+- for OpenCode Go, its inference paths.
+
+Anything else gets a 403 and a diagnostic line naming the method and
+path, with no bodies or headers logged. That removes the rev 1 problem
+of telemetry sharing an allowed host (`api.mistral.ai/v1/datalake/…`).
+Bodies are capped at 4 MiB.
+
+**Per-request reservation: the hard cap.** Before forwarding, the
+gateway:
+
+1. **Clamps the output.** It sets `max_tokens` (or
+ `max_completion_tokens`) to `min(requested, model limit, Equipo's
+ step limit)`.
+2. **Bounds the input.** It takes input tokens to be at most the body's
+ byte length, since a token is never shorter than a byte. That is
+ conservative and needs no tokenizer.
+3. **Prices the worst case.** `worst = in_bytes × in_price + max_tokens
+ × out_price`, using the connection's price table
+ (`price_version`).
+4. **Commits the reservation.** In one SQLite transaction in
+ `thin.db`, it checks `charged + Σ open reservations + worst ≤ cap`
+ for the day and the month, and writes a `gw_request` row
+ `{id, connection, attempt, worst, state: reserved}`. If the check
+ fails, the request gets a 429 with `x-equipo-reason: spend_cap`, and
+ the adapter classifies the attempt as failed with reason `spend_cap`.
+5. **Forces usage reporting.** It sets `stream_options.include_usage =
+ true` for streamed requests, then forwards.
+
+When the response ends, it reads `usage` (the final SSE chunk or the
+body). It charges `min(worst, priced usage)`, or the whole `worst` when
+usage is missing or malformed. The row becomes `charged` in one
+transaction.
+
+**What this proves.** A request is never sent unless its worst case
+fits. Committed money cannot be taken by another attempt, because every
+request reserves its own. The cap holds even when the harness
+under-reports or says nothing. It does assume Equipo's price table is
+right. A provider price rise is the one remaining gap, and it is closed
+by checking `/v1/models` pricing where the provider offers it and by the
+prepaid balance itself (TensorX).
+
+**Crash recovery.** At start, every `gw_request` in `reserved` is
+charged its `worst` and marked `charged_unknown`. It may have been
+billed, so it is never released as zero. No request is admitted until
+that sweep finishes. Request ids are the gateway's own, so a replayed
+usage event cannot charge twice.
+
+**Periods.** A request is charged to the day and month in which it was
+reserved, in the person's zone, UTC until one is known. A zone change
+takes effect at the next day boundary. A reservation made at 23:59 and
+charged at 00:01 stays in the old day.
+
+**Cap changes.** The instance sends a durable `caps{connection, day,
+month, revision}` frame. The new cap is effective on the runner when the
+frame is applied, which is the same transaction that acks it. Until the
+ack, the page shows "New cap applies when <runner> confirms". Requests
+already forwarded finish and are charged; nothing new is admitted over
+the new cap. Nothing is grandfathered beyond requests already sent.
+
+**Budget identity.** Charges belong to `(runner, provider, key
+fingerprint)`. The fingerprint is an HMAC of the key under a secret held
+only by that runner. Removing and re-adding the same key on the same
+runner keeps the day's and month's charges. The same key on two runners
+gets two caps, which the runner cannot see. The Usage page warns when a
+person has two metered connections to the same provider, and the
+provider's prepaid balance remains the outer bound. That limit is
+stated, not hidden.
+
+**Usage rows** come from the gateway, per request and per attempt.
+They are authoritative for these connectors. The harness's own usage
+events are recorded beside them only as a consistency check. The rows
+take the existing `wire.Usage` shape, with `cost_micros` and
+`price_version` added.
+
+**Headroom readings** are taken where the provider's responses carry
+them, because the gateway sees bodies and headers:
+
+- TensorX: `x-ratelimit-remaining-*`, per-minute rate limits, shown as
+ such and never as spend headroom;
+- OpenCode Go: `opencode.allowance` and `opencode.billing_source` in the
+ body;
+- Mistral: the budget read of §4.
+
+## 3. What every connector must have
+
+- **Sign-in is a sealed paste only.** The key goes into the rev 3 §2.4
+ path as built, generalised from `KindToken` to `KindAPIKey`, with an
+ `endpoint` bound to the upstream origin. The runner then calls
+ `GET /v1/models` through the gateway, and Paul picks the
+ connection's one model from the list on the connect card. A second
+ model is a second connection, which is enough without rev 3's
+ model-pair routing, still unbuilt. The connection is `healthy` after
+ one clamped one-token request. Sign-in by link and device code for
+ these providers are later designs.
+- **Containment (Linux).** The existing bubblewrap namespace, with the
+ connection home holding no secret, no relay and the gateway port
+ only, a runtime copy, no inherited environment, and pidfd
+ termination proofs. The harness's approval layer is set to "allow
+ inside the namespace", because the namespace is the containment.
+ Since the namespace holds no credential, a model tool that reads
+ everything it can reach finds nothing to steal (Critical finding 2).
+ **Isolated configuration:** each harness is started so that it loads
+ only Equipo's configuration. That means fixed config and home
+ directories, project-local configuration, extensions, plugins and
+ hooks disabled by flag or environment, and the effective-policy check
+ of `check_policy.go` extended to each harness. A hostile-repository
+ fixture (a project config, an extension, an `AGENTS.md` asking for a
+ tool) proves it.
+- **Pinning.** The expected digests are **committed per supported
+ platform**, as srt's tree digest is, not learned at install:
+ - npm trees (Pi, OpenCode): a committed `package-lock.json` installed
+ with `npm ci --ignore-scripts`, plus a committed SHA-256 over the
+ sorted list of every file path, mode and content digest, symlinks
+ included (a link must resolve inside the tree), and the platform
+ binary's own SHA-256 where there is one;
+ - the PyPI tree (Vibe): `uv pip install --require-hashes` from a
+ committed lock, a pinned Python, and the same committed tree
+ digest.
+
+ The launcher verifies the digest before every launch and refuses on
+ drift. The install directory is read-only, and update checks are off
+ by configuration. Even if one were not, the gateway allows no path
+ that could reach an updater.
+- **Mapping to turns and steps.** Each adapter's `Decode` yields
+ Equipo's existing event kinds: `delta`, `tool_call`, `tool_result`,
+ `ask`, `usage` (a consistency check only), `done` (`completed`,
+ `failed` or `interrupted`) and the failure classes. Unknown events
+ are counted and dropped, with type names only, never content.
+- **Families.** Each connection's model has a family. Review's
+ `other_family` is judged on the model that actually ran, so a Claude
+ step can be reviewed by GLM on TensorX, or by Mistral on Vibe.
+- **Acceptance**, per supported cell (connector × role), before the
+ cell turns yes, in CI with the fake and once on staging with the
+ pinned binary:
+ - the cap holds against a fake upstream that under-reports, omits
+ usage, or drops the connection mid-stream;
+ - a runner crash between reserve and charge is recovered;
+ - a cap lowered mid-attempt stops the next request;
+ - the hostile-repository fixture loads nothing;
+ - a model `cat` of every path it can reach finds no key;
+ - only the allowed paths pass the gateway;
+ - killing the namespace ends every descendant;
+ - Review has no write or shell tool.
+
+## 4. The connectors
+
+### 4.1 Pi on TensorX, and on the Command Code Provider API
Pi is `@earendil-works/pi-coding-agent` 1.5.2. The `@mariozechner`
package is deprecated. It needs Node 22.19 or later and has no install
scripts. [P1]
-- **Sign-in:** a sealed paste of the TensorX key (`tx-…`). [T1] The
- runner then calls `GET /v1/models` and makes a one-token completion,
- and it reports `healthy` with the model list. Pi's own `/login`
- subscription OAuth is not used, so no Claude subscription goes through
- a third-party harness.
-- **Containment:** `PI_CODING_AGENT_DIR` points at the connection's
- home. [P2] `models.json` declares `tensorx` with `baseUrl
- https://api.tensorx.ai/v1`, `api: openai-completions` and `apiKey:
- "$TENSORX_API_KEY"`. [P3, T1] The key reaches the launch through
- bubblewrap's `--args` pipe, never argv, exactly as Claude's token does
- (rev 3 §2.4, as built). The environment sets `PI_OFFLINE=1`,
- `PI_SKIP_VERSION_CHECK=1` and `PI_TELEMETRY=0`. [P4] The allowlist is
- `api.tensorx.ai`, and `pi.dev` and the catalogue host are denied. Pi
- has no permission layer at all. [P5] Gating is an extension of
- Equipo's (`-e`, hashed in the policy manifest) whose `tool_call` hook
- blocks or asks, as rev 3 §1.4 found. Review runs with `--tools
+- **Provider config:** `PI_CODING_AGENT_DIR` points at the home. [P2]
+ `models.json` declares one provider, `api: openai-completions`,
+ `baseUrl` the gateway, with a placeholder key. [P3] TensorX's API is
+ OpenAI-compatible (`https://api.tensorx.ai/v1`, keys `tx-…`). [T1]
+ The Command Code Provider API lives at `api.commandcode.ai/provider/v1`,
+ and its Claude models work only on its Anthropic-style `/messages`
+ route, which this design does not use. [CC6] That it serves the other
+ models on `chat/completions` is inferred, not documented. Probe CC-P1
+ checks it before S7, and if it fails, S7 is dropped.
+- **Switches:** `PI_OFFLINE=1`, `PI_SKIP_VERSION_CHECK=1` and
+ `PI_TELEMETRY=0`, with `--no-approve` for project trust. [P4] There
+ is no permission layer. [P5] Gating is Equipo's own extension (`-e`,
+ hashed in the manifest), and Review runs with `--tools
read,grep,find,ls`.
-- **Pinning:** a committed lockfile by integrity
- (`sha512-mUWI04rq…5yA==` for 1.5.2), `npm ci --ignore-scripts`, and
- the tree digest at launch. [P1]
-- **Usage:** `message_update` and `message_end` carry `usage {input,
- output, cacheRead, cacheWrite, totalTokens, cost{…, total}}`, and
- RPC's `get_session_stats` gives session totals. [P6, P7] The in-flight
- cap is charged per `message_end`.
- - **Headroom:** TensorX's `x-ratelimit-remaining-*` headers are
- per-minute rate limits, not spend, and neither Pi nor the CONNECT
- relay surfaces them. [T2] Headroom is therefore **not reported**,
- and the money cap (§6) is what limits TensorX. A 429 is `limited`
- for the rev 3 cool-off.
- - **Empty balance:** TensorX disables keys whose balance falls under
- $0.05, and they then fail as authentication errors. [T3] An `auth`
- failure on a TensorX connection that was healthy within the hour
- therefore reads "TensorX refused the key: the balance may be empty,
- or the key was revoked", state `sign_in_again`.
-- **Mapping:** RPC mode (`--mode rpc`). `prompt` starts a turn and
- `abort` stops it, but termination is always the namespace kill. The
- events map as:
- - `message_update` to `delta`;
- - `tool_execution_start` and `_end` (by `toolCallId`) to `tool_call`
- and `tool_result`;
- - `extension_ui_request` to `ask`;
- - `agent_end` to `done`. [P6, P7]
-
- Rev 3's probes P1 to P5 (100-turn session, relay, MCP pinning,
- credential-read denial, descendant termination) gate every cell.
-- **Families:** from the TensorX model id (`z-ai/glm-5.3` is `glm`,
- `moonshotai/kimi-k3.1-pro` is `kimi`, `deepseek/…` is `deepseek`,
- `minimax/…` is `minimax`, Qwen is `qwen`), with prices from TensorX's
- list (glm-5.3-flash $0.20 in and $0.50 out per million). [T1, T4]
-
-### 5.2 OpenCode: Paul's Go subscription, and Pi's fallback
+- **Mapping:** RPC mode. `message_update` is `delta`.
+ `tool_execution_start` and `_end` are `tool_call` and `tool_result`.
+ `extension_ui_request` is `ask`, and `agent_end` is `done`.
+ Termination is the namespace kill. [P6, P7] Rev 3's probes P1 to P5
+ gate every cell.
+- **Headroom:** TensorX has none beyond per-minute rate limits; it is
+ prepaid, and keys are disabled under a $0.05 balance, failing as
+ authentication errors. [T2, T3] So an `auth` failure on TensorX reads
+ "TensorX refused the key: the balance may be empty, or the key was
+ revoked". For the Command Code Provider API, headroom is not reported
+ headless; its plan windows appear only in Studio. [CC4]
+- **Families and prices:** from the model id (`z-ai/glm-5.3` is `glm`,
+ `moonshotai/kimi-k3.1-pro` is `kimi`, `deepseek/…` is `deepseek`) and
+ the provider's price list. [T4, CC7]
+
+### 4.2 OpenCode on OpenCode Go
OpenCode v2 is `@opencode/cli` 2.2.7. It has a `postinstall` script and
-platform binaries as optional dependencies. v1 `opencode-ai` 1.19.5 is
-the legacy major. [OC1] Paul's OpenCode subscription is presumably
+platform binaries as optional dependencies, so the platform binary is
+pinned by SHA-256. [OC1] Paul's OpenCode subscription is presumably
**OpenCode Go** ($10, Plus $40 a month): a dollar limit per model, with
the 5-hour limit at 20% of the monthly one and the weekly at 50%,
-serving GLM, Kimi, Qwen, DeepSeek, MiniMax and MiMo, plus Claude Haiku
-5.5, Gemini 4 Argon and GPT 6 Luna. [OC2] When a Go limit is reached,
-requests can fall back to Console credit, which is pay-as-you-go. [OC2]
-
-- **Sign-in:** a sealed paste of the key from opencode.ai/console. No
- environment variable name is documented, so the key is written into
- the home's credential store by `opencode auth login` run by the
- runner, reading stdin, as Codex's API key is. [OC3] Probe OC-P1
- checks that it works headless.
-- **Containment:**
- - `opencode serve --standalone --hostname 127.0.0.1 --port <fixed>`
- inside the namespace. Its loopback is the namespace's own, so the
- host's network never sees it. [OC4]
- - `XDG_CONFIG_HOME` and `OPENCODE_DB` point into the home. [OC5]
- - Config sets `update: "disable"` and a `permissions` list that ends
- in an explicit deny (the default base allows everything but
- `*.env`). Review gets explicit `edit` and `shell` denies. [OC6, OC7]
- - The runtime allowlist is `opencode.ai`, for `/inference/go/…` and
- `/inference/…`. [OC8]
- - The models.dev catalogue fetch, telemetry and share switches are
- **unconfirmed** in v2, so the slice starts with the host discovery
- probe. The relay denies `models.dev`, and the catalogue is seeded
- into the pinned tree.
- - The `openai-compatible` provider package is pre-installed in the
- pinned tree, because OpenCode would otherwise download it at
- runtime. [OC9]
-- **Pinning:** the lockfile by integrity
- (`sha512-qsSExDfp…LCg==` for 2.2.7), `npm ci --ignore-scripts`, and
- the platform binary's own SHA-256 pinned, since `postinstall` does not
- run. [OC1]
-- **Usage:** assistant messages and sessions carry `tokens {input,
- output, reasoning, cache}` and `cost` in USD, and `session.usage.updated`
- is an event. [OC4] Each Go response body includes
- `opencode.allowance` and `opencode.billing_source`, but there are no
- rate-limit headers or balance endpoint. [OC10] Whether OpenCode
- surfaces `allowance` in its events is **unconfirmed** (probe OC-P3).
- If it does, that is Go's headroom. If not, headroom is "not reported".
- `billing_source` matters for spend. A response billed to Console
- credit is metered, so the adapter records `overage: true` (rev 3 §6's
- field) and charges it against the connection's caps, when OpenCode
- surfaces it. When it does not, Paul's Console credit balance is the
- only guard (§0 decision 6).
-- **Mapping:** the `serve` HTTP API maps as:
- - `POST /api/session` and `/api/session/{id}/prompt` start the turn;
- - the SSE `GET /api/event` gives `session.text.delta` (`delta`),
- `session.tool.called` and `success` or `failed` (`tool_call` and
- `tool_result`), `session.step.ended`, `session.usage.updated` and
- `permission.asked` (`ask`);
- - `ask` is answered at `POST /api/session/{id}/permission/{requestID}/reply`.
- [OC4]
-
- It is a real relay. The cost is an HTTP server inside the namespace.
-- **Families:** many, read from the model id (`opencode-go/<id>`,
- `opencode/<id>`, `tensorx/<id>`). [OC2, OC11]
-- **As Pi's fallback for TensorX:** models.dev lists a `tensorx`
- provider (`TENSORX_API_KEY`, `@ai-sdk/openai-compatible`). [T5] If
- Pi fails its probes, the same TensorX connection gets
- `harness: opencode` and nothing else changes.
-
-### 5.3 The capability matrix, added rows
-
-| Connector | Coordinator | Engineering | Review | Ask | Headroom | Billing | Mac |
-|---|---|---|---|---|---|---|---|
-| Command Code over ACP | Not in this design | Yes, if CC-P1 passes; else `-p` with no relay | Yes, `plan` mode plus deny rules | Yes (`--resume` or an ACP session) | Not reported; exit 5 or 10 | Plan or credits, §0 decision 5 | After the srt probe |
-| Mistral Vibe over ACP | Not in this design | Yes | Yes | Yes | `/v1/billing/budget` if V-P3 passes, else not reported | Plan; a pay-as-you-go key is metered | After the srt probe |
-| Pi on TensorX (RPC) | Later (rev 3 P1 to P5 first) | Yes | Yes | Yes | Not reported; the money cap governs | Metered, capped | After the srt probe |
-| OpenCode on Go (serve) | Later | Yes | Yes | Yes | `allowance` if OC-P3 passes | Subscription, with an overflow risk | After the srt probe |
-| OpenCode on TensorX | Only if Pi fails | as Pi | as Pi | as Pi | as Pi | Metered, capped | After the srt probe |
-
-The coordinator stays on Claude and Codex in this design (§0
-decision 7). The new connectors take steps, which is where tokens go:
-Engineering, Review and the questions about them.
-
-## 6. Spend caps for pay-per-token connections
-
-A **metered** connection is an API key billed per token: Pi or OpenCode
-on TensorX, the Mistral API or OpenRouter, a Vibe or Command Code
-pay-as-you-go key. Paul's TensorX credit is prepaid and he does not want
-it run down.
-
-**The cap.** Each metered connection carries `caps {day, month}`, each
-`{limit, unit: money | tokens}`. Money is in the price table's currency
-(USD for TensorX), stored in micro-units. Day and month are in Paul's
-zone (UTC until one is known, as the Connections page does today).
-Paul sets the caps on the connection's row and on the Usage page. A
-metered connection is not usable until both caps are set. The connect
-card pre-fills them (§0 decision 3) and the connection becomes healthy
-on Save, so the setup is one tap, not a form.
-
-**Who enforces it.** A connection lives on exactly one runner, and every
-token it spends goes through that runner's harness. The runner is
-therefore the authoritative meter, and it enforces the cap even while
-the instance is unreachable. A `spend` ledger in `thin.db` holds
-reservations and charges per connection. It is written in one SQLite
-transaction with each admission, so two steps cannot both take the last
-dollar. The instance mirrors it for display only.
-
-**Four lines of defence:**
-
-1. **Admission.** A step or turn on a metered pair reserves its
- estimated `p90` cost (§7), priced by the model map's `price_version`.
- Without history it reserves the seed estimate. It is admitted only
- when the reservation fits under both the day and the month remaining.
- Otherwise it is held with reason `cap`.
-2. **In flight.** Every usage event the harness streams (Pi
- `message_end`, OpenCode `step_finish`, Vibe's per-message usage) is
- priced and charged as it arrives. When the charges reach the
- reservation and the cap's remainder is spent, the runner kills the
- namespace, waits for the termination proof, and ends the attempt
- `failed` with reason `spend_cap`. Engineering's partial tree is
- discarded, as on any failed attempt. A model response with no usage
- is charged at the worst case for that request (the context window's
- input plus the output limit Equipo set), so a harness that stops
- reporting cannot spend uncounted.
-3. **Harness limits**, where they exist: Vibe's `--max-price` set to
- the reservation, and Equipo's own `max_tokens` on every request where
- the harness takes a per-model output limit. These are a second
- barrier only; the runner's ledger is the rule.
-4. **Provider-side limits**, recommended to Paul and not relied on: a
- per-key credit limit where the provider offers one (OpenRouter does;
- TensorX's per-key limits are rate limits, not spend limits).
-
-**Reconciling.** A reservation is released only after the termination
-proof and the attempt's usage row (the housekeeping rule). An attempt
-with no usage figure is charged its whole reservation. Where the
-harness reports its own cost (Pi's `usage.cost`), the runner charges
-the larger of that and its own price-table figure, and records both.
-Lowering a cap stops new admissions at once. In-flight attempts may
-spend up to their reservation and no further.
-
-**Subscriptions first.** `schedule.Decide` (§8) offers a metered pair
-only when one of these holds:
-
-- **Spill:** no subscription pair is plausible for the step at its
- priority, and either the task is `urgent` (§0 decision 2) or Paul
- allowed metered use for this task. A `normal` or `low` task waits for
- the reset instead. A task whose `by` the wait would miss goes to Needs
- you with "I'd run it on TensorX" (§9), never to TensorX on its own.
-- **Cheap and short:** the step's `p90` cost is at most the
- connection's `cheap_job` threshold (default $0.02), its p90 duration
- is at most 10 minutes, and the role is Review, Checks triage or
- explore. This spends a few cents to save subscription room for
- Engineering. It is off until Paul turns it on (§0 decision 2).
-
-**The spend line on the Usage page.** It shows one row per metered
-connection, for example "TensorX: $0.84 today of $1 · $6.20 this month
-of $10", with a thin meter each and the words "estimated from tokens".
-TensorX and the Mistral API publish no usage API, and OpenRouter's key
-endpoint can later replace the estimate. Subscriptions show tokens,
-never dollars. A capped connection's row says "Paused until tomorrow" or
-"Paused until 1 Dec". The sidebar dot of rev 3 §6 also lights at 80% of
-any cap.
+serving GLM, Kimi, Qwen, DeepSeek, MiniMax and MiMo among others. On a
+limit it can fall back to Console credit. [OC2]
+
+- **Provider config:** a custom `openai-compatible` provider with
+ `baseURL` the gateway, its package pre-installed in the pinned tree
+ (OpenCode would otherwise download it). [OC3, OC9] The upstream is
+ `https://opencode.ai/inference/go`, with Go models served on chat
+ completions only in this design. [OC10]
+- **Switches:** `update: "disable"`, with `XDG_CONFIG_HOME` and
+ `OPENCODE_DB` in the home. [OC5, OC6] The permissions list ends in an
+ explicit deny, and Review gets explicit `edit` and `shell` denies.
+ [OC7] The models.dev catalogue, telemetry and share have no confirmed
+ v2 switches. With no egress but the gateway they cannot leave, and
+ probe OC-P1 confirms OpenCode starts and works without them.
+- **Driving it:** `opencode serve --standalone --hostname 127.0.0.1
+ --port <fixed>` inside the namespace. The SSE `GET /api/event` gives
+ text deltas, tool calls and results, and `permission.asked`, answered
+ at the reply endpoint. [OC4]
+- **Headroom and overflow:** the gateway reads `opencode.allowance` and
+ `opencode.billing_source` from each response body. [OC10] When
+ `billing_source` names Console credit, the connection becomes
+ `limited` at once, until the next Go reset, and the charged request is
+ recorded `overage: true`. So overflow costs at most the requests
+ already in flight, each within its worst case. Probe OC-P3 checks that
+ the fields are there. If they are not, the connection is metered and
+ capped.
+- **As Pi's fallback for TensorX:** the same gateway connection with
+ `harness: opencode`, if Pi fails its probes. [T5]
+
+### 4.3 Mistral Vibe on the Mistral plan
+
+Vibe 3.1.2 (PyPI, 2026-11-10) is Apache 2.0. `vibe` is a Rust binary
+driving a Python app server. [V1, V2]
+
+- **Provider config:** `VIBE_HOME` is the home. [V6] Its `mistral`
+ provider's `api_base` points at the gateway, whose upstream is
+ `https://api.mistral.ai`. [V6] The key is the plan key from
+ chat.mistral.ai/code/extensions, which the docs say "works … with a
+ paid plan". [V5] Mistral says plan usage is shared across Studio, the
+ API and Vibe. [V13] Probe V-P1 confirms that a custom `api_base` is
+ honoured for Mistral's own models.
+- **Switches:** `enable_telemetry = false`, `enable_update_checks =
+ false` and `outside_workdir = "deny"`. [V7, V8, V9] Engineering runs
+ `--auto-approve` inside the namespace. Review runs `--enabled-tools`
+ with the read tools only.
+- **Driving it:** `-p --output streaming` (completed history entries,
+ tool calls as `type: "effect"`), with `--output-dir` for
+ `export.json`. [V12, V16] The full line schema is unconfirmed (probe
+ V-P2). If it cannot be mapped, the Vibe cells stay No. Steps deny asks
+ by policy, so no permission relay is needed for Engineering and
+ Review.
+- **Headroom and overflow:** the gateway calls `GET
+ /v1/billing/budget` (`usage_percentage`, `initial_budget`,
+ `reset_at`) with the connection's key. That endpoint comes from Vibe's
+ source and is undocumented. [V15] It is called before a request when
+ the last reading is older than 5 minutes or at least 90%. At 100%,
+ the connection is `limited` until `reset_at`, so pay-as-you-go is
+ never reached through Equipo. If probe V-P3 shows the read does not
+ work, the connection is metered and capped at Mistral's API prices.
+- **Families:** `mistral-large-4-0` and `mistral-medium-latest` are
+ `mistral`, and `zai-glm-5-3` is `glm`. [V6]
+
+### 4.4 The capability matrix, added rows
+
+| Connection | Coordinator | Engineering | Review | Ask | Headroom | Billing |
+|---|---|---|---|---|---|---|
+| Pi → TensorX | No (later) | Yes, after the §3 acceptance | Yes | Yes | Rate limits only | Metered, hard cap |
+| Pi → Command Code Provider API | No | Yes | Yes | Yes | Not reported | Metered, hard cap (until §0 decision 2 shows it is plan) |
+| OpenCode → OpenCode Go | No | Yes | Yes | Yes | `allowance` (OC-P3) | Subscription; overflow stops it |
+| Vibe → Mistral plan | No | Yes, if V-P2 | Yes, if V-P2 | Yes (`--resume`) | Budget read (V-P3) | Subscription; 100% stops it |
+| OpenCode → TensorX | Only if Pi fails | as Pi | as Pi | as Pi | as Pi | as Pi |
+
+Mac cells are all "later". On a Mac, the gateway removes the credential
+from the harness, but srt profiles for these harnesses are their own
+design.
+
+## 5. Later, named so nothing is lost
+
+- the Command Code CLI as a harness, over ACP, with host discovery;
+- sign-in by link for Vibe;
+- coordinator cells;
+- Mac srt profiles;
+- token-denominated caps;
+- OpenRouter and local endpoints through the same gateway;
+- the "cheap and short" rule;
+- calibration of headroom in tokens;
+- advice about buying or swapping accounts.
+
+## 6. Spend on the Usage page
+
+Each gateway connection gets one line, for example "TensorX: $0.84
+today of $1 · $6.20 this month of $10", with a thin meter for each and
+"estimated from tokens and TensorX's prices". A request whose usage
+never arrived is counted at its worst case and marked "at most". A
+capped connection says "Paused until tomorrow" or "Paused until 1
+Dec". A pending cap change says it is pending. Subscriptions show
+tokens and the provider's own reading (Go allowance, Mistral budget),
+never a dollar figure. Rev 3 §6's sidebar dot also lights at 80% of any
+cap.
# Part B: token-aware scheduling and advice
-## 7. Facts the scheduler reads
-
-Everything is recorded before it is used. Nothing is read from a model's
-words at decision time.
-
-**Per connection** (runner, `thin.db`, mirrored to the instance as
-today): `kind` (`subscription`, `metered`, `local`), state, the
-headroom windows the provider reported (`used`, `resets_at`,
-`checked_at`), and for metered connections the caps and spend of §6.
-Unreported is null, never zero.
-
-**Calibration, per connection and window.** Providers report a
-percentage, steps cost tokens. The runner learns `w_per_pct`, the
-weighted tokens that moved a window by one percent. It uses two readings
-of the same window on the same connection, at most six hours apart and
-within one reset period, with every Equipo attempt between them
-`complete`. Weighted tokens are `input + cache_write + output +
-reasoning + cached_input / 10`. This is a unit for comparing steps
-against each other, not a claim about how providers meter. The runner
-keeps the median of the last 20 samples. Paul also uses these
-subscriptions outside Equipo, which only lowers a sample (more percent
-for the same Equipo tokens), so the calibration errs towards "less
-room". With fewer than 5 samples the calibration is `unknown`.
-
-**Per task:** `priority` (`urgent`, `normal`, `low`; default `normal`)
-and an optional `by` (a date). The coordinator may set `low`, `normal`
-and `by` on `record_task` and `start_task` from what the person said
-("no rush", "I need this by Friday"). Like rev 3 §4's size and risk,
-this describes the job and chooses nothing. **Only Paul's tap sets
-`urgent`**, because `urgent` is the one priority that may spend metered
-money (§6). This follows merge authority's rule that the coordinator
-can only tighten. The task page shows priority and `by`, and Paul
-changes them with one tap. A value the coordinator set is labelled "set
-from your message" until he does. Caps are never affected by priority.
-
-**Per step kind: the estimate.** The instance computes it from
-`chat_usage` rows with `complete` and `outcome = replied`, keyed by
-`(project, specialist, round = 0 | fix)`. It uses the last 20 rows, falls
-back to the same key across all the person's projects, and then to seed
-values (Engineering first pass 300k weighted, fix round 150k, Review
-100k, Checks 0) that data replaces after 5 rows. It sends `estimate {p50,
-p90, basis: project | person | seed, rows}` on `dispatch`, so the runner
-decides with the instance's history even when the instance is offline
-later. The size class, once rev 3 slice 3 lands, scales the seed only
-(small ×0.5, large ×2), never measured figures.
-
-## 8. The decision: `schedule.Decide`
-
-One pure function in `internal/schedule`, evaluated by the runner each
-time a step is admitted from its queue and again for every held step
-when a fact changes: a reset passes, a reading arrives, a step ends, a
-cap or preference changes, or Paul taps Run now. Its inputs are the
-facts of §7, the eligible pairs from `connect.Choose`'s filter
-(capable, usable, not avoided, the Review family rule), the open
-reservations and `now`. It returns `{action: run | hold, connection,
-model, reason, until, needs_person}`. A table test covers each rule and
-a property test covers the invariants below. The instance never
-re-decides; it shows what the runner reported, as it does for failover.
-
-**Room.** The room on a subscription connection for a step is the
-tightest reported window's `(1 − used − reserve) × 100 × w_per_pct`,
-less the open reservations on that connection. A step is **plausible**
-there when `room ≥ p90`. With calibration `unknown` the step is plausible
-when the tightest window's `used ≤ 1 − reserve − 0.1`. With no window
-reported at all (Command Code headless, Vibe), it is plausible when the
-connection is not `limited`, and the routing row says "headroom not
-reported". A reading older than 15 minutes is refreshed by the rev 3
-§2.7 probe before it counts, as housekeeping's stand-down already does.
-
-**The reserve ladder** is the core of "deciding what can wait". Each
-priority leaves part of every subscription window untouched:
-
-| Priority | Reserve kept free | Effect |
-|---|---|---|
-| `low` | 30% | runs on the first 70% of a window, then waits for its reset |
-| `normal` | 10% | stops short of the last 10%, which keeps the coordinator answering |
-| `urgent` | 0% | uses whatever is plausible |
-
-Person turns with the coordinator are never held for priority. They use
-the 10% the steps leave, and they still fail over and wait on
-`no_connection` as today. Housekeeping keeps its own stand-down (0.8 on
-the selected connection), which is stricter than `low`.
-
-**Order of rules**, the first that applies wins:
-
-1. **Hard bars.** Health, the Review family rule, and for metered
- connections the cap reservation of §6. Nothing overrides a hard bar,
- Run now included.
-2. **Override.** Paul tapped Run now: run on the eligible pair with the
- most room, ignoring the ladder and plausibility (reason `override`).
-3. **Subscription first.** Among subscription pairs where the step is
- plausible with its priority's reserve: stickiness, then preference,
- then the most room (rev 3 §3 order, reasons as today).
-4. **Local**, when a local endpoint is eligible and its tier meets the
- step's floor (rev 3 §4), reason `cheapest`.
-5. **Metered**, only as §6 allows (reason `metered_spill` or
- `metered_cheap`).
-6. **Hold.** No pair qualifies. `until` is the earliest reset among the
- eligible subscription pairs after which the step would be plausible,
- or null. The reason is `headroom` (naming that connection), `cap`, or
- `no_connection` (today's).
-
-**Release order.** When room returns, held steps are reconsidered in
-this order: `urgent`, then an earlier `by`, then `normal`, then `low`,
-oldest first within each. Each admitted step reserves its `p90` against
-the connection's room until it ends, so two steps never claim the same
-last room. Reservations live in one table and are written in one
-transaction with the admission, the shape of the housekeeping ledger.
-They are released after the termination proof and the attempt's usage
-row, and an attempt with no usage figure is charged its whole
-reservation.
-
-**Never start what cannot finish.** Rule 3's plausibility is the check
-before start. During a step nothing is cut short for headroom. A
-subscription that refuses mid-step is the existing quota failover
-(termination proof, fresh tree, another pair). Only a metered cap kills
-a step mid-run (§6).
-
-**Invariants**, each a property test over random facts:
-
-- Nothing is held while a plausible subscription pair exists for its
- priority.
-- A `low` step never takes a window past 70%.
-- A metered pair is never chosen when §6 forbids it.
-- The sum of open reservations never exceeds a connection's room at
- admission.
-- Run now never passes a hard bar.
-- The output depends only on the inputs: the same facts give the same
- decision.
-
-## 9. Holding, visibly, and Paul's override
+## 7. Facts
+
+All facts are recorded before they are used.
+
+**Connections:** state; the subscription windows as reported (`used`
+from 0 to 1, `resets_at`, `checked_at`), possibly several; the
+gateway caps and charges; `billing: subscription | metered`.
+
+**Tasks:**
+
+- `priority` is one of `urgent`, `normal` or `low`, and defaults to
+ `normal`.
+- `by` is an optional date.
+- The coordinator may set `low` or `normal`, and `by`, **only when it
+ creates the task** (`record_task`, `start_task`), from what Paul said.
+ Every later change, and every `urgent`, needs Paul's tap. This keeps
+ merge authority's rule: the model can describe, never loosen.
+- Values the coordinator set are labelled "set from your message".
+
+**Estimates**, computed by the instance from `chat_usage` and sent on
+`dispatch` (`estimate {tokens_p90, cost_p90_micros, duration_p90_s,
+basis, rows}`):
+
+- **Tokens:** a normalised sum of `input` (with cached input counted
+ once, using the per-provider rule `rowSpend` already applies),
+ `output` and `reasoning`, over complete, replied attempts.
+- **Cost:** from gateway charges on the same key.
+- **Duration:** from step start to end.
+- **Key:** `(project, specialist, first pass | fix)`, the last 20 rows.
+ It falls back to the person's same key across projects, then to seeds
+ (Engineering first pass 300k tokens and 20 min, fix round 150k and
+ 10 min, Review 100k and 5 min).
+- **Quantile:** nearest-rank p90. Fewer than 5 rows uses the seed.
+ Missing figures are skipped, and the row is counted only if it is
+ complete. All arithmetic is in int64 with overflow checks.
+
+The **subscription plausibility** of §8 uses windows, not token
+calibration. Calibration was cut (finding 18) and is in §5.
+
+## 8. `schedule.Decide`
+
+**Contract.** `Decide(in Input) Decision` is a pure function in
+`internal/schedule`. Its input is a versioned, immutable struct:
+
+- the step (role, priority, `by`, estimate, current binding, `avoid`,
+ per-task metered consent, `run_now` release id);
+- the person's connections on this runner, each with its capability for
+ the role, state, windows, billing kind, cap remainder, open margins
+ and family;
+- the role's preference and its `until`;
+- `now`.
+
+Probing a stale reading happens **before** the call, outside the
+function. The runner then calls `Decide` and, in the same `thin.db`
+transaction that writes the admission, revalidates that the inputs it
+read are unchanged (by row revisions). If they changed, it calls again.
+
+The output is `{run | hold, connection, reason, wake_at, needs_person}`.
+
+**Hard bars**, never overridden, Run now included:
+
+- the connection is usable (rev 3 §2.7 state);
+- the Review family rule;
+- not in `avoid`;
+- for a metered connection: the task is `urgent` or has Paul's metered
+ consent, and the cap remainder is at least the step's `cost_p90`;
+- for Ask: the exact session and connection that ran the step (rev 3
+ §3), so `Decide` is not called for Ask.
+
+**Subscription plausibility, by windows.** A step needs a **margin**
+of points of a window: Engineering 10, a fix round 5, Review 5. The
+priority's **reserve** is `low` 40, `normal` 20, `urgent` 0 (§0
+decision 5). A subscription connection is plausible for the step when,
+for **every** reported window:
+
+ used + open_margins + margin ≤ 1 − reserve
+
+`open_margins` is the sum of the margins of steps admitted on that
+connection **since that window's reading was taken**. A newer reading
+already includes their consumption, so a margin is dropped when a
+reading arrives whose `checked_at` is after the step's start, and is
+never double-counted (finding 19). A connection with no window reported
+is plausible when it is not limited, and the routing row says
+"headroom not reported". This is admission control, not a promise: a
+step may still run a window out, and then rev 3's quota failover takes
+over (finding 20). "Never start what cannot finish" holds as far as the
+provider's figures go, and the copy says so.
+
+**Order.** The first rule that yields a connection wins. Ties are
+broken by connection id.
+
+1. **Run now** (Paul's release): the usable connection with the most
+ room, ignoring the reserve and the margin. Hard bars still apply.
+ Reason `override`.
+2. **Sticky:** the current binding, if plausible. A failed attempt's
+ connection is in `avoid`, so failover goes through here too
+ (finding 15). Every new attempt, failover included, is admitted
+ through `Decide`.
+3. **Preferred:** the role's preferred connection, if plausible.
+4. **Subscription:** the plausible subscription with the lowest maximum
+ `used + open_margins` across windows. Known figures rank before
+ "not reported", then by id.
+5. **Metered:** the eligible metered connection with the largest cap
+ remainder. Reason `metered_urgent` or `metered_consent`.
+6. **Hold.** Reason `headroom` (naming the connection whose reset comes
+ first), `cap` or `no_connection`.
+
+**Wake-ups (finding 21).** `wake_at` is the earliest of:
+
+- every `resets_at` of every capable connection, limited ones
+ included;
+- the next cap period boundary;
+- the preference's `until`;
+- the moment `by` minus `duration_p90` is reached (the deadline
+ check).
+
+The runner persists `wake_at` with the hold and re-runs `Decide` then,
+and also on any fact change: a reading, a step end, a cap, a preference,
+or a release.
+
+**Release order:** `urgent`, then the earliest `by`, then `normal`,
+then `low`, oldest first within each. A held step never blocks a
+runnable step behind it, or a person's turn. Person turns are never
+held for priority.
+
+**Too big to ever run (finding 22).** When the step's `cost_p90` exceeds
+every metered connection's whole cap, and no subscription could admit
+it even at 0% used, the hold has `needs_person: true` and the reason
+`too_big`.
+
+**Housekeeping (finding 23).** Housekeeping's own ledger, reservations,
+`caused_by` and stand-down stay exactly as built. Its turns and retries
+are also `low` for the ladder, so the stricter rule wins. Housekeeping
+never uses a metered connection.
+
+**Invariants**, each a property test over random inputs:
+
+- (a) with no Run now, nothing is admitted that breaks the plausibility
+ inequality on any reported window;
+- (b) no metered admission without `urgent` or consent, Run now
+ included;
+- (c) no gateway request beyond the cap, whatever `Decide` said;
+- (d) a step is held only when no rule from 1 to 5 yields;
+- (e) the same input gives the same decision.
+
+## 9. Holds, Needs you, and Run now
A held step reports `step {state: deferred, hold {reason, connection,
-until}}`, an optional extension of today's deferred report. The task
-row and the task page say:
+wake_at}}`, an optional extension of today's deferred report. The task
+says one of:
-- "Waiting for headroom on Claude, resets Thu 10:00" (`headroom`, with
- `until`);
+- "Waiting for headroom on Claude, resets Thu 10:00";
- "Waiting for headroom on Claude" (no reset reported);
-- "Waiting: TensorX has reached today's cap" (`cap`).
-
-Each has one action, **Run it now anyway**.
-
-**Needs you stays clean.** A hold enters Needs you only when Paul's
-input would change the outcome:
-
-- the task has a `by` and `until` (or, with no `until`, now plus 24 h)
- falls after `by` minus the step's p90 duration;
-- no reset is in sight (`until` null, or more than 72 h away) and a
- metered pair could run it if Paul allowed it. Allow TensorX for this
- task is a per-task override, recorded, that still obeys the cap. A
- hold with a reset in sight stays quiet, even when TensorX could take
- it;
-- nothing at all can run the role (`no_connection`, today's card).
-
-The card asks with a recommendation, as the merge authority does
-(§4.1 there). The instance composes it from the hold:
-
-- "I'd wait: Claude resets Thu 10:00, before Friday." **Wait** /
- **Run now on Claude**
-- "I'd run it on TensorX: about $0.40, within today's cap." **Run on
- TensorX** / **Wait for Claude**
-
-**Run it now anyway** is `POST /api/v1/tasks/{id}/run-now`. It sends a
-durable `release{task, step}` frame, whose effect is rule 2 for that
-step's next admission only. A held coordinator turn is not something
-Paul sees here: person turns are never held for priority.
-
-## 10. Advice: quiet cards, computed, rate-limited
-
-`advice.Compute(facts, now) []Advice` is a pure function on the
-instance. It reads the mirrored connection facts, the open holds, the
-estimates, `chat_usage` and the routing rows. It runs on those events
-and at 08:00 in Paul's zone. Each advice has a `kind`, a `subject` and
-a stable key. The copy is fixed templates with slots, so no model turn
-computes or phrases it. The coordinator can read open advice through
-`status` when Paul asks how his tokens look. It cannot create, change or
-dismiss advice.
-
-| Kind | Fires when (all facts recorded) | Card | One-tap actions |
+- "Waiting: TensorX has reached today's cap".
+
+Each has the action **Run it now anyway**.
+
+**Needs you**, only where Paul's input changes the outcome:
+
+- the deadline check fires;
+- `too_big`;
+- no reset in sight (no `wake_at` from a reset, or one more than 72 h
+ away) while a metered connection could run it with consent;
+- `no_connection` (today's card).
+
+The card asks with a recommendation, composed by the instance, as merge
+authority §4.1 does: "I'd wait: Claude resets Thu 10:00, before Friday."
+**Wait** / **Run now on Claude**; or "I'd run it on TensorX: at most
+$0.40, within today's cap." **Run on TensorX** / **Wait for Claude**.
+
+**Run now (finding 12).** `POST /api/v1/tasks/{id}/run-now {step,
+step_revision}` is accepted from the task's owner only. It writes a
+durable `release{id, task, step, step_revision}` frame. The runner
+consumes the release **atomically with the admission it causes**. A
+release whose step revision is stale, or that was already consumed, is
+acked and ignored. Run now never grants metered consent; that is a
+separate per-task tap ("Allow TensorX for this task"), recorded with the
+person.
+
+## 10. Advice
+
+`advice.Compute(facts, now) []Advice` is pure, on the instance. It runs
+on fact changes and at 08:00 in the person's zone. The copy is fixed
+templates with slots, so no model turn computes or phrases it. The
+coordinator can read open advice through `status`, and cannot create,
+change or dismiss it. Every recommendation is checked for eligibility
+with the same capability, runner and family rules as `Decide`.
+
+| Kind (arbitration order) | Fires when | Card | Actions |
|---|---|---|---|
-| `prefer_switch` | the role's preferred subscription is past `normal`'s reserve with its reset more than 24 h away, another subscription has 50% room, and the queued steps' p50 fits in it | "Claude is near its limit until Thu. Codex has room. Prefer Codex for Engineering until then?" | **Prefer Codex until Thu** (a preference with `until`, which reverts by itself) / **Not now** |
-| `defer_tasks` | queued `normal` tasks without `by` have a p50 total above the room left before the reset, while `urgent` or `by` work is queued | "These 3 tasks would use most of Claude's week. Let them wait for Thu?" | **Make them low priority** / **Not now** |
-| `add_account` | in 14 days, steps waited on `headroom` for at least 8 h over at least 3 days, or one subscription was limited 3 or more times | "Work waited 19 h for Claude in the last two weeks. Another account would cover it." | **Add a connection** / **Not now** |
-| `swap_account` | a subscription has had no usage rows for 30 days while another was limited at least twice | "Vibe has not been used in a month while Claude ran out twice. Prefer Vibe for Review?" | **Prefer Vibe for Review** / **Not now** |
-| `cap_near` | a metered connection passes 80% of a cap | "TensorX: $0.84 of today's $1." | **Raise today's cap** / **Leave it** |
-
-**Never nags:**
-
-- at most one new advice card per person per day, and at most one open
- at a time;
-- a key Paul answered Not now stays silent for 14 days, and for 60 days
- after a second Not now;
-- advice whose facts stop holding is withdrawn silently;
-- quiet hours from 22:00 to 08:00, using housekeeping's `VisibleAt`;
-- never in Needs you, never a push notification.
-
-Cards show at the top of the Usage page and as one quiet card in the
-conversation, the receipt shape of merge authority §6.1. An action is a
-normal API call (preference, task priority, cap) recorded with
-`source: advice` and the key. Withdrawal and dismissal are rows in an
-`advice` table keyed `(person, kind, subject)`, which only moves forward
-like the housekeeping ledger.
+| `cap_near` | a gateway connection passes 80% of a cap | "TensorX: $0.84 of today's $1." | **Raise today's cap** / **Leave it** |
+| `prefer_switch` | the role's preferred subscription is past `normal`'s reserve with its reset more than 24 h away, another eligible subscription is below 50% on every window, and held or queued steps exist for the role | "Claude is near its limit until Thu. Codex has room. Prefer Codex for Engineering until then?" | **Prefer Codex until Thu** (a preference with `until`) / **Not now** |
+| `defer_tasks` | `normal` tasks without `by` are queued on a connection past 60%, while `urgent` or `by` work is held behind its reserve | "3 tasks could wait for Thu so the urgent one fits. Let them wait?" | **Make them low priority** / **Not now** |
+| `held_long` | a `low` task has been held for 7 days | "2 low-priority tasks have waited a week." | **Make them normal** / **Not now** |
+
+**Rules:**
+
+- Keys are `(person, kind, subject)`. The subject is the connection, the
+ role or the sorted task ids.
+- At most one new card per person per day, and at most one open at a
+ time. The arbitration order above picks which.
+- Not now silences a key for 14 days, and for 60 days after a second
+ Not now.
+- Advice whose facts stop holding is withdrawn silently.
+- Quiet hours are 22:00 to 08:00 (housekeeping's `VisibleAt`).
+- Never Needs you, never a push.
+- An action is the ordinary API call, revision-checked, recorded with
+ `source: advice` and the key.
+
+The `advice` table only moves forward, like the housekeeping ledger.
+Cards show at the top of Usage and as one quiet card in the
+conversation.
## 11. Wire, API and fixtures
-**Dispatch** gains `priority`, `by`, `estimate`, `metered_allowed`
-(the per-task override) and `run_now` (a release). **Step reports**
-gain `hold`. **Instance to runner:**
+**Dispatch** gains `priority`, `by`, `estimate` and `metered_consent`.
+**Step reports** gain `hold`.
-- `caps{connection, day, month, revision}` (durable);
-- `release{task, step}` (durable);
-- `preference` gains `until`.
+**Frames, instance to runner:** `caps` (durable, acked when applied),
+`release` (durable, consumed once), and `preference.until`.
-**Runner to instance:**
+**Frames, runner to instance:**
-- `connection` gains `kind: metered | local`, `spend {day, month,
- currency, estimated: true}` and `caps`;
-- `routing` reasons gain `override`, `metered_spill`, `metered_cheap`
- and `held`.
+- `connection` gains `billing`, `upstream` (origin only), `model`,
+ `spend {day, month, currency, pending_cap}` and `caps`;
+- `routing` reasons gain `override`, `metered_urgent`,
+ `metered_consent` and `held`;
+- `wire.Usage` gains `cost_micros`, `price_version` and `at_most`.
**API:**
- `PUT /api/v1/connections/{id}/caps`;
- `PUT /api/v1/tasks/{id}/priority {priority, by, revision}`;
- `POST /api/v1/tasks/{id}/run-now`;
-- `POST /api/v1/tasks/{id}/allow-metered`;
+- `POST /api/v1/tasks/{id}/metered-consent`;
- `GET /api/v1/advice`;
-- `POST /api/v1/advice/{id}/act|dismiss`;
-- `GET /api/v1/usage`, as rev 3 §6 with `spend` per connection.
-
-The tools `record_task` and `start_task` gain the optional `priority`
-and `by`. The protocol version is bumped, and an older runner is never
-sent the new fields. As merge authority does, older runners are refused
-metered dispatch: a runner without the cap ledger cannot hold a metered
-connection.
+- `POST /api/v1/advice/{id}/act`;
+- `POST /api/v1/advice/{id}/dismiss`.
-**Fixtures** under `wiretest/testdata`:
+`record_task` and `start_task` gain the optional `priority` (`low` or
+`normal`) and `by`. The protocol is bumped. As merge authority does,
+an older runner is refused rather than downgraded: it cannot hold a
+gateway connection or receive metered dispatch.
-- `api/connection-metered.json`, `api/caps.json`,
- `api/task-held.json`, `api/advice.json`;
-- `frames/caps.json`, `frames/release.json`,
- `frames/dispatch-estimate.json`, `frames/step-held.json`.
-
-The secret-field guard is extended to every new type.
+**Fixtures:** `api/connection-gateway.json`, `api/caps.json`,
+`api/task-held.json`, `api/advice.json`; `frames/caps.json`,
+`frames/release.json`, `frames/dispatch-estimate.json`,
+`frames/step-held.json`. The secret-field guard covers every new type,
+and `upstream` is an origin with no path or query.
## 12. Slices
-Each slice runs headless first (contracts, runner, a fake-CLI scenario
-green in CI), then on staging with the real pinned CLI, then UI, as
-rev 3 §8. Every connector slice opens with its probes, and a failed
-probe turns its cells to "No" with the reason; nothing is spun. **Sec**
-marks a slice that needs its own Astra round on its branch before merge.
-Sizes are agent days.
+Each slice runs headless first, then on staging with the real pinned
+binary, then UI. Each connector slice opens with its probes, and a
+failed probe turns its cells to No with the reason. **Sec** marks a
+slice that needs its own Astra round on its branch before merge.
| # | Slice | Finish line | Sec | Size |
|---|---|---|---|---|
-| S1 | Metered base: `KindAPIKey` sealed paste generalised from tokens, the egress host table keyed by harness and provider, the `spend` ledger, caps and the four defences of §6, the spend line | A fake metered step is killed at the cap with a termination proof, and the ledger, the usage row and the Usage line agree | **Sec** | 2 |
-| S2 | Pi on TensorX: pin, Pi profile in `policy.go`, the gating extension, `fakepi`, RPC adapter, rev 3 probes P1 to P5 | A real Review step runs on TensorX GLM under a $0.10 cap on staging and is recorded `other_family` | **Sec** | 3 |
-| S3 | Scheduler: `priority` and `by`, estimates on dispatch, `schedule.Decide` with the reserve ladder, holds with reason and `until`, release order, Run now, the Needs you rule | A `low` task shows "Waiting for headroom on Claude, resets …" past 70% and starts by itself after the reset, or at once on Run now | | 2.5 |
-| S4 | Calibration, the Usage page (availability, spend, tokens), advice and its rate limits | Each advice kind fires once from recorded fixtures, and Not now silences it for 14 days | | 2 |
-| S5 | OpenCode: Go subscription and TensorX fallback, `serve` adapter, host discovery, probes OC-P1 to OC-P3 | One real Engineering step on OpenCode Go on staging, with its usage row and no host outside the allowlist attempted | **Sec** | 2.5 |
-| S6 | The ACP adapter and Mistral Vibe: `fakeacp`, the link sign-in (V-P1) and the sealed key, `export.json` usage, V-P3 billing headroom | A real Vibe Review of a Claude step on staging, signed in from the app with no terminal | **Sec** | 3 |
-| S7 | Command Code over ACP: host discovery, CC-P1, the sealed Studio key | One real Command Code Engineering step on staging, or its cells marked No with the probe's reason | **Sec** | 1.5 |
-| S8 | Mac: an srt profile per connector and the P2-style denial probes | One Pi Review step on Tito Studio under srt, with denial proven on every path | **Sec** | 2 |
-
-The recommended order is S1, S2, S3, S4, S5, S6, S7, S8 (§0
-decision 8). S3 and S4 touch no credential and can run beside S1 and
-S2.
+| S1 | Gateway and caps: `KindAPIKey` sealed paste, the gateway (paths, clamping, worst-case reservation, charge, crash sweep, periods, budget identity), `caps` frame, spend line | Against a fake upstream that lies, goes silent, or dies mid-stream, and across a crash between reserve and charge, total charges never exceed the cap and every request is charged once | **Sec** | 3 |
+| S2 | Pi on TensorX: pins committed, isolated config, Equipo's extension, `fakepi`, RPC adapter, rev 3 P1 to P5, the §3 acceptance | A real Review step on TensorX GLM on staging under a $0.10 cap, recorded `other_family`, with the hostile-repository fixture loading nothing | **Sec** | 3 |
+| S3 | Scheduler: priority and `by` (creation-only for the coordinator), estimates, `Decide` with plausibility by windows, margins, holds, wake-ups, release order, Run now and consent, the Needs you rules | The five invariants pass as property tests, and a `low` task held at 61% starts by itself after the reset, or at once on Run now | | 3 |
+| S4 | Usage page (availability, spend, tokens) and the four advice kinds with their rules | Each kind fires once from fixtures, Not now silences it for 14 days, and no day shows two cards | | 2 |
+| S5 | OpenCode on Go: pins, isolated config, serve adapter, OC-P1 and OC-P3, the overflow stop | One real Engineering step on Go on staging, plus a recorded `billing_source` of credit turning the connection limited | **Sec** | 2.5 |
+| S6 | Vibe on the Mistral plan: PyPI pin, V-P1 to V-P3, the budget read and the 100% stop | A real Vibe Review of a Claude step on staging, with its budget reading on the Usage page | **Sec** | 2.5 |
+| S7 | Command Code Provider API behind Pi | One real Review step through the Command Code Provider API under a cap | **Sec** | 0.5 |
+
+S3 and S4 touch no credential and can run beside S1 and S2.
## 13. Risks
-- **Headroom stays best effort.** Three of the four new connectors
- report none headless. The scheduler treats "not reported" as "not
- limited" for plausibility, so on those connectors it holds nothing
- until a limit is hit, and failover does the rest.
-- **The calibration is a model.** Equipo has its own weighting, and
- Paul's outside use shares the windows. It errs towards holding, the
- invariants keep it from ever blocking `urgent` work on a subscription
- with reported room, and Run now is always one tap away.
-- **The relay cannot meter.** It is a CONNECT tunnel, so a harness that
- under-reports usage could spend more than Equipo counts. The
- worst-case charge for an unreported response and the whole-reservation
- charge for a silent attempt bound that.
-- **OpenCode Go can overflow into Console credit.** When OpenCode does
- not surface `billing_source`, Equipo cannot see that overflow, and
- the Console balance is the guard.
-- **Undocumented surfaces.** Command Code's hosts and stream, Vibe's
- billing endpoint, and OpenCode v2's switches are undocumented or
- unconfirmed. Each is a probe with a stated fallback, not an
- assumption.
-- **A third-party CLI holds a subscription key.** The Mistral plan key
- goes only into Vibe, and the OpenCode Go key only into OpenCode, so
- each subscription is used by its own vendor's client.
-- **Version drift.** Three npm trees and one Python tree to keep pinned
- means more upkeep. Each pin bump re-runs that connector's probes,
- as a Claude version bump rechecks its sandbox builder today.
+- **Headroom is the providers' word.** Plausibility rests on reported
+ windows. Without a reading, a subscription is not held until it
+ refuses, and failover handles the rest.
+- **Price tables are maintained by hand.** A provider price rise
+ between table updates is the one way past a cap. The prepaid balance
+ (TensorX), Paul's pay-as-you-go settings (§0 decision 6) and a
+ price-table check at connect bound it.
+- **The same key on two runners** has two caps (§2, Budget identity).
+- **Undocumented surfaces:** Mistral's budget read, OpenCode Go's
+ `allowance` fields and Vibe's line schema. Each is a probe with a
+ stated fallback that fails closed (metered and capped, or No).
+- **The gateway is a new trust boundary** in the runner. It is S1's own
+ Astra round, and it is small: one upstream per connection, fixed
+ paths, no redirects, no logging of bodies.
+- **Three more pinned trees to keep current.** Each bump re-runs that
+ connector's probes and acceptance.
## 14. Sources
@@ -903,3 +765,38 @@ such in the text.
- [T3] https://docs.tensorx.ai/billing.md
- [T4] https://tensorx.ai/pricing/
- [T5] https://github.com/anomalyco/models.dev/tree/dev/providers/tensorx
+
+## 15. Astra round 1, folded in
+
+Verdict on revision 1: NOT READY (full text in
+`CODEX-FINDINGS-CONNECTORS-SCHEDULING.md`). Each finding and where
+revision 2 answers it:
+
+| # | Finding, short | Revision 2 |
+|---|---|---|
+| 1 | Post-response usage cannot make a hard cap | §2: per-request worst-case reservation in the gateway before forwarding |
+| 2 | The harness's namespace exposes its credentials | §2, §3: keys stay in the runner, injected by the gateway; namespaces hold none. Mac cut (§5) |
+| 3 | An attempt could spend other attempts' reservations | §2: every request reserves its own worst case; `charged + open ≤ cap` |
+| 4 | No crash recovery for the ledger | §2: `gw_request` rows, start-up sweep charges unknowns in full, gateway-owned ids |
+| 5 | Lowering a cap is ambiguous | §2: effective on apply-and-ack, pending shown, only requests already sent finish |
+| 6 | Budget identity and period boundaries | §2: `(runner, provider, key HMAC)`, kept across re-add; period by reservation time; the two-runner limit is stated |
+| 7 | Overflow and mixed billing are post-hoc | §4.2, §4.3: stop on the first credit billing or the 100% budget; no reading means metered and capped. Command Code is metered until Paul confirms (§0 decision 2) |
+| 8 | New sign-in flows under-specified | Cut: sealed paste only (§3); link sign-in is later (§5) |
+| 9 | Host allowlists cannot block paths | §2: a path allowlist in the gateway, and no relay for these connectors |
+| 10 | A learned tree digest is not a pin | §3: committed digests per platform, full tree coverage and links |
+| 11 | Repository config can change the harness | §3: isolated configuration and the hostile-repository fixture |
+| 12 | Run now could bypass metered consent; release replay | §8 hard bars, §9: consent separate, release bound to the step revision and consumed once |
+| 13 | The coordinator could relax priority | §7: creation only, never `urgent` |
+| 14 | Depends on rev 3 slice 3, which is unbuilt | §3: one model per connection, prices in the gateway table, no tiers |
+| 15 | Stickiness and failover bypass admission | §8: every attempt goes through `Decide`, sticky before preference, Ask outside it |
+| 16 | Input contract and ordering incomplete | §8: versioned input, probing outside, revalidation in the admission transaction, id tie-break |
+| 17 | Estimates conflate tokens, cost and duration | §7: three estimates, normalised tokens, nearest-rank p90, int64 |
+| 18 | Calibration unsound | Cut (§5); plausibility by windows and margins |
+| 19 | Reservations against stale readings | §8: margins dropped when a newer reading arrives |
+| 20 | Invariants false as stated | §8: invariants restated as admission guarantees, with Run now excepted where it applies |
+| 21 | Wake-ups incomplete | §8: every reset, cap boundary, preference `until` and deadline check, persisted |
+| 22 | Starvation and impossible steps | §8: `too_big` to Needs you; §10 `held_long` |
+| 23 | Composition with housekeeping | §8: the ledger is unchanged, housekeeping is also `low`, never metered |
+| 24 | Advice arbitration and eligibility | §10: keys, arbitration order, eligibility checks; account advice cut |
+| 25 | Finish lines not adversarial | §3 acceptance per cell; §12 finish lines name the lies, crashes and hostile config |
+| Cut | "Cheap and short", token caps, OpenRouter, local, account advice | All in §5 |