@oyasmi/pipiclaw 0.9.4 → 0.9.5-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (405) hide show
  1. package/README.en.md +28 -22
  2. package/README.md +27 -21
  3. package/dist/agent/builtin-commands.d.ts +7 -2
  4. package/dist/agent/builtin-commands.js +19 -23
  5. package/dist/agent/channel-runner.d.ts +13 -13
  6. package/dist/agent/channel-runner.js +93 -76
  7. package/dist/agent/maintenance-context.d.ts +6 -5
  8. package/dist/agent/maintenance-context.js +15 -15
  9. package/dist/agent/prompt/manifest.js +1 -1
  10. package/dist/agent/prompt/resources.d.ts +1 -1
  11. package/dist/agent/prompt/resources.js +1 -1
  12. package/dist/agent/prompt/sections.js +4 -4
  13. package/dist/agent/runner-factory.d.ts +6 -6
  14. package/dist/agent/runner-factory.js +6 -7
  15. package/dist/agent/session/compaction-input.d.ts +6 -0
  16. package/dist/agent/session/compaction-input.js +75 -0
  17. package/dist/agent/session/compaction-snapshot.d.ts +30 -0
  18. package/dist/agent/session/compaction-snapshot.js +154 -0
  19. package/dist/agent/session/compaction-summary.d.ts +39 -0
  20. package/dist/agent/session/compaction-summary.js +158 -0
  21. package/dist/agent/session/compaction.d.ts +35 -0
  22. package/dist/agent/session/compaction.js +294 -0
  23. package/dist/agent/session/context-input.d.ts +15 -0
  24. package/dist/agent/session/context-input.js +82 -0
  25. package/dist/agent/session/context-snapshot.d.ts +11 -0
  26. package/dist/agent/session/context-snapshot.js +72 -0
  27. package/dist/agent/session/event-guards.d.ts +2 -0
  28. package/dist/agent/session/event-guards.js +4 -0
  29. package/dist/agent/session/request-tools.d.ts +3 -0
  30. package/dist/agent/session/request-tools.js +20 -0
  31. package/dist/agent/session/session-adapter.d.ts +2 -1
  32. package/dist/agent/session/session-adapter.js +6 -3
  33. package/dist/agent/session/session-events.d.ts +5 -4
  34. package/dist/agent/session/session-events.js +46 -59
  35. package/dist/agent/session/session-host.d.ts +29 -41
  36. package/dist/agent/session/session-host.js +86 -69
  37. package/dist/agent/session/settings-diagnostics.d.ts +5 -0
  38. package/dist/agent/session/settings-diagnostics.js +21 -0
  39. package/dist/agent/status-render.js +5 -2
  40. package/dist/{runtime → agent}/stop-watchdog.d.ts +3 -1
  41. package/dist/{runtime → agent}/stop-watchdog.js +7 -3
  42. package/dist/agent/turn/progress-formatter.d.ts +1 -3
  43. package/dist/agent/turn/progress-formatter.js +3 -22
  44. package/dist/agent/turn/task-digest.d.ts +4 -2
  45. package/dist/agent/turn/task-digest.js +7 -4
  46. package/dist/agent/turn/turn-context.d.ts +11 -7
  47. package/dist/agent/turn/turn-context.js +26 -18
  48. package/dist/agent/turn/turn-finish.d.ts +17 -5
  49. package/dist/agent/turn/turn-finish.js +51 -77
  50. package/dist/agent/turn/turn-input.d.ts +2 -2
  51. package/dist/agent/turn/turn-input.js +4 -3
  52. package/dist/agent/turn/turn-output.d.ts +19 -0
  53. package/dist/agent/turn/turn-output.js +41 -0
  54. package/dist/agent/turn/turn-pipeline.d.ts +11 -8
  55. package/dist/agent/turn/turn-pipeline.js +54 -55
  56. package/dist/agent/turn/turn-prompt.d.ts +1 -1
  57. package/dist/agent/turn/turn-recovery.d.ts +11 -10
  58. package/dist/agent/turn/turn-recovery.js +14 -29
  59. package/dist/agent/types.d.ts +31 -12
  60. package/dist/agent/types.js +2 -1
  61. package/dist/app/auth-command.js +1 -1
  62. package/dist/app/home.js +31 -15
  63. package/dist/channel/active-session-store.d.ts +14 -12
  64. package/dist/channel/active-session-store.js +29 -25
  65. package/dist/channel/attachments.d.ts +25 -0
  66. package/dist/channel/attachments.js +56 -0
  67. package/dist/channel/channel-context.d.ts +87 -96
  68. package/dist/channel/channel-context.js +1 -66
  69. package/dist/channel/channel-event.d.ts +51 -41
  70. package/dist/channel/channel-event.js +6 -11
  71. package/dist/channel/channel-id.d.ts +22 -0
  72. package/dist/channel/channel-id.js +13 -0
  73. package/dist/channel/channel-index.d.ts +17 -34
  74. package/dist/channel/channel-index.js +41 -80
  75. package/dist/channel/config.d.ts +10 -0
  76. package/dist/channel/config.js +55 -0
  77. package/dist/channel/ingress.d.ts +101 -0
  78. package/dist/channel/ingress.js +5 -0
  79. package/dist/channel/store.d.ts +13 -15
  80. package/dist/channel/store.js +21 -25
  81. package/dist/channel/transport.d.ts +99 -0
  82. package/dist/channel/turn-context.d.ts +23 -0
  83. package/dist/channel/turn-context.js +1 -0
  84. package/dist/commands/catalog.d.ts +4 -7
  85. package/dist/commands/catalog.js +24 -31
  86. package/dist/commands/router.d.ts +23 -12
  87. package/dist/commands/router.js +22 -24
  88. package/dist/config/settings.d.ts +5 -4
  89. package/dist/desk/bindings.d.ts +6 -0
  90. package/dist/desk/bindings.js +105 -0
  91. package/dist/desk/commands.d.ts +81 -0
  92. package/dist/desk/commands.js +145 -0
  93. package/dist/desk/default.d.ts +4 -0
  94. package/dist/desk/default.js +11 -0
  95. package/dist/desk/paths.d.ts +41 -0
  96. package/dist/desk/paths.js +81 -0
  97. package/dist/desk/registry.d.ts +17 -0
  98. package/dist/desk/registry.js +191 -0
  99. package/dist/desk/startup-error.d.ts +4 -0
  100. package/dist/desk/startup-error.js +7 -0
  101. package/dist/desk/types.d.ts +72 -0
  102. package/dist/desk/types.js +7 -0
  103. package/dist/dingtalk/bot.d.ts +18 -35
  104. package/dist/dingtalk/bot.js +21 -204
  105. package/dist/dingtalk/channel-ids.d.ts +15 -0
  106. package/dist/dingtalk/channel-ids.js +39 -0
  107. package/dist/dingtalk/config.d.ts +6 -3
  108. package/dist/dingtalk/config.js +13 -25
  109. package/dist/dingtalk/connection.d.ts +1 -0
  110. package/dist/dingtalk/connection.js +5 -4
  111. package/dist/dingtalk/conversation-meta.d.ts +10 -5
  112. package/dist/dingtalk/conversation-meta.js +72 -50
  113. package/dist/dingtalk/delivery.d.ts +30 -14
  114. package/dist/dingtalk/delivery.js +189 -62
  115. package/dist/dingtalk/inbound-media.d.ts +2 -18
  116. package/dist/dingtalk/inbound-media.js +0 -53
  117. package/dist/dingtalk/inbound.d.ts +10 -11
  118. package/dist/dingtalk/inbound.js +12 -19
  119. package/dist/dingtalk/media.d.ts +9 -11
  120. package/dist/dingtalk/media.js +18 -31
  121. package/dist/dingtalk/progress.d.ts +8 -0
  122. package/dist/dingtalk/progress.js +20 -0
  123. package/dist/dingtalk/response-mode.d.ts +13 -0
  124. package/dist/dingtalk/response-mode.js +31 -0
  125. package/dist/dingtalk/transport.d.ts +47 -0
  126. package/dist/dingtalk/transport.js +71 -0
  127. package/dist/events/commands.d.ts +7 -2
  128. package/dist/events/commands.js +40 -22
  129. package/dist/events/pre-action-error.d.ts +10 -0
  130. package/dist/events/pre-action-error.js +10 -0
  131. package/dist/events/types.d.ts +20 -2
  132. package/dist/events/watcher.d.ts +14 -7
  133. package/dist/events/watcher.js +49 -26
  134. package/dist/index.d.ts +4 -2
  135. package/dist/jobs/completion-wake.d.ts +14 -0
  136. package/dist/jobs/completion-wake.js +36 -0
  137. package/dist/jobs/manager.d.ts +27 -22
  138. package/dist/jobs/manager.js +58 -91
  139. package/dist/jobs/record.d.ts +2 -0
  140. package/dist/jobs/record.js +2 -0
  141. package/dist/log.d.ts +0 -1
  142. package/dist/log.js +1 -1
  143. package/dist/main.js +10 -3
  144. package/dist/memory/boundary-work.d.ts +17 -0
  145. package/dist/memory/boundary-work.js +162 -0
  146. package/dist/memory/commands.d.ts +4 -3
  147. package/dist/memory/commands.js +16 -16
  148. package/dist/memory/desk-memory-queue.d.ts +18 -0
  149. package/dist/memory/desk-memory-queue.js +33 -0
  150. package/dist/memory/index-budget.d.ts +3 -3
  151. package/dist/memory/index-budget.js +3 -3
  152. package/dist/memory/journal.d.ts +6 -6
  153. package/dist/memory/journal.js +14 -14
  154. package/dist/memory/lifecycle.d.ts +14 -21
  155. package/dist/memory/lifecycle.js +73 -103
  156. package/dist/memory/maintenance-state.d.ts +14 -15
  157. package/dist/memory/maintenance-state.js +43 -42
  158. package/dist/memory/reflect-job.d.ts +5 -4
  159. package/dist/memory/reflect-job.js +21 -15
  160. package/dist/memory/reflect.d.ts +2 -1
  161. package/dist/memory/reflect.js +13 -12
  162. package/dist/memory/render.d.ts +1 -1
  163. package/dist/memory/render.js +2 -2
  164. package/dist/memory/review-log.d.ts +4 -4
  165. package/dist/memory/review-log.js +5 -5
  166. package/dist/memory/scheduler.d.ts +12 -19
  167. package/dist/memory/scheduler.js +28 -64
  168. package/dist/memory/session-corpus.d.ts +4 -1
  169. package/dist/memory/session-corpus.js +70 -29
  170. package/dist/memory/session-search.d.ts +11 -3
  171. package/dist/memory/session-search.js +14 -11
  172. package/dist/memory/sidecar-worker.d.ts +1 -0
  173. package/dist/memory/sidecar-worker.js +57 -76
  174. package/dist/memory/source-window.d.ts +0 -6
  175. package/dist/memory/source-window.js +0 -20
  176. package/dist/memory/store.d.ts +12 -12
  177. package/dist/memory/store.js +44 -44
  178. package/dist/paths.d.ts +2 -0
  179. package/dist/paths.js +2 -0
  180. package/dist/playbooks/agent-delegation.md +16 -16
  181. package/dist/playbooks/background-jobs.md +5 -3
  182. package/dist/playbooks/event-scheduling.md +7 -5
  183. package/dist/playbooks/memory-and-learning.md +16 -12
  184. package/dist/playbooks/outbound-media.md +1 -1
  185. package/dist/playbooks/runtime-orientation.md +35 -23
  186. package/dist/playbooks/task-lead.md +13 -11
  187. package/dist/runtime/bootstrap.d.ts +36 -13
  188. package/dist/runtime/bootstrap.js +310 -138
  189. package/dist/runtime/channel-queue.d.ts +23 -0
  190. package/dist/{dingtalk → runtime}/channel-queue.js +20 -9
  191. package/dist/runtime/daemon-lock.d.ts +12 -0
  192. package/dist/runtime/daemon-lock.js +28 -0
  193. package/dist/runtime/desk-runtime.d.ts +131 -0
  194. package/dist/runtime/desk-runtime.js +402 -0
  195. package/dist/runtime/durable-dispatch.d.ts +11 -5
  196. package/dist/runtime/durable-dispatch.js +20 -8
  197. package/dist/runtime/inbound-images.d.ts +32 -10
  198. package/dist/runtime/inbound-images.js +95 -21
  199. package/dist/runtime/ingress-busy.d.ts +26 -0
  200. package/dist/runtime/ingress-busy.js +211 -0
  201. package/dist/runtime/ingress-commands.d.ts +7 -0
  202. package/dist/runtime/ingress-commands.js +162 -0
  203. package/dist/runtime/ingress-deps.d.ts +62 -0
  204. package/dist/runtime/ingress-deps.js +1 -0
  205. package/dist/runtime/ingress.d.ts +22 -0
  206. package/dist/runtime/ingress.js +376 -0
  207. package/dist/runtime/request-execution.d.ts +19 -0
  208. package/dist/runtime/request-execution.js +88 -0
  209. package/dist/runtime/shutdown.d.ts +13 -5
  210. package/dist/runtime/shutdown.js +10 -4
  211. package/dist/runtime/task-driver.d.ts +38 -22
  212. package/dist/runtime/task-driver.js +142 -116
  213. package/dist/runtime/task-spawn.d.ts +4 -4
  214. package/dist/runtime/task-spawn.js +6 -5
  215. package/dist/runtime/task-wake.d.ts +6 -4
  216. package/dist/runtime/task-wake.js +7 -7
  217. package/dist/runtime/transports.d.ts +32 -0
  218. package/dist/runtime/transports.js +101 -0
  219. package/dist/runtime/turn-run.d.ts +18 -9
  220. package/dist/runtime/turn-run.js +302 -71
  221. package/dist/runtime/wake-coalescing.d.ts +11 -3
  222. package/dist/runtime/wake-coalescing.js +10 -0
  223. package/dist/security/config.js +5 -10
  224. package/dist/security/logger.js +1 -1
  225. package/dist/security/path-guard.js +7 -63
  226. package/dist/security/types.d.ts +27 -30
  227. package/dist/security/types.js +0 -1
  228. package/dist/shared/atomic-file.d.ts +2 -0
  229. package/dist/shared/atomic-file.js +14 -1
  230. package/dist/shared/file-lock.d.ts +35 -0
  231. package/dist/shared/file-lock.js +195 -0
  232. package/dist/shared/with-timeout.d.ts +2 -0
  233. package/dist/shared/with-timeout.js +21 -0
  234. package/dist/skills/loader.d.ts +1 -1
  235. package/dist/skills/loader.js +2 -2
  236. package/dist/skills/workspace.js +2 -2
  237. package/dist/subagents/completion-wake.d.ts +11 -2
  238. package/dist/subagents/completion-wake.js +22 -9
  239. package/dist/subagents/discovery.js +1 -1
  240. package/dist/subagents/dispatch.d.ts +0 -10
  241. package/dist/subagents/dispatch.js +10 -28
  242. package/dist/subagents/external/dispatch.js +1 -1
  243. package/dist/subagents/external/run.d.ts +1 -1
  244. package/dist/subagents/external/run.js +3 -3
  245. package/dist/subagents/internal/run.js +1 -1
  246. package/dist/subagents/internal/worker.js +6 -14
  247. package/dist/subagents/run-archive.d.ts +11 -0
  248. package/dist/subagents/run-archive.js +49 -0
  249. package/dist/subagents/run-record.d.ts +9 -8
  250. package/dist/subagents/run-record.js +3 -3
  251. package/dist/subagents/run-registry.d.ts +5 -3
  252. package/dist/subagents/run-registry.js +22 -45
  253. package/dist/subagents/runs.d.ts +23 -13
  254. package/dist/subagents/runs.js +75 -82
  255. package/dist/subagents/task-envelope.js +9 -11
  256. package/dist/subagents/types.d.ts +6 -5
  257. package/dist/tasks/board.d.ts +1 -1
  258. package/dist/tasks/board.js +2 -2
  259. package/dist/tasks/bound-work.d.ts +2 -2
  260. package/dist/tasks/bound-work.js +7 -7
  261. package/dist/tasks/brief.d.ts +1 -1
  262. package/dist/tasks/brief.js +9 -9
  263. package/dist/tasks/commands.d.ts +11 -2
  264. package/dist/tasks/commands.js +66 -41
  265. package/dist/tasks/contract.d.ts +0 -2
  266. package/dist/tasks/contract.js +1 -3
  267. package/dist/tasks/create.d.ts +3 -1
  268. package/dist/tasks/create.js +10 -4
  269. package/dist/tasks/frontmatter.d.ts +6 -2
  270. package/dist/tasks/frontmatter.js +10 -10
  271. package/dist/tasks/loop-log.d.ts +7 -13
  272. package/dist/tasks/loop-log.js +14 -17
  273. package/dist/tasks/mutation-lock.d.ts +7 -5
  274. package/dist/tasks/mutation-lock.js +32 -9
  275. package/dist/tasks/session-path.d.ts +3 -3
  276. package/dist/tasks/session-path.js +5 -5
  277. package/dist/tasks/steer.d.ts +5 -5
  278. package/dist/tasks/steer.js +42 -40
  279. package/dist/tasks/store.d.ts +11 -11
  280. package/dist/tasks/store.js +32 -29
  281. package/dist/tools/bash.d.ts +5 -5
  282. package/dist/tools/bash.js +19 -18
  283. package/dist/tools/contract/names.d.ts +7 -0
  284. package/dist/tools/contract/names.js +22 -0
  285. package/dist/tools/edit.js +1 -1
  286. package/dist/tools/event-manage.d.ts +3 -1
  287. package/dist/tools/event-manage.js +34 -33
  288. package/dist/tools/glob.js +5 -5
  289. package/dist/tools/grep.js +2 -2
  290. package/dist/tools/index.d.ts +9 -8
  291. package/dist/tools/index.js +12 -16
  292. package/dist/tools/job.d.ts +4 -2
  293. package/dist/tools/job.js +11 -8
  294. package/dist/tools/memory-manage.d.ts +5 -3
  295. package/dist/tools/memory-manage.js +24 -24
  296. package/dist/tools/read.js +1 -1
  297. package/dist/tools/registry.d.ts +12 -8
  298. package/dist/tools/registry.js +13 -9
  299. package/dist/tools/send-media.d.ts +2 -2
  300. package/dist/tools/send-media.js +3 -3
  301. package/dist/tools/session-search.d.ts +3 -1
  302. package/dist/tools/session-search.js +8 -6
  303. package/dist/tools/subagent-manage.d.ts +2 -8
  304. package/dist/tools/subagent-manage.js +19 -15
  305. package/dist/tools/subagent.js +1 -1
  306. package/dist/tools/task-manage/create.js +1 -1
  307. package/dist/tools/task-manage/factory.js +2 -2
  308. package/dist/tools/task-manage/lifecycle.js +3 -1
  309. package/dist/tools/task-manage/log-view.js +2 -2
  310. package/dist/tools/task-manage/shared.js +3 -3
  311. package/dist/tools/task-manage/step-end.js +3 -3
  312. package/dist/tools/task-manage/types.d.ts +8 -3
  313. package/dist/tools/web-cache.d.ts +3 -3
  314. package/dist/tools/web-cache.js +12 -12
  315. package/dist/tools/web-fetch.d.ts +2 -2
  316. package/dist/tools/web-fetch.js +7 -7
  317. package/dist/tools/write-content.js +1 -1
  318. package/dist/tui/cli.d.ts +17 -5
  319. package/dist/tui/cli.js +90 -27
  320. package/dist/tui/client.d.ts +26 -0
  321. package/dist/tui/client.js +157 -0
  322. package/dist/tui/colors.d.ts +0 -1
  323. package/dist/tui/colors.js +0 -1
  324. package/dist/tui/commands.d.ts +10 -51
  325. package/dist/tui/commands.js +16 -39
  326. package/dist/tui/frontend.d.ts +2 -2
  327. package/dist/tui/frontend.js +2 -2
  328. package/dist/tui/pitui-frontend.d.ts +0 -2
  329. package/dist/tui/pitui-frontend.js +1 -6
  330. package/dist/tui/render.d.ts +62 -0
  331. package/dist/tui/render.js +123 -0
  332. package/dist/tui/session.d.ts +92 -0
  333. package/dist/tui/session.js +317 -0
  334. package/dist/usage/ledger.d.ts +5 -0
  335. package/dist/usage/ledger.js +2 -0
  336. package/dist/usage/render.d.ts +6 -1
  337. package/dist/usage/render.js +18 -13
  338. package/dist/webapi/auth.d.ts +13 -0
  339. package/dist/webapi/auth.js +29 -0
  340. package/dist/webapi/config.d.ts +29 -0
  341. package/dist/webapi/config.js +100 -0
  342. package/dist/webapi/errors.d.ts +39 -0
  343. package/dist/webapi/errors.js +32 -0
  344. package/dist/webapi/http.d.ts +25 -0
  345. package/dist/webapi/http.js +4 -0
  346. package/dist/webapi/ids.d.ts +9 -0
  347. package/dist/webapi/ids.js +20 -0
  348. package/dist/webapi/input.d.ts +17 -0
  349. package/dist/webapi/input.js +229 -0
  350. package/dist/webapi/items.d.ts +37 -0
  351. package/dist/webapi/items.js +48 -0
  352. package/dist/webapi/key-command.d.ts +2 -0
  353. package/dist/webapi/key-command.js +110 -0
  354. package/dist/webapi/limits.d.ts +47 -0
  355. package/dist/webapi/limits.js +48 -0
  356. package/dist/webapi/request-policy.d.ts +17 -0
  357. package/dist/webapi/request-policy.js +160 -0
  358. package/dist/webapi/response-record.d.ts +68 -0
  359. package/dist/webapi/response-record.js +58 -0
  360. package/dist/webapi/response-state.d.ts +90 -0
  361. package/dist/webapi/response-state.js +347 -0
  362. package/dist/webapi/routes/conversations.d.ts +8 -0
  363. package/dist/webapi/routes/conversations.js +80 -0
  364. package/dist/webapi/routes/models.d.ts +3 -0
  365. package/dist/webapi/routes/models.js +12 -0
  366. package/dist/webapi/routes/responses.d.ts +8 -0
  367. package/dist/webapi/routes/responses.js +118 -0
  368. package/dist/webapi/routes/websocket.d.ts +9 -0
  369. package/dist/webapi/routes/websocket.js +328 -0
  370. package/dist/webapi/server.d.ts +24 -0
  371. package/dist/webapi/server.js +229 -0
  372. package/dist/webapi/service.d.ts +130 -0
  373. package/dist/webapi/service.js +588 -0
  374. package/dist/webapi/store.d.ts +46 -0
  375. package/dist/webapi/store.js +245 -0
  376. package/dist/webapi/stream.d.ts +13 -0
  377. package/dist/webapi/stream.js +76 -0
  378. package/dist/webapi/transport.d.ts +43 -0
  379. package/dist/webapi/transport.js +100 -0
  380. package/package.json +8 -2
  381. package/dist/channel/channel-paths.d.ts +0 -16
  382. package/dist/channel/channel-paths.js +0 -53
  383. package/dist/channel/commands.d.ts +0 -32
  384. package/dist/channel/commands.js +0 -109
  385. package/dist/channel/project-scope-store.d.ts +0 -51
  386. package/dist/channel/project-scope-store.js +0 -112
  387. package/dist/dingtalk/channel-queue.d.ts +0 -19
  388. package/dist/dingtalk/handler.d.ts +0 -90
  389. package/dist/memory/channel-maintenance-queue.d.ts +0 -5
  390. package/dist/memory/channel-maintenance-queue.js +0 -8
  391. package/dist/runtime/task-migration.d.ts +0 -30
  392. package/dist/runtime/task-migration.js +0 -465
  393. package/dist/runtime/turn-handler.d.ts +0 -47
  394. package/dist/runtime/turn-handler.js +0 -318
  395. package/dist/security/project-scope.d.ts +0 -45
  396. package/dist/security/project-scope.js +0 -105
  397. package/dist/tui/app.d.ts +0 -16
  398. package/dist/tui/app.js +0 -166
  399. package/dist/tui/terminal-context.d.ts +0 -27
  400. package/dist/tui/terminal-context.js +0 -84
  401. package/dist/tui/terminal-media-sender.d.ts +0 -9
  402. package/dist/tui/terminal-media-sender.js +0 -15
  403. package/dist/tui/turn-controller.d.ts +0 -64
  404. package/dist/tui/turn-controller.js +0 -311
  405. /package/dist/{dingtalk/handler.js → channel/transport.js} +0 -0
