@blackbelt-technology/pi-dashboard-extension 0.9.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 (79) hide show
  1. package/.pi/skills/browser/SKILL.md +14 -9
  2. package/.pi/skills/browser/references/dashboard-relay.md +242 -40
  3. package/.pi/skills/browser/references/own-browser.agent.md +73 -0
  4. package/.pi/skills/pi-dashboard/SKILL.md +37 -22
  5. package/.pi/skills/pi-dashboard/commands/dashboard-peer-list.md +1 -1
  6. package/.pi/skills/pi-dashboard/commands/dashboard-peer-scan.md +1 -1
  7. package/.pi/skills/pi-dashboard/commands/dashboard-server-config.md +1 -1
  8. package/.pi/skills/pi-dashboard/references/api-reference.agent.md +14 -1
  9. package/.pi/skills/pi-dashboard/references/api-reference.md +156 -2
  10. package/.pi/skills/pi-dashboard/scripts/dashboard-api.sh +39 -1
  11. package/.pi/skills/pi-dashboard/scripts/dashboard-bus.ts +3 -1
  12. package/.pi/skills/pi-dashboard/scripts/local-proof.ts +40 -0
  13. package/.pi/skills/project-access/SKILL.md +190 -0
  14. package/.pi/skills/project-init/SKILL.agent.md +77 -0
  15. package/.pi/skills/project-init/SKILL.md +170 -25
  16. package/package.json +10 -8
  17. package/src/ask-user-tool.ts +65 -3
  18. package/src/auto-session-namer.ts +190 -50
  19. package/src/bridge-handlers/dispatch.ts +504 -0
  20. package/src/bridge-handlers/forwarders.ts +616 -0
  21. package/src/bridge-handlers/instance.ts +229 -0
  22. package/src/bridge-handlers/lifecycle.ts +1069 -0
  23. package/src/bridge-handlers/ui-prompt-patch.ts +198 -0
  24. package/src/bridge-identity-log.ts +45 -0
  25. package/src/bridge-ticket-client.ts +61 -7
  26. package/src/bridge-tls-checks.ts +79 -0
  27. package/src/bridge.ts +517 -2534
  28. package/src/canvas-tool.ts +2 -0
  29. package/src/command-handler.ts +259 -16
  30. package/src/connect-target.ts +23 -0
  31. package/src/connection.ts +294 -24
  32. package/src/dashboard-context-injector.ts +26 -47
  33. package/src/dashboard-http-origin.ts +88 -0
  34. package/src/dev-build.ts +11 -1
  35. package/src/empty-actionable-guard.ts +8 -3
  36. package/src/flow-event-wiring.ts +1 -1
  37. package/src/followup-buffer.ts +1 -1
  38. package/src/followup-drain.ts +79 -0
  39. package/src/git-link-builder.ts +11 -2
  40. package/src/inbound-limits.ts +138 -0
  41. package/src/local-token-header.ts +232 -17
  42. package/src/message-update-coalescer.ts +3 -1
  43. package/src/model-refresh.ts +88 -0
  44. package/src/multiselect-list.ts +6 -2
  45. package/src/multiselect-polyfill.ts +2 -2
  46. package/src/openspec-cli-shim.ts +1 -1
  47. package/src/path-gate/decide.ts +15 -41
  48. package/src/path-gate/grant-cache.ts +3 -1
  49. package/src/path-gate/handler.ts +51 -2
  50. package/src/path-gate/index.ts +12 -1
  51. package/src/path-gate/resolve.ts +6 -124
  52. package/src/path-gate/roots.ts +4 -1
  53. package/src/path-gate/suppression.ts +4 -1
  54. package/src/path-gate/yolo-link.ts +104 -0
  55. package/src/pinned-endpoint.ts +44 -0
  56. package/src/plugin-event-forward-registry.ts +200 -0
  57. package/src/project-trust-live.ts +143 -0
  58. package/src/project-trust.ts +258 -25
  59. package/src/prompt-expander.ts +5 -1
  60. package/src/prompt-meta.ts +64 -0
  61. package/src/provider-register.ts +146 -38
  62. package/src/remote-registration-gate.ts +21 -21
  63. package/src/remote-upgrade-preparer.ts +104 -0
  64. package/src/role-manager.ts +5 -4
  65. package/src/role-model-tools.ts +47 -6
  66. package/src/server-auto-start.ts +13 -6
  67. package/src/server-launcher.ts +11 -13
  68. package/src/server-proof-probe.ts +117 -0
  69. package/src/session-move.ts +19 -0
  70. package/src/session-sync.ts +73 -50
  71. package/src/spawn-token.ts +46 -0
  72. package/src/stream-forward-buffer.ts +161 -0
  73. package/src/subagent-frame-buffer.ts +6 -2
  74. package/src/subagent-tick-throttle.ts +3 -1
  75. package/src/vault-delivery.ts +404 -0
  76. package/src/vault-forwarder.ts +128 -0
  77. package/src/vault-masker.ts +165 -0
  78. package/src/vault-redaction.ts +181 -0
  79. package/src/vcs-info.ts +5 -2
