@oyasmi/pipiclaw 0.9.4-beta.2 → 0.9.5-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (405) hide show
  1. package/README.en.md +28 -22
  2. package/README.md +27 -21
  3. package/dist/agent/builtin-commands.d.ts +7 -2
  4. package/dist/agent/builtin-commands.js +19 -23
  5. package/dist/agent/channel-runner.d.ts +13 -13
  6. package/dist/agent/channel-runner.js +93 -76
  7. package/dist/agent/maintenance-context.d.ts +6 -5
  8. package/dist/agent/maintenance-context.js +15 -15
  9. package/dist/agent/prompt/manifest.js +1 -1
  10. package/dist/agent/prompt/resources.d.ts +1 -1
  11. package/dist/agent/prompt/resources.js +1 -1
  12. package/dist/agent/prompt/sections.js +4 -4
  13. package/dist/agent/runner-factory.d.ts +6 -6
  14. package/dist/agent/runner-factory.js +6 -7
  15. package/dist/agent/session/compaction-input.d.ts +6 -0
  16. package/dist/agent/session/compaction-input.js +75 -0
  17. package/dist/agent/session/compaction-snapshot.d.ts +30 -0
  18. package/dist/agent/session/compaction-snapshot.js +154 -0
  19. package/dist/agent/session/compaction-summary.d.ts +39 -0
  20. package/dist/agent/session/compaction-summary.js +158 -0
  21. package/dist/agent/session/compaction.d.ts +35 -0
  22. package/dist/agent/session/compaction.js +294 -0
  23. package/dist/agent/session/context-input.d.ts +15 -0
  24. package/dist/agent/session/context-input.js +82 -0
  25. package/dist/agent/session/context-snapshot.d.ts +11 -0
  26. package/dist/agent/session/context-snapshot.js +72 -0
  27. package/dist/agent/session/event-guards.d.ts +2 -0
  28. package/dist/agent/session/event-guards.js +4 -0
  29. package/dist/agent/session/request-tools.d.ts +3 -0
  30. package/dist/agent/session/request-tools.js +20 -0
  31. package/dist/agent/session/session-adapter.d.ts +2 -1
  32. package/dist/agent/session/session-adapter.js +6 -3
  33. package/dist/agent/session/session-events.d.ts +5 -4
  34. package/dist/agent/session/session-events.js +46 -59
  35. package/dist/agent/session/session-host.d.ts +29 -41
  36. package/dist/agent/session/session-host.js +86 -69
  37. package/dist/agent/session/settings-diagnostics.d.ts +5 -0
  38. package/dist/agent/session/settings-diagnostics.js +21 -0
  39. package/dist/agent/status-render.js +5 -2
  40. package/dist/{runtime → agent}/stop-watchdog.d.ts +3 -1
  41. package/dist/{runtime → agent}/stop-watchdog.js +7 -3
  42. package/dist/agent/turn/progress-formatter.d.ts +1 -3
  43. package/dist/agent/turn/progress-formatter.js +3 -22
  44. package/dist/agent/turn/task-digest.d.ts +4 -2
  45. package/dist/agent/turn/task-digest.js +7 -4
  46. package/dist/agent/turn/turn-context.d.ts +11 -7
  47. package/dist/agent/turn/turn-context.js +26 -18
  48. package/dist/agent/turn/turn-finish.d.ts +17 -5
  49. package/dist/agent/turn/turn-finish.js +51 -77
  50. package/dist/agent/turn/turn-input.d.ts +2 -2
  51. package/dist/agent/turn/turn-input.js +4 -3
  52. package/dist/agent/turn/turn-output.d.ts +19 -0
  53. package/dist/agent/turn/turn-output.js +41 -0
  54. package/dist/agent/turn/turn-pipeline.d.ts +11 -8
  55. package/dist/agent/turn/turn-pipeline.js +54 -55
  56. package/dist/agent/turn/turn-prompt.d.ts +1 -1
  57. package/dist/agent/turn/turn-recovery.d.ts +11 -10
  58. package/dist/agent/turn/turn-recovery.js +14 -29
  59. package/dist/agent/types.d.ts +31 -12
  60. package/dist/agent/types.js +2 -1
  61. package/dist/app/auth-command.js +1 -1
  62. package/dist/app/home.js +31 -15
  63. package/dist/channel/active-session-store.d.ts +14 -12
  64. package/dist/channel/active-session-store.js +29 -25
  65. package/dist/channel/attachments.d.ts +25 -0
  66. package/dist/channel/attachments.js +56 -0
  67. package/dist/channel/channel-context.d.ts +87 -96
  68. package/dist/channel/channel-context.js +1 -66
  69. package/dist/channel/channel-event.d.ts +51 -41
  70. package/dist/channel/channel-event.js +6 -11
  71. package/dist/channel/channel-id.d.ts +22 -0
  72. package/dist/channel/channel-id.js +13 -0
  73. package/dist/channel/channel-index.d.ts +17 -34
  74. package/dist/channel/channel-index.js +41 -80
  75. package/dist/channel/config.d.ts +10 -0
  76. package/dist/channel/config.js +55 -0
  77. package/dist/channel/ingress.d.ts +101 -0
  78. package/dist/channel/ingress.js +5 -0
  79. package/dist/channel/store.d.ts +13 -15
  80. package/dist/channel/store.js +21 -25
  81. package/dist/channel/transport.d.ts +99 -0
  82. package/dist/channel/turn-context.d.ts +23 -0
  83. package/dist/channel/turn-context.js +1 -0
  84. package/dist/commands/catalog.d.ts +4 -7
  85. package/dist/commands/catalog.js +24 -31
  86. package/dist/commands/router.d.ts +23 -12
  87. package/dist/commands/router.js +22 -24
  88. package/dist/config/settings.d.ts +5 -4
  89. package/dist/desk/bindings.d.ts +6 -0
  90. package/dist/desk/bindings.js +105 -0
  91. package/dist/desk/commands.d.ts +81 -0
  92. package/dist/desk/commands.js +145 -0
  93. package/dist/desk/default.d.ts +4 -0
  94. package/dist/desk/default.js +11 -0
  95. package/dist/desk/paths.d.ts +41 -0
  96. package/dist/desk/paths.js +81 -0
  97. package/dist/desk/registry.d.ts +17 -0
  98. package/dist/desk/registry.js +191 -0
  99. package/dist/desk/startup-error.d.ts +4 -0
  100. package/dist/desk/startup-error.js +7 -0
  101. package/dist/desk/types.d.ts +72 -0
  102. package/dist/desk/types.js +7 -0
  103. package/dist/dingtalk/bot.d.ts +18 -35
  104. package/dist/dingtalk/bot.js +21 -204
  105. package/dist/dingtalk/channel-ids.d.ts +15 -0
  106. package/dist/dingtalk/channel-ids.js +39 -0
  107. package/dist/dingtalk/config.d.ts +6 -3
  108. package/dist/dingtalk/config.js +13 -25
  109. package/dist/dingtalk/connection.d.ts +1 -0
  110. package/dist/dingtalk/connection.js +5 -4
  111. package/dist/dingtalk/conversation-meta.d.ts +10 -5
  112. package/dist/dingtalk/conversation-meta.js +72 -50
  113. package/dist/dingtalk/delivery.d.ts +30 -14
  114. package/dist/dingtalk/delivery.js +189 -62
  115. package/dist/dingtalk/inbound-media.d.ts +2 -18
  116. package/dist/dingtalk/inbound-media.js +0 -53
  117. package/dist/dingtalk/inbound.d.ts +10 -11
  118. package/dist/dingtalk/inbound.js +12 -19
  119. package/dist/dingtalk/media.d.ts +9 -11
  120. package/dist/dingtalk/media.js +18 -31
  121. package/dist/dingtalk/progress.d.ts +8 -0
  122. package/dist/dingtalk/progress.js +20 -0
  123. package/dist/dingtalk/response-mode.d.ts +13 -0
  124. package/dist/dingtalk/response-mode.js +31 -0
  125. package/dist/dingtalk/transport.d.ts +47 -0
  126. package/dist/dingtalk/transport.js +71 -0
  127. package/dist/events/commands.d.ts +7 -2
  128. package/dist/events/commands.js +40 -22
  129. package/dist/events/pre-action-error.d.ts +10 -0
  130. package/dist/events/pre-action-error.js +10 -0
  131. package/dist/events/types.d.ts +20 -2
  132. package/dist/events/watcher.d.ts +14 -7
  133. package/dist/events/watcher.js +49 -26
  134. package/dist/index.d.ts +4 -2
  135. package/dist/jobs/completion-wake.d.ts +14 -0
  136. package/dist/jobs/completion-wake.js +36 -0
  137. package/dist/jobs/manager.d.ts +27 -22
  138. package/dist/jobs/manager.js +58 -91
  139. package/dist/jobs/record.d.ts +2 -0
  140. package/dist/jobs/record.js +2 -0
  141. package/dist/log.d.ts +0 -1
  142. package/dist/log.js +1 -1
  143. package/dist/main.js +10 -3
  144. package/dist/memory/boundary-work.d.ts +17 -0
  145. package/dist/memory/boundary-work.js +162 -0
  146. package/dist/memory/commands.d.ts +4 -3
  147. package/dist/memory/commands.js +16 -16
  148. package/dist/memory/desk-memory-queue.d.ts +18 -0
  149. package/dist/memory/desk-memory-queue.js +33 -0
  150. package/dist/memory/index-budget.d.ts +3 -3
  151. package/dist/memory/index-budget.js +3 -3
  152. package/dist/memory/journal.d.ts +6 -6
  153. package/dist/memory/journal.js +14 -14
  154. package/dist/memory/lifecycle.d.ts +14 -21
  155. package/dist/memory/lifecycle.js +73 -103
  156. package/dist/memory/maintenance-state.d.ts +14 -15
  157. package/dist/memory/maintenance-state.js +43 -42
  158. package/dist/memory/reflect-job.d.ts +5 -4
  159. package/dist/memory/reflect-job.js +21 -15
  160. package/dist/memory/reflect.d.ts +2 -1
  161. package/dist/memory/reflect.js +13 -12
  162. package/dist/memory/render.d.ts +1 -1
  163. package/dist/memory/render.js +2 -2
  164. package/dist/memory/review-log.d.ts +4 -4
  165. package/dist/memory/review-log.js +5 -5
  166. package/dist/memory/scheduler.d.ts +12 -19
  167. package/dist/memory/scheduler.js +28 -64
  168. package/dist/memory/session-corpus.d.ts +4 -1
  169. package/dist/memory/session-corpus.js +70 -29
  170. package/dist/memory/session-search.d.ts +11 -3
  171. package/dist/memory/session-search.js +14 -11
  172. package/dist/memory/sidecar-worker.d.ts +1 -0
  173. package/dist/memory/sidecar-worker.js +57 -76
  174. package/dist/memory/source-window.d.ts +0 -6
  175. package/dist/memory/source-window.js +0 -20
  176. package/dist/memory/store.d.ts +12 -12
  177. package/dist/memory/store.js +44 -44
  178. package/dist/paths.d.ts +2 -0
  179. package/dist/paths.js +2 -0
  180. package/dist/playbooks/agent-delegation.md +16 -16
  181. package/dist/playbooks/background-jobs.md +5 -3
  182. package/dist/playbooks/event-scheduling.md +7 -5
  183. package/dist/playbooks/memory-and-learning.md +16 -12
  184. package/dist/playbooks/outbound-media.md +1 -1
  185. package/dist/playbooks/runtime-orientation.md +35 -23
  186. package/dist/playbooks/task-lead.md +13 -11
  187. package/dist/runtime/bootstrap.d.ts +36 -13
  188. package/dist/runtime/bootstrap.js +310 -138
  189. package/dist/runtime/channel-queue.d.ts +23 -0
  190. package/dist/{dingtalk → runtime}/channel-queue.js +20 -9
  191. package/dist/runtime/daemon-lock.d.ts +12 -0
  192. package/dist/runtime/daemon-lock.js +28 -0
  193. package/dist/runtime/desk-runtime.d.ts +131 -0
  194. package/dist/runtime/desk-runtime.js +402 -0
  195. package/dist/runtime/durable-dispatch.d.ts +11 -5
  196. package/dist/runtime/durable-dispatch.js +20 -8
  197. package/dist/runtime/inbound-images.d.ts +32 -10
  198. package/dist/runtime/inbound-images.js +95 -21
  199. package/dist/runtime/ingress-busy.d.ts +26 -0
  200. package/dist/runtime/ingress-busy.js +211 -0
  201. package/dist/runtime/ingress-commands.d.ts +7 -0
  202. package/dist/runtime/ingress-commands.js +162 -0
  203. package/dist/runtime/ingress-deps.d.ts +62 -0
  204. package/dist/runtime/ingress-deps.js +1 -0
  205. package/dist/runtime/ingress.d.ts +22 -0
  206. package/dist/runtime/ingress.js +376 -0
  207. package/dist/runtime/request-execution.d.ts +19 -0
  208. package/dist/runtime/request-execution.js +88 -0
  209. package/dist/runtime/shutdown.d.ts +13 -5
  210. package/dist/runtime/shutdown.js +10 -4
  211. package/dist/runtime/task-driver.d.ts +38 -22
  212. package/dist/runtime/task-driver.js +142 -116
  213. package/dist/runtime/task-spawn.d.ts +4 -4
  214. package/dist/runtime/task-spawn.js +6 -5
  215. package/dist/runtime/task-wake.d.ts +6 -4
  216. package/dist/runtime/task-wake.js +7 -7
  217. package/dist/runtime/transports.d.ts +32 -0
  218. package/dist/runtime/transports.js +101 -0
  219. package/dist/runtime/turn-run.d.ts +18 -9
  220. package/dist/runtime/turn-run.js +302 -71
  221. package/dist/runtime/wake-coalescing.d.ts +11 -3
  222. package/dist/runtime/wake-coalescing.js +10 -0
  223. package/dist/security/config.js +5 -10
  224. package/dist/security/logger.js +1 -1
  225. package/dist/security/path-guard.js +7 -63
  226. package/dist/security/types.d.ts +27 -30
  227. package/dist/security/types.js +0 -1
  228. package/dist/shared/atomic-file.d.ts +2 -0
  229. package/dist/shared/atomic-file.js +14 -1
  230. package/dist/shared/file-lock.d.ts +35 -0
  231. package/dist/shared/file-lock.js +195 -0
  232. package/dist/shared/with-timeout.d.ts +2 -0
  233. package/dist/shared/with-timeout.js +21 -0
  234. package/dist/skills/loader.d.ts +1 -1
  235. package/dist/skills/loader.js +2 -2
  236. package/dist/skills/workspace.js +2 -2
  237. package/dist/subagents/completion-wake.d.ts +11 -2
  238. package/dist/subagents/completion-wake.js +22 -9
  239. package/dist/subagents/discovery.js +1 -1
  240. package/dist/subagents/dispatch.d.ts +0 -10
  241. package/dist/subagents/dispatch.js +10 -28
  242. package/dist/subagents/external/dispatch.js +1 -1
  243. package/dist/subagents/external/run.d.ts +1 -1
  244. package/dist/subagents/external/run.js +3 -3
  245. package/dist/subagents/internal/run.js +1 -1
  246. package/dist/subagents/internal/worker.js +6 -14
  247. package/dist/subagents/run-archive.d.ts +11 -0
  248. package/dist/subagents/run-archive.js +49 -0
  249. package/dist/subagents/run-record.d.ts +9 -8
  250. package/dist/subagents/run-record.js +3 -3
  251. package/dist/subagents/run-registry.d.ts +5 -3
  252. package/dist/subagents/run-registry.js +22 -45
  253. package/dist/subagents/runs.d.ts +23 -13
  254. package/dist/subagents/runs.js +75 -82
  255. package/dist/subagents/task-envelope.js +9 -11
  256. package/dist/subagents/types.d.ts +6 -5
  257. package/dist/tasks/board.d.ts +1 -1
  258. package/dist/tasks/board.js +2 -2
  259. package/dist/tasks/bound-work.d.ts +2 -2
  260. package/dist/tasks/bound-work.js +7 -7
  261. package/dist/tasks/brief.d.ts +1 -1
  262. package/dist/tasks/brief.js +9 -9
  263. package/dist/tasks/commands.d.ts +11 -2
  264. package/dist/tasks/commands.js +66 -41
  265. package/dist/tasks/contract.d.ts +0 -2
  266. package/dist/tasks/contract.js +1 -3
  267. package/dist/tasks/create.d.ts +3 -1
  268. package/dist/tasks/create.js +10 -4
  269. package/dist/tasks/frontmatter.d.ts +6 -2
  270. package/dist/tasks/frontmatter.js +10 -10
  271. package/dist/tasks/loop-log.d.ts +7 -13
  272. package/dist/tasks/loop-log.js +14 -17
  273. package/dist/tasks/mutation-lock.d.ts +7 -5
  274. package/dist/tasks/mutation-lock.js +32 -9
  275. package/dist/tasks/session-path.d.ts +3 -3
  276. package/dist/tasks/session-path.js +5 -5
  277. package/dist/tasks/steer.d.ts +5 -5
  278. package/dist/tasks/steer.js +42 -40
  279. package/dist/tasks/store.d.ts +11 -11
  280. package/dist/tasks/store.js +32 -29
  281. package/dist/tools/bash.d.ts +5 -5
  282. package/dist/tools/bash.js +19 -18
  283. package/dist/tools/contract/names.d.ts +7 -0
  284. package/dist/tools/contract/names.js +22 -0
  285. package/dist/tools/edit.js +1 -1
  286. package/dist/tools/event-manage.d.ts +3 -1
  287. package/dist/tools/event-manage.js +34 -33
  288. package/dist/tools/glob.js +5 -5
  289. package/dist/tools/grep.js +2 -2
  290. package/dist/tools/index.d.ts +9 -8
  291. package/dist/tools/index.js +12 -16
  292. package/dist/tools/job.d.ts +4 -2
  293. package/dist/tools/job.js +11 -8
  294. package/dist/tools/memory-manage.d.ts +5 -3
  295. package/dist/tools/memory-manage.js +24 -24
  296. package/dist/tools/read.js +1 -1
  297. package/dist/tools/registry.d.ts +12 -8
  298. package/dist/tools/registry.js +13 -9
  299. package/dist/tools/send-media.d.ts +2 -2
  300. package/dist/tools/send-media.js +3 -3
  301. package/dist/tools/session-search.d.ts +3 -1
  302. package/dist/tools/session-search.js +8 -6
  303. package/dist/tools/subagent-manage.d.ts +2 -8
  304. package/dist/tools/subagent-manage.js +19 -15
  305. package/dist/tools/subagent.js +1 -1
  306. package/dist/tools/task-manage/create.js +1 -1
  307. package/dist/tools/task-manage/factory.js +2 -2
  308. package/dist/tools/task-manage/lifecycle.js +3 -1
  309. package/dist/tools/task-manage/log-view.js +2 -2
  310. package/dist/tools/task-manage/shared.js +3 -3
  311. package/dist/tools/task-manage/step-end.js +3 -3
  312. package/dist/tools/task-manage/types.d.ts +8 -3
  313. package/dist/tools/web-cache.d.ts +3 -3
  314. package/dist/tools/web-cache.js +12 -12
  315. package/dist/tools/web-fetch.d.ts +2 -2
  316. package/dist/tools/web-fetch.js +7 -7
  317. package/dist/tools/write-content.js +1 -1
  318. package/dist/tui/cli.d.ts +17 -5
  319. package/dist/tui/cli.js +90 -27
  320. package/dist/tui/client.d.ts +26 -0
  321. package/dist/tui/client.js +157 -0
  322. package/dist/tui/colors.d.ts +0 -1
  323. package/dist/tui/colors.js +0 -1
  324. package/dist/tui/commands.d.ts +10 -51
  325. package/dist/tui/commands.js +16 -39
  326. package/dist/tui/frontend.d.ts +2 -2
  327. package/dist/tui/frontend.js +2 -2
  328. package/dist/tui/pitui-frontend.d.ts +0 -2
  329. package/dist/tui/pitui-frontend.js +1 -6
  330. package/dist/tui/render.d.ts +62 -0
  331. package/dist/tui/render.js +123 -0
  332. package/dist/tui/session.d.ts +92 -0
  333. package/dist/tui/session.js +317 -0
  334. package/dist/usage/ledger.d.ts +5 -0
  335. package/dist/usage/ledger.js +2 -0
  336. package/dist/usage/render.d.ts +6 -1
  337. package/dist/usage/render.js +18 -13
  338. package/dist/webapi/auth.d.ts +13 -0
  339. package/dist/webapi/auth.js +29 -0
  340. package/dist/webapi/config.d.ts +29 -0
  341. package/dist/webapi/config.js +100 -0
  342. package/dist/webapi/errors.d.ts +39 -0
  343. package/dist/webapi/errors.js +32 -0
  344. package/dist/webapi/http.d.ts +25 -0
  345. package/dist/webapi/http.js +4 -0
  346. package/dist/webapi/ids.d.ts +9 -0
  347. package/dist/webapi/ids.js +20 -0
  348. package/dist/webapi/input.d.ts +17 -0
  349. package/dist/webapi/input.js +229 -0
  350. package/dist/webapi/items.d.ts +37 -0
  351. package/dist/webapi/items.js +48 -0
  352. package/dist/webapi/key-command.d.ts +2 -0
  353. package/dist/webapi/key-command.js +110 -0
  354. package/dist/webapi/limits.d.ts +47 -0
  355. package/dist/webapi/limits.js +48 -0
  356. package/dist/webapi/request-policy.d.ts +17 -0
  357. package/dist/webapi/request-policy.js +160 -0
  358. package/dist/webapi/response-record.d.ts +68 -0
  359. package/dist/webapi/response-record.js +58 -0
  360. package/dist/webapi/response-state.d.ts +90 -0
  361. package/dist/webapi/response-state.js +347 -0
  362. package/dist/webapi/routes/conversations.d.ts +8 -0
  363. package/dist/webapi/routes/conversations.js +80 -0
  364. package/dist/webapi/routes/models.d.ts +3 -0
  365. package/dist/webapi/routes/models.js +12 -0
  366. package/dist/webapi/routes/responses.d.ts +8 -0
  367. package/dist/webapi/routes/responses.js +118 -0
  368. package/dist/webapi/routes/websocket.d.ts +9 -0
  369. package/dist/webapi/routes/websocket.js +328 -0
  370. package/dist/webapi/server.d.ts +24 -0
  371. package/dist/webapi/server.js +229 -0
  372. package/dist/webapi/service.d.ts +130 -0
  373. package/dist/webapi/service.js +588 -0
  374. package/dist/webapi/store.d.ts +46 -0
  375. package/dist/webapi/store.js +245 -0
  376. package/dist/webapi/stream.d.ts +13 -0
  377. package/dist/webapi/stream.js +76 -0
  378. package/dist/webapi/transport.d.ts +43 -0
  379. package/dist/webapi/transport.js +100 -0
  380. package/package.json +9 -2
  381. package/dist/channel/channel-paths.d.ts +0 -16
  382. package/dist/channel/channel-paths.js +0 -53
  383. package/dist/channel/commands.d.ts +0 -32
  384. package/dist/channel/commands.js +0 -109
  385. package/dist/channel/project-scope-store.d.ts +0 -51
  386. package/dist/channel/project-scope-store.js +0 -112
  387. package/dist/dingtalk/channel-queue.d.ts +0 -19
  388. package/dist/dingtalk/handler.d.ts +0 -90
  389. package/dist/memory/channel-maintenance-queue.d.ts +0 -5
  390. package/dist/memory/channel-maintenance-queue.js +0 -8
  391. package/dist/runtime/task-migration.d.ts +0 -30
  392. package/dist/runtime/task-migration.js +0 -465
  393. package/dist/runtime/turn-handler.d.ts +0 -47
  394. package/dist/runtime/turn-handler.js +0 -318
  395. package/dist/security/project-scope.d.ts +0 -45
  396. package/dist/security/project-scope.js +0 -105
  397. package/dist/tui/app.d.ts +0 -16
  398. package/dist/tui/app.js +0 -166
  399. package/dist/tui/terminal-context.d.ts +0 -27
  400. package/dist/tui/terminal-context.js +0 -84
  401. package/dist/tui/terminal-media-sender.d.ts +0 -9
  402. package/dist/tui/terminal-media-sender.js +0 -15
  403. package/dist/tui/turn-controller.d.ts +0 -64
  404. package/dist/tui/turn-controller.js +0 -311
  405. /package/dist/{dingtalk/handler.js → channel/transport.js} +0 -0
