chatccc 0.2.252 → 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 (280) 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/os-prompts/darwin.md +8 -8
  5. package/deepccc-agent/os-prompts/linux.md +8 -8
  6. package/deepccc-agent/os-prompts/win32.md +11 -11
  7. package/deepccc-agent/package.json +65 -65
  8. package/dist/deepccc-agent/src/cli.js +634 -0
  9. package/dist/deepccc-agent/src/config.js +76 -0
  10. package/dist/deepccc-agent/src/context.js +348 -0
  11. package/dist/deepccc-agent/src/file-log.js +34 -0
  12. package/dist/deepccc-agent/src/file-tools.js +1208 -0
  13. package/dist/deepccc-agent/src/index.js +571 -0
  14. package/dist/deepccc-agent/src/permissions.js +170 -0
  15. package/dist/deepccc-agent/src/privacy.js +124 -0
  16. package/dist/deepccc-agent/src/proc-tree-kill.js +60 -0
  17. package/dist/deepccc-agent/src/progress/cards-helpers.js +70 -0
  18. package/dist/deepccc-agent/src/progress/reducer.js +102 -0
  19. package/dist/deepccc-agent/src/progress/terminal-renderer.js +264 -0
  20. package/dist/deepccc-agent/src/progress/view.js +30 -0
  21. package/dist/deepccc-agent/src/raw-stream-log.js +106 -0
  22. package/dist/deepccc-agent/src/session-search.js +276 -0
  23. package/dist/deepccc-agent/src/session-select.js +23 -0
  24. package/dist/deepccc-agent/src/sigint.js +26 -0
  25. package/dist/deepccc-agent/src/skills.js +178 -0
  26. package/dist/deepccc-agent/src/web-tools.js +246 -0
  27. package/dist/src/adapters/adapter-interface.js +19 -0
  28. package/dist/src/adapters/ccc-adapter.js +112 -0
  29. package/dist/src/adapters/claude-adapter.js +497 -0
  30. package/dist/src/adapters/claude-session-meta-store.js +92 -0
  31. package/dist/src/adapters/codex-adapter.js +279 -0
  32. package/dist/src/adapters/codex-session-meta-store.js +94 -0
  33. package/dist/src/adapters/cursor-adapter.js +491 -0
  34. package/dist/src/adapters/cursor-session-meta-store.js +116 -0
  35. package/dist/src/adapters/jsonl-stream.js +104 -0
  36. package/{src/adapters/proc-tree-kill.ts → dist/src/adapters/proc-tree-kill.js} +94 -97
  37. package/dist/src/adapters/raw-stream-log.js +106 -0
  38. package/dist/src/adapters/resource-monitor.js +113 -0
  39. package/dist/src/agent-activity.js +133 -0
  40. package/dist/src/agent-delegate-task-rpc.js +129 -0
  41. package/dist/src/agent-delegate-task.js +48 -0
  42. package/dist/src/agent-file-rpc.js +152 -0
  43. package/dist/src/agent-image-rpc.js +148 -0
  44. package/dist/src/agent-platform-routing.js +13 -0
  45. package/dist/src/agent-reload-config-rpc.js +23 -0
  46. package/dist/src/agent-rpc-body.js +87 -0
  47. package/dist/src/agent-stop-stuck.js +110 -0
  48. package/dist/src/card-action-routing.js +7 -0
  49. package/dist/src/card-plain-text.js +101 -0
  50. package/dist/src/cardkit.js +158 -0
  51. package/dist/src/cards.js +573 -0
  52. package/dist/src/chatgpt-subscription-rpc.js +18 -0
  53. package/dist/src/chatgpt-subscription.js +199 -0
  54. package/dist/src/chrome-devtools-guard.js +238 -0
  55. package/dist/src/claude-sdk-installer.js +249 -0
  56. package/dist/src/codex-reset-actions.js +143 -0
  57. package/dist/src/config-utils.js +149 -0
  58. package/dist/src/config.js +804 -0
  59. package/dist/src/cursor-usage.js +77 -0
  60. package/dist/src/exit-banner.js +28 -0
  61. package/dist/src/feishu-api.js +1404 -0
  62. package/dist/src/feishu-message-ingress.js +137 -0
  63. package/dist/src/feishu-platform.js +97 -0
  64. package/dist/src/format-message.js +252 -0
  65. package/dist/src/git-command.js +155 -0
  66. package/dist/src/im-skills.js +121 -0
  67. package/dist/src/index.js +833 -0
  68. package/dist/src/litellm-proxy.js +300 -0
  69. package/dist/src/orchestrator.js +2078 -0
  70. package/dist/src/package-root.js +26 -0
  71. package/dist/src/platform-adapter.js +7 -0
  72. package/dist/src/platform-startup.js +6 -0
  73. package/dist/src/privacy.js +100 -0
  74. package/dist/src/progress/reducer.js +102 -0
  75. package/dist/src/progress/terminal-renderer.js +264 -0
  76. package/dist/src/progress/view.js +30 -0
  77. package/dist/src/response-stall.js +14 -0
  78. package/dist/src/runtime-entry.js +13 -0
  79. package/dist/src/runtime-reload.js +19 -0
  80. package/dist/src/session-chat-binding.js +183 -0
  81. package/dist/src/session-name.js +7 -0
  82. package/dist/src/session.js +2144 -0
  83. package/dist/src/shared-prefix.js +16 -0
  84. package/dist/src/shared.js +493 -0
  85. package/dist/src/sim-agent.js +105 -0
  86. package/dist/src/sim-platform.js +142 -0
  87. package/dist/src/sim-store.js +231 -0
  88. package/dist/src/simplify.js +99 -0
  89. package/dist/src/startup-lifecycle.js +209 -0
  90. package/dist/src/stream-state.js +141 -0
  91. package/dist/src/terminal-error.js +100 -0
  92. package/dist/src/trace.js +50 -0
  93. package/dist/src/turn-cards.js +92 -0
  94. package/dist/src/update-command-guard.js +114 -0
  95. package/{src/web-ui.ts → dist/src/web-ui.js} +749 -823
  96. package/dist/src/wechat-platform.js +545 -0
  97. package/package.json +76 -74
  98. package/deepccc-agent/LICENSE +0 -201
  99. package/deepccc-agent/bin/deepccc.mjs +0 -26
  100. package/deepccc-agent/docs/cache-hit-rate-1.jpg +0 -0
  101. package/deepccc-agent/docs/cache-hit-rate-2.jpg +0 -0
  102. package/deepccc-agent/package-lock.json +0 -2027
  103. package/deepccc-agent/src/__tests__/chat-session.test.ts +0 -877
  104. package/deepccc-agent/src/__tests__/cli-json.test.ts +0 -49
  105. package/deepccc-agent/src/__tests__/config.test.ts +0 -34
  106. package/deepccc-agent/src/__tests__/context.test.ts +0 -341
  107. package/deepccc-agent/src/__tests__/file-tools.test.ts +0 -240
  108. package/deepccc-agent/src/__tests__/permissions.test.ts +0 -199
  109. package/deepccc-agent/src/__tests__/privacy.test.ts +0 -318
  110. package/deepccc-agent/src/__tests__/progress-reducer.test.ts +0 -121
  111. package/deepccc-agent/src/__tests__/session-search.test.ts +0 -262
  112. package/deepccc-agent/src/__tests__/session-select.test.ts +0 -116
  113. package/deepccc-agent/src/__tests__/sigint.test.ts +0 -56
  114. package/deepccc-agent/src/__tests__/skills.test.ts +0 -284
  115. package/deepccc-agent/src/__tests__/terminal-renderer.test.ts +0 -247
  116. package/deepccc-agent/src/__tests__/web-tools.test.ts +0 -220
  117. package/deepccc-agent/src/cli.ts +0 -682
  118. package/deepccc-agent/src/config.ts +0 -101
  119. package/deepccc-agent/src/context.ts +0 -465
  120. package/deepccc-agent/src/file-log.ts +0 -38
  121. package/deepccc-agent/src/file-tools.ts +0 -1493
  122. package/deepccc-agent/src/index.ts +0 -710
  123. package/deepccc-agent/src/permissions.ts +0 -226
  124. package/deepccc-agent/src/privacy.ts +0 -141
  125. package/deepccc-agent/src/proc-tree-kill.ts +0 -61
  126. package/deepccc-agent/src/progress/cards-helpers.ts +0 -76
  127. package/deepccc-agent/src/progress/reducer.ts +0 -113
  128. package/deepccc-agent/src/progress/terminal-renderer.ts +0 -294
  129. package/deepccc-agent/src/progress/view.ts +0 -77
  130. package/deepccc-agent/src/raw-stream-log.ts +0 -124
  131. package/deepccc-agent/src/session-search.ts +0 -370
  132. package/deepccc-agent/src/session-select.ts +0 -48
  133. package/deepccc-agent/src/sigint.ts +0 -50
  134. package/deepccc-agent/src/skills.ts +0 -205
  135. package/deepccc-agent/src/web-tools.ts +0 -313
  136. package/deepccc-agent/tsconfig.build.json +0 -13
  137. package/deepccc-agent/tsconfig.json +0 -13
  138. package/deepccc-agent/vitest.config.ts +0 -7
  139. package/src/__tests__/adapter-interface.test.ts +0 -152
  140. package/src/__tests__/agent-activity.test.ts +0 -86
  141. package/src/__tests__/agent-delegate-task-rpc.test.ts +0 -165
  142. package/src/__tests__/agent-image-rpc.test.ts +0 -34
  143. package/src/__tests__/agent-platform-routing.test.ts +0 -26
  144. package/src/__tests__/agent-reload-config-rpc.test.ts +0 -99
  145. package/src/__tests__/agent-rpc-body.test.ts +0 -42
  146. package/src/__tests__/builtin-chat-session.test.ts +0 -532
  147. package/src/__tests__/builtin-cli-json.test.ts +0 -39
  148. package/src/__tests__/builtin-config.test.ts +0 -26
  149. package/src/__tests__/builtin-context.test.ts +0 -319
  150. package/src/__tests__/builtin-file-tools.test.ts +0 -240
  151. package/src/__tests__/builtin-permissions.test.ts +0 -219
  152. package/src/__tests__/builtin-session-search.test.ts +0 -262
  153. package/src/__tests__/builtin-session-select.test.ts +0 -116
  154. package/src/__tests__/builtin-sigint.test.ts +0 -56
  155. package/src/__tests__/builtin-skills.test.ts +0 -284
  156. package/src/__tests__/builtin-web-tools.test.ts +0 -220
  157. package/src/__tests__/card-action-routing.test.ts +0 -18
  158. package/src/__tests__/card-plain-text.test.ts +0 -45
  159. package/src/__tests__/cardkit.test.ts +0 -60
  160. package/src/__tests__/cards.test.ts +0 -607
  161. package/src/__tests__/ccc-adapter.test.ts +0 -194
  162. package/src/__tests__/chatgpt-subscription-rpc.test.ts +0 -89
  163. package/src/__tests__/chatgpt-subscription.test.ts +0 -135
  164. package/src/__tests__/chrome-devtools-guard.test.ts +0 -165
  165. package/src/__tests__/claude-adapter.test.ts +0 -614
  166. package/src/__tests__/claude-raw-stream-log.test.ts +0 -96
  167. package/src/__tests__/claude-sdk-installer.test.ts +0 -285
  168. package/src/__tests__/codex-adapter.test.ts +0 -331
  169. package/src/__tests__/codex-raw-stream-log.test.ts +0 -170
  170. package/src/__tests__/codex-reset-actions.test.ts +0 -146
  171. package/src/__tests__/config-reload.test.ts +0 -284
  172. package/src/__tests__/config-sample.test.ts +0 -97
  173. package/src/__tests__/config-utils.test.ts +0 -40
  174. package/src/__tests__/config.test.ts +0 -395
  175. package/src/__tests__/crash-logging.test.ts +0 -360
  176. package/src/__tests__/cursor-adapter.test.ts +0 -890
  177. package/src/__tests__/cursor-session-meta-store.test.ts +0 -212
  178. package/src/__tests__/feishu-api.test.ts +0 -60
  179. package/src/__tests__/feishu-avatar.test.ts +0 -504
  180. package/src/__tests__/feishu-message-ingress.test.ts +0 -138
  181. package/src/__tests__/feishu-platform.test.ts +0 -75
  182. package/src/__tests__/fixtures/codex_simple_text.jsonl +0 -4
  183. package/src/__tests__/fixtures/codex_with_tool.jsonl +0 -6
  184. package/src/__tests__/fixtures/cursor_partial_only.jsonl +0 -5
  185. package/src/__tests__/fixtures/cursor_partial_with_final.jsonl +0 -13
  186. package/src/__tests__/fixtures/cursor_with_tool_call.jsonl +0 -12
  187. package/src/__tests__/format-message.test.ts +0 -316
  188. package/src/__tests__/git-command.test.ts +0 -288
  189. package/src/__tests__/im-skills.test.ts +0 -125
  190. package/src/__tests__/jsonl-stream.test.ts +0 -79
  191. package/src/__tests__/orchestrator.test.ts +0 -1268
  192. package/src/__tests__/package-files.test.ts +0 -24
  193. package/src/__tests__/platform-startup.test.ts +0 -19
  194. package/src/__tests__/privacy.test.ts +0 -198
  195. package/src/__tests__/proc-tree-kill.test.ts +0 -108
  196. package/src/__tests__/progress-reducer.test.ts +0 -121
  197. package/src/__tests__/raw-stream-log.test.ts +0 -106
  198. package/src/__tests__/response-stall.test.ts +0 -49
  199. package/src/__tests__/restart.test.ts +0 -232
  200. package/src/__tests__/session-ccc-config.test.ts +0 -66
  201. package/src/__tests__/session.test.ts +0 -3004
  202. package/src/__tests__/shared-prefix.test.ts +0 -36
  203. package/src/__tests__/sim-agent.test.ts +0 -174
  204. package/src/__tests__/sim-platform.test.ts +0 -93
  205. package/src/__tests__/sim-store.test.ts +0 -214
  206. package/src/__tests__/simplify.test.ts +0 -283
  207. package/src/__tests__/startup-lifecycle.test.ts +0 -231
  208. package/src/__tests__/stop-session.test.ts +0 -162
  209. package/src/__tests__/stream-state.test.ts +0 -164
  210. package/src/__tests__/terminal-error.test.ts +0 -54
  211. package/src/__tests__/terminal-renderer.test.ts +0 -247
  212. package/src/__tests__/update-command-guard.test.ts +0 -144
  213. package/src/__tests__/web-ui.test.ts +0 -438
  214. package/src/__tests__/wechat-platform.test.ts +0 -111
  215. package/src/adapters/adapter-interface.ts +0 -217
  216. package/src/adapters/ccc-adapter.ts +0 -150
  217. package/src/adapters/claude-adapter.ts +0 -673
  218. package/src/adapters/claude-session-meta-store.ts +0 -120
  219. package/src/adapters/codex-adapter.ts +0 -426
  220. package/src/adapters/codex-session-meta-store.ts +0 -131
  221. package/src/adapters/cursor-adapter.ts +0 -681
  222. package/src/adapters/cursor-session-meta-store.ts +0 -154
  223. package/src/adapters/jsonl-stream.ts +0 -157
  224. package/src/adapters/raw-stream-log.ts +0 -124
  225. package/src/adapters/resource-monitor.ts +0 -141
  226. package/src/agent-activity.ts +0 -175
  227. package/src/agent-delegate-task-rpc.ts +0 -153
  228. package/src/agent-delegate-task.ts +0 -91
  229. package/src/agent-file-rpc.ts +0 -172
  230. package/src/agent-image-rpc.ts +0 -168
  231. package/src/agent-platform-routing.ts +0 -28
  232. package/src/agent-reload-config-rpc.ts +0 -34
  233. package/src/agent-rpc-body.ts +0 -92
  234. package/src/agent-stop-stuck.ts +0 -129
  235. package/src/card-action-routing.ts +0 -14
  236. package/src/card-plain-text.ts +0 -108
  237. package/src/cardkit.ts +0 -179
  238. package/src/cards.ts +0 -684
  239. package/src/chatgpt-subscription-rpc.ts +0 -27
  240. package/src/chatgpt-subscription.ts +0 -299
  241. package/src/chrome-devtools-guard.ts +0 -318
  242. package/src/claude-sdk-installer.ts +0 -324
  243. package/src/codex-reset-actions.ts +0 -184
  244. package/src/config-utils.ts +0 -211
  245. package/src/config.ts +0 -1063
  246. package/src/cursor-usage.ts +0 -128
  247. package/src/exit-banner.ts +0 -33
  248. package/src/feishu-api.ts +0 -1616
  249. package/src/feishu-message-ingress.ts +0 -195
  250. package/src/feishu-platform.ts +0 -159
  251. package/src/format-message.ts +0 -293
  252. package/src/git-command.ts +0 -202
  253. package/src/im-skills.ts +0 -149
  254. package/src/index.ts +0 -1089
  255. package/src/litellm-proxy.ts +0 -374
  256. package/src/orchestrator.ts +0 -2543
  257. package/src/platform-adapter.ts +0 -70
  258. package/src/platform-startup.ts +0 -16
  259. package/src/privacy.ts +0 -118
  260. package/src/progress/reducer.ts +0 -113
  261. package/src/progress/terminal-renderer.ts +0 -294
  262. package/src/progress/view.ts +0 -77
  263. package/src/response-stall.ts +0 -28
  264. package/src/runtime-reload.ts +0 -34
  265. package/src/session-chat-binding.ts +0 -292
  266. package/src/session-name.ts +0 -8
  267. package/src/session.ts +0 -2659
  268. package/src/shared-prefix.ts +0 -29
  269. package/src/shared.ts +0 -552
  270. package/src/sim-agent.ts +0 -167
  271. package/src/sim-platform.ts +0 -177
  272. package/src/sim-store.ts +0 -317
  273. package/src/simplify.ts +0 -120
  274. package/src/startup-lifecycle.ts +0 -250
  275. package/src/stream-state.ts +0 -177
  276. package/src/terminal-error.ts +0 -129
  277. package/src/trace.ts +0 -51
  278. package/src/turn-cards.ts +0 -118
  279. package/src/update-command-guard.ts +0 -165
  280. package/src/wechat-platform.ts +0 -680
