@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,240 @@
1
+ /**
2
+ * PromptBus — Unified prompt routing infrastructure.
3
+ *
4
+ * Routes prompt requests to registered adapters (TUI, dashboard, custom).
5
+ * Enforces first-response-wins semantics and cross-adapter dismissal.
6
+ * Replaces the ui-proxy race pattern and emitPromptAndAwait event system.
7
+ */
8
+
9
+ // ── Interfaces ──────────────────────────────────────────────────────
10
+
11
+ export interface PromptComponent {
12
+ /** Component type identifier — maps to a React component on the client */
13
+ type: string;
14
+ /** Serializable props for the component */
15
+ props: Record<string, unknown>;
16
+ }
17
+
18
+ export interface PromptClaim {
19
+ /** Optional custom dashboard UI component. If omitted, adapter handles externally (e.g. TUI). */
20
+ component?: PromptComponent;
21
+ /** Where to render the component on the dashboard client */
22
+ placement?: "widget-bar" | "inline" | "overlay";
23
+ }
24
+
25
+ export interface PromptRequest {
26
+ id: string;
27
+ pipeline: string;
28
+ type: "select" | "input" | "confirm" | "editor" | "multiselect";
29
+ question: string;
30
+ options?: string[];
31
+ defaultValue?: string;
32
+ metadata?: Record<string, unknown>;
33
+ }
34
+
35
+ export interface PromptResponse {
36
+ id: string;
37
+ answer?: string;
38
+ cancelled?: boolean;
39
+ source: string;
40
+ }
41
+
42
+ export interface PromptAdapter {
43
+ name: string;
44
+ /**
45
+ * Called when a new prompt arrives.
46
+ * Return a PromptClaim to participate, or null/undefined to skip.
47
+ */
48
+ onRequest(prompt: PromptRequest): PromptClaim | null | undefined | void;
49
+ /** Called when any adapter answered — dismiss your UI if active. */
50
+ onResponse(response: PromptResponse): void;
51
+ /** Called on cancel/timeout — clean up your UI. */
52
+ onCancel(id: string): void;
53
+ }
54
+
55
+ // ── Internal types ──────────────────────────────────────────────────
56
+
57
+ interface PendingPrompt {
58
+ request: PromptRequest;
59
+ resolve: (response: PromptResponse) => void;
60
+ timer: ReturnType<typeof setTimeout>;
61
+ claims: Array<{ adapter: PromptAdapter; claim: PromptClaim }>;
62
+ /** Resolved component sent to dashboard at request time (for reconnect replay) */
63
+ resolvedComponent: PromptComponent | undefined;
64
+ /** Resolved placement sent to dashboard at request time (for reconnect replay) */
65
+ resolvedPlacement: string | undefined;
66
+ }
67
+
68
+ export interface PromptBusOptions {
69
+ /** Default timeout in milliseconds (default: 5 minutes) */
70
+ timeoutMs?: number;
71
+ /** Called when a prompt_request should be sent to the dashboard */
72
+ onDashboardRequest?: (prompt: PromptRequest, component: PromptComponent, placement: string) => void;
73
+ /** Called when a prompt_dismiss should be sent to the dashboard */
74
+ onDashboardDismiss?: (id: string) => void;
75
+ /** Called when a prompt_cancel should be sent to the dashboard */
76
+ onDashboardCancel?: (id: string) => void;
77
+ }
78
+
79
+ // ── PromptBus ───────────────────────────────────────────────────────
80
+
81
+ const DEFAULT_TIMEOUT_MS = 5 * 60 * 1000;
82
+
83
+ export class PromptBus {
84
+ private adapters: PromptAdapter[] = [];
85
+ private pending = new Map<string, PendingPrompt>();
86
+ private options: PromptBusOptions;
87
+
88
+ constructor(options: PromptBusOptions = {}) {
89
+ this.options = options;
90
+ }
91
+
92
+ /**
93
+ * Register an adapter. Returns an unsubscribe function.
94
+ * Re-registering with the same name replaces the previous adapter.
95
+ */
96
+ registerAdapter(adapter: PromptAdapter): () => void {
97
+ // Replace existing adapter with same name
98
+ this.adapters = this.adapters.filter(a => a.name !== adapter.name);
99
+ this.adapters.push(adapter);
100
+
101
+ return () => {
102
+ this.adapters = this.adapters.filter(a => a !== adapter);
103
+ };
104
+ }
105
+
106
+ /**
107
+ * Submit a prompt. Returns a promise that resolves when any adapter answers.
108
+ */
109
+ request(options: Omit<PromptRequest, "id">): Promise<PromptResponse> {
110
+ const id = crypto.randomUUID();
111
+ const request: PromptRequest = { id, ...options };
112
+
113
+ return new Promise<PromptResponse>((resolve) => {
114
+ const timeoutMs = this.options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
115
+ const timer = setTimeout(() => {
116
+ this.cancel(id);
117
+ }, timeoutMs);
118
+
119
+ // Distribute to all adapters and collect claims
120
+ const claims: PendingPrompt["claims"] = [];
121
+ for (const adapter of this.adapters) {
122
+ try {
123
+ const claim = adapter.onRequest(request);
124
+ if (claim) {
125
+ claims.push({ adapter, claim });
126
+ }
127
+ } catch {
128
+ // Adapter error — skip it
129
+ }
130
+ }
131
+
132
+ // Resolve dashboard rendering: first adapter with a component wins
133
+ const componentClaim = claims.find(c => c.claim.component);
134
+ let resolvedComponent: PromptComponent | undefined;
135
+ let resolvedPlacement: string | undefined;
136
+ if (componentClaim) {
137
+ resolvedComponent = componentClaim.claim.component!;
138
+ resolvedPlacement = componentClaim.claim.placement ?? "inline";
139
+ } else if (this.options.onDashboardRequest) {
140
+ resolvedComponent = {
141
+ type: "generic-dialog",
142
+ props: {
143
+ question: request.question,
144
+ type: request.type,
145
+ options: request.options,
146
+ defaultValue: request.defaultValue,
147
+ },
148
+ };
149
+ resolvedPlacement = "inline";
150
+ }
151
+
152
+ // Store pending state (with resolved component for reconnect replay)
153
+ this.pending.set(id, { request, resolve, timer, claims, resolvedComponent, resolvedPlacement });
154
+
155
+ // Send to dashboard
156
+ if (resolvedComponent && this.options.onDashboardRequest) {
157
+ this.options.onDashboardRequest(request, resolvedComponent, resolvedPlacement!);
158
+ }
159
+ });
160
+ }
161
+
162
+ /**
163
+ * An adapter calls this to answer a prompt. First response wins.
164
+ */
165
+ respond(response: PromptResponse): void {
166
+ const entry = this.pending.get(response.id);
167
+ if (!entry) return; // Already resolved or unknown
168
+
169
+ this.pending.delete(response.id);
170
+ clearTimeout(entry.timer);
171
+
172
+ // Notify ALL adapters so they can dismiss their UI
173
+ for (const adapter of this.adapters) {
174
+ try {
175
+ adapter.onResponse(response);
176
+ } catch {
177
+ // Adapter error — continue
178
+ }
179
+ }
180
+
181
+ // Send dismiss to dashboard if a non-dashboard source answered
182
+ if (this.options.onDashboardDismiss) {
183
+ this.options.onDashboardDismiss(response.id);
184
+ }
185
+
186
+ entry.resolve(response);
187
+ }
188
+
189
+ /**
190
+ * Cancel a pending prompt (e.g. on timeout or abort).
191
+ */
192
+ cancel(id: string): void {
193
+ const entry = this.pending.get(id);
194
+ if (!entry) return;
195
+
196
+ this.pending.delete(id);
197
+ clearTimeout(entry.timer);
198
+
199
+ // Notify adapters
200
+ for (const adapter of this.adapters) {
201
+ try {
202
+ adapter.onCancel(id);
203
+ } catch {
204
+ // Adapter error — continue
205
+ }
206
+ }
207
+
208
+ // Notify dashboard
209
+ if (this.options.onDashboardCancel) {
210
+ this.options.onDashboardCancel(id);
211
+ }
212
+
213
+ entry.resolve({ id, cancelled: true, source: "__bus__" });
214
+ }
215
+
216
+ /** Get pending requests with their resolved dashboard components (for reconnect replay). */
217
+ getPendingRequests(): Array<{ request: PromptRequest; component: PromptComponent; placement: string }> {
218
+ const result: Array<{ request: PromptRequest; component: PromptComponent; placement: string }> = [];
219
+ for (const entry of this.pending.values()) {
220
+ if (entry.resolvedComponent && entry.resolvedPlacement) {
221
+ result.push({
222
+ request: entry.request,
223
+ component: entry.resolvedComponent,
224
+ placement: entry.resolvedPlacement,
225
+ });
226
+ }
227
+ }
228
+ return result;
229
+ }
230
+
231
+ /** Get the number of pending prompts (for testing/diagnostics). */
232
+ get pendingCount(): number {
233
+ return this.pending.size;
234
+ }
235
+
236
+ /** Get registered adapter names (for testing/diagnostics). */
237
+ get adapterNames(): string[] {
238
+ return this.adapters.map(a => a.name);
239
+ }
240
+ }
@@ -0,0 +1,108 @@
1
+ /**
2
+ * Expand prompt templates from disk for slash commands sent via the dashboard.
3
+ *
4
+ * pi.sendUserMessage() calls session.prompt() with expandPromptTemplates: false,
5
+ * which skips prompt template and skill expansion. This module provides a workaround
6
+ * by reading template/skill files directly and expanding them.
7
+ */
8
+ import { readFileSync, existsSync } from "node:fs";
9
+ import { join, resolve } from "node:path";
10
+ import { readdirSync, statSync } from "node:fs";
11
+
12
+ /** Scan directories for .md prompt template files */
13
+ function findPromptTemplates(cwd: string): Map<string, string> {
14
+ const templates = new Map<string, string>();
15
+ const dirs = [
16
+ join(cwd, ".pi", "prompts"),
17
+ join(cwd, ".pi", "skills"),
18
+ ];
19
+
20
+ for (const dir of dirs) {
21
+ if (!existsSync(dir)) continue;
22
+ try {
23
+ scanDir(dir, templates);
24
+ } catch { /* ignore */ }
25
+ }
26
+ return templates;
27
+ }
28
+
29
+ function scanDir(dir: string, templates: Map<string, string>): void {
30
+ for (const entry of readdirSync(dir)) {
31
+ const fullPath = join(dir, entry);
32
+ try {
33
+ const stat = statSync(fullPath);
34
+ if (stat.isDirectory()) {
35
+ // Check for SKILL.md inside directory
36
+ const skillFile = join(fullPath, "SKILL.md");
37
+ if (existsSync(skillFile)) {
38
+ templates.set(`skill:${entry}`, skillFile);
39
+ }
40
+ } else if (entry.endsWith(".md")) {
41
+ const name = entry.replace(/\.md$/, "");
42
+ templates.set(name, fullPath);
43
+ }
44
+ } catch { /* ignore */ }
45
+ }
46
+ }
47
+
48
+ /** Read template content, stripping YAML frontmatter */
49
+ function readTemplate(filePath: string): string {
50
+ const content = readFileSync(filePath, "utf-8");
51
+ // Strip YAML frontmatter (---\n...\n---)
52
+ const match = content.match(/^---\n[\s\S]*?\n---\n([\s\S]*)$/);
53
+ return match ? match[1].trim() : content.trim();
54
+ }
55
+
56
+ /**
57
+ * Expand a slash command by finding and reading the prompt template from disk.
58
+ * Returns the expanded text, or the original text if no template found.
59
+ *
60
+ * @param pi Optional pi extension API — used to find globally installed skills
61
+ * and package skills via pi.getCommands() when local scan misses them.
62
+ */
63
+ export function expandPromptTemplateFromDisk(text: string, cwd: string, pi?: any): string {
64
+ if (!text.startsWith("/")) return text;
65
+
66
+ // Split template name from args on first whitespace (space OR newline).
67
+ // Using indexOf(" ") alone breaks multi-line payloads like "/skill:foo\nargs"
68
+ // because the first space can lie inside the args, producing a name such as
69
+ // "skill:foo\nargs-first-word" that never matches a template.
70
+ const m = text.slice(1).match(/^(\S+)\s*([\s\S]*)$/);
71
+ const templateName = m?.[1] ?? text.slice(1);
72
+ const argsString = m?.[2] ?? "";
73
+
74
+ const templates = findPromptTemplates(cwd);
75
+ let filePath = templates.get(templateName);
76
+
77
+ // Support colon as alias for hyphen (e.g. /opsx:continue → opsx-continue)
78
+ if (!filePath && templateName.includes(":")) {
79
+ filePath = templates.get(templateName.replace(/:/g, "-"));
80
+ }
81
+
82
+ // Fallback: check pi.getCommands() for globally installed skills and package skills
83
+ // that aren't in the local .pi/skills/ directory.
84
+ if (!filePath && pi?.getCommands) {
85
+ try {
86
+ const commands = pi.getCommands();
87
+ const skill = commands.find(
88
+ (c: any) => c.name === templateName && c.source === "skill" && c.path,
89
+ );
90
+ if (skill?.path && existsSync(skill.path)) {
91
+ filePath = skill.path;
92
+ }
93
+ } catch { /* ignore */ }
94
+ }
95
+
96
+ if (!filePath) return text;
97
+
98
+ try {
99
+ const content = readTemplate(filePath);
100
+ // Simple arg substitution: replace $1, $2, etc. or just append args
101
+ if (argsString) {
102
+ return `${content}\n\n${argsString}`;
103
+ }
104
+ return content;
105
+ } catch {
106
+ return text;
107
+ }
108
+ }