@blackbelt-technology/pi-dashboard-extension 0.8.0 → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.pi/skills/browser/SKILL.md +69 -28
- package/.pi/skills/browser/UPSTREAM.md +6 -3
- package/.pi/skills/browser/references/challenge.md +183 -0
- package/.pi/skills/browser/references/dashboard-relay.md +150 -0
- package/.pi/skills/browser/references/own-browser.md +7 -1
- package/.pi/skills/doctor/SKILL.md +1 -0
- package/.pi/skills/doctor/_lib/checks.ts +133 -0
- package/.pi/skills/doctor/_lib/derive-tokens.ts +4 -0
- package/.pi/skills/doctor/modules/apple-tools.md +2 -1
- package/.pi/skills/doctor/modules/mcp-builtin.knowledge.hash +1 -0
- package/.pi/skills/doctor/modules/mcp-builtin.md +61 -0
- package/.pi/skills/doctor/modules/pi-resolution.knowledge.hash +1 -1
- package/.pi/skills/doctor/modules/plugins-bridges.md +14 -1
- package/.pi/skills/pi-dashboard/SKILL.md +10 -3
- package/.pi/skills/pi-dashboard/scripts/dashboard-bus.ts +4 -4
- package/.pi/skills/project-init/SKILL.md +40 -27
- package/.pi/skills/project-init/profiles/coding/AGENTS.md.tmpl +0 -23
- package/package.json +19 -16
- package/src/ask-user-tool.ts +4 -0
- package/src/bridge-activation.ts +26 -0
- package/src/bridge-context.ts +21 -19
- package/src/bridge-default-model-gate.ts +38 -0
- package/src/bridge-polling.ts +148 -0
- package/src/bridge.ts +954 -248
- package/src/canvas-tool.ts +5 -0
- package/src/command-handler.ts +77 -31
- package/src/connection.ts +481 -16
- package/src/custom-entry-forward.ts +92 -0
- package/src/endpoint-resolution.ts +32 -0
- package/src/event-forwarder.ts +42 -0
- package/src/extension-identity.ts +59 -0
- package/src/git-dir-watcher.ts +79 -0
- package/src/git-poll.ts +45 -12
- package/src/git-probe-scheduler.ts +119 -0
- package/src/git-tracker.ts +284 -0
- package/src/instance-verification.ts +31 -0
- package/src/mcp-token-delivery.ts +147 -0
- package/src/message-update-coalescer.ts +340 -0
- package/src/model-tracker.ts +118 -35
- package/src/notify-proxy.ts +3 -0
- package/src/path-gate/decide.ts +149 -0
- package/src/path-gate/grant-cache.ts +71 -0
- package/src/path-gate/grant-link.ts +108 -0
- package/src/path-gate/handler.ts +307 -0
- package/src/path-gate/index.ts +155 -0
- package/src/path-gate/resolve.ts +126 -0
- package/src/path-gate/roots.ts +137 -0
- package/src/path-gate/suppression.ts +27 -0
- package/src/pending-prompt-emitter.ts +59 -0
- package/src/pi-env.d.ts +2 -10
- package/src/plugin-request-client.ts +114 -0
- package/src/poll-cost.ts +40 -0
- package/src/pr-status.ts +338 -0
- package/src/process-metrics.ts +77 -1
- package/src/process-scan-scheduler.ts +137 -0
- package/src/process-scanner.ts +226 -247
- package/src/project-init/dox-kb-config.ts +3 -0
- package/src/project-init/scaffold.ts +1 -4
- package/src/project-init/seed-doctrine.ts +23 -60
- package/src/prompt-bus.ts +13 -0
- package/src/provider-register.ts +6 -0
- package/src/retry-tracker.ts +0 -7
- package/src/role-manager.ts +22 -95
- package/src/role-model-tools.ts +6 -0
- package/src/server-auto-start.ts +192 -23
- package/src/server-launcher.ts +70 -34
- package/src/session-move.ts +4 -4
- package/src/session-sync.ts +51 -15
- package/src/slash-dispatch.ts +66 -81
- package/src/subagent-fanout-admission.ts +234 -0
- package/src/subagent-saturation.ts +196 -0
- package/src/terminal-reload.ts +298 -0
- package/src/tui-prompt-adapter.ts +13 -1
- package/src/usage-drain.ts +167 -0
- package/src/vcs-info.ts +261 -63
- package/.pi/skills/project-init/dox-doctrine.md +0 -146
- package/src/agent-settled.ts +0 -90
- package/src/transcript-request-guard.ts +0 -76
|
@@ -0,0 +1,284 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Per-bridge git state tracker (change: optimize-polling-hot-paths, D4–D6).
|
|
3
|
+
*
|
|
4
|
+
* Owns: the per-cwd static-facts cache, the HEAD-file branch reader, the cached
|
|
5
|
+
* `git status`, the two-lane probe scheduler and the git-dir watcher. The ONE
|
|
6
|
+
* place that decides when git is spawned; everything it spawns is async.
|
|
7
|
+
*
|
|
8
|
+
* Send discipline: a `git_info_update` for branch/status is only ever sent from
|
|
9
|
+
* the probe-result path (one coherent branch + facts + status), the PR-change
|
|
10
|
+
* path (cached state) and the synchronous FIRST evaluation (registration /
|
|
11
|
+
* session or cwd change — branch + worktree, status omitted). The 30 s tick,
|
|
12
|
+
* tool ends and watcher events only REQUEST a probe.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import * as git from "@blackbelt-technology/pi-dashboard-shared/platform/git.js";
|
|
16
|
+
import type { Result } from "@blackbelt-technology/pi-dashboard-shared/platform/runner.js";
|
|
17
|
+
import type { GitStatus } from "@blackbelt-technology/pi-dashboard-shared/types.js";
|
|
18
|
+
import type { BridgeContext } from "./bridge-context.js";
|
|
19
|
+
import { createGitDirWatcher, type GitDirWatcher, type WatchFn } from "./git-dir-watcher.js";
|
|
20
|
+
import {
|
|
21
|
+
createGitProbeScheduler,
|
|
22
|
+
type GitProbeScheduler,
|
|
23
|
+
type ProbeLane,
|
|
24
|
+
type ProbeOutcome,
|
|
25
|
+
type ProbeReason,
|
|
26
|
+
} from "./git-probe-scheduler.js";
|
|
27
|
+
import { sendGitInfoIfChanged } from "./model-tracker.js";
|
|
28
|
+
import { incPollCost, pollCost } from "./poll-cost.js";
|
|
29
|
+
import {
|
|
30
|
+
createHeadBranchReader,
|
|
31
|
+
detectBranch,
|
|
32
|
+
GitFactsCache,
|
|
33
|
+
gitInfoFrom,
|
|
34
|
+
type HeadBranchReader,
|
|
35
|
+
} from "./vcs-info.js";
|
|
36
|
+
|
|
37
|
+
/** Tools that cannot dirty the working tree (compared case-insensitively). */
|
|
38
|
+
const READ_ONLY_TOOLS = new Set(["read", "grep", "find", "ls", "glob"]);
|
|
39
|
+
/** Re-probe static facts on every Nth tick (~5 min at 30 s). */
|
|
40
|
+
const FACTS_REPROBE_EVERY_N_TICKS = 10;
|
|
41
|
+
|
|
42
|
+
type Timer = ReturnType<typeof setTimeout>;
|
|
43
|
+
|
|
44
|
+
export interface GitTrackerDeps {
|
|
45
|
+
getBc: () => BridgeContext;
|
|
46
|
+
applyBc: (bc: BridgeContext) => void;
|
|
47
|
+
isActive: () => boolean;
|
|
48
|
+
facts?: GitFactsCache;
|
|
49
|
+
statusProbe?: (cwd: string) => Promise<Result<GitStatus>>;
|
|
50
|
+
headReader?: (onResolved: () => void) => HeadBranchReader;
|
|
51
|
+
watch?: WatchFn;
|
|
52
|
+
now?: () => number;
|
|
53
|
+
setTimer?: (fn: () => void, ms: number) => Timer;
|
|
54
|
+
clearTimer?: (t: Timer) => void;
|
|
55
|
+
log?: (line: string) => void;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export interface GitTracker {
|
|
59
|
+
/**
|
|
60
|
+
* Synchronous first evaluation for `cwd` (registration, cwd or session
|
|
61
|
+
* change): caches facts, resolves the branch, attaches the watcher, sends
|
|
62
|
+
* branch + worktree (status omitted) through `bc`, requests a fast probe.
|
|
63
|
+
* Mutates `bc`; the caller applies it.
|
|
64
|
+
*/
|
|
65
|
+
evaluateFirst(bc: BridgeContext, cwd: string): void;
|
|
66
|
+
/** The git part of the 30 s tick: cheap checks + one slow-lane request. */
|
|
67
|
+
tick(bc: BridgeContext, cwd: string): void;
|
|
68
|
+
onToolEnd(toolName: string | undefined): void;
|
|
69
|
+
/** `git_info_refresh`: invalidate facts, fast probe. */
|
|
70
|
+
refresh(): void;
|
|
71
|
+
/** Re-send from cached state (PR tuple changed). No git spawn. */
|
|
72
|
+
sendCached(): void;
|
|
73
|
+
dispose(): void;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export function createGitTracker(deps: GitTrackerDeps): GitTracker {
|
|
77
|
+
const facts = deps.facts ?? new GitFactsCache();
|
|
78
|
+
const statusProbe = deps.statusProbe ?? ((cwd: string) => git.gitStatusV2Async({ cwd }));
|
|
79
|
+
const log = deps.log ?? ((line: string) => console.error(line));
|
|
80
|
+
|
|
81
|
+
let disposed = false;
|
|
82
|
+
let cwd: string | undefined;
|
|
83
|
+
let generation = 0;
|
|
84
|
+
let ticks = 0;
|
|
85
|
+
let branch: string | undefined;
|
|
86
|
+
let status: GitStatus | undefined;
|
|
87
|
+
let reprobing = false;
|
|
88
|
+
let queuedReprobe: { stamp: boolean } | undefined;
|
|
89
|
+
let logged = false;
|
|
90
|
+
|
|
91
|
+
const watcher: GitDirWatcher = createGitDirWatcher({
|
|
92
|
+
onEvent: (lane) => requestProbe(lane, "watch"),
|
|
93
|
+
watch: deps.watch,
|
|
94
|
+
});
|
|
95
|
+
const scheduler: GitProbeScheduler = createGitProbeScheduler({
|
|
96
|
+
probe: runProbe,
|
|
97
|
+
now: deps.now,
|
|
98
|
+
setTimer: deps.setTimer,
|
|
99
|
+
clearTimer: deps.clearTimer,
|
|
100
|
+
});
|
|
101
|
+
const reader: HeadBranchReader = (deps.headReader ?? ((cb) => createHeadBranchReader(cb)))(() =>
|
|
102
|
+
requestProbe("fast", "watch"),
|
|
103
|
+
);
|
|
104
|
+
|
|
105
|
+
function requestProbe(lane: ProbeLane, reason: ProbeReason): void {
|
|
106
|
+
if (disposed || !deps.isActive() || !cwd) return;
|
|
107
|
+
scheduler.request(lane, reason);
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
function attachWatcher(): void {
|
|
111
|
+
const f = cwd ? facts.get(cwd) : undefined;
|
|
112
|
+
const roots = f?.roots;
|
|
113
|
+
const ok = f?.gitDir ? watcher.attach(f.gitDir, roots?.commonDir) : (watcher.detach(), false);
|
|
114
|
+
pollCost.pollGitWatchersAttached = ok ? 1 : 0;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** Build + diff + send from cached state. Returns false when nothing to send. */
|
|
118
|
+
function sendFrom(bc: BridgeContext): void {
|
|
119
|
+
const f = cwd ? facts.get(cwd) : undefined;
|
|
120
|
+
if (!cwd || !branch || !f) return;
|
|
121
|
+
sendGitInfoIfChanged(bc, { info: gitInfoFrom(branch, f), status });
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
function sendCachedAsync(): void {
|
|
125
|
+
if (disposed || !deps.isActive()) return;
|
|
126
|
+
const bc = deps.getBc();
|
|
127
|
+
sendFrom(bc);
|
|
128
|
+
deps.applyBc(bc);
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
function observePr(bc: BridgeContext): void {
|
|
132
|
+
if (cwd && branch) bc.prStatus?.observe({ sessionId: bc.sessionId, cwd, branch });
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
async function runProbe(info: { lane: ProbeLane; reason: ProbeReason }): Promise<ProbeOutcome> {
|
|
136
|
+
if (disposed || !deps.isActive() || !cwd) return;
|
|
137
|
+
const probeCwd = cwd;
|
|
138
|
+
const gen = generation;
|
|
139
|
+
const gitDir = facts.get(probeCwd)?.gitDir;
|
|
140
|
+
const key = { tick: "pollGitProbesTick", tool: "pollGitProbesTool", watch: "pollGitProbesWatch", refresh: "pollGitProbesRefresh" } as const;
|
|
141
|
+
incPollCost(key[info.reason]);
|
|
142
|
+
incPollCost("pollGitSpawns");
|
|
143
|
+
const before = reader.read(probeCwd, gitDir);
|
|
144
|
+
const t0 = Date.now();
|
|
145
|
+
let res: Result<GitStatus>;
|
|
146
|
+
try {
|
|
147
|
+
res = await statusProbe(probeCwd);
|
|
148
|
+
} catch (err) {
|
|
149
|
+
res = { ok: false, error: { kind: "spawn-error", message: String(err) } } as unknown as Result<GitStatus>;
|
|
150
|
+
}
|
|
151
|
+
incPollCost("pollGitMs", Date.now() - t0);
|
|
152
|
+
if (disposed || !deps.isActive() || gen !== generation) return "ok"; // stale cwd/session: discard
|
|
153
|
+
const after = reader.read(probeCwd, facts.get(probeCwd)?.gitDir);
|
|
154
|
+
if (before !== after) return "discard"; // HEAD moved mid-probe → one more probe
|
|
155
|
+
if (after) branch = after;
|
|
156
|
+
status = res.ok ? res.value : undefined;
|
|
157
|
+
const bc = deps.getBc();
|
|
158
|
+
observePr(bc); // also on a failed status probe — PR refresh must not depend on it
|
|
159
|
+
sendFrom(bc);
|
|
160
|
+
deps.applyBc(bc);
|
|
161
|
+
return "ok";
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/**
|
|
165
|
+
* Re-probe the static facts asynchronously. A request that arrives while one
|
|
166
|
+
* is in flight is NOT dropped: it sets `reprobeAgain` and exactly one more
|
|
167
|
+
* probe runs after the first settles (the first may have read stale state).
|
|
168
|
+
* The watcher is re-attached after any probe the `.git` stamp triggered, even
|
|
169
|
+
* when the facts compare equal — a git dir replaced at the same path leaves a
|
|
170
|
+
* dead watch on the old inode.
|
|
171
|
+
*/
|
|
172
|
+
async function reprobeFacts(forCwd: string, stampTriggered = false): Promise<void> {
|
|
173
|
+
if (disposed) return;
|
|
174
|
+
if (reprobing) {
|
|
175
|
+
queuedReprobe = { stamp: (queuedReprobe?.stamp ?? false) || stampTriggered };
|
|
176
|
+
return;
|
|
177
|
+
}
|
|
178
|
+
reprobing = true;
|
|
179
|
+
let next: { cwd: string; stamp: boolean } | undefined = { cwd: forCwd, stamp: stampTriggered };
|
|
180
|
+
try {
|
|
181
|
+
while (next && !disposed) {
|
|
182
|
+
queuedReprobe = undefined;
|
|
183
|
+
const applied = await probeFactsOnce(next.cwd, next.stamp);
|
|
184
|
+
next = followUpReprobe(next.cwd, applied);
|
|
185
|
+
}
|
|
186
|
+
} catch (err) {
|
|
187
|
+
logOnce(err);
|
|
188
|
+
} finally {
|
|
189
|
+
reprobing = false;
|
|
190
|
+
queuedReprobe = undefined;
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
function logOnce(err: unknown): void {
|
|
195
|
+
if (logged) return;
|
|
196
|
+
logged = true;
|
|
197
|
+
log(`[dashboard] git facts re-probe failed: ${String(err)}`);
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/**
|
|
201
|
+
* The follow-up for a request that arrived mid-flight, aimed at the CURRENT
|
|
202
|
+
* cwd (a rejected stale probe may belong to a previous session). Nothing is
|
|
203
|
+
* queued, or a rejected probe with no queued request, ends the loop.
|
|
204
|
+
*/
|
|
205
|
+
function followUpReprobe(probedCwd: string, applied: boolean): { cwd: string; stamp: boolean } | undefined {
|
|
206
|
+
const queued = queuedReprobe;
|
|
207
|
+
if (!queued || (!applied && !cwd)) return undefined;
|
|
208
|
+
return { cwd: cwd ?? probedCwd, stamp: queued.stamp };
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/** One async facts probe; false when a newer evaluation owns the cache (nothing applied). */
|
|
212
|
+
async function probeFactsOnce(forCwd: string, stampTriggered: boolean): Promise<boolean> {
|
|
213
|
+
const gen = generation;
|
|
214
|
+
const { changed, committed } = await facts.reprobe(forCwd, () => !disposed && gen === generation && deps.isActive());
|
|
215
|
+
if (!committed) return false;
|
|
216
|
+
if (changed || stampTriggered) attachWatcher();
|
|
217
|
+
if (changed) requestProbe("fast", "refresh");
|
|
218
|
+
return true;
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
return {
|
|
222
|
+
evaluateFirst(bc, nextCwd) {
|
|
223
|
+
if (disposed) return;
|
|
224
|
+
cwd = nextCwd;
|
|
225
|
+
generation += 1;
|
|
226
|
+
ticks = 0;
|
|
227
|
+
status = undefined;
|
|
228
|
+
reader.reset();
|
|
229
|
+
bc.lastGitBranch = undefined;
|
|
230
|
+
bc.lastGitPrJson = undefined;
|
|
231
|
+
bc.lastGitWorktreeJson = undefined;
|
|
232
|
+
bc.lastGitStatusJson = undefined;
|
|
233
|
+
const f = facts.evaluate(nextCwd);
|
|
234
|
+
// The file read covers the common case; a detached HEAD pays one
|
|
235
|
+
// synchronous CLI read here (first evaluation only).
|
|
236
|
+
branch = reader.read(nextCwd, f.gitDir) ?? detectBranch(nextCwd);
|
|
237
|
+
attachWatcher();
|
|
238
|
+
if (!branch) return; // not a git repo (a later stamp change can promote it)
|
|
239
|
+
observePr(bc);
|
|
240
|
+
sendFrom(bc);
|
|
241
|
+
requestProbe("fast", "refresh");
|
|
242
|
+
},
|
|
243
|
+
|
|
244
|
+
tick(bc, tickCwd) {
|
|
245
|
+
if (disposed) return;
|
|
246
|
+
if (tickCwd !== cwd) {
|
|
247
|
+
this.evaluateFirst(bc, tickCwd);
|
|
248
|
+
return;
|
|
249
|
+
}
|
|
250
|
+
ticks += 1;
|
|
251
|
+
const stampChanged = facts.stampChanged(tickCwd);
|
|
252
|
+
if (stampChanged || ticks % FACTS_REPROBE_EVERY_N_TICKS === 0) reprobeFacts(tickCwd, stampChanged).catch(logOnce);
|
|
253
|
+
const fresh = reader.read(tickCwd, facts.get(tickCwd)?.gitDir);
|
|
254
|
+
const branchMoved = fresh !== undefined && fresh !== branch;
|
|
255
|
+
// Observe the last SETTLED branch; a moved branch is observed by the
|
|
256
|
+
// probe it triggers, together with its status.
|
|
257
|
+
observePr(bc);
|
|
258
|
+
// A cwd that is not (yet) a repository costs no `git status` per tick;
|
|
259
|
+
// the stamp / 10th-tick re-probe still notices a later `git init`.
|
|
260
|
+
if (!branch && !facts.get(tickCwd)?.gitDir) return;
|
|
261
|
+
requestProbe(branchMoved ? "fast" : "slow", "tick");
|
|
262
|
+
},
|
|
263
|
+
|
|
264
|
+
onToolEnd(toolName) {
|
|
265
|
+
if (toolName && READ_ONLY_TOOLS.has(toolName.toLowerCase())) return;
|
|
266
|
+
requestProbe("slow", "tool");
|
|
267
|
+
},
|
|
268
|
+
|
|
269
|
+
refresh() {
|
|
270
|
+
if (disposed || !cwd) return;
|
|
271
|
+
reprobeFacts(cwd).catch(logOnce);
|
|
272
|
+
requestProbe("fast", "refresh");
|
|
273
|
+
},
|
|
274
|
+
|
|
275
|
+
sendCached: sendCachedAsync,
|
|
276
|
+
|
|
277
|
+
dispose() {
|
|
278
|
+
disposed = true;
|
|
279
|
+
scheduler.dispose();
|
|
280
|
+
watcher.detach();
|
|
281
|
+
pollCost.pollGitWatchersAttached = 0;
|
|
282
|
+
},
|
|
283
|
+
};
|
|
284
|
+
}
|
|
@@ -123,3 +123,34 @@ export async function verifyInstanceIdentity(input: VerifyInput): Promise<Verify
|
|
|
123
123
|
}
|
|
124
124
|
return { ...decideAdoption({ expected: input.expectedInstanceId, observed }), observed };
|
|
125
125
|
}
|
|
126
|
+
|
|
127
|
+
export interface ReachabilityInput {
|
|
128
|
+
healthUrl: string;
|
|
129
|
+
fetchImpl?: typeof fetch;
|
|
130
|
+
timeoutMs?: number;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* Probe whether a candidate endpoint is REACHABLE — `GET /api/health`
|
|
135
|
+
* answering `{ ok: true }` — without caring WHO answers.
|
|
136
|
+
*
|
|
137
|
+
* This is the admission gate's probe (fix-bridge-mdns-migration-hijack D1):
|
|
138
|
+
* it runs BEFORE an established connection is dropped, because the failure
|
|
139
|
+
* window between "dropped" and "found dead" is exactly the outage the gate
|
|
140
|
+
* exists to prevent. Identity (who answered) is {@link verifyInstanceIdentity}'s
|
|
141
|
+
* question; this is only "did anyone answer". Every failure mode —
|
|
142
|
+
* unreachable, non-OK, unparseable, timeout — is `false`.
|
|
143
|
+
*/
|
|
144
|
+
export async function probeEndpointReachability(input: ReachabilityInput): Promise<boolean> {
|
|
145
|
+
const doFetch = input.fetchImpl ?? fetch;
|
|
146
|
+
try {
|
|
147
|
+
const res = await doFetch(input.healthUrl, {
|
|
148
|
+
signal: AbortSignal.timeout(input.timeoutMs ?? 1500),
|
|
149
|
+
});
|
|
150
|
+
if (!res.ok) return false;
|
|
151
|
+
const body = (await res.json()) as { ok?: unknown };
|
|
152
|
+
return body?.ok === true;
|
|
153
|
+
} catch {
|
|
154
|
+
return false;
|
|
155
|
+
}
|
|
156
|
+
}
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Bridge-side registration of the dashboard MCP server
|
|
3
|
+
* (migrate-mcp-to-pi-builtin D1; earlier: wire-mcp-session-token D5/D6).
|
|
4
|
+
*
|
|
5
|
+
* The dashboard mints a per-session bearer every time this session's bridge
|
|
6
|
+
* (re)registers and delivers it — with the `/mcp` URL — over the
|
|
7
|
+
* session-private extension lane (`mcp_token_minted`; never `pi.events`,
|
|
8
|
+
* which is shared with every extension). This module is the ENTIRE in-session
|
|
9
|
+
* surface of that delivery:
|
|
10
|
+
*
|
|
11
|
+
* - Register `pi-dashboard` with pi's built-in MCP via
|
|
12
|
+
* `pi.registerMcpServer(name, { url, headers: { Authorization }, exposure:
|
|
13
|
+
* "deferred" })`. A later registration of the same name replaces the earlier
|
|
14
|
+
* one, so a re-mint simply registers again.
|
|
15
|
+
* - Unregister on `session_shutdown` AND on `session_start` (a replacement
|
|
16
|
+
* session on the same instance never inherits the previous bearer); later
|
|
17
|
+
* deliveries are ignored between shutdown and the next `session_start`.
|
|
18
|
+
* - The credential lives only in this closure and in pi's registration. It is
|
|
19
|
+
* NEVER written to `process.env` (subprocesses must not inherit it), to a
|
|
20
|
+
* file, to a log line, or to `pi.events`.
|
|
21
|
+
* - Guard: a missing/throwing `registerMcpServer`, or a delivery without a URL
|
|
22
|
+
* (older server), logs once with the session id and reports
|
|
23
|
+
* "registration unavailable" once; the session otherwise works.
|
|
24
|
+
*
|
|
25
|
+
* No pi import: the pi surface is injected, which keeps the module testable.
|
|
26
|
+
*
|
|
27
|
+
* See change: migrate-mcp-to-pi-builtin (D1).
|
|
28
|
+
*/
|
|
29
|
+
|
|
30
|
+
/** Name the dashboard's MCP server is registered under in every session. */
|
|
31
|
+
export const DASHBOARD_MCP_SERVER_NAME = "pi-dashboard";
|
|
32
|
+
|
|
33
|
+
export interface McpTokenMintedPayload {
|
|
34
|
+
type: "mcp_token_minted";
|
|
35
|
+
token?: unknown;
|
|
36
|
+
url?: unknown;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** The slice of pi's ExtensionAPI this module uses (both optional: old pi). */
|
|
40
|
+
export interface McpRegistrationApi {
|
|
41
|
+
registerMcpServer?: (name: string, config: { url: string; headers: Record<string, string>; exposure: "deferred" }) => void;
|
|
42
|
+
unregisterMcpServer?: (name: string) => void;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
type McpRegistrationUnavailableReason = "api-missing" | "register-failed" | "no-url";
|
|
46
|
+
|
|
47
|
+
export interface McpDashboardRegistrarDeps {
|
|
48
|
+
pi: McpRegistrationApi;
|
|
49
|
+
/** Live session id (it changes across new/fork/resume). */
|
|
50
|
+
sessionId: () => string;
|
|
51
|
+
/** Tell the server registration is unavailable. Called at most once. */
|
|
52
|
+
reportUnavailable: (reason: McpRegistrationUnavailableReason) => void;
|
|
53
|
+
/** Console-shaped logger. NEVER given the plaintext. */
|
|
54
|
+
log?: Pick<Console, "info" | "warn" | "error">;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export interface McpDashboardRegistrar {
|
|
58
|
+
onMinted(msg: McpTokenMintedPayload): void;
|
|
59
|
+
onSessionShutdown(): void;
|
|
60
|
+
/**
|
|
61
|
+
* Re-arm after a shutdown: on new/fork/resume pi keeps the same extension
|
|
62
|
+
* instance and fires `session_start` for the replacement session, whose own
|
|
63
|
+
* mint then registers again.
|
|
64
|
+
*/
|
|
65
|
+
onSessionStart(): void;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export function createMcpDashboardRegistrar(deps: McpDashboardRegistrarDeps): McpDashboardRegistrar {
|
|
69
|
+
let ended = false;
|
|
70
|
+
let registered = false;
|
|
71
|
+
let reported = false;
|
|
72
|
+
|
|
73
|
+
const unavailable = (reason: McpRegistrationUnavailableReason): void => {
|
|
74
|
+
if (reported) return;
|
|
75
|
+
reported = true;
|
|
76
|
+
deps.log?.warn(
|
|
77
|
+
`[dashboard] MCP registration unavailable for session ${deps.sessionId()} (${reason}); dashboard MCP tools are not reachable from this session`,
|
|
78
|
+
);
|
|
79
|
+
try {
|
|
80
|
+
deps.reportUnavailable(reason);
|
|
81
|
+
} catch {
|
|
82
|
+
/* best-effort report */
|
|
83
|
+
}
|
|
84
|
+
};
|
|
85
|
+
|
|
86
|
+
const unregister = (): void => {
|
|
87
|
+
if (!registered) return;
|
|
88
|
+
registered = false;
|
|
89
|
+
try {
|
|
90
|
+
deps.pi.unregisterMcpServer?.call(deps.pi, DASHBOARD_MCP_SERVER_NAME);
|
|
91
|
+
} catch {
|
|
92
|
+
// A reload releases the old runtime; its registry may already be gone.
|
|
93
|
+
}
|
|
94
|
+
};
|
|
95
|
+
|
|
96
|
+
return {
|
|
97
|
+
onMinted(msg) {
|
|
98
|
+
if (ended) return;
|
|
99
|
+
const token = msg?.token;
|
|
100
|
+
if (typeof token !== "string" || token.length === 0) {
|
|
101
|
+
// Never echo the payload (it may carry the credential).
|
|
102
|
+
deps.log?.warn("[dashboard] received a malformed mcp_token_minted message; ignoring");
|
|
103
|
+
return;
|
|
104
|
+
}
|
|
105
|
+
const url = msg.url;
|
|
106
|
+
if (typeof url !== "string" || url.length === 0) {
|
|
107
|
+
unavailable("no-url");
|
|
108
|
+
return;
|
|
109
|
+
}
|
|
110
|
+
const register = deps.pi.registerMcpServer;
|
|
111
|
+
if (typeof register !== "function") {
|
|
112
|
+
unavailable("api-missing");
|
|
113
|
+
return;
|
|
114
|
+
}
|
|
115
|
+
try {
|
|
116
|
+
register.call(deps.pi, DASHBOARD_MCP_SERVER_NAME, {
|
|
117
|
+
url,
|
|
118
|
+
headers: { Authorization: `Bearer ${token}` },
|
|
119
|
+
exposure: "deferred",
|
|
120
|
+
});
|
|
121
|
+
} catch {
|
|
122
|
+
// No exception text: pi's error may echo the rejected config, and with
|
|
123
|
+
// it the bearer. The fixed reason is the whole record.
|
|
124
|
+
unavailable("register-failed");
|
|
125
|
+
return;
|
|
126
|
+
}
|
|
127
|
+
registered = true;
|
|
128
|
+
deps.log?.info(`[dashboard] registered MCP server "${DASHBOARD_MCP_SERVER_NAME}" for session ${deps.sessionId()}`);
|
|
129
|
+
},
|
|
130
|
+
|
|
131
|
+
onSessionShutdown() {
|
|
132
|
+
if (ended) return;
|
|
133
|
+
ended = true;
|
|
134
|
+
unregister();
|
|
135
|
+
},
|
|
136
|
+
|
|
137
|
+
onSessionStart() {
|
|
138
|
+
// A replacement session must never call /mcp with the previous
|
|
139
|
+
// session's bearer while its own mint is pending (or fails): drop any
|
|
140
|
+
// registration still standing, even without a preceding shutdown.
|
|
141
|
+
unregister();
|
|
142
|
+
ended = false;
|
|
143
|
+
// A replacement session reports its own unavailability.
|
|
144
|
+
reported = false;
|
|
145
|
+
},
|
|
146
|
+
};
|
|
147
|
+
}
|