@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,356 @@
1
+ /**
2
+ * The DingTalk Stream socket lifecycle: connect with a timeout, keep it alive, and reconnect with
3
+ * exponential backoff. Owns the client, every timer and the reconnect state machine; it knows
4
+ * nothing about messages beyond handing raw frames to the callback it was given.
5
+ */
6
+ import { DWClient, TOPIC_ROBOT } from "dingtalk-stream";
7
+ import * as log from "../log.js";
8
+ import { errorMessage } from "../shared/text-utils.js";
9
+ import { isRecord } from "../shared/type-guards.js";
10
+ import { sleepUnref } from "../shared/with-timeout.js";
11
+ const CONNECT_ATTEMPT_TIMEOUT_MS = 10_000;
12
+ const SOCKET_CLOSE_GRACE_MS = 1_000;
13
+ const SOCKET_TERMINATE_GRACE_MS = 250;
14
+ const SOCKET_STATE_CONNECTING = 0;
15
+ const SOCKET_STATE_OPEN = 1;
16
+ const SOCKET_STATE_CLOSING = 2;
17
+ const SOCKET_STATE_CLOSED = 3;
18
+ export class StreamConnection {
19
+ constructor(options) {
20
+ this.options = options;
21
+ this.client = null;
22
+ this.lastSocketAvailableTime = Date.now();
23
+ this.activeMessageProcessing = false;
24
+ this.keepAliveTimer = null;
25
+ this.reconnectTimer = null;
26
+ // Dedicated timer for the in-flight backoff sleep inside doReconnect, kept
27
+ // separate from reconnectTimer so an external scheduleReconnect() (e.g. a
28
+ // WebSocket close event) can never clear the sleep out from under an active
29
+ // attempt and leave isReconnecting stuck true forever.
30
+ this.reconnectDelayTimer = null;
31
+ this.reconnectDelayResolve = null;
32
+ this.isReconnecting = false;
33
+ this.reconnectAttempts = 0;
34
+ this.hasReportedReady = false;
35
+ }
36
+ /** Create the client and make the first (immediate) connection attempt. */
37
+ async start() {
38
+ this.clearAllTimers();
39
+ const clientOptions = {
40
+ clientId: this.options.clientId,
41
+ clientSecret: this.options.clientSecret,
42
+ autoReconnect: false,
43
+ keepAlive: false,
44
+ };
45
+ this.client = new DWClient(clientOptions);
46
+ this.client.registerCallbackListener(TOPIC_ROBOT, (msg) => {
47
+ return this.options.onRawMessage(msg);
48
+ });
49
+ const connected = await this.doReconnect(true); // Initial connection
50
+ if (!connected) {
51
+ log.logWarn("dingtalk.connect.pending", "Initial stream connection not ready; retrying in background");
52
+ }
53
+ }
54
+ /** Acknowledge a downstream frame immediately so DingTalk does not redeliver it. */
55
+ ack(messageId) {
56
+ this.client?.socketCallBackResponse(messageId, { status: "SUCCESS", message: "OK" });
57
+ }
58
+ /** A turn is running: the keep-alive watchdog must not treat the quiet socket as dead. */
59
+ beginMessageProcessing() {
60
+ this.activeMessageProcessing = true;
61
+ }
62
+ endMessageProcessing() {
63
+ this.activeMessageProcessing = false;
64
+ this.lastSocketAvailableTime = Date.now();
65
+ }
66
+ /** Cancel the keep-alive, scheduled-reconnect and backoff timers. */
67
+ clearAllTimers() {
68
+ this.clearKeepAliveTimer();
69
+ this.clearReconnectTimer();
70
+ this.clearReconnectDelay();
71
+ }
72
+ /** Close the socket and drop the client (the bot is stopping). */
73
+ async disconnect() {
74
+ if (this.client) {
75
+ try {
76
+ await this.cleanupSocket("stop");
77
+ }
78
+ catch (err) {
79
+ log.logWarn("dingtalk.disconnect.failed", "Clean disconnect failed", { reason: errorMessage(err) });
80
+ }
81
+ finally {
82
+ this.client = null;
83
+ }
84
+ }
85
+ }
86
+ getSocket() {
87
+ if (!this.client) {
88
+ return null;
89
+ }
90
+ const socket = Reflect.get(this.client, "socket");
91
+ return this.isSocketLike(socket) ? socket : null;
92
+ }
93
+ isSocketLike(value) {
94
+ if (!isRecord(value)) {
95
+ return false;
96
+ }
97
+ return typeof value.on === "function";
98
+ }
99
+ setTrackedTimeout(callback, delayMs) {
100
+ const timer = setTimeout(() => {
101
+ callback();
102
+ }, delayMs);
103
+ timer.unref?.();
104
+ return timer;
105
+ }
106
+ setTrackedInterval(callback, intervalMs) {
107
+ const timer = setInterval(callback, intervalMs);
108
+ timer.unref?.();
109
+ return timer;
110
+ }
111
+ clearKeepAliveTimer() {
112
+ if (this.keepAliveTimer) {
113
+ clearInterval(this.keepAliveTimer);
114
+ this.keepAliveTimer = null;
115
+ }
116
+ }
117
+ clearReconnectTimer() {
118
+ if (this.reconnectTimer) {
119
+ clearTimeout(this.reconnectTimer);
120
+ this.reconnectTimer = null;
121
+ }
122
+ }
123
+ // Cancel the backoff sleep and resolve its pending promise so the awaiting
124
+ // doReconnect unblocks (and then bails on the isStopped/!client re-check)
125
+ // instead of hanging forever.
126
+ clearReconnectDelay() {
127
+ if (this.reconnectDelayTimer) {
128
+ clearTimeout(this.reconnectDelayTimer);
129
+ this.reconnectDelayTimer = null;
130
+ }
131
+ if (this.reconnectDelayResolve) {
132
+ const resolve = this.reconnectDelayResolve;
133
+ this.reconnectDelayResolve = null;
134
+ resolve();
135
+ }
136
+ }
137
+ async waitForDelay(delayMs) {
138
+ await new Promise((resolve) => {
139
+ this.reconnectDelayResolve = resolve;
140
+ this.reconnectDelayTimer = this.setTrackedTimeout(() => {
141
+ this.reconnectDelayTimer = null;
142
+ this.reconnectDelayResolve = null;
143
+ resolve();
144
+ }, delayMs);
145
+ });
146
+ }
147
+ async waitForSocketState(socket, expectedState, timeoutMs) {
148
+ const deadline = Date.now() + timeoutMs;
149
+ while ((socket.readyState ?? SOCKET_STATE_CLOSED) !== expectedState && Date.now() < deadline) {
150
+ await sleepUnref(25);
151
+ }
152
+ return (socket.readyState ?? SOCKET_STATE_CLOSED) === expectedState;
153
+ }
154
+ markClientDisconnected() {
155
+ if (!this.client) {
156
+ return;
157
+ }
158
+ Reflect.set(this.client, "connected", false);
159
+ Reflect.set(this.client, "registered", false);
160
+ Reflect.set(this.client, "reconnecting", false);
161
+ }
162
+ clearClientSocketReference() {
163
+ if (!this.client) {
164
+ return;
165
+ }
166
+ Reflect.set(this.client, "socket", undefined);
167
+ }
168
+ async cleanupSocket(reason) {
169
+ const socket = this.getSocket();
170
+ this.markClientDisconnected();
171
+ if (!socket) {
172
+ this.clearClientSocketReference();
173
+ return;
174
+ }
175
+ socket.removeAllListeners?.();
176
+ // ws emits an asynchronous error when close() aborts a CONNECTING socket.
177
+ const ignoreCleanupError = () => { };
178
+ socket.on("error", ignoreCleanupError);
179
+ if ((socket.readyState ?? SOCKET_STATE_CLOSED) !== SOCKET_STATE_CLOSED) {
180
+ try {
181
+ socket.close?.();
182
+ }
183
+ catch (err) {
184
+ log.logWarn("dingtalk.socket.close_failed", "Socket close failed", {
185
+ reason: errorMessage(err),
186
+ fields: { during: reason },
187
+ });
188
+ }
189
+ const closed = await this.waitForSocketState(socket, SOCKET_STATE_CLOSED, SOCKET_CLOSE_GRACE_MS);
190
+ if (!closed) {
191
+ log.logWarn("dingtalk.socket.terminating", "Forcing socket termination", { fields: { during: reason } });
192
+ try {
193
+ socket.terminate?.();
194
+ }
195
+ catch (err) {
196
+ log.logWarn("dingtalk.socket.terminate_failed", "Socket terminate failed", {
197
+ reason: errorMessage(err),
198
+ fields: { during: reason },
199
+ });
200
+ }
201
+ await this.waitForSocketState(socket, SOCKET_STATE_CLOSED, SOCKET_TERMINATE_GRACE_MS);
202
+ }
203
+ }
204
+ if ((socket.readyState ?? SOCKET_STATE_CLOSED) === SOCKET_STATE_CLOSED) {
205
+ socket.removeListener?.("error", ignoreCleanupError);
206
+ }
207
+ this.clearClientSocketReference();
208
+ }
209
+ async connectWithTimeout() {
210
+ if (!this.client) {
211
+ throw new Error("DingTalk client is not initialized");
212
+ }
213
+ const connectPromise = Promise.resolve(this.client.connect());
214
+ let timeoutHandle = null;
215
+ const timeoutPromise = new Promise((_, reject) => {
216
+ timeoutHandle = setTimeout(() => {
217
+ reject(new Error(`connect timed out after ${CONNECT_ATTEMPT_TIMEOUT_MS}ms`));
218
+ }, CONNECT_ATTEMPT_TIMEOUT_MS);
219
+ timeoutHandle.unref?.();
220
+ });
221
+ try {
222
+ await Promise.race([connectPromise, timeoutPromise]);
223
+ }
224
+ finally {
225
+ if (timeoutHandle) {
226
+ clearTimeout(timeoutHandle);
227
+ }
228
+ }
229
+ const socket = this.getSocket();
230
+ if (!socket || socket.readyState !== SOCKET_STATE_OPEN) {
231
+ throw new Error("stream socket did not reach open state");
232
+ }
233
+ }
234
+ scheduleReconnect(delayMs, immediate) {
235
+ if (this.options.isStopped()) {
236
+ return;
237
+ }
238
+ // An attempt is already in flight; it owns the retry loop and will
239
+ // reschedule itself on failure. Scheduling here would be redundant and,
240
+ // worse, tear down a just-established socket if the attempt has already
241
+ // succeeded by the time this fires.
242
+ if (this.isReconnecting) {
243
+ return;
244
+ }
245
+ this.clearReconnectTimer();
246
+ this.reconnectTimer = this.setTrackedTimeout(() => {
247
+ this.reconnectTimer = null;
248
+ this.doReconnect(immediate).catch((err) => {
249
+ log.logWarn("dingtalk.reconnect.failed", "Reconnect failed", { reason: errorMessage(err) });
250
+ });
251
+ }, delayMs);
252
+ }
253
+ async doReconnect(immediate = false) {
254
+ if (this.isReconnecting || this.options.isStopped() || !this.client)
255
+ return false;
256
+ this.isReconnecting = true;
257
+ let connectionFailed = false;
258
+ let connected = false;
259
+ this.clearReconnectTimer();
260
+ this.clearKeepAliveTimer();
261
+ if (!immediate && this.reconnectAttempts > 0) {
262
+ const delay = Math.min(1000 * 2 ** this.reconnectAttempts + Math.random() * 1000, 30000);
263
+ log.logEvent("info", "runtime.dingtalk.reconnect_scheduled", "Reconnect scheduled", {
264
+ fields: { delayMs: delay },
265
+ });
266
+ await this.waitForDelay(delay);
267
+ if (this.options.isStopped() || !this.client) {
268
+ this.isReconnecting = false;
269
+ return false;
270
+ }
271
+ }
272
+ try {
273
+ const socket = this.getSocket();
274
+ const readyState = socket?.readyState;
275
+ if (readyState === SOCKET_STATE_CONNECTING ||
276
+ readyState === SOCKET_STATE_OPEN ||
277
+ readyState === SOCKET_STATE_CLOSING ||
278
+ readyState === SOCKET_STATE_CLOSED) {
279
+ await this.cleanupSocket("reconnect");
280
+ }
281
+ await this.connectWithTimeout();
282
+ this.lastSocketAvailableTime = Date.now();
283
+ this.reconnectAttempts = 0; // Success, reset backoff
284
+ log.logEvent("info", "runtime.dingtalk.stream_connected", "Connected to stream");
285
+ if (!this.hasReportedReady) {
286
+ log.logConnected();
287
+ this.hasReportedReady = true;
288
+ }
289
+ connected = true;
290
+ // Setup keep alive
291
+ this.clearKeepAliveTimer();
292
+ this.keepAliveTimer = this.setTrackedInterval(() => {
293
+ if (this.options.isStopped())
294
+ return;
295
+ const elapsed = Date.now() - this.lastSocketAvailableTime;
296
+ if (elapsed > 90 * 1000 && !this.activeMessageProcessing) {
297
+ // No pong / activity for >90s: the socket is (half-)dead and may
298
+ // never emit a close event. Proactively force a reconnect instead
299
+ // of waiting indefinitely. scheduleReconnect no-ops if an attempt
300
+ // is already in flight or the bot has stopped.
301
+ log.logWarn("dingtalk.connection.timeout", "Connection timeout (>90s); forcing reconnect");
302
+ this.scheduleReconnect(1000, true);
303
+ return;
304
+ }
305
+ try {
306
+ const s = this.getSocket();
307
+ if (s?.readyState === 1) {
308
+ s.ping?.();
309
+ }
310
+ }
311
+ catch (_err) {
312
+ // Ignore
313
+ }
314
+ }, 30 * 1000);
315
+ // Setup native socket events
316
+ const s = this.getSocket();
317
+ s?.on("pong", () => {
318
+ this.lastSocketAvailableTime = Date.now();
319
+ });
320
+ s?.on("close", (code, reason) => {
321
+ log.logWarn("dingtalk.socket.closed", "WebSocket closed", { fields: { code, reason } });
322
+ if (this.options.isStopped())
323
+ return;
324
+ this.scheduleReconnect(1000, true);
325
+ });
326
+ s?.on("message", (raw) => {
327
+ try {
328
+ const msg = JSON.parse(raw);
329
+ if (msg.type === "SYSTEM" && msg.headers?.topic === "disconnect") {
330
+ log.logWarn("dingtalk.connection.disconnected", "Server sent a disconnect event");
331
+ if (!this.options.isStopped()) {
332
+ this.doReconnect(true).catch(() => { });
333
+ }
334
+ }
335
+ }
336
+ catch (_e) {
337
+ // skip
338
+ }
339
+ });
340
+ }
341
+ catch (err) {
342
+ await this.cleanupSocket("reconnect failure");
343
+ this.reconnectAttempts++;
344
+ connectionFailed = true;
345
+ log.logWarn("dingtalk.connect.failed", "Connection failed", { reason: errorMessage(err) });
346
+ }
347
+ finally {
348
+ this.isReconnecting = false;
349
+ }
350
+ // Auto-retry on failure with exponential backoff
351
+ if (connectionFailed && !this.options.isStopped()) {
352
+ this.scheduleReconnect(0, false);
353
+ }
354
+ return connected;
355
+ }
356
+ }
@@ -0,0 +1,16 @@
1
+ import type { ConversationMeta } from "./api.js";
2
+ import type { DingTalkConfig } from "./config.js";
3
+ export declare class ConversationMetaStore {
4
+ private config;
5
+ /** Marks the channel as recently used, so the idle-cache sweep leaves it alone. */
6
+ private touchChannel;
7
+ private convMeta;
8
+ constructor(config: Pick<DingTalkConfig, "stateDir">,
9
+ /** Marks the channel as recently used, so the idle-cache sweep leaves it alone. */
10
+ touchChannel: (channelId: string) => void);
11
+ get(channelId: string): ConversationMeta | null;
12
+ set(channelId: string, meta: ConversationMeta): void;
13
+ /** Drop the in-memory entry only; the persisted file stays and is reloaded on demand. */
14
+ evict(channelId: string): void;
15
+ private getPath;
16
+ }
@@ -0,0 +1,77 @@
1
+ /**
2
+ * Per-channel conversation metadata (conversation id, DM vs group, sender): cached in memory and
3
+ * persisted under the channel's state directory, so a card or plain message can be routed after a
4
+ * restart or after the in-memory cache was reclaimed.
5
+ */
6
+ import { existsSync, mkdirSync, readFileSync } from "fs";
7
+ import { dirname, join } from "path";
8
+ import { getChannelDir } from "../channel/channel-paths.js";
9
+ import * as log from "../log.js";
10
+ import { writeFileAtomicallySync } from "../shared/atomic-file.js";
11
+ import { errorMessage } from "../shared/text-utils.js";
12
+ export class ConversationMetaStore {
13
+ constructor(config,
14
+ /** Marks the channel as recently used, so the idle-cache sweep leaves it alone. */
15
+ touchChannel) {
16
+ this.config = config;
17
+ this.touchChannel = touchChannel;
18
+ // Conversation metadata cache: channelId → metadata
19
+ this.convMeta = new Map();
20
+ }
21
+ get(channelId) {
22
+ this.touchChannel(channelId);
23
+ const cached = this.convMeta.get(channelId);
24
+ if (cached)
25
+ return cached;
26
+ const metaPath = this.getPath(channelId);
27
+ if (!metaPath || !existsSync(metaPath)) {
28
+ return null;
29
+ }
30
+ try {
31
+ const parsed = JSON.parse(readFileSync(metaPath, "utf-8"));
32
+ if (!parsed.conversationId || !parsed.conversationType || !parsed.senderId) {
33
+ return null;
34
+ }
35
+ const meta = {
36
+ conversationId: parsed.conversationId,
37
+ conversationType: parsed.conversationType,
38
+ senderId: parsed.senderId,
39
+ };
40
+ this.convMeta.set(channelId, meta);
41
+ return meta;
42
+ }
43
+ catch (err) {
44
+ log.logWarn("dingtalk.metadata.load_failed", "Conversation metadata load failed", {
45
+ channelId: channelId,
46
+ reason: errorMessage(err),
47
+ });
48
+ return null;
49
+ }
50
+ }
51
+ set(channelId, meta) {
52
+ this.touchChannel(channelId);
53
+ this.convMeta.set(channelId, meta);
54
+ const metaPath = this.getPath(channelId);
55
+ if (!metaPath)
56
+ return;
57
+ try {
58
+ mkdirSync(dirname(metaPath), { recursive: true });
59
+ writeFileAtomicallySync(metaPath, JSON.stringify(meta, null, 2));
60
+ }
61
+ catch (err) {
62
+ log.logWarn("dingtalk.metadata.persist_failed", "Conversation metadata persist failed", {
63
+ channelId: channelId,
64
+ reason: errorMessage(err),
65
+ });
66
+ }
67
+ }
68
+ /** Drop the in-memory entry only; the persisted file stays and is reloaded on demand. */
69
+ evict(channelId) {
70
+ this.convMeta.delete(channelId);
71
+ }
72
+ getPath(channelId) {
73
+ if (!this.config.stateDir)
74
+ return null;
75
+ return join(getChannelDir(this.config.stateDir, channelId), ".channel-meta.json");
76
+ }
77
+ }
@@ -1,7 +1,11 @@
1
+ /**
2
+ * The DingTalk implementation of the delivery contract (`ChannelContext`): per-turn progress, AI-Card
3
+ * streaming or plain messages, and final-answer delivery for one turn.
4
+ */
1
5
  import type { ChannelContext, ProgressStyle } from "../channel/channel-context.js";