@@ -7,7 +7,7 @@
7
7
  */
8
8
  import { Agent } from "@earendil-works/pi-agent-core";
9
9
  import { streamSimple } from "@earendil-works/pi-ai/compat";
10
- import { AgentSession, AgentSessionRuntime, convertToLlm, DefaultResourceLoader, } from "@earendil-works/pi-coding-agent";
10
+ import { AgentSession, AgentSessionRuntime, DefaultResourceLoader, } from "@earendil-works/pi-coding-agent";
11
11
  import { mkdir } from "fs/promises";
12
12
  import { dirname, join } from "path";
13
13
  import { commitActiveSessionRef, resolveActiveSessionFile } from "../../channel/active-session-store.js";
@@ -18,7 +18,6 @@ import { hasMemoryBootstrapBlock } from "../../memory/render.js";
18
18
  import { getApiKeyForModel } from "../../models/api-keys.js";
19
19
  import { findExactModelReferenceMatch, hasKnownModelPricing } from "../../models/reference.js";
20
20
  import { createModelRuntime, resolveInitialModel, wrapModelRegistry } from "../../models/runtime.js";
21
- import { formatConfigDiagnostic } from "../../shared/config-diagnostic.js";
22
21
  import { errorMessage } from "../../shared/text-utils.js";