@@ -2,5 +2,5 @@
2
2
  executable: bash
3
3
  description: mDNS scan for peer dashboard servers on the network. Runs locally, no LLM.
4
4
  ---
5
- curl -s -X POST "$PI_DASHBOARD_BASE/api/discover-servers" \
5
+ eval "$PI_DASHBOARD_CLI" api POST /api/discover-servers \
6
6
  | jq -r '.data[]? | "\(.host):\(.port) v\(.version // "-") \(if .isLocal then "(local)" else "" end)"'
@@ -2,4 +2,4 @@
2
2
  executable: bash
3
3
  description: Dashboard server config (secrets redacted). Runs locally, no LLM.
4
4
  ---
5
- curl -s "$PI_DASHBOARD_BASE/api/config" | jq .
5
+ eval "$PI_DASHBOARD_CLI" api GET /api/config | jq .
@@ -5,11 +5,17 @@ Pull-only condensed map. Source: packages/extension/.pi/skills/pi-dashboard/refe
5
5
  ## WebSocket bus verbs
6
6
  - Session/flow COMMAND verbs — prefer WS bus over REST; client `@blackbelt-technology/pi-dashboard-bus-client` (`scripts/dashboard-bus.ts`). Verbs = `BrowserToServerMessage` union; `plugin_config_write` excluded → stays REST. `spawn`/`resume` replies exact-correlated; other waits structural (session-id + status).
7
7
 
8
+ ## UI routes (browser)
9
+ - Prefix with `BASE`. Sessions: `/session/:id`, `/session/:id/diff`, `/session/:id/editor`. Folders: `/folder/:encodedCwd`, `.../openspec`, `.../openspec/specs`, `.../openspec/:changeName/:artifactId`, `.../openspec/archive[/:entry[/:artifact]]`.
10
+ - Session id: full id from `GET /api/sessions`; unique prefix >= 8 chars (case-insensitive) converges to the full id; shorter/unknown → inline "Session not found" (no redirect), ambiguous → candidate links. Archived: `/session/<full id>?archived=1` only (no prefix).
11
+ - `?embed=1` → no session list (sticky per tab until `?embed=0`). `uiUrl` / `diffUrl` per session row; base = matching configured origin/tunnel, else admitted `Host`, else `http://localhost:<port>` (https proxy not in `publicBaseUrls` → `http://`).
12
+ - `:encodedCwd` = base64url UTF-8 path, no `=`: `printf %s "$CWD" | base64 | tr '+/' '-_' | tr -d '=\n'`. Other params `encodeURIComponent`. No credentials in UI URLs.
13
+
8
14
  ## Health & Status
9
15
  - `GET /api/health` — liveness `{ ok, pid, uptime }`. `GET /auth/status` — `{ authenticated, authEnabled }`.
10
16
 
11
17
  ## Sessions
12
- - `GET /api/sessions` — list all. Fields: `id, cwd, name?, source (tui|zed|tmux|dashboard|terminal|unknown), status (active|idle|streaming|ended), model?, thinkingLevel?, startedAt, endedAt?, tokensIn?, tokensOut?, cost?, currentTool?, gitBranch?, attachedProposal?, hidden?, activeFlowName?, flowStatus? (running|success|error|aborted), sessionFile?`.
18
+ - `GET /api/sessions` — list all; optional `?id=` (single value; exact or >= 8-char prefix, case-insensitive; repeated → 400). Fields: `uiUrl, diffUrl` (absolute browser links, never stored), `id, cwd, name?, source (tui|zed|tmux|dashboard|terminal|unknown), status (active|idle|streaming|ended), model?, thinkingLevel?, startedAt, endedAt?, tokensIn?, tokensOut?, cost?, currentTool?, gitBranch?, attachedProposal?, hidden?, activeFlowName?, flowStatus? (running|success|error|aborted), sessionFile?`.
13
19
 
14
20
  ## Session Control
15
21
  - `POST /api/session/:id/prompt` — `{ text (required), images? [{ type:"image", data, mimeType }] }`. 400 no text, 404, 502 no bridge.
