@blackbelt-technology/pi-dashboard-extension 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 (42) hide show
  1. package/.pi/skills/browser/SKILL.md +2 -2
  2. package/.pi/skills/browser/references/dashboard-relay.md +21 -20
  3. package/.pi/skills/pi-dashboard/SKILL.md +37 -22
  4. package/.pi/skills/pi-dashboard/commands/dashboard-peer-list.md +1 -1
  5. package/.pi/skills/pi-dashboard/commands/dashboard-peer-scan.md +1 -1
  6. package/.pi/skills/pi-dashboard/commands/dashboard-server-config.md +1 -1
  7. package/.pi/skills/pi-dashboard/references/api-reference.agent.md +14 -1
  8. package/.pi/skills/pi-dashboard/references/api-reference.md +100 -2
  9. package/.pi/skills/pi-dashboard/scripts/dashboard-api.sh +39 -1
  10. package/.pi/skills/pi-dashboard/scripts/dashboard-bus.ts +3 -1
  11. package/.pi/skills/pi-dashboard/scripts/local-proof.ts +40 -0
  12. package/.pi/skills/project-access/SKILL.md +190 -0
  13. package/.pi/skills/project-init/SKILL.agent.md +7 -0
  14. package/.pi/skills/project-init/SKILL.md +37 -4
  15. package/package.json +5 -3
  16. package/src/bridge-handlers/dispatch.ts +57 -3
  17. package/src/bridge-handlers/instance.ts +10 -1
  18. package/src/bridge-handlers/lifecycle.ts +65 -26
  19. package/src/bridge-ticket-client.ts +61 -7
  20. package/src/bridge-tls-checks.ts +79 -0
  21. package/src/bridge.ts +41 -28
  22. package/src/canvas-tool.ts +2 -0
  23. package/src/command-handler.ts +80 -6
  24. package/src/connect-target.ts +23 -0
  25. package/src/connection.ts +30 -7
  26. package/src/dashboard-http-origin.ts +88 -0
  27. package/src/dev-build.ts +11 -1
  28. package/src/git-link-builder.ts +11 -2
  29. package/src/inbound-limits.ts +138 -0
  30. package/src/local-token-header.ts +77 -6
  31. package/src/model-refresh.ts +69 -0
  32. package/src/pinned-endpoint.ts +44 -0
  33. package/src/project-trust-live.ts +143 -0
  34. package/src/project-trust.ts +159 -20
  35. package/src/provider-register.ts +59 -18
  36. package/src/remote-registration-gate.ts +21 -21
  37. package/src/remote-upgrade-preparer.ts +104 -0
  38. package/src/role-model-tools.ts +47 -6
  39. package/src/server-auto-start.ts +1 -1
  40. package/src/server-proof-probe.ts +117 -0
  41. package/src/session-sync.ts +42 -12
  42. package/src/vault-delivery.ts +11 -1
