@kapybara/zerosub 1.5.0 → 1.18.2

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.
Files changed (56) hide show
  1. package/README.md +222 -27
  2. package/client/accounts-surface.tsx +344 -110
  3. package/client/add-account.tsx +335 -23
  4. package/client/api-account.tsx +250 -0
  5. package/client/azure-account.tsx +311 -0
  6. package/client/commands.ts +44 -8
  7. package/client/composer-item.tsx +203 -0
  8. package/client/fork-confirm.tsx +71 -0
  9. package/client/fork-settings.tsx +148 -0
  10. package/client/pace.tsx +196 -0
  11. package/client/pi-accounts.tsx +571 -0
  12. package/client/pills.ts +63 -25
  13. package/client/reset-confirm.tsx +12 -3
  14. package/client/settings-screen.tsx +48 -9
  15. package/client/store.ts +148 -19
  16. package/client/switch-row.tsx +28 -8
  17. package/client/ui.tsx +11 -0
  18. package/index.client.tsx +4 -1
  19. package/index.server.ts +53 -10
  20. package/package.json +5 -2
  21. package/server/account-identity.ts +11 -0
  22. package/server/adapter.ts +115 -8
  23. package/server/api-usage.ts +144 -0
  24. package/server/azure.ts +346 -0
  25. package/server/binaries.ts +41 -3
  26. package/server/claude.ts +276 -21
  27. package/server/codex-same-conversation.ts +71 -0
  28. package/server/codex.ts +35 -7
  29. package/server/continuations.ts +128 -18
  30. package/server/cursor.ts +222 -0
  31. package/server/families.ts +105 -8
  32. package/server/grok.ts +225 -0
  33. package/server/handoff.ts +221 -30
  34. package/server/homes.ts +1263 -35
  35. package/server/json-file.ts +39 -8
  36. package/server/launchers.ts +319 -0
  37. package/server/limits.ts +80 -3
  38. package/server/main-proxy.ts +238 -0
  39. package/server/modes.ts +20 -4
  40. package/server/paths.ts +81 -1
  41. package/server/pi.ts +528 -0
  42. package/server/placement.ts +133 -0
  43. package/server/process.ts +18 -1
  44. package/server/processes.ts +66 -0
  45. package/server/provider-env.ts +28 -0
  46. package/server/proxy.ts +282 -0
  47. package/server/reopen.ts +50 -8
  48. package/server/routing.ts +337 -30
  49. package/server/service.ts +4320 -803
  50. package/server/state.ts +305 -24
  51. package/server/usage.ts +2 -0
  52. package/shared/format.ts +170 -2
  53. package/shared/model.ts +339 -2
  54. package/shared/preferences.ts +22 -1
  55. package/shared/rpc.ts +130 -8
  56. package/shared/timeline.ts +11 -0
