chatccc 0.2.200 → 0.2.202

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 (92) hide show
  1. package/README.md +17 -15
  2. package/agent-prompts/claude_specific.md +45 -45
  3. package/agent-prompts/codex_specific.md +2 -2
  4. package/agent-prompts/cursor_specific.md +13 -13
  5. package/bin/cccagent.mjs +17 -17
  6. package/config.sample.json +27 -27
  7. package/im-skills/feishu-skill/receive-send-file.md +63 -63
  8. package/im-skills/feishu-skill/receive-send-image.md +24 -24
  9. package/im-skills/feishu-skill/skill.md +3 -3
  10. package/im-skills/wechat-file-skill/receive-send-file.md +38 -38
  11. package/im-skills/wechat-file-skill/send-file.mjs +83 -83
  12. package/im-skills/wechat-file-skill/skill.md +10 -10
  13. package/im-skills/wechat-image-skill/skill.md +10 -10
  14. package/im-skills/wechat-video-skill/receive-send-video.md +38 -38
  15. package/im-skills/wechat-video-skill/send-video.mjs +79 -79
  16. package/im-skills/wechat-video-skill/skill.md +10 -10
  17. package/package.json +1 -1
  18. package/scripts/postinstall-sharp-check.mjs +58 -58
  19. package/src/__tests__/agent-delegate-task-rpc.test.ts +165 -165
  20. package/src/__tests__/agent-reload-config-rpc.test.ts +99 -99
  21. package/src/__tests__/builtin-chat-session.test.ts +277 -277
  22. package/src/__tests__/builtin-cli-json.test.ts +39 -39
  23. package/src/__tests__/builtin-config.test.ts +33 -33
  24. package/src/__tests__/builtin-context.test.ts +163 -163
  25. package/src/__tests__/builtin-file-tools.test.ts +224 -224
  26. package/src/__tests__/builtin-session-select.test.ts +116 -116
  27. package/src/__tests__/builtin-sigint.test.ts +56 -56
  28. package/src/__tests__/card-plain-text.test.ts +5 -5
  29. package/src/__tests__/cardkit.test.ts +60 -60
  30. package/src/__tests__/cards.test.ts +133 -122
  31. package/src/__tests__/ccc-adapter.test.ts +114 -114
  32. package/src/__tests__/chatgpt-subscription-rpc.test.ts +89 -89
  33. package/src/__tests__/chatgpt-subscription.test.ts +135 -135
  34. package/src/__tests__/chrome-devtools-guard.test.ts +165 -165
  35. package/src/__tests__/claude-adapter.test.ts +592 -592
  36. package/src/__tests__/claude-raw-stream-log.test.ts +87 -87
  37. package/src/__tests__/codex-raw-stream-log.test.ts +163 -163
  38. package/src/__tests__/codex-reset-actions.test.ts +146 -146
  39. package/src/__tests__/config-reload.test.ts +10 -10
  40. package/src/__tests__/config-sample.test.ts +18 -18
  41. package/src/__tests__/cursor-adapter.test.ts +226 -226
  42. package/src/__tests__/feishu-api.test.ts +60 -60
  43. package/src/__tests__/feishu-avatar.test.ts +90 -90
  44. package/src/__tests__/feishu-platform.test.ts +22 -22
  45. package/src/__tests__/format-message.test.ts +47 -47
  46. package/src/__tests__/jsonl-stream.test.ts +79 -79
  47. package/src/__tests__/orchestrator.test.ts +464 -301
  48. package/src/__tests__/privacy.test.ts +198 -198
  49. package/src/__tests__/raw-stream-log.test.ts +106 -106
  50. package/src/__tests__/session.test.ts +46 -44
  51. package/src/__tests__/shared-prefix.test.ts +36 -36
  52. package/src/__tests__/sim-platform.test.ts +12 -12
  53. package/src/__tests__/stream-state.test.ts +42 -42
  54. package/src/__tests__/web-ui.test.ts +209 -209
  55. package/src/adapters/ccc-adapter.ts +121 -121
  56. package/src/adapters/claude-adapter.ts +603 -603
  57. package/src/adapters/claude-session-meta-store.ts +120 -120
  58. package/src/adapters/codex-adapter.ts +380 -380
  59. package/src/adapters/cursor-adapter.ts +673 -673
  60. package/src/adapters/jsonl-stream.ts +157 -157
  61. package/src/adapters/raw-stream-log.ts +124 -124
  62. package/src/adapters/resource-monitor.ts +140 -140
  63. package/src/agent-delegate-task-rpc.ts +153 -153
  64. package/src/agent-delegate-task.ts +81 -81
  65. package/src/agent-reload-config-rpc.ts +34 -34
  66. package/src/agent-stop-stuck.ts +129 -129
  67. package/src/builtin/cli.ts +473 -473
  68. package/src/builtin/context.ts +323 -323
  69. package/src/builtin/file-tools.ts +1072 -1072
  70. package/src/builtin/index.ts +404 -404
  71. package/src/builtin/session-select.ts +48 -48
  72. package/src/builtin/sigint.ts +50 -50
  73. package/src/cards.ts +222 -210
  74. package/src/chatgpt-subscription-rpc.ts +27 -27
  75. package/src/chatgpt-subscription.ts +299 -299
  76. package/src/chrome-devtools-guard.ts +318 -318
  77. package/src/codex-reset-actions.ts +184 -184
  78. package/src/config.ts +125 -125
  79. package/src/feishu-api.ts +118 -118
  80. package/src/feishu-platform.ts +20 -20
  81. package/src/format-message.ts +293 -293
  82. package/src/litellm-proxy.ts +374 -374
  83. package/src/orchestrator.ts +348 -329
  84. package/src/privacy.ts +118 -118
  85. package/src/runtime-reload.ts +34 -34
  86. package/src/session-chat-binding.ts +6 -6
  87. package/src/session-name.ts +8 -8
  88. package/src/session.ts +177 -169
  89. package/src/shared-prefix.ts +29 -29
  90. package/src/sim-platform.ts +20 -20
  91. package/src/turn-cards.ts +117 -117
  92. package/src/web-ui.ts +205 -205