@@ -0,0 +1,190 @@
1
+ ---
2
+ name: project-access
3
+ description: 'Map, suggest and request the folder access a project needs: `map` (read-only report), `suggest` (draft `.pi/access.json` from this project''s grants), `provision` (submit it for line-by-line operator approval). Use on "what folders can this project reach", "set up folder access", "write .pi/access.json", repeated folder access prompts, or retrying access setup after project-init.'
4
+ license: MIT
5
+ metadata:
6
+ author: pi-dashboard
7
+ version: "1.0"
8
+ ---
9
+
10
+ # Project Access
11
+
12
+ Work out which folders outside a project its agents need, and ask the dashboard
13
+ operator to approve them once, ahead of time, instead of one prompt per denial.
14
+
15
+ You only ever **propose**. The operator answers per line in the dashboard.
16
+ Nothing in this skill grants access, changes configuration, or answers for the
17
+ operator.
18
+
19
+ ## Setup — server URL
20
+
21
+ Discover the server the way the `pi-dashboard` skill does (config `port`, default 8000):
22
+
23
+ ```bash
24
+ PORT=$(grep -m1 '"port"' ~/.pi/dashboard/config.json 2>/dev/null | grep -o '[0-9]*'); PORT=${PORT:-8000}
25
+ BASE="http://localhost:$PORT"
26
+ curl -s "$BASE/api/health"
27
+ ```
28
+
29
+ (`grep -m1` takes the top-level `port`; the config also nests other `port` keys.)
30
+
31
+ If health does not answer, say the dashboard is not running and stop (every mode
32
+ needs it, except reading `.pi/access.json`). When auth is enabled, pass the JWT
33
+ cookie as the `pi-dashboard` skill describes (`curl -b "pi_dash_token=…"`).
34
+
35
+ **Project root** = `git rev-parse --show-toplevel` from the cwd; when that
36
+ fails, the cwd if it holds a `.pi` directory. A root with neither `.git` nor
37
+ `.pi` is not a project: say so and stop.
38
+
39
+ ## Profile — `.pi/access.json` (format v1)
40
+
41
+ Optional file in the project root. A **proposal only**: the dashboard server
42
+ never reads it, and the file alone grants nothing. Its contents take effect only
43
+ through an approved `provision` request.
44
+
45
+ ```json
46
+ {
47
+ "version": 1,
48
+ "folders": [{ "path": "../shared-lib", "why": "sibling package used by tests" }],
49
+ "remote": ["lan"]
50
+ }
51
+ ```
52
+
53
+ - `folders[].path`: absolute, `~/`-rooted or relative to the project root.
54
+ `why` is optional, plain text, shown to the operator (cut at 200 characters).
55
+ - `remote` (optional): any of `lan`, `internet`, `device`. A goal only points the
56
+ operator at the Remote access dialog; nothing is configured for them.
57
+ - At most 32 folder lines.
58
+ - An unknown `version` (or a missing/non-numeric one): refuse. Say the file is
59
+ not version 1, show the value found, and do not read or send any of it.
60
+
61
+ ## Mode `map`
62
+
63
+ Read-only. It never writes a file, a grant or a configuration value. Report, for
64
+ the project root and each session cwd inside it (`GET $BASE/api/sessions`, rows
65
+ whose `cwd` lies in the root; if unreachable, say "session roots: unknown" and
66
+ use the project root alone):
67
+
68
+ 1. **Covering grants** — `GET $BASE/api/access/grants` → `pathGrants`. A grant
69
+ covers a folder when its `subject` equals it or is an ancestor. For each, say
70
+ how it was created: `via: "provision"` = approved through a provisioning
71
+ request for project `origin`; `via: "prompt"` = allow-always on an access
72
+ dialog; `via: "agent-prompt"` = answered on an agent file-access prompt; no
73
+ `via` = created from the Access page. Include `scope` and `grantedAt`.
74
+ Also list `projectTrust` / `worktreeTrust` / `kbTrust` entries covering it.
75
+ 2. **Profile coverage** — when `.pi/access.json` exists, resolve each folder and
76
+ mark it covered / not covered by the grants above. A missing or non-directory
77
+ path is reported as missing.
78
+ 3. **YOLO** — `GET $BASE/api/access/prompts` → `data.yolo.session`: `null` (off)
79
+ or `{source, expiresAt, unscoped, roots}`. Also `data.prompting` (is the
80
+ operator being asked at all, and `blockers`).
81
+ 4. **pi trust** — `GET $BASE/api/access/pi-trust` → `data.effective` entries
82
+ covering the root (`sourceLabel`), else "not trusted by the dashboard mirror".
83
+ 5. **Path-gate** — `GET $BASE/api/config` → `agentPathGate.enabled` (default on).
84
+ `PI_DASHBOARD_AGENT_PATH_GATE=off|on` in the environment overrides it; report
85
+ that value when set.
86
+ 6. **`bash` is not gated.** Always say so: grants and the path gate cover the
87
+ file tools, not shell commands, which run with the operator's own rights.
88
+
89
+ End with one line naming what could not be read. Every read that fails is
90
+ reported as unknown, never guessed.
91
+
92
+ ## Mode `suggest`
93
+
94
+ Draft `.pi/access.json` from grants this project's sessions created.
95
+
96
+ 1. Read `GET $BASE/api/access/grants` → `pathGrants`. A grant is **this project's**
97
+ when its `origin` equals the project root, or `origin` is a session id whose
98
+ `cwd` (from `GET $BASE/api/sessions`, best effort) lies in the root.
99
+ 2. Count what you could not attribute: grants whose `origin` is `unknown`, and
100
+ grants whose origin is a session id you could not resolve. Record whether the
101
+ sessions API answered.
102
+ 3. Drop grants whose subject lies inside the project root (they need nothing).
103
+ Express the rest relative to the root when under its parent, else absolute.
104
+ `why` = `"granted via <via or Access page> on <date>"`.
105
+ 4. Show the draft. **Before you ask to write**, state the coverage gaps: "N
106
+ grants were skipped (origin unknown)" and, when the sessions API did not
107
+ answer, "the sessions API was unreachable, so this list may be partial". Say
108
+ this even when N is 0 and the API answered ("nothing skipped").
109
+ 5. `ask_user` (confirm) to write `.pi/access.json`. Only on yes, write it. An
110
+ existing file is shown in full and needs its own overwrite confirmation.
111
+ Declined → write nothing.
112
+
113
+ The draft uses `"version": 1`. Never include credential folders (`~/.ssh`,
114
+ `~/.pi`, `~/.aws`, `~/.gnupg`, `~/.kube`, `~/.docker`, `~/Library/Keychains`):
115
+ the dashboard refuses them, so tell the user you left them out.
116
+
117
+ ## Mode `provision`
118
+
119
+ Submit the profile (or lines the user names) as one request, then follow it to
120
+ its end.
121
+
122
+ 1. Build `lines` from `.pi/access.json` (apply the v1 rule above) or from the
123
+ folders the user names. Show them and `ask_user` (confirm) before sending.
124
+ 2. Submit with `POST $BASE/api/access/provision`:
125
+
126
+ ```bash
127
+ curl -s -X POST "$BASE/api/access/provision" -H 'Content-Type: application/json' \
128
+ -d '{"projectRoot":"<root>","lines":[{"path":"../shared-lib","why":"…"}],"remote":["lan"]}'
129
+ ```
130
+
131
+ Success: `{ success: true, data: { requestId, status: "pending", projectRoot,
132
+ lines:[{lineId, path, why, classification}], remote, expiresAt } }`. Tell the
133
+ user the dashboard is asking, and report every line's `classification` and
134
+ real `path`: `grantable` lines wait for the operator; `in-root` / `covered`
135
+ need nothing; `invalid`, `missing`, `forbidden` and `sensitive` can never be
136
+ approved here — say why.
137
+ 3. Refused: `{ success: false, error, reason?, requestId?, retryAfterMs? }`.
138
+ Explain it and stop; never loop or resubmit on your own.
139
+
140
+ | `error` | Tell the user |
141
+ |---|---|
142
+ | `empty` / `too-many-lines` / `invalid-request` | Fix the profile (1–32 folder lines, or a remote goal). |
143
+ | `invalid-root` (`reason`) | The project root is not absolute, missing, not a directory, forbidden (e.g. home), or has no `.git`/`.pi`. |
144
+ | `no-operator` | Nobody can be asked: open the dashboard in a browser (signed in as operator), then retry with this skill. |
145
+ | `prompting-disabled` | Prompting is turned off in Settings ▸ Access. |
146
+ | `report-mode` | Host admission is in report mode, so the dashboard cannot ask. |
147
+ | `disabled` | The grant prompt is switched off (`PI_DASHBOARD_DISABLE_GRANT_PROMPT`). |
148
+ | `pending-exists` | A request for this project is already open (`requestId`): follow that one. |
149
+ | `capacity` | The dashboard has too many open requests; try later. |
150
+ | `rate-limited` | Too many requests; retry after `retryAfterMs`. |
151
+ | `cooldown` | A recent request for this project ended with nothing approved; retry after `retryAfterMs`, and only if the user asks. |
152
+
153
+ 4. Poll until terminal with `GET $BASE/api/access/provision/<requestId>`, every
154
+ ~3 s (bounded: one tool call at most ~60 s, then tell the user you are still
155
+ waiting and continue):
156
+
157
+ ```bash
158
+ curl -s "$BASE/api/access/provision/<requestId>"
159
+ ```
160
+
161
+ Keep going until `data.status` is not `pending` (`settled`, `dismissed` or
162
+ `expired`; a request expires after 10 minutes at `data.expiresAt`). A **404**
163
+ means the server restarted and forgot the request: report
164
+ "unknown — check Settings ▸ Access" and stop; do not resubmit automatically.
165
+ 5. Report **each line's** `outcome` and `reason` to the user:
166
+ `granted` (readable by every session now), `rejected`, `changed` (the folder
167
+ changed after the operator saw it), `refused` (e.g. `capacity`,
168
+ `root-changed`), `failed`, and `handed-off` for a remote goal (the operator
169
+ was pointed to the Remote access dialog; nothing was configured). `dismissed`
170
+ = everything rejected; `expired` = nothing granted.
171
+
172
+ ## Consent, not containment
173
+
174
+ Say this when you report a request, in your own words but without softening it:
175
+
176
+ - Approved folders become readable and writable by **every session on this
177
+ machine** until the operator revokes them on the Access page.
178
+ - Approval is **consent, not containment**: it records what the operator allowed.
179
+ It does not stop a program on this machine (an agent's `bash`, for one) from
180
+ changing access by other means.
181
+ - The project name is the requester's claim; the operator sees the real paths.
182
+
183
+ ## Notes
184
+
185
+ - **Never call** `POST /api/access/provision/<id>/settle` or `/api/access/provision/dismiss-all`. They are operator-only; an agent answering
186
+ its own request defeats the point.
187
+ - **Never write or edit** `~/.pi/dashboard/access-grants.json`, the dashboard
188
+ config, or any pi trust file to obtain access.
189
+ - Requests live in the server's memory only; a restart loses pending ones.
190
+ - Related: `project-init` offers this flow as an opt-in step after scaffolding.
@@ -44,6 +44,7 @@ Triggers: "create project", bare dir, dashboard "Initialize" button spawns sessi
44
44
  - DOX: pointer block in AGENTS.md; `./.pi/dashboard/knowledge_base.json` doctrine flip.
45
45
  - OpenSpec: `openspec init --tools pi --force`; overwrite `./.pi/skills/openspec-*`; may remove legacy files; may touch `~/.config/openspec`.
46
46
  - coding: may `pi install` eng-disciplines user-global (`~/.pi/agent/settings.json`), opt-in.
47
+ - Last: names Step 4c as a separate opt-in question (not a write).
47
48
  - Idempotency: ask before overwriting existing `AGENTS.md` / `.pi/settings.json`.
48
49
 
49
50
  ## Step 4 — Write
@@ -54,6 +55,12 @@ Triggers: "create project", bare dir, dashboard "Initialize" button spawns sessi
54
55
  - PRESENT → skip prompt; remove stale "not detected" footnote.
55
56
  - ABSENT → confirm; yes → `pi install npm:@blackbelt-technology/pi-dashboard-eng-disciplines`; no/fail → append footnote under `## Discipline Skills`: "Discipline skills not detected — run `pi install npm:…` to activate the checkpoints above."
56
57
 
58
+ ## Step 4c — Folder access (separate opt-in; never fails init)
59
+ - After scaffold, all profiles. Own `ask_user` confirm; declined → submit nothing.
60
+ - Lines: `./.pi/access.json` (v1 only; unknown version refused) else user lists folders; none → skip.
61
+ - Submit via `project-access` `provision`; report each line outcome.
62
+ - Refused/expired/dismissed/unreachable → report, init continues. `no-operator` → open dashboard, retry later with `project-access`. Never call settle routes.
63
+
57
64
  ## Step 5 — DOX seed (only if DOX_ENABLED)
58
65
  - Append marker block `<!-- dox-doctrine -->` to AGENTS.md unless marker present. No doctrine copied.
59
66
  - `knowledge_base.json`: set only `doctrine: {inject:"kb", write:true}`. Absent file → full default: `sources` `[{kind:"filesystem",ref:"."}]`, `indexAgentsFiles:true`, `directoryLevelAgents:{enabled:true}`, plus doctrine.
@@ -220,6 +220,12 @@ Step 4b) — NOT a file write:
220
220
  (the install runs `pi install npm:…`); the scaffolded repo itself gains no
