chatccc 0.2.4 → 0.2.5

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.
@@ -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<{
@@ -148,4 +151,146 @@ describe("processedMessages dedup", () => {
148
151
  it("MAX_PROCESSED is defined", () => {
149
152
  expect(MAX_PROCESSED).toBe(5000);
150
153
  });
154
+ });
155
+
156
+ // ---------------------------------------------------------------------------
157
+ // accumulateBlockContent — 统一消息块累积测试
158
+ // ---------------------------------------------------------------------------
159
+
160
+ function freshState(): AccumulatorState {
161
+ return { accumulatedContent: "", finalText: "", chunkCount: 0 };
162
+ }
163
+
164
+ describe("accumulateBlockContent", () => {
165
+ it("accumulates thinking block into accumulatedContent", () => {
166
+ const s = freshState();
167
+ accumulateBlockContent({ type: "thinking", thinking: "Let me think..." }, s);
168
+ expect(s.accumulatedContent).toBe("Let me think...");
169
+ expect(s.chunkCount).toBe(1);
170
+ expect(s.finalText).toBe("");
171
+ });
172
+
173
+ it("accumulates text block into finalText", () => {
174
+ const s = freshState();
175
+ accumulateBlockContent({ type: "text", text: "Hello world" }, s);
176
+ expect(s.finalText).toBe("Hello world");
177
+ expect(s.accumulatedContent).toBe("");
178
+ });
179
+
180
+ it("accumulates tool_use block with formatted name and input", () => {
181
+ const s = freshState();
182
+ accumulateBlockContent(
183
+ { type: "tool_use", name: "Read", input: { file_path: "/tmp/test.txt" } },
184
+ s,
185
+ );
186
+ expect(s.accumulatedContent).toContain("📖"); // 📖
187
+ expect(s.accumulatedContent).toContain("**Read**");
188
+ expect(s.accumulatedContent).toContain("file_path");
189
+ });
190
+
191
+ it("accumulates tool_use block with long input truncated", () => {
192
+ const s = freshState();
193
+ const longInput = "x".repeat(500);
194
+ accumulateBlockContent(
195
+ { type: "tool_use", name: "Bash", input: longInput },
196
+ s,
197
+ );
198
+ expect(s.accumulatedContent).toContain("...");
199
+ // Should be truncated to 300 + "..."
200
+ const inputPart = s.accumulatedContent.split("`")[1];
201
+ expect(inputPart.length).toBeLessThanOrEqual(304); // 300 + "..."
202
+ });
203
+
204
+ it("accumulates tool_result block with success icon (✅)", () => {
205
+ const s = freshState();
206
+ accumulateBlockContent(
207
+ { type: "tool_result", tool_use_id: "tool_abc123", content: "done", is_error: false },
208
+ s,
209
+ );
210
+ expect(s.accumulatedContent).toContain("✅"); // ✅
211
+ expect(s.accumulatedContent).toContain("abc123");
212
+ expect(s.accumulatedContent).toContain("done");
213
+ });
214
+
215
+ it("accumulates tool_result block with error icon (❌)", () => {
216
+ const s = freshState();
217
+ accumulateBlockContent(
218
+ { type: "tool_result", tool_use_id: "tool_err456", content: "failed", is_error: true },
219
+ s,
220
+ );
221
+ expect(s.accumulatedContent).toContain("❌"); // ❌
222
+ });
223
+
224
+ it("accumulates tool_result with array content (text blocks)", () => {
225
+ const s = freshState();
226
+ const content = [{ type: "text", text: "line1" }, { type: "text", text: "line2" }];
227
+ accumulateBlockContent(
228
+ { type: "tool_result", tool_use_id: "tool_arr", content },
229
+ s,
230
+ );
231
+ expect(s.accumulatedContent).toContain("line1line2");
232
+ });
233
+
234
+ it("accumulates tool_result with object content (JSON stringified)", () => {
235
+ const s = freshState();
236
+ accumulateBlockContent(
237
+ { type: "tool_result", tool_use_id: "tool_obj", content: { key: "val" } },
238
+ s,
239
+ );
240
+ expect(s.accumulatedContent).toContain('{"key":"val"}');
241
+ });
242
+
243
+ it("accumulates redacted_thinking block with safety notice", () => {
244
+ const s = freshState();
245
+ accumulateBlockContent({ type: "redacted_thinking" }, s);
246
+ expect(s.accumulatedContent).toContain("内容被安全过滤"); // 内容被安全过滤
247
+ });
248
+
249
+ it("accumulates search_result block with query", () => {
250
+ const s = freshState();
251
+ accumulateBlockContent(
252
+ { type: "search_result", query: "TypeScript docs" },
253
+ s,
254
+ );
255
+ expect(s.accumulatedContent).toContain("🔍"); // 🔍
256
+ expect(s.accumulatedContent).toContain("TypeScript docs");
257
+ });
258
+
259
+ it("accumulates compact_boundary block with trigger label", () => {
260
+ const s = freshState();
261
+ accumulateBlockContent(
262
+ { type: "compact_boundary", trigger: "auto", pre_tokens: 15000, post_tokens: 8000 },
263
+ s,
264
+ );
265
+ expect(s.accumulatedContent).toContain("🔄"); // 🔄
266
+ expect(s.accumulatedContent).toContain("自动");
267
+ expect(s.accumulatedContent).toContain("15000");
268
+ expect(s.accumulatedContent).toContain("8000");
269
+ });
270
+
271
+ it("accumulates compact_boundary with manual trigger label", () => {
272
+ const s = freshState();
273
+ accumulateBlockContent(
274
+ { type: "compact_boundary", trigger: "manual", pre_tokens: 20000 },
275
+ s,
276
+ );
277
+ expect(s.accumulatedContent).toContain("手动");
278
+ });
279
+
280
+ it("accumulates multiple blocks in sequence correctly", () => {
281
+ const s = freshState();
282
+ accumulateBlockContent({ type: "thinking", thinking: "Hmm..." }, s);
283
+ accumulateBlockContent({ type: "tool_use", name: "Grep", input: { pattern: "foo" } }, s);
284
+ accumulateBlockContent(
285
+ { type: "tool_result", tool_use_id: "abc123", content: "found 3 matches", is_error: false },
286
+ s,
287
+ );
288
+ accumulateBlockContent({ type: "text", text: "I found the results." }, s);
289
+
290
+ expect(s.accumulatedContent).toContain("Hmm...");
291
+ expect(s.accumulatedContent).toContain("Grep");
292
+ expect(s.accumulatedContent).toContain("found 3 matches");
293
+ expect(s.finalText).toBe("I found the results.");
294
+ expect(s.chunkCount).toBe(1); // Only thinking increments chunkCount
295
+ });
151
296
  });
@@ -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
+ }
@@ -0,0 +1,257 @@
1
+ // =============================================================================
2
+ // claude-adapter.ts — Claude Agent SDK 适配器
3
+ // =============================================================================
4
+ // 实现 ToolAdapter 接口,将 @anthropic-ai/claude-agent-sdk 调用封装在内。
5
+ // =============================================================================
6
+
7
+ import {
8
+ unstable_v2_createSession,
9
+ unstable_v2_resumeSession,
10
+ getSessionInfo as sdkGetSessionInfo,
11
+ } from "@anthropic-ai/claude-agent-sdk";
12
+
13
+ import type {
14
+ ToolAdapter,
15
+ UnifiedBlock,
16
+ UnifiedStreamMessage,
17
+ CreateSessionResult,
18
+ SessionInfo,
19
+ } from "./adapter-interface.ts";
20
+
21
+ // ---------------------------------------------------------------------------
22
+ // 类型别名:SDK 内部消息的形状(避免导入 sdk.d.ts 的大型联合类型)
23
+ // ---------------------------------------------------------------------------
24
+
25
+ interface SdkContentBlock {
26
+ type: string;
27
+ text?: string;
28
+ thinking?: string;
29
+ name?: string;
30
+ input?: unknown;
31
+ tool_use_id?: string;
32
+ content?: unknown;
33
+ is_error?: boolean;
34
+ query?: string;
35
+ [key: string]: unknown;
36
+ }
37
+
38
+ interface SdkMessageLike {
39
+ type?: string;
40
+ subtype?: string;
41
+ message?: { content?: SdkContentBlock[] };
42
+ compact_metadata?: {
43
+ trigger?: "manual" | "auto";
44
+ pre_tokens?: number;
45
+ post_tokens?: number;
46
+ };
47
+ session_id?: string;
48
+ }
49
+
50
+ // ---------------------------------------------------------------------------
51
+ // ClaudeAdapterOptions
52
+ // ---------------------------------------------------------------------------
53
+
54
+ export interface ClaudeAdapterOptions {
55
+ model: string;
56
+ effort: string;
57
+ isDefault: (value: string) => boolean;
58
+ }
59
+
60
+ // ---------------------------------------------------------------------------
61
+ // buildSessionOptions — 还原 claudeSdkSessionOptions 的精确行为
62
+ // ---------------------------------------------------------------------------
63
+
64
+ function buildSessionOptions(
65
+ cwd: string,
66
+ model: string,
67
+ effort: string,
68
+ isDefault: (value: string) => boolean,
69
+ ): Record<string, unknown> {
70
+ const o: Record<string, unknown> = {
71
+ cwd,
72
+ permissionMode: "bypassPermissions",
73
+ allowDangerouslySkipPermissions: true,
74
+ autoCompactEnabled: true,
75
+ };
76
+ if (!isDefault(model)) o.model = model;
77
+ if (!isDefault(effort)) o.effort = effort;
78
+ return o;
79
+ }
80
+
81
+ // ---------------------------------------------------------------------------
82
+ // normalizeSdkMessage — 关键映射:SDK 消息 → UnifiedStreamMessage | null
83
+ // ---------------------------------------------------------------------------
84
+
85
+ export function normalizeSdkMessage(msg: SdkMessageLike): UnifiedStreamMessage | null {
86
+ // 1) assistant / user 消息:遍历 content 块
87
+ if (
88
+ (msg.type === "assistant" || msg.type === "user") &&
89
+ msg.message?.content
90
+ ) {
91
+ const blocks: UnifiedBlock[] = [];
92
+ for (const block of msg.message.content) {
93
+ if (block.type === "thinking" && block.thinking) {
94
+ blocks.push({ type: "thinking", thinking: block.thinking });
95
+ } else if (block.type === "tool_use") {
96
+ blocks.push({
97
+ type: "tool_use",
98
+ name: block.name ?? "unknown",
99
+ input: block.input,
100
+ });
101
+ } else if (block.type === "tool_result") {
102
+ blocks.push({
103
+ type: "tool_result",
104
+ tool_use_id: block.tool_use_id ?? "",
105
+ content: block.content,
106
+ is_error: block.is_error,
107
+ });
108
+ } else if (block.type === "redacted_thinking") {
109
+ blocks.push({ type: "redacted_thinking" });
110
+ } else if (block.type === "search_result") {
111
+ blocks.push({
112
+ type: "search_result",
113
+ query: block.query ?? "",
114
+ });
115
+ } else if (block.type === "text" && block.text) {
116
+ blocks.push({ type: "text", text: block.text });
117
+ }
118
+ }
119
+ return { type: msg.type, blocks };
120
+ }
121
+
122
+ // 2) system / compact_boundary 消息:上下文压缩事件
123
+ if (msg.type === "system" && msg.subtype === "compact_boundary") {
124
+ const meta = msg.compact_metadata;
125
+ if (!meta) return null;
126
+ return {
127
+ type: "system",
128
+ blocks: [
129
+ {
130
+ type: "compact_boundary",
131
+ trigger: meta.trigger ?? "auto",
132
+ pre_tokens: meta.pre_tokens ?? 0,
133
+ post_tokens: meta.post_tokens,
134
+ },
135
+ ],
136
+ };
137
+ }
138
+
139
+ // 3) 其他消息类型:跳过
140
+ return null;
141
+ }
142
+
143
+ // ---------------------------------------------------------------------------
144
+ // 适配器实现(私有类,仅通过工厂函数暴露)
145
+ // ---------------------------------------------------------------------------
146
+
147
+ class ClaudeAdapter implements ToolAdapter {
148
+ readonly displayName = "Claude";
149
+ readonly sessionDescPrefix = "Claude Session:";
150
+ private model: string;
151
+ private effort: string;
152
+ private isDefault: (value: string) => boolean;
153
+
154
+ constructor(options: ClaudeAdapterOptions) {
155
+ this.model = options.model;
156
+ this.effort = options.effort;
157
+ this.isDefault = options.isDefault;
158
+ }
159
+
160
+ async createSession(cwd: string): Promise<CreateSessionResult> {
161
+ const sessionOpts = buildSessionOptions(
162
+ cwd,
163
+ this.model,
164
+ this.effort,
165
+ this.isDefault,
166
+ );
167
+ const session = unstable_v2_createSession(sessionOpts as any);
168
+
169
+ await session.send("ok");
170
+
171
+ const stream = session.stream();
172
+ const first = await stream.next();
173
+
174
+ if (first.done || !(first.value as SdkMessageLike)?.session_id) {
175
+ session.close();
176
+ throw new Error("No session ID in Claude init event");
177
+ }
178
+
179
+ const sessionId = (first.value as SdkMessageLike).session_id!;
180
+
181
+ // 后台消费剩余的 stream(必须:否则 SDK 内部缓冲可能阻塞)
182
+ (async () => {
183
+ try {
184
+ for await (const _msg of stream) {
185
+ // 静默消费
186
+ }
187
+ } catch {
188
+ // stream 异常不阻塞主流程
189
+ } finally {
190
+ session.close();
191
+ }
192
+ })();
193
+
194
+ return { sessionId };
195
+ }
196
+
197
+ async *prompt(
198
+ sessionId: string,
199
+ userText: string,
200
+ cwd: string,
201
+ signal?: AbortSignal,
202
+ ): AsyncIterable<UnifiedStreamMessage> {
203
+ const sessionOpts = buildSessionOptions(
204
+ cwd,
205
+ this.model,
206
+ this.effort,
207
+ this.isDefault,
208
+ );
209
+ const session = unstable_v2_resumeSession(
210
+ sessionId,
211
+ sessionOpts as any,
212
+ );
213
+
214
+ await session.send(userText);
215
+
216
+ const stream = session.stream();
217
+
218
+ try {
219
+ for await (const msg of stream) {
220
+ if (signal?.aborted) break;
221
+ const normalized = normalizeSdkMessage(
222
+ msg as unknown as SdkMessageLike,
223
+ );
224
+ if (normalized) yield normalized;
225
+ }
226
+ } finally {
227
+ session.close();
228
+ }
229
+ }
230
+
231
+ async getSessionInfo(
232
+ sessionId: string,
233
+ ): Promise<SessionInfo | undefined> {
234
+ const info = await sdkGetSessionInfo(sessionId);
235
+ if (!info) return undefined;
236
+ return {
237
+ sessionId: info.sessionId,
238
+ cwd: info.cwd,
239
+ summary: info.summary,
240
+ lastModified: info.lastModified,
241
+ };
242
+ }
243
+
244
+ async closeSession(_sessionId: string): Promise<void> {
245
+ // Claude SDK 在 stream 结束后自动关闭 session,此处为 no-op
246
+ }
247
+ }
248
+
249
+ // ---------------------------------------------------------------------------
250
+ // 工厂函数
251
+ // ---------------------------------------------------------------------------
252
+
253
+ export function createClaudeAdapter(
254
+ options: ClaudeAdapterOptions,
255
+ ): ToolAdapter {
256
+ return new ClaudeAdapter(options);
257
+ }
package/src/config.ts CHANGED
@@ -62,6 +62,9 @@ export const CLAUDE_MODEL = process.env.CHATCCC_ANTHROPIC_MODEL?.trim() || "defa
62
62
 
