@blackbelt-technology/pi-dashboard-extension 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/.pi/skills/pi-dashboard/SKILL.md +134 -0
  2. package/.pi/skills/pi-dashboard/references/api-reference.md +470 -0
  3. package/.pi/skills/pi-dashboard/references/recipes.md +252 -0
  4. package/.pi/skills/pi-dashboard/scripts/dashboard-api.sh +75 -0
  5. package/package.json +38 -0
  6. package/src/__tests__/ask-user-tool.test.ts +432 -0
  7. package/src/__tests__/command-handler.test.ts +712 -0
  8. package/src/__tests__/connection.test.ts +344 -0
  9. package/src/__tests__/credentials-updated.test.ts +26 -0
  10. package/src/__tests__/dashboard-default-adapter.test.ts +77 -0
  11. package/src/__tests__/dev-build.test.ts +79 -0
  12. package/src/__tests__/enrich-model-metadata.test.ts +201 -0
  13. package/src/__tests__/event-forwarder.test.ts +89 -0
  14. package/src/__tests__/fork-entryid-timing.test.ts +100 -0
  15. package/src/__tests__/git-info.test.ts +124 -0
  16. package/src/__tests__/git-link-builder.test.ts +102 -0
  17. package/src/__tests__/openspec-activity-detector.test.ts +232 -0
  18. package/src/__tests__/openspec-poller.test.ts +124 -0
  19. package/src/__tests__/process-metrics.test.ts +47 -0
  20. package/src/__tests__/process-scanner-kill.test.ts +61 -0
  21. package/src/__tests__/process-scanner.test.ts +202 -0
  22. package/src/__tests__/prompt-bus-wiring.test.ts +791 -0
  23. package/src/__tests__/prompt-bus.test.ts +469 -0
  24. package/src/__tests__/prompt-expander.test.ts +54 -0
  25. package/src/__tests__/provider-register-reload.test.ts +394 -0
  26. package/src/__tests__/server-auto-start.test.ts +258 -0
  27. package/src/__tests__/server-launcher.test.ts +61 -0
  28. package/src/__tests__/server-probe.test.ts +25 -0
  29. package/src/__tests__/session-switch.test.ts +139 -0
  30. package/src/__tests__/session-sync.test.ts +55 -0
  31. package/src/__tests__/source-detector.test.ts +73 -0
  32. package/src/__tests__/stats-extractor.test.ts +92 -0
  33. package/src/__tests__/tui-prompt-adapter.test.ts +207 -0
  34. package/src/__tests__/watchdog.test.ts +161 -0
  35. package/src/ask-user-tool.ts +352 -0
  36. package/src/bridge-context.ts +64 -0
  37. package/src/bridge.ts +1182 -0
  38. package/src/command-handler.ts +533 -0
  39. package/src/connection.ts +204 -0
  40. package/src/dashboard-default-adapter.ts +37 -0
  41. package/src/dev-build.ts +39 -0
  42. package/src/event-forwarder.ts +40 -0
  43. package/src/flow-event-wiring.ts +85 -0
  44. package/src/git-info.ts +55 -0
  45. package/src/git-link-builder.ts +112 -0
  46. package/src/model-tracker.ts +56 -0
  47. package/src/pi-env.d.ts +37 -0
  48. package/src/process-metrics.ts +70 -0
  49. package/src/process-scanner.ts +430 -0
  50. package/src/prompt-bus.ts +240 -0
  51. package/src/prompt-expander.ts +108 -0
  52. package/src/provider-register.ts +564 -0
  53. package/src/server-auto-start.ts +113 -0
  54. package/src/server-launcher.ts +126 -0
  55. package/src/server-probe.ts +33 -0
  56. package/src/session-sync.ts +155 -0
  57. package/src/source-detector.ts +26 -0
