@oyasmi/pipiclaw 0.9.4-beta.2 → 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 +9 -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,21 +1,23 @@
1
1
  /**
2
- * The daemon's composition root: loads config and builds the bot, durable dispatch, jobs, delegation
3
- * runs, the events, memory and task services, then wires the per-channel handler (`turn-handler.ts`)
4
- * and the ordered shutdown (`shutdown.ts`).
2
+ * The daemon's composition root: loads config and builds the transports, the ingress, durable
3
+ * dispatch, jobs, delegation runs, the events, memory and task services, then wires the ordered
4
+ * shutdown (`shutdown.ts`).
5
5
  */
6
6
  import { join } from "path";
7
7
  import { loadDetachedMaintenanceContext } from "../agent/maintenance-context.js";
8
8
  import { createRunner } from "../agent/runner-factory.js";
9
- import { scanWorkspaceForInterruptedTurns } from "../agent/turn/turn-recovery.js";
9
+ import { scanConversationsForInterruptedTurns } from "../agent/turn/turn-recovery.js";
10
10
  import { BootstrapExitError, bootstrapAppHome, DEFAULT_BOOTSTRAP_PATHS, parseArgs, printBootstrapSummary, printFirstRunGuide, readCliVersion, } from "../app/home.js";
11
11
  import { prepareAppServices } from "../app/services.js";
12
- import { createChannelIndex } from "../channel/channel-index.js";
13
- import { ensureChannelDir, getChannelDir } from "../channel/channel-paths.js";
12
+ import { CHANNELS_INDEX_FILENAME, createChannelIndex } from "../channel/channel-index.js";
14
13
  import { ChannelStore } from "../channel/store.js";
15
14
  import { PipiclawSettingsManager } from "../config/settings.js";
16
15
  import { getToolsConfigPath, loadToolsConfig } from "../config/tools.js";
17
- import { DingTalkBot } from "../dingtalk/bot.js";
18
- import { loadConfig } from "../dingtalk/config.js";
16
+ import { buildDeskList } from "../desk/commands.js";
17
+ import { initializeDefaultDesk } from "../desk/default.js";
18
+ import { getDeskDir } from "../desk/paths.js";
19
+ import { listDesks } from "../desk/registry.js";
20
+ import { StartupRefusal } from "../desk/startup-error.js";
19
21
  import { createEventsWatcher } from "../events/watcher.js";
20
22
  import { createExecutor } from "../executor.js";
21
23
  import { createJobRuntime } from "../jobs/manager.js";
@@ -23,17 +25,21 @@ import * as log from "../log.js";
23
25
  import { MemoryMaintenanceScheduler } from "../memory/scheduler.js";
24
26
  import { defaultModel } from "../models/runtime.js";
25
27
  import { loadSecurityConfigWithDiagnostics } from "../security/config.js";
28
+ import { logSecurityEvent } from "../security/logger.js";
26
29
  import { fileStamp } from "../shared/format.js";
27
30
  import { errorMessage } from "../shared/text-utils.js";
28
31
  import { renderRunNotice } from "../subagents/commands.js";
29
32
  import { createSubAgentRuntime } from "../subagents/run-registry.js";
30
33
  import { getUsageLedger } from "../usage/ledger.js";
34
+ import { acquireDaemonLock, tryAcquireDaemonLock } from "./daemon-lock.js";
35
+ import { DeskRuntime } from "./desk-runtime.js";
31
36
  import { DurableDispatchService, renderDispatchExhaustedNotice } from "./durable-dispatch.js";
37
+ import { createIngress } from "./ingress.js";
38
+ import { createRequestExecution } from "./request-execution.js";
32
39
  import { createShutdown } from "./shutdown.js";
33
40
  import { TaskDriver } from "./task-driver.js";
34
- import { migrateTasksToV5 } from "./task-migration.js";
35
41
  import { createTaskSpawner } from "./task-spawn.js";
