@blackbelt-technology/pi-agent-dashboard 0.10.0 → 0.11.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 (255) hide show
  1. package/AGENTS.md +2 -2
  2. package/README.md +47 -6
  3. package/docs/architecture.md +1369 -63
  4. package/package.json +14 -9
  5. package/packages/extension/package.json +5 -3
  6. package/packages/extension/src/bridge-handlers/dispatch.ts +57 -3
  7. package/packages/extension/src/bridge-handlers/instance.ts +10 -1
  8. package/packages/extension/src/bridge-handlers/lifecycle.ts +65 -26
  9. package/packages/extension/src/bridge-ticket-client.ts +61 -7
  10. package/packages/extension/src/bridge-tls-checks.ts +79 -0
  11. package/packages/extension/src/bridge.ts +41 -28
  12. package/packages/extension/src/canvas-tool.ts +2 -0
  13. package/packages/extension/src/command-handler.ts +80 -6
  14. package/packages/extension/src/connect-target.ts +23 -0
  15. package/packages/extension/src/connection.ts +30 -7
  16. package/packages/extension/src/dashboard-http-origin.ts +88 -0
  17. package/packages/extension/src/dev-build.ts +11 -1
  18. package/packages/extension/src/git-link-builder.ts +11 -2
  19. package/packages/extension/src/inbound-limits.ts +138 -0
  20. package/packages/extension/src/local-token-header.ts +77 -6
  21. package/packages/extension/src/model-refresh.ts +69 -0
  22. package/packages/extension/src/pinned-endpoint.ts +44 -0
  23. package/packages/extension/src/project-trust-live.ts +143 -0
  24. package/packages/extension/src/project-trust.ts +159 -20
  25. package/packages/extension/src/provider-register.ts +59 -18
  26. package/packages/extension/src/remote-registration-gate.ts +21 -21
  27. package/packages/extension/src/remote-upgrade-preparer.ts +104 -0
  28. package/packages/extension/src/role-model-tools.ts +47 -6
  29. package/packages/extension/src/server-auto-start.ts +1 -1
  30. package/packages/extension/src/server-proof-probe.ts +117 -0
  31. package/packages/extension/src/session-sync.ts +42 -12
  32. package/packages/extension/src/vault-delivery.ts +11 -1
  33. package/packages/server/package.json +8 -8
  34. package/packages/server/src/access/access-grants.ts +61 -8
  35. package/packages/server/src/access/access-health.ts +10 -0
  36. package/packages/server/src/access/access-plane.ts +5 -1
  37. package/packages/server/src/access/containment-gate.ts +55 -17
  38. package/packages/server/src/access/cwd-verdict.ts +3 -3
  39. package/packages/server/src/access/pi-trust-live.ts +244 -0
  40. package/packages/server/src/access/pi-trust-mirror-service.ts +44 -11
  41. package/packages/server/src/access/planes.ts +106 -1
  42. package/packages/server/src/access/preview-egress-store.ts +153 -0
  43. package/packages/server/src/access/prompt-channel.ts +5 -0
  44. package/packages/server/src/access/provisioning-wiring.ts +113 -0
  45. package/packages/server/src/access/provisioning.ts +763 -0
  46. package/packages/server/src/access/yolo-session.ts +54 -2
  47. package/packages/server/src/acp-bridge/acp-session-adapter.ts +8 -3
  48. package/packages/server/src/agent-events/agent-event-hub.ts +158 -0
  49. package/packages/server/src/auth/audit-log.ts +80 -0
  50. package/packages/server/src/auth/auth-plugin.ts +44 -25
  51. package/packages/server/src/auth/auth.ts +24 -4
  52. package/packages/server/src/auth/bearer-auth.ts +52 -12
  53. package/packages/server/src/auth/cors-origin.ts +76 -29
  54. package/packages/server/src/auth/csp-report-paths.ts +31 -0
  55. package/packages/server/src/auth/csp-report-sink.ts +302 -0
  56. package/packages/server/src/auth/csp-report-store.ts +406 -0
  57. package/packages/server/src/auth/csp.ts +105 -9
  58. package/packages/server/src/auth/dashboard-credential-store.ts +4 -0
  59. package/packages/server/src/auth/dashboard-state-caller.ts +29 -0
  60. package/packages/server/src/auth/local-proof-refusal-log.ts +89 -0
  61. package/packages/server/src/auth/local-proof.ts +69 -18
  62. package/packages/server/src/auth/localhost-guard.ts +48 -10
  63. package/packages/server/src/auth/nav-intent.ts +72 -0
  64. package/packages/server/src/auth/passkey/passkey-assets.ts +99 -0
  65. package/packages/server/src/auth/passkey/passkey-pages.ts +17 -81
  66. package/packages/server/src/auth/passkey/passkey-routes.ts +8 -0
  67. package/packages/server/src/auth/pi-legacy-credentials.ts +3 -0
  68. package/packages/server/src/auth/plugin-server-trust.ts +29 -0
  69. package/packages/server/src/auth/plugin-trust-store.ts +103 -0
  70. package/packages/server/src/auth/proven-tls.ts +45 -0
  71. package/packages/server/src/auth/provider-auth-storage.ts +6 -1
  72. package/packages/server/src/auth/radius-mcp.ts +1 -1
  73. package/packages/server/src/auth/request-principal.ts +32 -0
  74. package/packages/server/src/auth/secret-rotation.ts +246 -0
  75. package/packages/server/src/auth/secure-origin.ts +56 -0
  76. package/packages/server/src/auth/serve-app-host.ts +111 -11
  77. package/packages/server/src/auth/ws-ticket.ts +39 -1
  78. package/packages/server/src/auth/ws-upgrade-reject-log.ts +4 -1
  79. package/packages/server/src/browser-handlers/directory-handler.ts +23 -0
  80. package/packages/server/src/browser-handlers/folder-gate.ts +55 -0
  81. package/packages/server/src/browser-handlers/handler-context.ts +25 -2
  82. package/packages/server/src/browser-handlers/session-action-handler.ts +9 -1
  83. package/packages/server/src/browser-handlers/subscription-handler.ts +100 -2
  84. package/packages/server/src/browser-handlers/terminal-handler.ts +108 -10
  85. package/packages/server/src/canvas/canvas-accumulator.ts +35 -7
  86. package/packages/server/src/cli.ts +210 -39
  87. package/packages/server/src/config-api.ts +23 -1
  88. package/packages/server/src/config-snapshot.ts +48 -1
  89. package/packages/server/src/directory-service.ts +160 -54
  90. package/packages/server/src/event-wiring.ts +143 -108
  91. package/packages/server/src/git-worktree/git-operations.ts +44 -10
  92. package/packages/server/src/git-worktree/redact-git-text.ts +124 -0
  93. package/packages/server/src/git-worktree/ref-arg.ts +39 -0
  94. package/packages/server/src/git-worktree/worktree-init-trust.ts +43 -1
  95. package/packages/server/src/identity/http-road-classification.ts +13 -1
  96. package/packages/server/src/identity/ws-message-scope.ts +1 -0
  97. package/packages/server/src/identity/ws-road-classification.ts +1 -0
  98. package/packages/server/src/known-server-moves.ts +36 -15
  99. package/packages/server/src/lib/browse-roots.ts +118 -17
  100. package/packages/server/src/lib/client-dist.ts +36 -21
  101. package/packages/server/src/lib/dashboard-state-guard.ts +230 -0
  102. package/packages/server/src/lib/diagram-render.ts +4 -6
  103. package/packages/server/src/lib/eml.ts +3 -8
  104. package/packages/server/src/lib/file-cwd-admission.ts +145 -0
  105. package/packages/server/src/lib/grep-worker.ts +23 -0
  106. package/packages/server/src/lib/grep.ts +93 -7
  107. package/packages/server/src/lib/index-html.ts +81 -0
  108. package/packages/server/src/lib/office-preview.ts +2 -3
  109. package/packages/server/src/lib/path-containment.ts +7 -0
  110. package/packages/server/src/lib/resolve-file-mention.ts +11 -9
  111. package/packages/server/src/lib/route-admission.ts +80 -0
  112. package/packages/server/src/lib/writable-md-target.ts +4 -0
  113. package/packages/server/src/lifecycle/recovery-server.ts +65 -18
  114. package/packages/server/src/live-server/capability-redact.ts +15 -0
  115. package/packages/server/src/live-server/live-browser-gate.ts +22 -0
  116. package/packages/server/src/live-server/live-capability.ts +224 -17
  117. package/packages/server/src/live-server/live-csp-report.ts +63 -0
  118. package/packages/server/src/live-server/live-csp.ts +93 -0
  119. package/packages/server/src/live-server/live-egress.ts +435 -0
  120. package/packages/server/src/live-server/live-exposure.ts +149 -0
  121. package/packages/server/src/live-server/live-log.ts +21 -0
  122. package/packages/server/src/live-server/live-origin-scan.ts +298 -0
  123. package/packages/server/src/live-server/live-server-manager.ts +209 -33
  124. package/packages/server/src/live-server/live-server-proxy.ts +162 -17
  125. package/packages/server/src/live-server/live-static.ts +228 -0
  126. package/packages/server/src/openspec/dependencies-file.ts +122 -0
  127. package/packages/server/src/openspec/openspec-change-watcher.ts +3 -1
  128. package/packages/server/src/openspec/openspec-dependency-inputs.ts +281 -0
  129. package/packages/server/src/openspec/openspec-poll-fs-helpers.ts +72 -26
  130. package/packages/server/src/openspec/openspec-poll-worker-pool.ts +48 -12
  131. package/packages/server/src/openspec/openspec-poll-worker.ts +95 -9
  132. package/packages/server/src/openspec/workflow-schema-status.ts +379 -0
  133. package/packages/server/src/openspec/workflow-schema.ts +141 -267
  134. package/packages/server/src/package/npm-search-proxy.ts +5 -2
  135. package/packages/server/src/package/provider-probe.ts +8 -2
  136. package/packages/server/src/pairing/browser-gateway.ts +188 -12
  137. package/packages/server/src/pairing/device-token-services.ts +26 -0
  138. package/packages/server/src/pairing/paired-devices.ts +335 -22
  139. package/packages/server/src/pairing/pairing.ts +34 -4
  140. package/packages/server/src/pairing/socket-locality.ts +26 -0
  141. package/packages/server/src/persistence/preferences-store.ts +9 -0
  142. package/packages/server/src/pi/bridge-channel.ts +33 -0
  143. package/packages/server/src/pi/bridge-upgrade-auth.ts +18 -3
  144. package/packages/server/src/pi/gateway-listeners.ts +9 -3
  145. package/packages/server/src/pi/host-project-trust.ts +14 -6
  146. package/packages/server/src/pi/pi-gateway.ts +191 -21
  147. package/packages/server/src/pi/resource-toggle-trust.ts +1 -1
  148. package/packages/server/src/plugin-discovery-wiring.ts +142 -0
  149. package/packages/server/src/plugin-event-seam.ts +116 -4
  150. package/packages/server/src/plugin-runtime-clients.ts +89 -0
  151. package/packages/server/src/routes/access-routes.ts +159 -9
  152. package/packages/server/src/routes/agent-event-stream-routes.ts +137 -0
  153. package/packages/server/src/routes/canvas-types-routes.ts +20 -6
  154. package/packages/server/src/routes/csp-violations-routes.ts +162 -0
  155. package/packages/server/src/routes/file-routes.ts +329 -209
  156. package/packages/server/src/routes/file-write-binary-routes.ts +77 -20
  157. package/packages/server/src/routes/folder-project-routes.ts +18 -12
  158. package/packages/server/src/routes/git-routes.ts +319 -203
  159. package/packages/server/src/routes/grep-routes.ts +38 -14
  160. package/packages/server/src/routes/known-servers-routes.ts +189 -91
  161. package/packages/server/src/routes/live-server-routes.ts +378 -15
  162. package/packages/server/src/routes/local-proof-routes.ts +14 -0
  163. package/packages/server/src/routes/nav-intent-routes.ts +46 -0
  164. package/packages/server/src/routes/openspec-group-routes.ts +53 -44
  165. package/packages/server/src/routes/openspec-routes.ts +379 -28
  166. package/packages/server/src/routes/package-routes.ts +58 -10
  167. package/packages/server/src/routes/pairing-routes.ts +146 -10
  168. package/packages/server/src/routes/pi-trust-query-routes.ts +330 -0
  169. package/packages/server/src/routes/plugin-activation-routes.ts +59 -0
  170. package/packages/server/src/routes/plugin-runtime-client-routes.ts +149 -0
  171. package/packages/server/src/routes/provider-auth-routes.ts +15 -2
  172. package/packages/server/src/routes/resource-activation-routes.ts +18 -4
  173. package/packages/server/src/routes/session-routes.ts +51 -4
  174. package/packages/server/src/routes/system-routes.ts +84 -15
  175. package/packages/server/src/routes/ui-link-base.ts +88 -0
  176. package/packages/server/src/runtime-overlay/runtime-io.ts +2 -9
  177. package/packages/server/src/server.ts +648 -137
  178. package/packages/server/src/session/hydration-state.ts +148 -0
  179. package/packages/server/src/session/memory-session-manager.ts +7 -0
  180. package/packages/server/src/session/replay-exit-controller.ts +221 -0
  181. package/packages/server/src/session/retained-transcript.ts +9 -2
  182. package/packages/server/src/session/session-load-worker.ts +11 -2
  183. package/packages/server/src/spawn-process/headless-pid-registry.ts +14 -9
  184. package/packages/server/src/terminal/terminal-manager.ts +54 -46
  185. package/packages/server/src/tls/tls-bridge-route.ts +61 -0
  186. package/packages/server/src/tls/tls-config-validation.ts +2 -0
  187. package/packages/server/src/vault/device-expiry-sweep.ts +36 -0
  188. package/packages/server/src/vault/vault-delivery-hub.ts +155 -25
  189. package/packages/server/src/watch-files-handler.ts +66 -0
  190. package/packages/shared/package.json +1 -1
  191. package/packages/shared/src/browser-protocol.ts +148 -2
  192. package/packages/shared/src/canvas-declare.ts +27 -0
  193. package/packages/shared/src/config.ts +372 -53
  194. package/packages/shared/src/containment-guard.ts +35 -0
  195. package/packages/shared/src/dashboard-plugin/anthropic-peer-names.ts +9 -0
  196. package/packages/shared/src/dashboard-plugin/event-type-owners.ts +50 -0
  197. package/packages/shared/src/dashboard-plugin/file-handler.ts +2 -0
  198. package/packages/shared/src/dashboard-plugin/host-api.ts +61 -0
  199. package/packages/shared/src/dashboard-plugin/host-fx-classes.ts +23 -0
  200. package/packages/shared/src/dashboard-plugin/host-import-map.ts +38 -0
  201. package/packages/shared/src/dashboard-plugin/index.ts +2 -0
  202. package/packages/shared/src/dashboard-plugin/manifest-types.ts +54 -1
  203. package/packages/shared/src/dashboard-plugin/plugin-status.ts +54 -0
  204. package/packages/shared/src/dashboard-plugin/slot-props.ts +45 -3
  205. package/packages/shared/src/dashboard-plugin/slot-types.ts +8 -0
  206. package/packages/shared/src/dashboard-plugin/subagent-types.ts +219 -0
  207. package/packages/shared/src/dashboard-plugin/ui-primitives.ts +28 -0
  208. package/packages/shared/src/display-prefs.ts +13 -0
  209. package/packages/shared/src/doctor-core.ts +94 -27
  210. package/packages/shared/src/live-server.ts +141 -0
  211. package/packages/shared/src/local-proof-signal.ts +16 -0
  212. package/packages/shared/src/loopback-host.ts +26 -0
  213. package/packages/shared/src/mcp/verb-tiers.generated.ts +178 -0
  214. package/packages/shared/src/mdns-discovery.ts +25 -6
  215. package/packages/shared/src/nav-intent.ts +29 -0
  216. package/packages/shared/src/openspec-dependencies.ts +760 -0
  217. package/packages/shared/src/openspec-poller.ts +3 -2
  218. package/packages/shared/src/pairing-knock-client.ts +44 -4
  219. package/packages/shared/src/pi-trust-live-query.ts +93 -0
  220. package/packages/shared/src/pi-trust-mirror-snapshot.ts +5 -7
  221. package/packages/shared/src/pi-trust-mirror-types.ts +36 -3
  222. package/packages/shared/src/pi-trust-mirror.ts +29 -3
  223. package/packages/shared/src/pi-trust-resource-digest.ts +255 -0
  224. package/packages/shared/src/platform/ensure-bundled-git.ts +57 -34
  225. package/packages/shared/src/platform/git-source.ts +88 -26
  226. package/packages/shared/src/platform/git.ts +14 -8
  227. package/packages/shared/src/platform/process.ts +48 -4
  228. package/packages/shared/src/platform/resolve-pi-shell.ts +76 -0
  229. package/packages/shared/src/platform/select-git-source.ts +7 -0
  230. package/packages/shared/src/plugin-route-cwd.ts +95 -0
  231. package/packages/shared/src/preview-egress.ts +138 -0
  232. package/packages/shared/src/project-root.ts +16 -0
  233. package/packages/shared/src/protocol.ts +40 -1
  234. package/packages/shared/src/recommended-extensions.ts +18 -0
  235. package/packages/shared/src/recovery-timing.ts +27 -0
  236. package/packages/shared/src/remote-credentials.ts +63 -0
  237. package/packages/shared/src/rest-api.ts +55 -8
  238. package/packages/shared/src/route-tiers.ts +55 -1
  239. package/packages/shared/src/runtime-overlay/archive-safety.d.mts +2 -0
  240. package/packages/shared/src/runtime-overlay/archive-safety.mjs +33 -0
  241. package/packages/shared/src/runtime-overlay/manifest.d.mts +7 -0
  242. package/packages/shared/src/runtime-overlay/manifest.mjs +22 -2
  243. package/packages/shared/src/safe-local-path.ts +24 -0
  244. package/packages/shared/src/sanitize-profiles.ts +98 -0
  245. package/packages/shared/src/server-launcher.ts +9 -1
  246. package/packages/shared/src/server-pinning.ts +55 -2
  247. package/packages/shared/src/server-routes.ts +462 -0
  248. package/packages/shared/src/session-ui-path.ts +11 -0
  249. package/packages/shared/src/tls-only-token.ts +16 -0
  250. package/packages/shared/src/tool-registry/definitions.ts +5 -5
  251. package/packages/shared/src/tool-registry/strategies.ts +12 -11
  252. package/packages/shared/src/types.ts +66 -0
  253. package/packages/shared/src/url-policy.ts +96 -0
  254. package/packages/shared/src/vault-delivery.ts +15 -0
  255. package/packages/shared/src/ws-message-tiers.ts +1 -0