@@ -0,0 +1,161 @@
1
+ import { describe, it, expect, vi, beforeEach } from "vitest";
2
+ import { ConnectionManager } from "../connection.js";
3
+
4
+ // Mock WebSocket (same pattern as connection.test.ts)
5
+ class MockWebSocket {
6
+ static instances: MockWebSocket[] = [];
7
+ readyState = 0;
8
+ onopen: (() => void) | null = null;
9
+ onclose: (() => void) | null = null;
10
+ onmessage: ((ev: { data: string }) => void) | null = null;
11
+ onerror: ((ev: unknown) => void) | null = null;
12
+ sentMessages: string[] = [];
13
+
14
+ constructor(public url: string) {
15
+ MockWebSocket.instances.push(this);
16
+ }
17
+
18
+ send(data: string) {
19
+ this.sentMessages.push(data);
20
+ }
21
+
22
+ close() {
23
+ this.readyState = 3;
24
+ this.onclose?.();
25
+ }
26
+
27
+ simulateOpen() {
28
+ this.readyState = 1;
29
+ this.onopen?.();
30
+ }
31
+
32
+ simulateClose() {
33
+ this.readyState = 3;
34
+ this.onclose?.();
35
+ }
36
+
37
+ simulateMessage(data: string) {
38
+ this.onmessage?.({ data });
39
+ }
40
+ }
41
+
42
+ describe("ConnectionManager watchdog", () => {
43
+ beforeEach(() => {
44
+ MockWebSocket.instances = [];
45
+ vi.useFakeTimers();
46
+ });
47
+
48
+ it("should force-close when no messages received for watchdogTimeout", () => {
49
+ const cm = new ConnectionManager({
50
+ url: "ws://localhost:9999",
51
+ WebSocketImpl: MockWebSocket as any,
52
+ watchdogTimeout: 60_000,
53
+ });
54
+ cm.connect();
55
+
56
+ const ws = MockWebSocket.instances[0];
57
+ ws.simulateOpen();
58
+
59
+ // Advance past watchdog timeout (checked every 15s)
60
+ vi.advanceTimersByTime(60_000);
61
+
62
+ // Watchdog should have triggered — ws should be closed and reconnect scheduled
63
+ expect(MockWebSocket.instances.length).toBeGreaterThanOrEqual(1);
64
+ // The connection should have been torn down
65
+ expect(cm.isConnected).toBe(false);
66
+
67
+ cm.disconnect();
68
+ });
69
+
70
+ it("should NOT force-close when messages are received regularly", () => {
71
+ const cm = new ConnectionManager({
72
+ url: "ws://localhost:9999",
73
+ WebSocketImpl: MockWebSocket as any,
74
+ watchdogTimeout: 60_000,
75
+ });
76
+ cm.connect();
77
+
78
+ const ws = MockWebSocket.instances[0];
79
+ ws.simulateOpen();
80
+
81
+ // Send messages every 20s to keep watchdog happy
82
+ for (let i = 0; i < 5; i++) {
83
+ vi.advanceTimersByTime(20_000);
84
+ ws.simulateMessage(JSON.stringify({ type: "heartbeat_ack" }));
85
+ }
86
+
87
+ // Should still be connected (100s elapsed, but messages kept coming)
88
+ expect(cm.isConnected).toBe(true);
89
+ expect(MockWebSocket.instances).toHaveLength(1);
90
+
91
+ cm.disconnect();
92
+ });
93
+
94
+ it("should stop watchdog on disconnect", () => {
95
+ const cm = new ConnectionManager({
96
+ url: "ws://localhost:9999",
97
+ WebSocketImpl: MockWebSocket as any,
98
+ watchdogTimeout: 60_000,
99
+ });
100
+ cm.connect();
101
+
102
+ const ws = MockWebSocket.instances[0];
103
+ ws.simulateOpen();
104
+
105
+ // Disconnect before watchdog fires
106
+ cm.disconnect();
107
+
108
+ // Advance past timeout — should not create new connections
109
+ vi.advanceTimersByTime(120_000);
110
+ expect(MockWebSocket.instances).toHaveLength(1);
111
+ });
112
+
113
+ it("should be disabled when watchdogTimeout is 0", () => {
114
+ const cm = new ConnectionManager({
115
+ url: "ws://localhost:9999",
116
+ WebSocketImpl: MockWebSocket as any,
117
+ watchdogTimeout: 0,
118
+ });
119
+ cm.connect();
120
+
121
+ const ws = MockWebSocket.instances[0];
122
+ ws.simulateOpen();
123
+
124
+ // Advance way past any timeout — should stay connected
125
+ vi.advanceTimersByTime(300_000);
126
+ expect(cm.isConnected).toBe(true);
127
+ expect(MockWebSocket.instances).toHaveLength(1);
128
+
129
+ cm.disconnect();
130
+ });
131
+
132
+ it("should reconnect after watchdog triggers", () => {
133
+ const onReconnect = vi.fn();
134
+ const cm = new ConnectionManager({
135
+ url: "ws://localhost:9999",
136
+ WebSocketImpl: MockWebSocket as any,
137
+ watchdogTimeout: 60_000,
138
+ onReconnect,
139
+ });
140
+ cm.connect();
141
+
142
+ const ws1 = MockWebSocket.instances[0];
143
+ ws1.simulateOpen();
144
+
145
+ // Let watchdog trigger
146
+ vi.advanceTimersByTime(60_000);
147
+ expect(cm.isConnected).toBe(false);
148
+
149
+ // Reconnect timer fires (1s backoff)
150
+ vi.advanceTimersByTime(1000);
151
+ expect(MockWebSocket.instances.length).toBeGreaterThanOrEqual(2);
152
+
153
+ // Simulate successful reconnect
154
+ const ws2 = MockWebSocket.instances[MockWebSocket.instances.length - 1];
155
+ ws2.simulateOpen();
156
+ expect(cm.isConnected).toBe(true);
157
+ expect(onReconnect).toHaveBeenCalled();
158
+
159
+ cm.disconnect();
160
+ });
161
+ });
@@ -0,0 +1,352 @@
1
+ /**
2
+ * Registers the ask_user tool in the bridge extension.
3
+ *
4
+ * Called at runtime (session_start) rather than extension load time to avoid
5
+ * static tool-name conflicts with other extensions (e.g. pi-flows) that also
6
+ * register ask_user. Runtime registration bypasses detectExtensionConflicts.
7
+ */
8
+ import type { ExtensionAPI } from "@mariozechner/pi-coding-agent";
9
+ import { Type } from "@sinclair/typebox";
10
+
11
+ // ──────────────────────────────────────────────────────────────────────────
12
+ // Single-question schema arms (reused inside the batch arm's questions array)
13
+ // ──────────────────────────────────────────────────────────────────────────
14
+
15
+ const ConfirmSchema = Type.Object({
16
+ method: Type.Literal("confirm", { description: "Yes/no question" }),
17
+ title: Type.String({ description: "The question to confirm" }),
18
+ message: Type.Optional(Type.String({ description: "Additional context or detailed question body" })),
19
+ });
20
+
21
+ const SelectSchema = Type.Object({
22
+ method: Type.Literal("select", { description: "Pick one option from a list" }),
23
+ title: Type.String({ description: "Short title for the question" }),
24
+ options: Type.Array(Type.String(), {
25
+ minItems: 2,
26
+ description: "Options the user chooses between (at least 2; use 'confirm' for yes/no)",
27
+ }),
28
+ message: Type.Optional(Type.String({ description: "Additional context" })),
29
+ });
30
+
31
+ const MultiselectSchema = Type.Object({
32
+ method: Type.Literal("multiselect", { description: "Pick multiple options from a list" }),
33
+ title: Type.String({ description: "Short title for the question" }),
34
+ options: Type.Array(Type.String(), {
35
+ minItems: 1,
36
+ description: "Options the user can multi-select",
37
+ }),
38
+ message: Type.Optional(Type.String({ description: "Additional context" })),
39
+ });
40
+
41
+ const InputSchema = Type.Object({
42
+ method: Type.Literal("input", { description: "Free-text input" }),
43
+ title: Type.String({ description: "Short title for the question" }),
44
+ placeholder: Type.Optional(Type.String({ description: "Placeholder text for the input field" })),
45
+ message: Type.Optional(Type.String({ description: "Additional context" })),
46
+ });
47
+
48
+ // Sub-question union deliberately omits the batch arm (no nesting).
49
+ const SubQuestionSchema = Type.Union([ConfirmSchema, SelectSchema, MultiselectSchema, InputSchema], {
50
+ description: "A single question inside a batch. Must not itself be a batch.",
51
+ });
52
+
53
+ const BatchSchema = Type.Object({
54
+ method: Type.Literal("batch", {
55
+ description: "Ask multiple related questions in one call; answers are returned as an ordered array.",
56
+ }),
57
+ title: Type.String({ description: "Header shown above the sequence of dialogs" }),
58
+ questions: Type.Array(SubQuestionSchema, {
59
+ minItems: 1,
60
+ description: "One or more sub-questions (confirm/select/multiselect/input). Cannot nest batch.",
61
+ }),
62
+ message: Type.Optional(Type.String({ description: "Additional context for the whole batch" })),
63
+ });
64
+
65
+ // ──────────────────────────────────────────────────────────────────────────
66
+ // Argument rescue helpers
67
+ // ──────────────────────────────────────────────────────────────────────────
68
+
69
+ type NormalizationWarning = string;
70
+
71
+ function normalizeSubQuestion(
72
+ sq: unknown,
73
+ warnings: NormalizationWarning[],
74
+ ): Record<string, unknown> {
75
+ if (!sq || typeof sq !== "object" || Array.isArray(sq)) return sq as any;
76
+ let obj = { ...(sq as Record<string, unknown>) };
77
+
78
+ // Flatten `input_type: {method, options, ...}` wrapper if present.
79
+ if (obj.input_type && typeof obj.input_type === "object" && !Array.isArray(obj.input_type)) {
80
+ const inner = obj.input_type as Record<string, unknown>;
81
+ const { input_type: _drop, ...rest } = obj;
82
+ obj = { ...inner, ...rest };
83
+ delete (obj as Record<string, unknown>).input_type;
84
+ }
85
+
86
+ // Rename `question` / `header` → `title` (only if title missing).
87
+ if (obj.title === undefined) {
88
+ if (typeof obj.question === "string") obj.title = obj.question;
89
+ else if (typeof obj.header === "string") obj.title = obj.header;
90
+ }
91
+
92
+ // Parse stringified options.
93
+ if (typeof obj.options === "string") {
94
+ try {
95
+ const parsed = JSON.parse(obj.options);
96
+ if (Array.isArray(parsed)) obj.options = parsed;
97
+ } catch {
98
+ /* leave as-is */
99
+ }
100
+ }
101
+
102
+ // Convert options: [{label, value}] → [label, ...] with a warning.
103
+ if (Array.isArray(obj.options) && obj.options.length > 0 && obj.options.every(
104
+ (o) => o && typeof o === "object" && !Array.isArray(o) && typeof (o as any).label === "string",
105
+ )) {
106
+ obj.options = (obj.options as Array<Record<string, unknown>>).map((o) => o.label as string);
107
+ warnings.push(
108
+ "ask_user: options with {label, value} pairs are not supported — only labels were used. Send options as string[].",
109
+ );
110
+ }
111
+
112
+ return obj;
113
+ }
114
+
115
+ // ──────────────────────────────────────────────────────────────────────────
116
+ // Tool registration
117
+ // ──────────────────────────────────────────────────────────────────────────
118
+
119
+ export function registerAskUserTool(pi: ExtensionAPI): void {
120
+ pi.registerTool({
121
+ name: "ask_user",
122
+ label: "Ask User",
123
+ description:
124
+ "Ask the user a question interactively. Use this when you need clarification, confirmation, or a choice from the user before proceeding.",
125
+ promptSnippet:
126
+ "Ask the user interactive questions (confirm, select, multiselect, input, or batch — multiple related questions at once)",
127
+ promptGuidelines: [
128
+ "When you need to ask the user a question, ALWAYS use the ask_user tool instead of writing the question as plain text.",
129
+ "Use method 'confirm' for yes/no questions, 'select' when offering specific choices, 'multiselect' when the user should pick multiple items from a list, and 'input' for open-ended questions.",
130
+ "Use method 'batch' with a `questions` array to ask multiple related questions in one call (e.g. project setup: name + language + init git). Prefer single-method calls for standalone questions.",
131
+ "Do not nest batches. Send `options` as a plain string[] — not [{label, value}].",
132
+ "This applies to all workflows including OpenSpec, planning, and any situation where you need user input before proceeding.",
133
+ ],
134
+ parameters: Type.Union(
135
+ [ConfirmSchema, SelectSchema, MultiselectSchema, InputSchema, BatchSchema],
136
+ { description: "Parameters for ask_user, discriminated by method." },
137
+ ),
138
+ prepareArguments(args: unknown) {
139
+ let obj = (args && typeof args === "object" ? { ...(args as Record<string, unknown>) } : {}) as Record<string, unknown>;
140
+
141
+ // 1. LLMs sometimes wrap everything under `params` (stringified or object).
142
+ if (obj.params !== undefined) {
143
+ let inner: Record<string, unknown> | undefined;
144
+ if (typeof obj.params === "string") {
145
+ try {
146
+ const parsed = JSON.parse(obj.params);
147
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
148
+ inner = parsed as Record<string, unknown>;
149
+ }
150
+ } catch { /* leave as-is */ }
151
+ } else if (obj.params && typeof obj.params === "object" && !Array.isArray(obj.params)) {
152
+ inner = obj.params as Record<string, unknown>;
153
+ }
154
+ if (inner) {
155
+ const { params: _omit, ...rest } = obj;
156
+ obj = { ...inner, ...rest };
157
+ delete (obj as Record<string, unknown>).params;
158
+ }
159
+ }
160
+
161
+ // 2. `question` → `title` (only if title missing).
162
+ if (obj.title === undefined && typeof obj.question === "string") {
163
+ obj.title = obj.question;
164
+ }
165
+
166
+ // 3. Stringified top-level `options` for single-method calls.
167
+ if (typeof obj.options === "string") {
168
+ try {
169
+ const parsed = JSON.parse(obj.options);
170
+ if (Array.isArray(parsed)) obj.options = parsed;
171
+ } catch { /* leave as-is */ }
172
+ }
173
+
174
+ // 4. Batch rescue: `questions` as a JSON string → parsed array.
175
+ if (typeof obj.questions === "string") {
176
+ try {
177
+ const parsed = JSON.parse(obj.questions);
178
+ if (Array.isArray(parsed)) obj.questions = parsed;
179
+ } catch { /* leave as-is */ }
180
+ }
181
+
182
+ // 5. If `questions` is a non-empty array and `method` is absent, synthesize `method: "batch"`.
183
+ if (
184
+ !obj.method &&
185
+ Array.isArray(obj.questions) &&
186
+ obj.questions.length > 0
187
+ ) {
188
+ obj.method = "batch";
189
+ }
190
+
191
+ // 6. For any batch call (synthesized or explicit), backfill a missing outer `title`
192
+ // from the first sub-question so the schema validates. Opus frequently sends
193
+ // `{method:"batch", questions:[...]}` without an outer `title`.
194
+ if (
195
+ obj.method === "batch" &&
196
+ Array.isArray(obj.questions) &&
197
+ obj.questions.length > 0 &&
198
+ obj.title === undefined
199
+ ) {
200
+ const first = obj.questions[0] as Record<string, unknown> | undefined;
201
+ const candidate =
202
+ (first && (first.title ?? first.question ?? first.header)) || "Questions";
203
+ obj.title = typeof candidate === "string" ? candidate : "Questions";
204
+ }
205
+
206
+ // 7. For batch calls, normalize each sub-question (input_type, question/header, {label,value}).
207
+ const warnings: NormalizationWarning[] = [];
208
+ if (obj.method === "batch" && Array.isArray(obj.questions)) {
209
+ obj.questions = obj.questions.map((sq) => normalizeSubQuestion(sq, warnings));
210
+ }
211
+
212
+ if (warnings.length > 0) {
213
+ // Non-enumerable so it doesn't interfere with schema validation.
214
+ Object.defineProperty(obj, "__normalizations", {
215
+ value: warnings,
216
+ enumerable: false,
217
+ configurable: true,
218
+ writable: true,
219
+ });
220
+ }
221
+
222
+ return obj as any;
223
+ },
224
+ async execute(_toolCallId: any, params: any, _signal: any, _onUpdate: any, ctx: any) {
225
+ // ── Batch branch ─────────────────────────────────────────────────
226
+ if (params.method === "batch" && Array.isArray(params.questions)) {
227
+ const results: Array<unknown> = [];
228
+ let cancelled = false;
229
+
230
+ for (const sq of params.questions) {
231
+ const subTitle = `${params.title} — ${sq.title ?? "Question"}`;
232
+ const subMsg = params.message ? { message: params.message } : undefined;
233
+
234
+ let answer: unknown;
235
+ try {
236
+ switch (sq.method) {
237
+ case "confirm":
238
+ answer = await ctx.ui.confirm(subTitle, sq.message ?? params.message ?? "");
239
+ break;
240
+ case "select": {
241
+ const opts = Array.isArray(sq.options) ? sq.options : [];
242
+ if (opts.length === 0) {
243
+ throw new Error(
244
+ `ask_user batch: sub-question method "select" requires a non-empty "options" array.`,
245
+ );
246
+ }
247
+ answer = await ctx.ui.select(subTitle, opts, subMsg);
248
+ break;
249
+ }
250
+ case "multiselect": {
251
+ const opts = Array.isArray(sq.options) ? sq.options : [];
252
+ if (opts.length === 0) {
253
+ throw new Error(
254
+ `ask_user batch: sub-question method "multiselect" requires a non-empty "options" array.`,
255
+ );
256
+ }
257
+ answer = await (ctx.ui as any).multiselect(subTitle, opts, subMsg);
258
+ break;
259
+ }
260
+ case "input":
261
+ answer = await ctx.ui.input(subTitle, sq.placeholder, subMsg);
262
+ break;
263
+ default:
264
+ throw new Error(`ask_user batch: unknown sub-question method "${sq.method}"`);
265
+ }
266
+ } catch (err) {
267
+ // Propagate hard errors (schema/logic bugs); cancellation is signalled by undefined.
268
+ throw err;
269
+ }
270
+
271
+ // Treat `undefined` from input/select/multiselect as cancellation.
272
+ // (confirm always resolves to a boolean and has no cancel path.)
273
+ if (
274
+ (sq.method === "input" || sq.method === "select" || sq.method === "multiselect") &&
275
+ answer === undefined
276
+ ) {
277
+ cancelled = true;
278
+ results.push(null);
279
+ break;
280
+ }
281
+
282
+ results.push(answer);
283
+ }
284
+
285
+ const warnings: string[] = (params as any).__normalizations ?? [];
286
+ const lines: string[] = [];
287
+ if (cancelled) {
288
+ lines.push(`User cancelled batch after ${results.filter((r) => r !== null).length} of ${params.questions.length} answers.`);
289
+ } else {
290
+ lines.push(`User completed batch (${results.length} answers).`);
291
+ }
292
+ params.questions.forEach((sq: any, i: number) => {
293
+ const ans = i < results.length ? results[i] : "(not asked)";
294
+ lines.push(` ${i + 1}. ${sq.title ?? sq.method}: ${JSON.stringify(ans)}`);
295
+ });
296
+ if (warnings.length > 0) {
297
+ lines.push("", "Warnings:");
298
+ for (const w of warnings) lines.push(` - ${w}`);
299
+ }
300
+
301
+ return {
302
+ content: [{ type: "text", text: lines.join("\n") }],
303
+ details: {
304
+ method: "batch",
305
+ results,
306
+ cancelled,
307
+ warnings,
308
+ },
309
+ };
310
+ }
311
+
312
+ // ── Single-question branches (unchanged behavior) ────────────────
313
+ let result: unknown;
314
+ const msgOpts = params.message ? { message: params.message } : undefined;
315
+ const title = params.title || params.message || "Question";
316
+
317
+ const options: string[] = Array.isArray(params.options)
318
+ ? params.options
319
+ : typeof params.options === "string"
320
+ ? (() => { try { const p = JSON.parse(params.options); return Array.isArray(p) ? p : []; } catch { return []; } })()
321
+ : [];
322
+
323
+ if ((params.method === "select" || params.method === "multiselect") && options.length === 0) {
324
+ throw new Error(
325
+ `ask_user: method "${params.method}" requires a non-empty "options" array. ` +
326
+ `Received: ${JSON.stringify(params.options)}. ` +
327
+ `If no choices are available, use method "input" instead.`,
328
+ );
329
+ }
330
+
331
+ switch (params.method) {
332
+ case "confirm":
333
+ result = await ctx.ui.confirm(title, params.message ?? "");
334
+ break;
335
+ case "select":
336
+ result = await ctx.ui.select(title, options, msgOpts);
337
+ break;
338
+ case "multiselect":
339
+ result = await (ctx.ui as any).multiselect(title, options, msgOpts);
340
+ break;
341
+ case "input":
342
+ result = await ctx.ui.input(title, params.placeholder, msgOpts);
343
+ break;
344
+ }
345
+
346
+ return {
347
+ content: [{ type: "text", text: `User responded: ${JSON.stringify(result)}` }],
348
+ details: { method: params.method, result },
349
+ };
350
+ },
351
+ });
352
+ }
@@ -0,0 +1,64 @@
1
+ /**
2
+ * Shared mutable state for bridge modules.
3
+ * Avoids passing 14+ closure variables to every extracted function.
4
+ */
5
+ import type { ExtensionAPI } from "@mariozechner/pi-coding-agent";
6
+ import type { ConnectionManager } from "./connection.js";
7
+
8
+ export interface BridgeContext {
9
+ pi: ExtensionAPI;
10
+ connection: ConnectionManager;
11
+ /** Current session ID (mutated on session change: new/fork/resume) */
12
+ sessionId: string;
13
+ cachedCtx: any;
14
+ cachedModelRegistry: any;
15
+ cachedHasUI: boolean | undefined;
16
+ lastModel: string | undefined;
17
+ lastThinkingLevel: string | undefined;
18
+ lastSessionFile: string | undefined;
19
+ lastSessionDir: string | undefined;
20
+ lastFirstMessage: string | undefined;
21
+ lastGitBranch: string | undefined;
22
+ lastGitPrNumber: number | undefined;
23
+ lastSessionName: string | undefined;
24
+ }
25
+
26
+ // Commands that the dashboard handles natively with superior UX.
27
+ // These are filtered from the command list sent to dashboard clients.
28
+ const DASHBOARD_NATIVE_COMMANDS = new Set(["roles"]);
29
+
30
+ /** Filter out hidden commands (names starting with __) and dashboard-native commands from commands list */
31
+ export function filterHiddenCommands(commands: any[]): any[] {
32
+ return commands.filter((cmd) =>
33
+ !cmd.name.startsWith("__") &&
34
+ !DASHBOARD_NATIVE_COMMANDS.has(cmd.name)
35
+ );
36
+ }
37
+
38
+ /** Extract first user message text from session entries */
39
+ export function extractFirstMessage(ctx: any): string | undefined {
40
+ try {
41
+ const entries = ctx?.sessionManager?.getEntries?.();
42
+ if (!entries || !Array.isArray(entries)) return undefined;
43
+ for (const entry of entries) {
44
+ if (entry.role === "user" && typeof entry.content === "string") {
45
+ return entry.content.slice(0, 200);
46
+ }
47
+ if (entry.role === "user" && Array.isArray(entry.content)) {
48
+ for (const part of entry.content) {
49
+ if (part.type === "text" && typeof part.text === "string") {
50
+ return part.text.slice(0, 200);
51
+ }
52
+ }
53
+ }
54
+ }
55
+ } catch { /* ignore */ }
56
+ return undefined;
57
+ }
58
+
59
+ /** Get current model string (provider/id) from cached context */
60
+ export function getCurrentModelString(bc: BridgeContext): string | undefined {
61
+ const model = bc.cachedCtx?.model;
62
+ if (!model) return undefined;
63
+ return `${model.provider}/${model.id}`;
64
+ }