Skip to content

Latest commit

 

History

History
246 lines (203 loc) · 68.7 KB

configuration.md

File metadata and controls

246 lines (203 loc) · 68.7 KB

Configuration

Where it lives

Config is stored at ~/.config/teamclaude.json (or $XDG_CONFIG_HOME/teamclaude.json). A random proxy API key is generated on first use.

Volatile runtime state (observed quota, per-client and per-dimension usage) is written separately to teamclaude.state.json alongside the config, so the config file stays clean and hand-editable. The state file is safe to delete — quota is simply re-learned from traffic, and usage windows refill from the next day's traffic (the lifetime counters do not come back). The samples behind the fleet forecast go to teamclaude.quota-series.json beside it, bounded to 7 days and equally safe to delete.

That file is small for a typical fleet, but it is no longer trivially small: usage is kept per 15-minute slot for a day (see Usage windows). Every client key and dimension value ever seen keeps a row of lifetime counters, as it always has, and those are never deleted; what the day of slots adds is carried only by the keys active in the last 24 hours, because a key that goes quiet drops its slots the next time it is read or written. So a dimension that merely accumulates stale values does not accumulate slots with them.

At the 500-value cap that means a file of a few MiB when every value is genuinely active at once (the file is pretty-printed, so that is bytes on disk), and on the order of a hundred KiB when the values churn — one busy day each — or when only the lifetime rows remain. The write is synchronous: serialising the all-active case costs tens of milliseconds before the fsync, once a minute. A fleet with a handful of client keys is unaffected either way, but a deployment pointing a high-cardinality dimension at this on slow storage should know the shape of it.

While the config is being rewritten — by the server rotating a refresh token, by a CLI command that saves, or by any other client — the writer holds teamclaude.json.lock next to it: a file containing {"pid":<pid>,"at":<ms epoch>}. It is an advisory lock so that separate writers wait for one another instead of overwriting each other's edit (a lost write here was typically a freshly rotated refresh token, which cost a re-login). It exists for milliseconds; a lock older than 10 s or whose pid is gone is treated as stale and removed by the next writer (one waiter at a time, under a short-lived teamclaude.json.lock.steal file, so a slower waiter does not remove the fresh lock a faster one just took; this narrows the race rather than closing it, and holds only among writers that honour that file), and a writer that cannot get it within 2 s (TEAMCLAUDE_CONFIG_LOCK_WAIT_MS) proceeds anyway, with one warning in the log, rather than hang. It is safe to delete by hand if one is left behind.

Format

{
  "proxy": {
    "port": 3456,
    "apiKey": "tc-auto-generated-key"
  },
  "upstream": "https://api.anthropic.com",
  "switchThreshold": 0.98,
  "sx": { "apiKey": "your-sx-org-api-key", "mode": "always" },
  "accounts": [
    {
      "name": "user@example.com (Acme)",
      "type": "oauth",
      "accountUuid": "...",
      "orgUuid": "...",
      "orgName": "Acme",
      "priority": 0,
      "accessToken": "sk-ant-oat01-...",
      "refreshToken": "sk-ant-ort01-...",
      "expiresAt": 1774384968427
    }
  ]
}

Fields

