@oyasmi/pipiclaw 0.9.4-beta.1 → 0.9.4

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 (291) hide show
  1. package/dist/agent/builtin-commands.d.ts +19 -0
  2. package/dist/agent/builtin-commands.js +80 -0
  3. package/dist/agent/channel-runner.d.ts +20 -208
  4. package/dist/agent/channel-runner.js +148 -1245
  5. package/dist/agent/maintenance-context.d.ts +1 -1
  6. package/dist/agent/maintenance-context.js +1 -1
  7. package/dist/agent/prompt/resources.d.ts +3 -0
  8. package/dist/agent/prompt/resources.js +7 -1
  9. package/dist/agent/runner-factory.d.ts +1 -43
  10. package/dist/agent/{command-extension.d.ts → session/command-extension.d.ts} +4 -0
  11. package/dist/agent/{command-extension.js → session/command-extension.js} +5 -5
  12. package/dist/agent/{type-guards.d.ts → session/event-guards.d.ts} +2 -2
  13. package/dist/agent/{type-guards.js → session/event-guards.js} +5 -1
  14. package/dist/agent/session/model-selection.d.ts +47 -0
  15. package/dist/agent/session/model-selection.js +99 -0
  16. package/dist/agent/{session-adapter.d.ts → session/session-adapter.d.ts} +21 -1
  17. package/dist/agent/{session-adapter.js → session/session-adapter.js} +83 -1
  18. package/dist/agent/{session-events.d.ts → session/session-events.d.ts} +9 -5
  19. package/dist/agent/{session-events.js → session/session-events.js} +10 -10
  20. package/dist/agent/session/session-host.d.ts +200 -0
  21. package/dist/agent/session/session-host.js +621 -0
  22. package/dist/agent/{session-resource-gate.js → session/session-resource-gate.js} +2 -2
  23. package/dist/agent/{context-budget.js → turn/context-budget.js} +5 -1
  24. package/dist/agent/{progress-formatter.d.ts → turn/progress-formatter.d.ts} +4 -1
  25. package/dist/agent/{run-queue.d.ts → turn/run-queue.d.ts} +1 -1
  26. package/dist/agent/{run-queue.js → turn/run-queue.js} +3 -3
  27. package/dist/{memory → agent/turn}/task-digest.js +4 -4
  28. package/dist/agent/turn/turn-context.d.ts +14 -0
  29. package/dist/agent/turn/turn-context.js +64 -0
  30. package/dist/agent/turn/turn-finish.d.ts +50 -0
  31. package/dist/agent/turn/turn-finish.js +188 -0
  32. package/dist/agent/turn/turn-input.d.ts +43 -0
  33. package/dist/agent/turn/turn-input.js +79 -0
  34. package/dist/agent/turn/turn-pipeline.d.ts +68 -0
  35. package/dist/agent/turn/turn-pipeline.js +257 -0
  36. package/dist/agent/{turn-prompt.d.ts → turn/turn-prompt.d.ts} +2 -2
  37. package/dist/agent/{turn-prompt.js → turn/turn-prompt.js} +6 -2
  38. package/dist/agent/{turn-recovery.js → turn/turn-recovery.js} +1 -1
  39. package/dist/agent/{turn-state.d.ts → turn/turn-state.d.ts} +1 -1
  40. package/dist/agent/types.d.ts +43 -2
  41. package/dist/agent/types.js +1 -1
  42. package/dist/{models/auth-cli.d.ts → app/auth-command.d.ts} +1 -1
  43. package/dist/{models/auth-cli.js → app/auth-command.js} +11 -8
  44. package/dist/{runtime/app-home.d.ts → app/home.d.ts} +0 -2
  45. package/dist/{runtime/app-home.js → app/home.js} +4 -75
  46. package/dist/{app-services.d.ts → app/services.d.ts} +5 -5
  47. package/dist/{app-services.js → app/services.js} +10 -10
  48. package/dist/channel/channel-context.d.ts +12 -2
  49. package/dist/channel/channel-context.js +29 -2
  50. package/dist/channel/channel-event.d.ts +10 -2
  51. package/dist/channel/channel-event.js +1 -1
  52. package/dist/{runtime/project-commands.d.ts → channel/commands.d.ts} +1 -1
  53. package/dist/{runtime/project-commands.js → channel/commands.js} +1 -1
  54. package/dist/channel/store.js +4 -0
  55. package/dist/commands/catalog.d.ts +3 -3
  56. package/dist/commands/catalog.js +3 -3
  57. package/dist/{runtime/report-commands.d.ts → commands/router.d.ts} +10 -3
  58. package/dist/{runtime/report-commands.js → commands/router.js} +5 -5
  59. package/dist/{settings.d.ts → config/settings.d.ts} +7 -8
  60. package/dist/{settings.js → config/settings.js} +7 -10
  61. package/dist/{tools/config.d.ts → config/tools.d.ts} +1 -2
  62. package/dist/{tools/config.js → config/tools.js} +5 -2
  63. package/dist/dingtalk/access-token.d.ts +12 -0
  64. package/dist/dingtalk/access-token.js +51 -0
  65. package/dist/dingtalk/api.d.ts +19 -0
  66. package/dist/dingtalk/api.js +67 -0
  67. package/dist/dingtalk/bot.d.ts +97 -0
  68. package/dist/dingtalk/bot.js +389 -0
  69. package/dist/dingtalk/cards.d.ts +56 -0
  70. package/dist/dingtalk/cards.js +318 -0
  71. package/dist/{runtime → dingtalk}/channel-queue.js +3 -0
  72. package/dist/dingtalk/config.d.ts +19 -0
  73. package/dist/dingtalk/config.js +95 -0
  74. package/dist/dingtalk/connection.d.ts +57 -0
  75. package/dist/dingtalk/connection.js +356 -0
  76. package/dist/dingtalk/conversation-meta.d.ts +16 -0
  77. package/dist/dingtalk/conversation-meta.js +77 -0
  78. package/dist/{runtime → dingtalk}/delivery.d.ts +6 -2
  79. package/dist/dingtalk/handler.d.ts +90 -0
  80. package/dist/dingtalk/handler.js +1 -0
  81. package/dist/dingtalk/inbound.d.ts +66 -0
  82. package/dist/dingtalk/inbound.js +137 -0
  83. package/dist/dingtalk/media.d.ts +66 -0
  84. package/dist/dingtalk/media.js +214 -0
  85. package/dist/events/{event-commands.js → commands.js} +6 -2
  86. package/dist/events/parse.d.ts +14 -0
  87. package/dist/events/parse.js +114 -0
  88. package/dist/events/types.d.ts +93 -0
  89. package/dist/events/types.js +1 -0
  90. package/dist/events/{event-validation.d.ts → validation.d.ts} +1 -1
  91. package/dist/events/watcher.d.ts +67 -0
  92. package/dist/events/{events.js → watcher.js} +6 -109
  93. package/dist/index.d.ts +6 -4
  94. package/dist/index.js +2 -2
  95. package/dist/jobs/launch.d.ts +42 -0
  96. package/dist/jobs/launch.js +118 -0
  97. package/dist/{agent/job-manager.d.ts → jobs/manager.d.ts} +1 -67
  98. package/dist/{agent/job-manager.js → jobs/manager.js} +3 -146
  99. package/dist/jobs/record.d.ts +55 -0
  100. package/dist/jobs/record.js +36 -0
  101. package/dist/main.js +2 -2
  102. package/dist/memory/maintenance-gates.d.ts +2 -2
  103. package/dist/memory/maintenance-tuning.d.ts +15 -0
  104. package/dist/memory/maintenance-tuning.js +3 -0
  105. package/dist/memory/reflect-job.d.ts +2 -2
  106. package/dist/memory/reflect-job.js +4 -2
  107. package/dist/memory/scheduler.d.ts +3 -3
  108. package/dist/memory/scheduler.js +2 -1
  109. package/dist/memory/sidecar-worker.js +1 -1
  110. package/dist/memory/transcript.js +1 -1
  111. package/dist/{agent/model-fallback.d.ts → models/fallback.d.ts} +6 -6
  112. package/dist/{agent/model-fallback.js → models/fallback.js} +15 -28
  113. package/dist/models/login-identity.d.ts +2 -0
  114. package/dist/models/login-identity.js +83 -0
  115. package/dist/models/provider-login.d.ts +3 -1
  116. package/dist/models/provider-login.js +8 -2
  117. package/dist/models/reference.d.ts +20 -0
  118. package/dist/models/{utils.js → reference.js} +0 -48
  119. package/dist/models/{utils.d.ts → runtime.d.ts} +1 -16
  120. package/dist/models/runtime.js +52 -0
  121. package/dist/playbooks/catalog.d.ts +6 -2
  122. package/dist/playbooks/catalog.js +9 -6
  123. package/dist/runtime/bootstrap.d.ts +7 -17
  124. package/dist/runtime/bootstrap.js +37 -755
  125. package/dist/runtime/durable-dispatch.d.ts +17 -4
  126. package/dist/runtime/durable-dispatch.js +60 -18
  127. package/dist/runtime/inbound-images.d.ts +18 -0
  128. package/dist/runtime/inbound-images.js +51 -0
  129. package/dist/runtime/shutdown.d.ts +39 -0
  130. package/dist/runtime/shutdown.js +120 -0
  131. package/dist/runtime/stop-watchdog.d.ts +16 -0
  132. package/dist/runtime/stop-watchdog.js +32 -0
  133. package/dist/runtime/task-driver.d.ts +2 -2
  134. package/dist/runtime/task-driver.js +3 -3
  135. package/dist/runtime/task-migration.js +2 -2
  136. package/dist/runtime/task-spawn.d.ts +1 -1
  137. package/dist/runtime/task-spawn.js +1 -1
  138. package/dist/runtime/turn-handler.d.ts +47 -0
  139. package/dist/runtime/turn-handler.js +318 -0
  140. package/dist/runtime/turn-run.d.ts +52 -0
  141. package/dist/runtime/turn-run.js +318 -0
  142. package/dist/security/command-guard.js +4 -0
  143. package/dist/security/network.js +4 -0
  144. package/dist/security/path-guard.js +4 -0
  145. package/dist/security/types.d.ts +1 -2
  146. package/dist/security/types.js +1 -2
  147. package/dist/shared/exact-keys.d.ts +1 -1
  148. package/dist/shared/host-process.js +1 -1
  149. package/dist/shared/wake-claim.d.ts +1 -1
  150. package/dist/{runtime/skill-commands.d.ts → skills/commands.d.ts} +2 -2
  151. package/dist/{runtime/skill-commands.js → skills/commands.js} +1 -1
  152. package/dist/{agent/workspace-resources.js → skills/loader.js} +1 -1
  153. package/dist/{tools/skill-security.js → skills/validation.js} +4 -0
  154. package/dist/skills/workspace.d.ts +33 -0
  155. package/dist/skills/workspace.js +116 -0
  156. package/dist/{runtime/subagent-commands.d.ts → subagents/commands.d.ts} +4 -3
  157. package/dist/{runtime/subagent-commands.js → subagents/commands.js} +2 -2
  158. package/dist/subagents/completion-wake.d.ts +17 -0
  159. package/dist/subagents/completion-wake.js +76 -0
  160. package/dist/subagents/detached-discovery.js +1 -1
  161. package/dist/subagents/discovery.d.ts +1 -1
  162. package/dist/subagents/discovery.js +2 -2
  163. package/dist/subagents/dispatch.d.ts +33 -0
  164. package/dist/subagents/dispatch.js +190 -0
  165. package/dist/subagents/external/dispatch.d.ts +25 -0
  166. package/dist/subagents/external/dispatch.js +90 -0
  167. package/dist/subagents/external/harness.d.ts +1 -1
  168. package/dist/subagents/external/progress-tail.d.ts +1 -1
  169. package/dist/subagents/external/run.d.ts +2 -1
  170. package/dist/subagents/external/run.js +2 -2
  171. package/dist/subagents/external/settlement.d.ts +1 -1
  172. package/dist/subagents/format.d.ts +1 -1
  173. package/dist/subagents/grace.d.ts +24 -0
  174. package/dist/subagents/grace.js +57 -0
  175. package/dist/subagents/internal/outcome.d.ts +24 -0
  176. package/dist/subagents/internal/outcome.js +149 -0
  177. package/dist/subagents/internal/provider-retry.d.ts +19 -0
  178. package/dist/subagents/internal/provider-retry.js +83 -0
  179. package/dist/subagents/internal/run.d.ts +31 -0
  180. package/dist/subagents/internal/run.js +240 -0
  181. package/dist/subagents/internal/state.d.ts +43 -0
  182. package/dist/subagents/internal/state.js +48 -0
  183. package/dist/subagents/internal/worker.d.ts +51 -0
  184. package/dist/subagents/internal/worker.js +167 -0
  185. package/dist/subagents/result.d.ts +62 -0
  186. package/dist/subagents/result.js +103 -0
  187. package/dist/subagents/run-record.d.ts +222 -0
  188. package/dist/subagents/run-record.js +101 -0
  189. package/dist/subagents/run-registry.d.ts +9 -0
  190. package/dist/subagents/run-registry.js +125 -0
  191. package/dist/subagents/runs.d.ts +7 -243
  192. package/dist/subagents/runs.js +8 -291
  193. package/dist/subagents/task-envelope.d.ts +36 -0
  194. package/dist/subagents/task-envelope.js +168 -0
  195. package/dist/subagents/types.d.ts +154 -0
  196. package/dist/subagents/types.js +1 -0
  197. package/dist/subagents/verification-outcome.d.ts +1 -1
  198. package/dist/tasks/board.d.ts +2 -2
  199. package/dist/tasks/board.js +2 -2
  200. package/dist/tasks/{work-log.d.ts → bound-work.d.ts} +1 -1
  201. package/dist/tasks/{work-log.js → bound-work.js} +1 -1
  202. package/dist/tasks/brief.js +1 -1
  203. package/dist/{runtime/task-commands.d.ts → tasks/commands.d.ts} +1 -1
  204. package/dist/{runtime/task-commands.js → tasks/commands.js} +12 -8
  205. package/dist/tasks/contract-input.d.ts +1 -1
  206. package/dist/tasks/contract-input.js +1 -1
  207. package/dist/tasks/create.js +1 -1
  208. package/dist/tasks/{log.js → loop-log.js} +1 -1
  209. package/dist/tasks/mutation-lock.js +1 -1
  210. package/dist/tasks/session-path.js +1 -1
  211. package/dist/tasks/steer.js +1 -1
  212. package/dist/tasks/store.js +2 -2
  213. package/dist/tools/bash.d.ts +1 -1
  214. package/dist/tools/{tool-details.d.ts → contract/details.d.ts} +2 -2
  215. package/dist/tools/{tool-details.js → contract/details.js} +4 -4
  216. package/dist/tools/{presentation.js → contract/presentation.js} +3 -3
  217. package/dist/tools/event-manage.d.ts +1 -1
  218. package/dist/tools/event-manage.js +4 -4
  219. package/dist/tools/index.d.ts +3 -3
  220. package/dist/tools/index.js +7 -6
  221. package/dist/tools/job.d.ts +1 -1
  222. package/dist/tools/registry.d.ts +7 -7
  223. package/dist/tools/registry.js +6 -6
  224. package/dist/tools/session-search.d.ts +1 -1
  225. package/dist/tools/skill.d.ts +2 -34
  226. package/dist/tools/skill.js +8 -116
  227. package/dist/tools/subagent-manage.js +4 -3
  228. package/dist/tools/subagent.d.ts +46 -0
  229. package/dist/tools/subagent.js +127 -0
  230. package/dist/tools/{task-manage.d.ts → task-manage/factory.d.ts} +7 -3
  231. package/dist/tools/{task-manage.js → task-manage/factory.js} +7 -7
  232. package/dist/tools/task-manage/lifecycle.js +2 -2
  233. package/dist/tools/task-manage/log-view.js +2 -2
  234. package/dist/tools/task-manage/shared.js +3 -3
  235. package/dist/tools/task-manage/step-end.js +3 -3
  236. package/dist/tools/task-manage/types.d.ts +1 -1
  237. package/dist/tools/web-fetch.d.ts +1 -1
  238. package/dist/tools/web-search.d.ts +1 -1
  239. package/dist/tui/app.d.ts +1 -1
  240. package/dist/tui/app.js +6 -6
  241. package/dist/tui/cli.d.ts +1 -1
  242. package/dist/tui/cli.js +1 -1
  243. package/dist/tui/frontend.d.ts +44 -0
  244. package/dist/tui/frontend.js +13 -0
  245. package/dist/tui/pitui-frontend.d.ts +1 -1
  246. package/dist/tui/plain-frontend.d.ts +1 -1
  247. package/dist/tui/renderer.d.ts +3 -42
  248. package/dist/tui/terminal-context.d.ts +2 -2
  249. package/dist/tui/terminal-media-sender.d.ts +1 -1
  250. package/dist/tui/turn-controller.d.ts +1 -1
  251. package/dist/usage/ledger.js +4 -0
  252. package/dist/{shared/types.d.ts → usage/totals.d.ts} +3 -0
  253. package/dist/web/client.d.ts +5 -1
  254. package/dist/web/client.js +4 -0
  255. package/dist/web/config.d.ts +1 -1
  256. package/dist/web/fetch.d.ts +1 -1
  257. package/dist/web/search-providers.d.ts +1 -1
  258. package/dist/web/search.d.ts +1 -1
  259. package/package.json +10 -7
  260. package/dist/events/events.d.ts +0 -159
  261. package/dist/runtime/dingtalk.d.ts +0 -272
  262. package/dist/runtime/dingtalk.js +0 -1470
  263. package/dist/subagents/tool.d.ts +0 -213
  264. package/dist/subagents/tool.js +0 -1282
  265. /package/dist/{runtime → agent/prompt}/workspace-templates.d.ts +0 -0
  266. /package/dist/{runtime → agent/prompt}/workspace-templates.js +0 -0
  267. /package/dist/agent/{session-resource-gate.d.ts → session/session-resource-gate.d.ts} +0 -0
  268. /package/dist/agent/{context-budget.d.ts → turn/context-budget.d.ts} +0 -0
  269. /package/dist/agent/{progress-formatter.js → turn/progress-formatter.js} +0 -0
  270. /package/dist/{memory → agent/turn}/task-digest.d.ts +0 -0
  271. /package/dist/agent/{turn-error.d.ts → turn/turn-error.d.ts} +0 -0
  272. /package/dist/agent/{turn-error.js → turn/turn-error.js} +0 -0
  273. /package/dist/agent/{turn-recovery.d.ts → turn/turn-recovery.d.ts} +0 -0
  274. /package/dist/agent/{turn-state.js → turn/turn-state.js} +0 -0
  275. /package/dist/{runtime → app}/proxy.d.ts +0 -0
  276. /package/dist/{runtime → app}/proxy.js +0 -0
  277. /package/dist/{runtime → dingtalk}/channel-queue.d.ts +0 -0
  278. /package/dist/{runtime → dingtalk}/delivery.js +0 -0
  279. /package/dist/{runtime → dingtalk}/inbound-media.d.ts +0 -0
  280. /package/dist/{runtime → dingtalk}/inbound-media.js +0 -0
  281. /package/dist/events/{event-commands.d.ts → commands.d.ts} +0 -0
  282. /package/dist/events/{event-validation.js → validation.js} +0 -0
  283. /package/dist/{agent/workspace-resources.d.ts → skills/loader.d.ts} +0 -0
  284. /package/dist/{tools/skill-security.d.ts → skills/validation.d.ts} +0 -0
  285. /package/dist/tasks/{ledger.d.ts → contract.d.ts} +0 -0
  286. /package/dist/tasks/{ledger.js → contract.js} +0 -0
  287. /package/dist/tasks/{log.d.ts → loop-log.d.ts} +0 -0
  288. /package/dist/tools/{subagent-tool-names.d.ts → contract/names.d.ts} +0 -0
  289. /package/dist/tools/{subagent-tool-names.js → contract/names.js} +0 -0
  290. /package/dist/tools/{presentation.d.ts → contract/presentation.d.ts} +0 -0
  291. /package/dist/{shared/types.js → usage/totals.js} +0 -0