@@ -45,6 +51,7 @@ Pull-only condensed map. Source: packages/extension/.pi/skills/pi-dashboard/refe
45
51
 
46
52
  ## Events
47
53
  - `GET /api/events/:sessionId/:seq` — `{ eventType, timestamp, data }`.
54
+ - `GET /api/events/stream?session=ID,…&types=T,…` — SSE, never ends. `ready`, then open questions, then live: `session_added`, `status {from?,to}` (changes only), `session_removed`, `question_opened {questionId, questionType, preview, sessionLabel}`, `question_closed {reason: answered|removed}`. `: ping` every 20 s. Unknown type → 400. observe; visibility = session list; not an MCP tool.
48
55
  - `GET /api/session-diff?sessionId=ID` — localhost-only. `{ isGitRepo, files:[{ path, changes:[{ type, timestamp, message }], gitDiff }] }`.
49
56
 
50
57
  ## Configuration
@@ -67,3 +74,9 @@ Pull-only condensed map. Source: packages/extension/.pi/skills/pi-dashboard/refe
67
74
 
68
75
  ## Pinned Directories
69
76
  - `GET /api/pinned-dirs` — `{ success, data: ["/path"] }`.
77
+
78
+ ## Access Provisioning
79
+ - Proposal only: writes no grant/config. In-memory, expires 10 min. Prefer the `project-access` skill.
80
+ - `POST /api/access/provision` — `{ projectRoot, lines:[{path, why?}] (≤32), remote?:["lan"|"internet"|"device"] }` → `data:{ requestId, status, projectRoot, lines:[{lineId, path, why, classification}], remote, expiresAt }`. Classification: `invalid|missing|forbidden|sensitive|in-root|covered|grantable`. Refusals `{success:false, error, reason?, requestId?, retryAfterMs?}`: 400 `empty|too-many-lines|invalid-request|invalid-root`; 409 `pending-exists|no-operator|prompting-disabled|report-mode`; 429 `capacity|rate-limited|cooldown`; 503 `disabled`.
81
+ - `GET /api/access/provision` — `data.requests` (pending). `GET /api/access/provision/:id` — status `pending|settled|dismissed|expired` + per-line `outcome` (`granted|rejected|changed|refused|failed`, remote `handed-off`); 404 after restart.
82
+ - `POST /api/access/provision/:id/settle`, `POST /api/access/provision/dismiss-all` — operator-only (`403 no-capability`); skills never call.
@@ -20,6 +20,41 @@ no-WS-twin endpoints.
20
20
 
21
21
  ---
22
22
 
