@blackbelt-technology/pi-dashboard-extension 0.6.1 → 0.7.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.
@@ -26,9 +26,10 @@
26
26
  import { existsSync, readFileSync } from "node:fs";
27
27
  import { homedir } from "node:os";
28
28
  import { join } from "node:path";
29
+ import { flattenModelsJson, type NativeModelEntry } from "@blackbelt-technology/pi-dashboard-shared/models-json-reader.js";
29
30
  import type { ProviderInfo } from "@blackbelt-technology/pi-dashboard-shared/types.js";
30
31
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
31
- import { lookupRole, loadRoleConfig } from "./role-manager.js";
32
+ import { loadRoleConfig, lookupRole } from "./role-manager.js";
32
33
 
33
34
  // -- Types ----------------------------------------------------------------
34
35
 
@@ -53,6 +54,15 @@ export interface ModelMetadata {
53
54
  * verified capability). See change: enrich-model-selector-capabilities-favorites.
54
55
  */
55
56
  metadataSource: "catalog" | "fallback";
57
+ /**
58
+ * Native per-model thinking-level override table + opaque request-formatting
59
+ * hints, present only when the metadata came from the user-authored native
60
+ * `~/.pi/agent/models.json`. Carried through `pi.registerProvider` so pi's
61
+ * clamp + request formatting operate on true native capabilities.
62
+ * See change: honor-native-models-json-metadata.
63
+ */
64
+ thinkingLevelMap?: Record<string, unknown>;
65
+ compat?: Record<string, unknown>;
56
66
  }
57
67
 
