@pi-chamber/web 1.0.7 → 1.0.8-rc.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 (212) hide show
  1. package/dist/assets/AgentsSurface-BmHImX8m.js +1 -0
  2. package/dist/assets/ChoicesArtifact-C71fGOm2.js +1 -0
  3. package/dist/assets/DiagramView-BZQxoiZu.js +1 -0
  4. package/dist/assets/{DiffView-BxW6BuOC.js → DiffView-C70pbgk-.js} +6 -6
  5. package/dist/assets/FileSaveConflictDialog-Cu8c3gBV.js +3 -0
  6. package/dist/assets/FilesView-nFJYEdRw.js +6 -0
  7. package/dist/assets/GitHubDetailScaffold-Jvv_tgbl.js +11 -0
  8. package/dist/assets/GitHubLinkPicker-BXD2ODRi.js +1 -0
  9. package/dist/assets/GitHubListPrimitives-BWI706F0.js +1 -0
  10. package/dist/assets/{GitView-DD33ngnM.js → GitView-MIDG5RYW.js} +5 -5
  11. package/dist/assets/{IssuesSurface-BAY_eyX5.js → IssuesSurface-uNlozeu0.js} +2 -2
  12. package/dist/assets/{JsonTreeView-DpXbUrAl.js → JsonTreeView-CSLsTriz.js} +1 -1
  13. package/dist/assets/{MarkdownRendererImpl-Cn63lAmn.js → MarkdownRendererImpl-Cs-7BfWi.js} +3 -3
  14. package/dist/assets/PatchDiff-axbsnbTJ.js +1 -0
  15. package/dist/assets/PierreDiffViewer-lwn6w_5w.js +147 -0
  16. package/dist/assets/PullRequestsSurface-o_AXDjbO.js +2 -0
  17. package/dist/assets/{SessionSwitcherContent-CscYekC1.js → SessionSwitcherContent-C4CMlcbv.js} +1 -1
  18. package/dist/assets/SessionSwitcherDropdown-DCBVuCoo.js +2 -0
  19. package/dist/assets/SessionUnreadDot-DyeIrsro.js +1 -0
  20. package/dist/assets/SettingsView-BHBpt2Um.js +7 -0
  21. package/dist/assets/{SettingsWindow-gxjULdm1.js → SettingsWindow-Cb4st5y5.js} +1 -1
  22. package/dist/assets/{StickyHorizontalScrollbar-DNsbTLS7.js → StickyHorizontalScrollbar-CMbTn5WQ.js} +1 -1
  23. package/dist/assets/SubagentsArtifact-BzeMEoFP.js +1 -0
  24. package/dist/assets/ToolOutputDialog-BP2mOWdV.js +8 -0
  25. package/dist/assets/ToolPartDiffPreview-D49XBR9b.js +1 -0
  26. package/dist/assets/{VirtualizedFileDiff-BrbPymTL.js → VirtualizedFileDiff-CLgDONEQ.js} +4 -4
  27. package/dist/assets/{Virtualizer-okhy9Aq3.js → Virtualizer-PxblpQn6.js} +1 -1
  28. package/dist/assets/VisualFrame-CJrAvWSo.js +22 -0
  29. package/dist/assets/VisualsArtifact-DqLGgU-Q.js +1 -0
  30. package/dist/assets/{collapsible-D6qdoq7-.js → collapsible-BeyKtQGB.js} +1 -1
  31. package/dist/assets/{computeVirtualFileMetrics-G4csGiKs.js → computeVirtualFileMetrics-DmO6H8u6.js} +2 -2
  32. package/dist/assets/contextFileOpenGuard-DOK251YW.js +1 -0
  33. package/dist/assets/{fileTreeStatus-Bskhj4qT.js → fileTreeStatus-CnzR7kxA.js} +2 -2
  34. package/dist/assets/gitStatusPredicates-4kPg2t6j.js +1 -0
  35. package/dist/assets/githubLink-QvaLfNNT.js +10 -0
  36. package/dist/assets/{index-I2QYqABE.js → index-B2v0_mez.js} +8 -8
  37. package/dist/assets/index-D3F4JrPN.css +1 -0
  38. package/dist/assets/{index-ComwtfT4.js → index-DMX9wT1Z.js} +1 -1
  39. package/dist/assets/{main-DoiadX0a.js → main-BW9J3Y72.js} +2 -2
  40. package/dist/assets/main-BirYxac2.js +137 -0
  41. package/dist/assets/{markdownCore-DczkEluO.js → markdownCore-CxmcPur8.js} +2 -2
  42. package/dist/assets/miniChat-BRB11eEs.js +2 -0
  43. package/dist/assets/{mobile-BucKVm1P.js → mobile-DJZYYCuB.js} +2 -2
  44. package/dist/assets/{nativeFileSave-Cp9i5QGd.js → nativeFileSave-B6QpoPRn.js} +1 -1
  45. package/dist/assets/pi-session-focus-preference-PWoh3LNA.js +9 -0
  46. package/dist/assets/{renderDiffWithHighlighter-PL82AR81.js → renderDiffWithHighlighter-C48T6YFJ.js} +1 -1
  47. package/dist/assets/renderElectronMiniChatApp-N-BQdJl0.js +2 -0
  48. package/dist/assets/{renderFileWithHighlighter-CYgfbA4F.js → renderFileWithHighlighter-8Kt2MyTN.js} +1 -1
  49. package/dist/assets/{renderMobileApp-Bp74b_Lo.js → renderMobileApp-B7cT7m5b.js} +3 -3
  50. package/dist/assets/runtimeEndpointReset-BC6yGnxN.js +62 -0
  51. package/dist/assets/runtimeSurface-kIEoYsPP.js +1 -0
  52. package/dist/assets/selection-BTEdLRVK.js +1 -0
  53. package/dist/assets/useAppFontEffects-EcTZ_I_I.js +225 -0
  54. package/dist/assets/useGitHubRemoteSearch-DIBHNu8r.js +1 -0
  55. package/dist/assets/useSwitcherItems-DfLbfX37.js +1 -0
  56. package/dist/assets/{vendor-aparajita-capacitor-secure-storage-DVZvgYu4.js → vendor-aparajita-capacitor-secure-storage-DUoR8t1G.js} +1 -1
  57. package/dist/assets/{vendor-base-ui-BCqPBzDj.js → vendor-base-ui-DE6jnTiC.js} +1 -1
  58. package/dist/assets/{vendor-boot-3SaHYVb1.js → vendor-boot-D-KEJjsM.js} +29 -29
  59. package/dist/assets/{vendor-capacitor-app-NbQ-WiPS.js → vendor-capacitor-app-CO5jS31X.js} +1 -1
  60. package/dist/assets/{vendor-capacitor-keyboard-CgrHt8iN.js → vendor-capacitor-keyboard-335osRpd.js} +1 -1
  61. package/dist/assets/{vendor-capacitor-status-bar-CWt0OF5t.js → vendor-capacitor-status-bar-lB9y4H9d.js} +1 -1
  62. package/dist/assets/{vendor-codemirror-autocomplete-WThuuUAz.js → vendor-codemirror-autocomplete-BKvJ8PfM.js} +1 -1
  63. package/dist/assets/{vendor-codemirror-lang-angular-BbLGCxF6.js → vendor-codemirror-lang-angular-wjCUD0bM.js} +1 -1
  64. package/dist/assets/{vendor-codemirror-lang-cpp-Cceks-9O.js → vendor-codemirror-lang-cpp-LJzlG8sJ.js} +1 -1
  65. package/dist/assets/{vendor-codemirror-lang-css-D1wpUg3Z.js → vendor-codemirror-lang-css-DoEEdEpW.js} +1 -1
  66. package/dist/assets/{vendor-codemirror-lang-go-Cv0zXHHM.js → vendor-codemirror-lang-go-DexsLPb8.js} +1 -1
  67. package/dist/assets/{vendor-codemirror-lang-html-DbL8oT9H.js → vendor-codemirror-lang-html-h25V-Hp5.js} +1 -1
  68. package/dist/assets/{vendor-codemirror-lang-java-CNugenuC.js → vendor-codemirror-lang-java-D8xoT8cv.js} +1 -1
  69. package/dist/assets/{vendor-codemirror-lang-javascript-Bx_FIyZF.js → vendor-codemirror-lang-javascript-DF3GDYje.js} +1 -1
  70. package/dist/assets/{vendor-codemirror-lang-jinja-DDGjB3Zq.js → vendor-codemirror-lang-jinja-BboTHFdn.js} +1 -1
  71. package/dist/assets/{vendor-codemirror-lang-json-DIvqf9Pb.js → vendor-codemirror-lang-json-DCqvG1nE.js} +1 -1
  72. package/dist/assets/{vendor-codemirror-lang-less-D8r9dGG1.js → vendor-codemirror-lang-less-B8ZrSKJM.js} +1 -1
  73. package/dist/assets/{vendor-codemirror-lang-liquid-B24mguYi.js → vendor-codemirror-lang-liquid-DF9S5m5F.js} +1 -1
  74. package/dist/assets/{vendor-codemirror-lang-markdown-v3yG2sbf.js → vendor-codemirror-lang-markdown-6BNbCEPe.js} +1 -1
  75. package/dist/assets/{vendor-codemirror-lang-php-BcZGalqy.js → vendor-codemirror-lang-php-CQwAz1Hd.js} +1 -1
  76. package/dist/assets/{vendor-codemirror-lang-python-b-JqEwQy.js → vendor-codemirror-lang-python-DQym-8Tx.js} +1 -1
  77. package/dist/assets/{vendor-codemirror-lang-rust-B1uZxDW-.js → vendor-codemirror-lang-rust-DknzOTkO.js} +1 -1
  78. package/dist/assets/{vendor-codemirror-lang-sass-DqPrngKp.js → vendor-codemirror-lang-sass-dB0Rm5HI.js} +1 -1
  79. package/dist/assets/{vendor-codemirror-lang-sql-UyCnpt-k.js → vendor-codemirror-lang-sql-CCQUnnD-.js} +1 -1
  80. package/dist/assets/{vendor-codemirror-lang-vue-xDwYkovV.js → vendor-codemirror-lang-vue-h1M5bF00.js} +1 -1
  81. package/dist/assets/{vendor-codemirror-lang-wast-CF3169p_.js → vendor-codemirror-lang-wast-DWgtlGfu.js} +1 -1
  82. package/dist/assets/{vendor-codemirror-lang-xml-FCtVhuOb.js → vendor-codemirror-lang-xml-DncwoCUY.js} +1 -1
  83. package/dist/assets/{vendor-codemirror-lang-yaml-g0sPmAnv.js → vendor-codemirror-lang-yaml-C7QkS5ER.js} +1 -1
  84. package/dist/assets/{vendor-codemirror-language-data-B03xgzP2.js → vendor-codemirror-language-data-BUZIlm3G.js} +2 -2
  85. package/dist/assets/{vendor-codemirror-search-Dw3Wpu15.js → vendor-codemirror-search-BlDCaCMK.js} +1 -1
  86. package/dist/assets/{vendor-lezer-cpp-Cu3E-KUI.js → vendor-lezer-cpp-B4JK1BC1.js} +1 -1
  87. package/dist/assets/{vendor-lezer-css-Cb8vp67u.js → vendor-lezer-css-DRxDmhcy.js} +1 -1
  88. package/dist/assets/{vendor-lezer-go-BTsIaOm7.js → vendor-lezer-go-DsUgfmxi.js} +1 -1
  89. package/dist/assets/{vendor-lezer-html-UQMsUwj-.js → vendor-lezer-html-qr9pUPmM.js} +1 -1
  90. package/dist/assets/{vendor-lezer-java-BIWrFrAx.js → vendor-lezer-java-6UyNiQiB.js} +1 -1
  91. package/dist/assets/{vendor-lezer-javascript-BH2Etgoy.js → vendor-lezer-javascript-CUdJ0VGA.js} +1 -1
  92. package/dist/assets/{vendor-lezer-json-CE-QUCwM.js → vendor-lezer-json-BKYAA8Hu.js} +1 -1
  93. package/dist/assets/{vendor-lezer-lr-HY6Yc0Vr.js → vendor-lezer-lr-DluApmOX.js} +1 -1
  94. package/dist/assets/{vendor-lezer-markdown-xFL3Evwf.js → vendor-lezer-markdown-B-uzYzYT.js} +1 -1
  95. package/dist/assets/{vendor-lezer-php-Cr_mQGrG.js → vendor-lezer-php-DI6PNjlz.js} +1 -1
  96. package/dist/assets/{vendor-lezer-python-BNRFWCb0.js → vendor-lezer-python-Bj232yb5.js} +1 -1
  97. package/dist/assets/{vendor-lezer-rust-BvfOK5cU.js → vendor-lezer-rust-DlPG_Yau.js} +1 -1
  98. package/dist/assets/{vendor-lezer-sass-qoxiLisk.js → vendor-lezer-sass-CBsyWB2A.js} +1 -1
  99. package/dist/assets/{vendor-lezer-xml--x8SSpqU.js → vendor-lezer-xml-C1FmgtmE.js} +1 -1
  100. package/dist/assets/{vendor-lezer-yaml-BDo1JaEr.js → vendor-lezer-yaml-DpHmjriG.js} +1 -1
  101. package/dist/assets/{vendor-replit-codemirror-vim-D1Fe7FiY.js → vendor-replit-codemirror-vim-Cvk64got.js} +1 -1
  102. package/dist/assets/{web-components-CGDpzixf.js → web-components-C_DsTJis.js} +4 -4
  103. package/dist/index.html +4 -4
  104. package/dist/mini-chat.html +3 -3
  105. package/dist/mobile.html +3 -3
  106. package/package.json +2 -1
  107. package/plugins/registry.json +7 -0
  108. package/plugins/subagents/LICENSE +25 -0
  109. package/plugins/subagents/agents/planner.md +36 -0
  110. package/plugins/subagents/agents/reviewer.md +34 -0
  111. package/plugins/subagents/agents/scout.md +49 -0
  112. package/plugins/subagents/agents/worker.md +23 -0
  113. package/plugins/subagents/extension.js +631 -0
  114. package/plugins/subagents/extension.test.js +295 -0
  115. package/plugins/subagents/package.json +41 -0
  116. package/plugins/visuals/choices.js +168 -0
  117. package/plugins/visuals/extension.js +87 -0
  118. package/plugins/visuals/files.js +74 -0
  119. package/plugins/visuals/package.json +32 -0
  120. package/server/index.js +20 -0
  121. package/server/lib/github/DOCUMENTATION.md +4 -2
  122. package/server/lib/github/gh-cli.js +35 -9
  123. package/server/lib/github/gh-cli.test.js +122 -0
  124. package/server/lib/notifications/pi-notification-watcher.js +3 -0
  125. package/server/lib/notifications/pi-notification-watcher.test.js +10 -0
  126. package/server/lib/open-url/DOCUMENTATION.md +1 -1
  127. package/server/lib/pi/extension-protocol.js +54 -0
  128. package/server/lib/pi/fixtures/pichamber-gui-demo.ts +12 -13
  129. package/server/lib/pi/routes-extension-events.test.js +115 -0
  130. package/server/lib/pi/routes.js +307 -5
  131. package/server/lib/pi/routes.test.js +296 -1
  132. package/server/lib/pi/session-daemon/DOCUMENTATION.md +25 -8
  133. package/server/lib/pi/session-daemon/extension-bridge.js +89 -29
  134. package/server/lib/pi/session-daemon/extension-config.js +719 -0
  135. package/server/lib/pi/session-daemon/extension-config.test.js +618 -0
  136. package/server/lib/pi/session-daemon/extension-controls.js +177 -0
  137. package/server/lib/pi/session-daemon/extension-controls.test.js +181 -0
  138. package/server/lib/pi/session-daemon/extension-name.js +6 -0
  139. package/server/lib/pi/session-daemon/extension-name.test.js +5 -0
  140. package/server/lib/pi/session-daemon/extension-palette.js +146 -0
  141. package/server/lib/pi/session-daemon/extension-palette.test.js +107 -0
  142. package/server/lib/pi/session-daemon/extension-replacements.js +138 -0
  143. package/server/lib/pi/session-daemon/extension-replacements.test.js +116 -0
  144. package/server/lib/pi/session-daemon/extension-ui-mode.js +30 -0
  145. package/server/lib/pi/session-daemon/extension-ui-mode.test.js +34 -0
  146. package/server/lib/pi/session-daemon/pichamber-ui.js +44 -0
  147. package/server/lib/pi/session-daemon/plugin-host.js +245 -0
  148. package/server/lib/pi/session-daemon/plugin-host.test.js +192 -0
  149. package/server/lib/pi/session-daemon/session-daemon-controls.e2e.test.js +205 -0
  150. package/server/lib/pi/session-daemon/session-daemon-drafts.e2e.test.js +409 -0
  151. package/server/lib/pi/session-daemon/session-daemon-extension-config.e2e.test.js +196 -0
  152. package/server/lib/pi/session-daemon/session-daemon-extensions.test.js +137 -6
  153. package/server/lib/pi/session-daemon/session-daemon-plugins.e2e.test.js +272 -0
  154. package/server/lib/pi/session-daemon/session-daemon-providers.e2e.test.js +153 -0
  155. package/server/lib/pi/session-daemon/session-daemon.js +568 -61
  156. package/server/lib/pi/session-daemon/session-daemon.test.js +164 -4
  157. package/server/lib/pi/session-daemon/session-engine-router.js +7 -0
  158. package/server/lib/pi/session-daemon/session-engine-router.test.js +20 -0
  159. package/server/lib/pi/session-daemon/supervisor.js +22 -3
  160. package/server/lib/pi/settings-store.js +14 -0
  161. package/server/lib/pi/settings-store.test.js +11 -0
  162. package/server/lib/plugins/DOCUMENTATION.md +186 -0
  163. package/server/lib/plugins/daemon-sync.js +78 -0
  164. package/server/lib/plugins/daemon-sync.supervisor.test.js +83 -0
  165. package/server/lib/plugins/daemon-sync.test.js +96 -0
  166. package/server/lib/plugins/impact.js +139 -0
  167. package/server/lib/plugins/impact.test.js +82 -0
  168. package/server/lib/plugins/manifest.js +195 -0
  169. package/server/lib/plugins/manifest.test.js +118 -0
  170. package/server/lib/plugins/registry.js +59 -0
  171. package/server/lib/plugins/routes.js +92 -0
  172. package/server/lib/plugins/routes.test.js +219 -0
  173. package/server/lib/plugins/service.js +161 -0
  174. package/server/lib/plugins/store.js +261 -0
  175. package/server/lib/plugins/store.test.js +188 -0
  176. package/server/lib/plugins/visuals-extension.test.js +237 -0
  177. package/server/lib/server-browser/DOCUMENTATION.md +32 -7
  178. package/server/lib/server-browser/browser-tab.js +4 -1
  179. package/server/lib/server-browser/downloads.js +261 -34
  180. package/server/lib/server-browser/downloads.test.js +171 -0
  181. package/server/lib/server-browser/runtime.integration.test.js +47 -0
  182. package/server/lib/server-browser/runtime.js +16 -0
  183. package/server/lib/server-browser/server-browser.js +25 -6
  184. package/server/lib/tunnels/executable-search.js +5 -1
  185. package/server/lib/tunnels/executable-search.test.js +26 -0
  186. package/dist/assets/DiagramView-BB-aZobi.js +0 -1
  187. package/dist/assets/FileSaveConflictDialog-Bzz8FNMq.js +0 -3
  188. package/dist/assets/FilesView-DECxN8Z0.js +0 -6
  189. package/dist/assets/GitHubDetailScaffold-CWsWycRd.js +0 -11
  190. package/dist/assets/GitHubLinkPicker-BVYdg_e8.js +0 -1
  191. package/dist/assets/GitHubListPrimitives-Dlv3tC4d.js +0 -1
  192. package/dist/assets/PatchDiff-BklyOEHs.js +0 -1
  193. package/dist/assets/PierreDiffViewer-wc6cB6qw.js +0 -147
  194. package/dist/assets/PullRequestsSurface-BZvJkT1I.js +0 -2
  195. package/dist/assets/SessionSwitcherDropdown-DShvvGwC.js +0 -2
  196. package/dist/assets/SessionUnreadDot-CbqRq6h_.js +0 -1
  197. package/dist/assets/SettingsView-DcF-At5E.js +0 -6
  198. package/dist/assets/ToolOutputDialog-DdMIfrnK.js +0 -8
  199. package/dist/assets/ToolPartDiffPreview-C6Sm4eVf.js +0 -1
  200. package/dist/assets/contextFileOpenGuard-UU86YHgI.js +0 -1
  201. package/dist/assets/gitStatusPredicates-DQEO4Psc.js +0 -1
  202. package/dist/assets/githubLink-ByPAyFjh.js +0 -10
  203. package/dist/assets/index-BaLCg7tL.css +0 -1
  204. package/dist/assets/main-DyFfbllq.js +0 -137
  205. package/dist/assets/miniChat-Ck6MEZ9Q.js +0 -2
  206. package/dist/assets/pi-session-focus-preference-Dx0UXPoO.js +0 -9
  207. package/dist/assets/renderElectronMiniChatApp-Cb7s7dWl.js +0 -2
  208. package/dist/assets/runtimeEndpointReset-7nWYnKd4.js +0 -62
  209. package/dist/assets/runtimeSurface-CFwnvks_.js +0 -1
  210. package/dist/assets/useAppFontEffects-ZTyNwFk6.js +0 -213
  211. package/dist/assets/useGitHubRemoteSearch-BF3ohpsh.js +0 -1
  212. package/dist/assets/useSwitcherItems-BJzwyDGX.js +0 -1
