@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,92 @@
1
+ /**
2
+ * Pure mapping for pi `entry_appended` events → the dashboard `custom_entry`
3
+ * protocol event (change: render-inline-reasoning-and-custom-entries, D2).
4
+ *
5
+ * `pi.appendEntry(customType, data)` persists a `CustomEntry` and fires
6
+ * `entry_appended`; before this module the bridge did not subscribe, so
7
+ * generic custom entries rendered as nothing at all. The mapping forwards
8
+ * ONLY `customType` / `data` / `entryId` — the entry's other fields are
9
+ * transport trivia the renderer never needs.
10
+ *
11
+ * `customType: "flow-event"` returns null: pi-flows appends those entries
12
+ * live itself, so forwarding them would double-render alongside the
13
+ * dedicated flow card. Non-`custom` entry types are likewise not ours to
14
+ * forward.
15
+ */
16
+
17
+ export interface CustomEntryForwardData {
18
+ customType: string;
19
+ data: unknown;
20
+ entryId: string;
21
+ /**
22
+ * Server-stamped custom event group id (design D1,
23
+ * add-custom-event-group-filters). The extension never sets it: resolution
24
+ * + stamping happen in the dashboard server before browser ingest.
25
+ */
26
+ groupId?: string;
27
+ }
28
+
29
+ /**
30
+ * Map one pi entry to the custom_entry payload, or null when the entry must
31
+ * NOT be forwarded (non-custom type, missing/empty customType, flow-event).
32
+ */
33
+ export function toCustomEntryForward(entry: unknown): CustomEntryForwardData | null {
34
+ if (!entry || typeof entry !== "object") return null;
35
+ const e = entry as Record<string, unknown>;
36
+ if (e.type !== "custom") return null;
37
+ if (typeof e.customType !== "string" || e.customType === "") return null;
38
+ if (e.customType === "flow-event") return null;
39
+ return {
40
+ customType: e.customType,
41
+ data: e.data,
42
+ entryId: typeof e.id === "string" ? e.id : String(e.id ?? ""),
43
+ };
44
+ }
45
+
46
+ export interface CustomMessageForwardData {
47
+ message: {
48
+ role: "custom";
49
+ customType: string;
50
+ content: unknown;
51
+ display: boolean | undefined;
52
+ details: unknown;
53
+ /** Server-stamped (design D1); never set by the extension. */
54
+ groupId?: string;
55
+ };
56
+ entryId: string | undefined;
57
+ }
58
+
59
+ /**
60
+ * Map one persisted custom MESSAGE (pi.sendMessage) to the `message_end`
61
+ * payload the client reducer's role=custom arm expects, or null when it must
62
+ * NOT be forwarded.
63
+ *
64
+ * EXACT `display === false` exclusion (D5): pi normalizes content but NOT
65
+ * display, so an untyped extension omitting the flag yields undefined — which
66
+ * RENDERS (absent flag = meant to be seen). Mirrors the state-replay arm so
67
+ * live and replay forward identically.
68
+ */
69
+ export function toCustomMessageForward(m: {
70
+ customType: unknown;
71
+ content: unknown;
72
+ display?: unknown;
73
+ details?: unknown;
74
+ entryId?: unknown;
75
+ }): CustomMessageForwardData | null {
76
+ if (!m || typeof m.customType !== "string" || m.customType === "") return null;
77
+ if (m.display === false) return null;
78
+ // flow-event parity with the entry path: pi-flows does not send custom
79
+ // MESSAGES today, but a spoofing customType must not lease the generic
80
+ // card either. See change: render-inline-reasoning-and-custom-entries.
81
+ if (m.customType === "flow-event") return null;
82
+ return {
83
+ message: {
84
+ role: "custom",
85
+ customType: m.customType,
86
+ content: m.content,
87
+ display: m.display as boolean | undefined,
88
+ details: m.details,
89
+ },
90
+ entryId: typeof m.entryId === "string" ? m.entryId : undefined,
91
+ };
92
+ }
@@ -0,0 +1,253 @@
1
+ /**
2
+ * The ONLY place the bridge chooses an endpoint.
3
+ *
4
+ * The hijack class (`fix-bridge-mdns-migration-hijack`,
5
+ * `fix-bridge-autostart-port-resolution`) exists because the bridge *asks the
6
+ * network* where its dashboard is, and the answer can be wrong — stale, or
7
+ * simply another machine's. Two rules kill it:
8
+ *
9
+ * D3 precedence — explicit configuration is PINNED and outranks anything
10
+ * discovered. Discovery MAY suggest; it MAY NEVER override.
11
+ * D4 stickiness — once registered with instance X, a bridge re-targets only
12
+ * when the current endpoint is unpinned AND has failed AND
13
+ * the candidate's identity verifies.
14
+ *
15
+ * Absence of a local dashboard resolves to *unavailable*, never to a
16
+ * discovered substitute: silently swapping in whatever answered is exactly the
17
+ * failure being removed. A discovered candidate is still reported as a
18
+ * `suggestion` so an operator can act on it deliberately.
19
+ *
20
+ * See change: add-pi-gateway-transport-identity (D3, D4).
21
+ */
22
+
23
+ /** An endpoint plus the instance identity expected to answer at it. */
24
+ interface EndpointCandidate {
25
+ endpoint: string;
26
+ instanceId?: string;
27
+ }
28
+
29
+ export interface EndpointInputs {
30
+ /** `PI_DASHBOARD_SOCKET` — an explicit local socket path. */
31
+ socketEnv?: string;
32
+ /** `PI_DASHBOARD_URL` — an explicit endpoint (local or remote). */
33
+ urlEnv?: string;
34
+ /** Operator-configured pinned instance. */
35
+ pinnedInstance?: EndpointCandidate;
36
+ /** The HOME-derived rendezvous record written by the lock holder. */
37
+ record?: EndpointCandidate;
38
+ /** A paired remote dashboard (remote-join). */
39
+ pairedRemote?: EndpointCandidate;
40
+ /** An mDNS/discovery candidate. Suggestion only — never selected. */
41
+ discovered?: EndpointCandidate;
42
+ }
43
+
44
+ export type EndpointSource =
45
+ | "PI_DASHBOARD_SOCKET"
46
+ | "PI_DASHBOARD_URL"
47
+ | "pinned-instance"
48
+ | "rendezvous-record"
49
+ | "paired-remote";
50
+
51
+ export type EndpointResolution =
52
+ | {
53
+ available: true;
54
+ url: string;
55
+ source: EndpointSource;
56
+ /** Pinned endpoints refuse every re-target (D3/D4). */
57
+ pinned: boolean;
58
+ instanceId?: string;
59
+ /** A discovered candidate that lost. Informational only. */
60
+ suggestion?: EndpointCandidate;
61
+ }
62
+ | {
63
+ available: false;
64
+ reason: string;
65
+ suggestion?: EndpointCandidate;
66
+ };
67
+
68
+ /** Trim, treating whitespace-only as unset. */
69
+ function present(s: string | undefined): string | undefined {
70
+ const t = s?.trim();
71
+ return t ? t : undefined;
72
+ }
73
+
74
+ /**
75
+ * Loopback hosts, lexically: the reserved localhost names plus the loopback
76
+ * literal addresses. Hostname-as-hint classification (design D3): a `*.local`
77
+ * mDNS name is REMOTE even though some such names resolve to loopback — the
78
+ * poisoned advertisement was exactly a `*.local` name, and treating it as
79
+ * remote is the strict side of the rule: it can only decline a migration,
80
+ * never adopt a wrong endpoint, and the health gate still guards any
81
+ * legitimate move. DNS resolution is deliberately NOT performed here — the
82
+ * ambiguous "`.local` that resolves loopback" shape is removed at the source
83
+ * by the advertisement gate, and reachability is verified independently.
84
+ */
85
+ function isLoopbackHost(host: string): boolean {
86
+ const h = host.trim().toLowerCase().replace(/^\[/, "").replace(/\]$/, "");
87
+ if (h === "localhost" || h.endsWith(".localhost")) return true;
88
+ if (h === "::1") return true;
89
+ if (/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(h)) return true;
90
+ return false;
91
+ }
92
+
93
+ /**
94
+ * {@link isLoopbackHost} for a URL (any scheme). A URL that cannot be parsed
95
+ * classifies REMOTE: the strict side never displaces an established loopback
96
+ * connection on a guess.
97
+ */
98
+ export function isLoopbackEndpoint(url: string): boolean {
99
+ try {
100
+ return isLoopbackHost(new URL(url).hostname);
101
+ } catch {
102
+ return false;
103
+ }
104
+ }
105
+
106
+ /** `ws+unix://<path>:/` — the `ws` package's unix-socket URL form. */
107
+ function socketUrl(socketPath: string): string {
108
+ return `ws+unix://${socketPath}:/`;
109
+ }
110
+
111
+ /**
112
+ * Resolve the endpoint to dial, highest precedence first.
113
+ *
114
+ * Deliberately pure: every input is passed in, so the ladder is a decision
115
+ * table a test can enumerate rather than an emergent property of I/O order.
116
+ */
117
+ export function resolveEndpoint(inputs: EndpointInputs): EndpointResolution {
118
+ const suggestion = inputs.discovered;
119
+
120
+ const socketEnv = present(inputs.socketEnv);
121
+ if (socketEnv) {
122
+ return {
123
+ available: true,
124
+ url: socketUrl(socketEnv),
125
+ source: "PI_DASHBOARD_SOCKET",
126
+ pinned: true,
127
+ suggestion,
128
+ };
129
+ }
130
+
131
+ const urlEnv = present(inputs.urlEnv);
132
+ if (urlEnv) {
133
+ return { available: true, url: urlEnv, source: "PI_DASHBOARD_URL", pinned: true, suggestion };
134
+ }
135
+
136
+ const ladder: Array<[EndpointCandidate | undefined, EndpointSource, boolean]> = [
137
+ [inputs.pinnedInstance, "pinned-instance", true],
138
+ [inputs.record, "rendezvous-record", false],
139
+ [inputs.pairedRemote, "paired-remote", false],
140
+ ];
141
+ for (const [candidate, source, pinned] of ladder) {
142
+ const endpoint = present(candidate?.endpoint);
143
+ if (endpoint) {
144
+ return {
145
+ available: true,
146
+ url: endpoint,
147
+ source,
148
+ pinned,
149
+ instanceId: candidate?.instanceId,
150
+ suggestion,
151
+ };
152
+ }
153
+ }
154
+
155
+ return {
156
+ available: false,
157
+ reason:
158
+ "no local dashboard available: no PI_DASHBOARD_SOCKET, no PI_DASHBOARD_URL, " +
159
+ "no pinned instance, no rendezvous record under this HOME, and no paired remote",
160
+ suggestion,
161
+ };
162
+ }
163
+
164
+ /**
165
+ * The per-instance id file that belongs to a pinned gateway socket, or
166
+ * `undefined` when the path is not one.
167
+ *
168
+ * WHY THE SOCKET AND NOT THE RECORD. A bridge pinned via `PI_DASHBOARD_SOCKET`
169
+ * — which is every session the dashboard spawns (task 2.0f) — had no instance
170
+ * id at all, so `/dashboard-where` answered `unverified` in the one case a
171
+ * user would ever ask. The rendezvous record cannot fill that gap: it names
172
+ * the HOME's OWNER, so a session pinned to an ATTACH instance's socket would
173
+ * be told a confident wrong id, which is worse than admitting ignorance. The
174
+ * socket path is the only artefact that names the instance on the other end —
175
+ * `gateway-<piPort>.sock` and `instances/<piPort>.id` are siblings under the
176
+ * same `0700` directory.
177
+ *
178
+ * No network verification is needed for this source: the socket is `0600`
179
+ * inside a `0700` dir, so the kernel already decided the caller is the same OS
180
+ * user (D5), and the id file is in that same directory. Verification stays on
181
+ * the record-sourced path, where the endpoint is a network address some other
182
+ * instance could be answering on.
183
+ *
184
+ * Pure by design, like the rest of this module: the caller does the reading.
185
+ *
186
+ * See change: add-pi-gateway-transport-identity (task 9.6).
187
+ */
188
+ export function instanceIdFileForSocket(socketPathOrUrl: string): string | undefined {
189
+ const raw = present(socketPathOrUrl);
190
+ if (!raw) return undefined;
191
+ // Accept both the bare path and the `ws+unix://<path>:/` form the bridge dials.
192
+ const path = raw.startsWith("ws+unix://") ? raw.slice("ws+unix://".length).replace(/:\/$/, "") : raw;
193
+ const slash = path.lastIndexOf("/");
194
+ if (slash < 0) return undefined;
195
+ const dir = path.slice(0, slash);
196
+ const base = path.slice(slash + 1);
197
+ const match = /^gateway-(\d+)\.sock$/.exec(base);
198
+ if (!match) return undefined;
199
+ return `${dir}/instances/${match[1]}.id`;
200
+ }
201
+
202
+ export interface RetargetInputs {
203
+ current: EndpointCandidate;
204
+ candidate: EndpointCandidate;
205
+ /** The current endpoint came from an explicit source (D3). */
206
+ pinned: boolean;
207
+ /** The current endpoint is unreachable. */
208
+ failed: boolean;
209
+ /** The candidate proved it is the instance it claims to be. */
210
+ identityVerified: boolean;
211
+ }
212
+
213
+ export interface RetargetDecision {
214
+ retarget: boolean;
215
+ /** Always names both endpoints — a silent migration is the bug (task 10.2). */
216
+ reason: string;
217
+ }
218
+
219
+ /**
220
+ * Decide whether a bridge registered with `current` may move to `candidate`.
221
+ *
222
+ * Conjunctive by construction: any single missing precondition keeps the
223
+ * bridge where it is and surfaces a retrying failure, which is the visible
224
+ * behaviour a silent migration denied us.
225
+ */
226
+ export function decideRetarget(input: RetargetInputs): RetargetDecision {
227
+ const { current, candidate, pinned, failed, identityVerified } = input;
228
+ const pair = `current=${current.endpoint} candidate=${candidate.endpoint}`;
229
+
230
+ if (pinned) {
231
+ return { retarget: false, reason: `refused: current endpoint is pinned (${pair})` };
232
+ }
233
+ if (!failed) {
234
+ return { retarget: false, reason: `refused: current endpoint has not failed (${pair})` };
235
+ }
236
+ if (!identityVerified) {
237
+ return { retarget: false, reason: `refused: candidate identity did not verify (${pair})` };
238
+ }
239
+ if (
240
+ current.instanceId !== undefined &&
241
+ candidate.instanceId !== undefined &&
242
+ current.instanceId === candidate.instanceId
243
+ ) {
244
+ return {
245
+ retarget: true,
246
+ reason: `re-address: same instance ${current.instanceId} at a new endpoint (${pair})`,
247
+ };
248
+ }
249
+ return {
250
+ retarget: true,
251
+ reason: `re-target: unpinned, failed, and candidate identity verified (${pair})`,
252
+ };
253
+ }
@@ -38,3 +38,45 @@ export function mapEventToProtocol(
38
38
  },