@@ -1,5 +1,5 @@
1
1
  /**
2
- * `project_trust` auto-decision — the bridge's snapshot-only decision.
2
+ * `project_trust` auto-decision — the bridge's snapshot decision plus a bounded live step.
3
3
  *
4
4
  * A dashboard-spawned headless RPC session has no human at pi's TUI to answer
5
5
  * `project_trust`, so pi leaves the no-UI decision un-trusted and the session can
@@ -12,21 +12,39 @@
12
12
  * every session when `piTrustMirror.coverInteractive` is on.
13
13
  *
14
14
  * Neither contacts the server: config, pi's `trust.json` (lockless, pi's own
15
- * reading rules) and the snapshot are read per event, never cached. Everything
16
- * doubtful is `undecided`. A recorded pi entry (true OR false) always wins, and
15
+ * reading rules) and the snapshot are read per event, never cached. Only when the
16
+ * snapshot does not cover the cwd — and the snapshot reports live (server-lifetime)
17
+ * entries, or this is a REMOTE bridge — does a third rule ask the server, once, over
18
+ * an authenticated one-shot HTTP request, under ONE deadline (`liveQueryTimeoutMs`)
19
+ * that bounds the request and the folder-proof check together. Every failure is
20
+ * `undecided` with a reason code. Everything doubtful is `undecided`. A recorded pi entry (true OR false) always wins, and
17
21
  * forbidden/temporary folders never auto-trust. Pure decision logic lives here
18
22
  * (deps injected) so it is unit-testable without the bridge.
19
23
  *
20
24
  * pi emits `project_trust` during resource-loader reload, BEFORE `session_start`,
21
25
  * so the activation cwd is captured at bridge module scope.
22
26
  *
23
- * See change: adopt-pi-074-080-features (A.3), mirror-dashboard-trust-to-pi.
27
+ * See change: adopt-pi-074-080-features (A.3), mirror-dashboard-trust-to-pi,
28
+ * mirror-dashboard-trust-live-remote.
24
29
  */
