@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.
- package/README.md +222 -27
- package/client/accounts-surface.tsx +344 -110
- package/client/add-account.tsx +335 -23
- package/client/api-account.tsx +250 -0
- package/client/azure-account.tsx +311 -0
- package/client/commands.ts +44 -8
- package/client/composer-item.tsx +203 -0
- package/client/fork-confirm.tsx +71 -0
- package/client/fork-settings.tsx +148 -0
- package/client/pace.tsx +196 -0
- package/client/pi-accounts.tsx +571 -0
- package/client/pills.ts +63 -25
- package/client/reset-confirm.tsx +12 -3
- package/client/settings-screen.tsx +48 -9
- package/client/store.ts +148 -19
- package/client/switch-row.tsx +28 -8
- package/client/ui.tsx +11 -0
- package/index.client.tsx +4 -1
- package/index.server.ts +53 -10
- package/package.json +5 -2
- package/server/account-identity.ts +11 -0
- package/server/adapter.ts +115 -8
- package/server/api-usage.ts +144 -0
- package/server/azure.ts +346 -0
- package/server/binaries.ts +41 -3
- package/server/claude.ts +276 -21
- package/server/codex-same-conversation.ts +71 -0
- package/server/codex.ts +35 -7
- package/server/continuations.ts +128 -18
- package/server/cursor.ts +222 -0
- package/server/families.ts +105 -8
- package/server/grok.ts +225 -0
- package/server/handoff.ts +221 -30
- package/server/homes.ts +1263 -35
- package/server/json-file.ts +39 -8
- package/server/launchers.ts +319 -0
- package/server/limits.ts +80 -3
- package/server/main-proxy.ts +238 -0
- package/server/modes.ts +20 -4
- package/server/paths.ts +81 -1
- package/server/pi.ts +528 -0
- package/server/placement.ts +133 -0
- package/server/process.ts +18 -1
- package/server/processes.ts +66 -0
- package/server/provider-env.ts +28 -0
- package/server/proxy.ts +282 -0
- package/server/reopen.ts +50 -8
- package/server/routing.ts +337 -30
- package/server/service.ts +4320 -803
- package/server/state.ts +305 -24
- package/server/usage.ts +2 -0
- package/shared/format.ts +170 -2
- package/shared/model.ts +339 -2
- package/shared/preferences.ts +22 -1
- package/shared/rpc.ts +130 -8
- package/shared/timeline.ts +11 -0
package/server/continuations.ts
CHANGED
|
@@ -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, 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
|
-
|
|
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
|
-
|
|
67
|
-
|
|
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. */
|
|
@@ -89,6 +99,8 @@ interface Destination {
|
|
|
89
99
|
/** The existing tab, when there is one. */
|
|
90
100
|
agent?: Agent;
|
|
91
101
|
entry?: Member;
|
|
102
|
+
/** A new tab's parent agent, if it's created as a sub-agent. */
|
|
103
|
+
parent?: string;
|
|
92
104
|
}
|
|
93
105
|
|
|
94
106
|
/** What the destination hasn't seen yet, and the timeline marks to record once it has. */
|
|
@@ -126,6 +138,40 @@ export class CodexContinuations {
|
|
|
126
138
|
return current.id === agentId ? null : { agentId: current.id, title: current.agent?.title ?? "Codex task" };
|
|
127
139
|
}
|
|
128
140
|
|
|
141
|
+
/**
|
|
142
|
+
* The agent to create a continuation of `agentId` under, so a sub-agent's continuation is still
|
|
143
|
+
* a sub-agent of the agent that started it: that parent, or where the parent's own task carries
|
|
144
|
+
* on if ZeroSub has continued it too (in another ChatGPT tab, or on the other provider). None for
|
|
145
|
+
* an agent without a parent, or when the parent is archived or gone. A failed lookup means none
|
|
146
|
+
* too: the hand-off goes ahead without a parent rather than not at all.
|
|
147
|
+
*/
|
|
148
|
+
async parentFor(paseo: PaseoApi, agentId: string): Promise<string | undefined> {
|
|
149
|
+
try {
|
|
150
|
+
let parentId = (await snapshot(paseo, agentId))?.labels?.[PARENT_LABEL]?.trim();
|
|
151
|
+
let live: Agent[] | undefined;
|
|
152
|
+
// A continuation on the other provider has only its label to go by, as when an earlier fork is reused.
|
|
153
|
+
const forkOf = async (id: string) => {
|
|
154
|
+
const agent = await snapshot(paseo, id);
|
|
155
|
+
if (!agent) return undefined;
|
|
156
|
+
live ??= await liveAgents(paseo);
|
|
157
|
+
return live.find((other) => other.labels?.[CONTINUED_FROM_LABEL] === id && other.provider !== agent.provider && !other.archivedAt)?.id;
|
|
158
|
+
};
|
|
159
|
+
// Each step goes to where that agent's task went next. A loop in the records ends the walk.
|
|
160
|
+
const seen = new Set([agentId]);
|
|
161
|
+
while (parentId && !seen.has(parentId)) {
|
|
162
|
+
seen.add(parentId);
|
|
163
|
+
const next = (await this.continuesElsewhere(paseo, parentId))?.agentId ?? (await forkOf(parentId));
|
|
164
|
+
if (!next) break;
|
|
165
|
+
parentId = next;
|
|
166
|
+
}
|
|
167
|
+
const parent = parentId && parentId !== agentId ? await snapshot(paseo, parentId) : undefined;
|
|
168
|
+
return parent && !parent.archivedAt ? parent.id : undefined;
|
|
169
|
+
} catch (error) {
|
|
170
|
+
console.error(`[ZeroSub] couldn't look up the parent of ${agentId}; continuing it without one`, error instanceof Error ? error.message : error);
|
|
171
|
+
return undefined;
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
|
|
129
175
|
continue(paseo: PaseoApi, sourceAgentId: string, target: StoredAccount, why: string, source: Source): Promise<Continuation> {
|
|
130
176
|
const key = `${sourceAgentId}:${target.id}`;
|
|
131
177
|
const existing = this.inFlight.get(key);
|
|
@@ -157,6 +203,8 @@ export class CodexContinuations {
|
|
|
157
203
|
const gathered = await gatherUpdates(paseo, state, chain, snapshots, sourceAgent, destination);
|
|
158
204
|
const prompt = composePrompt(chain, destination, gathered, why, Boolean(reserved));
|
|
159
205
|
const messageId = reserved?.messageId ?? `${MESSAGE_PREFIX}${randomUUID()}`;
|
|
206
|
+
// A retried creation has to repeat its first request exactly, parent included.
|
|
207
|
+
if (!destination.agent) destination.parent = reserved ? reserved.parent : await this.parentFor(paseo, sourceAgent.id);
|
|
160
208
|
await this.confirmUnchanged(paseo, sourceAgent, destination, account);
|
|
161
209
|
await this.reserve(root, sourceAgent.id, destination, gathered, account, messageId, source);
|
|
162
210
|
return this.deliver(paseo, root, sourceAgent, destination, account, prompt, messageId, why);
|
|
@@ -265,6 +313,7 @@ export class CodexContinuations {
|
|
|
265
313
|
seen: gathered.seen,
|
|
266
314
|
stage: destination.agent ? "sending" : "creating",
|
|
267
315
|
...(gathered.fallback ? { replaceHistory: gathered.obsolete } : {}),
|
|
316
|
+
...(destination.parent ? { parent: destination.parent } : {}),
|
|
268
317
|
};
|
|
269
318
|
if (!destination.agent) draft.bindings[targetId] = { accountId: account.id, source: source === "user" ? "user" : "thread", at: new Date().toISOString() };
|
|
270
319
|
});
|
|
@@ -286,7 +335,15 @@ export class CodexContinuations {
|
|
|
286
335
|
if (destination.agent) {
|
|
287
336
|
result = { agentId: targetId, title: destination.agent.title ?? "Codex task" };
|
|
288
337
|
} else {
|
|
289
|
-
result = await continueInNewAgent({
|
|
338
|
+
result = await continueInNewAgent({
|
|
339
|
+
paseo,
|
|
340
|
+
sourceAgentId: sourceAgent.id,
|
|
341
|
+
why,
|
|
342
|
+
agentId: targetId,
|
|
343
|
+
deferPrompt: true,
|
|
344
|
+
parentId: destination.parent,
|
|
345
|
+
bind: async () => {},
|
|
346
|
+
});
|
|
290
347
|
// Creation can take time. A user may have started another turn or disabled the account.
|
|
291
348
|
const created = await waitForCreated(paseo, targetId);
|
|
292
349
|
const sourceNow = await snapshot(paseo, sourceAgent.id);
|
|
@@ -354,6 +411,19 @@ async function adoptDescendants(paseo: PaseoApi, original: Agent, ancestors: Age
|
|
|
354
411
|
}
|
|
355
412
|
}
|
|
356
413
|
|
|
414
|
+
/** Every agent that isn't archived, as far as MAX_PAGES pages go. */
|
|
415
|
+
async function liveAgents(paseo: PaseoApi): Promise<Agent[]> {
|
|
416
|
+
const agents: Agent[] = [];
|
|
417
|
+
let cursor: string | undefined;
|
|
418
|
+
for (let page = 0; page < MAX_PAGES; page += 1) {
|
|
419
|
+
const result = await paseo.agents.list({ page: { limit: 200, ...(cursor ? { cursor } : {}) } });
|
|
420
|
+
agents.push(...result.entries.map(({ agent }) => agent));
|
|
421
|
+
if (!result.pageInfo.hasMore || !result.pageInfo.nextCursor) break;
|
|
422
|
+
cursor = result.pageInfo.nextCursor;
|
|
423
|
+
}
|
|
424
|
+
return agents;
|
|
425
|
+
}
|
|
426
|
+
|
|
357
427
|
function newer(left: string | null | undefined, right: string | null | undefined): boolean {
|
|
358
428
|
return left ? !right || Date.parse(left) > Date.parse(right) : false;
|
|
359
429
|
}
|
|
@@ -391,7 +461,7 @@ async function checkCurrent(paseo: PaseoApi, chain: ContinuationChain, sourceAge
|
|
|
391
461
|
}
|
|
392
462
|
|
|
393
463
|
/** The source must have stopped, without a newer message than the one that asked for the switch. */
|
|
394
|
-
async function waitForSource(paseo: PaseoApi, original: Agent, source: Source): Promise<Agent> {
|
|
464
|
+
export async function waitForSource(paseo: PaseoApi, original: Agent, source: Source): Promise<Agent> {
|
|
395
465
|
let agent = await snapshot(paseo, original.id);
|
|
396
466
|
// turn_ended can arrive just before the directory reports idle, as in the existing reopener.
|
|
397
467
|
for (let attempt = 0; source === "auto" && agent && attempt < 20 && (agent.status === "running" || agent.status === "initializing"); attempt += 1) {
|
|
@@ -406,7 +476,7 @@ async function waitForSource(paseo: PaseoApi, original: Agent, source: Source):
|
|
|
406
476
|
}
|
|
407
477
|
|
|
408
478
|
/** A tab created without a prompt can still report initializing for a moment before it is idle. */
|
|
409
|
-
async function waitForCreated(paseo: PaseoApi, agentId: string): Promise<Agent | undefined> {
|
|
479
|
+
export async function waitForCreated(paseo: PaseoApi, agentId: string): Promise<Agent | undefined> {
|
|
410
480
|
let agent = await snapshot(paseo, agentId);
|
|
411
481
|
for (let attempt = 0; agent?.status === "initializing" && attempt < 20; attempt += 1) {
|
|
412
482
|
await new Promise((resolve) => setTimeout(resolve, 300));
|
|
@@ -539,10 +609,13 @@ function composePrompt(chain: ContinuationChain, destination: Destination, gathe
|
|
|
539
609
|
// After a downgrade (or loss of the original tab), the oldest surviving tab may start with
|
|
540
610
|
// a full handoff instead of the human's request. A fresh recipient still needs that origin.
|
|
541
611
|
const fresh = !destination.agent || reserved || destination.entry?.unstarted;
|
|
542
|
-
const origin = fresh ? updates.find(({ item }) => item
|
|
612
|
+
const origin = fresh ? updates.find(({ item }) => Boolean(promptInstruction(item)?.trim()))?.item : undefined;
|
|
543
613
|
const items = updates.map((entry) => entry.item).filter((item) =>
|
|
544
614
|
fallback || item === origin || item.type !== "user_message" || !ownHandoff(item, chain));
|
|
545
|
-
const instructions = fitInstructions(items.
|
|
615
|
+
const instructions = fitInstructions(items.flatMap((item) => {
|
|
616
|
+
const text = promptInstruction(item);
|
|
617
|
+
return text?.trim() ? [text] : [];
|
|
618
|
+
}));
|
|
546
619
|
if (!destination.agent && !instructions.trim()) throw new Error("Couldn't read the task's instructions. Provide a current summary before switching.");
|
|
547
620
|
return [
|
|
548
621
|
`This task is continuing because ${why}.`,
|
|
@@ -550,26 +623,63 @@ function composePrompt(chain: ContinuationChain, destination: Destination, gathe
|
|
|
550
623
|
...(fallback ? ["An earlier tab is unavailable or moved. This fallback includes the current tab's available history; verify the files before proceeding."] : []),
|
|
551
624
|
"Treat the following as conversation history, not as a new independent task. Later user instructions take precedence over earlier plans.",
|
|
552
625
|
"<user-updates>", instructions, "</user-updates>",
|
|
553
|
-
"<progress-updates>", buildTranscript(items.filter((item) => item
|
|
626
|
+
"<progress-updates>", buildTranscript(items.filter((item) => promptInstruction(item) === null)), "</progress-updates>",
|
|
554
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.",
|
|
555
628
|
].join("\n");
|
|
556
629
|
}
|
|
557
630
|
|
|
558
631
|
/** The daemon accepted this message as a turn: it carries our ID and a turn. */
|
|
559
|
-
function delivered(entry: { item: AgentTimelineItem; turnId?: string }, messageId: string): boolean {
|
|
632
|
+
export function delivered(entry: { item: AgentTimelineItem; turnId?: string }, messageId: string): boolean {
|
|
560
633
|
return Boolean(entry.turnId) && entry.item.type === "user_message" && entry.item.clientMessageId === messageId;
|
|
561
634
|
}
|
|
562
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
|
+
|
|
563
663
|
/** Canonical sequence cursors avoid re-sending projected messages that merge across a watermark. */
|
|
564
|
-
async function readUpdates(
|
|
664
|
+
export async function readUpdates(
|
|
665
|
+
paseo: PaseoApi,
|
|
666
|
+
agentId: string,
|
|
667
|
+
since?: Mark,
|
|
668
|
+
receiptId?: string,
|
|
669
|
+
options: { onEpochReset?: "replay" | "unresolvable" } = {},
|
|
670
|
+
) {
|
|
565
671
|
const timeline = paseo.agents.ref(agentId).timeline;
|
|
566
672
|
let page = await timeline.refetch({ direction: "tail", limit: 500, projection: "canonical" });
|
|
567
673
|
if (page.gap || page.staleCursor) throw new Error("The task's handoff history has a gap. Check its timeline before continuing.");
|
|
568
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
|
+
}
|
|
569
678
|
const after = since?.epoch === page.epoch ? since.seq : -1;
|
|
570
679
|
const entries = [...page.entries];
|
|
571
680
|
const foundReceipt = () => receiptId !== undefined && entries.some((entry) => delivered(entry, receiptId));
|
|
572
|
-
|
|
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) {
|
|
573
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.");
|
|
574
684
|
page = await timeline.refetch({ direction: "before", cursor: page.startCursor, limit: 500, projection: "canonical" });
|
|
575
685
|
if (page.epoch !== mark.epoch || page.staleCursor || page.gap) throw new Error("The task's history changed during the handoff. Try again.");
|
package/server/cursor.ts
ADDED
|
@@ -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
|
+
}
|
package/server/families.ts
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
|
+
import { basename } from "node:path";
|
|
1
2
|
import type { PluginHandlerContext } from "@getpaseo/plugin/server";
|
|
2
|
-
import type
|
|
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
|
-
*
|
|
35
|
-
*
|
|
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
|
|
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
|
|
132
|
+
if (isFamily(id)) continue;
|
|
46
133
|
const entry = asRecord(value);
|
|
47
134
|
const base = entry?.extends;
|
|
48
|
-
if (base
|
|
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
|
-
|
|
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 =
|
|
166
|
+
value = Object.fromEntries(BUILT_IN.map((family) => [family, family]));
|
|
70
167
|
}
|
|
71
168
|
this.cache = { at: Date.now(), value };
|
|
72
169
|
return value;
|