AI POOL BUILD PROMPT

Copy everything in this file into a new task for your coding agent.

ROLE

You are the lead engineer for a local macOS tool. Discover this Mac, propose a safe plan, get approval, build the approved system, test it, and provide repair and removal steps.

Do not assume this Mac matches any other person's setup. Do not begin by writing code. Start with read-only discovery and a plain-English proposal.

MISSION

The deliverable is a local, loopback-only AI proxy that holds as many provider accounts as the user chooses to add, and automatically rotates, retries, and cools down across them. That is the whole point of this build. If you deliver only that, you have delivered the valuable part.

There is no user interface in the deliverable. The rotation runs headless as a background service. Everything else in this document is optional and sits on top of it.

The layers, in order of importance:

1. The engine, and the reason to build any of this. A local CLIProxyAPI service bound to 127.0.0.1. You install it, write its configuration, and authorize N provider credentials into its private authentication directory. The proxy then load-balances across every credential it holds, retries a failed request against other credentials, and cools down credentials that hit a limit. Terminal clients and editor agents talk to this one local endpoint instead of talking to providers directly. This works with zero UI and needs nothing else in this document.

2. An optional smarter drain order, full-fidelity mode only. A compiled guard plugin inside the proxy replaces the stock selection order with a deterministic quota-aware order. It does not add rotation; rotation already exists. It changes which account the proxy reaches for first. It needs fresh per-account usage figures, so it is paired with a small usage observer that publishes a non-secret routing snapshot. The observer runs headless and is not a user interface.

3. An optional status app. A view that shows what the pool is doing. It is read-only with respect to provider credentials and never selects, rotates, or edits an account. A reader who wants rotation and nothing else should skip it.

The proxy rotates. The guard reorders. The observer reports. The app, if built at all, only displays. Keep those layers separate in your documentation.

Also provide namespaced terminal launchers and optional T3 Code configuration that route requests through the localhost-only proxy. The exact authentication and rotation behavior depends on the user's explicit choice between FULL-FIDELITY MODE and SUPPORTED-ONLY MODE below.

The result is for this user and this Mac. Do not create a public repository, publish a binary, or distribute credentials unless the user separately requests that work.

PRINCIPLES

These rules apply to every section below. They are stated once here, and later sections point back to them instead of repeating them.

1. Verify against the exact installed version. Every command, flag, configuration key, environment variable name, model identifier, request header, response shape, and file path in this document is a reference fact, not a guarantee. Confirm each against the version installed on this Mac, using its own help output, its own config.example.yaml, or current official documentation, before you rely on it.

2. Never copy a value out of an example. Model identifiers, header names, response schemas, paths, and launcher names are setup-specific. An inherited value either fails outright or silently routes somewhere unintended, which looks like the setting worked.

3. Guess nothing. If you cannot verify something, stop and report it as unverified. Do not invent a configuration key and do not substitute a similar-looking one. If a key described here does not exist in your version, find the real equivalent or drop the behavior.

4. Technical support is not permission. An open-source proxy supporting a feature does not prove a provider permits it, and neither does the fact that it works.

5. Never print or store secrets. No token, API key, client key, credential record content, or provider account identifier belongs in chat, source, logs, shell history, screenshots, test fixtures, crash reports, built artifacts, or final reports. Redact authorization headers, tokens, client keys, account identifiers, and sensitive query values from every diagnostic.

6. Read-only first, approval before change. Discovery modifies nothing. Every item under HUMAN CHOICES needs explicit approval before it happens.

7. Fail closed and say so. When state is missing, stale, invalid, or contradictory, refuse rather than fall back quietly. Never let a failure degrade into different behavior without telling the user.

RISK DISCLOSURE AND BUILD MODE

Read this entire section before you plan or build anything. Present it to the user in plain English and get an explicit answer before implementation.

YOUR RESPONSIBILITY

The reader is solely responsible for reviewing the current terms of every provider account they intend to use, and for accepting any consequence of what they choose to build. This document is not permission, endorsement, approval, or legal advice. Nobody has reviewed the reader's accounts, contracts, employer rules, or jurisdiction. If the reader is not willing to read their providers' current terms themselves, they should not build FULL-FIDELITY MODE.

THE TWO MODES

FULL-FIDELITY MODE recreates the complete reference workflow. It authorizes several Claude and Codex consumer accounts in CLIProxyAPI, routes terminal and T3 sessions through the proxy, keeps a session on the same account with session affinity, and retries or cools down credentials according to CLIProxyAPI behavior. It needs a quota-aware scheduler guard, not merely the base proxy's round-robin option; base round-robin remains only as a fallback for traffic the guard does not handle.

SUPPORTED-ONLY MODE keeps consumer clients on their official direct login paths. It uses the proxy only for provider-supported API keys, cloud-provider credentials, or other documented profiles. It does not pool or rotate consumer subscriptions.

Both modes install and configure the same proxy engine. The difference is what goes into the authentication directory: supported API keys, documented cloud-provider credentials, or at most one consumer login per provider, versus several paid consumer subscription logins per provider. The rotation machinery described later is stock proxy behavior and works either way. The risk lives in stacking paid consumer subscriptions, not in the fact that the proxy rotates.

Be honest about what SUPPORTED-ONLY MODE actually produces today. It produces a within-terms single-account setup for each provider, plus the optional usage monitor if the user wants one. The monitor shows only what an official, documented usage interface exposes; wherever a provider publishes none, that cell shows Unavailable, and for some providers it will be mostly Unavailable. That is the current honest reality, not a bug in the build, and the user should choose knowing it. The monitor still gives real value: account presence, login state, error states, and any usage figures a provider does document.

NAMED RISKS IN FULL-FIDELITY MODE

Do not soften any of these. State each one to the user in plain words.

1. Rate-limit circumvention. This is the system's core purpose, not a side effect. Each provider sets a usage limit per subscription. Pooling several subscriptions behind one proxy exists to get past the limit any one of those subscriptions imposes, so that one person can keep working after a single account would have stopped them. Providers generally write their limits to apply to a person, not to a login. Treat "this design is built to exceed the limit my provider set for me" as the accurate description.

2. Account stacking and individual use. Whether one person may even hold and pool several individual consumer subscriptions at once is a separate question from how the traffic is routed, and it is likely against providers' individual-use and account-sharing terms. This risk exists the moment the accounts are stacked, before any request is proxied. The rule below about never copying another person's credential files does not address this risk. That rule is about borrowed credentials, which is a different problem. Stacking subscriptions the reader paid for themselves is not automatically clean.

3. Unofficial provider endpoints. FULL-FIDELITY MODE reads usage from private endpoints that providers do not document or support for third-party use. They can change or stop working without notice, and using them may itself be outside the terms.

4. Automation and client rules. Routing an official client through a third-party proxy, and presenting a proxy as the provider endpoint to that client, may conflict with the provider's rules for how their clients and subscriptions may be used.

WHAT HAPPENS IF A PROVIDER OBJECTS

Say this plainly to the user. If a provider decides this use violates their terms, the realistic outcomes include rate limiting, suspension of one or more accounts, and permanent termination of those accounts. That means losing the paid subscriptions involved, along with the access, history, and any work tied to them, potentially with no refund and no appeal. The loss is not limited to the account that triggered the review, because providers can act on every account they associate with the same person or payment method. There is no technical safeguard in this build that prevents that outcome.

READ THE RIGHT DOCUMENTS FIRST

Before choosing an authentication or routing design, read the current governing documents for each provider account the user intends to pool: the consumer subscription agreement, the terms of service, and the usage policy attached to that consumer subscription.

Do not substitute developer platform documentation, API reference pages, or command-line tool documentation for those terms. Developer docs describe a different product with a different contract, and they generally say nothing about consumer subscription limits or account sharing. An agent that reads only developer docs will report "I found nothing against this," and that report will be wrong because it read the wrong document.

Find each provider's consumer terms from the provider's own website, signed in to the account in question, and read the current version at the time of the build. Do not rely on any URL quoted from memory or copied out of a document like this one, including this one. Terms change and links move.

Do not silently remove FULL-FIDELITY MODE from this brief. Do not silently enable it either. Present the warning, quote the current official rules you actually read, and require explicit informed approval for that mode.

WHICH SECTIONS BELONG TO FULL-FIDELITY MODE ONLY

If the user chooses SUPPORTED-ONLY MODE, skip these sections entirely. Do not build any part of them, and do not treat them as background reading that shapes the safe build. Each one carries a short gate marker in the body of this document.