221
221
  dependency.
222
222
 
223
+ Then name, last, the separate opt-in question of Step 4c — NOT a file write:
224
+
225
+ - will ask whether to set up this project's folder access: submits a request the
226
+ dashboard operator approves line by line (via the `project-access` skill). Writes
227
+ nothing itself; declining, a refusal or no answer never fails the init.
228
+
223
229
  **Idempotency:** before writing, check whether `./AGENTS.md` or
224
230
  `./.pi/settings.json` already exist. If they do, ask before overwriting — never
225
231
  clobber silently.
@@ -281,6 +287,34 @@ branch, never on the present/installed path (so a successfully-wired project
281
287
  never carries a false "not detected" line). The install is always user-global
282
288
  and never forced.
283
289
 
290
+ ## Step 4c — Offer folder access (separate opt-in; never fails the init)
291
+
292
+ Runs after the scaffold is written (Steps 4/4b), for every profile. It asks the
293
+ operator's dashboard to pre-approve folders outside the project, through the
294
+ `project-access` skill's `provision` mode. Nothing here grants access: the
295
+ operator approves each line in the dashboard.
296
+
297
+ 1. `ask_user` (confirm), as a question separate from the Step 3c confirmation:
298
+
299
+ > Set up this project's folder access now? This asks the dashboard operator to
300
+ > approve folders outside the project, line by line. Nothing is granted until
301
+ > they approve.
302
+
303
+ **Declined** → submit nothing; go to Step 5. The user can run `project-access`
304
+ later.
305
+ 2. **Accepted** → find the lines:
306
+ - `./.pi/access.json` exists → read it per the `project-access` profile rules
307
+ (version 1 only; an unknown `version` is refused — say so and treat it as no
308
+ profile). Offer its lines, showing each path and reason.
309
+ - otherwise → ask the user (`ask_user` input) to list folders to approve, or
310
+ none. No folders and no remote goals → skip.
311
+ 3. Follow `project-access` `provision` (its confirm, request, polling and refusal
312
+ table) and report each line's outcome.
313
+ 4. **Never fail the init.** A refused request, an `expired`/`dismissed` one or an
314
+ unreachable dashboard is reported and the init continues. On `no-operator`,
315
+ tell the user to open the dashboard and retry later with the `project-access`
316
+ skill. Do not retry on your own, and never call the settle routes.
317
+
284
318
  ## Step 5 — DOX pointer seed (only when `DOX_ENABLED` is true)