36
- import { createTurnHandler } from "./turn-handler.js";
42
+ import { createTransportRegistry, loadTransports } from "./transports.js";
37
43
  /**
38
44
  * Ceiling on cached runners per daemon process. A long-lived daemon otherwise accumulates one
39
45
  * `ChannelRunner` (session, subscriptions, memory state) per distinct channel it has ever heard
@@ -55,20 +61,52 @@ async function evictIdleRunnersOverCap(channelRunners) {
55
61
  break;
56
62
  if (runner.isBusy())
57
63
  continue;
58
- channelRunners.delete(channelId);
59
- await runner.dispose().catch((err) => {
60
- log.logWarn("runtime.runner.evict_dispose_failed", "Evicted runner dispose failed", {
61
- channelId: channelId,
62
- reason: errorMessage(err),
63
- });
64
- });
64
+ await releaseCachedRunner(channelRunners, channelId);
65
65
  }
66
66
  }
67
+ /**
68
+ * Take a channel's runner out of the cache, then dispose it: the next message builds a fresh one
69
+ * from the channel's current binding. Used by LRU eviction and by `/desk bind` (spec 058, D5 step
70
+ * 5), whose final reflect writes into the desk the runner belonged to.
71
+ */
72
+ async function releaseCachedRunner(channelRunners, channelId) {
73
+ const runner = channelRunners.get(channelId);
74
+ if (!runner)
75
+ return;
76
+ channelRunners.delete(channelId);
77
+ await runner.dispose().catch((err) => {
78
+ log.logWarn("runtime.runner.dispose_failed", "Released runner dispose failed", {
79
+ channelId: channelId,
80
+ reason: errorMessage(err),
81
+ });
82
+ });
83
+ }
84
+ /** The security audit log as a transport's `audit` callback; the config is read when the first event arrives. */
85
+ function securityAudit(paths) {
86
+ let config;
87
+ return (event) => {
88
+ config ??= loadSecurityConfigWithDiagnostics(paths.appHomeDir).config;
89
+ void logSecurityEvent(paths.workspaceDir, config, event);
90
+ };
91
+ }
67
92
  export async function createRuntimeContext(options) {
93
+ // One runtime per app home (INV-11): a second one would write the same desks, sessions and
94
+ // state files with no lock between them. Taken before anything is touched.
95
+ const daemonLock = options.daemonLock ?? (await acquireDaemonLock(options.paths.appHomeDir));
96
+ try {
97
+ initializeDefaultDesk(options.paths);
98
+ return await buildRuntimeContext(options, daemonLock);
99
+ }
100
+ catch (error) {
101
+ await daemonLock.release();
102
+ throw error;
103
+ }
104
+ }
105
+ async function buildRuntimeContext(options, daemonLock) {
68
106
  const startServices = options.startServices ?? true;
69
107
  const registerSignalHandlers = options.registerSignalHandlers ?? true;
70
- const store = new ChannelStore({ workingDir: options.paths.workspaceDir });
71
- const runtimeSettingsManager = options.settingsManager ?? new PipiclawSettingsManager(options.paths.appHomeDir);
108
+ const { workspaceDir, appHomeDir } = options.paths;
109
+ const runtimeSettingsManager = options.settingsManager ?? new PipiclawSettingsManager(appHomeDir);
72
110
  log.configureLogging(runtimeSettingsManager.getLoggingSettings());
73
111
  const startedAt = Date.now();
74
112
  const cliVersion = readCliVersion();
@@ -77,11 +115,93 @@ export async function createRuntimeContext(options) {
77
115
  const activeTasks = new Set();
78
116
  /** Channels with a `/stop` watchdog in flight, so a burst of `/stop` starts only one. */
79
117
  const stopWatchdogs = new Set();
80
- // `workspace/CHANNELS.md`: names every channel id so the workspace, the logs and the agent
81
- // stop dealing in `group_cid...`. Writes are debounced internally (see channel-index.ts).
82
- const channelIndex = createChannelIndex({ workspaceDir: options.paths.workspaceDir });
83
118
  let durableDispatch;
84
119
  let shuttingDown = false;
120
+ const executor = options.executor ?? createExecutor();
121
+ const dispatch = (event) => durableDispatch?.dispatch(event) ?? false;
122
+ // The transports this process hosts. A delivered answer is archived through `store`, which is
123
+ // built below: the closure only runs once a turn is under way.
124
+ const transports = createTransportRegistry(options.transports ??
125
+ (await loadTransports({
126
+ paths: options.paths,
127
+ stateDir: join(appHomeDir, "state"),
128
+ audit: securityAudit(options.paths),
129
+ archiveBotResponse: (channelId, text) => store.logBotResponse(channelId, text, Date.now().toString()),
130
+ })));
131
+ /** Say something to a channel outside any turn; whether it was delivered. */
132
+ const pushTo = (channelId, message) => transports.forChannel(channelId)?.push(channelId, message) ?? Promise.resolve(false);
133
+ // The one authority on bindings and active desks (spec 058, D6). `ingress`, `taskDriver` and the
134
+ // spawner are resolved lazily by its callbacks: none of them runs before this function returns.
135
+ const deskRuntime = new DeskRuntime({
136
+ workspaceDir,
137
+ conversationKindOf: (channelId) => transports.conversationKindOf(channelId),
138
+ recover: async (conversations) => {
139
+ // Spec 043, D10 point 1: repair turns interrupted by the last shutdown/crash before any of
140
+ // these channels takes traffic — a dangling session would 400 against the provider on
141
+ // every attempt until a human ran /new.
142
+ const report = await scanConversationsForInterruptedTurns(conversations, {
143
+ api: defaultModel.api,
144
+ provider: defaultModel.provider,
145
+ model: defaultModel.id,
146
+ });
147
+ if (report.repaired.length > 0) {
148
+ log.logWarn("runtime.recovery.repaired", "Interrupted turns repaired on restart", {
149
+ fields: {
150
+ repaired: report.repaired.length,
151
+ scanned: report.scanned,
152
+ channels: report.repaired.map((r) => r.conversation.channelId),
153
+ },
154
+ });
155
+ }
156
+ if (report.blocked.length > 0) {
157
+ log.logWarn("runtime.recovery.blocked", "Channels with an unrecoverable session will refuse new turns", {
158
+ reason: report.blocked.map((b) => `${b.conversation.channelId}: ${b.reason}`).join("; "),
159
+ });
160
+ }
161
+ },
162
+ createWatcher: (target) => options.createEventsWatcher
163
+ ? options.createEventsWatcher(target)
164
+ : createEventsWatcher({
165
+ ...target,
166
+ isBound: (channelId) => deskRuntime.isBoundTo(channelId, target.desk),
167
+ isReachable: (channelId) => transports.isReachable(channelId),
168
+ sink: ingress,
169
+ executor,
170
+ commandGuardConfig: loadSecurityConfigWithDiagnostics(appHomeDir).config.commandGuard,
171
+ historyPath: options.paths.eventHistoryPath,
172
+ dispatch,
173
+ spawnTask: createTaskSpawner({
174
+ getDeskDir: (desk) => getDeskDir(workspaceDir, desk),
175
+ nudge: () => getTaskDriver().nudge?.(),
176
+ notify: (desk, channelId, text) => deskRuntime.sendFromDesk(desk, channelId, text),
177
+ }),
178
+ }),
179
+ send: (channelId, text) => pushTo(channelId, { text }),
180
+ isChannelBusy: (channelId) => channelRunners.get(channelId)?.isBusy() ?? false,
181
+ releaseRunner: (channelId) => releaseCachedRunner(channelRunners, channelId),
182
+ onBindingChanged: () => channelIndex.noteBindingChanged(),
183
+ });
184
+ await deskRuntime.load();
185
+ const isBoundTo = (channelId, desk) => deskRuntime.isBoundTo(channelId, desk);
186
+ const store = new ChannelStore({
187
+ resolveArchiveDir: (channelId) => {
188
+ const resolution = deskRuntime.resolve(channelId);
189
+ return resolution.kind === "bound" ? resolution.conversation.conversationDir : undefined;
190
+ },
191
+ });
192
+ // `workspace/CHANNELS.md`: names every channel id (and shows its desk) so the workspace, the logs
193
+ // and `/desk` stop dealing in `group_cid...`. Writes are debounced internally.
194
+ const channelIndex = createChannelIndex({
195
+ workspaceDir,
196
+ getBoundDesk: (channelId) => deskRuntime.boundDesk(channelId),
197
+ });
198
+ await channelIndex.load();
199
+ // How a channel is named to a user: its transport says.
200
+ const labelOf = (channelId) => transports.describeChannel(channelId, channelIndex.nameOf(channelId));
201
+ const describeChannel = (desk, channelId) => ({
202
+ label: labelOf(channelId),
203
+ boundHere: deskRuntime.isBoundTo(channelId, desk),
204
+ });
85
205
  const archiveIncomingMessage = async (channelId, message, contextLabel) => {
86
206
  try {
87
207
  await store.logMessage(channelId, message);
@@ -94,28 +214,46 @@ export async function createRuntimeContext(options) {
94
214
  });
95
215
  }
96
216
  };
217
+ /**
218
+ * The channel's runner, or `undefined` when it is not bound to an available desk — the runtime
219
+ * never builds a runner (or a directory) for an unbound channel (INV-2).
220
+ */
97
221
  const getRunner = (channelId) => {
222
+ const resolution = deskRuntime.resolve(channelId);
223
+ if (resolution.kind !== "bound")
224
+ return undefined;
225
+ const { conversation } = resolution;
98
226
  const existing = channelRunners.get(channelId);
99
- if (existing) {
227
+ if (existing && existing.conversation.desk === conversation.desk) {
100
228
  // Re-insert to move this channel to the end (most-recently-used) of the Map's
101
229
  // iteration order, which evictIdleRunnersOverCap relies on.
102
230
  channelRunners.delete(channelId);
103
231
  channelRunners.set(channelId, existing);
104
232
  return existing;
105
233
  }
106
- const channelDir = ensureChannelDir(options.paths.workspaceDir, channelId);
107
- const runner = createRunner(channelId, channelDir, {
108
- jobManager: jobs.get(channelId),
109
- runManager: runs.get(channelId),
110
- appHomeDir: options.paths.appHomeDir,
234
+ const runner = createRunner(conversation, {
235
+ jobManager: jobs.get(conversation.desk),
236
+ runManager: runs.get(conversation.desk),
237
+ appHomeDir,
238
+ workspaceDir,
111
239
  authConfigPath: options.paths.authConfigPath,
112
240
  modelsConfigPath: options.paths.modelsConfigPath,
113
241
  settingsManager: runtimeSettingsManager,
114
242
  onSessionEvent: options.observer,
115
- // The DingTalk bot is the media sender for this transport; enables `send_media`.
116
- // `bot` is defined below in this same scope and initialized before any message
117
- // (and thus any getRunner call) can arrive.
118
- mediaSender: bot,
243
+ describeChannel: (id) => (channelIndex.nameOf(id) ? labelOf(id) : undefined),
244
+ describeConversation: (dir) => {
245
+ const owner = deskRuntime.channelOfConversation(conversation.desk, dir);
246
+ return owner ? labelOf(owner) : undefined;
247
+ },
248
+ // Enables `send_media`: the file goes out through the transport that owns this channel.
249
+ ...(transports.forChannel(channelId)?.sendsMedia === false
250
+ ? {}
251
+ : {
252
+ sendMedia: async (id, media) => (await transports.forChannel(id)?.sendMedia(id, media)) ?? {
253
+ ok: false,
254
+ error: "This channel cannot receive attachments. Tell the user the file's path on the server instead.",
255
+ },
256
+ }),
119
257
  });
120
258
  channelRunners.set(channelId, runner);
121
259
  void evictIdleRunnersOverCap(channelRunners);
@@ -123,15 +261,32 @@ export async function createRuntimeContext(options) {
123
261
  };
124
262
  const isShuttingDown = () => shuttingDown;
125
263
  const getDurableDispatch = () => durableDispatch;
126
- // `executor`/`taskDriver` are declared further down this function (after `bot`, which the
127
- // task driver's own `notify` needs) — these two closures resolve them lazily, the same way
128
- // `getRunner` above already resolves `bot` before its own declaration: nothing here calls
129
- // through them until long after the whole function has finished setting up.
264
+ // `jobs`/`runs`/`taskDriver` are declared further down; these closures resolve them lazily.
130
265
  const getJobs = () => jobs;
131
266
  const getRuns = () => runs;
132
267
  const getTaskDriver = () => taskDriver;
133
- const handler = createTurnHandler({
268
+ const ingress = createIngress({
269
+ requestExecution: createRequestExecution({
270
+ workspaceDir,
271
+ runners: channelRunners,
272
+ activeTasks,
273
+ transports,
274
+ store,
275
+ isShuttingDown,
276
+ createRunner: (conversation) => createRunner(conversation, {
277
+ requestScoped: true,
278
+ jobManager: jobs.get(conversation.desk),
279
+ runManager: runs.get(conversation.desk),
280
+ appHomeDir,
281
+ workspaceDir,
282
+ authConfigPath: options.paths.authConfigPath,
283
+ modelsConfigPath: options.paths.modelsConfigPath,
284
+ settingsManager: runtimeSettingsManager,
285
+ onSessionEvent: options.observer,
286
+ }),
287
+ }),
134
288
  options,
289
+ transports,
135
290
  store,
136
291
  channelRunners,
137
292
  sessionResetChains,
@@ -140,6 +295,16 @@ export async function createRuntimeContext(options) {
140
295
  channelIndex,
141
296
  archiveIncomingMessage,
142
297
  getRunner,
298
+ resolveChannel: (channelId) => deskRuntime.resolve(channelId),
299
+ ensureBinding: (channelId, desk) => deskRuntime.ensureDefaultBinding(channelId, desk),
300
+ unbind: (channelId) => deskRuntime.unbind(channelId),
301
+ deskPort: (channelId) => ({
302
+ list: async () => buildDeskList(await listDesks(workspaceDir), deskRuntime.bindingTable(), deskRuntime.boundDesk(channelId), labelOf),
303
+ channelIndexPath: join(workspaceDir, CHANNELS_INDEX_FILENAME),
304
+ create: (name) => deskRuntime.create(name),
305
+ bind: (name) => deskRuntime.bind(channelId, name),
306
+ }),
307
+ describeChannel,
143
308
  cliVersion,
144
309
  startedAt,
145
310
  isShuttingDown,
@@ -147,45 +312,43 @@ export async function createRuntimeContext(options) {
147
312
  getJobs,
148
313
  getRuns,
149
314
  getTaskDriver,
315
+ pushTo,
150
316
  });
151
- const bot = options.createBot
152
- ? options.createBot(handler, options.dingtalkConfig)
153
- : new DingTalkBot(handler, options.dingtalkConfig);
154
- const dispatchStateDir = join(options.paths.appHomeDir, "state", "dispatch");
317
+ const dispatchStateDir = join(appHomeDir, "state", "dispatch");
155
318
  durableDispatch = new DurableDispatchService({
156
319
  stateDir: dispatchStateDir,
157
- bot,
158
- // A structured wake (job/subagent completion, task-driver) that keeps failing before it can
159
- // ever mark itself complete would otherwise redeliver forever (30s tick, no backoff prior to
160
- // this notice). Surface it once instead of looping silently; the record stays on disk for
161
- // inspection until a human clears it.
320
+ bot: ingress,
321
+ isReachable: (channelId) => transports.isReachable(channelId),
322
+ // A structured wake that keeps failing before it can mark itself complete would otherwise
323
+ // redeliver forever. Surface it once instead of looping silently; the record stays on disk
324
+ // for inspection until a human clears it. Like every background notice, only to a channel
325
+ // still bound to the wake's desk (D7).
162
326
  onExhausted: async (record) => {
163
327
  log.logEvent("warn", "dispatch.exhausted", "Dispatch exhausted", {
164
328
  ctx: { channelId: record.event.channelId },
165
329
  details: record.event.text.slice(0, 500),
166
- fields: { dispatchId: record.id, deliveries: record.deliveries, producer: record.event.user },
330
+ fields: { dispatchId: record.id, deliveries: record.deliveries, producer: record.event.producer },
167
331
  });
168
- await bot.sendPlain(record.event.channelId, renderDispatchExhaustedNotice(record, dispatchStateDir));
332
+ await deskRuntime.sendFromDesk(record.event.desk, record.event.channelId, renderDispatchExhaustedNotice(record, dispatchStateDir));
169
333
  },
170
334
  });
171
- const executor = options.executor ?? createExecutor();
172
- // Background jobs get their persistence root and their way to wake a channel before any turn
173
- // can start one, then re-adopt whatever survived the last shutdown (spec 031, D6).
335
+ // Background jobs and delegation runs are owned per desk (spec 058, D15); their completion wakes
336
+ // pass the producer-side binding check before they are dispatched.
174
337
  const jobs = createJobRuntime(executor, {
175
- jobsStateDir: join(options.paths.appHomeDir, "state", "jobs"),
176
- workspaceDir: options.paths.workspaceDir,
177
- dispatch: (event) => durableDispatch?.dispatch(event) ?? false,
338
+ jobsStateDir: join(appHomeDir, "state", "jobs"),
339
+ workspaceDir,
340
+ dispatch,
341
+ isBoundTo,
178
342
  ...(options.jobSweepIntervalMs ? { sweepIntervalMs: options.jobSweepIntervalMs } : {}),
179
343
  });
180
- // Delegation runs get the same treatment (spec 040, D1/D7): persistence root, wake delivery,
181
- // and the usage/archive authority, wired before any turn can start a run.
182
344
  const runs = createSubAgentRuntime({
183
- stateDir: join(options.paths.appHomeDir, "state", "subagent-runs"),
184
- dispatch: (event) => durableDispatch?.dispatch(event) ?? false,
185
- // P0-1/P1a: a best-effort out-of-band notice, independent of the completion wake — it reaches
186
- // the channel in roughly the time the run itself takes, not the wake turn's own LLM latency
187
- // on top of that. `notices: "off"` (settings.json) restores today's silent behavior.
188
- notify: (channelId, notice) => {
345
+ stateDir: join(appHomeDir, "state", "subagent-runs"),
346
+ workspaceDir,
347
+ dispatch,
348
+ isBoundTo,
349
+ // A best-effort out-of-band notice, independent of the completion wake. `notices: "off"`
350
+ // (settings.json) restores the silent behavior.
351
+ notify: (desk, channelId, notice) => {
189
352
  const level = runtimeSettingsManager.getDelegationSettings().notices;
190
353
  if (level === "off")
191
354
  return;
@@ -193,68 +356,33 @@ export async function createRuntimeContext(options) {
193
356
  return;
194
357
  const text = renderRunNotice(notice);
195
358
  if (text)
196
- void bot.sendPlain(channelId, text);
359
+ void deskRuntime.sendFromDesk(desk, channelId, text);
197
360
  },
198
361
  ledger: getUsageLedger(),
199
362
  store,
200
363
  });
201
364
  // Admission (bot.start() below) must not open until every persisted job and run is back in
202
- // memory: a message arriving mid-restore would see partial running-count/short-id/lease state,
203
- // and durableDispatch's redelivery of a pending completion wake would find no record to claim.
204
- // Spec 042 D11: `restoreChannelJobs` used to be a bare `void` while `restoreAllSubAgentRuns`
205
- // was already awaited — the same admission race P0-1 closed for delegation runs was still open
206
- // for background jobs.
365
+ // memory, and restore is independent of bindings (D6): a dormant desk's runs still settle.
207
366
  await jobs.restore();
208
367
  await runs.restore();
209
368
  runs.start();
210
- // Spec 043, D10 point 1: repair any turn interrupted by the last shutdown/crash before opening
211
- // admission — a message routed to a still-dangling session would 400 against the provider on
212
- // every attempt (F3) until a human ran /new. Runs before bot.start() for the same reason as
213
- // the job/run restores above: admission must see a structurally legal session, not a partial one.
214
- const recoveryReport = await scanWorkspaceForInterruptedTurns(options.paths.workspaceDir, {
215
- api: defaultModel.api,
216
- provider: defaultModel.provider,
217
- model: defaultModel.id,
218
- });
219
- if (recoveryReport.repaired.length > 0) {
220
- log.logWarn("runtime.recovery.repaired", "Interrupted turns repaired on restart", {
221
- fields: {
222
- repaired: recoveryReport.repaired.length,
223
- scanned: recoveryReport.scanned,
224
- channels: recoveryReport.repaired.map((r) => r.channelDir),
225
- },
226
- });
227
- }
228
- if (recoveryReport.blocked.length > 0) {
229
- log.logWarn("runtime.recovery.blocked", "Channels with an unrecoverable session will refuse new turns", {
230
- reason: recoveryReport.blocked.map((b) => `${b.channelDir}: ${b.reason}`).join("; "),
231
- });
232
- }
233
- const eventsWatcher = options.createEventsWatcher
234
- ? options.createEventsWatcher(options.paths.workspaceDir, bot, executor, options.paths.eventHistoryPath)
235
- : createEventsWatcher(options.paths.workspaceDir, bot, executor, loadSecurityConfigWithDiagnostics(options.paths.appHomeDir).config.commandGuard, options.paths.eventHistoryPath, (event) => durableDispatch?.dispatch(event) ?? false, createTaskSpawner({
236
- getChannelDir: (channelId) => getChannelDir(options.paths.workspaceDir, channelId),
237
- nudge: () => getTaskDriver().nudge?.(),
238
- notify: (channelId, text) => bot.sendPlain(channelId, text),
239
- }));
369
+ // Activation repairs each bound desk's conversations before its channels can take traffic.
370
+ await deskRuntime.activateBound();
240
371
  const memoryMaintenanceScheduler = options.createMemoryMaintenanceScheduler
241
372
  ? options.createMemoryMaintenanceScheduler()
242
373
  : new MemoryMaintenanceScheduler({
243
- appHomeDir: options.paths.appHomeDir,
244
- workspaceDir: options.paths.workspaceDir,
245
- getKnownChannelIds: () => channelRunners.keys(),
246
- // Channels active this boot reuse their runner's in-memory context; every
247
- // other discovered channel gets a lightweight disk-backed context instead
248
- // of resurrecting a full ChannelRunner (session, tools, sub-agents) that
249
- // would then sit in the runner cache forever.
250
- getRuntimeContext: async (channelId) => {
251
- const runner = channelRunners.get(channelId);
252
- if (runner) {
374
+ appHomeDir,
375
+ getConversations: () => deskRuntime.boundConversations(),
376
+ // Conversations active this boot reuse their runner's in-memory context; every other one
377
+ // gets a lightweight disk-backed context instead of resurrecting a full runner.
378
+ getRuntimeContext: async (conversation) => {
379
+ const runner = channelRunners.get(conversation.channelId);
380
+ if (runner && runner.conversation.desk === conversation.desk) {
253
381
  return runner.getMemoryMaintenanceContext();
254
382
  }
255
383
  return loadDetachedMaintenanceContext({
256
- channelId,
257
- channelDir: getChannelDir(options.paths.workspaceDir, channelId),
384
+ conversation,
385
+ workspaceDir,
258
386
  authConfigPath: options.paths.authConfigPath,
259
387
  modelsConfigPath: options.paths.modelsConfigPath,
260
388
  settingsManager: runtimeSettingsManager,
@@ -272,32 +400,34 @@ export async function createRuntimeContext(options) {
272
400
  let cachedToolsStamp;
273
401
  let cachedTasksEnabled = true;
274
402
  const tasksToolEnabled = () => {
275
- const stamp = fileStamp(getToolsConfigPath(options.paths.appHomeDir));
403
+ const stamp = fileStamp(getToolsConfigPath(appHomeDir));
276
404
  if (stamp !== cachedToolsStamp) {
277
405
  cachedToolsStamp = stamp;
278
- cachedTasksEnabled = loadToolsConfig(options.paths.appHomeDir).tools.tasks.enabled;
406
+ cachedTasksEnabled = loadToolsConfig(appHomeDir).tools.tasks.enabled;
279
407
  }
280
408
  return cachedTasksEnabled;
281
409
  };
282
410
  const taskDriver = options.createTaskDriver
283
411
  ? options.createTaskDriver()
284
412
  : new TaskDriver({
285
- workspaceDir: options.paths.workspaceDir,
286
- getKnownChannelIds: () => channelRunners.keys(),
413
+ getActiveDesks: () => deskRuntime.activeDesks(),
414
+ isBoundTo,
415
+ isReachable: (channelId) => transports.isReachable(channelId),
287
416
  isChannelActive: (channelId) => channelRunners.get(channelId)?.isBusy() ?? false,
288
- dispatch: (event) => durableDispatch?.dispatch(event) ?? false,
417
+ dispatch,
289
418
  onDispatch: options.onTaskDriverDispatch,
290
- notify: (receipt) => bot.sendPlain(receipt.channelId, receipt.text),
419
+ notify: (receipt) => receipt.desk ? deskRuntime.sendFromDesk(receipt.desk, receipt.channelId, receipt.text) : false,
291
420
  isEnabled: tasksToolEnabled,
292
421
  });
293
422
  const shutdownWithReason = createShutdown({
294
423
  taskDriver,
295
424
  getDurableDispatch,
296
425
  memoryMaintenanceScheduler,
297
- eventsWatcher,
426
+ deskRuntime,
298
427
  runs,
299
428
  jobs,
300
- bot,
429
+ transports,
430
+ ingress,
301
431
  store,
302
432
  channelIndex,
303
433
  channelRunners,
@@ -305,6 +435,7 @@ export async function createRuntimeContext(options) {
305
435
  markShuttingDown: () => {
306
436
  shuttingDown = true;
307
437
  },
438
+ releaseDaemonLock: () => daemonLock.release(),
308
439
  });
309
440
  if (registerSignalHandlers) {
310
441
  process.once("SIGINT", () => {
@@ -319,23 +450,19 @@ export async function createRuntimeContext(options) {
319
450
  });
320
451
  }
321
452
  if (startServices) {
322
- // Convert supported v3 task files and their schedules (v4 beta files are skipped) before services rely
323
- // on the v5 layout (spec 052, D12). Marker-gated and awaited: the pass writes event
324
- // templates the watcher is about to load, so the services must not start underneath it.
325
- // A failed or partial conversion throws and aborts startup: nothing may run on half-migrated state.
326
- await migrateTasksToV5(options.paths.workspaceDir, join(options.paths.appHomeDir, "state"));
327
- eventsWatcher.start();
453
+ deskRuntime.startServices();
328
454
  memoryMaintenanceScheduler.start();
329
455
  taskDriver.start();
330
456
  durableDispatch.start();
331
- void bot.start();
457
+ await transports.startAll(ingress);
332
458
  }
333
459
  return {
334
- handler,
460
+ ingress,
461
+ transports,
335
462
  jobs,
336
463
  runs,
464
+ desks: deskRuntime,
337
465
  store,
338
- bot,
339
466
  taskDriver,
340
467
  memoryMaintenance: memoryMaintenanceScheduler,
341
468
  shutdown: shutdownWithReason,
@@ -350,27 +477,72 @@ export async function bootstrap(argv, options = {}) {
350
477
  const bootstrapResult = bootstrapAppHome(paths);
351
478
  printBootstrapSummary(bootstrapResult, io, paths);
352
479
  // A freshly written template is the expected first-run outcome, not a failure: guide and exit 0.
353
- // A template that exists but is still unfilled is caught by `loadConfig` below and exits 1.
480
+ // A template that exists but is still unfilled is caught by the transport loader (`loadTransports`) and exits 1.
354
481
  if (bootstrapResult.channelTemplateCreated) {
355
482
  printFirstRunGuide(io, paths);
356
483
  throw new BootstrapExitError(0);
357
484
  }
358
- const dingtalkConfig = loadConfig(paths, io);
359
- dingtalkConfig.stateDir = paths.workspaceDir;
360
485
  const { settingsManager } = prepareAppServices(paths);
361
486
  log.logStartup(paths.workspaceDir);
362
- const runtime = await createRuntimeContext({
363
- paths,
364
- dingtalkConfig,
365
- registerSignalHandlers,
366
- startServices,
367
- settingsManager,
368
- });
487
+ let runtime;
488
+ try {
489
+ runtime = await createRuntimeContext({
490
+ paths,
491
+ ...(options.transports ? { transports: options.transports } : {}),
492
+ registerSignalHandlers,
493
+ startServices,
494
+ settingsManager,
495
+ });
496
+ }
497
+ catch (error) {
498
+ if (!(error instanceof StartupRefusal))
499
+ throw error;
500
+ io.error(error.message);
501
+ throw new BootstrapExitError(1);
502
+ }
369
503
  return {
370
- bot: runtime.bot,
371
504
  store: runtime.store,
372
505
  shutdown: async () => {
373
506
  await runtime.shutdown("manual");
374
507
  },
375
508
  };
376
509
  }
510
+ /**
511
+ * Start the runtime for `pipiclaw tui` when no daemon is running: only the Web API's local socket
512
+ * is switched on (the terminal is its client), whatever `channel.json` says. Returns `undefined`
513
+ * when another process already holds the app home — a daemon is running and the terminal should
514
+ * connect to it. The lock is taken exactly once and handed to the runtime.
515
+ */
516
+ export async function bootstrapEmbedded(paths, io) {
517
+ printBootstrapSummary(bootstrapAppHome(paths), io, paths);
518
+ const lock = await tryAcquireDaemonLock(paths.appHomeDir);
519
+ if (lock.kind === "held")
520
+ return undefined;
521
+ // The full-screen terminal owns stdout: the runtime logs to its file sink only.
522
+ log.setConsoleLoggingEnabled(false);
523
+ const { settingsManager } = prepareAppServices(paths);
524
+ log.logStartup(paths.workspaceDir);
525
+ const { WebApiTransport } = await import("../webapi/transport.js");
526
+ let runtime;
527
+ try {
528
+ runtime = await createRuntimeContext({
529
+ paths,
530
+ daemonLock: lock.handle,
531
+ transports: [
532
+ new WebApiTransport({
533
+ config: { socket: true, keys: [] },
534
+ stateDir: join(paths.appHomeDir, "state", "webapi"),
535
+ audit: securityAudit(paths),
536
+ }),
537
+ ],
538
+ registerSignalHandlers: false,
539
+ startServices: true,
540
+ settingsManager,
541
+ });
542
+ }
543
+ catch (error) {
544
+ await lock.handle.release();
545
+ throw error;
546
+ }
547
+ return { stop: () => runtime.shutdown("manual") };
548
+ }