chatccc 0.2.230 → 0.2.231

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 (116) 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 -76
  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 +65 -1
  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 +202 -163
  28. package/src/__tests__/builtin-permissions.test.ts +211 -211
  29. package/src/__tests__/builtin-session-select.test.ts +116 -116
  30. package/src/__tests__/builtin-sigint.test.ts +56 -56
  31. package/src/__tests__/builtin-web-tools.test.ts +220 -220
  32. package/src/__tests__/card-action-routing.test.ts +18 -18
  33. package/src/__tests__/cardkit.test.ts +60 -60
  34. package/src/__tests__/ccc-adapter.test.ts +170 -136
  35. package/src/__tests__/chatgpt-subscription-rpc.test.ts +89 -89
  36. package/src/__tests__/chatgpt-subscription.test.ts +135 -135
  37. package/src/__tests__/chrome-devtools-guard.test.ts +165 -165
  38. package/src/__tests__/claude-adapter.test.ts +614 -614
  39. package/src/__tests__/claude-raw-stream-log.test.ts +87 -87
  40. package/src/__tests__/codex-adapter.test.ts +58 -58
  41. package/src/__tests__/codex-raw-stream-log.test.ts +170 -170
  42. package/src/__tests__/codex-reset-actions.test.ts +146 -146
  43. package/src/__tests__/cursor-adapter.test.ts +268 -268
  44. package/src/__tests__/feishu-api.test.ts +60 -60
  45. package/src/__tests__/feishu-avatar.test.ts +164 -164
  46. package/src/__tests__/feishu-message-ingress.test.ts +138 -138
  47. package/src/__tests__/feishu-platform.test.ts +22 -22
  48. package/src/__tests__/format-message.test.ts +47 -47
  49. package/src/__tests__/jsonl-stream.test.ts +79 -79
  50. package/src/__tests__/package-files.test.ts +24 -24
  51. package/src/__tests__/privacy.test.ts +198 -198
  52. package/src/__tests__/progress-reducer.test.ts +121 -110
  53. package/src/__tests__/raw-stream-log.test.ts +106 -106
  54. package/src/__tests__/response-stall.test.ts +49 -49
  55. package/src/__tests__/session.test.ts +11 -16
  56. package/src/__tests__/shared-prefix.test.ts +36 -36
  57. package/src/__tests__/sim-platform.test.ts +16 -16
  58. package/src/__tests__/startup-lifecycle.test.ts +231 -231
  59. package/src/__tests__/stop-session.test.ts +34 -34
  60. package/src/__tests__/stream-state.test.ts +42 -42
  61. package/src/__tests__/terminal-renderer.test.ts +247 -247
  62. package/src/__tests__/update-command-guard.test.ts +144 -144
  63. package/src/__tests__/web-ui.test.ts +326 -326
  64. package/src/adapters/adapter-interface.ts +24 -18
  65. package/src/adapters/ccc-adapter.ts +141 -131
  66. package/src/adapters/claude-adapter.ts +620 -620
  67. package/src/adapters/claude-session-meta-store.ts +120 -120
  68. package/src/adapters/codex-adapter.ts +426 -426
  69. package/src/adapters/cursor-adapter.ts +681 -681
  70. package/src/adapters/jsonl-stream.ts +157 -157
  71. package/src/adapters/raw-stream-log.ts +124 -124
  72. package/src/adapters/resource-monitor.ts +140 -140
  73. package/src/agent-activity.ts +175 -170
  74. package/src/agent-delegate-task-rpc.ts +153 -153
  75. package/src/agent-delegate-task.ts +91 -91
  76. package/src/agent-reload-config-rpc.ts +34 -34
  77. package/src/agent-stop-stuck.ts +129 -129
  78. package/src/builtin/cli.ts +9 -2
  79. package/src/builtin/config.ts +84 -84
  80. package/src/builtin/context.ts +62 -4
  81. package/src/builtin/file-log.ts +38 -38
  82. package/src/builtin/index.ts +83 -19
  83. package/src/builtin/proc-tree-kill.ts +61 -61
  84. package/src/builtin/progress/cards-helpers.ts +76 -76
  85. package/src/builtin/progress/reducer.ts +113 -108
  86. package/src/builtin/progress/terminal-renderer.ts +294 -294
  87. package/src/builtin/progress/view.ts +77 -77
  88. package/src/builtin/raw-stream-log.ts +124 -124
  89. package/src/builtin/session-select.ts +48 -48
  90. package/src/builtin/sigint.ts +50 -50
  91. package/src/builtin/web-tools.ts +313 -313
  92. package/src/card-action-routing.ts +14 -14
  93. package/src/chatgpt-subscription-rpc.ts +27 -27
  94. package/src/chatgpt-subscription.ts +299 -299
  95. package/src/chrome-devtools-guard.ts +318 -318
  96. package/src/codex-reset-actions.ts +184 -184
  97. package/src/feishu-api.ts +193 -193
  98. package/src/feishu-message-ingress.ts +195 -195
  99. package/src/feishu-platform.ts +20 -20
  100. package/src/format-message.ts +293 -293
  101. package/src/litellm-proxy.ts +374 -374
  102. package/src/platform-adapter.ts +6 -6
  103. package/src/privacy.ts +118 -118
  104. package/src/progress/reducer.ts +113 -108
  105. package/src/progress/terminal-renderer.ts +294 -294
  106. package/src/progress/view.ts +77 -77
  107. package/src/response-stall.ts +28 -28
  108. package/src/runtime-reload.ts +34 -34
  109. package/src/session-chat-binding.ts +82 -82
  110. package/src/session-name.ts +8 -8
  111. package/src/session.ts +12 -11
  112. package/src/shared-prefix.ts +29 -29
  113. package/src/sim-platform.ts +20 -20
  114. package/src/startup-lifecycle.ts +250 -250
  115. package/src/turn-cards.ts +117 -117
  116. 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