285
319
 
286
320
  > Gated on the user's Step 3a answer (`DOX_ENABLED`), NOT the raw `profile.json`
@@ -370,9 +404,8 @@ when `ENABLE_SCHEMA` was true in Step 3b and disclosed in the Step 3c preview,
370
404
  request the dashboard's enable flow, `POST /api/openspec/workflow-schema`:
371
405
 
372
406
  ```bash
373
- curl -sS -X POST "http://localhost:${PORT:-8000}/api/openspec/workflow-schema" \
374
- -H 'Content-Type: application/json' \
375
- -d '{"cwd": "<TARGET>", "action": "enable"}'
407
+ pi-dashboard api POST /api/openspec/workflow-schema --port "${PORT:-8000}" \
408
+ --data '{"cwd": "<TARGET>", "action": "enable"}'
376
409
  ```
377
410
 
378
411
  `PORT` is `port` from `~/.pi/dashboard/config.json` (default `8000`). A
@@ -392,7 +425,7 @@ command, no clobber. A re-run after a failed repair lands in `repair` again.
392
425
 
393
426
  ## Step 7 — Done
394
427
 
395
- Confirm what was written. Writing `worktreeInit` flips the directory to
428
+ Confirm what was written, and the outcome of any Step 4c access request. Writing `worktreeInit` flips the directory to
396
429
  "configured": the next dashboard **Initialize** click runs the hook (change-A)
397
430
  instead of re-launching this skill. Tell the user they can click Initialize
398
431
  again to run `npm ci` (or the profile's hook).
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blackbelt-technology/pi-dashboard-extension",
3
- "version": "0.10.0",
3
+ "version": "0.11.0",
4
4
  "description": "Pi bridge extension for pi-dashboard",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -20,6 +20,7 @@
20
20
  ".pi/skills/pi-dashboard",
21
21
  ".pi/skills/browser",
22
22
  ".pi/skills/project-init",
23
+ ".pi/skills/project-access",
23
24
  ".pi/skills/doctor"
24
25
  ],
