@kapybara/zerosub 1.3.0 → 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 +8 -3
- package/client/pills.ts +3 -3
- 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 +157 -15
- package/server/state.ts +28 -0
- package/shared/rpc.ts +1 -1
package/README.md
CHANGED
|
@@ -46,6 +46,7 @@ Then open **Accounts (ZeroSub)** in the sidebar.
|
|
|
46
46
|
- **Disable for now** (the pause button on a card): the account stays signed in but ZeroSub stops using it. Its agents move to your other accounts right away (busy ones after their turn) and come back when you press **Enable**. ChatGPT conversations already on it stay, since they can't change accounts. You can't disable the last usable account of a provider.
|
|
47
47
|
4. Leave **Automatic switching** on (in Accounts, or **Settings → Plugins → zerosub → ZeroSub preferences**) and limits take care of themselves:
|
|
48
48
|
- Only the CLIs' own limit notices trigger a switch. That covers Claude Code's "You've hit your session limit · resets 3pm" and Codex's "You’ve hit your usage limit…".
|
|
49
|
+
- Paseo 0.13 and later no longer send the finished turn to plugins, so ZeroSub reads that turn from the agent's timeline instead.
|
|
49
50
|
- A short note in the agent's timeline says what happened.
|
|
50
51
|
- As a safety stop, one agent changes accounts at most 4 times in 10 minutes. If it hits that, its timeline says so; pick an account from its account button to carry on.
|
|
51
52
|
- An exhausted account is skipped until it resets. If you know it has room again sooner, for example after upgrading or buying credits, press **Mark as available again** (the check mark) on its card.
|
|
@@ -53,7 +54,11 @@ Then open **Accounts (ZeroSub)** in the sidebar.
|
|
|
53
54
|
### Claude vs. ChatGPT when switching mid-conversation
|
|
54
55
|
|
|
55
56
|
- **Claude:** a conversation moves to another account in place. The agent reopens on the new account with its full history and continues.
|
|
56
|
-
- **ChatGPT (Codex):** Codex encrypts its reasoning per ChatGPT account, so another account can't read an existing thread. The thread stays on its account. When it hits a limit, or you pick another account for it, ZeroSub
|
|
57
|
+
- **ChatGPT (Codex):** Codex encrypts its reasoning per ChatGPT account, so another account can't read an existing thread. The thread stays on its account. When it hits a limit, or you pick another account for it, ZeroSub carries the task on in its tab for the other account: a **continuation agent** in the same workspace, created on the first visit and reused after that. Switching A → B → A → B keeps two tabs, not four. Independent tasks keep separate tabs, even in the same workspace.
|
|
58
|
+
- A tab you return to gets the instructions and progress since it was last used, and checks the current files and Git diff before going on. Very long instructions are shortened, keeping the first one since the tab was last used (the original request, for a new tab), the latest ones and a note of how many were left out.
|
|
59
|
+
- You can type in any of a task's tabs and switch from any of them. The tab you used last is where the task continues: automatic switches and resets only move that tab, and another tab that hits a limit says in its timeline where the task went.
|
|
60
|
+
- A tab is reused while it is in the same workspace with the same account and permission mode; otherwise ZeroSub starts a new one. While one of the task's tabs is working or asking for permission, a switch you pick is refused until it stops, and an automatic switch leaves the task where it is and says so in its timeline.
|
|
61
|
+
- ZeroSub never sends a hand-off twice. If a lost connection leaves one unconfirmed, the switch stops and names the tab to check. Continuation agents from earlier versions are picked up on the first switch. New Codex agents simply start on the chosen account.
|
|
57
62
|
|
|
58
63
|
### Banked resets
|
|
59
64
|
|
|
@@ -70,7 +75,7 @@ ZeroSub tries these in order, and a timeline note says which one happened:
|
|
|
70
75
|
|
|
71
76
|
1. **Use a banked reset**, if you turned on **Use banked resets when every account is out**.
|
|
72
77
|
2. **Fork the chat to the other provider**, if you turned on **When every account is out, fork the chat to the other provider** (off by default). A stopped Claude chat continues in a new ChatGPT agent, or the other way round:
|
|
73
|
-
- The new agent opens in the same workspace with the conversation so far and goes straight back to work. It uses the other provider's default model and its account with the most room left.
|
|
78
|
+
- The new agent opens in the same workspace with the conversation so far and goes straight back to work. If that conversation began as a hand-off itself, only the start and end of the earlier one are quoted. It uses the other provider's default model and its account with the most room left.
|
|
74
79
|
- Its permission mode matches the original's level. Bypass becomes Full Access, and Accept File Edits becomes Default Permissions. Codex has no read-only or ask-first mode, so a Claude agent in Plan Mode or Always Ask isn't forked. ZeroSub never gives a fork more freedom than you gave the original.
|
|
75
80
|
- The original agent stays as it was, and prompting it again while its provider is still out points to the same fork rather than starting another.
|
|
76
81
|
- With the option off, a stopped agent's account button offers **Continue on ChatGPT (new agent)…** (or Claude) instead, with a confirmation.
|
|
@@ -106,7 +111,7 @@ ZeroSub never implements OAuth itself and never copies credentials between accou
|
|
|
106
111
|
|
|
107
112
|
## Privacy and security
|
|
108
113
|
|
|
109
|
-
- Credentials stay in the CLIs' own stores. ZeroSub's registry (`$PASEO_HOME/zerosub/state.json`) holds
|
|
114
|
+
- Credentials stay in the CLIs' own stores. ZeroSub's registry (`$PASEO_HOME/zerosub/state.json`) holds account names, emails, plans, which agent uses which account, and continuation links with timeline positions. Handoff text stays in the agents' conversation histories; it isn't copied into the registry.
|
|
110
115
|
- To show Claude usage, ZeroSub reads each account's current access token and calls Anthropic's usage endpoint, the same way Paseo's built-in usage display and `/usage` do. It never logs or stores tokens and never refreshes them itself. When you refresh usage (the ↻ button beside the title) or use a reset and a token has expired, it runs `claude -p /usage` so Claude Code renews its own sign-in. Codex usage comes from `codex app-server`.
|
|
111
116
|
- Using a banked reset calls the provider's own reset endpoint with that account's sign-in, and only after you confirm (or turn on automatic use).
|
|
112
117
|
- Removing an account moves its agents to the default account, then signs it out (`claude auth logout` / `codex` logout) and deletes its home. This happens once no agent is mid-turn on it. Abandoned sign-ins are cleaned up the same way.
|
package/client/pills.ts
CHANGED
|
@@ -169,13 +169,13 @@ function buttonFor(
|
|
|
169
169
|
await store.rpc(setAgentAccount, { agentId: agent.id, accountId });
|
|
170
170
|
};
|
|
171
171
|
|
|
172
|
-
// Codex threads can't change
|
|
172
|
+
// Codex threads can't change accounts in place; continue in this task's tab for that account.
|
|
173
173
|
const movable = route?.movable ?? true;
|
|
174
174
|
const items: PluginButtonMenuEntry[] = accounts.map((account, index) => ({
|
|
175
175
|
kind: "item",
|
|
176
176
|
id: `account-${index}`,
|
|
177
|
-
title: account.id === current.id || movable ? menuTitle(account) : `Continue on ${account.label}
|
|
178
|
-
icon: account.id === current.id ? "CircleCheck" : movable ? "Circle" : "
|
|
177
|
+
title: account.id === current.id || movable ? menuTitle(account) : `Continue on ${account.label}`,
|
|
178
|
+
icon: account.id === current.id ? "CircleCheck" : movable ? "Circle" : "ArrowRightLeft",
|
|
179
179
|
disabled: account.status === "signed_out" || account.status === "disabled" || account.id === current.id,
|
|
180
180
|
behavior: { kind: "action", onPress: choose(account.id) },
|
|
181
181
|
}));
|
package/client/switch-row.tsx
CHANGED
|
@@ -56,7 +56,7 @@ export function describeRow(row: SwitchRow): string {
|
|
|
56
56
|
switch (row.outcome) {
|
|
57
57
|
case "continued":
|
|
58
58
|
return row.continuedIn
|
|
59
|
-
? `${lead}ChatGPT conversations can't change accounts, so this
|
|
59
|
+
? `${lead}ChatGPT conversations can't change accounts, so this task continues in “${row.continuedIn.title}” on ${row.to}.`
|
|
60
60
|
: `${lead}Continuing on ${row.to}.`;
|
|
61
61
|
case "stayed":
|
|
62
62
|
return `${lead}This conversation stays on ${row.from ?? "its account"}.${row.detail ? ` ${row.detail}` : ""}`;
|
|
@@ -80,9 +80,7 @@ export function SwitchRowView({ item, theme }: PluginTimelineItemProps<SwitchRow
|
|
|
80
80
|
? "GitFork"
|
|
81
81
|
: row.reason === "exhausted" || row.outcome === "stayed"
|
|
82
82
|
? "CircleAlert"
|
|
83
|
-
: row.outcome === "
|
|
84
|
-
? "CopyPlus"
|
|
85
|
-
: row.outcome === "reset"
|
|
83
|
+
: row.outcome === "reset"
|
|
86
84
|
? "TimerReset"
|
|
87
85
|
: "ArrowRightLeft";
|
|
88
86
|
return (
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kapybara/zerosub",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.4.0",
|
|
4
4
|
"description": "ZeroSub: use several Claude and ChatGPT (Codex) subscriptions side by side in Paseo. Add accounts in-app, pick one per agent, and switch automatically when an account hits its limit.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"paseo",
|
package/server/codex.ts
CHANGED
|
@@ -70,7 +70,7 @@ class AppServer {
|
|
|
70
70
|
try {
|
|
71
71
|
await server.request(
|
|
72
72
|
"initialize",
|
|
73
|
-
{ clientInfo: { name: CLIENT_NAME, title: "Paseo ZeroSub", version: "1.
|
|
73
|
+
{ clientInfo: { name: CLIENT_NAME, title: "Paseo ZeroSub", version: "1.4.0" }, capabilities: { experimentalApi: false } },
|
|
74
74
|
60_000,
|
|
75
75
|
);
|
|
76
76
|
server.send({ method: "initialized" });
|
|
@@ -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
|
+
}
|
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,9 +31,11 @@ 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";
|
|
@@ -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";
|
|
@@ -81,6 +84,8 @@ const RESET_GRACE_MS = 5 * 60_000;
|
|
|
81
84
|
const AGENT_LIST_MS = 3_000;
|
|
82
85
|
/** How long a default change waits for sessions already being routed to record their account. */
|
|
83
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;
|
|
84
89
|
|
|
85
90
|
const DEFAULT_PREFERENCES: Preferences = {
|
|
86
91
|
autoSwitch: true,
|
|
@@ -130,6 +135,7 @@ function emptySummary(): ReopenSummary {
|
|
|
130
135
|
}
|
|
131
136
|
|
|
132
137
|
export class Service {
|
|
138
|
+
private readonly continuations: CodexContinuations;
|
|
133
139
|
private paseo: PaseoApi | null = null;
|
|
134
140
|
private prefs: Preferences = DEFAULT_PREFERENCES;
|
|
135
141
|
private readonly usage = new Map<string, Usage>();
|
|
@@ -148,7 +154,7 @@ export class Service {
|
|
|
148
154
|
/** One failover at a time per exhausted account. */
|
|
149
155
|
private readonly failoverLocks = new Map<string, Mutex>();
|
|
150
156
|
private readonly switchGuard = new SwitchGuard();
|
|
151
|
-
/** When
|
|
157
|
+
/** When ZeroSub last told an agent's timeline why it didn't switch, by agent and notice, so it says so once. */
|
|
152
158
|
private readonly guardNoticeAt = new Map<string, number>();
|
|
153
159
|
/** When each account's agents last started or ended a turn, to read busy accounts often. */
|
|
154
160
|
private readonly activeAt = new Map<string, number>();
|
|
@@ -169,7 +175,9 @@ export class Service {
|
|
|
169
175
|
private readonly store = new StateStore(),
|
|
170
176
|
private readonly families = new FamilyResolver(),
|
|
171
177
|
private readonly reopener = new Reopener(),
|
|
172
|
-
) {
|
|
178
|
+
) {
|
|
179
|
+
this.continuations = new CodexContinuations(store);
|
|
180
|
+
}
|
|
173
181
|
|
|
174
182
|
setPreferences(prefs: Preferences): void {
|
|
175
183
|
this.prefs = prefs;
|
|
@@ -274,10 +282,18 @@ export class Service {
|
|
|
274
282
|
const old = (at: string) => now - (Date.parse(at) || 0) > PRUNE_MS;
|
|
275
283
|
const staleSessions = Object.entries(state.sessions).filter(([id, session]) => !known.has(id) && old(session.openedAt));
|
|
276
284
|
const staleBindings = Object.entries(state.bindings).filter(([id, binding]) => !known.has(id) && old(binding.at));
|
|
277
|
-
|
|
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;
|
|
278
293
|
await this.store.update((draft) => {
|
|
279
294
|
for (const [id] of staleSessions) delete draft.sessions[id];
|
|
280
295
|
for (const [id] of staleBindings) delete draft.bindings[id];
|
|
296
|
+
for (const [id] of staleChains) delete draft.continuations[id];
|
|
281
297
|
});
|
|
282
298
|
}
|
|
283
299
|
|
|
@@ -423,10 +439,13 @@ export class Service {
|
|
|
423
439
|
const accountId = this.runningOn(await this.store.read(), agentId, family);
|
|
424
440
|
if (accountId) this.activeAt.set(accountId, Date.now());
|
|
425
441
|
if (event.outcome.kind !== "canceled") {
|
|
426
|
-
const
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
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" });
|
|
430
449
|
}
|
|
431
450
|
}
|
|
432
451
|
if (this.deferred.has(agentId)) await this.finishDeferred(context.paseo, agentId, family);
|
|
@@ -434,10 +453,42 @@ export class Service {
|
|
|
434
453
|
if (accountId) void this.refreshUsage(accountId).catch(() => undefined);
|
|
435
454
|
}
|
|
436
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
|
+
|
|
437
487
|
async onAgentArchived(agentId: string): Promise<void> {
|
|
438
488
|
this.deferred.delete(agentId);
|
|
439
489
|
this.switchGuard.forget(agentId);
|
|
440
490
|
this.guardNoticeAt.delete(agentId);
|
|
491
|
+
this.guardNoticeAt.delete(`${agentId}:elsewhere`);
|
|
441
492
|
if (!(await this.store.read()).sessions[agentId]) return;
|
|
442
493
|
await this.store.update((draft) => {
|
|
443
494
|
delete draft.sessions[agentId];
|
|
@@ -476,10 +527,21 @@ export class Service {
|
|
|
476
527
|
paseo: PaseoApi,
|
|
477
528
|
agentId: string,
|
|
478
529
|
family: Family,
|
|
479
|
-
timeline: readonly AgentTimelineItem[],
|
|
530
|
+
timeline: readonly AgentTimelineItem[] | undefined,
|
|
480
531
|
problem: Problem,
|
|
481
532
|
): Promise<void> {
|
|
482
|
-
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
|
+
}
|
|
483
545
|
this.switching.add(agentId);
|
|
484
546
|
let exhausted: string | null = null;
|
|
485
547
|
try {
|
|
@@ -503,14 +565,26 @@ export class Service {
|
|
|
503
565
|
agentId: string,
|
|
504
566
|
family: Family,
|
|
505
567
|
account: StoredAccount,
|
|
506
|
-
timeline: readonly AgentTimelineItem[],
|
|
568
|
+
timeline: readonly AgentTimelineItem[] | undefined,
|
|
507
569
|
problem: Problem,
|
|
508
570
|
): Promise<void> {
|
|
509
571
|
const adapter = this.adapters[family];
|
|
510
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
|
+
});
|
|
511
581
|
if (problem.kind === "limit" && problem.hit.kind === "window" && this.recentlyRedeemed(account.id)) {
|
|
512
582
|
// This turn hit the limit just before a reset refilled it (another agent's failover or the
|
|
513
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
|
+
}
|
|
514
588
|
console.log(`[ZeroSub] ${account.label} was just reset; ${agentId} carries on where it is`);
|
|
515
589
|
if (this.prefs.autoContinue && this.switchGuard.allows(agentId, now)) {
|
|
516
590
|
this.switchGuard.note(agentId, now);
|
|
@@ -544,6 +618,10 @@ export class Service {
|
|
|
544
618
|
}
|
|
545
619
|
|
|
546
620
|
if (!this.prefs.autoSwitch) return;
|
|
621
|
+
if (elsewhere) {
|
|
622
|
+
await this.noteElsewhere(paseo, agentId, account, problem.kind, resetsAt, elsewhere, "switch");
|
|
623
|
+
return;
|
|
624
|
+
}
|
|
547
625
|
const latest = await this.store.read();
|
|
548
626
|
if (this.runningOn(latest, agentId, family) !== account.id) return; // Already moved.
|
|
549
627
|
const base = {
|
|
@@ -560,8 +638,7 @@ export class Service {
|
|
|
560
638
|
if (!this.switchGuard.allows(agentId, now)) {
|
|
561
639
|
console.warn(`[ZeroSub] not switching ${agentId} again: it changed accounts ${this.switchGuard.limit} times in 10 minutes`);
|
|
562
640
|
// Say so once, so the user knows to pick an account rather than wait.
|
|
563
|
-
if (
|
|
564
|
-
this.guardNoticeAt.set(agentId, now);
|
|
641
|
+
if (this.noticeDue(agentId, now)) {
|
|
565
642
|
await this.appendRow(paseo, agentId, {
|
|
566
643
|
...base,
|
|
567
644
|
to: account.label,
|
|
@@ -695,11 +772,46 @@ export class Service {
|
|
|
695
772
|
to: next.label,
|
|
696
773
|
reason,
|
|
697
774
|
outcome: "stayed",
|
|
698
|
-
detail: `Couldn't
|
|
775
|
+
detail: `Couldn't continue on ${next.label}: ${describe(error)}`,
|
|
699
776
|
});
|
|
700
777
|
}
|
|
701
778
|
}
|
|
702
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
|
+
|
|
703
815
|
private async markLimited(accountId: string, until: string, kind: LimitKind): Promise<void> {
|
|
704
816
|
await this.store.update((draft) => {
|
|
705
817
|
const account = findAccount(draft, accountId);
|
|
@@ -784,6 +896,11 @@ export class Service {
|
|
|
784
896
|
if (this.runningOn(await this.store.read(), agentId, account.family) !== account.id) return false;
|
|
785
897
|
// Only resume an agent that this limit actually stopped.
|
|
786
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
|
+
}
|
|
787
904
|
const at = new Date().toISOString();
|
|
788
905
|
await this.appendRow(paseo, agentId, {
|
|
789
906
|
family: account.family,
|
|
@@ -959,6 +1076,21 @@ export class Service {
|
|
|
959
1076
|
|
|
960
1077
|
/** "Continue on …" from an agent's account button: the same fork, asked for by the user. */
|
|
961
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> {
|
|
962
1094
|
this.attach(paseo);
|
|
963
1095
|
const info = await agentInfo(paseo, agentId);
|
|
964
1096
|
if (!info || info.archived) throw new Error("That agent is no longer available.");
|
|
@@ -994,6 +1126,7 @@ export class Service {
|
|
|
994
1126
|
timeline: readonly AgentTimelineItem[] | undefined,
|
|
995
1127
|
source: "auto" | "user",
|
|
996
1128
|
): Promise<Continuation> {
|
|
1129
|
+
if (target.family === "codex") return this.continuations.continue(paseo, agentId, target, why, source);
|
|
997
1130
|
return continueInNewAgent({
|
|
998
1131
|
paseo,
|
|
999
1132
|
sourceAgentId: agentId,
|
|
@@ -1469,14 +1602,14 @@ export class Service {
|
|
|
1469
1602
|
const binding = state.bindings[agentId];
|
|
1470
1603
|
const current = binding?.source === "thread" ? binding.accountId : this.runningOn(state, agentId, family);
|
|
1471
1604
|
if (current === target.id) return emptySummary();
|
|
1472
|
-
const continuation = await this.continueElsewhere(
|
|
1605
|
+
const continuation = await this.withSwitch(agentId, () => this.continueElsewhere(
|
|
1473
1606
|
paseo,
|
|
1474
1607
|
agentId,
|
|
1475
1608
|
target,
|
|
1476
1609
|
`you moved the work to your ChatGPT account "${target.label}"`,
|
|
1477
1610
|
undefined,
|
|
1478
1611
|
"user",
|
|
1479
|
-
);
|
|
1612
|
+
));
|
|
1480
1613
|
await this.appendRow(paseo, agentId, {
|
|
1481
1614
|
family,
|
|
1482
1615
|
from: findAccount(state, current)?.label ?? null,
|
|
@@ -1802,6 +1935,15 @@ async function withTimeout(task: Promise<unknown>, ms: number): Promise<void> {
|
|
|
1802
1935
|
await Promise.race([task.catch(() => undefined), delay(ms)]);
|
|
1803
1936
|
}
|
|
1804
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
|
+
|
|
1805
1947
|
function log(message: string, error: unknown): void {
|
|
1806
1948
|
console.error(`[ZeroSub] ${message}`, describe(error));
|
|
1807
1949
|
}
|
package/server/state.ts
CHANGED
|
@@ -49,6 +49,32 @@ export const LiveSessionSchema = z.object({
|
|
|
49
49
|
});
|
|
50
50
|
export type LiveSession = z.infer<typeof LiveSessionSchema>;
|
|
51
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
|
+
|
|
52
78
|
export const StoredStateSchema = z.object({
|
|
53
79
|
version: z.literal(1).default(1),
|
|
54
80
|
accounts: z.array(StoredAccountSchema).default([]),
|
|
@@ -59,6 +85,7 @@ export const StoredStateSchema = z.object({
|
|
|
59
85
|
bindings: z.record(z.string(), BindingSchema).default({}),
|
|
60
86
|
/** Which account each agent's live provider session was opened with. */
|
|
61
87
|
sessions: z.record(z.string(), LiveSessionSchema).default({}),
|
|
88
|
+
continuations: z.record(z.string(), ContinuationChainSchema).default({}),
|
|
62
89
|
});
|
|
63
90
|
export type StoredState = z.infer<typeof StoredStateSchema>;
|
|
64
91
|
|
|
@@ -102,6 +129,7 @@ export function salvageState(raw: unknown): { state: StoredState; dropped: boole
|
|
|
102
129
|
defaults,
|
|
103
130
|
bindings: records(BindingSchema, source.bindings),
|
|
104
131
|
sessions: records(LiveSessionSchema, source.sessions),
|
|
132
|
+
continuations: records(ContinuationChainSchema, source.continuations),
|
|
105
133
|
},
|
|
106
134
|
dropped: true,
|
|
107
135
|
};
|
package/shared/rpc.ts
CHANGED
|
@@ -48,7 +48,7 @@ export const ReopenSummarySchema = z.object({
|
|
|
48
48
|
/** Busy agents move when their current turn ends. */
|
|
49
49
|
deferred: z.array(z.string()),
|
|
50
50
|
failed: z.array(z.object({ agentId: z.string(), error: z.string() })),
|
|
51
|
-
/** A conversation that could not move in place and continues in this
|
|
51
|
+
/** A conversation that could not move in place and continues in this account's agent instead. */
|
|
52
52
|
continuedIn: z.object({ agentId: z.string(), title: z.string() }).nullable().default(null),
|
|
53
53
|
});
|
|
54
54
|
export type ReopenSummary = z.infer<typeof ReopenSummarySchema>;
|