chatccc 0.2.231 → 0.2.232

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.
Files changed (127) hide show
  1. package/.agents/skills/create-chatccc-feishu-app/SKILL.md +85 -85
  2. package/.claude/skills/create-chatccc-feishu-app/SKILL.md +85 -85
  3. package/.cursor/skills/create-chatccc-feishu-app/SKILL.md +85 -85
  4. package/README.md +90 -90
  5. package/agent-prompts/claude_specific.md +45 -45
  6. package/agent-prompts/codex_specific.md +2 -2
  7. package/agent-prompts/cursor_specific.md +13 -13
  8. package/bin/cccagent.mjs +17 -17
  9. package/im-skills/feishu-skill/receive-send-file.md +63 -63
  10. package/im-skills/feishu-skill/receive-send-image.md +24 -24
  11. package/im-skills/feishu-skill/skill.md +3 -3
  12. package/im-skills/wechat-file-skill/receive-send-file.md +38 -38
  13. package/im-skills/wechat-file-skill/send-file.mjs +83 -83
  14. package/im-skills/wechat-file-skill/skill.md +10 -10
  15. package/im-skills/wechat-image-skill/skill.md +10 -10
  16. package/im-skills/wechat-video-skill/receive-send-video.md +38 -38
  17. package/im-skills/wechat-video-skill/send-video.mjs +79 -79
  18. package/im-skills/wechat-video-skill/skill.md +10 -10
  19. package/package.json +1 -1
  20. package/scripts/postinstall-sharp-check.mjs +58 -58
  21. package/src/__tests__/agent-activity.test.ts +86 -86
  22. package/src/__tests__/agent-delegate-task-rpc.test.ts +165 -165
  23. package/src/__tests__/agent-reload-config-rpc.test.ts +99 -99
  24. package/src/__tests__/builtin-chat-session.test.ts +449 -393
  25. package/src/__tests__/builtin-cli-json.test.ts +39 -39
  26. package/src/__tests__/builtin-config.test.ts +26 -26
  27. package/src/__tests__/builtin-context.test.ts +319 -202
  28. package/src/__tests__/builtin-file-tools.test.ts +240 -240
  29. package/src/__tests__/builtin-permissions.test.ts +211 -211
  30. package/src/__tests__/builtin-session-search.test.ts +228 -0
  31. package/src/__tests__/builtin-session-select.test.ts +116 -116
  32. package/src/__tests__/builtin-sigint.test.ts +56 -56
  33. package/src/__tests__/builtin-skills.test.ts +284 -284
  34. package/src/__tests__/builtin-web-tools.test.ts +220 -220
  35. package/src/__tests__/card-action-routing.test.ts +18 -18
  36. package/src/__tests__/cardkit.test.ts +60 -60
  37. package/src/__tests__/ccc-adapter.test.ts +170 -170
  38. package/src/__tests__/chatgpt-subscription-rpc.test.ts +89 -89
  39. package/src/__tests__/chatgpt-subscription.test.ts +135 -135
  40. package/src/__tests__/chrome-devtools-guard.test.ts +165 -165
  41. package/src/__tests__/claude-adapter.test.ts +614 -614
  42. package/src/__tests__/claude-raw-stream-log.test.ts +87 -87
  43. package/src/__tests__/codex-adapter.test.ts +58 -58
  44. package/src/__tests__/codex-raw-stream-log.test.ts +170 -170
  45. package/src/__tests__/codex-reset-actions.test.ts +146 -146
  46. package/src/__tests__/cursor-adapter.test.ts +268 -268
  47. package/src/__tests__/feishu-api.test.ts +60 -60
  48. package/src/__tests__/feishu-avatar.test.ts +164 -164
  49. package/src/__tests__/feishu-message-ingress.test.ts +138 -138
  50. package/src/__tests__/feishu-platform.test.ts +22 -22
  51. package/src/__tests__/format-message.test.ts +47 -47
  52. package/src/__tests__/jsonl-stream.test.ts +79 -79
  53. package/src/__tests__/package-files.test.ts +24 -24
  54. package/src/__tests__/privacy.test.ts +198 -198
  55. package/src/__tests__/progress-reducer.test.ts +121 -121
  56. package/src/__tests__/raw-stream-log.test.ts +106 -106
  57. package/src/__tests__/response-stall.test.ts +49 -49
  58. package/src/__tests__/restart.test.ts +132 -132
  59. package/src/__tests__/session.test.ts +199 -199
  60. package/src/__tests__/shared-prefix.test.ts +36 -36
  61. package/src/__tests__/sim-platform.test.ts +16 -16
  62. package/src/__tests__/startup-lifecycle.test.ts +231 -231
  63. package/src/__tests__/stop-session.test.ts +34 -34
  64. package/src/__tests__/stream-state.test.ts +42 -42
  65. package/src/__tests__/terminal-error.test.ts +54 -54
  66. package/src/__tests__/terminal-renderer.test.ts +247 -247
  67. package/src/__tests__/update-command-guard.test.ts +144 -144
  68. package/src/__tests__/web-ui.test.ts +326 -326
  69. package/src/adapters/adapter-interface.ts +33 -33
  70. package/src/adapters/ccc-adapter.ts +141 -141
  71. package/src/adapters/claude-adapter.ts +620 -620
  72. package/src/adapters/claude-session-meta-store.ts +120 -120
  73. package/src/adapters/codex-adapter.ts +426 -426
  74. package/src/adapters/cursor-adapter.ts +681 -681
  75. package/src/adapters/jsonl-stream.ts +157 -157
  76. package/src/adapters/raw-stream-log.ts +124 -124
  77. package/src/adapters/resource-monitor.ts +140 -140
  78. package/src/agent-activity.ts +175 -175
  79. package/src/agent-delegate-task-rpc.ts +153 -153
  80. package/src/agent-delegate-task.ts +91 -91
  81. package/src/agent-reload-config-rpc.ts +34 -34
  82. package/src/agent-stop-stuck.ts +129 -129
  83. package/src/builtin/cli.ts +6 -0
  84. package/src/builtin/config.ts +84 -84
  85. package/src/builtin/context.ts +465 -391
  86. package/src/builtin/file-log.ts +38 -38
  87. package/src/builtin/file-tools.ts +34 -0
  88. package/src/builtin/index.ts +24 -23
  89. package/src/builtin/proc-tree-kill.ts +61 -61
  90. package/src/builtin/progress/cards-helpers.ts +76 -76
  91. package/src/builtin/progress/reducer.ts +113 -113
  92. package/src/builtin/progress/terminal-renderer.ts +294 -294
  93. package/src/builtin/progress/view.ts +77 -77
  94. package/src/builtin/raw-stream-log.ts +124 -124
  95. package/src/builtin/session-search.ts +363 -0
  96. package/src/builtin/session-select.ts +48 -48
  97. package/src/builtin/sigint.ts +50 -50
  98. package/src/builtin/skills.ts +205 -205
  99. package/src/builtin/web-tools.ts +313 -313
  100. package/src/card-action-routing.ts +14 -14
  101. package/src/chatgpt-subscription-rpc.ts +27 -27
  102. package/src/chatgpt-subscription.ts +299 -299
  103. package/src/chrome-devtools-guard.ts +318 -318
  104. package/src/codex-reset-actions.ts +184 -184
  105. package/src/feishu-api.ts +193 -193
  106. package/src/feishu-message-ingress.ts +195 -195
  107. package/src/feishu-platform.ts +20 -20
  108. package/src/format-message.ts +293 -293
  109. package/src/litellm-proxy.ts +374 -374
  110. package/src/orchestrator.ts +2494 -2494
  111. package/src/platform-adapter.ts +6 -6
  112. package/src/privacy.ts +118 -118
  113. package/src/progress/reducer.ts +113 -113
  114. package/src/progress/terminal-renderer.ts +294 -294
  115. package/src/progress/view.ts +77 -77
  116. package/src/response-stall.ts +28 -28
  117. package/src/runtime-reload.ts +34 -34
  118. package/src/session-chat-binding.ts +82 -82
  119. package/src/session-name.ts +8 -8
  120. package/src/session.ts +201 -201
  121. package/src/shared-prefix.ts +29 -29
  122. package/src/sim-platform.ts +20 -20
  123. package/src/startup-lifecycle.ts +250 -250
  124. package/src/stream-state.ts +21 -21
  125. package/src/terminal-error.ts +129 -129
  126. package/src/turn-cards.ts +117 -117
  127. package/src/update-command-guard.ts +165 -165
