@kapybara/zerosub 1.5.1 → 1.18.2

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.
Files changed (56) hide show
  1. package/README.md +220 -26
  2. package/client/accounts-surface.tsx +344 -110
  3. package/client/add-account.tsx +335 -23
  4. package/client/api-account.tsx +250 -0
  5. package/client/azure-account.tsx +311 -0
  6. package/client/commands.ts +44 -8
  7. package/client/composer-item.tsx +203 -0
  8. package/client/fork-confirm.tsx +71 -0
  9. package/client/fork-settings.tsx +148 -0
  10. package/client/pace.tsx +196 -0
  11. package/client/pi-accounts.tsx +571 -0
  12. package/client/pills.ts +63 -25
  13. package/client/reset-confirm.tsx +12 -3
  14. package/client/settings-screen.tsx +48 -9
  15. package/client/store.ts +148 -19
  16. package/client/switch-row.tsx +28 -8
  17. package/client/ui.tsx +11 -0
  18. package/index.client.tsx +4 -1
  19. package/index.server.ts +53 -10
  20. package/package.json +5 -2
  21. package/server/account-identity.ts +11 -0
  22. package/server/adapter.ts +115 -8
  23. package/server/api-usage.ts +144 -0
  24. package/server/azure.ts +346 -0
  25. package/server/binaries.ts +41 -3
  26. package/server/claude.ts +276 -21
  27. package/server/codex-same-conversation.ts +71 -0
  28. package/server/codex.ts +35 -7
  29. package/server/continuations.ts +67 -17
  30. package/server/cursor.ts +222 -0
  31. package/server/families.ts +105 -8
  32. package/server/grok.ts +225 -0
  33. package/server/handoff.ts +211 -29
  34. package/server/homes.ts +1263 -35
  35. package/server/json-file.ts +39 -8
  36. package/server/launchers.ts +319 -0
  37. package/server/limits.ts +80 -3
  38. package/server/main-proxy.ts +238 -0
  39. package/server/modes.ts +20 -4
  40. package/server/paths.ts +81 -1
  41. package/server/pi.ts +528 -0
  42. package/server/placement.ts +133 -0
  43. package/server/process.ts +18 -1
  44. package/server/processes.ts +66 -0
  45. package/server/provider-env.ts +28 -0
  46. package/server/proxy.ts +282 -0
  47. package/server/reopen.ts +50 -8
  48. package/server/routing.ts +337 -30
  49. package/server/service.ts +4320 -805
  50. package/server/state.ts +303 -24
  51. package/server/usage.ts +2 -0
  52. package/shared/format.ts +170 -2
  53. package/shared/model.ts +339 -2
  54. package/shared/preferences.ts +22 -1
  55. package/shared/rpc.ts +130 -8
  56. package/shared/timeline.ts +11 -0
package/server/routing.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { peakUsage } from "../shared/format";
2
- import type { Family, Usage } from "../shared/model";
1
+ import { accountPeak } from "../shared/format";
2
+ import { isAzureAccount, PACE_GATE_PERCENT, type Family, type PaceView, type Usage, type UsageWindow } from "../shared/model";
3
3
  import { FIVE_HOUR_MINUTES, WEEK_MINUTES } from "./codex";
