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,137 @@
1
+ import { homedir } from "node:os";
2
+ import { dirname, join } from "node:path";
3
+ import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
4
+ export const MAX_PROCESSED = 5000;
5
+ const defaultSchedule = (task) => {
6
+ setImmediate(task);
7
+ };
8
+ /**
9
+ * The Feishu SDK waits for an event handler's return value before sending its
10
+ * WebSocket response. Schedule the real work for the next event-loop turn so
11
+ * the SDK callback can return and acknowledge the event immediately.
12
+ */
13
+ export function createAckFirstEventHandler(worker, onError, schedule = defaultSchedule) {
14
+ return async (data) => {
15
+ schedule(() => {
16
+ void worker(data).catch(onError);
17
+ });
18
+ };
19
+ }
20
+ function isPersistedEntry(value) {
21
+ if (!value || typeof value !== "object")
22
+ return false;
23
+ const entry = value;
24
+ return typeof entry.messageId === "string"
25
+ && entry.messageId.length > 0
26
+ && typeof entry.chatId === "string"
27
+ && typeof entry.createTime === "number"
28
+ && Number.isFinite(entry.createTime);
29
+ }
30
+ export class FeishuMessageLedger {
31
+ filePath;
32
+ maxEntries;
33
+ messageIds;
34
+ entries = [];
35
+ latestCreateTimeByChat = new Map();
36
+ persistTail = Promise.resolve();
37
+ constructor(filePath, maxEntries = MAX_PROCESSED, messageIds) {
38
+ this.filePath = filePath;
39
+ this.maxEntries = maxEntries;
40
+ this.messageIds = messageIds ?? new Set();
41
+ }
42
+ async load() {
43
+ this.clearMemory();
44
+ try {
45
+ const raw = await readFile(this.filePath, "utf-8");
46
+ const parsed = JSON.parse(raw);
47
+ const entries = Array.isArray(parsed.entries)
48
+ ? parsed.entries.filter(isPersistedEntry)
49
+ : [];
50
+ this.entries = entries.slice(-this.maxEntries);
51
+ this.rebuildIndexes();
52
+ if (entries.length > this.maxEntries) {
53
+ await this.persist();
54
+ }
55
+ }
56
+ catch (error) {
57
+ if (error.code !== "ENOENT") {
58
+ console.error(`[FEISHU-DEDUP] Failed to load ${this.filePath}: ${error.message}`);
59
+ }
60
+ }
61
+ }
62
+ async accept(identity) {
63
+ const { messageId, chatId, createTime } = identity;
64
+ if (messageId && this.messageIds.has(messageId)) {
65
+ return "duplicate";
66
+ }
67
+ const latestCreateTime = this.latestCreateTimeByChat.get(chatId);
68
+ if (latestCreateTime !== undefined && createTime < latestCreateTime) {
69
+ return "stale";
70
+ }
71
+ if (!messageId) {
72
+ this.recordLatestCreateTime(chatId, createTime);
73
+ return "accepted";
74
+ }
75
+ this.entries.push({ messageId, chatId, createTime });
76
+ this.messageIds.add(messageId);
77
+ this.recordLatestCreateTime(chatId, createTime);
78
+ if (this.entries.length > this.maxEntries) {
79
+ this.entries = this.entries.slice(-this.maxEntries);
80
+ this.rebuildIndexes();
81
+ }
82
+ try {
83
+ await this.persist();
84
+ }
85
+ catch (error) {
86
+ console.error(`[FEISHU-DEDUP] Failed to persist ${this.filePath}: ${error.message}`);
87
+ }
88
+ return "accepted";
89
+ }
90
+ clearMemory() {
91
+ this.entries = [];
92
+ this.messageIds.clear();
93
+ this.latestCreateTimeByChat.clear();
94
+ this.persistTail = Promise.resolve();
95
+ }
96
+ recordLatestCreateTime(chatId, createTime) {
97
+ const current = this.latestCreateTimeByChat.get(chatId);
98
+ if (current === undefined || createTime > current) {
99
+ this.latestCreateTimeByChat.set(chatId, createTime);
100
+ }
101
+ }
102
+ rebuildIndexes() {
103
+ this.messageIds.clear();
104
+ this.latestCreateTimeByChat.clear();
105
+ for (const entry of this.entries) {
106
+ this.messageIds.add(entry.messageId);
107
+ this.recordLatestCreateTime(entry.chatId, entry.createTime);
108
+ }
109
+ }
110
+ persist() {
111
+ const snapshot = {
112
+ version: 1,
113
+ entries: this.entries.map((entry) => ({ ...entry })),
114
+ };
115
+ const nextPersist = this.persistTail
116
+ .catch(() => { })
117
+ .then(async () => {
118
+ await mkdir(dirname(this.filePath), { recursive: true });
119
+ const tempPath = `${this.filePath}.${process.pid}.tmp`;
120
+ try {
121
+ await writeFile(tempPath, JSON.stringify(snapshot), "utf-8");
122
+ await rename(tempPath, this.filePath);
123
+ }
124
+ finally {
125
+ await rm(tempPath, { force: true }).catch(() => { });
126
+ }
127
+ });
128
+ this.persistTail = nextPersist;
129
+ return nextPersist;
130
+ }
131
+ }
132
+ const defaultLedgerPath = join(homedir(), ".chatccc", "state", "feishu-message-ledger.json");
133
+ export const processedMessages = new Set();
134
+ export const feishuMessageLedger = new FeishuMessageLedger(defaultLedgerPath, MAX_PROCESSED, processedMessages);
135
+ export function clearFeishuMessageLedgerMemory() {
136
+ feishuMessageLedger.clearMemory();
137
+ }
@@ -0,0 +1,97 @@
1
+ /**
2
+ * feishu-platform.ts — 可替换的飞书 API 实现层
3
+ *
4
+ * 默认情况下所有函数直接委托给 feishu-api.ts(真实飞书 API)。
5
+ * 在 --simulate 模式下通过 setPlatform() 整体替换为 SimulatedPlatform。
6
+ *
7
+ * 设计:每个导出函数都是一个"通过 _impl 代理"的包装器,
8
+ * 消费者不需要感知底层是真实飞书还是模拟实现。
9
+ */
10
+ import * as realApi from "./feishu-api.js";
11
+ let _impl = realApi;
12
+ /** 替换当前平台实现(模拟模式入口) */
13
+ export function setPlatform(impl) {
14
+ _impl = impl;
15
+ }
16
+ /** 获取当前平台实现(仅供诊断/测试) */
17
+ export function getPlatform() {
18
+ return _impl;
19
+ }
20
+ // ---------------------------------------------------------------------------
21
+ // 包装器:每个函数直接委托到 _impl,签名与原函数完全一致
22
+ // ---------------------------------------------------------------------------
23
+ export function getTenantAccessToken() {
24
+ return _impl.getTenantAccessToken();
25
+ }
26
+ export function sendTextReply(...args) {
27
+ return _impl.sendTextReply(...args);
28
+ }
29
+ export function sendCardReply(...args) {
30
+ return _impl.sendCardReply(...args);
31
+ }
32
+ export function sendRawCard(...args) {
33
+ return _impl.sendRawCard(...args);
34
+ }
35
+ export function sendImageReply(...args) {
36
+ return _impl.sendImageReply(...args);
37
+ }
38
+ export function sendFileReply(...args) {
39
+ return _impl.sendFileReply(...args);
40
+ }
41
+ export function addReaction(...args) {
42
+ return _impl.addReaction(...args);
43
+ }
44
+ export function recallMessage(...args) {
45
+ return _impl.recallMessage(...args);
46
+ }
47
+ export function updateCardMessage(...args) {
48
+ return _impl.updateCardMessage(...args);
49
+ }
50
+ export function createGroupChat(...args) {
51
+ return _impl.createGroupChat(...args);
52
+ }
53
+ export function updateChatInfo(...args) {
54
+ return _impl.updateChatInfo(...args);
55
+ }
56
+ export function getChatInfo(...args) {
57
+ return _impl.getChatInfo(...args);
58
+ }
59
+ export function disbandChat(...args) {
60
+ return _impl.disbandChat(...args);
61
+ }
62
+ export function setChatAvatar(...args) {
63
+ return _impl.setChatAvatar(...args);
64
+ }
65
+ export function getCodexUsageSummary(...args) {
66
+ return _impl.getCodexUsageSummary(...args);
67
+ }
68
+ export function consumeCodexRateLimitResetCredit(...args) {
69
+ return _impl.consumeCodexRateLimitResetCredit(...args);
70
+ }
71
+ export function getOrDownloadImage(...args) {
72
+ return _impl.getOrDownloadImage(...args);
73
+ }
74
+ export function verifyAllPermissions(...args) {
75
+ return _impl.verifyAllPermissions(...args);
76
+ }
77
+ export function reportPermissionResults(...args) {
78
+ return _impl.reportPermissionResults(...args);
79
+ }
80
+ export function extractSessionInfo(...args) {
81
+ return _impl.extractSessionInfo(...args);
82
+ }
83
+ export function extractSessionId(...args) {
84
+ return _impl.extractSessionId(...args);
85
+ }
86
+ export function formatDelayNotice(...args) {
87
+ return _impl.formatDelayNotice(...args);
88
+ }
89
+ export function sendPostMessage(...args) {
90
+ return _impl.sendPostMessage(...args);
91
+ }
92
+ export function sendRestartCard(...args) {
93
+ return _impl.sendRestartCard(...args);
94
+ }
95
+ export function getMergeForwardMessages(...args) {
96
+ return _impl.getMergeForwardMessages(...args);
97
+ }
@@ -0,0 +1,252 @@
1
+ /**
2
+ * format-message.ts — 飞书消息内容格式化
3
+ *
4
+ * 从 index.ts 中提取,独立模块便于测试。
5
+ */
6
+ import { cardJsonToPlainText } from "./card-plain-text.js";
7
+ import { ts } from "./config.js";
8
+ import { getTenantAccessToken, getOrDownloadImage, getMergeForwardMessages, } from "./feishu-platform.js";
9
+ /**
10
+ * 根据消息类型格式化消息内容为可读文本。
11
+ */
12
+ export async function formatMessageContent(message) {
13
+ const contentStr = message.content ?? "{}";
14
+ let content;
15
+ try {
16
+ content = JSON.parse(contentStr);
17
+ }
18
+ catch {
19
+ // merge_forward 消息的 content 可能为空字符串,但可通过 message_id 调 API 获取子消息
20
+ if (message.message_type === "merge_forward") {
21
+ content = {};
22
+ }
23
+ else {
24
+ return "";
25
+ }
26
+ }
27
+ if (message.message_type === "text") {
28
+ let text = (content.text ?? "");
29
+ text = text.replace(/<\/?p[^>]*>/gi, "");
30
+ text = text.replace(/<br\s*\/?>/gi, "\n");
31
+ text = text.replace(/&nbsp;/gi, " ");
32
+ return text.trim();
33
+ }
34
+ if (message.message_type === "post") {
35
+ return formatPostContentWithImages(content, message.message_id);
36
+ }
37
+ if (message.message_type === "image") {
38
+ const imageKey = content.image_key;
39
+ const messageId = message.message_id;
40
+ if (!imageKey || !messageId)
41
+ return contentStr;
42
+ try {
43
+ const token = await getTenantAccessToken();
44
+ const localPath = await getOrDownloadImage(token, messageId, imageKey);
45
+ return `[图片] ${localPath}`;
46
+ }
47
+ catch (err) {
48
+ console.error(`[${ts()}] [IMAGE] download failed for ${imageKey}: ${err.message}`);
49
+ return `[图片: ${imageKey}]`;
50
+ }
51
+ }
52
+ if (message.message_type === "media") {
53
+ const fileKey = content.file_key;
54
+ const fileName = content.file_name || "video.mp4";
55
+ const messageId = message.message_id;
56
+ if (!fileKey || !messageId)
57
+ return contentStr;
58
+ return `[视频] message_id=${messageId} file_key=${fileKey} file_name=${fileName}`;
59
+ }
60
+ if (message.message_type === "file") {
61
+ const fileKey = content.file_key;
62
+ const fileName = content.file_name || "download.bin";
63
+ const messageId = message.message_id;
64
+ if (!fileKey || !messageId)
65
+ return contentStr;
66
+ return `[文件] message_id=${messageId} file_key=${fileKey} file_name=${fileName}`;
67
+ }
68
+ if (message.message_type === "interactive") {
69
+ const raw = JSON.stringify(content);
70
+ const text = cardJsonToPlainText(raw);
71
+ if (text)
72
+ return `[卡片] ${text}`;
73
+ return contentStr;
74
+ }
75
+ if (message.message_type === "merge_forward") {
76
+ return formatMergeForward(message.message_id ?? "", content);
77
+ }
78
+ // 其他类型(audio, sticker 等)直接给原始 JSON
79
+ return contentStr;
80
+ }
81
+ export function formatPostContent(content) {
82
+ const paragraphs = getPostParagraphs(content);
83
+ if (!Array.isArray(paragraphs))
84
+ return "";
85
+ const parts = [];
86
+ for (const line of paragraphs) {
87
+ if (!Array.isArray(line))
88
+ continue;
89
+ for (const elem of line) {
90
+ const el = elem;
91
+ if (!el || typeof el !== "object")
92
+ continue;
93
+ const text = formatPostTextElement(el);
94
+ if (text)
95
+ parts.push(text);
96
+ }
97
+ }
98
+ return parts.join("\n").trim();
99
+ }
100
+ function getPostParagraphs(content) {
101
+ const direct = content.content;
102
+ if (Array.isArray(direct))
103
+ return direct;
104
+ for (const locale of ["zh_cn", "en_us", "ja_jp"]) {
105
+ const localized = content[locale];
106
+ if (localized && Array.isArray(localized.content)) {
107
+ return localized.content;
108
+ }
109
+ }
110
+ return [];
111
+ }
112
+ function formatPostTextElement(el) {
113
+ const t = typeof el.text === "string" ? el.text : "";
114
+ if (el.tag === "code_block") {
115
+ const lang = typeof el.language === "string" ? el.language : "";
116
+ return "```" + lang + "\n" + t + "\n```";
117
+ }
118
+ if (el.tag === "p" || el.tag === "text") {
119
+ return t;
120
+ }
121
+ return "";
122
+ }
123
+ function getPostImageKey(el) {
124
+ const imageKey = el.image_key;
125
+ if (typeof imageKey === "string" && imageKey.trim())
126
+ return imageKey;
127
+ if (el.tag === "img") {
128
+ const fileKey = el.file_key;
129
+ if (typeof fileKey === "string" && fileKey.trim())
130
+ return fileKey;
131
+ }
132
+ return undefined;
133
+ }
134
+ async function formatPostContentWithImages(content, messageId) {
135
+ const paragraphs = getPostParagraphs(content);
136
+ if (!Array.isArray(paragraphs))
137
+ return "";
138
+ const parts = [];
139
+ for (const line of paragraphs) {
140
+ if (!Array.isArray(line))
141
+ continue;
142
+ for (const elem of line) {
143
+ const el = elem;
144
+ if (!el || typeof el !== "object")
145
+ continue;
146
+ const text = formatPostTextElement(el);
147
+ if (text)
148
+ parts.push(text);
149
+ const imageKey = getPostImageKey(el);
150
+ if (imageKey) {
151
+ parts.push(await formatPostImageElement(messageId, imageKey));
152
+ }
153
+ }
154
+ }
155
+ return parts.join("\n").trim();
156
+ }
157
+ async function formatPostImageElement(messageId, imageKey) {
158
+ if (!messageId)
159
+ return `[图片: ${imageKey}]`;
160
+ try {
161
+ const token = await getTenantAccessToken();
162
+ const localPath = await getOrDownloadImage(token, messageId, imageKey);
163
+ return `[图片] ${localPath}`;
164
+ }
165
+ catch (err) {
166
+ console.error(`[${ts()}] [IMAGE] download failed for post image ${imageKey}: ${err.message}`);
167
+ return `[图片: ${imageKey}]`;
168
+ }
169
+ }
170
+ // ---------------------------------------------------------------------------
171
+ // 合并转发消息格式化
172
+ // ---------------------------------------------------------------------------
173
+ /**
174
+ * 格式化合并转发消息。
175
+ *
176
+ * 三阶段降级策略:
177
+ * 1. 调用 GET /im/v1/messages/{messageId} 获取完整子消息列表
178
+ * 2. API 失败时降级使用 content.preview 字段
179
+ * 3. preview 也为空时返回原始 JSON
180
+ *
181
+ * 递归深度限制 MAX_DEPTH=3,避免嵌套合并转发 API 爆炸。
182
+ */
183
+ export async function formatMergeForward(messageId, content, depth = 0) {
184
+ const MAX_DEPTH = 3;
185
+ if (depth >= MAX_DEPTH) {
186
+ return `[合并转发: 超出最大嵌套深度 ${MAX_DEPTH}]`;
187
+ }
188
+ const title = content.title || "聊天记录";
189
+ const chatName = content.chat_name || "";
190
+ const header = `[合并转发: ${title}${chatName ? ` (${chatName})` : ""}]`;
191
+ // 从 preview 构建 sender ID → name 映射表
192
+ const senderNameMap = new Map();
193
+ const preview = content.preview;
194
+ if (Array.isArray(preview)) {
195
+ for (const entry of preview) {
196
+ const e = entry;
197
+ const s = e.sender;
198
+ if (s && typeof s.id === "string" && typeof s.name === "string") {
199
+ senderNameMap.set(s.id, s.name);
200
+ }
201
+ }
202
+ }
203
+ const lines = [];
204
+ let usedApi = false;
205
+ // Phase 1: 尝试通过 API 获取完整子消息列表
206
+ try {
207
+ const token = await getTenantAccessToken();
208
+ const items = await getMergeForwardMessages(token, messageId);
209
+ // 跳过第一个 item(合并转发消息自身,无 upper_message_id)
210
+ const subItems = items.filter((item) => item.upper_message_id);
211
+ if (subItems.length > 0) {
212
+ for (const item of subItems) {
213
+ const senderId = item.sender?.id ?? "unknown";
214
+ const senderName = senderNameMap.get(senderId) ?? senderId;
215
+ const subMsgType = item.msg_type ?? "";
216
+ const subContent = item.body?.content ?? "{}";
217
+ try {
218
+ const formatted = await formatMessageContent({
219
+ message_id: item.message_id,
220
+ message_type: subMsgType,
221
+ content: subContent,
222
+ });
223
+ lines.push(`${senderName}: ${formatted}`);
224
+ }
225
+ catch {
226
+ lines.push(`${senderName}: ${subContent}`);
227
+ }
228
+ }
229
+ usedApi = true;
230
+ }
231
+ }
232
+ catch (err) {
233
+ console.error(`[${ts()}] [MERGE_FORWARD] API 获取子消息失败 (${messageId}), 降级使用 preview: ${err.message}`);
234
+ }
235
+ // Phase 2: API 失败或返回空时降级使用 preview
236
+ if (!usedApi) {
237
+ if (Array.isArray(preview) && preview.length > 0) {
238
+ for (const entry of preview) {
239
+ const e = entry;
240
+ const s = e.sender;
241
+ const senderName = s?.name ?? "未知用户";
242
+ const text = e.content ?? "";
243
+ lines.push(`${senderName}: ${text}`);
244
+ }
245
+ }
246
+ }
247
+ // Phase 3: 没有任何内容时返回原始 JSON
248
+ if (lines.length === 0) {
249
+ return JSON.stringify(content);
250
+ }
251
+ return header + "\n" + lines.join("\n");
252
+ }
@@ -0,0 +1,155 @@
1
+ // =============================================================================
2
+ // git-command.ts — /git 命令的执行与结果格式化
3
+ // =============================================================================
4
+ // 解析自 /git 后的原始字符串作为 shell 参数,在指定 cwd 下通过 shell 调起
5
+ // `git ...`,收集 stdout/stderr 与退出码。带超时(kill)与逐路输出字节上限
6
+ // (超过即截断),避免长输出撑爆内存或刷屏。
7
+ //
8
+ // 抽成独立模块是为了便于在不依赖飞书 SDK / 网络的前提下跑单元测试。
9
+ // =============================================================================
10
+ import { spawn } from "node:child_process";
11
+ import { truncateContent } from "./cards.js";
12
+ // ---------------------------------------------------------------------------
13
+ // runGitCommand —— 在 cwd 下执行 `git <args>`
14
+ // ---------------------------------------------------------------------------
15
+ /**
16
+ * 在 `cwd` 目录下执行 `git <args>`。
17
+ * - 通过 shell 执行(`shell: true`),允许用户使用引号、管道等 shell 语法
18
+ * - stdout/stderr 各自最多采集 `maxBytes` 字节,超过则置 truncated=true 并丢弃后续片段
19
+ * - 超时则 SIGKILL 并置 timedOut=true,仍返回已收集的部分输出
20
+ *
21
+ * 注意:本函数 **不会抛错**——任何失败都通过返回值传递(退出码、spawnError 等),
22
+ * 调用方需通过 exitCode/spawnError/timedOut/truncated 判断结果。
23
+ */
24
+ export function runGitCommand(args, cwd, opts = {}) {
25
+ const timeoutMs = opts.timeoutMs ?? 60_000;
26
+ const maxBytes = opts.maxBytes ?? 64 * 1024;
27
+ const spawnImpl = opts.spawnImpl ?? spawn;
28
+ const startTime = Date.now();
29
+ return new Promise((resolve) => {
30
+ let child;
31
+ try {
32
+ child = spawnImpl(`git ${args}`, {
33
+ cwd,
34
+ shell: true,
35
+ windowsHide: true,
36
+ });
37
+ }
38
+ catch (err) {
39
+ resolve({
40
+ exitCode: null,
41
+ stdout: "",
42
+ stderr: "",
43
+ durationMs: Date.now() - startTime,
44
+ truncated: false,
45
+ timedOut: false,
46
+ spawnError: err instanceof Error ? err.message : String(err),
47
+ });
48
+ return;
49
+ }
50
+ let stdout = "";
51
+ let stderr = "";
52
+ let stdoutBytes = 0;
53
+ let stderrBytes = 0;
54
+ let truncated = false;
55
+ let timedOut = false;
56
+ let spawnError;
57
+ const collect = (chunk, current) => {
58
+ const room = maxBytes - current.bytes;
59
+ if (room <= 0) {
60
+ truncated = true;
61
+ return;
62
+ }
63
+ const slice = chunk.length <= room ? chunk : chunk.subarray(0, room);
64
+ current.text += slice.toString("utf-8");
65
+ current.bytes += slice.length;
66
+ if (chunk.length > room)
67
+ truncated = true;
68
+ };
69
+ const stdoutState = { bytes: 0, text: "" };
70
+ const stderrState = { bytes: 0, text: "" };
71
+ child.stdout?.on("data", (chunk) => {
72
+ collect(chunk, stdoutState);
73
+ stdout = stdoutState.text;
74
+ stdoutBytes = stdoutState.bytes;
75
+ });
76
+ child.stderr?.on("data", (chunk) => {
77
+ collect(chunk, stderrState);
78
+ stderr = stderrState.text;
79
+ stderrBytes = stderrState.bytes;
80
+ });
81
+ const killTimer = setTimeout(() => {
82
+ timedOut = true;
83
+ try {
84
+ child.kill("SIGKILL");
85
+ }
86
+ catch {
87
+ // ignore: 进程可能已退出
88
+ }
89
+ }, timeoutMs);
90
+ child.on("error", (err) => {
91
+ spawnError = err.message;
92
+ });
93
+ child.on("close", (code) => {
94
+ clearTimeout(killTimer);
95
+ // 仅引用未直接使用的字节计数变量以避免编译告警
96
+ void stdoutBytes;
97
+ void stderrBytes;
98
+ resolve({
99
+ exitCode: code,
100
+ stdout,
101
+ stderr,
102
+ durationMs: Date.now() - startTime,
103
+ truncated,
104
+ timedOut,
105
+ spawnError,
106
+ });
107
+ });
108
+ });
109
+ }
110
+ // ---------------------------------------------------------------------------
111
+ // formatGitResult —— 把执行结果渲染为飞书卡片用的 markdown
112
+ // ---------------------------------------------------------------------------
113
+ /**
114
+ * 渲染 `/git` 执行结果为发送给用户的 markdown 字符串。
115
+ * stdout/stderr 单路各最多保留 `maxLines` 行 / `maxChars` 字符(沿用 truncateContent),
116
+ * 命令本身的截断状态(truncated/timedOut/spawnError)也会在头部说明。
117
+ */
118
+ export function formatGitResult(args, cwd, result, opts = {}) {
119
+ const maxLines = opts.maxLines ?? 50;
120
+ const maxChars = opts.maxChars ?? 6000;
121
+ const sec = (result.durationMs / 1000).toFixed(2);
122
+ const lines = [];
123
+ lines.push(`**\$ git ${args}**`);
124
+ lines.push(`工作目录: \`${cwd}\``);
125
+ const exitDisplay = result.exitCode === null ? "(无)" : String(result.exitCode);
126
+ lines.push(`退出码: \`${exitDisplay}\` | 用时: \`${sec}s\``);
127
+ if (result.timedOut)
128
+ lines.push(`⏱️ 命令超时被强制终止`);
129
+ if (result.truncated)
130
+ lines.push(`⚠️ 输出超出采集上限,已截断`);
131
+ if (result.spawnError)
132
+ lines.push(`❌ 启动失败: ${result.spawnError}`);
133
+ const stdoutTrim = result.stdout.trim();
134
+ const stderrTrim = result.stderr.trim();
135
+ if (stdoutTrim) {
136
+ lines.push("", "**stdout:**", "```", truncateContent(stdoutTrim, maxLines, maxChars), "```");
137
+ }
138
+ if (stderrTrim) {
139
+ lines.push("", "**stderr:**", "```", truncateContent(stderrTrim, maxLines, maxChars), "```");
140
+ }
141
+ if (!stdoutTrim && !stderrTrim && !result.spawnError) {
142
+ lines.push("", "_(命令无输出)_");
143
+ }
144
+ return lines.join("\n");
145
+ }
146
+ // ---------------------------------------------------------------------------
147
+ // 头部颜色:成功绿色,失败红色,超时黄色
148
+ // ---------------------------------------------------------------------------
149
+ export function gitResultHeaderTemplate(result) {
150
+ if (result.timedOut || result.spawnError)
151
+ return "yellow";
152
+ if (result.exitCode === 0)
153
+ return "green";
154
+ return "red";
155
+ }