@kapybara/zerosub 1.2.2 → 1.4.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/README.md +11 -4
- package/client/accounts-surface.tsx +7 -0
- package/client/pills.ts +3 -3
- package/client/settings-screen.tsx +7 -0
- package/client/switch-row.tsx +2 -4
- package/package.json +1 -1
- package/server/codex.ts +1 -1
- package/server/continuations.ts +576 -0
- package/server/handoff.ts +52 -8
- package/server/limits.ts +18 -1
- package/server/service.ts +230 -17
- package/server/state.ts +30 -1
- package/shared/preferences.ts +7 -0
- package/shared/rpc.ts +1 -1
package/server/handoff.ts
CHANGED
|
@@ -9,12 +9,48 @@ export const CONTINUED_FROM_LABEL = "zerosub.continued-from";
|
|
|
9
9
|
|
|
10
10
|
const MAX_TRANSCRIPT = 40_000;
|
|
11
11
|
const MAX_FIRST_MESSAGE = 6_000;
|
|
12
|
+
const MAX_EARLIER_HANDOFF = 6_000;
|
|
13
|
+
|
|
14
|
+
const OPEN = "<previous-session>";
|
|
15
|
+
const CLOSE = "</previous-session>";
|
|
12
16
|
|
|
13
17
|
function clip(text: string, max: number): string {
|
|
14
18
|
const trimmed = text.trim();
|
|
15
19
|
return trimmed.length <= max ? trimmed : `${trimmed.slice(0, max)}…`;
|
|
16
20
|
}
|
|
17
21
|
|
|
22
|
+
/**
|
|
23
|
+
* Fits a long text into `max` characters by keeping its start (where the request usually is) and
|
|
24
|
+
* its end (the most recent context), with a marker where the middle was cut. The end gets more room.
|
|
25
|
+
*/
|
|
26
|
+
export function keepEnds(text: string, max: number, marker = "[… omitted …]"): string {
|
|
27
|
+
if (text.length <= max) return text;
|
|
28
|
+
const room = Math.max(0, max - marker.length - 4);
|
|
29
|
+
const head = Math.floor(room / 3);
|
|
30
|
+
return `${text.slice(0, head).trimEnd()}\n\n${marker}\n\n${text.slice(text.length - (room - head)).trimStart()}`;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** Tags become plain words, so a quote can't open or close the block around it. */
|
|
34
|
+
function neutralise(text: string): string {
|
|
35
|
+
return text.replaceAll(OPEN, "[earlier session:").replaceAll(CLOSE, "]");
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* A continuation's first message quotes the session before it. Quoting that again would nest every
|
|
40
|
+
* earlier hand-off inside the next, so keep only the start of the earlier session (its original
|
|
41
|
+
* request) and its end (where it left off), and say what was cut. Based on liloli's version in #14.
|
|
42
|
+
*/
|
|
43
|
+
export function shortenEarlierHandOff(text: string): string {
|
|
44
|
+
const open = text.indexOf(OPEN);
|
|
45
|
+
if (open < 0) return text;
|
|
46
|
+
const close = text.lastIndexOf(CLOSE);
|
|
47
|
+
const end = close > open ? close : text.length;
|
|
48
|
+
const inner = neutralise(shortenEarlierHandOff(text.slice(open + OPEN.length, end))).trim();
|
|
49
|
+
const kept = keepEnds(inner, MAX_EARLIER_HANDOFF, "[… middle of that earlier session omitted …]");
|
|
50
|
+
const after = close > open ? text.slice(close + CLOSE.length) : "";
|
|
51
|
+
return `${neutralise(text.slice(0, open))}${OPEN}\n${kept}\n${CLOSE}${neutralise(after)}`;
|
|
52
|
+
}
|
|
53
|
+
|
|
18
54
|
function describeTool(item: Extract<AgentTimelineItem, { type: "tool_call" }>): string {
|
|
19
55
|
const detail = item.detail;
|
|
20
56
|
const failed = item.status === "failed" ? " (failed)" : "";
|
|
@@ -48,10 +84,13 @@ export function buildTranscript(timeline: readonly AgentTimelineItem[], max = MA
|
|
|
48
84
|
let todos: string | null = null;
|
|
49
85
|
for (const item of timeline) {
|
|
50
86
|
switch (item.type) {
|
|
51
|
-
case "user_message":
|
|
52
|
-
|
|
53
|
-
|
|
87
|
+
case "user_message": {
|
|
88
|
+
// Clipping below can't then split a quoted pair: the prompt's own tags are the only ones.
|
|
89
|
+
const text = neutralise(shortenEarlierHandOff(item.text));
|
|
90
|
+
if (firstUser === null) firstUser = clip(text, MAX_FIRST_MESSAGE);
|
|
91
|
+
lines.push(`User: ${text.trim()}`);
|
|
54
92
|
break;
|
|
93
|
+
}
|
|
55
94
|
case "assistant_message":
|
|
56
95
|
if (item.text.trim()) lines.push(`Assistant: ${item.text.trim()}`);
|
|
57
96
|
break;
|
|
@@ -81,9 +120,9 @@ export function continuationPrompt(transcript: string, why: string, previous = "
|
|
|
81
120
|
`This task is continuing from an earlier ${previous} session that stopped because ${why}.`,
|
|
82
121
|
"The working directory already contains every change that session made. Here is its conversation, oldest first:",
|
|
83
122
|
"",
|
|
84
|
-
|
|
123
|
+
OPEN,
|
|
85
124
|
transcript,
|
|
86
|
-
|
|
125
|
+
CLOSE,
|
|
87
126
|
"",
|
|
88
127
|
"Pick up exactly where it left off. Check the current state of the files before changing anything, and don't redo finished work.",
|
|
89
128
|
].join("\n");
|
|
@@ -128,6 +167,9 @@ export async function continueInNewAgent(options: {
|
|
|
128
167
|
target?: ContinuationTarget;
|
|
129
168
|
/** What to call the session that stopped, e.g. `Claude Code`. */
|
|
130
169
|
previous?: string;
|
|
170
|
+
agentId?: string;
|
|
171
|
+
/** Create the pre-bound tab first; the caller delivers its handoff separately. */
|
|
172
|
+
deferPrompt?: boolean;
|
|
131
173
|
}): Promise<Continuation> {
|
|
132
174
|
const { paseo, sourceAgentId } = options;
|
|
133
175
|
const refreshed = await paseo.agents.ref(sourceAgentId).refresh();
|
|
@@ -135,7 +177,7 @@ export async function continueInNewAgent(options: {
|
|
|
135
177
|
if (!source) throw new Error("The original agent is no longer available.");
|
|
136
178
|
|
|
137
179
|
let timeline = options.timeline;
|
|
138
|
-
if (!timeline) {
|
|
180
|
+
if (!timeline && !options.deferPrompt) {
|
|
139
181
|
const page = await paseo.agents.ref(sourceAgentId).timeline.refetch({ direction: "tail", limit: 500 });
|
|
140
182
|
timeline = page.entries.map((entry) => entry.item);
|
|
141
183
|
}
|
|
@@ -149,7 +191,7 @@ export async function continueInNewAgent(options: {
|
|
|
149
191
|
: (source.model ?? source.runtimeInfo?.model ?? (await defaultModel(paseo, provider)));
|
|
150
192
|
if (!model) throw new Error(`Couldn't tell which ${provider} model to use for the new agent.`);
|
|
151
193
|
|
|
152
|
-
const agentId = randomUUID();
|
|
194
|
+
const agentId = options.agentId ?? randomUUID();
|
|
153
195
|
await options.bind(agentId);
|
|
154
196
|
const title = target
|
|
155
197
|
? `${source.title?.trim() || "Task"} (continued on ${target.label})`
|
|
@@ -161,12 +203,14 @@ export async function continueInNewAgent(options: {
|
|
|
161
203
|
provider: `${provider}/${model}`,
|
|
162
204
|
...(source.currentModeId ? { modeId: source.currentModeId } : {}),
|
|
163
205
|
...(source.thinkingOptionId ? { thinkingOptionId: source.thinkingOptionId } : {}),
|
|
206
|
+
...(source.features ? { featureValues: Object.fromEntries(source.features.map((feature) => [feature.id, feature.value])) } : {}),
|
|
164
207
|
};
|
|
165
208
|
const request = {
|
|
166
209
|
agentId,
|
|
210
|
+
...(options.agentId ? { idempotencyKey: options.agentId } : {}),
|
|
167
211
|
config,
|
|
168
212
|
title,
|
|
169
|
-
prompt: continuationPrompt(buildTranscript(timeline), options.why, options.previous),
|
|
213
|
+
...(!options.deferPrompt ? { prompt: continuationPrompt(buildTranscript(timeline ?? []), options.why, options.previous) } : {}),
|
|
170
214
|
labels: { [CONTINUED_FROM_LABEL]: sourceAgentId },
|
|
171
215
|
};
|
|
172
216
|
if (source.workspaceId) await paseo.workspaces.ref(source.workspaceId).agents.create(request);
|
package/server/limits.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { LimitHit, LimitKind, TurnEvent } from "./adapter";
|
|
1
|
+
import type { AgentTimelineItem, LimitHit, LimitKind, TurnEvent } from "./adapter";
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
4
|
* Claude Code's exact wording for hard limits (2.1.x templates: `You've hit your ${limit}${suffix}`),
|
|
@@ -49,6 +49,23 @@ function clean(text: string): string {
|
|
|
49
49
|
return text.replace(SYSTEM_ERROR, "").replace(/^API Error:\s*/i, "").trim();
|
|
50
50
|
}
|
|
51
51
|
|
|
52
|
+
/**
|
|
53
|
+
* A turn's rows in a page of the agent's timeline (oldest first), to read as that turn. Paseo 0.13
|
|
54
|
+
* tags each row of a live turn with the turn's id, but providers count turns per session, so an
|
|
55
|
+
* earlier turn can carry the same id. Reading back from the turn's last row, another turn's prompt
|
|
56
|
+
* is where this one began. Rows of other turns, and rows without an id, are left out.
|
|
57
|
+
*/
|
|
58
|
+
export function turnRows(entries: ReadonlyArray<{ item: AgentTimelineItem; turnId?: string }>, turnId: string): AgentTimelineItem[] {
|
|
59
|
+
const rows: AgentTimelineItem[] = [];
|
|
60
|
+
for (let index = entries.length - 1; index >= 0; index -= 1) {
|
|
61
|
+
const entry = entries[index];
|
|
62
|
+
if (!entry) continue;
|
|
63
|
+
if (entry.turnId === turnId) rows.push(entry.item);
|
|
64
|
+
else if (rows.length > 0 && entry.turnId && entry.item.type === "user_message") break;
|
|
65
|
+
}
|
|
66
|
+
return rows.reverse();
|
|
67
|
+
}
|
|
68
|
+
|
|
52
69
|
/**
|
|
53
70
|
* Where a CLI-generated notice can appear in a finished turn: the failure message, error items,
|
|
54
71
|
* Paseo's `[System Error]` rows, and — for Claude, which reports limits as a synthetic reply — the
|
package/server/service.ts
CHANGED
|
@@ -31,16 +31,18 @@ import {
|
|
|
31
31
|
type UsageRead,
|
|
32
32
|
} from "./adapter";
|
|
33
33
|
import { FamilyResolver } from "./families";
|
|
34
|
+
import { CodexContinuations } from "./continuations";
|
|
34
35
|
import { CONTINUED_FROM_LABEL, continueInNewAgent, type Continuation } from "./handoff";
|
|
35
36
|
import { removeHome } from "./homes";
|
|
36
37
|
import { Mutex } from "./json-file";
|
|
38
|
+
import { turnRows } from "./limits";
|
|
37
39
|
import { canSignInWithBrowser } from "./machine";
|
|
38
40
|
import { equivalentMode } from "./modes";
|
|
39
41
|
import { homesDir } from "./paths";
|
|
40
42
|
import { Reopener } from "./reopen";
|
|
41
43
|
import { SwitchGuard } from "./switch-guard";
|
|
42
44
|
import { loadReadings, mergeUsage, saveReadings, showLimit } from "./usage";
|
|
43
|
-
import { chooseAccount, isLimited, mostAvailable } from "./routing";
|
|
45
|
+
import { chooseAccount, isLimited, isUsable, mostAvailable } from "./routing";
|
|
44
46
|
import {
|
|
45
47
|
MAIN_ACCOUNT_ID,
|
|
46
48
|
StateStore,
|
|
@@ -48,6 +50,7 @@ import {
|
|
|
48
50
|
defaultAccount,
|
|
49
51
|
findAccount,
|
|
50
52
|
mainAccount,
|
|
53
|
+
type ContinuationChain,
|
|
51
54
|
type StoredAccount,
|
|
52
55
|
type StoredState,
|
|
53
56
|
} from "./state";
|
|
@@ -79,11 +82,16 @@ const PRUNE_MS = 10 * 60_000;
|
|
|
79
82
|
/** After a reset, limit notices from turns that were already running are stale. */
|
|
80
83
|
const RESET_GRACE_MS = 5 * 60_000;
|
|
81
84
|
const AGENT_LIST_MS = 3_000;
|
|
85
|
+
/** How long a default change waits for sessions already being routed to record their account. */
|
|
86
|
+
const ROUTING_WAIT_MS = 5_000;
|
|
87
|
+
/** How long the end of a turn waits for Paseo to page the agent's timeline. The SDK itself waits 60 s. */
|
|
88
|
+
const TURN_READ_MS = 10_000;
|
|
82
89
|
|
|
83
90
|
const DEFAULT_PREFERENCES: Preferences = {
|
|
84
91
|
autoSwitch: true,
|
|
85
92
|
autoContinue: true,
|
|
86
93
|
continuePrompt: DEFAULT_CONTINUE_PROMPT,
|
|
94
|
+
moveAgentsOnDefaultChange: true,
|
|
87
95
|
balanceNewAgents: false,
|
|
88
96
|
showComposerPill: true,
|
|
89
97
|
autoRedeem: false,
|
|
@@ -127,6 +135,7 @@ function emptySummary(): ReopenSummary {
|
|
|
127
135
|
}
|
|
128
136
|
|
|
129
137
|
export class Service {
|
|
138
|
+
private readonly continuations: CodexContinuations;
|
|
130
139
|
private paseo: PaseoApi | null = null;
|
|
131
140
|
private prefs: Preferences = DEFAULT_PREFERENCES;
|
|
132
141
|
private readonly usage = new Map<string, Usage>();
|
|
@@ -140,10 +149,12 @@ export class Service {
|
|
|
140
149
|
private readonly deferred = new Map<string, SwitchRow | null>();
|
|
141
150
|
/** Agents in the middle of a failover, so nothing else moves them at the same time. */
|
|
142
151
|
private readonly switching = new Set<string>();
|
|
152
|
+
/** Interactive sessions being routed right now, and their agents. Where each opens isn't recorded yet. */
|
|
153
|
+
private readonly routing = new Map<Promise<unknown>, string>();
|
|
143
154
|
/** One failover at a time per exhausted account. */
|
|
144
155
|
private readonly failoverLocks = new Map<string, Mutex>();
|
|
145
156
|
private readonly switchGuard = new SwitchGuard();
|
|
146
|
-
/** When
|
|
157
|
+
/** When ZeroSub last told an agent's timeline why it didn't switch, by agent and notice, so it says so once. */
|
|
147
158
|
private readonly guardNoticeAt = new Map<string, number>();
|
|
148
159
|
/** When each account's agents last started or ended a turn, to read busy accounts often. */
|
|
149
160
|
private readonly activeAt = new Map<string, number>();
|
|
@@ -164,7 +175,9 @@ export class Service {
|
|
|
164
175
|
private readonly store = new StateStore(),
|
|
165
176
|
private readonly families = new FamilyResolver(),
|
|
166
177
|
private readonly reopener = new Reopener(),
|
|
167
|
-
) {
|
|
178
|
+
) {
|
|
179
|
+
this.continuations = new CodexContinuations(store);
|
|
180
|
+
}
|
|
168
181
|
|
|
169
182
|
setPreferences(prefs: Preferences): void {
|
|
170
183
|
this.prefs = prefs;
|
|
@@ -269,10 +282,18 @@ export class Service {
|
|
|
269
282
|
const old = (at: string) => now - (Date.parse(at) || 0) > PRUNE_MS;
|
|
270
283
|
const staleSessions = Object.entries(state.sessions).filter(([id, session]) => !known.has(id) && old(session.openedAt));
|
|
271
284
|
const staleBindings = Object.entries(state.bindings).filter(([id, binding]) => !known.has(id) && old(binding.at));
|
|
272
|
-
|
|
285
|
+
const active = new Set(agents.filter((agent) => !agent.archived).map((agent) => agent.id));
|
|
286
|
+
// A hand-off that may have sent its prompt stays on record while its tab could come back. A
|
|
287
|
+
// failed creation sent nothing, so it doesn't keep the task's record alive.
|
|
288
|
+
const unsettled = (pending: ContinuationChain["pending"]) => pending?.stage === "sending" && known.has(pending.agentId);
|
|
289
|
+
const staleChains = Object.entries(state.continuations).filter(([, chain]) =>
|
|
290
|
+
!unsettled(chain.pending) && Object.keys(chain.members).every((id) => !active.has(id) && !this.switching.has(id)),
|
|
291
|
+
);
|
|
292
|
+
if (staleSessions.length === 0 && staleBindings.length === 0 && staleChains.length === 0) return;
|
|
273
293
|
await this.store.update((draft) => {
|
|
274
294
|
for (const [id] of staleSessions) delete draft.sessions[id];
|
|
275
295
|
for (const [id] of staleBindings) delete draft.bindings[id];
|
|
296
|
+
for (const [id] of staleChains) delete draft.continuations[id];
|
|
276
297
|
});
|
|
277
298
|
}
|
|
278
299
|
|
|
@@ -339,6 +360,20 @@ export class Service {
|
|
|
339
360
|
async onSessionOpen(
|
|
340
361
|
request: PluginSessionOpenRequest,
|
|
341
362
|
context: PluginHookContext,
|
|
363
|
+
): Promise<PluginSessionOpenRequest | undefined> {
|
|
364
|
+
const routed = this.route(request, context);
|
|
365
|
+
if (request.purpose !== "interactive") return routed;
|
|
366
|
+
this.routing.set(routed, request.agentId);
|
|
367
|
+
try {
|
|
368
|
+
return await routed;
|
|
369
|
+
} finally {
|
|
370
|
+
this.routing.delete(routed);
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
private async route(
|
|
375
|
+
request: PluginSessionOpenRequest,
|
|
376
|
+
context: PluginHookContext,
|
|
342
377
|
): Promise<PluginSessionOpenRequest | undefined> {
|
|
343
378
|
this.attach(context.paseo);
|
|
344
379
|
const family = (await this.families.resolve(context.paseo))[request.provider];
|
|
@@ -404,10 +439,13 @@ export class Service {
|
|
|
404
439
|
const accountId = this.runningOn(await this.store.read(), agentId, family);
|
|
405
440
|
if (accountId) this.activeAt.set(accountId, Date.now());
|
|
406
441
|
if (event.outcome.kind !== "canceled") {
|
|
407
|
-
const
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
442
|
+
const turn = await this.turnWithTimeline(context.paseo, event);
|
|
443
|
+
// A hand-off quotes the whole conversation, not just this turn. Paseo 0.13 sends none, so the hand-off pages it.
|
|
444
|
+
const conversation = event.timeline.length > 0 ? event.timeline : undefined;
|
|
445
|
+
const hit = adapter.detectLimit(turn);
|
|
446
|
+
if (hit) return this.handleUnavailable(context.paseo, agentId, family, conversation, { kind: "limit", hit });
|
|
447
|
+
if (adapter.detectSignOut(turn) && (await this.confirmSignedOut(agentId, family))) {
|
|
448
|
+
return this.handleUnavailable(context.paseo, agentId, family, conversation, { kind: "signed_out" });
|
|
411
449
|
}
|
|
412
450
|
}
|
|
413
451
|
if (this.deferred.has(agentId)) await this.finishDeferred(context.paseo, agentId, family);
|
|
@@ -415,10 +453,42 @@ export class Service {
|
|
|
415
453
|
if (accountId) void this.refreshUsage(accountId).catch(() => undefined);
|
|
416
454
|
}
|
|
417
455
|
|
|
456
|
+
/**
|
|
457
|
+
* Paseo 0.13 (getpaseo/paseo#7477) stopped copying the conversation into turn-ended hooks: `timeline`
|
|
458
|
+
* is always `[]`. Claude reports its limits as an ordinary reply, so when the hook arrives empty the
|
|
459
|
+
* tail of the agent's timeline is paged here and read as the turn. A hook that still sends the
|
|
460
|
+
* conversation (Paseo 0.12 and older) is used as is. A turn that never started (`turnId === null`)
|
|
461
|
+
* has nothing to read, as `notices()` in limits.ts ignores its timeline anyway, and a hook without
|
|
462
|
+
* a turn id gives nothing to tell its rows by. If the page can't be read within
|
|
463
|
+
* `TURN_READ_MS` the event stands: its failure is still read, and a switch waiting for the turn to
|
|
464
|
+
* end isn't held up.
|
|
465
|
+
*
|
|
466
|
+
* The page can reach back into earlier turns, and a later turn may have started by the time it's
|
|
467
|
+
* read, so only this turn's rows count (`turnRows()` in limits.ts): a turn Claude starts by itself
|
|
468
|
+
* has no message to stop at, and must not find the last turn's limit again. Paseo's
|
|
469
|
+
* `[System Error]` row carries no turn id, but it repeats the failure the hook still sends.
|
|
470
|
+
*/
|
|
471
|
+
private async turnWithTimeline(paseo: PaseoApi, event: TurnEnded): Promise<TurnEnded> {
|
|
472
|
+
const { turnId } = event;
|
|
473
|
+
if (!turnId || event.timeline.length > 0) return event;
|
|
474
|
+
try {
|
|
475
|
+
const page = await deadline(
|
|
476
|
+
paseo.agents.ref(event.agent.id).timeline.refetch({ direction: "tail", limit: 40 }),
|
|
477
|
+
TURN_READ_MS,
|
|
478
|
+
"Paseo didn't send the agent's timeline in time",
|
|
479
|
+
);
|
|
480
|
+
return { ...event, timeline: turnRows(page.entries, turnId) };
|
|
481
|
+
} catch (error) {
|
|
482
|
+
log(`could not read the last turn of ${event.agent.id}`, error);
|
|
483
|
+
return event;
|
|
484
|
+
}
|
|
485
|
+
}
|
|
486
|
+
|
|
418
487
|
async onAgentArchived(agentId: string): Promise<void> {
|
|
419
488
|
this.deferred.delete(agentId);
|
|
420
489
|
this.switchGuard.forget(agentId);
|
|
421
490
|
this.guardNoticeAt.delete(agentId);
|
|
491
|
+
this.guardNoticeAt.delete(`${agentId}:elsewhere`);
|
|
422
492
|
if (!(await this.store.read()).sessions[agentId]) return;
|
|
423
493
|
await this.store.update((draft) => {
|
|
424
494
|
delete draft.sessions[agentId];
|
|
@@ -457,10 +527,21 @@ export class Service {
|
|
|
457
527
|
paseo: PaseoApi,
|
|
458
528
|
agentId: string,
|
|
459
529
|
family: Family,
|
|
460
|
-
timeline: readonly AgentTimelineItem[],
|
|
530
|
+
timeline: readonly AgentTimelineItem[] | undefined,
|
|
461
531
|
problem: Problem,
|
|
462
532
|
): Promise<void> {
|
|
463
|
-
if (this.switching.has(agentId))
|
|
533
|
+
if (this.switching.has(agentId)) {
|
|
534
|
+
// A manual Codex handoff can race the old thread's limit event. Its account is immutable:
|
|
535
|
+
// remember the limit even though the ongoing handoff owns continuation dispatch.
|
|
536
|
+
if (!this.adapters[family].portable && problem.kind === "limit") {
|
|
537
|
+
const accountId = this.runningOn(await this.store.read(), agentId, family);
|
|
538
|
+
if (accountId && !this.recentlyRedeemed(accountId)) {
|
|
539
|
+
const hit = problem.hit;
|
|
540
|
+
await this.markLimited(accountId, hit.resetsAt ?? new Date(Date.now() + (hit.kind === "budget" ? BUDGET_LIMIT_MS : WINDOW_LIMIT_MS)).toISOString(), hit.kind);
|
|
541
|
+
}
|
|
542
|
+
}
|
|
543
|
+
return;
|
|
544
|
+
}
|
|
464
545
|
this.switching.add(agentId);
|
|
465
546
|
let exhausted: string | null = null;
|
|
466
547
|
try {
|
|
@@ -484,14 +565,26 @@ export class Service {
|
|
|
484
565
|
agentId: string,
|
|
485
566
|
family: Family,
|
|
486
567
|
account: StoredAccount,
|
|
487
|
-
timeline: readonly AgentTimelineItem[],
|
|
568
|
+
timeline: readonly AgentTimelineItem[] | undefined,
|
|
488
569
|
problem: Problem,
|
|
489
570
|
): Promise<void> {
|
|
490
571
|
const adapter = this.adapters[family];
|
|
491
572
|
const now = Date.now();
|
|
573
|
+
// A parked Codex tab stays stopped: its task carries on in another tab. A failed lookup must not
|
|
574
|
+
// stop the limit from being recorded below.
|
|
575
|
+
const elsewhere = adapter.portable
|
|
576
|
+
? null
|
|
577
|
+
: await this.continuations.continuesElsewhere(paseo, agentId).catch((error: unknown) => {
|
|
578
|
+
log(`could not find where ${agentId}'s task continues`, error);
|
|
579
|
+
return null;
|
|
580
|
+
});
|
|
492
581
|
if (problem.kind === "limit" && problem.hit.kind === "window" && this.recentlyRedeemed(account.id)) {
|
|
493
582
|
// This turn hit the limit just before a reset refilled it (another agent's failover or the
|
|
494
583
|
// user spent one moments ago). The account has room again: carry on instead of switching.
|
|
584
|
+
if (elsewhere) {
|
|
585
|
+
await this.noteElsewhere(paseo, agentId, account, "limit", null, elsewhere, "resume");
|
|
586
|
+
return;
|
|
587
|
+
}
|
|
495
588
|
console.log(`[ZeroSub] ${account.label} was just reset; ${agentId} carries on where it is`);
|
|
496
589
|
if (this.prefs.autoContinue && this.switchGuard.allows(agentId, now)) {
|
|
497
590
|
this.switchGuard.note(agentId, now);
|
|
@@ -525,6 +618,10 @@ export class Service {
|
|
|
525
618
|
}
|
|
526
619
|
|
|
527
620
|
if (!this.prefs.autoSwitch) return;
|
|
621
|
+
if (elsewhere) {
|
|
622
|
+
await this.noteElsewhere(paseo, agentId, account, problem.kind, resetsAt, elsewhere, "switch");
|
|
623
|
+
return;
|
|
624
|
+
}
|
|
528
625
|
const latest = await this.store.read();
|
|
529
626
|
if (this.runningOn(latest, agentId, family) !== account.id) return; // Already moved.
|
|
530
627
|
const base = {
|
|
@@ -541,8 +638,7 @@ export class Service {
|
|
|
541
638
|
if (!this.switchGuard.allows(agentId, now)) {
|
|
542
639
|
console.warn(`[ZeroSub] not switching ${agentId} again: it changed accounts ${this.switchGuard.limit} times in 10 minutes`);
|
|
543
640
|
// Say so once, so the user knows to pick an account rather than wait.
|
|
544
|
-
if (
|
|
545
|
-
this.guardNoticeAt.set(agentId, now);
|
|
641
|
+
if (this.noticeDue(agentId, now)) {
|
|
546
642
|
await this.appendRow(paseo, agentId, {
|
|
547
643
|
...base,
|
|
548
644
|
to: account.label,
|
|
@@ -676,11 +772,46 @@ export class Service {
|
|
|
676
772
|
to: next.label,
|
|
677
773
|
reason,
|
|
678
774
|
outcome: "stayed",
|
|
679
|
-
detail: `Couldn't
|
|
775
|
+
detail: `Couldn't continue on ${next.label}: ${describe(error)}`,
|
|
680
776
|
});
|
|
681
777
|
}
|
|
682
778
|
}
|
|
683
779
|
|
|
780
|
+
/** True once per guard window for each agent and notice, so repeated skips don't flood its timeline. */
|
|
781
|
+
private noticeDue(key: string, now: number): boolean {
|
|
782
|
+
if (now - (this.guardNoticeAt.get(key) ?? 0) <= this.switchGuard.windowMs) return false;
|
|
783
|
+
this.guardNoticeAt.set(key, now);
|
|
784
|
+
return true;
|
|
785
|
+
}
|
|
786
|
+
|
|
787
|
+
/** Says why ZeroSub left a parked Codex tab alone, instead of silently doing nothing. */
|
|
788
|
+
private async noteElsewhere(
|
|
789
|
+
paseo: PaseoApi,
|
|
790
|
+
agentId: string,
|
|
791
|
+
account: StoredAccount,
|
|
792
|
+
reason: "limit" | "signed_out",
|
|
793
|
+
resetsAt: string | null,
|
|
794
|
+
elsewhere: Continuation,
|
|
795
|
+
skipped: "switch" | "resume",
|
|
796
|
+
): Promise<void> {
|
|
797
|
+
console.log(`[ZeroSub] not ${skipped === "switch" ? "switching" : "resuming"} ${agentId} automatically: its task continues in ${elsewhere.agentId}`);
|
|
798
|
+
const now = Date.now();
|
|
799
|
+
if (!this.noticeDue(`${agentId}:elsewhere`, now)) return;
|
|
800
|
+
await this.appendRow(paseo, agentId, {
|
|
801
|
+
family: account.family,
|
|
802
|
+
from: account.label,
|
|
803
|
+
to: account.label,
|
|
804
|
+
reason,
|
|
805
|
+
resetsAt,
|
|
806
|
+
continued: false,
|
|
807
|
+
continuedIn: null,
|
|
808
|
+
toFamily: null,
|
|
809
|
+
outcome: "stayed",
|
|
810
|
+
detail: `This task continues in “${elsewhere.title}”, so ZeroSub didn't ${skipped} this tab automatically. Carry on there, or pick an account from the account button to continue from here.`,
|
|
811
|
+
at: new Date(now).toISOString(),
|
|
812
|
+
});
|
|
813
|
+
}
|
|
814
|
+
|
|
684
815
|
private async markLimited(accountId: string, until: string, kind: LimitKind): Promise<void> {
|
|
685
816
|
await this.store.update((draft) => {
|
|
686
817
|
const account = findAccount(draft, accountId);
|
|
@@ -765,6 +896,11 @@ export class Service {
|
|
|
765
896
|
if (this.runningOn(await this.store.read(), agentId, account.family) !== account.id) return false;
|
|
766
897
|
// Only resume an agent that this limit actually stopped.
|
|
767
898
|
if (!(await this.lastTurnHitLimit(paseo, agentId, account.family))) return false;
|
|
899
|
+
const elsewhere = this.adapters[account.family].portable ? null : await this.continuations.continuesElsewhere(paseo, agentId);
|
|
900
|
+
if (elsewhere) {
|
|
901
|
+
await this.noteElsewhere(paseo, agentId, account, "limit", null, elsewhere, "resume");
|
|
902
|
+
return false;
|
|
903
|
+
}
|
|
768
904
|
const at = new Date().toISOString();
|
|
769
905
|
await this.appendRow(paseo, agentId, {
|
|
770
906
|
family: account.family,
|
|
@@ -940,6 +1076,21 @@ export class Service {
|
|
|
940
1076
|
|
|
941
1077
|
/** "Continue on …" from an agent's account button: the same fork, asked for by the user. */
|
|
942
1078
|
async forkAgent(paseo: PaseoApi, agentId: string): Promise<Continuation> {
|
|
1079
|
+
return this.withSwitch(agentId, () => this.forkAgentNow(paseo, agentId));
|
|
1080
|
+
}
|
|
1081
|
+
|
|
1082
|
+
/** Manual continuations share the automatic failover guard, including cross-provider forks. */
|
|
1083
|
+
private async withSwitch<T>(agentId: string, action: () => Promise<T>): Promise<T> {
|
|
1084
|
+
if (this.switching.has(agentId)) throw new Error("This agent is already switching accounts. Wait for its handoff to finish.");
|
|
1085
|
+
this.switching.add(agentId);
|
|
1086
|
+
try {
|
|
1087
|
+
return await action();
|
|
1088
|
+
} finally {
|
|
1089
|
+
this.switching.delete(agentId);
|
|
1090
|
+
}
|
|
1091
|
+
}
|
|
1092
|
+
|
|
1093
|
+
private async forkAgentNow(paseo: PaseoApi, agentId: string): Promise<Continuation> {
|
|
943
1094
|
this.attach(paseo);
|
|
944
1095
|
const info = await agentInfo(paseo, agentId);
|
|
945
1096
|
if (!info || info.archived) throw new Error("That agent is no longer available.");
|
|
@@ -975,6 +1126,7 @@ export class Service {
|
|
|
975
1126
|
timeline: readonly AgentTimelineItem[] | undefined,
|
|
976
1127
|
source: "auto" | "user",
|
|
977
1128
|
): Promise<Continuation> {
|
|
1129
|
+
if (target.family === "codex") return this.continuations.continue(paseo, agentId, target, why, source);
|
|
978
1130
|
return continueInNewAgent({
|
|
979
1131
|
paseo,
|
|
980
1132
|
sourceAgentId: agentId,
|
|
@@ -1303,10 +1455,18 @@ export class Service {
|
|
|
1303
1455
|
if (!account) throw new Error("That account no longer exists.");
|
|
1304
1456
|
if (!account.signedIn) throw new Error(`${account.label} is signed out. Sign it in first.`);
|
|
1305
1457
|
if (account.disabled) throw new Error(`${account.label} is disabled. Enable it before making it the default.`);
|
|
1306
|
-
|
|
1458
|
+
const portable = this.adapters[account.family].portable;
|
|
1459
|
+
if (!portable) await this.pinThreads(paseo, account.family);
|
|
1307
1460
|
await this.store.update((draft) => {
|
|
1308
1461
|
draft.defaults[account.family] = account.id;
|
|
1309
1462
|
});
|
|
1463
|
+
if (portable && !this.prefs.moveAgentsOnDefaultChange) {
|
|
1464
|
+
// The new default is for what comes next: open agents stay on the account they run on.
|
|
1465
|
+
const { kept, moving } = await this.keepOpenAgents(paseo, account.family, account.id);
|
|
1466
|
+
console.log(`[ZeroSub] ${account.label} is the default now; ${kept} open agent(s) stay on their account`);
|
|
1467
|
+
// Agents that can't stay where they are move as they would with the switch on; nothing else does.
|
|
1468
|
+
return moving.length > 0 ? this.reconcile(paseo, "default", moving) : emptySummary();
|
|
1469
|
+
}
|
|
1310
1470
|
// Conversations that can't move (Codex threads) are pinned, so this only moves portable ones.
|
|
1311
1471
|
return this.reconcile(paseo, "default");
|
|
1312
1472
|
}
|
|
@@ -1366,6 +1526,50 @@ export class Service {
|
|
|
1366
1526
|
});
|
|
1367
1527
|
}
|
|
1368
1528
|
|
|
1529
|
+
/**
|
|
1530
|
+
* Pins each open agent that follows the default to the account it runs on, so the new default
|
|
1531
|
+
* doesn't move it, now or when it next opens. Runs once the new default is in place, so an agent
|
|
1532
|
+
* that opened under the old one just before is kept too, even if its session was still being
|
|
1533
|
+
* routed. Agents already on the new default keep following it. An account that's gone, signed
|
|
1534
|
+
* out, disabled or at its limit is no place to keep work, so those agents come back in `moving`.
|
|
1535
|
+
*/
|
|
1536
|
+
private async keepOpenAgents(
|
|
1537
|
+
paseo: PaseoApi,
|
|
1538
|
+
family: Family,
|
|
1539
|
+
newDefault: string,
|
|
1540
|
+
): Promise<{ kept: number; moving: string[] }> {
|
|
1541
|
+
// A session being routed may have gone by the old default: let it record where it opens first.
|
|
1542
|
+
if (this.routing.size > 0) await withTimeout(Promise.allSettled(this.routing.keys()), ROUTING_WAIT_MS);
|
|
1543
|
+
const families = await this.families.resolve(paseo);
|
|
1544
|
+
const open = (await listAgents(paseo, false)).agents.filter(
|
|
1545
|
+
(agent) => families[agent.provider] === family && !agent.archived && isLive(agent.status),
|
|
1546
|
+
);
|
|
1547
|
+
let kept = 0;
|
|
1548
|
+
const moving: string[] = [];
|
|
1549
|
+
if (open.length === 0) return { kept, moving };
|
|
1550
|
+
const now = Date.now();
|
|
1551
|
+
const at = new Date(now).toISOString();
|
|
1552
|
+
await this.store.update((draft) => {
|
|
1553
|
+
// Where these open isn't recorded yet, and a session routed now goes by the new default.
|
|
1554
|
+
const routing = new Set(this.routing.values());
|
|
1555
|
+
for (const agent of open) {
|
|
1556
|
+
if (routing.has(agent.id)) continue;
|
|
1557
|
+
// An agent with an account of its own never followed the default.
|
|
1558
|
+
if (findAccount(draft, draft.bindings[agent.id]?.accountId)?.family === family) continue;
|
|
1559
|
+
// Still starting, and not routed yet: it will be, by the new default.
|
|
1560
|
+
if (agent.status === "initializing" && !draft.sessions[agent.id]) continue;
|
|
1561
|
+
const current = findAccount(draft, this.runningOn(draft, agent.id, family));
|
|
1562
|
+
if (!current || current.family !== family || !isUsable(current, now)) moving.push(agent.id);
|
|
1563
|
+
else if (current.id !== newDefault) {
|
|
1564
|
+
// "auto", like a limit switch, so the account button still offers "Follow default".
|
|
1565
|
+
draft.bindings[agent.id] = { accountId: current.id, source: "auto", at };
|
|
1566
|
+
kept += 1;
|
|
1567
|
+
}
|
|
1568
|
+
}
|
|
1569
|
+
});
|
|
1570
|
+
return { kept, moving };
|
|
1571
|
+
}
|
|
1572
|
+
|
|
1369
1573
|
async clearLimit(accountId: string): Promise<void> {
|
|
1370
1574
|
const state = await this.store.update((draft) => {
|
|
1371
1575
|
const account = findAccount(draft, accountId);
|
|
@@ -1398,14 +1602,14 @@ export class Service {
|
|
|
1398
1602
|
const binding = state.bindings[agentId];
|
|
1399
1603
|
const current = binding?.source === "thread" ? binding.accountId : this.runningOn(state, agentId, family);
|
|
1400
1604
|
if (current === target.id) return emptySummary();
|
|
1401
|
-
const continuation = await this.continueElsewhere(
|
|
1605
|
+
const continuation = await this.withSwitch(agentId, () => this.continueElsewhere(
|
|
1402
1606
|
paseo,
|
|
1403
1607
|
agentId,
|
|
1404
1608
|
target,
|
|
1405
1609
|
`you moved the work to your ChatGPT account "${target.label}"`,
|
|
1406
1610
|
undefined,
|
|
1407
1611
|
"user",
|
|
1408
|
-
);
|
|
1612
|
+
));
|
|
1409
1613
|
await this.appendRow(paseo, agentId, {
|
|
1410
1614
|
family,
|
|
1411
1615
|
from: findAccount(state, current)?.label ?? null,
|
|
@@ -1731,6 +1935,15 @@ async function withTimeout(task: Promise<unknown>, ms: number): Promise<void> {
|
|
|
1731
1935
|
await Promise.race([task.catch(() => undefined), delay(ms)]);
|
|
1732
1936
|
}
|
|
1733
1937
|
|
|
1938
|
+
/** `task`, or a rejection with `message` once `ms` pass without it settling. */
|
|
1939
|
+
function deadline<T>(task: Promise<T>, ms: number, message: string): Promise<T> {
|
|
1940
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
1941
|
+
const expired = new Promise<never>((_, reject) => {
|
|
1942
|
+
timer = setTimeout(() => reject(new Error(message)), ms);
|
|
1943
|
+
});
|
|
1944
|
+
return Promise.race([task, expired]).finally(() => clearTimeout(timer));
|
|
1945
|
+
}
|
|
1946
|
+
|
|
1734
1947
|
function log(message: string, error: unknown): void {
|
|
1735
1948
|
console.error(`[ZeroSub] ${message}`, describe(error));
|
|
1736
1949
|
}
|
package/server/state.ts
CHANGED
|
@@ -33,7 +33,8 @@ export type StoredAccount = z.infer<typeof StoredAccountSchema>;
|
|
|
33
33
|
export const BindingSchema = z.object({
|
|
34
34
|
accountId: z.string(),
|
|
35
35
|
/**
|
|
36
|
-
* `user`: chosen in the UI. `auto`: moved after a limit
|
|
36
|
+
* `user`: chosen in the UI. `auto`: moved after a limit, or kept on its account when the default
|
|
37
|
+
* changed. `balance`: spread at creation.
|
|
37
38
|
* `thread`: a conversation that can't change accounts, pinned where it started.
|
|
38
39
|
*/
|
|
39
40
|
source: z.enum(["user", "auto", "balance", "thread"]),
|
|
@@ -48,6 +49,32 @@ export const LiveSessionSchema = z.object({
|
|
|
48
49
|
});
|
|
49
50
|
export type LiveSession = z.infer<typeof LiveSessionSchema>;
|
|
50
51
|
|
|
52
|
+
const TimelineMarkSchema = z.object({ epoch: z.string(), seq: z.number().int().nonnegative() });
|
|
53
|
+
const ContinuationMemberSchema = z.object({
|
|
54
|
+
accountId: z.string(),
|
|
55
|
+
identity: z.string().nullable(),
|
|
56
|
+
email: z.string().nullable(),
|
|
57
|
+
/** Timeline ranges already known by this tab; no conversation text is stored here. */
|
|
58
|
+
seen: z.record(z.string(), TimelineMarkSchema).default({}),
|
|
59
|
+
/** Reserved/created without a handoff; not a source of task history yet. */
|
|
60
|
+
unstarted: z.boolean().optional(),
|
|
61
|
+
});
|
|
62
|
+
export const ContinuationChainSchema = z.object({
|
|
63
|
+
activeAgentId: z.string(),
|
|
64
|
+
members: z.record(z.string(), ContinuationMemberSchema),
|
|
65
|
+
/** A full fallback that replaces history from deleted/moved tabs. */
|
|
66
|
+
baselineMessageId: z.string().optional(),
|
|
67
|
+
/** Written before dispatch. An uncertain dispatch must never start a second turn. */
|
|
68
|
+
pending: z.object({
|
|
69
|
+
agentId: z.string(),
|
|
70
|
+
messageId: z.string(),
|
|
71
|
+
seen: z.record(z.string(), TimelineMarkSchema),
|
|
72
|
+
stage: z.enum(["creating", "sending"]).default("sending"),
|
|
73
|
+
replaceHistory: z.array(z.string()).optional(),
|
|
74
|
+
}).optional(),
|
|
75
|
+
});
|
|
76
|
+
export type ContinuationChain = z.infer<typeof ContinuationChainSchema>;
|
|
77
|
+
|
|
51
78
|
export const StoredStateSchema = z.object({
|
|
52
79
|
version: z.literal(1).default(1),
|
|
53
80
|
accounts: z.array(StoredAccountSchema).default([]),
|
|
@@ -58,6 +85,7 @@ export const StoredStateSchema = z.object({
|
|
|
58
85
|
bindings: z.record(z.string(), BindingSchema).default({}),
|
|
59
86
|
/** Which account each agent's live provider session was opened with. */
|
|
60
87
|
sessions: z.record(z.string(), LiveSessionSchema).default({}),
|
|
88
|
+
continuations: z.record(z.string(), ContinuationChainSchema).default({}),
|
|
61
89
|
});
|
|
62
90
|
export type StoredState = z.infer<typeof StoredStateSchema>;
|
|
63
91
|
|
|
@@ -101,6 +129,7 @@ export function salvageState(raw: unknown): { state: StoredState; dropped: boole
|
|
|
101
129
|
defaults,
|
|
102
130
|
bindings: records(BindingSchema, source.bindings),
|
|
103
131
|
sessions: records(LiveSessionSchema, source.sessions),
|
|
132
|
+
continuations: records(ContinuationChainSchema, source.continuations),
|
|
104
133
|
},
|
|
105
134
|
dropped: true,
|
|
106
135
|
};
|
package/shared/preferences.ts
CHANGED
|
@@ -15,6 +15,13 @@ export const preferences = defineSettings({
|
|
|
15
15
|
/** After an automatic switch, send a follow-up so the interrupted turn keeps going. */
|
|
16
16
|
autoContinue: z.boolean().default(true),
|
|
17
17
|
continuePrompt: z.string().trim().min(1).max(500).default(DEFAULT_CONTINUE_PROMPT),
|
|
18
|
+
/**
|
|
19
|
+
* When the default account changes, open agents that follow it move to the new one. Off, each
|
|
20
|
+
* stays pinned to the account it runs on (so it stays there when it next opens too), unless that
|
|
21
|
+
* account can't be used right now, and the new default is for new agents and ones that aren't
|
|
22
|
+
* open at the time. Codex threads never move either way.
|
|
23
|
+
*/
|
|
24
|
+
moveAgentsOnDefaultChange: z.boolean().default(true),
|
|
18
25
|
/** New agents start on the account with the most headroom instead of the default. */
|
|
19
26
|
balanceNewAgents: z.boolean().default(false),
|
|
20
27
|
/** When every account of a provider is at its limit, spend a banked reset instead of stopping. */
|