@pi-chamber/web 1.0.8-rc.3 → 1.0.8-rc.4

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 (102) hide show
  1. package/dist/assets/{AgentsSurface-wsW9VCRp.js → AgentsSurface-DbCBygRD.js} +1 -1
  2. package/dist/assets/{ChoicesArtifact-EwCf4Yxu.js → ChoicesArtifact-DUqhCvXh.js} +1 -1
  3. package/dist/assets/{DiagramView-BX6N99cQ.js → DiagramView-CnVOyJd2.js} +1 -1
  4. package/dist/assets/{DiffView-CI0eSnPP.js → DiffView-Db8JXsvA.js} +1 -1
  5. package/dist/assets/{FileSaveConflictDialog-GLj2W7VE.js → FileSaveConflictDialog-D6xyf709.js} +1 -1
  6. package/dist/assets/{FilesView-CI0tfZQL.js → FilesView-Cir0Wl9F.js} +1 -1
  7. package/dist/assets/{GitHubDetailScaffold-B85tZ9m7.js → GitHubDetailScaffold-US37Di_K.js} +1 -1
  8. package/dist/assets/{GitHubLinkPicker-Y6AuNiGl.js → GitHubLinkPicker-k_D-sk-e.js} +1 -1
  9. package/dist/assets/{GitHubListPrimitives-BJHBud6i.js → GitHubListPrimitives-DuUXrJGk.js} +1 -1
  10. package/dist/assets/{GitView-DueE69kW.js → GitView-BdX_3XRr.js} +3 -3
  11. package/dist/assets/{IssuesSurface-Cg-xkdIu.js → IssuesSurface-Cw93HC0G.js} +2 -2
  12. package/dist/assets/{JsonTreeView-Cvg6lc40.js → JsonTreeView-Bze4htWt.js} +1 -1
  13. package/dist/assets/{MarkdownRendererImpl-DExPx-QM.js → MarkdownRendererImpl-Ch7NDkF9.js} +1 -1
  14. package/dist/assets/{PatchDiff-_c3HZ34I.js → PatchDiff-l68Yz45X.js} +1 -1
  15. package/dist/assets/{PierreDiffViewer-CZnaqO-_.js → PierreDiffViewer-BHBySiXQ.js} +1 -1
  16. package/dist/assets/{PullRequestsSurface-C9AYPiwo.js → PullRequestsSurface-CGD4_ljc.js} +2 -2
  17. package/dist/assets/{SessionSwitcherContent-DOpnN-8S.js → SessionSwitcherContent-DqP8OWzB.js} +1 -1
  18. package/dist/assets/{SessionSwitcherDropdown-CmHMPZ69.js → SessionSwitcherDropdown-BkTg-cVd.js} +2 -2
  19. package/dist/assets/{SessionUnreadDot-CZCQ4t1J.js → SessionUnreadDot-CgvC3F5e.js} +1 -1
  20. package/dist/assets/{SettingsView-D5PO5M3z.js → SettingsView-CkIxCYhs.js} +3 -3
  21. package/dist/assets/{SettingsWindow-DXV5UOE8.js → SettingsWindow-DSdhzapT.js} +1 -1
  22. package/dist/assets/{SubagentsArtifact-CO1ZiI1x.js → SubagentsArtifact-BN3aX_8M.js} +1 -1
  23. package/dist/assets/{ToolOutputDialog-GOwNLj-y.js → ToolOutputDialog-CLwm4TjA.js} +1 -1
  24. package/dist/assets/{ToolPartDiffPreview-BoaiZji6.js → ToolPartDiffPreview-ERAStEKA.js} +1 -1
  25. package/dist/assets/{VirtualizedFileDiff-Chq1X8nw.js → VirtualizedFileDiff-DwR2fZHv.js} +1 -1
  26. package/dist/assets/{VisualFrame-u7aRcX7O.js → VisualFrame-Dwp7B_st.js} +1 -1
  27. package/dist/assets/{VisualsArtifact-D9vPjihW.js → VisualsArtifact-DlOxifHd.js} +1 -1
  28. package/dist/assets/{collapsible-BjpDEohv.js → collapsible-CW-_qd6v.js} +1 -1
  29. package/dist/assets/{computeVirtualFileMetrics-DmPCxbok.js → computeVirtualFileMetrics-SlBfr8LB.js} +1 -1
  30. package/dist/assets/{contextFileOpenGuard-CukNcUeY.js → contextFileOpenGuard-CHoFT50j.js} +1 -1
  31. package/dist/assets/{fileTreeStatus-CDyfNPYO.js → fileTreeStatus-D0uiC1D0.js} +1 -1
  32. package/dist/assets/{gitStatusPredicates-uI7Y7L5k.js → gitStatusPredicates-Bj3pkh2e.js} +1 -1
  33. package/dist/assets/{githubLink-B9Mxac4R.js → githubLink-CheLNuP0.js} +1 -1
  34. package/dist/assets/{index-BxKPJ9uG.js → index-BFkW-BPM.js} +3 -3
  35. package/dist/assets/{index-BWq2ibCw.js → index-C8zaLvup.js} +1 -1
  36. package/dist/assets/{main-ckQ0ciIN.js → main-CUEqZRu1.js} +2 -2
  37. package/dist/assets/{main-CWfC-9xT.js → main-V66ie29o.js} +4 -4
  38. package/dist/assets/{markdownCore-p2q2Kxwo.js → markdownCore-BRedKgCo.js} +1 -1
  39. package/dist/assets/{miniChat-x2TrwRYA.js → miniChat-BXwuEQhz.js} +2 -2
  40. package/dist/assets/{mobile-B0x2G8h1.js → mobile-7s-xLDG3.js} +2 -2
  41. package/dist/assets/{nativeFileSave-D542OJlG.js → nativeFileSave-Bj-V_9ae.js} +1 -1
  42. package/dist/assets/{pi-session-focus-preference-Q_RZUCnt.js → pi-session-focus-preference-clbekCjz.js} +1 -1
  43. package/dist/assets/{renderDiffWithHighlighter-CSFGSknx.js → renderDiffWithHighlighter-g9eKWi78.js} +1 -1
  44. package/dist/assets/{renderElectronMiniChatApp-CFIdesZT.js → renderElectronMiniChatApp-B6BN8YgC.js} +2 -2
  45. package/dist/assets/{renderFileWithHighlighter-C5JE0mRX.js → renderFileWithHighlighter-DKl6vubK.js} +1 -1
  46. package/dist/assets/{renderMobileApp-B1ybjcGM.js → renderMobileApp-Bp735rW7.js} +3 -3
  47. package/dist/assets/{runtimeEndpointReset-DyZSKCYM.js → runtimeEndpointReset-CtHv_OMT.js} +7 -7
  48. package/dist/assets/{runtimeSurface-BR_dhe7_.js → runtimeSurface-DD4Vn4HC.js} +1 -1
  49. package/dist/assets/{selection-CfOpW4rA.js → selection-DDT954wY.js} +1 -1
  50. package/dist/assets/useAppFontEffects-DJCrUN2D.js +226 -0
  51. package/dist/assets/{useGitHubRemoteSearch-M1AE2YuX.js → useGitHubRemoteSearch-B77fMiwQ.js} +1 -1
  52. package/dist/assets/{useSwitcherItems-D0i2BYYP.js → useSwitcherItems-CFY3mP06.js} +1 -1
  53. package/dist/assets/{web-components-wOQkOurQ.js → web-components-XIP_3VZv.js} +1 -1
  54. package/dist/index.html +3 -3
  55. package/dist/mini-chat.html +2 -2
  56. package/dist/mobile.html +2 -2
  57. package/package.json +2 -1
  58. package/pichamber.d.ts +139 -0
  59. package/plugins/subagents/extension.js +5 -5
  60. package/plugins/subagents/package.json +3 -2
  61. package/plugins/visuals/choices.js +8 -7
  62. package/plugins/visuals/extension.js +4 -4
  63. package/plugins/visuals/package.json +1 -1
  64. package/server/lib/marketplace/DOCUMENTATION.md +2 -2
  65. package/server/lib/marketplace/npm-registry.js +1 -1
  66. package/server/lib/marketplace/npm-registry.test.js +1 -1
  67. package/server/lib/marketplace/service.test.js +4 -4
  68. package/server/lib/open-url/DOCUMENTATION.md +1 -1
  69. package/server/lib/pi/extension-card.js +48 -0
  70. package/server/lib/pi/extension-card.test.js +35 -0
  71. package/server/lib/pi/extension-commands.js +49 -0
  72. package/server/lib/pi/extension-commands.test.js +38 -0
  73. package/server/lib/pi/extension-protocol.js +1 -2
  74. package/server/lib/pi/fixtures/pichamber-gui-demo.ts +52 -223
  75. package/server/lib/pi/routes-extension-events.test.js +35 -48
  76. package/server/lib/pi/routes.js +44 -54
  77. package/server/lib/pi/routes.test.js +32 -0
  78. package/server/lib/pi/session-daemon/DOCUMENTATION.md +7 -7
  79. package/server/lib/pi/session-daemon/extension-bridge-draft.test.js +0 -54
  80. package/server/lib/pi/session-daemon/extension-bridge.js +39 -162
  81. package/server/lib/pi/session-daemon/extension-controls.js +12 -57
  82. package/server/lib/pi/session-daemon/extension-controls.test.js +4 -34
  83. package/server/lib/pi/session-daemon/pichamber-api.js +38 -0
  84. package/server/lib/pi/session-daemon/pichamber-api.test.js +24 -0
  85. package/server/lib/pi/session-daemon/plugin-host.js +5 -7
  86. package/server/lib/pi/session-daemon/plugin-host.test.js +2 -3
  87. package/server/lib/pi/session-daemon/session-daemon-controls.e2e.test.js +53 -7
  88. package/server/lib/pi/session-daemon/session-daemon-drafts.e2e.test.js +5 -5
  89. package/server/lib/pi/session-daemon/session-daemon-extensions.e2e.test.js +9 -4
  90. package/server/lib/pi/session-daemon/session-daemon-extensions.test.js +28 -71
  91. package/server/lib/pi/session-daemon/session-daemon-plugins.e2e.test.js +1 -1
  92. package/server/lib/pi/session-daemon/session-daemon.js +138 -78
  93. package/server/lib/pi/session-daemon/session-daemon.test.js +68 -0
  94. package/server/lib/plugins/DOCUMENTATION.md +3 -3
  95. package/server/lib/plugins/impact.js +2 -4
  96. package/server/lib/plugins/impact.test.js +0 -1
  97. package/server/lib/plugins/manifest.js +9 -5
  98. package/server/lib/plugins/manifest.test.js +5 -4
  99. package/server/lib/plugins/store.test.js +1 -1
  100. package/server/lib/plugins/visuals-extension.test.js +16 -14
  101. package/dist/assets/useAppFontEffects-COMvkffC.js +0 -226
  102. package/server/lib/pi/session-daemon/pichamber-ui.js +0 -44