1. COMPLETE REFERENCE WORKFLOW.
2. USAGE OBSERVER AND PRIVATE USAGE ENDPOINTS.
3. ROUTING STATE PUBLICATION.
4. QUOTA-AWARE DRAIN ORDER AND SESSION AFFINITY.
5. CLAUDE CODE LAUNCHER.
6. CLAUDE-CODEX LAUNCHER.
7. FULL SYSTEM STARTUP ORDER.
8. FULL SYSTEM TROUBLESHOOTING ORDER.
9. The guard-plugin portions of CLIPROXYAPI INSTALLATION and CLIPROXYAPI CONFIGURATION, marked inline.
10. The multi-subscription pooling portions of ADDING ACCOUNTS, marked inline. Installing the proxy, writing its configuration, authorizing a supported credential, and the stock rotation, retry, and cooling behavior are not gated; they belong to both modes.
11. The private-usage-endpoint portions of OPTIONAL STATUS APP, if that optional app is built at all. The app itself is not gated, but in SUPPORTED-ONLY MODE it may show only documented interfaces.

An agent reading this document from top to bottom must not drift into building the risky mode because a section looked like a neutral engineering task.

In either mode, never copy another person's login files, browser data, cookies, Keychain items, OAuth cache, client key, or account configuration. Each user must authorize their own accounts through the provider's real browser flow. This rule prevents borrowed credentials. It does not make account stacking acceptable; see named risk 2.

Never send credentials, account data, or usage data anywhere except the provider endpoint required by the mode the user explicitly approved. FULL-FIDELITY MODE sends each provider's bearer token and account identifier only to that provider's private usage endpoint, never to this tool's developer, analytics, logs, or another third party.

If the user chooses SUPPORTED-ONLY MODE and the requested design is not clearly supported, stop and offer a supported API-key, cloud-provider, official single-account, or documented manual-profile design.

SECRET HANDLING

Never ask the user to paste a token, API key, OAuth file, cookie, password, recovery code, or full credential into chat. Use the provider's official browser login when available, and macOS Keychain for tool-owned secrets. If a tool requires a private file, make the containing directory owner-only and the file mode 0600. Principle 5 covers where secrets may never appear.

Use ephemeral network sessions where practical. Do not create a cookie store, URL cache, analytics service, or remote log sink for account data.

Credential material never leaves the process that needs it. In the usage observer, and in any optional status app:

1. Provider credential material and provider account identifiers stay in the privileged process that makes the usage request.
2. Any display process receives only a safe snapshot with no credential fields.
3. If the display is an Electron app, enable context isolation and disable Node integration in every window, and expose one narrow typed preload bridge with a fixed, reviewed set of calls and events.
4. Nothing in a display bundle, its source maps, or its packaged resources may contain credential material.

Two weaknesses are common in ad-hoc proxy installs and must not be reproduced here: a proxy configuration file readable beyond its owner, and the proxy's local control panel left enabled. Set the proxy configuration to mode 0600 and disable the control panel unless the user explicitly needs a loopback-only panel.

HUMAN CHOICES

After discovery, ask the user only for choices that cannot be safely discovered. Present your recommended defaults. Confirm these:

1. FULL-FIDELITY MODE or SUPPORTED-ONLY MODE, after reading the risk disclosure including the named risks and consequences.
2. Claude only, Codex only, or both.
3. How many credentials to authorize per provider, and of what kind. In SUPPORTED-ONLY MODE that means supported API keys, documented cloud profiles, or a single consumer login. In FULL-FIDELITY MODE this is the pooling decision, carrying named risks 1 and 2.
4. Whether to install the quota-aware routing guard at all. Recommend starting without it; stock rotation is the valuable part and needs nothing else.
5. Whether the usage observer should publish non-secret routing state for that guard. Recommend off until the guard is understood and approved.
6. Whether they want any status view at all, and if so whether it is a desktop app, a command-line printout, or both. Recommend none until rotation is verified working.
7. Terminal launchers, optional T3 Code setup, or both.
8. Start local services at login, or by hand.
9. App name and application identifier, only if a desktop app was chosen.
10. Preferred local port.
11. How updates are delivered, only if a desktop app was chosen: no updater, manual rebuild, or an updater pointed at the user's own release repository with their own signing setup.
12. Whether uninstall should preserve the user's own provider login files. Recommend preserving them.
13. Whether the user approves changes to existing T3 settings.
14. Preferred models, and the desired context or auto-compaction limit if the installed client supports one.

Pause for approval before any of these actions: changing an existing proxy configuration; installing, enabling, or configuring a proxy scheduler plugin; enabling the routing-state writer; replacing or editing an existing shell command, alias, function, or launcher; installing or changing a LaunchAgent; starting an OAuth login; accessing or creating a Keychain item; changing T3 settings; removing an existing app, configuration, or account file; installing a paid dependency or starting paid API usage.

DISCOVERY

Perform read-only discovery first. Do not read the contents of credential files: it is enough to report that a file or Keychain item exists, who owns it, and whether its permissions are safe. The finished usage observer does read the minimum fields it needs during live operation; that is approved implementation behavior, not a reason to read them now.

Discover and report:

1. macOS version and processor type, including Apple Silicon or Intel.
2. The user's real home directory, without placing it in shared documentation.
3. Homebrew location, if installed.
4. Only if a status app was requested: Node.js and npm versions if you would build on that toolchain, desktop packaging prerequisites including build tooling and disk space, and any code-signing identity and notarization credentials the user holds. Assume no signing material unless proven.
5. Installed Claude, Codex, ChatGPT, T3 Code, and related command-line clients, and their exact versions.
6. Current provider login status using documented status commands only. Where a client has no documented status command, report Unavailable rather than treating discovery as failed.
7. Existing local proxy services, their versions, and the exact name of the installed binary.
8. Whether the installed proxy version supports scheduler or routing plugins, and its plugin interface version. Verify this before planning a guard.
9. Whether any other process already writes a routing-state file the guard would read.
10. Local ports already in use.
11. Existing shell aliases, functions, launchers, and LaunchAgents that could conflict, and existing apps with the proposed name or application identifier.
12. Supported credential-storage mode for each installed client.
13. Which official usage or quota interfaces exist, and which providers offer none.
14. Whether T3 supports a custom endpoint and authentication method in its installed version.
15. Which model identifiers each installed client and each local service actually accepts on this Mac (principle 2).

DISCOVERY REPORT

Before changing anything, show the user:

1. What was found.
2. What can be supported with official methods.
3. What cannot be supported, and why.
4. The proposed architecture, described as the MISSION layers in this order: the proxy engine and how many credentials it will hold; its rotation, retry, and cooling settings; then the optional quota-aware guard with its usage observer and routing-state writer; and last the optional status view, if wanted at all.
5. Every file, app, launcher, port, login item, plugin, and setting that would be created or changed.
6. Which existing items will be preserved.
7. The requested human choices.
8. The test and uninstall plan.

Wait for approval before implementation.

HOW THE ROTATION ACTUALLY WORKS

This is the mental model the rest of the document assumes, and it corrects the most common misunderstanding about this system. Read it before writing any configuration.

The proxy is the thing that holds N accounts and rotates across them. This is stock behavior, not something you build. Every credential file in the proxy's authentication directory is a candidate. For a given provider, the proxy selects among all eligible candidates using its configured routing strategy, retries a failed request against other eligible candidates, and puts a credential that hit a limit into cooldown so later requests skip it. Adding a tenth account is the same operation as adding a second: run the login command again. There is no per-account configuration to write and no rotation code to author.

The optional guard does not add rotation. It replaces the stock selection order for protected providers with a deterministic, quota-aware drain order, and fails closed when it cannot see fresh state. Remove the guard and the proxy still rotates, just in stock order.

Know exactly what needs what, because this is where most rebuilds add work they did not need:

1. Stock rotation across N accounts, including round-robin or fill-first selection, automatic retry onto another account, and cooling of an account that hit its limit, needs the proxy and nothing else. No usage observer, no status app, no plugin. Configure it, add accounts, done.
2. Only the optional quota-aware drain order needs more: fresh per-account usage figures, meaning the usage observer and its routing snapshot, plus the guard plugin. That is the advanced path and it is full-fidelity mode only.
3. A status app is never required by either. It displays; it does not route.

If you catch yourself planning to write rotation logic in an app, or to have an app call a rotate command, stop. That is not how this system works. If the user only wants rotation, do not build the observer, the guard, or any UI.

CLIPROXYAPI INSTALLATION

Both modes. CLIProxyAPI is a public open-source project:

  https://github.com/router-for-me/CLIProxyAPI
  https://help.router-for.me

