@pi-chamber/web 1.0.8-rc.2 → 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 (113) hide show
  1. package/dist/assets/{AgentsSurface-CcWBqAWV.js → AgentsSurface-DbCBygRD.js} +1 -1
  2. package/dist/assets/{ChoicesArtifact-Kk-qvrSB.js → ChoicesArtifact-DUqhCvXh.js} +1 -1
  3. package/dist/assets/{DiagramView-DZUBo1uP.js → DiagramView-CnVOyJd2.js} +1 -1
  4. package/dist/assets/{DiffView-CiZy4jFA.js → DiffView-Db8JXsvA.js} +1 -1
  5. package/dist/assets/{FileSaveConflictDialog-DZ9NDwOO.js → FileSaveConflictDialog-D6xyf709.js} +1 -1
  6. package/dist/assets/{FilesView-DqiZ9kw9.js → FilesView-Cir0Wl9F.js} +1 -1
  7. package/dist/assets/{GitHubDetailScaffold-DM2DH7o8.js → GitHubDetailScaffold-US37Di_K.js} +1 -1
  8. package/dist/assets/{GitHubLinkPicker-ChB8NZ1h.js → GitHubLinkPicker-k_D-sk-e.js} +1 -1
  9. package/dist/assets/{GitHubListPrimitives-CibDiJGq.js → GitHubListPrimitives-DuUXrJGk.js} +1 -1
  10. package/dist/assets/{GitView--EaZQrBr.js → GitView-BdX_3XRr.js} +3 -3
  11. package/dist/assets/{IssuesSurface-CySTpaD1.js → IssuesSurface-Cw93HC0G.js} +2 -2
  12. package/dist/assets/{JsonTreeView-_yMHKKQZ.js → JsonTreeView-Bze4htWt.js} +1 -1
  13. package/dist/assets/{MarkdownRendererImpl-D_-2fQw0.js → MarkdownRendererImpl-Ch7NDkF9.js} +1 -1
  14. package/dist/assets/{PatchDiff-bHObDlhD.js → PatchDiff-l68Yz45X.js} +1 -1
  15. package/dist/assets/{PierreDiffViewer-UY7Cse-s.js → PierreDiffViewer-BHBySiXQ.js} +1 -1
  16. package/dist/assets/{PullRequestsSurface-iXy6chwc.js → PullRequestsSurface-CGD4_ljc.js} +2 -2
  17. package/dist/assets/{SessionSwitcherContent-DJGCa_wN.js → SessionSwitcherContent-DqP8OWzB.js} +1 -1
  18. package/dist/assets/{SessionSwitcherDropdown-CDOX-5Y2.js → SessionSwitcherDropdown-BkTg-cVd.js} +2 -2
  19. package/dist/assets/{SessionUnreadDot-Dwc3MdvA.js → SessionUnreadDot-CgvC3F5e.js} +1 -1
  20. package/dist/assets/SettingsView-CkIxCYhs.js +11 -0
  21. package/dist/assets/{SettingsWindow-CUg49Mfh.js → SettingsWindow-DSdhzapT.js} +1 -1
  22. package/dist/assets/{SubagentsArtifact-DUZX9tDe.js → SubagentsArtifact-BN3aX_8M.js} +1 -1
  23. package/dist/assets/{ToolOutputDialog-BuZZaRw4.js → ToolOutputDialog-CLwm4TjA.js} +1 -1
  24. package/dist/assets/{ToolPartDiffPreview-CKncG6i2.js → ToolPartDiffPreview-ERAStEKA.js} +1 -1
  25. package/dist/assets/{VirtualizedFileDiff-BGZiLPe_.js → VirtualizedFileDiff-DwR2fZHv.js} +1 -1
  26. package/dist/assets/VisualFrame-Dwp7B_st.js +22 -0
  27. package/dist/assets/{VisualsArtifact-Bq0vMO-i.js → VisualsArtifact-DlOxifHd.js} +1 -1
  28. package/dist/assets/{collapsible-Bro9KrfM.js → collapsible-CW-_qd6v.js} +1 -1
  29. package/dist/assets/{computeVirtualFileMetrics-DJQqK49u.js → computeVirtualFileMetrics-SlBfr8LB.js} +1 -1
  30. package/dist/assets/{contextFileOpenGuard-ByWK3Sru.js → contextFileOpenGuard-CHoFT50j.js} +1 -1
  31. package/dist/assets/{fileTreeStatus-CyJ3TOYD.js → fileTreeStatus-D0uiC1D0.js} +1 -1
  32. package/dist/assets/{gitStatusPredicates-BsXrwngT.js → gitStatusPredicates-Bj3pkh2e.js} +1 -1
  33. package/dist/assets/{githubLink-g2bmC0qi.js → githubLink-CheLNuP0.js} +1 -1
  34. package/dist/assets/index-BFkW-BPM.js +11 -0
  35. package/dist/assets/index-C5JgjS20.css +1 -0
  36. package/dist/assets/{index-C9rUUQ_Y.js → index-C8zaLvup.js} +1 -1
  37. package/dist/assets/{main-DT-4_fhe.js → main-CUEqZRu1.js} +2 -2
  38. package/dist/assets/{main-DsLMU9CT.js → main-V66ie29o.js} +4 -4
  39. package/dist/assets/{markdownCore-QmM_aOnZ.js → markdownCore-BRedKgCo.js} +1 -1
  40. package/dist/assets/{miniChat-BqGslD2z.js → miniChat-BXwuEQhz.js} +2 -2
  41. package/dist/assets/{mobile-C5JOcDIC.js → mobile-7s-xLDG3.js} +2 -2
  42. package/dist/assets/{nativeFileSave-DSMsJqXM.js → nativeFileSave-Bj-V_9ae.js} +1 -1
  43. package/dist/assets/{pi-session-focus-preference-Cc_S4zi1.js → pi-session-focus-preference-clbekCjz.js} +1 -1
  44. package/dist/assets/{renderDiffWithHighlighter-BXhnIAHg.js → renderDiffWithHighlighter-g9eKWi78.js} +1 -1
  45. package/dist/assets/{renderElectronMiniChatApp-CiSkecEE.js → renderElectronMiniChatApp-B6BN8YgC.js} +2 -2
  46. package/dist/assets/{renderFileWithHighlighter-CK29YZtC.js → renderFileWithHighlighter-DKl6vubK.js} +1 -1
  47. package/dist/assets/{renderMobileApp-C4JuoxsZ.js → renderMobileApp-Bp735rW7.js} +3 -3
  48. package/dist/assets/{runtimeEndpointReset-Dwj-jCDS.js → runtimeEndpointReset-CtHv_OMT.js} +7 -7
  49. package/dist/assets/{runtimeSurface-0K7vuUpd.js → runtimeSurface-DD4Vn4HC.js} +1 -1
  50. package/dist/assets/{selection-CnYkEsu_.js → selection-DDT954wY.js} +1 -1
  51. package/dist/assets/useAppFontEffects-DJCrUN2D.js +226 -0
  52. package/dist/assets/{useGitHubRemoteSearch-CgP-zEBj.js → useGitHubRemoteSearch-B77fMiwQ.js} +1 -1
  53. package/dist/assets/{useSwitcherItems-C8G5F0hs.js → useSwitcherItems-CFY3mP06.js} +1 -1
  54. package/dist/assets/{web-components-BpncHjnV.js → web-components-XIP_3VZv.js} +1 -1
  55. package/dist/index.html +4 -4
  56. package/dist/mini-chat.html +3 -3
  57. package/dist/mobile.html +3 -3
  58. package/package.json +2 -1
  59. package/pichamber.d.ts +139 -0
  60. package/plugins/subagents/extension.js +5 -5
  61. package/plugins/subagents/package.json +3 -2
  62. package/plugins/visuals/choices.js +8 -7
  63. package/plugins/visuals/extension.js +6 -6
  64. package/plugins/visuals/package.json +1 -1
  65. package/server/index.js +4 -0
  66. package/server/lib/marketplace/DOCUMENTATION.md +2 -2
  67. package/server/lib/marketplace/npm-registry.js +1 -1
  68. package/server/lib/marketplace/npm-registry.test.js +1 -1
  69. package/server/lib/marketplace/service.test.js +4 -4
  70. package/server/lib/open-url/DOCUMENTATION.md +1 -1
  71. package/server/lib/pi/extension-card.js +48 -0
  72. package/server/lib/pi/extension-card.test.js +35 -0
  73. package/server/lib/pi/extension-commands.js +49 -0
  74. package/server/lib/pi/extension-commands.test.js +38 -0
  75. package/server/lib/pi/extension-protocol.js +1 -2
  76. package/server/lib/pi/fixtures/pichamber-gui-demo.ts +52 -223
  77. package/server/lib/pi/routes-extension-events.test.js +35 -48
  78. package/server/lib/pi/routes.js +44 -54
  79. package/server/lib/pi/routes.test.js +32 -0
  80. package/server/lib/pi/session-daemon/DOCUMENTATION.md +7 -7
  81. package/server/lib/pi/session-daemon/extension-bridge-draft.test.js +0 -54
  82. package/server/lib/pi/session-daemon/extension-bridge.js +39 -162
  83. package/server/lib/pi/session-daemon/extension-controls.js +12 -57
  84. package/server/lib/pi/session-daemon/extension-controls.test.js +4 -34
  85. package/server/lib/pi/session-daemon/pichamber-api.js +38 -0
  86. package/server/lib/pi/session-daemon/pichamber-api.test.js +24 -0
  87. package/server/lib/pi/session-daemon/plugin-host.js +5 -7
  88. package/server/lib/pi/session-daemon/plugin-host.test.js +2 -3
  89. package/server/lib/pi/session-daemon/session-daemon-controls.e2e.test.js +53 -7
  90. package/server/lib/pi/session-daemon/session-daemon-drafts.e2e.test.js +5 -5
  91. package/server/lib/pi/session-daemon/session-daemon-extensions.e2e.test.js +9 -4
  92. package/server/lib/pi/session-daemon/session-daemon-extensions.test.js +28 -71
  93. package/server/lib/pi/session-daemon/session-daemon-plugins.e2e.test.js +1 -1
  94. package/server/lib/pi/session-daemon/session-daemon.js +138 -78
  95. package/server/lib/pi/session-daemon/session-daemon.test.js +68 -0
  96. package/server/lib/pi/ui-settings-store.js +2 -1
  97. package/server/lib/plugins/DOCUMENTATION.md +3 -3
  98. package/server/lib/plugins/impact.js +2 -4
  99. package/server/lib/plugins/impact.test.js +0 -1
  100. package/server/lib/plugins/manifest.js +9 -5
  101. package/server/lib/plugins/manifest.test.js +5 -4
  102. package/server/lib/plugins/store.test.js +1 -1
  103. package/server/lib/plugins/visuals-extension.test.js +16 -14
  104. package/server/lib/wallpaper/DOCUMENTATION.md +25 -0
  105. package/server/lib/wallpaper/routes.js +63 -0
  106. package/server/lib/wallpaper/routes.test.js +109 -0
  107. package/server/lib/wallpaper/store.js +87 -0
  108. package/dist/assets/SettingsView-DA-U9lsj.js +0 -11
  109. package/dist/assets/VisualFrame-DBZkHFnG.js +0 -22
  110. package/dist/assets/index-B_L9GVYw.css +0 -1
  111. package/dist/assets/index-CKKWVoND.js +0 -11
  112. package/dist/assets/useAppFontEffects-CV5UyTRw.js +0 -226
  113. package/server/lib/pi/session-daemon/pichamber-ui.js +0 -44