@@ -1,59 +1,13 @@
1
- import { convertToLlm, serializeConversation } from "@earendil-works/pi-coding-agent";
2
1
  import * as log from "../log.js";
3
2
  import { formatLocalTime } from "../shared/local-time.js";
4
- import { clipTextByPromptUnits } from "../shared/prompt-units.js";
5
3
  import { errorMessage } from "../shared/text-utils.js";
6
- import { getDefaultChannelMemoryQueue } from "./channel-maintenance-queue.js";
4
+ import { drainBoundaryReflectWork, enqueueBoundaryReflectWork } from "./boundary-work.js";
5
+ import { getDeskMemoryQueue } from "./desk-memory-queue.js";
7
6
  import { readMemoryMaintenanceState, updateMemoryMaintenanceState, } from "./maintenance-state.js";
8
7
  import { runReflect } from "./reflect.js";
9
8
  import { reviewLogEntryFor } from "./reflect-job.js";
10
9
  import { appendMemoryReviewLog } from "./review-log.js";
11
- import { buildCompactionMemorySourceWindow, buildIncrementalMemorySourceWindow } from "./source-window.js";
12
- const COMPACTION_INPUT_MAX_UNITS = 48_000;
13
- const COMPACTION_INPUT_MIN_UNITS = 4_000;
14
- const COMPACTION_INPUT_CHARS_PER_TOKEN = 3;
15
- const COMPACTION_INPUT_HEAD_RATIO = 0.35;
16
- /**
17
- * Bound one standalone summarization request. Provider limits can be lower than a model's
18
- * advertised context window; sending the whole pre-compaction transcript is therefore not safe.
19
- * The head preserves the original goal and the larger tail preserves current work. Durable
20
- * memory is refreshed before this runs, so the omitted middle is still available outside the
21
- * provider request.
22
- */
23
- export function boundCompactionMessages(messages, contextWindow, reserveTokens) {
24
- if (messages.length === 0) {
25
- return { messages, truncated: false, originalChars: 0, boundedChars: 0 };
26
- }
27
- const safeWindow = Number.isFinite(contextWindow) && contextWindow > 0 ? Math.floor(contextWindow) : 128_000;
28
- const safeReserve = Number.isFinite(reserveTokens) && reserveTokens > 0 ? Math.floor(reserveTokens) : 16_384;
29
- const maxUnits = Math.min(COMPACTION_INPUT_MAX_UNITS, Math.max(COMPACTION_INPUT_MIN_UNITS, safeWindow - safeReserve - 8_192));
30
- const serialized = serializeConversation(convertToLlm(messages));
31
- const clipped = clipTextByPromptUnits(serialized, maxUnits, {
32
- headRatio: COMPACTION_INPUT_HEAD_RATIO,
33
- maxChars: maxUnits * COMPACTION_INPUT_CHARS_PER_TOKEN,
34
- marker: "\n\n[... middle omitted from this compaction request; durable channel memory was refreshed before compaction ...]\n\n",
35
- });
36
- if (!clipped.truncated) {
37
- return {
38
- messages,
39
- truncated: false,
40
- originalChars: serialized.length,
41
- boundedChars: serialized.length,
42
- };
43
- }
44
- return {
45
- messages: [
46
- {
47
- role: "user",
48
- content: [{ type: "text", text: clipped.text }],
49
- timestamp: Date.now(),
50
- },
51
- ],
52
- truncated: true,
53
- originalChars: serialized.length,
54
- boundedChars: clipped.text.length,
55
- };
56
- }
10
+ import { buildIncrementalMemorySourceWindow } from "./source-window.js";
57
11
  export class MemoryLifecycle {
58
12
  constructor(options) {
59
13
  this.options = options;
@@ -62,16 +16,18 @@ export class MemoryLifecycle {
62
16
  this.lastDurableConsolidationRevision = 0;
63
17
  // Tracks the detached new-session reflect run so shutdown/tests can await it.
64
18
  this.backgroundNewSessionReflect = Promise.resolve();
65
- this.channelMemoryQueue = options.channelMemoryQueue ?? getDefaultChannelMemoryQueue();
19
+ this.memoryQueue = options.memoryQueue ?? getDeskMemoryQueue();
66
20
  }
67
21
  createExtensionFactory() {
68
22
  return (pi) => {
69
- pi.on("session_before_compact", async (event) => {
70
- await this.handleSessionBeforeCompact(event);
71
- });
23
+ if (this.options.enabled === false)
24
+ return;
72
25
  pi.on("session_compact", async (event) => {
73
26
  this.handleSessionCompact(event);
74
27
  });
28
+ pi.on("session_compact_failed", () => {
29
+ this.startBoundaryReflect();
30
+ });
75
31
  pi.on("session_before_switch", (event) => {
76
32
  this.handleSessionBeforeSwitch(event);
77
33
  });
@@ -84,16 +40,23 @@ export class MemoryLifecycle {
84
40
  this.recordActivity("user-turn-started");
85
41
  }
86
42
  noteToolCall() {
43
+ if (this.options.enabled === false)
44
+ return;
87
45
  this.durableDirty = true;
88
46
  this.durableRevision++;
89
47
  this.recordActivity("tool-call");
90
48
  }
91
49
  noteCompletedAssistantTurn() {
50
+ if (this.options.enabled === false)
51
+ return;
92
52
  this.durableDirty = true;
93
53
  this.durableRevision++;
94
54
  this.recordActivity("assistant-turn-completed");
95
55
  }
96
56
  async flushForShutdown() {
57
+ if (this.options.enabled === false)
58
+ return;
59
+ await this.resumeBoundaryReflect();
97
60
  // Let any detached new-session reflect run finish (and update the durable checkpoint)
98
61
  // before deciding whether a final flush is still needed.
99
62
  await this.whenNewSessionReflectSettled();
@@ -111,7 +74,7 @@ export class MemoryLifecycle {
111
74
  });
112
75
  }
113
76
  runDurableMemoryJobSerial(job) {
114
- return this.channelMemoryQueue.run(this.options.channelId, job);
77
+ return this.memoryQueue.run(this.options.conversation, job);
115
78
  }
116
79
  // Any unconsolidated durable activity since the last checkpoint, regardless of whether it
117
80
  // ended on an assistant turn. Used only for the shutdown flush.
@@ -125,68 +88,65 @@ export class MemoryLifecycle {
125
88
  logReflectResult(reason, result) {
126
89
  if (result.skipped) {
127
90
  log.logEvent("debug", "memory.reflect.skipped", "No meaningful snapshot", {
128
- ctx: { channelId: this.options.channelId },
91
+ ctx: { channelId: this.options.conversation.channelId },
129
92
  fields: { reason },
130
93
  });
131
94
  return;
132
95
  }
133
- log.logInfo(`[${this.options.channelId}] Memory reflect finished (${reason}): added=${result.added.length} updated=${result.updated.length} deleted=${result.deleted.length} touched=${result.touched.length} journal+=${result.journalAppended}`);
96
+ log.logInfo(`[${this.options.conversation.channelId}] Memory reflect finished (${reason}): added=${result.added.length} updated=${result.updated.length} deleted=${result.deleted.length} touched=${result.touched.length} journal+=${result.journalAppended}`);
134
97
  }
135
98
  async appendReviewLog(entry) {
136
99
  try {
137
- await appendMemoryReviewLog(this.options.channelDir, {
100
+ await appendMemoryReviewLog(this.options.conversation.deskDir, {
138
101
  timestamp: formatLocalTime(),
139
- channelId: this.options.channelId,
102
+ channelId: this.options.conversation.channelId,
140
103
  ...entry,
141
104
  });
142
105
  }
143
106
  catch (error) {
144
107
  const message = errorMessage(error);
145
108
  log.logWarn("memory.review_log.write_failed", "Memory review log write failed", {
146
- channelId: this.options.channelId,
109
+ channelId: this.options.conversation.channelId,
147
110
  reason: message,
148
111
  });
149
112
  }
150
113
  }
151
- async runBoundaryReflect(reason, messages, sessionEntries, firstKeptEntryId) {
114
+ async runBoundaryReflect(reason, messages, sessionEntries) {
152
115
  const messageSnapshot = [...(messages ?? this.options.getMessages())];
153
116
  const sessionEntrySnapshot = sessionEntries ? [...sessionEntries] : [...this.options.getSessionEntries()];
154
117
  const revisionSnapshot = this.durableRevision;
155
118
  await this.runDurableMemoryJobSerial(async () => {
156
- await this.runBoundaryReflectNow(reason, messageSnapshot, sessionEntrySnapshot, revisionSnapshot, firstKeptEntryId);
119
+ await this.runBoundaryReflectNow(reason, messageSnapshot, sessionEntrySnapshot, revisionSnapshot);
157
120
  });
158
121
  }
159
- async runBoundaryReflectNow(reason, messageSnapshot, sessionEntrySnapshot = [], revisionSnapshot = this.durableRevision, firstKeptEntryId) {
122
+ async runBoundaryReflectNow(reason, messageSnapshot, sessionEntrySnapshot = [], revisionSnapshot = this.durableRevision) {
160
123
  try {
161
124
  const maintenanceState = this.options.appHomeDir
162
- ? await readMemoryMaintenanceState(this.options.appHomeDir, this.options.channelId)
125
+ ? await readMemoryMaintenanceState(this.options.appHomeDir, this.options.conversation)
163
126
  : undefined;
164
127
  const lastEntryId = maintenanceState?.lastReflectedEntryId;
165
- const sourceWindow = reason === "compaction"
166
- ? buildCompactionMemorySourceWindow({
167
- entries: sessionEntrySnapshot,
168
- messagesToSummarize: messageSnapshot,
169
- firstKeptEntryId,
170
- lastEntryId,
171
- })
172
- : buildIncrementalMemorySourceWindow({
173
- entries: sessionEntrySnapshot,
174
- lastEntryId,
175
- sourceKind: reason,
176
- fallbackMessages: messageSnapshot,
177
- });
178
- log.logInfo(`[${this.options.channelId}] Memory reflect starting (${reason})`);
128
+ const sourceWindow = buildIncrementalMemorySourceWindow({
129
+ entries: sessionEntrySnapshot,
130
+ lastEntryId,
131
+ sourceKind: reason,
132
+ fallbackMessages: messageSnapshot,
133
+ });
134
+ log.logInfo(`[${this.options.conversation.channelId}] Memory reflect starting (${reason})`);
179
135
  const result = await runReflect({
180
- channelId: this.options.channelId,
181
- channelDir: this.options.channelDir,
136
+ channelId: this.options.conversation.channelId,
137
+ deskDir: this.options.conversation.deskDir,
182
138
  workspaceDir: this.options.workspaceDir,
183
139
  model: this.options.getModel(),
184
140
  resolveApiKey: this.options.resolveApiKey,
185
141
  messages: sourceWindow.messages,
186
- usageContext: { channelId: this.options.channelId, correlationId: sourceWindow.windowId },
142
+ usageContext: {
143
+ channelId: this.options.conversation.channelId,
144
+ desk: this.options.conversation.desk,
145
+ correlationId: sourceWindow.windowId,
146
+ },
187
147
  });
188
148
  if (this.options.appHomeDir && sourceWindow.throughEntryId) {
189
- await updateMemoryMaintenanceState(this.options.appHomeDir, this.options.channelId, (current) => ({
149
+ await updateMemoryMaintenanceState(this.options.appHomeDir, this.options.conversation, (current) => ({
190
150
  ...current,
191
151
  lastReflectedEntryId: sourceWindow.throughEntryId,
192
152
  lastReflectAt: formatLocalTime(),
@@ -204,7 +164,7 @@ export class MemoryLifecycle {
204
164
  catch (error) {
205
165
  const message = errorMessage(error);
206
166
  log.logWarn("memory.reflect.failed", "Memory reflect failed", {
207
- channelId: this.options.channelId,
167
+ channelId: this.options.conversation.channelId,
208
168
  reason: message,
209
169
  fields: { trigger: reason },
210
170
  });
@@ -215,27 +175,33 @@ export class MemoryLifecycle {
215
175
  });
216
176
  }
217
177
  }
218
- async handleSessionBeforeCompact(event) {
219
- await this.runBoundaryReflect("compaction", event.preparation.messagesToSummarize, this.options.getSessionEntries(), event.preparation.firstKeptEntryId);
220
- const model = this.options.getModel();
221
- for (const key of ["messagesToSummarize", "turnPrefixMessages"]) {
222
- const bounded = boundCompactionMessages(event.preparation[key] ?? [], model.contextWindow, event.preparation.settings?.reserveTokens ?? 16_384);
223
- if (!bounded.truncated)
224
- continue;
225
- event.preparation[key] = bounded.messages;
226
- log.logWarn("memory.compaction_input.bounded", "Oversized compaction input bounded", {
227
- channelId: this.options.channelId,
228
- fields: {
229
- key,
230
- originalChars: bounded.originalChars,
231
- boundedChars: bounded.boundedChars,
232
- model: `${model.provider}/${model.id}`,
233
- },
234
- });
235
- }
178
+ /** The agent's bounded compaction operation awaits only durable snapshot persistence. */
179
+ async prepareCompaction(event) {
180
+ if (this.options.enabled === false)
181
+ return;
182
+ await enqueueBoundaryReflectWork(this.options.conversation, event.branchEntries, event.preparation.firstKeptEntryId, event.signal);
183
+ }
184
+ resumeBoundaryReflect() {
185
+ this.startBoundaryReflect();
186
+ return this.backgroundNewSessionReflect;
187
+ }
188
+ startBoundaryReflect() {
189
+ if (this.options.enabled === false)
190
+ return;
191
+ if (!this.options.appHomeDir)
192
+ return;
193
+ this.backgroundNewSessionReflect = drainBoundaryReflectWork({
194
+ conversation: this.options.conversation,
195
+ workspaceDir: this.options.workspaceDir,
196
+ appHomeDir: this.options.appHomeDir,
197
+ model: this.options.getModel(),
198
+ resolveApiKey: this.options.resolveApiKey,
199
+ queue: this.memoryQueue,
200
+ });
236
201
  }
237
202
  handleSessionCompact(_event) {
238
203
  this.recordActivity("boundary");
204
+ this.startBoundaryReflect();
239
205
  }
240
206
  handleSessionBeforeSwitch(event) {
241
207
  if (event.reason !== "new") {
@@ -245,6 +211,8 @@ export class MemoryLifecycle {
245
211
  }
246
212
  /** Snapshot the outgoing state for an out-of-band `/new` before its runner is retired. */
247
213
  noteNewSessionBoundary() {
214
+ if (this.options.enabled === false)
215
+ return;
248
216
  // Snapshot the outgoing session synchronously: the switch has not happened yet, so
249
217
  // getMessages()/getSessionEntries() still reference the session about to be replaced.
250
218
  // Once we yield, this.session is rebound to the new (empty) session and the snapshot
@@ -257,7 +225,7 @@ export class MemoryLifecycle {
257
225
  this.backgroundNewSessionReflect = this.runBoundaryReflect("new-session", messageSnapshot, sessionEntrySnapshot).catch((error) => {
258
226
  const message = errorMessage(error);
259
227
  log.logWarn("memory.reflect.rejected", "Background new-session reflect rejected", {
260
- channelId: this.options.channelId,
228
+ channelId: this.options.conversation.channelId,
261
229
  reason: message,
262
230
  });
263
231
  });
@@ -274,10 +242,12 @@ export class MemoryLifecycle {
274
242
  this.recordActivity("boundary");
275
243
  }
276
244
  recordActivity(kind) {
245
+ if (this.options.enabled === false)
246
+ return;
277
247
  const now = new Date();
278
248
  const event = {
279
249
  kind,
280
- channelId: this.options.channelId,
250
+ ref: this.options.conversation,
281
251
  timestamp: formatLocalTime(now),
282
252
  };
283
253
  try {
@@ -286,7 +256,7 @@ export class MemoryLifecycle {
286
256
  catch (error) {
287
257
  const message = errorMessage(error);
288
258
  log.logWarn("memory.activity.record_failed", "Memory activity record failed", {
289
- channelId: this.options.channelId,
259
+ channelId: this.options.conversation.channelId,
290
260
  reason: message,
291
261
  });
292
262
  }
@@ -1,3 +1,4 @@
1
+ import type { DeskConversation } from "../desk/types.js";
1
2
  /** Spec 050, D9: one job (reflect), one small state shape. */
2
3
  export interface MemoryMaintenanceState {
3
4
  channelId: string;
@@ -8,25 +9,23 @@ export interface MemoryMaintenanceState {
8
9
  lastReflectedEntryId?: string;
9
10
  failureBackoffUntil?: string | null;
10
11
  }
12
+ /**
13
+ * Which conversation a maintenance state belongs to (spec 058, D12): reflect works one
14
+ * conversation at a time, so its dirty flag, idle clock and checkpoint are per conversation.
15
+ */
16
+ export type MaintenanceStateRef = Pick<DeskConversation, "desk" | "conversation" | "channelId">;
11
17
  export type MemoryActivityKind = "user-turn-started" | "tool-call" | "assistant-turn-completed" | "boundary";
12
18
  export interface MemoryActivityEvent {
13
19
  kind: MemoryActivityKind;
14
- channelId: string;
20
+ ref: MaintenanceStateRef;
15
21
  timestamp: string;
16
22
  eligibleAfter?: string;
17
23
  }
18
24
  export declare function getMemoryMaintenanceStateDir(appHomeDir: string): string;
19
- /**
20
- * One flat file per channel, named by the same escaped form directories use.
21
- *
22
- * The id goes into a filename here, and a DingTalk group id routinely contains `/`, so writing
23
- * it raw put the file in a subdirectory of the state dir — `group_a/b==.json`. Reads and writes
24
- * agreed, so nothing was lost, but {@link getMemoryMaintenanceStateDir}'s only listing walks the
25
- * top level: every such channel was invisible to the scheduler's state-derived discovery.
26
- */
27
- export declare function getMemoryMaintenanceStatePath(appHomeDir: string, channelId: string): string;
28
- export declare function readMemoryMaintenanceState(appHomeDir: string, channelId: string): Promise<MemoryMaintenanceState>;
29
- export declare function updateMemoryMaintenanceState(appHomeDir: string, channelId: string, update: (state: MemoryMaintenanceState) => MemoryMaintenanceState): Promise<MemoryMaintenanceState>;
25
+ /** `state/memory/<desk>/<conversation>.json`: both segments are validated names, never a channel id. */
26
+ export declare function getMemoryMaintenanceStatePath(appHomeDir: string, ref: MaintenanceStateRef): string;
27
+ export declare function readMemoryMaintenanceState(appHomeDir: string, ref: MaintenanceStateRef): Promise<MemoryMaintenanceState>;
28
+ export declare function updateMemoryMaintenanceState(appHomeDir: string, ref: MaintenanceStateRef, update: (state: MemoryMaintenanceState) => MemoryMaintenanceState): Promise<MemoryMaintenanceState>;
30
29
  /** Apply a single activity event. The buffered path folds a whole burst through the same core. */
31
30
  export declare function applyMemoryActivityToState(state: MemoryMaintenanceState, event: MemoryActivityEvent): MemoryMaintenanceState;
32
31
  /**
@@ -46,14 +45,14 @@ export declare function applyMemoryActivityToState(state: MemoryMaintenanceState
46
45
  */
47
46
  export interface MemoryActivityRecorder {
48
47
  record(event: MemoryActivityEvent): void;
49
- /** Write out buffered activity for one channel, or for all of them when `channelId` is omitted. */
50
- flush(channelId?: string): Promise<void>;
48
+ /** Write out buffered activity for one conversation, or for all of them when `ref` is omitted. */
49
+ flush(ref?: MaintenanceStateRef): Promise<void>;
51
50
  }
52
51
  export declare const DEFAULT_ACTIVITY_FLUSH_DEBOUNCE_MS = 5000;
53
52
  export interface CreateMemoryActivityRecorderOptions {
54
53
  appHomeDir: string;
55
54
  /** Override the flush debounce; tests use a short one. */
56
55
  debounceMs?: number;
57
- onError?: (channelId: string, error: unknown) => void;
56
+ onError?: (ref: MaintenanceStateRef, error: unknown) => void;
58
57
  }
59
58
  export declare function createMemoryActivityRecorder(options: CreateMemoryActivityRecorderOptions): MemoryActivityRecorder;
@@ -1,6 +1,5 @@
1
1
  import { readFile } from "node:fs/promises";
2
2
  import { join } from "node:path";
3
- import { getChannelDirName } from "../channel/channel-paths.js";
4
3
  import * as log from "../log.js";
5
4
  import { writeFileAtomically } from "../shared/atomic-file.js";
6
5
  import { createSerialQueue } from "../shared/serial-queue.js";
@@ -9,16 +8,12 @@ const stateUpdateQueue = createSerialQueue();
9
8
  export function getMemoryMaintenanceStateDir(appHomeDir) {
10
9
  return join(appHomeDir, "state", "memory");
11
10
  }
12
- /**
13
- * One flat file per channel, named by the same escaped form directories use.
14
- *
15
- * The id goes into a filename here, and a DingTalk group id routinely contains `/`, so writing
16
- * it raw put the file in a subdirectory of the state dir — `group_a/b==.json`. Reads and writes
17
- * agreed, so nothing was lost, but {@link getMemoryMaintenanceStateDir}'s only listing walks the
18
- * top level: every such channel was invisible to the scheduler's state-derived discovery.
19
- */
20
- export function getMemoryMaintenanceStatePath(appHomeDir, channelId) {
21
- return join(getMemoryMaintenanceStateDir(appHomeDir), `${getChannelDirName(channelId)}.json`);
11
+ /** `state/memory/<desk>/<conversation>.json`: both segments are validated names, never a channel id. */
12
+ export function getMemoryMaintenanceStatePath(appHomeDir, ref) {
13
+ return join(getMemoryMaintenanceStateDir(appHomeDir), ref.desk, `${ref.conversation}.json`);
14
+ }
15
+ function refKey(ref) {
16
+ return `${ref.desk}/${ref.conversation}`;
22
17
  }
23
18
  function createDefaultState(channelId) {
24
19
  return { channelId, dirty: false, failureBackoffUntil: null };
@@ -47,8 +42,9 @@ function normalizeState(channelId, value) {
47
42
  failureBackoffUntil: normalizeOptionalNullableString(record.failureBackoffUntil) ?? null,
48
43
  };
49
44
  }
50
- export async function readMemoryMaintenanceState(appHomeDir, channelId) {
51
- const path = getMemoryMaintenanceStatePath(appHomeDir, channelId);
45
+ export async function readMemoryMaintenanceState(appHomeDir, ref) {
46
+ const { channelId } = ref;
47
+ const path = getMemoryMaintenanceStatePath(appHomeDir, ref);
52
48
  try {
53
49
  const raw = await readFile(path, "utf-8");
54
50
  return normalizeState(channelId, JSON.parse(raw));
@@ -61,15 +57,16 @@ export async function readMemoryMaintenanceState(appHomeDir, channelId) {
61
57
  log.logWarn("memory.state.read_failed", "Memory maintenance state unreadable; rebuilding defaults", {
62
58
  channelId: channelId,
63
59
  reason: message,
60
+ fields: { desk: ref.desk, conversation: ref.conversation },
64
61
  });
65
62
  return createDefaultState(channelId);
66
63
  }
67
64
  }
68
- export async function updateMemoryMaintenanceState(appHomeDir, channelId, update) {
69
- const path = getMemoryMaintenanceStatePath(appHomeDir, channelId);
65
+ export async function updateMemoryMaintenanceState(appHomeDir, ref, update) {
66
+ const path = getMemoryMaintenanceStatePath(appHomeDir, ref);
70
67
  return stateUpdateQueue.run(path, async () => {
71
- const current = await readMemoryMaintenanceState(appHomeDir, channelId);
72
- const next = normalizeState(channelId, update(current));
68
+ const current = await readMemoryMaintenanceState(appHomeDir, ref);
69
+ const next = normalizeState(ref.channelId, update(current));
73
70
  await writeFileAtomically(path, `${JSON.stringify(next, null, 2)}\n`);
74
71
  return next;
75
72
  });
@@ -94,64 +91,68 @@ function applyPendingActivityToState(state, channelId, pending) {
94
91
  }
95
92
  /** Apply a single activity event. The buffered path folds a whole burst through the same core. */
96
93
  export function applyMemoryActivityToState(state, event) {
97
- return applyPendingActivityToState(state, event.channelId, mergeMemoryActivity(undefined, event));
94
+ return applyPendingActivityToState(state, event.ref.channelId, mergeMemoryActivity(undefined, event));
98
95
  }
99
96
  export const DEFAULT_ACTIVITY_FLUSH_DEBOUNCE_MS = 5_000;
100
97
  export function createMemoryActivityRecorder(options) {
101
98
  const debounceMs = options.debounceMs ?? DEFAULT_ACTIVITY_FLUSH_DEBOUNCE_MS;
102
99
  const pending = new Map();
100
+ const refs = new Map();
103
101
  const timers = new Map();
104
- /** The most recent write per channel, so `flush` can await work another caller started. */
102
+ /** The most recent write per conversation, so `flush` can await work another caller started. */
105
103
  const inFlight = new Map();
106
- const cancelTimer = (channelId) => {
107
- const timer = timers.get(channelId);
104
+ const cancelTimer = (key) => {
105
+ const timer = timers.get(key);
108
106
  if (timer) {
109
107
  clearTimeout(timer);
110
- timers.delete(channelId);
108
+ timers.delete(key);
111
109
  }
112
110
  };
113
- const flushChannel = (channelId) => {
114
- cancelTimer(channelId);
115
- const delta = pending.get(channelId);
116
- if (!delta) {
117
- return inFlight.get(channelId) ?? Promise.resolve();
111
+ const flushConversation = (key) => {
112
+ cancelTimer(key);
113
+ const delta = pending.get(key);
114
+ const ref = refs.get(key);
115
+ if (!delta || !ref) {
116
+ return inFlight.get(key) ?? Promise.resolve();
118
117
  }
119
118
  // Cleared before the await so events arriving during the write start a fresh batch
120
119
  // instead of being swallowed by this one.
121
- pending.delete(channelId);
122
- const write = updateMemoryMaintenanceState(options.appHomeDir, channelId, (state) => applyPendingActivityToState(state, channelId, delta))
120
+ pending.delete(key);
121
+ const write = updateMemoryMaintenanceState(options.appHomeDir, ref, (state) => applyPendingActivityToState(state, ref.channelId, delta))
123
122
  .then(() => undefined)
124
123
  .catch((error) => {
125
124
  // Put the delta back so the counters are not silently lost; the next event (or
126
125
  // flush) retries it, folded in front of anything buffered while this write ran.
127
- pending.set(channelId, mergeBack(delta, pending.get(channelId)));
128
- options.onError?.(channelId, error);
126
+ pending.set(key, mergeBack(delta, pending.get(key)));
127
+ options.onError?.(ref, error);
129
128
  })
130
129
  .finally(() => {
131
- if (inFlight.get(channelId) === write) {
132
- inFlight.delete(channelId);
130
+ if (inFlight.get(key) === write) {
131
+ inFlight.delete(key);
133
132
  }
134
133
  });
135
- inFlight.set(channelId, write);
134
+ inFlight.set(key, write);
136
135
  return write;
137
136
  };
138
137
  return {
139
138
  record(event) {
140
- pending.set(event.channelId, mergeMemoryActivity(pending.get(event.channelId), event));
141
- if (timers.has(event.channelId)) {
139
+ const key = refKey(event.ref);
140
+ refs.set(key, event.ref);
141
+ pending.set(key, mergeMemoryActivity(pending.get(key), event));
142
+ if (timers.has(key)) {
142
143
  return;
143
144
  }
144
145
  const timer = setTimeout(() => {
145
- timers.delete(event.channelId);
146
- void flushChannel(event.channelId);
146
+ timers.delete(key);
147
+ void flushConversation(key);
147
148
  }, debounceMs);
148
149
  // Buffered counters are never a reason to keep the process alive.
149
150
  timer.unref?.();
150
- timers.set(event.channelId, timer);
151
+ timers.set(key, timer);
151
152
  },
152
- async flush(channelId) {
153
- const channelIds = channelId ? [channelId] : new Set([...pending.keys(), ...inFlight.keys()]);
154
- await Promise.all([...channelIds].map((id) => flushChannel(id)));
153
+ async flush(ref) {
154
+ const keys = ref ? [refKey(ref)] : new Set([...pending.keys(), ...inFlight.keys()]);
155
+ await Promise.all([...keys].map((key) => flushConversation(key)));
155
156
  },
156
157
  };
157
158
  }
@@ -1,7 +1,8 @@
1
1
  import type { AgentMessage } from "@earendil-works/pi-agent-core";
2
2
  import type { Api, Model } from "@earendil-works/pi-ai";
3
3
  import type { SessionEntry } from "@earendil-works/pi-coding-agent";
4
- import { type ChannelMemoryQueue } from "./channel-maintenance-queue.js";
4
+ import type { DeskConversation } from "../desk/types.js";
5
+ import { type DeskMemoryQueue } from "./desk-memory-queue.js";
5
6
  import { type MemoryMaintenanceInput } from "./maintenance-tuning.js";
6
7
  import { runReflect } from "./reflect.js";
7
8
  /**
@@ -12,8 +13,8 @@ import { runReflect } from "./reflect.js";
12
13
  */
13
14
  export interface ReflectJobInput {
14
15
  appHomeDir: string;
15
- channelId: string;
16
- channelDir: string;
16
+ /** The conversation to reflect on; its maintenance state is per conversation, its memory per desk. */
17
+ conversation: DeskConversation;
17
18
  workspaceDir: string;
18
19
  channelActive: boolean;
19
20
  now?: Date;
@@ -25,7 +26,7 @@ export interface ReflectJobInput {
25
26
  /** Transcript accessors: only called once the gate has decided the job may actually run. */
26
27
  messages: () => AgentMessage[];
27
28
  sessionEntries: () => SessionEntry[];
28
- queue?: ChannelMemoryQueue;
29
+ queue?: DeskMemoryQueue;
29
30
  }
30
31
  export declare function runReflectJob(input: ReflectJobInput): Promise<void>;
31
32
  /** Shared by the idle job and `lifecycle.ts`'s boundary calls, so both write the same shape. */
@@ -1,6 +1,7 @@
1
1
  import { formatLocalTime } from "../shared/local-time.js";
2
2
  import { errorMessage } from "../shared/text-utils.js";
3
- import { getDefaultChannelMemoryQueue } from "./channel-maintenance-queue.js";
3
+ import { drainBoundaryReflectWork } from "./boundary-work.js";
4
+ import { getDeskMemoryQueue } from "./desk-memory-queue.js";
4
5
  import { shouldRunReflect } from "./maintenance-gates.js";
5
6
  import { readMemoryMaintenanceState, updateMemoryMaintenanceState } from "./maintenance-state.js";
6
7
  import { resolveMemoryMaintenanceSettings, } from "./maintenance-tuning.js";
@@ -12,11 +13,16 @@ function backoffUntil(now, settings) {
12
13
  return formatLocalTime(new Date(now.getTime() + Math.max(0, settings.failureBackoffMinutes) * 60_000));
13
14
  }
14
15
  export async function runReflectJob(input) {
15
- const queue = input.queue ?? getDefaultChannelMemoryQueue();
16
- return queue.run(input.channelId, async () => {
16
+ const queue = input.queue ?? getDeskMemoryQueue();
17
+ const { conversation } = input;
18
+ const { channelId, deskDir } = conversation;
19
+ await drainBoundaryReflectWork({ ...input, queue });
20
+ if (!input.settings.memoryMaintenance.enabled)
21
+ return;
22
+ return queue.run(conversation, async () => {
17
23
  const now = input.now ?? new Date();
18
24
  const maintenance = resolveMemoryMaintenanceSettings(input.settings.memoryMaintenance);
19
- const state = await readMemoryMaintenanceState(input.appHomeDir, input.channelId);
25
+ const state = await readMemoryMaintenanceState(input.appHomeDir, conversation);
20
26
  let cachedWindow;
21
27
  const loadSourceWindow = () => {
22
28
  cachedWindow ??= buildIncrementalMemorySourceWindow({
@@ -41,9 +47,9 @@ export async function runReflectJob(input) {
41
47
  },
42
48
  });
43
49
  if (!decision.allowed) {
44
- await appendMemoryReviewLog(input.channelDir, {
50
+ await appendMemoryReviewLog(deskDir, {
45
51
  timestamp: formatLocalTime(now),
46
- channelId: input.channelId,
52
+ channelId: channelId,
47
53
  reason: "reflect",
48
54
  skipped: [{ target: "reflect", reason: decision.skipReason }],
49
55
  });
@@ -52,37 +58,37 @@ export async function runReflectJob(input) {
52
58
  const sourceWindow = loadSourceWindow();
53
59
  try {
54
60
  const result = await runReflect({
55
- channelId: input.channelId,
56
- channelDir: input.channelDir,
61
+ channelId: channelId,
62
+ deskDir: deskDir,
57
63
  workspaceDir: input.workspaceDir,
58
64
  model: input.model,
59
65
  resolveApiKey: input.resolveApiKey,
60
66
  messages: sourceWindow.messages,
61
- usageContext: { channelId: input.channelId, correlationId: sourceWindow.windowId },
67
+ usageContext: { channelId, desk: conversation.desk, correlationId: sourceWindow.windowId },
62
68
  });
63
- await updateMemoryMaintenanceState(input.appHomeDir, input.channelId, (current) => ({
69
+ await updateMemoryMaintenanceState(input.appHomeDir, conversation, (current) => ({
64
70
  ...current,
65
71
  lastReflectAt: formatLocalTime(now),
66
72
  lastReflectedEntryId: sourceWindow.throughEntryId ?? current.lastReflectedEntryId,
67
73
  failureBackoffUntil: null,
68
74
  }));
69
- await appendMemoryReviewLog(input.channelDir, {
75
+ await appendMemoryReviewLog(deskDir, {
70
76
  timestamp: formatLocalTime(now),
71
- channelId: input.channelId,
77
+ channelId: channelId,
72
78
  reason: "reflect",
73
79
  correlationId: sourceWindow.windowId,
74
80
  ...reviewLogEntryFor(result),
75
81
  });
76
82
  }
77
83
  catch (error) {
78
- await updateMemoryMaintenanceState(input.appHomeDir, input.channelId, (current) => ({
84
+ await updateMemoryMaintenanceState(input.appHomeDir, conversation, (current) => ({
79
85
  ...current,
80
86
  failureBackoffUntil: backoffUntil(now, maintenance),
81
87
  }));
82
88
  const message = errorMessage(error);
83
- await appendMemoryReviewLog(input.channelDir, {
89
+ await appendMemoryReviewLog(deskDir, {
84
90
  timestamp: formatLocalTime(now),
85
- channelId: input.channelId,
91
+ channelId: channelId,
86
92
  reason: "reflect",
87
93
  error: message,
88
94
  });