@pi-chamber/web 0.7.2 → 0.8.1

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 (181) hide show
  1. package/README.md +1 -1
  2. package/dist/assets/{DiagramEditor-TeJ1G_NN.js → DiagramEditor-D_3eJVSw.js} +1 -1
  3. package/dist/assets/DiagramView-pGYm0-DR.js +1 -0
  4. package/dist/assets/DiffView-BApPTLGp.js +18 -0
  5. package/dist/assets/FilesView-CiPpuGiF.js +6 -0
  6. package/dist/assets/GitView-uW3w_LlQ.js +8 -0
  7. package/dist/assets/JsonTreeView-CpgqCk9_.js +1 -0
  8. package/dist/assets/MarkdownRendererImpl-fI6n3kqT.js +12 -0
  9. package/dist/assets/PatchDiff-BRloGXPs.js +1 -0
  10. package/dist/assets/SessionSwitcherContent-BQc-vW4s.js +1 -0
  11. package/dist/assets/SessionSwitcherDropdown-v_8TaIZm.js +2 -0
  12. package/dist/assets/SessionUnreadDot-A7vSfll2.js +1 -0
  13. package/dist/assets/SettingsView-CphlZvfd.js +2 -0
  14. package/dist/assets/SettingsWindow-D7UDhYd4.js +1 -0
  15. package/dist/assets/ToolOutputDialog-wpU0ylYS.js +8 -0
  16. package/dist/assets/ToolPartDiffPreview-BvoQK5Gm.js +1 -0
  17. package/dist/assets/{VirtualizedFileDiff-sRc4lN0B.js → VirtualizedFileDiff-DdPbLdh7.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-BO6FIjvn.js +1 -0
  21. package/dist/assets/computeVirtualFileMetrics-DMvXzUJh.js +3 -0
  22. package/dist/assets/contextFileOpenGuard-BwXQVjtS.js +1 -0
  23. package/dist/assets/gitStatusPredicates-CgNk6M2_.js +134 -0
  24. package/dist/assets/index-BebQicw3.css +1 -0
  25. package/dist/assets/index-Bkz23mZq.js +8 -0
  26. package/dist/assets/index-C3SyF-cA.js +1 -0
  27. package/dist/assets/isDiffPlainText-BboRbmcm.js +1 -0
  28. package/dist/assets/isFilePlainText-BpTnLRyI.js +1 -0
  29. package/dist/assets/main-CMOAwZnJ.js +135 -0
  30. package/dist/assets/main-xLwCWLu-.js +2 -0
  31. package/dist/assets/{markdownCore-BfuFM7mg.js → markdownCore-CmFv4H-w.js} +2 -2
  32. package/dist/assets/miniChat-Vwo4K1IK.js +2 -0
  33. package/dist/assets/mobile-BRaxtEoC.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-DM4rRUUz.js +2 -0
  37. package/dist/assets/renderMobileApp-DWWewNhc.js +11 -0
  38. package/dist/assets/runtimeEndpointReset-BF60eHSx.js +54 -0
  39. package/dist/assets/{runtimeSurface-DF3VwUlO.js → runtimeSurface-SmPSdfop.js} +1 -1
  40. package/dist/assets/themeResolver-yJ9XpNMI.js +1 -0
  41. package/dist/assets/{WindowsWindowControls-CCnU0ckO.js → useAppFontEffects-Bg-8jtrQ.js} +127 -500
  42. package/dist/assets/useFilesViewSearch-GLcYNIUV.js +7 -0
  43. package/dist/assets/usePushVisibilityBeacon-VSYBfNoY.js +10 -0
  44. package/dist/assets/useSwitcherItems-BkEt9K-N.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-B5cJDWBR.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-CfplGuM0.js +1 -0
  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-motion-dom-DJLgZh4Q.js → vendor-motion-dom-DhJ-sYS5.js} +1 -1
  86. package/dist/assets/{vendor-motion-utils-BGh8QBgx.js → vendor-motion-utils-CKEGc_YG.js} +1 -1
  87. package/dist/assets/{vendor-pierre-theming-C6Z4M5_u.js → vendor-pierre-theming-Dgp7B_O4.js} +1 -1
  88. package/dist/assets/{vendor-qrcode-COsmt6jn.js → vendor-qrcode-B0KNSajT.js} +1 -1
  89. package/dist/assets/{vendor-radix-ui-react-compose-refs-D1GnwnP9.js → vendor-radix-ui-react-compose-refs-8xy6TJML.js} +1 -1
  90. package/dist/assets/{vendor-radix-ui-react-context-CM4yFQ2I.js → vendor-radix-ui-react-context-CFsX-AUC.js} +1 -1
  91. package/dist/assets/{vendor-radix-ui-react-dialog-jX3Dld8c.js → vendor-radix-ui-react-dialog-D2yhEu2p.js} +1 -1
  92. package/dist/assets/{vendor-radix-ui-react-dismissable-layer-M7LsH3yL.js → vendor-radix-ui-react-dismissable-layer-DrorBNg9.js} +1 -1
  93. package/dist/assets/{vendor-radix-ui-react-focus-guards-D5MZ0nQs.js → vendor-radix-ui-react-focus-guards-BfdFmL7c.js} +1 -1
  94. package/dist/assets/{vendor-radix-ui-react-focus-scope-C2K7lNPv.js → vendor-radix-ui-react-focus-scope-D2BkImwt.js} +1 -1
  95. package/dist/assets/{vendor-radix-ui-react-id-BcxRjnbX.js → vendor-radix-ui-react-id-D2kS9K1j.js} +1 -1
  96. package/dist/assets/vendor-radix-ui-react-portal-YgCRIyi7.js +1 -0
  97. package/dist/assets/{vendor-radix-ui-react-presence-Btn-Dp7L.js → vendor-radix-ui-react-presence-D432pCMB.js} +1 -1
  98. package/dist/assets/{vendor-radix-ui-react-primitive-CfpW6_IT.js → vendor-radix-ui-react-primitive-DkH8dMOR.js} +1 -1
  99. package/dist/assets/{vendor-radix-ui-react-slot-BxUc3Pvz.js → vendor-radix-ui-react-slot-BIDFZX0-.js} +1 -1
  100. package/dist/assets/{vendor-radix-ui-react-use-callback-ref-UKEWHtoP.js → vendor-radix-ui-react-use-callback-ref-BwDcSoGV.js} +1 -1
  101. package/dist/assets/{vendor-radix-ui-react-use-controllable-state-C_ecoh35.js → vendor-radix-ui-react-use-controllable-state-LiqmKSXO.js} +1 -1
  102. package/dist/assets/vendor-radix-ui-react-use-effect-event-D94va83M.js +1 -0
  103. package/dist/assets/{vendor-radix-ui-react-use-escape-keydown-Co13lHGj.js → vendor-radix-ui-react-use-escape-keydown-DTkqjenV.js} +1 -1
  104. package/dist/assets/vendor-radix-ui-react-use-layout-effect-C8Yrsaph.js +1 -0
  105. package/dist/assets/{vendor-react-DYyjh7Q0.js → vendor-react-B5Z1Mdn3.js} +1 -1
  106. package/dist/assets/{vendor-react-drawio-Boqanm0j.js → vendor-react-drawio-BYDptOsj.js} +1 -1
  107. package/dist/assets/{vendor-react-remove-scroll-bar-C9YRs2nU.js → vendor-react-remove-scroll-bar-CSAHp1YF.js} +1 -1
  108. package/dist/assets/{vendor-react-remove-scroll-CfeMe0DL.js → vendor-react-remove-scroll-vR1dy1aP.js} +1 -1
  109. package/dist/assets/{vendor-react-style-singleton-B1H4bWSG.js → vendor-react-style-singleton-Ctw6HnYx.js} +1 -1
  110. package/dist/assets/{vendor-replit-codemirror-vim-BJY5fGLS.js → vendor-replit-codemirror-vim-CGHHNQxC.js} +1 -1
  111. package/dist/assets/{vendor-sonner-CW8w438f.js → vendor-sonner-BDtm25td.js} +1 -1
  112. package/dist/assets/{vendor-tanstack-react-virtual-IrbCBGJ4.js → vendor-tanstack-react-virtual-2skouoFw.js} +1 -1
  113. package/dist/assets/{vendor-use-callback-ref-CJB0R85I.js → vendor-use-callback-ref-CVVuCyLj.js} +1 -1
  114. package/dist/assets/{vendor-use-sidecar-C-AuTczP.js → vendor-use-sidecar-Vv4V8Nd1.js} +1 -1
  115. package/dist/assets/{vendor-use-sync-external-store-B7OScDIw.js → vendor-use-sync-external-store-D0AXkdQC.js} +1 -1
  116. package/dist/assets/{vendor-zustand-CnsBKjP5.js → vendor-zustand-GVb4H8HE.js} +1 -1
  117. package/dist/assets/{web-components-BYNCGylQ.js → web-components-0H9kvZwn.js} +2 -2
  118. package/dist/index.html +6 -6
  119. package/dist/mini-chat.html +5 -5
  120. package/dist/mobile.html +5 -5
  121. package/package.json +1 -1
  122. package/server/lib/git/DOCUMENTATION.md +3 -2
  123. package/server/lib/git/routes.js +27 -0
  124. package/server/lib/git/routes.test.js +41 -0
  125. package/server/lib/git/service.js +7 -1
  126. package/server/lib/git/service.test.js +23 -0
  127. package/server/lib/pi/routes.js +263 -6
  128. package/server/lib/pi/routes.test.js +314 -1
  129. package/server/lib/pi/session-daemon/DOCUMENTATION.md +2 -2
  130. package/server/lib/pi/session-daemon/prompt-operations.test.js +318 -0
  131. package/server/lib/pi/session-daemon/session-daemon.js +309 -25
  132. package/server/lib/pi/session-daemon/session-daemon.test.js +137 -0
  133. package/server/lib/pi/session-daemon/supervisor.test.js +1 -1
  134. package/server/lib/pi/snippets-store.js +400 -0
  135. package/server/lib/pi/snippets-store.test.js +252 -0
  136. package/server/lib/relay/host-client.test.js +79 -15
  137. package/server/lib/server/cors.js +4 -0
  138. package/server/lib/server/cors.test.js +8 -5
  139. package/dist/assets/CommitSection-DfAlM30E.js +0 -1
  140. package/dist/assets/DiagramView-DKLIwNth.js +0 -1
  141. package/dist/assets/DiffView-CZyqSs5W.js +0 -18
  142. package/dist/assets/FilesView-rftA7fEL.js +0 -14
  143. package/dist/assets/GitView-D5LMTT2M.js +0 -6
  144. package/dist/assets/JsonTreeView-DMI3-Smy.js +0 -1
  145. package/dist/assets/MarkdownRendererImpl-gdd-5n9J.js +0 -12
  146. package/dist/assets/PatchDiff-GNB1NlAN.js +0 -1
  147. package/dist/assets/PierreDiffViewer-DmJv2AoJ.js +0 -136
  148. package/dist/assets/SessionSwitcherContent-CWdDPll7.js +0 -1
  149. package/dist/assets/SessionSwitcherDropdown-Cx-Jfmvo.js +0 -2
  150. package/dist/assets/SessionUnreadDot-CKe4uVcf.js +0 -1
  151. package/dist/assets/SettingsView-DaxkNy5C.js +0 -4
  152. package/dist/assets/SettingsWindow-D1M_rRDo.js +0 -1
  153. package/dist/assets/ToolOutputDialog-CUKcp77A.js +0 -15
  154. package/dist/assets/ToolPartDiffPreview-CkzwXAC5.js +0 -8
  155. package/dist/assets/collapsible-B0cIItyf.js +0 -1
  156. package/dist/assets/computeVirtualFileMetrics-B1uVA58l.js +0 -3
  157. package/dist/assets/contextFileOpenGuard-BuedQ5EQ.js +0 -1
  158. package/dist/assets/index-BA67uOfZ.js +0 -1
  159. package/dist/assets/index-CcbDTf8Q.js +0 -8
  160. package/dist/assets/index-Cl3XbCeC.css +0 -1
  161. package/dist/assets/isDiffPlainText-DLDFLL6P.js +0 -1
  162. package/dist/assets/isFilePlainText-B2wwrpRU.js +0 -1
  163. package/dist/assets/main-B5k0qpHJ.js +0 -133
  164. package/dist/assets/main-Bepu8Jr9.js +0 -2
  165. package/dist/assets/miniChat-Co0Snpgl.js +0 -2
  166. package/dist/assets/mobile-CSvL_Zyu.js +0 -2
  167. package/dist/assets/registerCustomTheme-BBXUCRnG.js +0 -1
  168. package/dist/assets/renderElectronMiniChatApp-DrMJ1RXX.js +0 -2
  169. package/dist/assets/renderMobileApp-B2toAnMW.js +0 -14
  170. package/dist/assets/themeResolver-BmJyTmjJ.js +0 -1
  171. package/dist/assets/useInlineCommentController-CxMP78jg.js +0 -2
  172. package/dist/assets/usePanelSlide-DUuoQt5X.js +0 -56
  173. package/dist/assets/usePushVisibilityBeacon-CSPdFBaA.js +0 -10
  174. package/dist/assets/useSwitcherItems-zOeC2Cta.js +0 -1
  175. package/dist/assets/vendor-base-ui-DL8r2fgQ.js +0 -1
  176. package/dist/assets/vendor-framer-motion-DJASDzNt.js +0 -1
  177. package/dist/assets/vendor-radix-ui-react-portal-xlJWBfDg.js +0 -1
  178. package/dist/assets/vendor-radix-ui-react-use-effect-event-DkJl_Rn_.js +0 -1
  179. package/dist/assets/vendor-radix-ui-react-use-layout-effect-0fyGwS2_.js +0 -1
  180. package/dist/assets/vendor-remixicon-react-CzPq62YO.js +0 -1
  181. /package/dist/assets/{usePanelSlide-BV3KOtdA.css → runtimeEndpointReset-BV3KOtdA.css} +0 -0
