chatccc 0.2.187 → 0.2.189

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 (71) hide show
  1. package/agent-prompts/claude_specific.md +45 -45
  2. package/agent-prompts/codex_specific.md +2 -2
  3. package/agent-prompts/cursor_specific.md +13 -13
  4. package/config.sample.json +5 -0
  5. package/im-skills/feishu-skill/receive-send-file.md +63 -63
  6. package/im-skills/feishu-skill/receive-send-image.md +24 -24
  7. package/im-skills/feishu-skill/skill.md +3 -3
  8. package/im-skills/wechat-file-skill/receive-send-file.md +38 -38
  9. package/im-skills/wechat-file-skill/send-file.mjs +83 -83
  10. package/im-skills/wechat-file-skill/skill.md +10 -10
  11. package/im-skills/wechat-image-skill/skill.md +10 -10
  12. package/im-skills/wechat-video-skill/receive-send-video.md +38 -38
  13. package/im-skills/wechat-video-skill/send-video.mjs +79 -79
  14. package/im-skills/wechat-video-skill/skill.md +10 -10
  15. package/package.json +1 -1
  16. package/scripts/postinstall-sharp-check.mjs +58 -58
  17. package/src/__tests__/agent-delegate-task-rpc.test.ts +165 -165
  18. package/src/__tests__/builtin-config.test.ts +33 -0
  19. package/src/__tests__/card-plain-text.test.ts +5 -5
  20. package/src/__tests__/cardkit.test.ts +60 -60
  21. package/src/__tests__/cards.test.ts +77 -77
  22. package/src/__tests__/chatgpt-subscription-rpc.test.ts +89 -89
  23. package/src/__tests__/chatgpt-subscription.test.ts +135 -135
  24. package/src/__tests__/chrome-devtools-guard.test.ts +165 -125
  25. package/src/__tests__/claude-adapter.test.ts +592 -592
  26. package/src/__tests__/codex-reset-actions.test.ts +146 -146
  27. package/src/__tests__/config-reload.test.ts +1 -0
  28. package/src/__tests__/config-sample.test.ts +11 -0
  29. package/src/__tests__/feishu-api.test.ts +60 -60
  30. package/src/__tests__/feishu-avatar.test.ts +180 -115
  31. package/src/__tests__/feishu-platform.test.ts +22 -22
  32. package/src/__tests__/format-message.test.ts +47 -47
  33. package/src/__tests__/orchestrator.test.ts +150 -2
  34. package/src/__tests__/privacy.test.ts +198 -198
  35. package/src/__tests__/raw-stream-log.test.ts +106 -106
  36. package/src/__tests__/session.test.ts +10 -0
  37. package/src/__tests__/shared-prefix.test.ts +36 -36
  38. package/src/__tests__/stream-state.test.ts +42 -42
  39. package/src/__tests__/web-ui.test.ts +209 -130
  40. package/src/adapters/claude-adapter.ts +566 -566
  41. package/src/adapters/claude-session-meta-store.ts +120 -120
  42. package/src/adapters/codex-adapter.ts +10 -6
  43. package/src/adapters/cursor-adapter.ts +46 -46
  44. package/src/adapters/raw-stream-log.ts +124 -124
  45. package/src/adapters/resource-monitor.ts +140 -140
  46. package/src/agent-delegate-task-rpc.ts +153 -153
  47. package/src/agent-delegate-task.ts +81 -81
  48. package/src/agent-stop-stuck.ts +129 -129
  49. package/src/builtin/cli.ts +189 -197
  50. package/src/builtin/index.ts +168 -167
  51. package/src/cards.ts +130 -89
  52. package/src/chatgpt-subscription-rpc.ts +27 -27
  53. package/src/chatgpt-subscription.ts +299 -299
  54. package/src/chrome-devtools-guard.ts +318 -242
  55. package/src/codex-reset-actions.ts +184 -184
  56. package/src/config.ts +38 -0
  57. package/src/feishu-api.ts +219 -190
  58. package/src/feishu-platform.ts +20 -20
  59. package/src/format-message.ts +293 -293
  60. package/src/index.ts +2 -2
  61. package/src/litellm-proxy.ts +374 -374
  62. package/src/orchestrator.ts +201 -9
  63. package/src/platform-adapter.ts +9 -1
  64. package/src/privacy.ts +118 -118
  65. package/src/session-chat-binding.ts +6 -6
  66. package/src/session-name.ts +8 -8
  67. package/src/session.ts +44 -16
  68. package/src/shared-prefix.ts +29 -29
  69. package/src/sim-platform.ts +20 -20
  70. package/src/turn-cards.ts +117 -117
  71. package/src/web-ui.ts +142 -24
