chatccc 0.2.252 → 0.2.253

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 (280) hide show
  1. package/README.md +1 -1
  2. package/bin/cccagent.mjs +12 -3
  3. package/bin/chatccc.mjs +15 -6
  4. package/deepccc-agent/os-prompts/darwin.md +8 -8
  5. package/deepccc-agent/os-prompts/linux.md +8 -8
  6. package/deepccc-agent/os-prompts/win32.md +11 -11
  7. package/deepccc-agent/package.json +65 -65
  8. package/dist/deepccc-agent/src/cli.js +634 -0
  9. package/dist/deepccc-agent/src/config.js +76 -0
  10. package/dist/deepccc-agent/src/context.js +348 -0
  11. package/dist/deepccc-agent/src/file-log.js +34 -0
  12. package/dist/deepccc-agent/src/file-tools.js +1208 -0
  13. package/dist/deepccc-agent/src/index.js +571 -0
  14. package/dist/deepccc-agent/src/permissions.js +170 -0
  15. package/dist/deepccc-agent/src/privacy.js +124 -0
  16. package/dist/deepccc-agent/src/proc-tree-kill.js +60 -0
  17. package/dist/deepccc-agent/src/progress/cards-helpers.js +70 -0
  18. package/dist/deepccc-agent/src/progress/reducer.js +102 -0
  19. package/dist/deepccc-agent/src/progress/terminal-renderer.js +264 -0
  20. package/dist/deepccc-agent/src/progress/view.js +30 -0
  21. package/dist/deepccc-agent/src/raw-stream-log.js +106 -0
  22. package/dist/deepccc-agent/src/session-search.js +276 -0
  23. package/dist/deepccc-agent/src/session-select.js +23 -0
  24. package/dist/deepccc-agent/src/sigint.js +26 -0
  25. package/dist/deepccc-agent/src/skills.js +178 -0
  26. package/dist/deepccc-agent/src/web-tools.js +246 -0
  27. package/dist/src/adapters/adapter-interface.js +19 -0
  28. package/dist/src/adapters/ccc-adapter.js +112 -0
  29. package/dist/src/adapters/claude-adapter.js +497 -0
  30. package/dist/src/adapters/claude-session-meta-store.js +92 -0
  31. package/dist/src/adapters/codex-adapter.js +279 -0
  32. package/dist/src/adapters/codex-session-meta-store.js +94 -0
  33. package/dist/src/adapters/cursor-adapter.js +491 -0
  34. package/dist/src/adapters/cursor-session-meta-store.js +116 -0
  35. package/dist/src/adapters/jsonl-stream.js +104 -0
  36. package/{src/adapters/proc-tree-kill.ts → dist/src/adapters/proc-tree-kill.js} +94 -97
  37. package/dist/src/adapters/raw-stream-log.js +106 -0
  38. package/dist/src/adapters/resource-monitor.js +113 -0
  39. package/dist/src/agent-activity.js +133 -0
  40. package/dist/src/agent-delegate-task-rpc.js +129 -0
  41. package/dist/src/agent-delegate-task.js +48 -0
  42. package/dist/src/agent-file-rpc.js +152 -0
  43. package/dist/src/agent-image-rpc.js +148 -0
  44. package/dist/src/agent-platform-routing.js +13 -0
  45. package/dist/src/agent-reload-config-rpc.js +23 -0
  46. package/dist/src/agent-rpc-body.js +87 -0
  47. package/dist/src/agent-stop-stuck.js +110 -0
  48. package/dist/src/card-action-routing.js +7 -0
  49. package/dist/src/card-plain-text.js +101 -0
  50. package/dist/src/cardkit.js +158 -0
  51. package/dist/src/cards.js +573 -0
  52. package/dist/src/chatgpt-subscription-rpc.js +18 -0
  53. package/dist/src/chatgpt-subscription.js +199 -0
  54. package/dist/src/chrome-devtools-guard.js +238 -0
  55. package/dist/src/claude-sdk-installer.js +249 -0
  56. package/dist/src/codex-reset-actions.js +143 -0
  57. package/dist/src/config-utils.js +149 -0
  58. package/dist/src/config.js +804 -0
  59. package/dist/src/cursor-usage.js +77 -0
  60. package/dist/src/exit-banner.js +28 -0
  61. package/dist/src/feishu-api.js +1404 -0
  62. package/dist/src/feishu-message-ingress.js +137 -0
  63. package/dist/src/feishu-platform.js +97 -0
  64. package/dist/src/format-message.js +252 -0
  65. package/dist/src/git-command.js +155 -0
  66. package/dist/src/im-skills.js +121 -0
  67. package/dist/src/index.js +833 -0
  68. package/dist/src/litellm-proxy.js +300 -0
  69. package/dist/src/orchestrator.js +2078 -0
  70. package/dist/src/package-root.js +26 -0
  71. package/dist/src/platform-adapter.js +7 -0
  72. package/dist/src/platform-startup.js +6 -0
  73. package/dist/src/privacy.js +100 -0
  74. package/dist/src/progress/reducer.js +102 -0
  75. package/dist/src/progress/terminal-renderer.js +264 -0
  76. package/dist/src/progress/view.js +30 -0
  77. package/dist/src/response-stall.js +14 -0
  78. package/dist/src/runtime-entry.js +13 -0
  79. package/dist/src/runtime-reload.js +19 -0
  80. package/dist/src/session-chat-binding.js +183 -0
  81. package/dist/src/session-name.js +7 -0
  82. package/dist/src/session.js +2144 -0
  83. package/dist/src/shared-prefix.js +16 -0
  84. package/dist/src/shared.js +493 -0
  85. package/dist/src/sim-agent.js +105 -0
  86. package/dist/src/sim-platform.js +142 -0
  87. package/dist/src/sim-store.js +231 -0
  88. package/dist/src/simplify.js +99 -0
  89. package/dist/src/startup-lifecycle.js +209 -0
  90. package/dist/src/stream-state.js +141 -0
  91. package/dist/src/terminal-error.js +100 -0
  92. package/dist/src/trace.js +50 -0
  93. package/dist/src/turn-cards.js +92 -0
  94. package/dist/src/update-command-guard.js +114 -0
  95. package/{src/web-ui.ts → dist/src/web-ui.js} +749 -823
  96. package/dist/src/wechat-platform.js +545 -0
  97. package/package.json +76 -74
  98. package/deepccc-agent/LICENSE +0 -201
  99. package/deepccc-agent/bin/deepccc.mjs +0 -26
  100. package/deepccc-agent/docs/cache-hit-rate-1.jpg +0 -0
  101. package/deepccc-agent/docs/cache-hit-rate-2.jpg +0 -0
  102. package/deepccc-agent/package-lock.json +0 -2027
  103. package/deepccc-agent/src/__tests__/chat-session.test.ts +0 -877
  104. package/deepccc-agent/src/__tests__/cli-json.test.ts +0 -49
  105. package/deepccc-agent/src/__tests__/config.test.ts +0 -34
  106. package/deepccc-agent/src/__tests__/context.test.ts +0 -341
  107. package/deepccc-agent/src/__tests__/file-tools.test.ts +0 -240
  108. package/deepccc-agent/src/__tests__/permissions.test.ts +0 -199
  109. package/deepccc-agent/src/__tests__/privacy.test.ts +0 -318
  110. package/deepccc-agent/src/__tests__/progress-reducer.test.ts +0 -121
  111. package/deepccc-agent/src/__tests__/session-search.test.ts +0 -262
  112. package/deepccc-agent/src/__tests__/session-select.test.ts +0 -116
  113. package/deepccc-agent/src/__tests__/sigint.test.ts +0 -56
  114. package/deepccc-agent/src/__tests__/skills.test.ts +0 -284
  115. package/deepccc-agent/src/__tests__/terminal-renderer.test.ts +0 -247
  116. package/deepccc-agent/src/__tests__/web-tools.test.ts +0 -220
  117. package/deepccc-agent/src/cli.ts +0 -682
  118. package/deepccc-agent/src/config.ts +0 -101
  119. package/deepccc-agent/src/context.ts +0 -465
  120. package/deepccc-agent/src/file-log.ts +0 -38
  121. package/deepccc-agent/src/file-tools.ts +0 -1493
  122. package/deepccc-agent/src/index.ts +0 -710
  123. package/deepccc-agent/src/permissions.ts +0 -226
  124. package/deepccc-agent/src/privacy.ts +0 -141
  125. package/deepccc-agent/src/proc-tree-kill.ts +0 -61
  126. package/deepccc-agent/src/progress/cards-helpers.ts +0 -76
  127. package/deepccc-agent/src/progress/reducer.ts +0 -113
  128. package/deepccc-agent/src/progress/terminal-renderer.ts +0 -294
  129. package/deepccc-agent/src/progress/view.ts +0 -77
  130. package/deepccc-agent/src/raw-stream-log.ts +0 -124
  131. package/deepccc-agent/src/session-search.ts +0 -370
  132. package/deepccc-agent/src/session-select.ts +0 -48
  133. package/deepccc-agent/src/sigint.ts +0 -50
  134. package/deepccc-agent/src/skills.ts +0 -205
  135. package/deepccc-agent/src/web-tools.ts +0 -313
  136. package/deepccc-agent/tsconfig.build.json +0 -13
  137. package/deepccc-agent/tsconfig.json +0 -13
  138. package/deepccc-agent/vitest.config.ts +0 -7
  139. package/src/__tests__/adapter-interface.test.ts +0 -152
  140. package/src/__tests__/agent-activity.test.ts +0 -86
  141. package/src/__tests__/agent-delegate-task-rpc.test.ts +0 -165
  142. package/src/__tests__/agent-image-rpc.test.ts +0 -34
  143. package/src/__tests__/agent-platform-routing.test.ts +0 -26
  144. package/src/__tests__/agent-reload-config-rpc.test.ts +0 -99
  145. package/src/__tests__/agent-rpc-body.test.ts +0 -42
  146. package/src/__tests__/builtin-chat-session.test.ts +0 -532
  147. package/src/__tests__/builtin-cli-json.test.ts +0 -39
  148. package/src/__tests__/builtin-config.test.ts +0 -26
  149. package/src/__tests__/builtin-context.test.ts +0 -319
  150. package/src/__tests__/builtin-file-tools.test.ts +0 -240
  151. package/src/__tests__/builtin-permissions.test.ts +0 -219
  152. package/src/__tests__/builtin-session-search.test.ts +0 -262
  153. package/src/__tests__/builtin-session-select.test.ts +0 -116
  154. package/src/__tests__/builtin-sigint.test.ts +0 -56
  155. package/src/__tests__/builtin-skills.test.ts +0 -284
  156. package/src/__tests__/builtin-web-tools.test.ts +0 -220
  157. package/src/__tests__/card-action-routing.test.ts +0 -18
  158. package/src/__tests__/card-plain-text.test.ts +0 -45
  159. package/src/__tests__/cardkit.test.ts +0 -60
  160. package/src/__tests__/cards.test.ts +0 -607
  161. package/src/__tests__/ccc-adapter.test.ts +0 -194
  162. package/src/__tests__/chatgpt-subscription-rpc.test.ts +0 -89
  163. package/src/__tests__/chatgpt-subscription.test.ts +0 -135
  164. package/src/__tests__/chrome-devtools-guard.test.ts +0 -165
  165. package/src/__tests__/claude-adapter.test.ts +0 -614
  166. package/src/__tests__/claude-raw-stream-log.test.ts +0 -96
  167. package/src/__tests__/claude-sdk-installer.test.ts +0 -285
  168. package/src/__tests__/codex-adapter.test.ts +0 -331
  169. package/src/__tests__/codex-raw-stream-log.test.ts +0 -170
  170. package/src/__tests__/codex-reset-actions.test.ts +0 -146
  171. package/src/__tests__/config-reload.test.ts +0 -284
  172. package/src/__tests__/config-sample.test.ts +0 -97
  173. package/src/__tests__/config-utils.test.ts +0 -40
  174. package/src/__tests__/config.test.ts +0 -395
  175. package/src/__tests__/crash-logging.test.ts +0 -360
  176. package/src/__tests__/cursor-adapter.test.ts +0 -890
  177. package/src/__tests__/cursor-session-meta-store.test.ts +0 -212
  178. package/src/__tests__/feishu-api.test.ts +0 -60
  179. package/src/__tests__/feishu-avatar.test.ts +0 -504
  180. package/src/__tests__/feishu-message-ingress.test.ts +0 -138
  181. package/src/__tests__/feishu-platform.test.ts +0 -75
  182. package/src/__tests__/fixtures/codex_simple_text.jsonl +0 -4
  183. package/src/__tests__/fixtures/codex_with_tool.jsonl +0 -6
  184. package/src/__tests__/fixtures/cursor_partial_only.jsonl +0 -5
  185. package/src/__tests__/fixtures/cursor_partial_with_final.jsonl +0 -13
  186. package/src/__tests__/fixtures/cursor_with_tool_call.jsonl +0 -12
  187. package/src/__tests__/format-message.test.ts +0 -316
  188. package/src/__tests__/git-command.test.ts +0 -288
  189. package/src/__tests__/im-skills.test.ts +0 -125
  190. package/src/__tests__/jsonl-stream.test.ts +0 -79
  191. package/src/__tests__/orchestrator.test.ts +0 -1268
  192. package/src/__tests__/package-files.test.ts +0 -24
  193. package/src/__tests__/platform-startup.test.ts +0 -19
  194. package/src/__tests__/privacy.test.ts +0 -198
  195. package/src/__tests__/proc-tree-kill.test.ts +0 -108
  196. package/src/__tests__/progress-reducer.test.ts +0 -121
  197. package/src/__tests__/raw-stream-log.test.ts +0 -106
  198. package/src/__tests__/response-stall.test.ts +0 -49
  199. package/src/__tests__/restart.test.ts +0 -232
  200. package/src/__tests__/session-ccc-config.test.ts +0 -66
  201. package/src/__tests__/session.test.ts +0 -3004
  202. package/src/__tests__/shared-prefix.test.ts +0 -36
  203. package/src/__tests__/sim-agent.test.ts +0 -174
  204. package/src/__tests__/sim-platform.test.ts +0 -93
  205. package/src/__tests__/sim-store.test.ts +0 -214
  206. package/src/__tests__/simplify.test.ts +0 -283
  207. package/src/__tests__/startup-lifecycle.test.ts +0 -231
  208. package/src/__tests__/stop-session.test.ts +0 -162
  209. package/src/__tests__/stream-state.test.ts +0 -164
  210. package/src/__tests__/terminal-error.test.ts +0 -54
  211. package/src/__tests__/terminal-renderer.test.ts +0 -247
  212. package/src/__tests__/update-command-guard.test.ts +0 -144
  213. package/src/__tests__/web-ui.test.ts +0 -438
  214. package/src/__tests__/wechat-platform.test.ts +0 -111
  215. package/src/adapters/adapter-interface.ts +0 -217
  216. package/src/adapters/ccc-adapter.ts +0 -150
  217. package/src/adapters/claude-adapter.ts +0 -673
  218. package/src/adapters/claude-session-meta-store.ts +0 -120
  219. package/src/adapters/codex-adapter.ts +0 -426
  220. package/src/adapters/codex-session-meta-store.ts +0 -131
  221. package/src/adapters/cursor-adapter.ts +0 -681
  222. package/src/adapters/cursor-session-meta-store.ts +0 -154
  223. package/src/adapters/jsonl-stream.ts +0 -157
  224. package/src/adapters/raw-stream-log.ts +0 -124
  225. package/src/adapters/resource-monitor.ts +0 -141
  226. package/src/agent-activity.ts +0 -175
  227. package/src/agent-delegate-task-rpc.ts +0 -153
  228. package/src/agent-delegate-task.ts +0 -91
  229. package/src/agent-file-rpc.ts +0 -172
  230. package/src/agent-image-rpc.ts +0 -168
  231. package/src/agent-platform-routing.ts +0 -28
  232. package/src/agent-reload-config-rpc.ts +0 -34
  233. package/src/agent-rpc-body.ts +0 -92
  234. package/src/agent-stop-stuck.ts +0 -129
  235. package/src/card-action-routing.ts +0 -14
  236. package/src/card-plain-text.ts +0 -108
  237. package/src/cardkit.ts +0 -179
  238. package/src/cards.ts +0 -684
  239. package/src/chatgpt-subscription-rpc.ts +0 -27
  240. package/src/chatgpt-subscription.ts +0 -299
  241. package/src/chrome-devtools-guard.ts +0 -318
  242. package/src/claude-sdk-installer.ts +0 -324
  243. package/src/codex-reset-actions.ts +0 -184
  244. package/src/config-utils.ts +0 -211
  245. package/src/config.ts +0 -1063
  246. package/src/cursor-usage.ts +0 -128
  247. package/src/exit-banner.ts +0 -33
  248. package/src/feishu-api.ts +0 -1616
  249. package/src/feishu-message-ingress.ts +0 -195
  250. package/src/feishu-platform.ts +0 -159
  251. package/src/format-message.ts +0 -293
  252. package/src/git-command.ts +0 -202
  253. package/src/im-skills.ts +0 -149
  254. package/src/index.ts +0 -1089
  255. package/src/litellm-proxy.ts +0 -374
  256. package/src/orchestrator.ts +0 -2543
  257. package/src/platform-adapter.ts +0 -70
  258. package/src/platform-startup.ts +0 -16
  259. package/src/privacy.ts +0 -118
  260. package/src/progress/reducer.ts +0 -113
  261. package/src/progress/terminal-renderer.ts +0 -294
  262. package/src/progress/view.ts +0 -77
  263. package/src/response-stall.ts +0 -28
  264. package/src/runtime-reload.ts +0 -34
  265. package/src/session-chat-binding.ts +0 -292
  266. package/src/session-name.ts +0 -8
  267. package/src/session.ts +0 -2659
  268. package/src/shared-prefix.ts +0 -29
  269. package/src/shared.ts +0 -552
  270. package/src/sim-agent.ts +0 -167
  271. package/src/sim-platform.ts +0 -177
  272. package/src/sim-store.ts +0 -317
  273. package/src/simplify.ts +0 -120
  274. package/src/startup-lifecycle.ts +0 -250
  275. package/src/stream-state.ts +0 -177
  276. package/src/terminal-error.ts +0 -129
  277. package/src/trace.ts +0 -51
  278. package/src/turn-cards.ts +0 -118
  279. package/src/update-command-guard.ts +0 -165
  280. package/src/wechat-platform.ts +0 -680