58
68
  /**
@@ -181,6 +191,101 @@ export function enrichModelMetadata(
181
191
  };
182
192
  }
183
193
 
194
+ // -- Native models.json metadata (user-authored) --------------------------
195
+ //
196
+ // A native Pi install can attach rich capability metadata to a custom-provider
197
+ // model in `~/.pi/agent/models.json` (`providers.<name>.models[]` with
198
+ // `contextWindow`, `maxTokens`, `reasoning`, `thinkingLevelMap`, `compat`,
199
+ // `input`, `cost`). That native metadata is the AUTHORITY for a matching
200
+ // `provider/id` — it wins over the api-typed enrichment fallback so the session
201
+ // and the web thinking-level selector see the true capabilities.
202
+ // See change: honor-native-models-json-metadata.
203
+
204
+ function nativeModelsPath(): string {
205
+ return join(homedir(), ".pi", "agent", "models.json");
206
+ }
207
+
208
+ /**
209
+ * Read + flatten the user-authored `~/.pi/agent/models.json` via the shared
210
+ * reader. Read-only and defensive: a missing/invalid file yields `[]` (a syntax
211
+ * error is warned, not thrown), so the enrichment fallback chain still applies.
212
+ */
213
+ function loadNativeModels(): NativeModelEntry[] {
214
+ const path = nativeModelsPath();
215
+ if (!existsSync(path)) return [];
216
+ let raw: unknown;
217
+ try {
218
+ raw = JSON.parse(readFileSync(path, "utf-8"));
219
+ } catch (err: any) {
220
+ console.warn(`[dashboard] models.json parse failed: ${err?.message ?? String(err)}`);
221
+ return [];
222
+ }
223
+ return flattenModelsJson(raw);
224
+ }
225
+
226
+ /** Turn a native `models.json` entry into `ModelMetadata`, filling gaps with api-typed floors. */
227
+ function metadataFromNative(native: NativeModelEntry, api?: string): ModelMetadata {
228
+ const resolvedApi = api && api in FALLBACK_DEFAULTS ? api : "openai-completions";
229
+ const fb = FALLBACK_DEFAULTS[resolvedApi] ?? FALLBACK_DEFAULTS["openai-completions"];
230
+ return {
231
+ contextWindow: native.contextWindow ?? fb.contextWindow,
232
+ maxTokens: native.maxTokens ?? fb.maxTokens,
233
+ reasoning: native.reasoning ?? fb.reasoning,
234
+ cost: native.cost
235
+ ? {
236
+ input: native.cost.input,
237
+ output: native.cost.output,
238
+ cacheRead: native.cost.cacheRead ?? 0,
239
+ cacheWrite: native.cost.cacheWrite ?? 0,
240
+ }
241
+ : { ...fb.cost },
242
+ input: (native.input as InputModality[] | undefined) ?? [...DEFAULT_INPUT],
243
+ metadataSource: "catalog",
244
+ ...(native.thinkingLevelMap ? { thinkingLevelMap: native.thinkingLevelMap } : {}),
245
+ ...(native.compat ? { compat: native.compat } : {}),
246
+ };
247
+ }
248
+
249
+ /**
250
+ * Resolve a discovered/authored model id to metadata in precedence order,
251
+ * first hit wins: (1) the native `models.json` entry for `name/id`; (2) the
252
+ * session registry's own `find(name, id)` for the custom provider name; (3) the
253
+ * api-typed `enrichModelMetadata` fallback (which itself probes built-in
254
+ * candidate catalogs). Only path 1 supplies `thinkingLevelMap`/`compat`.
255
+ * See change: honor-native-models-json-metadata (D-E1).
256
+ */
257
+ function resolveMetadata(
258
+ name: string,
259
+ id: string,
260
+ api: string | undefined,
261
+ probe: CatalogProbe | null,
262
+ native: NativeModelEntry | undefined,
263
+ ): ModelMetadata {
264
+ // Path 1: native user-authored models.json.
265
+ if (native) return metadataFromNative(native, api);
266
+ // Path 2: the session registry's own entry for the custom provider name.
267
+ if (probe) {
268
+ let hit: ReturnType<CatalogProbe> | undefined;
269
+ try {
270
+ hit = probe(name, id);
271
+ } catch {
272
+ hit = undefined;
273
+ }
274
+ if (hit) {
275
+ return {
276
+ contextWindow: hit.contextWindow,
277
+ maxTokens: hit.maxTokens,
278
+ reasoning: hit.reasoning,
279
+ cost: hit.cost,
280
+ input: [...hit.input] as InputModality[],
281
+ metadataSource: "catalog",
282
+ };
283
+ }
284
+ }
285
+ // Path 3: api-typed enrichment fallback (built-in candidate probe → floors).
286
+ return enrichModelMetadata(id, api, probe);
287
+ }
288
+
184
289
  // -- Config path ----------------------------------------------------------
185
290
 
186
291
  // Resolved lazily so HOME can be changed in tests.
@@ -199,8 +304,10 @@ const lastRegistered = new Map<string, ProviderEntry>();
199
304
  // See change: enrich-model-selector-capabilities-favorites.
200
305
  const enrichmentSource = new Map<string, "catalog" | "fallback">();
201
306
 
202
- // Canonical thinking-level order pi uses (EXTENDED_THINKING_LEVELS).
203
- const EXTENDED_THINKING_LEVELS = ["off", "minimal", "low", "medium", "high", "xhigh"] as const;
307
+ // Canonical thinking-level order. Extends pi 0.75.5's EXTENDED_THINKING_LEVELS
308
+ // (off..xhigh) with the opt-in, runtime-gated `max` tier (reachable on newer
309
+ // session runtimes, e.g. pi 0.80.10). See change: honor-native-models-json-metadata.
310
+ const EXTENDED_THINKING_LEVELS = ["off", "minimal", "low", "medium", "high", "xhigh", "max"] as const;
204
311
 
205
312
  /**
206
313
  * Mirror of pi's `getSupportedThinkingLevels` (from @earendil-works/pi-ai) —
@@ -216,19 +323,43 @@ const EXTENDED_THINKING_LEVELS = ["off", "minimal", "low", "medium", "high", "xh
216
323
  * `xhigh` is supported only when declared with a non-null entry.
217
324
  * See change: fix-thinking-level-supported-projection.
218
325
  */
