@pi-chamber/web 0.7.2 → 0.8.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 (178) hide show
  1. package/README.md +1 -1
  2. package/dist/assets/{DiagramEditor-TeJ1G_NN.js → DiagramEditor-YPSKccgo.js} +1 -1
  3. package/dist/assets/DiagramView-C-PbBHce.js +1 -0
  4. package/dist/assets/DiffView-DfltyfN2.js +18 -0
  5. package/dist/assets/FilesView-BEjbLiK2.js +6 -0
  6. package/dist/assets/GitView-B_zTaXX4.js +8 -0
  7. package/dist/assets/JsonTreeView-9p4txyB_.js +1 -0
  8. package/dist/assets/MarkdownRendererImpl-CbRPLK2x.js +12 -0
  9. package/dist/assets/PatchDiff-rKjeUBRl.js +1 -0
  10. package/dist/assets/SessionSwitcherContent-C_VxKFJy.js +1 -0
  11. package/dist/assets/SessionSwitcherDropdown-_k4P32o9.js +2 -0
  12. package/dist/assets/SessionUnreadDot-bT_0MixU.js +1 -0
  13. package/dist/assets/SettingsView-CqZ1ZAWG.js +2 -0
  14. package/dist/assets/SettingsWindow-C7vVE35-.js +1 -0
  15. package/dist/assets/ToolOutputDialog-GBbzATa6.js +8 -0
  16. package/dist/assets/ToolPartDiffPreview-Bdb9p5uS.js +1 -0
  17. package/dist/assets/{VirtualizedFileDiff-sRc4lN0B.js → VirtualizedFileDiff-CA8hQyz9.js} +4 -4
  18. package/dist/assets/{Virtualizer-BxW2CJGB.js → Virtualizer-BSHVMKgK.js} +1 -1
  19. package/dist/assets/{appThemeRegistry-BK0dHKa6.js → appThemeRegistry-gegrE2dq.js} +1 -1
  20. package/dist/assets/collapsible-uwSKBy-K.js +1 -0
  21. package/dist/assets/computeVirtualFileMetrics-9LNCLvAG.js +3 -0
  22. package/dist/assets/contextFileOpenGuard-CZSqdEHk.js +1 -0
  23. package/dist/assets/gitStatusPredicates-CRmbLl-x.js +134 -0
  24. package/dist/assets/index-BeJEipxi.js +1 -0
  25. package/dist/assets/index-CaP8oFLB.js +8 -0
  26. package/dist/assets/index-Dq8CnRYM.css +1 -0
  27. package/dist/assets/isDiffPlainText-YYyZNTdb.js +1 -0
  28. package/dist/assets/isFilePlainText-C70Z71bG.js +1 -0
  29. package/dist/assets/main-CsdVAKy_.js +135 -0
  30. package/dist/assets/main-GMQIZjuQ.js +2 -0
  31. package/dist/assets/{markdownCore-BfuFM7mg.js → markdownCore-BgVcDt0q.js} +2 -2
  32. package/dist/assets/miniChat-W6YsdiWR.js +2 -0
  33. package/dist/assets/mobile-BFR9CR5w.js +2 -0
  34. package/dist/assets/{permissionStore-BRcQ9Jgt.js → permissionStore-iKN1K2_x.js} +1 -1
  35. package/dist/assets/registerCustomTheme-DmolaWWZ.js +1 -0
  36. package/dist/assets/renderElectronMiniChatApp-B8ZiW-3E.js +2 -0
  37. package/dist/assets/renderMobileApp-C5CdsYP6.js +11 -0
  38. package/dist/assets/runtimeEndpointReset-D3AZYuoF.js +54 -0
  39. package/dist/assets/{runtimeSurface-DF3VwUlO.js → runtimeSurface-B818u-_c.js} +1 -1
  40. package/dist/assets/themeResolver-yJ9XpNMI.js +1 -0
  41. package/dist/assets/{WindowsWindowControls-CCnU0ckO.js → useAppFontEffects-CYzYRbLp.js} +126 -499
  42. package/dist/assets/useFilesViewSearch-C--GWtn-.js +7 -0
  43. package/dist/assets/usePushVisibilityBeacon-D9lajdAc.js +10 -0
  44. package/dist/assets/useSwitcherItems-DOoi3x_8.js +1 -0
  45. package/dist/assets/vendor-base-ui-vkqQ2P9o.js +1 -0
  46. package/dist/assets/{vendor-beautiful-mermaid-r4GK_usS.js → vendor-beautiful-mermaid-DneUawHp.js} +1 -1
  47. package/dist/assets/{vendor-cmdk-BCEUzcHE.js → vendor-cmdk-zXx6sGnS.js} +1 -1
  48. package/dist/assets/{vendor-codemirror-autocomplete-BS2SpSAZ.js → vendor-codemirror-autocomplete-wd6iRebq.js} +1 -1
  49. package/dist/assets/{vendor-codemirror-commands-RrgJ8H_6.js → vendor-codemirror-commands-DYppkHEk.js} +1 -1
  50. package/dist/assets/{vendor-codemirror-lang-angular-ADhO_TUK.js → vendor-codemirror-lang-angular-DU_4KiiW.js} +1 -1
  51. package/dist/assets/{vendor-codemirror-lang-cpp-BGCWj7Om.js → vendor-codemirror-lang-cpp-CmIT9Z5_.js} +1 -1
  52. package/dist/assets/{vendor-codemirror-lang-css-Ba8JZ6fp.js → vendor-codemirror-lang-css-djiuoTi8.js} +1 -1
  53. package/dist/assets/{vendor-codemirror-lang-go-DyTiHXo4.js → vendor-codemirror-lang-go-COZSwZYW.js} +1 -1
  54. package/dist/assets/{vendor-codemirror-lang-html-DK27qQri.js → vendor-codemirror-lang-html-CKHqhW5R.js} +1 -1
  55. package/dist/assets/{vendor-codemirror-lang-java-CvFfnhPQ.js → vendor-codemirror-lang-java-CNMP5hyC.js} +1 -1
  56. package/dist/assets/{vendor-codemirror-lang-javascript-BUlYhQ3o.js → vendor-codemirror-lang-javascript-DuOEwJ3f.js} +1 -1
  57. package/dist/assets/{vendor-codemirror-lang-jinja-wBMtAEvT.js → vendor-codemirror-lang-jinja-DaKn_b1k.js} +1 -1
  58. package/dist/assets/{vendor-codemirror-lang-json-CqayksDf.js → vendor-codemirror-lang-json-CZ07HmNC.js} +1 -1
  59. package/dist/assets/{vendor-codemirror-lang-less-Ct3-H1PB.js → vendor-codemirror-lang-less-wJdQiDBf.js} +1 -1
  60. package/dist/assets/{vendor-codemirror-lang-liquid-XspREksq.js → vendor-codemirror-lang-liquid-0z48Roi8.js} +1 -1
  61. package/dist/assets/{vendor-codemirror-lang-markdown-CvO36Y1p.js → vendor-codemirror-lang-markdown-DtcZDGqe.js} +1 -1
  62. package/dist/assets/{vendor-codemirror-lang-php-BlUF9cCe.js → vendor-codemirror-lang-php-W8plS-JQ.js} +1 -1
  63. package/dist/assets/{vendor-codemirror-lang-python-_2bIYTiJ.js → vendor-codemirror-lang-python-DzzokVau.js} +1 -1
  64. package/dist/assets/{vendor-codemirror-lang-rust-BdTYih_U.js → vendor-codemirror-lang-rust-C4ulBVpf.js} +1 -1
  65. package/dist/assets/{vendor-codemirror-lang-sass-E6MhfOFk.js → vendor-codemirror-lang-sass-BkZJYEwS.js} +1 -1
  66. package/dist/assets/{vendor-codemirror-lang-sql-B1BRhQSF.js → vendor-codemirror-lang-sql-HpQWHJjv.js} +1 -1
  67. package/dist/assets/{vendor-codemirror-lang-vue-BYQJRa1Q.js → vendor-codemirror-lang-vue-DiBPljCc.js} +1 -1
  68. package/dist/assets/{vendor-codemirror-lang-wast-D706yuyC.js → vendor-codemirror-lang-wast-DoABsogh.js} +1 -1
  69. package/dist/assets/{vendor-codemirror-lang-xml--MfWU6Dj.js → vendor-codemirror-lang-xml-BhLJhOCH.js} +1 -1
  70. package/dist/assets/{vendor-codemirror-lang-yaml-CRUFIbRX.js → vendor-codemirror-lang-yaml-D95i1Y5R.js} +1 -1
  71. package/dist/assets/{vendor-codemirror-language-E2vgV9K3.js → vendor-codemirror-language-BByA_dGF.js} +2 -2
  72. package/dist/assets/{vendor-codemirror-language-data-C7_BPMCr.js → vendor-codemirror-language-data-DS_4W5G4.js} +2 -2
  73. package/dist/assets/{vendor-codemirror-search-8kyQdB3f.js → vendor-codemirror-search-BV44140v.js} +1 -1
  74. package/dist/assets/{vendor-codemirror-view-DSzLbZiS.js → vendor-codemirror-view-Ct4T37Ue.js} +1 -1
  75. package/dist/assets/{vendor-dnd-kit-accessibility-Cv52zwWT.js → vendor-dnd-kit-accessibility-DZKKhs9S.js} +1 -1
  76. package/dist/assets/{vendor-dnd-kit-core-GipZW2tY.js → vendor-dnd-kit-core-CP8ck10N.js} +1 -1
  77. package/dist/assets/{vendor-dnd-kit-sortable-Ct2QxIHb.js → vendor-dnd-kit-sortable-B-Icjoj4.js} +1 -1
  78. package/dist/assets/{vendor-dnd-kit-utilities-CrOcp0Bp.js → vendor-dnd-kit-utilities-DTY1C6ST.js} +1 -1
  79. package/dist/assets/{vendor-elkjs-CRCLNXjf.js → vendor-elkjs-mzfkf0ML.js} +1 -1
  80. package/dist/assets/{vendor-floating-ui-dom-Bkw82kL9.js → vendor-floating-ui-dom-WyXykhNi.js} +1 -1
  81. package/dist/assets/{vendor-floating-ui-react-dom-sVFnuruh.js → vendor-floating-ui-react-dom-BZOGXAGe.js} +1 -1
  82. package/dist/assets/{vendor-framer-motion-DJASDzNt.js → vendor-framer-motion-BUygY0oN.js} +1 -1
  83. package/dist/assets/{vendor-heic2any-L8hyfc24.js → vendor-heic2any-BHsbokcA.js} +1 -1
  84. package/dist/assets/{vendor-lru_map-B-cPXHXW.js → vendor-lru_map-Cy8fTs3_.js} +1 -1
  85. package/dist/assets/{vendor-pierre-theming-C6Z4M5_u.js → vendor-pierre-theming-Dgp7B_O4.js} +1 -1
  86. package/dist/assets/{vendor-qrcode-COsmt6jn.js → vendor-qrcode-B0KNSajT.js} +1 -1
  87. package/dist/assets/{vendor-radix-ui-react-compose-refs-D1GnwnP9.js → vendor-radix-ui-react-compose-refs-8xy6TJML.js} +1 -1
  88. package/dist/assets/{vendor-radix-ui-react-context-CM4yFQ2I.js → vendor-radix-ui-react-context-CFsX-AUC.js} +1 -1
  89. package/dist/assets/{vendor-radix-ui-react-dialog-jX3Dld8c.js → vendor-radix-ui-react-dialog-D2yhEu2p.js} +1 -1
  90. package/dist/assets/{vendor-radix-ui-react-dismissable-layer-M7LsH3yL.js → vendor-radix-ui-react-dismissable-layer-DrorBNg9.js} +1 -1
  91. package/dist/assets/{vendor-radix-ui-react-focus-guards-D5MZ0nQs.js → vendor-radix-ui-react-focus-guards-BfdFmL7c.js} +1 -1
  92. package/dist/assets/{vendor-radix-ui-react-focus-scope-C2K7lNPv.js → vendor-radix-ui-react-focus-scope-D2BkImwt.js} +1 -1
  93. package/dist/assets/{vendor-radix-ui-react-id-BcxRjnbX.js → vendor-radix-ui-react-id-D2kS9K1j.js} +1 -1
  94. package/dist/assets/vendor-radix-ui-react-portal-YgCRIyi7.js +1 -0
  95. package/dist/assets/{vendor-radix-ui-react-presence-Btn-Dp7L.js → vendor-radix-ui-react-presence-D432pCMB.js} +1 -1
  96. package/dist/assets/{vendor-radix-ui-react-primitive-CfpW6_IT.js → vendor-radix-ui-react-primitive-DkH8dMOR.js} +1 -1
  97. package/dist/assets/{vendor-radix-ui-react-slot-BxUc3Pvz.js → vendor-radix-ui-react-slot-BIDFZX0-.js} +1 -1
  98. package/dist/assets/{vendor-radix-ui-react-use-callback-ref-UKEWHtoP.js → vendor-radix-ui-react-use-callback-ref-BwDcSoGV.js} +1 -1
  99. package/dist/assets/{vendor-radix-ui-react-use-controllable-state-C_ecoh35.js → vendor-radix-ui-react-use-controllable-state-LiqmKSXO.js} +1 -1
  100. package/dist/assets/vendor-radix-ui-react-use-effect-event-D94va83M.js +1 -0
  101. package/dist/assets/{vendor-radix-ui-react-use-escape-keydown-Co13lHGj.js → vendor-radix-ui-react-use-escape-keydown-DTkqjenV.js} +1 -1
  102. package/dist/assets/vendor-radix-ui-react-use-layout-effect-C8Yrsaph.js +1 -0
  103. package/dist/assets/{vendor-react-DYyjh7Q0.js → vendor-react-B5Z1Mdn3.js} +1 -1
  104. package/dist/assets/{vendor-react-drawio-Boqanm0j.js → vendor-react-drawio-BYDptOsj.js} +1 -1
  105. package/dist/assets/{vendor-react-remove-scroll-bar-C9YRs2nU.js → vendor-react-remove-scroll-bar-CSAHp1YF.js} +1 -1
  106. package/dist/assets/{vendor-react-remove-scroll-CfeMe0DL.js → vendor-react-remove-scroll-vR1dy1aP.js} +1 -1
  107. package/dist/assets/{vendor-react-style-singleton-B1H4bWSG.js → vendor-react-style-singleton-Ctw6HnYx.js} +1 -1
  108. package/dist/assets/{vendor-replit-codemirror-vim-BJY5fGLS.js → vendor-replit-codemirror-vim-CGHHNQxC.js} +1 -1
  109. package/dist/assets/{vendor-sonner-CW8w438f.js → vendor-sonner-BDtm25td.js} +1 -1
  110. package/dist/assets/{vendor-tanstack-react-virtual-IrbCBGJ4.js → vendor-tanstack-react-virtual-2skouoFw.js} +1 -1
  111. package/dist/assets/{vendor-use-callback-ref-CJB0R85I.js → vendor-use-callback-ref-CVVuCyLj.js} +1 -1
  112. package/dist/assets/{vendor-use-sidecar-C-AuTczP.js → vendor-use-sidecar-Vv4V8Nd1.js} +1 -1
  113. package/dist/assets/{vendor-use-sync-external-store-B7OScDIw.js → vendor-use-sync-external-store-D0AXkdQC.js} +1 -1
  114. package/dist/assets/{vendor-zustand-CnsBKjP5.js → vendor-zustand-GVb4H8HE.js} +1 -1
  115. package/dist/assets/{web-components-BYNCGylQ.js → web-components-C2cMNPqE.js} +2 -2
  116. package/dist/index.html +6 -6
  117. package/dist/mini-chat.html +5 -5
  118. package/dist/mobile.html +5 -5
  119. package/package.json +1 -1
  120. package/server/lib/git/DOCUMENTATION.md +3 -2
  121. package/server/lib/git/routes.js +27 -0
  122. package/server/lib/git/routes.test.js +41 -0
  123. package/server/lib/git/service.js +7 -1
  124. package/server/lib/git/service.test.js +23 -0
  125. package/server/lib/pi/routes.js +263 -6
  126. package/server/lib/pi/routes.test.js +314 -1
  127. package/server/lib/pi/session-daemon/DOCUMENTATION.md +2 -2
  128. package/server/lib/pi/session-daemon/prompt-operations.test.js +318 -0
  129. package/server/lib/pi/session-daemon/session-daemon.js +309 -25
  130. package/server/lib/pi/session-daemon/session-daemon.test.js +137 -0
  131. package/server/lib/pi/session-daemon/supervisor.test.js +1 -1
  132. package/server/lib/pi/snippets-store.js +400 -0
  133. package/server/lib/pi/snippets-store.test.js +252 -0
  134. package/server/lib/relay/host-client.test.js +79 -15
  135. package/server/lib/server/cors.js +2 -0
  136. package/server/lib/server/cors.test.js +6 -5
  137. package/dist/assets/CommitSection-DfAlM30E.js +0 -1
  138. package/dist/assets/DiagramView-DKLIwNth.js +0 -1
  139. package/dist/assets/DiffView-CZyqSs5W.js +0 -18
  140. package/dist/assets/FilesView-rftA7fEL.js +0 -14
  141. package/dist/assets/GitView-D5LMTT2M.js +0 -6
  142. package/dist/assets/JsonTreeView-DMI3-Smy.js +0 -1
  143. package/dist/assets/MarkdownRendererImpl-gdd-5n9J.js +0 -12
  144. package/dist/assets/PatchDiff-GNB1NlAN.js +0 -1
  145. package/dist/assets/PierreDiffViewer-DmJv2AoJ.js +0 -136
  146. package/dist/assets/SessionSwitcherContent-CWdDPll7.js +0 -1
  147. package/dist/assets/SessionSwitcherDropdown-Cx-Jfmvo.js +0 -2
  148. package/dist/assets/SessionUnreadDot-CKe4uVcf.js +0 -1
  149. package/dist/assets/SettingsView-DaxkNy5C.js +0 -4
  150. package/dist/assets/SettingsWindow-D1M_rRDo.js +0 -1
  151. package/dist/assets/ToolOutputDialog-CUKcp77A.js +0 -15
  152. package/dist/assets/ToolPartDiffPreview-CkzwXAC5.js +0 -8
  153. package/dist/assets/collapsible-B0cIItyf.js +0 -1
  154. package/dist/assets/computeVirtualFileMetrics-B1uVA58l.js +0 -3
  155. package/dist/assets/contextFileOpenGuard-BuedQ5EQ.js +0 -1
  156. package/dist/assets/index-BA67uOfZ.js +0 -1
  157. package/dist/assets/index-CcbDTf8Q.js +0 -8
  158. package/dist/assets/index-Cl3XbCeC.css +0 -1
  159. package/dist/assets/isDiffPlainText-DLDFLL6P.js +0 -1
  160. package/dist/assets/isFilePlainText-B2wwrpRU.js +0 -1
  161. package/dist/assets/main-B5k0qpHJ.js +0 -133
  162. package/dist/assets/main-Bepu8Jr9.js +0 -2
  163. package/dist/assets/miniChat-Co0Snpgl.js +0 -2
  164. package/dist/assets/mobile-CSvL_Zyu.js +0 -2
  165. package/dist/assets/registerCustomTheme-BBXUCRnG.js +0 -1
  166. package/dist/assets/renderElectronMiniChatApp-DrMJ1RXX.js +0 -2
  167. package/dist/assets/renderMobileApp-B2toAnMW.js +0 -14
  168. package/dist/assets/themeResolver-BmJyTmjJ.js +0 -1
  169. package/dist/assets/useInlineCommentController-CxMP78jg.js +0 -2
  170. package/dist/assets/usePanelSlide-DUuoQt5X.js +0 -56
  171. package/dist/assets/usePushVisibilityBeacon-CSPdFBaA.js +0 -10
  172. package/dist/assets/useSwitcherItems-zOeC2Cta.js +0 -1
  173. package/dist/assets/vendor-base-ui-DL8r2fgQ.js +0 -1
  174. package/dist/assets/vendor-radix-ui-react-portal-xlJWBfDg.js +0 -1
  175. package/dist/assets/vendor-radix-ui-react-use-effect-event-DkJl_Rn_.js +0 -1
  176. package/dist/assets/vendor-radix-ui-react-use-layout-effect-0fyGwS2_.js +0 -1
  177. package/dist/assets/vendor-remixicon-react-CzPq62YO.js +0 -1
  178. /package/dist/assets/{usePanelSlide-BV3KOtdA.css → runtimeEndpointReset-BV3KOtdA.css} +0 -0