package/server/grok.ts ADDED
@@ -0,0 +1,225 @@
1
+ import { spawn } from "node:child_process";
2
+ import { readFile } from "node:fs/promises";
3
+ import { join, resolve } from "node:path";
4
+ import type { LoginMethod } from "../shared/model";
5
+ import {
6
+ ProgressEmitter,
7
+ spawnEnv,
8
+ type EnvPatch,
9
+ type FamilyAdapter,
10
+ type Identity,
11
+ type LoginHandle,
12
+ type RedeemReply,
13
+ type UsageRead,
14
+ } from "./adapter";
15
+ import { browserCaptureScript, grokBinary } from "./binaries";
16
+ import { prepareGrokHome } from "./homes";
17
+ import { mainGrokHome } from "./paths";
18
+ import { firstUrl, run, stripAnsi } from "./process";
19
+
20
+ /**
21
+ * Logins Grok would use in place of the home's `auth.json`, or fall back to once its sign-in lapses:
22
+ * an added account's agents get them blanked, when the daemon's environment sets them, so their work
23
+ * never moves to another login or onto an API key's bill.
24
+ */
25
+ const OVERRIDING_AUTH = [
26
+ "GROK_AUTH",
27
+ "XAI_API_KEY",
28
+ "GROK_CODE_XAI_API_KEY",
29
+ "GROK_AUTH_PROVIDER_COMMAND",
30
+ "GROK_AUTH_PROVIDER_ACCESS_TOKEN",
31
+ "GROK_OIDC_ISSUER",
32
+ "GROK_OIDC_CLIENT_ID",
33
+ "GROK_OIDC_AUDIENCE",
34
+ "GROK_OIDC_SCOPES",
35
+ "GROK_DEPLOYMENT_KEY",
36
+ "GROK_CLI_CHAT_PROXY_BASE_URL",
37
+ ] as const;
38
+
39
+ /** The login file of a home (`home === null`: the CLI login, which may name another with `GROK_AUTH_PATH`). */
40
+ export function grokAuthPath(home: string | null): string {
41
+ if (home) return join(home, "auth.json");
42
+ const configured = process.env.GROK_AUTH_PATH?.trim();
43
+ return configured ? resolve(configured) : join(mainGrokHome(), "auth.json");
44
+ }
45
+
46
+ function str(value: unknown): string | null {
47
+ return typeof value === "string" && value.trim() ? value.trim() : null;
48
+ }
49
+
50
+ /**
51
+ * Who a Grok `auth.json` is signed in as. It holds one entry per sign-in scope, keyed
52
+ * `https://auth.x.ai::<client id>` for Grok's own sign-in (preferred), with `email`, `user_id` and
53
+ * `team_id` beside the login. Only those are read, and whether a login (`key` or `refresh_token`) is
54
+ * there; never its value. Null when no entry holds a login.
55
+ */
56
+ export function parseGrokAuth(value: unknown): Identity | null {
57
+ if (!value || typeof value !== "object" || Array.isArray(value)) return null;
58
+ const entries = Object.entries(value as Record<string, unknown>).filter(
59
+ (entry): entry is [string, Record<string, unknown>] => Boolean(entry[1]) && typeof entry[1] === "object" && !Array.isArray(entry[1]),
60
+ );
61
+ const preferred = entries.filter(([key]) => key.startsWith("https://auth.x.ai::"));
62
+ const login = (preferred.length > 0 ? preferred : entries).map(([, entry]) => entry).find((entry) => str(entry.key) || str(entry.refresh_token));
63
+ if (!login) return null;
64
+ const email = str(login.email);
65
+ const who = str(login.user_id) ?? email?.toLowerCase() ?? null;
66
+ return {
67
+ signedIn: true,
68
+ email,
69
+ plan: null,
70
+ organization: null,
71
+ identity: who ? `grok|${str(login.team_id) ?? "personal"}|${who}` : null,
72
+ };
73
+ }
74
+
75
+ /** Why `grok usage --json` gave no reading, in a few words. */
76
+ export function grokUsageProblem(result: { code: number | null; stdout: string; stderr: string; timedOut: boolean }): string {
77
+ if (result.timedOut) return "`grok usage` didn't answer in time.";
78
+ const said = stripAnsi(`${result.stderr}\n${result.stdout}`);
79
+ if (/can't show your plan's usage here/i.test(said)) return "Grok can't show plan usage on this machine yet. Run /usage inside Grok instead.";
80
+ if (/managed by your team/i.test(said)) return "Usage limits are managed by your team.";
81
+ const line = said.split("\n").map((entry) => entry.replace(/^Error:\s*/i, "").trim()).find(Boolean);
82
+ if (result.code !== 0) return line ? line.slice(0, 200) : `\`grok usage\` failed (exit ${result.code ?? "signal"}).`;
83
+ return "Grok usage JSON format support awaits verification. Run /usage inside Grok to check your plan.";
84
+ }
85
+
86
+ export class GrokAdapter implements FamilyAdapter {
87
+ readonly family = "grok" as const;
88
+ /**
89
+ * A conversation's history may carry reasoning only its account can read (Grok has an
90
+ * `encrypted_content_mismatch` error), and resuming on a second account isn't verified, so Grok
91
+ * agents stay on their account, like Codex threads, and don't hand off (see `HAND_OFF`).
92
+ */
93
+ readonly portable = false;
94
+ readonly usageSpacingMs = 60_000;
95
+
96
+ async env(home: string | null): Promise<EnvPatch> {
97
+ if (!home) return { GROK_HOME: null, GROK_AUTH_PATH: null };
98
+ // `GROK_AUTH_PATH` too, so one set in the daemon's environment can't point every account at one file.
99
+ const patch: EnvPatch = { GROK_HOME: home, GROK_AUTH_PATH: join(home, "auth.json") };
100
+ for (const key of OVERRIDING_AUTH) if (process.env[key]) patch[key] = "";
101
+ return patch;
102
+ }
103
+
104
+ async available(): Promise<{ ok: boolean; detail: string | null }> {
105
+ const command = await grokBinary();
106
+ if (!command) return { ok: false, detail: "no Paseo provider runs `grok agent stdio`" };
107
+ const result = await run(command, ["--version"], { timeoutMs: 30_000 });
108
+ if (result.code === 0) return { ok: true, detail: null };
109
+ return { ok: false, detail: (result.stderr || result.stdout).trim().split("\n")[0] || `${command} not found` };
110
+ }
111
+
112
+ prepareHome(home: string): Promise<void> {
113
+ return prepareGrokHome(home);
114
+ }
115
+
116
+ async identity(home: string | null): Promise<Identity> {
117
+ let text = "";
118
+ try {
119
+ text = await readFile(grokAuthPath(home), "utf8");
120
+ } catch (error) {
121
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
122
+ }
123
+ const identity = text.trim() ? parseGrokAuth(JSON.parse(text)) : null;
124
+ return identity ?? { signedIn: false, email: null, plan: null, organization: null, identity: null };
125
+ }
126
+
127
+ /** Invoke only Grok's own CLI; its successful JSON stays unavailable until the format is verified. */
128
+ async usage(home: string | null): Promise<UsageRead> {
129
+ const fetchedAt = new Date().toISOString();
130
+ const command = (await grokBinary()) ?? "grok";
131
+ const result = await run(command, ["usage", "--json"], { env: spawnEnv(await this.env(home), "grok"), timeoutMs: 30_000 });
132
+ return { fetchedAt, windows: [], error: grokUsageProblem(result), cached: false, resets: null };
133
+ }
134
+
135
+ async redeemReset(): Promise<RedeemReply> {
136
+ return { outcome: "none", message: "Grok has no banked resets.", left: null };
137
+ }
138
+
139
+ async login(home: string | null, method: LoginMethod): Promise<LoginHandle> {
140
+ const command = (await grokBinary()) ?? "grok";
141
+ const env = spawnEnv(await this.env(home), "grok");
142
+ // The link is read from what `grok login` prints; no browser opens on the daemon's machine.
143
+ const shim = await browserCaptureScript();
144
+ if (shim) env.BROWSER = shim;
145
+ return new GrokLogin(command, ["login", method === "code" ? "--device-auth" : "--oauth"], env);
146
+ }
147
+
148
+ async logout(home: string): Promise<void> {
149
+ const command = (await grokBinary()) ?? "grok";
150
+ const result = await run(command, ["logout"], { env: spawnEnv(await this.env(home), "grok"), timeoutMs: 30_000 });
151
+ if (result.code !== 0) throw new Error((result.stderr || result.stdout).trim().split("\n")[0] || "grok logout failed");
152
+ }
153
+
154
+ /** Failover is for a follow-up: how Grok's limit and sign-out notices reach Paseo isn't known yet. */
155
+ detectLimit(): null {
156
+ return null;
157
+ }
158
+
159
+ detectSignOut(): null {
160
+ return null;
161
+ }
162
+ }
163
+
164
+ /** Grok's device code, as `grok login --device-auth` prints it: `ABCD-1234`. */
165
+ const DEVICE_CODE = /\b([A-Z0-9]{4}-[A-Z0-9]{4})\b/;
166
+
167
+ /**
168
+ * The link and code `grok login` printed so far: `--device-auth` prints the device page and a code to
169
+ * confirm there (any device), `--oauth` the sign-in link (its callback is on the daemon's machine).
170
+ */
171
+ export function readGrokLogin(output: string): { url: string; userCode: string | null } | null {
172
+ const device = firstUrl(output, /\/oauth2\/device/);
173
+ if (device) {
174
+ const code = output.slice(output.indexOf(device) + device.length).match(DEVICE_CODE)?.[1] ?? new URL(device).searchParams.get("user_code");
175
+ return { url: device, userCode: code };
176
+ }
177
+ const browser = firstUrl(output, /\/oauth2\/authorize/);
178
+ return browser ? { url: browser, userCode: null } : null;
179
+ }
180
+
181
+ /** `grok login`, which exits 0 once signed in. */
182
+ export class GrokLogin extends ProgressEmitter implements LoginHandle {
183
+ readonly finished: Promise<{ ok: boolean; message: string | null }>;
184
+ private readonly child;
185
+ private output = "";
186
+ private canceled = false;
187
+ private exited = false;
188
+
189
+ constructor(command: string, args: string[], env: NodeJS.ProcessEnv) {
190
+ super();
191
+ this.child = spawn(command, args, { env, stdio: ["ignore", "pipe", "pipe"] });
192
+ this.finished = new Promise((settle) => {
193
+ this.child.on("error", (error) => settle({ ok: false, message: `Could not start Grok: ${error.message}` }));
194
+ this.child.on("close", (code) => {
195
+ this.exited = true;
196
+ if (this.canceled) return settle({ ok: false, message: "Sign-in was canceled." });
197
+ if (code === 0) return settle({ ok: true, message: null });
198
+ const lines = this.output.split("\n").map((line) => line.trim()).filter(Boolean);
199
+ settle({ ok: false, message: lines.reverse().find((line) => /error|fail|denied|expired/i.test(line)) ?? "Sign-in did not finish." });
200
+ });
201
+ });
202
+ const read = (chunk: string) => {
203
+ this.output = (this.output + stripAnsi(chunk)).slice(-16_384);
204
+ const link = readGrokLogin(this.output);
205
+ if (link && (link.url !== this.progress.url || link.userCode !== this.progress.userCode)) this.update({ step: "waiting", ...link });
206
+ };
207
+ this.child.stdout.setEncoding("utf8");
208
+ this.child.stderr.setEncoding("utf8");
209
+ this.child.stdout.on("data", read);
210
+ this.child.stderr.on("data", read);
211
+ }
212
+
213
+ async submitCode(): Promise<void> {
214
+ throw new Error("Grok sign-in doesn't use a pasted code. Finish on the sign-in page.");
215
+ }
216
+
217
+ cancel(): void {
218
+ if (this.exited || this.canceled) return;
219
+ this.canceled = true;
220
+ this.child.kill("SIGTERM");
221
+ setTimeout(() => {
222
+ if (!this.exited) this.child.kill("SIGKILL");
223
+ }, 3_000).unref();
224
+ }
225
+ }
package/server/handoff.ts CHANGED
@@ -6,9 +6,12 @@ type PaseoApi = PluginHookContext["paseo"];
6
6
 
