@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,126 @@
1
+ /**
2
+ * Server launcher — spawns the dashboard server as a detached process.
3
+ * The spawned server runs in foreground mode (no subcommand) and writes
4
+ * its own PID file at ~/.pi/dashboard/server.pid.
5
+ */
6
+ import { spawnDetached, waitForReady } from "@blackbelt-technology/pi-dashboard-shared/platform/detached-spawn.js";
7
+ import fs from "node:fs";
8
+ import os from "node:os";
9
+ import path from "node:path";
10
+ import { createRequire } from "node:module";
11
+ import { fileURLToPath } from "node:url";
12
+ import type { DashboardConfig } from "@blackbelt-technology/pi-dashboard-shared/config.js";
13
+ import { resolveJitiImport } from "@blackbelt-technology/pi-dashboard-shared/resolve-jiti.js";
14
+ import { isDashboardRunning } from "@blackbelt-technology/pi-dashboard-shared/server-identity.js";
15
+
16
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
17
+ const require = createRequire(import.meta.url);
18
+
19
+ export interface LaunchResult {
20
+ success: boolean;
21
+ message: string;
22
+ }
23
+
24
+ /**
25
+ * Resolve the dashboard server CLI script path.
26
+ *
27
+ * Handles two layouts:
28
+ * 1. Monorepo dev: `<repo>/packages/extension/src/` → `<repo>/packages/server/src/cli.ts`
29
+ * 2. Installed : `<x>/node_modules/@blackbelt-technology/pi-dashboard-extension/src/`
30
+ * → `<x>/node_modules/@blackbelt-technology/pi-dashboard-server/src/cli.ts`
31
+ *
32
+ * Uses Node's module resolver (`require.resolve`) to find the server package
33
+ * and joins `src/cli.ts`. Falls back to the monorepo-relative path so existing
34
+ * dev workflows keep working even if the server package isn't resolvable (e.g.
35
+ * a pristine checkout with no node_modules yet).
36
+ */
37
+ export function resolveServerCliPath(): string {
38
+ try {
39
+ const serverPkgJson = require.resolve("@blackbelt-technology/pi-dashboard-server/package.json");
40
+ return path.resolve(path.dirname(serverPkgJson), "src", "cli.ts");
41
+ } catch {
42
+ // Dev-repo fallback: <extension>/src/../../server/src/cli.ts
43
+ return path.resolve(__dirname, "..", "..", "server", "src", "cli.ts");
44
+ }
45
+ }
46
+
47
+ /**
48
+ * Build the spawn arguments from config.
49
+ */
50
+ export function buildSpawnArgs(config: DashboardConfig): string[] {
51
+ return [
52
+ "--port", String(config.port),
53
+ "--pi-port", String(config.piPort),
54
+ ];
55
+ }
56
+
57
+ /**
58
+ * Launch the dashboard server as a detached background process.
59
+ * Returns success/failure after a brief wait to detect early crashes.
60
+ */
61
+ export async function launchServer(config: DashboardConfig): Promise<LaunchResult> {
62
+ const cliPath = resolveServerCliPath();
63
+ const args = buildSpawnArgs(config);
64
+
65
+ try {
66
+ // Open the server.log in append mode so any startup error is visible.
67
+ // Matches the log location used by `pi-dashboard start`.
68
+ let logFd: number | undefined;
69
+ try {
70
+ const logDir = path.join(os.homedir(), ".pi", "dashboard");
71
+ fs.mkdirSync(logDir, { recursive: true });
72
+ const logPath = path.join(logDir, "server.log");
73
+ logFd = fs.openSync(logPath, "a");
74
+ fs.writeSync(
75
+ logFd,
76
+ `\n[${new Date().toISOString()}] bridge auto-start (parent pid ${process.pid}, port ${config.port})\n`,
77
+ );
78
+ } catch { /* if we can't open the log, spawn still works */ }
79
+
80
+ // Spawn server via the detached-spawn primitive. resolveJitiImport()
81
+ // returns a file:// URL (required on Windows for node --import).
82
+ const r = await spawnDetached({
83
+ cmd: process.execPath,
84
+ args: ["--import", resolveJitiImport(), cliPath, ...args],
85
+ env: { ...process.env },
86
+ logFd,
87
+ });
88
+
89
+ // Close the parent's copy of the log fd — the child has its own.
90
+ if (logFd !== undefined) {
91
+ try { fs.closeSync(logFd); } catch { /* ignore */ }
92
+ }
93
+
94
+ if (!r.ok || !r.process) {
95
+ return { success: false, message: `Server process failed to spawn: ${r.error ?? "unknown"}` };
96
+ }
97
+
98
+ // Wait for the server to actually become available via positive
99
+ // HTTP probe. NO deadline — we rely on child-exit for failure
100
+ // detection. A timeout here only catches the pathological case
101
+ // "process alive but never ready", which is rarer than the
102
+ // false-positive case "slow cold-start mistakenly flagged as
103
+ // failure" (Fastify + jiti compile + session scan can take 15–30s
104
+ // on Windows). If the child crashes, `waitForReady` returns
105
+ // { ok: false, error: "child exited with code N" } via its
106
+ // `child` listener. If the child hangs alive-but-broken, the user
107
+ // can kill it manually — timers don't help that case anyway.
108
+ const ready = await waitForReady({
109
+ probe: async () => (await isDashboardRunning(config.port)).running,
110
+ pollIntervalMs: 300,
111
+ child: r.process,
112
+ // deadlineMs intentionally omitted — wait indefinitely.
113
+ });
114
+
115
+ if (!ready.ok) {
116
+ return {
117
+ success: false,
118
+ message: `Server process failed: ${ready.error ?? "unknown"}. See ~/.pi/dashboard/server.log`,
119
+ };
120
+ }
121
+
122
+ return { success: true, message: "Server started" };
123
+ } catch (err: any) {
124
+ return { success: false, message: err.message };
125
+ }
126
+ }
@@ -0,0 +1,33 @@
1
+ /**
2
+ * TCP port probe to detect if the dashboard server is running.
3
+ */
4
+ import net from "node:net";
5
+
6
+ const PROBE_TIMEOUT = 1000;
7
+
8
+ /**
9
+ * Check if a port is open on localhost by attempting a TCP connection.
10
+ * Returns true if connection succeeds, false if refused or timed out.
11
+ */
12
+ export function isPortOpen(port: number): Promise<boolean> {
13
+ return new Promise((resolve) => {
14
+ const socket = net.connect({ host: "localhost", port });
15
+
16
+ const timer = setTimeout(() => {
17
+ socket.destroy();
18
+ resolve(false);
19
+ }, PROBE_TIMEOUT);
20
+
21
+ socket.on("connect", () => {
22
+ clearTimeout(timer);
23
+ socket.destroy();
24
+ resolve(true);
25
+ });
26
+
27
+ socket.on("error", () => {
28
+ clearTimeout(timer);
29
+ socket.destroy();
30
+ resolve(false);
31
+ });
32
+ });
33
+ }
@@ -0,0 +1,155 @@
1
+ /**
2
+ * Session sync: register, replay, and handle session changes.
3
+ * Extracted from bridge.ts for clarity.
4
+ */
5
+ import type { BridgeContext } from "./bridge-context.js";
6
+ import { getCurrentModelString, extractFirstMessage, filterHiddenCommands } from "./bridge-context.js";
7
+ import { detectSessionSource } from "./source-detector.js";
8
+ import { replayEntriesAsEvents } from "@blackbelt-technology/pi-dashboard-shared/state-replay.js";
9
+ import { gatherGitInfo } from "./git-info.js";
10
+ import type { FlowInfo } from "@blackbelt-technology/pi-dashboard-shared/types.js";
11
+
12
+ /**
13
+ * Send full state sync to the server (session_register, commands, flows, models).
14
+ * Called on initial connect and reconnect.
15
+ */
16
+ export function sendStateSync(
17
+ bc: BridgeContext,
18
+ getFlowsList: () => FlowInfo[],
19
+ ): void {
20
+ const model = getCurrentModelString(bc);
21
+ const thinkingLevel = (bc.pi as any).getThinkingLevel?.() ?? undefined;
22
+ bc.lastModel = model;
23
+ bc.lastThinkingLevel = thinkingLevel;
24
+
25
+ const sessionFile = bc.lastSessionFile ?? bc.cachedCtx?.sessionManager?.getSessionFile?.() ?? undefined;
26
+ const sessionDir = bc.lastSessionDir ?? bc.cachedCtx?.sessionManager?.getSessionDir?.() ?? undefined;
27
+ const firstMessage = extractFirstMessage(bc.cachedCtx);
28
+
29
+ // Include eventCount so server can skip event wipe on reconnect
30
+ let eventCount: number | undefined;
31
+ try {
32
+ const entries = bc.cachedCtx?.sessionManager?.getBranch?.();
33
+ if (entries) eventCount = entries.length;
34
+ } catch { /* ignore */ }
35
+
36
+ bc.connection.send({
37
+ type: "session_register",
38
+ sessionId: bc.sessionId,
39
+ cwd: process.cwd(),
40
+ name: bc.pi.getSessionName() ?? undefined,
41
+ source: detectSessionSource(bc.cachedHasUI, sessionFile),
42
+ model,
43
+ thinkingLevel,
44
+ sessionFile,
45
+ sessionDir,
46
+ firstMessage,
47
+ eventCount,
48
+ pid: process.pid,
49
+ });
50
+
51
+ const commands = filterHiddenCommands(bc.pi.getCommands());
52
+ bc.connection.send({ type: "commands_list", sessionId: bc.sessionId, commands });
53
+
54
+ // Send flows list
55
+ const flows = getFlowsList();
56
+ bc.connection.send({ type: "flows_list", sessionId: bc.sessionId, flows });
57
+
58
+ if (bc.cachedModelRegistry) {
59
+ try {
60
+ const models = bc.cachedModelRegistry.getAvailable().map((m: any) => ({
61
+ provider: m.provider,
62
+ id: m.id,
63
+ }));
64
+ bc.connection.send({ type: "models_list", sessionId: bc.sessionId, models });
65
+ } catch { /* ignore */ }
66
+ }
67
+ }
68
+
69
+ /**
70
+ * Replay all session entries as protocol events.
71
+ */
72
+ export function replaySessionEntries(bc: BridgeContext): void {
73
+ try {
74
+ const entries = bc.cachedCtx?.sessionManager?.getBranch?.();
75
+ if (!entries || entries.length === 0) return;
76
+ const events = replayEntriesAsEvents(bc.sessionId, entries);
77
+ for (const msg of events) {
78
+ bc.connection.send(msg);
79
+ }
80
+ } catch { /* ignore */ }
81
+ }
82
+
83
+ /**
84
+ * Handle session change (new/fork/resume): unregister old, register new, replay, sync.
85
+ * Called from session_start when event.reason indicates a session switch.
86
+ */
87
+ export function handleSessionChange(
88
+ bc: BridgeContext,
89
+ ctx: any,
90
+ getFlowsList: () => FlowInfo[],
91
+ ): void {
92
+ bc.connection.send({ type: "session_unregister", sessionId: bc.sessionId });
93
+
94
+ bc.sessionId = ctx.sessionManager.getSessionId();
95
+ bc.lastSessionFile = ctx.sessionManager.getSessionFile?.() ?? undefined;
96
+ bc.lastSessionDir = ctx.sessionManager.getSessionDir?.() ?? undefined;
97
+ const firstMessage = extractFirstMessage(ctx);
98
+
99
+ bc.lastFirstMessage = firstMessage;
100
+ bc.lastGitBranch = undefined;
101
+ bc.lastGitPrNumber = undefined;
102
+ bc.lastSessionName = bc.pi.getSessionName() ?? "";
103
+ bc.lastModel = getCurrentModelString(bc);
104
+ bc.lastThinkingLevel = (bc.pi as any).getThinkingLevel?.() ?? undefined;
105
+
106
+ // Include eventCount for consistency (session switch/fork changes sessionId,
107
+ // so the server will wipe regardless, but include for completeness)
108
+ let eventCount: number | undefined;
109
+ try {
110
+ const entries = ctx.sessionManager?.getBranch?.();
111
+ if (entries) eventCount = entries.length;
112
+ } catch { /* ignore */ }
113
+
114
+ bc.connection.send({
115
+ type: "session_register",
116
+ sessionId: bc.sessionId,
117
+ cwd: ctx.cwd,
118
+ name: bc.lastSessionName || undefined,
119
+ source: detectSessionSource(bc.cachedHasUI, bc.lastSessionFile),
120
+ model: bc.lastModel,
121
+ thinkingLevel: bc.lastThinkingLevel,
122
+ sessionFile: bc.lastSessionFile,
123
+ sessionDir: bc.lastSessionDir,
124
+ firstMessage,
125
+ eventCount,
126
+ pid: process.pid,
127
+ });
128
+
129
+ replaySessionEntries(bc);
130
+ bc.connection.send({ type: "replay_complete", sessionId: bc.sessionId });
131
+
132
+ // Send git info
133
+ const gitInfo = gatherGitInfo(ctx.cwd);
134
+ if (gitInfo) {
135
+ bc.lastGitBranch = gitInfo.gitBranch;
136
+ bc.lastGitPrNumber = gitInfo.gitPrNumber;
137
+ bc.connection.send({ type: "git_info_update", sessionId: bc.sessionId, ...gitInfo });
138
+ }
139
+
140
+ const commands = filterHiddenCommands(bc.pi.getCommands());
141
+ bc.connection.send({ type: "commands_list", sessionId: bc.sessionId, commands });
142
+
143
+ const flows = getFlowsList();
144
+ bc.connection.send({ type: "flows_list", sessionId: bc.sessionId, flows });
145
+
146
+ if (bc.cachedModelRegistry) {
147
+ try {
148
+ const models = bc.cachedModelRegistry.getAvailable().map((m: any) => ({
149
+ provider: m.provider,
150
+ id: m.id,
151
+ }));
152
+ bc.connection.send({ type: "models_list", sessionId: bc.sessionId, models });
153
+ } catch { /* ignore */ }
154
+ }
155
+ }
@@ -0,0 +1,26 @@
1
+ import type { SessionSource } from "@blackbelt-technology/pi-dashboard-shared/types.js";
2
+ import { readSessionMeta } from "@blackbelt-technology/pi-dashboard-shared/session-meta.js";
3
+
4
+ /**
5
+ * Detect the source environment of the current pi session
6
+ * by checking environment variables in priority order.
7
+ *
8
+ * @param hasUI - Whether the pi session has a UI (TUI). When true and ZED_TERM
9
+ * is set, it means pi TUI is running inside Zed's terminal (not Zed's agent).
10
+ * @param sessionFile - Path to the session's .jsonl file, used to check for
11
+ * a .meta.json sidecar with source information.
12
+ */
13
+ export function detectSessionSource(hasUI?: boolean, sessionFile?: string): SessionSource {
14
+ // Check for .meta.json sidecar written by the dashboard server
15
+ if (sessionFile) {
16
+ const meta = readSessionMeta(sessionFile);
17
+ if (meta?.source === "dashboard") return "dashboard";
18
+ }
19
+
20
+ if (process.env.ZED_TERM) {
21
+ if (hasUI) return "tui";
22
+ return "zed";
23
+ }
24
+ if (process.env.TMUX) return "tmux";
25
+ return "tui";
26
+ }