@@ -1,21 +1,18 @@
1
1
  import { randomUUID } from 'node:crypto';
2
2
 
3
+ import { CARD_ENTRY_TYPE, normalizeExtensionCard } from '../extension-card.js';
3
4
  import {
4
- MAX_EXTENSION_APP_HTML_CHARS,
5
5
  projectExtensionChooseFields,
6
6
  sanitizeExtensionFormFields,
7
7
  validateExtensionChoiceAnswer,
8
8
  validateExtensionFormValues,
9
9
  } from '../extension-protocol.js';
10
10
  import { handleBrowserArguments, isHttpUrl } from '../../open-url/browser-handler.mjs';
11
- import { createComposerControls } from './extension-controls.js';
11
+ import { createComposerControls, parseComposerControl } from './extension-controls.js';
12
12
  import { resolveExtensionName } from './extension-name.js';
13
13
  import { createExtensionTheme } from './extension-theme.js';
14
- import { PICHAMBER_UI } from './pichamber-ui.js';
14
+ import { PICHAMBER_API } from './pichamber-api.js';
15
15
 
16
- const MAX_EXTENSION_PANELS_PER_SESSION = 24;
17
- const MAX_EXTENSION_APPS_PER_SESSION = 8;
18
- const MAX_EXTENSION_PANEL_ACTIONS = 8;
19
16
  const MAX_EXTENSION_EDITOR_TEXT_CHARS = 100_000;