+ });
@@ -1,116 +1,116 @@
1
- import { mkdir, mkdtemp, writeFile } from "node:fs/promises";
2
- import { tmpdir } from "node:os";
3
- import { join } from "node:path";
4
-
5
- import { describe, expect, it } from "vitest";
6
-
7
- import { defaultBuiltinSessionId } from "../builtin/context.ts";
8
- import { resolveBuiltinSession } from "../builtin/session-select.ts";
9
-
10
- async function writeSession(
11
- contextDir: string,
12
- sessionId: string,
13
- options: { cwd?: string; updatedAt: number; totalMessages?: number },
14
- ): Promise<void> {
15
- const dir = join(contextDir, sessionId);
16
- await mkdir(dir, { recursive: true });
17
- await writeFile(
18
- join(dir, "context.json"),
19
- JSON.stringify({
20
- version: 1,
21
- createdAt: options.updatedAt,
22
- updatedAt: options.updatedAt,
23
- sessionId,
24
- ...(options.cwd ? { cwd: options.cwd } : {}),
25
- summary: "",
26
- messages: [],
27
- totalMessages: options.totalMessages ?? 0,
28
- compactedMessages: 0,
29
- }),
30
- "utf8",
31
- );
32
- }
33
-
34
- describe("resolveBuiltinSession", () => {
35
- it("creates a fresh timestamp session by default", async () => {
36
- const contextDir = await mkdtemp(join(tmpdir(), "chatccc-session-select-new-"));
37
-
38
- const result = resolveBuiltinSession({
39
- cwd: "C:\\repo",
40
- contextDir,
41
- now: new Date(2026, 6, 2, 12, 15, 30),
42
- randomSuffix: "a1b2c3",
43
- });
44
-
45
- expect(result).toEqual({
46
- mode: "new",
47
- sessionId: "session-20260702-121530-a1b2c3",
48
- });
49
- });
50
-
51
- it("resumes an explicit existing session id", async () => {
52
- const contextDir = join(tmpdir(), `chatccc-session-select-explicit-${Date.now()}`);
53
- await writeSession(contextDir, "manual-session", { updatedAt: 1 });
54
-
55
- expect(resolveBuiltinSession({
56
- cwd: "C:\\repo",
57
- contextDir,
58
- resume: "manual-session",
59
- })).toEqual({
60
- mode: "resumed",
61
- sessionId: "manual-session",
62
- });
63
- });
64
-
65
- it("fails when an explicit session id does not exist", async () => {
66
- const contextDir = join(tmpdir(), `chatccc-session-select-missing-${Date.now()}`);
67
-
68
- expect(() => resolveBuiltinSession({
69
- cwd: "C:\\repo",
70
- contextDir,
71
- resume: "missing",
72
- })).toThrow("DeepCCC session not found: missing");
73
- });
74
-
75
- it("resumes the newest session for cwd when resume has no id", async () => {
76
- const contextDir = join(tmpdir(), `chatccc-session-select-cwd-${Date.now()}`);
77
- await writeSession(contextDir, "old-match", { cwd: "C:\\repo", updatedAt: 1_000 });
78
- await writeSession(contextDir, "new-match", { cwd: "C:\\repo", updatedAt: 2_000 });
79
- await writeSession(contextDir, "other-cwd", { cwd: "C:\\other", updatedAt: 3_000 });
80
-
81
- expect(resolveBuiltinSession({
82
- cwd: "C:\\repo",
83
- contextDir,
84
- resume: true,
85
- })).toEqual({
86
- mode: "resumed",
87
- sessionId: "new-match",
88
- });
89
- });
90
-
91
- it("resumes legacy cwd-hash sessions when resume has no id", async () => {
92
- const contextDir = join(tmpdir(), `chatccc-session-select-legacy-${Date.now()}`);
93
- const cwd = "C:\\repo";
94
- const legacySessionId = defaultBuiltinSessionId(cwd);
95
- await writeSession(contextDir, legacySessionId, { updatedAt: 1_000 });
96
-
97
- expect(resolveBuiltinSession({
98
- cwd,
99
- contextDir,
100
- resume: true,
101
- })).toEqual({
102
- mode: "resumed",
103
- sessionId: legacySessionId,
104
- });
105
- });
106
-
107
- it("fails when there is no cwd session to resume", async () => {
108
- const contextDir = join(tmpdir(), `chatccc-session-select-empty-${Date.now()}`);
109
-
110
- expect(() => resolveBuiltinSession({
111
- cwd: "C:\\repo",
112
- contextDir,
113
- resume: true,
114
- })).toThrow("No resumable DeepCCC session found for cwd: C:\\repo");
115
- });
116
- });
1
+ import { mkdir, mkdtemp, writeFile } from "node:fs/promises";
2
+ import { tmpdir } from "node:os";
3
+ import { join } from "node:path";
4
+
5
+ import { describe, expect, it } from "vitest";
6
+
7
+ import { defaultBuiltinSessionId } from "../builtin/context.ts";
8
+ import { resolveBuiltinSession } from "../builtin/session-select.ts";
9
+
10
+ async function writeSession(
11
+ contextDir: string,
12
+ sessionId: string,
13
+ options: { cwd?: string; updatedAt: number; totalMessages?: number },
14
+ ): Promise<void> {
15
+ const dir = join(contextDir, sessionId);
16
+ await mkdir(dir, { recursive: true });
17
+ await writeFile(
18
+ join(dir, "context.json"),
19
+ JSON.stringify({
20
+ version: 1,
21
+ createdAt: options.updatedAt,
22
+ updatedAt: options.updatedAt,
23
+ sessionId,
24
+ ...(options.cwd ? { cwd: options.cwd } : {}),
25
+ summary: "",
26
+ messages: [],
27
+ totalMessages: options.totalMessages ?? 0,
28
+ compactedMessages: 0,
29
+ }),
30
+ "utf8",
31
+ );
32
+ }
33
+
34
+ describe("resolveBuiltinSession", () => {
35
+ it("creates a fresh timestamp session by default", async () => {
36
+ const contextDir = await mkdtemp(join(tmpdir(), "chatccc-session-select-new-"));
37
+
38
+ const result = resolveBuiltinSession({
39
+ cwd: "C:\\repo",
40
+ contextDir,
41
+ now: new Date(2026, 6, 2, 12, 15, 30),
42
+ randomSuffix: "a1b2c3",
43
+ });
44
+
45
+ expect(result).toEqual({
46
+ mode: "new",
47
+ sessionId: "session-20260702-121530-a1b2c3",
48
+ });
49
+ });
50
+
51
+ it("resumes an explicit existing session id", async () => {
52
+ const contextDir = join(tmpdir(), `chatccc-session-select-explicit-${Date.now()}`);
53
+ await writeSession(contextDir, "manual-session", { updatedAt: 1 });
54
+
55
+ expect(resolveBuiltinSession({
56
+ cwd: "C:\\repo",
57
+ contextDir,
58
+ resume: "manual-session",
59
+ })).toEqual({
60
+ mode: "resumed",
61
+ sessionId: "manual-session",
62
+ });
63
+ });
64
+
65
+ it("fails when an explicit session id does not exist", async () => {
66
+ const contextDir = join(tmpdir(), `chatccc-session-select-missing-${Date.now()}`);
67
+
68
+ expect(() => resolveBuiltinSession({
69
+ cwd: "C:\\repo",
70
+ contextDir,
71
+ resume: "missing",
72
+ })).toThrow("DeepCCC session not found: missing");
73
+ });
74
+
75
+ it("resumes the newest session for cwd when resume has no id", async () => {
76
+ const contextDir = join(tmpdir(), `chatccc-session-select-cwd-${Date.now()}`);
77
+ await writeSession(contextDir, "old-match", { cwd: "C:\\repo", updatedAt: 1_000 });
78
+ await writeSession(contextDir, "new-match", { cwd: "C:\\repo", updatedAt: 2_000 });
79
+ await writeSession(contextDir, "other-cwd", { cwd: "C:\\other", updatedAt: 3_000 });
80
+
81
+ expect(resolveBuiltinSession({
82
+ cwd: "C:\\repo",
83
+ contextDir,
84
+ resume: true,
85
+ })).toEqual({
86
+ mode: "resumed",
87
+ sessionId: "new-match",
88
+ });
89
+ });
90
+
91
+ it("resumes legacy cwd-hash sessions when resume has no id", async () => {
92
+ const contextDir = join(tmpdir(), `chatccc-session-select-legacy-${Date.now()}`);
93
+ const cwd = "C:\\repo";
94
+ const legacySessionId = defaultBuiltinSessionId(cwd);
95
+ await writeSession(contextDir, legacySessionId, { updatedAt: 1_000 });
96
+
97
+ expect(resolveBuiltinSession({
98
+ cwd,
99
+ contextDir,
100
+ resume: true,
101
+ })).toEqual({
102
+ mode: "resumed",
103
+ sessionId: legacySessionId,
104
+ });
105
+ });
106
+
107
+ it("fails when there is no cwd session to resume", async () => {
108
+ const contextDir = join(tmpdir(), `chatccc-session-select-empty-${Date.now()}`);
109
+
110
+ expect(() => resolveBuiltinSession({
111
+ cwd: "C:\\repo",
112
+ contextDir,
113
+ resume: true,
114
+ })).toThrow("No resumable DeepCCC session found for cwd: C:\\repo");
115
+ });
116
+ });