copperhead 0.7.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. package/README.md +36 -4
  2. package/dist/agent/animate.js +76 -0
  3. package/dist/agent/animate.js.map +1 -0
  4. package/dist/agent/box.js +89 -0
  5. package/dist/agent/box.js.map +1 -0
  6. package/dist/agent/dock-renderer.js +173 -0
  7. package/dist/agent/dock-renderer.js.map +1 -0
  8. package/dist/agent/logo.js +21 -0
  9. package/dist/agent/logo.js.map +1 -0
  10. package/dist/agent/loop.js +15 -5
  11. package/dist/agent/loop.js.map +1 -1
  12. package/dist/agent/providers/claude-code.js +1 -212
  13. package/dist/agent/providers/claude-code.js.map +1 -1
  14. package/dist/agent/providers/cursor.js +317 -0
  15. package/dist/agent/providers/cursor.js.map +1 -0
  16. package/dist/agent/providers/tool-protocol.js +205 -0
  17. package/dist/agent/providers/tool-protocol.js.map +1 -0
  18. package/dist/agent/render.js +32 -15
  19. package/dist/agent/render.js.map +1 -1
  20. package/dist/agent/runmeta.js +4 -5
  21. package/dist/agent/runmeta.js.map +1 -1
  22. package/dist/agent/theme.js +84 -0
  23. package/dist/agent/theme.js.map +1 -0
  24. package/dist/cli.js +134 -13
  25. package/dist/cli.js.map +1 -1
  26. package/dist/commands/create.js +41 -32
  27. package/dist/commands/create.js.map +1 -1
  28. package/dist/commands/demo.js +146 -0
  29. package/dist/commands/demo.js.map +1 -0
  30. package/dist/commands/doctor.js +240 -0
  31. package/dist/commands/doctor.js.map +1 -0
  32. package/dist/commands/repl-inspect.js +342 -0
  33. package/dist/commands/repl-inspect.js.map +1 -0
  34. package/dist/commands/repl.js +618 -0
  35. package/dist/commands/repl.js.map +1 -0
  36. package/dist/config.js +5 -2
  37. package/dist/config.js.map +1 -1
  38. package/dist/kicad/cli.js +126 -6
  39. package/dist/kicad/cli.js.map +1 -1
  40. package/dist/util/cli-args.js +35 -0
  41. package/dist/util/cli-args.js.map +1 -0
  42. package/dist/util/dock.js +155 -0
  43. package/dist/util/dock.js.map +1 -0
  44. package/dist/util/git.js +129 -4
  45. package/dist/util/git.js.map +1 -1
  46. package/dist/util/live-prompt.js +542 -0
  47. package/dist/util/live-prompt.js.map +1 -0
  48. package/dist/util/paths.js +9 -0
  49. package/dist/util/paths.js.map +1 -1
  50. package/dist/util/select.js +172 -0
  51. package/dist/util/select.js.map +1 -0
  52. package/package.json +3 -2
  53. package/src/agent/animate.ts +90 -0
  54. package/src/agent/box.ts +99 -0
  55. package/src/agent/dock-renderer.ts +181 -0
  56. package/src/agent/logo.ts +23 -0
  57. package/src/agent/loop.ts +15 -5
  58. package/src/agent/providers/claude-code.ts +2 -216
  59. package/src/agent/providers/cursor.ts +364 -0
  60. package/src/agent/providers/tool-protocol.ts +212 -0
  61. package/src/agent/render.ts +33 -16
  62. package/src/agent/runmeta.ts +6 -7
  63. package/src/agent/theme.ts +91 -0
  64. package/src/cli.ts +139 -15
  65. package/src/commands/create.ts +81 -30
  66. package/src/commands/demo.ts +184 -0
  67. package/src/commands/doctor.ts +289 -0
  68. package/src/commands/repl-inspect.ts +353 -0
  69. package/src/commands/repl.ts +685 -0
  70. package/src/config.ts +6 -3
  71. package/src/kicad/cli.ts +132 -7
  72. package/src/layout/claude-ui-layout.md +72 -0
  73. package/src/layout/repl-ui-layout.md +139 -0
  74. package/src/util/cli-args.ts +42 -0
  75. package/src/util/dock.ts +161 -0
  76. package/src/util/git.ts +140 -4
  77. package/src/util/live-prompt.ts +595 -0
  78. package/src/util/paths.ts +10 -0
  79. package/src/util/select.ts +192 -0