@@ -1,250 +1,79 @@
1
1
  /**
2
- * Reference pi extension that works in plain pi CLI via normal pi APIs and
3
- * optionally renders rich UI in PiChamber.
4
- *
5
- * Drop this file into `~/.pi/agent/extensions/pichamber-gui-demo.ts` to try it:
2
+ * Reference Pi extension that works in the plain Pi CLI and uses PiChamber's
3
+ * extension API when it is there.
6
4
  *
7
5
  * pi -e ./pichamber-gui-demo.ts
8
6
  *
9
- * Or place it under `.pi/extensions/` for a single project.
7
+ * Or drop it into `~/.pi/agent/extensions/`, or `.pi/extensions/` for one
8
+ * project. `globalThis.pichamber` is undefined in the CLI, so every PiChamber
9
+ * call below sits behind that one check and has a plain fallback.
10
10
  *
11
- * PiChamber detection is optional and never required: the tool, commands,
12
- * and hooks work without PiChamber, and the `pichamber.ui` card degrades to a
13
- * generic JSON card in the CLI transcript.
11
+ * Types: `@pi-chamber/web/pichamber` (`pichamber.d.ts`).
14
12
  */
15
13
 
16
- import type { ExtensionAPI } from '@earendil-works/pi-coding-agent';
17
- import { Type } from 'typebox';
18
-
19
- // Inline helpers keep the extension independent of PiChamber packages. Copy
20
- // the same detection and descriptor shape into extensions that opt into the GUI.
21
- const isPiChamber = (ctx: { mode: string; hasUI: boolean }): boolean => {
22
- const marker = (globalThis as unknown as Record<string, unknown>).__PICHAMBER__ as
23
- | { version?: number }
24
- | undefined;
25
- if (marker?.version) return true;
26
- try {
27
- if (typeof process !== 'undefined' && (process as unknown as { env?: Record<string, string> }).env?.PICHAMBER === '1') return true;
28
- } catch {}
29
- return ctx.mode === 'rpc' && ctx.hasUI === true;
30
- };
14
+ import type { ExtensionAPI, ExtensionContext } from '@earendil-works/pi-coding-agent';
15
+ import type { PiChamber } from '../../../../pichamber.js';
31
16
 