On a Homebrew Mac the usual installation and service commands are:

  brew install cliproxyapi
  brew services start cliproxyapi
  brew services restart cliproxyapi
  brew services stop cliproxyapi

Docker images are published, and the project builds from source with a standard Go build:

  go build -o cli-proxy-api ./cmd/server

Inspect the current formula and release first, and pin or record the tested version. The formula is named cliproxyapi and the built binary is commonly named cli-proxy-api; run the package manager's file listing and the binary's help output once and use whichever name is actually installed, rather than assuming an Apple Silicon Homebrew prefix. This document uses cli-proxy-api in examples.

The Homebrew service runs at user login with KeepAlive and RunAtLoad, as the current user rather than root.

The project's default endpoint is:

  http://127.0.0.1:8317

The receiving user may choose another free port. All launchers, T3 settings, tests, the routing guard, and any status view must use the same chosen value.

Before going further, confirm the service is loaded and running, that only 127.0.0.1 is listening on the selected port, and that the service restarts after login and after a Mac restart.

Full-fidelity mode only, for the rest of this section. If the user selected the quota-aware routing guard, also verify before implementation that this exact installed version supports scheduler or routing plugins; the plugin interface version it expects, and that your guard matches it; that the plugin loads at startup and reports itself active; and that a plugin failure is visible rather than silently falling back to base routing.

CLIPROXYAPI CONFIGURATION

Both modes. The proxy reads a single YAML file, config.yaml, created by copying the project's config.example.yaml into the authentication directory. Write a fresh file for this Mac. Do not copy another user's file.

The block below uses the project's current public key names. Fill in the angle-bracket placeholders with values you generate or discover here. Configuration schemas drift between releases, so principles 1 and 3 apply to every key in it.

  host: "127.0.0.1"
  port: 8317
  auth-dir: "<USER_HOME>/<PROXY_PRIVATE_AUTH_DIR>"
  api-keys:
    - "<NEW_RANDOM_LOCAL_CLIENT_KEY>"
  debug: false
  logging-to-file: false
  usage-statistics-enabled: false
  proxy-url: ""
  ws-auth: true
  tls:
    enable: false
    cert: ""
    key: ""
  remote-management:
    allow-remote: false
    secret-key: ""
    disable-control-panel: true
  request-retry: 3
  max-retry-credentials: 0
  max-retry-interval: 30
  disable-cooling: false
  save-cooldown-status: false
  transient-error-cooldown-seconds: 0
  quota-exceeded:
    switch-project: true
    switch-preview-model: true
    antigravity-credits: true
  routing:
    strategy: "round-robin"
    session-affinity: false
    session-affinity-ttl: "1h"
  plugins:
    enabled: false
    dir: "plugins"
    configs: {}

What the load-bearing keys do:

1. host. The bind interface. 127.0.0.1 makes the proxy reachable only from this Mac; an empty value binds every interface, which you do not want.
2. port. The listening port. 8317 is the project default.
3. auth-dir. The directory holding provider credential JSON files. Every login writes one more file here, and every file here is a rotation candidate. This is the single most important setting for multi-account behavior.
4. api-keys. The keys a local client must present to the proxy. Generate one high-entropy value and give it to your launchers only.
5. tls. Leave disabled for a loopback-only service unless the user has a specific reason.
6. remote-management. Keep allow-remote false and disable-control-panel true. A local control panel is unnecessary attack surface.
7. proxy-url. An optional outbound upstream proxy. Leave empty unless the user needs one.
8. request-retry. How many extra retry rounds run after the first round has exhausted the eligible credentials. This is what turns a single account failure into an automatic hand-off to another account.
9. max-retry-credentials. A cap on distinct credentials tried per round. Zero means unlimited, that is, all eligible credentials. Confirm that meaning in your version rather than guessing whether zero means disabled.
10. max-retry-interval. The maximum seconds the proxy waits for a credential cooldown to lapse between rounds.
11. disable-cooling. Turns cooldown off globally. Leave it false; cooling is how an exhausted account stops absorbing requests.
12. save-cooldown-status. Whether cooldown survives a restart. With false, cooldown lives only in process memory and a restart clears it.
13. transient-error-cooldown-seconds. Cooldown length after a transient error. Zero means the version's built-in default, roughly sixty seconds; minus one disables it. Zero is not the same as disabled.
14. quota-exceeded. Version-specific fallbacks when a credential reports a quota problem, including project switching and preview-model switching. Explain these to the user and get approval before enabling them.
15. routing.strategy. How the proxy picks among eligible credentials. The documented options are round-robin, which spreads load evenly; fill-first, which drains one account before moving to the next; and weighted-round-robin, which biases the split.
16. routing.session-affinity and routing.session-affinity-ttl. With affinity on, a session sticks to the account it was first routed to until the TTL lapses. Turn it on to keep a long agent session on one account; leave it off for maximum spreading.
17. plugins. The real mechanism that loads a compiled routing plugin. It stays disabled unless the user approved the quota-aware guard.

Generate a new high-entropy local client key. Keep it out of this prompt and out of source control; launchers should inject it as an environment variable at process start from the user's own Keychain or secret manager.

Set the proxy configuration to mode 0600 because it contains the client key. Set the authentication directory to mode 0700 and credential files to mode 0600. A default install may leave the configuration world-readable and the control panel enabled; correct both.

After every configuration change, repeat the service checks from CLIPROXYAPI INSTALLATION and also confirm that the proxy accepts the new local client key, that remote management and the control panel are disabled, that logs and process arguments do not expose the key, and, in full-fidelity mode with a guard installed, that the guard is loaded and reports the expected policy values.

Full-fidelity mode only, for the rest of this section. The guard loads through the real plugins mechanism above, but the guard's own settings are not a public schema. This block is shape and intent only; confirm the real key names and nesting against the installed proxy version and the guard you build, and use placeholders for every path, credential, and hash:

  plugins:
    enabled: true
    dir: "plugins"
    configs:
      <QUOTA_AWARE_ROUTING_GUARD>:
        enabled: true
        priority: 100
        max-state-age-seconds: 90
        session-affinity-ttl-seconds: 3600
        state-file: "<APP_OWNED_ROUTING_SNAPSHOT_PATH>"
        client-credential-hash: "<HASH_OF_LOCAL_CLIENT_KEY>"

Store a hash of the local client credential, never the credential itself.

Once the guard is installed, do not present the base routing strategy as the effective policy for protected providers. The guard chooses Claude and Codex accounts before the base strategy runs, so drain order plus affinity controls those requests. The base strategy remains only as the fallback for traffic the guard does not handle.

ADDING ACCOUNTS

Both modes. Read the mode note at the end before deciding how many accounts to add.

Each login command run creates one more provider credential record in the authentication directory, and the proxy treats every record there as a rotation candidate for its provider. To pool five accounts, run the same command five times, signing into a different account in the browser each time. There is no other step.

Verify the flags against the installed binary's help output first. The project's current login flags are:

  cli-proxy-api --claude-login
  cli-proxy-api --codex-login
  cli-proxy-api --gemini-login

Other providers have their own equivalents. Add --no-browser to print the login URL instead of opening a browser, which is useful over SSH. The local OAuth callback listens on port 54545; confirm nothing else is using it and that the listener binds loopback only.

For every account:

1. Start the login command locally.
2. Let it open the official provider browser flow, or open the printed URL yourself.
3. Confirm the browser is signed into the intended account before approving access.
4. Complete the provider's real OAuth flow.
5. Confirm the proxy created or refreshed exactly one credential record for that provider.
6. Check ownership and mode without printing the record.
7. Confirm the proxy recognizes the account, then repeat for the next one.

For Codex or ChatGPT records, confirm you can read both an access credential and a provider account identifier from the record, because a Codex usage request needs both. That identifier must never appear in a UI, log, screenshot, or report; use a masked label.

Refer to these records generically as provider credential records. Never write real record names, labels, or addresses into documentation, never copy a record from another person, and never paste an access token into chat.

Mode note. In SUPPORTED-ONLY MODE, populate the authentication directory with provider-supported API keys, documented cloud-provider credentials, or at most one consumer login per provider, and check that provider's current terms on whether a single consumer login through a local proxy is acceptable at all. Rotating across several supported API keys or documented cloud profiles is ordinary key management and is legitimate.

Full-fidelity mode only, for this paragraph. Authorizing several paid consumer subscription accounts for the same provider is the pooling step, and it is where the risk lives. Be honest with the user every time an account is added: each additional subscription adds its capacity to the pool, which is exactly how the system continues past the point where a single subscription's limit would have stopped the work. That is named risk 1, and named risk 2 applies the moment the subscriptions are stacked, before any request is proxied.

