@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,318 @@
1
+ /**
2
+ * AI Card streaming: create a card, stream appended or replaced content into it, and close it.
3
+ * Owns the per-channel card state — the active card, the turn "generation" that invalidates a late
4
+ * writer after `/stop` or `/new`, and the single-flight creation guard.
5
+ */
6
+ import axios from "axios";
7
+ import * as log from "../log.js";
8
+ import { errorMessage } from "../shared/text-utils.js";
9
+ import { DINGTALK_API, http } from "./api.js";
10
+ const TOKEN_REFRESH_SECS = 90 * 60; // 1.5 hours (tokens expire after 2 hours)
11
+ export class CardController {
12
+ constructor(deps) {
13
+ this.deps = deps;
14
+ // Active AI cards: channelId → AICard
15
+ this.activeCards = new Map();
16
+ this.cardGenerations = new Map();
17
+ this.cardCreationAttempted = new Set();
18
+ // Share creation within a turn, but never let a late old turn own a new turn's card.
19
+ this.cardCreationInFlight = new Map();
20
+ }
21
+ /** Capture the current turn's identity; close, /stop and /new invalidate it. */
22
+ getCardGeneration(channelId) {
23
+ let generation = this.cardGenerations.get(channelId);
24
+ if (!generation) {
25
+ generation = Symbol(channelId);
26
+ this.cardGenerations.set(channelId, generation);
27
+ }
28
+ return generation;
29
+ }
30
+ isCardGenerationCurrent(channelId, generation) {
31
+ return this.cardGenerations.get(channelId) === generation;
32
+ }
33
+ /** Get or create an AI card without joining an earlier turn's in-flight creation. */
34
+ async ensureCard(channelId, generation = this.getCardGeneration(channelId)) {
35
+ if (!this.deps.config.cardTemplateId || !this.isCardGenerationCurrent(channelId, generation))
36
+ return;
37
+ const existing = this.activeCards.get(channelId);
38
+ if (existing && !existing.finished)
39
+ return;
40
+ await this.createCard(channelId, generation);
41
+ }
42
+ /**
43
+ * Replace the active card content with a full snapshot.
44
+ */
45
+ async replaceCard(channelId, content, finalize = false, failed = false, generation = this.getCardGeneration(channelId)) {
46
+ return this.writeCard(channelId, content, { append: false, finalize, failed }, generation);
47
+ }
48
+ /**
49
+ * Append a delta to the active card transcript.
50
+ */
51
+ async appendToCard(channelId, content, finalize = false, failed = false, generation = this.getCardGeneration(channelId)) {
52
+ return this.writeCard(channelId, content, { append: true, finalize, failed }, generation);
53
+ }
54
+ /**
55
+ * Shared body of `replaceCard`/`appendToCard`: whether to open a fresh card differs between the
56
+ * two (a full-snapshot replace opens one for a finalize/failed close too; a delta append only
57
+ * opens one for genuinely new content), so that predicate stays keyed on `append` rather than
58
+ * being collapsed away — everything after it (stream, then drop the card on finalize/failed/a
59
+ * failed stream) is identical either way.
60
+ */
61
+ async writeCard(channelId, content, options, generation) {
62
+ if (!this.isCardGenerationCurrent(channelId, generation))
63
+ return false;
64
+ const { append, finalize, failed } = options;
65
+ if (append && !content && !finalize && !failed) {
66
+ return true;
67
+ }
68
+ let card = this.activeCards.get(channelId);
69
+ const shouldEnsure = append
70
+ ? !finalize && !failed && content.trim().length > 0
71
+ : content.trim().length > 0 || !finalize || failed;
72
+ if ((!card || card.finished) && this.deps.config.cardTemplateId && shouldEnsure) {
73
+ await this.ensureCard(channelId, generation);
74
+ if (!this.isCardGenerationCurrent(channelId, generation))
75
+ return false;
76
+ card = this.activeCards.get(channelId);
77
+ }
78
+ if (!card || card.finished) {
79
+ return false;
80
+ }
81
+ // Never erase a visible card, including callers finishing with no new text.
82
+ const snapshot = !append && !content.trim() ? card.content || "处理已结束。" : content;
83
+ const streamed = await this.streamCard(card, snapshot, { append, finalize, failed });
84
+ if (streamed && (finalize || failed) && this.activeCards.get(channelId) === card) {
85
+ this.activeCards.delete(channelId);
86
+ }
87
+ return streamed;
88
+ }
89
+ /**
90
+ * Finalize and remove the active card for a channel.
91
+ */
92
+ async finalizeCard(channelId, content, generation = this.getCardGeneration(channelId)) {
93
+ if (!content.trim() || !this.isCardGenerationCurrent(channelId, generation))
94
+ return false;
95
+ const finalized = await this.replaceCard(channelId, content, true, false, generation);
96
+ if (!finalized && this.isCardGenerationCurrent(channelId, generation)) {
97
+ return this.deps.sendPlain(channelId, content);
98
+ }
99
+ return finalized;
100
+ }
101
+ /** Finish progress only: never create a card or send a fallback chat message. */
102
+ async finalizeExistingCard(channelId, content, generation = this.getCardGeneration(channelId)) {
103
+ if (!this.isCardGenerationCurrent(channelId, generation) || !this.activeCards.has(channelId))
104
+ return false;
105
+ return this.replaceCard(channelId, content, true, false, generation);
106
+ }
107
+ /** Invalidate this turn's local state. This is not a remote message deletion. */
108
+ discardCard(channelId, generation = this.cardGenerations.get(channelId)) {
109
+ if (!generation || !this.isCardGenerationCurrent(channelId, generation))
110
+ return;
111
+ this.cardGenerations.delete(channelId);
112
+ this.cardCreationAttempted.delete(generation);
113
+ const card = this.activeCards.get(channelId);
114
+ this.activeCards.delete(channelId);
115
+ // /stop and /new may invalidate a turn before its controller gets to finish.
116
+ if (card && !card.finished) {
117
+ void this.streamCard(card, `${card.content || "正在处理…"}\n\n处理已结束。`, {
118
+ append: false,
119
+ finalize: true,
120
+ failed: false,
121
+ });
122
+ }
123
+ }
124
+ /** True while this channel has a card being created (the idle-cache sweep must not reclaim it). */
125
+ hasCreationInFlight(channelId) {
126
+ return this.cardCreationInFlight.has(channelId);
127
+ }
128
+ /** True when the channel's card was updated after `cutoffMs` (epoch ms). */
129
+ hasCardUpdatedSince(channelId, cutoffMs) {
130
+ const card = this.activeCards.get(channelId);
131
+ return card !== undefined && card.lastUpdated * 1000 > cutoffMs;
132
+ }
133
+ /** Forget everything held for an idle channel. */
134
+ dropChannel(channelId) {
135
+ this.activeCards.delete(channelId);
136
+ const generation = this.cardGenerations.get(channelId);
137
+ if (generation)
138
+ this.cardCreationAttempted.delete(generation);
139
+ this.cardGenerations.delete(channelId);
140
+ }
141
+ async createCard(channelId, generation) {
142
+ // Re-check under the singleflight: a concurrent caller may have already
143
+ // created the card while we awaited, so avoid a duplicate create.
144
+ const existing = this.activeCards.get(channelId);
145
+ if (existing && !existing.finished) {
146
+ return existing;
147
+ }
148
+ const inFlight = this.cardCreationInFlight.get(channelId);
149
+ if (inFlight?.generation === generation) {
150
+ return inFlight.promise;
151
+ }
152
+ // A failed create may already have reached DingTalk. Never mint another ID in this turn.
153
+ if (this.cardCreationAttempted.has(generation))
154
+ return null;
155
+ this.cardCreationAttempted.add(generation);
156
+ const creation = this.createCardUncached(channelId, generation).finally(() => {
157
+ if (this.cardCreationInFlight.get(channelId)?.generation === generation) {
158
+ this.cardCreationInFlight.delete(channelId);
159
+ }
160
+ });
161
+ this.cardCreationInFlight.set(channelId, { generation, promise: creation });
162
+ return creation;
163
+ }
164
+ async createCardUncached(channelId, generation) {
165
+ const { config } = this.deps;
166
+ const token = await this.deps.getAccessToken();
167
+ if (!token || !this.isCardGenerationCurrent(channelId, generation))
168
+ return null;
169
+ const meta = this.deps.getConversationMeta(channelId);
170
+ if (!meta) {
171
+ log.logWarn("dingtalk.card.no_metadata", "Card not created: no conversation metadata", {
172
+ channelId: channelId,
173
+ });
174
+ return null;
175
+ }
176
+ const isGroup = meta.conversationType === "2";
177
+ const instanceId = `card_${Date.now()}_${Math.random().toString(36).substring(2, 8)}`;
178
+ const robotCode = config.robotCode || config.clientId;
179
+ // openSpaceId format:
180
+ // 群聊: dtv1.card//IM_GROUP.{openConversationId}
181
+ // 单聊: dtv1.card//IM_ROBOT.{userId}
182
+ const openSpaceId = isGroup
183
+ ? `dtv1.card//IM_GROUP.${meta.conversationId}`
184
+ : `dtv1.card//IM_ROBOT.${meta.senderId}`;
185
+ const body = {
186
+ cardTemplateId: config.cardTemplateId,
187
+ outTrackId: instanceId,
188
+ cardData: {
189
+ cardParamMap: {
190
+ [config.cardTemplateKey || "content"]: "正在处理…",
191
+ sys_full_json_obj: JSON.stringify({
192
+ config: {
193
+ autoLayout: config.cardAutoLayout ?? true,
194
+ },
195
+ }),
196
+ },
197
+ },
198
+ callbackType: "STREAM",
199
+ imGroupOpenSpaceModel: { supportForward: true },
200
+ imRobotOpenSpaceModel: { supportForward: true },
201
+ openSpaceId,
202
+ userIdType: 1,
203
+ };
204
+ if (isGroup) {
205
+ body.imGroupOpenDeliverModel = { robotCode };
206
+ }
207
+ else {
208
+ body.imRobotOpenDeliverModel = { spaceType: "IM_ROBOT" };
209
+ }
210
+ try {
211
+ await http.post(`${DINGTALK_API}/v1.0/card/instances/createAndDeliver`, body, {
212
+ headers: {
213
+ "x-acs-dingtalk-access-token": token,
214
+ "Content-Type": "application/json",
215
+ },
216
+ });
217
+ }
218
+ catch (err) {
219
+ if (axios.isAxiosError(err) && err.response) {
220
+ log.logWarn("dingtalk.card.create_failed", "Card create failed", {
221
+ reason: JSON.stringify(err.response.data),
222
+ fields: { status: err.response.status },
223
+ });
224
+ }
225
+ else {
226
+ log.logWarn("dingtalk.card.create_failed", "Card create failed", { reason: errorMessage(err) });
227
+ }
228
+ return null;
229
+ }
230
+ const card = {
231
+ instanceId,
232
+ conversationId: meta.conversationId,
233
+ accessToken: token,
234
+ templateKey: config.cardTemplateKey || "content",
235
+ createdAt: Date.now() / 1000,
236
+ lastUpdated: Date.now() / 1000,
237
+ content: "正在处理…",
238
+ finished: false,
239
+ };
240
+ if (!this.isCardGenerationCurrent(channelId, generation)) {
241
+ await this.streamCard(card, "处理已结束。", { append: false, finalize: true, failed: false });
242
+ return null;
243
+ }
244
+ this.activeCards.set(channelId, card);
245
+ return card;
246
+ }
247
+ async streamCard(card, content, options) {
248
+ // A stop/new-session close can arrive while the prior HTTP write is in flight.
249
+ // Order writes by instance so that close remains the last update to the old card.
250
+ const pending = (card.pendingWrite ?? Promise.resolve(true))
251
+ .then(async () => {
252
+ if (card.finished)
253
+ return false;
254
+ return this.streamCardRequest(card, content, options);
255
+ })
256
+ .catch((error) => {
257
+ log.logWarn("dingtalk.card.stream_failed", "Card streaming failed", { reason: errorMessage(error) });
258
+ return false;
259
+ });
260
+ card.pendingWrite = pending;
261
+ return pending;
262
+ }
263
+ async streamCardRequest(card, content, options) {
264
+ // Refresh token if needed
265
+ const ageSecs = Date.now() / 1000 - card.createdAt;
266
+ if (ageSecs > TOKEN_REFRESH_SECS) {
267
+ const token = await this.deps.getAccessToken();
268
+ if (token) {
269
+ card.accessToken = token;
270
+ }
271
+ }
272
+ const body = {
273
+ outTrackId: card.instanceId,
274
+ guid: `${Date.now()}_${Math.random().toString(36).substring(2, 8)}`,
275
+ key: card.templateKey,
276
+ content,
277
+ append: options.append,
278
+ finished: options.finalize,
279
+ failed: options.failed,
280
+ isFull: !options.append,
281
+ isFinalize: options.finalize,
282
+ isError: options.failed,
283
+ };
284
+ const start = Date.now();
285
+ try {
286
+ await http.put(`${DINGTALK_API}/v1.0/card/streaming`, body, {
287
+ headers: {
288
+ "x-acs-dingtalk-access-token": card.accessToken,
289
+ "Content-Type": "application/json",
290
+ },
291
+ });
292
+ const duration = Date.now() - start;
293
+ if (duration > 1000) {
294
+ log.logWarn("dingtalk.card.stream_slow", "Card streaming request slow", {
295
+ fields: { durationMs: duration },
296
+ });
297
+ }
298
+ card.lastUpdated = Date.now() / 1000;
299
+ card.content = options.append ? `${card.content}${content}` : content;
300
+ if (options.finalize || options.failed) {
301
+ card.finished = true;
302
+ }
303
+ return true;
304
+ }
305
+ catch (err) {
306
+ if (axios.isAxiosError(err) && err.response) {
307
+ log.logWarn("dingtalk.card.stream_failed", "Card streaming failed", {
308
+ reason: JSON.stringify(err.response.data),
309
+ fields: { status: err.response.status },
310
+ });
311
+ }
312
+ else {
313
+ log.logWarn("dingtalk.card.stream_failed", "Card streaming failed", { reason: errorMessage(err) });
314
+ }
315
+ return false;
316
+ }
317
+ }
318
+ }
@@ -1,3 +1,6 @@
1
+ /**
2
+ * The per-channel serial work queue for inbound turns (user message and event limits live in the bot).
3
+ */
1
4
  import * as log from "../log.js";