7
7
  /** Label on a continuation agent naming the agent it carries on from. */
8
8
  export const CONTINUED_FROM_LABEL = "zerosub.continued-from";
9
+ /** Paseo's label naming the agent a sub-agent was created by (`PARENT_AGENT_ID_LABEL`). */
10
+ export const PARENT_LABEL = "paseo.parent-agent-id";
9
11
 
10
12
  const MAX_TRANSCRIPT = 40_000;
11
13
  const MAX_FIRST_MESSAGE = 6_000;
14
+ const MAX_TODOS = 6_000;
12
15
  const MAX_EARLIER_HANDOFF = 6_000;
13
16
 
14
17
  const OPEN = "<previous-session>";
@@ -51,7 +54,92 @@ export function shortenEarlierHandOff(text: string): string {
51
54
  return `${neutralise(text.slice(0, open))}${OPEN}\n${kept}\n${CLOSE}${neutralise(after)}`;
52
55
  }
53
56
 
54
- function describeTool(item: Extract<AgentTimelineItem, { type: "tool_call" }>): string {
57
+ type ToolCallItem = Extract<AgentTimelineItem, { type: "tool_call" }>;
58
+
59
+ interface ParsedAgentMessage {
60
+ event: string;
61
+ sender: string | null;
62
+ text: string;
63
+ }
64
+
65
+ function isRecord(value: unknown): value is Record<string, unknown> {
66
+ return typeof value === "object" && value !== null && !Array.isArray(value);
67
+ }
68
+
69
+ function formatSender(sender: unknown): string | null {
70
+ if (!isRecord(sender) || typeof sender.id !== "string" || !sender.id.trim()) return null;
71
+ const id = sender.id.trim();
72
+ const title = typeof sender.title === "string" ? sender.title.trim() : "";
73
+ return title && title !== id ? `${title} (${id})` : id;
74
+ }
75
+
76
+ /**
77
+ * Since Paseo 0.11.1, a prompt or finish notification from another agent is projected as an
78
+ * `agent_message` tool call (`paseo-agent-message:…`) rather than a `user_message`.
79
+ */
80
+ function readAgentMessage(item: ToolCallItem): ParsedAgentMessage | null {
81
+ if (isRecord(item.agentMessage) && typeof item.agentMessage.event === "string" && typeof item.agentMessage.text === "string") {
82
+ return {
83
+ event: item.agentMessage.event,
84
+ sender: formatSender(item.agentMessage.sender),
85
+ text: item.agentMessage.text,
86
+ };
87
+ }
88
+ if (
89
+ item.name === "agent_message" &&
90
+ item.callId.startsWith("paseo-agent-message:") &&
91
+ item.detail.type === "plain_text" &&
92
+ typeof item.detail.text === "string"
93
+ ) {
94
+ return { event: "message", sender: null, text: item.detail.text };
95
+ }
96
+ return null;
97
+ }
98
+
99
+ /** Paseo projects a schedule or heartbeat fire (`<paseo-system>…</paseo-system>`) as a `heartbeat` tool call. */
100
+ function readHeartbeatPrompt(item: ToolCallItem): string | null {
101
+ if (
102
+ item.name === "heartbeat" &&
103
+ item.callId.startsWith("paseo-system:") &&
104
+ item.detail.type === "plain_text" &&
105
+ typeof item.detail.text === "string"
106
+ ) {
107
+ return item.detail.text;
108
+ }
109
+ return null;
110
+ }
111
+
112
+ /** Whether `item` is a prompt row that starts or steers a turn (human, another agent, or a schedule). */
113
+ export function isTurnPrompt(item: AgentTimelineItem): boolean {
114
+ if (item.type === "user_message") return true;
115
+ if (item.type !== "tool_call") return false;
116
+ return readAgentMessage(item) !== null || readHeartbeatPrompt(item) !== null;
117
+ }
118
+
119
+ /**
120
+ * Task instructions sent into the conversation: a human message, a prompt from another agent
121
+ * (`create_agent` / `send_agent_prompt`), or a scheduled prompt. Child lifecycle notifications
122
+ * (`event !== "message"`) return `null` so they stay in progress updates rather than instructions.
123
+ */
124
+ export function promptInstruction(item: AgentTimelineItem): string | null {
125
+ if (item.type === "user_message") return item.text;
126
+ if (item.type !== "tool_call") return null;
127
+ const agentMsg = readAgentMessage(item);
128
+ if (agentMsg) {
129
+ if (agentMsg.event !== "message") return null;
130
+ if (!agentMsg.text.trim()) return "";
131
+ return agentMsg.sender ? `From ${agentMsg.sender}:\n${agentMsg.text}` : agentMsg.text;
132
+ }
133
+ return readHeartbeatPrompt(item);
134
+ }
135
+
136
+ function describeTool(item: ToolCallItem): string {
137
+ const agentMsg = readAgentMessage(item);
138
+ if (agentMsg) {
139
+ const head = `[agent_message: ${agentMsg.event}${agentMsg.sender ? ` from ${agentMsg.sender}` : ""}]`;
140
+ const body = clip(neutralise(agentMsg.text), 2_000);
141
+ return body ? `${head}\n${body}` : head;
142
+ }
55
143
  const detail = item.detail;
56
144
  const failed = item.status === "failed" ? " (failed)" : "";
57
145
  switch (detail.type) {
@@ -74,61 +162,112 @@ function describeTool(item: Extract<AgentTimelineItem, { type: "tool_call" }>):
74
162
  }
75
163
  }
76
164
 
165
+ type Prompt = { speaker: string; text: string; index: number };
166
+
77
167
  /**
78
168
  * A readable account of what happened in a conversation, for a fresh agent to pick up from.
79
169
  * Keeps the opening request and the most recent history; drops reasoning and tool output.
80
170
  */
81
171
  export function buildTranscript(timeline: readonly AgentTimelineItem[], max = MAX_TRANSCRIPT): string {
82
172
  const lines: string[] = [];
83
- let firstUser: string | null = null;
173
+ // Typed by assertion: recordPrompt assigns these, and TypeScript doesn't follow assignments in closures.
174
+ let first = null as Prompt | null;
175
+ let latest = null as Prompt | null;
84
176
  let todos: string | null = null;
177
+ let todosIndex = 0;
178
+ // A user, agent or scheduled prompt is an instruction: the first stays at the top, the latest goes last.
179
+ const recordPrompt = (speaker: string, rawText: string) => {
180
+ // Clipping below can't then split a quoted pair: the prompt's own tags are the only ones.
181
+ const text = neutralise(shortenEarlierHandOff(rawText)).trim();
182
+ if (first === null && text) first = { speaker, text, index: lines.length };
183
+ latest = { speaker, text, index: lines.length };
184
+ lines.push(`${speaker}: ${text}`);
185
+ };
85
186
  for (const item of timeline) {
86
187
  switch (item.type) {
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()}`);
188
+ case "user_message":
189
+ recordPrompt("User", item.text);
92
190
  break;
93
- }
94
191
  case "assistant_message":
95
192
  if (item.text.trim()) lines.push(`Assistant: ${item.text.trim()}`);
96
193
  break;
97
- case "tool_call":
194
+ case "tool_call": {
195
+ const agentMsg = readAgentMessage(item);
196
+ if (agentMsg?.event === "message") {
197
+ if (agentMsg.text.trim()) recordPrompt(agentMsg.sender ? `From ${agentMsg.sender}` : "Agent", agentMsg.text);
198
+ break;
199
+ }
200
+ const heartbeat = readHeartbeatPrompt(item);
201
+ if (heartbeat !== null) {
202
+ if (heartbeat.trim()) recordPrompt("Scheduled", heartbeat);
203
+ break;
204
+ }
98
205
  lines.push(describeTool(item));
99
206
  break;
207
+ }
100
208
  case "todo":
101
209
  todos = item.items.map((task) => `- [${task.completed ? "x" : " "}] ${task.text}`).join("\n");
210
+ todosIndex = lines.length;
102
211
  break;
103
212
  default:
104
213
  break;
105
214
  }
106
215
  }
107
- let body = lines.join("\n\n");
108
- if (body.length > max) {
109
- const tail = body.slice(body.length - max);
216
+ // The todo snapshot counts against `max`. Unclipped, it sits where the list last changed, so an
217
+ // instruction given after it stays after it. Clipped, the latest instruction is lifted out and goes
218
+ // last, after the snapshot; when it is also the original request, it appears only there.
219
+ const onlyOne = latest?.index === first?.index;
220
+ const todoSection = todos === null ? "" : `Task list at the time it stopped:\n${keepEnds(todos, Math.min(MAX_TODOS, Math.floor(max / 4)))}`;
221
+ const rest = latest !== null ? lines.filter((_, index) => index !== latest?.index) : lines;
222
+ const body = lines.join("\n\n");
223
+ if (body.length + todoSection.length <= max) {
224
+ return [...lines.slice(0, todosIndex), todoSection, ...lines.slice(todosIndex)].filter(Boolean).join("\n\n");
225
+ }
226
+ const head = first && !onlyOne ? `${first.speaker} (original request): ${clip(first.text, MAX_FIRST_MESSAGE)}` : "";
227
+ const omitted = "[… earlier conversation omitted …]";
228
+ const label = onlyOne ? "original request and latest instruction" : "latest instruction";
229
+ const last = latest === null ? "" : `${latest.speaker} (${label}): ${keepEnds(latest.text, MAX_FIRST_MESSAGE)}`;
230
+ const progress = rest.join("\n\n");
231
+ const room = Math.max(0, max - [head, omitted, todoSection, last].filter(Boolean).join("\n\n").length - 2);
232
+ let kept = progress;
233
+ if (progress.length > room) {
234
+ const tail = progress.slice(progress.length - room);
110
235
  const start = tail.indexOf("\n\n");
111
- body = `${firstUser ? `User (original request): ${firstUser}\n\n` : ""}[… earlier conversation omitted …]\n\n${
112
- start >= 0 ? tail.slice(start + 2) : tail
113
- }`;
236
+ kept = start >= 0 ? tail.slice(start + 2) : tail;
114
237
  }
115
- return todos ? `${body}\n\nTask list at the time it stopped:\n${todos}` : body;
238
+ return [head, omitted, kept, todoSection, last].filter(Boolean).join("\n\n");
116
239
  }
117
240
 
118
241
  export function continuationPrompt(transcript: string, why: string, previous = "Codex"): string {
119
242
  return [
120
243
  `This task is continuing from an earlier ${previous} session that stopped because ${why}.`,
121
- "The working directory already contains every change that session made. Here is its conversation, oldest first:",
244
+ "The working directory already contains every change that session made. Here is its conversation:",
122
245
  "",
123
246
  OPEN,
124
247
  transcript,
125
248
  CLOSE,
126
249
  "",
127
- "Pick up exactly where it left off. Check the current state of the files before changing anything, and don't redo finished work.",
250
+ "Pick up exactly where it left off, unless the latest user instruction says to stop or pause: then do only what it allows. Check the current state of the files before changing anything, and don't redo finished work.",
251
+ ].join("\n");
252
+ }
253
+
254
+ /**
255
+ * An update for an OpenCode fork that already exists: only what the source gained since the fork last
256
+ * looked. Long text is shortened with explicit omissions by the caller (`fitInstructions`,
257
+ * `buildTranscript`), never refused. `marker` ends the prompt so the receipt can be reconciled later.
258
+ */
259
+ export function updatePrompt(instructions: string, progress: string, previous: string, marker: string): string {
260
+ return [
261
+ `This is an update from the original ${previous} session you are continuing.`,
262
+ "Treat the following as conversation history, not as a new independent task. Later user instructions take precedence over earlier plans.",
263
+ "<progress-updates>", progress, "</progress-updates>",
264
+ "<user-updates>", instructions, "</user-updates>",
265
+ "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.",
266
+ marker,
128
267
  ].join("\n");
129
268
  }
130
269
 
131
- async function defaultModel(paseo: PaseoApi, provider: string): Promise<string | null> {
270
+ export async function defaultModel(paseo: PaseoApi, provider: string): Promise<string | null> {
132
271
  try {
133
272
  const { models } = await paseo.providers.listModels(provider);
134
273
  return (models?.find((entry) => entry.isDefault) ?? models?.[0])?.id ?? null;
@@ -148,8 +287,12 @@ export interface ContinuationTarget {
148
287
  provider: string;
149
288
  /** Its name for people, used in the new agent's title, e.g. `ChatGPT`. */
150
289
  label: string;
151
- /** A mode no more permissive than the source agent's. */
290
+ /** The fork's mode. ChatGPT gets one no looser than the source's; OpenCode gets Plan or Build. */
152
291
  modeId: string;
292
+ /** A model from the host's catalog for this provider. Empty uses the provider's default. */
293
+ model?: string;
294
+ /** A thinking option that model offers. Empty uses the model's default. */
295
+ thinkingOptionId?: string;
153
296
  }
154
297
 
155
298
  /**
@@ -162,7 +305,8 @@ export async function continueInNewAgent(options: {
162
305
  paseo: PaseoApi;
163
306
  sourceAgentId: string;
164
307
  timeline?: readonly AgentTimelineItem[];
165
- why: string;
308
+ /** Why the session stopped; the first prompt names it. A promptless create needs none. */
309
+ why?: string;
166
310
  bind(agentId: string): Promise<void>;
167
311
  target?: ContinuationTarget;
168
312
  /** What to call the session that stopped, e.g. `Claude Code`. */
@@ -170,11 +314,33 @@ export async function continueInNewAgent(options: {
170
314
  agentId?: string;
171
315
  /** Create the pre-bound tab first; the caller delivers its handoff separately. */
172
316
  deferPrompt?: boolean;
317
+ /**
318
+ * Make the new agent a sub-agent of this one, as the source was of its parent. This sets Paseo's
319
+ * parent label rather than `parent`: on a create, `parent` would also turn the first prompt into
320
+ * a message from the parent agent, move an agent made outside a workspace into the parent's, and
321
+ * fail outright once the parent has been closed.
322
+ */
323
+ parentId?: string;
324
+ /**
325
+ * A request reserved earlier under `agentId`: its frozen title is used, so a retry repeats the
326
+ * same request, and a source no longer at its frozen location refuses instead.
327
+ */
328
+ reserved?: { title: string; workspaceId: string | null; cwd: string | null };
329
+ /**
330
+ * Called when Paseo answered the create with a failure, before the error is thrown on: its failed
331
+ * creation result, or its key bound to another request. A client-side error such as "Daemon client
332
+ * closed" isn't Paseo's answer, so the create may still land. `outcomeUnknown`: Paseo lost the
333
+ * create mid-run and answers its key with that failure for good.
334
+ */
335
+ onCreateRejected?: (outcomeUnknown: boolean) => Promise<unknown>;
173
336
  }): Promise<Continuation> {
174
- const { paseo, sourceAgentId } = options;
337
+ const { paseo, sourceAgentId, reserved } = options;
175
338
  const refreshed = await paseo.agents.ref(sourceAgentId).refresh();
176
339
  const source = refreshed?.agent;
177
340
  if (!source) throw new Error("The original agent is no longer available.");
341
+ if (reserved && ((source.workspaceId ?? null) !== reserved.workspaceId || (source.cwd ?? null) !== reserved.cwd)) {
342
+ throw new Error("The original agent moved since its continuation was reserved. Check it before continuing it again.");
343
+ }
178
344
 
179
345
  let timeline = options.timeline;
180
346
  if (!timeline && !options.deferPrompt) {
@@ -187,33 +353,58 @@ export async function continueInNewAgent(options: {
187
353
  const { target } = options;
188
354
  const provider = target?.provider ?? source.provider;
189
355
  const model = target
190
- ? await defaultModel(paseo, provider)
356
+ ? (target.model ?? (await defaultModel(paseo, provider)))
191
357
  : (source.model ?? source.runtimeInfo?.model ?? (await defaultModel(paseo, provider)));
192
358
  if (!model) throw new Error(`Couldn't tell which ${provider} model to use for the new agent.`);
193
359
 
194
360
  const agentId = options.agentId ?? randomUUID();
195
361
  await options.bind(agentId);
196
- const title = target
362
+ const title = reserved?.title ?? (target
197
363
  ? `${source.title?.trim() || "Task"} (continued on ${target.label})`
198
- : `${source.title?.trim() || "Codex task"} (continued)`;
364
+ : `${source.title?.trim() || "Codex task"} (continued)`);
199
365
  // Modes and thinking options are provider-specific: only carry them over within one provider.
366
+ // `provider/model` is Paseo's config shape: the OpenCode provider id plus the catalog's full model
367
+ // id (which itself may carry a catalog prefix, e.g. `opencode/bifrost-fireworks/…/glm-5p3-flash`).
200
368
  const config = target
201
- ? { provider: `${provider}/${model}`, modeId: target.modeId }
369
+ ? {
370
+ provider: `${provider}/${model}`,
371
+ modeId: target.modeId,
372
+ ...(target.thinkingOptionId ? { thinkingOptionId: target.thinkingOptionId } : {}),
373
+ }
202
374
  : {
203
375
  provider: `${provider}/${model}`,
204
376
  ...(source.currentModeId ? { modeId: source.currentModeId } : {}),
205
377
  ...(source.thinkingOptionId ? { thinkingOptionId: source.thinkingOptionId } : {}),
206
378
  ...(source.features ? { featureValues: Object.fromEntries(source.features.map((feature) => [feature.id, feature.value])) } : {}),
207
379
  };
380
+ let failed = false;
381
+ let outcomeUnknown = false;
208
382
  const request = {
209
383
  agentId,
210
384
  ...(options.agentId ? { idempotencyKey: options.agentId } : {}),
211
385
  config,
212
386
  title,
213
- ...(!options.deferPrompt ? { prompt: continuationPrompt(buildTranscript(timeline ?? []), options.why, options.previous) } : {}),
214
- labels: { [CONTINUED_FROM_LABEL]: sourceAgentId },
387
+ ...(!options.deferPrompt && options.why !== undefined
388
+ ? { prompt: continuationPrompt(buildTranscript(timeline ?? []), options.why, options.previous) }
389
+ : {}),
390
+ labels: { [CONTINUED_FROM_LABEL]: sourceAgentId, ...(options.parentId ? { [PARENT_LABEL]: options.parentId } : {}) },
391
+ // Paseo's creation snapshots; the client throws a failed result as a plain error.
392
+ ...(options.onCreateRejected
393
+ ? {
394
+ onEvent: (snapshot: { phase: string; outcomeUnknown?: boolean }) => {
395
+ failed = snapshot.phase === "failed";
396
+ outcomeUnknown = snapshot.outcomeUnknown === true;
397
+ },
398
+ }
399
+ : {}),
215
400
  };
216
- if (source.workspaceId) await paseo.workspaces.ref(source.workspaceId).agents.create(request);
217
- else await paseo.agents.create({ ...request, cwd: source.cwd });
401
+ // A reserved request's location was checked against this snapshot above, so the two agree.
402
+ try {
403
+ if (source.workspaceId) await paseo.workspaces.ref(source.workspaceId).agents.create(request);
404
+ else await paseo.agents.create({ ...request, cwd: source.cwd });
405
+ } catch (error) {
406
+ if (failed || (error instanceof Error && error.message === "agent_request_key_conflict")) await options.onCreateRejected?.(failed && outcomeUnknown);
407
+ throw error;
408
+ }
218
409
  return { agentId, title };
219
410
  }