STOCK ROTATION, RETRY, AND COOLING

Both modes. This is behavior the proxy already has once the configuration above is in place. You do not implement any of it; you configure it and verify it.

1. Load balancing. Multiple credential files for the same provider become a rotation set. The proxy picks among them using routing.strategy.
2. Retry across accounts. When a request fails against the selected credential, the proxy retries other eligible credentials in the same round. request-retry adds rounds after the first exhausts the eligible set; max-retry-credentials caps how many distinct credentials each round may try.
3. Cooling. A credential that hits a limit or a transient error is put into cooldown and skipped while cooling. transient-error-cooldown-seconds sets the length, disable-cooling turns the behavior off entirely, and save-cooldown-status decides whether cooldown survives a restart.
4. Waiting for a cooldown. Between rounds the proxy waits for a cooling credential up to max-retry-interval seconds rather than failing immediately.
5. Session affinity. With routing.session-affinity enabled, a session stays bound to one credential until session-affinity-ttl lapses, so you will not see per-request movement while a session is bound.
6. Exhaustion. When every eligible credential for a model is unavailable, the client receives a 429 stating that all credentials are cooling down. That message means the pool itself is empty, not that one account failed.

Retryable status codes commonly include 403, 408, 500, 502, 503, and 504 (principle 1).

How to test rotation honestly:

1. Start a brand-new session for each test. An existing session may still be affinity-bound and will not move.
2. With affinity off and round-robin on, consecutive fresh requests should land on different credentials. Observe this in the proxy's own logs, not by guessing from client behavior.
3. To test failover rather than balancing, make one credential fail, then confirm a fresh request still succeeds and the proxy logs the hand-off.
4. Do not treat deterministic sameness as proof of failure. With affinity on, with fill-first, or with the guard installed, staying on one account is expected until quota state changes.

ACCOUNT ADDITION AND ACTIVATION

Both modes, except where a step names the guard. After adding any account:

1. Confirm the new credential record exists and is readable only by its owner.
2. Check whether the running CLIProxyAPI version hot-reloads the authentication directory; if it does not, restart the service.
3. Run a proxy health or model-list check using the local client key without printing it, and record the model identifiers the proxy actually serves. The launcher sections need those real values.
4. If a usage observer or status view is running, refresh it and confirm the account appears under the correct provider.
5. Start a brand-new task to test routing.
6. Full-fidelity mode only: with the guard installed, confirm the account appears in the routing snapshot and is classified with fresh observations.

With stock routing, a newly added credential joins the rotation set immediately after reload and fresh sessions begin landing on it according to the configured strategy. Sessions already bound by affinity keep their credential until the TTL lapses.

Full-fidelity mode only, with the guard active: a newly eligible account enters the deterministic drain order described below and receives requests when it is first in that order, not necessarily next. Existing sessions stay bound while their account remains eligible, on a sliding one-hour expiry that extends on each successful selection. If a bound account becomes ineligible, the next request rebinds immediately to the first eligible account in the current order.

Do not expect an already-running task to jump to a new account, and never use an old affinity-bound process as your only routing test.

ACCOUNT LIFECYCLE

Neither the usage observer nor any status view adds, re-authenticates, disables, re-enables, removes, archives, or edits provider credentials. They discover and read them. All account repair happens outside them, through the proxy's own provider login flow. Be honest with the user about that scope.

The reference observer does de-duplicate display accounts by canonical provider identity, falling back to a normalized account label when a canonical identity is unavailable, and selects one preferred current credential per canonical account deterministically, so the same record wins on every refresh.

If the user wants in-app lifecycle management, treat it as optional future scope and build it deliberately:

1. List accounts by provider, masked label, enabled state, expiry state, and model eligibility.
2. Add an account with the matching proxy browser-login command.
3. Re-authenticate through the provider-wide proxy login flow. Tell the user that the browser account they choose determines which credential is created or refreshed; a provider-wide command cannot target a specific row.
4. Disable an account using the installed version's documented mechanism, so it is excluded from routing while its login is preserved.
5. Re-enable a disabled account after checking it is still valid.
6. Remove an account only after showing which provider and masked label will be removed, and receiving confirmation.
7. Refresh after every lifecycle change, and start a new task when testing routing changes.

Do not hand-edit token values inside credential records. If the installed proxy version has no documented disable or remove command, stop; treat account disable and removal as a separate, separately reviewed design problem and bring it back to the user as its own decision. Do not edit, move, rename, or truncate credential records at the file level as a workaround. That path is unsupported, can corrupt account state, can silently break routing, and can destroy a login the user cannot easily recover.

During discovery, detect any credential-switching helper that rewrites which account the official clients consider active. Such a tool fights a proxy that manages its own pool. Explain the conflict and ask whether to disable or uninstall the helper after preserving any user-owned data.

COMPLETE REFERENCE WORKFLOW

Full-fidelity mode only.

This is the complete reference architecture end to end, layering the guard and its usage observer on top of the engine you have already built. Recreate it with generic paths and fresh credentials owned by the receiving user; copy no files or secrets from another Mac.

1. Install CLIProxyAPI and bind it to loopback only, as a per-user service.
2. Authorize each provider profile through the proxy's own browser login flow, one account at a time.
3. Confirm stock rotation, retry, and cooling work across those accounts before adding anything on top. If the user is satisfied there, stop; the rest is optional.
4. Install the usage observer as a background process, plus a user-level startup job if approved.
5. The observer scans the proxy's private authentication directory, de-duplicates records into canonical accounts, and polls provider usage for each.
6. It computes included-capacity state, credit availability, and separate provider usable counts.
7. It writes a mode-0600 non-secret routing snapshot every 15 seconds and immediately after each completed pool refresh.
8. Install and enable the quota-aware routing guard inside CLIProxyAPI. It rejects stale or unknown routing state for protected providers, orders included accounts by a deterministic drain policy, and applies sliding session affinity.
9. Base proxy retry and cooling remain underneath the guard as a separate, lower layer.
10. Terminal and T3 sessions call namespaced launchers that point the harness at the local proxy.
11. Optionally attach a status view to the observer's snapshot. This adds no capability and can be skipped entirely.

Steps 1, 2, and 8 exist so that one person's work can continue across several subscriptions after any single subscription would have hit its limit. See named risk 1.

USAGE OBSERVER AND PRIVATE USAGE ENDPOINTS

Full-fidelity mode only.

The guard cannot order accounts by remaining capacity unless something tells it how much capacity each account has left. That something is the usage observer: a small headless background process with no window. The optional status app described later is merely one possible face on the same data. Build the observer for the guard; build a view only if the user separately wants one. Stock rotation does not need any of this, so if the user is not installing the guard, skip the observer entirely.

What the observer does:

1. Scans the proxy's private authentication directory and reads only the fields it needs: masked account label, canonical provider identity, provider account identifier, disabled state, expiry state, and the current access credential.
2. De-duplicates records into canonical accounts and picks one preferred candidate per account deterministically, so the same record wins on every pass.
3. Polls each canonical account's usage on a timer, roughly every 60 seconds, with about one second of pacing between account network calls and a 15-second per-request timeout.
4. Honors a provider-requested retry delay per account, capped at three minutes, and does not re-poll that account while the wait is active.
5. Strictly validates every response. Missing fields, changed schemas, HTML error pages, and unexpected content types are errors, never zero usage.
6. Classifies each account: exhausted at the 99 percent cutoff on any binding window, fresh or stale by observation age, enabled or disabled, and credit-available separately from included capacity.
7. Publishes the routing snapshot described in the next section.

Credential handling here is not optional. Access credentials and provider account identifiers exist only in the observer process, in memory, and only while a usage request is in flight. They are never printed, logged, cached, persisted, or written into the snapshot. Network sessions are ephemeral, with cookies, URL cache, and credential storage disabled.

The reference observer reads usage from these private, unstable endpoints:

  Claude usage:
  https://api.anthropic.com/api/oauth/usage

  ChatGPT or Codex usage:
  https://chatgpt.com/backend-api/wham/usage

Each request carries the account's own credential material, and each provider requires its own additional request headers. Treat the endpoint paths above as reference facts and everything else about the request as unverified. Before implementing either call, discover and verify against the current provider what request headers are actually required, including any version or beta header, and what the response actually contains. Do not copy header names, header values, or a response schema from this document, from a blog post, or from another project; none of that is authoritative and all of it goes stale. If you cannot verify a requirement, stop and report it as unverified rather than guessing.

