chatccc 0.2.190 → 0.2.191

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 (67) 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 +14 -14
  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 -33
  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 -165
  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 +4 -4
  28. package/src/__tests__/config-sample.test.ts +17 -17
  29. package/src/__tests__/feishu-api.test.ts +60 -60
  30. package/src/__tests__/feishu-platform.test.ts +22 -22
  31. package/src/__tests__/format-message.test.ts +47 -47
  32. package/src/__tests__/orchestrator.test.ts +120 -120
  33. package/src/__tests__/privacy.test.ts +198 -198
  34. package/src/__tests__/raw-stream-log.test.ts +106 -106
  35. package/src/__tests__/session.test.ts +17 -17
  36. package/src/__tests__/shared-prefix.test.ts +36 -36
  37. package/src/__tests__/stream-state.test.ts +42 -42
  38. package/src/__tests__/web-ui.test.ts +209 -209
  39. package/src/adapters/claude-adapter.ts +566 -566
  40. package/src/adapters/claude-session-meta-store.ts +120 -120
  41. package/src/adapters/codex-adapter.ts +30 -30
  42. package/src/adapters/cursor-adapter.ts +46 -46
  43. package/src/adapters/raw-stream-log.ts +124 -124
  44. package/src/adapters/resource-monitor.ts +140 -140
  45. package/src/agent-delegate-task-rpc.ts +153 -153
  46. package/src/agent-delegate-task.ts +81 -81
  47. package/src/agent-stop-stuck.ts +129 -129
  48. package/src/builtin/cli.ts +204 -189
  49. package/src/builtin/index.ts +170 -170
  50. package/src/cards.ts +137 -137
  51. package/src/chatgpt-subscription-rpc.ts +27 -27
  52. package/src/chatgpt-subscription.ts +299 -299
  53. package/src/chrome-devtools-guard.ts +318 -318
  54. package/src/codex-reset-actions.ts +184 -184
  55. package/src/config.ts +86 -86
  56. package/src/feishu-platform.ts +20 -20
  57. package/src/format-message.ts +293 -293
  58. package/src/litellm-proxy.ts +374 -374
  59. package/src/orchestrator.ts +143 -143
  60. package/src/privacy.ts +118 -118
  61. package/src/session-chat-binding.ts +6 -6
  62. package/src/session-name.ts +8 -8
  63. package/src/session.ts +98 -98
  64. package/src/shared-prefix.ts +29 -29
  65. package/src/sim-platform.ts +20 -20
  66. package/src/turn-cards.ts +117 -117
  67. package/src/web-ui.ts +205 -205
@@ -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,189 +1,204 @@
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
- });
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
+ const DOUBLE_CTRL_C_EXIT_WINDOW_MS = 2000;
80
+
81
+ // ---------------------------------------------------------------------------
82
+ // 主程序
83
+ // ---------------------------------------------------------------------------
84
+
85
+ async function main(): Promise<void> {
86
+ const { config, options } = parseArgs();
87
+
88
+ console.log(`${C.dim}ChatCCC 内置 Agent 原型${C.reset}`);
89
+ console.log(`${C.dim}模型: ${config.model ?? appConfig.ccc.model}${C.reset}`);
90
+ if (options.cwd) {
91
+ console.log(`${C.dim}目录: ${options.cwd}${C.reset}`);
92
+ }
93
+ console.log(`${C.dim}输入消息开始对话,Ctrl+C 中断当前回复,exit 退出${C.reset}`);
94
+ console.log("");
95
+
96
+ let session: ChatSession;
97
+ try {
98
+ session = new ChatSession(config, options);
99
+ } catch (err) {
100
+ console.error(`${C.yellow}${(err as Error).message}${C.reset}`);
101
+ process.exit(1);
102
+ }
103
+
104
+ const rl = readline.createInterface({
105
+ input: process.stdin,
106
+ output: process.stdout,
107
+ prompt: `${C.green}>${C.reset} `,
108
+ });
109
+
110
+ // 用于中断当前 LLM 调用的 AbortController
111
+ let currentAbort: AbortController | null = null;
112
+ let lastCtrlCAt = 0;
113
+
114
+ rl.prompt();
115
+
116
+ rl.on("line", async (line: string) => {
117
+ lastCtrlCAt = 0;
118
+ const input = line.trim();
119
+ if (!input) {
120
+ rl.prompt();
121
+ return;
122
+ }
123
+
124
+ // 特殊命令
125
+ if (input === "exit") {
126
+ console.log(`${C.dim}再见${C.reset}`);
127
+ rl.close();
128
+ return;
129
+ }
130
+
131
+ if (input === "/clear") {
132
+ session.reset();
133
+ console.log(`${C.dim}会话已重置${C.reset}`);
134
+ rl.prompt();
135
+ return;
136
+ }
137
+
138
+ if (input === "/history") {
139
+ console.log(`${C.dim}共 ${session.turnCount} 轮对话${C.reset}`);
140
+ rl.prompt();
141
+ return;
142
+ }
143
+
144
+ // 发送消息
145
+ currentAbort = new AbortController();
146
+ const signal = currentAbort.signal;
147
+
148
+ try {
149
+ let lastAccumulated = "";
150
+ for await (const event of session.chat(input, signal)) {
151
+ if (event.type === "text") {
152
+ // 增量输出(仅在首次和行首时不换行)
153
+ const newText = event.accumulated.slice(lastAccumulated.length);
154
+ process.stdout.write(newText);
155
+ lastAccumulated = event.accumulated;
156
+ } else if (event.type === "done") {
157
+ if (lastAccumulated) console.log("");
158
+ console.log(`${C.dim}[完成]${C.reset}`);
159
+ } else if (event.type === "error") {
160
+ console.log(`\n${C.yellow}[错误] ${event.message}${C.reset}`);
161
+ }
162
+ }
163
+ } catch (err) {
164
+ console.log(`\n${C.yellow}[错误] ${(err as Error).message}${C.reset}`);
165
+ } finally {
166
+ currentAbort = null;
167
+ }
168
+
169
+ rl.prompt();
170
+ });
171
+
172
+ // Ctrl+C → 生成中中断;空闲或连续按下时退出
173
+ rl.on("SIGINT", () => {
174
+ const now = Date.now();
175
+ const shouldExit = now - lastCtrlCAt <= DOUBLE_CTRL_C_EXIT_WINDOW_MS;
176
+
177
+ if (shouldExit) {
178
+ console.log(`\n${C.dim}再见${C.reset}`);
179
+ rl.close();
180
+ return;
181
+ }
182
+
183
+ lastCtrlCAt = now;
184
+
185
+ if (currentAbort) {
186
+ console.log(`\n${C.yellow}[中断中...]${C.reset} ${C.dim}再次 Ctrl+C 退出${C.reset}`);
187
+ currentAbort.abort();
188
+ currentAbort = null;
189
+ } else {
190
+ console.log(`\n${C.dim}再次 Ctrl+C 退出,或输入 exit 退出${C.reset}`);
191
+ rl.prompt();
192
+ }
193
+ });
194
+
195
+ rl.on("close", () => {
196
+ console.log("");
197
+ process.exit(0);
198
+ });
199
+ }
200
+
201
+ main().catch((err) => {
202
+ console.error(`${C.yellow}启动失败: ${(err as Error).message}${C.reset}`);
203
+ process.exit(1);
204
+ });