@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
@@ -0,0 +1,66 @@
1
+ /**
2
+ * Inbound messages: acknowledge and deduplicate raw Stream frames, parse a robot message into a
3
+ * `ChannelEvent`, apply the sender allow-list, resolve image attachments, and hand the event to the
4
+ * bot's routing. The per-channel ingestion queue lives here so an attachment download can never be
5
+ * overtaken by a later message on the same channel.
6
+ */
7
+ import type { DWClientDownStream } from "dingtalk-stream";
8
+ import type { InboundImage } from "../channel/channel-event.js";
9
+ import type { DingTalkConfig } from "./config.js";
10
+ import type { ConversationMetaStore } from "./conversation-meta.js";
11
+ import type { DingTalkEvent, DingTalkHandler } from "./handler.js";
12
+ import { type ParsedInboundMessage } from "./inbound-media.js";
13
+ interface DingTalkIncomingMessage {
14
+ msgId?: string;
15
+ senderStaffId?: string;
16
+ senderId?: string;
17
+ senderNick?: string;
18
+ conversationId?: string;
19
+ conversationType?: string;
20
+ /** Group title. Present on group messages only; DingTalk omits it for DMs. */
21
+ conversationTitle?: string;
22
+ msgtype?: string;
23
+ text?: {
24
+ content?: string;
25
+ };
26
+ content?: {
27
+ richText?: Array<Record<string, string>>;
28
+ /** Present on a `picture` message; see `inbound-media.ts`'s `parseInboundMessage`. */
29
+ downloadCode?: string;
30
+ };
31
+ }
32
+ export interface InboundMessagesDeps {
33
+ config: DingTalkConfig;
34
+ handler: DingTalkHandler;
35
+ conversations: ConversationMetaStore;
36
+ isStopped: () => boolean;
37
+ /** Acknowledge a downstream frame to DingTalk. */
38
+ ack: (messageId: string) => void;
39
+ resolveInboundAttachments: (channelId: string, parsed: ParsedInboundMessage) => Promise<{
40
+ text: string;
41
+ images: InboundImage[];
42
+ }>;
43
+ /** Command / busy / `/new` routing for a built event (the bot's `routeInboundEvent`). */
44
+ routeInboundEvent: (event: DingTalkEvent) => Promise<void>;
45
+ }
46
+ export declare class InboundMessages {
47
+ private deps;
48
+ private processedIds;
49
+ private processedIdsOrder;
50
+ private inboundIngestQueue;
51
+ private pendingInboundIngestCount;
52
+ constructor(deps: InboundMessagesDeps);
53
+ /** True while an inbound message is still being ingested (downloading, not yet enqueued). */
54
+ hasPendingIngest(): boolean;
55
+ /**
56
+ * Mark an ID as processed. Returns true if this is a new ID, false if already seen.
57
+ * Maintains a FIFO buffer of at most 200 entries.
58
+ */
59
+ private markProcessed;
60
+ handleRawMessage(msg: DWClientDownStream): {
61
+ status: "SUCCESS";
62
+ message: string;
63
+ };
64
+ onStreamMessage(data: DingTalkIncomingMessage): Promise<void>;
65
+ }
66
+ export {};
@@ -0,0 +1,137 @@
1
+ import * as log from "../log.js";
2
+ import { createSerialQueue } from "../shared/serial-queue.js";
3
+ import { errorMessage } from "../shared/text-utils.js";
4
+ import { isRecord } from "../shared/type-guards.js";
5
+ import { parseInboundMessage } from "./inbound-media.js";
6
+ export class InboundMessages {
7
+ constructor(deps) {
8
+ this.deps = deps;
9
+ // Deduplication cache (Set for O(1) lookup, order array for FIFO eviction)
10
+ this.processedIds = new Set();
11
+ this.processedIdsOrder = [];
12
+ // Serializes "resolve inbound image attachments → build event → route" per channel (spec 049
13
+ // D3): a message needing a download must not be overtaken, in delivery order, by a later
14
+ // download-free message on the same channel. `pendingInboundIngestCount` lets the bot's
15
+ // `allChannelQueuesIdle()` see this in-flight network work, which `ChannelQueue.isIdle()`
16
+ // alone cannot — the event has not been built yet, let alone enqueued.
17
+ this.inboundIngestQueue = createSerialQueue();
18
+ this.pendingInboundIngestCount = 0;
19
+ }
20
+ /** True while an inbound message is still being ingested (downloading, not yet enqueued). */
21
+ hasPendingIngest() {
22
+ return this.pendingInboundIngestCount > 0;
23
+ }
24
+ /**
25
+ * Mark an ID as processed. Returns true if this is a new ID, false if already seen.
26
+ * Maintains a FIFO buffer of at most 200 entries.
27
+ */
28
+ markProcessed(id) {
29
+ if (this.processedIds.has(id))
30
+ return false;
31
+ this.processedIds.add(id);
32
+ this.processedIdsOrder.push(id);
33
+ while (this.processedIdsOrder.length > 200) {
34
+ this.processedIds.delete(this.processedIdsOrder.shift());
35
+ }
36
+ return true;
37
+ }
38
+ handleRawMessage(msg) {
39
+ // 1. Immediate ACK
40
+ if (msg.headers?.messageId) {
41
+ this.deps.ack(msg.headers.messageId);
42
+ }
43
+ // 2. Protocol deduplication
44
+ const messageId = msg.headers?.messageId;
45
+ if (messageId && !this.markProcessed(messageId)) {
46
+ return { status: "SUCCESS", message: "OK" };
47
+ }
48
+ try {
49
+ const parsedData = typeof msg.data === "string" ? JSON.parse(msg.data) : msg.data;
50
+ const data = isRecord(parsedData) ? parsedData : {};
51
+ // 3. Business logic deduplication
52
+ const msgId = data.msgId;
53
+ if (msgId && !this.markProcessed(msgId)) {
54
+ return { status: "SUCCESS", message: "OK" };
55
+ }
56
+ // Fire-and-forget processing
57
+ this.onStreamMessage(data).catch((err) => {
58
+ log.logWarn("dingtalk.handler.failed", "Message handler failed", { reason: errorMessage(err) });
59
+ });
60
+ }
61
+ catch (err) {
62
+ log.logWarn("dingtalk.message.parse_failed", "Message parse failed", { reason: errorMessage(err) });
63
+ }
64
+ return { status: "SUCCESS", message: "OK" };
65
+ }
66
+ async onStreamMessage(data) {
67
+ const { config, handler } = this.deps;
68
+ if (this.deps.isStopped()) {
69
+ return;
70
+ }
71
+ const parsed = parseInboundMessage(data);
72
+ const senderId = data.senderStaffId || data.senderId || "";
73
+ const senderName = data.senderNick || "Unknown";
74
+ const conversationId = data.conversationId || "";
75
+ const conversationType = data.conversationType || "1";
76
+ if (!parsed.text && parsed.downloadCodes.length === 0) {
77
+ const msgtype = typeof data.msgtype === "string" ? data.msgtype : "unknown";
78
+ log.logWarn("dingtalk.message.empty", "Empty message ignored", { fields: { msgtype } });
79
+ return;
80
+ }
81
+ if (config.allowFrom && config.allowFrom.length > 0) {
82
+ if (!config.allowFrom.includes(senderId)) {
83
+ log.logWarn("dingtalk.message.unauthorized", "Message from unauthorized user ignored", {
84
+ fields: { senderName, senderId },
85
+ });
86
+ return;
87
+ }
88
+ }
89
+ // Determine channel ID
90
+ const channelId = conversationType === "2" ? `group_${conversationId}` : `dm_${senderId}`;
91
+ // Parsing above is free; resolving image attachments below is a real network round-trip.
92
+ // Serialize the whole "resolve attachments → build event → route" unit per channel (spec
93
+ // 049 D3): without this, a message needing a download can be overtaken, in delivery order,
94
+ // by a later download-free message on the same channel — nothing upstream of
95
+ // `enqueueStreamMessage` otherwise waits on anything asynchronous.
96
+ this.pendingInboundIngestCount++;
97
+ try {
98
+ await this.inboundIngestQueue.run(channelId, async () => {
99
+ const { text: content, images } = await this.deps.resolveInboundAttachments(channelId, parsed);
100
+ log.logEvent("info", "runtime.dingtalk.message_received", "Accepted incoming message", {
101
+ ctx: { channelId, userName: senderName },
102
+ fields: { messageType: conversationType === "2" ? "group" : "dm", messageLength: content.length },
103
+ });
104
+ // A group carries its title on every message; a DM has none, so the peer's nickname
105
+ // is the only human-readable handle that channel will ever have.
106
+ const conversationTitle = typeof data.conversationTitle === "string" ? data.conversationTitle.trim() : "";
107
+ const channelName = (conversationType === "2" ? conversationTitle : senderName) || undefined;
108
+ // Cache conversation metadata for card creation
109
+ this.deps.conversations.set(channelId, {
110
+ conversationId,
111
+ conversationType,
112
+ senderId,
113
+ });
114
+ // The one place a real person's message is seen before command/busy routing splits
115
+ // the path, so the channel index counts every human message and no synthetic wake.
116
+ handler.noteChannelActivity?.({ channelId, name: channelName, at: Date.now() });
117
+ // Build event
118
+ const event = {
119
+ type: conversationType === "2" ? "group" : "dm",
120
+ channelId,
121
+ ts: Date.now().toString(),
122
+ user: senderId,
123
+ userName: senderName,
124
+ text: content,
125
+ conversationId,
126
+ conversationType,
127
+ ...(channelName ? { channelName } : {}),
128
+ ...(images.length > 0 ? { images } : {}),
129
+ };
130
+ await this.deps.routeInboundEvent(event);
131
+ });
132
+ }
133
+ finally {
134
+ this.pendingInboundIngestCount--;
135
+ }
136
+ }
137
+ }
@@ -0,0 +1,66 @@
1
+ import type { MediaSendResult, OutboundMedia } from "../channel/channel-context.js";
2
+ import type { InboundImage } from "../channel/channel-event.js";
3
+ import { type ConversationMeta } from "./api.js";
4
+ import type { DingTalkConfig } from "./config.js";
5
+ import type { DingTalkHandler } from "./handler.js";
6
+ import { type ParsedInboundMessage } from "./inbound-media.js";
7
+ export interface DingTalkMediaDeps {
8
+ config: DingTalkConfig;
9
+ handler: DingTalkHandler;
10
+ getAccessToken: () => Promise<string | null>;
11
+ getConversationMeta: (channelId: string) => ConversationMeta | null;
12
+ sendRobotMessage: (meta: ConversationMeta, msgKey: string, msgParam: string) => Promise<boolean>;
13
+ /**
14
+ * The inbound file fetch used while resolving attachments. The bot supplies its own overridable
15
+ * `downloadMessageFile`, so the deterministic e2e harness can stub the network out.
16
+ */
17
+ downloadMessageFile: (downloadCode: string) => Promise<{
18
+ data: Buffer;
19
+ } | null>;
20
+ }
21
+ export declare class DingTalkMedia {
22
+ private deps;
23
+ constructor(deps: DingTalkMediaDeps);
24
+ /**
25
+ * Deliver a local file to a channel as a native attachment. Uploads the bytes
26
+ * to get a `media_id`, then sends a `sampleImageMsg` (inline image) or
27
+ * `sampleFile` (downloadable file) robot message. `channelId` is supplied by
28
+ * the runtime (the tool is bound to its channel at build time), never by the
29
+ * model, so an agent cannot target a channel other than its own.
30
+ */
31
+ sendMedia(channelId: string, media: OutboundMedia): Promise<MediaSendResult>;
32
+ /**
33
+ * Upload raw bytes to DingTalk and return the reusable `media_id`, or null on
34
+ * failure. The upload endpoint lives on the legacy oapi host and answers 200
35
+ * with a non-zero `errcode` on failure, so the body is inspected explicitly.
36
+ */
37
+ private uploadMedia;
38
+ /**
39
+ * Two-step DingTalk inbound file download (spec 049): `messageFiles/download` exchanges the
40
+ * message's `downloadCode` for a short-lived `downloadUrl`, then that URL is fetched for the
41
+ * actual bytes. Both hops reuse the shared access token — the same app access token works across
42
+ * DingTalk's hosts, as the comment on `DINGTALK_OAPI` explains for the outbound side.
43
+ *
44
+ * This runs from the inbound per-channel ingestion queue, never from inside a turn: a busy
45
+ * channel can queue a message for minutes (`USER_MESSAGE_QUEUE_LIMIT`), and by the time a
46
+ * queued turn actually ran, a `downloadCode`/`downloadUrl` fetched only then could easily have
47
+ * already expired.
48
+ */
49
+ downloadMessageFile(downloadCode: string): Promise<{
50
+ data: Buffer;
51
+ } | null>;
52
+ /**
53
+ * Resolve one parsed message's image credentials into persisted `InboundImage`s and a text
54
+ * with every `[图片N]` marker either left as-is (success) or replaced with a reason (spec 049
55
+ * D8): a download failure, an unrecognized format, an oversized file, or a message that
56
+ * simply carried more images than `MAX_INBOUND_IMAGES_PER_MESSAGE` allows. A failure on one
57
+ * image never drops the rest of the message — only that one marker changes.
58
+ *
59
+ * No-op (no network call at all) when the message carries no image credentials, so a plain
60
+ * text message never pays for this method's existence.
61
+ */
62
+ resolveInboundAttachments(channelId: string, parsed: ParsedInboundMessage): Promise<{
63
+ text: string;
64
+ images: InboundImage[];
65
+ }>;
66
+ }
@@ -0,0 +1,214 @@
1
+ /**
2
+ * Media (image / file) for DingTalk: outbound delivery (`MediaSender` contract), and the two-step
3
+ * inbound download plus the per-message attachment resolution built on it (spec 049).
4
+ */
5
+ import axios from "axios";
6
+ import * as log from "../log.js";
7
+ import { errorMessage } from "../shared/text-utils.js";
8
+ import { isRecord } from "../shared/type-guards.js";
9
+ import { formatSize } from "../tools/truncate.js";
10
+ import { DINGTALK_API, DINGTALK_OAPI, http } from "./api.js";
11
+ import { MAX_INBOUND_IMAGE_BYTES, MAX_INBOUND_IMAGES_PER_MESSAGE, MEDIA_DOWNLOAD_TIMEOUT_MS, sniffImageMimeType, } from "./inbound-media.js";
12
+ // DingTalk caps robot image messages at 1MB and file messages at 20MB. We reject
13
+ // oversized files before spending an upload round-trip on a request the API rejects.
14
+ const MAX_IMAGE_BYTES = 1024 * 1024;
15
+ const MAX_FILE_BYTES = 20 * 1024 * 1024;
16
+ // Uploads can move up to 20MB; the 15s default HTTP timeout is too tight for that.
17
+ const MEDIA_UPLOAD_TIMEOUT_MS = 60_000;
18
+ // File extensions the `sampleFile` message type accepts (per DingTalk docs).
19
+ const SUPPORTED_FILE_TYPES = new Set(["xlsx", "pdf", "zip", "rar", "doc", "docx", "ppt", "pptx", "csv", "txt"]);
20
+ /** Lowercased extension without the dot ("Report.PDF" → "pdf"); "" when none. */
21
+ function extractFileExtension(fileName) {
22
+ const dot = fileName.lastIndexOf(".");
23
+ if (dot < 0 || dot === fileName.length - 1)
24
+ return "";
25
+ return fileName.slice(dot + 1).toLowerCase();
26
+ }
27
+ export class DingTalkMedia {
28
+ constructor(deps) {
29
+ this.deps = deps;
30
+ }
31
+ /**
32
+ * Deliver a local file to a channel as a native attachment. Uploads the bytes
33
+ * to get a `media_id`, then sends a `sampleImageMsg` (inline image) or
34
+ * `sampleFile` (downloadable file) robot message. `channelId` is supplied by
35
+ * the runtime (the tool is bound to its channel at build time), never by the
36
+ * model, so an agent cannot target a channel other than its own.
37
+ */
38
+ async sendMedia(channelId, media) {
39
+ const isImage = media.kind === "image";
40
+ const limit = isImage ? MAX_IMAGE_BYTES : MAX_FILE_BYTES;
41
+ if (media.data.length > limit) {
42
+ return {
43
+ ok: false,
44
+ error: `File is ${(media.data.length / 1024 / 1024).toFixed(1)}MB, exceeds the ${limit / 1024 / 1024}MB DingTalk limit for ${media.kind} messages.`,
45
+ };
46
+ }
47
+ const fileType = extractFileExtension(media.fileName);
48
+ if (!isImage && !SUPPORTED_FILE_TYPES.has(fileType)) {
49
+ return {
50
+ ok: false,
51
+ error: `DingTalk file messages do not support the "${fileType || "(none)"}" type. Supported: ${[...SUPPORTED_FILE_TYPES].join(", ")}.`,
52
+ };
53
+ }
54
+ const meta = this.deps.getConversationMeta(channelId);
55
+ if (!meta) {
56
+ return { ok: false, error: "No conversation is known for this channel yet; cannot deliver a file." };
57
+ }
58
+ const mediaId = await this.uploadMedia(isImage ? "image" : "file", media.data, media.fileName);
59
+ if (!mediaId) {
60
+ return { ok: false, error: "Failed to upload the file to DingTalk (see server logs)." };
61
+ }
62
+ const { msgKey, msgParam } = isImage
63
+ ? { msgKey: "sampleImageMsg", msgParam: JSON.stringify({ photoURL: mediaId }) }
64
+ : {
65
+ msgKey: "sampleFile",
66
+ msgParam: JSON.stringify({ mediaId, fileName: media.fileName, fileType }),
67
+ };
68
+ const sent = await this.deps.sendRobotMessage(meta, msgKey, msgParam);
69
+ return sent ? { ok: true } : { ok: false, error: "DingTalk rejected the file message (see server logs)." };
70
+ }
71
+ /**
72
+ * Upload raw bytes to DingTalk and return the reusable `media_id`, or null on
73
+ * failure. The upload endpoint lives on the legacy oapi host and answers 200
74
+ * with a non-zero `errcode` on failure, so the body is inspected explicitly.
75
+ */
76
+ async uploadMedia(type, data, fileName) {
77
+ const token = await this.deps.getAccessToken();
78
+ if (!token)
79
+ return null;
80
+ const form = new FormData();
81
+ form.append("media", new Blob([new Uint8Array(data)]), fileName);
82
+ try {
83
+ const resp = await http.post(`${DINGTALK_OAPI}/media/upload?access_token=${encodeURIComponent(token)}&type=${type}`, form,
84
+ // Override the 15s default: a multi-MB upload over a slow link can take
85
+ // longer, and unlike card streaming this call is not on the delivery loop.
86
+ { timeout: MEDIA_UPLOAD_TIMEOUT_MS });
87
+ const body = isRecord(resp.data) ? resp.data : {};
88
+ if (body.errcode && body.errcode !== 0) {
89
+ log.logWarn("dingtalk.media.upload_failed", "Media upload failed", {
90
+ reason: String(body.errmsg ?? ""),
91
+ fields: { errcode: body.errcode },
92
+ });
93
+ return null;
94
+ }
95
+ const mediaId = typeof body.media_id === "string" ? body.media_id : null;
96
+ if (!mediaId) {
97
+ log.logWarn("dingtalk.media.upload_failed", "Media upload returned no media_id", {
98
+ reason: JSON.stringify(body),
99
+ });
100
+ }
101
+ return mediaId;
102
+ }
103
+ catch (err) {
104
+ if (axios.isAxiosError(err) && err.response) {
105
+ log.logWarn("dingtalk.media.upload_failed", "Media upload failed", {
106
+ reason: JSON.stringify(err.response.data),
107
+ fields: { status: err.response.status },
108
+ });
109
+ }
110
+ else {
111
+ log.logWarn("dingtalk.media.upload_failed", "Media upload failed", { reason: errorMessage(err) });
112
+ }
113
+ return null;
114
+ }
115
+ }
116
+ /**
117
+ * Two-step DingTalk inbound file download (spec 049): `messageFiles/download` exchanges the
118
+ * message's `downloadCode` for a short-lived `downloadUrl`, then that URL is fetched for the
119
+ * actual bytes. Both hops reuse the shared access token — the same app access token works across
120
+ * DingTalk's hosts, as the comment on `DINGTALK_OAPI` explains for the outbound side.
121
+ *
122
+ * This runs from the inbound per-channel ingestion queue, never from inside a turn: a busy
123
+ * channel can queue a message for minutes (`USER_MESSAGE_QUEUE_LIMIT`), and by the time a
124
+ * queued turn actually ran, a `downloadCode`/`downloadUrl` fetched only then could easily have
125
+ * already expired.
126
+ */
127
+ async downloadMessageFile(downloadCode) {
128
+ const token = await this.deps.getAccessToken();
129
+ if (!token)
130
+ return null;
131
+ const robotCode = this.deps.config.robotCode || this.deps.config.clientId;
132
+ try {
133
+ const downloadUrlResp = await http.post(`${DINGTALK_API}/v1.0/robot/messageFiles/download`, { robotCode, downloadCode }, { headers: { "x-acs-dingtalk-access-token": token } });
134
+ const downloadUrl = isRecord(downloadUrlResp.data) ? downloadUrlResp.data.downloadUrl : undefined;
135
+ if (typeof downloadUrl !== "string" || !downloadUrl) {
136
+ log.logWarn("dingtalk.file.download_failed", "Inbound file download returned no downloadUrl", {
137
+ reason: JSON.stringify(downloadUrlResp.data),
138
+ });
139
+ return null;
140
+ }
141
+ const fileResp = await http.get(downloadUrl, {
142
+ responseType: "arraybuffer",
143
+ // Reject an oversized body before it fully lands in memory rather than after.
144
+ maxContentLength: MAX_INBOUND_IMAGE_BYTES,
145
+ timeout: MEDIA_DOWNLOAD_TIMEOUT_MS,
146
+ });
147
+ return { data: Buffer.from(fileResp.data) };
148
+ }
149
+ catch (err) {
150
+ if (axios.isAxiosError(err) && err.response) {
151
+ log.logWarn("dingtalk.file.download_failed", "Inbound file download failed", {
152
+ reason: JSON.stringify(err.response.data),
153
+ fields: { status: err.response.status },
154
+ });
155
+ }
156
+ else {
157
+ log.logWarn("dingtalk.file.download_failed", "Inbound file download failed", { reason: errorMessage(err) });
158
+ }
159
+ return null;
160
+ }
161
+ }
162
+ /**
163
+ * Resolve one parsed message's image credentials into persisted `InboundImage`s and a text
164
+ * with every `[图片N]` marker either left as-is (success) or replaced with a reason (spec 049
165
+ * D8): a download failure, an unrecognized format, an oversized file, or a message that
166
+ * simply carried more images than `MAX_INBOUND_IMAGES_PER_MESSAGE` allows. A failure on one
167
+ * image never drops the rest of the message — only that one marker changes.
168
+ *
169
+ * No-op (no network call at all) when the message carries no image credentials, so a plain
170
+ * text message never pays for this method's existence.
171
+ */
172
+ async resolveInboundAttachments(channelId, parsed) {
173
+ if (parsed.downloadCodes.length === 0) {
174
+ return { text: parsed.text, images: [] };
175
+ }
176
+ let text = parsed.text;
177
+ const images = [];
178
+ const replaceMarker = (index, replacement) => {
179
+ text = text.replace(`[图片${index + 1}]`, replacement);
180
+ };
181
+ await Promise.all(parsed.downloadCodes.map(async (downloadCode, index) => {
182
+ const marker = index + 1;
183
+ if (index >= MAX_INBOUND_IMAGES_PER_MESSAGE) {
184
+ replaceMarker(index, `[图片${marker}:超出单条消息图片数量上限,已丢弃]`);
185
+ return;
186
+ }
187
+ const downloaded = await this.deps.downloadMessageFile(downloadCode);
188
+ if (!downloaded) {
189
+ replaceMarker(index, `[图片${marker}:接收失败]`);
190
+ return;
191
+ }
192
+ if (downloaded.data.byteLength > MAX_INBOUND_IMAGE_BYTES) {
193
+ replaceMarker(index, `[图片${marker}:文件过大(${formatSize(downloaded.data.byteLength)}),已丢弃]`);
194
+ return;
195
+ }
196
+ const mimeType = sniffImageMimeType(downloaded.data);
197
+ const persisted = await this.deps.handler.persistInboundImage?.(channelId, {
198
+ data: downloaded.data,
199
+ mimeType,
200
+ });
201
+ if (!persisted) {
202
+ replaceMarker(index, `[图片${marker}:保存失败]`);
203
+ return;
204
+ }
205
+ if (!mimeType) {
206
+ // Persisted for the record, but never handed to a model — see the handler
207
+ // contract's doc comment on `persistInboundImage`.
208
+ replaceMarker(index, `[图片${marker}:格式不支持,已保存]`);
209
+ }
210
+ images[index] = persisted;
211
+ }));
212
+ return { text, images: images.filter((image) => image !== undefined) };
213
+ }
214
+ }