@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,533 @@
1
+ /**
2
+ * Handles server→extension messages by dispatching to pi API.
3
+ */
4
+ import { readdirSync } from "node:fs";
5
+ import { join, relative } from "node:path";
6
+ import type { ExtensionAPI } from "@mariozechner/pi-coding-agent";
7
+ import type {
8
+ ServerToExtensionMessage,
9
+ ExtensionToServerMessage,
10
+ } from "@blackbelt-technology/pi-dashboard-shared/protocol.js";
11
+ import { killProcessByPgid } from "./process-scanner.js";
12
+ import type { FileEntry, PiSessionInfo } from "@blackbelt-technology/pi-dashboard-shared/types.js";
13
+ import { filterHiddenCommands } from "./bridge-context.js";
14
+ import { expandPromptTemplateFromDisk } from "./prompt-expander.js";
15
+
16
+ const IGNORE_DIRS = new Set([".git", "node_modules", ".next", "dist", "build", ".cache", "__pycache__", ".venv"]);
17
+ const MAX_RESULTS = 20;
18
+
19
+ function searchFiles(cwd: string, query: string): FileEntry[] {
20
+ const results: FileEntry[] = [];
21
+ const lowerQuery = query?.toLowerCase() ?? "";
22
+
23
+ function walk(dir: string, depth: number): void {
24
+ if (results.length >= MAX_RESULTS || depth > 6) return;
25
+ let entries;
26
+ try { entries = readdirSync(dir, { withFileTypes: true }); } catch { return; }
27
+ for (const entry of entries) {
28
+ if (results.length >= MAX_RESULTS) return;
29
+ if (IGNORE_DIRS.has(entry.name)) continue;
30
+ const fullPath = join(dir, entry.name);
31
+ const relPath = relative(cwd, fullPath).replace(/\\/g, "/") + (entry.isDirectory() ? "/" : "");
32
+ if (!lowerQuery || relPath.toLowerCase().includes(lowerQuery)) {
33
+ results.push({ path: relPath, isDirectory: entry.isDirectory() });
34
+ }
35
+ if (entry.isDirectory()) walk(fullPath, depth + 1);
36
+ }
37
+ }
38
+
39
+ walk(cwd, 0);
40
+ return results;
41
+ }
42
+
43
+ /** Parsed result from parseSendPrompt */
44
+ export type ParsedPrompt =
45
+ | { type: "bash"; command: string; excludeFromContext: boolean }
46
+ | { type: "compact"; customInstructions: string | undefined }
47
+ | { type: "model"; provider: string; modelId: string }
48
+ | { type: "shutdown" }
49
+ | { type: "reload" }
50
+ | { type: "new" }
51
+ | { type: "mgmt"; event: string; data: Record<string, unknown> }
52
+ | { type: "slash"; text: string }
53
+ | { type: "passthrough"; text: string };
54
+
55
+ /** pi-flows management commands with known event mappings.
56
+ * These are dispatched via pi.events instead of flow:run.
57
+ * Flow management commands (flows:new, flows:edit, flows:delete) are
58
+ * handled in bridge.ts sessionPrompt callback which passes cachedCtx
59
+ * as fallback context for headless sessions. */
60
+ const MANAGEMENT_COMMAND_EVENTS: Record<string, {
61
+ event: string;
62
+ dataFn: (args: string) => Record<string, unknown>;
63
+ }> = {};
64
+
65
+ /** Parse input text to detect pi internal command prefixes */
66
+ export function parseSendPrompt(text: string): ParsedPrompt {
67
+ // 1. Check !! (must check before !)
68
+ if (text.startsWith("!!")) {
69
+ const command = text.slice(2).trim();
70
+ if (!command) return { type: "passthrough", text };
71
+ return { type: "bash", command, excludeFromContext: true };
72
+ }
73
+
74
+ // 2. Check !
75
+ if (text.startsWith("!")) {
76
+ const command = text.slice(1).trim();
77
+ if (!command) return { type: "passthrough", text };
78
+ return { type: "bash", command, excludeFromContext: false };
79
+ }
80
+
81
+ // 3. Check /compact
82
+ if (text === "/compact" || text.startsWith("/compact ")) {
83
+ const args = text.startsWith("/compact ") ? text.slice(9).trim() : undefined;
84
+ return { type: "compact", customInstructions: args || undefined };
85
+ }
86
+
87
+ // 4. Check /quit and /exit
88
+ if (text === "/quit" || text === "/exit") {
89
+ return { type: "shutdown" };
90
+ }
91
+
92
+ // 4b. Check /reload
93
+ if (text === "/reload") {
94
+ return { type: "reload" };
95
+ }
96
+
97
+ // 4c. Check /new
98
+ if (text === "/new") {
99
+ return { type: "new" };
100
+ }
101
+
102
+ // 4d. Check /model <provider/id>
103
+ if (text.startsWith("/model ")) {
104
+ const modelStr = text.slice(7).trim();
105
+ const slashIdx = modelStr.indexOf("/");
106
+ if (slashIdx > 0) {
107
+ return { type: "model", provider: modelStr.slice(0, slashIdx), modelId: modelStr.slice(slashIdx + 1) };
108
+ }
109
+ }
110
+
111
+ // 5. Check management commands (/flows:new, etc.) with known event mappings
112
+ if (text.startsWith("/") && !text.includes("\n")) {
113
+ const cmdText = text.slice(1);
114
+ const spaceIdx = cmdText.indexOf(" ");
115
+ const cmdName = spaceIdx === -1 ? cmdText : cmdText.slice(0, spaceIdx);
116
+ const cmdArgs = spaceIdx === -1 ? "" : cmdText.slice(spaceIdx + 1);
117
+ const mgmt = MANAGEMENT_COMMAND_EVENTS[cmdName];
118
+ if (mgmt) {
119
+ return { type: "mgmt", event: mgmt.event, data: mgmt.dataFn(cmdArgs) };
120
+ }
121
+ }
122
+
123
+ // 6. Check / prefix (generic slash command)
124
+ if (text.startsWith("/") && !text.includes("\n")) {
125
+ return { type: "slash", text };
126
+ }
127
+
128
+ // 5. Passthrough
129
+ return { type: "passthrough", text };
130
+ }
131
+
132
+ const BASH_TIMEOUT = 30_000;
133
+
134
+ export interface CommandHandler {
135
+ handle(msg: ServerToExtensionMessage): ExtensionToServerMessage | undefined | Promise<ExtensionToServerMessage | undefined>;
136
+ }
137
+
138
+ export function createCommandHandler(
139
+ pi: ExtensionAPI,
140
+ sessionIdOrGetter: string | (() => string),
141
+ options?: {
142
+ getModelRegistry?: () => any;
143
+ setThinkingLevel?: (level: string) => void;
144
+ getThinkingLevel?: () => string | undefined;
145
+ shutdown?: () => void;
146
+ abort?: () => void;
147
+ getCwd?: () => string;
148
+ /** Callback to send events (e.g., bash_output, command_feedback) back to server */
149
+ eventSink?: (msg: ExtensionToServerMessage) => void;
150
+ /** Trigger context compaction */
151
+ compact?: (options: { customInstructions?: string }) => void;
152
+ /** Trigger session reload (extensions, settings, skills, etc.) */
153
+ reload?: () => void;
154
+ /** Spawn a new session in the same cwd */
155
+ spawnNew?: () => void;
156
+ /** Switch model via pi.setModel() */
157
+ setModel?: (provider: string, modelId: string) => Promise<void>;
158
+ /** Route slash commands through session.prompt() */
159
+ sessionPrompt?: (text: string) => void;
160
+ },
161
+ ): CommandHandler {
162
+ const getSessionId = typeof sessionIdOrGetter === "function" ? sessionIdOrGetter : () => sessionIdOrGetter;
163
+ return {
164
+ async handle(msg: ServerToExtensionMessage): Promise<ExtensionToServerMessage | undefined> {
165
+ const sessionId = getSessionId();
166
+
167
+ // Ignore messages for other sessions (skip session-less messages like heartbeat_ack)
168
+ if ((msg as any).sessionId !== undefined && (msg as any).sessionId !== sessionId) {
169
+ console.error(`[dashboard] Ignoring message type=${msg.type} for session ${(msg as any).sessionId}, current session is ${sessionId}`);
170
+ return undefined;
171
+ }
172
+
173
+ switch (msg.type) {
174
+ case "send_prompt": {
175
+ const parsed = parseSendPrompt(msg.text);
176
+
177
+ // Route based on parsed command type
178
+ if (parsed.type === "bash") {
179
+ await handleBashCommand(pi, sessionId, parsed.command, parsed.excludeFromContext, options?.eventSink);
180
+ return undefined;
181
+ }
182
+
183
+ if (parsed.type === "compact") {
184
+ await handleCompactCommand(sessionId, parsed.customInstructions, options?.compact, options?.eventSink);
185
+ return undefined;
186
+ }
187
+
188
+ if (parsed.type === "shutdown") {
189
+ if (options?.shutdown) {
190
+ options.shutdown();
191
+ }
192
+ return undefined;
193
+ }
194
+
195
+ if (parsed.type === "reload") {
196
+ if (options?.reload) {
197
+ options.reload();
198
+ }
199
+ options?.eventSink?.({
200
+ type: "event_forward",
201
+ sessionId,
202
+ event: {
203
+ eventType: "command_feedback",
204
+ timestamp: Date.now(),
205
+ data: { command: "/reload", status: "completed" },
206
+ },
207
+ });
208
+ return undefined;
209
+ }
210
+
211
+ if (parsed.type === "new") {
212
+ if (options?.spawnNew) {
213
+ options.spawnNew();
214
+ }
215
+ options?.eventSink?.({
216
+ type: "event_forward",
217
+ sessionId,
218
+ event: {
219
+ eventType: "command_feedback",
220
+ timestamp: Date.now(),
221
+ data: { command: "/new", status: "completed" },
222
+ },
223
+ });
224
+ return undefined;
225
+ }
226
+
227
+ if (parsed.type === "model") {
228
+ if (options?.setModel) {
229
+ await options.setModel(parsed.provider, parsed.modelId);
230
+ }
231
+ options?.eventSink?.({
232
+ type: "event_forward",
233
+ sessionId,
234
+ event: {
235
+ eventType: "command_feedback",
236
+ timestamp: Date.now(),
237
+ data: { command: `/model ${parsed.provider}/${parsed.modelId}`, status: "completed" },
238
+ },
239
+ });
240
+ return undefined;
241
+ }
242
+
243
+ if (parsed.type === "mgmt") {
244
+ // Dispatch management command via pi.events (e.g. flows:new-request)
245
+ if ((pi as any).events) {
246
+ (pi as any).events.emit(parsed.event, parsed.data);
247
+ }
248
+ options?.eventSink?.({
249
+ type: "event_forward",
250
+ sessionId,
251
+ event: {
252
+ eventType: "command_feedback",
253
+ timestamp: Date.now(),
254
+ data: { command: parsed.event, status: "completed" },
255
+ },
256
+ });
257
+ return undefined;
258
+ }
259
+
260
+ if (parsed.type === "slash") {
261
+ if (options?.sessionPrompt) {
262
+ options.sessionPrompt(parsed.text);
263
+ } else {
264
+ pi.sendUserMessage(parsed.text);
265
+ }
266
+ options?.eventSink?.({
267
+ type: "event_forward",
268
+ sessionId,
269
+ event: {
270
+ eventType: "command_feedback",
271
+ timestamp: Date.now(),
272
+ data: { command: parsed.text, status: "completed" },
273
+ },
274
+ });
275
+ return undefined;
276
+ }
277
+
278
+ // Passthrough: send as regular user message (with image handling).
279
+ // Multi-line slash commands (e.g. "/skill:foo\nuser text") are classified as
280
+ // passthrough by parseSendPrompt to preserve images (the slash route strips them),
281
+ // so we expand prompt templates / skills here before sending.
282
+ let outgoing = msg.text;
283
+ if (outgoing.startsWith("/")) {
284
+ outgoing = expandPromptTemplateFromDisk(outgoing, process.cwd(), pi);
285
+ }
286
+ sendUserMessageWithImages(pi, outgoing, msg.images);
287
+ return undefined;
288
+ }
289
+
290
+ case "abort":
291
+ if (options?.abort) {
292
+ options.abort();
293
+ }
294
+ return undefined;
295
+
296
+ case "request_commands": {
297
+ const commands = filterHiddenCommands(pi.getCommands());
298
+ // Also send flows list alongside commands
299
+ if (options?.eventSink) {
300
+ const probe: any = {};
301
+ try { pi.events?.emit("flow:list-flows", probe); } catch { /* ignore */ }
302
+ options.eventSink({ type: "flows_list", sessionId, flows: probe.flows ?? [] });
303
+ }
304
+ return {
305
+ type: "commands_list",
306
+ sessionId,
307
+ commands,
308
+ };
309
+ }
310
+
311
+ case "list_files": {
312
+ const files = searchFiles(process.cwd(), msg.query);
313
+ return {
314
+ type: "files_list",
315
+ sessionId,
316
+ query: msg.query,
317
+ files,
318
+ };
319
+ }
320
+
321
+ // openspec_refresh removed — server handles directly via DirectoryService
322
+
323
+ case "rename_session":
324
+ pi.setSessionName(msg.name);
325
+ return {
326
+ type: "session_name_update",
327
+ sessionId,
328
+ name: msg.name,
329
+ };
330
+
331
+ case "request_models": {
332
+ const registry = options?.getModelRegistry?.();
333
+ if (registry) {
334
+ try {
335
+ registry.authStorage?.reload?.();
336
+ registry.refresh();
337
+ const models = registry.getAvailable().map((m: any) => ({
338
+ provider: m.provider,
339
+ id: m.id,
340
+ }));
341
+ return { type: "models_list", sessionId, models };
342
+ } catch { /* ignore */ }
343
+ }
344
+ return { type: "models_list", sessionId, models: [] };
345
+ }
346
+
347
+ case "set_thinking_level":
348
+ if (options?.setThinkingLevel) {
349
+ options.setThinkingLevel(msg.level);
350
+ }
351
+ return undefined;
352
+
353
+ case "set_model":
354
+ if (options?.setModel) {
355
+ await options.setModel(msg.provider, msg.modelId);
356
+ }
357
+ return undefined;
358
+
359
+ case "kill_process": {
360
+ const pgid = (msg as { pgid: number }).pgid;
361
+ if (pgid) {
362
+ const killed = killProcessByPgid(pgid);
363
+ console.error(`[dashboard] kill_process pgid=${pgid} result=${killed}`);
364
+ }
365
+ return undefined;
366
+ }
367
+
368
+ case "shutdown":
369
+ if (options?.shutdown) {
370
+ options.shutdown();
371
+ }
372
+ return undefined;
373
+
374
+ case "request_state_sync":
375
+ // State sync is handled by the bridge on reconnect
376
+ return undefined;
377
+
378
+ case "request_flows_refresh": {
379
+ // Re-query pi-flows and send updated list
380
+ if (options?.eventSink) {
381
+ const probe: any = {};
382
+ try { pi.events?.emit("flow:list-flows", probe); } catch { /* ignore */ }
383
+ options.eventSink({ type: "flows_list", sessionId, flows: probe.flows ?? [] });
384
+ }
385
+ return undefined;
386
+ }
387
+
388
+ case "list_sessions": {
389
+ try {
390
+ // Dynamic import to avoid hard dependency at module load
391
+ const { SessionManager } = await import("@mariozechner/pi-coding-agent") as any;
392
+ const cwd = msg.cwd || options?.getCwd?.() || process.cwd();
393
+ const sessionInfos = await SessionManager.list(cwd);
394
+ const sessions: PiSessionInfo[] = (sessionInfos || []).map((s: any) => ({
395
+ id: s.id,
396
+ path: s.path,
397
+ cwd: s.cwd,
398
+ name: s.name,
399
+ parentSessionPath: s.parentSessionPath,
400
+ created: s.created instanceof Date ? s.created.toISOString() : String(s.created),
401
+ modified: s.modified instanceof Date ? s.modified.toISOString() : String(s.modified),
402
+ messageCount: s.messageCount ?? 0,
403
+ firstMessage: s.firstMessage,
404
+ }));
405
+ return { type: "sessions_list", sessionId, cwd, sessions };
406
+ } catch {
407
+ return { type: "sessions_list", sessionId, cwd: msg.cwd || process.cwd(), sessions: [] };
408
+ }
409
+ }
410
+
411
+ default:
412
+ return undefined;
413
+ }
414
+ },
415
+ };
416
+ }
417
+
418
+ /** Send a user message with optional image validation.
419
+ * Uses deliverAs: "followUp" so messages queue properly when the agent is streaming. */
420
+ function sendUserMessageWithImages(
421
+ pi: ExtensionAPI,
422
+ text: string,
423
+ images?: Array<{ type: string; data: string; mimeType: string }>,
424
+ ): void {
425
+ const sendOptions = { deliverAs: "followUp" as const };
426
+ if (images && images.length > 0) {
427
+ const validMimeTypes = new Set(["image/jpeg", "image/png", "image/gif", "image/webp"]);
428
+ const validImages = images.filter((img) => {
429
+ if (!img || typeof img !== "object") {
430
+ console.error("[dashboard] Dropping non-object image entry");
431
+ return false;
432
+ }
433
+ if (!img.mimeType || typeof img.mimeType !== "string" || !validMimeTypes.has(img.mimeType)) {
434
+ console.error(`[dashboard] Dropping image with invalid mimeType: "${img.mimeType}" (type: ${typeof img.mimeType})`);
435
+ return false;
436
+ }
437
+ if (!img.data || typeof img.data !== "string") {
438
+ console.error(`[dashboard] Dropping image with invalid data (type: ${typeof img.data}, length: ${img.data?.length ?? 0})`);
439
+ return false;
440
+ }
441
+ return true;
442
+ });
443
+ if (validImages.length > 0) {
444
+ const content = [
445
+ { type: "text" as const, text },
446
+ ...validImages.map((img) => ({
447
+ type: "image" as const,
448
+ data: img.data,
449
+ mimeType: img.mimeType,
450
+ })),
451
+ ];
452
+ console.error(`[dashboard] Sending message with ${validImages.length} image(s), mimeTypes: ${validImages.map(i => i.mimeType).join(", ")}`);
453
+ (pi.sendUserMessage as any)(content, sendOptions);
454
+ } else {
455
+ (pi.sendUserMessage as any)(text, sendOptions);
456
+ }
457
+ } else {
458
+ (pi.sendUserMessage as any)(text, sendOptions);
459
+ }
460
+ }
461
+
462
+ /** Execute a bash command and forward results */
463
+ async function handleBashCommand(
464
+ pi: ExtensionAPI,
465
+ sessionId: string,
466
+ command: string,
467
+ excludeFromContext: boolean,
468
+ eventSink?: (msg: ExtensionToServerMessage) => void,
469
+ ): Promise<void> {
470
+ let output = "";
471
+ let exitCode = 0;
472
+ try {
473
+ const result = await pi.exec("sh", ["-c", command], { timeout: BASH_TIMEOUT });
474
+ output = (result.stdout || "") + (result.stderr || "");
475
+ exitCode = result.exitCode ?? 0;
476
+ } catch (err: any) {
477
+ output = err?.message ?? "Command execution failed";
478
+ exitCode = 1;
479
+ }
480
+
481
+ // Forward bash output event
482
+ eventSink?.({
483
+ type: "event_forward",
484
+ sessionId,
485
+ event: {
486
+ eventType: "bash_output",
487
+ timestamp: Date.now(),
488
+ data: { command, output, exitCode, excludeFromContext },
489
+ },
490
+ });
491
+
492
+ // For ! (not !!), also send to LLM
493
+ if (!excludeFromContext) {
494
+ const message = `$ ${command}\n${output}`;
495
+ pi.sendUserMessage(message);
496
+ }
497
+ }
498
+
499
+ /** Handle /compact command */
500
+ async function handleCompactCommand(
501
+ sessionId: string,
502
+ customInstructions: string | undefined,
503
+ compact?: (options: { customInstructions?: string }) => void,
504
+ eventSink?: (msg: ExtensionToServerMessage) => void,
505
+ ): Promise<void> {
506
+ eventSink?.({
507
+ type: "event_forward",
508
+ sessionId,
509
+ event: {
510
+ eventType: "command_feedback",
511
+ timestamp: Date.now(),
512
+ data: { command: "/compact", status: "started" },
513
+ },
514
+ });
515
+
516
+ try {
517
+ if (compact) {
518
+ compact({ customInstructions });
519
+ }
520
+ } catch (err: any) {
521
+ eventSink?.({
522
+ type: "event_forward",
523
+ sessionId,
524
+ event: {
525
+ eventType: "command_feedback",
526
+ timestamp: Date.now(),
527
+ data: { command: "/compact", status: "error", message: err?.message ?? "Compaction failed" },
528
+ },
529
+ });
530
+ }
531
+ }
532
+
533
+ // handleLoadSessionEvents removed — server loads sessions directly via DirectoryService