@blackbelt-technology/pi-dashboard-mcp-client-plugin 0.9.0 → 0.10.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/package.json +5 -3
- package/schema/mcp-config.schema.json +11 -1
- package/src/client/FolderMcpPage.tsx +183 -45
- package/src/client/FolderMcpSection.tsx +2 -1
- package/src/client/McpSettings.tsx +56 -39
- package/src/client/ProjectSettings.tsx +217 -0
- package/src/client/ServerList.tsx +430 -169
- package/src/client/api.ts +52 -2
- package/src/client/folder-view.ts +30 -8
- package/src/client/hooks.ts +38 -4
- package/src/client/index.tsx +0 -2
- package/src/client/settings-ui.ts +19 -0
- package/src/core/config-writer.ts +252 -25
- package/src/core/effective-view.ts +63 -9
- package/src/core/index.ts +12 -0
- package/src/core/path-utils.ts +12 -0
- package/src/core/pi-rules.ts +80 -3
- package/src/core/schema-validation.ts +10 -5
- package/src/core/service.ts +48 -3
- package/src/core/types.ts +86 -8
- package/src/server/index.ts +23 -1
- package/src/server/routes.ts +236 -48
package/src/client/api.ts
CHANGED
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
* Wire shapes mirror the route handlers in `../server/routes.ts`.
|
|
9
9
|
* See change: migrate-mcp-to-pi-builtin.
|
|
10
10
|
*/
|
|
11
|
-
import type { EffectiveView, LiveState, Scope, SetEnabledResult } from "../core/types.js";
|
|
11
|
+
import type { EffectiveView, LiveState, ProjectOverridePatch, Scope, SetEnabledResult } from "../core/types.js";
|
|
12
12
|
|
|
13
13
|
const API_BASE = "/api/mcp-client";
|
|
14
14
|
|
|
@@ -18,22 +18,42 @@ export interface ScopeWire {
|
|
|
18
18
|
cwd?: string;
|
|
19
19
|
}
|
|
20
20
|
|
|
21
|
+
/**
|
|
22
|
+
* Wire form of a scope. Picks fields explicitly so a server-side `admission`
|
|
23
|
+
* token (request-scoped, never on the wire) can never be serialized, even if a
|
|
24
|
+
* caller hands in a scope that carries one. See change: harden-plugin-cwd-admission.
|
|
25
|
+
*/
|
|
21
26
|
export function scopeToWire(scope: Scope): ScopeWire {
|
|
22
27
|
return scope.kind === "global" ? { scope: "global" } : { scope: "project", cwd: scope.cwd };
|
|
23
28
|
}
|
|
24
29
|
|
|
30
|
+
/** The 503 code the server answers when it could not DECIDE cwd admission. */
|
|
31
|
+
const ADMISSION_UNAVAILABLE_CODE = "cwd-admission-unavailable";
|
|
32
|
+
|
|
25
33
|
/** A refusal from any route, carrying the closed `error` code + optional fields. */
|
|
26
34
|
export class ApiError extends Error {
|
|
27
35
|
readonly status: number;
|
|
28
36
|
readonly code: string;
|
|
29
37
|
readonly fields: string[];
|
|
38
|
+
/** Server-suggested base retry delay for a transient refusal (ms). */
|
|
39
|
+
readonly retryAfterMs: number | undefined;
|
|
30
40
|
|
|
31
|
-
constructor(status: number, code: string, message: string, fields?: string[]) {
|
|
41
|
+
constructor(status: number, code: string, message: string, fields?: string[], retryAfterMs?: number) {
|
|
32
42
|
super(message);
|
|
33
43
|
this.name = "ApiError";
|
|
34
44
|
this.status = status;
|
|
35
45
|
this.code = code;
|
|
36
46
|
this.fields = fields ?? [];
|
|
47
|
+
this.retryAfterMs = retryAfterMs;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* The server could not decide cwd admission right now (503
|
|
52
|
+
* `cwd-admission-unavailable`). Transient: retry with backoff, and never read
|
|
53
|
+
* it as "not tracked". A genuine 403 stays {@link isNotAllowed}.
|
|
54
|
+
*/
|
|
55
|
+
get isTransient(): boolean {
|
|
56
|
+
return this.status === 503 && this.code === ADMISSION_UNAVAILABLE_CODE;
|
|
37
57
|
}
|
|
38
58
|
|
|
39
59
|
/** A cwd outside the dashboard's known-folder set (403 `not-allowed`). */
|
|
@@ -46,6 +66,7 @@ interface ErrorBody {
|
|
|
46
66
|
error?: unknown;
|
|
47
67
|
message?: unknown;
|
|
48
68
|
fields?: unknown;
|
|
69
|
+
retryAfterMs?: unknown;
|
|
49
70
|
}
|
|
50
71
|
|
|
51
72
|
async function failure(res: Response): Promise<ApiError> {
|
|
@@ -60,6 +81,7 @@ async function failure(res: Response): Promise<ApiError> {
|
|
|
60
81
|
typeof body.error === "string" ? body.error : `http-${res.status}`,
|
|
61
82
|
typeof body.message === "string" ? body.message : `request failed (${res.status})`,
|
|
62
83
|
Array.isArray(body.fields) ? body.fields.filter((f): f is string => typeof f === "string") : [],
|
|
84
|
+
typeof body.retryAfterMs === "number" && body.retryAfterMs > 0 ? body.retryAfterMs : undefined,
|
|
63
85
|
);
|
|
64
86
|
}
|
|
65
87
|
|
|
@@ -147,3 +169,31 @@ export async function convertServer(name: string, wire: ScopeWire): Promise<void
|
|
|
147
169
|
);
|
|
148
170
|
}
|
|
149
171
|
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* `PUT /servers/:name/project-override` — patch the project override of a global
|
|
175
|
+
* server (project scope only). Absent key = unchanged, `null` = delete the key.
|
|
176
|
+
* Resolves with the written override, or `removed: true` when none is left.
|
|
177
|
+
*/
|
|
178
|
+
export async function setProjectOverride(
|
|
179
|
+
name: string,
|
|
180
|
+
patch: ProjectOverridePatch,
|
|
181
|
+
wire: ScopeWire,
|
|
182
|
+
): Promise<{ ok: true; override?: Record<string, unknown>; removed?: true }> {
|
|
183
|
+
return readJson(
|
|
184
|
+
await fetch(
|
|
185
|
+
`${API_BASE}/servers/${encodeURIComponent(name)}/project-override`,
|
|
186
|
+
methodWith("PUT", { ...wire, ...patch }),
|
|
187
|
+
),
|
|
188
|
+
);
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/** `POST /servers/:name/convert-to-override` — legacy folder copy → override; returns the previous raw entry. */
|
|
192
|
+
export async function convertToOverride(
|
|
193
|
+
name: string,
|
|
194
|
+
wire: ScopeWire,
|
|
195
|
+
): Promise<{ ok: true; previous: Record<string, unknown> }> {
|
|
196
|
+
return readJson(
|
|
197
|
+
await fetch(`${API_BASE}/servers/${encodeURIComponent(name)}/convert-to-override`, methodWith("POST", wire)),
|
|
198
|
+
);
|
|
199
|
+
}
|
|
@@ -1,15 +1,17 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* mcp-client-plugin · folder-scope view helpers.
|
|
3
3
|
*
|
|
4
|
-
* The folder
|
|
5
|
-
*
|
|
6
|
-
* fields (`headers`, `env`,
|
|
7
|
-
*
|
|
8
|
-
* never sent back either).
|
|
4
|
+
* The "Replace with folder entry…" pre-fill: a project entry with a transport
|
|
5
|
+
* replaces a global entry WHOLE, so the editor starts from the complete global
|
|
6
|
+
* entry EXCEPT the secret-bearing fields (`headers`, `env`,
|
|
7
|
+
* `oauth.clientSecret`) and `auth` — those are left out and flagged, never
|
|
8
|
+
* copied silently (the server's redaction markers are never sent back either).
|
|
9
|
+
* Also the project-override presentation helpers (badge text, undo patch).
|
|
9
10
|
*
|
|
10
|
-
* See change: migrate-mcp-to-pi-builtin.
|
|
11
|
+
* See change: migrate-mcp-to-pi-builtin; mcp-client-project-overrides.
|
|
11
12
|
*/
|
|
12
|
-
import
|
|
13
|
+
import { displayExposure, OVERRIDE_KEYS } from "../core/pi-rules.js";
|
|
14
|
+
import type { ProjectOverridePatch, Provenance } from "../core/types.js";
|
|
13
15
|
import { stripRedacted } from "./schema.js";
|
|
14
16
|
|
|
15
17
|
/**
|
|
@@ -45,7 +47,7 @@ function deletePath(draft: Record<string, unknown>, path: string[]): void {
|
|
|
45
47
|
delete parent[path[path.length - 1] as string];
|
|
46
48
|
}
|
|
47
49
|
|
|
48
|
-
/** A copy of a global entry for a folder
|
|
50
|
+
/** A copy of a global entry for a whole-entry folder replace, without secrets or `auth`. */
|
|
49
51
|
export function folderOverrideDraftOf(entry: Record<string, unknown>): FolderOverridePrefill {
|
|
50
52
|
// Flag against the RAW entry (the server's redaction sentinels mark the
|
|
51
53
|
// secret fields), then strip the markers and the flagged paths.
|
|
@@ -65,3 +67,23 @@ export function provenanceLabel(provenance: Provenance): string {
|
|
|
65
67
|
export function isFolderOwned(provenance: Provenance): boolean {
|
|
66
68
|
return provenance === "pi-folder";
|
|
67
69
|
}
|
|
70
|
+
|
|
71
|
+
/** One text badge per overridden key ("Off in this folder", …) — text, never colour alone. */
|
|
72
|
+
export function overrideBadges(raw: Record<string, unknown>): Array<{ key: string; text: string }> {
|
|
73
|
+
const out: Array<{ key: string; text: string }> = [];
|
|
74
|
+
if (typeof raw.enabled === "boolean") {
|
|
75
|
+
out.push({ key: "enabled", text: raw.enabled ? "On in this folder" : "Off in this folder" });
|
|
76
|
+
}
|
|
77
|
+
if (raw.exposure !== undefined) {
|
|
78
|
+
out.push({ key: "exposure", text: `Exposure: ${displayExposure(raw.exposure)} in this folder` });
|
|
79
|
+
}
|
|
80
|
+
if (raw.toolExposure !== undefined) out.push({ key: "toolExposure", text: "Tool exposure set in this folder" });
|
|
81
|
+
return out;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** The patch that restores a removed override exactly: its raw keys, absent keys as `null`. */
|
|
85
|
+
export function overrideRestorePatch(removed: Record<string, unknown>): ProjectOverridePatch {
|
|
86
|
+
const patch: Record<string, unknown> = {};
|
|
87
|
+
for (const k of OVERRIDE_KEYS) patch[k] = removed[k] ?? null;
|
|
88
|
+
return patch as ProjectOverridePatch;
|
|
89
|
+
}
|
package/src/client/hooks.ts
CHANGED
|
@@ -34,6 +34,35 @@ function keyOf(cwd?: string): string {
|
|
|
34
34
|
return cwd ?? "";
|
|
35
35
|
}
|
|
36
36
|
|
|
37
|
+
/** Retries after the first attempt when the server could not decide admission. */
|
|
38
|
+
const TRANSIENT_MAX_RETRIES = 3;
|
|
39
|
+
/** Base delay when the 503 carries no `retryAfterMs`. */
|
|
40
|
+
const TRANSIENT_BASE_MS = 1000;
|
|
41
|
+
|
|
42
|
+
/** Jittered exponential backoff: `base × 2^n × (0.75 + random × 0.5)` (~1 s, 2 s, 4 s ±25 %). */
|
|
43
|
+
function transientDelayMs(err: ApiError, attempt: number): number {
|
|
44
|
+
return (err.retryAfterMs ?? TRANSIENT_BASE_MS) * 2 ** attempt * (0.75 + Math.random() * 0.5);
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* `fetchEffective` with the transient-503 retry chain. ONE chain per key: it
|
|
49
|
+
* lives inside the key's single in-flight promise, so N pills on one cwd make
|
|
50
|
+
* one chain. A transient error is retried while `isCurrent()` (a superseding
|
|
51
|
+
* `invalidate` / forced reload ends the chain); only after exhaustion is it
|
|
52
|
+
* surfaced, and it is NEVER recorded as "not tracked".
|
|
53
|
+
*/
|
|
54
|
+
async function fetchEffectiveWithRetry(cwd: string | undefined, isCurrent: () => boolean): Promise<EffectiveView> {
|
|
55
|
+
for (let attempt = 0; ; attempt++) {
|
|
56
|
+
try {
|
|
57
|
+
return await fetchEffective(cwd);
|
|
58
|
+
} catch (err) {
|
|
59
|
+
if (!(err instanceof ApiError && err.isTransient) || attempt >= TRANSIENT_MAX_RETRIES || !isCurrent()) throw err;
|
|
60
|
+
await new Promise<void>((resolve) => setTimeout(resolve, transientDelayMs(err, attempt)));
|
|
61
|
+
if (!isCurrent()) throw err;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
37
66
|
/** Test-only: drop every cached 403 so each test starts from a clean slate. */
|
|
38
67
|
export function __resetNotTrackedCache(): void {
|
|
39
68
|
notTracked.clear();
|
|
@@ -56,7 +85,7 @@ export function loadEffective(
|
|
|
56
85
|
const hit = cache.get(key);
|
|
57
86
|
if (hit) return Promise.resolve(hit);
|
|
58
87
|
}
|
|
59
|
-
const request =
|
|
88
|
+
const request: Promise<EffectiveView> = fetchEffectiveWithRetry(cwd, () => inflight.get(key) === request).then(
|
|
60
89
|
(view) => {
|
|
61
90
|
// A superseded request (invalidated, or replaced by a forced reload) must
|
|
62
91
|
// not repopulate the cache with a now-stale body.
|
|
@@ -68,9 +97,14 @@ export function loadEffective(
|
|
|
68
97
|
return view;
|
|
69
98
|
},
|
|
70
99
|
(err: unknown) => {
|
|
71
|
-
|
|
72
|
-
//
|
|
73
|
-
|
|
100
|
+
// A SUPERSEDED request (invalidated by a pin-list change, or replaced by a forced
|
|
101
|
+
// reload) must not write state either way: its late 403 would otherwise shadow the
|
|
102
|
+
// newer request's success, because `notTracked` is consulted before the view cache.
|
|
103
|
+
if (inflight.get(key) === request) {
|
|
104
|
+
inflight.delete(key);
|
|
105
|
+
// Remember a cwd refusal so a remount / sibling pill does not re-ask.
|
|
106
|
+
if (err instanceof ApiError && err.isNotAllowed) notTracked.set(key, err);
|
|
107
|
+
}
|
|
74
108
|
throw err;
|
|
75
109
|
},
|
|
76
110
|
);
|
package/src/client/index.tsx
CHANGED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* mcp-client · settings-body class recipes (token-only, ≥ 12 px).
|
|
3
|
+
*
|
|
4
|
+
* Buttons / link follow the `ui-contract.md` recipes; status pills, notices and
|
|
5
|
+
* the item card come from the runtime settings kit. Kept in one place so the
|
|
6
|
+
* list toolbar, rows and empty state share one set of recipes.
|
|
7
|
+
* See change: retro-ux-plugin-settings-wave-2.
|
|
8
|
+
*/
|
|
9
|
+
const BTN_BASE =
|
|
10
|
+
"focus-ring inline-flex items-center justify-center gap-1 rounded-md px-3 min-h-[44px] sm:min-h-[32px] text-xs font-semibold disabled:cursor-not-allowed";
|
|
11
|
+
/** Secondary button. */
|
|
12
|
+
export const BTN =
|
|
13
|
+
`${BTN_BASE} border border-[var(--border-secondary)] bg-[var(--bg-tertiary)] text-[var(--text-primary)] hover:bg-[var(--bg-hover)] disabled:opacity-60`;
|
|
14
|
+
/** Primary button — exactly one per state. */
|
|
15
|
+
export const BTN_PRIMARY =
|
|
16
|
+
`${BTN_BASE} bg-[var(--accent-solid)] text-white hover:brightness-110 disabled:bg-[var(--bg-tertiary)] disabled:text-[var(--text-secondary)]`;
|
|
17
|
+
/** Inline text-button / link recipe (`--link`). */
|
|
18
|
+
export const LINK =
|
|
19
|
+
"focus-ring inline-flex min-h-[32px] items-center gap-1 rounded text-xs font-semibold text-[var(--link)] hover:text-[var(--link-hover)] hover:underline disabled:opacity-60";
|
|
@@ -17,15 +17,31 @@
|
|
|
17
17
|
* See change: migrate-mcp-to-pi-builtin (D3); earlier: extract-mcp-client-plugin.
|
|
18
18
|
*/
|
|
19
19
|
|
|
20
|
-
import { isAllowedCwd } from "@blackbelt-technology/pi-dashboard-shared/cwd-guard.js";
|
|
20
|
+
import { isAllowedCwd, tokenAllows } from "@blackbelt-technology/pi-dashboard-shared/cwd-guard.js";
|
|
21
21
|
import { type LayerPaths, type LayerRead, nullProto, readLayer } from "./layers.js";
|
|
22
|
-
import { isPlainObject } from "./path-utils.js";
|
|
23
|
-
import {
|
|
22
|
+
import { deepEqual, isPlainObject } from "./path-utils.js";
|
|
23
|
+
import {
|
|
24
|
+
ADAPTER_ONLY_KEYS,
|
|
25
|
+
classifyProjectEntry,
|
|
26
|
+
displayExposure,
|
|
27
|
+
isFullEntry,
|
|
28
|
+
isProjectOverride,
|
|
29
|
+
isValidServerName,
|
|
30
|
+
keptGlobalOf,
|
|
31
|
+
mcpNamespace,
|
|
32
|
+
OVERRIDE_KEYS,
|
|
33
|
+
transportOf,
|
|
34
|
+
validatePiEntry,
|
|
35
|
+
} from "./pi-rules.js";
|
|
36
|
+
import { errorFields, validateServerEntry } from "./schema-validation.js";
|
|
24
37
|
import type {
|
|
25
38
|
ConfigIO,
|
|
26
39
|
ConfigRefusal,
|
|
27
40
|
ConfigWriteResult,
|
|
41
|
+
ConvertLegacyResult,
|
|
28
42
|
ParseStatus,
|
|
43
|
+
ProjectOverridePatch,
|
|
44
|
+
ProjectOverrideResult,
|
|
29
45
|
RemoveResult,
|
|
30
46
|
Scope,
|
|
31
47
|
ServerEntry,
|
|
@@ -34,8 +50,11 @@ import type {
|
|
|
34
50
|
|
|
35
51
|
/** Thrown when a project scope names a cwd outside the known-folder set. */
|
|
36
52
|
export class NotAllowedCwdError extends Error {
|
|
37
|
-
|
|
53
|
+
public readonly cwd: string;
|
|
54
|
+
|
|
55
|
+
constructor(cwd: string) {
|
|
38
56
|
super(`cwd not allowed: ${cwd}`);
|
|
57
|
+
this.cwd = cwd;
|
|
39
58
|
this.name = "NotAllowedCwdError";
|
|
40
59
|
}
|
|
41
60
|
}
|
|
@@ -63,6 +82,8 @@ export interface ConfigWriter {
|
|
|
63
82
|
): ConfigWriteResult;
|
|
64
83
|
removeServer(name: string, scope: Scope): RemoveResult;
|
|
65
84
|
setEnabled(name: string, enabled: boolean, scope: Scope): SetEnabledResult;
|
|
85
|
+
setProjectOverride(name: string, patch: ProjectOverridePatch, scope: Scope): ProjectOverrideResult;
|
|
86
|
+
convertLegacyCopy(name: string, scope: Scope): ConvertLegacyResult;
|
|
66
87
|
convertAdapterLeftovers(name: string, scope: Scope): ConfigWriteResult;
|
|
67
88
|
/** Dry run of `ensureServerEntry`: the refusal it would return, or null. */
|
|
68
89
|
previewEnsure(name: string, fields: Partial<ServerEntry>, scope: Scope): ConfigRefusal | null;
|
|
@@ -91,12 +112,96 @@ export function folderCopyOf(entry: Record<string, unknown>): { copy: Record<str
|
|
|
91
112
|
return { copy, omitted };
|
|
92
113
|
}
|
|
93
114
|
|
|
115
|
+
const OVERRIDE_ROUTE_HINT = "use the project-override operation to change a global server for one folder";
|
|
116
|
+
|
|
117
|
+
function omitKeys(entry: Record<string, unknown>, keys: readonly string[]): Record<string, unknown> {
|
|
118
|
+
return Object.fromEntries(Object.entries(entry).filter(([k]) => !keys.includes(k)));
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* A whole-entry folder copy of `globalRaw` made by the old disable path: both
|
|
123
|
+
* are full entries, the folder entry carries none of the secret-bearing fields
|
|
124
|
+
* (a re-entered secret vetoes), and apart from the override keys it equals the
|
|
125
|
+
* global entry without those fields. See change: mcp-client-project-overrides (D7).
|
|
126
|
+
*/
|
|
127
|
+
export function isLegacyFolderCopy(folderRaw: unknown, globalRaw: unknown): boolean {
|
|
128
|
+
if (!isFullEntry(folderRaw) || !isFullEntry(globalRaw)) return false;
|
|
129
|
+
if (folderRaw.headers !== undefined || folderRaw.env !== undefined || folderRaw.auth !== undefined) return false;
|
|
130
|
+
if (isPlainObject(folderRaw.oauth) && folderRaw.oauth.clientSecret !== undefined) return false;
|
|
131
|
+
return deepEqual(omitKeys(folderRaw, OVERRIDE_KEYS), omitKeys(folderCopyOf(globalRaw).copy, OVERRIDE_KEYS));
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/** `existing` override with `patch` applied: absent key = unchanged, `null` = delete the key. */
|
|
135
|
+
function patchedOverride(existing: Record<string, unknown> | undefined, patch: ProjectOverridePatch): Record<string, unknown> {
|
|
136
|
+
const next = nullProto({ ...(existing ?? {}) });
|
|
137
|
+
for (const k of OVERRIDE_KEYS) {
|
|
138
|
+
const v = (patch as Record<string, unknown>)[k];
|
|
139
|
+
if (v === undefined) continue;
|
|
140
|
+
if (v === null) delete next[k];
|
|
141
|
+
else next[k] = v;
|
|
142
|
+
}
|
|
143
|
+
return next;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** A legacy copy rewritten to only the override keys whose value differs from the global entry. */
|
|
147
|
+
function convertedOverride(folder: Record<string, unknown>, base: Record<string, unknown>): Record<string, unknown> {
|
|
148
|
+
const next: Record<string, unknown> = nullProto({});
|
|
149
|
+
// A non-boolean `enabled` is carried forward so the merged validation refuses it, never silently dropped.
|
|
150
|
+
if (folder.enabled !== undefined && folder.enabled !== (base.enabled !== false)) next.enabled = folder.enabled;
|
|
151
|
+
if (folder.exposure !== undefined && displayExposure(folder.exposure) !== displayExposure(base.exposure)) {
|
|
152
|
+
next.exposure = folder.exposure;
|
|
153
|
+
}
|
|
154
|
+
if (folder.toolExposure !== undefined && !deepEqual(folder.toolExposure, base.toolExposure)) {
|
|
155
|
+
next.toolExposure = folder.toolExposure;
|
|
156
|
+
}
|
|
157
|
+
return next;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/** Shape-check a patch BEFORE any IO: only override keys, correctly typed (`null` = delete). */
|
|
161
|
+
function patchShapeRefusal(name: string, patch: unknown): ConfigRefusal | null {
|
|
162
|
+
if (!isPlainObject(patch)) {
|
|
163
|
+
return { code: "invalid-entry", message: `server "${name}": override patch must be an object` };
|
|
164
|
+
}
|
|
165
|
+
const present = Object.fromEntries(Object.entries(patch).filter(([, v]) => v !== null && v !== undefined));
|
|
166
|
+
const shape = validateServerEntry(present, { kind: "override" });
|
|
167
|
+
if (shape.ok) return null;
|
|
168
|
+
const f = errorFields(shape.errors);
|
|
169
|
+
return { code: "invalid-entry", message: `server "${name}": invalid project override${f.length ? ` (${f.join(", ")})` : ""}` };
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
function wholeEntryRefusal(name: string, path: string): { ok: false; refusal: ConfigRefusal } {
|
|
173
|
+
return {
|
|
174
|
+
ok: false,
|
|
175
|
+
refusal: {
|
|
176
|
+
code: "invalid-entry",
|
|
177
|
+
message: `server "${name}" is a whole-entry folder entry, not an override (${OVERRIDE_ROUTE_HINT})`,
|
|
178
|
+
path,
|
|
179
|
+
},
|
|
180
|
+
};
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/** The refusal when `next` merged onto its kept global base is not a valid pi override. */
|
|
184
|
+
function mergedOverrideRefusal(
|
|
185
|
+
name: string,
|
|
186
|
+
next: Record<string, unknown>,
|
|
187
|
+
kept: ReadonlyMap<string, Record<string, unknown>>,
|
|
188
|
+
path: string,
|
|
189
|
+
): ConfigRefusal | null {
|
|
190
|
+
const cls = classifyProjectEntry(name, next, kept);
|
|
191
|
+
if (cls.kind === "override") return null;
|
|
192
|
+
return { code: "invalid-entry", message: cls.kind === "replace" ? OVERRIDE_ROUTE_HINT : cls.message, path };
|
|
193
|
+
}
|
|
194
|
+
|
|
94
195
|
export function createConfigWriter(deps: ConfigWriterDeps): ConfigWriter {
|
|
95
196
|
const { configIO, paths, knownCwds } = deps;
|
|
96
197
|
const trusted = (cwd: string): boolean => deps.isProjectTrusted?.(cwd) === true;
|
|
97
198
|
|
|
98
199
|
function targetPath(scope: Scope): string {
|
|
99
200
|
if (scope.kind === "global") return paths.globalPath();
|
|
201
|
+
// A live request-scoped token means the route already admitted this exact cwd
|
|
202
|
+
// (async, once): accept it without a second, synchronous git probe. Any other
|
|
203
|
+
// scope (non-route callers, a released token) is decided by the sync guard.
|
|
204
|
+
if (tokenAllows(scope.admission, scope.cwd)) return paths.projectPath(scope.cwd);
|
|
100
205
|
if (!isAllowedCwd(scope.cwd, knownCwds)) throw new NotAllowedCwdError(scope.cwd);
|
|
101
206
|
return paths.projectPath(scope.cwd);
|
|
102
207
|
}
|
|
@@ -126,18 +231,23 @@ export function createConfigWriter(deps: ConfigWriterDeps): ConfigWriter {
|
|
|
126
231
|
/** Every entry a write could collide with, and the file it lives in. */
|
|
127
232
|
function collisionCandidates(scope: Scope): Array<{ name: string; path: string }> {
|
|
128
233
|
const out: Array<{ name: string; path: string }> = [];
|
|
129
|
-
const add = (path: string): void => {
|
|
234
|
+
const add = (path: string, skipOverrides: boolean): void => {
|
|
130
235
|
const l = readLayer(configIO, path);
|
|
131
|
-
if (l.ok)
|
|
236
|
+
if (!l.ok) return;
|
|
237
|
+
for (const [n, raw] of Object.entries(l.servers)) {
|
|
238
|
+
// pi never clash-checks a project override (it reuses the global entry's name).
|
|
239
|
+
if (skipOverrides && isProjectOverride(raw)) continue;
|
|
240
|
+
out.push({ name: n, path });
|
|
241
|
+
}
|
|
132
242
|
};
|
|
133
|
-
add(paths.globalPath());
|
|
243
|
+
add(paths.globalPath(), false);
|
|
134
244
|
if (scope.kind === "project") {
|
|
135
|
-
add(paths.projectPath(scope.cwd));
|
|
245
|
+
add(paths.projectPath(scope.cwd), true);
|
|
136
246
|
} else {
|
|
137
247
|
// pi loads the global layer first, then the trusted project layer, and
|
|
138
248
|
// DROPS the project entry on a collision — so a global write must not
|
|
139
249
|
// collide with any known trusted folder's entry.
|
|
140
|
-
for (const cwd of knownCwds()) if (trusted(cwd)) add(paths.projectPath(cwd));
|
|
250
|
+
for (const cwd of knownCwds()) if (trusted(cwd)) add(paths.projectPath(cwd), true);
|
|
141
251
|
}
|
|
142
252
|
return out;
|
|
143
253
|
}
|
|
@@ -270,6 +380,13 @@ export function createConfigWriter(deps: ConfigWriterDeps): ConfigWriter {
|
|
|
270
380
|
const bad = nameRefusal(prev);
|
|
271
381
|
if (bad) return { ok: false, refusal: bad };
|
|
272
382
|
}
|
|
383
|
+
if (scope.kind === "project") {
|
|
384
|
+
// Overrides have exactly one write path (`setProjectOverride`).
|
|
385
|
+
const prevEntry = renaming ? p.layer.servers[prev] : undefined;
|
|
386
|
+
if (isProjectOverride(entry) || isProjectOverride(prevEntry)) {
|
|
387
|
+
return { ok: false, refusal: { code: "invalid-entry", message: `server "${name}": ${OVERRIDE_ROUTE_HINT}`, path: p.path } };
|
|
388
|
+
}
|
|
389
|
+
}
|
|
273
390
|
// A rename or a create never replaces another entry: one write, one entry.
|
|
274
391
|
if ((renaming || opts?.create === true) && p.layer.servers[name] !== undefined) {
|
|
275
392
|
return {
|
|
@@ -301,27 +418,100 @@ export function createConfigWriter(deps: ConfigWriterDeps): ConfigWriter {
|
|
|
301
418
|
return w.ok ? { ok: true, removed } : w;
|
|
302
419
|
}
|
|
303
420
|
|
|
421
|
+
/** The kept Pi-global base for `name`, or a refusal (unparseable global wins over `no-global-server`). */
|
|
422
|
+
function keptBase(name: string): { ok: true; base: Record<string, unknown>; kept: ReadonlyMap<string, Record<string, unknown>> } | { ok: false; refusal: ConfigRefusal } {
|
|
423
|
+
const gpath = paths.globalPath();
|
|
424
|
+
const g = readLayer(configIO, gpath);
|
|
425
|
+
if (!g.ok) {
|
|
426
|
+
return { ok: false, refusal: { code: "unparseable", message: `${g.message} (pi skips this file; fix it by hand)`, path: gpath } };
|
|
427
|
+
}
|
|
428
|
+
const { kept } = keptGlobalOf(g.servers);
|
|
429
|
+
const base = kept.get(name);
|
|
430
|
+
if (!base) {
|
|
431
|
+
return {
|
|
432
|
+
ok: false,
|
|
433
|
+
refusal: {
|
|
434
|
+
code: "no-global-server",
|
|
435
|
+
message: `server "${name}" needs "command" or "url", or a global server to override`,
|
|
436
|
+
path: gpath,
|
|
437
|
+
},
|
|
438
|
+
};
|
|
439
|
+
}
|
|
440
|
+
return { ok: true, base, kept };
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
/** Everything an override write needs, or the refusal: scope, patch shape, target file, base. */
|
|
444
|
+
function planOverride(
|
|
445
|
+
name: string,
|
|
446
|
+
patch: ProjectOverridePatch,
|
|
447
|
+
scope: Scope,
|
|
448
|
+
):
|
|
449
|
+
| { ok: true; p: Extract<Prepared, { ok: true }>; existing: Record<string, unknown> | undefined; kept: ReadonlyMap<string, Record<string, unknown>> }
|
|
450
|
+
| { ok: false; refusal: ConfigRefusal } {
|
|
451
|
+
if (scope.kind !== "project") {
|
|
452
|
+
return { ok: false, refusal: { code: "invalid-entry", message: "a project override can only be written at project scope" } };
|
|
453
|
+
}
|
|
454
|
+
const bad = patchShapeRefusal(name, patch);
|
|
455
|
+
if (bad) return { ok: false, refusal: bad };
|
|
456
|
+
const p = prepare(name, scope);
|
|
457
|
+
if (!p.ok) return p;
|
|
458
|
+
const existing = existingObject(p, name);
|
|
459
|
+
if (!existing.ok) return existing;
|
|
460
|
+
if (existing.entry !== undefined && !isProjectOverride(existing.entry)) return wholeEntryRefusal(name, p.path);
|
|
461
|
+
const kb = keptBase(name); // an unparseable global file wins over no-global-server
|
|
462
|
+
if (!kb.ok) return kb;
|
|
463
|
+
return { ok: true, p, existing: existing.entry, kept: kb.kept };
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
/** Validate `next` as a pi override of its kept base, then write it (or delete the emptied entry). */
|
|
467
|
+
function commitOverride(
|
|
468
|
+
name: string,
|
|
469
|
+
p: Extract<Prepared, { ok: true }>,
|
|
470
|
+
next: Record<string, unknown>,
|
|
471
|
+
kept: ReadonlyMap<string, Record<string, unknown>>,
|
|
472
|
+
): ProjectOverrideResult {
|
|
473
|
+
const empty = Object.keys(next).length === 0;
|
|
474
|
+
const invalid = empty ? null : mergedOverrideRefusal(name, next, kept, p.path);
|
|
475
|
+
if (invalid) return { ok: false, refusal: invalid };
|
|
476
|
+
const servers = nullProto({ ...p.layer.servers });
|
|
477
|
+
if (empty) delete servers[name];
|
|
478
|
+
else servers[name] = next;
|
|
479
|
+
const w = write(p.path, p.layer.config, servers);
|
|
480
|
+
return w.ok ? { ok: true, override: empty ? undefined : { ...next } } : w;
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
function setProjectOverride(name: string, patch: ProjectOverridePatch, scope: Scope): ProjectOverrideResult {
|
|
484
|
+
const plan = planOverride(name, patch, scope);
|
|
485
|
+
if (!plan.ok) return plan;
|
|
486
|
+
const next = patchedOverride(plan.existing, patch);
|
|
487
|
+
// No key change touches no file (and creates none).
|
|
488
|
+
if (deepEqual({ ...(plan.existing ?? {}) }, { ...next })) {
|
|
489
|
+
return { ok: true, override: plan.existing === undefined ? undefined : { ...next } };
|
|
490
|
+
}
|
|
491
|
+
return commitOverride(name, plan.p, next, plan.kept);
|
|
492
|
+
}
|
|
493
|
+
|
|
304
494
|
function setEnabled(name: string, enabled: boolean, scope: Scope): SetEnabledResult {
|
|
305
495
|
const p = prepare(name, scope);
|
|
306
496
|
if (!p.ok) return p;
|
|
307
497
|
const existing = existingObject(p, name);
|
|
308
498
|
if (!existing.ok) return existing;
|
|
309
499
|
|
|
310
|
-
// The global entry
|
|
311
|
-
let
|
|
500
|
+
// The global entry the folder layer shadows or overrides (project scope only).
|
|
501
|
+
let globalRaw: unknown;
|
|
312
502
|
if (scope.kind === "project") {
|
|
313
503
|
const g = readLayer(configIO, paths.globalPath());
|
|
314
|
-
|
|
315
|
-
globalEntry = isPlainObject(raw) ? raw : undefined;
|
|
504
|
+
globalRaw = g.ok ? g.servers[name] : undefined;
|
|
316
505
|
}
|
|
317
506
|
|
|
318
|
-
|
|
507
|
+
// A whole-entry layer entry (any scope): toggle its own `enabled` key.
|
|
508
|
+
if (existing.entry !== undefined && !(scope.kind === "project" && isProjectOverride(existing.entry))) {
|
|
319
509
|
const next = existing.entry;
|
|
320
510
|
if (enabled) {
|
|
321
511
|
// Enabling a folder copy that lacks the global entry's secrets would
|
|
322
512
|
// connect without credentials: let the caller choose instead.
|
|
323
|
-
if (
|
|
324
|
-
const missing = folderCopyOf(
|
|
513
|
+
if (isPlainObject(globalRaw) && next.enabled === false) {
|
|
514
|
+
const missing = folderCopyOf(globalRaw).omitted.filter((f) => !hasPath(next, f));
|
|
325
515
|
if (missing.length > 0) return { ok: true, action: "needs-choice", omitted: missing };
|
|
326
516
|
}
|
|
327
517
|
delete next.enabled;
|
|
@@ -334,15 +524,13 @@ export function createConfigWriter(deps: ConfigWriterDeps): ConfigWriter {
|
|
|
334
524
|
return w.ok ? { ok: true, action: "written" } : w;
|
|
335
525
|
}
|
|
336
526
|
|
|
337
|
-
if (scope.kind === "project" &&
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
const
|
|
343
|
-
|
|
344
|
-
const w = write(p.path, p.layer.config, servers);
|
|
345
|
-
return w.ok ? { ok: true, action: "written", ...(omitted.length ? { omitted } : {}) } : w;
|
|
527
|
+
if (scope.kind === "project" && (existing.entry !== undefined || globalRaw !== undefined)) {
|
|
528
|
+
// A global server (with or without an override): write only the smallest override.
|
|
529
|
+
const kb = keptBase(name);
|
|
530
|
+
if (!kb.ok) return kb;
|
|
531
|
+
const globalOn = kb.base.enabled !== false;
|
|
532
|
+
const r = setProjectOverride(name, { enabled: enabled === globalOn ? null : enabled }, scope);
|
|
533
|
+
return r.ok ? { ok: true, action: "written" } : r;
|
|
346
534
|
}
|
|
347
535
|
|
|
348
536
|
return {
|
|
@@ -351,6 +539,43 @@ export function createConfigWriter(deps: ConfigWriterDeps): ConfigWriter {
|
|
|
351
539
|
};
|
|
352
540
|
}
|
|
353
541
|
|
|
542
|
+
/** The override a legacy copy converts to, or the refusal (not a legacy copy / invalid override keys). */
|
|
543
|
+
function legacyConversion(
|
|
544
|
+
name: string,
|
|
545
|
+
p: Extract<Prepared, { ok: true }>,
|
|
546
|
+
folder: Record<string, unknown> | undefined,
|
|
547
|
+
kb: { base: Record<string, unknown>; kept: ReadonlyMap<string, Record<string, unknown>> },
|
|
548
|
+
): { ok: true; next: Record<string, unknown> } | { ok: false; refusal: ConfigRefusal } {
|
|
549
|
+
if (folder === undefined || !isLegacyFolderCopy(p.layer.servers[name], kb.base)) {
|
|
550
|
+
return {
|
|
551
|
+
ok: false,
|
|
552
|
+
refusal: { code: "invalid-entry", message: `server "${name}" in ${p.path} is not a legacy copy of the global entry`, path: p.path },
|
|
553
|
+
};
|
|
554
|
+
}
|
|
555
|
+
const next = convertedOverride(folder, kb.base);
|
|
556
|
+
const invalid = Object.keys(next).length === 0 ? null : mergedOverrideRefusal(name, next, kb.kept, p.path);
|
|
557
|
+
return invalid ? { ok: false, refusal: invalid } : { ok: true, next };
|
|
558
|
+
}
|
|
559
|
+
|
|
560
|
+
function convertLegacyCopy(name: string, scope: Scope): ConvertLegacyResult {
|
|
561
|
+
if (scope.kind !== "project") {
|
|
562
|
+
return { ok: false, refusal: { code: "invalid-entry", message: "a legacy folder copy can only be converted at project scope" } };
|
|
563
|
+
}
|
|
564
|
+
const p = prepare(name, scope);
|
|
565
|
+
if (!p.ok) return p;
|
|
566
|
+
const existing = existingObject(p, name);
|
|
567
|
+
if (!existing.ok) return existing;
|
|
568
|
+
const kb = keptBase(name);
|
|
569
|
+
if (!kb.ok) return kb;
|
|
570
|
+
const plan = legacyConversion(name, p, existing.entry, kb);
|
|
571
|
+
if (!plan.ok) return plan;
|
|
572
|
+
const servers = nullProto({ ...p.layer.servers });
|
|
573
|
+
if (Object.keys(plan.next).length === 0) delete servers[name];
|
|
574
|
+
else servers[name] = plan.next;
|
|
575
|
+
const w = write(p.path, p.layer.config, servers);
|
|
576
|
+
return w.ok ? { ok: true, previous: p.layer.servers[name] as ServerEntry } : w;
|
|
577
|
+
}
|
|
578
|
+
|
|
354
579
|
function convertAdapterLeftovers(name: string, scope: Scope): ConfigWriteResult {
|
|
355
580
|
const p = prepare(name, scope);
|
|
356
581
|
if (!p.ok) return p;
|
|
@@ -392,6 +617,8 @@ export function createConfigWriter(deps: ConfigWriterDeps): ConfigWriter {
|
|
|
392
617
|
saveServer,
|
|
393
618
|
removeServer,
|
|
394
619
|
setEnabled,
|
|
620
|
+
setProjectOverride,
|
|
621
|
+
convertLegacyCopy,
|
|
395
622
|
convertAdapterLeftovers,
|
|
396
623
|
previewEnsure,
|
|
397
624
|
readParseStatus,
|