chatccc 0.2.3 → 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.
- package/package.json +6 -3
- package/src/__tests__/adapter-interface.test.ts +152 -0
- package/src/__tests__/cards.test.ts +297 -0
- package/src/__tests__/claude-adapter.test.ts +529 -0
- package/src/__tests__/session.test.ts +296 -0
- package/src/adapters/adapter-interface.ts +127 -0
- package/src/adapters/claude-adapter.ts +257 -0
- package/src/cards.ts +21 -19
- package/src/config.ts +4 -1
- package/src/index.ts +12 -9
- package/src/session.ts +450 -455
|
@@ -0,0 +1,296 @@
|
|
|
1
|
+
import { describe, it, expect, beforeEach } from "vitest";
|
|
2
|
+
import {
|
|
3
|
+
chatSessionMap,
|
|
4
|
+
sessionInfoMap,
|
|
5
|
+
processedMessages,
|
|
6
|
+
MAX_PROCESSED,
|
|
7
|
+
resetState,
|
|
8
|
+
getSessionStatus,
|
|
9
|
+
getAllSessionsStatus,
|
|
10
|
+
accumulateBlockContent,
|
|
11
|
+
} from "../session.ts";
|
|
12
|
+
import type { AccumulatorState } from "../session.ts";
|
|
13
|
+
import type { UnifiedBlock } from "../adapters/adapter-interface.ts";
|
|
14
|
+
|
|
15
|
+
// Helper to create a mock active session entry
|
|
16
|
+
function mockActiveSession(chatId: string, overrides: Partial<{
|
|
17
|
+
accumulatedContent: string;
|
|
18
|
+
finalText: string;
|
|
19
|
+
stopped: boolean;
|
|
20
|
+
}> = {}) {
|
|
21
|
+
chatSessionMap.set(chatId, {
|
|
22
|
+
gen: 1,
|
|
23
|
+
close: () => {},
|
|
24
|
+
cardId: null,
|
|
25
|
+
stopped: overrides.stopped ?? false,
|
|
26
|
+
accumulatedContent: overrides.accumulatedContent ?? "thinking...",
|
|
27
|
+
finalText: overrides.finalText ?? "",
|
|
28
|
+
spinnerTimer: null,
|
|
29
|
+
msgTimestamp: Date.now(),
|
|
30
|
+
sequence: 0,
|
|
31
|
+
cardBusy: false,
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function mockSessionInfo(chatId: string, overrides: Partial<{
|
|
36
|
+
sessionId: string;
|
|
37
|
+
turnCount: number;
|
|
38
|
+
lastContextTokens: number;
|
|
39
|
+
startTime: number;
|
|
40
|
+
}> = {}) {
|
|
41
|
+
sessionInfoMap.set(chatId, {
|
|
42
|
+
sessionId: overrides.sessionId ?? "test-session-id",
|
|
43
|
+
turnCount: overrides.turnCount ?? 3,
|
|
44
|
+
lastContextTokens: overrides.lastContextTokens ?? 50000,
|
|
45
|
+
startTime: overrides.startTime ?? Date.now(),
|
|
46
|
+
model: "Claude Opus 4.7",
|
|
47
|
+
effort: "high",
|
|
48
|
+
});
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
describe("resetState", () => {
|
|
52
|
+
it("clears all maps and sets", () => {
|
|
53
|
+
chatSessionMap.set("chat1", {
|
|
54
|
+
gen: 1, close: () => {}, cardId: null, stopped: false,
|
|
55
|
+
accumulatedContent: "", finalText: "", spinnerTimer: null,
|
|
56
|
+
msgTimestamp: 0, sequence: 0, cardBusy: false,
|
|
57
|
+
});
|
|
58
|
+
sessionInfoMap.set("chat1", {
|
|
59
|
+
sessionId: "s1", turnCount: 1, lastContextTokens: 0,
|
|
60
|
+
startTime: 0, model: "", effort: "",
|
|
61
|
+
});
|
|
62
|
+
processedMessages.add("msg1");
|
|
63
|
+
|
|
64
|
+
resetState();
|
|
65
|
+
|
|
66
|
+
expect(chatSessionMap.size).toBe(0);
|
|
67
|
+
expect(sessionInfoMap.size).toBe(0);
|
|
68
|
+
expect(processedMessages.size).toBe(0);
|
|
69
|
+
});
|
|
70
|
+
});
|
|
71
|
+
|
|
72
|
+
describe("getSessionStatus", () => {
|
|
73
|
+
beforeEach(() => {
|
|
74
|
+
chatSessionMap.clear();
|
|
75
|
+
sessionInfoMap.clear();
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
it("returns null for unknown chatId", () => {
|
|
79
|
+
expect(getSessionStatus("nonexistent")).toBeNull();
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
it("returns status for idle session (info exists, no active session)", () => {
|
|
83
|
+
mockSessionInfo("chat1");
|
|
84
|
+
const status = getSessionStatus("chat1");
|
|
85
|
+
expect(status).not.toBeNull();
|
|
86
|
+
expect(status!.sessionId).toBe("test-session-id");
|
|
87
|
+
expect(status!.running).toBe(false);
|
|
88
|
+
expect(status!.turnCount).toBe(3);
|
|
89
|
+
expect(status!.accumulatedLength).toBe(0);
|
|
90
|
+
});
|
|
91
|
+
|
|
92
|
+
it("returns running=true for active session", () => {
|
|
93
|
+
mockSessionInfo("chat1");
|
|
94
|
+
mockActiveSession("chat1", { accumulatedContent: "thinking...", finalText: "reply" });
|
|
95
|
+
const status = getSessionStatus("chat1");
|
|
96
|
+
expect(status!.running).toBe(true);
|
|
97
|
+
expect(status!.accumulatedLength).toBe(16); // "thinking..."(11) + "reply"(5)
|
|
98
|
+
});
|
|
99
|
+
|
|
100
|
+
it("returns running=false for stopped session", () => {
|
|
101
|
+
mockSessionInfo("chat1");
|
|
102
|
+
mockActiveSession("chat1", { stopped: true });
|
|
103
|
+
const status = getSessionStatus("chat1");
|
|
104
|
+
expect(status!.running).toBe(false);
|
|
105
|
+
});
|
|
106
|
+
|
|
107
|
+
it("returns correct turnCount and other info fields", () => {
|
|
108
|
+
mockSessionInfo("chat1", { turnCount: 7, lastContextTokens: 100000 });
|
|
109
|
+
const status = getSessionStatus("chat1");
|
|
110
|
+
expect(status!.turnCount).toBe(7);
|
|
111
|
+
expect(status!.lastContextTokens).toBe(100000);
|
|
112
|
+
});
|
|
113
|
+
});
|
|
114
|
+
|
|
115
|
+
describe("getAllSessionsStatus", () => {
|
|
116
|
+
beforeEach(() => {
|
|
117
|
+
chatSessionMap.clear();
|
|
118
|
+
sessionInfoMap.clear();
|
|
119
|
+
});
|
|
120
|
+
|
|
121
|
+
it("returns empty array when no sessions", () => {
|
|
122
|
+
expect(getAllSessionsStatus()).toEqual([]);
|
|
123
|
+
});
|
|
124
|
+
|
|
125
|
+
it("returns statuses for all recorded sessions", () => {
|
|
126
|
+
mockSessionInfo("chat1", { sessionId: "s1" });
|
|
127
|
+
mockSessionInfo("chat2", { sessionId: "s2" });
|
|
128
|
+
mockActiveSession("chat1");
|
|
129
|
+
const result = getAllSessionsStatus();
|
|
130
|
+
expect(result).toHaveLength(2);
|
|
131
|
+
expect(result.find(r => r.chatId === "chat1")!.active).toBe(true);
|
|
132
|
+
expect(result.find(r => r.chatId === "chat2")!.active).toBe(false);
|
|
133
|
+
});
|
|
134
|
+
|
|
135
|
+
it("marks stopped sessions as not active", () => {
|
|
136
|
+
mockSessionInfo("chat1");
|
|
137
|
+
mockActiveSession("chat1", { stopped: true });
|
|
138
|
+
const result = getAllSessionsStatus();
|
|
139
|
+
expect(result[0].active).toBe(false);
|
|
140
|
+
});
|
|
141
|
+
});
|
|
142
|
+
|
|
143
|
+
describe("processedMessages dedup", () => {
|
|
144
|
+
it("supports add/has semantics", () => {
|
|
145
|
+
processedMessages.clear();
|
|
146
|
+
processedMessages.add("msg_001");
|
|
147
|
+
expect(processedMessages.has("msg_001")).toBe(true);
|
|
148
|
+
expect(processedMessages.has("msg_002")).toBe(false);
|
|
149
|
+
});
|
|
150
|
+
|
|
151
|
+
it("MAX_PROCESSED is defined", () => {
|
|
152
|
+
expect(MAX_PROCESSED).toBe(5000);
|
|
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
|
+
});
|
|
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
|
+
}
|