@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
@@ -1,38 +1,52 @@
1
1
  /**
2
- * RetryTracker — synthesizes `auto_retry_start` / `auto_retry_end` events by
3
- * OBSERVING pi's own retry behavior, never by predicting it with a regex.
2
+ * RetryTracker — synthesizes `auto_retry_start` / `auto_retry_waiting` /
3
+ * `auto_retry_end` events by OBSERVING pi's own retry behavior, never by
4
+ * predicting it with a regex.
4
5
  *
5
6
  * Background: pi's ExtensionAPI does NOT expose `auto_retry_*` events to
6
- * extensions (verified against pi 0.70/0.73 — see
7
- * https://github.com/badlogic/pi-mono/discussions/2073). They fire only via
8
- * `AgentSession._emit → _eventListeners` which only the embedded SDK can
9
- * subscribe to.
7
+ * extensions (verified against pi 0.70–0.81 — see
8
+ * https://github.com/badlogic/pi-mono/discussions/2073). They fire only on the
9
+ * RPC stream / embedded-SDK listener channel, which the dashboard's WebSocket
10
+ * bridge cannot read.
10
11
  *
11
- * Observe-based model (change: simplify-error-retry-single-card):
12
- * pi owns retry policy; the bridge only observes. pi's `_handleRetryableError`
13
- * fires `message_end` for the failed assistant message, sleeps, then starts a
14
- * fresh assistant `message_start` for the next attempt — all within a single
15
- * agent turn. The tracker keys on exactly that observed sequence:
12
+ * CORRECTED observation model (change: retry-forever-with-stop-control).
13
+ * pi does NOT keep a retry chain inside one agent turn. Measured against pi
14
+ * 0.81.1, every attempt is a complete `agent_start` … `agent_end` cycle, and
15
+ * exactly ONE `agent_settled` fires after the final `agent_end`:
16
16
  *
17
- * 1. error `message_end` → record a PENDING failure, emit NOTHING.
18
- * 2. assistant `message_start` while a failure is pending (no user prompt in
19
- * between) → pi re-attempted → emit `auto_retry_start { attempt: N }`.
20
- * 3. non-error `message_end` while a chain is in flight → `auto_retry_end
21
- * { success: true }`.
22
- * 4. terminal error `agent_end` while a chain is in flight → `auto_retry_end
23
- * { success: false, finalError }`.
17
+ * agent_start → message_end(error) → agent_end attempt 0 (initial)
18
+ * [sleep baseDelayMs · 2^0]
19
+ * agent_start → message_end(error) → agent_end retry 1
20
+ * [sleep baseDelayMs · 2^1]
21
+ * agent_start → message_end(error) → agent_end → agent_settled TERMINAL
24
22
  *
25
- * A terminal error pi deems non-retryable (e.g. context overflow) never fires a
26
- * fresh `message_start`, so no `auto_retry_start` is ever emitted — the error
27
- * surfaces as an ordinary settled error via `agent_end`.
23
+ * The PREVIOUS model keyed on "error message_end then a fresh assistant
24
+ * message_start in the same turn", which never matches this shape — so the
25
+ * tracker synthesized NOTHING and the retry surface was dead in production.
28
26
  *
29
- * `delayMs` and `maxAttempts` are unknowable from observed events (pi's
30
- * settings are not exposed); we send sentinel `-1` for both. The banner renders
31
- * an indeterminate "retrying…" sub-line in that case.
27
+ * Corrected rules:
28
+ * 1. assistant `message_end` with `stopReason:"error"` → record the pending
29
+ * error text. Emit NOTHING. Do NOT clear the chain.
30
+ * 2. error `agent_end` → an attempt just ended and another is (optimistically)
31
+ * coming. Advance the retry counter and, when it is still within pi's
32
+ * budget, emit a WAITING signal carrying the next attempt number, the
33
+ * computed delay, and the absolute `nextAttemptAt`. Do NOT clear the chain.
34
+ * (A non-retryable terminal error also lands here; `agent_settled` clears
35
+ * the mistaken waiting state ~1 ms later — see design D4.)
36
+ * 3. retry `agent_start` (a fresh turn while a chain is active) → the awaited
37
+ * attempt is now in flight → emit `auto_retry_start` (waiting:false).
38
+ * 4. `agent_settled` → the SOLE terminal signal. Close the chain with
39
+ * `auto_retry_end` (success = last message not an error) and clear all
40
+ * per-session tracking.
41
+ *
42
+ * `maxAttempts` / `delayMs` are sourced read-only from pi's retry settings
43
+ * (defaults 3 / 2000). `baseDelayMs === 0` (unreadable settings) yields
44
+ * `delayMs: 0`, which the surface renders elapsed-only. The `-1` sentinels are
45
+ * REMOVED. The tracker never writes pi's settings.
32
46
  */
