@kapybara/zerosub 1.0.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.
@@ -0,0 +1,213 @@
1
+ import type { AgentTimelineItem } from "@getpaseo/protocol/agent-types";
2
+ import type { PluginTurnOutcome } from "@getpaseo/plugin/server";
3
+ import type { LimitHit, LimitKind } from "./adapter";
4
+
5
+ type TurnEvent = { outcome: PluginTurnOutcome; timeline: readonly AgentTimelineItem[] };
6
+
7
+ /**
8
+ * Claude Code's exact wording for hard limits (2.1.x templates: `You've hit your ${limit}${suffix}`),
9
+ * plus the legacy `Claude AI usage limit reached|<epoch>`. Each must be followed by the CLI's own
10
+ * separator (" · …", ".") or end the line, so prose like "You've hit your GitHub API rate limit"
11
+ * never matches. Warnings ("You've used 80%…") and capacity 429s ("…not your usage limit") are
12
+ * deliberately absent: switching accounts doesn't help with those.
13
+ */
14
+ const END = String.raw`(?=\s*(?:·|\.|$))`;
15
+ const APOSTROPHE = "['’]";
16
+ const CLAUDE_LIMITS: ReadonlyArray<{ pattern: RegExp; kind: LimitKind }> = [
17
+ { pattern: new RegExp(`^You${APOSTROPHE}ve hit your (?:session |weekly |Opus |Sonnet |Fable )?limit${END}`, "i"), kind: "window" },
18
+ { pattern: new RegExp(`^You${APOSTROPHE}ve reached your (?:Fable|Opus|Sonnet|Haiku)(?: [\\w.]{1,10})? limit${END}`), kind: "window" },
19
+ { pattern: /Claude AI usage limit reached\|\d{9,}/, kind: "window" },
20
+ {
21
+ pattern: new RegExp(
22
+ `^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}`,
23
+ "i",
24
+ ),
25
+ kind: "budget",
26
+ },
27
+ { pattern: new RegExp(`^You${APOSTROPHE}re out of (?:usage credits|extra usage)${END}`, "i"), kind: "budget" },
28
+ { pattern: /^Your org is out of usage\s*·/i, kind: "budget" },
29
+ { pattern: new RegExp(`^Your seat type doesn${APOSTROPHE}t include (?:usage credits|extra usage|usage)\\b`, "i"), kind: "budget" },
30
+ { pattern: /^Your usage allocation has been disabled by your admin/i, kind: "budget" },
31
+ { pattern: new RegExp(`^Your group${APOSTROPHE}s usage limit is set to \\$0`, "i"), kind: "budget" },
32
+ { pattern: /^Fable(?: [^·\n]{1,40})? requires usage credits\./, kind: "budget" },
33
+ ];
34
+
35
+ /** Codex's messages for plan limits (typographic apostrophe) and workspace budgets, plus the raw error type. */
36
+ const CODEX_LIMITS: ReadonlyArray<{ pattern: RegExp; kind: LimitKind }> = [
37
+ { pattern: new RegExp(`^You${APOSTROPHE}ve hit your usage limit\\b`, "i"), kind: "window" },
38
+ { pattern: /^The usage limit has been reached\b/i, kind: "window" },
39
+ { pattern: /"type"\s*:\s*"usage_limit_reached"/, kind: "window" },
40
+ { pattern: /^Your workspace is out of credits\b/i, kind: "budget" },
41
+ { pattern: /^You hit your spend cap\b/i, kind: "budget" },
42
+ ];
43
+
44
+ const CLAUDE_SIGNED_OUT =
45
+ /^(?:Not logged in\s*·|Invalid API key\s*·|OAuth token (?:has expired|has been revoked)|Failed to authenticate\. API Error: 401)/i;
46
+ const CODEX_SIGNED_OUT =
47
+ /refresh token was already used|please log out and sign in again|access token could not be refreshed|refresh_token_reused|refresh_token_expired/i;
48
+
49
+ const SYSTEM_ERROR = /^\[System Error\]\s*/;
50
+ const MAX_NOTICE = 400;
51
+
52
+ function clean(text: string): string {
53
+ return text.replace(SYSTEM_ERROR, "").replace(/^API Error:\s*/i, "").trim();
54
+ }
55
+
56
+ /**
57
+ * Where a CLI-generated notice can appear in a finished turn: the failure message, error items,
58
+ * Paseo's `[System Error]` rows, and — for Claude, which reports limits as a synthetic reply — the
59
+ * final assistant messages. Ordinary replies earlier in the turn are never inspected.
60
+ */
61
+ function notices(event: TurnEvent, includeFinalReplies: boolean): string[] {
62
+ const found: string[] = [];
63
+ if (event.outcome.kind === "failed") found.push(event.outcome.error.message);
64
+ let replies = 0;
65
+ for (let index = event.timeline.length - 1; index >= 0; index -= 1) {
66
+ const item = event.timeline[index];
67
+ if (!item) continue;
68
+ if (item.type === "user_message") break;
69
+ if (item.type === "error") found.push(item.message);
70
+ else if (item.type === "notification" && item.level !== "info") found.push(item.message);
71
+ else if (item.type === "assistant_message") {
72
+ if (SYSTEM_ERROR.test(item.text)) found.push(item.text);
73
+ else if (includeFinalReplies && replies < 2) found.push(item.text);
74
+ replies += 1;
75
+ }
76
+ }
77
+ return found.map(clean).filter((text) => text.length > 0 && text.length <= MAX_NOTICE);
78
+ }
79
+
80
+ function firstLine(text: string): string {
81
+ return (text.split("\n")[0] ?? text).trim();
82
+ }
83
+
84
+ export function detectClaudeLimit(event: TurnEvent, now: Date = new Date()): LimitHit | null {
85
+ for (const text of notices(event, true)) {
86
+ const line = firstLine(text);
87
+ const match = CLAUDE_LIMITS.find(({ pattern }) => pattern.test(line));
88
+ if (match) return { message: line, kind: match.kind, resetsAt: parseClaudeReset(line, now) };
89
+ }
90
+ return null;
91
+ }
92
+
93
+ export function detectCodexLimit(event: TurnEvent, now: Date = new Date()): LimitHit | null {
94
+ for (const text of notices(event, false)) {
95
+ const match = CODEX_LIMITS.find(({ pattern }) => pattern.test(text));
96
+ if (match) return { message: firstLine(text), kind: match.kind, resetsAt: parseCodexReset(text, now) };
97
+ }
98
+ return null;
99
+ }
100
+
101
+ /** A turn that failed because the account's login is no longer valid. */
102
+ export function detectClaudeSignOut(event: TurnEvent): string | null {
103
+ for (const text of notices(event, true)) if (CLAUDE_SIGNED_OUT.test(firstLine(text))) return firstLine(text);
104
+ return null;
105
+ }
106
+
107
+ export function detectCodexSignOut(event: TurnEvent): string | null {
108
+ for (const text of notices(event, false)) if (CODEX_SIGNED_OUT.test(text)) return firstLine(text);
109
+ return null;
110
+ }
111
+
112
+ // --------------------------------------------------------------------------- reset times
113
+
114
+ const MONTHS = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"];
115
+
116
+ /**
117
+ * "· resets 3pm (Asia/Kolkata)", "· resets 3:30pm (America/New_York)",
118
+ * "· resets Sep 25, 3pm (Europe/Berlin)", or the legacy "|1790150000" epoch.
119
+ */
120
+ export function parseClaudeReset(text: string, now: Date): string | null {
121
+ const epoch = text.match(/usage limit reached\|(\d{9,})/i);
122
+ if (epoch?.[1]) return new Date(Number(epoch[1]) * 1000).toISOString();
123
+ const match = text.match(
124
+ /resets\s+(?:([A-Za-z]{3})[a-z]*\.?\s+(\d{1,2}),?\s+)?(\d{1,2})(?::(\d{2}))?\s*([ap])\.?m\.?(?:\s*\(([^)]+)\))?/i,
125
+ );
126
+ if (!match) return null;
127
+ const [, monthName, dayText, hourText, minuteText, meridiem, zone] = match;
128
+ const hour = to24(Number(hourText), meridiem ?? "a");
129
+ const minute = Number(minuteText ?? 0);
130
+ const timeZone = zone && isTimeZone(zone.trim()) ? zone.trim() : undefined;
131
+ const month = monthName ? MONTHS.indexOf(monthName.toLowerCase()) : -1;
132
+ return nextOccurrence(now, { month: month >= 0 ? month : null, day: dayText ? Number(dayText) : null, hour, minute, timeZone });
133
+ }
134
+
135
+ /** "try again at 3:45 PM" or "try again at Sep 24, 2026 3:45 PM", in the daemon's local time. */
136
+ export function parseCodexReset(text: string, now: Date): string | null {
137
+ const match = text.match(
138
+ /try again at\s+(?:([A-Za-z]{3})[a-z]*\.?\s+(\d{1,2}),?\s+(?:(\d{4})\s+)?)?(\d{1,2})(?::(\d{2}))?\s*([AaPp])\.?[Mm]\.?/,
139
+ );
140
+ if (!match) return null;
141
+ const [, monthName, dayText, yearText, hourText, minuteText, meridiem] = match;
142
+ const hour = to24(Number(hourText), meridiem ?? "a");
143
+ const minute = Number(minuteText ?? 0);
144
+ const month = monthName ? MONTHS.indexOf(monthName.toLowerCase()) : -1;
145
+ if (yearText && month >= 0 && dayText) {
146
+ const at = new Date(Number(yearText), month, Number(dayText), hour, minute);
147
+ return Number.isNaN(at.getTime()) ? null : at.toISOString();
148
+ }
149
+ return nextOccurrence(now, { month: month >= 0 ? month : null, day: dayText ? Number(dayText) : null, hour, minute });
150
+ }
151
+
152
+ function to24(hour: number, meridiem: string): number {
153
+ const pm = meridiem.toLowerCase() === "p";
154
+ if (hour === 12) return pm ? 12 : 0;
155
+ return pm ? hour + 12 : hour;
156
+ }
157
+
158
+ function isTimeZone(zone: string): boolean {
159
+ try {
160
+ new Intl.DateTimeFormat("en-US", { timeZone: zone });
161
+ return true;
162
+ } catch {
163
+ return false;
164
+ }
165
+ }
166
+
167
+ /** Wall-clock parts of `instant` in `timeZone` (or the local zone). */
168
+ function partsIn(instant: number, timeZone?: string) {
169
+ const parts = new Intl.DateTimeFormat("en-US", {
170
+ timeZone,
171
+ hourCycle: "h23",
172
+ year: "numeric",
173
+ month: "numeric",
174
+ day: "numeric",
175
+ hour: "numeric",
176
+ minute: "numeric",
177
+ }).formatToParts(instant);
178
+ const get = (type: string) => Number(parts.find((part) => part.type === type)?.value ?? 0);
179
+ return { year: get("year"), month: get("month") - 1, day: get("day"), hour: get("hour") % 24, minute: get("minute") };
180
+ }
181
+
182
+ /** The UTC instant at which `timeZone`'s wall clock reads the given date and time. */
183
+ function zonedInstant(year: number, month: number, day: number, hour: number, minute: number, timeZone?: string): number {
184
+ const wall = Date.UTC(year, month, day, hour, minute);
185
+ let guess = wall;
186
+ for (let attempt = 0; attempt < 3; attempt += 1) {
187
+ const seen = partsIn(guess, timeZone);
188
+ const delta = wall - Date.UTC(seen.year, seen.month, seen.day, seen.hour, seen.minute);
189
+ if (delta === 0) break;
190
+ guess += delta;
191
+ }
192
+ return guess;
193
+ }
194
+
195
+ function nextOccurrence(
196
+ now: Date,
197
+ target: { month: number | null; day: number | null; hour: number; minute: number; timeZone?: string },
198
+ ): string | null {
199
+ const today = partsIn(now.getTime(), target.timeZone);
200
+ if (target.month !== null && target.day !== null) {
201
+ let at = zonedInstant(today.year, target.month, target.day, target.hour, target.minute, target.timeZone);
202
+ if (at < now.getTime() - 60_000) {
203
+ at = zonedInstant(today.year + 1, target.month, target.day, target.hour, target.minute, target.timeZone);
204
+ }
205
+ return new Date(at).toISOString();
206
+ }
207
+ let at = zonedInstant(today.year, today.month, today.day, target.hour, target.minute, target.timeZone);
208
+ if (at <= now.getTime()) {
209
+ const tomorrow = partsIn(now.getTime() + 24 * 3_600_000, target.timeZone);
210
+ at = zonedInstant(tomorrow.year, tomorrow.month, tomorrow.day, target.hour, target.minute, target.timeZone);
211
+ }
212
+ return new Date(at).toISOString();
213
+ }
@@ -0,0 +1,17 @@
1
+ import { existsSync } from "node:fs";
2
+
3
+ /**
4
+ * Whether a browser on this machine can finish a sign-in. The providers' browser sign-ins redirect
5
+ * to `localhost`, which reaches the daemon only from the machine it runs on. Servers, containers
6
+ * and daemons started over SSH have nobody at a browser there, so they sign in with a code.
7
+ */
8
+ export function canSignInWithBrowser(
9
+ env: NodeJS.ProcessEnv = process.env,
10
+ platform: NodeJS.Platform = process.platform,
11
+ exists: (path: string) => boolean = existsSync,
12
+ ): boolean {
13
+ if (env.SSH_CONNECTION || env.SSH_CLIENT || env.SSH_TTY) return false;
14
+ if (platform === "darwin" || platform === "win32") return true;
15
+ if (exists("/.dockerenv") || exists("/run/.containerenv")) return false;
16
+ return Boolean(env.DISPLAY || env.WAYLAND_DISPLAY);
17
+ }
@@ -0,0 +1,34 @@
1
+ /** Paseo's permission tiers for agent modes, most careful first. */
2
+ const TIERS = ["planning", "safe", "moderate", "dangerous"] as const;
3
+
4
+ export interface ModeInfo {
5
+ id: string;
6
+ label?: string;
7
+ colorTier?: string | null;
8
+ }
9
+
10
+ function tierOf(mode: ModeInfo | undefined): number {
11
+ return mode?.colorTier ? TIERS.indexOf(mode.colorTier as (typeof TIERS)[number]) : -1;
12
+ }
13
+
14
+ /**
15
+ * The other provider's mode that allows no more than the source agent's mode: the same tier if it
16
+ * has one, otherwise the closest more careful one (first listed wins a tie). `null` when it has
17
+ * nothing that careful, or the source mode is unknown, so a fork never gets more freedom than the
18
+ * user gave the original.
19
+ */
20
+ export function equivalentMode(
21
+ sourceModes: readonly ModeInfo[],
22
+ sourceModeId: string | null | undefined,
23
+ targetModes: readonly ModeInfo[],
24
+ ): string | null {
25
+ const ceiling = tierOf(sourceModes.find((mode) => mode.id === sourceModeId));
26
+ if (ceiling < 0) return null;
27
+ let best: { id: string; tier: number } | null = null;
28
+ for (const mode of targetModes) {
29
+ const tier = tierOf(mode);
30
+ if (tier < 0 || tier > ceiling) continue;
31
+ if (!best || tier > best.tier) best = { id: mode.id, tier };
32
+ }
33
+ return best?.id ?? null;
34
+ }
@@ -0,0 +1,37 @@
1
+ import { homedir } from "node:os";
2
+ import { join, resolve } from "node:path";
3
+
4
+ export function paseoHome(): string {
5
+ const configured = process.env.PASEO_HOME?.trim();
6
+ return configured ? resolve(configured) : join(homedir(), ".paseo");
7
+ }
8
+
9
+ /** Everything ZeroSub writes lives here: its registry and the per-account credential homes. */
10
+ export function dataDir(): string {
11
+ return join(paseoHome(), "zerosub");
12
+ }
13
+
14
+ export function statePath(): string {
15
+ return join(dataDir(), "state.json");
16
+ }
17
+
18
+ export function homesDir(): string {
19
+ return join(dataDir(), "homes");
20
+ }
21
+
22
+ /** The config directory the Claude CLI uses when `CLAUDE_CONFIG_DIR` is not set. */
23
+ export function mainClaudeDir(): string {
24
+ const configured = process.env.CLAUDE_CONFIG_DIR?.trim();
25
+ return configured ? resolve(configured) : join(homedir(), ".claude");
26
+ }
27
+
28
+ /** Claude keeps its global config beside the config directory unless `CLAUDE_CONFIG_DIR` is set. */
29
+ export function mainClaudeGlobalConfig(): string {
30
+ const configured = process.env.CLAUDE_CONFIG_DIR?.trim();
31
+ return configured ? join(resolve(configured), ".claude.json") : join(homedir(), ".claude.json");
32
+ }
33
+
34
+ export function mainCodexHome(): string {
35
+ const configured = process.env.CODEX_HOME?.trim();
36
+ return configured ? resolve(configured) : join(homedir(), ".codex");
37
+ }
@@ -0,0 +1,66 @@
1
+ import { spawn, type ChildProcess } from "node:child_process";
2
+
3
+ export interface RunResult {
4
+ code: number | null;
5
+ stdout: string;
6
+ stderr: string;
7
+ timedOut: boolean;
8
+ }
9
+
10
+ /** Runs a command to completion with a timeout. Never throws for a non-zero exit. */
11
+ export function run(
12
+ command: string,
13
+ args: readonly string[],
14
+ options: { env?: NodeJS.ProcessEnv; timeoutMs?: number; input?: string; cwd?: string } = {},
15
+ ): Promise<RunResult> {
16
+ return new Promise((resolve) => {
17
+ let stdout = "";
18
+ let stderr = "";
19
+ let timedOut = false;
20
+ let child: ChildProcess;
21
+ try {
22
+ child = spawn(command, [...args], {
23
+ env: options.env ?? process.env,
24
+ cwd: options.cwd,
25
+ stdio: ["pipe", "pipe", "pipe"],
26
+ });
27
+ } catch (error) {
28
+ resolve({ code: null, stdout, stderr: error instanceof Error ? error.message : String(error), timedOut });
29
+ return;
30
+ }
31
+ const timer = setTimeout(() => {
32
+ timedOut = true;
33
+ child.kill("SIGTERM");
34
+ setTimeout(() => child.kill("SIGKILL"), 2_000).unref();
35
+ }, options.timeoutMs ?? 30_000);
36
+ // A child that exits early turns our stdin write into EPIPE; without a listener that kills the plugin.
37
+ child.stdin?.on("error", () => undefined);
38
+ child.stdout?.on("data", (chunk: Buffer) => (stdout += chunk.toString("utf8")));
39
+ child.stderr?.on("data", (chunk: Buffer) => (stderr += chunk.toString("utf8")));
40
+ child.on("error", (error) => {
41
+ stderr += error.message;
42
+ });
43
+ child.on("close", (code) => {
44
+ clearTimeout(timer);
45
+ resolve({ code, stdout, stderr, timedOut });
46
+ });
47
+ if (options.input !== undefined) child.stdin?.end(options.input);
48
+ else child.stdin?.end();
49
+ });
50
+ }
51
+
52
+ /** Strips ANSI escape sequences (colors, cursor movement, OSC hyperlinks) from terminal output. */
53
+ export function stripAnsi(text: string): string {
54
+ return text
55
+ .replace(/\u001b\][^\u0007\u001b]*(?:\u0007|\u001b\\)/g, "")
56
+ .replace(/\u001b\[[0-?]*[ -/]*[@-~]/g, "")
57
+ .replace(/\u001b[@-Z\\-_]/g, "")
58
+ .replace(/\r/g, "\n");
59
+ }
60
+
61
+ export function firstUrl(text: string, pattern: RegExp): string | null {
62
+ for (const match of text.matchAll(/https?:\/\/[^\s"'<>]+/g)) {
63
+ if (pattern.test(match[0])) return match[0];
64
+ }
65
+ return null;
66
+ }
@@ -0,0 +1,95 @@
1
+ import { execFile } from "node:child_process";
2
+ import { access, constants } from "node:fs/promises";
3
+ import { homedir } from "node:os";
4
+ import { delimiter, dirname, join } from "node:path";
5
+ import { paseoHome } from "./paths";
6
+
7
+ /**
8
+ * Reopens an agent's provider session so it picks up a new account.
9
+ *
10
+ * The plugin SDK has no session reopen (`agents.ref(id).refresh()` only refetches data), so this
11
+ * uses the bundled CLI's `paseo agent reload`, which the daemon implements as close + reopen with
12
+ * the current configuration. The CLI connects on its own; on a password-protected daemon it cannot,
13
+ * and the switch then applies the next time the session opens.
14
+ */
15
+ export class Reopener {
16
+ private cli: { at: number; path: Promise<string | null> } | null = null;
17
+
18
+ /** Path to the CLI, or null when none can be found (looked for again every few minutes). */
19
+ async locate(): Promise<string | null> {
20
+ if (this.cli && (Date.now() - this.cli.at < 5 * 60_000 || (await this.cli.path) !== null)) return this.cli.path;
21
+ this.cli = { at: Date.now(), path: findCli() };
22
+ return this.cli.path;
23
+ }
24
+
25
+ async reopen(agentId: string): Promise<{ ok: true } | { ok: false; error: string }> {
26
+ const cli = await this.locate();
27
+ if (!cli) return { ok: false, error: "The paseo command-line tool was not found on the daemon machine." };
28
+ return new Promise((resolve) => {
29
+ execFile(
30
+ cli,
31
+ ["agent", "reload", agentId, "--json", "--home", paseoHome()],
32
+ { timeout: 90_000, maxBuffer: 1024 * 1024, env: process.env },
33
+ (error, _stdout, stderr) => {
34
+ if (!error) return resolve({ ok: true });
35
+ const detail = `${stderr || error.message}`.trim().split("\n").slice(-3).join(" ");
36
+ resolve({ ok: false, error: explainFailure(detail) });
37
+ },
38
+ );
39
+ });
40
+ }
41
+ }
42
+
43
+ function explainFailure(detail: string): string {
44
+ if (/transport closed|cannot connect|cannot reach|password|unauthori[sz]ed|DAEMON_NOT_RUNNING/i.test(detail)) {
45
+ return "Paseo's CLI could not connect to this daemon (it may require a password). The agent switches accounts the next time its session starts.";
46
+ }
47
+ return detail || "Reload failed.";
48
+ }
49
+
50
+ async function isExecutable(path: string): Promise<boolean> {
51
+ try {
52
+ await access(path, constants.X_OK);
53
+ return true;
54
+ } catch {
55
+ return false;
56
+ }
57
+ }
58
+
59
+ async function findCli(): Promise<string | null> {
60
+ const candidates: string[] = [];
61
+ const executable = process.platform === "win32" ? "paseo.cmd" : "paseo";
62
+
63
+ // The daemon (and this subprocess) usually run inside the desktop app bundle, which ships the CLI.
64
+ const exec = process.execPath;
65
+ const appContents = exec.match(/^(.*?\.app\/Contents)\//)?.[1];
66
+ if (appContents) candidates.push(join(appContents, "Resources", "bin", "paseo"));
67
+ const resources = findAncestor(exec, "resources");
68
+ if (resources) candidates.push(join(resources, "bin", executable));
69
+
70
+ for (const directory of (process.env.PATH ?? "").split(delimiter)) {
71
+ if (directory) candidates.push(join(directory, executable));
72
+ }
73
+
74
+ if (process.platform === "darwin") {
75
+ candidates.push("/Applications/Paseo.app/Contents/Resources/bin/paseo");
76
+ candidates.push(join(homedir(), "Applications", "Paseo.app", "Contents", "Resources", "bin", "paseo"));
77
+ }
78
+ candidates.push(join(homedir(), ".local", "bin", executable));
79
+
80
+ for (const candidate of candidates) {
81
+ if (await isExecutable(candidate)) return candidate;
82
+ }
83
+ return null;
84
+ }
85
+
86
+ function findAncestor(path: string, name: string): string | null {
87
+ let current = dirname(path);
88
+ for (let depth = 0; depth < 6; depth += 1) {
89
+ if (current.toLowerCase().endsWith(`/${name}`) || current.toLowerCase().endsWith(`\\${name}`)) return current;
90
+ const parent = dirname(current);
91
+ if (parent === current) break;
92
+ current = parent;
93
+ }
94
+ return null;
95
+ }
@@ -0,0 +1,131 @@
1
+ import { peakUsage } from "../shared/format";
2
+ import type { Family, Usage } from "../shared/model";
3
+ import {
4
+ accountsOf,
5
+ defaultAccount,
6
+ findAccount,
7
+ mainAccount,
8
+ type Binding,
9
+ type StoredAccount,
10
+ type StoredState,
11
+ } from "./state";
12
+
13
+ export function isLimited(account: StoredAccount, now: number): boolean {
14
+ if (!account.limitedUntil) return false;
15
+ const until = Date.parse(account.limitedUntil);
16
+ return Number.isFinite(until) && until > now;
17
+ }
18
+
19
+ export function isUsable(account: StoredAccount, now: number): boolean {
20
+ return account.signedIn && !isLimited(account, now);
21
+ }
22
+
23
+ /** Lower is better. Unknown usage ranks in the middle so a known-quiet account wins over a mystery. */
24
+ export function headroomScore(usage: Usage | null | undefined): number {
25
+ const peak = usage ? peakUsage(usage.windows) : null;
26
+ return peak ? peak.usedPercent : 50;
27
+ }
28
+
29
+ /** The usable account with the most room, preferring the default, then the CLI login, on ties. */
30
+ export function mostAvailable(
31
+ state: StoredState,
32
+ family: Family,
33
+ usageOf: (accountId: string) => Usage | null | undefined,
34
+ now: number,
35
+ exclude: ReadonlySet<string> = new Set(),
36
+ ): StoredAccount | undefined {
37
+ const preferred = defaultAccount(state, family)?.id;
38
+ const candidates = accountsOf(state, family).filter(
39
+ (account) => !exclude.has(account.id) && isUsable(account, now),
40
+ );
41
+ const rank = (account: StoredAccount) => [
42
+ headroomScore(usageOf(account.id)),
43
+ account.id === preferred ? 0 : 1,
44
+ account.kind === "main" ? 0 : 1,
45
+ Date.parse(account.createdAt) || 0,
46
+ ];
47
+ candidates.sort((a, b) => {
48
+ const left = rank(a);
49
+ const right = rank(b);
50
+ for (let index = 0; index < left.length; index += 1) {
51
+ const delta = (left[index] ?? 0) - (right[index] ?? 0);
52
+ if (delta !== 0) return delta;
53
+ }
54
+ return 0;
55
+ });
56
+ return candidates[0];
57
+ }
58
+
59
+ export interface RouteInput {
60
+ agentId: string;
61
+ family: Family;
62
+ reason: "create" | "resume" | "refresh" | "import";
63
+ now: number;
64
+ autoSwitch: boolean;
65
+ balanceNewAgents: boolean;
66
+ /**
67
+ * Whether an existing conversation can open on a different account. When it can't (Codex), a
68
+ * thread stays on the account it started on, and only brand-new agents are balanced or rerouted.
69
+ */
70
+ portable: boolean;
71
+ usageOf(accountId: string): Usage | null | undefined;
72
+ }
73
+
74
+ export interface RouteDecision {
75
+ account: StoredAccount;
76
+ /** A binding to persist so the agent stays where it was routed. */
77
+ bind: Binding | null;
78
+ /** Why the preferred account was skipped, if it was. */
79
+ skipped: { account: StoredAccount; why: "limited" | "signed_out" } | null;
80
+ }
81
+
82
+ /**
83
+ * Which account a session opens on: the agent's own binding, else (for balanced new agents) the
84
+ * roomiest account, else the default. An exhausted or signed-out choice is swapped for the roomiest
85
+ * usable account when automatic switching is on — for new agents always, and for existing ones
86
+ * only when their conversation can move between accounts.
87
+ */
88
+ export function chooseAccount(state: StoredState, input: RouteInput): RouteDecision | null {
89
+ const accounts = accountsOf(state, input.family);
90
+ if (accounts.length === 0) return null;
91
+ const at = new Date(input.now).toISOString();
92
+ const fresh = input.reason === "create";
93
+
94
+ const binding = state.bindings[input.agentId];
95
+ const bound = findAccount(state, binding?.accountId);
96
+ let account = bound && bound.family === input.family ? bound : undefined;
97
+ let bind: Binding | null = null;
98
+
99
+ if (!account && fresh && input.balanceNewAgents && accounts.length > 1) {
100
+ account = mostAvailable(state, input.family, input.usageOf, input.now);
101
+ if (account) bind = { accountId: account.id, source: "balance", at };
102
+ }
103
+ if (!account) {
104
+ // An imported Codex thread most likely came from the user's own CLI, so it belongs to that login.
105
+ const imported = !input.portable && input.reason === "import" ? mainAccount(state, input.family) : undefined;
106
+ account = imported ?? defaultAccount(state, input.family);
107
+ // A thread that can't move is pinned to the account it first opened on.
108
+ if (account && !input.portable) bind = { accountId: account.id, source: "thread", at };
109
+ }
110
+ if (!account) return null;
111
+
112
+ let skipped: RouteDecision["skipped"] = null;
113
+ const why = !account.signedIn ? "signed_out" : isLimited(account, input.now) ? "limited" : null;
114
+ const mayMove = fresh || input.portable;
115
+ if (why && mayMove && (input.autoSwitch || why === "signed_out")) {
116
+ const alternative = mostAvailable(state, input.family, input.usageOf, input.now, new Set([account.id]));
117
+ if (alternative) {
118
+ skipped = { account, why };
119
+ account = alternative;
120
+ bind = { accountId: alternative.id, source: input.portable ? "auto" : "thread", at };
121
+ }
122
+ }
123
+ return { account, bind, skipped };
124
+ }
125
+
126
+ /** The account an agent is routed to right now, without side effects (for display). */
127
+ export function effectiveAccountId(state: StoredState, agentId: string, family: Family): string | undefined {
128
+ const bound = findAccount(state, state.bindings[agentId]?.accountId);
129
+ if (bound && bound.family === family) return bound.id;
130
+ return defaultAccount(state, family)?.id;
131
+ }