@oyasmi/pipiclaw 0.9.4-beta.1 → 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 (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 +9 -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,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;
@@ -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 {};
@@ -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 {};