@@ -1,614 +1,614 @@
1
- import { describe, it, expect } from "vitest";
2
- import {
3
- normalizeSdkMessage,
4
- createClaudeAdapter,
5
- buildClaudePromptText,
6
- buildSdkEnv,
7
- } from "../adapters/claude-adapter.ts";
8
- import type { UnifiedStreamMessage } from "../adapters/adapter-interface.ts";
9
- import type {
10
- ClaudeSessionMeta,
11
- ClaudeSessionMetaStore,
12
- } from "../adapters/claude-session-meta-store.ts";
13
-
14
- // ---------------------------------------------------------------------------
15
- // 进程内内存版 meta store(测试用,避开磁盘 IO)
16
- // ---------------------------------------------------------------------------
17
-
18
- function createInMemoryMetaStore(
19
- initial: Record<string, ClaudeSessionMeta> = {},
20
- ): ClaudeSessionMetaStore & { snapshot(): Record<string, ClaudeSessionMeta> } {
21
- const map = new Map<string, ClaudeSessionMeta>(Object.entries(initial));
22
- return {
23
- async get(sid) {
24
- return map.get(sid);
25
- },
26
- async set(sid, partial) {
27
- const existing = map.get(sid);
28
- const merged: { cwd?: string; model?: string } = { ...existing };
29
- if (typeof partial.cwd === "string" && partial.cwd.length > 0) merged.cwd = partial.cwd;
30
- if (typeof partial.model === "string" && partial.model.length > 0) merged.model = partial.model;
31
- if (!merged.cwd) return;
32
- map.set(sid, merged.model ? { cwd: merged.cwd, model: merged.model } : { cwd: merged.cwd });
33
- },
34
- snapshot() {
35
- return Object.fromEntries(map);
36
- },
37
- };
38
- }
39
-
40
- // ---------------------------------------------------------------------------
41
- // normalizeSdkMessage — 核心映射逻辑测试(纯函数,CLI 与 SDK 格式相同)
42
- // ---------------------------------------------------------------------------
43
-
44
- describe("normalizeSdkMessage", () => {
45
- // --- assistant messages ---
46
-
47
- it("normalizes assistant message with text block", () => {
48
- const result = normalizeSdkMessage({
49
- type: "assistant",
50
- message: { content: [{ type: "text", text: "Hello world" }] },
51
- });
52
- expect(result).not.toBeNull();
53
- expect(result!.type).toBe("assistant");
54
- expect(result!.blocks).toEqual([{ type: "text", text: "Hello world" }]);
55
- expect(result!.isFinalResponse).toBeUndefined();
56
- });
57
-
58
- it("normalizes assistant message with thinking block", () => {
59
- const result = normalizeSdkMessage({
60
- type: "assistant",
61
- message: { content: [{ type: "thinking", thinking: "Let me analyze..." }] },
62
- });
63
- expect(result).not.toBeNull();
64
- expect(result!.blocks).toEqual([{ type: "thinking", thinking: "Let me analyze..." }]);
65
- });
66
-
67
- it("normalizes assistant message with tool_use block", () => {
68
- const result = normalizeSdkMessage({
69
- type: "assistant",
70
- message: {
71
- content: [{ type: "tool_use", name: "Read", input: { file_path: "/tmp/test.txt" } }],
72
- },
73
- });
74
- expect(result).not.toBeNull();
75
- expect(result!.blocks).toEqual([
76
- { type: "tool_use", name: "Read", input: { file_path: "/tmp/test.txt" } },
77
- ]);
78
- });
79
-
80
- it('uses "unknown" for tool_use without name', () => {
81
- const result = normalizeSdkMessage({
82
- type: "assistant",
83
- message: { content: [{ type: "tool_use", input: { x: 1 } }] },
84
- });
85
- expect(result!.blocks[0]).toMatchObject({ type: "tool_use", name: "unknown" });
86
- });
87
-
88
- it("normalizes user message with tool_result block (success)", () => {
89
- const result = normalizeSdkMessage({
90
- type: "user",
91
- message: {
92
- content: [
93
- { type: "tool_result", tool_use_id: "abc123", content: "file content here", is_error: false },
94
- ],
95
- },
96
- });
97
- expect(result).not.toBeNull();
98
- expect(result!.type).toBe("user");
99
- const block = result!.blocks[0] as any;
100
- expect(block.type).toBe("tool_result");
101
- expect(block.tool_use_id).toBe("abc123");
102
- expect(block.content).toBe("file content here");
103
- expect(block.is_error).toBe(false);
104
- });
105
-
106
- it("normalizes user message with tool_result block (error)", () => {
107
- const result = normalizeSdkMessage({
108
- type: "user",
109
- message: {
110
- content: [
111
- { type: "tool_result", tool_use_id: "err456", content: "permission denied", is_error: true },
112
- ],
113
- },
114
- });
115
- expect(result!.blocks[0]).toMatchObject({
116
- type: "tool_result",
117
- tool_use_id: "err456",
118
- is_error: true,
119
- });
120
- });
121
-
122
- it("normalizes tool_result with array content", () => {
123
- const content = [{ type: "text", text: "line 1" }, { type: "text", text: "line 2" }];
124
- const result = normalizeSdkMessage({
125
- type: "user",
126
- message: { content: [{ type: "tool_result", tool_use_id: "arr", content }] },
127
- });
128
- expect(result!.blocks[0]).toMatchObject({
129
- type: "tool_result",
130
- tool_use_id: "arr",
131
- });
132
- expect((result!.blocks[0] as any).content).toEqual(content);
133
- });
134
-
135
- it("skips text blocks in user messages", () => {
136
- // user text is host input, not assistant output. If the CLI emits it for
137
- // any reason, it should not appear in the final reply.
138
- const result = normalizeSdkMessage({
139
- type: "user",
140
- message: {
141
- content: [
142
- { type: "text", text: "[ChatCCC IM skill: feishu-skill]\n...[/ChatCCC IM skill: feishu-skill]" },
143
- { type: "tool_result", tool_use_id: "abc", content: "result" },
144
- ],
145
- },
146
- });
147
- expect(result).not.toBeNull();
148
- expect(result!.type).toBe("user");
149
- // text block 应被跳过,只保留 tool_result
150
- expect(result!.blocks).toHaveLength(1);
151
- expect(result!.blocks[0]).toMatchObject({ type: "tool_result", tool_use_id: "abc" });
152
- });
153
-
154
- it("returns null for user message with only text blocks (all skipped)", () => {
155
- // 纯 user text 消息(无 tool_result)→ 全部跳过,不产生有效 blocks
156
- const result = normalizeSdkMessage({
157
- type: "user",
158
- message: {
159
- content: [{ type: "text", text: "some replayed user input" }],
160
- },
161
- });
162
- // 此时 blocks 为空,但消息本身仍有 type,返回非 null 以保持流完整性
163
- // 调用方 accumulateBlockContent 对空 blocks 是 no-op
164
- expect(result).not.toBeNull();
165
- expect(result!.blocks).toEqual([]);
166
- });
167
-
168
- it("normalizes redacted_thinking block", () => {
169
- const result = normalizeSdkMessage({
170
- type: "assistant",
171
- message: { content: [{ type: "redacted_thinking" }] },
172
- });
173
- expect(result!.blocks).toEqual([{ type: "redacted_thinking" }]);
174
- });
175
-
176
- it("normalizes search_result block", () => {
177
- const result = normalizeSdkMessage({
178
- type: "assistant",
179
- message: {
180
- content: [{ type: "search_result", query: "TypeScript best practices" }],
181
- },
182
- });
183
- expect(result!.blocks).toEqual([
184
- { type: "search_result", query: "TypeScript best practices" },
185
- ]);
186
- });
187
-
188
- it("normalizes search_result without query (empty string)", () => {
189
- const result = normalizeSdkMessage({
190
- type: "assistant",
191
- message: { content: [{ type: "search_result" }] },
192
- });
193
- expect(result!.blocks).toEqual([{ type: "search_result", query: "" }]);
194
- });
195
-
196
- // --- system messages ---
197
-
198
- it("normalizes system compact_boundary message", () => {
199
- const result = normalizeSdkMessage({
200
- type: "system",
201
- subtype: "compact_boundary",
202
- compact_metadata: {
203
- trigger: "auto",
204
- pre_tokens: 15000,
205
- post_tokens: 8000,
206
- },
207
- });
208
- expect(result).not.toBeNull();
209
- expect(result!.type).toBe("system");
210
- expect(result!.blocks).toEqual([
211
- { type: "compact_boundary", trigger: "auto", pre_tokens: 15000, post_tokens: 8000 },
212
- ]);
213
- });
214
-
215
- it("normalizes compact_boundary with manual trigger", () => {
216
- const result = normalizeSdkMessage({
217
- type: "system",
218
- subtype: "compact_boundary",
219
- compact_metadata: { trigger: "manual", pre_tokens: 20000 },
220
- });
221
- expect(result!.blocks).toEqual([
222
- { type: "compact_boundary", trigger: "manual", pre_tokens: 20000, post_tokens: undefined },
223
- ]);
224
- });
225
-
226
- it("normalizes compact_boundary without post_tokens", () => {
227
- const result = normalizeSdkMessage({
228
- type: "system",
229
- subtype: "compact_boundary",
230
- compact_metadata: { trigger: "auto", pre_tokens: 10000 },
231
- });
232
- expect(result!.blocks).toEqual([
233
- { type: "compact_boundary", trigger: "auto", pre_tokens: 10000, post_tokens: undefined },
234
- ]);
235
- });
236
-
237
- // --- mixed blocks ---
238
-
239
- it("normalizes message with multiple block types mixed", () => {
240
- const result = normalizeSdkMessage({
241
- type: "assistant",
242
- message: {
243
- content: [
244
- { type: "thinking", thinking: "Hmm..." },
245
- { type: "tool_use", name: "Grep", input: { pattern: "foo" } },
246
- { type: "text", text: "Found it." },
247
- ],
248
- },
249
- });
250
- expect(result).not.toBeNull();
251
- expect(result!.blocks).toHaveLength(3);
252
- expect(result!.blocks[0]).toEqual({ type: "thinking", thinking: "Hmm..." });
253
- expect(result!.blocks[1]).toEqual({ type: "tool_use", name: "Grep", input: { pattern: "foo" } });
254
- expect(result!.blocks[2]).toEqual({ type: "text", text: "Found it." });
255
- });
256
-
257
- // --- edge cases ---
258
-
259
- it("skips unknown block types", () => {
260
- const result = normalizeSdkMessage({
261
- type: "assistant",
262
- message: {
263
- content: [
264
- { type: "unknown_type", data: "whatever" },
265
- { type: "text", text: "still here" },
266
- ],
267
- },
268
- });
269
- expect(result!.blocks).toHaveLength(1);
270
- expect(result!.blocks[0]).toEqual({ type: "text", text: "still here" });
271
- });
272
-
273
- it("marks a successful result event as an authoritative final response", () => {
274
- expect(
275
- normalizeSdkMessage({ type: "result", subtype: "success" }),
276
- ).toEqual({
277
- type: "assistant",
278
- blocks: [],
279
- isFinalResponse: true,
280
- });
281
- });
282
-
283
- it("returns null for other non-assistant/non-user/non-system messages", () => {
284
- expect(
285
- normalizeSdkMessage({ type: "stream_event" }),
286
- ).toBeNull();
287
- expect(
288
- normalizeSdkMessage({ type: "status" }),
289
- ).toBeNull();
290
- });
291
-
292
- it("returns null for system message without compact_boundary subtype", () => {
293
- expect(
294
- normalizeSdkMessage({ type: "system", subtype: "init" }),
295
- ).toBeNull();
296
- expect(
297
- normalizeSdkMessage({ type: "system", subtype: "notification" }),
298
- ).toBeNull();
299
- });
300
-
301
- it("returns message with empty blocks for content=[ ]", () => {
302
- const result = normalizeSdkMessage({
303
- type: "assistant",
304
- message: { content: [] },
305
- });
306
- expect(result).not.toBeNull();
307
- expect(result!.blocks).toEqual([]);
308
- });
309
-
310
- it("returns null for message without content", () => {
311
- const result = normalizeSdkMessage({
312
- type: "assistant",
313
- message: {},
314
- });
315
- expect(result).toBeNull();
316
- });
317
-
318
- it("returns null for message with null content array", () => {
319
- const result = normalizeSdkMessage({
320
- type: "assistant",
321
- message: { content: undefined as any },
322
- });
323
- expect(result).toBeNull();
324
- });
325
-
326
- it("returns null for compact_boundary without metadata", () => {
327
- const result = normalizeSdkMessage({
328
- type: "system",
329
- subtype: "compact_boundary",
330
- });
331
- expect(result).toBeNull();
332
- });
333
-
334
- it("skips thinking block with empty thinking string", () => {
335
- const result = normalizeSdkMessage({
336
- type: "assistant",
337
- message: { content: [{ type: "thinking", thinking: "" }] },
338
- });
339
- expect(result!.blocks).toEqual([]);
340
- });
341
-
342
- it("skips text block with empty text string", () => {
343
- const result = normalizeSdkMessage({
344
- type: "assistant",
345
- message: { content: [{ type: "text", text: "" }] },
346
- });
347
- expect(result!.blocks).toEqual([]);
348
- });
349
-
350
- it("handles message with undefined type gracefully", () => {
351
- const result = normalizeSdkMessage({
352
- message: { content: [{ type: "text", text: "orphan" }] },
353
- });
354
- expect(result).toBeNull();
355
- });
356
- });
357
-
358
- // ---------------------------------------------------------------------------
359
- // createClaudeAdapter — 工厂函数 + getSessionInfo / closeSession 测试
360
- // ---------------------------------------------------------------------------
361
-
362
- describe("createClaudeAdapter", () => {
363
- it("returns adapter with correct displayName and sessionDescPrefix", () => {
364
- const adapter = createClaudeAdapter({
365
- model: "claude-sonnet-4-6",
366
- effort: "high",
367
- isEmpty: (v) => v.trim() === "",
368
- });
369
- expect(adapter.displayName).toBe("Claude Code");
370
- expect(adapter.sessionDescPrefix).toBe("Claude Code Session:");
371
- });
372
-
373
- it("closeSession does not throw", async () => {
374
- const adapter = createClaudeAdapter({
375
- model: "claude-sonnet-4-6",
376
- effort: "high",
377
- isEmpty: () => false,
378
- });
379
- await expect(adapter.closeSession("any-sid")).resolves.toBeUndefined();
380
- });
381
-
382
- it("does not start SDK session creation when the startup signal is already aborted", async () => {
383
- const adapter = createClaudeAdapter({
384
- model: "claude-sonnet-4-6",
385
- effort: "high",
386
- isEmpty: () => false,
387
- });
388
- const controller = new AbortController();
389
- controller.abort();
390
-
391
- await expect(
392
- adapter.createSession("F:\\repo", controller.signal),
393
- ).rejects.toThrow("Claude session creation aborted");
394
- });
395
-
396
- // -------------------------------------------------------------------------
397
- // getSessionInfo 行为契约
398
- // - cwd 决定 /git 是否可用
399
- // - model 用于 /state、/sessions 显示
400
- // -------------------------------------------------------------------------
401
-
402
- it("getSessionInfo: store 中无该 sessionId 时只返回 sessionId", async () => {
403
- const store = createInMemoryMetaStore();
404
- const adapter = createClaudeAdapter({
405
- model: "",
406
- effort: "",
407
- isEmpty: () => false,
408
- metaStore: store,
409
- });
410
- const info = await adapter.getSessionInfo("unknown-sid");
411
- expect(info).toEqual({ sessionId: "unknown-sid" });
412
- expect(info?.cwd).toBeUndefined();
413
- expect(info?.model).toBeUndefined();
414
- });
415
-
416
- it("getSessionInfo: store 仅有 cwd 时返回 cwd,model 仍为 undefined", async () => {
417
- const store = createInMemoryMetaStore({ "sid-known": { cwd: "F:/proj/Foo" } });
418
- const adapter = createClaudeAdapter({
419
- model: "",
420
- effort: "",
421
- isEmpty: () => false,
422
- metaStore: store,
423
- });
424
- const info = await adapter.getSessionInfo("sid-known");
425
- expect(info).toEqual({ sessionId: "sid-known", cwd: "F:/proj/Foo" });
426
- expect(info?.model).toBeUndefined();
427
- });
428
-
429
- it("getSessionInfo: store 同时有 cwd + model 时一并返回", async () => {
430
- const store = createInMemoryMetaStore({
431
- "sid-known": { cwd: "F:/proj/Foo", model: "claude-sonnet-4-6" },
432
- });
433
- const adapter = createClaudeAdapter({
434
- model: "",
435
- effort: "",
436
- isEmpty: () => false,
437
- metaStore: store,
438
- });
439
- const info = await adapter.getSessionInfo("sid-known");
440
- expect(info).toEqual({
441
- sessionId: "sid-known",
442
- cwd: "F:/proj/Foo",
443
- model: "claude-sonnet-4-6",
444
- });
445
- });
446
-
447
- it("getSessionInfo: 不同 sessionId 互不影响", async () => {
448
- const store = createInMemoryMetaStore({
449
- "sid-A": { cwd: "/a", model: "mA" },
450
- "sid-B": { cwd: "/b" },
451
- });
452
- const adapter = createClaudeAdapter({
453
- model: "",
454
- effort: "",
455
- isEmpty: () => false,
456
- metaStore: store,
457
- });
458
- expect(await adapter.getSessionInfo("sid-A")).toEqual({
459
- sessionId: "sid-A",
460
- cwd: "/a",
461
- model: "mA",
462
- });
463
- expect(await adapter.getSessionInfo("sid-B")).toEqual({
464
- sessionId: "sid-B",
465
- cwd: "/b",
466
- });
467
- expect(await adapter.getSessionInfo("sid-C")).toEqual({ sessionId: "sid-C" });
468
- });
469
- });
470
-
471
- describe("buildClaudePromptText", () => {
472
- it("prepends the Claude-specific injection prompt when present", () => {
473
- const result = buildClaudePromptText(
474
- "[User message]\nhello\n[/User message]",
475
- "Never repeat successful commands.",
476
- );
477
-
478
- expect(result).toContain("[ChatCCC Claude-specific injection prompt]");
479
- expect(result).toContain("Never repeat successful commands.");
480
- expect(result).toContain("[/ChatCCC Claude-specific injection prompt]");
481
- expect(result.endsWith("[User message]\nhello\n[/User message]")).toBe(true);
482
- });
483
-
484
- it("prepends the Claude-specific injection prompt on every resumed prompt", () => {
485
- const first = buildClaudePromptText(
486
- "[ChatCCC IM skill: feishu-skill]\ncapabilities\n[/ChatCCC IM skill: feishu-skill]\n\n[User message]\nfirst\n[/User message]",
487
- "Never repeat successful commands for {{session_id}}.",
488
- "sid-resume",
489
- );
490
- const second = buildClaudePromptText(
491
- "[ChatCCC IM skill: feishu-skill]\ncapabilities\n[/ChatCCC IM skill: feishu-skill]\n\n[User message]\nsecond\n[/User message]",
492
- "Never repeat successful commands for {{session_id}}.",
493
- "sid-resume",
494
- );
495
-
496
- for (const result of [first, second]) {
497
- expect(result).toContain("[ChatCCC Claude-specific injection prompt]");
498
- expect(result).toContain("Never repeat successful commands for sid-resume.");
499
- expect(result).toContain("[/ChatCCC Claude-specific injection prompt]");
500
- expect(result).toContain("[ChatCCC IM skill: feishu-skill]");
501
- expect(result).toContain("[/ChatCCC IM skill: feishu-skill]");
502
- }
503
- expect(first).toContain("[User message]\nfirst\n[/User message]");
504
- expect(second).toContain("[User message]\nsecond\n[/User message]");
505
- });
506
-
507
- it("leaves user text unchanged when the injection prompt is empty", () => {
508
- expect(buildClaudePromptText("hello", " ")).toBe("hello");
509
- expect(buildClaudePromptText("hello", null)).toBe("hello");
510
- });
511
-
512
- it("replaces {{stop_stuck_url}} and {{session_id}} placeholders when sessionId is provided", () => {
513
- const result = buildClaudePromptText(
514
- "[User message]\nhello\n[/User message]",
515
- "Call POST {{stop_stuck_url}} with {\"session_id\": \"{{session_id}}\"}",
516
- "test-sid-123",
517
- );
518
-
519
- expect(result).toContain("http://127.0.0.1:");
520
- expect(result).toContain("/api/agent/stop-stuck-loop");
521
- expect(result).toContain("\"session_id\": \"test-sid-123\"");
522
- expect(result).not.toContain("{{stop_stuck_url}}");
523
- expect(result).not.toContain("{{session_id}}");
524
- });
525
-
526
- it("does not replace placeholders when sessionId is not provided", () => {
527
- const result = buildClaudePromptText(
528
- "hello",
529
- "Call POST {{stop_stuck_url}} with {\"session_id\": \"{{session_id}}\"}",
530
- );
531
-
532
- expect(result).toContain("{{stop_stuck_url}}");
533
- expect(result).toContain("{{session_id}}");
534
- });
535
- });
536
-
537
- describe("buildSdkEnv", () => {
538
- it("always sets CLAUDE_CODE_ATTRIBUTION_HEADER=0 to preserve prompt cache hit rate", () => {
539
- const originalPath = process.env.PATH;
540
- try {
541
- process.env.PATH = process.platform === "win32"
542
- ? "C:\\Program Files\\Git\\usr\\bin;C:\\Windows\\System32"
543
- : "/usr/bin:/bin";
544
- const env = buildSdkEnv("", " ", undefined);
545
- expect(env).toBeDefined();
546
- expect(env!.CLAUDE_CODE_ATTRIBUTION_HEADER).toBe("0");
547
- } finally {
548
- process.env.PATH = originalPath;
549
- }
550
- });
551
-
552
- it("prefers Git Bash before WindowsApps for Claude SDK subprocesses on Windows", () => {
553
- if (process.platform !== "win32") return;
554
- const originalPath = process.env.PATH;
555
- try {
556
- process.env.PATH = [
557
- "C:\\Users\\weizhangjian\\AppData\\Local\\Microsoft\\WindowsApps",
558
- "C:\\Program Files\\Git\\usr\\bin",
559
- "%PATH%",
560
- "C:\\Windows\\System32",
561
- ].join(";");
562
-
563
- const env = buildSdkEnv("", "", "");
564
-
565
- expect(env).toBeDefined();
566
- const parts = env!.PATH!.split(";");
567
- expect(parts[0]).toBe("C:\\Program Files\\Git\\usr\\bin");
568
- expect(parts).not.toContain("%PATH%");
569
- } finally {
570
- process.env.PATH = originalPath;
571
- }
572
- });
573
-
574
- it("sets requested SDK env overrides and removes conflicting Claude auth/model vars", () => {
575
- const original = {
576
- ANTHROPIC_AUTH_TOKEN: process.env.ANTHROPIC_AUTH_TOKEN,
577
- CLAUDE_CODE_OAUTH_TOKEN: process.env.CLAUDE_CODE_OAUTH_TOKEN,
578
- ANTHROPIC_MODEL: process.env.ANTHROPIC_MODEL,
579
- CLAUDE_CODE_EFFORT_LEVEL: process.env.CLAUDE_CODE_EFFORT_LEVEL,
580
- CLAUDE_CODE_SUBAGENT_MODEL: process.env.CLAUDE_CODE_SUBAGENT_MODEL,
581
- };
582
-
583
- process.env.ANTHROPIC_AUTH_TOKEN = "token";
584
- process.env.CLAUDE_CODE_OAUTH_TOKEN = "oauth";
585
- process.env.ANTHROPIC_MODEL = "old-model";
586
- process.env.CLAUDE_CODE_EFFORT_LEVEL = "old-effort";
587
- process.env.CLAUDE_CODE_SUBAGENT_MODEL = "old-subagent";
588
-
589
- try {
590
- const env = buildSdkEnv(
591
- " claude-haiku-4-5-20251001 ",
592
- " sk-test ",
593
- " https://api.example.com ",
594
- );
595
-
596
- expect(env).toBeDefined();
597
- expect(env!.ANTHROPIC_AUTH_TOKEN).toBeUndefined();
598
- expect(env!.CLAUDE_CODE_OAUTH_TOKEN).toBeUndefined();
599
- expect(env!.ANTHROPIC_MODEL).toBeUndefined();
600
- expect(env!.CLAUDE_CODE_EFFORT_LEVEL).toBeUndefined();
601
- expect(env!.CLAUDE_CODE_SUBAGENT_MODEL).toBe("claude-haiku-4-5-20251001");
602
- expect(env!.ANTHROPIC_API_KEY).toBe("sk-test");
603
- expect(env!.ANTHROPIC_BASE_URL).toBe("https://api.example.com");
604
- } finally {
605
- for (const [key, value] of Object.entries(original)) {
606
- if (value === undefined) {
607
- delete process.env[key];
608
- } else {
609
- process.env[key] = value;
610
- }
611
- }
612
- }
613
- });
614
- });
1
+ import { describe, it, expect } from "vitest";
2
+ import {
3
+ normalizeSdkMessage,
4
+ createClaudeAdapter,
5
+ buildClaudePromptText,
6
+ buildSdkEnv,
7
+ } from "../adapters/claude-adapter.ts";
8
+ import type { UnifiedStreamMessage } from "../adapters/adapter-interface.ts";
9
+ import type {
10
+ ClaudeSessionMeta,
11
+ ClaudeSessionMetaStore,
12
+ } from "../adapters/claude-session-meta-store.ts";
13
+
14
+ // ---------------------------------------------------------------------------
15
+ // 进程内内存版 meta store(测试用,避开磁盘 IO)
16
+ // ---------------------------------------------------------------------------
17
+
18
+ function createInMemoryMetaStore(
19
+ initial: Record<string, ClaudeSessionMeta> = {},
20
+ ): ClaudeSessionMetaStore & { snapshot(): Record<string, ClaudeSessionMeta> } {
21
+ const map = new Map<string, ClaudeSessionMeta>(Object.entries(initial));
22
+ return {
23
+ async get(sid) {
24
+ return map.get(sid);
25
+ },
26
+ async set(sid, partial) {
27
+ const existing = map.get(sid);
28
+ const merged: { cwd?: string; model?: string } = { ...existing };
29
+ if (typeof partial.cwd === "string" && partial.cwd.length > 0) merged.cwd = partial.cwd;
30
+ if (typeof partial.model === "string" && partial.model.length > 0) merged.model = partial.model;
31
+ if (!merged.cwd) return;
32
+ map.set(sid, merged.model ? { cwd: merged.cwd, model: merged.model } : { cwd: merged.cwd });
33
+ },
34
+ snapshot() {
35
+ return Object.fromEntries(map);
36
+ },
37
+ };
38
+ }
39
+
40
+ // ---------------------------------------------------------------------------
41
+ // normalizeSdkMessage — 核心映射逻辑测试(纯函数,CLI 与 SDK 格式相同)
42
+ // ---------------------------------------------------------------------------
43
+
44
+ describe("normalizeSdkMessage", () => {
45
+ // --- assistant messages ---
46
+
47
+ it("normalizes assistant message with text block", () => {
48
+ const result = normalizeSdkMessage({
49
+ type: "assistant",
50
+ message: { content: [{ type: "text", text: "Hello world" }] },
51
+ });
52
+ expect(result).not.toBeNull();
53
+ expect(result!.type).toBe("assistant");
54
+ expect(result!.blocks).toEqual([{ type: "text", text: "Hello world" }]);
55
+ expect(result!.isFinalResponse).toBeUndefined();
56
+ });
57
+
58
+ it("normalizes assistant message with thinking block", () => {
59
+ const result = normalizeSdkMessage({
60
+ type: "assistant",
61
+ message: { content: [{ type: "thinking", thinking: "Let me analyze..." }] },
62
+ });
63
+ expect(result).not.toBeNull();
64
+ expect(result!.blocks).toEqual([{ type: "thinking", thinking: "Let me analyze..." }]);
65
+ });
66
+
67
+ it("normalizes assistant message with tool_use block", () => {
68
+ const result = normalizeSdkMessage({
69
+ type: "assistant",
70
+ message: {
71
+ content: [{ type: "tool_use", name: "Read", input: { file_path: "/tmp/test.txt" } }],
72
+ },
73
+ });
74
+ expect(result).not.toBeNull();
75
+ expect(result!.blocks).toEqual([
76
+ { type: "tool_use", name: "Read", input: { file_path: "/tmp/test.txt" } },
77
+ ]);
78
+ });
79
+
80
+ it('uses "unknown" for tool_use without name', () => {
81
+ const result = normalizeSdkMessage({
82
+ type: "assistant",
83
+ message: { content: [{ type: "tool_use", input: { x: 1 } }] },
84
+ });
85
+ expect(result!.blocks[0]).toMatchObject({ type: "tool_use", name: "unknown" });
86
+ });
87
+
88
+ it("normalizes user message with tool_result block (success)", () => {
89
+ const result = normalizeSdkMessage({
90
+ type: "user",
91
+ message: {
92
+ content: [
93
+ { type: "tool_result", tool_use_id: "abc123", content: "file content here", is_error: false },
94
+ ],
95
+ },
96
+ });
97
+ expect(result).not.toBeNull();
98
+ expect(result!.type).toBe("user");
99
+ const block = result!.blocks[0] as any;
100
+ expect(block.type).toBe("tool_result");
101
+ expect(block.tool_use_id).toBe("abc123");
102
+ expect(block.content).toBe("file content here");
103
+ expect(block.is_error).toBe(false);
104
+ });
105
+
106
+ it("normalizes user message with tool_result block (error)", () => {
107
+ const result = normalizeSdkMessage({
108
+ type: "user",
109
+ message: {
110
+ content: [
111
+ { type: "tool_result", tool_use_id: "err456", content: "permission denied", is_error: true },
112
+ ],
113
+ },
114
+ });
115
+ expect(result!.blocks[0]).toMatchObject({
116
+ type: "tool_result",
117
+ tool_use_id: "err456",
118
+ is_error: true,
119
+ });
120
+ });
121
+
122
+ it("normalizes tool_result with array content", () => {
123
+ const content = [{ type: "text", text: "line 1" }, { type: "text", text: "line 2" }];
124
+ const result = normalizeSdkMessage({
125
+ type: "user",
126
+ message: { content: [{ type: "tool_result", tool_use_id: "arr", content }] },
127
+ });
128
+ expect(result!.blocks[0]).toMatchObject({
129
+ type: "tool_result",
130
+ tool_use_id: "arr",
131
+ });
132
+ expect((result!.blocks[0] as any).content).toEqual(content);
133
+ });
134
+
135
+ it("skips text blocks in user messages", () => {
136
+ // user text is host input, not assistant output. If the CLI emits it for
137
+ // any reason, it should not appear in the final reply.
138
+ const result = normalizeSdkMessage({
139
+ type: "user",
140
+ message: {
141
+ content: [
142
+ { type: "text", text: "[ChatCCC IM skill: feishu-skill]\n...[/ChatCCC IM skill: feishu-skill]" },
143
+ { type: "tool_result", tool_use_id: "abc", content: "result" },
144
+ ],
145
+ },
146
+ });
147
+ expect(result).not.toBeNull();
148
+ expect(result!.type).toBe("user");
149
+ // text block 应被跳过,只保留 tool_result
150
+ expect(result!.blocks).toHaveLength(1);
151
+ expect(result!.blocks[0]).toMatchObject({ type: "tool_result", tool_use_id: "abc" });
152
+ });
153
+
154
+ it("returns null for user message with only text blocks (all skipped)", () => {
155
+ // 纯 user text 消息(无 tool_result)→ 全部跳过,不产生有效 blocks
156
+ const result = normalizeSdkMessage({
157
+ type: "user",
158
+ message: {
159
+ content: [{ type: "text", text: "some replayed user input" }],
160
+ },
161
+ });
162
+ // 此时 blocks 为空,但消息本身仍有 type,返回非 null 以保持流完整性
163
+ // 调用方 accumulateBlockContent 对空 blocks 是 no-op
164
+ expect(result).not.toBeNull();
165
+ expect(result!.blocks).toEqual([]);
166
+ });
167
+
168
+ it("normalizes redacted_thinking block", () => {
169
+ const result = normalizeSdkMessage({
170
+ type: "assistant",
171
+ message: { content: [{ type: "redacted_thinking" }] },
172
+ });
173
+ expect(result!.blocks).toEqual([{ type: "redacted_thinking" }]);
174
+ });
175
+
176
+ it("normalizes search_result block", () => {
177
+ const result = normalizeSdkMessage({
178
+ type: "assistant",
179
+ message: {
180
+ content: [{ type: "search_result", query: "TypeScript best practices" }],
181
+ },
182
+ });
183
+ expect(result!.blocks).toEqual([
184
+ { type: "search_result", query: "TypeScript best practices" },
185
+ ]);
186
+ });
187
+
188
+ it("normalizes search_result without query (empty string)", () => {
189
+ const result = normalizeSdkMessage({
190
+ type: "assistant",
191
+ message: { content: [{ type: "search_result" }] },
192
+ });
193
+ expect(result!.blocks).toEqual([{ type: "search_result", query: "" }]);
194
+ });
195
+
196
+ // --- system messages ---
197
+
198
+ it("normalizes system compact_boundary message", () => {
199
+ const result = normalizeSdkMessage({
200
+ type: "system",
201
+ subtype: "compact_boundary",
202
+ compact_metadata: {
203
+ trigger: "auto",
204
+ pre_tokens: 15000,
205
+ post_tokens: 8000,
206
+ },
207
+ });
208
+ expect(result).not.toBeNull();
209
+ expect(result!.type).toBe("system");
210
+ expect(result!.blocks).toEqual([
211
+ { type: "compact_boundary", trigger: "auto", pre_tokens: 15000, post_tokens: 8000 },
212
+ ]);
213
+ });
214
+
215
+ it("normalizes compact_boundary with manual trigger", () => {
216
+ const result = normalizeSdkMessage({
217
+ type: "system",
218
+ subtype: "compact_boundary",
219
+ compact_metadata: { trigger: "manual", pre_tokens: 20000 },
220
+ });
221
+ expect(result!.blocks).toEqual([
222
+ { type: "compact_boundary", trigger: "manual", pre_tokens: 20000, post_tokens: undefined },
223
+ ]);
224
+ });
225
+
226
+ it("normalizes compact_boundary without post_tokens", () => {
227
+ const result = normalizeSdkMessage({
228
+ type: "system",
229
+ subtype: "compact_boundary",
230
+ compact_metadata: { trigger: "auto", pre_tokens: 10000 },
231
+ });
232
+ expect(result!.blocks).toEqual([
233
+ { type: "compact_boundary", trigger: "auto", pre_tokens: 10000, post_tokens: undefined },
234
+ ]);
235
+ });
236
+
237
+ // --- mixed blocks ---
238
+
239
+ it("normalizes message with multiple block types mixed", () => {
240
+ const result = normalizeSdkMessage({
241
+ type: "assistant",
242
+ message: {
243
+ content: [
244
+ { type: "thinking", thinking: "Hmm..." },
245
+ { type: "tool_use", name: "Grep", input: { pattern: "foo" } },
246
+ { type: "text", text: "Found it." },
247
+ ],
248
+ },
249
+ });
250
+ expect(result).not.toBeNull();
251
+ expect(result!.blocks).toHaveLength(3);
252
+ expect(result!.blocks[0]).toEqual({ type: "thinking", thinking: "Hmm..." });
253
+ expect(result!.blocks[1]).toEqual({ type: "tool_use", name: "Grep", input: { pattern: "foo" } });
254
+ expect(result!.blocks[2]).toEqual({ type: "text", text: "Found it." });
255
+ });
256
+
257
+ // --- edge cases ---
258
+
259
+ it("skips unknown block types", () => {
260
+ const result = normalizeSdkMessage({
261
+ type: "assistant",
262
+ message: {
263
+ content: [
264
+ { type: "unknown_type", data: "whatever" },
265
+ { type: "text", text: "still here" },
266
+ ],
267
+ },
268
+ });
269
+ expect(result!.blocks).toHaveLength(1);
270
+ expect(result!.blocks[0]).toEqual({ type: "text", text: "still here" });
271
+ });
272
+
273
+ it("marks a successful result event as an authoritative final response", () => {
274
+ expect(
275
+ normalizeSdkMessage({ type: "result", subtype: "success" }),
276
+ ).toEqual({
277
+ type: "assistant",
278
+ blocks: [],
279
+ isFinalResponse: true,
280
+ });
281
+ });
282
+
283
+ it("returns null for other non-assistant/non-user/non-system messages", () => {
284
+ expect(
285
+ normalizeSdkMessage({ type: "stream_event" }),
286
+ ).toBeNull();
287
+ expect(
288
+ normalizeSdkMessage({ type: "status" }),
289
+ ).toBeNull();
290
+ });
291
+
292
+ it("returns null for system message without compact_boundary subtype", () => {
293
+ expect(
294
+ normalizeSdkMessage({ type: "system", subtype: "init" }),
295
+ ).toBeNull();
296
+ expect(
297
+ normalizeSdkMessage({ type: "system", subtype: "notification" }),
298
+ ).toBeNull();
299
+ });
300
+
301
+ it("returns message with empty blocks for content=[ ]", () => {
302
+ const result = normalizeSdkMessage({
303
+ type: "assistant",
304
+ message: { content: [] },
305
+ });
306
+ expect(result).not.toBeNull();
307
+ expect(result!.blocks).toEqual([]);
308
+ });
309
+
310
+ it("returns null for message without content", () => {
311
+ const result = normalizeSdkMessage({
312
+ type: "assistant",
313
+ message: {},
314
+ });
315
+ expect(result).toBeNull();
316
+ });
317
+
318
+ it("returns null for message with null content array", () => {
319
+ const result = normalizeSdkMessage({
320
+ type: "assistant",
321
+ message: { content: undefined as any },
322
+ });
323
+ expect(result).toBeNull();
324
+ });
325
+
326
+ it("returns null for compact_boundary without metadata", () => {
327
+ const result = normalizeSdkMessage({
328
+ type: "system",
329
+ subtype: "compact_boundary",
330
+ });
331
+ expect(result).toBeNull();
332
+ });
333
+
334
+ it("skips thinking block with empty thinking string", () => {
335
+ const result = normalizeSdkMessage({
336
+ type: "assistant",
337
+ message: { content: [{ type: "thinking", thinking: "" }] },
338
+ });
339
+ expect(result!.blocks).toEqual([]);
340
+ });
341
+
342
+ it("skips text block with empty text string", () => {
343
+ const result = normalizeSdkMessage({
344
+ type: "assistant",
345
+ message: { content: [{ type: "text", text: "" }] },
346
+ });
347
+ expect(result!.blocks).toEqual([]);
348
+ });
349
+
350
+ it("handles message with undefined type gracefully", () => {
351
+ const result = normalizeSdkMessage({
352
+ message: { content: [{ type: "text", text: "orphan" }] },
353
+ });
354
+ expect(result).toBeNull();
355
+ });
356
+ });
357
+
358
+ // ---------------------------------------------------------------------------
359
+ // createClaudeAdapter — 工厂函数 + getSessionInfo / closeSession 测试
360
+ // ---------------------------------------------------------------------------
361
+
362
+ describe("createClaudeAdapter", () => {
363
+ it("returns adapter with correct displayName and sessionDescPrefix", () => {
364
+ const adapter = createClaudeAdapter({
365
+ model: "claude-sonnet-4-6",
366
+ effort: "high",
367
+ isEmpty: (v) => v.trim() === "",
368
+ });
369
+ expect(adapter.displayName).toBe("Claude Code");
370
+ expect(adapter.sessionDescPrefix).toBe("Claude Code Session:");
371
+ });
372
+
373
+ it("closeSession does not throw", async () => {
374
+ const adapter = createClaudeAdapter({
375
+ model: "claude-sonnet-4-6",
376
+ effort: "high",
377
+ isEmpty: () => false,
378
+ });
379
+ await expect(adapter.closeSession("any-sid")).resolves.toBeUndefined();
380
+ });
381
+
382
+ it("does not start SDK session creation when the startup signal is already aborted", async () => {
383
+ const adapter = createClaudeAdapter({
384
+ model: "claude-sonnet-4-6",
385
+ effort: "high",
386
+ isEmpty: () => false,
387
+ });
388
+ const controller = new AbortController();
389
+ controller.abort();
390
+
391
+ await expect(
392
+ adapter.createSession("F:\\repo", controller.signal),
393
+ ).rejects.toThrow("Claude session creation aborted");
394
+ });
395
+
396
+ // -------------------------------------------------------------------------
397
+ // getSessionInfo 行为契约
398
+ // - cwd 决定 /git 是否可用
399
+ // - model 用于 /state、/sessions 显示
400
+ // -------------------------------------------------------------------------
401
+
402
+ it("getSessionInfo: store 中无该 sessionId 时只返回 sessionId", async () => {
403
+ const store = createInMemoryMetaStore();
404
+ const adapter = createClaudeAdapter({
405
+ model: "",
406
+ effort: "",
407
+ isEmpty: () => false,
408
+ metaStore: store,
409
+ });
410
+ const info = await adapter.getSessionInfo("unknown-sid");
411
+ expect(info).toEqual({ sessionId: "unknown-sid" });
412
+ expect(info?.cwd).toBeUndefined();
413
+ expect(info?.model).toBeUndefined();
414
+ });
415
+
416
+ it("getSessionInfo: store 仅有 cwd 时返回 cwd,model 仍为 undefined", async () => {
417
+ const store = createInMemoryMetaStore({ "sid-known": { cwd: "F:/proj/Foo" } });
418
+ const adapter = createClaudeAdapter({
419
+ model: "",
420
+ effort: "",
421
+ isEmpty: () => false,
422
+ metaStore: store,
423
+ });
424
+ const info = await adapter.getSessionInfo("sid-known");
425
+ expect(info).toEqual({ sessionId: "sid-known", cwd: "F:/proj/Foo" });
426
+ expect(info?.model).toBeUndefined();
427
+ });
428
+
429
+ it("getSessionInfo: store 同时有 cwd + model 时一并返回", async () => {
430
+ const store = createInMemoryMetaStore({
431
+ "sid-known": { cwd: "F:/proj/Foo", model: "claude-sonnet-4-6" },
432
+ });
433
+ const adapter = createClaudeAdapter({
434
+ model: "",
435
+ effort: "",
436
+ isEmpty: () => false,
437
+ metaStore: store,
438
+ });
439
+ const info = await adapter.getSessionInfo("sid-known");
440
+ expect(info).toEqual({
441
+ sessionId: "sid-known",
442
+ cwd: "F:/proj/Foo",
443
+ model: "claude-sonnet-4-6",
444
+ });
445
+ });
446
+
447
+ it("getSessionInfo: 不同 sessionId 互不影响", async () => {
448
+ const store = createInMemoryMetaStore({
449
+ "sid-A": { cwd: "/a", model: "mA" },
450
+ "sid-B": { cwd: "/b" },
451
+ });
452
+ const adapter = createClaudeAdapter({
453
+ model: "",
454
+ effort: "",
455
+ isEmpty: () => false,
456
+ metaStore: store,
457
+ });
458
+ expect(await adapter.getSessionInfo("sid-A")).toEqual({
459
+ sessionId: "sid-A",
460
+ cwd: "/a",
461
+ model: "mA",
462
+ });
463
+ expect(await adapter.getSessionInfo("sid-B")).toEqual({
464
+ sessionId: "sid-B",
465
+ cwd: "/b",
466
+ });
467
+ expect(await adapter.getSessionInfo("sid-C")).toEqual({ sessionId: "sid-C" });
468
+ });
469
+ });
470
+
471
+ describe("buildClaudePromptText", () => {
472
+ it("prepends the Claude-specific injection prompt when present", () => {
473
+ const result = buildClaudePromptText(
474
+ "[User message]\nhello\n[/User message]",
475
+ "Never repeat successful commands.",
476
+ );
477
+
478
+ expect(result).toContain("[ChatCCC Claude-specific injection prompt]");
479
+ expect(result).toContain("Never repeat successful commands.");
480
+ expect(result).toContain("[/ChatCCC Claude-specific injection prompt]");
481
+ expect(result.endsWith("[User message]\nhello\n[/User message]")).toBe(true);
482
+ });
483
+
484
+ it("prepends the Claude-specific injection prompt on every resumed prompt", () => {
485
+ const first = buildClaudePromptText(
486
+ "[ChatCCC IM skill: feishu-skill]\ncapabilities\n[/ChatCCC IM skill: feishu-skill]\n\n[User message]\nfirst\n[/User message]",
487
+ "Never repeat successful commands for {{session_id}}.",
488
+ "sid-resume",
489
+ );
490
+ const second = buildClaudePromptText(
491
+ "[ChatCCC IM skill: feishu-skill]\ncapabilities\n[/ChatCCC IM skill: feishu-skill]\n\n[User message]\nsecond\n[/User message]",
492
+ "Never repeat successful commands for {{session_id}}.",
493
+ "sid-resume",
494
+ );
495
+
496
+ for (const result of [first, second]) {
497
+ expect(result).toContain("[ChatCCC Claude-specific injection prompt]");
498
+ expect(result).toContain("Never repeat successful commands for sid-resume.");
499
+ expect(result).toContain("[/ChatCCC Claude-specific injection prompt]");
500
+ expect(result).toContain("[ChatCCC IM skill: feishu-skill]");
501
+ expect(result).toContain("[/ChatCCC IM skill: feishu-skill]");
502
+ }
503
+ expect(first).toContain("[User message]\nfirst\n[/User message]");
504
+ expect(second).toContain("[User message]\nsecond\n[/User message]");
505
+ });
506
+
507
+ it("leaves user text unchanged when the injection prompt is empty", () => {
508
+ expect(buildClaudePromptText("hello", " ")).toBe("hello");
509
+ expect(buildClaudePromptText("hello", null)).toBe("hello");
510
+ });
511
+
512
+ it("replaces {{stop_stuck_url}} and {{session_id}} placeholders when sessionId is provided", () => {
513
+ const result = buildClaudePromptText(
514
+ "[User message]\nhello\n[/User message]",
515
+ "Call POST {{stop_stuck_url}} with {\"session_id\": \"{{session_id}}\"}",
516
+ "test-sid-123",
517
+ );
518
+
519
+ expect(result).toContain("http://127.0.0.1:");
520
+ expect(result).toContain("/api/agent/stop-stuck-loop");
521
+ expect(result).toContain("\"session_id\": \"test-sid-123\"");
522
+ expect(result).not.toContain("{{stop_stuck_url}}");
523
+ expect(result).not.toContain("{{session_id}}");
524
+ });
525
+
526
+ it("does not replace placeholders when sessionId is not provided", () => {
527
+ const result = buildClaudePromptText(
528
+ "hello",
529
+ "Call POST {{stop_stuck_url}} with {\"session_id\": \"{{session_id}}\"}",
530
+ );
531
+
532
+ expect(result).toContain("{{stop_stuck_url}}");
533
+ expect(result).toContain("{{session_id}}");
534
+ });
535
+ });
536
+
537
+ describe("buildSdkEnv", () => {
538
+ it("always sets CLAUDE_CODE_ATTRIBUTION_HEADER=0 to preserve prompt cache hit rate", () => {
539
+ const originalPath = process.env.PATH;
540
+ try {
541
+ process.env.PATH = process.platform === "win32"
542
+ ? "C:\\Program Files\\Git\\usr\\bin;C:\\Windows\\System32"
543
+ : "/usr/bin:/bin";
544
+ const env = buildSdkEnv("", " ", undefined);
545
+ expect(env).toBeDefined();
546
+ expect(env!.CLAUDE_CODE_ATTRIBUTION_HEADER).toBe("0");
547
+ } finally {
548
+ process.env.PATH = originalPath;
549
+ }
550
+ });
551
+
552
+ it("prefers Git Bash before WindowsApps for Claude SDK subprocesses on Windows", () => {
553
+ if (process.platform !== "win32") return;
554
+ const originalPath = process.env.PATH;
555
+ try {
556
+ process.env.PATH = [
557
+ "C:\\Users\\weizhangjian\\AppData\\Local\\Microsoft\\WindowsApps",
558
+ "C:\\Program Files\\Git\\usr\\bin",
559
+ "%PATH%",
560
+ "C:\\Windows\\System32",
561
+ ].join(";");
562
+
563
+ const env = buildSdkEnv("", "", "");
564
+
565
+ expect(env).toBeDefined();
566
+ const parts = env!.PATH!.split(";");
567
+ expect(parts[0]).toBe("C:\\Program Files\\Git\\usr\\bin");
568
+ expect(parts).not.toContain("%PATH%");
569
+ } finally {
570
+ process.env.PATH = originalPath;
571
+ }
572
+ });
573
+
574
+ it("sets requested SDK env overrides and removes conflicting Claude auth/model vars", () => {
575
+ const original = {
576
+ ANTHROPIC_AUTH_TOKEN: process.env.ANTHROPIC_AUTH_TOKEN,
577
+ CLAUDE_CODE_OAUTH_TOKEN: process.env.CLAUDE_CODE_OAUTH_TOKEN,
578
+ ANTHROPIC_MODEL: process.env.ANTHROPIC_MODEL,
579
+ CLAUDE_CODE_EFFORT_LEVEL: process.env.CLAUDE_CODE_EFFORT_LEVEL,
580
+ CLAUDE_CODE_SUBAGENT_MODEL: process.env.CLAUDE_CODE_SUBAGENT_MODEL,
581
+ };
582
+
583
+ process.env.ANTHROPIC_AUTH_TOKEN = "token";
584
+ process.env.CLAUDE_CODE_OAUTH_TOKEN = "oauth";
585
+ process.env.ANTHROPIC_MODEL = "old-model";
586
+ process.env.CLAUDE_CODE_EFFORT_LEVEL = "old-effort";
587
+ process.env.CLAUDE_CODE_SUBAGENT_MODEL = "old-subagent";
588
+
589
+ try {
590
+ const env = buildSdkEnv(
591
+ " claude-haiku-4-5-20251001 ",
592
+ " sk-test ",
593
+ " https://api.example.com ",
594
+ );
595
+
596
+ expect(env).toBeDefined();
597
+ expect(env!.ANTHROPIC_AUTH_TOKEN).toBeUndefined();
598
+ expect(env!.CLAUDE_CODE_OAUTH_TOKEN).toBeUndefined();
599
+ expect(env!.ANTHROPIC_MODEL).toBeUndefined();
600
+ expect(env!.CLAUDE_CODE_EFFORT_LEVEL).toBeUndefined();
601
+ expect(env!.CLAUDE_CODE_SUBAGENT_MODEL).toBe("claude-haiku-4-5-20251001");
602
+ expect(env!.ANTHROPIC_API_KEY).toBe("sk-test");
603
+ expect(env!.ANTHROPIC_BASE_URL).toBe("https://api.example.com");
604
+ } finally {
605
+ for (const [key, value] of Object.entries(original)) {
606
+ if (value === undefined) {
607
+ delete process.env[key];
608
+ } else {
609
+ process.env[key] = value;
610
+ }
611
+ }
612
+ }
613
+ });
614
+ });