33
47
 
34
48
  export interface SyntheticRetryEvent {
35
- eventType: "auto_retry_start" | "auto_retry_end";
49
+ eventType: "auto_retry_start" | "auto_retry_waiting" | "auto_retry_end";
36
50
  data: Record<string, unknown>;
37
51
  }
38
52
 
@@ -43,106 +57,264 @@ export interface ObservedAssistantMessage {
43
57
  errorMessage?: string;
44
58
  }
45
59
 
60
+ /** pi retry settings the tracker needs, read-only, for display math. */
61
+ export interface RetrySettings {
62
+ /**
63
+ * pi's `retry.enabled`; default true. When false pi never retries, so no
64
+ * waiting signal is emitted at all. This mirrors the first condition of pi's
65
+ * own `_willRetryAfterAgentEnd` predicate.
66
+ */
67
+ enabled: boolean;
68
+ /** pi's `retry.maxRetries`; default 3. */
69
+ maxRetries: number;
70
+ /** pi's `retry.baseDelayMs`; default 2000. 0 = unknown → elapsed-only. */
71
+ baseDelayMs: number;
72
+ }
73
+
74
+ const DEFAULT_SETTINGS: RetrySettings = { enabled: true, maxRetries: 3, baseDelayMs: 2000 };
75
+
76
+ /** Per-session retry-chain state. */
77
+ interface Chain {
78
+ /** Number of the last/next retry (0 = only the initial attempt has failed so far). */
79
+ attempt: number;
80
+ /** Most recent error text, from the error `message_end` / `agent_end`. */
81
+ errorMessage: string;
82
+ /** True when an error `agent_end` armed the next attempt; the next retry
83
+ * `agent_start` consumes it to emit `auto_retry_start`. */
84
+ armed: boolean;
85
+ /** Disposition of the most recent `agent_end`. `agent_settled` reads this to
86
+ * decide success/failure, because native `agent_settled` carries no messages
87
+ * (verified pi 0.81.1). */
88
+ lastEndWasError: boolean;
89
+ }
90
+
46
91
  export class RetryTracker {
47
- /** sessionId → errorMessage of an error message_end awaiting a re-attempt. */
48
- private pending = new Map<string, string>();
49
- /** sessionId → 1-based attempt counter for the in-flight retry chain. */
50
- private attempt = new Map<string, number>();
92
+ private chains = new Map<string, Chain>();
93
+ /** Suppresses delayed events from a user-cancelled chain until settle or a
94
+ * deliberate new user run releases the session. */
95
+ private cancelled = new Set<string>();
96
+ private readonly settings: RetrySettings;
97
+
98
+ constructor(settings?: Partial<RetrySettings>) {
99
+ this.settings = {
100
+ enabled: typeof settings?.enabled === "boolean" ? settings.enabled : DEFAULT_SETTINGS.enabled,
101
+ maxRetries:
102
+ typeof settings?.maxRetries === "number" ? settings.maxRetries : DEFAULT_SETTINGS.maxRetries,
103
+ baseDelayMs:
104
+ typeof settings?.baseDelayMs === "number" ? settings.baseDelayMs : DEFAULT_SETTINGS.baseDelayMs,
105
+ };
106
+ }
107
+
108
+ /** `delayMs = baseDelayMs · 2^(attempt-1)`; 0 when the base is unknown. */
109
+ private delayFor(attempt: number): number {
110
+ if (this.settings.baseDelayMs <= 0 || attempt < 1) return 0;
111
+ const delayMs = this.settings.baseDelayMs * 2 ** (attempt - 1);
112
+ return Number.isFinite(delayMs) ? delayMs : 0;
113
+ }
114
+
115
+ /**
116
+ * Process a fresh `agent_start`. When a chain is armed (an error `agent_end`
117
+ * scheduled the next attempt), this start IS that attempt going in flight →
118
+ * emit `auto_retry_start`. Otherwise (the initial turn, or a non-retry start)
119
+ * emit nothing.
120
+ */
121
+ observeAgentStart(sessionId: string): SyntheticRetryEvent | null {
122
+ if (this.cancelled.has(sessionId)) return null;
123
+ const chain = this.chains.get(sessionId);
124
+ if (!chain?.armed) return null;
125
+ chain.armed = false;
126
+ return {
127
+ eventType: "auto_retry_start",
128
+ data: {
129
+ attempt: chain.attempt,
130
+ maxAttempts: this.settings.maxRetries,
131
+ delayMs: this.delayFor(chain.attempt),
132
+ errorMessage: chain.errorMessage,
133
+ },
134
+ };
135
+ }
51
136
 
52
137
  /**
53
- * Process a `message_end` event.
54
- *
55
- * - error assistant message → record a pending failure, return null (the
56
- * retry is only confirmed once pi starts a fresh attempt).
57
- * - non-error assistant message → if a retry chain is in flight, close it
58
- * with `auto_retry_end { success: true }`; otherwise clear any stray
59
- * pending failure and return null.
138
+ * Process an assistant `message_end`. Errors open/refresh the chain. The
139
+ * first non-error completion closes an active chain immediately — matching
140
+ * pi's own automatic-continuation success signal without requiring a user
141
+ * message. Aborted completions terminate the chain but are never success.
60
142
  */
61
143
  observeMessageEnd(
62
144
  sessionId: string,
63
145
  message: ObservedAssistantMessage | undefined | null,
64
146
  ): SyntheticRetryEvent | null {
65
- if (!message || message.role !== "assistant") return null;
147
+ if (this.cancelled.has(sessionId) || message?.role !== "assistant") return null;
66
148
 
67
149
  if (message.stopReason === "error") {
68
150
  const err = typeof message.errorMessage === "string" ? message.errorMessage : "";
69
- this.pending.set(sessionId, err);
151
+ const chain = this.chains.get(sessionId);
152
+ if (chain) {
153
+ chain.errorMessage = err;
154
+ chain.lastEndWasError = true;
155
+ } else {
156
+ this.chains.set(sessionId, {
157
+ attempt: 0,
158
+ errorMessage: err,
159
+ armed: false,
160
+ lastEndWasError: true,
161
+ });
162
+ }
70
163
  return null;
71
164
  }
72
165
 
73
- // Non-error assistant completion — clears any pending failure.
74
- this.pending.delete(sessionId);
75
- if (this.attempt.has(sessionId)) {
76
- const last = this.attempt.get(sessionId) ?? 0;
77
- this.attempt.delete(sessionId);
78
- return { eventType: "auto_retry_end", data: { success: true, attempt: last } };
166
+ const stopReason = message.stopReason;
167
+ if (typeof stopReason !== "string" || stopReason.length === 0) return null;
168
+
169
+ const chain = this.chains.get(sessionId);
170
+ if (!chain) return null;
171
+ this.chains.delete(sessionId);
172
+
173
+ if (stopReason === "aborted") {
174
+ this.cancelled.add(sessionId);
175
+ return { eventType: "auto_retry_end", data: { success: false, attempt: -1 } };
79
176
  }
80
- return null;
177
+
178
+ return {
179
+ eventType: "auto_retry_end",
180
+ data: { success: true, attempt: chain.attempt },
181
+ };
81
182
  }
82
183
 
83
184
  /**
84
- * Process an assistant `message_start` event. If a failure is pending for the
85
- * session, pi has started a fresh attempt in the same turn → emit
86
- * `auto_retry_start`. Returns the synthetic event the bridge should forward,
87
- * or null.
185
+ * Process an `agent_end`. When its last message is an error, an attempt just
186
+ * failed and another is optimistically coming: advance the counter, arm the
187
+ * next `agent_start`, and — while still within pi's budget — emit the WAITING
188
+ * signal. The chain is NEVER cleared here; only `agent_settled` terminates it.
88
189
  */
89
- observeMessageStart(
190
+ observeAgentEnd(
90
191
  sessionId: string,
91
- message: ObservedAssistantMessage | undefined | null,
192
+ agentEndData: { messages?: unknown } | undefined | null,
92
193
  ): SyntheticRetryEvent | null {
93
- if (!message || message.role !== "assistant") return null;
94
- if (!this.pending.has(sessionId)) return null;
95
- const err = this.pending.get(sessionId) ?? "";
96
- this.pending.delete(sessionId);
97
- const next = (this.attempt.get(sessionId) ?? 0) + 1;
98
- this.attempt.set(sessionId, next);
194
+ if (this.cancelled.has(sessionId)) return null;
195
+ const messages = agentEndData?.messages;
196
+ // Match pi's own `_willRetryAfterAgentEnd`: the retry decision keys off the
197
+ // last ASSISTANT message (found by its structured `role`), NOT merely the
198
+ // final array element. A turn can end with a `toolResult` (or other
199
+ // non-assistant entry) after the failed assistant message, so a bare
200
+ // `messages[length-1]` check would miss the error and never arm the chain —
201
+ // yielding no retry counting even though pi is retrying. Scan backward for
202
+ // `role === "assistant"`. See change: unify-retry-visibility.
203
+ let lastMsg: ObservedAssistantMessage | undefined;
204
+ if (Array.isArray(messages)) {
205
+ for (let i = messages.length - 1; i >= 0; i--) {
206
+ const m = messages[i] as ObservedAssistantMessage;
207
+ if (m?.role === "assistant") {
208
+ lastMsg = m;
209
+ break;
210
+ }
211
+ }
212
+ }
213
+ // NO assistant message = NO disposition. Distinct from "a clean assistant
214
+ // message": absence tells us nothing about whether the turn succeeded, so
215
+ // the chain's recorded disposition must be left exactly as it was.
216
+ // Collapsing the two cases let a payload carrying no assistant entry mark a
217
+ // LIVE retry chain successful, and `agent_settled` then reported success for
218
+ // a turn that never succeeded.
219
+ // See change: raw-error-render-and-retry-authority.
220
+ if (lastMsg === undefined) return null;
221
+ const stopReason = lastMsg.stopReason;
222
+ if (typeof stopReason !== "string" || stopReason.length === 0) return null;
223
+
224
+ if (stopReason === "aborted") {
225
+ const existing = this.chains.get(sessionId);
226
+ if (!existing) return null;
227
+ this.chains.delete(sessionId);
228
+ this.cancelled.add(sessionId);
229
+ return { eventType: "auto_retry_end", data: { success: false, attempt: -1 } };
230
+ }
231
+
232
+ const isError = stopReason === "error";
233
+ if (!isError) {
234
+ // `message_end` normally closes success first. Keep this disposition as
235
+ // a fallback for event sources that omit message_end.
236
+ const existing = this.chains.get(sessionId);
237
+ if (existing) existing.lastEndWasError = false;
238
+ return null;
239
+ }
240
+
241
+ const err =
242
+ typeof lastMsg.errorMessage === "string" && lastMsg.errorMessage.length > 0
243
+ ? lastMsg.errorMessage
244
+ : (this.chains.get(sessionId)?.errorMessage ?? "");
245
+ const chain =
246
+ this.chains.get(sessionId) ?? { attempt: 0, errorMessage: err, armed: false, lastEndWasError: true };
247
+ chain.errorMessage = err;
248
+ chain.attempt += 1;
249
+ chain.armed = true;
250
+ chain.lastEndWasError = true;
251
+ this.chains.set(sessionId, chain);
252
+
253
+ // Suppress the waiting signal when pi provably will NOT retry. These are the
254
+ // two conditions of pi's own `_willRetryAfterAgentEnd` predicate that an
255
+ // extension may legitimately read; the third (`_isRetryableError`) is pi's
256
+ // regex classifier and is deliberately NOT replicated — a non-retryable
257
+ // settle is corrected by `agent_settled` instead.
258
+ // See change: retry-forever-with-stop-control (design D4/E9).
259
+ if (!this.settings.enabled) return null;
260
+ if (chain.attempt > this.settings.maxRetries) return null;
261
+
262
+ const delayMs = this.delayFor(chain.attempt);
99
263
  return {
100
- eventType: "auto_retry_start",
101
- data: { attempt: next, maxAttempts: -1, delayMs: -1, errorMessage: err },
264
+ eventType: "auto_retry_waiting",
265
+ data: {
266
+ attempt: chain.attempt,
267
+ maxAttempts: this.settings.maxRetries,
268
+ delayMs,
269
+ nextAttemptAt: delayMs > 0 ? Date.now() + delayMs : undefined,
270
+ errorMessage: err,
271
+ },
102
272
  };
103
273
  }
104
274
 
105
275
  /**
106
- * Process an `agent_end` event. Always clears any in-flight retry tracking
107
- * (terminal turn boundary). Only synthesizes when a retry chain was actually
108
- * in flight: a settled error that pi never re-attempted surfaces through the
109
- * ordinary `agent_end` error path, not through the retry lifecycle.
276
+ * Process `agent_settled` — the SOLE terminal signal. Closes an active chain
277
+ * with `auto_retry_end` (success = last message is not an error) and clears
278
+ * all per-session tracking. No active chain → nothing.
110
279
  */
111
- observeAgentEnd(
112
- sessionId: string,
113
- agentEndData: { messages?: unknown } | undefined | null,
114
- ): SyntheticRetryEvent | null {
115
- const wasRetrying = this.attempt.has(sessionId);
116
- const last = this.attempt.get(sessionId) ?? -1;
117
- this.attempt.delete(sessionId);
118
- this.pending.delete(sessionId);
119
- if (!wasRetrying) return null;
280
+ observeAgentSettled(sessionId: string): SyntheticRetryEvent | null {
281
+ if (this.cancelled.delete(sessionId)) {
282
+ this.chains.delete(sessionId);
283
+ return null;
284
+ }
285
+ const chain = this.chains.get(sessionId);
286
+ if (!chain) return null;
287
+ this.chains.delete(sessionId);
120
288
 
121
- const messages = agentEndData?.messages;
122
- const lastMsg =
123
- Array.isArray(messages) && messages.length > 0
124
- ? (messages[messages.length - 1] as ObservedAssistantMessage)
125
- : undefined;
126
- if (lastMsg?.stopReason === "error" && typeof lastMsg.errorMessage === "string") {
289
+ // Native `agent_settled` carries no messages (verified pi 0.81.1), so the
290
+ // disposition comes from the last observed `agent_end`.
291
+ if (chain.lastEndWasError) {
127
292
  return {
128
293
  eventType: "auto_retry_end",
129
- data: { success: false, attempt: last, finalError: lastMsg.errorMessage },
294
+ data: { success: false, attempt: chain.attempt, finalError: chain.errorMessage },
130
295
  };
131
296
  }
132
- return { eventType: "auto_retry_end", data: { success: true, attempt: last } };
297
+ return { eventType: "auto_retry_end", data: { success: true, attempt: chain.attempt } };
133
298
  }
134
299
 
135
300
  /**
136
- * Notify the tracker of a user abort. Clears in-flight tracking so a
137
- * subsequent agent_end does not double-emit auto_retry_end.
301
+ * Notify the tracker of a user abort. Clear the active chain and suppress
302
+ * delayed events until settle or a deliberate new user run.
138
303
  */
139
304
  noteAbort(sessionId: string): void {
140
- this.attempt.delete(sessionId);
141
- this.pending.delete(sessionId);
305
+ this.chains.delete(sessionId);
306
+ this.cancelled.add(sessionId);
307
+ }
308
+
309
+ /** A new explicit user run is independent from any cancelled or floor-pi
310
+ * chain left without a native terminal settle. */
311
+ noteExplicitRun(sessionId: string): void {
312
+ this.cancelled.delete(sessionId);
313
+ this.chains.delete(sessionId);
142
314
  }
143
315
 
144
- /** Test-only / bridge-coordination: is a retry currently in flight? */
316
+ /** Bridge coordination: is a retry chain currently active? */
145
317
  isRetrying(sessionId: string): boolean {
146
- return this.attempt.has(sessionId);
318
+ return this.chains.has(sessionId);
147
319
  }
148
320
  }
@@ -28,36 +28,30 @@
28
28
  * See change: add-custom-roles-ui (roles:remove + builtinRoleNames payload).
29
29
  */
30
30
 
31
- import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
32
- import { isValidRoleName } from "@blackbelt-technology/pi-dashboard-shared/role-name-validation.js";
33
31
  import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
34
32
  import { homedir } from "node:os";
35
33
  import { join } from "node:path";
34
+ import { isValidRoleName } from "@blackbelt-technology/pi-dashboard-shared/role-name-validation.js";
35
+ import {
36
+ DEFAULT_ROLE_NAMES,
37
+ effectiveRoleNames,
38
+ overlayRoles,
39
+ parseRoleConfig,
40
+ type RoleConfig,
41
+ type RolePreset,
42
+ } from "@blackbelt-technology/pi-dashboard-shared/role-schema.js";
43
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
36
44
 
37
45
  // -- Types ----------------------------------------------------------------
38
46
 
39
- export interface RolePreset {
40
- name: string;
41
- roles: Record<string, string>;
42
- }
43
-
44
- export interface RoleConfig {
45
- roles: Record<string, string>;
46
- rolePresets: RolePreset[];
47
- activePreset: string | null;
48
- /**
49
- * User-added role names beyond DEFAULT_ROLE_NAMES. Persisted so an added
50
- * role surfaces as an empty slot everywhere even before a model is assigned.
51
- * See change: add-agent-role-model-tools (design D5, task 3.1).
52
- */
53
- roleNames?: string[];
54
- /**
55
- * Removal markers for DEFAULT role names the user removed, so the read-time
56
- * overlay does NOT re-inject them. User-added names need no marker (dropping
57
- * them from `roleNames` removes them from the effective schema).
58
- */
59
- removedRoles?: string[];
60
- }
47
+ export type { RoleConfig, RolePreset };
48
+ // The role-schema core (types, DEFAULT_ROLE_NAMES, effectiveRoleNames,
49
+ // overlayRoles, and the normalizer) now lives in
50
+ // `@blackbelt-technology/pi-dashboard-shared/role-schema.js` so the bridge,
51
+ // the roles-plugin server route, and the plugin client derive one definition.
52
+ // Re-exported here for the existing importers of this module.
53
+ // See change: add-roles-read-api.
54
+ export { DEFAULT_ROLE_NAMES, effectiveRoleNames, overlayRoles };
61
55
 
62
56
  // -- Config path ----------------------------------------------------------
63
57
 
@@ -89,26 +83,10 @@ function loadFullConfig(): Record<string, unknown> {
89
83
  * Re-read on every call — handlers depend on this to see cross-session updates.
90
84
  */
91
85
  export function loadRoleConfig(): RoleConfig {
92
- const raw = loadFullConfig();
93
- const roles: Record<string, string> = {};
94
- const rawRoles = raw.roles;
95
- if (rawRoles && typeof rawRoles === "object") {
96
- for (const [k, v] of Object.entries(rawRoles)) {
97
- if (typeof v === "string" && v.trim() !== "") roles[k] = v.trim();
98
- }
99
- }
100
- const rolePresets: RolePreset[] = Array.isArray(raw.rolePresets)
101
- ? (raw.rolePresets as RolePreset[])
102
- : [];
103
- const activePreset: string | null =
104
- typeof raw.activePreset === "string" ? (raw.activePreset as string) : null;
105
- const roleNames: string[] | undefined = Array.isArray(raw.roleNames)
106
- ? (raw.roleNames as unknown[]).filter((n): n is string => typeof n === "string")
107
- : undefined;
108
- const removedRoles: string[] | undefined = Array.isArray(raw.removedRoles)
109
- ? (raw.removedRoles as unknown[]).filter((n): n is string => typeof n === "string")
110
- : undefined;
111
- return { roles, rolePresets, activePreset, roleNames, removedRoles };
86
+ // File read stays here (per-side); normalization is delegated to the shared
87
+ // total normalizer so every reader normalizes identically. See change:
88
+ // add-roles-read-api (design D2a).
89
+ return parseRoleConfig(loadFullConfig());
112
90
  }
113
91
 
114
92
  /**
@@ -136,21 +114,6 @@ export function saveRoleConfig(roleConfig: RoleConfig): void {
136
114
  }
137
115
 
138
116
  // -- Default roles --------------------------------------------------------
139
- //
140
- // Dashboard-owned canonical role-name set. Roles ownership moved off
141
- // pi-flows (change: adopt-model-resolve-handler-and-roles-ownership), so the
142
- // dashboard owns the default names too rather than depending on pi-flows
143
- // being installed. Mirrors pi-flows' `KNOWN_MODEL_ROLES`.
144
- //
145
- // See change: roles-standalone-defaults-and-local-install-detection.
146
- export const DEFAULT_ROLE_NAMES = [
147
- "planning",
148
- "coding",
149
- "compact",
150
- "fast",
151
- "vision",
152
- "research",
153
- ] as const;
154
117
 
155
118
  /**
156
119
  * Overlay the default role names onto an assigned-roles map for DISPLAY.
@@ -169,38 +132,6 @@ export function overlayDefaultRoles(
169
132
  return { ...out, ...roles };
170
133
  }
171
134
 
172
- /**
173
- * Effective role-name schema = (defaults ∪ added ∪ assigned) − removed,
174
- * order-stable (defaults first, then adds, then any assigned extras).
175
- * A removed default is NOT re-injected. See change: add-agent-role-model-tools.
176
- */
177
- export function effectiveRoleNames(
178
- cfg: Pick<RoleConfig, "roles" | "roleNames" | "removedRoles">,
179
- ): string[] {
180
- const removed = new Set(cfg.removedRoles ?? []);
181
- const out: string[] = [];
182
- const seen = new Set<string>();
183
- for (const n of [...DEFAULT_ROLE_NAMES, ...(cfg.roleNames ?? []), ...Object.keys(cfg.roles)]) {
184
- if (removed.has(n) || seen.has(n)) continue;
185
- seen.add(n);
186
- out.push(n);
187
- }
188
- return out;
189
- }
190
-
191
- /**
192
- * Read-time overlay keyed off the EFFECTIVE schema (defaults ∪ added − removed)
193
- * instead of the hardcoded const. Every effective name appears (empty when
194
- * unassigned); assigned values win. Used by roles:get-all.
195
- */
196
- export function overlayRoles(
197
- cfg: Pick<RoleConfig, "roles" | "roleNames" | "removedRoles">,
198
- ): Record<string, string> {
199
- const out: Record<string, string> = {};
200
- for (const name of effectiveRoleNames(cfg)) out[name] = "";
201
- return { ...out, ...cfg.roles };
202
- }
203
-
204
135
  /**
205
136
  * Register a role name in the editable schema. Clears any removal marker and
206
137
  * (for non-defaults) records it in `roleNames`. Mutates `cfg` in place; the
@@ -277,6 +208,22 @@ export function getModelRole(role: string): string | undefined {
277
208
  return lookupRole(role).literal;
278
209
  }
279
210
 
211
+ /**
212
+ * Resolve the auto-naming model: `@naming` first, falling back to `@fast` so an
213
+ * install that never assigned `naming` resolves EXACTLY as it did before the
214
+ * role existed. `slot` names which role supplied the reference, so a stop error
215
+ * can tell the operator which slot to change. When neither is configured the
216
+ * reason names BOTH slots — naming only one would send the operator to a role
217
+ * that is not the one in force. See change: fix-auto-naming-reasoning-model.
218
+ */
219
+ export function resolveNamingModel(): { literal?: string; reason?: string; slot?: string } {
220
+ const naming = lookupRole("@naming");
221
+ if (naming.literal) return { literal: naming.literal, slot: "naming" };
222
+ const fast = lookupRole("@fast");
223
+ if (fast.literal) return { literal: fast.literal, slot: "fast" };
224
+ return { reason: `${naming.reason ?? "role 'naming' unset"}; ${fast.reason ?? "role 'fast' unset"}` };
225
+ }
226
+
280
227
  // -- Extension entry point ------------------------------------------------
281
228
 
282
229
  /**
@@ -13,6 +13,12 @@
13
13
  * role slice, so a missing/malformed `providers.json#roles` cannot break model
14
14
  * discovery.
15
15
  *
16
+ * Cwd-independence (change: update-pi-core-0-85-adopt-apis, task 5.1): these
17
+ * tools are intentionally cwd-independent — they read the in-process session
18
+ * registry and the machine-wide `~/.pi/agent/providers.json` (an absolute
19
+ * path), and resolve no session-relative path or spawn a process. `ctx.cwd` is
20
+ * never consulted.
21
+ *
16
22
  * See change: add-agent-role-model-tools.
17
23
  */
18
24
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
@@ -28,6 +34,14 @@ import {
28
34
  export interface RoleModelToolsDeps {
29
35
  /** Returns the in-process session ModelRegistry (bridge's cachedModelRegistry). */
30
36
  getRegistry: () => any;
37
+ /**
38
+ * Returns the session's resolved model scope (`ctx.scopedModels`, pi ≥ 0.83.0)
39
+ * read from the LIVE ctx at call time (the scope is dynamic — Ctrl+P cycling).
40
+ * Absent on older pi, or an empty array when no scoping is configured; in both
41
+ * cases `list_models` output is byte-identical to the pre-adoption behavior.
42
+ * See change: update-pi-core-0-83-adopt-apis.
43
+ */
44
+ getScopedModels?: () => unknown;
31
45
  }
32
46
 
33
47
  // ── list_models row shape ───────────────────────────────────────────────────
@@ -81,6 +95,28 @@ export function buildModelRows(registry: any, annotated: boolean): ModelRow[] {
81
95
  });
82
96
  }
83
97
 
98
+ /**
99
+ * Constrain rows to a NON-EMPTY `ctx.scopedModels` scope. Each scoped entry is
100
+ * `{ model, thinkingLevel? }` where `model` is a Model OBJECT (not a ref string);
101
+ * the ref is derived as `provider/id` to match the row `ref` key `buildModelRows`
102
+ * builds. Absent, non-array, or EMPTY scope → rows returned unchanged (the
103
+ * empty-when-unscoped case must NOT empty the catalogue). A scope that yields no
104
+ * parseable ref also returns rows unchanged (safe). Exported for unit tests.
105
+ * See change: update-pi-core-0-83-adopt-apis.
106
+ */
107
+ export function filterRowsByScope(rows: ModelRow[], scopedModels: unknown): ModelRow[] {
108
+ if (!Array.isArray(scopedModels) || scopedModels.length === 0) return rows;
109
+ const refs = new Set<string>();
110
+ for (const entry of scopedModels) {
111
+ const m = (entry as any)?.model ?? entry;
112
+ const provider = (m as any)?.provider;
113
+ const id = (m as any)?.id;
114
+ if (provider != null && id != null) refs.add(`${provider}/${id}`);
115
+ }
116
+ if (refs.size === 0) return rows;
117
+ return rows.filter((r) => refs.has(r.ref));
118
+ }
119
+
84
120
  // ── list_models result envelope (registry-readiness discriminator) ──────────
85
121
 
86
122
  export interface ModelsResult {
@@ -99,7 +135,11 @@ export interface ModelsResult {
99
135
  * models" (true answer). Additive/backward-compatible: consumers reading only
100
136
  * `models` are unaffected. See change: fix-list-models-empty-on-unhydrated-registry.
101
137
  */
102
- export function buildModelsResult(registry: any, annotated: boolean): ModelsResult {
138
+ export function buildModelsResult(
139
+ registry: any,
140
+ annotated: boolean,
141
+ scopedModels?: unknown,
142
+ ): ModelsResult {
103
143
  if (!registry) {
104
144
  return {
105
145
  models: [],
@@ -107,7 +147,8 @@ export function buildModelsResult(registry: any, annotated: boolean): ModelsResu
107
147
  reason: "model registry not yet hydrated in this session; retry shortly",
108
148
  };
109
149
  }
110
- return { models: buildModelRows(registry, annotated), registryReady: true };
150
+ const rows = filterRowsByScope(buildModelRows(registry, annotated), scopedModels);
151
+ return { models: rows, registryReady: true };
111
152
  }
112
153
 
113
154
  // ── Registration ─────────────────────────────────────────────────────────────
@@ -129,7 +170,7 @@ export function registerRoleModelTools(pi: ExtensionAPI, deps: RoleModelToolsDep
129
170
  }),
130
171
  async execute(_id: any, params: any, _signal: any, _onUpdate: any, _ctx: any) {
131
172
  const annotated = params?.annotated === true;
132
- const result = buildModelsResult(deps.getRegistry(), annotated);
173
+ const result = buildModelsResult(deps.getRegistry(), annotated, deps.getScopedModels?.());
133
174
  return {
134
175
  content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
135
176
  details: result,