219
- function deriveSupportedThinkingLevels(
326
+ export function deriveSupportedThinkingLevels(
220
327
  reasoning: boolean,
221
328
  thinkingLevelMap: Record<string, unknown> | null | undefined,
329
+ maxSupported: boolean,
222
330
  ): string[] {
223
331
  if (!reasoning) return ["off"];
224
332
  return EXTENDED_THINKING_LEVELS.filter((level) => {
225
333
  const mapped = thinkingLevelMap?.[level];
226
334
  if (mapped === null) return false;
227
335
  if (level === "xhigh") return mapped !== undefined;
336
+ // `max` is fail-CLOSED: opt-in (declared non-null) AND the session runtime
337
+ // must advertise `max`. Without this explicit branch, appending `max` to
338
+ // the list would fail OPEN (`undefined !== null` is true).
339
+ if (level === "max") return maxSupported && mapped != null;
228
340
  return true;
229
341
  });
230
342
  }
231
343
 
344
+ // Whether the SESSION's pi runtime advertises `max` in its canonical
345
+ // thinking-level set. Probed lazily from the runtime's own
346
+ // `getSupportedThinkingLevels` (pi 0.75.5 has no `max`; 0.80.10 does). Fails
347
+ // CLOSED (false) when the runtime helper is unavailable or the probe throws.
348
+ // See change: honor-native-models-json-metadata (D-E3 / §3b.1).
349
+ let _maxRuntimeSupported: boolean | null = null;
350
+ function getMaxSupported(): boolean {
351
+ if (_maxRuntimeSupported !== null) return _maxRuntimeSupported;
352
+ const fn = _piAiModule?.getSupportedThinkingLevels;
353
+ if (typeof fn !== "function") return false; // not loaded yet — fail closed, don't cache
354
+ try {
355
+ const levels = fn({ reasoning: true, thinkingLevelMap: { max: "max" } });
356
+ _maxRuntimeSupported = Array.isArray(levels) && levels.includes("max");
357
+ } catch {
358
+ _maxRuntimeSupported = false;
359
+ }
360
+ return _maxRuntimeSupported;
361
+ }
362
+
232
363
  /**
233
364
  * Build a `ModelInfo` wire object from a pi registry `Model`, deriving the
234
365
  * `vision` flag from `input` and resolving `metadataSource` from the
@@ -258,7 +389,7 @@ export function toModelInfo(m: any): {
258
389
  typeof m?.reasoning === "boolean" ||
259
390
  (m?.thinkingLevelMap != null && typeof m.thinkingLevelMap === "object");
260
391
  const supportedThinkingLevels = hasThinkingMetadata
261
- ? deriveSupportedThinkingLevels(m?.reasoning === true, m?.thinkingLevelMap)
392
+ ? deriveSupportedThinkingLevels(m?.reasoning === true, m?.thinkingLevelMap, getMaxSupported())
262
393
  : undefined;
263
394
  return {
264
395
  provider,
@@ -422,6 +553,14 @@ export function getCustomProviderNames(): Set<string> {
422
553
  type PiAiHelpers = {
423
554
  findEnvKeys?: (id: string) => string[] | undefined;
424
555
  getEnvApiKey?: (id: string) => string | undefined;
556
+ /**
557
+ * The session runtime's own thinking-level clamp rule. Probed to detect
558
+ * whether this pi advertises `max` in its canonical set. See getMaxSupported.
559
+ */
560
+ getSupportedThinkingLevels?: (model: {
561
+ reasoning?: boolean;
562
+ thinkingLevelMap?: Record<string, unknown>;
563
+ }) => string[];
425
564
  };
426
565
 