2
6
  import type { ChannelEvent } from "../channel/channel-event.js";
3
7
  import type { ChannelStore } from "../channel/store.js";
4
- import type { DingTalkBot } from "./dingtalk.js";
8
+ import type { DingTalkBotPort } from "./handler.js";
5
9
  /**
6
10
  * Build the delivery contract for one turn.
7
11
  *
@@ -11,4 +15,4 @@ import type { DingTalkBot } from "./dingtalk.js";
11
15
  * final answer is unaffected; it is delivered by `respondPlain`/`replaceMessage` either way, so a
12
16
  * background turn that has something to say still says it.
13
17
  */
14
- export declare function createDingTalkContext(event: ChannelEvent, bot: DingTalkBot, store: ChannelStore, progressStyleOverride?: ProgressStyle): ChannelContext;
18
+ export declare function createDingTalkContext(event: ChannelEvent, bot: DingTalkBotPort, store: ChannelStore, progressStyleOverride?: ProgressStyle): ChannelContext;
@@ -1,4 +1,5 @@
1
1
  import * as log from "../log.js";
2
+ import { formatElapsedZh } from "../shared/format.js";
2
3
  import { errorMessage } from "../shared/text-utils.js";
3
4
  const MIN_UPDATE_INTERVAL_MS = 800;
