@oyasmi/pipiclaw 0.9.4 → 0.9.5-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 (405) hide show
  1. package/README.en.md +28 -22
  2. package/README.md +27 -21
  3. package/dist/agent/builtin-commands.d.ts +7 -2
  4. package/dist/agent/builtin-commands.js +19 -23
  5. package/dist/agent/channel-runner.d.ts +13 -13
  6. package/dist/agent/channel-runner.js +93 -76
  7. package/dist/agent/maintenance-context.d.ts +6 -5
  8. package/dist/agent/maintenance-context.js +15 -15
  9. package/dist/agent/prompt/manifest.js +1 -1
  10. package/dist/agent/prompt/resources.d.ts +1 -1
  11. package/dist/agent/prompt/resources.js +1 -1
  12. package/dist/agent/prompt/sections.js +4 -4
  13. package/dist/agent/runner-factory.d.ts +6 -6
  14. package/dist/agent/runner-factory.js +6 -7
  15. package/dist/agent/session/compaction-input.d.ts +6 -0
  16. package/dist/agent/session/compaction-input.js +75 -0
  17. package/dist/agent/session/compaction-snapshot.d.ts +30 -0
  18. package/dist/agent/session/compaction-snapshot.js +154 -0
  19. package/dist/agent/session/compaction-summary.d.ts +39 -0
  20. package/dist/agent/session/compaction-summary.js +158 -0
  21. package/dist/agent/session/compaction.d.ts +35 -0
  22. package/dist/agent/session/compaction.js +294 -0
  23. package/dist/agent/session/context-input.d.ts +15 -0
  24. package/dist/agent/session/context-input.js +82 -0
  25. package/dist/agent/session/context-snapshot.d.ts +11 -0
  26. package/dist/agent/session/context-snapshot.js +72 -0
  27. package/dist/agent/session/event-guards.d.ts +2 -0
  28. package/dist/agent/session/event-guards.js +4 -0
  29. package/dist/agent/session/request-tools.d.ts +3 -0
  30. package/dist/agent/session/request-tools.js +20 -0
  31. package/dist/agent/session/session-adapter.d.ts +2 -1
  32. package/dist/agent/session/session-adapter.js +6 -3
  33. package/dist/agent/session/session-events.d.ts +5 -4
  34. package/dist/agent/session/session-events.js +46 -59
  35. package/dist/agent/session/session-host.d.ts +29 -41
  36. package/dist/agent/session/session-host.js +86 -69
  37. package/dist/agent/session/settings-diagnostics.d.ts +5 -0
  38. package/dist/agent/session/settings-diagnostics.js +21 -0
  39. package/dist/agent/status-render.js +5 -2
  40. package/dist/{runtime → agent}/stop-watchdog.d.ts +3 -1
  41. package/dist/{runtime → agent}/stop-watchdog.js +7 -3
  42. package/dist/agent/turn/progress-formatter.d.ts +1 -3
  43. package/dist/agent/turn/progress-formatter.js +3 -22
  44. package/dist/agent/turn/task-digest.d.ts +4 -2
  45. package/dist/agent/turn/task-digest.js +7 -4
  46. package/dist/agent/turn/turn-context.d.ts +11 -7
  47. package/dist/agent/turn/turn-context.js +26 -18
  48. package/dist/agent/turn/turn-finish.d.ts +17 -5
  49. package/dist/agent/turn/turn-finish.js +51 -77
  50. package/dist/agent/turn/turn-input.d.ts +2 -2
  51. package/dist/agent/turn/turn-input.js +4 -3
  52. package/dist/agent/turn/turn-output.d.ts +19 -0
  53. package/dist/agent/turn/turn-output.js +41 -0
  54. package/dist/agent/turn/turn-pipeline.d.ts +11 -8
  55. package/dist/agent/turn/turn-pipeline.js +54 -55
  56. package/dist/agent/turn/turn-prompt.d.ts +1 -1
  57. package/dist/agent/turn/turn-recovery.d.ts +11 -10
  58. package/dist/agent/turn/turn-recovery.js +14 -29
  59. package/dist/agent/types.d.ts +31 -12
  60. package/dist/agent/types.js +2 -1
  61. package/dist/app/auth-command.js +1 -1
  62. package/dist/app/home.js +31 -15
  63. package/dist/channel/active-session-store.d.ts +14 -12
  64. package/dist/channel/active-session-store.js +29 -25
  65. package/dist/channel/attachments.d.ts +25 -0
  66. package/dist/channel/attachments.js +56 -0
  67. package/dist/channel/channel-context.d.ts +87 -96
  68. package/dist/channel/channel-context.js +1 -66
  69. package/dist/channel/channel-event.d.ts +51 -41
  70. package/dist/channel/channel-event.js +6 -11
  71. package/dist/channel/channel-id.d.ts +22 -0
  72. package/dist/channel/channel-id.js +13 -0
  73. package/dist/channel/channel-index.d.ts +17 -34
  74. package/dist/channel/channel-index.js +41 -80
  75. package/dist/channel/config.d.ts +10 -0
  76. package/dist/channel/config.js +55 -0
  77. package/dist/channel/ingress.d.ts +101 -0
  78. package/dist/channel/ingress.js +5 -0
  79. package/dist/channel/store.d.ts +13 -15
  80. package/dist/channel/store.js +21 -25
  81. package/dist/channel/transport.d.ts +99 -0
  82. package/dist/channel/turn-context.d.ts +23 -0
  83. package/dist/channel/turn-context.js +1 -0
  84. package/dist/commands/catalog.d.ts +4 -7
  85. package/dist/commands/catalog.js +24 -31
  86. package/dist/commands/router.d.ts +23 -12
  87. package/dist/commands/router.js +22 -24
  88. package/dist/config/settings.d.ts +5 -4
  89. package/dist/desk/bindings.d.ts +6 -0
  90. package/dist/desk/bindings.js +105 -0
  91. package/dist/desk/commands.d.ts +81 -0
  92. package/dist/desk/commands.js +145 -0
  93. package/dist/desk/default.d.ts +4 -0
  94. package/dist/desk/default.js +11 -0
  95. package/dist/desk/paths.d.ts +41 -0
  96. package/dist/desk/paths.js +81 -0
  97. package/dist/desk/registry.d.ts +17 -0
  98. package/dist/desk/registry.js +191 -0
  99. package/dist/desk/startup-error.d.ts +4 -0
  100. package/dist/desk/startup-error.js +7 -0
  101. package/dist/desk/types.d.ts +72 -0
  102. package/dist/desk/types.js +7 -0
  103. package/dist/dingtalk/bot.d.ts +18 -35
  104. package/dist/dingtalk/bot.js +21 -204
  105. package/dist/dingtalk/channel-ids.d.ts +15 -0
  106. package/dist/dingtalk/channel-ids.js +39 -0
  107. package/dist/dingtalk/config.d.ts +6 -3
  108. package/dist/dingtalk/config.js +13 -25
  109. package/dist/dingtalk/connection.d.ts +1 -0
  110. package/dist/dingtalk/connection.js +5 -4
  111. package/dist/dingtalk/conversation-meta.d.ts +10 -5
  112. package/dist/dingtalk/conversation-meta.js +72 -50
  113. package/dist/dingtalk/delivery.d.ts +30 -14
  114. package/dist/dingtalk/delivery.js +189 -62
  115. package/dist/dingtalk/inbound-media.d.ts +2 -18
  116. package/dist/dingtalk/inbound-media.js +0 -53
  117. package/dist/dingtalk/inbound.d.ts +10 -11
  118. package/dist/dingtalk/inbound.js +12 -19
  119. package/dist/dingtalk/media.d.ts +9 -11
  120. package/dist/dingtalk/media.js +18 -31
  121. package/dist/dingtalk/progress.d.ts +8 -0
  122. package/dist/dingtalk/progress.js +20 -0
  123. package/dist/dingtalk/response-mode.d.ts +13 -0
  124. package/dist/dingtalk/response-mode.js +31 -0
  125. package/dist/dingtalk/transport.d.ts +47 -0
  126. package/dist/dingtalk/transport.js +71 -0
  127. package/dist/events/commands.d.ts +7 -2
  128. package/dist/events/commands.js +40 -22
  129. package/dist/events/pre-action-error.d.ts +10 -0
  130. package/dist/events/pre-action-error.js +10 -0
  131. package/dist/events/types.d.ts +20 -2
  132. package/dist/events/watcher.d.ts +14 -7
  133. package/dist/events/watcher.js +49 -26
  134. package/dist/index.d.ts +4 -2
  135. package/dist/jobs/completion-wake.d.ts +14 -0
  136. package/dist/jobs/completion-wake.js +36 -0
  137. package/dist/jobs/manager.d.ts +27 -22
  138. package/dist/jobs/manager.js +58 -91
  139. package/dist/jobs/record.d.ts +2 -0
  140. package/dist/jobs/record.js +2 -0
  141. package/dist/log.d.ts +0 -1
  142. package/dist/log.js +1 -1
  143. package/dist/main.js +10 -3
  144. package/dist/memory/boundary-work.d.ts +17 -0
  145. package/dist/memory/boundary-work.js +162 -0
  146. package/dist/memory/commands.d.ts +4 -3
  147. package/dist/memory/commands.js +16 -16
  148. package/dist/memory/desk-memory-queue.d.ts +18 -0
  149. package/dist/memory/desk-memory-queue.js +33 -0
  150. package/dist/memory/index-budget.d.ts +3 -3
  151. package/dist/memory/index-budget.js +3 -3
  152. package/dist/memory/journal.d.ts +6 -6
  153. package/dist/memory/journal.js +14 -14
  154. package/dist/memory/lifecycle.d.ts +14 -21
  155. package/dist/memory/lifecycle.js +73 -103
  156. package/dist/memory/maintenance-state.d.ts +14 -15
  157. package/dist/memory/maintenance-state.js +43 -42
  158. package/dist/memory/reflect-job.d.ts +5 -4
  159. package/dist/memory/reflect-job.js +21 -15
  160. package/dist/memory/reflect.d.ts +2 -1
  161. package/dist/memory/reflect.js +13 -12
  162. package/dist/memory/render.d.ts +1 -1
  163. package/dist/memory/render.js +2 -2
  164. package/dist/memory/review-log.d.ts +4 -4
  165. package/dist/memory/review-log.js +5 -5
  166. package/dist/memory/scheduler.d.ts +12 -19
  167. package/dist/memory/scheduler.js +28 -64
  168. package/dist/memory/session-corpus.d.ts +4 -1
  169. package/dist/memory/session-corpus.js +70 -29
  170. package/dist/memory/session-search.d.ts +11 -3
  171. package/dist/memory/session-search.js +14 -11
  172. package/dist/memory/sidecar-worker.d.ts +1 -0
  173. package/dist/memory/sidecar-worker.js +57 -76
  174. package/dist/memory/source-window.d.ts +0 -6
  175. package/dist/memory/source-window.js +0 -20
  176. package/dist/memory/store.d.ts +12 -12
  177. package/dist/memory/store.js +44 -44
  178. package/dist/paths.d.ts +2 -0
  179. package/dist/paths.js +2 -0
  180. package/dist/playbooks/agent-delegation.md +16 -16
  181. package/dist/playbooks/background-jobs.md +5 -3
  182. package/dist/playbooks/event-scheduling.md +7 -5
  183. package/dist/playbooks/memory-and-learning.md +16 -12
  184. package/dist/playbooks/outbound-media.md +1 -1
  185. package/dist/playbooks/runtime-orientation.md +35 -23
  186. package/dist/playbooks/task-lead.md +13 -11
  187. package/dist/runtime/bootstrap.d.ts +36 -13
  188. package/dist/runtime/bootstrap.js +310 -138
  189. package/dist/runtime/channel-queue.d.ts +23 -0
  190. package/dist/{dingtalk → runtime}/channel-queue.js +20 -9
  191. package/dist/runtime/daemon-lock.d.ts +12 -0
  192. package/dist/runtime/daemon-lock.js +28 -0
  193. package/dist/runtime/desk-runtime.d.ts +131 -0
  194. package/dist/runtime/desk-runtime.js +402 -0
  195. package/dist/runtime/durable-dispatch.d.ts +11 -5
  196. package/dist/runtime/durable-dispatch.js +20 -8
  197. package/dist/runtime/inbound-images.d.ts +32 -10
  198. package/dist/runtime/inbound-images.js +95 -21
  199. package/dist/runtime/ingress-busy.d.ts +26 -0
  200. package/dist/runtime/ingress-busy.js +211 -0
  201. package/dist/runtime/ingress-commands.d.ts +7 -0
  202. package/dist/runtime/ingress-commands.js +162 -0
  203. package/dist/runtime/ingress-deps.d.ts +62 -0
  204. package/dist/runtime/ingress-deps.js +1 -0
  205. package/dist/runtime/ingress.d.ts +22 -0
  206. package/dist/runtime/ingress.js +376 -0
  207. package/dist/runtime/request-execution.d.ts +19 -0
  208. package/dist/runtime/request-execution.js +88 -0
  209. package/dist/runtime/shutdown.d.ts +13 -5
  210. package/dist/runtime/shutdown.js +10 -4
  211. package/dist/runtime/task-driver.d.ts +38 -22
  212. package/dist/runtime/task-driver.js +142 -116
  213. package/dist/runtime/task-spawn.d.ts +4 -4
  214. package/dist/runtime/task-spawn.js +6 -5
  215. package/dist/runtime/task-wake.d.ts +6 -4
  216. package/dist/runtime/task-wake.js +7 -7
  217. package/dist/runtime/transports.d.ts +32 -0
  218. package/dist/runtime/transports.js +101 -0
  219. package/dist/runtime/turn-run.d.ts +18 -9
  220. package/dist/runtime/turn-run.js +302 -71
  221. package/dist/runtime/wake-coalescing.d.ts +11 -3
  222. package/dist/runtime/wake-coalescing.js +10 -0
  223. package/dist/security/config.js +5 -10
  224. package/dist/security/logger.js +1 -1
  225. package/dist/security/path-guard.js +7 -63
  226. package/dist/security/types.d.ts +27 -30
  227. package/dist/security/types.js +0 -1
  228. package/dist/shared/atomic-file.d.ts +2 -0
  229. package/dist/shared/atomic-file.js +14 -1
  230. package/dist/shared/file-lock.d.ts +35 -0
  231. package/dist/shared/file-lock.js +195 -0
  232. package/dist/shared/with-timeout.d.ts +2 -0
  233. package/dist/shared/with-timeout.js +21 -0
  234. package/dist/skills/loader.d.ts +1 -1
  235. package/dist/skills/loader.js +2 -2
  236. package/dist/skills/workspace.js +2 -2
  237. package/dist/subagents/completion-wake.d.ts +11 -2
  238. package/dist/subagents/completion-wake.js +22 -9
  239. package/dist/subagents/discovery.js +1 -1
  240. package/dist/subagents/dispatch.d.ts +0 -10
  241. package/dist/subagents/dispatch.js +10 -28
  242. package/dist/subagents/external/dispatch.js +1 -1
  243. package/dist/subagents/external/run.d.ts +1 -1
  244. package/dist/subagents/external/run.js +3 -3
  245. package/dist/subagents/internal/run.js +1 -1
  246. package/dist/subagents/internal/worker.js +6 -14
  247. package/dist/subagents/run-archive.d.ts +11 -0
  248. package/dist/subagents/run-archive.js +49 -0
  249. package/dist/subagents/run-record.d.ts +9 -8
  250. package/dist/subagents/run-record.js +3 -3
  251. package/dist/subagents/run-registry.d.ts +5 -3
  252. package/dist/subagents/run-registry.js +22 -45
  253. package/dist/subagents/runs.d.ts +23 -13
  254. package/dist/subagents/runs.js +75 -82
  255. package/dist/subagents/task-envelope.js +9 -11
  256. package/dist/subagents/types.d.ts +6 -5
  257. package/dist/tasks/board.d.ts +1 -1
  258. package/dist/tasks/board.js +2 -2
  259. package/dist/tasks/bound-work.d.ts +2 -2
  260. package/dist/tasks/bound-work.js +7 -7
  261. package/dist/tasks/brief.d.ts +1 -1
  262. package/dist/tasks/brief.js +9 -9
  263. package/dist/tasks/commands.d.ts +11 -2
  264. package/dist/tasks/commands.js +66 -41
  265. package/dist/tasks/contract.d.ts +0 -2
  266. package/dist/tasks/contract.js +1 -3
  267. package/dist/tasks/create.d.ts +3 -1
  268. package/dist/tasks/create.js +10 -4
  269. package/dist/tasks/frontmatter.d.ts +6 -2
  270. package/dist/tasks/frontmatter.js +10 -10
  271. package/dist/tasks/loop-log.d.ts +7 -13
  272. package/dist/tasks/loop-log.js +14 -17
  273. package/dist/tasks/mutation-lock.d.ts +7 -5
  274. package/dist/tasks/mutation-lock.js +32 -9
  275. package/dist/tasks/session-path.d.ts +3 -3
  276. package/dist/tasks/session-path.js +5 -5
  277. package/dist/tasks/steer.d.ts +5 -5
  278. package/dist/tasks/steer.js +42 -40
  279. package/dist/tasks/store.d.ts +11 -11
  280. package/dist/tasks/store.js +32 -29
  281. package/dist/tools/bash.d.ts +5 -5
  282. package/dist/tools/bash.js +19 -18
  283. package/dist/tools/contract/names.d.ts +7 -0
  284. package/dist/tools/contract/names.js +22 -0
  285. package/dist/tools/edit.js +1 -1
  286. package/dist/tools/event-manage.d.ts +3 -1
  287. package/dist/tools/event-manage.js +34 -33
  288. package/dist/tools/glob.js +5 -5
  289. package/dist/tools/grep.js +2 -2
  290. package/dist/tools/index.d.ts +9 -8
  291. package/dist/tools/index.js +12 -16
  292. package/dist/tools/job.d.ts +4 -2
  293. package/dist/tools/job.js +11 -8
  294. package/dist/tools/memory-manage.d.ts +5 -3
  295. package/dist/tools/memory-manage.js +24 -24
  296. package/dist/tools/read.js +1 -1
  297. package/dist/tools/registry.d.ts +12 -8
  298. package/dist/tools/registry.js +13 -9
  299. package/dist/tools/send-media.d.ts +2 -2
  300. package/dist/tools/send-media.js +3 -3
  301. package/dist/tools/session-search.d.ts +3 -1
  302. package/dist/tools/session-search.js +8 -6
  303. package/dist/tools/subagent-manage.d.ts +2 -8
  304. package/dist/tools/subagent-manage.js +19 -15
  305. package/dist/tools/subagent.js +1 -1
  306. package/dist/tools/task-manage/create.js +1 -1
  307. package/dist/tools/task-manage/factory.js +2 -2
  308. package/dist/tools/task-manage/lifecycle.js +3 -1
  309. package/dist/tools/task-manage/log-view.js +2 -2
  310. package/dist/tools/task-manage/shared.js +3 -3
  311. package/dist/tools/task-manage/step-end.js +3 -3
  312. package/dist/tools/task-manage/types.d.ts +8 -3
  313. package/dist/tools/web-cache.d.ts +3 -3
  314. package/dist/tools/web-cache.js +12 -12
  315. package/dist/tools/web-fetch.d.ts +2 -2
  316. package/dist/tools/web-fetch.js +7 -7
  317. package/dist/tools/write-content.js +1 -1
  318. package/dist/tui/cli.d.ts +17 -5
  319. package/dist/tui/cli.js +90 -27
  320. package/dist/tui/client.d.ts +26 -0
  321. package/dist/tui/client.js +157 -0
  322. package/dist/tui/colors.d.ts +0 -1
  323. package/dist/tui/colors.js +0 -1
  324. package/dist/tui/commands.d.ts +10 -51
  325. package/dist/tui/commands.js +16 -39
  326. package/dist/tui/frontend.d.ts +2 -2
  327. package/dist/tui/frontend.js +2 -2
  328. package/dist/tui/pitui-frontend.d.ts +0 -2
  329. package/dist/tui/pitui-frontend.js +1 -6
  330. package/dist/tui/render.d.ts +62 -0
  331. package/dist/tui/render.js +123 -0
  332. package/dist/tui/session.d.ts +92 -0
  333. package/dist/tui/session.js +317 -0
  334. package/dist/usage/ledger.d.ts +5 -0
  335. package/dist/usage/ledger.js +2 -0
  336. package/dist/usage/render.d.ts +6 -1
  337. package/dist/usage/render.js +18 -13
  338. package/dist/webapi/auth.d.ts +13 -0
  339. package/dist/webapi/auth.js +29 -0
  340. package/dist/webapi/config.d.ts +29 -0
  341. package/dist/webapi/config.js +100 -0
  342. package/dist/webapi/errors.d.ts +39 -0
  343. package/dist/webapi/errors.js +32 -0
  344. package/dist/webapi/http.d.ts +25 -0
  345. package/dist/webapi/http.js +4 -0
  346. package/dist/webapi/ids.d.ts +9 -0
  347. package/dist/webapi/ids.js +20 -0
  348. package/dist/webapi/input.d.ts +17 -0
  349. package/dist/webapi/input.js +229 -0
  350. package/dist/webapi/items.d.ts +37 -0
  351. package/dist/webapi/items.js +48 -0
  352. package/dist/webapi/key-command.d.ts +2 -0
  353. package/dist/webapi/key-command.js +110 -0
  354. package/dist/webapi/limits.d.ts +47 -0
  355. package/dist/webapi/limits.js +48 -0
  356. package/dist/webapi/request-policy.d.ts +17 -0
  357. package/dist/webapi/request-policy.js +160 -0
  358. package/dist/webapi/response-record.d.ts +68 -0
  359. package/dist/webapi/response-record.js +58 -0
  360. package/dist/webapi/response-state.d.ts +90 -0
  361. package/dist/webapi/response-state.js +347 -0
  362. package/dist/webapi/routes/conversations.d.ts +8 -0
  363. package/dist/webapi/routes/conversations.js +80 -0
  364. package/dist/webapi/routes/models.d.ts +3 -0
  365. package/dist/webapi/routes/models.js +12 -0
  366. package/dist/webapi/routes/responses.d.ts +8 -0
  367. package/dist/webapi/routes/responses.js +118 -0
  368. package/dist/webapi/routes/websocket.d.ts +9 -0
  369. package/dist/webapi/routes/websocket.js +328 -0
  370. package/dist/webapi/server.d.ts +24 -0
  371. package/dist/webapi/server.js +229 -0
  372. package/dist/webapi/service.d.ts +130 -0
  373. package/dist/webapi/service.js +588 -0
  374. package/dist/webapi/store.d.ts +46 -0
  375. package/dist/webapi/store.js +245 -0
  376. package/dist/webapi/stream.d.ts +13 -0
  377. package/dist/webapi/stream.js +76 -0
  378. package/dist/webapi/transport.d.ts +43 -0
  379. package/dist/webapi/transport.js +100 -0
  380. package/package.json +8 -2
  381. package/dist/channel/channel-paths.d.ts +0 -16
  382. package/dist/channel/channel-paths.js +0 -53
  383. package/dist/channel/commands.d.ts +0 -32
  384. package/dist/channel/commands.js +0 -109
  385. package/dist/channel/project-scope-store.d.ts +0 -51
  386. package/dist/channel/project-scope-store.js +0 -112
  387. package/dist/dingtalk/channel-queue.d.ts +0 -19
  388. package/dist/dingtalk/handler.d.ts +0 -90
  389. package/dist/memory/channel-maintenance-queue.d.ts +0 -5
  390. package/dist/memory/channel-maintenance-queue.js +0 -8
  391. package/dist/runtime/task-migration.d.ts +0 -30
  392. package/dist/runtime/task-migration.js +0 -465
  393. package/dist/runtime/turn-handler.d.ts +0 -47
  394. package/dist/runtime/turn-handler.js +0 -318
  395. package/dist/security/project-scope.d.ts +0 -45
  396. package/dist/security/project-scope.js +0 -105
  397. package/dist/tui/app.d.ts +0 -16
  398. package/dist/tui/app.js +0 -166
  399. package/dist/tui/terminal-context.d.ts +0 -27
  400. package/dist/tui/terminal-context.js +0 -84
  401. package/dist/tui/terminal-media-sender.d.ts +0 -9
  402. package/dist/tui/terminal-media-sender.js +0 -15
  403. package/dist/tui/turn-controller.d.ts +0 -64
  404. package/dist/tui/turn-controller.js +0 -311
  405. /package/dist/{dingtalk/handler.js → channel/transport.js} +0 -0