@@ -1,1470 +0,0 @@
1
- /**
2
- * DingTalk communication layer using dingtalk-stream SDK with AI Card streaming.
3
- *
4
- * Handles:
5
- * - Receiving messages via DingTalk Stream Mode (DWClient)
6
- * - Responding via AI Card (streaming) or plain markdown (fallback)
7
- * - Access token management
8
- * - Per-channel message queuing
9
- */
10
- import axios from "axios";
11
- import { DWClient, TOPIC_ROBOT } from "dingtalk-stream";
12
- import { existsSync, mkdirSync, readFileSync } from "fs";
13
- import { dirname, join } from "path";
14
- import { getChannelDir } from "../channel/channel-paths.js";
15
- import { formatBusyHint, parseBuiltInCommand, renderBuiltInHelp, slashCommandName, } from "../commands/catalog.js";
16
- import * as log from "../log.js";
17
- import { writeFileAtomicallySync } from "../shared/atomic-file.js";
18
- import { createSerialQueue } from "../shared/serial-queue.js";
19
- import { errorMessage } from "../shared/text-utils.js";
20
- import { isRecord } from "../shared/type-guards.js";
21
- import { sleepUnref } from "../shared/with-timeout.js";
22
- import { formatSize } from "../tools/truncate.js";
23
- // Turn serialization is runtime policy; the queue lives in its own module and
24
- // this transport only consumes it.
25
- import { ChannelQueue } from "./channel-queue.js";
26
- import { MAX_INBOUND_IMAGE_BYTES, MAX_INBOUND_IMAGES_PER_MESSAGE, MEDIA_DOWNLOAD_TIMEOUT_MS, parseInboundMessage, sniffImageMimeType, } from "./inbound-media.js";
27
- const RESPONSE_MODE_VALUES = [
28
- "full_progress_then_plain_final",
29
- "rolling_progress_then_plain_final",
30
- "final_card_only",
31
- ];
32
- export function progressStyleOf(mode) {
33
- if (mode === "final_card_only")
34
- return "none";
35
- if (mode === "rolling_progress_then_plain_final")
36
- return "rolling";
37
- return "full";
38
- }
39
- export function finalDeliveryOf(mode) {
40
- return mode === "final_card_only" ? "card" : "plain";
41
- }
42
- export function isBusyMessageDefaultConfig(value) {
43
- return value === "steer" || value === "followUp" || value === "followup";
44
- }
45
- export function isResponseModeConfig(value) {
46
- return typeof value === "string" && RESPONSE_MODE_VALUES.includes(value);
47
- }
48
- export function normalizeBusyMessageDefault(value) {
49
- if (value === undefined) {
50
- return "steer";
51
- }
52
- if (value === "steer") {
53
- return "steer";
54
- }
55
- if (value === "followUp" || value === "followup") {
56
- return "followUp";
57
- }
58
- throw new Error('Invalid `busyMessageDefault`: expected "steer", "followUp", or "followup".');
59
- }
60
- export function normalizeResponseMode(value) {
61
- if (value === undefined) {
62
- return "full_progress_then_plain_final";
63
- }
64
- if (isResponseModeConfig(value)) {
65
- return value;
66
- }
67
- throw new Error('Invalid `responseMode`: expected "full_progress_then_plain_final", "rolling_progress_then_plain_final", or "final_card_only".');
68
- }
69
- /** Lowercased extension without the dot ("Report.PDF" → "pdf"); "" when none. */
70
- function extractFileExtension(fileName) {
71
- const dot = fileName.lastIndexOf(".");
72
- if (dot < 0 || dot === fileName.length - 1)
73
- return "";
74
- return fileName.slice(dot + 1).toLowerCase();
75
- }
76
- // ============================================================================
77
- // Constants
78
- // ============================================================================
79
- const DINGTALK_API = "https://api.dingtalk.com";
80
- // Media upload lives on the legacy oapi host, not the v1.0 api host. It returns a
81
- // reusable `media_id` that the v1.0 robot send endpoints reference (photoURL /
82
- // mediaId). The `access_token` query param is the same app access token minted by
83
- // `/v1.0/oauth2/accessToken` — DingTalk unified the internal-app token across both
84
- // hosts — so `getAccessToken()` is reused rather than fetching a second token.
85
- const DINGTALK_OAPI = "https://oapi.dingtalk.com";
86
- // DingTalk caps robot image messages at 1MB and file messages at 20MB. We reject
87
- // oversized files before spending an upload round-trip on a request the API rejects.
88
- const MAX_IMAGE_BYTES = 1024 * 1024;
89
- const MAX_FILE_BYTES = 20 * 1024 * 1024;
90
- // Uploads can move up to 20MB; the 15s default HTTP timeout is too tight for that.
91
- const MEDIA_UPLOAD_TIMEOUT_MS = 60_000;
92
- // File extensions the `sampleFile` message type accepts (per DingTalk docs).
93
- const SUPPORTED_FILE_TYPES = new Set(["xlsx", "pdf", "zip", "rar", "doc", "docx", "ppt", "pptx", "csv", "txt"]);
94
- // Bound every outbound DingTalk HTTP call. Without this, axios waits forever on a
95
- // hung connection, and a stalled card-streaming request would wedge the delivery
96
- // sync loop (never resolving flush()), leaving the whole channel permanently busy.
97
- // A timeout turns "hang" into a normal failure that the existing fallback paths
98
- // (bounded snapshot replay / sendPlain) already handle.
99
- const DINGTALK_HTTP_TIMEOUT_MS = 15_000;
100
- const http = axios.create({ timeout: DINGTALK_HTTP_TIMEOUT_MS });
101
- // Bounds enqueueStreamMessage (user messages + busy-message requeues), mirroring the
102
- // existing cap on enqueueEvent. Without a limit, a busy channel getting flooded with
103
- // messages (or repeated followUp requeues) grows this queue without bound — each item
104
- // still runs a full serialized turn, so an unbounded queue means unbounded backlog time
105
- // and unbounded memory, not just a slow channel.
106
- const USER_MESSAGE_QUEUE_LIMIT = 20;
107
- const EVENT_QUEUE_LIMIT = 5;
108
- // Channel metadata is persisted on disk, so these in-memory caches can be safely
109
- // reclaimed after inactivity. A stale unfinished card falls back to a fresh card
110
- // on the next update rather than retaining one channel forever.
111
- const CHANNEL_CACHE_TTL_MS = 60 * 60 * 1000;
112
- const CHANNEL_CACHE_SWEEP_MS = 10 * 60 * 1000;
113
- const TOKEN_REFRESH_SECS = 90 * 60; // 1.5 hours (tokens expire after 2 hours)
114
- const CONNECT_ATTEMPT_TIMEOUT_MS = 10_000;
115
- const SOCKET_CLOSE_GRACE_MS = 1_000;
116
- const SOCKET_TERMINATE_GRACE_MS = 250;
117
- const SOCKET_STATE_CONNECTING = 0;
118
- const SOCKET_STATE_OPEN = 1;
119
- const SOCKET_STATE_CLOSING = 2;
120
- const SOCKET_STATE_CLOSED = 3;
121
- // ============================================================================
122
- // DingTalkBot
123
- // ============================================================================
124
- export class DingTalkBot {
125
- constructor(handler, config) {
126
- // Access token cache
127
- this.accessToken = null;
128
- this.tokenExpiry = 0;
129
- this.tokenRefreshPromise = null;
130
- // Active AI cards: channelId → AICard
131
- this.activeCards = new Map();
132
- this.cardGenerations = new Map();
133
- this.cardCreationAttempted = new Set();
134
- // Share creation within a turn, but never let a late old turn own a new turn's card.
135
- this.cardCreationInFlight = new Map();
136
- // Conversation metadata cache: channelId → metadata
137
- this.convMeta = new Map();
138
- this.channelLastActiveAt = new Map();
139
- // Per-channel queues
140
- this.queues = new Map();
141
- // Serializes "resolve inbound image attachments → build event → route" per channel (spec 049
142
- // D3): a message needing a download must not be overtaken, in delivery order, by a later
143
- // download-free message on the same channel. `pendingInboundIngestCount` lets
144
- // `allChannelQueuesIdle()` see this in-flight network work, which `ChannelQueue.isIdle()`
145
- // alone cannot — the event has not been built yet, let alone enqueued.
146
- this.inboundIngestQueue = createSerialQueue();
147
- this.pendingInboundIngestCount = 0;
148
- // Connection stability
149
- this.client = null;
150
- this.lastSocketAvailableTime = Date.now();
151
- this.activeMessageProcessing = false;
152
- this.keepAliveTimer = null;
153
- this.reconnectTimer = null;
154
- // Dedicated timer for the in-flight backoff sleep inside doReconnect, kept
155
- // separate from reconnectTimer so an external scheduleReconnect() (e.g. a
156
- // WebSocket close event) can never clear the sleep out from under an active
157
- // attempt and leave isReconnecting stuck true forever.
158
- this.reconnectDelayTimer = null;
159
- this.reconnectDelayResolve = null;
160
- this.channelCacheSweepTimer = null;
161
- this.isReconnecting = false;
162
- this.isStopped = false;
163
- this.reconnectAttempts = 0;
164
- this.hasReportedReady = false;
165
- // Deduplication cache (Set for O(1) lookup, order array for FIFO eviction)
166
- this.processedIds = new Set();
167
- this.processedIdsOrder = [];
168
- this.handler = handler;
169
- this.config = {
170
- ...config,
171
- busyMessageDefault: normalizeBusyMessageDefault(config.busyMessageDefault),
172
- responseMode: normalizeResponseMode(config.responseMode),
173
- cardAutoLayout: config.cardAutoLayout ?? true,
174
- };
175
- this.channelCacheSweepTimer = setInterval(() => this.cleanupIdleChannelCaches(), CHANNEL_CACHE_SWEEP_MS);
176
- this.channelCacheSweepTimer.unref?.();
177
- }
178
- get busyMessageDefault() {
179
- return normalizeBusyMessageDefault(this.config.busyMessageDefault);
180
- }
181
- get responseMode() {
182
- return normalizeResponseMode(this.config.responseMode);
183
- }
184
- get progressStyle() {
185
- return progressStyleOf(this.responseMode);
186
- }
187
- get finalDelivery() {
188
- return finalDeliveryOf(this.responseMode);
189
- }
190
- /**
191
- * Mark an ID as processed. Returns true if this is a new ID, false if already seen.
192
- * Maintains a FIFO buffer of at most 200 entries.
193
- */
194
- markProcessed(id) {
195
- if (this.processedIds.has(id))
196
- return false;
197
- this.processedIds.add(id);
198
- this.processedIdsOrder.push(id);
199
- while (this.processedIdsOrder.length > 200) {
200
- this.processedIds.delete(this.processedIdsOrder.shift());
201
- }
202
- return true;
203
- }
204
- getSocket() {
205
- if (!this.client) {
206
- return null;
207
- }
208
- const socket = Reflect.get(this.client, "socket");
209
- return this.isSocketLike(socket) ? socket : null;
210
- }
211
- isSocketLike(value) {
212
- if (!isRecord(value)) {
213
- return false;
214
- }
215
- return typeof value.on === "function";
216
- }
217
- setTrackedTimeout(callback, delayMs) {
218
- const timer = setTimeout(() => {
219
- callback();
220
- }, delayMs);
221
- timer.unref?.();
222
- return timer;
223
- }
224
- setTrackedInterval(callback, intervalMs) {
225
- const timer = setInterval(callback, intervalMs);
226
- timer.unref?.();
227
- return timer;
228
- }
229
- clearKeepAliveTimer() {
230
- if (this.keepAliveTimer) {
231
- clearInterval(this.keepAliveTimer);
232
- this.keepAliveTimer = null;
233
- }
234
- }
235
- clearReconnectTimer() {
236
- if (this.reconnectTimer) {
237
- clearTimeout(this.reconnectTimer);
238
- this.reconnectTimer = null;
239
- }
240
- }
241
- // Cancel the backoff sleep and resolve its pending promise so the awaiting
242
- // doReconnect unblocks (and then bails on the isStopped/!client re-check)
243
- // instead of hanging forever.
244
- clearReconnectDelay() {
245
- if (this.reconnectDelayTimer) {
246
- clearTimeout(this.reconnectDelayTimer);
247
- this.reconnectDelayTimer = null;
248
- }
249
- if (this.reconnectDelayResolve) {
250
- const resolve = this.reconnectDelayResolve;
251
- this.reconnectDelayResolve = null;
252
- resolve();
253
- }
254
- }
255
- clearAllTimers() {
256
- this.clearKeepAliveTimer();
257
- this.clearReconnectTimer();
258
- this.clearReconnectDelay();
259
- }
260
- async waitForDelay(delayMs) {
261
- await new Promise((resolve) => {
262
- this.reconnectDelayResolve = resolve;
263
- this.reconnectDelayTimer = this.setTrackedTimeout(() => {
264
- this.reconnectDelayTimer = null;
265
- this.reconnectDelayResolve = null;
266
- resolve();
267
- }, delayMs);
268
- });
269
- }
270
- async waitForSocketState(socket, expectedState, timeoutMs) {
271
- const deadline = Date.now() + timeoutMs;
272
- while ((socket.readyState ?? SOCKET_STATE_CLOSED) !== expectedState && Date.now() < deadline) {
273
- await sleepUnref(25);
274
- }
275
- return (socket.readyState ?? SOCKET_STATE_CLOSED) === expectedState;
276
- }
277
- markClientDisconnected() {
278
- if (!this.client) {
279
- return;
280
- }
281
- Reflect.set(this.client, "connected", false);
282
- Reflect.set(this.client, "registered", false);
283
- Reflect.set(this.client, "reconnecting", false);
284
- }
285
- clearClientSocketReference() {
286
- if (!this.client) {
287
- return;
288
- }
289
- Reflect.set(this.client, "socket", undefined);
290
- }
291
- async cleanupSocket(reason) {
292
- const socket = this.getSocket();
293
- this.markClientDisconnected();
294
- if (!socket) {
295
- this.clearClientSocketReference();
296
- return;
297
- }
298
- socket.removeAllListeners?.();
299
- // ws emits an asynchronous error when close() aborts a CONNECTING socket.
300
- const ignoreCleanupError = () => { };
301
- socket.on("error", ignoreCleanupError);
302
- if ((socket.readyState ?? SOCKET_STATE_CLOSED) !== SOCKET_STATE_CLOSED) {
303
- try {
304
- socket.close?.();
305
- }
306
- catch (err) {
307
- log.logWarn("dingtalk.socket.close_failed", "Socket close failed", {
308
- reason: errorMessage(err),
309
- fields: { during: reason },
310
- });
311
- }
312
- const closed = await this.waitForSocketState(socket, SOCKET_STATE_CLOSED, SOCKET_CLOSE_GRACE_MS);
313
- if (!closed) {
314
- log.logWarn("dingtalk.socket.terminating", "Forcing socket termination", { fields: { during: reason } });
315
- try {
316
- socket.terminate?.();
317
- }
318
- catch (err) {
319
- log.logWarn("dingtalk.socket.terminate_failed", "Socket terminate failed", {
320
- reason: errorMessage(err),
321
- fields: { during: reason },
322
- });
323
- }
324
- await this.waitForSocketState(socket, SOCKET_STATE_CLOSED, SOCKET_TERMINATE_GRACE_MS);
325
- }
326
- }
327
- if ((socket.readyState ?? SOCKET_STATE_CLOSED) === SOCKET_STATE_CLOSED) {
328
- socket.removeListener?.("error", ignoreCleanupError);
329
- }
330
- this.clearClientSocketReference();
331
- }
332
- async connectWithTimeout() {
333
- if (!this.client) {
334
- throw new Error("DingTalk client is not initialized");
335
- }
336
- const connectPromise = Promise.resolve(this.client.connect());
337
- let timeoutHandle = null;
338
- const timeoutPromise = new Promise((_, reject) => {
339
- timeoutHandle = setTimeout(() => {
340
- reject(new Error(`connect timed out after ${CONNECT_ATTEMPT_TIMEOUT_MS}ms`));
341
- }, CONNECT_ATTEMPT_TIMEOUT_MS);
342
- timeoutHandle.unref?.();
343
- });
344
- try {
345
- await Promise.race([connectPromise, timeoutPromise]);
346
- }
347
- finally {
348
- if (timeoutHandle) {
349
- clearTimeout(timeoutHandle);
350
- }
351
- }
352
- const socket = this.getSocket();
353
- if (!socket || socket.readyState !== SOCKET_STATE_OPEN) {
354
- throw new Error("stream socket did not reach open state");
355
- }
356
- }
357
- scheduleReconnect(delayMs, immediate) {
358
- if (this.isStopped) {
359
- return;
360
- }
361
- // An attempt is already in flight; it owns the retry loop and will
362
- // reschedule itself on failure. Scheduling here would be redundant and,
363
- // worse, tear down a just-established socket if the attempt has already
364
- // succeeded by the time this fires.
365
- if (this.isReconnecting) {
366
- return;
367
- }
368
- this.clearReconnectTimer();
369
- this.reconnectTimer = this.setTrackedTimeout(() => {
370
- this.reconnectTimer = null;
371
- this.doReconnect(immediate).catch((err) => {
372
- log.logWarn("dingtalk.reconnect.failed", "Reconnect failed", { reason: errorMessage(err) });
373
- });
374
- }, delayMs);
375
- }
376
- // ==========================================================================
377
- // Public API
378
- // ==========================================================================
379
- async start() {
380
- if (!this.config.clientId || !this.config.clientSecret) {
381
- log.logWarn("dingtalk.config.missing_credentials", "clientId / clientSecret not configured");
382
- return;
383
- }
384
- if (!this.config.cardTemplateId) {
385
- log.logWarn("dingtalk.config.missing_card_template", "cardTemplateId not configured; AI Card streaming is off");
386
- }
387
- log.logEvent("info", "runtime.dingtalk.connecting", "Initializing stream client", {
388
- fields: { clientIdPrefix: this.config.clientId.substring(0, 8) },
389
- });
390
- this.clearAllTimers();
391
- const clientOptions = {
392
- clientId: this.config.clientId,
393
- clientSecret: this.config.clientSecret,
394
- autoReconnect: false,
395
- keepAlive: false,
396
- };
397
- this.client = new DWClient(clientOptions);
398
- this.client.registerCallbackListener(TOPIC_ROBOT, (msg) => {
399
- return this.handleRawMessage(msg);
400
- });
401
- const connected = await this.doReconnect(true); // Initial connection
402
- if (!connected) {
403
- log.logWarn("dingtalk.connect.pending", "Initial stream connection not ready; retrying in background");
404
- }
405
- }
406
- handleRawMessage(msg) {
407
- // 1. Immediate ACK
408
- if (msg.headers?.messageId && this.client) {
409
- this.client.socketCallBackResponse(msg.headers.messageId, { status: "SUCCESS", message: "OK" });
410
- }
411
- // 2. Protocol deduplication
412
- const messageId = msg.headers?.messageId;
413
- if (messageId && !this.markProcessed(messageId)) {
414
- return { status: "SUCCESS", message: "OK" };
415
- }
416
- try {
417
- const parsedData = typeof msg.data === "string" ? JSON.parse(msg.data) : msg.data;
418
- const data = isRecord(parsedData) ? parsedData : {};
419
- // 3. Business logic deduplication
420
- const msgId = data.msgId;
421
- if (msgId && !this.markProcessed(msgId)) {
422
- return { status: "SUCCESS", message: "OK" };
423
- }
424
- // Fire-and-forget processing
425
- this.onStreamMessage(data).catch((err) => {
426
- log.logWarn("dingtalk.handler.failed", "Message handler failed", { reason: errorMessage(err) });
427
- });
428
- }
429
- catch (err) {
430
- log.logWarn("dingtalk.message.parse_failed", "Message parse failed", { reason: errorMessage(err) });
431
- }
432
- return { status: "SUCCESS", message: "OK" };
433
- }
434
- async doReconnect(immediate = false) {
435
- if (this.isReconnecting || this.isStopped || !this.client)
436
- return false;
437
- this.isReconnecting = true;
438
- let connectionFailed = false;
439
- let connected = false;
440
- this.clearReconnectTimer();
441
- this.clearKeepAliveTimer();
442
- if (!immediate && this.reconnectAttempts > 0) {
443
- const delay = Math.min(1000 * 2 ** this.reconnectAttempts + Math.random() * 1000, 30000);
444
- log.logEvent("info", "runtime.dingtalk.reconnect_scheduled", "Reconnect scheduled", {
445
- fields: { delayMs: delay },
446
- });
447
- await this.waitForDelay(delay);
448
- if (this.isStopped || !this.client) {
449
- this.isReconnecting = false;
450
- return false;
451
- }
452
- }
453
- try {
454
- const socket = this.getSocket();
455
- const readyState = socket?.readyState;
456
- if (readyState === SOCKET_STATE_CONNECTING ||
457
- readyState === SOCKET_STATE_OPEN ||
458
- readyState === SOCKET_STATE_CLOSING ||
459
- readyState === SOCKET_STATE_CLOSED) {
460
- await this.cleanupSocket("reconnect");
461
- }
462
- await this.connectWithTimeout();
463
- this.lastSocketAvailableTime = Date.now();
464
- this.reconnectAttempts = 0; // Success, reset backoff
465
- log.logEvent("info", "runtime.dingtalk.stream_connected", "Connected to stream");
466
- if (!this.hasReportedReady) {
467
- log.logConnected();
468
- this.hasReportedReady = true;
469
- }
470
- connected = true;
471
- // Setup keep alive
472
- this.clearKeepAliveTimer();
473
- this.keepAliveTimer = this.setTrackedInterval(() => {
474
- if (this.isStopped)
475
- return;
476
- const elapsed = Date.now() - this.lastSocketAvailableTime;
477
- if (elapsed > 90 * 1000 && !this.activeMessageProcessing) {
478
- // No pong / activity for >90s: the socket is (half-)dead and may
479
- // never emit a close event. Proactively force a reconnect instead
480
- // of waiting indefinitely. scheduleReconnect no-ops if an attempt
481
- // is already in flight or the bot has stopped.
482
- log.logWarn("dingtalk.connection.timeout", "Connection timeout (>90s); forcing reconnect");
483
- this.scheduleReconnect(1000, true);
484
- return;
485
- }
486
- try {
487
- const s = this.getSocket();
488
- if (s?.readyState === 1) {
489
- s.ping?.();
490
- }
491
- }
492
- catch (_err) {
493
- // Ignore
494
- }
495
- }, 30 * 1000);
496
- // Setup native socket events
497
- const s = this.getSocket();
498
- s?.on("pong", () => {
499
- this.lastSocketAvailableTime = Date.now();
500
- });
501
- s?.on("close", (code, reason) => {
502
- log.logWarn("dingtalk.socket.closed", "WebSocket closed", { fields: { code, reason } });
503
- if (this.isStopped)
504
- return;
505
- this.scheduleReconnect(1000, true);
506
- });
507
- s?.on("message", (raw) => {
508
- try {
509
- const msg = JSON.parse(raw);
510
- if (msg.type === "SYSTEM" && msg.headers?.topic === "disconnect") {
511
- log.logWarn("dingtalk.connection.disconnected", "Server sent a disconnect event");
512
- if (!this.isStopped) {
513
- this.doReconnect(true).catch(() => { });
514
- }
515
- }
516
- }
517
- catch (_e) {
518
- // skip
519
- }
520
- });
521
- }
522
- catch (err) {
523
- await this.cleanupSocket("reconnect failure");
524
- this.reconnectAttempts++;
525
- connectionFailed = true;
526
- log.logWarn("dingtalk.connect.failed", "Connection failed", { reason: errorMessage(err) });
527
- }
528
- finally {
529
- this.isReconnecting = false;
530
- }
531
- // Auto-retry on failure with exponential backoff
532
- if (connectionFailed && !this.isStopped) {
533
- this.scheduleReconnect(0, false);
534
- }
535
- return connected;
536
- }
537
- async stop() {
538
- log.logInfoEvent("dingtalk.bot.stopping", "Stopping bot");
539
- this.isStopped = true;
540
- this.clearAllTimers();
541
- if (this.channelCacheSweepTimer) {
542
- clearInterval(this.channelCacheSweepTimer);
543
- this.channelCacheSweepTimer = null;
544
- }
545
- for (const queue of this.queues.values()) {
546
- queue.stop();
547
- }
548
- if (this.client) {
549
- try {
550
- await this.cleanupSocket("stop");
551
- }
552
- catch (err) {
553
- log.logWarn("dingtalk.disconnect.failed", "Clean disconnect failed", { reason: errorMessage(err) });
554
- }
555
- finally {
556
- this.client = null;
557
- }
558
- }
559
- }
560
- /**
561
- * Enqueue an event for processing.
562
- * Returns true if enqueued, false if queue is full (max 5).
563
- */
564
- enqueueEvent(event) {
565
- if (this.isStopped) {
566
- return false;
567
- }
568
- const queue = this.getQueue(event.channelId);
569
- if (queue.size() >= EVENT_QUEUE_LIMIT) {
570
- log.logEvent("warn", "runtime.channel_queue.full", "Discarding incoming event", {
571
- ctx: { channelId: event.channelId, userName: event.userName },
572
- fields: { messageLength: event.text.length },
573
- });
574
- return false;
575
- }
576
- log.logEvent("debug", "runtime.channel_queue.enqueued", "Incoming event queued", {
577
- ctx: { channelId: event.channelId, userName: event.userName },
578
- fields: { messageLength: event.text.length },
579
- });
580
- queue.enqueue(async () => {
581
- this.activeMessageProcessing = true;
582
- try {
583
- this.handler.reserveEvent?.(event);
584
- await this.handler.handleEvent(event, this, true);
585
- }
586
- finally {
587
- this.activeMessageProcessing = false;
588
- this.lastSocketAvailableTime = Date.now();
589
- }
590
- });
591
- return true;
592
- }
593
- enqueueStreamMessage(event, textOverride) {
594
- const queuedEvent = textOverride === undefined ? event : { ...event, text: textOverride };
595
- const queue = this.getQueue(event.channelId);
596
- if (queue.size() >= USER_MESSAGE_QUEUE_LIMIT) {
597
- log.logWarn("dingtalk.queue.full", "Message discarded: channel queue full", {
598
- channelId: event.channelId,
599
- fields: { limit: USER_MESSAGE_QUEUE_LIMIT, preview: queuedEvent.text.substring(0, 50) },
600
- });
601
- this.sendPlain(event.channelId, `⚠️ 消息积压过多(超过 ${USER_MESSAGE_QUEUE_LIMIT} 条待处理),本条消息已丢弃,请稍后重试。`).catch(() => undefined);
602
- return;
603
- }
604
- queue.enqueue(async () => {
605
- this.activeMessageProcessing = true;
606
- try {
607
- this.handler.reserveEvent?.(queuedEvent);
608
- await this.handler.handleEvent(queuedEvent, this);
609
- }
610
- finally {
611
- this.activeMessageProcessing = false;
612
- this.lastSocketAvailableTime = Date.now();
613
- }
614
- });
615
- }
616
- // ==========================================================================
617
- // AI Card operations
618
- // ==========================================================================
619
- /** Capture the current turn's identity; close, /stop and /new invalidate it. */
620
- getCardGeneration(channelId) {
621
- let generation = this.cardGenerations.get(channelId);
622
- if (!generation) {
623
- generation = Symbol(channelId);
624
- this.cardGenerations.set(channelId, generation);
625
- }
626
- return generation;
627
- }
628
- isCardGenerationCurrent(channelId, generation) {
629
- return this.cardGenerations.get(channelId) === generation;
630
- }
631
- /** Get or create an AI card without joining an earlier turn's in-flight creation. */
632
- async ensureCard(channelId, generation = this.getCardGeneration(channelId)) {
633
- if (!this.config.cardTemplateId || !this.isCardGenerationCurrent(channelId, generation))
634
- return;
635
- const existing = this.activeCards.get(channelId);
636
- if (existing && !existing.finished)
637
- return;
638
- await this.createCard(channelId, generation);
639
- }
640
- /**
641
- * Replace the active card content with a full snapshot.
642
- */
643
- async replaceCard(channelId, content, finalize = false, failed = false, generation = this.getCardGeneration(channelId)) {
644
- return this.writeCard(channelId, content, { append: false, finalize, failed }, generation);
645
- }
646
- /**
647
- * Append a delta to the active card transcript.
648
- */
649
- async appendToCard(channelId, content, finalize = false, failed = false, generation = this.getCardGeneration(channelId)) {
650
- return this.writeCard(channelId, content, { append: true, finalize, failed }, generation);
651
- }
652
- /**
653
- * Shared body of `replaceCard`/`appendToCard`: whether to open a fresh card differs between the
654
- * two (a full-snapshot replace opens one for a finalize/failed close too; a delta append only
655
- * opens one for genuinely new content), so that predicate stays keyed on `append` rather than
656
- * being collapsed away — everything after it (stream, then drop the card on finalize/failed/a
657
- * failed stream) is identical either way.
658
- */
659
- async writeCard(channelId, content, options, generation) {
660
- if (!this.isCardGenerationCurrent(channelId, generation))
661
- return false;
662
- const { append, finalize, failed } = options;
663
- if (append && !content && !finalize && !failed) {
664
- return true;
665
- }
666
- let card = this.activeCards.get(channelId);
667
- const shouldEnsure = append
668
- ? !finalize && !failed && content.trim().length > 0
669
- : content.trim().length > 0 || !finalize || failed;
670
- if ((!card || card.finished) && this.config.cardTemplateId && shouldEnsure) {
671
- await this.ensureCard(channelId, generation);
672
- if (!this.isCardGenerationCurrent(channelId, generation))
673
- return false;
674
- card = this.activeCards.get(channelId);
675
- }
676
- if (!card || card.finished) {
677
- return false;
678
- }
679
- // Never erase a visible card, including callers finishing with no new text.
680
- const snapshot = !append && !content.trim() ? card.content || "处理已结束。" : content;
681
- const streamed = await this.streamCard(card, snapshot, { append, finalize, failed });
682
- if (streamed && (finalize || failed) && this.activeCards.get(channelId) === card) {
683
- this.activeCards.delete(channelId);
684
- }
685
- return streamed;
686
- }
687
- /**
688
- * Finalize and remove the active card for a channel.
689
- */
690
- async finalizeCard(channelId, content, generation = this.getCardGeneration(channelId)) {
691
- if (!content.trim() || !this.isCardGenerationCurrent(channelId, generation))
692
- return false;
693
- const finalized = await this.replaceCard(channelId, content, true, false, generation);
694
- if (!finalized && this.isCardGenerationCurrent(channelId, generation)) {
695
- return this.sendPlain(channelId, content);
696
- }
697
- return finalized;
698
- }
699
- /** Finish progress only: never create a card or send a fallback chat message. */
700
- async finalizeExistingCard(channelId, content, generation = this.getCardGeneration(channelId)) {
701
- if (!this.isCardGenerationCurrent(channelId, generation) || !this.activeCards.has(channelId))
702
- return false;
703
- return this.replaceCard(channelId, content, true, false, generation);
704
- }
705
- /** Invalidate this turn's local state. This is not a remote message deletion. */
706
- discardCard(channelId, generation = this.cardGenerations.get(channelId)) {
707
- if (!generation || !this.isCardGenerationCurrent(channelId, generation))
708
- return;
709
- this.cardGenerations.delete(channelId);
710
- this.cardCreationAttempted.delete(generation);
711
- const card = this.activeCards.get(channelId);
712
- this.activeCards.delete(channelId);
713
- // /stop and /new may invalidate a turn before its controller gets to finish.
714
- if (card && !card.finished) {
715
- void this.streamCard(card, `${card.content || "正在处理…"}\n\n处理已结束。`, {
716
- append: false,
717
- finalize: true,
718
- failed: false,
719
- });
720
- }
721
- }
722
- /**
723
- * Send a normal message natively mapping DM and Group to correct endpoints (fallback when no card).
724
- *
725
- * Only the message shape is decided here; the DM-vs-group routing and the POST itself belong to
726
- * `sendRobotMessage`, which every other outbound message type already goes through.
727
- *
728
- * `opts` lets a caller that already knows what it produced (a command reply) state the format
729
- * and a real title instead of the regex guess below, which exists only for callers — free-form
730
- * notices, `replaceWithFinal` — that do not know their own content ahead of time (review
731
- * 2026-08-24 §1.3c).
732
- */
733
- async sendPlain(channelId, text, opts) {
734
- const meta = this.getConversationMeta(channelId);
735
- if (!meta) {
736
- log.logWarn("dingtalk.send.no_metadata", "Plain message not sent: no conversation metadata", {
737
- channelId: channelId,
738
- });
739
- return false;
740
- }
741
- const hasMarkdown = opts?.markdown ?? /^#{1,6}\s|^\s*[-*]\s|\*\*.*\*\*|```|`[^`]+`|\[.*?\]\(.*?\)/m.test(text);
742
- const title = opts?.title ?? "Bot";
743
- const msgKey = hasMarkdown ? "sampleMarkdown" : "sampleText";
744
- const msgParam = hasMarkdown ? JSON.stringify({ text, title }) : JSON.stringify({ content: text });
745
- return this.sendRobotMessage(meta, msgKey, msgParam);
746
- }
747
- // ==========================================================================
748
- // Media (image / file) delivery — MediaSender contract
749
- // ==========================================================================
750
- /**
751
- * Deliver a local file to a channel as a native attachment. Uploads the bytes
752
- * to get a `media_id`, then sends a `sampleImageMsg` (inline image) or
753
- * `sampleFile` (downloadable file) robot message. `channelId` is supplied by
754
- * the runtime (the tool is bound to its channel at build time), never by the
755
- * model, so an agent cannot target a channel other than its own.
756
- */
757
- async sendMedia(channelId, media) {
758
- const isImage = media.kind === "image";
759
- const limit = isImage ? MAX_IMAGE_BYTES : MAX_FILE_BYTES;
760
- if (media.data.length > limit) {
761
- return {
762
- ok: false,
763
- error: `File is ${(media.data.length / 1024 / 1024).toFixed(1)}MB, exceeds the ${limit / 1024 / 1024}MB DingTalk limit for ${media.kind} messages.`,
764
- };
765
- }
766
- const fileType = extractFileExtension(media.fileName);
767
- if (!isImage && !SUPPORTED_FILE_TYPES.has(fileType)) {
768
- return {
769
- ok: false,
770
- error: `DingTalk file messages do not support the "${fileType || "(none)"}" type. Supported: ${[...SUPPORTED_FILE_TYPES].join(", ")}.`,
771
- };
772
- }
773
- const meta = this.getConversationMeta(channelId);
774
- if (!meta) {
775
- return { ok: false, error: "No conversation is known for this channel yet; cannot deliver a file." };
776
- }
777
- const mediaId = await this.uploadMedia(isImage ? "image" : "file", media.data, media.fileName);
778
- if (!mediaId) {
779
- return { ok: false, error: "Failed to upload the file to DingTalk (see server logs)." };
780
- }
781
- const { msgKey, msgParam } = isImage
782
- ? { msgKey: "sampleImageMsg", msgParam: JSON.stringify({ photoURL: mediaId }) }
783
- : {
784
- msgKey: "sampleFile",
785
- msgParam: JSON.stringify({ mediaId, fileName: media.fileName, fileType }),
786
- };
787
- const sent = await this.sendRobotMessage(meta, msgKey, msgParam);
788
- return sent ? { ok: true } : { ok: false, error: "DingTalk rejected the file message (see server logs)." };
789
- }
790
- /**
791
- * Upload raw bytes to DingTalk and return the reusable `media_id`, or null on
792
- * failure. The upload endpoint lives on the legacy oapi host and answers 200
793
- * with a non-zero `errcode` on failure, so the body is inspected explicitly.
794
- */
795
- async uploadMedia(type, data, fileName) {
796
- const token = await this.getAccessToken();
797
- if (!token)
798
- return null;
799
- const form = new FormData();
800
- form.append("media", new Blob([new Uint8Array(data)]), fileName);
801
- try {
802
- const resp = await http.post(`${DINGTALK_OAPI}/media/upload?access_token=${encodeURIComponent(token)}&type=${type}`, form,
803
- // Override the 15s default: a multi-MB upload over a slow link can take
804
- // longer, and unlike card streaming this call is not on the delivery loop.
805
- { timeout: MEDIA_UPLOAD_TIMEOUT_MS });
806
- const body = isRecord(resp.data) ? resp.data : {};
807
- if (body.errcode && body.errcode !== 0) {
808
- log.logWarn("dingtalk.media.upload_failed", "Media upload failed", {
809
- reason: String(body.errmsg ?? ""),
810
- fields: { errcode: body.errcode },
811
- });
812
- return null;
813
- }
814
- const mediaId = typeof body.media_id === "string" ? body.media_id : null;
815
- if (!mediaId) {
816
- log.logWarn("dingtalk.media.upload_failed", "Media upload returned no media_id", {
817
- reason: JSON.stringify(body),
818
- });
819
- }
820
- return mediaId;
821
- }
822
- catch (err) {
823
- if (axios.isAxiosError(err) && err.response) {
824
- log.logWarn("dingtalk.media.upload_failed", "Media upload failed", {
825
- reason: JSON.stringify(err.response.data),
826
- fields: { status: err.response.status },
827
- });
828
- }
829
- else {
830
- log.logWarn("dingtalk.media.upload_failed", "Media upload failed", { reason: errorMessage(err) });
831
- }
832
- return null;
833
- }
834
- }
835
- /**
836
- * Two-step DingTalk inbound file download (spec 049): `messageFiles/download` exchanges the
837
- * message's `downloadCode` for a short-lived `downloadUrl`, then that URL is fetched for the
838
- * actual bytes. Both hops reuse `getAccessToken()` — the same app access token works across
839
- * DingTalk's hosts, as the comment on `DINGTALK_OAPI` above explains for the outbound side.
840
- *
841
- * This runs from `onStreamMessage`'s per-channel ingestion queue, never from inside a turn: a
842
- * busy channel can queue a message for minutes (`USER_MESSAGE_QUEUE_LIMIT`), and by the time a
843
- * queued turn actually ran, a `downloadCode`/`downloadUrl` fetched only then could easily have
844
- * already expired.
845
- *
846
- * `protected` so the deterministic e2e harness can override it and run this path with zero
847
- * network, the same pattern `HarnessDingTalkBot` already uses for outbound calls.
848
- */
849
- async downloadMessageFile(downloadCode) {
850
- const token = await this.getAccessToken();
851
- if (!token)
852
- return null;
853
- const robotCode = this.config.robotCode || this.config.clientId;
854
- try {
855
- const downloadUrlResp = await http.post(`${DINGTALK_API}/v1.0/robot/messageFiles/download`, { robotCode, downloadCode }, { headers: { "x-acs-dingtalk-access-token": token } });
856
- const downloadUrl = isRecord(downloadUrlResp.data) ? downloadUrlResp.data.downloadUrl : undefined;
857
- if (typeof downloadUrl !== "string" || !downloadUrl) {
858
- log.logWarn("dingtalk.file.download_failed", "Inbound file download returned no downloadUrl", {
859
- reason: JSON.stringify(downloadUrlResp.data),
860
- });
861
- return null;
862
- }
863
- const fileResp = await http.get(downloadUrl, {
864
- responseType: "arraybuffer",
865
- // Reject an oversized body before it fully lands in memory rather than after.
866
- maxContentLength: MAX_INBOUND_IMAGE_BYTES,
867
- timeout: MEDIA_DOWNLOAD_TIMEOUT_MS,
868
- });
869
- return { data: Buffer.from(fileResp.data) };
870
- }
871
- catch (err) {
872
- if (axios.isAxiosError(err) && err.response) {
873
- log.logWarn("dingtalk.file.download_failed", "Inbound file download failed", {
874
- reason: JSON.stringify(err.response.data),
875
- fields: { status: err.response.status },
876
- });
877
- }
878
- else {
879
- log.logWarn("dingtalk.file.download_failed", "Inbound file download failed", { reason: errorMessage(err) });
880
- }
881
- return null;
882
- }
883
- }
884
- /**
885
- * Resolve one parsed message's image credentials into persisted `InboundImage`s and a text
886
- * with every `[图片N]` marker either left as-is (success) or replaced with a reason (spec 049
887
- * D8): a download failure, an unrecognized format, an oversized file, or a message that
888
- * simply carried more images than `MAX_INBOUND_IMAGES_PER_MESSAGE` allows. A failure on one
889
- * image never drops the rest of the message — only that one marker changes.
890
- *
891
- * No-op (no network call at all) when the message carries no image credentials, so a plain
892
- * text message never pays for this method's existence.
893
- */
894
- async resolveInboundAttachments(channelId, parsed) {
895
- if (parsed.downloadCodes.length === 0) {
896
- return { text: parsed.text, images: [] };
897
- }
898
- let text = parsed.text;
899
- const images = [];
900
- const replaceMarker = (index, replacement) => {
901
- text = text.replace(`[图片${index + 1}]`, replacement);
902
- };
903
- await Promise.all(parsed.downloadCodes.map(async (downloadCode, index) => {
904
- const marker = index + 1;
905
- if (index >= MAX_INBOUND_IMAGES_PER_MESSAGE) {
906
- replaceMarker(index, `[图片${marker}:超出单条消息图片数量上限,已丢弃]`);
907
- return;
908
- }
909
- const downloaded = await this.downloadMessageFile(downloadCode);
910
- if (!downloaded) {
911
- replaceMarker(index, `[图片${marker}:接收失败]`);
912
- return;
913
- }
914
- if (downloaded.data.byteLength > MAX_INBOUND_IMAGE_BYTES) {
915
- replaceMarker(index, `[图片${marker}:文件过大(${formatSize(downloaded.data.byteLength)}),已丢弃]`);
916
- return;
917
- }
918
- const mimeType = sniffImageMimeType(downloaded.data);
919
- const persisted = await this.handler.persistInboundImage?.(channelId, {
920
- data: downloaded.data,
921
- mimeType,
922
- });
923
- if (!persisted) {
924
- replaceMarker(index, `[图片${marker}:保存失败]`);
925
- return;
926
- }
927
- if (!mimeType) {
928
- // Persisted for the record, but never handed to a model — see the handler
929
- // contract's doc comment on `persistInboundImage`.
930
- replaceMarker(index, `[图片${marker}:格式不支持,已保存]`);
931
- }
932
- images[index] = persisted;
933
- }));
934
- return { text, images: images.filter((image) => image !== undefined) };
935
- }
936
- /**
937
- * POST a robot message with an arbitrary msgKey/msgParam, routing DM vs group
938
- * to the correct endpoint. The single outbound path for every non-card message:
939
- * plain text/markdown, images, and files.
940
- */
941
- async sendRobotMessage(meta, msgKey, msgParam) {
942
- const token = await this.getAccessToken();
943
- if (!token)
944
- return false;
945
- const robotCode = this.config.robotCode || this.config.clientId;
946
- const isGroup = meta.conversationType === "2";
947
- const url = isGroup
948
- ? `${DINGTALK_API}/v1.0/robot/groupMessages/send`
949
- : `${DINGTALK_API}/v1.0/robot/oToMessages/batchSend`;
950
- const body = { robotCode, msgKey, msgParam };
951
- if (isGroup) {
952
- body.openConversationId = meta.conversationId;
953
- }
954
- else {
955
- body.userIds = [meta.senderId];
956
- }
957
- try {
958
- await http.post(url, body, {
959
- headers: {
960
- "x-acs-dingtalk-access-token": token,
961
- "Content-Type": "application/json",
962
- },
963
- });
964
- return true;
965
- }
966
- catch (err) {
967
- if (axios.isAxiosError(err) && err.response) {
968
- log.logWarn("dingtalk.send.failed", "Message send failed", {
969
- reason: JSON.stringify(err.response.data),
970
- fields: { msgKey, status: err.response.status },
971
- });
972
- }
973
- else {
974
- log.logWarn("dingtalk.send.failed", "Message send failed", {
975
- reason: errorMessage(err),
976
- fields: { msgKey },
977
- });
978
- }
979
- return false;
980
- }
981
- }
982
- // ==========================================================================
983
- // Private - AI Card implementation
984
- // ==========================================================================
985
- async createCard(channelId, generation) {
986
- // Re-check under the singleflight: a concurrent caller may have already
987
- // created the card while we awaited, so avoid a duplicate create.
988
- const existing = this.activeCards.get(channelId);
989
- if (existing && !existing.finished) {
990
- return existing;
991
- }
992
- const inFlight = this.cardCreationInFlight.get(channelId);
993
- if (inFlight?.generation === generation) {
994
- return inFlight.promise;
995
- }
996
- // A failed create may already have reached DingTalk. Never mint another ID in this turn.
997
- if (this.cardCreationAttempted.has(generation))
998
- return null;
999
- this.cardCreationAttempted.add(generation);
1000
- const creation = this.createCardUncached(channelId, generation).finally(() => {
1001
- if (this.cardCreationInFlight.get(channelId)?.generation === generation) {
1002
- this.cardCreationInFlight.delete(channelId);
1003
- }
1004
- });
1005
- this.cardCreationInFlight.set(channelId, { generation, promise: creation });
1006
- return creation;
1007
- }
1008
- async createCardUncached(channelId, generation) {
1009
- const token = await this.getAccessToken();
1010
- if (!token || !this.isCardGenerationCurrent(channelId, generation))
1011
- return null;
1012
- const meta = this.getConversationMeta(channelId);
1013
- if (!meta) {
1014
- log.logWarn("dingtalk.card.no_metadata", "Card not created: no conversation metadata", {
1015
- channelId: channelId,
1016
- });
1017
- return null;
1018
- }
1019
- const isGroup = meta.conversationType === "2";
1020
- const instanceId = `card_${Date.now()}_${Math.random().toString(36).substring(2, 8)}`;
1021
- const robotCode = this.config.robotCode || this.config.clientId;
1022
- // openSpaceId format:
1023
- // 群聊: dtv1.card//IM_GROUP.{openConversationId}
1024
- // 单聊: dtv1.card//IM_ROBOT.{userId}
1025
- const openSpaceId = isGroup
1026
- ? `dtv1.card//IM_GROUP.${meta.conversationId}`
1027
- : `dtv1.card//IM_ROBOT.${meta.senderId}`;
1028
- const body = {
1029
- cardTemplateId: this.config.cardTemplateId,
1030
- outTrackId: instanceId,
1031
- cardData: {
1032
- cardParamMap: {
1033
- [this.config.cardTemplateKey || "content"]: "正在处理…",
1034
- sys_full_json_obj: JSON.stringify({
1035
- config: {
1036
- autoLayout: this.config.cardAutoLayout ?? true,
1037
- },
1038
- }),
1039
- },
1040
- },
1041
- callbackType: "STREAM",
1042
- imGroupOpenSpaceModel: { supportForward: true },
1043
- imRobotOpenSpaceModel: { supportForward: true },
1044
- openSpaceId,
1045
- userIdType: 1,
1046
- };
1047
- if (isGroup) {
1048
- body.imGroupOpenDeliverModel = { robotCode };
1049
- }
1050
- else {
1051
- body.imRobotOpenDeliverModel = { spaceType: "IM_ROBOT" };
1052
- }
1053
- try {
1054
- await http.post(`${DINGTALK_API}/v1.0/card/instances/createAndDeliver`, body, {
1055
- headers: {
1056
- "x-acs-dingtalk-access-token": token,
1057
- "Content-Type": "application/json",
1058
- },
1059
- });
1060
- }
1061
- catch (err) {
1062
- if (axios.isAxiosError(err) && err.response) {
1063
- log.logWarn("dingtalk.card.create_failed", "Card create failed", {
1064
- reason: JSON.stringify(err.response.data),
1065
- fields: { status: err.response.status },
1066
- });
1067
- }
1068
- else {
1069
- log.logWarn("dingtalk.card.create_failed", "Card create failed", { reason: errorMessage(err) });
1070
- }
1071
- return null;
1072
- }
1073
- const card = {
1074
- instanceId,
1075
- conversationId: meta.conversationId,
1076
- accessToken: token,
1077
- templateKey: this.config.cardTemplateKey || "content",
1078
- createdAt: Date.now() / 1000,
1079
- lastUpdated: Date.now() / 1000,
1080
- content: "正在处理…",
1081
- finished: false,
1082
- };
1083
- if (!this.isCardGenerationCurrent(channelId, generation)) {
1084
- await this.streamCard(card, "处理已结束。", { append: false, finalize: true, failed: false });
1085
- return null;
1086
- }
1087
- this.activeCards.set(channelId, card);
1088
- return card;
1089
- }
1090
- async streamCard(card, content, options) {
1091
- // A stop/new-session close can arrive while the prior HTTP write is in flight.
1092
- // Order writes by instance so that close remains the last update to the old card.
1093
- const pending = (card.pendingWrite ?? Promise.resolve(true))
1094
- .then(async () => {
1095
- if (card.finished)
1096
- return false;
1097
- return this.streamCardRequest(card, content, options);
1098
- })
1099
- .catch((error) => {
1100
- log.logWarn("dingtalk.card.stream_failed", "Card streaming failed", { reason: errorMessage(error) });
1101
- return false;
1102
- });
1103
- card.pendingWrite = pending;
1104
- return pending;
1105
- }
1106
- async streamCardRequest(card, content, options) {
1107
- // Refresh token if needed
1108
- const ageSecs = Date.now() / 1000 - card.createdAt;
1109
- if (ageSecs > TOKEN_REFRESH_SECS) {
1110
- const token = await this.getAccessToken();
1111
- if (token) {
1112
- card.accessToken = token;
1113
- }
1114
- }
1115
- const body = {
1116
- outTrackId: card.instanceId,
1117
- guid: `${Date.now()}_${Math.random().toString(36).substring(2, 8)}`,
1118
- key: card.templateKey,
1119
- content,
1120
- append: options.append,
1121
- finished: options.finalize,
1122
- failed: options.failed,
1123
- isFull: !options.append,
1124
- isFinalize: options.finalize,
1125
- isError: options.failed,
1126
- };
1127
- const start = Date.now();
1128
- try {
1129
- await http.put(`${DINGTALK_API}/v1.0/card/streaming`, body, {
1130
- headers: {
1131
- "x-acs-dingtalk-access-token": card.accessToken,
1132
- "Content-Type": "application/json",
1133
- },
1134
- });
1135
- const duration = Date.now() - start;
1136
- if (duration > 1000) {
1137
- log.logWarn("dingtalk.card.stream_slow", "Card streaming request slow", {
1138
- fields: { durationMs: duration },
1139
- });
1140
- }
1141
- card.lastUpdated = Date.now() / 1000;
1142
- card.content = options.append ? `${card.content}${content}` : content;
1143
- if (options.finalize || options.failed) {
1144
- card.finished = true;
1145
- }
1146
- return true;
1147
- }
1148
- catch (err) {
1149
- if (axios.isAxiosError(err) && err.response) {
1150
- log.logWarn("dingtalk.card.stream_failed", "Card streaming failed", {
1151
- reason: JSON.stringify(err.response.data),
1152
- fields: { status: err.response.status },
1153
- });
1154
- }
1155
- else {
1156
- log.logWarn("dingtalk.card.stream_failed", "Card streaming failed", { reason: errorMessage(err) });
1157
- }
1158
- return false;
1159
- }
1160
- }
1161
- // ==========================================================================
1162
- // Private - Access Token
1163
- // ==========================================================================
1164
- async getAccessToken() {
1165
- if (this.accessToken && Date.now() / 1000 < this.tokenExpiry) {
1166
- return this.accessToken;
1167
- }
1168
- // Coalesce concurrent refresh requests into a single HTTP call
1169
- if (!this.tokenRefreshPromise) {
1170
- this.tokenRefreshPromise = this.refreshAccessToken().finally(() => {
1171
- this.tokenRefreshPromise = null;
1172
- });
1173
- }
1174
- return this.tokenRefreshPromise;
1175
- }
1176
- async refreshAccessToken() {
1177
- try {
1178
- const resp = await http.post(`${DINGTALK_API}/v1.0/oauth2/accessToken`, {
1179
- appKey: this.config.clientId,
1180
- appSecret: this.config.clientSecret,
1181
- }, {
1182
- headers: { "Content-Type": "application/json" },
1183
- });
1184
- const data = resp.data;
1185
- this.accessToken = data.accessToken || null;
1186
- this.tokenExpiry = Date.now() / 1000 + (data.expireIn || 7200) - 60;
1187
- return this.accessToken;
1188
- }
1189
- catch (err) {
1190
- if (axios.isAxiosError(err) && err.response) {
1191
- log.logWarn("dingtalk.token.failed", "Access token request failed", {
1192
- reason: JSON.stringify(err.response.data),
1193
- fields: { status: err.response.status },
1194
- });
1195
- }
1196
- else {
1197
- log.logWarn("dingtalk.token.failed", "Access token request failed", { reason: errorMessage(err) });
1198
- }
1199
- return null;
1200
- }
1201
- }
1202
- // ==========================================================================
1203
- // Private - Message handling
1204
- // ==========================================================================
1205
- async onStreamMessage(data) {
1206
- if (this.isStopped) {
1207
- return;
1208
- }
1209
- const parsed = parseInboundMessage(data);
1210
- const senderId = data.senderStaffId || data.senderId || "";
1211
- const senderName = data.senderNick || "Unknown";
1212
- const conversationId = data.conversationId || "";
1213
- const conversationType = data.conversationType || "1";
1214
- if (!parsed.text && parsed.downloadCodes.length === 0) {
1215
- const msgtype = typeof data.msgtype === "string" ? data.msgtype : "unknown";
1216
- log.logWarn("dingtalk.message.empty", "Empty message ignored", { fields: { msgtype } });
1217
- return;
1218
- }
1219
- if (this.config.allowFrom && this.config.allowFrom.length > 0) {
1220
- if (!this.config.allowFrom.includes(senderId)) {
1221
- log.logWarn("dingtalk.message.unauthorized", "Message from unauthorized user ignored", {
1222
- fields: { senderName, senderId },
1223
- });
1224
- return;
1225
- }
1226
- }
1227
- // Determine channel ID
1228
- const channelId = conversationType === "2" ? `group_${conversationId}` : `dm_${senderId}`;
1229
- // Parsing above is free; resolving image attachments below is a real network round-trip.
1230
- // Serialize the whole "resolve attachments → build event → route" unit per channel (spec
1231
- // 049 D3): without this, a message needing a download can be overtaken, in delivery order,
1232
- // by a later download-free message on the same channel — nothing upstream of
1233
- // `enqueueStreamMessage` otherwise waits on anything asynchronous.
1234
- this.pendingInboundIngestCount++;
1235
- try {
1236
- await this.inboundIngestQueue.run(channelId, async () => {
1237
- const { text: content, images } = await this.resolveInboundAttachments(channelId, parsed);
1238
- log.logEvent("info", "runtime.dingtalk.message_received", "Accepted incoming message", {
1239
- ctx: { channelId, userName: senderName },
1240
- fields: { messageType: conversationType === "2" ? "group" : "dm", messageLength: content.length },
1241
- });
1242
- // A group carries its title on every message; a DM has none, so the peer's nickname
1243
- // is the only human-readable handle that channel will ever have.
1244
- const conversationTitle = typeof data.conversationTitle === "string" ? data.conversationTitle.trim() : "";
1245
- const channelName = (conversationType === "2" ? conversationTitle : senderName) || undefined;
1246
- // Cache conversation metadata for card creation
1247
- this.setConversationMeta(channelId, {
1248
- conversationId,
1249
- conversationType,
1250
- senderId,
1251
- });
1252
- // The one place a real person's message is seen before command/busy routing splits
1253
- // the path, so the channel index counts every human message and no synthetic wake.
1254
- this.handler.noteChannelActivity?.({ channelId, name: channelName, at: Date.now() });
1255
- // Build event
1256
- const event = {
1257
- type: conversationType === "2" ? "group" : "dm",
1258
- channelId,
1259
- ts: Date.now().toString(),
1260
- user: senderId,
1261
- userName: senderName,
1262
- text: content,
1263
- conversationId,
1264
- conversationType,
1265
- ...(channelName ? { channelName } : {}),
1266
- ...(images.length > 0 ? { images } : {}),
1267
- };
1268
- await this.routeInboundEvent(event);
1269
- });
1270
- }
1271
- finally {
1272
- this.pendingInboundIngestCount--;
1273
- }
1274
- }
1275
- /**
1276
- * Command / busy / `/new` routing for one inbound event, ending in `enqueueStreamMessage`
1277
- * for a normal message. Split out of `onStreamMessage` so the deterministic e2e harness
1278
- * (spec 048) can exercise the real transport queue and busy semantics without a socket.
1279
- */
1280
- async routeInboundEvent(event) {
1281
- const { channelId } = event;
1282
- const content = event.text;
1283
- const builtInCommand = parseBuiltInCommand(content);
1284
- const isSlashCommand = content.trim().startsWith("/");
1285
- // `/new` is an emergency boundary as well as a session command. Route it before
1286
- // busy checking and before the old channel queue, so a wedged compaction/provider
1287
- // request cannot prevent recovery.
1288
- if (slashCommandName(content) === "new") {
1289
- await this.handler.handleNewSession(event, this);
1290
- return;
1291
- }
1292
- // Check if busy
1293
- if (this.handler.isRunning(channelId)) {
1294
- // All built-in transport commands are usable while a task streams.
1295
- if (builtInCommand) {
1296
- switch (builtInCommand.name) {
1297
- case "help":
1298
- await this.sendPlain(channelId, renderBuiltInHelp(builtInCommand.args), {
1299
- title: "/help",
1300
- markdown: true,
1301
- });
1302
- return;
1303
- case "stop": {
1304
- const outcome = await this.handler.handleStop(channelId, this);
1305
- await this.sendPlain(channelId, outcome.pausedTaskId
1306
- ? `已停止当前回合。任务 \`${outcome.pausedTaskId}\` 已暂停,用 \`/tasks resume ${outcome.pausedTaskId}\` 继续。`
1307
- : "已停止当前回合。", { title: "/stop", markdown: true });
1308
- return;
1309
- }
1310
- case "steer":
1311
- case "followup": {
1312
- const mode = builtInCommand.name === "steer" ? "steer" : "followUp";
1313
- const result = await this.handler.handleBusyMessage(event, this, mode, builtInCommand.args);
1314
- if (result.kind === "requeue") {
1315
- this.enqueueStreamMessage(event, result.text);
1316
- }
1317
- return;
1318
- }
1319
- default: {
1320
- // Every remaining BuiltInCommandName is a stateless report (events/tasks/status/usage/
1321
- // context/subagents/project), narrowed to RuntimeCommandName by TS after the four
1322
- // cases above. Busy has no sendCommandReply-style retry semantics, so `/context` is
1323
- // answered here like the rest instead of the runner-handled path idle uses for it
1324
- // (see the IDLE_RUNTIME_COMMAND_NAMES comment in bootstrap.ts).
1325
- const response = await this.handler.runRuntimeCommand(event, builtInCommand.name, builtInCommand.args);
1326
- const delivered = await this.sendPlain(channelId, response, {
1327
- title: `/${builtInCommand.name}`,
1328
- markdown: true,
1329
- });
1330
- if (!delivered) {
1331
- log.logWarn("delivery.command_reply.failed", "Command reply delivery failed", {
1332
- channelId: channelId,
1333
- fields: { command: builtInCommand.name, chars: response.length },
1334
- });
1335
- }
1336
- return;
1337
- }
1338
- }
1339
- }
1340
- // Other session commands (/model, /compact, …) and unknown slash commands cannot
1341
- // run mid-turn: they would need the idle session layer.
1342
- if (isSlashCommand) {
1343
- await this.sendPlain(channelId, formatBusyHint());
1344
- return;
1345
- }
1346
- const result = await this.handler.handleBusyMessage(event, this, this.busyMessageDefault, content);
1347
- if (result.kind === "requeue") {
1348
- this.enqueueStreamMessage(event, result.text);
1349
- }
1350
- return;
1351
- }
1352
- // Enqueue for processing
1353
- this.enqueueStreamMessage(event);
1354
- }
1355
- /**
1356
- * Drop queued-but-not-started messages for a channel (e.g. on /stop) so they
1357
- * do not run after the user halts the current task. Returns dropped count.
1358
- */
1359
- clearPendingMessages(channelId) {
1360
- const queue = this.queues.get(channelId);
1361
- return queue ? queue.clearPending() : 0;
1362
- }
1363
- /**
1364
- * Detach all queued work from the previous session generation. The in-flight callback may
1365
- * still unwind on its old queue object, while subsequent messages get a fresh queue.
1366
- */
1367
- resetChannelQueue(channelId) {
1368
- const queue = this.queues.get(channelId);
1369
- const dropped = queue?.clearPending() ?? 0;
1370
- queue?.stop();
1371
- this.queues.delete(channelId);
1372
- this.discardCard(channelId);
1373
- return dropped;
1374
- }
1375
- /** Test seam (spec 048): true when no channel queue has pending or in-flight work. */
1376
- allChannelQueuesIdle() {
1377
- if (this.pendingInboundIngestCount > 0)
1378
- return false;
1379
- for (const queue of this.queues.values()) {
1380
- if (!queue.isIdle())
1381
- return false;
1382
- }
1383
- return true;
1384
- }
1385
- getQueue(channelId) {
1386
- this.touchChannel(channelId);
1387
- let queue = this.queues.get(channelId);
1388
- if (!queue) {
1389
- queue = new ChannelQueue();
1390
- this.queues.set(channelId, queue);
1391
- }
1392
- return queue;
1393
- }
1394
- getConversationMeta(channelId) {
1395
- this.touchChannel(channelId);
1396
- const cached = this.convMeta.get(channelId);
1397
- if (cached)
1398
- return cached;
1399
- const metaPath = this.getConversationMetaPath(channelId);
1400
- if (!metaPath || !existsSync(metaPath)) {
1401
- return null;
1402
- }
1403
- try {
1404
- const parsed = JSON.parse(readFileSync(metaPath, "utf-8"));
1405
- if (!parsed.conversationId || !parsed.conversationType || !parsed.senderId) {
1406
- return null;
1407
- }
1408
- const meta = {
1409
- conversationId: parsed.conversationId,
1410
- conversationType: parsed.conversationType,
1411
- senderId: parsed.senderId,
1412
- };
1413
- this.convMeta.set(channelId, meta);
1414
- return meta;
1415
- }
1416
- catch (err) {
1417
- log.logWarn("dingtalk.metadata.load_failed", "Conversation metadata load failed", {
1418
- channelId: channelId,
1419
- reason: errorMessage(err),
1420
- });
1421
- return null;
1422
- }
1423
- }
1424
- setConversationMeta(channelId, meta) {
1425
- this.touchChannel(channelId);
1426
- this.convMeta.set(channelId, meta);
1427
- const metaPath = this.getConversationMetaPath(channelId);
1428
- if (!metaPath)
1429
- return;
1430
- try {
1431
- mkdirSync(dirname(metaPath), { recursive: true });
1432
- writeFileAtomicallySync(metaPath, JSON.stringify(meta, null, 2));
1433
- }
1434
- catch (err) {
1435
- log.logWarn("dingtalk.metadata.persist_failed", "Conversation metadata persist failed", {
1436
- channelId: channelId,
1437
- reason: errorMessage(err),
1438
- });
1439
- }
1440
- }
1441
- getConversationMetaPath(channelId) {
1442
- if (!this.config.stateDir)
1443
- return null;
1444
- return join(getChannelDir(this.config.stateDir, channelId), ".channel-meta.json");
1445
- }
1446
- touchChannel(channelId) {
1447
- this.channelLastActiveAt.set(channelId, Date.now());
1448
- }
1449
- cleanupIdleChannelCaches(now = Date.now()) {
1450
- const cutoff = now - CHANNEL_CACHE_TTL_MS;
1451
- for (const [channelId, lastActiveAt] of this.channelLastActiveAt) {
1452
- if (lastActiveAt > cutoff)
1453
- continue;
1454
- const queue = this.queues.get(channelId);
1455
- if (!queue?.isIdle() || this.cardCreationInFlight.has(channelId))
1456
- continue;
1457
- const card = this.activeCards.get(channelId);
1458
- if (card && card.lastUpdated * 1000 > cutoff)
1459
- continue;
1460
- this.activeCards.delete(channelId);
1461
- const generation = this.cardGenerations.get(channelId);
1462
- if (generation)
1463
- this.cardCreationAttempted.delete(generation);
1464
- this.cardGenerations.delete(channelId);
1465
- this.convMeta.delete(channelId);
1466
- this.queues.delete(channelId);
1467
- this.channelLastActiveAt.delete(channelId);
1468
- }
1469
- }
1470
- }