4
5
  const ROLLING_WINDOW_SIZE = 3;
@@ -76,7 +77,10 @@ class ChannelDeliveryController {
76
77
  }
77
78
  const delivered = await this.bot.sendPlain(this.event.channelId, text);
78
79
  if (!delivered) {
79
- log.logWarning(`[${this.event.channelId}] Failed to send light notice`, text.substring(0, 200));
80
+ log.logWarn("delivery.notice.failed", "Light notice delivery failed", {
81
+ channelId: this.event.channelId,
82
+ fields: { text: text.substring(0, 200) },
83
+ });
80
84
  }
81
85
  },
82
86
  setTyping: async (_isTyping) => { },
@@ -117,7 +121,10 @@ class ChannelDeliveryController {
117
121
  }
118
122
  archiveBotResponse(text) {
119
123
  void this.store.logBotResponse(this.event.channelId, text, Date.now().toString()).catch((err) => {
120
- log.logWarning(`[${this.event.channelId}] Failed to archive bot response`, errorMessage(err));
124
+ log.logWarn("channel.archive.write_failed", "Bot response archive failed", {
125
+ channelId: this.event.channelId,
126
+ reason: errorMessage(err),
127
+ });
121
128
  });
122
129
  }
123
130
  async appendProgress(text, shouldLog) {
@@ -275,7 +282,7 @@ class ChannelDeliveryController {
275
282
  if (content || this.cardWarmupTriggered) {
276
283
  const finalProgressText = this.progressStyle === "rolling"
277
284
  ? this.buildSummaryText()
278
- : [body, "答复已发送。"].filter(Boolean).join("\n\n");
285
+ : [body, "已答复。"].filter(Boolean).join("\n\n");
279
286
  touchedRemote = await this.bot.finalizeExistingCard(this.event.channelId, finalProgressText, this.cardGeneration);
280
287
  }
281
288
  }
@@ -287,12 +294,15 @@ class ChannelDeliveryController {
287
294
  }
288
295
  else if (mode === "silent") {
289
296
  if (content) {
290
- touchedRemote = await this.bot.finalizeExistingCard(this.event.channelId, [body, "处理已结束。"].filter(Boolean).join("\n\n"), this.cardGeneration);
297
+ touchedRemote = await this.bot.finalizeExistingCard(this.event.channelId, [body, "已处理,无需答复。"].filter(Boolean).join("\n\n"), this.cardGeneration);
291
298
  }
292
299
  }
293
300
  }
