@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.
- package/.pi/skills/pi-dashboard/SKILL.md +134 -0
- package/.pi/skills/pi-dashboard/references/api-reference.md +470 -0
- package/.pi/skills/pi-dashboard/references/recipes.md +252 -0
- package/.pi/skills/pi-dashboard/scripts/dashboard-api.sh +75 -0
- package/package.json +38 -0
- package/src/__tests__/ask-user-tool.test.ts +432 -0
- package/src/__tests__/command-handler.test.ts +712 -0
- package/src/__tests__/connection.test.ts +344 -0
- package/src/__tests__/credentials-updated.test.ts +26 -0
- package/src/__tests__/dashboard-default-adapter.test.ts +77 -0
- package/src/__tests__/dev-build.test.ts +79 -0
- package/src/__tests__/enrich-model-metadata.test.ts +201 -0
- package/src/__tests__/event-forwarder.test.ts +89 -0
- package/src/__tests__/fork-entryid-timing.test.ts +100 -0
- package/src/__tests__/git-info.test.ts +124 -0
- package/src/__tests__/git-link-builder.test.ts +102 -0
- package/src/__tests__/openspec-activity-detector.test.ts +232 -0
- package/src/__tests__/openspec-poller.test.ts +124 -0
- package/src/__tests__/process-metrics.test.ts +47 -0
- package/src/__tests__/process-scanner-kill.test.ts +61 -0
- package/src/__tests__/process-scanner.test.ts +202 -0
- package/src/__tests__/prompt-bus-wiring.test.ts +791 -0
- package/src/__tests__/prompt-bus.test.ts +469 -0
- package/src/__tests__/prompt-expander.test.ts +54 -0
- package/src/__tests__/provider-register-reload.test.ts +394 -0
- package/src/__tests__/server-auto-start.test.ts +258 -0
- package/src/__tests__/server-launcher.test.ts +61 -0
- package/src/__tests__/server-probe.test.ts +25 -0
- package/src/__tests__/session-switch.test.ts +139 -0
- package/src/__tests__/session-sync.test.ts +55 -0
- package/src/__tests__/source-detector.test.ts +73 -0
- package/src/__tests__/stats-extractor.test.ts +92 -0
- package/src/__tests__/tui-prompt-adapter.test.ts +207 -0
- package/src/__tests__/watchdog.test.ts +161 -0
- package/src/ask-user-tool.ts +352 -0
- package/src/bridge-context.ts +64 -0
- package/src/bridge.ts +1182 -0
- package/src/command-handler.ts +533 -0
- package/src/connection.ts +204 -0
- package/src/dashboard-default-adapter.ts +37 -0
- package/src/dev-build.ts +39 -0
- package/src/event-forwarder.ts +40 -0
- package/src/flow-event-wiring.ts +85 -0
- package/src/git-info.ts +55 -0
- package/src/git-link-builder.ts +112 -0
- package/src/model-tracker.ts +56 -0
- package/src/pi-env.d.ts +37 -0
- package/src/process-metrics.ts +70 -0
- package/src/process-scanner.ts +430 -0
- package/src/prompt-bus.ts +240 -0
- package/src/prompt-expander.ts +108 -0
- package/src/provider-register.ts +564 -0
- package/src/server-auto-start.ts +113 -0
- package/src/server-launcher.ts +126 -0
- package/src/server-probe.ts +33 -0
- package/src/session-sync.ts +155 -0
- package/src/source-detector.ts +26 -0
|
@@ -0,0 +1,564 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Provider Extension (Dashboard)
|
|
3
|
+
*
|
|
4
|
+
* Registers custom LLM providers with auto-discovered models.
|
|
5
|
+
* Config: ~/.pi/agent/providers.json (providers section only — preserves other fields)
|
|
6
|
+
*
|
|
7
|
+
* Providers are configured via the dashboard settings UI or by editing
|
|
8
|
+
* ~/.pi/agent/providers.json directly. No TUI commands.
|
|
9
|
+
*
|
|
10
|
+
* Event API:
|
|
11
|
+
* flow:resolve-model / flow:get-available-models
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import type { ExtensionAPI } from "@mariozechner/pi-coding-agent";
|
|
15
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
16
|
+
import { homedir } from "node:os";
|
|
17
|
+
import { join } from "node:path";
|
|
18
|
+
|
|
19
|
+
// -- Types ----------------------------------------------------------------
|
|
20
|
+
|
|
21
|
+
interface ProviderEntry {
|
|
22
|
+
baseUrl: string;
|
|
23
|
+
apiKey: string;
|
|
24
|
+
api?: string;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
type InputModality = "text" | "image";
|
|
28
|
+
|
|
29
|
+
export interface ModelMetadata {
|
|
30
|
+
contextWindow: number;
|
|
31
|
+
maxTokens: number;
|
|
32
|
+
reasoning: boolean;
|
|
33
|
+
cost: { input: number; output: number; cacheRead: number; cacheWrite: number };
|
|
34
|
+
input: InputModality[];
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* A catalog probe: given (provider, id), return the catalog entry or null.
|
|
39
|
+
* In production this is `modelRegistry.find(provider, id)` from pi's
|
|
40
|
+
* ModelRegistry (which knows both built-in pi-ai models AND user-configured
|
|
41
|
+
* custom models). Exposed as a parameter so unit tests can supply a fake
|
|
42
|
+
* catalog without needing pi-ai installed.
|
|
43
|
+
*/
|
|
44
|
+
export type CatalogProbe = (provider: string, modelId: string) => {
|
|
45
|
+
contextWindow: number;
|
|
46
|
+
maxTokens: number;
|
|
47
|
+
reasoning: boolean;
|
|
48
|
+
cost: { input: number; output: number; cacheRead: number; cacheWrite: number };
|
|
49
|
+
input: readonly ("text" | "image")[];
|
|
50
|
+
} | null | undefined;
|
|
51
|
+
|
|
52
|
+
// -- Model metadata enrichment --------------------------------------------
|
|
53
|
+
//
|
|
54
|
+
// Custom-provider `/v1/models` endpoints return only { id, object, ... } —
|
|
55
|
+
// they do not advertise context_window, max_tokens, cost, or reasoning
|
|
56
|
+
// capability. Rather than hardcode 200k / 16k / $0 / no-reasoning for every
|
|
57
|
+
// discovered model (the prior behavior, which was wrong for Opus 4.6+/Sonnet
|
|
58
|
+
// 4.6+/GPT-5/Gemini 2.5), we consult pi's `modelRegistry.find(provider, id)`
|
|
59
|
+
// — which surfaces pi-ai's bundled catalog plus any custom models — for
|
|
60
|
+
// accurate metadata and fall back to api-appropriate defaults when the
|
|
61
|
+
// catalog has no match.
|
|
62
|
+
//
|
|
63
|
+
// See change: enrich-custom-provider-model-metadata.
|
|
64
|
+
|
|
65
|
+
// API type → ordered list of candidate providers in pi's catalog.
|
|
66
|
+
// Provider keys match pi-ai's MODELS export as surfaced by modelRegistry.
|
|
67
|
+
// Order matters: first match wins.
|
|
68
|
+
const CANDIDATE_PROVIDERS: Record<string, readonly string[]> = {
|
|
69
|
+
"anthropic-messages": ["anthropic", "opencode"],
|
|
70
|
+
"google-generative-ai": ["google", "google-vertex"],
|
|
71
|
+
"openai-completions": ["openai", "openrouter", "groq", "xai", "mistral"],
|
|
72
|
+
};
|
|
73
|
+
|
|
74
|
+
// Api-typed fallback defaults when the catalog has no match. Modern floors:
|
|
75
|
+
// - anthropic-messages: 200k ctx (Claude 3/4 floor), 64k maxTok
|
|
76
|
+
// - google-generative-ai: 1M ctx (Gemini 1.5+/2.x floor), 65k maxTok
|
|
77
|
+
// - openai-completions (default): 128k ctx (GPT-4o floor), 16k maxTok
|
|
78
|
+
const FALLBACK_DEFAULTS: Record<string, Omit<ModelMetadata, "input">> = {
|
|
79
|
+
"anthropic-messages": {
|
|
80
|
+
contextWindow: 200_000,
|
|
81
|
+
maxTokens: 64_000,
|
|
82
|
+
reasoning: false,
|
|
83
|
+
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
|
|
84
|
+
},
|
|
85
|
+
"google-generative-ai": {
|
|
86
|
+
contextWindow: 1_000_000,
|
|
87
|
+
maxTokens: 65_536,
|
|
88
|
+
reasoning: false,
|
|
89
|
+
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
|
|
90
|
+
},
|
|
91
|
+
"openai-completions": {
|
|
92
|
+
contextWindow: 128_000,
|
|
93
|
+
maxTokens: 16_384,
|
|
94
|
+
reasoning: false,
|
|
95
|
+
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
|
|
96
|
+
},
|
|
97
|
+
};
|
|
98
|
+
|
|
99
|
+
const DEFAULT_INPUT: InputModality[] = ["text", "image"];
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* Resolve a discovered custom-provider model id to full metadata by consulting
|
|
103
|
+
* pi's model catalog via the supplied `probe` function. Falls back to
|
|
104
|
+
* api-appropriate defaults when no catalog entry matches OR when no probe is
|
|
105
|
+
* available (e.g., modelRegistry not yet captured from spawn-context).
|
|
106
|
+
*
|
|
107
|
+
* Strips common proxy-prefix path segments (`cc/`, `anthropic/`,
|
|
108
|
+
* `openrouter/anthropic/…`) before lookup so prefixed ids resolve to the same
|
|
109
|
+
* catalog entry as the bare id.
|
|
110
|
+
*
|
|
111
|
+
* Exported (with the `probe` parameter) for unit testing. Production callers
|
|
112
|
+
* use `registerEntry()` which injects `modelRegistry.find`.
|
|
113
|
+
*/
|
|
114
|
+
export function enrichModelMetadata(
|
|
115
|
+
discoveredId: string,
|
|
116
|
+
api?: string,
|
|
117
|
+
probe?: CatalogProbe | null,
|
|
118
|
+
): ModelMetadata {
|
|
119
|
+
const resolvedApi = api && api in CANDIDATE_PROVIDERS ? api : "openai-completions";
|
|
120
|
+
const candidates = CANDIDATE_PROVIDERS[resolvedApi] ?? CANDIDATE_PROVIDERS["openai-completions"];
|
|
121
|
+
|
|
122
|
+
// Build dedup'd list of ids to try: full, then everything after the last `/`.
|
|
123
|
+
const lookupIds: string[] = [discoveredId];
|
|
124
|
+
const lastSlash = discoveredId.lastIndexOf("/");
|
|
125
|
+
if (lastSlash >= 0 && lastSlash < discoveredId.length - 1) {
|
|
126
|
+
const bare = discoveredId.slice(lastSlash + 1);
|
|
127
|
+
if (bare && bare !== discoveredId) lookupIds.push(bare);
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
if (probe) {
|
|
131
|
+
for (const id of lookupIds) {
|
|
132
|
+
for (const provider of candidates) {
|
|
133
|
+
let match: ReturnType<CatalogProbe> | undefined;
|
|
134
|
+
try {
|
|
135
|
+
match = probe(provider, id);
|
|
136
|
+
} catch {
|
|
137
|
+
match = undefined;
|
|
138
|
+
}
|
|
139
|
+
if (match) {
|
|
140
|
+
return {
|
|
141
|
+
contextWindow: match.contextWindow,
|
|
142
|
+
maxTokens: match.maxTokens,
|
|
143
|
+
reasoning: match.reasoning,
|
|
144
|
+
cost: match.cost,
|
|
145
|
+
input: [...match.input] as InputModality[],
|
|
146
|
+
};
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
// No probe, or no catalog match — use api-appropriate fallback with
|
|
153
|
+
// image-capable default (see change: enable-image-input-custom-providers).
|
|
154
|
+
const fallback = FALLBACK_DEFAULTS[resolvedApi] ?? FALLBACK_DEFAULTS["openai-completions"];
|
|
155
|
+
return {
|
|
156
|
+
...fallback,
|
|
157
|
+
input: [...DEFAULT_INPUT],
|
|
158
|
+
};
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
// -- Config path ----------------------------------------------------------
|
|
162
|
+
|
|
163
|
+
// Resolved lazily so HOME can be changed in tests.
|
|
164
|
+
function configPath(): string {
|
|
165
|
+
return join(homedir(), ".pi", "agent", "providers.json");
|
|
166
|
+
}
|
|
167
|
+
const CONFIG_PATH = configPath();
|
|
168
|
+
|
|
169
|
+
// Snapshot of last-registered provider entries so reloadProviders can diff.
|
|
170
|
+
const lastRegistered = new Map<string, ProviderEntry>();
|
|
171
|
+
|
|
172
|
+
function entriesEqual(a: ProviderEntry, b: ProviderEntry): boolean {
|
|
173
|
+
return (
|
|
174
|
+
a.baseUrl === b.baseUrl &&
|
|
175
|
+
a.apiKey === b.apiKey &&
|
|
176
|
+
(a.api ?? "openai-completions") === (b.api ?? "openai-completions")
|
|
177
|
+
);
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
// -- Config I/O (read-only — providers section) ----------------------------
|
|
181
|
+
|
|
182
|
+
function loadProviders(): Record<string, ProviderEntry> {
|
|
183
|
+
const path = configPath();
|
|
184
|
+
if (existsSync(path)) {
|
|
185
|
+
try {
|
|
186
|
+
const raw = JSON.parse(readFileSync(path, "utf-8"));
|
|
187
|
+
const providers: Record<string, ProviderEntry> = { ...raw.providers };
|
|
188
|
+
for (const [, entry] of Object.entries(providers) as [string, any][]) {
|
|
189
|
+
if (entry.apiKeyEnv && !entry.apiKey) {
|
|
190
|
+
entry.apiKey = "$" + entry.apiKeyEnv;
|
|
191
|
+
delete entry.apiKeyEnv;
|
|
192
|
+
}
|
|
193
|
+
delete (entry as any).modelIds;
|
|
194
|
+
}
|
|
195
|
+
return providers;
|
|
196
|
+
} catch (err: any) {
|
|
197
|
+
console.error(
|
|
198
|
+
`[dashboard] providers.json reload failed: ${err?.message ?? String(err)}`,
|
|
199
|
+
);
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
return {};
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
// -- API key resolution ---------------------------------------------------
|
|
206
|
+
|
|
207
|
+
function resolveApiKey(apiKey: string): string | undefined {
|
|
208
|
+
if (apiKey.startsWith("$")) {
|
|
209
|
+
return process.env[apiKey.slice(1)];
|
|
210
|
+
}
|
|
211
|
+
return apiKey;
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
function resolveApiKeyEnvName(providerName: string, apiKey: string): string {
|
|
215
|
+
if (apiKey.startsWith("$")) {
|
|
216
|
+
return apiKey.slice(1);
|
|
217
|
+
}
|
|
218
|
+
const syntheticEnv = `JUDO_${providerName.toUpperCase().replace(/[^A-Z0-9]/g, "_")}_KEY`;
|
|
219
|
+
process.env[syntheticEnv] = apiKey;
|
|
220
|
+
return syntheticEnv;
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
function hasApiKey(_providerName: string, entry: ProviderEntry): boolean {
|
|
224
|
+
if (entry.apiKey.startsWith("$")) {
|
|
225
|
+
return !!process.env[entry.apiKey.slice(1)];
|
|
226
|
+
}
|
|
227
|
+
return true;
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
// -- Model discovery from /v1/models endpoint -----------------------------
|
|
231
|
+
|
|
232
|
+
interface DiscoveredModel {
|
|
233
|
+
id: string;
|
|
234
|
+
owned_by?: string;
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
async function discoverModels(baseUrl: string, apiKey: string): Promise<DiscoveredModel[]> {
|
|
238
|
+
const resolved = resolveApiKey(apiKey);
|
|
239
|
+
if (!resolved) return [];
|
|
240
|
+
|
|
241
|
+
const url = baseUrl.endsWith("/") ? `${baseUrl}models` : `${baseUrl}/models`;
|
|
242
|
+
|
|
243
|
+
try {
|
|
244
|
+
const response = await fetch(url, {
|
|
245
|
+
headers: {
|
|
246
|
+
"Authorization": `Bearer ${resolved}`,
|
|
247
|
+
"Content-Type": "application/json",
|
|
248
|
+
},
|
|
249
|
+
signal: AbortSignal.timeout(10_000),
|
|
250
|
+
});
|
|
251
|
+
|
|
252
|
+
if (!response.ok) {
|
|
253
|
+
console.warn(`[provider] Model discovery failed for ${url}: HTTP ${response.status}`);
|
|
254
|
+
return [];
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
const body = await response.json() as any;
|
|
258
|
+
if (!body?.data || !Array.isArray(body.data)) {
|
|
259
|
+
console.warn(`[provider] Model discovery: unexpected response format from ${url}`);
|
|
260
|
+
return [];
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
return body.data
|
|
264
|
+
.filter((m: any) => m?.id && typeof m.id === "string")
|
|
265
|
+
.map((m: any) => ({ id: m.id, owned_by: m.owned_by }));
|
|
266
|
+
} catch (err: any) {
|
|
267
|
+
console.warn(`[provider] Model discovery failed for ${url}: ${err.message}`);
|
|
268
|
+
return [];
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
// -- Mutable state --------------------------------------------------------
|
|
273
|
+
|
|
274
|
+
let currentSessionProvider = "";
|
|
275
|
+
let currentSessionModelId = "";
|
|
276
|
+
|
|
277
|
+
let piRef: ExtensionAPI | null = null;
|
|
278
|
+
|
|
279
|
+
// Captured from any pi event handler's ctx.modelRegistry (first available wins).
|
|
280
|
+
// Used by getModelRegistry() to probe pi's catalog for model metadata enrichment.
|
|
281
|
+
// See change: enrich-custom-provider-model-metadata.
|
|
282
|
+
let modelRegistryRef: any = null;
|
|
283
|
+
|
|
284
|
+
// Callback for notifying the bridge when providers change
|
|
285
|
+
let onProvidersChanged: (() => void) | null = null;
|
|
286
|
+
|
|
287
|
+
export function getSessionInfo(): { provider: string; modelId: string } {
|
|
288
|
+
return { provider: currentSessionProvider, modelId: currentSessionModelId };
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
export function getModelDisplayName(modelId: string): string {
|
|
292
|
+
if (piRef) {
|
|
293
|
+
const data: any = {};
|
|
294
|
+
piRef.events.emit("flow:get-available-models", data);
|
|
295
|
+
if (data.models && Array.isArray(data.models)) {
|
|
296
|
+
const match = data.models.find((m: any) => m.id === modelId || `${m.provider}/${m.id}` === modelId);
|
|
297
|
+
if (match?.name) return match.name;
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
return modelId;
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
/** Register a callback for when providers change (used by bridge for models_list push). */
|
|
304
|
+
export function onProviderChanged(callback: () => void): void {
|
|
305
|
+
onProvidersChanged = callback;
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
// -- Helper: get modelRegistry --------------------------------------------
|
|
309
|
+
//
|
|
310
|
+
// pi's ModelRegistry is passed as `ctx.modelRegistry` to every extension
|
|
311
|
+
// event handler (see ExtensionContext in pi's types). We capture the first
|
|
312
|
+
// reference we see in `session_start` and reuse it thereafter. This avoids
|
|
313
|
+
// depending on pi-flows' `flow:get-spawn-context` event which is not
|
|
314
|
+
// guaranteed to be present in every install.
|
|
315
|
+
function getModelRegistry(): any {
|
|
316
|
+
return modelRegistryRef;
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
// -- Provider registration (with auto-discovery) --------------------------
|
|
320
|
+
|
|
321
|
+
async function registerEntry(pi: ExtensionAPI, name: string, entry: ProviderEntry): Promise<number> {
|
|
322
|
+
const discovered = await discoverModels(entry.baseUrl, entry.apiKey);
|
|
323
|
+
|
|
324
|
+
// Metadata (contextWindow, maxTokens, reasoning, cost, input) is resolved
|
|
325
|
+
// via pi's `modelRegistry.find(provider, id)` when the registry is
|
|
326
|
+
// reachable, with api-appropriate fallbacks otherwise — the previous
|
|
327
|
+
// hardcoded 200k / 16k / $0 / no-reasoning was silently wrong for
|
|
328
|
+
// Opus 4.6+/Sonnet 4.6+/GPT-5/Gemini-2.x proxied via OpenAI-compatible
|
|
329
|
+
// endpoints. See enrichModelMetadata above, and change:
|
|
330
|
+
// enrich-custom-provider-model-metadata.
|
|
331
|
+
const registry = getModelRegistry();
|
|
332
|
+
const probe: CatalogProbe | null =
|
|
333
|
+
registry && typeof registry.find === "function"
|
|
334
|
+
? (provider, modelId) => registry.find(provider, modelId) ?? null
|
|
335
|
+
: null;
|
|
336
|
+
|
|
337
|
+
const models = discovered.map((m) => ({
|
|
338
|
+
id: m.id,
|
|
339
|
+
name: m.id,
|
|
340
|
+
...enrichModelMetadata(m.id, entry.api, probe),
|
|
341
|
+
}));
|
|
342
|
+
|
|
343
|
+
pi.registerProvider(name, {
|
|
344
|
+
baseUrl: entry.baseUrl,
|
|
345
|
+
apiKey: resolveApiKeyEnvName(name, entry.apiKey),
|
|
346
|
+
api: (entry.api ?? "openai-completions") as any,
|
|
347
|
+
models,
|
|
348
|
+
});
|
|
349
|
+
|
|
350
|
+
// Record snapshot so reloadProviders can detect subsequent changes.
|
|
351
|
+
lastRegistered.set(name, {
|
|
352
|
+
baseUrl: entry.baseUrl,
|
|
353
|
+
apiKey: entry.apiKey,
|
|
354
|
+
api: entry.api ?? "openai-completions",
|
|
355
|
+
});
|
|
356
|
+
|
|
357
|
+
// Notify bridge directly (same package — no cross-package event needed)
|
|
358
|
+
onProvidersChanged?.();
|
|
359
|
+
|
|
360
|
+
return discovered.length;
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
/**
|
|
364
|
+
* Diff the current providers.json against the last-registered snapshot and
|
|
365
|
+
* apply add / remove / change operations via `pi.registerProvider` and
|
|
366
|
+
* `pi.unregisterProvider`. Called by the bridge's `credentials_updated`
|
|
367
|
+
* handler so adding/editing/removing providers in the dashboard UI takes
|
|
368
|
+
* effect without a session restart.
|
|
369
|
+
*
|
|
370
|
+
* Malformed providers.json or IO errors produce an empty diff and do not
|
|
371
|
+
* throw, so the caller can still run `modelRegistry.refresh()` for other
|
|
372
|
+
* credential updates.
|
|
373
|
+
*/
|
|
374
|
+
export async function reloadProviders(
|
|
375
|
+
pi: ExtensionAPI,
|
|
376
|
+
): Promise<{ added: string[]; removed: string[]; changed: string[] }> {
|
|
377
|
+
piRef = pi;
|
|
378
|
+
const added: string[] = [];
|
|
379
|
+
const removed: string[] = [];
|
|
380
|
+
const changed: string[] = [];
|
|
381
|
+
|
|
382
|
+
let current: Record<string, ProviderEntry>;
|
|
383
|
+
try {
|
|
384
|
+
current = loadProviders();
|
|
385
|
+
} catch {
|
|
386
|
+
return { added, removed, changed };
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
// Detect removals and changes against previous snapshot.
|
|
390
|
+
for (const [name, prev] of lastRegistered) {
|
|
391
|
+
const next = current[name];
|
|
392
|
+
if (!next) {
|
|
393
|
+
try {
|
|
394
|
+
pi.unregisterProvider(name);
|
|
395
|
+
} catch (err: any) {
|
|
396
|
+
console.error(`[dashboard] unregisterProvider("${name}") failed: ${err?.message ?? String(err)}`);
|
|
397
|
+
}
|
|
398
|
+
lastRegistered.delete(name);
|
|
399
|
+
removed.push(name);
|
|
400
|
+
} else if (!entriesEqual(prev, next)) {
|
|
401
|
+
try {
|
|
402
|
+
pi.unregisterProvider(name);
|
|
403
|
+
} catch (err: any) {
|
|
404
|
+
console.error(`[dashboard] unregisterProvider("${name}") failed: ${err?.message ?? String(err)}`);
|
|
405
|
+
}
|
|
406
|
+
lastRegistered.delete(name);
|
|
407
|
+
changed.push(name);
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
// Register new entries and changed entries (order-dependent: unregister ran first above).
|
|
412
|
+
for (const [name, entry] of Object.entries(current)) {
|
|
413
|
+
if (lastRegistered.has(name)) continue;
|
|
414
|
+
try {
|
|
415
|
+
await registerEntry(pi, name, entry);
|
|
416
|
+
if (!added.includes(name) && !changed.includes(name)) {
|
|
417
|
+
added.push(name);
|
|
418
|
+
}
|
|
419
|
+
} catch (err: any) {
|
|
420
|
+
console.error(`[dashboard] registerProvider("${name}") failed: ${err?.message ?? String(err)}`);
|
|
421
|
+
}
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
return { added, removed, changed };
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
// -- Extension entry point ------------------------------------------------
|
|
428
|
+
|
|
429
|
+
export function activate(pi: ExtensionAPI) {
|
|
430
|
+
piRef = pi;
|
|
431
|
+
const providers = loadProviders();
|
|
432
|
+
|
|
433
|
+
// Register providers (async discovery, fire-and-forget at startup)
|
|
434
|
+
for (const [name, entry] of Object.entries(providers)) {
|
|
435
|
+
registerEntry(pi, name, entry).catch(() => {});
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
// ── Event API: Model Resolution ─────────────────────────────────────
|
|
439
|
+
|
|
440
|
+
pi.events.on("flow:resolve-model", async (data: any) => {
|
|
441
|
+
const modelRef: string = data?.modelRef;
|
|
442
|
+
if (!modelRef) return;
|
|
443
|
+
|
|
444
|
+
// Role aliases (@planning etc.) are handled by pi-flows role-manager.
|
|
445
|
+
if (modelRef.startsWith("@")) return;
|
|
446
|
+
|
|
447
|
+
const registry = getModelRegistry();
|
|
448
|
+
if (!registry) return;
|
|
449
|
+
|
|
450
|
+
const parts = modelRef.split("/");
|
|
451
|
+
let model: any;
|
|
452
|
+
if (parts.length >= 2) {
|
|
453
|
+
model = registry.find(parts[0], parts.slice(1).join("/"));
|
|
454
|
+
}
|
|
455
|
+
if (!model) {
|
|
456
|
+
const allModels = registry.getAll?.() ?? [];
|
|
457
|
+
model = allModels.find((m: any) => m.id === modelRef);
|
|
458
|
+
}
|
|
459
|
+
if (!model) return;
|
|
460
|
+
|
|
461
|
+
data.model = model;
|
|
462
|
+
try {
|
|
463
|
+
data.auth = await registry.getApiKeyAndHeaders(model);
|
|
464
|
+
} catch {
|
|
465
|
+
data.auth = { ok: false, error: "Auth resolution failed" };
|
|
466
|
+
}
|
|
467
|
+
});
|
|
468
|
+
|
|
469
|
+
pi.events.on("flow:get-available-models", (data: any) => {
|
|
470
|
+
const registry = getModelRegistry();
|
|
471
|
+
if (!registry) {
|
|
472
|
+
data.models = [];
|
|
473
|
+
return;
|
|
474
|
+
}
|
|
475
|
+
try {
|
|
476
|
+
const available = registry.getAvailable?.() ?? registry.getAll?.() ?? [];
|
|
477
|
+
data.models = available.map((m: any) => ({
|
|
478
|
+
provider: m.provider,
|
|
479
|
+
id: m.id,
|
|
480
|
+
name: m.name ?? m.id,
|
|
481
|
+
}));
|
|
482
|
+
} catch {
|
|
483
|
+
data.models = [];
|
|
484
|
+
}
|
|
485
|
+
});
|
|
486
|
+
|
|
487
|
+
// ── Session lifecycle ──────────────────────────────────────────────
|
|
488
|
+
|
|
489
|
+
pi.on("model_select", async (_event, ctx) => {
|
|
490
|
+
// Also capture modelRegistry here as a belt-and-suspenders in case
|
|
491
|
+
// session_start ran before activate() finished in some edge case.
|
|
492
|
+
if (!modelRegistryRef && ctx.modelRegistry) {
|
|
493
|
+
modelRegistryRef = ctx.modelRegistry;
|
|
494
|
+
}
|
|
495
|
+
if (ctx.model) {
|
|
496
|
+
currentSessionProvider = ctx.model.provider ?? "";
|
|
497
|
+
currentSessionModelId = ctx.model.id ?? "";
|
|
498
|
+
}
|
|
499
|
+
});
|
|
500
|
+
|
|
501
|
+
pi.on("session_start", async (_event, ctx) => {
|
|
502
|
+
// Capture the modelRegistry reference the first time we see it, then
|
|
503
|
+
// re-register already-registered providers so their model metadata gets
|
|
504
|
+
// enriched from pi's catalog (they were registered at activate() before
|
|
505
|
+
// any ctx was available, so they currently carry fallback defaults).
|
|
506
|
+
// See change: enrich-custom-provider-model-metadata.
|
|
507
|
+
if (!modelRegistryRef && ctx.modelRegistry) {
|
|
508
|
+
modelRegistryRef = ctx.modelRegistry;
|
|
509
|
+
if (lastRegistered.size > 0) {
|
|
510
|
+
// Force re-registration: clear snapshot so reloadProviders re-adds all
|
|
511
|
+
// entries (which will now probe the captured registry).
|
|
512
|
+
const names = Array.from(lastRegistered.keys());
|
|
513
|
+
lastRegistered.clear();
|
|
514
|
+
for (const name of names) {
|
|
515
|
+
const entry = providers[name];
|
|
516
|
+
if (entry) {
|
|
517
|
+
try {
|
|
518
|
+
await registerEntry(pi, name, entry);
|
|
519
|
+
} catch (err: any) {
|
|
520
|
+
console.error(`[dashboard] re-registerProvider("${name}") failed: ${err?.message ?? String(err)}`);
|
|
521
|
+
}
|
|
522
|
+
}
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
// If the session's currently-selected model belongs to one of the
|
|
526
|
+
// providers we just re-registered, re-apply it via pi.setModel() so
|
|
527
|
+
// the snapshot on agent.state.model picks up the enriched metadata
|
|
528
|
+
// (reasoning / contextWindow / cost). Without this, pi's session
|
|
529
|
+
// still holds the pre-enrichment descriptor with reasoning: false,
|
|
530
|
+
// causing setThinkingLevel to clamp to "off" even though the registry
|
|
531
|
+
// now has reasoning: true. See change: enrich-custom-provider-model-metadata.
|
|
532
|
+
const current = ctx.model as any;
|
|
533
|
+
if (current?.provider && current?.id && names.includes(current.provider)) {
|
|
534
|
+
try {
|
|
535
|
+
const refreshed = ctx.modelRegistry.find(current.provider, current.id);
|
|
536
|
+
if (refreshed && (pi as any).setModel) {
|
|
537
|
+
await (pi as any).setModel(refreshed);
|
|
538
|
+
}
|
|
539
|
+
} catch (err: any) {
|
|
540
|
+
console.error(`[dashboard] re-setModel after enrichment failed: ${err?.message ?? String(err)}`);
|
|
541
|
+
}
|
|
542
|
+
}
|
|
543
|
+
}
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
if (ctx.model) {
|
|
547
|
+
currentSessionProvider = ctx.model.provider ?? "";
|
|
548
|
+
currentSessionModelId = ctx.model.id ?? "";
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
// Warn about providers missing API keys
|
|
552
|
+
for (const [name, entry] of Object.entries(providers)) {
|
|
553
|
+
if (!hasApiKey(name, entry)) {
|
|
554
|
+
const hint = entry.apiKey.startsWith("$")
|
|
555
|
+
? `Set ${entry.apiKey}`
|
|
556
|
+
: "Check API key";
|
|
557
|
+
ctx.ui.notify(
|
|
558
|
+
`${name}: ${hint} or add "${name}" to ~/.pi/agent/auth.json`,
|
|
559
|
+
"warning",
|
|
560
|
+
);
|
|
561
|
+
}
|
|
562
|
+
}
|
|
563
|
+
});
|
|
564
|
+
}
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Auto-start logic for the dashboard server.
|
|
3
|
+
* Uses mDNS discovery first, falls back to health check, then auto-starts.
|
|
4
|
+
*/
|
|
5
|
+
import os from "node:os";
|
|
6
|
+
import path from "node:path";
|
|
7
|
+
|
|
8
|
+
export interface DiscoveredServer {
|
|
9
|
+
host: string;
|
|
10
|
+
port: number;
|
|
11
|
+
piPort: number;
|
|
12
|
+
isLocal: boolean;
|
|
13
|
+
source: "mdns" | "fallback";
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export interface AutoStartDeps {
|
|
17
|
+
discoverDashboard: (timeout?: number) => Promise<DiscoveredServer[]>;
|
|
18
|
+
isDashboardRunning: (port: number) => Promise<{ running: boolean; portConflict?: boolean }>;
|
|
19
|
+
launchServer: (config: any) => Promise<{ success: boolean; message: string }>;
|
|
20
|
+
notify: (message: string, level: "info" | "warning") => void;
|
|
21
|
+
/**
|
|
22
|
+
* Optional callback fired immediately BEFORE `launchServer(config)` is
|
|
23
|
+
* invoked. Used by TUI-aware callers (bridge extension) to show a
|
|
24
|
+
* "starting dashboard server" spinner. NOT fired during mDNS discovery
|
|
25
|
+
* or health-check phases — only when an actual server process is
|
|
26
|
+
* about to be spawned.
|
|
27
|
+
*/
|
|
28
|
+
onLaunchStart?: () => void;
|
|
29
|
+
/**
|
|
30
|
+
* Optional callback fired after `launchServer` resolves (success or
|
|
31
|
+
* failure), AND after the post-launch mDNS re-discovery + recheck.
|
|
32
|
+
* Passes the final success state so the caller can clear spinners.
|
|
33
|
+
*/
|
|
34
|
+
onLaunchEnd?: (success: boolean) => void;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export interface AutoStartResult {
|
|
38
|
+
/** The server to connect to (if found or launched) */
|
|
39
|
+
server?: { host: string; port: number; piPort: number };
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Discover or auto-start the dashboard server.
|
|
44
|
+
* Discovery chain: mDNS browse → health check fallback → auto-start.
|
|
45
|
+
* Returns the server to connect to.
|
|
46
|
+
*/
|
|
47
|
+
export async function autoStartServer(
|
|
48
|
+
config: { piPort: number; port: number; autoStart: boolean },
|
|
49
|
+
deps: AutoStartDeps,
|
|
50
|
+
): Promise<AutoStartResult> {
|
|
51
|
+
// 1. Try mDNS discovery (2s timeout)
|
|
52
|
+
try {
|
|
53
|
+
const servers = await deps.discoverDashboard(2000);
|
|
54
|
+
const local = servers.find(s => s.isLocal);
|
|
55
|
+
if (local) {
|
|
56
|
+
return { server: { host: local.host, port: local.port, piPort: local.piPort } };
|
|
57
|
+
}
|
|
58
|
+
// Remote servers exist but no local — fall through to health check
|
|
59
|
+
} catch {
|
|
60
|
+
// mDNS failed — fall through to health check
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
// 2. Fallback: health check on configured port
|
|
64
|
+
const status = await deps.isDashboardRunning(config.port);
|
|
65
|
+
if (status.running) {
|
|
66
|
+
return { server: { host: "localhost", port: config.port, piPort: config.piPort } };
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
if (!config.autoStart) return {};
|
|
70
|
+
|
|
71
|
+
if (status.portConflict) {
|
|
72
|
+
deps.notify(`Port ${config.port} is occupied by another service`, "warning");
|
|
73
|
+
return {};
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
// 3. Auto-start server
|
|
77
|
+
deps.onLaunchStart?.();
|
|
78
|
+
const result = await deps.launchServer(config);
|
|
79
|
+
if (result.success) {
|
|
80
|
+
deps.onLaunchEnd?.(true);
|
|
81
|
+
deps.notify(`🌐 Dashboard started at http://localhost:${config.port}`, "info");
|
|
82
|
+
|
|
83
|
+
// Wait for mDNS advertisement from the newly started server (up to 10s)
|
|
84
|
+
try {
|
|
85
|
+
const discovered = await deps.discoverDashboard(10000);
|
|
86
|
+
const local = discovered.find(s => s.isLocal);
|
|
87
|
+
if (local) {
|
|
88
|
+
return { server: { host: local.host, port: local.port, piPort: local.piPort } };
|
|
89
|
+
}
|
|
90
|
+
} catch {
|
|
91
|
+
// mDNS failed — use config defaults
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
return { server: { host: "localhost", port: config.port, piPort: config.piPort } };
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
// Another agent may have started the server concurrently — recheck before warning
|
|
98
|
+
const recheck = await deps.isDashboardRunning(config.port);
|
|
99
|
+
if (recheck.running) {
|
|
100
|
+
deps.onLaunchEnd?.(true);
|
|
101
|
+
return { server: { host: "localhost", port: config.port, piPort: config.piPort } };
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
// Surface the log path so users can inspect the crash output without having
|
|
105
|
+
// to know the convention. See change: fix-windows-server-parity.
|
|
106
|
+
deps.onLaunchEnd?.(false);
|
|
107
|
+
const logPath = path.join(os.homedir(), ".pi", "dashboard", "server.log");
|
|
108
|
+
deps.notify(
|
|
109
|
+
`Dashboard server failed to start: ${result.message}\nSee log: ${logPath}`,
|
|
110
|
+
"warning",
|
|
111
|
+
);
|
|
112
|
+
return {};
|
|
113
|
+
}
|