# Equipo connectors and token-aware scheduling

Status: **revision 3.3, approved** (2026-11-12): §16, models chosen per
step, on Paul's question at the TensorX model picker. Astra's round on
the first draft said NOT READY (ten Important); §16 was revised to
answer them (§16.8) and the controller approved it as written, with
three notes folded in: the tier table is committed beside the price
tables and covers OpenCode Go too (§16.2), OpenCode's model is fixed
over ACP rather than by a bridge (§16.5), and S5b takes protocol 18
(§16.1). S5 (OpenCode on Go, protocol 17) is built and merged:
`S5-OPENCODE-PROGRESS.md`. Slice S5b builds this revision:
`S5B-MODELS-PROGRESS.md`. Revision 3.2 below is unchanged elsewhere,
except that §2.2's "one model per connection" is superseded by §16.

Revision 3.2: approved (2026-11-12, the controller's rulings
#7 and #8 on S3's review). S1 (metered connections), S2 (Pi on TensorX)
and S3 (the scheduler) are built and merged: `S1-METERED-PROGRESS.md`,
`S2-PI-PROGRESS.md`, `S3-SCHEDULER-PROGRESS.md`. S4 (Usage and advice)
builds on this revision. Ruling #7: Codex readings older than 15 minutes
are refreshed by `account/rateLimits/read` with no model turn, Claude's
stay as last reported, and every reading's age is shown (§6, §7, §12).
Ruling #8: a kept metered session whose step lost its leave to spend
starts afresh on a subscription, as built (§7 rule 1). Drafted by
Claude (Opus 5.5) on `connections-slice2-design` from main 1d7b4e4.

**History.**

- Revision 1 (732d7d6): Astra round 1 said NOT READY.
- Revision 2 (6591b33) added a metering gateway on the runner. Astra
  round 2 also said NOT READY, with a new Critical (the gateway did not
  bound request bodies) and an Important (no namespace transport for
  it). The full texts are in `CODEX-FINDINGS-CONNECTORS-SCHEDULING.md`
  and `-R2.md`.
- Revision 3, on the controller's direction, **cuts the gateway from
  v1**:
  - hard caps live at the provider;
  - Equipo keeps a soft budget from reported usage;
  - keys reach the harness as Claude's and Codex's credentials do;
  - scheduling decides admission from the readings taken at admission
    and claims nothing about what a step will go on to consume.

- Astra round 3, the last, on revision 3 (e9f1bc7): **READY WITH
  CHANGES**, no Critical. Its ten Important findings are folded into
  revision 3.1 (`-R3.md`, §15), with no further round.
- Revision 3.2 (2026-11-12) records the controller's two rulings on
  S3's security review (#7 reading freshness, #8 a kept metered session
  moving) and that S1 to S3 are built. Nothing else changes.
- S5 (OpenCode on Go, 2026-11-12) records the controller's ruling on
  its security round's finding 3: OpenCode's usage gap is accepted and
  stated (§2.3, §4.2, §12); reading OpenCode's own per-request rows is a
  follow-up slice.

§15 maps all three rounds' findings.

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. *Recommend: yes.*
2. **Command Code comes in as a provider behind Pi, for now.** You
   already use its models through Pi, and its Provider API is a plain
   API key. Its own CLI has undocumented hosts and output, so it is a
   later design. *Recommend: yes.* Please check in Command Code Studio
   whether Provider API calls draw on your plan's windows or on credits.
   Until then it counts as metered.
3. **The hard cap is the provider's, never Equipo's.** A metered
   connection is accepted only after you confirm, on the add-connection
   screen, that the key has a provider-side limit (§2.1 shows how for
   each provider). For TensorX that limit is the prepaid balance, so
   keep it at what you are willing to spend. A shell inside a step
   could use the key up to that limit. *Recommend: accept this.* The
   alternative, Equipo enforcing a hard cap itself, needs the gateway
   that failed two reviews (§5).
4. **Equipo's own budget is soft.** It is a daily and a monthly figure
   per metered connection. Equipo stops starting new steps when the
   **reported** spend reaches either. A metered connection runs one
   step at a time, so it can overshoot by at most one step, and the
   screen says so. *Recommend: $1 a day and $10 a month* as the
   pre-filled defaults.