@@ -0,0 +1,110 @@
1
+ import { readUtf8JsonBody } from "./agent-rpc-body.js";
2
+ import { activePrompts, getChatsForSession } from "./session-chat-binding.js";
3
+ import { getPlatformForChat } from "./session.js";
4
+ import { readStreamState, writeStreamState } from "./stream-state.js";
5
+ import { ts } from "./config.js";
6
+ export const AGENT_STOP_STUCK_PATH = "/api/agent/stop-stuck-loop";
7
+ const MAX_REQUEST_BYTES = 8 * 1024;
8
+ function jsonReply(res, status, data) {
9
+ res.writeHead(status, { "Content-Type": "application/json; charset=utf-8" });
10
+ res.end(JSON.stringify(data));
11
+ }
12
+ /**
13
+ * 从原始 body 字节中用正则尽力提取 session_id。
14
+ * 兼容 JSON 编码异常(如 GBK 中文导致 JSON.parse 失败)的场景。
15
+ */
16
+ function extractSessionIdFromRaw(buf) {
17
+ // 匹配 "session_id":"<uuid>" 或 "session_id": "<uuid>"
18
+ const match = buf.toString("latin1").match(/"session_id"\s*:\s*"([^"]+)"/);
19
+ return match?.[1] ?? null;
20
+ }
21
+ export async function handleAgentStopStuckRequest(req, res) {
22
+ const url = new URL(req.url ?? "/", "http://127.0.0.1");
23
+ if (url.pathname !== AGENT_STOP_STUCK_PATH)
24
+ return false;
25
+ if (req.method !== "POST") {
26
+ jsonReply(res, 405, { error: "Method not allowed, use POST" });
27
+ return true;
28
+ }
29
+ let body;
30
+ let rawBody = null;
31
+ try {
32
+ body = await readUtf8JsonBody(req, MAX_REQUEST_BYTES);
33
+ }
34
+ catch (err) {
35
+ // JSON 解析失败时仍尝试从原始字节中提取 session_id 并强行停止
36
+ // 宁可输出乱码,也不能让 agent 持续循环
37
+ rawBody = err.rawBody ?? null;
38
+ if (!rawBody) {
39
+ jsonReply(res, 400, { error: `Invalid request body: ${err.message}` });
40
+ return true;
41
+ }
42
+ const fallbackId = extractSessionIdFromRaw(rawBody);
43
+ if (!fallbackId) {
44
+ jsonReply(res, 400, { error: `Invalid request body: ${err.message}` });
45
+ return true;
46
+ }
47
+ body = { session_id: fallbackId };
48
+ }
49
+ const sessionId = typeof body?.session_id === "string" ? body.session_id.trim() : "";
50
+ if (!sessionId) {
51
+ jsonReply(res, 400, { error: "session_id is required" });
52
+ return true;
53
+ }
54
+ const prompt = activePrompts.get(sessionId);
55
+ if (!prompt) {
56
+ jsonReply(res, 404, { error: "Session not found or not running" });
57
+ return true;
58
+ }
59
+ // 先发"卡住"提示消息给所有绑定的群聊
60
+ const chats = getChatsForSession(sessionId);
61
+ for (const chatId of chats) {
62
+ const platform = getPlatformForChat(chatId);
63
+ if (platform) {
64
+ await platform.sendText(chatId, "⚠️ Agent 检测到自己陷入了循环,正在结束生成…").catch(() => { });
65
+ }
66
+ }
67
+ // 不丢弃缓存队列中的消息,让 runAgentSession 的 finally 块正常消费,
68
+ // 确保 stop-stuck-loop 结束后排队的消息仍能被正常处理。
69
+ const finalReply = typeof body?.final_reply === "string" ? body.final_reply.trim() : "";
70
+ // fire-and-forget:立即把 stream-state 标为 done(而非 stopped),
71
+ // 让 display loop 以"正常完成"而非"已停止"来渲染卡片和最终回复。
72
+ // 不设 prompt.stopped = true,这样 runAgentSession 的 finally 也会写 "done"。
73
+ void (async () => {
74
+ try {
75
+ const current = await readStreamState(sessionId);
76
+ if (!current)
77
+ return;
78
+ if (current.status !== "running")
79
+ return;
80
+ await writeStreamState({
81
+ ...current,
82
+ status: "done",
83
+ stuckAt: Date.now(),
84
+ finalReply: finalReply ? current.finalReply + "\n\n" + finalReply : current.finalReply,
85
+ updatedAt: Date.now(),
86
+ });
87
+ }
88
+ catch (err) {
89
+ console.warn(`[${ts()}] [STUCK-LOOP] writeStreamState(done) failed for ${sessionId}: ${err.message}`);
90
+ }
91
+ })();
92
+ // 先关闭底层 SDK session,终止 CLI 子进程,然后再 abort 清理 adapter 层
93
+ prompt.closeSession?.();
94
+ // 强制杀死 CLI 子进程。controller.abort() 只在 for-await 收到下一条
95
+ // stream 消息时才被检测到——如果 agent 陷入无输出的计算循环,abort 信号
96
+ // 永远不会生效;SDK 的 session.close() 也不保证立即终止子进程。
97
+ if (prompt.processPid !== undefined) {
98
+ try {
99
+ process.kill(prompt.processPid);
100
+ }
101
+ catch {
102
+ // 进程可能已退出,忽略错误
103
+ }
104
+ }
105
+ // 不设 stopped 标记 → finally block 写 "done" → 卡片正常结束
106
+ prompt.controller.abort();
107
+ console.log(`[${ts()}] [STUCK-LOOP] Session ${sessionId} aborted as done (agent detected stuck loop, final_reply=${finalReply ? "yes" : "no"})`);
108
+ jsonReply(res, 200, { ok: true });
109
+ return true;
110
+ }
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Feishu card action callbacks do not include the chat type. Recover it from
3
+ * the persisted binding so buttons clicked in a private chat stay in p2p.
4
+ */
5
+ export function resolveFeishuCardActionChatType(chatId, registry) {
6
+ return registry[chatId]?.chatType === "p2p" ? "p2p" : "group";
7
+ }
@@ -0,0 +1,101 @@
1
+ function isObject(value) {
2
+ return !!value && typeof value === "object" && !Array.isArray(value);
3
+ }
4
+ function stringValue(value) {
5
+ return typeof value === "string" && value.trim() ? value.trim() : null;
6
+ }
7
+ function textContent(value) {
8
+ if (typeof value === "string")
9
+ return stringValue(value);
10
+ if (!isObject(value))
11
+ return null;
12
+ return stringValue(value.content);
13
+ }
14
+ function parseButtonValue(value) {
15
+ if (typeof value !== "string")
16
+ return value;
17
+ try {
18
+ return JSON.parse(value);
19
+ }
20
+ catch {
21
+ return value;
22
+ }
23
+ }
24
+ function commandFromValue(value) {
25
+ const parsed = parseButtonValue(value);
26
+ if (typeof parsed === "string") {
27
+ const trimmed = parsed.trim();
28
+ return trimmed.startsWith("/") ? trimmed : null;
29
+ }
30
+ if (!isObject(parsed))
31
+ return null;
32
+ const cmd = stringValue(parsed.cmd);
33
+ if (cmd)
34
+ return cmd.startsWith("/") ? cmd : `/${cmd}`;
35
+ const action = stringValue(parsed.action);
36
+ if (!action)
37
+ return null;
38
+ if (action === "cd") {
39
+ const path = stringValue(parsed.path);
40
+ return path ? `/cd ${path}` : "/cd";
41
+ }
42
+ return action.startsWith("/") ? action : `/${action}`;
43
+ }
44
+ function buttonText(element) {
45
+ const label = textContent(element.text);
46
+ const command = commandFromValue(element.value);
47
+ if (label && command)
48
+ return `${label}: ${command}`;
49
+ return label ?? command;
50
+ }
51
+ function elementToText(element) {
52
+ if (!isObject(element))
53
+ return [];
54
+ const tag = stringValue(element.tag);
55
+ if (tag === "div") {
56
+ const content = textContent(element.text);
57
+ return content ? [content] : [];
58
+ }
59
+ if (tag === "markdown") {
60
+ const content = stringValue(element.content);
61
+ return content ? [content] : [];
62
+ }
63
+ if (tag === "button") {
64
+ const content = buttonText(element);
65
+ return content ? [content] : [];
66
+ }
67
+ if (tag === "action" && Array.isArray(element.actions)) {
68
+ return element.actions.flatMap(elementToText);
69
+ }
70
+ return [];
71
+ }
72
+ function rootElements(card) {
73
+ if (Array.isArray(card.elements))
74
+ return card.elements;
75
+ if (isObject(card.body) && Array.isArray(card.body.elements)) {
76
+ return card.body.elements;
77
+ }
78
+ return [];
79
+ }
80
+ export function cardJsonToPlainText(cardJson) {
81
+ let card;
82
+ try {
83
+ card = JSON.parse(cardJson);
84
+ }
85
+ catch {
86
+ return null;
87
+ }
88
+ if (!isObject(card))
89
+ return null;
90
+ const title = isObject(card.header) && isObject(card.header.title)
91
+ ? textContent(card.header.title)
92
+ : null;
93
+ const lines = rootElements(card).flatMap(elementToText);
94
+ const parts = title ? [`# ${title}`, ...lines] : lines;
95
+ const text = parts
96
+ .map((part) => part.trim())
97
+ .filter(Boolean)
98
+ .join("\n\n")
99
+ .trim();
100
+ return text || null;
101
+ }
@@ -0,0 +1,158 @@
1
+ import { BASE_URL, fileLog, ts } from "./config.js";
2
+ // CardKit 是飞书的卡片流式更新 API,通过 cardElement.content 端点
3
+ // 对卡片上指定 element_id 的元素进行增量内容更新,实现打字机效果。
4
+ // 与普通卡片 PATCH 的区别:PATCH 是全量替换卡片 JSON,CardKit 是
5
+ // 由飞书客户端自行渲染增量文本,用户看到的是逐字出现的效果。
6
+ // 参考: https://open.feishu.cn/document/uYjLw4iNukDO6YDN4ITM4MjM
7
+ const CARDKIT_REQUEST_TIMEOUT_MS = 15_000;
8
+ async function fetchCardKit(url, init, operation) {
9
+ const controller = new AbortController();
10
+ const timer = setTimeout(() => controller.abort(), CARDKIT_REQUEST_TIMEOUT_MS);
11
+ try {
12
+ const resp = await fetch(url, { ...init, signal: controller.signal });
13
+ const respText = await resp.text();
14
+ return { resp, respText };
15
+ }
16
+ catch (err) {
17
+ if (err.name === "AbortError") {
18
+ console.error(`[${ts()}] [CARDIKT] ${operation} TIMEOUT after ${CARDKIT_REQUEST_TIMEOUT_MS}ms`);
19
+ fileLog.flush();
20
+ throw new Error(`${operation} timeout after ${CARDKIT_REQUEST_TIMEOUT_MS}ms`);
21
+ }
22
+ throw err;
23
+ }
24
+ finally {
25
+ clearTimeout(timer);
26
+ }
27
+ }
28
+ export async function createCardKitCard(token, cardJson) {
29
+ const body = JSON.stringify({ type: "card_json", data: cardJson });
30
+ const { resp, respText } = await fetchCardKit(`${BASE_URL}/cardkit/v1/cards`, {
31
+ method: "POST",
32
+ headers: {
33
+ Authorization: `Bearer ${token}`,
34
+ "Content-Type": "application/json",
35
+ },
36
+ body,
37
+ }, "createCard");
38
+ let data;
39
+ try {
40
+ data = JSON.parse(respText);
41
+ }
42
+ catch {
43
+ console.error(`[${ts()}] [CARDIKT] createCard: invalid JSON response (status=${resp.status}) body=${respText.slice(0, 500)}`);
44
+ fileLog.flush();
45
+ throw new Error(`CardKit create: invalid JSON response (status=${resp.status})`);
46
+ }
47
+ if (data.code !== 0) {
48
+ console.error(`[${ts()}] [CARDIKT] createCard FAIL: status=${resp.status} code=${data.code} msg="${data.msg}" body=${respText.slice(0, 500)}`);
49
+ fileLog.flush();
50
+ throw new Error(`CardKit create: [${data.code}] ${data.msg}`);
51
+ }
52
+ console.log(`[${ts()}] [CARDIKT] createCard OK cardId=${data.data?.card_id ?? "(none)"}`);
53
+ return data.data?.card_id ?? "";
54
+ }
55
+ export async function setCardKitSettings(token, cardId, settings, sequence) {
56
+ const { resp, respText } = await fetchCardKit(`${BASE_URL}/cardkit/v1/cards/${cardId}/settings`, {
57
+ method: "PATCH",
58
+ headers: {
59
+ Authorization: `Bearer ${token}`,
60
+ "Content-Type": "application/json",
61
+ },
62
+ body: JSON.stringify({ settings: JSON.stringify(settings), sequence }),
63
+ }, `settings cardId=${cardId} seq=${sequence}`);
64
+ let data;
65
+ try {
66
+ data = JSON.parse(respText);
67
+ }
68
+ catch {
69
+ console.error(`[${ts()}] [CARDIKT] settings FAIL: invalid JSON cardId=${cardId} seq=${sequence} status=${resp.status}`);
70
+ fileLog.flush();
71
+ throw new Error(`CardKit settings: invalid JSON (status=${resp.status})`);
72
+ }
73
+ if (data.code !== 0) {
74
+ console.error(`[${ts()}] [CARDIKT] settings FAIL: cardId=${cardId} seq=${sequence} status=${resp.status} code=${data.code} msg="${data.msg}"`);
75
+ fileLog.flush();
76
+ throw new Error(`CardKit settings: [${data.code}] ${data.msg}`);
77
+ }
78
+ console.log(`[${ts()}] [CARDIKT] settings OK cardId=${cardId} seq=${sequence}`);
79
+ }
80
+ export async function streamCardKitElement(token, cardId, elementId, content, sequence) {
81
+ const { resp, respText } = await fetchCardKit(`${BASE_URL}/cardkit/v1/cards/${cardId}/elements/${elementId}/content`, {
82
+ method: "PUT",
83
+ headers: {
84
+ Authorization: `Bearer ${token}`,
85
+ "Content-Type": "application/json",
86
+ },
87
+ body: JSON.stringify({ content, sequence }),
88
+ }, `streamElement cardId=${cardId} element=${elementId} seq=${sequence}`);
89
+ let data;
90
+ try {
91
+ data = JSON.parse(respText);
92
+ }
93
+ catch {
94
+ console.error(`[${ts()}] [CARDIKT] streamElement FAIL: invalid JSON cardId=${cardId} element=${elementId} seq=${sequence} status=${resp.status}`);
95
+ fileLog.flush();
96
+ throw new Error(`CardKit stream: invalid JSON (status=${resp.status})`);
97
+ }
98
+ if (data.code !== 0) {
99
+ console.error(`[${ts()}] [CARDIKT] streamElement FAIL: cardId=${cardId} element=${elementId} seq=${sequence} status=${resp.status} code=${data.code} msg="${data.msg}"`);
100
+ fileLog.flush();
101
+ throw new Error(`CardKit stream: [${data.code}] ${data.msg}`);
102
+ }
103
+ // success log is intentionally sparse — uncomment to debug streaming throughput
104
+ // console.log(`[${ts()}] [CARDIKT] streamElement OK cardId=${cardId} seq=${sequence}`);
105
+ }
106
+ export async function updateCardKitCard(token, cardId, cardJson, sequence) {
107
+ const { resp, respText } = await fetchCardKit(`${BASE_URL}/cardkit/v1/cards/${cardId}`, {
108
+ method: "PUT",
109
+ headers: {
110
+ Authorization: `Bearer ${token}`,
111
+ "Content-Type": "application/json",
112
+ },
113
+ body: JSON.stringify({ card: { type: "card_json", data: cardJson }, sequence }),
114
+ }, `updateCard cardId=${cardId} seq=${sequence}`);
115
+ let data;
116
+ try {
117
+ data = JSON.parse(respText);
118
+ }
119
+ catch {
120
+ console.error(`[${ts()}] [CARDIKT] updateCard FAIL: invalid JSON cardId=${cardId} seq=${sequence} status=${resp.status}`);
121
+ fileLog.flush();
122
+ throw new Error(`CardKit update: invalid JSON (status=${resp.status})`);
123
+ }
124
+ if (data.code !== 0) {
125
+ console.error(`[${ts()}] [CARDIKT] updateCard FAIL: cardId=${cardId} seq=${sequence} status=${resp.status} code=${data.code} msg="${data.msg}"`);
126
+ fileLog.flush();
127
+ throw new Error(`CardKit update: [${data.code}] ${data.msg}`);
128
+ }
129
+ console.log(`[${ts()}] [CARDIKT] updateCard OK cardId=${cardId} seq=${sequence}`);
130
+ }
131
+ export async function sendCardKitMessage(token, chatId, cardId) {
132
+ const payload = { receive_id: chatId, msg_type: "interactive", content: JSON.stringify({ type: "card", data: { card_id: cardId } }) };
133
+ const url = `${BASE_URL}/im/v1/messages?receive_id_type=chat_id`;
134
+ const { resp, respText } = await fetchCardKit(url, {
135
+ method: "POST",
136
+ headers: {
137
+ Authorization: `Bearer ${token}`,
138
+ "Content-Type": "application/json",
139
+ },
140
+ body: JSON.stringify(payload),
141
+ }, `sendMessage cardId=${cardId} chatId=${chatId}`);
142
+ let data;
143
+ try {
144
+ data = JSON.parse(respText);
145
+ }
146
+ catch {
147
+ console.error(`[${ts()}] [CARDIKT] sendMessage FAIL: invalid JSON cardId=${cardId} chatId=${chatId} status=${resp.status}`);
148
+ fileLog.flush();
149
+ throw new Error(`sendCardKitMessage: invalid JSON (status=${resp.status})`);
150
+ }
151
+ if (data.code !== 0) {
152
+ console.error(`[${ts()}] [CARDIKT] sendMessage FAIL: status=${resp.status} code=${data.code} msg="${data.msg}" cardId=${cardId} chatId=${chatId}`);
153
+ fileLog.flush();
154
+ throw new Error(`[${data.code}] ${data.msg}`);
155
+ }
156
+ console.log(`[${ts()}] [CARDIKT] sendMessage OK cardId=${cardId} chatId=${chatId} msgId=${data.data?.message_id ?? "(none)"}`);
157
+ return data.data?.message_id ?? "";
158
+ }