-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathindex.ts
More file actions
814 lines (730 loc) · 29 KB
/
Copy pathindex.ts
File metadata and controls
814 lines (730 loc) · 29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
/**
* Pi Cursor Provider Extension
*
* Routes Pi model requests through the Cursor Agent CLI (`agent`) so that any
* active Cursor subscription can be used from inside Pi.
*
* Authentication is handled by the CLI itself — run `agent login` (or set the
* CURSOR_API_KEY environment variable) before using this provider.
*
* Usage:
* pi install npm:@netandreus/pi-cursor-provider
* # Then /model cursor/<model-id>, e.g. /model cursor/sonnet-4.5-thinking
*
* Configuration env vars:
* CURSOR_AGENT_PATH Path to the Cursor Agent CLI binary (default: "agent")
* CURSOR_API_KEY API key for Cursor (used by the agent subprocess if set)
*/
import { spawn } from "node:child_process";
import { createInterface } from "node:readline";
import type {
Api,
AssistantMessage,
AssistantMessageEventStream,
Context,
Model,
SimpleStreamOptions,
TextContent,
} from "@mariozechner/pi-ai";
import { createAssistantMessageEventStream } from "@mariozechner/pi-ai";
import type { ExtensionAPI } from "@mariozechner/pi-coding-agent";
// ---------------------------------------------------------------------------
// Model definitions
// ---------------------------------------------------------------------------
interface CursorModelDef {
id: string;
name: string;
reasoning: boolean;
contextWindow: number;
maxTokens: number;
}
/**
* Static fallback list. Used when `agent models` fails or times out, and as
* an attribute lookup table for models discovered dynamically.
*
* Source: `agent models` output (Cursor Agent CLI v2026.02.13-41ac335).
*/
const STATIC_MODELS: CursorModelDef[] = [
// Auto
{ id: "auto", name: "Auto", reasoning: false, contextWindow: 200000, maxTokens: 32768 },
// Composer
{ id: "composer-1.5", name: "Composer 1.5", reasoning: false, contextWindow: 200000, maxTokens: 32768 },
{ id: "composer-1", name: "Composer 1", reasoning: false, contextWindow: 200000, maxTokens: 32768 },
// Claude Opus
{ id: "opus-4.6-thinking", name: "Claude 4.6 Opus (Thinking)", reasoning: true, contextWindow: 200000, maxTokens: 32000 },
{ id: "opus-4.6", name: "Claude 4.6 Opus", reasoning: false, contextWindow: 200000, maxTokens: 32000 },
{ id: "opus-4.5-thinking", name: "Claude 4.5 Opus (Thinking)", reasoning: true, contextWindow: 200000, maxTokens: 32000 },
{ id: "opus-4.5", name: "Claude 4.5 Opus", reasoning: false, contextWindow: 200000, maxTokens: 32000 },
// Claude Sonnet
{ id: "sonnet-4.6-thinking", name: "Claude 4.6 Sonnet (Thinking)", reasoning: true, contextWindow: 200000, maxTokens: 32000 },
{ id: "sonnet-4.6", name: "Claude 4.6 Sonnet", reasoning: false, contextWindow: 200000, maxTokens: 32000 },
{ id: "sonnet-4.5-thinking", name: "Claude 4.5 Sonnet (Thinking)", reasoning: true, contextWindow: 200000, maxTokens: 32000 },
{ id: "sonnet-4.5", name: "Claude 4.5 Sonnet", reasoning: false, contextWindow: 200000, maxTokens: 32000 },
// GPT-5 series
{ id: "gpt-5.3-codex", name: "GPT-5.3 Codex", reasoning: false, contextWindow: 200000, maxTokens: 32768 },
{ id: "gpt-5.3-codex-low", name: "GPT-5.3 Codex Low", reasoning: false, contextWindow: 200000, maxTokens: 32768 },
{ id: "gpt-5.3-codex-high", name: "GPT-5.3 Codex High", reasoning: true, contextWindow: 200000, maxTokens: 32768 },
{ id: "gpt-5.3-codex-xhigh", name: "GPT-5.3 Codex Extra High", reasoning: true, contextWindow: 200000, maxTokens: 32768 },
{ id: "gpt-5.3-codex-fast", name: "GPT-5.3 Codex Fast", reasoning: false, contextWindow: 200000, maxTokens: 32768 },
{ id: "gpt-5.3-codex-low-fast", name: "GPT-5.3 Codex Low Fast", reasoning: false, contextWindow: 200000, maxTokens: 32768 },
{ id: "gpt-5.3-codex-high-fast", name: "GPT-5.3 Codex High Fast", reasoning: true, contextWindow: 200000, maxTokens: 32768 },
{ id: "gpt-5.3-codex-xhigh-fast", name: "GPT-5.3 Codex Extra High Fast", reasoning: true, contextWindow: 200000, maxTokens: 32768 },
{ id: "gpt-5.2", name: "GPT-5.2", reasoning: false, contextWindow: 200000, maxTokens: 32768 },
{ id: "gpt-5.2-high", name: "GPT-5.2 High", reasoning: true, contextWindow: 200000, maxTokens: 32768 },
{ id: "gpt-5.2-codex", name: "GPT-5.2 Codex", reasoning: false, contextWindow: 200000, maxTokens: 32768 },
{ id: "gpt-5.2-codex-high", name: "GPT-5.2 Codex High", reasoning: true, contextWindow: 200000, maxTokens: 32768 },
{ id: "gpt-5.2-codex-low", name: "GPT-5.2 Codex Low", reasoning: false, contextWindow: 200000, maxTokens: 32768 },
{ id: "gpt-5.2-codex-xhigh", name: "GPT-5.2 Codex Extra High", reasoning: true, contextWindow: 200000, maxTokens: 32768 },
{ id: "gpt-5.2-codex-fast", name: "GPT-5.2 Codex Fast", reasoning: false, contextWindow: 200000, maxTokens: 32768 },
{ id: "gpt-5.2-codex-high-fast", name: "GPT-5.2 Codex High Fast", reasoning: true, contextWindow: 200000, maxTokens: 32768 },
{ id: "gpt-5.2-codex-low-fast", name: "GPT-5.2 Codex Low Fast", reasoning: false, contextWindow: 200000, maxTokens: 32768 },
{ id: "gpt-5.2-codex-xhigh-fast", name: "GPT-5.2 Codex Extra High Fast", reasoning: true, contextWindow: 200000, maxTokens: 32768 },
{ id: "gpt-5.1-high", name: "GPT-5.1 High", reasoning: true, contextWindow: 200000, maxTokens: 32768 },
{ id: "gpt-5.1-codex-max", name: "GPT-5.1 Codex Max", reasoning: true, contextWindow: 200000, maxTokens: 32768 },
{ id: "gpt-5.1-codex-max-high", name: "GPT-5.1 Codex Max High", reasoning: true, contextWindow: 200000, maxTokens: 32768 },
{ id: "gpt-5.1-codex-mini", name: "GPT-5.1 Codex Mini", reasoning: false, contextWindow: 200000, maxTokens: 32768 },
// Gemini
{ id: "gemini-3-pro", name: "Gemini 3 Pro", reasoning: false, contextWindow: 1000000, maxTokens: 65536 },
{ id: "gemini-3-flash", name: "Gemini 3 Flash", reasoning: false, contextWindow: 1000000, maxTokens: 65536 },
// Grok
{ id: "grok", name: "Grok", reasoning: false, contextWindow: 131072, maxTokens: 32768 },
];
/** Fast lookup: static model id → definition */
const STATIC_MODELS_MAP = new Map<string, CursorModelDef>(
STATIC_MODELS.map((m) => [m.id, m]),
);
// ---------------------------------------------------------------------------
// Canonical model ID mapping
// Maps canonical IDs (e.g. claude-sonnet-4-5) to CLI model IDs. When Pi
// provides a reasoning/thinking level, the corresponding variant is used.
// ---------------------------------------------------------------------------
type ReasoningLevel = "minimal" | "low" | "medium" | "high" | "xhigh";
interface ModelVariants {
default: string;
minimal?: string;
low?: string;
medium?: string;
high?: string;
xhigh?: string;
}
const MODEL_MAP: Record<string, ModelVariants> = {
"claude-sonnet-4-5": {
default: "sonnet-4.5",
minimal: "sonnet-4.5-thinking",
low: "sonnet-4.5-thinking",
medium: "sonnet-4.5-thinking",
high: "sonnet-4.5-thinking",
xhigh: "sonnet-4.5-thinking",
},
"claude-sonnet-4-6": {
default: "sonnet-4.6",
minimal: "sonnet-4.6-thinking",
low: "sonnet-4.6-thinking",
medium: "sonnet-4.6-thinking",
high: "sonnet-4.6-thinking",
xhigh: "sonnet-4.6-thinking",
},
"claude-opus-4-5": {
default: "opus-4.5",
minimal: "opus-4.5-thinking",
low: "opus-4.5-thinking",
medium: "opus-4.5-thinking",
high: "opus-4.5-thinking",
xhigh: "opus-4.5-thinking",
},
"claude-opus-4-6": {
default: "opus-4.6",
minimal: "opus-4.6-thinking",
low: "opus-4.6-thinking",
medium: "opus-4.6-thinking",
high: "opus-4.6-thinking",
xhigh: "opus-4.6-thinking",
},
"gpt-5.2": {
default: "gpt-5.2",
high: "gpt-5.2-high",
xhigh: "gpt-5.2-high",
},
"gpt-5.2-codex": {
default: "gpt-5.2-codex",
minimal: "gpt-5.2-codex-low",
low: "gpt-5.2-codex-low",
high: "gpt-5.2-codex-high",
xhigh: "gpt-5.2-codex-xhigh",
},
"gpt-5.2-codex-fast": {
default: "gpt-5.2-codex-fast",
minimal: "gpt-5.2-codex-low-fast",
low: "gpt-5.2-codex-low-fast",
high: "gpt-5.2-codex-high-fast",
xhigh: "gpt-5.2-codex-xhigh-fast",
},
"gpt-5.3-codex": {
default: "gpt-5.3-codex",
minimal: "gpt-5.3-codex-low",
low: "gpt-5.3-codex-low",
high: "gpt-5.3-codex-high",
xhigh: "gpt-5.3-codex-xhigh",
},
"gpt-5.3-codex-fast": {
default: "gpt-5.3-codex-fast",
minimal: "gpt-5.3-codex-low-fast",
low: "gpt-5.3-codex-low-fast",
high: "gpt-5.3-codex-high-fast",
xhigh: "gpt-5.3-codex-xhigh-fast",
},
"gpt-5.1": {
default: "gpt-5.1-high",
},
"gpt-5.1-codex-max": {
default: "gpt-5.1-codex-max",
high: "gpt-5.1-codex-max-high",
xhigh: "gpt-5.1-codex-max-high",
},
"gemini-3-pro-preview": { default: "gemini-3-pro" },
"gemini-3-flash-preview": { default: "gemini-3-flash" },
"grok-code-fast-1": { default: "grok" },
};
const cursorDefaultToCanonical = new Map<string, string>();
const allMappedCursorIds = new Set<string>();
for (const [canonicalId, variants] of Object.entries(MODEL_MAP)) {
if (variants.default) cursorDefaultToCanonical.set(variants.default, canonicalId);
for (const cursorId of Object.values(variants)) {
if (cursorId) allMappedCursorIds.add(cursorId);
}
}
/**
* Convert a Cursor CLI model ID to its canonical ID.
* Returns null for variant-only IDs (e.g. thinking); they are not shown as separate models.
* Returns the id as-is for unmapped models.
*/
function toCanonicalId(cursorId: string): string | null {
const canonical = cursorDefaultToCanonical.get(cursorId);
if (canonical) return canonical;
if (allMappedCursorIds.has(cursorId)) return null;
return cursorId;
}
/**
* Resolve a canonical model ID (and optional reasoning level) to the Cursor CLI model ID.
* Returns the id as-is for unmapped models.
*/
function toCursorId(canonicalId: string, reasoning?: string): string {
const family = MODEL_MAP[canonicalId];
if (!family) return canonicalId;
const level = reasoning as ReasoningLevel | undefined;
const variant = level && family[level];
return variant ?? family.default ?? canonicalId;
}
// ---------------------------------------------------------------------------
// Dynamic model discovery via `agent models`
// ---------------------------------------------------------------------------
/** Timeout (ms) for `agent models` discovery call. */
const DISCOVERY_TIMEOUT_MS = 15_000;
/**
* Infer the `reasoning` flag for a model that is not in the static list.
* Models whose id ends with -thinking, -high, -xhigh, -max-high, or -max are
* treated as reasoning/extended-thinking models.
*/
function inferReasoning(id: string): boolean {
return /(-thinking|-high|-xhigh|-max-high)$/.test(id);
}
/**
* Parse the text output of `agent models` into a list of model definitions.
*
* Expected format (one model per line after the header, before the tip):
* <id> - <name> [(current[, default] | default)]
*
* Example lines:
* "auto - Auto"
* "opus-4.6-thinking - Claude 4.6 Opus (Thinking) (default)"
* "sonnet-4.6 - Claude 4.6 Sonnet (current)"
*/
function parseAgentModelsOutput(output: string): CursorModelDef[] {
const results: CursorModelDef[] = [];
// Match lines like: "model-id - Display Name (optional flags)"
const lineRe = /^([a-zA-Z0-9][a-zA-Z0-9._-]*)\s+-\s+(.+?)(?:\s+\((?:current|default|current,\s*default)\))?$/;
for (const line of output.split("\n")) {
const trimmed = line.trim();
if (!trimmed || trimmed.startsWith("Available") || trimmed.startsWith("Tip:")) continue;
const match = lineRe.exec(trimmed);
if (!match) continue;
const id = match[1].trim();
const rawName = match[2].trim();
// Use static attributes if available, otherwise infer
const known = STATIC_MODELS_MAP.get(id);
results.push({
id,
name: rawName,
reasoning: known?.reasoning ?? inferReasoning(id),
contextWindow: known?.contextWindow ?? 200000,
maxTokens: known?.maxTokens ?? 32768,
});
}
return results;
}
/**
* Run `agent models` and return the parsed model list.
* Rejects if the CLI exits with an error, produces no usable output, or
* exceeds the discovery timeout.
*/
function runAgentModels(agentPath: string): Promise<CursorModelDef[]> {
return new Promise((resolve, reject) => {
const args = ["models"];
if (process.env["CURSOR_API_KEY"]) {
args.unshift("--api-key", process.env["CURSOR_API_KEY"]);
}
let stdout = "";
let stderr = "";
const child = spawn(agentPath, args, {
stdio: ["ignore", "pipe", "pipe"],
env: process.env,
});
const timeout = setTimeout(() => {
child.kill("SIGTERM");
reject(new Error(`agent models timed out after ${DISCOVERY_TIMEOUT_MS}ms`));
}, DISCOVERY_TIMEOUT_MS);
child.stdout?.on("data", (chunk: Buffer) => { stdout += chunk.toString(); });
child.stderr?.on("data", (chunk: Buffer) => { stderr += chunk.toString(); });
child.on("error", (err) => {
clearTimeout(timeout);
reject(err);
});
child.on("close", (code) => {
clearTimeout(timeout);
if (code !== 0) {
reject(new Error(`agent models exited with code ${code}: ${stderr.trim()}`));
return;
}
const models = parseAgentModelsOutput(stdout);
if (models.length === 0) {
reject(new Error("agent models returned no models"));
return;
}
resolve(models);
});
});
}
// ---------------------------------------------------------------------------
// Prompt serialisation
// Serialises the Pi context into a single text prompt for the CLI.
// Cursor CLI receives the conversation as one -p "..." argument; multi-turn
// history is included as a prefixed transcript (best-effort).
// ---------------------------------------------------------------------------
/**
* Convert a content block (text or image) to a plain string for the CLI prompt.
* Images are serialised as a textual placeholder because the Cursor Agent CLI
* (v2026.02.13) does not support image attachments in the `--print` prompt.
* The placeholder preserves the image's MIME type and byte-size so the model
* can at least acknowledge that an image was intended.
*/
function contentBlockToText(block: TextContent | import("@mariozechner/pi-ai").ImageContent): string {
if (block.type === "text") return block.text;
// ImageContent: { type: "image", data: string (base64), mimeType: string }
const bytes = Math.round((block.data.length * 3) / 4);
return `[Image: ${block.mimeType}, ~${bytes} bytes — note: image input is not supported by the Cursor Agent CLI; the visual content cannot be passed through]`;
}
function serializeContext(context: Context): string {
const lines: string[] = [];
if (context.systemPrompt) {
lines.push(`[System]\n${context.systemPrompt}\n`);
}
for (const msg of context.messages) {
if (msg.role === "user") {
const text =
typeof msg.content === "string"
? msg.content
: msg.content.map(contentBlockToText).join("\n");
lines.push(`[User]\n${text}`);
} else if (msg.role === "assistant") {
const text = msg.content
.filter((c): c is TextContent => c.type === "text")
.map((c) => c.text)
.join("\n");
if (text.trim()) {
lines.push(`[Assistant]\n${text}`);
}
} else if (msg.role === "toolResult") {
const text = msg.content.map(contentBlockToText).join("\n");
if (text.trim()) {
lines.push(`[Tool result: ${msg.toolName}]\n${text}`);
}
}
}
return lines.join("\n\n");
}
// ---------------------------------------------------------------------------
// NDJSON event types — Cursor CLI stream-json shape
// ---------------------------------------------------------------------------
interface CursorAssistantEvent {
type: "assistant";
message: { role: "assistant"; content: Array<{ type: "text"; text: string }> };
session_id: string;
}
/**
* A single Cursor CLI tool call (the value keyed by tool name).
* The key is the tool name in camelCase (e.g. "shellToolCall", "readToolCall").
* args are present on both started and completed; result only on completed.
*/
interface CursorToolCallPayload {
args: Record<string, unknown>;
result?: {
success?: Record<string, unknown>;
rejected?: { reason?: string };
error?: { message?: string };
};
}
interface CursorToolCallEvent {
type: "tool_call";
subtype: "started" | "completed";
/** The outer object has exactly one key: the tool name (e.g. "shellToolCall"). */
tool_call: Record<string, CursorToolCallPayload>;
}
interface CursorResultEvent {
type: "result";
subtype: string;
duration_ms: number;
}
type CursorStreamEvent =
| CursorAssistantEvent
| CursorToolCallEvent
| CursorResultEvent
| { type: string };
function parseLine(line: string): CursorStreamEvent | null {
const trimmed = line.trim();
if (!trimmed) return null;
try {
return JSON.parse(trimmed) as CursorStreamEvent;
} catch {
return null;
}
}
// ---------------------------------------------------------------------------
// Tool name mapping — CLI camelCase key → Pi display name
// ---------------------------------------------------------------------------
const TOOL_NAME_MAP: Record<string, string> = {
shellToolCall: "Shell",
readToolCall: "Read",
editToolCall: "Edit",
writeToolCall: "Write",
deleteToolCall: "Delete",
grepToolCall: "Grep",
globToolCall: "Glob",
lsToolCall: "Ls",
todoToolCall: "Todo",
updateTodosToolCall: "UpdateTodos",
findToolCall: "Find",
webFetchToolCall: "WebFetch",
webSearchToolCall: "WebSearch",
};
/** Convert a CLI tool event key (e.g. "shellToolCall") to a Pi tool name. */
function toPiToolName(cliKey: string): string {
return TOOL_NAME_MAP[cliKey] ?? cliKey.replace(/ToolCall$/, "");
}
// ---------------------------------------------------------------------------
// streamSimple — the custom backend for the cursor provider
// ---------------------------------------------------------------------------
function streamCursorCli(
model: Model<Api>,
context: Context,
options?: SimpleStreamOptions,
): AssistantMessageEventStream {
const stream = createAssistantMessageEventStream();
(async () => {
const startTime = Date.now();
let firstTokenTime: number | undefined;
const output: AssistantMessage & { duration?: number; ttft?: number } = {
role: "assistant",
content: [],
api: model.api,
provider: model.provider,
model: model.id,
usage: {
input: 0,
output: 0,
cacheRead: 0,
cacheWrite: 0,
totalTokens: 0,
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
},
stopReason: "stop",
timestamp: Date.now(),
};
const setTiming = () => {
output.duration = Date.now() - startTime;
output.ttft = firstTokenTime != null ? firstTokenTime - startTime : undefined;
};
try {
const agentPath =
process.env["CURSOR_AGENT_PATH"] ??
process.env["AGENT_PATH"] ??
"agent";
const workspacePath = process.cwd();
const prompt = serializeContext(context);
const reasoningLevel = (options as { reasoning?: string })?.reasoning;
const cliModelId = toCursorId(model.id, reasoningLevel);
const args = [
"--print",
"--output-format", "stream-json",
"--model", cliModelId,
"--trust",
"--workspace", workspacePath,
prompt,
];
if (process.env["CURSOR_API_KEY"]) {
args.unshift("--api-key", process.env["CURSOR_API_KEY"]);
}
stream.push({ type: "start", partial: output });
const child = spawn(agentPath, args, {
stdio: ["ignore", "pipe", "pipe"],
env: process.env,
});
const onAbort = () => {
child.kill("SIGTERM");
};
options?.signal?.addEventListener("abort", onAbort, { once: true });
const stderrChunks: string[] = [];
child.stderr?.on("data", (chunk: Buffer) => {
stderrChunks.push(chunk.toString());
});
let textBlockOpen = false;
let accumulatedText = "";
const rl = createInterface({ input: child.stdout!, crlfDelay: Infinity });
rl.on("line", (line: string) => {
const event = parseLine(line);
if (!event) return;
if (event.type === "assistant") {
const ae = event as CursorAssistantEvent;
for (const block of ae.message.content) {
if (block.type !== "text") continue;
if (!block.text.trim()) continue;
if (firstTokenTime === undefined) firstTokenTime = Date.now();
if (!textBlockOpen) {
output.content.push({ type: "text", text: "" });
const idx = output.content.length - 1;
stream.push({ type: "text_start", contentIndex: idx, partial: output });
textBlockOpen = true;
}
const idx = output.content.length - 1;
const textBlock = output.content[idx] as TextContent;
textBlock.text += block.text;
accumulatedText += block.text;
stream.push({ type: "text_delta", contentIndex: idx, delta: block.text, partial: output });
}
return;
}
// Tool calls are rendered as informational text, not as Pi toolcall_*
// events, to prevent Pi's agentic loop from re-invoking streamSimple.
if (event.type === "tool_call") {
const tce = event as CursorToolCallEvent;
const cliKey = Object.keys(tce.tool_call)[0];
if (!cliKey) return;
const toolName = toPiToolName(cliKey);
if (tce.subtype === "started") {
const payload = tce.tool_call[cliKey];
const argsSnippet = JSON.stringify(payload.args ?? {});
const brief = argsSnippet.length > 120 ? argsSnippet.slice(0, 120) + "…" : argsSnippet;
const marker = `\n⏳ [${toolName}] ${brief}\n`;
if (!textBlockOpen) {
output.content.push({ type: "text", text: "" });
const idx = output.content.length - 1;
stream.push({ type: "text_start", contentIndex: idx, partial: output });
textBlockOpen = true;
}
const idx = output.content.length - 1;
const textBlock = output.content[idx] as TextContent;
textBlock.text += marker;
accumulatedText += marker;
stream.push({ type: "text_delta", contentIndex: idx, delta: marker, partial: output });
}
}
});
await new Promise<void>((resolve) => {
child.on("close", (code) => {
options?.signal?.removeEventListener("abort", onAbort);
if (textBlockOpen) {
const idx = output.content.length - 1;
stream.push({ type: "text_end", contentIndex: idx, content: accumulatedText, partial: output });
textBlockOpen = false;
}
if (options?.signal?.aborted) {
output.stopReason = "aborted";
setTiming();
stream.push({ type: "error", reason: "aborted", error: output });
stream.end();
resolve();
return;
}
if (code !== 0 && !accumulatedText) {
const stderr = stderrChunks.join("").trim();
output.stopReason = "error";
output.errorMessage = stderr || `Cursor CLI exited with code ${code}`;
setTiming();
stream.push({ type: "error", reason: "error", error: output });
stream.end();
resolve();
return;
}
setTiming();
stream.push({ type: "done", reason: "stop", message: output });
stream.end();
resolve();
});
child.on("error", (err) => {
options?.signal?.removeEventListener("abort", onAbort);
output.stopReason = "error";
output.errorMessage = err.message;
setTiming();
stream.push({ type: "error", reason: "error", error: output });
stream.end();
resolve();
});
});
} catch (error) {
output.stopReason = options?.signal?.aborted ? "aborted" : "error";
output.errorMessage = error instanceof Error ? error.message : String(error);
setTiming();
stream.push({ type: "error", reason: output.stopReason, error: output });
stream.end();
}
})();
return stream;
}
// ---------------------------------------------------------------------------
// Auth helpers
// ---------------------------------------------------------------------------
/**
* Spawn `agent login` in an interactive child process so the user can
* authenticate with Cursor from within a Pi session.
* Returns a promise that resolves when login completes (exit 0) and rejects
* on non-zero exit or spawn error.
*/
function runAgentLogin(agentPath: string): Promise<void> {
return new Promise((resolve, reject) => {
const args: string[] = ["login"];
// Suppress browser-open so login is purely CLI-driven (prints URL/code)
const env = { ...process.env, NO_OPEN_BROWSER: "1" };
const child = spawn(agentPath, args, {
stdio: "inherit",
env,
});
child.on("error", (err) => reject(err));
child.on("close", (code) => {
if (code === 0) resolve();
else reject(new Error(`agent login exited with code ${code}`));
});
});
}
/**
* Run `agent status` and return the trimmed output (e.g. "✓ Logged in as …").
*/
function runAgentStatus(agentPath: string): Promise<string> {
return new Promise((resolve, reject) => {
let out = "";
const child = spawn(agentPath, ["status"], {
stdio: ["ignore", "pipe", "pipe"],
env: process.env,
});
child.stdout?.on("data", (c: Buffer) => { out += c.toString(); });
child.stderr?.on("data", (c: Buffer) => { out += c.toString(); });
child.on("error", (err) => reject(err));
child.on("close", () => resolve(out.trim()));
});
}
// ---------------------------------------------------------------------------
// Extension entry point
// ---------------------------------------------------------------------------
/**
* Build a ProviderModelConfig array from a list of CursorModelDef entries.
* Uses canonical IDs where a mapping exists and omits variant-only entries.
*/
function toProviderModels(defs: CursorModelDef[]) {
const seen = new Set<string>();
return defs.flatMap((m) => {
const canonicalId = toCanonicalId(m.id);
if (canonicalId === null) return []; // variant-only; hide
const id = canonicalId !== m.id ? canonicalId : m.id;
if (seen.has(id)) return [];
seen.add(id);
return [
{
id,
name: `${m.name} (Cursor)`,
reasoning: m.reasoning,
input: ["text"] as ("text" | "image")[],
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
contextWindow: m.contextWindow,
maxTokens: m.maxTokens,
},
];
});
}
export default async function (pi: ExtensionAPI) {
const agentPath =
process.env["CURSOR_AGENT_PATH"] ??
process.env["AGENT_PATH"] ??
"agent";
// Attempt dynamic model discovery; fall back to static list on any failure.
let modelDefs: CursorModelDef[];
try {
modelDefs = await runAgentModels(agentPath);
} catch {
modelDefs = STATIC_MODELS;
}
pi.registerProvider("cursor", {
baseUrl: "cli://cursor-agent",
apiKey: "CURSOR_API_KEY",
api: "cursor-cli" as Api,
models: toProviderModels(modelDefs),
streamSimple: streamCursorCli,
});
// ---------------------------------------------------------------------------
// Slash commands for Cursor auth management
// ---------------------------------------------------------------------------
pi.registerCommand("cursor-login", {
description: "Log in to Cursor (runs `agent login`)",
handler: async (_args, ctx) => {
ctx.ui.notify("Starting Cursor login (NO_OPEN_BROWSER=1 — copy the URL from the output)…", "info");
try {
await runAgentLogin(agentPath);
ctx.ui.notify("Cursor login successful.", "info");
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
ctx.ui.notify(`Cursor login failed: ${msg}`, "error");
}
},
});
pi.registerCommand("cursor-status", {
description: "Show Cursor authentication status (runs `agent status`)",
handler: async (_args, ctx) => {
try {
const status = await runAgentStatus(agentPath);
ctx.ui.notify(status || "No output from `agent status`.", "info");
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
ctx.ui.notify(`Could not get Cursor status: ${msg}`, "error");
}
},
});
pi.registerCommand("cursor-logout", {
description: "Log out of Cursor (runs `agent logout`)",
handler: async (_args, ctx) => {
try {
await new Promise<void>((resolve, reject) => {
const child = spawn(agentPath, ["logout"], {
stdio: "inherit",
env: process.env,
});
child.on("error", reject);
child.on("close", (code) => {
if (code === 0) resolve();
else reject(new Error(`agent logout exited with code ${code}`));
});
});
ctx.ui.notify("Logged out of Cursor.", "info");
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
ctx.ui.notify(`Cursor logout failed: ${msg}`, "error");
}
},
});
}