@@ -28,10 +28,10 @@ This module is the Pi-owned session-daemon foundation. A detached local daemon p
28
28
  - The public health route deliberately whitelists its response fields. It never returns a daemon endpoint, credential, PID, cwd, agent directory, or transcript data. Public transcript and event projections preserve daemon-redacted assistant error messages so the UI can distinguish provider/runtime failures instead of reducing every failure to `ASSISTANT_ERROR`.
29
29
  - A client must send an `authenticate` frame carrying the host-private daemon credential before it can issue a request. Credentials are never logged or returned.
30
30
  - Frames are LF-delimited JSON. They have a 1 MiB maximum buffered size. A malformed, oversized, unauthenticated, or invalid request closes the connection.
31
- - The private core commands are `runtime.health`, `projects.list/select`, `providers.list/config.get/models.set/status/login/login.respond/login.status/logout`, `settings.get/set`, `resources.list/update/prompts.create/prompts.delete`, `extensions.list/respond`, and session list/create/open/rename/delete/tree/navigate/fork/clone/prompt/steer/followUp/abort/model/thinking/compact operations. Resource lists use opaque IDs and never disclose server paths. Only top-level Pi prompt templates and applicable AGENTS.md sources are editable; package/path resources and skills are browse-only. Resource writes are rejected while a session streams, use an atomic replace, then recreate the idle runtime. Project trust changes are persisted in Pi trust.json and likewise recreate an idle runtime; project-local extensions load through Pi's own trust flow once trust is resolved. Provider login submits API keys only across authenticated private IPC or brokers Pi's OAuth/device/manual-code interaction; public projections contain only opaque login IDs, prompts, URLs/device codes, model catalog/configuration, and stable states, never credentials or write-only headers. `providers.models.set` is rejected while a session streams, atomically persists Pi's `models.json`, then rehydrates the idle runtime so the catalog is authoritative immediately. `providers.list` projects only catalog and authentication-status metadata, including Pi-supported `thinkingLevels` (`null` map entries hidden, `xhigh`/`max` opt-in). Session thinking overrides are clamped to the live model's supported levels. `sessions.list` checks each cwd JSONL header (not the full transcript) so a project with large session logs cannot spend tens of seconds on startup. SDK `SessionManager.list` is not used for that path; `listPiSessionJsonlDirectory` reads a header, a bounded prefix for the first user prompt, and a tail for the latest rename. Concurrent lists of the same directory share one in-flight result. Concurrent `sessions.open` of the same id share one in-flight runtime create; a duplicate that finishes later disposes itself and returns the registered runtime instead of `SESSION_RUNTIME_CONFLICT`. Full-file JSONL validation stays on open of a chosen session. The browser explicitly selects an existing user-chosen project directory before listing it; the daemon's startup cwd is an internal fallback, not a user-visible default project. Unnamed persisted sessions use their first prompt as a readable list title when available. `sessions.open` and `getSession` project the last assistant `provider`/`model`/`thinkingLevel` onto the session record so reopening a chat keeps that cache identity. Session selection validates a persisted JSONL path before Pi opens it; inactive mutations are never directed by a browser-supplied path. `sessions.open` first checks a caller-supplied directory through its bounded header list, so an ordinary project-scoped open neither walks every directory in the agent store nor adopts a same-id session from another directory. Directory-less deep links resolve by Pi's `timestamp_<id>.jsonl` filename before broader SDK-list and header-scan fallbacks. Directory-wide JSONL checks on list/create/startup are header-only; full-file validation stays on open of a chosen transcript. Attachment paths originate in the server-local upload map and cross only private IPC into Pi's tool context. Pi may persist or echo those paths in its authoritative JSONL transcript, so every public projection redacts them recursively: session titles/previews, user and assistant text/thinking, tool arguments, errors, snapshots, and live message events never expose the server-local path. Persisted projection first checks for the attachment marker, then redacts matching tokens with a delimiter scan whose work stays linear for large encoded strings and tool payloads. The daemon maps Pi message lifecycle, deltas, tools, queue changes, model/thinking, compaction, interruption state, and session title updates (`session.updated` on create-with-title, first-prompt auto-title, and rename) to canonical events. Pi `model_select`, `thinking_level_changed`, and `session_info_changed` events are authoritative for model, thinking, and session-name changes made by extensions, the TUI, or another client. The bridge observes Pi provider registration and label writes because Pi 0.84.1 emits no corresponding session events: provider mutations publish a catalog invalidation, and label mutations invalidate the bounded session-tree projection. `ctx.reload()` clears old extension UI state, reloads Pi resources, and invalidates provider/resource/command catalogs. `ctx.shutdown()` disposes only the requesting idle session runtime after its command or turn settles; it never stops the shared daemon or unrelated sessions. Compaction events preserve Pi's manual/threshold/overflow reason, active/retrying/terminal phase, retry timing, redacted failure, compact-and-retry intent, and pre/post token estimates. The latest state is included in `getSession` and reconnect snapshots; after daemon restart, the latest persisted Pi `CompactionEntry` restores completed feedback without treating history as live work. Tool events carry redacted input arguments, cumulative partial-output snapshots, final output, error text, renderer metadata (edit diffs, truncation notes), and start/end timestamps. Pi loads skills with the ordinary `read` tool. The daemon matches those read paths against the active runtime's authoritative `resourceLoader.getSkills()` catalog and adds path-free `metadata.pichamber.skill.name` for live events, hydrated history, and reconnect snapshots. PiChamber uses that metadata for its compact Skill row and Settings navigation; an arbitrary file named `SKILL.md` remains a normal read. Persisted `toolResult` entries merge into their assistant `toolCall` parts as output/error/end time so hydrated sessions render complete tool cards; tool-result entries never surface as standalone messages. Assistant message projections and start events carry the owning user-message id so the restored turn renderer can group and display replies; all assistant entries in a tool loop and every retry/compaction continuation remain attached to the latest user turn until `agent_settled` closes the run. Assistant message projections also pass through Pi's per-turn `Usage` (input, output, cacheRead, cacheWrite, totalTokens, and the same five numeric cost fields). The daemon sanitizes the raw payload through `projectUsage` before publication: every numeric must be finite and non-negative, the whole object is omitted when any field is missing or wrong type, and unknown keys are never copied. The `assistant.message.end` event carries the same sanitized usage so the last turn updates without waiting for a full `getSession` refetch. The public route whitelist re-applies the same sanitizer on each projection so a stale or malformed payload from a different daemon version cannot surface as `NaN` or `Infinity` in the reducer.
31
+ - The private core commands are `runtime.health`, `projects.list/select`, `providers.list/config.get/models.set/status/login/login.respond/login.status/logout`, `settings.get/set`, `resources.list/update/prompts.create/prompts.update/prompts.delete`, `extensions.list/respond`, and session list/create/open/rename/delete/tree/navigate/fork/clone/prompt/steer/followUp/abort/model/thinking/compact operations. Resource lists use opaque IDs and never disclose server paths. Only top-level Pi prompt templates and applicable AGENTS.md sources are editable; package/path resources and skills are browse-only. Prompt-template mutations resolve against the caller's explicit effective directory, reject stale and cross-directory opaque IDs, enforce project trust for project prompts, are rejected while a session streams, serialize create/update/delete operations, preserve existing files on validation or write failure, atomically reserve new destinations without overwriting concurrent writers, use temporary-file persistence with cleanup, preserve unknown frontmatter fields (for example `argument-hint`) when editing description or content, and for rename validate the destination name and scope, reject collisions, write the destination atomically, remove the source only after success, roll back the destination when source removal fails, then recreate the idle runtime and clear the service cache so `/api/pi/commands` reflects the change. Resource writes are rejected while a session streams, use an atomic replace, then recreate the idle runtime. Project trust changes are persisted in Pi trust.json and likewise recreate an idle runtime; project-local extensions load through Pi's own trust flow once trust is resolved. Provider login submits API keys only across authenticated private IPC or brokers Pi's OAuth/device/manual-code interaction; public projections contain only opaque login IDs, prompts, URLs/device codes, model catalog/configuration, and stable states, never credentials or write-only headers. `providers.models.set` is rejected while a session streams, atomically persists Pi's `models.json`, then rehydrates the idle runtime so the catalog is authoritative immediately. `providers.list` projects only catalog and authentication-status metadata, including Pi-supported `thinkingLevels` (`null` map entries hidden, `xhigh`/`max` opt-in). Session thinking overrides are clamped to the live model's supported levels. `sessions.list` checks each cwd JSONL header (not the full transcript) so a project with large session logs cannot spend tens of seconds on startup. SDK `SessionManager.list` is not used for that path; `listPiSessionJsonlDirectory` reads a header, a bounded prefix for the first user prompt, and a tail for the latest rename. Concurrent lists of the same directory share one in-flight result. Concurrent `sessions.open` of the same id share one in-flight runtime create; a duplicate that finishes later disposes itself and returns the registered runtime instead of `SESSION_RUNTIME_CONFLICT`. Full-file JSONL validation stays on open of a chosen session. The browser explicitly selects an existing user-chosen project directory before listing it; the daemon's startup cwd is an internal fallback, not a user-visible default project. Unnamed persisted sessions use their first prompt as a readable list title when available. `sessions.open` and `getSession` project the last assistant `provider`/`model`/`thinkingLevel` onto the session record so reopening a chat keeps that cache identity. Session selection validates a persisted JSONL path before Pi opens it; inactive mutations are never directed by a browser-supplied path. `sessions.open` first checks a caller-supplied directory through its bounded header list, so an ordinary project-scoped open neither walks every directory in the agent store nor adopts a same-id session from another directory. Directory-less deep links resolve by Pi's `timestamp_<id>.jsonl` filename before broader SDK-list and header-scan fallbacks. Directory-wide JSONL checks on list/create/startup are header-only; full-file validation stays on open of a chosen transcript. Attachment paths originate in the server-local upload map and cross only private IPC into Pi's tool context. Pi may persist or echo those paths in its authoritative JSONL transcript, so every public projection redacts them recursively: session titles/previews, user and assistant text/thinking, tool arguments, errors, snapshots, and live message events never expose the server-local path. Persisted projection first checks for the attachment marker, then redacts matching tokens with a delimiter scan whose work stays linear for large encoded strings and tool payloads. The daemon maps Pi message lifecycle, deltas, tools, queue changes, model/thinking, compaction, interruption state, and session title updates (`session.updated` on create-with-title, first-prompt auto-title, and rename) to canonical events. Pi `model_select`, `thinking_level_changed`, and `session_info_changed` events are authoritative for model, thinking, and session-name changes made by extensions, the TUI, or another client. The bridge observes Pi provider registration and label writes because Pi 0.84.1 emits no corresponding session events: provider mutations publish a catalog invalidation, and label mutations invalidate the bounded session-tree projection. `ctx.reload()` clears old extension UI state, reloads Pi resources, and invalidates provider/resource/command catalogs. `ctx.shutdown()` disposes only the requesting idle session runtime after its command or turn settles; it never stops the shared daemon or unrelated sessions. Compaction events preserve Pi's manual/threshold/overflow reason, active/retrying/terminal phase, retry timing, redacted failure, compact-and-retry intent, and pre/post token estimates. The latest state is included in `getSession` and reconnect snapshots; after daemon restart, the latest persisted Pi `CompactionEntry` restores completed feedback without treating history as live work. Tool events carry redacted input arguments, cumulative partial-output snapshots, final output, error text, renderer metadata (edit diffs, truncation notes), and start/end timestamps. Pi loads skills with the ordinary `read` tool. The daemon matches those read paths against the active runtime's authoritative `resourceLoader.getSkills()` catalog and adds path-free `metadata.pichamber.skill.name` for live events, hydrated history, and reconnect snapshots. PiChamber uses that metadata for its compact Skill row and Settings navigation; an arbitrary file named `SKILL.md` remains a normal read. Persisted `toolResult` entries merge into their assistant `toolCall` parts as output/error/end time so hydrated sessions render complete tool cards; tool-result entries never surface as standalone messages. Assistant message projections and start events carry the owning user-message id so the restored turn renderer can group and display replies; all assistant entries in a tool loop and every retry/compaction continuation remain attached to the latest user turn until `agent_settled` closes the run. Assistant message projections also pass through Pi's per-turn `Usage` (input, output, cacheRead, cacheWrite, totalTokens, and the same five numeric cost fields). The daemon sanitizes the raw payload through `projectUsage` before publication: every numeric must be finite and non-negative, the whole object is omitted when any field is missing or wrong type, and unknown keys are never copied. The `assistant.message.end` event carries the same sanitized usage so the last turn updates without waiting for a full `getSession` refetch. The public route whitelist re-applies the same sanitizer on each projection so a stale or malformed payload from a different daemon version cannot surface as `NaN` or `Infinity` in the reducer.
32
32
  - Live `message_start` events use daemon-generated browser message IDs because Pi has not appended the corresponding session entry yet. Pi agent-core emits streaming assistant starts as shallow copies, not as the finalized object it later persists. At `message_end`, `message-entry-aliases.js` therefore rebinds the synthetic ID to the finalized event object, then maps that object by identity to Pi's appended entry in a microtask. `sessions.navigate` and `sessions.fork` resolve the mapping after stripping any part suffix. Alias keys include cwd and session ID, survive idle runtime disposal, and clear only on explicit session deletion or daemon shutdown. Hydrated message projections continue to use the Pi entry ID directly.
