@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
@@ -4,16 +4,20 @@
4
4
  import { readdirSync, readFileSync } from "node:fs";
5
5
  import { homedir } from "node:os";
6
6
  import { join, relative } from "node:path";
7
+ import { resolveDashboardPorts } from "@blackbelt-technology/pi-dashboard-shared/config.js";
8
+ import { imageBlockData, imageBlockMime } from "@blackbelt-technology/pi-dashboard-shared/image-block.js";
7
9
  import { diffOr } from "@blackbelt-technology/pi-dashboard-shared/platform/git.js";
8
10
  import type {
9
11
  ExtensionToServerMessage,
12
+ InboundDropClass,
10
13
  ServerToExtensionMessage,
11
14
  } from "@blackbelt-technology/pi-dashboard-shared/protocol.js";
12
15
  import { getDefaultRegistry } from "@blackbelt-technology/pi-dashboard-shared/tool-registry/index.js";
13
- import type { FileEntry, MissingToolError, PiSessionInfo } from "@blackbelt-technology/pi-dashboard-shared/types.js";
16
+ import type { FileEntry, ImageContent, MissingToolError, PiSessionInfo } from "@blackbelt-technology/pi-dashboard-shared/types.js";
14
17
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
15
18
  import { filterHiddenCommands } from "./bridge-context.js";
16
19
  import { draftCommitMessage } from "./commit-draft.js";
20
+ import { errText, reportRefresh } from "./model-refresh.js";
17
21
  import { killProcessByPgid } from "./process-scanner.js";
18
22
  import { expandPromptTemplateFromDisk, loadPromptTemplate } from "./prompt-expander.js";
19
23
  import { buildProviderCatalogue, toModelInfo } from "./provider-register.js";
