chatccc 0.2.4 → 0.2.6

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,250 @@
1
+ import { describe, it, expect } from "vitest";
2
+ import { normalizeCursorMessage, createCursorAdapter } from "../adapters/cursor-adapter.ts";
3
+ import type { UnifiedStreamMessage } from "../adapters/adapter-interface.ts";
4
+
5
+ // ---------------------------------------------------------------------------
6
+ // normalizeCursorMessage — 核心映射逻辑测试(纯函数)
7
+ // ---------------------------------------------------------------------------
8
+
9
+ describe("normalizeCursorMessage", () => {
10
+ // --- assistant messages ---
11
+
12
+ it("normalizes assistant message with text block", () => {
13
+ const result = normalizeCursorMessage({
14
+ type: "assistant",
15
+ message: {
16
+ role: "assistant",
17
+ content: [{ type: "text", text: "Hello world" }],
18
+ },
19
+ });
20
+ expect(result).not.toBeNull();
21
+ expect(result!.type).toBe("assistant");
22
+ expect(result!.blocks).toEqual([{ type: "text", text: "Hello world" }]);
23
+ });
24
+
25
+ it("normalizes assistant message with thinking block", () => {
26
+ const result = normalizeCursorMessage({
27
+ type: "assistant",
28
+ message: {
29
+ role: "assistant",
30
+ content: [{ type: "thinking", thinking: "Let me think..." }],
31
+ },
32
+ });
33
+ expect(result).not.toBeNull();
34
+ expect(result!.blocks).toEqual([{ type: "thinking", thinking: "Let me think..." }]);
35
+ });
36
+
37
+ it("normalizes assistant message with tool_use block", () => {
38
+ const result = normalizeCursorMessage({
39
+ type: "assistant",
40
+ message: {
41
+ role: "assistant",
42
+ content: [
43
+ { type: "tool_use", name: "read_file", input: { filePath: "/tmp/test" } },
44
+ ],
45
+ },
46
+ });
47
+ expect(result).not.toBeNull();
48
+ expect(result!.blocks).toEqual([
49
+ { type: "tool_use", name: "read_file", input: { filePath: "/tmp/test" } },
50
+ ]);
51
+ });
52
+
53
+ it("uses 'unknown' for tool_use without name", () => {
54
+ const result = normalizeCursorMessage({
55
+ type: "assistant",
56
+ message: { role: "assistant", content: [{ type: "tool_use", input: {} }] },
57
+ });
58
+ expect(result!.blocks[0]).toMatchObject({ type: "tool_use", name: "unknown" });
59
+ });
60
+
61
+ it("normalizes assistant message with search_result block", () => {
62
+ const result = normalizeCursorMessage({
63
+ type: "assistant",
64
+ message: {
65
+ role: "assistant",
66
+ content: [{ type: "search_result", query: "cursor docs" }],
67
+ },
68
+ });
69
+ expect(result!.blocks).toEqual([{ type: "search_result", query: "cursor docs" }]);
70
+ });
71
+
72
+ it("normalizes assistant message with redacted_thinking block", () => {
73
+ const result = normalizeCursorMessage({
74
+ type: "assistant",
75
+ message: { role: "assistant", content: [{ type: "redacted_thinking" }] },
76
+ });
77
+ expect(result!.blocks).toEqual([{ type: "redacted_thinking" }]);
78
+ });
79
+
80
+ // --- user messages (tool_result) ---
81
+
82
+ it("normalizes user message with tool_result block (success)", () => {
83
+ const result = normalizeCursorMessage({
84
+ type: "user",
85
+ message: {
86
+ role: "user",
87
+ content: [
88
+ { type: "tool_result", tool_use_id: "call_abc", content: "done", is_error: false },
89
+ ],
90
+ },
91
+ });
92
+ expect(result).not.toBeNull();
93
+ expect(result!.type).toBe("user");
94
+ expect(result!.blocks).toEqual([
95
+ { type: "tool_result", tool_use_id: "call_abc", content: "done", is_error: false },
96
+ ]);
97
+ });
98
+
99
+ it("normalizes user message with tool_result block (error)", () => {
100
+ const result = normalizeCursorMessage({
101
+ type: "user",
102
+ message: {
103
+ role: "user",
104
+ content: [
105
+ { type: "tool_result", tool_use_id: "call_err", content: "fail", is_error: true },
106
+ ],
107
+ },
108
+ });
109
+ expect(result!.blocks).toEqual([
110
+ { type: "tool_result", tool_use_id: "call_err", content: "fail", is_error: true },
111
+ ]);
112
+ });
113
+
114
+ // --- mixed blocks ---
115
+
116
+ it("normalizes message with multiple block types", () => {
117
+ const result = normalizeCursorMessage({
118
+ type: "assistant",
119
+ message: {
120
+ role: "assistant",
121
+ content: [
122
+ { type: "thinking", thinking: "Hmm..." },
123
+ { type: "tool_use", name: "search", input: { query: "x" } },
124
+ { type: "text", text: "Result found." },
125
+ ],
126
+ },
127
+ });
128
+ expect(result).not.toBeNull();
129
+ expect(result!.blocks).toHaveLength(3);
130
+ });
131
+
132
+ // --- edge cases ---
133
+
134
+ it("returns null for result messages (completion signal)", () => {
135
+ expect(
136
+ normalizeCursorMessage({
137
+ type: "result",
138
+ subtype: "success",
139
+ result: "done",
140
+ }),
141
+ ).toBeNull();
142
+ });
143
+
144
+ it("returns null for system init messages", () => {
145
+ expect(
146
+ normalizeCursorMessage({
147
+ type: "system",
148
+ subtype: "init",
149
+ session_id: "abc",
150
+ }),
151
+ ).toBeNull();
152
+ });
153
+
154
+ it("returns null for unknown message types", () => {
155
+ expect(normalizeCursorMessage({ type: "unknown_type" })).toBeNull();
156
+ expect(normalizeCursorMessage({})).toBeNull();
157
+ });
158
+
159
+ it("skips unknown block types in content", () => {
160
+ const result = normalizeCursorMessage({
161
+ type: "assistant",
162
+ message: {
163
+ role: "assistant",
164
+ content: [
165
+ { type: "custom_block", data: "ignored" },
166
+ { type: "text", text: "visible" },
167
+ ],
168
+ },
169
+ });
170
+ expect(result!.blocks).toEqual([{ type: "text", text: "visible" }]);
171
+ });
172
+
173
+ it("returns message with empty blocks for empty content array", () => {
174
+ const result = normalizeCursorMessage({
175
+ type: "assistant",
176
+ message: { role: "assistant", content: [] },
177
+ });
178
+ expect(result).not.toBeNull();
179
+ expect(result!.blocks).toEqual([]);
180
+ });
181
+
182
+ it("returns null for message without content", () => {
183
+ const result = normalizeCursorMessage({
184
+ type: "assistant",
185
+ message: { role: "assistant" },
186
+ });
187
+ expect(result).toBeNull();
188
+ });
189
+
190
+ it("skips thinking block with empty string", () => {
191
+ const result = normalizeCursorMessage({
192
+ type: "assistant",
193
+ message: { role: "assistant", content: [{ type: "thinking", thinking: "" }] },
194
+ });
195
+ expect(result!.blocks).toEqual([]);
196
+ });
197
+
198
+ it("skips text block with empty string", () => {
199
+ const result = normalizeCursorMessage({
200
+ type: "assistant",
201
+ message: { role: "assistant", content: [{ type: "text", text: "" }] },
202
+ });
203
+ expect(result!.blocks).toEqual([]);
204
+ });
205
+
206
+ it("returns null for system message without compact_boundary subtype", () => {
207
+ expect(
208
+ normalizeCursorMessage({ type: "system", subtype: "notification" }),
209
+ ).toBeNull();
210
+ });
211
+
212
+ it("normalizes system compact_boundary message", () => {
213
+ const msg: Record<string, unknown> = {
214
+ type: "system",
215
+ subtype: "compact_boundary",
216
+ compact_metadata: { trigger: "auto", pre_tokens: 15000, post_tokens: 8000 },
217
+ };
218
+ const result = normalizeCursorMessage(
219
+ msg as Parameters<typeof normalizeCursorMessage>[0],
220
+ );
221
+ expect(result).not.toBeNull();
222
+ expect(result!.type).toBe("system");
223
+ expect(result!.blocks).toEqual([
224
+ { type: "compact_boundary", trigger: "auto", pre_tokens: 15000, post_tokens: 8000 },
225
+ ]);
226
+ });
227
+ });
228
+
229
+ // ---------------------------------------------------------------------------
230
+ // createCursorAdapter — 工厂函数测试
231
+ // ---------------------------------------------------------------------------
232
+
233
+ describe("createCursorAdapter", () => {
234
+ it("returns adapter with correct displayName and sessionDescPrefix", () => {
235
+ const adapter = createCursorAdapter();
236
+ expect(adapter.displayName).toBe("Cursor");
237
+ expect(adapter.sessionDescPrefix).toBe("Cursor Session:");
238
+ });
239
+
240
+ it("closeSession does not throw", async () => {
241
+ const adapter = createCursorAdapter();
242
+ await expect(adapter.closeSession("any-id")).resolves.toBeUndefined();
243
+ });
244
+
245
+ it("getSessionInfo returns basic info", async () => {
246
+ const adapter = createCursorAdapter();
247
+ const info = await adapter.getSessionInfo("test-sid");
248
+ expect(info).toEqual({ sessionId: "test-sid" });
249
+ });
250
+ });
@@ -7,7 +7,10 @@ import {
7
7
  resetState,
8
8
  getSessionStatus,
9
9
  getAllSessionsStatus,
10
+ accumulateBlockContent,
10
11
  } from "../session.ts";