These are not public stable APIs. They are undocumented, they can change or disappear without notice, and they may not be approved for third-party use at all. This is named risk 3. Label the risk clearly wherever the observer's output is surfaced and in the final report.

Decoding intent, to confirm against real observed responses rather than treat as a schema:

1. Claude decoding requires valid five-hour and seven-day windows. A response missing either is a data error, not zero usage.
2. Claude model-specific data is selected from the provider's limits structure, with direct fallback fields when the limits structure does not carry it.
3. Claude extra-usage and spend state is read separately from included capacity.
4. Codex primary and secondary windows are mapped by duration, not by provider order. A window of at most one day becomes the short window; a longer one becomes the weekly window.
5. Codex also reads its allow flag, limit-reached flag, and credit fields.

Field names, nesting, and value units are all things you observe and validate yourself. Build the validator against what the provider actually returns during your build, and fail closed when the shape changes.

Last-good behavior is provider-specific. Claude may retain its last good reading across transient network and rate-limit failures and still be counted while that reading is at most 90 seconds old, but Claude authentication and data-validation failures fail closed immediately with no retained credit. Only a live Codex reading counts as usable. Retained data must be marked as retained wherever it is surfaced, with its observation time. Never report stale data as live, and never let retained data reach the guard as if it were fresh.

Observing usage must not itself create meaningful model usage or a burst of provider requests. The observer must never modify provider credential records, login state, or provider configuration. Its only write is the routing snapshot.

ROUTING STATE PUBLICATION

Full-fidelity mode only.

This is the bridge between the observer and the guard. It is optional and off until the user enables it. When enabled, the observer writes one small owned file:

1. Written every 15 seconds on a heartbeat, and immediately after each completed pool refresh.
2. Written atomically: stage a temporary file in the same owner-only directory, then move it into place.
3. The containing directory is mode 0700; the file is mode 0600.
4. Its safe fields are capacity class, a credit-available boolean, observation and reset timestamps, a preferred-candidate flag, short-window utilization, and opaque candidate and canonical identifiers.
5. It must never contain access tokens, provider account identifiers, real account labels, or the local client credential.
6. Its path is chosen generically on the receiving Mac and referenced by the guard configuration.

Only one writer may own that file. If discovery finds another process writing routing state, stop and ask the user.

If the writer is disabled while the guard is installed and expecting state, the guard must fail closed rather than guess. Document that pairing so a user cannot end up with a guard reading a file nobody updates.

QUOTA-AWARE DRAIN ORDER AND SESSION AFFINITY

Full-fidelity mode only.

This policy is not neutral load balancing, and it is not what makes the pool rotate; the proxy already rotates without it. Its purpose is to spend each pooled subscription's capacity in a deliberate order, so that hitting one account's provider-set limit does not stop the work. That is rate-limit circumvention by design, named risk 1. Describe it to the user that way, not as scheduling.

With the guard installed, protected Claude and Codex requests are selected by the guard rather than the base routing strategy:

1. Group duplicate credential candidates by canonical account and keep one preferred candidate per account.
2. Require a fresh routing snapshot and fresh per-account observations, with a 90-second ceiling. Missing, stale, invalid, contradictory, or incomplete state fails closed.
3. Treat an account as included-capacity exhausted when any binding window reaches 99 percent. Claude routing requires complete five-hour, seven-day, and model-specific binding data. Codex uses its available short and weekly rate windows plus its allow and limit flags.
4. If any included subscription account is available, exclude credit-backed exhausted accounts from selection.
5. Order available included accounts first by five-hour headroom: accounts below 90 percent utilization before accounts at or above 90 percent.
6. Within that group, prefer the account whose next weekly reset arrives soonest, so capacity that replenishes sooner is drained first. Accounts with no known future weekly reset follow those with one. Canonical identity is the deterministic final tie-break.
7. Select the first account in that order. With no usable session identity, every pick selects the current first account. That is deliberate, and it is not rotation.
8. With a session identity, keep the selected account for a sliding one-hour TTL that each successful selection extends. If the account leaves the eligible set, rebind immediately to the first current candidate.
9. Credit-backed routing unlocks only when every non-excluded subscription account for that provider is freshly confirmed exhausted. Any unknown, guarded, or stale account blocks credits entirely. Among credit-capable accounts, selection is deterministic rather than round-robin.
10. Base proxy retry and cooling still exist beneath the guard, exactly as configured in STOCK ROTATION, RETRY, AND COOLING.

Test and document the installed version's exact session key, retry rules, cooldown rules, and hot-reload behavior. With a guard active, deterministic sameness is expected until quota state changes, so do not tell users to look for round-robin movement as proof the system works.

Neither the observer nor any view may call a rotate command. They report what they observe and, when enabled, publish it. The guard and the proxy own request routing.

CLAUDE CODE LAUNCHER

Full-fidelity mode only.

Create a namespaced wrapper, or use the normal claude name only after the user explicitly approves replacing its resolution in PATH.

Before writing any launcher, establish the real model identifiers and the real environment variable names for this Mac. Run the proxy health or model-list check from ACCOUNT ADDITION AND ACTIVATION using the local client key without printing it, and confirm each identifier against the installed client's accepted values. Check the installed client's own documentation or help output for the environment variables it currently reads. Principles 1 through 3 apply to every name in this section; an unrecognized variable is silently ignored, which looks like the setting worked. Below, <MODEL_ID> means an identifier you verified this way.

The reference wrapper, at launch time:

1. Loads the local proxy client key from the user's own secret manager.
2. Sets the client's base URL variable to http://127.0.0.1:<PROXY_PORT>.
3. Sets the client's auth token variable to the local client key.
4. Clears any direct provider API key variable so the local token path wins.
5. Sets the client's primary model variable to <MODEL_ID>.
6. Sets each model-tier default variable to <MODEL_ID>, so the harness cannot silently request a model the proxy does not serve.
7. Sets the subagent model variable to <MODEL_ID>.
8. Sets whatever context and compaction variables the installed client documents, to the limits the user chose.
9. Starts the real Claude Code binary with <MODEL_ID> and those settings.
10. Forwards every original argument and preserves the child's exit code and signals.

The reference wrapper also passes a flag that skips permission prompts. That removes normal permission prompts and is high risk. Say so, ask whether the user wants it, and recommend leaving it off unless they accept the local filesystem and command-execution risk.

Verify inside the client that the selected model is the intended one, that direct API billing is not being used accidentally, that the proxy receives the request, that subagents inherit the same model, and that context and compaction settings actually took effect rather than being silently ignored.

CLAUDE-CODEX LAUNCHER

Full-fidelity mode only.

The reference workflow also has a separate launcher that runs a GPT model through the Claude Code harness. This is different from running the official Codex CLI directly. Get the GPT model identifier from your own proxy's model list; <DEFAULT_MODEL_ID> below means an identifier verified on this Mac.

The launcher loads the local proxy client key; sets the client's base URL variable to the same localhost proxy and its auth token variable to the local client key; sets the primary model variable, the model-tier defaults, and the subagent default all to <DEFAULT_MODEL_ID>, so the Claude harness cannot silently request another model; allows an explicit environment variable or model flag to override the model; and starts the real Claude Code binary, forwarding all arguments.

Use a clear name such as claude-codex, kept separate from the normal claude and codex commands.

If the user wants the official Codex CLI itself to use a custom model provider, inspect current official Codex authentication and custom-provider documentation and configure that as a separate client path. Do not confuse official Codex CLI authentication with the Claude-Code-backed-by-Codex launcher.

T3 CODE WORKFLOW

T3 Code creates and resumes tasks by launching an agent command. The intended workflow depends on T3 calling the wrappers above rather than the raw provider binaries, but do not claim this is configured until the live child-process path proves it.

The reference design places its Claude wrapper at <USER_HOME>/.local/bin/claude while the real vendor binary remains at the discovered package-manager path, and the user's PATH resolves the wrapper first. That is why normal terminal Claude sessions and T3 Claude sessions share the same proxy, model, and context settings. This command shadowing is powerful and easy to misunderstand: show the exact which -a claude result before and after the change, keep an explicit direct-vendor command available, and if the installed T3 version supports an explicit agent executable path, prefer pointing T3 at the wrapper instead of changing global command resolution.

The separate GPT-through-Claude-harness wrapper lives at a distinct user-local command such as <USER_HOME>/.local/bin/claude-codex. That is one possible Codex-backed T3 mode. T3 also has a native Codex provider, which is a different path; discover which one the user wants, show the differences, verify the real spawned process for each, and do not treat them as interchangeable.

