@kapybara/zerosub 1.5.1 → 1.18.3

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 +220 -26
  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 +67 -17
  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 +211 -29
  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 -805
  50. package/server/state.ts +303 -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
@@ -1,37 +1,38 @@
1
- import { randomUUID } from "node:crypto";
1
+ import { createHash, randomUUID } from "node:crypto";
2
2
  import type { PluginHookContext } from "@getpaseo/plugin/server";
3
3
  import { sameAccountIdentity } from "./account-identity";
4
4
  import type { AgentTimelineItem } from "./adapter";
5
- import { buildTranscript, CONTINUED_FROM_LABEL, continueInNewAgent, keepEnds, PARENT_LABEL, type Continuation } from "./handoff";
5
+ import { buildTranscript, CONTINUED_FROM_LABEL, continueInNewAgent, keepEnds, PARENT_LABEL, promptInstruction, type Continuation } from "./handoff";
6
6
  import { Mutex } from "./json-file";
7
7
  import { isUsable } from "./routing";
8
8
  import { findAccount, MAIN_ACCOUNT_ID, StateStore, type ContinuationChain, type StoredAccount, type StoredState } from "./state";
9
9
 
10
10
  type PaseoApi = PluginHookContext["paseo"];
11
- type Agent = NonNullable<Awaited<ReturnType<ReturnType<PaseoApi["agents"]["ref"]>["refresh"]>>>["agent"];
11
+ export type Agent = NonNullable<Awaited<ReturnType<ReturnType<PaseoApi["agents"]["ref"]>["refresh"]>>>["agent"];
12
12
  type Member = ContinuationChain["members"][string];
13
13
  type Pending = NonNullable<ContinuationChain["pending"]>;
14
14
  type Mark = Member["seen"][string];
15
15
  type Source = "auto" | "user";
16
16
  type Update = { item: AgentTimelineItem; timestamp: string };
17
- const MESSAGE_PREFIX = "zerosub-handoff-";
17
+ /** Every handoff prompt of ours carries a caller message ID with this prefix. */
18
+ export const MESSAGE_PREFIX = "zerosub-handoff-";
18
19
  const MAX_PAGES = 100;
19
20
  const MAX_INSTRUCTIONS = 60_000;
20
21
  const MAX_ORIGIN = 6_000;
21
22
  const OMITTED = "[… part of this message omitted to fit this update …]";
22
23
 
23
24
  /** The same checkout. Paseo starts a workspace's new agents in its directory, not the source's subfolder. */