33
33
  - Each event and reconnect snapshot has a monotonic sequence. A reconnect receives a bounded contiguous replay after its cursor when available, otherwise an authoritative `session.snapshot`; unavailable runtimes are not represented as empty sessions.
34
- - Prompt, steer, and follow-up requests acknowledge acceptance immediately after Pi accepts the call; the daemon owns the still-running send promise and publishes any asynchronous rejection as `session.error`. An extension command may resolve without starting an agent turn, so completion of its non-streaming prompt promise publishes the idle lifecycle boundary that Pi does not emit as `agent_settled`. Manual compact requests likewise acknowledge startup instead of holding the public/private request open for the summarization call; the daemon-owned promise reports its outcome through `session.compaction`. A second compact request while Pi is compacting fails as `SESSION_BUSY`, and optional `/compact` instructions pass to `AgentSession.compact(customInstructions)`. A later prompt on the same session invalidates an older send rejection so it cannot error the new turn. If the rejected send left Pi streaming, the daemon aborts it. Steer/follow-up against an idle session starts a new prompt instead of `SESSION_NOT_RUNNING`. Agent and compaction completion are never held behind the 30-second public/private request budgets. Pi retryable provider failures remain live: an `agent_end` with `willRetry` does not publish terminal `session.error`, and `auto_retry_start` projects Pi's attempt, next-attempt time, and redacted error text through `session.lifecycle: retry`. Retry metadata is retained in reconnect and `getSession` snapshots until the next `agent_start` begins the attempt. `agent_settled` remains the authoritative idle boundary after retry success, exhaustion, or cancellation and clears the run's user/assistant ownership.
34
+ - Prompt, steer, and follow-up requests acknowledge acceptance immediately after Pi accepts the call; the daemon owns the still-running send promise and publishes any asynchronous rejection as `session.error`. Pi can emit the live user-message start before that message is branch-readable, so the daemon queues each accepted prompt's path-free file metadata and adds it to the matching user start in send order. The browser can render the attachment footer immediately without exposing bytes or server paths, while later hydration remains authoritative. An extension command may resolve without starting an agent turn, so completion of its non-streaming prompt promise publishes the idle lifecycle boundary that Pi does not emit as `agent_settled`. Pi notifies extensions of model switches (`model_select`) but not session subscribers, so that same completion edge also reconciles a changed live model into `session.model` before the idle boundary; thinking already emits `thinking_level_changed` to subscribers and needs no reconciliation. A registered extension invocation is not used for automatic first-prompt naming: an extension-only empty session remains unnamed unless the extension names it, and the first later conversation prompt supplies the derived title. Classification uses the active Pi runtime's registered extension commands, not a browser claim. Manual compact requests likewise acknowledge startup instead of holding the public/private request open for the summarization call; the daemon-owned promise reports its outcome through `session.compaction`. A second compact request while Pi is compacting fails as `SESSION_BUSY`, and optional `/compact` instructions pass to `AgentSession.compact(customInstructions)`. A later prompt on the same session invalidates an older send rejection so it cannot error the new turn. If the rejected send left Pi streaming, the daemon aborts it. Steer/follow-up against an idle session starts a new prompt instead of `SESSION_NOT_RUNNING`. Agent and compaction completion are never held behind the 30-second public/private request budgets. Pi retryable provider failures remain live: an `agent_end` with `willRetry` does not publish terminal `session.error`, and `auto_retry_start` projects Pi's attempt, next-attempt time, and redacted error text through `session.lifecycle: retry`. Retry metadata is retained in reconnect and `getSession` snapshots until the next `agent_start` begins the attempt. `agent_settled` remains the authoritative idle boundary after retry success, exhaustion, or cancellation and clears the run's user/assistant ownership.
35
35
  - Registry keys combine the SDK session ID with its cwd. A replacement subscription is rebound to the replacement session so old-session events cannot be published under the new identity. A collision is a visible error; it never replaces or disposes an unrelated runtime.