63
63
  export const CLAUDE_EFFORT = process.env.CHATCCC_ANTHROPIC_EFFORT?.trim() || "default";
64
64
 
65
+ /** AI 工具选择:claude | cursor | codex(未设置时默认 claude) */
66
+ export const AI_TOOL = process.env.CHATCCC_AI_TOOL?.trim().toLowerCase() || "claude";
67
+
65
68
  // 新建会话的默认工作路径(/cd 命令设置,持久化到本地文件)
66
69
  // 该路径仅影响通过 /new 新建的 Claude 会话,不影响已有会话的 resume。
67
70
  export const DEFAULT_CWD_FILE = join(PROJECT_ROOT, ".claude", "working_dir.txt");
@@ -224,4 +227,4 @@ export function explainMissingFeishuCredentialsAndExit(): never {
224
227
  process.exit(1);
225
228
  }
226
229
 
227
- export const SESSION_DESC_PREFIX = "Claude Session:";
230
+ export let SESSION_DESC_PREFIX: string = "Claude Session:";
package/src/index.ts CHANGED
@@ -22,7 +22,6 @@
22
22
  */
23
23
 
24
24
  import { spawn } from "node:child_process";
25
- import { getSessionInfo } from "@anthropic-ai/claude-agent-sdk";
26
25
  import { readdir, stat } from "node:fs/promises";
