chatccc 0.2.122 → 0.2.123
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
CHANGED
|
@@ -1,442 +1,442 @@
|
|
|
1
|
-
import { describe, it, expect } from "vitest";
|
|
2
|
-
import { normalizeSdkMessage, createClaudeAdapter } from "../adapters/claude-adapter.ts";
|
|
3
|
-
import type { UnifiedStreamMessage } from "../adapters/adapter-interface.ts";
|
|
4
|
-
import type {
|
|
5
|
-
ClaudeSessionMeta,
|
|
6
|
-
ClaudeSessionMetaStore,
|
|
7
|
-
} from "../adapters/claude-session-meta-store.ts";
|
|
8
|
-
|
|
9
|
-
// ---------------------------------------------------------------------------
|
|
10
|
-
// 进程内内存版 meta store(测试用,避开磁盘 IO)
|
|
11
|
-
// ---------------------------------------------------------------------------
|
|
12
|
-
|
|
13
|
-
function createInMemoryMetaStore(
|
|
14
|
-
initial: Record<string, ClaudeSessionMeta> = {},
|
|
15
|
-
): ClaudeSessionMetaStore & { snapshot(): Record<string, ClaudeSessionMeta> } {
|
|
16
|
-
const map = new Map<string, ClaudeSessionMeta>(Object.entries(initial));
|
|
17
|
-
return {
|
|
18
|
-
async get(sid) {
|
|
19
|
-
return map.get(sid);
|
|
20
|
-
},
|
|
21
|
-
async set(sid, partial) {
|
|
22
|
-
const existing = map.get(sid);
|
|
23
|
-
const merged: { cwd?: string; model?: string } = { ...existing };
|
|
24
|
-
if (typeof partial.cwd === "string" && partial.cwd.length > 0) merged.cwd = partial.cwd;
|
|
25
|
-
if (typeof partial.model === "string" && partial.model.length > 0) merged.model = partial.model;
|
|
26
|
-
if (!merged.cwd) return;
|
|
27
|
-
map.set(sid, merged.model ? { cwd: merged.cwd, model: merged.model } : { cwd: merged.cwd });
|
|
28
|
-
},
|
|
29
|
-
snapshot() {
|
|
30
|
-
return Object.fromEntries(map);
|
|
31
|
-
},
|
|
32
|
-
};
|
|
33
|
-
}
|
|
34
|
-
|
|
35
|
-
// ---------------------------------------------------------------------------
|
|
36
|
-
// normalizeSdkMessage — 核心映射逻辑测试(纯函数,CLI 与 SDK 格式相同)
|
|
37
|
-
// ---------------------------------------------------------------------------
|
|
38
|
-
|
|
39
|
-
describe("normalizeSdkMessage", () => {
|
|
40
|
-
// --- assistant messages ---
|
|
41
|
-
|
|
42
|
-
it("normalizes assistant message with text block", () => {
|
|
43
|
-
const result = normalizeSdkMessage({
|
|
44
|
-
type: "assistant",
|
|
45
|
-
message: { content: [{ type: "text", text: "Hello world" }] },
|
|
46
|
-
});
|
|
47
|
-
expect(result).not.toBeNull();
|
|
48
|
-
expect(result!.type).toBe("assistant");
|
|
49
|
-
expect(result!.blocks).toEqual([{ type: "text", text: "Hello world" }]);
|
|
50
|
-
});
|
|
51
|
-
|
|
52
|
-
it("normalizes assistant message with thinking block", () => {
|
|
53
|
-
const result = normalizeSdkMessage({
|
|
54
|
-
type: "assistant",
|
|
55
|
-
message: { content: [{ type: "thinking", thinking: "Let me analyze..." }] },
|
|
56
|
-
});
|
|
57
|
-
expect(result).not.toBeNull();
|
|
58
|
-
expect(result!.blocks).toEqual([{ type: "thinking", thinking: "Let me analyze..." }]);
|
|
59
|
-
});
|
|
60
|
-
|
|
61
|
-
it("normalizes assistant message with tool_use block", () => {
|
|
62
|
-
const result = normalizeSdkMessage({
|
|
63
|
-
type: "assistant",
|
|
64
|
-
message: {
|
|
65
|
-
content: [{ type: "tool_use", name: "Read", input: { file_path: "/tmp/test.txt" } }],
|
|
66
|
-
},
|
|
67
|
-
});
|
|
68
|
-
expect(result).not.toBeNull();
|
|
69
|
-
expect(result!.blocks).toEqual([
|
|
70
|
-
{ type: "tool_use", name: "Read", input: { file_path: "/tmp/test.txt" } },
|
|
71
|
-
]);
|
|
72
|
-
});
|
|
73
|
-
|
|
74
|
-
it('uses "unknown" for tool_use without name', () => {
|
|
75
|
-
const result = normalizeSdkMessage({
|
|
76
|
-
type: "assistant",
|
|
77
|
-
message: { content: [{ type: "tool_use", input: { x: 1 } }] },
|
|
78
|
-
});
|
|
79
|
-
expect(result!.blocks[0]).toMatchObject({ type: "tool_use", name: "unknown" });
|
|
80
|
-
});
|
|
81
|
-
|
|
82
|
-
it("normalizes user message with tool_result block (success)", () => {
|
|
83
|
-
const result = normalizeSdkMessage({
|
|
84
|
-
type: "user",
|
|
85
|
-
message: {
|
|
86
|
-
content: [
|
|
87
|
-
{ type: "tool_result", tool_use_id: "abc123", content: "file content here", is_error: false },
|
|
88
|
-
],
|
|
89
|
-
},
|
|
90
|
-
});
|
|
91
|
-
expect(result).not.toBeNull();
|
|
92
|
-
expect(result!.type).toBe("user");
|
|
93
|
-
const block = result!.blocks[0] as any;
|
|
94
|
-
expect(block.type).toBe("tool_result");
|
|
95
|
-
expect(block.tool_use_id).toBe("abc123");
|
|
96
|
-
expect(block.content).toBe("file content here");
|
|
97
|
-
expect(block.is_error).toBe(false);
|
|
98
|
-
});
|
|
99
|
-
|
|
100
|
-
it("normalizes user message with tool_result block (error)", () => {
|
|
101
|
-
const result = normalizeSdkMessage({
|
|
102
|
-
type: "user",
|
|
103
|
-
message: {
|
|
104
|
-
content: [
|
|
105
|
-
{ type: "tool_result", tool_use_id: "err456", content: "permission denied", is_error: true },
|
|
106
|
-
],
|
|
107
|
-
},
|
|
108
|
-
});
|
|
109
|
-
expect(result!.blocks[0]).toMatchObject({
|
|
110
|
-
type: "tool_result",
|
|
111
|
-
tool_use_id: "err456",
|
|
112
|
-
is_error: true,
|
|
113
|
-
});
|
|
114
|
-
});
|
|
115
|
-
|
|
116
|
-
it("normalizes tool_result with array content", () => {
|
|
117
|
-
const content = [{ type: "text", text: "line 1" }, { type: "text", text: "line 2" }];
|
|
118
|
-
const result = normalizeSdkMessage({
|
|
119
|
-
type: "user",
|
|
120
|
-
message: { content: [{ type: "tool_result", tool_use_id: "arr", content }] },
|
|
121
|
-
});
|
|
122
|
-
expect(result!.blocks[0]).toMatchObject({
|
|
123
|
-
type: "tool_result",
|
|
124
|
-
tool_use_id: "arr",
|
|
125
|
-
});
|
|
126
|
-
expect((result!.blocks[0] as any).content).toEqual(content);
|
|
127
|
-
});
|
|
128
|
-
|
|
129
|
-
it("skips text blocks in user messages (replayed input from --replay-user-messages)", () => {
|
|
130
|
-
// user 消息中的 text block 来自 --replay-user-messages 重放的用户输入
|
|
131
|
-
// (含内嵌的 IM skill prompt),不应出现在最终回复中
|
|
132
|
-
const result = normalizeSdkMessage({
|
|
133
|
-
type: "user",
|
|
134
|
-
message: {
|
|
135
|
-
content: [
|
|
136
|
-
{ type: "text", text: "[ChatCCC IM skill: feishu-skill]\n...[/ChatCCC IM skill: feishu-skill]" },
|
|
137
|
-
{ type: "tool_result", tool_use_id: "abc", content: "result" },
|
|
138
|
-
],
|
|
139
|
-
},
|
|
140
|
-
});
|
|
141
|
-
expect(result).not.toBeNull();
|
|
142
|
-
expect(result!.type).toBe("user");
|
|
143
|
-
// text block 应被跳过,只保留 tool_result
|
|
144
|
-
expect(result!.blocks).toHaveLength(1);
|
|
145
|
-
expect(result!.blocks[0]).toMatchObject({ type: "tool_result", tool_use_id: "abc" });
|
|
146
|
-
});
|
|
147
|
-
|
|
148
|
-
it("returns null for user message with only text blocks (all skipped)", () => {
|
|
149
|
-
// 纯 user text 消息(无 tool_result)→ 全部跳过,不产生有效 blocks
|
|
150
|
-
const result = normalizeSdkMessage({
|
|
151
|
-
type: "user",
|
|
152
|
-
message: {
|
|
153
|
-
content: [{ type: "text", text: "some replayed user input" }],
|
|
154
|
-
},
|
|
155
|
-
});
|
|
156
|
-
// 此时 blocks 为空,但消息本身仍有 type,返回非 null 以保持流完整性
|
|
157
|
-
// 调用方 accumulateBlockContent 对空 blocks 是 no-op
|
|
158
|
-
expect(result).not.toBeNull();
|
|
159
|
-
expect(result!.blocks).toEqual([]);
|
|
160
|
-
});
|
|
161
|
-
|
|
162
|
-
it("normalizes redacted_thinking block", () => {
|
|
163
|
-
const result = normalizeSdkMessage({
|
|
164
|
-
type: "assistant",
|
|
165
|
-
message: { content: [{ type: "redacted_thinking" }] },
|
|
166
|
-
});
|
|
167
|
-
expect(result!.blocks).toEqual([{ type: "redacted_thinking" }]);
|
|
168
|
-
});
|
|
169
|
-
|
|
170
|
-
it("normalizes search_result block", () => {
|
|
171
|
-
const result = normalizeSdkMessage({
|
|
172
|
-
type: "assistant",
|
|
173
|
-
message: {
|
|
174
|
-
content: [{ type: "search_result", query: "TypeScript best practices" }],
|
|
175
|
-
},
|
|
176
|
-
});
|
|
177
|
-
expect(result!.blocks).toEqual([
|
|
178
|
-
{ type: "search_result", query: "TypeScript best practices" },
|
|
179
|
-
]);
|
|
180
|
-
});
|
|
181
|
-
|
|
182
|
-
it("normalizes search_result without query (empty string)", () => {
|
|
183
|
-
const result = normalizeSdkMessage({
|
|
184
|
-
type: "assistant",
|
|
185
|
-
message: { content: [{ type: "search_result" }] },
|
|
186
|
-
});
|
|
187
|
-
expect(result!.blocks).toEqual([{ type: "search_result", query: "" }]);
|
|
188
|
-
});
|
|
189
|
-
|
|
190
|
-
// --- system messages ---
|
|
191
|
-
|
|
192
|
-
it("normalizes system compact_boundary message", () => {
|
|
193
|
-
const result = normalizeSdkMessage({
|
|
194
|
-
type: "system",
|
|
195
|
-
subtype: "compact_boundary",
|
|
196
|
-
compact_metadata: {
|
|
197
|
-
trigger: "auto",
|
|
198
|
-
pre_tokens: 15000,
|
|
199
|
-
post_tokens: 8000,
|
|
200
|
-
},
|
|
201
|
-
});
|
|
202
|
-
expect(result).not.toBeNull();
|
|
203
|
-
expect(result!.type).toBe("system");
|
|
204
|
-
expect(result!.blocks).toEqual([
|
|
205
|
-
{ type: "compact_boundary", trigger: "auto", pre_tokens: 15000, post_tokens: 8000 },
|
|
206
|
-
]);
|
|
207
|
-
});
|
|
208
|
-
|
|
209
|
-
it("normalizes compact_boundary with manual trigger", () => {
|
|
210
|
-
const result = normalizeSdkMessage({
|
|
211
|
-
type: "system",
|
|
212
|
-
subtype: "compact_boundary",
|
|
213
|
-
compact_metadata: { trigger: "manual", pre_tokens: 20000 },
|
|
214
|
-
});
|
|
215
|
-
expect(result!.blocks).toEqual([
|
|
216
|
-
{ type: "compact_boundary", trigger: "manual", pre_tokens: 20000, post_tokens: undefined },
|
|
217
|
-
]);
|
|
218
|
-
});
|
|
219
|
-
|
|
220
|
-
it("normalizes compact_boundary without post_tokens", () => {
|
|
221
|
-
const result = normalizeSdkMessage({
|
|
222
|
-
type: "system",
|
|
223
|
-
subtype: "compact_boundary",
|
|
224
|
-
compact_metadata: { trigger: "auto", pre_tokens: 10000 },
|
|
225
|
-
});
|
|
226
|
-
expect(result!.blocks).toEqual([
|
|
227
|
-
{ type: "compact_boundary", trigger: "auto", pre_tokens: 10000, post_tokens: undefined },
|
|
228
|
-
]);
|
|
229
|
-
});
|
|
230
|
-
|
|
231
|
-
// --- mixed blocks ---
|
|
232
|
-
|
|
233
|
-
it("normalizes message with multiple block types mixed", () => {
|
|
234
|
-
const result = normalizeSdkMessage({
|
|
235
|
-
type: "assistant",
|
|
236
|
-
message: {
|
|
237
|
-
content: [
|
|
238
|
-
{ type: "thinking", thinking: "Hmm..." },
|
|
239
|
-
{ type: "tool_use", name: "Grep", input: { pattern: "foo" } },
|
|
240
|
-
{ type: "text", text: "Found it." },
|
|
241
|
-
],
|
|
242
|
-
},
|
|
243
|
-
});
|
|
244
|
-
expect(result).not.toBeNull();
|
|
245
|
-
expect(result!.blocks).toHaveLength(3);
|
|
246
|
-
expect(result!.blocks[0]).toEqual({ type: "thinking", thinking: "Hmm..." });
|
|
247
|
-
expect(result!.blocks[1]).toEqual({ type: "tool_use", name: "Grep", input: { pattern: "foo" } });
|
|
248
|
-
expect(result!.blocks[2]).toEqual({ type: "text", text: "Found it." });
|
|
249
|
-
});
|
|
250
|
-
|
|
251
|
-
// --- edge cases ---
|
|
252
|
-
|
|
253
|
-
it("skips unknown block types", () => {
|
|
254
|
-
const result = normalizeSdkMessage({
|
|
255
|
-
type: "assistant",
|
|
256
|
-
message: {
|
|
257
|
-
content: [
|
|
258
|
-
{ type: "unknown_type", data: "whatever" },
|
|
259
|
-
{ type: "text", text: "still here" },
|
|
260
|
-
],
|
|
261
|
-
},
|
|
262
|
-
});
|
|
263
|
-
expect(result!.blocks).toHaveLength(1);
|
|
264
|
-
expect(result!.blocks[0]).toEqual({ type: "text", text: "still here" });
|
|
265
|
-
});
|
|
266
|
-
|
|
267
|
-
it("returns null for non-assistant/non-user/non-system messages", () => {
|
|
268
|
-
expect(
|
|
269
|
-
normalizeSdkMessage({ type: "result", subtype: "success" }),
|
|
270
|
-
).toBeNull();
|
|
271
|
-
expect(
|
|
272
|
-
normalizeSdkMessage({ type: "stream_event" }),
|
|
273
|
-
).toBeNull();
|
|
274
|
-
expect(
|
|
275
|
-
normalizeSdkMessage({ type: "status" }),
|
|
276
|
-
).toBeNull();
|
|
277
|
-
});
|
|
278
|
-
|
|
279
|
-
it("returns null for system message without compact_boundary subtype", () => {
|
|
280
|
-
expect(
|
|
281
|
-
normalizeSdkMessage({ type: "system", subtype: "init" }),
|
|
282
|
-
).toBeNull();
|
|
283
|
-
expect(
|
|
284
|
-
normalizeSdkMessage({ type: "system", subtype: "notification" }),
|
|
285
|
-
).toBeNull();
|
|
286
|
-
});
|
|
287
|
-
|
|
288
|
-
it("returns message with empty blocks for content=[ ]", () => {
|
|
289
|
-
const result = normalizeSdkMessage({
|
|
290
|
-
type: "assistant",
|
|
291
|
-
message: { content: [] },
|
|
292
|
-
});
|
|
293
|
-
expect(result).not.toBeNull();
|
|
294
|
-
expect(result!.blocks).toEqual([]);
|
|
295
|
-
});
|
|
296
|
-
|
|
297
|
-
it("returns null for message without content", () => {
|
|
298
|
-
const result = normalizeSdkMessage({
|
|
299
|
-
type: "assistant",
|
|
300
|
-
message: {},
|
|
301
|
-
});
|
|
302
|
-
expect(result).toBeNull();
|
|
303
|
-
});
|
|
304
|
-
|
|
305
|
-
it("returns null for message with null content array", () => {
|
|
306
|
-
const result = normalizeSdkMessage({
|
|
307
|
-
type: "assistant",
|
|
308
|
-
message: { content: undefined as any },
|
|
309
|
-
});
|
|
310
|
-
expect(result).toBeNull();
|
|
311
|
-
});
|
|
312
|
-
|
|
313
|
-
it("returns null for compact_boundary without metadata", () => {
|
|
314
|
-
const result = normalizeSdkMessage({
|
|
315
|
-
type: "system",
|
|
316
|
-
subtype: "compact_boundary",
|
|
317
|
-
});
|
|
318
|
-
expect(result).toBeNull();
|
|
319
|
-
});
|
|
320
|
-
|
|
321
|
-
it("skips thinking block with empty thinking string", () => {
|
|
322
|
-
const result = normalizeSdkMessage({
|
|
323
|
-
type: "assistant",
|
|
324
|
-
message: { content: [{ type: "thinking", thinking: "" }] },
|
|
325
|
-
});
|
|
326
|
-
expect(result!.blocks).toEqual([]);
|
|
327
|
-
});
|
|
328
|
-
|
|
329
|
-
it("skips text block with empty text string", () => {
|
|
330
|
-
const result = normalizeSdkMessage({
|
|
331
|
-
type: "assistant",
|
|
332
|
-
message: { content: [{ type: "text", text: "" }] },
|
|
333
|
-
});
|
|
334
|
-
expect(result!.blocks).toEqual([]);
|
|
335
|
-
});
|
|
336
|
-
|
|
337
|
-
it("handles message with undefined type gracefully", () => {
|
|
338
|
-
const result = normalizeSdkMessage({
|
|
339
|
-
message: { content: [{ type: "text", text: "orphan" }] },
|
|
340
|
-
});
|
|
341
|
-
expect(result).toBeNull();
|
|
342
|
-
});
|
|
343
|
-
});
|
|
344
|
-
|
|
345
|
-
// ---------------------------------------------------------------------------
|
|
346
|
-
// createClaudeAdapter — 工厂函数 + getSessionInfo / closeSession 测试
|
|
347
|
-
// ---------------------------------------------------------------------------
|
|
348
|
-
|
|
349
|
-
describe("createClaudeAdapter", () => {
|
|
350
|
-
it("returns adapter with correct displayName and sessionDescPrefix", () => {
|
|
351
|
-
const adapter = createClaudeAdapter({
|
|
352
|
-
model: "claude-sonnet-4-6",
|
|
353
|
-
effort: "high",
|
|
354
|
-
isEmpty: (v) => v.trim() === "",
|
|
355
|
-
});
|
|
356
|
-
expect(adapter.displayName).toBe("Claude Code");
|
|
357
|
-
expect(adapter.sessionDescPrefix).toBe("Claude Code Session:");
|
|
358
|
-
});
|
|
359
|
-
|
|
360
|
-
it("closeSession does not throw", async () => {
|
|
361
|
-
const adapter = createClaudeAdapter({
|
|
362
|
-
model: "claude-sonnet-4-6",
|
|
363
|
-
effort: "high",
|
|
364
|
-
isEmpty: () => false,
|
|
365
|
-
});
|
|
366
|
-
await expect(adapter.closeSession("any-sid")).resolves.toBeUndefined();
|
|
367
|
-
});
|
|
368
|
-
|
|
369
|
-
// -------------------------------------------------------------------------
|
|
370
|
-
// getSessionInfo 行为契约
|
|
371
|
-
// - cwd 决定 /git 是否可用
|
|
372
|
-
// - model 用于 /state、/sessions 显示
|
|
373
|
-
// -------------------------------------------------------------------------
|
|
374
|
-
|
|
375
|
-
it("getSessionInfo: store 中无该 sessionId 时只返回 sessionId", async () => {
|
|
376
|
-
const store = createInMemoryMetaStore();
|
|
377
|
-
const adapter = createClaudeAdapter({
|
|
378
|
-
model: "",
|
|
379
|
-
effort: "",
|
|
380
|
-
isEmpty: () => false,
|
|
381
|
-
metaStore: store,
|
|
382
|
-
});
|
|
383
|
-
const info = await adapter.getSessionInfo("unknown-sid");
|
|
384
|
-
expect(info).toEqual({ sessionId: "unknown-sid" });
|
|
385
|
-
expect(info?.cwd).toBeUndefined();
|
|
386
|
-
expect(info?.model).toBeUndefined();
|
|
387
|
-
});
|
|
388
|
-
|
|
389
|
-
it("getSessionInfo: store 仅有 cwd 时返回 cwd,model 仍为 undefined", async () => {
|
|
390
|
-
const store = createInMemoryMetaStore({ "sid-known": { cwd: "F:/proj/Foo" } });
|
|
391
|
-
const adapter = createClaudeAdapter({
|
|
392
|
-
model: "",
|
|
393
|
-
effort: "",
|
|
394
|
-
isEmpty: () => false,
|
|
395
|
-
metaStore: store,
|
|
396
|
-
});
|
|
397
|
-
const info = await adapter.getSessionInfo("sid-known");
|
|
398
|
-
expect(info).toEqual({ sessionId: "sid-known", cwd: "F:/proj/Foo" });
|
|
399
|
-
expect(info?.model).toBeUndefined();
|
|
400
|
-
});
|
|
401
|
-
|
|
402
|
-
it("getSessionInfo: store 同时有 cwd + model 时一并返回", async () => {
|
|
403
|
-
const store = createInMemoryMetaStore({
|
|
404
|
-
"sid-known": { cwd: "F:/proj/Foo", model: "claude-sonnet-4-6" },
|
|
405
|
-
});
|
|
406
|
-
const adapter = createClaudeAdapter({
|
|
407
|
-
model: "",
|
|
408
|
-
effort: "",
|
|
409
|
-
isEmpty: () => false,
|
|
410
|
-
metaStore: store,
|
|
411
|
-
});
|
|
412
|
-
const info = await adapter.getSessionInfo("sid-known");
|
|
413
|
-
expect(info).toEqual({
|
|
414
|
-
sessionId: "sid-known",
|
|
415
|
-
cwd: "F:/proj/Foo",
|
|
416
|
-
model: "claude-sonnet-4-6",
|
|
417
|
-
});
|
|
418
|
-
});
|
|
419
|
-
|
|
420
|
-
it("getSessionInfo: 不同 sessionId 互不影响", async () => {
|
|
421
|
-
const store = createInMemoryMetaStore({
|
|
422
|
-
"sid-A": { cwd: "/a", model: "mA" },
|
|
423
|
-
"sid-B": { cwd: "/b" },
|
|
424
|
-
});
|
|
425
|
-
const adapter = createClaudeAdapter({
|
|
426
|
-
model: "",
|
|
427
|
-
effort: "",
|
|
428
|
-
isEmpty: () => false,
|
|
429
|
-
metaStore: store,
|
|
430
|
-
});
|
|
431
|
-
expect(await adapter.getSessionInfo("sid-A")).toEqual({
|
|
432
|
-
sessionId: "sid-A",
|
|
433
|
-
cwd: "/a",
|
|
434
|
-
model: "mA",
|
|
435
|
-
});
|
|
436
|
-
expect(await adapter.getSessionInfo("sid-B")).toEqual({
|
|
437
|
-
sessionId: "sid-B",
|
|
438
|
-
cwd: "/b",
|
|
439
|
-
});
|
|
440
|
-
expect(await adapter.getSessionInfo("sid-C")).toEqual({ sessionId: "sid-C" });
|
|
441
|
-
});
|
|
1
|
+
import { describe, it, expect } from "vitest";
|
|
2
|
+
import { normalizeSdkMessage, createClaudeAdapter } from "../adapters/claude-adapter.ts";
|
|
3
|
+
import type { UnifiedStreamMessage } from "../adapters/adapter-interface.ts";
|
|
4
|
+
import type {
|
|
5
|
+
ClaudeSessionMeta,
|
|
6
|
+
ClaudeSessionMetaStore,
|
|
7
|
+
} from "../adapters/claude-session-meta-store.ts";
|
|
8
|
+
|
|
9
|
+
// ---------------------------------------------------------------------------
|
|
10
|
+
// 进程内内存版 meta store(测试用,避开磁盘 IO)
|
|
11
|
+
// ---------------------------------------------------------------------------
|
|
12
|
+
|
|
13
|
+
function createInMemoryMetaStore(
|
|
14
|
+
initial: Record<string, ClaudeSessionMeta> = {},
|
|
15
|
+
): ClaudeSessionMetaStore & { snapshot(): Record<string, ClaudeSessionMeta> } {
|
|
16
|
+
const map = new Map<string, ClaudeSessionMeta>(Object.entries(initial));
|
|
17
|
+
return {
|
|
18
|
+
async get(sid) {
|
|
19
|
+
return map.get(sid);
|
|
20
|
+
},
|
|
21
|
+
async set(sid, partial) {
|
|
22
|
+
const existing = map.get(sid);
|
|
23
|
+
const merged: { cwd?: string; model?: string } = { ...existing };
|
|
24
|
+
if (typeof partial.cwd === "string" && partial.cwd.length > 0) merged.cwd = partial.cwd;
|
|
25
|
+
if (typeof partial.model === "string" && partial.model.length > 0) merged.model = partial.model;
|
|
26
|
+
if (!merged.cwd) return;
|
|
27
|
+
map.set(sid, merged.model ? { cwd: merged.cwd, model: merged.model } : { cwd: merged.cwd });
|
|
28
|
+
},
|
|
29
|
+
snapshot() {
|
|
30
|
+
return Object.fromEntries(map);
|
|
31
|
+
},
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
// ---------------------------------------------------------------------------
|
|
36
|
+
// normalizeSdkMessage — 核心映射逻辑测试(纯函数,CLI 与 SDK 格式相同)
|
|
37
|
+
// ---------------------------------------------------------------------------
|
|
38
|
+
|
|
39
|
+
describe("normalizeSdkMessage", () => {
|
|
40
|
+
// --- assistant messages ---
|
|
41
|
+
|
|
42
|
+
it("normalizes assistant message with text block", () => {
|
|
43
|
+
const result = normalizeSdkMessage({
|
|
44
|
+
type: "assistant",
|
|
45
|
+
message: { content: [{ type: "text", text: "Hello world" }] },
|
|
46
|
+
});
|
|
47
|
+
expect(result).not.toBeNull();
|
|
48
|
+
expect(result!.type).toBe("assistant");
|
|
49
|
+
expect(result!.blocks).toEqual([{ type: "text", text: "Hello world" }]);
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
it("normalizes assistant message with thinking block", () => {
|
|
53
|
+
const result = normalizeSdkMessage({
|
|
54
|
+
type: "assistant",
|
|
55
|
+
message: { content: [{ type: "thinking", thinking: "Let me analyze..." }] },
|
|
56
|
+
});
|
|
57
|
+
expect(result).not.toBeNull();
|
|
58
|
+
expect(result!.blocks).toEqual([{ type: "thinking", thinking: "Let me analyze..." }]);
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
it("normalizes assistant message with tool_use block", () => {
|
|
62
|
+
const result = normalizeSdkMessage({
|
|
63
|
+
type: "assistant",
|
|
64
|
+
message: {
|
|
65
|
+
content: [{ type: "tool_use", name: "Read", input: { file_path: "/tmp/test.txt" } }],
|
|
66
|
+
},
|
|
67
|
+
});
|
|
68
|
+
expect(result).not.toBeNull();
|
|
69
|
+
expect(result!.blocks).toEqual([
|
|
70
|
+
{ type: "tool_use", name: "Read", input: { file_path: "/tmp/test.txt" } },
|
|
71
|
+
]);
|
|
72
|
+
});
|
|
73
|
+
|
|
74
|
+
it('uses "unknown" for tool_use without name', () => {
|
|
75
|
+
const result = normalizeSdkMessage({
|
|
76
|
+
type: "assistant",
|
|
77
|
+
message: { content: [{ type: "tool_use", input: { x: 1 } }] },
|
|
78
|
+
});
|
|
79
|
+
expect(result!.blocks[0]).toMatchObject({ type: "tool_use", name: "unknown" });
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
it("normalizes user message with tool_result block (success)", () => {
|
|
83
|
+
const result = normalizeSdkMessage({
|
|
84
|
+
type: "user",
|
|
85
|
+
message: {
|
|
86
|
+
content: [
|
|
87
|
+
{ type: "tool_result", tool_use_id: "abc123", content: "file content here", is_error: false },
|
|
88
|
+
],
|
|
89
|
+
},
|
|
90
|
+
});
|
|
91
|
+
expect(result).not.toBeNull();
|
|
92
|
+
expect(result!.type).toBe("user");
|
|
93
|
+
const block = result!.blocks[0] as any;
|
|
94
|
+
expect(block.type).toBe("tool_result");
|
|
95
|
+
expect(block.tool_use_id).toBe("abc123");
|
|
96
|
+
expect(block.content).toBe("file content here");
|
|
97
|
+
expect(block.is_error).toBe(false);
|
|
98
|
+
});
|
|
99
|
+
|
|
100
|
+
it("normalizes user message with tool_result block (error)", () => {
|
|
101
|
+
const result = normalizeSdkMessage({
|
|
102
|
+
type: "user",
|
|
103
|
+
message: {
|
|
104
|
+
content: [
|
|
105
|
+
{ type: "tool_result", tool_use_id: "err456", content: "permission denied", is_error: true },
|
|
106
|
+
],
|
|
107
|
+
},
|
|
108
|
+
});
|
|
109
|
+
expect(result!.blocks[0]).toMatchObject({
|
|
110
|
+
type: "tool_result",
|
|
111
|
+
tool_use_id: "err456",
|
|
112
|
+
is_error: true,
|
|
113
|
+
});
|
|
114
|
+
});
|
|
115
|
+
|
|
116
|
+
it("normalizes tool_result with array content", () => {
|
|
117
|
+
const content = [{ type: "text", text: "line 1" }, { type: "text", text: "line 2" }];
|
|
118
|
+
const result = normalizeSdkMessage({
|
|
119
|
+
type: "user",
|
|
120
|
+
message: { content: [{ type: "tool_result", tool_use_id: "arr", content }] },
|
|
121
|
+
});
|
|
122
|
+
expect(result!.blocks[0]).toMatchObject({
|
|
123
|
+
type: "tool_result",
|
|
124
|
+
tool_use_id: "arr",
|
|
125
|
+
});
|
|
126
|
+
expect((result!.blocks[0] as any).content).toEqual(content);
|
|
127
|
+
});
|
|
128
|
+
|
|
129
|
+
it("skips text blocks in user messages (replayed input from --replay-user-messages)", () => {
|
|
130
|
+
// user 消息中的 text block 来自 --replay-user-messages 重放的用户输入
|
|
131
|
+
// (含内嵌的 IM skill prompt),不应出现在最终回复中
|
|
132
|
+
const result = normalizeSdkMessage({
|
|
133
|
+
type: "user",
|
|
134
|
+
message: {
|
|
135
|
+
content: [
|
|
136
|
+
{ type: "text", text: "[ChatCCC IM skill: feishu-skill]\n...[/ChatCCC IM skill: feishu-skill]" },
|
|
137
|
+
{ type: "tool_result", tool_use_id: "abc", content: "result" },
|
|
138
|
+
],
|
|
139
|
+
},
|
|
140
|
+
});
|
|
141
|
+
expect(result).not.toBeNull();
|
|
142
|
+
expect(result!.type).toBe("user");
|
|
143
|
+
// text block 应被跳过,只保留 tool_result
|
|
144
|
+
expect(result!.blocks).toHaveLength(1);
|
|
145
|
+
expect(result!.blocks[0]).toMatchObject({ type: "tool_result", tool_use_id: "abc" });
|
|
146
|
+
});
|
|
147
|
+
|
|
148
|
+
it("returns null for user message with only text blocks (all skipped)", () => {
|
|
149
|
+
// 纯 user text 消息(无 tool_result)→ 全部跳过,不产生有效 blocks
|
|
150
|
+
const result = normalizeSdkMessage({
|
|
151
|
+
type: "user",
|
|
152
|
+
message: {
|
|
153
|
+
content: [{ type: "text", text: "some replayed user input" }],
|
|
154
|
+
},
|
|
155
|
+
});
|
|
156
|
+
// 此时 blocks 为空,但消息本身仍有 type,返回非 null 以保持流完整性
|
|
157
|
+
// 调用方 accumulateBlockContent 对空 blocks 是 no-op
|
|
158
|
+
expect(result).not.toBeNull();
|
|
159
|
+
expect(result!.blocks).toEqual([]);
|
|
160
|
+
});
|
|
161
|
+
|
|
162
|
+
it("normalizes redacted_thinking block", () => {
|
|
163
|
+
const result = normalizeSdkMessage({
|
|
164
|
+
type: "assistant",
|
|
165
|
+
message: { content: [{ type: "redacted_thinking" }] },
|
|
166
|
+
});
|
|
167
|
+
expect(result!.blocks).toEqual([{ type: "redacted_thinking" }]);
|
|
168
|
+
});
|
|
169
|
+
|
|
170
|
+
it("normalizes search_result block", () => {
|
|
171
|
+
const result = normalizeSdkMessage({
|
|
172
|
+
type: "assistant",
|
|
173
|
+
message: {
|
|
174
|
+
content: [{ type: "search_result", query: "TypeScript best practices" }],
|
|
175
|
+
},
|
|
176
|
+
});
|
|
177
|
+
expect(result!.blocks).toEqual([
|
|
178
|
+
{ type: "search_result", query: "TypeScript best practices" },
|
|
179
|
+
]);
|
|
180
|
+
});
|
|
181
|
+
|
|
182
|
+
it("normalizes search_result without query (empty string)", () => {
|
|
183
|
+
const result = normalizeSdkMessage({
|
|
184
|
+
type: "assistant",
|
|
185
|
+
message: { content: [{ type: "search_result" }] },
|
|
186
|
+
});
|
|
187
|
+
expect(result!.blocks).toEqual([{ type: "search_result", query: "" }]);
|
|
188
|
+
});
|
|
189
|
+
|
|
190
|
+
// --- system messages ---
|
|
191
|
+
|
|
192
|
+
it("normalizes system compact_boundary message", () => {
|
|
193
|
+
const result = normalizeSdkMessage({
|
|
194
|
+
type: "system",
|
|
195
|
+
subtype: "compact_boundary",
|
|
196
|
+
compact_metadata: {
|
|
197
|
+
trigger: "auto",
|
|
198
|
+
pre_tokens: 15000,
|
|
199
|
+
post_tokens: 8000,
|
|
200
|
+
},
|
|
201
|
+
});
|
|
202
|
+
expect(result).not.toBeNull();
|
|
203
|
+
expect(result!.type).toBe("system");
|
|
204
|
+
expect(result!.blocks).toEqual([
|
|
205
|
+
{ type: "compact_boundary", trigger: "auto", pre_tokens: 15000, post_tokens: 8000 },
|
|
206
|
+
]);
|
|
207
|
+
});
|
|
208
|
+
|
|
209
|
+
it("normalizes compact_boundary with manual trigger", () => {
|
|
210
|
+
const result = normalizeSdkMessage({
|
|
211
|
+
type: "system",
|
|
212
|
+
subtype: "compact_boundary",
|
|
213
|
+
compact_metadata: { trigger: "manual", pre_tokens: 20000 },
|
|
214
|
+
});
|
|
215
|
+
expect(result!.blocks).toEqual([
|
|
216
|
+
{ type: "compact_boundary", trigger: "manual", pre_tokens: 20000, post_tokens: undefined },
|
|
217
|
+
]);
|
|
218
|
+
});
|
|
219
|
+
|
|
220
|
+
it("normalizes compact_boundary without post_tokens", () => {
|
|
221
|
+
const result = normalizeSdkMessage({
|
|
222
|
+
type: "system",
|
|
223
|
+
subtype: "compact_boundary",
|
|
224
|
+
compact_metadata: { trigger: "auto", pre_tokens: 10000 },
|
|
225
|
+
});
|
|
226
|
+
expect(result!.blocks).toEqual([
|
|
227
|
+
{ type: "compact_boundary", trigger: "auto", pre_tokens: 10000, post_tokens: undefined },
|
|
228
|
+
]);
|
|
229
|
+
});
|
|
230
|
+
|
|
231
|
+
// --- mixed blocks ---
|
|
232
|
+
|
|
233
|
+
it("normalizes message with multiple block types mixed", () => {
|
|
234
|
+
const result = normalizeSdkMessage({
|
|
235
|
+
type: "assistant",
|
|
236
|
+
message: {
|
|
237
|
+
content: [
|
|
238
|
+
{ type: "thinking", thinking: "Hmm..." },
|
|
239
|
+
{ type: "tool_use", name: "Grep", input: { pattern: "foo" } },
|
|
240
|
+
{ type: "text", text: "Found it." },
|
|
241
|
+
],
|
|
242
|
+
},
|
|
243
|
+
});
|
|
244
|
+
expect(result).not.toBeNull();
|
|
245
|
+
expect(result!.blocks).toHaveLength(3);
|
|
246
|
+
expect(result!.blocks[0]).toEqual({ type: "thinking", thinking: "Hmm..." });
|
|
247
|
+
expect(result!.blocks[1]).toEqual({ type: "tool_use", name: "Grep", input: { pattern: "foo" } });
|
|
248
|
+
expect(result!.blocks[2]).toEqual({ type: "text", text: "Found it." });
|
|
249
|
+
});
|
|
250
|
+
|
|
251
|
+
// --- edge cases ---
|
|
252
|
+
|
|
253
|
+
it("skips unknown block types", () => {
|
|
254
|
+
const result = normalizeSdkMessage({
|
|
255
|
+
type: "assistant",
|
|
256
|
+
message: {
|
|
257
|
+
content: [
|
|
258
|
+
{ type: "unknown_type", data: "whatever" },
|
|
259
|
+
{ type: "text", text: "still here" },
|
|
260
|
+
],
|
|
261
|
+
},
|
|
262
|
+
});
|
|
263
|
+
expect(result!.blocks).toHaveLength(1);
|
|
264
|
+
expect(result!.blocks[0]).toEqual({ type: "text", text: "still here" });
|
|
265
|
+
});
|
|
266
|
+
|
|
267
|
+
it("returns null for non-assistant/non-user/non-system messages", () => {
|
|
268
|
+
expect(
|
|
269
|
+
normalizeSdkMessage({ type: "result", subtype: "success" }),
|
|
270
|
+
).toBeNull();
|
|
271
|
+
expect(
|
|
272
|
+
normalizeSdkMessage({ type: "stream_event" }),
|
|
273
|
+
).toBeNull();
|
|
274
|
+
expect(
|
|
275
|
+
normalizeSdkMessage({ type: "status" }),
|
|
276
|
+
).toBeNull();
|
|
277
|
+
});
|
|
278
|
+
|
|
279
|
+
it("returns null for system message without compact_boundary subtype", () => {
|
|
280
|
+
expect(
|
|
281
|
+
normalizeSdkMessage({ type: "system", subtype: "init" }),
|
|
282
|
+
).toBeNull();
|
|
283
|
+
expect(
|
|
284
|
+
normalizeSdkMessage({ type: "system", subtype: "notification" }),
|
|
285
|
+
).toBeNull();
|
|
286
|
+
});
|
|
287
|
+
|
|
288
|
+
it("returns message with empty blocks for content=[ ]", () => {
|
|
289
|
+
const result = normalizeSdkMessage({
|
|
290
|
+
type: "assistant",
|
|
291
|
+
message: { content: [] },
|
|
292
|
+
});
|
|
293
|
+
expect(result).not.toBeNull();
|
|
294
|
+
expect(result!.blocks).toEqual([]);
|
|
295
|
+
});
|
|
296
|
+
|
|
297
|
+
it("returns null for message without content", () => {
|
|
298
|
+
const result = normalizeSdkMessage({
|
|
299
|
+
type: "assistant",
|
|
300
|
+
message: {},
|
|
301
|
+
});
|
|
302
|
+
expect(result).toBeNull();
|
|
303
|
+
});
|
|
304
|
+
|
|
305
|
+
it("returns null for message with null content array", () => {
|
|
306
|
+
const result = normalizeSdkMessage({
|
|
307
|
+
type: "assistant",
|
|
308
|
+
message: { content: undefined as any },
|
|
309
|
+
});
|
|
310
|
+
expect(result).toBeNull();
|
|
311
|
+
});
|
|
312
|
+
|
|
313
|
+
it("returns null for compact_boundary without metadata", () => {
|
|
314
|
+
const result = normalizeSdkMessage({
|
|
315
|
+
type: "system",
|
|
316
|
+
subtype: "compact_boundary",
|
|
317
|
+
});
|
|
318
|
+
expect(result).toBeNull();
|
|
319
|
+
});
|
|
320
|
+
|
|
321
|
+
it("skips thinking block with empty thinking string", () => {
|
|
322
|
+
const result = normalizeSdkMessage({
|
|
323
|
+
type: "assistant",
|
|
324
|
+
message: { content: [{ type: "thinking", thinking: "" }] },
|
|
325
|
+
});
|
|
326
|
+
expect(result!.blocks).toEqual([]);
|
|
327
|
+
});
|
|
328
|
+
|
|
329
|
+
it("skips text block with empty text string", () => {
|
|
330
|
+
const result = normalizeSdkMessage({
|
|
331
|
+
type: "assistant",
|
|
332
|
+
message: { content: [{ type: "text", text: "" }] },
|
|
333
|
+
});
|
|
334
|
+
expect(result!.blocks).toEqual([]);
|
|
335
|
+
});
|
|
336
|
+
|
|
337
|
+
it("handles message with undefined type gracefully", () => {
|
|
338
|
+
const result = normalizeSdkMessage({
|
|
339
|
+
message: { content: [{ type: "text", text: "orphan" }] },
|
|
340
|
+
});
|
|
341
|
+
expect(result).toBeNull();
|
|
342
|
+
});
|
|
343
|
+
});
|
|
344
|
+
|
|
345
|
+
// ---------------------------------------------------------------------------
|
|
346
|
+
// createClaudeAdapter — 工厂函数 + getSessionInfo / closeSession 测试
|
|
347
|
+
// ---------------------------------------------------------------------------
|
|
348
|
+
|
|
349
|
+
describe("createClaudeAdapter", () => {
|
|
350
|
+
it("returns adapter with correct displayName and sessionDescPrefix", () => {
|
|
351
|
+
const adapter = createClaudeAdapter({
|
|
352
|
+
model: "claude-sonnet-4-6",
|
|
353
|
+
effort: "high",
|
|
354
|
+
isEmpty: (v) => v.trim() === "",
|
|
355
|
+
});
|
|
356
|
+
expect(adapter.displayName).toBe("Claude Code");
|
|
357
|
+
expect(adapter.sessionDescPrefix).toBe("Claude Code Session:");
|
|
358
|
+
});
|
|
359
|
+
|
|
360
|
+
it("closeSession does not throw", async () => {
|
|
361
|
+
const adapter = createClaudeAdapter({
|
|
362
|
+
model: "claude-sonnet-4-6",
|
|
363
|
+
effort: "high",
|
|
364
|
+
isEmpty: () => false,
|
|
365
|
+
});
|
|
366
|
+
await expect(adapter.closeSession("any-sid")).resolves.toBeUndefined();
|
|
367
|
+
});
|
|
368
|
+
|
|
369
|
+
// -------------------------------------------------------------------------
|
|
370
|
+
// getSessionInfo 行为契约
|
|
371
|
+
// - cwd 决定 /git 是否可用
|
|
372
|
+
// - model 用于 /state、/sessions 显示
|
|
373
|
+
// -------------------------------------------------------------------------
|
|
374
|
+
|
|
375
|
+
it("getSessionInfo: store 中无该 sessionId 时只返回 sessionId", async () => {
|
|
376
|
+
const store = createInMemoryMetaStore();
|
|
377
|
+
const adapter = createClaudeAdapter({
|
|
378
|
+
model: "",
|
|
379
|
+
effort: "",
|
|
380
|
+
isEmpty: () => false,
|
|
381
|
+
metaStore: store,
|
|
382
|
+
});
|
|
383
|
+
const info = await adapter.getSessionInfo("unknown-sid");
|
|
384
|
+
expect(info).toEqual({ sessionId: "unknown-sid" });
|
|
385
|
+
expect(info?.cwd).toBeUndefined();
|
|
386
|
+
expect(info?.model).toBeUndefined();
|
|
387
|
+
});
|
|
388
|
+
|
|
389
|
+
it("getSessionInfo: store 仅有 cwd 时返回 cwd,model 仍为 undefined", async () => {
|
|
390
|
+
const store = createInMemoryMetaStore({ "sid-known": { cwd: "F:/proj/Foo" } });
|
|
391
|
+
const adapter = createClaudeAdapter({
|
|
392
|
+
model: "",
|
|
393
|
+
effort: "",
|
|
394
|
+
isEmpty: () => false,
|
|
395
|
+
metaStore: store,
|
|
396
|
+
});
|
|
397
|
+
const info = await adapter.getSessionInfo("sid-known");
|
|
398
|
+
expect(info).toEqual({ sessionId: "sid-known", cwd: "F:/proj/Foo" });
|
|
399
|
+
expect(info?.model).toBeUndefined();
|
|
400
|
+
});
|
|
401
|
+
|
|
402
|
+
it("getSessionInfo: store 同时有 cwd + model 时一并返回", async () => {
|
|
403
|
+
const store = createInMemoryMetaStore({
|
|
404
|
+
"sid-known": { cwd: "F:/proj/Foo", model: "claude-sonnet-4-6" },
|
|
405
|
+
});
|
|
406
|
+
const adapter = createClaudeAdapter({
|
|
407
|
+
model: "",
|
|
408
|
+
effort: "",
|
|
409
|
+
isEmpty: () => false,
|
|
410
|
+
metaStore: store,
|
|
411
|
+
});
|
|
412
|
+
const info = await adapter.getSessionInfo("sid-known");
|
|
413
|
+
expect(info).toEqual({
|
|
414
|
+
sessionId: "sid-known",
|
|
415
|
+
cwd: "F:/proj/Foo",
|
|
416
|
+
model: "claude-sonnet-4-6",
|
|
417
|
+
});
|
|
418
|
+
});
|
|
419
|
+
|
|
420
|
+
it("getSessionInfo: 不同 sessionId 互不影响", async () => {
|
|
421
|
+
const store = createInMemoryMetaStore({
|
|
422
|
+
"sid-A": { cwd: "/a", model: "mA" },
|
|
423
|
+
"sid-B": { cwd: "/b" },
|
|
424
|
+
});
|
|
425
|
+
const adapter = createClaudeAdapter({
|
|
426
|
+
model: "",
|
|
427
|
+
effort: "",
|
|
428
|
+
isEmpty: () => false,
|
|
429
|
+
metaStore: store,
|
|
430
|
+
});
|
|
431
|
+
expect(await adapter.getSessionInfo("sid-A")).toEqual({
|
|
432
|
+
sessionId: "sid-A",
|
|
433
|
+
cwd: "/a",
|
|
434
|
+
model: "mA",
|
|
435
|
+
});
|
|
436
|
+
expect(await adapter.getSessionInfo("sid-B")).toEqual({
|
|
437
|
+
sessionId: "sid-B",
|
|
438
|
+
cwd: "/b",
|
|
439
|
+
});
|
|
440
|
+
expect(await adapter.getSessionInfo("sid-C")).toEqual({ sessionId: "sid-C" });
|
|
441
|
+
});
|
|
442
442
|
});
|
|
@@ -285,7 +285,7 @@ function buildCliArgs(
|
|
|
285
285
|
"--setting-sources", "user,project,local",
|
|
286
286
|
"--permission-mode", permMode,
|
|
287
287
|
...(skipPermissions ? ["--dangerously-skip-permissions"] : []),
|
|
288
|
-
"--settings", "{\"maxTurns\":0}",
|
|
288
|
+
"--settings", "{\"maxTurns\":0,\"autoCompact\":{\"enabled\":true}}",
|
|
289
289
|
];
|
|
290
290
|
|
|
291
291
|
if (!isEmpty(model)) args.push("--model", model);
|
|
@@ -1,141 +1,141 @@
|
|
|
1
|
-
// =============================================================================
|
|
2
|
-
// resource-monitor.ts — CLI 进程资源监控(CPU + 内存)
|
|
3
|
-
// =============================================================================
|
|
4
|
-
// 对所有 chatccc 启动的 CLI 进程持续监控 CPU 和内存占用。
|
|
5
|
-
// 若连续 3 分钟两项指标均无变化,判定为僵死,发出 "stuck" 事件。
|
|
6
|
-
// =============================================================================
|
|
7
|
-
|
|
8
|
-
import { exec } from "node:child_process";
|
|
9
|
-
import { EventEmitter } from "node:events";
|
|
10
|
-
|
|
11
|
-
const CHECK_INTERVAL_MS = 30_000; // 30 秒检查一次
|
|
12
|
-
const STUCK_THRESHOLD = 6; // 连续 6 次无变化 = 3 分钟
|
|
13
|
-
|
|
14
|
-
interface ProcessSnapshot {
|
|
15
|
-
cpu: number;
|
|
16
|
-
memory: number;
|
|
17
|
-
unchangedCount: number;
|
|
18
|
-
}
|
|
19
|
-
|
|
20
|
-
interface TrackedProcess {
|
|
21
|
-
pid: number;
|
|
22
|
-
sessionId: string;
|
|
23
|
-
snapshot: ProcessSnapshot;
|
|
24
|
-
}
|
|
25
|
-
|
|
26
|
-
export const resourceMonitor = new EventEmitter();
|
|
27
|
-
|
|
28
|
-
const tracked = new Map<number, TrackedProcess>();
|
|
29
|
-
|
|
30
|
-
let timer: ReturnType<typeof setInterval> | null = null;
|
|
31
|
-
|
|
32
|
-
function startIfNeeded(): void {
|
|
33
|
-
if (timer) return;
|
|
34
|
-
timer = setInterval(checkAll, CHECK_INTERVAL_MS);
|
|
35
|
-
timer.unref?.();
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
function stopIfIdle(): void {
|
|
39
|
-
if (tracked.size > 0) return;
|
|
40
|
-
if (timer) { clearInterval(timer); timer = null; }
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
export function registerProcess(pid: number, sessionId: string): void {
|
|
44
|
-
tracked.set(pid, { pid, sessionId, snapshot: { cpu: -1, memory: -1, unchangedCount: 0 } });
|
|
45
|
-
startIfNeeded();
|
|
46
|
-
}
|
|
47
|
-
|
|
48
|
-
export function unregisterProcess(pid: number): void {
|
|
49
|
-
tracked.delete(pid);
|
|
50
|
-
stopIfIdle();
|
|
51
|
-
}
|
|
52
|
-
|
|
53
|
-
// ---------------------------------------------------------------------------
|
|
54
|
-
// 批量查询进程指标(Windows PowerShell)
|
|
55
|
-
// ---------------------------------------------------------------------------
|
|
56
|
-
|
|
57
|
-
function execPowerShell(script: string, timeoutMs: number): Promise<string> {
|
|
58
|
-
return new Promise((resolve, reject) => {
|
|
59
|
-
exec(
|
|
60
|
-
`powershell -NoProfile -Command "${script}"`,
|
|
61
|
-
{ timeout: timeoutMs, windowsHide: true },
|
|
62
|
-
(err, stdout) => {
|
|
63
|
-
if (err) reject(err);
|
|
64
|
-
else resolve(stdout);
|
|
65
|
-
},
|
|
66
|
-
);
|
|
67
|
-
});
|
|
68
|
-
}
|
|
69
|
-
|
|
70
|
-
async function getProcessMetrics(pids: number[]): Promise<Map<number, { cpu: number; memory: number }>> {
|
|
71
|
-
const result = new Map<number, { cpu: number; memory: number }>();
|
|
72
|
-
if (pids.length === 0) return result;
|
|
73
|
-
|
|
74
|
-
const psScript = `Get-Process -Id ${pids.join(",")} -ErrorAction SilentlyContinue | ForEach-Object { "$($_.Id)|$($_.CPU)|$($_.WorkingSet64)" }`;
|
|
75
|
-
|
|
76
|
-
try {
|
|
77
|
-
const stdout = await execPowerShell(psScript, 10_000);
|
|
78
|
-
for (const line of stdout.trim().split(/\r?\n/)) {
|
|
79
|
-
const trimmed = line.trim();
|
|
80
|
-
if (!trimmed) continue;
|
|
81
|
-
const [idStr, cpuStr, memStr] = trimmed.split("|");
|
|
82
|
-
const id = parseInt(idStr, 10);
|
|
83
|
-
const cpu = parseFloat(cpuStr);
|
|
84
|
-
const memory = parseInt(memStr, 10);
|
|
85
|
-
if (!isNaN(id) && !isNaN(cpu) && !isNaN(memory)) {
|
|
86
|
-
result.set(id, { cpu, memory });
|
|
87
|
-
}
|
|
88
|
-
}
|
|
89
|
-
} catch {
|
|
90
|
-
// PowerShell 查询失败时跳过本轮,下次重试
|
|
91
|
-
}
|
|
92
|
-
|
|
93
|
-
return result;
|
|
94
|
-
}
|
|
95
|
-
|
|
96
|
-
// ---------------------------------------------------------------------------
|
|
97
|
-
// 定时检查
|
|
98
|
-
// ---------------------------------------------------------------------------
|
|
99
|
-
|
|
100
|
-
async function checkAll(): Promise<void> {
|
|
101
|
-
if (tracked.size === 0) return;
|
|
102
|
-
|
|
103
|
-
const pids = [...tracked.keys()];
|
|
104
|
-
const metrics = await getProcessMetrics(pids);
|
|
105
|
-
|
|
106
|
-
for (const [pid, tp] of tracked) {
|
|
107
|
-
const m = metrics.get(pid);
|
|
108
|
-
if (!m) {
|
|
109
|
-
// 进程已不存在,停止追踪
|
|
110
|
-
tracked.delete(pid);
|
|
111
|
-
continue;
|
|
112
|
-
}
|
|
113
|
-
|
|
114
|
-
const prev = tp.snapshot;
|
|
115
|
-
const cpuChanged = m.cpu !== prev.cpu;
|
|
116
|
-
// 内存允许 ±1% 波动,避免正常抖动触发误判
|
|
117
|
-
const memTolerance = prev.memory > 0 ? Math.max(prev.memory * 0.01, 1024 * 1024) : 1024 * 1024;
|
|
118
|
-
const memChanged = Math.abs(m.memory - prev.memory) > memTolerance;
|
|
119
|
-
|
|
120
|
-
if (!cpuChanged && !memChanged) {
|
|
121
|
-
tp.snapshot.unchangedCount++;
|
|
122
|
-
if (tp.snapshot.unchangedCount >= STUCK_THRESHOLD) {
|
|
123
|
-
const idleMinutes = Math.round(
|
|
124
|
-
(tp.snapshot.unchangedCount * CHECK_INTERVAL_MS) / 60_000,
|
|
125
|
-
);
|
|
126
|
-
resourceMonitor.emit("stuck", {
|
|
127
|
-
pid: tp.pid,
|
|
128
|
-
sessionId: tp.sessionId,
|
|
129
|
-
idleMinutes,
|
|
130
|
-
});
|
|
131
|
-
tracked.delete(pid);
|
|
132
|
-
}
|
|
133
|
-
} else {
|
|
134
|
-
tp.snapshot.unchangedCount = 0;
|
|
135
|
-
}
|
|
136
|
-
tp.snapshot.cpu = m.cpu;
|
|
137
|
-
tp.snapshot.memory = m.memory;
|
|
138
|
-
}
|
|
139
|
-
|
|
140
|
-
stopIfIdle();
|
|
1
|
+
// =============================================================================
|
|
2
|
+
// resource-monitor.ts — CLI 进程资源监控(CPU + 内存)
|
|
3
|
+
// =============================================================================
|
|
4
|
+
// 对所有 chatccc 启动的 CLI 进程持续监控 CPU 和内存占用。
|
|
5
|
+
// 若连续 3 分钟两项指标均无变化,判定为僵死,发出 "stuck" 事件。
|
|
6
|
+
// =============================================================================
|
|
7
|
+
|
|
8
|
+
import { exec } from "node:child_process";
|
|
9
|
+
import { EventEmitter } from "node:events";
|
|
10
|
+
|
|
11
|
+
const CHECK_INTERVAL_MS = 30_000; // 30 秒检查一次
|
|
12
|
+
const STUCK_THRESHOLD = 6; // 连续 6 次无变化 = 3 分钟
|
|
13
|
+
|
|
14
|
+
interface ProcessSnapshot {
|
|
15
|
+
cpu: number;
|
|
16
|
+
memory: number;
|
|
17
|
+
unchangedCount: number;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
interface TrackedProcess {
|
|
21
|
+
pid: number;
|
|
22
|
+
sessionId: string;
|
|
23
|
+
snapshot: ProcessSnapshot;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export const resourceMonitor = new EventEmitter();
|
|
27
|
+
|
|
28
|
+
const tracked = new Map<number, TrackedProcess>();
|
|
29
|
+
|
|
30
|
+
let timer: ReturnType<typeof setInterval> | null = null;
|
|
31
|
+
|
|
32
|
+
function startIfNeeded(): void {
|
|
33
|
+
if (timer) return;
|
|
34
|
+
timer = setInterval(checkAll, CHECK_INTERVAL_MS);
|
|
35
|
+
timer.unref?.();
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function stopIfIdle(): void {
|
|
39
|
+
if (tracked.size > 0) return;
|
|
40
|
+
if (timer) { clearInterval(timer); timer = null; }
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export function registerProcess(pid: number, sessionId: string): void {
|
|
44
|
+
tracked.set(pid, { pid, sessionId, snapshot: { cpu: -1, memory: -1, unchangedCount: 0 } });
|
|
45
|
+
startIfNeeded();
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export function unregisterProcess(pid: number): void {
|
|
49
|
+
tracked.delete(pid);
|
|
50
|
+
stopIfIdle();
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
// ---------------------------------------------------------------------------
|
|
54
|
+
// 批量查询进程指标(Windows PowerShell)
|
|
55
|
+
// ---------------------------------------------------------------------------
|
|
56
|
+
|
|
57
|
+
function execPowerShell(script: string, timeoutMs: number): Promise<string> {
|
|
58
|
+
return new Promise((resolve, reject) => {
|
|
59
|
+
exec(
|
|
60
|
+
`powershell -NoProfile -Command "${script}"`,
|
|
61
|
+
{ timeout: timeoutMs, windowsHide: true },
|
|
62
|
+
(err, stdout) => {
|
|
63
|
+
if (err) reject(err);
|
|
64
|
+
else resolve(stdout);
|
|
65
|
+
},
|
|
66
|
+
);
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
async function getProcessMetrics(pids: number[]): Promise<Map<number, { cpu: number; memory: number }>> {
|
|
71
|
+
const result = new Map<number, { cpu: number; memory: number }>();
|
|
72
|
+
if (pids.length === 0) return result;
|
|
73
|
+
|
|
74
|
+
const psScript = `Get-Process -Id ${pids.join(",")} -ErrorAction SilentlyContinue | ForEach-Object { "$($_.Id)|$($_.CPU)|$($_.WorkingSet64)" }`;
|
|
75
|
+
|
|
76
|
+
try {
|
|
77
|
+
const stdout = await execPowerShell(psScript, 10_000);
|
|
78
|
+
for (const line of stdout.trim().split(/\r?\n/)) {
|
|
79
|
+
const trimmed = line.trim();
|
|
80
|
+
if (!trimmed) continue;
|
|
81
|
+
const [idStr, cpuStr, memStr] = trimmed.split("|");
|
|
82
|
+
const id = parseInt(idStr, 10);
|
|
83
|
+
const cpu = parseFloat(cpuStr);
|
|
84
|
+
const memory = parseInt(memStr, 10);
|
|
85
|
+
if (!isNaN(id) && !isNaN(cpu) && !isNaN(memory)) {
|
|
86
|
+
result.set(id, { cpu, memory });
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
} catch {
|
|
90
|
+
// PowerShell 查询失败时跳过本轮,下次重试
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
return result;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
// ---------------------------------------------------------------------------
|
|
97
|
+
// 定时检查
|
|
98
|
+
// ---------------------------------------------------------------------------
|
|
99
|
+
|
|
100
|
+
async function checkAll(): Promise<void> {
|
|
101
|
+
if (tracked.size === 0) return;
|
|
102
|
+
|
|
103
|
+
const pids = [...tracked.keys()];
|
|
104
|
+
const metrics = await getProcessMetrics(pids);
|
|
105
|
+
|
|
106
|
+
for (const [pid, tp] of tracked) {
|
|
107
|
+
const m = metrics.get(pid);
|
|
108
|
+
if (!m) {
|
|
109
|
+
// 进程已不存在,停止追踪
|
|
110
|
+
tracked.delete(pid);
|
|
111
|
+
continue;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
const prev = tp.snapshot;
|
|
115
|
+
const cpuChanged = m.cpu !== prev.cpu;
|
|
116
|
+
// 内存允许 ±1% 波动,避免正常抖动触发误判
|
|
117
|
+
const memTolerance = prev.memory > 0 ? Math.max(prev.memory * 0.01, 1024 * 1024) : 1024 * 1024;
|
|
118
|
+
const memChanged = Math.abs(m.memory - prev.memory) > memTolerance;
|
|
119
|
+
|
|
120
|
+
if (!cpuChanged && !memChanged) {
|
|
121
|
+
tp.snapshot.unchangedCount++;
|
|
122
|
+
if (tp.snapshot.unchangedCount >= STUCK_THRESHOLD) {
|
|
123
|
+
const idleMinutes = Math.round(
|
|
124
|
+
(tp.snapshot.unchangedCount * CHECK_INTERVAL_MS) / 60_000,
|
|
125
|
+
);
|
|
126
|
+
resourceMonitor.emit("stuck", {
|
|
127
|
+
pid: tp.pid,
|
|
128
|
+
sessionId: tp.sessionId,
|
|
129
|
+
idleMinutes,
|
|
130
|
+
});
|
|
131
|
+
tracked.delete(pid);
|
|
132
|
+
}
|
|
133
|
+
} else {
|
|
134
|
+
tp.snapshot.unchangedCount = 0;
|
|
135
|
+
}
|
|
136
|
+
tp.snapshot.cpu = m.cpu;
|
|
137
|
+
tp.snapshot.memory = m.memory;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
stopIfIdle();
|
|
141
141
|
}
|