39
39
  };
40
40
  }
41
+
42
+ /**
43
+ * Bridge forwarding policy for `session_compact`: return a shallow COPY of the
44
+ * event with `compactionEntry` omitted. Every other top-level field is
45
+ * preserved.
46
+ *
47
+ * The field carries pi >= 0.86's prompt-sections + tool-declaration
48
+ * `systemMessage` checkpoint and the compaction `summary`; no dashboard
49
+ * consumer reads either (the client renders the divider from the event's
50
+ * presence and the badge from `reason`/`willRetry`/`estimatedPostCompactionTokens`;
51
+ * the server only clears the `compacting` latch).
52
+ *
53
+ * Copy, never mutate: pi's `ExtensionRunner.emit` hands the SAME event object
54
+ * to every subscribed handler, so `delete event.compactionEntry` would strip the
55
+ * field from unrelated extensions too. Applied at the bridge's `session_compact`
56
+ * forwarding site — NOT inside {@link mapEventToProtocol}, which stays generic
57
+ * over every forwarded event type.
58
+ *
59
+ * See OpenSpec change: filter-system-role-message-forwarding (D6/D7).
60
+ */
61
+ export function redactCompactionEntry(
62
+ event: Record<string, unknown>,
63
+ ): Record<string, unknown> {
64
+ const forwarded: Record<string, unknown> = { ...event };
65
+ delete forwarded.compactionEntry;
66
+ return forwarded;
67
+ }
68
+
69
+ /**
70
+ * Bridge forwarding policy for pi 0.87+ `agent_before_settle`: a shallow COPY
71
+ * without `context` (the boundary preview carries full message arrays, like
72
+ * the never-forwarded `context` event). No dashboard consumer reads it; the
73
+ * event itself has no status effect. Copy, never mutate (shared event object).
74
+ * See change: update-pi-core-1-0-adopt-apis (D5).
75
+ */
76
+ export function redactBeforeSettleContext(
77
+ event: Record<string, unknown>,
78
+ ): Record<string, unknown> {
79
+ const forwarded: Record<string, unknown> = { ...event };
80
+ delete forwarded.context;
81
+ return forwarded;
82
+ }
@@ -0,0 +1,59 @@
1
+ /**
2
+ * The bridge's own extension package identity (D8): realpath of the nearest
3
+ * package dir above this module + its version. Cached for the process.
4
+ * Sent on every `session_register`; the server compares it with the active
5
+ * runtime's extension and reloads a stale bridge once.
6
+ *
7
+ * See change: electron-runtime-overlay-updates.
8
+ */
9
+ import fs from "node:fs";
10
+ import path from "node:path";
11
+ import { fileURLToPath } from "node:url";
12
+ import type { BridgeExtensionIdentity } from "@blackbelt-technology/pi-dashboard-shared/protocol.js";
13
+
14
+ function readVersion(file: string): string | undefined {
15
+ try {
16
+ const v = (JSON.parse(fs.readFileSync(file, "utf8")) as { version?: unknown }).version;
17
+ return typeof v === "string" ? v : undefined;
18
+ } catch {
19
+ return undefined; // unreadable manifest — identity is the dir alone
20
+ }
21
+ }
22
+
23
+ function realpathOr(dir: string): string {
24
+ try {
25
+ return fs.realpathSync(dir);
26
+ } catch {
27
+ return dir;
28
+ }
29
+ }
30
+
31
+ /** Walk up from `startDir` to the first dir with a package.json. */
32
+ export function resolveExtensionIdentity(startDir: string): BridgeExtensionIdentity | undefined {
33
+ let dir = startDir;
34
+ for (let i = 0; i < 8; i++) {
35
+ const file = path.join(dir, "package.json");
36
+ if (fs.existsSync(file)) {
37
+ const version = readVersion(file);
38
+ const real = realpathOr(dir);
39
+ return version ? { dir: real, version } : { dir: real };
40
+ }
41
+ const parent = path.dirname(dir);
42
+ if (parent === dir) return undefined;
43
+ dir = parent;
44
+ }
45
+ return undefined;
46
+ }
47
+
48
+ let cached: BridgeExtensionIdentity | undefined | null = null;
49
+
50
+ export function bridgeExtensionIdentity(): BridgeExtensionIdentity | undefined {
51
+ if (cached === null) {
52
+ try {
53
+ cached = resolveExtensionIdentity(path.dirname(fileURLToPath(import.meta.url)));
54
+ } catch {
55
+ cached = undefined;
56
+ }
57
+ }
58
+ return cached;
59
+ }
@@ -2,10 +2,10 @@
2
2
  * Flow event wiring: registers listeners for pi-flows events