@@ -19,6 +19,7 @@ import {
19
19
  sanitizeExtensionFormFields,
20
20
  } from './extension-protocol.js';
21
21
  import { createPiUiSettingsStore } from './ui-settings-store.js';
22
+ import { createPiSnippetsStore } from './snippets-store.js';
22
23
 
23
24
  const UNAVAILABLE_CODES = new Set([
24
25
  'DAEMON_UNAVAILABLE',
@@ -195,6 +196,16 @@ const sanitizeNavigation = (value) => {
195
196
  };
196
197
  };
197
198
 
199
+ const projectFilePart = (part) => {
200
+ // Optional fields degrade instead of failing the whole message. The daemon
201
+ // only emits inline data URLs; never pass a filesystem or remote URL on.
202
+ const file = {};
203
+ if (typeof part.mime === 'string' && part.mime.length > 0 && part.mime.length <= 200) file.mime = part.mime.slice(0, 200);
204
+ if (typeof part.filename === 'string' && part.filename.length > 0 && part.filename.length <= 2048) file.filename = part.filename.slice(0, 2048);
205
+ if (typeof part.url === 'string' && part.url.length > 0 && part.url.length <= 8000000 && part.url.startsWith('data:')) file.url = part.url;
206
+ return { type: 'file', id: part.id, index: part.index, ...file };
207
+ };
208
+
198
209
  const projectSessionDetail = (value) => {
199
210
  if (!value || typeof value !== 'object' || !Array.isArray(value.messages) || !Number.isSafeInteger(value.lastSequence)) throw protocolMismatch();
200
211
  const messages = value.messages.map((item) => {
@@ -240,6 +251,7 @@ const projectSessionDetail = (value) => {
240
251
  state: ['pending', 'running', 'completed', 'error', 'cancelled'].includes(part.state) ? part.state : 'completed',
241
252
  };
242
253
  }
254
+ if (part.type === 'file') return projectFilePart(part);
243
255
  throw protocolMismatch();
244
256
  });
245
257
  return { message: projected, parts };
@@ -535,7 +547,15 @@ export const projectEventFrame = (frame) => {
535
547
  return { ...common, payload: { title } };
536
548
  }
537
549
  case 'session.tree.updated': return { ...common, payload: {} };
538
- case 'assistant.message.start': return { ...common, payload: { messageId: frame.payload.messageId, role: frame.payload.role, startedAt: frame.payload.startedAt, ...(typeof frame.payload.parentId === 'string' ? { parentId: frame.payload.parentId } : {}), ...(typeof frame.payload.text === 'string' ? { text: frame.payload.text } : {}), ...(frame.payload.model ? { model: frame.payload.model } : {}) } };
550
+ case 'assistant.message.start': {
551
+ const files = frame.payload.role === 'user' && Array.isArray(frame.payload.files)
552
+ ? frame.payload.files
553
+ .filter((part) => part && part.type === 'file' && typeof part.id === 'string' && Number.isSafeInteger(part.index))
554
+ .slice(0, 32)
555
+ .map(projectFilePart)
556
+ : [];
557
+ return { ...common, payload: { messageId: frame.payload.messageId, role: frame.payload.role, startedAt: frame.payload.startedAt, ...(typeof frame.payload.parentId === 'string' ? { parentId: frame.payload.parentId } : {}), ...(typeof frame.payload.text === 'string' ? { text: frame.payload.text } : {}), ...(files.length > 0 ? { files } : {}), ...(frame.payload.model ? { model: frame.payload.model } : {}) } };
558
+ }
539
559
  case 'assistant.message.delta':
540
560
  case 'assistant.thinking.delta': return { ...common, payload: { messageId: frame.payload.messageId, contentIndex: frame.payload.contentIndex, delta: frame.payload.delta, ...(typeof frame.payload.partId === 'string' ? { partId: frame.payload.partId } : {}) } };
541
561
  case 'assistant.message.end': return {
@@ -746,6 +766,7 @@ export const registerPiRuntimeRoutes = (app, {
746
766
  settingsStore = createPiSettingsStore(),
747
767
  sessionFoldersStore = createPiSessionFoldersStore(),
748
768
  uiSettingsStore = createPiUiSettingsStore(),
769
+ snippetsStore = createPiSnippetsStore(),
749
770
  listCustomThemes = listPiCustomThemes,
750
771
  updateChecker = checkForUpdates,
751
772
  updateLauncher = launchUpdateCommand,
@@ -1065,14 +1086,206 @@ export const registerPiRuntimeRoutes = (app, {
1065
1086
  }
1066
1087
  });
1067
1088
 
1068
- app.get('/api/pi/resources', async (_req, res) => {
1089
+ app.get('/api/pi/resources', async (req, res) => {
1090
+ const directory = typeof req.query?.directory === 'string' && req.query.directory.length > 0
1091
+ ? req.query.directory
1092
+ : undefined;
1093
+ try {
1094
+ res.json(projectResources(await getDaemonRuntime(getPiSessionDaemonRuntime).request(
1095
+ 'resources.list',
1096
+ directory ? { directory } : undefined,
1097
+ )));
1098
+ } catch (error) {
1099
+ writeDaemonError(res, error);
1100
+ }
1101
+ });
1102
+
1103
+ app.get('/api/pi/commands', async (req, res) => {
1104
+ const directory = typeof req.query?.directory === 'string' && req.query.directory.length > 0
1105
+ ? req.query.directory
1106
+ : undefined;
1069
1107
  try {
1070
- res.json(projectResources(await getDaemonRuntime(getPiSessionDaemonRuntime).request('resources.list')));
1108
+ const runtime = getDaemonRuntime(getPiSessionDaemonRuntime);
1109
+ const [resources, extensionList] = await Promise.all([
1110
+ runtime.request('resources.list', { ...(directory ? { directory } : {}) }),
1111
+ runtime.request('extensions.list', { ...(directory ? { directory } : {}) }),
1112
+ ]);
1113
+ const projectedResources = projectResources(resources);
1114
+ const projectedExtensions = projectExtensionList(extensionList);
1115
+ // Pi SDK 0.84.1 `getCommands()` exposes skills as `skill:name`, prompts
1116
+ // as `name`, and extensions under their registered invocation name
1117
+ // (including Pi-generated `:suffix` disambiguation). Mirror that
1118
+ // executable identity here so `/` autocomplete inserts what Pi executes.
1119
+ // Precedence at execution time is extension > skill/prompt expansion,
1120
+ // with PiChamber-local system commands intercepting before Pi.
1121
+ const commands = [
1122
+ ...projectedExtensions.commands,
1123
+ ...projectedResources.prompts.map((prompt) => ({
1124
+ name: prompt.name,
1125
+ ...(typeof prompt.description === 'string' ? { description: prompt.description } : {}),
1126
+ source: 'prompt',
1127
+ ...(typeof prompt.location === 'string' ? { scope: prompt.location } : {}),
1128
+ })),
1129
+ ...projectedResources.skills.map((skill) => ({
1130
+ name: `skill:${skill.name}`,
1131
+ ...(typeof skill.description === 'string' ? { description: skill.description } : {}),
1132
+ source: 'skill',
1133
+ ...(typeof skill.location === 'string' ? { scope: skill.location } : {}),
1134
+ })),
1135
+ ];
1136
+ res.json({ directory: projectedExtensions.directory, commands });
1071
1137
  } catch (error) {
1072
1138
  writeDaemonError(res, error);
1073
1139
  }
1074
1140
  });
1075
1141
 
1142
+ const SNIPPET_NAME_PATTERN = /^[a-z0-9][a-z0-9_-]{0,63}$/i;
1143
+ const validSnippetAliases = (aliases) => aliases === undefined
1144
+ || (Array.isArray(aliases)
1145
+ && aliases.length <= 10
1146
+ && aliases.every((alias) => typeof alias === 'string' && SNIPPET_NAME_PATTERN.test(alias.trim())));
1147
+
1148
+ const projectSnippets = (snippets) => {
1149
+ if (!Array.isArray(snippets)) throw protocolMismatch();
1150
+ return {
1151
+ snippets: snippets.map((snippet) => {
1152
+ if (!snippet || typeof snippet !== 'object'
1153
+ || typeof snippet.id !== 'string' || snippet.id.length === 0
1154
+ || typeof snippet.name !== 'string' || snippet.name.length === 0
1155
+ || typeof snippet.content !== 'string'
1156
+ || (snippet.description !== undefined && typeof snippet.description !== 'string')
1157
+ || !Array.isArray(snippet.aliases)
1158
+ || (snippet.scope !== 'global' && snippet.scope !== 'project')) throw protocolMismatch();
1159
+ return {
1160
+ id: snippet.id,
1161
+ name: snippet.name,
1162
+ content: snippet.content,
1163
+ ...(typeof snippet.description === 'string' && snippet.description.length > 0 ? { description: snippet.description } : {}),
1164
+ aliases: snippet.aliases.filter((alias) => typeof alias === 'string'),
1165
+ scope: snippet.scope,
1166
+ ...(snippet.scope === 'project' && typeof snippet.directory === 'string' ? { directory: snippet.directory } : {}),
1167
+ ...(Number.isSafeInteger(snippet.createdAt) ? { createdAt: snippet.createdAt } : {}),
1168
+ ...(Number.isSafeInteger(snippet.updatedAt) ? { updatedAt: snippet.updatedAt } : {}),
1169
+ };
1170
+ }),
1171
+ };
1172
+ };
1173
+
1174
+ const snippetDirectoryFrom = (req) => {
1175
+ const queryDirectory = typeof req.query?.directory === 'string' && req.query.directory.length > 0
1176
+ ? req.query.directory
1177
+ : undefined;
1178
+ const bodyDirectory = typeof req.body?.directory === 'string' && req.body.directory.length > 0
1179
+ ? req.body.directory
1180
+ : undefined;
1181
+ return queryDirectory ?? bodyDirectory;
1182
+ };
1183
+
1184
+ const writeSnippetError = (res, error) => {
1185
+ const code = typeof error?.code === 'string' ? error.code : 'SNIPPETS_INVALID';
1186
+ if (code === 'SNIPPET_NOT_FOUND') {
1187
+ res.status(404).json({ error: { code } });
1188
+ return;
1189
+ }
1190
+ if (code === 'SNIPPETS_INVALID') {
1191
+ res.status(500).json({ error: { code } });
1192
+ return;
1193
+ }
1194
+ res.status(400).json({ error: { code } });
1195
+ };
1196
+
1197
+ app.get('/api/pi/snippets', async (req, res) => {
1198
+ try {
1199
+ res.json(projectSnippets(await snippetsStore.list(snippetDirectoryFrom(req))));
1200
+ } catch {
1201
+ res.status(500).json({ error: { code: 'SNIPPETS_INVALID' } });
1202
+ }
1203
+ });
1204
+
1205
+ app.post('/api/pi/snippets', async (req, res) => {
1206
+ const { name, content, description, aliases, scope, directory } = req.body ?? {};
1207
+ if (typeof name !== 'string' || typeof content !== 'string'
1208
+ || !SNIPPET_NAME_PATTERN.test(name.trim())
1209
+ || content.length === 0 || content.length > 200_000
1210
+ || (description !== undefined && (typeof description !== 'string' || description.length > 4_000))
1211
+ || !validSnippetAliases(aliases)
1212
+ || (scope !== undefined && scope !== 'global' && scope !== 'project')
1213
+ || (directory !== undefined && typeof directory !== 'string')) {
1214
+ res.status(400).json({ error: { code: 'INVALID_ARGUMENT' } });
1215
+ return;
1216
+ }
1217
+ try {
1218
+ const snippets = await snippetsStore.create({
1219
+ name,
1220
+ content,
1221
+ ...(description !== undefined ? { description } : {}),
1222
+ ...(aliases !== undefined ? { aliases } : {}),
1223
+ scope: scope ?? 'global',
1224
+ ...(directory !== undefined ? { directory } : {}),
1225
+ });
1226
+ res.status(201).json(projectSnippets(snippets));
1227
+ } catch (error) {
1228
+ writeSnippetError(res, error);
1229
+ }
1230
+ });
1231
+
1232
+ app.put('/api/pi/snippets/:snippetId', async (req, res) => {
1233
+ const snippetId = req.params.snippetId;
1234
+ if (typeof snippetId !== 'string' || snippetId.length === 0 || snippetId.length > 128) {
1235
+ res.status(400).json({ error: { code: 'INVALID_ARGUMENT' } });
1236
+ return;
1237
+ }
1238
+ const { content, description, aliases, name, scope, directory } = req.body ?? {};
1239
+ if ((content !== undefined && (typeof content !== 'string' || content.length === 0 || content.length > 200_000))
1240
+ || (description !== undefined && (typeof description !== 'string' || description.length > 4_000))
1241
+ || !validSnippetAliases(aliases)
1242
+ || (name !== undefined && typeof name !== 'string')
1243
+ || (scope !== undefined && scope !== 'global' && scope !== 'project')
1244
+ || (directory !== undefined && typeof directory !== 'string')) {
1245
+ res.status(400).json({ error: { code: 'INVALID_ARGUMENT' } });
1246
+ return;
1247
+ }
1248
+ if (name !== undefined && !SNIPPET_NAME_PATTERN.test(name.trim())) {
1249
+ res.status(400).json({ error: { code: 'INVALID_ARGUMENT' } });
1250
+ return;
1251
+ }
1252
+ try {
1253
+ res.json(projectSnippets(await snippetsStore.update(snippetId, {
1254
+ ...(name !== undefined ? { name } : {}),
1255
+ ...(content !== undefined ? { content } : {}),
1256
+ ...(description !== undefined ? { description } : {}),
1257
+ ...(aliases !== undefined ? { aliases } : {}),
1258
+ ...(scope !== undefined ? { scope } : {}),
1259
+ ...(directory !== undefined ? { directory } : {}),
1260
+ }, snippetDirectoryFrom(req))));
1261
+ } catch (error) {
1262
+ writeSnippetError(res, error);
1263
+ }
1264
+ });
1265
+
1266
+ app.delete('/api/pi/snippets/:snippetId', async (req, res) => {
1267
+ const snippetId = req.params.snippetId;
1268
+ if (typeof snippetId !== 'string' || snippetId.length === 0) {
1269
+ res.status(400).json({ error: { code: 'INVALID_ARGUMENT' } });
1270
+ return;
1271
+ }
1272
+ try {
1273
+ res.json(projectSnippets(await snippetsStore.remove(snippetId, snippetDirectoryFrom(req))));
1274
+ } catch (error) {
1275
+ writeSnippetError(res, error);
1276
+ }
1277
+ });
1278
+
1279
+ const resourceDirectoryFrom = (req) => {
1280
+ const queryDirectory = typeof req.query?.directory === 'string' && req.query.directory.length > 0
1281
+ ? req.query.directory
1282
+ : undefined;
1283
+ const bodyDirectory = typeof req.body?.directory === 'string' && req.body.directory.length > 0
1284
+ ? req.body.directory
1285
+ : undefined;
1286
+ return queryDirectory ?? bodyDirectory;
1287
+ };
1288
+
1076
1289
  app.put('/api/pi/resources/:resourceId', async (req, res) => {
1077
1290
  const resourceId = req.params.resourceId;
1078
1291
  const content = req.body?.content;
@@ -1080,8 +1293,9 @@ export const registerPiRuntimeRoutes = (app, {
1080
1293
  res.status(400).json({ error: { code: 'INVALID_ARGUMENT' } });
1081
1294
  return;
1082
1295
  }
1296
+ const directory = resourceDirectoryFrom(req);
1083
1297
  try {
1084
- res.json(projectResources(await getDaemonRuntime(getPiSessionDaemonRuntime).request('resources.update', { resourceId, content })));
1298
+ res.json(projectResources(await getDaemonRuntime(getPiSessionDaemonRuntime).request('resources.update', { resourceId, content, ...(directory ? { directory } : {}) })));
1085
1299
  } catch (error) {
1086
1300
  writeDaemonError(res, error);
1087
1301
  }
@@ -1093,8 +1307,50 @@ export const registerPiRuntimeRoutes = (app, {
1093
1307
  res.status(400).json({ error: { code: 'INVALID_ARGUMENT' } });
1094
1308
  return;
1095
1309
  }
1310
+ if (!/^[a-z0-9][a-z0-9_-]{0,63}$/i.test(name)) {
1311
+ res.status(400).json({ error: { code: 'INVALID_ARGUMENT' } });
1312
+ return;
1313
+ }
1314
+ const directory = resourceDirectoryFrom(req);
1096
1315
  try {
1097
- res.status(201).json(projectResources(await getDaemonRuntime(getPiSessionDaemonRuntime).request('resources.prompts.create', { name, description, content, location })));
1316
+ res.status(201).json(projectResources(await getDaemonRuntime(getPiSessionDaemonRuntime).request('resources.prompts.create', { name, description, content, location, ...(directory ? { directory } : {}) })));
1317
+ } catch (error) {
1318
+ writeDaemonError(res, error);
1319
+ }
1320
+ });
1321
+
1322
+ app.put('/api/pi/resources/prompts/:resourceId', async (req, res) => {
1323
+ const resourceId = req.params.resourceId;
1324
+ if (typeof resourceId !== 'string' || resourceId.length === 0) {
1325
+ res.status(400).json({ error: { code: 'INVALID_ARGUMENT' } });
1326
+ return;
1327
+ }
1328
+ const { name, description, content, location } = req.body ?? {};
1329
+ if ((name !== undefined && typeof name !== 'string')
1330
+ || (description !== undefined && typeof description !== 'string')
1331
+ || (content !== undefined && typeof content !== 'string')
1332
+ || (location !== undefined && location !== 'global' && location !== 'project')) {
1333
+ res.status(400).json({ error: { code: 'INVALID_ARGUMENT' } });
1334
+ return;
1335
+ }
1336
+ if (name !== undefined && !/^[a-z0-9][a-z0-9_-]{0,63}$/i.test(name)) {
1337
+ res.status(400).json({ error: { code: 'INVALID_ARGUMENT' } });
1338
+ return;
1339
+ }
1340
+ if (name === undefined && description === undefined && content === undefined && location === undefined) {
1341
+ res.status(400).json({ error: { code: 'INVALID_ARGUMENT' } });
1342
+ return;
1343
+ }
1344
+ const directory = resourceDirectoryFrom(req);
1345
+ try {
1346
+ res.json(projectResources(await getDaemonRuntime(getPiSessionDaemonRuntime).request('resources.prompts.update', {
1347
+ resourceId,
1348
+ ...(directory ? { directory } : {}),
1349
+ ...(name !== undefined ? { name } : {}),
1350
+ ...(description !== undefined ? { description } : {}),
1351
+ ...(content !== undefined ? { content } : {}),
1352
+ ...(location !== undefined ? { location } : {}),
1353
+ })));
1098
1354
  } catch (error) {
1099
1355
  writeDaemonError(res, error);
1100
1356
  }
@@ -1106,8 +1362,9 @@ export const registerPiRuntimeRoutes = (app, {
1106
1362
  res.status(400).json({ error: { code: 'INVALID_ARGUMENT' } });
1107
1363
  return;
1108
1364
  }
1365
+ const directory = resourceDirectoryFrom(req);
1109
1366
  try {
1110
- res.json(projectResources(await getDaemonRuntime(getPiSessionDaemonRuntime).request('resources.prompts.delete', { resourceId })));
1367
+ res.json(projectResources(await getDaemonRuntime(getPiSessionDaemonRuntime).request('resources.prompts.delete', { resourceId, ...(directory ? { directory } : {}) })));
1111
1368
  } catch (error) {
1112
1369
  writeDaemonError(res, error);
1113
1370
  }
@@ -1,7 +1,7 @@
1
1
  import { afterEach, describe, expect, it } from 'vitest';
2
2
  import express from 'express';
3
3
 
4
- import { registerPiRuntimeRoutes } from './routes.js';
4
+ import { projectEventFrame, registerPiRuntimeRoutes } from './routes.js';
5
5
 
6
6
  const listen = (app) => new Promise((resolve, reject) => {
7
7
  const server = app.listen(0, '127.0.0.1', () => resolve(server));
@@ -25,6 +25,36 @@ const close = (server) => new Promise((resolve, reject) => {
25
25
  describe('Pi runtime route', () => {
26
26
  let server;
27
27
 
28
+ it('projects prompt-time files on a live user message start', () => {
29
+ expect(projectEventFrame({
30
+ protocolVersion: 1,
31
+ kind: 'event',
32
+ event: 'assistant.message.start',
33
+ sequence: 4,
34
+ payload: {
35
+ sessionId: 'pi-session-files',
36
+ directory: '/workspace',
37
+ messageId: 'user-1',
38
+ role: 'user',
39
+ text: 'look',
40
+ startedAt: 2,
41
+ files: [
42
+ { type: 'file', id: 'user-1:file:0', index: 0, mime: 'image/png', filename: 'image.png' },
43
+ { type: 'file', id: 'bad', index: 1, mime: `x/${'y'.repeat(300)}`, filename: 'bad.png', url: 'file:///private/path' },
44
+ ],
45
+ },
46
+ })).toMatchObject({
47
+ name: 'assistant.message.start',
48
+ payload: {
49
+ messageId: 'user-1',
50
+ files: [
51
+ { type: 'file', id: 'user-1:file:0', index: 0, mime: 'image/png', filename: 'image.png' },
52
+ { type: 'file', id: 'bad', index: 1, filename: 'bad.png' },
53
+ ],
54
+ },
55
+ });
56
+ });
57
+
28
58
  afterEach(async () => {
29
59
  await close(server);
30
60
  server = undefined;
@@ -597,6 +627,56 @@ describe('Pi runtime route', () => {
597
627
  }
598
628
  });
599
629
 
630
+ it('projects daemon file parts for image and attachment history instead of failing the session open', async () => {
631
+ const detail = {
632
+ session: { id: 'pi-session-files', directory: '/workspace', createdAt: 1, updatedAt: 2 },
633
+ messages: [{
634
+ message: { id: 'entry-1', sessionId: 'pi-session-files', directory: '/workspace', role: 'user', text: 'look', createdAt: 2 },
635
+ parts: [
636
+ { type: 'file', id: 'entry-1:image:1', index: 1, mime: 'image/png', url: 'data:image/png;base64,AAA', filename: 'image.png' },
637
+ { type: 'file', id: 'entry-1:attachment:0', index: 0, filename: 'notes.zip' },
638
+ // Degraded, never fatal: oversized/non-data URLs and oversized mime are stripped.
639
+ { type: 'file', id: 'entry-1:image:9', index: 9, mime: 'image/png', url: `data:image/png;base64,${'A'.repeat(9000000)}`, filename: 'huge.png' },
640
+ { type: 'file', id: 'entry-1:image:10', index: 10, mime: 'image/png', url: 'https://example.test/image.png', filename: 'remote.png' },
641
+ { type: 'file', id: 'entry-1:image:11', index: 11, mime: `x/${'y'.repeat(300)}`, filename: 'bad-mime.png' },
642
+ ],
643
+ }],
644
+ lastSequence: 3,
645
+ isStreaming: false,
646
+ lifecycle: 'idle',
647
+ };
648
+ const runtime = {
649
+ health: async () => ({ state: 'ready', protocolVersion: 1, capabilities: [] }),
650
+ request: async (command) => {
651
+ if (command === 'sessions.open') return detail;
652
+ return {};
653
+ },
654
+ };
655
+ const app = express();
656
+ app.use(express.json());
657
+ registerPiRuntimeRoutes(app, { getPiSessionDaemonRuntime: () => runtime, archiveStore: { read: async () => ({}) } });
658
+ server = await listen(app);
659
+
660
+ const response = await fetch(`http://127.0.0.1:${server.address().port}/api/pi/sessions/pi-session-files`);
661
+ expect(response.status).toBe(200);
662
+ await expect(response.json()).resolves.toEqual({
663
+ session: { id: 'pi-session-files', directory: '/workspace', createdAt: 1, updatedAt: 2 },
664
+ messages: [{
665
+ message: { id: 'entry-1', sessionId: 'pi-session-files', directory: '/workspace', role: 'user', text: 'look', createdAt: 2 },
666
+ parts: [
667
+ { type: 'file', id: 'entry-1:image:1', index: 1, mime: 'image/png', url: 'data:image/png;base64,AAA', filename: 'image.png' },
668
+ { type: 'file', id: 'entry-1:attachment:0', index: 0, filename: 'notes.zip' },
669
+ { type: 'file', id: 'entry-1:image:9', index: 9, mime: 'image/png', filename: 'huge.png' },
670
+ { type: 'file', id: 'entry-1:image:10', index: 10, mime: 'image/png', filename: 'remote.png' },
671
+ { type: 'file', id: 'entry-1:image:11', index: 11, filename: 'bad-mime.png' },
672
+ ],
673
+ }],
674
+ lastSequence: 3,
675
+ isStreaming: false,
676
+ lifecycle: 'idle',
677
+ });
678
+ });
679
+
600
680
  it('rejects unauthenticated requests before the Pi adapters run', async () => {
601
681
  let invoked = false;
602
682
  const app = express();
@@ -874,4 +954,237 @@ describe('Pi runtime route', () => {
874
954
  expect(response.status).toBe(503);
875
955
  await expect(response.json()).resolves.toEqual({ error: { code: 'DAEMON_LOCK_UNAVAILABLE' } });
876
956
  });
957
+
958
+ it('lists Pi prompt templates and extension commands as native slash commands', async () => {
959
+ const calls = [];
960
+ const runtime = {
961
+ request: async (command, payload) => {
962
+ calls.push({ command, payload });
963
+ if (command === 'resources.list') {
964
+ return {
965
+ skills: [],
966
+ prompts: [{ id: 'prompt-1', kind: 'prompt', name: 'review', description: 'Review', location: 'project', content: 'Review', filePath: '/private/review.md' }],
967
+ agents: [],
968
+ };
969
+ }
970
+ return {
971
+ directory: '/workspace',
972
+ extensions: [{ id: 'a1b2c3d4e5f60718', name: 'ext' }],
973
+ commands: [{ name: 'hello', description: 'Say hello', source: 'extension' }],
974
+ };
975
+ },
976
+ };
977
+ const app = express();
978
+ app.use(express.json());
979
+ registerPiRuntimeRoutes(app, { getPiSessionDaemonRuntime: () => runtime });
980
+ server = await listen(app);
981
+ const response = await fetch(`http://127.0.0.1:${server.address().port}/api/pi/commands?directory=/workspace`);
982
+ expect(response.status).toBe(200);
983
+ // Order mirrors Pi SDK getCommands(): extensions, prompts, skills.
984
+ await expect(response.json()).resolves.toEqual({
985
+ directory: '/workspace',
986
+ commands: [
987
+ { name: 'hello', description: 'Say hello', source: 'extension' },
988
+ { name: 'review', description: 'Review', source: 'prompt', scope: 'project' },
989
+ ],
990
+ });
991
+ expect(calls).toEqual([
992
+ { command: 'resources.list', payload: { directory: '/workspace' } },
993
+ { command: 'extensions.list', payload: { directory: '/workspace' } },
994
+ ]);
995
+ });
996
+
997
+ it('exposes Pi skills as /skill:name commands (never bare /name)', async () => {
998
+ const runtime = {
999
+ request: async (command) => {
1000
+ if (command === 'resources.list') {
1001
+ return {
1002
+ skills: [{ id: 'skill-1', kind: 'skill', name: 'code-review', description: 'Review', location: 'global' }],
1003
+ prompts: [{ id: 'prompt-1', kind: 'prompt', name: 'review', description: 'Review', location: 'global' }],
1004
+ agents: [],
1005
+ };
1006
+ }
1007
+ return { directory: '/work', extensions: [], commands: [] };
1008
+ },
1009
+ };
1010
+ const app = express();
1011
+ app.use(express.json());
1012
+ registerPiRuntimeRoutes(app, { getPiSessionDaemonRuntime: () => runtime });
1013
+ server = await listen(app);
1014
+ const response = await fetch(`http://127.0.0.1:${server.address().port}/api/pi/commands?directory=/work`);
1015
+ expect(response.status).toBe(200);
1016
+ await expect(response.json()).resolves.toEqual({
1017
+ directory: '/work',
1018
+ commands: [
1019
+ { name: 'review', description: 'Review', source: 'prompt', scope: 'global' },
1020
+ { name: 'skill:code-review', description: 'Review', source: 'skill', scope: 'global' },
1021
+ ],
1022
+ });
1023
+ });
1024
+
1025
+ it('stores PiChamber snippets independently of Pi prompt templates', async () => {
1026
+ const snippets = [];
1027
+ const snippetsStore = {
1028
+ list: async (directory) => snippets.filter((snippet) => snippet.scope === 'global' || snippet.directory === directory),
1029
+ create: async (input) => {
1030
+ const snippet = { id: 'snippet-1', aliases: [], ...input };
1031
+ snippets.push(snippet);
1032
+ return snippets;
1033
+ },
1034
+ update: async (id, input) => {
1035
+ const snippet = snippets.find((entry) => entry.id === id);
1036
+ Object.assign(snippet, input);
1037
+ return snippets;
1038
+ },
1039
+ remove: async (id) => {
1040
+ const index = snippets.findIndex((entry) => entry.id === id);
1041
+ snippets.splice(index, 1);
1042
+ return snippets;
1043
+ },
1044
+ };
1045
+ const app = express();
1046
+ app.use(express.json());
1047
+ registerPiRuntimeRoutes(app, { getPiSessionDaemonRuntime: () => ({}), snippetsStore });
1048
+ server = await listen(app);
1049
+ const base = `http://127.0.0.1:${server.address().port}/api/pi/snippets`;
1050
+ await expect((await fetch(base)).json()).resolves.toEqual({ snippets: [] });
1051
+ const created = await fetch(base, {
1052
+ method: 'POST',
1053
+ headers: { 'Content-Type': 'application/json' },
1054
+ body: JSON.stringify({ name: 'note', content: 'Content', scope: 'global' }),
1055
+ });
1056
+ expect(created.status).toBe(201);
1057
+ await expect(created.json()).resolves.toEqual({
1058
+ snippets: [{ id: 'snippet-1', aliases: [], name: 'note', content: 'Content', scope: 'global' }],
1059
+ });
1060
+ const invalid = await fetch(base, {
1061
+ method: 'POST',
1062
+ headers: { 'Content-Type': 'application/json' },
1063
+ body: JSON.stringify({ name: 'bad name!', content: 'x', scope: 'global' }),
1064
+ });
1065
+ expect(invalid.status).toBe(400);
1066
+ });
1067
+
1068
+ it('renames snippets and moves scopes by opaque id', async () => {
1069
+ const calls = [];
1070
+ const snippetsStore = {
1071
+ list: async () => [],
1072
+ create: async () => [],
1073
+ update: async (id, input, directory) => {
1074
+ calls.push({ id, input, directory });
1075
+ return [];
1076
+ },
1077
+ remove: async () => [],
1078
+ };
1079
+ const app = express();
1080
+ app.use(express.json());
1081
+ registerPiRuntimeRoutes(app, { getPiSessionDaemonRuntime: () => ({}), snippetsStore });
1082
+ server = await listen(app);
1083
+ const base = `http://127.0.0.1:${server.address().port}/api/pi/snippets/s1?directory=/work`;
1084
+ const renamed = await fetch(base, {
1085
+ method: 'PUT', headers: { 'Content-Type': 'application/json' },
1086
+ body: JSON.stringify({ name: 'renamed', scope: 'project', directory: '/work', aliases: ['r'] }),
1087
+ });
1088
+ expect(renamed.status).toBe(200);
1089
+ expect(calls[0]).toMatchObject({ id: 's1', directory: '/work' });
1090
+ expect(calls[0].input).toMatchObject({ name: 'renamed', scope: 'project' });
1091
+ const bad = await fetch(base, {
1092
+ method: 'PUT', headers: { 'Content-Type': 'application/json' },
1093
+ body: JSON.stringify({ name: 'bad name!' }),
1094
+ });
1095
+ expect(bad.status).toBe(400);
1096
+ const oversized = await fetch(base, {
1097
+ method: 'PUT', headers: { 'Content-Type': 'application/json' },
1098
+ body: JSON.stringify({ content: 'x'.repeat(200_001) }),
1099
+ });
1100
+ expect([400, 413]).toContain(oversized.status);
1101
+ const invalidAliases = await fetch(base, {
1102
+ method: 'PUT', headers: { 'Content-Type': 'application/json' },
1103
+ body: JSON.stringify({ aliases: ['valid', 'bad alias'] }),
1104
+ });
1105
+ expect(invalidAliases.status).toBe(400);
1106
+ expect(calls).toHaveLength(1);
1107
+ });
1108
+
1109
+ it('carries explicit directories for prompt create, update, and delete', async () => {
1110
+ const calls = [];
1111
+ const runtime = {
1112
+ request: async (command, payload) => {
1113
+ calls.push({ command, payload });
1114
+ return { skills: [], prompts: [], agents: [] };
1115
+ },
1116
+ };
1117
+ const app = express();
1118
+ app.use(express.json());
1119
+ registerPiRuntimeRoutes(app, { getPiSessionDaemonRuntime: () => runtime });
1120
+ server = await listen(app);
1121
+ const base = `http://127.0.0.1:${server.address().port}/api/pi/resources/prompts`;
1122
+ const created = await fetch(`${base}?directory=/work`, {
1123
+ method: 'POST', headers: { 'Content-Type': 'application/json' },
1124
+ body: JSON.stringify({ name: 'review', description: 'Review', content: 'Do $1', location: 'global' }),
1125
+ });
1126
+ expect(created.status).toBe(201);
1127
+ const updated = await fetch(`${base}/prompt-1?directory=/work`, {
1128
+ method: 'PUT', headers: { 'Content-Type': 'application/json' },
1129
+ body: JSON.stringify({ name: 'review2', description: 'Updated' }),
1130
+ });
1131
+ expect(updated.status).toBe(200);
1132
+ const deleted = await fetch(`${base}/prompt-1?directory=/work`, { method: 'DELETE' });
1133
+ expect(deleted.status).toBe(200);
1134
+ expect(calls).toEqual([
1135
+ { command: 'resources.prompts.create', payload: { name: 'review', description: 'Review', content: 'Do $1', location: 'global', directory: '/work' } },
1136
+ { command: 'resources.prompts.update', payload: { resourceId: 'prompt-1', directory: '/work', name: 'review2', description: 'Updated' } },
1137
+ { command: 'resources.prompts.delete', payload: { resourceId: 'prompt-1', directory: '/work' } },
1138
+ ]);
1139
+ });
1140
+
1141
+ it('refreshes /commands after prompt mutations without stale entries', async () => {
1142
+ let prompts = [{ id: 'prompt-1', kind: 'prompt', name: 'review', description: 'Review', location: 'global', content: 'Do $1', editable: true }];
1143
+ const runtime = {
1144
+ request: async (command, payload) => {
1145
+ if (command === 'resources.list') {
1146
+ return { skills: [], prompts: [...prompts], agents: [] };
1147
+ }
1148
+ if (command === 'resources.prompts.create') {
1149
+ prompts.push({ id: 'prompt-2', kind: 'prompt', name: payload.name, description: payload.description, location: payload.location, content: payload.content, editable: true });
1150
+ return { skills: [], prompts: [...prompts], agents: [] };
1151
+ }
1152
+ if (command === 'resources.prompts.update') {
1153
+ prompts = prompts.map((p) => p.id === payload.resourceId ? { ...p, ...(payload.name ? { name: payload.name } : {}) } : p);
1154
+ return { skills: [], prompts: [...prompts], agents: [] };
1155
+ }
1156
+ if (command === 'resources.prompts.delete') {
1157
+ prompts = prompts.filter((p) => p.id !== payload.resourceId);
1158
+ return { skills: [], prompts: [...prompts], agents: [] };
1159
+ }
1160
+ if (command === 'extensions.list') {
1161
+ return { directory: '/work', extensions: [], commands: [] };
1162
+ }
1163
+ return { skills: [], prompts: [...prompts], agents: [] };
1164
+ },
1165
+ };
1166
+ const app = express();
1167
+ app.use(express.json());
1168
+ registerPiRuntimeRoutes(app, { getPiSessionDaemonRuntime: () => runtime });
1169
+ server = await listen(app);
1170
+ const api = `http://127.0.0.1:${server.address().port}/api/pi`;
1171
+ const commandsBefore = await (await fetch(`${api}/commands?directory=/work`)).json();
1172
+ expect(commandsBefore.commands.map((c) => c.name)).toContain('review');
1173
+ await fetch(`${api}/resources/prompts?directory=/work`, {
1174
+ method: 'POST', headers: { 'Content-Type': 'application/json' },
1175
+ body: JSON.stringify({ name: 'second', description: 'Second', content: 'Body', location: 'global' }),
1176
+ });
1177
+ const commandsAfterCreate = await (await fetch(`${api}/commands?directory=/work`)).json();
1178
+ expect(commandsAfterCreate.commands.map((c) => c.name).sort()).toEqual(['review', 'second']);
1179
+ await fetch(`${api}/resources/prompts/prompt-1?directory=/work`, {
1180
+ method: 'PUT', headers: { 'Content-Type': 'application/json' },
1181
+ body: JSON.stringify({ name: 'renamed' }),
1182
+ });
1183
+ const commandsAfterRename = await (await fetch(`${api}/commands?directory=/work`)).json();
1184
+ expect(commandsAfterRename.commands.map((c) => c.name)).toContain('renamed');
1185
+ expect(commandsAfterRename.commands.map((c) => c.name)).not.toContain('review');
1186
+ await fetch(`${api}/resources/prompts/prompt-2?directory=/work`, { method: 'DELETE' });
1187
+ const commandsAfterDelete = await (await fetch(`${api}/commands?directory=/work`)).json();
1188
+ expect(commandsAfterDelete.commands.map((c) => c.name)).not.toContain('second');
1189
+ });
877
1190
  });