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,34 +1,34 @@
1
- import { afterEach, describe, expect, it } from "vitest";
2
-
3
- import { ChatSession } from "../index.js";
4
- import { config, normalizeDeepCccProvider } from "../config.js";
5
-
6
- const originalDeepSeekApiKey = process.env.DEEPSEEK_API_KEY;
7
- const originalDeepCccApiKey = config.apiKey;
8
-
9
- afterEach(() => {
10
- if (originalDeepSeekApiKey === undefined) {
11
- delete process.env.DEEPSEEK_API_KEY;
12
- } else {
13
- process.env.DEEPSEEK_API_KEY = originalDeepSeekApiKey;
14
- }
15
- config.apiKey = originalDeepCccApiKey;
16
- });
17
-
18
- describe("builtin ChatSession config", () => {
19
- it("defaults provider selection to openai and accepts anthropic case-insensitively", () => {
20
- expect(normalizeDeepCccProvider(undefined)).toBe("openai");
21
- expect(normalizeDeepCccProvider("")).toBe("openai");
22
- expect(normalizeDeepCccProvider("OPENAI")).toBe("openai");
23
- expect(normalizeDeepCccProvider("Anthropic")).toBe("anthropic");
24
- expect(() => normalizeDeepCccProvider("antropic")).toThrow(/openai.*anthropic/i);
25
- });
26
-
27
- it("uses the builtin ~/.deepccc config when no apiKey is passed", () => {
28
- expect(() => new ChatSession()).not.toThrow();
29
- });
30
-
31
- it("allows constructor parameters to override config defaults", () => {
32
- expect(() => new ChatSession({ apiKey: "sk-test" })).not.toThrow();
33
- });
34
- });
1
+ import { afterEach, describe, expect, it } from "vitest";
2
+
3
+ import { ChatSession } from "../index.js";
4
+ import { config, normalizeDeepCccProvider } from "../config.js";
5
+
6
+ const originalDeepSeekApiKey = process.env.DEEPSEEK_API_KEY;
7
+ const originalDeepCccApiKey = config.apiKey;
8
+
9
+ afterEach(() => {
10
+ if (originalDeepSeekApiKey === undefined) {
11
+ delete process.env.DEEPSEEK_API_KEY;
12
+ } else {
13
+ process.env.DEEPSEEK_API_KEY = originalDeepSeekApiKey;
14
+ }
15
+ config.apiKey = originalDeepCccApiKey;
16
+ });
17
+
18
+ describe("builtin ChatSession config", () => {
19
+ it("defaults provider selection to openai and accepts anthropic case-insensitively", () => {
20
+ expect(normalizeDeepCccProvider(undefined)).toBe("openai");
21
+ expect(normalizeDeepCccProvider("")).toBe("openai");
22
+ expect(normalizeDeepCccProvider("OPENAI")).toBe("openai");
23
+ expect(normalizeDeepCccProvider("Anthropic")).toBe("anthropic");
24
+ expect(() => normalizeDeepCccProvider("antropic")).toThrow(/openai.*anthropic/i);
25
+ });
26
+
27
+ it("uses the builtin ~/.deepccc config when no apiKey is passed", () => {
28
+ expect(() => new ChatSession()).not.toThrow();
29
+ });
30
+
31
+ it("allows constructor parameters to override config defaults", () => {
32
+ expect(() => new ChatSession({ apiKey: "sk-test" })).not.toThrow();
33
+ });
34
+ });
@@ -1,199 +1,199 @@
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("../raw-stream-log.js", () => ({
39
- createRawStreamLog: vi.fn().mockResolvedValue(null),
40
- }));
41
-
42
- import {
43
- PermissionGate,
44
- getAllowRules,
45
- isDangerousCommand,
46
- matchRule,
47
- reloadAllowRules,
48
- } from "../permissions.js";
49
- import { createBuiltinFileTools } from "../file-tools.js";
50
- import { ChatSession } from "../index.js";
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" },
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" },
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
- });
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("../raw-stream-log.js", () => ({
39
+ createRawStreamLog: vi.fn().mockResolvedValue(null),
40
+ }));
41
+
42
+ import {
43
+ PermissionGate,
44
+ getAllowRules,
45
+ isDangerousCommand,
46
+ matchRule,
47
+ reloadAllowRules,
48
+ } from "../permissions.js";
49
+ import { createBuiltinFileTools } from "../file-tools.js";
50
+ import { ChatSession } from "../index.js";
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" },
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" },
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
+ });
@@ -25,13 +25,13 @@ vi.mock("../config.js", async () => {
25
25
  };
26
26
  });
