@blackbelt-technology/pi-agent-dashboard 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.
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
@@ -141,14 +141,24 @@ function isImageBlock(obj: object): boolean {
141
141
  const SKILL_ENVELOPE_RE =
142
142
  /^(<skill name="[^"]+" location="[^"]+">\n)([\s\S]*?)(\n<\/skill>)((?:\n\n[\s\S]+)?)$/;
143
143
 
144
- /** Cap a string to `maxSize`, appending a truncation marker when trimmed. */
145
- function capString(s: string, maxSize: number): string {
144
+ /**
145
+ * Cap a string to `maxSize`, keeping BOTH its head and tail when trimmed.
146
+ * The generic branch keeps `floor(maxSize/2)` head + the remaining tail joined
147
+ * by a `\n…[N chars hidden]…\n` marker (N = original length − kept) — a 50/50
148
+ * split, the safe universal across tool outputs and errors. Exported so the
149
+ * subagent reducer can cap individual entry leaves.
150
+ * See change: head-tail-truncate-subagent-event-timeline (D2).
151
+ */
152
+ export function capString(s: string, maxSize: number): string {
146
153
  if (s.length <= maxSize) return s;
147
154
  // Skill invocation envelope: naive mid-string truncation would sever the
148
155
  // closing </skill> tag, making the client's parseSkillBlock return null —
149
156
  // the message then renders as a wall of raw pseudo-HTML (or nothing).
150
157
  // Truncate the BODY only, keeping header + closing tag + trailing args
151
- // intact so the envelope stays well-formed and parseable.
158
+ // intact so the envelope stays well-formed and parseable. This branch stays
159
+ // HEAD-ONLY on the body: head+tail on a skill body risks the client
160
+ // parseSkillBlock contract, and the branch already bounds the body while
161
+ // keeping the closing tag.
152
162
  // See change: bound-subagent-event-serialization (skill regression fix).
153
163
  const skill = s.match(SKILL_ENVELOPE_RE);
154
164
  if (skill) {
@@ -160,7 +170,10 @@ function capString(s: string, maxSize: number): string {
160
170
  }
161
171
  return s; // over maxSize only due to envelope overhead — leave intact
162
172
  }
163
- return `${s.slice(0, maxSize)}\n…[truncated]`;
173
+ const head = Math.floor(maxSize / 2);
174
+ const tail = maxSize - head;
175
+ const hidden = s.length - maxSize;
176
+ return `${s.slice(0, head)}\n…[${hidden} chars hidden]…\n${s.slice(s.length - tail)}`;
164
177
  }
165
178
 
166
179
  /**
@@ -221,14 +234,57 @@ function truncateStrings(obj: unknown, maxSize: number, depth = 0): unknown {
221
234
  return obj;
222
235
  }
223
236
 
237
+ /**
238
+ * Byte-accurate JSON-serialized length of a string (UTF-8 width + escape
239
+ * expansion), INCLUDING the two surrounding quotes. Only called on strings
240
+ * whose code-unit length is already known to be within the remaining budget
241
+ * (the caller short-circuits huge strings via the code-unit lower bound), so
242
+ * this scan is bounded by `cap`, never by the raw payload size.
243
+ * See change: head-tail-truncate-subagent-event-timeline (D8).
244
+ */
245
+ function jsonStringByteSize(s: string): number {
246
+ let n = 2; // surrounding quotes
247
+ for (let i = 0; i < s.length; i++) {
248
+ const c = s.charCodeAt(i);
249
+ if (c === 0x22 || c === 0x5c) {
250
+ n += 2; // \" or \\
251
+ } else if (c < 0x20) {
252
+ // \b \t \n \f \r escape to 2 chars; other control chars to \u00XX (6).
253
+ n += c === 0x08 || c === 0x09 || c === 0x0a || c === 0x0c || c === 0x0d ? 2 : 6;
254
+ } else if (c < 0x80) {
255
+ n += 1;
256
+ } else if (c < 0x800) {
257
+ n += 2;
258
+ } else if (c >= 0xd800 && c <= 0xdbff) {
259
+ // High surrogate: a valid pair (one 4-byte UTF-8 sequence) ONLY when a low
260
+ // surrogate follows; otherwise ES2019+ JSON.stringify escapes the lone
261
+ // surrogate as \uXXXX (6 bytes) — count 6 so we never undercount.
262
+ const next = i + 1 < s.length ? s.charCodeAt(i + 1) : 0;
263
+ if (next >= 0xdc00 && next <= 0xdfff) {
264
+ n += 4;
265
+ i++;
266
+ } else {
267
+ n += 6;
268
+ }
269
+ } else if (c >= 0xdc00 && c <= 0xdfff) {
270
+ n += 6; // lone low surrogate → \uXXXX
271
+ } else {
272
+ n += 3;
273
+ }
274
+ }
275
+ return n;
276
+ }
277
+
224
278
  /**
225
279
  * Bounded-cost check: does `value` serialize to more than `cap` bytes?
226
280
  * Early-exits the moment the running estimate crosses `cap`, so it NEVER
227
281
  * materializes the full serialization (that allocation is exactly the OOM we
228
282
  * are guarding against). Worst-case cost is O(cap), not O(payload).
229
- * The estimate approximates JSON byte length (ignores escape expansion); it is
230
- * a guard threshold, not an exact size. See change:
231
- * bound-subagent-event-serialization.
283
+ * The walk is BYTE-ACCURATE: each string counts its actual JSON byte length
284
+ * (UTF-8 + escapes) and a base64 image `data` counts at its REAL size, so the
285
+ * ceiling holds in actual bytes for escape/CJK/image-heavy input. A huge string
286
+ * is short-circuited via its code-unit lower bound (UTF-8 bytes ≥ UTF-16 units)
287
+ * so it is never scanned. See change: head-tail-truncate-subagent-event-timeline (D8).
232
288
  */
233
289
  interface SizeWalk {
234
290
  total: number;
@@ -255,15 +311,14 @@ function walkObjectSize(obj: Record<string, unknown>, w: SizeWalk): boolean {
255
311
  // pasted image (> cap base64) collapses to the {__truncated} placeholder and
256
312
  // vanishes from chat. Count a small constant instead of the raw bytes.
257
313
  // See change: bound-subagent-event-serialization (image regression fix).
258
- const imageBlock = isImageBlock(obj);
314
+ // A base64 image `data` string used to be exempt (counted as 8 bytes), which
315
+ // let a multi-megabyte image escape the ceiling and then OOM the broadcast
316
+ // `JSON.stringify`. It now counts at its REAL byte size like any other string
317
+ // (short-circuited via the code-unit lower bound when huge).
318
+ // See change: head-tail-truncate-subagent-event-timeline (D8).
259
319
  for (const k of Object.keys(obj)) {
260
320
  w.total += k.length + 3; // "k":
261
321
  if (w.total > w.cap) return true;
262
- if (imageBlock && k === "data" && typeof obj[k] === "string") {
263
- w.total += 8; // stand-in for the preserved base64 payload
264
- if (w.total > w.cap) return true;
265
- continue;
266
- }
267
322
  if (walkSize(obj[k], w)) return true;
268
323
  w.total += 1; // comma
269
324
  }
@@ -275,7 +330,14 @@ function walkSize(v: unknown, w: SizeWalk): boolean {
275
330
  if (w.total > w.cap) return true;
276
331
  switch (typeof v) {
277
332
  case "string":
278
- w.total += v.length + 2; // surrounding quotes
333
+ // Code-unit lower bound: UTF-8 bytes ≥ UTF-16 code units. If even the
334
+ // lower bound crosses the cap, the actual byte count does too — short
335
+ // out WITHOUT scanning the (possibly multi-megabyte) string.
336
+ if (w.total + v.length > w.cap) {
337
+ w.total += v.length + 2;
338
+ return true;
339
+ }
340
+ w.total += jsonStringByteSize(v);
279
341
  return w.total > w.cap;
280
342
  case "number":
281
343
  case "boolean":
@@ -304,6 +366,288 @@ export function exceedsSerializedSize(value: unknown, cap: number): boolean {
304
366
  return walkSize(value, { total: 0, cap, seen: new WeakSet<object>() });
305
367
  }
306
368
 
369
+ /**
370
+ * Byte-accurate, BOUNDED serialized-size measurement. Returns the exact JSON
371
+ * byte length when `value` fits within `cap`, else `cap + 1` (an over-ceiling
372
+ * sentinel) — the walk early-exits and NEVER materializes a full
373
+ * `JSON.stringify`. Used by the subagent reducer for both the entries budget
374
+ * `E` and the terminal bound proof, and per-entry by the shrink loop.
375
+ * See change: head-tail-truncate-subagent-event-timeline (D8).
376
+ */
377
+ export function measureBytes(value: unknown, cap: number): number {
378
+ const w: SizeWalk = { total: 0, cap, seen: new WeakSet<object>() };
379
+ walkSize(value, w);
380
+ return Math.min(w.total, cap + 1);
381
+ }
382
+
383
+ // ---- Subagent-timeline head+tail reduction ----
384
+ // See change: head-tail-truncate-subagent-event-timeline.
385
+
386
+ /** Non-`entries` string caps (D3/D7). */
387
+ const PROMPT_CAP = 2_000;
388
+ const DESC_CAP = 1_500;
389
+ const CONTENT_CAP = 1_500;
390
+ /** Head/tail entry retention + per-ENTRY byte-budget floors (D3). */
391
+ const K_HEAD = 1;
392
+ const K_TAIL = 4;
393
+ const MID_FLOOR = 800;
394
+ const ENTRY_FLOOR = 256;
395
+ /** Reserve for the sentinel entry + per-field `…hidden…` markers (D3). */
396
+ const MARKER_RESERVE = 300;
397
+
398
+ function clamp(n: number, lo: number, hi: number): number {
399
+ return Math.max(lo, Math.min(hi, n));
400
+ }
401
+
402
+ interface SubagentTimeline {
403
+ /** The resolved `details` object carrying `entries[]` (+ `description`). */
404
+ details: Record<string, unknown>;
405
+ /** The `entries[]` array reachable on `details`. */
406
+ entries: unknown[];
407
+ /** Whether `details` sits under `data.partialResult` (live) vs `data`. */
408
+ underPartialResult: boolean;
409
+ }
410
+
411
+ /**
412
+ * TYPE-scoped detector (D1). Returns the resolved `details` + its `entries[]`
413
+ * ONLY when the event is a subagent-carrying tool event — `data.toolName ===
414
+ * "Agent"`, OR eventType `tool_execution_update`/`tool_execution_end` with a
415
+ * `details.agentId` — AND an array sits at `data.partialResult.details.entries`
416
+ * (live) or `data.details.entries` (started/end). Shape alone (a bare array)
417
+ * MUST NOT match.
418
+ */
419
+ function locateSubagentTimeline(event: DashboardEvent): SubagentTimeline | undefined {
420
+ const data = event.data as Record<string, unknown> | undefined;
421
+ if (!data || typeof data !== "object") return undefined;
422
+ const pr = data.partialResult as Record<string, unknown> | undefined;
423
+ let details: Record<string, unknown> | undefined;
424
+ let underPartialResult = false;
425
+ if (pr && typeof pr === "object" && pr.details && typeof pr.details === "object") {
426
+ details = pr.details as Record<string, unknown>;
427
+ underPartialResult = true;
428
+ } else if (data.details && typeof data.details === "object") {
429
+ details = data.details as Record<string, unknown>;
430
+ }
431
+ if (!details || !Array.isArray(details.entries)) return undefined;
432
+ const isAgentTool = data.toolName === "Agent";
433
+ const isUpdateOrEnd =
434
+ event.eventType === "tool_execution_update" || event.eventType === "tool_execution_end";
435
+ const hasAgentId = typeof details.agentId === "string";
436
+ if (!isAgentTool && !(isUpdateOrEnd && hasAgentId)) return undefined;
437
+ return { details, entries: details.entries as unknown[], underPartialResult };
438
+ }
439
+
440
+ /** Head+tail-cap every string reachable inside `content[*]`, recursing container blocks. */
441
+ function capContentBlocks(blocks: unknown[], cap: number): void {
442
+ for (const b of blocks) {
443
+ if (!b || typeof b !== "object") continue;
444
+ const block = b as Record<string, unknown>;
445
+ if (typeof block.text === "string") block.text = capString(block.text, cap);
446
+ // Base64 image `data` is capped too — no image preservation on this path.
447
+ if (typeof block.data === "string") block.data = capString(block.data, cap);
448
+ if (Array.isArray(block.content)) capContentBlocks(block.content, cap);
449
+ }
450
+ }
451
+
452
+ /**
453
+ * Step 0 (D3): head+tail-cap ALL big non-`entries` strings on the CLONE —
454
+ * `args.prompt`, `details.description`, and every string inside
455
+ * `partialResult.content[*]` (both `.text` and image `.data`). After this no
456
+ * non-`entries` string exceeds its cap, so the envelope is provably bounded.
457
+ */
458
+ function capLargeStrings(data: Record<string, unknown>, details: Record<string, unknown>): void {
459
+ const args = data.args as Record<string, unknown> | undefined;
460
+ if (args && typeof args.prompt === "string") args.prompt = capString(args.prompt, PROMPT_CAP);
461
+ if (typeof details.description === "string") {
462
+ details.description = capString(details.description, DESC_CAP);
463
+ }
464
+ const pr = data.partialResult as Record<string, unknown> | undefined;
465
+ if (pr && Array.isArray(pr.content)) capContentBlocks(pr.content, CONTENT_CAP);
466
+ }
467
+
468
+ interface LeafRef {
469
+ parent: Record<string, unknown> | unknown[];
470
+ key: string | number;
471
+ value: string;
472
+ }
473
+
474
+ /** One bounded walk returning the entry's CURRENTLY-largest string leaf, if any. */
475
+ function findLargestStringLeaf(root: unknown): LeafRef | undefined {
476
+ let best: LeafRef | undefined;
477
+ const seen = new WeakSet<object>();
478
+ const stack: unknown[] = [root];
479
+ while (stack.length) {
480
+ const node = stack.pop();
481
+ if (!node || typeof node !== "object") continue;
482
+ if (seen.has(node)) continue;
483
+ seen.add(node);
484
+ if (Array.isArray(node)) {
485
+ for (let i = 0; i < node.length; i++) {
486
+ const v = node[i];
487
+ if (typeof v === "string") {
488
+ if (!best || v.length > best.value.length) best = { parent: node, key: i, value: v };
489
+ } else if (v && typeof v === "object") {
490
+ stack.push(v);
491
+ }
492
+ }
493
+ } else {
494
+ const obj = node as Record<string, unknown>;
495
+ for (const k of Object.keys(obj)) {
496
+ const v = obj[k];
497
+ if (typeof v === "string") {
498
+ if (!best || v.length > best.value.length) best = { parent: obj, key: k, value: v };
499
+ } else if (v && typeof v === "object") {
500
+ stack.push(v);
501
+ }
502
+ }
503
+ }
504
+ }
505
+ return best;
506
+ }
507
+
508
+ /**
509
+ * D3a: shrink one entry to a byte budget `B` by repeatedly head+tail-capping its
510
+ * CURRENTLY-largest string leaf at a shrinking cap, down to `ENTRY_FLOOR`. Bounds
511
+ * the ENTRY total regardless of leaf count and caps base64 leaves inside entries
512
+ * — never relies on a per-leaf `maxSize`. Mutates the (already-cloned) entry.
513
+ */
514
+ export function shrinkEntryToBudget(entry: unknown, B: number): unknown {
515
+ if (!entry || typeof entry !== "object") return entry;
516
+ let guard = 0;
517
+ while (measureBytes(entry, B) > B && guard < 100_000) {
518
+ guard++;
519
+ const leaf = findLargestStringLeaf(entry);
520
+ if (!leaf || leaf.value.length <= ENTRY_FLOOR) break;
521
+ const newCap = Math.max(ENTRY_FLOOR, Math.floor(leaf.value.length / 2));
522
+ (leaf.parent as Record<string | number, unknown>)[leaf.key] = capString(leaf.value, newCap);
523
+ }
524
+ return entry;
525
+ }
526
+
527
+ /** Byte-bounded `{ __truncated }` placeholder built WITHOUT stringifying the original. */
528
+ function truncatedPlaceholder(event: DashboardEvent, maxEventDataSize: number): DashboardEvent {
529
+ return {
530
+ ...event,
531
+ data: {
532
+ __truncated: true,
533
+ reason: "event data exceeded MAX_EVENT_DATA_SIZE",
534
+ thresholdBytes: maxEventDataSize,
535
+ eventType: event.eventType,
536
+ },
537
+ };
538
+ }
539
+
540
+ function entryTs(entry: unknown): number {
541
+ if (entry && typeof entry === "object" && typeof (entry as Record<string, unknown>).ts === "number") {
542
+ return (entry as Record<string, unknown>).ts as number;
543
+ }
544
+ return Date.now();
545
+ }
546
+
547
+ /**
548
+ * D3: reduce an over-ceiling subagent-timeline event, tail-weighted and
549
+ * final-protected, to `≤ ceiling` ACTUAL bytes. Returns a NEW event with the
550
+ * touched spine (`data`, `data.args`, resolved `details`, `details.entries`)
551
+ * cloned — NEVER mutates the in-flight `event`. Falls back to `{ __truncated }`
552
+ * when the event is unreducible (e.g. empty `entries[]` + oversized envelope).
553
+ * No `JSON.stringify` anywhere — all measurement is via `measureBytes`.
554
+ */
555
+ export function reduceSubagentEvent(event: DashboardEvent, ceiling: number): DashboardEvent {
556
+ const origData = event.data as Record<string, unknown>;
557
+ const data: Record<string, unknown> = { ...origData };
558
+ if (data.args && typeof data.args === "object") data.args = { ...(data.args as object) };
559
+
560
+ // Resolve + clone the details spine on the CLONE.
561
+ const loc = locateSubagentTimeline(event);
562
+ if (!loc) return event; // defensive — caller only routes detected events
563
+ let details: Record<string, unknown>;
564
+ if (loc.underPartialResult) {
565
+ const prClone = { ...(data.partialResult as Record<string, unknown>) };
566
+ if (Array.isArray(prClone.content)) prClone.content = structuredClone(prClone.content);
567
+ details = { ...(prClone.details as object) } as Record<string, unknown>;
568
+ prClone.details = details;
569
+ data.partialResult = prClone;
570
+ } else {
571
+ details = { ...(data.details as object) } as Record<string, unknown>;
572
+ data.details = details;
573
+ }
574
+ const origEntries = loc.entries;
575
+
576
+ // Step 0: cap all big non-`entries` strings.
577
+ capLargeStrings(data, details);
578
+
579
+ // Compute the envelope budget with entries removed.
580
+ details.entries = [];
581
+ const envBytes = measureBytes(data, ceiling);
582
+ const E = ceiling - envBytes - MARKER_RESERVE;
583
+ const ENTRY_FINAL = clamp(Math.round(E * 0.45), 1_500, 6_000);
584
+
585
+ const n = origEntries.length;
586
+ let kHead = Math.min(K_HEAD, n);
587
+ let kTail = Math.min(K_TAIL, n - kHead);
588
+
589
+ // Decrement K_TAIL while the intermediate per-entry budget underflows MID_FLOOR.
590
+ while (kHead + kTail > 1) {
591
+ const kept = kHead + kTail;
592
+ const entryMid = (E - ENTRY_FINAL) / (kept - 1);
593
+ if (entryMid >= MID_FLOOR) break;
594
+ if (kTail > 1) kTail--;
595
+ else break;
596
+ }
597
+ const kept = kHead + kTail;
598
+ const ENTRY_MID = kept > 1 ? Math.max(ENTRY_FLOOR, Math.floor((E - ENTRY_FINAL) / (kept - 1))) : E;
599
+
600
+ // Build kept real entries (cloned) + a text sentinel for the dropped middle.
601
+ const head = origEntries.slice(0, kHead).map((e) => structuredClone(e));
602
+ const tail = kTail > 0 ? origEntries.slice(n - kTail).map((e) => structuredClone(e)) : [];
603
+ const keptReal = [...head, ...tail];
604
+ const hiddenCount = n - kHead - kTail;
605
+ const display: unknown[] = [...head];
606
+ if (hiddenCount > 0) {
607
+ display.push({
608
+ kind: "text",
609
+ text: `⋯ ${hiddenCount} steps hidden ⋯`,
610
+ ts: entryTs(origEntries[kHead]),
611
+ });
612
+ }
613
+ display.push(...tail);
614
+
615
+ // Shrink intermediate entries to ENTRY_MID, then the final entry to ENTRY_FINAL.
616
+ for (let i = 0; i < keptReal.length - 1; i++) shrinkEntryToBudget(keptReal[i], ENTRY_MID);
617
+ if (keptReal.length > 0) shrinkEntryToBudget(keptReal[keptReal.length - 1], ENTRY_FINAL);
618
+
619
+ details.entries = display;
620
+
621
+ // Terminal proof (byte-accurate, bounded). Shrink the largest kept entry
622
+ // toward ENTRY_FLOOR; if all are at the floor and still over, drop a tail
623
+ // entry; if nothing remains to shrink, fall back to the placeholder.
624
+ let guard = 0;
625
+ while (measureBytes(data, ceiling) > ceiling && guard < 200) {
626
+ guard++;
627
+ if (keptReal.length === 0) return truncatedPlaceholder(event, ceiling);
628
+ let largest = keptReal[0];
629
+ let largestBytes = measureBytes(largest, ceiling);
630
+ for (const e of keptReal) {
631
+ const b = measureBytes(e, ceiling);
632
+ if (b > largestBytes) {
633
+ largest = e;
634
+ largestBytes = b;
635
+ }
636
+ }
637
+ if (largestBytes <= ENTRY_FLOOR + 64) {
638
+ // Everything is already at the floor — drop the oldest kept entry.
639
+ const dropped = keptReal.shift();
640
+ const di = display.indexOf(dropped);
641
+ if (di !== -1) display.splice(di, 1);
642
+ if (keptReal.length === 0) return truncatedPlaceholder(event, ceiling);
643
+ } else {
644
+ shrinkEntryToBudget(largest, Math.max(ENTRY_FLOOR, Math.floor(largestBytes / 2)));
645
+ }
646
+ }
647
+ if (measureBytes(data, ceiling) > ceiling) return truncatedPlaceholder(event, ceiling);
648
+ return { ...event, data };
649
+ }
650
+
307
651
  /**
308
652
  * Truncate large event data to bound memory usage per event. Applies a
309
653
  * per-field string cap (`maxStringSize`) and then a hard per-event total-size
@@ -317,19 +661,21 @@ function createTruncator(maxStringSize: number, maxEventDataSize: number) {
317
661
  return (event: DashboardEvent): DashboardEvent => {
318
662
  const data = event.data;
319
663
  if (!data || typeof data !== "object") return event;
664
+ // Detect subagent-timeline events on the ORIGINAL event BEFORE the generic
665
+ // per-field pass, so the generic `obj.length > 20` array clobber can NEVER
666
+ // reach a detected `entries[]` regardless of `maxStringSize`. Over-ceiling
667
+ // → head+tail reduce; under-ceiling → store unchanged (skip generic pass).
668
+ // See change: head-tail-truncate-subagent-event-timeline (D1/D4).
669
+ if (sizePass && locateSubagentTimeline(event)) {
670
+ return exceedsSerializedSize(data, maxEventDataSize)
671
+ ? reduceSubagentEvent(event, maxEventDataSize)
672
+ : event;
673
+ }
320
674
  const truncated = stringPass
321
675
  ? (truncateStrings(data, maxStringSize) as Record<string, unknown>)
322
676
  : (data as Record<string, unknown>);
323
677
  if (sizePass && exceedsSerializedSize(truncated, maxEventDataSize)) {
324
- return {
325
- ...event,
326
- data: {
327
- __truncated: true,
328
- reason: "event data exceeded MAX_EVENT_DATA_SIZE",
329
- thresholdBytes: maxEventDataSize,
330
- eventType: event.eventType,
331
- },
332
- };
678
+ return truncatedPlaceholder(event, maxEventDataSize);
333
679
  }
334
680
  return truncated !== data ? { ...event, data: truncated } : event;
335
681
  };
@@ -1,3 +1,3 @@
1
1
  # memory-event-store.ts — index
2
2
 
3
- In-memory event store with LRU eviction; replaces SQLite-backed event-store. Exports `StoredEvent`, `EventStore`, `createMemoryEventStore(isSessionPinned, maxCachedSessions, maxEventsPerSession, maxStringFieldSize, maxEventDataSize)`, `exceedsSerializedSize(value, cap)`, `DEFAULT_MAX_CACHED_SESSIONS`, `DEFAULT_MAX_EVENTS_PER_SESSION`, `DEFAULT_MAX_EVENT_DATA_SIZE`. Per-session buffers, truncates large string fields, `findToolEndEvent` reverse-scans for `tool_execution_end`. Skips pinned sessions in eviction. Per-session trim preserves chat head: drops oldest NON-essential event first (tool/subagent/flow/reasoning noise), only drops oldest `message_start`/`message_end` under extreme pressure; `DEFAULT_MAX_EVENTS_PER_SESSION`=20000 (was 5000, subagent floods parent buffer). Per-event total-serialized-size ceiling (`DEFAULT_MAX_EVENT_DATA_SIZE`=20000, `0`=off): after per-field truncation, `exceedsSerializedSize` (bounded early-exit walk, never full-stringifies) gates replacing over-cap `event.data` with a `{__truncated}` placeholder — stops one oversized subagent event OOM-ing the broadcast `JSON.stringify`; `truncateStrings` depth>4 now truncates/collapses to `[truncated: deep]` (preserves image blocks) instead of returning raw. See change: bound-subagent-event-serialization. See change: preserve-chat-head-on-event-trim. `capString` skill-envelope-aware: `SKILL_ENVELOPE_RE` truncates BODY only, keeps `<skill>` header/closing tag/args intact so client `parseSkillBlock` survives; base64 image blocks exempt from per-event size ceiling. See change: bound-subagent-event-serialization (skill regression). Store-shed telemetry: `trimBufferToLimit` returns `{dropped,toolEndDropped}` (counts `tool_execution_end` among drops in the same O(n) pass), `evictIfNeeded` returns evicted-buffer count; closure accumulates `trimmedEventsTotal`/`trimmedToolEndTotal`/`trimmedEventsBySession`(Map)/`evictedSessionsTotal`; `getTrimStats()` handle returns `TrimStats {trimmedEvents:{total,toolExecutionEnd,bySession},evictedSessions}` (global counters cumulative/never-reset; `bySession` lifecycle-scoped — entry dropped in `evictIfNeeded`/`deleteEventsForSession` when its buffer is removed, so the Map cannot accumulate stale sessions). See change: instrument-event-store-trim.
3
+ In-memory event store with LRU eviction; replaces SQLite-backed event-store. Exports `StoredEvent`, `EventStore`, `createMemoryEventStore(isSessionPinned, maxCachedSessions, maxEventsPerSession, maxStringFieldSize, maxEventDataSize)`, `exceedsSerializedSize(value, cap)`, `measureBytes(value, cap)`, `capString(s, maxSize)`, `reduceSubagentEvent(event, ceiling)`, `shrinkEntryToBudget(entry, B)`, `DEFAULT_MAX_CACHED_SESSIONS`, `DEFAULT_MAX_EVENTS_PER_SESSION`, `DEFAULT_MAX_EVENT_DATA_SIZE`. Per-session buffers, truncates large string fields, `findToolEndEvent` reverse-scans for `tool_execution_end`. Skips pinned sessions in eviction. Per-session trim preserves chat head: drops oldest NON-essential event first (tool/subagent/flow/reasoning noise), only drops oldest `message_start`/`message_end` under extreme pressure; `DEFAULT_MAX_EVENTS_PER_SESSION`=20000 (was 5000, subagent floods parent buffer). Per-event total-serialized-size ceiling (`DEFAULT_MAX_EVENT_DATA_SIZE`=20000, `0`=off): after per-field truncation, `exceedsSerializedSize` (bounded early-exit walk, never full-stringifies) gates replacing over-cap `event.data` with a `{__truncated}` placeholder — stops one oversized subagent event OOM-ing the broadcast `JSON.stringify`; `truncateStrings` depth>4 now truncates/collapses to `[truncated: deep]` (preserves image blocks) instead of returning raw. See change: bound-subagent-event-serialization. See change: preserve-chat-head-on-event-trim. `capString` skill-envelope-aware: `SKILL_ENVELOPE_RE` truncates BODY only, keeps `<skill>` header/closing tag/args intact so client `parseSkillBlock` survives. See change: bound-subagent-event-serialization (skill regression). Subagent-timeline head+tail: `locateSubagentTimeline` TYPE-scopes detection (`data.toolName==="Agent"` or `tool_execution_update`/`_end` + `details.agentId`, AND `entries[]` at `partialResult.details.entries`/`data.details.entries`); such over-ceiling events route to `reduceSubagentEvent` (detected BEFORE the generic pass so the >20-array clobber never hits `entries[]`) instead of `{__truncated}` — keeps first `K_HEAD`=1 + last `K_TAIL`=4 entries, elides the middle into a `{kind:"text","⋯ N steps hidden ⋯"}` sentinel (no new wire kind), caps `args.prompt`@2000/`details.description`@1500/`content[*]` text+image@1500, shrinks kept entries to a per-ENTRY byte budget via `shrinkEntryToBudget` (largest-leaf head+tail, floor 256), byte-accurate terminal proof, `{__truncated}` fallback when unreducible; returns a NEW event (never mutates the in-flight one). `capString` generic branch is now head+tail 50/50 (`…[N chars hidden]…`). Size walk is byte-accurate (`jsonStringByteSize`: UTF-8 width + JSON escapes; base64 image `data` counted at REAL size — no longer exempt — so image-bearing over-ceiling events correctly hit `{__truncated}`, closing a latent broadcast OOM); huge strings short-circuit via the code-unit lower bound (no scan, no stringify). `measureBytes` returns exact bytes when under cap else cap+1. See change: head-tail-truncate-subagent-event-timeline. Store-shed telemetry: `trimBufferToLimit` returns `{dropped,toolEndDropped}` (counts `tool_execution_end` among drops in the same O(n) pass), `evictIfNeeded` returns evicted-buffer count; closure accumulates `trimmedEventsTotal`/`trimmedToolEndTotal`/`trimmedEventsBySession`(Map)/`evictedSessionsTotal`; `getTrimStats()` handle returns `TrimStats {trimmedEvents:{total,toolExecutionEnd,bySession},evictedSessions}` (global counters cumulative/never-reset; `bySession` lifecycle-scoped — entry dropped in `evictIfNeeded`/`deleteEventsForSession` when its buffer is removed, so the Map cannot accumulate stale sessions). See change: instrument-event-store-trim.
@@ -8,7 +8,7 @@ Files in this directory. One row per source file.
8
8
  | `live-server-routes.ts` | Live-server-preview REST. `registerLiveServerRoutes`. `POST /api/live-server/start {host,port,label}` (SSRF gate via manager `validateLiveTarget`; non-loopback→400; returns proxied `/live/<id>/` path), `GET /api/live-server/list`, `DELETE /api/live-server/:id`. See change: improve-content-editor. |
9
9
  | `file-routes.ts` | REST routes for file read/browse. `/api/file` decodes leading `file://` on `path` via `decodeFileUri`. Absolute paths accepted but still gated by known-session-cwd + traversal check. See change: unify-file-link-openability. Adds GET /api/favorite-models → {labels}. See change: enrich-model-selector-capabilities-favorites. 4 guard sites (`/api/file`, `/api/file/exists`, `/api/file/raw`, `/api/file/render`) route through `isAllowed`. exists keeps pinned-dir anchor + `"unknown cwd"`/`"path outside cwd"` strings. See change: git-root-file-containment. /api/file/raw adds layer ③ artifact-root image anchor via isImageUnderArtifactRoot (image-only, realpath-contained); only raw route, not /api/file or /api/file/render. See change: serve-agent-artifact-previews. GET /api/file file branch sniffs first 1024 bytes, calls `fileKind(resolved, sniff)`, returns `{ type:"file", kind, mimeType, size, content? }`. content read only for monaco/markdown viewers. /api/file/raw (pre-existing) serves image/pdf bytes. See change: add-internal-monaco-editor-pane. Adds `POST /api/file/write` (body `{cwd?,path,content,mtime}`; isWritableMdTarget gate → 403; mtime mismatch → 409; atomic tmp+rename; returns new mtime), `GET /api/file/md-candidates` (scoped picker list), `GET /api/file/md-read` (scoped markdown read, same guard, serves global ~/.pi/agent that /api/file cannot). `/api/file` read now returns `mtime`. See change: directory-settings-page-and-scoped-md-editing. Adds `GET /api/file/tree?cwd=&path=` → `{entries:{name,isDir}[]}` via single `readdir(withFileTypes)`, hidden INCLUDED, same known-cwd+containment gate; single source of truth for editor-pane tree (fixes #1 hidden-dir mislabel). See change: improve-content-editor. `/api/file/render` gains a `.docx` branch (two-tier, design D8): `{mode:"pdf"}` (document-converter render, cached) or `{mode:"html",html,truncated,imageCount}` (mammoth+hyperlink-guard+DOMPurify+image-cap); ANY engine error falls through to html. Adds `GET /api/file/rendered-pdf?cwd=&path=` (streams cached docx→PDF, `application/pdf`) and `GET /api/file/sheet?cwd=&path=&limit=` (SheetJS structured JSON `{sheets[],activeSheet,encoding?}`; csv encoding-detected). Shared `gateOfficeFile` helper: ext allowlist (else 400) + `stat.size` cap (>cap → 413 before read) + traversal gate. Injectable `docxPdfEngine`/`officeCaps`/`docxRenderMode` deps (tests). Corrupt/password/oversize degrade to `{success:false}` (design D5). See change: render-office-previews. `/api/file/render` + `/api/file/rendered-pdf` also accept `.pptx` (per-ext size cap via `pptxSizeCap`): pptx → engine-only PDF render (`renderPptx`, `{mode:"pdf"}`); NO in-process fallback — engine absent → `{success:false}` → client FallbackPreview. See change: render-pptx-preview. Adds shared async `gateFilePath(cwd, relPath, sessionManager)` (known-session + `isAllowed`, factored so the EML routes CALL it not re-impl) + `GET /api/file/eml?cwd=&path=&allowRemote=` (mailparser parse + DOMPurify sanitize → metadata-only JSON; non-`.eml`→400; >25 MB→413 before read; malformed→400 no crash; parse cache) and `GET /api/file/eml-attachment?cwd=&path=&index=` (streams one decoded part, ALWAYS `Content-Disposition: attachment` + `nosniff`; bad index→400; out-of-range→404). See change: add-eml-preview. Adds `POST /api/file/resolve-mention` (body `{cwd,mention}` → `{resolved, kind}`\|`{resolved:null}`): gates `cwd` against known-session set FIRST (mirrors `/api/file`, NOT the wider exists-only pinned set — D2/F6/F7) then delegates to `resolveFileMention`; never stats an untrusted cwd (403). Module `homePiAnchor()` = `join(os.homedir(),".pi")` (call-time, fake-HOME safe); the open/preview routes `/api/file` + `/api/file/raw` + `/api/file/render` now anchor `isAllowed` on `[cwd, homePiAnchor()]` so a resolved `~/.pi/…` mention previews without a 403 (D7). See change: server-side-file-mention-resolution. |
10
10
  | `git-routes.ts` | REST routes: git branches, checkout, init, stash-pop. Adds `GET /api/git/head`, `GET /api/git/worktrees`, `POST /api/git/worktree` (body `{cwd, branch, base?, path?}`) forwarding structured `{code, stderr}` errors from `addWorktree`. See change: add-worktree-spawn-dialog. Adds `POST /api/git/worktree/{remove,merge,push,pr}` + `GET /api/git/worktree/diff-stat`. Localhost-gated. Takes `sessionManager` + `browserGateway` deps. `/remove` pre-flight calls `activeSessionsUnder` → returns `{code:"active_sessions", sessionIds}` when non-empty; on success broadcasts `cwdMissing:true` per session under removed path. See change: add-worktree-lifecycle-actions. Adds `GET /api/git/worktree/bootstrap-status?cwd=<path>` (returns `{needsBootstrap, reason}` per decision tree: `not_required` / `ok` / `no_node_modules` / `stale_lockfile`) and `POST /api/git/worktree/bootstrap` (body `{cwd, requestId?}`; runs install in existing worktree). `POST /api/git/worktree` body extended with optional `requestId`; runs `detectBootstrapRequirement(repoRoot)` + `runBootstrap(...)` post-add; streams `worktree_bootstrap_progress` / `_done` / `_failed` to requesting browser via `worktreeBootstrapRegistry`. Response shape gains `bootstrap: {ran, durationMs?, skippedReason?}`. New error code `bootstrap_failed`. Takes `worktreeBootstrapRegistry` dep. See change: harden-worktree-spawn. worktree-init endpoints: `GET /api/git/worktree/init-status` (cached gate eval → {hasHook,needsInit,trusted}; `hasHook:false` responses also carry `configured:boolean` — `configRoot===null`→false, else `existsSync(<configRoot>/.pi/settings.json)` — distinguishing unconfigured dir ① from configured-no-hook ③; see change: distinguish-initialize-actions), `POST /api/git/worktree/init` (TOFU-gated; untrusted → init_untrusted carrying {hook,hash}; runs hook, streams progress). `POST /api/git/worktree` no longer auto-runs init. friendlier-worktree-init: `/init` registers a cwd-keyed run in `worktreeInitRegistry` (startRun/progressRun/finishRun) + fans progress/done/failed by cwd (not just requestId); after trust passes, re-evals gate → `needsInit:false`→`{ran:false,skippedReason:"already_initialized"}` (re-trust grants trust without running). New `GET /api/git/worktree/active-inits` → `{runs}` (running + terminal-within-TTL) for boot rehydration. `lastLineOf(tail)` = last non-empty line for the ghost preview. See change: friendlier-worktree-init. Replaced bootstrap + bootstrap-status endpoints. See change: generalize-worktree-init-hook. Adds `GET /api/git/pull-requests?cwd=` (lists open PRs via `listPullRequests`, `networkGuard` + gh resolution) + `POST /api/git/worktree/from-pr` (body `{cwd, prNumber, path?}`; runs `addWorktreeFromPr`). See change: add-worktree-from-pull-request. `POST /api/git/worktree` body `newBranch` now optional (string when present, else checkout mode); base still required. See change: worktree-checkout-existing-branch. Adds `GET /api/git/status?cwd=` (fresh `getGitStatus`), `GET /api/git/changed-files?cwd=` (picker list), `POST /api/git/commit` (body `{cwd,message,files}` → `commitFiles`; on success broadcasts fresh `gitStatus` to every same-cwd session; error codes → 400/409), `POST /api/git/commit-draft` (body `{cwd,files,sessionId}` → `commitDraftRelay.request` via `sendToSession`; stub when unwired). New deps `sendToSession`, `commitDraftRelay`. See change: add-session-uncommitted-indicator-and-commit. |
11
- | `goal-routes.ts` | REST routes for folder GoalRecords. `parseJudge(raw)` validates `judge` on POST/PATCH (clamp-or-reject, mirrors parseBudget). Rejects missing provider/modelId. `autoRespawn?:boolean` validated + persisted on POST/PATCH. `VALID_STATUS` includes `respawning`+`failed`. A PATCH to a terminal/pause status (`paused`/`cleared`/`achieved`/`failed`) OR a DELETE routes through `abortGoalSupervision` dep (supervisor finalize+kill: terminal-status-first, generation-guarded) BEFORE the record is finalized/removed. See changes: sophisticate-goal-authoring-and-control, add-goal-session-supervisor. |
11
+ | `goal-routes.ts` | REST routes for folder GoalRecords. `parseJudge(raw)` validates `judge` on POST/PATCH (clamp-or-reject, mirrors parseBudget). Rejects missing provider/modelId. `autoRespawn?:boolean` validated + persisted on POST/PATCH. `VALID_STATUS` includes `respawning`+`failed`. A PATCH to a terminal/pause status (`paused`/`cleared`/`achieved`/`failed`) OR a DELETE routes through `abortGoalSupervision` dep (supervisor finalize+kill: terminal-status-first, generation-guarded) BEFORE the record is finalized/removed. See changes: sophisticate-goal-authoring-and-control, add-goal-session-supervisor. Every goal-record response (GET list, POST/PATCH, link/unlink `data:updated`) now passes through `decorateGoalsWithSpend` (local `withSpend` wrapper) so each carries server-derived `totalSpendUsd`. See change: fix-goal-detail-turns-and-spend. |
12
12
  | `grep-routes.ts` | `GET /api/grep?cwd&q&regex`. Gates: known-session cwd, min-3 q, per-match cwd containment. See change: split-editor-workspace. |
13
13
  | `known-servers-routes.ts` | Known-servers config + mDNS discovery routes. Exports `registerKnownServersRoutes`. Endpoints: `GET/POST/DELETE /api/known-servers`, `POST /api/discover-servers`. Persists via `writeConfigPartial`, returns peer servers from `getPeerServers`. |
14
14
  | `manifest-route.ts` | Dynamic `/manifest.json` route. Exports `stripPort`, `resolveManifestSource`, `buildManifestBody`, `loadStaticManifest`, `registerManifestRoute`. Resolves source: `config.dashboardName` → request `Host` header (port stripped, IPv6-safe) → `os.hostname()` → `"Pi-Dash"`. `buildManifestBody` sets `id="/"`, `name="Pi-Dash · <src>"`, `short_name=src.slice(0,12)`. Registered before `@fastify/static` so explicit route wins over on-disk asset. Re-reads config per request via `loadConfig()`; Settings change propagates without restart. Sets `Cache-Control: no-cache, must-revalidate` + `Content-Type: application/manifest+json`. See change: add-dynamic-pwa-manifest-naming. |
@@ -16,7 +16,7 @@ Files in this directory. One row per source file.
16
16
  | `model-proxy-diagnostics-routes.ts` | `GET /api/model-proxy/diagnostics`. JWT-gated, main instance only (NOT second `/v1` proxy port). `registerModelProxyDiagnosticsRoutes(fastify)`. Returns `getAllAnnotated()` → `{id, provider, excludedReason}` per model (`null` \| `no-credential` \| `oauth-incompatible`). Sibling to `model-proxy-refresh-routes.ts`; resolves registry via `getModelRegistry()` singleton. 503 when pi-ai unresolved. See change: filter-oauth-incompatible-models. |
17
17
  | `model-proxy-refresh-routes.ts` | Force-refresh model proxy registry. Exports `registerModelProxyRefreshRoutes`. `POST /api/model-proxy/refresh` → `refreshModelRegistry`; 503 `MODEL_PROXY_RUNTIME_MISSING` on failure. |
18
18
  | `model-proxy-routes.ts` | OpenAI- + Anthropic-compatible proxy endpoints fronting model registry via pi-ai `streamSimple`. Exports `registerModelProxyRoutes`, `ModelProxyRouteDeps`, `ModelProxyRegistry` (now requires `firstAvailable`), `StreamSimpleFn`. Endpoints: `GET /v1/models`, `POST /v1/chat/completions`, `POST /v1/messages`. Shared `resolveRequestedModel` resolves both POST endpoints: label = request.model → firstAvailable(preferredModels) → defaultModel (else 400); alias-expand (`modelAliases`, exact key); first-slash `parseModelId`; `registry.find`; preferred fallback; else 404. Both split("/",2) resolution + concurrency-provider sites converged onto `parseModelId`. Concurrency + SSE/non-stream + request logging + abort on disconnect. See change: fix-and-prefer-model-proxy-resolution. |
19
- | `models-introspection-routes.ts` | Ungated `GET /api/models` model-introspection surface for in-session agents. Exports `registerModelsIntrospectionRoute`, `ModelsIntrospectionRegistry`, `ModelsIntrospectionRouteDeps`. Subject only to dashboard auth gate (same posture as `/api/provider-auth/status`), registered unconditionally. Default = `getAvailable()` reachable rows `{id: provider/modelId, provider, reasoning?, input?, contextWindow?, maxTokens?, cost?}`; `?annotated=1` = `getAllAnnotated()` adds `excludedReason`. No credential material. 503 `MODEL_PROXY_RUNTIME_MISSING` when pi-ai unresolved. See change: surface-model-introspection-to-agents. |
19
+ | `models-introspection-routes.ts` | Ungated `GET /api/models` model-introspection surface for in-session agents. Exports `registerModelsIntrospectionRoute`, `ModelsIntrospectionRegistry`, `ModelsIntrospectionRouteDeps`. Subject only to dashboard auth gate (same posture as `/api/provider-auth/status`), registered unconditionally. Default = `getAvailable()` reachable rows `{id: provider/modelId, provider, reasoning?, input?, contextWindow?, maxTokens?, thinkingLevelMap?, cost?}`; `?annotated=1` = `getAllAnnotated()` adds `excludedReason`. `toRow` passes through the RAW native `thinkingLevelMap` (agent consumers interpret it; server derives NO `supportedThinkingLevels`), and NEVER emits `compat` or any credential. 503 `MODEL_PROXY_RUNTIME_MISSING` when pi-ai unresolved. See change: surface-model-introspection-to-agents, honor-native-models-json-metadata. |
20
20
  | `openspec-group-routes.ts` | REST routes for `/api/openspec/groups` CRUD + assignment. Adds PUT `/api/openspec/groups/change-order` (body `{groupId, order:string[]}`) → `store.setChangeOrder`. See change: add-openspec-change-grouping. See change: redesign-openspec-board. |
21
21
  | `openspec-routes.ts` | REST routes: openspec-archive, pi-resources (cwd optional → falls back to `process.cwd()` for the global Settings resource pages; change: resources-card-tabs), pi-resource-file. Adds POST /api/openspec/config (core→CLI preset, expanded/custom→atomic JSON write, busts configCache), POST /api/openspec/update (per-cwd or all known cwds, records signature), GET /api/openspec/update-status (up-to-date|needs-update|unknown). knownCwds = union(session cwds, pinned dirs). GET /api/openspec/config reads via `configListOrAsync` (async, non-blocking). `currentGlobalSignature` async + computed ONCE per request (profile is global). GET /api/openspec/update-status + POST /api/openspec/update signature step no longer spawn `openspec config list` per-cwd — was ~11s blocking for 11 projects, starved concurrent config GET. See changes: add-openspec-profile-settings, fix-openspec-profile-load-race. |
22
22
  | `package-routes.ts` | Extension/package management routes. Exports `registerPackageRoutes`. Endpoints: `GET /api/packages/search`, `GET /api/packages/readme`, `GET /api/packages/installed`, `POST /api/packages/{install,remove,update,move,check-updates}`. Uses `PackageManagerWrapper`; move returns phases based on `parseSourceKind`. `POST /api/packages/reset-to-npm {source,scope,cwd?}` resolves the published variant server-side (`resolvePublishedVariant`), validates the row is installed + resolvable, then invokes `wrapper.reset()`; 202 `{resetId,publishedSource,phases}`. `GET /installed` fills `publishedVariantSource/Version` via `attachPublishedVariants`. See change: reset-override-to-npm. |
@@ -15,11 +15,12 @@
15
15
  * extension, associated by `goalId`. See change: add-goals-folder-page (design.md).
16
16
  */
17
17
 
18
- import type { ApiResponse, GoalBudget, GoalCriterion, GoalJudge, GoalRecordStatus } from "@blackbelt-technology/pi-dashboard-shared/types.js";
18
+ import type { ApiResponse, GoalBudget, GoalCriterion, GoalJudge, GoalRecord, GoalRecordStatus } from "@blackbelt-technology/pi-dashboard-shared/types.js";
19
19
  import type { FastifyInstance, FastifyReply } from "fastify";
20
+ import { decorateGoalsWithSpend } from "../goal/decorate-goals-spend.js";
20
21
  import { GoalNotFoundError, type GoalStore } from "../goal/goal-store.js";
21
- import type { SessionManager } from "../session/memory-session-manager.js";
22
22
  import type { PreferencesStore } from "../persistence/preferences-store.js";
23
+ import type { SessionManager } from "../session/memory-session-manager.js";
23
24
  import type { NetworkGuard } from "./route-deps.js";
24
25
 
25
26
  export interface GoalRoutesDeps {
@@ -69,6 +70,10 @@ const VALID_STATUS: ReadonlySet<string> = new Set(["pursuing", "paused", "achiev
69
70
  export function registerGoalRoutes(fastify: FastifyInstance, deps: GoalRoutesDeps): void {
70
71
  const { sessionManager, preferencesStore, networkGuard, store, applyGoalIdToSession, primeGoalSession, spawnGoalSession, abortGoalSupervision } = deps;
71
72
 
73
+ // Server-derived read-time spend join. Single choke point for every
74
+ // goal-record response. See change: fix-goal-detail-turns-and-spend.
75
+ const withSpend = (record: GoalRecord): GoalRecord => decorateGoalsWithSpend([record], sessionManager)[0]!;
76
+
72
77
  function rejectInvalidCwd(reply: FastifyReply, cwd: string | undefined): cwd is undefined {
73
78
  if (!cwd) {
74
79
  reply.code(400);
@@ -155,7 +160,7 @@ export function registerGoalRoutes(fastify: FastifyInstance, deps: GoalRoutesDep
155
160
  const { cwd } = request.query;
156
161
  if (rejectInvalidCwd(reply, cwd)) return;
157
162
  try {
158
- const data = await store.list(cwd!);
163
+ const data = decorateGoalsWithSpend(await store.list(cwd!), sessionManager);
159
164
  return { success: true, data } satisfies ApiResponse;
160
165
  } catch (err) {
161
166
  return handleError(reply, err);
@@ -207,7 +212,7 @@ export function registerGoalRoutes(fastify: FastifyInstance, deps: GoalRoutesDep
207
212
  ...(body.autoRespawn !== undefined ? { autoRespawn: body.autoRespawn } : {}),
208
213
  });
209
214
  reply.code(201);
210
- return { success: true, data: created } satisfies ApiResponse;
215
+ return { success: true, data: withSpend(created) } satisfies ApiResponse;
211
216
  } catch (err) {
212
217
  return handleError(reply, err);
213
218
  }
@@ -282,16 +287,16 @@ export function registerGoalRoutes(fastify: FastifyInstance, deps: GoalRoutesDep
282
287
  const { status: _omit, ...rest } = update;
283
288
  if (Object.keys(rest).length > 0) {
284
289
  const updated = await store.update(cwd!, id, rest);
285
- return { success: true, data: updated } satisfies ApiResponse;
290
+ return { success: true, data: withSpend(updated) } satisfies ApiResponse;
286
291
  }
287
292
  // Re-fetch the finalized record; 404 if it was concurrently deleted
288
293
  // (never a 200 with no data via a masked non-null assertion).
289
294
  const updated = (await store.list(cwd!)).find((g) => g.id === id);
290
295
  if (!updated) throw new GoalNotFoundError(id);
291
- return { success: true, data: updated } satisfies ApiResponse;
296
+ return { success: true, data: withSpend(updated) } satisfies ApiResponse;
292
297
  }
293
298
  const updated = await store.update(cwd!, id, update);
294
- return { success: true, data: updated } satisfies ApiResponse;
299
+ return { success: true, data: withSpend(updated) } satisfies ApiResponse;
295
300
  } catch (err) {
296
301
  return handleError(reply, err);
297
302
  }
@@ -374,7 +379,7 @@ export function registerGoalRoutes(fastify: FastifyInstance, deps: GoalRoutesDep
374
379
  const updated = await store.linkSession(cwd!, id, sessionId);
375
380
  applyGoalIdToSession(sessionId, id);
376
381
  primeGoalSession?.(sessionId, updated);
377
- return { success: true, data: updated } satisfies ApiResponse;
382
+ return { success: true, data: withSpend(updated) } satisfies ApiResponse;
378
383
  } catch (err) {
379
384
  return handleError(reply, err);
380
385
  }
@@ -392,7 +397,7 @@ export function registerGoalRoutes(fastify: FastifyInstance, deps: GoalRoutesDep
392
397
  try {
393
398
  const updated = await store.unlinkSession(cwd!, id, sid);
394
399
  applyGoalIdToSession(sid, null);
395
- return { success: true, data: updated } satisfies ApiResponse;
400
+ return { success: true, data: withSpend(updated) } satisfies ApiResponse;
396
401
  } catch (err) {
397
402
  return handleError(reply, err);
398
403
  }
@@ -23,6 +23,15 @@ export interface RegistryModel {
23
23
  contextWindow?: number;
24
24
  maxTokens?: number;
25
25
  cost?: unknown;
26
+ /**
27
+ * Raw native per-model thinking-level override table (pi 0.72+). Passed
28
+ * through verbatim for agent consumers; the server derives NO
29
+ * `supportedThinkingLevels` (the sole derivation lives in the bridge
30
+ * extension). `compat` is intentionally NOT in this interface — it is
31
+ * carried on the registry model for proxy routing but never projected here.
32
+ * See change: honor-native-models-json-metadata.
33
+ */
34
+ thinkingLevelMap?: Record<string, unknown>;
26
35
  }
27
36
 
28
37
  type ExcludedReason = null | "no-credential" | "oauth-incompatible";
@@ -47,6 +56,7 @@ function toRow(m: RegistryModel, excludedReason?: ExcludedReason) {
47
56
  ...(m.input ? { input: m.input } : {}),
48
57
  ...(m.contextWindow ? { contextWindow: m.contextWindow } : {}),
49
58
  ...(m.maxTokens ? { maxTokens: m.maxTokens } : {}),
59
+ ...(m.thinkingLevelMap ? { thinkingLevelMap: m.thinkingLevelMap } : {}),
50
60
  ...(m.cost ? { cost: m.cost } : {}),
51
61
  ...(excludedReason !== undefined ? { excludedReason } : {}),
52
62
  };
@@ -121,9 +121,13 @@ export function registerSystemRoutes(
121
121
  evictedSessions: number;
122
122
  };
123
123
  };
124
+ // Embed-session-lifecycle diagnostics; `/api/health` reads its snapshot
125
+ // (active/idle ephemeral counts, reaped-by-reason, capacity rejections,
126
+ // acquire reuse hit/miss). See change: add-embed-session-lifecycle.
127
+ embedLifecycle?: { snapshot: () => unknown };
124
128
  },
125
129
  ) {
126
- const { sessionManager, preferencesStore, metaPersistence, config, networkGuard, version, directoryService, piGateway, browserGateway, hydrationMetrics, readEventLoopDelay, eventLoopSpikes, eventStore } = deps;
130
+ const { sessionManager, preferencesStore, metaPersistence, config, networkGuard, version, directoryService, piGateway, browserGateway, hydrationMetrics, readEventLoopDelay, eventLoopSpikes, eventStore, embedLifecycle } = deps;
127
131
 
128
132
  // Quiesce windows for the bridge `server_restarting` broadcast. See change
129
133
  // `fix-restart-bridge-auto-start-race`. Bridges that receive this message
@@ -480,6 +484,17 @@ export function registerSystemRoutes(
480
484
  trimmedEvents: { total: 0, toolExecutionEnd: 0, bySession: {} },
481
485
  evictedSessions: 0,
482
486
  },
487
+ // Embed-session-lifecycle diagnostics (active/idle ephemeral counts,
488
+ // reaped-by-reason, capacity rejections, acquire reuse hit/miss). Failure-
489
+ // isolated so a throwing snapshot can never 500 the health hot path.
490
+ // See change: add-embed-session-lifecycle.
491
+ embedLifecycle: (() => {
492
+ try {
493
+ return embedLifecycle?.snapshot();
494
+ } catch {
495
+ return undefined;
496
+ }
497
+ })(),
483
498
  };
484
499
  });
485
500