Configure Claude-backed T3 tasks to invoke the model-pinned Claude launcher, and Codex-backed tasks that use the Claude harness to invoke claude-codex. Identify the real agent-command or executable-path setting from the installed T3 version or current open-source code (principle 3).

For each T3 agent choice, verify that the launched process path is the wrapper rather than the raw binary; that it receives the localhost proxy URL and local client key through the wrapper; that Claude tasks and their subagents use the intended model; that Codex-backed tasks use the intended GPT model; that the context limit and compaction setting match the chat setting in T3; that a fresh task works, a resumed task still uses the wrapper, and a long-running task survives normal compaction; and that restarting T3 does not lose the configuration.

Changing CLIProxyAPI credentials does not rewrite old T3 transcripts. Existing live agent processes may keep their original session affinity until restarted or until the affinity expires.

OPTIONAL STATUS APP

This section is optional and low value compared with everything above it. The rotation you built works with zero user interface: the proxy is a background service, and adding an account is a login command, not a click. A reader who only wants automatic rotation across their accounts can skip this entire section and has lost nothing.

Build it only if the user asked for a view. The reference implementation is an Electron desktop app with a tray popover and a dashboard, but any stack is fine, including a plain command-line status printout. What matters is the following invariants, not the layout.

1. It is read-only with respect to provider credentials. It never edits, rotates, archives, replaces, disables, or re-authorizes a credential record, and it never selects an account for a request. Its only routing role is the optional writer already described under ROUTING STATE PUBLICATION, and that belongs to the observer, not to the view.

2. It is a face on the usage observer, not a second implementation of it. Do not write a separate poller inside the app; if the observer already runs for the guard, read its output. If no guard is installed, the app may poll on its own under the rules in USAGE OBSERVER AND PRIVATE USAGE ENDPOINTS, including the full-fidelity gating on those endpoints. In SUPPORTED-ONLY MODE it shows only what documented interfaces expose. Expect many Unavailable cells; that is correct, not a failure.

3. One shared calculation in the privileged process drives every surface, including any tray title or summary count, so counts cannot drift between them.

4. The view process never receives credentials. Access credentials and provider account identifiers stay in the privileged process, in memory, and only while a usage request is in flight. On Electron that means context isolation on, Node integration off, a sandboxed renderer, and one narrow typed preload bridge. Nothing in the view bundle, its source maps, or its packaged resources may contain credential material, and a test must prove it.

5. Display per-account percent used, never percent remaining. Label the meaning once and never mix the two. Show reset times where the provider gives them, keep provider-specific columns and counts separate rather than merging them into one total, and never invent a value for a field a provider does not expose; show Unavailable instead.

6. Refresh on a timer of about 60 seconds, plus a manual refresh that does not cause a burst of provider requests. Validate every response: missing fields, changed schemas, HTML error pages, and unexpected content types are errors, never zero usage.

7. Mark retained or last-good data as retained, with its observation time. Never present stale data as live.

8. Distinguish at least these account states, with a short useful error where data is unavailable: loading, live, disabled, expired, authentication rejected, rate limited, and data or request error. Re-authentication is not a button; it happens outside through the official provider login flow, and the app should point the user at the correct external command.

9. Never invent account data. If the view cannot reach its data source, show an explicit unavailable state and retry rather than falling back to empty or default rows that look real.

If you package a desktop app, sign and notarize it only with the reader's own signing material; an unsigned local build is an expected and supported outcome and must not be distributed to other people. Any updater must point at the reader's own release repository and identifier, or be omitted. Use neutral or generic provider marks unless you have separately confirmed a license; do not copy artwork out of installed official applications.

The detailed reference UI layout, its pixel dimensions, column order, status-dot color thresholds, and countdown formatting are intentionally out of scope. Build whatever view the user likes, or none.

FULL SYSTEM STARTUP ORDER

Full-fidelity mode only. In SUPPORTED-ONLY MODE the startup order is simply that the proxy service starts, loads its supported credentials, and terminal sessions use it. Nothing else is required.

On login or after a restart:

1. The local proxy service starts as the current user and loads its configuration, account records, and routing guard plugin.
2. The usage observer starts, manually or as an approved login item, and acquires a single-instance lock so two copies cannot write the routing snapshot.
3. The observer loads its persisted settings and begins its initial pool refresh.
4. Routing publication starts only if its persisted setting is enabled.
5. Terminal and T3 tasks call the wrappers, which load the local client key and point the harness at the proxy.
6. Protected requests are selected by the guard's drain order and sliding affinity, not by the base routing strategy.
7. A task continues on its bound credential until the affinity window lapses, the account becomes ineligible, or a relevant failure changes routing.
8. Any optional status view starts last and simply renders the observer's snapshot. If it fails to start, rotation is unaffected.

FULL SYSTEM TROUBLESHOOTING ORDER

Full-fidelity mode only.

When a task says not logged in or gets an authentication error:

1. Confirm the task launched the wrapper instead of the raw binary, and that the wrapper loaded the local client key.
2. Confirm the proxy is running and only loopback is listening on its port.
3. Confirm the client key is accepted.
4. Confirm at least one matching provider credential record exists.
5. Check whether the account is expired, disabled, cooling down, or malformed.
6. Run the matching official proxy login flow when re-authentication is appropriate. No part of this system can do that for you.
7. Restart the proxy only when the installed version requires it to reload account records.
8. Start a new task to test a new routing assignment; do not use an old affinity-bound process as the only test.

When routing looks wrong or an account seems to get no work:

1. Confirm the observer completed a pool refresh within the last 60 seconds.
2. Confirm the routing-state writer is enabled if the guard expects state.
3. Confirm the snapshot file and each account observation are younger than 90 seconds.
4. Confirm the guard is loaded and reporting its expected policy values.
5. Check whether the account was classified exhausted at the 99 percent cutoff.
6. Check whether it was ordered behind another account because its five-hour utilization is at or above 90 percent.
7. For Claude, check whether incomplete model-specific binding data blocked it.
8. Check whether an unknown or stale account is blocking credit-backed routing for that provider.
9. Remember that deterministic sameness is expected with the guard active; do not look for round-robin movement as proof routing works.
10. To isolate the guard, disable it and confirm the pool still rotates on stock behavior. If stock rotation works and guarded routing does not, the problem is the guard or its state file, not the pool.

When every pooled credential is exhausted, authorizing an additional account adds that subscription's capacity and lets the work continue past the limit the exhausted accounts reached. That is the rate-limit-circumvention behavior named in the risk disclosure, not routine troubleshooting; confirm the user still accepts that risk before adding capacity. If they do, verify the new record, reload behavior, its appearance in the routing snapshot, and a brand-new task.

When T3 tasks stop unexpectedly, determine whether T3 restarted the Claude process; check the T3 and harness logs without printing secrets; confirm the task used the correct wrapper after restart; check for a 429 stating that all credentials are cooling down; check whether context reached the compaction threshold; verify that T3 and the wrapper use the same context and compaction settings; and resume only after identifying whether the cause was process restart, proxy capacity, authentication, or compaction.

SUPPORTED LOCAL ROUTING

This section is about which credentials are legitimate to put in the pool, not about how the pool works.

Prefer supported API keys, Anthropic Console access, Amazon Bedrock, Google Vertex AI, Microsoft Foundry, OpenAI Platform API keys, or another provider-documented enterprise method. Rotating across several of those is ordinary key management and carries none of the named risks.

The official Codex client supports ChatGPT sign-in and API-key sign-in, and documents custom model providers. Use only combinations described by current official Codex documentation, and do not assume a custom provider permits several ChatGPT subscription sessions. Principle 4 applies: technical support in a proxy proves nothing about permission.

Whichever credentials you use:

1. Pin one reviewed proxy version and verify an upstream-published checksum or signature. If the project publishes neither, pin and build a reviewed source commit rather than trusting an unverified download.
2. Apply the loopback hardening from CLIPROXYAPI CONFIGURATION: bind 127.0.0.1 only, require a unique local client key, disable remote management and any control panel, and keep the private configuration and authentication directory outside the source tree.
3. Check the selected port before staging and again before activation, and verify that every temporary login or OAuth callback listener also binds loopback only. Stop if that cannot be proved.
4. Do not silently adopt, upgrade, or downgrade an existing proxy installation.
5. Match routing to the approved mode. FULL-FIDELITY MODE uses the quota-aware guard on top of stock rotation: fail-closed freshness, deterministic drain order, sliding session affinity, and credits only after every included subscription is freshly exhausted. SUPPORTED-ONLY MODE uses supported profiles and stock rotation across them.
6. Never hide which routing mode is active, and never let a guard failure silently degrade into base routing without saying so.