@@ -1,5 +1,5 @@
1
1
  import { afterEach, describe, expect, it } from 'vitest';
2
- import { mkdir, mkdtemp } from 'node:fs/promises';
2
+ import { mkdir, mkdtemp, writeFile } from 'node:fs/promises';
3
3
  import { createConnection } from 'node:net';
4
4
  import { tmpdir } from 'node:os';
5
5
  import { join } from 'node:path';
@@ -154,12 +154,13 @@ describe('Pi session daemon extension bridging', () => {
154
154
  let daemon;
155
155
  let sessions = [];
156
156
 
157
- const startWithExtensibleSession = async ({ entries } = {}) => {
157
+ const startWithExtensibleSession = async ({ entries, extensionMode = 'tui', piSettings, resolveExtensionPalette } = {}) => {
158
158
  const root = await mkdtemp(join(tmpdir(), 'pichamber-pi-daemon-ext-'));
159
159
  const projectDir = join(root, 'project');
160
160
  const agentDir = join(root, 'agent');
161
161
  await mkdir(projectDir, { recursive: true });
162
162
  await mkdir(agentDir, { recursive: true });
163
+ if (piSettings) await writeFile(join(agentDir, 'settings.json'), JSON.stringify(piSettings));
163
164
  const endpoint = join(root, 'daemon.sock');
164
165
  const session = new ExtensibleFakeSession();
165
166
  const runtimeState = { disposeCount: 0 };
@@ -171,6 +172,8 @@ describe('Pi session daemon extension bridging', () => {
171
172
  credential,
172
173
  cwd: projectDir,
173
174
  agentDir,
175
+ resolveExtensionMode: () => extensionMode,
176
+ ...(resolveExtensionPalette ? { resolveExtensionPalette } : {}),
174
177
  createRuntime: async (_options, hooks) => {
175
178
  // Mirror the default factory contract: bind extensions when the daemon
176
179
  // supplies bindings hooks.
@@ -185,7 +188,7 @@ describe('Pi session daemon extension bridging', () => {
185
188
  const client = connectClient(endpoint);
186
189
  await client.authenticate();
187
190
  await client.request('sessions.create', { cwd: projectDir });
188
- return { client, session, endpoint, runtimeState, projectDir };
191
+ return { client, session, endpoint, runtimeState, projectDir, agentDir };
189
192
  };
190
193
 
191
194
  afterEach(async () => {
@@ -194,6 +197,43 @@ describe('Pi session daemon extension bridging', () => {
194
197
  sessions = [];
195
198
  });
196
199
 
200
+ it("passes Pi's theme setting to the palette resolver, light/dark pairs intact", async () => {
201
+ const calls = [];
202
+ const palette = { theme: 'light', appearance: 'light', colors: { accent: '#5a8080' } };
203
+ const { client } = await startWithExtensibleSession({
204
+ piSettings: { theme: 'light/dark' },
205
+ resolveExtensionPalette: async (input) => {
206
+ calls.push(input);
207
+ return palette;
208
+ },
209
+ });
210
+ const terminal = { background: '#ffffff', foreground: '#000000', palette: Array(16).fill('#808080') };
211
+ const response = await client.request('extensions.palette', { terminal });
212
+ expect(response.result).toEqual(palette);
213
+ expect(calls).toEqual([{ themeSetting: 'light/dark', terminal }]);
214
+ });
215
+
216
+ it('reports unreadable Pi settings instead of answering with the system theme', async () => {
217
+ let calls = 0;
218
+ const { client, agentDir } = await startWithExtensibleSession({
219
+ resolveExtensionPalette: async () => {
220
+ calls += 1;
221
+ return { theme: 'system', appearance: 'light', colors: {} };
222
+ },
223
+ });
224
+ await writeFile(join(agentDir, 'settings.json'), '{ not json');
225
+ const terminal = { background: '#ffffff', foreground: '#000000', palette: Array(16).fill('#808080') };
226
+ const failure = client.next((frame) => frame.kind === 'error');
227
+ client.request('extensions.palette', { terminal }).catch(() => {});
228
+ await expect(failure).resolves.toMatchObject({ error: { code: 'PI_SETTINGS_INVALID' } });
229
+ expect(calls).toBe(0);
230
+ });
231
+
232
+ it('binds the mode the Extension interface setting resolves to', async () => {
233
+ const { session } = await startWithExtensibleSession({ extensionMode: 'rpc' });
234
+ expect(session.boundBindings.mode).toBe('rpc');
235
+ });
236
+
197
237
  it('binds extensions into every created runtime and resolves blocking dialogs via extensions.respond', async () => {
198
238
  const { client, session } = await startWithExtensibleSession();
199
239
  expect(session.boundBindings).toBeTruthy();
@@ -806,11 +846,11 @@ describe('Pi session daemon extension panels, apps, and forms', () => {
806
846
  expect(removal.payload.appId).toBe('board');
807
847
  });
808
848
 
809
- it('bridges ctx.ui.form to a form dialog and resolves with a values object', async () => {
849
+ it('bridges pichamber.ui.form to a form dialog and resolves with a values object', async () => {
810
850
  const { client, session, endpoint } = await startWithExtensibleSession();
811
- const ui = session.boundBindings.uiContext;
851
+ const ctx = { ui: session.boundBindings.uiContext };
812
852
 
813
- const pending = ui.form('Spawn agent', [
853
+ const pending = globalThis.pichamber.ui.form(ctx, 'Spawn agent', [
814
854
  { id: 'name', label: 'Name', type: 'text', required: true },
815
855
  { id: 'level', label: 'Level', type: 'select', options: ['low', 'high'], initial: 'high' },
816
856
  { id: 'workers', label: 'Workers', type: 'number', min: 1, max: 4 },
@@ -842,6 +882,97 @@ describe('Pi session daemon extension panels, apps, and forms', () => {
842
882
  expect(await pending).toEqual({ name: 'research', level: 'high', workers: '4' });
843
883
  });
844
884
 
885
+ it('bridges pichamber.ui.choose to a choose dialog tied to its tool call', async () => {
886
+ const { client, session, endpoint } = await startWithExtensibleSession();
887
+ const ctx = { ui: session.boundBindings.uiContext };
888
+ const { pichamber } = globalThis;
889
+ // PiChamber's own calls are not on Pi's `ctx.ui` under a string name.
890
+ expect(ctx.ui).not.toHaveProperty('choose');
891
+ const choices = [
892
+ { id: 'a', label: 'A: Compact', description: 'One row' },
893
+ { id: 'b', label: 'B: Tall' },
894
+ { id: 'a', label: 'A again' },
895
+ { label: 'no id' },
896
+ ];
897
+
898
+ const pending = pichamber.ui.choose(ctx, 'Which header?', choices, { toolCallId: 'call-7', allowNote: true });
899
+ const request = await client.next((message) => message.kind === 'event' && message.event === 'extension.dialog');
900
+ expect(request.payload).toMatchObject({
901
+ method: 'choose',
902
+ title: 'Which header?',
903
+ choices: [{ id: 'a', label: 'A: Compact', description: 'One row' }, { id: 'b', label: 'B: Tall' }],
904
+ allowNote: true,
905
+ toolCallId: 'call-7',
906
+ });
907
+ // The session counts as waiting on the user, like any dialog.
908
+ const waiting = await client.request('sessions.pendingInput', {});
909
+ expect(waiting.result.sessions).toEqual([expect.objectContaining({ sessionId: session.sessionId })]);
910
+
911
+ // An id the question never offered is a bad request and leaves it open.
912
+ await expect(client.request('extensions.respond', {
913
+ requestId: request.payload.requestId,
914
+ value: 'z',
915
+ })).rejects.toThrow('Daemon connection closed');
916
+
917
+ const answering = connectClient(endpoint);
918
+ await answering.authenticate();
919
+ await answering.request('extensions.respond', {
920
+ requestId: request.payload.requestId,
921
+ value: 'b',
922
+ note: ' darker header ',
923
+ });
924
+ expect(await pending).toEqual({ id: 'b', note: 'darker header' });
925
+
926
+ // A note for a question that takes none is refused; dismissing resolves undefined.
927
+ const plain = pichamber.ui.choose(ctx, 'Pick', [{ id: 'x', label: 'X' }]);
928
+ const plainRequest = await answering.next((message) => message.kind === 'event' && message.event === 'extension.dialog');
929
+ expect(plainRequest.payload).not.toHaveProperty('allowNote');
930
+ expect(plainRequest.payload).not.toHaveProperty('toolCallId');
931
+ await expect(answering.request('extensions.respond', {
932
+ requestId: plainRequest.payload.requestId,
933
+ value: 'x',
934
+ note: 'not asked for',
935
+ })).rejects.toThrow('Daemon connection closed');
936
+ const dismissing = connectClient(endpoint);
937
+ await dismissing.authenticate();
938
+ await dismissing.request('extensions.respond', { requestId: plainRequest.payload.requestId, cancelled: true });
939
+ dismissing.close();
940
+ expect(await plain).toBeUndefined();
941
+
942
+ // Nothing to choose, or no title: nothing is shown and the call fails.
943
+ await expect(pichamber.ui.choose(ctx, 'Pick', [{ label: 'no id' }])).rejects.toThrow(/at least one choice/);
944
+ await expect(pichamber.ui.choose(ctx, '', [{ id: 'x', label: 'X' }])).rejects.toThrow(/title/);
945
+ });
946
+
947
+ it('exposes globalThis.pichamber with ui, and keeps the released markers', () => {
948
+ expect(Object.isFrozen(globalThis.pichamber)).toBe(true);
949
+ expect(globalThis.pichamber.version).toBe(1);
950
+ expect(Object.keys(globalThis.pichamber.ui).sort()).toEqual(['choose', 'form', 'openUrl']);
951
+ expect(globalThis.__PICHAMBER__.version).toBe(1);
952
+ expect(process.env.PICHAMBER).toBe('1');
953
+ });
954
+
955
+ it('keeps form and openUrl off ctx.ui, and refuses a URL that is not http(s)', async () => {
956
+ const { session } = await startWithExtensibleSession();
957
+ const ctx = { ui: session.boundBindings.uiContext };
958
+
959
+ // PiChamber's own calls are not on Pi's `ctx.ui` under a string name.
960
+ expect(ctx.ui).not.toHaveProperty('form');
961
+ expect(ctx.ui).not.toHaveProperty('openUrl');
962
+ await expect(globalThis.pichamber.ui.openUrl(ctx, 'file:///etc/passwd')).resolves.toBe(false);
963
+ });
964
+
965
+ it('rejects a pichamber.ui call without a PiChamber ctx, never synchronously', async () => {
966
+ const { pichamber } = globalThis;
967
+ for (const name of ['choose', 'form', 'openUrl']) {
968
+ let promise;
969
+ expect(() => { promise = pichamber.ui[name](undefined, 'T', []); }).not.toThrow();
970
+ await expect(promise).rejects.toBeInstanceOf(TypeError);
971
+ await expect(promise).rejects.toThrow(/ctx/);
972
+ await expect(pichamber.ui[name]({ ui: { select: async () => undefined } }, 'T', [])).rejects.toBeInstanceOf(TypeError);
973
+ }
974
+ });
975
+
845
976
  it('lists extensions with opaque ids and never leaks server paths', async () => {
846
977
  const { client, session } = await startWithExtensibleSession();
847
978
  session.extensionRunner = {
@@ -0,0 +1,272 @@
1
+ import { createConnection } from 'node:net';
2
+ import { afterEach, describe, expect, it } from 'vitest';
3
+ import { mkdir, mkdtemp, writeFile } from 'node:fs/promises';
4
+ import { tmpdir } from 'node:os';
5
+ import { join } from 'node:path';
6
+ import { fileURLToPath } from 'node:url';
7
+
8
+ import { createSessionDaemon } from './session-daemon.js';
9
+
10
+ // Real SDK: the bundled plugins load through `plugins.configure`, which
11
+ // recreates the runtime. Visuals has no switch: `render_html` is declared and
12
+ // runs while the plugin is configured, and `render_choices` shows its options,
13
+ // asks through `pichamber.ui.choose` tied to its tool call, and returns the answer.
14
+ // Sub-agents follows its `on` state: a
15
+ // state-only change removes `subagent` from the declared tools without
16
+ // recreation, and a session's own value (its composer switch) applies to
17
+ // that session only.
18
+
19
+ const credential = 'plugins-e2e-daemon-credential';
20
+ const VISUALS_ENTRY = fileURLToPath(new URL('../../../../plugins/visuals/extension.js', import.meta.url));
21
+ const SUBAGENTS_ENTRY = fileURLToPath(new URL('../../../../plugins/subagents/extension.js', import.meta.url));
22
+
23
+ // Records, per model request, which plugin tools are declared to the model,
24
+ // and answers from a script.
25
+ const PROVIDER_EXTENSION = `
26
+ import { fauxProvider, fauxAssistantMessage, fauxToolCall } from '@earendil-works/pi-ai';
27
+
28
+ export default function (pi) {
29
+ const faux = fauxProvider({
30
+ provider: 'plugins-mock-provider',
31
+ models: [{ id: 'plugins-mock-model', name: 'Plugins Mock Model', cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }, contextWindow: 16384, maxTokens: 2048 }],
32
+ tokensPerSecond: 1000,
33
+ });
34
+ // System messages declare the tools: the first lists them, later ones add
35
+ // (toolsAdded) or remove (toolsRemoved) declarations.
36
+ const TOOLS = { visuals: /\\brender_html\\b/, subagents: /\\bsubagent\\b/ };
37
+ const NAMES = { visuals: 'render_html', subagents: 'subagent' };
38
+ const record = (context) => {
39
+ const declared = { visuals: false, subagents: false };
40
+ for (const message of context.messages) {
41
+ if (message.role !== 'system') continue;
42
+ for (const key of Object.keys(declared)) {
43
+ if (TOOLS[key].test(String(message.sections?.tools ?? ''))) declared[key] = true;
44
+ if ((message.toolsAdded ?? []).some((tool) => tool.name === NAMES[key])) declared[key] = true;
45
+ if ((message.toolsRemoved ?? []).some((tool) => tool.name === NAMES[key])) declared[key] = false;
46
+ }
47
+ }
48
+ (globalThis.__pluginsE2eDeclared ??= []).push(declared);
49
+ };
50
+ // Runtime recreation reloads this extension, so the script position lives
51
+ // on globalThis instead of in this closure.
52
+ const script = [
53
+ () => fauxAssistantMessage('first'),
54
+ () => fauxAssistantMessage([fauxToolCall('render_html', { title: 'Demo', html: '<p>hi</p>', height: 200 }, { id: 'call-visual-1' })], { stopReason: 'toolUse' }),
55
+ () => fauxAssistantMessage('drawn'),
56
+ () => fauxAssistantMessage('third'),
57
+ () => fauxAssistantMessage('fourth'),
58
+ () => fauxAssistantMessage('fifth'),
59
+ () => fauxAssistantMessage([fauxToolCall('render_choices', { title: 'Which header?', options: [
60
+ { label: 'Compact', html: '<p>compact</p>' },
61
+ { label: 'Tall', description: 'More room for the logo', html: '<p>tall</p>' },
62
+ ] }, { id: 'call-choices-1' })], { stopReason: 'toolUse' }),
63
+ () => fauxAssistantMessage('picked'),
64
+ ];
65
+ const respond = (context) => {
66
+ record(context);
67
+ const step = globalThis.__pluginsE2eStep ?? 0;
68
+ globalThis.__pluginsE2eStep = step + 1;
69
+ return script[step]();
70
+ };
71
+ faux.setResponses(script.map(() => respond));
72
+ pi.registerProvider(faux.provider);
73
+ }
74
+ `;
75
+
76
+ function connectClient(endpoint) {
77
+ const socket = createConnection({ path: endpoint });
78
+ let buffer = '';
79
+ const messages = [];
80
+ const waiters = [];
81
+ socket.on('data', (chunk) => {
82
+ buffer += chunk.toString('utf8');
83
+ let newline;
84
+ while ((newline = buffer.indexOf('\n')) !== -1) {
85
+ const line = buffer.slice(0, newline);
86
+ buffer = buffer.slice(newline + 1);
87
+ if (!line) continue;
88
+ const message = JSON.parse(line);
89
+ messages.push(message);
90
+ for (let index = waiters.length - 1; index >= 0; index -= 1) {
91
+ if (waiters[index].predicate(message)) waiters.splice(index, 1)[0].resolve(message);
92
+ }
93
+ }
94
+ });
95
+ const next = (predicate, timeoutMs = 20_000) => {
96
+ const existing = messages.find(predicate);
97
+ if (existing) return Promise.resolve(existing);
98
+ return new Promise((resolve, reject) => {
99
+ const timer = setTimeout(() => reject(new Error('Timed out waiting for a daemon message.')), timeoutMs);
100
+ waiters.push({ predicate, resolve: (message) => { clearTimeout(timer); resolve(message); } });
101
+ });
102
+ };
103
+ return {
104
+ async authenticate() {
105
+ await new Promise((resolve, reject) => {
106
+ socket.once('connect', resolve);
107
+ socket.once('error', reject);
108
+ });
109
+ socket.write(`${JSON.stringify({ kind: 'authenticate', credential })}\n`);
110
+ await next((message) => message.kind === 'authenticated');
111
+ },
112
+ async request(command, payload = {}) {
113
+ const requestId = `request-${Math.random()}`;
114
+ socket.write(`${JSON.stringify({ protocolVersion: 1, kind: 'request', requestId, command, payload })}\n`);
115
+ const response = await next((message) => (message.kind === 'response' || message.kind === 'error') && message.requestId === requestId);
116
+ if (response.kind === 'error') throw new Error(`Daemon error: ${response.code}`);
117
+ return response.result;
118
+ },
119
+ next,
120
+ lastSequence: () => Math.max(0, ...messages.map((message) => message.sequence ?? 0)),
121
+ async close() {
122
+ socket.end();
123
+ await new Promise((resolve) => socket.once('close', resolve));
124
+ },
125
+ };
126
+ }
127
+
128
+ describe('session daemon plugins end-to-end with real SDK', () => {
129
+ let daemon;
130
+
131
+ afterEach(async () => {
132
+ await daemon?.stop();
133
+ daemon = undefined;
134
+ delete globalThis.__pluginsE2eDeclared;
135
+ delete globalThis.__pluginsE2eStep;
136
+ });
137
+
138
+ it('loads plugins only when configured; Sub-agents follows its `on` state live', async () => {
139
+ const root = await mkdtemp(join(tmpdir(), 'pichamber-plugins-e2e-'));
140
+ const projectDir = join(root, 'project');
141
+ const agentDir = join(root, 'agent');
142
+ await mkdir(projectDir, { recursive: true });
143
+ await mkdir(join(agentDir, 'extensions'), { recursive: true });
144
+ await writeFile(join(agentDir, 'extensions', 'plugins-provider.ts'), PROVIDER_EXTENSION);
145
+ await writeFile(join(agentDir, 'settings.json'), JSON.stringify({ defaultProvider: 'plugins-mock-provider', defaultModel: 'plugins-mock-model' }));
146
+ await writeFile(join(agentDir, 'auth.json'), JSON.stringify({ 'plugins-mock-provider': { type: 'api_key', key: 'faux-test-key' } }));
147
+ const endpoint = process.platform === 'win32' ? `\\\\.\\pipe\\pichamber-plugins-e2e-${Date.now()}` : join(root, 'daemon.sock');
148
+
149
+ daemon = createSessionDaemon({ endpoint, credential, cwd: projectDir, agentDir });
150
+ await daemon.start();
151
+ const client = connectClient(endpoint);
152
+ await client.authenticate();
153
+
154
+ const health = await client.request('runtime.health');
155
+ expect(health.capabilities).toContain('plugins.configure');
156
+
157
+ const created = await client.request('sessions.create', { cwd: projectDir });
158
+ const sessionId = created.session.id;
159
+ const prompt = async (text) => {
160
+ const sequence = client.lastSequence();
161
+ const idle = client.next((message) => message.sequence > sequence && message.event === 'session.lifecycle' && message.payload?.state === 'idle');
162
+ await client.request('sessions.prompt', { sessionId, text });
163
+ await idle;
164
+ return sequence;
165
+ };
166
+
167
+ const none = { visuals: false, subagents: false };
168
+ const both = { visuals: true, subagents: true };
169
+ const visualsOnly = { visuals: true, subagents: false };
170
+
171
+ // Never configured: no plugin reaches the model.
172
+ await prompt('one');
173
+ expect(globalThis.__pluginsE2eDeclared).toEqual([none]);
174
+
175
+ // Sub-agents' `on` comes from the manifest default (on) unless state sets it.
176
+ const plugins = (subagentsGlobal = {}, sessions = {}) => ({
177
+ plugins: [
178
+ { id: 'visuals', entry: VISUALS_ENTRY, state: { global: { allowNetwork: false }, projects: {}, sessions: {} } },
179
+ { id: 'subagents', entry: SUBAGENTS_ENTRY, state: { global: subagentsGlobal, projects: {}, sessions } },
180
+ ],
181
+ });
182
+ await expect(client.request('plugins.configure', plugins())).resolves.toEqual({
183
+ plugins: [{ id: 'visuals', loaded: true }, { id: 'subagents', loaded: true }],
184
+ enabledChanged: true,
185
+ deferred: false,
186
+ });
187
+
188
+ const listed = await client.request('extensions.list', { directory: projectDir });
189
+ const names = listed.extensions.map((extension) => extension.name);
190
+ expect(names).toContain('pichamber:visuals');
191
+ expect(names).toContain('pichamber:subagents');
192
+
193
+ const before = await prompt('draw');
194
+ const toolEnd = await client.next((message) => message.sequence > before && message.event === 'session.tool.end' && message.payload?.toolCallId === 'call-visual-1');
195
+ expect(toolEnd.payload).toMatchObject({
196
+ toolName: 'render_html',
197
+ state: 'completed',
198
+ output: 'Rendered "Demo".',
199
+ metadata: { title: 'Demo', html: '<p>hi</p>', height: 200 },
200
+ });
201
+ expect(globalThis.__pluginsE2eDeclared).toEqual([none, both, both]);
202
+
203
+ // State-only change: no recreation, `subagent` leaves the declared set and
204
+ // Visuals, which has no switch, stays.
205
+ await expect(client.request('plugins.configure', plugins({ on: false }))).resolves.toMatchObject({ enabledChanged: false, deferred: false });
206
+ await prompt('three');
207
+ expect(globalThis.__pluginsE2eDeclared.at(-1)).toEqual(visualsOnly);
208
+
209
+ // Another session's value changes nothing here; this session's own value
210
+ // wins over the global one.
211
+ await client.request('plugins.configure', plugins({ on: false }, { 'some-other-session': { on: true } }));
212
+ await prompt('four');
213
+ expect(globalThis.__pluginsE2eDeclared.at(-1)).toEqual(visualsOnly);
214
+ await client.request('plugins.configure', plugins({ on: false }, { [sessionId]: { on: true } }));
215
+ await prompt('five');
216
+ expect(globalThis.__pluginsE2eDeclared.at(-1)).toEqual(both);
217
+
218
+ // `render_choices`: the options reach the client first, then a question
219
+ // tied to the tool call. The call waits until a client answers it.
220
+ const options = [
221
+ { id: 'a', label: 'Compact', html: '<p>compact</p>' },
222
+ { id: 'b', label: 'Tall', description: 'More room for the logo', html: '<p>tall</p>' },
223
+ ];
224
+ const asked = client.lastSequence();
225
+ const settled = client.next((message) => message.sequence > asked && message.event === 'session.lifecycle' && message.payload?.state === 'idle');
226
+ await client.request('sessions.prompt', { sessionId, text: 'choose' });
227
+ const shown = await client.next((message) => message.sequence > asked && message.event === 'session.tool.update' && message.payload?.toolCallId === 'call-choices-1');
228
+ expect(shown.payload.metadata).toEqual({ title: 'Which header?', options });
229
+ const question = await client.next((message) => message.sequence > asked && message.event === 'extension.dialog' && message.payload?.method === 'choose');
230
+ expect(question.payload).toMatchObject({
231
+ sessionId,
232
+ title: 'Which header?',
233
+ toolCallId: 'call-choices-1',
234
+ allowNote: true,
235
+ choices: [
236
+ { id: 'a', label: 'A: Compact' },
237
+ { id: 'b', label: 'B: Tall', description: 'More room for the logo' },
238
+ ],
239
+ });
240
+ expect(question.sequence).toBeGreaterThan(shown.sequence);
241
+ // A session opened now gets the question and what the call has shown.
242
+ const waiting = await client.request('sessions.open', { sessionId });
243
+ expect(waiting.messages.at(-1).parts).toEqual([expect.objectContaining({
244
+ toolCallId: 'call-choices-1',
245
+ state: 'running',
246
+ output: 'Waiting for the user to choose.',
247
+ metadata: { title: 'Which header?', options },
248
+ })]);
249
+ expect(waiting.extensionDialogs).toEqual([expect.objectContaining({ requestId: question.payload.requestId, method: 'choose', toolCallId: 'call-choices-1' })]);
250
+
251
+ await client.request('extensions.respond', { sessionId, requestId: question.payload.requestId, value: 'b', note: 'but with the smaller logo' });
252
+ const chosen = await client.next((message) => message.sequence > asked && message.event === 'session.tool.end' && message.payload?.toolCallId === 'call-choices-1');
253
+ expect(chosen.payload).toMatchObject({
254
+ toolName: 'render_choices',
255
+ state: 'completed',
256
+ output: 'The user chose B: "Tall". Their note: "but with the smaller logo"',
257
+ metadata: { title: 'Which header?', options, answer: { id: 'b', note: 'but with the smaller logo' } },
258
+ });
259
+ await client.next((message) => message.sequence > asked && message.event === 'extension.dialog.dismiss' && message.payload?.requestId === question.payload.requestId);
260
+ await settled;
261
+ // The answer replaces the partial result on the finished call.
262
+ const answered = await client.request('sessions.open', { sessionId });
263
+ expect(answered.extensionDialogs ?? []).toEqual([]);
264
+ expect(answered.messages.find((entry) => entry.parts.some((part) => part.toolCallId === 'call-choices-1')).parts[0]).toMatchObject({
265
+ state: 'completed',
266
+ output: 'The user chose B: "Tall". Their note: "but with the smaller logo"',
267
+ metadata: { answer: { id: 'b', note: 'but with the smaller logo' } },
268
+ });
269
+
270
+ await client.close();
271
+ }, 60_000);
272
+ });
@@ -0,0 +1,153 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { mkdir, mkdtemp, readdir } from 'node:fs/promises';
3
+ import { createConnection } from 'node:net';
4
+ import { tmpdir } from 'node:os';
5
+ import { join } from 'node:path';
6
+ import { StringDecoder } from 'node:string_decoder';
7
+ import { afterEach, describe, expect, it } from 'vitest';
8
+
9
+ import { createSessionDaemon } from './session-daemon.js';
10
+
11
+ // End-to-end validation against the pinned Pi SDK (issue #252). Pi assigns a
12
+ // fresh session a JSONL path but writes the file only with the first message.
13
+ // Saving a provider recreates the runtime, which must not try to reopen that
14
+ // never-written file and leave every later provider read failing.
15
+ const credential = 'a-private-daemon-credential';
16
+
17
+ function testDaemonEndpoint(root) {
18
+ if (process.platform === 'win32') {
19
+ const pipeHash = createHash('sha1').update(root).digest('hex').slice(0, 16);
20
+ return `\\\\.\\pipe\\pichamber-test-${pipeHash}`;
21
+ }
22
+ return join(root, 'daemon.sock');
23
+ }
24
+
25
+ function connectClient(endpoint) {
26
+ const socket = createConnection({ path: endpoint });
27
+ const decoder = new StringDecoder('utf8');
28
+ let buffer = '';
29
+ const messages = [];
30
+ const waiters = [];
31
+
32
+ const publish = (message) => {
33
+ messages.push(message);
34
+ for (let index = waiters.length - 1; index >= 0; index -= 1) {
35
+ const waiter = waiters[index];
36
+ if (waiter.predicate(message)) {
37
+ waiters.splice(index, 1);
38
+ waiter.resolve(message);
39
+ }
40
+ }
41
+ };
42
+
43
+ socket.on('data', (chunk) => {
44
+ buffer += decoder.write(chunk);
45
+ while (true) {
46
+ const newline = buffer.indexOf('\n');
47
+ if (newline === -1) break;
48
+ const line = buffer.slice(0, newline).replace(/\r$/, '');
49
+ buffer = buffer.slice(newline + 1);
50
+ if (line) publish(JSON.parse(line));
51
+ }
52
+ });
53
+
54
+ const next = (predicate) => new Promise((resolve, reject) => {
55
+ const existing = messages.find(predicate);
56
+ if (existing) {
57
+ resolve(existing);
58
+ return;
59
+ }
60
+ const timer = setTimeout(() => {
61
+ const index = waiters.findIndex((waiter) => waiter.resolve === resolve);
62
+ if (index !== -1) waiters.splice(index, 1);
63
+ reject(new Error('Timed out waiting for daemon message'));
64
+ }, 30_000);
65
+ waiters.push({
66
+ predicate,
67
+ reject,
68
+ resolve: (message) => {
69
+ clearTimeout(timer);
70
+ resolve(message);
71
+ },
72
+ });
73
+ });
74
+
75
+ return {
76
+ async authenticate() {
77
+ await new Promise((resolve, reject) => {
78
+ socket.once('connect', resolve);
79
+ socket.once('error', reject);
80
+ });
81
+ socket.write(`${JSON.stringify({ kind: 'authenticate', credential })}\n`);
82
+ await next((message) => message.kind === 'authenticated');
83
+ },
84
+ async request(command, payload = {}) {
85
+ const requestId = `request-${Math.random()}`;
86
+ socket.write(`${JSON.stringify({ protocolVersion: 1, kind: 'request', requestId, command, payload })}\n`);
87
+ // A failed request answers with an error frame that carries no
88
+ // requestId and closes the connection.
89
+ const response = await next((message) => message.requestId === requestId || message.kind === 'error');
90
+ if (response.kind !== 'response') {
91
+ throw Object.assign(new Error(`Daemon request failed: ${response.error?.code}`), { code: response.error?.code });
92
+ }
93
+ return response.result;
94
+ },
95
+ close() {
96
+ socket.end();
97
+ },
98
+ };
99
+ }
100
+
101
+ describe('Pi session daemon provider changes with the real SDK', () => {
102
+ let daemon;
103
+ let originalAgentDirEnv;
104
+
105
+ afterEach(async () => {
106
+ await daemon?.stop();
107
+ daemon = undefined;
108
+ if (originalAgentDirEnv === undefined) delete process.env.PI_CODING_AGENT_DIR;
109
+ else process.env.PI_CODING_AGENT_DIR = originalAgentDirEnv;
110
+ });
111
+
112
+ it('keeps listing providers after a provider is saved before any message', async () => {
113
+ const root = await mkdtemp(join(tmpdir(), 'pichamber-pi-provider-fresh-sdk-'));
114
+ const projectDir = join(root, 'project');
115
+ await mkdir(projectDir);
116
+ // No agent directory: a fresh install.
117
+ const agentDir = join(root, 'agent');
118
+ // Extensions such as MCP read the process-wide agent directory, so point it
119
+ // at the test's directory instead of the developer's real Pi config.
120
+ originalAgentDirEnv = process.env.PI_CODING_AGENT_DIR;
121
+ process.env.PI_CODING_AGENT_DIR = agentDir;
122
+
123
+ const endpoint = testDaemonEndpoint(root);
124
+ daemon = createSessionDaemon({ endpoint, credential, cwd: projectDir, agentDir });
125
+ await daemon.start();
126
+
127
+ const client = connectClient(endpoint);
128
+ await client.authenticate();
129
+
130
+ const before = await client.request('providers.list');
131
+ expect(before.providers.length).toBeGreaterThan(0);
132
+
133
+ const saved = await client.request('providers.models.set', {
134
+ providerId: 'example-gateway',
135
+ label: 'Example gateway',
136
+ baseUrl: 'https://gateway.example.test/v1',
137
+ api: 'openai-completions',
138
+ models: [{ id: 'example-model' }],
139
+ });
140
+ expect(saved).toEqual({ config: expect.objectContaining({ providerId: 'example-gateway' }) });
141
+
142
+ const after = await client.request('providers.list');
143
+ expect(after.providers.map((provider) => provider.id)).toContain('example-gateway');
144
+
145
+ // Nothing was sent, so Pi wrote no session file.
146
+ const sessionDirs = await readdir(join(agentDir, 'sessions'));
147
+ for (const dir of sessionDirs) {
148
+ expect(await readdir(join(agentDir, 'sessions', dir))).toEqual([]);
149
+ }
150
+
151
+ client.close();
152
+ }, 120_000);
153
+ });