23
+ ## UI routes (browser)
24
+
25
+ Open these in a browser (an agent's browser pane) to show the dashboard UI. Prefix every route with `BASE` (for example `http://localhost:8000`). Prefer the ready-made `uiUrl` / `diffUrl` from `GET /api/sessions` for sessions.
26
+
27
+ | Route | Shows |
28
+ |-------|-------|
29
+ | `/session/:id` | Session chat |
30
+ | `/session/:id/diff` | Session changed-files diff |
31
+ | `/session/:id/editor` | Session editor pane |
32
+ | `/folder/:encodedCwd` | Folder home |
33
+ | `/folder/:encodedCwd/openspec` | OpenSpec board |
34
+ | `/folder/:encodedCwd/openspec/specs` | OpenSpec specs browser |
35
+ | `/folder/:encodedCwd/openspec/:changeName/:artifactId` | One OpenSpec change artifact |
36
+ | `/folder/:encodedCwd/openspec/archive[/:entry[/:artifact]]` | OpenSpec archive list, one entry, one artifact |
37
+
38
+ **Session ids.** Use the full `id` from `GET /api/sessions`. A prefix of at least 8 characters (case-insensitive) is accepted when it matches exactly one session, and the URL converges to the full id. Session ids are time-ordered UUIDs, so sessions created within about a minute share their first 8 characters: prefer `uiUrl` over a hand-cut prefix. A shorter or unknown id shows "Session not found" (the page is not redirected), and an ambiguous prefix lists the candidates. `GET /api/sessions?id=<id>` returns only the matching rows (same rules).
39
+
40
+ **Archived sessions.** Open `/session/<full id>?archived=1`. The full id is required, a prefix is not resolved for archived sessions. Get ids from `GET /api/sessions/archived`.
41
+
42
+ **Embed.** Append `?embed=1` to show the session without the session list (for a narrow pane). It sticks for that browser tab until `?embed=0`. The "Open full dashboard" control leaves embed mode.
43
+
44
+ **`uiUrl` / `diffUrl`.** Each `GET /api/sessions` row carries absolute links built from the origin you called: a configured public base URL or live tunnel whose host matches, else an admitted `Host` as given, else `http://localhost:<port>`. A reverse proxy that terminates https but is not listed in `publicBaseUrls` therefore yields `http://` links: add its origin to `publicBaseUrls`.
45
+
46
+ **`:encodedCwd`.** base64url of the UTF-8 absolute path, with no `=` padding. In a POSIX shell:
47
+
48
+ ```bash
49
+ printf %s "$CWD" | base64 | tr '+/' '-_' | tr -d '=\n'
50
+ ```
51
+
52
+ `:changeName`, `:artifactId`, `:entry` and `:artifact` are `encodeURIComponent`-encoded.
53
+
54
+ **No credentials in UI URLs.** Never put a token, header value or password in a UI URL. When the page asks to sign in, the user signs in inside the browser.
55
+
56
+ ---
57
+
23
58
  ## Health & Status
24
59
 
25
60
  ### `GET /api/health`
@@ -43,7 +78,7 @@ Check authentication status.
43
78
  ## Sessions
44
79
 
45
80
  ### `GET /api/sessions`
46
- List all sessions.
81
+ List all sessions. Optional `?id=<id>` (single value) returns only the matching session(s): case-insensitive exact id, or a prefix of 8+ characters. A repeated `id` returns 400.
47
82
 
48
83
  **Response:**
49
84
  ```json
@@ -63,7 +98,9 @@ List all sessions.
63
98
  "cost": 0.05,
64
99
  "currentTool": "Edit",
65
100
  "gitBranch": "main",
66
- "hidden": false
101
+ "hidden": false,
102
+ "uiUrl": "http://localhost:8000/session/abc123",
103
+ "diffUrl": "http://localhost:8000/session/abc123/diff"
67
104
  }
68
105
  ]
69
106
  }
@@ -91,6 +128,8 @@ List all sessions.
91
128
  | `activeFlowName` | string? | Running flow name |
92
129
  | `flowStatus` | string? | `running`, `success`, `error`, `aborted` |
93
130
  | `sessionFile` | string? | Path to session JSONL file |
131
+ | `uiUrl` | string | Absolute browser link to the session chat, built from the origin of this request. Append `?embed=1` for a narrow pane. Never stored |
132
+ | `diffUrl` | string | Absolute browser link to the session diff (`uiUrl` + `/diff`) |
94
133
 
95
134
  ---
96
135
 
@@ -391,6 +430,31 @@ Fetch a specific event by sequence number.
391
430
  }
392
431
  ```
393
432
 
433
+ ### `GET /api/events/stream`
434
+ Server-Sent Events feed of agent transitions, for a controller that reacts instead of polling (observe tier).
435
+ Query: `session=<id>[,<id>…]` (full ids) and `types=<type>[,<type>…]`. Unknown type → `400`.
436
+ The response never ends: it starts with a `ready` frame, then every currently open question as `question_opened`, then live events. A `: ping` comment arrives every 20 s.
437
+
438
+ ```
439
+ retry: 3000
440
+ event: ready
441
+ data: {"sessions":["<id>"],"types":["status","question_opened"]}
442
+
443
+ id: 1
444
+ event: question_opened
445
+ data: {"type":"question_opened","sessionId":"<id>","questionId":"<qid>","questionType":"select","preview":"Push to main?","sessionLabel":"<label>"}
446
+ ```
447
+
448
+ | Event | Data |
449
+ |---|---|
450
+ | `session_added` | `sessionId`, `status?`, `cwd?`, `name?` |
451
+ | `status` | `sessionId`, `from?` (absent when the previous status is unknown), `to` (`active`, `idle`, `streaming`, `ended`). Emitted only when the status changes |
452
+ | `session_removed` | `sessionId` |
453
+ | `question_opened` | `sessionId`, `questionId`, `questionType`, `preview`, `sessionLabel`. Detail and answer: `GET /api/questions/:id`, `POST /api/questions/:id/answer` |
454
+ | `question_closed` | `sessionId`, `questionId`, `reason` (`answered`, `removed`) |
455
+
456
+ Visibility follows the session list: an event for a session the caller may not see is not sent. Not exposed as an MCP tool.
457
+
394
458
  ### `GET /api/session-diff?sessionId=ID`
395
459
  Get file changes made during a session (localhost-only).
396
460
 
@@ -498,3 +562,93 @@ List pinned directories.
498
562
  ```json
499
563
  { "success": true, "data": ["/path/to/project1", "/path/to/project2"] }
500
564
  ```
565
+
566
+ ---
567
+
568
+ ## Access Provisioning
569
+
570
+ An agent proposes the folders a project needs; the dashboard operator approves them line by line. A request is a proposal: it writes no grant and no configuration. Requests are in memory only (a server restart forgets them) and expire 10 minutes after creation. Use the `project-access` skill rather than calling these by hand. Replies use the usual envelope: `{ "success": true, "data": … }` or `{ "success": false, "error": "<code>", … }`.
571
+
572
+ ### `POST /api/access/provision`
573
+ Propose a request. Delivered as a dialog only to operator browsers (operate tier holding a prompt capability).
574
+
575
+ **Body:**
576
+ ```json
577
+ { "projectRoot": "/abs/project", "lines": [{ "path": "../shared-lib", "why": "sibling package" }], "remote": ["lan"] }
578
+ ```
579
+ - `projectRoot`: absolute path to a directory holding `.git` or `.pi`; its real path is the per-project key
580
+ - `lines`: 0–32 entries; `path` absolute, `~/`-rooted or relative to the root; `why` optional (cut at 200 characters, control characters removed)
581
+ - `remote` (optional): `lan`, `internet`, `device` — hand-off to the Remote access dialog, nothing is configured
582
+
583
+ **Response `200`:** `{ "success": true, "data": { "requestId", "status": "pending", "projectRoot", "lines": [{ "lineId", "path", "why", "classification", "projectRoot"? }], "remote": [{ "goal" }], "createdAt", "expiresAt" } }`. `classification`: `invalid`, `missing`, `forbidden`, `sensitive`, `in-root`, `covered`, `grantable`.
584
+
585
+ **Refusals** (`error`, plus `reason` / `requestId` / `retryAfterMs` where noted; `retry-after` header on 429):
586
+ - `400`: `empty`, `too-many-lines`, `invalid-request`, `invalid-root` (`reason`: `not-absolute`, `missing`, `not-directory`, `forbidden`, `no-marker`)
587
+ - `409`: `pending-exists` (`requestId` of the open one), `no-operator`, `prompting-disabled`, `report-mode`
588
+ - `429`: `capacity`, `rate-limited`, `cooldown` (each with `retryAfterMs`)
589
+ - `503`: `disabled` (grant prompt kill switch)
590
+
591
+ ### `GET /api/access/provision`
592
+ Pending requests: `{ "success": true, "data": { "requests": [ …request views ] } }`. Observe tier.
593
+
594
+ ### `GET /api/access/provision/:id`
595
+ One request: `status` (`pending`, `settled`, `dismissed`, `expired`) and, once ended, each line's `outcome` (`granted`, `rejected`, `changed`, `refused`, `failed`) with `reason`, and each remote goal's `outcome` (`handed-off`). `404 not-found` for an unknown id or after a server restart.
596
+
597
+ ### `POST /api/access/provision/:id/settle` · `POST /api/access/provision/dismiss-all`
598
+ Operator-only: `403 no-capability` without a live prompt capability. Used by the dashboard UI, never by an agent or skill. `settle` is `409 already-settled` once the request ended.
599
+
600
+ ---
601
+
602
+ ## Open Questions
603
+
604
+ Every open `ask_user` question of every session the caller may see, including hidden, headless, automation and goal-driver sessions. Question ids are opaque URL-safe strings, stable while the question is pending (also across a bridge reconnect). A question the caller may not see is `404`, the same as an unknown id. Reads need the `observe` tier, answers the `control` tier. These routes are not exposed as MCP tools.
605
+
606
+ ### `GET /api/questions`
607
+ List open questions, newest first. Rows carry no context bodies.
608
+
609
+ **Response:**
610
+ ```json
611
+ { "success": true, "data": [
612
+ { "id": "Zk3...", "sessionId": "abc", "sessionLabel": "my session", "changeName": "add-x",
613
+ "preview": "Resume or hand back?", "type": "select", "origin": "chat-gateway",
614
+ "askedAt": 1700000000000, "briefStatus": "ready" } ] }
615
+ ```
616
+ - `origin` (optional): `file` (agent file-access prompt), `chat-gateway`, `widget-bar`
617
+ - `briefStatus`: `provided`, `pending`, `ready`, `failed` or `unavailable`
618
+
619
+ ### `GET /api/questions/:id`
620
+ Full question: options, brief (with `briefLabel`), context snapshot and an `answerable` flag (false for file-access prompts).
621
+
622
+ **Responses:**
623
+ - `200`: `{ "success": true, "data": { ...row, "question": "...", "options": [], "brief": "...", "snapshot": {}, "answerable": true } }`
624
+ - `404`: Unknown, no longer pending, already answered, or not visible to the caller
625
+
626
+ ### `POST /api/questions/:id/answer`
627
+ Answer or cancel an open question. At most one answer is ever transmitted per question, across this route, the dashboard chat and the question dialog.
628
+
629
+ **Body** (exactly one form):
630
+ ```json
631
+ { "answer": "Resume" }
632
+ ```
633
+ ```json
634
+ { "cancelled": true }
635
+ ```
636
+ `answer` uses the encoding the dashboard chat sends: `confirm` → `"true"` / `"false"`; `select` → one of the options; `multiselect` → JSON array of distinct options (`"[]"` allowed, distinct from cancel); `input` / `editor` → any string, empty allowed; `batch` → JSON array with one entry per sub-question. Text only: images cannot be sent on this route.
637
+
638
+ **Responses:**
639
+ - `200`: `{ "success": true, "data": { "transmitted": true } }`. `transmitted` is not a delivery guarantee. `false` means the session's bridge was not reachable: the question stays open and the same answer can be posted again.
640
+ - `400`: Both or neither of `answer` / `cancelled`, or an answer invalid for the prompt type; nothing is transmitted
641
+ - `403`: File-access prompt (answered on the Access page), or the caller's tier is below `control`
642
+ - `404`: Unknown or not visible (also an id answered more than 10 minutes ago, or before a server restart)
643
+ - `409`: `{ "error": "answered" }`: an answer was transmitted within the last 10 minutes
644
+
645
+ ### `POST /api/questions/:id/summarize`
646
+ Generate a brief for a question whose brief is not a generated one (the dialog's "Summarize" action). The result is stored like an automatic brief.
647
+
648
+ **Body:** `{}`
649
+
650
+ **Responses:**
651
+ - `200`: `{ "success": true, "data": { ...question detail with the new brief } }`
652
+ - `404`: Unknown or not visible
653
+ - `409`: Already answered, or the brief is already generated
654
+ - `502` / `503`: Generation failed or timed out / the `@fast` role does not resolve; the current brief is kept and the call may be retried
@@ -1,5 +1,6 @@
1
1
  #!/usr/bin/env bash
2
- # Pi Dashboard API helper — wraps curl with port auto-detection and JSON formatting.
2
+ # Pi Dashboard API helper — wraps curl (or `pi-dashboard api` for a local target, which sends local proof)
3
+ # with port auto-detection and JSON formatting.
3
4
  #
4
5
  # This is the REST layer for READ-ONLY + no-WS-twin operations (session/health/
5
6
  # config reads, git ops, grep/browse, plugin_config_write, tunnel, peer scan,
@@ -40,9 +41,46 @@ else
40
41
  PORT=8000
41
42
  fi
42
43
 
44
+ # The config file can hold several "port" keys (e.g. nested ones): the first match is the server port.
45
+ PORT="${PORT%%$'\n'*}"
46
+
43
47
  HOST="${DASHBOARD_HOST:-localhost}"
44
48
  BASE="http://$HOST:$PORT"
45
49
 
50
+ # ── Local callers: send local proof ────────────────────────────────
51
+ #
52
+ # The strict `requireLocalProof` default refuses a bare-loopback curl on every non-observe route.
53
+ # When the target is THIS host and no JWT is in play, delegate to `pi-dashboard api`, which mints a
54
+ # fresh local proof for the request. A remote HOST (or a JWT) keeps the plain curl path below.
55
+ # See change: close-container-loopback-impersonation (D5).
56
+ case "$HOST" in
57
+ localhost|127.0.0.1|::1|"[::1]")
58
+ if [ -z "${DASHBOARD_TOKEN:-}" ] && command -v pi-dashboard >/dev/null 2>&1; then
59
+ API_ARGS=(api "$METHOD" "$PATH_ARG" --port "$PORT")
60
+ case "$METHOD" in
61
+ POST|PUT|PATCH)
62
+ BODY_OUT="$BODY"
63
+ [ -n "$BODY_OUT" ] || BODY_OUT='{}'
64
+ API_ARGS+=(--data "$BODY_OUT")
65
+ ;;
66
+ esac
67
+ if RESPONSE=$(pi-dashboard "${API_ARGS[@]}" 2>&1); then
68
+ :
69
+ else
70
+ RC=$?
71
+ # A non-2xx answer: show the server's body, then fail like curl -f would not (curl -s prints it and exits 0).
72
+ if [ "$RC" = "2" ]; then
73
+ echo "ERROR: Failed to reach dashboard at $BASE" >&2
74
+ echo "Is the server running? Try: pi-dashboard status" >&2
75
+ exit 1
76
+ fi
77
+ fi
78
+ if command -v jq &>/dev/null; then echo "$RESPONSE" | jq . 2>/dev/null || echo "$RESPONSE"; else echo "$RESPONSE"; fi
79
+ exit 0
80
+ fi
81
+ ;;
82
+ esac
83
+
46
84
  # ── Build curl args ────────────────────────────────────────────────
