@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/server/service.ts CHANGED
@@ -31,15 +31,18 @@ import {
31
31
  type UsageRead,
32
32
  } from "./adapter";
33
33
  import { FamilyResolver } from "./families";
34
+ import { sameAccountIdentity } from "./account-identity";
35
+ import { CodexContinuations } from "./continuations";
34
36
  import { CONTINUED_FROM_LABEL, continueInNewAgent, type Continuation } from "./handoff";
35
37
  import { removeHome } from "./homes";
36
38
  import { Mutex } from "./json-file";
39
+ import { turnRows } from "./limits";
37
40
  import { canSignInWithBrowser } from "./machine";
38
41
  import { equivalentMode } from "./modes";
39
42
  import { homesDir } from "./paths";
40
43
  import { Reopener } from "./reopen";
41
44
  import { SwitchGuard } from "./switch-guard";
42
- import { loadReadings, mergeUsage, saveReadings, showLimit } from "./usage";
45
+ import { loadReadings, mergeUsage, pastReset, saveReadings, showLimit } from "./usage";
43
46
  import { chooseAccount, isLimited, isUsable, mostAvailable } from "./routing";
44
47
  import {
45
48
  MAIN_ACCOUNT_ID,
@@ -48,6 +51,7 @@ import {
48
51
  defaultAccount,
49
52
  findAccount,
50
53
  mainAccount,
54
+ type ContinuationChain,
51
55
  type StoredAccount,
52
56
  type StoredState,
53
57
  } from "./state";
@@ -62,6 +66,8 @@ const OTHER_FAMILY: Record<Family, Family> = { claude: "codex", codex: "claude"
62
66
  const USAGE_BUSY_MS = 60_000;
63
67
  const USAGE_DEFAULT_MS = 5 * 60_000;
64
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;
65
71
  /** An account counts as in use for this long after one of its agents starts or ends a turn. */
66
72
  const ACTIVE_WINDOW_MS = 15 * 60_000;
67
73
  const UPKEEP_MS = 30_000;
@@ -81,6 +87,8 @@ const RESET_GRACE_MS = 5 * 60_000;
81
87
  const AGENT_LIST_MS = 3_000;
82
88
  /** How long a default change waits for sessions already being routed to record their account. */
83
89
  const ROUTING_WAIT_MS = 5_000;
90
+ /** How long the end of a turn waits for Paseo to page the agent's timeline. The SDK itself waits 60 s. */
91
+ const TURN_READ_MS = 10_000;
84
92
 
85
93
  const DEFAULT_PREFERENCES: Preferences = {
86
94
  autoSwitch: true,
@@ -90,6 +98,7 @@ const DEFAULT_PREFERENCES: Preferences = {
90
98
  balanceNewAgents: false,
91
99
  showComposerPill: true,
92
100
  autoRedeem: false,
101
+ useCredits: false,
93
102
  forkOtherProvider: false,
94
103
  };
95
104
 
@@ -130,6 +139,7 @@ function emptySummary(): ReopenSummary {
130
139
  }
131
140
 
132
141
  export class Service {
142
+ private readonly continuations: CodexContinuations;
133
143
  private paseo: PaseoApi | null = null;
134
144
  private prefs: Preferences = DEFAULT_PREFERENCES;
135
145
  private readonly usage = new Map<string, Usage>();
@@ -148,12 +158,16 @@ export class Service {
148
158
  /** One failover at a time per exhausted account. */
149
159
  private readonly failoverLocks = new Map<string, Mutex>();
150
160
  private readonly switchGuard = new SwitchGuard();
151
- /** When the guard last told an agent's timeline it stopped switching, so it says so once. */
161
+ /** When ZeroSub last told an agent's timeline why it didn't switch, by agent and notice, so it says so once. */
152
162
  private readonly guardNoticeAt = new Map<string, number>();
153
163
  /** When each account's agents last started or ended a turn, to read busy accounts often. */
154
164
  private readonly activeAt = new Map<string, number>();
155
165
  /** The provider asked us not to read this account's usage again before then. */
156
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>();
157
171
  private usageSave: ReturnType<typeof setTimeout> | null = null;
158
172
  private readonly lastRedeemAt = new Map<string, number>();
159
173
  private readonly redeemLocks = new Map<string, Mutex>();
@@ -169,7 +183,9 @@ export class Service {
169
183
  private readonly store = new StateStore(),
170
184
  private readonly families = new FamilyResolver(),
171
185
  private readonly reopener = new Reopener(),
172
- ) {}
186
+ ) {
187
+ this.continuations = new CodexContinuations(store);
188
+ }
173
189
 
174
190
  setPreferences(prefs: Preferences): void {
175
191
  this.prefs = prefs;
@@ -274,10 +290,18 @@ export class Service {
274
290
  const old = (at: string) => now - (Date.parse(at) || 0) > PRUNE_MS;
275
291
  const staleSessions = Object.entries(state.sessions).filter(([id, session]) => !known.has(id) && old(session.openedAt));
276
292
  const staleBindings = Object.entries(state.bindings).filter(([id, binding]) => !known.has(id) && old(binding.at));
277
- if (staleSessions.length === 0 && staleBindings.length === 0) return;
293
+ const active = new Set(agents.filter((agent) => !agent.archived).map((agent) => agent.id));
294
+ // A hand-off that may have sent its prompt stays on record while its tab could come back. A
295
+ // failed creation sent nothing, so it doesn't keep the task's record alive.
296
+ const unsettled = (pending: ContinuationChain["pending"]) => pending?.stage === "sending" && known.has(pending.agentId);
297
+ const staleChains = Object.entries(state.continuations).filter(([, chain]) =>
298
+ !unsettled(chain.pending) && Object.keys(chain.members).every((id) => !active.has(id) && !this.switching.has(id)),
299
+ );
300
+ if (staleSessions.length === 0 && staleBindings.length === 0 && staleChains.length === 0) return;
278
301
  await this.store.update((draft) => {
279
302
  for (const [id] of staleSessions) delete draft.sessions[id];
280
303
  for (const [id] of staleBindings) delete draft.bindings[id];
304
+ for (const [id] of staleChains) delete draft.continuations[id];
281
305
  });
282
306
  }
283
307
 
@@ -423,10 +447,13 @@ export class Service {
423
447
  const accountId = this.runningOn(await this.store.read(), agentId, family);
424
448
  if (accountId) this.activeAt.set(accountId, Date.now());
425
449
  if (event.outcome.kind !== "canceled") {
426
- const hit = adapter.detectLimit(event);
427
- if (hit) return this.handleUnavailable(context.paseo, agentId, family, event.timeline, { kind: "limit", hit });
428
- if (adapter.detectSignOut(event) && (await this.confirmSignedOut(agentId, family))) {
429
- return this.handleUnavailable(context.paseo, agentId, family, event.timeline, { kind: "signed_out" });
450
+ const turn = await this.turnWithTimeline(context.paseo, event);
451
+ // A hand-off quotes the whole conversation, not just this turn. Paseo 0.13 sends none, so the hand-off pages it.
452
+ const conversation = event.timeline.length > 0 ? event.timeline : undefined;
453
+ const hit = adapter.detectLimit(turn);
454
+ if (hit) return this.handleUnavailable(context.paseo, agentId, family, conversation, { kind: "limit", hit });
455
+ if (adapter.detectSignOut(turn) && (await this.confirmSignedOut(agentId, family))) {
456
+ return this.handleUnavailable(context.paseo, agentId, family, conversation, { kind: "signed_out" });
430
457
  }
431
458
  }
432
459
  if (this.deferred.has(agentId)) await this.finishDeferred(context.paseo, agentId, family);
@@ -434,10 +461,42 @@ export class Service {
434
461
  if (accountId) void this.refreshUsage(accountId).catch(() => undefined);
435
462
  }
436
463
 
464
+ /**
465
+ * Paseo 0.13 (getpaseo/paseo#7477) stopped copying the conversation into turn-ended hooks: `timeline`
466
+ * is always `[]`. Claude reports its limits as an ordinary reply, so when the hook arrives empty the
467
+ * tail of the agent's timeline is paged here and read as the turn. A hook that still sends the
468
+ * conversation (Paseo 0.12 and older) is used as is. A turn that never started (`turnId === null`)
469
+ * has nothing to read, as `notices()` in limits.ts ignores its timeline anyway, and a hook without
470
+ * a turn id gives nothing to tell its rows by. If the page can't be read within
471
+ * `TURN_READ_MS` the event stands: its failure is still read, and a switch waiting for the turn to
472
+ * end isn't held up.
473
+ *
474
+ * The page can reach back into earlier turns, and a later turn may have started by the time it's
475
+ * read, so only this turn's rows count (`turnRows()` in limits.ts): a turn Claude starts by itself
476
+ * has no message to stop at, and must not find the last turn's limit again. Paseo's
477
+ * `[System Error]` row carries no turn id, but it repeats the failure the hook still sends.
478
+ */
479
+ private async turnWithTimeline(paseo: PaseoApi, event: TurnEnded): Promise<TurnEnded> {
480
+ const { turnId } = event;
481
+ if (!turnId || event.timeline.length > 0) return event;
482
+ try {
483
+ const page = await deadline(
484
+ paseo.agents.ref(event.agent.id).timeline.refetch({ direction: "tail", limit: 40 }),
485
+ TURN_READ_MS,
486
+ "Paseo didn't send the agent's timeline in time",
487
+ );
488
+ return { ...event, timeline: turnRows(page.entries, turnId) };
489
+ } catch (error) {
490
+ log(`could not read the last turn of ${event.agent.id}`, error);
491
+ return event;
492
+ }
493
+ }
494
+
437
495
  async onAgentArchived(agentId: string): Promise<void> {
438
496
  this.deferred.delete(agentId);
439
497
  this.switchGuard.forget(agentId);
440
498
  this.guardNoticeAt.delete(agentId);
499
+ this.guardNoticeAt.delete(`${agentId}:elsewhere`);
441
500
  if (!(await this.store.read()).sessions[agentId]) return;
442
501
  await this.store.update((draft) => {
443
502
  delete draft.sessions[agentId];
@@ -476,10 +535,21 @@ export class Service {
476
535
  paseo: PaseoApi,
477
536
  agentId: string,
478
537
  family: Family,
479
- timeline: readonly AgentTimelineItem[],
538
+ timeline: readonly AgentTimelineItem[] | undefined,
480
539
  problem: Problem,
481
540
  ): Promise<void> {
482
- if (this.switching.has(agentId)) return;
541
+ if (this.switching.has(agentId)) {
542
+ // A manual Codex handoff can race the old thread's limit event. Its account is immutable:
543
+ // remember the limit even though the ongoing handoff owns continuation dispatch.
544
+ if (!this.adapters[family].portable && problem.kind === "limit") {
545
+ const accountId = this.runningOn(await this.store.read(), agentId, family);
546
+ if (accountId && !this.recentlyRedeemed(accountId)) {
547
+ const hit = problem.hit;
548
+ await this.markLimited(accountId, hit.resetsAt ?? new Date(Date.now() + (hit.kind === "budget" ? BUDGET_LIMIT_MS : WINDOW_LIMIT_MS)).toISOString(), hit.kind, "turn");
549
+ }
550
+ }
551
+ return;
552
+ }
483
553
  this.switching.add(agentId);
484
554
  let exhausted: string | null = null;
485
555
  try {
@@ -503,14 +573,26 @@ export class Service {
503
573
  agentId: string,
504
574
  family: Family,
505
575
  account: StoredAccount,
506
- timeline: readonly AgentTimelineItem[],
576
+ timeline: readonly AgentTimelineItem[] | undefined,
507
577
  problem: Problem,
508
578
  ): Promise<void> {
509
579
  const adapter = this.adapters[family];
510
580
  const now = Date.now();
581
+ // A parked Codex tab stays stopped: its task carries on in another tab. A failed lookup must not
582
+ // stop the limit from being recorded below.
583
+ const elsewhere = adapter.portable
584
+ ? null
585
+ : await this.continuations.continuesElsewhere(paseo, agentId).catch((error: unknown) => {
586
+ log(`could not find where ${agentId}'s task continues`, error);
587
+ return null;
588
+ });
511
589
  if (problem.kind === "limit" && problem.hit.kind === "window" && this.recentlyRedeemed(account.id)) {
512
590
  // This turn hit the limit just before a reset refilled it (another agent's failover or the
513
591
  // user spent one moments ago). The account has room again: carry on instead of switching.
592
+ if (elsewhere) {
593
+ await this.noteElsewhere(paseo, agentId, account, "limit", null, elsewhere, "resume");
594
+ return;
595
+ }
514
596
  console.log(`[ZeroSub] ${account.label} was just reset; ${agentId} carries on where it is`);
515
597
  if (this.prefs.autoContinue && this.switchGuard.allows(agentId, now)) {
516
598
  this.switchGuard.note(agentId, now);
@@ -525,7 +607,7 @@ export class Service {
525
607
  if (problem.kind === "limit") {
526
608
  const { hit } = problem;
527
609
  resetsAt = hit.resetsAt ?? new Date(now + (hit.kind === "budget" ? BUDGET_LIMIT_MS : WINDOW_LIMIT_MS)).toISOString();
528
- await this.markLimited(account.id, resetsAt, hit.kind);
610
+ await this.markLimited(account.id, resetsAt, hit.kind, "turn");
529
611
  if (hit.kind === "window") {
530
612
  // The notice is the freshest word on usage: show that window full until a new reading lands.
531
613
  const shown = this.usage.get(account.id);
@@ -535,7 +617,7 @@ export class Service {
535
617
  const exact = this.resetFromUsage(account.id);
536
618
  if (exact && Date.parse(exact) > now) {
537
619
  resetsAt = exact;
538
- await this.markLimited(account.id, exact, "window");
620
+ await this.markLimited(account.id, exact, "window", "turn");
539
621
  }
540
622
  }
541
623
  console.log(`[ZeroSub] ${account.label} hit a ${hit.kind} limit (agent ${agentId}): ${hit.message}`);
@@ -544,6 +626,10 @@ export class Service {
544
626
  }
545
627
 
546
628
  if (!this.prefs.autoSwitch) return;
629
+ if (elsewhere) {
630
+ await this.noteElsewhere(paseo, agentId, account, problem.kind, resetsAt, elsewhere, "switch");
631
+ return;
632
+ }
547
633
  const latest = await this.store.read();
548
634
  if (this.runningOn(latest, agentId, family) !== account.id) return; // Already moved.
549
635
  const base = {
@@ -560,8 +646,7 @@ export class Service {
560
646
  if (!this.switchGuard.allows(agentId, now)) {
561
647
  console.warn(`[ZeroSub] not switching ${agentId} again: it changed accounts ${this.switchGuard.limit} times in 10 minutes`);
562
648
  // Say so once, so the user knows to pick an account rather than wait.
563
- if (now - (this.guardNoticeAt.get(agentId) ?? 0) > this.switchGuard.windowMs) {
564
- this.guardNoticeAt.set(agentId, now);
649
+ if (this.noticeDue(agentId, now)) {
565
650
  await this.appendRow(paseo, agentId, {
566
651
  ...base,
567
652
  to: account.label,
@@ -695,18 +780,54 @@ export class Service {
695
780
  to: next.label,
696
781
  reason,
697
782
  outcome: "stayed",
698
- detail: `Couldn't start a new agent on ${next.label}: ${describe(error)}`,
783
+ detail: `Couldn't continue on ${next.label}: ${describe(error)}`,
699
784
  });
700
785
  }
701
786
  }
702
787
 
703
- private async markLimited(accountId: string, until: string, kind: LimitKind): Promise<void> {
788
+ /** True once per guard window for each agent and notice, so repeated skips don't flood its timeline. */
789
+ private noticeDue(key: string, now: number): boolean {
790
+ if (now - (this.guardNoticeAt.get(key) ?? 0) <= this.switchGuard.windowMs) return false;
791
+ this.guardNoticeAt.set(key, now);
792
+ return true;
793
+ }
794
+
795
+ /** Says why ZeroSub left a parked Codex tab alone, instead of silently doing nothing. */
796
+ private async noteElsewhere(
797
+ paseo: PaseoApi,
798
+ agentId: string,
799
+ account: StoredAccount,
800
+ reason: "limit" | "signed_out",
801
+ resetsAt: string | null,
802
+ elsewhere: Continuation,
803
+ skipped: "switch" | "resume",
804
+ ): Promise<void> {
805
+ console.log(`[ZeroSub] not ${skipped === "switch" ? "switching" : "resuming"} ${agentId} automatically: its task continues in ${elsewhere.agentId}`);
806
+ const now = Date.now();
807
+ if (!this.noticeDue(`${agentId}:elsewhere`, now)) return;
808
+ await this.appendRow(paseo, agentId, {
809
+ family: account.family,
810
+ from: account.label,
811
+ to: account.label,
812
+ reason,
813
+ resetsAt,
814
+ continued: false,
815
+ continuedIn: null,
816
+ toFamily: null,
817
+ outcome: "stayed",
818
+ detail: `This task continues in “${elsewhere.title}”, so ZeroSub didn't ${skipped} this tab automatically. Carry on there, or pick an account from the account button to continue from here.`,
819
+ at: new Date(now).toISOString(),
820
+ });
821
+ }
822
+
823
+ private async markLimited(accountId: string, until: string, kind: LimitKind, source: "turn" | "reading"): Promise<void> {
704
824
  await this.store.update((draft) => {
705
825
  const account = findAccount(draft, accountId);
706
826
  if (!account) return;
707
827
  account.limitedUntil = until;
708
828
  account.limitKind = kind;
709
829
  account.limitedAt = new Date().toISOString();
830
+ account.limitSource = source;
710
831
  });
711
832
  }
712
833
 
@@ -784,6 +905,11 @@ export class Service {
784
905
  if (this.runningOn(await this.store.read(), agentId, account.family) !== account.id) return false;
785
906
  // Only resume an agent that this limit actually stopped.
786
907
  if (!(await this.lastTurnHitLimit(paseo, agentId, account.family))) return false;
908
+ const elsewhere = this.adapters[account.family].portable ? null : await this.continuations.continuesElsewhere(paseo, agentId);
909
+ if (elsewhere) {
910
+ await this.noteElsewhere(paseo, agentId, account, "limit", null, elsewhere, "resume");
911
+ return false;
912
+ }
787
913
  const at = new Date().toISOString();
788
914
  await this.appendRow(paseo, agentId, {
789
915
  family: account.family,
@@ -959,6 +1085,21 @@ export class Service {
959
1085
 
960
1086
  /** "Continue on …" from an agent's account button: the same fork, asked for by the user. */
961
1087
  async forkAgent(paseo: PaseoApi, agentId: string): Promise<Continuation> {
1088
+ return this.withSwitch(agentId, () => this.forkAgentNow(paseo, agentId));
1089
+ }
1090
+
1091
+ /** Manual continuations share the automatic failover guard, including cross-provider forks. */
1092
+ private async withSwitch<T>(agentId: string, action: () => Promise<T>): Promise<T> {
1093
+ if (this.switching.has(agentId)) throw new Error("This agent is already switching accounts. Wait for its handoff to finish.");
1094
+ this.switching.add(agentId);
1095
+ try {
1096
+ return await action();
1097
+ } finally {
1098
+ this.switching.delete(agentId);
1099
+ }
1100
+ }
1101
+
1102
+ private async forkAgentNow(paseo: PaseoApi, agentId: string): Promise<Continuation> {
962
1103
  this.attach(paseo);
963
1104
  const info = await agentInfo(paseo, agentId);
964
1105
  if (!info || info.archived) throw new Error("That agent is no longer available.");
@@ -994,6 +1135,7 @@ export class Service {
994
1135
  timeline: readonly AgentTimelineItem[] | undefined,
995
1136
  source: "auto" | "user",
996
1137
  ): Promise<Continuation> {
1138
+ if (target.family === "codex") return this.continuations.continue(paseo, agentId, target, why, source);
997
1139
  return continueInNewAgent({
998
1140
  paseo,
999
1141
  sourceAgentId: agentId,
@@ -1146,7 +1288,10 @@ export class Service {
1146
1288
 
1147
1289
  // ------------------------------------------------------------------ usage
1148
1290
 
1149
- /** `renewLogin` lets the CLI refresh an expired sign-in first (explicit refreshes only: it's slow). */
1291
+ /**
1292
+ * `renewLogin` lets the CLI refresh an expired sign-in first (explicit refreshes: it's slow). Other
1293
+ * reads may renew it too, at most every RENEW_LOGIN_MS (see `renewsInBackground`).
1294
+ */
1150
1295
  refreshUsage(accountId: string, force = false, renewLogin = false): Promise<void> {
1151
1296
  const pending = this.usageInFlight.get(accountId);
1152
1297
  if (pending) return pending;
@@ -1160,26 +1305,37 @@ export class Service {
1160
1305
  const spacing = this.adapters[account.family].usageSpacingMs;
1161
1306
  if (since < (force ? spacing : Math.max(spacing, 60_000))) return;
1162
1307
  this.usageAttemptAt.set(accountId, Date.now());
1163
- const { retryAt, ...usage } = await this.adapters[account.family]
1164
- .usage(account.home, { renewLogin })
1308
+ const renew = renewLogin || this.renewsInBackground(account, Date.now());
1309
+ if (renew) this.renewAttemptAt.set(accountId, Date.now());
1310
+ const { retryAt, ...read } = await this.adapters[account.family]
1311
+ .usage(account.home, { renewLogin: renew })
1165
1312
  .catch(
1166
1313
  (error: unknown): UsageRead => ({ fetchedAt: new Date().toISOString(), windows: [], error: describe(error), cached: false, resets: null }),
1167
1314
  );
1168
1315
  if (retryAt) this.usageRetryAt.set(accountId, retryAt);
1169
1316
  else this.usageRetryAt.delete(accountId);
1317
+ const usage: Usage = { ...read, credits: read.credits ?? null };
1170
1318
  this.setUsage(accountId, mergeUsage(this.usage.get(accountId), usage));
1171
1319
  // Only a live reading may change an account's limit state.
1172
- if (usage.windows.length === 0 || usage.error || usage.cached) return;
1320
+ if (usage.windows.length === 0 || usage.error || usage.cached) {
1321
+ this.usageLive.delete(accountId);
1322
+ return;
1323
+ }
1324
+ this.usageLive.add(accountId);
1173
1325
  const now = Date.now();
1174
- const full = usage.windows.find((window) => window.usedPercent >= 100 && window.resetsAt);
1326
+ // With "Use ChatGPT credits when a limit is reached" on, credits keep an account going past a
1327
+ // full window, so a full window alone isn't a limit then.
1328
+ const creditsCover = this.prefs.useCredits && usage.credits != null;
1329
+ const full = creditsCover ? undefined : usage.windows.find((window) => window.usedPercent >= 100 && window.resetsAt);
1175
1330
  if (full && !isLimited(account, now)) {
1176
- await this.markLimited(accountId, full.resetsAt ?? new Date(now + WINDOW_LIMIT_MS).toISOString(), "window");
1331
+ await this.markLimited(accountId, full.resetsAt ?? new Date(now + WINDOW_LIMIT_MS).toISOString(), "window", "reading");
1177
1332
  return;
1178
1333
  }
1179
- // A window limit clears once usage shows room again. Budget limits never appear in usage
1334
+ // A window limit clears once usage shows room again, or once credits cover it if a reading set
1335
+ // it: a limit a turn ran into stands, credits or not. Budget limits never appear in usage
1180
1336
  // windows, and a fresh limit is trusted for a while (it may be on a window we can't see).
1181
1337
  const settled = account.limitedAt ? now - Date.parse(account.limitedAt) > LIMIT_TRUST_MS : true;
1182
- const roomy = Math.max(...usage.windows.map((window) => window.usedPercent)) < 90;
1338
+ const roomy = (creditsCover && account.limitSource === "reading") || Math.max(...usage.windows.map((window) => window.usedPercent)) < 90;
1183
1339
  if (!full && account.limitedUntil && account.limitKind === "window" && settled && roomy) {
1184
1340
  await this.store.update((draft) => {
1185
1341
  const target = findAccount(draft, accountId);
@@ -1193,6 +1349,18 @@ export class Service {
1193
1349
  return task;
1194
1350
  }
1195
1351
 
1352
+ /**
1353
+ * A read nobody asked to renew the sign-in for still renews it when the reading is past a reset
1354
+ * (its old numbers would stay up until the account is next used), or when a window limit has no
1355
+ * live reading (a reset used on another machine, or an early one, wouldn't lift it). At most
1356
+ * every RENEW_LOGIN_MS, and not for a disabled account.
1357
+ */
1358
+ private renewsInBackground(account: StoredAccount, now: number): boolean {
1359
+ if (account.disabled || now - (this.renewAttemptAt.get(account.id) ?? 0) < RENEW_LOGIN_MS) return false;
1360
+ const windowLimited = account.limitKind === "window" && isLimited(account, now);
1361
+ return pastReset(this.usage.get(account.id), now) || (windowLimited && !this.usageLive.has(account.id));
1362
+ }
1363
+
1196
1364
  /** Records a reading and saves the readings shortly after, so a restart shows them straight away. */
1197
1365
  private setUsage(accountId: string, usage: Usage | null): void {
1198
1366
  if (usage) this.usage.set(accountId, usage);
@@ -1234,6 +1402,11 @@ export class Service {
1234
1402
  family,
1235
1403
  accountId,
1236
1404
  pinned: Boolean(binding && binding.source !== "thread"),
1405
+ // Only while the agent is still on the account that was picked for it.
1406
+ selectionReason:
1407
+ binding?.source === "balance" && binding.selectionReason === "weekly_reset" && binding.accountId === accountId
1408
+ ? "weekly_reset"
1409
+ : undefined,
1237
1410
  pendingAccountId: current && current !== accountId ? current : null,
1238
1411
  movable: this.adapters[family].portable || !agent.hasHistory,
1239
1412
  });
@@ -1469,14 +1642,14 @@ export class Service {
1469
1642
  const binding = state.bindings[agentId];
1470
1643
  const current = binding?.source === "thread" ? binding.accountId : this.runningOn(state, agentId, family);
1471
1644
  if (current === target.id) return emptySummary();
1472
- const continuation = await this.continueElsewhere(
1645
+ const continuation = await this.withSwitch(agentId, () => this.continueElsewhere(
1473
1646
  paseo,
1474
1647
  agentId,
1475
1648
  target,
1476
1649
  `you moved the work to your ChatGPT account "${target.label}"`,
1477
1650
  undefined,
1478
1651
  "user",
1479
- );
1652
+ ));
1480
1653
  await this.appendRow(paseo, agentId, {
1481
1654
  family,
1482
1655
  from: findAccount(state, current)?.label ?? null,
@@ -1651,20 +1824,23 @@ export class Service {
1651
1824
 
1652
1825
  const state = await this.store.read();
1653
1826
  const existing = findAccount(state, session.accountId);
1654
- if (existing?.kind === "managed" && existing.identity && identity.identity && existing.identity !== identity.identity) {
1827
+ if (existing?.kind === "managed" && existing.identity && identity.identity && !sameAccountIdentity(session.family, existing, identity)) {
1655
1828
  // Signing an account back in must not quietly turn it into a different login.
1656
1829
  if (session.home) await adapter.logout(session.home).catch(() => undefined);
1657
1830
  const expected = existing.email ?? existing.label;
1831
+ // Only a Codex key can come without the email, and then it doesn't say which member signed in.
1658
1832
  return this.failLogin(
1659
1833
  session,
1660
- `You signed in as ${identity.email ?? "a different account"}, but this is ${expected}. Sign in as ${expected}, or use Add account for the other one.`,
1834
+ identity.email
1835
+ ? `You signed in as ${identity.email}, but this is ${expected}. Sign in as ${expected}, or use Add account for the other one.`
1836
+ : `Couldn't tell which workspace member signed in, because Codex didn't return an email. Sign in again as ${expected}.`,
1661
1837
  );
1662
1838
  }
1663
1839
  // The CLI's own login is whatever the user signs it into; only added accounts must be distinct.
1664
1840
  const duplicate =
1665
1841
  identity.identity && existing?.kind !== "main"
1666
1842
  ? accountsOf(state, session.family).find(
1667
- (account) => account.id !== session.accountId && account.identity === identity.identity,
1843
+ (account) => account.id !== session.accountId && sameAccountIdentity(session.family, account, identity, true),
1668
1844
  )
1669
1845
  : undefined;
1670
1846
  if (duplicate) {
@@ -1802,6 +1978,15 @@ async function withTimeout(task: Promise<unknown>, ms: number): Promise<void> {
1802
1978
  await Promise.race([task.catch(() => undefined), delay(ms)]);
1803
1979
  }
1804
1980
 
1981
+ /** `task`, or a rejection with `message` once `ms` pass without it settling. */
1982
+ function deadline<T>(task: Promise<T>, ms: number, message: string): Promise<T> {
1983
+ let timer: ReturnType<typeof setTimeout> | undefined;
1984
+ const expired = new Promise<never>((_, reject) => {
1985
+ timer = setTimeout(() => reject(new Error(message)), ms);
1986
+ });
1987
+ return Promise.race([task, expired]).finally(() => clearTimeout(timer));
1988
+ }
1989
+
1805
1990
  function log(message: string, error: unknown): void {
1806
1991
  console.error(`[ZeroSub] ${message}`, describe(error));
1807
1992
  }
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
 
@@ -49,6 +55,32 @@ export const LiveSessionSchema = z.object({
49
55
  });
50
56
  export type LiveSession = z.infer<typeof LiveSessionSchema>;
51
57
 
58
+ const TimelineMarkSchema = z.object({ epoch: z.string(), seq: z.number().int().nonnegative() });
59
+ const ContinuationMemberSchema = z.object({
60
+ accountId: z.string(),
61
+ identity: z.string().nullable(),
62
+ email: z.string().nullable(),
63
+ /** Timeline ranges already known by this tab; no conversation text is stored here. */
64
+ seen: z.record(z.string(), TimelineMarkSchema).default({}),
65
+ /** Reserved/created without a handoff; not a source of task history yet. */
66
+ unstarted: z.boolean().optional(),
67
+ });
68
+ export const ContinuationChainSchema = z.object({
69
+ activeAgentId: z.string(),
70
+ members: z.record(z.string(), ContinuationMemberSchema),
71
+ /** A full fallback that replaces history from deleted/moved tabs. */
72
+ baselineMessageId: z.string().optional(),
73
+ /** Written before dispatch. An uncertain dispatch must never start a second turn. */
74
+ pending: z.object({
75
+ agentId: z.string(),
76
+ messageId: z.string(),
77
+ seen: z.record(z.string(), TimelineMarkSchema),
78
+ stage: z.enum(["creating", "sending"]).default("sending"),
79
+ replaceHistory: z.array(z.string()).optional(),
80
+ }).optional(),
81
+ });
82
+ export type ContinuationChain = z.infer<typeof ContinuationChainSchema>;
83
+
52
84
  export const StoredStateSchema = z.object({
53
85
  version: z.literal(1).default(1),
54
86
  accounts: z.array(StoredAccountSchema).default([]),
@@ -59,6 +91,7 @@ export const StoredStateSchema = z.object({
59
91
  bindings: z.record(z.string(), BindingSchema).default({}),
60
92
  /** Which account each agent's live provider session was opened with. */
61
93
  sessions: z.record(z.string(), LiveSessionSchema).default({}),
94
+ continuations: z.record(z.string(), ContinuationChainSchema).default({}),
62
95
  });
63
96
  export type StoredState = z.infer<typeof StoredStateSchema>;
64
97
 
@@ -102,6 +135,7 @@ export function salvageState(raw: unknown): { state: StoredState; dropped: boole
102
135
  defaults,
103
136
  bindings: records(BindingSchema, source.bindings),
104
137
  sessions: records(LiveSessionSchema, source.sessions),
138
+ continuations: records(ContinuationChainSchema, source.continuations),
105
139
  },
106
140
  dropped: true,
107
141
  };
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