24
- function samePlace(left: Agent, right: Agent): boolean {
25
+ export function samePlace(left: Agent, right: Agent): boolean {
25
26
  if (left.provider !== right.provider || left.workspaceId !== right.workspaceId) return false;
26
27
  return Boolean(left.workspaceId) || left.cwd === right.cwd;
27
28
  }
28
29
 
29
- function ready(agent: Agent): boolean {
30
+ export function ready(agent: Agent): boolean {
30
31
  return !agent.archivedAt && !agent.providerUnavailable && !agent.activeTurn &&
31
32
  !agent.pendingPermissions?.length && (agent.status === "idle" || agent.status === "closed" || agent.status === "error");
32
33
  }
33
34
 
34
- function busy(agent: Agent): boolean {
35
+ export function busy(agent: Agent): boolean {
35
36
  return agent.status === "running" || agent.status === "initializing" || Boolean(agent.activeTurn);
36
37
  }
37
38
 
@@ -63,8 +64,17 @@ function chainOf(state: StoredState, agentId: string): string | undefined {
63
64
  return Object.keys(state.continuations).find((id) => state.continuations[id]?.members[agentId]);
64
65
  }
65
66
 
66
- async function snapshot(paseo: PaseoApi, agentId: string): Promise<Agent | undefined> {
67
- return (await paseo.agents.ref(agentId).refresh())?.agent;
67
+ /**
68
+ * The agent, or undefined when Paseo doesn't know it. Paseo 0.9.1 to 0.10.3 throw "Agent not found"
69
+ * for an unknown ID where later versions answer null; any other error still throws.
70
+ */
71
+ export async function snapshot(paseo: PaseoApi, agentId: string): Promise<Agent | undefined> {
72
+ try {
73
+ return (await paseo.agents.ref(agentId).refresh())?.agent ?? undefined;
74
+ } catch (error) {
75
+ if (error instanceof Error && /Agent not found/.test(error.message)) return undefined;
76
+ throw error;
77
+ }
68
78
  }
69
79
 
70
80
  /** Commit exactly the reserved context, whether the acknowledgement arrived normally or on retry. */
@@ -451,7 +461,7 @@ async function checkCurrent(paseo: PaseoApi, chain: ContinuationChain, sourceAge
451
461
  }
452
462
 
453
463
  /** The source must have stopped, without a newer message than the one that asked for the switch. */
454
- async function waitForSource(paseo: PaseoApi, original: Agent, source: Source): Promise<Agent> {
464
+ export async function waitForSource(paseo: PaseoApi, original: Agent, source: Source): Promise<Agent> {
455
465
  let agent = await snapshot(paseo, original.id);
456
466
  // turn_ended can arrive just before the directory reports idle, as in the existing reopener.
457
467
  for (let attempt = 0; source === "auto" && agent && attempt < 20 && (agent.status === "running" || agent.status === "initializing"); attempt += 1) {
@@ -466,7 +476,7 @@ async function waitForSource(paseo: PaseoApi, original: Agent, source: Source):
466
476
  }
467
477
 
468
478
  /** A tab created without a prompt can still report initializing for a moment before it is idle. */
469
- async function waitForCreated(paseo: PaseoApi, agentId: string): Promise<Agent | undefined> {
479
+ export async function waitForCreated(paseo: PaseoApi, agentId: string): Promise<Agent | undefined> {
470
480
  let agent = await snapshot(paseo, agentId);
471
481
  for (let attempt = 0; agent?.status === "initializing" && attempt < 20; attempt += 1) {
472
482
  await new Promise((resolve) => setTimeout(resolve, 300));
@@ -599,10 +609,13 @@ function composePrompt(chain: ContinuationChain, destination: Destination, gathe
599
609
  // After a downgrade (or loss of the original tab), the oldest surviving tab may start with
600
610
  // a full handoff instead of the human's request. A fresh recipient still needs that origin.
601
611
  const fresh = !destination.agent || reserved || destination.entry?.unstarted;
602
- const origin = fresh ? updates.find(({ item }) => item.type === "user_message")?.item : undefined;
612
+ const origin = fresh ? updates.find(({ item }) => Boolean(promptInstruction(item)?.trim()))?.item : undefined;
603
613
  const items = updates.map((entry) => entry.item).filter((item) =>
604
614
  fallback || item === origin || item.type !== "user_message" || !ownHandoff(item, chain));
605
- const instructions = fitInstructions(items.filter((item) => item.type === "user_message").map((item) => item.text));
615
+ const instructions = fitInstructions(items.flatMap((item) => {
616
+ const text = promptInstruction(item);
617
+ return text?.trim() ? [text] : [];
618
+ }));
606
619
  if (!destination.agent && !instructions.trim()) throw new Error("Couldn't read the task's instructions. Provide a current summary before switching.");
607
620
  return [
608
621
  `This task is continuing because ${why}.`,
@@ -610,26 +623,63 @@ function composePrompt(chain: ContinuationChain, destination: Destination, gathe
610
623
  ...(fallback ? ["An earlier tab is unavailable or moved. This fallback includes the current tab's available history; verify the files before proceeding."] : []),
611
624
  "Treat the following as conversation history, not as a new independent task. Later user instructions take precedence over earlier plans.",
612
625
  "<user-updates>", instructions, "</user-updates>",
613
- "<progress-updates>", buildTranscript(items.filter((item) => item.type !== "user_message")), "</progress-updates>",
626
+ "<progress-updates>", buildTranscript(items.filter((item) => promptInstruction(item) === null)), "</progress-updates>",
614
627
  "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.",
615
628
  ].join("\n");
616
629
  }
617
630
 
618
631
  /** The daemon accepted this message as a turn: it carries our ID and a turn. */
619
- function delivered(entry: { item: AgentTimelineItem; turnId?: string }, messageId: string): boolean {
632
+ export function delivered(entry: { item: AgentTimelineItem; turnId?: string }, messageId: string): boolean {
620
633
  return Boolean(entry.turnId) && entry.item.type === "user_message" && entry.item.clientMessageId === messageId;
621
634
  }
622
635
 
636
+ /** The marker line that ends every OpenCode-path prompt, so a receipt can be found after a reload. */
637
+ export function transferMarker(messageId: string): string {
638
+ return `zerosub transfer ${messageId}`;
639
+ }
640
+
641
+ function digestOf(text: string): string {
642
+ return createHash("sha256").update(text).digest("hex");
643
+ }
644
+
645
+ /** Digest of the exact sent text, stored with the reservation so a receipt can be matched later. */
646
+ export function sentDigestOf(prompt: string): string {
647
+ return digestOf(prompt);
648
+ }
649
+
650
+ /**
651
+ * Whether a timeline row proves this exact message arrived. The fast path is our caller message ID on
652
+ * a turn. A provider reload changes the timeline's epoch and drops that ID, so the marker line inside
653
+ * the exact text, hashed, settles it too.
654
+ */
655
+ export function matchesTransfer(entry: { item: AgentTimelineItem; turnId?: string }, messageId: string, digest: string): boolean {
656
+ if (delivered(entry, messageId)) return true;
657
+ return entry.item.type === "user_message" && entry.item.text.includes(transferMarker(messageId)) &&
658
+ digestOf(entry.item.text) === digest;
659
+ }
660
+
661
+ export class UnresolvableEpochError extends Error {}
662
+
623
663
  /** Canonical sequence cursors avoid re-sending projected messages that merge across a watermark. */
624
- async function readUpdates(paseo: PaseoApi, agentId: string, since?: Mark, receiptId?: string) {
664
+ export async function readUpdates(
665
+ paseo: PaseoApi,
666
+ agentId: string,
667
+ since?: Mark,
668
+ receiptId?: string,
669
+ options: { onEpochReset?: "replay" | "unresolvable" } = {},
670
+ ) {
625
671
  const timeline = paseo.agents.ref(agentId).timeline;
626
672
  let page = await timeline.refetch({ direction: "tail", limit: 500, projection: "canonical" });
627
673
  if (page.gap || page.staleCursor) throw new Error("The task's handoff history has a gap. Check its timeline before continuing.");
628
674
  const mark = { epoch: page.epoch, seq: page.window.maxSeq };
675
+ if (since && since.epoch !== page.epoch && options.onEpochReset === "unresolvable") {
676
+ throw new UnresolvableEpochError("The source timeline epoch changed, so its unread history can't be determined.");
677
+ }
629
678
  const after = since?.epoch === page.epoch ? since.seq : -1;
630
679
  const entries = [...page.entries];
631
680
  const foundReceipt = () => receiptId !== undefined && entries.some((entry) => delivered(entry, receiptId));
632
- for (let pages = 1; page.hasOlder && (page.startCursor?.seq ?? 0) > after && !foundReceipt(); pages += 1) {
681
+ // Older rows with no cursor to reach them can't be proven read, whatever the watermark says.
682
+ for (let pages = 1; page.hasOlder && (page.startCursor?.seq ?? Infinity) > after && !foundReceipt(); pages += 1) {
633
683
  if (pages >= MAX_PAGES || !page.startCursor) throw new Error("Couldn't read the complete handoff history. Try again after checking the task's timeline.");
634
684
  page = await timeline.refetch({ direction: "before", cursor: page.startCursor, limit: 500, projection: "canonical" });
635
685
  if (page.epoch !== mark.epoch || page.staleCursor || page.gap) throw new Error("The task's history changed during the handoff. Try again.");
@@ -0,0 +1,222 @@
1
+ import { spawn } from "node:child_process";
2
+ import {
3
+ ProgressEmitter,
4
+ spawnEnv,
5
+ type EnvPatch,
6
+ type FamilyAdapter,
7
+ type Identity,
8
+ type LoginHandle,
9
+ type RedeemReply,
10
+ type UsageRead,
11
+ } from "./adapter";
12
+ import { cursorBinary } from "./binaries";
13
+ import { prepareCursorHome } from "./homes";
14
+ import { firstUrl, run, stripAnsi } from "./process";
15
+
16
+ /**
17
+ * Logins `cursor-agent` takes from the environment over the one in its login file, and saves into
18
+ * that file when it does: an added account's agents get them blanked, when the daemon's environment
19
+ * sets them, so their work never runs on, or overwrites the account with, another login.
20
+ */
21
+ export const OVERRIDING_AUTH = ["CURSOR_API_KEY", "CURSOR_AUTH_TOKEN"] as const;
22
+
23
+ /**
24
+ * Why Cursor accounts are Linux only: elsewhere `cursor-agent` keeps its login where only moving a
25
+ * folder every tool reads too would separate it (`HOME` on macOS, `APPDATA` on Windows).
26
+ */
27
+ export const CURSOR_UNSUPPORTED: Partial<Record<NodeJS.Platform, string>> = {
28
+ darwin: "Cursor accounts are Linux only for now: on macOS cursor-agent keeps its login in the Keychain or under ~/.cursor, which only moving HOME for every tool would separate.",
29
+ win32: "Cursor accounts are Linux only for now: on Windows cursor-agent keeps its login under %APPDATA%, which only moving APPDATA for every tool would separate.",
30
+ };
31
+
32
+ const OTHER_PLATFORM = "Cursor accounts are Linux only for now.";
33
+
34
+ function str(value: unknown): string | null {
35
+ if (typeof value === "number" && Number.isFinite(value)) return String(value);
36
+ return typeof value === "string" && value.trim() ? value.trim() : null;
37
+ }
38
+
39
+ /**
40
+ * Who `cursor-agent status --format json` says is signed in: `isAuthenticated`, and `userInfo` with
41
+ * `email`, `userId` and `teamId` (`teamName` too), when Cursor could say. Signed in without
42
+ * `userInfo` is still signed in, just not knowing as whom. Never reads anything else. Throws on output
43
+ * that isn't that JSON, so a failed check never counts as signed out.
44
+ */
45
+ export function parseCursorStatus(output: string): Identity {
46
+ const start = output.indexOf("{");
47
+ const value = JSON.parse(start >= 0 ? output.slice(start) : output) as unknown;
48
+ if (!value || typeof value !== "object" || Array.isArray(value) || typeof (value as { isAuthenticated?: unknown }).isAuthenticated !== "boolean") {
49
+ throw new Error("cursor-agent status gave no sign-in status.");
50
+ }
51
+ const status = value as { isAuthenticated: boolean; userInfo?: unknown };
52
+ if (!status.isAuthenticated) return { signedIn: false, email: null, plan: null, organization: null, identity: null };
53
+ const info = status.userInfo && typeof status.userInfo === "object" && !Array.isArray(status.userInfo) ? (status.userInfo as Record<string, unknown>) : {};
54
+ const email = str(info.email);
55
+ const who = str(info.userId) ?? email?.toLowerCase() ?? null;
56
+ const team = str(info.teamId);
57
+ return {
58
+ signedIn: true,
59
+ email,
60
+ plan: null,
61
+ organization: str(info.teamName),
62
+ identity: who ? `cursor|${team && team !== "0" ? team : "personal"}|${who}` : null,
63
+ };
64
+ }
65
+
66
+ /** The sign-in link `cursor-agent login` prints (`https://cursor.com/loginDeepControl?…`), once it has. */
67
+ export function readCursorLogin(output: string): { url: string; userCode: null } | null {
68
+ const url =
69
+ firstUrl(output, /^https:\/\/(?:[\w-]+\.)*cursor\.(?:com|sh)\/loginDeepControl\b/) ?? firstUrl(output, /^https:\/\/(?:[\w-]+\.)*cursor\.(?:com|sh)\//);
70
+ return url ? { url, userCode: null } : null;
71
+ }
72
+
73
+ export class CursorAdapter implements FamilyAdapter {
74
+ readonly family = "cursor" as const;
75
+ /**
76
+ * Resuming a Cursor conversation on a second account isn't verified, so Cursor agents stay on their
77
+ * account, like Grok's, and don't hand off (see `HAND_OFF`).
78
+ */
79
+ readonly portable = false;
80
+ readonly usageSpacingMs = 60_000;
81
+
82
+ constructor(private readonly platform: NodeJS.Platform = process.platform) {}
83
+
84
+ /**
85
+ * An added account's home is its `XDG_CONFIG_HOME` (see `prepareCursorHome`); the CLI login runs as
86
+ * the daemon has it. A `CURSOR_CONFIG_DIR` in the daemon's environment is blanked for added accounts,
87
+ * like the logins in `OVERRIDING_AUTH`, so it can't point every account at one `cli-config.json`
88
+ * (`cursor-agent` takes an empty one as unset).
89
+ */
90
+ async env(home: string | null): Promise<EnvPatch> {
91
+ if (this.platform !== "linux") return {};
92
+ if (!home) return { XDG_CONFIG_HOME: null };
93
+ const patch: EnvPatch = { XDG_CONFIG_HOME: home };
94
+ for (const key of [...OVERRIDING_AUTH, "CURSOR_CONFIG_DIR"]) if (process.env[key]) patch[key] = "";
95
+ return patch;
96
+ }
97
+
98
+ /** Linux only (see `CURSOR_UNSUPPORTED`); there, once a Paseo provider runs `cursor-agent acp`. */
99
+ async available(): Promise<{ ok: boolean; detail: string | null }> {
100
+ if (this.platform !== "linux") return { ok: false, detail: CURSOR_UNSUPPORTED[this.platform] ?? OTHER_PLATFORM };
101
+ const command = await cursorBinary();
102
+ if (!command) return { ok: false, detail: "no Paseo provider runs `cursor-agent acp`" };
103
+ const result = await run(command, ["--version"], { timeoutMs: 30_000 });
104
+ if (result.code === 0) return { ok: true, detail: null };
105
+ return { ok: false, detail: (result.stderr || result.stdout).trim().split("\n")[0] || `${command} not found` };
106
+ }
107
+
108
+ prepareHome(home: string): Promise<void> {
109
+ if (this.platform !== "linux") return Promise.reject(new Error(CURSOR_UNSUPPORTED[this.platform] ?? OTHER_PLATFORM));
110
+ return prepareCursorHome(home);
111
+ }
112
+
113
+ /**
114
+ * Runs `cursor-agent status --format json` with the account's folders; never reads its login file.
115
+ * Off Linux only for the CLI login: `env` leaves an added account on the CLI login's folders there.
116
+ */
117
+ async identity(home: string | null): Promise<Identity> {
118
+ if (home && this.platform !== "linux") throw new Error(CURSOR_UNSUPPORTED[this.platform] ?? OTHER_PLATFORM);
119
+ const command = (await cursorBinary()) ?? "cursor-agent";
120
+ const result = await run(command, ["status", "--format", "json"], { env: spawnEnv(await this.env(home), "cursor"), timeoutMs: 30_000 });
121
+ if (result.timedOut) throw new Error("`cursor-agent status` didn't answer in time.");
122
+ if (result.code !== 0) {
123
+ throw new Error(stripAnsi(result.stderr || result.stdout).trim().split("\n")[0] || `cursor-agent status failed (exit ${result.code ?? "signal"})`);
124
+ }
125
+ return parseCursorStatus(stripAnsi(result.stdout));
126
+ }
127
+
128
+ /**
129
+ * `cursor-agent` has no command that shows plan usage, and ZeroSub doesn't call Cursor's dashboard
130
+ * API with the account's login, so usage stays unavailable.
131
+ */
132
+ async usage(): Promise<UsageRead> {
133
+ return {
134
+ fetchedAt: new Date().toISOString(),
135
+ windows: [],
136
+ error: "cursor-agent has no command that shows plan usage yet. Check it in Cursor's dashboard.",
137
+ cached: false,
138
+ resets: null,
139
+ };
140
+ }
141
+
142
+ async redeemReset(): Promise<RedeemReply> {
143
+ return { outcome: "none", message: "Cursor has no banked resets.", left: null };
144
+ }
145
+
146
+ async login(home: string | null): Promise<LoginHandle> {
147
+ if (home && this.platform !== "linux") throw new Error(CURSOR_UNSUPPORTED[this.platform] ?? OTHER_PLATFORM);
148
+ const command = (await cursorBinary()) ?? "cursor-agent";
149
+ // The link is read from what `cursor-agent login` prints; no browser opens on the daemon's machine.
150
+ const env = { ...spawnEnv(await this.env(home), "cursor"), NO_OPEN_BROWSER: "1" };
151
+ return new CursorLogin(command, ["login"], env);
152
+ }
153
+
154
+ /**
155
+ * Linux only, like an added account's sign-in: elsewhere `env` leaves the account on the CLI
156
+ * login's folders, so this would sign the CLI login out.
157
+ */
158
+ async logout(home: string): Promise<void> {
159
+ if (this.platform !== "linux") throw new Error(CURSOR_UNSUPPORTED[this.platform] ?? OTHER_PLATFORM);
160
+ const command = (await cursorBinary()) ?? "cursor-agent";
161
+ const result = await run(command, ["logout"], { env: spawnEnv(await this.env(home), "cursor"), timeoutMs: 30_000 });
162
+ if (result.code !== 0) throw new Error((result.stderr || result.stdout).trim().split("\n")[0] || "cursor-agent logout failed");
163
+ }
164
+
165
+ /** Failover is for a follow-up: how Cursor's limit and sign-out notices reach Paseo isn't known yet. */
166
+ detectLimit(): null {
167
+ return null;
168
+ }
169
+
170
+ detectSignOut(): null {
171
+ return null;
172
+ }
173
+ }
174
+
175
+ /**
176
+ * `cursor-agent login`: it prints a sign-in link, which works in a browser on any device (the CLI asks
177
+ * Cursor whether it was used), and exits 0 once signed in.
178
+ */
179
+ export class CursorLogin extends ProgressEmitter implements LoginHandle {
180
+ readonly finished: Promise<{ ok: boolean; message: string | null }>;
181
+ private readonly child;
182
+ private output = "";
183
+ private canceled = false;
184
+ private exited = false;
185
+
186
+ constructor(command: string, args: string[], env: NodeJS.ProcessEnv) {
187
+ super();
188
+ this.child = spawn(command, args, { env, stdio: ["ignore", "pipe", "pipe"] });
189
+ this.finished = new Promise((settle) => {
190
+ this.child.on("error", (error) => settle({ ok: false, message: `Could not start cursor-agent: ${error.message}` }));
191
+ this.child.on("close", (code) => {
192
+ this.exited = true;
193
+ if (this.canceled) return settle({ ok: false, message: "Sign-in was canceled." });
194
+ if (code === 0) return settle({ ok: true, message: null });
195
+ const lines = this.output.split("\n").map((line) => line.trim()).filter(Boolean);
196
+ settle({ ok: false, message: lines.reverse().find((line) => /error|fail|denied|expired|timed out/i.test(line)) ?? "Sign-in did not finish." });
197
+ });
198
+ });
199
+ const read = (chunk: string) => {
200
+ this.output = (this.output + stripAnsi(chunk)).slice(-16_384);
201
+ const link = readCursorLogin(this.output);
202
+ if (link && link.url !== this.progress.url) this.update({ step: "waiting", ...link });
203
+ };
204
+ this.child.stdout.setEncoding("utf8");
205
+ this.child.stderr.setEncoding("utf8");
206
+ this.child.stdout.on("data", read);
207
+ this.child.stderr.on("data", read);
208
+ }
209
+
210
+ async submitCode(): Promise<void> {
211
+ throw new Error("Cursor sign-in doesn't use a pasted code. Finish on the sign-in page.");
212
+ }
213
+
214
+ cancel(): void {
215
+ if (this.exited || this.canceled) return;
216
+ this.canceled = true;
217
+ this.child.kill("SIGTERM");
218
+ setTimeout(() => {
219
+ if (!this.exited) this.child.kill("SIGKILL");
220
+ }, 3_000).unref();
221
+ }
222
+ }
@@ -1,5 +1,7 @@
1
+ import { basename } from "node:path";
1
2
  import type { PluginHandlerContext } from "@getpaseo/plugin/server";
2
- import type { Family } from "../shared/model";
3
+ import { FAMILIES, type Family } from "../shared/model";
4
+ import { rememberProviderEnvs } from "./provider-env";
3
5
 
4
6
  type PaseoApi = PluginHandlerContext["paseo"];
5
7
 
@@ -19,8 +21,45 @@ const OWN_AUTH_KEYS: Record<Family, readonly string[]> = {
19
21
  "CLAUDE_CODE_USE_FOUNDRY",
20
22
  ],
21
23
  codex: ["OPENAI_API_KEY", "CODEX_API_KEY", "CODEX_HOME", "OPENAI_BASE_URL"],
24
+ // Pi keeps every sign-in in its agent directory, and a key stored there outranks one in the
25
+ // environment, so only a directory of the entry's own means it isn't Pi's usual login.
26
+ pi: ["PI_CODING_AGENT_DIR"],
27
+ // Grok's own home, auth file, environment login, API keys, an external auth command, customer SSO,
28
+ // or another chat endpoint: any of them means the entry isn't signed in with `~/.grok`'s login.
29
+ grok: [
30
+ "GROK_HOME",
31
+ "GROK_AUTH",
32
+ "GROK_AUTH_PATH",
33
+ "XAI_API_KEY",
34
+ "GROK_CODE_XAI_API_KEY",
35
+ "GROK_DEPLOYMENT_KEY",
36
+ "GROK_AUTH_PROVIDER_COMMAND",
37
+ "GROK_AUTH_PROVIDER_ACCESS_TOKEN",
38
+ "GROK_OIDC_ISSUER",
39
+ "GROK_OIDC_CLIENT_ID",
40
+ "GROK_OIDC_AUDIENCE",
41
+ "GROK_OIDC_SCOPES",
42
+ "GROK_CLI_CHAT_PROXY_BASE_URL",
43
+ ],
44
+ // An API key or session token (cursor-agent saves either as its login), another endpoint, or a
45
+ // login or settings folder of the entry's own: any of them means it isn't the usual Cursor login.
46
+ cursor: [
47
+ "CURSOR_API_KEY",
48
+ "CURSOR_AUTH_TOKEN",
49
+ "CURSOR_API_ENDPOINT",
50
+ "XDG_CONFIG_HOME",
51
+ "CURSOR_CONFIG_DIR",
52
+ ],
22
53
  };
23
54
 
55
+ /**
56
+ * Families Paseo has a provider of its own for. Grok and Cursor only run as custom ACP providers (see
57
+ * `ACP_COMMANDS`).
58
+ */
59
+ const BUILT_IN: readonly Family[] = ["claude", "codex", "pi"];
60
+
61
+ const isFamily = (id: unknown): id is Family => typeof id === "string" && (FAMILIES as readonly string[]).includes(id);
62
+
24
63
  export function bringsOwnAuth(family: Family, env: Record<string, unknown> | undefined): boolean {
25
64
  if (!env) return false;
26
65
  return OWN_AUTH_KEYS[family].some((key) => typeof env[key] === "string" && env[key] !== "");
@@ -31,24 +70,79 @@ function asRecord(value: unknown): Record<string, unknown> | undefined {
31
70
  }
32
71
 
33
72
  /**
34
- * Maps Paseo provider IDs to the subscription family they run on: the built-in `claude` and `codex`
35
- * providers, plus custom profiles that extend them without their own credentials.
73
+ * Agents Paseo runs only as custom ACP providers, by the binary a provider entry runs (its base name)
74
+ * and the arguments that make it the agent:
75
+ * - Grok Build: `grok` or `grok-<version>`, with `agent` then `stdio` (options between), as in Paseo's
76
+ * catalog entry `["grok", "agent", "stdio"]`. Not one that joins a shared leader (`--leader`): the
77
+ * leader's sessions run on whichever login started it.
78
+ * - Cursor: `cursor-agent` (never the generic `agent` alias; Linux only, so no `.exe` or `.cmd`), with
79
+ * `acp`, as in Paseo's catalog entry `["cursor-agent", "acp"]`. Not one given its own API key or
80
+ * endpoint (`--api-key`, `-e`/`--endpoint`).
81
+ */
82
+ const ACP_COMMANDS: Partial<Record<Family, { binary: RegExp; args(args: readonly string[]): boolean }>> = {
83
+ grok: {
84
+ binary: /^grok(?:-\d[\w.]*)?(?:\.exe)?$/i,
85
+ args: (args) => {
86
+ const agent = args.indexOf("agent");
87
+ return agent >= 0 && args.indexOf("stdio", agent + 1) >= 0 && !args.includes("--leader");
88
+ },
89
+ },
90
+ cursor: {
91
+ binary: /^cursor-agent$/,
92
+ args: (args) => args.includes("acp") && !args.some((arg) => /^(?:--api-key|-e|--endpoint)(?:=|$)/.test(arg)),
93
+ },
94
+ };
95
+
96
+ /** The families matched by command (see `ACP_COMMANDS`), in the order they're tried. */
97
+ const ACP_FAMILIES = Object.keys(ACP_COMMANDS) as Family[];
98
+
99
+ /**
100
+ * The binary a provider entry runs, when it's `family`'s agent over ACP (see `ACP_COMMANDS`):
101
+ * `extends: "acp"`, not disabled, and a command whose binary and arguments are that agent's. Null for
102
+ * anything else.
103
+ */
104
+ export function acpCommand(family: Family, entry: Record<string, unknown> | undefined): string | null {
105
+ const spec = ACP_COMMANDS[family];
106
+ if (!spec || !entry || entry.extends !== "acp" || entry.enabled === false) return null;
107
+ const command = entry.command;
108
+ if (!Array.isArray(command) || command.length === 0 || !command.every((part) => typeof part === "string")) return null;
109
+ const [binary, ...args] = command as string[];
110
+ if (!binary || !spec.binary.test(basename(binary)) || !spec.args(args)) return null;
111
+ return binary;
112
+ }
113
+
114
+ /** The Grok binary a provider entry runs (see `ACP_COMMANDS`), or null. */
115
+ export function grokCommand(entry: Record<string, unknown> | undefined): string | null {
116
+ return acpCommand("grok", entry);
117
+ }
118
+
119
+ /**
120
+ * Maps Paseo provider IDs to the family they run on: the built-in `claude`, `codex` and `pi`
121
+ * providers, custom profiles that extend them without their own credentials, and custom ACP providers
122
+ * that run Grok Build or Cursor's agent (see `ACP_COMMANDS`) without their own credentials.
36
123
  */
37
124
  export function familiesFromConfig(providers: Record<string, unknown> | undefined): Record<string, Family> {
38
125
  const result: Record<string, Family> = {};
39
126
  const entries = providers ?? {};
40
- for (const family of ["claude", "codex"] as const) {
127
+ for (const family of BUILT_IN) {
41
128
  const entry = asRecord(entries[family]);
42
129
  if (!entry || !bringsOwnAuth(family, asRecord(entry.env))) result[family] = family;
43
130
  }
44
131
  for (const [id, value] of Object.entries(entries)) {
45
- if (id === "claude" || id === "codex") continue;
132
+ if (isFamily(id)) continue;
46
133
  const entry = asRecord(value);
47
134
  const base = entry?.extends;
48
- if (base !== "claude" && base !== "codex") continue;
135
+ if (!isFamily(base)) continue;
49
136
  if (bringsOwnAuth(base, asRecord(entry?.env))) continue;
50
137
  result[id] = base;
51
138
  }
139
+ for (const family of ACP_FAMILIES) {
140
+ for (const [id, value] of Object.entries(entries)) {
141
+ if (id in result || (isFamily(id) && id !== family)) continue;
142
+ const entry = asRecord(value);
143
+ if (acpCommand(family, entry) && !bringsOwnAuth(family, asRecord(entry?.env))) result[id] = family;
144
+ }
145
+ }
52
146
  return result;
53
147
  }
54
148
 
@@ -63,10 +157,13 @@ export class FamilyResolver {
63
157
  let value: Record<string, Family>;
64
158
  try {
65
159
  const { config } = await paseo.config.get();
66
- value = familiesFromConfig(asRecord(config.providers));
160
+ const providers = asRecord(config.providers);
161
+ value = familiesFromConfig(providers);
162
+ // Pi's provider `env` (a proxy there, say) is what its agents inherit; see server/pi.ts.
163
+ rememberProviderEnvs(value, providers);
67
164
  } catch (error) {
68
165
  console.warn("[ZeroSub] could not read provider config; using built-in providers only", describe(error));
69
- value = { claude: "claude", codex: "codex" };
166
+ value = Object.fromEntries(BUILT_IN.map((family) => [family, family]));
70
167
  }
71
168
  this.cache = { at: Date.now(), value };
72
169
  return value;