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,211 +1,211 @@
1
- import { mkdtempSync, mkdirSync, rmSync, writeFileSync, existsSync } from "node:fs";
2
- import { tmpdir } from "node:os";
3
- import { join } from "node:path";
4
-
5
- import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
6
-
7
- const testHome = vi.hoisted(() => ({ dir: "" }));
8
-
9
- const aiMocks = vi.hoisted(() => ({
10
- streamText: vi.fn(),
11
- generateText: vi.fn(),
12
- }));
13
-
14
- vi.mock("node:os", async () => {
15
- const actual = await vi.importActual<typeof import("node:os")>("node:os");
16
- const [{ mkdtempSync }, { join }] = await Promise.all([import("node:fs"), import("node:path")]);
17
- testHome.dir = mkdtempSync(join(actual.tmpdir(), "chatccc-builtin-perm-"));
18
- return { ...actual, homedir: () => testHome.dir };
19
- });
20
-
21
- vi.mock("@ai-sdk/openai-compatible", () => ({
22
- createOpenAICompatible: vi.fn(() => (modelId: string) => ({ modelId })),
23
- }));
24
-
25
- vi.mock("ai", () => ({
26
- streamText: aiMocks.streamText,
27
- generateText: aiMocks.generateText,
28
- isLoopFinished: vi.fn(() => ({ loopFinished: true })),
29
- stepCountIs: vi.fn((count: number) => ({ count })),
30
- jsonSchema: vi.fn((schema: unknown) => schema),
31
- tool: vi.fn((definition: unknown) => definition),
32
- }));
33
-
34
- vi.mock("../builtin/raw-stream-log.ts", () => ({
35
- createRawStreamLog: vi.fn().mockResolvedValue(null),
36
- }));
37
-
38
- import {
39
- PermissionGate,
40
- getAllowRules,
41
- isDangerousCommand,
42
- matchRule,
43
- reloadAllowRules,
44
- } from "../builtin/permissions.ts";
45
- import { createBuiltinFileTools } from "../builtin/file-tools.ts";
46
- import { ChatSession } from "../builtin/index.ts";
47
-
48
- const streamTextMock = aiMocks.streamText;
49
- const generateTextMock = aiMocks.generateText;
50
-
51
- const ALLOW_FILE = () => join(testHome.dir, ".deepccc", "allow.json");
52
-
53
- async function collect(iterable: AsyncIterable<unknown>): Promise<unknown[]> {
54
- const events: unknown[] = [];
55
- for await (const event of iterable) events.push(event);
56
- return events;
57
- }
58
-
59
- async function* textStream(...chunks: string[]): AsyncIterable<string> {
60
- for (const chunk of chunks) yield chunk;
61
- }
62
-
63
- function lastRunCommandExecute(): (input: { command: string }, opts?: unknown) => Promise<unknown> {
64
- const call = streamTextMock.mock.calls.at(-1)?.[0] as { tools?: Record<string, { execute?: unknown }> };
65
- const execute = call?.tools?.run_command?.execute as ((input: { command: string }, opts?: unknown) => Promise<unknown>) | undefined;
66
- if (!execute) throw new Error("streamText was not called with tools.run_command.execute");
67
- return execute;
68
- }
69
-
70
- afterEach(() => {
71
- try {
72
- rmSync(ALLOW_FILE(), { force: true });
73
- } catch {}
74
- reloadAllowRules();
75
- streamTextMock.mockReset();
76
- generateTextMock.mockReset();
77
- });
78
-
79
- beforeEach(() => {
80
- try {
81
- rmSync(join(testHome.dir, ".deepccc"), { recursive: true, force: true });
82
- } catch {}
83
- mkdirSync(join(testHome.dir, ".deepccc"), { recursive: true });
84
- reloadAllowRules();
85
- });
86
-
87
- describe("builtin permissions module", () => {
88
- it("flags destructive commands and ignores normal ones", () => {
89
- expect(isDangerousCommand("rm -rf node_modules")).toBe(true);
90
- expect(isDangerousCommand("git push --force origin main")).toBe(true);
91
- expect(isDangerousCommand("git status")).toBe(false);
92
- expect(isDangerousCommand("npm test")).toBe(false);
93
- });
94
-
95
- it("matches allow/deny rules with wildcards and relative paths", () => {
96
- expect(matchRule("run_command:git status*", "run_command:git status --short")).toBe(true);
97
- expect(matchRule("edit_file:node_modules/**", "edit_file:node_modules/a/b.js")).toBe(true);
98
- expect(matchRule("run_command:npm test", "run_command:npm test extra")).toBe(false);
99
- });
100
-
101
- it("returns empty rules when allow.json is missing", () => {
102
- expect(getAllowRules()).toEqual({ allow: [], deny: [] });
103
- });
104
-
105
- it("loads rules from ~/.deepccc/allow.json", () => {
106
- writeFileSync(ALLOW_FILE(), JSON.stringify({ deny: ["run_command:npm publish*"] }), "utf-8");
107
- reloadAllowRules();
108
- expect(getAllowRules().deny).toEqual(["run_command:npm publish*"]);
109
- });
110
- });
111
-
112
- describe("builtin PermissionGate", () => {
113
- it("bypass mode allows everything", async () => {
114
- const gate = new PermissionGate("bypass");
115
- expect(await gate.check({ tool: "run_command", action: "rm -rf /", reason: "high-risk", detail: "x" })).toBe("allow");
116
- });
117
-
118
- it("ask mode denies high-risk without resolver", async () => {
119
- const gate = new PermissionGate("ask");
120
- expect(await gate.check({ tool: "run_command", action: "rm -rf x", reason: "high-risk", detail: "x" })).toBe("deny");
121
- });
122
-
123
- it("ask mode allows non-high-risk operations without asking", async () => {
124
- const resolver = vi.fn();
125
- const gate = new PermissionGate("ask", resolver as never);
126
- expect(await gate.check({ tool: "run_command", action: "npm test", reason: "rule", detail: "x" })).toBe("allow");
127
- expect(await gate.check({ tool: "edit_file", action: "src/a.ts", reason: "rule", detail: "x" })).toBe("allow");
128
- expect(resolver).not.toHaveBeenCalled();
129
- });
130
-
131
- it("follows resolver answer", async () => {
132
- let answer: "allow" | "deny" = "allow";
133
- const gate = new PermissionGate("ask", async () => answer);
134
- expect(await gate.check({ tool: "run_command", action: "rm -rf x", reason: "high-risk", detail: "x" })).toBe("allow");
135
- answer = "deny";
136
- expect(await gate.check({ tool: "run_command", action: "rm -rf x", reason: "high-risk", detail: "x" })).toBe("deny");
137
- });
138
-
139
- it("deny rule wins over allow rule", async () => {
140
- writeFileSync(
141
- ALLOW_FILE(),
142
- JSON.stringify({ allow: ["run_command:rm -rf /tmp*"], deny: ["run_command:rm -rf /tmp/forbidden*"] }),
143
- "utf-8",
144
- );
145
- reloadAllowRules();
146
- const gate = new PermissionGate("ask");
147
- expect(await gate.check({ tool: "run_command", action: "rm -rf /tmp/forbidden/x", reason: "high-risk", detail: "x" })).toBe("deny");
148
- });
149
- });
150
-
151
- describe("builtin file-tools permission integration", () => {
152
- it("run_command high-risk is denied by default gate", async () => {
153
- const tools = createBuiltinFileTools(testHome.dir, { permissionGate: new PermissionGate("ask") });
154
- const tool = tools.run_command as unknown as {
155
- execute: (input: { command: string }, opts?: unknown) => Promise<unknown>;
156
- };
157
- await expect(tool.execute({ command: "rm -rf node_modules" }, { abortSignal: undefined })).rejects.toThrow(/权限拒绝/);
158
- });
159
-
160
- it("no gate keeps original behavior", async () => {
161
- const tools = createBuiltinFileTools(testHome.dir);
162
- const tool = tools.run_command as unknown as {
163
- execute: (input: { command: string }, opts?: unknown) => Promise<{ exitCode: number | null }>;
164
- };
165
- const result = await tool.execute({ command: "node -e \"console.log('ok')\"" }, { abortSignal: undefined });
166
- expect(result.exitCode).toBe(0);
167
- });
168
- });
169
-
170
- describe("builtin ChatSession permission integration", () => {
171
- it("permissionMode bypass lets high-risk run_command execute", async () => {
172
- const session = new ChatSession(
173
- { apiKey: "sk-test" },
174
- { sessionId: "perm-bypass", permissionMode: "bypass" },
175
- );
176
- streamTextMock.mockReturnValueOnce({ textStream: textStream("hi") });
177
- await collect(session.chat("hi"));
178
-
179
- const result = (await lastRunCommandExecute()({ command: "node -e \"console.log('ok')\"" }, { abortSignal: undefined })) as { exitCode: number };
180
- expect(result.exitCode).toBe(0);
181
- });
182
-
183
- it("default ask mode without resolver denies high-risk run_command", async () => {
184
- const session = new ChatSession(
185
- { apiKey: "sk-test" },
186
- { sessionId: "perm-ask" },
187
- );
188
- streamTextMock.mockReturnValueOnce({ textStream: textStream("hi") });
189
- await collect(session.chat("hi"));
190
-
191
- await expect(
192
- lastRunCommandExecute()({ command: "rm -rf node_modules" }, { abortSignal: undefined }),
193
- ).rejects.toThrow(/权限拒绝/);
194
- });
195
- });
196
-
197
- describe("ccc-adapter uses bypass mode (aligns with claude/codex)", () => {
198
- it("tools created via ccc adapter run high-risk commands without asking", async () => {
199
- const { createCccAdapter } = await import("../adapters/ccc-adapter.ts");
200
- const adapter = createCccAdapter({ apiKey: "sk-test", contextDir: testHome.dir });
201
- const { sessionId } = await adapter.createSession(testHome.dir);
202
- streamTextMock.mockReturnValueOnce({ textStream: textStream("hi") });
203
-
204
- for await (const _m of adapter.prompt(sessionId, "hi", testHome.dir)) {
205
- // drain
206
- }
207
-
208
- const result = (await lastRunCommandExecute()({ command: "node -e \"console.log('bypass')\"" }, { abortSignal: undefined })) as { exitCode: number };
209
- expect(result.exitCode).toBe(0);
210
- });
211
- });
1
+ import { mkdtempSync, mkdirSync, rmSync, writeFileSync, existsSync } from "node:fs";
2
+ import { tmpdir } from "node:os";
3
+ import { join } from "node:path";
4
+
5
+ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
6
+
7
+ const testHome = vi.hoisted(() => ({ dir: "" }));
8
+
9
+ const aiMocks = vi.hoisted(() => ({
10
+ streamText: vi.fn(),
11
+ generateText: vi.fn(),
12
+ }));
13
+
14
+ vi.mock("node:os", async () => {
15
+ const actual = await vi.importActual<typeof import("node:os")>("node:os");
16
+ const [{ mkdtempSync }, { join }] = await Promise.all([import("node:fs"), import("node:path")]);
17
+ testHome.dir = mkdtempSync(join(actual.tmpdir(), "chatccc-builtin-perm-"));
18
+ return { ...actual, homedir: () => testHome.dir };
19
+ });
20
+
21
+ vi.mock("@ai-sdk/openai-compatible", () => ({
22
+ createOpenAICompatible: vi.fn(() => (modelId: string) => ({ modelId })),
23
+ }));
24
+
25
+ vi.mock("ai", () => ({
26
+ streamText: aiMocks.streamText,
27
+ generateText: aiMocks.generateText,
28
+ isLoopFinished: vi.fn(() => ({ loopFinished: true })),
29
+ stepCountIs: vi.fn((count: number) => ({ count })),
30
+ jsonSchema: vi.fn((schema: unknown) => schema),
31
+ tool: vi.fn((definition: unknown) => definition),
32
+ }));
33
+
34
+ vi.mock("../builtin/raw-stream-log.ts", () => ({
35
+ createRawStreamLog: vi.fn().mockResolvedValue(null),
36
+ }));
37
+
38
+ import {
39
+ PermissionGate,
40
+ getAllowRules,
41
+ isDangerousCommand,
42
+ matchRule,
43
+ reloadAllowRules,
44
+ } from "../builtin/permissions.ts";
45
+ import { createBuiltinFileTools } from "../builtin/file-tools.ts";
46
+ import { ChatSession } from "../builtin/index.ts";
47
+
48
+ const streamTextMock = aiMocks.streamText;
49
+ const generateTextMock = aiMocks.generateText;
50
+
51
+ const ALLOW_FILE = () => join(testHome.dir, ".deepccc", "allow.json");
52
+
53
+ async function collect(iterable: AsyncIterable<unknown>): Promise<unknown[]> {
54
+ const events: unknown[] = [];
55
+ for await (const event of iterable) events.push(event);
56
+ return events;
57
+ }
58
+
59
+ async function* textStream(...chunks: string[]): AsyncIterable<string> {
60
+ for (const chunk of chunks) yield chunk;
61
+ }
62
+
63
+ function lastRunCommandExecute(): (input: { command: string }, opts?: unknown) => Promise<unknown> {
64
+ const call = streamTextMock.mock.calls.at(-1)?.[0] as { tools?: Record<string, { execute?: unknown }> };
65
+ const execute = call?.tools?.run_command?.execute as ((input: { command: string }, opts?: unknown) => Promise<unknown>) | undefined;
66
+ if (!execute) throw new Error("streamText was not called with tools.run_command.execute");
67
+ return execute;
68
+ }
69
+
70
+ afterEach(() => {
71
+ try {
72
+ rmSync(ALLOW_FILE(), { force: true });
73
+ } catch {}
74
+ reloadAllowRules();
75
+ streamTextMock.mockReset();
76
+ generateTextMock.mockReset();
77
+ });
78
+
79
+ beforeEach(() => {
80
+ try {
81
+ rmSync(join(testHome.dir, ".deepccc"), { recursive: true, force: true });
82
+ } catch {}
83
+ mkdirSync(join(testHome.dir, ".deepccc"), { recursive: true });
84
+ reloadAllowRules();
85
+ });
86
+
87
+ describe("builtin permissions module", () => {
88
+ it("flags destructive commands and ignores normal ones", () => {
89
+ expect(isDangerousCommand("rm -rf node_modules")).toBe(true);
90
+ expect(isDangerousCommand("git push --force origin main")).toBe(true);
91
+ expect(isDangerousCommand("git status")).toBe(false);
92
+ expect(isDangerousCommand("npm test")).toBe(false);
93
+ });
94
+
95
+ it("matches allow/deny rules with wildcards and relative paths", () => {
96
+ expect(matchRule("run_command:git status*", "run_command:git status --short")).toBe(true);
97
+ expect(matchRule("edit_file:node_modules/**", "edit_file:node_modules/a/b.js")).toBe(true);
98
+ expect(matchRule("run_command:npm test", "run_command:npm test extra")).toBe(false);
99
+ });
100
+
101
+ it("returns empty rules when allow.json is missing", () => {
102
+ expect(getAllowRules()).toEqual({ allow: [], deny: [] });
103
+ });
104
+
105
+ it("loads rules from ~/.deepccc/allow.json", () => {
106
+ writeFileSync(ALLOW_FILE(), JSON.stringify({ deny: ["run_command:npm publish*"] }), "utf-8");
107
+ reloadAllowRules();
108
+ expect(getAllowRules().deny).toEqual(["run_command:npm publish*"]);
109
+ });
110
+ });
111
+
112
+ describe("builtin PermissionGate", () => {
113
+ it("bypass mode allows everything", async () => {
114
+ const gate = new PermissionGate("bypass");
115
+ expect(await gate.check({ tool: "run_command", action: "rm -rf /", reason: "high-risk", detail: "x" })).toBe("allow");
116
+ });
117
+
118
+ it("ask mode denies high-risk without resolver", async () => {
119
+ const gate = new PermissionGate("ask");
120
+ expect(await gate.check({ tool: "run_command", action: "rm -rf x", reason: "high-risk", detail: "x" })).toBe("deny");
121
+ });
122
+
123
+ it("ask mode allows non-high-risk operations without asking", async () => {
124
+ const resolver = vi.fn();
125
+ const gate = new PermissionGate("ask", resolver as never);
126
+ expect(await gate.check({ tool: "run_command", action: "npm test", reason: "rule", detail: "x" })).toBe("allow");
127
+ expect(await gate.check({ tool: "edit_file", action: "src/a.ts", reason: "rule", detail: "x" })).toBe("allow");
128
+ expect(resolver).not.toHaveBeenCalled();
129
+ });
130
+
131
+ it("follows resolver answer", async () => {
132
+ let answer: "allow" | "deny" = "allow";
133
+ const gate = new PermissionGate("ask", async () => answer);
134
+ expect(await gate.check({ tool: "run_command", action: "rm -rf x", reason: "high-risk", detail: "x" })).toBe("allow");
135
+ answer = "deny";
136
+ expect(await gate.check({ tool: "run_command", action: "rm -rf x", reason: "high-risk", detail: "x" })).toBe("deny");
137
+ });
138
+
139
+ it("deny rule wins over allow rule", async () => {
140
+ writeFileSync(
141
+ ALLOW_FILE(),
142
+ JSON.stringify({ allow: ["run_command:rm -rf /tmp*"], deny: ["run_command:rm -rf /tmp/forbidden*"] }),
143
+ "utf-8",
144
+ );
145
+ reloadAllowRules();
146
+ const gate = new PermissionGate("ask");
147
+ expect(await gate.check({ tool: "run_command", action: "rm -rf /tmp/forbidden/x", reason: "high-risk", detail: "x" })).toBe("deny");
148
+ });
149
+ });
150
+
151
+ describe("builtin file-tools permission integration", () => {
152
+ it("run_command high-risk is denied by default gate", async () => {
153
+ const tools = createBuiltinFileTools(testHome.dir, { permissionGate: new PermissionGate("ask") });
154
+ const tool = tools.run_command as unknown as {
155
+ execute: (input: { command: string }, opts?: unknown) => Promise<unknown>;
156
+ };
157
+ await expect(tool.execute({ command: "rm -rf node_modules" }, { abortSignal: undefined })).rejects.toThrow(/权限拒绝/);
158
+ });
159
+
160
+ it("no gate keeps original behavior", async () => {
161
+ const tools = createBuiltinFileTools(testHome.dir);
162
+ const tool = tools.run_command as unknown as {
163
+ execute: (input: { command: string }, opts?: unknown) => Promise<{ exitCode: number | null }>;
164
+ };
165
+ const result = await tool.execute({ command: "node -e \"console.log('ok')\"" }, { abortSignal: undefined });
166
+ expect(result.exitCode).toBe(0);
167
+ });
168
+ });
169
+
170
+ describe("builtin ChatSession permission integration", () => {
171
+ it("permissionMode bypass lets high-risk run_command execute", async () => {
172
+ const session = new ChatSession(
173
+ { apiKey: "sk-test" },
174
+ { sessionId: "perm-bypass", permissionMode: "bypass" },
175
+ );
176
+ streamTextMock.mockReturnValueOnce({ textStream: textStream("hi") });
177
+ await collect(session.chat("hi"));
178
+
179
+ const result = (await lastRunCommandExecute()({ command: "node -e \"console.log('ok')\"" }, { abortSignal: undefined })) as { exitCode: number };
180
+ expect(result.exitCode).toBe(0);
181
+ });
182
+
183
+ it("default ask mode without resolver denies high-risk run_command", async () => {
184
+ const session = new ChatSession(
185
+ { apiKey: "sk-test" },
186
+ { sessionId: "perm-ask" },
187
+ );
188
+ streamTextMock.mockReturnValueOnce({ textStream: textStream("hi") });
189
+ await collect(session.chat("hi"));
190
+
191
+ await expect(
192
+ lastRunCommandExecute()({ command: "rm -rf node_modules" }, { abortSignal: undefined }),
193
+ ).rejects.toThrow(/权限拒绝/);
194
+ });
195
+ });
196
+
197
+ describe("ccc-adapter uses bypass mode (aligns with claude/codex)", () => {
198
+ it("tools created via ccc adapter run high-risk commands without asking", async () => {
199
+ const { createCccAdapter } = await import("../adapters/ccc-adapter.ts");
200
+ const adapter = createCccAdapter({ apiKey: "sk-test", contextDir: testHome.dir });
201
+ const { sessionId } = await adapter.createSession(testHome.dir);
202
+ streamTextMock.mockReturnValueOnce({ textStream: textStream("hi") });
203
+
204
+ for await (const _m of adapter.prompt(sessionId, "hi", testHome.dir)) {
205
+ // drain
206
+ }
207
+
208
+ const result = (await lastRunCommandExecute()({ command: "node -e \"console.log('bypass')\"" }, { abortSignal: undefined })) as { exitCode: number };
209
+ expect(result.exitCode).toBe(0);
210
+ });
211
+ });
@@ -0,0 +1,228 @@
1
+ import { mkdir, mkdtemp, writeFile } from "node:fs/promises";
2
+ import { tmpdir } from "node:os";
3
+ import { join } from "node:path";
4
+ import { gzipSync } from "node:zlib";
5
+
6
+ import { describe, expect, it } from "vitest";
7
+
8
+ import { searchBuiltinSessions } from "../builtin/session-search.ts";
9
+
10
+ interface TestMessage {
11
+ role: "user" | "assistant";
12
+ content: string;
13
+ toolCalls?: Array<{ name: string; input?: string; output?: string; is_error?: boolean }>;
14
+ }
15
+
16
+ async function writeContextSession(
17
+ contextDir: string,
18
+ sessionId: string,
19
+ state: { summary?: string; messages?: TestMessage[] },
20
+ ): Promise<void> {
21
+ const dir = join(contextDir, sessionId);
22
+ await mkdir(dir, { recursive: true });
23
+ await writeFile(
24
+ join(dir, "context.json"),
25
+ JSON.stringify({
26
+ version: 1,
27
+ createdAt: 1,
28
+ updatedAt: 2,
29
+ sessionId,
30
+ summary: state.summary ?? "",
31
+ messages: state.messages ?? [],
32
+ totalMessages: (state.messages ?? []).length,
33
+ compactedMessages: 0,
34
+ }),
35
+ "utf8",
36
+ );
37
+ }
38
+
39
+ describe("searchBuiltinSessions (context.json)", () => {
40
+ it("finds matching messages and summary across sessions", async () => {
41
+ const contextDir = await mkdtemp(join(tmpdir(), "deepccc-search-basic-"));
42
+ await writeContextSession(contextDir, "session-a", {
43
+ summary: "## 当前任务\n- 修复飞书卡片渲染",
44
+ messages: [{ role: "user", content: "你好" }],
45
+ });
46
+ await writeContextSession(contextDir, "session-b", {
47
+ messages: [
48
+ { role: "assistant", content: "我修改了飞书卡片组件并运行了测试" },
49
+ ],
50
+ });
51
+
52
+ const output = await searchBuiltinSessions("飞书", { contextDir });
53
+
54
+ expect(output.terms).toEqual(["飞书"]);
55
+ expect(output.scannedSessions).toBe(2);
56
+ expect(output.matches).toHaveLength(2);
57
+ const sources = output.matches.map((m) => [m.sessionId, m.source]);
58
+ expect(sources).toContainEqual(["session-a", "summary"]);
59
+ expect(sources).toContainEqual(["session-b", "context"]);
60
+ expect(output.matches[1]).toMatchObject({
61
+ sessionId: "session-b",
62
+ source: "context",
63
+ role: "assistant",
64
+ messageIndex: 0,
65
+ });
66
+ });
67
+
68
+ it("matches all terms with AND semantics, case-insensitively", async () => {
69
+ const contextDir = await mkdtemp(join(tmpdir(), "deepccc-search-and-"));
70
+ await writeContextSession(contextDir, "both", {
71
+ messages: [{ role: "assistant", content: "DeepCCC deploy 到生产环境成功" }],
72
+ });
73
+ await writeContextSession(contextDir, "one-term", {
74
+ messages: [{ role: "assistant", content: "只提到 deploy" }],
75
+ });
76
+
77
+ const output = await searchBuiltinSessions("deepccc deploy", { contextDir });
78
+
79
+ expect(output.matches.map((m) => m.sessionId)).toEqual(["both"]);
80
+ });
81
+
82
+ it("searches structured tool calls and reports tool indexes", async () => {
83
+ const contextDir = await mkdtemp(join(tmpdir(), "deepccc-search-tools-"));
84
+ await writeContextSession(contextDir, "tool-session", {
85
+ messages: [
86
+ {
87
+ role: "assistant",
88
+ content: "回复正文",
89
+ toolCalls: [
90
+ { name: "run_command", input: "{\"command\":\"npm test\"}", output: "{\"exitCode\":0}" },
91
+ { name: "read_file", input: "{\"path\":\"secret-key.txt\"}" },
92
+ ],
93
+ },
94
+ ],
95
+ });
96
+
97
+ const output = await searchBuiltinSessions("secret-key", { contextDir });
98
+
99
+ expect(output.matches).toHaveLength(1);
100
+ expect(output.matches[0]).toMatchObject({
101
+ sessionId: "tool-session",
102
+ source: "context",
103
+ messageIndex: 0,
104
+ toolCallIndex: 1,
105
+ toolCallName: "read_file",
106
+ });
107
+ expect(output.matches[0].snippet).toContain("secret-key");
108
+ });
109
+
110
+ it("restricts search to an explicit session id", async () => {
111
+ const contextDir = await mkdtemp(join(tmpdir(), "deepccc-search-restrict-"));
112
+ await writeContextSession(contextDir, "keep-me", {
113
+ messages: [{ role: "user", content: "目标关键词 token-xyz" }],
114
+ });
115
+ await writeContextSession(contextDir, "skip-me", {
116
+ messages: [{ role: "user", content: "目标关键词 token-xyz" }],
117
+ });
118
+
119
+ const output = await searchBuiltinSessions("token-xyz", {
120
+ contextDir,
121
+ sessionId: "keep-me",
122
+ });
123
+
124
+ expect(output.matches.map((m) => m.sessionId)).toEqual(["keep-me"]);
125
+ expect(output.scannedSessions).toBe(1);
126
+ });
127
+
128
+ it("caps results and reports truncation", async () => {
129
+ const contextDir = await mkdtemp(join(tmpdir(), "deepccc-search-cap-"));
130
+ for (let index = 0; index < 5; index += 1) {
131
+ await writeContextSession(contextDir, `session-${index}`, {
132
+ messages: [{ role: "user", content: "共同关键词 shared-term" }],
133
+ });
134
+ }
135
+
136
+ const output = await searchBuiltinSessions("shared-term", { contextDir, maxResults: 3 });
137
+
138
+ expect(output.matches).toHaveLength(3);
139
+ expect(output.truncated).toBe(true);
140
+ });
141
+
142
+ it("returns an empty result for empty query or missing directory", async () => {
143
+ const contextDir = await mkdtemp(join(tmpdir(), "deepccc-search-empty-"));
144
+ await writeContextSession(contextDir, "some", {
145
+ messages: [{ role: "user", content: "内容" }],
146
+ });
147
+
148
+ const empty = await searchBuiltinSessions(" ", { contextDir });
149
+ expect(empty.matches).toEqual([]);
150
+ expect(empty.truncated).toBe(false);
151
+
152
+ const missing = await searchBuiltinSessions("内容", {
153
+ contextDir: join(contextDir, "does-not-exist"),
154
+ });
155
+ expect(missing.matches).toEqual([]);
156
+ expect(missing.scannedSessions).toBe(0);
157
+ });
158
+
159
+ it("skips corrupted context files without failing", async () => {
160
+ const contextDir = await mkdtemp(join(tmpdir(), "deepccc-search-corrupt-"));
161
+ await writeContextSession(contextDir, "good", {
162
+ messages: [{ role: "user", content: "可搜索内容 needle-42" }],
163
+ });
164
+ const corruptDir = join(contextDir, "corrupt");
165
+ await mkdir(corruptDir);
166
+ await writeFile(join(corruptDir, "context.json"), "not json{{{", "utf8");
167
+
168
+ const output = await searchBuiltinSessions("needle-42", { contextDir });
169
+
170
+ expect(output.matches.map((m) => m.sessionId)).toEqual(["good"]);
171
+ expect(output.scannedSessions).toBe(1);
172
+ });
173
+ });
174
+
175
+ describe("searchBuiltinSessions (raw stream logs)", () => {
176
+ it("searches gzipped jsonl logs only when enabled", async () => {
177
+ const contextDir = await mkdtemp(join(tmpdir(), "deepccc-search-raw-context-"));
178
+ const rawLogsDir = await mkdtemp(join(tmpdir(), "deepccc-search-raw-logs-"));
179
+ await writeContextSession(contextDir, "raw-session", {
180
+ messages: [{ role: "user", content: "无关键词" }],
181
+ });
182
+
183
+ const sessionDir = join(rawLogsDir, "deepccc", "raw-session");
184
+ await mkdir(sessionDir, { recursive: true });
185
+ const lines = [
186
+ JSON.stringify({ type: "text-delta", text: "普通输出" }),
187
+ JSON.stringify({ type: "tool-call", toolCallId: "c1", toolName: "run_command", input: { command: "git push --force origin" } }),
188
+ JSON.stringify({ type: "tool-result", toolCallId: "c1", toolName: "run_command", output: { exitCode: 0, stdout: "done" } }),
189
+ ];
190
+ await writeFile(join(sessionDir, "2026-08-04T00-00-00-000Z-prompt.jsonl.gz"), gzipSync(lines.join("\n")), "utf8");
191
+
192
+ const disabled = await searchBuiltinSessions("git push", {
193
+ contextDir,
194
+ rawLogsDir,
195
+ includeRawLogs: false,
196
+ });
197
+ expect(disabled.matches).toHaveLength(0);
198
+
199
+ const enabled = await searchBuiltinSessions("git push", {
200
+ contextDir,
201
+ rawLogsDir,
202
+ includeRawLogs: true,
203
+ });
204
+ expect(enabled.matches).toHaveLength(1);
205
+ expect(enabled.matches[0]).toMatchObject({
206
+ sessionId: "raw-session",
207
+ source: "raw-log",
208
+ });
209
+ expect(enabled.matches[0].snippet).toContain("git push");
210
+ expect(enabled.scannedRawLogFiles).toBe(1);
211
+ });
212
+
213
+ it("ignores missing raw log roots", async () => {
214
+ const contextDir = await mkdtemp(join(tmpdir(), "deepccc-search-raw-missing-"));
215
+ await writeContextSession(contextDir, "s", {
216
+ messages: [{ role: "user", content: "关键词 kw-77" }],
217
+ });
218
+
219
+ const output = await searchBuiltinSessions("kw-77", {
220
+ contextDir,
221
+ rawLogsDir: join(contextDir, "no-raw-logs"),
222
+ includeRawLogs: true,
223
+ });
224
+
225
+ expect(output.matches.map((m) => m.source)).toEqual(["context"]);
226
+ expect(output.scannedRawLogFiles).toBe(0);
227
+ });
228
+ });