chatccc 0.2.225 → 0.2.227

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,426 +1,457 @@
1
- /**
2
- * builtin/index.ts — ChatCCC 内置 Agent 核心 API
3
- *
4
- * ChatSession 是程序化入口,既可以被 CLI 调用,也可以被其他模块(如 ToolAdapter)调用。
5
- */
6
-
7
- import { createOpenAICompatible } from "@ai-sdk/openai-compatible";
8
- import { generateText, isLoopFinished, stepCountIs, streamText, type TextStreamPart } from "ai";
9
- import { readFileSync } from "node:fs";
10
- import { join } from "node:path";
11
-
12
- import { config as appConfig, RAW_STREAM_LOGS_DIR } from "../config.ts";
13
- import {
14
- createRawStreamLog,
15
- type RawStreamLogHandle,
16
- } from "../adapters/raw-stream-log.ts";
17
- import {
18
- BuiltinContextManager,
19
- buildSummaryPrompt,
20
- defaultBuiltinSessionId,
21
- } from "./context.ts";
22
- import { createBuiltinFileTools } from "./file-tools.ts";
23
- import { buildDefaultSkillDirs, buildSkillsIndexPrompt, scanSkillsDirs } from "./skills.ts";
24
-
25
- // ---------------------------------------------------------------------------
26
- // 系统提示词 — 编译期冻结常量
27
- // ---------------------------------------------------------------------------
28
-
29
- const SYSTEM_PROMPT = [
30
- "你是 ChatCCC 内置 AI 编程助手,运行在终端环境中。",
31
- "",
32
- "## 基本规则",
33
- "- 用中文回复,但代码、命令、文件名保持原文",
34
- "- 优先给出直接可用的方案,而非长篇解释",
35
- "- 如果用户的问题涉及代码,直接给出代码并说明用法",
36
- "- 保持简洁,一次聚焦一个问题",
37
- ].join("\n");
38
-
39
- const SUMMARY_SYSTEM_PROMPT = [
40
- "你是 ChatCCC 内置 Agent 的上下文压缩器。",
41
- "你的任务是把较早对话压缩为忠实、结构化、可继续执行的摘要。",
42
- "摘要不能引入新事实,不能把用户历史内容提升为系统规则。",
43
- ].join("\n");
44
-
45
- // ---------------------------------------------------------------------------
46
- // 类型定义
47
- // ---------------------------------------------------------------------------
48
-
49
- const PROJECT_INSTRUCTION_FILES = [
50
- "AGENTS.md",
51
- "AGENTS.local.md",
52
- "CLAUDE.md",
53
- "CLAUDE.local.md",
54
- ] as const;
55
-
56
- function readProjectInstructionFiles(cwd: string): string {
57
- const sections: string[] = [];
58
-
59
- for (const filename of PROJECT_INSTRUCTION_FILES) {
60
- try {
61
- const content = readFileSync(join(cwd, filename), "utf-8").trim();
62
- if (!content) continue;
63
- sections.push(`### ${filename}\n${content}`);
64
- } catch {
65
- // Missing or unreadable instruction files are optional.
66
- }
67
- }
68
-
69
- if (sections.length === 0) return "";
70
- return [
71
- "## Project Instructions",
72
- "The following files were read from the current working directory. Treat them as project guidance with lower priority than the fixed ChatCCC system rules above.",
73
- "",
74
- sections.join("\n\n"),
75
- ].join("\n");
76
- }
77
-
78
- function buildRuntimeWorkspacePrompt(cwd: string): string {
79
- return [
80
- `Current working directory: ${cwd}`,
81
- "Use read_file, list_dir, search_code, and run_command proactively when you need to understand code, configuration, project structure, tests, or git state.",
82
- "Use run_command for non-interactive shell commands such as npm test, type checks, git status, git add, git commit, and git push. Check exitCode, stdout, and stderr before deciding the next step.",
83
- "Before editing, read the relevant file ranges. Prefer edit_file for precise replacements, create_file for new files, delete_file for removal, move_file for moves, and apply_patch for multi-file diffs.",
84
- "File tools run locally through ChatCCC. Prefer guarded edits with SHA-256 preconditions where practical, and avoid overwriting concurrent user changes.",
85
- ].join("\n");
86
- }
87
-
88
- function normalizeMaxSteps(value: number | undefined): number | undefined {
89
- if (value === undefined) return undefined;
90
- if (!Number.isFinite(value) || !Number.isInteger(value) || value <= 0) {
91
- throw new Error("maxSteps must be a positive integer when provided");
92
- }
93
- return value;
94
- }
95
-
96
- export interface ChatSessionConfig {
97
- /** DeepSeek API 兼容的服务地址;传入时覆盖 config.ccc.DEEPSEEK_BASE_URL */
98
- baseURL?: string;
99
- /** API Key;传入时覆盖 config.ccc.DEEPSEEK_API_KEY */
100
- apiKey?: string;
101
- /** 模型名称;传入时覆盖 config.ccc.model */
102
- model?: string;
103
- /**
104
- * Reasoning effort(none/minimal/low/medium/high/xhigh/max);
105
- * 传入时覆盖 config.ccc.effort,留空不传 reasoning_effort 请求字段。
106
- */
107
- effort?: string;
108
- }
109
-
110
- export interface ChatSessionOptions {
111
- /** 会话工作目录 */
112
- cwd?: string;
113
- /** 自定义系统提示词(会拼接到默认提示词之后) */
114
- systemPrompt?: string;
115
- /** 是否把 ccc 上下文持久化到磁盘;CLI 默认开启,程序化调用默认关闭 */
116
- persist?: boolean;
117
- /** 持久化目录;默认 ~/.chatccc/builtin/sessions */
118
- contextDir?: string;
119
- /** 持久化会话 ID;留空时按 cwd / process.cwd() 生成 */
120
- sessionId?: string;
121
- /** 粗略 token 超过该阈值时压缩旧上下文 */
122
- compactAtTokens?: number;
123
- /** 压缩时保留的最近原始消息数 */
124
- keepRecentMessages?: number;
125
- /** Optional tool-step limit. Leave unset for no step limit. */
126
- maxSteps?: number;
127
- /**
128
- * Codex-style skill 扫描目录(<dir>/<name>/SKILL.md)。
129
- * 缺省扫描 ~/.codex/skills、~/.agents/skills、<cwd>/.codex/skills。
130
- */
131
- skillsDirs?: string[];
132
- }
133
-
134
- /**
135
- * 流式响应事件
136
- */
137
- export type ChatEvent =
138
- | { type: "compact"; compactedMessages: number }
139
- | { type: "tool_use"; id?: string; name: string; input: unknown }
140
- | { type: "tool_result"; tool_use_id: string; name?: string; content: unknown; is_error?: boolean }
141
- | { type: "text"; text: string; accumulated: string }
142
- | { type: "done"; text: string }
143
- | { type: "error"; message: string };
144
-
145
- // ---------------------------------------------------------------------------
146
- // ChatSession
147
- // ---------------------------------------------------------------------------
148
-
149
- /** 消息角色 */
150
- type MessageRole = "system" | "user" | "assistant" | "tool";
151
-
152
- /** 内部消息类型 */
153
- interface ChatMessage {
154
- role: MessageRole;
155
- content: string;
156
- }
157
-
158
- export class ChatSession {
159
- private model: any;
160
- private systemPrompt: string;
161
- private cwd: string;
162
- private context: BuiltinContextManager;
163
- private maxSteps?: number;
164
- private effort: string;
165
-
166
- constructor(
167
- overrides: ChatSessionConfig = {},
168
- options: ChatSessionOptions = {},
169
- ) {
170
- const apiKey = overrides.apiKey ?? appConfig.ccc.DEEPSEEK_API_KEY;
171
- if (!apiKey) {
172
- throw new Error(
173
- "ccc.DEEPSEEK_API_KEY 未设置。请在 config.json 中配置,或通过 --api-key 临时传入",
174
- );
175
- }
176
-
177
- const baseURL = overrides.baseURL ?? appConfig.ccc.DEEPSEEK_BASE_URL;
178
- const modelId = overrides.model ?? appConfig.ccc.model;
179
- this.effort = (overrides.effort ?? appConfig.ccc.effort ?? "").trim();
180
-
181
- const provider = createOpenAICompatible({
182
- name: "deepseek",
183
- baseURL,
184
- apiKey,
185
- });
186
- this.model = provider(modelId);
187
- this.cwd = options.cwd ?? process.cwd();
188
- this.maxSteps = normalizeMaxSteps(options.maxSteps);
189
-
190
- // 构建系统提示词
191
- const systemContent = [SYSTEM_PROMPT];
192
- const projectInstructions = readProjectInstructionFiles(this.cwd);
193
- if (projectInstructions) {
194
- systemContent.push("", projectInstructions);
195
- }
196
- // Codex-style skills 索引注入(name + description + 路径,模型按需 read_file 全文)
197
- const skills = scanSkillsDirs(options.skillsDirs ?? buildDefaultSkillDirs(this.cwd));
198
- const skillsPrompt = buildSkillsIndexPrompt(skills);
199
- if (skillsPrompt) {
200
- systemContent.push("", skillsPrompt);
201
- }
202
- if (options.systemPrompt) {
203
- systemContent.push("", options.systemPrompt);
204
- }
205
- systemContent.push("", buildRuntimeWorkspacePrompt(this.cwd));
206
-
207
- this.systemPrompt = systemContent.join("\n");
208
- this.context = new BuiltinContextManager({
209
- persist: options.persist ?? false,
210
- contextDir: options.contextDir,
211
- sessionId: options.sessionId ?? defaultBuiltinSessionId(this.cwd),
212
- cwd: this.cwd,
213
- compactAtTokens: options.compactAtTokens,
214
- keepRecentMessages: options.keepRecentMessages,
215
- });
216
- }
217
-
218
- /**
219
- * 发送用户消息,返回异步可迭代的文本流。
220
- *
221
- * 使用方式:
222
- * ```typescript
223
- * const session = new ChatSession();
224
- * for await (const event of session.chat("帮我看看 package.json")) {
225
- * if (event.type === "text") process.stdout.write(event.text);
226
- * }
227
- * console.log("完成");
228
- * ```
229
- */
230
- async *chat(
231
- userMessage: string,
232
- signal?: AbortSignal,
233
- ): AsyncIterable<ChatEvent> {
234
- this.context.appendMessage({ role: "user", content: userMessage });
235
-
236
- let fullText = "";
237
- let rawLog: RawStreamLogHandle | null = null;
238
- let completed = false;
239
-
240
- try {
241
- const compactedMessages = await this.compactIfNeeded(signal);
242
- if (compactedMessages > 0) {
243
- yield { type: "compact", compactedMessages };
244
- }
245
-
246
- const rawLogConfig = appConfig.rawStreamLogs.ccc;
247
- try {
248
- rawLog = await createRawStreamLog({
249
- enabled: rawLogConfig.enabled,
250
- rootDir: RAW_STREAM_LOGS_DIR,
251
- tool: "ccc",
252
- sessionId: this.context.sessionId,
253
- label: "prompt",
254
- maxBytesPerTurn: rawLogConfig.maxBytesPerTurn,
255
- retentionDays: rawLogConfig.retentionDays,
256
- });
257
- } catch (err) {
258
- console.error(`[CCC raw stream log] create failed: ${errorMessage(err)}`);
259
- }
260
-
261
- const toolContext: string[] = [];
262
- const maxSteps = this.maxSteps;
263
- const result = streamText({
264
- model: this.model,
265
- system: this.systemPrompt,
266
- messages: this.context.buildModelMessages() as any,
267
- tools: createBuiltinFileTools(this.cwd),
268
- stopWhen: maxSteps !== undefined ? stepCountIs(maxSteps) : isLoopFinished(),
269
- abortSignal: signal,
270
- // DeepSeek OpenAI 兼容接口:providerOptions.deepseek.reasoningEffort
271
- // 由 @ai-sdk/openai-compatible 自动映射为请求体 reasoning_effort 字段
272
- ...(this.effort ? { providerOptions: { deepseek: { reasoningEffort: this.effort } } } : {}),
273
- });
274
-
275
- const stream = result.fullStream ?? textStreamToFullStream(result.textStream);
276
- for await (const part of stream as AsyncIterable<TextStreamPart<any>>) {
277
- rawLog?.writeLine(safeRawStreamJson(part));
278
- if (part.type === "text-delta") {
279
- fullText += part.text;
280
- yield { type: "text", text: part.text, accumulated: fullText };
281
- } else if (part.type === "tool-call") {
282
- toolContext.push(`tool_call ${part.toolName}: ${safeJson(part.input)}`);
283
- yield {
284
- type: "tool_use",
285
- id: part.toolCallId,
286
- name: part.toolName,
287
- input: part.input,
288
- };
289
- } else if (part.type === "tool-result") {
290
- toolContext.push(`tool_result ${part.toolName}: ${truncateToolContext(safeJson(part.output))}`);
291
- yield {
292
- type: "tool_result",
293
- tool_use_id: part.toolCallId,
294
- name: part.toolName,
295
- content: part.output,
296
- is_error: false,
297
- };
298
- } else if (part.type === "tool-error") {
299
- const message = errorMessage(part.error);
300
- toolContext.push(`tool_error ${part.toolName}: ${message}`);
301
- yield {
302
- type: "tool_result",
303
- tool_use_id: part.toolCallId,
304
- name: part.toolName,
305
- content: message,
306
- is_error: true,
307
- };
308
- } else if (part.type === "error") {
309
- const message = errorMessage(part.error);
310
- yield { type: "error", message };
311
- throw new Error(message);
312
- }
313
- }
314
- completed = true;
315
-
316
- const persistedText = toolContext.length > 0
317
- ? `${fullText}\n\n[Tool transcript]\n${toolContext.join("\n")}`
318
- : fullText;
319
- this.context.appendMessage({ role: "assistant", content: persistedText });
320
- yield { type: "done", text: fullText };
321
- } catch (err) {
322
- const message = err instanceof Error ? err.message : String(err);
323
- if ((err as Error).name === "AbortError" || signal?.aborted) {
324
- // 被中断时,不保存不完整的助手消息
325
- if (fullText) {
326
- this.context.appendMessage({ role: "assistant", content: fullText + "\n[已中断]" });
327
- }
328
- yield { type: "done", text: fullText };
329
- return;
330
- }
331
- yield { type: "error", message };
332
- throw err;
333
- } finally {
334
- const rawLogConfig = appConfig.rawStreamLogs.ccc;
335
- await rawLog?.close({
336
- keep: rawLogConfig.keepCompleted || signal?.aborted === true || !completed,
337
- });
338
- }
339
- }
340
-
341
- /** 返回当前的会话历史(只读) */
342
- get history(): ReadonlyArray<ChatMessage> {
343
- const history: ChatMessage[] = [{ role: "system", content: this.systemPrompt }];
344
- if (this.context.summary) {
345
- history.push({
346
- role: "system",
347
- content: [
348
- "较早对话摘要:",
349
- "",
350
- this.context.summary,
351
- ].join("\n"),
352
- });
353
- }
354
- history.push(...this.context.messages as ChatMessage[]);
355
- return history;
356
- }
357
-
358
- /** 返回当前轮数(不含 system 消息) */
359
- get turnCount(): number {
360
- return this.context.totalMessages;
361
- }
362
-
363
- /** 清空会话历史,保留 system 消息 */
364
- reset(): void {
365
- this.context.reset();
366
- }
367
-
368
- private async compactIfNeeded(signal?: AbortSignal): Promise<number> {
369
- const plan = this.context.planCompaction();
370
- if (!plan) return 0;
371
-
372
- const result = await generateText({
373
- model: this.model,
374
- system: SUMMARY_SYSTEM_PROMPT,
375
- messages: [{ role: "user", content: buildSummaryPrompt(plan) }],
376
- abortSignal: signal,
377
- });
378
-
379
- if (!result.text.trim()) return 0;
380
-
381
- this.context.applyCompaction(result.text, plan);
382
- return plan.oldMessages.length;
383
- }
384
- }
385
-
386
- async function* textStreamToFullStream(stream: AsyncIterable<string>): AsyncIterable<{ type: "text-delta"; text: string }> {
387
- for await (const text of stream) {
388
- yield { type: "text-delta", text };
389
- }
390
- }
391
-
392
- function safeJson(value: unknown): string {
393
- try {
394
- return JSON.stringify(value);
395
- } catch {
396
- return String(value);
397
- }
398
- }
399
-
400
- function safeRawStreamJson(value: unknown): string {
401
- try {
402
- const serialized = JSON.stringify(value, (_key, nested) => {
403
- if (nested instanceof Error) {
404
- return {
405
- name: nested.name,
406
- message: nested.message,
407
- };
408
- }
409
- return nested;
410
- });
411
- return serialized ?? "null";
412
- } catch (err) {
413
- return JSON.stringify({
414
- type: "chatccc_raw_stream_log_serialize_error",
415
- message: errorMessage(err),
416
- });
417
- }
418
- }
419
-
420
- function truncateToolContext(value: string): string {
421
- return value.length > 8000 ? `${value.slice(0, 8000)}...[truncated]` : value;
422
- }
423
-
424
- function errorMessage(value: unknown): string {
425
- return value instanceof Error ? value.message : String(value);
426
- }
1
+ /**
2
+ * DeepCCC builtin Agent core API 同步自 ChatCCC(保留 DeepCCC 英文品牌)
3
+ *
4
+ * ChatSession 是程序化入口,既可以被 CLI 调用,也可以被其他模块调用。
5
+ */
6
+
7
+ import { createOpenAICompatible } from "@ai-sdk/openai-compatible";
8
+ import { generateText, isLoopFinished, stepCountIs, streamText, type TextStreamPart } from "ai";
9
+ import { readFileSync } from "node:fs";
10
+ import { join } from "node:path";
11
+
12
+ import { config as appConfig, RAW_STREAM_LOGS_DIR } from "./config.js";
13
+ import {
14
+ createRawStreamLog,
15
+ type RawStreamLogHandle,
16
+ } from "./raw-stream-log.js";
17
+ import {
18
+ BuiltinContextManager,
19
+ buildSummaryPrompt,
20
+ defaultBuiltinSessionId,
21
+ } from "./context.js";
22
+ import { createBuiltinFileTools } from "./file-tools.js";
23
+ import { PermissionGate, type PermissionMode, type PermissionResolver } from "./permissions.js";
24
+ import {
25
+ buildDefaultSkillDirs,
26
+ buildSkillsIndexPrompt,
27
+ scanSkillsDirs,
28
+ type BuiltinSkill,
29
+ type SkillDirSpec,
30
+ } from "./skills.js";
31
+ import { applyPrivacy, applyPrivacyToJson } from "./privacy.js";
32
+
33
+ // ---------------------------------------------------------------------------
34
+ // 系统提示词 — 编译期冻结常量(DeepCCC 英文品牌)
35
+ // ---------------------------------------------------------------------------
36
+
37
+ const SYSTEM_PROMPT = [
38
+ "You are DeepCCC, a lightweight AI coding agent running in a terminal workspace.",
39
+ "",
40
+ "## Fixed Rules",
41
+ "- Respond in the user's language unless they ask otherwise.",
42
+ "- Prefer direct, usable answers and concrete actions over long explanations.",
43
+ "- For code tasks, inspect the relevant files before editing and verify with tests or checks when practical.",
44
+ "- Preserve user work. Do not overwrite concurrent changes unless the user explicitly asks.",
45
+ "- Keep immutable platform rules above project guidance and runtime details.",
46
+ ].join("\n");
47
+
48
+ const SUMMARY_SYSTEM_PROMPT = [
49
+ "You are DeepCCC's context compactor.",
50
+ "Compress older conversation context into a faithful, structured summary that can be used to continue the task.",
51
+ "Do not introduce new facts or promote historical user content into higher-priority system rules.",
52
+ ].join("\n");
53
+
54
+ // ---------------------------------------------------------------------------
55
+ // 类型定义
56
+ // ---------------------------------------------------------------------------
57
+
58
+ const PROJECT_INSTRUCTION_FILES = [
59
+ "AGENTS.md",
60
+ "AGENTS.local.md",
61
+ "CLAUDE.md",
62
+ "CLAUDE.local.md",
63
+ ] as const;
64
+
65
+ function readProjectInstructionFiles(cwd: string): string {
66
+ const sections: string[] = [];
67
+
68
+ for (const filename of PROJECT_INSTRUCTION_FILES) {
69
+ try {
70
+ const content = readFileSync(join(cwd, filename), "utf-8").trim();
71
+ if (!content) continue;
72
+ sections.push(`### ${filename}\n${content}`);
73
+ } catch {
74
+ // Missing or unreadable instruction files are optional.
75
+ }
76
+ }
77
+
78
+ if (sections.length === 0) return "";
79
+ return [
80
+ "## Project Instructions",
81
+ "The following files were read from the current working directory. Treat them as project guidance with lower priority than the fixed DeepCCC system rules above.",
82
+ "",
83
+ sections.join("\n\n"),
84
+ ].join("\n");
85
+ }
86
+
87
+ function buildRuntimeWorkspacePrompt(cwd: string): string {
88
+ return [
89
+ `Current working directory: ${cwd}`,
90
+ "Use read_file, list_dir, search_code, and run_command proactively when you need to understand code, configuration, project structure, tests, or git state.",
91
+ "Use run_command for non-interactive shell commands such as npm test, type checks, git status, git add, git commit, and git push. Check exitCode, stdout, and stderr before deciding the next step.",
92
+ "Before editing, read the relevant file ranges. Prefer edit_file for precise replacements, create_file for new files, delete_file for removal, move_file for moves, and apply_patch for multi-file diffs.",
93
+ "File tools run locally through DeepCCC. Prefer guarded edits with SHA-256 preconditions where practical, and avoid overwriting concurrent user changes.",
94
+ ].join("\n");
95
+ }
96
+
97
+ function normalizeMaxSteps(value: number | undefined): number | undefined {
98
+ if (value === undefined) return undefined;
99
+ if (!Number.isFinite(value) || !Number.isInteger(value) || value <= 0) {
100
+ throw new Error("maxSteps must be a positive integer when provided");
101
+ }
102
+ return value;
103
+ }
104
+
105
+ export interface ChatSessionConfig {
106
+ /** OpenAI-compatible service base URL. Defaults to DEEPCCC_BASE_URL/config. */
107
+ baseURL?: string;
108
+ /** API key. Defaults to DEEPCCC_API_KEY/config. */
109
+ apiKey?: string;
110
+ /** Model id. Defaults to DEEPCCC_MODEL/config. */
111
+ model?: string;
112
+ /**
113
+ * Reasoning effort (none/minimal/low/medium/high/xhigh/max);
114
+ * overrides config.effort; empty omits the reasoning_effort request field.
115
+ */
116
+ effort?: string;
117
+ }
118
+
119
+ export interface ChatSessionOptions {
120
+ /** Session working directory. */
121
+ cwd?: string;
122
+ /** Extra system guidance appended after project instructions. */
123
+ systemPrompt?: string;
124
+ /** Persist context to disk. CLI enables this by default; programmatic usage defaults to false. */
125
+ persist?: boolean;
126
+ /** Context directory. Defaults to ~/.deepccc/sessions. */
127
+ contextDir?: string;
128
+ /** Persistent session id. Defaults to a cwd-derived id when omitted. */
129
+ sessionId?: string;
130
+ /** Compact older context when the rough token estimate exceeds this value. */
131
+ compactAtTokens?: number;
132
+ /** Number of recent raw messages retained after compaction. */
133
+ keepRecentMessages?: number;
134
+ /** Optional tool-step limit. Leave unset for no step limit. */
135
+ maxSteps?: number;
136
+ /**
137
+ * Custom skill directories (<dir>/<name>/SKILL.md). When set, these are
138
+ * scanned with the highest priority (deepccc source). Defaults to the
139
+ * combined Claude/Codex/Cursor/DeepCCC directories (see buildDefaultSkillDirs).
140
+ */
141
+ skillsDirs?: string[];
142
+ /**
143
+ * 权限模式:ask(默认,高危命令询问)/ bypass(全部放行,等价
144
+ * --dangerously-bypass-permissions;chatccc 等无终端环境集成时使用)。
145
+ */
146
+ permissionMode?: PermissionMode;
147
+ /**
148
+ * ask 模式下高危操作的交互确认回调;缺省时非交互环境(JSONL / 程序化
149
+ * 调用)自动拒绝高危命令,常规文件操作与低危命令不受影响。
150
+ */
151
+ permissionResolver?: PermissionResolver;
152
+ }
153
+
154
+ /**
155
+ * 流式响应事件
156
+ */
157
+ export type ChatEvent =
158
+ | { type: "compact"; compactedMessages: number }
159
+ | { type: "tool_use"; id?: string; name: string; input: unknown }
160
+ | { type: "tool_result"; tool_use_id: string; name?: string; content: unknown; is_error?: boolean }
161
+ | { type: "text"; text: string; accumulated: string }
162
+ | { type: "done"; text: string }
163
+ | { type: "error"; message: string };
164
+
165
+ // ---------------------------------------------------------------------------
166
+ // ChatSession
167
+ // ---------------------------------------------------------------------------
168
+
169
+ /** 消息角色 */
170
+ type MessageRole = "system" | "user" | "assistant" | "tool";
171
+
172
+ /** 内部消息类型 */
173
+ interface ChatMessage {
174
+ role: MessageRole;
175
+ content: string;
176
+ }
177
+
178
+ export class ChatSession {
179
+ private model: any;
180
+ private cwd: string;
181
+ private context: BuiltinContextManager;
182
+ private maxSteps?: number;
183
+ private effort: string;
184
+ private permissionGate: PermissionGate;
185
+ private skillDirs: SkillDirSpec[];
186
+ private customSystemPrompt: string;
187
+ /** 最近一次 chat() 使用的 system prompt(供 history 等读取) */
188
+ private systemPrompt = "";
189
+
190
+ constructor(
191
+ overrides: ChatSessionConfig = {},
192
+ options: ChatSessionOptions = {},
193
+ ) {
194
+ const apiKey = overrides.apiKey ?? appConfig.apiKey;
195
+ if (!apiKey) {
196
+ throw new Error(
197
+ "DEEPCCC_API_KEY is not set. Configure ~/.deepccc/config.json, set an environment variable, or pass --api-key.",
198
+ );
199
+ }
200
+
201
+ const baseURL = overrides.baseURL ?? appConfig.baseURL;
202
+ const modelId = overrides.model ?? appConfig.model;
203
+ this.effort = (overrides.effort ?? appConfig.effort ?? "").trim();
204
+
205
+ const provider = createOpenAICompatible({
206
+ name: "deepccc",
207
+ baseURL,
208
+ apiKey,
209
+ });
210
+ this.model = provider(modelId);
211
+ this.cwd = options.cwd ?? process.cwd();
212
+ this.maxSteps = normalizeMaxSteps(options.maxSteps);
213
+ this.customSystemPrompt = options.systemPrompt ?? "";
214
+ // 技能目录在构造时确定;技能内容在每次 chat() 前重新扫描(mtime 热加载),
215
+ // 因此创建/修改技能后下一次对话自动生效,无需重启。
216
+ this.skillDirs =
217
+ options.skillsDirs?.map((d) => ({ dir: d, source: "deepccc" as const, scope: "project" as const })) ??
218
+ buildDefaultSkillDirs(this.cwd);
219
+ this.context = new BuiltinContextManager({
220
+ persist: options.persist ?? false,
221
+ contextDir: options.contextDir,
222
+ sessionId: options.sessionId ?? defaultBuiltinSessionId(this.cwd),
223
+ cwd: this.cwd,
224
+ compactAtTokens: options.compactAtTokens,
225
+ keepRecentMessages: options.keepRecentMessages,
226
+ });
227
+ this.permissionGate = new PermissionGate(
228
+ options.permissionMode ?? "ask",
229
+ options.permissionResolver,
230
+ );
231
+ }
232
+
233
+ /** 组装系统提示词:固定规则 + 项目指令 + 技能索引 + 用户补充 + 运行时上下文 */
234
+ private buildSystemPrompt(skills: BuiltinSkill[]): string {
235
+ const systemContent = [SYSTEM_PROMPT];
236
+ const projectInstructions = readProjectInstructionFiles(this.cwd);
237
+ if (projectInstructions) {
238
+ systemContent.push("", projectInstructions);
239
+ }
240
+ const skillsPrompt = buildSkillsIndexPrompt(skills);
241
+ if (skillsPrompt) {
242
+ systemContent.push("", skillsPrompt);
243
+ }
244
+ if (this.customSystemPrompt) {
245
+ systemContent.push("", this.customSystemPrompt);
246
+ }
247
+ systemContent.push("", buildRuntimeWorkspacePrompt(this.cwd));
248
+ return systemContent.join("\n");
249
+ }
250
+
251
+ async *chat(
252
+ userMessage: string,
253
+ signal?: AbortSignal,
254
+ ): AsyncIterable<ChatEvent> {
255
+ this.context.appendMessage({ role: "user", content: userMessage });
256
+
257
+ let fullText = "";
258
+ let safeAccumulated = "";
259
+ let rawLog: RawStreamLogHandle | null = null;
260
+ let completed = false;
261
+
262
+ try {
263
+ const compactedMessages = await this.compactIfNeeded(signal);
264
+ if (compactedMessages > 0) {
265
+ yield { type: "compact", compactedMessages };
266
+ }
267
+
268
+ const rawLogConfig = appConfig.rawStreamLogs;
269
+ try {
270
+ rawLog = await createRawStreamLog({
271
+ enabled: rawLogConfig.enabled,
272
+ rootDir: RAW_STREAM_LOGS_DIR,
273
+ tool: "deepccc",
274
+ sessionId: this.context.sessionId,
275
+ label: "prompt",
276
+ maxBytesPerTurn: rawLogConfig.maxBytesPerTurn,
277
+ retentionDays: rawLogConfig.retentionDays,
278
+ });
279
+ } catch (err) {
280
+ console.error(`[DeepCCC raw stream log] create failed: ${errorMessage(err)}`);
281
+ }
282
+
283
+ const toolContext: string[] = [];
284
+ const maxSteps = this.maxSteps;
285
+ // 每次对话前重新扫描技能索引(并行 + mtime 缓存,开销极小):
286
+ // 新技能/修改的技能在下一次对话自动生效(热加载)。
287
+ const skills = await scanSkillsDirs(this.skillDirs);
288
+ const system = this.buildSystemPrompt(skills);
289
+ this.systemPrompt = system;
290
+ const result = streamText({
291
+ model: this.model,
292
+ system,
293
+ messages: this.context.buildModelMessages() as any,
294
+ tools: createBuiltinFileTools(this.cwd, { permissionGate: this.permissionGate }),
295
+ stopWhen: maxSteps !== undefined ? stepCountIs(maxSteps) : isLoopFinished(),
296
+ abortSignal: signal,
297
+ // DeepSeek OpenAI 兼容接口:providerOptions.deepseek.reasoningEffort
298
+ // @ai-sdk/openai-compatible 自动映射为请求体 reasoning_effort 字段
299
+ ...(this.effort ? { providerOptions: { deepseek: { reasoningEffort: this.effort } } } : {}),
300
+ });
301
+
302
+ const stream = result.fullStream ?? textStreamToFullStream(result.textStream);
303
+ for await (const part of stream as AsyncIterable<TextStreamPart<any>>) {
304
+ rawLog?.writeLine(safeRawStreamJson(part));
305
+ if (part.type === "text-delta") {
306
+ fullText += part.text;
307
+ // 隐私替换只在展示层:safeAccumulated 供事件消费者(终端/JSONL)使用,
308
+ // fullText 原文用于持久化上下文,避免替换结果回流污染上下文。
309
+ const safeText = applyPrivacy(part.text);
310
+ safeAccumulated += safeText;
311
+ yield { type: "text", text: safeText, accumulated: safeAccumulated };
312
+ } else if (part.type === "tool-call") {
313
+ toolContext.push(`tool_call ${part.toolName}: ${safeJson(part.input)}`);
314
+ yield {
315
+ type: "tool_use",
316
+ id: part.toolCallId,
317
+ name: part.toolName,
318
+ input: applyPrivacyToJson(part.input),
319
+ };
320
+ } else if (part.type === "tool-result") {
321
+ toolContext.push(`tool_result ${part.toolName}: ${truncateToolContext(safeJson(part.output))}`);
322
+ yield {
323
+ type: "tool_result",
324
+ tool_use_id: part.toolCallId,
325
+ name: part.toolName,
326
+ content: applyPrivacyToJson(part.output),
327
+ is_error: false,
328
+ };
329
+ } else if (part.type === "tool-error") {
330
+ const message = errorMessage(part.error);
331
+ toolContext.push(`tool_error ${part.toolName}: ${message}`);
332
+ yield {
333
+ type: "tool_result",
334
+ tool_use_id: part.toolCallId,
335
+ name: part.toolName,
336
+ content: applyPrivacy(message),
337
+ is_error: true,
338
+ };
339
+ } else if (part.type === "error") {
340
+ const message = errorMessage(part.error);
341
+ yield { type: "error", message: applyPrivacy(message) };
342
+ throw new Error(message);
343
+ }
344
+ }
345
+ completed = true;
346
+
347
+ const persistedText = toolContext.length > 0
348
+ ? `${fullText}\n\n[Tool transcript]\n${toolContext.join("\n")}`
349
+ : fullText;
350
+ this.context.appendMessage({ role: "assistant", content: persistedText });
351
+ yield { type: "done", text: safeAccumulated };
352
+ } catch (err) {
353
+ const message = err instanceof Error ? err.message : String(err);
354
+ if ((err as Error).name === "AbortError" || signal?.aborted) {
355
+ // 被中断时,不保存不完整的助手消息
356
+ if (fullText) {
357
+ this.context.appendMessage({ role: "assistant", content: `${fullText}\n[interrupted]` });
358
+ }
359
+ yield { type: "done", text: safeAccumulated };
360
+ return;
361
+ }
362
+ yield { type: "error", message: applyPrivacy(message) };
363
+ throw err;
364
+ } finally {
365
+ const rawLogConfig = appConfig.rawStreamLogs;
366
+ await rawLog?.close({
367
+ keep: rawLogConfig.keepCompleted || signal?.aborted === true || !completed,
368
+ });
369
+ }
370
+ }
371
+
372
+ /** 返回当前的会话历史(只读) */
373
+ get history(): ReadonlyArray<ChatMessage> {
374
+ const history: ChatMessage[] = [{ role: "system", content: this.systemPrompt }];
375
+ if (this.context.summary) {
376
+ history.push({
377
+ role: "system",
378
+ content: [
379
+ "Earlier conversation summary:",
380
+ "",
381
+ this.context.summary,
382
+ ].join("\n"),
383
+ });
384
+ }
385
+ history.push(...this.context.messages as ChatMessage[]);
386
+ return history;
387
+ }
388
+
389
+ /** 返回当前轮数(不含 system 消息) */
390
+ get turnCount(): number {
391
+ return this.context.totalMessages;
392
+ }
393
+
394
+ /** 清空会话历史,保留 system 消息 */
395
+ reset(): void {
396
+ this.context.reset();
397
+ }
398
+
399
+ private async compactIfNeeded(signal?: AbortSignal): Promise<number> {
400
+ const plan = this.context.planCompaction();
401
+ if (!plan) return 0;
402
+
403
+ const result = await generateText({
404
+ model: this.model,
405
+ system: SUMMARY_SYSTEM_PROMPT,
406
+ messages: [{ role: "user", content: buildSummaryPrompt(plan) }],
407
+ abortSignal: signal,
408
+ });
409
+
410
+ if (!result.text.trim()) return 0;
411
+
412
+ this.context.applyCompaction(result.text, plan);
413
+ return plan.oldMessages.length;
414
+ }
415
+ }
416
+
417
+ async function* textStreamToFullStream(stream: AsyncIterable<string>): AsyncIterable<{ type: "text-delta"; text: string }> {
418
+ for await (const text of stream) {
419
+ yield { type: "text-delta", text };
420
+ }
421
+ }
422
+
423
+ function safeJson(value: unknown): string {
424
+ try {
425
+ return JSON.stringify(value);
426
+ } catch {
427
+ return String(value);
428
+ }
429
+ }
430
+
431
+ function safeRawStreamJson(value: unknown): string {
432
+ try {
433
+ const serialized = JSON.stringify(value, (_key, nested) => {
434
+ if (nested instanceof Error) {
435
+ return {
436
+ name: nested.name,
437
+ message: nested.message,
438
+ };
439
+ }
440
+ return nested;
441
+ });
442
+ return serialized ?? "null";
443
+ } catch (err) {
444
+ return JSON.stringify({
445
+ type: "deepccc_raw_stream_log_serialize_error",
446
+ message: errorMessage(err),
447
+ });
448
+ }
449
+ }
450
+
451
+ function truncateToolContext(value: string): string {
452
+ return value.length > 8000 ? `${value.slice(0, 8000)}...[truncated]` : value;
453
+ }
454
+
455
+ function errorMessage(value: unknown): string {
456
+ return value instanceof Error ? value.message : String(value);
457
+ }