@@ -1,33 +1,67 @@
1
- import { muteChannelContext } from "../channel/channel-context.js";
2
- import { ensureChannelDir } from "../channel/channel-paths.js";
3
- import { BUILT_IN_COMMANDS, formatUnknownCommandMessage, isRunnerBuiltInCommand, parseBuiltInCommand, slashCommandName, } from "../commands/catalog.js";
4
- import { createDingTalkContext } from "../dingtalk/delivery.js";
1
+ import { senderOf } from "../channel/channel-event.js";
2
+ import { BUILT_IN_COMMANDS, formatUnknownCommandMessage, isRunnerBuiltInCommand, parseBuiltInCommand, renderBuiltInHelp, slashCommandName, } from "../commands/catalog.js";
3
+ import { formatNoDeskReply } from "../desk/commands.js";
4
+ import { getDeskDir } from "../desk/paths.js";
5
5
  import * as log from "../log.js";
6
6
  import { errorMessage } from "../shared/text-utils.js";
7
7
  import { buildTaskStepBrief } from "../tasks/brief.js";
8
8
  import { consumeTaskNotice } from "../tasks/steer.js";
9
+ import { createEmptyUsageTotals } from "../usage/totals.js";
10
+ import { admitsSyntheticEvent, resolvedDesk } from "./desk-runtime.js";
9
11
  import { relativeImagePaths } from "./inbound-images.js";
