gentle-pi 4.8.0 → 4.9.0

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 (370) hide show
  1. package/README.md +60 -0
  2. package/assets/agents/gentle-ai-explore.md +1 -1
  3. package/assets/agents/gentle-ai-verify.md +1 -1
  4. package/assets/agents/gentle-ai-worker.md +10 -9
  5. package/assets/design-canvas/canvas-boards.js +22 -2
  6. package/assets/design-canvas/canvas-boot.js +3 -1
  7. package/assets/design-canvas/canvas-i18n-es.js +5 -0
  8. package/assets/design-canvas/canvas-menu.js +13 -7
  9. package/assets/design-canvas/canvas-messages.js +1 -1
  10. package/assets/design-canvas/canvas-rail.js +5 -2
  11. package/assets/design-canvas/canvas-store.js +3 -0
  12. package/assets/design-canvas/canvas-theme.js +69 -0
  13. package/assets/design-canvas/canvas.css +27 -2
  14. package/assets/design-canvas/index.html +3 -0
  15. package/assets/design-canvas/inspector.js +28 -5
  16. package/assets/design-canvas/theme-early.js +10 -0
  17. package/assets/migrations/agent-body-history.json +6 -0
  18. package/assets/orchestrator-delegation.md +1 -5
  19. package/assets/orchestrator-full-delegation-card.md +9 -13
  20. package/assets/orchestrator-full-delegation.md +2 -2
  21. package/assets/orchestrator-memory.md +2 -2
  22. package/assets/orchestrator-prompts.md +3 -31
  23. package/assets/orchestrator-tracking.md +6 -6
  24. package/assets/orchestrator-verification.md +4 -4
  25. package/assets/orchestrator-writer.md +12 -12
  26. package/assets/orchestrator.md +2 -2
  27. package/bin/gentle-shell.mjs +77 -1
  28. package/contracts/review-provider-contract-mirror/provider-contract.lock.json +7 -7
  29. package/contracts/review-provider-contract-mirror/{v1.5.0 → v1.6.0}/bundle/manifest.json +3 -3
  30. package/contracts/review-provider-contract-mirror/{v1.5.0 → v1.6.0}/bundle/orchestration/pi.md +1 -1
  31. package/contracts/review-provider-contract-mirror/{v1.5.0 → v1.6.0}/bundle/routing/pi.md +10 -10
  32. package/contracts/review-provider-contract-mirror/{v1.5.0 → v1.6.0}/generated/provider-capabilities.baseline.json +3 -3
  33. package/contracts/review-provider-contract-mirror/{v1.5.0 → v1.6.0}/generated/provider-roles.baseline.json +1 -1
  34. package/docs/assets/features/gentle-tower.png +0 -0
  35. package/docs/auto-permission-answers.md +1 -1
  36. package/docs/bundled-install.md +1 -1
  37. package/docs/delegated-verification.md +6 -4
  38. package/docs/desktop-feed.md +303 -0
  39. package/docs/desktop-rpc.md +703 -25
  40. package/docs/fast-mode.md +2 -2
  41. package/docs/gentle-shell-desktop.md +465 -0
  42. package/docs/gentle-shell.md +65 -3
  43. package/docs/images/desktop/chat.png +0 -0
  44. package/docs/images/desktop/palette.png +0 -0
  45. package/docs/images/desktop/todo.png +0 -0
  46. package/docs/install-wizard.md +1 -1
  47. package/docs/odd-preparation-continuity.md +1 -1
  48. package/docs/readme-reference.md +44 -15
  49. package/docs/work-continuity.md +10 -7
  50. package/extensions/ask-user-choice.ts +36 -18
  51. package/extensions/ask-user-question.ts +47 -8
  52. package/extensions/gentle-agents.ts +206 -37
  53. package/extensions/gentle-ai.ts +234 -24
  54. package/extensions/gentle-desktop-feed.ts +778 -0
  55. package/extensions/gentle-desktop-rpc.ts +145 -12
  56. package/extensions/gentle-herdr-desktop-status.ts +275 -0
  57. package/extensions/gentle-shell.ts +69 -7
  58. package/extensions/gentle-stats.ts +30 -1
  59. package/extensions/gentle-tower.ts +305 -0
  60. package/extensions/skill-registry.ts +13 -3
  61. package/herdr/RECIPE.md +157 -0
  62. package/herdr/keys.json +14 -0
  63. package/herdr/layouts/gentle-shell.json +202 -0
  64. package/herdr/mods/gentle-agents/icons/kind-herdr.svg +1 -0
  65. package/herdr/mods/gentle-agents/icons/kind-remote.svg +1 -0
  66. package/herdr/mods/gentle-agents/icons/kind-tui.svg +1 -0
  67. package/herdr/mods/gentle-agents/main.js +190 -0
  68. package/herdr/mods/gentle-agents/mod.json +1 -0
  69. package/herdr/mods/gentle-agents/snapshot.js +469 -0
  70. package/herdr/mods/gentle-agents/tokens.js +273 -0
  71. package/herdr/mods/gentle-chat/MINIMAL.md +69 -0
  72. package/herdr/mods/gentle-chat/actions.js +180 -0
  73. package/herdr/mods/gentle-chat/feed.js +321 -0
  74. package/herdr/mods/gentle-chat/icons/branch.svg +1 -0
  75. package/herdr/mods/gentle-chat/icons/chat.svg +1 -0
  76. package/herdr/mods/gentle-chat/icons/check.svg +1 -0
  77. package/herdr/mods/gentle-chat/icons/chev.svg +1 -0
  78. package/herdr/mods/gentle-chat/icons/clip.svg +1 -0
  79. package/herdr/mods/gentle-chat/icons/down.svg +1 -0
  80. package/herdr/mods/gentle-chat/icons/folder.svg +1 -0
  81. package/herdr/mods/gentle-chat/icons/kind-herdr.svg +1 -0
  82. package/herdr/mods/gentle-chat/icons/kind-remote.svg +1 -0
  83. package/herdr/mods/gentle-chat/icons/kind-tui.svg +1 -0
  84. package/herdr/mods/gentle-chat/icons/mark.svg +1 -0
  85. package/herdr/mods/gentle-chat/icons/send.svg +1 -0
  86. package/herdr/mods/gentle-chat/icons/shield.svg +1 -0
  87. package/herdr/mods/gentle-chat/icons/stop.svg +1 -0
  88. package/herdr/mods/gentle-chat/icons/term.svg +1 -0
  89. package/herdr/mods/gentle-chat/icons/user.svg +1 -0
  90. package/herdr/mods/gentle-chat/icons/x.svg +1 -0
  91. package/herdr/mods/gentle-chat/main.js +968 -0
  92. package/herdr/mods/gentle-chat/mod.json +1 -0
  93. package/herdr/mods/gentle-chat/session.js +212 -0
  94. package/herdr/mods/gentle-chat/snapshot.js +469 -0
  95. package/herdr/mods/gentle-chat/tokens.js +137 -0
  96. package/herdr/mods/gentle-chat/ui.js +883 -0
  97. package/herdr/mods/gentle-confirm/main.js +60 -0
  98. package/herdr/mods/gentle-confirm/mod.json +1 -0
  99. package/herdr/mods/gentle-inspector/actions.js +180 -0
  100. package/herdr/mods/gentle-inspector/icons/bolt.svg +1 -0
  101. package/herdr/mods/gentle-inspector/icons/bot.svg +1 -0
  102. package/herdr/mods/gentle-inspector/icons/check.svg +1 -0
  103. package/herdr/mods/gentle-inspector/icons/db.svg +1 -0
  104. package/herdr/mods/gentle-inspector/icons/diff.svg +1 -0
  105. package/herdr/mods/gentle-inspector/icons/jobs.svg +1 -0
  106. package/herdr/mods/gentle-inspector/icons/plug.svg +1 -0
  107. package/herdr/mods/gentle-inspector/icons/review.svg +1 -0
  108. package/herdr/mods/gentle-inspector/icons/stats.svg +1 -0
  109. package/herdr/mods/gentle-inspector/icons/stop.svg +1 -0
  110. package/herdr/mods/gentle-inspector/icons/todo.svg +1 -0
  111. package/herdr/mods/gentle-inspector/main.js +500 -0
  112. package/herdr/mods/gentle-inspector/mod.json +1 -0
  113. package/herdr/mods/gentle-inspector/snapshot.js +469 -0
  114. package/herdr/mods/gentle-inspector/tokens.js +273 -0
  115. package/herdr/mods/gentle-palette/actions.js +180 -0
  116. package/herdr/mods/gentle-palette/icons/bolt.svg +1 -0
  117. package/herdr/mods/gentle-palette/icons/bot.svg +1 -0
  118. package/herdr/mods/gentle-palette/icons/chat.svg +1 -0
  119. package/herdr/mods/gentle-palette/icons/check.svg +1 -0
  120. package/herdr/mods/gentle-palette/icons/cmd.svg +1 -0
  121. package/herdr/mods/gentle-palette/icons/diff.svg +1 -0
  122. package/herdr/mods/gentle-palette/icons/jobs.svg +1 -0
  123. package/herdr/mods/gentle-palette/icons/plus.svg +1 -0
  124. package/herdr/mods/gentle-palette/icons/review.svg +1 -0
  125. package/herdr/mods/gentle-palette/icons/search.svg +1 -0
  126. package/herdr/mods/gentle-palette/icons/shield.svg +1 -0
  127. package/herdr/mods/gentle-palette/icons/stats.svg +1 -0
  128. package/herdr/mods/gentle-palette/icons/stop.svg +1 -0
  129. package/herdr/mods/gentle-palette/icons/term.svg +1 -0
  130. package/herdr/mods/gentle-palette/icons/todo.svg +1 -0
  131. package/herdr/mods/gentle-palette/main.js +333 -0
  132. package/herdr/mods/gentle-palette/mod.json +1 -0
  133. package/herdr/mods/gentle-palette/snapshot.js +469 -0
  134. package/herdr/mods/gentle-palette/tokens.js +273 -0
  135. package/herdr/mods/gentle-pane/icons/chat.svg +1 -0
  136. package/herdr/mods/gentle-pane/icons/close.svg +1 -0
  137. package/herdr/mods/gentle-pane/icons/kind-herdr.svg +1 -0
  138. package/herdr/mods/gentle-pane/icons/kind-remote.svg +1 -0
  139. package/herdr/mods/gentle-pane/icons/kind-tui.svg +1 -0
  140. package/herdr/mods/gentle-pane/icons/split-down.svg +1 -0
  141. package/herdr/mods/gentle-pane/icons/split-right.svg +1 -0
  142. package/herdr/mods/gentle-pane/icons/term.svg +1 -0
  143. package/herdr/mods/gentle-pane/icons/unzoom.svg +1 -0
  144. package/herdr/mods/gentle-pane/icons/zoom.svg +1 -0
  145. package/herdr/mods/gentle-pane/main.js +91 -0
  146. package/herdr/mods/gentle-pane/mod.json +1 -0
  147. package/herdr/mods/gentle-pane/snapshot.js +469 -0
  148. package/herdr/mods/gentle-pane/tokens.js +273 -0
  149. package/herdr/mods/gentle-sidebar/actions.js +180 -0
  150. package/herdr/mods/gentle-sidebar/icons/gear.svg +1 -0
  151. package/herdr/mods/gentle-sidebar/icons/mark.svg +1 -0
  152. package/herdr/mods/gentle-sidebar/icons/refresh.svg +1 -0
  153. package/herdr/mods/gentle-sidebar/icons/server-plus.svg +1 -0
  154. package/herdr/mods/gentle-sidebar/main.js +171 -0
  155. package/herdr/mods/gentle-sidebar/mod.json +1 -0
  156. package/herdr/mods/gentle-sidebar/snapshot.js +469 -0
  157. package/herdr/mods/gentle-sidebar/tokens.js +273 -0
  158. package/herdr/mods/gentle-spaces/icons/kind-herdr.svg +1 -0
  159. package/herdr/mods/gentle-spaces/icons/kind-remote.svg +1 -0
  160. package/herdr/mods/gentle-spaces/icons/kind-tui.svg +1 -0
  161. package/herdr/mods/gentle-spaces/icons/monitor.svg +1 -0
  162. package/herdr/mods/gentle-spaces/icons/plus.svg +1 -0
  163. package/herdr/mods/gentle-spaces/icons/server.svg +1 -0
  164. package/herdr/mods/gentle-spaces/machines.js +31 -0
  165. package/herdr/mods/gentle-spaces/main.js +299 -0
  166. package/herdr/mods/gentle-spaces/mod.json +1 -0
  167. package/herdr/mods/gentle-spaces/snapshot.js +469 -0
  168. package/herdr/mods/gentle-spaces/tokens.js +273 -0
  169. package/herdr/mods/gentle-status/actions.js +180 -0
  170. package/herdr/mods/gentle-status/main.js +192 -0
  171. package/herdr/mods/gentle-status/mod.json +1 -0
  172. package/herdr/mods/gentle-status/snapshot.js +469 -0
  173. package/herdr/mods/gentle-status/tokens.js +273 -0
  174. package/herdr/mods/gentle-tabs/icons/close.svg +1 -0
  175. package/herdr/mods/gentle-tabs/icons/kind-herdr.svg +1 -0
  176. package/herdr/mods/gentle-tabs/icons/kind-remote.svg +1 -0
  177. package/herdr/mods/gentle-tabs/icons/kind-tui.svg +1 -0
  178. package/herdr/mods/gentle-tabs/icons/plus.svg +1 -0
  179. package/herdr/mods/gentle-tabs/icons/win-close.svg +1 -0
  180. package/herdr/mods/gentle-tabs/icons/win-max.svg +1 -0
  181. package/herdr/mods/gentle-tabs/icons/win-min.svg +1 -0
  182. package/herdr/mods/gentle-tabs/icons/win-restore.svg +1 -0
  183. package/herdr/mods/gentle-tabs/main.js +171 -0
  184. package/herdr/mods/gentle-tabs/mod.json +1 -0
  185. package/herdr/mods/gentle-tabs/snapshot.js +469 -0
  186. package/herdr/mods/gentle-tabs/tokens.js +273 -0
  187. package/herdr/mods/gentle-tokens/main.js +20 -0
  188. package/herdr/mods/gentle-tokens/mod.json +1 -0
  189. package/herdr/mods/gentle-tokens/snapshot.js +469 -0
  190. package/herdr/mods/gentle-tokens/tokens.js +273 -0
  191. package/herdr/preview.png +0 -0
  192. package/herdr/themes/gentle-shell-dark.json +33 -0
  193. package/herdr/themes/gentle-shell-light.json +34 -0
  194. package/lib/agents-protocol.ts +2 -0
  195. package/lib/agents-rpc-publisher.ts +39 -12
  196. package/lib/agents-runner.ts +1 -0
  197. package/lib/auto-permission-answers.ts +2 -1
  198. package/lib/background-jobs.ts +22 -2
  199. package/lib/bounded-writer-admission.ts +1 -1
  200. package/lib/change-diff.ts +104 -0
  201. package/lib/commit-slice-signal.ts +1 -1
  202. package/lib/design-canvas-assets.ts +2 -0
  203. package/lib/desktop-agents-service.ts +31 -10
  204. package/lib/desktop-changes-service.ts +171 -0
  205. package/lib/desktop-feed-actions.ts +804 -0
  206. package/lib/desktop-feed-answers.ts +129 -0
  207. package/lib/desktop-feed-sources.ts +184 -0
  208. package/lib/desktop-feed-stats.ts +98 -0
  209. package/lib/desktop-feed-store.ts +124 -0
  210. package/lib/desktop-feed.ts +788 -0
  211. package/lib/desktop-jobs-service.ts +34 -7
  212. package/lib/desktop-review-service.ts +187 -0
  213. package/lib/desktop-rpc-agents.ts +112 -3
  214. package/lib/desktop-rpc-changes.ts +223 -0
  215. package/lib/desktop-rpc-config-watch.ts +285 -0
  216. package/lib/desktop-rpc-config.ts +162 -8
  217. package/lib/desktop-rpc-jobs.ts +118 -9
  218. package/lib/desktop-rpc-permissions.ts +154 -3
  219. package/lib/desktop-rpc-review.ts +180 -0
  220. package/lib/desktop-rpc-session.ts +203 -0
  221. package/lib/desktop-rpc-sessions.ts +250 -0
  222. package/lib/desktop-rpc-stats.ts +187 -0
  223. package/lib/desktop-rpc-updates.ts +143 -0
  224. package/lib/desktop-rpc.ts +116 -5
  225. package/lib/desktop-session-service.ts +223 -0
  226. package/lib/desktop-sessions-service.ts +249 -0
  227. package/lib/desktop-stats-service.ts +142 -0
  228. package/lib/desktop-updates-service.ts +268 -0
  229. package/lib/gentle-shell-desktop.ts +1370 -0
  230. package/lib/gentle-shell-launcher.ts +45 -3
  231. package/lib/herdr-desktop-events.ts +40 -0
  232. package/lib/herdr-desktop-status.ts +229 -0
  233. package/lib/jobs-sidebar-state.ts +5 -0
  234. package/lib/native-review-cli.ts +7 -0
  235. package/lib/openai-fast-tier.ts +1 -0
  236. package/lib/session-profile-freeze.ts +13 -5
  237. package/lib/stats-collector.ts +56 -27
  238. package/lib/tower-actions.ts +100 -0
  239. package/lib/tower-hub.ts +73 -0
  240. package/lib/tower-launch.ts +111 -0
  241. package/lib/tower-open.ts +99 -0
  242. package/lib/tower-presence.ts +70 -0
  243. package/lib/tower-server.ts +234 -0
  244. package/lib/tower-snapshot.ts +298 -0
  245. package/lib/update-status.ts +238 -0
  246. package/lib/verifier-settle-reminder.ts +1 -1
  247. package/package.json +13 -4
  248. package/runtime/design-canvas-assets.mjs +2 -0
  249. package/runtime/gentle-shell-desktop.mjs +1371 -0
  250. package/runtime/gentle-shell-launcher.mjs +44 -2
  251. package/runtime/native-review-cli.mjs +7 -0
  252. package/runtime/tower-actions.mjs +101 -0
  253. package/runtime/tower-hub.mjs +74 -0
  254. package/runtime/tower-launch.mjs +112 -0
  255. package/runtime/tower-open.mjs +100 -0
  256. package/runtime/tower-presence.mjs +71 -0
  257. package/runtime/tower-server.mjs +234 -0
  258. package/runtime/tower-snapshot.mjs +299 -0
  259. package/scripts/build-full-delegation-card.mjs +1 -21
  260. package/scripts/build-runtime-modules.mjs +9 -0
  261. package/scripts/gentle-ai-installer.mjs +10 -10
  262. package/scripts/verify-package-files.mjs +35 -15
  263. package/skills/provider-defect-report/SKILL.md +61 -0
  264. package/skills/rdd-defect-workflow/SKILL.md +3 -3
  265. package/tests/agent-prompt-diet-contract.test.ts +2 -2
  266. package/tests/append-system-prompt-route.test.ts +16 -5
  267. package/tests/ask-user-choice.test.ts +78 -21
  268. package/tests/ask-user-question.test.ts +59 -5
  269. package/tests/auto-permission-answers.test.ts +12 -1
  270. package/tests/background-jobs.test.ts +12 -0
  271. package/tests/bounded-stop-contract.test.ts +139 -26
  272. package/tests/change-diff.test.ts +75 -0
  273. package/tests/commit-slice-signal.test.ts +3 -2
  274. package/tests/decision-routing-contract.test.ts +390 -0
  275. package/tests/delegated-key-learnings-contract.test.ts +21 -28
  276. package/tests/delivery-b-rendered-surfaces.test.ts +32 -0
  277. package/tests/design-canvas-i18n.test.ts +24 -22
  278. package/tests/design-canvas-inspector.test.ts +67 -0
  279. package/tests/design-canvas-modules.test.ts +3 -2
  280. package/tests/design-canvas-rail.test.ts +10 -10
  281. package/tests/design-canvas-store.test.ts +9 -0
  282. package/tests/design-canvas-theme.test.ts +198 -0
  283. package/tests/design-canvas-tokens.test.ts +1 -1
  284. package/tests/desktop-feed-actions-guards.test.ts +595 -0
  285. package/tests/desktop-feed-actions.test.ts +761 -0
  286. package/tests/desktop-feed-live-work.test.ts +209 -0
  287. package/tests/desktop-feed-performance.test.ts +369 -0
  288. package/tests/desktop-feed-plan-profiles.test.ts +509 -0
  289. package/tests/desktop-feed-send-prompt.test.ts +303 -0
  290. package/tests/desktop-feed-tool-summaries.test.ts +69 -0
  291. package/tests/desktop-feed.test.ts +615 -0
  292. package/tests/desktop-rpc-agents.test.ts +428 -2
  293. package/tests/desktop-rpc-changes.test.ts +608 -0
  294. package/tests/desktop-rpc-config-watch.test.ts +1159 -0
  295. package/tests/desktop-rpc-config.test.ts +11 -1
  296. package/tests/desktop-rpc-design.test.ts +11 -1
  297. package/tests/desktop-rpc-jobs.test.ts +402 -5
  298. package/tests/desktop-rpc-permissions.test.ts +11 -1
  299. package/tests/desktop-rpc-review.test.ts +678 -0
  300. package/tests/desktop-rpc-session.test.ts +642 -0
  301. package/tests/desktop-rpc-sessions.test.ts +647 -0
  302. package/tests/desktop-rpc-stats.test.ts +431 -0
  303. package/tests/desktop-rpc-updates.test.ts +525 -0
  304. package/tests/desktop-rpc-usage.test.ts +11 -1
  305. package/tests/desktop-rpc.test.ts +43 -2
  306. package/tests/fixtures/primary-session-prompt/gentleman.golden.md +11 -13
  307. package/tests/fixtures/session-profile-v1/replay.ts +4 -1
  308. package/tests/full-delegation-closure.test.ts +20 -1
  309. package/tests/gentle-agents.test.ts +519 -4
  310. package/tests/gentle-ai-binary.test.ts +1 -1
  311. package/tests/gentle-ai-installer.test.ts +52 -52
  312. package/tests/gentle-ai.test.ts +75 -16
  313. package/tests/gentle-fast.test.ts +15 -0
  314. package/tests/gentle-herdr-desktop-status.test.ts +595 -0
  315. package/tests/gentle-shell-desktop-bin.test.ts +125 -0
  316. package/tests/gentle-shell-desktop.test.ts +927 -0
  317. package/tests/gentle-shell-launcher-tower.test.ts +104 -0
  318. package/tests/gentle-shell.test.ts +3 -0
  319. package/tests/gentle-tower.test.ts +578 -0
  320. package/tests/herdr-desktop-status.test.ts +285 -0
  321. package/tests/independent-recovery-delivery.test.ts +16 -4
  322. package/tests/installer-server.test.ts +2 -2
  323. package/tests/lazy-module-contradictions-contract.test.ts +27 -4
  324. package/tests/maintainer/desktop-rpc.maintest.ts +279 -4
  325. package/tests/native-review-capability-contract.test.ts +9 -1
  326. package/tests/no-self-pause-contract.test.ts +23 -13
  327. package/tests/odd-routing-canonical-ratchet.test.ts +10 -0
  328. package/tests/odd-routing-contract.test.ts +19 -3
  329. package/tests/orchestrator-budget.test.ts +3 -1
  330. package/tests/orchestrator-prompt-budget.test.ts +2 -1
  331. package/tests/orchestrator-prompt-diet-contract.test.ts +31 -3
  332. package/tests/package-manifest.test.ts +10 -10
  333. package/tests/pi-routing-measured-values.test.ts +24 -0
  334. package/tests/primary-session-prompt.test.ts +25 -0
  335. package/tests/profile-fast-tier.test.ts +66 -1
  336. package/tests/provider-defect-handoff.test.ts +118 -100
  337. package/tests/review-contract-prompt.test.ts +2 -1
  338. package/tests/review-due-public-boundary.test.ts +2 -1
  339. package/tests/sensitive-path-tools.test.ts +138 -4
  340. package/tests/session-profile-extension.test.ts +310 -16
  341. package/tests/session-profile-freeze.test.ts +26 -0
  342. package/tests/session-profile-v1-compat.test.ts +20 -0
  343. package/tests/skill-collision-prefixes.test.ts +1 -0
  344. package/tests/skill-contradictions-contract.test.ts +5 -3
  345. package/tests/skill-registry.test.ts +54 -0
  346. package/tests/stats-collector.test.ts +109 -2
  347. package/tests/support/design-canvas-dom.ts +17 -0
  348. package/tests/task-size-routing-contract.test.ts +7 -3
  349. package/tests/tower-actions.test.ts +247 -0
  350. package/tests/tower-artifacts.test.ts +114 -0
  351. package/tests/tower-open.test.ts +97 -0
  352. package/tests/tower-presence.test.ts +175 -0
  353. package/tests/tower-server.test.ts +122 -0
  354. package/tests/tower-snapshot.test.ts +236 -0
  355. package/tests/tower-web-echo.test.ts +125 -0
  356. package/tests/tower-web-hover.test.ts +251 -0
  357. package/tests/verification-scoped-stop-contract.test.ts +32 -0
  358. package/tests/verification-tiers-contract.test.ts +5 -5
  359. package/tests/verifier-settle-reminder.test.ts +2 -2
  360. package/tests/verify-first-launch-contract.test.ts +2 -2
  361. package/tests/work-continuity-contract.test.ts +83 -17
  362. package/tests/writer-rejection-next-step.test.ts +55 -0
  363. package/tests/writer-surface-authority-contract.test.ts +158 -0
  364. /package/contracts/review-provider-contract-mirror/{v1.5.0 → v1.6.0}/bundle/README.md +0 -0
  365. /package/contracts/review-provider-contract-mirror/{v1.5.0 → v1.6.0}/bundle/schemas/lens.schema.json +0 -0
  366. /package/contracts/review-provider-contract-mirror/{v1.5.0 → v1.6.0}/bundle/schemas/refuter.schema.json +0 -0
  367. /package/contracts/review-provider-contract-mirror/{v1.5.0 → v1.6.0}/bundle/schemas/targeted-validator.schema.json +0 -0
  368. /package/contracts/review-provider-contract-mirror/{v1.5.0 → v1.6.0}/bundle/vectors/lens.json +0 -0
  369. /package/contracts/review-provider-contract-mirror/{v1.5.0 → v1.6.0}/bundle/vectors/refuter.json +0 -0
  370. /package/contracts/review-provider-contract-mirror/{v1.5.0 → v1.6.0}/bundle/vectors/targeted-validator.json +0 -0