294
301
  catch (err) {
295
- log.logWarning(`[${this.event.channelId}] Delivery sync failed`, errorMessage(err));
302
+ log.logWarn("delivery.sync.failed", "Delivery sync failed", {
303
+ channelId: this.event.channelId,
304
+ reason: errorMessage(err),
305
+ });
296
306
  if (mode === "progress") {
297
307
  this.progressFailures++;
298
308
  this.replayRequired = true;
@@ -335,7 +345,10 @@ class ChannelDeliveryController {
335
345
  this.flushWaiters.push(resolve);
336
346
  deadlineTimer = setTimeout(() => {
337
347
  if (this.flushWaiters.includes(resolve)) {
338
- log.logWarning(`[${this.event.channelId}] Delivery flush deadline exceeded (${FLUSH_DEADLINE_MS}ms); releasing caller`);
348
+ log.logWarn("delivery.flush.timeout", "Delivery flush deadline exceeded; releasing caller", {
349
+ channelId: this.event.channelId,
350
+ fields: { deadlineMs: FLUSH_DEADLINE_MS },
351
+ });
339
352
  this.flushWaiters = this.flushWaiters.filter((waiter) => waiter !== resolve);
340
353
  resolve();
341
354
  }
@@ -369,25 +382,26 @@ class ChannelDeliveryController {
369
382
  this.progressTextDirty = false;
370
383
  return this.cachedProgressText;
371
384
  }
372
- formatElapsed(ms) {
385
+ /** Clock-style elapsed time (`0:42`, `1:02`, `1:05:09`) for the narrow rolling header. */
386
+ formatClock(ms) {
373
387
  const seconds = Math.max(0, Math.round(ms / 1000));
374
- if (seconds < 60)
375
- return `${seconds}s`;
376
388
  const minutes = Math.floor(seconds / 60);
389
+ const ss = String(seconds % 60).padStart(2, "0");
377
390
  if (minutes < 60)
378
- return `${minutes}m${String(seconds % 60).padStart(2, "0")}s`;
379
- return `${Math.floor(minutes / 60)}h${String(minutes % 60).padStart(2, "0")}m`;
391
+ return `${minutes}:${ss}`;
392
+ return `${Math.floor(minutes / 60)}:${String(minutes % 60).padStart(2, "0")}:${ss}`;
380
393
  }
381
394
  elapsedMs() {
382
395
  return this.progressStartedAt > 0 ? Date.now() - this.progressStartedAt : 0;
383
396
  }
384
397
  /**
385
398
  * Standing first line for rolling mode. The window only keeps the last few entries, so a long
386
- * turn otherwise gave no way to tell "still working, 14 steps in" from "stuck": every visible
387
- * line looked the same as a minute ago. The numbers are already tracked for the closing summary.
399
+ * turn otherwise gave no way to tell "still working, 14 tool calls in" from "stuck": every
400
+ * visible line looked the same as a minute ago. The numbers are already tracked for the closing
401
+ * summary. Counted as tool calls, never "steps" — a step is a task's unit (spec 053, D4).
388
402
  */
389
403
  buildRollingHeader() {
390
- return `⏱ ${this.formatElapsed(this.elapsedMs())} · ${this.toolCallCount} 步`;
404
+ return `⏱ ${this.formatClock(this.elapsedMs())} · 工具 ${this.toolCallCount}`;
391
405
  }
392
406
  trimToRecentEntries(maxEntries) {
393
407
  let entryCount = 0;
@@ -415,7 +429,7 @@ class ChannelDeliveryController {
415
429
  this.sentProgressChars = 0;
416
430
  }
417
431
  buildSummaryText() {
418
- return `完成 · ${this.toolCallCount} 步 · ${this.formatElapsed(this.elapsedMs())}`;
432
+ return `完成 · 工具调用 ${this.toolCallCount} 次 · ${formatElapsedZh(this.elapsedMs())}`;
419
433
  }
420
434
  }
421
435
  /**
@@ -0,0 +1,90 @@
1
+ /**
2
+ * The contract between the DingTalk transport and the runtime that drives it: what the runtime
3
+ * implements (`DingTalkHandler`) and the slice of the bot it may call back into (`DingTalkBotPort`).
4
+ * Declared here, below `bot.ts`, so the bot and the runtime both depend on it and not on each other.
5
+ */
6
+ import type { FinalDelivery, ProgressStyle } from "../channel/channel-context.js";
7
+ import type { ChannelEvent, InboundImage } from "../channel/channel-event.js";
8
+ import type { ChannelObservation } from "../channel/channel-index.js";
9
+ import type { RuntimeCommandName } from "../commands/catalog.js";
10
+ import type { BusyMessageMode } from "./config.js";
11
+ /**
12
+ * `DingTalkEvent` is kept as the public name (spec 035 D4: `src/index.ts`'s barrel is a
13
+ * compatibility promise, so exported names there stay stable). Internally the type now lives in
14
+ * `channel-event.ts` as `ChannelEvent`: most producers of this shape are not DingTalk at all
15
+ * (jobs/manager, task-driver, events, subagents/runs all synthesize wakes), so `ChannelEvent` is
16
+ * what the rest of the runtime imports.
17
+ */
18
+ export type DingTalkEvent = ChannelEvent;
19
+ export type BusyMessageResult = {
20
+ kind: "handled";
21
+ } | {
22
+ kind: "requeue";
23
+ text: string;
24
+ };
25
+ /**
26
+ * What `/stop` actually did. Stopping a task-driven turn also pauses that task, which the user
27
+ * has to be told: a disabled task is never picked up again until `/tasks resume <id>`, so silence
28
+ * here reads as "the turn was interrupted" while the whole task has in fact gone quiet.
29
+ */
30
+ export interface StopOutcome {
31
+ pausedTaskId?: string;
32
+ }
33
+ /**
34
+ * The part of `DingTalkBot` that the runtime's handler and the delivery controller use. `DingTalkBot`
35
+ * implements it; keeping it structural lets this contract stay free of an import cycle with the bot.
36
+ */
37
+ export interface DingTalkBotPort {
38
+ readonly progressStyle: ProgressStyle;
39
+ readonly finalDelivery: FinalDelivery;
40
+ sendPlain(channelId: string, text: string, opts?: {
41
+ title?: string;
42
+ markdown?: boolean;
43
+ }): Promise<boolean>;
44
+ getCardGeneration(channelId: string): symbol;
45
+ isCardGenerationCurrent(channelId: string, generation: symbol): boolean;
46
+ replaceCard(channelId: string, content: string, finalize?: boolean, failed?: boolean, generation?: symbol): Promise<boolean>;
47
+ appendToCard(channelId: string, content: string, finalize?: boolean, failed?: boolean, generation?: symbol): Promise<boolean>;
48
+ finalizeCard(channelId: string, content: string, generation?: symbol): Promise<boolean>;
49
+ finalizeExistingCard(channelId: string, content: string, generation?: symbol): Promise<boolean>;
50
+ discardCard(channelId: string, generation?: symbol): void;
51
+ clearPendingMessages(channelId: string): number;
52
+ resetChannelQueue(channelId: string): number;
53
+ }
54
+ export interface DingTalkHandler {
55
+ isRunning(channelId: string): boolean;
56
+ /**
57
+ * Note that a real person just wrote in this channel. Called once per accepted inbound
58
+ * message, before any busy/command routing, and never for synthetic wakes — see the
59
+ * maintenance contract in `channel-index.ts`. Must stay synchronous and cheap.
60
+ */
61
+ noteChannelActivity?(observation: ChannelObservation): void;
62
+ /**
63
+ * Synchronously reserve an inbound turn before the queued async body yields.
64
+ * The transport calls this hook, when provided, immediately before `handleEvent`.
65
+ */
66
+ reserveEvent?(event: DingTalkEvent): void;
67
+ handleEvent(event: DingTalkEvent, bot: DingTalkBotPort, isEvent?: boolean): Promise<void>;
68
+ handleStop(channelId: string, bot: DingTalkBotPort): Promise<StopOutcome>;
69
+ /** `/new` bypasses the old per-channel queue and live SDK session. */
70
+ handleNewSession(event: DingTalkEvent, bot: DingTalkBotPort): Promise<void>;
71
+ /**
72
+ * Render one of the stateless report commands (events/tasks/status/usage/context/subagents) to
73
+ * text. Single dispatch point shared by the busy-turn switch below and bootstrap's idle-turn
74
+ * switch — both used to hand-copy the same six-case table.
75
+ */
76
+ runRuntimeCommand(event: DingTalkEvent, name: RuntimeCommandName, args: string): Promise<string>;
77
+ handleBusyMessage(event: DingTalkEvent, bot: DingTalkBotPort, mode: BusyMessageMode, queueText: string): Promise<BusyMessageResult>;
78
+ /**
79
+ * Persist one downloaded inbound image under the channel's `inbox/` (spec 049). Owned by
80
+ * bootstrap — it holds the workspace root — not the transport, which only knows how to fetch
81
+ * bytes over the DingTalk API. `mimeType` is `null` when magic-byte sniffing did not recognize
82
+ * a supported image format; the file is still persisted (for the archive/record) but the
83
+ * transport excludes it from the model-facing text marker. Returns `null` on a local I/O
84
+ * failure, surfaced to the user as "保存失败" — the rest of the message is still delivered.
85
+ */
86
+ persistInboundImage?(channelId: string, image: {
87
+ data: Buffer;
88
+ mimeType: string | null;
89
+ }): Promise<InboundImage | null>;
90
+ }
@@ -0,0 +1 @@
1
+ export {};