32
- const publishUi = (
33
- pi: Pick<ExtensionAPI, 'appendEntry'>,
34
- payload: Record<string, unknown>,
35
- ) => {
36
- pi.appendEntry('pichamber.ui', {
37
- protocol: 'pichamber-extension-ui',
38
- version: 1,
39
- ...payload,
40
- });
41
- };
42
-
43
- const publishApp = (
44
- pi: Pick<ExtensionAPI, 'appendEntry'>,
45
- payload: Record<string, unknown>,
46
- ) => {
47
- pi.appendEntry('pichamber.app', {
48
- protocol: 'pichamber-extension-ui',
49
- version: 1,
50
- ...payload,
51
- });
52
- };
53
-
54
- type SubagentRecord = {
55
- id: string;
56
- name: string;
57
- status: 'running' | 'done' | 'error';
58
- task: string;
59
- };
17
+ const pichamber = (globalThis as { pichamber?: PiChamber }).pichamber;
60
18
 
61
19
  export default function (pi: ExtensionAPI): void {
62
- // In-memory state owned by the extension. PiChamber mirrors the `subagents`
63
- // snapshot as a server-side normalized map (statuses/widgets) so a phone
64
- // that connects later sees the current list without the extension resending.
65
- const subagents = new Map<string, SubagentRecord>();
66
- let appVisible = false;
67
-
68
- const renderSubagents = () => {
69
- const agents = [...subagents.values()];
70
- if (agents.length === 0) {
71
- publishUi(pi, {
72
- id: 'pichamber-demo-subagents',
73
- title: 'Sub-agents',
74
- component: 'markdown',
75
- props: { body: '_No sub-agents running._' },
76
- });
77
- return;
78
- }
79
-
80
- publishUi(pi, {
81
- id: 'pichamber-demo-subagents',
82
- title: 'Sub-agents',
83
- component: 'table',
84
- props: {
85
- columns: ['Agent', 'Status', 'Task'],
86
- rows: agents.map((agent) => [agent.name, agent.status, agent.task]),
87
- },
88
- actions: [
89
- { label: 'Clear finished', command: 'pichamber-demo-clear', variant: 'ghost' as const },
90
- { label: 'Spawn…', command: 'pichamber-demo-spawn', promptForArgs: { label: 'Agent name' } },
91
- ],
92
- });
93
- };
20
+ let plan = false;
94
21
 
95
- // Standard pi tool: callable by the model from any host.
96
- pi.registerTool({
97
- name: 'pichamber_demo_spawn',
98
- label: 'Demo: spawn sub-agent',
99
- description: 'Demo tool that pretends to spawn a sub-agent and publishes PiChamber GUI state.',
100
- parameters: Type.Object({
101
- name: Type.String({ description: 'Sub-agent name' }),
102
- task: Type.String({ description: 'Task description' }),
103
- }),
104
- async execute(_toolCallId, params) {
105
- const id = `agent-${Date.now().toString(36)}`;
106
- subagents.set(id, { id, name: params.name, status: 'running', task: params.task });
107
-
108
- // Optional PiChamber enhancement: publish a table that updates in place
109
- // (same `id` replaces the previous card; transcript history stays as fallback).
110
- renderSubagents();
111
-
112
- // Simulate async completion without actually spawning work, so the demo
113
- // remains useful without credentials or side effects.
114
- setTimeout(() => {
115
- const existing = subagents.get(id);
116
- if (existing) {
117
- existing.status = 'done';
118
- renderSubagents();
119
- }
120
- }, 800).unref?.();
121
-
122
- return {
123
- content: [{ type: 'text', text: `Spawned demo sub-agent "${params.name}" (${id}) for: ${params.task}` }],
124
- details: { subagentId: id, name: params.name, task: params.task },
125
- };
126
- },
22
+ // A toggle in the composer. The extension keeps the value; a click runs
23
+ // `/demo-plan`, which declares the control again with the new value.
24
+ const declarePlan = (ctx: ExtensionContext) => pichamber?.control(ctx, {
25
+ id: 'plan', kind: 'toggle', label: 'Plan', description: 'Plan before editing', value: plan, command: 'demo-plan',
127
26
  });
128
-
129
- // Standard slash commands: discoverable via `extensions.list` and invokable
130
- // through PiChamber's prompt path (action buttons also use this path).
131
- pi.registerCommand('pichamber-demo-subagents', {
132
- description: 'Show demo sub-agents',
27
+ pi.on('session_start', async (_event, ctx) => { await declarePlan(ctx); });
28
+ pi.registerCommand('demo-plan', {
29
+ description: 'Toggle plan mode',
133
30
  handler: async (_args, ctx) => {
134
- if (isPiChamber(ctx)) {
135
- renderSubagents();
136
- ctx.ui.notify(`Demo sub-agents: ${subagents.size} tracked`, 'info');
137
- return;
138
- }
139
- // CLI fallback: plain notification, no PiChamber card needed.
140
- ctx.ui.notify(`Demo sub-agents (${subagents.size}): ${[...subagents.values()].map((agent) => `${agent.name}:${agent.status}`).join(', ') || 'none'}`, 'info');
31
+ plan = !plan;
32
+ await declarePlan(ctx);
33
+ if (!pichamber) ctx.ui.notify(`Plan mode ${plan ? 'on' : 'off'}`, 'info');
141
34
  },
142
35
  });
143
36
 
144
- pi.registerCommand('pichamber-demo-clear', {
145
- description: 'Clear finished demo sub-agents',
37
+ // A card in the chat with a button that runs `/demo-plan`.
38
+ pi.registerCommand('demo-status', {
39
+ description: 'Show the demo status',
146
40
  handler: async (_args, ctx) => {
147
- for (const [id, agent] of subagents) {
148
- if (agent.status === 'done') subagents.delete(id);
41
+ if (!pichamber) {
42
+ ctx.ui.notify(`Plan mode is ${plan ? 'on' : 'off'}`, 'info');
43
+ return;
149
44
  }
150
- if (isPiChamber(ctx)) renderSubagents();
151
- ctx.ui.notify('Cleared finished demo sub-agents', 'info');
152
- },
153
- });
154
-
155
- pi.registerCommand('pichamber-demo-progress', {
156
- description: 'Show a progress demo card',
157
- handler: async (args) => {
158
- const value = Math.max(0, Math.min(100, Number(args) || 40));
159
- publishUi(pi, {
160
- id: 'pichamber-demo-progress',
161
- title: 'Demo progress',
162
- component: 'progress',
163
- props: { label: 'Indexing', value, max: 100 },
164
- actions: [{ label: 'Reset', command: 'pichamber-demo-progress', args: '0' }],
45
+ await pichamber.card(ctx, {
46
+ title: 'Demo status',
47
+ component: 'kv',
48
+ props: { rows: [{ label: 'Plan mode', value: plan ? 'On' : 'Off', tone: plan ? 'success' : 'neutral' }] },
49
+ actions: [{ label: plan ? 'Turn plan off' : 'Turn plan on', command: 'demo-plan' }],
165
50
  });
166
51
  },
167
52
  });
168
53
 
169
- // Structured multi-input dialog. PiChamber renders a native form and
170
- // resolves with a values object; plain pi falls back to sequential prompts.
171
- type PichamberHandle = {
172
- ui: { form: (ctx: unknown, title: string, fields: Array<Record<string, unknown>>) => Promise<Record<string, string> | undefined> };
173
- };
174
- type FormCtx = Parameters<NonNullable<Parameters<ExtensionAPI['registerCommand']>[1]['handler']>>[1];
175
- const askAgent = async (ctx: FormCtx): Promise<{ name: string; task: string } | undefined> => {
176
- const pichamber = (globalThis as { pichamber?: PichamberHandle }).pichamber;
177
- if (isPiChamber(ctx) && pichamber) {
178
- const values = await pichamber.ui.form(ctx, 'Spawn sub-agent', [
179
- { id: 'name', label: 'Name', type: 'text', required: true, placeholder: 'research' },
180
- { id: 'task', label: 'Task', type: 'textarea', required: true },
181
- { id: 'priority', label: 'Priority', type: 'select', options: ['low', 'normal', 'high'], initial: 'normal' },
182
- ]);
183
- if (!values?.name || !values.task) return undefined;
184
- return { name: values.name, task: values.task };
185
- }
186
- const name = await ctx.ui.input('Sub-agent name');
187
- if (!name) return undefined;
188
- const task = await ctx.ui.input('Task description');
189
- if (!task) return undefined;
190
- return { name, task };
191
- };
192
-
193
- pi.registerCommand('pichamber-demo-spawn', {
194
- description: 'Spawn a demo sub-agent interactively (form dialog in PiChamber)',
195
- handler: async (args, ctx) => {
196
- let name = args?.trim() ?? '';
197
- let task = name ? `demo task for ${name}` : '';
198
- if (!name) {
199
- const answers = await askAgent(ctx);
200
- if (!answers) return;
201
- ({ name, task } = answers);
202
- }
203
- const id = `agent-${Date.now().toString(36)}`;
204
- subagents.set(id, { id, name, status: 'running', task });
205
- renderSubagents();
206
- ctx.ui.notify(`Spawned ${name}`, 'info');
207
- },
208
- });
209
-
210
- // Sandboxed app surface: self-contained HTML rendered in an iframe that can
211
- // only invoke registered commands through data-pichamber-command buttons.
212
- pi.registerCommand('pichamber-demo-app', {
213
- description: 'Toggle a sandboxed demo app surface (PiChamber only)',
54
+ // A question with described choices, and a form; Pi's own dialogs otherwise.
55
+ pi.registerCommand('demo-ask', {
56
+ description: 'Ask a question',
214
57
  handler: async (_args, ctx) => {
215
- if (!isPiChamber(ctx)) {
216
- ctx.ui.notify('App surfaces are a PiChamber feature', 'warning');
217
- return;
218
- }
219
- if (appVisible) {
220
- publishApp(pi, { appId: 'demo-board', removed: true });
221
- appVisible = false;
222
- return;
58
+ const sizes = [
59
+ { id: 's', label: 'Small', description: 'One file' },
60
+ { id: 'l', label: 'Large', description: 'The whole package' },
61
+ ];
62
+ let size: string | undefined;
63
+ if (pichamber) {
64
+ size = (await pichamber.choose(ctx, 'How big is the change?', sizes, { allowNote: true }))?.id;
65
+ } else {
66
+ const label = await ctx.ui.select('How big is the change?', sizes.map((choice) => choice.label));
67
+ size = sizes.find((choice) => choice.label === label)?.id;
223
68
  }
224
- publishApp(pi, {
225
- appId: 'demo-board',
226
- title: 'Demo board',
227
- html: `<!doctype html><html><body style="font-family:system-ui;padding:12px">
228
- <h3 style="margin:0 0 8px">Demo board</h3>
229
- <button data-pichamber-command="pichamber-demo-subagents">Refresh panel</button>
230
- <button data-pichamber-command="pichamber-demo-clear">Clear finished</button>
231
- <p style="color:#666">Buttons fire slash commands through PiChamber's authenticated prompt path.</p>
232
- </body></html>`,
233
- });
234
- appVisible = true;
69
+ if (!size) return;
70
+ const answers = pichamber
71
+ ? await pichamber.form(ctx, 'Describe it', [
72
+ { id: 'title', label: 'Title', required: true },
73
+ { id: 'tests', label: 'Add tests', type: 'checkbox' },
74
+ ])
75
+ : { title: await ctx.ui.input('Title') ?? '' };
76
+ if (answers?.title) ctx.ui.notify(`${size === 's' ? 'Small' : 'Large'} change: ${answers.title}`, 'info');
235
77
  },
236
78
  });
237
-
238
- // Lifecycle hooks run identically inside PiChamber and plain pi. They do not
239
- // need PiChamber-specific branching, but can optionally publish UI when that
240
- // capability is present.
241
- pi.on('session_start', async (_event, ctx) => {
242
- if (isPiChamber(ctx)) {
243
- ctx.ui.setStatus('pichamber-demo', 'Demo extension active');
244
- }
245
- });
246
-
247
- pi.on('session_shutdown', async () => {
248
- subagents.clear();
249
- });
250
79
  }
@@ -40,49 +40,6 @@ describe('extension public projections', () => {
40
40
  commands: [],
41
41
  })).toThrow();
42
42
  });
43
- it('projects extension.ui panels with caps and removals', () => {
44
- const projected = projectEventFrame(frame('extension.ui', {
45
- id: 'subagents',
46
- title: 'Sub-agents',
47
- component: 'table',
48
- props: { columns: ['Agent'], rows: [['research']] },
49
- actions: [{ label: 'Clear', command: 'agents-clear' }],
50
- }));
51
- expect(projected).toMatchObject({
52
- name: 'extension.ui',
53
- payload: { id: 'subagents', title: 'Sub-agents', component: 'table' },
54
- });
55
-
56
- // Missing component and title is treated as an unregister.
57
- expect(projectEventFrame(frame('extension.ui', { id: 'gone' }))).toMatchObject({
58
- payload: { id: 'gone', removed: true },
59
- });
60
-
61
- // Invalid ids are dropped entirely.
62
- expect(projectEventFrame(frame('extension.ui', { id: '' }))).toBeNull();
63
- expect(projectEventFrame(frame('extension.ui', { id: `${'x'.repeat(200)}` }))).toBeNull();
64
- });
65
-
66
- it('projects extension.app payloads and rejects oversized html', () => {
67
- const projected = projectEventFrame(frame('extension.app', {
68
- appId: 'board',
69
- title: 'Board',
70
- html: '<button data-pichamber-command="run">Run</button>',
71
- }));
72
- expect(projected?.payload).toMatchObject({ appId: 'board', title: 'Board' });
73
- expect(projected?.payload.html).toContain('data-pichamber-command');
74
-
75
- expect(projectEventFrame(frame('extension.app', {
76
- appId: 'big',
77
- html: `${'<a>'.repeat(70_000)}`,
78
- }))).toBeNull();
79
-
80
- expect(projectEventFrame(frame('extension.app', { appId: 'gone', removed: true }))?.payload).toMatchObject({
81
- appId: 'gone',
82
- removed: true,
83
- });
84
- });
85
-
86
43
  it('projects bounded editor/title/catalog and tree invalidation events', () => {
87
44
  expect(projectEventFrame(frame('extension.editor', { text: 'draft' }))).toMatchObject({
88
45
  name: 'extension.editor', payload: { text: 'draft', mode: 'set' },
@@ -211,15 +168,13 @@ describe('extension public projections', () => {
211
168
  expect(projectEventFrame(frame('extension.editor.track', {}))).toBeNull();
212
169
  });
213
170
 
214
- it('projects snapshot extensionPanels/extensionApps/extensionDraftTracked for reconnect', () => {
171
+ it('projects snapshot dialogs, title, working and extensionDraftTracked for reconnect', () => {
215
172
  const projected = projectEventFrame(frame('session.snapshot', {
216
173
  isStreaming: false,
217
174
  lifecycle: 'idle',
218
175
  queue: { steering: 0, followUp: 0 },
219
176
  lastSequence: 5,
220
177
  extensionStatuses: [{ key: 'mode', text: 'economy' }],
221
- extensionPanels: [{ id: 'panel-1', component: 'progress', props: { value: 50 } }],
222
- extensionApps: [{ appId: 'app-1', html: '<p>x</p>' }],
223
178
  extensionTitle: 'Build mode',
224
179
  extensionWorking: { message: 'Indexing...', visible: true },
225
180
  extensionDraftTracked: true,
@@ -231,8 +186,6 @@ describe('extension public projections', () => {
231
186
  }],
232
187
  }));
233
188
  const snapshot = projected?.payload.snapshot;
234
- expect(snapshot.extensionPanels).toHaveLength(1);
235
- expect(snapshot.extensionApps).toHaveLength(1);
236
189
  expect(snapshot.extensionDialogs[0].fields).toHaveLength(1);
237
190
  expect(snapshot.extensionTitle).toBe('Build mode');
238
191
  expect(snapshot.extensionWorking).toEqual({ message: 'Indexing...', visible: true });
@@ -759,4 +712,38 @@ describe('composer controls', () => {
759
712
  expect(unavailable.status).toBe(409);
760
713
  await expect(unavailable.json()).resolves.toEqual({ error: { code: 'CONTROL_UNAVAILABLE' } });
761
714
  });
715
+
716
+ it('forwards a card action\'s command by the shared rule', async () => {
717
+ const calls = [];
718
+ let answer = { ran: true };
719
+ const runtime = {
720
+ request: async (command, payload) => {
721
+ calls.push({ command, payload });
722
+ if (answer instanceof Error) throw answer;
723
+ return answer;
724
+ },
725
+ };
726
+ const app = express();
727
+ app.use(express.json());
728
+ registerPiRuntimeRoutes(app, { getPiSessionDaemonRuntime: () => runtime });
729
+ server = await listen(app);
730
+ const url = `http://127.0.0.1:${server.address().port}/api/pi/extensions/command`;
731
+ const post = (body) => fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) });
732
+
733
+ const ok = await post({ sessionId: 's1', command: '/explore-focus', args: 'src', clientId: 'tab-1', extra: 'x' });
734
+ expect(ok.status).toBe(200);
735
+ await expect(ok.json()).resolves.toEqual({ ran: true });
736
+ expect(calls).toEqual([{ command: 'extensions.command', payload: { sessionId: 's1', command: '/explore-focus', args: 'src', clientId: 'tab-1' } }]);
737
+
738
+ for (const bad of [{}, { sessionId: 's1' }, { sessionId: 's1', command: 'a/b' }, { sessionId: 's1', command: '..etc' }, { sessionId: 's1', command: 'run now' }, { sessionId: 's1', command: 'x'.repeat(129) }, { sessionId: 's1', command: 'ok', args: 3 }]) {
739
+ const res = await post(bad);
740
+ expect(res.status).toBe(400);
741
+ }
742
+ expect(calls).toHaveLength(1);
743
+
744
+ answer = Object.assign(new Error('gone'), { code: 'COMMAND_UNAVAILABLE' });
745
+ const unavailable = await post({ sessionId: 's1', command: 'ghost' });
746
+ expect(unavailable.status).toBe(409);
747
+ await expect(unavailable.json()).resolves.toEqual({ error: { code: 'COMMAND_UNAVAILABLE' } });
748
+ });
762
749
  });
@@ -19,7 +19,6 @@ import { isPiThinkingLevel } from './thinking-levels.js';
19
19
  import { createPiSessionFoldersStore } from './session-folders-store.js';
20
20
  import { createPiSessionShelfStore } from './session-shelf-store.js';
21
21
  import {
22
- MAX_EXTENSION_APP_HTML_CHARS,
23
22
  isValidCustomInputItems,
24
23
  projectCustomDismiss,
25
24
  projectCustomFrame,
@@ -39,6 +38,7 @@ import { createPiDaemonPool, MAIN_DAEMON_KEY, publicDaemonStreamId } from './ses
39
38
  import { decodePiEventCursor, subscribeMergedPiEvents } from './merged-event-stream.js';
40
39
  import { registerPiSandboxRoutes } from './sandbox/sandbox-routes.js';
41
40
  import { MAX_CONTROLS_PER_SESSION, parseComposerControl } from './session-daemon/extension-controls.js';
41
+ import { EXTENSION_COMMAND_NAME_PATTERN, parseExtensionCommandName } from './extension-commands.js';
42
42
  import {
43
43
  DEFAULT_EVENT_STREAM_MAX_BUFFERED_BYTES,
44
44
  createPiEventStreamRegistry,
@@ -92,7 +92,7 @@ const writeDaemonError = (res, error) => {
92
92
  : code === 'INVALID_SESSION'
93
93
  ? 404
94
94
  : code === 'SESSION_IN_USE' || code === 'OPERATION_PAYLOAD_MISMATCH' || code === 'STALE_STREAM_EPOCH'
95
- || code === ENGINE_UNSUPPORTED_OPERATION || code === 'CONTROL_UNAVAILABLE'
95
+ || code === ENGINE_UNSUPPORTED_OPERATION || code === 'CONTROL_UNAVAILABLE' || code === 'COMMAND_UNAVAILABLE'
96
96
  || code === 'PACKAGE_ALREADY_INSTALLED' || code === 'PACKAGE_PINNED'
97
97
  ? 409
98
98
  : code === 'OPERATION_EXPIRED'
@@ -148,6 +148,7 @@ const projectSession = (value) => {
148
148
  ...(Number.isSafeInteger(value.messageCount) && value.messageCount >= 0 ? { messageCount: value.messageCount } : {}),
149
149
  ...(value.model && typeof value.model.providerId === 'string' && typeof value.model.modelId === 'string' ? { model: { providerId: value.model.providerId, modelId: value.model.modelId } } : {}),
150
150
  ...(typeof value.thinking === 'string' ? { thinking: value.thinking } : {}),
151
+ ...(Number.isSafeInteger(value.extensionModelSequence) ? { extensionModelSequence: value.extensionModelSequence } : {}),
151
152
  ...(value.archived === true ? { archived: true } : {}),
152
153
  ...(Number.isFinite(value.timeArchived) ? { timeArchived: value.timeArchived } : {}),
153
154
  };
@@ -676,28 +677,6 @@ const projectSessionTree = (value) => {
676
677
 
677
678
  const sessionIdFrom = (req) => typeof req.params.sessionId === 'string' && req.params.sessionId.length > 0 ? req.params.sessionId : undefined;
678
679
 
679
-
680
- const projectExtensionPanelActions = (actions) => (
681
- Array.isArray(actions)
682
- ? actions.filter((action) => action && typeof action === 'object' && typeof action.command === 'string').slice(0, 8)
683
- : undefined
684
- );
685
-
686
- const projectExtensionPanelPayload = (panel) => ({
687
- id: panel.id.slice(0, 128),
688
- ...(typeof panel.title === 'string' ? { title: panel.title.slice(0, 256) } : {}),
689
- ...(typeof panel.component === 'string' ? { component: panel.component.slice(0, 64) } : {}),
690
- ...(panel.props && typeof panel.props === 'object' && !Array.isArray(panel.props) ? { props: panel.props } : {}),
691
- ...(projectExtensionPanelActions(panel.actions) ? { actions: panel.actions } : {}),
692
- });
693
-
694
- const projectExtensionAppPayload = (app) => ({
695
- appId: app.appId.slice(0, 128),
696
- ...(typeof app.title === 'string' ? { title: app.title.slice(0, 256) } : {}),
697
- html: typeof app.html === 'string' ? app.html.slice(0, MAX_EXTENSION_APP_HTML_CHARS) : '',
698
- });
699
-
700
- const EXTENSION_COMMAND_PATTERN = /^[A-Za-z0-9][A-Za-z0-9:_-]{0,127}$/;
701
680
  const OPAQUE_EXTENSION_ID_PATTERN = /^[a-f0-9]{16}$/;
702
681
 
703
682
  const HEX_COLOR_PATTERN = /^#[0-9a-f]{6}$/i;
@@ -746,7 +725,7 @@ export const projectExtensionList = (result) => {
746
725
  });
747
726
  const commands = result.commands.map((command) => {
748
727
  if (!command || typeof command !== 'object'
749
- || typeof command.name !== 'string' || !EXTENSION_COMMAND_PATTERN.test(command.name)
728
+ || typeof command.name !== 'string' || !EXTENSION_COMMAND_NAME_PATTERN.test(command.name)
750
729
  || (command.description !== undefined && typeof command.description !== 'string')
751
730
  || (command.scope !== undefined && typeof command.scope !== 'string')) throw protocolMismatch();
752
731
  return {
@@ -931,12 +910,6 @@ function projectExtensionSnapshotState(snapshot) {
931
910
  }))
932
911
  : undefined;
933
912
 
934
- const extensionPanels = Array.isArray(snapshot.extensionPanels)
935
- ? snapshot.extensionPanels.filter((entry) => entry && typeof entry.id === 'string' && entry.id.length > 0).slice(0, 24).map(projectExtensionPanelPayload)
936
- : undefined;
937
- const extensionApps = Array.isArray(snapshot.extensionApps)
938
- ? snapshot.extensionApps.filter((entry) => entry && typeof entry.appId === 'string' && entry.appId.length > 0 && typeof entry.html === 'string' && entry.html.length > 0).slice(0, 8).map(projectExtensionAppPayload)
939
- : undefined;
940
913
  const extensionWorking = snapshot.extensionWorking && typeof snapshot.extensionWorking === 'object'
941
914
  ? {
942
915
  ...(typeof snapshot.extensionWorking.message === 'string'
@@ -950,8 +923,6 @@ function projectExtensionSnapshotState(snapshot) {
950
923
  ...(extensionControls ? { extensionControls } : {}),
951
924
  ...(extensionWidgets ? { extensionWidgets } : {}),
952
925
  ...(extensionDialogs ? { extensionDialogs } : {}),
953
- ...(extensionPanels ? { extensionPanels } : {}),
954
- ...(extensionApps ? { extensionApps } : {}),
955
926
  ...(typeof snapshot.extensionTitle === 'string' && snapshot.extensionTitle.length > 0
956
927
  ? { extensionTitle: snapshot.extensionTitle.replace(/[\u0000-\u001f\u007f]/g, ' ').trim().slice(0, 256) }
957
928
  : {}),
@@ -1006,6 +977,7 @@ export const projectEventFrame = (frame) => {
1006
977
  queue: { steering: Number.isSafeInteger(snapshot.queue?.steering) ? snapshot.queue.steering : 0, followUp: Number.isSafeInteger(snapshot.queue?.followUp) ? snapshot.queue.followUp : 0 },
1007
978
  ...(snapshot.model && typeof snapshot.model.providerId === 'string' && typeof snapshot.model.modelId === 'string' ? { model: { providerId: snapshot.model.providerId, modelId: snapshot.model.modelId } } : {}),
1008
979
  ...(typeof snapshot.thinking === 'string' ? { thinking: snapshot.thinking } : {}),
980
+ ...(Number.isSafeInteger(snapshot.extensionModelSequence) ? { extensionModelSequence: snapshot.extensionModelSequence } : {}),
1009
981
  ...(typeof snapshot.lastText === 'string' ? { lastText: snapshot.lastText } : {}),
1010
982
  ...(typeof snapshot.lastThinking === 'string' ? { lastThinking: snapshot.lastThinking } : {}),
1011
983
  ...(Number.isFinite(snapshot.runStartedAt) ? { runStartedAt: Math.floor(snapshot.runStartedAt) } : {}),
@@ -1106,7 +1078,13 @@ export const projectEventFrame = (frame) => {
1106
1078
  },
1107
1079
  };
1108
1080
  case 'session.queue': return { ...common, payload: { steering: frame.payload.steering, followUp: frame.payload.followUp } };
1109
- case 'session.model': return { ...common, payload: { model: frame.payload.model } };
1081
+ case 'session.model': return {
1082
+ ...common,
1083
+ payload: {
1084
+ model: frame.payload.model,
1085
+ ...(frame.payload.source === 'extension' ? { source: 'extension' } : {}),
1086
+ },
1087
+ };
1110
1088
  case 'session.thinking': return { ...common, payload: { thinking: frame.payload.thinking } };
1111
1089
  case 'session.compaction': {
1112
1090
  const compaction = projectCompactionInfo(frame.payload);
@@ -1262,26 +1240,6 @@ export const projectEventFrame = (frame) => {
1262
1240
  },
1263
1241
  };
1264
1242
  }
1265
- case 'extension.ui': {
1266
- if (typeof frame.payload.id !== 'string' || frame.payload.id.length === 0 || frame.payload.id.length > 128) return null;
1267
- const hasBody = typeof frame.payload.component === 'string'
1268
- || typeof frame.payload.title === 'string'
1269
- || Array.isArray(frame.payload.actions);
1270
- const removed = frame.payload.removed === true || !hasBody;
1271
- return {
1272
- ...common,
1273
- payload: removed
1274
- ? { id: frame.payload.id.slice(0, 128), removed: true }
1275
- : projectExtensionPanelPayload(frame.payload),
1276
- };
1277
- }
1278
- case 'extension.app': {
1279
- if (typeof frame.payload.appId !== 'string' || frame.payload.appId.length === 0 || frame.payload.appId.length > 128) return null;
1280
- const html = typeof frame.payload.html === 'string' ? frame.payload.html : '';
1281
- if (html.length === 0) return { ...common, payload: { appId: frame.payload.appId.slice(0, 128), removed: true } };
1282
- if (html.length > MAX_EXTENSION_APP_HTML_CHARS) return null;
1283
- return { ...common, payload: projectExtensionAppPayload({ ...frame.payload, html }) };
1284
- }
1285
1243
  case 'extension.working': {
1286
1244
  if (frame.payload.message !== undefined && typeof frame.payload.message !== 'string') return null;
1287
1245
  if (frame.payload.visible !== undefined && typeof frame.payload.visible !== 'boolean') return null;
@@ -2905,6 +2863,38 @@ export const registerPiRuntimeRoutes = (app, {
2905
2863
  }
2906
2864
  });
2907
2865
 
2866
+ // A click on a card action: the extension's own command,
2867
+ // which the daemon runs only when the session's extensions register it
2868
+ // (`COMMAND_UNAVAILABLE`, 409, otherwise). Same name rule as composer
2869
+ // controls (extension-commands.js).
2870
+ app.post('/api/pi/extensions/command', async (req, res) => {
2871
+ const body = req.body;
2872
+ if (!body || typeof body !== 'object' || Array.isArray(body)
2873
+ || typeof body.sessionId !== 'string' || body.sessionId.length === 0 || body.sessionId.length > 256
2874
+ || !parseExtensionCommandName(body.command)
2875
+ || (body.args !== undefined && (typeof body.args !== 'string' || body.args.length > 4096))
2876
+ || (body.clientId !== undefined && (typeof body.clientId !== 'string' || body.clientId.length > 128))
2877
+ || (body.directory !== undefined && (typeof body.directory !== 'string' || body.directory.length > 4096))) {
2878
+ res.status(400).json({ error: { code: 'INVALID_ARGUMENT' } });
2879
+ return;
2880
+ }
2881
+ try {
2882
+ drainingSessionRuntime(res, sandboxManager, body.sessionId, 'extensions.command');
2883
+ const directory = typeof body.directory === 'string' && body.directory.length > 0 ? body.directory : undefined;
2884
+ const routeDirectory = await sessionDaemonDirectory(res, sandboxManager, body.sessionId, directory);
2885
+ const result = await daemonFor(routeDirectory).request('extensions.command', {
2886
+ sessionId: body.sessionId,
2887
+ command: body.command,
2888
+ ...(typeof body.args === 'string' ? { args: body.args } : {}),
2889
+ ...(directory ? { directory } : {}),
2890
+ ...(typeof body.clientId === 'string' && body.clientId.length > 0 ? { clientId: body.clientId } : {}),
2891
+ });
2892
+ res.json({ ran: result?.ran === true });
2893
+ } catch (error) {
2894
+ writeDaemonError(res, error);
2895
+ }
2896
+ });
2897
+
2908
2898
  // `ctx.ui.custom()` surfaces: keys, the sender's viewport, Close, picking a
2909
2899
  // panel in a tab stack, and a full-frame refresh after a missed patch. A surface that already closed
2910
2900
  // answers 404 so the browser drops it without retrying.
@@ -53,6 +53,38 @@ describe('Pi runtime route', () => {
53
53
  expect(projectEventFrame(frame({ archived: 'yes' }))).toBeNull();
54
54
  });
55
55
 
56
+ it('keeps only the extension source on a session model event', () => {
57
+ const model = (payload) => projectEventFrame({
58
+ protocolVersion: 1,
59
+ kind: 'event',
60
+ event: 'session.model',
61
+ sequence: 3,
62
+ payload: { sessionId: 'pi-session-mode', directory: '/workspace', model: { providerId: 'p', modelId: 'm' }, ...payload },
63
+ })?.payload;
64
+ expect(model({ source: 'extension' })).toEqual({ model: { providerId: 'p', modelId: 'm' }, source: 'extension' });
65
+ expect(model({ source: 'other' })).toEqual({ model: { providerId: 'p', modelId: 'm' } });
66
+ expect(model({})).toEqual({ model: { providerId: 'p', modelId: 'm' } });
67
+ });
68
+
69
+ it('keeps the last extension model choice on a session snapshot', () => {
70
+ const snapshot = (extensionModelSequence) => projectEventFrame({
71
+ protocolVersion: 1,
72
+ kind: 'event',
73
+ event: 'session.snapshot',
74
+ sequence: 8,
75
+ payload: {
76
+ sessionId: 'pi-session-mode',
77
+ directory: '/workspace',
78
+ isStreaming: false,
79
+ lifecycle: 'idle',
80
+ lastSequence: 8,
81
+ extensionModelSequence,
82
+ },
83
+ })?.payload.snapshot;
84
+ expect(snapshot(5)).toMatchObject({ extensionModelSequence: 5 });
85
+ expect(snapshot('5')).not.toHaveProperty('extensionModelSequence');
86
+ });
87
+
56
88
  it('projects prompt-time files on a live user message start', () => {
57
89
  expect(projectEventFrame({
58
90
  protocolVersion: 1,