@pi-chamber/web 0.7.1 → 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 (190) hide show
  1. package/README.md +2 -1
  2. package/bin/cli.js +2 -2
  3. package/bin/cli.test.js +98 -1
  4. package/bin/lib/DOCUMENTATION.md +2 -1
  5. package/bin/lib/cli-args.js +8 -5
  6. package/bin/lib/cli-startup.js +10 -7
  7. package/bin/lib/cli-startup.test.js +28 -0
  8. package/bin/lib/commands-startup.js +152 -6
  9. package/dist/assets/{DiagramEditor-C7xe1Brl.js → DiagramEditor-YPSKccgo.js} +1 -1
  10. package/dist/assets/DiagramView-C-PbBHce.js +1 -0
  11. package/dist/assets/DiffView-DfltyfN2.js +18 -0
  12. package/dist/assets/FilesView-BEjbLiK2.js +6 -0
  13. package/dist/assets/GitView-B_zTaXX4.js +8 -0
  14. package/dist/assets/JsonTreeView-9p4txyB_.js +1 -0
  15. package/dist/assets/MarkdownRendererImpl-CbRPLK2x.js +12 -0
  16. package/dist/assets/PatchDiff-rKjeUBRl.js +1 -0
  17. package/dist/assets/SessionSwitcherContent-C_VxKFJy.js +1 -0
  18. package/dist/assets/SessionSwitcherDropdown-_k4P32o9.js +2 -0
  19. package/dist/assets/SessionUnreadDot-bT_0MixU.js +1 -0
  20. package/dist/assets/SettingsView-CqZ1ZAWG.js +2 -0
  21. package/dist/assets/SettingsWindow-C7vVE35-.js +1 -0
  22. package/dist/assets/ToolOutputDialog-GBbzATa6.js +8 -0
  23. package/dist/assets/ToolPartDiffPreview-Bdb9p5uS.js +1 -0
  24. package/dist/assets/{VirtualizedFileDiff-DFx8xsmh.js → VirtualizedFileDiff-CA8hQyz9.js} +4 -4
  25. package/dist/assets/{Virtualizer-BxW2CJGB.js → Virtualizer-BSHVMKgK.js} +1 -1
  26. package/dist/assets/{appThemeRegistry-BK0dHKa6.js → appThemeRegistry-gegrE2dq.js} +1 -1
  27. package/dist/assets/collapsible-uwSKBy-K.js +1 -0
  28. package/dist/assets/computeVirtualFileMetrics-9LNCLvAG.js +3 -0
  29. package/dist/assets/contextFileOpenGuard-CZSqdEHk.js +1 -0
  30. package/dist/assets/gitStatusPredicates-CRmbLl-x.js +134 -0
  31. package/dist/assets/index-BeJEipxi.js +1 -0
  32. package/dist/assets/index-CaP8oFLB.js +8 -0
  33. package/dist/assets/index-Dq8CnRYM.css +1 -0
  34. package/dist/assets/isDiffPlainText-YYyZNTdb.js +1 -0
  35. package/dist/assets/isFilePlainText-C70Z71bG.js +1 -0
  36. package/dist/assets/main-CsdVAKy_.js +135 -0
  37. package/dist/assets/main-GMQIZjuQ.js +2 -0
  38. package/dist/assets/{markdownCore-CzWR_p3k.js → markdownCore-BgVcDt0q.js} +2 -2
  39. package/dist/assets/miniChat-W6YsdiWR.js +2 -0
  40. package/dist/assets/mobile-BFR9CR5w.js +2 -0
  41. package/dist/assets/{permissionStore-BRcQ9Jgt.js → permissionStore-iKN1K2_x.js} +1 -1
  42. package/dist/assets/registerCustomTheme-DmolaWWZ.js +1 -0
  43. package/dist/assets/renderElectronMiniChatApp-B8ZiW-3E.js +2 -0
  44. package/dist/assets/renderMobileApp-C5CdsYP6.js +11 -0
  45. package/dist/assets/runtimeEndpointReset-D3AZYuoF.js +54 -0
  46. package/dist/assets/{runtimeSurface-OhCUGSKg.js → runtimeSurface-B818u-_c.js} +1 -1
  47. package/dist/assets/themeResolver-yJ9XpNMI.js +1 -0
  48. package/dist/assets/{WindowsWindowControls-DIqnZ2uU.js → useAppFontEffects-CYzYRbLp.js} +126 -499
  49. package/dist/assets/useFilesViewSearch-C--GWtn-.js +7 -0
  50. package/dist/assets/usePushVisibilityBeacon-D9lajdAc.js +10 -0
  51. package/dist/assets/useSwitcherItems-DOoi3x_8.js +1 -0
  52. package/dist/assets/vendor-base-ui-vkqQ2P9o.js +1 -0
  53. package/dist/assets/{vendor-beautiful-mermaid-r4GK_usS.js → vendor-beautiful-mermaid-DneUawHp.js} +1 -1
  54. package/dist/assets/{vendor-cmdk-BCEUzcHE.js → vendor-cmdk-zXx6sGnS.js} +1 -1
  55. package/dist/assets/{vendor-codemirror-autocomplete-BS2SpSAZ.js → vendor-codemirror-autocomplete-wd6iRebq.js} +1 -1
  56. package/dist/assets/{vendor-codemirror-commands-RrgJ8H_6.js → vendor-codemirror-commands-DYppkHEk.js} +1 -1
  57. package/dist/assets/{vendor-codemirror-lang-angular-ADhO_TUK.js → vendor-codemirror-lang-angular-DU_4KiiW.js} +1 -1
  58. package/dist/assets/{vendor-codemirror-lang-cpp-BGCWj7Om.js → vendor-codemirror-lang-cpp-CmIT9Z5_.js} +1 -1
  59. package/dist/assets/{vendor-codemirror-lang-css-Ba8JZ6fp.js → vendor-codemirror-lang-css-djiuoTi8.js} +1 -1
  60. package/dist/assets/{vendor-codemirror-lang-go-DyTiHXo4.js → vendor-codemirror-lang-go-COZSwZYW.js} +1 -1
  61. package/dist/assets/{vendor-codemirror-lang-html-DK27qQri.js → vendor-codemirror-lang-html-CKHqhW5R.js} +1 -1
  62. package/dist/assets/{vendor-codemirror-lang-java-CvFfnhPQ.js → vendor-codemirror-lang-java-CNMP5hyC.js} +1 -1
  63. package/dist/assets/{vendor-codemirror-lang-javascript-BUlYhQ3o.js → vendor-codemirror-lang-javascript-DuOEwJ3f.js} +1 -1
  64. package/dist/assets/{vendor-codemirror-lang-jinja-wBMtAEvT.js → vendor-codemirror-lang-jinja-DaKn_b1k.js} +1 -1
  65. package/dist/assets/{vendor-codemirror-lang-json-CqayksDf.js → vendor-codemirror-lang-json-CZ07HmNC.js} +1 -1
  66. package/dist/assets/{vendor-codemirror-lang-less-Ct3-H1PB.js → vendor-codemirror-lang-less-wJdQiDBf.js} +1 -1
  67. package/dist/assets/{vendor-codemirror-lang-liquid-XspREksq.js → vendor-codemirror-lang-liquid-0z48Roi8.js} +1 -1
  68. package/dist/assets/{vendor-codemirror-lang-markdown-CvO36Y1p.js → vendor-codemirror-lang-markdown-DtcZDGqe.js} +1 -1
  69. package/dist/assets/{vendor-codemirror-lang-php-BlUF9cCe.js → vendor-codemirror-lang-php-W8plS-JQ.js} +1 -1
  70. package/dist/assets/{vendor-codemirror-lang-python-_2bIYTiJ.js → vendor-codemirror-lang-python-DzzokVau.js} +1 -1
  71. package/dist/assets/{vendor-codemirror-lang-rust-BdTYih_U.js → vendor-codemirror-lang-rust-C4ulBVpf.js} +1 -1
  72. package/dist/assets/{vendor-codemirror-lang-sass-E6MhfOFk.js → vendor-codemirror-lang-sass-BkZJYEwS.js} +1 -1
  73. package/dist/assets/{vendor-codemirror-lang-sql-B1BRhQSF.js → vendor-codemirror-lang-sql-HpQWHJjv.js} +1 -1
  74. package/dist/assets/{vendor-codemirror-lang-vue-BYQJRa1Q.js → vendor-codemirror-lang-vue-DiBPljCc.js} +1 -1
  75. package/dist/assets/{vendor-codemirror-lang-wast-D706yuyC.js → vendor-codemirror-lang-wast-DoABsogh.js} +1 -1
  76. package/dist/assets/{vendor-codemirror-lang-xml--MfWU6Dj.js → vendor-codemirror-lang-xml-BhLJhOCH.js} +1 -1
  77. package/dist/assets/{vendor-codemirror-lang-yaml-CRUFIbRX.js → vendor-codemirror-lang-yaml-D95i1Y5R.js} +1 -1
  78. package/dist/assets/{vendor-codemirror-language-E2vgV9K3.js → vendor-codemirror-language-BByA_dGF.js} +2 -2
  79. package/dist/assets/{vendor-codemirror-language-data-Dv4zaHRN.js → vendor-codemirror-language-data-DS_4W5G4.js} +2 -2
  80. package/dist/assets/{vendor-codemirror-search-8kyQdB3f.js → vendor-codemirror-search-BV44140v.js} +1 -1
  81. package/dist/assets/{vendor-codemirror-view-DSzLbZiS.js → vendor-codemirror-view-Ct4T37Ue.js} +1 -1
  82. package/dist/assets/{vendor-dnd-kit-accessibility-Cv52zwWT.js → vendor-dnd-kit-accessibility-DZKKhs9S.js} +1 -1
  83. package/dist/assets/{vendor-dnd-kit-core-GipZW2tY.js → vendor-dnd-kit-core-CP8ck10N.js} +1 -1
  84. package/dist/assets/{vendor-dnd-kit-sortable-Ct2QxIHb.js → vendor-dnd-kit-sortable-B-Icjoj4.js} +1 -1
  85. package/dist/assets/{vendor-dnd-kit-utilities-CrOcp0Bp.js → vendor-dnd-kit-utilities-DTY1C6ST.js} +1 -1
  86. package/dist/assets/{vendor-elkjs-CRCLNXjf.js → vendor-elkjs-mzfkf0ML.js} +1 -1
  87. package/dist/assets/{vendor-floating-ui-dom-Bkw82kL9.js → vendor-floating-ui-dom-WyXykhNi.js} +1 -1
  88. package/dist/assets/{vendor-floating-ui-react-dom-sVFnuruh.js → vendor-floating-ui-react-dom-BZOGXAGe.js} +1 -1
  89. package/dist/assets/{vendor-framer-motion-DJASDzNt.js → vendor-framer-motion-BUygY0oN.js} +1 -1
  90. package/dist/assets/{vendor-heic2any-L8hyfc24.js → vendor-heic2any-BHsbokcA.js} +1 -1
  91. package/dist/assets/{vendor-lru_map-B-cPXHXW.js → vendor-lru_map-Cy8fTs3_.js} +1 -1
  92. package/dist/assets/{vendor-pierre-theming-C6Z4M5_u.js → vendor-pierre-theming-Dgp7B_O4.js} +1 -1
  93. package/dist/assets/{vendor-qrcode-COsmt6jn.js → vendor-qrcode-B0KNSajT.js} +1 -1
  94. package/dist/assets/{vendor-radix-ui-react-compose-refs-D1GnwnP9.js → vendor-radix-ui-react-compose-refs-8xy6TJML.js} +1 -1
  95. package/dist/assets/{vendor-radix-ui-react-context-CM4yFQ2I.js → vendor-radix-ui-react-context-CFsX-AUC.js} +1 -1
  96. package/dist/assets/{vendor-radix-ui-react-dialog-jX3Dld8c.js → vendor-radix-ui-react-dialog-D2yhEu2p.js} +1 -1
  97. package/dist/assets/{vendor-radix-ui-react-dismissable-layer-M7LsH3yL.js → vendor-radix-ui-react-dismissable-layer-DrorBNg9.js} +1 -1
  98. package/dist/assets/{vendor-radix-ui-react-focus-guards-D5MZ0nQs.js → vendor-radix-ui-react-focus-guards-BfdFmL7c.js} +1 -1
  99. package/dist/assets/{vendor-radix-ui-react-focus-scope-C2K7lNPv.js → vendor-radix-ui-react-focus-scope-D2BkImwt.js} +1 -1
  100. package/dist/assets/{vendor-radix-ui-react-id-BcxRjnbX.js → vendor-radix-ui-react-id-D2kS9K1j.js} +1 -1
  101. package/dist/assets/vendor-radix-ui-react-portal-YgCRIyi7.js +1 -0
  102. package/dist/assets/{vendor-radix-ui-react-presence-Btn-Dp7L.js → vendor-radix-ui-react-presence-D432pCMB.js} +1 -1
  103. package/dist/assets/{vendor-radix-ui-react-primitive-CfpW6_IT.js → vendor-radix-ui-react-primitive-DkH8dMOR.js} +1 -1
  104. package/dist/assets/{vendor-radix-ui-react-slot-BxUc3Pvz.js → vendor-radix-ui-react-slot-BIDFZX0-.js} +1 -1
  105. package/dist/assets/{vendor-radix-ui-react-use-callback-ref-UKEWHtoP.js → vendor-radix-ui-react-use-callback-ref-BwDcSoGV.js} +1 -1
  106. package/dist/assets/{vendor-radix-ui-react-use-controllable-state-C_ecoh35.js → vendor-radix-ui-react-use-controllable-state-LiqmKSXO.js} +1 -1
  107. package/dist/assets/vendor-radix-ui-react-use-effect-event-D94va83M.js +1 -0
  108. package/dist/assets/{vendor-radix-ui-react-use-escape-keydown-Co13lHGj.js → vendor-radix-ui-react-use-escape-keydown-DTkqjenV.js} +1 -1
  109. package/dist/assets/vendor-radix-ui-react-use-layout-effect-C8Yrsaph.js +1 -0
  110. package/dist/assets/{vendor-react-DYyjh7Q0.js → vendor-react-B5Z1Mdn3.js} +1 -1
  111. package/dist/assets/{vendor-react-drawio-Boqanm0j.js → vendor-react-drawio-BYDptOsj.js} +1 -1
  112. package/dist/assets/{vendor-react-remove-scroll-bar-C9YRs2nU.js → vendor-react-remove-scroll-bar-CSAHp1YF.js} +1 -1
  113. package/dist/assets/{vendor-react-remove-scroll-CfeMe0DL.js → vendor-react-remove-scroll-vR1dy1aP.js} +1 -1
  114. package/dist/assets/{vendor-react-style-singleton-B1H4bWSG.js → vendor-react-style-singleton-Ctw6HnYx.js} +1 -1
  115. package/dist/assets/{vendor-replit-codemirror-vim-BJY5fGLS.js → vendor-replit-codemirror-vim-CGHHNQxC.js} +1 -1
  116. package/dist/assets/{vendor-sonner-CW8w438f.js → vendor-sonner-BDtm25td.js} +1 -1
  117. package/dist/assets/{vendor-tanstack-react-virtual-IrbCBGJ4.js → vendor-tanstack-react-virtual-2skouoFw.js} +1 -1
  118. package/dist/assets/{vendor-use-callback-ref-CJB0R85I.js → vendor-use-callback-ref-CVVuCyLj.js} +1 -1
  119. package/dist/assets/{vendor-use-sidecar-C-AuTczP.js → vendor-use-sidecar-Vv4V8Nd1.js} +1 -1
  120. package/dist/assets/{vendor-use-sync-external-store-B7OScDIw.js → vendor-use-sync-external-store-D0AXkdQC.js} +1 -1
  121. package/dist/assets/{vendor-zustand-CnsBKjP5.js → vendor-zustand-GVb4H8HE.js} +1 -1
  122. package/dist/assets/{web-components-BOt08OHk.js → web-components-C2cMNPqE.js} +2 -2
  123. package/dist/index.html +6 -6
  124. package/dist/mini-chat.html +5 -5
  125. package/dist/mobile.html +5 -5
  126. package/package.json +1 -1
  127. package/server/lib/git/DOCUMENTATION.md +3 -2
  128. package/server/lib/git/routes.js +27 -0
  129. package/server/lib/git/routes.test.js +41 -0
  130. package/server/lib/git/service.js +7 -1
  131. package/server/lib/git/service.test.js +23 -0
  132. package/server/lib/package-manager.js +32 -1
  133. package/server/lib/package-manager.test.js +21 -0
  134. package/server/lib/pi/attachment-store.js +95 -22
  135. package/server/lib/pi/attachment-store.test.js +23 -0
  136. package/server/lib/pi/routes.js +383 -49
  137. package/server/lib/pi/routes.test.js +377 -3
  138. package/server/lib/pi/session-daemon/DOCUMENTATION.md +3 -3
  139. package/server/lib/pi/session-daemon/prompt-operations.test.js +318 -0
  140. package/server/lib/pi/session-daemon/session-daemon-extensions.test.js +2 -0
  141. package/server/lib/pi/session-daemon/session-daemon.js +316 -25
  142. package/server/lib/pi/session-daemon/session-daemon.test.js +137 -0
  143. package/server/lib/pi/session-daemon/supervisor.test.js +1 -1
  144. package/server/lib/pi/snippets-store.js +400 -0
  145. package/server/lib/pi/snippets-store.test.js +252 -0
  146. package/server/lib/relay/host-client.test.js +79 -15
  147. package/server/lib/server/cors.js +2 -0
  148. package/server/lib/server/cors.test.js +6 -5
  149. package/dist/assets/CommitSection-DuGkZ_bm.js +0 -1
  150. package/dist/assets/DiagramView-BTqROEWP.js +0 -1
  151. package/dist/assets/DiffView-hcqXTjEc.js +0 -18
  152. package/dist/assets/FilesView-GadyKxta.js +0 -14
  153. package/dist/assets/GitView-BKy-hYUN.js +0 -6
  154. package/dist/assets/JsonTreeView-CGc4eTGI.js +0 -1
  155. package/dist/assets/MarkdownRendererImpl-CqfEAhPM.js +0 -12
  156. package/dist/assets/PatchDiff-P17-Byb8.js +0 -1
  157. package/dist/assets/PierreDiffViewer-BbUCO4IF.js +0 -136
  158. package/dist/assets/SessionSwitcherContent-j6KFBSe0.js +0 -1
  159. package/dist/assets/SessionSwitcherDropdown-DSVeuuVL.js +0 -2
  160. package/dist/assets/SessionUnreadDot-BVBBEBTg.js +0 -1
  161. package/dist/assets/SettingsView-FnmtcWZc.js +0 -4
  162. package/dist/assets/SettingsWindow-Bascj0V3.js +0 -1
  163. package/dist/assets/ToolOutputDialog-CPMzJ27S.js +0 -15
  164. package/dist/assets/ToolPartDiffPreview-BZSRKHHM.js +0 -8
  165. package/dist/assets/collapsible-DlqZyxEY.js +0 -1
  166. package/dist/assets/computeVirtualFileMetrics-elCbdk6U.js +0 -3
  167. package/dist/assets/contextFileOpenGuard-BmQ7Zu-L.js +0 -1
  168. package/dist/assets/index-BerHSX92.js +0 -1
  169. package/dist/assets/index-ChFxkws4.js +0 -8
  170. package/dist/assets/index-DZ-f_hCQ.css +0 -1
  171. package/dist/assets/isDiffPlainText-CvfRfc7h.js +0 -1
  172. package/dist/assets/isFilePlainText-_vq9Ghu3.js +0 -1
  173. package/dist/assets/main-DTCOwPr3.js +0 -2
  174. package/dist/assets/main-DYs-nZO6.js +0 -133
  175. package/dist/assets/miniChat-C2XxEA3N.js +0 -2
  176. package/dist/assets/mobile-BQhAOqV7.js +0 -2
  177. package/dist/assets/registerCustomTheme-BBXUCRnG.js +0 -1
  178. package/dist/assets/renderElectronMiniChatApp-M2bY1WKA.js +0 -2
  179. package/dist/assets/renderMobileApp-BnpHUUhY.js +0 -14
  180. package/dist/assets/themeResolver-BmJyTmjJ.js +0 -1
  181. package/dist/assets/useInlineCommentController-DC0iNSYX.js +0 -2
  182. package/dist/assets/usePanelSlide-aeAIo1cp.js +0 -56
  183. package/dist/assets/usePushVisibilityBeacon-om5Qlrt6.js +0 -10
  184. package/dist/assets/useSwitcherItems-Bln2r_Q2.js +0 -1
  185. package/dist/assets/vendor-base-ui-DL8r2fgQ.js +0 -1
  186. package/dist/assets/vendor-radix-ui-react-portal-xlJWBfDg.js +0 -1
  187. package/dist/assets/vendor-radix-ui-react-use-effect-event-DkJl_Rn_.js +0 -1
  188. package/dist/assets/vendor-radix-ui-react-use-layout-effect-0fyGwS2_.js +0 -1
  189. package/dist/assets/vendor-remixicon-react-CzPq62YO.js +0 -1
  190. /package/dist/assets/{usePanelSlide-BV3KOtdA.css → runtimeEndpointReset-BV3KOtdA.css} +0 -0
