@blackbelt-technology/pi-dashboard-extension 0.7.0 → 0.9.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 (265) hide show
  1. package/.pi/skills/browser/SKILL.md +84 -29
  2. package/.pi/skills/browser/UPSTREAM.md +13 -1
  3. package/.pi/skills/browser/references/challenge.md +183 -0
  4. package/.pi/skills/browser/references/dashboard-relay.md +150 -0
  5. package/.pi/skills/browser/references/electron.agent.md +57 -0
  6. package/.pi/skills/browser/references/own-browser.md +305 -0
  7. package/.pi/skills/browser/references/web.agent.md +323 -0
  8. package/.pi/skills/browser/scripts/check-panerelay.sh +157 -0
  9. package/.pi/skills/doctor/SKILL.md +4 -9
  10. package/.pi/skills/doctor/_lib/checks.ts +133 -54
  11. package/.pi/skills/doctor/_lib/derive-tokens.ts +5 -0
  12. package/.pi/skills/doctor/modules/apple-tools.knowledge.hash +1 -0
  13. package/.pi/skills/doctor/modules/apple-tools.md +52 -0
  14. package/.pi/skills/doctor/modules/mcp-builtin.knowledge.hash +1 -0
  15. package/.pi/skills/doctor/modules/mcp-builtin.md +61 -0
  16. package/.pi/skills/doctor/modules/oauth-redirect-base.knowledge.hash +1 -0
  17. package/.pi/skills/doctor/modules/oauth-redirect-base.md +71 -0
  18. package/.pi/skills/doctor/modules/pi-resolution.knowledge.hash +1 -1
  19. package/.pi/skills/doctor/modules/pi-resolution.md +21 -1
  20. package/.pi/skills/doctor/modules/plugins-bridges.md +14 -1
  21. package/.pi/skills/pi-dashboard/SKILL.md +10 -3
  22. package/.pi/skills/pi-dashboard/references/api-reference.agent.md +69 -0
  23. package/.pi/skills/pi-dashboard/scripts/dashboard-bus.ts +4 -4
  24. package/.pi/skills/project-init/SKILL.md +41 -34
  25. package/.pi/skills/project-init/profiles/coding/AGENTS.md.tmpl +0 -23
  26. package/.pi/skills/project-init/profiles/docs/profile.json +1 -1
  27. package/README.md +19 -0
  28. package/agents/DoxTriage.md +80 -0
  29. package/package.json +30 -16
  30. package/src/ask-user-tool.ts +4 -0
  31. package/src/auto-session-namer.ts +486 -70
  32. package/src/autostart-guard.ts +99 -0
  33. package/src/autostart-lock.ts +258 -0
  34. package/src/bridge-activation.ts +26 -0
  35. package/src/bridge-context.ts +106 -23
  36. package/src/bridge-default-model-gate.ts +38 -0
  37. package/src/bridge-polling.ts +148 -0
  38. package/src/bridge-ticket-client.ts +105 -0
  39. package/src/bridge.ts +1760 -350
  40. package/src/canvas-tool.ts +5 -0
  41. package/src/command-handler.ts +392 -71
  42. package/src/connect-target.ts +130 -0
  43. package/src/connection.ts +846 -17
  44. package/src/custom-entry-forward.ts +92 -0
  45. package/src/endpoint-resolution.ts +253 -0
  46. package/src/event-forwarder.ts +42 -0
  47. package/src/extension-identity.ts +59 -0
  48. package/src/flow-event-wiring.ts +125 -3
  49. package/src/followup-buffer.ts +217 -0
  50. package/src/git-dir-watcher.ts +79 -0
  51. package/src/git-poll.ts +45 -12
  52. package/src/git-probe-scheduler.ts +119 -0
  53. package/src/git-tracker.ts +284 -0
  54. package/src/instance-verification.ts +156 -0
  55. package/src/local-token-header.ts +44 -0
  56. package/src/mcp-token-delivery.ts +147 -0
  57. package/src/message-update-coalescer.ts +340 -0
  58. package/src/model-refresh.ts +95 -0
  59. package/src/model-tracker.ts +118 -35
  60. package/src/notify-proxy.ts +36 -0
  61. package/src/path-gate/decide.ts +149 -0
  62. package/src/path-gate/grant-cache.ts +71 -0
  63. package/src/path-gate/grant-link.ts +108 -0
  64. package/src/path-gate/handler.ts +307 -0
  65. package/src/path-gate/index.ts +155 -0
  66. package/src/path-gate/resolve.ts +126 -0
  67. package/src/path-gate/roots.ts +137 -0
  68. package/src/path-gate/suppression.ts +27 -0
  69. package/src/pending-prompt-emitter.ts +59 -0
  70. package/src/pi-env.d.ts +6 -10
  71. package/src/pi-retry-settings.ts +91 -0
  72. package/src/plugin-request-client.ts +114 -0
  73. package/src/poll-cost.ts +40 -0
  74. package/src/pr-status.ts +338 -0
  75. package/src/process-metrics.ts +77 -1
  76. package/src/process-scan-scheduler.ts +137 -0
  77. package/src/process-scanner.ts +226 -247
  78. package/src/project-init/dox-kb-config.ts +3 -0
  79. package/src/project-init/scaffold.ts +1 -4
  80. package/src/project-init/seed-doctrine.ts +23 -60
  81. package/src/prompt-bus.ts +13 -0
  82. package/src/provider-register.ts +92 -21
  83. package/src/remote-registration-gate.ts +102 -0
  84. package/src/retry-tracker.ts +258 -86
  85. package/src/role-manager.ts +38 -91
  86. package/src/role-model-tools.ts +44 -3
  87. package/src/server-auto-start.ts +331 -20
  88. package/src/server-launcher.ts +70 -34
  89. package/src/server-pin-store.ts +92 -0
  90. package/src/session-move.ts +275 -0
  91. package/src/session-sync.ts +75 -20
  92. package/src/slash-dispatch.ts +66 -81
  93. package/src/subagent-fanout-admission.ts +234 -0
  94. package/src/subagent-forward-sites.ts +69 -0
  95. package/src/subagent-frame-buffer.ts +24 -3
  96. package/src/subagent-frame-strip.ts +109 -0
  97. package/src/subagent-saturation.ts +196 -0
  98. package/src/subagent-tick-throttle.ts +250 -0
  99. package/src/terminal-reload.ts +298 -0
  100. package/src/transcript-backfill.ts +151 -0
  101. package/src/transport-diagnostics.ts +76 -0
  102. package/src/tui-prompt-adapter.ts +13 -1
  103. package/src/turn-actionability.ts +20 -0
  104. package/src/ui-stale-guard.ts +58 -0
  105. package/src/usage-drain.ts +167 -0
  106. package/src/vcs-info.ts +261 -63
  107. package/.pi/skills/doctor/AGENTS.md +0 -27
  108. package/.pi/skills/project-init/dox-doctrine.md +0 -104
  109. package/src/AGENTS.md +0 -57
  110. package/src/__tests__/abort-latch.test.ts +0 -97
  111. package/src/__tests__/agent-settled.test.ts +0 -82
  112. package/src/__tests__/artifact-roots.test.ts +0 -83
  113. package/src/__tests__/ask-user-attachments.test.ts +0 -106
  114. package/src/__tests__/ask-user-schema-discriminator.test.ts +0 -141
  115. package/src/__tests__/ask-user-tool.test.ts +0 -571
  116. package/src/__tests__/auto-session-namer.test.ts +0 -339
  117. package/src/__tests__/bridge-default-model-apply.test.ts +0 -242
  118. package/src/__tests__/bridge-default-model-gate.test.ts +0 -50
  119. package/src/__tests__/bridge-entry-id-pi-070.test.ts +0 -174
  120. package/src/__tests__/bridge-followup-chat-order.test.ts +0 -215
  121. package/src/__tests__/bridge-followup-multi-entry.test.ts +0 -202
  122. package/src/__tests__/bridge-followup-mutation.test.ts +0 -217
  123. package/src/__tests__/bridge-followup-queue-drain.test.ts +0 -266
  124. package/src/__tests__/bridge-hasui-flip.test.ts +0 -109
  125. package/src/__tests__/bridge-no-queue-mutation.test.ts +0 -112
  126. package/src/__tests__/bridge-plugin-emit-event.test.ts +0 -44
  127. package/src/__tests__/bridge-queue-update-forward.test.ts +0 -77
  128. package/src/__tests__/bridge-resume-disconnect.test.ts +0 -333
  129. package/src/__tests__/bridge-shadow-queue-gate.test.ts +0 -299
  130. package/src/__tests__/bridge-shutdown-reset.test.ts +0 -159
  131. package/src/__tests__/bridge-slash-command-routing.test.ts +0 -458
  132. package/src/__tests__/bridge-stop-after-turn.test.ts +0 -72
  133. package/src/__tests__/bridge-system-followup.test.ts +0 -163
  134. package/src/__tests__/bridge-thinking-level-select.test.ts +0 -68
  135. package/src/__tests__/browser-skill-registered.test.ts +0 -84
  136. package/src/__tests__/build-provider-catalogue.test.ts +0 -210
  137. package/src/__tests__/command-handler.test.ts +0 -1180
  138. package/src/__tests__/commit-draft.test.ts +0 -100
  139. package/src/__tests__/connection-dropped-frames.test.ts +0 -78
  140. package/src/__tests__/connection-suppress-auto-start.test.ts +0 -97
  141. package/src/__tests__/connection.test.ts +0 -344
  142. package/src/__tests__/credentials-updated.test.ts +0 -26
  143. package/src/__tests__/custom-provider-apikey-roundtrip.test.ts +0 -128
  144. package/src/__tests__/cwd-missing-probe.test.ts +0 -82
  145. package/src/__tests__/dashboard-commands-shipped.test.ts +0 -53
  146. package/src/__tests__/dashboard-context-injector.test.ts +0 -190
  147. package/src/__tests__/dashboard-default-adapter.test.ts +0 -77
  148. package/src/__tests__/dev-build.test.ts +0 -79
  149. package/src/__tests__/doctor/checks.test.ts +0 -121
  150. package/src/__tests__/doctor/modules.test.ts +0 -64
  151. package/src/__tests__/doctor/provenance-hash.test.ts +0 -94
  152. package/src/__tests__/doctor/router.test.ts +0 -143
  153. package/src/__tests__/empty-actionable-guard-config.test.ts +0 -32
  154. package/src/__tests__/empty-actionable-guard.test.ts +0 -73
  155. package/src/__tests__/enrich-model-metadata.test.ts +0 -222
  156. package/src/__tests__/event-forwarder.test.ts +0 -119
  157. package/src/__tests__/extension-slash-command-detection.test.ts +0 -143
  158. package/src/__tests__/filter-enabled-models.test.ts +0 -151
  159. package/src/__tests__/fixtures/turn-actionability-fixtures.ts +0 -69
  160. package/src/__tests__/fork-entryid-timing.test.ts +0 -88
  161. package/src/__tests__/git-info-status.test.ts +0 -73
  162. package/src/__tests__/git-link-builder.test.ts +0 -102
  163. package/src/__tests__/git-poll.test.ts +0 -69
  164. package/src/__tests__/markdown-image-inliner.test.ts +0 -392
  165. package/src/__tests__/model-resolve.test.ts +0 -379
  166. package/src/__tests__/multiselect-dashboard-routing.test.ts +0 -203
  167. package/src/__tests__/multiselect-list.test.ts +0 -137
  168. package/src/__tests__/multiselect-polyfill.test.ts +0 -92
  169. package/src/__tests__/no-session-replacement-calls.test.ts +0 -99
  170. package/src/__tests__/no-tui-multiselect-arm-regression.test.ts +0 -81
  171. package/src/__tests__/openspec-activity-detector.test.ts +0 -337
  172. package/src/__tests__/openspec-cli-shim.test.ts +0 -145
  173. package/src/__tests__/openspec-poller.test.ts +0 -124
  174. package/src/__tests__/pi-version-tracker.test.ts +0 -109
  175. package/src/__tests__/process-metrics.test.ts +0 -47
  176. package/src/__tests__/process-scanner-kill.test.ts +0 -61
  177. package/src/__tests__/process-scanner.test.ts +0 -292
  178. package/src/__tests__/project-init-detect-stack.test.ts +0 -61
  179. package/src/__tests__/project-init-dox-kb-config.test.ts +0 -53
  180. package/src/__tests__/project-init-profiles.test.ts +0 -84
  181. package/src/__tests__/project-init-scaffold.test.ts +0 -139
  182. package/src/__tests__/project-init-seed-doctrine.test.ts +0 -100
  183. package/src/__tests__/project-trust.test.ts +0 -92
  184. package/src/__tests__/prompt-bus-wiring.test.ts +0 -791
  185. package/src/__tests__/prompt-bus.test.ts +0 -513
  186. package/src/__tests__/prompt-expander.test.ts +0 -398
  187. package/src/__tests__/provider-register-native-models.test.ts +0 -182
  188. package/src/__tests__/provider-register-reload.test.ts +0 -498
  189. package/src/__tests__/provider-register-thinking-levels.test.ts +0 -104
  190. package/src/__tests__/retry-tracker.test.ts +0 -152
  191. package/src/__tests__/role-manager.test.ts +0 -585
  192. package/src/__tests__/role-model-tools-registry-readiness.test.ts +0 -114
  193. package/src/__tests__/role-model-tools.test.ts +0 -229
  194. package/src/__tests__/search-files-completeness.test.ts +0 -111
  195. package/src/__tests__/search-files-ranking.test.ts +0 -168
  196. package/src/__tests__/server-auto-start.test.ts +0 -375
  197. package/src/__tests__/server-launcher-launch.test.ts +0 -96
  198. package/src/__tests__/server-launcher.test.ts +0 -101
  199. package/src/__tests__/server-probe.test.ts +0 -25
  200. package/src/__tests__/session-switch.test.ts +0 -139
  201. package/src/__tests__/session-sync.test.ts +0 -243
  202. package/src/__tests__/single-derivation-guard.test.ts +0 -39
  203. package/src/__tests__/source-detector.test.ts +0 -88
  204. package/src/__tests__/stats-extractor.test.ts +0 -92
  205. package/src/__tests__/subagent-frame-buffer.test.ts +0 -239
  206. package/src/__tests__/tool-result-image-inliner.test.ts +0 -206
  207. package/src/__tests__/tui-prompt-adapter.test.ts +0 -213
  208. package/src/__tests__/turn-actionability.test.ts +0 -86
  209. package/src/__tests__/ui-decorators.test.ts +0 -309
  210. package/src/__tests__/ui-modules.test.ts +0 -293
  211. package/src/__tests__/vcs-info.test.ts +0 -265
  212. package/src/__tests__/visibility-intent.test.ts +0 -43
  213. package/src/__tests__/watchdog.test.ts +0 -161
  214. package/src/abort-latch.ts.AGENTS.md +0 -3
  215. package/src/agent-settled.ts +0 -72
  216. package/src/agent-settled.ts.AGENTS.md +0 -3
  217. package/src/artifact-roots.ts.AGENTS.md +0 -3
  218. package/src/ask-user-attachments.ts.AGENTS.md +0 -3
  219. package/src/ask-user-tool.ts.AGENTS.md +0 -3
  220. package/src/auto-session-namer.ts.AGENTS.md +0 -3
  221. package/src/bridge-context.ts.AGENTS.md +0 -3
  222. package/src/bridge-default-model-gate.ts.AGENTS.md +0 -3
  223. package/src/bridge.ts.AGENTS.md +0 -3
  224. package/src/command-handler.ts.AGENTS.md +0 -3
  225. package/src/commit-draft-agent.ts.AGENTS.md +0 -3
  226. package/src/commit-draft.ts.AGENTS.md +0 -3
  227. package/src/connection.ts.AGENTS.md +0 -3
  228. package/src/dashboard-context-injector.ts.AGENTS.md +0 -3
  229. package/src/dashboard-default-adapter.ts.AGENTS.md +0 -3
  230. package/src/dev-build.ts.AGENTS.md +0 -3
  231. package/src/empty-actionable-guard-config.ts.AGENTS.md +0 -3
  232. package/src/empty-actionable-guard.ts.AGENTS.md +0 -3
  233. package/src/event-forwarder.ts.AGENTS.md +0 -3
  234. package/src/flow-event-wiring.ts.AGENTS.md +0 -3
  235. package/src/git-link-builder.ts.AGENTS.md +0 -3
  236. package/src/git-poll.ts.AGENTS.md +0 -3
  237. package/src/hasui-flip.ts.AGENTS.md +0 -3
  238. package/src/markdown-image-inliner.ts.AGENTS.md +0 -3
  239. package/src/model-tracker.ts.AGENTS.md +0 -3
  240. package/src/multiselect-decode.ts.AGENTS.md +0 -3
  241. package/src/multiselect-list.ts.AGENTS.md +0 -3
  242. package/src/multiselect-polyfill.ts.AGENTS.md +0 -3
  243. package/src/openspec-cli-shim.ts.AGENTS.md +0 -7
  244. package/src/process-metrics.ts.AGENTS.md +0 -3
  245. package/src/process-scanner.ts.AGENTS.md +0 -3
  246. package/src/project-init/AGENTS.md +0 -12
  247. package/src/project-trust.ts.AGENTS.md +0 -3
  248. package/src/prompt-bus.ts.AGENTS.md +0 -3
  249. package/src/prompt-expander.ts.AGENTS.md +0 -3
  250. package/src/provider-register.ts.AGENTS.md +0 -3
  251. package/src/retry-tracker.ts.AGENTS.md +0 -3
  252. package/src/role-manager.ts.AGENTS.md +0 -3
  253. package/src/role-model-tools.ts.AGENTS.md +0 -3
  254. package/src/server-auto-start.ts.AGENTS.md +0 -3
  255. package/src/server-launcher.ts.AGENTS.md +0 -3
  256. package/src/session-sync.ts.AGENTS.md +0 -3
  257. package/src/slash-dispatch.ts.AGENTS.md +0 -3
  258. package/src/source-detector.ts.AGENTS.md +0 -3
  259. package/src/subagent-frame-buffer.ts.AGENTS.md +0 -3
  260. package/src/tool-result-image-inliner.ts.AGENTS.md +0 -3
  261. package/src/tui-prompt-adapter.ts.AGENTS.md +0 -3
  262. package/src/turn-actionability.ts.AGENTS.md +0 -3
  263. package/src/ui-modules.ts.AGENTS.md +0 -3
  264. package/src/vcs-info.ts.AGENTS.md +0 -3
  265. package/src/visibility-intent.ts.AGENTS.md +0 -3
