chatccc 0.2.190 → 0.2.191

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