Field Description
proxy.port Local port the proxy listens on
proxy.host Interface to bind. Defaults to 127.0.0.1 (localhost only). Set to 0.0.0.0 (or override with env TEAMCLAUDE_HOST) to accept off-box clients — in which case set proxy.apiKey, since remote clients must present it (via x-api-key, or Proxy-Authorization for CONNECT/HTTPS-proxy usage); loopback is exempt unless proxy.trustLoopback is false
proxy.apiKey API key clients use to authenticate with the proxy (required for any non-loopback client; the proxy injects real account tokens, so an unauthenticated open port would leak them)
proxy.trustLoopback Whether a connection from 127.0.0.1 / ::1 may skip the proxy key (default true). Set it to false behind a reverse proxy on the same host — nginx or Caddy terminating TLS in front of a listener bound to 127.0.0.1 makes every caller on the internet loopback-sourced, so without this the key gate never runs and an anonymous request spends the fleet's quota. Independently of the setting, a loopback request carrying X-Forwarded-For, X-Real-IP or Forwarded is never exempt, which closes the common deployments by default; the setting covers a reverse proxy configured to send none of them. TeamClaude's own commands present proxy.apiKey on every call, so a local install keeps working either way
proxy.terminalOnly In MITM mode, tunnel chatgpt.com instead of terminating it, even when the pool holds Codex accounts (default false). For a machine that also runs the ChatGPT Desktop app: its native auth and feature endpoints then stay outside TeamClaude entirely, while the terminal Codex CLI still reaches the pool through its explicit /backend-api/codex base URL
proxy.clientKeys Optional per-client keys, one per machine or group of agents of yours: [{ "name": "laptop", "key": "tc-…" }, …]. They tell your own consumers apart in the stats and let you revoke one without touching the rest; they are not a way to hand the pool to other people (see compliance). Each entry authenticates exactly like proxy.apiKey, and the tokens its responses report are booked against name — per-client usage shows up under clients in /teamclaude/status, in teamclaude status, and (with --activity-log) as a [name] prefix on each request line. A WebSocket channel (Remote Control) opened with the key is counted under connections for that client, apart from its requests, and its open/close lines carry the same prefix. Counters persist in the state file. Traffic on the shared proxy.apiKey or the loopback exemption stays unattributed, so give every consumer its own entry when you want complete stats. An entry may set "scope": "inference" for one of your own agents or machines that should reach the model API and nothing else: it is served every path outside /teamclaude/ as usual, and gets a 403 on every /teamclaude/* route, including /teamclaude/mcp. The dashboard page still loads for it, but its status call is refused, so the page shows no data. Leave scope out, or set "full", for a key that may also read status and switch or reload. Any other value is logged once per load, and that key is treated as inference-only, so a typo narrows a key rather than removing it. A caller on the proxy's own machine that sends no key is still the operator (see proxy.trustLoopback), so a scoped agent there has to present its key. This is for your own agents, not a way to give the pool to anyone else. Edits apply live via POST /teamclaude/reload
proxy.clientKeys[].weeklyUsd Optional weekly spending limit for one client key, in US dollars at API list prices, from 0.01 up to about 9 billion. Leave it out for no limit; a value that is not such a number is reported at load and refuses that key's requests to the pool, rather than leaving it unlimited. See Weekly spending limit per client key. Edits apply live via POST /teamclaude/reload
proxy.usageDimensions Optional request-header usage dimensions: [{ "name": "project", "header": "x-teamclaude-project" }, …]. For each request the proxy reads the configured headers and books the response tokens against their sanitized values, shown under usageDimensions in /teamclaude/status, teamclaude status, and the dashboard. A request that omits a header is simply unattributed for that dimension. Counters persist in the state file, and each dimension is capped at 500 distinct values — further values are summed into (other) rather than evicting existing rows. Edits apply live via POST /teamclaude/reload
proxy.sessionDetail Adds a per-conversation breakdown (sessions.items) to /teamclaude/status and the dashboard: one row per conversation — the client session it belongs to and a digest naming the conversation within it, plus client, dimension values, pinned accounts, and the tokens it spent per weekly bucket. A session that fans out to subagents is one row per agent. A row's id is the composite session/digest key, with the halves repeated as the separate session and conversation fields; group by session, not id. Off by default — any holder of any proxy key can read status, so on a shared proxy this shows every consumer what every other consumer is working on. The aggregate sessions counts are unaffected and always present
proxy.mcp Serves an MCP management endpoint at /teamclaude/mcp. "read" exposes status, quota and the rotation settings; "full" adds the tools that change them, including removing accounts. "off" is the default, and any value other than these three is treated as "off". Read per request and picked up by a reload. The endpoint sits behind the same gates as the rest of /teamclaude/, with two of its own: a named proxy.clientKeys key is served as "read" even in "full" mode, so only the shared proxy.apiKey and key-exempt loopback callers can reconfigure the fleet, and with no proxy key configured at all it serves only loopback callers that carry no forwarding header. Deleting the key, or the whole proxy section, turns it off on the next reload
proxy.drainTimeoutSeconds Off by default (unset, or 0). A positive number of seconds turns SIGTERM into a drain: the server stops taking new requests, lets the requests already in flight finish, and exits when they have, or when the window runs out. SIGINT, and q or ctrl-c in the TUI, follow the same path. A second signal still exits at once. Requests the proxy counts as in flight are those its forwarding listener admits, MITM-intercepted ones included, until it finishes them; a request held for quota (holdSeconds) counts while it waits. Blind CONNECT tunnels, the WebSocket channel Remote Control opens, and absolute-form forward-proxy requests are not counted, so they are cut at exit. Keep the value below your service manager's stop timeout, or the manager sends SIGKILL first. A set value that is not a positive number is ignored, with a warning at start. See Draining for maintenance
proxy.cliproxyApi Serves a CLIProxyAPI-compatible usage API under /v0/management/, for usage dashboards that read a CLIProxyAPI hub. "read" turns it on; "off" is the default, and any other value is treated as "off". Read-only: it lists the subscription accounts and answers the Claude and Codex usage URLs from the quota the server already tracks, never relaying a request upstream or handing out a credential. The dashboard's management key is proxy.apiKey or a proxy.clientKeys key, sent as Authorization: Bearer; with no proxy key configured it serves only loopback callers, as proxy.mcp does. Read per request and picked up by a reload
proxy.controlPlane Which credential Claude Code's bootstrap, policy, feature, WebFetch and registry calls go out on. "client", the default, relays them with the client's own login; any other value is treated as "client". "pool" sends them through account selection like a model request, so the model flags, plan and fast-mode state in their answers come from the pooled account picked for that call rather than from the login. For your own Claude Code login on a lighter plan than your pooled accounts. Each call is answered by one account, not by the pool as a whole, and like any request it can be picked onto an inference-only gateway that does not serve these endpoints. The identity plane (/api/oauth/*, Remote Control, attachments) stays on the client's login either way. Read per request and picked up by a reload
proxy.usageHistory true records each request forwarded to an account in a local SQLite file and serves it as usage history at GET /teamclaude/usage, broken down by consumer (proxy.clientKeys name), model and account. Off by default. Read at start, so turning it on or off needs a restart. Needs node:sqlite (Node 22.13 or later, or 22.5 with --experimental-sqlite); without it the server logs that history is unavailable and runs as before
upstream Upstream API base URL
messageThreads Set true when the global upstream is a relay that keeps Anthropic message-thread state. Accounts without an upstream of their own go wherever this points, and when that is a host other than Anthropic's, thread: {"type": "continue"} is refused for them the same way it is for a per-account third-party upstream (see accounts[].messageThreads); this flag is the fleet-wide way to say the relay does keep threads. Default off. See message threads
switchThreshold Quota utilization (0–1) at which to switch accounts (teamclaude threshold <1-100>, or the TUI settings screen: Switch threshold). The screen accepts tenths of a percent, e.g. 99.5, which is stored as 0.995. Reported OAuth utilization arrives on a whole-percent grid, so a fraction only changes the outcome for an API-key account, whose used share is continuous When any account is opted into allowExtraUsage, the fallback spends quota between this threshold and 100% before any account is billed; a reserve that must hold is maxUsage.
quotaProbeSeconds Background quota-probe interval in seconds (0 = off, the default; CLI probe, or the Quota probe row on the TUI settings screen)
probeDisabledAccounts Let the quota probe — the periodic one and the one-shot p refresh — also read accounts you disabled, so their quota stays current while they are out of rotation (true). Off by default (false): a probe refreshes the account's OAuth token when it is due and sends it upstream, and an account you took out of service gets neither unless you say so. An account whose refresh token upstream rejected stays skipped either way. Toggled from the settings screen (g → Probe disabled); applied live on reload
warmupSeconds Keep-warm interval in seconds (0 = off, the default; CLI warmup). Spawns a minimal claude per idle account to start its 5h timer — spends a little quota, unlike the probe. An account with no 5-hour window is skipped
warmupSchedule Optional reset-target keep-warm schedule. Daily mode stores { "resetTime": "15:30", "timezone": "Europe/Moscow" }; rolling mode also stores "mode": "rolling" and an absolute "anchorResetAt". The timezone must be an IANA name. Mutually exclusive with warmupSeconds; set with teamclaude warmup reset HH:MM --timezone Area/City or teamclaude warmup rolling HH:MM --timezone Area/City
holdSeconds Maximum seconds to hold the connection when all accounts are exhausted, polling silently until one recovers (0 = return 429 immediately, the default). teamclaude run raises API_TIMEOUT_MS automatically to match. Read at startup — a change needs a restart An allowExtraUsage account, if any, serves before the hold engages.
distributeSessions Spread concurrent conversations across equal-priority accounts, each pinned for cache reuse (teamclaude distribute <on|off|adaptive|load>) — the unit is a conversation and not the client session that holds it, so a session and its subagents spread rather than funnelling onto one account; one pin per weekly quota bucket, so a diversion in one model family leaves the others where they are (false = quota-driven rotation only, the default). Set to "adaptive" for a third mode that concentrates new conversations on the account with the least remaining weekly credit — tapering off as it nears its switchThreshold and backing off when it is congested. Subscription capacity comes from the OAuth profile tier; current utilization/reset comes from quota headers; burn rate and tolerated concurrency adapt to live traffic. See Adaptive distribution. Applied live on config reload; turning it off drains — conversations already running keep their accounts and only new ones stop being distributed, so nobody loses a prompt cache mid-conversation. Session tracking and readout is always on regardless — see Session-aware routing
persistSessionAffinity false by default; only literal true saves automatic conversation/bucket affinity and bounded message-thread ownership in the existing owner-only state file. Read at startup: changing it requires a restart. Restored accounts must still pass current routing checks. See persistence for lifetime, bounds and save timing
adaptiveDistribution Optional tuning for adaptive distribution. Object of numbers, one string and one boolean, every field optional; an unknown field, a non-numeric or non-finite value, a scoring that is not "burndown" or "pressure", or a pressureFiveHour that is not a boolean, or a value out of range is a startup error naming the field (a bad number would otherwise turn every adaptive score into NaN and silently route as even mode). The learners run and persist in every mode, so the block is checked whether or not the mode is on. Fields, with defaults: maxSampleAgeMs (900000, > 0) — a burn sample older than this spans an idle gap and is discarded; lookaheadMs (1800000, > 0) — how far ahead the reserve projects the account's burn rate; burnWindowMs (300000, > 0) — the wall-clock interval one burn-rate sample is measured over; burnAlpha (0.3, in (0, 1]) — EWMA weight of a new burn sample; minReserve / maxReserve (0.01 / 0.2, fractions in [0, 1], min ≤ max) — bounds on the reserve the taper works across; initialBurnRate (0.05/3600000 utilization per ms ≈ 5% of a window per hour, ≥ 0) — assumed until something is observed; initialConcCap / minConcCap / maxConcCap (6 / 1 / 64, > 0, min ≤ initial ≤ max) — where the tolerated-concurrency estimate starts and the range it may learn within; concBackoff (0.5, in (0, 1]) — EWMA weight applied on a throttle; concBackoffTo (0.75, in (0, 1]) — the fraction of the throttling load retreated to; concGrowth (0.05, in (0, 1]) — EWMA weight of the +1 probe while running at the cap; maxBurnBoost (4, ≥ 1) — ceiling on the burn-down preference, which is what lets the taper win at the threshold; fiveHourSoftMargin (0 = off, fraction in [0, 1], under scoring: "pressure" only) — stop placing new conversations on an account this far below its 5-hour cap, see Scoring by expiry pressure; pressureFiveHour (false, under scoring: "pressure" only) — also scale the score by the room left in the account's 5-hour window, see Scoring by expiry pressure; scoring ("burndown" or "pressure", default "burndown") — how a new conversation is scored, see Scoring by expiry pressure. Read at startup only
defaultClientMode What teamclaude run and teamclaude env do when neither --mitm nor --no-mitm is given: mitm (the default) routes every request of the launched client through the proxy, which is what covers the hard-coded api.anthropic.com endpoints and the Codex CLI; base-url sets only ANTHROPIC_BASE_URL, so a shell set up with eval "$(teamclaude env)" does not send its other tools (gh, git, package managers) through the proxy. A flag always wins over the setting. Toggled from the settings screen (g → Client mode); read from disk by each launch
eventLogging How to handle Claude Code's telemetry (/api/event_logging/*), which is high-volume activity-log noise: hide (default) forwards it but keeps it out of the activity log; block answers 200 locally without forwarding (no upstream round-trip); show forwards and displays it. Edits apply live via POST /teamclaude/reload
logDir Directory for request/response logs, one file per logged request (CLI: --log-to DIR). Unset (the default) writes nothing. The directory is created 0700 and each file 0600 (an existing directory or file keeps its mode); a directory that cannot be created is reported once at startup and logging is switched off for that run. The logged request body is the one sent upstream, so a rewrite by the proxy (tool-pair sanitising, modelMap) is visible. A 429 leaves no file at all, whether it rotates to another account, waits inline, or is returned to the client; an auth failure leaves none for the attempts it retries. Left unbounded it grows fast — a week of a few concurrent sessions measured 13 GB across 24,516 files, because a logged request records both bodies in full. Of the three keys below, logMaxBodyBytes and logRetentionHours are the bounds and are on by default; logLevel trades detail for size
logLevel How much of each request logDir records: body (default) writes the headers and both bodies; headers writes only the request and response heads, roughly a kilobyte per request instead of megabytes; off records nothing while leaving logDir set
logMaxBodyBytes Largest body logDir keeps per direction, default 262144. JSON is pretty-printed on the way out, so what lands on disk is larger than the cap. Anything longer is truncated and marked with the number of bytes dropped: a complete body keeps its head and its tail, a streamed one keeps its head alone. 0 records every body in full. What the client receives is never affected
logRetentionHours Age at which logDir files are deleted, default 72. Swept once at startup and every ten minutes after, and only names the logger wrote itself are considered. 0 keeps everything forever
advisorEligibility How an advisor request's second model (Claude Code's advisor tool, declared on every request) bears on account selection. "strict" (the default) requires an account eligible for both the main model and the advisor's; when only some accounts qualify, all such traffic is confined to them, which is logged at most once a minute. "prefer" routes a request by its main model only whenever the advisor's model would leave out accounts that could otherwise serve it, so an account not routed for the advisor's family, or with that bucket spent, may be asked to run the advisor. Any other value is "strict", with a warning. Applied live on config reload. See Model-aware routing
compactBeforeSwitch Have Claude Code compact a long conversation shortly before its account reaches a switch threshold, so the switch carries a summary. false (the default), true, or { "margin": 0.04, "minBodyBytes": 400000, "cooldownSeconds": 1800 }. When on, the proxy answers one request of such a conversation itself with the API's 400 prompt is too long error instead of forwarding it. Off by default because that changes what the client receives and relies on undocumented Claude Code behaviour: read Compact before a switch first. Invalid values are off, or the default for that field. Read per request; POST /teamclaude/reload applies an edit to the next one
blockedModels Array of model glob patterns (e.g. ["*fable*"]) whose requests are rejected with a fast, non-retryable 400 instead of being forwarded — avoids a model no account can serve getting rate-limited upstream and hanging the pipeline. Empty (the default) blocks nothing. Edits apply live via POST /teamclaude/reload
stripOverageHeaders Remove the per-organization billing headers (anthropic-ratelimit-unified-overage-*, anthropic-ratelimit-unified-upgrade-paths) from every upstream response whose HTTP headers TeamClaude parses, before it reaches the client. Default false: everything is forwarded unchanged. Meant for a pool whose accounts belong to several organizations: those headers describe whichever org served the response, and Claude Code caches them as its own, so one org with extra usage disabled can make it report "no usage credits", block a model the pool still has plan quota for, or show a consent dialog offering to enable paid overage on the wrong org. Operators whose serving and client organization state agree may prefer passthrough, since stripping also hides legitimate billing information. The plan-quota headers (5h, 7d and 7d_oi status, utilization and reset, the overall status, representative-claim, fallback) always pass through. TeamClaude's quota tracking receives the unfiltered headers either way and does not store the stripped family. The flag is sampled when each request is dispatched; POST /teamclaude/reload applies an edit to subsequent requests
synthesizeQuotaHeaders State a third-party backend's probed 5-hour and weekly windows to the client as anthropic-ratelimit-unified-5h-* and -7d-* headers (utilization and reset) plus anthropic-ratelimit-unified-status: allowed (always allowed, even on a spent window: the proxy does not judge the backend's verdict), so Claude Code fills its rate_limits (and any status line reading them) for backend accounts too. Default false. Only successful responses and only the client-bound copy change: quota tracking sees the upstream's own headers, and an upstream that states its own unified quota is left alone. A window the backend does not report (a Kimi plan with no weekly window, say) or without a known future reset is not stated, and Claude Code may keep showing a value it cached for it from an earlier Anthropic response. A monthly window has no header Claude Code reads, so it stays on GET /teamclaude/quota. Off by default because Claude Code words its limit warnings for Anthropic plans. Needs the quota probe, which is what reads the windows; the stated value is the last successful probe reading, so a probe that keeps failing leaves the previous value in place until that window's reset passes. The flag is sampled when each request is dispatched; POST /teamclaude/reload applies an edit to subsequent requests
poolQuotaHeaders While another account could still serve the request, state the pool's quota to the client instead of the serving account's. On a successful response, each anthropic-ratelimit-unified-5h-*, -7d-* and -7d_oi-* window the upstream stated carries the lowest utilization (and that account's reset) among the accounts that could serve the request, its per-window status reads allowed, -surpassed-threshold and -grace-* are removed, and an overall allowed_warning becomes allowed. A window no such account has a reading for loses its utilization and reset. Once the serving account is the only one left, its own headers pass through unchanged, so Claude Code's limit warnings and its near-limit wrap-up hint appear only when rotation can no longer help. A request pinned to one account (/tc-acct/<name>/, TC_ACCT) also keeps its own headers, since rotation cannot move it. Default false. Error responses and quota tracking are unaffected. The flag is sampled when each request is dispatched; POST /teamclaude/reload applies an edit to subsequent requests
sessionTitles Session titles in the activity log (off by default). Object: { enabled, width, projectsDir } — name each activity row after the Claude Code session that sent it, instead of showing six hex characters of its id. width is the columns the label gets (default 18; while enabled every row pays it, so the columns after it stay aligned). projectsDir overrides ~/.claude/projects. Display only: no selection code reads it. Toggled from the settings screen (g → Session titles); every field is applied live on config reload
quotaBarPercent Draw the utilization percentage beside the reset countdown on each TUI quota bar — 97% · 2h30m — on bars wide enough for both (true). Off by default (false): the bar carries the countdown alone, and its fill is the percentage. Display only, and only in the TUI: teamclaude status and the dashboard carry their own percentage regardless. Toggled from the settings screen (g → Bar percentage); applied live on config reload
quotaBarStretch How the TUI draws a row with one quota window where its neighbours have two: an account whose plan meters no 5-hour window (a Codex plan, a Claude Ultra plan once its 5-hour limit is lifted), or a seat with no shared weekly window. true (default) widens that one bar across both columns, so the row ends where its neighbours do. false keeps it at its own width in its own column (the weekly bar under the other rows' Wk) and leaves the other cell blank. Only when the row has room for two bars; display only, and only in the TUI. Only a literal false turns it off. Toggled from the settings screen (g → Stretch lone bar); applied live on config reload
accountSort How the TUI orders the account list inside each provider group. "arranged" (the default) is your own order — see accounts[].displayOrder below. The others put the account whose window resets soonest first, so quota about to expire unspent is at the top: "session-reset" (the five-hour window), "weekly-reset" (the all-models weekly), "sonnet-reset" and "fable-reset" (the Sonnet and Fable weekly buckets — S7 and F7 — or, on an account without that bucket, the all-models weekly that governs the family there). On a third-party backend account the sorts read its probed windows (weekly-reset reads the monthly window when the plan has no weekly one). An account with no reading for the window lists last, and the arranged order breaks ties. Display only — rotation still follows priority (and expiryRouting, if you want routing to prefer the soonest weekly reset too). Cycled from the settings screen (g → Sort accounts); applied live on config reload
stormRamp Optional storm-control tuning (on by default). Object: { enabled, startConc, stepConc, stepMs, windowMs, pollMs }, each number finite and above 0, and pollMs (how often a request waiting on the ramp re-checks it, default 50) a whole number of milliseconds from 5 to 536870911; a value that is not is ignored with a line in the log and that field keeps its default. Read at startup — a change needs a restart
preferSoonestWeeklyReset true to keep traffic on the available account (top priority tier) with the soonest deadline (its governing weekly reset, or its end date when that comes first), switching as soon as another's deadline is sooner — earliest-deadline-first, so quota about to expire is spent first. Default false (stay on the current account until switchThreshold). See Choosing an account. Applied live on config reload
switchOnSessionReset When another account's 5-hour window resets and its deadline (its weekly reset, or its end date when that comes first) is sooner than the current account's, move traffic to it at once, even though the current account is healthy. Default true. false keeps traffic where it is: the reset account is back in rotation and is ranked when rotation next has to pick, but no conversation is moved off a working account (and loses its prompt cache) for it, unless preferSoonestWeeklyReset is on: that setting moves traffic to the account with the soonest deadline as soon as it can serve again, a 5-hour reset included. Only a literal false turns switchOnSessionReset off. See Choosing an account. Applied live on config reload
expiryRouting Optional expiry-pressure routing (off by default). Object: { enabled, tolerance, preempt, reclaimHours, reclaimAcrossOrganizations } — prefer accounts whose governing weekly quota is ample and resets soonest. reclaimHours (default 0, off; anything but a positive number is off) opts in to the reclaim window: a conversation pinned outside the top pressure band moves to an account of the same organization whose quota expires within that many hours. reclaimAcrossOrganizations: true (default false) allows that move between organizations, at the cost of the prompt cache and thinking blocks. All of it applies on reload. The key name is provisional — see #176
sessionAdvice Optional session move advice (off by default). Object: { enabled, maxContextTokens, cooldownMinutes, ask }, defaults false, 150000, 60, false. Only a literal true turns enabled or ask on; a number that is not finite and positive falls back to its default. Applied live on config reload
routes Optional list of routing rules that pin model patterns to specific accounts
autoUpdate Set to false to disable the background self-update check
autoRedeemResets Let a Codex account whose weekly window has run out spend one of its free rate-limit reset credits to clear it. false by default, and deliberately so: a redemption cannot be undone and the credits are scarce, so nothing spends one automatically until you switch this on. For a manual spend, press r on the local TUI main screen, then choose the account; it does not need this switch. The switch is fleet-wide because the policy is — a credit is spent only when the weekly (never the 5-hour) window is exhausted and either every other Codex account is unavailable too, or the credit itself expires within three days. The same switch arms banked Claude usage-limit resets: a request no Claude account can serve may spend one reset, on the account that would wait longest and only where the reset clears every limit it is at. For Claude it fires when the pool is dry and the account is either at its upstream weekly limit or held out of rotation by its weekly switchThreshold; in the second case the last part of the week below upstream's limit (2% at the default 0.98) is given up with the reset. Among usable grants that clear the whole wall, it spends the cheapest kind (Fable, then session, then weekly), then the soonest expiry (no expiry last), then next_grant_id to break a remaining tie. Toggled from the settings screen (g → Auto-redeem) and applied live on reload, so it can be armed or killed without a restart. Individual accounts can opt out with accounts[].autoRedeemReset below
autoRedeemMinDaysToReset With autoRedeemResets on, never auto-redeem a Codex account whose natural weekly reset is closer than this many days. A Codex reset credit restarts the 7-day timer when it is redeemed, so a credit spent T days before the natural reset buys T/7 of a week. An account whose reset time is unknown is skipped too. A positive number of days; 0 by default (off), and any other value is off, and is named in the log at start and at each reload. A value of 7 or more cannot be met on a 7-day weekly window, since an account that has used one up is always less than 7 days from its reset, so it stops every automatic redemption on such a window; the usage parser also reads a window of up to 7.7 days as weekly, and on one of those a value from 7 to 7.5 can pass. It is kept as written and logged the same way. Applied live on reload. Codex only. See the spending strategy
autoRedeemMaxShare With autoRedeemResets on, auto-redeem at most this share (rounded up; 0.5 of three allows two) of the armed Codex accounts whose natural weekly resets fall on the same UTC calendar day (disabled and cordoned ones, and ones waiting for a sign-in, are not counted), most-exhausted first, so the rest keep their place in the week. A fraction strictly between 0 and 1; 1 by default (off), and any other value is off, and is named in the log at start and at each reload. Applied live on reload. Codex only. See the spending strategy
autoRedeemMaxPerDay With autoRedeemResets on, at most this many automatic Codex redemptions per rolling 24 hours, across all Codex accounts. A redemption made by hand from the TUI is not counted and not stopped. The six-hour hold after each redemption this cap counts already keeps those to 4 in any 24 hours, so a value of 4 or more never stops one. A consume whose answer was lost arms only a 30-minute hold and is not counted until a retry reads its answer, so it does not use up any of this cap. A whole number; 0 by default (off), and any other value is off, and is named in the log at start and at each reload. Applied live on reload. Codex only. See the spending strategy
upstreamProxy Outbound HTTP proxy for everything TeamClaude sends to Anthropic — request forwarding, OAuth login, token refresh, profile and usage. "http://user:pass@host:3128", or just "host:3128". false disables it and ignores the environment. Unset = use HTTPS_PROXY/ALL_PROXY if present. A value addressing TeamClaude's own listener is ignored (it would proxy the server through itself). TUI settings screen: Upstream proxy. See Upstream proxy
noProxy Comma-separated hosts that bypass upstreamProxy (suffix match, * = all). Defaults to NO_PROXY from the environment
mitm.http1Only Offer only HTTP/1.1 on the intercepted MITM connection (default false). Needed for Remote Control from the Claude Code Desktop app: a WebSocket over HTTP/2 requires RFC 8441 extended CONNECT, which is not relayed, so a client negotiating h2 has its handshake dropped with no error — the session syncs one way and messages from the phone are never delivered (#164). Costs client→proxy multiplexing on a loopback hop; upstream is already pooled HTTP/1.1
sx.apiKey sx.org API key. When set, TeamClaude auto-provisions a residential proxy (egress-IP 429 workaround). Absent/empty = off — see sx.org proxy mode. New to sx.org? Signing up via https://sx.org/c/ufVrLW supports TeamClaude development
sx.mode always (route all upstream traffic), 429 (direct, fail over to the proxy after a 429), or off (keep the key but don't use it). Defaults to always when a key is set
accounts[].accountUuid Anthropic account (person) id; set automatically from the OAuth profile
accounts[].orgUuid / orgName Organization the account is scoped to — lets one email hold multiple org accounts
accounts[].refreshTokenExpiresAt When the account's refresh token lapses and a new login is due, in epoch milliseconds. Written by the proxy, not meant to be hand-edited: present when the provider's token response or the imported credential file stated the date, or, for a Claude teamclaude login that stated none, set to 30 days from the sign-in; kept at the earlier value across refreshes, and replaced or removed by a new login. See knowing ahead of time
accounts[].priority Rotation preference, lower = preferred (default 0)
accounts[].endsAt When the account stops being usable, if you know: a cancelled subscription's last paid day, the end of a trial. Epoch milliseconds or an ISO 8601 string ("2026-12-01T09:00:00Z"); a date alone ("2026-12-01") is the start of that day in the server's local time, as is a date-time with no offset. Selection then ranks the account by the earlier of its weekly reset and this time, so it is spent before it ends. It only ranks: priority still comes first, and an end time that has passed does nothing, the account is not disabled. A value that is not a time is ignored with one log line. Set with teamclaude ends <name> <time>, removed with --clear; applied live on reload. Unset by default. See An account with an end date
accounts[].switchThreshold Per-account override of the fleet-wide switchThreshold: a number, or a per-bucket table like { "unified7dFable": 0.8 }. Resolution is per bucket — the account table's entry for that bucket, else the account's own default (or bare number), else the fleet's switchThreshold for that bucket — so a table without default only overrides the buckets it lists and inherits the rest from the fleet. Still a preference, exactly like the fleet setting: the all-exhausted revalidation probe can override it too. That is what keeps it a different setting from the hard accounts[].maxUsage cap below. No CLI editor — hand-edit and reload, same as maxUsage. Applied live on reload. See Per-account thresholds When any account is opted into allowExtraUsage, the fallback spends quota between this threshold and 100% before any account is billed; a reserve that must hold is maxUsage.
accounts[].displayOrder Where the account sits in the TUI's account list, lowest first; unset lists after every account that has one. Display only — it decides nothing about which account rotation spends, which is priority above. Set it from the TUI (g → Reorder accounts), or by hand; applied live on reload
accounts[].maxUsage Hard per-account usage cap: a number, or a per-bucket table like { "unified7d": 0.6, "unified7dFable": 0.8 } (same keys as switchThreshold; default covers unlisted buckets, anything else is uncapped). At the cap the account receives no requests — rotation skips it, the all-exhausted revalidation probe skips it, and a pin gets the exhausted answer. Model-scoped like the thresholds, applied live on reload. See Per-account usage caps
accounts[].maxSpend Hard per-account money cap, in the account's billing currency (20 is $20.00): once upstream's month-to-date extra-usage figure reaches it, the account bills nothing more: until the figure resets with the month it serves only requests its included quota provably covers (the session and weekly buckets known and under 100%, and the model's own family bucket under 100% if the plan meters one), and rotation, the revalidation probe, the extra-usage fallback and pins skip it for every other request. 0 means not one cent. Judged only while extra usage is enabled upstream. Requires the quota probe (quotaProbeSeconds, or teamclaude probe N): the spend figure comes only from probe readings, so the cap binds within one probe interval of the figure being reached, not on the request in flight — a usage cap of 1.0 alongside it stops the account before billing can start at all. Applied live on reload. See Per-account spend caps
accounts[].credit Prepaid API credit on an Anthropic API-key account (no upstream), such as the monthly credit a Max or Ultra plan grants a linked Console organization: { "amount": 200, "currency": "USD", "cycleStart": "2026-11-02", "adminKey": "sk-ant-admin01-…" }. The TUI row adds a Cr bar and $X left, teamclaude status a Credit line, and /teamclaude/status, /teamclaude/quota and the MCP tools a credit object. The spend comes from the organization's cost report when adminKey is set, else from a local estimate of the replies this proxy served. Off unless set; on any other account it is ignored with one warning. Applied live on reload. See Prepaid API credit
accounts[].credit.amount The credit per cycle, in dollars (200 is $200.00). Required, positive
accounts[].credit.currency "USD", the default and the only value accepted: Anthropic prices and reports cost in USD
accounts[].credit.cycleStart A date, "YYYY-MM-DD", whose day of the month is the renewal day. Each cycle runs from 00:00 UTC on that day to the same day next month; a day past a month's end falls on that month's last day for that month only (the 31st renews Jan 31, Feb 28, Mar 31, …). Required
accounts[].credit.adminKey Optional Admin API key (sk-ant-admin01-…, created at platform.claude.com/settings/admin-keys by an organization admin). With it, the spend is the organization's real spend since the cycle began, read from Anthropic's cost report — zero-spend, and read for disabled accounts too. It carries full admin access to the organization: it is sent to api.anthropic.com only and never logged or put in any payload. Without it, the spend is an estimate from replies served through this proxy, an upper bound on what is left
accounts[].credit.refreshMinutes How often the cost report is read with adminKey, in minutes (default 15, at least 1, at most 1440). A failing read waits this long doubled per consecutive failure, up to six hours
accounts[].allowExtraUsage Set true to let this account keep serving past its quota on Anthropic's paid "extra usage" (overage) — this spends real money. Off by default; only a literal true opts in, and Anthropic OAuth accounts only: on an API key, a third-party backend (upstream) or a Codex login the flag is ignored, with one warning when the account is loaded. Rotation is unchanged: the account still rotates away at switchThreshold like any other. Only when no account can serve under the normal rules does the fallback run, and it spends free quota first: any account between its threshold and 100% serves before an opted-in account is billed. It returns to normal as soon as any account has headroom again. Every hard gate still applies — disabled, maxUsage, a live 429 hold, an error state, an entitlement cooldown, routes. maxUsage above 1.0 (e.g. 1.5) makes a natural spend limit, and accounts[].maxSpend above caps the month's bill in money. Applied live on reload. See Extra-usage fallback
accounts[].preferExtraUsage Set true alongside allowExtraUsage: true to use this subscription's remaining included quota, and then its paid usage credits, before API accounts and backends that still have capacity. Off by default; only a literal true opts in, and a true that cannot apply (no allowExtraUsage, or not an Anthropic OAuth account) is ignored with one warning when the account is loaded. Subscriptions under their threshold are still used first, and an API account with a strictly lower priority number still goes first. Applied live on reload. See Extra-usage preference for the full order
accounts[].routing The account's own egress proxy: "socks5h://user:pass@host:1080", also socks5, socks4a, socks4 and http, and a bare host:port is http. Every connection made for the account goes through it (requests, sign-in, token refresh, profile, usage and quota), and the account then ignores upstreamProxy and sx.org. Set it with teamclaude routing <name> <url>, login --routing, the TUI (g then Account proxy) or by hand; applied live on reload. See Per-account routing
accounts[].autoRedeemReset Set false to exempt this Codex or Claude account from autoRedeemResets above: it never spends a reset credit or a banked reset automatically, however dry the pool gets. Manual spending with r in the local TUI still works. Negative only — true and an absent key mean the same thing, and neither arms anything on its own; the fleet-wide autoRedeemResets is the only switch that does. Ignored for third-party backend accounts. Applied live on reload
accounts[].disabled If true, the account is excluded from rotation until re-enabled
accounts[].cordoned If true, no new conversation goes to the account, while one already on it stays until it finishes. Written by teamclaude cordon and the dashboard's cordon button, removed by uncordon; applied live on reload. Off by default. See Cordoning one account
accounts[].longLived Written as true by teamclaude login --long-lived: the entry holds a one-year, inference-only token (the kind claude setup-token makes) and no refresh token. Such an account is never refreshed, probed or synced between installs, takes no part in reset redemption, has its quota read from response headers only, and needs a new login --long-lived when the year runs out. Any value other than true is off. Removed by an ordinary login or import of the same account, and ignored on an entry that names importFrom. Applied live on reload. See Long-lived login
accounts[].upstream Alternative upstream base URL for this account (e.g. https://api.deepseek.com/anthropic). Overrides the global upstream for this account only — see third-party backends
accounts[].modelMap Object mapping Anthropic model names to this backend's model names (e.g. {"claude-sonnet-4-6": "deepseek-v4-pro[1m]"}). Applied automatically when requests are routed to this account
accounts[].messageThreads Set true when this upstream keeps Anthropic message-thread state. Off by default for accounts whose effective upstream — their own upstream, or the global one — has a host that is not Anthropic's own (a region pin or mirror needs no flag): a backend that keeps no thread state would be handed only the turn's delta, so the proxy answers thread: {"type": "continue"} with the same 400 Anthropic gives for a thread it cannot continue, and Claude Code resends the whole conversation and stops threading that model for the session. Completions only — count_tokens is always forwarded. For accounts on the global upstream, the top-level messageThreads declares it for the whole fleet. See message threads
accounts[].stripRequestFields Array of top-level request-body fields to drop before forwarding to this account. For third-party upstreams that implement the Anthropic message API but reject fields Claude Code sends (e.g. ["context_management"], which some return a 400 Extra inputs are not permitted for — breaking every request once that account is selected). Applies to this account only; Anthropic accounts are untouched. Two nested forms are accepted. "cache_control.<subfield>" (e.g. ["cache_control.scope"]) drops that subfield from every documented prompt-cache breakpoint (root, system[], messages[].content[], tools[]) for backends that reject it with 400 unknown parameter; type and ttl are forwarded unless listed. "content.<block type>" (e.g. ["content.tool_addition", "content.tool_removal"]) drops every messages[].content[] block of that type, for backends that answer 400 to the blocks Claude Code uses to announce a tool that appears mid-conversation; such a block stays in the history, so without the entry every later turn of that conversation fails as well. A cache breakpoint on a dropped block moves to the last block left in the same message, and a message left empty is dropped. Nothing is dropped without an entry
accounts[].models Deprecated — use a routes entry with match and accounts instead. Array of model names this account exclusively handles; kept for backward compatibility with pre-routes configs

Environment variables

Every TEAMCLAUDE_* variable below is also read under the name TEAMROUTER_*, which wins when both are set — the project is being renamed, and the old spelling keeps working throughout.

Variable Effect
TC_ACCT Pin a session to one account, bypassing rotation. Accepts accountUuid, orgUuid, accountUuid/orgUuid, or a display name/email. A comma-separated list of API-key accounts moves a request to the next one when upstream billing refuses the account it is on (details). A list of subscriptions keeps a session to them, in order, moving on when one's quota is spent (details). Read by teamclaude run and teamclaude env, then removed from the environment so it never reaches claude
TEAMCLAUDE_CONFIG Path to the config file (default ~/.config/teamclaude.json, or ~/.config/teamrouter.json when that file exists)
TEAMCLAUDE_HOST Override proxy.host
TEAMCLAUDE_DISABLE_AUTOUPDATE Set to 1 to skip the background self-update check
TEAMCLAUDE_CONFIG_LOCK_WAIT_MS How long a writer waits for another process's <config>.lock before writing without it (default 2000). See Where it lives
TEAMCLAUDE_REMOTE Whether sign-in treats this terminal as remote. 1: remote, so no browser is opened on this machine and a Claude login skips its loopback listener; you open the link elsewhere and paste the answer back. 0: local. Unset, it reads SSH_CONNECTION/SSH_TTY, and on Linux a missing DISPLAY/WAYLAND_DISPLAY. Set it for a server a service started, which never sees your SSH session. See Signing accounts in over SSH
TEAMCLAUDE_CALLBACK_CLIENT_ID The OAuth2 app teamclaude callback login signs in to callback.net as, for a self-registered app or a test realm. The built-in id is the project's own
TEAMCLAUDE_CALLBACK_API_BASE Where the callback.net API is reached (default https://www.callback.net). Must be https://, or plain http:// to this machine only, since the session token travels to whatever this names; a value that is neither is refused, and nothing is sent. See Syncing accounts across machines
TEAMCLAUDE_SURFACE_TIMEOUT_MS How long teamclaude statusline and teamclaude stop-hook wait for the server's answer (default 1000). Past it the status line reads teamclaude offline and the hook prints nothing
TEAMCLAUDE_STATUS_TIMEOUT_MS How long teamclaude status waits for the server's answer before giving up (default 5000). A connection that is accepted but never answered is reported as a stalled or overloaded server, distinct from a refused one ("Is the server running?")
HTTPS_PROXY / ALL_PROXY Outbound proxy used when the config sets no upstreamProxy (lowercase forms honoured too)
NO_PROXY Hosts that bypass the outbound proxy, when the config sets no noProxy. Also inherited by clients that teamclaude run/env launch — their loopback entries are added to yours, and * is ignored
TEAMCLAUDE_CONFIG=./my-config.json teamclaude server

Event-loop diagnostics

A wedged event loop is the one failure the status endpoint cannot report, because the endpoint itself cannot run. The server therefore keeps a small watchdog: a 1 s timer measures how late each tick fires, and a tick more than 500 ms late counts as a stall and writes one line to the service log (at most one every 30 s):

[TeamClaude] Event loop stalled: lag=1840ms (threshold=500ms, stalls=3)

The figures are reported under server.eventLoop in GET /teamclaude/status and teamclaude status --json — numbers only, never request content:

Field Meaning
lastLagMs How late the most recent tick fired
maxLagMs The worst lag seen since the server started
stallCount Ticks that exceeded the threshold since start
lastStallAt ISO timestamp of the most recent stall, or null
warnLagMs The threshold in effect (500)

A teamclaude status that times out (see TEAMCLAUDE_STATUS_TIMEOUT_MS) while the log shows stalls is the signature of a starved or blocked process — on macOS, check that the LaunchAgent is not running under a Background QoS clamp — rather than of an upstream problem.

Usage Dimensions

Usage dimensions answer which project, branch, pull request, or CI job spent the tokens, without a TeamClaude change for every new grouping. proxy.clientKeys names WHO spent them; a dimension names what they were spent ON, which one shared CI key cannot express on its own.

Configure the dimensions once on the proxy:

{
  "proxy": {
    "usageDimensions": [
      { "name": "project", "header": "x-teamclaude-project" },
      { "name": "ref", "header": "x-teamclaude-ref" }
    ]
  }
}

Developers set a project identity per repository in .claude/settings.json:

{
  "env": {
    "ANTHROPIC_CUSTOM_HEADERS": "X-Teamclaude-Project: KarpelesLab/teamclaude"
  }
}

CI can set several dimensions with newline-separated custom headers:

export ANTHROPIC_CUSTOM_HEADERS=$'X-Teamclaude-Project: KarpelesLab/teamclaude\nX-Teamclaude-Ref: pull/123'

Use stable, low-cardinality values such as org/repo, pull/123, or a branch name — a dimension is capped at 500 distinct values, and everything past the cap is summed into an (other) row. Header values are client-supplied: they are sanitized on ingest and length-capped before they reach any status output.

A configured dimension header is consumed by the proxy and not forwarded upstream — it labels traffic for this proxy, so your internal project and branch names stay on your own infrastructure. It is still not a place for secrets: the values are persisted to the state file and readable by any proxy-key holder. Two exceptions to the first point: a dimension named connection, upgrade or sec-websocket-* still rides a WebSocket handshake (Remote Control's real-time channel), since those headers are the handshake itself; and an absolute-form plain-HTTP request (GET http://host/path, what a tool honoring HTTP_PROXY sends) is relayed with the client's headers, labels included: in practice it reaches third-party hosts, but the proxy does not check whether it names an http:// upstream you configured.

Header names the proxy refuses to use as a dimension, because it or the client already relies on them: authorization, proxy-authorization, cookie, x-api-key, x-app, x-claude-code-session-id, x-claude-code-agent-id, x-claude-code-parent-agent-id, x-anthropic-additional-protection.

Per-session cost

Per-session token cost is not a usage dimension. The session tracker already meters what each session's responses reported — cache reads and cache creation included — per weekly bucket, and that is the number that matters: a sum of input_tokens and output_tokens understates a cached Claude Code session by orders of magnitude. Set proxy.sessionDetail to surface it per session.

Network resilience

After a host network drop and reconnect, Node's shared connection pool can hold dead keep-alive sockets. Because a request has no default time limit, a retry can land on a dead socket and hang forever — every account and every retry keeps hitting the same poison, so the proxy appears wedged until you restart it. TeamClaude bounds each stage so a stuck request fails fast instead: the failure lets Node evict the dead socket, the client retries, and the next request connects fresh — no restart needed. Recovery is per-socket, so after a flap it can take a few failed-then-retried requests to fully drain, but it always converges.

Connection pooling under concurrency. Upstream requests go over a pooled HTTP/1.1 transport (node:https), so each concurrent request gets its own connection. Node's global fetch instead multiplexes every request to api.anthropic.com over a single HTTP/2 connection; under many concurrent large uploads (Claude Code POSTs ~1 MB of context per turn) that one connection serializes on HTTP/2's shared flow-control windows, and a trivial request can wait minutes for headers (#106). Independent H1 connections have no such contention — each upload fills its own socket at TCP speed, matching what N direct Claude Code processes do.

The defaults are meant to be left alone; these exist for the rare case where they aren't right for you.

Variable Default Description
TEAMCLAUDE_UPSTREAM_HEADERS_TIMEOUT_MS 120000, Codex accounts 300000 Max wait for upstream response headers (time-to-first-byte). Cleared the instant headers arrive, so a long streaming body is never cut. Streamed completions deliver first byte in seconds; a non-streaming (stream:false) request that legitimately generates for longer than this could trip it — raise it for such callers. A backend that sends its head before it generates, and the whole body only when generation ends, is allowed the same silence after the head: a forwarded answer held whole (one that is not an event stream) is cut only after the longer of this and TEAMCLAUDE_UPSTREAM_BODY_TIMEOUT_MS without a byte. At the defaults the two are equal, so that wait is longer only when this is longer than the body-idle timeout: a Codex account, a raised headers timeout, or a lowered body-idle timeout; a client's token refresh and a call retried on the client's own login keep the body timeout alone. Requests forwarded to a Codex account start from 300000 instead, because the ChatGPT backend holds the head open while the model reasons (see Codex accounts). Setting this variable replaces both figures, for every account. At most 2147483647 (about 24.8 days, the longest delay a Node timer holds); a larger value is read as that
TEAMCLAUDE_UPSTREAM_BODY_TIMEOUT_MS 120000 Max idle gap between response-body chunks, while a body is relayed or read whole before it is relayed (an answer that is not an event stream, a client's token refresh relayed through the proxy, a call retried on the client's own login). Resets on every chunk, so a slow-but-healthy body is fine; it fires only when the socket goes silent after the headers, turning a hang into a fast, retryable failure. A forwarded answer read whole is allowed the headers timeout instead when that is longer, since a non-streaming completion may be all silence after its head. At most 2147483647 (about 24.8 days, the longest delay a Node timer holds); a larger value is read as that
TEAMCLAUDE_UPSTREAM_MAX_HELD_BYTES 67108864 (64 MiB) The largest upstream answer read whole before it is relayed. Past it, a forwarded answer that is not an event stream is relayed as it arrives instead (no usage is read from it), and a client's token refresh relayed through the proxy, or a call retried on the client's own login, answers 502. Per answer, not for the process; the proxy's own token refreshes, for its accounts, are not bounded by it. A whole number of bytes, read as JavaScript's Number() reads the text (so 0x1000, 1e3 and 4096 with spaces around it count); unless that gives a whole number from 1 to 9007199254740991, the default is used (unset, empty, 0, a negative or fractional value, Infinity, 64MiB)
TEAMCLAUDE_UPSTREAM_MAX_SOCKETS 256 Max concurrent upstream connections per origin in the pooled path, and the width of the admission gate in front of it. A long stream holds its slot until its body ends; requests beyond this wait in the bounded queue below (raise it if you run more concurrent sessions than this against one host)
TEAMCLAUDE_UPSTREAM_MAX_QUEUE 64 How many requests may wait per origin for a free slot once all MAX_SOCKETS are busy. A request arriving at a full queue is refused immediately (0 disables queueing)
TEAMCLAUDE_UPSTREAM_QUEUE_TIMEOUT_MS 5000 Longest a queued request waits for a slot before it is refused. Separate from the headers timeout, which is armed only once the request is admitted
TEAMCLAUDE_UPSTREAM_GLOBAL_FETCH (off) Set to 1 to route upstream requests through Node's global fetch (single HTTP/2 connection) instead of the pooled H1 transport — an escape hatch, not recommended under concurrency
TEAMCLAUDE_REFRESH_TIMEOUT_MS 30000 Max time for one attempt at an OAuth token refresh, counted from its start. A Claude refresh makes up to three attempts, so at the default one refresh can take about 91.5s — see Refresh timeout below
TEAMCLAUDE_RATE_LIMIT_ABSORB_MAX_SECONDS 60 Longest retry-after absorbed inline on the same account before a rate-limit 429 is surfaced to the client — see the two kinds of 429. It also caps how long each such 429 pauses the account
TEAMCLAUDE_HEADERLESS_429_RETRY_DELAY_MS 2000 How long to wait before the single retry of a headerless (request-scoped) 429 — one carrying no retry-after and no anthropic-ratelimit-* headers. Retried once per request, for every provider — after a failover hop it stays on the account the hop landed on; if the retry is refused too the 429 goes to the client, just later. Lower it if you would rather have the 429 sooner than have the transient absorbed, or set it to 0 to disable the retry altogether, so a headerless 429 goes back to the client as soon as the failover hop (if any) has been refused too. Unset, empty or unparseable means the default — see the two kinds of 429

Refresh timeout. TEAMCLAUDE_REFRESH_TIMEOUT_MS bounds one attempt. Through a proxy it cannot end an attempt while the tunnel is still opening, which has timeouts of its own, for the CONNECT and for the TLS handshake over it (20s each through an account's routing proxy, 30s each through the upstream proxy). A hung refresh is coalesced across all callers, so without this bound it would wedge every request for that account. A Claude refresh that times out, fails on the network or gets a 5xx is tried up to three times in all, 0.5s and then 1s apart, so at the default one refresh can take about 91.5s, and longer through a proxy. Through the upstream proxy, a refused or reset connection and a timeout once the tunnel is open are retried, but not a DNS error, a CONNECT the proxy refuses or never answers, or a TLS handshake over it that times out. Through an account's routing proxy, of the network failures only a reset or a timeout once the tunnel is open is retried: a tunnel it fails to open is not, and the running proxy then holds that account out of rotation for 30 seconds (see When the proxy is down). A Codex refresh is a single attempt. Under a callback.net lock the provider call gets what is left of the lock less 10s, at most about 20s (a tunnel still opening can run past it), though waiting for another install's renewal can take longer

Upstream admission. Node's connection pool queues requests past MAX_SOCKETS internally, without bound and without a deadline — a client that had already gone away kept its request (and its buffered body) parked there until a long-lived stream ahead of it ended. Requests are now admitted per origin before the upstream connection is built: the queue is bounded by TEAMCLAUDE_UPSTREAM_MAX_QUEUE, the wait by TEAMCLAUDE_UPSTREAM_QUEUE_TIMEOUT_MS, and a client that disconnects while queued leaves the queue at once. A request the gate refuses gets a 503 with Retry-After: 1 and an overloaded_error body. That is the proxy saying it is saturated, not the account: it is never retried on another account (every account shares the same origin gate, and another attempt would only add load), no account is paused or sidelined over it, and in the activity log the row is attributed to (upstream queue full) rather than to an account. GET /teamclaude/status reports the gate under upstreamPool — active, queued, origins, perOriginLimit, maxQueue, queueTimeoutMs — counters only.

If you lowered TEAMCLAUDE_UPSTREAM_MAX_SOCKETS, note the change in behaviour: requests past the limit used to queue indefinitely inside Node's pool; they now wait at most TEAMCLAUDE_UPSTREAM_QUEUE_TIMEOUT_MS (5 s) and then fail with the 503 above. Long streaming completions hold their slot for their whole duration, so a small pool with many concurrent sessions will see these 503s; raise the pool width (or the queue and its deadline) to match your concurrency. The global-fetch escape hatch (TEAMCLAUDE_UPSTREAM_GLOBAL_FETCH=1) has no pool and is not gated.

A client that disconnects mid-request no longer keeps its upstream work alive either: the upstream request is cancelled (queued or in flight), a quota-hold or rate-limit sleep ends immediately, and a silent SSE stream is cancelled rather than held until the body-idle watchdog. The activity row for such a request closes as 499.