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,175 +0,0 @@
1
- import type { UnifiedBlock } from "./adapters/adapter-interface.ts";
2
-
3
- export type AgentActivityKind =
4
- | "starting"
5
- | "thinking"
6
- | "tool"
7
- | "processing"
8
- | "responding"
9
- | "searching"
10
- | "compacting";
11
-
12
- /** The user-visible activity of a running Agent turn. */
13
- export interface AgentActivity {
14
- kind: AgentActivityKind;
15
- /** Time when the current activity began, used for truthful elapsed time. */
16
- startedAt: number;
17
- toolName?: string;
18
- toolCount?: number;
19
- }
20
-
21
- interface ActiveTool {
22
- id: string;
23
- name: string;
24
- startedAt: number;
25
- }
26
-
27
- export interface AgentActivityTracker {
28
- activity: AgentActivity;
29
- activeTools: Map<string, ActiveTool>;
30
- nextAnonymousToolId: number;
31
- }
32
-
33
- export function createAgentActivityTracker(now = Date.now()): AgentActivityTracker {
34
- return {
35
- activity: { kind: "starting", startedAt: now },
36
- activeTools: new Map(),
37
- nextAnonymousToolId: 1,
38
- };
39
- }
40
-
41
- function sameVisibleActivity(left: AgentActivity, right: AgentActivity): boolean {
42
- return left.kind === right.kind
43
- && left.toolName === right.toolName
44
- && left.toolCount === right.toolCount;
45
- }
46
-
47
- function setActivity(tracker: AgentActivityTracker, next: AgentActivity): boolean {
48
- if (sameVisibleActivity(tracker.activity, next)) return false;
49
- tracker.activity = next;
50
- return true;
51
- }
52
-
53
- function refreshToolActivity(tracker: AgentActivityTracker): boolean {
54
- const tools = [...tracker.activeTools.values()];
55
- const first = tools[0];
56
- if (!first) return false;
57
- return setActivity(tracker, {
58
- kind: "tool",
59
- startedAt: first.startedAt,
60
- toolName: first.name,
61
- toolCount: tools.length,
62
- });
63
- }
64
-
65
- function removeCompletedTool(tracker: AgentActivityTracker, toolUseId: string): void {
66
- if (toolUseId && tracker.activeTools.delete(toolUseId)) return;
67
-
68
- // Older adapters did not always include a tool ID. Prefer an anonymous entry;
69
- // if there is only one active call, it is still safe to match that result.
70
- const anonymousId = [...tracker.activeTools.keys()].find((id) => id.startsWith("anonymous:"));
71
- if (anonymousId) {
72
- tracker.activeTools.delete(anonymousId);
73
- } else if (tracker.activeTools.size === 1) {
74
- const onlyId = tracker.activeTools.keys().next().value as string | undefined;
75
- if (onlyId) tracker.activeTools.delete(onlyId);
76
- }
77
- }
78
-
79
- /**
80
- * Applies one normalized Agent event and returns whether the persisted activity
81
- * changed. Tool activity takes precedence while a tool call is still active.
82
- */
83
- export function updateAgentActivity(
84
- tracker: AgentActivityTracker,
85
- block: UnifiedBlock,
86
- now = Date.now(),
87
- ): boolean {
88
- if (block.type === "tool_use") {
89
- const id = block.id || `anonymous:${tracker.nextAnonymousToolId++}`;
90
- const existing = tracker.activeTools.get(id);
91
- tracker.activeTools.set(id, {
92
- id,
93
- name: block.name || "未知工具",
94
- startedAt: existing?.startedAt ?? now,
95
- });
96
- return refreshToolActivity(tracker);
97
- }
98
-
99
- if (block.type === "tool_result") {
100
- removeCompletedTool(tracker, block.tool_use_id);
101
- if (tracker.activeTools.size > 0) return refreshToolActivity(tracker);
102
- return setActivity(tracker, { kind: "processing", startedAt: now });
103
- }
104
-
105
- if (tracker.activeTools.size > 0) return false;
106
-
107
- switch (block.type) {
108
- case "agent_status":
109
- return setActivity(tracker, {
110
- kind: block.status === "compacting" ? "compacting" : "responding",
111
- startedAt: now,
112
- });
113
- case "thinking":
114
- case "redacted_thinking":
115
- return setActivity(tracker, { kind: "thinking", startedAt: now });
116
- case "text":
117
- case "text_final":
118
- return setActivity(tracker, { kind: "responding", startedAt: now });
119
- case "search_result":
120
- return setActivity(tracker, { kind: "searching", startedAt: now });
121
- case "compact_boundary":
122
- return setActivity(tracker, { kind: "compacting", startedAt: now });
123
- }
124
- }
125
-
126
- function formatElapsed(startedAt: number, now: number): string {
127
- const totalSeconds = Math.max(0, Math.floor((now - startedAt) / 1000));
128
- if (totalSeconds < 60) return `${totalSeconds}秒`;
129
- const totalMinutes = Math.floor(totalSeconds / 60);
130
- const seconds = totalSeconds % 60;
131
- if (totalMinutes < 60) return `${totalMinutes}分${seconds}秒`;
132
- const hours = Math.floor(totalMinutes / 60);
133
- const minutes = totalMinutes % 60;
134
- return `${hours}小时${minutes}分`;
135
- }
136
-
137
- function displayToolName(name: string | undefined): string {
138
- const normalized = (name || "未知工具").replace(/\s+/g, " ").trim();
139
- return normalized.length > 24 ? `${normalized.slice(0, 23)}…` : normalized;
140
- }
141
-
142
- export function formatAgentActivityTitle(
143
- activity: AgentActivity | undefined,
144
- now = Date.now(),
145
- ): string {
146
- if (!activity) return "正在处理";
147
-
148
- let label: string;
149
- switch (activity.kind) {
150
- case "starting":
151
- label = "正在启动 Agent";
152
- break;
153
- case "thinking":
154
- label = "思考中";
155
- break;
156
- case "tool": {
157
- const count = Math.max(1, activity.toolCount ?? 1);
158
- label = `正在执行 ${displayToolName(activity.toolName)}${count > 1 ? ` 等 ${count} 项` : ""}`;
159
- break;
160
- }
161
- case "processing":
162
- label = "正在处理工具结果";
163
- break;
164
- case "responding":
165
- label = "正在生成回复";
166
- break;
167
- case "searching":
168
- label = "正在处理搜索结果";
169
- break;
170
- case "compacting":
171
- label = "正在整理上下文";
172
- break;
173
- }
174
- return `${label} · ${formatElapsed(activity.startedAt, now)}`;
175
- }
@@ -1,153 +0,0 @@
1
- import type { IncomingMessage, ServerResponse } from "node:http";
2
- import { resolve } from "node:path";
3
-
4
- import { resolveDefaultAgentTool } from "./config.ts";
5
- import { readUtf8JsonBody } from "./agent-rpc-body.ts";
6
- import { delegateAgentTask } from "./agent-delegate-task.ts";
7
- import type { PlatformAdapter } from "./platform-adapter.ts";
8
- import { applySharedPrefix } from "./shared-prefix.ts";
9
-
10
- export const AGENT_DELEGATE_TASK_PATH = "/api/agent/delegate-task";
11
-
12
- const MAX_REQUEST_BYTES = 128 * 1024;
13
- const VALID_TOOLS = new Set(["claude", "cursor", "codex"]);
14
-
15
- interface AgentDelegateTaskPayload {
16
- tool?: unknown;
17
- cwd?: unknown;
18
- prompt?: unknown;
19
- text?: unknown;
20
- message?: unknown;
21
- open_id?: unknown;
22
- open_ids?: unknown;
23
- openIds?: unknown;
24
- chat_name?: unknown;
25
- }
26
-
27
- function jsonReply(res: ServerResponse, status: number, data: unknown): void {
28
- res.writeHead(status, { "Content-Type": "application/json; charset=utf-8" });
29
- res.end(JSON.stringify(data));
30
- }
31
-
32
- function stringValue(value: unknown): string {
33
- return typeof value === "string" ? value.trim() : "";
34
- }
35
-
36
- function normalizeOpenIds(payload: AgentDelegateTaskPayload): string[] {
37
- const explicitOpenId = stringValue(payload.open_id);
38
- if (explicitOpenId) return [explicitOpenId];
39
-
40
- const rawOpenIds = Array.isArray(payload.open_ids) ? payload.open_ids : payload.openIds;
41
- if (!Array.isArray(rawOpenIds)) return [];
42
- return rawOpenIds
43
- .filter((item): item is string => typeof item === "string")
44
- .map((item) => item.trim())
45
- .filter(Boolean);
46
- }
47
-
48
- function promptFromPayload(payload: AgentDelegateTaskPayload): string {
49
- return stringValue(payload.prompt) || stringValue(payload.text) || stringValue(payload.message);
50
- }
51
-
52
- function validateTool(rawTool: unknown): string {
53
- const tool = stringValue(rawTool).toLowerCase() || resolveDefaultAgentTool();
54
- if (!VALID_TOOLS.has(tool)) throw new Error(`unsupported tool: ${tool}`);
55
- return tool;
56
- }
57
-
58
- function validateCwd(rawCwd: unknown): string {
59
- const cwd = stringValue(rawCwd);
60
- if (!cwd) throw new Error("cwd must be a non-empty string");
61
- return resolve(cwd);
62
- }
63
-
64
- export async function handleAgentDelegateTaskRequest(
65
- req: IncomingMessage,
66
- res: ServerResponse,
67
- platform: PlatformAdapter,
68
- ): Promise<boolean> {
69
- const url = new URL(req.url ?? "/", "http://127.0.0.1");
70
- if (url.pathname !== AGENT_DELEGATE_TASK_PATH) return false;
71
-
72
- if (req.method !== "POST") {
73
- jsonReply(res, 405, { ok: false, error: "Method not allowed" });
74
- return true;
75
- }
76
-
77
- if (platform.kind !== "feishu") {
78
- jsonReply(res, 409, { ok: false, error: "This endpoint currently only supports Feishu." });
79
- return true;
80
- }
81
-
82
- let payload: AgentDelegateTaskPayload;
83
- try {
84
- payload = await readUtf8JsonBody(req, MAX_REQUEST_BYTES);
85
- } catch (err) {
86
- jsonReply(res, 400, { ok: false, error: (err as Error).message || "Invalid JSON" });
87
- return true;
88
- }
89
-
90
- let tool: string;
91
- let cwd: string;
92
- let promptText: string;
93
- let promptNamePrefix: string;
94
- let openIds: string[];
95
- try {
96
- tool = validateTool(payload.tool);
97
- cwd = validateCwd(payload.cwd);
98
- const rawPrompt = promptFromPayload(payload);
99
- if (!rawPrompt) throw new Error("prompt must be a non-empty string");
100
- const sharedPrefix = applySharedPrefix(rawPrompt);
101
- promptText = sharedPrefix.text;
102
- promptNamePrefix = sharedPrefix.body || rawPrompt;
103
- openIds = normalizeOpenIds(payload);
104
- if (openIds.length === 0) throw new Error("open_id or openIds must include at least one user");
105
- } catch (err) {
106
- jsonReply(res, 400, { ok: false, error: (err as Error).message });
107
- return true;
108
- }
109
-
110
- try {
111
- const result = await delegateAgentTask({
112
- platform,
113
- tool,
114
- cwd,
115
- promptText,
116
- openIds,
117
- chatNamePrefix: stringValue(payload.chat_name) || promptNamePrefix.slice(0, 10),
118
- });
119
- jsonReply(res, 200, {
120
- ok: true,
121
- chat_id: result.chatId,
122
- session_id: result.sessionId,
123
- tool: result.tool,
124
- cwd: result.cwd,
125
- });
126
- } catch (err) {
127
- jsonReply(res, 500, { ok: false, error: (err as Error).message });
128
- }
129
- return true;
130
- }
131
-
132
- export function buildAgentDelegateTaskCapabilityPrompt(input: { url: string; cwd?: string }): string {
133
- const lines = [
134
- "[ChatCCC local capability: delegate task]",
135
- "You can create a separate Feishu ChatCCC agent session and assign its first task by calling this local endpoint.",
136
- "",
137
- `POST ${input.url}`,
138
- "Content-Type: application/json; charset=utf-8",
139
- "",
140
- 'Body: {"tool":"codex|claude|cursor","cwd":"absolute working directory","open_id":"Feishu open_id to invite","prompt":"first task text"}',
141
- "",
142
- "Rules:",
143
- "- Use this only when the user asks you to start a separate delegated conversation/session.",
144
- "- Pass cwd explicitly as an absolute local path.",
145
- "- Pass tool explicitly when the user specified a target agent.",
146
- "- Use open_id for one user or open_ids/openIds for multiple users.",
147
- "- The prompt is sent through the normal ChatCCC prompt path, so project prompt injection and IM skills still apply.",
148
- "- Request body must be UTF-8 encoded JSON bytes. Do not call Feishu Open Platform directly.",
149
- "[/ChatCCC local capability: delegate task]",
150
- ];
151
- if (input.cwd) lines.splice(2, 0, `Current working directory: ${input.cwd}`);
152
- return lines.join("\n");
153
- }
@@ -1,91 +0,0 @@
1
- import { resolve } from "node:path";
2
-
3
- import { sessionPrefixForTool, toolDisplayName, ts } from "./config.ts";
4
- import { setDefaultCwd } from "./config.ts";
5
- import type { PlatformAdapter } from "./platform-adapter.ts";
6
- import {
7
- getEffectiveFastModeForTool,
8
- initClaudeSession,
9
- recordSessionRegistry,
10
- resumeAndPrompt,
11
- saveSessionTool,
12
- } from "./session.ts";
13
- import { bindChatToSession } from "./session-chat-binding.ts";
14
- import { sessionChatName } from "./session-name.ts";
15
-
16
- export interface DelegateAgentTaskInput {
17
- platform: PlatformAdapter;
18
- tool: string;
19
- cwd: string;
20
- promptText: string;
21
- openIds: string[];
22
- chatNamePrefix?: string;
23
- msgTimestamp?: number;
24
- traceId?: string;
25
- }
26
-
27
- export interface DelegateAgentTaskResult {
28
- chatId: string;
29
- sessionId: string;
30
- tool: string;
31
- cwd: string;
32
- }
33
-
34
- export async function delegateAgentTask(input: DelegateAgentTaskInput): Promise<DelegateAgentTaskResult> {
35
- const cwd = resolve(input.cwd);
36
- const toolLabel = toolDisplayName(input.tool);
37
- const init = await initClaudeSession(input.tool, cwd);
38
- const sessionId = init.sessionId;
39
- const chatNamePrefix = input.chatNamePrefix?.trim() || input.promptText.slice(0, 10) || "新会话";
40
- const chatName = sessionChatName(chatNamePrefix, cwd);
41
-
42
- let chatId: string;
43
- try {
44
- chatId = await input.platform.createGroup(chatName, input.openIds);
45
- await input.platform.updateChatInfo(chatId, chatName, `${sessionPrefixForTool(input.tool)} ${sessionId}`);
46
- await setDefaultCwd(cwd, chatId);
47
- bindChatToSession(sessionId, chatId);
48
- await recordSessionRegistry({
49
- chatId,
50
- sessionId,
51
- tool: input.tool,
52
- chatType: "group",
53
- chatName,
54
- turnCount: 0,
55
- startTime: Date.now(),
56
- running: false,
57
- });
58
- await saveSessionTool(sessionId, input.tool, chatName);
59
- } catch (err) {
60
- console.error(`[${ts()}] [AGENT-DELEGATE-TASK] create group failed: ${(err as Error).message}`);
61
- throw err;
62
- }
63
-
64
- await input.platform.sendCard(
65
- chatId,
66
- `${toolLabel} Session Ready`,
67
- `已创建 **${toolLabel}** 会话群。\n\n` +
68
- `**Session ID:** ${sessionId}\n` +
69
- `**工作目录:** \`${cwd}\`\n\n` +
70
- `下面会自动把任务作为第一句话发送给 ${toolLabel}。`,
71
- "green",
72
- ).catch(() => {});
73
- const fastMode = getEffectiveFastModeForTool(input.tool, sessionId);
74
- const avatarUpdate = fastMode
75
- ? input.platform.setChatAvatar(chatId, input.tool, "new", { fastMode: true })
76
- : input.platform.setChatAvatar(chatId, input.tool, "new");
77
- avatarUpdate.catch(() => {});
78
-
79
- await resumeAndPrompt(
80
- sessionId,
81
- input.promptText,
82
- input.platform,
83
- chatId,
84
- input.msgTimestamp ?? Date.now(),
85
- input.tool,
86
- input.traceId,
87
- );
88
-
89
- console.log(`[${ts()}] [AGENT-DELEGATE-TASK] created ${toolLabel} session=${sessionId} chat=${chatId} cwd=${cwd}`);
90
- return { chatId, sessionId, tool: input.tool, cwd };
91
- }
@@ -1,172 +0,0 @@
1
- import type { IncomingMessage, ServerResponse } from "node:http";
2
- import { extname, isAbsolute, resolve } from "node:path";
3
- import { stat } from "node:fs/promises";
4
-
5
- import { getTenantAccessToken, sendFileReply, sendTextReply } from "./feishu-platform.ts";
6
- import { ts, resolveDefaultAgentTool } from "./config.ts";
7
- import { readUtf8JsonBody } from "./agent-rpc-body.ts";
8
- import { getAdapterForTool } from "./session.ts";
9
- import { getChatsForSession } from "./session-chat-binding.ts";
10
- import { splitFeishuTargetChats } from "./agent-platform-routing.ts";
11
-
12
- export const AGENT_SEND_FILE_PATH = "/api/agent/send-file";
13
-
14
- const MAX_REQUEST_BYTES = 64 * 1024;
15
- const MAX_FILE_BYTES = 100 * 1024 * 1024;
16
- const ALLOWED_FILE_EXTS = new Set([
17
- ".mp4", ".mov", ".avi", ".mkv", ".webm", ".flv",
18
- ".mp3", ".wav", ".ogg", ".aac", ".m4a",
19
- ".pdf", ".doc", ".docx", ".xls", ".xlsx", ".csv", ".ppt", ".pptx",
20
- ".txt", ".zip", ".tar", ".gz",
21
- ]);
22
-
23
- function jsonReply(res: ServerResponse, status: number, data: unknown): void {
24
- res.writeHead(status, { "Content-Type": "application/json; charset=utf-8" });
25
- res.end(JSON.stringify(data));
26
- }
27
-
28
- async function resolveAndValidateFilePath(cwd: string, rawPath: unknown): Promise<string> {
29
- if (typeof rawPath !== "string" || rawPath.trim() === "") {
30
- throw new Error("path must be a non-empty string");
31
- }
32
-
33
- const sessionRoot = resolve(cwd);
34
- const filePath = isAbsolute(rawPath)
35
- ? resolve(rawPath)
36
- : resolve(sessionRoot, rawPath);
37
-
38
- const ext = extname(filePath).toLowerCase();
39
- if (!ALLOWED_FILE_EXTS.has(ext)) {
40
- throw new Error(`unsupported file extension: ${ext || "(none)"}`);
41
- }
42
-
43
- const st = await stat(filePath);
44
- if (!st.isFile()) throw new Error("file path is not a file");
45
- if (st.size <= 0) throw new Error("file is empty");
46
- if (st.size > MAX_FILE_BYTES) throw new Error("file is larger than 100MB");
47
- return filePath;
48
- }
49
-
50
- export async function handleAgentFileRequest(
51
- req: IncomingMessage,
52
- res: ServerResponse,
53
- ): Promise<boolean> {
54
- const url = new URL(req.url ?? "/", "http://127.0.0.1");
55
- if (url.pathname !== AGENT_SEND_FILE_PATH) return false;
56
-
57
- if (req.method !== "POST") {
58
- jsonReply(res, 405, { ok: false, error: "Method not allowed" });
59
- return true;
60
- }
61
-
62
- let payload: { session_id?: unknown; path?: unknown; caption?: unknown };
63
- try {
64
- payload = await readUtf8JsonBody(req, MAX_REQUEST_BYTES);
65
- } catch (err) {
66
- jsonReply(res, 400, { ok: false, error: (err as Error).message || "Invalid JSON" });
67
- return true;
68
- }
69
-
70
- const sessionId = typeof payload.session_id === "string" ? payload.session_id : "";
71
- if (!sessionId) {
72
- jsonReply(res, 400, { ok: false, error: "Missing session_id" });
73
- return true;
74
- }
75
-
76
- let cwd: string;
77
- try {
78
- const { getSessionTool } = await import("./session.ts");
79
- const tool = await getSessionTool(sessionId);
80
- const adapter = getAdapterForTool(tool ?? resolveDefaultAgentTool());
81
- const info = await adapter.getSessionInfo(sessionId);
82
- if (!info?.cwd) {
83
- jsonReply(res, 400, { ok: false, error: "Cannot determine cwd for session" });
84
- return true;
85
- }
86
- cwd = info.cwd;
87
- } catch (err) {
88
- jsonReply(res, 500, { ok: false, error: `Failed to get session info: ${(err as Error).message}` });
89
- return true;
90
- }
91
-
92
- let filePath: string;
93
- try {
94
- filePath = await resolveAndValidateFilePath(cwd, payload.path);
95
- } catch (err) {
96
- jsonReply(res, 400, { ok: false, error: (err as Error).message });
97
- return true;
98
- }
99
-
100
- const chatIds = getChatsForSession(sessionId);
101
- if (chatIds.length === 0) {
102
- jsonReply(res, 404, { ok: false, error: "No chats bound to this session" });
103
- return true;
104
- }
105
-
106
- const { getPlatformForChat } = await import("./session.ts");
107
- const { targetChatIds, skippedUnsupported } = splitFeishuTargetChats(
108
- chatIds,
109
- (cid) => getPlatformForChat(cid)?.kind,
110
- );
111
- if (targetChatIds.length === 0) {
112
- jsonReply(res, 409, {
113
- ok: false,
114
- error: "This endpoint only sends to Feishu chats. The bound chats are WeChat chats; use the WeChat file or video helper script instead.",
115
- skippedUnsupported,
116
- });
117
- return true;
118
- }
119
-
120
- try {
121
- const token = await getTenantAccessToken();
122
- const caption = typeof payload.caption === "string" ? payload.caption.trim() : "";
123
- let sentCount = 0;
124
- for (const cid of targetChatIds) {
125
- try {
126
- await sendFileReply(token, cid, filePath);
127
- if (caption) await sendTextReply(token, cid, caption);
128
- sentCount++;
129
- } catch (err) {
130
- console.error(`[${ts()}] [AGENT-FILE] send to ${cid} failed: ${(err as Error).message}`);
131
- }
132
- }
133
- console.log(`[${ts()}] [AGENT-FILE] sent file to ${sentCount}/${targetChatIds.length} Feishu chats, session=${sessionId} path=${filePath} skippedUnsupported=${skippedUnsupported.length}`);
134
- jsonReply(res, 200, { ok: true, sentTo: sentCount, total: targetChatIds.length, skippedUnsupported });
135
- } catch (err) {
136
- console.error(`[${ts()}] [AGENT-FILE] send failed: ${(err as Error).message}`);
137
- jsonReply(res, 500, { ok: false, error: (err as Error).message });
138
- }
139
- return true;
140
- }
141
-
142
- // ---------------------------------------------------------------------------
143
- // 兼容旧版 buildAgentFileCapabilityPrompt(供 im-skills 使用)
144
- // ---------------------------------------------------------------------------
145
-
146
- export function buildAgentFileCapabilityPrompt(input: {
147
- url: string;
148
- sessionId?: string;
149
- cwd?: string;
150
- }): string {
151
- const lines = [
152
- "[ChatCCC local capability: send file]",
153
- "You can send a file (video, audio, document, etc.) to all chats bound to this session by calling this local endpoint.",
154
- "",
155
- `POST ${input.url}`,
156
- "Content-Type: application/json; charset=utf-8",
157
- "",
158
- `Body: {"session_id":"${input.sessionId ?? "YOUR_SESSION_ID"}","path":"absolute file path","caption":"optional caption"}`,
159
- "",
160
- "Rules:",
161
- "- Save or choose a local file first, then call the endpoint.",
162
- "- Use an absolute local file path. Do not call Feishu Open Platform directly.",
163
- "- Request body must be UTF-8 encoded JSON bytes; caption supports Unicode text, including Chinese.",
164
- "- Only call this endpoint when the user asked for a file/video or when a file is useful to the answer.",
165
- "- Max file size: 100MB.",
166
- "[/ChatCCC local capability: send file]",
167
- ];
168
- if (input.cwd) {
169
- lines.splice(2, 0, `Current working directory: ${input.cwd}`);
170
- }
171
- return lines.join("\n");
172
- }