23
22
  import { isRecord } from "../../shared/type-guards.js";
24
23
  import { withTimeout } from "../../shared/with-timeout.js";
@@ -31,10 +30,14 @@ import { createPromptBoundaryExtension } from "../prompt/extension.js";
31
30
  import { measureToolSchemas, TOOL_SCHEMA_TARGET_UNITS, toolSchemaBudgetWarning } from "../prompt/manifest.js";
32
31
  import { loadPlaybooks, loadWorkspacePromptResources } from "../prompt/resources.js";
33
32
  import { createCommandExtension } from "./command-extension.js";
33
+ import { SessionCompaction } from "./compaction.js";
34
+ import { RequestContextInput } from "./context-input.js";
34
35
  import { getLastAssistantUsage, isAutoCompactionEndEvent } from "./event-guards.js";
36
+ import { requestTools } from "./request-tools.js";
35
37
  import { asSdkSettingsManager, DEFAULT_MAIN_THINKING_LEVEL, initializeThinkingLevelCompat, setSessionBaseToolsOverride, } from "./session-adapter.js";
36
38
  import { handleSessionEvent } from "./session-events.js";
37
39
  import { SessionResourceGate } from "./session-resource-gate.js";
40
+ import { reportConfigDiagnostics, reportSettingsDiagnostics } from "./settings-diagnostics.js";
38
41
  const MODEL_REGISTRY_REFRESH_TIMEOUT_MS = 15_000;
