chatccc 0.2.246 → 0.2.247

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.
@@ -1,219 +1,219 @@
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-sdk/anthropic", () => ({
26
- createAnthropic: vi.fn(() => (modelId: string) => ({ modelId })),
27
- }));
28
-
29
- vi.mock("ai", () => ({
30
- streamText: aiMocks.streamText,
31
- generateText: aiMocks.generateText,
32
- isLoopFinished: vi.fn(() => ({ loopFinished: true })),
33
- stepCountIs: vi.fn((count: number) => ({ count })),
34
- jsonSchema: vi.fn((schema: unknown) => schema),
35
- tool: vi.fn((definition: unknown) => definition),
36
- }));
37
-
38
- vi.mock("../../deepccc-agent/src/raw-stream-log.ts", () => ({
39
- createRawStreamLog: vi.fn().mockResolvedValue(null),
40
- }));
41
-
42
- import {
43
- PermissionGate,
44
- getAllowRules,
45
- isDangerousCommand,
46
- matchRule,
47
- reloadAllowRules,
48
- } from "../../deepccc-agent/src/permissions.ts";
49
- import { createBuiltinFileTools } from "../../deepccc-agent/src/file-tools.ts";
50
- import { ChatSession } from "../../deepccc-agent/src/index.ts";
51
-
52
- const streamTextMock = aiMocks.streamText;
53
- const generateTextMock = aiMocks.generateText;
54
-
55
- const ALLOW_FILE = () => join(testHome.dir, ".deepccc", "allow.json");
56
-
57
- async function collect(iterable: AsyncIterable<unknown>): Promise<unknown[]> {
58
- const events: unknown[] = [];
59
- for await (const event of iterable) events.push(event);
60
- return events;
61
- }
62
-
63
- async function* textStream(...chunks: string[]): AsyncIterable<string> {
64
- for (const chunk of chunks) yield chunk;
65
- }
66
-
67
- function lastRunCommandExecute(): (input: { command: string }, opts?: unknown) => Promise<unknown> {
68
- const call = streamTextMock.mock.calls.at(-1)?.[0] as { tools?: Record<string, { execute?: unknown }> };
69
- const execute = call?.tools?.run_command?.execute as ((input: { command: string }, opts?: unknown) => Promise<unknown>) | undefined;
70
- if (!execute) throw new Error("streamText was not called with tools.run_command.execute");
71
- return execute;
72
- }
73
-
74
- afterEach(() => {
75
- try {
76
- rmSync(ALLOW_FILE(), { force: true });
77
- } catch {}
78
- reloadAllowRules();
79
- streamTextMock.mockReset();
80
- generateTextMock.mockReset();
81
- });
82
-
83
- beforeEach(() => {
84
- try {
85
- rmSync(join(testHome.dir, ".deepccc"), { recursive: true, force: true });
86
- } catch {}
87
- mkdirSync(join(testHome.dir, ".deepccc"), { recursive: true });
88
- reloadAllowRules();
89
- });
90
-
91
- describe("builtin permissions module", () => {
92
- it("flags destructive commands and ignores normal ones", () => {
93
- expect(isDangerousCommand("rm -rf node_modules")).toBe(true);
94
- expect(isDangerousCommand("git push --force origin main")).toBe(true);
95
- expect(isDangerousCommand("git status")).toBe(false);
96
- expect(isDangerousCommand("npm test")).toBe(false);
97
- });
98
-
99
- it("matches allow/deny rules with wildcards and relative paths", () => {
100
- expect(matchRule("run_command:git status*", "run_command:git status --short")).toBe(true);
101
- expect(matchRule("edit_file:node_modules/**", "edit_file:node_modules/a/b.js")).toBe(true);
102
- expect(matchRule("run_command:npm test", "run_command:npm test extra")).toBe(false);
103
- });
104
-
105
- it("returns empty rules when allow.json is missing", () => {
106
- expect(getAllowRules()).toEqual({ allow: [], deny: [] });
107
- });
108
-
109
- it("loads rules from ~/.deepccc/allow.json", () => {
110
- writeFileSync(ALLOW_FILE(), JSON.stringify({ deny: ["run_command:npm publish*"] }), "utf-8");
111
- reloadAllowRules();
112
- expect(getAllowRules().deny).toEqual(["run_command:npm publish*"]);
113
- });
114
- });
115
-
116
- describe("builtin PermissionGate", () => {
117
- it("bypass mode allows everything", async () => {
118
- const gate = new PermissionGate("bypass");
119
- expect(await gate.check({ tool: "run_command", action: "rm -rf /", reason: "high-risk", detail: "x" })).toBe("allow");
120
- });
121
-
122
- it("ask mode denies high-risk without resolver", async () => {
123
- const gate = new PermissionGate("ask");
124
- expect(await gate.check({ tool: "run_command", action: "rm -rf x", reason: "high-risk", detail: "x" })).toBe("deny");
125
- });
126
-
127
- it("ask mode allows non-high-risk operations without asking", async () => {
128
- const resolver = vi.fn();
129
- const gate = new PermissionGate("ask", resolver as never);
130
- expect(await gate.check({ tool: "run_command", action: "npm test", reason: "rule", detail: "x" })).toBe("allow");
131
- expect(await gate.check({ tool: "edit_file", action: "src/a.ts", reason: "rule", detail: "x" })).toBe("allow");
132
- expect(resolver).not.toHaveBeenCalled();
133
- });
134
-
135
- it("follows resolver answer", async () => {
136
- let answer: "allow" | "deny" = "allow";
137
- const gate = new PermissionGate("ask", async () => answer);
138
- expect(await gate.check({ tool: "run_command", action: "rm -rf x", reason: "high-risk", detail: "x" })).toBe("allow");
139
- answer = "deny";
140
- expect(await gate.check({ tool: "run_command", action: "rm -rf x", reason: "high-risk", detail: "x" })).toBe("deny");
141
- });
142
-
143
- it("deny rule wins over allow rule", async () => {
144
- writeFileSync(
145
- ALLOW_FILE(),
146
- JSON.stringify({ allow: ["run_command:rm -rf /tmp*"], deny: ["run_command:rm -rf /tmp/forbidden*"] }),
147
- "utf-8",
148
- );
149
- reloadAllowRules();
150
- const gate = new PermissionGate("ask");
151
- expect(await gate.check({ tool: "run_command", action: "rm -rf /tmp/forbidden/x", reason: "high-risk", detail: "x" })).toBe("deny");
152
- });
153
- });
154
-
155
- describe("builtin file-tools permission integration", () => {
156
- it("run_command high-risk is denied by default gate", async () => {
157
- const tools = createBuiltinFileTools(testHome.dir, { permissionGate: new PermissionGate("ask") });
158
- const tool = tools.run_command as unknown as {
159
- execute: (input: { command: string }, opts?: unknown) => Promise<unknown>;
160
- };
161
- await expect(tool.execute({ command: "rm -rf node_modules" }, { abortSignal: undefined })).rejects.toThrow(/权限拒绝/);
162
- });
163
-
164
- it("no gate keeps original behavior", async () => {
165
- const tools = createBuiltinFileTools(testHome.dir);
166
- const tool = tools.run_command as unknown as {
167
- execute: (input: { command: string }, opts?: unknown) => Promise<{ exitCode: number | null }>;
168
- };
169
- const result = await tool.execute({ command: "node -e \"console.log('ok')\"" }, { abortSignal: undefined });
170
- expect(result.exitCode).toBe(0);
171
- });
172
- });
173
-
174
- describe("builtin ChatSession permission integration", () => {
175
- it("permissionMode bypass lets high-risk run_command execute", async () => {
176
- const session = new ChatSession(
177
- { apiKey: "sk-test", provider: "openai" },
178
- { sessionId: "perm-bypass", permissionMode: "bypass" },
179
- );
180
- streamTextMock.mockReturnValueOnce({ textStream: textStream("hi") });
181
- await collect(session.chat("hi"));
182
-
183
- const result = (await lastRunCommandExecute()({ command: "node -e \"console.log('ok')\"" }, { abortSignal: undefined })) as { exitCode: number };
184
- expect(result.exitCode).toBe(0);
185
- });
186
-
187
- it("default ask mode without resolver denies high-risk run_command", async () => {
188
- const session = new ChatSession(
189
- { apiKey: "sk-test", provider: "openai" },
190
- { sessionId: "perm-ask" },
191
- );
192
- streamTextMock.mockReturnValueOnce({ textStream: textStream("hi") });
193
- await collect(session.chat("hi"));
194
-
195
- await expect(
196
- lastRunCommandExecute()({ command: "rm -rf node_modules" }, { abortSignal: undefined }),
197
- ).rejects.toThrow(/权限拒绝/);
198
- });
199
- });
200
-
201
- describe("ccc-adapter uses bypass mode (aligns with claude/codex)", () => {
202
- it("tools created via ccc adapter run high-risk commands without asking", async () => {
203
- const { createCccAdapter } = await import("../adapters/ccc-adapter.ts");
204
- const adapter = createCccAdapter({
205
- apiKey: "sk-test",
206
- provider: "openai",
207
- contextDir: testHome.dir,
208
- });
209
- const { sessionId } = await adapter.createSession(testHome.dir);
210
- streamTextMock.mockReturnValueOnce({ textStream: textStream("hi") });
211
-
212
- for await (const _m of adapter.prompt(sessionId, "hi", testHome.dir)) {
213
- // drain
214
- }
215
-
216
- const result = (await lastRunCommandExecute()({ command: "node -e \"console.log('bypass')\"" }, { abortSignal: undefined })) as { exitCode: number };
217
- expect(result.exitCode).toBe(0);
218
- });
219
- });
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-sdk/anthropic", () => ({
26
+ createAnthropic: vi.fn(() => (modelId: string) => ({ modelId })),
27
+ }));
28
+
29
+ vi.mock("ai", () => ({
30
+ streamText: aiMocks.streamText,
31
+ generateText: aiMocks.generateText,
32
+ isLoopFinished: vi.fn(() => ({ loopFinished: true })),
33
+ stepCountIs: vi.fn((count: number) => ({ count })),
34
+ jsonSchema: vi.fn((schema: unknown) => schema),
35
+ tool: vi.fn((definition: unknown) => definition),
36
+ }));
37
+
38
+ vi.mock("../../deepccc-agent/src/raw-stream-log.ts", () => ({
39
+ createRawStreamLog: vi.fn().mockResolvedValue(null),
40
+ }));
41
+
42
+ import {
43
+ PermissionGate,
44
+ getAllowRules,
45
+ isDangerousCommand,
46
+ matchRule,
47
+ reloadAllowRules,
48
+ } from "../../deepccc-agent/src/permissions.ts";
49
+ import { createBuiltinFileTools } from "../../deepccc-agent/src/file-tools.ts";
50
+ import { ChatSession } from "../../deepccc-agent/src/index.ts";
51
+
52
+ const streamTextMock = aiMocks.streamText;
53
+ const generateTextMock = aiMocks.generateText;
54
+
55
+ const ALLOW_FILE = () => join(testHome.dir, ".deepccc", "allow.json");
56
+
57
+ async function collect(iterable: AsyncIterable<unknown>): Promise<unknown[]> {
58
+ const events: unknown[] = [];
59
+ for await (const event of iterable) events.push(event);
60
+ return events;
61
+ }
62
+
63
+ async function* textStream(...chunks: string[]): AsyncIterable<string> {
64
+ for (const chunk of chunks) yield chunk;
65
+ }
66
+
67
+ function lastRunCommandExecute(): (input: { command: string }, opts?: unknown) => Promise<unknown> {
68
+ const call = streamTextMock.mock.calls.at(-1)?.[0] as { tools?: Record<string, { execute?: unknown }> };
69
+ const execute = call?.tools?.run_command?.execute as ((input: { command: string }, opts?: unknown) => Promise<unknown>) | undefined;
70
+ if (!execute) throw new Error("streamText was not called with tools.run_command.execute");
71
+ return execute;
72
+ }
73
+
74
+ afterEach(() => {
75
+ try {
76
+ rmSync(ALLOW_FILE(), { force: true });
77
+ } catch {}
78
+ reloadAllowRules();
79
+ streamTextMock.mockReset();
80
+ generateTextMock.mockReset();
81
+ });
82
+
83
+ beforeEach(() => {
84
+ try {
85
+ rmSync(join(testHome.dir, ".deepccc"), { recursive: true, force: true });
86
+ } catch {}
87
+ mkdirSync(join(testHome.dir, ".deepccc"), { recursive: true });
88
+ reloadAllowRules();
89
+ });
90
+
91
+ describe("builtin permissions module", () => {
92
+ it("flags destructive commands and ignores normal ones", () => {
93
+ expect(isDangerousCommand("rm -rf node_modules")).toBe(true);
94
+ expect(isDangerousCommand("git push --force origin main")).toBe(true);
95
+ expect(isDangerousCommand("git status")).toBe(false);
96
+ expect(isDangerousCommand("npm test")).toBe(false);
97
+ });
98
+
99
+ it("matches allow/deny rules with wildcards and relative paths", () => {
100
+ expect(matchRule("run_command:git status*", "run_command:git status --short")).toBe(true);
101
+ expect(matchRule("edit_file:node_modules/**", "edit_file:node_modules/a/b.js")).toBe(true);
102
+ expect(matchRule("run_command:npm test", "run_command:npm test extra")).toBe(false);
103
+ });
104
+
105
+ it("returns empty rules when allow.json is missing", () => {
106
+ expect(getAllowRules()).toEqual({ allow: [], deny: [] });
107
+ });
108
+
109
+ it("loads rules from ~/.deepccc/allow.json", () => {
110
+ writeFileSync(ALLOW_FILE(), JSON.stringify({ deny: ["run_command:npm publish*"] }), "utf-8");
111
+ reloadAllowRules();
112
+ expect(getAllowRules().deny).toEqual(["run_command:npm publish*"]);
113
+ });
114
+ });
115
+
116
+ describe("builtin PermissionGate", () => {
117
+ it("bypass mode allows everything", async () => {
118
+ const gate = new PermissionGate("bypass");
119
+ expect(await gate.check({ tool: "run_command", action: "rm -rf /", reason: "high-risk", detail: "x" })).toBe("allow");
120
+ });
121
+
122
+ it("ask mode denies high-risk without resolver", async () => {
123
+ const gate = new PermissionGate("ask");
124
+ expect(await gate.check({ tool: "run_command", action: "rm -rf x", reason: "high-risk", detail: "x" })).toBe("deny");
125
+ });
126
+
127
+ it("ask mode allows non-high-risk operations without asking", async () => {
128
+ const resolver = vi.fn();
129
+ const gate = new PermissionGate("ask", resolver as never);
130
+ expect(await gate.check({ tool: "run_command", action: "npm test", reason: "rule", detail: "x" })).toBe("allow");
131
+ expect(await gate.check({ tool: "edit_file", action: "src/a.ts", reason: "rule", detail: "x" })).toBe("allow");
132
+ expect(resolver).not.toHaveBeenCalled();
133
+ });
134
+
135
+ it("follows resolver answer", async () => {
136
+ let answer: "allow" | "deny" = "allow";
137
+ const gate = new PermissionGate("ask", async () => answer);
138
+ expect(await gate.check({ tool: "run_command", action: "rm -rf x", reason: "high-risk", detail: "x" })).toBe("allow");
139
+ answer = "deny";
140
+ expect(await gate.check({ tool: "run_command", action: "rm -rf x", reason: "high-risk", detail: "x" })).toBe("deny");
141
+ });
142
+
143
+ it("deny rule wins over allow rule", async () => {
144
+ writeFileSync(
145
+ ALLOW_FILE(),
146
+ JSON.stringify({ allow: ["run_command:rm -rf /tmp*"], deny: ["run_command:rm -rf /tmp/forbidden*"] }),
147
+ "utf-8",
148
+ );
149
+ reloadAllowRules();
150
+ const gate = new PermissionGate("ask");
151
+ expect(await gate.check({ tool: "run_command", action: "rm -rf /tmp/forbidden/x", reason: "high-risk", detail: "x" })).toBe("deny");
152
+ });
153
+ });
154
+
155
+ describe("builtin file-tools permission integration", () => {
156
+ it("run_command high-risk is denied by default gate", async () => {
157
+ const tools = createBuiltinFileTools(testHome.dir, { permissionGate: new PermissionGate("ask") });
158
+ const tool = tools.run_command as unknown as {
159
+ execute: (input: { command: string }, opts?: unknown) => Promise<unknown>;
160
+ };
161
+ await expect(tool.execute({ command: "rm -rf node_modules" }, { abortSignal: undefined })).rejects.toThrow(/权限拒绝/);
162
+ });
163
+
164
+ it("no gate keeps original behavior", async () => {
165
+ const tools = createBuiltinFileTools(testHome.dir);
166
+ const tool = tools.run_command as unknown as {
167
+ execute: (input: { command: string }, opts?: unknown) => Promise<{ exitCode: number | null }>;
168
+ };
169
+ const result = await tool.execute({ command: "node -e \"console.log('ok')\"" }, { abortSignal: undefined });
170
+ expect(result.exitCode).toBe(0);
171
+ });
172
+ });
173
+
174
+ describe("builtin ChatSession permission integration", () => {
175
+ it("permissionMode bypass lets high-risk run_command execute", async () => {
176
+ const session = new ChatSession(
177
+ { apiKey: "sk-test", provider: "openai" },
178
+ { sessionId: "perm-bypass", permissionMode: "bypass" },
179
+ );
180
+ streamTextMock.mockReturnValueOnce({ textStream: textStream("hi") });
181
+ await collect(session.chat("hi"));
182
+
183
+ const result = (await lastRunCommandExecute()({ command: "node -e \"console.log('ok')\"" }, { abortSignal: undefined })) as { exitCode: number };
184
+ expect(result.exitCode).toBe(0);
185
+ });
186
+
187
+ it("default ask mode without resolver denies high-risk run_command", async () => {
188
+ const session = new ChatSession(
189
+ { apiKey: "sk-test", provider: "openai" },
190
+ { sessionId: "perm-ask" },
191
+ );
192
+ streamTextMock.mockReturnValueOnce({ textStream: textStream("hi") });
193
+ await collect(session.chat("hi"));
194
+
195
+ await expect(
196
+ lastRunCommandExecute()({ command: "rm -rf node_modules" }, { abortSignal: undefined }),
197
+ ).rejects.toThrow(/权限拒绝/);
198
+ });
199
+ });
200
+
201
+ describe("ccc-adapter uses bypass mode (aligns with claude/codex)", () => {
202
+ it("tools created via ccc adapter run high-risk commands without asking", async () => {
203
+ const { createCccAdapter } = await import("../adapters/ccc-adapter.ts");
204
+ const adapter = createCccAdapter({
205
+ apiKey: "sk-test",
206
+ provider: "openai",
207
+ contextDir: testHome.dir,
208
+ });
209
+ const { sessionId } = await adapter.createSession(testHome.dir);
210
+ streamTextMock.mockReturnValueOnce({ textStream: textStream("hi") });
211
+
212
+ for await (const _m of adapter.prompt(sessionId, "hi", testHome.dir)) {
213
+ // drain
214
+ }
215
+
216
+ const result = (await lastRunCommandExecute()({ command: "node -e \"console.log('bypass')\"" }, { abortSignal: undefined })) as { exitCode: number };
217
+ expect(result.exitCode).toBe(0);
218
+ });
219
+ });