@kapybara/zerosub 1.3.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,15 +46,24 @@ 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…".
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.
49
51
  - A short note in the agent's timeline says what happened.
50
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.
51
- - 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.
52
58
 
53
59
  ### Claude vs. ChatGPT when switching mid-conversation
54
60
 
55
61
  - **Claude:** a conversation moves to another account in place. The agent reopens on the new account with its full history and continues.
56
- - **ChatGPT (Codex):** Codex encrypts its reasoning per ChatGPT account, so another account can't read an existing thread. The thread stays on its account. When it hits a limit, or you pick another account for it, ZeroSub starts a **continuation agent** on the other account. It goes in the same workspace and gets a transcript of the conversation so far, so the work keeps going. New Codex agents simply start on the chosen account.
62
+ - **ChatGPT (Codex):** Codex encrypts its reasoning per ChatGPT account, so another account can't read an existing thread. The thread stays on its account. When it hits a limit, or you pick another account for it, ZeroSub carries the task on in its tab for the other account: a **continuation agent** in the same workspace, created on the first visit and reused after that. Switching A → B → A → B keeps two tabs, not four. Independent tasks keep separate tabs, even in the same workspace.
63
+ - A tab you return to gets the instructions and progress since it was last used, and checks the current files and Git diff before going on. Very long instructions are shortened, keeping the first one since the tab was last used (the original request, for a new tab), the latest ones and a note of how many were left out.
64
+ - You can type in any of a task's tabs and switch from any of them. The tab you used last is where the task continues: automatic switches and resets only move that tab, and another tab that hits a limit says in its timeline where the task went.
65
+ - A tab is reused while it is in the same workspace with the same account and permission mode; otherwise ZeroSub starts a new one. While one of the task's tabs is working or asking for permission, a switch you pick is refused until it stops, and an automatic switch leaves the task where it is and says so in its timeline.
66
+ - ZeroSub never sends a hand-off twice. If a lost connection leaves one unconfirmed, the switch stops and names the tab to check. Continuation agents from earlier versions are picked up on the first switch. New Codex agents simply start on the chosen account.
57
67
 
58
68
  ### Banked resets
59
69
 
@@ -64,13 +74,21 @@ Some plans come with banked limit resets: ChatGPT's reset credits, and Claude Co
64
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.
65
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.
66
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
+
67
85
  ### When every account of a provider is out
68
86
 
69
87
  ZeroSub tries these in order, and a timeline note says which one happened:
70
88
 
71
89
  1. **Use a banked reset**, if you turned on **Use banked resets when every account is out**.
72
90
  2. **Fork the chat to the other provider**, if you turned on **When every account is out, fork the chat to the other provider** (off by default). A stopped Claude chat continues in a new ChatGPT agent, or the other way round:
73
- - The new agent opens in the same workspace with the conversation so far and goes straight back to work. It uses the other provider's default model and its account with the most room left.
91
+ - The new agent opens in the same workspace with the conversation so far and goes straight back to work. If that conversation began as a hand-off itself, only the start and end of the earlier one are quoted. It uses the other provider's default model and its account with the most room left.
74
92
  - Its permission mode matches the original's level. Bypass becomes Full Access, and Accept File Edits becomes Default Permissions. Codex has no read-only or ask-first mode, so a Claude agent in Plan Mode or Always Ask isn't forked. ZeroSub never gives a fork more freedom than you gave the original.
75
93
  - The original agent stays as it was, and prompting it again while its provider is still out points to the same fork rather than starting another.
76
94
  - With the option off, a stopped agent's account button offers **Continue on ChatGPT (new agent)…** (or Claude) instead, with a confirmation.
@@ -106,8 +124,8 @@ ZeroSub never implements OAuth itself and never copies credentials between accou
106
124
 
107
125
  ## Privacy and security
108
126
 
109
- - Credentials stay in the CLIs' own stores. ZeroSub's registry (`$PASEO_HOME/zerosub/state.json`) holds only account names, emails, plans and which agent uses which account.
110
- - 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`.
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.
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`.
111
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).
112
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.
113
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.
@@ -117,7 +135,7 @@ ZeroSub never implements OAuth itself and never copies credentials between accou
117
135
 
118
136
  - **MCP servers that use OAuth** (Linear, Notion, …) store their tokens per Claude account, so sign in to them once on each account.
119
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.
120
- - **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.
121
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.
122
140
  - **Imported Codex threads** (`paseo agent import`) are assigned to your CLI login, since that's where standalone Codex sessions come from.
123
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";
@@ -169,13 +169,13 @@ function buttonFor(
169
169
  await store.rpc(setAgentAccount, { agentId: agent.id, accountId });
170
170
  };
171
171
 
172
- // Codex threads can't change ChatGPT accounts in place; picking one continues in a new agent.
172
+ // Codex threads can't change accounts in place; continue in this task's tab for that account.
173
173
  const movable = route?.movable ?? true;
174
174
  const items: PluginButtonMenuEntry[] = accounts.map((account, index) => ({
175
175
  kind: "item",
176
176
  id: `account-${index}`,
177
- title: account.id === current.id || movable ? menuTitle(account) : `Continue on ${account.label} (new agent)`,
178
- icon: account.id === current.id ? "CircleCheck" : movable ? "Circle" : "CopyPlus",
177
+ title: account.id === current.id || movable ? menuTitle(account) : `Continue on ${account.label}`,
178
+ icon: account.id === current.id ? "CircleCheck" : movable ? "Circle" : "ArrowRightLeft",
179
179
  disabled: account.status === "signed_out" || account.status === "disabled" || account.id === current.id,
180
180
  behavior: { kind: "action", onPress: choose(account.id) },
181
181
  }));
@@ -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."
@@ -56,7 +56,7 @@ export function describeRow(row: SwitchRow): string {
56
56
  switch (row.outcome) {
57
57
  case "continued":
58
58
  return row.continuedIn
59
- ? `${lead}ChatGPT conversations can't change accounts, so this one continues in a new agent: “${row.continuedIn.title}” on ${row.to}.`
59
+ ? `${lead}ChatGPT conversations can't change accounts, so this task continues in “${row.continuedIn.title}” on ${row.to}.`
60
60
  : `${lead}Continuing on ${row.to}.`;
61
61
  case "stayed":
62
62
  return `${lead}This conversation stays on ${row.from ?? "its account"}.${row.detail ? ` ${row.detail}` : ""}`;
@@ -80,9 +80,7 @@ export function SwitchRowView({ item, theme }: PluginTimelineItemProps<SwitchRow
80
80
  ? "GitFork"
81
81
  : row.reason === "exhausted" || row.outcome === "stayed"
82
82
  ? "CircleAlert"
83
- : row.outcome === "continued"
84
- ? "CopyPlus"
85
- : row.outcome === "reset"
83
+ : row.outcome === "reset"
86
84
  ? "TimerReset"
87
85
  : "ArrowRightLeft";
88
86
  return (
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kapybara/zerosub",
3
- "version": "1.3.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.3.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;