@kapybara/zerosub 1.4.0 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -6,7 +6,7 @@ Use several Claude and ChatGPT (Codex) subscriptions side by side in [Paseo](htt
6
6
  - **Your existing CLI logins show up automatically.** Nothing changes until you add a second account.
7
7
  - **Pick an account per agent.** An account button in the message box shows which account each Claude or Codex agent uses. Tap it to switch.
8
8
  - **Automatic failover.** When an account hits its 5-hour or weekly limit, the agent moves to the account with the most room left and carries on. New agents skip exhausted accounts.
9
- - **Live usage.** Each account shows its own 5-hour and weekly usage and when they reset. Accounts in use refresh about every minute and after each turn, and a limit shows up the moment it hits.
9
+ - **Live usage.** Each account shows its own 5-hour and weekly usage and when they reset, plus any ChatGPT credits. Accounts in use refresh about every minute and after each turn, and a limit shows up the moment it hits.
10
10
  - **Banked resets.** If a provider has banked limit resets on an account, you can use one from the account card or the agent's account button.
11
11
  - **Set an account aside.** Disable an account for a while and its agents move to your other accounts, then come back when you enable it again.
12
12
  - **Several hosts.** Each Paseo host keeps its own accounts, and the Accounts screen says which host you're looking at.
@@ -36,6 +36,7 @@ Then open **Accounts (ZeroSub)** in the sidebar.
36
36
  2. Click **Add account** under Claude or ChatGPT (Codex), then **Open sign-in page**, and sign in with the other account.
37
37
  - In a browser on the host's own computer, the page finishes by itself.
38
38
  - Anywhere else, choose **Use a code instead**. For Claude, paste the code shown after sign-in. For ChatGPT, type the code shown in Paseo on the page. Phones, and hosts without a desktop (servers, containers, daemons started over SSH), start with the code.
39
+ - Members of the same ChatGPT Team or Business workspace can each be added; ZeroSub tells them apart by email. If Codex doesn't return one, ZeroSub won't add a second account from that workspace or sign one of its members back in.
39
40
  3. Choose which account agents use:
40
41
  - **Make default**: new agents, and agents that follow the default, use it. Open Claude agents switch right away, busy ones after their turn.
41
42
  - To leave open agents where they are, turn off **Move open agents when the default changes** (in Accounts, or **Settings → Plugins → zerosub → ZeroSub preferences**). Each open agent that follows the default then stays pinned to the account it's using, even after it reopens, unless that account is signed out, disabled or at its limit. New agents, and agents that aren't open at the time, use the new default.
@@ -45,11 +46,15 @@ Then open **Accounts (ZeroSub)** in the sidebar.
45
46
  - **⌘K → "Make … the default"**.
46
47
  - **Disable for now** (the pause button on a card): the account stays signed in but ZeroSub stops using it. Its agents move to your other accounts right away (busy ones after their turn) and come back when you press **Enable**. ChatGPT conversations already on it stay, since they can't change accounts. You can't disable the last usable account of a provider.
47
48
  4. Leave **Automatic switching** on (in Accounts, or **Settings → Plugins → zerosub → ZeroSub preferences**) and limits take care of themselves:
48
- - Only the CLIs' own limit notices trigger a switch. That covers Claude Code's "You've hit your session limit · resets 3pm" and Codex's "You’ve hit your usage limit…".
49
+ - Only the CLIs' own limit notices trigger a switch. That covers Claude Code's "You've hit your 5-hour limit · resets 3pm" ("session limit" before Claude Code 2.1.312) and Codex's "You’ve hit your usage limit…".
49
50
  - Paseo 0.13 and later no longer send the finished turn to plugins, so ZeroSub reads that turn from the agent's timeline instead.
50
51
  - A short note in the agent's timeline says what happened.
51
52
  - As a safety stop, one agent changes accounts at most 4 times in 10 minutes. If it hits that, its timeline says so; pick an account from its account button to carry on.
52
- - An exhausted account is skipped until it resets. If you know it has room again sooner, for example after upgrading or buying credits, press **Mark as available again** (the check mark) on its card.
53
+ - An exhausted account is skipped until it resets. If you know it has room again sooner, for example after upgrading or buying credits, press **Mark as available again** (the check mark) on its card. For ChatGPT credits, see [ChatGPT credits](#chatgpt-credits).
54
+
55
+ ### Choose accounts for new agents
56
+
57
+ Turn on **Spread new agents across accounts** to select an account from its usage. For ChatGPT agents, ZeroSub prefers an account when its weekly limit resets within one day and both limits have at least 20% left. Usage for every available account must be complete and less than 30 minutes old. Otherwise, ZeroSub selects the account with the most room. Claude agents use the account with the most room. When a near weekly reset was the reason, the agent's account menu says **Started here: weekly reset was near**. Existing agents stay on their accounts.
53
58
 
54
59
  ### Claude vs. ChatGPT when switching mid-conversation
55
60
 
@@ -69,6 +74,14 @@ Some plans come with banked limit resets: ChatGPT's reset credits, and Claude Co
69
74
  - **Claude** uses Claude Code's limit-reset endpoint. Anthropic decides which accounts get resets; so far it reports the tested accounts as not eligible, so the button may not appear for Claude. It shows up by itself once an account has a reset.
70
75
  - **Use banked resets when every account is out** (off by default) spends one automatically, but only when every account of that provider is at its limit and the provider confirms the limit at that moment.
71
76
 
77
+ ### ChatGPT credits
78
+
79
+ A ChatGPT account can also have prepaid ChatGPT credits, which Codex spends once the account reaches its limit. They aren't the reset credits above. The card shows them under the usage bars, for example "57,714 ChatGPT credits left", and an agent's account button shows them next to the account's usage.
80
+
81
+ - By default, an account at its limit is skipped until it resets, credits or not, so new agents use the free room on your other accounts first. That room is lost at each reset; credits aren't. **Mark as available again** only lasts until the next usage reading, which still shows the limit reached.
82
+ - **Use ChatGPT credits when a limit is reached** (off by default; in Accounts, or **Settings → Plugins → zerosub → ZeroSub preferences**) keeps an account with credits in use at its limit. New agents may then spend paid credits even while another account still has room.
83
+ - Even with it on, a limit an agent actually ran into stays until it resets: Codex stopped that agent, so the credits didn't cover it.
84
+
72
85
  ### When every account of a provider is out
73
86
 
74
87
  ZeroSub tries these in order, and a timeline note says which one happened:
@@ -112,7 +125,7 @@ ZeroSub never implements OAuth itself and never copies credentials between accou
112
125
  ## Privacy and security
113
126
 
114
127
  - Credentials stay in the CLIs' own stores. ZeroSub's registry (`$PASEO_HOME/zerosub/state.json`) holds account names, emails, plans, which agent uses which account, and continuation links with timeline positions. Handoff text stays in the agents' conversation histories; it isn't copied into the registry.
115
- - To show Claude usage, ZeroSub reads each account's current access token and calls Anthropic's usage endpoint, the same way Paseo's built-in usage display and `/usage` do. It never logs or stores tokens and never refreshes them itself. When you refresh usage (the ↻ button beside the title) or use a reset and a token has expired, it runs `claude -p /usage` so Claude Code renews its own sign-in. Codex usage comes from `codex app-server`.
128
+ - To show Claude usage, ZeroSub reads each account's current access token and calls Anthropic's usage endpoint, the same way Paseo's built-in usage display and `/usage` do. It never logs or stores tokens and never refreshes them itself. When you refresh usage (the ↻ button beside the title) or use a reset and a token has expired, it runs `claude -p /usage` so Claude Code renews its own sign-in. In the background it does the same at most every 30 minutes per account, and only for a reading that has passed its reset time or an account at its 5-hour or weekly limit. Codex usage comes from `codex app-server`.
116
129
  - Using a banked reset calls the provider's own reset endpoint with that account's sign-in, and only after you confirm (or turn on automatic use).
117
130
  - Removing an account moves its agents to the default account, then signs it out (`claude auth logout` / `codex` logout) and deletes its home. This happens once no agent is mid-turn on it. Abandoned sign-ins are cleaned up the same way.
118
131
  - An account that still has ChatGPT conversations on it can't be removed until you archive them or continue them elsewhere, because they can't move.
@@ -122,7 +135,7 @@ ZeroSub never implements OAuth itself and never copies credentials between accou
122
135
 
123
136
  - **MCP servers that use OAuth** (Linear, Notion, …) store their tokens per Claude account, so sign in to them once on each account.
124
137
  - **Shared settings apply to every account.** If `~/.claude/settings.json` sets an `apiKeyHelper` or API-key `env`, every account uses that key instead of its subscription.
125
- - **Usage for an idle Claude account** shows the last reading until the account is used again or you refresh usage. Anthropic rate-limits its usage endpoint (Claude Code and Paseo read it too), so a reading can be a few minutes old; the card then says when it was taken. Readings are saved in `$PASEO_HOME/zerosub/usage.json`, so they survive restarts.
138
+ - **Usage for an idle Claude account** shows the last reading until the account is used again or you refresh usage. If a window in it has passed its reset time, or the account is at its limit, ZeroSub also renews the sign-in in the background to read it again, at most every 30 minutes, so an early reset or one used on another machine shows up too. Anthropic rate-limits its usage endpoint (Claude Code and Paseo read it too), so a reading can be a few minutes old; the card then says when it was taken. Readings are saved in `$PASEO_HOME/zerosub/usage.json`, so they survive restarts.
126
139
  - **Password-protected daemons:** `paseo agent reload` can't authenticate. Agents then switch the next time their session starts, not immediately, and their timeline note says so.
127
140
  - **Imported Codex threads** (`paseo agent import`) are assigned to your CLI login, since that's where standalone Codex sessions come from.
128
141
  - **ChatGPT device-code sign-in** has to be enabled in ChatGPT → Settings → Security. The browser option works from a browser on the host's own computer.
@@ -3,7 +3,7 @@ import { Icon, Modal, TextInput, useToast } from "@getpaseo/plugin/client/react-
3
3
  import { SettingsCard, SettingsSwitch } from "@getpaseo/plugin/client/ui";
4
4
  import { useCallback, useEffect, useMemo, useState } from "react";
5
5
  import { ScrollView, Text, View } from "react-native";
6
- import { accountSubtitle, formatAge, formatPlan, usageSummary } from "../shared/format";
6
+ import { accountSubtitle, formatAge, formatCredits, formatPlan, usageSummary } from "../shared/format";
7
7
  import { FAMILY_LABEL, type AccountView, type Family } from "../shared/model";
8
8
  import { preferences } from "../shared/preferences";
9
9
  import {
@@ -245,6 +245,7 @@ function AccountCard({
245
245
  const [confirmRemove, setConfirmRemove] = useState(false);
246
246
  const [confirmReset, setConfirmReset] = useState(false);
247
247
  const resets = account.usage?.resets ?? null;
248
+ const credits = account.usage?.credits ?? null;
248
249
  const plan = formatPlan(account.plan);
249
250
  const summary = usageSummary(account);
250
251
  const subtitle = accountSubtitle(account);
@@ -401,6 +402,7 @@ function AccountCard({
401
402
  ) : (
402
403
  <Text style={text.small}>{account.usage?.error ?? summary ?? "Checking usage…"}</Text>
403
404
  )}
405
+ {!signedOut && credits ? <Text style={text.small}>{formatCredits(credits)}</Text> : null}
404
406
  {!signedOut && windows.length > 0 && account.usage?.error ? <Text style={text.small}>{account.usage.error}</Text> : null}
405
407
  {!signedOut && resets?.blockedReason ? <Text style={text.small}>{resets.blockedReason}</Text> : null}
406
408
  </View>
@@ -634,7 +636,7 @@ function AutomationSettings({ theme }: { theme: Theme }) {
634
636
  />
635
637
  <SettingsSwitch
636
638
  label="Spread new agents across accounts"
637
- hint="New agents start on the account with the most room instead of the default."
639
+ hint="New ChatGPT agents prefer a weekly reset within one day when both limits have at least 20% left. Otherwise, new agents use the account with the most room."
638
640
  value={settings.values.balanceNewAgents}
639
641
  disabled={settings.saving}
640
642
  onValueChange={(balanceNewAgents) => save({ balanceNewAgents })}
@@ -653,6 +655,13 @@ function AutomationSettings({ theme }: { theme: Theme }) {
653
655
  disabled={settings.saving || !settings.values.autoSwitch}
654
656
  onValueChange={(autoRedeem) => save({ autoRedeem })}
655
657
  />
658
+ <SettingsSwitch
659
+ label="Use ChatGPT credits when a limit is reached"
660
+ hint="A ChatGPT account at its limit stays in use while it has credits, so new agents may spend paid credits even while another account still has room."
661
+ value={settings.values.useCredits}
662
+ disabled={settings.saving}
663
+ onValueChange={(useCredits) => save({ useCredits })}
664
+ />
656
665
  <SettingsSwitch
657
666
  label="When every account is out, fork the chat to the other provider"
658
667
  hint="A stopped Claude chat carries on in a new ChatGPT agent, or the other way round, with the conversation so far. The new agent gets no more permissions than the original; the original stays as it was."
package/client/pills.ts CHANGED
@@ -4,7 +4,7 @@ import type {
4
4
  PluginButtonRegistration,
5
5
  PluginClientContext,
6
6
  } from "@getpaseo/plugin/client";
7
- import { formatPercent, peakUsage, shortLabel } from "../shared/format";
7
+ import { formatCredits, formatPercent, peakUsage, shortLabel } from "../shared/format";
8
8
  import { FAMILY_LABEL, type AccountView, type Family, type StateView } from "../shared/model";
9
9
  import { setAgentAccount } from "../shared/rpc";
10
10
  import { forkPopover } from "./fork-confirm";
@@ -202,6 +202,13 @@ function buttonFor(
202
202
  });
203
203
  }
204
204
  if (wayOut.length > 0) items.unshift(...wayOut, { kind: "separator", id: "way-out-divider" });
205
+ if (route?.selectionReason === "weekly_reset") {
206
+ items.push({
207
+ kind: "item", id: "selection-reason",
208
+ title: "Started here: weekly reset was near",
209
+ icon: "Info", disabled: true, behavior: { kind: "action", onPress() {} },
210
+ });
211
+ }
205
212
  items.push({ kind: "separator", id: "manage-divider" });
206
213
  if (route?.pinned && movable) {
207
214
  const fallback = accounts.find((account) => account.isDefault);
@@ -240,7 +247,9 @@ function menuTitle(account: AccountView): string {
240
247
  if (account.status === "disabled") return `${account.label} — disabled`;
241
248
  if (account.status === "limited") return `${account.label} — limit reached`;
242
249
  const peak = account.usage ? peakUsage(account.usage.windows) : null;
243
- return peak ? `${account.label} — ${formatPercent(peak.usedPercent)} used` : account.label;
250
+ if (!peak) return account.label;
251
+ const credits = account.usage?.credits;
252
+ return `${account.label} — ${formatPercent(peak.usedPercent)} used${credits ? ` · ${formatCredits(credits)}` : ""}`;
244
253
  }
245
254
 
246
255
  function menuKey(button: PluginButton): string {
@@ -94,7 +94,7 @@ export function PreferencesScreen({ theme, host, onOpenAccounts }: PluginSurface
94
94
  <SettingsCard>
95
95
  <SettingsSwitch
96
96
  label="Spread new agents across accounts"
97
- hint="New agents start on the account with the most room instead of the default."
97
+ hint="New ChatGPT agents prefer a weekly reset within one day when both limits have at least 20% left. Otherwise, new agents use the account with the most room."
98
98
  value={settings.values.balanceNewAgents}
99
99
  disabled={settings.saving}
100
100
  onValueChange={(balanceNewAgents) => save({ balanceNewAgents })}
@@ -106,6 +106,13 @@ export function PreferencesScreen({ theme, host, onOpenAccounts }: PluginSurface
106
106
  disabled={settings.saving || !settings.values.autoSwitch}
107
107
  onValueChange={(autoRedeem) => save({ autoRedeem })}
108
108
  />
109
+ <SettingsSwitch
110
+ label="Use ChatGPT credits when a limit is reached"
111
+ hint="A ChatGPT account at its limit stays in use while it has credits, so new agents may spend paid credits even while another account still has room."
112
+ value={settings.values.useCredits}
113
+ disabled={settings.saving}
114
+ onValueChange={(useCredits) => save({ useCredits })}
115
+ />
109
116
  <SettingsSwitch
110
117
  label="When every account is out, fork the chat to the other provider"
111
118
  hint="A stopped Claude chat carries on in a new ChatGPT agent, or the other way round, with the conversation so far and no more permissions than the original. The original stays as it was."
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kapybara/zerosub",
3
- "version": "1.4.0",
3
+ "version": "1.5.0",
4
4
  "description": "ZeroSub: use several Claude and ChatGPT (Codex) subscriptions side by side in Paseo. Add accounts in-app, pick one per agent, and switch automatically when an account hits its limit.",
5
5
  "keywords": [
6
6
  "paseo",
@@ -0,0 +1,22 @@
1
+ import type { Family } from "../shared/model";
2
+ import type { Identity } from "./adapter";
3
+
4
+ type AccountIdentity = Pick<Identity, "identity" | "email">;
5
+
6
+ /** Compare old workspace-only Codex keys using their saved email, without rewriting the registry. */
7
+ export function sameAccountIdentity(
8
+ family: Family, left: AccountIdentity, right: AccountIdentity, unknownMemberIsDuplicate = false,
9
+ ): boolean {
10
+ if (!left.identity || !right.identity) return false;
11
+ if (family !== "codex") return left.identity === right.identity;
12
+ const workspace = /^chatgpt\|([^|]+)(?:\|(.+))?$/;
13
+ const a = workspace.exec(left.identity);
14
+ const b = workspace.exec(right.identity);
15
+ if (!a || !b) return left.identity === right.identity;
16
+ if (a[1] !== b[1]) return false;
17
+ const memberA = (a[2] ?? left.email)?.trim().toLowerCase();
18
+ const memberB = (b[2] ?? right.email)?.trim().toLowerCase();
19
+ // Unknown members block duplicate additions but cannot authenticate as a known managed member.
20
+ if (!memberA || !memberB) return unknownMemberIsDuplicate || (!memberA && !memberB);
21
+ return memberA === memberB;
22
+ }
package/server/adapter.ts CHANGED
@@ -20,7 +20,7 @@ export interface Identity {
20
20
  email: string | null;
21
21
  plan: string | null;
22
22
  organization: string | null;
23
- /** Stable key for spotting the same account twice (org + email, or the ChatGPT account ID). */
23
+ /** Key for spotting the same account twice (org + email, or ChatGPT workspace + member email). */
24
24
  identity: string | null;
25
25
  }
26
26
 
@@ -30,8 +30,11 @@ export interface Identity {
30
30
  */
31
31
  export type LimitKind = "window" | "budget";
32
32
 
33
- /** A usage reading, plus when to ask again if the provider said to slow down. */
34
- export type UsageRead = Usage & { retryAt?: number };
33
+ /**
34
+ * A usage reading, plus when to ask again if the provider said to slow down. An adapter may leave
35
+ * `credits` out; the reading is stored with `null` then.
36
+ */
37
+ export type UsageRead = Omit<Usage, "credits"> & { credits?: Usage["credits"]; retryAt?: number };
35
38
 
36
39
  export interface LimitHit {
37
40
  kind: LimitKind;
@@ -88,7 +91,7 @@ export interface FamilyAdapter {
88
91
  identity(home: string | null): Promise<Identity>;
89
92
  /**
90
93
  * Usage windows and banked resets. `renewLogin` lets the adapter have the CLI refresh an expired
91
- * sign-in first (slow, so only for explicit requests, never background polls).
94
+ * sign-in first (slow, so only for explicit requests, and at most every 30 minutes in the background).
92
95
  */
93
96
  usage(home: string | null, options?: { renewLogin?: boolean }): Promise<UsageRead>;
94
97
  /** Spends one banked reset. Only called for an explicit user request or the opt-in auto setting. */
package/server/claude.ts CHANGED
@@ -116,27 +116,27 @@ export class ClaudeAdapter implements FamilyAdapter {
116
116
  const body = (await response.json()) as { cedar_ember?: unknown };
117
117
  const windows = parseUsage(body);
118
118
  this.noteResetStatus(home, body.cedar_ember);
119
- return { fetchedAt, windows, error: null, cached: false, resets: parseClaudeResets(body.cedar_ember).offer };
119
+ return { fetchedAt, windows, error: null, cached: false, resets: parseClaudeResets(body.cedar_ember).offer, credits: null };
120
120
  }
121
121
  // Anthropic rate-limits this endpoint (Claude Code and Paseo read it too). Wait as long as it
122
122
  // asks; meanwhile the last reading stays up, or Claude Code's own cached copy if it's newer.
123
123
  if (response.status === 429) {
124
124
  const retryAt = Date.now() + retryDelayMs(response.headers.get("retry-after"));
125
125
  const cached = await cachedUsage(home);
126
- return { ...(cached ?? { fetchedAt, windows: [], error: null, cached: false, resets: null }), retryAt };
126
+ return { ...(cached ?? { fetchedAt, windows: [], error: null, cached: false, resets: null, credits: null }), retryAt };
127
127
  }
128
128
  if (response.status !== 401 && response.status !== 403) {
129
- return { fetchedAt, windows: [], error: `Usage request failed (HTTP ${response.status})`, cached: false, resets: null };
129
+ return { fetchedAt, windows: [], error: `Usage request failed (HTTP ${response.status})`, cached: false, resets: null, credits: null };
130
130
  }
131
131
  } catch (error) {
132
- return { fetchedAt, windows: [], error: error instanceof Error ? error.message : String(error), cached: false, resets: null };
132
+ return { fetchedAt, windows: [], error: error instanceof Error ? error.message : String(error), cached: false, resets: null, credits: null };
133
133
  }
134
134
  }
135
135
  // An idle account's token may have expired; Claude Code refreshes it on next use. Until then,
136
136
  // show the last utilisation Claude Code itself cached for this account.
137
137
  const cached = await cachedUsage(home);
138
138
  if (cached) return cached;
139
- return { fetchedAt, windows: [], error: "Usage shows up after this account is next used.", cached: false, resets: null };
139
+ return { fetchedAt, windows: [], error: "Usage shows up after this account is next used.", cached: false, resets: null, credits: null };
140
140
  }
141
141
 
142
142
  /** Logs (only when it changes) why an account does or doesn't show a banked reset. */
@@ -428,7 +428,7 @@ async function cachedUsage(home: string | null): Promise<Usage | null> {
428
428
  if (!cache || typeof cache.fetchedAtMs !== "number") return null;
429
429
  const windows = parseUsage(cache.utilization);
430
430
  if (windows.length === 0) return null;
431
- return { fetchedAt: new Date(cache.fetchedAtMs).toISOString(), windows, error: null, cached: true, resets: null };
431
+ return { fetchedAt: new Date(cache.fetchedAtMs).toISOString(), windows, error: null, cached: true, resets: null, credits: null };
432
432
  }
433
433
 
434
434
  const WINDOW_LABELS: Array<[key: string, label: string]> = [
package/server/codex.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";
2
2
  import { randomUUID } from "node:crypto";
3
- import type { LoginMethod, ResetOffer, Usage, UsageWindow } from "../shared/model";
3
+ import type { Credits, LoginMethod, ResetOffer, Usage, UsageWindow } from "../shared/model";
4
4
  import {
5
5
  ProgressEmitter,
6
6
  spawnEnv,
@@ -70,7 +70,7 @@ class AppServer {
70
70
  try {
71
71
  await server.request(
72
72
  "initialize",
73
- { clientInfo: { name: CLIENT_NAME, title: "Paseo ZeroSub", version: "1.4.0" }, capabilities: { experimentalApi: false } },
73
+ { clientInfo: { name: CLIENT_NAME, title: "Paseo ZeroSub", version: "1.5.0" }, capabilities: { experimentalApi: false } },
74
74
  60_000,
75
75
  );
76
76
  server.send({ method: "initialized" });
@@ -282,6 +282,7 @@ export class CodexAdapter implements FamilyAdapter {
282
282
  error: signedIn ? "Signed in with an API key, not a ChatGPT plan." : "Not signed in.",
283
283
  cached: false,
284
284
  resets: null,
285
+ credits: null,
285
286
  },
286
287
  };
287
288
  }
@@ -302,9 +303,10 @@ export class CodexAdapter implements FamilyAdapter {
302
303
  error: null,
303
304
  cached: false,
304
305
  resets: parseResetCredits(limits.rateLimitResetCredits),
306
+ credits: parseCredits(limits.rateLimits),
305
307
  };
306
308
  } catch (error) {
307
- usage = { fetchedAt, windows: [], error: error instanceof Error ? error.message : String(error), cached: false, resets: null };
309
+ usage = { fetchedAt, windows: [], error: error instanceof Error ? error.message : String(error), cached: false, resets: null, credits: null };
308
310
  }
309
311
  return {
310
312
  identity: {
@@ -312,9 +314,11 @@ export class CodexAdapter implements FamilyAdapter {
312
314
  email,
313
315
  plan,
314
316
  organization: null,
315
- // The ChatGPT account (workspace) ID tells a personal plan from a Team workspace on the same
316
- // email; without it, fall back to email plus plan so those two still stay distinct.
317
- identity: accountId ? `chatgpt|${accountId}` : email ? `chatgpt-email|${email.toLowerCase()}|${plan ?? "unknown"}` : null,
317
+ // A workspace can have several members. Include the email returned by account/read so
318
+ // each member is distinct while one email's personal and Team workspaces stay separate.
319
+ identity: accountId
320
+ ? `chatgpt|${accountId}${email?.trim() ? `|${email.trim().toLowerCase()}` : ""}`
321
+ : email ? `chatgpt-email|${email.trim().toLowerCase()}|${plan ?? "unknown"}` : null,
318
322
  },
319
323
  usage,
320
324
  };
@@ -445,9 +449,13 @@ function friendlyCodexError(message: string | null): string {
445
449
  return message;
446
450
  }
447
451
 
452
+ /** How long a ChatGPT plan's two windows are, in minutes, as Codex reports them in `windowDurationMins`. */
453
+ export const FIVE_HOUR_MINUTES = 300;
454
+ export const WEEK_MINUTES = 10_080;
455
+
448
456
  function windowLabel(minutes: number | null): string {
449
457
  if (!minutes) return "Usage";
450
- if (minutes === 10_080) return "Weekly";
458
+ if (minutes === WEEK_MINUTES) return "Weekly";
451
459
  if (minutes % 1_440 === 0) return `${minutes / 1_440}-day`;
452
460
  if (minutes % 60 === 0) return `${minutes / 60}-hour`;
453
461
  return `${minutes}-minute`;
@@ -466,11 +474,30 @@ export function parseRateLimits(snapshot: unknown): UsageWindow[] {
466
474
  label: windowLabel(minutes),
467
475
  usedPercent: window.usedPercent,
468
476
  resetsAt: typeof window.resetsAt === "number" ? new Date(window.resetsAt * 1000).toISOString() : null,
477
+ minutes,
469
478
  });
470
479
  }
471
480
  return windows;
472
481
  }
473
482
 
483
+ /**
484
+ * Prepaid ChatGPT credits, from `rateLimits.credits` (`balance` is a decimal string on the wire).
485
+ * Codex bills them once the plan's windows are used up, so `null` means there are none to fall back on,
486
+ * as does a balance at or below zero.
487
+ */
488
+ export function parseCredits(snapshot: unknown): Credits | null {
489
+ if (!snapshot || typeof snapshot !== "object") return null;
490
+ const record = snapshot as Json;
491
+ if (record.spendControlReached === true) return null;
492
+ const credits = record.credits as { hasCredits?: unknown; unlimited?: unknown; balance?: unknown } | null;
493
+ if (!credits || typeof credits !== "object") return null;
494
+ const unlimited = credits.unlimited === true;
495
+ if (!unlimited && credits.hasCredits !== true) return null;
496
+ const balance = typeof credits.balance === "string" || typeof credits.balance === "number" ? Number(credits.balance) : Number.NaN;
497
+ if (!unlimited && balance <= 0) return null;
498
+ return { balance: Number.isFinite(balance) ? balance : null, unlimited };
499
+ }
500
+
474
501
  /** Banked reset credits, from `rateLimitResetCredits` (`availableCount` is a JSON number on the wire). */
475
502
  export function resetCount(summary: unknown): number {
476
503
  const count = (summary as { availableCount?: unknown } | null)?.availableCount;
@@ -1,5 +1,6 @@
1
1
  import { randomUUID } from "node:crypto";
2
2
  import type { PluginHookContext } from "@getpaseo/plugin/server";
3
+ import { sameAccountIdentity } from "./account-identity";
3
4
  import type { AgentTimelineItem } from "./adapter";
4
5
  import { buildTranscript, CONTINUED_FROM_LABEL, continueInNewAgent, keepEnds, type Continuation } from "./handoff";
5
6
  import { Mutex } from "./json-file";
@@ -49,7 +50,9 @@ function boundTo(state: StoredState, agentId: string, accountId: string): boolea
49
50
  /** The account still exists, can take work and is still signed in as the same person. */
50
51
  function stillUsable(state: StoredState, account: StoredAccount): boolean {
51
52
  const current = findAccount(state, account.id);
52
- return current !== undefined && isUsable(current, Date.now()) && current.identity === account.identity && current.email === account.email;
53
+ // Upkeep may add the member's email to an old workspace-only Codex key during the handoff; that's the same person.
54
+ return current !== undefined && isUsable(current, Date.now()) &&
55
+ (current.identity === account.identity || sameAccountIdentity(account.family, current, account)) && current.email === account.email;
53
56
  }
54
57
 
55
58
  function member(account: StoredAccount): Member {
@@ -437,7 +440,8 @@ function pickDestination(
437
440
  ): Destination {
438
441
  const candidate = Object.entries(chain.members).find(([id, entry]) => {
439
442
  const agent = snapshots.get(id);
440
- return id !== sourceAgent.id && entry.accountId === account.id && entry.identity !== null && entry.identity === account.identity &&
443
+ // A tab recorded under an old workspace-only Codex key is matched by its saved email.
444
+ return id !== sourceAgent.id && entry.accountId === account.id && sameAccountIdentity(account.family, entry, account) &&
441
445
  entry.email === account.email && boundTo(state, id, account.id) &&
442
446
  agent !== undefined && samePlace(sourceAgent, agent) && !agent.archivedAt && !agent.providerUnavailable;
443
447
  });
package/server/limits.ts CHANGED
@@ -5,17 +5,20 @@ import type { AgentTimelineItem, LimitHit, LimitKind, TurnEvent } from "./adapte
5
5
  * plus the legacy `Claude AI usage limit reached|<epoch>`. Each must be followed by the CLI's own
6
6
  * separator (" · …", ".") or end the line, so prose like "You've hit your GitHub API rate limit"
7
7
  * never matches. Warnings ("You've used 80%…") and capacity 429s ("…not your usage limit") are
8
- * deliberately absent: switching accounts doesn't help with those.
8
+ * deliberately absent: switching accounts doesn't help with those. Claude Code 2.1.312 renamed the
9
+ * session limit the "5-hour limit"; older builds still print "session limit". A plain "usage limit"
10
+ * is a budget: Claude Code prints it for an org on usage-based billing, and as its fallback when the
11
+ * API names no window it knows. Usage readings show neither.
9
12
  */
10
13
  const END = String.raw`(?=\s*(?:·|\.|$))`;
11
14
  const APOSTROPHE = "['’]";
12
15
  const CLAUDE_LIMITS: ReadonlyArray<{ pattern: RegExp; kind: LimitKind }> = [
13
- { pattern: new RegExp(`^You${APOSTROPHE}ve hit your (?:session |weekly |Opus |Sonnet |Fable )?limit${END}`, "i"), kind: "window" },
16
+ { pattern: new RegExp(`^You${APOSTROPHE}ve hit your (?:5-hour |session |weekly |Opus |Sonnet |Fable )?limit${END}`, "i"), kind: "window" },
14
17
  { pattern: new RegExp(`^You${APOSTROPHE}ve reached your (?:Fable|Opus|Sonnet|Haiku)(?: [\\w.]{1,10})? limit${END}`), kind: "window" },
15
18
  { pattern: /Claude AI usage limit reached\|\d{9,}/, kind: "window" },
16
19
  {
17
20
  pattern: new RegExp(
18
- `^You${APOSTROPHE}ve hit your (?:usage credit limit|team${APOSTROPHE}s shared budget|(?:monthly|individual) spend limit|(?:org|channel)${APOSTROPHE}s monthly (?:usage|spend) limit)${END}`,
21
+ `^You${APOSTROPHE}ve hit your (?:usage limit|usage credit limit|team${APOSTROPHE}s shared budget|(?:monthly|individual) spend limit|individual usage limit|(?:org|channel)${APOSTROPHE}s monthly (?:usage|spend) limit)${END}`,
19
22
  "i",
20
23
  ),
21
24
  kind: "budget",
package/server/routing.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { peakUsage } from "../shared/format";
2
2
  import type { Family, Usage } from "../shared/model";
3
+ import { FIVE_HOUR_MINUTES, WEEK_MINUTES } from "./codex";
3
4
  import {
4
5
  accountsOf,
5
6
  defaultAccount,
@@ -10,6 +11,13 @@ import {
10
11
  type StoredState,
11
12
  } from "./state";
12
13
 
14
+ /** Weekly resets only steer a new agent when every account it could use was read this recently. */
15
+ const FRESH_READING_MS = 30 * 60_000;
16
+ /** How soon a weekly reset has to be for its account to be preferred. */
17
+ const NEAR_RESET_MS = 24 * 60 * 60_000;
18
+ /** The most a near-reset account may have used of any window, so it still has room to spare. */
19
+ const NEAR_RESET_MAX_USED_PERCENT = 80;
20
+
13
21
  export function isLimited(account: StoredAccount, now: number): boolean {
14
22
  if (!account.limitedUntil) return false;
15
23
  const until = Date.parse(account.limitedUntil);
@@ -56,6 +64,28 @@ export function mostAvailable(
56
64
  return candidates[0];
57
65
  }
58
66
 
67
+ /** Prefer a weekly reset within a day only when every usable account has fresh, complete usage. */
68
+ function soonestWeeklyReset(state: StoredState, family: Family, usageOf: RouteInput["usageOf"], now: number): StoredAccount | undefined {
69
+ const candidates = accountsOf(state, family).filter((account) => isUsable(account, now));
70
+ const readings = candidates.map((account) => ({ account, usage: usageOf(account.id) }));
71
+ const complete = readings.every(({ usage }) => {
72
+ if (!usage || usage.error || usage.cached) return false;
73
+ const age = now - Date.parse(usage.fetchedAt);
74
+ const short = usage.windows.find((window) => window.minutes === FIVE_HOUR_MINUTES);
75
+ const weekly = usage.windows.find((window) => window.minutes === WEEK_MINUTES);
76
+ return Number.isFinite(age) && age >= 0 && age <= FRESH_READING_MS && !!short && !!weekly &&
77
+ [short, weekly].every((window) => Number.isFinite(window.usedPercent) && window.usedPercent >= 0 &&
78
+ window.usedPercent <= 100 && window.resetsAt !== null && Date.parse(window.resetsAt) > now);
79
+ });
80
+ if (!complete) return undefined;
81
+ return readings.filter(({ usage }) => {
82
+ const weekly = usage!.windows.find((window) => window.minutes === WEEK_MINUTES)!;
83
+ return usage!.windows.every((window) => window.usedPercent <= NEAR_RESET_MAX_USED_PERCENT) &&
84
+ Date.parse(weekly.resetsAt!) - now <= NEAR_RESET_MS;
85
+ }).sort((a, b) => Date.parse(a.usage!.windows.find((window) => window.minutes === WEEK_MINUTES)!.resetsAt!) -
86
+ Date.parse(b.usage!.windows.find((window) => window.minutes === WEEK_MINUTES)!.resetsAt!))[0]?.account;
87
+ }
88
+
59
89
  export interface RouteInput {
60
90
  agentId: string;
61
91
  family: Family;
@@ -98,8 +128,9 @@ export function chooseAccount(state: StoredState, input: RouteInput): RouteDecis
98
128
  let bind: Binding | null = null;
99
129
 
100
130
  if (!account && fresh && input.balanceNewAgents && accounts.length > 1) {
101
- account = mostAvailable(state, input.family, input.usageOf, input.now);
102
- if (account) bind = { accountId: account.id, source: "balance", at };
131
+ const nearReset = input.family === "codex" ? soonestWeeklyReset(state, input.family, input.usageOf, input.now) : undefined;
132
+ account = nearReset ?? mostAvailable(state, input.family, input.usageOf, input.now);
133
+ if (account) bind = { accountId: account.id, source: "balance", at, selectionReason: nearReset ? "weekly_reset" : "headroom" };
103
134
  }
104
135
  if (!account) {
105
136
  // An imported Codex thread most likely came from the user's own CLI, so it belongs to that login.
package/server/service.ts CHANGED
@@ -31,6 +31,7 @@ import {
31
31
  type UsageRead,
32
32
  } from "./adapter";
33
33
  import { FamilyResolver } from "./families";
34
+ import { sameAccountIdentity } from "./account-identity";
34
35
  import { CodexContinuations } from "./continuations";
35
36
  import { CONTINUED_FROM_LABEL, continueInNewAgent, type Continuation } from "./handoff";
36
37
  import { removeHome } from "./homes";
@@ -41,7 +42,7 @@ import { equivalentMode } from "./modes";
41
42
  import { homesDir } from "./paths";
42
43
  import { Reopener } from "./reopen";
43
44
  import { SwitchGuard } from "./switch-guard";
44
- import { loadReadings, mergeUsage, saveReadings, showLimit } from "./usage";
45
+ import { loadReadings, mergeUsage, pastReset, saveReadings, showLimit } from "./usage";
45
46
  import { chooseAccount, isLimited, isUsable, mostAvailable } from "./routing";
46
47
  import {
47
48
  MAIN_ACCOUNT_ID,
@@ -65,6 +66,8 @@ const OTHER_FAMILY: Record<Family, Family> = { claude: "codex", codex: "claude"
65
66
  const USAGE_BUSY_MS = 60_000;
66
67
  const USAGE_DEFAULT_MS = 5 * 60_000;
67
68
  const USAGE_IDLE_MS = 20 * 60_000;
69
+ /** Background reads renew an expired sign-in (slow) at most this often per account. Explicit refreshes (↻) aren't limited. */
70
+ const RENEW_LOGIN_MS = 30 * 60_000;
68
71
  /** An account counts as in use for this long after one of its agents starts or ends a turn. */
69
72
  const ACTIVE_WINDOW_MS = 15 * 60_000;
70
73
  const UPKEEP_MS = 30_000;
@@ -95,6 +98,7 @@ const DEFAULT_PREFERENCES: Preferences = {
95
98
  balanceNewAgents: false,
96
99
  showComposerPill: true,
97
100
  autoRedeem: false,
101
+ useCredits: false,
98
102
  forkOtherProvider: false,
99
103
  };
100
104
 
@@ -160,6 +164,10 @@ export class Service {
160
164
  private readonly activeAt = new Map<string, number>();
161
165
  /** The provider asked us not to read this account's usage again before then. */
162
166
  private readonly usageRetryAt = new Map<string, number>();
167
+ /** When a usage read last asked each account's CLI to renew its sign-in. */
168
+ private readonly renewAttemptAt = new Map<string, number>();
169
+ /** Accounts whose last usage read was live, rather than an error or the CLI's cached copy. */
170
+ private readonly usageLive = new Set<string>();
163
171
  private usageSave: ReturnType<typeof setTimeout> | null = null;
164
172
  private readonly lastRedeemAt = new Map<string, number>();
165
173
  private readonly redeemLocks = new Map<string, Mutex>();
@@ -537,7 +545,7 @@ export class Service {
537
545
  const accountId = this.runningOn(await this.store.read(), agentId, family);
538
546
  if (accountId && !this.recentlyRedeemed(accountId)) {
539
547
  const hit = problem.hit;
540
- await this.markLimited(accountId, hit.resetsAt ?? new Date(Date.now() + (hit.kind === "budget" ? BUDGET_LIMIT_MS : WINDOW_LIMIT_MS)).toISOString(), hit.kind);
548
+ await this.markLimited(accountId, hit.resetsAt ?? new Date(Date.now() + (hit.kind === "budget" ? BUDGET_LIMIT_MS : WINDOW_LIMIT_MS)).toISOString(), hit.kind, "turn");
541
549
  }
542
550
  }
543
551
  return;
@@ -599,7 +607,7 @@ export class Service {
599
607
  if (problem.kind === "limit") {
600
608
  const { hit } = problem;
601
609
  resetsAt = hit.resetsAt ?? new Date(now + (hit.kind === "budget" ? BUDGET_LIMIT_MS : WINDOW_LIMIT_MS)).toISOString();
602
- await this.markLimited(account.id, resetsAt, hit.kind);
610
+ await this.markLimited(account.id, resetsAt, hit.kind, "turn");
603
611
  if (hit.kind === "window") {
604
612
  // The notice is the freshest word on usage: show that window full until a new reading lands.
605
613
  const shown = this.usage.get(account.id);
@@ -609,7 +617,7 @@ export class Service {
609
617
  const exact = this.resetFromUsage(account.id);
610
618
  if (exact && Date.parse(exact) > now) {
611
619
  resetsAt = exact;
612
- await this.markLimited(account.id, exact, "window");
620
+ await this.markLimited(account.id, exact, "window", "turn");
613
621
  }
614
622
  }
615
623
  console.log(`[ZeroSub] ${account.label} hit a ${hit.kind} limit (agent ${agentId}): ${hit.message}`);
@@ -812,13 +820,14 @@ export class Service {
812
820
  });
813
821
  }
814
822
 
815
- private async markLimited(accountId: string, until: string, kind: LimitKind): Promise<void> {
823
+ private async markLimited(accountId: string, until: string, kind: LimitKind, source: "turn" | "reading"): Promise<void> {
816
824
  await this.store.update((draft) => {
817
825
  const account = findAccount(draft, accountId);
818
826
  if (!account) return;
819
827
  account.limitedUntil = until;
820
828
  account.limitKind = kind;
821
829
  account.limitedAt = new Date().toISOString();
830
+ account.limitSource = source;
822
831
  });
823
832
  }
824
833
 
@@ -1279,7 +1288,10 @@ export class Service {
1279
1288
 
1280
1289
  // ------------------------------------------------------------------ usage
1281
1290
 
1282
- /** `renewLogin` lets the CLI refresh an expired sign-in first (explicit refreshes only: it's slow). */
1291
+ /**
1292
+ * `renewLogin` lets the CLI refresh an expired sign-in first (explicit refreshes: it's slow). Other
1293
+ * reads may renew it too, at most every RENEW_LOGIN_MS (see `renewsInBackground`).
1294
+ */
1283
1295
  refreshUsage(accountId: string, force = false, renewLogin = false): Promise<void> {
1284
1296
  const pending = this.usageInFlight.get(accountId);
1285
1297
  if (pending) return pending;
@@ -1293,26 +1305,37 @@ export class Service {
1293
1305
  const spacing = this.adapters[account.family].usageSpacingMs;
1294
1306
  if (since < (force ? spacing : Math.max(spacing, 60_000))) return;
1295
1307
  this.usageAttemptAt.set(accountId, Date.now());
1296
- const { retryAt, ...usage } = await this.adapters[account.family]
1297
- .usage(account.home, { renewLogin })
1308
+ const renew = renewLogin || this.renewsInBackground(account, Date.now());
1309
+ if (renew) this.renewAttemptAt.set(accountId, Date.now());
1310
+ const { retryAt, ...read } = await this.adapters[account.family]
1311
+ .usage(account.home, { renewLogin: renew })
1298
1312
  .catch(
1299
1313
  (error: unknown): UsageRead => ({ fetchedAt: new Date().toISOString(), windows: [], error: describe(error), cached: false, resets: null }),
1300
1314
  );
1301
1315
  if (retryAt) this.usageRetryAt.set(accountId, retryAt);
1302
1316
  else this.usageRetryAt.delete(accountId);
1317
+ const usage: Usage = { ...read, credits: read.credits ?? null };
1303
1318
  this.setUsage(accountId, mergeUsage(this.usage.get(accountId), usage));
1304
1319
  // Only a live reading may change an account's limit state.
1305
- if (usage.windows.length === 0 || usage.error || usage.cached) return;
1320
+ if (usage.windows.length === 0 || usage.error || usage.cached) {
1321
+ this.usageLive.delete(accountId);
1322
+ return;
1323
+ }
1324
+ this.usageLive.add(accountId);
1306
1325
  const now = Date.now();
1307
- const full = usage.windows.find((window) => window.usedPercent >= 100 && window.resetsAt);
1326
+ // With "Use ChatGPT credits when a limit is reached" on, credits keep an account going past a
1327
+ // full window, so a full window alone isn't a limit then.
1328
+ const creditsCover = this.prefs.useCredits && usage.credits != null;
1329
+ const full = creditsCover ? undefined : usage.windows.find((window) => window.usedPercent >= 100 && window.resetsAt);
1308
1330
  if (full && !isLimited(account, now)) {
1309
- await this.markLimited(accountId, full.resetsAt ?? new Date(now + WINDOW_LIMIT_MS).toISOString(), "window");
1331
+ await this.markLimited(accountId, full.resetsAt ?? new Date(now + WINDOW_LIMIT_MS).toISOString(), "window", "reading");
1310
1332
  return;
1311
1333
  }
1312
- // A window limit clears once usage shows room again. Budget limits never appear in usage
1334
+ // A window limit clears once usage shows room again, or once credits cover it if a reading set
1335
+ // it: a limit a turn ran into stands, credits or not. Budget limits never appear in usage
1313
1336
  // windows, and a fresh limit is trusted for a while (it may be on a window we can't see).
1314
1337
  const settled = account.limitedAt ? now - Date.parse(account.limitedAt) > LIMIT_TRUST_MS : true;
1315
- const roomy = Math.max(...usage.windows.map((window) => window.usedPercent)) < 90;
1338
+ const roomy = (creditsCover && account.limitSource === "reading") || Math.max(...usage.windows.map((window) => window.usedPercent)) < 90;
1316
1339
  if (!full && account.limitedUntil && account.limitKind === "window" && settled && roomy) {
1317
1340
  await this.store.update((draft) => {
1318
1341
  const target = findAccount(draft, accountId);
@@ -1326,6 +1349,18 @@ export class Service {
1326
1349
  return task;
1327
1350
  }
1328
1351
 
1352
+ /**
1353
+ * A read nobody asked to renew the sign-in for still renews it when the reading is past a reset
1354
+ * (its old numbers would stay up until the account is next used), or when a window limit has no
1355
+ * live reading (a reset used on another machine, or an early one, wouldn't lift it). At most
1356
+ * every RENEW_LOGIN_MS, and not for a disabled account.
1357
+ */
1358
+ private renewsInBackground(account: StoredAccount, now: number): boolean {
1359
+ if (account.disabled || now - (this.renewAttemptAt.get(account.id) ?? 0) < RENEW_LOGIN_MS) return false;
1360
+ const windowLimited = account.limitKind === "window" && isLimited(account, now);
1361
+ return pastReset(this.usage.get(account.id), now) || (windowLimited && !this.usageLive.has(account.id));
1362
+ }
1363
+
1329
1364
  /** Records a reading and saves the readings shortly after, so a restart shows them straight away. */
1330
1365
  private setUsage(accountId: string, usage: Usage | null): void {
1331
1366
  if (usage) this.usage.set(accountId, usage);
@@ -1367,6 +1402,11 @@ export class Service {
1367
1402
  family,
1368
1403
  accountId,
1369
1404
  pinned: Boolean(binding && binding.source !== "thread"),
1405
+ // Only while the agent is still on the account that was picked for it.
1406
+ selectionReason:
1407
+ binding?.source === "balance" && binding.selectionReason === "weekly_reset" && binding.accountId === accountId
1408
+ ? "weekly_reset"
1409
+ : undefined,
1370
1410
  pendingAccountId: current && current !== accountId ? current : null,
1371
1411
  movable: this.adapters[family].portable || !agent.hasHistory,
1372
1412
  });
@@ -1784,20 +1824,23 @@ export class Service {
1784
1824
 
1785
1825
  const state = await this.store.read();
1786
1826
  const existing = findAccount(state, session.accountId);
1787
- if (existing?.kind === "managed" && existing.identity && identity.identity && existing.identity !== identity.identity) {
1827
+ if (existing?.kind === "managed" && existing.identity && identity.identity && !sameAccountIdentity(session.family, existing, identity)) {
1788
1828
  // Signing an account back in must not quietly turn it into a different login.
1789
1829
  if (session.home) await adapter.logout(session.home).catch(() => undefined);
1790
1830
  const expected = existing.email ?? existing.label;
1831
+ // Only a Codex key can come without the email, and then it doesn't say which member signed in.
1791
1832
  return this.failLogin(
1792
1833
  session,
1793
- `You signed in as ${identity.email ?? "a different account"}, but this is ${expected}. Sign in as ${expected}, or use Add account for the other one.`,
1834
+ identity.email
1835
+ ? `You signed in as ${identity.email}, but this is ${expected}. Sign in as ${expected}, or use Add account for the other one.`
1836
+ : `Couldn't tell which workspace member signed in, because Codex didn't return an email. Sign in again as ${expected}.`,
1794
1837
  );
1795
1838
  }
1796
1839
  // The CLI's own login is whatever the user signs it into; only added accounts must be distinct.
1797
1840
  const duplicate =
1798
1841
  identity.identity && existing?.kind !== "main"
1799
1842
  ? accountsOf(state, session.family).find(
1800
- (account) => account.id !== session.accountId && account.identity === identity.identity,
1843
+ (account) => account.id !== session.accountId && sameAccountIdentity(session.family, account, identity, true),
1801
1844
  )
1802
1845
  : undefined;
1803
1846
  if (duplicate) {
package/server/state.ts CHANGED
@@ -26,6 +26,11 @@ export const StoredAccountSchema = z.object({
26
26
  limitKind: z.enum(["window", "budget"]).nullable().default(null),
27
27
  /** When the current limit was recorded. */
28
28
  limitedAt: z.string().nullable().default(null),
29
+ /**
30
+ * What reported the current limit: a turn's limit notice, or a usage reading. Missing for limits
31
+ * saved by earlier versions, which count as a turn's.
32
+ */
33
+ limitSource: z.enum(["turn", "reading"]).optional(),
29
34
  createdAt: z.string(),
30
35
  });
31
36
  export type StoredAccount = z.infer<typeof StoredAccountSchema>;
@@ -39,6 +44,7 @@ export const BindingSchema = z.object({
39
44
  */
40
45
  source: z.enum(["user", "auto", "balance", "thread"]),
41
46
  at: z.string(),
47
+ selectionReason: z.enum(["weekly_reset", "headroom"]).optional(),
42
48
  });
43
49
  export type Binding = z.infer<typeof BindingSchema>;
44
50
 
package/server/usage.ts CHANGED
@@ -47,6 +47,14 @@ export function mergeUsage(previous: Usage | undefined, next: Usage): Usage {
47
47
  return next;
48
48
  }
49
49
 
50
+ /**
51
+ * A window in the reading has already reset, so its numbers are out of date. An idle account's
52
+ * sign-in can expire while it sits full, and only a renewed sign-in reads it again.
53
+ */
54
+ export function pastReset(usage: Usage | undefined, now: number): boolean {
55
+ return Boolean(usage?.windows.some((window) => window.resetsAt && Date.parse(window.resetsAt) <= now));
56
+ }
57
+
50
58
  function usagePath(): string {
51
59
  return join(dataDir(), "usage.json");
52
60
  }
package/shared/format.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { AccountView, UsageWindow } from "./model";
1
+ import type { AccountView, Credits, UsageWindow } from "./model";
2
2
 
3
3
  /** "in 2h 14m", "in 3d 4h", "now". */
4
4
  export function formatResetIn(resetsAt: string | null, now: number = Date.now()): string | null {
@@ -22,6 +22,16 @@ export function formatPercent(value: number): string {
22
22
  return `${Math.round(Math.min(100, Math.max(0, value)))}%`;
23
23
  }
24
24
 
25
+ /** "57,714 ChatGPT credits left", "Unlimited ChatGPT credits", or "ChatGPT credits available" when the balance isn't given. */
26
+ export function formatCredits(credits: Credits): string {
27
+ if (credits.unlimited) return "Unlimited ChatGPT credits";
28
+ if (credits.balance === null) return "ChatGPT credits available";
29
+ // Rounding a last fraction of a credit down would read as none left.
30
+ if (credits.balance < 1) return "Less than 1 ChatGPT credit left";
31
+ const whole = String(Math.floor(credits.balance)).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
32
+ return `${whole} ChatGPT credit${whole === "1" ? "" : "s"} left`;
33
+ }
34
+
25
35
  /** The busiest window decides how close an account is to being cut off. */
26
36
  export function peakUsage(windows: readonly UsageWindow[]): UsageWindow | null {
27
37
  let peak: UsageWindow | null = null;
package/shared/model.ts CHANGED
@@ -16,6 +16,8 @@ export const UsageWindowSchema = z.object({
16
16
  /** 0–100. */
17
17
  usedPercent: z.number(),
18
18
  resetsAt: z.string().nullable(),
19
+ /** How long the window is, in minutes. Only Codex readings have it; `null` when Codex doesn't say. */
20
+ minutes: z.number().nullable().optional(),
19
21
  });
20
22
  export type UsageWindow = z.infer<typeof UsageWindowSchema>;
21
23
 
@@ -36,6 +38,14 @@ export const ResetOfferSchema = z.object({
36
38
  });
37
39
  export type ResetOffer = z.infer<typeof ResetOfferSchema>;
38
40
 
41
+ /** Prepaid credits that keep an account going once its windows run out (ChatGPT credits for Codex). */
42
+ export const CreditsSchema = z.object({
43
+ /** Credits left; `null` when the provider doesn't say how many. */
44
+ balance: z.number().nullable(),
45
+ unlimited: z.boolean(),
46
+ });
47
+ export type Credits = z.infer<typeof CreditsSchema>;
48
+
39
49
  export const UsageSchema = z.object({
40
50
  fetchedAt: z.string(),
41
51
  windows: z.array(UsageWindowSchema),
@@ -45,6 +55,8 @@ export const UsageSchema = z.object({
45
55
  cached: z.boolean().default(false),
46
56
  /** Banked resets, when the provider reports any. */
47
57
  resets: ResetOfferSchema.nullable().default(null),
58
+ /** Credits the account can spend past full windows, when the provider reports any. */
59
+ credits: CreditsSchema.nullable().default(null),
48
60
  });
49
61
  export type Usage = z.infer<typeof UsageSchema>;
50
62
 
@@ -92,6 +104,8 @@ export const AgentRouteSchema = z.object({
92
104
  * continues the work in a new agent instead.
93
105
  */
94
106
  movable: z.boolean(),
107
+ /** The agent started on this account because its weekly reset was near, and is still on it. */
108
+ selectionReason: z.literal("weekly_reset").optional(),
95
109
  });
96
110
  export type AgentRoute = z.infer<typeof AgentRouteSchema>;
97
111
 
@@ -22,10 +22,15 @@ export const preferences = defineSettings({
22
22
  * open at the time. Codex threads never move either way.
23
23
  */
24
24
  moveAgentsOnDefaultChange: z.boolean().default(true),
25
- /** New agents start on the account with the most headroom instead of the default. */
25
+ /** New agents choose an account by usage instead of the default. */
26
26
  balanceNewAgents: z.boolean().default(false),
27
27
  /** When every account of a provider is at its limit, spend a banked reset instead of stopping. */
28
28
  autoRedeem: z.boolean().default(false),
29
+ /**
30
+ * A ChatGPT account at its limit stays in use while it has ChatGPT credits, so new agents may
31
+ * spend paid credits even while another account still has room. A limit a turn ran into stands.
32
+ */
33
+ useCredits: z.boolean().default(false),
29
34
  /**
30
35
  * When every account of a provider is at its limit, carry the chat on in a new agent on the
31
36
  * other provider (Claude ↔ ChatGPT), in a mode no more permissive than the original's.