@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,340 @@
1
+ /**
2
+ * MessageUpdateCoalescer — bounds the bridge's per-token forwarding cost during
3
+ * assistant streaming.
4
+ *
5
+ * pi's `message_update` carries the FULL accumulated text snapshot, not a delta,
6
+ * and the bridge forwarded every one of them synchronously on pi's own
7
+ * single-threaded loop. A turn of N tokens therefore paid N `JSON.stringify`
8
+ * calls on strings growing to O(N) — O(N²) bytes — and stalled the TUI with it.
9
+ *
10
+ * This module is a transport-agnostic single-slot state machine (only one
11
+ * assistant message streams at a time in pi). The bridge injects `send`, the
12
+ * timer schedule/cancel, and a liveness predicate, so every ordering rule below
13
+ * is provable with fake timers rather than only through the end-to-end bridge
14
+ * test.
15
+ *
16
+ * Three rules are load-bearing and easy to lose:
17
+ *
18
+ * - **Fixed window, not a debounce.** The window is anchored at the arrival of
19
+ * the first pending update and is NOT restarted by later ones. A debounce
20
+ * would starve: a continuous token stream never sees a gap, so the first
21
+ * snapshot would land only at `message_end` and nothing would stream. A fixed
22
+ * window bounds added latency at exactly one window and keeps it
23
+ * non-cumulative.
24
+ * - **TEXT coalesces, everything else flushes then forwards.** Only
25
+ * `text_start`/`text_delta`/`text_end` are snapshot-carrying. Thinking deltas
26
+ * are ADDITIVE, not snapshot-carrying, so coalescing them would silently
27
+ * swallow them. Unknown sub-event types take the same immediate path as the
28
+ * known non-text ones: a future additive sub-event must not be swallowed.
29
+ * - **Drop rule is narrow and fail-open.** ONLY an update whose identity has
30
+ * already been closed by `messageEnd` is discarded. An update with no open
31
+ * message, or with an identity the coalescer never saw open, opens one
32
+ * instead. `npm run reload` re-inits the bridge mid-turn, so the fresh
33
+ * instance never saw that message's `message_start`; dropping there would
34
+ * silence the rest of the turn.
35
+ *
36
+ * The pending slot holds the LIVE event, not a copy: `partial` is the same
37
+ * object pi mutates in place for the whole message, so a copy would only buy a
38
+ * point-in-time distinction the consumer cannot observe — while paying the
39
+ * per-token serialisation this module exists to remove. Snapshots are
40
+ * cumulative and the client is last-wins, so a flushed snapshot carrying
41
+ * content that arrived after the update it nominally represents is safe.
42
+ *
43
+ * See change: coalesce-bridge-message-update-snapshots (design D1–D4, D7).
44
+ */
45
+
46
+ /** Fixed coalescing window: ~20 frames/s, an order of magnitude above a fast
47
+ * provider's per-token interval and below the ~100 ms "instant" threshold. */
48
+ export const COALESCE_WINDOW_MS = 50;
49
+
50
+ /**
51
+ * The snapshot-carrying sub-events. Everything else — including sub-events this
52
+ * build does not recognise — flushes pending text and forwards immediately.
53
+ */
54
+ const TEXT_SUB_EVENTS: ReadonlySet<string> = new Set([
55
+ "text_start",
56
+ "text_delta",
57
+ "text_end",
58
+ ]);
59
+
60
+ /**
61
+ * Closed identities remembered for the drop rule. A straggler arrives within one
62
+ * window of its `message_end`, so a small FIFO is ample; the cap keeps a
63
+ * long-lived session's key set bounded.
64
+ */
65
+ const CLOSED_KEY_MEMORY = 64;
66
+
67
+ export interface MessageUpdateCoalescerOptions<E> {
68
+ /** Write a flushed event. Called at most once per armed window. */
69
+ send: (event: E) => void;
70
+ /** Arm the window timer. Injectable so unit tests drive a fake clock. */
71
+ setTimer: (fn: () => void, ms: number) => ReturnType<typeof setTimeout>;
72
+ /** Cancel an armed window timer (also used to release it from any registry). */
73
+ clearTimer: (timer: ReturnType<typeof setTimeout>) => void;
74
+ /** Window length. Defaults to {@link COALESCE_WINDOW_MS}. */
75
+ windowMs?: number;
76
+ /**
77
+ * Fire-time liveness gate. A window that outlives its bridge (reload,
78
+ * shutdown) must not write to a dead socket, so the timer path re-checks it
79
+ * instead of trusting the state captured when the timer was armed.
80
+ */
81
+ isActive?: () => boolean;
82
+ }
83
+
84
+ interface PendingSnapshot<E> {
85
+ event: E;
86
+ key: string;
87
+ gen: number;
88
+ }
89
+
90
+ export class MessageUpdateCoalescer<E = unknown> {
91
+ private readonly windowMs: number;
92
+ private readonly isActive: () => boolean;
93
+
94
+ /** The single parked snapshot, if any. */
95
+ private pending?: PendingSnapshot<E>;
96
+ /** The armed window timer, if a snapshot is parked. */
97
+ private timer?: ReturnType<typeof setTimeout>;
98
+
99
+ /** The identity of the currently open message, if any. */
100
+ private openKey?: string;
101
+ private openGen?: number;
102
+
103
+ /** Identities already closed by `messageEnd` (bounded FIFO). */
104
+ private readonly closedKeys = new Set<string>();
105
+ private readonly closedOrder: string[] = [];
106
+
107
+ /** Stable fallback identities for messages with no usable `timestamp`. */
108
+ private readonly fallbackIds = new WeakMap<object, string>();
109
+ private fallbackCounter = 0;
110
+
111
+ /** Generations bound to a message object at its `message_start`. */
112
+ private readonly genByMessage = new WeakMap<object, number>();
113
+
114
+ constructor(private readonly opts: MessageUpdateCoalescerOptions<E>) {
115
+ this.windowMs = opts.windowMs ?? COALESCE_WINDOW_MS;
116
+ this.isActive = opts.isActive ?? (() => true);
117
+ }
118
+
119
+ /**
120
+ * Stable identity for a message: `<gen>:<role>:<timestamp>`.
121
+ *
122
+ * `message.id` is unusable (pi stamps it only at post-handler persistence, so
123
+ * it does not exist while the message streams). The generation is folded INTO
124
+ * the key rather than compared separately: `role:timestamp` alone collides for
125
+ * two messages created in the same millisecond (retry loop, mock provider,
126
+ * coarse clock), and a `message_update` carries no generation of its own.
127
+ *
128
+ * `timestamp` is a required pi field, but a fallback keeps a malformed or
129
+ * older event from collapsing every key and swallowing a whole turn: the
130
+ * object identity pins one counter value for the message's lifetime.
131
+ */
132
+ keyOf(gen: number, message: unknown): string {
133
+ const m = (message ?? undefined) as { role?: unknown; timestamp?: unknown } | undefined;
134
+ const role = typeof m?.role === "string" ? m.role : "unknown";
135
+ const timestamp = typeof m?.timestamp === "number" ? String(m.timestamp) : undefined;
136
+ if (timestamp !== undefined) return `${gen}:${role}:${timestamp}`;
137
+ if (!m || typeof m !== "object") return `${gen}:${role}:anonymous`;
138
+ let id = this.fallbackIds.get(m as object);
139
+ if (id === undefined) {
140
+ id = `f${++this.fallbackCounter}`;
141
+ this.fallbackIds.set(m as object, id);
142
+ }
143
+ return `${gen}:${role}:${id}`;
144
+ }
145
+
146
+ /** `message_start` (user or assistant) opens the lifecycle for `key`.
147
+ *
148
+ * `message` (when supplied) is BOUND to `gen`, so later `messageEnd` / `offer`
149
+ * calls can recover the generation this message was actually opened under.
150
+ */
151
+ messageStart(gen: number, key: string, message?: unknown): void {
152
+ // A new identity supersedes a parked snapshot of a different one: flush it
153
+ // rather than let it land after this message begins.
154
+ if (this.pending && this.pending.key !== key) this.flush();
155
+ // Re-opening a key forgets its closed marker (retry/resume of the same id).
156
+ this.closedKeys.delete(key);
157
+ this.openKey = key;
158
+ this.openGen = gen;
159
+ this.bindGeneration(gen, message);
160
+ }
161
+
162
+ /**
163
+ * Bind `message` to the generation assigned at its `message_start`.
164
+ *
165
+ * A `message_update` carries no generation of its own, so a late update for a
166
+ * message that has ALREADY ended would otherwise be keyed under the counter's
167
+ * current value. That key no longer matches the message's closed key, so the
168
+ * drop rule would fail open and the straggler would be forwarded after the
169
+ * next message started. Binding generation to the message object makes the
170
+ * barrier structural rather than dependent on pi's emit discipline.
171
+ */
172
+ bindGeneration(gen: number, message: unknown): void {
173
+ if (message && typeof message === "object") {
174
+ this.genByMessage.set(message as object, gen);
175
+ }
176
+ }
177
+
178
+ /**
179
+ * The generation bound to `message`, else `fallback`.
180
+ *
181
+ * `fallback` covers a message this instance never saw open — `npm run reload`
182
+ * mid-turn re-inits the bridge, and the rest of that turn must still stream.
183
+ */
184
+ generationOf(message: unknown, fallback: number): number {
185
+ if (!message || typeof message !== "object") return fallback;
186
+ return this.genByMessage.get(message as object) ?? fallback;
187
+ }
188
+
189
+ /**
190
+ * `message_end` closes `key`. The bridge flushes the final snapshot BEFORE
191
+ * calling this — closing first would drop the last text of a turn.
192
+ */
193
+ messageEnd(gen: number, key: string): void {
194
+ // A deferred `messageEnd` from an older generation must not close a newer
195
+ // open message.
196
+ if (this.openKey === key && this.openGen === gen) {
197
+ this.openKey = undefined;
198
+ this.openGen = undefined;
199
+ }
200
+ this.markClosed(key);
201
+ }
202
+
203
+ /**
204
+ * Offer a `message_update` for its `gen`.
205
+ *
206
+ * Text-carrying sub-events park (last wins) until the window elapses; every
207
+ * other sub-event flushes pending text and then forwards immediately, so
208
+ * source order is preserved and additive sub-events stay lossless.
209
+ */
210
+ offer(event: E, gen: number): void {
211
+ const key = this.keyOf(gen, (event as { message?: unknown } | undefined)?.message);
212
+ // The ONLY drop: an identity already closed by `messageEnd`.
213
+ if (this.closedKeys.has(key)) return;
214
+
215
+ if (this.openKey !== key) {
216
+ // Either no message is open (reload mid-turn) or this is an identity the
217
+ // barrier never saw. Flush what belongs to the old one, then re-key.
218
+ if (this.pending) this.flush();
219
+ this.openKey = key;
220
+ this.openGen = gen;
221
+ }
222
+
223
+ if (isTextSubEvent(event)) {
224
+ this.park(event, key, gen);
225
+ return;
226
+ }
227
+ // Non-text (and unrecognised): flush first so the snapshot keeps its place
228
+ // in the source order, then forward unmodified.
229
+ this.flush();
230
+ this.opts.send(event);
231
+ }
232
+
233
+ /**
234
+ * Write the parked snapshot now. Synchronous and idempotent — a second call
235
+ * with nothing parked is a no-op. Called by the window timer and by the
236
+ * bridge's flush choke point at every non-`message_update` handler entry.
237
+ */
238
+ flush(): void {
239
+ this.disarm();
240
+ const held = this.pending;
241
+ this.pending = undefined;
242
+ if (!held) return;
243
+ this.opts.send(held.event);
244
+ }
245
+
246
+ /**
247
+ * Session boundary: drop any parked snapshot, cancel the window, close the
248
+ * lifecycle and forget the closed-identity memory (a new session shares none
249
+ * of the old one's messages).
250
+ */
251
+ clear(): void {
252
+ this.disarm();
253
+ this.pending = undefined;
254
+ this.openKey = undefined;
255
+ this.openGen = undefined;
256
+ this.closedKeys.clear();
257
+ this.closedOrder.length = 0;
258
+ }
259
+
260
+ /** Whether a snapshot is parked (test/introspection aid). */
261
+ get hasPending(): boolean {
262
+ return this.pending !== undefined;
263
+ }
264
+
265
+ /** Park `event` as the pending snapshot, arming the window if it is the first. */
266
+ private park(event: E, key: string, gen: number): void {
267
+ const alreadyArmed = this.pending !== undefined;
268
+ this.pending = { event, key, gen };
269
+ if (!alreadyArmed) {
270
+ this.timer = this.opts.setTimer(() => this.onWindow(), this.windowMs);
271
+ }
272
+ }
273
+
274
+ /**
275
+ * Window elapsed. Re-checks liveness: a timer that outlived its bridge
276
+ * (reload/shutdown) drops the snapshot instead of writing to a dead socket.
277
+ */
278
+ private onWindow(): void {
279
+ // `clearTimer` on a fired timer is a harmless no-op that still releases it
280
+ // from the bridge's timer registry.
281
+ this.disarm();
282
+ if (!this.isActive()) {
283
+ this.pending = undefined;
284
+ return;
285
+ }
286
+ const held = this.pending;
287
+ this.pending = undefined;
288
+ if (held) this.opts.send(held.event);
289
+ }
290
+
291
+ /** Release the armed window timer, if any. */
292
+ private disarm(): void {
293
+ if (this.timer === undefined) return;
294
+ this.opts.clearTimer(this.timer);
295
+ this.timer = undefined;
296
+ }
297
+
298
+ private markClosed(key: string): void {
299
+ if (this.closedKeys.has(key)) return;
300
+ this.closedKeys.add(key);
301
+ this.closedOrder.push(key);
302
+ while (this.closedOrder.length > CLOSED_KEY_MEMORY) {
303
+ const evicted = this.closedOrder.shift();
304
+ if (evicted !== undefined) this.closedKeys.delete(evicted);
305
+ }
306
+ }
307
+ }
308
+
309
+ /**
310
+ * Whether an event must flush parked text BEFORE its own handler runs.
311
+ *
312
+ * EVERY event except `message_update` does. Naming the rule here (rather than
313
+ * inlining the comparison at each call site) keeps the bridge's hard invariant —
314
+ * "no non-`message_update` event may reach the wire, defer, or early-return
315
+ * while a snapshot is parked" — a single, unit-testable predicate. A new
316
+ * early-returning branch inherits it because the bridge checks it ONCE at
317
+ * handler entry, before any branch runs.
318
+ *
319
+ * See change: coalesce-bridge-message-update-snapshots (D5).
320
+ */
321
+ export function flushesParkedText(eventType: string): boolean {
322
+ return eventType !== "message_update";
323
+ }
324
+
325
+ /** The `message_update` sub-event type, if the event carries one. */
326
+ function subEventTypeOf(event: unknown): string | undefined {
327
+ const type = (event as { assistantMessageEvent?: { type?: unknown } } | undefined)
328
+ ?.assistantMessageEvent?.type;
329
+ return typeof type === "string" ? type : undefined;
330
+ }
331
+
332
+ /**
333
+ * Whether this `message_update` carries a full text snapshot. Only the three
334
+ * `text_*` sub-events do; an unrecognised type is deliberately NOT treated as
335
+ * text (forwarding it immediately is the safe side of the fail-open choice).
336
+ */
337
+ export function isTextSubEvent(event: unknown): boolean {
338
+ const type = subEventTypeOf(event);
339
+ return type !== undefined && TEXT_SUB_EVENTS.has(type);
340
+ }
@@ -0,0 +1,95 @@
1
+ /**
2
+ * Shared handling for pi 0.84.0's `ModelRegistry.refresh()` contract.
3
+ *
4
+ * BREAKING in 0.84.0: `refresh()` takes `ModelsRefreshOptions` and returns
5
+ * `Promise<ModelsRefreshResult>` — `{ aborted, errors }` — instead of
6
+ * discarding cancellation and per-provider errors. Both dashboard call sites
7
+ * (`command-handler.ts` request_models, `bridge.ts` credentials reload)
8
+ * previously fire-and-forgot it, so a refresh that failed for one provider was
9
+ * indistinguishable from a clean one.
10
+ *
11
+ * A failed refresh is NOT fatal: the registry still serves its last-known
12
+ * catalogue. The contract here is therefore "surface it, keep going" — never
13
+ * "swallow it".
14
+ *
15
+ * See change: update-pi-core-0-84-adopt-apis (design D-refresh).
16
+ */
17
+
18
+ /** `ModelsRefreshResult` as pi-ai declares it. */
19
+ export interface ModelsRefreshResultLike {
20
+ aborted: boolean;
21
+ errors: ReadonlyMap<string, Error>;
22
+ }
23
+
24
+ export function errText(err: unknown): string {
25
+ return err instanceof Error ? err.message : String(err);
26
+ }
27
+
28
+ /**
29
+ * Hard bound on how long a catalogue refresh may block its caller.
30
+ *
31
+ * `request_models` is dispatched from the bridge's SERIALIZED inbound pump
32
+ * (`serialize-bridge-message-pump`), which awaits each handler to completion.
33
+ * A `refresh()` that never settles therefore wedges the pump forever: every
34
+ * later browser message — including `send_prompt` — is queued and never
35
+ * dispatched, so the composer's optimistic bubble never gets its
36
+ * `prompt_received` ack and hangs at `sending`.
37
+ * See change: fix-optimistic-prompt-stuck-sending.
38
+ */
39
+ export const REFRESH_TIMEOUT_MS = 10_000;
40
+
41
+ /**
42
+ * Await a refresh and report its outcome. Returns the result when one was
43
+ * produced, or `undefined` when the refresh threw (already reported).
44
+ *
45
+ * Never rethrows: callers treat a failed catalogue refresh as degraded, not
46
+ * broken.
47
+ */
48
+ export async function reportRefresh(
49
+ pending: Promise<ModelsRefreshResultLike | undefined> | undefined,
50
+ label = "model refresh",
51
+ ): Promise<ModelsRefreshResultLike | undefined> {
52
+ if (!pending) return undefined;
53
+ // Keep the caller's own rejection handling AND make sure a late rejection of
54
+ // the abandoned promise never surfaces as an unhandled rejection.
55
+ pending.catch(() => {});
56
+ let timer: ReturnType<typeof setTimeout> | undefined;
57
+ const TIMED_OUT = Symbol("refresh-timeout");
58
+ let result: ModelsRefreshResultLike | undefined | typeof TIMED_OUT;
59
+ try {
60
+ result = await Promise.race([
61
+ pending,
62
+ new Promise<typeof TIMED_OUT>((resolve) => {
63
+ timer = setTimeout(() => resolve(TIMED_OUT), REFRESH_TIMEOUT_MS);
64
+ }),
65
+ ]);
66
+ } catch (err) {
67
+ console.warn(`[dashboard] ${label} threw:`, errText(err));
68
+ return undefined;
69
+ } finally {
70
+ if (timer) clearTimeout(timer);
71
+ }
72
+ if (result === TIMED_OUT) {
73
+ // Degraded, never broken: the registry still serves its last-known
74
+ // catalogue, and the caller (and the message pump behind it) moves on.
75
+ console.warn(`[dashboard] ${label} timed out after ${REFRESH_TIMEOUT_MS}ms — using the last-known catalogue`);
76
+ return undefined;
77
+ }
78
+ if (!result) return undefined;
79
+
80
+ if (result.aborted) {
81
+ console.warn(`[dashboard] ${label} aborted before completing`);
82
+ }
83
+ // `errors` is keyed by provider id — name the provider, never a bare "failed".
84
+ if (result.errors && result.errors.size > 0) {
85
+ for (const [providerId, err] of result.errors) {
86
+ console.warn(`[dashboard] ${label} failed for provider '${providerId}':`, errText(err));
87
+ }
88
+ }
89
+ return result;
90
+ }
91
+
92
+ /** True when the refresh completed with no abort and no provider error. */
93
+ export function refreshFullySucceeded(result: ModelsRefreshResultLike | undefined): boolean {
94
+ return !!result && !result.aborted && result.errors.size === 0;
95
+ }