@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
@@ -2,7 +2,7 @@ import { randomBytes } from "node:crypto";
2
2
  import { chmod, mkdir, readdir, readFile, unlink } from "node:fs/promises";
3
3
  import { tmpdir } from "node:os";
4
4
  import { join } from "node:path";
5
- import { getChannelDir } from "../channel/channel-paths.js";
5
+ import { getDeskDir, getDeskLogsDir, isDeskName } from "../desk/paths.js";
6
6
  import { createFileStore } from "../file-store.js";
7
7
  import * as log from "../log.js";
8
8
  import { writeFileAtomically } from "../shared/atomic-file.js";
@@ -11,6 +11,8 @@ import { createSerialQueue } from "../shared/serial-queue.js";
11
11
  import { errorMessage } from "../shared/text-utils.js";
12
12
  import { beginWakeClaim, finishWakeClaim } from "../shared/wake-claim.js";
13
13
  import { logTaskDispatch, logTaskSettlement } from "../tasks/bound-work.js";
14
+ import { redeemTicket } from "../tasks/store.js";
15
+ import { buildJobCompletionWake, jobWakeDispatchId } from "./completion-wake.js";
14
16
  import { buildLaunchScript, jobArtifacts, parseLaunchOutput } from "./launch.js";
15
17
  import { isTerminal, parseJobRecord, toSnapshot } from "./record.js";
16
18
  /** Outcomes that prove the job's process is gone — safe to apply a terminal status. */
@@ -20,7 +22,7 @@ const KILL_CONFIRMED_GONE = new Set([
20
22
  "identity-mismatch",
21
23
  "no-target",
22
24
  ]);
23
- /** Cap on concurrently running jobs per channel, so a runaway model can't spawn unbounded processes. */
25
+ /** Cap on concurrently running jobs per desk, so a runaway model can't spawn unbounded processes. */
24
26
  export const MAX_RUNNING_JOBS = 5;
25
27
  /** Longest a single `poll` call blocks before returning a snapshot; the model can poll again. */
26
28
  export const POLL_WAIT_MS = 30_000;
@@ -55,9 +57,10 @@ function sleep(ms, signal) {
55
57
  }, { once: true });
56
58
  });
57
59
  }