4
4
  import {
5
5
  accountsOf,
@@ -7,6 +7,7 @@ import {
7
7
  findAccount,
8
8
  mainAccount,
9
9
  type Binding,
10
+ type NextAgentPick,
10
11
  type StoredAccount,
11
12
  type StoredState,
12
13
  } from "./state";
@@ -17,6 +18,28 @@ const FRESH_READING_MS = 30 * 60_000;
17
18
  const NEAR_RESET_MS = 24 * 60 * 60_000;
18
19
  /** The most a near-reset account may have used of any window, so it still has room to spare. */
19
20
  const NEAR_RESET_MAX_USED_PERCENT = 80;
21
+ /**
22
+ * An account that has used this much of its 5-hour window is about to run out of it: when spreading
23
+ * new agents, any account under this ranks ahead of every account past it, unless a window that caps
24
+ * it is full (see `mostAvailable`).
25
+ */
26
+ const FIVE_HOUR_GATE_PERCENT = PACE_GATE_PERCENT;
27
+
28
+ const FIVE_HOUR_MS = FIVE_HOUR_MINUTES * 60_000;
29
+ const WEEK_MS = WEEK_MINUTES * 60_000;
30
+ /** Tunable: how far ahead the 5-hour use is projected. Rests on a low-confidence window size. */
31
+ const PACE_HORIZON_MS = 3_600_000;
32
+ /** Tunable: a young window's burn rate is measured over at least this long, so a first burst doesn't extrapolate wildly. */
33
+ const MIN_FIVE_HOUR_ELAPSED_MS = 1_800_000;
34
+ /** Tunable: the least share of the week that counts as elapsed, so a fresh week doesn't inflate the pace. */
35
+ const MIN_WEEK_SHARE = 1 / 7;
36
+ const UNKNOWN_SCORE = 50;
37
+ /** Tunable: 5-hour percent charged for each agent placed on an account since its reading. */
38
+ export const PENDING_FIVE_HOUR_PERCENT = 10;
39
+ /** Tunable: weekly percent charged for each agent placed on an account since its reading. */
40
+ export const PENDING_WEEKLY_PERCENT = 2;
41
+ /** How long a placement counts as pending, until a usage reading can show it. */
42
+ export const PENDING_MS = 600_000;
20
43
 
21
44
  export function isLimited(account: StoredAccount, now: number): boolean {
22
45
  if (!account.limitedUntil) return false;
@@ -24,34 +47,208 @@ export function isLimited(account: StoredAccount, now: number): boolean {
24
47
  return Number.isFinite(until) && until > now;
25
48
  }
26
49
 
27
- export function isUsable(account: StoredAccount, now: number): boolean {
28
- return account.signedIn && !account.disabled && !isLimited(account, now);
50
+ function tokens(text: string): string[] {
51
+ return text.toLowerCase().split(/[^a-z0-9]+/).filter((token) => token.length > 0);
52
+ }
53
+
54
+ /**
55
+ * Whether a model limit's scope ("fable") covers a model id ("claude-fable-5-2"): every word of the
56
+ * scope is a word of the model. An unknown or default model is covered by nothing, so it's never
57
+ * kept off an account for a limit of one model.
58
+ */
59
+ export function scopeCoversModel(scope: string, model: string | null | undefined): boolean {
60
+ if (!model || model.toLowerCase() === "default") return false;
61
+ const wanted = tokens(scope);
62
+ if (wanted.length === 0) return false;
63
+ const have = new Set(tokens(model));
64
+ return wanted.every((token) => have.has(token));
65
+ }
66
+
67
+ /** The account is at a limit of its own, or at the limit of a model window that covers `model`. */
68
+ export function isLimitedFor(account: StoredAccount, now: number, model?: string | null): boolean {
69
+ if (isLimited(account, now)) return true;
70
+ return Object.entries(account.modelLimits ?? {}).some(
71
+ ([scope, limit]) => Date.parse(limit.until) > now && scopeCoversModel(scope, model),
72
+ );
73
+ }
74
+
75
+ export function isUsable(account: StoredAccount, now: number, model?: string | null): boolean {
76
+ return account.signedIn && !account.disabled && !isLimitedFor(account, now, model);
77
+ }
78
+
79
+ /**
80
+ * Routing may put agents on this account by itself: it's usable and not billed per use. No Pi
81
+ * account is ever picked that way: an added one is an API key, and Pi's own login may be one too,
82
+ * so moving work onto either would move it onto a bill nobody chose.
83
+ */
84
+ export function canStandIn(account: StoredAccount, now: number, model?: string | null): boolean {
85
+ return account.family !== "pi" && account.auth !== "api" && isUsable(account, now, model);
86
+ }
87
+
88
+ /**
89
+ * A paid API account that stands in for a subscription (an Azure OpenAI account), marked so when it
90
+ * was added. Like any API account it's billed per use, so routing never puts agents on it by itself
91
+ * unless `paidApiFallback` is on, and then only as a last resort: once no subscription account of the
92
+ * family can stand in (see `mostAvailable`). It can always be picked by hand, or made the default.
93
+ */
94
+ export function isLastResort(account: StoredAccount): boolean {
95
+ return isAzureAccount(account);
29
96
  }
30
97
 
31
- /** Lower is better. Unknown usage ranks in the middle so a known-quiet account wins over a mystery. */
32
- export function headroomScore(usage: Usage | null | undefined): number {
33
- const peak = usage ? peakUsage(usage.windows) : null;
98
+ /**
99
+ * Lower is better. Unknown usage ranks in the middle so a known-quiet account wins over a mystery.
100
+ * A full window of one model only, such as "Weekly · Opus", leaves the account its room for the rest.
101
+ * A window whose reset has passed since the reading starts again empty, so an account that just
102
+ * reset ranks by what it has left, not by the full window its last reading showed.
103
+ */
104
+ export function headroomScore(usage: Usage | null | undefined, now = Date.now()): number {
105
+ const windows = usage?.windows.map((window) =>
106
+ window.resetsAt && Date.parse(window.resetsAt) <= now ? { ...window, usedPercent: 0 } : window);
107
+ const peak = windows ? accountPeak(windows) : null;
34
108
  return peak ? peak.usedPercent : 50;
35
109
  }
36
110
 
37
- /** The usable account with the most room, preferring the default, then the CLI login, on ties. */
111
+ /** The 5-hour window: Codex says how long its windows are, Claude's is known by id. */
112
+ export function fiveHourWindow(usage: Usage): UsageWindow | undefined {
113
+ return usage.windows.find((window) => window.minutes === FIVE_HOUR_MINUTES) ??
114
+ usage.windows.find((window) => window.minutes == null && (window.id === "five_hour" || window.id === "primary"));
115
+ }
116
+
117
+ /**
118
+ * Whether the account has used `FIVE_HOUR_GATE_PERCENT` of its 5-hour window, and that window hasn't
119
+ * reset yet. Unknown counts as under the gate.
120
+ */
121
+ export function fiveHourGated(usage: Usage | null | undefined, now: number): boolean {
122
+ const short = usage ? fiveHourWindow(usage) : undefined;
123
+ if (!short || !Number.isFinite(short.usedPercent)) return false;
124
+ if (short.resetsAt && Date.parse(short.resetsAt) <= now) return false;
125
+ return short.usedPercent >= FIVE_HOUR_GATE_PERCENT;
126
+ }
127
+
128
+ /** Agents ZeroSub placed on an account that its latest usage reading may not show yet. */
129
+ export interface Pacing {
130
+ pendingOf(accountId: string): number;
131
+ }
132
+
133
+ export interface PaceScore {
134
+ /** Projected 5-hour use an hour ahead, plus pending agents. */
135
+ fiveHour: number;
136
+ /** Weekly use against the share of the week that has passed, plus pending agents. */
137
+ weekly: number;
138
+ score: number;
139
+ gated: boolean;
140
+ }
141
+
142
+ export function weeklyWindow(usage: Usage): UsageWindow | undefined {
143
+ return usage.windows.find((window) => window.minutes === WEEK_MINUTES) ??
144
+ usage.windows.find((window) => window.minutes == null && (window.id === "seven_day" || window.id === "secondary"));
145
+ }
146
+
147
+ /** Lower is better. Combines the 5-hour projection and the weekly pace; see the README. */
148
+ export function paceScore(usage: Usage | null | undefined, pending: number, now: number): PaceScore {
149
+ const fiveCharge = PENDING_FIVE_HOUR_PERCENT * pending;
150
+ const weekCharge = PENDING_WEEKLY_PERCENT * pending;
151
+ const short = usage ? fiveHourWindow(usage) : undefined;
152
+ const long = usage ? weeklyWindow(usage) : undefined;
153
+ if (!usage || usage.windows.length === 0 || (!short && !long)) {
154
+ const fiveHour = UNKNOWN_SCORE + fiveCharge;
155
+ return { fiveHour, weekly: 0, score: fiveHour, gated: fiveHour >= FIVE_HOUR_GATE_PERCENT };
156
+ }
157
+ const parsed = Date.parse(usage.fetchedAt);
158
+ const fetched = Number.isFinite(parsed) ? Math.min(parsed, now) : now;
159
+ const expired = (window: UsageWindow) => !!window.resetsAt && Date.parse(window.resetsAt) <= now;
160
+
161
+ let fiveHour = fiveCharge;
162
+ if (short && Number.isFinite(short.usedPercent) && !expired(short)) {
163
+ const reset = Date.parse(short.resetsAt ?? "");
164
+ if (!Number.isFinite(reset)) fiveHour = short.usedPercent + fiveCharge;
165
+ else {
166
+ const elapsed = Math.max(MIN_FIVE_HOUR_ELAPSED_MS, fetched - (reset - FIVE_HOUR_MS));
167
+ const ahead = Math.min(now + PACE_HORIZON_MS, reset) - fetched;
168
+ fiveHour = short.usedPercent + (short.usedPercent / elapsed) * ahead + fiveCharge;
169
+ }
170
+ }
171
+ let weekly = 0;
172
+ if (long && Number.isFinite(long.usedPercent) && !expired(long)) {
173
+ const reset = Date.parse(long.resetsAt ?? "");
174
+ if (!Number.isFinite(reset)) weekly = long.usedPercent + weekCharge;
175
+ else {
176
+ const share = 1 - (reset - fetched) / WEEK_MS;
177
+ weekly = (long.usedPercent + weekCharge) / Math.min(1, Math.max(MIN_WEEK_SHARE, share));
178
+ }
179
+ }
180
+ return {
181
+ fiveHour,
182
+ weekly,
183
+ score: Math.max(fiveHour, weekly),
184
+ gated: fiveHourGated(usage, now) || fiveHour >= FIVE_HOUR_GATE_PERCENT,
185
+ };
186
+ }
187
+
188
+ /** `paceScore` broken into the parts an account card draws. */
189
+ export function paceView(usage: Usage | null | undefined, pending: number, now: number): PaceView {
190
+ const pace = paceScore(usage, pending, now);
191
+ const short = usage ? fiveHourWindow(usage) : undefined;
192
+ const long = usage ? weeklyWindow(usage) : undefined;
193
+ const expired = (window: UsageWindow) => !!window.resetsAt && Date.parse(window.resetsAt) <= now;
194
+ const used = (window: UsageWindow | undefined) =>
195
+ window && Number.isFinite(window.usedPercent) ? (expired(window) ? 0 : window.usedPercent) : null;
196
+ const parsed = usage ? Date.parse(usage.fetchedAt) : Number.NaN;
197
+ const fetched = Number.isFinite(parsed) ? Math.min(parsed, now) : now;
198
+ const weekReset = long?.resetsAt ? Date.parse(long.resetsAt) : Number.NaN;
199
+ const weekElapsed =
200
+ long && Number.isFinite(long.usedPercent) && !expired(long) && Number.isFinite(weekReset)
201
+ ? Math.min(100, Math.max(0, (1 - (weekReset - fetched) / WEEK_MS) * 100))
202
+ : null;
203
+ return {
204
+ fiveHourUsed: used(short),
205
+ fiveHourProjected: pace.fiveHour,
206
+ pendingFiveHour: PENDING_FIVE_HOUR_PERCENT * pending,
207
+ weeklyUsed: used(long),
208
+ pendingWeekly: PENDING_WEEKLY_PERCENT * pending,
209
+ weekElapsed,
210
+ pending,
211
+ gated: pace.gated,
212
+ };
213
+ }
214
+
215
+ /**
216
+ * The usable account with the most room: one under the 5-hour gate before one past it (by peak alone,
217
+ * an account at 81% of its 5 hours beats one at 88% of its week, and runs out minutes later), then
218
+ * the lowest peak, preferring the default, then the CLI login, on ties. An account with a full window
219
+ * that caps it ranks last, gate or not, though it's usable: its limit lifted at the 5-hour reset with
220
+ * its week still full, say, or ChatGPT credits keep it going.
221
+ *
222
+ * With `paidFallback` (the `paidApiFallback` preference), a usable paid API account (`isLastResort`)
223
+ * is chosen once no subscription account can stand in; without it, never.
224
+ */
38
225
  export function mostAvailable(
39
226
  state: StoredState,
40
227
  family: Family,
41
228
  usageOf: (accountId: string) => Usage | null | undefined,
42
229
  now: number,
43
230
  exclude: ReadonlySet<string> = new Set(),
231
+ paidFallback = false,
232
+ pacing?: Pacing,
233
+ model?: string | null,
44
234
  ): StoredAccount | undefined {
45
235
  const preferred = defaultAccount(state, family)?.id;
46
- const candidates = accountsOf(state, family).filter(
47
- (account) => !exclude.has(account.id) && isUsable(account, now),
48
- );
49
- const rank = (account: StoredAccount) => [
50
- headroomScore(usageOf(account.id)),
51
- account.id === preferred ? 0 : 1,
52
- account.kind === "main" ? 0 : 1,
53
- Date.parse(account.createdAt) || 0,
54
- ];
236
+ const open = accountsOf(state, family).filter((account) => !exclude.has(account.id));
237
+ const subscriptions = open.filter((account) => canStandIn(account, now, model));
238
+ const candidates =
239
+ subscriptions.length > 0 || !paidFallback ? subscriptions : open.filter((account) => isLastResort(account) && isUsable(account, now, model));
240
+ const rank = (account: StoredAccount) => {
241
+ const usage = usageOf(account.id);
242
+ const score = headroomScore(usage, now);
243
+ const pace = pacing ? paceScore(usage, pacing.pendingOf(account.id), now) : undefined;
244
+ return [
245
+ score >= 100 ? 2 : (pace ? pace.gated : fiveHourGated(usage, now)) ? 1 : 0,
246
+ pace ? pace.score : score,
247
+ account.id === preferred ? 0 : 1,
248
+ account.kind === "main" ? 0 : 1,
249
+ Date.parse(account.createdAt) || 0,
250
+ ];
251
+ };
55
252
  candidates.sort((a, b) => {
56
253
  const left = rank(a);
57
254
  const right = rank(b);
@@ -64,9 +261,38 @@ export function mostAvailable(
64
261
  return candidates[0];
65
262
  }
66
263
 
264
+ /**
265
+ * A subscription account at a usage-window limit (5-hour or weekly) whose latest reading shows a
266
+ * banked reset it can spend right now. With `autoRedeem` on, a new agent opens on it rather than on
267
+ * a paid stand-in: its first turn hits the limit and spends the reset, as it would with paid fallback
268
+ * off. Signed-out, disabled and budget-limited accounts never count, nor does any API account.
269
+ * Preferred: the default, then the CLI login, then the most resets left.
270
+ */
271
+ export function withBankedReset(
272
+ state: StoredState,
273
+ family: Family,
274
+ usageOf: (accountId: string) => Usage | null | undefined,
275
+ now: number,
276
+ ): StoredAccount | undefined {
277
+ const preferred = defaultAccount(state, family)?.id;
278
+ const left = (account: StoredAccount) => usageOf(account.id)?.resets?.available ?? 0;
279
+ return accountsOf(state, family)
280
+ .filter((account) => account.family !== "pi" && account.auth !== "api" && !isLastResort(account) &&
281
+ account.signedIn && !account.disabled && account.limitKind === "window" && isLimited(account, now))
282
+ .filter((account) => {
283
+ const resets = usageOf(account.id)?.resets;
284
+ return !!resets && resets.available > 0 && resets.usableNow;
285
+ })
286
+ .sort((a, b) =>
287
+ (a.id === preferred ? 0 : 1) - (b.id === preferred ? 0 : 1) ||
288
+ (a.kind === "main" ? 0 : 1) - (b.kind === "main" ? 0 : 1) ||
289
+ left(b) - left(a))[0];
290
+ }
291
+
67
292
  /** Prefer a weekly reset within a day only when every usable account has fresh, complete usage. */
68
293
  function soonestWeeklyReset(state: StoredState, family: Family, usageOf: RouteInput["usageOf"], now: number): StoredAccount | undefined {
69
- const candidates = accountsOf(state, family).filter((account) => isUsable(account, now));
294
+ // An API account has no plan windows, and is never preferred for a reset coming up.
295
+ const candidates = accountsOf(state, family).filter((account) => isUsable(account, now) && account.auth !== "api");
70
296
  const readings = candidates.map((account) => ({ account, usage: usageOf(account.id) }));
71
297
  const complete = readings.every(({ usage }) => {
72
298
  if (!usage || usage.error || usage.cached) return false;
@@ -99,6 +325,36 @@ export interface RouteInput {
99
325
  */
100
326
  portable: boolean;
101
327
  usageOf(accountId: string): Usage | null | undefined;
328
+ /**
329
+ * The account the agent's session runs on now. When the account it's routed to has to be skipped
330
+ * and this one can stand in, the agent stays on it rather than following whichever account ranks
331
+ * first at the moment, which would move it again each time two accounts swap places.
332
+ */
333
+ current?: string;
334
+ /** A paid API account may stand in once every subscription account is out (`paidApiFallback`). */
335
+ paidFallback?: boolean;
336
+ /**
337
+ * Banked resets are spent when every account is out (`autoRedeem`). With it, a new agent opens on a
338
+ * limited subscription with a usable reset before a paid stand-in (see `withBankedReset`).
339
+ */
340
+ autoRedeem?: boolean;
341
+ /**
342
+ * The account named for this agent when it was created (`ACCOUNT_METADATA_KEY` in its metadata):
343
+ * chosen in its composer before it existed. Only a new agent without an account takes it.
344
+ */
345
+ requested?: string;
346
+ /**
347
+ * Whether this session may take the one-time "next new agent" pick: one the user's own agents
348
+ * open, not Paseo's helpers (see `takesNextPick` in service.ts). Only a new agent takes it.
349
+ */
350
+ allowNextPick?: boolean;
351
+ /** Agents recently placed on an account; only read while `balanceNewAgents` is on. */
352
+ pendingOf?(accountId: string): number;
353
+ /**
354
+ * The model the agent runs, when known. A limit of that model's own window keeps the agent off the
355
+ * account; without it only limits of the whole account count.
356
+ */
357
+ model?: string | null;
102
358
  }
103
359
 
104
360
  export interface RouteDecision {
@@ -107,45 +363,96 @@ export interface RouteDecision {
107
363
  bind: Binding | null;
108
364
  /** Why the preferred account was skipped, if it was. */
109
365
  skipped: { account: StoredAccount; why: "limited" | "signed_out" | "disabled" } | null;
366
+ /**
367
+ * The "next new agent" pick routing looked at, to be cleared: it's spent whether the agent starts
368
+ * on its account or that account couldn't take it.
369
+ */
370
+ nextPick?: NextAgentPick;
110
371
  }
111
372
 
112
373
  /**
113
- * Which account a session opens on: the agent's own binding, else (for balanced new agents) the
114
- * roomiest account, else the default. An exhausted or signed-out choice is swapped for the roomiest
115
- * usable account when automatic switching is on — for new agents always, and for existing ones
116
- * only when their conversation can move between accounts. A disabled choice is always swapped,
117
- * and the agent keeps its own binding so it returns once the account is enabled again.
374
+ * Which account a session opens on: the agent's own binding, else (for a new agent) the account
375
+ * named for it or the one-time pick, else (for balanced new agents) the
376
+ * roomiest account, else the default (the CLI login for an existing Codex thread ZeroSub never
377
+ * routed). An exhausted or signed-out choice is swapped for the roomiest usable account when
378
+ * automatic switching is on — for new agents always, and for existing ones only when their
379
+ * conversation can move between accounts. A disabled choice is always swapped,
380
+ * and the agent keeps its own binding so it returns once the account is enabled again. An agent
381
+ * already running on a usable stand-in keeps it (see `RouteInput.current`).
118
382
  */
119
383
  export function chooseAccount(state: StoredState, input: RouteInput): RouteDecision | null {
120
384
  const accounts = accountsOf(state, input.family);
121
385
  if (accounts.length === 0) return null;
122
386
  const at = new Date(input.now).toISOString();
123
387
  const fresh = input.reason === "create";
388
+ const pacing: Pacing | undefined = input.balanceNewAgents
389
+ ? { pendingOf: (id) => input.pendingOf?.(id) ?? 0 }
390
+ : undefined;
124
391
 
125
392
  const binding = state.bindings[input.agentId];
126
393
  const bound = findAccount(state, binding?.accountId);
127
394
  let account = bound && bound.family === input.family ? bound : undefined;
128
395
  let bind: Binding | null = null;
129
396
 
397
+ // The account named for this very agent outranks the pick, which waits for an agent that names
398
+ // none. One that can't take the agent is passed over, and the agent routes as usual.
399
+ const takes = (candidate: StoredAccount | undefined): candidate is StoredAccount =>
400
+ candidate?.family === input.family && candidate.signedIn && !candidate.disabled && !(input.autoSwitch && isLimitedFor(candidate, input.now, input.model));
401
+ const requested = !account && fresh ? findAccount(state, input.requested) : undefined;
402
+ if (takes(requested)) {
403
+ account = requested;
404
+ bind = { accountId: requested.id, source: "user", at };
405
+ }
406
+
407
+ // A pick whose account can't take the agent (at its limit, signed out, disabled, removed) is spent
408
+ // all the same, and the agent routes as usual: kept, it would send every new agent to whichever
409
+ // account stands in for its own until it expires.
410
+ const nextPick = !account && fresh && input.allowNextPick ? (state.nextAgent?.[input.family] ?? undefined) : undefined;
411
+ if (nextPick && Date.parse(nextPick.until) > input.now) {
412
+ const picked = findAccount(state, nextPick.accountId);
413
+ if (takes(picked)) {
414
+ account = picked;
415
+ bind = { accountId: picked.id, source: "user", at };
416
+ }
417
+ }
130
418
  if (!account && fresh && input.balanceNewAgents && accounts.length > 1) {
131
419
  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);
420
+ account = nearReset ?? mostAvailable(state, input.family, input.usageOf, input.now, new Set(), input.paidFallback, pacing, input.model);
421
+ // A banked reset is free, so it goes before a paid stand-in, as it does when a turn hits a limit.
422
+ if (account && isLastResort(account) && input.autoRedeem) {
423
+ account = withBankedReset(state, input.family, input.usageOf, input.now) ?? account;
424
+ }
133
425
  if (account) bind = { accountId: account.id, source: "balance", at, selectionReason: nearReset ? "weekly_reset" : "headroom" };
134
426
  }
135
427
  if (!account) {
136
- // An imported Codex thread most likely came from the user's own CLI, so it belongs to that login.
137
- const imported = !input.portable && input.reason === "import" ? mainAccount(state, input.family) : undefined;
138
- account = imported ?? defaultAccount(state, input.family);
428
+ // An existing Codex thread ZeroSub never routed (imported from the user's own CLI, or started
429
+ // while ZeroSub was off) ran on the CLI login, so it belongs to that login: on any other account
430
+ // its encrypted reasoning can't be read. Only a brand-new agent follows the default.
431
+ const unrouted = !input.portable && !fresh && !state.sessions[input.agentId] ? mainAccount(state, input.family) : undefined;
432
+ account = unrouted ?? defaultAccount(state, input.family);
139
433
  // A thread that can't move is pinned to the account it first opened on.
140
434
  if (account && !input.portable) bind = { accountId: account.id, source: "thread", at };
141
435
  }
142
436
  if (!account) return null;
143
437
 
144
438
  let skipped: RouteDecision["skipped"] = null;
145
- const why = !account.signedIn ? "signed_out" : account.disabled ? "disabled" : isLimited(account, input.now) ? "limited" : null;
439
+ const why = !account.signedIn ? "signed_out" : account.disabled ? "disabled" : isLimitedFor(account, input.now, input.model) ? "limited" : null;
146
440
  const mayMove = fresh || input.portable;
147
441
  if (why && mayMove && (input.autoSwitch || why !== "limited")) {
148
- const alternative = mostAvailable(state, input.family, input.usageOf, input.now, new Set([account.id]));
442
+ const staying = findAccount(state, input.current);
443
+ // A paid stand-in is only kept while no subscription account could take over from it.
444
+ const keeps = (stand: StoredAccount) =>
445
+ !isLastResort(stand) || !accountsOf(state, input.family).some((other) => other.id !== account!.id && canStandIn(other, input.now, input.model));
446
+ let alternative =
447
+ staying && staying.family === input.family && staying.id !== account.id && isUsable(staying, input.now, input.model) && keeps(staying)
448
+ ? staying
449
+ : mostAvailable(state, input.family, input.usageOf, input.now, new Set([account.id]), input.paidFallback, pacing, input.model);
450
+ // Before a paid stand-in, a limited subscription with a usable banked reset: the account itself
451
+ // (it stays, and its first turn spends the reset) or another one.
452
+ if (alternative && isLastResort(alternative) && input.autoRedeem) {
453
+ const banked = withBankedReset(state, input.family, input.usageOf, input.now);
454
+ if (banked) alternative = banked.id === account.id ? undefined : banked;
455
+ }
149
456
  if (alternative) {
150
457
  skipped = { account, why };
151
458
  account = alternative;
@@ -159,7 +466,7 @@ export function chooseAccount(state: StoredState, input: RouteInput): RouteDecis
159
466
  : { accountId: alternative.id, source: "auto", at };
160
467
  }
161
468
  }
162
- return { account, bind, skipped };
469
+ return { account, bind, skipped, nextPick };
163
470
  }
164
471
 
165
472
  /** The account an agent is routed to right now, without side effects (for display). */