39
42
  const SESSION_RELOAD_TIMEOUT_MS = 30_000;
40
43
  const CONTEXT_FAULT_MESSAGE = "会话上下文保存失败。请让部署者检查服务器存储后发送 /new 重新开启会话。";
@@ -48,23 +51,14 @@ function plainTextOf(content) {
48
51
  .map((part) => (isRecord(part) && part.type === "text" && typeof part.text === "string" ? part.text : ""))
49
52
  .join("\n");
50
53
  }
51
- /** Task sessions live under `<channelDir>/tasks/.sessions/`; nothing else may be mistaken for one. */
54
+ /** Task sessions live under `<deskDir>/tasks/.sessions/`; nothing else may be mistaken for one. */
52
55
  function isTaskSessionPath(sessionFile) {
53
56
  return sessionFile?.replace(/\\/g, "/").includes(`/${TASK_SESSIONS_DIRNAME}/`) === true;
54
57
  }
55
- /** Surface settings.json load errors (once drained) as warnings; shared by construction and reload. */
56
- export function reportSettingsDiagnostics(settingsManager, channelId, appHomeDir) {
57
- for (const { scope, error } of settingsManager.drainErrors()) {
58
- log.logWarn("config.settings.load_failed", "Settings load failed", {
59
- channelId,
60
- reason: error.message,
61
- fields: { scope, path: join(appHomeDir, "settings.json") },
62
- });
63
- }
64
- }
65
58
  export class SessionHost {
66
59
  constructor(deps) {
67
60
  this.deps = deps;
61
+ this.contextInput = new RequestContextInput();
68
62
  /**
69
63
  * Flips true only once `initializeSession` has fully assigned `this.session`
70
64
  * and loaded its resources. Synchronous dispatch-path callers (`isKnownSlashCommand`)
@@ -73,19 +67,23 @@ export class SessionHost {
73
67
  */
74
68
  this.sessionInitialized = false;
75
69
  this.currentTools = [];
70
+ this.retired = false;
76
71
  this.firstTurnMemoryBootstrapPending = true;
77
72
  /** Mirror of `tools.tasks.enabled` from the last tools-config load (see buildRuntimeTools). */
78
73
  this.tasksEnabled = true;
79
74
  this.contextFaults = new WeakSet();
80
- this.channelId = deps.channelId;
81
- this.channelDir = deps.channelDir;
75
+ this.conversation = deps.conversation;
76
+ this.channelId = deps.conversation.channelId;
77
+ this.deskDir = deps.conversation.deskDir;
78
+ this.conversationDir = deps.conversation.conversationDir;
82
79
  this.workspaceDir = deps.workspaceDir;
80
+ this.describeConversation = deps.describeConversation;
83
81
  this.appHomeDir = deps.appHomeDir;
84
82
  this.authConfigPath = deps.authConfigPath;
85
83
  this.modelsConfigPath = deps.modelsConfigPath;
86
84
  this.onSessionEvent = deps.onSessionEvent;
87
- this.mediaSender = deps.mediaSender;
88
- this.projectScope = deps.projectScope;
85
+ this.sendMedia = deps.sendMedia;
86
+ this.cwd = deps.cwd;
89
87
  this.settingsManager = deps.settingsManager;
90
88
  this.loadSecurityConfig = deps.loadSecurityConfig;
91
89
  this.executor = deps.executor;
@@ -96,6 +94,20 @@ export class SessionHost {
96
94
  this.models = deps.models;
97
95
  this.ledger = deps.ledger;
98
96
  this.currentSkills = deps.initialSkills;
97
+ this.compaction = new SessionCompaction({
98
+ conversation: this.conversation,
99
+ getSession: () => this.session,
100
+ getRuntime: () => this.modelRuntime,
101
+ preserveMemory: (event) => this.memoryLifecycle.prepareCompaction(event),
102
+ ledger: this.ledger,
103
+ getRunState: () => this.runState,
104
+ isEnabled: () => this.settingsManager.getCompactionEnabled(),
105
+ onPersistenceFault: (session, error) => this.markContextFault(session, error, "background-compaction"),
106
+ onAdopt: () => {
107
+ this.firstTurnMemoryBootstrapPending = true;
108
+ void this.memoryLifecycle.resumeBoundaryReflect();
109
+ },
110
+ });
99
111
  this.sessionResourceGate = new SessionResourceGate(async () => {
100
112
  await this.reloadSessionResources();
101
113
  });
@@ -106,6 +118,12 @@ export class SessionHost {
106
118
  get agent() {
107
119
  return this.session.agent;
108
120
  }
121
+ importContext(context) {
122
+ this.contextInput.import(this.session, context);
123
+ }
124
+ async promptContext(context, submit) {
125
+ await this.contextInput.prompt(this.session, context, submit ? "" : (this.lastPromptBuild?.footer ?? ""), submit);
126
+ }
109
127
  get sessionManager() {
110
128
  return this.session.sessionManager;
111
129
  }
@@ -113,12 +131,12 @@ export class SessionHost {
113
131
  start(sessionManager) {
114
132
  this.sessionReady = this.initializeSession(sessionManager);
115
133
  }
116
- markContextFault(session, error) {
134
+ markContextFault(session, error, stage = "fallback-context-edit") {
117
135
  this.contextFaults.add(session);
118
136
  log.logWarn("agent.session.context_failed", "Session context persistence failed", {
119
137
  channelId: this.channelId,
120
138
  reason: errorMessage(error),
121
- fields: { sessionId: session.sessionManager.getSessionId(), stage: "fallback-context-edit" },
139
+ fields: { sessionId: session.sessionManager.getSessionId(), stage },
122
140
  });
123
141
  return new Error(CONTEXT_FAULT_MESSAGE, { cause: error });
124
142
  }
@@ -135,9 +153,11 @@ export class SessionHost {
135
153
  }
136
154
  /** Stop listening to the live session and dispose it (no-op error handling is the caller's). */
137
155
  retireLiveSession() {
156
+ this.retired = true;
157
+ this.compaction.retire();
138
158
  this.sessionUnsubscribe?.();
139
159
  this.sessionUnsubscribe = undefined;
140
- this.session.dispose();
160
+ this.session?.dispose();
141
161
  }
142
162
  /**
143
163
  * Release the session once idle. Guards a dispose() racing construction: initializeSession
@@ -145,6 +165,7 @@ export class SessionHost {
145
165
  * not have one yet.
146
166
  */
147
167
  async disposeSession() {
168
+ this.compaction.retire();
148
169
  await this.sessionReady;
149
170
  this.sessionUnsubscribe?.();
150
171
  this.sessionUnsubscribe = undefined;
@@ -175,7 +196,13 @@ export class SessionHost {
175
196
  this.subAgentDiscovery = await this.refreshSubAgentDiscovery();
176
197
  const initial = await this.createSessionRuntime(sessionManager);
177
198
  this.session = initial.session;
199
+ if (this.retired) {
200
+ this.session.dispose();
201
+ throw new Error("Session generation retired");
202
+ }
178
203
  this.sessionRuntime = new AgentSessionRuntime(this.session, this.createAgentSessionServices(initial.resourceLoader), async ({ sessionManager, sessionStartEvent }) => {
204
+ if (this.retired)
205
+ throw new Error("Session generation retired");
179
206
  // `/new`, fork, and switch already wrote the target session's durable header by
180
207
  // this point (the SDK does it synchronously before invoking this callback); commit
181
208
  // the pointer before we rebuild and rebind to it, so a crash between "SDK created
@@ -185,7 +212,7 @@ export class SessionHost {
185
212
  // ref at it, or `/new` and restart recovery would adopt a task's transcript as the
186
213
  // conversation (spec 051, D3).
187
214
  if (!isTaskSessionPath(sessionManager.getSessionFile())) {
188
- await commitActiveSessionRef(this.channelDir, sessionManager);
215
+ await commitActiveSessionRef(this.conversationDir, sessionManager);
189
216
  }
190
217
  const next = await this.createSessionRuntime(sessionManager, sessionStartEvent);
191
218
  return {
@@ -196,6 +223,11 @@ export class SessionHost {
196
223
  };
197
224
  });
198
225
  this.sessionRuntime.setRebindSession(async (session) => {
226
+ this.compaction.cancel("session-rebind");
227
+ if (this.retired) {
228
+ session.dispose();
229
+ throw new Error("Session generation retired");
230
+ }
199
231
  this.session = session;
200
232
  await this.bindSessionExtensions();
201
233
  this.subscribeToSessionEvents();
@@ -210,11 +242,15 @@ export class SessionHost {
210
242
  this.sessionInitialized = true;
211
243
  }
212
244
  async reloadSessionResources() {
245
+ if (this.retired)
246
+ return;
213
247
  this.settingsManager.reload();
214
- this.reportSettingsDiagnostics();
215
- const skills = loadPipiclawSkills(this.channelDir);
248
+ reportSettingsDiagnostics(this.settingsManager, this.channelId, this.appHomeDir);
249
+ const skills = loadPipiclawSkills(this.workspaceDir);
216
250
  this.currentSkills = skills;
217
251
  this.subAgentDiscovery = await this.refreshSubAgentDiscovery();
252
+ if (this.retired)
253
+ return;
218
254
  this.rebuildSessionTools();
219
255
  try {
220
256
  await withTimeout(`[${this.channelId}] session reload`, SESSION_RELOAD_TIMEOUT_MS, () => this.session.reload());
@@ -277,27 +313,7 @@ export class SessionHost {
277
313
  }
278
314
  return discovery;
279
315
  }
280
- reportSettingsDiagnostics() {
281
- reportSettingsDiagnostics(this.settingsManager, this.channelId, this.appHomeDir);
282
- }
283
- reportConfigDiagnostics(diagnostics) {
284
- for (const diagnostic of diagnostics) {
285
- log.logWarn("config.diagnostic", formatConfigDiagnostic(diagnostic), {
286
- channelId: this.channelId,
287
- fields: { path: diagnostic.path },
288
- });
289
- }
290
- }
291
- /**
292
- * Build the Pipiclaw-owned system prompt (spec 025). This replaces pi's default
293
- * base prompt entirely: identity, execution contract, hard invariants, the tool
294
- * catalog and the workspace files are ours. pi still appends its tail (skills,
295
- * date, cwd), and the boundary footer is appended after that by the prompt
296
- * extension.
297
- *
298
- * Nothing channel-specific enters this text — that is what lets two channels in
299
- * one workspace share a cached prompt prefix. Channel facts ride the turn.
300
- */
316
+ /** Build the shared Pipiclaw prompt; channel facts stay in turn context and pi appends its tail. */
301
317
  buildSystemPrompt() {
302
318
  const toolNames = this.currentTools.map((tool) => tool.name);
303
319
  const resources = loadWorkspacePromptResources(this.workspaceDir);
@@ -338,10 +354,11 @@ export class SessionHost {
338
354
  }
339
355
  createResourceLoader() {
340
356
  return new DefaultResourceLoader({
341
- cwd: this.projectScope.projectRoot,
357
+ cwd: this.cwd,
342
358
  agentDir: this.appHomeDir,
343
359
  settingsManager: asSdkSettingsManager(this.settingsManager),
344
360
  extensionFactories: [
361
+ this.compaction.createExtensionFactory(),
345
362
  this.memoryLifecycle.createExtensionFactory(),
346
363
  createPromptBoundaryExtension({
347
364
  getFooter: () => this.lastPromptBuild?.footer ?? "",
@@ -371,8 +388,7 @@ export class SessionHost {
371
388
  await this.refreshSessionResources();
372
389
  },
373
390
  runMemoryCommand: async (args) => handleMemoryCommand({
374
- channelId: this.channelId,
375
- channelDir: this.channelDir,
391
+ conversation: this.conversation,
376
392
  appHomeDir: this.appHomeDir,
377
393
  args,
378
394
  }),
@@ -402,7 +418,7 @@ export class SessionHost {
402
418
  }
403
419
  createAgentSessionServices(resourceLoader) {
404
420
  return {
405
- cwd: this.projectScope.projectRoot,
421
+ cwd: this.cwd,
406
422
  agentDir: this.appHomeDir,
407
423
  settingsManager: asSdkSettingsManager(this.settingsManager),
408
424
  modelRuntime: this.modelRuntime,
@@ -440,6 +456,8 @@ export class SessionHost {
440
456
  initializeThinkingLevelCompat(agent, model, sessionManager, this.settingsManager.getDefaultThinkingLevel());
441
457
  }
442
458
  async createSessionRuntime(sessionManager, sessionStartEvent) {
459
+ if (this.retired)
460
+ throw new Error("Session generation retired");
443
461
  const tools = this.buildRuntimeTools();
444
462
  const agent = new Agent({
445
463
  initialState: {
@@ -449,7 +467,7 @@ export class SessionHost {
449
467
  tools: [],
450
468
  messages: sessionManager.buildSessionContext().messages,
451
469
  },
452
- convertToLlm,
470
+ convertToLlm: (messages) => this.contextInput.convert(messages),
453
471
  getApiKey: async () => getApiKeyForModel(this.modelRegistry, this.models.activeModel),
454
472
  streamFn: streamSimple,
455
473
  });
@@ -458,12 +476,14 @@ export class SessionHost {
458
476
  // Must precede `new AgentSession`: the session snapshots the loader's extensions in its
459
477
  // constructor (see `loadSessionResources`).
460
478
  await this.loadSessionResources(resourceLoader);
479
+ if (this.retired)
480
+ throw new Error("Session generation retired");
461
481
  const sessionSettingsManager = asSdkSettingsManager(this.settingsManager);
462
482
  const session = new AgentSession({
463
483
  agent,
464
484
  sessionManager,
465
485
  settingsManager: sessionSettingsManager,
466
- cwd: this.projectScope.projectRoot,
486
+ cwd: this.cwd,
467
487
  modelRuntime: this.modelRuntime,
468
488
  resourceLoader,
469
489
  baseToolsOverride: Object.fromEntries(tools.map((tool) => [tool.name, tool])),
@@ -473,18 +493,12 @@ export class SessionHost {
473
493
  this.sessionSettingsManager = sessionSettingsManager;
474
494
  return { session, resourceLoader };
475
495
  }
476
- /**
477
- * Bind this runner to a task cycle's own session (spec 051, D3/INV-5).
478
- *
479
- * Task work must not accumulate in the channel's chat transcript: the one real channel on the
480
- * author's machine had grown to 7.4 MB and been compacted six times because chat and two daily
481
- * tasks shared it, so every compaction damaged all three at once. Swapping the bound session
482
- * per turn gives each task its own bounded context while leaving turn state, `/stop`, and
483
- * delivery exactly where they already are.
484
- */
496
+ /** Bind a task to its own transcript, keeping scheduled work out of the chat history. */
485
497
  async bindTaskSession(taskId) {
486
498
  await this.sessionReady;
487
- const path = taskSessionPath(this.channelDir, taskId);
499
+ if (this.retired)
500
+ return;
501
+ const path = taskSessionPath(this.deskDir, taskId);
488
502
  await mkdir(dirname(path), { recursive: true });
489
503
  this.taskLoop = { taskId };
490
504
  await this.sessionRuntime.switchSession(path);
@@ -492,10 +506,10 @@ export class SessionHost {
492
506
  }
493
507
  /** Return to the channel's chat session after a task step. Safe to call when already bound. */
494
508
  async bindChatSession() {
495
- if (!this.taskLoop)
509
+ if (this.retired || !this.taskLoop)
496
510
  return;
497
511
  this.taskLoop = undefined;
498
- await this.sessionRuntime.switchSession(join(this.channelDir, resolveActiveSessionFile(this.channelDir)));
512
+ await this.sessionRuntime.switchSession(join(this.conversationDir, resolveActiveSessionFile(this.conversationDir)));
499
513
  this.syncMemoryBootstrapPendingFromSession();
500
514
  }
501
515
  /** Bootstrap presence follows canonical context, including omissions and compaction.
@@ -518,7 +532,7 @@ export class SessionHost {
518
532
  buildRuntimeTools() {
519
533
  const securityLoad = this.loadSecurityConfig();
520
534
  const toolsLoad = loadToolsConfigWithDiagnostics(this.appHomeDir);
521
- this.reportConfigDiagnostics([...securityLoad.diagnostics, ...toolsLoad.diagnostics]);
535
+ reportConfigDiagnostics([...securityLoad.diagnostics, ...toolsLoad.diagnostics], this.channelId);
522
536
  this.tasksEnabled = toolsLoad.config.tools.tasks.enabled;
523
537
  const tools = createPipiclawTools({
524
538
  jobManager: this.jobManager,
@@ -529,33 +543,36 @@ export class SessionHost {
529
543
  getAvailableModels: () => this.modelRegistry.getAvailable(),
530
544
  resolveApiKey: async (model) => getApiKeyForModel(this.modelRegistry, model),
531
545
  workspaceDir: this.workspaceDir,
532
- projectScope: this.projectScope,
533
- channelDir: this.channelDir,
546
+ cwd: this.cwd,
547
+ desk: this.conversation.desk,
548
+ deskDir: this.deskDir,
534
549
  channelId: this.channelId,
550
+ describeConversation: this.describeConversation,
535
551
  getSubAgentDiscovery: () => this.subAgentDiscovery,
536
552
  getSubAgentModelReference: () => this.settingsManager.getSubAgentModelReference(),
537
553
  resolveFallbackModel: () => this.models.resolveFallbackModel(),
538
554
  getSessionSearchSettings: () => this.settingsManager.getSessionSearchSettings(),
539
555
  securityConfig: securityLoad.config,
540
556
  toolsConfig: toolsLoad.config,
541
- mediaSender: this.mediaSender,
557
+ sendMedia: this.sendMedia,
542
558
  taskLoop: this.taskLoop,
543
559
  getToolsUsed: () => this.runState.toolsUsed,
544
560
  // Assistant usage only: an internal sub-agent's cost is also in `totalUsage`, and a bound
545
561
  // one is already credited to the task when it settles.
546
562
  getStepCost: () => ({ usd: this.runState.assistantUsage.cost.total, estimated: !this.runState.costKnown }),
547
563
  });
548
- this.currentTools = tools;
564
+ const active = this.deps.requestScoped ? requestTools(tools) : tools;
565
+ this.currentTools = active;
549
566
  // Tool schemas are billed with the system prompt and, unlike it, nothing trims them.
550
567
  // Warn where the prompt's own budget diagnostics are reported, once per tool rebuild.
551
- const schemas = measureToolSchemas(tools);
568
+ const schemas = measureToolSchemas(active);
552
569
  if (schemas.units > TOOL_SCHEMA_TARGET_UNITS) {
553
570
  log.logWarn("agent.tools.schema_over_budget", "Tool schemas over budget", {
554
571
  channelId: this.channelId,
555
572
  reason: toolSchemaBudgetWarning(schemas),
556
573
  });
557
574
  }
558
- return tools;
575
+ return active;
559
576
  }
560
577
  rebuildSessionTools() {
561
578
  const tools = this.buildRuntimeTools();
@@ -0,0 +1,5 @@
1
+ import type { PipiclawSettingsManager } from "../../config/settings.js";
2
+ import { type ConfigDiagnostic } from "../../shared/config-diagnostic.js";
3
+ /** Surface settings.json load errors (once drained) as warnings; shared by construction and reload. */
4
+ export declare function reportSettingsDiagnostics(settingsManager: PipiclawSettingsManager, channelId: string, appHomeDir: string): void;
5
+ export declare function reportConfigDiagnostics(diagnostics: ConfigDiagnostic[], channelId: string): void;
@@ -0,0 +1,21 @@
1
+ import { join } from "node:path";
2
+ import * as log from "../../log.js";
3
+ import { formatConfigDiagnostic } from "../../shared/config-diagnostic.js";
4
+ /** Surface settings.json load errors (once drained) as warnings; shared by construction and reload. */
5
+ export function reportSettingsDiagnostics(settingsManager, channelId, appHomeDir) {
6
+ for (const { scope, error } of settingsManager.drainErrors()) {
7
+ log.logWarn("config.settings.load_failed", "Settings load failed", {
8
+ channelId,
9
+ reason: error.message,
10
+ fields: { scope, path: join(appHomeDir, "settings.json") },
11
+ });
12
+ }
13
+ }
14
+ export function reportConfigDiagnostics(diagnostics, channelId) {
15
+ for (const diagnostic of diagnostics) {
16
+ log.logWarn("config.diagnostic", formatConfigDiagnostic(diagnostic), {
17
+ channelId: channelId,
18
+ fields: { path: diagnostic.path },
19
+ });
20
+ }
21
+ }
@@ -24,9 +24,12 @@ export function renderStatus(options) {
24
24
  runState = "空闲";
25
25
  }
26
26
  const lines = [`**状态** · ${runState}`];
27
- if (runner) {
27
+ const snapshot = runner?.getStatusSnapshot();
28
+ if (runner && !snapshot) {
29
+ lines.push("- 模型:会话正在启动,稍后再试");
30
+ }
31
+ else if (runner && snapshot) {
28
32
  try {
29
- const snapshot = runner.getStatusSnapshot();
30
33
  let modelLine = `- 模型:\`${snapshot.model}\`(思考档位 \`${snapshot.thinkingLevel}\`)`;
31
34
  if (snapshot.fallback) {
32
35
  const until = new Date(snapshot.fallback.cooldownUntilMs);
@@ -2,7 +2,7 @@
2
2
  * The `/stop` watchdog: a stopped turn that never ends is force-released after a grace window, so
3
3
  * the channel does not keep reporting "a turn is already running".
4
4
  */
5
- import type { AgentRunner } from "../agent/types.js";
5
+ import type { AgentRunner } from "./types.js";
6
6
  /**
7
7
  * Watchdog for `/stop`: release the channel if the stopped turn has not ended
8
8
  * once the grace window elapses. Returns true when it had to force the release.
@@ -13,4 +13,6 @@ export declare function forceEndStuckTurnAfterStop(input: {
13
13
  graceMs?: number;
14
14
  pollMs?: number;
15
15
  notify?: (text: string) => Promise<unknown>;
16
+ isCurrent?: () => boolean;
17
+ recover?: () => void;
16
18
  }): Promise<boolean>;
@@ -9,7 +9,7 @@ import { sleepUnref } from "../shared/with-timeout.js";
9
9
  * epilogue (delivery drain, session-resource reload, memory flush) ignores both
10
10
  * and would otherwise keep the channel reporting "已有回合在运行" indefinitely.
11
11
  */
12
- const STOP_FORCE_END_GRACE_MS = 15_000;
12
+ const STOP_FORCE_END_GRACE_MS = 3_000;
13
13
  const STOP_FORCE_END_POLL_MS = 250;
14
14
  /**
15
15
  * Watchdog for `/stop`: release the channel if the stopped turn has not ended
@@ -19,14 +19,18 @@ export async function forceEndStuckTurnAfterStop(input) {
19
19
  const graceMs = input.graceMs ?? STOP_FORCE_END_GRACE_MS;
20
20
  const pollMs = input.pollMs ?? STOP_FORCE_END_POLL_MS;
21
21
  const deadline = Date.now() + graceMs;
22
- while (input.runner.isBusy() && Date.now() < deadline) {
22
+ const stopped = () => input.runner.isBusy() && input.runner.getTurnStatus().stopRequested && (input.isCurrent?.() ?? true);
23
+ while (stopped() && Date.now() < deadline) {
23
24
  await sleepUnref(Math.min(pollMs, Math.max(1, deadline - Date.now())));
24
25
  }
26
+ if (!stopped())
27
+ return false;
25
28
  if (!input.runner.forceEndTurn(`/stop did not take effect within ${graceMs}ms`)) {
26
29
  return false;
27
30
  }
31
+ input.recover?.();
28
32
  await input
29
- .notify?.(`⚠️ 上一个回合的收尾卡住了,已强制结束以释放会话(后台清理仍在继续)。现在可以正常发消息或使用 \`/new\`、\`/model\`。`)
33
+ .notify?.(`⚠️ 上一个回合未能及时停止,已隔离并恢复原会话。现在可以继续发消息,或使用 \`/new\`、\`/model\`。`)
30
34
  .catch(() => undefined);
31
35
  return true;
32
36
  }
@@ -1,7 +1,6 @@
1
1
  /**
2
- * Formatting helpers for turn progress entries and for clipping over-length user input.
2
+ * Helpers for clipping over-length user input and for reading a tool result as text.
3
3
  */
4
- import type { ProgressEntryKind } from "../types.js";
5
4
  /**
6
5
  * Head + tail of an over-length message, with the middle replaced by a marker.
7
6
  *
@@ -12,5 +11,4 @@ import type { ProgressEntryKind } from "../types.js";
12
11
  * in this runtime follows).
13
12
  */
14
13
  export declare function clipUserInput(text: string, maxChars: number, fullTextPath?: string): string;
15
- export declare function formatProgressEntry(kind: ProgressEntryKind, text: string): string;
16
14
  export declare function extractToolResultText(result: unknown): string;
@@ -1,9 +1,6 @@
1
- function sanitizeProgressText(text) {
2
- return text
3
- .replace(/\uFFFC/g, "")
4
- .replace(/\r/g, "")
5
- .trim();
6
- }
1
+ /**
2
+ * Helpers for clipping over-length user input and for reading a tool result as text.
3
+ */
7
4
  /**
8
5
  * Head + tail of an over-length message, with the middle replaced by a marker.
9
6
  *
@@ -25,22 +22,6 @@ export function clipUserInput(text, maxChars, fullTextPath) {
25
22
  : "";
26
23
  return `${normalized.slice(0, headChars)}\n\n[... omitted ${normalized.length - maxChars} chars${recovery} ...]\n\n${normalized.slice(-tailChars)}`;
27
24
  }
28
- export function formatProgressEntry(kind, text) {
29
- const cleaned = sanitizeProgressText(text);
30
- if (!cleaned)
31
- return "";
32
- const normalized = cleaned.replace(/\n+/g, " ").trim();
33
- switch (kind) {
34
- case "tool":
35
- return `➜ ${normalized}`;
36
- case "thinking":
37
- return `✦ ${normalized}`;
38
- case "error":
39
- return `✕ ${normalized}`;
40
- case "assistant":
41
- return normalized;
42
- }
43
- }
44
25
  export function extractToolResultText(result) {
45
26
  if (typeof result === "string") {
46
27
  return result;
@@ -10,8 +10,10 @@ export declare const TASK_AGENDA_MAX_UNITS = 600;
10
10
  * reference, not instruction, so it can never turn an unrelated user turn into task work.
11
11
  */
12
12
  export interface TaskDigestOptions {
13
- /** The channel directory; tasks live in `<channelDir>/tasks/`. */
14
- channelDir: string;
13
+ /** The desk directory; tasks live in `<deskDir>/tasks/`. */
14
+ deskDir: string;
15
+ /** The asking channel: a task delivering to another channel is marked, as it reports there. */
16
+ channelId?: string;
15
17
  maxTasks: number;
16
18
  maxChars: number;
17
19
  /** Runtime hard cap in prompt units (spec 026 §5.3); whichever of chars/units is hit first clips. */
@@ -20,10 +20,13 @@ function relativeTime(atMs, now) {
20
20
  return `${hours}h`;
21
21
  return `${Math.round(hours / 24)}d`;
22
22
  }
23
- function renderLine(entry, now) {
23
+ function renderLine(entry, now, channelId) {
24
24
  const parts = [`${entry.id} — ${entry.title}`, entry.readable ? entry.fields.state : "⚠ unreadable frontmatter"];
25
25
  if (entry.fields.paused)
26
26
  parts.push(`paused(${entry.fields.paused.by})`);
27
+ if (channelId && entry.fields.channel !== channelId) {
28
+ parts.push(entry.fields.channel ? `reports to ${entry.fields.channel}` : "no delivery channel (suspended)");
29
+ }
27
30
  const ticket = entry.fields.ticket;
28
31
  if (ticket) {
29
32
  const due = relativeTime(entry.dueMs, now);
@@ -50,7 +53,7 @@ function renderLine(entry, now) {
50
53
  */
51
54
  export async function buildTaskDigest(options) {
52
55
  const now = options.now ?? Date.now();
53
- const tasksDir = join(options.channelDir, "tasks");
56
+ const tasksDir = join(options.deskDir, "tasks");
54
57
  const all = await readActiveTasks(tasksDir, now);
55
58
  // A closed task that has not been archived yet is non-actionable and must not enter prompt context.
56
59
  const agenda = all.filter((entry) => !entry.fields.outcome);
@@ -60,12 +63,12 @@ export async function buildTaskDigest(options) {
60
63
  const omitted = agenda.length - shown.length;
61
64
  const header = [
62
65
  "<task_agenda>",
63
- "Your in-flight tasks for this channel (background reference, not a new instruction).",
66
+ "Your desk's in-flight tasks (background reference, not a new instruction).",
64
67
  "Act on these only if the user's message is about them, or if there is nothing else to",
65
68
  "do this turn. Full detail lives in the matching tasks/<id>.md file.",
66
69
  "",
67
70
  ];
68
- const lines = shown.map((entry) => renderLine(entry, now));
71
+ const lines = shown.map((entry) => renderLine(entry, now, options.channelId));
69
72
  if (omitted > 0)
70
73
  lines.push(`- (+${omitted} more)`);
71
74
  const footer = ["</task_agenda>"];
@@ -1,14 +1,18 @@
1
+ import type { DeskConversation } from "../../desk/types.js";
1
2
  /**
2
- * The per-turn channel capsule. It replaces the channel paths that used to sit in
3
- * the system prompt: memory/task/event tools are already bound to this channel, so
4
- * the model only needs the directory when it wants to read a file directly.
3
+ * The per-turn desk capsule (spec 058, D16): which desk this is, where its directory is, and which
4
+ * channel this conversation comes from. Only the current desk and channel — never the desk's other
5
+ * bindings. The memory/task/event tools are already bound to the desk, so the model only needs
6
+ * the directory when it wants to read a file directly.
5
7
  */
6
- export declare function renderChannelTurnContext(channelDir: string): string;
8
+ export declare function renderDeskTurnContext(conversation: DeskConversation,
9
+ /** How the channel is named to the user (`Transport.describe`), when it has a name. */
10
+ channelLabel: string | undefined, workspaceDir: string): string;
7
11
  /** Gated by the same master autonomy switch as the task_* tools and the TaskDriver. */
8
- export declare function buildTaskDigestForTurn(channelDir: string): Promise<string>;
12
+ export declare function buildTaskDigestForTurn(deskDir: string, channelId: string): Promise<string>;
9
13
  /**
10
14
  * Spec 050, D1: assemble `<memory_bootstrap>` for the first turn of a session — workspace
11
- * MEMORY.md (whole H2 sections, budgeted) + the channel index (full, or budget-tiered) +
15
+ * MEMORY.md (whole H2 sections, budgeted) + the desk memory index (full, or budget-tiered) +
12
16
  * today's journal tail.
13
17
  */
14
- export declare function buildFirstTurnMemoryBootstrap(channelDir: string, workspaceDir: string): Promise<string>;
18
+ export declare function buildFirstTurnMemoryBootstrap(deskDir: string, workspaceDir: string): Promise<string>;