58
- export class ChannelJobManager {
59
- constructor(channelId, executor, options = {}) {
60
- this.channelId = channelId;
60
+ export class DeskJobManager {
61
+ /** `target` owns these jobs (task logs live in its directory); each job's own channel gets its wake. */
62
+ constructor(target, executor, options = {}) {
63
+ this.target = target;
61
64
  this.executor = executor;
62
65
  this.jobs = new Map();
63
66
  this.wakeQueue = createSerialQueue();
@@ -156,25 +159,12 @@ export class ChannelJobManager {
156
159
  }, Math.max(0, nextExpiry - now));
157
160
  this.garbageCollectionTimer.unref?.();
158
161
  }
159
- get channel() {
160
- return this.channelId;
161
- }
162
162
  runningCount() {
163
163
  return Array.from(this.jobs.values()).filter((job) => job.status === "running").length;
164
164
  }
165
165
  listRunning() {
166
166
  return Array.from(this.jobs.values()).filter((job) => job.status === "running");
167
167
  }
168
- /** Task ids that a still-running job on this channel promises to wake. See `channelJobTaskIds`. */
169
- runningTaskIds() {
170
- const ids = new Set();
171
- for (const job of this.jobs.values()) {
172
- if (job.status === "running" && job.contract.notify && job.contract.taskId) {
173
- ids.add(job.contract.taskId);
174
- }
175
- }
176
- return ids;
177
- }
178
168
  /**
179
169
  * Launch a command in the background and return its snapshot. The wrapper (`buildLaunchScript`)
180
170
  * runs a readiness handshake before the command executes: only after the inner shell proves it
@@ -182,7 +172,7 @@ export class ChannelJobManager {
182
172
  * 0. A failed handshake, a non-zero launch, or an interrupted launch never creates a `running`
183
173
  * record; a persist failure right after a successful launch terminates the process (see below).
184
174
  */
185
- async start(command, label, timeoutSeconds, options = {}) {
175
+ async start(command, label, timeoutSeconds, options) {
186
176
  if (this.runningCount() >= MAX_RUNNING_JOBS) {
187
177
  throw new Error(`Too many background jobs already running (>= ${MAX_RUNNING_JOBS}). Poll or cancel some with the job tool first.`);
188
178
  }
@@ -200,7 +190,7 @@ export class ChannelJobManager {
200
190
  catch (error) {
201
191
  // The launch was aborted (or the executor could not run it). A detached child may
202
192
  // already be running — try to recover its pid and clean it up honestly.
203
- throw await this.recoverInterruptedLaunch(command, art, error);
193
+ throw await this.recoverInterruptedLaunch(art, error);
204
194
  }
205
195
  const launched = parseLaunchOutput(result.stdout);
206
196
  if (result.code !== 0 || launched.handshakeFailed) {
@@ -237,6 +227,7 @@ export class ChannelJobManager {
237
227
  exitFile: art.exitFile,
238
228
  timeoutSeconds,
239
229
  contract: { notify: options.notify ?? true, ...(options.taskId ? { taskId: options.taskId } : {}) },
230
+ channelId: options.channelId,
240
231
  };
241
232
  this.jobs.set(id, record);
242
233
  // The persisted record is the only thing that survives a restart — a detached process
@@ -270,8 +261,8 @@ export class ChannelJobManager {
270
261
  });
271
262
  throw failure;
272
263
  }
273
- if (options.taskId && this.options.channelDir) {
274
- await logTaskDispatch(this.options.channelDir, options.taskId, {
264
+ if (options.taskId && this.target.deskDir) {
265
+ await logTaskDispatch(this.target.deskDir, options.taskId, {
275
266
  ref: id,
276
267
  agent: "job",
277
268
  label,
@@ -291,7 +282,7 @@ export class ChannelJobManager {
291
282
  * its readiness handshake, so even an interrupted launch usually leaves a recoverable pid;
292
283
  * clean it up with no caller signal and return an error that is honest about what is known.
293
284
  */
294
- async recoverInterruptedLaunch(command, art, error) {
285
+ async recoverInterruptedLaunch(art, error) {
295
286
  const cause = errorMessage(error);
296
287
  const partialStdout = typeof error.stdout === "string" ? error.stdout : "";
297
288
  let launched = parseLaunchOutput(partialStdout);
@@ -311,19 +302,9 @@ export class ChannelJobManager {
311
302
  return new Error(`Background job launch was interrupted (${cause}); no pid could be recovered, so whether the command actually started cannot be confirmed. No job was created.`);
312
303
  }
313
304
  const provisional = {
314
- id: "(interrupted-launch)",
315
- label: "(interrupted launch)",
316
- command,
317
- status: "running",
318
- startedAt: Date.now(),
319
- durationMs: 0,
320
305
  pid,
321
306
  ...(launched.pgid !== undefined ? { pgid: launched.pgid } : {}),
322
307
  ...(launched.pidStartedAt ? { pidStartedAt: launched.pidStartedAt } : {}),
323
- spillFile: art.spillFile,
324
- exitFile: art.exitFile,
325
- timeoutSeconds: 0,
326
- contract: { notify: false },
327
308
  };
328
309
  const outcome = await this.runKill(provisional); // deliberately no signal
329
310
  await this.unlinkArtifacts(art);
@@ -566,12 +547,12 @@ export class ChannelJobManager {
566
547
  */
567
548
  async logSettlementToTask(record) {
568
549
  const taskId = record.contract.taskId;
569
- const channelDir = this.options.channelDir;
570
- if (!taskId || !channelDir || record.taskLogged)
550
+ const deskDir = this.target.deskDir;
551
+ if (!taskId || !deskDir || record.taskLogged)
571
552
  return;
572
553
  record.taskLogged = true;
573
554
  const output = await this.readOutput(record.id).catch(() => undefined);
574
- await logTaskSettlement(channelDir, taskId, {
555
+ await logTaskSettlement(deskDir, taskId, {
575
556
  ref: record.id,
576
557
  status: record.status,
577
558
  exitCode: record.exitCode,
@@ -597,37 +578,14 @@ export class ChannelJobManager {
597
578
  if (!this.options.dispatch || !record.contract.notify || record.notified) {
598
579
  return;
599
580
  }
581
+ const channelId = record.channelId;
582
+ if (this.options.isBoundTo && !this.options.isBoundTo(channelId, this.target.desk)) {
583
+ await this.suppressWake(record);
584
+ return;
585
+ }
600
586
  const output = await this.readOutput(record.id, signal);
601
587
  const tail = output?.text.slice(-WAKE_OUTPUT_TAIL_BYTES).trim();
602
- const exit = record.exitCode !== undefined ? `exit ${record.exitCode}` : record.status;
603
- const seconds = Math.round(record.durationMs / 1000);
604
- const belongsTo = record.contract.taskId ? ` It belongs to task ${record.contract.taskId}.` : "";
605
- const event = {
606
- type: this.channelId.startsWith("group_") ? "group" : "dm",
607
- channelId: this.channelId,
608
- user: "JOB",
609
- userName: "JOB",
610
- text: `[JOB:${record.id}] Background job "${record.label}" finished: ${record.status} (${exit}, ${seconds}s).${belongsTo} ` +
611
- `Command: ${record.command}\n` +
612
- `Output tail:\n${tail || "(no output)"}\n` +
613
- `Full output: ${record.spillFile}\n` +
614
- "Continue whatever was waiting on this job. If it needs no follow-up, respond with exactly [SILENT].",
615
- ts: String(Date.now()),
616
- conversationType: this.channelId.startsWith("group_") ? "2" : "1",
617
- dispatchId: `job:${this.channelId}:${record.id}:done`,
618
- // The result is awaited; the wake itself still runs without a progress card.
619
- presentation: "awaited",
620
- ...(record.contract.taskId
621
- ? {
622
- internalWake: {
623
- kind: "job",
624
- resourceId: record.id,
625
- taskId: record.contract.taskId,
626
- dispatchId: `job:${this.channelId}:${record.id}:done`,
627
- },
628
- }
629
- : {}),
630
- };
588
+ const event = buildJobCompletionWake({ desk: this.target.desk, channelId, record, tail });
631
589
  try {
632
590
  await this.options.dispatch(event);
633
591
  }
@@ -641,6 +599,24 @@ export class ChannelJobManager {
641
599
  record.notified = true;
642
600
  await this.persist(record);
643
601
  }
602
+ /** Same contract as `SubAgentRunManager.suppressWake`: drop the wake, still redeem the `work` ticket. */
603
+ async suppressWake(record) {
604
+ log.logInfoEvent("job.wake.suppressed", "Completion wake dropped: channel not bound to the job's desk", {
605
+ channelId: record.channelId,
606
+ fields: { jobId: record.id, desk: this.target.desk, taskId: record.contract.taskId },
607
+ });
608
+ const taskId = record.contract.taskId;
609
+ if (taskId && this.target.deskDir) {
610
+ await redeemTicket(this.target.deskDir, taskId, (ticket) => ticket.kind === "work").catch((error) => {
611
+ log.logWarn("job.wake.redeem_failed", "Work ticket redeem for a dropped wake failed", {
612
+ reason: errorMessage(error),
613
+ fields: { jobId: record.id, taskId },
614
+ });
615
+ });
616
+ }
617
+ record.notified = true;
618
+ await this.persist(record);
619
+ }
644
620
  /**
645
621
  * The shell command that terminates `record`'s process and prints one token describing what
646
622
  * happened (`TERMINATED` / `GONE` / `IDENTITY_MISMATCH` / `UNCONFIRMED`), or `undefined` when
@@ -707,7 +683,7 @@ export class ChannelJobManager {
707
683
  async beginWakeConsumption(id, taskId, dispatchId) {
708
684
  return this.wakeQueue.run(id, async () => {
709
685
  const record = this.jobs.get(id);
710
- const expected = `job:${this.channelId}:${id}:done`;
686
+ const expected = jobWakeDispatchId(this.target.desk, id);
711
687
  if (!record)
712
688
  return false;
713
689
  const eligible = record.status !== "running" && record.contract.taskId === taskId && dispatchId === expected;
@@ -892,45 +868,37 @@ export function createJobRuntime(executor, options = {}) {
892
868
  const config = { ...options };
893
869
  const managers = new Map();
894
870
  let stopped = false;
895
- function runningLines(channelId) {
896
- const manager = managers.get(channelId);
897
- if (!manager)
898
- return [];
899
- return manager.listRunning().map((job) => `后台作业 \`${job.id}\` 仍在运行:${job.command.slice(0, 80)}`);
900
- }
901
- function get(channelId) {
902
- let manager = managers.get(channelId);
871
+ function get(desk) {
872
+ let manager = managers.get(desk);
903
873
  if (!manager) {
904
- manager = new ChannelJobManager(channelId, executor, {
905
- ...(config.jobsStateDir ? { stateDir: join(config.jobsStateDir, channelId) } : {}),
906
- ...(config.workspaceDir
907
- ? {
908
- spillDir: join(getChannelDir(config.workspaceDir, channelId), "logs"),
909
- channelDir: getChannelDir(config.workspaceDir, channelId),
910
- }
911
- : {}),
874
+ const deskDir = config.workspaceDir ? getDeskDir(config.workspaceDir, desk) : undefined;
875
+ manager = new DeskJobManager({ desk, deskDir }, executor, {
876
+ ...(config.jobsStateDir ? { stateDir: join(config.jobsStateDir, desk) } : {}),
877
+ ...(deskDir ? { spillDir: getDeskLogsDir(deskDir) } : {}),
912
878
  ...(config.dispatch ? { dispatch: config.dispatch } : {}),
879
+ ...(config.isBoundTo ? { isBoundTo: config.isBoundTo } : {}),
913
880
  ...(config.sweepIntervalMs ? { sweepIntervalMs: config.sweepIntervalMs } : {}),
914
881
  });
915
- managers.set(channelId, manager);
882
+ managers.set(desk, manager);
916
883
  if (stopped)
917
884
  manager.stop();
918
885
  }
919
886
  return manager;
920
887
  }
921
888
  /**
922
- * Re-adopt every channel's persisted jobs at startup. Channels are discovered from the state
923
- * directory itself, so a job survives even when its channel has had no traffic since the restart.
889
+ * Re-adopt every desk's persisted jobs at startup. Desks are the record directories themselves,
890
+ * and restore does not depend on bindings (spec 058, D6): a job still running when its desk went
891
+ * dormant survives the restart too.
924
892
  */
925
893
  async function restore() {
926
894
  const jobsStateDir = config.jobsStateDir;
927
895
  if (!jobsStateDir)
928
896
  return 0;
929
- let channelIds;
897
+ let desks;
930
898
  try {
931
899
  await mkdir(jobsStateDir, { recursive: true });
932
- channelIds = (await readdir(jobsStateDir, { withFileTypes: true }))
933
- .filter((entry) => entry.isDirectory())
900
+ desks = (await readdir(jobsStateDir, { withFileTypes: true }))
901
+ .filter((entry) => entry.isDirectory() && isDeskName(entry.name))
934
902
  .map((entry) => entry.name);
935
903
  }
936
904
  catch (error) {
@@ -938,8 +906,8 @@ export function createJobRuntime(executor, options = {}) {
938
906
  return 0;
939
907
  }
940
908
  let restored = 0;
941
- for (const channelId of channelIds) {
942
- restored += await get(channelId).restore();
909
+ for (const desk of desks) {
910
+ restored += await get(desk).restore();
943
911
  }
944
912
  if (restored > 0) {
945
913
  log.logInfoEvent("job.restore.done", "Background job records restored", { fields: { count: restored } });
@@ -948,7 +916,6 @@ export function createJobRuntime(executor, options = {}) {
948
916
  }
949
917
  return {
950
918
  get,
951
- runningLines,
952
919
  restore,
953
920
  stop: () => {
954
921
  stopped = true;
@@ -12,6 +12,8 @@ export interface JobSnapshot {
12
12
  /** The task this job's completion wake belongs to, if any — lets a caller verify that a
13
13
  * `[JOB:<id>] ... belongs to task <taskId>.` wake actually names the job it claims to (T9). */
14
14
  taskId?: string;
15
+ /** The channel that started the job, where its completion wake goes; jobs are shared per desk. */
16
+ channelId: string;
15
17
  }
16
18
  /** What should happen when the job finishes. */
17
19
  export interface JobWakeContract {
@@ -11,6 +11,7 @@ export function parseJobRecord(raw) {
11
11
  const value = JSON.parse(raw);
12
12
  if (!isRecord(value) ||
13
13
  typeof value.id !== "string" ||
14
+ typeof value.channelId !== "string" ||
14
15
  typeof value.pid !== "number" ||
15
16
  typeof value.spillFile !== "string" ||
16
17
  typeof value.exitFile !== "string" ||
@@ -32,5 +33,6 @@ export function toSnapshot(record) {
32
33
  exitCode: record.exitCode,
33
34
  timeoutSeconds: record.timeoutSeconds,
34
35
  taskId: record.contract.taskId,
36
+ channelId: record.channelId,
35
37
  };
36
38
  }
package/dist/log.d.ts CHANGED
@@ -1,7 +1,6 @@
1
1
  export interface LogContext {
2
2
  channelId: string;
3
3
  userName?: string;
4
- channelName?: string;
5
4
  }
6
5
  export type LogLevel = "debug" | "info" | "warn" | "error";
7
6
  export interface LoggingConfig {
package/dist/log.js CHANGED
@@ -217,7 +217,7 @@ export function logResponse(ctx, text) {
217
217
  }
218
218
  // Compatibility helpers keep lower-risk call sites centralized while they use
219
219
  // the same output contract as structured events. The channel prefix accepts any non-blank id:
220
- // a group channel is `group_<conversationId>`, and DingTalk conversation ids are base64 (`+`, `/`,
220
+ // a group channel is `dingtalk:group:<conversationId>`, and DingTalk conversation ids are base64 (`+`, `/`,
221
221
  // `=`), which a word-character class silently failed to match — group logs lost their `channel`.
222
222
  function legacyContext(message) {
223
223
  const match = /^\[([^\]\s]+)\]\s*/.exec(message);
package/dist/main.js CHANGED
@@ -1,8 +1,9 @@
1
1
  #!/usr/bin/env node
2
2
  import { runAuth } from "./app/auth-command.js";
3
3
  import { formatCliCommandsHelp, isBootstrapExitError } from "./app/home.js";
4
+ import { StartupRefusal } from "./desk/startup-error.js";
4
5
  import * as log from "./log.js";
5
- import { bootstrap } from "./runtime/bootstrap.js";
6
+ import { bootstrap, bootstrapEmbedded } from "./runtime/bootstrap.js";
6
7
  import { errorMessage } from "./shared/text-utils.js";
7
8
  import { runTui } from "./tui/cli.js";
8
9
  /**
@@ -35,7 +36,7 @@ function handleError(error) {
35
36
  if (isBootstrapExitError(error)) {
36
37
  process.exit(error.code);
37
38
  }
38
- console.error(error);
39
+ console.error(error instanceof StartupRefusal ? error.message : error);
39
40
  process.exit(1);
40
41
  }
41
42
  const command = process.argv[2];
@@ -44,7 +45,13 @@ if (command === "tui") {
44
45
  // --print finishes. Exit explicitly: raw-mode stdin and the runner session
45
46
  // keep the event loop alive, so the process would otherwise hang after the UI
46
47
  // tears down.
47
- runTui(process.argv).then(() => process.exit(0), handleError);
48
+ runTui(process.argv, { startEmbeddedRuntime: bootstrapEmbedded }).then(() => process.exit(0), handleError);
49
+ }
50
+ else if (command === "webapi") {
51
+ // Only the key commands live here; the Web API itself is loaded by the daemon, if channel.json turns it on.
52
+ import("./webapi/key-command.js")
53
+ .then(({ runWebApiCommand }) => runWebApiCommand(process.argv))
54
+ .then(() => process.exit(0), handleError);
48
55
  }
49
56
  else if (command === "auth") {
50
57
  // readline keeps stdin open, so exit explicitly on success too.
@@ -0,0 +1,17 @@
1
+ import type { Api, Model } from "@earendil-works/pi-ai";
2
+ import type { SessionEntry } from "@earendil-works/pi-coding-agent";
3
+ import type { DeskConversation } from "../desk/types.js";
4
+ import { type DeskMemoryQueue } from "./desk-memory-queue.js";
5
+ export declare function hasBoundaryReflectWork(conversation: DeskConversation): Promise<boolean>;
6
+ /** Persist before context is replaced. No desk-memory queue/lock or model request on this path. */
7
+ export declare function enqueueBoundaryReflectWork(conversation: DeskConversation, entries: SessionEntry[], firstKeptEntryId: string, signal: AbortSignal): Promise<void>;
8
+ export interface BoundaryReflectOptions {
9
+ conversation: DeskConversation;
10
+ workspaceDir: string;
11
+ appHomeDir: string;
12
+ model: Model<Api>;
13
+ resolveApiKey: (model: Model<Api>) => Promise<string>;
14
+ queue?: DeskMemoryQueue;
15
+ }
16
+ /** Called by the live lifecycle and the startup/idle scheduler, including when idle maintenance is off. */
17
+ export declare function drainBoundaryReflectWork(options: BoundaryReflectOptions): Promise<void>;
@@ -0,0 +1,162 @@
1
+ /** Durable pre-compaction reflect snapshots. Inference never holds up the compaction hook. */
2
+ import { createHash } from "node:crypto";
3
+ import { access, readdir, readFile, unlink } from "node:fs/promises";
4
+ import { join } from "node:path";
5
+ import { getMemoryWorkDir } from "../desk/paths.js";
6
+ import * as log from "../log.js";
7
+ import { writeFileAtomically } from "../shared/atomic-file.js";
8
+ import { formatLocalTime, parseLocalTime } from "../shared/local-time.js";
9
+ import { isNodeError } from "../shared/os.js";
10
+ import { errorMessage } from "../shared/text-utils.js";
11
+ import { isRecord } from "../shared/type-guards.js";
12
+ import { getDeskMemoryQueue } from "./desk-memory-queue.js";
13
+ import { readMemoryMaintenanceState, updateMemoryMaintenanceState } from "./maintenance-state.js";
14
+ import { runReflect } from "./reflect.js";
15
+ import { appendMemoryReviewLog } from "./review-log.js";
16
+ import { sanitizeMessagesForMemory } from "./transcript.js";
17
+ function workDir(conversation) {
18
+ return join(getMemoryWorkDir(conversation.deskDir), conversation.conversation);
19
+ }
20
+ async function pendingFiles(conversation) {
21
+ try {
22
+ return (await readdir(workDir(conversation))).filter((name) => /^[a-f0-9]{32}\.json$/.test(name)).sort();
23
+ }
24
+ catch (error) {
25
+ if (isNodeError(error) && error.code === "ENOENT")
26
+ return [];
27
+ throw error;
28
+ }
29
+ }
30
+ async function completed(conversation, id) {
31
+ try {
32
+ await access(join(workDir(conversation), `${id}.done`));
33
+ return true;
34
+ }
35
+ catch (error) {
36
+ if (isNodeError(error) && error.code === "ENOENT")
37
+ return false;
38
+ throw error;
39
+ }
40
+ }
41
+ export async function hasBoundaryReflectWork(conversation) {
42
+ return (await pendingFiles(conversation)).length > 0;
43
+ }
44
+ /** Persist before context is replaced. No desk-memory queue/lock or model request on this path. */
45
+ export async function enqueueBoundaryReflectWork(conversation, entries, firstKeptEntryId, signal) {
46
+ signal.throwIfAborted();
47
+ const cut = entries.findIndex((entry) => entry.id === firstKeptEntryId);
48
+ if (cut < 0)
49
+ throw new Error("Cannot preserve compaction memory: kept entry is missing. Use /new to recover.");
50
+ const prefix = entries.slice(0, cut);
51
+ if (prefix.length === 0)
52
+ return;
53
+ const id = createHash("sha256")
54
+ .update(prefix.map((entry) => entry.id).join("\0"))
55
+ .digest("hex")
56
+ .slice(0, 32);
57
+ if (await completed(conversation, id))
58
+ return;
59
+ signal.throwIfAborted();
60
+ const work = {
61
+ version: 1,
62
+ id,
63
+ createdAt: Date.now(),
64
+ entryIds: prefix.map((entry) => entry.id),
65
+ messages: prefix.flatMap((entry) => entry.type === "message"
66
+ ? sanitizeMessagesForMemory([entry.message]).map((message) => ({ entryId: entry.id, message }))
67
+ : []),
68
+ };
69
+ await writeFileAtomically(join(workDir(conversation), `${id}.json`), `${JSON.stringify(work)}\n`);
70
+ signal.throwIfAborted();
71
+ }
72
+ /** Called by the live lifecycle and the startup/idle scheduler, including when idle maintenance is off. */
73
+ export async function drainBoundaryReflectWork(options) {
74
+ const { conversation, appHomeDir } = options;
75
+ try {
76
+ if (!(await hasBoundaryReflectWork(conversation)))
77
+ return;
78
+ const queue = options.queue ?? getDeskMemoryQueue();
79
+ await queue.run(conversation, async () => {
80
+ const maintenance = await readMemoryMaintenanceState(appHomeDir, conversation);
81
+ const retryAt = maintenance.failureBackoffUntil ? parseLocalTime(maintenance.failureBackoffUntil) : undefined;
82
+ if (retryAt !== undefined && retryAt > Date.now())
83
+ return;
84
+ const files = await pendingFiles(conversation);
85
+ const work = [];
86
+ for (const file of files) {
87
+ if (await completed(conversation, file.slice(0, -5))) {
88
+ await unlink(join(workDir(conversation), file));
89
+ continue;
90
+ }
91
+ const value = JSON.parse(await readFile(join(workDir(conversation), file), "utf8"));
92
+ if (!isRecord(value) ||
93
+ value.version !== 1 ||
94
+ typeof value.createdAt !== "number" ||
95
+ !Number.isFinite(value.createdAt) ||
96
+ value.id !== file.slice(0, -5) ||
97
+ !Array.isArray(value.entryIds) ||
98
+ value.entryIds.length === 0 ||
99
+ !value.entryIds.every((id) => typeof id === "string") ||
100
+ !Array.isArray(value.messages) ||
101
+ !value.messages.every((item) => isRecord(item) &&
102
+ typeof item.entryId === "string" &&
103
+ isRecord(item.message) &&
104
+ ["user", "assistant"].includes(String(item.message.role)))) {
105
+ throw new Error(`Corrupt memory work ${file}; inspect it on the server before retrying.`);
106
+ }
107
+ work.push(value);
108
+ }
109
+ work.sort((a, b) => a.createdAt - b.createdAt);
110
+ for (const item of work) {
111
+ const state = await readMemoryMaintenanceState(appHomeDir, conversation);
112
+ const cursor = state.lastReflectedEntryId ? item.entryIds.indexOf(state.lastReflectedEntryId) : -1;
113
+ const remaining = new Set(item.entryIds.slice(cursor + 1));
114
+ const messages = item.messages
115
+ .filter((entry) => remaining.has(entry.entryId))
116
+ .map((entry) => entry.message);
117
+ // A crash after checkpointing but before removing the work must not repeat inference.
118
+ if (cursor !== item.entryIds.length - 1) {
119
+ const result = await runReflect({
120
+ channelId: conversation.channelId,
121
+ deskDir: conversation.deskDir,
122
+ workspaceDir: options.workspaceDir,
123
+ model: options.model,
124
+ resolveApiKey: options.resolveApiKey,
125
+ messages,
126
+ usageContext: { channelId: conversation.channelId, desk: conversation.desk, correlationId: item.id },
127
+ });
128
+ await appendMemoryReviewLog(conversation.deskDir, {
129
+ timestamp: formatLocalTime(),
130
+ channelId: conversation.channelId,
131
+ reason: "reflect-boundary",
132
+ correlationId: item.id,
133
+ actions: [{ target: "memory", action: "reflect", added: result.added, updated: result.updated }],
134
+ });
135
+ }
136
+ await updateMemoryMaintenanceState(appHomeDir, conversation, (current) => ({
137
+ ...current,
138
+ // A later session/idle pass may already be ahead of this snapshot.
139
+ lastReflectedEntryId: !current.lastReflectedEntryId || item.entryIds.includes(current.lastReflectedEntryId)
140
+ ? item.entryIds.at(-1)
141
+ : current.lastReflectedEntryId,
142
+ }));
143
+ await updateMemoryMaintenanceState(appHomeDir, conversation, (current) => ({
144
+ ...current,
145
+ failureBackoffUntil: null,
146
+ }));
147
+ await writeFileAtomically(join(workDir(conversation), `${item.id}.done`), `${item.id}\n`);
148
+ await unlink(join(workDir(conversation), `${item.id}.json`));
149
+ }
150
+ });
151
+ }
152
+ catch (error) {
153
+ await updateMemoryMaintenanceState(appHomeDir, conversation, (current) => ({
154
+ ...current,
155
+ failureBackoffUntil: formatLocalTime(new Date(Date.now() + 30 * 60_000)),
156
+ })).catch(() => undefined);
157
+ log.logWarn("memory.boundary.failed", "Boundary memory reflect failed", {
158
+ channelId: conversation.channelId,
159
+ reason: errorMessage(error),
160
+ });
161
+ }
162
+ }
@@ -1,12 +1,13 @@
1
+ import type { DeskConversation } from "../desk/types.js";
1
2
  /**
2
3
  * Spec 050, D10: `/memory` is the no-LLM control surface — it must work even when the model or
3
4
  * the reflect pass is unavailable. `status` / `list` / `show` / `journal` are pure reads over
4
- * `store.ts` / `journal.ts`; `forget` is the one write, going through the same channel memory
5
+ * `store.ts` / `journal.ts`; `forget` is the one write, going through the same desk memory
5
6
  * queue as the tool and reflect so it never races them.
6
7
  */
7
8
  interface MemoryCommandOptions {
8
- channelId: string;
9
- channelDir: string;
9
+ /** The asking conversation: memory is read from its desk, maintenance state from it. */
10
+ conversation: DeskConversation;
10
11
  appHomeDir?: string;
11
12
  args: string;
12
13
  }