@@ -0,0 +1,76 @@
1
+ /**
2
+ * Transport diagnostics that survive the default configuration.
3
+ *
4
+ * The endpoint decision (10.1) and every refusal to re-target (10.2) are the
5
+ * two facts you need to answer "why is this session on that dashboard". Both
6
+ * were `console.log` only, and pi's stdout is discarded whenever
7
+ * `keeperLog.capturePiOutput` is false — which is the default. So they also
8
+ * travel to the server, which writes its own stdout to `server.log`.
9
+ *
10
+ * Buffered, because endpoint resolution happens before a socket exists and
11
+ * before a sessionId is known: reporting only when live would drop precisely
12
+ * the diagnostic that explains a misrouted bridge. Bounded, because a bridge
13
+ * that never registers must not accumulate them forever.
14
+ *
15
+ * See change: add-pi-gateway-transport-identity (tasks 10.1, 10.2, 10.5).
16
+ */
17
+
18
+ // Subpath import, not the package barrel: the barrel does not resolve here
19
+ // (the same trap that yields "getDashboardConfigDir is not a function").
20
+ import type { BridgeDiagnosticEvent } from "@blackbelt-technology/pi-dashboard-shared/protocol.js";
21
+
22
+ interface TransportDiagnostic {
23
+ event: BridgeDiagnosticEvent;
24
+ detail: string;
25
+ }
26
+
27
+ interface DiagnosticsSink {
28
+ send: (message: unknown) => void;
29
+ /** Undefined until `session_register` has settled on an id. */
30
+ getSessionId: () => string | undefined;
31
+ }
32
+
33
+ export interface TransportDiagnostics {
34
+ record: (d: TransportDiagnostic) => void;
35
+ attach: (sink: DiagnosticsSink) => void;
36
+ }
37
+
38
+ const DEFAULT_MAX_BUFFERED = 32;
39
+
40
+ export function createTransportDiagnostics(
41
+ opts?: { maxBuffered?: number },
42
+ ): TransportDiagnostics {
43
+ const max = opts?.maxBuffered ?? DEFAULT_MAX_BUFFERED;
44
+ const buffered: TransportDiagnostic[] = [];
45
+ let sink: DiagnosticsSink | undefined;
46
+
47
+ const flush = (): void => {
48
+ if (!sink) return;
49
+ const sessionId = sink.getSessionId();
50
+ if (!sessionId) return;
51
+ // Splice first: a throwing `send` must not replay what it already took,
52
+ // and must not strand the entries behind it either.
53
+ const pending = buffered.splice(0);
54
+ for (let i = 0; i < pending.length; i++) {
55
+ try {
56
+ sink.send({ type: "bridge_diagnostic", sessionId, ...pending[i] });
57
+ } catch {
58
+ // Best-effort by contract, exactly like `inbound_drop_report`.
59
+ }
60
+ }
61
+ };
62
+
63
+ return {
64
+ record(d) {
65
+ buffered.push(d);
66
+ // Drop the OLDEST on overflow — the newest refusals describe the state
67
+ // the operator is actually looking at.
68
+ while (buffered.length > max) buffered.shift();
69
+ flush();
70
+ },
71
+ attach(next) {
72
+ sink = next;
73
+ flush();
74
+ },
75
+ };
76
+ }
@@ -34,6 +34,18 @@ function promptMessage(prompt: PromptRequest): string {
34
34
  : "";
35
35
  }