3
3
  * and forwards them as protocol messages to the dashboard server.
4
4
  */
5
- import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
5
+
6
+ import type { FlowInfo } from "@blackbelt-technology/pi-dashboard-shared/types.js";
6
7
  import type { BridgeContext } from "./bridge-context.js";
7
8
  import { filterHiddenCommands } from "./bridge-context.js";
8
- import type { FlowInfo } from "@blackbelt-technology/pi-dashboard-shared/types.js";
9
9
 
10
10
  /** Map of pi-flows event names to dashboard protocol event types */
11
11
  export const FLOW_EVENT_MAP: Record<string, string> = {
@@ -30,6 +30,69 @@ export const FLOW_EVENT_MAP: Record<string, string> = {
30
30
  // See change: rework-flows-plugin-for-new-pi-flows (consumes pi-flows surface-node-kind).
31
31
  };
32
32
 
33
+ /**
34
+ * Deps the EventBus forwarding wiring needs from the bridge. The bridge owns
35
+ * the transport (`sendEventForward`), the readiness gates, and the subagent
36
+ * frame buffer; this module owns WHICH channels are forwarded and HOW they are
37
+ * observed. See change: fix-automation-run-lifecycle.
38
+ */
39
+ export interface EventBusForwardingDeps {
40
+ /** Send one frame as an `event_forward` (applies the channel rename map). */
41
+ sendEventForward: (channel: string, data: Record<string, unknown>) => void;
42
+ /** True once `session_start` established the session id. */
43
+ isSessionReady: () => boolean;
44
+ /** False once a newer bridge instance took over. */
45
+ isActive: () => boolean;
46
+ /** True while the WebSocket transport is actually open. */
47
+ isConnected: () => boolean;
48
+ /** Subagent-channel predicate + latest-wins buffer (reconcilable state). */
49
+ subagent: {
50
+ isSubagentChannel: (channel: string) => boolean;
51
+ markForwarded: (channel: string, data: Record<string, unknown>) => void;
52
+ buffer: (channel: string, data: Record<string, unknown>) => boolean;
53
+ /**
54
+ * Drop the cumulative `details.entries` timeline from a NON-terminal
55
+ * subagent frame before it goes on the wire. MUST clone — the buffer
56
+ * retains frames by reference, so the fat pull source stays fat.
57
+ * See change: reduce-subagent-details-payload (D2).
58
+ */
59
+ stripForForward: (data: Record<string, unknown>, channel?: string) => Record<string, unknown>;
60
+ };
61
+ }
62
+
63
+ /**
64
+ * Forward one EventBus frame, applying the gates the bridge has always applied:
65
+ * subagent frames forward live only when ready AND the transport is open (else
66
+ * they are buffered latest-wins per agent); every other channel forwards when
67
+ * ready. Forwarding failure MUST never propagate to the emitter.
68
+ * See change: fix-automation-run-lifecycle.
69
+ */
70
+ export function forwardBusEvent(
71
+ deps: EventBusForwardingDeps,
72
+ channel: string,
73
+ data: unknown,
74
+ ): void {
75
+ try {
76
+ const eventData = (data && typeof data === "object" ? data : {}) as Record<string, unknown>;
77
+ if (deps.subagent.isSubagentChannel(channel)) {
78
+ if (deps.isSessionReady() && deps.isActive() && deps.isConnected()) {
79
+ // Buffer the FAT frame, forward the thin one. The strip clones, so the
80
+ // retained snapshot (the resync source) keeps its full timeline.
81
+ deps.sendEventForward(channel, deps.subagent.stripForForward(eventData, channel));
82
+ deps.subagent.markForwarded(channel, eventData);
83
+ } else if (!deps.subagent.buffer(channel, eventData)) {
84
+ console.warn(
85
+ `[dashboard] subagent frame dropped (no agentId) channel=${channel} while not ready`,
86
+ );
87
+ }
88
+ } else if (deps.isSessionReady() && deps.isActive()) {
89
+ deps.sendEventForward(channel, eventData);
90
+ }
91
+ } catch {
92
+ /* forwarding failure must never break event delivery */
93
+ }
94
+ }
95
+
33
96
  /** Map of pi-subagents event names to dashboard protocol event types */
34
97
  export const SUBAGENT_EVENT_MAP: Record<string, string> = {
35
98
  "subagents:created": "subagent_created",
@@ -38,6 +101,64 @@ export const SUBAGENT_EVENT_MAP: Record<string, string> = {
38
101
  "subagents:failed": "subagent_failed",
39
102
  };
40
103
 
104
+ /** Minimal shape of the host event surface this module uses. */
105
+ interface PiEventsLike {
106
+ emit: (channel: string, data: unknown) => void;
107
+ on: (channel: string, handler: (data: unknown) => void) => (() => void) | void;
108
+ }
109
+
110
+ /**
111
+ * Every EventBus channel the bridge forwards. Derived from the rename maps so a
112
+ * mapped channel can never be silently unforwarded.
113
+ * See change: fix-automation-run-lifecycle.
114
+ */
115
+ export const EVENT_BUS_MAP_FOR_TEST: Record<string, string> = {
116
+ ...FLOW_EVENT_MAP,
117
+ ...SUBAGENT_EVENT_MAP,
118
+ };
119
+
120
+ export function forwardedBusChannels(extraMaps: Array<Record<string, string>> = []): string[] {
121
+ const keys = new Set<string>();
122
+ for (const map of [FLOW_EVENT_MAP, SUBAGENT_EVENT_MAP, ...extraMaps]) {
123
+ for (const channel of Object.keys(map)) keys.add(channel);
124
+ }
125
+ return [...keys];
126
+ }
127
+
128
+ /**
129
+ * Wire EventBus forwarding: ONE subscription per declared channel.
130
+ *
131
+ * MUST NOT wrap/replace `events.emit`. pi gives every extension its own
132
+ * `events` facade (`createExtensionAPI` → `events: { emit, on }`) over a shared
133
+ * bus, so mutating OUR `emit` only ever observes OUR OWN emissions — pi-flows'
134
+ * `flow:complete` (and every other foreign emission) bypasses it entirely,
135
+ * which left automation runs unfinalized until the max-age reaper.
136
+ * `on()` observes every emitter. Returns a dispose releasing our subscriptions.
137
+ * See change: fix-automation-run-lifecycle.
138
+ */
139
+ export function registerEventBusForwarding(
140
+ events: PiEventsLike | undefined,
141
+ deps: EventBusForwardingDeps,
142
+ extraMaps: Array<Record<string, string>> = [],
143
+ ): () => void {
144
+ if (!events) return () => {};
145
+ const unsubscribers: Array<() => void> = [];
146
+ for (const channel of forwardedBusChannels(extraMaps)) {
147
+ const off = events.on(channel, (data: unknown) => forwardBusEvent(deps, channel, data));
148
+ if (typeof off === "function") unsubscribers.push(off);
149
+ }
150
+ return () => {
151
+ for (const off of unsubscribers) {
152
+ try {
153
+ off();
154
+ } catch {
155
+ /* keep releasing */
156
+ }
157
+ }
158
+ unsubscribers.length = 0;
159
+ };
160
+ }
161
+
41
162
  /**
42
163
  * Register flow event listeners on pi.events.
43
164
  * Must be called after session_start when pi.events is available.
@@ -66,7 +187,8 @@ export function registerFlowEventListeners(
66
187
  pi.events.on("flow:complete", resendCommandsAndFlows);
67
188
 
68
189
  // Note: event_forward sending for flow and subagent events is handled by
69
- // the EventBus emit intercept in bridge.ts (catch-all forwarding).
190
+ // subscription-based forwarding (`registerEventBusForwarding` above, wired
191
+ // from bridge.ts) — NOT by an emit intercept.
70
192
 
71
193
  // Legacy architect prompt forwarding REMOVED.
72
194
  // Previously forwarded flow:prompt-request events with architect-* pipelines