@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.
- package/LICENSE +21 -0
- package/README.md +152 -0
- package/client/accounts-surface.tsx +592 -0
- package/client/add-account.tsx +351 -0
- package/client/commands.ts +112 -0
- package/client/fork-confirm.tsx +57 -0
- package/client/pills.ts +251 -0
- package/client/reset-confirm.tsx +138 -0
- package/client/settings-screen.tsx +120 -0
- package/client/store.ts +139 -0
- package/client/switch-row.tsx +103 -0
- package/client/ui.tsx +231 -0
- package/index.client.tsx +39 -0
- package/index.server.ts +91 -0
- package/package.json +58 -0
- package/paseo-plugin.json +7 -0
- package/server/adapter.ts +126 -0
- package/server/binaries.ts +63 -0
- package/server/claude-resets.ts +192 -0
- package/server/claude.ts +478 -0
- package/server/codex.ts +459 -0
- package/server/families.ts +78 -0
- package/server/handoff.ts +175 -0
- package/server/homes.ts +352 -0
- package/server/json-file.ts +39 -0
- package/server/limits.ts +213 -0
- package/server/machine.ts +17 -0
- package/server/modes.ts +34 -0
- package/server/paths.ts +37 -0
- package/server/process.ts +66 -0
- package/server/reopen.ts +95 -0
- package/server/routing.ts +131 -0
- package/server/service.ts +1692 -0
- package/server/state.ts +177 -0
- package/server/switch-guard.ts +28 -0
- package/server/usage.ts +68 -0
- package/shared/format.ts +99 -0
- package/shared/model.ts +150 -0
- package/shared/preferences.ts +32 -0
- package/shared/rpc.ts +120 -0
- package/shared/timeline.ts +42 -0
|
@@ -0,0 +1,1692 @@
|
|
|
1
|
+
import { randomBytes } from "node:crypto";
|
|
2
|
+
import { readdir } from "node:fs/promises";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import type { AgentTimelineItem } from "@getpaseo/protocol/agent-types";
|
|
5
|
+
import type {
|
|
6
|
+
PluginHookContext,
|
|
7
|
+
PluginLifecycleEvents,
|
|
8
|
+
PluginSessionOpenRequest,
|
|
9
|
+
} from "@getpaseo/plugin/server";
|
|
10
|
+
import {
|
|
11
|
+
FAMILY_LABEL,
|
|
12
|
+
type AccountView,
|
|
13
|
+
type AgentRoute,
|
|
14
|
+
type Family,
|
|
15
|
+
type LoginMethod,
|
|
16
|
+
type LoginView,
|
|
17
|
+
type StateView,
|
|
18
|
+
type Usage,
|
|
19
|
+
} from "../shared/model";
|
|
20
|
+
import { DEFAULT_CONTINUE_PROMPT, type Preferences } from "../shared/preferences";
|
|
21
|
+
import type { RedeemResult, ReopenSummary } from "../shared/rpc";
|
|
22
|
+
import { SWITCH_ROW_KIND, SWITCH_ROW_VERSION, type SwitchRow } from "../shared/timeline";
|
|
23
|
+
import {
|
|
24
|
+
applyEnv,
|
|
25
|
+
type FamilyAdapter,
|
|
26
|
+
type Identity,
|
|
27
|
+
type LimitHit,
|
|
28
|
+
type LimitKind,
|
|
29
|
+
type LoginHandle,
|
|
30
|
+
type RedeemReply,
|
|
31
|
+
type UsageRead,
|
|
32
|
+
} from "./adapter";
|
|
33
|
+
import { FamilyResolver } from "./families";
|
|
34
|
+
import { CONTINUED_FROM_LABEL, continueInNewAgent, type Continuation } from "./handoff";
|
|
35
|
+
import { removeHome } from "./homes";
|
|
36
|
+
import { Mutex } from "./json-file";
|
|
37
|
+
import { canSignInWithBrowser } from "./machine";
|
|
38
|
+
import { equivalentMode } from "./modes";
|
|
39
|
+
import { homesDir } from "./paths";
|
|
40
|
+
import { Reopener } from "./reopen";
|
|
41
|
+
import { SwitchGuard } from "./switch-guard";
|
|
42
|
+
import { loadReadings, mergeUsage, saveReadings, showLimit } from "./usage";
|
|
43
|
+
import { chooseAccount, isLimited, mostAvailable } from "./routing";
|
|
44
|
+
import {
|
|
45
|
+
MAIN_ACCOUNT_ID,
|
|
46
|
+
StateStore,
|
|
47
|
+
accountsOf,
|
|
48
|
+
defaultAccount,
|
|
49
|
+
findAccount,
|
|
50
|
+
mainAccount,
|
|
51
|
+
type StoredAccount,
|
|
52
|
+
type StoredState,
|
|
53
|
+
} from "./state";
|
|
54
|
+
|
|
55
|
+
type PaseoApi = PluginHookContext["paseo"];
|
|
56
|
+
type TurnEnded = PluginLifecycleEvents["agent.turn_ended"];
|
|
57
|
+
|
|
58
|
+
const FAMILIES: readonly Family[] = ["claude", "codex"];
|
|
59
|
+
const PROVIDER_NAME: Record<Family, string> = { claude: "Claude Code", codex: "Codex" };
|
|
60
|
+
const OTHER_FAMILY: Record<Family, Family> = { claude: "codex", codex: "claude" };
|
|
61
|
+
/** How often to read usage: accounts in use, the defaults, and the rest. Adapters space reads further. */
|
|
62
|
+
const USAGE_BUSY_MS = 60_000;
|
|
63
|
+
const USAGE_DEFAULT_MS = 5 * 60_000;
|
|
64
|
+
const USAGE_IDLE_MS = 20 * 60_000;
|
|
65
|
+
/** An account counts as in use for this long after one of its agents starts or ends a turn. */
|
|
66
|
+
const ACTIVE_WINDOW_MS = 15 * 60_000;
|
|
67
|
+
const UPKEEP_MS = 30_000;
|
|
68
|
+
const IDENTITY_MS = 30 * 60_000;
|
|
69
|
+
const AVAILABILITY_MS = 10 * 60_000;
|
|
70
|
+
/** Assumed length of a window limit whose reset time couldn't be read. */
|
|
71
|
+
const WINDOW_LIMIT_MS = 60 * 60_000;
|
|
72
|
+
/** Budget limits (spend caps, credits) don't show in usage; retry after this long. */
|
|
73
|
+
const BUDGET_LIMIT_MS = 3 * 60 * 60_000;
|
|
74
|
+
/** A fresh limit isn't second-guessed by usage readings for this long. */
|
|
75
|
+
const LIMIT_TRUST_MS = 15 * 60_000;
|
|
76
|
+
const LOGIN_TTL_MS = 15 * 60_000;
|
|
77
|
+
const LOGIN_GRACE_MS = 3_000;
|
|
78
|
+
const PRUNE_MS = 10 * 60_000;
|
|
79
|
+
/** After a reset, limit notices from turns that were already running are stale. */
|
|
80
|
+
const RESET_GRACE_MS = 5 * 60_000;
|
|
81
|
+
const AGENT_LIST_MS = 3_000;
|
|
82
|
+
|
|
83
|
+
const DEFAULT_PREFERENCES: Preferences = {
|
|
84
|
+
autoSwitch: true,
|
|
85
|
+
autoContinue: true,
|
|
86
|
+
continuePrompt: DEFAULT_CONTINUE_PROMPT,
|
|
87
|
+
balanceNewAgents: false,
|
|
88
|
+
showComposerPill: true,
|
|
89
|
+
autoRedeem: false,
|
|
90
|
+
forkOtherProvider: false,
|
|
91
|
+
};
|
|
92
|
+
|
|
93
|
+
interface LoginSession {
|
|
94
|
+
id: string;
|
|
95
|
+
family: Family;
|
|
96
|
+
/** Existing account being signed back in. */
|
|
97
|
+
accountId: string | null;
|
|
98
|
+
/** Where the CLI writes credentials; null for the CLI's own login. */
|
|
99
|
+
home: string | null;
|
|
100
|
+
handle: LoginHandle | null;
|
|
101
|
+
view: LoginView;
|
|
102
|
+
finishedAt: number | null;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
interface AgentInfo {
|
|
106
|
+
id: string;
|
|
107
|
+
provider: string;
|
|
108
|
+
status: string;
|
|
109
|
+
archived: boolean;
|
|
110
|
+
/** The conversation has started (so a Codex thread already holds account-bound reasoning). */
|
|
111
|
+
hasHistory: boolean;
|
|
112
|
+
title: string | null;
|
|
113
|
+
/** The agent this one carries on from, when ZeroSub started it as a continuation. */
|
|
114
|
+
continuedFrom: string | null;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
type ReopenOutcome = "reopened" | "deferred" | "closed" | "failed";
|
|
118
|
+
type Problem = { kind: "limit"; hit: LimitHit } | { kind: "signed_out" };
|
|
119
|
+
|
|
120
|
+
/** The agent has a running CLI session (idle between turns counts). */
|
|
121
|
+
function isLive(status: string): boolean {
|
|
122
|
+
return status === "idle" || status === "running" || status === "initializing";
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
function emptySummary(): ReopenSummary {
|
|
126
|
+
return { reopened: [], deferred: [], failed: [], continuedIn: null };
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
export class Service {
|
|
130
|
+
private paseo: PaseoApi | null = null;
|
|
131
|
+
private prefs: Preferences = DEFAULT_PREFERENCES;
|
|
132
|
+
private readonly usage = new Map<string, Usage>();
|
|
133
|
+
private readonly usageAttemptAt = new Map<string, number>();
|
|
134
|
+
private readonly usageInFlight = new Map<string, Promise<void>>();
|
|
135
|
+
private readonly identityCheckedAt = new Map<string, number>();
|
|
136
|
+
private readonly availability = new Map<Family, { ok: boolean; detail: string | null; at: number }>();
|
|
137
|
+
private readonly logins = new Map<string, LoginSession>();
|
|
138
|
+
private readonly loginLocks: Record<Family, Mutex> = { claude: new Mutex(), codex: new Mutex() };
|
|
139
|
+
/** Agents whose account changed mid-turn; reopened when the turn ends. */
|
|
140
|
+
private readonly deferred = new Map<string, SwitchRow | null>();
|
|
141
|
+
/** Agents in the middle of a failover, so nothing else moves them at the same time. */
|
|
142
|
+
private readonly switching = new Set<string>();
|
|
143
|
+
/** One failover at a time per exhausted account. */
|
|
144
|
+
private readonly failoverLocks = new Map<string, Mutex>();
|
|
145
|
+
private readonly switchGuard = new SwitchGuard();
|
|
146
|
+
/** When the guard last told an agent's timeline it stopped switching, so it says so once. */
|
|
147
|
+
private readonly guardNoticeAt = new Map<string, number>();
|
|
148
|
+
/** When each account's agents last started or ended a turn, to read busy accounts often. */
|
|
149
|
+
private readonly activeAt = new Map<string, number>();
|
|
150
|
+
/** The provider asked us not to read this account's usage again before then. */
|
|
151
|
+
private readonly usageRetryAt = new Map<string, number>();
|
|
152
|
+
private usageSave: ReturnType<typeof setTimeout> | null = null;
|
|
153
|
+
private readonly lastRedeemAt = new Map<string, number>();
|
|
154
|
+
private readonly redeemLocks = new Map<string, Mutex>();
|
|
155
|
+
private readonly browserSignIn = canSignInWithBrowser();
|
|
156
|
+
private agentCache: { at: number; agents: Promise<AgentInfo[]> } | null = null;
|
|
157
|
+
private lastPrune = 0;
|
|
158
|
+
private collecting = false;
|
|
159
|
+
private timer: ReturnType<typeof setInterval> | null = null;
|
|
160
|
+
private stopped = false;
|
|
161
|
+
|
|
162
|
+
constructor(
|
|
163
|
+
private readonly adapters: Record<Family, FamilyAdapter>,
|
|
164
|
+
private readonly store = new StateStore(),
|
|
165
|
+
private readonly families = new FamilyResolver(),
|
|
166
|
+
private readonly reopener = new Reopener(),
|
|
167
|
+
) {}
|
|
168
|
+
|
|
169
|
+
setPreferences(prefs: Preferences): void {
|
|
170
|
+
this.prefs = prefs;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/** Remember the plugin's SDK connection for background work (cleanup, failover). */
|
|
174
|
+
attach(paseo: PaseoApi): void {
|
|
175
|
+
this.paseo ??= paseo;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
async start(): Promise<void> {
|
|
179
|
+
// The last readings show right away; fresh ones replace them as they arrive.
|
|
180
|
+
for (const [accountId, reading] of await loadReadings()) if (!this.usage.has(accountId)) this.usage.set(accountId, reading);
|
|
181
|
+
await Promise.all(FAMILIES.map((family) => this.ensureFamily(family)));
|
|
182
|
+
this.timer = setInterval(() => void this.tick().catch((error: unknown) => log("upkeep failed", error)), UPKEEP_MS);
|
|
183
|
+
this.timer.unref?.();
|
|
184
|
+
void this.tick().catch(() => undefined);
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
async stop(): Promise<void> {
|
|
188
|
+
this.stopped = true;
|
|
189
|
+
if (this.timer) clearInterval(this.timer);
|
|
190
|
+
if (this.usageSave) {
|
|
191
|
+
clearTimeout(this.usageSave);
|
|
192
|
+
await saveReadings(this.usage).catch(() => undefined);
|
|
193
|
+
}
|
|
194
|
+
for (const login of this.logins.values()) login.handle?.cancel();
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
// ------------------------------------------------------------------ upkeep
|
|
198
|
+
|
|
199
|
+
/** Checks the CLI is installed and registers its own login as an account. */
|
|
200
|
+
private async ensureFamily(family: Family): Promise<void> {
|
|
201
|
+
const adapter = this.adapters[family];
|
|
202
|
+
const availability = await adapter.available().catch((error: unknown) => ({ ok: false, detail: describe(error) }));
|
|
203
|
+
this.availability.set(family, { ...availability, at: Date.now() });
|
|
204
|
+
if (!availability.ok) return;
|
|
205
|
+
const identity = await adapter.identity(null).catch(() => null);
|
|
206
|
+
this.identityCheckedAt.set(MAIN_ACCOUNT_ID[family], Date.now());
|
|
207
|
+
await this.store.update((draft) => {
|
|
208
|
+
let main = findAccount(draft, MAIN_ACCOUNT_ID[family]);
|
|
209
|
+
if (!main) {
|
|
210
|
+
main = newAccount({ id: MAIN_ACCOUNT_ID[family], family, kind: "main", home: null });
|
|
211
|
+
main.signedIn = false;
|
|
212
|
+
draft.accounts.unshift(main);
|
|
213
|
+
}
|
|
214
|
+
if (identity) applyIdentity(main, identity, draft);
|
|
215
|
+
if (!main.label) main.label = `${FAMILY_LABEL[family]} (CLI login)`;
|
|
216
|
+
});
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
private async tick(): Promise<void> {
|
|
220
|
+
if (this.stopped) return;
|
|
221
|
+
const now = Date.now();
|
|
222
|
+
for (const family of FAMILIES) {
|
|
223
|
+
const availability = this.availability.get(family);
|
|
224
|
+
if (availability && !availability.ok && now - availability.at > AVAILABILITY_MS) {
|
|
225
|
+
void this.ensureFamily(family).catch(() => undefined);
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
const state = await this.store.read();
|
|
229
|
+
for (const account of state.accounts) {
|
|
230
|
+
const attempted = this.usageAttemptAt.get(account.id) ?? 0;
|
|
231
|
+
const busy = now - (this.activeAt.get(account.id) ?? 0) < ACTIVE_WINDOW_MS;
|
|
232
|
+
const isDefault = defaultAccount(state, account.family)?.id === account.id;
|
|
233
|
+
const every = busy ? USAGE_BUSY_MS : isDefault ? USAGE_DEFAULT_MS : USAGE_IDLE_MS;
|
|
234
|
+
if (account.signedIn && now - attempted > every) {
|
|
235
|
+
void this.refreshUsage(account.id).catch((error: unknown) => log(`usage refresh for ${account.label} failed`, error));
|
|
236
|
+
}
|
|
237
|
+
if (now - (this.identityCheckedAt.get(account.id) ?? 0) > IDENTITY_MS) {
|
|
238
|
+
void this.refreshIdentity(account.id).catch(() => undefined);
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
for (const [id, login] of this.logins) {
|
|
242
|
+
if (login.finishedAt && now - login.finishedAt > LOGIN_TTL_MS) this.logins.delete(id);
|
|
243
|
+
else if (!login.finishedAt && now - Date.parse(login.view.startedAt) > LOGIN_TTL_MS) void this.cancelLogin(id);
|
|
244
|
+
}
|
|
245
|
+
if (this.paseo) await this.collectOrphanHomes(this.paseo);
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
private async refreshIdentity(accountId: string): Promise<void> {
|
|
249
|
+
this.identityCheckedAt.set(accountId, Date.now());
|
|
250
|
+
const account = findAccount(await this.store.read(), accountId);
|
|
251
|
+
if (!account) return;
|
|
252
|
+
const identity = await this.adapters[account.family].identity(account.home).catch(() => null);
|
|
253
|
+
if (!identity) return;
|
|
254
|
+
await this.store.update((draft) => {
|
|
255
|
+
const target = findAccount(draft, accountId);
|
|
256
|
+
if (target) applyIdentity(target, identity, draft);
|
|
257
|
+
});
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
/** Forget bindings and sessions of agents that no longer exist (including Paseo's internal helpers). */
|
|
261
|
+
private async prune(paseo: PaseoApi): Promise<void> {
|
|
262
|
+
const now = Date.now();
|
|
263
|
+
if (now - this.lastPrune < PRUNE_MS) return;
|
|
264
|
+
this.lastPrune = now;
|
|
265
|
+
const { agents, complete } = await listAgents(paseo, true);
|
|
266
|
+
if (!complete) return; // Can't tell "gone" from "not listed".
|
|
267
|
+
const known = new Set(agents.map((agent) => agent.id));
|
|
268
|
+
const state = await this.store.read();
|
|
269
|
+
const old = (at: string) => now - (Date.parse(at) || 0) > PRUNE_MS;
|
|
270
|
+
const staleSessions = Object.entries(state.sessions).filter(([id, session]) => !known.has(id) && old(session.openedAt));
|
|
271
|
+
const staleBindings = Object.entries(state.bindings).filter(([id, binding]) => !known.has(id) && old(binding.at));
|
|
272
|
+
if (staleSessions.length === 0 && staleBindings.length === 0) return;
|
|
273
|
+
await this.store.update((draft) => {
|
|
274
|
+
for (const [id] of staleSessions) delete draft.sessions[id];
|
|
275
|
+
for (const [id] of staleBindings) delete draft.bindings[id];
|
|
276
|
+
});
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
/**
|
|
280
|
+
* Signs out and deletes managed homes no account owns any more — removed accounts, and abandoned
|
|
281
|
+
* or failed sign-ins — once no live agent session still runs on them.
|
|
282
|
+
*/
|
|
283
|
+
private async collectOrphanHomes(paseo: PaseoApi): Promise<void> {
|
|
284
|
+
if (this.collecting) return;
|
|
285
|
+
this.collecting = true;
|
|
286
|
+
try {
|
|
287
|
+
const root = homesDir();
|
|
288
|
+
const names = await readdir(root).catch(() => [] as string[]);
|
|
289
|
+
if (names.length === 0) return;
|
|
290
|
+
const state = await this.store.read();
|
|
291
|
+
const owned = new Set(state.accounts.map((account) => account.home).filter((home): home is string => Boolean(home)));
|
|
292
|
+
for (const login of this.logins.values()) {
|
|
293
|
+
const active = !login.finishedAt || Date.now() - login.finishedAt < LOGIN_GRACE_MS;
|
|
294
|
+
if (active && login.home) owned.add(login.home);
|
|
295
|
+
}
|
|
296
|
+
for (const name of names) {
|
|
297
|
+
const home = join(root, name);
|
|
298
|
+
const family: Family | null = name.startsWith("claude-") ? "claude" : name.startsWith("codex-") ? "codex" : null;
|
|
299
|
+
if (!family || owned.has(home)) continue;
|
|
300
|
+
// A managed account's ID is its home's folder name, so sessions still name it after removal.
|
|
301
|
+
const users = Object.entries(state.sessions)
|
|
302
|
+
.filter(([, session]) => session.accountId === name)
|
|
303
|
+
.map(([agentId]) => agentId);
|
|
304
|
+
let live = false;
|
|
305
|
+
for (const agentId of users) {
|
|
306
|
+
const info = await agentInfo(paseo, agentId);
|
|
307
|
+
if (info && !info.archived && info.status !== "closed") {
|
|
308
|
+
live = true;
|
|
309
|
+
break;
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
if (live) continue;
|
|
313
|
+
await this.adapters[family].logout(home).catch((error: unknown) => log(`signing out ${name} failed`, error));
|
|
314
|
+
await removeHome(home);
|
|
315
|
+
if (users.length > 0) {
|
|
316
|
+
await this.store.update((draft) => {
|
|
317
|
+
for (const agentId of users) if (draft.sessions[agentId]?.accountId === name) delete draft.sessions[agentId];
|
|
318
|
+
});
|
|
319
|
+
}
|
|
320
|
+
console.log(`[ZeroSub] removed the unused account home ${name}`);
|
|
321
|
+
}
|
|
322
|
+
} finally {
|
|
323
|
+
this.collecting = false;
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
private scheduleCleanup(): void {
|
|
328
|
+
const paseo = this.paseo;
|
|
329
|
+
if (!paseo) return;
|
|
330
|
+
setTimeout(
|
|
331
|
+
() => void this.collectOrphanHomes(paseo).catch((error: unknown) => log("cleanup failed", error)),
|
|
332
|
+
LOGIN_GRACE_MS + 500,
|
|
333
|
+
).unref?.();
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
// ------------------------------------------------------------------ hooks
|
|
337
|
+
|
|
338
|
+
/** Routes every provider session (create, resume, refresh, import) to the agent's account. */
|
|
339
|
+
async onSessionOpen(
|
|
340
|
+
request: PluginSessionOpenRequest,
|
|
341
|
+
context: PluginHookContext,
|
|
342
|
+
): Promise<PluginSessionOpenRequest | undefined> {
|
|
343
|
+
this.attach(context.paseo);
|
|
344
|
+
const family = (await this.families.resolve(context.paseo))[request.provider];
|
|
345
|
+
if (!family) return undefined;
|
|
346
|
+
const adapter = this.adapters[family];
|
|
347
|
+
const now = Date.now();
|
|
348
|
+
const state = await this.store.read();
|
|
349
|
+
const decision = chooseAccount(state, {
|
|
350
|
+
agentId: request.agentId,
|
|
351
|
+
family,
|
|
352
|
+
reason: request.reason,
|
|
353
|
+
now,
|
|
354
|
+
autoSwitch: this.prefs.autoSwitch,
|
|
355
|
+
balanceNewAgents: this.prefs.balanceNewAgents,
|
|
356
|
+
portable: adapter.portable,
|
|
357
|
+
usageOf: (id) => this.usage.get(id),
|
|
358
|
+
});
|
|
359
|
+
if (!decision) return undefined;
|
|
360
|
+
const { account } = decision;
|
|
361
|
+
|
|
362
|
+
if (account.kind === "managed" && account.home) {
|
|
363
|
+
await adapter.prepareHome(account.home).catch((error: unknown) => log(`could not refresh the home of ${account.label}`, error));
|
|
364
|
+
}
|
|
365
|
+
const interactive = request.purpose === "interactive";
|
|
366
|
+
const seenBinding = state.bindings[request.agentId]?.accountId;
|
|
367
|
+
const bindingChanged = decision.bind !== null && seenBinding !== decision.bind.accountId;
|
|
368
|
+
const sessionChanged = interactive && state.sessions[request.agentId]?.accountId !== account.id;
|
|
369
|
+
if (bindingChanged || sessionChanged) {
|
|
370
|
+
await this.store.update((draft) => {
|
|
371
|
+
// Don't overwrite a choice the user made while this decision was being taken.
|
|
372
|
+
if (decision.bind && bindingChanged && draft.bindings[request.agentId]?.accountId === seenBinding) {
|
|
373
|
+
draft.bindings[request.agentId] = decision.bind;
|
|
374
|
+
}
|
|
375
|
+
if (interactive) draft.sessions[request.agentId] = { accountId: account.id, family, openedAt: new Date(now).toISOString() };
|
|
376
|
+
});
|
|
377
|
+
}
|
|
378
|
+
// A fresh session already runs on the routed account, so any pending switch is done.
|
|
379
|
+
if (interactive) this.deferred.delete(request.agentId);
|
|
380
|
+
this.activeAt.set(account.id, now);
|
|
381
|
+
console.log(
|
|
382
|
+
`[ZeroSub] ${request.provider} agent ${request.agentId} → ${account.label} (${request.reason}${
|
|
383
|
+
decision.skipped ? `; skipped ${decision.skipped.account.label}: ${decision.skipped.why}` : ""
|
|
384
|
+
})`,
|
|
385
|
+
);
|
|
386
|
+
return { ...request, env: applyEnv(await adapter.env(account.home), request.env) };
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
/** A turn uses the account from its first token, so a long one keeps its usage fresh too. */
|
|
390
|
+
async onTurnStarted(agent: { id: string; provider: string }, context: PluginHookContext): Promise<void> {
|
|
391
|
+
this.attach(context.paseo);
|
|
392
|
+
const family = (await this.families.resolve(context.paseo))[agent.provider];
|
|
393
|
+
if (!family) return;
|
|
394
|
+
const accountId = this.runningOn(await this.store.read(), agent.id, family);
|
|
395
|
+
if (accountId) this.activeAt.set(accountId, Date.now());
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
async onTurnEnded(event: TurnEnded, context: PluginHookContext): Promise<void> {
|
|
399
|
+
this.attach(context.paseo);
|
|
400
|
+
const family = (await this.families.resolve(context.paseo))[event.agent.provider];
|
|
401
|
+
if (!family) return;
|
|
402
|
+
const adapter = this.adapters[family];
|
|
403
|
+
const agentId = event.agent.id;
|
|
404
|
+
const accountId = this.runningOn(await this.store.read(), agentId, family);
|
|
405
|
+
if (accountId) this.activeAt.set(accountId, Date.now());
|
|
406
|
+
if (event.outcome.kind !== "canceled") {
|
|
407
|
+
const hit = adapter.detectLimit(event);
|
|
408
|
+
if (hit) return this.handleUnavailable(context.paseo, agentId, family, event.timeline, { kind: "limit", hit });
|
|
409
|
+
if (adapter.detectSignOut(event) && (await this.confirmSignedOut(agentId, family))) {
|
|
410
|
+
return this.handleUnavailable(context.paseo, agentId, family, event.timeline, { kind: "signed_out" });
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
if (this.deferred.has(agentId)) await this.finishDeferred(context.paseo, agentId, family);
|
|
414
|
+
// The turn just used the account: read its usage again as soon as the provider allows.
|
|
415
|
+
if (accountId) void this.refreshUsage(accountId).catch(() => undefined);
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
async onAgentArchived(agentId: string): Promise<void> {
|
|
419
|
+
this.deferred.delete(agentId);
|
|
420
|
+
this.switchGuard.forget(agentId);
|
|
421
|
+
this.guardNoticeAt.delete(agentId);
|
|
422
|
+
if (!(await this.store.read()).sessions[agentId]) return;
|
|
423
|
+
await this.store.update((draft) => {
|
|
424
|
+
delete draft.sessions[agentId];
|
|
425
|
+
});
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
/** Re-checks the account an agent was using; true when it really is signed out now. */
|
|
429
|
+
private async confirmSignedOut(agentId: string, family: Family): Promise<boolean> {
|
|
430
|
+
const state = await this.store.read();
|
|
431
|
+
const accountId = this.runningOn(state, agentId, family);
|
|
432
|
+
if (!accountId) return false;
|
|
433
|
+
await this.refreshIdentity(accountId);
|
|
434
|
+
return findAccount(await this.store.read(), accountId)?.signedIn === false;
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
/** Carries out a switch that waited for the agent's turn to end, unless it's no longer wanted. */
|
|
438
|
+
private async finishDeferred(paseo: PaseoApi, agentId: string, family: Family): Promise<void> {
|
|
439
|
+
const row = this.deferred.get(agentId) ?? null;
|
|
440
|
+
this.deferred.delete(agentId);
|
|
441
|
+
const state = await this.store.read();
|
|
442
|
+
const current = this.runningOn(state, agentId, family);
|
|
443
|
+
if (!current || this.targetFor(state, agentId, family) === current) return; // Switched back meanwhile.
|
|
444
|
+
const outcome = await this.reopenAgent(paseo, agentId, row, true);
|
|
445
|
+
if (outcome === "reopened" && row) await this.appendRow(paseo, agentId, await this.landed(row, agentId));
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
// ------------------------------------------------------------------ limits and failover
|
|
449
|
+
|
|
450
|
+
private lockFor(accountId: string): Mutex {
|
|
451
|
+
let lock = this.failoverLocks.get(accountId);
|
|
452
|
+
if (!lock) this.failoverLocks.set(accountId, (lock = new Mutex()));
|
|
453
|
+
return lock;
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
private async handleUnavailable(
|
|
457
|
+
paseo: PaseoApi,
|
|
458
|
+
agentId: string,
|
|
459
|
+
family: Family,
|
|
460
|
+
timeline: readonly AgentTimelineItem[],
|
|
461
|
+
problem: Problem,
|
|
462
|
+
): Promise<void> {
|
|
463
|
+
if (this.switching.has(agentId)) return;
|
|
464
|
+
this.switching.add(agentId);
|
|
465
|
+
let exhausted: string | null = null;
|
|
466
|
+
try {
|
|
467
|
+
const state = await this.store.read();
|
|
468
|
+
const account = findAccount(state, this.runningOn(state, agentId, family));
|
|
469
|
+
if (!account) return;
|
|
470
|
+
exhausted = account.id;
|
|
471
|
+
await this.lockFor(account.id).run(() => this.failover(paseo, agentId, family, account, timeline, problem));
|
|
472
|
+
} finally {
|
|
473
|
+
this.switching.delete(agentId);
|
|
474
|
+
}
|
|
475
|
+
if (exhausted && this.prefs.autoSwitch && this.adapters[family].portable) {
|
|
476
|
+
void this.moveIdleAgentsOff(paseo, exhausted, family, agentId, problem.kind).catch((error: unknown) =>
|
|
477
|
+
log("moving idle agents failed", error),
|
|
478
|
+
);
|
|
479
|
+
}
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
private async failover(
|
|
483
|
+
paseo: PaseoApi,
|
|
484
|
+
agentId: string,
|
|
485
|
+
family: Family,
|
|
486
|
+
account: StoredAccount,
|
|
487
|
+
timeline: readonly AgentTimelineItem[],
|
|
488
|
+
problem: Problem,
|
|
489
|
+
): Promise<void> {
|
|
490
|
+
const adapter = this.adapters[family];
|
|
491
|
+
const now = Date.now();
|
|
492
|
+
if (problem.kind === "limit" && problem.hit.kind === "window" && this.recentlyRedeemed(account.id)) {
|
|
493
|
+
// This turn hit the limit just before a reset refilled it (another agent's failover or the
|
|
494
|
+
// user spent one moments ago). The account has room again: carry on instead of switching.
|
|
495
|
+
console.log(`[ZeroSub] ${account.label} was just reset; ${agentId} carries on where it is`);
|
|
496
|
+
if (this.prefs.autoContinue && this.switchGuard.allows(agentId, now)) {
|
|
497
|
+
this.switchGuard.note(agentId, now);
|
|
498
|
+
await paseo.agents
|
|
499
|
+
.ref(agentId)
|
|
500
|
+
.send(this.prefs.continuePrompt)
|
|
501
|
+
.catch((error: unknown) => log(`could not continue ${agentId}`, error));
|
|
502
|
+
}
|
|
503
|
+
return;
|
|
504
|
+
}
|
|
505
|
+
let resetsAt: string | null = null;
|
|
506
|
+
if (problem.kind === "limit") {
|
|
507
|
+
const { hit } = problem;
|
|
508
|
+
resetsAt = hit.resetsAt ?? new Date(now + (hit.kind === "budget" ? BUDGET_LIMIT_MS : WINDOW_LIMIT_MS)).toISOString();
|
|
509
|
+
await this.markLimited(account.id, resetsAt, hit.kind);
|
|
510
|
+
if (hit.kind === "window") {
|
|
511
|
+
// The notice is the freshest word on usage: show that window full until a new reading lands.
|
|
512
|
+
const shown = this.usage.get(account.id);
|
|
513
|
+
if (shown) this.setUsage(account.id, showLimit(shown, hit.resetsAt));
|
|
514
|
+
// The account was just used, so its token is fresh: ask for the exact reset time.
|
|
515
|
+
await withTimeout(this.refreshUsage(account.id, true), 12_000);
|
|
516
|
+
const exact = this.resetFromUsage(account.id);
|
|
517
|
+
if (exact && Date.parse(exact) > now) {
|
|
518
|
+
resetsAt = exact;
|
|
519
|
+
await this.markLimited(account.id, exact, "window");
|
|
520
|
+
}
|
|
521
|
+
}
|
|
522
|
+
console.log(`[ZeroSub] ${account.label} hit a ${hit.kind} limit (agent ${agentId}): ${hit.message}`);
|
|
523
|
+
} else {
|
|
524
|
+
console.log(`[ZeroSub] ${account.label} is signed out (agent ${agentId})`);
|
|
525
|
+
}
|
|
526
|
+
|
|
527
|
+
if (!this.prefs.autoSwitch) return;
|
|
528
|
+
const latest = await this.store.read();
|
|
529
|
+
if (this.runningOn(latest, agentId, family) !== account.id) return; // Already moved.
|
|
530
|
+
const base = {
|
|
531
|
+
family,
|
|
532
|
+
from: account.label,
|
|
533
|
+
resetsAt,
|
|
534
|
+
continued: false,
|
|
535
|
+
continuedIn: null,
|
|
536
|
+
toFamily: null,
|
|
537
|
+
detail: null,
|
|
538
|
+
at: new Date(now).toISOString(),
|
|
539
|
+
};
|
|
540
|
+
const reason = problem.kind;
|
|
541
|
+
if (!this.switchGuard.allows(agentId, now)) {
|
|
542
|
+
console.warn(`[ZeroSub] not switching ${agentId} again: it changed accounts ${this.switchGuard.limit} times in 10 minutes`);
|
|
543
|
+
// Say so once, so the user knows to pick an account rather than wait.
|
|
544
|
+
if (now - (this.guardNoticeAt.get(agentId) ?? 0) > this.switchGuard.windowMs) {
|
|
545
|
+
this.guardNoticeAt.set(agentId, now);
|
|
546
|
+
await this.appendRow(paseo, agentId, {
|
|
547
|
+
...base,
|
|
548
|
+
to: account.label,
|
|
549
|
+
reason,
|
|
550
|
+
outcome: "stayed",
|
|
551
|
+
detail: `It changed accounts ${this.switchGuard.limit} times in 10 minutes, so ZeroSub stopped switching it for now. Pick an account from the account button to carry on.`,
|
|
552
|
+
});
|
|
553
|
+
}
|
|
554
|
+
return;
|
|
555
|
+
}
|
|
556
|
+
const next = mostAvailable(latest, family, (id) => this.usage.get(id), now, new Set([account.id]));
|
|
557
|
+
if (!next) {
|
|
558
|
+
if (problem.kind === "limit" && problem.hit.kind === "window" && this.prefs.autoRedeem) {
|
|
559
|
+
// Opt-in: every account is out, so spend a banked reset rather than stop.
|
|
560
|
+
const reply = await this.redeemOn(account, true);
|
|
561
|
+
if (reply.outcome === "reset") {
|
|
562
|
+
this.switchGuard.note(agentId, now);
|
|
563
|
+
const continued = this.prefs.autoContinue;
|
|
564
|
+
await this.appendRow(paseo, agentId, {
|
|
565
|
+
...base,
|
|
566
|
+
to: account.label,
|
|
567
|
+
reason: "limit",
|
|
568
|
+
continued,
|
|
569
|
+
outcome: "reset",
|
|
570
|
+
detail: reply.message,
|
|
571
|
+
});
|
|
572
|
+
if (continued) {
|
|
573
|
+
await paseo.agents
|
|
574
|
+
.ref(agentId)
|
|
575
|
+
.send(this.prefs.continuePrompt)
|
|
576
|
+
.catch((error: unknown) => log(`could not continue ${agentId}`, error));
|
|
577
|
+
}
|
|
578
|
+
return;
|
|
579
|
+
}
|
|
580
|
+
if (reply.outcome === "not_limited") {
|
|
581
|
+
// Refilled since this turn stopped (another host sharing the account, or the user, spent
|
|
582
|
+
// a reset), so carry on here without spending a second one.
|
|
583
|
+
console.log(`[ZeroSub] ${account.label} has room again; ${agentId} carries on where it is`);
|
|
584
|
+
this.switchGuard.note(agentId, now);
|
|
585
|
+
await this.afterReset(account.id, reply.left);
|
|
586
|
+
if (this.prefs.autoContinue) {
|
|
587
|
+
await paseo.agents
|
|
588
|
+
.ref(agentId)
|
|
589
|
+
.send(this.prefs.continuePrompt)
|
|
590
|
+
.catch((error: unknown) => log(`could not continue ${agentId}`, error));
|
|
591
|
+
}
|
|
592
|
+
return;
|
|
593
|
+
}
|
|
594
|
+
console.log(`[ZeroSub] no automatic reset for ${account.label}: ${reply.message}`);
|
|
595
|
+
}
|
|
596
|
+
if (reason !== "limit") return;
|
|
597
|
+
let detail: string | null = null;
|
|
598
|
+
if (this.prefs.forkOtherProvider) {
|
|
599
|
+
// Opt-in: every account of this provider is out, so carry on with the other provider.
|
|
600
|
+
const result = await this.forkToOtherProvider(paseo, agentId, family, timeline, "auto").catch((error: unknown) => ({
|
|
601
|
+
skipped: `Couldn't continue on ${FAMILY_LABEL[OTHER_FAMILY[family]]}: ${describe(error)}`,
|
|
602
|
+
}));
|
|
603
|
+
if ("fork" in result) {
|
|
604
|
+
this.switchGuard.note(agentId, now);
|
|
605
|
+
await this.appendRow(paseo, agentId, {
|
|
606
|
+
...base,
|
|
607
|
+
to: result.account.label,
|
|
608
|
+
toFamily: result.family,
|
|
609
|
+
reason: "exhausted",
|
|
610
|
+
continued: true,
|
|
611
|
+
continuedIn: result.fork,
|
|
612
|
+
outcome: "continued",
|
|
613
|
+
});
|
|
614
|
+
return;
|
|
615
|
+
}
|
|
616
|
+
console.log(`[ZeroSub] not continuing ${agentId} on ${FAMILY_LABEL[OTHER_FAMILY[family]]}: ${result.skipped}`);
|
|
617
|
+
detail = result.skipped;
|
|
618
|
+
} else if (mostAvailable(latest, OTHER_FAMILY[family], (id) => this.usage.get(id), now, new Set())) {
|
|
619
|
+
detail = `Or continue on ${FAMILY_LABEL[OTHER_FAMILY[family]]} in a new agent from the account button.`;
|
|
620
|
+
}
|
|
621
|
+
await this.appendRow(paseo, agentId, { ...base, to: account.label, reason: "exhausted", outcome: "stayed", detail });
|
|
622
|
+
return;
|
|
623
|
+
}
|
|
624
|
+
|
|
625
|
+
if (adapter.portable) {
|
|
626
|
+
await this.store.update((draft) => {
|
|
627
|
+
draft.bindings[agentId] = { accountId: next.id, source: "auto", at: new Date(now).toISOString() };
|
|
628
|
+
});
|
|
629
|
+
this.switchGuard.note(agentId, now);
|
|
630
|
+
const outcome = await this.reopenAgent(paseo, agentId, null, true);
|
|
631
|
+
const continued = outcome === "reopened" && this.prefs.autoContinue;
|
|
632
|
+
const row = await this.landed(
|
|
633
|
+
{ ...base, to: next.label, reason, continued, outcome: outcome === "reopened" ? "switched" : "pending" },
|
|
634
|
+
agentId,
|
|
635
|
+
);
|
|
636
|
+
await this.appendRow(paseo, agentId, row);
|
|
637
|
+
if (continued) {
|
|
638
|
+
await paseo.agents
|
|
639
|
+
.ref(agentId)
|
|
640
|
+
.send(this.prefs.continuePrompt)
|
|
641
|
+
.catch((error: unknown) => log(`could not continue ${agentId}`, error));
|
|
642
|
+
}
|
|
643
|
+
return;
|
|
644
|
+
}
|
|
645
|
+
|
|
646
|
+
// A ChatGPT thread can't move to another account; carry the work on in a new agent there.
|
|
647
|
+
if (!this.prefs.autoContinue) {
|
|
648
|
+
await this.appendRow(paseo, agentId, {
|
|
649
|
+
...base,
|
|
650
|
+
to: next.label,
|
|
651
|
+
reason,
|
|
652
|
+
outcome: "stayed",
|
|
653
|
+
detail: `New ChatGPT agents will use ${next.label}.`,
|
|
654
|
+
});
|
|
655
|
+
return;
|
|
656
|
+
}
|
|
657
|
+
const why =
|
|
658
|
+
reason === "limit"
|
|
659
|
+
? `its ChatGPT account (${account.label}) reached its usage limit`
|
|
660
|
+
: `its ChatGPT account (${account.label}) was signed out`;
|
|
661
|
+
try {
|
|
662
|
+
const continuation = await this.continueElsewhere(paseo, agentId, next, why, timeline, "auto");
|
|
663
|
+
this.switchGuard.note(agentId, now);
|
|
664
|
+
await this.appendRow(paseo, agentId, {
|
|
665
|
+
...base,
|
|
666
|
+
to: next.label,
|
|
667
|
+
reason,
|
|
668
|
+
continued: true,
|
|
669
|
+
continuedIn: continuation,
|
|
670
|
+
outcome: "continued",
|
|
671
|
+
});
|
|
672
|
+
} catch (error) {
|
|
673
|
+
log(`could not continue ${agentId} on ${next.label}`, error);
|
|
674
|
+
await this.appendRow(paseo, agentId, {
|
|
675
|
+
...base,
|
|
676
|
+
to: next.label,
|
|
677
|
+
reason,
|
|
678
|
+
outcome: "stayed",
|
|
679
|
+
detail: `Couldn't start a new agent on ${next.label}: ${describe(error)}`,
|
|
680
|
+
});
|
|
681
|
+
}
|
|
682
|
+
}
|
|
683
|
+
|
|
684
|
+
private async markLimited(accountId: string, until: string, kind: LimitKind): Promise<void> {
|
|
685
|
+
await this.store.update((draft) => {
|
|
686
|
+
const account = findAccount(draft, accountId);
|
|
687
|
+
if (!account) return;
|
|
688
|
+
account.limitedUntil = until;
|
|
689
|
+
account.limitKind = kind;
|
|
690
|
+
account.limitedAt = new Date().toISOString();
|
|
691
|
+
});
|
|
692
|
+
}
|
|
693
|
+
|
|
694
|
+
// ------------------------------------------------------------------ banked resets
|
|
695
|
+
|
|
696
|
+
private recentlyRedeemed(accountId: string): boolean {
|
|
697
|
+
return Date.now() - (this.lastRedeemAt.get(accountId) ?? 0) < RESET_GRACE_MS;
|
|
698
|
+
}
|
|
699
|
+
|
|
700
|
+
/**
|
|
701
|
+
* Spends one banked reset on `account`, one attempt at a time per account. `automatic` use shares
|
|
702
|
+
* a reset this host just spent across concurrent failovers, and spends one only while the provider
|
|
703
|
+
* still sees the limit, so hosts sharing the account can't spend two on the same limit.
|
|
704
|
+
*/
|
|
705
|
+
private redeemOn(account: StoredAccount, automatic: boolean): Promise<RedeemReply> {
|
|
706
|
+
let lock = this.redeemLocks.get(account.id);
|
|
707
|
+
if (!lock) this.redeemLocks.set(account.id, (lock = new Mutex()));
|
|
708
|
+
return lock.run(async () => {
|
|
709
|
+
if (automatic && this.recentlyRedeemed(account.id)) {
|
|
710
|
+
return { outcome: "reset", message: "A reset was just used on this account.", left: null };
|
|
711
|
+
}
|
|
712
|
+
const reply = await this.adapters[account.family]
|
|
713
|
+
.redeemReset(account.home, { onlyAtLimit: automatic })
|
|
714
|
+
.catch((error: unknown): RedeemReply => ({ outcome: "error", message: describe(error), left: null }));
|
|
715
|
+
console.log(`[ZeroSub] banked reset on ${account.label}: ${reply.outcome}`);
|
|
716
|
+
if (reply.outcome === "reset") {
|
|
717
|
+
this.lastRedeemAt.set(account.id, Date.now());
|
|
718
|
+
await this.afterReset(account.id, reply.left);
|
|
719
|
+
} else if (reply.left !== null) {
|
|
720
|
+
this.updateResetCount(account.id, reply.left);
|
|
721
|
+
}
|
|
722
|
+
return reply;
|
|
723
|
+
});
|
|
724
|
+
}
|
|
725
|
+
|
|
726
|
+
private async afterReset(accountId: string, left: number | null): Promise<void> {
|
|
727
|
+
await this.store.update((draft) => {
|
|
728
|
+
const account = findAccount(draft, accountId);
|
|
729
|
+
if (!account) return;
|
|
730
|
+
account.limitedUntil = null;
|
|
731
|
+
account.limitKind = null;
|
|
732
|
+
});
|
|
733
|
+
if (left !== null) this.updateResetCount(accountId, left);
|
|
734
|
+
// Give the provider a moment to settle before reading the refilled usage.
|
|
735
|
+
setTimeout(() => {
|
|
736
|
+
this.usageAttemptAt.delete(accountId);
|
|
737
|
+
void this.refreshUsage(accountId, true).catch(() => undefined);
|
|
738
|
+
}, 5_000).unref?.();
|
|
739
|
+
}
|
|
740
|
+
|
|
741
|
+
private updateResetCount(accountId: string, left: number): void {
|
|
742
|
+
const usage = this.usage.get(accountId);
|
|
743
|
+
if (!usage?.resets) return;
|
|
744
|
+
this.setUsage(accountId, { ...usage, resets: left > 0 ? { ...usage.resets, available: left } : null });
|
|
745
|
+
}
|
|
746
|
+
|
|
747
|
+
/** A user-requested reset, optionally resuming the agent that was stopped by the limit. */
|
|
748
|
+
async redeem(paseo: PaseoApi, accountId: string, agentId?: string): Promise<RedeemResult> {
|
|
749
|
+
this.attach(paseo);
|
|
750
|
+
const account = findAccount(await this.store.read(), accountId);
|
|
751
|
+
if (!account) throw new Error("That account no longer exists.");
|
|
752
|
+
if (!account.signedIn) throw new Error(`${account.label} is signed out. Sign it in first.`);
|
|
753
|
+
const reply = await this.redeemOn(account, false);
|
|
754
|
+
let continued = false;
|
|
755
|
+
if (reply.outcome === "reset" && agentId) {
|
|
756
|
+
continued = await this.continueAfterReset(paseo, agentId, account, reply.message).catch(() => false);
|
|
757
|
+
}
|
|
758
|
+
return { ...reply, continued };
|
|
759
|
+
}
|
|
760
|
+
|
|
761
|
+
private async continueAfterReset(paseo: PaseoApi, agentId: string, account: StoredAccount, detail: string): Promise<boolean> {
|
|
762
|
+
if (!this.prefs.autoContinue) return false;
|
|
763
|
+
const info = await agentInfo(paseo, agentId);
|
|
764
|
+
if (!info || info.archived || info.status !== "idle") return false;
|
|
765
|
+
if (this.runningOn(await this.store.read(), agentId, account.family) !== account.id) return false;
|
|
766
|
+
// Only resume an agent that this limit actually stopped.
|
|
767
|
+
if (!(await this.lastTurnHitLimit(paseo, agentId, account.family))) return false;
|
|
768
|
+
const at = new Date().toISOString();
|
|
769
|
+
await this.appendRow(paseo, agentId, {
|
|
770
|
+
family: account.family,
|
|
771
|
+
from: account.label,
|
|
772
|
+
to: account.label,
|
|
773
|
+
reason: "limit",
|
|
774
|
+
resetsAt: null,
|
|
775
|
+
continued: true,
|
|
776
|
+
continuedIn: null,
|
|
777
|
+
toFamily: null,
|
|
778
|
+
outcome: "reset",
|
|
779
|
+
detail,
|
|
780
|
+
at,
|
|
781
|
+
});
|
|
782
|
+
await paseo.agents.ref(agentId).send(this.prefs.continuePrompt);
|
|
783
|
+
return true;
|
|
784
|
+
}
|
|
785
|
+
|
|
786
|
+
/**
|
|
787
|
+
* The account an agent's live session really runs on. ZeroSub records every session it routes; one
|
|
788
|
+
* it never routed (opened before ZeroSub was installed, or while it was stopped) has no account
|
|
789
|
+
* override, so it runs on the CLI login.
|
|
790
|
+
*/
|
|
791
|
+
private runningOn(state: StoredState, agentId: string, family: Family): string | undefined {
|
|
792
|
+
return state.sessions[agentId]?.accountId ?? mainAccount(state, family)?.id;
|
|
793
|
+
}
|
|
794
|
+
|
|
795
|
+
/** The reset time of the window that is full, from the freshest live usage reading. */
|
|
796
|
+
private resetFromUsage(accountId: string): string | null {
|
|
797
|
+
const usage = this.usage.get(accountId);
|
|
798
|
+
if (!usage || usage.cached) return null;
|
|
799
|
+
const full = usage.windows.filter((window) => window.usedPercent >= 99 && window.resetsAt);
|
|
800
|
+
full.sort((a, b) => Date.parse(b.resetsAt ?? "") - Date.parse(a.resetsAt ?? ""));
|
|
801
|
+
return full[0]?.resetsAt ?? null;
|
|
802
|
+
}
|
|
803
|
+
|
|
804
|
+
/** Did this agent's own last turn end on a limit? Then its own failover (with a follow-up) handles it. */
|
|
805
|
+
private async lastTurnHitLimit(paseo: PaseoApi, agentId: string, family: Family): Promise<boolean> {
|
|
806
|
+
try {
|
|
807
|
+
const page = await paseo.agents.ref(agentId).timeline.refetch({ direction: "tail", limit: 40 });
|
|
808
|
+
const timeline = page.entries.map((entry) => entry.item);
|
|
809
|
+
return this.adapters[family].detectLimit({ outcome: { kind: "completed" }, timeline }) !== null;
|
|
810
|
+
} catch {
|
|
811
|
+
return true; // When unsure, leave it alone.
|
|
812
|
+
}
|
|
813
|
+
}
|
|
814
|
+
|
|
815
|
+
/** Idle agents still on an exhausted account would fail on their next turn; move them now. */
|
|
816
|
+
private async moveIdleAgentsOff(
|
|
817
|
+
paseo: PaseoApi,
|
|
818
|
+
accountId: string,
|
|
819
|
+
family: Family,
|
|
820
|
+
except: string,
|
|
821
|
+
reason: "limit" | "signed_out",
|
|
822
|
+
): Promise<void> {
|
|
823
|
+
const state = await this.store.read();
|
|
824
|
+
const from = findAccount(state, accountId);
|
|
825
|
+
const families = await this.families.resolve(paseo);
|
|
826
|
+
const candidates = (await this.cachedAgents(paseo))
|
|
827
|
+
.filter(
|
|
828
|
+
(agent) =>
|
|
829
|
+
agent.id !== except &&
|
|
830
|
+
!agent.archived &&
|
|
831
|
+
families[agent.provider] === family &&
|
|
832
|
+
this.runningOn(state, agent.id, family) === accountId,
|
|
833
|
+
)
|
|
834
|
+
.map((agent) => agent.id);
|
|
835
|
+
for (const agentId of candidates) {
|
|
836
|
+
if (this.switching.has(agentId) || !this.switchGuard.allows(agentId, Date.now())) continue;
|
|
837
|
+
const info = await agentInfo(paseo, agentId);
|
|
838
|
+
if (!info || info.archived || info.status !== "idle") continue;
|
|
839
|
+
if (await this.lastTurnHitLimit(paseo, agentId, family)) continue;
|
|
840
|
+
this.switching.add(agentId);
|
|
841
|
+
try {
|
|
842
|
+
const now = Date.now();
|
|
843
|
+
const latest = await this.store.read();
|
|
844
|
+
if (this.runningOn(latest, agentId, family) !== accountId) continue;
|
|
845
|
+
const next = mostAvailable(latest, family, (id) => this.usage.get(id), now, new Set([accountId]));
|
|
846
|
+
if (!next) return;
|
|
847
|
+
await this.store.update((draft) => {
|
|
848
|
+
draft.bindings[agentId] = { accountId: next.id, source: "auto", at: new Date(now).toISOString() };
|
|
849
|
+
});
|
|
850
|
+
this.switchGuard.note(agentId, now);
|
|
851
|
+
if ((await this.reopenAgent(paseo, agentId)) !== "reopened") continue;
|
|
852
|
+
const row: SwitchRow = {
|
|
853
|
+
family,
|
|
854
|
+
from: from?.label ?? null,
|
|
855
|
+
to: next.label,
|
|
856
|
+
reason,
|
|
857
|
+
resetsAt: findAccount(latest, accountId)?.limitedUntil ?? null,
|
|
858
|
+
continued: false,
|
|
859
|
+
continuedIn: null,
|
|
860
|
+
toFamily: null,
|
|
861
|
+
outcome: "switched",
|
|
862
|
+
detail: null,
|
|
863
|
+
at: new Date(now).toISOString(),
|
|
864
|
+
};
|
|
865
|
+
await this.appendRow(paseo, agentId, await this.landed(row, agentId));
|
|
866
|
+
} finally {
|
|
867
|
+
this.switching.delete(agentId);
|
|
868
|
+
}
|
|
869
|
+
}
|
|
870
|
+
}
|
|
871
|
+
|
|
872
|
+
/**
|
|
873
|
+
* Carries an agent's work on in a new agent on the other provider (Claude ↔ ChatGPT), for when
|
|
874
|
+
* every account of its own provider is out. The new agent gets the conversation so far and a mode
|
|
875
|
+
* no more permissive than the original's; the original stays as it was.
|
|
876
|
+
*/
|
|
877
|
+
private async forkToOtherProvider(
|
|
878
|
+
paseo: PaseoApi,
|
|
879
|
+
agentId: string,
|
|
880
|
+
family: Family,
|
|
881
|
+
timeline: readonly AgentTimelineItem[] | undefined,
|
|
882
|
+
source: "auto" | "user",
|
|
883
|
+
): Promise<{ fork: Continuation; account: StoredAccount; family: Family } | { skipped: string }> {
|
|
884
|
+
const other = OTHER_FAMILY[family];
|
|
885
|
+
const name = FAMILY_LABEL[other];
|
|
886
|
+
const families = await this.families.resolve(paseo);
|
|
887
|
+
const state = await this.store.read();
|
|
888
|
+
// Prompting the original again while it's still out mustn't start a second copy of the work.
|
|
889
|
+
const earlier = (await listAgents(paseo, false)).agents.find(
|
|
890
|
+
(agent) => agent.continuedFrom === agentId && families[agent.provider] === other,
|
|
891
|
+
);
|
|
892
|
+
const earlierAccount = earlier && (findAccount(state, state.bindings[earlier.id]?.accountId) ?? mainAccount(state, other));
|
|
893
|
+
if (earlier && earlierAccount) {
|
|
894
|
+
return { fork: { agentId: earlier.id, title: earlier.title ?? `${name} agent` }, account: earlierAccount, family: other };
|
|
895
|
+
}
|
|
896
|
+
|
|
897
|
+
if (this.availability.get(other)?.ok === false) return { skipped: `${PROVIDER_NAME[other]} isn't installed where the daemon runs.` };
|
|
898
|
+
const provider = families[other] === other ? other : Object.keys(families).find((id) => families[id] === other);
|
|
899
|
+
const available = provider
|
|
900
|
+
? (await paseo.providers.listAvailable()).providers?.some((entry) => entry.provider === provider && entry.available)
|
|
901
|
+
: false;
|
|
902
|
+
if (!provider || !available) return { skipped: `${name} isn't available in Paseo on this host.` };
|
|
903
|
+
const account = mostAvailable(state, other, (id) => this.usage.get(id), Date.now(), new Set());
|
|
904
|
+
if (!account) return { skipped: `Every ${name} account is at its limit too.` };
|
|
905
|
+
|
|
906
|
+
const original = (await paseo.agents.ref(agentId).refresh())?.agent;
|
|
907
|
+
if (!original) throw new Error("That agent is no longer available.");
|
|
908
|
+
const [sourceModes, targetModes] = await Promise.all([
|
|
909
|
+
paseo.providers.listModes(original.provider).then((result) => result.modes ?? []),
|
|
910
|
+
paseo.providers.listModes(provider).then((result) => result.modes ?? []),
|
|
911
|
+
]);
|
|
912
|
+
const modeId = equivalentMode(sourceModes, original.currentModeId, targetModes);
|
|
913
|
+
if (!modeId) {
|
|
914
|
+
const current = sourceModes.find((mode) => mode.id === original.currentModeId)?.label;
|
|
915
|
+
return {
|
|
916
|
+
skipped: `${name} has no mode as careful as this agent's${current ? ` (“${current}”)` : ""}, so ZeroSub didn't continue it there.`,
|
|
917
|
+
};
|
|
918
|
+
}
|
|
919
|
+
|
|
920
|
+
const fork = await continueInNewAgent({
|
|
921
|
+
paseo,
|
|
922
|
+
sourceAgentId: agentId,
|
|
923
|
+
timeline,
|
|
924
|
+
why: source === "auto" ? `every ${FAMILY_LABEL[family]} account reached its usage limit` : `the work was moved to ${name}`,
|
|
925
|
+
previous: PROVIDER_NAME[family],
|
|
926
|
+
target: { provider, label: name, modeId },
|
|
927
|
+
bind: async (newAgentId) => {
|
|
928
|
+
await this.store.update((draft) => {
|
|
929
|
+
draft.bindings[newAgentId] = {
|
|
930
|
+
accountId: account.id,
|
|
931
|
+
source: source === "user" ? "user" : this.adapters[other].portable ? "auto" : "thread",
|
|
932
|
+
at: new Date().toISOString(),
|
|
933
|
+
};
|
|
934
|
+
});
|
|
935
|
+
},
|
|
936
|
+
});
|
|
937
|
+
console.log(`[ZeroSub] ${agentId} continues on ${name} (${account.label}) in ${fork.agentId}`);
|
|
938
|
+
return { fork, account, family: other };
|
|
939
|
+
}
|
|
940
|
+
|
|
941
|
+
/** "Continue on …" from an agent's account button: the same fork, asked for by the user. */
|
|
942
|
+
async forkAgent(paseo: PaseoApi, agentId: string): Promise<Continuation> {
|
|
943
|
+
this.attach(paseo);
|
|
944
|
+
const info = await agentInfo(paseo, agentId);
|
|
945
|
+
if (!info || info.archived) throw new Error("That agent is no longer available.");
|
|
946
|
+
const family = (await this.families.resolve(paseo))[info.provider];
|
|
947
|
+
if (!family) throw new Error(`${info.provider} agents don't use Claude or ChatGPT subscription accounts.`);
|
|
948
|
+
if (info.status === "running" || info.status === "initializing") {
|
|
949
|
+
throw new Error("This agent is working right now. Wait for its turn to finish, then continue it elsewhere.");
|
|
950
|
+
}
|
|
951
|
+
const result = await this.forkToOtherProvider(paseo, agentId, family, undefined, "user");
|
|
952
|
+
if ("skipped" in result) throw new Error(result.skipped);
|
|
953
|
+
const state = await this.store.read();
|
|
954
|
+
await this.appendRow(paseo, agentId, {
|
|
955
|
+
family,
|
|
956
|
+
from: findAccount(state, this.runningOn(state, agentId, family))?.label ?? null,
|
|
957
|
+
to: result.account.label,
|
|
958
|
+
reason: "manual",
|
|
959
|
+
resetsAt: null,
|
|
960
|
+
continued: true,
|
|
961
|
+
continuedIn: result.fork,
|
|
962
|
+
toFamily: result.family,
|
|
963
|
+
outcome: "continued",
|
|
964
|
+
detail: null,
|
|
965
|
+
at: new Date().toISOString(),
|
|
966
|
+
});
|
|
967
|
+
return result.fork;
|
|
968
|
+
}
|
|
969
|
+
|
|
970
|
+
private async continueElsewhere(
|
|
971
|
+
paseo: PaseoApi,
|
|
972
|
+
agentId: string,
|
|
973
|
+
target: StoredAccount,
|
|
974
|
+
why: string,
|
|
975
|
+
timeline: readonly AgentTimelineItem[] | undefined,
|
|
976
|
+
source: "auto" | "user",
|
|
977
|
+
): Promise<Continuation> {
|
|
978
|
+
return continueInNewAgent({
|
|
979
|
+
paseo,
|
|
980
|
+
sourceAgentId: agentId,
|
|
981
|
+
timeline,
|
|
982
|
+
why,
|
|
983
|
+
bind: async (newAgentId) => {
|
|
984
|
+
await this.store.update((draft) => {
|
|
985
|
+
draft.bindings[newAgentId] = {
|
|
986
|
+
accountId: target.id,
|
|
987
|
+
source: source === "user" ? "user" : "thread",
|
|
988
|
+
at: new Date().toISOString(),
|
|
989
|
+
};
|
|
990
|
+
});
|
|
991
|
+
},
|
|
992
|
+
});
|
|
993
|
+
}
|
|
994
|
+
|
|
995
|
+
// ------------------------------------------------------------------ reopening sessions
|
|
996
|
+
|
|
997
|
+
/** Where routing would put this agent's next session, including skipping exhausted accounts. */
|
|
998
|
+
private targetFor(state: StoredState, agentId: string, family: Family): string | undefined {
|
|
999
|
+
return chooseAccount(state, {
|
|
1000
|
+
agentId,
|
|
1001
|
+
family,
|
|
1002
|
+
reason: "refresh",
|
|
1003
|
+
now: Date.now(),
|
|
1004
|
+
autoSwitch: this.prefs.autoSwitch,
|
|
1005
|
+
balanceNewAgents: false,
|
|
1006
|
+
portable: this.adapters[family].portable,
|
|
1007
|
+
usageOf: (id) => this.usage.get(id),
|
|
1008
|
+
})?.account.id;
|
|
1009
|
+
}
|
|
1010
|
+
|
|
1011
|
+
/** Names the account the agent actually reopened on in its timeline note. */
|
|
1012
|
+
private async landed(row: SwitchRow, agentId: string): Promise<SwitchRow> {
|
|
1013
|
+
const state = await this.store.read();
|
|
1014
|
+
const label = findAccount(state, state.sessions[agentId]?.accountId)?.label;
|
|
1015
|
+
return label && row.outcome === "switched" ? { ...row, to: label } : row;
|
|
1016
|
+
}
|
|
1017
|
+
|
|
1018
|
+
/**
|
|
1019
|
+
* Reopens an idle agent now, or defers a busy one until its turn ends. `settle` waits a moment for
|
|
1020
|
+
* an agent whose turn just ended to report idle, since nothing else would reopen it later.
|
|
1021
|
+
*/
|
|
1022
|
+
private async reopenAgent(
|
|
1023
|
+
paseo: PaseoApi,
|
|
1024
|
+
agentId: string,
|
|
1025
|
+
row: SwitchRow | null = null,
|
|
1026
|
+
settle = false,
|
|
1027
|
+
): Promise<ReopenOutcome> {
|
|
1028
|
+
let info = await agentInfo(paseo, agentId);
|
|
1029
|
+
for (let attempt = 0; settle && info && attempt < 20 && (info.status === "running" || info.status === "initializing"); attempt += 1) {
|
|
1030
|
+
await delay(300);
|
|
1031
|
+
info = await agentInfo(paseo, agentId);
|
|
1032
|
+
}
|
|
1033
|
+
if (!info) return "closed";
|
|
1034
|
+
if (info.status === "running" || info.status === "initializing") {
|
|
1035
|
+
this.deferred.set(agentId, row);
|
|
1036
|
+
return "deferred";
|
|
1037
|
+
}
|
|
1038
|
+
// Reloading an archived agent would unarchive it; a closed one routes itself when it next opens.
|
|
1039
|
+
if (info.archived || info.status === "closed") return "closed";
|
|
1040
|
+
const family = (await this.families.resolve(paseo))[info.provider];
|
|
1041
|
+
if (family && !this.adapters[family].portable && info.hasHistory) {
|
|
1042
|
+
// The thread gained history while waiting, so it can no longer change accounts: keep it put.
|
|
1043
|
+
const state = await this.store.read();
|
|
1044
|
+
const current = this.runningOn(state, agentId, family);
|
|
1045
|
+
if (current && findAccount(state, current)) {
|
|
1046
|
+
await this.store.update((draft) => {
|
|
1047
|
+
draft.bindings[agentId] = { accountId: current, source: "thread", at: new Date().toISOString() };
|
|
1048
|
+
});
|
|
1049
|
+
}
|
|
1050
|
+
return "closed";
|
|
1051
|
+
}
|
|
1052
|
+
const result = await this.reopener.reopen(agentId);
|
|
1053
|
+
if (!result.ok) {
|
|
1054
|
+
console.warn(`[ZeroSub] could not reopen ${agentId}: ${result.error}`);
|
|
1055
|
+
return "failed";
|
|
1056
|
+
}
|
|
1057
|
+
return "reopened";
|
|
1058
|
+
}
|
|
1059
|
+
|
|
1060
|
+
/**
|
|
1061
|
+
* Reopens every live agent whose session runs on a different account than it is routed to now,
|
|
1062
|
+
* and notes the switch in its timeline. Busy agents switch (and get their note) after their turn.
|
|
1063
|
+
*/
|
|
1064
|
+
private async reconcile(
|
|
1065
|
+
paseo: PaseoApi,
|
|
1066
|
+
reason: SwitchRow["reason"],
|
|
1067
|
+
agentIds?: readonly string[],
|
|
1068
|
+
fromLabels: ReadonlyMap<string, string> = new Map(),
|
|
1069
|
+
): Promise<ReopenSummary> {
|
|
1070
|
+
const summary = emptySummary();
|
|
1071
|
+
const state = await this.store.read();
|
|
1072
|
+
const families = await this.families.resolve(paseo);
|
|
1073
|
+
for (const agent of await this.liveAgents(paseo, agentIds)) {
|
|
1074
|
+
const agentId = agent.id;
|
|
1075
|
+
const family = families[agent.provider];
|
|
1076
|
+
if (!family || this.switching.has(agentId)) continue;
|
|
1077
|
+
const current = this.runningOn(state, agentId, family);
|
|
1078
|
+
const target = this.targetFor(state, agentId, family);
|
|
1079
|
+
if (!current || !target || target === current) continue;
|
|
1080
|
+
const row: SwitchRow = {
|
|
1081
|
+
family,
|
|
1082
|
+
from: findAccount(state, current)?.label ?? fromLabels.get(current) ?? null,
|
|
1083
|
+
to: findAccount(state, target)?.label ?? target,
|
|
1084
|
+
reason,
|
|
1085
|
+
resetsAt: null,
|
|
1086
|
+
continued: false,
|
|
1087
|
+
continuedIn: null,
|
|
1088
|
+
toFamily: null,
|
|
1089
|
+
outcome: "switched",
|
|
1090
|
+
detail: null,
|
|
1091
|
+
at: new Date().toISOString(),
|
|
1092
|
+
};
|
|
1093
|
+
const outcome = await this.reopenAgent(paseo, agentId, row);
|
|
1094
|
+
if (outcome === "reopened") {
|
|
1095
|
+
summary.reopened.push(agentId);
|
|
1096
|
+
await this.appendRow(paseo, agentId, await this.landed(row, agentId));
|
|
1097
|
+
} else if (outcome === "deferred") summary.deferred.push(agentId);
|
|
1098
|
+
else if (outcome === "failed") summary.failed.push({ agentId, error: "Reload failed" });
|
|
1099
|
+
}
|
|
1100
|
+
return summary;
|
|
1101
|
+
}
|
|
1102
|
+
|
|
1103
|
+
private async appendRow(paseo: PaseoApi, agentId: string, row: SwitchRow): Promise<void> {
|
|
1104
|
+
try {
|
|
1105
|
+
await paseo.agents.ref(agentId).timeline.append({
|
|
1106
|
+
type: "plugin",
|
|
1107
|
+
id: `switch-${Date.parse(row.at) || Date.now()}`,
|
|
1108
|
+
kind: SWITCH_ROW_KIND,
|
|
1109
|
+
version: SWITCH_ROW_VERSION,
|
|
1110
|
+
data: row,
|
|
1111
|
+
});
|
|
1112
|
+
} catch (error) {
|
|
1113
|
+
log(`could not add a timeline note to ${agentId}`, error);
|
|
1114
|
+
}
|
|
1115
|
+
}
|
|
1116
|
+
|
|
1117
|
+
// ------------------------------------------------------------------ usage
|
|
1118
|
+
|
|
1119
|
+
/** `renewLogin` lets the CLI refresh an expired sign-in first (explicit refreshes only: it's slow). */
|
|
1120
|
+
refreshUsage(accountId: string, force = false, renewLogin = false): Promise<void> {
|
|
1121
|
+
const pending = this.usageInFlight.get(accountId);
|
|
1122
|
+
if (pending) return pending;
|
|
1123
|
+
const now = Date.now();
|
|
1124
|
+
// The provider asked us to wait; asking sooner would only be refused again.
|
|
1125
|
+
if (now < (this.usageRetryAt.get(accountId) ?? 0)) return Promise.resolve();
|
|
1126
|
+
const since = now - (this.usageAttemptAt.get(accountId) ?? 0);
|
|
1127
|
+
const task = (async () => {
|
|
1128
|
+
const account = findAccount(await this.store.read(), accountId);
|
|
1129
|
+
if (!account) return;
|
|
1130
|
+
const spacing = this.adapters[account.family].usageSpacingMs;
|
|
1131
|
+
if (since < (force ? spacing : Math.max(spacing, 60_000))) return;
|
|
1132
|
+
this.usageAttemptAt.set(accountId, Date.now());
|
|
1133
|
+
const { retryAt, ...usage } = await this.adapters[account.family]
|
|
1134
|
+
.usage(account.home, { renewLogin })
|
|
1135
|
+
.catch(
|
|
1136
|
+
(error: unknown): UsageRead => ({ fetchedAt: new Date().toISOString(), windows: [], error: describe(error), cached: false, resets: null }),
|
|
1137
|
+
);
|
|
1138
|
+
if (retryAt) this.usageRetryAt.set(accountId, retryAt);
|
|
1139
|
+
else this.usageRetryAt.delete(accountId);
|
|
1140
|
+
this.setUsage(accountId, mergeUsage(this.usage.get(accountId), usage));
|
|
1141
|
+
// Only a live reading may change an account's limit state.
|
|
1142
|
+
if (usage.windows.length === 0 || usage.error || usage.cached) return;
|
|
1143
|
+
const now = Date.now();
|
|
1144
|
+
const full = usage.windows.find((window) => window.usedPercent >= 100 && window.resetsAt);
|
|
1145
|
+
if (full && !isLimited(account, now)) {
|
|
1146
|
+
await this.markLimited(accountId, full.resetsAt ?? new Date(now + WINDOW_LIMIT_MS).toISOString(), "window");
|
|
1147
|
+
return;
|
|
1148
|
+
}
|
|
1149
|
+
// A window limit clears once usage shows room again. Budget limits never appear in usage
|
|
1150
|
+
// windows, and a fresh limit is trusted for a while (it may be on a window we can't see).
|
|
1151
|
+
const settled = account.limitedAt ? now - Date.parse(account.limitedAt) > LIMIT_TRUST_MS : true;
|
|
1152
|
+
const roomy = Math.max(...usage.windows.map((window) => window.usedPercent)) < 90;
|
|
1153
|
+
if (!full && account.limitedUntil && account.limitKind === "window" && settled && roomy) {
|
|
1154
|
+
await this.store.update((draft) => {
|
|
1155
|
+
const target = findAccount(draft, accountId);
|
|
1156
|
+
if (!target) return;
|
|
1157
|
+
target.limitedUntil = null;
|
|
1158
|
+
target.limitKind = null;
|
|
1159
|
+
});
|
|
1160
|
+
}
|
|
1161
|
+
})().finally(() => this.usageInFlight.delete(accountId));
|
|
1162
|
+
this.usageInFlight.set(accountId, task);
|
|
1163
|
+
return task;
|
|
1164
|
+
}
|
|
1165
|
+
|
|
1166
|
+
/** Records a reading and saves the readings shortly after, so a restart shows them straight away. */
|
|
1167
|
+
private setUsage(accountId: string, usage: Usage | null): void {
|
|
1168
|
+
if (usage) this.usage.set(accountId, usage);
|
|
1169
|
+
else this.usage.delete(accountId);
|
|
1170
|
+
if (this.usageSave) return;
|
|
1171
|
+
this.usageSave = setTimeout(() => {
|
|
1172
|
+
this.usageSave = null;
|
|
1173
|
+
void saveReadings(this.usage).catch((error: unknown) => log("could not save usage", error));
|
|
1174
|
+
}, 3_000);
|
|
1175
|
+
this.usageSave.unref?.();
|
|
1176
|
+
}
|
|
1177
|
+
|
|
1178
|
+
// ------------------------------------------------------------------ RPC: state
|
|
1179
|
+
|
|
1180
|
+
async view(paseo: PaseoApi, refreshUsage = false): Promise<StateView> {
|
|
1181
|
+
this.attach(paseo);
|
|
1182
|
+
if (refreshUsage) {
|
|
1183
|
+
const state = await this.store.read();
|
|
1184
|
+
await Promise.allSettled(state.accounts.map((account) => this.refreshUsage(account.id, true, true)));
|
|
1185
|
+
}
|
|
1186
|
+
void this.prune(paseo).catch(() => undefined);
|
|
1187
|
+
const state = await this.store.read();
|
|
1188
|
+
const families = await this.families.resolve(paseo);
|
|
1189
|
+
const agents = await this.cachedAgents(paseo);
|
|
1190
|
+
const now = Date.now();
|
|
1191
|
+
|
|
1192
|
+
const routes: AgentRoute[] = [];
|
|
1193
|
+
const counts = new Map<string, number>();
|
|
1194
|
+
for (const agent of agents) {
|
|
1195
|
+
const family = families[agent.provider];
|
|
1196
|
+
if (!family || agent.archived) continue;
|
|
1197
|
+
const accountId = this.targetFor(state, agent.id, family);
|
|
1198
|
+
if (!accountId) continue;
|
|
1199
|
+
counts.set(accountId, (counts.get(accountId) ?? 0) + 1);
|
|
1200
|
+
const current = isLive(agent.status) ? this.runningOn(state, agent.id, family) : undefined;
|
|
1201
|
+
const binding = state.bindings[agent.id];
|
|
1202
|
+
routes.push({
|
|
1203
|
+
agentId: agent.id,
|
|
1204
|
+
family,
|
|
1205
|
+
accountId,
|
|
1206
|
+
pinned: Boolean(binding && binding.source !== "thread"),
|
|
1207
|
+
pendingAccountId: current && current !== accountId ? current : null,
|
|
1208
|
+
movable: this.adapters[family].portable || !agent.hasHistory,
|
|
1209
|
+
});
|
|
1210
|
+
}
|
|
1211
|
+
|
|
1212
|
+
const accounts: AccountView[] = state.accounts.map((account) => {
|
|
1213
|
+
const limited = isLimited(account, now);
|
|
1214
|
+
return {
|
|
1215
|
+
id: account.id,
|
|
1216
|
+
family: account.family,
|
|
1217
|
+
label: account.label,
|
|
1218
|
+
kind: account.kind,
|
|
1219
|
+
email: account.email,
|
|
1220
|
+
plan: account.plan,
|
|
1221
|
+
organization: account.organization,
|
|
1222
|
+
status: !account.signedIn ? "signed_out" : limited ? "limited" : "ready",
|
|
1223
|
+
isDefault: defaultAccount(state, account.family)?.id === account.id,
|
|
1224
|
+
limitedUntil: limited ? account.limitedUntil : null,
|
|
1225
|
+
usage: this.usage.get(account.id) ?? null,
|
|
1226
|
+
agentCount: counts.get(account.id) ?? 0,
|
|
1227
|
+
home: account.home,
|
|
1228
|
+
};
|
|
1229
|
+
});
|
|
1230
|
+
|
|
1231
|
+
return {
|
|
1232
|
+
accounts,
|
|
1233
|
+
agents: routes,
|
|
1234
|
+
logins: [...this.logins.values()].map((login) => login.view),
|
|
1235
|
+
providers: families,
|
|
1236
|
+
canReopen: (await this.reopener.locate()) !== null,
|
|
1237
|
+
browserSignIn: this.browserSignIn,
|
|
1238
|
+
showComposerPill: this.prefs.showComposerPill,
|
|
1239
|
+
warnings: await this.warnings(),
|
|
1240
|
+
};
|
|
1241
|
+
}
|
|
1242
|
+
|
|
1243
|
+
/** Agents with a live session: the given ones (looked up fresh), or every one. */
|
|
1244
|
+
private async liveAgents(paseo: PaseoApi, agentIds?: readonly string[]): Promise<AgentInfo[]> {
|
|
1245
|
+
const agents = agentIds
|
|
1246
|
+
? (await Promise.all(agentIds.map((agentId) => agentInfo(paseo, agentId)))).filter((agent): agent is AgentInfo => agent !== null)
|
|
1247
|
+
: await this.cachedAgents(paseo);
|
|
1248
|
+
return agents.filter((agent) => !agent.archived && isLive(agent.status));
|
|
1249
|
+
}
|
|
1250
|
+
|
|
1251
|
+
private cachedAgents(paseo: PaseoApi): Promise<AgentInfo[]> {
|
|
1252
|
+
if (this.agentCache && Date.now() - this.agentCache.at < AGENT_LIST_MS) return this.agentCache.agents;
|
|
1253
|
+
const agents = listAgents(paseo, false).then((result) => result.agents);
|
|
1254
|
+
this.agentCache = { at: Date.now(), agents };
|
|
1255
|
+
agents.catch(() => {
|
|
1256
|
+
this.agentCache = null;
|
|
1257
|
+
});
|
|
1258
|
+
return agents;
|
|
1259
|
+
}
|
|
1260
|
+
|
|
1261
|
+
private async warnings(): Promise<string[]> {
|
|
1262
|
+
const warnings: string[] = [];
|
|
1263
|
+
for (const family of FAMILIES) {
|
|
1264
|
+
const availability = this.availability.get(family);
|
|
1265
|
+
if (availability && !availability.ok) {
|
|
1266
|
+
warnings.push(
|
|
1267
|
+
`${PROVIDER_NAME[family]} isn't installed where the daemon can run it${availability.detail ? ` (${availability.detail})` : ""}. Install it to add ${FAMILY_LABEL[family]} accounts.`,
|
|
1268
|
+
);
|
|
1269
|
+
}
|
|
1270
|
+
}
|
|
1271
|
+
if (process.env.CLAUDE_CODE_OAUTH_TOKEN || process.env.ANTHROPIC_AUTH_TOKEN || process.env.ANTHROPIC_API_KEY) {
|
|
1272
|
+
warnings.push(
|
|
1273
|
+
"The daemon's environment sets a Claude API key or token. Agents on your CLI login use it; agents on added accounts use their own sign-in.",
|
|
1274
|
+
);
|
|
1275
|
+
}
|
|
1276
|
+
if (process.env.CODEX_ACCESS_TOKEN) {
|
|
1277
|
+
warnings.push("The daemon's environment sets CODEX_ACCESS_TOKEN. Codex agents on your CLI login use it instead of a ChatGPT sign-in.");
|
|
1278
|
+
}
|
|
1279
|
+
if ((await this.reopener.locate()) === null) {
|
|
1280
|
+
warnings.push(
|
|
1281
|
+
"Paseo's command-line tool wasn't found, so running agents change accounts the next time their session starts instead of right away.",
|
|
1282
|
+
);
|
|
1283
|
+
}
|
|
1284
|
+
return warnings;
|
|
1285
|
+
}
|
|
1286
|
+
|
|
1287
|
+
// ------------------------------------------------------------------ RPC: accounts
|
|
1288
|
+
|
|
1289
|
+
async setDefault(paseo: PaseoApi, accountId: string): Promise<ReopenSummary> {
|
|
1290
|
+
this.attach(paseo);
|
|
1291
|
+
const account = findAccount(await this.store.read(), accountId);
|
|
1292
|
+
if (!account) throw new Error("That account no longer exists.");
|
|
1293
|
+
if (!account.signedIn) throw new Error(`${account.label} is signed out. Sign it in first.`);
|
|
1294
|
+
if (!this.adapters[account.family].portable) await this.pinThreads(paseo, account.family);
|
|
1295
|
+
await this.store.update((draft) => {
|
|
1296
|
+
draft.defaults[account.family] = account.id;
|
|
1297
|
+
});
|
|
1298
|
+
// Conversations that can't move (Codex threads) are pinned, so this only moves portable ones.
|
|
1299
|
+
return this.reconcile(paseo, "default");
|
|
1300
|
+
}
|
|
1301
|
+
|
|
1302
|
+
/**
|
|
1303
|
+
* Pins every existing agent of a non-portable provider to the account it runs on now, before the
|
|
1304
|
+
* default changes. Agents that haven't opened a session since ZeroSub was installed have no pin yet.
|
|
1305
|
+
*/
|
|
1306
|
+
private async pinThreads(paseo: PaseoApi, family: Family): Promise<void> {
|
|
1307
|
+
const families = await this.families.resolve(paseo);
|
|
1308
|
+
const { agents } = await listAgents(paseo, true);
|
|
1309
|
+
const state = await this.store.read();
|
|
1310
|
+
const current = defaultAccount(state, family);
|
|
1311
|
+
const unpinned = agents.filter((agent) => families[agent.provider] === family && !state.bindings[agent.id]);
|
|
1312
|
+
if (!current || unpinned.length === 0) return;
|
|
1313
|
+
const at = new Date().toISOString();
|
|
1314
|
+
await this.store.update((draft) => {
|
|
1315
|
+
for (const agent of unpinned) {
|
|
1316
|
+
if (draft.bindings[agent.id]) continue;
|
|
1317
|
+
// A thread lives where its session ran: the CLI login when ZeroSub never routed it.
|
|
1318
|
+
draft.bindings[agent.id] = { accountId: this.runningOn(draft, agent.id, family) ?? current.id, source: "thread", at };
|
|
1319
|
+
}
|
|
1320
|
+
});
|
|
1321
|
+
}
|
|
1322
|
+
|
|
1323
|
+
async clearLimit(accountId: string): Promise<void> {
|
|
1324
|
+
const state = await this.store.update((draft) => {
|
|
1325
|
+
const account = findAccount(draft, accountId);
|
|
1326
|
+
if (!account) return;
|
|
1327
|
+
account.limitedUntil = null;
|
|
1328
|
+
account.limitKind = null;
|
|
1329
|
+
});
|
|
1330
|
+
if (!findAccount(state, accountId)) throw new Error("That account no longer exists.");
|
|
1331
|
+
void this.refreshUsage(accountId, true).catch(() => undefined);
|
|
1332
|
+
}
|
|
1333
|
+
|
|
1334
|
+
async setAgentAccount(paseo: PaseoApi, agentId: string, accountId: string | null): Promise<ReopenSummary> {
|
|
1335
|
+
this.attach(paseo);
|
|
1336
|
+
const info = await agentInfo(paseo, agentId);
|
|
1337
|
+
if (!info) throw new Error("That agent is no longer available.");
|
|
1338
|
+
const family = (await this.families.resolve(paseo))[info.provider];
|
|
1339
|
+
if (!family) throw new Error(`${info.provider} agents don't use Claude or ChatGPT subscription accounts.`);
|
|
1340
|
+
const adapter = this.adapters[family];
|
|
1341
|
+
const state = await this.store.read();
|
|
1342
|
+
const target = accountId ? findAccount(state, accountId) : defaultAccount(state, family);
|
|
1343
|
+
if (!target || target.family !== family) throw new Error("That account can't be used with this agent.");
|
|
1344
|
+
if (!target.signedIn) throw new Error(`${target.label} is signed out. Sign it in first.`);
|
|
1345
|
+
|
|
1346
|
+
if (!adapter.portable) {
|
|
1347
|
+
if (info.status === "running" || info.status === "initializing") {
|
|
1348
|
+
throw new Error("This agent is working right now. Wait for its turn to finish, then switch.");
|
|
1349
|
+
}
|
|
1350
|
+
if (info.hasHistory) {
|
|
1351
|
+
const binding = state.bindings[agentId];
|
|
1352
|
+
const current = binding?.source === "thread" ? binding.accountId : this.runningOn(state, agentId, family);
|
|
1353
|
+
if (current === target.id) return emptySummary();
|
|
1354
|
+
const continuation = await this.continueElsewhere(
|
|
1355
|
+
paseo,
|
|
1356
|
+
agentId,
|
|
1357
|
+
target,
|
|
1358
|
+
`you moved the work to your ChatGPT account "${target.label}"`,
|
|
1359
|
+
undefined,
|
|
1360
|
+
"user",
|
|
1361
|
+
);
|
|
1362
|
+
await this.appendRow(paseo, agentId, {
|
|
1363
|
+
family,
|
|
1364
|
+
from: findAccount(state, current)?.label ?? null,
|
|
1365
|
+
to: target.label,
|
|
1366
|
+
reason: "manual",
|
|
1367
|
+
resetsAt: null,
|
|
1368
|
+
continued: true,
|
|
1369
|
+
continuedIn: continuation,
|
|
1370
|
+
toFamily: null,
|
|
1371
|
+
outcome: "continued",
|
|
1372
|
+
detail: null,
|
|
1373
|
+
at: new Date().toISOString(),
|
|
1374
|
+
});
|
|
1375
|
+
return { ...emptySummary(), continuedIn: continuation };
|
|
1376
|
+
}
|
|
1377
|
+
}
|
|
1378
|
+
|
|
1379
|
+
await this.store.update((draft) => {
|
|
1380
|
+
if (accountId) draft.bindings[agentId] = { accountId, source: adapter.portable ? "user" : "thread", at: new Date().toISOString() };
|
|
1381
|
+
else delete draft.bindings[agentId];
|
|
1382
|
+
});
|
|
1383
|
+
return this.reconcile(paseo, "manual", [agentId]);
|
|
1384
|
+
}
|
|
1385
|
+
|
|
1386
|
+
async rename(accountId: string, label: string): Promise<void> {
|
|
1387
|
+
const state = await this.store.update((draft) => {
|
|
1388
|
+
const account = findAccount(draft, accountId);
|
|
1389
|
+
if (!account) return;
|
|
1390
|
+
account.label = label;
|
|
1391
|
+
account.autoLabel = false;
|
|
1392
|
+
});
|
|
1393
|
+
if (!findAccount(state, accountId)) throw new Error("That account no longer exists.");
|
|
1394
|
+
}
|
|
1395
|
+
|
|
1396
|
+
async remove(paseo: PaseoApi, accountId: string): Promise<number> {
|
|
1397
|
+
this.attach(paseo);
|
|
1398
|
+
const state = await this.store.read();
|
|
1399
|
+
const account = findAccount(state, accountId);
|
|
1400
|
+
if (!account) throw new Error("That account no longer exists.");
|
|
1401
|
+
if (account.kind === "main") {
|
|
1402
|
+
throw new Error("Your CLI login can't be removed here. Sign out with `claude auth logout` or `codex logout` instead.");
|
|
1403
|
+
}
|
|
1404
|
+
if (!this.adapters[account.family].portable) {
|
|
1405
|
+
// These conversations can't move to another ChatGPT account, so removing theirs would strand them.
|
|
1406
|
+
const families = await this.families.resolve(paseo);
|
|
1407
|
+
const stranded = (await listAgents(paseo, false)).agents.filter(
|
|
1408
|
+
(agent) =>
|
|
1409
|
+
families[agent.provider] === account.family &&
|
|
1410
|
+
agent.hasHistory &&
|
|
1411
|
+
(state.bindings[agent.id]?.accountId ?? state.sessions[agent.id]?.accountId) === accountId,
|
|
1412
|
+
);
|
|
1413
|
+
if (stranded.length > 0) {
|
|
1414
|
+
const one = stranded.length === 1;
|
|
1415
|
+
throw new Error(
|
|
1416
|
+
`${stranded.length} ChatGPT conversation${one ? "" : "s"} still ${one ? "runs" : "run"} on ${account.label} and can't move to another account. Archive ${
|
|
1417
|
+
one ? "it" : "them"
|
|
1418
|
+
} (the work stays in your files) or continue ${one ? "it" : "them"} on another account from the account button, then remove ${account.label}.`,
|
|
1419
|
+
);
|
|
1420
|
+
}
|
|
1421
|
+
}
|
|
1422
|
+
const affected = Object.entries(state.sessions)
|
|
1423
|
+
.filter(([, session]) => session.accountId === accountId)
|
|
1424
|
+
.map(([agentId]) => agentId);
|
|
1425
|
+
await this.store.update((draft) => {
|
|
1426
|
+
draft.accounts = draft.accounts.filter((entry) => entry.id !== accountId);
|
|
1427
|
+
for (const [agentId, binding] of Object.entries(draft.bindings)) {
|
|
1428
|
+
if (binding.accountId === accountId) delete draft.bindings[agentId];
|
|
1429
|
+
}
|
|
1430
|
+
if (draft.defaults[account.family] === accountId) draft.defaults[account.family] = null;
|
|
1431
|
+
});
|
|
1432
|
+
this.setUsage(accountId, null);
|
|
1433
|
+
// Idle agents move now and busy ones after their turn. The home is signed out and deleted by the
|
|
1434
|
+
// cleanup pass only once nothing runs on it any more.
|
|
1435
|
+
await this.reconcile(paseo, "removed", affected, new Map([[account.id, account.label]]));
|
|
1436
|
+
void this.collectOrphanHomes(paseo).catch((error: unknown) => log("cleanup failed", error));
|
|
1437
|
+
return affected.length;
|
|
1438
|
+
}
|
|
1439
|
+
|
|
1440
|
+
// ------------------------------------------------------------------ RPC: sign-in
|
|
1441
|
+
|
|
1442
|
+
startLogin(family: Family, method: LoginMethod, accountId?: string): Promise<LoginView> {
|
|
1443
|
+
return this.loginLocks[family].run(() => this.beginLogin(family, method, accountId));
|
|
1444
|
+
}
|
|
1445
|
+
|
|
1446
|
+
private async beginLogin(family: Family, method: LoginMethod, accountId?: string): Promise<LoginView> {
|
|
1447
|
+
let availability = this.availability.get(family);
|
|
1448
|
+
if (!availability?.ok) {
|
|
1449
|
+
await this.ensureFamily(family);
|
|
1450
|
+
availability = this.availability.get(family);
|
|
1451
|
+
}
|
|
1452
|
+
if (!availability?.ok) throw new Error(`${PROVIDER_NAME[family]} isn't installed on the daemon machine.`);
|
|
1453
|
+
// One flow per provider at a time (Codex's browser sign-in uses a fixed local port).
|
|
1454
|
+
for (const login of this.logins.values()) {
|
|
1455
|
+
if (login.family === family && !login.finishedAt) await this.cancelLogin(login.id);
|
|
1456
|
+
}
|
|
1457
|
+
const state = await this.store.read();
|
|
1458
|
+
const existing = accountId ? findAccount(state, accountId) : undefined;
|
|
1459
|
+
if (accountId && (!existing || existing.family !== family)) throw new Error("That account no longer exists.");
|
|
1460
|
+
|
|
1461
|
+
const id = randomBytes(6).toString("hex");
|
|
1462
|
+
const home = existing ? existing.home : join(homesDir(), `${family}-${id}`);
|
|
1463
|
+
const session: LoginSession = {
|
|
1464
|
+
id,
|
|
1465
|
+
family,
|
|
1466
|
+
accountId: existing?.id ?? null,
|
|
1467
|
+
home,
|
|
1468
|
+
handle: null,
|
|
1469
|
+
finishedAt: null,
|
|
1470
|
+
view: {
|
|
1471
|
+
id,
|
|
1472
|
+
family,
|
|
1473
|
+
method,
|
|
1474
|
+
accountId: existing?.id ?? null,
|
|
1475
|
+
step: "starting",
|
|
1476
|
+
url: null,
|
|
1477
|
+
codeUrl: null,
|
|
1478
|
+
userCode: null,
|
|
1479
|
+
message: null,
|
|
1480
|
+
startedAt: new Date().toISOString(),
|
|
1481
|
+
},
|
|
1482
|
+
};
|
|
1483
|
+
this.logins.set(id, session);
|
|
1484
|
+
try {
|
|
1485
|
+
if (home) await this.adapters[family].prepareHome(home);
|
|
1486
|
+
const handle = await this.adapters[family].login(home, method);
|
|
1487
|
+
if (session.finishedAt) {
|
|
1488
|
+
handle.cancel();
|
|
1489
|
+
return session.view;
|
|
1490
|
+
}
|
|
1491
|
+
session.handle = handle;
|
|
1492
|
+
const sync = () => {
|
|
1493
|
+
if (!session.finishedAt) session.view = { ...session.view, ...handle.progress };
|
|
1494
|
+
};
|
|
1495
|
+
handle.onProgress(sync);
|
|
1496
|
+
sync();
|
|
1497
|
+
void handle.finished
|
|
1498
|
+
.then((result) => this.finishLogin(session, result))
|
|
1499
|
+
.catch((error: unknown) => this.failLogin(session, describe(error)));
|
|
1500
|
+
} catch (error) {
|
|
1501
|
+
this.failLogin(session, describe(error));
|
|
1502
|
+
}
|
|
1503
|
+
return session.view;
|
|
1504
|
+
}
|
|
1505
|
+
|
|
1506
|
+
async submitCode(loginId: string, code: string): Promise<LoginView> {
|
|
1507
|
+
const session = this.logins.get(loginId);
|
|
1508
|
+
if (!session?.handle) throw new Error("This sign-in has expired. Start again.");
|
|
1509
|
+
if (!session.finishedAt) await session.handle.submitCode(code);
|
|
1510
|
+
return session.view;
|
|
1511
|
+
}
|
|
1512
|
+
|
|
1513
|
+
async cancelLogin(loginId: string): Promise<LoginView | null> {
|
|
1514
|
+
const session = this.logins.get(loginId);
|
|
1515
|
+
if (!session) return null;
|
|
1516
|
+
if (!session.finishedAt) {
|
|
1517
|
+
session.finishedAt = Date.now();
|
|
1518
|
+
session.handle?.cancel();
|
|
1519
|
+
session.view = { ...session.view, step: "canceled", message: "Sign-in was canceled." };
|
|
1520
|
+
this.scheduleCleanup();
|
|
1521
|
+
}
|
|
1522
|
+
return session.view;
|
|
1523
|
+
}
|
|
1524
|
+
|
|
1525
|
+
private async finishLogin(session: LoginSession, result: { ok: boolean; message: string | null }): Promise<void> {
|
|
1526
|
+
if (session.finishedAt) return;
|
|
1527
|
+
if (!result.ok) return this.failLogin(session, result.message ?? "Sign-in did not finish.");
|
|
1528
|
+
session.view = { ...session.view, step: "verifying", message: null };
|
|
1529
|
+
const adapter = this.adapters[session.family];
|
|
1530
|
+
const identity = await adapter.identity(session.home).catch(() => null);
|
|
1531
|
+
if (session.finishedAt) return; // Canceled while verifying.
|
|
1532
|
+
if (!identity?.signedIn) return this.failLogin(session, "Sign-in finished, but the account isn't signed in. Try again.");
|
|
1533
|
+
|
|
1534
|
+
const state = await this.store.read();
|
|
1535
|
+
const existing = findAccount(state, session.accountId);
|
|
1536
|
+
if (existing?.kind === "managed" && existing.identity && identity.identity && existing.identity !== identity.identity) {
|
|
1537
|
+
// Signing an account back in must not quietly turn it into a different login.
|
|
1538
|
+
if (session.home) await adapter.logout(session.home).catch(() => undefined);
|
|
1539
|
+
const expected = existing.email ?? existing.label;
|
|
1540
|
+
return this.failLogin(
|
|
1541
|
+
session,
|
|
1542
|
+
`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.`,
|
|
1543
|
+
);
|
|
1544
|
+
}
|
|
1545
|
+
// The CLI's own login is whatever the user signs it into; only added accounts must be distinct.
|
|
1546
|
+
const duplicate =
|
|
1547
|
+
identity.identity && existing?.kind !== "main"
|
|
1548
|
+
? accountsOf(state, session.family).find(
|
|
1549
|
+
(account) => account.id !== session.accountId && account.identity === identity.identity,
|
|
1550
|
+
)
|
|
1551
|
+
: undefined;
|
|
1552
|
+
if (duplicate) {
|
|
1553
|
+
if (!existing && session.home) await adapter.logout(session.home).catch(() => undefined);
|
|
1554
|
+
return this.failLogin(
|
|
1555
|
+
session,
|
|
1556
|
+
`${identity.email ?? "That account"} is already added as "${duplicate.label}". Sign in with a different account.`,
|
|
1557
|
+
);
|
|
1558
|
+
}
|
|
1559
|
+
if (session.finishedAt) return;
|
|
1560
|
+
session.finishedAt = Date.now(); // Claim completion before writing, so a late cancel can't race it.
|
|
1561
|
+
|
|
1562
|
+
let accountId = session.accountId;
|
|
1563
|
+
await this.store.update((draft) => {
|
|
1564
|
+
let account = findAccount(draft, accountId);
|
|
1565
|
+
if (!account) {
|
|
1566
|
+
// A managed account's ID matches its home's folder name (collectOrphanHomes relies on it).
|
|
1567
|
+
accountId = `${session.family}-${session.id}`;
|
|
1568
|
+
account = newAccount({ id: accountId, family: session.family, kind: "managed", home: session.home });
|
|
1569
|
+
draft.accounts.push(account);
|
|
1570
|
+
}
|
|
1571
|
+
applyIdentity(account, identity, draft);
|
|
1572
|
+
account.limitedUntil = null;
|
|
1573
|
+
account.limitKind = null;
|
|
1574
|
+
});
|
|
1575
|
+
if (accountId) this.identityCheckedAt.set(accountId, Date.now());
|
|
1576
|
+
session.accountId = accountId;
|
|
1577
|
+
session.view = { ...session.view, step: "done", accountId, message: null };
|
|
1578
|
+
if (accountId) void this.refreshUsage(accountId, true).catch(() => undefined);
|
|
1579
|
+
}
|
|
1580
|
+
|
|
1581
|
+
private failLogin(session: LoginSession, message: string): void {
|
|
1582
|
+
if (session.finishedAt) return;
|
|
1583
|
+
session.finishedAt = Date.now();
|
|
1584
|
+
session.handle?.cancel();
|
|
1585
|
+
session.view = { ...session.view, step: "failed", message };
|
|
1586
|
+
this.scheduleCleanup();
|
|
1587
|
+
}
|
|
1588
|
+
}
|
|
1589
|
+
|
|
1590
|
+
// -------------------------------------------------------------------- helpers
|
|
1591
|
+
|
|
1592
|
+
function newAccount(fields: Pick<StoredAccount, "id" | "family" | "kind" | "home">): StoredAccount {
|
|
1593
|
+
return {
|
|
1594
|
+
...fields,
|
|
1595
|
+
label: "",
|
|
1596
|
+
autoLabel: true,
|
|
1597
|
+
email: null,
|
|
1598
|
+
plan: null,
|
|
1599
|
+
organization: null,
|
|
1600
|
+
identity: null,
|
|
1601
|
+
signedIn: true,
|
|
1602
|
+
limitedUntil: null,
|
|
1603
|
+
limitKind: null,
|
|
1604
|
+
limitedAt: null,
|
|
1605
|
+
createdAt: new Date().toISOString(),
|
|
1606
|
+
};
|
|
1607
|
+
}
|
|
1608
|
+
|
|
1609
|
+
function applyIdentity(account: StoredAccount, identity: Identity, state: StoredState): void {
|
|
1610
|
+
account.signedIn = identity.signedIn;
|
|
1611
|
+
if (!identity.signedIn) return;
|
|
1612
|
+
account.email = identity.email ?? account.email;
|
|
1613
|
+
account.plan = identity.plan ?? account.plan;
|
|
1614
|
+
account.organization = identity.organization ?? account.organization;
|
|
1615
|
+
account.identity = identity.identity ?? account.identity;
|
|
1616
|
+
if (account.autoLabel || !account.label) {
|
|
1617
|
+
account.label = suggestLabel(account, state);
|
|
1618
|
+
account.autoLabel = true;
|
|
1619
|
+
}
|
|
1620
|
+
}
|
|
1621
|
+
|
|
1622
|
+
/** "work" for work@acme.com, or the full address when another account would read the same. */
|
|
1623
|
+
export function suggestLabel(account: StoredAccount, state: StoredState): string {
|
|
1624
|
+
const others = accountsOf(state, account.family).filter((entry) => entry.id !== account.id);
|
|
1625
|
+
if (account.email) {
|
|
1626
|
+
const local = account.email.split("@")[0] ?? account.email;
|
|
1627
|
+
const clash = others.some(
|
|
1628
|
+
(entry) => entry.label.toLowerCase() === local.toLowerCase() || entry.email?.split("@")[0]?.toLowerCase() === local.toLowerCase(),
|
|
1629
|
+
);
|
|
1630
|
+
return clash ? account.email : local;
|
|
1631
|
+
}
|
|
1632
|
+
const base = FAMILY_LABEL[account.family];
|
|
1633
|
+
let index = others.length + 1;
|
|
1634
|
+
while (others.some((entry) => entry.label === `${base} ${index}`)) index += 1;
|
|
1635
|
+
return `${base} ${index}`;
|
|
1636
|
+
}
|
|
1637
|
+
|
|
1638
|
+
type AgentSnapshot = Awaited<ReturnType<PaseoApi["agents"]["list"]>>["entries"][number]["agent"];
|
|
1639
|
+
|
|
1640
|
+
function toAgentInfo(agent: AgentSnapshot): AgentInfo {
|
|
1641
|
+
return {
|
|
1642
|
+
id: agent.id,
|
|
1643
|
+
provider: agent.provider,
|
|
1644
|
+
status: agent.status,
|
|
1645
|
+
archived: Boolean(agent.archivedAt),
|
|
1646
|
+
hasHistory: Boolean(agent.lastUserMessageAt),
|
|
1647
|
+
title: agent.title ?? null,
|
|
1648
|
+
continuedFrom: agent.labels?.[CONTINUED_FROM_LABEL] ?? null,
|
|
1649
|
+
};
|
|
1650
|
+
}
|
|
1651
|
+
|
|
1652
|
+
async function agentInfo(paseo: PaseoApi, agentId: string): Promise<AgentInfo | null> {
|
|
1653
|
+
try {
|
|
1654
|
+
const agent = (await paseo.agents.ref(agentId).refresh())?.agent;
|
|
1655
|
+
return agent ? toAgentInfo(agent) : null;
|
|
1656
|
+
} catch {
|
|
1657
|
+
return null;
|
|
1658
|
+
}
|
|
1659
|
+
}
|
|
1660
|
+
|
|
1661
|
+
const MAX_PAGES = 100;
|
|
1662
|
+
|
|
1663
|
+
async function listAgents(paseo: PaseoApi, includeArchived: boolean): Promise<{ agents: AgentInfo[]; complete: boolean }> {
|
|
1664
|
+
const agents: AgentInfo[] = [];
|
|
1665
|
+
let cursor: string | undefined;
|
|
1666
|
+
for (let page = 0; page < MAX_PAGES; page += 1) {
|
|
1667
|
+
const result = await paseo.agents.list({
|
|
1668
|
+
...(includeArchived ? { filter: { includeArchived: true } } : {}),
|
|
1669
|
+
page: { limit: 200, ...(cursor ? { cursor } : {}) },
|
|
1670
|
+
});
|
|
1671
|
+
for (const { agent } of result.entries) agents.push(toAgentInfo(agent));
|
|
1672
|
+
if (!result.pageInfo.hasMore || !result.pageInfo.nextCursor) return { agents, complete: true };
|
|
1673
|
+
cursor = result.pageInfo.nextCursor;
|
|
1674
|
+
}
|
|
1675
|
+
return { agents, complete: false };
|
|
1676
|
+
}
|
|
1677
|
+
|
|
1678
|
+
function delay(ms: number): Promise<void> {
|
|
1679
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
1680
|
+
}
|
|
1681
|
+
|
|
1682
|
+
async function withTimeout(task: Promise<unknown>, ms: number): Promise<void> {
|
|
1683
|
+
await Promise.race([task.catch(() => undefined), delay(ms)]);
|
|
1684
|
+
}
|
|
1685
|
+
|
|
1686
|
+
function log(message: string, error: unknown): void {
|
|
1687
|
+
console.error(`[ZeroSub] ${message}`, describe(error));
|
|
1688
|
+
}
|
|
1689
|
+
|
|
1690
|
+
export function describe(error: unknown): string {
|
|
1691
|
+
return error instanceof Error ? error.message : String(error);
|
|
1692
|
+
}
|