If supported routing is not possible, keep the official claude and codex clients on their normal authentication paths. A status view, if wanted at all, may still be built on whatever supported data sources remain.

TERMINAL LAUNCHERS

Never replace the normal claude or codex command by default. Create namespaced launchers such as ai-claude and ai-codex, or names chosen by the user.

Each launcher must:

1. Preserve the working directory.
2. Forward all arguments exactly once.
3. Preserve standard input, output, and error, and forward signals.
4. Return the real child exit code.
5. Avoid shell recursion and alias loops.
6. Use the supported local endpoint and secret source without printing either secret.
7. Fail with a clear message when the local service is unavailable.
8. Leave the official unproxied command working.
9. Use only model identifiers and environment variable names verified on this Mac.

OPTIONAL T3 CODE SETUP

Treat T3 Code as optional. First inspect the installed T3 version and its current settings, and verify the exact supported setting names and behavior from current source or official documentation.

Before changing T3:

1. Show the exact proposed setting changes.
2. Back up only the settings file being changed.
3. Ask for approval.
4. Keep unrelated T3 settings and projects unchanged.
5. Use only the supported local endpoint and authentication design.
6. Verify a new task, a resumed task, and that restarting T3 does not lose the configuration.
7. Where supported, keep the selected model and auto-compaction limit consistent between terminal and T3 sessions.
8. Verify that a long-running task continues after normal compaction instead of silently stopping.

Do not copy another person's T3 session data or project history.

FILES, OWNERSHIP, AND INSTALLATION

Choose paths after discovery. Do not assume a particular username, package-manager prefix, or CPU architecture.

Use one tool-owned private directory under the current user's Library folder, owner-only, keeping source code, private configuration, logs, and provider-owned login files separate. Provider credential records stay in the proxy's private authentication directory, outside any installed bundle and outside any source repository, and everything this build installs treats them as read-only. The routing-state writer creates its own directory as mode 0700 and publishes its non-secret snapshot atomically as mode 0600.

Before writing private data, verify the parent directory owner, refuse unsafe symbolic links, set strict permissions, stage new files in a temporary directory, validate them, and move them into place atomically when practical. Any staging directory that may contain private data must be owner-only with mode 0700.

Create a small ownership receipt listing only files and settings created by this setup, with no secrets in it, and use it for doctor, repair, and uninstall. On setup failure, remove only files created during that run and restore only files that run changed and backed up. Do not build a general rollback system.

Handle these starting states safely: a clean Mac with no related tools; official clients installed but not logged in; official clients installed and logged in; existing supported provider profiles; an existing local proxy owned by this tool; an existing foreign proxy or conflicting configuration; an existing routing guard or routing-state writer owned by something else; an interrupted earlier setup owned by this tool; and an existing installed component with the same name or application identifier.

Refuse to overwrite foreign files or configurations. Explain the conflict and ask the user what to do.

START AT LOGIN

If the user approves automatic startup, use a per-user LaunchAgent rather than a system daemon. It must run as the current user, use absolute discovered paths, store no secret directly in the plist, write only redacted size-limited logs, start at load and relaunch after a crash or nonzero exit without a tight crash loop, respect a normal Quit instead of immediately relaunching something the user just closed, and stop cleanly during uninstall.

DOCTOR COMMAND

The reference project does not yet have a complete doctor command. Treat this as a requested addition you must build and test, not an observed feature. Provide one read-only doctor command with stable PASS, WARN, and FAIL results.

Doctor should check:

1. Supported macOS and tool versions.
2. Installed launcher paths, and the status app path if one was built.
3. Ownership and permissions on every owned file, including the proxy configuration at 0600 and the authentication directory at 0700.
4. Unsafe symbolic links.
5. Required local service state.
6. Listener address and port.
7. Local authentication, without printing the key.
8. Credential record count per provider, and how many are currently eligible versus cooling.
9. The effective routing strategy, retry, and cooldown settings actually loaded by the running service.
10. Provider login status through documented commands.
11. Time since the observer's last completed pool refresh, against the 60-second cycle.
12. Per-account observation freshness against the 90-second ceiling.
13. Whether the routing-state writer is enabled, and the snapshot's age and file mode.
14. Whether the routing guard is loaded, its plugin interface compatibility, and the effective drain policy values.
15. Single-instance process state for the observer.
16. LaunchAgent state, when used.
17. T3 configuration, when enabled.
18. Status app state and update state, only when a status app was built.
19. Conflicts and stale owned files.

Checks 11 through 15 apply only when the observer and guard were installed, which is full-fidelity mode only; in SUPPORTED-ONLY MODE they report Not applicable rather than FAIL. Check 18 reports Not applicable when no status app was built.

Doctor must not make live model requests by default. A live smoke test is a separate, clearly labeled, user-approved action because it may consume paid usage.

REPAIR

The reference project does not yet have a complete repair implementation; build and test it. Provide narrow repair actions instead of one destructive repair button. Examples:

1. Restart the local proxy service.
2. Reload the authentication directory after adding or removing a credential.
3. Reinstall an owned launcher.
4. Correct permissions on owned files, including the proxy configuration and the routing snapshot directory.
5. Restart the usage observer.
6. Re-enable or disable routing publication.
7. Reload or reinstall the routing guard plugin.
8. Rebuild and reinstall the optional status app, when one was built.
9. Restore an owned T3 settings backup after approval.

Actions 5 through 7 apply only in full-fidelity mode; action 8 only when a status app exists.

Account re-authentication is not a repair button. It is an external login operation; the repair flow may print the exact command for the user to run, and nothing more. No repair action may edit, move, or rewrite a provider credential record. Every repair action must say what it will change before it runs.

UNINSTALL

Provide one clear uninstall command or script. The reference project provides a local build and install path only, so treat doctor, repair, safe rollback, and full uninstall as additions you must build and test.

Use this order:

1. Quit and remove the optional status app, its user settings, and its encrypted private-update credential, if one was built.
2. Stop the usage observer and remove its login item or LaunchAgent, along with its bounded logs.
3. Remove the owned routing snapshot file and its owner-only directory.
4. Remove the routing guard plugin and its configuration block, and confirm the proxy still starts cleanly without it.
5. Remove the launchers created by this setup.
6. Undo only PATH, alias, or shell changes recorded by this setup.
7. Restore only T3 settings backed up and changed by this setup.
8. Stop the proxy service.
9. Ask whether the user wants to uninstall the proxy package or keep it.
10. Remove the owned proxy configuration, ownership receipt, redacted logs, and local client key.
11. Ask separately whether to preserve or delete the proxy's OAuth account directory. Recommend preserving it unless the user wants every authorized account removed.
12. Run discovery again and report every remaining related item.

Step 1 applies only when a status app was built. Steps 2 through 4 apply only when the observer, snapshot, and guard were installed, which happens only in full-fidelity mode.

Uninstall must stop owned processes and LaunchAgents; remove only items listed in the ownership receipt; restore a backed-up setting only when this setup changed it and the user approves; preserve provider-owned credential records by default and ask separately before removing provider login data; leave unrelated Claude, Codex, ChatGPT, T3, package-manager, shell, and proxy installations untouched; be safe to run a second time; and report what was removed, what was preserved, and any manual cleanup left.

TESTING

Use automated tests where possible and manual tests only where macOS UI or official browser login requires them.

Cover at least these safety cases:

1. Clean user account, and zero provider accounts.
2. Claude only, Codex only, and both providers.
3. Several credentials for one provider, and rotation across them.
4. Missing login, expired login, and authentication rejected.
5. Unreadable credential record.
6. Unsupported usage data, and a malformed provider response.
7. Network offline, and a provider rate limit or temporary failure.
8. Every credential for a provider cooling at once, producing the all-credentials-cooling 429.
9. Local proxy stopped.
10. Port conflict, including the OAuth callback port.
11. Keychain access denied.
12. Existing foreign configuration.
13. Routing guard installed but routing state missing or stale.
14. Interrupted setup, and a second setup run.
15. Mac restart.
16. T3 fresh task and resumed task, when enabled.
17. Repair.
18. Uninstall, and a second uninstall run.

Also cover these behavior cases. The rotation cases matter most, because rotation is the deliverable. Cases 4 and 7 through 9 are full-fidelity mode only, and case 11 applies only if a status view was built:

