@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
|
@@ -0,0 +1,576 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import type { PluginHookContext } from "@getpaseo/plugin/server";
|
|
3
|
+
import type { AgentTimelineItem } from "./adapter";
|
|
4
|
+
import { buildTranscript, CONTINUED_FROM_LABEL, continueInNewAgent, keepEnds, type Continuation } from "./handoff";
|
|
5
|
+
import { Mutex } from "./json-file";
|
|
6
|
+
import { isUsable } from "./routing";
|
|
7
|
+
import { findAccount, MAIN_ACCOUNT_ID, StateStore, type ContinuationChain, type StoredAccount, type StoredState } from "./state";
|
|
8
|
+
|
|
9
|
+
type PaseoApi = PluginHookContext["paseo"];
|
|
10
|
+
type Agent = NonNullable<Awaited<ReturnType<ReturnType<PaseoApi["agents"]["ref"]>["refresh"]>>>["agent"];
|
|
11
|
+
type Member = ContinuationChain["members"][string];
|
|
12
|
+
type Pending = NonNullable<ContinuationChain["pending"]>;
|
|
13
|
+
type Mark = Member["seen"][string];
|
|
14
|
+
type Source = "auto" | "user";
|
|
15
|
+
type Update = { item: AgentTimelineItem; timestamp: string };
|
|
16
|
+
const MESSAGE_PREFIX = "zerosub-handoff-";
|
|
17
|
+
const MAX_PAGES = 100;
|
|
18
|
+
const MAX_INSTRUCTIONS = 60_000;
|
|
19
|
+
const MAX_ORIGIN = 6_000;
|
|
20
|
+
const OMITTED = "[… part of this message omitted to fit this update …]";
|
|
21
|
+
|
|
22
|
+
/** The same checkout. Paseo starts a workspace's new agents in its directory, not the source's subfolder. */
|
|
23
|
+
function samePlace(left: Agent, right: Agent): boolean {
|
|
24
|
+
if (left.provider !== right.provider || left.workspaceId !== right.workspaceId) return false;
|
|
25
|
+
return Boolean(left.workspaceId) || left.cwd === right.cwd;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function ready(agent: Agent): boolean {
|
|
29
|
+
return !agent.archivedAt && !agent.providerUnavailable && !agent.activeTurn &&
|
|
30
|
+
!agent.pendingPermissions?.length && (agent.status === "idle" || agent.status === "closed" || agent.status === "error");
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function busy(agent: Agent): boolean {
|
|
34
|
+
return agent.status === "running" || agent.status === "initializing" || Boolean(agent.activeTurn);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** Still ready, in the same place and mode, and nobody has sent it another message. */
|
|
38
|
+
function untouched(before: Agent, now: Agent | undefined): boolean {
|
|
39
|
+
return now !== undefined && ready(now) && samePlace(before, now) &&
|
|
40
|
+
now.currentModeId === before.currentModeId && now.lastUserMessageAt === before.lastUserMessageAt;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** Pinned to the account, and not already running on another one. */
|
|
44
|
+
function boundTo(state: StoredState, agentId: string, accountId: string): boolean {
|
|
45
|
+
const session = state.sessions[agentId];
|
|
46
|
+
return state.bindings[agentId]?.accountId === accountId && (!session || session.accountId === accountId);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** The account still exists, can take work and is still signed in as the same person. */
|
|
50
|
+
function stillUsable(state: StoredState, account: StoredAccount): boolean {
|
|
51
|
+
const current = findAccount(state, account.id);
|
|
52
|
+
return current !== undefined && isUsable(current, Date.now()) && current.identity === account.identity && current.email === account.email;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function member(account: StoredAccount): Member {
|
|
56
|
+
return { accountId: account.id, identity: account.identity, email: account.email, seen: {} };
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function chainOf(state: StoredState, agentId: string): string | undefined {
|
|
60
|
+
return Object.keys(state.continuations).find((id) => state.continuations[id]?.members[agentId]);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
async function snapshot(paseo: PaseoApi, agentId: string): Promise<Agent | undefined> {
|
|
64
|
+
return (await paseo.agents.ref(agentId).refresh())?.agent;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** Commit exactly the reserved context, whether the acknowledgement arrived normally or on retry. */
|
|
68
|
+
function completeHandoff(chain: ContinuationChain): void {
|
|
69
|
+
const pending = chain.pending!;
|
|
70
|
+
chain.members[pending.agentId]!.seen = pending.seen;
|
|
71
|
+
delete chain.members[pending.agentId]!.unstarted;
|
|
72
|
+
chain.activeAgentId = pending.agentId;
|
|
73
|
+
if (pending.replaceHistory) {
|
|
74
|
+
chain.baselineMessageId = pending.messageId;
|
|
75
|
+
for (const id of pending.replaceHistory) {
|
|
76
|
+
delete chain.members[id];
|
|
77
|
+
for (const entry of Object.values(chain.members)) delete entry.seen[id];
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
delete chain.pending;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** Where the handoff goes: an existing tab for the account, or a new (possibly reserved) one. */
|
|
84
|
+
interface Destination {
|
|
85
|
+
targetId: string;
|
|
86
|
+
/** The existing tab, when there is one. */
|
|
87
|
+
agent?: Agent;
|
|
88
|
+
entry?: Member;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** What the destination hasn't seen yet, and the timeline marks to record once it has. */
|
|
92
|
+
interface Gathered {
|
|
93
|
+
updates: Update[];
|
|
94
|
+
seen: Record<string, Mark>;
|
|
95
|
+
/** An earlier tab is gone or moved, so the source's own history stands in for the task's. */
|
|
96
|
+
fallback: boolean;
|
|
97
|
+
/** Members whose history the fallback replaces. */
|
|
98
|
+
obsolete: string[];
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** Codex keeps one account-bound thread per task/account. All dispatches share the chain lock. */
|
|
102
|
+
export class CodexContinuations {
|
|
103
|
+
private readonly locks = new Map<string, { mutex: Mutex; users: number }>();
|
|
104
|
+
private readonly inFlight = new Map<string, Promise<Continuation>>();
|
|
105
|
+
|
|
106
|
+
constructor(private readonly store: StateStore) {}
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* Automatic follow-ups (including banked resets) must not wake a parked task tab. Returns the tab
|
|
110
|
+
* the task continues in when that isn't this one, else null.
|
|
111
|
+
*/
|
|
112
|
+
async continuesElsewhere(paseo: PaseoApi, agentId: string): Promise<Continuation | null> {
|
|
113
|
+
const chain = Object.values((await this.store.read()).continuations).find((entry) => entry.members[agentId]);
|
|
114
|
+
if (!chain) return null;
|
|
115
|
+
const { pending } = chain;
|
|
116
|
+
if (pending?.stage === "sending") {
|
|
117
|
+
// Only a hand-off whose prompt may have reached a live tab holds the task. A failed creation
|
|
118
|
+
// sent nothing, and an archived or deleted destination has been given up.
|
|
119
|
+
const target = await snapshot(paseo, pending.agentId);
|
|
120
|
+
if (target && !target.archivedAt) return pending.agentId === agentId ? null : { agentId: pending.agentId, title: target.title ?? "Codex task" };
|
|
121
|
+
}
|
|
122
|
+
const current = await currentTab(paseo, chain, agentId);
|
|
123
|
+
return current.id === agentId ? null : { agentId: current.id, title: current.agent?.title ?? "Codex task" };
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
continue(paseo: PaseoApi, sourceAgentId: string, target: StoredAccount, why: string, source: Source): Promise<Continuation> {
|
|
127
|
+
const key = `${sourceAgentId}:${target.id}`;
|
|
128
|
+
const existing = this.inFlight.get(key);
|
|
129
|
+
if (existing) return existing;
|
|
130
|
+
const task = this.dispatch(paseo, sourceAgentId, target, why, source).finally(() => this.inFlight.delete(key));
|
|
131
|
+
this.inFlight.set(key, task);
|
|
132
|
+
return task;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
private async dispatch(paseo: PaseoApi, sourceAgentId: string, target: StoredAccount, why: string, source: Source): Promise<Continuation> {
|
|
136
|
+
const original = await snapshot(paseo, sourceAgentId);
|
|
137
|
+
if (!original || original.archivedAt) throw new Error("The original agent is no longer available.");
|
|
138
|
+
const { root, ancestors } = await findTask(paseo, await this.store.read(), original);
|
|
139
|
+
return this.locked(root, async () => {
|
|
140
|
+
const chain = await this.openChain(root, ancestors, sourceAgentId);
|
|
141
|
+
if (!chain.members[sourceAgentId]) throw new Error("This older continuation isn't part of the active task. Switch from the task's current tab.");
|
|
142
|
+
const settled = await this.settlePending(paseo, root, chain, target);
|
|
143
|
+
if ("done" in settled) return settled.done;
|
|
144
|
+
const { reserved } = settled;
|
|
145
|
+
if (source === "auto") await checkCurrent(paseo, chain, sourceAgentId);
|
|
146
|
+
const sourceAgent = await waitForSource(paseo, original, source);
|
|
147
|
+
const state = await this.store.read();
|
|
148
|
+
const account = findAccount(state, target.id);
|
|
149
|
+
if (!account || account.family !== "codex" || !isUsable(account, Date.now())) {
|
|
150
|
+
throw new Error("That ChatGPT account is no longer available. Enable it, sign in or wait for its limit to reset.");
|
|
151
|
+
}
|
|
152
|
+
const snapshots = await memberSnapshots(paseo, chain, sourceAgent);
|
|
153
|
+
const destination = pickDestination(state, chain, snapshots, sourceAgent, account, reserved);
|
|
154
|
+
const gathered = await gatherUpdates(paseo, state, chain, snapshots, sourceAgent, destination);
|
|
155
|
+
const prompt = composePrompt(chain, destination, gathered, why, Boolean(reserved));
|
|
156
|
+
const messageId = reserved?.messageId ?? `${MESSAGE_PREFIX}${randomUUID()}`;
|
|
157
|
+
await this.confirmUnchanged(paseo, sourceAgent, destination, account);
|
|
158
|
+
await this.reserve(root, sourceAgent.id, destination, gathered, account, messageId, source);
|
|
159
|
+
return this.deliver(paseo, root, sourceAgent, destination, account, prompt, messageId, why);
|
|
160
|
+
});
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/** One dispatch per task at a time; the lock is dropped once nobody waits on it. */
|
|
164
|
+
private locked<T>(root: string, section: () => Promise<T>): Promise<T> {
|
|
165
|
+
let lock = this.locks.get(root);
|
|
166
|
+
if (!lock) this.locks.set(root, (lock = { mutex: new Mutex(), users: 0 }));
|
|
167
|
+
lock.users += 1;
|
|
168
|
+
return lock.mutex.run(section).finally(() => {
|
|
169
|
+
if (--lock.users === 0) this.locks.delete(root);
|
|
170
|
+
});
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/** The task's record, created from the discovered tabs on the first switch. */
|
|
174
|
+
private async openChain(root: string, ancestors: Agent[], sourceAgentId: string): Promise<ContinuationChain> {
|
|
175
|
+
const existing = (await this.store.read()).continuations[root];
|
|
176
|
+
if (existing) return existing;
|
|
177
|
+
const next = await this.store.update((draft) => {
|
|
178
|
+
const members: ContinuationChain["members"] = {};
|
|
179
|
+
for (const agent of [...ancestors].reverse()) {
|
|
180
|
+
// A tab with no recorded session runs on the CLI login; pin it there so reuse stays exact.
|
|
181
|
+
const account = findAccount(draft, draft.sessions[agent.id]?.accountId ?? draft.bindings[agent.id]?.accountId ?? MAIN_ACCOUNT_ID.codex);
|
|
182
|
+
if (account?.family === "codex") {
|
|
183
|
+
members[agent.id] = member(account);
|
|
184
|
+
draft.bindings[agent.id] ??= { accountId: account.id, source: "thread", at: new Date().toISOString() };
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
if (!members[sourceAgentId]) throw new Error("Couldn't establish this Codex thread's account. Reopen it before switching.");
|
|
188
|
+
draft.continuations[root] = { activeAgentId: sourceAgentId, members };
|
|
189
|
+
});
|
|
190
|
+
return next.continuations[root]!;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/**
|
|
194
|
+
* Resolves a handoff an earlier call reserved but didn't finish. A disconnected RPC can have
|
|
195
|
+
* delivered its prompt, so never resend it or create another tab.
|
|
196
|
+
*/
|
|
197
|
+
private async settlePending(
|
|
198
|
+
paseo: PaseoApi,
|
|
199
|
+
root: string,
|
|
200
|
+
chain: ContinuationChain,
|
|
201
|
+
target: StoredAccount,
|
|
202
|
+
): Promise<{ done: Continuation } | { reserved?: Pending }> {
|
|
203
|
+
const pending = chain.pending;
|
|
204
|
+
if (!pending) return {};
|
|
205
|
+
const agent = await snapshot(paseo, pending.agentId);
|
|
206
|
+
const release = () => this.store.update((draft) => { delete draft.continuations[root]!.pending; });
|
|
207
|
+
if (pending.stage === "creating") {
|
|
208
|
+
if (!agent?.archivedAt && chain.members[pending.agentId]?.accountId === target.id) {
|
|
209
|
+
// No prompt is sent during creation, so retrying this same idempotent creation is safe.
|
|
210
|
+
if (agent?.lastUserMessageAt) throw new Error(`The unstarted tab ${agent.id} received another message. Check it and archive it before retrying.`);
|
|
211
|
+
return { reserved: pending };
|
|
212
|
+
}
|
|
213
|
+
// Nothing was sent, so dropping the reservation cannot duplicate work. Keep its tab for later reuse.
|
|
214
|
+
await release();
|
|
215
|
+
return {};
|
|
216
|
+
}
|
|
217
|
+
if (agent && !agent.archivedAt) {
|
|
218
|
+
const history = await readUpdates(paseo, pending.agentId, undefined, pending.messageId);
|
|
219
|
+
if (history.entries.some((entry) => delivered(entry, pending.messageId))) {
|
|
220
|
+
await this.store.update((draft) => completeHandoff(draft.continuations[root]!));
|
|
221
|
+
return { done: { agentId: agent.id, title: agent.title ?? "Codex task" } };
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
if (!agent || agent.archivedAt) {
|
|
225
|
+
// The user gave that tab up; it can't run the prompt any more. Automatic switches may carry on too.
|
|
226
|
+
await release();
|
|
227
|
+
return {};
|
|
228
|
+
}
|
|
229
|
+
if (busy(agent)) throw new Error("The previous handoff may still be starting. Wait for that tab to stop, then retry.");
|
|
230
|
+
throw new Error(`The previous handoff to ${pending.agentId} could not be confirmed. Check that tab; archive it before retrying the switch.`);
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
/** Last look before reserving: nothing may have changed while the update was being read. */
|
|
234
|
+
private async confirmUnchanged(paseo: PaseoApi, sourceAgent: Agent, destination: Destination, account: StoredAccount): Promise<void> {
|
|
235
|
+
const sourceNow = await snapshot(paseo, sourceAgent.id);
|
|
236
|
+
const targetNow = destination.agent && await snapshot(paseo, destination.targetId);
|
|
237
|
+
const state = await this.store.read();
|
|
238
|
+
const sourceOk = untouched(sourceAgent, sourceNow);
|
|
239
|
+
const targetOk = !destination.agent || (untouched(destination.agent, targetNow) && boundTo(state, destination.targetId, account.id));
|
|
240
|
+
if (!sourceOk || !targetOk || !stillUsable(state, account)) {
|
|
241
|
+
throw new Error("The task or account changed during the handoff. Check the active tab and try again.");
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
/** Reserve before either SDK operation: a crash or uncertain reply must not duplicate work. */
|
|
246
|
+
private async reserve(
|
|
247
|
+
root: string,
|
|
248
|
+
sourceAgentId: string,
|
|
249
|
+
destination: Destination,
|
|
250
|
+
gathered: Gathered,
|
|
251
|
+
account: StoredAccount,
|
|
252
|
+
messageId: string,
|
|
253
|
+
source: Source,
|
|
254
|
+
): Promise<void> {
|
|
255
|
+
const { targetId } = destination;
|
|
256
|
+
await this.store.update((draft) => {
|
|
257
|
+
const current = draft.continuations[root]!;
|
|
258
|
+
if (!destination.agent) current.members[targetId] = { ...member(account), unstarted: true };
|
|
259
|
+
current.pending = {
|
|
260
|
+
agentId: targetId,
|
|
261
|
+
messageId,
|
|
262
|
+
seen: gathered.seen,
|
|
263
|
+
stage: destination.agent ? "sending" : "creating",
|
|
264
|
+
...(gathered.fallback ? { replaceHistory: gathered.obsolete } : {}),
|
|
265
|
+
};
|
|
266
|
+
if (!destination.agent) draft.bindings[targetId] = { accountId: account.id, source: source === "user" ? "user" : "thread", at: new Date().toISOString() };
|
|
267
|
+
});
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
/** Creates the tab if needed (without a prompt), then sends the update under its reserved ID. */
|
|
271
|
+
private async deliver(
|
|
272
|
+
paseo: PaseoApi,
|
|
273
|
+
root: string,
|
|
274
|
+
sourceAgent: Agent,
|
|
275
|
+
destination: Destination,
|
|
276
|
+
account: StoredAccount,
|
|
277
|
+
prompt: string,
|
|
278
|
+
messageId: string,
|
|
279
|
+
why: string,
|
|
280
|
+
): Promise<Continuation> {
|
|
281
|
+
const { targetId } = destination;
|
|
282
|
+
let result: Continuation;
|
|
283
|
+
if (destination.agent) {
|
|
284
|
+
result = { agentId: targetId, title: destination.agent.title ?? "Codex task" };
|
|
285
|
+
} else {
|
|
286
|
+
result = await continueInNewAgent({ paseo, sourceAgentId: sourceAgent.id, why, agentId: targetId, deferPrompt: true, bind: async () => {} });
|
|
287
|
+
// Creation can take time. A user may have started another turn or disabled the account.
|
|
288
|
+
const created = await waitForCreated(paseo, targetId);
|
|
289
|
+
const sourceNow = await snapshot(paseo, sourceAgent.id);
|
|
290
|
+
const state = await this.store.read();
|
|
291
|
+
const createdOk = created !== undefined && ready(created) && samePlace(sourceAgent, created) && !created.lastUserMessageAt &&
|
|
292
|
+
created.currentModeId === sourceAgent.currentModeId && boundTo(state, targetId, account.id);
|
|
293
|
+
if (!untouched(sourceAgent, sourceNow) || !createdOk || !stillUsable(state, account)) {
|
|
294
|
+
throw new Error("The task or account changed while its tab was being created. Check the active tab and retry the switch.");
|
|
295
|
+
}
|
|
296
|
+
await this.store.update((draft) => { draft.continuations[root]!.pending!.stage = "sending"; });
|
|
297
|
+
}
|
|
298
|
+
await paseo.agents.ref(targetId).send(prompt, { messageId });
|
|
299
|
+
await this.store.update((draft) => completeHandoff(draft.continuations[root]!));
|
|
300
|
+
return result;
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
/**
|
|
305
|
+
* Finds the task a tab belongs to. Only ancestors carrying ZeroSub's continuation label count, so
|
|
306
|
+
* unrelated agents in the same workspace (even on the same account) never join this task.
|
|
307
|
+
*/
|
|
308
|
+
async function findTask(paseo: PaseoApi, state: StoredState, original: Agent): Promise<{ root: string; ancestors: Agent[] }> {
|
|
309
|
+
let root = chainOf(state, original.id);
|
|
310
|
+
const ancestors: Agent[] = [original];
|
|
311
|
+
if (!root) {
|
|
312
|
+
let parent = original.labels?.[CONTINUED_FROM_LABEL];
|
|
313
|
+
while (parent && !ancestors.some((agent) => agent.id === parent)) {
|
|
314
|
+
const agent = await snapshot(paseo, parent);
|
|
315
|
+
if (!agent || !samePlace(original, agent)) break;
|
|
316
|
+
ancestors.push(agent);
|
|
317
|
+
root = chainOf(state, agent.id);
|
|
318
|
+
if (root) break;
|
|
319
|
+
parent = agent.labels?.[CONTINUED_FROM_LABEL];
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
root ??= ancestors.at(-1)!.id;
|
|
323
|
+
if (!state.continuations[root]) await adoptDescendants(paseo, original, ancestors);
|
|
324
|
+
return { root, ancestors };
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
/**
|
|
328
|
+
* Adopts existing descendants too: switching from the original tab after upgrading mustn't create
|
|
329
|
+
* a second B tab just because B's label points towards A rather than the other way. This pages
|
|
330
|
+
* through every agent, archived ones included, but only once per task: the record exists afterwards.
|
|
331
|
+
*/
|
|
332
|
+
async function adoptDescendants(paseo: PaseoApi, original: Agent, ancestors: Agent[]): Promise<void> {
|
|
333
|
+
const related: Agent[] = [];
|
|
334
|
+
let cursor: string | undefined;
|
|
335
|
+
for (let page = 0; ; page += 1) {
|
|
336
|
+
if (page >= MAX_PAGES) throw new Error("Couldn't find all existing continuation tabs. Check this task's tabs before retrying.");
|
|
337
|
+
const result = await paseo.agents.list({ filter: { includeArchived: true }, page: { limit: 200, ...(cursor ? { cursor } : {}) } });
|
|
338
|
+
related.push(...result.entries.map(({ agent }) => agent).filter((agent) => samePlace(original, agent)));
|
|
339
|
+
if (!result.pageInfo.hasMore || !result.pageInfo.nextCursor) break;
|
|
340
|
+
cursor = result.pageInfo.nextCursor;
|
|
341
|
+
}
|
|
342
|
+
const known = (id: string | undefined) => ancestors.some((entry) => entry.id === id);
|
|
343
|
+
for (let added = true; added;) {
|
|
344
|
+
added = false;
|
|
345
|
+
for (const agent of related) {
|
|
346
|
+
if (!known(agent.id) && known(agent.labels?.[CONTINUED_FROM_LABEL])) {
|
|
347
|
+
ancestors.unshift(agent);
|
|
348
|
+
added = true;
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
function newer(left: string | null | undefined, right: string | null | undefined): boolean {
|
|
355
|
+
return left ? !right || Date.parse(left) > Date.parse(right) : false;
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
/**
|
|
359
|
+
* The tab the task continues in: the last handoff's destination, unless the user has since typed
|
|
360
|
+
* in another of the task's tabs. That tab has taken the task over; its new messages are part of it.
|
|
361
|
+
* An archived or deleted destination doesn't hold the task: the most recently used tab left does,
|
|
362
|
+
* starting from the asking tab, which is current when no other tab is left. Neither does a tab
|
|
363
|
+
* moved to another workspace: it has left the task.
|
|
364
|
+
*/
|
|
365
|
+
async function currentTab(paseo: PaseoApi, chain: ContinuationChain, askingId: string): Promise<{ id: string; agent?: Agent }> {
|
|
366
|
+
const asking = await snapshot(paseo, askingId);
|
|
367
|
+
const active = chain.activeAgentId === askingId ? asking : await snapshot(paseo, chain.activeAgentId);
|
|
368
|
+
const place = asking ?? active;
|
|
369
|
+
const usable = (agent: Agent | undefined): agent is Agent => agent !== undefined && !agent.archivedAt && (!place || samePlace(place, agent));
|
|
370
|
+
let current = usable(active) ? { id: chain.activeAgentId, agent: active } : usable(asking) ? { id: askingId, agent: asking } : undefined;
|
|
371
|
+
for (const [id, entry] of Object.entries(chain.members)) {
|
|
372
|
+
if (id === current?.id || entry.unstarted) continue;
|
|
373
|
+
const agent = await snapshot(paseo, id);
|
|
374
|
+
if (usable(agent) && (!current || newer(agent.lastUserMessageAt, current.agent.lastUserMessageAt))) current = { id, agent };
|
|
375
|
+
}
|
|
376
|
+
return current ?? { id: askingId };
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
/**
|
|
380
|
+
* Automatic switches only move the task's current tab. The user may switch from any of its tabs:
|
|
381
|
+
* the destination gets every other tab's updates, so nothing is lost either way.
|
|
382
|
+
*/
|
|
383
|
+
async function checkCurrent(paseo: PaseoApi, chain: ContinuationChain, sourceAgentId: string): Promise<void> {
|
|
384
|
+
const current = await currentTab(paseo, chain, sourceAgentId);
|
|
385
|
+
if (current.id !== sourceAgentId) {
|
|
386
|
+
throw new Error(`This task now continues in “${current.agent?.title ?? current.id}”. Switch accounts from that tab.`);
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
/** The source must have stopped, without a newer message than the one that asked for the switch. */
|
|
391
|
+
async function waitForSource(paseo: PaseoApi, original: Agent, source: Source): Promise<Agent> {
|
|
392
|
+
let agent = await snapshot(paseo, original.id);
|
|
393
|
+
// turn_ended can arrive just before the directory reports idle, as in the existing reopener.
|
|
394
|
+
for (let attempt = 0; source === "auto" && agent && attempt < 20 && (agent.status === "running" || agent.status === "initializing"); attempt += 1) {
|
|
395
|
+
await new Promise((resolve) => setTimeout(resolve, 300));
|
|
396
|
+
agent = await snapshot(paseo, original.id);
|
|
397
|
+
}
|
|
398
|
+
if (!agent || !ready(agent)) throw new Error("Wait for the current agent to stop before switching accounts.");
|
|
399
|
+
if (agent.lastUserMessageAt !== original.lastUserMessageAt) {
|
|
400
|
+
throw new Error("The agent received another message while waiting to switch. Check the current turn before retrying.");
|
|
401
|
+
}
|
|
402
|
+
return agent;
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
/** A tab created without a prompt can still report initializing for a moment before it is idle. */
|
|
406
|
+
async function waitForCreated(paseo: PaseoApi, agentId: string): Promise<Agent | undefined> {
|
|
407
|
+
let agent = await snapshot(paseo, agentId);
|
|
408
|
+
for (let attempt = 0; agent?.status === "initializing" && attempt < 20; attempt += 1) {
|
|
409
|
+
await new Promise((resolve) => setTimeout(resolve, 300));
|
|
410
|
+
agent = await snapshot(paseo, agentId);
|
|
411
|
+
}
|
|
412
|
+
return agent;
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
/** Current snapshots of the task's tabs; none of them may be working while the task moves. */
|
|
416
|
+
async function memberSnapshots(paseo: PaseoApi, chain: ContinuationChain, sourceAgent: Agent): Promise<Map<string, Agent>> {
|
|
417
|
+
const snapshots = new Map<string, Agent>();
|
|
418
|
+
for (const id of Object.keys(chain.members)) {
|
|
419
|
+
const agent = await snapshot(paseo, id);
|
|
420
|
+
if (!agent) continue;
|
|
421
|
+
snapshots.set(id, agent);
|
|
422
|
+
if (samePlace(sourceAgent, agent) && !agent.archivedAt && (busy(agent) || agent.pendingPermissions?.length)) {
|
|
423
|
+
throw new Error("Another tab in this task is working or waiting for permission. Finish or stop it before switching.");
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
return snapshots;
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
/** Reuse the task's tab for this account when it's still exactly that account's, else make one. */
|
|
430
|
+
function pickDestination(
|
|
431
|
+
state: StoredState,
|
|
432
|
+
chain: ContinuationChain,
|
|
433
|
+
snapshots: Map<string, Agent>,
|
|
434
|
+
sourceAgent: Agent,
|
|
435
|
+
account: StoredAccount,
|
|
436
|
+
reserved: Pending | undefined,
|
|
437
|
+
): Destination {
|
|
438
|
+
const candidate = Object.entries(chain.members).find(([id, entry]) => {
|
|
439
|
+
const agent = snapshots.get(id);
|
|
440
|
+
return id !== sourceAgent.id && entry.accountId === account.id && entry.identity !== null && entry.identity === account.identity &&
|
|
441
|
+
entry.email === account.email && boundTo(state, id, account.id) &&
|
|
442
|
+
agent !== undefined && samePlace(sourceAgent, agent) && !agent.archivedAt && !agent.providerUnavailable;
|
|
443
|
+
});
|
|
444
|
+
if (reserved && snapshots.has(reserved.agentId) && candidate?.[0] !== reserved.agentId) {
|
|
445
|
+
throw new Error(`The reserved tab ${reserved.agentId} changed identity or location. Check it and archive it before retrying.`);
|
|
446
|
+
}
|
|
447
|
+
if (!candidate) return { targetId: reserved?.agentId ?? randomUUID() };
|
|
448
|
+
const [targetId, entry] = candidate;
|
|
449
|
+
const agent = snapshots.get(targetId)!;
|
|
450
|
+
if (entry.unstarted && agent.lastUserMessageAt) {
|
|
451
|
+
throw new Error(`The unstarted tab ${targetId} received another message. Check it and archive it before retrying.`);
|
|
452
|
+
}
|
|
453
|
+
if (!ready(agent)) throw new Error("The account's existing tab isn't ready to continue. Check it before switching.");
|
|
454
|
+
if (agent.currentModeId !== sourceAgent.currentModeId) {
|
|
455
|
+
throw new Error(`The existing tab ${targetId} has a different permission mode. Align its mode with the current tab before switching.`);
|
|
456
|
+
}
|
|
457
|
+
// Anything the user typed in this tab while it was parked is part of the task; it already knows it.
|
|
458
|
+
return { targetId, agent, entry };
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
/** Reads every other tab's timeline since the destination last saw it. */
|
|
462
|
+
async function gatherUpdates(
|
|
463
|
+
paseo: PaseoApi,
|
|
464
|
+
state: StoredState,
|
|
465
|
+
chain: ContinuationChain,
|
|
466
|
+
snapshots: Map<string, Agent>,
|
|
467
|
+
sourceAgent: Agent,
|
|
468
|
+
destination: Destination,
|
|
469
|
+
): Promise<Gathered> {
|
|
470
|
+
const { targetId } = destination;
|
|
471
|
+
const known = destination.entry?.seen ?? {};
|
|
472
|
+
// A deleted or moved tab must not strand the task or leak a different task's new history.
|
|
473
|
+
const lost = (id: string) => {
|
|
474
|
+
const agent = snapshots.get(id);
|
|
475
|
+
return !agent || !samePlace(sourceAgent, agent) || state.bindings[id]?.accountId !== chain.members[id]!.accountId;
|
|
476
|
+
};
|
|
477
|
+
const others = Object.keys(chain.members).filter((id) => id !== targetId && !chain.members[id]!.unstarted);
|
|
478
|
+
const obsolete = others.filter((id) => id !== sourceAgent.id && lost(id));
|
|
479
|
+
if (others.some(lost)) {
|
|
480
|
+
// The current source already received the earlier work in its last successful handoff.
|
|
481
|
+
// Marks for the deltas this replaces are discarded as well.
|
|
482
|
+
const history = await readUpdates(paseo, sourceAgent.id);
|
|
483
|
+
return { updates: byTime(history.entries), seen: { ...known, [sourceAgent.id]: history.mark }, fallback: true, obsolete };
|
|
484
|
+
}
|
|
485
|
+
const seen = { ...known };
|
|
486
|
+
const updates: Update[] = [];
|
|
487
|
+
for (const id of others) {
|
|
488
|
+
const delta = await readUpdates(paseo, id, seen[id]);
|
|
489
|
+
seen[id] = delta.mark;
|
|
490
|
+
updates.push(...delta.entries);
|
|
491
|
+
}
|
|
492
|
+
return { updates: byTime(updates), seen, fallback: false, obsolete };
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
function byTime(updates: Update[]): Update[] {
|
|
496
|
+
return updates.sort((a, b) => a.timestamp.localeCompare(b.timestamp));
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
/** ZeroSub's own earlier handoff prompts, which the destination mustn't receive again. */
|
|
500
|
+
function ownHandoff(item: Extract<AgentTimelineItem, { type: "user_message" }>, chain: ContinuationChain): boolean {
|
|
501
|
+
if (chain.baselineMessageId !== undefined && item.clientMessageId === chain.baselineMessageId) return false;
|
|
502
|
+
if (item.clientMessageId?.startsWith(MESSAGE_PREFIX)) return true;
|
|
503
|
+
// Older releases didn't assign message IDs to their full-transcript handoffs.
|
|
504
|
+
return Object.keys(chain.members).length > 1 && item.text.startsWith("This task is continuing from an earlier Codex session that stopped because");
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
/**
|
|
508
|
+
* Every pending user instruction when they fit; the tool/assistant recap is clipped separately.
|
|
509
|
+
* Otherwise the first one (the original request, for a new tab) and as many of the most recent as
|
|
510
|
+
* fit, saying how many were left out. Pasted logs mustn't stop a task from moving on.
|
|
511
|
+
*/
|
|
512
|
+
export function fitInstructions(texts: string[], max = MAX_INSTRUCTIONS): string {
|
|
513
|
+
const all = texts.join("\n\n");
|
|
514
|
+
if (all.length <= max) return all;
|
|
515
|
+
const [first = "", ...rest] = texts;
|
|
516
|
+
if (!rest.length) return keepEnds(first, max, OMITTED);
|
|
517
|
+
const head = keepEnds(first, MAX_ORIGIN, OMITTED);
|
|
518
|
+
let room = max - head.length - 100; // Leaves space for the note below.
|
|
519
|
+
const recent: string[] = [];
|
|
520
|
+
for (let index = rest.length - 1; index >= 0 && room > 0; index -= 1) {
|
|
521
|
+
const text = rest[index]!;
|
|
522
|
+
if (text.length + 2 > room && recent.length) break;
|
|
523
|
+
// The latest instruction always stays, shortened if it alone is too long.
|
|
524
|
+
const kept = text.length + 2 > room ? keepEnds(text, room - 2, OMITTED) : text;
|
|
525
|
+
recent.unshift(kept);
|
|
526
|
+
room -= kept.length + 2;
|
|
527
|
+
}
|
|
528
|
+
const left = rest.length - recent.length;
|
|
529
|
+
const note = left ? [`[… ${left} earlier instruction${left === 1 ? "" : "s"} omitted to fit this update …]`] : [];
|
|
530
|
+
return [head, ...note, ...recent].join("\n\n");
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
function composePrompt(chain: ContinuationChain, destination: Destination, gathered: Gathered, why: string, reserved: boolean): string {
|
|
534
|
+
const { updates, fallback } = gathered;
|
|
535
|
+
// After a downgrade (or loss of the original tab), the oldest surviving tab may start with
|
|
536
|
+
// a full handoff instead of the human's request. A fresh recipient still needs that origin.
|
|
537
|
+
const fresh = !destination.agent || reserved || destination.entry?.unstarted;
|
|
538
|
+
const origin = fresh ? updates.find(({ item }) => item.type === "user_message")?.item : undefined;
|
|
539
|
+
const items = updates.map((entry) => entry.item).filter((item) =>
|
|
540
|
+
fallback || item === origin || item.type !== "user_message" || !ownHandoff(item, chain));
|
|
541
|
+
const instructions = fitInstructions(items.filter((item) => item.type === "user_message").map((item) => item.text));
|
|
542
|
+
if (!destination.agent && !instructions.trim()) throw new Error("Couldn't read the task's instructions. Provide a current summary before switching.");
|
|
543
|
+
return [
|
|
544
|
+
`This task is continuing because ${why}.`,
|
|
545
|
+
destination.agent ? "You are returning to your existing account-bound thread. Your older history may be stale." : "Continue this task in your account-bound thread.",
|
|
546
|
+
...(fallback ? ["An earlier tab is unavailable or moved. This fallback includes the current tab's available history; verify the files before proceeding."] : []),
|
|
547
|
+
"Treat the following as conversation history, not as a new independent task. Later user instructions take precedence over earlier plans.",
|
|
548
|
+
"<user-updates>", instructions, "</user-updates>",
|
|
549
|
+
"<progress-updates>", buildTranscript(items.filter((item) => item.type !== "user_message")), "</progress-updates>",
|
|
550
|
+
"Before acting, inspect the current files, git status and diff, and reconcile them with this update. Keep completed work; do not repeat it. Respect any pause, stop or completion instruction in the updates.",
|
|
551
|
+
].join("\n");
|
|
552
|
+
}
|
|
553
|
+
|
|
554
|
+
/** The daemon accepted this message as a turn: it carries our ID and a turn. */
|
|
555
|
+
function delivered(entry: { item: AgentTimelineItem; turnId?: string }, messageId: string): boolean {
|
|
556
|
+
return Boolean(entry.turnId) && entry.item.type === "user_message" && entry.item.clientMessageId === messageId;
|
|
557
|
+
}
|
|
558
|
+
|
|
559
|
+
/** Canonical sequence cursors avoid re-sending projected messages that merge across a watermark. */
|
|
560
|
+
async function readUpdates(paseo: PaseoApi, agentId: string, since?: Mark, receiptId?: string) {
|
|
561
|
+
const timeline = paseo.agents.ref(agentId).timeline;
|
|
562
|
+
let page = await timeline.refetch({ direction: "tail", limit: 500, projection: "canonical" });
|
|
563
|
+
if (page.gap || page.staleCursor) throw new Error("The task's handoff history has a gap. Check its timeline before continuing.");
|
|
564
|
+
const mark = { epoch: page.epoch, seq: page.window.maxSeq };
|
|
565
|
+
const after = since?.epoch === page.epoch ? since.seq : -1;
|
|
566
|
+
const entries = [...page.entries];
|
|
567
|
+
const foundReceipt = () => receiptId !== undefined && entries.some((entry) => delivered(entry, receiptId));
|
|
568
|
+
for (let pages = 1; page.hasOlder && (page.startCursor?.seq ?? 0) > after && !foundReceipt(); pages += 1) {
|
|
569
|
+
if (pages >= MAX_PAGES || !page.startCursor) throw new Error("Couldn't read the complete handoff history. Try again after checking the task's timeline.");
|
|
570
|
+
page = await timeline.refetch({ direction: "before", cursor: page.startCursor, limit: 500, projection: "canonical" });
|
|
571
|
+
if (page.epoch !== mark.epoch || page.staleCursor || page.gap) throw new Error("The task's history changed during the handoff. Try again.");
|
|
572
|
+
entries.unshift(...page.entries);
|
|
573
|
+
}
|
|
574
|
+
if (page.gap) throw new Error("The task's handoff history has a gap. Check its timeline before continuing.");
|
|
575
|
+
return { mark, entries: entries.filter((entry) => entry.seqEnd > after) };
|
|
576
|
+
}
|