47
85
 
48
86
  CURL_ARGS=(-s -X "$METHOD")
@@ -30,6 +30,7 @@
30
30
  */
31
31
  import { BusClient } from "@blackbelt-technology/pi-dashboard-bus-client";
32
32
  import type { SessionStatus } from "@blackbelt-technology/pi-dashboard-shared/types.js";
33
+ import { dialHost, proofHeaders } from "./local-proof.ts";
33
34
 
34
35
  function flag(args: string[], name: string): string | undefined {
35
36
  const i = args.indexOf(`--${name}`);
@@ -62,7 +63,8 @@ async function main(): Promise<void> {
62
63
  const [cmd, ...rest] = process.argv.slice(2);
63
64
  if (!cmd) die("usage: dashboard-bus.ts <command> … (see file header)");
64
65
 
65
- const client = new BusClient();
66
+ // Dial the loopback literal and prove locality for the ticket mint (the strict default refuses a bare caller).
67
+ const client = new BusClient({ host: dialHost(), proofHeaders });
66
68
  await client.connect();
67
69
 
68
70
  const resolveId = (prefix: string): string => {
@@ -0,0 +1,40 @@
1
+ /**
2
+ * Local-proof headers for the dashboard skill's scripts.
3
+ *
4
+ * The strict `requireLocalProof` default refuses a bare-loopback caller on every non-observe route
5
+ * (including the `/api/ws-ticket` mint the bus client starts with). A script running on the dashboard's
6
+ * own host proves it by minting an `X-Pi-Local-Proof` from the local token, bound to the exact request.
7
+ * The proof binds an address LITERAL, so scripts dial `127.0.0.1`, never `localhost` (`dialHost`).
8
+ *
9
+ * Node built-ins + the shared proof primitive only. No token (the dashboard never ran here) ⇒ `{}`.
10
+ *
11
+ * See change: close-container-loopback-impersonation (D5).
12
+ */
13
+ import { readFileSync } from "node:fs";
14
+ import { homedir } from "node:os";
15
+ import { join } from "node:path";
16
+ import { httpProofHeaders, localDialHost } from "@blackbelt-technology/pi-dashboard-shared/local-credential-proof.js";
17
+
18
+ function localToken(): string | null {
19
+ try {
20
+ return readFileSync(join(homedir(), ".pi", "dashboard", "local", "token"), "utf8").trim() || null;
21
+ } catch {
22
+ return null;
23
+ }
24
+ }
25
+
26
+ /** The literal to dial for a configured host (`localhost` → `127.0.0.1`). */
27
+ export function dialHost(configured: string | undefined = process.env.DASHBOARD_HOST): string {
28
+ return localDialHost(configured);
29
+ }
30
+
31
+ /** A `BusClient` `proofHeaders` provider. */
32
+ export function proofHeaders(method: string, url: string): Record<string, string> {
33
+ const token = localToken();
34
+ if (!token) return {};
35
+ try {
36
+ return httpProofHeaders(token, url, method);
37
+ } catch {
38
+ return {};
39
+ }
40
+ }
@@ -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.
@@ -0,0 +1,77 @@
1
+ # SKILL.md — project-init index
2
+
3
+ Pull-only condensed map. Source: packages/extension/.pi/skills/project-init/SKILL.md. Scaffold unconfigured dir into configured pi project; interactive, profile-driven, preview before write.
4
+
5
+ Triggers: "create project", bare dir, dashboard "Initialize" button spawns session. Target = cwd. `<skill>` = this skill dir.
6
+
7
+ ## Step 1 — Profiles
8
+ - Sources (user wins by name): `<skill>/profiles/*`, `~/.pi/project-profiles/*`.
9
+ - Usable only if both `AGENTS.md.tmpl` + `settings.json.tmpl` exist.
10
+ - `profile.json`: `description`, `dox` (default false), `stackAware`.
11
+ - Shipped: `coding` (TDD/simplicity/surgical, OpenSpec on, `npm ci`), `docs` (OpenSpec off, no build).
12
+
13
+ ## Step 2 — Select profile
14
+ - `ask_user` select.
15
+
16
+ ## Step 2b — Stack (stackAware only)
17
+ - Placeholders: `{{INSTALL_CMD}}`, `{{TEST_CMD}}`, `{{BUILD_CMD}}`, `{{INIT_GATE}}`, `{{INIT_COMMAND}}`.
18
+ - Marker → stack: `pnpm-lock.yaml`→pnpm, `yarn.lock`→yarn, `bun.lock(b)`→bun, `package-lock.json`/`package.json`→npm, `Cargo.toml`→cargo, `go.mod`→go, `poetry.lock`→poetry, `requirements.txt`/`pyproject.toml`→pip, `pom.xml`→maven, `build.gradle(.kts)`→gradle.
19
+ - JS lockfile beats bare `package.json`. No guess on bare dir.
20
+ - Confirm via `ask_user`. Never scaffold stackAware without resolved stack.
21
+ - Post-write: no `{{…}}` left in `AGENTS.md` or `.pi/settings.json`.
22
+
23
+ ## Step 3 — Optional capabilities + preview
24
+ ### 3a DOX
25
+ - `ask_user` confirm; default = profile `dox`. Answer → `DOX_ENABLED`.
26
+ ### 3b OpenSpec (coding only) → `OPENSPEC_MODE`
27
+ - Config `~/.pi/dashboard/config.json` `openspec`: `enabled`, `offerInitialization` (default true), `optOutDirectories` (default []).
28
+ - Unreadable/invalid JSON or wrong types → fail closed → `skip`.
29
+ - Opt-out match: pathKey = resolve, `/` separators, strip trailing `/`, lowercase unless linux.
30
+ - Git placement fail-closed: linked worktree or subdir of checkout → `skip`.
31
+ - First match wins:
32
+ 1. config undeterminable → `skip`
33
+ 2. `enabled===false` or opt-out match → `skip`
34
+ 3. git placement skip → `skip`
35
+ 4. no `./openspec/` AND `offerInitialization===false` → `skip`
36
+ 5. no `./openspec/` → `offer` (confirm; runs `openspec init --tools pi --force`)
37
+ 6. `./openspec/` present, `.pi/skills/openspec-explore/` absent → `repair` (no question; preview confirm = overwrite confirm)
38
+ 7. both present → `skip`
39
+ - Legacy artifacts (offer/repair only): root `CLAUDE.md`, `AGENTS.md`, etc. only if `<!-- OPENSPEC:START/END -->` present; `.claude/commands/openspec`, `.cursor/commands`, `.codex/prompts`, etc. Disclose by path.
40
+ ### 3c Preview writes
41
+ - `./AGENTS.md` ← `AGENTS.md.tmpl` (`{{PROJECT_NAME}}` = basename)
42
+ - `./.pi/settings.json` ← `settings.json.tmpl`
43
+ - `./.pi/prompts/*.md` ← `prompts/`
44
+ - DOX: pointer block in AGENTS.md; `./.pi/dashboard/knowledge_base.json` doctrine flip.
45
+ - OpenSpec: `openspec init --tools pi --force`; overwrite `./.pi/skills/openspec-*`; may remove legacy files; may touch `~/.config/openspec`.
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).
48
+ - Idempotency: ask before overwriting existing `AGENTS.md` / `.pi/settings.json`.
49
+
50
+ ## Step 4 — Write
51
+ - Validate `worktreeInit`: `gate` non-empty string; `run` = `{type:"script",command}` or `{type:"agent",prompt}` non-empty. Invalid → warn (fails open).
52
+
53
+ ## Step 4b — Discipline skills (coding only)
54
+ - Detect: `pi list | grep pi-dashboard-eng-disciplines` or stat `~/.pi/agent/npm/node_modules/@blackbelt-technology/pi-dashboard-eng-disciplines`.
55
+ - PRESENT → skip prompt; remove stale "not detected" footnote.
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."
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
+
64
+ ## Step 5 — DOX seed (only if DOX_ENABLED)
65
+ - Append marker block `<!-- dox-doctrine -->` to AGENTS.md unless marker present. No doctrine copied.
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.
67
+ - Run `kb dox init`.
68
+ - Offer `dox-describe` (≤50 rows/run, one subagent per AGENTS.md).
69
+
70
+ ## Step 6 — OpenSpec init (repair, or offer confirmed)
71
+ - Run `openspec init --tools pi --force`.
72
+ - Verify exit 0, `.pi/skills/openspec-explore/` exists (+ `./openspec/` for offer).
73
+ - Failure → warn, `ls .pi/skills`, manual cmd. Do not error.
74
+ - Re-run after success → skip.
75
+
76
+ ## Step 7 — Done
77
+ - `worktreeInit` written → Initialize button runs hook instead of this skill.