@@ -1,7 +1,8 @@
1
1
  import { mkdtemp, rm, utimes } from 'node:fs/promises';
2
2
  import os from 'node:os';
3
3
  import path from 'node:path';
4
- import type { ChatOpts, Msg, Provider, ToolCall, ToolSchema, Turn } from '../types.js';
4
+ import type { ChatOpts, Msg, Provider, ToolSchema, Turn } from '../types.js';
5
+ import { parseToolCalls, renderConversation, renderDelta, renderToolProtocol } from './tool-protocol.js';
5
6
 
6
7
  /**
7
8
  * Saved-login provider: drives Claude Code through the Claude Agent SDK
@@ -314,221 +315,6 @@ export class ClaudeCodeProvider implements Provider {
314
315
  }
315
316
  }
316
317
 
317
- function renderToolProtocol(tools: ToolSchema[]): string {
318
- if (!tools.length) return '';
319
- const lines = [
320
- '# Tool protocol',
321
- '',
322
- 'You are the reasoning half of a tool-driven workflow; you cannot run anything yourself.',
323
- 'To take an action, reply with EXACTLY ONE JSON object and nothing else, wrapped in a',
324
- '```json fenced code block:',
325
- '',
326
- '```json',
327
- '{"tool": "<tool_name>", "args": { ... }}',
328
- '```',
329
- '',
330
- 'Use only the tools listed below, with `args` matching the tool\'s JSON Schema. If you have',
331
- 'no tool to call and only want to say something, reply with plain prose and no JSON block.',
332
- '',
333
- '## Available tools',
334
- ];
335
- for (const t of tools) {
336
- lines.push(
337
- '',
338
- `### ${t.name}`,
339
- t.description,
340
- `Parameters (JSON Schema): ${JSON.stringify(t.parameters)}`,
341
- );
342
- }
343
- return lines.join('\n');
344
- }
345
-
346
- /**
347
- * The prompt for a *resumed* turn (1.1): only the messages added since the last
348
- * turn we sent, and only the ones the resumed session does not already hold. The
349
- * subprocess already has every prior turn plus its own assistant replies, so we
350
- * send just the new user nudges and tool results — that delta is what advances
351
- * the conversation. Falls back to the full render (via the caller) when there is
352
- * no session yet.
353
- */
354
- function renderDelta(messages: Msg[], from: number): string {
355
- const idToName = new Map<string, string>();
356
- for (const m of messages) {
357
- if (m.role === 'assistant') for (const call of m.toolCalls ?? []) idToName.set(call.id, call.name);
358
- }
359
- const parts: string[] = [];
360
- for (const m of messages.slice(Math.max(0, from))) {
361
- if (m.role === 'user') {
362
- parts.push(`[user]\n${m.content}`);
363
- } else if (m.role === 'tool') {
364
- const name = idToName.get(m.toolCallId) ?? m.toolCallId;
365
- parts.push(`[result of ${name}]\n${m.content}`);
366
- }
367
- // assistant/system messages are already in the resumed session — skip them.
368
- }
369
- return parts.join('\n\n');
370
- }
371
-
372
- function renderConversation(messages: Msg[]): string {
373
- const idToName = new Map<string, string>();
374
- const parts: string[] = [];
375
- for (const m of messages) {
376
- if (m.role === 'system') continue;
377
- if (m.role === 'user') {
378
- parts.push(`[user]\n${m.content}`);
379
- } else if (m.role === 'assistant') {
380
- if (m.content) parts.push(`[assistant]\n${m.content}`);
381
- for (const call of m.toolCalls ?? []) {
382
- idToName.set(call.id, call.name);
383
- parts.push(
384
- `[assistant tool call]\n\`\`\`json\n${JSON.stringify({ tool: call.name, args: call.args })}\n\`\`\``,
385
- );
386
- }
387
- } else {
388
- const name = idToName.get(m.toolCallId) ?? m.toolCallId;
389
- parts.push(`[result of ${name}]\n${m.content}`);
390
- }
391
- }
392
- return parts.join('\n\n');
393
- }
394
-
395
- interface Parsed {
396
- text: string | null;
397
- toolCalls: ToolCall[];
398
- nudge?: string;
399
- }
400
-
401
- /**
402
- * Detect a malformed-but-intended tool call in a turn that dispatched none
403
- * (#I10). The signature is machine-recognizable: the text contains
404
- * `"tool":"<name>"` naming a tool in the current catalog, yet nothing parsed.
405
- * That is the exact case where the tolerant extractor's silence misleads the
406
- * model — the JSON was near-miss malformed (a brace short, or the outer object
407
- * split so only an inner `{args}` with no `tool` key balanced), not the tool
408
- * being broken. Returns a one-line steer to re-emit it, or undefined when the
409
- * absence of a call is genuine (plain prose, no tool named).
410
- */
411
- function detectMalformedCall(text: string, catalog: Set<string>): string | undefined {
412
- const re = /"tool"\s*:\s*"([^"]+)"/g;
413
- let m: RegExpExecArray | null;
414
- while ((m = re.exec(text)) !== null) {
415
- const name = m[1]!;
416
- if (catalog.has(name)) {
417
- return (
418
- `A tool call for "${name}" looks malformed — it named the tool but did not parse as ` +
419
- 'valid JSON (likely unbalanced braces or a missing closing brace), so no call ran. ' +
420
- 'Re-emit it as exactly one complete JSON object: {"tool": "...", "args": { ... }}.'
421
- );
422
- }
423
- }
424
- return undefined;
425
- }
426
-
427
- /**
428
- * Extract tool-call JSON from the model's reply. Tolerant by design (D1):
429
- * unparseable output is returned as plain text with no tool calls rather than
430
- * throwing, so a non-conforming turn degrades to the loop's stall/nudge path.
431
- * A parsed block only counts as a tool call when its name is in the current
432
- * turn's catalog (`availableTools(ctx)`): a hallucinated or locked tool name is
433
- * left as prose so the loop nudges, rather than dispatching a bogus call.
434
- */
435
- function parseToolCalls(text: string | null, nextId: () => string, catalog: Set<string>): Parsed {
436
- if (!text) return { text: null, toolCalls: [] };
437
- const toolCalls: ToolCall[] = [];
438
- const matched: Array<[number, number]> = [];
439
-
440
- // Extract tool calls by scanning for complete JSON objects, NOT by matching
441
- // ``` fences. A tool call's `content`/`args` can hold a full markdown doc that
442
- // itself contains ``` code fences; a fence regex truncates the JSON at the
443
- // first inner fence, JSON.parse fails, and the call is silently dropped (the
444
- // model then assumes it wrote a file it never did). The brace scan is
445
- // string-aware, so braces and backticks inside JSON string values are ignored.
446
- let searchFrom = 0;
447
- while (searchFrom < text.length) {
448
- const braceAt = text.indexOf('{', searchFrom);
449
- if (braceAt < 0) break;
450
- const span = scanJsonObject(text, braceAt);
451
- if (!span) {
452
- // Unbalanced '{' (stray brace in prose): retry from the next candidate so
453
- // one bad brace can't hide a well-formed call later in the reply.
454
- searchFrom = braceAt + 1;
455
- continue;
456
- }
457
- const call = toToolCall(text.slice(span.start, span.end), nextId, catalog);
458
- if (call) {
459
- toolCalls.push(call);
460
- matched.push([span.start, span.end]);
461
- }
462
- searchFrom = span.end;
463
- }
464
-
465
- if (!toolCalls.length) {
466
- // No call dispatched — but did the model clearly *intend* one? A fenced
467
- // ```json block that names a catalog tool yet produced zero calls is a
468
- // malformed near-miss (unbalanced braces, a missing `}`, or an inner object
469
- // with no `tool` key). Silently dropping it gives the model no signal, so it
470
- // misreads "no result" as "this tool is broken" and can bake that false
471
- // conclusion into a committed summary (#I10). Surface a nudge instead.
472
- return { text: text.trim() ? text : null, toolCalls, nudge: detectMalformedCall(text, catalog) };
473
- }
474
-
475
- // Prose is whatever survives once the tool-call objects (and any now-empty
476
- // ```json fences around them) are removed.
477
- let prose = '';
478
- let cursor = 0;
479
- for (const [start, end] of matched) {
480
- prose += text.slice(cursor, start);
481
- cursor = end;
482
- }
483
- prose += text.slice(cursor);
484
- prose = prose.replace(/```(?:json)?\s*```/gi, '').replace(/```(?:json)?\s*$/gi, '').trim();
485
- return { text: prose.length ? prose : null, toolCalls };
486
- }
487
-
488
- /**
489
- * Find the first complete, brace-balanced JSON object at or after `from`,
490
- * respecting JSON string quoting/escaping so braces or backticks inside string
491
- * values do not end the scan. Returns its `[start, end)` bounds or null.
492
- */
493
- function scanJsonObject(text: string, from: number): { start: number; end: number } | null {
494
- const start = text.indexOf('{', from);
495
- if (start < 0) return null;
496
- let depth = 0;
497
- let inStr = false;
498
- let esc = false;
499
- for (let i = start; i < text.length; i++) {
500
- const ch = text[i];
501
- if (inStr) {
502
- if (esc) esc = false;
503
- else if (ch === '\\') esc = true;
504
- else if (ch === '"') inStr = false;
505
- continue;
506
- }
507
- if (ch === '"') inStr = true;
508
- else if (ch === '{') depth++;
509
- else if (ch === '}' && --depth === 0) return { start, end: i + 1 };
510
- }
511
- return null;
512
- }
513
-
514
- function toToolCall(raw: string | undefined, nextId: () => string, catalog: Set<string>): ToolCall | null {
515
- if (!raw) return null;
516
- let obj: unknown;
517
- try {
518
- obj = JSON.parse(raw.trim());
519
- } catch {
520
- return null;
521
- }
522
- if (!obj || typeof obj !== 'object') return null;
523
- const rec = obj as Record<string, unknown>;
524
- if (typeof rec.tool !== 'string') return null;
525
- // Only accept names the turn actually advertised. An empty catalog means the
526
- // turn offered no tools, so nothing parses as a call.
527
- if (!catalog.has(rec.tool)) return null;
528
- const args = rec.args && typeof rec.args === 'object' ? (rec.args as Record<string, unknown>) : {};
529
- return { id: nextId(), name: rec.tool, args };
530
- }
531
-
532
318
  function isAuthError(err: unknown): boolean {
533
319
  const status = (err as { status?: number; statusCode?: number })?.status
534
320
  ?? (err as { statusCode?: number })?.statusCode;
@@ -0,0 +1,364 @@
1
+ import { mkdtemp, rm, utimes } from 'node:fs/promises';
2
+ import os from 'node:os';
3
+ import path from 'node:path';
4
+ import { execa } from 'execa';
5
+ import type { ChatOpts, Msg, Provider, ToolSchema, Turn } from '../types.js';
6
+ import { parseToolCalls, renderConversation, renderDelta, renderToolProtocol } from './tool-protocol.js';
7
+
8
+ /**
9
+ * Saved-login provider: drives the Cursor Agent CLI (`agent` / `cursor-agent`) with
10
+ * `agent login` authentication. Reasoning-only: plan mode, sandbox, isolated
11
+ * workspace, JSON tool protocol (see `add-cursor-cli-provider`).
12
+ *
13
+ * Session resume is opt-in and mutually exclusive with the response cache (same
14
+ * rule as claude-code): the cache can replay turns a resumed CLI session never
15
+ * saw, which desyncs history. `makeProvider` enables resume only when the cache
16
+ * is off.
17
+ */
18
+
19
+ export interface CursorRunArgs {
20
+ prompt: string;
21
+ systemPrompt: string;
22
+ workspace: string;
23
+ model?: string;
24
+ resume?: string;
25
+ signal?: AbortSignal;
26
+ env?: NodeJS.ProcessEnv;
27
+ }
28
+
29
+ export interface CursorRunResult {
30
+ text: string;
31
+ sessionId?: string;
32
+ usage: { inputTokens: number; outputTokens: number };
33
+ }
34
+
35
+ export type CursorRunLike = (args: CursorRunArgs) => Promise<CursorRunResult>;
36
+
37
+ const NATIVE_MUTATION_TYPES = new Set([
38
+ 'tool_call',
39
+ 'tool_use',
40
+ 'tool-call',
41
+ 'shell',
42
+ 'write',
43
+ 'edit',
44
+ 'apply_patch',
45
+ 'file_change',
46
+ 'mcp_tool',
47
+ ]);
48
+
49
+ /** Subtype tokens that indicate native execution (whole-token match). */
50
+ const NATIVE_SUBTYPE_RE = /(^|_)(tool|shell|write|edit|patch|mutation)(_|$)/;
51
+
52
+ export class CursorProvider implements Provider {
53
+ readonly name = 'cursor';
54
+ private callSeq = 0;
55
+ private cwdPromise?: Promise<string>;
56
+ private sessionId?: string;
57
+ private sentCount = 0;
58
+ private readonly inFlight = new Set<AbortController>();
59
+
60
+ constructor(
61
+ private readonly model?: string,
62
+ private readonly runFn: CursorRunLike = defaultCursorRun,
63
+ /**
64
+ * Opt-in: resume one CLI session across turns and send only new messages.
65
+ * OFF by default and mutually exclusive with the response cache — mixing
66
+ * them desyncs the resumed session. `makeProvider` enables it only when
67
+ * the cache is off.
68
+ */
69
+ private readonly sessionResume = false,
70
+ ) {}
71
+
72
+ async chat(messages: Msg[], tools: ToolSchema[], opts: ChatOpts = {}): Promise<Turn> {
73
+ const system = messages
74
+ .filter((m) => m.role === 'system')
75
+ .map((m) => m.content)
76
+ .join('\n\n');
77
+ const systemPrompt = [system, renderToolProtocol(tools)].filter(Boolean).join('\n\n');
78
+ const resume = this.sessionResume ? this.sessionId : undefined;
79
+ const prompt = resume ? renderDelta(messages, this.sentCount) : renderConversation(messages);
80
+ const catalog = new Set(tools.map((t) => t.name));
81
+ const workspace = await this.ensureWorkspace();
82
+
83
+ const aborter = new AbortController();
84
+ this.inFlight.add(aborter);
85
+ let inputTokens = 0;
86
+ let outputTokens = 0;
87
+ let text: string | null = null;
88
+ try {
89
+ const result = await this.runFn({
90
+ prompt,
91
+ systemPrompt,
92
+ workspace,
93
+ ...(this.model ? { model: this.model } : {}),
94
+ ...(resume ? { resume } : {}),
95
+ signal: aborter.signal,
96
+ env: subprocessEnv(),
97
+ });
98
+ text = result.text;
99
+ if (this.sessionResume && result.sessionId) this.sessionId = result.sessionId;
100
+ inputTokens = result.usage.inputTokens;
101
+ outputTokens = result.usage.outputTokens;
102
+ opts.onStream?.(text.length);
103
+ } catch (err) {
104
+ if (isAuthError(err)) throw new Error(authHint((err as Error).message));
105
+ throw enhanceCliError(err);
106
+ } finally {
107
+ this.inFlight.delete(aborter);
108
+ }
109
+
110
+ // Only advance the high-water mark when resume is on (same as claude-code).
111
+ if (this.sessionResume) this.sentCount = messages.length;
112
+ const parsed = parseToolCalls(text, () => `cur-${++this.callSeq}`, catalog);
113
+ return {
114
+ text: parsed.text,
115
+ toolCalls: parsed.toolCalls,
116
+ usage: { inputTokens, outputTokens },
117
+ nudge: parsed.nudge,
118
+ };
119
+ }
120
+
121
+ async close(): Promise<void> {
122
+ for (const aborter of this.inFlight) {
123
+ try {
124
+ aborter.abort();
125
+ } catch {
126
+ // best effort
127
+ }
128
+ }
129
+ this.inFlight.clear();
130
+ const pending = this.cwdPromise;
131
+ this.cwdPromise = undefined;
132
+ if (!pending) return;
133
+ try {
134
+ await rm(await pending, { recursive: true, force: true });
135
+ } catch {
136
+ // best effort
137
+ }
138
+ }
139
+
140
+ private async ensureWorkspace(): Promise<string> {
141
+ if (!this.cwdPromise) this.cwdPromise = mkdtemp(path.join(os.tmpdir(), 'copperhead-cursor-'));
142
+ const cwd = await this.cwdPromise;
143
+ const now = new Date();
144
+ await utimes(cwd, now, now).catch(() => {});
145
+ return cwd;
146
+ }
147
+ }
148
+
149
+ /** Minimal env passed to the Cursor CLI subprocess (saved login via `agent login`). */
150
+ const CURSOR_SUBPROCESS_ENV_KEYS = [
151
+ 'PATH',
152
+ 'HOME',
153
+ 'USER',
154
+ 'LOGNAME',
155
+ 'SHELL',
156
+ 'TMPDIR',
157
+ 'TEMP',
158
+ 'TMP',
159
+ 'LANG',
160
+ 'LC_ALL',
161
+ 'LC_CTYPE',
162
+ 'LC_MESSAGES',
163
+ 'TERM',
164
+ 'XDG_CONFIG_HOME',
165
+ 'XDG_DATA_HOME',
166
+ 'XDG_CACHE_HOME',
167
+ 'XDG_RUNTIME_DIR',
168
+ // Windows home / login-config location (`USERPROFILE\.cursor\cli-config.json`)
169
+ 'USERPROFILE',
170
+ 'HOMEDRIVE',
171
+ 'HOMEPATH',
172
+ 'SystemRoot',
173
+ 'ComSpec',
174
+ 'APPDATA',
175
+ 'LOCALAPPDATA',
176
+ ] as const;
177
+
178
+ /** Build an allowlisted env for the Cursor Agent subprocess (no API keys or unrelated secrets). */
179
+ export function subprocessEnv(): NodeJS.ProcessEnv {
180
+ const env: NodeJS.ProcessEnv = {};
181
+ for (const key of CURSOR_SUBPROCESS_ENV_KEYS) {
182
+ const value = process.env[key];
183
+ if (value !== undefined) env[key] = value;
184
+ }
185
+ return env;
186
+ }
187
+
188
+ /** Parse `--print --output-format json` stdout into assistant text and session id. */
189
+ export function parseCursorStdout(stdout: string): CursorRunResult {
190
+ const trimmed = stdout.trim();
191
+ let text = '';
192
+ let sessionId: string | undefined;
193
+ let sawResult = false;
194
+
195
+ // Prefer a single pretty-printed JSON object (whole buffer) before NDJSON lines.
196
+ if (trimmed) {
197
+ try {
198
+ const whole = JSON.parse(trimmed) as Record<string, unknown>;
199
+ const extracted = extractResultFields(whole);
200
+ if (extracted) {
201
+ return {
202
+ text: extracted.text,
203
+ sessionId: extracted.sessionId,
204
+ usage: { inputTokens: 0, outputTokens: 0 },
205
+ };
206
+ }
207
+ } catch (err) {
208
+ if (isCursorHardFail(err)) throw err;
209
+ // fall through to line-based parse
210
+ }
211
+ }
212
+
213
+ const lines = trimmed
214
+ .split('\n')
215
+ .map((l) => l.trim())
216
+ .filter(Boolean);
217
+
218
+ for (const line of lines) {
219
+ let obj: Record<string, unknown>;
220
+ try {
221
+ obj = JSON.parse(line) as Record<string, unknown>;
222
+ } catch {
223
+ continue;
224
+ }
225
+ const extracted = extractResultFields(obj);
226
+ if (extracted) {
227
+ text = extracted.text;
228
+ sessionId = extracted.sessionId ?? sessionId;
229
+ sawResult = true;
230
+ }
231
+ }
232
+
233
+ if (!sawResult && !text && lines.length) {
234
+ // Fallback: last parseable JSON line with a string result field
235
+ for (let i = lines.length - 1; i >= 0; i--) {
236
+ try {
237
+ const obj = JSON.parse(lines[i]!) as Record<string, unknown>;
238
+ if (typeof obj.result === 'string') {
239
+ assertNoNativeMutation(obj);
240
+ text = obj.result;
241
+ if (typeof obj.session_id === 'string') sessionId = obj.session_id;
242
+ sawResult = true;
243
+ break;
244
+ }
245
+ } catch (err) {
246
+ if (isCursorHardFail(err)) throw err;
247
+ continue;
248
+ }
249
+ }
250
+ }
251
+
252
+ if (!sawResult && trimmed) {
253
+ throw new Error(
254
+ `cursor: could not parse Cursor Agent output as JSON — raw stdout: ${trimmed.slice(0, 500)}`,
255
+ );
256
+ }
257
+
258
+ // Official Cursor JSON schema does not expose token usage; callers see zeros.
259
+ return { text, sessionId, usage: { inputTokens: 0, outputTokens: 0 } };
260
+ }
261
+
262
+ function extractResultFields(
263
+ obj: Record<string, unknown>,
264
+ ): { text: string; sessionId?: string } | null {
265
+ assertNoNativeMutation(obj);
266
+ const type = typeof obj.type === 'string' ? obj.type.toLowerCase() : '';
267
+ if (type === 'result' || typeof obj.result === 'string') {
268
+ if (obj.is_error === true) {
269
+ throw new Error(typeof obj.result === 'string' ? obj.result : 'Cursor Agent returned an error result');
270
+ }
271
+ if (typeof obj.result === 'string') {
272
+ return {
273
+ text: obj.result,
274
+ ...(typeof obj.session_id === 'string' ? { sessionId: obj.session_id } : {}),
275
+ };
276
+ }
277
+ }
278
+ return null;
279
+ }
280
+
281
+ function isCursorHardFail(err: unknown): boolean {
282
+ return (
283
+ err instanceof Error &&
284
+ (err.message.includes('reasoning-only invariant') ||
285
+ err.message.includes('Cursor Agent returned an error') ||
286
+ err.message.startsWith('cursor:'))
287
+ );
288
+ }
289
+
290
+ function assertNoNativeMutation(obj: Record<string, unknown>): void {
291
+ const type = typeof obj.type === 'string' ? obj.type.toLowerCase() : '';
292
+ if (NATIVE_MUTATION_TYPES.has(type)) {
293
+ throw new Error(
294
+ `cursor: Cursor Agent emitted native tool event "${obj.type}" — reasoning-only invariant violated. Refusing to continue.`,
295
+ );
296
+ }
297
+ const subtype = typeof obj.subtype === 'string' ? obj.subtype.toLowerCase() : '';
298
+ if (subtype && NATIVE_SUBTYPE_RE.test(subtype) && type !== 'result') {
299
+ throw new Error(
300
+ `cursor: Cursor Agent output subtype "${obj.subtype}" (line type "${obj.type ?? ''}") suggests native execution — reasoning-only invariant violated.`,
301
+ );
302
+ }
303
+ }
304
+
305
+ /** Default subprocess runner: invokes `agent` (or `COPPERHEAD_CURSOR_PATH`) in plan mode. */
306
+ export async function defaultCursorRun(args: CursorRunArgs): Promise<CursorRunResult> {
307
+ const bin = process.env.COPPERHEAD_CURSOR_PATH || 'agent';
308
+ const fullPrompt = [args.systemPrompt, args.prompt].filter(Boolean).join('\n\n---\n\n');
309
+ // Prompt goes on stdin — a single argv element caps at ~128 KiB on Linux
310
+ // (MAX_ARG_STRLEN); real .kicad_pcb reads routinely exceed that.
311
+ const cmdArgs = [
312
+ '--print',
313
+ '--output-format',
314
+ 'json',
315
+ '--mode',
316
+ 'plan',
317
+ '--trust',
318
+ '--sandbox',
319
+ 'enabled',
320
+ '--workspace',
321
+ args.workspace,
322
+ ];
323
+ if (args.model) cmdArgs.push('--model', args.model);
324
+ if (args.resume) cmdArgs.push('--resume', args.resume);
325
+
326
+ const { stdout } = await execa(bin, cmdArgs, {
327
+ input: fullPrompt,
328
+ env: args.env ?? subprocessEnv(),
329
+ cancelSignal: args.signal,
330
+ reject: true,
331
+ maxBuffer: 50 * 1024 * 1024,
332
+ });
333
+ return parseCursorStdout(stdout);
334
+ }
335
+
336
+ function isAuthError(err: unknown): boolean {
337
+ // Subprocess failures use exitCode, not HTTP status. Only treat real HTTP
338
+ // status fields as 401/403; otherwise match the CLI's auth message.
339
+ const status =
340
+ (err as { status?: number; statusCode?: number })?.status ??
341
+ (err as { statusCode?: number })?.statusCode;
342
+ if (status === 401 || status === 403) return true;
343
+ const m = ((err as Error)?.message ?? '').toLowerCase();
344
+ return /unauthenticat|unauthoriz|not logged in|please log in|login required|agent login/.test(m);
345
+ }
346
+
347
+ function authHint(detail: string): string {
348
+ return (
349
+ 'cursor is not authenticated: run `agent login` and verify with `agent status`. ' +
350
+ `Set COPPERHEAD_CURSOR_PATH if the CLI is not on PATH (original error: ${detail})`
351
+ );
352
+ }
353
+
354
+ function enhanceCliError(err: unknown): Error {
355
+ const original = err as Error & { code?: string; exitCode?: number };
356
+ if (original.code === 'ENOENT') {
357
+ return new Error(
358
+ 'Cursor Agent CLI not found on PATH. Install Cursor Agent or set COPPERHEAD_CURSOR_PATH to the `agent` binary.',
359
+ { cause: err },
360
+ );
361
+ }
362
+ if (original.message?.includes('reasoning-only invariant')) return original;
363
+ return new Error(`Cursor CLI provider failed: ${original.message}`, { cause: err });
364
+ }