5. **When does metered money get spent?** Only on tasks you mark
   `urgent` (your tap, never the coordinator's), or a step you release
   with "Run it now anyway". `normal` and `low` work waits for a
   subscription. *Recommend: yes.*
6. **The reserve thresholds.** A `low` step starts only while every
   reported window of a subscription is below 60%, and a `normal` step
   below 80%. `urgent` steps start on any connection that is not
   limited. The thresholds are the margin, because Equipo does not
   predict a step's consumption. *Recommend: these numbers.*
7. **Subscriptions that can bill overflow** count as metered unless you
   confirm on the add-connection screen that a **standing setting**
   turns overflow off. For a Mistral plan that setting is pay-as-you-go
   off. For OpenCode Go, a zero Console balance is a snapshot rather
   than a setting, and no overflow switch is documented, so Go counts
   as **metered** until you find one in the Console. *Recommend:* turn
   Mistral's pay-as-you-go off and confirm it; leave OpenCode Go
   metered until a switch is confirmed.
8. **The coordinator stays on Claude and Codex.** The new connectors
   take Engineering, Review and Ask. *Recommend: yes.*
9. **Order.** *Recommend:* metered connections and the budget, Pi on
   TensorX, the scheduler, Usage and advice, OpenCode Go, Mistral Vibe,
   then the Command Code provider. The gateway, Command Code's CLI and
   Mac are later (§5).

## 1. Why, and the shape

Paul, 2026-11-12: the coordinator should "prioritise tasks according to
token availability… deciding what can wait etc, and … proactively offer
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 three harnesses (Pi, OpenCode, Mistral Vibe) over four
accounts: TensorX, the Command Code Provider API, OpenCode Go and the
Mistral plan. The provider holds the hard cap, and Equipo keeps a soft
budget.

**Part B** adds `schedule.Decide`, a pure function on the runner that
starts or holds each step from the readings taken at admission, and
`advice.Compute`, a pure function on the instance that turns recorded
facts into quiet cards. No model decides anything.

**Reused, not redesigned:**

- connections, homes and `connect.Choose`;
- the sealed paste, with `sealbox`, `seen_seals` and the delivery state
  machine (rev 3 §2.4, built for Claude tokens);
- the token's delivery to the CLI, via a 0600 file outside
  model-readable paths and bubblewrap's `--args` pipe;
- the egress relay (`internal/runner/egress`), CONNECT to allowlisted
  public hosts on 443;
- usage rows (`wire.Usage`, `chat_usage`);
- the step deferral (`stepDeferred`);
- the policy and manifest digests;
- srt's committed-digest pinning.

# Part A: connectors

## 2. Metered connections

### 2.1 The provider's limit is the only hard cap

A connection is **metered** when its key is billed per token, or when it
is a subscription that can bill overflow and Paul has not confirmed that
pay-as-you-go is off. The add-connection screen for a metered connection
has one required confirmation, "This key has a spending limit at
<provider>", with a line and a link saying how, from the provider's
docs:

| Provider | The provider-side limit | Source |
|---|---|---|
| TensorX | The prepaid balance. Keys are disabled when it falls under $0.05. Keep it at what you are willing to spend. Whether TensorX has automatic top-up, and per-key spend limits, is not documented; check that no top-up is set. | [T3] |
| Command Code Provider API | A pay-as-you-go account has only its credit balance, and a plan has dollar caps per 5 hours and per week. Either is a limit, if auto-purchase of credits is off (not documented; check in Studio). | [CC4] |
| OpenCode Go | The Go plan's per-model limits, and then the prepaid Console credit that overflow draws on (top-ups carry a fee). The Console balance is the hard limit. It is a balance, not a setting, so Go stays metered (§0 decision 7). | [OC2, OC12] |
| Mistral plan | The plan's monthly usage. Overflow needs pay-as-you-go to be enabled, so pay-as-you-go off is the limit. | [V13] |

The confirmation is recorded with the person, the time and the provider.
Equipo cannot verify it, and the screen says so:

> "Equipo can't see this limit. It is the only thing that stops spending
> for certain: Equipo's own budget is checked between steps, and a step
> that is running can use this key up to the limit you set at
> <provider>."

**Why a step can use the key.** These harnesses have no sandbox of
their own for shell commands, unlike Claude Code's nested sandbox, which
keeps its token out of reach (rev 3 §2.4). A command a model runs is in
the same namespace and user as the harness, so it can read the harness's
environment and spend the key. It can spend it only at the provider's
host, because the relay allows nothing else. That is stated, not
mitigated, in v1. Keeping the key out of the namespace altogether is the
gateway, which is later (§5).

### 2.2 Delivery, as Claude and Codex credentials are delivered

- **Sign-in is a sealed paste only:** rev 3 §2.4 as built, generalised
  from `KindToken` to `KindAPIKey`, with `endpoint` the provider's
  origin. The key lands as a 0600 file in the connection's home,
  outside every path a model tool is given.
- **Each launch** gets the key as the harness's environment variable
  through bubblewrap's `--args` pipe, never in argv, a manifest or a
  record. The harness's config names that variable and never holds the
  key.
- **Egress** goes through the relay, allowed to the provider's host
  only: `api.tensorx.ai`, `api.commandcode.ai`, `opencode.ai`,
  `api.mistral.ai`. `egress.ProviderPolicy` and `Policy.Hash` become a
  table keyed by `(harness, provider)`. There is no other network.
- **Health (round 3, finding 10):** the runner, outside the namespace,
  calls `GET /v1/models` with the key, and Paul picks the connection's
  one model from the list on the connect card (superseded by §16: an
  allowed set, with the model chosen per step). A second model is a
  second connection, since rev 3's model-pair routing is unbuilt. The
  connection is `healthy` only after a **one-token completion** on the
  selected model (`POST …/chat/completions`, `max_tokens: 1`, at the
  provider's own path in §4) succeeds. That is the selected-model proof
  rev 3 §2.5 requires. It runs at connect and on Check again only, as
  Claude's token check does, never hourly. It is billable, so it is
  recorded as a usage row with role `probe` and charged to the budget
  like any other.

### 2.3 The soft budget

- **Figures.** Each metered connection has `budget {day, month}` in the
  price table's currency, with both required and pre-filled (§0
  decision 4). Day and month are in the person's zone, UTC until one is
  known.
- **Spend is what the harness reported (round 3, finding 5).** Each
  attempt's usage becomes **normalised billable components**:
  `uncached_input`, `cached_input`, `cache_write`, `output` and
  `reasoning`. `reasoning` is counted apart from `output` only where
  the provider's price-table entry says it bills separately; otherwise
  it is treated as included in `output` and not added. Per adapter:
  - **Pi:** `message_end.usage` is per request. The attempt's figure is
    the sum over its assistant messages, and it is `complete` when
    `agent_end` was seen.
  - **OpenCode:** whether `session.usage.updated` is cumulative or
    incremental is probe OC-P4. If cumulative, the attempt is the last
    total less the total at the attempt's start, as `CodexTally` does;
    if incremental, the sum. It is `complete` when the session went
    idle. As built (S5, over ACP, §4.2): the prompt's answer carries the
    turn's own sum over its requests (OC-P4), complete at that answer;
    a turn whose figure has no input at all is spend unknown. A request
    inside a turn that the provider answers without usage counts as
    zero in that sum, so a turn of several requests can be
    under-counted, and Equipo cannot see it through ACP (§12).
  - **Vibe:** one attempt is one run. It is `export.json`'s totals,
    `complete` when the file is present and parses.

  Price tables are versioned per connection: `{model, currency,
  micros per million for each component, price_version}`. Cost is
  int64 micro-units with overflow checks. A model with no price, or a
  component the table cannot price, makes the attempt's spend unknown
  (above). Where the harness reports its own cost (Pi `usage.cost`,
  OpenCode `cost`, Vibe's export), the larger figure is charged and
  both are recorded. `wire.Usage` gains `cost_micros`, `currency`,
  `price_version` and `cost_reported_micros`. Spend is charged to the
  day and month in which the attempt's usage row was recorded.
- **The ledger:** `budget_charge` rows in `thin.db`, keyed by the usage
  row's existing key `(turn, step, attempt, connection, model)`, so a
  resent row charges once.
- **One slot per metered connection (round 3, finding 1).** A metered
  connection has one durable `metered_slot` row in `thin.db`. Every
  attempt on it claims the slot in the same transaction as its
  admission, whatever it is: an Engineering or Review step, a question,
  a probe. Admission requires the slot to be free and `reported spend <
  budget` for both the day and the month. The slot is released only
  after the attempt's **termination proof** and either a committed
  charge or `spend_unknown`, in one transaction. Cancellation and
  failure take the same path.
- **Restart recovery.** At start-up, before anything is admitted, a
  claimed slot is reconciled:
  1. the attempt's namespace is recovered and killed, with the exit
     proven, as the existing recovery does;
  2. a usage row already committed is charged;
  3. otherwise the connection becomes `spend_unknown`;
  4. then the slot is released.

  The overshoot is therefore at most what one attempt spends, which the
  provider's limit bounds.
- **Unknown spend pauses.** An attempt that ends without a complete,
  priced usage figure marks the connection **"spend unknown"**, with a
  `pause_revision`. Nothing more is admitted to it until Paul taps
  Resume, after looking at the provider's dashboard. **Resume (finding
  3)** carries the `pause_revision` it saw. The runner consumes it
  atomically once, and only if that is still the current pause. A stale
  or repeated Resume leaves a newer pause in place.
- **Budget changes** take effect when the runner applies the durable
  `budget` frame. Until then the page shows "applies when <runner>
  confirms". A running step is not stopped by a change.
- **The screen** shows, for example, "TensorX: $0.84 today of $1 ·
  $6.20 this month of $10 · reported by Pi, can go over by one step",
  with "Paused until tomorrow", "Paused until 1 Dec" or "Spend unknown:
  check TensorX, then Resume".

## 3. What every connector must have

- **Isolated configuration.** Each harness loads only Equipo's
  configuration: fixed config and home directories; project-local
  configuration, extensions, plugins and hooks disabled by flag or
  environment; and `check_policy.go`'s effective-policy check extended
  to each harness. A hostile-repository fixture (a project config, an
  extension, an `AGENTS.md` asking for a tool) proves it.
- **Containment (Linux).** The existing bubblewrap namespace: the
  credential home mounted to the harness, the relay to the provider
  host only, a runtime copy, no inherited environment, pidfd
  termination. The harness's approval layer is set to "allow inside the
  namespace", because the namespace is the containment. Update checks,
  telemetry and catalogue fetches are switched off by configuration,
  and on a host other than the provider's they are also refused by the
  relay.
- **Pinning.** Expected digests are **committed per supported
  platform**, as srt's tree digest is:
  - npm trees (Pi, OpenCode): a committed `package-lock.json` installed
    with `npm ci --ignore-scripts`, plus a committed SHA-256 over every
    file's path, mode and content, symlinks included (each 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 tree digest.

  The digest is verified before every launch, and the install directory
  is read-only.
- **Mapping.** Each adapter's `Decode` yields Equipo's existing kinds:
  `delta`, `tool_call`, `tool_result`, `ask`, `usage`, `done`
  (`completed`, `failed` or `interrupted`) and the failure classes.
  Unknown events are counted and dropped, type names only.
- **Families.** Review's `other_family` is judged on the model that ran.
- **Acceptance**, per supported cell, in CI with the fake and once on
  staging with the pinned binary:
  - the hostile-repository fixture loads nothing;
  - only the provider host is reachable;
  - Review has no write or shell tool;
  - killing the namespace ends every descendant;
  - the budget stops the next step when the reported spend reaches it;
  - a step with no usage figure pauses the connection;
  - a resent usage row charges once.

  Unlike Claude's acceptance, there is **no** "a model `cat` finds no
  key" check, because §2.1 says it can. The test asserts the opposite
  plainly, so the statement stays true.

## 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]

- **Provider config:** `PI_CODING_AGENT_DIR` points at the home. [P2]
  `models.json` declares the provider as `openai-completions` with
  `apiKey: "$TENSORX_API_KEY"`, or Command Code's variable. [P3]
  - TensorX is OpenAI-compatible at `https://api.tensorx.ai/v1`. [T1]
  - Command Code's Provider API is at `api.commandcode.ai/provider/v1`,
    and its Claude models need `/messages`, which is not used. [CC6]
    That other models are served on chat completions is inferred. Probe
    CC-P1 checks it, and S7 is dropped if it fails.
- **Switches:** `PI_OFFLINE=1`, `PI_SKIP_VERSION_CHECK=1`,
  `PI_TELEMETRY=0` and `--no-approve`. [P4] Pi has no permission layer.
  [P5] Gating is Equipo's own extension (`-e`, hashed in the manifest),
  and Review runs with `--tools read,grep,find,ls`.
- **Mapping:** RPC mode. `message_update` is `delta`.
  `tool_execution_start` and `_end` are `tool_call` and `tool_result`.
  `extension_ui_request` is `ask`, `agent_end` is `done`, and
  `message_end.usage` gives `usage`, with `cost`. [P6, P7] Rev 3's
  probes P1 to P5 gate every cell.
- **Headroom:** none reported. TensorX shows only per-minute rate
  limits, and a key whose balance is under $0.05 fails as an
  authentication error. [T2, T3] Such a failure reads "TensorX refused
  the key: the balance may be empty, or the key was revoked".
- **Families:** from the model id (`z-ai/glm-5.3` is `glm`,
  `moonshotai/kimi-k3.1-pro` is `kimi`, `deepseek/…` is `deepseek`).
  [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, so the platform binary is
pinned by SHA-256. [OC1] Paul's 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%. On a limit it can
fall back to Console credit. [OC2]

- **Provider config:** a custom `openai-compatible` provider, its
  package pre-installed in the pinned tree, with the key in an
  environment variable it names. [OC3, OC9] The upstream is
  `https://opencode.ai/inference/go`, chat completions only. [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] Catalogue and telemetry switches are unconfirmed in v2. Probe
  OC-P1 checks that OpenCode works with only `opencode.ai` reachable.
  If the catalogue lives on `opencode.ai` too, its fetch is a known,
  stated leak of the model list request, not of data.
- **Driving it (round 3, finding 9):** `opencode serve --standalone
  --hostname 127.0.0.1 --port <fixed>` inside the namespace, on the
  namespace's own loopback, which the runner cannot reach. The control
  path is therefore an **in-namespace stdio bridge**: a small mode of
  the certified namespace helper (the binary that is already PID 1). It
  connects only to `127.0.0.1:<fixed>` inside the namespace, allows only
  the OpenCode paths the adapter uses (create session, prompt, the SSE
  event stream, the permission reply, abort), and relays them as framed
  JSON over the helper's stdio, which the runner already owns as the
  capture. Its mode, port and path list are part of the policy manifest
  and its hash, and it exits with the namespace. The SSE `GET
  /api/event` gives text, tool calls, results and `permission.asked`,
  answered at the reply endpoint. Usage comes from
  `session.usage.updated`. [OC4] If probe OC-P2 finds a stdio mode in
  OpenCode v2 (`acp`, unconfirmed), the bridge is not built.
- **Usage as built (S5).** OC-P2 found `opencode acp`, so S5 drives ACP
  and builds no bridge. ACP gives each turn's usage summed over its
  requests, with no per-request figure. In a turn with several
  requests, OpenCode reports a request without usage as zero, so the
  turn's spend can be under-counted, and Equipo cannot see this through
  ACP. The gap is accepted (the controller's ruling on S5's security
  round, finding 3) and stated on the Usage page for OpenCode's
  connections. The follow-up slice reads the per-request rows from
  `OPENCODE_DB` after the attempt (each request is one `assistant` row
  with its own tokens; one without usage has every token 0), and makes
  such a turn spend unknown.
- **Billing:** metered (§0 decision 7), unless Paul confirms a standing
  Console setting that disables overflow, which is undocumented today.
  Headroom is "not reported" unless probe OC-P3 finds the Go allowance
  in OpenCode's events.
- **Fallback:** if Pi fails its probes, a TensorX connection may use
  `harness: opencode`. [T5]

### 4.3 Mistral Vibe on the Mistral plan

Vibe 3.1.2 (PyPI, 2026-11-10) is Apache 2.0. [V1, V2]

- **Provider config:** `VIBE_HOME` is the home. [V6] The plan key, from
  chat.mistral.ai/code/extensions, "works … with a paid plan". [V5] It
  reaches the launch as `MISTRAL_API_KEY`, through the pipe.
- **Switches:** `enable_telemetry = false` (which also stops crash
  reports), `enable_update_checks = false` and `outside_workdir =
  "deny"`. [V7, V8, V9] Telemetry would otherwise post to
  `api.mistral.ai`, the one allowed host, so this switch, checked by the
  policy test, is what stops it.
- **Driving it:** Engineering runs `-p --output streaming
  --auto-approve`, and Review runs `--enabled-tools` with the read tools
  only. `--output-dir` gives `export.json` with usage and cost. [V12,
  V16] The line schema is unconfirmed: if probe V-P2 cannot map it, the
  cells stay No.
- **Headroom:** the runner, outside the namespace, may read `GET
  /v1/billing/budget` (`usage_percentage`, `reset_at`) with the key,
  rev 3 §2.7's probe at most every 15 minutes. That endpoint is from
  Vibe's source and undocumented. [V15] Probe V-P3 decides whether it is
  used. If not, headroom is "not reported".
- **Billing:** a subscription only if Paul confirms pay-as-you-go is
  off. Otherwise it is metered.
- **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 | Yes, after §3 acceptance | Yes | Yes | Not reported | Metered |
| Pi → Command Code Provider API | No | Yes, if CC-P1 | Yes | Yes | Not reported | Metered until §0 decision 2 |
| OpenCode → OpenCode Go | No | Yes | Yes | Yes | OC-P3, else not reported | Metered, unless a standing overflow-off setting is confirmed |
| Vibe → Mistral plan | No | Yes, if V-P2 | Yes, if V-P2 | Yes (`--resume`) | V-P3, else not reported | Subscription if pay-as-you-go is off, else metered |
| OpenCode → TensorX | No | only if Pi fails | as Pi | as Pi | as Pi | Metered |

Mac cells are all "later".

## 5. Later, named so nothing is lost

- **The metering gateway.** Its requirements, from Astra round 2:
  - a strict request schema per provider, forcing the priced model, a
    single completion and text-only input, rejecting unpriced features,
    and bounding every billable component;
  - a per-attempt socket bridge into the namespace, with fixed
    connection and attempt authority, lifecycle and policy attestation;
  - dialing the validated address without resolving again.

  It is the only route to a cap Equipo enforces, and to keeping the key
  out of the namespace.
- Command Code's own CLI (over ACP, after host discovery).
- Mac srt profiles.
- Coordinator cells.
- Sign-in by link or device code for these providers.
- Model-pair routing and tiers (rev 3 slice 3).
- Step estimates (tokens, cost, duration), the "too big" outcome, and
  calibration.
- The "cheap and short" rule, token-denominated budgets, OpenRouter and
  local endpoints.
- Advice about buying or swapping accounts.

# Part B: token-aware scheduling and advice

## 6. Facts

**Connections:** `state`; `billing` (`subscription | metered`); the
windows as reported (`used` from 0 to 1, `minutes`, `resets_at`,
`checked_at`); and, for metered connections, the budget, the reported
spend, `spend_unknown` and whether a step is running.

**Readings and their age (rev 3.2, ruling #7).** A Codex reading older
than 15 minutes is refreshed **before** `Decide` is called by the
app-server's `account/rateLimits/read`: no thread and no model turn,
run as the hourly refresh runs (the source home under its lock, the
same containment and egress), at most once per 15 minutes a
connection. Claude has no read without a model turn, so a **Claude
reading may be stale**: it is used as last reported, and a window past
its reset counts as not reported (§7). Every reading carries the time
the runner took it (`Headroom.checked_at`, protocol 15), and its age is
shown on the routing line of a step held for headroom and on the Usage
page's availability rows: "as of 2 h ago" for Codex, "as last reported
2 h ago" for Claude.

**Tasks:**

- `priority` is `urgent`, `normal` or `low`, default `normal`.
- `by` is an optional date.
- The coordinator may set `low` or `normal`, and `by`, **only when it
  creates the task**, from what Paul said. Every later change, and
  every `urgent`, is Paul's tap. That keeps merge authority's rule: the
  model can describe, never loosen.
- Values the coordinator set are labelled "set from your message".

## 7. `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`, `kept_session` (the connection whose
  session it resumes, or none), `avoid`, and `release` (a Run now id,
  or none);
- the person's connections on this runner, with the facts of §6 and
  each one's capability for the role and family;
- the role's preference and its `until`;
- `now`.

The output is `{run | hold, connection, reason, wake_at, needs_person}`.
The runner calls it at admission and writes the admission in one
`thin.db` transaction that rechecks the connections' row revisions it
read. If any changed, it calls `Decide` again.

**What it claims.** Admission is decided from the readings taken at
admission. It does not predict or reserve a step's future consumption,
and several steps admitted against the same reading may together run a
window out. The reserve thresholds are the margin. A window that runs
out mid-step is rev 3's quota failover (termination proof, then another
connection), as today. A Claude reading may be stale (§6): Codex's are
refreshed without a turn, Claude's are as last reported.

**Bars**, never overridden, Run now included:

- the connection is usable (rev 3 §2.7);
- the Review family rule;
- not in `avoid`;
- for a metered connection: the task is `urgent` or the step carries a
  release, no other step is running on it, spend is known, and the
  reported spend is under both the day and the month budget.

**Ask (round 3, finding 2)** never comes through `Decide` for its
choice: it stays on its step's exact session and connection (rev 3 §3).
On a metered connection, every question still passes the **metered
guard**: the slot, the day and month budget, and no `spend_unknown`,
all in the same admission transaction as a step. Consent is the
question itself, because Paul asking is his own action. A question the
guard refuses is held with the step's hold copy ("Waiting: TensorX has
reached today's budget"), never moved to another connection.

**Thresholds.** A subscription connection **admits** a step at priority
`p` when every reported window has `used < t(p)`, where `t(low) = 0.60`,
`t(normal) = 0.80`, `t(urgent) = 1.0` (only "not limited"). A
A connection with no window reported admits when it is not limited, and
the routing row says "headroom not reported". A window whose
`resets_at` has passed with no newer reading counts as not reported,
never at its old figure. A release (Run now) gives the step the
**effective priority** `urgent` for thresholds and metered eligibility,
and the bars still apply.

**Room, with a fixed precedence (finding 16).** Among subscription
connections that admit the step, the one with the most room is the
least by these keys, in order (round 3, finding 6):

1. connections with at least one reported window before those with
   none; the rest of the keys apply only between two connections that
   both have windows;
2. the largest `used` among its reported windows (lower is more room);
3. the `used` of its first window when its windows are sorted by
   `minutes` ascending (missing `minutes` sorts last), then by name;
4. the connection id, bytewise.

Among metered connections, the most room is the least by:

1. the larger of day and month spend as a fraction of its budget;
2. the connection id, bytewise.

A subscription always ranks before a metered connection. A preference
for a metered connection does not change that: it orders metered
connections first among themselves, in rule 4.

**Order of rules.** The first that yields a connection wins.

1. **Kept session (findings 15 and round 3, finding 4).** A step that
   resumes a kept session (a fix round on its Engineering session) stays
   on that connection, whatever the threshold, while it is usable. When
   a **spending bar** blocks it (busy slot, budget, spend unknown), the
   step is **held** on that connection, not moved. It switches only as
   rev 3 allows: a quota or auth failure (the connection is then not
   usable and is in `avoid`), Paul's explicit per-task "Run on …", or
   **spending permission withdrawn** (rev 3.2, ruling #8): a kept
   metered session whose step no longer has leave to spend (neither
   `urgent` nor a release) starts afresh on a subscription rather than
   being held on the metered connection. Reason `sticky`.
2. **Preferred.** The role's preferred connection, if it admits the
   step. Reason `preference`.
3. **Subscription.** The subscription with the most room. Reason
   `headroom`.
4. **Metered.** The metered connection with the most room. Reason
   `metered_urgent` or `metered_release`.
5. **Hold.** Reason `headroom` (naming the admitting candidate whose
   reset comes first), `budget`, `spend_unknown` or `no_connection`.

Every attempt, failover included, is admitted through `Decide`, with
the failed connection in `avoid`. A consumed release becomes a durable
**grant** for `(step, step_revision)`. It covers every attempt of that
step revision, failover attempts included, and ends when the step ends.
A second admission for the same step revision is refused by a unique
key, so a replayed release cannot start another execution.

**Wake-ups (round 3, finding 7).** `wake_at` is the earliest time
**strictly after `now`** among:

- every future `resets_at` of every capable connection, limited ones
  included;
- the next budget day or month boundary;
- the preference's `until`, while it is in the future (an expired
  preference is cleared and treated as absent);
- `by` minus 24 h, unless the deadline check has already fired for
  this step, which is recorded as `deadline_notified`.

When none exists, `wake_at` is null and only a fact change wakes the
step.

The runner persists it with the hold, re-runs `Decide` then, and also
on any reading, step end, budget change, preference change or release.

**Release order.** `urgent`, then the earliest `by`, then `normal`, then
`low`, then the oldest, then the step id. A held step never blocks a
runnable step or a person's turn. Person turns are never held for
priority.

**Housekeeping.** Its ledger, reservations and 0.8 stand-down stay as
built. Its turns and retries count as `low` for the threshold, so the
stricter rule wins, and it never uses a metered connection.

**Invariants**, each a property test:

- (a) no admission on a subscription with a reported, unexpired window
  at or above `t(effective priority)`, except a kept session;
- (b) no metered admission without `urgent` or a release;
- (c) never two attempts (steps, questions or probes) holding one
  metered connection's slot, and never a slot released before its
  attempt's termination proof and charge;
- (d) no metered admission once the reported spend reaches the budget,
  or while spend is unknown;
- (e) a hold only when rules 1 to 4 all fail;
- (f) the same input gives the same output.

## 8. Holds, Needs you, and Run now

A held step reports `step {state: deferred, hold {reason, connection,
wake_at}}`, an optional extension of today's deferred report. The task
says one of:

- "Waiting for headroom on Claude, resets Thu 10:00";
- "Waiting for headroom on Claude" (no reset reported);
- "Waiting: TensorX has reached today's budget";
- "Waiting: TensorX spend unknown, check it, then Resume".

Each has **Run it now anyway**, except `budget` and `spend_unknown`,
which offer **Raise the budget** and **Resume**.

**Needs you**, only where Paul's input changes the outcome:

- the deadline check fires (`by` minus 24 h with the step still held);
- no reset in sight (no reset-based `wake_at`, or one more than 72 h
  away);
- `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 it now**.

**Run now.** `POST /api/v1/tasks/{id}/run-now {step, step_revision}`,
from the task's owner only, writes a durable `release{id, task, step,
step_revision}`. The runner consumes it **atomically with the admission
it causes**. A release with a stale step revision, or one already
consumed, is acked and ignored. A release may use a metered connection
(§0 decision 5), and never passes a bar.

## 9. 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 is involved. The coordinator can
read open advice through `status`, and cannot create, change or dismiss
it. Each recommendation is checked with the same capability, runner and
family rules as `Decide`.

| Kind (arbitration order) | Fires when | Card | Actions |
|---|---|---|---|
| `budget_near` | a metered connection's reported spend passes 80% of a budget | "TensorX: $0.84 of today's $1." | **Raise today's budget** / **Leave it** |
| `prefer_switch` | the role's preferred subscription has a window at or above 0.80 with its reset more than 24 h away, another eligible subscription has every window below 0.50, and steps for the role are held or queued | "Claude is near its limit until Thu. Codex has room. Prefer Codex for Engineering until then?" | **Prefer Codex until Thu** / **Not now** |
| `defer_tasks` | `urgent` or `by` work is held on `headroom` while `normal` tasks without `by` are queued for the same role | "3 tasks could wait for Thu so the urgent one goes first. 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** |

**Deterministic choice (finding 24).** Each advice has the key `(person,
kind, subject)`:

- for `budget_near` and `prefer_switch`, the subject is the connection
  id (for `prefer_switch`, the role then the target connection id);
- for `defer_tasks` and `held_long`, it is the sorted task ids.

When several are eligible, the one shown is the least by: the kind's
arbitration order; then, within a kind, for connection subjects the
connection id bytewise, for roles the fixed order coordinator,
engineering, review, and for task sets the earliest task `created_at`,
then the first task id; then the key string bytewise.

**Rules:**

- At most one new card per person per day, and one open at a time.
- 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 and recorded
  with `source: advice` and the key.

The `advice` table only moves forward. Cards show at the top of Usage
and as one quiet card in the conversation.

## 10. Wire, API and fixtures

**`Connection`** gains `harness`, `upstream` (origin only), `billing`,
`model`, `limit_confirmed_at`, `payg_off_confirmed_at`, `budget`,
`spend {day, month, currency, unknown}` and `budget_pending`.
**`Dispatch`** gains `priority`, `by` and `release`. **Step reports**
gain `hold`. **`Headroom`** gains `checked_at` (rev 3.2, protocol 15;
dropped below it and from the runner's first hello).

**Frames, instance to runner:** `budget` (durable, acked when applied),
`release` (durable, consumed once), `preference.until` (durable) and
`resume_spend{connection, pause_revision}` (durable, consumed once).

**Routing reasons** gain `sticky`, `metered_urgent`, `metered_release`
and `held`.

**API:**

- `POST /api/v1/connections` gains `kind: api_key`, `sealed`,
  `limit_confirmed` and `payg_off_confirmed`;
- `PUT /api/v1/connections/{id}/budget`;
- `POST /api/v1/connections/{id}/resume`;
- `PUT /api/v1/tasks/{id}/priority {priority, by, revision}`;
- `POST /api/v1/tasks/{id}/run-now`;
- `GET /api/v1/advice`;
- `POST /api/v1/advice/{id}/act`;
- `POST /api/v1/advice/{id}/dismiss`;
- `PUT /api/v1/preferences` gains `until`.

`record_task` and `start_task` gain the optional `priority` (`low` or
`normal`) and `by`. The protocol is bumped, and an older runner is
refused metered connections rather than downgraded.

**Fixtures:** `api/connection-metered.json`, `api/budget.json`,
`api/task-held.json`, `api/advice.json`; `frames/budget.json`,
`frames/release.json`, `frames/step-held.json`. The secret-field guard
covers every new type.

## 11. Slices

Each slice runs headless first, then on staging with the real pinned
binary, then UI. Connector slices open with their probes, and a failed
probe turns a cell to No with the reason. **Sec** marks a slice that
needs its own Astra round on its branch.

| # | Slice | Finish line | Sec | Size |
|---|---|---|---|---|
| S1 | Metered connections: `KindAPIKey` sealed paste, the limit and overflow confirmations, the selected-model probe, the egress table keyed by `(harness, provider)`, normalised components and price tables, the budget ledger, the durable slot and its restart recovery, spend unknown with bound Resume, the metered guard for questions, the spend line | With a fake harness: the attempt after the budget is crossed is held; a concurrent Engineering, Review and question race admits exactly one; a crash between exit and charge ends in `spend_unknown` before anything else is admitted; a stale Resume leaves a newer pause; a resent usage row charges once; an unpriced model gives spend unknown | **Sec** | 2.5 |
| S2 | Pi on TensorX: committed pins, 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, recorded `other_family`, with the hostile-repository fixture loading nothing | **Sec** | 3 |
| S3 | Scheduler: priority and `by`, `Decide`, holds, wake-ups, release order, Run now grants with replay refusal, the Needs you rules, `preference.until` | The six invariants pass as property tests; a `low` step holds at 0.61 and starts by itself after the reset; a replayed or stale release starts nothing; a failover attempt inside a grant is admitted; no wake-up is ever in the past | | 2.5 |
| S4 | Usage page (availability, spend, tokens) and the four advice kinds | From fixtures, each kind fires once, ties pick the same card on every run, and Not now silences it for 14 days | | 2 |
| S5 | OpenCode on Go: pins, isolated config, the in-namespace stdio bridge (unless OC-P2 finds a stdio mode), serve adapter, OC-P1, OC-P3 and OC-P4 | A real Engineering step on Go on staging, with its usage row; the bridge refuses a path outside its list | **Sec** | 3 |
| S6 | Vibe on the Mistral plan: PyPI pin, V-P2 and V-P3 | A real Vibe Review of a Claude step on staging | **Sec** | 2 |
| S7 | Command Code Provider API behind Pi, after CC-P1 | A real Review step through it | **Sec** | 0.5 |

## 12. Risks

- **Claude readings may be stale (rev 3.2).** Claude reports headroom
  only on a model turn, so its reading can be hours old when `Decide`
  uses it. Codex readings are refreshed by `account/rateLimits/read`.
  Each reading's age is shown, so a stale one is visible.

- **A step can spend up to the provider's limit.** The key sits in the
  namespace, and the soft budget is checked only between steps. This is
  the trade Paul is asked to accept (§0 decision 3). The gateway (§5) is
  the remedy.
- **Reported usage can be wrong or missing.** Wrong usage misleads the
  soft budget. Missing usage pauses the connection.
- **OpenCode can under-count a turn (S5).** In a turn with several
  requests, OpenCode reports a request without usage as zero, so the
  turn's spend can be under-counted; Equipo cannot see this through ACP.
  The Usage page says so for OpenCode's connections. The follow-up slice
  reads the per-request rows from `OPENCODE_DB` after the attempt (§4.2).
- **OpenCode cannot see another model answering (S5b).** OpenCode's ACP
  usage names no model of its own, so a provider answering with a
  different model than the one fixed at launch is charged as the fixed
  model and the mismatch is not detected (§16.5). Pi is unaffected. The
  same follow-up slice, reading OpenCode's per-request rows from
  `OPENCODE_DB` after the attempt, closes it.
- **The confirmations are Paul's word.** Equipo cannot check a provider
  limit or a pay-as-you-go setting.
- **Thresholds are not predictions.** Concurrent steps can run a window
  out. Failover is the backstop.
- **Undocumented surfaces:** Command Code's chat-completions route, Go's
  allowance in events, Vibe's line schema and its budget read. Each is
  a probe whose failure turns a cell to No or headroom to "not
  reported".
- **Three more pinned trees** to keep current. Each bump re-runs that
  connector's probes.

## 13. Not claimed

- Equipo does not enforce a hard spend cap.
- It does not keep metered keys from a step's shell.
- It does not predict a step's consumption.
- It does not read provider headers or bodies.

## 14. Sources

Read 2026-11-12. Facts from source code rather than docs are marked as
such in the text.

- [CC1] https://registry.npmjs.org/command-code/latest, https://commandcode.ai/changelog
- [CC2] https://commandcode.ai/docs/headless
- [CC3] https://commandcode.ai/docs/quickstart, https://commandcode.ai/docs/settings
- [CC4] https://commandcode.ai/docs/resources/pricing-limits, https://commandcode.ai/docs/resources/usage-limits
- [CC5] https://commandcode.ai/docs/permissions, https://commandcode.ai/docs/resources/security
- [CC6] https://commandcode.ai/docs/provider, https://commandcode.ai/docs/troubleshooting/telemetry
- [CC7] https://commandcode.ai/docs/reference/cli/models
- [V1] https://github.com/mistralai/mistral-vibe
- [V2] https://pypi.org/pypi/mistral-vibe/3.1.2/json
- [V3] https://github.com/mistralai/mistral-vibe/blob/main/vibe/setup/auth/http_browser_sign_in_gateway.py (source)
- [V4] https://github.com/mistralai/mistral-vibe/blob/main/vibe/setup/auth/_oidc_config.py (source)
- [V5] https://docs.mistral.ai/vibe/code/cli/api-keys-profiles
- [V6] https://docs.mistral.ai/vibe/code/cli/configuration
- [V7] https://docs.mistral.ai/vibe/code/cli/configuration-reference
- [V8] https://docs.mistral.ai/vibe/code/safety-approvals-permissions
- [V9] https://github.com/mistralai/mistral-vibe/blob/main/vibe/core/telemetry/send.py, .../vibe/observability/sentry.py (source)
- [V10] https://github.com/mistralai/mistral-vibe/blob/main/docs/proxy-setup.md
- [V11] https://api.github.com/repos/mistralai/mistral-vibe/releases
- [V12] https://github.com/mistralai/mistral-vibe/blob/main/docs/programmatic-mode.md
- [V13] https://docs.mistral.ai/admin/billing-usage/subscriptions
- [V14] https://mistral.ai/pricing/
- [V15] https://github.com/mistralai/mistral-vibe/blob/main/vibe/app_server/_billing.py (source)
- [V16] https://github.com/mistralai/mistral-vibe/blob/main/vibe/cli-rust/src/headless_output.rs (source)
- [P1] https://registry.npmjs.org/@earendil-works/pi-coding-agent/latest
- [P2] https://github.com/earendil-works/pi/blob/main/packages/coding-agent/docs/configuration.md
- [P3] https://github.com/earendil-works/pi/blob/main/packages/coding-agent/docs/models.md
- [P4] https://github.com/earendil-works/pi/blob/main/packages/coding-agent/docs/environment-variables.md, .../docs/settings.md
- [P5] https://pi.dev
- [P6] https://github.com/earendil-works/pi/blob/main/packages/coding-agent/docs/json.md
- [P7] https://github.com/earendil-works/pi/blob/main/packages/coding-agent/docs/rpc.md, .../docs/rpc-commands.md
- [OC1] https://registry.npmjs.org/@opencode/cli/latest, https://registry.npmjs.org/opencode-ai/latest
- [OC2] https://opencode.ai/docs/console/go/
- [OC3] https://opencode.ai/docs/providers/
- [OC4] https://opencode.ai/docs/api, https://opencode.ai/docs/cli/
- [OC5] https://opencode.ai/docs/cli/config/, https://opencode.ai/docs/troubleshooting/
- [OC6] https://opencode.ai/docs/config/
- [OC7] https://opencode.ai/docs/permissions/
- [OC8] https://opencode.ai/docs/network/
- [OC9] https://opencode.ai/docs/providers/ (custom provider package)
- [OC10] https://opencode.ai/docs/console/api/inference/
- [OC11] https://opencode.ai/docs/console/models/
- [OC12] https://opencode.ai/docs/console/billing/
- [T1] https://docs.tensorx.ai/, https://tensorx.ai/
- [T2] https://docs.tensorx.ai/api-reference/rate-limits.md
- [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 rounds 1 and 2, folded in

Round 1 (revision 1) and round 2 (revision 2) both said NOT READY. The
dispositions below are for revision 3. Round 2 counted items 2 to 6, 9
to 13 and 20 to 23 resolved under the gateway. Those that depended on
the gateway are now cut or restated.

| # | Finding, short | Revision 3 |
|---|---|---|
| 1 | No hard cap from post-response usage | Not claimed (§13): the provider's limit is the hard cap (§2.1), and Equipo's budget is soft (§2.3) |
| 2 | The key is reachable from the namespace | Stated (§2.1), and the acceptance asserts it (§3); remedy later (§5) |
| 3 to 6 | Reservation, crash, cap change, identity | The gateway ledger is gone. The soft budget is keyed by usage rows, changes apply on ack, and periods follow the row time (§2.3) |
| 7 | Overflow billing | Metered unless Paul confirms pay-as-you-go is off (§2.1, §4.2, §4.3) |
| 8 | Sign-in flows | Sealed paste only |
| 9 | Paths on allowed hosts | Vibe telemetry is off by config, under the policy check; OpenCode's catalogue on its own host is stated (§4) |
| 10, 11 | Pins, isolated config | §3, unchanged from revision 2 (resolved in round 2) |
| 12 | Run now replay | §8: revision-bound, consumed atomically, refused on replay (S3 finish line) |
| 13 | The coordinator relaxing priority | Creation only, never `urgent` (§6) |
| 14 | Unbuilt rev 3 slice 3 | One model per connection; new fields named in §10 and assigned to S1 and S3 |
| 15 | Switching boundaries | §7 rule 1: kept sessions stay, as rev 3 binds them |
| 16 | "Most room" undefined | §7: a fixed key precedence for subscriptions and for metered connections |
| 17 | Estimates | Cut (§5) |
| 18 | Calibration | Cut (§5) |
| 19 | A reading after the step starts | Removed: admission uses only the readings taken at admission, and claims nothing further (§7) |
| 20 | Invariants | §7: restated for the new rules |
| 21 to 23 | Wake-ups, starvation, housekeeping | §7: wake-ups kept; `too_big` cut with the estimates; `held_long` kept; housekeeping unchanged |
| 24 | Equal-kind ordering in advice | §9: subject ordering defined |
| 25 | Adversarial finish lines | §3 acceptance and §11 finish lines name the budget, replay and hostile-config cases |
| R2 Critical | The gateway does not bound request bodies | Gateway cut (§5), requirement recorded |
| R2 Important | No namespace transport for the gateway | Gateway cut (§5), requirement recorded |

**Round 3 (revision 3): READY WITH CHANGES.** All ten Important
findings are folded into 3.1:

| # | Finding, short | Revision 3.1 |
|---|---|---|
| 1 | No durable lifecycle for the one-step bound | §2.3: a durable slot for every attempt, released after the proof and the charge; restart reconciliation; S1 race and crash cases |
| 2 | Ask bypasses the budget | §7: questions pass the metered guard and are held, never moved |
| 3 | Resume not bound to its pause | §2.3: `pause_revision`, consumed once |
| 4 | Kept session and release lifetime | §7: a spending bar holds a kept session; a release becomes a grant for the step revision |
| 5 | Cost accounting underspecified | §2.3: normalised components, per-adapter aggregation, versioned price tables, unpriced means unknown |
| 6 | Comparator and invariant | §7: known before unknown first, window ordering defined, effective priority, metered preference |
| 7 | Wake-ups in the past | §7: strictly future, expired preferences cleared, `deadline_notified`, expired readings not reported |
| 8 | A zero balance is not a setting | §0 decision 7, §2.1, §4.2: Go stays metered without a standing overflow-off setting |
| 9 | No OpenCode control transport | §4.2: an in-namespace stdio bridge in the certified helper, unless OC-P2 finds a stdio mode |
| 10 | Model list is not a credential proof | §2.2: a one-token completion on the selected model, charged as a `probe` |

The round 3 statuses it gave "NOT RESOLVED" for round 1 items (#4,
#7, #12, #15 to #17, #20, #21, #25) are these ten findings, and are
answered above.

## 16. Models chosen per step (revision 3.3)

Paul, at the Connect TensorX model picker ("Pick the model this
connection uses. Another model needs another connection."): "Surely the
co-ordinator or some other process would choose the model too, no?" He
is right. This section supersedes §2.2's "one model per connection" and
the connect-time model pick. It is its own slice, S5b, built after S5
and before Vibe. Everything else in revisions 3.1 and 3.2 stands.

Astra's one round on the first draft (a0fc42a) said NOT READY, with ten
Important findings. This text answers them (§16.8).

### 16.1 A connection is a key and an allowed set

- **The allowed set.** A metered connection is its key plus a set of
  allowed models. These are a subset of the models the key lists
  (`GET /v1/models`) that are both priced (§2.3) and tiered (§16.2).
  - A listed model with no price or tier is shown greyed with "No price
    yet", and cannot be allowed.
  - On the add screen, every model that can be allowed is ticked by
    default. Paul can untick any, but at least one must stay ticked.
  - The connection row says "Models: 9 of 10" and opens the same list.
- **Connecting (supersedes §2.2's pick).** The connection becomes
  `healthy` after the key is proven once. That proof is one charged
  one-token completion on the cheapest allowed model, run at connect as
  today. Every other allowed model starts `unprobed`.
- **Changing the set (finding 8).** A change is `PUT
  /api/v1/connections/{id}/models {allowed[], revision}`:
  - owner-only, with the actor taken from the session;
  - the roster checked in the write transaction, and audited;
  - delivered as a durable `models{connection, allowed[], revision}`
    frame, which replaces S1's `model` frame.

  Revisions rise by one per change, and the runner refuses any revision
  not above the one it holds. The runner applies the set in one
  `thin.db` transaction, then acks. Until the ack the page shows the
  pending set beside the applied one. `hello` and `sync` carry each
  connection's applied revision, so a reconnect sends the frame again
  if the runner is behind.
- **Removing a model.** A removed model is never admitted again. A step
  already running on it finishes.
- **Older runners.** S5b takes protocol 18. A runner below it is refused
  any change to the set. Its connections keep working with their one
  model, exactly as before, and the page says the runner needs an
  update to allow more models.

### 16.2 The model table (finding 10)

The model table is committed beside the price table. It gives a
`family` and a `tier` (`strong`, `standard` or `cheap`) per `(provider,
model)`, under its own version. Version `tiers-2026-11-12`, Equipo's
judgement from TensorX's prices and the models' public descriptions,
for review with this spec:

| Model | Family | Tier |
|---|---|---|
| `z-ai/glm-5.3` | glm | strong |
| `moonshotai/kimi-k3.1-pro` | kimi | strong |
| `moonshotai/kimi-k3` | kimi | strong |
| `deepseek/deepseek-v4-pro-0813` | deepseek | strong |
| `z-ai/glm-5.2` | glm | standard |
| `qwen/qwen3.8-27b` | qwen | standard |
| `deepseek/deepseek-v4.1-flash` | deepseek | standard |
| `z-ai/glm-5.3-flash` | glm | cheap |
| `deepseek/deepseek-v4-flash-0731` | deepseek | cheap |
| `minimax/minimax-m3.1-flash` | minimax | cheap |

- **OpenCode Go.** Its priced models (S5's `opencode-go-2026-11-12`
  table) are tiered in the same table and version, judged the same way
  from Go's prices and the models' public descriptions; the assignments
  are listed in `S5B-MODELS-PROGRESS.md` for review.
- **Where it lives.** The table is committed in the runner beside the
  price tables (`internal/runner/metered`), with its source date. The
  Usage page's source line names it beside the price date, so the
  tiers read as Equipo's own judgement.
- **Versions.** The tier table is keyed by model id, separately from a
  connection's pinned price version. A model allowed under one table
  that has no entry in a newer one stops being eligible, and the row
  says "No price yet".
- **Recording.** Every attempt records the model, family, tier,
  `price_version` and `tier_version` it ran under.
- **Tests.** A test fails if a priced model has no tier, or a tiered
  model has no price, in the current versions. The Usage page's source
  line names both tables' dates.

### 16.3 One ordered choice over connection and model pairs (findings 4 and 6)

`Decide` now ranks **pairs** of `(connection, model)` rather than
connections. A subscription connection is one pair, with its own model
as today. Each metered connection contributes one pair per eligible
model.

**Eligible models.** A model is eligible when it is allowed, its tier
and price exist in the current tables, and it is not `unhealthy`. An
`unprobed` model is eligible, and is probed on first use (§16.4).

**The fill and the tier cap.** A connection's fill is the larger of
reported spend ÷ budget for the day and for the month. The cap is
`strong` below 0.5, `standard` below 0.8, and `cheap` at or above 0.8.

**The model for a role on one connection.** `pickModel` takes the
eligible models and picks:

1. the highest tier that is at or below the cap;
2. if no allowed model is at or below the cap, the **lowest** tier
   present.

Within a tier, ties go to the lower output price, then the lower input
price, then the model id, bytewise. This is monotone: a higher fill
never yields a higher tier.

**Choosing the pair.** The order of rules is §7's, applied to pairs:

1. **Kept session.** A step resuming a kept session uses that session's
   connection and model while both are usable, allowed and not
   `unhealthy`. A spending bar holds the step; it never moves (§7
   rule 1, with ruling #8's switch for a withdrawn leave to spend).
2. **Preferred.** The role's preferred connection, with its
   `pickModel` model.
3. **Subscription.** As §7.
4. **Metered.** As §7, each metered connection with its `pickModel`
   model.

**Review across families.** For Review, one more key comes before all
of the order above:

- Pairs whose family differs from the family Engineering's attempt
  recorded (§16.5) rank first. Those whose family matches rank second.
- §7's order then applies within each group. That covers the kept
  session (never for Review), preference, subscription before metered,
  and room, and for Review it prefers a connection other than
  Engineering's at equal rank, as the scheduler does today.
- The labels stay as built: `other_family`, `same_family` and
  `same_account`.

For a metered connection, the family key takes the best other-family
model under that connection's cap, with the same tie rule. So Review of
a GLM step on TensorX runs Kimi or DeepSeek when one is allowed, and
GLM only when nothing else is.

**Questions (finding 5)** never go through the choice. A question
resumes its step's session, on that session's model. If the model has
since been removed or is `unhealthy`, the question fails with reason
`model_unavailable` and the card "That model is no longer allowed on
TensorX" or "That model is not answering". It never moves to another
model or connection. A question with no kept session does not exist
today, and is out of scope.

**Probes** target the model the step chose (§16.4). At connect, the
cheapest allowed model is probed (§16.1).

### 16.4 Probing a model on first use (findings 1, 2 and 3)

- **Admission covers the probe.** When `Decide` picks an `unprobed`
  model, the step's admission is made as usual. That means:
  - leave to spend, from urgent or a Run now grant for the step
    revision;
  - the budget;
  - the slot.

  Before the step itself launches, the admitted attempt runs the probe
  as its own durable sub-attempt, `probe:<step>:<attempt>:<model>`,
  charged as role `probe`. The probe must be answered by that model.
- **Then decide again.** When the probe settles (charged, or spend
  unknown), the slot is released and `Decide` runs again from fresh
  facts: budget, urgency, grant, allowed set and probe state. If the
  step is still admissible on that model, it launches under a new
  admission. If not (the budget is now reached, urgency withdrawn, or
  the model removed), it is held as §8 says.
- **Run now.** A Run now grant covers the step revision's probes and
  its attempts, and ends with the step, as built.
- **Failures:**
  - **Authentication** (401 or 403): connection-wide. The connection
    becomes `sign_in_again`, as today; no model is marked.
  - **Model not found, or answered by another model:** that model
    becomes `unhealthy`, with `failed_at` and the reason. `Decide` runs
    again without it.
  - **Spend unknown** (no usable usage): the connection pauses, as §2.3
    says. Nothing else is probed until Paul taps Resume.
- **Retries.** An `unhealthy` model becomes eligible again only on
  demand:
  - when Paul taps Check again, which probes each `unhealthy` allowed
    model under the normal budget bar, as Check again does today;
  - or when 24 hours have passed since `failed_at` and a step would pick
    it, in which case it is probed as on first use, under the same
    admission rules.

  No timer probes on its own.
- **After a step fails.** A `healthy` model whose step fails with
  model-not-found becomes `unhealthy` the same way.

### 16.5 What is bound and recorded (findings 7 and 9)

- **Attempts.** Every attempt records its model, family, tier,
  `price_version` and `tier_version` as immutable columns.
- **Sessions.** Kept sessions record the model and family they were
  created on. Engineering's family for Review is read from Engineering's
  attempt record, never from the connection.
- **Backfill.** Rows written before S5b are backfilled from the
  connection's one model, which was the only model it could run. A
  connection with no model selected gets no backfill, and its sessions
  (there are none) need none.
- **Migration** of connections:
  - with a selected model: the allowed set is `{that model}`, with that
    model's probe state as it is;
  - with none selected yet: the allowed set is every model that can be
    allowed, all `unprobed`, and the connection state unchanged;
  - refused or unvalidated: unchanged, with an allowed set of the
    selected model if there is one, and no invented probe results or
    times.
- **What Equipo guarantees about the model.** Equipo chooses the model,
  launches the harness with it, and checks that at launch:
  - **Pi:** `--model`, plus a `models.json` holding exactly that model,
    under the exact-config policy.
  - **OpenCode:** driven over `opencode acp` (S5's probe OC-P2), not
    an HTTP bridge. The exact-config policy pins the one provider and
    model in `opencode.json` and holds the launch's selection to it at
    attestation. The adapter checks the ACP session's model option is
    that model when the session is created or loaded and again before
    every prompt, never sends a request that sets a model or a config
    option, and refuses to go on (an identity failure) once OpenCode
    reports the model option changed.

  Equipo does not claim more. During an attempt, a harness's writable
  runtime configuration, or a step's shell holding the key (§2.1),
  could reach another model at the provider. So the usage rows record
  the model the provider reported. If that differs from the chosen
  model, the row is marked `model_mismatch` and charged at the reported
  model's price, or spend is unknown if that model is unpriced.
  `model_mismatch` makes the chosen model `unhealthy` for this
  connection until Check again.

  **OpenCode's gap (the controller's ruling on S5b's security round,
  finding 7).** Pi reports the model of each request, so the rule above
  holds for Pi. OpenCode's ACP usage carries no model of its own: a
  provider answering with another model than the one fixed at launch is
  charged as the fixed model, and the mismatch is not detected. This is
  accepted and stated (§12). The follow-up slice that closes it reads
  OpenCode's per-request rows from `OPENCODE_DB` after the attempt,
  which closes the under-count gap too (§4.2).

### 16.6 Invariants (property tests)

- (a) The chosen model is allowed, priced, tiered and not unhealthy.
  Kept sessions are the exception: they use their own model under rule
  1's conditions, which imply the same.
- (b) For Review, a pair whose family differs from Engineering's
  recorded family is chosen whenever any eligible one exists on any
  eligible connection.
- (c) At equal inputs except fill, a higher fill never yields a higher
  tier.
- (d) A question uses its session's model or fails `model_unavailable`;
  it never runs on another model.
- (e) The same input gives the same pair.
- (f) No harness is launched with a model other than the chosen one.
- (g) A probe never runs without the admission its step would need, and
  a step never launches on a model whose first-use probe has not
  settled healthy.

### 16.7 Slice S5b

| # | Slice | Finish line | Sec | Size |
|---|---|---|---|---|
| S5b | Allowed sets and their protocol, migration and backfill, the tier table, `pickModel` and pairs in `Decide`, first-use probes inside admission, unhealthy models and their retries, `model_unavailable`, `model_mismatch`, the add screen and row, and the model shown on steps and Usage | With fakes: a first Engineering pass probes, then runs the strongest allowed model; at 0.8 fill the next pass runs a cheap one; Review of a GLM step runs Kimi; with Kimi and DeepSeek unticked, Review runs GLM labelled same family; a question whose model was unticked fails `model_unavailable`; a probe answered by another model marks it unhealthy and the step runs on the next pick; a migrated single-model connection behaves exactly as before; an older runner is refused a set change | **Sec** (it sets what is spent) | 2.5 |

### 16.8 Astra on the first draft, folded in

| # | Finding, short | Here |
|---|---|---|
| 1 | Probe admission lifecycle | §16.4: a sub-attempt inside the step's admission; decide again after it settles; Run now grants cover probes |
| 2 | Probe target and bootstrap | §16.1 connect-time proof on the cheapest model; §16.3 and §16.4 first-use probes target the chosen model; §2.2's pick superseded |
| 3 | Retries and failure states | §16.4: `failed_at`, demand-driven retries, authentication connection-wide, spend unknown stops |
| 4 | Review chose the connection first | §16.3: one ordered choice over pairs, family first for Review, labels kept |
| 5 | Questions and removed models | §16.3, §16.6(d): `model_unavailable`, never moved |
| 6 | Fallback broke monotonicity | §16.3: the lowest tier present, so the rule is monotone |
| 7 | "Never chooses itself" overstated | §16.5: claims limited to choice and launch; `model_mismatch` recorded and charged |
| 8 | The models protocol | §16.1: monotonic revisions, applied then acked, reconcile on reconnect, owner-only, older runners refused |
| 9 | Session and migration identity | §16.5: immutable bindings, backfill, migration per connection state |
| 10 | No actual tiers | §16.2: the initial table and its version rules |