@@ -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;
@@ -84,6 +114,8 @@ describe('Pi runtime route', () => {
84
114
  },
85
115
  listCustomThemes: async () => [{ metadata: { id: 'custom' } }],
86
116
  updateChecker: async () => ({ available: false, currentVersion: '1.0.0' }),
117
+ resolveUpdatePackageManager: () => 'npm',
118
+ updateLauncher: () => ({ success: true }),
87
119
  });
88
120
  server = await listen(app);
89
121
  const base = `http://127.0.0.1:${server.address().port}`;
@@ -98,6 +130,26 @@ describe('Pi runtime route', () => {
98
130
  })).json()).resolves.toEqual({ exists: true, version: 1, foldersMap: {}, collapsedFolderIds: [], updatedAt: 1 });
99
131
  await expect((await fetch(`${base}/api/pi/themes`)).json()).resolves.toEqual({ themes: [{ metadata: { id: 'custom' } }] });
100
132
  await expect((await fetch(`${base}/api/pi/update-check`)).json()).resolves.toEqual({ available: false, currentVersion: '1.0.0' });
133
+ const installResponse = await fetch(`${base}/api/pi/update-install`, { method: 'POST' });
134
+ expect(installResponse.status).toBe(200);
135
+ await expect(installResponse.json()).resolves.toEqual({ success: true, autoRestart: true });
136
+ });
137
+
138
+ it('rejects web updates when the current install is not owned by a trusted package manager', async () => {
139
+ const app = express();
140
+ registerPiRuntimeRoutes(app, {
141
+ getPiSessionDaemonRuntime: () => null,
142
+ resolveUpdatePackageManager: () => null,
143
+ updateLauncher: () => { throw new Error('must not run'); },
144
+ });
145
+ server = await listen(app);
146
+
147
+ const response = await fetch(`http://127.0.0.1:${server.address().port}/api/pi/update-install`, { method: 'POST' });
148
+ expect(response.status).toBe(409);
149
+ await expect(response.json()).resolves.toEqual({
150
+ success: false,
151
+ error: 'This PiChamber copy is not a supported global package-manager install. Run: pichamber update',
152
+ });
101
153
  });
