@oyasmi/pipiclaw 0.9.4-beta.1 → 0.9.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (291) hide show
  1. package/dist/agent/builtin-commands.d.ts +19 -0
  2. package/dist/agent/builtin-commands.js +80 -0
  3. package/dist/agent/channel-runner.d.ts +20 -208
  4. package/dist/agent/channel-runner.js +148 -1245
  5. package/dist/agent/maintenance-context.d.ts +1 -1
  6. package/dist/agent/maintenance-context.js +1 -1
  7. package/dist/agent/prompt/resources.d.ts +3 -0
  8. package/dist/agent/prompt/resources.js +7 -1
  9. package/dist/agent/runner-factory.d.ts +1 -43
  10. package/dist/agent/{command-extension.d.ts → session/command-extension.d.ts} +4 -0
  11. package/dist/agent/{command-extension.js → session/command-extension.js} +5 -5
  12. package/dist/agent/{type-guards.d.ts → session/event-guards.d.ts} +2 -2
  13. package/dist/agent/{type-guards.js → session/event-guards.js} +5 -1
  14. package/dist/agent/session/model-selection.d.ts +47 -0
  15. package/dist/agent/session/model-selection.js +99 -0
  16. package/dist/agent/{session-adapter.d.ts → session/session-adapter.d.ts} +21 -1
  17. package/dist/agent/{session-adapter.js → session/session-adapter.js} +83 -1
  18. package/dist/agent/{session-events.d.ts → session/session-events.d.ts} +9 -5
  19. package/dist/agent/{session-events.js → session/session-events.js} +10 -10
  20. package/dist/agent/session/session-host.d.ts +200 -0
  21. package/dist/agent/session/session-host.js +621 -0
  22. package/dist/agent/{session-resource-gate.js → session/session-resource-gate.js} +2 -2
  23. package/dist/agent/{context-budget.js → turn/context-budget.js} +5 -1
  24. package/dist/agent/{progress-formatter.d.ts → turn/progress-formatter.d.ts} +4 -1
  25. package/dist/agent/{run-queue.d.ts → turn/run-queue.d.ts} +1 -1
  26. package/dist/agent/{run-queue.js → turn/run-queue.js} +3 -3
  27. package/dist/{memory → agent/turn}/task-digest.js +4 -4
  28. package/dist/agent/turn/turn-context.d.ts +14 -0
  29. package/dist/agent/turn/turn-context.js +64 -0
  30. package/dist/agent/turn/turn-finish.d.ts +50 -0
  31. package/dist/agent/turn/turn-finish.js +188 -0
  32. package/dist/agent/turn/turn-input.d.ts +43 -0
  33. package/dist/agent/turn/turn-input.js +79 -0
  34. package/dist/agent/turn/turn-pipeline.d.ts +68 -0
  35. package/dist/agent/turn/turn-pipeline.js +257 -0
  36. package/dist/agent/{turn-prompt.d.ts → turn/turn-prompt.d.ts} +2 -2
  37. package/dist/agent/{turn-prompt.js → turn/turn-prompt.js} +6 -2
  38. package/dist/agent/{turn-recovery.js → turn/turn-recovery.js} +1 -1
  39. package/dist/agent/{turn-state.d.ts → turn/turn-state.d.ts} +1 -1
  40. package/dist/agent/types.d.ts +43 -2
  41. package/dist/agent/types.js +1 -1
  42. package/dist/{models/auth-cli.d.ts → app/auth-command.d.ts} +1 -1
  43. package/dist/{models/auth-cli.js → app/auth-command.js} +11 -8
  44. package/dist/{runtime/app-home.d.ts → app/home.d.ts} +0 -2
  45. package/dist/{runtime/app-home.js → app/home.js} +4 -75
  46. package/dist/{app-services.d.ts → app/services.d.ts} +5 -5
  47. package/dist/{app-services.js → app/services.js} +10 -10
  48. package/dist/channel/channel-context.d.ts +12 -2
  49. package/dist/channel/channel-context.js +29 -2
  50. package/dist/channel/channel-event.d.ts +10 -2
  51. package/dist/channel/channel-event.js +1 -1
  52. package/dist/{runtime/project-commands.d.ts → channel/commands.d.ts} +1 -1
  53. package/dist/{runtime/project-commands.js → channel/commands.js} +1 -1
  54. package/dist/channel/store.js +4 -0
  55. package/dist/commands/catalog.d.ts +3 -3
  56. package/dist/commands/catalog.js +3 -3
  57. package/dist/{runtime/report-commands.d.ts → commands/router.d.ts} +10 -3
  58. package/dist/{runtime/report-commands.js → commands/router.js} +5 -5
  59. package/dist/{settings.d.ts → config/settings.d.ts} +7 -8
  60. package/dist/{settings.js → config/settings.js} +7 -10
  61. package/dist/{tools/config.d.ts → config/tools.d.ts} +1 -2
  62. package/dist/{tools/config.js → config/tools.js} +5 -2
  63. package/dist/dingtalk/access-token.d.ts +12 -0
  64. package/dist/dingtalk/access-token.js +51 -0
  65. package/dist/dingtalk/api.d.ts +19 -0
  66. package/dist/dingtalk/api.js +67 -0
  67. package/dist/dingtalk/bot.d.ts +97 -0
  68. package/dist/dingtalk/bot.js +389 -0
  69. package/dist/dingtalk/cards.d.ts +56 -0
  70. package/dist/dingtalk/cards.js +318 -0
  71. package/dist/{runtime → dingtalk}/channel-queue.js +3 -0
  72. package/dist/dingtalk/config.d.ts +19 -0
  73. package/dist/dingtalk/config.js +95 -0
  74. package/dist/dingtalk/connection.d.ts +57 -0
  75. package/dist/dingtalk/connection.js +356 -0
  76. package/dist/dingtalk/conversation-meta.d.ts +16 -0
  77. package/dist/dingtalk/conversation-meta.js +77 -0
  78. package/dist/{runtime → dingtalk}/delivery.d.ts +6 -2
  79. package/dist/dingtalk/handler.d.ts +90 -0
  80. package/dist/dingtalk/handler.js +1 -0
  81. package/dist/dingtalk/inbound.d.ts +66 -0
  82. package/dist/dingtalk/inbound.js +137 -0
  83. package/dist/dingtalk/media.d.ts +66 -0
  84. package/dist/dingtalk/media.js +214 -0
  85. package/dist/events/{event-commands.js → commands.js} +6 -2
  86. package/dist/events/parse.d.ts +14 -0
  87. package/dist/events/parse.js +114 -0
  88. package/dist/events/types.d.ts +93 -0
  89. package/dist/events/types.js +1 -0
  90. package/dist/events/{event-validation.d.ts → validation.d.ts} +1 -1
  91. package/dist/events/watcher.d.ts +67 -0
  92. package/dist/events/{events.js → watcher.js} +6 -109
  93. package/dist/index.d.ts +6 -4
  94. package/dist/index.js +2 -2
  95. package/dist/jobs/launch.d.ts +42 -0
  96. package/dist/jobs/launch.js +118 -0
  97. package/dist/{agent/job-manager.d.ts → jobs/manager.d.ts} +1 -67
  98. package/dist/{agent/job-manager.js → jobs/manager.js} +3 -146
  99. package/dist/jobs/record.d.ts +55 -0
  100. package/dist/jobs/record.js +36 -0
  101. package/dist/main.js +2 -2
  102. package/dist/memory/maintenance-gates.d.ts +2 -2
  103. package/dist/memory/maintenance-tuning.d.ts +15 -0
  104. package/dist/memory/maintenance-tuning.js +3 -0
  105. package/dist/memory/reflect-job.d.ts +2 -2
  106. package/dist/memory/reflect-job.js +4 -2
  107. package/dist/memory/scheduler.d.ts +3 -3
  108. package/dist/memory/scheduler.js +2 -1
  109. package/dist/memory/sidecar-worker.js +1 -1
  110. package/dist/memory/transcript.js +1 -1
  111. package/dist/{agent/model-fallback.d.ts → models/fallback.d.ts} +6 -6
  112. package/dist/{agent/model-fallback.js → models/fallback.js} +15 -28
  113. package/dist/models/login-identity.d.ts +2 -0
  114. package/dist/models/login-identity.js +83 -0
  115. package/dist/models/provider-login.d.ts +3 -1
  116. package/dist/models/provider-login.js +8 -2
  117. package/dist/models/reference.d.ts +20 -0
  118. package/dist/models/{utils.js → reference.js} +0 -48
  119. package/dist/models/{utils.d.ts → runtime.d.ts} +1 -16
  120. package/dist/models/runtime.js +52 -0
  121. package/dist/playbooks/catalog.d.ts +6 -2
  122. package/dist/playbooks/catalog.js +9 -6
  123. package/dist/runtime/bootstrap.d.ts +7 -17
  124. package/dist/runtime/bootstrap.js +37 -755
  125. package/dist/runtime/durable-dispatch.d.ts +17 -4
  126. package/dist/runtime/durable-dispatch.js +60 -18
  127. package/dist/runtime/inbound-images.d.ts +18 -0
  128. package/dist/runtime/inbound-images.js +51 -0
  129. package/dist/runtime/shutdown.d.ts +39 -0
  130. package/dist/runtime/shutdown.js +120 -0
  131. package/dist/runtime/stop-watchdog.d.ts +16 -0
  132. package/dist/runtime/stop-watchdog.js +32 -0
  133. package/dist/runtime/task-driver.d.ts +2 -2
  134. package/dist/runtime/task-driver.js +3 -3
  135. package/dist/runtime/task-migration.js +2 -2
  136. package/dist/runtime/task-spawn.d.ts +1 -1
  137. package/dist/runtime/task-spawn.js +1 -1
  138. package/dist/runtime/turn-handler.d.ts +47 -0
  139. package/dist/runtime/turn-handler.js +318 -0
  140. package/dist/runtime/turn-run.d.ts +52 -0
  141. package/dist/runtime/turn-run.js +318 -0
  142. package/dist/security/command-guard.js +4 -0
  143. package/dist/security/network.js +4 -0
  144. package/dist/security/path-guard.js +4 -0
  145. package/dist/security/types.d.ts +1 -2
  146. package/dist/security/types.js +1 -2
  147. package/dist/shared/exact-keys.d.ts +1 -1
  148. package/dist/shared/host-process.js +1 -1
  149. package/dist/shared/wake-claim.d.ts +1 -1
  150. package/dist/{runtime/skill-commands.d.ts → skills/commands.d.ts} +2 -2
  151. package/dist/{runtime/skill-commands.js → skills/commands.js} +1 -1
  152. package/dist/{agent/workspace-resources.js → skills/loader.js} +1 -1
  153. package/dist/{tools/skill-security.js → skills/validation.js} +4 -0
  154. package/dist/skills/workspace.d.ts +33 -0
  155. package/dist/skills/workspace.js +116 -0
  156. package/dist/{runtime/subagent-commands.d.ts → subagents/commands.d.ts} +4 -3
  157. package/dist/{runtime/subagent-commands.js → subagents/commands.js} +2 -2
  158. package/dist/subagents/completion-wake.d.ts +17 -0
  159. package/dist/subagents/completion-wake.js +76 -0
  160. package/dist/subagents/detached-discovery.js +1 -1
  161. package/dist/subagents/discovery.d.ts +1 -1
  162. package/dist/subagents/discovery.js +2 -2
  163. package/dist/subagents/dispatch.d.ts +33 -0
  164. package/dist/subagents/dispatch.js +190 -0
  165. package/dist/subagents/external/dispatch.d.ts +25 -0
  166. package/dist/subagents/external/dispatch.js +90 -0
  167. package/dist/subagents/external/harness.d.ts +1 -1
  168. package/dist/subagents/external/progress-tail.d.ts +1 -1
  169. package/dist/subagents/external/run.d.ts +2 -1
  170. package/dist/subagents/external/run.js +2 -2
  171. package/dist/subagents/external/settlement.d.ts +1 -1
  172. package/dist/subagents/format.d.ts +1 -1
  173. package/dist/subagents/grace.d.ts +24 -0
  174. package/dist/subagents/grace.js +57 -0
  175. package/dist/subagents/internal/outcome.d.ts +24 -0
  176. package/dist/subagents/internal/outcome.js +149 -0
  177. package/dist/subagents/internal/provider-retry.d.ts +19 -0
  178. package/dist/subagents/internal/provider-retry.js +83 -0
  179. package/dist/subagents/internal/run.d.ts +31 -0
  180. package/dist/subagents/internal/run.js +240 -0
  181. package/dist/subagents/internal/state.d.ts +43 -0
  182. package/dist/subagents/internal/state.js +48 -0
  183. package/dist/subagents/internal/worker.d.ts +51 -0
  184. package/dist/subagents/internal/worker.js +167 -0
  185. package/dist/subagents/result.d.ts +62 -0
  186. package/dist/subagents/result.js +103 -0
  187. package/dist/subagents/run-record.d.ts +222 -0
  188. package/dist/subagents/run-record.js +101 -0
  189. package/dist/subagents/run-registry.d.ts +9 -0
  190. package/dist/subagents/run-registry.js +125 -0
  191. package/dist/subagents/runs.d.ts +7 -243
  192. package/dist/subagents/runs.js +8 -291
  193. package/dist/subagents/task-envelope.d.ts +36 -0
  194. package/dist/subagents/task-envelope.js +168 -0
  195. package/dist/subagents/types.d.ts +154 -0
  196. package/dist/subagents/types.js +1 -0
  197. package/dist/subagents/verification-outcome.d.ts +1 -1
  198. package/dist/tasks/board.d.ts +2 -2
  199. package/dist/tasks/board.js +2 -2
  200. package/dist/tasks/{work-log.d.ts → bound-work.d.ts} +1 -1
  201. package/dist/tasks/{work-log.js → bound-work.js} +1 -1
  202. package/dist/tasks/brief.js +1 -1
  203. package/dist/{runtime/task-commands.d.ts → tasks/commands.d.ts} +1 -1
  204. package/dist/{runtime/task-commands.js → tasks/commands.js} +12 -8
  205. package/dist/tasks/contract-input.d.ts +1 -1
  206. package/dist/tasks/contract-input.js +1 -1
  207. package/dist/tasks/create.js +1 -1
  208. package/dist/tasks/{log.js → loop-log.js} +1 -1
  209. package/dist/tasks/mutation-lock.js +1 -1
  210. package/dist/tasks/session-path.js +1 -1
  211. package/dist/tasks/steer.js +1 -1
  212. package/dist/tasks/store.js +2 -2
  213. package/dist/tools/bash.d.ts +1 -1
  214. package/dist/tools/{tool-details.d.ts → contract/details.d.ts} +2 -2
  215. package/dist/tools/{tool-details.js → contract/details.js} +4 -4
  216. package/dist/tools/{presentation.js → contract/presentation.js} +3 -3
  217. package/dist/tools/event-manage.d.ts +1 -1
  218. package/dist/tools/event-manage.js +4 -4
  219. package/dist/tools/index.d.ts +3 -3
  220. package/dist/tools/index.js +7 -6
  221. package/dist/tools/job.d.ts +1 -1
  222. package/dist/tools/registry.d.ts +7 -7
  223. package/dist/tools/registry.js +6 -6
  224. package/dist/tools/session-search.d.ts +1 -1
  225. package/dist/tools/skill.d.ts +2 -34
  226. package/dist/tools/skill.js +8 -116
  227. package/dist/tools/subagent-manage.js +4 -3
  228. package/dist/tools/subagent.d.ts +46 -0
  229. package/dist/tools/subagent.js +127 -0
  230. package/dist/tools/{task-manage.d.ts → task-manage/factory.d.ts} +7 -3
  231. package/dist/tools/{task-manage.js → task-manage/factory.js} +7 -7
  232. package/dist/tools/task-manage/lifecycle.js +2 -2
  233. package/dist/tools/task-manage/log-view.js +2 -2
  234. package/dist/tools/task-manage/shared.js +3 -3
  235. package/dist/tools/task-manage/step-end.js +3 -3
  236. package/dist/tools/task-manage/types.d.ts +1 -1
  237. package/dist/tools/web-fetch.d.ts +1 -1
  238. package/dist/tools/web-search.d.ts +1 -1
  239. package/dist/tui/app.d.ts +1 -1
  240. package/dist/tui/app.js +6 -6
  241. package/dist/tui/cli.d.ts +1 -1
  242. package/dist/tui/cli.js +1 -1
  243. package/dist/tui/frontend.d.ts +44 -0
  244. package/dist/tui/frontend.js +13 -0
  245. package/dist/tui/pitui-frontend.d.ts +1 -1
  246. package/dist/tui/plain-frontend.d.ts +1 -1
  247. package/dist/tui/renderer.d.ts +3 -42
  248. package/dist/tui/terminal-context.d.ts +2 -2
  249. package/dist/tui/terminal-media-sender.d.ts +1 -1
  250. package/dist/tui/turn-controller.d.ts +1 -1
  251. package/dist/usage/ledger.js +4 -0
  252. package/dist/{shared/types.d.ts → usage/totals.d.ts} +3 -0
  253. package/dist/web/client.d.ts +5 -1
  254. package/dist/web/client.js +4 -0
  255. package/dist/web/config.d.ts +1 -1
  256. package/dist/web/fetch.d.ts +1 -1
  257. package/dist/web/search-providers.d.ts +1 -1
  258. package/dist/web/search.d.ts +1 -1
  259. package/package.json +10 -7
  260. package/dist/events/events.d.ts +0 -159
  261. package/dist/runtime/dingtalk.d.ts +0 -272
  262. package/dist/runtime/dingtalk.js +0 -1470
  263. package/dist/subagents/tool.d.ts +0 -213
  264. package/dist/subagents/tool.js +0 -1282
  265. /package/dist/{runtime → agent/prompt}/workspace-templates.d.ts +0 -0
  266. /package/dist/{runtime → agent/prompt}/workspace-templates.js +0 -0
  267. /package/dist/agent/{session-resource-gate.d.ts → session/session-resource-gate.d.ts} +0 -0
  268. /package/dist/agent/{context-budget.d.ts → turn/context-budget.d.ts} +0 -0
  269. /package/dist/agent/{progress-formatter.js → turn/progress-formatter.js} +0 -0
  270. /package/dist/{memory → agent/turn}/task-digest.d.ts +0 -0
  271. /package/dist/agent/{turn-error.d.ts → turn/turn-error.d.ts} +0 -0
  272. /package/dist/agent/{turn-error.js → turn/turn-error.js} +0 -0
  273. /package/dist/agent/{turn-recovery.d.ts → turn/turn-recovery.d.ts} +0 -0
  274. /package/dist/agent/{turn-state.js → turn/turn-state.js} +0 -0
  275. /package/dist/{runtime → app}/proxy.d.ts +0 -0
  276. /package/dist/{runtime → app}/proxy.js +0 -0
  277. /package/dist/{runtime → dingtalk}/channel-queue.d.ts +0 -0
  278. /package/dist/{runtime → dingtalk}/delivery.js +0 -0
  279. /package/dist/{runtime → dingtalk}/inbound-media.d.ts +0 -0
  280. /package/dist/{runtime → dingtalk}/inbound-media.js +0 -0
  281. /package/dist/events/{event-commands.d.ts → commands.d.ts} +0 -0
  282. /package/dist/events/{event-validation.js → validation.js} +0 -0
  283. /package/dist/{agent/workspace-resources.d.ts → skills/loader.d.ts} +0 -0
  284. /package/dist/{tools/skill-security.d.ts → skills/validation.d.ts} +0 -0
  285. /package/dist/tasks/{ledger.d.ts → contract.d.ts} +0 -0
  286. /package/dist/tasks/{ledger.js → contract.js} +0 -0
  287. /package/dist/tasks/{log.d.ts → loop-log.d.ts} +0 -0
  288. /package/dist/tools/{subagent-tool-names.d.ts → contract/names.d.ts} +0 -0
  289. /package/dist/tools/{subagent-tool-names.js → contract/names.js} +0 -0
  290. /package/dist/tools/{presentation.d.ts → contract/presentation.d.ts} +0 -0
  291. /package/dist/{shared/types.js → usage/totals.js} +0 -0
