@blackbelt-technology/pi-agent-dashboard 0.6.0 → 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.
Files changed (105) hide show
  1. package/README.md +40 -38
  2. package/docs/architecture.md +148 -2
  3. package/package.json +6 -4
  4. package/packages/extension/package.json +4 -3
  5. package/packages/extension/src/AGENTS.md +1 -0
  6. package/packages/extension/src/__tests__/bridge-resume-disconnect.test.ts +333 -0
  7. package/packages/extension/src/__tests__/openspec-cli-shim.test.ts +145 -0
  8. package/packages/extension/src/__tests__/provider-register-native-models.test.ts +182 -0
  9. package/packages/extension/src/__tests__/provider-register-thinking-levels.test.ts +54 -1
  10. package/packages/extension/src/__tests__/single-derivation-guard.test.ts +39 -0
  11. package/packages/extension/src/bridge-context.ts +21 -0
  12. package/packages/extension/src/bridge.ts +41 -6
  13. package/packages/extension/src/openspec-cli-shim.ts +173 -0
  14. package/packages/extension/src/openspec-cli-shim.ts.AGENTS.md +7 -0
  15. package/packages/extension/src/provider-register.ts +180 -17
  16. package/packages/extension/src/provider-register.ts.AGENTS.md +1 -1
  17. package/packages/extension/src/session-sync.ts +9 -4
  18. package/packages/server/package.json +8 -8
  19. package/packages/server/src/__tests__/decorate-goals-spend.test.ts +79 -0
  20. package/packages/server/src/__tests__/embed-lifecycle-boot-smoke.test.ts +44 -0
  21. package/packages/server/src/__tests__/goal-routes.test.ts +62 -7
  22. package/packages/server/src/__tests__/goal-supervisor.test.ts +4 -4
  23. package/packages/server/src/__tests__/headless-pid-registry.test.ts +7 -3
  24. package/packages/server/src/__tests__/memory-event-store.test.ts +369 -13
  25. package/packages/server/src/__tests__/models-introspection-thinking-map.test.ts +67 -0
  26. package/packages/server/src/__tests__/pi-changelog-routes.test.ts +9 -2
  27. package/packages/server/src/__tests__/recovery-offer.test.ts +42 -7
  28. package/packages/server/src/__tests__/recovery-reattach-retraction.test.ts +188 -0
  29. package/packages/server/src/__tests__/session-tags-persistence.test.ts +29 -0
  30. package/packages/server/src/browser-handlers/AGENTS.md +1 -1
  31. package/packages/server/src/browser-handlers/__tests__/session-meta-handler.test.ts +98 -1
  32. package/packages/server/src/browser-handlers/handler-context.ts +24 -13
  33. package/packages/server/src/browser-handlers/session-action-handler.ts +12 -1
  34. package/packages/server/src/browser-handlers/session-meta-handler.ts +29 -0
  35. package/packages/server/src/embed-lifecycle/AGENTS.md +17 -0
  36. package/packages/server/src/embed-lifecycle/__tests__/caps.test.ts +129 -0
  37. package/packages/server/src/embed-lifecycle/__tests__/embed-lifecycle-controller.test.ts +84 -0
  38. package/packages/server/src/embed-lifecycle/__tests__/identity-key.test.ts +73 -0
  39. package/packages/server/src/embed-lifecycle/__tests__/idle-reaper.test.ts +173 -0
  40. package/packages/server/src/embed-lifecycle/__tests__/lifecycle-config.test.ts +26 -0
  41. package/packages/server/src/embed-lifecycle/__tests__/lifecycle-event-capture.test.ts +32 -0
  42. package/packages/server/src/embed-lifecycle/__tests__/lifecycle-marker-persistence.test.ts +106 -0
  43. package/packages/server/src/embed-lifecycle/__tests__/lifecycle-metrics.test.ts +39 -0
  44. package/packages/server/src/embed-lifecycle/__tests__/liveness-probe.test.ts +77 -0
  45. package/packages/server/src/embed-lifecycle/__tests__/quiescence.test.ts +175 -0
  46. package/packages/server/src/embed-lifecycle/__tests__/reclamation-soak.test.ts +77 -0
  47. package/packages/server/src/embed-lifecycle/__tests__/session-lifecycle-policy.test.ts +38 -0
  48. package/packages/server/src/embed-lifecycle/__tests__/visitor-session-registry.test.ts +140 -0
  49. package/packages/server/src/embed-lifecycle/caps.ts +88 -0
  50. package/packages/server/src/embed-lifecycle/cwd-allowlist.ts +50 -0
  51. package/packages/server/src/embed-lifecycle/embed-lifecycle-controller.ts +90 -0
  52. package/packages/server/src/embed-lifecycle/identity-key.ts +73 -0
  53. package/packages/server/src/embed-lifecycle/idle-reaper.ts +161 -0
  54. package/packages/server/src/embed-lifecycle/lifecycle-event-capture.ts +30 -0
  55. package/packages/server/src/embed-lifecycle/lifecycle-metrics.ts +70 -0
  56. package/packages/server/src/embed-lifecycle/liveness-probe.ts +123 -0
  57. package/packages/server/src/embed-lifecycle/quiescence.ts +159 -0
  58. package/packages/server/src/embed-lifecycle/session-lifecycle-policy.ts +31 -0
  59. package/packages/server/src/embed-lifecycle/visitor-session-registry.ts +178 -0
  60. package/packages/server/src/event-wiring.ts +20 -0
  61. package/packages/server/src/event-wiring.ts.AGENTS.md +1 -0
  62. package/packages/server/src/goal/AGENTS.md +1 -0
  63. package/packages/server/src/goal/decorate-goals-spend.ts +47 -0
  64. package/packages/server/src/goal/goal-supervisor.ts +5 -3
  65. package/packages/server/src/model-proxy/AGENTS.md +2 -2
  66. package/packages/server/src/model-proxy/__tests__/internal-registry-native-merge.test.ts +155 -0
  67. package/packages/server/src/model-proxy/__tests__/read-native-models.test.ts +92 -0
  68. package/packages/server/src/model-proxy/internal-registry.ts +49 -23
  69. package/packages/server/src/model-proxy/registry-singleton.ts +15 -9
  70. package/packages/server/src/pairing/browser-gateway.ts +40 -11
  71. package/packages/server/src/pairing/browser-gateway.ts.AGENTS.md +1 -1
  72. package/packages/server/src/persistence/memory-event-store.ts +369 -23
  73. package/packages/server/src/persistence/memory-event-store.ts.AGENTS.md +1 -1
  74. package/packages/server/src/routes/AGENTS.md +2 -2
  75. package/packages/server/src/routes/goal-routes.ts +14 -9
  76. package/packages/server/src/routes/models-introspection-routes.ts +10 -0
  77. package/packages/server/src/routes/system-routes.ts +16 -1
  78. package/packages/server/src/server.ts +216 -65
  79. package/packages/server/src/server.ts.AGENTS.md +1 -1
  80. package/packages/server/src/session/memory-session-manager.ts +4 -0
  81. package/packages/server/src/session/session-scanner.ts +9 -0
  82. package/packages/server/src/session/session-to-meta.ts +6 -0
  83. package/packages/server/src/spawn-process/headless-pid-registry.ts +14 -4
  84. package/packages/shared/package.json +1 -1
  85. package/packages/shared/src/AGENTS.md +5 -3
  86. package/packages/shared/src/__tests__/models-json-reader.test.ts +100 -0
  87. package/packages/shared/src/__tests__/nightly-workflow-contract.test.ts +125 -0
  88. package/packages/shared/src/__tests__/openspec-poller-1.6.0-compat.test.ts +112 -0
  89. package/packages/shared/src/__tests__/pnpm-migration-contract.test.ts +177 -0
  90. package/packages/shared/src/__tests__/publish-workflow-contract.test.ts +6 -3
  91. package/packages/shared/src/browser-protocol.ts +22 -0
  92. package/packages/shared/src/config.ts +70 -0
  93. package/packages/shared/src/dashboard-plugin/AGENTS.md +1 -1
  94. package/packages/shared/src/dashboard-plugin/slot-props.ts +9 -0
  95. package/packages/shared/src/dashboard-plugin/ui-primitives.ts +19 -0
  96. package/packages/shared/src/models-json-reader.ts +98 -0
  97. package/packages/shared/src/platform/AGENTS.md +1 -1
  98. package/packages/shared/src/platform/paths.ts +12 -0
  99. package/packages/shared/src/session-meta.ts +9 -0
  100. package/packages/shared/src/types.ts +52 -1
  101. package/docs/AGENTS.md +0 -47
  102. package/packages/extension/AGENTS.md +0 -7
  103. package/packages/server/AGENTS.md +0 -7
  104. package/packages/shared/AGENTS.md +0 -7
  105. package/scripts/AGENTS.md +0 -38
