@kapybara/zerosub 1.4.0 → 1.5.1
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 +20 -6
- package/client/accounts-surface.tsx +11 -2
- package/client/pills.ts +11 -2
- package/client/settings-screen.tsx +8 -1
- package/package.json +1 -1
- package/server/account-identity.ts +22 -0
- package/server/adapter.ts +7 -4
- package/server/claude.ts +6 -6
- package/server/codex.ts +34 -7
- package/server/continuations.ts +68 -4
- package/server/handoff.ts +10 -1
- package/server/limits.ts +6 -3
- package/server/routing.ts +33 -2
- package/server/service.ts +61 -16
- package/server/state.ts +8 -0
- package/server/usage.ts +8 -0
- package/shared/format.ts +11 -1
- package/shared/model.ts +14 -0
- package/shared/preferences.ts +6 -1
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
|
|
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
|
|
|
@@ -58,6 +63,7 @@ Then open **Accounts (ZeroSub)** in the sidebar.
|
|
|
58
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.
|
|
59
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.
|
|
60
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
|
+
- A sub-agent (one another agent started) keeps its parent: its new tab goes under the same agent, or under the tab where that agent's own task now continues. Like the first tab, it's archived with the parent and sends no notifications of its own. Paseo doesn't tell the parent when the new tab finishes, though: it only reports to an agent on agents it started or prompted itself.
|
|
61
67
|
- 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.
|
|
62
68
|
|
|
63
69
|
### Banked resets
|
|
@@ -69,13 +75,21 @@ Some plans come with banked limit resets: ChatGPT's reset credits, and Claude Co
|
|
|
69
75
|
- **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
76
|
- **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
77
|
|
|
78
|
+
### ChatGPT credits
|
|
79
|
+
|
|
80
|
+
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.
|
|
81
|
+
|
|
82
|
+
- 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.
|
|
83
|
+
- **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.
|
|
84
|
+
- 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.
|
|
85
|
+
|
|
72
86
|
### When every account of a provider is out
|
|
73
87
|
|
|
74
88
|
ZeroSub tries these in order, and a timeline note says which one happened:
|
|
75
89
|
|
|
76
90
|
1. **Use a banked reset**, if you turned on **Use banked resets when every account is out**.
|
|
77
91
|
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:
|
|
78
|
-
- 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.
|
|
92
|
+
- The new agent opens in the same workspace (under the same parent, for a sub-agent) 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.
|
|
79
93
|
- 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.
|
|
80
94
|
- 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.
|
|
81
95
|
- With the option off, a stopped agent's account button offers **Continue on ChatGPT (new agent)…** (or Claude) instead, with a confirmation.
|
|
@@ -112,7 +126,7 @@ ZeroSub never implements OAuth itself and never copies credentials between accou
|
|
|
112
126
|
## Privacy and security
|
|
113
127
|
|
|
114
128
|
- 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`.
|
|
129
|
+
- 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
130
|
- 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
131
|
- 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
132
|
- 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 +136,7 @@ ZeroSub never implements OAuth itself and never copies credentials between accou
|
|
|
122
136
|
|
|
123
137
|
- **MCP servers that use OAuth** (Linear, Notion, …) store their tokens per Claude account, so sign in to them once on each account.
|
|
124
138
|
- **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.
|
|
139
|
+
- **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
140
|
- **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
141
|
- **Imported Codex threads** (`paseo agent import`) are assigned to your CLI login, since that's where standalone Codex sessions come from.
|
|
128
142
|
- **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
|
|
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
|
-
|
|
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
|
|
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.
|
|
3
|
+
"version": "1.5.1",
|
|
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
|
-
/**
|
|
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
|
-
/**
|
|
34
|
-
|
|
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,
|
|
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.
|
|
73
|
+
{ clientInfo: { name: CLIENT_NAME, title: "Paseo ZeroSub", version: "1.5.1" }, 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
|
-
//
|
|
316
|
-
//
|
|
317
|
-
identity: accountId
|
|
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 ===
|
|
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;
|
package/server/continuations.ts
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
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
|
-
import { buildTranscript, CONTINUED_FROM_LABEL, continueInNewAgent, keepEnds, type Continuation } from "./handoff";
|
|
5
|
+
import { buildTranscript, CONTINUED_FROM_LABEL, continueInNewAgent, keepEnds, PARENT_LABEL, type Continuation } from "./handoff";
|
|
5
6
|
import { Mutex } from "./json-file";
|
|
6
7
|
import { isUsable } from "./routing";
|
|
7
8
|
import { findAccount, MAIN_ACCOUNT_ID, StateStore, type ContinuationChain, type StoredAccount, type StoredState } from "./state";
|
|
@@ -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
|
-
|
|
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 {
|
|
@@ -86,6 +89,8 @@ interface Destination {
|
|
|
86
89
|
/** The existing tab, when there is one. */
|
|
87
90
|
agent?: Agent;
|
|
88
91
|
entry?: Member;
|
|
92
|
+
/** A new tab's parent agent, if it's created as a sub-agent. */
|
|
93
|
+
parent?: string;
|
|
89
94
|
}
|
|
90
95
|
|
|
91
96
|
/** What the destination hasn't seen yet, and the timeline marks to record once it has. */
|
|
@@ -123,6 +128,40 @@ export class CodexContinuations {
|
|
|
123
128
|
return current.id === agentId ? null : { agentId: current.id, title: current.agent?.title ?? "Codex task" };
|
|
124
129
|
}
|
|
125
130
|
|
|
131
|
+
/**
|
|
132
|
+
* The agent to create a continuation of `agentId` under, so a sub-agent's continuation is still
|
|
133
|
+
* a sub-agent of the agent that started it: that parent, or where the parent's own task carries
|
|
134
|
+
* on if ZeroSub has continued it too (in another ChatGPT tab, or on the other provider). None for
|
|
135
|
+
* an agent without a parent, or when the parent is archived or gone. A failed lookup means none
|
|
136
|
+
* too: the hand-off goes ahead without a parent rather than not at all.
|
|
137
|
+
*/
|
|
138
|
+
async parentFor(paseo: PaseoApi, agentId: string): Promise<string | undefined> {
|
|
139
|
+
try {
|
|
140
|
+
let parentId = (await snapshot(paseo, agentId))?.labels?.[PARENT_LABEL]?.trim();
|
|
141
|
+
let live: Agent[] | undefined;
|
|
142
|
+
// A continuation on the other provider has only its label to go by, as when an earlier fork is reused.
|
|
143
|
+
const forkOf = async (id: string) => {
|
|
144
|
+
const agent = await snapshot(paseo, id);
|
|
145
|
+
if (!agent) return undefined;
|
|
146
|
+
live ??= await liveAgents(paseo);
|
|
147
|
+
return live.find((other) => other.labels?.[CONTINUED_FROM_LABEL] === id && other.provider !== agent.provider && !other.archivedAt)?.id;
|
|
148
|
+
};
|
|
149
|
+
// Each step goes to where that agent's task went next. A loop in the records ends the walk.
|
|
150
|
+
const seen = new Set([agentId]);
|
|
151
|
+
while (parentId && !seen.has(parentId)) {
|
|
152
|
+
seen.add(parentId);
|
|
153
|
+
const next = (await this.continuesElsewhere(paseo, parentId))?.agentId ?? (await forkOf(parentId));
|
|
154
|
+
if (!next) break;
|
|
155
|
+
parentId = next;
|
|
156
|
+
}
|
|
157
|
+
const parent = parentId && parentId !== agentId ? await snapshot(paseo, parentId) : undefined;
|
|
158
|
+
return parent && !parent.archivedAt ? parent.id : undefined;
|
|
159
|
+
} catch (error) {
|
|
160
|
+
console.error(`[ZeroSub] couldn't look up the parent of ${agentId}; continuing it without one`, error instanceof Error ? error.message : error);
|
|
161
|
+
return undefined;
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
|
|
126
165
|
continue(paseo: PaseoApi, sourceAgentId: string, target: StoredAccount, why: string, source: Source): Promise<Continuation> {
|
|
127
166
|
const key = `${sourceAgentId}:${target.id}`;
|
|
128
167
|
const existing = this.inFlight.get(key);
|
|
@@ -154,6 +193,8 @@ export class CodexContinuations {
|
|
|
154
193
|
const gathered = await gatherUpdates(paseo, state, chain, snapshots, sourceAgent, destination);
|
|
155
194
|
const prompt = composePrompt(chain, destination, gathered, why, Boolean(reserved));
|
|
156
195
|
const messageId = reserved?.messageId ?? `${MESSAGE_PREFIX}${randomUUID()}`;
|
|
196
|
+
// A retried creation has to repeat its first request exactly, parent included.
|
|
197
|
+
if (!destination.agent) destination.parent = reserved ? reserved.parent : await this.parentFor(paseo, sourceAgent.id);
|
|
157
198
|
await this.confirmUnchanged(paseo, sourceAgent, destination, account);
|
|
158
199
|
await this.reserve(root, sourceAgent.id, destination, gathered, account, messageId, source);
|
|
159
200
|
return this.deliver(paseo, root, sourceAgent, destination, account, prompt, messageId, why);
|
|
@@ -262,6 +303,7 @@ export class CodexContinuations {
|
|
|
262
303
|
seen: gathered.seen,
|
|
263
304
|
stage: destination.agent ? "sending" : "creating",
|
|
264
305
|
...(gathered.fallback ? { replaceHistory: gathered.obsolete } : {}),
|
|
306
|
+
...(destination.parent ? { parent: destination.parent } : {}),
|
|
265
307
|
};
|
|
266
308
|
if (!destination.agent) draft.bindings[targetId] = { accountId: account.id, source: source === "user" ? "user" : "thread", at: new Date().toISOString() };
|
|
267
309
|
});
|
|
@@ -283,7 +325,15 @@ export class CodexContinuations {
|
|
|
283
325
|
if (destination.agent) {
|
|
284
326
|
result = { agentId: targetId, title: destination.agent.title ?? "Codex task" };
|
|
285
327
|
} else {
|
|
286
|
-
result = await continueInNewAgent({
|
|
328
|
+
result = await continueInNewAgent({
|
|
329
|
+
paseo,
|
|
330
|
+
sourceAgentId: sourceAgent.id,
|
|
331
|
+
why,
|
|
332
|
+
agentId: targetId,
|
|
333
|
+
deferPrompt: true,
|
|
334
|
+
parentId: destination.parent,
|
|
335
|
+
bind: async () => {},
|
|
336
|
+
});
|
|
287
337
|
// Creation can take time. A user may have started another turn or disabled the account.
|
|
288
338
|
const created = await waitForCreated(paseo, targetId);
|
|
289
339
|
const sourceNow = await snapshot(paseo, sourceAgent.id);
|
|
@@ -351,6 +401,19 @@ async function adoptDescendants(paseo: PaseoApi, original: Agent, ancestors: Age
|
|
|
351
401
|
}
|
|
352
402
|
}
|
|
353
403
|
|
|
404
|
+
/** Every agent that isn't archived, as far as MAX_PAGES pages go. */
|
|
405
|
+
async function liveAgents(paseo: PaseoApi): Promise<Agent[]> {
|
|
406
|
+
const agents: Agent[] = [];
|
|
407
|
+
let cursor: string | undefined;
|
|
408
|
+
for (let page = 0; page < MAX_PAGES; page += 1) {
|
|
409
|
+
const result = await paseo.agents.list({ page: { limit: 200, ...(cursor ? { cursor } : {}) } });
|
|
410
|
+
agents.push(...result.entries.map(({ agent }) => agent));
|
|
411
|
+
if (!result.pageInfo.hasMore || !result.pageInfo.nextCursor) break;
|
|
412
|
+
cursor = result.pageInfo.nextCursor;
|
|
413
|
+
}
|
|
414
|
+
return agents;
|
|
415
|
+
}
|
|
416
|
+
|
|
354
417
|
function newer(left: string | null | undefined, right: string | null | undefined): boolean {
|
|
355
418
|
return left ? !right || Date.parse(left) > Date.parse(right) : false;
|
|
356
419
|
}
|
|
@@ -437,7 +500,8 @@ function pickDestination(
|
|
|
437
500
|
): Destination {
|
|
438
501
|
const candidate = Object.entries(chain.members).find(([id, entry]) => {
|
|
439
502
|
const agent = snapshots.get(id);
|
|
440
|
-
|
|
503
|
+
// A tab recorded under an old workspace-only Codex key is matched by its saved email.
|
|
504
|
+
return id !== sourceAgent.id && entry.accountId === account.id && sameAccountIdentity(account.family, entry, account) &&
|
|
441
505
|
entry.email === account.email && boundTo(state, id, account.id) &&
|
|
442
506
|
agent !== undefined && samePlace(sourceAgent, agent) && !agent.archivedAt && !agent.providerUnavailable;
|
|
443
507
|
});
|
package/server/handoff.ts
CHANGED
|
@@ -6,6 +6,8 @@ type PaseoApi = PluginHookContext["paseo"];
|
|
|
6
6
|
|
|
7
7
|
/** Label on a continuation agent naming the agent it carries on from. */
|
|
8
8
|
export const CONTINUED_FROM_LABEL = "zerosub.continued-from";
|
|
9
|
+
/** Paseo's label naming the agent a sub-agent was created by (`PARENT_AGENT_ID_LABEL`). */
|
|
10
|
+
export const PARENT_LABEL = "paseo.parent-agent-id";
|
|
9
11
|
|
|
10
12
|
const MAX_TRANSCRIPT = 40_000;
|
|
11
13
|
const MAX_FIRST_MESSAGE = 6_000;
|
|
@@ -170,6 +172,13 @@ export async function continueInNewAgent(options: {
|
|
|
170
172
|
agentId?: string;
|
|
171
173
|
/** Create the pre-bound tab first; the caller delivers its handoff separately. */
|
|
172
174
|
deferPrompt?: boolean;
|
|
175
|
+
/**
|
|
176
|
+
* Make the new agent a sub-agent of this one, as the source was of its parent. This sets Paseo's
|
|
177
|
+
* parent label rather than `parent`: on a create, `parent` would also turn the first prompt into
|
|
178
|
+
* a message from the parent agent, move an agent made outside a workspace into the parent's, and
|
|
179
|
+
* fail outright once the parent has been closed.
|
|
180
|
+
*/
|
|
181
|
+
parentId?: string;
|
|
173
182
|
}): Promise<Continuation> {
|
|
174
183
|
const { paseo, sourceAgentId } = options;
|
|
175
184
|
const refreshed = await paseo.agents.ref(sourceAgentId).refresh();
|
|
@@ -211,7 +220,7 @@ export async function continueInNewAgent(options: {
|
|
|
211
220
|
config,
|
|
212
221
|
title,
|
|
213
222
|
...(!options.deferPrompt ? { prompt: continuationPrompt(buildTranscript(timeline ?? []), options.why, options.previous) } : {}),
|
|
214
|
-
labels: { [CONTINUED_FROM_LABEL]: sourceAgentId },
|
|
223
|
+
labels: { [CONTINUED_FROM_LABEL]: sourceAgentId, ...(options.parentId ? { [PARENT_LABEL]: options.parentId } : {}) },
|
|
215
224
|
};
|
|
216
225
|
if (source.workspaceId) await paseo.workspaces.ref(source.workspaceId).agents.create(request);
|
|
217
226
|
else await paseo.agents.create({ ...request, cwd: source.cwd });
|
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
|
-
|
|
102
|
-
|
|
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
|
|
|
@@ -1060,6 +1069,7 @@ export class Service {
|
|
|
1060
1069
|
why: source === "auto" ? `every ${FAMILY_LABEL[family]} account reached its usage limit` : `the work was moved to ${name}`,
|
|
1061
1070
|
previous: PROVIDER_NAME[family],
|
|
1062
1071
|
target: { provider, label: name, modeId },
|
|
1072
|
+
parentId: await this.continuations.parentFor(paseo, agentId),
|
|
1063
1073
|
bind: async (newAgentId) => {
|
|
1064
1074
|
await this.store.update((draft) => {
|
|
1065
1075
|
draft.bindings[newAgentId] = {
|
|
@@ -1132,6 +1142,7 @@ export class Service {
|
|
|
1132
1142
|
sourceAgentId: agentId,
|
|
1133
1143
|
timeline,
|
|
1134
1144
|
why,
|
|
1145
|
+
parentId: await this.continuations.parentFor(paseo, agentId),
|
|
1135
1146
|
bind: async (newAgentId) => {
|
|
1136
1147
|
await this.store.update((draft) => {
|
|
1137
1148
|
draft.bindings[newAgentId] = {
|
|
@@ -1279,7 +1290,10 @@ export class Service {
|
|
|
1279
1290
|
|
|
1280
1291
|
// ------------------------------------------------------------------ usage
|
|
1281
1292
|
|
|
1282
|
-
/**
|
|
1293
|
+
/**
|
|
1294
|
+
* `renewLogin` lets the CLI refresh an expired sign-in first (explicit refreshes: it's slow). Other
|
|
1295
|
+
* reads may renew it too, at most every RENEW_LOGIN_MS (see `renewsInBackground`).
|
|
1296
|
+
*/
|
|
1283
1297
|
refreshUsage(accountId: string, force = false, renewLogin = false): Promise<void> {
|
|
1284
1298
|
const pending = this.usageInFlight.get(accountId);
|
|
1285
1299
|
if (pending) return pending;
|
|
@@ -1293,26 +1307,37 @@ export class Service {
|
|
|
1293
1307
|
const spacing = this.adapters[account.family].usageSpacingMs;
|
|
1294
1308
|
if (since < (force ? spacing : Math.max(spacing, 60_000))) return;
|
|
1295
1309
|
this.usageAttemptAt.set(accountId, Date.now());
|
|
1296
|
-
const
|
|
1297
|
-
|
|
1310
|
+
const renew = renewLogin || this.renewsInBackground(account, Date.now());
|
|
1311
|
+
if (renew) this.renewAttemptAt.set(accountId, Date.now());
|
|
1312
|
+
const { retryAt, ...read } = await this.adapters[account.family]
|
|
1313
|
+
.usage(account.home, { renewLogin: renew })
|
|
1298
1314
|
.catch(
|
|
1299
1315
|
(error: unknown): UsageRead => ({ fetchedAt: new Date().toISOString(), windows: [], error: describe(error), cached: false, resets: null }),
|
|
1300
1316
|
);
|
|
1301
1317
|
if (retryAt) this.usageRetryAt.set(accountId, retryAt);
|
|
1302
1318
|
else this.usageRetryAt.delete(accountId);
|
|
1319
|
+
const usage: Usage = { ...read, credits: read.credits ?? null };
|
|
1303
1320
|
this.setUsage(accountId, mergeUsage(this.usage.get(accountId), usage));
|
|
1304
1321
|
// Only a live reading may change an account's limit state.
|
|
1305
|
-
if (usage.windows.length === 0 || usage.error || usage.cached)
|
|
1322
|
+
if (usage.windows.length === 0 || usage.error || usage.cached) {
|
|
1323
|
+
this.usageLive.delete(accountId);
|
|
1324
|
+
return;
|
|
1325
|
+
}
|
|
1326
|
+
this.usageLive.add(accountId);
|
|
1306
1327
|
const now = Date.now();
|
|
1307
|
-
|
|
1328
|
+
// With "Use ChatGPT credits when a limit is reached" on, credits keep an account going past a
|
|
1329
|
+
// full window, so a full window alone isn't a limit then.
|
|
1330
|
+
const creditsCover = this.prefs.useCredits && usage.credits != null;
|
|
1331
|
+
const full = creditsCover ? undefined : usage.windows.find((window) => window.usedPercent >= 100 && window.resetsAt);
|
|
1308
1332
|
if (full && !isLimited(account, now)) {
|
|
1309
|
-
await this.markLimited(accountId, full.resetsAt ?? new Date(now + WINDOW_LIMIT_MS).toISOString(), "window");
|
|
1333
|
+
await this.markLimited(accountId, full.resetsAt ?? new Date(now + WINDOW_LIMIT_MS).toISOString(), "window", "reading");
|
|
1310
1334
|
return;
|
|
1311
1335
|
}
|
|
1312
|
-
// A window limit clears once usage shows room again
|
|
1336
|
+
// A window limit clears once usage shows room again, or once credits cover it if a reading set
|
|
1337
|
+
// it: a limit a turn ran into stands, credits or not. Budget limits never appear in usage
|
|
1313
1338
|
// windows, and a fresh limit is trusted for a while (it may be on a window we can't see).
|
|
1314
1339
|
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;
|
|
1340
|
+
const roomy = (creditsCover && account.limitSource === "reading") || Math.max(...usage.windows.map((window) => window.usedPercent)) < 90;
|
|
1316
1341
|
if (!full && account.limitedUntil && account.limitKind === "window" && settled && roomy) {
|
|
1317
1342
|
await this.store.update((draft) => {
|
|
1318
1343
|
const target = findAccount(draft, accountId);
|
|
@@ -1326,6 +1351,18 @@ export class Service {
|
|
|
1326
1351
|
return task;
|
|
1327
1352
|
}
|
|
1328
1353
|
|
|
1354
|
+
/**
|
|
1355
|
+
* A read nobody asked to renew the sign-in for still renews it when the reading is past a reset
|
|
1356
|
+
* (its old numbers would stay up until the account is next used), or when a window limit has no
|
|
1357
|
+
* live reading (a reset used on another machine, or an early one, wouldn't lift it). At most
|
|
1358
|
+
* every RENEW_LOGIN_MS, and not for a disabled account.
|
|
1359
|
+
*/
|
|
1360
|
+
private renewsInBackground(account: StoredAccount, now: number): boolean {
|
|
1361
|
+
if (account.disabled || now - (this.renewAttemptAt.get(account.id) ?? 0) < RENEW_LOGIN_MS) return false;
|
|
1362
|
+
const windowLimited = account.limitKind === "window" && isLimited(account, now);
|
|
1363
|
+
return pastReset(this.usage.get(account.id), now) || (windowLimited && !this.usageLive.has(account.id));
|
|
1364
|
+
}
|
|
1365
|
+
|
|
1329
1366
|
/** Records a reading and saves the readings shortly after, so a restart shows them straight away. */
|
|
1330
1367
|
private setUsage(accountId: string, usage: Usage | null): void {
|
|
1331
1368
|
if (usage) this.usage.set(accountId, usage);
|
|
@@ -1367,6 +1404,11 @@ export class Service {
|
|
|
1367
1404
|
family,
|
|
1368
1405
|
accountId,
|
|
1369
1406
|
pinned: Boolean(binding && binding.source !== "thread"),
|
|
1407
|
+
// Only while the agent is still on the account that was picked for it.
|
|
1408
|
+
selectionReason:
|
|
1409
|
+
binding?.source === "balance" && binding.selectionReason === "weekly_reset" && binding.accountId === accountId
|
|
1410
|
+
? "weekly_reset"
|
|
1411
|
+
: undefined,
|
|
1370
1412
|
pendingAccountId: current && current !== accountId ? current : null,
|
|
1371
1413
|
movable: this.adapters[family].portable || !agent.hasHistory,
|
|
1372
1414
|
});
|
|
@@ -1784,20 +1826,23 @@ export class Service {
|
|
|
1784
1826
|
|
|
1785
1827
|
const state = await this.store.read();
|
|
1786
1828
|
const existing = findAccount(state, session.accountId);
|
|
1787
|
-
if (existing?.kind === "managed" && existing.identity && identity.identity &&
|
|
1829
|
+
if (existing?.kind === "managed" && existing.identity && identity.identity && !sameAccountIdentity(session.family, existing, identity)) {
|
|
1788
1830
|
// Signing an account back in must not quietly turn it into a different login.
|
|
1789
1831
|
if (session.home) await adapter.logout(session.home).catch(() => undefined);
|
|
1790
1832
|
const expected = existing.email ?? existing.label;
|
|
1833
|
+
// Only a Codex key can come without the email, and then it doesn't say which member signed in.
|
|
1791
1834
|
return this.failLogin(
|
|
1792
1835
|
session,
|
|
1793
|
-
|
|
1836
|
+
identity.email
|
|
1837
|
+
? `You signed in as ${identity.email}, but this is ${expected}. Sign in as ${expected}, or use Add account for the other one.`
|
|
1838
|
+
: `Couldn't tell which workspace member signed in, because Codex didn't return an email. Sign in again as ${expected}.`,
|
|
1794
1839
|
);
|
|
1795
1840
|
}
|
|
1796
1841
|
// The CLI's own login is whatever the user signs it into; only added accounts must be distinct.
|
|
1797
1842
|
const duplicate =
|
|
1798
1843
|
identity.identity && existing?.kind !== "main"
|
|
1799
1844
|
? accountsOf(state, session.family).find(
|
|
1800
|
-
(account) => account.id !== session.accountId &&
|
|
1845
|
+
(account) => account.id !== session.accountId && sameAccountIdentity(session.family, account, identity, true),
|
|
1801
1846
|
)
|
|
1802
1847
|
: undefined;
|
|
1803
1848
|
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
|
|
|
@@ -71,6 +77,8 @@ export const ContinuationChainSchema = z.object({
|
|
|
71
77
|
seen: z.record(z.string(), TimelineMarkSchema),
|
|
72
78
|
stage: z.enum(["creating", "sending"]).default("sending"),
|
|
73
79
|
replaceHistory: z.array(z.string()).optional(),
|
|
80
|
+
/** The agent a new tab is created under. A retried creation must repeat its first request. */
|
|
81
|
+
parent: z.string().optional(),
|
|
74
82
|
}).optional(),
|
|
75
83
|
});
|
|
76
84
|
export type ContinuationChain = z.infer<typeof ContinuationChainSchema>;
|
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
|
|
package/shared/preferences.ts
CHANGED
|
@@ -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
|
|
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.
|