10
12
  import { parseDriverTaskId } from "./task-driver.js";
11
13
  import { claimVerifiedWake } from "./task-wake.js";
12
- import { isCoalescableWake, MAX_COALESCED_WAKES, mergeCompletionWakes } from "./wake-coalescing.js";
14
+ import { canAbsorbWake, isCoalescableWake, MAX_COALESCED_WAKES, mergeCompletionWakes } from "./wake-coalescing.js";
13
15
  /**
14
16
  * The `runRuntimeCommand` names usable on the idle-turn path — every `BUILT_IN_COMMANDS` entry
15
17
  * *not* marked `runnerHandled`, i.e. every stateless report. `context` is the one deliberate
16
18
  * exception even though it isn't runner-handled while busy (see the busy-path switch in
17
- * `dingtalk/bot.ts`): idle answers it through the runner's ChannelContext-aware command path
18
- * (thread-reply, delete semantics) instead, so it is routed like the runner-handled built-ins
19
- * here and excluded from this stateless-report set.
19
+ * `ingress.ts`): idle answers it through the runner's command path (it reads the live session)
20
+ * instead, so it is routed like the runner-handled built-ins here and excluded from this
21
+ * stateless-report set.
20
22
  */
21
23
  const IDLE_RUNTIME_COMMAND_NAMES = new Set(BUILT_IN_COMMANDS.filter((command) => !command.runnerHandled).map((command) => command.name));