27
27
 
28
- vi.mock("@ai-sdk/openai-compatible", () => ({
29
- createOpenAICompatible: vi.fn(() => (modelId: string) => ({ modelId })),
30
- }));
31
-
32
- vi.mock("@ai-sdk/anthropic", () => ({
33
- createAnthropic: vi.fn(() => (modelId: string) => ({ modelId })),
34
- }));
28
+ vi.mock("@ai-sdk/openai-compatible", () => ({
29
+ createOpenAICompatible: vi.fn(() => (modelId: string) => ({ modelId })),
30
+ }));
31
+
32
+ vi.mock("@ai-sdk/anthropic", () => ({
33
+ createAnthropic: vi.fn(() => (modelId: string) => ({ modelId })),
34
+ }));
35
35
 
36
36
  vi.mock("ai", () => ({
37
37
  streamText: aiMocks.streamText,
@@ -59,8 +59,8 @@ import { ChatSession } from "../index.js";
59
59
  const streamTextMock = aiMocks.streamText;
60
60
  const generateTextMock = aiMocks.generateText;
61
61
 
62
- const originalRawStreamLogs = structuredClone(config.rawStreamLogs);
63
- const originalStreaming = config.streaming;
62
+ const originalRawStreamLogs = structuredClone(config.rawStreamLogs);
63
+ const originalStreaming = config.streaming;
64
64
  const PRIVACY_FILE = join(privacyState.dir, "privacy.json");
65
65
 
66
66
  function writePrivacy(content: string): void {
@@ -83,18 +83,18 @@ beforeEach(() => {
83
83
  } catch {}
84
84
  reloadPrivacyRules();
85
85
  streamTextMock.mockReset();
86
- generateTextMock.mockReset();
87
- config.rawStreamLogs = structuredClone(originalRawStreamLogs);
88
- config.streaming = true;
86
+ generateTextMock.mockReset();
87
+ config.rawStreamLogs = structuredClone(originalRawStreamLogs);
88
+ config.streaming = true;
89
89
  });
90
90
 
91
91
  afterEach(() => {
92
92
  try {
93
93
  rmSync(PRIVACY_FILE, { force: true });
94
94
  } catch {}
95
- reloadPrivacyRules();
96
- config.streaming = originalStreaming;
97
- });
95
+ reloadPrivacyRules();
96
+ config.streaming = originalStreaming;
97
+ });
98
98
 
99
99
  afterAll(() => {
100
100
  try {
@@ -11,8 +11,8 @@
11
11
  * 非 TTY(管道/CI)或 --plain 回退为纯文本流式输出;--stream-json 机器接口不变。
12
12
  */
13
13
 
14
- import * as readline from "node:readline";
15
- import process from "node:process";
14
+ import * as readline from "node:readline";
15
+ import process from "node:process";
16
16
  import { appendFileSync, existsSync, mkdirSync, writeFileSync } from "node:fs";
17
17
  import { homedir } from "node:os";
18
18
  import { join, resolve as resolvePath } from "node:path";
@@ -51,19 +51,19 @@ interface JsonLine {
51
51
  [key: string]: unknown;
52
52
  }
53
53
 
54
- function parsePositiveIntegerOption(name: string, value: string): number {
54
+ function parsePositiveIntegerOption(name: string, value: string): number {
55
55
  const parsed = Number(value);
56
56
  if (!Number.isInteger(parsed) || parsed <= 0) {
57
57
  throw new Error(`${name} must be a positive integer`);
58
58
  }
59
59
  return parsed;
60
- }
61
-
62
- function parseProviderOption(value: string): "openai" | "anthropic" {
63
- const normalized = value.trim().toLowerCase();
64
- if (normalized === "openai" || normalized === "anthropic") return normalized;
65
- throw new Error(`--provider must be "openai" or "anthropic", received: ${value}`);
66
- }
60
+ }
61
+
62
+ function parseProviderOption(value: string): "openai" | "anthropic" {
63
+ const normalized = value.trim().toLowerCase();
64
+ if (normalized === "openai" || normalized === "anthropic") return normalized;
65
+ throw new Error(`--provider must be "openai" or "anthropic", received: ${value}`);
66
+ }
67
67
 
68
68
  function parseArgs(argv = process.argv.slice(2)): ParsedArgs {
69
69
  const config: ChatSessionConfig = {};
@@ -78,10 +78,10 @@ function parseArgs(argv = process.argv.slice(2)): ParsedArgs {
78
78
  for (let i = 0; i < argv.length; i++) {
79
79
  const arg = argv[i];
80
80
  const next = argv[i + 1];
81
- if (arg === "--provider" && next !== undefined) {
82
- config.provider = parseProviderOption(next);
83
- i++;
84
- } else if (arg === "--model" && next !== undefined) {
81
+ if (arg === "--provider" && next !== undefined) {
82
+ config.provider = parseProviderOption(next);
83
+ i++;
84
+ } else if (arg === "--model" && next !== undefined) {
85
85
  config.model = next;
86
86
  i++;
87
87
  } else if (arg === "--effort" && next !== undefined) {
@@ -140,11 +140,11 @@ function printHelp(appConfig: RuntimeDeps["appConfig"]): void {
140
140
  "",
141
141
  "Usage: deepccc [options]",
142
142
  "",
143
- "Options:",
144
- ` --provider <name> API protocol: openai or anthropic (current default ${appConfig.provider})`,
145
- ` --model <name> Model name (current default ${appConfig.model})`,
143
+ "Options:",
144
+ ` --provider <name> API protocol: openai or anthropic (current default ${appConfig.provider})`,
145
+ ` --model <name> Model name (current default ${appConfig.model})`,
146
146
  ` --effort <level> Reasoning effort: none/minimal/low/medium/high/xhigh/max (overrides config.effort)`,
147
- ` --base-url <url> Provider API base URL (current default ${appConfig.baseURL})`,
147
+ ` --base-url <url> Provider API base URL (current default ${appConfig.baseURL})`,
148
148
  " --api-key <key> API key",
149
149
  " --cwd <path> Working directory",
150
150
  " --max-steps <n> Optional tool-step limit. Omit for no step limit",
@@ -385,8 +385,8 @@ async function runRepl(args: ParsedArgs): Promise<void> {
385
385
  }
386
386
 
387
387
  console.log(`${C.dim}DeepCCC agent${C.reset}`);
388
- console.log(`${C.dim}Provider: ${args.config.provider ?? appConfig.provider}${C.reset}`);
389
- console.log(`${C.dim}Model: ${args.config.model ?? appConfig.model}${C.reset}`);
388
+ console.log(`${C.dim}Provider: ${args.config.provider ?? appConfig.provider}${C.reset}`);
389
+ console.log(`${C.dim}Model: ${args.config.model ?? appConfig.model}${C.reset}`);
390
390
  console.log(`${C.dim}Directory: ${cwd}${C.reset}`);
391
391
  console.log(`${C.dim}Session: ${resolvedSession.sessionId} (${resolvedSession.mode === "new" ? "new" : "resumed"})${C.reset}`);
392
392
  console.log(`${C.dim}Type a message to chat. Double Ctrl+C interrupts generation or exits. Type exit to quit.${C.reset}`);
@@ -648,11 +648,11 @@ async function main(): Promise<void> {
648
648
 
649
649
  const args = parseArgs();
650
650
 
651
- if (args.streamJson) {
652
- const code = await runStreamJson(args);
653
- process.exitCode = code;
654
- return;
655
- }
651
+ if (args.streamJson) {
652
+ const code = await runStreamJson(args);
653
+ process.exitCode = code;
654
+ return;
655
+ }
656
656
 
657
657
  if (args.help) {
658
658
  const { appConfig } = await loadRuntime();