# Multi-Profile Support [← Back to README](../README.md) Meridian can route requests to different Claude accounts. Each **profile** is a named auth context — a separate Claude login with its own OAuth tokens. Switch between personal and work accounts, or share a single Meridian instance across teams. ### Adding profiles ```bash # Add your personal account meridian profile add personal # → Opens browser for Claude login # Add your work account (sign out of claude.ai first, then sign into the work account) meridian profile add work ``` Or add one from the Profiles page without a terminal at all — see [From the web UI: add a profile](#from-the-web-ui-add-a-profile). > **⚠ Important:** Claude's OAuth reuses your browser session. Before adding a second account, sign out of claude.ai and sign into the other account first. #### Headless / SSH: complete Claude OAuth with a pasted code When you still want a normal Claude Max browser-login profile but the Meridian host cannot open a browser (SSH, WSL, containers, remote servers), use `--headless`. Meridian prints a Claude OAuth URL, prompts for the returned code, exchanges it with PKCE, and saves the resulting credentials into the profile's isolated `CLAUDE_CONFIG_DIR`: ```bash meridian profile add work --headless ``` Open the printed URL in a browser, sign in to the target Claude account, then paste the returned code at Meridian's `Paste code:` prompt. For an existing browser-login profile: ```bash meridian profile login work --headless ``` The same login also records the account's plan (`subscriptionType`, `rateLimitTier`), read from Anthropic's OAuth profile endpoint — the token exchange itself returns no plan information. That is what lets `meridian profile list`, `/profiles/list`, `/health` and the dashboard tell a Max account from a Team one, and what makes `/v1/models` advertise the larger context window Max accounts actually have. If the lookup fails the login still succeeds and the plan simply stays unknown. Plans change while a login stays valid - an upgrade from Pro to Max, a Team seat moved to another tier - so Meridian re-reads the plan every six hours as part of its background credential maintenance, and takes the plan the endpoint reports when it differs from the stored one. A field the endpoint omits keeps its stored value, a failed lookup is retried after five minutes, and requests never wait on the lookup. A read-only instance (`MERIDIAN_CREDENTIALS_READONLY`) does not re-read plans. #### From the web UI: re-authenticate a profile without a terminal A profile whose credentials expired can be logged in again from the Profiles page, with no shell on the Meridian host. Click **Log in from browser** on the profile's card, sign in to that profile's Claude account, and you are done — Claude sends you back to Meridian, which finishes the login and updates the card. There is nothing to copy and paste. Browser login requires an explicit `claudeConfigDir` on the profile or an inherited `CLAUDE_CONFIG_DIR`, so credentials go to the same location model requests use. An implicit default credential context is refused rather than silently creating an unused profile directory. Profiles created by Meridian already have an explicit directory. While a token exchange is running, status polling continues to report the login as waiting; duplicate completions cannot redeem the code again. **It is an ordinary link, and that is deliberate.** If you are signed into several Claude accounts, the session your main browser offers is often the wrong one for the profile you are re-authenticating. Because the control is a real `` carrying the authorize URL, the browser's own context menu applies: **Open Link in Incognito Window**, **Open Link in New Private Window**, or **Copy Link Address** to paste into a different browser or browser profile. The login still lands on the profile it was started for — the PKCE verifier and `state` live on the server, keyed by `state`, so the browser that finishes the sign-in does not have to be the one that started it, and the page you started from notices and updates itself. Nothing secret is in the link: the authorize URL is public by design, and the verifier never leaves the server. That works whenever the **browser** is on the machine Meridian runs on — including through an SSH port-forward, and including when you reached the UI by some other name such as a LAN or tailnet hostname. What matters is the browser's position, not the URL in its address bar, so the page settles it by measurement: before opening the sign-in tab it asks the browser to reach Meridian on loopback, and takes the redirect flow only if that answers. A browser on a *different* machine cannot reach it, the check fails in under two seconds, and the panel asks for the code instead. Either form is accepted: the **bare code** Claude shows you, or the **whole callback URL** from the address bar (`https://platform.claude.com/oauth/code/callback?code=…&state=…`), which is usually easier to copy. The redirect flow also offers **Paste a code instead** as a manual fallback, which does not restart anything — both sign-in URLs belong to the same login. **Why the browser sometimes has to be on the same host.** Anthropic publishes the Claude Code client's registration at [`https://claude.ai/oauth/claude-code-client-metadata`](https://claude.ai/oauth/claude-code-client-metadata), and it declares exactly three ways back: ```json "redirect_uris": ["http://localhost/callback", "http://127.0.0.1/callback"] ``` plus the hosted code-display page, `https://platform.claude.com/oauth/code/callback`. The loopback pair is the [RFC 8252 §7.3](https://datatracker.ietf.org/doc/html/rfc8252#section-7.3) convention, where the port is not part of the match — which is why Meridian can use whichever port you reached it on. A redirect URI belonging to *your* hostname cannot be added to Anthropic's registration, so it would be rejected at the authorize step; the paste flow is what remains for that case. For scripting, the same login is three routes: ```bash # mode is "redirect" when the Host you call with is a loopback address, else "paste". # In "paste" mode the reply also carries loopbackAuthorizeUrl + loopbackProbeUrl: # fetch the probe, and if it answers {"status":"waiting"} you can use the # loopback URL after all — that is exactly what the web UI does. # → {"loginId":"…","mode":"redirect","authorizeUrl":"…","pasteAuthorizeUrl":"…","expiresAt":…,"profile":"work"} curl -X POST http://127.0.0.1:3456/profiles/login/start \ -H 'Content-Type: application/json' -d '{"profile":"work"}' # → {"status":"waiting"|"completed"|"failed", "profileId":"work", …} curl 'http://127.0.0.1:3456/profiles/login/status?loginId=…' # only needed for the paste path; `code` accepts the bare code or the full callback URL curl -X POST http://127.0.0.1:3456/profiles/login/complete \ -H 'Content-Type: application/json' -d '{"loginId":"…","code":"…"}' ``` Details worth knowing: - The PKCE verifier never leaves the server. The browser only ever holds an opaque login id. - The loopback check the page runs is that login's own `/profiles/login/status` URL, so a reply proves both that the browser can reach loopback *and* that what answered is the instance holding this login. Anything else listening on the port answers 410 and the paste flow stands. - A login is **single-use** and expires **10 minutes** after it starts. `state` must match the login it was started with, exactly as the CLI requires; on the redirect path that `state` is what identifies the login at all. - `GET /callback` is deliberately **not** behind `MERIDIAN_API_KEY` — Anthropic's redirect carries no key. It acts only on an unguessable, single-use `state` minted by `/profiles/login/start`, which *is* gated, and answers 410 to anything else. - Only **claude-max** profiles have this flow. `api` and `oauth-token` profiles are refused with the reason — replace an OAuth token with `meridian profile remove && meridian profile add --oauth-token`. - An unknown profile name is refused here rather than created — a typo in a re-authentication must not quietly produce a second account slot. Creating one is a separate, explicit act: see [Add a profile from the web UI](#from-the-web-ui-add-a-profile) below. - An instance told not to write credential files (`MERIDIAN_CREDENTIALS_READONLY=1` — set on a second instance that shares another's credentials) refuses **before** opening the sign-in tab, and names where the login can be completed instead. Refusing after sign-in would have burned a one-time code for nothing. #### From the web UI: add a profile A new Claude account can be added from the Profiles page without a shell on the Meridian host. Under **Add a profile**, type a name and click **Add profile**: 1. Meridian validates the name, refuses it if anything is wrong, then mints the PKCE login and opens Claude's sign-in in a new tab. 2. Sign in to the Claude account this profile should use. Claude shows you a code. 3. Paste it back — the **bare code** or the **whole callback URL**, exactly as for a re-login. The profile appears in the list with its own exclusive directory under `~/.config/meridian/profiles/.add-*/`, recorded as `claudeConfigDir` in `profiles.json`, ready to use with no restart. The directory is not derived from the requested name: a concurrent creation that loses that name cannot overwrite the winner's credentials. ```bash # → {"addId":"…","authorizeUrl":"https://claude.com/cai/oauth/authorize?…","expiresAt":…,"profile":"work"} curl -X POST http://127.0.0.1:3456/profiles/add/start \ -H 'Content-Type: application/json' -d '{"profile":"work"}' # `code` accepts the bare code or the full callback URL curl -X POST http://127.0.0.1:3456/profiles/add/complete \ -H 'Content-Type: application/json' -d '{"addId":"…","code":"…"}' ``` **No profile entry is written until the credentials are in hand.** The exchange uses an exclusive directory; the `profiles.json` entry is written only once it succeeds and the name is still available. Rejected attempts remove their own directory and never change the winning profile's credentials. On macOS, the existing credential-store API cannot delete an unreferenced Keychain item left by a rejected creation. Just start again with an available name. **Who can do this.** These routes inherit `/profiles/*`'s `requireAuth`, so they are behind `MERIDIAN_API_KEY` **when that key is set**. When it is not set - the default - the only thing standing between this page and account changes is whatever reaches the port: bind Meridian to loopback, or to a private network you trust. The page also supports renaming through its separate rename route, and removal through the trash can on each card. Details worth knowing: - Names may use only letters, numbers, hyphens and underscores, using the same validation as `meridian profile add`. - An existing name is refused and points you at **Log in from browser** on that profile's card — re-authenticating an account is what that button is for. - Starting another sign-in for the same name replaces an attempt that has not begun exchanging its code. An exchange already in progress can finish, but the first attempt to publish the profile wins; a later completion returns `profile_exists` without changing the winner's credentials. - `MERIDIAN_CREDENTIALS_READONLY=1` refuses **before** the sign-in tab opens, and names `meridian profile add ` as the alternative. - Only **claude-max** profiles are created this way. `api` and `oauth-token` profiles are CLI-only — neither has an OAuth flow to drive from a page. - **The `~/.claude` import offer is CLI-only.** `meridian profile add` on a host whose default config dir is already signed in offers to adopt those credentials as the new profile. The UI never does: clicking **Add profile** always signs in fresh. Silently claiming the account you happen to be logged in as on that machine is not something a button press should be able to do. #### Headless / CI: register an OAuth token When a browser isn't available (containers, CI runners, remote shells), generate a long-lived OAuth token with `claude setup-token` and register it as a profile: ```bash # Prompt for the token (input is hidden — paste the value from `claude setup-token`) meridian profile add ci --oauth-token # Or pass it inline meridian profile add ci --oauth-token sk-ant-oat01-... ``` OAuth-token profiles store the token in `profiles.json` and feed it to the SDK via `CLAUDE_CODE_OAUTH_TOKEN` — no Keychain entry, no browser handshake. To prevent the SDK's 401-recovery from silently falling back to the host's `~/.claude` credentials, OAuth-token profiles also pin `CLAUDE_CONFIG_DIR` to an isolated per-profile directory under `~/.config/meridian/profiles//`. That directory holds only SDK state (sessions, settings) — never `.credentials.json`, since the token is delivered through the env. ### Removing a profile The trash can on a Claude profile's card asks for confirmation, then calls `POST /profiles/claude/remove`, which does what `meridian profile remove ` does: - the entry leaves `profiles.json` first, then the credential directory it owns is deleted: a browser-login profile's `claudeConfigDir` only when it lives under `~/.config/meridian/profiles/` (a profile pointed at `~/.claude` never takes the host's own credentials with it), and an `oauth-token` profile's directory at `profiles/`; - the name and the former names that redirected to it leave the saved failover order; - when it was the active profile, the first remaining profile becomes active. ```bash # → {"success":true,"profile":"work","provider":"claude","activeProfile":"personal","remaining":["personal"],"dirsOrphaned":[]} curl -X POST http://127.0.0.1:3456/profiles/claude/remove \ -H 'Content-Type: application/json' -d '{"profile":"work"}' ``` The name must be the profile's current one: a former name is refused with the profile that holds it now. A directory that could not be deleted is listed in `dirsOrphaned`; the profile is removed regardless. Browser writes must come from the same origin, and `MERIDIAN_CREDENTIALS_READONLY=1` refuses the route (403) and the CLI alike. A profile defined in the startup configuration, or adopted from the instance named by `MERIDIAN_FOLLOW_ACTIVE`, is refused with `409 owned_elsewhere`: remove it where it is defined. ### Current login expiry Meridian preserves a valid refresh deadline when its OAuth token exchange reports one. The Profiles page and home details show this account's current stored refresh deadline and access-token expiry, with the exact recorded time on hover or keyboard focus. Access expiry may be estimated when the provider omits it. Authentication is checked separately: a deadline does not prove logout, revocation, a fixed login lifetime or how long an account will serve requests. `GET /profiles/list` adds four fields, read from one fresh snapshot of each stored-Claude profile's own credential: | Field | Meaning | | --- | --- | | `refreshTokenExpiresAt` | Current stored refresh deadline in epoch milliseconds, or `null` when unavailable | | `daysUntilRenewal` | `Math.ceil((refreshTokenExpiresAt - now) / 86400000)`, or `null`; zero includes a deadline less than one day past | | `renewalRequiredSoon` | Rounded days are at or below `MERIDIAN_AUTH_RENEWAL_WARN_DAYS` (default 3), matching `/health`; false with a null deadline means unknown/not applicable | | `accessTokenExpiresAt` | Current stored access-token expiry in epoch milliseconds, or `null`; advisory and possibly estimated | API-key and supplied setup-token profiles report null timestamps/day count and false without consulting the host's stored login. Failed credential reads also return unavailable expiry facts and preserve the existing authentication provenance. A changed or missing current deadline replaces the displayed value. ### Login history Claude Code wipes `.credentials.json` once a refresh is refused, and with it everything about the login. Meridian keeps its own record of each stored credential in `auth-lifecycle.json` beside `settings.json`: when the login happened, when Meridian last renewed it, and when the account was first found logged out and why. It never holds a token. Every transition is logged (`[PROXY] Profile "work" logged out: ...`, naming the deadline and how long the login lasted) and kept in the diagnostics log under `auth`. `GET /profiles/list` adds five fields to every profile, `null` when nothing is on record or the profile has no stored login: | Field | Meaning | | --- | --- | | `authObtainedAt` | When the current login happened (epoch ms); `null` when a replaced credential cannot be dated | | `authObtainedVia` | `login` when Meridian performed it, `observed` when a new login was found on disk (then `authObtainedAt` is when Meridian noticed it) | | `lastRefreshAt` | Meridian's last renewal of this login; a renewal by a Claude Code process is not seen | | `firstUnauthedAt` | When authentication was first found failing; cleared by a new login or a renewal that works | | `unauthedReason` | `refresh_rejected` (Anthropic answered `invalid_grant` for the stored refresh token) or `credentials_cleared` (the stored credential has no access token) | A refused renewal is not yet a logout: the account keeps serving until its access token expires, so `loggedIn` stays as `claude auth status` reports it and the card shows **Renewal refused, stops in …**. After that expiry, or once the credential is cleared, `loggedIn` is `false` and the card shows **Logged out … ago** with the reason on hover. Cards also show **Logged in … ago**, saying on hover whether Meridian performed the login or found it. Other OAuth errors, outages and stores that cannot be read record nothing. A different refresh token with a different deadline is a new login; one that cannot be told apart from a rotation of the old login is recorded without a login time instead of a wrong one. The history is best-effort. Renewals and `/profiles/list` write it in the background and never wait for it, so a problem with `auth-lifecycle.json` (such as a lock file left by a crashed process) only drops history entries; it never slows a request. Removing a profile deletes the history of the credentials it removes, and renaming one carries the history to the new name. ### Duplicate profiles Signing a profile in from a browser that is still signed in to another account leaves two profiles holding one account: two names, one quota. Meridian flags them. Each such card on `/` and `/profiles` carries a **duplicate of <other>** badge naming the other profile, so you can sign one of them in to the account it was meant for, or remove it. Nothing is removed, renamed or excluded automatically. `GET /profiles/list` reports two fields on every profile: | Field | Meaning | | --- | --- | | `duplicateOf` | Ids of the other profiles signed in to the same account, `[]` when there are none | | `duplicateBasis` | What proved it, or `null`: `account-organization`, `email-organization`, `seat` or `workspace-email` | One person legitimately holds several subscriptions - a personal plan and seats in several Team organizations - so an email alone never makes a duplicate. A Claude account is its account UUID **and** organization UUID, as `GET /api/oauth/profile` reports them. When a read for the current credential did not report them for one of the two profiles, the email **and** organization name stand in, and `duplicateBasis` says `email-organization`. A ChatGPT seat is its seat id, or the same email in the same workspace. Profiles of different providers never match. The account is read again whenever the stored credential changes - a login, a re-login or a token renewal - instead of waiting for the daily refresh, so a re-login into the right account clears the flag on the next poll. Until that read lands, the account recorded for the previous credential is not used: the profile is not flagged from it, and its email comes from `claude auth status`. Once it lands, the email shown is the one Anthropic reported for the credential the profile holds now. The badge itself changes nothing; priority routing acts only on the stricter proof described under [Priority failover routing](#priority-failover-routing). ### After a sign-in A finished sign-in (re-login by paste or redirect, adding a profile, connecting or re-signing a ChatGPT seat) is followed by the reads that say who it signed in as, its plan and its usage. Until they land, the profile's card stays where it is and shows **Updating with the new sign-in…**; if they fail, it shows the reason. On `/profiles` the card also stays visible during a search that no longer matches it, such as a search for the email it was signed in as before. `GET /profiles/list` reports the state as `factsRefresh`: `null` when idle, `{ "state": "updating", "since" }`, or `{ "state": "failed", "since", "at", "error" }` for five minutes after a failed read. `/` and `/profiles` refresh every ten seconds by updating each card in place, keyed by profile id, rather than redrawing the list, so the browser's find-in-page, a text selection, focus and scroll position survive a refresh. ### ChatGPT seats An instance serving [ChatGPT subscriptions](configuration.md#chatgpt-subscriptions) lists each seat as a profile of `type: "chatgpt"` beside the Claude ones, and the same commands and routes act on it. Each provider keeps its own active account, so switching a seat never moves the Claude pointer. Meridian renews each seat in its own store on the eighth day of its ten-day access token, whether or not work is sent to it, one seat per minute at most (`[chatgpt] renewing account … ahead of expiry`). A request renews only the seat it is routed to, so without this a seat no work goes to runs out and cannot serve though nothing refused it. A failed exchange leaves its seat needing a sign-in, so after OpenAI fails one, renewing ahead of expiry pauses for six hours. While a renewal is out, the seat is listed as it was before it: it reads as needing a sign-in only once the exchange fails, or when a stamp is left by one that never finished. chatgpt.com sometimes refuses a seat's access token while its refresh token is still good. Meridian then renews the seat on its own within a minute (`[chatgpt] renewing account …: chatgpt.com refused its access token`), and the card shows "Next renewal" instead of asking for a sign-in. When the renewed token is refused too, it renews again 5 minutes later, then 30 minutes, 2 hours, and every 6 hours after that. A read that chatgpt.com accepts in between does not restart that schedule; only six hours without a refusal does. A day after the first refusal Meridian stops renewing (`[chatgpt] chatgpt.com kept refusing account …`) and the seat needs a sign-in, since a refusal a fresh token does not fix, such as a deactivated workspace, needs attention. The seat also needs a sign-in once OpenAI refuses the refresh itself, or a renewal's result cannot be established; a refresh token that may already have been spent is never sent again. `GET /profiles/list` reports the next attempt as `renewalRetryAt`. An instance with `MERIDIAN_CREDENTIALS_READONLY=1` cannot see another instance's exchanges, so it can take up to about 20 seconds to show a failed renewal. When OpenAI refuses a renewal, the log line and the `cause` field of `POST /profiles/chatgpt/refresh` name which refusal it was: `refresh token expired`, `refresh token already used` (another program renewed the same login first) or `refresh token revoked`. A failure on OpenAI's side records `HTTP ` instead. A seat in Meridian's own store can be given its own renewal interval in hours, from 6 to 240: **Renew every** on its card, or `PATCH /settings/api/chatgpt` with `{"seatRenewalHours": {"": 24}}`, where `null` removes it. That seat is then renewed that long after its access token was issued, never later than a request would renew it; a token that does not say when it was issued is still left to the request path. The renewal pass reads the intervals every minute, so a change applies without a restart, and removing the seat drops its interval. Every other seat keeps the eighth day. `GET /settings/api/chatgpt` lists each seat's `renewalHours`, and the renewal log line names the interval. It exists to measure whether renewing more often changes how long a sign-in lasts. The six-hour minimum is there because each renewal spends the seat's refresh token, and a renewal that auth.openai.com throttles or fails logs the seat out; a saved interval below it is ignored. An instance with `MERIDIAN_CREDENTIALS_READONLY=1` never renews, interval or not. Each such seat keeps its latest 64 renewals with its record in the store, and `/profiles/list` lists them under `renewals`, oldest first, beside `renewalHours` (`null` for the default): when, the `outcome` (`rotated` or `kept`, whether OpenAI issued a new refresh token; `refused`; or `unverified`, a failure on OpenAI's side), the `cause` of a refusal or failure, and the new access token's `issuedAt` and `expiresAt`. An attempt that never reached OpenAI, such as one after an interrupted exchange, records nothing. The card shows the interval under **Renewal** and the latest entry under **Last renewal**, with the ones before it in its tooltip. A seat whose login another tool owns has `renewalHours: null` and `renewals: []`. ### Switching profiles ```bash # CLI (while proxy is running) meridian profile switch work # Per-request header (any agent) curl -H "x-meridian-profile: work" ... ``` A request with the header runs on that account or fails; it is never failed over to another one. A header naming a profile this Meridian does not have is answered `400` with error type `unknown_profile` rather than served from another account. You can also switch profiles from the web UI — click an account card on the home page (`http://127.0.0.1:3456/`) or use the Profiles page at `/profiles`. The site header on every page shows which profile is active. ### Filter accounts by login state With two or more accounts, `/` and `/profiles` show login-state chips beside the provider chips: **Authenticated**, **Expires soon** and **Needs auth**, each with its count. Every account is in exactly one state. **Needs auth** is an account with the red needs-login border (logged out, or no token); **Expires soon** is a logged-in Claude account whose refresh deadline is within `MERIDIAN_AUTH_RENEWAL_WARN_DAYS` (3 days by default); every other account is **Authenticated**. All chips start on; turn one off to hide its accounts. The browser remembers the choice for both pages, and **Show all states** turns every chip back on. A link can open either page on given states without changing that remembered choice, alone or with `?provider=`: ``` /profiles?login=needs-auth /profiles?login=needs-auth&provider=claude /?login=expires-soon,needs-auth ``` An empty `?login=` turns every state chip off. A card that is updating after a sign-in stays on screen until its new state is known. ### Sticky session routing With multiple profiles (e.g. two Claude Max subscriptions), Meridian can distribute sessions across profiles automatically while preserving **session affinity** — Anthropic's prompt caching is per-account, so keeping a session on one account helps preserve its cache: ```bash MERIDIAN_ROUTING=sticky meridian # or set "routing": "sticky" in ~/.config/meridian/settings.json ``` - Each session is assigned to a profile by rendezvous hashing of its session id — **deterministic and stateless**, so assignments survive proxy restarts with no state to lose - Removing a profile reassigns its sessions; adding one moves only sessions for which the new profile wins the hash. Other assignments stay unchanged - A session's subagent/fork requests share its assignment (same session id → same account) - The `x-meridian-profile` header still overrides everything, per request - Default is `active` (all traffic to the active profile — the pre-existing behavior); sticky is opt-in Request logs show the assignment (`profile=work(sticky)`), and `GET /profiles/list` reports the current `routing` mode. ### Priority failover routing **Opt-in.** With multiple profiles, `routing = "priority"` drains an ordered account pool: unpinned requests prefer the highest-priority account, and when it can no longer serve (a spent quota window, or a subscription the account can't bill), the request **fails over automatically** to the next account in the order — usually before the client sees any error: ```bash MERIDIAN_ROUTING=priority MERIDIAN_PROFILE_ORDER=work,personal meridian # or set "routing": "priority" and "profileOrder": ["work","personal"] in # ~/.config/meridian/settings.json — both editable live at /settings # Set "priorityFailback": "next-user-turn" in the settings file to change # failback behavior. MERIDIAN_PRIORITY_FAILBACK overrides the settings value. ``` - **Conversations keep their account** while it's healthy — a session never flips accounts just because the pool preference changed (protects per-account prompt caches). A session on an exhausted account fails over and then stays on its new account. A conversation is identified by its session header when the client sends one, and otherwise by a fingerprint of its opening message and project directory — so keyless clients get the same affinity. A conversation with a session header also keeps its account across a Meridian restart: Meridian resumes it on the account that served it last. - **Failback policy**: `new-conversation` is the default and current behavior. When the preferred account recovers, new conversations use it while existing conversations stay on their fallback. With `next-user-turn`, Meridian switches an existing OpenCode or Pi conversation only on a fresh HMAC-attested, visible primary human turn, using a full-history fresh backing session on the preferred account. Hidden/title/summary/compaction, fork, subagent, keyless, malformed, replayed, and explicitly pinned requests cannot promote. Tool-loop continuations retain and atomically refresh the current route. If the preferred account refuses before content, the fallback session is retained. After assistant content, structured output, or a tool side effect, Meridian never replays the turn on another account. Pi needs the extension from `meridian setup --client pi`; other adapters retain `new-conversation` behavior. - **One-time setup for `next-user-turn`**: rerun `meridian setup` after upgrading. Setup creates `~/.config/meridian/opencode-turn.key` as a 32-byte key with mode `0600` and configures the matching V1 or V2 plugin; `meridian setup --client pi` uses the same key for the Pi extension. Missing or invalid keys fail closed: requests still work, but they cannot promote. If OpenCode or Pi and Meridian run in separate hosts or config homes, set the same 32-byte base64url `MERIDIAN_OPENCODE_ATTESTATION_KEY` in both environments instead of relying on the shared file. Attestations bind the immutable creation time of the client's user message and are accepted only for the short freshness window; an old A-B-A replay keeps A's old time even after a restart and cannot cross B's durable high-water mark. - **Exposed turns are replay-fenced durably.** Meridian records an exact attempt claim before SDK work starts and clears it only with terminal route/session finalization or a proven pre-exposure account failure. A crash, cancellation, assistant output, structured output, or tool execution leaves the claim fail-closed. Retrying the same, older, missing, or invalid attestation then returns `503` before any SDK call; only a strictly newer trusted human turn can supersede the uncertain attempt. - **Exhaustion is tracked in-memory.** A quota refusal uses that account's own reported reset time (conservative 10-minute default when unknown), refined shortly after by an authoritative check against the usage API that can extend — never shorten — the cooldown once that account's five-hour window is confirmed exhausted. A billing refusal has no reset to wait for, so it takes the conservative default unrefined — the account is simply re-probed later, since only a human can fix a subscription. The home page shows `#n in pool` and `exhausted · resets in …` badges per account. - **A quota refusal speaks for the whole account.** Profiles signed in to one Claude account share its quota, so a quota refusal on one also cools down every other profile signed in to that account at that moment, and the request moves on to a different account without trying them. Only the account and organization UUIDs read for the token each profile stores now count: a profile re-logged into another account is not affected, and the email and organization name that can raise a duplicate badge never steer routing. A billing refusal still benches only its own profile. A token renewal makes a profile's account record stale until the next read, and records are re-read when a Meridian page polls the profile list. With no page open, a twin whose token renewed is still tried once. - **A per-model weekly limit benches only that model.** When Anthropic says an account's weekly allowance for one model ran out (for example `seven_day_fable`), the pool skips that account only for requests of that model until that allowance resets; other models keep using it. Other profiles signed in to that account skip it for that model too. The account's `spent` entry on `/v1/usage/quota/all` then carries `modelFamily` (`"fable"` here); it is `null` whenever the refusal benched the whole account or nothing. - When **every** account is exhausted, the last-tried account's error is surfaced unchanged, with its own status — a pool that ran out of billing is not reported as a rate limit. - An explicit `x-meridian-profile` header always bypasses the pool (per-session pinning keeps working). - **Weekly reserve (opt-in).** Hold back part of an account's weekly allowance, for example for someone who uses that account directly outside Meridian. Once its weekly usage reaches 100% minus the reserve, the pool skips it until the weekly window resets: ```bash MERIDIAN_WEEKLY_RESERVE=personal=20 meridian # or "weeklyReserve": { "personal": 20 } in ~/.config/meridian/settings.json ``` The reserve is approximate. It reads only usage Meridian has already observed (the SDK's rate-limit events and any cached usage reads) and never makes extra usage requests, so it can land a few percent past the line, and an account Meridian has not measured yet is not held. Right after a restart that means no protection until a usage read succeeds (the dashboard and desktop app read usage while open, and the usage endpoint rate-limits), or until the SDK reports weekly usage on a response. A conversation already on the account moves to the next account on its next turn. Internal work that may only resume its existing route (for example a title or compaction request) keeps it. Cache-keepalive pings skip a held account. When every account in the pool is holding its reserve, Meridian answers `429` with a `Retry-After` for the earliest weekly reset (capped at 24 hours). Explicit `x-meridian-profile` pins and the `active`/`sticky` modes are not affected. Changes are logged as `priority.weekly_reserve_held` and `priority.weekly_reserve_released`; a value outside 1–99 or a profile name that doesn't exist is logged (`priority.weekly_reserve_invalid`, `priority.weekly_reserve_unknown_ids`) and ignored. - **Extra Usage comes last.** An account whose plan windows are spent but that keeps serving on paid Extra Usage is moved behind every account that still has plan allowance, and a conversation on it moves to such an account on its next turn. Meridian sees this from the SDK's `isUsingOverage` on the account's last response (only from its five-hour, weekly or account-wide limit; an Opus- or Sonnet-only weekly limit does not move the account for other models), or from a cached usage read that shows a spent five-hour or weekly window; it never makes extra usage requests for it. Once no account has plan allowance left, the pool uses Extra Usage in its normal order. `MERIDIAN_CLAUDE_EXTRA_USAGE` (or `"claudeExtraUsage"` in the settings file) changes this: `reserve` (default) as described, `never` stops routing to an account once it is seen on Extra Usage and answers `429` with a `Retry-After` for the earliest plan reset when no other account can take the work. `never` is not a spending cap: Meridian only learns an account is on Extra Usage from a response, so the first turn after a plan window runs out can already be paid, and internal work that must resume its existing route (such as a title or compaction request) still runs there. Set a spending limit on the account itself if you need a hard cap. With `immediately`, Meridian treats Extra Usage like plan allowance. Cache-keepalive pings never run on such an account. Changes are logged as `priority.extra_usage_last_resort`. Pins and the `active`/`sticky` modes are not affected. - Failovers are logged (`profile.failover` in the diagnostic stream; `profile=(priority)` in request lines). ### Profile commands | Command | Description | |---------|-------------| | `meridian profile add [--headless]` | Add a profile and authenticate via Claude OAuth; `--headless` prints a URL, prompts for the returned code, and stores the exchanged credentials | | `meridian profile add --oauth-token [TOKEN]` | Add a headless profile from a `claude setup-token` value (prompts when `TOKEN` is omitted) | | `meridian profile list` | List profiles and auth status | | `meridian profile switch ` | Switch the active profile (requires running proxy) | | `meridian profile login [--headless]` | Re-authenticate an expired profile, adding it first if that name has no profile yet (browser-login profiles only); `--headless` uses the URL/code flow | | `meridian profile remove ` | Remove a profile and its credentials | ### How it works Each profile stores its credentials in its configured `CLAUDE_CONFIG_DIR`. CLI-created profiles normally use `~/.config/meridian/profiles//`; browser-created profiles use an exclusive `.add-*` directory under the same parent. OAuth-token profiles use the name-derived directory layout, but the token itself lives in `~/.config/meridian/profiles.json` and is fed to the SDK via `CLAUDE_CODE_OAUTH_TOKEN`, so that directory holds only SDK state (sessions, settings) and never the credential. When a request arrives, Meridian resolves the profile in priority order: 1. `x-meridian-profile` request header (per-request override) 2. Active profile (set via `meridian profile switch` or the web UI) 3. First configured profile Session state is scoped per profile — switching accounts won't cross-contaminate conversation history. A conversation that comes back to a profile after turns on another is not resumed from the copy it left there. That copy ends where the conversation was when it left, and a resume would send it the turns taken elsewhere without the replies given there. When another profile's copy holds more of the history the client sends, the history is replayed into a fresh session instead (`diverged=moved-on-elsewhere` in the request log). The profile's own copy is still resumed when nothing elsewhere holds more, for example after a rewind to a point it holds. ### Environment variable configuration For advanced setups (CI, Docker), profiles can also be provided via environment variable: ```bash export MERIDIAN_PROFILES='[ {"id":"personal","claudeConfigDir":"/path/to/config1"}, {"id":"work","claudeConfigDir":"/path/to/config2"}, {"id":"ci","oauthToken":"sk-ant-oat01-..."} ]' export MERIDIAN_DEFAULT_PROFILE=personal meridian ``` Profile shapes: - `claudeConfigDir` — points at a `~/.claude`-style directory; uses Claude Max OAuth from that dir - `apiKey` (with optional `baseUrl`) — direct Anthropic API access; sets `ANTHROPIC_API_KEY` / `ANTHROPIC_BASE_URL` - `oauthToken` — long-lived token from `claude setup-token`; sets `CLAUDE_CODE_OAUTH_TOKEN`. Meridian creates an isolated SDK state directory automatically; no credential mount is needed When `MERIDIAN_PROFILES` is set, it takes precedence over disk-configured profiles. When unset, Meridian auto-discovers profiles from `~/.config/meridian/profiles.json` on each request. `MERIDIAN_CONFIG_DIR` moves that file and the `profiles/` directory beside it, so a second instance can keep its own accounts — see [Relocating the config directory](configuration.md#relocating-the-config-directory). Related environment variables: - `MERIDIAN_ROUTING=sticky` — enable [sticky session routing](#sticky-session-routing) across profiles (default `active`) - `MERIDIAN_ADAPTER_INSTANCES='{...}'` — define [adapter instances](agents.md#adapter-instances) inline instead of via `~/.config/meridian/adapter-instances.json`