36
36
  - After `agent_settled` or a terminal compaction that will not resume the turn, the daemon disposes an idle runtime after five minutes (injectable for tests). Disposal never deletes Pi JSONL; the daemon remembers the selected session file and recreates that runtime on the next private prompt. Agent and compaction starts cancel pending disposal, and the timer refuses to dispose a session while `isStreaming` or `isCompacting` is authoritative.
37
37
  - A startup validation failure writes only a stable failure code to the owner-only non-secret state sidecar. It never records a transcript, session path, or credential. The supervisor surfaces that code as unavailable instead of claiming an empty or idle session.
@@ -0,0 +1,318 @@
1
+ import { afterEach, describe, expect, it, vi } from 'vitest';
2
+
3
+ vi.mock('node:fs/promises', async (importOriginal) => {
4
+ const actual = await importOriginal();
5
+ return {
6
+ ...actual,
7
+ rm: async (...args) => {
8
+ const target = String(args[0] ?? '');
9
+ const failPath = globalThis.__PROMPT_ROLLBACK_PATH__;
10
+ if (globalThis.__PROMPT_ROLLBACK_FAIL__ && failPath && target === String(failPath)) {
11
+ globalThis.__PROMPT_ROLLBACK_FAIL__ = false;
12
+ const error = new Error('remove failed');
13
+ error.code = 'EACCES';
14
+ throw error;
15
+ }
16
+ return actual.rm(...args);
17
+ },
18
+ };
19
+ });
20
+
21
+ import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
22
+ import { existsSync, readdirSync, readFileSync } from 'node:fs';
23
+ import { tmpdir } from 'node:os';
24
+ import { join } from 'node:path';
25
+
26
+ import { createSessionDaemon as createSessionDaemonImpl } from './session-daemon.js';
27
+ import { requestSessionDaemon } from './ipc-client.js';
28
+
29
+ const credential = 'test-prompt-credential';
30
+
31
+ function createSessionDaemon(options) {
32
+ return createSessionDaemonImpl({ ...options, agentDir: options.agentDir ?? options.cwd });
33
+ }
34
+
35
+ class FakeSession {
36
+ constructor() {
37
+ this.sessionId = 'sess-1';
38
+ this.isStreaming = false;
39
+ this.listeners = new Set();
40
+ }
41
+ subscribe(l) { this.listeners.add(l); return () => this.listeners.delete(l); }
42
+ async dispose() {}
43
+ }
44
+
45
+ function testDaemonEndpoint(root) {
46
+ if (process.platform === 'win32') return `\\\\.\\pipe\\pichamber-test-${Date.now()}-${Math.random().toString(16).slice(2)}`;
47
+ return join(root, 'daemon.sock');
48
+ }
49
+
50
+ const parseDescription = (raw) => {
51
+ const m = raw.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?/);
52
+ if (!m) return undefined;
53
+ const line = m[1].split(/\r?\n/).find((l) => /^description\s*:/.test(l));
54
+ if (!line) return undefined;
55
+ const v = line.slice(line.indexOf(':') + 1).trim();
56
+ try { return JSON.parse(v); } catch { return v.replace(/^['\"]|['\"]$/g, ''); }
57
+ };
58
+
59
+ const makeLoader = (agentDir, getCwd) => ({
60
+ getSkills: () => ({ skills: [] }),
61
+ getPrompts: () => {
62
+ const cwd = getCwd();
63
+ const entries = [];
64
+ const scan = (dir, scope) => {
65
+ const promptDir = join(dir, 'prompts');
66
+ if (!existsSync(promptDir)) return;
67
+ for (const file of readdirSync(promptDir)) {
68
+ if (!file.endsWith('.md')) continue;
69
+ const filePath = join(promptDir, file);
70
+ const raw = readFileSync(filePath, 'utf8');
71
+ const name = file.slice(0, -3);
72
+ const desc = parseDescription(raw);
73
+ const body = raw.replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n?/, '');
74
+ entries.push({
75
+ name,
76
+ ...(desc !== undefined ? { description: desc } : {}),
77
+ content: body,
78
+ filePath,
79
+ sourceInfo: { origin: 'top-level', scope },
80
+ });
81
+ }
82
+ };
83
+ scan(agentDir, 'user');
84
+ if (cwd) scan(join(cwd, '.pi'), 'project');
85
+ return { prompts: entries };
86
+ },
87
+ getAgentsFiles: () => ({ agentsFiles: [] }),
88
+ });
89
+
90
+ describe('prompt template daemon operations', () => {
91
+ const dirs = [];
92
+ let daemon = null;
93
+ afterEach(async () => {
94
+ if (daemon) { await daemon.stop().catch(() => {}); daemon = null; }
95
+ await Promise.all(dirs.splice(0).map((d) => rm(d, { recursive: true, force: true })));
96
+ });
97
+
98
+ const startDaemon = async ({ session, loader } = {}) => {
99
+ const root = await mkdtemp(join(tmpdir(), 'pichamber-prompt-'));
100
+ dirs.push(root);
101
+ const endpoint = testDaemonEndpoint(root);
102
+ const agentDir = join(root, 'agent');
103
+ const cwd = join(root, 'project');
104
+ await mkdir(agentDir, { recursive: true });
105
+ await mkdir(cwd, { recursive: true });
106
+ const sess = session ?? new FakeSession();
107
+ const baseLoader = loader;
108
+ daemon = createSessionDaemon({
109
+ endpoint, credential, cwd, agentDir,
110
+ createRuntime: async (opts) => {
111
+ const dir = typeof opts?.cwd === "string" && opts.cwd.length > 0 ? opts.cwd : cwd;
112
+ const runtimeLoader = baseLoader ?? makeLoader(agentDir, () => dir);
113
+ return { cwd: dir, session: sess, services: { resourceLoader: runtimeLoader }, async dispose() {} };
114
+ },
115
+ });
116
+ await daemon.start();
117
+ const request = (command, payload = {}) =>
118
+ requestSessionDaemon({ endpoint, credential, command, payload });
119
+ return { root, endpoint, agentDir, cwd, session: sess, request };
120
+ };
121
+
122
+ it('creates, reads, updates, renames, and deletes a global prompt', async () => {
123
+ const ctx = await startDaemon();
124
+ const created = await ctx.request('resources.prompts.create', {
125
+ name: 'review', description: 'Review', content: 'Do $1 $@', location: 'global', directory: ctx.cwd,
126
+ });
127
+ expect(created.prompts.some((p) => p.name === 'review')).toBe(true);
128
+ const listed = await ctx.request('resources.list', { directory: ctx.cwd });
129
+ const prompt = listed.prompts.find((p) => p.name === 'review');
130
+ expect(prompt).toMatchObject({ location: 'global', editable: true });
131
+ expect(prompt).not.toHaveProperty('filePath');
132
+
133
+ const updated = await ctx.request('resources.prompts.update', {
134
+ resourceId: prompt.id, directory: ctx.cwd, description: 'Updated', content: 'New $1',
135
+ });
136
+ expect(updated.prompts.find((p) => p.id === prompt.id)).toMatchObject({ description: 'Updated' });
137
+
138
+ const renamed = await ctx.request('resources.prompts.update', {
139
+ resourceId: prompt.id, directory: ctx.cwd, name: 'review2',
140
+ });
141
+ expect(renamed.prompts.some((p) => p.name === 'review2')).toBe(true);
142
+ expect(renamed.prompts.some((p) => p.name === 'review')).toBe(false);
143
+
144
+ const renamedPrompt = renamed.prompts.find((p) => p.name === 'review2');
145
+ const deleted = await ctx.request('resources.prompts.delete', {
146
+ resourceId: renamedPrompt.id, directory: ctx.cwd,
147
+ });
148
+ expect(deleted.prompts.some((p) => p.name === 'review2')).toBe(false);
149
+ });
150
+
151
+ it('preserves unknown frontmatter when editing', async () => {
152
+ const ctx = await startDaemon();
153
+ const filePath = join(ctx.agentDir, 'prompts', 'review.md');
154
+ await mkdir(join(ctx.agentDir, 'prompts'), { recursive: true });
155
+ await writeFile(filePath, '---\ndescription: \"Old\"\nargument-hint: \"[file]\"\n---\nBody $1\n', 'utf8');
156
+ const listed = await ctx.request('resources.list', { directory: ctx.cwd });
157
+ const prompt = listed.prompts.find((p) => p.name === 'review');
158
+ expect(prompt).toBeDefined();
159
+ await ctx.request('resources.prompts.update', {
160
+ resourceId: prompt.id, directory: ctx.cwd, description: 'New', content: 'Updated $@',
161
+ });
162
+ const raw = await readFile(filePath, 'utf8');
163
+ expect(raw).toContain('argument-hint');
164
+ expect(raw).toContain('Updated $@');
165
+ expect(raw).toContain('New');
166
+ });
167
+
168
+ it('serializes concurrent creates without overwriting the destination', async () => {
169
+ const ctx = await startDaemon();
170
+ const results = await Promise.allSettled([
171
+ ctx.request('resources.prompts.create', {
172
+ name: 'shared', description: 'First', content: 'One', location: 'global', directory: ctx.cwd,
173
+ }),
174
+ ctx.request('resources.prompts.create', {
175
+ name: 'shared', description: 'Second', content: 'Two', location: 'global', directory: ctx.cwd,
176
+ }),
177
+ ]);
178
+ expect(results.filter((result) => result.status === 'fulfilled')).toHaveLength(1);
179
+ expect(results.filter((result) => result.status === 'rejected')).toHaveLength(1);
180
+ const listed = await ctx.request('resources.list', { directory: ctx.cwd });
181
+ expect(listed.prompts.filter((prompt) => prompt.name === 'shared')).toHaveLength(1);
182
+ const raw = await readFile(join(ctx.agentDir, 'prompts', 'shared.md'), 'utf8');
183
+ expect(['One', 'Two'].some((content) => raw.includes(content))).toBe(true);
184
+ });
185
+
186
+ it('rejects duplicate destinations without overwriting', async () => {
187
+ const ctx = await startDaemon();
188
+ await ctx.request('resources.prompts.create', {
189
+ name: 'first', description: 'First', content: 'One', location: 'global', directory: ctx.cwd,
190
+ });
191
+ await ctx.request('resources.prompts.create', {
192
+ name: 'second', description: 'Second', content: 'Two', location: 'global', directory: ctx.cwd,
193
+ });
194
+ const listed = await ctx.request('resources.list', { directory: ctx.cwd });
195
+ const first = listed.prompts.find((p) => p.name === 'first');
196
+ await expect(ctx.request('resources.prompts.update', {
197
+ resourceId: first.id, directory: ctx.cwd, name: 'second',
198
+ })).rejects.toMatchObject({ code: 'INVALID_ARGUMENT' });
199
+ const after = await ctx.request('resources.list', { directory: ctx.cwd });
200
+ expect(after.prompts).toHaveLength(2);
201
+ });
202
+
203
+ it('supports trusted-project create, update, rename, and delete', async () => {
204
+ const ctx = await startDaemon();
205
+ const dir = join(ctx.root, 'trusted');
206
+ await mkdir(join(dir, '.pi', 'prompts'), { recursive: true });
207
+ const { ProjectTrustStore } = await import('@earendil-works/pi-coding-agent');
208
+ new ProjectTrustStore(ctx.agentDir).set(dir, true);
209
+ const created = await ctx.request('resources.prompts.create', {
210
+ name: 'local', description: 'Local', content: 'Body $1', location: 'project', directory: dir,
211
+ });
212
+ expect(created.prompts.some((p) => p.name === 'local')).toBe(true);
213
+ const listed = await ctx.request('resources.list', { directory: dir });
214
+ const prompt = listed.prompts.find((p) => p.name === 'local');
215
+ expect(prompt).toMatchObject({ location: 'project', editable: true });
216
+ await ctx.request('resources.prompts.update', {
217
+ resourceId: prompt.id, directory: dir, description: 'Updated', content: 'New $@',
218
+ });
219
+ const renamed = await ctx.request('resources.prompts.update', {
220
+ resourceId: prompt.id, directory: dir, name: 'local2',
221
+ });
222
+ expect(renamed.prompts.some((p) => p.name === 'local2')).toBe(true);
223
+ const renamedPrompt = renamed.prompts.find((p) => p.name === 'local2');
224
+ const deleted = await ctx.request('resources.prompts.delete', {
225
+ resourceId: renamedPrompt.id, directory: dir,
226
+ });
227
+ expect(deleted.prompts.some((p) => p.name === 'local2')).toBe(false);
228
+ });
229
+
230
+ it('rejects project mutations without trust', async () => {
231
+ const ctx = await startDaemon();
232
+ const dir = join(ctx.root, 'untrusted');
233
+ await mkdir(join(dir, '.pi', 'prompts'), { recursive: true });
234
+ const { ProjectTrustStore } = await import('@earendil-works/pi-coding-agent');
235
+ new ProjectTrustStore(ctx.agentDir).set(dir, false);
236
+ await expect(ctx.request('resources.prompts.create', {
237
+ name: 'local', description: 'Local', content: 'Body', location: 'project', directory: dir,
238
+ })).rejects.toMatchObject({ code: 'PROJECT_UNTRUSTED' });
239
+ });
240
+
241
+ it('rejects cross-directory resource ids', async () => {
242
+ const ctx = await startDaemon();
243
+ const dirA = join(ctx.root, 'a');
244
+ const dirB = join(ctx.root, 'b');
245
+ await mkdir(join(dirA, '.pi', 'prompts'), { recursive: true });
246
+ await mkdir(join(dirB, '.pi', 'prompts'), { recursive: true });
247
+ await writeFile(join(dirA, '.pi', 'prompts', 'private.md'), '---\ndescription: \"P\"\n---\nBody\n', 'utf8');
248
+ const { ProjectTrustStore } = await import('@earendil-works/pi-coding-agent');
249
+ new ProjectTrustStore(ctx.agentDir).set(dirA, true);
250
+ new ProjectTrustStore(ctx.agentDir).set(dirB, true);
251
+ const listedA = await ctx.request('resources.list', { directory: dirA });
252
+ const prompt = listedA.prompts.find((p) => p.name === 'private');
253
+ expect(prompt).toBeDefined();
254
+ await expect(ctx.request('resources.prompts.update', {
255
+ resourceId: prompt.id, directory: dirB, content: 'Hacked',
256
+ })).rejects.toMatchObject({ code: 'RESOURCE_NOT_FOUND' });
257
+ });
258
+
259
+ it('rolls back the destination when source removal fails', async () => {
260
+ const ctx = await startDaemon();
261
+ await ctx.request('resources.prompts.create', {
262
+ name: 'old', description: 'Old', content: 'Body', location: 'global', directory: ctx.cwd,
263
+ });
264
+ const listed = await ctx.request('resources.list', { directory: ctx.cwd });
265
+ const prompt = listed.prompts.find((p) => p.name === 'old');
266
+ const sourcePath = join(ctx.agentDir, 'prompts', 'old.md');
267
+ const destPath = join(ctx.agentDir, 'prompts', 'renamed.md');
268
+ globalThis.__PROMPT_ROLLBACK_PATH__ = sourcePath;
269
+ globalThis.__PROMPT_ROLLBACK_FAIL__ = true;
270
+ try {
271
+ await expect(ctx.request('resources.prompts.update', {
272
+ resourceId: prompt.id, directory: ctx.cwd, name: 'renamed',
273
+ })).rejects.toBeDefined();
274
+ } finally {
275
+ globalThis.__PROMPT_ROLLBACK_FAIL__ = false;
276
+ globalThis.__PROMPT_ROLLBACK_PATH__ = undefined;
277
+ }
278
+ const fsPromises = await import('node:fs/promises');
279
+ await expect(readFile(sourcePath, 'utf8')).resolves.toContain('Body');
280
+ await expect(fsPromises.stat(destPath)).rejects.toMatchObject({ code: 'ENOENT' });
281
+ const after = await ctx.request('resources.list', { directory: ctx.cwd });
282
+ expect(after.prompts.some((p) => p.name === 'old')).toBe(true);
283
+ expect(after.prompts.some((p) => p.name === 'renamed')).toBe(false);
284
+ });
285
+
286
+ it('blocks mutations while streaming', async () => {
287
+ const session = new FakeSession();
288
+ const ctx = await startDaemon({ session });
289
+ await ctx.request('resources.list', { directory: ctx.cwd });
290
+ session.isStreaming = true;
291
+ await expect(ctx.request('resources.prompts.create', {
292
+ name: 'blocked', description: 'Blocked', content: 'x', location: 'global', directory: ctx.cwd,
293
+ })).rejects.toMatchObject({ code: 'SESSION_BUSY' });
294
+ });
295
+
296
+ it('keeps package prompts read-only', async () => {
297
+ const loader = {
298
+ getSkills: () => ({ skills: [] }),
299
+ getPrompts: () => ({
300
+ prompts: [{
301
+ name: 'pkg', description: 'Pkg', content: 'Body', filePath: '/pkg/prompts/pkg.md',
302
+ sourceInfo: { origin: 'package', scope: 'user' },
303
+ }],
304
+ }),
305
+ getAgentsFiles: () => ({ agentsFiles: [] }),
306
+ };
307
+ const ctx = await startDaemon({ loader });
308
+ const listed = await ctx.request('resources.list', { directory: ctx.cwd });
309
+ const pkg = listed.prompts.find((p) => p.name === 'pkg');
310
+ expect(pkg.editable).not.toBe(true);
311
+ await expect(ctx.request('resources.prompts.update', {
312
+ resourceId: pkg.id, directory: ctx.cwd, content: 'x',
313
+ })).rejects.toMatchObject({ code: 'RESOURCE_NOT_FOUND' });
314
+ await expect(ctx.request('resources.prompts.delete', {
315
+ resourceId: pkg.id, directory: ctx.cwd,
316
+ })).rejects.toMatchObject({ code: 'RESOURCE_NOT_FOUND' });
317
+ });
318
+ });