427
566
  export function _buildProviderCatalogue(
@@ -511,7 +650,11 @@ async function loadPiAi(): Promise<PiAiHelpers> {
511
650
  _piAiLoadAttempted = true;
512
651
  try {
513
652
  const mod: any = await import("@earendil-works/pi-ai");
514
- _piAiModule = { findEnvKeys: mod.findEnvKeys, getEnvApiKey: mod.getEnvApiKey };
653
+ _piAiModule = {
654
+ findEnvKeys: mod.findEnvKeys,
655
+ getEnvApiKey: mod.getEnvApiKey,
656
+ getSupportedThinkingLevels: mod.getSupportedThinkingLevels,
657
+ };
515
658
  return _piAiModule;
516
659
  } catch {
517
660
  return {};
@@ -624,25 +767,45 @@ async function registerEntry(pi: ExtensionAPI, name: string, entry: ProviderEntr
624
767
 
625
768
  const discovered = await discoverModels(entry.baseUrl, entry.apiKey);
626
769
 
627
- // Metadata (contextWindow, maxTokens, reasoning, cost, input) is resolved
628
- // via pi's `modelRegistry.find(provider, id)` when the registry is
629
- // reachable, with api-appropriate fallbacks otherwise — the previous
630
- // hardcoded 200k / 16k / $0 / no-reasoning was silently wrong for
770
+ // Native user-authored `~/.pi/agent/models.json` entries for THIS provider
771
+ // (read-only). These are the capability AUTHORITY — native metadata wins over
772
+ // the api-typed enrichment fallback for a matching id. See change:
773
+ // honor-native-models-json-metadata.
774
+ const nativeForProvider = new Map<string, NativeModelEntry>();
775
+ for (const e of loadNativeModels()) {
776
+ if (e.provider === name) nativeForProvider.set(e.id, e);
777
+ }
778
+
779
+ // Metadata precedence per id: native models.json → registry probe
780
+ // (`find(provider, id)`) → api-typed `enrichModelMetadata` fallback. The
781
+ // former hardcoded 200k / 16k / $0 / no-reasoning was silently wrong for
631
782
  // Opus 4.6+/Sonnet 4.6+/GPT-5/Gemini-2.x proxied via OpenAI-compatible
632
- // endpoints. See enrichModelMetadata above, and change:
633
- // enrich-custom-provider-model-metadata.
783
+ // endpoints. See resolveMetadata above, and changes:
784
+ // enrich-custom-provider-model-metadata, honor-native-models-json-metadata.
634
785
  const registry = getModelRegistry();
635
786
  const probe: CatalogProbe | null =
636
787
  registry && typeof registry.find === "function"
637
788
  ? (provider, modelId) => registry.find(provider, modelId) ?? null
638
789
  : null;
639
790
 
640
- const models = discovered.map((m) => {
641
- const meta = enrichModelMetadata(m.id, entry.api, probe);
791
+ // Register the UNION of discovered ids and user-authored native ids, so a
792
+ // model authored under `providers.<name>.models[]` but absent from
793
+ // `/v1/models` (or when `/v1/models` is unreachable) still reaches the
794
+ // session and the web UI — matching the server path (AC5).
795
+ const unionIds: string[] = [];
796
+ const seenIds = new Set<string>();
797
+ for (const id of [...discovered.map((d) => d.id), ...nativeForProvider.keys()]) {
798
+ if (seenIds.has(id)) continue;
799
+ seenIds.add(id);
800
+ unionIds.push(id);
801
+ }
802
+
803
+ const models = unionIds.map((id) => {
804
+ const meta = resolveMetadata(name, id, entry.api, probe, nativeForProvider.get(id));
642
805
  // Record enrichment confidence so models_list push sites can flag
643
806
  // assumed-vs-verified capabilities. Keyed by the registered provider name.
644
- enrichmentSource.set(`${name}/${m.id}`, meta.metadataSource);
645
- return { id: m.id, name: m.id, ...meta };
807
+ enrichmentSource.set(`${name}/${id}`, meta.metadataSource);
808
+ return { id, name: id, ...meta };
646
809
  });
647
810
 
648
811
  pi.registerProvider(name, {
@@ -655,7 +818,7 @@ async function registerEntry(pi: ExtensionAPI, name: string, entry: ProviderEntr
655
818
  // Notify bridge directly (same package — no cross-package event needed)
656
819
  onProvidersChanged?.();
657
820
 
658
- return discovered.length;
821
+ return models.length;
659
822
  }
660
823
 
661
824
  /**
@@ -1,3 +1,3 @@
1
1
  # provider-register.ts — index
2
2
 
3
- Register custom LLM providers + auto-discovered models from `~/.pi/agent/providers.json`. Exports `activate`, `buildProviderCatalogue`, `_buildProviderCatalogue`, `reloadProviders`, `onProviderChanged`, `enrichModelMetadata`, `toModelInfo`, `getModelDisplayName`, `getSessionInfo`, `getCustomProviderNames`, `toRegisterApiKey`, `ModelMetadata`, `CatalogProbe`. Implements `model:resolve` handler (`@role` via `lookupRole()`, `provider/model[:thinking]`, bare id). See change: add-agent-role-model-tools — `getModelRegistry()` sources ONLY the `ctx.modelRegistry`-captured ref (dead `pi.modelRegistry` cast removed); `flow:resolve-model` alias DELETED; `getCustomProviderNames()` added for `list_models` custom flag. See change: fix-thinking-level-supported-projection — `toModelInfo` drops allowlist treatment of `thinkingLevelMap`. Derives `supportedThinkingLevels` via local `deriveSupportedThinkingLevels(reasoning, thinkingLevelMap)` mirroring pi `getSupportedThinkingLevels` verbatim. `thinkingLevelMap` = sparse override table, not allowlist: unmentioned level stays supported, `null` disables that level, `xhigh` supported only when declared non-null. Non-reasoning model → `["off"]`. Reasoning + no map → `[off,minimal,low,medium,high]` (xhigh excluded, needs explicit entry). Field emitted only when model carries thinking metadata (reasoning flag present OR thinkingLevelMap); else undefined so client shows all six. Rule inlined, NOT imported from `@earendil-works/pi-ai`: pi-ai `.d.ts` re-exports via `.ts` extensions (`export * from "./models.ts"`) repo tsconfig (no `allowImportingTsExtensions`) cannot resolve; main entry gives TS2305, `/compat` absent in pinned 0.75.5 gives TS2307.
3
+ Register custom LLM providers + auto-discovered models from `~/.pi/agent/providers.json`. Exports `activate`, `buildProviderCatalogue`, `_buildProviderCatalogue`, `reloadProviders`, `onProviderChanged`, `enrichModelMetadata`, `toModelInfo`, `getModelDisplayName`, `getSessionInfo`, `getCustomProviderNames`, `toRegisterApiKey`, `ModelMetadata`, `CatalogProbe`. Implements `model:resolve` handler (`@role` via `lookupRole()`, `provider/model[:thinking]`, bare id). See change: add-agent-role-model-tools — `getModelRegistry()` sources ONLY the `ctx.modelRegistry`-captured ref (dead `pi.modelRegistry` cast removed); `flow:resolve-model` alias DELETED; `getCustomProviderNames()` added for `list_models` custom flag. See change: fix-thinking-level-supported-projection — `toModelInfo` drops allowlist treatment of `thinkingLevelMap`. Derives `supportedThinkingLevels` via local `deriveSupportedThinkingLevels(reasoning, thinkingLevelMap)` mirroring pi `getSupportedThinkingLevels` verbatim. `thinkingLevelMap` = sparse override table, not allowlist: unmentioned level stays supported, `null` disables that level, `xhigh` supported only when declared non-null. Non-reasoning model → `["off"]`. Reasoning + no map → `[off,minimal,low,medium,high]` (xhigh excluded, needs explicit entry). Field emitted only when model carries thinking metadata (reasoning flag present OR thinkingLevelMap); else undefined so client shows all six. Rule inlined, NOT imported from `@earendil-works/pi-ai`: pi-ai `.d.ts` re-exports via `.ts` extensions (`export * from "./models.ts"`) repo tsconfig (no `allowImportingTsExtensions`) cannot resolve; main entry gives TS2305, `/compat` absent in pinned 0.75.5 gives TS2307. See change: honor-native-models-json-metadata — `registerEntry` registers the UNION of `/v1/models` ids + user-authored `providers.<name>.models[]` ids; per-id metadata precedence native `models.json` (`loadNativeModels`→shared `flattenModelsJson`) → registry `probe(name,id)` → `enrichModelMetadata`; native `thinkingLevelMap`/`compat` spread through `pi.registerProvider` + carried on `ModelMetadata`. `deriveSupportedThinkingLevels` gains `maxSupported` param + explicit fail-CLOSED `max` branch (`maxSupported && map.max != null`); canonical list extended to `off..xhigh,max`. `getMaxSupported()` probes the SESSION runtime's own `getSupportedThinkingLevels` (0.75.5 has no `max`; 0.80.10 does), fail-closed. `deriveSupportedThinkingLevels` exported for the E11 synthetic-table test. `toModelInfo` stays a hard whitelist — never emits `compat`/`apiKey`. Server derives NO levels (D-X1: one derivation here).
@@ -10,7 +10,7 @@ import { replayEntriesAsEvents } from "@blackbelt-technology/pi-dashboard-shared
10
10
  import type { FlowInfo } from "@blackbelt-technology/pi-dashboard-shared/types.js";
11
11
  import * as minimatchNS from "minimatch";
12
12
  import type { BridgeContext } from "./bridge-context.js";
13
- import { extractFirstMessage, filterHiddenCommands, getCurrentModelString } from "./bridge-context.js";
13
+ import { extractFirstMessage, filterHiddenCommands, getCurrentModelString, safeCwd } from "./bridge-context.js";
14
14
  import { buildProviderCatalogue, toModelInfo } from "./provider-register.js";
15
15
  import { detectSessionSource } from "./source-detector.js";
16
16
  import { detectIsGitRepo, gatherGitInfo } from "./vcs-info.js";
@@ -226,10 +226,15 @@ export function handleSessionChange(
226
226
  // dashboardSpawned from the capture-once boolean (token already scrubbed).
227
227
  // See change: fix-spawn-token-env-leak.
228
228
  const dashboardSpawned = bc.dashboardSpawned;
229
+ // ctx.cwd is a guarded getter that throws once the session is replaced
230
+ // (new/fork/resume). Reading it un-guarded here would abort session_start
231
+ // before connection.connect() runs — the #393 permanent disconnect.
232
+ // See change: fix-bridge-resume-disconnect.
233
+ const cwd = safeCwd(ctx);
229
234
  bc.connection.send({
230
235
  type: "session_register",
231
236
  sessionId: bc.sessionId,
232
- cwd: ctx.cwd,
237
+ cwd,
233
238
  name: bc.lastSessionName || undefined,
234
239
  source: detectSessionSource(bc.cachedHasUI, bc.lastSessionFile),
235
240
  model: bc.lastModel,
@@ -242,14 +247,14 @@ export function handleSessionChange(
242
247
  pid: process.pid,
243
248
  registerReason: "spawn",
244
249
  // See change: gate-session-worktree-button-on-git.
245
- isGitRepo: detectIsGitRepo(ctx.cwd),
250
+ isGitRepo: detectIsGitRepo(cwd),
246
251
  });
247
252
 
248
253
  replaySessionEntries(bc);
249
254
  bc.connection.send({ type: "replay_complete", sessionId: bc.sessionId });
250
255
 
251
256
  // Send git info
252
- const gitInfo = gatherGitInfo(ctx.cwd);
257
+ const gitInfo = gatherGitInfo(cwd);
253
258
  if (gitInfo) {
254
259
  bc.lastGitBranch = gitInfo.gitBranch;
255
260
  bc.lastGitPrNumber = gitInfo.gitPrNumber;