@@ -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;
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blackbelt-technology/pi-dashboard-server",
3
- "version": "0.6.0",
3
+ "version": "0.7.0",
4
4
  "description": "Dashboard server for monitoring and interacting with pi agent sessions",
5
5
  "type": "module",
6
6
  "repository": {
@@ -16,7 +16,7 @@
16
16
  },
17
17
  "piCompatibility": {
18
18
  "minimum": "0.78.0",
19
- "recommended": "0.78.0",
19
+ "recommended": "0.81.1",
20
20
  "maximum": null
21
21
  },
22
22
  "main": "src/cli.ts",
@@ -32,11 +32,11 @@
32
32
  "postinstall": "node scripts/fix-pty-permissions.cjs"
33
33
  },
34
34
  "dependencies": {
35
- "@blackbelt-technology/dashboard-plugin-runtime": "^0.6.0",
36
- "@blackbelt-technology/pi-dashboard-document-converter": "^0.6.0",
37
- "@blackbelt-technology/pi-dashboard-extension": "^0.6.0",
38
- "@blackbelt-technology/pi-dashboard-shared": "^0.6.0",
39
- "@earendil-works/pi-coding-agent": "^0.80.10",
35
+ "@blackbelt-technology/dashboard-plugin-runtime": "^0.7.0",
36
+ "@blackbelt-technology/pi-dashboard-document-converter": "^0.7.0",
37
+ "@blackbelt-technology/pi-dashboard-extension": "^0.7.0",
38
+ "@blackbelt-technology/pi-dashboard-shared": "^0.7.0",
39
+ "@earendil-works/pi-coding-agent": "^0.81.1",
40
40
  "chardet": "^2.1.0",
41
41
  "@fastify/compress": "^8.3.1",
42
42
  "@fastify/cookie": "^11.0.2",
@@ -45,7 +45,7 @@
45
45
  "@fastify/reply-from": "^12.6.1",
46
46
  "@fastify/static": "^8.0.0",
47
47
  "@fastify/websocket": "^11.0.0",
48
- "@fission-ai/openspec": "^1.3.0",
48
+ "@fission-ai/openspec": "^1.6.0",
49
49
  "asciidoctor": "^3.0.4",
50
50
  "bonjour-service": "^1.3.0",
51
51
  "diff": "^8.0.3",
@@ -0,0 +1,79 @@
1
+ /**
2
+ * Unit tests for the read-time spend-decoration choke point.
3
+ *
4
+ * Covers test-plan rows E5–E8 (sum / empty / costless / unresolvable), X1
5
+ * (throwing lookup), X4 (cold-start self-heal), and the purity invariant that
6
+ * underpins X2 (input records are never mutated).
7
+ *
8
+ * See change: fix-goal-detail-turns-and-spend.
9
+ */
10
+ import type { GoalRecord } from "@blackbelt-technology/pi-dashboard-shared/types.js";
11
+ import { describe, expect, it } from "vitest";
12
+ import { decorateGoalsWithSpend, type SpendSessionLookup } from "../goal/decorate-goals-spend.js";
13
+
14
+ function goal(over: Partial<GoalRecord> & { sessionIds: string[] }): GoalRecord {
15
+ return {
16
+ id: "g1",
17
+ cwd: "/repo",
18
+ objective: "Ship it",
19
+ criteria: [],
20
+ status: "pursuing",
21
+ createdAt: 1,
22
+ updatedAt: 1,
23
+ ...over,
24
+ };
25
+ }
26
+
27
+ /** Session lookup backed by a plain map of id → cost. */
28
+ function lookup(costs: Record<string, number | undefined>): SpendSessionLookup {
29
+ return { get: (sid) => (sid in costs ? { cost: costs[sid] } : undefined) };
30
+ }
31
+
32
+ describe("decorateGoalsWithSpend", () => {
33
+ it("E5: sums cost over linked sessions → 0.39", () => {
34
+ const out = decorateGoalsWithSpend([goal({ sessionIds: ["a", "b"] })], lookup({ a: 0.1, b: 0.29 }));
35
+ expect(out[0]!.totalSpendUsd).toBeCloseTo(0.39, 10);
36
+ });
37
+
38
+ it("E6: no sessions → 0", () => {
39
+ const out = decorateGoalsWithSpend([goal({ sessionIds: [] })], lookup({}));
40
+ expect(out[0]!.totalSpendUsd).toBe(0);
41
+ });
42
+
43
+ it("E7: session resolves with cost undefined → contributes 0", () => {
44
+ const out = decorateGoalsWithSpend([goal({ sessionIds: ["a", "b"] })], lookup({ a: 0.29, b: undefined }));
45
+ expect(out[0]!.totalSpendUsd).toBeCloseTo(0.29, 10);
46
+ });
47
+
48
+ it("E8: unresolvable id (get→undefined) → 0, no throw", () => {
49
+ const out = decorateGoalsWithSpend([goal({ sessionIds: ["missing"] })], lookup({}));
50
+ expect(out[0]!.totalSpendUsd).toBe(0);
51
+ });
52
+
53
+ it("X1: a throwing lookup for one sid contributes 0; others still sum", () => {
54
+ const sessions: SpendSessionLookup = {
55
+ get: (sid) => {
56
+ if (sid === "boom") throw new Error("lookup blew up");
57
+ return { cost: 0.29 };
58
+ },
59
+ };
60
+ const out = decorateGoalsWithSpend([goal({ sessionIds: ["good", "boom"] })], sessions);
61
+ expect(out[0]!.totalSpendUsd).toBeCloseTo(0.29, 10);
62
+ });
63
+
64
+ it("X4: cold-start self-heal — 0 before scan, 0.39 after", () => {
65
+ const g = goal({ sessionIds: ["a", "b"] });
66
+ const before = decorateGoalsWithSpend([g], lookup({ a: 0, b: 0 }));
67
+ expect(before[0]!.totalSpendUsd).toBe(0);
68
+ const after = decorateGoalsWithSpend([g], lookup({ a: 0.1, b: 0.29 }));
69
+ expect(after[0]!.totalSpendUsd).toBeCloseTo(0.39, 10);
70
+ });
71
+
72
+ it("purity: returns new objects and never mutates the input record", () => {
73
+ const input = goal({ sessionIds: ["a"] });
74
+ const out = decorateGoalsWithSpend([input], lookup({ a: 0.29 }));
75
+ expect(out[0]).not.toBe(input);
76
+ expect("totalSpendUsd" in input).toBe(false);
77
+ expect(input.totalSpendUsd).toBeUndefined();
78
+ });
79
+ });
@@ -0,0 +1,44 @@
1
+ /**
2
+ * Real-boot smoke: the full DashboardServer boots with the embed-lifecycle
3
+ * controller wired (reaper start/stop, /api/health snapshot) and the health
4
+ * endpoint exposes the `embedLifecycle` diagnostics field.
5
+ * See change: add-embed-session-lifecycle.
6
+ */
7
+ import { afterAll, beforeAll, describe, expect, it } from "vitest";
8
+ import { createTestServer, type TestServerHandle } from "../test-support/test-server.js";
9
+
10
+ describe("embed-lifecycle server boot smoke", () => {
11
+ let handle: TestServerHandle;
12
+
13
+ beforeAll(async () => {
14
+ handle = await createTestServer();
15
+ });
16
+ afterAll(async () => {
17
+ await handle?.stop();
18
+ });
19
+
20
+ it("boots with the lifecycle controller and exposes embedLifecycle on /api/health", async () => {
21
+ const res = await fetch(`http://127.0.0.1:${handle.httpPort}/api/health`);
22
+ expect(res.status).toBe(200);
23
+ const body = (await res.json()) as {
24
+ ok: boolean;
25
+ embedLifecycle?: {
26
+ activeEphemeral: number;
27
+ idleEphemeral: number;
28
+ reaped: Record<string, number>;
29
+ capacityRejections: number;
30
+ reuseHits: number;
31
+ reuseMisses: number;
32
+ };
33
+ };
34
+ expect(body.ok).toBe(true);
35
+ expect(body.embedLifecycle).toBeDefined();
36
+ // Fresh server: no ephemeral sessions, no reaps yet.
37
+ expect(body.embedLifecycle?.activeEphemeral).toBe(0);
38
+ expect(body.embedLifecycle?.reaped).toEqual({
39
+ idle: 0,
40
+ "stop-after-turn": 0,
41
+ phantom: 0,
42
+ });
43
+ });
44
+ });
@@ -7,18 +7,26 @@
7
7
  *
8
8
  * See change: add-goals-folder-page (tasks 1.2, 1.4).
9
9
  */
10
- import { describe, it, expect, beforeEach, afterEach } from "vitest";
11
- import Fastify, { type FastifyInstance } from "fastify";
10
+
11
+ import { createHash } from "node:crypto";
12
12
  import fs from "node:fs/promises";
13
13
  import os from "node:os";
14
14
  import path from "node:path";
15
- import { registerGoalRoutes } from "../routes/goal-routes.js";
15
+ import Fastify, { type FastifyInstance } from "fastify";
16
+ import { afterEach, beforeEach, describe, expect, it } from "vitest";
17
+ import { decorateGoalsWithSpend } from "../goal/decorate-goals-spend.js";
16
18
  import { createGoalStore, type GoalStore } from "../goal/goal-store.js";
19
+ import { registerGoalRoutes } from "../routes/goal-routes.js";
17
20
 
18
21
  const PASSTHRU_GUARD = async () => {};
19
22
 
20
- function makeSessionManager(cwd: string): any {
21
- return { listAll: () => [{ id: "s1", cwd, source: "tui" }] };
23
+ function makeSessionManager(cwd: string, costs: Record<string, number> = {}): any {
24
+ const ids = new Set(["s1", ...Object.keys(costs)]);
25
+ const sessions = [...ids].map((id) => ({ id, cwd, source: "tui", cost: costs[id] }));
26
+ return {
27
+ listAll: () => sessions,
28
+ get: (id: string) => sessions.find((s) => s.id === id),
29
+ };
22
30
  }
23
31
  function makePreferencesStore(): any {
24
32
  return { getPinnedDirectories: () => [] };
@@ -46,10 +54,10 @@ describe("goal REST routes", () => {
46
54
  await fs.rm(dataDir, { recursive: true, force: true });
47
55
  });
48
56
 
49
- async function setup(spawnGoalSession?: any) {
57
+ async function setup(spawnGoalSession?: any, sessionManager?: any) {
50
58
  fastify = Fastify();
51
59
  registerGoalRoutes(fastify, {
52
- sessionManager: makeSessionManager(cwd),
60
+ sessionManager: sessionManager ?? makeSessionManager(cwd),
53
61
  preferencesStore: makePreferencesStore(),
54
62
  networkGuard: PASSTHRU_GUARD,
55
63
  store,
@@ -235,6 +243,53 @@ describe("goal REST routes", () => {
235
243
  expect(spawnedFor).toBe(g.id);
236
244
  });
237
245
 
246
+ // See change: fix-goal-detail-turns-and-spend.
247
+ it("X3: GET record carries server-derived totalSpendUsd", async () => {
248
+ const sm = makeSessionManager(cwd, { s1: 0.29 });
249
+ await setup(undefined, sm);
250
+ const g = await store.create(cwd, { objective: "x" });
251
+ await store.linkSession(cwd, g.id, "s1");
252
+ const res = await fastify.inject({ method: "GET", url: `/api/folders/goals?${q()}` });
253
+ const body = JSON.parse(res.payload);
254
+ expect(body.data[0].totalSpendUsd).toBeCloseTo(0.29, 10);
255
+ });
256
+
257
+ it("X3: goals_update broadcast payload record carries totalSpendUsd", async () => {
258
+ const sm = makeSessionManager(cwd, { s1: 0.29 });
259
+ await setup(undefined, sm);
260
+ const g = await store.create(cwd, { objective: "x" });
261
+ await store.linkSession(cwd, g.id, "s1");
262
+ // Mirror the server.ts subscriber: decorate payload.goals before broadcast.
263
+ const seen = await new Promise<any[]>((resolve) => {
264
+ const unsub = store.subscribe((_cwd, payload) => {
265
+ unsub();
266
+ resolve(decorateGoalsWithSpend(payload.goals, sm));
267
+ });
268
+ void store.update(cwd, g.id, { objective: "x2" });
269
+ });
270
+ expect(seen.find((r) => r.id === g.id)?.totalSpendUsd).toBeCloseTo(0.29, 10);
271
+ });
272
+
273
+ it("X2: mutation response is decorated but persisted file has NO totalSpendUsd", async () => {
274
+ const sm = makeSessionManager(cwd, { s1: 0.29 });
275
+ await setup(undefined, sm);
276
+ const g = await store.create(cwd, { objective: "x" });
277
+ // Link via the route so the cache-aliased response path is exercised.
278
+ const res = await fastify.inject({
279
+ method: "POST",
280
+ url: `/api/folders/goals/${g.id}/sessions?${q()}`,
281
+ payload: { sessionId: "s1" },
282
+ });
283
+ expect(JSON.parse(res.payload).data.totalSpendUsd).toBeCloseTo(0.29, 10);
284
+ // Flush the debounced write, then inspect the on-disk record.
285
+ await new Promise((r) => setTimeout(r, 30));
286
+ const hash = createHash("sha256").update(cwd).digest("hex").slice(0, 12);
287
+ const raw = JSON.parse(await fs.readFile(path.join(dataDir, `${hash}.json`), "utf-8"));
288
+ const stored = raw.goals.find((r: any) => r.id === g.id);
289
+ expect(stored).toBeTruthy();
290
+ expect("totalSpendUsd" in stored).toBe(false);
291
+ });
292
+
238
293
  it("POST sessions spawn:true → 404 for unknown goal", async () => {
239
294
  await setup(async () => ({ success: true }));
240
295
  const res = await fastify.inject({
@@ -32,7 +32,7 @@ import {
32
32
  } from "../goal/goal-supervisor.js";
33
33
 
34
34
  interface FakeTimer {
35
- fn: () => void;
35
+ fn: () => void | Promise<void>;
36
36
  ms: number;
37
37
  fired: boolean;
38
38
  }
@@ -89,11 +89,11 @@ describe("goal-supervisor", () => {
89
89
  for (const t of timers) {
90
90
  if (!t.fired) {
91
91
  t.fired = true;
92
- t.fn();
92
+ // Await the returned performSpawn promise so real store I/O settles
93
+ // deterministically (no fixed-delay race on loaded CI runners).
94
+ await t.fn();
93
95
  }
94
96
  }
95
- // let the async performSpawn chain settle (real store I/O)
96
- await new Promise((r) => setTimeout(r, 10));
97
97
  }
98
98
 
99
99
  async function death(sessionId: string): Promise<void> {
@@ -458,9 +458,11 @@ describe("HeadlessPidRegistry: keeper mode", () => {
458
458
  expect(ok).toBe(true);
459
459
  });
460
460
 
461
- it("cleanupKeeperOrphans no-op when no keeper writer", async () => {
461
+ it("cleanupKeeperOrphans no-op (empty live set) when no keeper writer", async () => {
462
462
  const registry = createHeadlessPidRegistry({ pidFilePath: join(makeTempDir(), "pids.json") });
463
- await expect(registry.cleanupKeeperOrphans()).resolves.toBeUndefined();
463
+ // Returns the live keeper sessionIds; empty with no writer.
464
+ // See change: fix-recovery-offer-bridge-liveness-gate.
465
+ await expect(registry.cleanupKeeperOrphans()).resolves.toEqual([]);
464
466
  });
465
467
 
466
468
  it("persist round-trips keeper fields so linkByPid via piPid works after restart", async () => {
@@ -546,7 +548,9 @@ describe("HeadlessPidRegistry: keeper mode", () => {
546
548
  // Pre-existing entry with the same PID (would happen after
547
549
  // cleanupOrphans reclaim of a long-lived keeper from disk).
548
550
  registry.register(4242, "/proj", mockProcess());
549
- await registry.cleanupKeeperOrphans();
551
+ // Returns the live keeper sessionIds so cold-start recovery can gate on
552
+ // them. See change: fix-recovery-offer-bridge-liveness-gate.
553
+ await expect(registry.cleanupKeeperOrphans()).resolves.toEqual(["transport-1"]);
550
554
  // Verify writer was consulted and entry got keeper info via
551
555
  // observable side-effect: writeRpc now succeeds for that entry.
552
556
  registry.linkSession("S_attached", "/proj");