25
26
  "tools": [
@@ -39,6 +40,7 @@
39
40
  ".pi/skills/pi-dashboard/",
40
41
  ".pi/skills/browser/",
41
42
  ".pi/skills/project-init/",
43
+ ".pi/skills/project-access/",
42
44
  ".pi/skills/doctor/",
43
45
  "agents/",
44
46
  "!**/AGENTS.md",
@@ -48,8 +50,8 @@
48
50
  "!**/*.test.tsx"
49
51
  ],
50
52
  "dependencies": {
51
- "@blackbelt-technology/pi-dashboard-bus-client": "^0.10.0",
52
- "@blackbelt-technology/pi-dashboard-shared": "^0.10.0",
53
+ "@blackbelt-technology/pi-dashboard-bus-client": "^0.11.0",
54
+ "@blackbelt-technology/pi-dashboard-shared": "^0.11.0",
53
55
  "@fission-ai/openspec": "1.14.3",
54
56
  "minimatch": "^10.0.0",
55
57
  "ws": "^8.18.0"
@@ -20,10 +20,62 @@ import { handleUiManagement } from "../ui-modules.js";
20
20
  import type { BridgeInstance } from "./instance.js";
21
21
 
22
22
  /** Handle one inbound server message. Called by the connection's `onMessage` (wrapped in `safe`). */
23
+ /**
24
+ * Name of the turn-starting inbound command carried by `msg`, or `undefined`.
25
+ * Every entry here spends one token of the per-PROCESS prompt bucket;
26
+ * the list is exhaustive for commands that can start a turn or fan out into
27
+ * one (D17). Keep in step with the `Inbound command bounds` spec.
28
+ */
29
+ export function turnStartingCommand(msg: { type?: unknown; action?: unknown }): string | undefined {
30
+ switch (msg.type) {
31
+ case "send_prompt":
32
+ case "retry_session":
33
+ case "git_commit_draft":
34
+ case "plugin_emit_event":
35
+ case "promote_followup_entry":
36
+ return msg.type;
37
+ case "flow_management":
38
+ return msg.action === "run" ? "flow_management" : undefined;
39
+ default:
40
+ return undefined;
41
+ }
42
+ }
43
+
44
+ /** Refuse an over-rate command visibly: route a `command_feedback` error to the sender. */
45
+ function refuseOverRate(inst: BridgeInstance, command: string): void {
46
+ const { promptBurst, promptRefillPerSec } = inst.inboundLimits;
47
+ const message = `${command} refused: inbound command rate limit reached (burst ${promptBurst}, refill ${promptRefillPerSec}/s) — retry shortly`;
48
+ // A refused send_prompt must settle its optimistic bubble first, exactly like
49
+ // the other non-turn refusals in command-handler.
50
+ if (command === "send_prompt") {
51
+ inst.connection.send({ type: "prompt_received", sessionId: inst.sessionId, fresh: false } as never);
52
+ }
53
+ inst.connection.send({
54
+ type: "event_forward",
55
+ sessionId: inst.sessionId,
56
+ event: {
57
+ eventType: "command_feedback",
58
+ timestamp: Date.now(),
59
+ data: { command, status: "error", message },
60
+ },
61
+ } as never);
62
+ }
63
+
23
64
  export async function handleInboundMessage(inst: BridgeInstance, data: unknown): Promise<void> {
24
65
  const pi = inst.pi;
25
66
  if (!inst.isActive()) return; // Stale listener guard
26
67
  const msg = data as ServerToExtensionMessage;
68
+ // Prompt-rate bound (B21): ONE bucket per bridge PROCESS across every
69
+ // turn-starting command, spent before the command does any work. Keyed by the
70
+ // process-global `shared` state, not the `ConnectionManager`: `/reload` builds a
71
+ // new manager, so a connection key would hand the server a fresh allowance by
72
+ // sending `/reload` itself.
73
+ // See change: harden-bridge-inbound-and-discovery (D17).
74
+ const gated = turnStartingCommand(msg as { type?: unknown; action?: unknown });
75
+ if (gated && !inst.inboundLimits.takePrompt(inst.shared)) {
76
+ refuseOverRate(inst, gated);
77
+ return;
78
+ }
27
79
  // D12: the dashboard asking for a slice of THIS session's transcript.
28
80
  // Guarded before any filesystem touch — a request naming a path, or
29
81
  // another session, never reaches the reader. See change:
@@ -80,9 +132,11 @@ export async function handleInboundMessage(inst: BridgeInstance, data: unknown):
80
132
  if ((msg as any).type === "server_restarting") {
81
133
  const reason = (msg as any).reason;
82
134
  const quiesceMs = (msg as any).quiesceMs;
83
- if (typeof quiesceMs === "number" && quiesceMs > 0) {
84
- inst.connection.pauseAutoStart(quiesceMs);
85
- console.log(`[dashboard] server announced restart (reason=${reason} quiesceMs=${quiesceMs})`);
135
+ // `pauseAutoStart` normalizes + bounds (invalid -> 0 = ignored).
136
+ // See change: harden-bridge-inbound-and-discovery (D17).
137
+ const applied = inst.connection.pauseAutoStart(quiesceMs);
138
+ if (applied > 0) {
139
+ console.log(`[dashboard] server announced restart (reason=${reason} quiesceMs=${applied})`);
86
140
  }
87
141
  return;
88
142
  }
@@ -29,6 +29,7 @@ import type { EmptyActionableGuard } from "../empty-actionable-guard.js";
29
29
  import type { resolveEndpoint } from "../endpoint-resolution.js";
30
30
  import type { createFollowupBuffer } from "../followup-buffer.js";
31
31
  import type { GitTracker } from "../git-tracker.js";
32
+ import type { InboundLimits } from "../inbound-limits.js";
32
33
  import type { ReadFileOutcome } from "../markdown-image-inliner.js";
33
34
  import type { createMcpDashboardRegistrar } from "../mcp-token-delivery.js";
34
35
  import type { MessageUpdateCoalescer } from "../message-update-coalescer.js";
@@ -36,7 +37,6 @@ import type { createPathGate } from "../path-gate/index.js";
36
37
  import type { Suppression } from "../path-gate/suppression.js";
37
38
  import type { PluginForwardRegistry } from "../plugin-event-forward-registry.js";
38
39
  import type { createPluginRequestClient } from "../plugin-request-client.js";
39
- import type { VaultDelivery } from "../vault-delivery.js";
40
40
  import type { PrStatusScheduler } from "../pr-status.js";
41
41
  import type { PromptBus } from "../prompt-bus.js";
42
42
  import type { RetryTracker } from "../retry-tracker.js";
@@ -46,6 +46,7 @@ import type { SubagentTickThrottle } from "../subagent-tick-throttle.js";
46
46
  import type { createTransportDiagnostics } from "../transport-diagnostics.js";
47
47
  import type { UiModulesBridgeCtx } from "../ui-modules.js";
48
48
  import type { UsageDrain } from "../usage-drain.js";
49
+ import type { VaultDelivery } from "../vault-delivery.js";
49
50
 
50
51
  export interface BridgeState {
51
52
  cleanup?: () => void;
@@ -61,6 +62,8 @@ export interface BridgeState {
61
62
  pi?: ExtensionAPI;
62
63
  /** All connection instances from any bridge incarnation (for cleanup) */
63
64
  connections?: ConnectionManager[];
65
+ /** Process-wide inbound limiter (see `BridgeInstance.inboundLimits`). */
66
+ inboundLimits?: InboundLimits;
64
67
  /** All interval timers from any bridge incarnation (for cleanup) */
65
68
  timers?: ReturnType<typeof setInterval>[];
66
69
  /**
@@ -189,6 +192,12 @@ export interface BridgeInstance {
189
192
  vaultDelivery: VaultDelivery;
190
193
  connection: ConnectionManager;
191
194
  commandHandler: ReturnType<typeof createCommandHandler>;
195
+ /**
196
+ * Process-wide inbound bounds (bash concurrency + per-connection prompt
197
+ * bucket); the single instance lives in `shared.inboundLimits` so `/reload`
198
+ * keeps the allowance. See change: harden-bridge-inbound-and-discovery (D17).
199
+ */
200
+ inboundLimits: InboundLimits;
192
201
  syncBc: () => BridgeContext;
193
202
  applyBc: (bc: BridgeContext) => void;
194
203
  /** `liveTailOpen`: keep in-flight tail calls open. See change: fix-replay-fabricates-orphan-end-for-live-calls. */
@@ -6,6 +6,7 @@
6
6
  */
7
7
 
8
8
  import { loadConfig, resolveDashboardPorts } from "@blackbelt-technology/pi-dashboard-shared/config.js";
9
+ import { formatHostPort } from "@blackbelt-technology/pi-dashboard-shared/host-port.js";
9
10
  import { discoverDashboard } from "@blackbelt-technology/pi-dashboard-shared/mdns-discovery.js";
10
11
  import { isDashboardRunning } from "@blackbelt-technology/pi-dashboard-shared/server-identity.js";
11
12
  import { Loader } from "@earendil-works/pi-tui";
@@ -22,22 +23,24 @@ import { bridgeExtensionIdentity } from "../extension-identity.js";
22
23
  import { registerFlowEventListeners } from "../flow-event-wiring.js";
23
24
  import { createGitPollState, runGitPollTick } from "../git-poll.js";
24
25
  import { flipHasUI } from "../hasui-flip.js";
25
- import { healthUrlForInstance, probeEndpointReachability, verifyInstanceIdentity } from "../instance-verification.js";
26
+ import { healthUrlForInstance, verifyInstanceIdentity } from "../instance-verification.js";
26
27
  import { sendPiVersionIfChanged as _sendPiVersionIfChanged } from "../model-tracker.js";
27
28
  import { provisionOpenspecCli } from "../openspec-cli-shim.js";
28
29
  import { pollCost } from "../poll-cost.js";
29
30
  import { collectMetrics, startMetricsMonitor, stopMetricsMonitor } from "../process-metrics.js";
30
31
  import { createProcessScanScheduler } from "../process-scan-scheduler.js";
31
32
  import { scanChildProcessesAsync } from "../process-scanner.js";
32
- import { decideBridgeProjectTrust, readEventCwd } from "../project-trust.js";
33
+ import { decideBridgeProjectTrust, type ProjectTrustDeps, readEventCwd } from "../project-trust.js";
34
+ import { createHttpLiveQuery, isRemoteBridge } from "../project-trust-live.js";
33
35
  import { PromptBus } from "../prompt-bus.js";
34
- import { buildProviderCatalogue, toModelInfo } from "../provider-register.js";
36
+ import { buildProviderCatalogue, reloadProviders, toModelInfo } from "../provider-register.js";
35
37
  import { gateRemoteRegistration, isRemoteEndpoint } from "../remote-registration-gate.js";
36
38
  import { registerRoleModelTools } from "../role-model-tools.js";
37
39
  import { autoStartServer } from "../server-auto-start.js";
38
40
  import { launchServer } from "../server-launcher.js";
39
41
  import { loadServerPins, notePinEndpoint, serverPinsPath } from "../server-pin-store.js";
40
- import { handleSessionChange as _handleSessionChange, consumeSpawnToken, filterByEnabledModels, isLive } from "../session-sync.js";
42
+ import { verifyDiscoveredCandidate } from "../server-proof-probe.js";
43
+ import { handleSessionChange as _handleSessionChange, branchFingerprint, consumeSpawnToken, filterByEnabledModels, isLive } from "../session-sync.js";
41
44
  import { detectSessionSource } from "../source-detector.js";
42
45
  import { consumePendingReloadOnSessionStart, releaseBridgeOwnerOnShutdown, reloadCompletedFeedback } from "../terminal-reload.js";
43
46
  import { refreshUiModules, subscribeUiInvalidate } from "../ui-modules.js";
@@ -45,7 +48,6 @@ import { runUiSafely } from "../ui-stale-guard.js";
45
48
  import { sendShutdownUsageThenUnregister, type UsageDrain } from "../usage-drain.js";
46
49
  import { detectIsGitRepo } from "../vcs-info.js";
47
50
  import { buildVisibilityRegisterFields } from "../visibility-intent.js";
48
- import { formatHostPort } from "@blackbelt-technology/pi-dashboard-shared/host-port.js";
49
51
  import type { BridgeInstance } from "./instance.js";
50
52
  import { patchUiForPromptBus } from "./ui-prompt-patch.js";
51
53
 
@@ -182,23 +184,49 @@ export function registerSessionInfoChanged(inst: BridgeInstance): void {
182
184
  } catch { /* older pi: no session_info_changed — poll fallback covers it */ }
183
185
  }
184
186
 
185
- /** `project_trust`: trust-gate decision for the dashboard-spawned project. */
186
- export function registerProjectTrust(inst: BridgeInstance): void {
187
+ /**
188
+ * `project_trust`: trust-gate decision for the dashboard-spawned project.
189
+ *
190
+ * pi awaits this handler, so it may be asynchronous: on a snapshot miss the
191
+ * decision runs a live trust query bounded by `piTrustMirror.liveQueryTimeoutMs`
192
+ * (default 300 ms local / 1000 ms remote). The body has its own try/catch and
193
+ * every path resolves to `{ trusted: "undecided" }` or a per-run yes — it never
194
+ * relies on `safe()` or pi's runner to contain a failure. A bridge replaced while
195
+ * the query was pending (reload) answers undecided. See change: mirror-dashboard-trust-live-remote.
196
+ */
197
+ export function registerProjectTrust(inst: BridgeInstance, overrides: Partial<ProjectTrustDeps> = {}): void {
187
198
  const pi = inst.pi;
188
199
  try {
189
- pi.on("project_trust" as any, inst.safe((event: any, ctx: any) => {
200
+ pi.on("project_trust" as any, inst.safe(async (event: any, ctx: any) => {
190
201
  // Return the pi trust decision. A newer bridge taking over, or any
191
202
  // non-match, defers. `remember:false` = trust for THIS run only.
192
- if (!inst.isActive()) return { trusted: "undecided" };
193
- const decision = decideBridgeProjectTrust({
194
- dashboardSpawned: inst.dashboardSpawned,
195
- isHeadless: isHeadlessRpcSession(),
196
- eventCwd: readEventCwd(event, ctx),
197
- activationCwd: inst.activationCwd,
198
- });
199
- return decision.trusted === "yes"
200
- ? { trusted: "yes", remember: false }
201
- : { trusted: "undecided" };
203
+ try {
204
+ if (!inst.isActive()) return { trusted: "undecided" };
205
+ const decision = await decideBridgeProjectTrust(
206
+ {
207
+ dashboardSpawned: inst.dashboardSpawned,
208
+ isHeadless: isHeadlessRpcSession(),
209
+ eventCwd: readEventCwd(event, ctx),
210
+ activationCwd: inst.activationCwd,
211
+ },
212
+ {
213
+ isRemoteBridge: () => isRemoteBridge(inst.dashboardUrl),
214
+ liveQuery: createHttpLiveQuery({
215
+ endpoint: () => inst.dashboardUrl,
216
+ httpPort: () => inst.rendezvous?.httpPort,
217
+ env: process.env,
218
+ }),
219
+ ...overrides,
220
+ },
221
+ );
222
+ // The instance may have been replaced while the live query was pending.
223
+ if (!inst.isActive()) return { trusted: "undecided" };
224
+ return decision.trusted === "yes"
225
+ ? { trusted: "yes", remember: false }
226
+ : { trusted: "undecided" };
227
+ } catch {
228
+ return { trusted: "undecided" };
229
+ }
202
230
  }));
203
231
  } catch { /* older pi: no project_trust event — no-op */ }
204
232
  }
@@ -320,6 +348,9 @@ export function registerSessionStart(inst: BridgeInstance): void {
320
348
  // Ctrl+P cycling). Absent on older pi / empty when unscoped → no filter.
321
349
  // See change: update-pi-core-0-83-adopt-apis.
322
350
  getScopedModels: () => (inst.cachedCtx as any)?.scopedModels,
351
+ // Resync from global config before each read.
352
+ // See change: list-models-auto-resync (design D2).
353
+ reloadProviders: () => reloadProviders(pi),
323
354
  });
324
355
 
325
356
  // Extract session file/dir early — needed for source detection and UI proxy
@@ -445,6 +476,7 @@ export function registerSessionStart(inst: BridgeInstance): void {
445
476
  const verdict = await gateRemoteRegistration({
446
477
  endpoint: inst.dashboardUrl,
447
478
  store: loadServerPins(pinsFile),
479
+ env: process.env,
448
480
  });
449
481
  // Task 10.3: the cause is distinguishable in the log, not folded into
450
482
  // a generic connection failure.
@@ -533,12 +565,11 @@ export function registerSessionStart(inst: BridgeInstance): void {
533
565
  inst.lastModel = initialModel;
534
566
  inst.lastThinkingLevel = initialThinkingLevel;
535
567
 
536
- // Include eventCount so server can skip event wipe on reconnect
537
- let eventCount: number | undefined;
538
- try {
539
- const entries = ctx.sessionManager?.getBranch?.();
540
- if (entries) eventCount = entries.length;
541
- } catch { /* ignore */ }
568
+ // Include eventCount (+ leaf id, liveTailOpen) so server can skip event wipe
569
+ // on reconnect. `liveTailOpen` is computed ONCE and shared with the replay
570
+ // below. See change: fix-large-session-resume-replay (D7).
571
+ const { eventCount, leafEntryId } = branchFingerprint(ctx.sessionManager);
572
+ const liveTailOpen = isLive(ctx, inst.shared.isAgentStreaming);
542
573
 
543
574
  // See change: fix-dashboard-source-mislabelling — sent on every
544
575
  // register so server can re-stamp source after restart. Derived from the
@@ -563,6 +594,8 @@ export function registerSessionStart(inst: BridgeInstance): void {
563
594
  sessionDir,
564
595
  firstMessage,
565
596
  eventCount,
597
+ ...(leafEntryId !== undefined ? { leafEntryId } : {}),
598
+ liveTailOpen,
566
599
  // The ONLY channel by which the server learns this session's process for a
567
600
  // non-headless spawn: `tmux new-window` returns tmux's own pid, not pi's,
568
601
  // so without this the server's record has no `pid` and shutdown has
@@ -572,6 +605,8 @@ export function registerSessionStart(inst: BridgeInstance): void {
572
605
  // fresh session, did not.
573
606
  // See change: fix-tmux-session-shutdown-leak (D6).
574
607
  pid: process.pid,
608
+ // See change: prove-vault-bridge-tls (D7).
609
+ ...(inst.connection.certValidation ? { certValidation: "enforced" as const } : {}),
575
610
  // The spawn correlation token, echoed back so the server can match THIS
576
611
  // register to the spawn that produced it. This is a fresh session's FIRST
577
612
  // register, and it omitted the token entirely: tier-1 correlation never
@@ -626,7 +661,7 @@ export function registerSessionStart(inst: BridgeInstance): void {
626
661
  // still running across a `/reload` keeps its in-flight calls open instead
627
662
  // of getting a fabricated `session_ended` end. See change:
628
663
  // fix-replay-fabricates-orphan-end-for-live-calls (D3).
629
- inst.replaySessionEntries({ liveTailOpen: isLive(ctx, inst.shared.isAgentStreaming) });
664
+ inst.replaySessionEntries({ liveTailOpen });
630
665
  inst.connection.send({ type: "replay_complete", sessionId: inst.sessionId });
631
666
  // After replay_complete: inside the replay window the server may drop
632
667
  // forwarded events without insert or broadcast (`skipReplayInsert`).
@@ -829,7 +864,11 @@ export function registerSessionStart(inst: BridgeInstance): void {
829
864
  inst.connection
830
865
  .retargetTo(candidateUrl, {
831
866
  trigger,
832
- verify: () => probeEndpointReachability({ healthUrl }),
867
+ // Reachable AND — when this bridge holds the local token — able to
868
+ // return a valid server counter-proof: a healthy answer is not an
869
+ // identity. A refusal keeps the established connection and is logged
870
+ // with its named cause. See change: harden-bridge-inbound-and-discovery (D19).
871
+ verify: () => verifyDiscoveredCandidate({ healthUrl, candidateUrl }),
833
872
  })
834
873
  .then((accepted) => {
835
874
  console.log(`[dashboard] re-target ${inst.dashboardUrl} -> ${candidateUrl}: ${accepted ? "accepted" : "refused by migration gate"}`);