22
24
  function isIdleRuntimeCommandName(name) {
23
25
  return IDLE_RUNTIME_COMMAND_NAMES.has(name);
24
26
  }
27
+ /** A wake from an in-process producer rather than a person (spec 061, D8: the event's `source`). */
28
+ export function isSyntheticEvent(event) {
29
+ return event.source === "wake";
30
+ }
31
+ /** What a person sees when a turn ends in an error the runner did not report itself. */
32
+ const TURN_FAILED_MESSAGE = "这一轮处理异常中断,没有完成。请重发消息;反复出现时请部署者查看服务日志。";
33
+ function trackOutput(ctx) {
34
+ const tracked = { ctx: undefined, finished: false };
35
+ tracked.ctx = {
36
+ emit: (event) => ctx.emit(event),
37
+ finish: (outcome) => {
38
+ tracked.finished = true;
39
+ return ctx.finish(outcome);
40
+ },
41
+ };
42
+ return tracked;
43
+ }
44
+ /** A task step is silent: its output never reaches the channel (only `task_step_end`'s report does, through `push`). */
45
+ function silenceAnswers(ctx) {
46
+ return { emit: () => undefined, finish: (outcome) => ctx.finish(outcome) };
47
+ }
48
+ function turnInfoOf(event) {
49
+ return {
50
+ channelId: event.channelId,
51
+ ...senderOf(event),
52
+ text: event.text,
53
+ ...(event.source === "human" && event.context ? { context: event.context } : {}),
54
+ ...(event.images ? { images: event.images } : {}),
55
+ ...(event.source === "human" && event.ref !== undefined ? { ref: event.ref } : {}),
56
+ ts: event.ts,
57
+ };
58
+ }
25
59
  /**
26
- * The turn pipeline behind `DingTalkHandler.handleEvent`: admit the dispatch, run commands or the
27
- * agent (as a task step when the wake is one), and always settle the dispatch and release the turn.
60
+ * The turn pipeline behind a queued item: admit the dispatch, run commands or the agent (as a task
61
+ * step when the wake is one), and always settle the dispatch and release the turn.
28
62
  */