25
30
  import os from "node:os";
26
31
  import type { PiTrustMirrorConfig } from "@blackbelt-technology/pi-dashboard-shared/config.js";
27
- import { loadConfig } from "@blackbelt-technology/pi-dashboard-shared/config.js";
32
+ import { effectiveLiveQueryTimeoutMs, loadConfig } from "@blackbelt-technology/pi-dashboard-shared/config.js";
28
33
  import { resolvePiAgentDir } from "@blackbelt-technology/pi-dashboard-shared/dashboard-paths.js";
29
- import { isMirrorDenied, type MirrorDenyRules, mirrorDenyRules } from "@blackbelt-technology/pi-dashboard-shared/pi-trust-mirror.js";
34
+ import {
35
+ isRemoteLiveAnswer,
36
+ parsePiTrustLiveAnswer,
37
+ } from "@blackbelt-technology/pi-dashboard-shared/pi-trust-live-query.js";
38
+ import {
39
+ ancestorKeys,
40
+ type FolderIdentity,
41
+ identityMatches,
42
+ isCanonicalAbsolutePath,
43
+ isMirrorDenied,
44
+ type MirrorDenyRules,
45
+ mirrorDenyRules,
46
+ statFolderIdentityAsync,
47
+ } from "@blackbelt-technology/pi-dashboard-shared/pi-trust-mirror.js";
30
48
  import {
31
49
  coverSnapshot,
32
50
  nearestRecordedEntry,
@@ -36,6 +54,11 @@ import {
36
54
  safePiTrustKey,
37
55
  } from "@blackbelt-technology/pi-dashboard-shared/pi-trust-mirror-snapshot.js";
38
56
  import type { MirrorWithheldReason, PiTrustSnapshot } from "@blackbelt-technology/pi-dashboard-shared/pi-trust-mirror-types.js";
57
+ import {
58
+ trustResourceDigest,
59
+ trustResourceManifest,
60
+ } from "@blackbelt-technology/pi-dashboard-shared/pi-trust-resource-digest.js";
61
+ import type { LiveQueryFn } from "./project-trust-live.js";
39
62
 
40
63
  export interface ProjectTrustDecisionInput {
41
64
  /** True when this pi was spawned by the dashboard (spawn token captured at activation). */
@@ -57,6 +80,13 @@ export interface ProjectTrustDeps {
57
80
  denyRules: () => MirrorDenyRules;
58
81
  /** Receives one line per withheld decision of a dashboard-spawned session. */
59
82
  log: (line: string) => void;
83
+ /** Is the dashboard endpoint remote (non-loopback, with a paired-device token)? Default: no. */
84
+ isRemoteBridge: () => boolean;
85
+ /** The live query transport. Default: unreachable (no endpoint known outside the bridge). */
86
+ liveQuery: LiveQueryFn;
87
+ /** Async folder-proof inputs (all honour the deadline's `AbortSignal`). */
88
+ manifest: typeof trustResourceManifest;
89
+ statIdentity: (dir: string, signal: AbortSignal) => Promise<FolderIdentity | null>;
60
90
  }
61
91
 
62
92
  export interface ProjectTrustResult {
@@ -64,7 +94,7 @@ export interface ProjectTrustResult {
64
94
  /** Why trust was withheld (undecided only). */
65
95
  reason?: MirrorWithheldReason;
66
96
  /** Which rule granted "yes". */
67
- via?: "activation" | "mirror";
97
+ via?: "activation" | "mirror" | "live";
68
98
  }
69
99
 
70
100
  const UNDECIDED: ProjectTrustResult = { trusted: "undecided" };
@@ -79,17 +109,23 @@ function defaultDeps(): ProjectTrustDeps {
79
109
  readTrustFile: readPiTrustFileLockless,
80
110
  denyRules: () => mirrorDenyRules({ homedir: home }),
81
111
  log: (line) => console.error(`[dashboard] ${line}`),
112
+ isRemoteBridge: () => false,
113
+ liveQuery: async () => ({ kind: "unreachable" }),
114
+ manifest: trustResourceManifest,
115
+ statIdentity: statFolderIdentityAsync,
82
116
  };
83
117
  }
84
118
 
85
119
  /**
86
120
  * Decide `project_trust` for one event. Never throws: any error → undecided.
87
- * Order: unreadable store → recorded pi entry → activation rule → mirror rule.
121
+ * Order: unreadable store → recorded pi entry → activation rule → snapshot rule →
122
+ * live query (only on a snapshot miss, under its conditions). The live step is the
123
+ * only part that awaits, and it is bounded by `liveQueryTimeoutMs`.
88
124
  */
89
- export function decideBridgeProjectTrust(
125
+ export async function decideBridgeProjectTrust(
90
126
  input: ProjectTrustDecisionInput,
91
127
  overrides: Partial<ProjectTrustDeps> = {},
92
- ): ProjectTrustResult {
128
+ ): Promise<ProjectTrustResult> {
93
129
  try {
94
130
  const deps = { ...defaultDeps(), ...overrides };
95
131
  if (input.eventCwd === undefined) return UNDECIDED;
@@ -107,7 +143,7 @@ export function decideBridgeProjectTrust(
107
143
  if (spawnedHeadless && safePiTrustKey(input.activationCwd, deps.home) === cwdKey) {
108
144
  return isMirrorDenied(cwdKey, deps.denyRules()) ? withheld("forbidden-folder") : { trusted: "yes", via: "activation" };
109
145
  }
110
- return decideFromMirror(input, deps, cwdKey, withheld);
146
+ return await decideFromMirror(input, deps, cwdKey, withheld);
111
147
  } catch {
112
148
  return UNDECIDED;
113
149
  }
@@ -121,21 +157,124 @@ function piStoreBlocks(deps: ProjectTrustDeps, cwdKey: string): MirrorWithheldRe
121
157
  return null;
122
158
  }
123
159
 
124
- /** The snapshot rule: enabled, covered by a still-valid entry, and an allowed session class. */
125
- function decideFromMirror(
160
+ /** The snapshot rule, then the live query: enabled, covered, and an allowed session class. */
161
+ async function decideFromMirror(
126
162
  input: ProjectTrustDecisionInput,
127
163
  deps: ProjectTrustDeps,
128
164
  cwdKey: string,
129
165
  withheld: (reason: MirrorWithheldReason) => ProjectTrustResult,
130
- ): ProjectTrustResult {
166
+ ): Promise<ProjectTrustResult> {
131
167
  const cfg = deps.readConfig();
132
168
  if (!cfg.enabled) return UNDECIDED;
133
- const coverage = coverSnapshot(deps.readSnapshot(), cwdKey);
134
- if (!coverage.covered) return coverage.reason ? withheld(coverage.reason) : UNDECIDED;
135
- if ((input.dashboardSpawned && input.isHeadless) || cfg.coverInteractive) return { trusted: "yes", via: "mirror" };
136
- // Covered, but this session class is not: say so.
137
- if (input.dashboardSpawned) deps.log(`project_trust withheld for ${cwdKey}: not-covered-session`);
138
- return { trusted: "undecided", reason: "not-covered-session" };
169
+ const snapshot = deps.readSnapshot();
170
+ const coverage = coverSnapshot(snapshot, cwdKey);
171
+ const sessionAllowed = (input.dashboardSpawned && input.isHeadless) || cfg.coverInteractive;
172
+ if (coverage.covered) {
173
+ if (sessionAllowed) return { trusted: "yes", via: "mirror" };
174
+ // Covered, but this session class is not: say so.
175
+ if (input.dashboardSpawned) deps.log(`project_trust withheld for ${cwdKey}: not-covered-session`);
176
+ return { trusted: "undecided", reason: "not-covered-session" };
177
+ }
178
+
179
+ // The snapshot yields no cover (for any reason, including identity-mismatch): ask the
180
+ // server when it may know more — live entries exist, or this bridge is remote.
181
+ const remote = deps.isRemoteBridge();
182
+ if (shouldAskServer({ sessionAllowed, cfg, cwdKey, deps, liveCount: snapshot?.liveCount ?? 0, remote })) {
183
+ const live = await runLiveQuery(deps, cfg, cwdKey, remote);
184
+ return live.ok ? { trusted: "yes", via: "live" } : withheld(live.reason);
185
+ }
186
+ return coverage.reason ? withheld(coverage.reason) : UNDECIDED;
187
+ }
188
+
189
+ /** The live-query conditions: switches on, allowed session, not a denied folder, and something to learn. */
190
+ function shouldAskServer(c: {
191
+ sessionAllowed: boolean;
192
+ cfg: PiTrustMirrorConfig;
193
+ cwdKey: string;
194
+ deps: ProjectTrustDeps;
195
+ liveCount: number;
196
+ remote: boolean;
197
+ }): boolean {
198
+ if (!c.sessionAllowed || !c.cfg.liveQuery || isMirrorDenied(c.cwdKey, c.deps.denyRules())) return false;
199
+ return c.liveCount > 0 || c.remote;
200
+ }
201
+
202
+ type LiveOutcome = { ok: true } | { ok: false; reason: MirrorWithheldReason };
203
+
204
+ /**
205
+ * One live query under ONE deadline. The deadline is enforced by racing, not by
206
+ * cooperation: the whole step (request + folder-proof check) is `Promise.race`d
207
+ * against a timer, and on either outcome a per-call `AbortController` is aborted so
208
+ * no socket or filesystem walk outlives the handler. Never throws.
209
+ */
210
+ async function runLiveQuery(
211
+ deps: ProjectTrustDeps,
212
+ cfg: PiTrustMirrorConfig,
213
+ cwdKey: string,
214
+ remote: boolean,
215
+ ): Promise<LiveOutcome> {
216
+ const controller = new AbortController();
217
+ let timer: ReturnType<typeof setTimeout> | undefined;
218
+ const deadline = new Promise<LiveOutcome>((resolve) => {
219
+ timer = setTimeout(() => resolve({ ok: false, reason: "live-timeout" }), effectiveLiveQueryTimeoutMs(cfg, remote));
220
+ });
221
+ const work = liveWork(deps, cwdKey, remote, controller.signal).catch(
222
+ (): LiveOutcome => ({ ok: false, reason: "live-error" }),
223
+ );
224
+ try {
225
+ return await Promise.race([work, deadline]);
226
+ } finally {
227
+ clearTimeout(timer);
228
+ controller.abort();
229
+ }
230
+ }
231
+
232
+ function mapStatus(status: number): MirrorWithheldReason {
233
+ if (status === 401 || status === 403) return "live-refused";
234
+ if (status === 404) return "live-unsupported";
235
+ if (status === 429) return "live-rate-limited";
236
+ return "live-error";
237
+ }
238
+
239
+ /** Remote proof: recompute the digest of pi's trust-requiring resources HERE and compare. */
240
+ async function verifyRemoteProof(
241
+ deps: ProjectTrustDeps,
242
+ cwdKey: string,
243
+ answer: { salt: string; digest: string },
244
+ signal: AbortSignal,
245
+ ): Promise<LiveOutcome> {
246
+ const manifest = await deps.manifest(cwdKey, { home: deps.home, signal });
247
+ if (signal.aborted) return { ok: false, reason: "live-timeout" };
248
+ if (manifest === null) return { ok: false, reason: "identity-weak" };
249
+ return trustResourceDigest(answer.salt, cwdKey, manifest) === answer.digest
250
+ ? { ok: true }
251
+ : { ok: false, reason: "identity-mismatch" };
252
+ }
253
+
254
+ /** Local proof: the identity the server recorded when it created the live entry. */
255
+ async function verifyLocalProof(
256
+ deps: ProjectTrustDeps,
257
+ cwdKey: string,
258
+ answer: { key: string; dev: string; ino: string; birthtimeMs?: number },
259
+ signal: AbortSignal,
260
+ ): Promise<LiveOutcome> {
261
+ if (!isCanonicalAbsolutePath(answer.key) || !ancestorKeys(cwdKey).includes(answer.key)) {
262
+ return { ok: false, reason: "live-error" };
263
+ }
264
+ const observed = await deps.statIdentity(answer.key, signal);
265
+ if (signal.aborted) return { ok: false, reason: "live-timeout" };
266
+ return identityMatches(answer, observed) ? { ok: true } : { ok: false, reason: "identity-mismatch" };
267
+ }
268
+
269
+ async function liveWork(deps: ProjectTrustDeps, cwdKey: string, remote: boolean, signal: AbortSignal): Promise<LiveOutcome> {
270
+ const res = await deps.liveQuery({ cwdKey, remote, signal });
271
+ if (res.kind === "unreachable") return { ok: false, reason: "live-unreachable" };
272
+ if (res.kind === "error") return { ok: false, reason: "live-error" };
273
+ if (res.status !== 200) return { ok: false, reason: mapStatus(res.status) };
274
+ const answer = parsePiTrustLiveAnswer(res.body);
275
+ if (!answer) return { ok: false, reason: "live-error" };
276
+ if (!answer.covered) return { ok: false, reason: "live-not-covered" };
277
+ return isRemoteLiveAnswer(answer) ? verifyRemoteProof(deps, cwdKey, answer, signal) : verifyLocalProof(deps, cwdKey, answer, signal);
139
278
  }
140
279
 
141
280
  /**
@@ -473,28 +473,63 @@ function entriesEqual(a: ProviderEntry, b: ProviderEntry): boolean {
473
473
 
474
474
  // -- Config I/O (read-only — providers section) ----------------------------
475
475
 
476
- function loadProviders(): Record<string, ProviderEntry> {
476
+ /**
477
+ * Tri-state read of providers.json. `unreadable` (IO/parse error, `providers`
478
+ * absent or not a plain object, or any non-plain-object entry) is never treated
479
+ * as an empty map: a re-sync on an unreadable file must not unregister every
480
+ * custom provider (e.g. mid-save of a non-atomic hand-edit). Only a fully
481
+ * well-formed `providers` (including `{}`) is `ok`.
482
+ * See change: list-models-auto-resync (design D5).
483
+ */
484
+ type LoadedProviders =
485
+ | { kind: "absent" }
486
+ | { kind: "ok"; providers: Record<string, ProviderEntry> }
487
+ | { kind: "unreadable"; error: string };
488
+
489
+ function isPlainObject(v: unknown): v is Record<string, unknown> {
490
+ return typeof v === "object" && v !== null && !Array.isArray(v);
491
+ }
492
+
493
+ function loadProviders(): LoadedProviders {
477
494
  const path = configPath();
478
- if (existsSync(path)) {
479
- try {
480
- const raw = JSON.parse(readFileSync(path, "utf-8"));
481
- const providers: Record<string, ProviderEntry> = { ...raw.providers };
482
- for (const [, entry] of Object.entries(providers) as [string, any][]) {
483
- if (entry.apiKeyEnv && !entry.apiKey) {
484
- entry.apiKey = "$" + entry.apiKeyEnv;
485
- delete entry.apiKeyEnv;
495
+ if (!existsSync(path)) {
496
+ lastUnreadableError = undefined;
497
+ return { kind: "absent" };
498
+ }
499
+ let error: string;
500
+ try {
501
+ const raw = JSON.parse(readFileSync(path, "utf-8"));
502
+ if (!isPlainObject(raw) || !isPlainObject(raw.providers)) {
503
+ error = "`providers` is missing or not an object";
504
+ } else {
505
+ const bad = Object.entries(raw.providers).find(([, e]) => !isPlainObject(e));
506
+ if (bad) {
507
+ error = `provider entry "${bad[0]}" is not an object`;
508
+ } else {
509
+ const providers = { ...raw.providers } as Record<string, ProviderEntry>;
510
+ for (const [, entry] of Object.entries(providers) as [string, any][]) {
511
+ if (entry.apiKeyEnv && !entry.apiKey) {
512
+ entry.apiKey = "$" + entry.apiKeyEnv;
513
+ delete entry.apiKeyEnv;
514
+ }
515
+ delete (entry as any).modelIds;
486
516
  }
487
- delete (entry as any).modelIds;
517
+ lastUnreadableError = undefined;
518
+ return { kind: "ok", providers };
488
519
  }
489
- return providers;
490
- } catch (err: any) {
491
- console.error(
492
- `[dashboard] providers.json reload failed: ${err?.message ?? String(err)}`,
493
- );
494
520
  }
521
+ } catch (err: any) {
522
+ error = err?.message ?? String(err);
523
+ }
524
+ // Log once per distinct error: a roles-only file (no `providers` key) is
525
+ // re-read on every resync and must not spam the TUI.
526
+ if (error !== lastUnreadableError) {
527
+ console.error(`[dashboard] providers.json reload failed (keeping current providers): ${error}`);
528
+ lastUnreadableError = error;
495
529
  }
496
- return {};
530
+ return { kind: "unreadable", error };
497
531
  }
532
+ let lastUnreadableError: string | undefined;
498
533
 
499
534
  // -- API key resolution ---------------------------------------------------
500
535
 
@@ -955,7 +990,10 @@ async function reloadProvidersNow(
955
990
 
956
991
  let current: Record<string, ProviderEntry>;
957
992
  try {
958
- current = loadProviders();
993
+ const loaded = loadProviders();
994
+ // Unreadable → empty diff, `lastRegistered` untouched (design D5).
995
+ if (loaded.kind === "unreadable") return { added, removed, changed };
996
+ current = loaded.kind === "ok" ? loaded.providers : {};
959
997
  } catch {
960
998
  return { added, removed, changed };
961
999
  }
@@ -1107,7 +1145,10 @@ async function resolveModelProbe(probe: any, ref: string): Promise<void> {
1107
1145
 
1108
1146
  export function activate(pi: ExtensionAPI) {
1109
1147
  piRef = pi;
1110
- const providers = loadProviders();
1148
+ // Unreadable is treated like absent here: nothing is registered yet, so
1149
+ // nothing is lost. See change: list-models-auto-resync (design D5).
1150
+ const loaded = loadProviders();
1151
+ const providers = loaded.kind === "ok" ? loaded.providers : {};
1111
1152
 
1112
1153
  // Register providers (async discovery, fire-and-forget at startup).
1113
1154
  // Startup registrations join `reloadChain` so a re-sync arriving during
@@ -10,10 +10,11 @@
10
10
  *
11
11
  * The challenge is injected so the decision table is testable without I/O.
12
12
  *
13
- * See change: add-pi-gateway-transport-identity (D8).
13
+ * See change: add-pi-gateway-transport-identity (D8), fix-remote-bridge-ticket-origin (D2).
14
14
  */
15
15
  import type { PinVerdict, ServerPin } from "@blackbelt-technology/pi-dashboard-shared/server-pinning.js";
16
- import { challengePinnedServer } from "@blackbelt-technology/pi-dashboard-shared/server-pinning.js";
16
+ import { challengePinnedServer, TLS_VERIFY_ENV, tlsVerifyDisabled } from "@blackbelt-technology/pi-dashboard-shared/server-pinning.js";
17
+ import { resolveDashboardHttpOrigin } from "./dashboard-http-origin.js";
17
18
  import type { PinnedServer, ServerPinStore } from "./server-pin-store.js";
18
19
  import { resolvePinForEndpoint } from "./server-pin-store.js";
19
20
 
@@ -30,19 +31,7 @@ export function isRemoteEndpoint(endpoint: string): boolean {
30
31
  }
31
32
  }
32
33
 
33
- /** The http origin serving `/api/pair/challenge` for a ws endpoint. */
34
- export function httpBaseUrlFor(endpoint: string): string | null {
35
- try {
36
- const u = new URL(endpoint);
37
- if (u.protocol === "ws:") return `http://${u.host}`;
38
- if (u.protocol === "wss:") return `https://${u.host}`;
39
- return null;
40
- } catch {
41
- return null;
42
- }
43
- }
44
-
45
- type GateCause = PinVerdict["cause"] | "local" | "unpinned-legacy";
34
+ type GateCause = PinVerdict["cause"] | "local" | "unpinned-legacy" | "bad-http-url" | "no-http-origin";
46
35
 
47
36
  export interface GateResult {
48
37
  allow: boolean;
@@ -55,11 +44,11 @@ export interface GateResult {
55
44
  export interface GateInput {
56
45
  endpoint: string;
57
46
  store: ServerPinStore;
47
+ /** Required, not optional: an omitted env would silently drop `PI_DASHBOARD_HTTP_URL`. */
48
+ env: Record<string, string | undefined>;
58
49
  challenge?: (baseUrl: string, pin: ServerPin) => Promise<PinVerdict>;
59
50
  }
60
51
 
61
- const defaultChallenge = (baseUrl: string, pin: ServerPin) => challengePinnedServer({ baseUrl, pin });
62
-
63
52
  /**
64
53
  * Decide whether this bridge may register over `endpoint`.
65
54
  *
@@ -88,11 +77,22 @@ export async function gateRemoteRegistration(input: GateInput): Promise<GateResu
88
77
  reason: `refused: ${input.endpoint} matches no pinned server identity`,
89
78
  };
90
79
  }
91
- const baseUrl = httpBaseUrlFor(input.endpoint);
92
- if (!baseUrl) {
93
- return { allow: false, cause: "unreachable", reason: `refused: ${input.endpoint} has no http origin to challenge` };
80
+ // The challenge goes to the dashboard HTTP listener (it holds the server key),
81
+ // not to the gateway port the bridge dials.
82
+ const origin = resolveDashboardHttpOrigin(input.endpoint, input.env);
83
+ if (!origin.ok) {
84
+ return { allow: false, cause: origin.cause, reason: `refused: ${origin.reason}` };
85
+ }
86
+ // TLS origin with validation disabled in the process: no request at all (D7).
87
+ if (/^https:/i.test(origin.origin) && tlsVerifyDisabled(input.env)) {
88
+ return {
89
+ allow: false,
90
+ cause: "tls-verify-disabled",
91
+ reason: `refused: ${TLS_VERIFY_ENV}=0 disables certificate validation; ${origin.origin} is not contacted (trust a private CA with NODE_EXTRA_CA_CERTS instead)`,
92
+ };
94
93
  }
95
- const verdict = await (input.challenge ?? defaultChallenge)(baseUrl, pin);
94
+ const challenge = input.challenge ?? ((baseUrl: string, p: ServerPin) => challengePinnedServer({ baseUrl, pin: p, env: input.env }));
95
+ const verdict = await challenge(origin.origin, pin);
96
96
  return {
97
97
  allow: verdict.accept,
98
98
  cause: verdict.cause,
@@ -0,0 +1,104 @@
1
+ /**
2
+ * Mint a fresh, single-use bridge ticket for a REMOTE endpoint.
3
+ *
4
+ * Returns undefined for a local endpoint (nothing to mint) and THROWS when a
5
+ * remote endpoint cannot be authorised, so ConnectionManager retries on its
6
+ * backoff rather than dialling a credential-less upgrade the gateway will
7
+ * refuse. The cause is logged once per attempt: "refused" means the bearer is
8
+ * missing, unpaired or revoked; "wrong-origin" means the HTTP origin is wrong.
9
+ *
10
+ * The HTTP origin comes from `resolveDashboardHttpOrigin` (the gateway port is
11
+ * NOT the HTTP port). A change of origin is logged once through both channels
12
+ * — console and the transport diagnostics — deduped on `origin|source`. The
13
+ * bearer is never logged.
14
+ *
15
+ * Extracted from `bridge.ts` so it is testable without a live bridge.
16
+ *
17
+ * See change: fix-remote-bridge-ticket-origin (D2, D4); harden-bridge-inbound-and-discovery (D19: pinned-only).
18
+ */
19
+ import { mintBridgeTicket, readDeviceToken, withTicket } from "./bridge-ticket-client.js";
20
+ import { checkTlsCall } from "./bridge-tls-checks.js";
21
+ import { resolveDashboardHttpOrigin } from "./dashboard-http-origin.js";
22
+ import { isRemoteEndpoint } from "./remote-registration-gate.js";
23
+
24
+ export interface RemoteUpgradePreparerDeps {
25
+ env: Record<string, string | undefined>;
26
+ fetchImpl?: typeof fetch;
27
+ log: Pick<Console, "log" | "error">;
28
+ /** Mirror of a diagnostic line over the wire (`transportDiagnostics.record`). */
29
+ record: (d: { event: "endpoint_resolved"; detail: string }) => void;
30
+ /**
31
+ * Is `endpoint` pinned (configured endpoint or a pin-store `lastEndpoint`)?
32
+ * Required, not defaulted: an absent gate would silently hand the bearer to
33
+ * any discovered host. See change: harden-bridge-inbound-and-discovery (D19).
34
+ */
35
+ isPinned: (endpoint: string) => boolean;
36
+ }
37
+
38
+ export type RemoteUpgradePreparer = ((endpoint: string) => Promise<{ url?: string } | undefined>) & {
39
+ /** Resolve + log the HTTP origin for a remote endpoint (deduped) without minting. */
40
+ noteOrigin: (endpoint: string) => void;
41
+ };
42
+
43
+ export function createRemoteUpgradePreparer(deps: RemoteUpgradePreparerDeps): RemoteUpgradePreparer {
44
+ let lastEmitted: string | undefined;
45
+
46
+ /** Resolve, and emit one `http origin …` line whenever the outcome differs from the last one. */
47
+ function resolveAndNote(endpoint: string) {
48
+ const resolved = resolveDashboardHttpOrigin(endpoint, deps.env);
49
+ const key = resolved.ok ? `${resolved.origin}|${resolved.source}` : `${resolved.cause}|${endpoint}`;
50
+ if (key !== lastEmitted) {
51
+ lastEmitted = key;
52
+ const line = resolved.ok
53
+ ? `http origin ${resolved.origin} (${resolved.source})`
54
+ : `http origin unresolved: ${resolved.cause}: ${resolved.reason}`;
55
+ deps.log.log(`[dashboard] ${line}`);
56
+ deps.record({ event: "endpoint_resolved", detail: line });
57
+ }
58
+ return resolved;
59
+ }
60
+
61
+ const prepare = async (endpoint: string): Promise<{ url?: string } | undefined> => {
62
+ if (!isRemoteEndpoint(endpoint)) return undefined;
63
+ // The device bearer goes ONLY to a pinned endpoint. A discovery-only host
64
+ // gets no request at all — not even the ticket mint, which carries the
65
+ // bearer. See change: harden-bridge-inbound-and-discovery (D19).
66
+ if (!deps.isPinned(endpoint)) {
67
+ const reason = `${endpoint} is not a configured or pinned endpoint; the device bearer is not sent to a discovered host`;
68
+ deps.log.error(`[dashboard] bridge ticket unpinned_discovered_host: ${reason}`);
69
+ throw new Error(reason);
70
+ }
71
+ const resolved = resolveAndNote(endpoint);
72
+ if (!resolved.ok) {
73
+ deps.log.error(`[dashboard] bridge ticket ${resolved.cause}: ${resolved.reason}`);
74
+ throw new Error(resolved.reason);
75
+ }
76
+ // After `bad-http-url`: `tls-only-token`, then `tls-verify-disabled` (read per
77
+ // attempt, so a runtime flip is caught on the next reconnect). A refusal sends
78
+ // no bearer and does not dial. See change: prove-vault-bridge-tls (D7, D9).
79
+ const token = readDeviceToken(deps.env);
80
+ const refusal = checkTlsCall({ origin: resolved.origin, token, dialUrl: endpoint, env: deps.env });
81
+ if (refusal) {
82
+ deps.log.error(`[dashboard] bridge ticket ${refusal.cause}: ${refusal.reason}`);
83
+ throw new Error(refusal.reason);
84
+ }
85
+ const minted = await mintBridgeTicket({
86
+ httpBase: resolved.origin,
87
+ token,
88
+ originSource: resolved.source,
89
+ fetchImpl: deps.fetchImpl,
90
+ env: deps.env,
91
+ });
92
+ if (!minted.ok) {
93
+ deps.log.error(`[dashboard] bridge ticket ${minted.cause}: ${minted.reason}`);
94
+ throw new Error(minted.reason);
95
+ }
96
+ return { url: withTicket(endpoint, minted.ticket) };
97
+ };
98
+
99
+ return Object.assign(prepare, {
100
+ noteOrigin: (endpoint: string) => {
101
+ if (isRemoteEndpoint(endpoint)) resolveAndNote(endpoint);
102
+ },
103
+ });
104
+ }
@@ -2,9 +2,11 @@
2
2
  * Agent-facing role/model tools (capability `agent-role-model-tools`).
3
3
  *
4
4
  * Three decoupled tools registered via `pi.registerTool` at bridge activation:
5
- * - `list_models` — READ. Assignable model catalogue from the IN-PROCESS
6
- * session registry (the exact ModelSelector source:
7
- * `cachedModelRegistry.getAvailable()`), roles-independent.
5
+ * - `list_models` — Never writes config. Resyncs the IN-PROCESS session
6
+ * registry from global config (providers.json re-apply +
7
+ * local refresh), then reads the ModelSelector source
8
+ * (`cachedModelRegistry.getAvailable()`), roles-independent.
9
+ * See change: list-models-auto-resync.
8
10
  * - `list_roles` — READ. `{ roles(bound-only), presets, activePreset }`.
9
11
  * - `update_roles` — WRITE, action-dispatched, `ask_user`-confirmed. Mutates
10
12
  * the global `~/.pi/agent/providers.json` role slice.
@@ -23,6 +25,7 @@
23
25
  */
24
26
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
25
27
  import { Type } from "typebox";
28
+ import { resyncForListModels, toRefreshErrors } from "./model-refresh.js";
26
29
  import { getCustomProviderNames } from "./provider-register.js";
27
30
  import {
28
31
  addRoleName,
@@ -42,6 +45,12 @@ export interface RoleModelToolsDeps {
42
45
  * See change: update-pi-core-0-83-adopt-apis.
43
46
  */
44
47
  getScopedModels?: () => unknown;
48
+ /**
49
+ * Re-diff `~/.pi/agent/providers.json` into the session (bridge wires
50
+ * `reloadProviders(pi)`). Absent → `list_models` runs only the local refresh.
51
+ * See change: list-models-auto-resync (design D2).
52
+ */
53
+ reloadProviders?: () => Promise<unknown>;
45
54
  }
46
55
 
47
56
  // ── list_models row shape ───────────────────────────────────────────────────
@@ -125,6 +134,12 @@ export interface ModelsResult {
125
134
  registryReady: boolean;
126
135
  /** Present only when registryReady === false. */
127
136
  reason?: string;
137
+ /**
138
+ * Per-provider errors of the pre-read refresh. Omitted (never `[]`) on
139
+ * success or abort, mirroring `models_list.refreshErrors`.
140
+ * See change: list-models-auto-resync (design D4).
141
+ */
142
+ refreshErrors?: { provider: string; message: string }[];
128
143
  }
129
144
 
130
145
  /**
@@ -159,7 +174,7 @@ export function registerRoleModelTools(pi: ExtensionAPI, deps: RoleModelToolsDep
159
174
  name: "list_models",
160
175
  label: "List Models",
161
176
  description:
162
- "List the assignable model catalogue from this session's registry — the exact set the human Model Selector shows (including custom providers). Each row carries a `ref` (\"provider/id\") assignable via update_roles. Pass `annotated: true` to also include models excluded for lack of credentials (each with an `excludedReason`). Independent of roles — works even when no roles are configured. The result also carries `registryReady`: when `false` the in-process registry is not yet hydrated (empty `models` + a `reason`) — retry shortly, do NOT conclude no models exist. When `registryReady` is `true` and `models` is unexpectedly empty, try `annotated: true` to reveal `no-credential`/`oauth-incompatible` exclusions.",
177
+ "List the assignable model catalogue from this session's registry (including custom providers). Before reading, it automatically resyncs the registry from global config (~/.pi/agent/providers.json, models.json, stored credentials) so out-of-band changes are seen; it never writes config. This matches the human Model Selector except that the Selector also applies settings `enabledModels`. Each row carries a `ref` (\"provider/id\") assignable via update_roles. Pass `annotated: true` to also include models excluded for lack of credentials (each with an `excludedReason`). Independent of roles — works even when no roles are configured. The result also carries `registryReady`: when `false` the in-process registry is not yet hydrated (empty `models` + a `reason`) — retry shortly, do NOT conclude no models exist. When `registryReady` is `true` and `models` is unexpectedly empty, try `annotated: true` to reveal `no-credential`/`oauth-incompatible` exclusions. An optional `refreshErrors` ([{provider, message}]) names providers whose catalogue refresh failed; their models may be stale or missing.",
163
178
  parameters: Type.Object({
164
179
  annotated: Type.Optional(
165
180
  Type.Boolean({
@@ -168,9 +183,35 @@ export function registerRoleModelTools(pi: ExtensionAPI, deps: RoleModelToolsDep
168
183
  }),
169
184
  ),
170
185
  }),
171
- async execute(_id: any, params: any, _signal: any, _onUpdate: any, _ctx: any) {
186
+ async execute(_id: any, params: any, signal: any, _onUpdate: any, _ctx: any) {
172
187
  const annotated = params?.annotated === true;
173
- const result = buildModelsResult(deps.getRegistry(), annotated, deps.getScopedModels?.());
188
+ const reg = deps.getRegistry();
189
+ let result: ModelsResult;
190
+ if (!reg) {
191
+ result = buildModelsResult(reg, annotated, deps.getScopedModels?.());
192
+ } else {
193
+ // Resync before read (design D3). The resync never passes the agent
194
+ // signal into refresh, and its internal signal race only covers the
195
+ // providers re-apply — so race the signal here too, or an abort would
196
+ // still wait out the refresh bound.
197
+ const sig: AbortSignal | undefined = signal instanceof AbortSignal ? signal : undefined;
198
+ let onAbort: (() => void) | undefined;
199
+ const refreshResult = await Promise.race([
200
+ resyncForListModels(reg, { reloadProviders: deps.reloadProviders, signal: sig }),
201
+ new Promise<undefined>((resolve) => {
202
+ if (!sig) return;
203
+ onAbort = () => resolve(undefined);
204
+ if (sig.aborted) resolve(undefined);
205
+ else sig.addEventListener("abort", onAbort, { once: true });
206
+ }),
207
+ ]);
208
+ if (onAbort) sig?.removeEventListener("abort", onAbort);
209
+ // Re-read after the await; fall back to the start-of-call instance if
210
+ // it was cleared so the answer stays registryReady:true.
211
+ result = buildModelsResult(deps.getRegistry() ?? reg, annotated, deps.getScopedModels?.());
212
+ const refreshErrors = toRefreshErrors(refreshResult);
213
+ if (refreshErrors.length > 0) result.refreshErrors = refreshErrors;
214
+ }
174
215
  return {
175
216
  content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
176
217
  details: result,
@@ -424,7 +424,7 @@ async function spawnAndAttach(
424
424
  deps.onServerSpawned?.(result.childPid);
425
425
  }
426
426
  deps.onLaunchEnd?.(true);
427
- deps.notify(`🌐 Dashboard started at http://localhost:${config.port}`, "info");
427
+ deps.notify(`🌐 Dashboard started at http://localhost:${config.port} — a plain browser tab needs one-time local authorization: run \`pi-dashboard open\``, "info");
428
428
 
429
429
  // D-post: the server we just launched owns the attach decision. Probe the
430
430
  // resolved port with the SAME bootstrap-aware opts as the pre-launch gate;