@@ -1,673 +1,673 @@
1
- // =============================================================================
2
- // cursor-adapter.ts — Cursor Agent CLI 适配器
3
- // =============================================================================
4
- // 通过 agent -p --output-format stream-json 与 Cursor agent 交互。
5
- // 命令行可通过 config.json cursor.path / cursor.model 自定义。
6
- // =============================================================================
7
-
8
- import { spawn, type ChildProcess } from "node:child_process";
9
- import { existsSync, readFileSync } from "node:fs";
10
- import { dirname, join } from "node:path";
11
- import { fileURLToPath } from "node:url";
12
-
13
- import type {
14
- ToolAdapter,
15
- ToolPromptOptions,
16
- UnifiedBlock,
17
- UnifiedStreamMessage,
18
- CreateSessionResult,
19
- SessionInfo,
20
- } from "./adapter-interface.ts";
21
- import { parseUserCommand } from "./adapter-interface.ts";
22
- import { config, CURSOR_AGENT_COMMAND, CURSOR_AGENT_ARGS, RAW_STREAM_LOGS_DIR } from "../config.ts";
23
- import {
24
- defaultCursorSessionMetaStore,
25
- type CursorSessionMetaStore,
26
- } from "./cursor-session-meta-store.ts";
27
- import { killProcessTree } from "./proc-tree-kill.ts";
28
- import {
29
- createRawStreamLog,
30
- type RawStreamLogHandle,
31
- } from "./raw-stream-log.ts";
32
- import { readJsonLinesWithBadJsonIdleWatchdog } from "./jsonl-stream.ts";
33
-
34
- // ---------------------------------------------------------------------------
35
- // 特殊注入提示
36
- // ---------------------------------------------------------------------------
37
-
38
- const PROJECT_ROOT = dirname(dirname(dirname(fileURLToPath(import.meta.url))));
39
- const CURSOR_SPECIFIC_PROMPT_PATH = join(
40
- PROJECT_ROOT,
41
- "agent-prompts",
42
- "cursor_specific.md",
43
- );
44
-
45
- function readCursorSpecificInjectionPrompt(): string | null {
46
- try {
47
- if (!existsSync(CURSOR_SPECIFIC_PROMPT_PATH)) return null;
48
- const prompt = readFileSync(CURSOR_SPECIFIC_PROMPT_PATH, "utf-8").trim();
49
- return prompt.length > 0 ? prompt : null;
50
- } catch {
51
- return null;
52
- }
53
- }
54
-
55
- function buildCursorPromptText(userText: string): string {
56
- const prompt = readCursorSpecificInjectionPrompt();
57
- if (!prompt) return userText;
58
-
59
- return [
60
- "[ChatCCC Cursor-specific injection prompt]",
61
- prompt,
62
- "[/ChatCCC Cursor-specific injection prompt]",
63
- "",
64
- userText,
65
- ].join("\n");
66
- }
67
-
68
- // ---------------------------------------------------------------------------
69
- // 类型:Cursor JSONL 消息行
70
- // ---------------------------------------------------------------------------
71
-
72
- interface CursorMessageLine {
73
- type?: string;
74
- subtype?: string;
75
- session_id?: string;
76
- cwd?: string;
77
- model?: string;
78
- message?: {
79
- role?: string;
80
- content?: CursorContentBlock[];
81
- };
82
- result?: string;
83
- duration_ms?: number;
84
- usage?: {
85
- inputTokens?: number;
86
- outputTokens?: number;
87
- };
88
- /**
89
- * 三类 assistant 事件的判定字段之一。详见 normalizeCursorMessage。
90
- * 官方文档:cursor.com/docs/cli/reference/output-format
91
- */
92
- timestamp_ms?: number;
93
- /**
94
- * 三类 assistant 事件的判定字段之一:
95
- * - has timestamp_ms, no model_call_id → Streaming delta(真增量)
96
- * - has timestamp_ms, has model_call_id → Buffered flush before tool call(重复快照)
97
- * - no timestamp_ms → Final flush at end of turn(重复快照)
98
- */
99
- model_call_id?: string;
100
- /** thinking delta 消息的文本内容 */
101
- text?: string;
102
- /** tool_call 消息的 call_id */
103
- call_id?: string;
104
- /** tool_call 消息的 tool_call 载荷 */
105
- tool_call?: Record<string, unknown>;
106
- }
107
-
108
- interface CursorContentBlock {
109
- type?: string;
110
- text?: string;
111
- thinking?: string;
112
- name?: string;
113
- input?: unknown;
114
- tool_use_id?: string;
115
- content?: unknown;
116
- is_error?: boolean;
117
- query?: string;
118
- [key: string]: unknown;
119
- }
120
-
121
- interface CursorProcessCloseInfo {
122
- code: number | null;
123
- signal: NodeJS.Signals | null;
124
- stderr: string;
125
- }
126
-
127
- interface CursorProcessHandle {
128
- proc: ChildProcess;
129
- getStderr(): string;
130
- waitForClose(): Promise<CursorProcessCloseInfo>;
131
- }
132
-
133
- interface CursorStreamStats {
134
- stdoutLength: number;
135
- rawLineCount: number;
136
- parsedLineCount: number;
137
- }
138
-
139
- type CursorSpawn = typeof spawn;
140
-
141
- function createCursorStreamStats(): CursorStreamStats {
142
- return { stdoutLength: 0, rawLineCount: 0, parsedLineCount: 0 };
143
- }
144
-
145
- function isCursorAuthRelatedError(stderr: string): boolean {
146
- const text = stderr.toLowerCase();
147
- return (
148
- text.includes("authentication required") ||
149
- text.includes("not logged in") ||
150
- text.includes("login") ||
151
- text.includes("sign in") ||
152
- text.includes("unauthorized") ||
153
- text.includes("401") ||
154
- text.includes("cursor_api_key") ||
155
- text.includes("api key")
156
- );
157
- }
158
-
159
- const CURSOR_VISIBLE_STDERR_MAX_CHARS = 1200;
160
-
161
- function sanitizeCursorStderr(stderr: string): string {
162
- return stderr
163
- .replace(/\x1B\[[0-?]*[ -/]*[@-~]/g, "")
164
- .replace(/\bBearer\s+[A-Za-z0-9._~+/=-]{12,}\b/gi, "Bearer <redacted>")
165
- .replace(/\bsk-[A-Za-z0-9_-]{12,}\b/g, "<redacted-api-key>")
166
- .replace(
167
- /\b(api[_-]?key|token|authorization|password)\s*[:=]\s*["']?[^\s"']+/gi,
168
- "$1=<redacted>",
169
- )
170
- .trim();
171
- }
172
-
173
- function formatCursorVisibleStderr(stderr: string): string {
174
- const sanitized = sanitizeCursorStderr(stderr);
175
- if (sanitized.length <= CURSOR_VISIBLE_STDERR_MAX_CHARS) return sanitized;
176
- return `${sanitized.slice(0, CURSOR_VISIBLE_STDERR_MAX_CHARS)}\n...(stderr truncated)`;
177
- }
178
-
179
- export function formatCursorAgentEmptyOutputMessage(args: {
180
- exitCode: number | null;
181
- stdoutLength: number;
182
- stderr: string;
183
- }): string | null {
184
- if (args.exitCode === 0) return null;
185
- if (args.stdoutLength !== 0) return null;
186
- if (args.stderr.trim().length === 0) return null;
187
-
188
- const stderrBlock = `[Cursor stderr] exit=${args.exitCode ?? "unknown"}:\n${formatCursorVisibleStderr(args.stderr)}`;
189
- if (isCursorAuthRelatedError(args.stderr)) {
190
- return `Cursor Agent 没有返回内容。检测到认证相关错误,可能需要重新登录 Cursor Agent,或配置 CURSOR_API_KEY。请在本机运行 agent status 检查状态;如未登录,请运行 agent login 后重试。\n\n${stderrBlock}`;
191
- }
192
-
193
- return `Cursor Agent 没有返回内容。底层命令异常退出,错误信息如下:\n\n${stderrBlock}`;
194
- }
195
-
196
- function createCursorAgentFailureError(info: CursorProcessCloseInfo): Error {
197
- const stderr = info.stderr.trim().slice(0, 500);
198
- return new Error(
199
- `Cursor Agent exited without stream-json output (exit=${info.code ?? "unknown"}, stderr=${stderr})`,
200
- );
201
- }
202
-
203
- // ---------------------------------------------------------------------------
204
- // normalizeCursorMessage — Cursor 消息 → UnifiedStreamMessage | null
205
- // ---------------------------------------------------------------------------
206
-
207
- /** Cursor tool_call 内部 key → 统一工具名 */
208
- function mapToolCallKey(key: string): string {
209
- const KEY_MAP: Record<string, string> = {
210
- globToolCall: "Glob",
211
- shellToolCall: "Bash",
212
- readToolCall: "Read",
213
- writeToolCall: "Write",
214
- editToolCall: "Edit",
215
- grepToolCall: "Grep",
216
- webSearchToolCall: "WebSearch",
217
- webFetchToolCall: "WebFetch",
218
- taskToolCall: "Agent",
219
- notebookEditToolCall: "NotebookEdit",
220
- };
221
- return KEY_MAP[key] ?? key;
222
- }
223
-
224
- export function normalizeCursorMessage(
225
- msg: CursorMessageLine,
226
- ): UnifiedStreamMessage | null {
227
- if (msg.type === "assistant" && msg.message?.content) {
228
- // 按 cursor 官方 stream-json 规范区分三类 assistant 事件,避免 text 重复累加:
229
- // ┌────────────────┬───────────────┬─────────────────┐
230
- // │ 种类 │ timestamp_ms │ model_call_id │
231
- // ├────────────────┼───────────────┼─────────────────┤
232
- // │ Streaming delta│ 有 │ 无 │ → 唯一带新文本(text)
233
- // │ Buffered flush │ 有 │ 有 │ → 工具调用前完整快照(text_final)
234
- // │ Final flush │ 无 │ 无 │ → 回合末完整快照(text_final)
235
- // └────────────────┴───────────────┴─────────────────┘
236
- // 文档:cursor.com/docs/cli/reference/output-format
237
- const isStreamingDelta =
238
- msg.timestamp_ms !== undefined && msg.model_call_id === undefined;
239
- const blocks: UnifiedBlock[] = [];
240
- for (const block of msg.message.content) {
241
- if (block.type === "thinking" && block.thinking) {
242
- blocks.push({ type: "thinking", thinking: block.thinking });
243
- } else if (block.type === "tool_use") {
244
- blocks.push({
245
- type: "tool_use",
246
- id: block.tool_use_id,
247
- name: block.name ?? "unknown",
248
- input: block.input,
249
- });
250
- } else if (block.type === "tool_result") {
251
- blocks.push({
252
- type: "tool_result",
253
- tool_use_id: block.tool_use_id ?? "",
254
- content: block.content,
255
- is_error: block.is_error,
256
- });
257
- } else if (block.type === "redacted_thinking") {
258
- blocks.push({ type: "redacted_thinking" });
259
- } else if (block.type === "search_result") {
260
- blocks.push({
261
- type: "search_result",
262
- query: block.query ?? "",
263
- });
264
- } else if (block.type === "text" && block.text) {
265
- blocks.push(
266
- isStreamingDelta
267
- ? { type: "text", text: block.text }
268
- : { type: "text_final", text: block.text },
269
- );
270
- }
271
- }
272
- return { type: "assistant", blocks };
273
- }
274
-
275
- // Cursor agent 发出的独立 thinking delta 消息
276
- if (msg.type === "thinking" && msg.subtype === "delta" && msg.text) {
277
- return {
278
- type: "assistant",
279
- blocks: [{ type: "thinking", thinking: msg.text }],
280
- };
281
- }
282
-
283
- // Cursor agent 发出的独立 tool_call 消息(tool_call.started / tool_call.completed)
284
- if (msg.type === "tool_call" && msg.call_id && msg.tool_call) {
285
- const toolKey = Object.keys(msg.tool_call)[0];
286
- if (!toolKey) return null;
287
- const toolData = msg.tool_call[toolKey] as {
288
- args?: Record<string, unknown>;
289
- result?: Record<string, unknown>;
290
- description?: string;
291
- } | undefined;
292
- if (!toolData) return null;
293
-
294
- if (msg.subtype === "started") {
295
- return {
296
- type: "assistant",
297
- blocks: [
298
- {
299
- type: "tool_use",
300
- name: mapToolCallKey(toolKey),
301
- input: toolData.args ?? {},
302
- },
303
- ],
304
- };
305
- }
306
-
307
- if (msg.subtype === "completed") {
308
- const resultRaw = toolData.result as Record<string, unknown> | undefined;
309
- const hasSuccess = resultRaw && "success" in resultRaw;
310
- const hasError = resultRaw && "error" in resultRaw;
311
- return {
312
- type: "assistant",
313
- blocks: [
314
- {
315
- type: "tool_result",
316
- tool_use_id: msg.call_id,
317
- content: hasSuccess
318
- ? (resultRaw!.success as Record<string, unknown>)?.stdout ??
319
- resultRaw!.success
320
- : hasError
321
- ? resultRaw!.error
322
- : resultRaw ?? {},
323
- is_error: hasError || undefined,
324
- },
325
- ],
326
- };
327
- }
328
-
329
- return null;
330
- }
331
-
332
- if (msg.type === "user" && msg.message?.content) {
333
- // Cursor resume 模式会先 echo 一条用户输入消息(text 块就是用户原始输入),
334
- // 不应混入 assistant 输出累加。这里只保留 tool_result(工具调用反馈)。
335
- const blocks: UnifiedBlock[] = [];
336
- for (const block of msg.message.content) {
337
- if (block.type === "tool_result") {
338
- blocks.push({
339
- type: "tool_result",
340
- tool_use_id: block.tool_use_id ?? "",
341
- content: block.content,
342
- is_error: block.is_error,
343
- });
344
- }
345
- }
346
- return { type: "user", blocks };
347
- }
348
-
349
- // result 消息:cursor 官方推荐的"权威最终文本"来源(流末发出,含完整一段文字)。
350
- // 提取为 assistant 的 text_final 块,由 session.ts 累积到 finalCompleteText。
351
- if (msg.type === "result" && typeof msg.result === "string" && msg.result.length > 0) {
352
- return {
353
- type: "assistant",
354
- blocks: [{ type: "text_final", text: msg.result }],
355
- };
356
- }
357
-
358
- if (msg.type === "system" && msg.subtype === "compact_boundary") {
359
- const meta = (msg as Record<string, unknown>).compact_metadata as
360
- | { trigger?: "manual" | "auto"; pre_tokens?: number; post_tokens?: number }
361
- | undefined;
362
- if (!meta) return null;
363
- return {
364
- type: "system",
365
- blocks: [
366
- {
367
- type: "compact_boundary",
368
- trigger: meta.trigger ?? "auto",
369
- pre_tokens: meta.pre_tokens ?? 0,
370
- post_tokens: meta.post_tokens,
371
- },
372
- ],
373
- };
374
- }
375
-
376
- return null;
377
- }
378
-
379
- // ---------------------------------------------------------------------------
380
- // 子进程辅助函数
381
- // ---------------------------------------------------------------------------
382
-
383
- function spawnAgent(
384
- extraArgs: string[],
385
- cwd?: string,
386
- stdinText?: string,
387
- modelOverride?: string,
388
- mode?: "plan" | "ask",
389
- spawnImpl: CursorSpawn = spawn,
390
- ): CursorProcessHandle {
391
- let allArgs: string[];
392
- if (mode) {
393
- // plan/ask 模式:移除 --force/--yolo,添加 --mode plan/ask
394
- allArgs = CURSOR_AGENT_ARGS.filter(a => a !== "--force" && a !== "--yolo");
395
- allArgs.push("--mode", mode);
396
- allArgs.push(...extraArgs);
397
- } else {
398
- allArgs = [...CURSOR_AGENT_ARGS, ...extraArgs];
399
- }
400
- if (modelOverride) {
401
- // 替换全局 --model 为 per-session override
402
- const modelIdx = allArgs.findIndex((a, i) => a === "--model" && i + 1 < allArgs.length);
403
- if (modelIdx >= 0) {
404
- allArgs[modelIdx + 1] = modelOverride;
405
- } else {
406
- allArgs.push("--model", modelOverride);
407
- }
408
- }
409
- const proc = spawnImpl(CURSOR_AGENT_COMMAND, allArgs, {
410
- cwd,
411
- stdio: [stdinText !== undefined ? "pipe" : "ignore", "pipe", "pipe"],
412
- windowsHide: true,
413
- shell: true,
414
- });
415
-
416
- console.log(`[Cursor debug] spawn: cmd=${CURSOR_AGENT_COMMAND}, args=[${allArgs.join(", ")}], cwd=${cwd ?? "(none)"}, stdinLen=${stdinText?.length ?? 0}, pid=${proc.pid}`);
417
-
418
- // 收集 stderr,子进程异常退出时输出到日志,方便排查静默失败
419
- let stderr = "";
420
- let closeInfo: CursorProcessCloseInfo | null = null;
421
- let resolveClose: (info: CursorProcessCloseInfo) => void = () => {};
422
- const closePromise = new Promise<CursorProcessCloseInfo>((resolve) => {
423
- resolveClose = resolve;
424
- });
425
- const settleClose = (code: number | null, signal: NodeJS.Signals | null) => {
426
- if (closeInfo) return;
427
- closeInfo = { code, signal, stderr };
428
- if (stderr.trim()) {
429
- console.error(`[Cursor stderr] exit=${code}: ${stderr.trim().slice(0, 2000)}`);
430
- }
431
- resolveClose(closeInfo);
432
- };
433
- proc.stderr!.on("data", (chunk: Buffer) => { stderr += chunk.toString(); });
434
- proc.once("error", (err) => {
435
- stderr += `${stderr ? "\n" : ""}${(err as Error).message}`;
436
- settleClose(null, null);
437
- });
438
- proc.once("close", (code, signal) => { settleClose(code, signal); });
439
-
440
- if (stdinText !== undefined) {
441
- proc.stdin!.write(stdinText);
442
- proc.stdin!.end();
443
- }
444
- return {
445
- proc,
446
- getStderr: () => stderr,
447
- waitForClose: async () => {
448
- if (closeInfo) return { ...closeInfo, stderr };
449
- const info = await closePromise;
450
- return { ...info, stderr };
451
- },
452
- };
453
- }
454
-
455
- async function* readJsonLines(
456
- proc: ChildProcess,
457
- signal?: AbortSignal,
458
- debugTag?: string,
459
- rawLog?: RawStreamLogHandle | null,
460
- stats?: CursorStreamStats,
461
- idleTimeoutMs?: number,
462
- ): AsyncGenerator<CursorMessageLine> {
463
- const tag = debugTag ?? "cursor";
464
- yield* readJsonLinesWithBadJsonIdleWatchdog<CursorMessageLine>({
465
- input: proc.stdout!,
466
- tool: "cursor",
467
- tag,
468
- signal,
469
- rawLog,
470
- idleTimeoutMs,
471
- parse: (line) => JSON.parse(line) as CursorMessageLine,
472
- onRawLine: (line) => {
473
- if (stats) {
474
- stats.rawLineCount++;
475
- stats.stdoutLength += Buffer.byteLength(line, "utf-8") + 1;
476
- }
477
- },
478
- onParsedLine: () => {
479
- if (stats) stats.parsedLineCount++;
480
- },
481
- onDone: (info) => {
482
- console.log(`[Cursor debug] ${tag} readJsonLines done: ${info.lineCount} raw lines, signalAborted=${info.signalAborted}`);
483
- },
484
- });
485
- }
486
-
487
- // ---------------------------------------------------------------------------
488
- // 适配器实现
489
- // ---------------------------------------------------------------------------
490
-
491
- class CursorAdapter implements ToolAdapter {
492
- readonly displayName = "Cursor";
493
- readonly sessionDescPrefix = "Cursor Session:";
494
- private activeProcs = new Set<ChildProcess>();
495
- private metaStore: CursorSessionMetaStore;
496
- private modelOverride: string | undefined;
497
- private spawnImpl: CursorSpawn;
498
- private badJsonIdleTimeoutMs: number | undefined;
499
-
500
- constructor(
501
- metaStore: CursorSessionMetaStore,
502
- modelOverride?: string,
503
- spawnImpl: CursorSpawn = spawn,
504
- badJsonIdleTimeoutMs?: number,
505
- ) {
506
- this.metaStore = metaStore;
507
- this.modelOverride = modelOverride;
508
- this.spawnImpl = spawnImpl;
509
- this.badJsonIdleTimeoutMs = badJsonIdleTimeoutMs;
510
- }
511
-
512
- async createSession(cwd: string): Promise<CreateSessionResult> {
513
- const handle = spawnAgent(["ok"], cwd, undefined, this.modelOverride, undefined, this.spawnImpl);
514
- const proc = handle.proc;
515
- const stats = createCursorStreamStats();
516
- this.activeProcs.add(proc);
517
-
518
- for await (const msg of readJsonLines(proc, undefined, "createSession", null, stats, this.badJsonIdleTimeoutMs)) {
519
- if (msg.type === "system" && msg.subtype === "init" && msg.session_id) {
520
- const sessionId = msg.session_id;
521
- await this.metaStore
522
- .set(sessionId, { cwd: msg.cwd ?? cwd, model: msg.model })
523
- .catch(() => {});
524
- this.activeProcs.delete(proc);
525
- await killProcessTree(proc.pid);
526
- return { sessionId };
527
- }
528
- }
529
-
530
- await killProcessTree(proc.pid);
531
- this.activeProcs.delete(proc);
532
- const closeInfo = await handle.waitForClose();
533
- const visibleMessage = formatCursorAgentEmptyOutputMessage({
534
- exitCode: closeInfo.code,
535
- stdoutLength: stats.stdoutLength,
536
- stderr: closeInfo.stderr,
537
- });
538
- if (visibleMessage) throw new Error(visibleMessage);
539
- throw new Error("No session ID in Cursor init event");
540
- }
541
-
542
- async *prompt(
543
- sessionId: string,
544
- userText: string,
545
- cwd: string,
546
- signal?: AbortSignal,
547
- options?: ToolPromptOptions,
548
- ): AsyncIterable<UnifiedStreamMessage> {
549
- console.log(`[Cursor debug] prompt start: sessionId=${sessionId}, cwd=${cwd}, userTextLen=${userText.length}`);
550
- const cmd = parseUserCommand(userText);
551
- const handle = spawnAgent(
552
- ["--resume", sessionId],
553
- cwd,
554
- buildCursorPromptText(userText),
555
- this.modelOverride,
556
- cmd.mode ?? undefined,
557
- this.spawnImpl,
558
- );
559
- const proc = handle.proc;
560
- this.activeProcs.add(proc);
561
- if (proc.pid !== undefined) options?.onProcessStart?.({ pid: proc.pid });
562
-
563
- const rawLogConfig = config.rawStreamLogs.cursor;
564
- let rawLog: RawStreamLogHandle | null = null;
565
- try {
566
- rawLog = await createRawStreamLog({
567
- enabled: rawLogConfig.enabled,
568
- rootDir: RAW_STREAM_LOGS_DIR,
569
- tool: "cursor",
570
- sessionId,
571
- label: "prompt",
572
- maxBytesPerTurn: rawLogConfig.maxBytesPerTurn,
573
- retentionDays: rawLogConfig.retentionDays,
574
- });
575
- } catch (err) {
576
- console.error(`[Cursor raw stream log] create failed: ${(err as Error).message}`);
577
- }
578
-
579
- // 见 codex-adapter.ts 同位置注释:spawn 用了 shell:true,必须杀整棵树,
580
- // 否则 abort 后真正在跑的孙进程 cursor-agent 还会继续输出 & 占用资源。
581
- const onAbort = () => { void killProcessTree(proc.pid); };
582
- signal?.addEventListener("abort", onAbort, { once: true });
583
- let sawResult = false;
584
- const stats = createCursorStreamStats();
585
-
586
- try {
587
- for await (const raw of readJsonLines(proc, signal, sessionId, rawLog, stats, this.badJsonIdleTimeoutMs)) {
588
- if (signal?.aborted) break;
589
- if (
590
- raw.type === "system" &&
591
- raw.subtype === "init" &&
592
- raw.session_id &&
593
- (raw.cwd || raw.model)
594
- ) {
595
- this.metaStore
596
- .set(raw.session_id, { cwd: raw.cwd, model: raw.model })
597
- .catch(() => {});
598
- }
599
- const normalized = normalizeCursorMessage(raw);
600
- if (normalized) yield normalized;
601
-
602
- // result 是流末事件,收到后立即结束进程,防止 CLI 僵死导致 readline 挂起。
603
- if (raw.type === "result") {
604
- sawResult = true;
605
- void killProcessTree(proc.pid);
606
- break;
607
- }
608
- }
609
- if (!signal?.aborted && !sawResult) {
610
- const closeInfo = await handle.waitForClose();
611
- const visibleMessage = formatCursorAgentEmptyOutputMessage({
612
- exitCode: closeInfo.code,
613
- stdoutLength: stats.stdoutLength,
614
- stderr: closeInfo.stderr,
615
- });
616
- if (visibleMessage) {
617
- yield {
618
- type: "assistant",
619
- blocks: [{ type: "text_final", text: visibleMessage }],
620
- };
621
- throw createCursorAgentFailureError(closeInfo);
622
- }
623
- }
624
- } finally {
625
- signal?.removeEventListener("abort", onAbort);
626
- await killProcessTree(proc.pid);
627
- await rawLog?.close({ keep: rawLogConfig.keepCompleted || signal?.aborted === true || !sawResult });
628
- this.activeProcs.delete(proc);
629
- if (proc.pid !== undefined) options?.onProcessExit?.({ pid: proc.pid });
630
- console.log(`[Cursor debug] prompt end: sessionId=${sessionId}, signalAborted=${signal?.aborted ?? false}`);
631
- }
632
- }
633
-
634
- async getSessionInfo(
635
- sessionId: string,
636
- ): Promise<SessionInfo | undefined> {
637
- const meta = await this.metaStore.get(sessionId);
638
- if (!meta) return { sessionId };
639
- return meta.model
640
- ? { sessionId, cwd: meta.cwd, model: meta.model }
641
- : { sessionId, cwd: meta.cwd };
642
- }
643
-
644
- async closeSession(_sessionId: string): Promise<void> {
645
- // 子进程由 prompt 的 finally 自动 kill
646
- }
647
- }
648
-
649
- // ---------------------------------------------------------------------------
650
- // 工厂函数
651
- // ---------------------------------------------------------------------------
652
-
653
- export interface CreateCursorAdapterOptions {
654
- /** 注入自定义 meta 持久化 store(测试用);未提供时使用全局默认实例。 */
655
- metaStore?: CursorSessionMetaStore;
656
- /** per-session 模型覆盖(/model 命令);传了就用,不传走全局 cursor.model */
657
- model?: string;
658
- /** 注入自定义 spawn 实现(测试用)。 */
659
- spawn?: CursorSpawn;
660
- /** Test-only override for the bad JSON idle watchdog threshold. */
661
- badJsonIdleTimeoutMs?: number;
662
- }
663
-
664
- export function createCursorAdapter(
665
- options: CreateCursorAdapterOptions = {},
666
- ): ToolAdapter {
667
- return new CursorAdapter(
668
- options.metaStore ?? defaultCursorSessionMetaStore,
669
- options.model,
670
- options.spawn,
671
- options.badJsonIdleTimeoutMs,
672
- );
673
- }
1
+ // =============================================================================
2
+ // cursor-adapter.ts — Cursor Agent CLI 适配器
3
+ // =============================================================================
4
+ // 通过 agent -p --output-format stream-json 与 Cursor agent 交互。
5
+ // 命令行可通过 config.json cursor.path / cursor.model 自定义。
6
+ // =============================================================================
7
+
8
+ import { spawn, type ChildProcess } from "node:child_process";
9
+ import { existsSync, readFileSync } from "node:fs";
10
+ import { dirname, join } from "node:path";
11
+ import { fileURLToPath } from "node:url";
12
+
13
+ import type {
14
+ ToolAdapter,
15
+ ToolPromptOptions,
16
+ UnifiedBlock,
17
+ UnifiedStreamMessage,
18
+ CreateSessionResult,
19
+ SessionInfo,
20
+ } from "./adapter-interface.ts";
21
+ import { parseUserCommand } from "./adapter-interface.ts";
22
+ import { config, CURSOR_AGENT_COMMAND, CURSOR_AGENT_ARGS, RAW_STREAM_LOGS_DIR } from "../config.ts";
23
+ import {
24
+ defaultCursorSessionMetaStore,
25
+ type CursorSessionMetaStore,
26
+ } from "./cursor-session-meta-store.ts";
27
+ import { killProcessTree } from "./proc-tree-kill.ts";
28
+ import {
29
+ createRawStreamLog,
30
+ type RawStreamLogHandle,
31
+ } from "./raw-stream-log.ts";
32
+ import { readJsonLinesWithBadJsonIdleWatchdog } from "./jsonl-stream.ts";
33
+
34
+ // ---------------------------------------------------------------------------
35
+ // 特殊注入提示
36
+ // ---------------------------------------------------------------------------
37
+
38
+ const PROJECT_ROOT = dirname(dirname(dirname(fileURLToPath(import.meta.url))));
39
+ const CURSOR_SPECIFIC_PROMPT_PATH = join(
40
+ PROJECT_ROOT,
41
+ "agent-prompts",
42
+ "cursor_specific.md",
43
+ );
44
+
45
+ function readCursorSpecificInjectionPrompt(): string | null {
46
+ try {
47
+ if (!existsSync(CURSOR_SPECIFIC_PROMPT_PATH)) return null;
48
+ const prompt = readFileSync(CURSOR_SPECIFIC_PROMPT_PATH, "utf-8").trim();
49
+ return prompt.length > 0 ? prompt : null;
50
+ } catch {
51
+ return null;
52
+ }
53
+ }
54
+
55
+ function buildCursorPromptText(userText: string): string {
56
+ const prompt = readCursorSpecificInjectionPrompt();
57
+ if (!prompt) return userText;
58
+
59
+ return [
60
+ "[ChatCCC Cursor-specific injection prompt]",
61
+ prompt,
62
+ "[/ChatCCC Cursor-specific injection prompt]",
63
+ "",
64
+ userText,
65
+ ].join("\n");
66
+ }
67
+
68
+ // ---------------------------------------------------------------------------
69
+ // 类型:Cursor JSONL 消息行
70
+ // ---------------------------------------------------------------------------
71
+
72
+ interface CursorMessageLine {
73
+ type?: string;
74
+ subtype?: string;
75
+ session_id?: string;
76
+ cwd?: string;
77
+ model?: string;
78
+ message?: {
79
+ role?: string;
80
+ content?: CursorContentBlock[];
81
+ };
82
+ result?: string;
83
+ duration_ms?: number;
84
+ usage?: {
85
+ inputTokens?: number;
86
+ outputTokens?: number;
87
+ };
88
+ /**
89
+ * 三类 assistant 事件的判定字段之一。详见 normalizeCursorMessage。
90
+ * 官方文档:cursor.com/docs/cli/reference/output-format
91
+ */
92
+ timestamp_ms?: number;
93
+ /**
94
+ * 三类 assistant 事件的判定字段之一:
95
+ * - has timestamp_ms, no model_call_id → Streaming delta(真增量)
96
+ * - has timestamp_ms, has model_call_id → Buffered flush before tool call(重复快照)
97
+ * - no timestamp_ms → Final flush at end of turn(重复快照)
98
+ */
99
+ model_call_id?: string;
100
+ /** thinking delta 消息的文本内容 */
101
+ text?: string;
102
+ /** tool_call 消息的 call_id */
103
+ call_id?: string;
104
+ /** tool_call 消息的 tool_call 载荷 */
105
+ tool_call?: Record<string, unknown>;
106
+ }
107
+
108
+ interface CursorContentBlock {
109
+ type?: string;
110
+ text?: string;
111
+ thinking?: string;
112
+ name?: string;
113
+ input?: unknown;
114
+ tool_use_id?: string;
115
+ content?: unknown;
116
+ is_error?: boolean;
117
+ query?: string;
118
+ [key: string]: unknown;
119
+ }
120
+
121
+ interface CursorProcessCloseInfo {
122
+ code: number | null;
123
+ signal: NodeJS.Signals | null;
124
+ stderr: string;
125
+ }
126
+
127
+ interface CursorProcessHandle {
128
+ proc: ChildProcess;
129
+ getStderr(): string;
130
+ waitForClose(): Promise<CursorProcessCloseInfo>;
131
+ }
132
+
133
+ interface CursorStreamStats {
134
+ stdoutLength: number;
135
+ rawLineCount: number;
136
+ parsedLineCount: number;
137
+ }
138
+
139
+ type CursorSpawn = typeof spawn;
140
+
141
+ function createCursorStreamStats(): CursorStreamStats {
142
+ return { stdoutLength: 0, rawLineCount: 0, parsedLineCount: 0 };
143
+ }
144
+
145
+ function isCursorAuthRelatedError(stderr: string): boolean {
146
+ const text = stderr.toLowerCase();
147
+ return (
148
+ text.includes("authentication required") ||
149
+ text.includes("not logged in") ||
150
+ text.includes("login") ||
151
+ text.includes("sign in") ||
152
+ text.includes("unauthorized") ||
153
+ text.includes("401") ||
154
+ text.includes("cursor_api_key") ||
155
+ text.includes("api key")
156
+ );
157
+ }
158
+
159
+ const CURSOR_VISIBLE_STDERR_MAX_CHARS = 1200;
160
+
161
+ function sanitizeCursorStderr(stderr: string): string {
162
+ return stderr
163
+ .replace(/\x1B\[[0-?]*[ -/]*[@-~]/g, "")
164
+ .replace(/\bBearer\s+[A-Za-z0-9._~+/=-]{12,}\b/gi, "Bearer <redacted>")
165
+ .replace(/\bsk-[A-Za-z0-9_-]{12,}\b/g, "<redacted-api-key>")
166
+ .replace(
167
+ /\b(api[_-]?key|token|authorization|password)\s*[:=]\s*["']?[^\s"']+/gi,
168
+ "$1=<redacted>",
169
+ )
170
+ .trim();
171
+ }
172
+
173
+ function formatCursorVisibleStderr(stderr: string): string {
174
+ const sanitized = sanitizeCursorStderr(stderr);
175
+ if (sanitized.length <= CURSOR_VISIBLE_STDERR_MAX_CHARS) return sanitized;
176
+ return `${sanitized.slice(0, CURSOR_VISIBLE_STDERR_MAX_CHARS)}\n...(stderr truncated)`;
177
+ }
178
+
179
+ export function formatCursorAgentEmptyOutputMessage(args: {
180
+ exitCode: number | null;
181
+ stdoutLength: number;
182
+ stderr: string;
183
+ }): string | null {
184
+ if (args.exitCode === 0) return null;
185
+ if (args.stdoutLength !== 0) return null;
186
+ if (args.stderr.trim().length === 0) return null;
187
+
188
+ const stderrBlock = `[Cursor stderr] exit=${args.exitCode ?? "unknown"}:\n${formatCursorVisibleStderr(args.stderr)}`;
189
+ if (isCursorAuthRelatedError(args.stderr)) {
190
+ return `Cursor Agent 没有返回内容。检测到认证相关错误,可能需要重新登录 Cursor Agent,或配置 CURSOR_API_KEY。请在本机运行 agent status 检查状态;如未登录,请运行 agent login 后重试。\n\n${stderrBlock}`;
191
+ }
192
+
193
+ return `Cursor Agent 没有返回内容。底层命令异常退出,错误信息如下:\n\n${stderrBlock}`;
194
+ }
195
+
196
+ function createCursorAgentFailureError(info: CursorProcessCloseInfo): Error {
197
+ const stderr = info.stderr.trim().slice(0, 500);
198
+ return new Error(
199
+ `Cursor Agent exited without stream-json output (exit=${info.code ?? "unknown"}, stderr=${stderr})`,
200
+ );
201
+ }
202
+
203
+ // ---------------------------------------------------------------------------
204
+ // normalizeCursorMessage — Cursor 消息 → UnifiedStreamMessage | null
205
+ // ---------------------------------------------------------------------------
206
+
207
+ /** Cursor tool_call 内部 key → 统一工具名 */
208
+ function mapToolCallKey(key: string): string {
209
+ const KEY_MAP: Record<string, string> = {
210
+ globToolCall: "Glob",
211
+ shellToolCall: "Bash",
212
+ readToolCall: "Read",
213
+ writeToolCall: "Write",
214
+ editToolCall: "Edit",
215
+ grepToolCall: "Grep",
216
+ webSearchToolCall: "WebSearch",
217
+ webFetchToolCall: "WebFetch",
218
+ taskToolCall: "Agent",
219
+ notebookEditToolCall: "NotebookEdit",
220
+ };
221
+ return KEY_MAP[key] ?? key;
222
+ }
223
+
224
+ export function normalizeCursorMessage(
225
+ msg: CursorMessageLine,
226
+ ): UnifiedStreamMessage | null {
227
+ if (msg.type === "assistant" && msg.message?.content) {
228
+ // 按 cursor 官方 stream-json 规范区分三类 assistant 事件,避免 text 重复累加:
229
+ // ┌────────────────┬───────────────┬─────────────────┐
230
+ // │ 种类 │ timestamp_ms │ model_call_id │
231
+ // ├────────────────┼───────────────┼─────────────────┤
232
+ // │ Streaming delta│ 有 │ 无 │ → 唯一带新文本(text)
233
+ // │ Buffered flush │ 有 │ 有 │ → 工具调用前完整快照(text_final)
234
+ // │ Final flush │ 无 │ 无 │ → 回合末完整快照(text_final)
235
+ // └────────────────┴───────────────┴─────────────────┘
236
+ // 文档:cursor.com/docs/cli/reference/output-format
237
+ const isStreamingDelta =
238
+ msg.timestamp_ms !== undefined && msg.model_call_id === undefined;
239
+ const blocks: UnifiedBlock[] = [];
240
+ for (const block of msg.message.content) {
241
+ if (block.type === "thinking" && block.thinking) {
242
+ blocks.push({ type: "thinking", thinking: block.thinking });
243
+ } else if (block.type === "tool_use") {
244
+ blocks.push({
245
+ type: "tool_use",
246
+ id: block.tool_use_id,
247
+ name: block.name ?? "unknown",
248
+ input: block.input,
249
+ });
250
+ } else if (block.type === "tool_result") {
251
+ blocks.push({
252
+ type: "tool_result",
253
+ tool_use_id: block.tool_use_id ?? "",
254
+ content: block.content,
255
+ is_error: block.is_error,
256
+ });
257
+ } else if (block.type === "redacted_thinking") {
258
+ blocks.push({ type: "redacted_thinking" });
259
+ } else if (block.type === "search_result") {
260
+ blocks.push({
261
+ type: "search_result",
262
+ query: block.query ?? "",
263
+ });
264
+ } else if (block.type === "text" && block.text) {
265
+ blocks.push(
266
+ isStreamingDelta
267
+ ? { type: "text", text: block.text }
268
+ : { type: "text_final", text: block.text },
269
+ );
270
+ }
271
+ }
272
+ return { type: "assistant", blocks };
273
+ }
274
+
275
+ // Cursor agent 发出的独立 thinking delta 消息
276
+ if (msg.type === "thinking" && msg.subtype === "delta" && msg.text) {
277
+ return {
278
+ type: "assistant",
279
+ blocks: [{ type: "thinking", thinking: msg.text }],
280
+ };
281
+ }
282
+
283
+ // Cursor agent 发出的独立 tool_call 消息(tool_call.started / tool_call.completed)
284
+ if (msg.type === "tool_call" && msg.call_id && msg.tool_call) {
285
+ const toolKey = Object.keys(msg.tool_call)[0];
286
+ if (!toolKey) return null;
287
+ const toolData = msg.tool_call[toolKey] as {
288
+ args?: Record<string, unknown>;
289
+ result?: Record<string, unknown>;
290
+ description?: string;
291
+ } | undefined;
292
+ if (!toolData) return null;
293
+
294
+ if (msg.subtype === "started") {
295
+ return {
296
+ type: "assistant",
297
+ blocks: [
298
+ {
299
+ type: "tool_use",
300
+ name: mapToolCallKey(toolKey),
301
+ input: toolData.args ?? {},
302
+ },
303
+ ],
304
+ };
305
+ }
306
+
307
+ if (msg.subtype === "completed") {
308
+ const resultRaw = toolData.result as Record<string, unknown> | undefined;
309
+ const hasSuccess = resultRaw && "success" in resultRaw;
310
+ const hasError = resultRaw && "error" in resultRaw;
311
+ return {
312
+ type: "assistant",
313
+ blocks: [
314
+ {
315
+ type: "tool_result",
316
+ tool_use_id: msg.call_id,
317
+ content: hasSuccess
318
+ ? (resultRaw!.success as Record<string, unknown>)?.stdout ??
319
+ resultRaw!.success
320
+ : hasError
321
+ ? resultRaw!.error
322
+ : resultRaw ?? {},
323
+ is_error: hasError || undefined,
324
+ },
325
+ ],
326
+ };
327
+ }
328
+
329
+ return null;
330
+ }
331
+
332
+ if (msg.type === "user" && msg.message?.content) {
333
+ // Cursor resume 模式会先 echo 一条用户输入消息(text 块就是用户原始输入),
334
+ // 不应混入 assistant 输出累加。这里只保留 tool_result(工具调用反馈)。
335
+ const blocks: UnifiedBlock[] = [];
336
+ for (const block of msg.message.content) {
337
+ if (block.type === "tool_result") {
338
+ blocks.push({
339
+ type: "tool_result",
340
+ tool_use_id: block.tool_use_id ?? "",
341
+ content: block.content,
342
+ is_error: block.is_error,
343
+ });
344
+ }
345
+ }
346
+ return { type: "user", blocks };
347
+ }
348
+
349
+ // result 消息:cursor 官方推荐的"权威最终文本"来源(流末发出,含完整一段文字)。
350
+ // 提取为 assistant 的 text_final 块,由 session.ts 累积到 finalCompleteText。
351
+ if (msg.type === "result" && typeof msg.result === "string" && msg.result.length > 0) {
352
+ return {
353
+ type: "assistant",
354
+ blocks: [{ type: "text_final", text: msg.result }],
355
+ };
356
+ }
357
+
358
+ if (msg.type === "system" && msg.subtype === "compact_boundary") {
359
+ const meta = (msg as Record<string, unknown>).compact_metadata as
360
+ | { trigger?: "manual" | "auto"; pre_tokens?: number; post_tokens?: number }
361
+ | undefined;
362
+ if (!meta) return null;
363
+ return {
364
+ type: "system",
365
+ blocks: [
366
+ {
367
+ type: "compact_boundary",
368
+ trigger: meta.trigger ?? "auto",
369
+ pre_tokens: meta.pre_tokens ?? 0,
370
+ post_tokens: meta.post_tokens,
371
+ },
372
+ ],
373
+ };
374
+ }
375
+
376
+ return null;
377
+ }
378
+
379
+ // ---------------------------------------------------------------------------
380
+ // 子进程辅助函数
381
+ // ---------------------------------------------------------------------------
382
+
383
+ function spawnAgent(
384
+ extraArgs: string[],
385
+ cwd?: string,
386
+ stdinText?: string,
387
+ modelOverride?: string,
388
+ mode?: "plan" | "ask",
389
+ spawnImpl: CursorSpawn = spawn,
390
+ ): CursorProcessHandle {
391
+ let allArgs: string[];
392
+ if (mode) {
393
+ // plan/ask 模式:移除 --force/--yolo,添加 --mode plan/ask
394
+ allArgs = CURSOR_AGENT_ARGS.filter(a => a !== "--force" && a !== "--yolo");
395
+ allArgs.push("--mode", mode);
396
+ allArgs.push(...extraArgs);
397
+ } else {
398
+ allArgs = [...CURSOR_AGENT_ARGS, ...extraArgs];
399
+ }
400
+ if (modelOverride) {
401
+ // 替换全局 --model 为 per-session override
402
+ const modelIdx = allArgs.findIndex((a, i) => a === "--model" && i + 1 < allArgs.length);
403
+ if (modelIdx >= 0) {
404
+ allArgs[modelIdx + 1] = modelOverride;
405
+ } else {
406
+ allArgs.push("--model", modelOverride);
407
+ }
408
+ }
409
+ const proc = spawnImpl(CURSOR_AGENT_COMMAND, allArgs, {
410
+ cwd,
411
+ stdio: [stdinText !== undefined ? "pipe" : "ignore", "pipe", "pipe"],
412
+ windowsHide: true,
413
+ shell: true,
414
+ });
415
+
416
+ console.log(`[Cursor debug] spawn: cmd=${CURSOR_AGENT_COMMAND}, args=[${allArgs.join(", ")}], cwd=${cwd ?? "(none)"}, stdinLen=${stdinText?.length ?? 0}, pid=${proc.pid}`);
417
+
418
+ // 收集 stderr,子进程异常退出时输出到日志,方便排查静默失败
419
+ let stderr = "";
420
+ let closeInfo: CursorProcessCloseInfo | null = null;
421
+ let resolveClose: (info: CursorProcessCloseInfo) => void = () => {};
422
+ const closePromise = new Promise<CursorProcessCloseInfo>((resolve) => {
423
+ resolveClose = resolve;
424
+ });
425
+ const settleClose = (code: number | null, signal: NodeJS.Signals | null) => {
426
+ if (closeInfo) return;
427
+ closeInfo = { code, signal, stderr };
428
+ if (stderr.trim()) {
429
+ console.error(`[Cursor stderr] exit=${code}: ${stderr.trim().slice(0, 2000)}`);
430
+ }
431
+ resolveClose(closeInfo);
432
+ };
433
+ proc.stderr!.on("data", (chunk: Buffer) => { stderr += chunk.toString(); });
434
+ proc.once("error", (err) => {
435
+ stderr += `${stderr ? "\n" : ""}${(err as Error).message}`;
436
+ settleClose(null, null);
437
+ });
438
+ proc.once("close", (code, signal) => { settleClose(code, signal); });
439
+
440
+ if (stdinText !== undefined) {
441
+ proc.stdin!.write(stdinText);
442
+ proc.stdin!.end();
443
+ }
444
+ return {
445
+ proc,
446
+ getStderr: () => stderr,
447
+ waitForClose: async () => {
448
+ if (closeInfo) return { ...closeInfo, stderr };
449
+ const info = await closePromise;
450
+ return { ...info, stderr };
451
+ },
452
+ };
453
+ }
454
+
455
+ async function* readJsonLines(
456
+ proc: ChildProcess,
457
+ signal?: AbortSignal,
458
+ debugTag?: string,
459
+ rawLog?: RawStreamLogHandle | null,
460
+ stats?: CursorStreamStats,
461
+ idleTimeoutMs?: number,
462
+ ): AsyncGenerator<CursorMessageLine> {
463
+ const tag = debugTag ?? "cursor";
464
+ yield* readJsonLinesWithBadJsonIdleWatchdog<CursorMessageLine>({
465
+ input: proc.stdout!,
466
+ tool: "cursor",
467
+ tag,
468
+ signal,
469
+ rawLog,
470
+ idleTimeoutMs,
471
+ parse: (line) => JSON.parse(line) as CursorMessageLine,
472
+ onRawLine: (line) => {
473
+ if (stats) {
474
+ stats.rawLineCount++;
475
+ stats.stdoutLength += Buffer.byteLength(line, "utf-8") + 1;
476
+ }
477
+ },
478
+ onParsedLine: () => {
479
+ if (stats) stats.parsedLineCount++;
480
+ },
481
+ onDone: (info) => {
482
+ console.log(`[Cursor debug] ${tag} readJsonLines done: ${info.lineCount} raw lines, signalAborted=${info.signalAborted}`);
483
+ },
484
+ });
485
+ }
486
+
487
+ // ---------------------------------------------------------------------------
488
+ // 适配器实现
489
+ // ---------------------------------------------------------------------------
490
+
491
+ class CursorAdapter implements ToolAdapter {
492
+ readonly displayName = "Cursor";
493
+ readonly sessionDescPrefix = "Cursor Session:";
494
+ private activeProcs = new Set<ChildProcess>();
495
+ private metaStore: CursorSessionMetaStore;
496
+ private modelOverride: string | undefined;
497
+ private spawnImpl: CursorSpawn;
498
+ private badJsonIdleTimeoutMs: number | undefined;
499
+
500
+ constructor(
501
+ metaStore: CursorSessionMetaStore,
502
+ modelOverride?: string,
503
+ spawnImpl: CursorSpawn = spawn,
504
+ badJsonIdleTimeoutMs?: number,
505
+ ) {
506
+ this.metaStore = metaStore;
507
+ this.modelOverride = modelOverride;
508
+ this.spawnImpl = spawnImpl;
509
+ this.badJsonIdleTimeoutMs = badJsonIdleTimeoutMs;
510
+ }
511
+
512
+ async createSession(cwd: string): Promise<CreateSessionResult> {
513
+ const handle = spawnAgent(["ok"], cwd, undefined, this.modelOverride, undefined, this.spawnImpl);
514
+ const proc = handle.proc;
515
+ const stats = createCursorStreamStats();
516
+ this.activeProcs.add(proc);
517
+
518
+ for await (const msg of readJsonLines(proc, undefined, "createSession", null, stats, this.badJsonIdleTimeoutMs)) {
519
+ if (msg.type === "system" && msg.subtype === "init" && msg.session_id) {
520
+ const sessionId = msg.session_id;
521
+ await this.metaStore
522
+ .set(sessionId, { cwd: msg.cwd ?? cwd, model: msg.model })
523
+ .catch(() => {});
524
+ this.activeProcs.delete(proc);
525
+ await killProcessTree(proc.pid);
526
+ return { sessionId };
527
+ }
528
+ }
529
+
530
+ await killProcessTree(proc.pid);
531
+ this.activeProcs.delete(proc);
532
+ const closeInfo = await handle.waitForClose();
533
+ const visibleMessage = formatCursorAgentEmptyOutputMessage({
534
+ exitCode: closeInfo.code,
535
+ stdoutLength: stats.stdoutLength,
536
+ stderr: closeInfo.stderr,
537
+ });
538
+ if (visibleMessage) throw new Error(visibleMessage);
539
+ throw new Error("No session ID in Cursor init event");
540
+ }
541
+
542
+ async *prompt(
543
+ sessionId: string,
544
+ userText: string,
545
+ cwd: string,
546
+ signal?: AbortSignal,
547
+ options?: ToolPromptOptions,
548
+ ): AsyncIterable<UnifiedStreamMessage> {
549
+ console.log(`[Cursor debug] prompt start: sessionId=${sessionId}, cwd=${cwd}, userTextLen=${userText.length}`);
550
+ const cmd = parseUserCommand(userText);
551
+ const handle = spawnAgent(
552
+ ["--resume", sessionId],
553
+ cwd,
554
+ buildCursorPromptText(userText),
555
+ this.modelOverride,
556
+ cmd.mode ?? undefined,
557
+ this.spawnImpl,
558
+ );
559
+ const proc = handle.proc;
560
+ this.activeProcs.add(proc);
561
+ if (proc.pid !== undefined) options?.onProcessStart?.({ pid: proc.pid });
562
+
563
+ const rawLogConfig = config.rawStreamLogs.cursor;
564
+ let rawLog: RawStreamLogHandle | null = null;
565
+ try {
566
+ rawLog = await createRawStreamLog({
567
+ enabled: rawLogConfig.enabled,
568
+ rootDir: RAW_STREAM_LOGS_DIR,
569
+ tool: "cursor",
570
+ sessionId,
571
+ label: "prompt",
572
+ maxBytesPerTurn: rawLogConfig.maxBytesPerTurn,
573
+ retentionDays: rawLogConfig.retentionDays,
574
+ });
575
+ } catch (err) {
576
+ console.error(`[Cursor raw stream log] create failed: ${(err as Error).message}`);
577
+ }
578
+
579
+ // 见 codex-adapter.ts 同位置注释:spawn 用了 shell:true,必须杀整棵树,
580
+ // 否则 abort 后真正在跑的孙进程 cursor-agent 还会继续输出 & 占用资源。
581
+ const onAbort = () => { void killProcessTree(proc.pid); };
582
+ signal?.addEventListener("abort", onAbort, { once: true });
583
+ let sawResult = false;
584
+ const stats = createCursorStreamStats();
585
+
586
+ try {
587
+ for await (const raw of readJsonLines(proc, signal, sessionId, rawLog, stats, this.badJsonIdleTimeoutMs)) {
588
+ if (signal?.aborted) break;
589
+ if (
590
+ raw.type === "system" &&
591
+ raw.subtype === "init" &&
592
+ raw.session_id &&
593
+ (raw.cwd || raw.model)
594
+ ) {
595
+ this.metaStore
596
+ .set(raw.session_id, { cwd: raw.cwd, model: raw.model })
597
+ .catch(() => {});
598
+ }
599
+ const normalized = normalizeCursorMessage(raw);
600
+ if (normalized) yield normalized;
601
+
602
+ // result 是流末事件,收到后立即结束进程,防止 CLI 僵死导致 readline 挂起。
603
+ if (raw.type === "result") {
604
+ sawResult = true;
605
+ void killProcessTree(proc.pid);
606
+ break;
607
+ }
608
+ }
609
+ if (!signal?.aborted && !sawResult) {
610
+ const closeInfo = await handle.waitForClose();
611
+ const visibleMessage = formatCursorAgentEmptyOutputMessage({
612
+ exitCode: closeInfo.code,
613
+ stdoutLength: stats.stdoutLength,
614
+ stderr: closeInfo.stderr,
615
+ });
616
+ if (visibleMessage) {
617
+ yield {
618
+ type: "assistant",
619
+ blocks: [{ type: "text_final", text: visibleMessage }],
620
+ };
621
+ throw createCursorAgentFailureError(closeInfo);
622
+ }
623
+ }
624
+ } finally {
625
+ signal?.removeEventListener("abort", onAbort);
626
+ await killProcessTree(proc.pid);
627
+ await rawLog?.close({ keep: rawLogConfig.keepCompleted || signal?.aborted === true || !sawResult });
628
+ this.activeProcs.delete(proc);
629
+ if (proc.pid !== undefined) options?.onProcessExit?.({ pid: proc.pid });
630
+ console.log(`[Cursor debug] prompt end: sessionId=${sessionId}, signalAborted=${signal?.aborted ?? false}`);
631
+ }
632
+ }
633
+
634
+ async getSessionInfo(
635
+ sessionId: string,
636
+ ): Promise<SessionInfo | undefined> {
637
+ const meta = await this.metaStore.get(sessionId);
638
+ if (!meta) return { sessionId };
639
+ return meta.model
640
+ ? { sessionId, cwd: meta.cwd, model: meta.model }
641
+ : { sessionId, cwd: meta.cwd };
642
+ }
643
+
644
+ async closeSession(_sessionId: string): Promise<void> {
645
+ // 子进程由 prompt 的 finally 自动 kill
646
+ }
647
+ }
648
+
649
+ // ---------------------------------------------------------------------------
650
+ // 工厂函数
651
+ // ---------------------------------------------------------------------------
652
+
653
+ export interface CreateCursorAdapterOptions {
654
+ /** 注入自定义 meta 持久化 store(测试用);未提供时使用全局默认实例。 */
655
+ metaStore?: CursorSessionMetaStore;
656
+ /** per-session 模型覆盖(/model 命令);传了就用,不传走全局 cursor.model */
657
+ model?: string;
658
+ /** 注入自定义 spawn 实现(测试用)。 */
659
+ spawn?: CursorSpawn;
660
+ /** Test-only override for the bad JSON idle watchdog threshold. */
661
+ badJsonIdleTimeoutMs?: number;
662
+ }
663
+
664
+ export function createCursorAdapter(
665
+ options: CreateCursorAdapterOptions = {},
666
+ ): ToolAdapter {
667
+ return new CursorAdapter(
668
+ options.metaStore ?? defaultCursorSessionMetaStore,
669
+ options.model,
670
+ options.spawn,
671
+ options.badJsonIdleTimeoutMs,
672
+ );
673
+ }