@@ -0,0 +1,389 @@
1
+ /**
2
+ * DingTalk transport facade: owns the per-channel queues and the public surface the runtime and the
3
+ * delivery controller call. The Stream socket, access token, AI cards, media and inbound parsing
4
+ * are separate collaborators (`connection.ts`, `access-token.ts`, `cards.ts`, `media.ts`,
5
+ * `inbound.ts`) that this class wires together and forwards to.
6
+ */
7
+ import { finalDeliveryOf, normalizeResponseMode, progressStyleOf, } from "../channel/channel-context.js";
8
+ import { formatBusyHint, parseBuiltInCommand, renderBuiltInHelp, slashCommandName } from "../commands/catalog.js";
9
+ import * as log from "../log.js";
10
+ import { AccessTokenProvider } from "./access-token.js";
11
+ import { sendRobotMessage } from "./api.js";
12
+ import { CardController } from "./cards.js";
13
+ // Turn serialization is runtime policy; the queue lives in its own module and
14
+ // this transport only consumes it.
15
+ import { ChannelQueue } from "./channel-queue.js";
16
+ import { normalizeBusyMessageDefault } from "./config.js";
17
+ import { StreamConnection } from "./connection.js";
18
+ import { ConversationMetaStore } from "./conversation-meta.js";
19
+ import { InboundMessages } from "./inbound.js";
20
+ import { DingTalkMedia } from "./media.js";
21
+ // Bounds enqueueStreamMessage (user messages + busy-message requeues), mirroring the
22
+ // existing cap on enqueueEvent. Without a limit, a busy channel getting flooded with
23
+ // messages (or repeated followUp requeues) grows this queue without bound — each item
24
+ // still runs a full serialized turn, so an unbounded queue means unbounded backlog time
25
+ // and unbounded memory, not just a slow channel.
26
+ const USER_MESSAGE_QUEUE_LIMIT = 20;
27
+ const EVENT_QUEUE_LIMIT = 5;
28
+ // Channel metadata is persisted on disk, so these in-memory caches can be safely
29
+ // reclaimed after inactivity. A stale unfinished card falls back to a fresh card
30
+ // on the next update rather than retaining one channel forever.
31
+ const CHANNEL_CACHE_TTL_MS = 60 * 60 * 1000;
32
+ const CHANNEL_CACHE_SWEEP_MS = 10 * 60 * 1000;
33
+ export class DingTalkBot {
34
+ constructor(handler, config) {
35
+ this.channelLastActiveAt = new Map();
36
+ // Per-channel queues
37
+ this.queues = new Map();
38
+ this.channelCacheSweepTimer = null;
39
+ this.isStopped = false;
40
+ this.handler = handler;
41
+ this.config = {
42
+ ...config,
43
+ busyMessageDefault: normalizeBusyMessageDefault(config.busyMessageDefault),
44
+ responseMode: normalizeResponseMode(config.responseMode),
45
+ cardAutoLayout: config.cardAutoLayout ?? true,
46
+ };
47
+ this.channelCacheSweepTimer = setInterval(() => this.cleanupIdleChannelCaches(), CHANNEL_CACHE_SWEEP_MS);
48
+ this.channelCacheSweepTimer.unref?.();
49
+ this.tokens = new AccessTokenProvider(this.config);
50
+ this.conversations = new ConversationMetaStore(this.config, (channelId) => this.touchChannel(channelId));
51
+ const getAccessToken = () => this.tokens.get();
52
+ const sendRobot = (meta, msgKey, msgParam) => sendRobotMessage({ config: this.config, getAccessToken }, meta, msgKey, msgParam);
53
+ this.cards = new CardController({
54
+ config: this.config,
55
+ getAccessToken,
56
+ getConversationMeta: (channelId) => this.conversations.get(channelId),
57
+ sendPlain: (channelId, text) => this.sendPlain(channelId, text),
58
+ });
59
+ this.media = new DingTalkMedia({
60
+ config: this.config,
61
+ handler: this.handler,
62
+ getAccessToken,
63
+ getConversationMeta: (channelId) => this.conversations.get(channelId),
64
+ sendRobotMessage: sendRobot,
65
+ downloadMessageFile: (downloadCode) => this.downloadMessageFile(downloadCode),
66
+ });
67
+ this.connection = new StreamConnection({
68
+ clientId: this.config.clientId,
69
+ clientSecret: this.config.clientSecret,
70
+ isStopped: () => this.isStopped,
71
+ onRawMessage: (msg) => this.inbound.handleRawMessage(msg),
72
+ });
73
+ this.inbound = new InboundMessages({
74
+ config: this.config,
75
+ handler: this.handler,
76
+ conversations: this.conversations,
77
+ isStopped: () => this.isStopped,
78
+ ack: (messageId) => this.connection.ack(messageId),
79
+ resolveInboundAttachments: (channelId, parsed) => this.media.resolveInboundAttachments(channelId, parsed),
80
+ routeInboundEvent: (event) => this.routeInboundEvent(event),
81
+ });
82
+ }
83
+ get busyMessageDefault() {
84
+ return normalizeBusyMessageDefault(this.config.busyMessageDefault);
85
+ }
86
+ get responseMode() {
87
+ return normalizeResponseMode(this.config.responseMode);
88
+ }
89
+ get progressStyle() {
90
+ return progressStyleOf(this.responseMode);
91
+ }
92
+ get finalDelivery() {
93
+ return finalDeliveryOf(this.responseMode);
94
+ }
95
+ // ==========================================================================
96
+ // Public API
97
+ // ==========================================================================
98
+ async start() {
99
+ if (!this.config.clientId || !this.config.clientSecret) {
100
+ log.logWarn("dingtalk.config.missing_credentials", "clientId / clientSecret not configured");
101
+ return;
102
+ }
103
+ if (!this.config.cardTemplateId) {
104
+ log.logWarn("dingtalk.config.missing_card_template", "cardTemplateId not configured; AI Card streaming is off");
105
+ }
106
+ log.logEvent("info", "runtime.dingtalk.connecting", "Initializing stream client", {
107
+ fields: { clientIdPrefix: this.config.clientId.substring(0, 8) },
108
+ });
109
+ await this.connection.start();
110
+ }
111
+ async stop() {
112
+ log.logInfoEvent("dingtalk.bot.stopping", "Stopping bot");
113
+ this.isStopped = true;
114
+ this.connection.clearAllTimers();
115
+ if (this.channelCacheSweepTimer) {
116
+ clearInterval(this.channelCacheSweepTimer);
117
+ this.channelCacheSweepTimer = null;
118
+ }
119
+ for (const queue of this.queues.values()) {
120
+ queue.stop();
121
+ }
122
+ await this.connection.disconnect();
123
+ }
124
+ /**
125
+ * Enqueue an event for processing.
126
+ * Returns true if enqueued, false if queue is full (max 5).
127
+ */
128
+ enqueueEvent(event) {
129
+ if (this.isStopped) {
130
+ return false;
131
+ }
132
+ const queue = this.getQueue(event.channelId);
133
+ if (queue.size() >= EVENT_QUEUE_LIMIT) {
134
+ log.logEvent("warn", "runtime.channel_queue.full", "Discarding incoming event", {
135
+ ctx: { channelId: event.channelId, userName: event.userName },
136
+ fields: { messageLength: event.text.length },
137
+ });
138
+ return false;
139
+ }
140
+ log.logEvent("debug", "runtime.channel_queue.enqueued", "Incoming event queued", {
141
+ ctx: { channelId: event.channelId, userName: event.userName },
142
+ fields: { messageLength: event.text.length },
143
+ });
144
+ queue.enqueue(async () => {
145
+ this.connection.beginMessageProcessing();
146
+ try {
147
+ this.handler.reserveEvent?.(event);
148
+ await this.handler.handleEvent(event, this, true);
149
+ }
150
+ finally {
151
+ this.connection.endMessageProcessing();
152
+ }
153
+ });
154
+ return true;
155
+ }
156
+ enqueueStreamMessage(event, textOverride) {
157
+ const queuedEvent = textOverride === undefined ? event : { ...event, text: textOverride };
158
+ const queue = this.getQueue(event.channelId);
159
+ if (queue.size() >= USER_MESSAGE_QUEUE_LIMIT) {
160
+ log.logWarn("dingtalk.queue.full", "Message discarded: channel queue full", {
161
+ channelId: event.channelId,
162
+ fields: { limit: USER_MESSAGE_QUEUE_LIMIT, preview: queuedEvent.text.substring(0, 50) },
163
+ });
164
+ this.sendPlain(event.channelId, `⚠️ 消息积压过多(超过 ${USER_MESSAGE_QUEUE_LIMIT} 条待处理),本条消息已丢弃,请稍后重试。`).catch(() => undefined);
165
+ return;
166
+ }
167
+ queue.enqueue(async () => {
168
+ this.connection.beginMessageProcessing();
169
+ try {
170
+ this.handler.reserveEvent?.(queuedEvent);
171
+ await this.handler.handleEvent(queuedEvent, this);
172
+ }
173
+ finally {
174
+ this.connection.endMessageProcessing();
175
+ }
176
+ });
177
+ }
178
+ // ==========================================================================
179
+ // AI Card operations (see cards.ts)
180
+ // ==========================================================================
181
+ /** Capture the current turn's identity; close, /stop and /new invalidate it. */
182
+ getCardGeneration(channelId) {
183
+ return this.cards.getCardGeneration(channelId);
184
+ }
185
+ isCardGenerationCurrent(channelId, generation) {
186
+ return this.cards.isCardGenerationCurrent(channelId, generation);
187
+ }
188
+ /** Get or create an AI card without joining an earlier turn's in-flight creation. */
189
+ async ensureCard(channelId, generation) {
190
+ return this.cards.ensureCard(channelId, generation);
191
+ }
192
+ /** Replace the active card content with a full snapshot. */
193
+ async replaceCard(channelId, content, finalize = false, failed = false, generation) {
194
+ return this.cards.replaceCard(channelId, content, finalize, failed, generation);
195
+ }
196
+ /** Append a delta to the active card transcript. */
197
+ async appendToCard(channelId, content, finalize = false, failed = false, generation) {
198
+ return this.cards.appendToCard(channelId, content, finalize, failed, generation);
199
+ }
200
+ /** Finalize and remove the active card for a channel. */
201
+ async finalizeCard(channelId, content, generation) {
202
+ return this.cards.finalizeCard(channelId, content, generation);
203
+ }
204
+ /** Finish progress only: never create a card or send a fallback chat message. */
205
+ async finalizeExistingCard(channelId, content, generation) {
206
+ return this.cards.finalizeExistingCard(channelId, content, generation);
207
+ }
208
+ /** Invalidate this turn's local state. This is not a remote message deletion. */
209
+ discardCard(channelId, generation) {
210
+ this.cards.discardCard(channelId, generation);
211
+ }
212
+ /**
213
+ * Send a normal message natively mapping DM and Group to correct endpoints (fallback when no card).
214
+ *
215
+ * Only the message shape is decided here; the DM-vs-group routing and the POST itself belong to
216
+ * `sendRobotMessage`, which every other outbound message type already goes through.
217
+ *
218
+ * `opts` lets a caller that already knows what it produced (a command reply) state the format
219
+ * and a real title instead of the regex guess below, which exists only for callers — free-form
220
+ * notices, `replaceWithFinal` — that do not know their own content ahead of time (review
221
+ * 2026-08-24 §1.3c).
222
+ */
223
+ async sendPlain(channelId, text, opts) {
224
+ const meta = this.conversations.get(channelId);
225
+ if (!meta) {
226
+ log.logWarn("dingtalk.send.no_metadata", "Plain message not sent: no conversation metadata", {
227
+ channelId: channelId,
228
+ });
229
+ return false;
230
+ }
231
+ const hasMarkdown = opts?.markdown ?? /^#{1,6}\s|^\s*[-*]\s|\*\*.*\*\*|```|`[^`]+`|\[.*?\]\(.*?\)/m.test(text);
232
+ const title = opts?.title ?? "Bot";
233
+ const msgKey = hasMarkdown ? "sampleMarkdown" : "sampleText";
234
+ const msgParam = hasMarkdown ? JSON.stringify({ text, title }) : JSON.stringify({ content: text });
235
+ return sendRobotMessage({ config: this.config, getAccessToken: () => this.tokens.get() }, meta, msgKey, msgParam);
236
+ }
237
+ // ==========================================================================
238
+ // Media (image / file) delivery — MediaSender contract (see media.ts)
239
+ // ==========================================================================
240
+ sendMedia(channelId, media) {
241
+ return this.media.sendMedia(channelId, media);
242
+ }
243
+ /**
244
+ * Inbound file fetch used while resolving attachments (`media.ts`). `protected` so the
245
+ * deterministic e2e harness can override it and run the inbound path with zero network, the
246
+ * same pattern `HarnessDingTalkBot` already uses for outbound calls.
247
+ */
248
+ downloadMessageFile(downloadCode) {
249
+ return this.media.downloadMessageFile(downloadCode);
250
+ }
251
+ /**
252
+ * Command / busy / `/new` routing for one inbound event, ending in `enqueueStreamMessage`
253
+ * for a normal message. Split out of `onStreamMessage` so the deterministic e2e harness
254
+ * (spec 048) can exercise the real transport queue and busy semantics without a socket.
255
+ */
256
+ async routeInboundEvent(event) {
257
+ const { channelId } = event;
258
+ const content = event.text;
259
+ const builtInCommand = parseBuiltInCommand(content);
260
+ const isSlashCommand = content.trim().startsWith("/");
261
+ // `/new` is an emergency boundary as well as a session command. Route it before
262
+ // busy checking and before the old channel queue, so a wedged compaction/provider
263
+ // request cannot prevent recovery.
264
+ if (slashCommandName(content) === "new") {
265
+ await this.handler.handleNewSession(event, this);
266
+ return;
267
+ }
268
+ // Check if busy
269
+ if (this.handler.isRunning(channelId)) {
270
+ // All built-in transport commands are usable while a task streams.
271
+ if (builtInCommand) {
272
+ switch (builtInCommand.name) {
273
+ case "help":
274
+ await this.sendPlain(channelId, renderBuiltInHelp(builtInCommand.args), {
275
+ title: "/help",
276
+ markdown: true,
277
+ });
278
+ return;
279
+ case "stop": {
280
+ const outcome = await this.handler.handleStop(channelId, this);
281
+ await this.sendPlain(channelId, outcome.pausedTaskId
282
+ ? `已停止当前回合。任务 \`${outcome.pausedTaskId}\` 已暂停,用 \`/tasks resume ${outcome.pausedTaskId}\` 继续。`
283
+ : "已停止当前回合。", { title: "/stop", markdown: true });
284
+ return;
285
+ }
286
+ case "steer":
287
+ case "followup": {
288
+ const mode = builtInCommand.name === "steer" ? "steer" : "followUp";
289
+ const result = await this.handler.handleBusyMessage(event, this, mode, builtInCommand.args);
290
+ if (result.kind === "requeue") {
291
+ this.enqueueStreamMessage(event, result.text);
292
+ }
293
+ return;
294
+ }
295
+ default: {
296
+ // Every remaining BuiltInCommandName is a stateless report (events/tasks/status/usage/
297
+ // context/subagents/project), narrowed to RuntimeCommandName by TS after the four
298
+ // cases above. Busy has no sendCommandReply-style retry semantics, so `/context` is
299
+ // answered here like the rest instead of the runner-handled path idle uses for it
300
+ // (see the IDLE_RUNTIME_COMMAND_NAMES comment in bootstrap.ts).
301
+ const response = await this.handler.runRuntimeCommand(event, builtInCommand.name, builtInCommand.args);
302
+ const delivered = await this.sendPlain(channelId, response, {
303
+ title: `/${builtInCommand.name}`,
304
+ markdown: true,
305
+ });
306
+ if (!delivered) {
307
+ log.logWarn("delivery.command_reply.failed", "Command reply delivery failed", {
308
+ channelId: channelId,
309
+ fields: { command: builtInCommand.name, chars: response.length },
310
+ });
311
+ }
312
+ return;
313
+ }
314
+ }
315
+ }
316
+ // Other session commands (/model, /compact, …) and unknown slash commands cannot
317
+ // run mid-turn: they would need the idle session layer.
318
+ if (isSlashCommand) {
319
+ await this.sendPlain(channelId, formatBusyHint());
320
+ return;
321
+ }
322
+ const result = await this.handler.handleBusyMessage(event, this, this.busyMessageDefault, content);
323
+ if (result.kind === "requeue") {
324
+ this.enqueueStreamMessage(event, result.text);
325
+ }
326
+ return;
327
+ }
328
+ // Enqueue for processing
329
+ this.enqueueStreamMessage(event);
330
+ }
331
+ /**
332
+ * Drop queued-but-not-started messages for a channel (e.g. on /stop) so they
333
+ * do not run after the user halts the current task. Returns dropped count.
334
+ */
335
+ clearPendingMessages(channelId) {
336
+ const queue = this.queues.get(channelId);
337
+ return queue ? queue.clearPending() : 0;
338
+ }
339
+ /**
340
+ * Detach all queued work from the previous session generation. The in-flight callback may
341
+ * still unwind on its old queue object, while subsequent messages get a fresh queue.
342
+ */
343
+ resetChannelQueue(channelId) {
344
+ const queue = this.queues.get(channelId);
345
+ const dropped = queue?.clearPending() ?? 0;
346
+ queue?.stop();
347
+ this.queues.delete(channelId);
348
+ this.discardCard(channelId);
349
+ return dropped;
350
+ }
351
+ /** Test seam (spec 048): true when no channel queue has pending or in-flight work. */
352
+ allChannelQueuesIdle() {
353
+ if (this.inbound.hasPendingIngest())
354
+ return false;
355
+ for (const queue of this.queues.values()) {
356
+ if (!queue.isIdle())
357
+ return false;
358
+ }
359
+ return true;
360
+ }
361
+ getQueue(channelId) {
362
+ this.touchChannel(channelId);
363
+ let queue = this.queues.get(channelId);
364
+ if (!queue) {
365
+ queue = new ChannelQueue();
366
+ this.queues.set(channelId, queue);
367
+ }
368
+ return queue;
369
+ }
370
+ touchChannel(channelId) {
371
+ this.channelLastActiveAt.set(channelId, Date.now());
372
+ }
373
+ cleanupIdleChannelCaches(now = Date.now()) {
374
+ const cutoff = now - CHANNEL_CACHE_TTL_MS;
375
+ for (const [channelId, lastActiveAt] of this.channelLastActiveAt) {
376
+ if (lastActiveAt > cutoff)
377
+ continue;
378
+ const queue = this.queues.get(channelId);
379
+ if (!queue?.isIdle() || this.cards.hasCreationInFlight(channelId))
380
+ continue;
381
+ if (this.cards.hasCardUpdatedSince(channelId, cutoff))
382
+ continue;
383
+ this.cards.dropChannel(channelId);
384
+ this.conversations.evict(channelId);
385
+ this.queues.delete(channelId);
386
+ this.channelLastActiveAt.delete(channelId);
387
+ }
388
+ }
389
+ }
@@ -0,0 +1,56 @@
1
+ import { type ConversationMeta } from "./api.js";
2
+ import type { DingTalkConfig } from "./config.js";
3
+ export interface CardControllerDeps {
4
+ config: DingTalkConfig;
5
+ getAccessToken: () => Promise<string | null>;
6
+ getConversationMeta: (channelId: string) => ConversationMeta | null;
7
+ /** Plain-message fallback when a card cannot be finalized; goes through the bot's `sendPlain`. */
8
+ sendPlain: (channelId: string, text: string) => Promise<boolean>;
9
+ }
10
+ export declare class CardController {
11
+ private deps;
12
+ private activeCards;
13
+ private cardGenerations;
14
+ private cardCreationAttempted;
15
+ private cardCreationInFlight;
16
+ constructor(deps: CardControllerDeps);
17
+ /** Capture the current turn's identity; close, /stop and /new invalidate it. */
18
+ getCardGeneration(channelId: string): symbol;
19
+ isCardGenerationCurrent(channelId: string, generation: symbol): boolean;
20
+ /** Get or create an AI card without joining an earlier turn's in-flight creation. */
21
+ ensureCard(channelId: string, generation?: symbol): Promise<void>;
22
+ /**
23
+ * Replace the active card content with a full snapshot.
24
+ */
25
+ replaceCard(channelId: string, content: string, finalize?: boolean, failed?: boolean, generation?: symbol): Promise<boolean>;
26
+ /**
27
+ * Append a delta to the active card transcript.
28
+ */
29
+ appendToCard(channelId: string, content: string, finalize?: boolean, failed?: boolean, generation?: symbol): Promise<boolean>;
30
+ /**
31
+ * Shared body of `replaceCard`/`appendToCard`: whether to open a fresh card differs between the
32
+ * two (a full-snapshot replace opens one for a finalize/failed close too; a delta append only
33
+ * opens one for genuinely new content), so that predicate stays keyed on `append` rather than
34
+ * being collapsed away — everything after it (stream, then drop the card on finalize/failed/a
35
+ * failed stream) is identical either way.
36
+ */
37
+ private writeCard;
38
+ /**
39
+ * Finalize and remove the active card for a channel.
40
+ */
41
+ finalizeCard(channelId: string, content: string, generation?: symbol): Promise<boolean>;
42
+ /** Finish progress only: never create a card or send a fallback chat message. */
43
+ finalizeExistingCard(channelId: string, content: string, generation?: symbol): Promise<boolean>;
44
+ /** Invalidate this turn's local state. This is not a remote message deletion. */
45
+ discardCard(channelId: string, generation?: symbol | undefined): void;
46
+ /** True while this channel has a card being created (the idle-cache sweep must not reclaim it). */
47
+ hasCreationInFlight(channelId: string): boolean;
48
+ /** True when the channel's card was updated after `cutoffMs` (epoch ms). */
49
+ hasCardUpdatedSince(channelId: string, cutoffMs: number): boolean;
50
+ /** Forget everything held for an idle channel. */
51
+ dropChannel(channelId: string): void;
52
+ private createCard;
53
+ private createCardUncached;
54
+ private streamCard;
55
+ private streamCardRequest;
56
+ }