@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
@@ -0,0 +1,145 @@
1
+ /**
2
+ * `/desk` — list, create and bind desks (spec 060). Parsing and rendering live here; the
3
+ * runtime capabilities come in through {@link DeskCommandPort}, implemented by the daemon's
4
+ * `DeskRuntime` and, without `bind`, by the TUI.
5
+ */
6
+ import { renderSubcommandUsage } from "../commands/catalog.js";
7
+ import { capReply } from "../commands/reply-limits.js";
8
+ import { errorMessage } from "../shared/text-utils.js";
9
+ import { normalizeDeskName } from "./paths.js";
10
+ /**
11
+ * `/desk list`'s rows: every desk on disk, plus every desk a binding names that is no longer there
12
+ * (shown missing, D4), each with the channels bound to it. `label` names a channel (the caller
13
+ * owns channel ids); `current` is the asking channel's desk.
14
+ */
15
+ export function buildDeskList(desks, bindings, current, label) {
16
+ const onDisk = new Map(desks.map((summary) => [summary.name, summary.availability]));
17
+ const names = [...new Set([...onDisk.keys(), ...Object.values(bindings).map((binding) => binding.desk)])].sort();
18
+ return names.map((name) => ({
19
+ name,
20
+ availability: onDisk.get(name) ?? "missing",
21
+ current: name === current,
22
+ channels: Object.entries(bindings)
23
+ .filter(([, binding]) => binding.desk === name)
24
+ .map(([channelId]) => ({ channelId, label: label(channelId) })),
25
+ }));
26
+ }
27
+ /** Exported so `test/commands-subcommands.test.ts` can feed every broadcast example back through it. */
28
+ export function parseDeskCommand(args) {
29
+ const parts = args.trim().split(/\s+/).filter(Boolean);
30
+ if (parts.length === 0)
31
+ return { action: "list" };
32
+ const [action, ...rest] = parts;
33
+ if (action === "list") {
34
+ if (rest.length > 0)
35
+ throw new Error("用法:/desk list");
36
+ return { action: "list" };
37
+ }
38
+ if (action === "new" || action === "bind") {
39
+ if (rest.length !== 1)
40
+ throw new Error(`用法:/desk ${action} <名字>`);
41
+ return { action, name: normalizeDeskName(rest[0]) };
42
+ }
43
+ throw new Error(`未知子命令 \`${action}\`。`);
44
+ }
45
+ const NAME_RULE = "工位名只能用 1–32 个小写字母、数字和连字符,且不能以连字符开头或结尾";
46
+ /** The reply to anything but `/desk` and `/help` on a channel with no usable desk (D4). */
47
+ export function formatNoDeskReply(resolution) {
48
+ const why = resolution.kind === "unbound"
49
+ ? "默认工位 `default` 不可用,请部署者在服务器上检查 `workspace/desk-default/`"
50
+ : `本频道绑定的工位 \`${resolution.desk}\` 不可用(目录缺失或 desk.json 有误),请部署者在服务器上检查`;
51
+ return `本频道目前没有可用的工位:${why};也可以用 \`/desk bind <名字>\` 切到其他已有工位。`;
52
+ }
53
+ /** `canBind` is false in the TUI, whose current desk is the one it opened, not one a channel is bound to. */
54
+ function renderList(items, channelIndexPath, canBind) {
55
+ if (items.length === 0) {
56
+ return "暂无工位。默认工位 `default` 缺失且没有任何绑定,需要部署者在服务器上检查 `workspace/`。";
57
+ }
58
+ const lines = ["**工位列表**"];
59
+ for (const item of items) {
60
+ const head = `- \`${item.name}\`${item.current ? (canBind ? "(本频道)" : "(当前打开)") : ""}`;
61
+ if (item.availability !== "available") {
62
+ lines.push(`${head}:不可用(目录缺失或 desk.json 有误),需要部署者在服务器上检查`);
63
+ }
64
+ else if (item.channels.length === 0) {
65
+ lines.push(`${head}:未绑定频道,后台工作已暂停`);
66
+ }
67
+ else {
68
+ lines.push(`${head}:${item.channels.map((channel) => channel.label).join("、")}`);
69
+ }
70
+ }
71
+ return capReply(lines.join("\n"), {
72
+ nextStepHint: `完整的绑定关系在 \`${channelIndexPath}\``,
73
+ }).text;
74
+ }
75
+ function renderCreate(outcome, canBind) {
76
+ switch (outcome.kind) {
77
+ case "invalid":
78
+ return `工位名不合法:\`${outcome.name}\`。${NAME_RULE}。`;
79
+ case "unavailable":
80
+ return `工位 \`${outcome.name}\` 已有绑定但记录缺失,请联系部署者从备份恢复。`;
81
+ case "exists":
82
+ return `工位 \`${outcome.name}\` 已经存在。用 \`/desk\` 查看已有的工位。`;
83
+ case "created": {
84
+ const name = outcome.record.name;
85
+ return canBind
86
+ ? `已创建工位 \`${name}\`。用 \`/desk bind ${name}\` 把本频道绑定到它。`
87
+ : `已创建工位 \`${name}\`。在钉钉频道里用 \`/desk bind ${name}\` 绑定。`;
88
+ }
89
+ }
90
+ }
91
+ function renderBind(outcome) {
92
+ switch (outcome.kind) {
93
+ case "invalid":
94
+ return `工位名不合法:\`${outcome.desk}\`。${NAME_RULE}。`;
95
+ case "forbidden":
96
+ return `当前身份无权使用工位 \`${outcome.desk}\`。`;
97
+ case "unknown":
98
+ return `没有名为 \`${outcome.desk}\` 的工位。用 \`/desk\` 查看已有的工位,或先 \`/desk new ${outcome.desk}\` 创建。`;
99
+ case "unavailable":
100
+ return `工位 \`${outcome.desk}\` 当前不可用(目录缺失或 desk.json 有误),需要部署者在服务器上检查。`;
101
+ case "busy":
102
+ return `本频道正在运行一个回合,现在不能换绑。等它结束后重发 \`/desk bind ${outcome.desk}\`,或先用 \`/stop\` 停止。`;
103
+ case "same":
104
+ return `本频道已经绑定在工位 \`${outcome.desk}\` 上。`;
105
+ case "bound": {
106
+ const lines = [`本频道已绑定到工位 \`${outcome.desk}\`。`];
107
+ if (outcome.previousDesk && outcome.previousDeskDormant) {
108
+ lines.push(`原工位 \`${outcome.previousDesk}\` 已没有绑定的频道,它的定时事件和任务已暂停,重新绑定后自动恢复。`);
109
+ }
110
+ else if (outcome.previousDesk && ((outcome.suspendedTasks ?? 0) > 0 || (outcome.suspendedEvents ?? 0) > 0)) {
111
+ const parts = [];
112
+ if (outcome.suspendedTasks)
113
+ parts.push(`${outcome.suspendedTasks} 个任务`);
114
+ if (outcome.suspendedEvents)
115
+ parts.push(`${outcome.suspendedEvents} 个定时事件`);
116
+ lines.push(`原工位 \`${outcome.previousDesk}\` 中以本频道为投递频道的 ${parts.join("、")}已暂停。`);
117
+ }
118
+ return lines.join("\n");
119
+ }
120
+ }
121
+ }
122
+ export async function handleDeskCommand(args, port) {
123
+ let command;
124
+ try {
125
+ command = parseDeskCommand(args);
126
+ }
127
+ catch (error) {
128
+ return `${errorMessage(error)}\n\n${renderSubcommandUsage("desk")}`;
129
+ }
130
+ try {
131
+ switch (command.action) {
132
+ case "list":
133
+ return renderList(await port.list(), port.channelIndexPath, port.bind !== undefined);
134
+ case "new":
135
+ return renderCreate(await port.create(command.name), port.bind !== undefined);
136
+ case "bind":
137
+ if (!port.bind)
138
+ return "终端不支持绑定,用 `--desk` 选择工位。";
139
+ return renderBind(await port.bind(command.name));
140
+ }
141
+ }
142
+ catch (error) {
143
+ return `执行 /desk ${command.action} 失败:${errorMessage(error)}`;
144
+ }
145
+ }
@@ -0,0 +1,4 @@
1
+ /** Shared by first-run scaffolding, TUI and embedded daemon startup. Never repair an identity. */
2
+ export declare function initializeDefaultDesk(paths: {
3
+ workspaceDir: string;
4
+ }): boolean;
@@ -0,0 +1,11 @@
1
+ /** Initialization policy: the one Pipiclaw assistant starts with a default work context. */
2
+ import { initializeBindings } from "./bindings.js";
3
+ import { DEFAULT_DESK } from "./paths.js";
4
+ import { createDeskRecord } from "./registry.js";
5
+ /** Shared by first-run scaffolding, TUI and embedded daemon startup. Never repair an identity. */
6
+ export function initializeDefaultDesk(paths) {
7
+ const bindings = initializeBindings(paths.workspaceDir);
8
+ if (Object.values(bindings.bindings).some((binding) => binding.desk === DEFAULT_DESK))
9
+ return false;
10
+ return createDeskRecord(paths.workspaceDir, DEFAULT_DESK, new Date()).kind === "created";
11
+ }
@@ -0,0 +1,41 @@
1
+ import type { ConversationKind } from "./types.js";
2
+ /**
3
+ * Every path segment under `workspace/desk-<name>/` comes from a desk name, a conversation name or a
4
+ * fixed file name — never from a channel id (spec 058, INV-3). Both names are validated here,
5
+ * so a path built through these helpers cannot escape its parent.
6
+ */
7
+ export declare const DESK_DIR_PREFIX = "desk-";
8
+ export declare const DEFAULT_DESK = "default";
9
+ export declare const DESK_RECORD_FILENAME = "desk.json";
10
+ export declare const SUBAGENT_RUNS_LOG_FILENAME = "subagent-runs.jsonl";
11
+ export declare function isDeskName(value: string): boolean;
12
+ /** What a user typed, as a candidate desk name: trimmed and lower-cased (validity is checked separately). */
13
+ export declare function normalizeDeskName(value: string): string;
14
+ export declare function isConversationName(value: string): boolean;
15
+ /** `group-3` → `{ kind: "group", index: 3 }`; `undefined` for anything else. */
16
+ export declare function parseConversationName(value: string): {
17
+ kind: ConversationKind;
18
+ index: number;
19
+ } | undefined;
20
+ /** Whether a workspace entry is a desk: a `desk-` prefixed directory (or a link to one). */
21
+ export declare function isDeskEntry(entry: {
22
+ name: string;
23
+ isDirectory(): boolean;
24
+ isSymbolicLink(): boolean;
25
+ }): boolean;
26
+ export declare function getBindingsPath(workspaceDir: string): string;
27
+ export declare function getDeskDir(workspaceDir: string, desk: string): string;
28
+ export declare function getConversationsDir(deskDir: string): string;
29
+ export declare function getConversationDir(deskDir: string, conversation: string): string;
30
+ /** `desk-<desk>/.locks/<name>` — the cross-process short locks of D6 (`memory.lock`, `desk-json.lock`, …). */
31
+ export declare function getDeskLockPath(deskDir: string, lockName: string): string;
32
+ /** `desk-<desk>/inbox/` — inbound images and the full text of oversized messages. */
33
+ export declare function getDeskInboxDir(deskDir: string): string;
34
+ /** `desk-<desk>/logs/` — full output of commands whose result was truncated. */
35
+ export declare function getDeskLogsDir(deskDir: string): string;
36
+ /** `desk-<desk>/subagent-artifacts/` — one directory per delegation run. */
37
+ export declare function getSubAgentArtifactsDir(deskDir: string): string;
38
+ /** `desk-<desk>/.memory-work/` — durable pending boundary reflections, one directory per conversation. */
39
+ export declare function getMemoryWorkDir(deskDir: string): string;
40
+ /** `desk-<desk>/subagent-runs.jsonl` — the archive of settled delegation runs. */
41
+ export declare function getSubAgentRunsLogPath(deskDir: string): string;
@@ -0,0 +1,81 @@
1
+ import { join } from "node:path";
2
+ /**
3
+ * Every path segment under `workspace/desk-<name>/` comes from a desk name, a conversation name or a
4
+ * fixed file name — never from a channel id (spec 058, INV-3). Both names are validated here,
5
+ * so a path built through these helpers cannot escape its parent.
6
+ */
7
+ export const DESK_DIR_PREFIX = "desk-";
8
+ export const DEFAULT_DESK = "default";
9
+ export const DESK_RECORD_FILENAME = "desk.json";
10
+ const BINDINGS_FILENAME = "desk-bindings.json";
11
+ // `tasks/mutation-lock.ts` sits on the same layer and cannot import this module: keep its `.locks` in step.
12
+ const LOCKS_DIRNAME = ".locks";
13
+ const CONVERSATIONS_DIRNAME = "conversations";
14
+ const INBOX_DIRNAME = "inbox";
15
+ const LOGS_DIRNAME = "logs";
16
+ const SUBAGENT_ARTIFACTS_DIRNAME = "subagent-artifacts";
17
+ const MEMORY_WORK_DIRNAME = ".memory-work";
18
+ export const SUBAGENT_RUNS_LOG_FILENAME = "subagent-runs.jsonl";
19
+ const DESK_NAME_PATTERN = /^[a-z0-9](?:[a-z0-9-]{0,30}[a-z0-9])?$/;
20
+ const CONVERSATION_NAME_PATTERN = /^(dm|group|webapi)-([1-9][0-9]*)$/;
21
+ export function isDeskName(value) {
22
+ return DESK_NAME_PATTERN.test(value);
23
+ }
24
+ /** What a user typed, as a candidate desk name: trimmed and lower-cased (validity is checked separately). */
25
+ export function normalizeDeskName(value) {
26
+ return value.trim().toLowerCase();
27
+ }
28
+ export function isConversationName(value) {
29
+ return CONVERSATION_NAME_PATTERN.test(value);
30
+ }
31
+ /** `group-3` → `{ kind: "group", index: 3 }`; `undefined` for anything else. */
32
+ export function parseConversationName(value) {
33
+ const match = CONVERSATION_NAME_PATTERN.exec(value);
34
+ if (!match)
35
+ return undefined;
36
+ return { kind: match[1], index: Number(match[2]) };
37
+ }
38
+ /** Whether a workspace entry is a desk: a `desk-` prefixed directory (or a link to one). */
39
+ export function isDeskEntry(entry) {
40
+ return entry.name.startsWith(DESK_DIR_PREFIX) && (entry.isDirectory() || entry.isSymbolicLink());
41
+ }
42
+ export function getBindingsPath(workspaceDir) {
43
+ return join(workspaceDir, BINDINGS_FILENAME);
44
+ }
45
+ export function getDeskDir(workspaceDir, desk) {
46
+ if (!isDeskName(desk))
47
+ throw new Error(`Invalid desk name: ${desk}`);
48
+ return join(workspaceDir, `${DESK_DIR_PREFIX}${desk}`);
49
+ }
50
+ export function getConversationsDir(deskDir) {
51
+ return join(deskDir, CONVERSATIONS_DIRNAME);
52
+ }
53
+ export function getConversationDir(deskDir, conversation) {
54
+ if (!isConversationName(conversation))
55
+ throw new Error(`Invalid conversation name: ${conversation}`);
56
+ return join(getConversationsDir(deskDir), conversation);
57
+ }
58
+ /** `desk-<desk>/.locks/<name>` — the cross-process short locks of D6 (`memory.lock`, `desk-json.lock`, …). */
59
+ export function getDeskLockPath(deskDir, lockName) {
60
+ return join(deskDir, LOCKS_DIRNAME, lockName);
61
+ }
62
+ /** `desk-<desk>/inbox/` — inbound images and the full text of oversized messages. */
63
+ export function getDeskInboxDir(deskDir) {
64
+ return join(deskDir, INBOX_DIRNAME);
65
+ }
66
+ /** `desk-<desk>/logs/` — full output of commands whose result was truncated. */
67
+ export function getDeskLogsDir(deskDir) {
68
+ return join(deskDir, LOGS_DIRNAME);
69
+ }
70
+ /** `desk-<desk>/subagent-artifacts/` — one directory per delegation run. */
71
+ export function getSubAgentArtifactsDir(deskDir) {
72
+ return join(deskDir, SUBAGENT_ARTIFACTS_DIRNAME);
73
+ }
74
+ /** `desk-<desk>/.memory-work/` — durable pending boundary reflections, one directory per conversation. */
75
+ export function getMemoryWorkDir(deskDir) {
76
+ return join(deskDir, MEMORY_WORK_DIRNAME);
77
+ }
78
+ /** `desk-<desk>/subagent-runs.jsonl` — the archive of settled delegation runs. */
79
+ export function getSubAgentRunsLogPath(deskDir) {
80
+ return join(deskDir, SUBAGENT_RUNS_LOG_FILENAME);
81
+ }
@@ -0,0 +1,17 @@
1
+ import type { ConversationKind, CreateDeskOutcome, DeskConversation, DeskRecord, DeskSummary } from "./types.js";
2
+ /** Read one desk's record, classifying it the way `/desk` and binding resolution need. */
3
+ export declare function readDeskRecord(workspaceDir: string, name: string): Promise<DeskSummary>;
4
+ /** Every directory under `desk-`, each classified. A directory with an illegal name is reported invalid. */
5
+ export declare function listDesks(workspaceDir: string): Promise<DeskSummary[]>;
6
+ /** Create an empty desk without binding it, publishing it atomically. Holds no conversation lock. */
7
+ export declare function createDeskRecord(workspaceDir: string, name: string, now: Date): CreateDeskOutcome;
8
+ /**
9
+ * The conversation directory a channel uses in this desk, allocating it on first use (INV-7):
10
+ * `<kind>-<n>` with `n` one past the largest index of that kind already in `desk.json`. Idempotent —
11
+ * a channel already registered gets its existing directory back. The read-modify-write holds the
12
+ * cross-process `desk-json.lock`, so two processes allocating at once (the daemon and an
13
+ * embedded runtime, or a desk command run elsewhere) never lose each other's entry.
14
+ */
15
+ export declare function allocateConversation(workspaceDir: string, desk: string, channelId: string, kind: ConversationKind, now: Date): Promise<DeskConversation>;
16
+ /** The conversation already registered for `channelId` in `record`, or `undefined`. Pure lookup. */
17
+ export declare function findConversation(record: DeskRecord, deskDir: string, channelId: string): DeskConversation | undefined;
@@ -0,0 +1,191 @@
1
+ /**
2
+ * Disk I/O for `desk-<desk>/desk.json` and desk creation (spec 060). The binding table lives in
3
+ * `bindings.ts`.
4
+ *
5
+ * `desk.json` may be written by the daemon (`/desk bind`) and a TUI (first open) at once, so every
6
+ * read-modify-write of it runs under the cross-process lock `.locks/desk-json.lock`. Writes are
7
+ * atomic and serialized per path in-process.
8
+ *
9
+ * Channel ids are only JSON keys here; this module never parses them — callers pass the
10
+ * conversation kind (the format rules live in `channel/channel-id.ts`).
11
+ */
12
+ import { lstatSync, mkdirSync, mkdtempSync, renameSync, rmSync, writeFileSync } from "node:fs";
13
+ import { mkdir, readdir, readFile } from "node:fs/promises";
14
+ import { isAbsolute, join } from "node:path";
15
+ import { syncDirectoryBestEffort, writeFileAtomically } from "../shared/atomic-file.js";
16
+ import { withFileLock } from "../shared/file-lock.js";
17
+ import { createSerialQueue } from "../shared/serial-queue.js";
18
+ import { isPlainObject } from "../shared/type-guards.js";
19
+ import { initializeBindings } from "./bindings.js";
20
+ import { DESK_DIR_PREFIX, DESK_RECORD_FILENAME, getConversationDir, getDeskDir, getDeskLockPath, isConversationName, isDeskEntry, isDeskName, parseConversationName, } from "./paths.js";
21
+ /** `desk.json` writes are tiny; anything waiting this long is a stuck holder, not contention. */
22
+ const DESK_RECORD_LOCK_TIMEOUT_MS = 10_000;
23
+ const writeQueue = createSerialQueue();
24
+ function errorCode(error) {
25
+ return error && typeof error === "object" && "code" in error ? String(error.code) : undefined;
26
+ }
27
+ function recordPath(deskDir) {
28
+ return join(deskDir, DESK_RECORD_FILENAME);
29
+ }
30
+ /** Validate a parsed `desk.json`; returns the reason it is unusable, or `undefined`. */
31
+ function invalidRecordReason(value, dirName) {
32
+ if (!isPlainObject(value))
33
+ return "desk.json is not a JSON object";
34
+ if (value.version !== 1)
35
+ return `unsupported desk.json version ${String(value.version)}`;
36
+ if (value.name !== dirName)
37
+ return `desk.json name ${JSON.stringify(value.name)} does not match directory ${dirName}`;
38
+ if (typeof value.createdAt !== "string")
39
+ return "desk.json createdAt is missing";
40
+ if (!isPlainObject(value.conversations))
41
+ return "desk.json conversations is not an object";
42
+ if (value.cwd !== undefined && (typeof value.cwd !== "string" || !isAbsolute(value.cwd))) {
43
+ return "desk.json cwd must be an absolute path";
44
+ }
45
+ const dirs = new Set();
46
+ for (const [channelId, entry] of Object.entries(value.conversations)) {
47
+ if (!isPlainObject(entry) || typeof entry.dir !== "string" || !isConversationName(entry.dir)) {
48
+ return `desk.json conversation for ${channelId} has an invalid dir`;
49
+ }
50
+ if (dirs.has(entry.dir))
51
+ return `desk.json conversation dir ${entry.dir} is assigned twice`;
52
+ dirs.add(entry.dir);
53
+ }
54
+ return undefined;
55
+ }
56
+ /** Read one desk's record, classifying it the way `/desk` and binding resolution need. */
57
+ export async function readDeskRecord(workspaceDir, name) {
58
+ if (!isDeskName(name)) {
59
+ return { name, deskDir: "", availability: "invalid", reason: `invalid desk name ${JSON.stringify(name)}` };
60
+ }
61
+ const deskDir = getDeskDir(workspaceDir, name);
62
+ let text;
63
+ try {
64
+ text = await readFile(recordPath(deskDir), "utf-8");
65
+ }
66
+ catch (error) {
67
+ const code = errorCode(error);
68
+ return {
69
+ name,
70
+ deskDir,
71
+ availability: code === "ENOENT" ? "missing" : "invalid",
72
+ reason: code === "ENOENT" ? `${recordPath(deskDir)} does not exist` : `cannot read ${recordPath(deskDir)}`,
73
+ };
74
+ }
75
+ let parsed;
76
+ try {
77
+ parsed = JSON.parse(text);
78
+ }
79
+ catch {
80
+ return { name, deskDir, availability: "invalid", reason: `${recordPath(deskDir)} is not valid JSON` };
81
+ }
82
+ const reason = invalidRecordReason(parsed, name);
83
+ if (reason)
84
+ return { name, deskDir, availability: "invalid", reason };
85
+ return { name, deskDir, availability: "available", record: parsed };
86
+ }
87
+ /** Every directory under `desk-`, each classified. A directory with an illegal name is reported invalid. */
88
+ export async function listDesks(workspaceDir) {
89
+ let entries;
90
+ try {
91
+ entries = (await readdir(workspaceDir, { withFileTypes: true }))
92
+ .filter(isDeskEntry)
93
+ .map((entry) => entry.name.slice(DESK_DIR_PREFIX.length));
94
+ }
95
+ catch (error) {
96
+ if (errorCode(error) === "ENOENT")
97
+ return [];
98
+ throw error;
99
+ }
100
+ const summaries = await Promise.all(entries.sort().map((name) => readDeskRecord(workspaceDir, name)));
101
+ return summaries;
102
+ }
103
+ /** Create an empty desk without binding it, publishing it atomically. Holds no conversation lock. */
104
+ export function createDeskRecord(workspaceDir, name, now) {
105
+ if (!isDeskName(name))
106
+ return { kind: "invalid", name };
107
+ const bindings = initializeBindings(workspaceDir);
108
+ const deskDir = getDeskDir(workspaceDir, name);
109
+ try {
110
+ lstatSync(deskDir);
111
+ return { kind: "exists", name };
112
+ }
113
+ catch (error) {
114
+ if (errorCode(error) !== "ENOENT")
115
+ throw error;
116
+ }
117
+ if (Object.values(bindings.bindings).some((binding) => binding.desk === name))
118
+ return { kind: "unavailable", name };
119
+ mkdirSync(workspaceDir, { recursive: true });
120
+ const staging = mkdtempSync(join(workspaceDir, `.desk-init-${name}-`));
121
+ const record = { version: 1, name, createdAt: now.toISOString(), conversations: {} };
122
+ try {
123
+ writeFileSync(recordPath(staging), `${JSON.stringify(record, null, "\t")}\n`, { flush: true });
124
+ syncDirectoryBestEffort(staging);
125
+ try {
126
+ renameSync(staging, deskDir);
127
+ syncDirectoryBestEffort(workspaceDir);
128
+ }
129
+ catch (error) {
130
+ if (["EEXIST", "ENOTEMPTY"].includes(errorCode(error) ?? ""))
131
+ return { kind: "exists", name };
132
+ throw error;
133
+ }
134
+ return { kind: "created", record };
135
+ }
136
+ finally {
137
+ rmSync(staging, { recursive: true, force: true });
138
+ }
139
+ }
140
+ /**
141
+ * The conversation directory a channel uses in this desk, allocating it on first use (INV-7):
142
+ * `<kind>-<n>` with `n` one past the largest index of that kind already in `desk.json`. Idempotent —
143
+ * a channel already registered gets its existing directory back. The read-modify-write holds the
144
+ * cross-process `desk-json.lock`, so two processes allocating at once (the daemon and an
145
+ * embedded runtime, or a desk command run elsewhere) never lose each other's entry.
146
+ */
147
+ export async function allocateConversation(workspaceDir, desk, channelId, kind, now) {
148
+ const deskDir = getDeskDir(workspaceDir, desk);
149
+ return withFileLock(getDeskLockPath(deskDir, "desk-json.lock"), () => writeQueue.run(recordPath(deskDir), async () => {
150
+ const summary = await readDeskRecord(workspaceDir, desk);
151
+ if (!summary.record)
152
+ throw new Error(`Desk ${desk} is unavailable: ${summary.reason}`);
153
+ const record = summary.record;
154
+ const existing = record.conversations[channelId];
155
+ if (existing) {
156
+ return conversationOf(record, deskDir, channelId, existing.dir);
157
+ }
158
+ let next = 1;
159
+ for (const entry of Object.values(record.conversations)) {
160
+ const parsed = parseConversationName(entry.dir);
161
+ if (parsed?.kind === kind)
162
+ next = Math.max(next, parsed.index + 1);
163
+ }
164
+ const dir = `${kind}-${next}`;
165
+ await mkdir(getConversationDir(deskDir, dir), { recursive: true });
166
+ const updated = {
167
+ ...record,
168
+ conversations: { ...record.conversations, [channelId]: { dir, createdAt: now.toISOString() } },
169
+ };
170
+ await writeJson(recordPath(deskDir), updated);
171
+ return conversationOf(updated, deskDir, channelId, dir);
172
+ }), { timeoutMs: DESK_RECORD_LOCK_TIMEOUT_MS });
173
+ }
174
+ /** The conversation already registered for `channelId` in `record`, or `undefined`. Pure lookup. */
175
+ export function findConversation(record, deskDir, channelId) {
176
+ const entry = record.conversations[channelId];
177
+ return entry ? conversationOf(record, deskDir, channelId, entry.dir) : undefined;
178
+ }
179
+ function conversationOf(record, deskDir, channelId, conversation) {
180
+ return {
181
+ desk: record.name,
182
+ deskDir,
183
+ cwd: record.cwd ?? deskDir,
184
+ channelId,
185
+ conversation,
186
+ conversationDir: getConversationDir(deskDir, conversation),
187
+ };
188
+ }
189
+ async function writeJson(path, value) {
190
+ await writeFileAtomically(path, `${JSON.stringify(value, null, "\t")}\n`);
191
+ }
@@ -0,0 +1,4 @@
1
+ /** A current-state fault the deployer must fix before starting; render without a stack. */
2
+ export declare class StartupRefusal extends Error {
3
+ constructor(message: string);
4
+ }
@@ -0,0 +1,7 @@
1
+ /** A current-state fault the deployer must fix before starting; render without a stack. */
2
+ export class StartupRefusal extends Error {
3
+ constructor(message) {
4
+ super(message);
5
+ this.name = "StartupRefusal";
6
+ }
7
+ }
@@ -0,0 +1,72 @@
1
+ /**
2
+ * A desk is a named work context of the one Pipiclaw assistant (spec 060): it owns memory, journal, tasks,
3
+ * events and working files. Channels are only addresses, bound to a desk through
4
+ * `desk-bindings.json`; each channel that has talked to a desk gets its own conversation
5
+ * directory inside it.
6
+ */
7
+ /** Which family a channel belongs to; decides its conversation directory's `<kind>-<n>` name. */
8
+ export type ConversationKind = "dm" | "group" | "webapi";
9
+ /** One `desk.json` `conversations` entry: where a channel's sessions live inside this desk. */
10
+ export interface DeskConversationRecord {
11
+ /** `<kind>-<n>`, fixed at allocation and never renamed. */
12
+ dir: string;
13
+ createdAt: string;
14
+ }
15
+ /** `desk-<desk>/desk.json`. */
16
+ export interface DeskRecord {
17
+ version: 1;
18
+ /** Always equal to the logical name in desk-<name>; a mismatch makes the desk unavailable. */
19
+ name: string;
20
+ createdAt: string;
21
+ /** Append-only, keyed by channel id — the only place a channel id meets this desk's layout. */
22
+ conversations: Record<string, DeskConversationRecord>;
23
+ /**
24
+ * Optional absolute working directory for the agent (shell cwd, relative-path base, default
25
+ * delegation directory). Absent means the desk directory itself. Memory, tasks, events and
26
+ * every other piece of desk state stay in the desk directory regardless. Edited by hand (D9).
27
+ */
28
+ cwd?: string;
29
+ }
30
+ export interface DeskBinding {
31
+ desk: string;
32
+ boundAt: string;
33
+ }
34
+ /** `desk-bindings.json`: channel id → desk. The single source of truth for bindings (INV-1). */
35
+ export interface BindingsFile {
36
+ version: 1;
37
+ bindings: Record<string, DeskBinding>;
38
+ }
39
+ /** One (desk, channel) pairing, resolved to disk: what a runner, reflect pass or recovery scan works on. */
40
+ export interface DeskConversation {
41
+ desk: string;
42
+ deskDir: string;
43
+ /** Where the agent works: `desk.json`'s `cwd` when set, else `deskDir`. */
44
+ cwd: string;
45
+ channelId: string;
46
+ /** The conversation directory's name, e.g. `group-1`. */
47
+ conversation: string;
48
+ conversationDir: string;
49
+ }
50
+ export type DeskAvailability = "available" | "missing" | "invalid";
51
+ /** A desk as found on disk. `record` is present exactly when `availability` is `available`. */
52
+ export interface DeskSummary {
53
+ name: string;
54
+ deskDir: string;
55
+ availability: DeskAvailability;
56
+ /** English diagnostic for a `missing`/`invalid` desk, for logs and the deployer. */
57
+ reason?: string;
58
+ record?: DeskRecord;
59
+ }
60
+ export type CreateDeskOutcome = {
61
+ kind: "created";
62
+ record: DeskRecord;
63
+ } | {
64
+ kind: "invalid";
65
+ name: string;
66
+ } | {
67
+ kind: "exists";
68
+ name: string;
69
+ } | {
70
+ kind: "unavailable";
71
+ name: string;
72
+ };
@@ -0,0 +1,7 @@
1
+ /**
2
+ * A desk is a named work context of the one Pipiclaw assistant (spec 060): it owns memory, journal, tasks,
3
+ * events and working files. Channels are only addresses, bound to a desk through
4
+ * `desk-bindings.json`; each channel that has talked to a desk gets its own conversation
5
+ * directory inside it.
6
+ */
7
+ export {};