27
26
  import { resolve, dirname, basename } from "node:path";
28
27
 
@@ -79,6 +78,8 @@ import {
79
78
  resetState,
80
79
  resumeAndPrompt,
81
80
  sessionInfoMap,
81
+ initAdapter,
82
+ getAdapter,
82
83
  } from "./session.ts";
83
84
 
84
85
  // ---------------------------------------------------------------------------
@@ -190,7 +191,7 @@ async function handleCommand(text: string, chatId: string, openId: string, msgTi
190
191
  const chatInfo = await getChatInfo(cdToken, chatId);
191
192
  const sid = extractSessionId(chatInfo.description);
192
193
  if (sid) {
193
- const info = await getSessionInfo(sid);
194
+ const info = await getAdapter().getSessionInfo(sid);
194
195
  sessionCwd = info?.cwd;
195
196
  }
196
197
  } catch { /* 非会话群或获取失败,不显示 */ }
@@ -648,6 +649,7 @@ async function main(): Promise<void> {
648
649
  });
649
650
 
650
651
  if (USE_LOCAL) {
652
+ initAdapter();
651
653
  console.log(`\n[启动 6/7] 本地区 relay 模式:正在连接 ${LOCAL_RELAY_URL} …`);
652
654
  console.log(" 若失败:请先在 SDK 模式下启动主进程,或确认本机中继已在该地址监听。");
653
655
  let localRelayOpened = false;
@@ -693,12 +695,13 @@ async function main(): Promise<void> {
693
695
  });
694
696
  } else {
695
697
  resetState();
698
+ initAdapter();
696
699
 
697
700
  const wsClient = new WSClient({
698
701
  appId: APP_ID,
699
702
  appSecret: APP_SECRET,
700
- onReady: () => resetState(),
701
- onReconnected: () => resetState(),
703
+ onReady: () => { resetState(); initAdapter(); },
704
+ onReconnected: () => { resetState(); initAdapter(); },
702
705
  });
703
706
 
704
707
  console.log(`\n[启动 6/7] 飞书长连接:正在通过 SDK 建立 WebSocket …`);