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,195 +0,0 @@
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
-
5
- export const MAX_PROCESSED = 5000;
6
-
7
- export type FeishuMessageDisposition = "accepted" | "duplicate" | "stale";
8
-
9
- export interface FeishuMessageIdentity {
10
- messageId?: string;
11
- chatId: string;
12
- createTime: number;
13
- }
14
-
15
- interface PersistedMessageEntry {
16
- messageId: string;
17
- chatId: string;
18
- createTime: number;
19
- }
20
-
21
- interface PersistedMessageLedger {
22
- version: 1;
23
- entries: PersistedMessageEntry[];
24
- }
25
-
26
- type ScheduleTask = (task: () => void) => void;
27
-
28
- const defaultSchedule: ScheduleTask = (task) => {
29
- setImmediate(task);
30
- };
31
-
32
- /**
33
- * The Feishu SDK waits for an event handler's return value before sending its
34
- * WebSocket response. Schedule the real work for the next event-loop turn so
35
- * the SDK callback can return and acknowledge the event immediately.
36
- */
37
- export function createAckFirstEventHandler<T>(
38
- worker: (data: T) => Promise<void>,
39
- onError: (error: unknown) => void,
40
- schedule: ScheduleTask = defaultSchedule,
41
- ): (data: T) => Promise<void> {
42
- return async (data) => {
43
- schedule(() => {
44
- void worker(data).catch(onError);
45
- });
46
- };
47
- }
48
-
49
- function isPersistedEntry(value: unknown): value is PersistedMessageEntry {
50
- if (!value || typeof value !== "object") return false;
51
- const entry = value as Record<string, unknown>;
52
- return typeof entry.messageId === "string"
53
- && entry.messageId.length > 0
54
- && typeof entry.chatId === "string"
55
- && typeof entry.createTime === "number"
56
- && Number.isFinite(entry.createTime);
57
- }
58
-
59
- export class FeishuMessageLedger {
60
- private readonly messageIds: Set<string>;
61
- private entries: PersistedMessageEntry[] = [];
62
- private latestCreateTimeByChat = new Map<string, number>();
63
- private persistTail: Promise<void> = Promise.resolve();
64
-
65
- constructor(
66
- public readonly filePath: string,
67
- private readonly maxEntries = MAX_PROCESSED,
68
- messageIds?: Set<string>,
69
- ) {
70
- this.messageIds = messageIds ?? new Set<string>();
71
- }
72
-
73
- async load(): Promise<void> {
74
- this.clearMemory();
75
-
76
- try {
77
- const raw = await readFile(this.filePath, "utf-8");
78
- const parsed = JSON.parse(raw) as Partial<PersistedMessageLedger>;
79
- const entries = Array.isArray(parsed.entries)
80
- ? parsed.entries.filter(isPersistedEntry)
81
- : [];
82
- this.entries = entries.slice(-this.maxEntries);
83
- this.rebuildIndexes();
84
-
85
- if (entries.length > this.maxEntries) {
86
- await this.persist();
87
- }
88
- } catch (error) {
89
- if ((error as NodeJS.ErrnoException).code !== "ENOENT") {
90
- console.error(
91
- `[FEISHU-DEDUP] Failed to load ${this.filePath}: ${(error as Error).message}`,
92
- );
93
- }
94
- }
95
- }
96
-
97
- async accept(identity: FeishuMessageIdentity): Promise<FeishuMessageDisposition> {
98
- const { messageId, chatId, createTime } = identity;
99
-
100
- if (messageId && this.messageIds.has(messageId)) {
101
- return "duplicate";
102
- }
103
-
104
- const latestCreateTime = this.latestCreateTimeByChat.get(chatId);
105
- if (latestCreateTime !== undefined && createTime < latestCreateTime) {
106
- return "stale";
107
- }
108
-
109
- if (!messageId) {
110
- this.recordLatestCreateTime(chatId, createTime);
111
- return "accepted";
112
- }
113
-
114
- this.entries.push({ messageId, chatId, createTime });
115
- this.messageIds.add(messageId);
116
- this.recordLatestCreateTime(chatId, createTime);
117
-
118
- if (this.entries.length > this.maxEntries) {
119
- this.entries = this.entries.slice(-this.maxEntries);
120
- this.rebuildIndexes();
121
- }
122
-
123
- try {
124
- await this.persist();
125
- } catch (error) {
126
- console.error(
127
- `[FEISHU-DEDUP] Failed to persist ${this.filePath}: ${(error as Error).message}`,
128
- );
129
- }
130
- return "accepted";
131
- }
132
-
133
- clearMemory(): void {
134
- this.entries = [];
135
- this.messageIds.clear();
136
- this.latestCreateTimeByChat.clear();
137
- this.persistTail = Promise.resolve();
138
- }
139
-
140
- private recordLatestCreateTime(chatId: string, createTime: number): void {
141
- const current = this.latestCreateTimeByChat.get(chatId);
142
- if (current === undefined || createTime > current) {
143
- this.latestCreateTimeByChat.set(chatId, createTime);
144
- }
145
- }
146
-
147
- private rebuildIndexes(): void {
148
- this.messageIds.clear();
149
- this.latestCreateTimeByChat.clear();
150
- for (const entry of this.entries) {
151
- this.messageIds.add(entry.messageId);
152
- this.recordLatestCreateTime(entry.chatId, entry.createTime);
153
- }
154
- }
155
-
156
- private persist(): Promise<void> {
157
- const snapshot: PersistedMessageLedger = {
158
- version: 1,
159
- entries: this.entries.map((entry) => ({ ...entry })),
160
- };
161
-
162
- const nextPersist = this.persistTail
163
- .catch(() => {})
164
- .then(async () => {
165
- await mkdir(dirname(this.filePath), { recursive: true });
166
- const tempPath = `${this.filePath}.${process.pid}.tmp`;
167
- try {
168
- await writeFile(tempPath, JSON.stringify(snapshot), "utf-8");
169
- await rename(tempPath, this.filePath);
170
- } finally {
171
- await rm(tempPath, { force: true }).catch(() => {});
172
- }
173
- });
174
- this.persistTail = nextPersist;
175
- return nextPersist;
176
- }
177
- }
178
-
179
- const defaultLedgerPath = join(
180
- homedir(),
181
- ".chatccc",
182
- "state",
183
- "feishu-message-ledger.json",
184
- );
185
-
186
- export const processedMessages = new Set<string>();
187
- export const feishuMessageLedger = new FeishuMessageLedger(
188
- defaultLedgerPath,
189
- MAX_PROCESSED,
190
- processedMessages,
191
- );
192
-
193
- export function clearFeishuMessageLedgerMemory(): void {
194
- feishuMessageLedger.clearMemory();
195
- }
@@ -1,159 +0,0 @@
1
- /**
2
- * feishu-platform.ts — 可替换的飞书 API 实现层
3
- *
4
- * 默认情况下所有函数直接委托给 feishu-api.ts(真实飞书 API)。
5
- * 在 --simulate 模式下通过 setPlatform() 整体替换为 SimulatedPlatform。
6
- *
7
- * 设计:每个导出函数都是一个"通过 _impl 代理"的包装器,
8
- * 消费者不需要感知底层是真实飞书还是模拟实现。
9
- */
10
-
11
- import * as realApi from "./feishu-api.ts";
12
-
13
- // ---------------------------------------------------------------------------
14
- // 平台接口:覆盖 feishu-api.ts 的所有公开导出函数签名
15
- // ---------------------------------------------------------------------------
16
-
17
- export interface FeishuPlatform {
18
- getTenantAccessToken: typeof realApi.getTenantAccessToken;
19
- sendTextReply: typeof realApi.sendTextReply;
20
- sendCardReply: typeof realApi.sendCardReply;
21
- sendRawCard: typeof realApi.sendRawCard;
22
- sendPostMessage: typeof realApi.sendPostMessage;
23
- sendImageReply: typeof realApi.sendImageReply;
24
- sendFileReply: typeof realApi.sendFileReply;
25
- addReaction: typeof realApi.addReaction;
26
- recallMessage: typeof realApi.recallMessage;
27
- updateCardMessage: typeof realApi.updateCardMessage;
28
- createGroupChat: typeof realApi.createGroupChat;
29
- updateChatInfo: typeof realApi.updateChatInfo;
30
- getChatInfo: typeof realApi.getChatInfo;
31
- disbandChat: typeof realApi.disbandChat;
32
- setChatAvatar: typeof realApi.setChatAvatar;
33
- getCodexUsageSummary: typeof realApi.getCodexUsageSummary;
34
- consumeCodexRateLimitResetCredit: typeof realApi.consumeCodexRateLimitResetCredit;
35
- getOrDownloadImage: typeof realApi.getOrDownloadImage;
36
- verifyAllPermissions: typeof realApi.verifyAllPermissions;
37
- reportPermissionResults: typeof realApi.reportPermissionResults;
38
- extractSessionInfo: typeof realApi.extractSessionInfo;
39
- extractSessionId: typeof realApi.extractSessionId;
40
- formatDelayNotice: typeof realApi.formatDelayNotice;
41
- sendRestartCard: typeof realApi.sendRestartCard;
42
- getMergeForwardMessages: typeof realApi.getMergeForwardMessages;
43
- }
44
-
45
- let _impl: FeishuPlatform = realApi;
46
-
47
- /** 替换当前平台实现(模拟模式入口) */
48
- export function setPlatform(impl: FeishuPlatform): void {
49
- _impl = impl;
50
- }
51
-
52
- /** 获取当前平台实现(仅供诊断/测试) */
53
- export function getPlatform(): FeishuPlatform {
54
- return _impl;
55
- }
56
-
57
- // ---------------------------------------------------------------------------
58
- // 包装器:每个函数直接委托到 _impl,签名与原函数完全一致
59
- // ---------------------------------------------------------------------------
60
-
61
- export function getTenantAccessToken(): ReturnType<typeof realApi.getTenantAccessToken> {
62
- return _impl.getTenantAccessToken();
63
- }
64
-
65
- export function sendTextReply(...args: Parameters<typeof realApi.sendTextReply>): ReturnType<typeof realApi.sendTextReply> {
66
- return _impl.sendTextReply(...args);
67
- }
68
-
69
- export function sendCardReply(...args: Parameters<typeof realApi.sendCardReply>): ReturnType<typeof realApi.sendCardReply> {
70
- return _impl.sendCardReply(...args);
71
- }
72
-
73
- export function sendRawCard(...args: Parameters<typeof realApi.sendRawCard>): ReturnType<typeof realApi.sendRawCard> {
74
- return _impl.sendRawCard(...args);
75
- }
76
-
77
- export function sendImageReply(...args: Parameters<typeof realApi.sendImageReply>): ReturnType<typeof realApi.sendImageReply> {
78
- return _impl.sendImageReply(...args);
79
- }
80
-
81
- export function sendFileReply(...args: Parameters<typeof realApi.sendFileReply>): ReturnType<typeof realApi.sendFileReply> {
82
- return _impl.sendFileReply(...args);
83
- }
84
-
85
- export function addReaction(...args: Parameters<typeof realApi.addReaction>): ReturnType<typeof realApi.addReaction> {
86
- return _impl.addReaction(...args);
87
- }
88
-
89
- export function recallMessage(...args: Parameters<typeof realApi.recallMessage>): ReturnType<typeof realApi.recallMessage> {
90
- return _impl.recallMessage(...args);
91
- }
92
-
93
- export function updateCardMessage(...args: Parameters<typeof realApi.updateCardMessage>): ReturnType<typeof realApi.updateCardMessage> {
94
- return _impl.updateCardMessage(...args);
95
- }
96
-
97
- export function createGroupChat(...args: Parameters<typeof realApi.createGroupChat>): ReturnType<typeof realApi.createGroupChat> {
98
- return _impl.createGroupChat(...args);
99
- }
100
-
101
- export function updateChatInfo(...args: Parameters<typeof realApi.updateChatInfo>): ReturnType<typeof realApi.updateChatInfo> {
102
- return _impl.updateChatInfo(...args);
103
- }
104
-
105
- export function getChatInfo(...args: Parameters<typeof realApi.getChatInfo>): ReturnType<typeof realApi.getChatInfo> {
106
- return _impl.getChatInfo(...args);
107
- }
108
-
109
- export function disbandChat(...args: Parameters<typeof realApi.disbandChat>): ReturnType<typeof realApi.disbandChat> {
110
- return _impl.disbandChat(...args);
111
- }
112
-
113
- export function setChatAvatar(...args: Parameters<typeof realApi.setChatAvatar>): ReturnType<typeof realApi.setChatAvatar> {
114
- return _impl.setChatAvatar(...args);
115
- }
116
-
117
- export function getCodexUsageSummary(...args: Parameters<typeof realApi.getCodexUsageSummary>): ReturnType<typeof realApi.getCodexUsageSummary> {
118
- return _impl.getCodexUsageSummary(...args);
119
- }
120
-
121
- export function consumeCodexRateLimitResetCredit(...args: Parameters<typeof realApi.consumeCodexRateLimitResetCredit>): ReturnType<typeof realApi.consumeCodexRateLimitResetCredit> {
122
- return _impl.consumeCodexRateLimitResetCredit(...args);
123
- }
124
-
125
- export function getOrDownloadImage(...args: Parameters<typeof realApi.getOrDownloadImage>): ReturnType<typeof realApi.getOrDownloadImage> {
126
- return _impl.getOrDownloadImage(...args);
127
- }
128
-
129
- export function verifyAllPermissions(...args: Parameters<typeof realApi.verifyAllPermissions>): ReturnType<typeof realApi.verifyAllPermissions> {
130
- return _impl.verifyAllPermissions(...args);
131
- }
132
-
133
- export function reportPermissionResults(...args: Parameters<typeof realApi.reportPermissionResults>): ReturnType<typeof realApi.reportPermissionResults> {
134
- return _impl.reportPermissionResults(...args);
135
- }
136
-
137
- export function extractSessionInfo(...args: Parameters<typeof realApi.extractSessionInfo>): ReturnType<typeof realApi.extractSessionInfo> {
138
- return _impl.extractSessionInfo(...args);
139
- }
140
-
141
- export function extractSessionId(...args: Parameters<typeof realApi.extractSessionId>): ReturnType<typeof realApi.extractSessionId> {
142
- return _impl.extractSessionId(...args);
143
- }
144
-
145
- export function formatDelayNotice(...args: Parameters<typeof realApi.formatDelayNotice>): ReturnType<typeof realApi.formatDelayNotice> {
146
- return _impl.formatDelayNotice(...args);
147
- }
148
-
149
- export function sendPostMessage(...args: Parameters<typeof realApi.sendPostMessage>): ReturnType<typeof realApi.sendPostMessage> {
150
- return _impl.sendPostMessage(...args);
151
- }
152
-
153
- export function sendRestartCard(...args: Parameters<typeof realApi.sendRestartCard>): ReturnType<typeof realApi.sendRestartCard> {
154
- return _impl.sendRestartCard(...args);
155
- }
156
-
157
- export function getMergeForwardMessages(...args: Parameters<typeof realApi.getMergeForwardMessages>): ReturnType<typeof realApi.getMergeForwardMessages> {
158
- return _impl.getMergeForwardMessages(...args);
159
- }
@@ -1,293 +0,0 @@
1
- /**
2
- * format-message.ts — 飞书消息内容格式化
3
- *
4
- * 从 index.ts 中提取,独立模块便于测试。
5
- */
6
-
7
- import { cardJsonToPlainText } from "./card-plain-text.ts";
8
- import { ts } from "./config.ts";
9
- import {
10
- getTenantAccessToken,
11
- getOrDownloadImage,
12
- getMergeForwardMessages,
13
- } from "./feishu-platform.ts";
14
-
15
- /**
16
- * 根据消息类型格式化消息内容为可读文本。
17
- */
18
- export async function formatMessageContent(message: {
19
- message_id?: string;
20
- message_type?: string;
21
- content?: string;
22
- }): Promise<string> {
23
- const contentStr = message.content ?? "{}";
24
- let content: Record<string, unknown>;
25
- try { content = JSON.parse(contentStr); } catch {
26
- // merge_forward 消息的 content 可能为空字符串,但可通过 message_id 调 API 获取子消息
27
- if (message.message_type === "merge_forward") {
28
- content = {};
29
- } else {
30
- return "";
31
- }
32
- }
33
-
34
- if (message.message_type === "text") {
35
- let text = (content.text ?? "") as string;
36
- text = text.replace(/<\/?p[^>]*>/gi, "");
37
- text = text.replace(/<br\s*\/?>/gi, "\n");
38
- text = text.replace(/&nbsp;/gi, " ");
39
- return text.trim();
40
- }
41
-
42
- if (message.message_type === "post") {
43
- return formatPostContentWithImages(content, message.message_id);
44
- }
45
-
46
- if (message.message_type === "image") {
47
- const imageKey = content.image_key as string | undefined;
48
- const messageId = message.message_id;
49
- if (!imageKey || !messageId) return contentStr;
50
- try {
51
- const token = await getTenantAccessToken();
52
- const localPath = await getOrDownloadImage(token, messageId, imageKey);
53
- return `[图片] ${localPath}`;
54
- } catch (err) {
55
- console.error(
56
- `[${ts()}] [IMAGE] download failed for ${imageKey}: ${(err as Error).message}`,
57
- );
58
- return `[图片: ${imageKey}]`;
59
- }
60
- }
61
-
62
- if (message.message_type === "media") {
63
- const fileKey = content.file_key as string | undefined;
64
- const fileName = (content.file_name as string) || "video.mp4";
65
- const messageId = message.message_id;
66
- if (!fileKey || !messageId) return contentStr;
67
- return `[视频] message_id=${messageId} file_key=${fileKey} file_name=${fileName}`;
68
- }
69
-
70
- if (message.message_type === "file") {
71
- const fileKey = content.file_key as string | undefined;
72
- const fileName = (content.file_name as string) || "download.bin";
73
- const messageId = message.message_id;
74
- if (!fileKey || !messageId) return contentStr;
75
- return `[文件] message_id=${messageId} file_key=${fileKey} file_name=${fileName}`;
76
- }
77
-
78
- if (message.message_type === "interactive") {
79
- const raw = JSON.stringify(content);
80
- const text = cardJsonToPlainText(raw);
81
- if (text) return `[卡片] ${text}`;
82
- return contentStr;
83
- }
84
-
85
- if (message.message_type === "merge_forward") {
86
- return formatMergeForward(message.message_id ?? "", content);
87
- }
88
-
89
- // 其他类型(audio, sticker 等)直接给原始 JSON
90
- return contentStr;
91
- }
92
-
93
- export function formatPostContent(content: Record<string, unknown>): string {
94
- const paragraphs = getPostParagraphs(content);
95
- if (!Array.isArray(paragraphs)) return "";
96
-
97
- const parts: string[] = [];
98
- for (const line of paragraphs) {
99
- if (!Array.isArray(line)) continue;
100
- for (const elem of line) {
101
- const el = elem as Record<string, unknown>;
102
- if (!el || typeof el !== "object") continue;
103
- const text = formatPostTextElement(el);
104
- if (text) parts.push(text);
105
- }
106
- }
107
- return parts.join("\n").trim();
108
- }
109
-
110
- function getPostParagraphs(content: Record<string, unknown>): unknown[][] {
111
- const direct = content.content;
112
- if (Array.isArray(direct)) return direct as unknown[][];
113
-
114
- for (const locale of ["zh_cn", "en_us", "ja_jp"]) {
115
- const localized = content[locale] as Record<string, unknown> | undefined;
116
- if (localized && Array.isArray(localized.content)) {
117
- return localized.content as unknown[][];
118
- }
119
- }
120
-
121
- return [];
122
- }
123
-
124
- function formatPostTextElement(el: Record<string, unknown>): string {
125
- const t = typeof el.text === "string" ? el.text : "";
126
-
127
- if (el.tag === "code_block") {
128
- const lang = typeof el.language === "string" ? el.language : "";
129
- return "```" + lang + "\n" + t + "\n```";
130
- }
131
-
132
- if (el.tag === "p" || el.tag === "text") {
133
- return t;
134
- }
135
-
136
- return "";
137
- }
138
-
139
- function getPostImageKey(el: Record<string, unknown>): string | undefined {
140
- const imageKey = el.image_key;
141
- if (typeof imageKey === "string" && imageKey.trim()) return imageKey;
142
-
143
- if (el.tag === "img") {
144
- const fileKey = el.file_key;
145
- if (typeof fileKey === "string" && fileKey.trim()) return fileKey;
146
- }
147
-
148
- return undefined;
149
- }
150
-
151
- async function formatPostContentWithImages(
152
- content: Record<string, unknown>,
153
- messageId?: string,
154
- ): Promise<string> {
155
- const paragraphs = getPostParagraphs(content);
156
- if (!Array.isArray(paragraphs)) return "";
157
-
158
- const parts: string[] = [];
159
- for (const line of paragraphs) {
160
- if (!Array.isArray(line)) continue;
161
- for (const elem of line) {
162
- const el = elem as Record<string, unknown>;
163
- if (!el || typeof el !== "object") continue;
164
-
165
- const text = formatPostTextElement(el);
166
- if (text) parts.push(text);
167
-
168
- const imageKey = getPostImageKey(el);
169
- if (imageKey) {
170
- parts.push(await formatPostImageElement(messageId, imageKey));
171
- }
172
- }
173
- }
174
- return parts.join("\n").trim();
175
- }
176
-
177
- async function formatPostImageElement(
178
- messageId: string | undefined,
179
- imageKey: string,
180
- ): Promise<string> {
181
- if (!messageId) return `[图片: ${imageKey}]`;
182
-
183
- try {
184
- const token = await getTenantAccessToken();
185
- const localPath = await getOrDownloadImage(token, messageId, imageKey);
186
- return `[图片] ${localPath}`;
187
- } catch (err) {
188
- console.error(
189
- `[${ts()}] [IMAGE] download failed for post image ${imageKey}: ${(err as Error).message}`,
190
- );
191
- return `[图片: ${imageKey}]`;
192
- }
193
- }
194
-
195
- // ---------------------------------------------------------------------------
196
- // 合并转发消息格式化
197
- // ---------------------------------------------------------------------------
198
-
199
- /**
200
- * 格式化合并转发消息。
201
- *
202
- * 三阶段降级策略:
203
- * 1. 调用 GET /im/v1/messages/{messageId} 获取完整子消息列表
204
- * 2. API 失败时降级使用 content.preview 字段
205
- * 3. preview 也为空时返回原始 JSON
206
- *
207
- * 递归深度限制 MAX_DEPTH=3,避免嵌套合并转发 API 爆炸。
208
- */
209
- export async function formatMergeForward(
210
- messageId: string,
211
- content: Record<string, unknown>,
212
- depth: number = 0,
213
- ): Promise<string> {
214
- const MAX_DEPTH = 3;
215
- if (depth >= MAX_DEPTH) {
216
- return `[合并转发: 超出最大嵌套深度 ${MAX_DEPTH}]`;
217
- }
218
-
219
- const title = (content.title as string) || "聊天记录";
220
- const chatName = (content.chat_name as string) || "";
221
- const header = `[合并转发: ${title}${chatName ? ` (${chatName})` : ""}]`;
222
-
223
- // 从 preview 构建 sender ID → name 映射表
224
- const senderNameMap = new Map<string, string>();
225
- const preview = content.preview;
226
- if (Array.isArray(preview)) {
227
- for (const entry of preview) {
228
- const e = entry as Record<string, unknown>;
229
- const s = e.sender as Record<string, unknown> | undefined;
230
- if (s && typeof s.id === "string" && typeof s.name === "string") {
231
- senderNameMap.set(s.id, s.name);
232
- }
233
- }
234
- }
235
-
236
- const lines: string[] = [];
237
- let usedApi = false;
238
-
239
- // Phase 1: 尝试通过 API 获取完整子消息列表
240
- try {
241
- const token = await getTenantAccessToken();
242
- const items = await getMergeForwardMessages(token, messageId);
243
-
244
- // 跳过第一个 item(合并转发消息自身,无 upper_message_id)
245
- const subItems = items.filter((item) => item.upper_message_id);
246
-
247
- if (subItems.length > 0) {
248
- for (const item of subItems) {
249
- const senderId = item.sender?.id ?? "unknown";
250
- const senderName = senderNameMap.get(senderId) ?? senderId;
251
-
252
- const subMsgType = item.msg_type ?? "";
253
- const subContent = item.body?.content ?? "{}";
254
-
255
- try {
256
- const formatted = await formatMessageContent({
257
- message_id: item.message_id,
258
- message_type: subMsgType,
259
- content: subContent,
260
- });
261
- lines.push(`${senderName}: ${formatted}`);
262
- } catch {
263
- lines.push(`${senderName}: ${subContent}`);
264
- }
265
- }
266
- usedApi = true;
267
- }
268
- } catch (err) {
269
- console.error(
270
- `[${ts()}] [MERGE_FORWARD] API 获取子消息失败 (${messageId}), 降级使用 preview: ${(err as Error).message}`,
271
- );
272
- }
273
-
274
- // Phase 2: API 失败或返回空时降级使用 preview
275
- if (!usedApi) {
276
- if (Array.isArray(preview) && preview.length > 0) {
277
- for (const entry of preview) {
278
- const e = entry as Record<string, unknown>;
279
- const s = e.sender as Record<string, unknown> | undefined;
280
- const senderName = (s?.name as string) ?? "未知用户";
281
- const text = (e.content as string) ?? "";
282
- lines.push(`${senderName}: ${text}`);
283
- }
284
- }
285
- }
286
-
287
- // Phase 3: 没有任何内容时返回原始 JSON
288
- if (lines.length === 0) {
289
- return JSON.stringify(content);
290
- }
291
-
292
- return header + "\n" + lines.join("\n");
293
- }