chatccc 0.2.6 → 0.2.8

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.
@@ -1,229 +1,402 @@
1
- // =============================================================================
2
- // cursor-adapter.ts — Cursor Agent CLI 适配器
3
- // =============================================================================
4
- // 通过 agent -p --output-format stream-json 与 Cursor agent 交互。
5
- // 命令行可通过 CHATCCC_CURSOR_COMMAND / CHATCCC_CURSOR_ARGS 环境变量自定义。
6
- // =============================================================================
7
-
8
- import { spawn, type ChildProcess } from "node:child_process";
9
- import { createInterface } from "node:readline";
10
-
11
- import type {
12
- ToolAdapter,
13
- UnifiedBlock,
14
- UnifiedStreamMessage,
15
- CreateSessionResult,
16
- SessionInfo,
17
- } from "./adapter-interface.ts";
18
- import { CURSOR_AGENT_COMMAND, CURSOR_AGENT_ARGS } from "../config.ts";
19
-
20
- // ---------------------------------------------------------------------------
21
- // 类型:Cursor JSONL 消息行
22
- // ---------------------------------------------------------------------------
23
-
24
- interface CursorMessageLine {
25
- type?: string;
26
- subtype?: string;
27
- session_id?: string;
28
- cwd?: string;
29
- model?: string;
30
- message?: {
31
- role?: string;
32
- content?: CursorContentBlock[];
33
- };
34
- result?: string;
35
- duration_ms?: number;
36
- usage?: {
37
- inputTokens?: number;
38
- outputTokens?: number;
39
- };
40
- }
41
-
42
- interface CursorContentBlock {
43
- type?: string;
44
- text?: string;
45
- thinking?: string;
46
- name?: string;
47
- input?: unknown;
48
- tool_use_id?: string;
49
- content?: unknown;
50
- is_error?: boolean;
51
- query?: string;
52
- [key: string]: unknown;
53
- }
54
-
55
- // ---------------------------------------------------------------------------
56
- // normalizeCursorMessage Cursor 消息 → UnifiedStreamMessage | null
57
- // ---------------------------------------------------------------------------
58
-
59
- export function normalizeCursorMessage(
60
- msg: CursorMessageLine,
61
- ): UnifiedStreamMessage | null {
62
- if (msg.type === "assistant" && msg.message?.content) {
63
- const blocks: UnifiedBlock[] = [];
64
- for (const block of msg.message.content) {
65
- if (block.type === "thinking" && block.thinking) {
66
- blocks.push({ type: "thinking", thinking: block.thinking });
67
- } else if (block.type === "tool_use") {
68
- blocks.push({
69
- type: "tool_use",
70
- name: block.name ?? "unknown",
71
- input: block.input,
72
- });
73
- } else if (block.type === "tool_result") {
74
- blocks.push({
75
- type: "tool_result",
76
- tool_use_id: block.tool_use_id ?? "",
77
- content: block.content,
78
- is_error: block.is_error,
79
- });
80
- } else if (block.type === "redacted_thinking") {
81
- blocks.push({ type: "redacted_thinking" });
82
- } else if (block.type === "search_result") {
83
- blocks.push({
84
- type: "search_result",
85
- query: block.query ?? "",
86
- });
87
- } else if (block.type === "text" && block.text) {
88
- blocks.push({ type: "text", text: block.text });
89
- }
90
- }
91
- return { type: "assistant", blocks };
92
- }
93
-
94
- if (msg.type === "user" && msg.message?.content) {
95
- const blocks: UnifiedBlock[] = [];
96
- for (const block of msg.message.content) {
97
- if (block.type === "tool_result") {
98
- blocks.push({
99
- type: "tool_result",
100
- tool_use_id: block.tool_use_id ?? "",
101
- content: block.content,
102
- is_error: block.is_error,
103
- });
104
- } else if (block.type === "text" && block.text) {
105
- blocks.push({ type: "text", text: block.text });
106
- }
107
- }
108
- return { type: "user", blocks };
109
- }
110
-
111
- if (msg.type === "system" && msg.subtype === "compact_boundary") {
112
- const meta = (msg as Record<string, unknown>).compact_metadata as
113
- | { trigger?: "manual" | "auto"; pre_tokens?: number; post_tokens?: number }
114
- | undefined;
115
- if (!meta) return null;
116
- return {
117
- type: "system",
118
- blocks: [
119
- {
120
- type: "compact_boundary",
121
- trigger: meta.trigger ?? "auto",
122
- pre_tokens: meta.pre_tokens ?? 0,
123
- post_tokens: meta.post_tokens,
124
- },
125
- ],
126
- };
127
- }
128
-
129
- return null;
130
- }
131
-
132
- // ---------------------------------------------------------------------------
133
- // 子进程辅助函数
134
- // ---------------------------------------------------------------------------
135
-
136
- function spawnAgent(
137
- extraArgs: string[],
138
- cwd?: string,
139
- ): ChildProcess {
140
- const allArgs = [...CURSOR_AGENT_ARGS, ...extraArgs];
141
- return spawn(CURSOR_AGENT_COMMAND, allArgs, {
142
- cwd,
143
- stdio: ["ignore", "pipe", "pipe"],
144
- windowsHide: true,
145
- shell: true,
146
- });
147
- }
148
-
149
- async function* readJsonLines(
150
- proc: ChildProcess,
151
- signal?: AbortSignal,
152
- ): AsyncGenerator<CursorMessageLine> {
153
- const rl = createInterface({ input: proc.stdout!, crlfDelay: Infinity });
154
- for await (const line of rl) {
155
- if (signal?.aborted) break;
156
- const trimmed = line.trim();
157
- if (!trimmed) continue;
158
- try {
159
- yield JSON.parse(trimmed) as CursorMessageLine;
160
- } catch { /* JSON 行静默跳过 */ }
161
- }
162
- }
163
-
164
- // ---------------------------------------------------------------------------
165
- // 适配器实现
166
- // ---------------------------------------------------------------------------
167
-
168
- class CursorAdapter implements ToolAdapter {
169
- readonly displayName = "Cursor";
170
- readonly sessionDescPrefix = "Cursor Session:";
171
- private activeProcs = new Set<ChildProcess>();
172
-
173
- async createSession(cwd: string): Promise<CreateSessionResult> {
174
- const proc = spawnAgent(["ok"], cwd);
175
- this.activeProcs.add(proc);
176
-
177
- for await (const msg of readJsonLines(proc)) {
178
- if (msg.type === "system" && msg.subtype === "init" && msg.session_id) {
179
- const sessionId = msg.session_id;
180
- this.activeProcs.delete(proc);
181
- proc.kill();
182
- return { sessionId };
183
- }
184
- }
185
-
186
- proc.kill();
187
- this.activeProcs.delete(proc);
188
- throw new Error("No session ID in Cursor init event");
189
- }
190
-
191
- async *prompt(
192
- sessionId: string,
193
- userText: string,
194
- cwd: string,
195
- signal?: AbortSignal,
196
- ): AsyncIterable<UnifiedStreamMessage> {
197
- const proc = spawnAgent(["--resume", sessionId, userText], cwd);
198
- this.activeProcs.add(proc);
199
-
200
- try {
201
- for await (const raw of readJsonLines(proc, signal)) {
202
- if (signal?.aborted) break;
203
- const normalized = normalizeCursorMessage(raw);
204
- if (normalized) yield normalized;
205
- }
206
- } finally {
207
- proc.kill();
208
- this.activeProcs.delete(proc);
209
- }
210
- }
211
-
212
- async getSessionInfo(
213
- _sessionId: string,
214
- ): Promise<SessionInfo | undefined> {
215
- return { sessionId: _sessionId };
216
- }
217
-
218
- async closeSession(_sessionId: string): Promise<void> {
219
- // 子进程由 prompt finally 自动 kill
220
- }
221
- }
222
-
223
- // ---------------------------------------------------------------------------
224
- // 工厂函数
225
- // ---------------------------------------------------------------------------
226
-
227
- export function createCursorAdapter(): ToolAdapter {
228
- return new CursorAdapter();
1
+ // =============================================================================
2
+ // cursor-adapter.ts — Cursor Agent CLI 适配器
3
+ // =============================================================================
4
+ // 通过 agent -p --output-format stream-json 与 Cursor agent 交互。
5
+ // 命令行可通过 CHATCCC_CURSOR_COMMAND / CHATCCC_CURSOR_ARGS 环境变量自定义。
6
+ // =============================================================================
7
+
8
+ import { spawn, type ChildProcess } from "node:child_process";
9
+ import { createInterface } from "node:readline";
10
+
11
+ import type {
12
+ ToolAdapter,
13
+ UnifiedBlock,
14
+ UnifiedStreamMessage,
15
+ CreateSessionResult,
16
+ SessionInfo,
17
+ } from "./adapter-interface.ts";
18
+ import { CURSOR_AGENT_COMMAND, CURSOR_AGENT_ARGS } from "../config.ts";
19
+ import {
20
+ defaultCursorSessionMetaStore,
21
+ type CursorSessionMetaStore,
22
+ } from "./cursor-session-meta-store.ts";
23
+
24
+ // ---------------------------------------------------------------------------
25
+ // 类型:Cursor JSONL 消息行
26
+ // ---------------------------------------------------------------------------
27
+
28
+ interface CursorMessageLine {
29
+ type?: string;
30
+ subtype?: string;
31
+ session_id?: string;
32
+ cwd?: string;
33
+ model?: string;
34
+ message?: {
35
+ role?: string;
36
+ content?: CursorContentBlock[];
37
+ };
38
+ result?: string;
39
+ duration_ms?: number;
40
+ usage?: {
41
+ inputTokens?: number;
42
+ outputTokens?: number;
43
+ };
44
+ /**
45
+ * 三类 assistant 事件的判定字段之一。详见 normalizeCursorMessage。
46
+ * 官方文档:cursor.com/docs/cli/reference/output-format
47
+ */
48
+ timestamp_ms?: number;
49
+ /**
50
+ * 三类 assistant 事件的判定字段之一:
51
+ * - has timestamp_ms, no model_call_id Streaming delta(真增量)
52
+ * - has timestamp_ms, has model_call_id → Buffered flush before tool call(重复快照)
53
+ * - no timestamp_ms → Final flush at end of turn(重复快照)
54
+ */
55
+ model_call_id?: string;
56
+ /** thinking delta 消息的文本内容 */
57
+ text?: string;
58
+ /** tool_call 消息的 call_id */
59
+ call_id?: string;
60
+ /** tool_call 消息的 tool_call 载荷 */
61
+ tool_call?: Record<string, unknown>;
62
+ }
63
+
64
+ interface CursorContentBlock {
65
+ type?: string;
66
+ text?: string;
67
+ thinking?: string;
68
+ name?: string;
69
+ input?: unknown;
70
+ tool_use_id?: string;
71
+ content?: unknown;
72
+ is_error?: boolean;
73
+ query?: string;
74
+ [key: string]: unknown;
75
+ }
76
+
77
+ // ---------------------------------------------------------------------------
78
+ // normalizeCursorMessage — Cursor 消息 → UnifiedStreamMessage | null
79
+ // ---------------------------------------------------------------------------
80
+
81
+ /** Cursor tool_call 内部 key → 统一工具名 */
82
+ function mapToolCallKey(key: string): string {
83
+ const KEY_MAP: Record<string, string> = {
84
+ globToolCall: "Glob",
85
+ shellToolCall: "Bash",
86
+ readToolCall: "Read",
87
+ writeToolCall: "Write",
88
+ editToolCall: "Edit",
89
+ grepToolCall: "Grep",
90
+ webSearchToolCall: "WebSearch",
91
+ webFetchToolCall: "WebFetch",
92
+ taskToolCall: "Agent",
93
+ notebookEditToolCall: "NotebookEdit",
94
+ };
95
+ return KEY_MAP[key] ?? key;
96
+ }
97
+
98
+ export function normalizeCursorMessage(
99
+ msg: CursorMessageLine,
100
+ ): UnifiedStreamMessage | null {
101
+ if (msg.type === "assistant" && msg.message?.content) {
102
+ // 按 cursor 官方 stream-json 规范区分三类 assistant 事件,避免 text 重复累加:
103
+ // ┌────────────────┬───────────────┬─────────────────┐
104
+ // │ 种类 │ timestamp_ms │ model_call_id │
105
+ // ├────────────────┼───────────────┼─────────────────┤
106
+ // │ Streaming delta│ 有 │ 无 │ → 唯一带新文本(text)
107
+ // │ Buffered flush │ 有 │ 有 │ → 工具调用前完整快照(text_final)
108
+ // │ Final flush │ 无 │ 无 │ → 回合末完整快照(text_final)
109
+ // └────────────────┴───────────────┴─────────────────┘
110
+ // 文档:cursor.com/docs/cli/reference/output-format
111
+ const isStreamingDelta =
112
+ msg.timestamp_ms !== undefined && msg.model_call_id === undefined;
113
+ const blocks: UnifiedBlock[] = [];
114
+ for (const block of msg.message.content) {
115
+ if (block.type === "thinking" && block.thinking) {
116
+ blocks.push({ type: "thinking", thinking: block.thinking });
117
+ } else if (block.type === "tool_use") {
118
+ blocks.push({
119
+ type: "tool_use",
120
+ name: block.name ?? "unknown",
121
+ input: block.input,
122
+ });
123
+ } else if (block.type === "tool_result") {
124
+ blocks.push({
125
+ type: "tool_result",
126
+ tool_use_id: block.tool_use_id ?? "",
127
+ content: block.content,
128
+ is_error: block.is_error,
129
+ });
130
+ } else if (block.type === "redacted_thinking") {
131
+ blocks.push({ type: "redacted_thinking" });
132
+ } else if (block.type === "search_result") {
133
+ blocks.push({
134
+ type: "search_result",
135
+ query: block.query ?? "",
136
+ });
137
+ } else if (block.type === "text" && block.text) {
138
+ blocks.push(
139
+ isStreamingDelta
140
+ ? { type: "text", text: block.text }
141
+ : { type: "text_final", text: block.text },
142
+ );
143
+ }
144
+ }
145
+ return { type: "assistant", blocks };
146
+ }
147
+
148
+ // Cursor agent 发出的独立 thinking delta 消息
149
+ if (msg.type === "thinking" && msg.subtype === "delta" && msg.text) {
150
+ return {
151
+ type: "assistant",
152
+ blocks: [{ type: "thinking", thinking: msg.text }],
153
+ };
154
+ }
155
+
156
+ // Cursor agent 发出的独立 tool_call 消息(tool_call.started / tool_call.completed)
157
+ if (msg.type === "tool_call" && msg.call_id && msg.tool_call) {
158
+ const toolKey = Object.keys(msg.tool_call)[0];
159
+ if (!toolKey) return null;
160
+ const toolData = msg.tool_call[toolKey] as {
161
+ args?: Record<string, unknown>;
162
+ result?: Record<string, unknown>;
163
+ description?: string;
164
+ } | undefined;
165
+ if (!toolData) return null;
166
+
167
+ if (msg.subtype === "started") {
168
+ return {
169
+ type: "assistant",
170
+ blocks: [
171
+ {
172
+ type: "tool_use",
173
+ name: mapToolCallKey(toolKey),
174
+ input: toolData.args ?? {},
175
+ },
176
+ ],
177
+ };
178
+ }
179
+
180
+ if (msg.subtype === "completed") {
181
+ const resultRaw = toolData.result as Record<string, unknown> | undefined;
182
+ const hasSuccess = resultRaw && "success" in resultRaw;
183
+ const hasError = resultRaw && "error" in resultRaw;
184
+ return {
185
+ type: "assistant",
186
+ blocks: [
187
+ {
188
+ type: "tool_result",
189
+ tool_use_id: msg.call_id,
190
+ content: hasSuccess
191
+ ? (resultRaw!.success as Record<string, unknown>)?.stdout ??
192
+ resultRaw!.success
193
+ : hasError
194
+ ? resultRaw!.error
195
+ : resultRaw ?? {},
196
+ is_error: hasError || undefined,
197
+ },
198
+ ],
199
+ };
200
+ }
201
+
202
+ return null;
203
+ }
204
+
205
+ if (msg.type === "user" && msg.message?.content) {
206
+ // Cursor resume 模式会先 echo 一条用户输入消息(text 块就是用户原始输入),
207
+ // 不应混入 assistant 输出累加。这里只保留 tool_result(工具调用反馈)。
208
+ const blocks: UnifiedBlock[] = [];
209
+ for (const block of msg.message.content) {
210
+ if (block.type === "tool_result") {
211
+ blocks.push({
212
+ type: "tool_result",
213
+ tool_use_id: block.tool_use_id ?? "",
214
+ content: block.content,
215
+ is_error: block.is_error,
216
+ });
217
+ }
218
+ }
219
+ return { type: "user", blocks };
220
+ }
221
+
222
+ // result 消息:cursor 官方推荐的"权威最终文本"来源(流末发出,含完整一段文字)。
223
+ // 提取为 assistant 的 text_final 块,由 session.ts 累积到 finalCompleteText。
224
+ if (msg.type === "result" && typeof msg.result === "string" && msg.result.length > 0) {
225
+ return {
226
+ type: "assistant",
227
+ blocks: [{ type: "text_final", text: msg.result }],
228
+ };
229
+ }
230
+
231
+ if (msg.type === "system" && msg.subtype === "compact_boundary") {
232
+ const meta = (msg as Record<string, unknown>).compact_metadata as
233
+ | { trigger?: "manual" | "auto"; pre_tokens?: number; post_tokens?: number }
234
+ | undefined;
235
+ if (!meta) return null;
236
+ return {
237
+ type: "system",
238
+ blocks: [
239
+ {
240
+ type: "compact_boundary",
241
+ trigger: meta.trigger ?? "auto",
242
+ pre_tokens: meta.pre_tokens ?? 0,
243
+ post_tokens: meta.post_tokens,
244
+ },
245
+ ],
246
+ };
247
+ }
248
+
249
+ return null;
250
+ }
251
+
252
+ // ---------------------------------------------------------------------------
253
+ // 子进程辅助函数
254
+ // ---------------------------------------------------------------------------
255
+
256
+ function spawnAgent(
257
+ extraArgs: string[],
258
+ cwd?: string,
259
+ stdinText?: string,
260
+ ): ChildProcess {
261
+ const allArgs = [...CURSOR_AGENT_ARGS, ...extraArgs];
262
+ const proc = spawn(CURSOR_AGENT_COMMAND, allArgs, {
263
+ cwd,
264
+ stdio: [stdinText !== undefined ? "pipe" : "ignore", "pipe", "pipe"],
265
+ windowsHide: true,
266
+ shell: true,
267
+ });
268
+
269
+ // 收集 stderr,子进程异常退出时输出到日志,方便排查静默失败
270
+ let stderr = "";
271
+ proc.stderr!.on("data", (chunk: Buffer) => { stderr += chunk.toString(); });
272
+ proc.on("close", (code) => {
273
+ if (code !== 0 && stderr.trim()) {
274
+ console.error(`[Cursor stderr] exit=${code}: ${stderr.trim().slice(0, 2000)}`);
275
+ }
276
+ });
277
+
278
+ if (stdinText !== undefined) {
279
+ proc.stdin!.write(stdinText);
280
+ proc.stdin!.end();
281
+ }
282
+ return proc;
283
+ }
284
+
285
+ async function* readJsonLines(
286
+ proc: ChildProcess,
287
+ signal?: AbortSignal,
288
+ ): AsyncGenerator<CursorMessageLine> {
289
+ const rl = createInterface({ input: proc.stdout!, crlfDelay: Infinity });
290
+ for await (const line of rl) {
291
+ if (signal?.aborted) break;
292
+ const trimmed = line.trim();
293
+ if (!trimmed) continue;
294
+ try {
295
+ yield JSON.parse(trimmed) as CursorMessageLine;
296
+ } catch { /* 非 JSON 行静默跳过 */ }
297
+ }
298
+ }
299
+
300
+ // ---------------------------------------------------------------------------
301
+ // 适配器实现
302
+ // ---------------------------------------------------------------------------
303
+
304
+ class CursorAdapter implements ToolAdapter {
305
+ readonly displayName = "Cursor";
306
+ readonly sessionDescPrefix = "Cursor Session:";
307
+ private activeProcs = new Set<ChildProcess>();
308
+ private metaStore: CursorSessionMetaStore;
309
+
310
+ constructor(metaStore: CursorSessionMetaStore) {
311
+ this.metaStore = metaStore;
312
+ }
313
+
314
+ async createSession(cwd: string): Promise<CreateSessionResult> {
315
+ const proc = spawnAgent(["ok"], cwd);
316
+ this.activeProcs.add(proc);
317
+
318
+ for await (const msg of readJsonLines(proc)) {
319
+ if (msg.type === "system" && msg.subtype === "init" && msg.session_id) {
320
+ const sessionId = msg.session_id;
321
+ // 持久化 sessionId → { cwd, model }:getSessionInfo 后续依赖此映射,
322
+ // 否则 Cursor 会话上的 /git、/status、/sessions 等命令将无法显示
323
+ // 真实工作目录与真实模型。优先用 init 事件自报字段(cursor-agent
324
+ // 内部权威),cwd 没有时退回调用方传入的 cwd 兜底。
325
+ await this.metaStore
326
+ .set(sessionId, { cwd: msg.cwd ?? cwd, model: msg.model })
327
+ .catch(() => {});
328
+ this.activeProcs.delete(proc);
329
+ proc.kill();
330
+ return { sessionId };
331
+ }
332
+ }
333
+
334
+ proc.kill();
335
+ this.activeProcs.delete(proc);
336
+ throw new Error("No session ID in Cursor init event");
337
+ }
338
+
339
+ async *prompt(
340
+ sessionId: string,
341
+ userText: string,
342
+ cwd: string,
343
+ signal?: AbortSignal,
344
+ ): AsyncIterable<UnifiedStreamMessage> {
345
+ const proc = spawnAgent(["--resume", sessionId], cwd, userText);
346
+ this.activeProcs.add(proc);
347
+
348
+ try {
349
+ for await (const raw of readJsonLines(proc, signal)) {
350
+ if (signal?.aborted) break;
351
+ // 自动学习:resume 流首条 init 事件若带 cwd / model,更新映射。
352
+ // 这是为升级前创建的旧会话或映射文件意外丢失的情况兜底——
353
+ // 用户向旧会话发一次消息后,/git、/status 等即可正常显示。
354
+ // fire-and-forget:写失败不影响流式输出。
355
+ if (
356
+ raw.type === "system" &&
357
+ raw.subtype === "init" &&
358
+ raw.session_id &&
359
+ (raw.cwd || raw.model)
360
+ ) {
361
+ this.metaStore
362
+ .set(raw.session_id, { cwd: raw.cwd, model: raw.model })
363
+ .catch(() => {});
364
+ }
365
+ const normalized = normalizeCursorMessage(raw);
366
+ if (normalized) yield normalized;
367
+ }
368
+ } finally {
369
+ proc.kill();
370
+ this.activeProcs.delete(proc);
371
+ }
372
+ }
373
+
374
+ async getSessionInfo(
375
+ sessionId: string,
376
+ ): Promise<SessionInfo | undefined> {
377
+ const meta = await this.metaStore.get(sessionId);
378
+ if (!meta) return { sessionId };
379
+ return meta.model
380
+ ? { sessionId, cwd: meta.cwd, model: meta.model }
381
+ : { sessionId, cwd: meta.cwd };
382
+ }
383
+
384
+ async closeSession(_sessionId: string): Promise<void> {
385
+ // 子进程由 prompt 的 finally 自动 kill
386
+ }
387
+ }
388
+
389
+ // ---------------------------------------------------------------------------
390
+ // 工厂函数
391
+ // ---------------------------------------------------------------------------
392
+
393
+ export interface CreateCursorAdapterOptions {
394
+ /** 注入自定义 meta 持久化 store(测试用);未提供时使用全局默认实例。 */
395
+ metaStore?: CursorSessionMetaStore;
396
+ }
397
+
398
+ export function createCursorAdapter(
399
+ options: CreateCursorAdapterOptions = {},
400
+ ): ToolAdapter {
401
+ return new CursorAdapter(options.metaStore ?? defaultCursorSessionMetaStore);
229
402
  }