@@ -0,0 +1,203 @@
1
+ // Gentle Desktop session-state slice (#3319): the pure contract shared by the
2
+ // Desktop bridge (`lib/desktop-session-service.ts`) and the owner seam inside
3
+ // `extensions/gentle-desktop-feed.ts`.
4
+ //
5
+ // The feed extension already computes the whole session projection the TUI
6
+ // sidebar and the Herdr feed show (`buildDesktopFeedSnapshot`). This module
7
+ // keeps no second copy of that state: it names the sections `get_snapshot`
8
+ // may carry, parses the request strictly, and turns one feed snapshot into the
9
+ // wire-safe sections — no identity block, no process data, no absolute path.
10
+
11
+ import { createHash } from "node:crypto";
12
+ import type { DesktopFeedSnapshot } from "./desktop-feed.ts";
13
+
14
+ export const DESKTOP_SESSION_EVENT = "session_snapshot";
15
+ /** Advertised only while the feed owner seam is wired for the session. */
16
+ export const DESKTOP_SESSION_EVENTS = [DESKTOP_SESSION_EVENT] as const;
17
+
18
+ // The versioned owner-service discovery seam (the session analogue of
19
+ // `gentle:desktop:jobs-service`). The schema string guards the adapter against
20
+ // drift; the bridge ignores any responder whose shape does not match.
21
+ export const DESKTOP_SESSION_SERVICE_SCHEMA = "gentle-pi.desktop-session-service/v1";
22
+ export const DESKTOP_SESSION_SERVICE_CHANNEL = "gentle:desktop:session-service";
23
+
24
+ /** The feed sections a client may request, in their canonical wire order. */
25
+ export const DESKTOP_SESSION_SECTIONS = [
26
+ "project",
27
+ "model",
28
+ "context",
29
+ "cost",
30
+ "usage",
31
+ "profiles",
32
+ "permission",
33
+ "todo",
34
+ "changes",
35
+ "agents",
36
+ "jobs",
37
+ "review",
38
+ "stats",
39
+ "activity",
40
+ "pendingQuestion",
41
+ "commands",
42
+ ] as const;
43
+
44
+ export type DesktopSessionSection = typeof DESKTOP_SESSION_SECTIONS[number];
45
+ export type DesktopSessionSections = Partial<Record<DesktopSessionSection, unknown>>;
46
+
47
+ /**
48
+ * The owner-service adapter the bridge discovers. `read` builds the bound
49
+ * session's live feed snapshot (undefined when that session is not live);
50
+ * `observe` reports each snapshot the feed publishes on its own tiers.
51
+ */
52
+ export interface DesktopSessionService {
53
+ schema: typeof DESKTOP_SESSION_SERVICE_SCHEMA;
54
+ read(): DesktopFeedSnapshot | undefined;
55
+ observe(onSnapshot: (snapshot: DesktopFeedSnapshot) => void): () => void;
56
+ dispose(): void;
57
+ }
58
+
59
+ export const INVALID_SESSION_PARAMS = { code: "invalid_request", message: "Invalid session snapshot sections" } as const;
60
+ export const SESSION_UNAVAILABLE = { code: "session_unavailable", message: "Session state owner unavailable for this session" } as const;
61
+
62
+ const KNOWN = new Set<string>(DESKTOP_SESSION_SECTIONS);
63
+
64
+ /**
65
+ * `get_snapshot` params. Without a `sections` key the request is the legacy
66
+ * read, byte-for-byte (its params were never inspected). With one, the params
67
+ * are exactly `{ sections: [unique known names, at least one] }`.
68
+ */
69
+ export function parseSessionSnapshotParams(params: Record<string, unknown>):
70
+ | { legacy: true }
71
+ | { sections: DesktopSessionSection[] }
72
+ | { error: { code: string; message: string } } {
73
+ if (!Object.hasOwn(params, "sections")) return { legacy: true };
74
+ const keys = Object.keys(params);
75
+ const sections = params.sections;
76
+ if (keys.length !== 1 || !Array.isArray(sections) || sections.length === 0 || sections.length > DESKTOP_SESSION_SECTIONS.length) {
77
+ return { error: INVALID_SESSION_PARAMS };
78
+ }
79
+ const seen = new Set<string>();
80
+ for (const name of sections) {
81
+ if (typeof name !== "string" || !KNOWN.has(name) || seen.has(name)) return { error: INVALID_SESSION_PARAMS };
82
+ seen.add(name);
83
+ }
84
+ return { sections: sections as DesktopSessionSection[] };
85
+ }
86
+
87
+ /** True only for the adapter-shaped object the discovery responder must return. */
88
+ export function isDesktopSessionServiceShape(value: unknown): value is DesktopSessionService {
89
+ if (!value || typeof value !== "object") return false;
90
+ const adapter = value as Partial<DesktopSessionService>;
91
+ if (adapter.schema !== DESKTOP_SESSION_SERVICE_SCHEMA) return false;
92
+ return [adapter.read, adapter.observe, adapter.dispose].every((fn) => typeof fn === "function");
93
+ }
94
+
95
+ /** An opaque, stable label for a worktree root: never the path itself. */
96
+ export function desktopSessionRootLabel(root: string): string {
97
+ return `root-${createHash("sha256").update(root).digest("hex").slice(0, 12)}`;
98
+ }
99
+
100
+ /** A drive-qualified or rooted path (POSIX `/`, Windows `C:`, `\`, or UNC `\\`). */
101
+ const ABSOLUTE_PATH = /^(?:[a-zA-Z]:|[\\/])/;
102
+ /** A bare drive designator: `C:` once trailing separators are gone. */
103
+ const DRIVE_ONLY = /^[a-zA-Z]:$/;
104
+
105
+ /** The last path segment, whichever separator the platform used. */
106
+ function baseName(path: string): string {
107
+ return path.replace(/[\\/]+$/, "").split(/[\\/]/).pop() ?? "";
108
+ }
109
+
110
+ function projectSection(project: DesktopFeedSnapshot["project"]) {
111
+ const name = baseName(project.cwd);
112
+ // A filesystem root (`/`) or a drive root (`C:\`) names no project.
113
+ return { name: name.length > 0 && !DRIVE_ONLY.test(name) ? name : null, branch: project.branch, dirty: project.dirty };
114
+ }
115
+
116
+ /**
117
+ * A worktree root normalized for prefix matching, or undefined for a root
118
+ * that would relativize everything (`/`, a bare drive). Windows-style roots
119
+ * (a drive letter or a backslash) compare case-insensitively, as the
120
+ * filesystem does; POSIX roots stay case-sensitive.
121
+ */
122
+ function matchableRoot(root: string): { prefix: string; fold: boolean } | undefined {
123
+ const trimmed = root.replaceAll("\\", "/").replace(/\/+$/, "");
124
+ if (trimmed.length === 0 || DRIVE_ONLY.test(trimmed)) return undefined;
125
+ const fold = /^[a-zA-Z]:/.test(root) || root.includes("\\");
126
+ return { prefix: `${fold ? trimmed.toLowerCase() : trimmed}/`, fold };
127
+ }
128
+
129
+ /**
130
+ * Changes without a path: each worktree root becomes its opaque label, and
131
+ * each file path is made relative to the worktree that holds it (several
132
+ * worktrees prefix the combined model's paths with their absolute root). A
133
+ * path no worktree holds keeps only its file name. A root of `/` or a bare
134
+ * drive gets no label and holds no file, so it never relativizes every path.
135
+ */
136
+ function changesSection(changes: DesktopFeedSnapshot["changes"]) {
137
+ if (!changes) return null;
138
+ const label = (root: string) => (matchableRoot(root) ? desktopSessionRootLabel(root) : null);
139
+ const roots = changes.worktrees
140
+ .flatMap((tree) => {
141
+ const match = matchableRoot(tree.root);
142
+ return match ? [{ ...match, label: desktopSessionRootLabel(tree.root) }] : [];
143
+ })
144
+ .sort((left, right) => right.prefix.length - left.prefix.length);
145
+ const single = changes.worktrees.length === 1 ? label(changes.worktrees[0]!.root) : null;
146
+ // A lone `/` or drive-root worktree: its relative paths are root-relative, so only the name crosses.
147
+ const unlabeled = changes.worktrees.length === 1 && single === null;
148
+ const locate = (path: string): { path: string; root: string | null } => {
149
+ const normalized = path.replaceAll("\\", "/");
150
+ const folded = normalized.toLowerCase();
151
+ for (const { prefix, fold, label: rootLabel } of roots) {
152
+ if ((fold ? folded : normalized).startsWith(prefix)) return { path: normalized.slice(prefix.length), root: rootLabel };
153
+ }
154
+ if (ABSOLUTE_PATH.test(path) || unlabeled) return { path: baseName(path), root: null };
155
+ return { path, root: single };
156
+ };
157
+ return {
158
+ files: changes.files.map((file) => ({ ...locate(file.path), status: file.status, added: file.added, deleted: file.deleted })),
159
+ summary: { ...changes.summary },
160
+ worktrees: changes.worktrees.map((tree) => ({ root: label(tree.root), branch: tree.branch, files: tree.files })),
161
+ truncated: changes.truncated,
162
+ };
163
+ }
164
+
165
+ /** A detached copy of a section that carries no path (the feed already bounded it). */
166
+ const copy = <T>(value: T): T => (value === null || value === undefined ? value : JSON.parse(JSON.stringify(value)) as T);
167
+
168
+ function section(snapshot: DesktopFeedSnapshot, name: DesktopSessionSection): unknown {
169
+ switch (name) {
170
+ case "project": return projectSection(snapshot.project);
171
+ case "changes": return changesSection(snapshot.changes);
172
+ default: return copy(snapshot[name]);
173
+ }
174
+ }
175
+
176
+ /**
177
+ * The wire-safe sections of one feed snapshot, in canonical order. The
178
+ * identity block (session file, cwd, real cwd, pid, ppid, ancestors, agent
179
+ * dir) is never read; `project.cwd` becomes its basename `project.name`;
180
+ * worktree roots become opaque labels. Arrays keep the feed's caps.
181
+ */
182
+ export function projectDesktopSessionSections(snapshot: DesktopFeedSnapshot, names: readonly DesktopSessionSection[]): DesktopSessionSections {
183
+ const wanted = new Set(names);
184
+ const out: DesktopSessionSections = {};
185
+ for (const name of DESKTOP_SESSION_SECTIONS) {
186
+ if (wanted.has(name)) out[name] = section(snapshot, name);
187
+ }
188
+ return out;
189
+ }
190
+
191
+ /**
192
+ * The comparison key of one projected section: what counts as a change for
193
+ * `session_snapshot`. A job's elapsed time moves on every flush and is
194
+ * derived from `startedAt`, so it is not a change (as in the feed's digest).
195
+ */
196
+ export function desktopSessionSectionKey(name: DesktopSessionSection, value: unknown): string {
197
+ if (name === "jobs" && value && typeof value === "object") {
198
+ const jobs = value as { running?: Array<Record<string, unknown>>; recent?: Array<Record<string, unknown>> };
199
+ const strip = (list: Array<Record<string, unknown>> | undefined) => (list ?? []).map(({ elapsedMs: _elapsed, ...job }) => job);
200
+ return JSON.stringify({ running: strip(jobs.running), recent: strip(jobs.recent) });
201
+ }
202
+ return JSON.stringify(value ?? null);
203
+ }
@@ -0,0 +1,250 @@
1
+ // Gentle Desktop sessions slice: the pure contract shared by the Desktop
2
+ // bridge (`lib/desktop-sessions-service.ts`) and its tests.
3
+ //
4
+ // Nothing here reads a session file or switches a session. It only names the
5
+ // wire shapes, validates params, projects Pi's own `SessionInfo` into the safe
6
+ // Desktop entry, and pages the owner's list. The owner is Pi itself: its
7
+ // `SessionManager.list`/`listAll`/`findById` resolve and read sessions, and the
8
+ // command context's `switchSession` performs the switch. This module is a
9
+ // projection, not a second session scanner or index.
10
+
11
+ import { DESKTOP_RPC_SCHEMA } from "./desktop-rpc.ts";
12
+
13
+ export const DESKTOP_SESSIONS_METHODS = ["list_sessions", "switch_session"] as const;
14
+ /** The slice emits no event: a switch replaces the session, and the new router starts its own sequence. */
15
+ export const DESKTOP_SESSIONS_EVENTS = [] as const;
16
+
17
+ export const DESKTOP_SESSIONS_DEFAULT_LIMIT = 20;
18
+ export const DESKTOP_SESSIONS_MAX_LIMIT = 50;
19
+ export const DESKTOP_SESSIONS_FIRST_MESSAGE_MAX = 200;
20
+ export const DESKTOP_SESSIONS_NAME_MAX = 200;
21
+ const MAX_ID_LENGTH = 256;
22
+ const MAX_CURSOR_LENGTH = 512;
23
+ const UNKNOWN_PROJECT = "unknown";
24
+
25
+ export type DesktopSessionsScope = "project" | "all";
26
+
27
+ /**
28
+ * The safe wire window for one session. Only these fields exist on the wire:
29
+ * Pi's session id, the user-given name, the last-activity time, the message
30
+ * count, a bounded first user message, the project's display name, and
31
+ * whether it is the active session. Never a file path, a cwd, a parent
32
+ * session path, or the full message text.
33
+ */
34
+ export interface DesktopSessionEntry {
35
+ id: string;
36
+ name?: string;
37
+ modified: number;
38
+ messageCount?: number;
39
+ firstMessage: string;
40
+ project: string;
41
+ current: boolean;
42
+ }
43
+
44
+ /** The subset of Pi's `SessionInfo` this slice reads. Everything else is ignored. */
45
+ export interface DesktopSessionInfoLike {
46
+ id: unknown;
47
+ cwd?: unknown;
48
+ name?: unknown;
49
+ modified?: unknown;
50
+ messageCount?: unknown;
51
+ firstMessage?: unknown;
52
+ }
53
+
54
+ export interface DesktopListSessionsParams {
55
+ scope: DesktopSessionsScope;
56
+ limit: number;
57
+ cursor?: DesktopSessionsCursor;
58
+ }
59
+
60
+ export interface DesktopSwitchSessionParams {
61
+ id: string;
62
+ scope: DesktopSessionsScope;
63
+ }
64
+
65
+ /** Keyset position: the last entry of the previous page in newest-first order. */
66
+ export interface DesktopSessionsCursor {
67
+ modified: number;
68
+ id: string;
69
+ }
70
+
71
+ type ParamError = { error: { code: string; message: string } };
72
+
73
+ export const INVALID_SESSIONS_PARAMS = { code: "invalid_request", message: "Invalid sessions parameters" } as const;
74
+ export const SESSIONS_UNAVAILABLE = { code: "sessions_unavailable", message: "Sessions owner unavailable for this session" } as const;
75
+ export const SESSION_SWITCH_FAILED = { code: "sessions_unavailable", message: "The session could not be opened" } as const;
76
+ /** Every request that arrives while a switch is in flight; retry after the switch answers. */
77
+ export const SESSION_SWITCHING = { code: "session_switching", message: "A session switch is in progress; retry after it answers" } as const;
78
+ export const SESSION_NOT_FOUND ={ code: "not_found", message: "No session with that id in the requested scope" } as const;
79
+
80
+ function isScope(value: unknown): value is DesktopSessionsScope {
81
+ return value === "project" || value === "all";
82
+ }
83
+
84
+ /** Bound display text by UTF-16 length without splitting a surrogate pair; a cut is marked with an ellipsis. */
85
+ export function boundDisplayText(value: string, max: number): string {
86
+ const collapsed = value.replace(/\s+/g, " ").trim();
87
+ if (collapsed.length <= max) return collapsed;
88
+ let cut = collapsed.slice(0, max - 1);
89
+ const last = cut.charCodeAt(cut.length - 1);
90
+ if (last >= 0xd800 && last <= 0xdbff) cut = cut.slice(0, -1);
91
+ return `${cut.trimEnd()}…`;
92
+ }
93
+
94
+ /** The project's display name: the last segment of the session's cwd, never the path itself. */
95
+ export function sessionProjectName(cwd: unknown): string {
96
+ if (typeof cwd !== "string") return UNKNOWN_PROJECT;
97
+ const segments = cwd.split(/[\\/]+/).filter((segment) => segment.length > 0);
98
+ const last = segments[segments.length - 1];
99
+ // A bare drive root such as `C:` names no project.
100
+ if (last === undefined || /^[A-Za-z]:$/.test(last)) return UNKNOWN_PROJECT;
101
+ return last;
102
+ }
103
+
104
+ function modifiedMs(value: unknown): number | undefined {
105
+ const ms = value instanceof Date ? value.getTime() : typeof value === "number" ? value : NaN;
106
+ return Number.isFinite(ms) && ms >= 0 ? ms : undefined;
107
+ }
108
+
109
+ /**
110
+ * The whitelisted projection of one owner `SessionInfo`. Every field is rebuilt
111
+ * from the named members only, so `path`, `cwd`, `parentSessionPath`, and
112
+ * `allMessagesText` can never reach the Desktop payload. An entry without a
113
+ * usable id or time is dropped rather than projected into a malformed one.
114
+ */
115
+ export function projectDesktopSession(info: DesktopSessionInfoLike, currentId: string): DesktopSessionEntry | undefined {
116
+ if (!info || typeof info !== "object") return undefined;
117
+ if (typeof info.id !== "string" || info.id.length === 0 || info.id.length > MAX_ID_LENGTH) return undefined;
118
+ const modified = modifiedMs(info.modified);
119
+ if (modified === undefined) return undefined;
120
+ const name = typeof info.name === "string" && info.name.trim().length > 0 ? boundDisplayText(info.name, DESKTOP_SESSIONS_NAME_MAX) : undefined;
121
+ const messageCount = typeof info.messageCount === "number" && Number.isInteger(info.messageCount) && info.messageCount >= 0 ? info.messageCount : undefined;
122
+ // Fixed key order keeps responses byte-stable for clients that diff them.
123
+ return {
124
+ id: info.id,
125
+ ...(name !== undefined ? { name } : {}),
126
+ modified,
127
+ ...(messageCount !== undefined ? { messageCount } : {}),
128
+ firstMessage: typeof info.firstMessage === "string" ? boundDisplayText(info.firstMessage, DESKTOP_SESSIONS_FIRST_MESSAGE_MAX) : "",
129
+ project: sessionProjectName(info.cwd),
130
+ current: info.id === currentId,
131
+ };
132
+ }
133
+
134
+ /** Newest first; equal times fall back to id order so the keyset cursor is total. */
135
+ function compareEntries(left: DesktopSessionEntry, right: DesktopSessionEntry): number {
136
+ if (left.modified !== right.modified) return right.modified - left.modified;
137
+ return left.id < right.id ? -1 : left.id > right.id ? 1 : 0;
138
+ }
139
+
140
+ function isAfterCursor(entry: DesktopSessionEntry, cursor: DesktopSessionsCursor): boolean {
141
+ return compareEntries(entry, { ...entry, modified: cursor.modified, id: cursor.id }) > 0;
142
+ }
143
+
144
+ export function encodeSessionsCursor(cursor: DesktopSessionsCursor): string {
145
+ return Buffer.from(JSON.stringify([cursor.modified, cursor.id]), "utf8").toString("base64url");
146
+ }
147
+
148
+ export function decodeSessionsCursor(value: string): DesktopSessionsCursor | undefined {
149
+ if (value.length === 0 || value.length > MAX_CURSOR_LENGTH || !/^[A-Za-z0-9_-]+$/.test(value)) return undefined;
150
+ try {
151
+ const parsed: unknown = JSON.parse(Buffer.from(value, "base64url").toString("utf8"));
152
+ if (!Array.isArray(parsed) || parsed.length !== 2) return undefined;
153
+ const [modified, id] = parsed;
154
+ if (typeof modified !== "number" || !Number.isFinite(modified) || modified < 0) return undefined;
155
+ if (typeof id !== "string" || id.length === 0 || id.length > MAX_ID_LENGTH) return undefined;
156
+ return { modified, id };
157
+ } catch {
158
+ return undefined;
159
+ }
160
+ }
161
+
162
+ /**
163
+ * One bounded page of the owner's list, newest first. The cursor is a keyset
164
+ * position (last time + id), so sessions created between pages never shift or
165
+ * repeat entries the client already has.
166
+ */
167
+ export function pageDesktopSessions(
168
+ infos: readonly DesktopSessionInfoLike[],
169
+ currentId: string,
170
+ params: DesktopListSessionsParams,
171
+ ): { sessions: DesktopSessionEntry[]; nextCursor?: string } {
172
+ const cursor = params.cursor;
173
+ const entries = infos
174
+ .map((info) => projectDesktopSession(info, currentId))
175
+ .filter((entry): entry is DesktopSessionEntry => entry !== undefined)
176
+ .sort(compareEntries)
177
+ .filter((entry) => cursor === undefined || isAfterCursor(entry, cursor));
178
+ const sessions = entries.slice(0, params.limit);
179
+ const last = sessions[sessions.length - 1];
180
+ if (entries.length > params.limit && last) {
181
+ return { sessions, nextCursor: encodeSessionsCursor({ modified: last.modified, id: last.id }) };
182
+ }
183
+ return { sessions };
184
+ }
185
+
186
+ /**
187
+ * `list_sessions` params: optional `scope` (`project` | `all`, default
188
+ * `project`), optional integer `limit` 1–50 (default 20), and an optional
189
+ * opaque `cursor`. Any other key or value is a typed `invalid_request` before
190
+ * any owner work happens.
191
+ */
192
+ export function parseListSessionsParams(params: Record<string, unknown>): DesktopListSessionsParams | ParamError {
193
+ for (const key of Object.keys(params)) {
194
+ if (key !== "scope" && key !== "limit" && key !== "cursor") return { error: INVALID_SESSIONS_PARAMS };
195
+ }
196
+ if (params.scope !== undefined && !isScope(params.scope)) return { error: INVALID_SESSIONS_PARAMS };
197
+ const limit = params.limit ?? DESKTOP_SESSIONS_DEFAULT_LIMIT;
198
+ if (typeof limit !== "number" || !Number.isInteger(limit) || limit < 1 || limit > DESKTOP_SESSIONS_MAX_LIMIT) {
199
+ return { error: INVALID_SESSIONS_PARAMS };
200
+ }
201
+ const parsed: DesktopListSessionsParams = { scope: (params.scope as DesktopSessionsScope | undefined) ?? "project", limit };
202
+ if (params.cursor !== undefined) {
203
+ if (typeof params.cursor !== "string") return { error: INVALID_SESSIONS_PARAMS };
204
+ const cursor = decodeSessionsCursor(params.cursor);
205
+ if (!cursor) return { error: INVALID_SESSIONS_PARAMS };
206
+ parsed.cursor = cursor;
207
+ }
208
+ return parsed;
209
+ }
210
+
211
+ /**
212
+ * `switch_session` params: a non-empty `id` plus an optional `scope` naming
213
+ * where the id is resolved (default `project`, the same scope `list_sessions`
214
+ * defaults to). A path-shaped request (`sessionPath`) or any other key is a
215
+ * typed `invalid_request`.
216
+ */
217
+ export function parseSwitchSessionParams(params: Record<string, unknown>): DesktopSwitchSessionParams | ParamError {
218
+ for (const key of Object.keys(params)) {
219
+ if (key !== "id" && key !== "scope") return { error: INVALID_SESSIONS_PARAMS };
220
+ }
221
+ if (typeof params.id !== "string" || params.id.length === 0 || params.id.length > MAX_ID_LENGTH) return { error: INVALID_SESSIONS_PARAMS };
222
+ if (params.scope !== undefined && !isScope(params.scope)) return { error: INVALID_SESSIONS_PARAMS };
223
+ return { id: params.id, scope: (params.scope as DesktopSessionsScope | undefined) ?? "project" };
224
+ }
225
+
226
+ /**
227
+ * A success response line in the router's exact shape. A switch replaces the
228
+ * session, which stops the old router before Pi returns; the replacement
229
+ * context publishes this line instead, correlated by the original requestId.
230
+ */
231
+ export function desktopSessionsResponseLine(requestId: string, data: Record<string, unknown>): string {
232
+ return JSON.stringify({ schema: DESKTOP_RPC_SCHEMA, kind: "response", requestId, ok: true, data });
233
+ }
234
+
235
+ /** A failure response line in the router's exact shape, for an instance whose router a switch already stopped. */
236
+ export function desktopSessionsErrorLine(requestId: string | null, error: { code: string; message: string }): string {
237
+ return JSON.stringify({ schema: DESKTOP_RPC_SCHEMA, kind: "response", requestId, ok: false, error: { code: error.code, message: error.message } });
238
+ }
239
+
240
+ /** The correlation id of a raw `/gentle:desktop` request, or `null` when it has none. */
241
+ export function desktopRequestId(raw: string): string | null {
242
+ try {
243
+ const value: unknown = JSON.parse(raw);
244
+ if (!value || typeof value !== "object" || Array.isArray(value)) return null;
245
+ const requestId = (value as Record<string, unknown>).requestId;
246
+ return typeof requestId === "string" && requestId.length > 0 && requestId.length <= 128 ? requestId : null;
247
+ } catch {
248
+ return null;
249
+ }
250
+ }
@@ -0,0 +1,187 @@
1
+ // Gentle Desktop usage-stats slice: the pure contract shared by the Desktop
2
+ // bridge (`lib/desktop-stats-service.ts`) and the owner seam inside
3
+ // `extensions/gentle-stats.ts`.
4
+ //
5
+ // Nothing here reads a session file. The owner (`/gentle:stats`, with its one
6
+ // size/mtime-cached loader) supplies the parsed session records; this module
7
+ // runs the exact `aggregateStats` aggregation the stats panel runs and
8
+ // projects its result into the safe, bounded Desktop shape. It is a
9
+ // projection, not a second loader, cache, or aggregation.
10
+
11
+ import { aggregateStats, STATS_RANGE, STATS_SCOPE, type SessionRecord, type StatsRange, type StatsScope } from "./stats-collector.ts";
12
+
13
+ export const DESKTOP_STATS_METHODS = ["get_usage_stats"] as const;
14
+ /** Usage stats are an explicit read: this slice advertises no event. */
15
+ export const DESKTOP_STATS_EVENTS = [] as const;
16
+
17
+ // The versioned owner-service discovery seam (the stats analogue of the jobs
18
+ // `gentle:desktop:jobs-service` adapter). The schema string guards the adapter
19
+ // against drift; the bridge ignores any responder whose shape does not match.
20
+ export const DESKTOP_STATS_SERVICE_SCHEMA = "gentle-pi.desktop-stats-service/v1";
21
+ export const DESKTOP_STATS_SERVICE_CHANNEL = "gentle:desktop:stats-service";
22
+
23
+ /** Upper bounds on each array one answer carries. */
24
+ export const DESKTOP_STATS_LIMITS = { models: 50, days: 400, projects: 50 } as const;
25
+ /** Longest model id or project name the wire carries; longer strings are cut. */
26
+ export const DESKTOP_STATS_NAME_LIMIT = 128;
27
+
28
+ export const INVALID_STATS_PARAMS = { code: "invalid_request", message: "Invalid usage stats parameters" } as const;
29
+ export const STATS_UNAVAILABLE = { code: "stats_unavailable", message: "Usage stats unavailable: no session history can be read" } as const;
30
+
31
+ const RANGES: readonly StatsRange[] = [STATS_RANGE.WEEK, STATS_RANGE.MONTH, STATS_RANGE.ALL];
32
+ const SCOPES: readonly StatsScope[] = [STATS_SCOPE.PROJECT, STATS_SCOPE.ALL];
33
+ const PARAM_KEYS = new Set(["range", "scope"]);
34
+ const UNKNOWN_PROJECT = "unknown";
35
+
36
+ export interface DesktopUsageStatsQuery {
37
+ range: StatsRange;
38
+ scope: StatsScope;
39
+ }
40
+
41
+ export interface DesktopUsageStatsTotals {
42
+ sessions: number;
43
+ messages: number;
44
+ inputTokens: number;
45
+ outputTokens: number;
46
+ cacheReadTokens: number;
47
+ cacheWriteTokens: number;
48
+ totalTokens: number;
49
+ cost: number;
50
+ }
51
+
52
+ export interface DesktopUsageStatsModel {
53
+ model: string;
54
+ messages: number;
55
+ tokens: number;
56
+ cost: number;
57
+ share: number;
58
+ }
59
+
60
+ export interface DesktopUsageStatsDay {
61
+ day: string;
62
+ tokens: number;
63
+ }
64
+
65
+ export interface DesktopUsageStatsProject {
66
+ name: string;
67
+ sessions: number;
68
+ messages: number;
69
+ tokens: number;
70
+ cost: number;
71
+ }
72
+
73
+ /** The `get_usage_stats` answer. `byProject` exists only for `scope: "all"`. */
74
+ export interface DesktopUsageStats {
75
+ range: StatsRange;
76
+ scope: StatsScope;
77
+ totals: DesktopUsageStatsTotals;
78
+ byModel: DesktopUsageStatsModel[];
79
+ byDay: DesktopUsageStatsDay[];
80
+ byProject?: DesktopUsageStatsProject[];
81
+ truncated: { byModel: boolean; byDay: boolean; byProject?: boolean };
82
+ }
83
+
84
+ /** One owner read: the parsed history from the owner's loader, or truthful absence. */
85
+ export type DesktopStatsOwnerRead =
86
+ | { kind: "ok"; sessions: readonly SessionRecord[]; now: number }
87
+ | { kind: "unavailable" };
88
+
89
+ /**
90
+ * The owner-service adapter the bridge discovers. After `dispose()` `read`
91
+ * answers `unavailable` rather than speaking for a replaced session.
92
+ */
93
+ export interface DesktopStatsService {
94
+ schema: typeof DESKTOP_STATS_SERVICE_SCHEMA;
95
+ read(): Promise<DesktopStatsOwnerRead>;
96
+ dispose(): void;
97
+ }
98
+
99
+ /**
100
+ * `get_usage_stats` params are an object with only optional `range` and
101
+ * `scope`, each one of the values `aggregateStats` supports. Anything else is
102
+ * a typed `invalid_request` before any owner work happens.
103
+ */
104
+ export function parseUsageStatsParams(params: Record<string, unknown>): DesktopUsageStatsQuery | { error: { code: string; message: string } } {
105
+ if (Object.keys(params).some((key) => !PARAM_KEYS.has(key))) return { error: INVALID_STATS_PARAMS };
106
+ // An omitted key takes its default; an explicit null or any other value must be valid.
107
+ const range = "range" in params ? params.range : STATS_RANGE.WEEK;
108
+ const scope = "scope" in params ? params.scope : STATS_SCOPE.PROJECT;
109
+ if (!RANGES.includes(range as StatsRange) || !SCOPES.includes(scope as StatsScope)) return { error: INVALID_STATS_PARAMS };
110
+ return { range: range as StatsRange, scope: scope as StatsScope };
111
+ }
112
+
113
+ /** True only for the adapter-shaped object the discovery responder must return. */
114
+ export function isDesktopStatsServiceShape(value: unknown): value is DesktopStatsService {
115
+ if (!value || typeof value !== "object") return false;
116
+ const adapter = value as Partial<DesktopStatsService>;
117
+ return adapter.schema === DESKTOP_STATS_SERVICE_SCHEMA && typeof adapter.read === "function" && typeof adapter.dispose === "function";
118
+ }
119
+
120
+ const boundedName = (value: string): string => (value.length > DESKTOP_STATS_NAME_LIMIT ? value.slice(0, DESKTOP_STATS_NAME_LIMIT) : value);
121
+
122
+ /** A project's display name: the last segment of its working directory, never the path. */
123
+ export function projectDisplayName(cwd: string): string {
124
+ const segments = cwd.split(/[\\/]+/).filter((segment) => segment.length > 0);
125
+ return boundedName(segments.at(-1) ?? UNKNOWN_PROJECT);
126
+ }
127
+
128
+ /**
129
+ * The `get_usage_stats` projection over the owner's parsed history. Totals,
130
+ * models, and days come from one `aggregateStats` call with the requested
131
+ * range and scope; for `scope: "all"` each project row is the same
132
+ * aggregation scoped to that project. Every field is rebuilt by name, so no
133
+ * session id, path, or message text can reach the wire. Arrays keep the
134
+ * largest models and projects and the most recent days within the bounds.
135
+ */
136
+ export function projectDesktopUsageStats(
137
+ sessions: readonly SessionRecord[],
138
+ query: DesktopUsageStatsQuery & { cwd: string | undefined; now: number },
139
+ ): DesktopUsageStats {
140
+ const summary = aggregateStats(sessions, { range: query.range, scope: query.scope, cwd: query.cwd, now: query.now });
141
+ const models = summary.models.map((model) => ({ model: boundedName(model.model), messages: model.messages, tokens: model.tokens, cost: model.cost, share: model.share }));
142
+ const days = Object.keys(summary.days).sort().map((day) => ({ day, tokens: summary.days[day]! }));
143
+ const stats: DesktopUsageStats = {
144
+ range: query.range,
145
+ scope: query.scope,
146
+ totals: {
147
+ sessions: summary.sessions,
148
+ messages: summary.models.reduce((sum, model) => sum + model.messages, 0),
149
+ inputTokens: summary.totals.input,
150
+ outputTokens: summary.totals.output,
151
+ cacheReadTokens: summary.totals.cacheRead,
152
+ cacheWriteTokens: summary.totals.cacheWrite,
153
+ totalTokens: summary.totals.total,
154
+ cost: summary.totals.cost,
155
+ },
156
+ byModel: models.slice(0, DESKTOP_STATS_LIMITS.models),
157
+ byDay: days.slice(Math.max(0, days.length - DESKTOP_STATS_LIMITS.days)),
158
+ truncated: { byModel: models.length > DESKTOP_STATS_LIMITS.models, byDay: days.length > DESKTOP_STATS_LIMITS.days },
159
+ };
160
+ if (query.scope === STATS_SCOPE.ALL) {
161
+ const projects = projectRows(sessions, query);
162
+ stats.byProject = projects.slice(0, DESKTOP_STATS_LIMITS.projects);
163
+ stats.truncated.byProject = projects.length > DESKTOP_STATS_LIMITS.projects;
164
+ }
165
+ return stats;
166
+ }
167
+
168
+ function projectRows(sessions: readonly SessionRecord[], query: DesktopUsageStatsQuery & { now: number }): DesktopUsageStatsProject[] {
169
+ const byCwd = new Map<string, SessionRecord[]>();
170
+ for (const session of sessions) byCwd.set(session.cwd, [...(byCwd.get(session.cwd) ?? []), session]);
171
+ const rows: Array<DesktopUsageStatsProject & { cwd: string }> = [];
172
+ for (const [cwd, group] of byCwd) {
173
+ const summary = aggregateStats(group, { range: query.range, scope: STATS_SCOPE.PROJECT, cwd, now: query.now });
174
+ if (summary.sessions === 0) continue;
175
+ rows.push({
176
+ cwd,
177
+ name: projectDisplayName(cwd),
178
+ sessions: summary.sessions,
179
+ messages: summary.models.reduce((sum, model) => sum + model.messages, 0),
180
+ tokens: summary.totals.total,
181
+ cost: summary.totals.cost,
182
+ });
183
+ }
184
+ // Largest first; the private cwd only breaks a full tie and never leaves here.
185
+ rows.sort((a, b) => b.tokens - a.tokens || b.messages - a.messages || a.name.localeCompare(b.name) || a.cwd.localeCompare(b.cwd));
186
+ return rows.map(({ name, sessions: count, messages, tokens, cost }) => ({ name, sessions: count, messages, tokens, cost }));
187
+ }