chatccc 0.2.5 → 0.2.7

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.
@@ -0,0 +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
+ 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);
402
+ }
@@ -0,0 +1,154 @@
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. /status、/sessions 显示的"模型"只能硬塞 ChatCCC 的 ANTHROPIC 环境变量,
9
+ // 与 Cursor 实际跑的 Composer 2 Fast 等真实模型无关
10
+ //
11
+ // 存储:
12
+ // 文件 .claude/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
+
23
+ import { mkdir, readFile, writeFile } from "node:fs/promises";
24
+ import { dirname, join } from "node:path";
25
+
26
+ import { PROJECT_ROOT } from "../config.ts";
27
+
28
+ /** 持久化文件默认路径(生产)。测试可通过 createCursorSessionMetaStore(filePath) 注入。 */
29
+ export const CURSOR_SESSION_META_FILE = join(
30
+ PROJECT_ROOT,
31
+ ".claude",
32
+ "cursor-session-meta.json",
33
+ );
34
+
35
+ /**
36
+ * 单条会话元数据。cwd 为必填(无 cwd 的记录视为不完整,get 返回 undefined);
37
+ * model 可选(cursor agent init 事件理论上一定带,留可选是为防御性兜底)。
38
+ */
39
+ export interface CursorSessionMeta {
40
+ cwd: string;
41
+ model?: string;
42
+ }
43
+
44
+ export interface CursorSessionMetaStore {
45
+ /** 查询某 sessionId 对应的元数据;未记录或 cwd 缺失返回 undefined。 */
46
+ get(sessionId: string): Promise<CursorSessionMeta | undefined>;
47
+ /**
48
+ * 部分合并写入:仅写入非 undefined / 非空字段;其他字段保持原值。
49
+ * - 第一次写入若不含 cwd,记录视为不完整,get 仍返回 undefined
50
+ * - 同 sessionId 重复写入完全相同值时跳过 IO(性能优化)
51
+ */
52
+ set(sessionId: string, partial: Partial<CursorSessionMeta>): Promise<void>;
53
+ }
54
+
55
+ interface RawEntry {
56
+ cwd?: string;
57
+ model?: string;
58
+ }
59
+
60
+ function isNonEmptyString(v: unknown): v is string {
61
+ return typeof v === "string" && v.length > 0;
62
+ }
63
+
64
+ /**
65
+ * 解析持久化文件中的单条记录,兼容历史 schema:
66
+ * - 新版:{ cwd: string, model?: string }
67
+ * - 历史 v1:纯字符串(直接是 cwd 值)—— 升级前旧数据兼容
68
+ * 非法形态返回 null。
69
+ */
70
+ function parseEntry(raw: unknown): RawEntry | null {
71
+ if (typeof raw === "string" && raw.length > 0) {
72
+ return { cwd: raw };
73
+ }
74
+ if (raw && typeof raw === "object" && !Array.isArray(raw)) {
75
+ const obj = raw as Record<string, unknown>;
76
+ const out: RawEntry = {};
77
+ if (isNonEmptyString(obj.cwd)) out.cwd = obj.cwd;
78
+ if (isNonEmptyString(obj.model)) out.model = obj.model;
79
+ return out;
80
+ }
81
+ return null;
82
+ }
83
+
84
+ /**
85
+ * 创建一个基于 JSON 文件的 store 实例。
86
+ *
87
+ * - 首次访问时懒加载文件到内存缓存;后续读全部走缓存
88
+ * - 写时先合并到缓存再落盘(写失败仅 console.error,不抛异常)
89
+ * - 同一 sessionId 重复 set 完全相同值时跳过 IO
90
+ */
91
+ export function createCursorSessionMetaStore(
92
+ filePath: string = CURSOR_SESSION_META_FILE,
93
+ ): CursorSessionMetaStore {
94
+ let cache: Record<string, RawEntry> | null = null;
95
+
96
+ async function load(): Promise<Record<string, RawEntry>> {
97
+ if (cache) return cache;
98
+ try {
99
+ const raw = await readFile(filePath, "utf-8");
100
+ const parsed = JSON.parse(raw);
101
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
102
+ const out: Record<string, RawEntry> = {};
103
+ for (const [k, v] of Object.entries(parsed as Record<string, unknown>)) {
104
+ const entry = parseEntry(v);
105
+ if (entry) out[k] = entry;
106
+ }
107
+ cache = out;
108
+ return out;
109
+ }
110
+ } catch {
111
+ // 文件不存在 / JSON 损坏 / 读权限失败 → 视为空映射,不阻断主流程
112
+ }
113
+ cache = {};
114
+ return cache;
115
+ }
116
+
117
+ return {
118
+ async get(sessionId: string): Promise<CursorSessionMeta | undefined> {
119
+ const map = await load();
120
+ const entry = map[sessionId];
121
+ if (!entry || !isNonEmptyString(entry.cwd)) return undefined;
122
+ return entry.model
123
+ ? { cwd: entry.cwd, model: entry.model }
124
+ : { cwd: entry.cwd };
125
+ },
126
+
127
+ async set(
128
+ sessionId: string,
129
+ partial: Partial<CursorSessionMeta>,
130
+ ): Promise<void> {
131
+ const map = await load();
132
+ const existing = map[sessionId] ?? {};
133
+ const merged: RawEntry = { ...existing };
134
+ if (isNonEmptyString(partial.cwd)) merged.cwd = partial.cwd;
135
+ if (isNonEmptyString(partial.model)) merged.model = partial.model;
136
+
137
+ // 与原值完全相同时跳过 IO
138
+ if (existing.cwd === merged.cwd && existing.model === merged.model) return;
139
+
140
+ map[sessionId] = merged;
141
+ try {
142
+ await mkdir(dirname(filePath), { recursive: true });
143
+ await writeFile(filePath, JSON.stringify(map, null, 2), "utf-8");
144
+ } catch (err) {
145
+ console.error(
146
+ `[cursor-session-meta] failed to persist ${filePath}: ${(err as Error).message}`,
147
+ );
148
+ }
149
+ },
150
+ };
151
+ }
152
+
153
+ /** 生产环境共享的全局默认实例(指向 .claude/cursor-session-meta.json)。 */
154
+ export const defaultCursorSessionMetaStore = createCursorSessionMetaStore();