@@ -0,0 +1,491 @@
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
+ import { spawn } from "node:child_process";
8
+ import { existsSync, readFileSync } from "node:fs";
9
+ import { join } from "node:path";
10
+ import { parseUserCommand } from "./adapter-interface.js";
11
+ import { config, CURSOR_AGENT_COMMAND, CURSOR_AGENT_ARGS, PROJECT_ROOT, RAW_STREAM_LOGS_DIR } from "../config.js";
12
+ import { defaultCursorSessionMetaStore, } from "./cursor-session-meta-store.js";
13
+ import { killProcessTree } from "./proc-tree-kill.js";
14
+ import { createRawStreamLog, } from "./raw-stream-log.js";
15
+ import { readJsonLinesWithBadJsonIdleWatchdog } from "./jsonl-stream.js";
16
+ // ---------------------------------------------------------------------------
17
+ // 特殊注入提示
18
+ // ---------------------------------------------------------------------------
19
+ const CURSOR_SPECIFIC_PROMPT_PATH = join(PROJECT_ROOT, "agent-prompts", "cursor_specific.md");
20
+ function readCursorSpecificInjectionPrompt() {
21
+ try {
22
+ if (!existsSync(CURSOR_SPECIFIC_PROMPT_PATH))
23
+ return null;
24
+ const prompt = readFileSync(CURSOR_SPECIFIC_PROMPT_PATH, "utf-8").trim();
25
+ return prompt.length > 0 ? prompt : null;
26
+ }
27
+ catch {
28
+ return null;
29
+ }
30
+ }
31
+ function buildCursorPromptText(userText) {
32
+ const prompt = readCursorSpecificInjectionPrompt();
33
+ if (!prompt)
34
+ return userText;
35
+ return [
36
+ "[ChatCCC Cursor-specific injection prompt]",
37
+ prompt,
38
+ "[/ChatCCC Cursor-specific injection prompt]",
39
+ "",
40
+ userText,
41
+ ].join("\n");
42
+ }
43
+ function createCursorStreamStats() {
44
+ return { stdoutLength: 0, rawLineCount: 0, parsedLineCount: 0 };
45
+ }
46
+ function isCursorAuthRelatedError(stderr) {
47
+ const text = stderr.toLowerCase();
48
+ return (text.includes("authentication required") ||
49
+ text.includes("not logged in") ||
50
+ text.includes("login") ||
51
+ text.includes("sign in") ||
52
+ text.includes("unauthorized") ||
53
+ text.includes("401") ||
54
+ text.includes("cursor_api_key") ||
55
+ text.includes("api key"));
56
+ }
57
+ const CURSOR_VISIBLE_STDERR_MAX_CHARS = 1200;
58
+ function sanitizeCursorStderr(stderr) {
59
+ return stderr
60
+ .replace(/\x1B\[[0-?]*[ -/]*[@-~]/g, "")
61
+ .replace(/\bBearer\s+[A-Za-z0-9._~+/=-]{12,}\b/gi, "Bearer <redacted>")
62
+ .replace(/\bsk-[A-Za-z0-9_-]{12,}\b/g, "<redacted-api-key>")
63
+ .replace(/\b(api[_-]?key|token|authorization|password)\s*[:=]\s*["']?[^\s"']+/gi, "$1=<redacted>")
64
+ .trim();
65
+ }
66
+ function formatCursorVisibleStderr(stderr) {
67
+ const sanitized = sanitizeCursorStderr(stderr);
68
+ if (sanitized.length <= CURSOR_VISIBLE_STDERR_MAX_CHARS)
69
+ return sanitized;
70
+ return `${sanitized.slice(0, CURSOR_VISIBLE_STDERR_MAX_CHARS)}\n...(stderr truncated)`;
71
+ }
72
+ export function formatCursorAgentEmptyOutputMessage(args) {
73
+ if (args.exitCode === 0)
74
+ return null;
75
+ if (args.stdoutLength !== 0)
76
+ return null;
77
+ if (args.stderr.trim().length === 0)
78
+ return null;
79
+ const stderrBlock = `[Cursor stderr] exit=${args.exitCode ?? "unknown"}:\n${formatCursorVisibleStderr(args.stderr)}`;
80
+ if (isCursorAuthRelatedError(args.stderr)) {
81
+ return `Cursor Agent 没有返回内容。检测到认证相关错误,可能需要重新登录 Cursor Agent,或配置 CURSOR_API_KEY。请在本机运行 agent status 检查状态;如未登录,请运行 agent login 后重试。\n\n${stderrBlock}`;
82
+ }
83
+ return `Cursor Agent 没有返回内容。底层命令异常退出,错误信息如下:\n\n${stderrBlock}`;
84
+ }
85
+ function createCursorAgentFailureError(info) {
86
+ const stderr = info.stderr.trim().slice(0, 500);
87
+ return new Error(`Cursor Agent exited without stream-json output (exit=${info.code ?? "unknown"}, stderr=${stderr})`);
88
+ }
89
+ // ---------------------------------------------------------------------------
90
+ // normalizeCursorMessage — Cursor 消息 → UnifiedStreamMessage | null
91
+ // ---------------------------------------------------------------------------
92
+ /** Cursor tool_call 内部 key → 统一工具名 */
93
+ function mapToolCallKey(key) {
94
+ const KEY_MAP = {
95
+ globToolCall: "Glob",
96
+ shellToolCall: "Bash",
97
+ readToolCall: "Read",
98
+ writeToolCall: "Write",
99
+ editToolCall: "Edit",
100
+ grepToolCall: "Grep",
101
+ webSearchToolCall: "WebSearch",
102
+ webFetchToolCall: "WebFetch",
103
+ taskToolCall: "Agent",
104
+ notebookEditToolCall: "NotebookEdit",
105
+ };
106
+ return KEY_MAP[key] ?? key;
107
+ }
108
+ export function normalizeCursorMessage(msg) {
109
+ if (msg.type === "assistant" && msg.message?.content) {
110
+ // 按 cursor 官方 stream-json 规范区分三类 assistant 事件,避免 text 重复累加:
111
+ // ┌────────────────┬───────────────┬─────────────────┐
112
+ // │ 种类 │ timestamp_ms │ model_call_id │
113
+ // ├────────────────┼───────────────┼─────────────────┤
114
+ // │ Streaming delta│ 有 │ 无 │ → 唯一带新文本(text)
115
+ // │ Buffered flush │ 有 │ 有 │ → 工具调用前完整快照(text_final)
116
+ // │ Final flush │ 无 │ 无 │ → 回合末完整快照(text_final)
117
+ // └────────────────┴───────────────┴─────────────────┘
118
+ // 文档:cursor.com/docs/cli/reference/output-format
119
+ const isStreamingDelta = msg.timestamp_ms !== undefined && msg.model_call_id === undefined;
120
+ const blocks = [];
121
+ for (const block of msg.message.content) {
122
+ if (block.type === "thinking" && block.thinking) {
123
+ blocks.push({ type: "thinking", thinking: block.thinking });
124
+ }
125
+ else if (block.type === "tool_use") {
126
+ blocks.push({
127
+ type: "tool_use",
128
+ id: block.tool_use_id,
129
+ name: block.name ?? "unknown",
130
+ input: block.input,
131
+ });
132
+ }
133
+ else if (block.type === "tool_result") {
134
+ blocks.push({
135
+ type: "tool_result",
136
+ tool_use_id: block.tool_use_id ?? "",
137
+ content: block.content,
138
+ is_error: block.is_error,
139
+ });
140
+ }
141
+ else if (block.type === "redacted_thinking") {
142
+ blocks.push({ type: "redacted_thinking" });
143
+ }
144
+ else if (block.type === "search_result") {
145
+ blocks.push({
146
+ type: "search_result",
147
+ query: block.query ?? "",
148
+ });
149
+ }
150
+ else if (block.type === "text" && block.text) {
151
+ blocks.push(isStreamingDelta
152
+ ? { type: "text", text: block.text }
153
+ : { type: "text_final", text: block.text });
154
+ }
155
+ }
156
+ return { type: "assistant", blocks };
157
+ }
158
+ // Cursor agent 发出的独立 thinking delta 消息
159
+ if (msg.type === "thinking" && msg.subtype === "delta" && msg.text) {
160
+ return {
161
+ type: "assistant",
162
+ blocks: [{ type: "thinking", thinking: msg.text }],
163
+ };
164
+ }
165
+ // Cursor agent 发出的独立 tool_call 消息(tool_call.started / tool_call.completed)
166
+ if (msg.type === "tool_call" && msg.call_id && msg.tool_call) {
167
+ const toolKey = Object.keys(msg.tool_call)[0];
168
+ if (!toolKey)
169
+ return null;
170
+ const toolData = msg.tool_call[toolKey];
171
+ if (!toolData)
172
+ return null;
173
+ if (msg.subtype === "started") {
174
+ return {
175
+ type: "assistant",
176
+ blocks: [
177
+ {
178
+ type: "tool_use",
179
+ id: msg.call_id,
180
+ name: mapToolCallKey(toolKey),
181
+ input: toolData.args ?? {},
182
+ },
183
+ ],
184
+ };
185
+ }
186
+ if (msg.subtype === "completed") {
187
+ const resultRaw = toolData.result;
188
+ const hasSuccess = resultRaw && "success" in resultRaw;
189
+ const hasError = resultRaw && "error" in resultRaw;
190
+ return {
191
+ type: "assistant",
192
+ blocks: [
193
+ {
194
+ type: "tool_result",
195
+ tool_use_id: msg.call_id,
196
+ content: hasSuccess
197
+ ? resultRaw.success?.stdout ??
198
+ resultRaw.success
199
+ : hasError
200
+ ? resultRaw.error
201
+ : resultRaw ?? {},
202
+ is_error: hasError || undefined,
203
+ },
204
+ ],
205
+ };
206
+ }
207
+ return null;
208
+ }
209
+ if (msg.type === "user" && msg.message?.content) {
210
+ // Cursor resume 模式会先 echo 一条用户输入消息(text 块就是用户原始输入),
211
+ // 不应混入 assistant 输出累加。这里只保留 tool_result(工具调用反馈)。
212
+ const blocks = [];
213
+ for (const block of msg.message.content) {
214
+ if (block.type === "tool_result") {
215
+ blocks.push({
216
+ type: "tool_result",
217
+ tool_use_id: block.tool_use_id ?? "",
218
+ content: block.content,
219
+ is_error: block.is_error,
220
+ });
221
+ }
222
+ }
223
+ return { type: "user", blocks };
224
+ }
225
+ // result 消息:cursor 官方推荐的"权威最终文本"来源(流末发出,含完整一段文字)。
226
+ // 提取为 assistant 的 text_final 块,由 session.ts 累积到 finalCompleteText。
227
+ if (msg.type === "result" && typeof msg.result === "string" && msg.result.length > 0) {
228
+ return {
229
+ type: "assistant",
230
+ blocks: [{ type: "text_final", text: msg.result }],
231
+ isFinalResponse: true,
232
+ };
233
+ }
234
+ if (msg.type === "system" && msg.subtype === "compact_boundary") {
235
+ const meta = msg.compact_metadata;
236
+ if (!meta)
237
+ return null;
238
+ return {
239
+ type: "system",
240
+ blocks: [
241
+ {
242
+ type: "compact_boundary",
243
+ trigger: meta.trigger ?? "auto",
244
+ pre_tokens: meta.pre_tokens ?? 0,
245
+ post_tokens: meta.post_tokens,
246
+ },
247
+ ],
248
+ };
249
+ }
250
+ return null;
251
+ }
252
+ // ---------------------------------------------------------------------------
253
+ // 子进程辅助函数
254
+ // ---------------------------------------------------------------------------
255
+ function spawnAgent(extraArgs, cwd, stdinText, modelOverride, mode, spawnImpl = spawn) {
256
+ let allArgs;
257
+ if (mode) {
258
+ // plan/ask 模式:移除 --force/--yolo,添加 --mode plan/ask
259
+ allArgs = CURSOR_AGENT_ARGS.filter(a => a !== "--force" && a !== "--yolo");
260
+ allArgs.push("--mode", mode);
261
+ allArgs.push(...extraArgs);
262
+ }
263
+ else {
264
+ allArgs = [...CURSOR_AGENT_ARGS, ...extraArgs];
265
+ }
266
+ if (modelOverride) {
267
+ // 替换全局 --model 为 per-session override
268
+ const modelIdx = allArgs.findIndex((a, i) => a === "--model" && i + 1 < allArgs.length);
269
+ if (modelIdx >= 0) {
270
+ allArgs[modelIdx + 1] = modelOverride;
271
+ }
272
+ else {
273
+ allArgs.push("--model", modelOverride);
274
+ }
275
+ }
276
+ const proc = spawnImpl(CURSOR_AGENT_COMMAND, allArgs, {
277
+ cwd,
278
+ stdio: [stdinText !== undefined ? "pipe" : "ignore", "pipe", "pipe"],
279
+ windowsHide: true,
280
+ shell: true,
281
+ });
282
+ console.log(`[Cursor debug] spawn: cmd=${CURSOR_AGENT_COMMAND}, args=[${allArgs.join(", ")}], cwd=${cwd ?? "(none)"}, stdinLen=${stdinText?.length ?? 0}, pid=${proc.pid}`);
283
+ // 收集 stderr,子进程异常退出时输出到日志,方便排查静默失败
284
+ let stderr = "";
285
+ let closeInfo = null;
286
+ let resolveClose = () => { };
287
+ const closePromise = new Promise((resolve) => {
288
+ resolveClose = resolve;
289
+ });
290
+ const settleClose = (code, signal) => {
291
+ if (closeInfo)
292
+ return;
293
+ closeInfo = { code, signal, stderr };
294
+ if (stderr.trim()) {
295
+ console.error(`[Cursor stderr] exit=${code}: ${stderr.trim().slice(0, 2000)}`);
296
+ }
297
+ resolveClose(closeInfo);
298
+ };
299
+ proc.stderr.on("data", (chunk) => { stderr += chunk.toString(); });
300
+ proc.once("error", (err) => {
301
+ stderr += `${stderr ? "\n" : ""}${err.message}`;
302
+ settleClose(null, null);
303
+ });
304
+ proc.once("close", (code, signal) => { settleClose(code, signal); });
305
+ if (stdinText !== undefined) {
306
+ proc.stdin.write(stdinText);
307
+ proc.stdin.end();
308
+ }
309
+ return {
310
+ proc,
311
+ getStderr: () => stderr,
312
+ waitForClose: async () => {
313
+ if (closeInfo)
314
+ return { ...closeInfo, stderr };
315
+ const info = await closePromise;
316
+ return { ...info, stderr };
317
+ },
318
+ };
319
+ }
320
+ async function* readJsonLines(proc, signal, debugTag, rawLog, stats, idleTimeoutMs) {
321
+ const tag = debugTag ?? "cursor";
322
+ yield* readJsonLinesWithBadJsonIdleWatchdog({
323
+ input: proc.stdout,
324
+ tool: "cursor",
325
+ tag,
326
+ signal,
327
+ rawLog,
328
+ idleTimeoutMs,
329
+ parse: (line) => JSON.parse(line),
330
+ onRawLine: (line) => {
331
+ if (stats) {
332
+ stats.rawLineCount++;
333
+ stats.stdoutLength += Buffer.byteLength(line, "utf-8") + 1;
334
+ }
335
+ },
336
+ onParsedLine: () => {
337
+ if (stats)
338
+ stats.parsedLineCount++;
339
+ },
340
+ onDone: (info) => {
341
+ console.log(`[Cursor debug] ${tag} readJsonLines done: ${info.lineCount} raw lines, signalAborted=${info.signalAborted}`);
342
+ },
343
+ });
344
+ }
345
+ // ---------------------------------------------------------------------------
346
+ // 适配器实现
347
+ // ---------------------------------------------------------------------------
348
+ class CursorAdapter {
349
+ displayName = "Cursor";
350
+ sessionDescPrefix = "Cursor Session:";
351
+ activeProcs = new Set();
352
+ metaStore;
353
+ modelOverride;
354
+ spawnImpl;
355
+ badJsonIdleTimeoutMs;
356
+ constructor(metaStore, modelOverride, spawnImpl = spawn, badJsonIdleTimeoutMs) {
357
+ this.metaStore = metaStore;
358
+ this.modelOverride = modelOverride;
359
+ this.spawnImpl = spawnImpl;
360
+ this.badJsonIdleTimeoutMs = badJsonIdleTimeoutMs;
361
+ }
362
+ async createSession(cwd, signal) {
363
+ if (signal?.aborted)
364
+ throw new Error("Cursor session creation aborted");
365
+ const handle = spawnAgent(["ok"], cwd, undefined, this.modelOverride, undefined, this.spawnImpl);
366
+ const proc = handle.proc;
367
+ const stats = createCursorStreamStats();
368
+ this.activeProcs.add(proc);
369
+ const onAbort = () => { void killProcessTree(proc.pid); };
370
+ signal?.addEventListener("abort", onAbort, { once: true });
371
+ try {
372
+ for await (const msg of readJsonLines(proc, signal, "createSession", null, stats, this.badJsonIdleTimeoutMs)) {
373
+ if (msg.type === "system" && msg.subtype === "init" && msg.session_id) {
374
+ const sessionId = msg.session_id;
375
+ await this.metaStore
376
+ .set(sessionId, { cwd: msg.cwd ?? cwd, model: msg.model })
377
+ .catch(() => { });
378
+ return { sessionId };
379
+ }
380
+ }
381
+ if (signal?.aborted)
382
+ throw new Error("Cursor session creation aborted");
383
+ const closeInfo = await handle.waitForClose();
384
+ const visibleMessage = formatCursorAgentEmptyOutputMessage({
385
+ exitCode: closeInfo.code,
386
+ stdoutLength: stats.stdoutLength,
387
+ stderr: closeInfo.stderr,
388
+ });
389
+ if (visibleMessage)
390
+ throw new Error(visibleMessage);
391
+ throw new Error("No session ID in Cursor init event");
392
+ }
393
+ finally {
394
+ signal?.removeEventListener("abort", onAbort);
395
+ await killProcessTree(proc.pid);
396
+ this.activeProcs.delete(proc);
397
+ }
398
+ }
399
+ async *prompt(sessionId, userText, cwd, signal, options) {
400
+ console.log(`[Cursor debug] prompt start: sessionId=${sessionId}, cwd=${cwd}, userTextLen=${userText.length}`);
401
+ const cmd = parseUserCommand(userText);
402
+ const handle = spawnAgent(["--resume", sessionId], cwd, buildCursorPromptText(userText), this.modelOverride, cmd.mode ?? undefined, this.spawnImpl);
403
+ const proc = handle.proc;
404
+ this.activeProcs.add(proc);
405
+ if (proc.pid !== undefined)
406
+ options?.onProcessStart?.({ pid: proc.pid });
407
+ const rawLogConfig = config.rawStreamLogs.cursor;
408
+ let rawLog = null;
409
+ try {
410
+ rawLog = await createRawStreamLog({
411
+ enabled: rawLogConfig.enabled,
412
+ rootDir: RAW_STREAM_LOGS_DIR,
413
+ tool: "cursor",
414
+ sessionId,
415
+ label: "prompt",
416
+ maxBytesPerTurn: rawLogConfig.maxBytesPerTurn,
417
+ retentionDays: rawLogConfig.retentionDays,
418
+ });
419
+ }
420
+ catch (err) {
421
+ console.error(`[Cursor raw stream log] create failed: ${err.message}`);
422
+ }
423
+ // 见 codex-adapter.ts 同位置注释:spawn 用了 shell:true,必须杀整棵树,
424
+ // 否则 abort 后真正在跑的孙进程 cursor-agent 还会继续输出 & 占用资源。
425
+ const onAbort = () => { void killProcessTree(proc.pid); };
426
+ signal?.addEventListener("abort", onAbort, { once: true });
427
+ let sawResult = false;
428
+ const stats = createCursorStreamStats();
429
+ try {
430
+ for await (const raw of readJsonLines(proc, signal, sessionId, rawLog, stats, this.badJsonIdleTimeoutMs)) {
431
+ if (signal?.aborted)
432
+ break;
433
+ if (raw.type === "system" &&
434
+ raw.subtype === "init" &&
435
+ raw.session_id &&
436
+ (raw.cwd || raw.model)) {
437
+ this.metaStore
438
+ .set(raw.session_id, { cwd: raw.cwd, model: raw.model })
439
+ .catch(() => { });
440
+ }
441
+ const normalized = normalizeCursorMessage(raw);
442
+ if (normalized)
443
+ yield normalized;
444
+ // result 是流末事件,收到后立即结束进程,防止 CLI 僵死导致 readline 挂起。
445
+ if (raw.type === "result") {
446
+ sawResult = true;
447
+ void killProcessTree(proc.pid);
448
+ break;
449
+ }
450
+ }
451
+ if (!signal?.aborted && !sawResult) {
452
+ const closeInfo = await handle.waitForClose();
453
+ const visibleMessage = formatCursorAgentEmptyOutputMessage({
454
+ exitCode: closeInfo.code,
455
+ stdoutLength: stats.stdoutLength,
456
+ stderr: closeInfo.stderr,
457
+ });
458
+ if (visibleMessage) {
459
+ yield {
460
+ type: "assistant",
461
+ blocks: [{ type: "text_final", text: visibleMessage }],
462
+ };
463
+ throw createCursorAgentFailureError(closeInfo);
464
+ }
465
+ }
466
+ }
467
+ finally {
468
+ signal?.removeEventListener("abort", onAbort);
469
+ await killProcessTree(proc.pid);
470
+ await rawLog?.close({ keep: rawLogConfig.keepCompleted || signal?.aborted === true || !sawResult });
471
+ this.activeProcs.delete(proc);
472
+ if (proc.pid !== undefined)
473
+ options?.onProcessExit?.({ pid: proc.pid });
474
+ console.log(`[Cursor debug] prompt end: sessionId=${sessionId}, signalAborted=${signal?.aborted ?? false}`);
475
+ }
476
+ }
477
+ async getSessionInfo(sessionId) {
478
+ const meta = await this.metaStore.get(sessionId);
479
+ if (!meta)
480
+ return { sessionId };
481
+ return meta.model
482
+ ? { sessionId, cwd: meta.cwd, model: meta.model }
483
+ : { sessionId, cwd: meta.cwd };
484
+ }
485
+ async closeSession(_sessionId) {
486
+ // 子进程由 prompt 的 finally 自动 kill
487
+ }
488
+ }
489
+ export function createCursorAdapter(options = {}) {
490
+ return new CursorAdapter(options.metaStore ?? defaultCursorSessionMetaStore, options.model, options.spawn, options.badJsonIdleTimeoutMs);
491
+ }
@@ -0,0 +1,116 @@
1
+ // =============================================================================
2
+ // cursor-session-meta-store.ts — Cursor 会话 sessionId → meta 持久化映射
3
+ // =============================================================================
4
+ // 背景:Claude Adapter 通过 SDK 的 getSessionInfo 能拿到会话的真实 cwd(SDK
5
+ // 内部已持久化)。Cursor CLI 没有等价机制,因此 ChatCCC 必须自己维护一份
6
+ // sessionId → { cwd, model } 映射,否则:
7
+ // 1. /git、/cd 等需要"会话真实工作目录"的命令将在 Cursor 会话上 100% 失败
8
+ // 2. /state、/sessions 显示的"模型"只能硬塞 ChatCCC 的 ANTHROPIC 环境变量,
9
+ // 与 Cursor 实际跑的 Composer 2 Fast 等真实模型无关
10
+ //
11
+ // 存储:
12
+ // 文件 state/cursor-session-meta.json,结构:
13
+ // { "<sessionId>": { "cwd": "...", "model": "..." } }
14
+ //
15
+ // API 设计:
16
+ // set(sid, partial) → 部分合并写入;只更新非空字段,不会清空其他字段
17
+ // 这样 createSession(拿到 cwd+model)与 prompt(resume 时再次学习)都用同一
18
+ // 接口,但若某次 init 事件少了某字段也不会破坏已记录值。
19
+ //
20
+ // 鲁棒性:文件不存在/损坏/IO 失败一律视为空映射,仅打日志,不阻断主流程。
21
+ // =============================================================================
22
+ import { mkdir, readFile, writeFile } from "node:fs/promises";
23
+ import { dirname, join } from "node:path";
24
+ import { USER_DATA_DIR } from "../config.js";
25
+ /** 持久化文件默认路径(生产)。测试可通过 createCursorSessionMetaStore(filePath) 注入。 */
26
+ export const CURSOR_SESSION_META_FILE = join(USER_DATA_DIR, "state", "cursor-session-meta.json");
27
+ function isNonEmptyString(v) {
28
+ return typeof v === "string" && v.length > 0;
29
+ }
30
+ /**
31
+ * 解析持久化文件中的单条记录,兼容历史 schema:
32
+ * - 新版:{ cwd: string, model?: string }
33
+ * - 历史 v1:纯字符串(直接是 cwd 值)—— 升级前旧数据兼容
34
+ * 非法形态返回 null。
35
+ */
36
+ function parseEntry(raw) {
37
+ if (typeof raw === "string" && raw.length > 0) {
38
+ return { cwd: raw };
39
+ }
40
+ if (raw && typeof raw === "object" && !Array.isArray(raw)) {
41
+ const obj = raw;
42
+ const out = {};
43
+ if (isNonEmptyString(obj.cwd))
44
+ out.cwd = obj.cwd;
45
+ if (isNonEmptyString(obj.model))
46
+ out.model = obj.model;
47
+ return out;
48
+ }
49
+ return null;
50
+ }
51
+ /**
52
+ * 创建一个基于 JSON 文件的 store 实例。
53
+ *
54
+ * - 首次访问时懒加载文件到内存缓存;后续读全部走缓存
55
+ * - 写时先合并到缓存再落盘(写失败仅 console.error,不抛异常)
56
+ * - 同一 sessionId 重复 set 完全相同值时跳过 IO
57
+ */
58
+ export function createCursorSessionMetaStore(filePath = CURSOR_SESSION_META_FILE) {
59
+ let cache = null;
60
+ async function load() {
61
+ if (cache)
62
+ return cache;
63
+ try {
64
+ const raw = await readFile(filePath, "utf-8");
65
+ const parsed = JSON.parse(raw);
66
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
67
+ const out = {};
68
+ for (const [k, v] of Object.entries(parsed)) {
69
+ const entry = parseEntry(v);
70
+ if (entry)
71
+ out[k] = entry;
72
+ }
73
+ cache = out;
74
+ return out;
75
+ }
76
+ }
77
+ catch {
78
+ // 文件不存在 / JSON 损坏 / 读权限失败 → 视为空映射,不阻断主流程
79
+ }
80
+ cache = {};
81
+ return cache;
82
+ }
83
+ return {
84
+ async get(sessionId) {
85
+ const map = await load();
86
+ const entry = map[sessionId];
87
+ if (!entry || !isNonEmptyString(entry.cwd))
88
+ return undefined;
89
+ return entry.model
90
+ ? { cwd: entry.cwd, model: entry.model }
91
+ : { cwd: entry.cwd };
92
+ },
93
+ async set(sessionId, partial) {
94
+ const map = await load();
95
+ const existing = map[sessionId] ?? {};
96
+ const merged = { ...existing };
97
+ if (isNonEmptyString(partial.cwd))
98
+ merged.cwd = partial.cwd;
99
+ if (isNonEmptyString(partial.model))
100
+ merged.model = partial.model;
101
+ // 与原值完全相同时跳过 IO
102
+ if (existing.cwd === merged.cwd && existing.model === merged.model)
103
+ return;
104
+ map[sessionId] = merged;
105
+ try {
106
+ await mkdir(dirname(filePath), { recursive: true });
107
+ await writeFile(filePath, JSON.stringify(map, null, 2), "utf-8");
108
+ }
109
+ catch (err) {
110
+ console.error(`[cursor-session-meta] failed to persist ${filePath}: ${err.message}`);
111
+ }
112
+ },
113
+ };
114
+ }
115
+ /** 生产环境共享的全局默认实例(指向 state/cursor-session-meta.json)。 */
116
+ export const defaultCursorSessionMetaStore = createCursorSessionMetaStore();