1. Stock rotation across several credentials for one provider, verified from proxy logs on fresh sessions rather than inferred from client behavior.
2. Automatic retry onto a second credential when the first fails, and cooldown skipping of a credential that hit a limit.
3. Session affinity holding a session on one credential for its TTL, and releasing it when the TTL lapses.
4. The 99 percent exhaustion cutoff, the 90 percent short-window headroom split, soonest-future-weekly-reset ordering, unknown-state fail-closed behavior, and credits unlocking only after every included subscription is freshly exhausted.
5. Canonical de-duplication and deterministic preferred-credential selection.
6. Strict Claude and Codex response decoding, including the model-specific fallback order and Codex window mapping by duration, validated against responses you actually observed.
7. The 90-second freshness ceiling and the provider-specific last-good rules, including Claude retention across transient failures and Codex live-only usability.
8. Sliding one-hour guard affinity, extension on each successful selection, and immediate rebinding when the bound account becomes ineligible.
9. Observer pacing and limits: about one second between account fetches, the 15-second request timeout, the three-minute retry-wait cap, and coalescing of overlapping refreshes.
10. Credential handling: credentials present in the privileged process only while a request is in flight, absent from any message sent to a display process, absent from logs and diagnostics, and absent from built artifacts and source maps. Keep these tests even if the status app is trimmed or skipped, and apply them to the observer.
11. If a status view exists: it renders from the shared snapshot without drift, shows Unavailable rather than inventing data, marks retained data as retained, and shows an explicit unavailable state instead of empty rows when its data source is missing.

Decoding, routing, pacing, usability, and snapshot behavior are all unit-testable without any user interface.

Verify these observable results:

1. Local services listen only on 127.0.0.1.
2. Private files have safe ownership and permissions, including the proxy configuration at 0600, the authentication directory at 0700, and the routing snapshot at 0600.
3. Logs, packaged resources, and source maps contain no secrets.
4. Normal provider commands still work.
5. Namespaced launchers preserve arguments, streams, signals, working directory, and exit code.
6. Adding one more credential increases the pool without any configuration change beyond a reload.
7. Requests continue to succeed after one account is exhausted or fails, because another account picked them up.
8. Claude and Codex counts remain separate wherever they are reported.
9. Unsupported values report as unavailable, not zero.
10. Reading usage never changes credential records or login state, and changes routing state only when publication is explicitly enabled.
11. Uninstall removes only owned items.

Do not run live account tests in public CI. Use the current user's approved local test accounts only for the minimum live checks, and explain any usage cost first.

PRIVACY AND IDENTITY SCAN

Before delivery, scan every created source file, document, fixture, log sample, packaged resource, source map, release metadata file, updater configuration, routing-state fixture, and image for:

1. Real email addresses, account labels, usernames, and home paths.
2. Company, organization, and client names; machine names and remote aliases; repository names and owners unrelated to this project.
3. Tokens, API keys, client keys, credential hashes, cookies, and authorization headers.
4. OAuth cache contents, credential record names, and provider account identifiers.
5. Secret-manager names or project identifiers.
6. Real application identifiers, signing identities, and LaunchAgent labels from another setup.
7. Private agent instructions, task history, and T3 session data.
8. Model identifiers, launcher names, and paths inherited from another person's setup rather than discovered on this Mac.

Use neutral placeholders everywhere: masked account labels such as Account 1, opaque identifiers such as provider-account-a, and generic paths such as <USER_HOME>/<APP_PRIVATE_DIR>. Do not build fixtures from realistic addresses copied out of local data.

Do not claim the scan proves no secret exists; report the scan method and results so the user can review them.

DELIVERABLES

Provide the smallest complete local package. Required, in priority order:

1. The proxy configuration file for this Mac, with the local client key sourced from Keychain rather than written into any shared artifact.
2. A short written record of how many credentials the pool holds per provider, the effective routing strategy, and the retry and cooldown settings in use.
3. A safe setup command or script that installs the proxy, writes that configuration, and walks the user through authorizing each account, plus the startup job if approved.
4. Namespaced launchers, if selected and supported.
5. Automated tests, at minimum the rotation, retry, cooling, and credential-handling cases.
6. Doctor, repair, and uninstall commands.
7. A short local setup guide whose first and longest part is installing the proxy, configuring it, and adding accounts.
8. A security and privacy note repeating the named provider-policy risks and the possible consequences in plain words.
9. The ownership receipt created during setup.

Conditional, only when the matching option was approved:

1. The usage observer, runnable headless, plus the routing-state writer behind its persisted enable setting. Full-fidelity mode only.
2. Routing guard source and build instructions, plus a generic proxy plugin configuration example with placeholders for every path, credential, and hash. Full-fidelity mode only.
3. Optional T3 configuration instructions.
4. The optional status app source, its dependency lockfile, build command, packaging configuration, and neutral icons, only if the user asked for a status view. This is the lowest-priority item in the whole build; do not let it delay or complicate the rotation work.

An updater is optional and applies only to a status app. Include it only if the reader wants one, pointed at that reader's own release repository, application identifier, and signing identity. With no signing setup, ship an unsigned local build and say so plainly in the setup guide.

Use dependencies already present on the Mac when suitable, and check current library documentation before adding packages. Avoid adding a web server, database, analytics service, cloud backend, or remote control plane unless the user separately approves a real need.

Nothing you build may become the owner of provider credentials. Keep provider authentication in the official clients and in the proxy's own login flow.

FINAL REPORT

At completion, give the user a plain-English report containing:

1. What was built, installed, changed, and preserved.
2. Every owned path.
3. How many credentials the pool holds per provider, as counts and masked generic labels only. Never include a real account label or provider account identifier.
4. Exactly how to add one more account later, in one or two lines. This is the capability the user is keeping.
5. The effective routing strategy, retry count, retry-credential cap, retry interval, cooldown settings, and session-affinity setting actually loaded by the running service.
6. Evidence that rotation and failover were observed working across the pool, described without secrets.
7. Which authentication methods are active, without secrets.
8. Whether the usage observer and quota-aware guard were installed at all, and if so whether the guard is loaded and active, and the drain policy values in use.
9. Whether routing publication is enabled, and the observed freshness of the routing snapshot.
10. Whether an optional status app was built, and if so whether signing, notarization, and updates were configured or whether it is an unsigned local build. Say plainly that this piece is cosmetic and rotation does not depend on it.
11. Which tests passed and failed, and which live tests consumed usage.
12. Any unsupported request that was excluded, and any manual task that remains.
13. The doctor command, the repair commands, and the exact uninstall command.
14. Which build mode was approved, with a restatement of the provider-policy risks that mode carries and what happens if a provider objects.
15. Every operational detail you could not verify, listed plainly as unverified, including model identifiers, environment variable names, proxy configuration keys, request headers, and response shapes.

STOP CONDITIONS

Stop and ask the user before continuing when:

1. Provider documentation does not clearly support the requested authentication or routing design.
2. An existing configuration would be overwritten.
3. A required action could remove or expose credentials.
4. FULL-FIDELITY MODE was not explicitly approved, or current provider rules changed after approval.
5. The installed proxy version does not support a compatible scheduler plugin interface for the routing guard.
6. You cannot guarantee that the guard fails closed when routing state is missing, stale, invalid, or contradictory.
7. Another process already writes a routing-state file the guard would read.
8. You are building a status view and cannot keep its display process isolated from credential material, or context isolation and sandboxing cannot be enabled. Dropping the view and keeping the rotation is an acceptable resolution.
9. A paid service or new subscription is required.
10. T3 behavior cannot be verified from its current source or documentation.
11. A test could change billing, account status, or production data.
12. Setup cannot be completed without weakening localhost, file-permission, or secret-handling rules.
13. You cannot verify a model identifier, environment variable name, configuration key, request header, or response shape, and would have to guess it.
14. Disabling or removing an account has no documented mechanism, and the only remaining option would be editing a credential record directly.
15. The user has not read their providers' current consumer subscription terms, and you are about to build FULL-FIDELITY MODE.

BEGIN

Start now with read-only discovery only. Return the discovery report, supported and unsupported scope, proposed architecture, exact planned changes, human choices, test plan, and uninstall plan.

The proposal must lead with the proxy engine, because that is the deliverable: where it will be installed, how its configuration will be written, how many credentials the pool will hold per provider, how the user adds more later, and what rotation, retry, cooling, and affinity settings will be used. Then cover the optional routing guard, its usage observer, and whether routing publication will be enabled. Mention any status view last, in a sentence or two, and say plainly that it is optional and can be dropped.

Present the risk disclosure and both build modes, including the honest description of what SUPPORTED-ONLY MODE produces today, and get an explicit mode choice.

Do not implement anything until the user approves that report.
