chatccc 0.2.251 → 0.2.253

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 (277) hide show
  1. package/README.md +1 -1
  2. package/bin/cccagent.mjs +12 -3
  3. package/bin/chatccc.mjs +15 -6
  4. package/deepccc-agent/package.json +1 -1
  5. package/dist/deepccc-agent/src/cli.js +634 -0
  6. package/dist/deepccc-agent/src/config.js +76 -0
  7. package/dist/deepccc-agent/src/context.js +348 -0
  8. package/dist/deepccc-agent/src/file-log.js +34 -0
  9. package/dist/deepccc-agent/src/file-tools.js +1208 -0
  10. package/dist/deepccc-agent/src/index.js +571 -0
  11. package/dist/deepccc-agent/src/permissions.js +170 -0
  12. package/dist/deepccc-agent/src/privacy.js +124 -0
  13. package/dist/deepccc-agent/src/proc-tree-kill.js +60 -0
  14. package/dist/deepccc-agent/src/progress/cards-helpers.js +70 -0
  15. package/dist/deepccc-agent/src/progress/reducer.js +102 -0
  16. package/dist/deepccc-agent/src/progress/terminal-renderer.js +264 -0
  17. package/dist/deepccc-agent/src/progress/view.js +30 -0
  18. package/dist/deepccc-agent/src/raw-stream-log.js +106 -0
  19. package/dist/deepccc-agent/src/session-search.js +276 -0
  20. package/dist/deepccc-agent/src/session-select.js +23 -0
  21. package/dist/deepccc-agent/src/sigint.js +26 -0
  22. package/dist/deepccc-agent/src/skills.js +178 -0
  23. package/dist/deepccc-agent/src/web-tools.js +246 -0
  24. package/dist/src/adapters/adapter-interface.js +19 -0
  25. package/dist/src/adapters/ccc-adapter.js +112 -0
  26. package/dist/src/adapters/claude-adapter.js +497 -0
  27. package/dist/src/adapters/claude-session-meta-store.js +92 -0
  28. package/dist/src/adapters/codex-adapter.js +279 -0
  29. package/dist/src/adapters/codex-session-meta-store.js +94 -0
  30. package/dist/src/adapters/cursor-adapter.js +491 -0
  31. package/dist/src/adapters/cursor-session-meta-store.js +116 -0
  32. package/dist/src/adapters/jsonl-stream.js +104 -0
  33. package/{src/adapters/proc-tree-kill.ts → dist/src/adapters/proc-tree-kill.js} +94 -97
  34. package/dist/src/adapters/raw-stream-log.js +106 -0
  35. package/dist/src/adapters/resource-monitor.js +113 -0
  36. package/dist/src/agent-activity.js +133 -0
  37. package/dist/src/agent-delegate-task-rpc.js +129 -0
  38. package/dist/src/agent-delegate-task.js +48 -0
  39. package/dist/src/agent-file-rpc.js +152 -0
  40. package/dist/src/agent-image-rpc.js +148 -0
  41. package/dist/src/agent-platform-routing.js +13 -0
  42. package/dist/src/agent-reload-config-rpc.js +23 -0
  43. package/dist/src/agent-rpc-body.js +87 -0
  44. package/dist/src/agent-stop-stuck.js +110 -0
  45. package/dist/src/card-action-routing.js +7 -0
  46. package/dist/src/card-plain-text.js +101 -0
  47. package/dist/src/cardkit.js +158 -0
  48. package/dist/src/cards.js +573 -0
  49. package/dist/src/chatgpt-subscription-rpc.js +18 -0
  50. package/dist/src/chatgpt-subscription.js +199 -0
  51. package/dist/src/chrome-devtools-guard.js +238 -0
  52. package/dist/src/claude-sdk-installer.js +249 -0
  53. package/dist/src/codex-reset-actions.js +143 -0
  54. package/dist/src/config-utils.js +149 -0
  55. package/dist/src/config.js +804 -0
  56. package/dist/src/cursor-usage.js +77 -0
  57. package/dist/src/exit-banner.js +28 -0
  58. package/dist/src/feishu-api.js +1404 -0
  59. package/dist/src/feishu-message-ingress.js +137 -0
  60. package/dist/src/feishu-platform.js +97 -0
  61. package/dist/src/format-message.js +252 -0
  62. package/dist/src/git-command.js +155 -0
  63. package/dist/src/im-skills.js +121 -0
  64. package/dist/src/index.js +833 -0
  65. package/dist/src/litellm-proxy.js +300 -0
  66. package/dist/src/orchestrator.js +2078 -0
  67. package/dist/src/package-root.js +26 -0
  68. package/dist/src/platform-adapter.js +7 -0
  69. package/dist/src/platform-startup.js +6 -0
  70. package/dist/src/privacy.js +100 -0
  71. package/dist/src/progress/reducer.js +102 -0
  72. package/dist/src/progress/terminal-renderer.js +264 -0
  73. package/dist/src/progress/view.js +30 -0
  74. package/dist/src/response-stall.js +14 -0
  75. package/dist/src/runtime-entry.js +13 -0
  76. package/dist/src/runtime-reload.js +19 -0
  77. package/dist/src/session-chat-binding.js +183 -0
  78. package/dist/src/session-name.js +7 -0
  79. package/dist/src/session.js +2144 -0
  80. package/dist/src/shared-prefix.js +16 -0
  81. package/dist/src/shared.js +493 -0
  82. package/dist/src/sim-agent.js +105 -0
  83. package/dist/src/sim-platform.js +142 -0
  84. package/dist/src/sim-store.js +231 -0
  85. package/dist/src/simplify.js +99 -0
  86. package/dist/src/startup-lifecycle.js +209 -0
  87. package/dist/src/stream-state.js +141 -0
  88. package/dist/src/terminal-error.js +100 -0
  89. package/dist/src/trace.js +50 -0
  90. package/dist/src/turn-cards.js +92 -0
  91. package/dist/src/update-command-guard.js +114 -0
  92. package/{src/web-ui.ts → dist/src/web-ui.js} +749 -823
  93. package/dist/src/wechat-platform.js +545 -0
  94. package/package.json +7 -5
  95. package/deepccc-agent/LICENSE +0 -201
  96. package/deepccc-agent/bin/deepccc.mjs +0 -26
  97. package/deepccc-agent/docs/cache-hit-rate-1.jpg +0 -0
  98. package/deepccc-agent/docs/cache-hit-rate-2.jpg +0 -0
  99. package/deepccc-agent/package-lock.json +0 -2027
  100. package/deepccc-agent/src/__tests__/chat-session.test.ts +0 -852
  101. package/deepccc-agent/src/__tests__/cli-json.test.ts +0 -49
  102. package/deepccc-agent/src/__tests__/config.test.ts +0 -34
  103. package/deepccc-agent/src/__tests__/context.test.ts +0 -341
  104. package/deepccc-agent/src/__tests__/file-tools.test.ts +0 -240
  105. package/deepccc-agent/src/__tests__/permissions.test.ts +0 -199
  106. package/deepccc-agent/src/__tests__/privacy.test.ts +0 -318
  107. package/deepccc-agent/src/__tests__/progress-reducer.test.ts +0 -121
  108. package/deepccc-agent/src/__tests__/session-search.test.ts +0 -262
  109. package/deepccc-agent/src/__tests__/session-select.test.ts +0 -116
  110. package/deepccc-agent/src/__tests__/sigint.test.ts +0 -56
  111. package/deepccc-agent/src/__tests__/skills.test.ts +0 -284
  112. package/deepccc-agent/src/__tests__/terminal-renderer.test.ts +0 -247
  113. package/deepccc-agent/src/__tests__/web-tools.test.ts +0 -220
  114. package/deepccc-agent/src/cli.ts +0 -682
  115. package/deepccc-agent/src/config.ts +0 -101
  116. package/deepccc-agent/src/context.ts +0 -465
  117. package/deepccc-agent/src/file-log.ts +0 -38
  118. package/deepccc-agent/src/file-tools.ts +0 -1493
  119. package/deepccc-agent/src/index.ts +0 -676
  120. package/deepccc-agent/src/permissions.ts +0 -226
  121. package/deepccc-agent/src/privacy.ts +0 -141
  122. package/deepccc-agent/src/proc-tree-kill.ts +0 -61
  123. package/deepccc-agent/src/progress/cards-helpers.ts +0 -76
  124. package/deepccc-agent/src/progress/reducer.ts +0 -113
  125. package/deepccc-agent/src/progress/terminal-renderer.ts +0 -294
  126. package/deepccc-agent/src/progress/view.ts +0 -77
  127. package/deepccc-agent/src/raw-stream-log.ts +0 -124
  128. package/deepccc-agent/src/session-search.ts +0 -370
  129. package/deepccc-agent/src/session-select.ts +0 -48
  130. package/deepccc-agent/src/sigint.ts +0 -50
  131. package/deepccc-agent/src/skills.ts +0 -205
  132. package/deepccc-agent/src/web-tools.ts +0 -313
  133. package/deepccc-agent/tsconfig.build.json +0 -13
  134. package/deepccc-agent/tsconfig.json +0 -13
  135. package/deepccc-agent/vitest.config.ts +0 -7
  136. package/src/__tests__/adapter-interface.test.ts +0 -152
  137. package/src/__tests__/agent-activity.test.ts +0 -86
  138. package/src/__tests__/agent-delegate-task-rpc.test.ts +0 -165
  139. package/src/__tests__/agent-image-rpc.test.ts +0 -34
  140. package/src/__tests__/agent-platform-routing.test.ts +0 -26
  141. package/src/__tests__/agent-reload-config-rpc.test.ts +0 -99
  142. package/src/__tests__/agent-rpc-body.test.ts +0 -42
  143. package/src/__tests__/builtin-chat-session.test.ts +0 -532
  144. package/src/__tests__/builtin-cli-json.test.ts +0 -39
  145. package/src/__tests__/builtin-config.test.ts +0 -26
  146. package/src/__tests__/builtin-context.test.ts +0 -319
  147. package/src/__tests__/builtin-file-tools.test.ts +0 -240
  148. package/src/__tests__/builtin-permissions.test.ts +0 -219
  149. package/src/__tests__/builtin-session-search.test.ts +0 -262
  150. package/src/__tests__/builtin-session-select.test.ts +0 -116
  151. package/src/__tests__/builtin-sigint.test.ts +0 -56
  152. package/src/__tests__/builtin-skills.test.ts +0 -284
  153. package/src/__tests__/builtin-web-tools.test.ts +0 -220
  154. package/src/__tests__/card-action-routing.test.ts +0 -18
  155. package/src/__tests__/card-plain-text.test.ts +0 -45
  156. package/src/__tests__/cardkit.test.ts +0 -60
  157. package/src/__tests__/cards.test.ts +0 -607
  158. package/src/__tests__/ccc-adapter.test.ts +0 -194
  159. package/src/__tests__/chatgpt-subscription-rpc.test.ts +0 -89
  160. package/src/__tests__/chatgpt-subscription.test.ts +0 -135
  161. package/src/__tests__/chrome-devtools-guard.test.ts +0 -165
  162. package/src/__tests__/claude-adapter.test.ts +0 -614
  163. package/src/__tests__/claude-raw-stream-log.test.ts +0 -96
  164. package/src/__tests__/claude-sdk-installer.test.ts +0 -285
  165. package/src/__tests__/codex-adapter.test.ts +0 -331
  166. package/src/__tests__/codex-raw-stream-log.test.ts +0 -170
  167. package/src/__tests__/codex-reset-actions.test.ts +0 -146
  168. package/src/__tests__/config-reload.test.ts +0 -284
  169. package/src/__tests__/config-sample.test.ts +0 -97
  170. package/src/__tests__/config-utils.test.ts +0 -40
  171. package/src/__tests__/config.test.ts +0 -395
  172. package/src/__tests__/crash-logging.test.ts +0 -360
  173. package/src/__tests__/cursor-adapter.test.ts +0 -890
  174. package/src/__tests__/cursor-session-meta-store.test.ts +0 -212
  175. package/src/__tests__/feishu-api.test.ts +0 -60
  176. package/src/__tests__/feishu-avatar.test.ts +0 -504
  177. package/src/__tests__/feishu-message-ingress.test.ts +0 -138
  178. package/src/__tests__/feishu-platform.test.ts +0 -75
  179. package/src/__tests__/fixtures/codex_simple_text.jsonl +0 -4
  180. package/src/__tests__/fixtures/codex_with_tool.jsonl +0 -6
  181. package/src/__tests__/fixtures/cursor_partial_only.jsonl +0 -5
  182. package/src/__tests__/fixtures/cursor_partial_with_final.jsonl +0 -13
  183. package/src/__tests__/fixtures/cursor_with_tool_call.jsonl +0 -12
  184. package/src/__tests__/format-message.test.ts +0 -316
  185. package/src/__tests__/git-command.test.ts +0 -288
  186. package/src/__tests__/im-skills.test.ts +0 -125
  187. package/src/__tests__/jsonl-stream.test.ts +0 -79
  188. package/src/__tests__/orchestrator.test.ts +0 -1268
  189. package/src/__tests__/package-files.test.ts +0 -24
  190. package/src/__tests__/platform-startup.test.ts +0 -19
  191. package/src/__tests__/privacy.test.ts +0 -198
  192. package/src/__tests__/proc-tree-kill.test.ts +0 -108
  193. package/src/__tests__/progress-reducer.test.ts +0 -121
  194. package/src/__tests__/raw-stream-log.test.ts +0 -106
  195. package/src/__tests__/response-stall.test.ts +0 -49
  196. package/src/__tests__/restart.test.ts +0 -232
  197. package/src/__tests__/session-ccc-config.test.ts +0 -66
  198. package/src/__tests__/session.test.ts +0 -3004
  199. package/src/__tests__/shared-prefix.test.ts +0 -36
  200. package/src/__tests__/sim-agent.test.ts +0 -174
  201. package/src/__tests__/sim-platform.test.ts +0 -93
  202. package/src/__tests__/sim-store.test.ts +0 -214
  203. package/src/__tests__/simplify.test.ts +0 -283
  204. package/src/__tests__/startup-lifecycle.test.ts +0 -231
  205. package/src/__tests__/stop-session.test.ts +0 -162
  206. package/src/__tests__/stream-state.test.ts +0 -164
  207. package/src/__tests__/terminal-error.test.ts +0 -54
  208. package/src/__tests__/terminal-renderer.test.ts +0 -247
  209. package/src/__tests__/update-command-guard.test.ts +0 -144
  210. package/src/__tests__/web-ui.test.ts +0 -438
  211. package/src/__tests__/wechat-platform.test.ts +0 -111
  212. package/src/adapters/adapter-interface.ts +0 -217
  213. package/src/adapters/ccc-adapter.ts +0 -150
  214. package/src/adapters/claude-adapter.ts +0 -673
  215. package/src/adapters/claude-session-meta-store.ts +0 -120
  216. package/src/adapters/codex-adapter.ts +0 -426
  217. package/src/adapters/codex-session-meta-store.ts +0 -131
  218. package/src/adapters/cursor-adapter.ts +0 -681
  219. package/src/adapters/cursor-session-meta-store.ts +0 -154
  220. package/src/adapters/jsonl-stream.ts +0 -157
  221. package/src/adapters/raw-stream-log.ts +0 -124
  222. package/src/adapters/resource-monitor.ts +0 -141
  223. package/src/agent-activity.ts +0 -175
  224. package/src/agent-delegate-task-rpc.ts +0 -153
  225. package/src/agent-delegate-task.ts +0 -91
  226. package/src/agent-file-rpc.ts +0 -172
  227. package/src/agent-image-rpc.ts +0 -168
  228. package/src/agent-platform-routing.ts +0 -28
  229. package/src/agent-reload-config-rpc.ts +0 -34
  230. package/src/agent-rpc-body.ts +0 -92
  231. package/src/agent-stop-stuck.ts +0 -129
  232. package/src/card-action-routing.ts +0 -14
  233. package/src/card-plain-text.ts +0 -108
  234. package/src/cardkit.ts +0 -179
  235. package/src/cards.ts +0 -684
  236. package/src/chatgpt-subscription-rpc.ts +0 -27
  237. package/src/chatgpt-subscription.ts +0 -299
  238. package/src/chrome-devtools-guard.ts +0 -318
  239. package/src/claude-sdk-installer.ts +0 -324
  240. package/src/codex-reset-actions.ts +0 -184
  241. package/src/config-utils.ts +0 -211
  242. package/src/config.ts +0 -1063
  243. package/src/cursor-usage.ts +0 -128
  244. package/src/exit-banner.ts +0 -33
  245. package/src/feishu-api.ts +0 -1616
  246. package/src/feishu-message-ingress.ts +0 -195
  247. package/src/feishu-platform.ts +0 -159
  248. package/src/format-message.ts +0 -293
  249. package/src/git-command.ts +0 -202
  250. package/src/im-skills.ts +0 -149
  251. package/src/index.ts +0 -1089
  252. package/src/litellm-proxy.ts +0 -374
  253. package/src/orchestrator.ts +0 -2543
  254. package/src/platform-adapter.ts +0 -70
  255. package/src/platform-startup.ts +0 -16
  256. package/src/privacy.ts +0 -118
  257. package/src/progress/reducer.ts +0 -113
  258. package/src/progress/terminal-renderer.ts +0 -294
  259. package/src/progress/view.ts +0 -77
  260. package/src/response-stall.ts +0 -28
  261. package/src/runtime-reload.ts +0 -34
  262. package/src/session-chat-binding.ts +0 -292
  263. package/src/session-name.ts +0 -8
  264. package/src/session.ts +0 -2659
  265. package/src/shared-prefix.ts +0 -29
  266. package/src/shared.ts +0 -552
  267. package/src/sim-agent.ts +0 -167
  268. package/src/sim-platform.ts +0 -177
  269. package/src/sim-store.ts +0 -317
  270. package/src/simplify.ts +0 -120
  271. package/src/startup-lifecycle.ts +0 -250
  272. package/src/stream-state.ts +0 -177
  273. package/src/terminal-error.ts +0 -129
  274. package/src/trace.ts +0 -51
  275. package/src/turn-cards.ts +0 -118
  276. package/src/update-command-guard.ts +0 -165
  277. package/src/wechat-platform.ts +0 -680