36
36
 
37
+ /**
38
+ * `select` question as the terminal shows it. A `select` may carry
39
+ * `metadata.plainMessage` (plain text, no markdown): the TUI renders only the
40
+ * question + options, so decision context a dashboard card shows from metadata
41
+ * (agent path gate: session cwd, "can't be remembered here") must ride the question.
42
+ * See change: ask-agent-file-access-in-chat.
43
+ */
44
+ function selectQuestion(prompt: PromptRequest): string {
45
+ const plain = prompt.metadata?.plainMessage;
46
+ return typeof plain === "string" && plain ? `${prompt.question}\n\n${plain}` : prompt.question;
47
+ }
48
+
37
49
  /** Create the PromptBus adapter that presents supported prompts in Pi's TUI. */
38
50
  export function createTuiPromptAdapter(
39
51
  ui: TuiPromptUi,
@@ -53,7 +65,7 @@ export function createTuiPromptAdapter(
53
65
  let answer: string | boolean | undefined;
54
66
 
55
67
  if (prompt.type === "select" && prompt.options && ui.select) {
56
- answer = await ui.select(prompt.question, prompt.options, {
68
+ answer = await ui.select(selectQuestion(prompt), prompt.options, {
57
69
  signal: controller.signal,
58
70
  });
59
71
  } else if (prompt.type === "input" && ui.input) {
@@ -38,6 +38,18 @@ export interface ClassifiableTurn {
38
38
  */
39
39
  const TRUNCATION_STOP_REASONS: ReadonlySet<string> = new Set(["length", "max_tokens", "maxTokens"]);
40
40
 
41
+ /**
42
+ * Stop reasons that mark an IN-PROGRESS (not terminal-empty) turn. pi ≥ 0.83.0
43
+ * emits `"pending"` for a partial streaming message (`#7151`). A `"pending"`
44
+ * turn with no visible text/tool call yet is mid-stream — NOT the clean-but-empty
45
+ * completion the empty-actionable guard exists to catch — so it classifies as
46
+ * `normal` and never trips the guard. Genuinely idle (non-`"pending"`) empty
47
+ * turns still fall through to `empty-actionable`. Reachability at `agent_end`:
48
+ * treated defensively — if `"pending"` never reaches the terminal message this
49
+ * branch is simply inert. See change: update-pi-core-0-83-adopt-apis.
50
+ */
51
+ const IN_PROGRESS_STOP_REASONS: ReadonlySet<string> = new Set(["pending"]);
52
+
41
53
  /**
42
54
  * Content-part `type` values that count as a tool call. pi emits `"toolCall"`;
43
55
  * the others are accepted defensively so a normalized/adapter variant is never
@@ -111,6 +123,14 @@ export function classifyTurnActionability(turn: ClassifiableTurn | undefined | n
111
123
  return "truncated";
112
124
  }
113
125
 
126
+ // A mid-stream partial (pi ≥ 0.83.0 `"pending"`) has produced no terminal
127
+ // output yet but is NOT an empty completion — classify it in-progress so the
128
+ // empty-actionable guard does not fire on it. Only `"pending"` is exempted;
129
+ // any other empty non-error turn still falls through to the guard below.
130
+ if (typeof turn.stopReason === "string" && IN_PROGRESS_STOP_REASONS.has(turn.stopReason)) {
131
+ return "normal";
132
+ }
133
+
114
134
  // No visible text, no tool call, no error, not a truncation → the clean-but-
115
135
  // empty completion (thinking-only or empty). This is the captured defect.
116
136
  return "empty-actionable";
@@ -0,0 +1,58 @@
1
+ /**
2
+ * Guard for `ctx.ui` access that may land AFTER the extension context was
3
+ * invalidated.
4
+ *
5
+ * WHY THIS EXISTS
6
+ * ---------------
7
+ * `autoStartServer()` in `bridge.ts` is long-running and asynchronous. Its
8
+ * `notify` / `onLaunchStart` / `onLaunchEnd` callbacks and its terminal
9
+ * `.then()` / `.catch()` continuation all capture the extension `ctx` and touch
10
+ * `ctx.ui`. Any of them can run after the session has been replaced or reloaded.
11
+ *
12
+ * Since pi 0.84, `AgentSession.dispose()` calls
13
+ * `extensionRunner.invalidate(...)`, after which EVERY `ctx.ui` getter throws
14
+ * (`ExtensionRunner.assertActive`). Inside a floating-promise continuation that
15
+ * throw has no owner: it surfaces as an unhandled rejection and kills the pi
16
+ * process mid-session. Observed as a session that answers a prompt and then
17
+ * dies, leaving the composer disabled — which broke every faux browser-E2E
18
+ * round-trip.
19
+ *
20
+ * WHY ATTEMPT-AND-SWALLOW
21
+ * -----------------------
22
+ * Staleness is not observable. `assertActive()` throws rather than returning a
23
+ * verdict, `staleMessage` is internal, and pi exposes no `isActive` / `isStale`
24
+ * predicate on the public surface. There is no test-then-call option, so the
25
+ * only available guard is to attempt the call and absorb the failure.
26
+ *
27
+ * That is sound here because every guarded call site is UI presentation for a
28
+ * session that no longer exists: the widget was torn down with the old session
29
+ * and the notification has no surface left to render on. Dropping the work is
30
+ * the correct outcome, not merely the safe one.
31
+ *
32
+ * SCOPE — keep this tight
33
+ * -----------------------
34
+ * Wrap ONLY `ctx.ui` access. Auto-start's own failures (discovery, launching,
35
+ * port reconciliation) must keep travelling to their existing `.catch()`
36
+ * handler; routing them through here would hide real faults.
37
+ *
38
+ * See change: fix-bridge-stale-ctx-crash.
39
+ */
40
+
41
+ /**
42
+ * Run a `ctx.ui` thunk, absorbing the failure if the context has been
43
+ * invalidated. Returns the thunk's value, or `undefined` when it could not run.
44
+ *
45
+ * Any throw from a UI call is absorbed, not just the invalidation error:
46
+ * matching pi's message text would silently re-arm the crash the moment that
47
+ * copy changed, and a presentation call failing is never worth terminating the
48
+ * process over.
49
+ */
50
+ export function runUiSafely<T>(fn: () => T): T | undefined {
51
+ try {
52
+ return fn();
53
+ } catch {
54
+ // Context invalidated by session replacement / reload, or the TUI is gone.
55
+ // Nothing to present to — drop the call.
56
+ return undefined;
57
+ }
58
+ }
@@ -0,0 +1,167 @@
1
+ /**
2
+ * Bridge-side drain of non-message usage entries (design D2).
3
+ *
4
+ * pi records model-attributed usage that is not an assistant message as
5
+ * session entries: `usage` entries (cache warming, …) and the `usage` of
6
+ * compaction / branch-summary entries. pi dispatches no event for them to
7
+ * extensions, so the bridge reads `ctx.sessionManager.getEntries()` past a
8
+ * cursor `{ sessionId, lastEntryId }` at its drain points (`turn_end`,
9
+ * `agent_settled`, `cache_warming_decision`, `session_shutdown`) and forwards
10
+ * each allowlisted entry as a `usage_recorded` message.
11
+ *
12
+ * Invariants:
13
+ * - Baseline + seed share ONE snapshot: `baseline()` sets the cursor to the
14
+ * snapshot's last entry and returns that snapshot's full totals (every kind)
15
+ * — the `usageSeed` sent with `session_register`. Nothing in the snapshot is
16
+ * ever forwarded.
17
+ * - Keyed by session id, not session-file path (pi creates the file lazily).
18
+ * - A reconnect never touches the cursor.
19
+ * - A vanished `lastEntryId` (or a different session id) re-baselines and
20
+ * forwards nothing; no seed is resent.
21
+ * - Message entries are never forwarded (tool-result usage's live source is
22
+ * the forwarded `message_end`).
23
+ *
24
+ * See change: count-non-message-usage.
25
+ */
26
+ import type { UsageRecordedMessage } from "@blackbelt-technology/pi-dashboard-shared/protocol.js";
27
+ import {
28
+ drainableEntryUsage,
29
+ sumEntryUsage,
30
+ type UsageTotals,
31
+ } from "@blackbelt-technology/pi-dashboard-shared/usage-totals.js";
32
+
33
+ /** The slice of pi's `ReadonlySessionManager` the drain reads. */
34
+ export interface DrainSessionManager {
35
+ getSessionId(): string;
36
+ getEntries(): readonly unknown[];
37
+ }
38
+
39
+ interface Cursor {
40
+ sessionId: string;
41
+ lastEntryId: string | null;
42
+ }
43
+
44
+ function lastIdOf(entries: readonly unknown[]): string | null {
45
+ const last = entries[entries.length - 1] as { id?: unknown } | undefined;
46
+ return typeof last?.id === "string" ? last.id : null;
47
+ }
48
+
49
+ export class UsageDrain {
50
+ private cursor: Cursor | null = null;
51
+
52
+ /**
53
+ * Take one `getEntries()` snapshot, move the cursor to its end, and return
54
+ * its full usage totals (the `usageSeed`).
55
+ */
56
+ baseline(sm: DrainSessionManager): UsageTotals {
57
+ const entries = sm.getEntries();
58
+ this.cursor = { sessionId: sm.getSessionId(), lastEntryId: lastIdOf(entries) };
59
+ return sumEntryUsage(entries);
60
+ }
61
+
62
+ /** Cursor snapshot (tests / diagnostics). */
63
+ getCursor(): Readonly<Cursor> | null {
64
+ return this.cursor ? { ...this.cursor } : null;
65
+ }
66
+
67
+ /**
68
+ * Hand each allowlisted usage-bearing entry appended after the cursor to
69
+ * `send` (default: collect and return), advancing the cursor entry by entry
70
+ * only AFTER the hand-off succeeds; a throwing `send` leaves the failed
71
+ * entry and everything after it for the next drain. One `getEntries()` copy
72
+ * plus a reverse scan to `lastEntryId`.
73
+ */
74
+ drain(sm: DrainSessionManager, send?: (msg: UsageRecordedMessage) => void): UsageRecordedMessage[] {
75
+ const sessionId = sm.getSessionId();
76
+ const entries = sm.getEntries();
77
+ const cursor = this.cursor;
78
+ if (!cursor || cursor.sessionId !== sessionId) {
79
+ this.cursor = { sessionId, lastEntryId: lastIdOf(entries) };
80
+ return [];
81
+ }
82
+ let start = 0;
83
+ if (cursor.lastEntryId !== null) {
84
+ start = -1;
85
+ for (let i = entries.length - 1; i >= 0; i--) {
86
+ if ((entries[i] as { id?: unknown } | undefined)?.id === cursor.lastEntryId) {
87
+ start = i + 1;
88
+ break;
89
+ }
90
+ }
91
+ if (start === -1) {
92
+ // The last forwarded entry is gone (tree rewrite): re-baseline, forward nothing.
93
+ this.cursor = { sessionId, lastEntryId: lastIdOf(entries) };
94
+ return [];
95
+ }
96
+ }
97
+ const out: UsageRecordedMessage[] = [];
98
+ const emit = send ?? ((msg: UsageRecordedMessage) => { out.push(msg); });
99
+ for (let i = start; i < entries.length; i++) {
100
+ const entry = entries[i] as { id?: unknown };
101
+ const u = drainableEntryUsage(entry);
102
+ if (u) {
103
+ emit({
104
+ type: "usage_recorded",
105
+ sessionId,
106
+ kind: u.kind,
107
+ usage: u.usage,
108
+ ...(u.provider !== undefined ? { provider: u.provider } : {}),
109
+ ...(u.model !== undefined ? { model: u.model } : {}),
110
+ ...(typeof entry.id === "string" ? { entryId: entry.id } : {}),
111
+ });
112
+ }
113
+ if (typeof entry.id === "string") cursor.lastEntryId = entry.id;
114
+ }
115
+ return out;
116
+ }
117
+ }
118
+
119
+ /**
120
+ * Drain and send. Never throws: a drain point must not disturb the pi event it
121
+ * piggybacks on (`cache_warming_decision` in particular).
122
+ */
123
+ export function drainUsageAndSend(
124
+ drain: UsageDrain,
125
+ sm: DrainSessionManager | undefined | null,
126
+ send: (msg: UsageRecordedMessage) => void,
127
+ ): void {
128
+ try {
129
+ if (!sm) return;
130
+ drain.drain(sm, send);
131
+ } catch (err) {
132
+ console.error("[dashboard] usage drain failed:", err);
133
+ }
134
+ }
135
+
136
+ /**
137
+ * Observe-only `cache_warming_decision` handler: a drain point that returns
138
+ * no decision override (`undefined`), so pi applies its own `warm`/`stop`.
139
+ * Synchronous and self-guarded — never throws back into pi.
140
+ */
141
+ export function makeCacheWarmingDecisionHandler(runDrain: (ctx: unknown) => void) {
142
+ return (_event: unknown, ctx: unknown): undefined => {
143
+ try {
144
+ runDrain(ctx);
145
+ } catch (err) {
146
+ console.error("[dashboard] cache_warming_decision drain failed:", err);
147
+ }
148
+ return undefined;
149
+ };
150
+ }
151
+
152
+ /**
153
+ * Shutdown ordering: flush undrained usage for the outgoing session BEFORE its
154
+ * `session_unregister` (which ends the session server-side and drives the
155
+ * final sidecar write), on the same socket.
156
+ */
157
+ export function sendShutdownUsageThenUnregister(
158
+ runDrain: () => void,
159
+ sendUnregister: () => void,
160
+ ): void {
161
+ try {
162
+ runDrain();
163
+ } catch (err) {
164
+ console.error("[dashboard] shutdown usage drain failed:", err);
165
+ }
166
+ sendUnregister();
167
+ }