12
+ import type { AccumulatorState } from "../session.ts";
13
+ import type { UnifiedBlock } from "../adapters/adapter-interface.ts";
11
14
 
12
15
  // Helper to create a mock active session entry
13
16
  function mockActiveSession(chatId: string, overrides: Partial<{
@@ -42,6 +45,7 @@ function mockSessionInfo(chatId: string, overrides: Partial<{
42
45
  startTime: overrides.startTime ?? Date.now(),
43
46
  model: "Claude Opus 4.7",
44
47
  effort: "high",
48
+ tool: "claude",
45
49
  });
46
50
  }
47
51
 
@@ -54,7 +58,7 @@ describe("resetState", () => {
54
58
  });
55
59
  sessionInfoMap.set("chat1", {
56
60
  sessionId: "s1", turnCount: 1, lastContextTokens: 0,
57
- startTime: 0, model: "", effort: "",
61
+ startTime: 0, model: "", effort: "", tool: "claude",
58
62
  });
59
63
  processedMessages.add("msg1");
60
64
 
@@ -148,4 +152,146 @@ describe("processedMessages dedup", () => {
148
152
  it("MAX_PROCESSED is defined", () => {
149
153
  expect(MAX_PROCESSED).toBe(5000);
150
154
  });
155
+ });
156
+
157
+ // ---------------------------------------------------------------------------
158
+ // accumulateBlockContent — 统一消息块累积测试
159
+ // ---------------------------------------------------------------------------
160
+
161
+ function freshState(): AccumulatorState {
162
+ return { accumulatedContent: "", finalText: "", chunkCount: 0 };
163
+ }
164
+
165
+ describe("accumulateBlockContent", () => {
166
+ it("accumulates thinking block into accumulatedContent", () => {
167
+ const s = freshState();
168
+ accumulateBlockContent({ type: "thinking", thinking: "Let me think..." }, s);
169
+ expect(s.accumulatedContent).toBe("Let me think...");
170
+ expect(s.chunkCount).toBe(1);
171
+ expect(s.finalText).toBe("");
172
+ });
173
+
174
+ it("accumulates text block into finalText", () => {
175
+ const s = freshState();
176
+ accumulateBlockContent({ type: "text", text: "Hello world" }, s);
177
+ expect(s.finalText).toBe("Hello world");
178
+ expect(s.accumulatedContent).toBe("");
179
+ });
180
+
181
+ it("accumulates tool_use block with formatted name and input", () => {
182
+ const s = freshState();
183
+ accumulateBlockContent(
184
+ { type: "tool_use", name: "Read", input: { file_path: "/tmp/test.txt" } },
185
+ s,
186
+ );
187
+ expect(s.accumulatedContent).toContain("📖"); // 📖
188
+ expect(s.accumulatedContent).toContain("**Read**");
189
+ expect(s.accumulatedContent).toContain("file_path");
190
+ });
191
+
192
+ it("accumulates tool_use block with long input truncated", () => {
193
+ const s = freshState();
194
+ const longInput = "x".repeat(500);
195
+ accumulateBlockContent(
196
+ { type: "tool_use", name: "Bash", input: longInput },
197
+ s,
198
+ );
199
+ expect(s.accumulatedContent).toContain("...");
200
+ // Should be truncated to 300 + "..."
201
+ const inputPart = s.accumulatedContent.split("`")[1];
202
+ expect(inputPart.length).toBeLessThanOrEqual(304); // 300 + "..."
203
+ });
204
+
205
+ it("accumulates tool_result block with success icon (✅)", () => {
206
+ const s = freshState();
207
+ accumulateBlockContent(
208
+ { type: "tool_result", tool_use_id: "tool_abc123", content: "done", is_error: false },
209
+ s,
210
+ );
211
+ expect(s.accumulatedContent).toContain("✅"); // ✅
212
+ expect(s.accumulatedContent).toContain("abc123");
213
+ expect(s.accumulatedContent).toContain("done");
214
+ });
215
+
216
+ it("accumulates tool_result block with error icon (❌)", () => {
217
+ const s = freshState();
218
+ accumulateBlockContent(
219
+ { type: "tool_result", tool_use_id: "tool_err456", content: "failed", is_error: true },
220
+ s,
221
+ );
222
+ expect(s.accumulatedContent).toContain("❌"); // ❌
223
+ });
224
+
225
+ it("accumulates tool_result with array content (text blocks)", () => {
226
+ const s = freshState();
227
+ const content = [{ type: "text", text: "line1" }, { type: "text", text: "line2" }];
228
+ accumulateBlockContent(
229
+ { type: "tool_result", tool_use_id: "tool_arr", content },
230
+ s,
231
+ );
232
+ expect(s.accumulatedContent).toContain("line1line2");
233
+ });
234
+
235
+ it("accumulates tool_result with object content (JSON stringified)", () => {
236
+ const s = freshState();
237
+ accumulateBlockContent(
238
+ { type: "tool_result", tool_use_id: "tool_obj", content: { key: "val" } },
239
+ s,
240
+ );
241
+ expect(s.accumulatedContent).toContain('{"key":"val"}');
242
+ });
243
+
244
+ it("accumulates redacted_thinking block with safety notice", () => {
245
+ const s = freshState();
246
+ accumulateBlockContent({ type: "redacted_thinking" }, s);
247
+ expect(s.accumulatedContent).toContain("内容被安全过滤"); // 内容被安全过滤
248
+ });
249
+
250
+ it("accumulates search_result block with query", () => {
251
+ const s = freshState();
252
+ accumulateBlockContent(
253
+ { type: "search_result", query: "TypeScript docs" },
254
+ s,
255
+ );
256
+ expect(s.accumulatedContent).toContain("🔍"); // 🔍
257
+ expect(s.accumulatedContent).toContain("TypeScript docs");
258
+ });
259
+
260
+ it("accumulates compact_boundary block with trigger label", () => {
261
+ const s = freshState();
262
+ accumulateBlockContent(
263
+ { type: "compact_boundary", trigger: "auto", pre_tokens: 15000, post_tokens: 8000 },
264
+ s,
265
+ );
266
+ expect(s.accumulatedContent).toContain("🔄"); // 🔄
267
+ expect(s.accumulatedContent).toContain("自动");
268
+ expect(s.accumulatedContent).toContain("15000");
269
+ expect(s.accumulatedContent).toContain("8000");
270
+ });
271
+
272
+ it("accumulates compact_boundary with manual trigger label", () => {
273
+ const s = freshState();
274
+ accumulateBlockContent(
275
+ { type: "compact_boundary", trigger: "manual", pre_tokens: 20000 },
276
+ s,
277
+ );
278
+ expect(s.accumulatedContent).toContain("手动");
279
+ });
280
+
281
+ it("accumulates multiple blocks in sequence correctly", () => {
282
+ const s = freshState();
283
+ accumulateBlockContent({ type: "thinking", thinking: "Hmm..." }, s);
284
+ accumulateBlockContent({ type: "tool_use", name: "Grep", input: { pattern: "foo" } }, s);
285
+ accumulateBlockContent(
286
+ { type: "tool_result", tool_use_id: "abc123", content: "found 3 matches", is_error: false },
287
+ s,
288
+ );
289
+ accumulateBlockContent({ type: "text", text: "I found the results." }, s);
290
+
291
+ expect(s.accumulatedContent).toContain("Hmm...");
292
+ expect(s.accumulatedContent).toContain("Grep");
293
+ expect(s.accumulatedContent).toContain("found 3 matches");
294
+ expect(s.finalText).toBe("I found the results.");
295
+ expect(s.chunkCount).toBe(1); // Only thinking increments chunkCount
296
+ });
151
297
  });
@@ -0,0 +1,127 @@
1
+ // =============================================================================
2
+ // adapter-interface.ts — 统一的 AI 工具适配器接口和归一化消息类型
3
+ // =============================================================================
4
+ // 所有 AI 工具适配器(Claude SDK、Cursor CLI、Codex CLI 等)都必须实现
5
+ // ToolAdapter 接口。归一化消息类型 UnifiedBlock 屏蔽了各工具的差异,
6
+ // 使 session.ts 不需要关心底层是哪个 AI 工具。
7
+ // =============================================================================
8
+
9
+ // ---------------------------------------------------------------------------
10
+ // UnifiedBlock — 归一化后的消息块
11
+ // ---------------------------------------------------------------------------
12
+
13
+ export interface UnifiedThinkingBlock {
14
+ type: "thinking";
15
+ thinking: string;
16
+ }
17
+
18
+ export interface UnifiedTextBlock {
19
+ type: "text";
20
+ text: string;
21
+ }
22
+
23
+ export interface UnifiedToolUseBlock {
24
+ type: "tool_use";
25
+ name: string;
26
+ input: unknown;
27
+ }
28
+
29
+ export interface UnifiedToolResultBlock {
30
+ type: "tool_result";
31
+ tool_use_id: string;
32
+ content: unknown;
33
+ is_error?: boolean;
34
+ }
35
+
36
+ export interface UnifiedRedactedThinkingBlock {
37
+ type: "redacted_thinking";
38
+ }
39
+
40
+ export interface UnifiedSearchResultBlock {
41
+ type: "search_result";
42
+ query: string;
43
+ }
44
+
45
+ export interface UnifiedCompactBoundaryBlock {
46
+ type: "compact_boundary";
47
+ trigger: "manual" | "auto";
48
+ pre_tokens: number;
49
+ post_tokens?: number;
50
+ }
51
+
52
+ export type UnifiedBlock =
53
+ | UnifiedThinkingBlock
54
+ | UnifiedTextBlock
55
+ | UnifiedToolUseBlock
56
+ | UnifiedToolResultBlock
57
+ | UnifiedRedactedThinkingBlock
58
+ | UnifiedSearchResultBlock
59
+ | UnifiedCompactBoundaryBlock;
60
+
61
+ // ---------------------------------------------------------------------------
62
+ // UnifiedStreamMessage — 一次 SDK/CLI 事件对应的归一化消息
63
+ // ---------------------------------------------------------------------------
64
+
65
+ export interface UnifiedStreamMessage {
66
+ type: "assistant" | "user" | "system";
67
+ blocks: UnifiedBlock[];
68
+ }
69
+
70
+ // ---------------------------------------------------------------------------
71
+ // CreateSessionResult
72
+ // ---------------------------------------------------------------------------
73
+
74
+ export interface CreateSessionResult {
75
+ sessionId: string;
76
+ }
77
+
78
+ // ---------------------------------------------------------------------------
79
+ // SessionInfo — 会话元数据(/status、/cd 等命令使用)
80
+ // ---------------------------------------------------------------------------
81
+
82
+ export interface SessionInfo {
83
+ sessionId: string;
84
+ cwd?: string;
85
+ summary?: string;
86
+ lastModified?: number;
87
+ }
88
+
89
+ // ---------------------------------------------------------------------------
90
+ // ToolAdapter — 统一的 AI 工具适配器接口
91
+ // ---------------------------------------------------------------------------
92
+
93
+ export interface ToolAdapter {
94
+ /** 日志/展示用名称,如 "Claude" */
95
+ readonly displayName: string;
96
+
97
+ /** 群描述中会话 ID 的前缀,如 "Claude Session:" */
98
+ readonly sessionDescPrefix: string;
99
+
100
+ /**
101
+ * 创建新会话,返回会话 ID。
102
+ * 适配器内部需处理后台流消费(静默消费 stream 中除 init 外的所有事件)。
103
+ */
104
+ createSession(cwd: string): Promise<CreateSessionResult>;
105
+
106
+ /**
107
+ * 向已有会话发送提示文本,返回归一化消息的异步迭代器。
108
+ * 消费者遍历结束后(或提前中止时)适配器自动关闭底层会话。
109
+ */
110
+ prompt(
111
+ sessionId: string,
112
+ userText: string,
113
+ cwd: string,
114
+ signal?: AbortSignal,
115
+ ): AsyncIterable<UnifiedStreamMessage>;
116
+
117
+ /**
118
+ * 查询会话元数据。会话不存在时返回 undefined。
119
+ */
120
+ getSessionInfo(sessionId: string): Promise<SessionInfo | undefined>;
121
+
122
+ /**
123
+ * 关闭/清理会话(/stop 或中断时调用)。
124
+ * 对于流式结束后自动关闭的适配器(如 Claude SDK),此为 no-op。
125
+ */
126
+ closeSession(sessionId: string): Promise<void>;
127
+ }