@@ -1,168 +0,0 @@
1
- import type { IncomingMessage, ServerResponse } from "node:http";
2
- import { extname, isAbsolute, resolve } from "node:path";
3
- import { stat } from "node:fs/promises";
4
-
5
- import { getTenantAccessToken, sendImageReply, sendTextReply } from "./feishu-platform.ts";
6
- import { ts, resolveDefaultAgentTool } from "./config.ts";
7
- import { readUtf8JsonBody } from "./agent-rpc-body.ts";
8
- import { getAdapterForTool } from "./session.ts";
9
- import { getChatsForSession } from "./session-chat-binding.ts";
10
- import { splitFeishuTargetChats } from "./agent-platform-routing.ts";
11
-
12
- export const AGENT_SEND_IMAGE_PATH = "/api/agent/send-image";
13
-
14
- const MAX_REQUEST_BYTES = 64 * 1024;
15
- const MAX_IMAGE_BYTES = 10 * 1024 * 1024;
16
- const ALLOWED_IMAGE_EXTS = new Set([".png", ".jpg", ".jpeg", ".webp", ".gif", ".bmp"]);
17
-
18
- function jsonReply(res: ServerResponse, status: number, data: unknown): void {
19
- res.writeHead(status, { "Content-Type": "application/json; charset=utf-8" });
20
- res.end(JSON.stringify(data));
21
- }
22
-
23
- async function resolveAndValidateImagePath(cwd: string, rawPath: unknown): Promise<string> {
24
- if (typeof rawPath !== "string" || rawPath.trim() === "") {
25
- throw new Error("path must be a non-empty string");
26
- }
27
-
28
- const sessionRoot = resolve(cwd);
29
- const imagePath = isAbsolute(rawPath)
30
- ? resolve(rawPath)
31
- : resolve(sessionRoot, rawPath);
32
-
33
- const ext = extname(imagePath).toLowerCase();
34
- if (!ALLOWED_IMAGE_EXTS.has(ext)) {
35
- throw new Error(`unsupported image extension: ${ext || "(none)"}`);
36
- }
37
-
38
- const st = await stat(imagePath);
39
- if (!st.isFile()) throw new Error("image path is not a file");
40
- if (st.size <= 0) throw new Error("image file is empty");
41
- if (st.size > MAX_IMAGE_BYTES) throw new Error("image file is larger than 10MB");
42
- return imagePath;
43
- }
44
-
45
- export async function handleAgentImageRequest(
46
- req: IncomingMessage,
47
- res: ServerResponse,
48
- ): Promise<boolean> {
49
- const url = new URL(req.url ?? "/", "http://127.0.0.1");
50
- if (url.pathname !== AGENT_SEND_IMAGE_PATH) return false;
51
-
52
- if (req.method !== "POST") {
53
- jsonReply(res, 405, { ok: false, error: "Method not allowed" });
54
- return true;
55
- }
56
-
57
- let payload: { session_id?: unknown; path?: unknown; caption?: unknown };
58
- try {
59
- payload = await readUtf8JsonBody(req, MAX_REQUEST_BYTES);
60
- } catch (err) {
61
- jsonReply(res, 400, { ok: false, error: (err as Error).message || "Invalid JSON" });
62
- return true;
63
- }
64
-
65
- const sessionId = typeof payload.session_id === "string" ? payload.session_id : "";
66
- if (!sessionId) {
67
- jsonReply(res, 400, { ok: false, error: "Missing session_id" });
68
- return true;
69
- }
70
-
71
- // 获取 cwd 以校验路径
72
- let cwd: string;
73
- try {
74
- const { getSessionTool } = await import("./session.ts");
75
- const tool = await getSessionTool(sessionId);
76
- const adapter = getAdapterForTool(tool ?? resolveDefaultAgentTool());
77
- const info = await adapter.getSessionInfo(sessionId);
78
- if (!info?.cwd) {
79
- jsonReply(res, 400, { ok: false, error: "Cannot determine cwd for session" });
80
- return true;
81
- }
82
- cwd = info.cwd;
83
- } catch (err) {
84
- jsonReply(res, 500, { ok: false, error: `Failed to get session info: ${(err as Error).message}` });
85
- return true;
86
- }
87
-
88
- let imagePath: string;
89
- try {
90
- imagePath = await resolveAndValidateImagePath(cwd, payload.path);
91
- } catch (err) {
92
- jsonReply(res, 400, { ok: false, error: (err as Error).message });
93
- return true;
94
- }
95
-
96
- // 发送到所有绑定该 session 的群
97
- const chatIds = getChatsForSession(sessionId);
98
- if (chatIds.length === 0) {
99
- jsonReply(res, 404, { ok: false, error: "No chats bound to this session" });
100
- return true;
101
- }
102
-
103
- const { getPlatformForChat } = await import("./session.ts");
104
- const { targetChatIds, skippedUnsupported } = splitFeishuTargetChats(
105
- chatIds,
106
- (cid) => getPlatformForChat(cid)?.kind,
107
- );
108
- if (targetChatIds.length === 0) {
109
- jsonReply(res, 409, {
110
- ok: false,
111
- error: "This endpoint only sends to Feishu chats. The bound chats are WeChat chats; use the WeChat image helper script instead.",
112
- skippedUnsupported,
113
- });
114
- return true;
115
- }
116
-
117
- try {
118
- const token = await getTenantAccessToken();
119
- const caption = typeof payload.caption === "string" ? payload.caption.trim() : "";
120
- let sentCount = 0;
121
- for (const cid of targetChatIds) {
122
- try {
123
- await sendImageReply(token, cid, imagePath);
124
- if (caption) await sendTextReply(token, cid, caption);
125
- sentCount++;
126
- } catch (err) {
127
- console.error(`[${ts()}] [AGENT-IMAGE] send to ${cid} failed: ${(err as Error).message}`);
128
- }
129
- }
130
- console.log(`[${ts()}] [AGENT-IMAGE] sent image to ${sentCount}/${targetChatIds.length} Feishu chats, session=${sessionId} path=${imagePath} skippedUnsupported=${skippedUnsupported.length}`);
131
- jsonReply(res, 200, { ok: true, sentTo: sentCount, total: targetChatIds.length, skippedUnsupported });
132
- } catch (err) {
133
- console.error(`[${ts()}] [AGENT-IMAGE] send failed: ${(err as Error).message}`);
134
- jsonReply(res, 500, { ok: false, error: (err as Error).message });
135
- }
136
- return true;
137
- }
138
-
139
- // ---------------------------------------------------------------------------
140
- // 兼容旧版 buildAgentImageCapabilityPrompt(供 im-skills 使用)
141
- // ---------------------------------------------------------------------------
142
-
143
- export function buildAgentImageCapabilityPrompt(input: {
144
- url: string;
145
- sessionId?: string;
146
- cwd?: string;
147
- }): string {
148
- const lines = [
149
- "[ChatCCC local capability: send image]",
150
- "You can send an image to all chats bound to this session by calling this local endpoint.",
151
- "",
152
- `POST ${input.url}`,
153
- "Content-Type: application/json; charset=utf-8",
154
- "",
155
- `Body: {"session_id":"${input.sessionId ?? "YOUR_SESSION_ID"}","path":"absolute image file path","caption":"optional caption"}`,
156
- "",
157
- "Rules:",
158
- "- Save or choose a local image file first, then call the endpoint.",
159
- "- Use an absolute local file path. Do not call Feishu Open Platform directly.",
160
- "- Request body must be UTF-8 encoded JSON bytes; caption supports Unicode text, including Chinese.",
161
- "- Only call this endpoint when the user asked for an image or when an image is useful to the answer.",
162
- "[/ChatCCC local capability: send image]",
163
- ];
164
- if (input.cwd) {
165
- lines.splice(2, 0, `Current working directory: ${input.cwd}`);
166
- }
167
- return lines.join("\n");
168
- }
@@ -1,28 +0,0 @@
1
- export interface SkippedUnsupportedChat {
2
- chatId: string;
3
- platformKind: string;
4
- }
5
-
6
- export interface FeishuTargetSplit {
7
- targetChatIds: string[];
8
- skippedUnsupported: SkippedUnsupportedChat[];
9
- }
10
-
11
- export function splitFeishuTargetChats(
12
- chatIds: readonly string[],
13
- getPlatformKind: (chatId: string) => string | undefined,
14
- ): FeishuTargetSplit {
15
- const targetChatIds: string[] = [];
16
- const skippedUnsupported: SkippedUnsupportedChat[] = [];
17
-
18
- for (const chatId of chatIds) {
19
- const platformKind = getPlatformKind(chatId);
20
- if (platformKind === "wechat") {
21
- skippedUnsupported.push({ chatId, platformKind });
22
- continue;
23
- }
24
- targetChatIds.push(chatId);
25
- }
26
-
27
- return { targetChatIds, skippedUnsupported };
28
- }
@@ -1,34 +0,0 @@
1
- import type { IncomingMessage, ServerResponse } from "node:http";
2
-
3
- import { reloadRuntimeConfig, type RuntimeReloadResult } from "./runtime-reload.ts";
4
-
5
- export const AGENT_RELOAD_CONFIG_PATH = "/api/agent/reload-config";
6
-
7
- type ReloadRuntimeConfig = (source: string) => RuntimeReloadResult | Promise<RuntimeReloadResult>;
8
-
9
- function jsonReply(res: ServerResponse, status: number, data: unknown): void {
10
- res.writeHead(status, { "Content-Type": "application/json; charset=utf-8" });
11
- res.end(JSON.stringify(data));
12
- }
13
-
14
- export async function handleAgentReloadConfigRequest(
15
- req: IncomingMessage,
16
- res: ServerResponse,
17
- reload: ReloadRuntimeConfig = reloadRuntimeConfig,
18
- ): Promise<boolean> {
19
- const url = new URL(req.url ?? "/", "http://127.0.0.1");
20
- if (url.pathname !== AGENT_RELOAD_CONFIG_PATH) return false;
21
-
22
- if (req.method !== "POST") {
23
- jsonReply(res, 405, { ok: false, error: "Method not allowed" });
24
- return true;
25
- }
26
-
27
- try {
28
- const result = await reload("agent-reload-api");
29
- jsonReply(res, 200, { ok: true, ...result });
30
- } catch (err) {
31
- jsonReply(res, 500, { ok: false, error: (err as Error).message });
32
- }
33
- return true;
34
- }
@@ -1,92 +0,0 @@
1
- import type { IncomingMessage } from "node:http";
2
- import { TextDecoder } from "node:util";
3
-
4
- // Windows 下 curl 传中文可能用 GBK 编码而非 UTF-8,按顺序尝试解码
5
- const FALLBACK_ENCODINGS = ["gbk", "gb2312", "latin1"];
6
-
7
- /**
8
- * 检测 UTF-8 解码结果是否看起来像乱码(GBK 字节被误当 UTF-8 解析)。
9
- * 典型特征:有 Latin-1 补充字符(U+0080-U+00FF)但没有 CJK 字符。
10
- */
11
- function hasGarbledPattern(text: string): boolean {
12
- let latin1Count = 0;
13
- let cjkCount = 0;
14
- for (const ch of text) {
15
- const code = ch.codePointAt(0) ?? 0;
16
- if (code >= 0x4E00 && code <= 0x9FFF) cjkCount++;
17
- if (code >= 0x0080 && code <= 0x00FF) latin1Count++;
18
- }
19
- return latin1Count > 0 && cjkCount === 0;
20
- }
21
-
22
- function normalizeHeaderValue(value: string | string[] | undefined): string {
23
- if (Array.isArray(value)) return value.join("; ");
24
- return value ?? "";
25
- }
26
-
27
- export function getRequestCharset(req: IncomingMessage): string {
28
- const contentType = normalizeHeaderValue(req.headers["content-type"]);
29
- const match = contentType.match(/(?:^|;)\s*charset\s*=\s*("?)([^";\s]+)\1/i);
30
- return (match?.[2] ?? "utf-8").toLowerCase();
31
- }
32
-
33
- async function readLimitedBodyBuffer(req: IncomingMessage, maxBytes: number): Promise<Buffer> {
34
- const chunks: Buffer[] = [];
35
- let size = 0;
36
-
37
- return new Promise((resolve, reject) => {
38
- req.on("data", (chunk: Buffer) => {
39
- size += chunk.length;
40
- if (size > maxBytes) {
41
- reject(new Error("Request body too large"));
42
- req.destroy();
43
- return;
44
- }
45
- chunks.push(chunk);
46
- });
47
- req.on("end", () => resolve(Buffer.concat(chunks, size)));
48
- req.on("error", reject);
49
- });
50
- }
51
-
52
- export async function readUtf8JsonBody<T>(req: IncomingMessage, maxBytes: number): Promise<T> {
53
- const charset = getRequestCharset(req);
54
- if (charset !== "utf-8" && charset !== "utf8") {
55
- throw new Error(`Unsupported charset: ${charset}. Use UTF-8 JSON.`);
56
- }
57
-
58
- const body = await readLimitedBodyBuffer(req, maxBytes);
59
-
60
- // 首选 UTF-8;若 JSON 解析失败则尝试常见中文编码
61
- // 注意:UTF-8 解码可能"成功"但实际是 GBK 字节被误当 UTF-8 解析,
62
- // 此时 JSON 也能解析通过但中文变成乱码。通过 hasGarbledPattern 检测
63
- // 这种"假成功"并回退到 GBK。
64
- try {
65
- const text = new TextDecoder("utf-8", { fatal: true }).decode(body);
66
- const parsed = JSON.parse(text) as T;
67
- if (hasGarbledPattern(text)) {
68
- // UTF-8 解码出的文本看起来像乱码,尝试 GBK
69
- try {
70
- const gbkText = new TextDecoder("gbk", { fatal: true }).decode(body);
71
- return JSON.parse(gbkText) as T;
72
- } catch {
73
- // GBK 也不行,用 UTF-8 结果
74
- }
75
- }
76
- return parsed;
77
- } catch {
78
- // UTF-8 解码失败,尝试其他编码
79
- }
80
-
81
- for (const enc of FALLBACK_ENCODINGS) {
82
- try {
83
- const text = new TextDecoder(enc, { fatal: true }).decode(body);
84
- return JSON.parse(text) as T;
85
- } catch {
86
- // 解码或 JSON 解析失败,尝试下一个编码
87
- }
88
- }
89
- const err = new Error("Request body must be valid UTF-8 JSON");
90
- (err as { rawBody?: Buffer }).rawBody = body;
91
- throw err;
92
- }
@@ -1,129 +0,0 @@
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,14 +0,0 @@
1
- export type FeishuCommandChatType = "p2p" | "group";
2
-
3
- type SessionRegistryForRouting = Record<string, { chatType?: string }>;
4
-
5
- /**
6
- * Feishu card action callbacks do not include the chat type. Recover it from
7
- * the persisted binding so buttons clicked in a private chat stay in p2p.
8
- */
9
- export function resolveFeishuCardActionChatType(
10
- chatId: string,
11
- registry: SessionRegistryForRouting,
12
- ): FeishuCommandChatType {
13
- return registry[chatId]?.chatType === "p2p" ? "p2p" : "group";
14
- }
@@ -1,108 +0,0 @@
1
- type JsonObject = Record<string, unknown>;
2
-
3
- function isObject(value: unknown): value is JsonObject {
4
- return !!value && typeof value === "object" && !Array.isArray(value);
5
- }
6
-
7
- function stringValue(value: unknown): string | null {
8
- return typeof value === "string" && value.trim() ? value.trim() : null;
9
- }
10
-
11
- function textContent(value: unknown): string | null {
12
- if (typeof value === "string") return stringValue(value);
13
- if (!isObject(value)) return null;
14
- return stringValue(value.content);
15
- }
16
-
17
- function parseButtonValue(value: unknown): unknown {
18
- if (typeof value !== "string") return value;
19
- try {
20
- return JSON.parse(value);
21
- } catch {
22
- return value;
23
- }
24
- }
25
-
26
- function commandFromValue(value: unknown): string | null {
27
- const parsed = parseButtonValue(value);
28
- if (typeof parsed === "string") {
29
- const trimmed = parsed.trim();
30
- return trimmed.startsWith("/") ? trimmed : null;
31
- }
32
- if (!isObject(parsed)) return null;
33
-
34
- const cmd = stringValue(parsed.cmd);
35
- if (cmd) return cmd.startsWith("/") ? cmd : `/${cmd}`;
36
-
37
- const action = stringValue(parsed.action);
38
- if (!action) return null;
39
-
40
- if (action === "cd") {
41
- const path = stringValue(parsed.path);
42
- return path ? `/cd ${path}` : "/cd";
43
- }
44
- return action.startsWith("/") ? action : `/${action}`;
45
- }
46
-
47
- function buttonText(element: JsonObject): string | null {
48
- const label = textContent(element.text);
49
- const command = commandFromValue(element.value);
50
- if (label && command) return `${label}: ${command}`;
51
- return label ?? command;
52
- }
53
-
54
- function elementToText(element: unknown): string[] {
55
- if (!isObject(element)) return [];
56
- const tag = stringValue(element.tag);
57
-
58
- if (tag === "div") {
59
- const content = textContent(element.text);
60
- return content ? [content] : [];
61
- }
62
-
63
- if (tag === "markdown") {
64
- const content = stringValue(element.content);
65
- return content ? [content] : [];
66
- }
67
-
68
- if (tag === "button") {
69
- const content = buttonText(element);
70
- return content ? [content] : [];
71
- }
72
-
73
- if (tag === "action" && Array.isArray(element.actions)) {
74
- return element.actions.flatMap(elementToText);
75
- }
76
-
77
- return [];
78
- }
79
-
80
- function rootElements(card: JsonObject): unknown[] {
81
- if (Array.isArray(card.elements)) return card.elements;
82
- if (isObject(card.body) && Array.isArray(card.body.elements)) {
83
- return card.body.elements;
84
- }
85
- return [];
86
- }
87
-
88
- export function cardJsonToPlainText(cardJson: string): string | null {
89
- let card: unknown;
90
- try {
91
- card = JSON.parse(cardJson);
92
- } catch {
93
- return null;
94
- }
95
- if (!isObject(card)) return null;
96
-
97
- const title = isObject(card.header) && isObject(card.header.title)
98
- ? textContent(card.header.title)
99
- : null;
100
- const lines = rootElements(card).flatMap(elementToText);
101
- const parts = title ? [`# ${title}`, ...lines] : lines;
102
- const text = parts
103
- .map((part) => part.trim())
104
- .filter(Boolean)
105
- .join("\n\n")
106
- .trim();
107
- return text || null;
108
- }