29
63
  export function createEventTurnRunner(deps) {
30
- const { options, store, activeTasks, archiveIncomingMessage, getRunner, isShuttingDown, getDurableDispatch, getJobs, getRuns, getTaskDriver, } = deps;
64
+ const { options, transports, store, activeTasks, archiveIncomingMessage, getRunner, isShuttingDown, getDurableDispatch, getJobs, getRuns, getTaskDriver, } = deps;
31
65
  /**
32
66
  * Turn a `[TASK_DRIVER:<id>]` dispatch into a task loop step: bind the runner to the task
33
67
  * cycle's own session and replace the wake text with the step brief. Returns `undefined` for
@@ -37,12 +71,23 @@ export function createEventTurnRunner(deps) {
37
71
  * cannot open its session should still be visible, not silently skipped.
38
72
  */
39
73
  const prepareTaskStep = async (event, runner) => {
74
+ if (event.source !== "wake")
75
+ return undefined;
40
76
  const taskId = parseDriverTaskId(event.text) ?? event.internalWake?.taskId;
41
77
  if (!taskId)
42
78
  return undefined;
43
- const channelDir = ensureChannelDir(options.paths.workspaceDir, event.channelId);
79
+ const { desk, deskDir } = runner.conversation;
80
+ // Admission already refused a wake for another desk (spec 058, D7); a task step bound to the
81
+ // wrong desk's session would run a task this runner does not own, so check once more.
82
+ if (event.desk !== desk) {
83
+ log.logWarn("taskdriver.step.desk_mismatch", "Task step refused: wake is not for this runner's desk", {
84
+ channelId: event.channelId,
85
+ fields: { taskId, eventDesk: event.desk, runnerDesk: desk },
86
+ });
87
+ return undefined;
88
+ }
44
89
  try {
45
- const brief = await buildTaskStepBrief({ channelDir, taskId });
90
+ const brief = await buildTaskStepBrief({ deskDir, taskId });
46
91
  if (!brief)
47
92
  return undefined;
48
93
  await runner.bindTaskSession(taskId);
@@ -58,14 +103,13 @@ export function createEventTurnRunner(deps) {
58
103
  }
59
104
  };
60
105
  /** Deliver whatever the step asked to say, then hand the runner back to the chat session. */
61
- const finishTaskStep = async (channelId, taskId, bot) => {
62
- const channelDir = ensureChannelDir(options.paths.workspaceDir, channelId);
106
+ const finishTaskStep = async (runner, channelId, taskId, transport) => {
63
107
  try {
64
- const notice = await consumeTaskNotice(channelDir, taskId);
108
+ const notice = await consumeTaskNotice(runner.conversation.deskDir, taskId);
65
109
  if (notice) {
66
- // runner.run closes its per-turn delivery context before returning. Sending through that
67
- // closed context silently dropped successful task_step_end notifications (T-run-01).
68
- const delivered = await bot.sendPlain(channelId, notice);
110
+ // runner.run finishes its per-turn output before returning. Sending through that
111
+ // finished output silently dropped successful task_step_end notifications (T-run-01).
112
+ const delivered = await transport.push(channelId, { text: notice });
69
113
  if (delivered)
70
114
  await store.logBotResponse(channelId, notice, Date.now().toString());
71
115
  else
@@ -82,7 +126,7 @@ export function createEventTurnRunner(deps) {
82
126
  fields: { taskId },
83
127
  });
84
128
  }
85
- await getRunner(channelId).bindChatSession();
129
+ await runner.bindChatSession();
86
130
  };
87
131
  /**
88
132
  * Dispatch admission: refuse a stale redelivery of a wake an earlier turn already handled (the
@@ -93,16 +137,18 @@ export function createEventTurnRunner(deps) {
93
137
  const durable = getDurableDispatch();
94
138
  // Sampled synchronously, before any await: `/stop` after this point cleared the queued closures.
95
139
  const stopEpoch = durable?.stopEpoch(inboundEvent.channelId) ?? 0;
140
+ deps.reservedTurns.delete(inboundEvent);
96
141
  if (durable && !(await durable.markStarted(event.dispatchId))) {
97
142
  // A stale delivery of a wake an earlier turn already absorbed and handled.
98
143
  runner.endTurn();
99
144
  return undefined;
100
145
  }
101
- const structuredWakeFinalized = event.internalWake === undefined;
146
+ const structuredWakeFinalized = event.source !== "wake" || event.internalWake === undefined;
102
147
  let absorbedDispatchIds = [];
103
- if (durable && event.dispatchId && isCoalescableWake(event)) {
148
+ if (durable && event.source === "wake" && event.dispatchId && isCoalescableWake(event)) {
149
+ const primary = event;
104
150
  const absorbed = await durable
105
- .absorbPending(event.channelId, event.dispatchId, isCoalescableWake, MAX_COALESCED_WAKES - 1, stopEpoch)
151
+ .absorbPending(event.channelId, event.dispatchId, (candidate) => canAbsorbWake(primary, candidate), MAX_COALESCED_WAKES - 1, stopEpoch)
106
152
  .catch((error) => {
107
153
  log.logWarn("dispatch.wake.absorb_failed", "Wake coalescing failed", {
108
154
  channelId: event.channelId,
@@ -119,21 +165,41 @@ export function createEventTurnRunner(deps) {
119
165
  });
120
166
  }
121
167
  }
122
- return { event, baseCtx: undefined, structuredWakeFinalized, absorbedDispatchIds, mergedWakesHandled: false };
168
+ return {
169
+ event,
170
+ output: undefined,
171
+ structuredWakeFinalized,
172
+ absorbedDispatchIds,
173
+ mergedWakesHandled: false,
174
+ threw: false,
175
+ };
123
176
  };
177
+ /** Say something to the channel in answer to `event`, carrying its reference back to the transport. */
178
+ const replyTo = (transport, event, text, opts) => transport.push(event.channelId, {
179
+ text,
180
+ ...opts,
181
+ ...(event.source === "human" && event.ref !== undefined ? { ref: event.ref } : {}),
182
+ });
124
183
  /** A built-in slash command typed on an idle channel: stateless reports here, session commands on the runner. */
125
- const runBuiltinCommand = async (turn, builtInCommand, runner, ctx, bot) => {
184
+ const runBuiltinCommand = async (turn, builtInCommand, runner, transport) => {
126
185
  const { event } = turn;
127
186
  const commandStartedAt = Date.now();
128
- const logCtx = { channelId: event.channelId, userName: event.userName };
187
+ const logCtx = { channelId: event.channelId, userName: senderOf(event).userName };
129
188
  log.logEvent("info", "runtime.command.started", "Executing command", {
130
189
  ctx: logCtx,
131
190
  fields: { command: builtInCommand.name },
132
191
  });
133
192
  try {
193
+ let response;
134
194
  if (isIdleRuntimeCommandName(builtInCommand.name)) {
135
- const response = await deps.runRuntimeCommand(event, builtInCommand.name, builtInCommand.args);
136
- const delivered = await bot.sendPlain(event.channelId, response, {
195
+ response = await deps.runRuntimeCommand(event, builtInCommand.name, builtInCommand.args);
196
+ }
197
+ else if (isRunnerBuiltInCommand(builtInCommand)) {
198
+ response = await runner.handleBuiltinCommand(builtInCommand);
199
+ }
200
+ if (response !== undefined) {
201
+ // Command echoes are control-plane traffic, not conversation: sent, never archived.
202
+ const delivered = await replyTo(transport, event, response, {
137
203
  title: `/${builtInCommand.name}`,
138
204
  markdown: true,
139
205
  });
@@ -144,9 +210,6 @@ export function createEventTurnRunner(deps) {
144
210
  });
145
211
  }
146
212
  }
147
- else if (isRunnerBuiltInCommand(builtInCommand)) {
148
- await runner.handleBuiltinCommand(ctx, builtInCommand);
149
- }
150
213
  log.logEvent("info", "runtime.command.completed", "Command completed", {
151
214
  ctx: logCtx,
152
215
  fields: { command: builtInCommand.name, durationMs: Date.now() - commandStartedAt },
@@ -170,10 +233,11 @@ export function createEventTurnRunner(deps) {
170
233
  * message never counts — only the producer-created `internalWake` envelope. Returns whether the
171
234
  * turn should still run.
172
235
  */
173
- const verifyInternalWake = async (turn, internalWake) => {
174
- const { event } = turn;
236
+ const verifyInternalWake = async (turn, runner, internalWake) => {
237
+ const event = turn.event;
175
238
  const { kind, resourceId, taskId: wakeTaskId } = internalWake;
176
- const claimed = await claimVerifiedWake(event, options.paths.workspaceDir, kind === "job" ? getJobs().get(event.channelId) : getRuns().get(event.channelId), options.wakeTransitionHooks?.[kind]);
239
+ const { desk, deskDir } = runner.conversation;
240
+ const claimed = await claimVerifiedWake(event, deskDir, kind === "job" ? getJobs().get(desk) : getRuns().get(desk), options.wakeTransitionHooks?.[kind]);
177
241
  if (!claimed) {
178
242
  log.logWarn("dispatch.wake.unverified", "Unverifiable wake ignored", {
179
243
  channelId: event.channelId,
@@ -190,79 +254,103 @@ export function createEventTurnRunner(deps) {
190
254
  return claimed.activated || !claimed.taskStillDriven;
191
255
  };
192
256
  /** The turn proper: archive, route commands, verify wakes, then run the agent (as a task step if one). */
193
- const executeTurn = async (turn, runner, bot, backgroundOnly) => {
257
+ const executeTurn = async (turn, runner, transport, backgroundOnly) => {
194
258
  const { event } = turn;
259
+ const sender = senderOf(event);
195
260
  // Computed before archiving so a command's own text can be excluded from
196
261
  // memory-extraction input (review 2026-08-24 §1.2): it is control-plane
197
262
  // traffic, not conversation, and the history stays queryable via session_search.
198
- const builtInCommand = parseBuiltInCommand(event.text);
263
+ const structuredInput = event.source === "human" && Boolean(event.context?.messages.length);
264
+ const builtInCommand = structuredInput ? undefined : parseBuiltInCommand(event.text);
199
265
  await archiveIncomingMessage(event.channelId, {
200
266
  date: new Date().toISOString(),
201
267
  ts: event.ts,
202
- user: event.user,
203
- userName: event.userName,
268
+ ...sender,
204
269
  text: event.text,
205
270
  isBot: false,
206
271
  skipContextSync: Boolean(builtInCommand),
207
- images: relativeImagePaths(options.paths.workspaceDir, event.channelId, event.images),
272
+ images: relativeImagePaths(runner.conversation.deskDir, event.images),
208
273
  }, "user message");
209
- // Background wakes deliver their result, not their process: no progress card, no
210
- // thinking stream, nothing to clean up when a check-in ends `[SILENT]`.
211
- // Awaited completions deliver their result too, without opening another progress card.
212
- // Spec 051, D3: a task-driver dispatch runs as a *task step* — in the task cycle's
213
- // own session, with a brief instead of the wake text, and silent unless the step
214
- // asked for a notify. Everything below (busy state, /stop, delivery) is unchanged;
215
- // only which session the turn is bound to, and what reaches the channel, differ.
216
- let baseCtx = createDingTalkContext(event, bot, store, backgroundOnly ? "none" : undefined);
217
- turn.baseCtx = baseCtx;
218
- let ctx = baseCtx;
219
274
  if (builtInCommand) {
220
- await runBuiltinCommand(turn, builtInCommand, runner, ctx, bot);
275
+ // A command draws no progress: its output port is quiet, and it closes with the turn.
276
+ turn.output = trackOutput(transport.openTurn(turnInfoOf(event), { quiet: true }));
277
+ await runBuiltinCommand(turn, builtInCommand, runner, transport);
221
278
  return;
222
279
  }
223
280
  // Reject an unknown slash command instead of spending a full LLM turn
224
281
  // letting the model guess what `/modle` meant. Session commands,
225
282
  // skills, and prompt templates are recognized by isKnownSlashCommand.
226
- if (event.text.trim().startsWith("/") && !runner.isKnownSlashCommand(event.text)) {
283
+ if (!structuredInput && event.text.trim().startsWith("/") && !runner.isKnownSlashCommand(event.text)) {
227
284
  const name = slashCommandName(event.text) ?? "";
228
- await bot.sendPlain(event.channelId, formatUnknownCommandMessage(name));
285
+ turn.output = trackOutput(transport.openTurn(turnInfoOf(event), { quiet: true }));
286
+ await replyTo(transport, event, formatUnknownCommandMessage(name));
229
287
  return;
230
288
  }
231
289
  log.logEvent("info", "agent.turn.started", "Starting turn", {
232
- ctx: { channelId: event.channelId, userName: event.userName },
290
+ ctx: { channelId: event.channelId, userName: sender.userName },
233
291
  fields: { messageLength: event.text.length, source: backgroundOnly ? "event" : "message" },
234
292
  });
235
- if (event.internalWake && !(await verifyInternalWake(turn, event.internalWake)))
293
+ if (event.source === "wake" &&
294
+ event.internalWake &&
295
+ !(await verifyInternalWake(turn, runner, event.internalWake)))
236
296
  return;
237
297
  // Verified job/run wakes that activate a task are task steps too. Verification must happen
238
298
  // first: routing directly from user-controlled wake text would grant task-only tools.
239
299
  const taskStep = await prepareTaskStep(turn.event, runner);
240
300
  if (taskStep) {
241
- await baseCtx.close();
242
301
  turn.event = { ...turn.event, text: taskStep.brief };
243
- baseCtx = createDingTalkContext(turn.event, bot, store, "none");
244
- turn.baseCtx = baseCtx;
245
- ctx = muteChannelContext(baseCtx);
246
302
  }
247
- if (!backgroundOnly && !taskStep)
248
- ctx.primeCard(1500);
249
- const result = await runner.run(ctx, store);
303
+ // Background wakes deliver their result, not their process: no progress card, no
304
+ // thinking stream, nothing to clean up when a check-in ends `[SILENT]`. Awaited completions
305
+ // deliver their result too, without opening another progress card.
306
+ // Spec 051, D3: a task-driver dispatch runs as a *task step* — in the task cycle's own
307
+ // session, with a brief instead of the wake text, and silent unless the step asked for a
308
+ // notify. Everything below (busy state, /stop, delivery) is unchanged; only which session
309
+ // the turn is bound to, and what reaches the channel, differ.
310
+ const info = turnInfoOf(turn.event);
311
+ const opened = transport.openTurn(info, { quiet: backgroundOnly || taskStep !== undefined });
312
+ turn.output = trackOutput(taskStep ? silenceAnswers(opened) : opened);
313
+ const result = await runner.run(info, turn.output.ctx, store);
314
+ if (!deps.isCurrentRunner(runner))
315
+ return;
250
316
  turn.mergedWakesHandled = result.stopReason !== "aborted" && result.stopReason !== "error";
251
317
  if (taskStep)
252
- await finishTaskStep(turn.event.channelId, taskStep.taskId, bot);
318
+ await finishTaskStep(runner, turn.event.channelId, taskStep.taskId, transport);
253
319
  if (result.stopReason === "aborted" && runner.getTurnStatus().stopRequested) {
254
320
  log.logInfoEvent("agent.turn.stopped", "Turn stopped", { channelId: turn.event.channelId });
255
321
  }
256
322
  };
257
- /** Always runs: close delivery, settle the dispatch records, release the turn, nudge the task driver. */
323
+ /** Always runs: finish the output, settle the dispatch records, release the turn, nudge the task driver. */
258
324
  const finishTurn = async (turn, runner) => {
259
325
  const { event } = turn;
260
- await turn.baseCtx?.close().catch((error) => {
261
- log.logWarn("delivery.close.failed", "Delivery close failed", {
262
- channelId: event.channelId,
263
- reason: errorMessage(error),
326
+ // The runner finishes the output when it runs; a command, or a turn that failed before the
327
+ // runner took over, finishes here so the transport never keeps one open. A human message that
328
+ // threw before any output was opened still gets one, so its transport sees it end.
329
+ if (!turn.output && turn.threw && event.source === "human") {
330
+ const transport = transports.forChannel(event.channelId);
331
+ if (transport)
332
+ turn.output = trackOutput(transport.openTurn(turnInfoOf(event), { quiet: true }));
333
+ }
334
+ if (turn.output && !turn.output.finished) {
335
+ const outcome = turn.threw
336
+ ? {
337
+ kind: "failed",
338
+ message: TURN_FAILED_MESSAGE,
339
+ usage: createEmptyUsageTotals(),
340
+ executionDesk: runner.conversation.desk,
341
+ }
342
+ : { kind: "completed", usage: createEmptyUsageTotals(), executionDesk: runner.conversation.desk };
343
+ await turn.output.ctx.finish(outcome).catch((error) => {
344
+ log.logWarn("delivery.close.failed", "Delivery close failed", {
345
+ channelId: event.channelId,
346
+ reason: errorMessage(error),
347
+ });
264
348
  });
265
- });
349
+ }
350
+ if (!deps.isCurrentRunner(runner)) {
351
+ runner.endTurn();
352
+ return;
353
+ }
266
354
  if (turn.structuredWakeFinalized)
267
355
  await getDurableDispatch()?.markCompleted(event.dispatchId);
268
356
  else
@@ -281,24 +369,167 @@ export function createEventTurnRunner(deps) {
281
369
  // queues the next step immediately instead of waiting out the current sleep.
282
370
  getTaskDriver().nudge?.();
283
371
  };
284
- const runEventTurn = async (inboundEvent, bot, isEvent) => {
372
+ /**
373
+ * A task-bound wake dropped at admission because its channel left the wake's desk while it was
374
+ * queued. No turn runs, but the business side settles exactly as when the producer suppresses
375
+ * the wake itself: the owner verifies and claims it and the task's `work` ticket is redeemed, so
376
+ * the task resumes as soon as its channel is bound back instead of waiting out the backstop.
377
+ */
378
+ const settleDroppedTaskWake = async (event) => {
379
+ const wake = event.internalWake;
380
+ if (!wake)
381
+ return;
382
+ try {
383
+ const owner = wake.kind === "job" ? getJobs().get(event.desk) : getRuns().get(event.desk);
384
+ const claimed = await claimVerifiedWake(event, getDeskDir(options.paths.workspaceDir, event.desk), owner);
385
+ await claimed?.finish();
386
+ }
387
+ catch (error) {
388
+ log.logWarn("dispatch.wake.redeem_failed", "Work ticket redeem for a dropped wake failed", {
389
+ channelId: event.channelId,
390
+ reason: errorMessage(error),
391
+ fields: { dispatchId: event.dispatchId, taskId: wake.taskId },
392
+ });
393
+ }
394
+ };
395
+ /** Release a turn `reserveEvent` began for an event that admission then refused. */
396
+ const releaseReservation = (event) => {
397
+ if (!deps.reservedTurns.delete(event))
398
+ return;
399
+ getRunner(event.channelId)?.endTurn();
400
+ };
401
+ /**
402
+ * A human message on a channel with no usable desk (D4): nothing is archived, no runner is built
403
+ * and no model is called. `/help` still answers (and `/desk`, before this); everything else gets
404
+ * the one reason and the next step.
405
+ */
406
+ const replyWithoutDesk = async (event, resolution, transport) => {
407
+ const command = parseBuiltInCommand(event.text);
408
+ if (command?.name === "help") {
409
+ await replyTo(transport, event, renderBuiltInHelp(command.args), { title: "/help", markdown: true });
410
+ return;
411
+ }
412
+ await replyTo(transport, event, formatNoDeskReply(resolution), { markdown: true });
413
+ };
414
+ /**
415
+ * A human message that only gets an answer — a command, a refusal — still has its own turn as
416
+ * far as the transport is concerned: its output port is opened and finished around the reply,
417
+ * so a transport that follows each message to an end (the Web API) always sees one.
418
+ */
419
+ const answerOnly = async (transport, event, work) => {
420
+ const output = trackOutput(transport.openTurn(turnInfoOf(event), { quiet: true }));
421
+ try {
422
+ await work();
423
+ }
424
+ finally {
425
+ const executionDesk = resolvedDesk(deps.resolveChannel(event.channelId));
426
+ await output.ctx
427
+ .finish({
428
+ kind: "completed",
429
+ usage: createEmptyUsageTotals(),
430
+ ...(executionDesk !== undefined ? { executionDesk } : {}),
431
+ })
432
+ .catch((error) => {
433
+ log.logWarn("delivery.close.failed", "Delivery close failed", {
434
+ channelId: event.channelId,
435
+ reason: errorMessage(error),
436
+ });
437
+ });
438
+ }
439
+ };
440
+ const runDeskCommand = async (event, args, transport) => {
441
+ const logCtx = { channelId: event.channelId, userName: senderOf(event).userName };
442
+ log.logEvent("info", "runtime.command.started", "Executing command", {
443
+ ctx: logCtx,
444
+ fields: { command: "desk" },
445
+ });
446
+ const response = await deps.runRuntimeCommand(event, "desk", args);
447
+ const delivered = await replyTo(transport, event, response, { title: "/desk", markdown: true });
448
+ if (!delivered) {
449
+ log.logWarn("delivery.command_reply.failed", "Command reply delivery failed", {
450
+ channelId: event.channelId,
451
+ fields: { command: "desk", chars: response.length },
452
+ });
453
+ }
454
+ };
455
+ const runEventTurn = async (inboundEvent) => {
285
456
  if (isShuttingDown()) {
286
457
  log.logInfoEvent("runtime.shutdown.event_ignored", "Event ignored during shutdown", {
287
458
  channelId: inboundEvent.channelId,
288
459
  });
289
460
  return;
290
461
  }
462
+ const transport = transports.forChannel(inboundEvent.channelId);
463
+ if (!transport) {
464
+ log.logWarn("runtime.turn.no_transport", "Turn dropped: no transport hosts the channel", {
465
+ channelId: inboundEvent.channelId,
466
+ fields: { dispatchId: inboundEvent.dispatchId },
467
+ });
468
+ releaseReservation(inboundEvent);
469
+ return;
470
+ }
471
+ const resolution = deps.resolveChannel(inboundEvent.channelId);
472
+ if (isSyntheticEvent(inboundEvent)) {
473
+ // D7's authoritative check (the rule is `admitsSyntheticEvent`; `reserveEvent` applies it early).
474
+ if (!admitsSyntheticEvent(resolution, inboundEvent)) {
475
+ log.logInfoEvent("dispatch.wake.desk_mismatch", "Wake dropped: channel not bound to the wake's desk", {
476
+ channelId: inboundEvent.channelId,
477
+ fields: {
478
+ dispatchId: inboundEvent.dispatchId,
479
+ wakeDesk: inboundEvent.desk,
480
+ boundDesk: resolvedDesk(resolution),
481
+ },
482
+ });
483
+ releaseReservation(inboundEvent);
484
+ await settleDroppedTaskWake(inboundEvent);
485
+ await getDurableDispatch()?.markCompleted(inboundEvent.dispatchId);
486
+ return;
487
+ }
488
+ }
489
+ else {
490
+ // `/desk` runs outside any turn, bound or not: nothing is archived and no runner is built,
491
+ // so `/desk bind` sees this channel idle and the next queued message already resolves
492
+ // against the new binding (D5).
493
+ const command = parseBuiltInCommand(inboundEvent.text);
494
+ // Authorization is checked where the work runs, not only where it was admitted: a queued
495
+ // message outlives the binding it arrived under (an earlier `/desk bind` may have moved it).
496
+ const boundDesk = resolvedDesk(resolution);
497
+ if (inboundEvent.allowedDesks &&
498
+ boundDesk !== undefined &&
499
+ !inboundEvent.allowedDesks.includes(boundDesk) &&
500
+ command?.name !== "desk") {
501
+ releaseReservation(inboundEvent);
502
+ await answerOnly(transport, inboundEvent, () => replyTo(transport, inboundEvent, `当前身份无权使用工位 \`${boundDesk}\`。`).then(() => undefined));
503
+ return;
504
+ }
505
+ if (command?.name === "desk") {
506
+ releaseReservation(inboundEvent);
507
+ await answerOnly(transport, inboundEvent, () => runDeskCommand(inboundEvent, command.args, transport));
508
+ return;
509
+ }
510
+ if (resolution.kind !== "bound") {
511
+ await answerOnly(transport, inboundEvent, () => replyWithoutDesk(inboundEvent, resolution, transport));
512
+ return;
513
+ }
514
+ }
291
515
  const runner = getRunner(inboundEvent.channelId);
516
+ if (!runner) {
517
+ // The binding went away since the checks above: nothing can run, but the message still ends.
518
+ if (!isSyntheticEvent(inboundEvent))
519
+ await answerOnly(transport, inboundEvent, async () => undefined);
520
+ return;
521
+ }
292
522
  const turn = await admitTurn(inboundEvent, runner);
293
523
  if (!turn)
294
524
  return;
295
525
  const task = (async () => {
296
526
  try {
297
- await executeTurn(turn, runner, bot, Boolean(isEvent));
527
+ await executeTurn(turn, runner, transport, isSyntheticEvent(inboundEvent));
298
528
  }
299
529
  catch (err) {
530
+ turn.threw = true;
300
531
  log.logEvent("error", "agent.turn.failed", "Turn failed", {
301
- ctx: { channelId: turn.event.channelId, userName: turn.event.userName },
532
+ ctx: { channelId: turn.event.channelId, userName: senderOf(turn.event).userName },
302
533
  fields: { error: errorMessage(err) },
303
534
  });
304
535
  }
@@ -1,4 +1,4 @@
1
- import type { ChannelEvent } from "../channel/channel-event.js";
1
+ import type { WakeEvent } from "../channel/channel-event.js";
2
2
  /**
3
3
  * Consumer-side merging of completion wakes. K parallel delegations (or background jobs) used to
4
4
  * settle into K separate main-agent turns, each re-reading the whole session to handle one result
@@ -13,6 +13,14 @@ import type { ChannelEvent } from "../channel/channel-event.js";
13
13
  */
14
14
  /** The merged turn's prompt grows with every result's tail; past this many it is better split. */
15
15
  export declare const MAX_COALESCED_WAKES = 6;
16
- export declare function isCoalescableWake(event: ChannelEvent): boolean;
16
+ export declare function isCoalescableWake(event: WakeEvent): boolean;
17
+ /**
18
+ * Whether `candidate` may ride along in `primary`'s turn. The primary already passed
19
+ * `admitsSyntheticEvent` (spec 060, D7), so its desk is the channel's current one; a candidate is
20
+ * folded in only when it was produced for that same desk, so a wake left over from before a rebind
21
+ * (or a malformed record with no owning desk) never reaches the new desk's model. It stays queued
22
+ * and its own admission drops it.
23
+ */
24
+ export declare function canAbsorbWake(primary: WakeEvent, candidate: WakeEvent): boolean;
17
25
  /** The primary wake keeps its own text (and `[KIND:id]` tag) first; the others follow it. */
18
- export declare function mergeCompletionWakes(primary: ChannelEvent, others: ChannelEvent[]): ChannelEvent;
26
+ export declare function mergeCompletionWakes(primary: WakeEvent, others: WakeEvent[]): WakeEvent;
@@ -16,6 +16,16 @@ const COMPLETION_WAKE_ID = /^(subagent|job):.+:done$/;
16
16
  export function isCoalescableWake(event) {
17
17
  return !event.internalWake && typeof event.dispatchId === "string" && COMPLETION_WAKE_ID.test(event.dispatchId);
18
18
  }
19
+ /**
20
+ * Whether `candidate` may ride along in `primary`'s turn. The primary already passed
21
+ * `admitsSyntheticEvent` (spec 060, D7), so its desk is the channel's current one; a candidate is
22
+ * folded in only when it was produced for that same desk, so a wake left over from before a rebind
23
+ * (or a malformed record with no owning desk) never reaches the new desk's model. It stays queued
24
+ * and its own admission drops it.
25
+ */
26
+ export function canAbsorbWake(primary, candidate) {
27
+ return isCoalescableWake(candidate) && candidate.desk === primary.desk;
28
+ }
19
29
  /** The primary wake keeps its own text (and `[KIND:id]` tag) first; the others follow it. */
20
30
  export function mergeCompletionWakes(primary, others) {
21
31
  if (others.length === 0)
@@ -62,10 +62,11 @@ function mergeSecurityConfig(source, configPath, diagnostics) {
62
62
  const pathGuard = isRecord(source.pathGuard) ? source.pathGuard : {};
63
63
  const networkGuard = isRecord(source.networkGuard) ? source.networkGuard : {};
64
64
  const audit = isRecord(source.audit) ? source.audit : {};
65
- // Unlike the sections above, presence itself is meaningful (D3.2): a missing `projectAccess`
66
- // key must stay `undefined`, not fall back to `{}`, so the resolver in project-scope.ts can
67
- // tell "never configured" apart from "configured with defaults".
68
- const projectAccess = isRecord(source.projectAccess) ? source.projectAccess : undefined;
65
+ // Retired by spec 058 (D9): project scope is gone and a desk's directory is the working
66
+ // directory. Warned about, then ignored — the same treatment as `RETIRED_SETTINGS_KEYS`.
67
+ if ("projectAccess" in source) {
68
+ pushInvalidSecurityDiagnostic(diagnostics, configPath, "projectAccess", "retired key ignored: project scope was removed; the desk directory is now the working directory");
69
+ }
69
70
  if (networkGuard.maxRedirects !== undefined) {
70
71
  const maxRedirects = networkGuard.maxRedirects;
71
72
  const isValidMaxRedirects = typeof maxRedirects === "number" && Number.isFinite(maxRedirects) && maxRedirects > 0;
@@ -111,12 +112,6 @@ function mergeSecurityConfig(source, configPath, diagnostics) {
111
112
  logBlocked: typeof audit.logBlocked === "boolean" ? audit.logBlocked : DEFAULT_SECURITY_CONFIG.audit.logBlocked,
112
113
  logFile: asOptionalString(audit.logFile),
113
114
  },
114
- projectAccess: projectAccess
115
- ? {
116
- defaultRoot: asOptionalString(projectAccess.defaultRoot),
117
- allowedRoots: asStringArray(projectAccess.allowedRoots),
118
- }
119
- : undefined,
120
115
  };
121
116
  }
122
117
  export function getSecurityConfigPath(appHomeDir = APP_HOME_DIR) {
@@ -22,7 +22,7 @@ function getAppender(path) {
22
22
  export async function logSecurityEvent(workspaceDir, config, event) {
23
23
  // external-agent records a permitted action, not a blocked one (spec 040, D8.1): it must not
24
24
  // disappear just because the operator only wants blocked-action logging.
25
- if (!config.audit.logBlocked && event.type !== "external-agent")
25
+ if (!config.audit.logBlocked && event.type !== "external-agent" && event.type !== "webapi-request")
26
26
  return;
27
27
  if (event.type === "external-agent") {
28
28
  // External agents bypass command-guard. Their complete dispatch record is therefore a