@@ -1,129 +1,129 @@
1
- import type { IncomingMessage, ServerResponse } from "node:http";
2
-
3
- import { readUtf8JsonBody } from "./agent-rpc-body.ts";
4
- import { activePrompts, getChatsForSession } from "./session-chat-binding.ts";
5
- import { getPlatformForChat } from "./session.ts";
6
- import { readStreamState, writeStreamState } from "./stream-state.ts";
7
- import { ts } from "./config.ts";
8
-
9
- export const AGENT_STOP_STUCK_PATH = "/api/agent/stop-stuck-loop";
10
-
11
- const MAX_REQUEST_BYTES = 8 * 1024;
12
-
13
- function jsonReply(res: ServerResponse, status: number, data: unknown): void {
14
- res.writeHead(status, { "Content-Type": "application/json; charset=utf-8" });
15
- res.end(JSON.stringify(data));
16
- }
17
-
18
- /**
19
- * 从原始 body 字节中用正则尽力提取 session_id。
20
- * 兼容 JSON 编码异常(如 GBK 中文导致 JSON.parse 失败)的场景。
21
- */
22
- function extractSessionIdFromRaw(buf: Buffer): string | null {
23
- // 匹配 "session_id":"<uuid>" 或 "session_id": "<uuid>"
24
- const match = buf.toString("latin1").match(/"session_id"\s*:\s*"([^"]+)"/);
25
- return match?.[1] ?? null;
26
- }
27
-
28
- export async function handleAgentStopStuckRequest(
29
- req: IncomingMessage,
30
- res: ServerResponse,
31
- ): Promise<boolean> {
32
- const url = new URL(req.url ?? "/", "http://127.0.0.1");
33
- if (url.pathname !== AGENT_STOP_STUCK_PATH) return false;
34
-
35
- if (req.method !== "POST") {
36
- jsonReply(res, 405, { error: "Method not allowed, use POST" });
37
- return true;
38
- }
39
-
40
- let body: { session_id?: string; final_reply?: string };
41
- let rawBody: Buffer | null = null;
42
- try {
43
- body = await readUtf8JsonBody<{ session_id?: string; final_reply?: string }>(req, MAX_REQUEST_BYTES);
44
- } catch (err) {
45
- // JSON 解析失败时仍尝试从原始字节中提取 session_id 并强行停止
46
- // 宁可输出乱码,也不能让 agent 持续循环
47
- rawBody = (err as { rawBody?: Buffer }).rawBody as Buffer | undefined ?? null;
48
- if (!rawBody) {
49
- jsonReply(res, 400, { error: `Invalid request body: ${(err as Error).message}` });
50
- return true;
51
- }
52
- const fallbackId = extractSessionIdFromRaw(rawBody);
53
- if (!fallbackId) {
54
- jsonReply(res, 400, { error: `Invalid request body: ${(err as Error).message}` });
55
- return true;
56
- }
57
- body = { session_id: fallbackId };
58
- }
59
-
60
- const sessionId = typeof body?.session_id === "string" ? body.session_id.trim() : "";
61
- if (!sessionId) {
62
- jsonReply(res, 400, { error: "session_id is required" });
63
- return true;
64
- }
65
-
66
- const prompt = activePrompts.get(sessionId);
67
- if (!prompt) {
68
- jsonReply(res, 404, { error: "Session not found or not running" });
69
- return true;
70
- }
71
-
72
- // 先发"卡住"提示消息给所有绑定的群聊
73
- const chats = getChatsForSession(sessionId);
74
- for (const chatId of chats) {
75
- const platform = getPlatformForChat(chatId);
76
- if (platform) {
77
- await platform.sendText(chatId, "⚠️ Agent 检测到自己陷入了循环,正在结束生成…").catch(() => {});
78
- }
79
- }
80
-
81
- // 不丢弃缓存队列中的消息,让 runAgentSession 的 finally 块正常消费,
82
- // 确保 stop-stuck-loop 结束后排队的消息仍能被正常处理。
83
-
84
- const finalReply = typeof body?.final_reply === "string" ? body.final_reply.trim() : "";
85
-
86
- // fire-and-forget:立即把 stream-state 标为 done(而非 stopped),
87
- // 让 display loop 以"正常完成"而非"已停止"来渲染卡片和最终回复。
88
- // 不设 prompt.stopped = true,这样 runAgentSession 的 finally 也会写 "done"。
89
- void (async () => {
90
- try {
91
- const current = await readStreamState(sessionId);
92
- if (!current) return;
93
- if (current.status !== "running") return;
94
- await writeStreamState({
95
- ...current,
96
- status: "done",
97
- stuckAt: Date.now(),
98
- finalReply: finalReply ? current.finalReply + "\n\n" + finalReply : current.finalReply,
99
- updatedAt: Date.now(),
100
- });
101
- } catch (err) {
102
- console.warn(
103
- `[${ts()}] [STUCK-LOOP] writeStreamState(done) failed for ${sessionId}: ${(err as Error).message}`,
104
- );
105
- }
106
- })();
107
-
108
- // 先关闭底层 SDK session,终止 CLI 子进程,然后再 abort 清理 adapter 层
109
- prompt.closeSession?.();
110
-
111
- // 强制杀死 CLI 子进程。controller.abort() 只在 for-await 收到下一条
112
- // stream 消息时才被检测到——如果 agent 陷入无输出的计算循环,abort 信号
113
- // 永远不会生效;SDK 的 session.close() 也不保证立即终止子进程。
114
- if (prompt.processPid !== undefined) {
115
- try {
116
- process.kill(prompt.processPid);
117
- } catch {
118
- // 进程可能已退出,忽略错误
119
- }
120
- }
121
-
122
- // 不设 stopped 标记 → finally block 写 "done" → 卡片正常结束
123
- prompt.controller.abort();
124
-
125
- console.log(`[${ts()}] [STUCK-LOOP] Session ${sessionId} aborted as done (agent detected stuck loop, final_reply=${finalReply ? "yes" : "no"})`);
126
-
127
- jsonReply(res, 200, { ok: true });
128
- return true;
129
- }
1
+ import type { IncomingMessage, ServerResponse } from "node:http";
2
+
3
+ import { readUtf8JsonBody } from "./agent-rpc-body.ts";
4
+ import { activePrompts, getChatsForSession } from "./session-chat-binding.ts";
5
+ import { getPlatformForChat } from "./session.ts";
6
+ import { readStreamState, writeStreamState } from "./stream-state.ts";
7
+ import { ts } from "./config.ts";
8
+
9
+ export const AGENT_STOP_STUCK_PATH = "/api/agent/stop-stuck-loop";
10
+
11
+ const MAX_REQUEST_BYTES = 8 * 1024;
12
+
13
+ function jsonReply(res: ServerResponse, status: number, data: unknown): void {
14
+ res.writeHead(status, { "Content-Type": "application/json; charset=utf-8" });
15
+ res.end(JSON.stringify(data));
16
+ }
17
+
18
+ /**
19
+ * 从原始 body 字节中用正则尽力提取 session_id。
20
+ * 兼容 JSON 编码异常(如 GBK 中文导致 JSON.parse 失败)的场景。
21
+ */
22
+ function extractSessionIdFromRaw(buf: Buffer): string | null {
23
+ // 匹配 "session_id":"<uuid>" 或 "session_id": "<uuid>"
24
+ const match = buf.toString("latin1").match(/"session_id"\s*:\s*"([^"]+)"/);
25
+ return match?.[1] ?? null;
26
+ }
27
+
28
+ export async function handleAgentStopStuckRequest(
29
+ req: IncomingMessage,
30
+ res: ServerResponse,
31
+ ): Promise<boolean> {
32
+ const url = new URL(req.url ?? "/", "http://127.0.0.1");
33
+ if (url.pathname !== AGENT_STOP_STUCK_PATH) return false;
34
+
35
+ if (req.method !== "POST") {
36
+ jsonReply(res, 405, { error: "Method not allowed, use POST" });
37
+ return true;
38
+ }
39
+
40
+ let body: { session_id?: string; final_reply?: string };
41
+ let rawBody: Buffer | null = null;
42
+ try {
43
+ body = await readUtf8JsonBody<{ session_id?: string; final_reply?: string }>(req, MAX_REQUEST_BYTES);
44
+ } catch (err) {
45
+ // JSON 解析失败时仍尝试从原始字节中提取 session_id 并强行停止
46
+ // 宁可输出乱码,也不能让 agent 持续循环
47
+ rawBody = (err as { rawBody?: Buffer }).rawBody as Buffer | undefined ?? null;
48
+ if (!rawBody) {
49
+ jsonReply(res, 400, { error: `Invalid request body: ${(err as Error).message}` });
50
+ return true;
51
+ }
52
+ const fallbackId = extractSessionIdFromRaw(rawBody);
53
+ if (!fallbackId) {
54
+ jsonReply(res, 400, { error: `Invalid request body: ${(err as Error).message}` });
55
+ return true;
56
+ }
57
+ body = { session_id: fallbackId };
58
+ }
59
+
60
+ const sessionId = typeof body?.session_id === "string" ? body.session_id.trim() : "";
61
+ if (!sessionId) {
62
+ jsonReply(res, 400, { error: "session_id is required" });
63
+ return true;
64
+ }
65
+
66
+ const prompt = activePrompts.get(sessionId);
67
+ if (!prompt) {
68
+ jsonReply(res, 404, { error: "Session not found or not running" });
69
+ return true;
70
+ }
71
+
72
+ // 先发"卡住"提示消息给所有绑定的群聊
73
+ const chats = getChatsForSession(sessionId);
74
+ for (const chatId of chats) {
75
+ const platform = getPlatformForChat(chatId);
76
+ if (platform) {
77
+ await platform.sendText(chatId, "⚠️ Agent 检测到自己陷入了循环,正在结束生成…").catch(() => {});
78
+ }
79
+ }
80
+
81
+ // 不丢弃缓存队列中的消息,让 runAgentSession 的 finally 块正常消费,
82
+ // 确保 stop-stuck-loop 结束后排队的消息仍能被正常处理。
83
+
84
+ const finalReply = typeof body?.final_reply === "string" ? body.final_reply.trim() : "";
85
+
86
+ // fire-and-forget:立即把 stream-state 标为 done(而非 stopped),
87
+ // 让 display loop 以"正常完成"而非"已停止"来渲染卡片和最终回复。
88
+ // 不设 prompt.stopped = true,这样 runAgentSession 的 finally 也会写 "done"。
89
+ void (async () => {
90
+ try {
91
+ const current = await readStreamState(sessionId);
92
+ if (!current) return;
93
+ if (current.status !== "running") return;
94
+ await writeStreamState({
95
+ ...current,
96
+ status: "done",
97
+ stuckAt: Date.now(),
98
+ finalReply: finalReply ? current.finalReply + "\n\n" + finalReply : current.finalReply,
99
+ updatedAt: Date.now(),
100
+ });
101
+ } catch (err) {
102
+ console.warn(
103
+ `[${ts()}] [STUCK-LOOP] writeStreamState(done) failed for ${sessionId}: ${(err as Error).message}`,
104
+ );
105
+ }
106
+ })();
107
+
108
+ // 先关闭底层 SDK session,终止 CLI 子进程,然后再 abort 清理 adapter 层
109
+ prompt.closeSession?.();
110
+
111
+ // 强制杀死 CLI 子进程。controller.abort() 只在 for-await 收到下一条
112
+ // stream 消息时才被检测到——如果 agent 陷入无输出的计算循环,abort 信号
113
+ // 永远不会生效;SDK 的 session.close() 也不保证立即终止子进程。
114
+ if (prompt.processPid !== undefined) {
115
+ try {
116
+ process.kill(prompt.processPid);
117
+ } catch {
118
+ // 进程可能已退出,忽略错误
119
+ }
120
+ }
121
+
122
+ // 不设 stopped 标记 → finally block 写 "done" → 卡片正常结束
123
+ prompt.controller.abort();
124
+
125
+ console.log(`[${ts()}] [STUCK-LOOP] Session ${sessionId} aborted as done (agent detected stuck loop, final_reply=${finalReply ? "yes" : "no"})`);
126
+
127
+ jsonReply(res, 200, { ok: true });
128
+ return true;
129
+ }
@@ -1,197 +1,189 @@
1
- /**
2
- * builtin/cli.ts — ChatCCC 内置 Agent 终端 REPL
3
- *
4
- * 用法:
5
- * npx tsx src/builtin/cli.ts
6
- * npx tsx src/builtin/cli.ts --model deepseek-chat
7
- * npx tsx src/builtin/cli.ts --cwd /path/to/project
8
- *
9
- * 环境变量:
10
- * DEEPSEEK_API_KEY DeepSeek API Key(必需)
11
- * DEEPSEEK_BASE_URL API 地址(可选,默认 https://api.deepseek.com/v1)
12
- */
13
-
14
- import * as readline from "node:readline";
15
- import * as process from "node:process";
16
- import { ChatSession, type ChatSessionConfig, type ChatSessionOptions } from "./index.js";
17
-
18
- // ---------------------------------------------------------------------------
19
- // 命令行参数解析
20
- // ---------------------------------------------------------------------------
21
-
22
- function parseArgs(): { config: ChatSessionConfig; options: ChatSessionOptions } {
23
- const args = process.argv.slice(2);
24
- const config: ChatSessionConfig = {};
25
- const options: ChatSessionOptions = {};
26
-
27
- for (let i = 0; i < args.length; i++) {
28
- const arg = args[i];
29
- const next = args[i + 1];
30
- if (arg === "--model" && next) {
31
- config.model = next;
32
- i++;
33
- } else if (arg === "--base-url" && next) {
34
- config.baseURL = next;
35
- i++;
36
- } else if (arg === "--api-key" && next) {
37
- config.apiKey = next;
38
- i++;
39
- } else if (arg === "--cwd" && next) {
40
- options.cwd = next;
41
- i++;
42
- } else if (arg === "--help" || arg === "-h") {
43
- printHelp();
44
- process.exit(0);
45
- }
46
- }
47
-
48
- return { config, options };
49
- }
50
-
51
- function printHelp(): void {
52
- console.log([
53
- "ChatCCC 内置 Agent 终端 REPL",
54
- "",
55
- "用法: npx tsx src/builtin/cli.ts [选项]",
56
- "",
57
- "选项:",
58
- " --model <name> 模型名称(默认 deepseek-chat)",
59
- " --base-url <url> API 地址(默认 https://api.deepseek.com/v1)",
60
- " --api-key <key> API Key(默认读 DEEPSEEK_API_KEY 环境变量)",
61
- " --cwd <path> 工作目录",
62
- " --help, -h 显示帮助",
63
- "",
64
- "环境变量:",
65
- " DEEPSEEK_API_KEY DeepSeek API Key",
66
- " DEEPSEEK_BASE_URL API 地址",
67
- "",
68
- ].join("\n"));
69
- }
70
-
71
- // ---------------------------------------------------------------------------
72
- // ANSI 颜色
73
- // ---------------------------------------------------------------------------
74
-
75
- const C = {
76
- reset: "\x1b[0m",
77
- dim: "\x1b[2m",
78
- green: "\x1b[32m",
79
- cyan: "\x1b[36m",
80
- yellow: "\x1b[33m",
81
- };
82
-
83
- // ---------------------------------------------------------------------------
84
- // 主程序
85
- // ---------------------------------------------------------------------------
86
-
87
- async function main(): Promise<void> {
88
- const { config, options } = parseArgs();
89
-
90
- // 环境变量回退
91
- if (!config.baseURL) config.baseURL = process.env.DEEPSEEK_BASE_URL;
92
- if (!config.apiKey) config.apiKey = process.env.DEEPSEEK_API_KEY;
93
-
94
- console.log(`${C.dim}ChatCCC 内置 Agent 原型${C.reset}`);
95
- console.log(`${C.dim}模型: ${config.model ?? "deepseek-chat"}${C.reset}`);
96
- if (options.cwd) {
97
- console.log(`${C.dim}目录: ${options.cwd}${C.reset}`);
98
- }
99
- console.log(`${C.dim}输入消息开始对话,Ctrl+C 中断当前回复,/exit 退出${C.reset}`);
100
- console.log("");
101
-
102
- let session: ChatSession;
103
- try {
104
- session = new ChatSession(config, options);
105
- } catch (err) {
106
- console.error(`${C.yellow}${(err as Error).message}${C.reset}`);
107
- process.exit(1);
108
- }
109
-
110
- const rl = readline.createInterface({
111
- input: process.stdin,
112
- output: process.stdout,
113
- prompt: `${C.green}>${C.reset} `,
114
- });
115
-
116
- // 用于中断当前 LLM 调用的 AbortController
117
- let currentAbort: AbortController | null = null;
118
-
119
- rl.prompt();
120
-
121
- rl.on("line", async (line: string) => {
122
- const input = line.trim();
123
- if (!input) {
124
- rl.prompt();
125
- return;
126
- }
127
-
128
- // 特殊命令
129
- if (input === "/exit" || input === "/quit") {
130
- console.log(`${C.dim}再见${C.reset}`);
131
- rl.close();
132
- return;
133
- }
134
-
135
- if (input === "/clear") {
136
- session.reset();
137
- console.log(`${C.dim}会话已重置${C.reset}`);
138
- rl.prompt();
139
- return;
140
- }
141
-
142
- if (input === "/history") {
143
- console.log(`${C.dim}共 ${session.turnCount} 轮对话${C.reset}`);
144
- rl.prompt();
145
- return;
146
- }
147
-
148
- // 发送消息
149
- currentAbort = new AbortController();
150
- const signal = currentAbort.signal;
151
-
152
- try {
153
- let lastAccumulated = "";
154
- for await (const event of session.chat(input, signal)) {
155
- if (event.type === "text") {
156
- // 增量输出(仅在首次和行首时不换行)
157
- const newText = event.accumulated.slice(lastAccumulated.length);
158
- process.stdout.write(newText);
159
- lastAccumulated = event.accumulated;
160
- } else if (event.type === "done") {
161
- if (lastAccumulated) console.log("");
162
- console.log(`${C.dim}[完成]${C.reset}`);
163
- } else if (event.type === "error") {
164
- console.log(`\n${C.yellow}[错误] ${event.message}${C.reset}`);
165
- }
166
- }
167
- } catch (err) {
168
- console.log(`\n${C.yellow}[错误] ${(err as Error).message}${C.reset}`);
169
- } finally {
170
- currentAbort = null;
171
- }
172
-
173
- rl.prompt();
174
- });
175
-
176
- // Ctrl+C → 中断当前 LLM 调用(不退出程序)
177
- rl.on("SIGINT", () => {
178
- if (currentAbort) {
179
- console.log(`\n${C.yellow}[中断中...]${C.reset}`);
180
- currentAbort.abort();
181
- currentAbort = null;
182
- } else {
183
- console.log(`\n${C.dim}输入 /exit 退出${C.reset}`);
184
- rl.prompt();
185
- }
186
- });
187
-
188
- rl.on("close", () => {
189
- console.log("");
190
- process.exit(0);
191
- });
192
- }
193
-
194
- main().catch((err) => {
195
- console.error(`${C.yellow}启动失败: ${(err as Error).message}${C.reset}`);
196
- process.exit(1);
197
- });
1
+ /**
2
+ * builtin/cli.ts — ChatCCC 内置 Agent 终端 REPL
3
+ *
4
+ * 用法:
5
+ * npx tsx src/builtin/cli.ts
6
+ * npx tsx src/builtin/cli.ts --model deepseek-chat
7
+ * npx tsx src/builtin/cli.ts --cwd /path/to/project
8
+ */
9
+
10
+ import * as readline from "node:readline";
11
+ import * as process from "node:process";
12
+ import { config as appConfig } from "../config.ts";
13
+ import { ChatSession, type ChatSessionConfig, type ChatSessionOptions } from "./index.js";
14
+
15
+ // ---------------------------------------------------------------------------
16
+ // 命令行参数解析
17
+ // ---------------------------------------------------------------------------
18
+
19
+ function parseArgs(): { config: ChatSessionConfig; options: ChatSessionOptions } {
20
+ const args = process.argv.slice(2);
21
+ const config: ChatSessionConfig = {};
22
+ const options: ChatSessionOptions = {};
23
+
24
+ for (let i = 0; i < args.length; i++) {
25
+ const arg = args[i];
26
+ const next = args[i + 1];
27
+ if (arg === "--model" && next) {
28
+ config.model = next;
29
+ i++;
30
+ } else if (arg === "--base-url" && next) {
31
+ config.baseURL = next;
32
+ i++;
33
+ } else if (arg === "--api-key" && next) {
34
+ config.apiKey = next;
35
+ i++;
36
+ } else if (arg === "--cwd" && next) {
37
+ options.cwd = next;
38
+ i++;
39
+ } else if (arg === "--help" || arg === "-h") {
40
+ printHelp();
41
+ process.exit(0);
42
+ }
43
+ }
44
+
45
+ return { config, options };
46
+ }
47
+
48
+ function printHelp(): void {
49
+ console.log([
50
+ "ChatCCC 内置 Agent 终端 REPL",
51
+ "",
52
+ "用法: npx tsx src/builtin/cli.ts [选项]",
53
+ "",
54
+ "选项:",
55
+ ` --model <name> 模型名称(覆盖 config.ccc.model,当前默认 ${appConfig.ccc.model})`,
56
+ ` --base-url <url> API 地址(覆盖 config.ccc.DEEPSEEK_BASE_URL,当前默认 ${appConfig.ccc.DEEPSEEK_BASE_URL})`,
57
+ " --api-key <key> API Key(覆盖 config.ccc.DEEPSEEK_API_KEY)",
58
+ " --cwd <path> 工作目录",
59
+ " --help, -h 显示帮助",
60
+ "",
61
+ "默认配置来源:",
62
+ " ~/.chatccc/config.json 的 ccc.DEEPSEEK_API_KEY / ccc.DEEPSEEK_BASE_URL / ccc.model",
63
+ "",
64
+ ].join("\n"));
65
+ }
66
+
67
+ // ---------------------------------------------------------------------------
68
+ // ANSI 颜色
69
+ // ---------------------------------------------------------------------------
70
+
71
+ const C = {
72
+ reset: "\x1b[0m",
73
+ dim: "\x1b[2m",
74
+ green: "\x1b[32m",
75
+ cyan: "\x1b[36m",
76
+ yellow: "\x1b[33m",
77
+ };
78
+
79
+ // ---------------------------------------------------------------------------
80
+ // 主程序
81
+ // ---------------------------------------------------------------------------
82
+
83
+ async function main(): Promise<void> {
84
+ const { config, options } = parseArgs();
85
+
86
+ console.log(`${C.dim}ChatCCC 内置 Agent 原型${C.reset}`);
87
+ console.log(`${C.dim}模型: ${config.model ?? appConfig.ccc.model}${C.reset}`);
88
+ if (options.cwd) {
89
+ console.log(`${C.dim}目录: ${options.cwd}${C.reset}`);
90
+ }
91
+ console.log(`${C.dim}输入消息开始对话,Ctrl+C 中断当前回复,/exit 退出${C.reset}`);
92
+ console.log("");
93
+
94
+ let session: ChatSession;
95
+ try {
96
+ session = new ChatSession(config, options);
97
+ } catch (err) {
98
+ console.error(`${C.yellow}${(err as Error).message}${C.reset}`);
99
+ process.exit(1);
100
+ }
101
+
102
+ const rl = readline.createInterface({
103
+ input: process.stdin,
104
+ output: process.stdout,
105
+ prompt: `${C.green}>${C.reset} `,
106
+ });
107
+
108
+ // 用于中断当前 LLM 调用的 AbortController
109
+ let currentAbort: AbortController | null = null;
110
+
111
+ rl.prompt();
112
+
113
+ rl.on("line", async (line: string) => {
114
+ const input = line.trim();
115
+ if (!input) {
116
+ rl.prompt();
117
+ return;
118
+ }
119
+
120
+ // 特殊命令
121
+ if (input === "/exit" || input === "/quit") {
122
+ console.log(`${C.dim}再见${C.reset}`);
123
+ rl.close();
124
+ return;
125
+ }
126
+
127
+ if (input === "/clear") {
128
+ session.reset();
129
+ console.log(`${C.dim}会话已重置${C.reset}`);
130
+ rl.prompt();
131
+ return;
132
+ }
133
+
134
+ if (input === "/history") {
135
+ console.log(`${C.dim}共 ${session.turnCount} 轮对话${C.reset}`);
136
+ rl.prompt();
137
+ return;
138
+ }
139
+
140
+ // 发送消息
141
+ currentAbort = new AbortController();
142
+ const signal = currentAbort.signal;
143
+
144
+ try {
145
+ let lastAccumulated = "";
146
+ for await (const event of session.chat(input, signal)) {
147
+ if (event.type === "text") {
148
+ // 增量输出(仅在首次和行首时不换行)
149
+ const newText = event.accumulated.slice(lastAccumulated.length);
150
+ process.stdout.write(newText);
151
+ lastAccumulated = event.accumulated;
152
+ } else if (event.type === "done") {
153
+ if (lastAccumulated) console.log("");
154
+ console.log(`${C.dim}[完成]${C.reset}`);
155
+ } else if (event.type === "error") {
156
+ console.log(`\n${C.yellow}[错误] ${event.message}${C.reset}`);
157
+ }
158
+ }
159
+ } catch (err) {
160
+ console.log(`\n${C.yellow}[错误] ${(err as Error).message}${C.reset}`);
161
+ } finally {
162
+ currentAbort = null;
163
+ }
164
+
165
+ rl.prompt();
166
+ });
167
+
168
+ // Ctrl+C 中断当前 LLM 调用(不退出程序)
169
+ rl.on("SIGINT", () => {
170
+ if (currentAbort) {
171
+ console.log(`\n${C.yellow}[中断中...]${C.reset}`);
172
+ currentAbort.abort();
173
+ currentAbort = null;
174
+ } else {
175
+ console.log(`\n${C.dim}输入 /exit 退出${C.reset}`);
176
+ rl.prompt();
177
+ }
178
+ });
179
+
180
+ rl.on("close", () => {
181
+ console.log("");
182
+ process.exit(0);
183
+ });
184
+ }
185
+
186
+ main().catch((err) => {
187
+ console.error(`${C.yellow}启动失败: ${(err as Error).message}${C.reset}`);
188
+ process.exit(1);
189
+ });