@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
+ * The daemon's per-channel turn handler: what happens when the DingTalk transport hands the runtime
3
+ * a message, `/stop`, `/new`, a busy-turn message, or a synthetic wake. Wired together (and handed
4
+ * its collaborators) by `bootstrap.ts`.
5
+ */
6
+ import { join } from "path";
7
+ import { createFreshActiveSession } from "../channel/active-session-store.js";
8
+ import { ensureChannelDir, getChannelDir } from "../channel/channel-paths.js";
9
+ import { resolveProjectScope } from "../channel/project-scope-store.js";
10
+ import { formatMissingQueueMessage, formatNewSessionReply, formatSteerQueued, } from "../commands/catalog.js";
11
+ import { runReportCommand } from "../commands/router.js";
12
+ import * as log from "../log.js";
13
+ import { loadSecurityConfigWithDiagnostics } from "../security/config.js";
14
+ import { resolveProjectAccessPolicy } from "../security/project-scope.js";
15
+ import { errorMessage } from "../shared/text-utils.js";
16
+ import { readActiveTasks } from "../tasks/contract.js";
17
+ import { pauseTask as pauseStoredTask } from "../tasks/store.js";
18
+ import { persistInboundImage, relativeImagePaths } from "./inbound-images.js";
19
+ import { forceEndStuckTurnAfterStop } from "./stop-watchdog.js";
20
+ import { createTaskDriverEvent, parseDriverTaskId } from "./task-driver.js";
21
+ import { createEventTurnRunner } from "./turn-run.js";
22
+ function isNoRunningTaskQueueError(err) {
23
+ return err instanceof Error && err.message === "No task is currently running.";
24
+ }
25
+ export function createTurnHandler(deps) {
26
+ const { options, store, channelRunners, sessionResetChains, activeTasks, stopWatchdogs, channelIndex, archiveIncomingMessage, getRunner, cliVersion, startedAt, isShuttingDown, getDurableDispatch, getJobs, getRuns, getTaskDriver, } = deps;
27
+ const runEventTurn = createEventTurnRunner({
28
+ options,
29
+ store,
30
+ activeTasks,
31
+ archiveIncomingMessage,
32
+ getRunner,
33
+ isShuttingDown,
34
+ getDurableDispatch,
35
+ getJobs,
36
+ getRuns,
37
+ getTaskDriver,
38
+ runRuntimeCommand: (event, name, args) => handler.runRuntimeCommand(event, name, args),
39
+ });
40
+ const handler = {
41
+ isRunning(channelId) {
42
+ return channelRunners.get(channelId)?.isBusy() ?? false;
43
+ },
44
+ noteChannelActivity(observation) {
45
+ if (isShuttingDown())
46
+ return;
47
+ channelIndex.note(observation);
48
+ },
49
+ async handleStop(channelId, _bot) {
50
+ const runner = channelRunners.get(channelId);
51
+ let pausedTaskId;
52
+ if (runner?.isBusy()) {
53
+ runner.requestStop();
54
+ // Stopping a task step stops the task: otherwise the driver would queue the next step
55
+ // straight away. The step may not be bound to its session yet, so fall back to the text.
56
+ const taskId = runner.getTaskLoop()?.taskId ?? parseDriverTaskId(runner.getTurnStatus().taskText);
57
+ if (taskId) {
58
+ await pauseStoredTask(getChannelDir(options.paths.workspaceDir, channelId), taskId, {
59
+ by: "user",
60
+ reason: "用户 /stop 中止了该任务的当前步骤。",
61
+ });
62
+ pausedTaskId = taskId;
63
+ log.logInfoEvent("tasks.task.paused_on_stop", "Task paused on /stop", {
64
+ channelId: channelId,
65
+ fields: { taskId },
66
+ });
67
+ }
68
+ _bot.discardCard(channelId);
69
+ // Drop queued-but-not-started messages so a burst does not keep
70
+ // running after the user asked to halt; abort the in-flight one.
71
+ const dropped = _bot.clearPendingMessages(channelId);
72
+ // Same tick as the clear: record that absorbed wakes' queued closures are gone.
73
+ getDurableDispatch()?.discardQueuedClaims(channelId);
74
+ if (dropped > 0) {
75
+ log.logInfoEvent("agent.turn.queue_dropped", "Queued messages dropped on /stop", {
76
+ channelId: channelId,
77
+ fields: { count: dropped },
78
+ });
79
+ }
80
+ void runner.abort().catch((err) => {
81
+ log.logWarn("agent.turn.abort_failed", "Turn abort failed", {
82
+ channelId: channelId,
83
+ reason: errorMessage(err),
84
+ });
85
+ });
86
+ void getDurableDispatch()
87
+ ?.cancelChannel(channelId)
88
+ .then((canceled) => {
89
+ if (canceled)
90
+ log.logInfoEvent("dispatch.cancel.reset", "Durable dispatch leases reset on /stop", {
91
+ channelId: channelId,
92
+ fields: { count: canceled },
93
+ });
94
+ })
95
+ .catch((err) => {
96
+ log.logWarn("dispatch.cancel.failed", "Durable dispatch lease reset on stop failed", {
97
+ channelId: channelId,
98
+ reason: errorMessage(err),
99
+ });
100
+ });
101
+ log.logInfoEvent("agent.turn.stop_requested", "Stop requested", { channelId: channelId });
102
+ if (!stopWatchdogs.has(channelId)) {
103
+ stopWatchdogs.add(channelId);
104
+ void forceEndStuckTurnAfterStop({
105
+ channelId,
106
+ runner,
107
+ graceMs: options.stopForceEndGraceMs,
108
+ notify: (text) => _bot.sendPlain(channelId, text),
109
+ })
110
+ .catch((err) => {
111
+ log.logWarn("agent.turn.stop_watchdog_failed", "Stop watchdog failed", {
112
+ channelId: channelId,
113
+ reason: errorMessage(err),
114
+ });
115
+ })
116
+ .finally(() => {
117
+ stopWatchdogs.delete(channelId);
118
+ });
119
+ }
120
+ }
121
+ return { pausedTaskId };
122
+ },
123
+ async handleNewSession(event, _bot) {
124
+ if (isShuttingDown())
125
+ return;
126
+ const previous = sessionResetChains.get(event.channelId) ?? Promise.resolve();
127
+ const reset = previous
128
+ .catch(() => undefined)
129
+ .then(async () => {
130
+ try {
131
+ const channelDir = ensureChannelDir(options.paths.workspaceDir, event.channelId);
132
+ const access = resolveProjectAccessPolicy(loadSecurityConfigWithDiagnostics(options.paths.appHomeDir).config, process.cwd());
133
+ const scope = resolveProjectScope(channelDir, access);
134
+ if (scope.kind === "blocked") {
135
+ throw new Error(scope.reason);
136
+ }
137
+ // The empty session file and active pointer are committed before the old
138
+ // generation is touched. A filesystem failure therefore leaves the live
139
+ // session authoritative and retryable.
140
+ const result = await createFreshActiveSession(channelDir, scope.scope.projectRoot);
141
+ const oldRunner = channelRunners.get(event.channelId);
142
+ if (oldRunner) {
143
+ channelRunners.delete(event.channelId);
144
+ try {
145
+ oldRunner.retireForNewSession();
146
+ }
147
+ catch (error) {
148
+ // The active pointer already names the new session. Retirement is
149
+ // best-effort cleanup and must not misreport the committed reset as failed.
150
+ log.logWarn("agent.session.retire_failed", "Old runner retirement after /new failed", {
151
+ channelId: event.channelId,
152
+ reason: errorMessage(error),
153
+ });
154
+ }
155
+ }
156
+ const dropped = _bot.resetChannelQueue(event.channelId);
157
+ if (dropped > 0) {
158
+ log.logInfoEvent("agent.session.queue_dropped", "Old-session queued messages discarded by /new", {
159
+ channelId: event.channelId,
160
+ fields: { count: dropped },
161
+ });
162
+ }
163
+ await _bot.sendPlain(event.channelId, formatNewSessionReply(result.sessionId));
164
+ void archiveIncomingMessage(event.channelId, {
165
+ date: new Date().toISOString(),
166
+ ts: event.ts,
167
+ user: event.user,
168
+ userName: event.userName,
169
+ text: event.text,
170
+ isBot: false,
171
+ images: relativeImagePaths(options.paths.workspaceDir, event.channelId, event.images),
172
+ }, "/new command");
173
+ }
174
+ catch (error) {
175
+ const message = errorMessage(error);
176
+ log.logWarn("agent.session.create_failed", "Fresh session creation failed", {
177
+ channelId: event.channelId,
178
+ reason: message,
179
+ });
180
+ await _bot.sendPlain(event.channelId, `新会话创建失败:${message}\n旧会话保持不变,可以重试 \`/new\`。`);
181
+ }
182
+ });
183
+ sessionResetChains.set(event.channelId, reset);
184
+ activeTasks.add(reset);
185
+ try {
186
+ await reset;
187
+ }
188
+ finally {
189
+ activeTasks.delete(reset);
190
+ if (sessionResetChains.get(event.channelId) === reset) {
191
+ sessionResetChains.delete(event.channelId);
192
+ }
193
+ }
194
+ },
195
+ async runRuntimeCommand(event, name, args) {
196
+ const { channelId } = event;
197
+ return runReportCommand({
198
+ channelId,
199
+ paths: options.paths,
200
+ actor: "dingtalk-command",
201
+ version: cliVersion,
202
+ startedAt,
203
+ peekRunner: () => channelRunners.get(channelId),
204
+ getRunner: () => getRunner(channelId),
205
+ runManager: getRuns().get(channelId),
206
+ runningJobLines: () => getJobs().runningLines(channelId),
207
+ // D4.2: dispose the cached runner so the next access rebuilds it under the new scope.
208
+ // The active-session ref is untouched — same session, new project root.
209
+ onScopeChanged: async () => {
210
+ const runner = channelRunners.get(channelId);
211
+ channelRunners.delete(channelId);
212
+ await runner?.dispose().catch((err) => {
213
+ log.logWarn("runtime.runner.dispose_failed", "Runner dispose after /project failed", {
214
+ channelId: channelId,
215
+ reason: errorMessage(err),
216
+ });
217
+ });
218
+ },
219
+ dispatchTask: async (id) => {
220
+ const channelDir = getChannelDir(options.paths.workspaceDir, channelId);
221
+ const entry = (await readActiveTasks(join(channelDir, "tasks"))).find((candidate) => candidate.id === id);
222
+ if (!entry)
223
+ return false;
224
+ // A human asking to run a task twice means twice, so this key is deliberately
225
+ // unique per invocation rather than sharing the driver's occurrence key (D1).
226
+ const now = Date.now();
227
+ return ((await getDurableDispatch()?.dispatch({
228
+ ...createTaskDriverEvent(channelId, entry, now),
229
+ dispatchId: `task:${channelId}:${entry.id}:manual:${new Date(now).toISOString()}`,
230
+ })) ?? false);
231
+ },
232
+ }, name, args);
233
+ },
234
+ async handleBusyMessage(event, bot, mode, queueText) {
235
+ if (isShuttingDown()) {
236
+ return { kind: "handled" };
237
+ }
238
+ const runner = getRunner(event.channelId);
239
+ const trimmedQueueText = queueText.trim();
240
+ if (!trimmedQueueText) {
241
+ await bot.sendPlain(event.channelId, formatMissingQueueMessage(mode === "followUp" ? "followup" : "steer"));
242
+ return { kind: "handled" };
243
+ }
244
+ // Compaction is maintenance, not user work. A new message cancels it and is
245
+ // kept as a normal queued turn instead of trying to steer an agent loop that
246
+ // is currently disconnected for summarization.
247
+ if (runner.interruptCompaction()) {
248
+ log.logInfoEvent("agent.compaction.interrupted", "Compaction interrupted for a new user message", {
249
+ channelId: event.channelId,
250
+ });
251
+ return { kind: "requeue", text: trimmedQueueText };
252
+ }
253
+ // A task step runs in the task's own session and is muted: a steer here would land in
254
+ // the background task's context and its answer would never reach the user, while the
255
+ // message itself is kept out of the chat session. Run it as the next chat turn instead.
256
+ const taskLoop = runner.getTaskLoop();
257
+ if (taskLoop) {
258
+ await bot.sendPlain(event.channelId, `后台任务 \`${taskLoop.taskId}\` 正在执行一步,你的消息会在这一步结束后处理;要给该任务补充指示,用 \`/tasks steer ${taskLoop.taskId} <内容>\`。`);
259
+ log.logEvent("info", "agent.turn.followup_queued", "Message deferred past a task step", {
260
+ ctx: { channelId: event.channelId, userName: event.userName },
261
+ fields: { messageLength: trimmedQueueText.length, taskId: taskLoop.taskId },
262
+ });
263
+ return { kind: "requeue", text: trimmedQueueText };
264
+ }
265
+ if (mode === "followUp") {
266
+ log.logEvent("info", "agent.turn.followup_queued", "Follow-up queued", {
267
+ ctx: { channelId: event.channelId, userName: event.userName },
268
+ fields: { messageLength: trimmedQueueText.length },
269
+ });
270
+ return { kind: "requeue", text: trimmedQueueText };
271
+ }
272
+ try {
273
+ await runner.queueSteer(trimmedQueueText, event.userName, event.images);
274
+ await archiveIncomingMessage(event.channelId, {
275
+ date: new Date().toISOString(),
276
+ ts: event.ts,
277
+ user: event.user,
278
+ userName: event.userName,
279
+ text: event.text,
280
+ isBot: false,
281
+ deliveryMode: mode,
282
+ skipContextSync: true,
283
+ images: relativeImagePaths(options.paths.workspaceDir, event.channelId, event.images),
284
+ }, `${mode} message`);
285
+ await bot.sendPlain(event.channelId, formatSteerQueued(!event.text.trim().startsWith("/")));
286
+ log.logEvent("info", "agent.turn.steer_queued", "Steer queued", {
287
+ ctx: { channelId: event.channelId, userName: event.userName },
288
+ fields: { messageLength: trimmedQueueText.length },
289
+ });
290
+ return { kind: "handled" };
291
+ }
292
+ catch (err) {
293
+ const errMsg = errorMessage(err);
294
+ if (isNoRunningTaskQueueError(err)) {
295
+ log.logInfoEvent("agent.turn.requeued", "Busy window closed; message requeued as a normal turn", {
296
+ channelId: event.channelId,
297
+ fields: { mode },
298
+ });
299
+ return { kind: "requeue", text: trimmedQueueText };
300
+ }
301
+ log.logWarn("agent.turn.queue_failed", "Busy message queueing failed", {
302
+ channelId: event.channelId,
303
+ reason: errMsg,
304
+ fields: { mode },
305
+ });
306
+ await bot.sendPlain(event.channelId, `这条消息没能排进当前回合:${errMsg}\n等当前回合结束后重发,或用 \`/followup <消息>\` 排到它之后。`);
307
+ return { kind: "handled" };
308
+ }
309
+ },
310
+ persistInboundImage: (channelId, image) => persistInboundImage(options.paths.workspaceDir, channelId, image),
311
+ handleEvent: runEventTurn,
312
+ reserveEvent(event) {
313
+ // Must stay synchronous: runs before the queued handler is awaited, so busy state shows up at once.
314
+ getRunner(event.channelId).beginTurn(event.text);
315
+ },
316
+ };
317
+ return handler;
318
+ }
@@ -0,0 +1,52 @@
1
+ /**
2
+ * One turn of the daemon's per-channel pipeline (`DingTalkHandler.handleEvent`): dispatch admission,
3
+ * built-in commands, wake verification, the agent run — as a task step when the wake is one — and
4
+ * the settle-and-release epilogue that runs whatever happens.
5
+ */
6
+ import type { AgentRunner } from "../agent/types.js";
7
+ import type { BootstrapPaths } from "../app/home.js";
8
+ import type { ChannelEvent } from "../channel/channel-event.js";
9
+ import type { ChannelStore } from "../channel/store.js";
10
+ import { type RuntimeCommandName } from "../commands/catalog.js";
11
+ import type { DingTalkBotPort } from "../dingtalk/handler.js";
12
+ import type { JobRuntime } from "../jobs/manager.js";
13
+ import type { SubAgentRuntime } from "../subagents/run-registry.js";
14
+ import type { DurableDispatchService } from "./durable-dispatch.js";
15
+ import type { WakeTaskTransitionHooks } from "./task-wake.js";
16
+ /** One message or wake, written to the message archive (see `ChannelStore.logMessage`). */
17
+ export interface ArchivedMessage {
18
+ date: string;
19
+ ts: string;
20
+ user: string;
21
+ userName?: string;
22
+ text: string;
23
+ isBot: boolean;
24
+ deliveryMode?: "steer" | "followUp";
25
+ skipContextSync?: boolean;
26
+ images?: string[];
27
+ }
28
+ export interface EventTurnDeps {
29
+ options: {
30
+ paths: BootstrapPaths;
31
+ /** Test-only fault seams for the atomic structured-wake task transition. */
32
+ wakeTransitionHooks?: Partial<Record<"job" | "subagent", WakeTaskTransitionHooks>>;
33
+ };
34
+ store: ChannelStore;
35
+ activeTasks: Set<Promise<void>>;
36
+ archiveIncomingMessage: (channelId: string, message: ArchivedMessage, contextLabel: string) => Promise<void>;
37
+ getRunner: (channelId: string) => AgentRunner;
38
+ isShuttingDown: () => boolean;
39
+ getDurableDispatch: () => DurableDispatchService | undefined;
40
+ getJobs: () => JobRuntime;
41
+ getRuns: () => SubAgentRuntime;
42
+ getTaskDriver: () => {
43
+ nudge?(): void;
44
+ };
45
+ /** The handler's `runRuntimeCommand`, for stateless reports typed on an idle channel. */
46
+ runRuntimeCommand: (event: ChannelEvent, name: RuntimeCommandName, args: string) => Promise<string>;
47
+ }
48
+ /**
49
+ * The turn pipeline behind `DingTalkHandler.handleEvent`: admit the dispatch, run commands or the
50
+ * agent (as a task step when the wake is one), and always settle the dispatch and release the turn.
51
+ */
52
+ export declare function createEventTurnRunner(deps: EventTurnDeps): (inboundEvent: ChannelEvent, bot: DingTalkBotPort, isEvent?: boolean) => Promise<void>;