102
154
 
103
155
  it('generates a task name with the configured small model without exposing model details', async () => {
@@ -307,7 +359,7 @@ describe('Pi runtime route', () => {
307
359
  it('uploads opaque attachments and resolves them only across the private prompt adapter', async () => {
308
360
  const calls = [];
309
361
  const attachmentStore = {
310
- create: async (input) => ({ id: 'attachment-1', name: input.filename, mime: input.mime, size: 3, path: '/never-public' }),
362
+ create: async (input) => ({ id: 'attachment-1', name: input.filename, mime: input.mime, size: 3, expiresAt: 3_600_000, path: '/never-public' }),
311
363
  resolve: async (ids) => {
312
364
  expect(ids).toEqual(['attachment-1']);
313
365
  return [{ id: 'attachment-1', name: 'note.txt', mime: 'text/plain', size: 3, path: '/private/upload' }];
@@ -327,12 +379,49 @@ describe('Pi runtime route', () => {
327
379
 
328
380
  const upload = await fetch(`${base}/attachments`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ filename: 'note.txt', mime: 'text/plain', base64: 'YWJj' }) });
329
381
  expect(upload.status).toBe(201);
330
- await expect(upload.json()).resolves.toEqual({ attachment: { id: 'attachment-1', name: 'note.txt', mime: 'text/plain', size: 3 } });
382
+ await expect(upload.json()).resolves.toEqual({ attachment: { id: 'attachment-1', name: 'note.txt', mime: 'text/plain', size: 3, expiresAt: 3_600_000 } });
331
383
  const prompt = await fetch(`${base}/sessions/session-1/prompt`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ text: 'read this', attachments: [{ id: 'attachment-1' }] }) });
332
384
  expect(prompt.status).toBe(202);
333
385
  expect(calls).toEqual([{ command: 'sessions.prompt', payload: { sessionId: 'session-1', text: 'read this', attachments: [{ id: 'attachment-1', name: 'note.txt', mime: 'text/plain', size: 3, path: '/private/upload' }] } }]);
334
386
  });
335
387
 
388
+ it('streams binary attachments with bounded metadata and deletes unused uploads', async () => {
389
+ const calls = [];
390
+ const attachmentStore = {
391
+ createFromStream: async ({ filename, mime, stream }) => {
392
+ const chunks = [];
393
+ for await (const chunk of stream) chunks.push(chunk);
394
+ calls.push({ filename, mime, body: Buffer.concat(chunks).toString('utf8') });
395
+ return { id: 'binary-1', name: filename, mime, size: 5, expiresAt: 4_000 };
396
+ },
397
+ remove: async (id) => calls.push({ removed: id }),
398
+ };
399
+ const app = express();
400
+ app.use(express.json());
401
+ registerPiRuntimeRoutes(app, { getPiSessionDaemonRuntime: () => null, attachmentStore });
402
+ server = await listen(app);
403
+ const base = `http://127.0.0.1:${server.address().port}/api/pi/attachments`;
404
+
405
+ const upload = await fetch(base, {
406
+ method: 'POST',
407
+ headers: {
408
+ 'Content-Type': 'application/octet-stream',
409
+ 'X-PiChamber-Filename': encodeURIComponent('notes ü.txt'),
410
+ 'X-PiChamber-Mime': 'text/plain',
411
+ },
412
+ body: 'hello',
413
+ });
414
+ expect(upload.status).toBe(201);
415
+ await expect(upload.json()).resolves.toEqual({
416
+ attachment: { id: 'binary-1', name: 'notes ü.txt', mime: 'text/plain', size: 5, expiresAt: 4_000 },
417
+ });
418
+ expect((await fetch(`${base}/binary-1`, { method: 'DELETE' })).status).toBe(204);
419
+ expect(calls).toEqual([
420
+ { filename: 'notes ü.txt', mime: 'text/plain', body: 'hello' },
421
+ { removed: 'binary-1' },
422
+ ]);
423
+ });
424
+
336
425
  it('proxies a cwd-scoped session collection without exposing private daemon details', async () => {
337
426
  const runtime = {
338
427
  health: async () => ({ state: 'ready', protocolVersion: 1, capabilities: ['sessions.list'] }),
@@ -452,6 +541,7 @@ describe('Pi runtime route', () => {
452
541
  isStreaming: true,
453
542
  lifecycle: 'retry',
454
543
  retry: { attempt: 2, next: 5_000, message: 'provider request timed out' },
544
+ extensionStatuses: [{ key: 'mode', text: 'mode:economy/xhigh' }],
455
545
  };
456
546
  const runtime = {
457
547
  health: async () => ({ state: 'ready', protocolVersion: 1, capabilities: [] }),
@@ -479,6 +569,7 @@ describe('Pi runtime route', () => {
479
569
  isStreaming: true,
480
570
  lifecycle: 'retry',
481
571
  retry: { attempt: 2, next: 5_000, message: 'provider request timed out' },
572
+ extensionStatuses: [{ key: 'mode', text: 'mode:economy/xhigh' }],
482
573
  });
483
574
  const promptResponse = await fetch(`http://127.0.0.1:${server.address().port}/api/pi/sessions/pi-session-4/prompt`, {
484
575
  method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ sessionId: 'other', text: 'hello' }),
@@ -536,6 +627,56 @@ describe('Pi runtime route', () => {
536
627
  }
537
628
  });
538
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
+
539
680
  it('rejects unauthenticated requests before the Pi adapters run', async () => {
540
681
  let invoked = false;
541
682
  const app = express();
@@ -813,4 +954,237 @@ describe('Pi runtime route', () => {
813
954
  expect(response.status).toBe(503);
814
955
  await expect(response.json()).resolves.toEqual({ error: { code: 'DAEMON_LOCK_UNAVAILABLE' } });
815
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
+ });
816
1190
  });
@@ -10,7 +10,7 @@ This module is the Pi-owned session-daemon foundation. A detached local daemon p
10
10
  - `extension-bridge.js` owns extension UI bindings, pending dialog lifecycle, normalized status/widget/panel/app state, snapshot projection, and extension event publication. `session-daemon.js` supplies runtime lookup, publication, redaction, and directory dependencies through its narrow factory interface.
11
11
  - `session-daemon.js`
12
12
  - `createPiSessionRuntime({ cwd, agentDir })` creates a persistent Pi runtime using the selected server-side cwd and Pi agent directory. It uses Pi's normal settings, credentials, models, sessions, skills, prompts, context discovery, and native extensions. Every runtime creation binds extensions through `session.bindExtensions()` in rpc-like mode with a daemon-owned UI bridge, so pi extensions load exactly as they do under the Pi CLI's RPC mode. Sessions created outside PiChamber (Pi CLI or any other writer of the cwd-scoped JSONL directory) are the same records: `sessions.list`/`open` hydrate from `getEntries()`, then overlay the live `session.messages` / `state.streamingMessage` turn while `isStreaming` is true, including an unpersisted user prompt that has not flushed to JSONL yet. A later prompt must overlay live turns onto that log rather than replace it. An unmatched `toolCall` projects as `running` only while `isStreaming` is authoritative; the same unmatched call in an idle persisted turn projects as a timestamped interruption error instead of malformed `completed` state. `getSession` also reports `isStreaming` and `lifecycle` so a restarted UI can restore the working/tooling state without waiting for the next token.
13
- - Extension bridging: blocking dialogs (`ctx.ui.select/confirm/input/editor`, plus the PiChamber-specific `ctx.ui.form` which resolves with a values object keyed by field id) publish an `extension.dialog` event and stay pending until answered by the `extensions.respond` private command; every answer, timeout, abort, session close, or daemon stop publishes an authoritative `extension.dialog.dismiss` event before resolving the extension so every connected client removes the modal (timeouts resolve defaults, abort resolves cancellation, form answers travel as a sanitized `values` record and are rejected unless required fields, number bounds, select options, and checkbox values match the pending form); fire-and-forget calls publish `extension.notify`, `extension.status`, `extension.widget`, session-scoped `extension.editor`, and `extension.title`; extension errors publish `extension.error`; appended custom entries and displayed custom messages publish `extension.entry` / `extension.message`. `pichamber.ui` entries with a stable `id` are additionally mirrored into normalized `extension.ui` panel events (latest wins per id, `removed: true` unregisters) and `pichamber.app` entries into sandboxed `extension.app` app surfaces; both are kept in per-session maps and replayed through `session.snapshot` so reconnects rebuild live panels. TUI-only component replacement, footers, and themes remain intentional no-ops; standard RPC editor replacement and window titles are projected to the focused browser session. Pending dialogs are cancelled when the owning runtime hits idle disposal or daemon stop so no extension thread blocks forever. Unknown dialog responses return `{ resolved: false }` rather than throwing so a stale client retry cannot tear down the shared socket.
13
+ - Extension bridging: blocking dialogs (`ctx.ui.select/confirm/input/editor`, plus the PiChamber-specific `ctx.ui.form` which resolves with a values object keyed by field id) publish an `extension.dialog` event and stay pending until answered by the `extensions.respond` private command; every answer, timeout, abort, session close, or daemon stop publishes an authoritative `extension.dialog.dismiss` event before resolving the extension so every connected client removes the modal (timeouts resolve defaults, abort resolves cancellation, form answers travel as a sanitized `values` record and are rejected unless required fields, number bounds, select options, and checkbox values match the pending form); fire-and-forget calls publish `extension.notify`, `extension.status`, `extension.widget`, session-scoped `extension.editor`, and `extension.title`; extension errors publish `extension.error`; appended custom entries and displayed custom messages publish `extension.entry` / `extension.message`. `pichamber.ui` entries with a stable `id` are additionally mirrored into normalized `extension.ui` panel events (latest wins per id, `removed: true` unregisters) and `pichamber.app` entries into sandboxed `extension.app` app surfaces; extension live state is kept in per-session maps and included in both `sessions.open` and `session.snapshot`. The open response must cover every extension event at or below its `lastSequence`, so first attach cannot skip one-time startup statuses before the browser stream connects; reconnect snapshots rebuild the same live panels. TUI-only component replacement, footers, and themes remain intentional no-ops; standard RPC editor replacement and window titles are projected to the focused browser session. Pending dialogs are cancelled when the owning runtime hits idle disposal or daemon stop so no extension thread blocks forever. Unknown dialog responses return `{ resolved: false }` rather than throwing so a stale client retry cannot tear down the shared socket.
14
14
  - `createSessionDaemon(options)` starts/stops the authenticated local socket daemon and validates its endpoint and setup inputs.
15
15
  - `daemon-process.js` is the detached private-process entrypoint. It reads the daemon credential from its owner-only sidecar, starts the socket, writes non-secret identity state only after readiness, and removes only its own state on signal shutdown.
16
16
  - `ipc-client.js` is the server-only authenticated request client. It owns JSONL framing and never exposes endpoint or credential values to callers.
@@ -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.