@@ -194,6 +198,45 @@ export function searchFiles(cwd: string, query: string, opts?: { regex?: boolean
194
198
  return candidates.slice(0, MAX_RESULTS).map((c) => ({ path: c.path, isDirectory: c.isDirectory }));
195
199
  }
196
200
 
201
+ /**
202
+ * Outcome of a bridge-side `/reload` attempt.
203
+ *
204
+ * `ok: false` carries the operator-facing reason so the terminal
205
+ * `command_feedback` says WHY nothing reloaded instead of claiming success.
206
+ * `handedOff` means the terminal feedback is owned by someone else — the
207
+ * bridge instance loaded by an in-process reload reports `completed` after it
208
+ * re-registers — so the requesting side must emit nothing.
209
+ *
210
+ * See change: fix-out-of-band-reload, fix-terminal-session-dashboard-reload.
211
+ */
212
+ export type ReloadOutcome =
213
+ | { ok: true; handedOff?: false }
214
+ | { ok: true; handedOff: true }
215
+ | { ok: false; reason: string };
216
+
217
+ /** Reason emitted when the bridge has no reload path for this session. */
218
+ const NO_RELOAD_PATH_REASON =
219
+ "No dashboard reload path for this session — run /reload in the pi TUI.";
220
+
221
+ /** A dashboard reload for this session is still in flight. */
222
+ export const RELOAD_IN_PROGRESS_REASON = "A reload is already in progress for this session.";
223
+
224
+ /** The self-dispatched reload command never reached its handler. */
225
+ export const RELOAD_DID_NOT_RUN_REASON =
226
+ "The reload command did not run — is the dashboard extension still loaded? See the pi terminal.";
227
+
228
+ /** `ctx.reload()` settled without pi re-running `session_start{reason:"reload"}`. */
229
+ export const PI_DID_NOT_RELOAD_REASON =
230
+ "pi did not reload — session busy or reload failed; see the pi terminal.";
231
+
232
+ /** The pending-reload slot vanished or was replaced before completion was proven. */
233
+ export const RELOAD_SUPERSEDED_REASON =
234
+ "The reload was superseded before completion could be confirmed — see the pi terminal.";
235
+
236
+ /** The reload did not finish within the bridge's bound. */
237
+ export const RELOAD_TIMEOUT_REASON =
238
+ "The reload did not finish within 60 s — see the pi terminal.";
239
+
197
240
  /** Parsed result from parseSendPrompt */
198
241
  export type ParsedPrompt =
199
242
  | { type: "bash"; command: string; excludeFromContext: boolean }
@@ -202,6 +245,7 @@ export type ParsedPrompt =
202
245
  | { type: "shutdown" }
203
246
  | { type: "reload" }
204
247
  | { type: "new" }
248
+ | { type: "retry" }
205
249
  | { type: "mgmt"; event: string; data: Record<string, unknown> }
206
250
  | { type: "slash"; text: string }
207
251
  | { type: "passthrough"; text: string };
@@ -216,6 +260,19 @@ const MANAGEMENT_COMMAND_EVENTS: Record<string, {
216
260
  dataFn: (args: string) => Record<string, unknown>;
217
261
  }> = {};
218
262
 
263
+ /**
264
+ * Team sessions (add-team-plugin D7): the guard extension confines TOOL calls, but a prompt the bridge
265
+ * turns into a host action (`!cmd` bash, `/slash` extension commands, reload, new, model, shutdown,
266
+ * management) never reaches `tool_call`. Such a session's owner could run unconfined bash by typing
267
+ * `!id`. The spawn projects `PI_EXT_TEAM_TOOLS` into the pi process, so the bridge refuses those routes
268
+ * there; plain prompts, `/compact` and the dashboard-internal retry stay available.
269
+ */
270
+ export function isTeamConfinedSession(env: NodeJS.ProcessEnv = process.env): boolean {
271
+ return typeof env.PI_EXT_TEAM_TOOLS === "string";
272
+ }
273
+
274
+ const TEAM_ALLOWED_PARSED: ReadonlySet<ParsedPrompt["type"]> = new Set(["passthrough", "compact", "retry"]);
275
+
219
276
  /** Parse input text to detect pi internal command prefixes */
220
277
  export function parseSendPrompt(text: string): ParsedPrompt {
221
278
  // 1. Check !! (must check before !)
@@ -253,7 +310,13 @@ export function parseSendPrompt(text: string): ParsedPrompt {
253
310
  return { type: "new" };
254
311
  }
255
312
 
256
- // 4d. Check /model <provider/id>
313
+ // 4d. Dashboard-internal settled-error retry. Hidden from command lists;
314
+ // triggers a non-user custom turn through pi.sendMessage.
315
+ if (text === "/__dashboard_retry") {
316
+ return { type: "retry" };
317
+ }
318
+
319
+ // 4e. Check /model <provider/id>
257
320
  if (text.startsWith("/model ")) {
258
321
  const modelStr = text.slice(7).trim();
259
322
  const slashIdx = modelStr.indexOf("/");
@@ -332,10 +395,35 @@ export function createCommandHandler(
332
395
  getCwd?: () => string;
333
396
  /** Callback to send events (e.g., bash_output, command_feedback) back to server */
334
397
  eventSink?: (msg: ExtensionToServerMessage) => void;
398
+ /**
399
+ * Report an inbound message this handler threw away. The mismatch guard
400
+ * lives inside `handle()`, which holds no connection reference, so the
401
+ * channel is injected. See change: fix-spawn-correlation-ttl-coupling (D6).
402
+ */
403
+ reportInboundDrop?: (drop: {
404
+ dropClass: InboundDropClass;
405
+ messageType?: string;
406
+ droppedSessionId?: string;
407
+ }) => void;
335
408
  /** Trigger context compaction */
336
409
  compact?: (options: { customInstructions?: string }) => void;
337
- /** Trigger session reload (extensions, settings, skills, etc.) */
338
- reload?: () => void;
410
+ /**
411
+ * Trigger session reload (extensions, settings, skills, etc.).
412
+ *
413
+ * Returns whether a reload ACTUALLY ran, so the caller never emits an
414
+ * unconditional `completed`. The bridge self-dispatches its
415
+ * `/__dashboard_reload <token>` command in-process and
416
+ * resolves `{ok:true, handedOff:true}` on success: the RELOADED bridge
417
+ * instance reports `completed` after re-registering, because this
418
+ * instance's connection is torn down by the reload. On `handedOff` the
419
+ * handler emits nothing.
420
+ *
421
+ * ASYNC by contract: a rejection that lands after we have already
422
+ * emitted `completed` would be a false success. The handler awaits it.
423
+ * See change: fix-out-of-band-reload (design.md D5),
424
+ * fix-terminal-session-dashboard-reload (D4).
425
+ */
426
+ reload?: () => Promise<ReloadOutcome>;
339
427
  /** Spawn a new session in the same cwd */
340
428
  spawnNew?: () => void;
341
429
  /** Switch model via pi.setModel() */
@@ -347,7 +435,11 @@ export function createCommandHandler(
347
435
  * events emitted by the dispatch path arrive before this turn returns.
348
436
  * See change: fix-extension-slash-commands-in-dashboard.
349
437
  */
350
- sessionPrompt?: (text: string, delivery?: "steer" | "followUp") => void | Promise<void>;
438
+ sessionPrompt?: (
439
+ text: string,
440
+ delivery?: "steer" | "followUp",
441
+ promptId?: string,
442
+ ) => void | Promise<void>;
351
443
  /**
352
444
  * Bridge-shadow-queue hooks: called AFTER pi accepts the user message,
353
445
  * gated by `isStreaming()` captured BEFORE the send. The capture order
@@ -358,7 +450,13 @@ export function createCommandHandler(
358
450
  * source of truth. See change: add-followup-edit-and-steer-cancel.
359
451
  */
360
452
  onSteerSent?: (text: string) => void;
361
- onFollowupSent?: (text: string) => void;
453
+ /**
454
+ * `images` carries the attachments sent with a buffered follow-up. Passing
455
+ * them is what makes the bridge buffer able to deliver them on drain;
456
+ * dropping them here was the original bug.
457
+ * See change: fix-bridge-followup-image-drop.
458
+ */
459
+ onFollowupSent?: (text: string, images?: unknown) => void;
362
460
  /**
363
461
  * Returns true iff the agent was streaming at the moment of the call.
364
462
  * Used to capture pre-send streaming state before `pi.sendUserMessage`
@@ -381,6 +479,14 @@ export function createCommandHandler(
381
479
  * unify-error-retry-lifecycle.
382
480
  */
383
481
  noteUserPrompt?: () => void;
482
+ /**
483
+ * Disarm a still-armed provider-retry chain before a manual retry re-drive
484
+ * (bridge wires this to `retryTracker.noteExplicitRun`). Without it the
485
+ * manual turn's native `agent_start` is converted into a synthetic
486
+ * `auto_retry_start`, rendering pi's attempt counter for a user-initiated
487
+ * retry. See change: replace-dashboard-retry-command-with-protocol-message.
488
+ */
489
+ disarmRetryChain?: () => void;
384
490
  },
385
491
  ): CommandHandler {
386
492
  const getSessionId = typeof sessionIdOrGetter === "function" ? sessionIdOrGetter : () => sessionIdOrGetter;
@@ -436,6 +542,16 @@ export function createCommandHandler(
436
542
  // Ignore messages for other sessions (skip session-less messages like heartbeat_ack)
437
543
  if ((msg as any).sessionId !== undefined && (msg as any).sessionId !== sessionId) {
438
544
  console.error(`[dashboard] Ignoring message type=${msg.type} for session ${(msg as any).sessionId}, current session is ${sessionId}`);
545
+ // This `console.error` is written to /dev/null whenever
546
+ // `keeperLog.capturePiOutput` is false (the default), so the drop is
547
+ // ALSO reported over the socket. The guard cannot tell "never mine"
548
+ // from "was mine, since replaced" — one reportable class.
549
+ // See change: fix-spawn-correlation-ttl-coupling (D6).
550
+ options?.reportInboundDrop?.({
551
+ dropClass: "session_mismatch",
552
+ messageType: msg.type,
553
+ droppedSessionId: (msg as any).sessionId,
554
+ });
439
555
  return undefined;
440
556
  }
441
557
 
@@ -443,12 +559,24 @@ export function createCommandHandler(
443
559
  case "send_prompt": {
444
560
  const parsed = parseSendPrompt(msg.text);
445
561
 
562
+ if (isTeamConfinedSession() && !TEAM_ALLOWED_PARSED.has(parsed.type)) {
563
+ options?.eventSink?.({ type: "prompt_received", sessionId, fresh: false });
564
+ return undefined;
565
+ }
566
+
446
567
  // Non-turn commands (bash/compact/shutdown/reload/new/model/mgmt)
447
568
  // return early below and never produce a user `message_start`, so an
448
569
  // optimistic idle `pendingPrompt` bubble would hang until the 30s
449
570
  // safety timeout. Settle it immediately (fresh:false → drop). The
450
571
  // passthrough + slash paths emit their own `prompt_received` with the
451
572
  // real streaming verdict. See change: optimistic-prompt-progress.
573
+ // The `promptId` echo means ONE narrow thing — the owning bridge
574
+ // handed this prompt to pi — so it rides only the ack emitted AFTER
575
+ // an actual `pi.sendUserMessage`. The acks below are UI-state signals
576
+ // for non-turn commands and for the buffered follow-up path (pi never
577
+ // sees those), and attaching the handle to them would report a
578
+ // delivery that did not happen.
579
+ // See change: fix-spawn-correlation-ttl-coupling (D7).
452
580
  if (parsed.type !== "passthrough" && parsed.type !== "slash") {
453
581
  options?.eventSink?.({ type: "prompt_received", sessionId, fresh: false });
454
582
  }
@@ -472,16 +600,36 @@ export function createCommandHandler(
472
600
  }
473
601
 
474
602
  if (parsed.type === "reload") {
603
+ // Emit the REAL outcome. The previous unconditional `completed`
604
+ // reported success for every reload that silently no-op'd on a
605
+ // session with no captured reload function — which is every
606
+ // dashboard-spawned session that was never touched in a TUI.
607
+ // See change: fix-out-of-band-reload.
608
+ let outcome: ReloadOutcome = { ok: false, reason: NO_RELOAD_PATH_REASON };
475
609
  if (options?.reload) {
476
- options.reload();
610
+ // Defence in depth: the bridge already converts a throw into an
611
+ // outcome, but a stale captured `ctx.reload` throws
612
+ // SYNCHRONOUSLY out of `assertActive()`, and any caller wiring a
613
+ // different `reload` must not be able to take the turn down.
614
+ try {
615
+ outcome = await options.reload();
616
+ } catch (err: any) {
617
+ const reason = err instanceof Error ? err.message : String(err);
618
+ outcome = { ok: false, reason: `Reload failed: ${reason}` };
619
+ }
477
620
  }
621
+ // The reloaded bridge owns the terminal feedback.
622
+ // See change: fix-terminal-session-dashboard-reload (D4).
623
+ if (outcome.ok && outcome.handedOff) return undefined;
478
624
  options?.eventSink?.({
479
625
  type: "event_forward",
480
626
  sessionId,
481
627
  event: {
482
628
  eventType: "command_feedback",
483
629
  timestamp: Date.now(),
484
- data: { command: "/reload", status: "completed" },
630
+ data: outcome.ok
631
+ ? { command: "/reload", status: "completed" }
632
+ : { command: "/reload", status: "error", message: outcome.reason },
485
633
  },
486
634
  });
487
635
  return undefined;
@@ -503,6 +651,17 @@ export function createCommandHandler(
503
651
  return undefined;
504
652
  }
505
653
 
654
+ if (parsed.type === "retry") {
655
+ // Deprecated `/__dashboard_retry` sentinel alias: an un-upgraded
656
+ // client still smuggles retry through send_prompt. Route it to the
657
+ // SAME dispatch as the typed retry_session, never replaying the
658
+ // sentinel as a user message. Remove one release after clients are
659
+ // known upgraded. See change:
660
+ // replace-dashboard-retry-command-with-protocol-message.
661
+ dispatchDashboardRetry(pi, sessionId, options);
662
+ return undefined;
663
+ }
664
+
506
665
  if (parsed.type === "model") {
507
666
  if (options?.setModel) {
508
667
  await options.setModel(parsed.provider, parsed.modelId);
@@ -543,7 +702,12 @@ export function createCommandHandler(
543
702
  // extension-command dispatch. Do NOT emit completed here — would
544
703
  // duplicate the dispatch path's terminal event.
545
704
  // See change: fix-extension-slash-commands-in-dashboard.
546
- await options.sessionPrompt(parsed.text, msg.delivery);
705
+ // The handle rides along so the branch that actually reaches
706
+ // `pi.sendUserMessage` can acknowledge it; the non-turn slash
707
+ // routes (flow, extension dispatch, exec template) settle without
708
+ // one, because pi never receives those as a prompt.
709
+ // See change: fix-spawn-correlation-ttl-coupling (D7).
710
+ await options.sessionPrompt(parsed.text, msg.delivery, msg.promptId);
547
711
  } else {
548
712
  // Test / non-bridge callers: apply the extension-command dispatch
549
713
  // branch inline before falling through to sendUserMessage. Keeps
@@ -553,7 +717,6 @@ export function createCommandHandler(
553
717
  parsed.text,
554
718
  sessionId,
555
719
  options?.eventSink,
556
- undefined, // connection — absent in non-bridge path
557
720
  msg.delivery,
558
721
  );
559
722
  // Exec-mode slash template (executable: bash): run as bash, no LLM.
@@ -570,7 +733,22 @@ export function createCommandHandler(
570
733
  // Forward delivery so steering on slash fallback honors the
571
734
  // dashboard's keyboard contract. See change: add-steering-message.
572
735
  const deliverAs = msg.delivery ?? ("followUp" as const);
736
+ // Capture the streaming verdict BEFORE the pi call: an idle
737
+ // send synchronously fires `agent_start`, so reading it
738
+ // afterwards reports `fresh:false` for every fresh turn — the
739
+ // same trap the passthrough path documents.
740
+ const wasStreamingBeforeSend = options?.isStreaming?.() ?? false;
573
741
  (pi.sendUserMessage as any)(parsed.text, { deliverAs });
742
+ // This slash DID reach pi as a user prompt, so it is delivered.
743
+ // See change: fix-spawn-correlation-ttl-coupling (D7).
744
+ if (msg.promptId) {
745
+ options?.eventSink?.({
746
+ type: "prompt_received",
747
+ sessionId,
748
+ fresh: !wasStreamingBeforeSend,
749
+ promptId: msg.promptId,
750
+ });
751
+ }
574
752
  }
575
753
  }
576
754
  return undefined;
@@ -611,21 +789,34 @@ export function createCommandHandler(
611
789
  // idle→streaming synchronously on the first user message, so
612
790
  // checking after sendUserMessage gives false positives.
613
791
  //
614
- // Image attachments are NOT carried in the bridge buffer in v1
615
- // (text-only). Image-bearing follow-ups buffered during streaming
616
- // will lose their images on drain (Known Limitation).
617
- //
618
- // See change: rework-mid-turn-prompt-queue (design.md D1).
792
+ // Image attachments RIDE the bridge buffer and are delivered on
793
+ // drain. See change: rework-mid-turn-prompt-queue (design.md D1),
794
+ // fix-bridge-followup-image-drop.
619
795
  const wasStreaming = options?.isStreaming?.() ?? false;
620
796
  // Per-send ack carrying the capture-before-send streaming verdict.
621
797
  // Drives the optimistic `pendingPrompt` bubble: fresh:true → "sent",
622
798
  // fresh:false → drop (raced mid-turn). Emitted BEFORE any pi call so
623
799
  // the snapshot is authoritative. See change: optimistic-prompt-progress.
624
- options?.eventSink?.({ type: "prompt_received", sessionId, fresh: !wasStreaming });
625
800
  const da = msg.delivery ?? "followUp";
626
- if (wasStreaming && da === "followUp") {
627
- // Bridge-owned buffer path — do NOT call pi.sendUserMessage.
628
- options?.onFollowupSent?.(outgoing);
801
+ const buffered = wasStreaming && da === "followUp";
802
+ // The streaming-verdict ack is unchanged and still emitted BEFORE any
803
+ // pi call, so the snapshot stays authoritative. It carries the
804
+ // `promptId` ONLY on the branch that actually hands the prompt to pi;
805
+ // a buffered follow-up stays `transmitted` until (and unless) the
806
+ // drain ships it, which is the same honest degradation an older
807
+ // bridge gets. See change: optimistic-prompt-progress,
808
+ // fix-spawn-correlation-ttl-coupling (D7).
809
+ options?.eventSink?.({
810
+ type: "prompt_received",
811
+ sessionId,
812
+ fresh: !wasStreaming,
813
+ ...(msg.promptId && !buffered ? { promptId: msg.promptId } : {}),
814
+ });
815
+ if (buffered) {
816
+ // Bridge-owned buffer path — do NOT call pi.sendUserMessage. The
817
+ // images ride into the buffer so the drain can deliver them.
818
+ // See change: fix-bridge-followup-image-drop.
819
+ options?.onFollowupSent?.(outgoing, msg.images);
629
820
  } else {
630
821
  // Idle or steer — forward to pi directly.
631
822
  sendUserMessageWithImages(pi, outgoing, msg.images, msg.delivery);
@@ -634,6 +825,13 @@ export function createCommandHandler(
634
825
  return undefined;
635
826
  }
636
827
 
828
+ case "retry_session":
829
+ // First-class settled-error retry. Same dispatch as the deprecated
830
+ // /__dashboard_retry sentinel, minus the send_prompt channel abuse.
831
+ // See change: replace-dashboard-retry-command-with-protocol-message.
832
+ dispatchDashboardRetry(pi, sessionId, options);
833
+ return undefined;
834
+
637
835
  case "abort":
638
836
  // Pi owns both queues now. abort() asks pi to halt the current turn;
639
837
  // pi's native drain logic handles any remaining queue entries naturally.
@@ -766,10 +964,35 @@ export function createCommandHandler(
766
964
  if (registry) {
767
965
  try {
768
966
  registry.authStorage?.reload?.();
769
- registry.refresh();
967
+ // pi 0.84.0: refresh() is async and returns { aborted, errors }.
968
+ // Await it -- the pre-0.84 fire-and-forget read the catalogue
969
+ // before the refresh resolved. Report the outcome instead of
970
+ // discarding it: a partly-failed refresh still yields a usable
971
+ // (stale) catalogue, so we log and continue rather than throw.
972
+ // See change: update-pi-core-0-84-adopt-apis.
973
+ const refreshResult = await reportRefresh(registry.refresh({}));
770
974
  const models = filterByEnabledModels(registry.getAvailable().map(toModelInfo));
771
- return { type: "models_list", sessionId, models };
772
- } catch { /* ignore */ }
975
+ // Per-provider failures travel to the browser so the dropdown can
976
+ // say WHY a model is missing. Omitted (never `[]`) on success so
977
+ // the happy-path message is byte-identical to before.
978
+ //
979
+ // An ABORTED refresh never populates the field, even when it also
980
+ // carries provider errors: the spec makes abort a log-level concern
981
+ // only, and an abort means a newer refresh superseded this one — so
982
+ // its partial errors describe a run whose result is already stale.
983
+ // See change: upgrade-model-selector-primitives (design D5).
984
+ const refreshErrors = refreshResult?.aborted
985
+ ? []
986
+ : [...(refreshResult?.errors ?? [])].map(([provider, err]) => ({
987
+ provider,
988
+ message: errText(err),
989
+ }));
990
+ return refreshErrors.length > 0
991
+ ? { type: "models_list", sessionId, models, refreshErrors }
992
+ : { type: "models_list", sessionId, models };
993
+ } catch (err) {
994
+ console.warn("[dashboard] request_models failed:", errText(err));
995
+ }
773
996
  }
774
997
  return { type: "models_list", sessionId, models: [] };
775
998
  }
@@ -850,6 +1073,82 @@ export function createCommandHandler(
850
1073
  };
851
1074
  }
852
1075
 
1076
+ /** The image MIME types pi accepts inline. NEVER widened by this codebase. */
1077
+ const VALID_IMAGE_MIME_TYPES = new Set(["image/jpeg", "image/png", "image/gif", "image/webp"]);
1078
+
1079
+ /** Outcome of the image allow-list filter: what survives, and what did not. */
1080
+ export interface ImageValidation {
1081
+ valid: ImageContent[];
1082
+ /** One human-readable reason per DROPPED image, for `command_feedback`. */
1083
+ dropped: string[];
1084
+ }
1085
+
1086
+ /**
1087
+ * Filter an image array down to the blocks pi will accept.
1088
+ *
1089
+ * Mime and bytes are read through the canonical accessors (design D3c), never
1090
+ * through a direct `.mimeType` / `.data` property read: the direct read is
1091
+ * correct only for the flat pi shape and silently destroys a valid nested
1092
+ * Anthropic block (`{type:"image", source:{media_type, data}}`) as "invalid
1093
+ * mimeType". Survivors are normalised to the flat shape pi consumes.
1094
+ *
1095
+ * Dropped images are RETURNED rather than only logged — a bare `console.error`
1096
+ * is invisible to a dashboard user, which is the same defect class as the image
1097
+ * drop this change fixes (design D7).
1098
+ *
1099
+ * See change: fix-bridge-followup-image-drop (design D6, D7, D3c).
1100
+ */
1101
+ export function validateImages(images?: unknown): ImageValidation {
1102
+ const valid: ImageContent[] = [];
1103
+ const dropped: string[] = [];
1104
+ if (images === undefined || images === null) return { valid, dropped };
1105
+ // A non-array container would throw on `for...of`, failing the whole prompt
1106
+ // instead of reporting an unusable attachment. The wire is untrusted.
1107
+ if (!Array.isArray(images)) {
1108
+ dropped.push("attachments were not a list");
1109
+ return { valid, dropped };
1110
+ }
1111
+ for (const img of images) {
1112
+ if (!img || typeof img !== "object") {
1113
+ dropped.push("attachment was not an image block");
1114
+ continue;
1115
+ }
1116
+ const mimeType = imageBlockMime(img);
1117
+ if (!mimeType || !VALID_IMAGE_MIME_TYPES.has(mimeType)) {
1118
+ dropped.push(`unsupported image type "${mimeType ?? "unknown"}"`);
1119
+ continue;
1120
+ }
1121
+ const data = imageBlockData(img);
1122
+ if (!data) {
1123
+ dropped.push("attachment carried no image data");
1124
+ continue;
1125
+ }
1126
+ valid.push({ type: "image", data, mimeType });
1127
+ }
1128
+ return { valid, dropped };
1129
+ }
1130
+
1131
+ /**
1132
+ * Assemble the pi message content for `text` + `images`: a bare string when
1133
+ * there is no surviving attachment, otherwise a `[{text}, {image}…]` content
1134
+ * array — the shape pi already accepts on the idle and steer paths.
1135
+ *
1136
+ * Deliberately carries NO send options. `sendUserMessageWithImages` used to
1137
+ * fuse validation, assembly and `deliverAs`; the bridge drain must reuse the
1138
+ * first two while passing NO options, because `{deliverAs:"followUp"}` is a
1139
+ * known-broken path there (pi has already exited `getFollowUpMessages()`, so
1140
+ * the entry never drains). Splitting the concerns makes that confusion
1141
+ * structurally impossible (design D6).
1142
+ */
1143
+ export function buildUserMessageContent(
1144
+ text: string,
1145
+ images?: unknown,
1146
+ ): string | Array<{ type: "text"; text: string } | ImageContent> {
1147
+ const { valid } = validateImages(images);
1148
+ if (valid.length === 0) return text;
1149
+ return [{ type: "text" as const, text }, ...valid];
1150
+ }
1151
+
853
1152
  /** Send a user message with optional image validation.
854
1153
  * Uses deliverAs: "followUp" by default so messages queue properly when the agent is streaming.
855
1154
  * Pass deliverAs: "steer" for steering messages (delivered after current turn).
@@ -857,74 +1156,45 @@ export function createCommandHandler(
857
1156
  function sendUserMessageWithImages(
858
1157
  pi: ExtensionAPI,
859
1158
  text: string,
860
- images?: Array<{ type: string; data: string; mimeType: string }>,
1159
+ images?: unknown,
861
1160
  delivery?: "steer" | "followUp",
862
1161
  ): void {
863
1162
  const deliverAs = delivery ?? ("followUp" as const);
864
- const sendOptions = { deliverAs };
865
1163
  // POST-rework-mid-turn-prompt-queue: this helper is called for STEER and
866
1164
  // for IDLE sends only — followUp-while-streaming is intercepted upstream
867
1165
  // (bridge buffer path; never calls this helper). The deliverAs parameter
868
1166
  // is preserved for steer routing.
869
1167
  // See change: rework-mid-turn-prompt-queue (design.md D1).
870
- if (images && images.length > 0) {
871
- const validMimeTypes = new Set(["image/jpeg", "image/png", "image/gif", "image/webp"]);
872
- const validImages = images.filter((img) => {
873
- if (!img || typeof img !== "object") {
874
- console.error("[dashboard] Dropping non-object image entry");
875
- return false;
876
- }
877
- if (!img.mimeType || typeof img.mimeType !== "string" || !validMimeTypes.has(img.mimeType)) {
878
- console.error(`[dashboard] Dropping image with invalid mimeType: "${img.mimeType}" (type: ${typeof img.mimeType})`);
879
- return false;
880
- }
881
- if (!img.data || typeof img.data !== "string") {
882
- console.error(`[dashboard] Dropping image with invalid data (type: ${typeof img.data}, length: ${img.data?.length ?? 0})`);
883
- return false;
884
- }
885
- return true;
886
- });
887
- if (validImages.length > 0) {
888
- const content = [
889
- { type: "text" as const, text },
890
- ...validImages.map((img) => ({
891
- type: "image" as const,
892
- data: img.data,
893
- mimeType: img.mimeType,
894
- })),
895
- ];
896
- console.error(`[dashboard] Sending message with ${validImages.length} image(s), mimeTypes: ${validImages.map(i => i.mimeType).join(", ")}`);
897
- (pi.sendUserMessage as any)(content, sendOptions);
898
- } else {
899
- (pi.sendUserMessage as any)(text, sendOptions);
900
- }
901
- } else {
902
- (pi.sendUserMessage as any)(text, sendOptions);
903
- }
1168
+ //
1169
+ // Drops are logged here rather than surfaced: this path has no event sink.
1170
+ // The buffer path emits `command_feedback` instead (design D7).
1171
+ const { dropped } = validateImages(images);
1172
+ for (const reason of dropped) console.error(`[dashboard] Dropping image — ${reason}`);
1173
+ (pi.sendUserMessage as any)(buildUserMessageContent(text, images), { deliverAs });
904
1174
  }
905
1175
 
906
1176
  /**
907
1177
  * Resolve the dashboard HTTP port, in precedence order:
908
- * 1. `PI_DASHBOARD_PORT` / `DASHBOARD_PORT` env — set by the dashboard server
909
- * and inherited by spawned sessions (the only reliable source when the
910
- * server runs on a non-default port, e.g. the Docker test harness, whose
911
- * `config.json` carries no `port` field).
1178
+ * 1. `PI_DASHBOARD_PORT` / `DASHBOARD_PORT` env — set by the session's
1179
+ * RUNTIME environment (e.g. the docker harness compose env). The
1180
+ * dashboard server does NOT inject these into spawned sessions; it
1181
+ * pins them via `PI_DASHBOARD_URL` / `PI_DASHBOARD_SOCKET` instead.
912
1182
  * 2. `~/.pi/dashboard/config.json` `port` — normal local installs write it.
913
- * 3. 8000 (default).
914
- * Note: `PI_DASHBOARD_URL` is the gateway (ws) port, NOT the HTTP port, so it is
915
- * deliberately not consulted here. See change: add-dashboard-slash-commands.
1183
+ * 3. The shared default.
1184
+ * Delegates to the shared `resolveDashboardPorts` so this path and the
1185
+ * bridge's auto-start port resolution cannot drift.
1186
+ * Note: `PI_DASHBOARD_URL` is the gateway (ws) endpoint, NOT the HTTP port,
1187
+ * so it is deliberately not consulted here.
1188
+ * See change: add-dashboard-slash-commands, fix-bridge-autostart-port-resolution.
916
1189
  */
917
1190
  function resolveDashboardPort(): number {
918
- for (const v of [process.env.PI_DASHBOARD_PORT, process.env.DASHBOARD_PORT]) {
919
- const n = Number(v);
920
- if (v && Number.isFinite(n) && n > 0) return n;
921
- }
1191
+ let fileConfig: { port?: number } = {};
922
1192
  try {
923
1193
  const raw = readFileSync(join(homedir(), ".pi", "dashboard", "config.json"), "utf-8");
924
1194
  const parsed = JSON.parse(raw);
925
- if (typeof parsed?.port === "number" && Number.isFinite(parsed.port)) return parsed.port;
1195
+ if (typeof parsed?.port === "number") fileConfig = { port: parsed.port };
926
1196
  } catch { /* missing / unparseable config */ }
927
- return 8000;
1197
+ return resolveDashboardPorts(process.env, fileConfig).port;
928
1198
  }
929
1199
 
930
1200
  /**
@@ -981,6 +1251,57 @@ interface BashExecOptions {
981
1251
  source?: "slash-exec";
982
1252
  }
983
1253
 
1254
+ /**
1255
+ * Re-drive a settled-error turn via the pi custom-message primitive. Shared by
1256
+ * the typed `retry_session` message and the deprecated `/__dashboard_retry`
1257
+ * sentinel alias, so both converge on ONE dispatch. See change:
1258
+ * replace-dashboard-retry-command-with-protocol-message.
1259
+ */
1260
+ function dispatchDashboardRetry(
1261
+ pi: ExtensionAPI,
1262
+ sessionId: string,
1263
+ options?: {
1264
+ eventSink?: (msg: ExtensionToServerMessage) => void;
1265
+ /** Disarm a still-armed RetryTracker chain (bridge → retryTracker.noteExplicitRun). */
1266
+ disarmRetryChain?: () => void;
1267
+ },
1268
+ ): void {
1269
+ // Disarm any still-armed provider-retry chain BEFORE the re-drive. Otherwise
1270
+ // the manual turn's native agent_start is converted into a synthetic
1271
+ // auto_retry_start, rendering pi's attempt counter for a user-initiated retry.
1272
+ options?.disarmRetryChain?.();
1273
+ const emitFailure = (error: unknown) => {
1274
+ const finalError = errText(error);
1275
+ console.error("[dashboard] Internal Retry dispatch failed:", finalError);
1276
+ options?.eventSink?.({
1277
+ type: "event_forward",
1278
+ sessionId,
1279
+ event: {
1280
+ eventType: "auto_retry_end",
1281
+ timestamp: Date.now(),
1282
+ data: { success: false, attempt: 0, finalError },
1283
+ },
1284
+ });
1285
+ };
1286
+ try {
1287
+ // sendMessage is async at runtime (the .d.ts types it void). A SYNC throw is
1288
+ // trapped here; an ASYNC rejection by the .catch() below. Both surface as a
1289
+ // single auto_retry_end{success:false} so a failed dispatch never strands
1290
+ // the retry surface. See change (spike caveat 1).
1291
+ const result = pi.sendMessage(
1292
+ {
1293
+ customType: "pi-dashboard:retry",
1294
+ content: "Continue the interrupted response without repeating the user's request.",
1295
+ display: false,
1296
+ },
1297
+ { triggerTurn: true },
1298
+ ) as unknown as Promise<void> | void;
1299
+ void Promise.resolve(result).catch(emitFailure);
1300
+ } catch (error) {
1301
+ emitFailure(error);
1302
+ }
1303
+ }
1304
+
984
1305
  /** Execute a bash command and forward results */
985
1306
  async function handleBashCommand(
986
1307
  pi: ExtensionAPI,