2
5
  import { errorMessage } from "../shared/text-utils.js";
3
6
  /**
@@ -34,7 +37,7 @@ export class ChannelQueue {
34
37
  await work();
35
38
  }
36
39
  catch (err) {
37
- log.logWarning("Queue error", errorMessage(err));
40
+ log.logWarn("runtime.queue.item_failed", "Channel queue item failed", { reason: errorMessage(err) });
38
41
  }
39
42
  this.processing = false;
40
43
  this.processNext();
@@ -0,0 +1,19 @@
1
+ import { type BootstrapIO, type BootstrapPaths } from "../app/home.js";
2
+ import { type ResponseMode } from "../channel/channel-context.js";
3
+ export type BusyMessageMode = "steer" | "followUp";
4
+ export type BusyMessageDefaultConfig = BusyMessageMode | "followup";
5
+ export declare function isBusyMessageDefaultConfig(value: unknown): value is BusyMessageDefaultConfig;
6
+ export declare function normalizeBusyMessageDefault(value: unknown): BusyMessageMode;
7
+ export interface DingTalkConfig {
8
+ clientId: string;
9
+ clientSecret: string;
10
+ robotCode?: string;
11
+ cardTemplateId?: string;
12
+ cardTemplateKey?: string;
13
+ allowFrom?: string[];
14
+ stateDir?: string;
15
+ busyMessageDefault?: BusyMessageDefaultConfig;
16
+ responseMode?: ResponseMode;
17
+ cardAutoLayout?: boolean;
18
+ }
19
+ export declare function loadConfig(paths?: BootstrapPaths, io?: BootstrapIO): DingTalkConfig;
@@ -0,0 +1,95 @@
1
+ /**
2
+ * `channel.json`: the DingTalk transport's configuration shape, validation and loading. This is
3
+ * the only loader of that file (spec 054 D7); the app-home scaffolding only writes its template.
4
+ */
5
+ import { readFileSync } from "fs";
6
+ import { BootstrapExitError, DEFAULT_BOOTSTRAP_PATHS } from "../app/home.js";
7
+ import { isResponseModeConfig, normalizeResponseMode } from "../channel/channel-context.js";
8
+ import { docsUrl } from "../paths.js";
9
+ import { errorMessage } from "../shared/text-utils.js";
10
+ export function isBusyMessageDefaultConfig(value) {
11
+ return value === "steer" || value === "followUp" || value === "followup";
12
+ }
13
+ export function normalizeBusyMessageDefault(value) {
14
+ if (value === undefined) {
15
+ return "steer";
16
+ }
17
+ if (value === "steer") {
18
+ return "steer";
19
+ }
20
+ if (value === "followUp" || value === "followup") {
21
+ return "followUp";
22
+ }
23
+ throw new Error('Invalid `busyMessageDefault`: expected "steer", "followUp", or "followup".');
24
+ }
25
+ function isPlaceholderString(value) {
26
+ return value.trim().startsWith("your-");
27
+ }
28
+ function listChannelConfigIssues(config) {
29
+ const issues = [];
30
+ if (!config.clientId) {
31
+ issues.push("Missing required field `clientId`.");
32
+ }
33
+ else if (isPlaceholderString(config.clientId)) {
34
+ issues.push("Replace placeholder value for `clientId`.");
35
+ }
36
+ if (!config.clientSecret) {
37
+ issues.push("Missing required field `clientSecret`.");
38
+ }
39
+ else if (isPlaceholderString(config.clientSecret)) {
40
+ issues.push("Replace placeholder value for `clientSecret`.");
41
+ }
42
+ if (config.robotCode && isPlaceholderString(config.robotCode)) {
43
+ issues.push("Replace placeholder value for `robotCode`, or set it to an empty string to reuse `clientId`.");
44
+ }
45
+ if (config.cardTemplateId && isPlaceholderString(config.cardTemplateId)) {
46
+ issues.push("Replace placeholder value for `cardTemplateId`, or set it to an empty string to disable AI Card streaming.");
47
+ }
48
+ if (Array.isArray(config.allowFrom) && config.allowFrom.some((value) => isPlaceholderString(value))) {
49
+ issues.push("Replace placeholder values in `allowFrom`, or set it to an empty array to allow all users.");
50
+ }
51
+ const busyMessageDefault = config.busyMessageDefault;
52
+ if (busyMessageDefault !== undefined && !isBusyMessageDefaultConfig(busyMessageDefault)) {
53
+ issues.push('Invalid `busyMessageDefault`: expected "steer", "followUp", or "followup".');
54
+ }
55
+ const responseMode = config.responseMode;
56
+ if (responseMode !== undefined && !isResponseModeConfig(responseMode)) {
57
+ issues.push('Invalid `responseMode`: expected "full_progress_then_plain_final", "rolling_progress_then_plain_final", or "final_card_only".');
58
+ }
59
+ const cardAutoLayout = config.cardAutoLayout;
60
+ if (cardAutoLayout !== undefined && typeof cardAutoLayout !== "boolean") {
61
+ issues.push("Invalid `cardAutoLayout`: expected boolean.");
62
+ }
63
+ return issues;
64
+ }
65
+ export function loadConfig(paths = DEFAULT_BOOTSTRAP_PATHS, io = console) {
66
+ let parsed;
67
+ try {
68
+ parsed = JSON.parse(readFileSync(paths.channelConfigPath, "utf-8"));
69
+ }
70
+ catch (err) {
71
+ io.error(`Failed to parse configuration: ${paths.channelConfigPath}`);
72
+ io.error(errorMessage(err));
73
+ throw new BootstrapExitError(1);
74
+ }
75
+ const issues = listChannelConfigIssues(parsed);
76
+ if (issues.length > 0) {
77
+ io.error(`Configuration is not ready: ${paths.channelConfigPath}`);
78
+ for (const issue of issues) {
79
+ io.error(` - ${issue}`);
80
+ }
81
+ io.error("");
82
+ io.error(`Fix ${paths.channelConfigPath} and run \`${paths.appName}\` again.`);
83
+ io.error(`Docs: ${docsUrl("configuration.md")}`);
84
+ throw new BootstrapExitError(1);
85
+ }
86
+ parsed.cardTemplateKey = parsed.cardTemplateKey || "content";
87
+ parsed.robotCode = parsed.robotCode?.trim() ? parsed.robotCode : parsed.clientId;
88
+ parsed.busyMessageDefault = normalizeBusyMessageDefault(parsed.busyMessageDefault);
89
+ parsed.responseMode = normalizeResponseMode(parsed.responseMode);
90
+ parsed.cardAutoLayout = parsed.cardAutoLayout ?? true;
91
+ if (Array.isArray(parsed.allowFrom)) {
92
+ parsed.allowFrom = parsed.allowFrom.filter((value) => value.trim().length > 0);
93
+ }
94
+ return parsed;
95
+ }
@@ -0,0 +1,57 @@
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 { type DWClientDownStream } from "dingtalk-stream";
7
+ export interface StreamConnectionOptions {
8
+ clientId: string;
9
+ clientSecret: string;
10
+ /** True once the bot is stopping: no further reconnects are scheduled. */
11
+ isStopped: () => boolean;
12
+ /** Handles one downstream robot frame; the ack to DingTalk is the callee's business. */
13
+ onRawMessage: (msg: DWClientDownStream) => {
14
+ status: "SUCCESS";
15
+ message: string;
16
+ };
17
+ }
18
+ export declare class StreamConnection {
19
+ private options;
20
+ private client;
21
+ private lastSocketAvailableTime;
22
+ private activeMessageProcessing;
23
+ private keepAliveTimer;
24
+ private reconnectTimer;
25
+ private reconnectDelayTimer;
26
+ private reconnectDelayResolve;
27
+ private isReconnecting;
28
+ private reconnectAttempts;
29
+ private hasReportedReady;
30
+ constructor(options: StreamConnectionOptions);
31
+ /** Create the client and make the first (immediate) connection attempt. */
32
+ start(): Promise<void>;
33
+ /** Acknowledge a downstream frame immediately so DingTalk does not redeliver it. */
34
+ ack(messageId: string): void;
35
+ /** A turn is running: the keep-alive watchdog must not treat the quiet socket as dead. */
36
+ beginMessageProcessing(): void;
37
+ endMessageProcessing(): void;
38
+ /** Cancel the keep-alive, scheduled-reconnect and backoff timers. */
39
+ clearAllTimers(): void;
40
+ /** Close the socket and drop the client (the bot is stopping). */
41
+ disconnect(): Promise<void>;
42
+ private getSocket;
43
+ private isSocketLike;
44
+ private setTrackedTimeout;
45
+ private setTrackedInterval;
46
+ private clearKeepAliveTimer;
47
+ private clearReconnectTimer;
48
+ private clearReconnectDelay;
49
+ private waitForDelay;
50
+ private waitForSocketState;
51
+ private markClientDisconnected;
52
+ private clearClientSocketReference;
53
+ private cleanupSocket;
54
+ private connectWithTimeout;
55
+ private scheduleReconnect;
56
+ private doReconnect;
57
+ }