@oyasmi/pipiclaw 0.9.3 → 0.9.4-beta.2

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