20
17
  const MAX_EXTENSION_TITLE_CHARS = 256;
21
18
  const MAX_EXTENSION_WORKING_CHARS = 200;
@@ -32,27 +29,23 @@ const textFromContent = (content) => (
32
29
 
33
30
  // Pi keeps `appendEntry` custom entries out of the TUI transcript; they
34
31
  // persist extension state. Only PiChamber GUI entries are meant to render.
32
+ // `pichamber.card` is what `pichamber.card()` saves; cards saved before the
33
+ // function existed carry `pichamber.ui` and read the same way.
34
+
35
35
  export const isDisplayedExtensionEntryType = (customType) => (
36
36
  typeof customType === 'string' && customType.startsWith('pichamber.')
37
37
  );
38
38
 
39
- export const extractExtensionDescriptor = (entry) => {
40
- if (!entry || typeof entry !== 'object' || entry.type !== 'custom') return undefined;
41
- if (!isDisplayedExtensionEntryType(entry.customType)) return undefined;
42
- const data = entry.data;
43
- if (!data || typeof data !== 'object' || Array.isArray(data)) return undefined;
44
- return data.ui && typeof data.ui === 'object' && !Array.isArray(data.ui) ? data.ui : data;
45
- };
46
-
47
- export const isIddExtensionEntry = (entry) => {
48
- const descriptor = extractExtensionDescriptor(entry);
49
- if (!descriptor) return false;
50
- if (entry.customType === 'pichamber.app') {
51
- const appId = typeof descriptor.appId === 'string' && descriptor.appId.length > 0
52
- ? descriptor.appId
53
- : (typeof descriptor.id === 'string' && descriptor.id.length > 0 ? descriptor.id : undefined);
54
- return Boolean(appId);
55
- }
39
+ // 1.0.6 and 1.0.7 kept two more entry kinds that no client ever drew: live
40
+ // panels (`pichamber.ui` with an `id`) and app surfaces (`pichamber.app`).
41
+ // Sessions saved then still hold them; they stay out of the transcript, as
42
+ // they always were.
43
+ export const isRetiredExtensionEntry = (entry) => {
44
+ if (entry?.type !== 'custom') return false;
45
+ if (entry.customType === 'pichamber.app') return true;
46
+ if (entry.customType !== 'pichamber.ui') return false;
47
+ const data = entry.data && typeof entry.data === 'object' ? entry.data : {};
48
+ const descriptor = data.ui && typeof data.ui === 'object' ? data.ui : data;
56
49
  return typeof descriptor.id === 'string' && descriptor.id.length > 0;
57
50
  };
58
51
 
@@ -67,6 +60,7 @@ export const createExtensionBridge = ({
67
60
  getSequence,
68
61
  protocolError,
69
62
  renderExtensionMessage,
63
+ appendSessionEntry,
70
64
  requestSessionShutdown,
71
65
  pendingInput,
72
66
  customHost,
@@ -77,8 +71,6 @@ export const createExtensionBridge = ({
77
71
  const extensionWidgetsBySession = new Map();
78
72
  const extensionComponentWidgetsBySession = new Map();
79
73
  const extensionWidgetRenderTimersBySession = new Map();
80
- const extensionPanelsBySession = new Map();
81
- const extensionAppsBySession = new Map();
82
74
  const extensionTitlesBySession = new Map();
83
75
  const extensionWorkingBySession = new Map();
84
76
  const extensionDraftBySession = new Map();
@@ -89,7 +81,7 @@ export const createExtensionBridge = ({
89
81
  // into public stream events; blocking dialogs are resolved by the
90
82
  // `extensions.respond` daemon command.
91
83
  const pendingExtensionDialogs = new Map();
92
- // Composer controls extensions declare on `pi.events` (extension-controls.js).
84
+ // Composer controls extensions declare with `pichamber.control` (extension-controls.js).
93
85
  const composerControls = createComposerControls({
94
86
  publish: (sessionId, payload) => publishForSession('extension.control', payload, sessionId),
95
87
  });
@@ -257,20 +249,14 @@ export const createExtensionBridge = ({
257
249
 
258
250
  const statuses = extensionStatusesBySession.get(sessionId);
259
251
  const widgets = extensionWidgetsBySession.get(sessionId);
260
- const panels = extensionPanelsBySession.get(sessionId);
261
- const apps = extensionAppsBySession.get(sessionId);
262
252
  if (statuses) for (const key of statuses.keys()) publishForSession('extension.status', { key }, sessionId);
263
253
  if (widgets) for (const key of widgets.keys()) publishForSession('extension.widget', { key }, sessionId);
264
- if (panels) for (const id of panels.keys()) publishForSession('extension.ui', { id, removed: true }, sessionId);
265
- if (apps) for (const appId of apps.keys()) publishForSession('extension.app', { appId, removed: true }, sessionId);
266
254
  if (extensionTitlesBySession.has(sessionId)) publishForSession('extension.title', {}, sessionId);
267
255
  if (extensionWorkingBySession.has(sessionId)) publishForSession('extension.working', {}, sessionId);
268
256
  // Stop browser draft sync; a later getEditorText() call re-enables it.
269
257
  if (extensionDraftTrackedSessions.has(sessionId)) publishForSession('extension.editor.track', { enabled: false }, sessionId);
270
258
  extensionStatusesBySession.delete(sessionId);
271
259
  extensionWidgetsBySession.delete(sessionId);
272
- extensionPanelsBySession.delete(sessionId);
273
- extensionAppsBySession.delete(sessionId);
274
260
  extensionTitlesBySession.delete(sessionId);
275
261
  extensionWorkingBySession.delete(sessionId);
276
262
  extensionDraftBySession.delete(sessionId);
@@ -289,8 +275,6 @@ export const createExtensionBridge = ({
289
275
  ...extensionStatusesBySession.keys(),
290
276
  ...extensionWidgetsBySession.keys(),
291
277
  ...extensionComponentWidgetsBySession.keys(),
292
- ...extensionPanelsBySession.keys(),
293
- ...extensionAppsBySession.keys(),
294
278
  ...extensionTitlesBySession.keys(),
295
279
  ...extensionWorkingBySession.keys(),
296
280
  ...extensionDraftBySession.keys(),
@@ -338,7 +322,7 @@ export const createExtensionBridge = ({
338
322
  }
339
323
  };
340
324
 
341
- const createExtensionUIContext = (sessionId) => {
325
+ const createExtensionUIContext = (sessionId, session) => {
342
326
  const extensionTheme = createExtensionTheme();
343
327
  const tuiStub = createTuiStub(sessionId);
344
328
 
@@ -384,8 +368,8 @@ export const createExtensionBridge = ({
384
368
  });
385
369
  };
386
370
 
387
- // PiChamber's own dialog calls, reached through `pichamber.ui.x(ctx, ...)`.
388
- const pichamberUi = {
371
+ // PiChamber's own calls, reached through `pichamber.x(ctx, ...)`.
372
+ const pichamberApi = {
389
373
  // Structured multi-input dialog resolved with a values object keyed by
390
374
  // field id.
391
375
  form: (title, fields, opts) => {
@@ -413,7 +397,7 @@ export const createExtensionBridge = ({
413
397
  // the question and the caller would wait forever.
414
398
  const question = typeof title === 'string' ? title.trim().slice(0, 512) : '';
415
399
  if (!question || fields.choices.length === 0) {
416
- return Promise.reject(new TypeError('pichamber.ui.choose needs a title and at least one choice with an id and a label.'));
400
+ return Promise.reject(new TypeError('pichamber.choose needs a title and at least one choice with an id and a label.'));
417
401
  }
418
402
  return dialog(
419
403
  'choose',
@@ -436,6 +420,20 @@ export const createExtensionBridge = ({
436
420
  });
437
421
  return code === 0;
438
422
  },
423
+ // A card in the chat: saved in the session as a `pichamber.card` entry,
424
+ // the same entry `pi.appendEntry('pichamber.card', card)` writes.
425
+ card: async (card) => {
426
+ const checked = normalizeExtensionCard(card);
427
+ if (checked.error) throw new TypeError(`pichamber.card: ${checked.error}.`);
428
+ appendSessionEntry(session, CARD_ENTRY_TYPE, checked.card);
429
+ },
430
+ // A control in the composer; `{ id, remove: true }` takes it away.
431
+ control: async (control) => {
432
+ if (!parseComposerControl(control)) {
433
+ throw new TypeError('pichamber.control needs a valid control: an id, a kind (toggle, cycle or action), a label and a command.');
434
+ }
435
+ composerControls.set(sessionId, control);
436
+ },
439
437
  };
440
438
 
441
439
  return {
@@ -458,8 +456,8 @@ export const createExtensionBridge = ({
458
456
  (response) => (typeof response?.value === 'string' ? response.value : undefined),
459
457
  ),
460
458
  // Nothing PiChamber-only goes on `ctx.ui` under a string name, so a
461
- // method Pi adds later is never shadowed; see `pichamber-ui.js`.
462
- [PICHAMBER_UI]: pichamberUi,
459
+ // method Pi adds later is never shadowed; see `pichamber-api.js`.
460
+ [PICHAMBER_API]: pichamberApi,
463
461
  editor: (title, prefill) => dialog(
464
462
  'editor',
465
463
  { title, ...(typeof prefill === 'string' ? { prefill } : {}) },
@@ -666,15 +664,13 @@ export const createExtensionBridge = ({
666
664
  } finally {
667
665
  if (providerObserver) providerObserver.suppress = false;
668
666
  }
669
- const entries = session.sessionManager?.getBranch?.() ?? session.sessionManager?.getEntries?.();
670
- rebuildSessionPanelsAndApps(session.sessionId, Array.isArray(entries) ? entries : []);
671
667
  publishCatalogChange(session.sessionId, { providers: true, resources: true, commands: true });
672
668
  };
673
669
 
674
670
  const buildExtensionBindings = (session) => {
675
671
  installMutationObservers(session);
676
672
  return {
677
- uiContext: createExtensionUIContext(session.sessionId),
673
+ uiContext: createExtensionUIContext(session.sessionId, session),
678
674
  // PiChamber hosts `ctx.ui.custom()` components and draws them in the
679
675
  // browser (extension-custom-host.js), so extensions see a TUI by
680
676
  // default. The "Extension interface" setting can report RPC instead, so
@@ -702,10 +698,6 @@ export const createExtensionBridge = ({
702
698
  replaceInstructions: navigateOptions?.replaceInstructions,
703
699
  label: navigateOptions?.label,
704
700
  });
705
- if (result?.cancelled !== true) {
706
- const entries = session.sessionManager?.getBranch?.() ?? session.sessionManager?.getEntries?.();
707
- rebuildSessionPanelsAndApps(session.sessionId, Array.isArray(entries) ? entries : []);
708
- }
709
701
  return { cancelled: result.cancelled };
710
702
  },
711
703
  switchSession: async (sessionPath, switchOptions) => {
@@ -808,113 +800,6 @@ export const createExtensionBridge = ({
808
800
  }, sessionId, directory);
809
801
  };
810
802
 
811
- const setNormalizedPanel = (sessionId, descriptor) => {
812
- const id = typeof descriptor.id === 'string' && descriptor.id.length > 0 ? descriptor.id.slice(0, 128) : '';
813
- if (!id) return undefined;
814
- const hasBody = typeof descriptor.component === 'string'
815
- || typeof descriptor.title === 'string'
816
- || Array.isArray(descriptor.actions);
817
- const removed = descriptor.removed === true || !hasBody;
818
- const panels = extensionPanelsBySession.get(sessionId) ?? new Map();
819
- const normalized = removed ? undefined : {
820
- id,
821
- ...(typeof descriptor.title === 'string' ? { title: descriptor.title.slice(0, 256) } : {}),
822
- ...(typeof descriptor.component === 'string' ? { component: descriptor.component.slice(0, 64) } : {}),
823
- ...(descriptor.props && typeof descriptor.props === 'object' && !Array.isArray(descriptor.props) ? { props: redactAttachmentValues(descriptor.props) } : {}),
824
- ...(Array.isArray(descriptor.actions) ? { actions: descriptor.actions.slice(0, MAX_EXTENSION_PANEL_ACTIONS) } : {}),
825
- };
826
- if (removed) {
827
- panels.delete(id);
828
- } else {
829
- panels.set(id, normalized);
830
- }
831
- if (panels.size > MAX_EXTENSION_PANELS_PER_SESSION) {
832
- const oldest = [...panels.keys()].slice(0, panels.size - MAX_EXTENSION_PANELS_PER_SESSION);
833
- for (const key of oldest) panels.delete(key);
834
- }
835
- if (panels.size === 0) extensionPanelsBySession.delete(sessionId);
836
- else extensionPanelsBySession.set(sessionId, panels);
837
- return { id, removed, normalized };
838
- };
839
-
840
- // Mirrors a declarative `pichamber.ui` descriptor into normalized panel
841
- // state and publishes an `extension.ui` event. Latest wins per stable id;
842
- // `removed: true` (or a payload without component/title) unregisters.
843
- const mirrorExtensionPanel = (sessionId, descriptor, directory) => {
844
- const result = setNormalizedPanel(sessionId, descriptor);
845
- if (!result) return;
846
- publish('extension.ui', result.removed ? { id: result.id, removed: true } : result.normalized, sessionId, directory);
847
- };
848
-
849
- const setNormalizedApp = (sessionId, descriptor) => {
850
- const appId = typeof descriptor.appId === 'string' && descriptor.appId.length > 0
851
- ? descriptor.appId.slice(0, 128)
852
- : (typeof descriptor.id === 'string' && descriptor.id.length > 0 ? descriptor.id.slice(0, 128) : '');
853
- if (!appId) return undefined;
854
- const html = typeof descriptor.html === 'string'
855
- ? (descriptor.html.length > MAX_EXTENSION_APP_HTML_CHARS ? descriptor.html.slice(0, MAX_EXTENSION_APP_HTML_CHARS) : descriptor.html)
856
- : undefined;
857
- const removed = descriptor.removed === true || !html || html.length === 0;
858
- const apps = extensionAppsBySession.get(sessionId) ?? new Map();
859
- if (removed) {
860
- apps.delete(appId);
861
- } else {
862
- apps.set(appId, {
863
- appId,
864
- ...(typeof descriptor.title === 'string' ? { title: descriptor.title.slice(0, 256) } : {}),
865
- html,
866
- });
867
- }
868
- if (apps.size > MAX_EXTENSION_APPS_PER_SESSION) {
869
- const oldest = [...apps.keys()].slice(0, apps.size - MAX_EXTENSION_APPS_PER_SESSION);
870
- for (const key of oldest) apps.delete(key);
871
- }
872
- if (apps.size === 0) extensionAppsBySession.delete(sessionId);
873
- else extensionAppsBySession.set(sessionId, apps);
874
- return {
875
- appId,
876
- removed,
877
- app: removed ? undefined : {
878
- appId,
879
- ...(typeof descriptor.title === 'string' ? { title: descriptor.title.slice(0, 256) } : {}),
880
- html,
881
- },
882
- };
883
- };
884
-
885
- // Mirrors a `pichamber.app` descriptor into normalized app state and
886
- // publishes an `extension.app` event. HTML is capped; removal unregisters.
887
- const mirrorExtensionApp = (sessionId, descriptor, directory) => {
888
- const result = setNormalizedApp(sessionId, descriptor);
889
- if (!result) return;
890
- publish('extension.app', {
891
- appId: result.appId,
892
- ...(result.removed ? { removed: true } : {
893
- ...(typeof descriptor.title === 'string' ? { title: descriptor.title.slice(0, 256) } : {}),
894
- html: descriptor.html && typeof descriptor.html === 'string' && descriptor.html.length > MAX_EXTENSION_APP_HTML_CHARS ? descriptor.html.slice(0, MAX_EXTENSION_APP_HTML_CHARS) : descriptor.html,
895
- }),
896
- }, sessionId, directory);
897
- };
898
-
899
- // Replays persisted custom entries on the active branch without publishing
900
- // events to restore live panel and app state across restarts and branch switches.
901
- const rebuildSessionPanelsAndApps = (sessionId, entries) => {
902
- if (!sessionId) return;
903
- extensionPanelsBySession.delete(sessionId);
904
- extensionAppsBySession.delete(sessionId);
905
- if (!Array.isArray(entries)) return;
906
- for (const entry of entries) {
907
- if (entry?.type !== 'custom' || !isDisplayedExtensionEntryType(entry.customType)) continue;
908
- const descriptor = extractExtensionDescriptor(entry);
909
- if (!descriptor) continue;
910
- if (entry.customType === 'pichamber.app') {
911
- setNormalizedApp(sessionId, descriptor);
912
- } else {
913
- setNormalizedPanel(sessionId, descriptor);
914
- }
915
- }
916
- };
917
-
918
803
  const updateExtensionDraft = (sessionId, text, revision) => {
919
804
  if (typeof sessionId !== 'string' || !sessionId) return { accepted: false };
920
805
  if (!extensionDraftTrackedSessions.has(sessionId)) return { accepted: false };
@@ -940,8 +825,6 @@ export const createExtensionBridge = ({
940
825
  if (!sessionId) return {};
941
826
  const statuses = extensionStatusesBySession.get(sessionId);
942
827
  const widgets = extensionWidgetsBySession.get(sessionId);
943
- const panels = extensionPanelsBySession.get(sessionId);
944
- const apps = extensionAppsBySession.get(sessionId);
945
828
  const title = extensionTitlesBySession.get(sessionId);
946
829
  const dialogs = [...pendingExtensionDialogs.values()]
947
830
  .filter((pending) => pending.sessionId === sessionId)
@@ -955,8 +838,6 @@ export const createExtensionBridge = ({
955
838
  ...(controls ? { controls } : {}),
956
839
  ...(widgets?.size ? { widgets: [...widgets.entries()].map(([key, widget]) => ({ key, ...widget })) } : {}),
957
840
  ...(dialogs.length ? { dialogs } : {}),
958
- ...(panels?.size ? { panels: [...panels.values()] } : {}),
959
- ...(apps?.size ? { apps: [...apps.values()] } : {}),
960
841
  ...(title ? { title } : {}),
961
842
  ...(working ? { working: { ...working } } : {}),
962
843
  ...(draftTracked ? { draftTracked: true } : {}),
@@ -968,15 +849,11 @@ export const createExtensionBridge = ({
968
849
  buildExtensionBindings,
969
850
  clearExtensionState,
970
851
  getSnapshotState,
971
- mirrorExtensionApp,
972
- mirrorExtensionPanel,
973
- rebuildSessionPanelsAndApps,
974
852
  publishExtensionCustomMessage,
975
853
  reloadSession,
976
854
  resetExtensionDraft,
977
855
  resolveExtensionDialog,
978
856
  updateExtensionDraft,
979
- setComposerControl: composerControls.set,
980
857
  resolveComposerControl: composerControls.resolve,
981
858
  };
982
859
  };
@@ -1,50 +1,35 @@
1
1
  // Composer controls declared by Pi extensions.
2
2
  //
3
- // A plain Pi extension puts a control in PiChamber's composer by emitting
4
- // `pichamber:composer` on Pi's shared extension event bus (`pi.events`). The
5
- // Pi CLI has no listener, so the same extension keeps working there through
6
- // its own slash commands. Each control names the extension's own commands; a
7
- // click in PiChamber runs one of them as if it had been typed, and the
8
- // extension reports its new value by emitting again. The extension stays the
9
- // only source of truth for the value.
3
+ // An extension puts a control in PiChamber's composer with
4
+ // `pichamber.control(ctx, control)`. Each control names the extension's own
5
+ // commands; a click in PiChamber runs one of them as if it had been typed,
6
+ // and the extension reports its new value by calling again. The extension
7
+ // stays the only source of truth for the value.
10
8
  //
11
- // pi.events.emit('pichamber:composer', {
9
+ // pichamber.control(ctx, {
12
10
  // id: 'mode', kind: 'cycle', label: 'Mode', value: 'balance',
13
11
  // options: [{ value: 'economy', label: 'Economy', command: 'economy' }, ...],
14
12
  // });
15
- // pi.events.emit('pichamber:composer', { id: 'mode', remove: true });
13
+ // pichamber.control(ctx, { id: 'mode', remove: true });
16
14
  //
17
15
  // Kinds: `toggle` (`value: boolean`, `command` flips it), `cycle` (`value`,
18
16
  // 2 to 12 `options`, each with its own command), `action` (`command` only).
19
17
 
20
- export const COMPOSER_CONTROL_EVENT = 'pichamber:composer';
18
+ // Command names and arguments follow the rule every extension surface shares.
19
+ import { parseExtensionCommandText } from '../extension-commands.js';
21
20
 
22
21
  const ID_PATTERN = /^[a-z0-9][a-z0-9-]{0,39}$/;
23
22
  const ICON_PATTERN = /^[a-z0-9][a-z0-9-]{0,47}$/;
24
- // Pi command invocation names: no spaces; Pi adds `:<n>` to tell apart two
25
- // extensions' commands of the same name.
26
- const COMMAND_NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9_.:-]{0,63}$/;
27
23
  const KINDS = new Set(['toggle', 'cycle', 'action']);
28
24
  export const MAX_CONTROLS_PER_SESSION = 16;
29
25
  const MAX_OPTIONS = 12;
30
- const MAX_PENDING = 64;
31
26
 
32
27
  const cleanText = (value, max) => (typeof value === 'string'
33
28
  ? value.replace(/[\u0000-\u001f\u007f-\u009f]/g, ' ').replace(/\s+/g, ' ').trim().slice(0, max)
34
29
  : '');
35
30
 
36
- /** `/plan on` or `plan on` → `plan on`; null when the name is not a command name. */
37
- const parseCommand = (value) => {
38
- const text = cleanText(value, 200).replace(/^\//, '');
39
- const name = text.split(' ')[0];
40
- return COMMAND_NAME_PATTERN.test(name) ? text : null;
41
- };
42
-
43
- /** The command's invocation name: the part before the first space. */
44
- export const commandName = (command) => command.split(' ')[0];
45
-
46
31
  /**
47
- * Validate one `pichamber:composer` payload. Returns the control,
32
+ * Validate one `pichamber.control` payload. Returns the control,
48
33
  * `{ id, remove: true }`, or null when the payload is not usable (it is then
49
34
  * ignored, like a malformed status).
50
35
  */
@@ -69,7 +54,7 @@ export const parseComposerControl = (raw) => {
69
54
  for (const option of raw.options.slice(0, MAX_OPTIONS)) {
70
55
  const value = cleanText(option?.value, 40);
71
56
  const optionLabel = cleanText(option?.label, 40) || value;
72
- const command = parseCommand(option?.command);
57
+ const command = parseExtensionCommandText(option?.command);
73
58
  if (!value || !command || options.some((existing) => existing.value === value)) return null;
74
59
  options.push({ value, label: optionLabel, command });
75
60
  }
@@ -77,7 +62,7 @@ export const parseComposerControl = (raw) => {
77
62
  const value = typeof raw.value === 'string' && options.some((option) => option.value === raw.value) ? raw.value : undefined;
78
63
  return { ...common, options, ...(value !== undefined ? { value } : {}) };
79
64
  }
80
- const command = parseCommand(raw.command);
65
+ const command = parseExtensionCommandText(raw.command);
81
66
  if (!command) return null;
82
67
  if (raw.kind === 'toggle') return { ...common, command, value: raw.value === true };
83
68
  return { ...common, command };
@@ -145,33 +130,3 @@ export const createComposerControls = ({ publish }) => {
145
130
 
146
131
  return { set, clear, snapshot, resolve, sessionIds };
147
132
  };
148
-
149
- /**
150
- * The extension factory that listens on a runtime's event bus. One runtime
151
- * hosts one session; the id is known from `session_start`, which reaches
152
- * this factory after the user's extensions (Pi loads factories last), so
153
- * controls emitted before it are held until then.
154
- */
155
- const COMPOSER_CONTROLS_EXTENSION_NAME = 'pichamber:composer-controls';
156
-
157
- /** Pi labels a named factory `<inline:name>`; this one is not listed as an extension. */
158
- export const isComposerControlsExtensionPath = (extensionPath) => extensionPath === `<inline:${COMPOSER_CONTROLS_EXTENSION_NAME}>`;
159
-
160
- export const createComposerControlsExtension = (onControl) => ({
161
- name: COMPOSER_CONTROLS_EXTENSION_NAME,
162
- hidden: true,
163
- factory: (pi) => {
164
- let sessionId;
165
- const pending = [];
166
- pi.events?.on?.(COMPOSER_CONTROL_EVENT, (data) => {
167
- if (sessionId) onControl(sessionId, data);
168
- else if (pending.length < MAX_PENDING) pending.push(data);
169
- });
170
- pi.on?.('session_start', (_event, ctx) => {
171
- const id = ctx?.sessionManager?.getSessionId?.();
172
- if (typeof id !== 'string' || id.length === 0) return;
173
- sessionId = id;
174
- for (const data of pending.splice(0)) onControl(sessionId, data);
175
- });
176
- },
177
- });
@@ -1,14 +1,11 @@
1
1
  import { describe, expect, it } from 'vitest';
2
2
 
3
3
  import {
4
- COMPOSER_CONTROL_EVENT,
5
4
  MAX_CONTROLS_PER_SESSION,
6
- commandName,
7
5
  createComposerControls,
8
- createComposerControlsExtension,
9
- isComposerControlsExtensionPath,
10
6
  parseComposerControl,
11
7
  } from './extension-controls.js';
8
+ import { commandName } from '../extension-commands.js';
12
9
 
13
10
  const MODES = {
14
11
  id: 'mode',
@@ -48,6 +45,7 @@ describe('parseComposerControl', () => {
48
45
 
49
46
  it('reads a removal', () => {
50
47
  expect(parseComposerControl({ id: 'mode', remove: true })).toEqual({ id: 'mode', remove: true });
48
+ expect(parseComposerControl({ id: 'mode', removed: true })).toBeNull();
51
49
  });
52
50
 
53
51
  it('drops a cycle value that is not one of its options', () => {
@@ -80,11 +78,9 @@ describe('parseComposerControl', () => {
80
78
  });
81
79
  });
82
80
 
83
- describe('commandName and the listener path', () => {
84
- it('reads the invocation name and recognises the listener', () => {
81
+ describe('commandName', () => {
82
+ it('reads the invocation name', () => {
85
83
  expect(commandName('review --staged')).toBe('review');
86
- expect(isComposerControlsExtensionPath('<inline:pichamber:composer-controls>')).toBe(true);
87
- expect(isComposerControlsExtensionPath('<inline:pichamber:visuals>')).toBe(false);
88
84
  });
89
85
  });
90
86
 
@@ -153,29 +149,3 @@ describe('createComposerControls', () => {
153
149
  expect(controls.resolve('s2', 'mode', 'premium')).toEqual({ error: 'CONTROL_NOT_FOUND' });
154
150
  });
155
151
  });
156
-
157
- describe('createComposerControlsExtension', () => {
158
- const fakePi = () => {
159
- const listeners = new Map();
160
- const handlers = new Map();
161
- return {
162
- events: { on: (event, listener) => listeners.set(event, listener), emit: (event, data) => listeners.get(event)?.(data) },
163
- on: (event, handler) => handlers.set(event, handler),
164
- start: (sessionId) => handlers.get('session_start')?.({ type: 'session_start' }, { sessionManager: { getSessionId: () => sessionId } }),
165
- };
166
- };
167
-
168
- it('holds controls emitted before session_start, then forwards them with the session id', () => {
169
- const received = [];
170
- const extension = createComposerControlsExtension((sessionId, data) => received.push([sessionId, data.id]));
171
- expect(extension).toMatchObject({ name: 'pichamber:composer-controls', hidden: true });
172
- const pi = fakePi();
173
- extension.factory(pi);
174
- pi.events.emit(COMPOSER_CONTROL_EVENT, { id: 'early' });
175
- expect(received).toEqual([]);
176
- pi.start('s1');
177
- pi.events.emit(COMPOSER_CONTROL_EVENT, { id: 'late' });
178
- pi.events.emit('other:event', { id: 'ignored' });
179
- expect(received).toEqual([['s1', 'early'], ['s1', 'late']]);
180
- });
181
- });
@@ -0,0 +1,38 @@
1
+ // PiChamber's extension API: the functions on `globalThis.pichamber`.
2
+ //
3
+ // They live on PiChamber's own object, not on Pi's `ctx.ui`, so a method Pi
4
+ // adds later with the same name and another shape cannot be shadowed by ours.
5
+ // Every function takes the tool or handler `ctx` first.
6
+ //
7
+ // The session's ui context carries the working implementations under a
8
+ // Symbol key. A Symbol cannot collide with any name Pi adds, and Pi's runner
9
+ // copies the ui context with an object spread, which keeps own symbol
10
+ // properties. `pichamber.x(ctx, ...)` reads them back from `ctx.ui`, so no
11
+ // session lookup is needed: `ctx` already identifies the session.
12
+
13
+ /** The one extension API version. A breaking change raises it. */
14
+ export const PICHAMBER_API_VERSION = 1;
15
+
16
+ export const PICHAMBER_API = Symbol.for('pichamber.api');
17
+
18
+ /** Every function of the API. `pichamber.d.ts` declares the same names. */
19
+ export const PICHAMBER_API_FUNCTIONS = Object.freeze(['choose', 'form', 'openUrl', 'card', 'control']);
20
+
21
+ /**
22
+ * `{ apiVersion, choose, form, openUrl, card, control }`. Every call returns
23
+ * a promise; a `ctx` with no PiChamber session behind it rejects with a
24
+ * `TypeError` and never throws synchronously.
25
+ */
26
+ export const createPichamberApi = () => {
27
+ const api = { apiVersion: PICHAMBER_API_VERSION };
28
+ for (const name of PICHAMBER_API_FUNCTIONS) {
29
+ api[name] = async (ctx, ...args) => {
30
+ const impl = ctx?.ui?.[PICHAMBER_API]?.[name];
31
+ if (typeof impl !== 'function') {
32
+ throw new TypeError(`pichamber.${name} needs the tool or handler \`ctx\` of a PiChamber session as its first argument.`);
33
+ }
34
+ return impl(...args);
35
+ };
36
+ }
37
+ return Object.freeze(api);
38
+ };
@@ -0,0 +1,24 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ import { describe, expect, it } from 'vitest';
3
+
4
+ import { PICHAMBER_API, PICHAMBER_API_FUNCTIONS, PICHAMBER_API_VERSION, createPichamberApi } from './pichamber-api.js';
5
+
6
+ describe('the pichamber API object', () => {
7
+ it('routes every function to the session behind ctx', async () => {
8
+ const api = createPichamberApi();
9
+ const calls = [];
10
+ const ctx = { ui: { [PICHAMBER_API]: Object.fromEntries(PICHAMBER_API_FUNCTIONS.map((name) => [name, (...args) => { calls.push([name, ...args]); return name; }])) } };
11
+ for (const name of PICHAMBER_API_FUNCTIONS) await expect(api[name](ctx, 'a', 'b')).resolves.toBe(name);
12
+ expect(calls).toEqual(PICHAMBER_API_FUNCTIONS.map((name) => [name, 'a', 'b']));
13
+ await expect(api.card({ ui: {} }, {})).rejects.toThrow(/pichamber\.card needs the tool or handler `ctx`/);
14
+ });
15
+
16
+ // Authors read `pichamber.d.ts`; it must name what the object really has.
17
+ it('is declared in full by pichamber.d.ts', async () => {
18
+ const types = await readFile(new URL('../../../../pichamber.d.ts', import.meta.url), 'utf8');
19
+ const declared = types.slice(types.indexOf('export interface PiChamber {'), types.indexOf('declare global'));
20
+ const members = [...declared.matchAll(/^ {2}(?:readonly )?(\w+)[(:]/gm)].map((match) => match[1]).sort();
21
+ expect(members).toEqual(Object.keys(createPichamberApi()).sort());
22
+ expect(declared).toContain(`readonly apiVersion: ${PICHAMBER_API_VERSION};`);
23
+ });
24
+ });
@@ -1,7 +1,6 @@
1
1
  import { realpath } from 'node:fs/promises';
2
2
  import { isAbsolute, relative, resolve } from 'node:path';
3
3
  import { fileURLToPath, pathToFileURL } from 'node:url';
4
- import { createPichamberUi } from './pichamber-ui.js';
5
4
 
6
5
  // Holds the PiChamber plugins the server configured through the private
7
6
  // `plugins.configure` command and turns the enabled ones into Pi extension
@@ -208,10 +207,10 @@ export const createPluginHost = ({
208
207
 
209
208
  /**
210
209
  * Entries for `resourceLoaderOptions.extensionFactories`, added after Pi's
211
- * built-ins. Each runtime's factory call gets its own `pichamber` handle; its
212
- * state listeners are dropped when that session shuts down.
210
+ * built-ins. Each runtime's factory call gets its own `plugin` handle, the
211
+ * plugin's stored state; its state listeners are dropped when that session
212
+ * shuts down. Everything else a plugin calls is on `globalThis.pichamber`.
213
213
  */
214
- const pichamberUi = createPichamberUi();
215
214
  const extensionFactories = () => [...loaded.values()].map((plugin) => ({
216
215
  name: `pichamber:${plugin.id}`,
217
216
  replaceable: plugin.replaceable,
@@ -221,9 +220,8 @@ export const createPluginHost = ({
221
220
  pi.on?.('session_shutdown', () => {
222
221
  plugin.listeners.delete(runtimeListeners);
223
222
  });
224
- const pichamber = Object.freeze({
223
+ const handle = Object.freeze({
225
224
  id: plugin.id,
226
- ui: pichamberUi,
227
225
  state: (directory, sessionId) => resolveState(loaded.get(plugin.id) ?? plugin, directory, sessionId),
228
226
  onStateChange: (listener) => {
229
227
  if (typeof listener !== 'function') return () => {};
@@ -231,7 +229,7 @@ export const createPluginHost = ({
231
229
  return () => runtimeListeners.delete(listener);
232
230
  },
233
231
  });
234
- await plugin.factory(recordRegistrations(plugin.id, pi), pichamber);
232
+ await plugin.factory(recordRegistrations(plugin.id, pi), handle);
235
233
  },
236
234
  }));
237
235
 
@@ -34,7 +34,7 @@ describe('daemon plugin host', () => {
34
34
  expect(createPluginHost().extensionFactories()).toEqual([]);
35
35
  });
36
36
 
37
- it('builds named factories that receive pichamber with resolved state', async () => {
37
+ it('builds named factories that receive the plugin handle with resolved state', async () => {
38
38
  const root = await pluginsRoot({ demo: 'export default function (pi, pichamber) { globalThis.__pluginHostDemo = { pi, pichamber }; }' });
39
39
  const host = createPluginHost({ pluginsRoot: root });
40
40
  const result = await host.configure({
@@ -47,8 +47,7 @@ describe('daemon plugin host', () => {
47
47
  await factories[0].factory(pi);
48
48
  const { pichamber } = globalThis.__pluginHostDemo;
49
49
  expect(pichamber.id).toBe('demo');
50
- expect(Object.keys(pichamber.ui).sort()).toEqual(['choose', 'form', 'openUrl']);
51
- await expect(pichamber.ui.choose(undefined, 'T', [])).rejects.toBeInstanceOf(TypeError);
50
+ expect(Object.keys(pichamber).sort()).toEqual(['id', 'onStateChange', 'state']);
52
51
  expect(pichamber.state('/p')).toEqual({ on: true, mode: 'b' });
53
52
  expect(pichamber.state('/p/')).toEqual({ on: true, mode: 'b' });
54
53
  expect(pichamber.state('/q')).toEqual({ on: true, mode: 'a' });