@mcpjam/inspector 3.12.9 → 3.14.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/bin/runtime-profile.mjs +774 -0
- package/bin/start.js +138 -19
- package/dist/client/assets/OAuthDesktopReturnNotice-BZEaGzn6.css +2 -0
- package/dist/client/assets/{OAuthDesktopReturnNotice-DlTJhJwy.js → OAuthDesktopReturnNotice-D7d-faB1.js} +2 -2
- package/dist/client/assets/{app-bootstrap-BtbHLWDU.js → app-bootstrap-BtDjj9nz.js} +370 -387
- package/dist/client/assets/{button-12hqsTUk.js → button-B99pZFz_.js} +2 -2
- package/dist/client/assets/chunk-D32TOXHM-Bcyg0ZVj.js +160 -0
- package/dist/client/assets/dead-clicks-autocapture-CnUHv5CB.js +3 -0
- package/dist/client/assets/error-reporting-BohBwcQQ.js +120 -0
- package/dist/client/assets/{error-reporting-D3byeSLw.js → error-reporting-p6G1ojum.js} +1 -1
- package/dist/client/assets/{exception-autocapture-CzpTtsxv.js → exception-autocapture-Q-isBTHp.js} +4 -4
- package/dist/client/assets/{failed-request-tracker-CmHxaDPF.js → failed-request-tracker-BBJW8izb.js} +2 -2
- package/dist/client/assets/highlighted-body-KQOG7T2V-zsXWRnSM.js +3 -0
- package/dist/client/assets/{index-C0SfPmai.js → index-C9oFRqoK.js} +3 -3
- package/dist/client/assets/{jszip.min-BmAHHtmZ.js → jszip.min-C86zG41a.js} +2 -2
- package/dist/client/assets/mermaid-MCJ5UELQ-DAW4LYwz.js +1 -0
- package/dist/client/assets/posthog-recorder-trUd0BXy.js +110 -0
- package/dist/client/assets/{preload-helper-B22rzauv.js → preload-helper-Buauuydw.js} +2 -2
- package/dist/client/assets/{react-BzkNdoI5.js → react-CZb-kDOs.js} +2 -2
- package/dist/client/assets/{rolldown-runtime-BNuWddGb.js → rolldown-runtime-Bkua2_Tb.js} +1 -1
- package/dist/client/assets/surveys-BISK_WOT.js +3 -0
- package/dist/client/assets/trace-timeline-CRewsP1E.js +71 -0
- package/dist/client/assets/{trace-timeline-Bg58ukyI.js → trace-timeline-D-DWE-sO.js} +1 -1
- package/dist/client/assets/{web-vitals-D4bU8W1t.js → web-vitals-DqmZ9w02.js} +2 -2
- package/dist/client/index.html +8 -8
- package/dist/server/authorization-MA42CNYT.js +22 -0
- package/dist/server/chunk-7M3XVZCQ.js +381 -0
- package/dist/server/{chunk-SH24KJBI.js → chunk-7ZIR7SX7.js} +17 -45
- package/dist/server/chunk-C47PTIDS.js +487 -0
- package/dist/server/chunk-DHRTCKJA.js +3979 -0
- package/dist/server/chunk-HJTKF2X6.js +45 -0
- package/dist/server/{chunk-DGAFFBDM.js → chunk-KNO4KZJF.js} +728 -682
- package/dist/server/{chunk-4PYR7GMQ.js → chunk-RWFTW2EW.js} +7 -5
- package/dist/server/chunk-SDWJSPSI.js +252 -0
- package/dist/server/chunk-VFRLMHOC.js +33 -0
- package/dist/server/chunk-XSQ2GC45.js +438 -0
- package/dist/server/chunk-YQ2BTE46.js +88 -0
- package/dist/server/{consent-lifetime-M7PS6RUU.js → consent-lifetime-OXQM37RV.js} +4 -3
- package/dist/server/grants-UVE62NGN.js +37 -0
- package/dist/server/harness-install-cli.js +259 -7
- package/dist/server/index.js +14252 -12005
- package/dist/server/local-turn-XSUGEKTL.js +19 -0
- package/dist/server/runtime-health-TCF3ZEKS.js +28 -0
- package/dist/server/runtime-lifecycle-YQ3KWDLJ.js +53 -0
- package/package.json +62 -59
- package/dist/client/assets/OAuthDesktopReturnNotice-FnFv52Ym.css +0 -2
- package/dist/client/assets/chunk-YOKDWASO--Bd-6XAf.js +0 -145
- package/dist/client/assets/dead-clicks-autocapture-RCao2exY.js +0 -3
- package/dist/client/assets/error-reporting-StyhxjHz.js +0 -102
- package/dist/client/assets/highlighted-body-KPVGNVTW-BweERQbm.js +0 -3
- package/dist/client/assets/mermaid-HWGCJPDP-C6s_jIuz.js +0 -1
- package/dist/client/assets/posthog-recorder-wc41pimR.js +0 -110
- package/dist/client/assets/surveys-D-NcCeqw.js +0 -3
- package/dist/client/assets/trace-timeline-CxoCCEiW.js +0 -137
- package/dist/server/chunk-WZVZ6LQX.js +0 -2876
- package/dist/server/local-turn-ZWMMQGV3.js +0 -12
|
@@ -1,2876 +0,0 @@
|
|
|
1
|
-
// server/utils/logger.ts
|
|
2
|
-
import * as Sentry from "@sentry/node";
|
|
3
|
-
import { Axiom } from "@axiomhq/js";
|
|
4
|
-
|
|
5
|
-
// server/utils/log-events.ts
|
|
6
|
-
var warnedMissingEnv = false;
|
|
7
|
-
var ALLOWED_ENVIRONMENTS = [
|
|
8
|
-
"prod",
|
|
9
|
-
"staging",
|
|
10
|
-
"preview",
|
|
11
|
-
"dev",
|
|
12
|
-
"local",
|
|
13
|
-
"test"
|
|
14
|
-
];
|
|
15
|
-
var ENVIRONMENT_ALIASES = {
|
|
16
|
-
production: "prod",
|
|
17
|
-
development: "dev"
|
|
18
|
-
};
|
|
19
|
-
function resolveEnvironment() {
|
|
20
|
-
const fromEnv = process.env.ENVIRONMENT?.trim();
|
|
21
|
-
if (fromEnv && ALLOWED_ENVIRONMENTS.includes(fromEnv)) {
|
|
22
|
-
return fromEnv;
|
|
23
|
-
}
|
|
24
|
-
const aliased = fromEnv ? ENVIRONMENT_ALIASES[fromEnv] : void 0;
|
|
25
|
-
if (aliased) {
|
|
26
|
-
return aliased;
|
|
27
|
-
}
|
|
28
|
-
if (process.env.NODE_ENV === "test") return "test";
|
|
29
|
-
if (process.env.NODE_ENV === "production") {
|
|
30
|
-
if (!warnedMissingEnv) {
|
|
31
|
-
warnedMissingEnv = true;
|
|
32
|
-
process.stderr.write(
|
|
33
|
-
"[logging] ENVIRONMENT not set in production; defaulting to 'prod'\n"
|
|
34
|
-
);
|
|
35
|
-
}
|
|
36
|
-
return "prod";
|
|
37
|
-
}
|
|
38
|
-
return "dev";
|
|
39
|
-
}
|
|
40
|
-
var BAKED_VERSION = "3.12.9";
|
|
41
|
-
function blankToNull(value) {
|
|
42
|
-
return value === void 0 || value.trim() === "" ? null : value;
|
|
43
|
-
}
|
|
44
|
-
function resolveAppVersion() {
|
|
45
|
-
return blankToNull(BAKED_VERSION) ?? blankToNull(process.env.npm_package_version);
|
|
46
|
-
}
|
|
47
|
-
function resolveRelease() {
|
|
48
|
-
return blankToNull(process.env.RAILWAY_GIT_COMMIT_SHA) ?? blankToNull(process.env.GIT_SHA) ?? resolveAppVersion();
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
// shared/secret-shape-redaction.ts
|
|
52
|
-
var authHeaderLike = () => /\b(authorization["']?\s*:\s*)["']?[^\n\r"'`]+/gi;
|
|
53
|
-
var tokenLike = () => /\bBearer\s+[A-Za-z0-9._~\-+/=]+\b/gi;
|
|
54
|
-
var skKeyLike = () => /\bsk-(?:[A-Za-z0-9]+-)*[A-Za-z0-9]{16,}\b/g;
|
|
55
|
-
var jwtLike = () => /\beyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\b/g;
|
|
56
|
-
var secretParamLike = () => /\b((?:api[_-]?key|apikey|access[_-]?token|refresh[_-]?token|id[_-]?token|client[_-]?secret|authorization|secret|password|passwd|pwd|token|auth|key|sig|signature)\s*[=:]\s*["']?)[^&\s"'`]+/gi;
|
|
57
|
-
var urlBasicAuthLike = () => /(\/\/[^\s/:@]+:)[^\s@/]+@/g;
|
|
58
|
-
function redactSecretShapes(text, replacement = "[redacted]") {
|
|
59
|
-
if (!text) return text;
|
|
60
|
-
const parts = text.split(SECRET_PLACEHOLDER);
|
|
61
|
-
if (parts.length === 1) return redactSegment(text, replacement);
|
|
62
|
-
return parts.map(
|
|
63
|
-
(part, index) => (
|
|
64
|
-
// Odd segments are the captured names.
|
|
65
|
-
index % 2 === 1 ? `{{secret:${part}}}` : redactSegment(part, replacement)
|
|
66
|
-
)
|
|
67
|
-
).join("");
|
|
68
|
-
}
|
|
69
|
-
var SECRET_PLACEHOLDER = /\{\{secret:([A-Z_][A-Z0-9_]*)\}\}/g;
|
|
70
|
-
function redactSegment(text, replacement) {
|
|
71
|
-
if (!text) return text;
|
|
72
|
-
return text.replace(authHeaderLike(), `$1${replacement}`).replace(tokenLike(), `Bearer ${replacement}`).replace(jwtLike(), replacement).replace(urlBasicAuthLike(), `$1${replacement}@`).replace(skKeyLike(), replacement).replace(secretParamLike(), `$1${replacement}`);
|
|
73
|
-
}
|
|
74
|
-
|
|
75
|
-
// server/utils/log-scrubber.ts
|
|
76
|
-
var FORBIDDEN_KEY_SUBSTRINGS = [
|
|
77
|
-
"authorization",
|
|
78
|
-
"cookie",
|
|
79
|
-
"password",
|
|
80
|
-
"token",
|
|
81
|
-
"secret",
|
|
82
|
-
"apikey",
|
|
83
|
-
"pkceverifier",
|
|
84
|
-
"pkcechallenge",
|
|
85
|
-
"stripecustomer",
|
|
86
|
-
"stripesubscription",
|
|
87
|
-
"stripeprice",
|
|
88
|
-
"x-mcp-session-auth",
|
|
89
|
-
"x-api-key",
|
|
90
|
-
// Header-broker model lease (E2B network-transform delivery). A signed model
|
|
91
|
-
// lease — never log it, even though the inspector never handles it directly
|
|
92
|
-
// (defense in depth).
|
|
93
|
-
"x-mcpjam-harness-lease"
|
|
94
|
-
];
|
|
95
|
-
var ALLOWLISTED_KEYS = /* @__PURE__ */ new Set(["emaildomain"]);
|
|
96
|
-
var EMAIL_LIKE = /\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b/gi;
|
|
97
|
-
function isForbiddenKey(key) {
|
|
98
|
-
const lower = key.toLowerCase();
|
|
99
|
-
if (ALLOWLISTED_KEYS.has(lower)) return false;
|
|
100
|
-
if (lower === "email" || lower.endsWith("email")) return true;
|
|
101
|
-
return FORBIDDEN_KEY_SUBSTRINGS.some((s) => lower.includes(s));
|
|
102
|
-
}
|
|
103
|
-
function scrubString(s) {
|
|
104
|
-
return s.replace(authHeaderLike(), "$1[redacted]").replace(tokenLike(), "Bearer [redacted-token]").replace(jwtLike(), "[redacted-jwt]").replace(urlBasicAuthLike(), "$1[redacted]@").replace(EMAIL_LIKE, "[redacted-email]").replace(skKeyLike(), "[redacted-secret]").replace(secretParamLike(), "$1[redacted]");
|
|
105
|
-
}
|
|
106
|
-
function scrubLogPayload(value) {
|
|
107
|
-
return scrubValue(value, /* @__PURE__ */ new WeakSet());
|
|
108
|
-
}
|
|
109
|
-
function scrubValue(value, seen) {
|
|
110
|
-
if (value === null || value === void 0) return value;
|
|
111
|
-
if (typeof value === "string") return scrubString(value);
|
|
112
|
-
if (typeof value !== "object") return value;
|
|
113
|
-
if (value instanceof Date) return value.toISOString();
|
|
114
|
-
if (value instanceof Error) {
|
|
115
|
-
return {
|
|
116
|
-
name: value.name,
|
|
117
|
-
message: scrubString(value.message),
|
|
118
|
-
stack: value.stack ? scrubString(value.stack) : void 0
|
|
119
|
-
};
|
|
120
|
-
}
|
|
121
|
-
if (typeof Buffer !== "undefined" && Buffer.isBuffer(value)) {
|
|
122
|
-
return "[buffer]";
|
|
123
|
-
}
|
|
124
|
-
if (seen.has(value)) return "[circular]";
|
|
125
|
-
seen.add(value);
|
|
126
|
-
if (Array.isArray(value)) return value.map((v) => scrubValue(v, seen));
|
|
127
|
-
const out = {};
|
|
128
|
-
for (const [k, v] of Object.entries(value)) {
|
|
129
|
-
if (isForbiddenKey(k)) {
|
|
130
|
-
out[k] = "[redacted]";
|
|
131
|
-
continue;
|
|
132
|
-
}
|
|
133
|
-
out[k] = scrubValue(v, seen);
|
|
134
|
-
}
|
|
135
|
-
return out;
|
|
136
|
-
}
|
|
137
|
-
|
|
138
|
-
// server/utils/error-capture-stamp.ts
|
|
139
|
-
var CAPTURE_STAMP = Symbol.for("mcpjam.errorOriginCaptureHandled");
|
|
140
|
-
function isStampable(value) {
|
|
141
|
-
return typeof value === "object" && value !== null;
|
|
142
|
-
}
|
|
143
|
-
function safeErrorMessage(value) {
|
|
144
|
-
try {
|
|
145
|
-
return value instanceof Error ? value.message : String(value);
|
|
146
|
-
} catch {
|
|
147
|
-
return "[unreadable error value]";
|
|
148
|
-
}
|
|
149
|
-
}
|
|
150
|
-
function markOriginCaptureHandled(value) {
|
|
151
|
-
if (!isStampable(value)) return;
|
|
152
|
-
try {
|
|
153
|
-
Object.defineProperty(value, CAPTURE_STAMP, {
|
|
154
|
-
value: true,
|
|
155
|
-
enumerable: false,
|
|
156
|
-
configurable: true,
|
|
157
|
-
writable: true
|
|
158
|
-
});
|
|
159
|
-
} catch {
|
|
160
|
-
}
|
|
161
|
-
}
|
|
162
|
-
function ensureStampable(value) {
|
|
163
|
-
if (!isStampable(value)) return new Error(String(value));
|
|
164
|
-
let extensible;
|
|
165
|
-
try {
|
|
166
|
-
extensible = Object.isExtensible(value);
|
|
167
|
-
} catch {
|
|
168
|
-
extensible = false;
|
|
169
|
-
}
|
|
170
|
-
if (!extensible) {
|
|
171
|
-
const wrapped = new Error(
|
|
172
|
-
safeErrorMessage(value)
|
|
173
|
-
);
|
|
174
|
-
Object.defineProperty(wrapped, "cause", {
|
|
175
|
-
value,
|
|
176
|
-
enumerable: false,
|
|
177
|
-
configurable: true,
|
|
178
|
-
writable: true
|
|
179
|
-
});
|
|
180
|
-
return wrapped;
|
|
181
|
-
}
|
|
182
|
-
return value;
|
|
183
|
-
}
|
|
184
|
-
var MAX_CAUSE_DEPTH = 8;
|
|
185
|
-
function isOriginCaptureHandled(error) {
|
|
186
|
-
const seen = /* @__PURE__ */ new Set();
|
|
187
|
-
let current = error;
|
|
188
|
-
for (let depth = 0; depth < MAX_CAUSE_DEPTH; depth += 1) {
|
|
189
|
-
if (!isStampable(current) || seen.has(current)) return false;
|
|
190
|
-
seen.add(current);
|
|
191
|
-
try {
|
|
192
|
-
if (current[CAPTURE_STAMP] === true) return true;
|
|
193
|
-
const normalized = current.normalized;
|
|
194
|
-
if (isStampable(normalized) && normalized[CAPTURE_STAMP] === true) {
|
|
195
|
-
return true;
|
|
196
|
-
}
|
|
197
|
-
current = current.cause;
|
|
198
|
-
} catch {
|
|
199
|
-
return false;
|
|
200
|
-
}
|
|
201
|
-
}
|
|
202
|
-
return false;
|
|
203
|
-
}
|
|
204
|
-
|
|
205
|
-
// server/utils/logger.ts
|
|
206
|
-
var isVerbose = () => process.env.VERBOSE_LOGS === "true";
|
|
207
|
-
var isDev = () => process.env.NODE_ENV !== "production";
|
|
208
|
-
var shouldLog = () => isVerbose() || isDev();
|
|
209
|
-
function isTrackingDisabled() {
|
|
210
|
-
const dnt = process.env.DO_NOT_TRACK;
|
|
211
|
-
return dnt === "1" || dnt === "true";
|
|
212
|
-
}
|
|
213
|
-
var axiomClient;
|
|
214
|
-
function getAxiom() {
|
|
215
|
-
if (isTrackingDisabled()) return null;
|
|
216
|
-
if (axiomClient === void 0) {
|
|
217
|
-
axiomClient = process.env.AXIOM_TOKEN && process.env.AXIOM_DATASET ? new Axiom({ token: process.env.AXIOM_TOKEN }) : null;
|
|
218
|
-
}
|
|
219
|
-
return axiomClient;
|
|
220
|
-
}
|
|
221
|
-
var dataset = () => process.env.AXIOM_DATASET ?? "";
|
|
222
|
-
var environment = () => resolveEnvironment();
|
|
223
|
-
function ingestToAxiom(level, message, context) {
|
|
224
|
-
const axiom = getAxiom();
|
|
225
|
-
if (!axiom) return;
|
|
226
|
-
axiom.ingest(dataset(), [
|
|
227
|
-
{ ...context, level, message, environment: environment() }
|
|
228
|
-
]);
|
|
229
|
-
}
|
|
230
|
-
function safeErrorText(error) {
|
|
231
|
-
try {
|
|
232
|
-
return error instanceof Error ? error.message : String(error);
|
|
233
|
-
} catch {
|
|
234
|
-
return "[unreadable error value]";
|
|
235
|
-
}
|
|
236
|
-
}
|
|
237
|
-
function captureOriginErrorToSentry(error, options) {
|
|
238
|
-
Sentry.captureException(error, options);
|
|
239
|
-
}
|
|
240
|
-
var logger = {
|
|
241
|
-
/**
|
|
242
|
-
* Log an error. Always sends to Sentry and Axiom, only prints to console in dev/verbose mode.
|
|
243
|
-
*
|
|
244
|
-
* This is the server's single Sentry capture path for free-form errors —
|
|
245
|
-
* `Hono.onError` routes through here, so route handlers never call
|
|
246
|
-
* `captureException` themselves and nothing double-counts.
|
|
247
|
-
*
|
|
248
|
-
* NOTE: For new production diagnostics in `server/routes/web/`, prefer `logger.event()` —
|
|
249
|
-
* free-form messages are not queryable in Axiom. Legacy callers (CLI, system code,
|
|
250
|
-
* non-route utilities) remain on this API. See `server/utils/LOGGING.md`.
|
|
251
|
-
*/
|
|
252
|
-
error(message, error, context) {
|
|
253
|
-
if (!isOriginCaptureHandled(error)) {
|
|
254
|
-
Sentry.captureException(error ?? new Error(message), {
|
|
255
|
-
extra: { message, ...context }
|
|
256
|
-
});
|
|
257
|
-
}
|
|
258
|
-
ingestToAxiom("error", message, {
|
|
259
|
-
...context,
|
|
260
|
-
error: safeErrorText(error)
|
|
261
|
-
});
|
|
262
|
-
if (shouldLog()) {
|
|
263
|
-
console.error(message, error);
|
|
264
|
-
}
|
|
265
|
-
},
|
|
266
|
-
/**
|
|
267
|
-
* Log a warning. Sends to Axiom, only prints to console in dev/verbose mode.
|
|
268
|
-
*
|
|
269
|
-
* Deliberately does NOT capture to Sentry. Every `logger.warn` in the tree
|
|
270
|
-
* used to become a Sentry event, which across thousands of self-hosted
|
|
271
|
-
* installs is the single largest quota-spike vector we have — and a warning
|
|
272
|
-
* is by definition something we chose not to treat as a failure. Axiom is
|
|
273
|
-
* the right home for it: queryable, cheap, no issue-tracker noise. A warning
|
|
274
|
-
* that genuinely needs a Sentry issue should be an explicit
|
|
275
|
-
* `logger.event(..., { error, sentry: true })` at the callsite that owns it.
|
|
276
|
-
*
|
|
277
|
-
* NOTE: For new production diagnostics in `server/routes/web/`, prefer `logger.event()` —
|
|
278
|
-
* free-form messages are not queryable in Axiom. Legacy callers (CLI, system code,
|
|
279
|
-
* non-route utilities) remain on this API. See `server/utils/LOGGING.md`.
|
|
280
|
-
*/
|
|
281
|
-
warn(message, context) {
|
|
282
|
-
ingestToAxiom("warn", message, context);
|
|
283
|
-
if (shouldLog()) {
|
|
284
|
-
console.warn(message);
|
|
285
|
-
}
|
|
286
|
-
},
|
|
287
|
-
/**
|
|
288
|
-
* Log info. Always sends to Axiom. Only prints to console in dev/verbose mode.
|
|
289
|
-
*
|
|
290
|
-
* NOTE: For new production diagnostics in `server/routes/web/`, prefer `logger.event()` —
|
|
291
|
-
* free-form messages are not queryable in Axiom. Legacy callers (CLI, system code,
|
|
292
|
-
* non-route utilities) remain on this API. See `server/utils/LOGGING.md`.
|
|
293
|
-
*/
|
|
294
|
-
info(message, context) {
|
|
295
|
-
ingestToAxiom("info", message, context);
|
|
296
|
-
if (shouldLog()) {
|
|
297
|
-
console.log(message);
|
|
298
|
-
}
|
|
299
|
-
},
|
|
300
|
-
/**
|
|
301
|
-
* Log debug info. Always sends to Axiom. Only prints to console in dev/verbose mode. Does not send to Sentry.
|
|
302
|
-
*/
|
|
303
|
-
debug(message, ...args) {
|
|
304
|
-
ingestToAxiom("debug", message, args.length ? { args } : void 0);
|
|
305
|
-
if (shouldLog()) {
|
|
306
|
-
console.log(message, ...args);
|
|
307
|
-
}
|
|
308
|
-
},
|
|
309
|
-
/**
|
|
310
|
-
* Flush pending Axiom events. Call before process exit.
|
|
311
|
-
*/
|
|
312
|
-
async flush() {
|
|
313
|
-
await getAxiom()?.flush();
|
|
314
|
-
},
|
|
315
|
-
event(eventName, base, payload, options) {
|
|
316
|
-
emit(eventName, base, payload, options);
|
|
317
|
-
},
|
|
318
|
-
systemEvent(eventName, base, payload, options) {
|
|
319
|
-
emit(eventName, base, payload, options);
|
|
320
|
-
}
|
|
321
|
-
};
|
|
322
|
-
var MAX_ERROR_MESSAGE_CHARS = 2e3;
|
|
323
|
-
var MAX_ERROR_STACK_CHARS = 4e3;
|
|
324
|
-
function serializeEmitError(error) {
|
|
325
|
-
try {
|
|
326
|
-
if (error instanceof Error) {
|
|
327
|
-
return {
|
|
328
|
-
name: error.name,
|
|
329
|
-
message: error.message.slice(0, MAX_ERROR_MESSAGE_CHARS),
|
|
330
|
-
...error.stack ? { stack: error.stack.slice(0, MAX_ERROR_STACK_CHARS) } : {}
|
|
331
|
-
};
|
|
332
|
-
}
|
|
333
|
-
return String(error).slice(0, MAX_ERROR_MESSAGE_CHARS);
|
|
334
|
-
} catch {
|
|
335
|
-
return "[unserializable error]";
|
|
336
|
-
}
|
|
337
|
-
}
|
|
338
|
-
function emit(eventName, base, payload, options) {
|
|
339
|
-
const fullPayload = scrubLogPayload({
|
|
340
|
-
...base,
|
|
341
|
-
...payload,
|
|
342
|
-
...options?.error !== void 0 ? { error: serializeEmitError(options.error) } : {},
|
|
343
|
-
event: eventName,
|
|
344
|
-
timestamp: (/* @__PURE__ */ new Date()).toISOString()
|
|
345
|
-
});
|
|
346
|
-
const axiom = getAxiom();
|
|
347
|
-
if (axiom) {
|
|
348
|
-
axiom.ingest(dataset(), [fullPayload]);
|
|
349
|
-
}
|
|
350
|
-
if (options?.sentry === true) {
|
|
351
|
-
if (options.error instanceof Error) {
|
|
352
|
-
Sentry.captureException(options.error, { extra: fullPayload });
|
|
353
|
-
} else {
|
|
354
|
-
Sentry.captureMessage(eventName, {
|
|
355
|
-
level: "error",
|
|
356
|
-
extra: {
|
|
357
|
-
...fullPayload,
|
|
358
|
-
...options.error !== void 0 ? { rawError: String(options.error) } : {}
|
|
359
|
-
}
|
|
360
|
-
});
|
|
361
|
-
}
|
|
362
|
-
}
|
|
363
|
-
if (shouldLog()) {
|
|
364
|
-
const consoleFn = eventName.endsWith(".failed") ? console.error : console.log;
|
|
365
|
-
consoleFn(`[event] ${eventName}`, fullPayload);
|
|
366
|
-
}
|
|
367
|
-
}
|
|
368
|
-
process.on("beforeExit", () => logger.flush());
|
|
369
|
-
|
|
370
|
-
// server/utils/harness/local/targets.ts
|
|
371
|
-
var LOCAL_PACK_TARGETS = /* @__PURE__ */ new Set([
|
|
372
|
-
"darwin-arm64",
|
|
373
|
-
"darwin-x64",
|
|
374
|
-
"linux-x64",
|
|
375
|
-
"linux-arm64",
|
|
376
|
-
"win32-x64"
|
|
377
|
-
]);
|
|
378
|
-
function localPackTarget(platform = process.platform, arch = process.arch) {
|
|
379
|
-
const key = `${platform}-${arch}`;
|
|
380
|
-
return LOCAL_PACK_TARGETS.has(key) ? key : null;
|
|
381
|
-
}
|
|
382
|
-
var LOCAL_HARNESS_POLICY_VERSION = "local-harness-policy-2026-09-28";
|
|
383
|
-
var LOCAL_ISOLATION_POLICY_VERSION = "local-isolation-policy-2026-09-01";
|
|
384
|
-
function currentLocalPlatform(platform = process.platform) {
|
|
385
|
-
if (platform === "darwin" || platform === "linux" || platform === "win32") {
|
|
386
|
-
return platform;
|
|
387
|
-
}
|
|
388
|
-
return null;
|
|
389
|
-
}
|
|
390
|
-
|
|
391
|
-
// server/utils/harness/local/runtime-lifecycle.ts
|
|
392
|
-
import { randomUUID as randomUUID2 } from "crypto";
|
|
393
|
-
import {
|
|
394
|
-
mkdir as mkdir2,
|
|
395
|
-
readdir,
|
|
396
|
-
readFile as readFile2,
|
|
397
|
-
rename,
|
|
398
|
-
rm as rm2,
|
|
399
|
-
stat as stat2,
|
|
400
|
-
writeFile as writeFile2
|
|
401
|
-
} from "fs/promises";
|
|
402
|
-
import { join as join2 } from "path";
|
|
403
|
-
|
|
404
|
-
// server/utils/harness/local/local-state-lock.ts
|
|
405
|
-
import { randomUUID } from "crypto";
|
|
406
|
-
import { mkdir, readFile, rm, stat, writeFile } from "fs/promises";
|
|
407
|
-
import { join } from "path";
|
|
408
|
-
var DEFAULT_STALE_MS = 3e4;
|
|
409
|
-
var DEFAULT_POLL_MS = 25;
|
|
410
|
-
var DEFAULT_TIMEOUT_MS = 45e3;
|
|
411
|
-
async function readLockBody(file) {
|
|
412
|
-
try {
|
|
413
|
-
const parsed = JSON.parse(await readFile(file, "utf8"));
|
|
414
|
-
if (!parsed || typeof parsed !== "object") return null;
|
|
415
|
-
const body = parsed;
|
|
416
|
-
if (typeof body.pid !== "number" || !Number.isInteger(body.pid) || body.pid <= 0 || typeof body.nonce !== "string" || body.nonce.length === 0) {
|
|
417
|
-
return null;
|
|
418
|
-
}
|
|
419
|
-
return { pid: body.pid, nonce: body.nonce, at: Number(body.at) || 0 };
|
|
420
|
-
} catch {
|
|
421
|
-
return null;
|
|
422
|
-
}
|
|
423
|
-
}
|
|
424
|
-
function lockHolderProvablyGone(body) {
|
|
425
|
-
if (body === null || body.pid === process.pid) return false;
|
|
426
|
-
try {
|
|
427
|
-
process.kill(body.pid, 0);
|
|
428
|
-
return false;
|
|
429
|
-
} catch (error) {
|
|
430
|
-
return error.code === "ESRCH";
|
|
431
|
-
}
|
|
432
|
-
}
|
|
433
|
-
function createLocalStateMutationLock(options) {
|
|
434
|
-
let mutationChain = Promise.resolve();
|
|
435
|
-
const staleMs = options.staleMs ?? DEFAULT_STALE_MS;
|
|
436
|
-
const pollMs = options.pollMs ?? DEFAULT_POLL_MS;
|
|
437
|
-
const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
438
|
-
const acquire = async () => {
|
|
439
|
-
const root = options.rootDir();
|
|
440
|
-
const file = join(root, options.lockFileName);
|
|
441
|
-
await mkdir(root, { recursive: true, mode: 448 });
|
|
442
|
-
const nonce = randomUUID();
|
|
443
|
-
const deadline = Date.now() + timeoutMs;
|
|
444
|
-
for (; ; ) {
|
|
445
|
-
try {
|
|
446
|
-
await writeFile(
|
|
447
|
-
file,
|
|
448
|
-
JSON.stringify({ pid: process.pid, nonce, at: Date.now() }),
|
|
449
|
-
{ flag: "wx", mode: 384 }
|
|
450
|
-
);
|
|
451
|
-
return async () => {
|
|
452
|
-
const held = await readLockBody(file);
|
|
453
|
-
if (held?.nonce !== nonce) {
|
|
454
|
-
logger.warn(
|
|
455
|
-
`[local-harness] ${options.resourceLabel} lock was taken over; not releasing`
|
|
456
|
-
);
|
|
457
|
-
return;
|
|
458
|
-
}
|
|
459
|
-
await rm(file, { force: true }).catch(() => {
|
|
460
|
-
});
|
|
461
|
-
};
|
|
462
|
-
} catch (error) {
|
|
463
|
-
if (error.code !== "EEXIST") throw error;
|
|
464
|
-
const body = await readLockBody(file);
|
|
465
|
-
const age = await stat(file).then(
|
|
466
|
-
(info) => Date.now() - info.mtimeMs,
|
|
467
|
-
() => 0
|
|
468
|
-
);
|
|
469
|
-
const holderGone = lockHolderProvablyGone(body);
|
|
470
|
-
const unattributable = body === null && age > staleMs;
|
|
471
|
-
if (holderGone || unattributable) {
|
|
472
|
-
logger.warn(
|
|
473
|
-
`[local-harness] breaking an abandoned ${options.resourceLabel} lock`,
|
|
474
|
-
{ age, holderGone, unattributable }
|
|
475
|
-
);
|
|
476
|
-
await rm(file, { force: true }).catch(() => {
|
|
477
|
-
});
|
|
478
|
-
continue;
|
|
479
|
-
}
|
|
480
|
-
if (Date.now() > deadline) {
|
|
481
|
-
throw new Error(
|
|
482
|
-
`timed out waiting for the local harness ${options.resourceLabel} lock` + (body === null ? "" : ` (held by pid ${body.pid})`) + ". Its holder could not be proven gone, and taking it over would admit concurrent state writers."
|
|
483
|
-
);
|
|
484
|
-
}
|
|
485
|
-
await new Promise(
|
|
486
|
-
(resolvePromise) => setTimeout(resolvePromise, pollMs)
|
|
487
|
-
);
|
|
488
|
-
}
|
|
489
|
-
}
|
|
490
|
-
};
|
|
491
|
-
return (operation) => {
|
|
492
|
-
const guarded = async () => {
|
|
493
|
-
const release = await acquire();
|
|
494
|
-
try {
|
|
495
|
-
return await operation();
|
|
496
|
-
} finally {
|
|
497
|
-
await release();
|
|
498
|
-
}
|
|
499
|
-
};
|
|
500
|
-
const run = mutationChain.then(guarded, guarded);
|
|
501
|
-
mutationChain = run.then(
|
|
502
|
-
() => void 0,
|
|
503
|
-
() => void 0
|
|
504
|
-
);
|
|
505
|
-
return run;
|
|
506
|
-
};
|
|
507
|
-
}
|
|
508
|
-
|
|
509
|
-
// server/utils/harness/local/runtime-lifecycle.ts
|
|
510
|
-
var OPERATION_FILE = ".mcpjam-operation.json";
|
|
511
|
-
var USE_DIR = ".mcpjam-inuse";
|
|
512
|
-
var STAGING_PREFIX = ".mcpjam-tmp-";
|
|
513
|
-
var STAGING_OWNER_FILE = ".mcpjam-staging-owner.json";
|
|
514
|
-
function operationKeyString(key) {
|
|
515
|
-
return [
|
|
516
|
-
key.runtimeRoot,
|
|
517
|
-
key.harnessId,
|
|
518
|
-
key.target,
|
|
519
|
-
key.packVersion,
|
|
520
|
-
key.treeDigest
|
|
521
|
-
].join("\0");
|
|
522
|
-
}
|
|
523
|
-
function installRootOf(key) {
|
|
524
|
-
return join2(key.runtimeRoot, key.target);
|
|
525
|
-
}
|
|
526
|
-
var locksByRoot = /* @__PURE__ */ new Map();
|
|
527
|
-
function lockFor(key) {
|
|
528
|
-
const root = installRootOf(key);
|
|
529
|
-
let lock = locksByRoot.get(root);
|
|
530
|
-
if (lock === void 0) {
|
|
531
|
-
lock = createLocalStateMutationLock({
|
|
532
|
-
rootDir: () => root,
|
|
533
|
-
lockFileName: ".mcpjam-runtime-lifecycle.lock",
|
|
534
|
-
resourceLabel: "runtime lifecycle",
|
|
535
|
-
// Short by construction: every critical section here is a read, a
|
|
536
|
-
// compare and an atomic write. A caller waiting longer than this is
|
|
537
|
-
// waiting on something that is not doing that.
|
|
538
|
-
timeoutMs: 15e3
|
|
539
|
-
});
|
|
540
|
-
locksByRoot.set(root, lock);
|
|
541
|
-
}
|
|
542
|
-
return lock;
|
|
543
|
-
}
|
|
544
|
-
function ownerProvablyGone(record) {
|
|
545
|
-
if (record.ownerPid === process.pid) {
|
|
546
|
-
return record.ownerStartedAt !== processStartedAt();
|
|
547
|
-
}
|
|
548
|
-
try {
|
|
549
|
-
process.kill(record.ownerPid, 0);
|
|
550
|
-
return false;
|
|
551
|
-
} catch (error) {
|
|
552
|
-
return error.code === "ESRCH";
|
|
553
|
-
}
|
|
554
|
-
}
|
|
555
|
-
var cachedStartedAt = null;
|
|
556
|
-
function processStartedAt() {
|
|
557
|
-
if (cachedStartedAt === null) {
|
|
558
|
-
cachedStartedAt = Math.floor((Date.now() - process.uptime() * 1e3) / 1e3);
|
|
559
|
-
}
|
|
560
|
-
return cachedStartedAt;
|
|
561
|
-
}
|
|
562
|
-
async function writeJsonAtomic(file, value) {
|
|
563
|
-
const tmp = `${file}.${process.pid}.${randomUUID2()}.tmp`;
|
|
564
|
-
await writeFile2(tmp, `${JSON.stringify(value, null, 2)}
|
|
565
|
-
`, { mode: 384 });
|
|
566
|
-
await rename(tmp, file);
|
|
567
|
-
}
|
|
568
|
-
async function readJson(file) {
|
|
569
|
-
try {
|
|
570
|
-
return JSON.parse(await readFile2(file, "utf8"));
|
|
571
|
-
} catch {
|
|
572
|
-
return null;
|
|
573
|
-
}
|
|
574
|
-
}
|
|
575
|
-
async function readRuntimeOperation(key) {
|
|
576
|
-
const file = join2(installRootOf(key), OPERATION_FILE);
|
|
577
|
-
const record = await readJson(file);
|
|
578
|
-
if (record === null) return null;
|
|
579
|
-
if (record.packVersion !== key.packVersion || record.treeDigest !== key.treeDigest || record.harnessId !== key.harnessId) {
|
|
580
|
-
return null;
|
|
581
|
-
}
|
|
582
|
-
const terminal = record.state === "ready" || record.state === "failed" || record.state === "interrupted";
|
|
583
|
-
if (terminal || !ownerProvablyGone(record)) return record;
|
|
584
|
-
return lockFor(key)(async () => {
|
|
585
|
-
const fresh = await readJson(file);
|
|
586
|
-
if (fresh === null) return null;
|
|
587
|
-
if (fresh.attemptId !== record.attemptId) return fresh;
|
|
588
|
-
if (fresh.state === "ready" || fresh.state === "failed" || fresh.state === "interrupted") {
|
|
589
|
-
return fresh;
|
|
590
|
-
}
|
|
591
|
-
if (!ownerProvablyGone(fresh)) return fresh;
|
|
592
|
-
const reconciled = {
|
|
593
|
-
...fresh,
|
|
594
|
-
state: "interrupted",
|
|
595
|
-
message: "the Inspector that started this install is no longer running, so the attempt was abandoned partway through",
|
|
596
|
-
updatedAt: Date.now()
|
|
597
|
-
};
|
|
598
|
-
await writeJsonAtomic(file, reconciled);
|
|
599
|
-
logger.info("[local-harness] recovered an interrupted install attempt", {
|
|
600
|
-
attemptId: reconciled.attemptId,
|
|
601
|
-
packVersion: reconciled.packVersion
|
|
602
|
-
});
|
|
603
|
-
return reconciled;
|
|
604
|
-
});
|
|
605
|
-
}
|
|
606
|
-
async function beginInstallAttempt(key) {
|
|
607
|
-
const root = installRootOf(key);
|
|
608
|
-
await mkdir2(root, { recursive: true, mode: 448 });
|
|
609
|
-
const file = join2(root, OPERATION_FILE);
|
|
610
|
-
return lockFor(key)(async () => {
|
|
611
|
-
const existing = await readJson(file);
|
|
612
|
-
if (existing !== null && existing.packVersion === key.packVersion && existing.treeDigest === key.treeDigest && existing.harnessId === key.harnessId) {
|
|
613
|
-
const live = existing.state !== "ready" && existing.state !== "failed" && existing.state !== "interrupted";
|
|
614
|
-
if (live && !ownerProvablyGone(existing)) {
|
|
615
|
-
return { kind: "joined", record: existing };
|
|
616
|
-
}
|
|
617
|
-
}
|
|
618
|
-
const record = {
|
|
619
|
-
attemptId: `att_${randomUUID2()}`,
|
|
620
|
-
ownerPid: process.pid,
|
|
621
|
-
ownerStartedAt: processStartedAt(),
|
|
622
|
-
harnessId: key.harnessId,
|
|
623
|
-
target: key.target,
|
|
624
|
-
packVersion: key.packVersion,
|
|
625
|
-
treeDigest: key.treeDigest,
|
|
626
|
-
state: "reserved",
|
|
627
|
-
startedAt: Date.now(),
|
|
628
|
-
updatedAt: Date.now()
|
|
629
|
-
};
|
|
630
|
-
await writeJsonAtomic(file, record);
|
|
631
|
-
return { kind: "started", record };
|
|
632
|
-
});
|
|
633
|
-
}
|
|
634
|
-
async function updateInstallAttempt(key, attemptId, patch) {
|
|
635
|
-
const file = join2(installRootOf(key), OPERATION_FILE);
|
|
636
|
-
return lockFor(key)(async () => {
|
|
637
|
-
const existing = await readJson(file);
|
|
638
|
-
if (existing === null || existing.attemptId !== attemptId) return false;
|
|
639
|
-
await writeJsonAtomic(file, {
|
|
640
|
-
...existing,
|
|
641
|
-
...patch,
|
|
642
|
-
updatedAt: Date.now()
|
|
643
|
-
});
|
|
644
|
-
return true;
|
|
645
|
-
});
|
|
646
|
-
}
|
|
647
|
-
async function attemptStillOwns(key, attemptId) {
|
|
648
|
-
const record = await readJson(
|
|
649
|
-
join2(installRootOf(key), OPERATION_FILE)
|
|
650
|
-
);
|
|
651
|
-
return record?.attemptId === attemptId;
|
|
652
|
-
}
|
|
653
|
-
async function reserveRuntimeUse(args) {
|
|
654
|
-
const dir = join2(installRootOf(args.key), USE_DIR);
|
|
655
|
-
await mkdir2(dir, { recursive: true, mode: 448 });
|
|
656
|
-
const file = join2(dir, `${process.pid}-${randomUUID2()}.json`);
|
|
657
|
-
const record = {
|
|
658
|
-
pid: process.pid,
|
|
659
|
-
startedAt: processStartedAt(),
|
|
660
|
-
runtimeRoot: args.runtimeRoot,
|
|
661
|
-
at: Date.now(),
|
|
662
|
-
...args.label ? { label: args.label } : {}
|
|
663
|
-
};
|
|
664
|
-
await writeJsonAtomic(file, record);
|
|
665
|
-
let released = false;
|
|
666
|
-
return {
|
|
667
|
-
release: async () => {
|
|
668
|
-
if (released) return;
|
|
669
|
-
released = true;
|
|
670
|
-
await rm2(file, { force: true }).catch(() => {
|
|
671
|
-
});
|
|
672
|
-
}
|
|
673
|
-
};
|
|
674
|
-
}
|
|
675
|
-
async function runtimeUseState(args) {
|
|
676
|
-
const dir = join2(installRootOf(args.key), USE_DIR);
|
|
677
|
-
let entries;
|
|
678
|
-
try {
|
|
679
|
-
entries = await readdir(dir);
|
|
680
|
-
} catch {
|
|
681
|
-
return { busy: false, holders: [] };
|
|
682
|
-
}
|
|
683
|
-
const holders = [];
|
|
684
|
-
for (const entry of entries) {
|
|
685
|
-
if (!entry.endsWith(".json")) continue;
|
|
686
|
-
const file = join2(dir, entry);
|
|
687
|
-
const record = await readJson(file);
|
|
688
|
-
if (record === null) {
|
|
689
|
-
continue;
|
|
690
|
-
}
|
|
691
|
-
if (record.runtimeRoot !== args.runtimeRoot) continue;
|
|
692
|
-
if (ownerProvablyGone({ ownerPid: record.pid, ownerStartedAt: record.startedAt })) {
|
|
693
|
-
await rm2(file, { force: true }).catch(() => {
|
|
694
|
-
});
|
|
695
|
-
continue;
|
|
696
|
-
}
|
|
697
|
-
holders.push(record.pid);
|
|
698
|
-
}
|
|
699
|
-
return { busy: holders.length > 0, holders };
|
|
700
|
-
}
|
|
701
|
-
async function claimStagingDirectory(args) {
|
|
702
|
-
await writeJsonAtomic(join2(args.staging, STAGING_OWNER_FILE), {
|
|
703
|
-
pid: process.pid,
|
|
704
|
-
startedAt: processStartedAt(),
|
|
705
|
-
attemptId: args.attemptId,
|
|
706
|
-
at: Date.now()
|
|
707
|
-
});
|
|
708
|
-
}
|
|
709
|
-
async function sweepAbandonedStaging(key) {
|
|
710
|
-
const root = installRootOf(key);
|
|
711
|
-
let entries;
|
|
712
|
-
try {
|
|
713
|
-
entries = await readdir(root);
|
|
714
|
-
} catch {
|
|
715
|
-
return { removed: 0, left: 0 };
|
|
716
|
-
}
|
|
717
|
-
let removed = 0;
|
|
718
|
-
let left = 0;
|
|
719
|
-
for (const entry of entries) {
|
|
720
|
-
if (!entry.startsWith(STAGING_PREFIX)) continue;
|
|
721
|
-
const path = join2(root, entry);
|
|
722
|
-
const owner = await readJson(join2(path, STAGING_OWNER_FILE));
|
|
723
|
-
if (owner === null) {
|
|
724
|
-
left += 1;
|
|
725
|
-
continue;
|
|
726
|
-
}
|
|
727
|
-
if (!ownerProvablyGone({ ownerPid: owner.pid, ownerStartedAt: owner.startedAt })) {
|
|
728
|
-
left += 1;
|
|
729
|
-
continue;
|
|
730
|
-
}
|
|
731
|
-
await rm2(path, { recursive: true, force: true }).catch(() => {
|
|
732
|
-
});
|
|
733
|
-
removed += 1;
|
|
734
|
-
}
|
|
735
|
-
if (removed > 0 || left > 0) {
|
|
736
|
-
logger.debug("[local-harness] staging sweep", { removed, left });
|
|
737
|
-
}
|
|
738
|
-
return { removed, left };
|
|
739
|
-
}
|
|
740
|
-
async function recoverInterruptedActivation(args) {
|
|
741
|
-
const previous = `${args.versionRoot}${PREVIOUS_SUFFIX}`;
|
|
742
|
-
const hasPrevious = await stat2(previous).then(
|
|
743
|
-
(info) => info.isDirectory(),
|
|
744
|
-
() => false
|
|
745
|
-
);
|
|
746
|
-
if (!hasPrevious) return false;
|
|
747
|
-
return lockFor(args.key)(async () => {
|
|
748
|
-
const current = await stat2(args.versionRoot).then(
|
|
749
|
-
(info) => info.isDirectory(),
|
|
750
|
-
() => false
|
|
751
|
-
);
|
|
752
|
-
if (current) {
|
|
753
|
-
await rm2(previous, { recursive: true, force: true }).catch(() => {
|
|
754
|
-
});
|
|
755
|
-
return false;
|
|
756
|
-
}
|
|
757
|
-
await rename(previous, args.versionRoot);
|
|
758
|
-
logger.warn("[local-harness] restored a runtime after an interrupted activation", {
|
|
759
|
-
packVersion: args.key.packVersion
|
|
760
|
-
});
|
|
761
|
-
return true;
|
|
762
|
-
});
|
|
763
|
-
}
|
|
764
|
-
var PREVIOUS_SUFFIX = ".mcpjam-previous";
|
|
765
|
-
function withRuntimeLifecycleLock(key, operation) {
|
|
766
|
-
return lockFor(key)(operation);
|
|
767
|
-
}
|
|
768
|
-
|
|
769
|
-
// server/utils/harness/local/runtime-install.ts
|
|
770
|
-
import { createHash as createHash2, randomUUID as randomUUID3 } from "crypto";
|
|
771
|
-
import { createReadStream, createWriteStream } from "fs";
|
|
772
|
-
import {
|
|
773
|
-
mkdir as mkdir3,
|
|
774
|
-
readdir as readdir4,
|
|
775
|
-
readFile as readFile5,
|
|
776
|
-
rename as rename2,
|
|
777
|
-
rm as rm3,
|
|
778
|
-
stat as stat4,
|
|
779
|
-
writeFile as writeFile3
|
|
780
|
-
} from "fs/promises";
|
|
781
|
-
import { homedir } from "os";
|
|
782
|
-
import { basename, join as join5 } from "path";
|
|
783
|
-
import { pipeline } from "stream/promises";
|
|
784
|
-
import { Readable } from "stream";
|
|
785
|
-
import { x as extractTar } from "tar";
|
|
786
|
-
|
|
787
|
-
// server/utils/harness/local/pack-digests.generated.ts
|
|
788
|
-
var PACK_TREE_DIGESTS = {
|
|
789
|
-
"claude-code": {},
|
|
790
|
-
codex: {}
|
|
791
|
-
};
|
|
792
|
-
var PACK_RECORDS = {
|
|
793
|
-
"claude-code": {},
|
|
794
|
-
codex: {}
|
|
795
|
-
};
|
|
796
|
-
var EXPECTED_PACK_VERSION = "";
|
|
797
|
-
|
|
798
|
-
// server/utils/harness/local/pack-signing-key.ts
|
|
799
|
-
import { createPublicKey, verify as edVerify } from "crypto";
|
|
800
|
-
var PACK_SIGNING_KEYS = [
|
|
801
|
-
{
|
|
802
|
-
// Rotated before the first pack publication on 2026-09-28. The private
|
|
803
|
-
// key was uploaded directly to the protected release environment; no
|
|
804
|
-
// file or repository-level secret retains it. Recovery is rotation.
|
|
805
|
-
keyId: "pack-2026-09-28",
|
|
806
|
-
publicKeyPem: `-----BEGIN PUBLIC KEY-----
|
|
807
|
-
MCowBQYDK2VwAyEA/8fkvTTgyzjmmlLmN4veODTVpexBi4Ib6SGVq8xmyTs=
|
|
808
|
-
-----END PUBLIC KEY-----
|
|
809
|
-
`
|
|
810
|
-
}
|
|
811
|
-
];
|
|
812
|
-
function verifyPackManifestSignature(manifestBytes, signatureBase64, keys = PACK_SIGNING_KEYS) {
|
|
813
|
-
if (keys.length === 0) {
|
|
814
|
-
return {
|
|
815
|
-
ok: false,
|
|
816
|
-
reason: "no-keys",
|
|
817
|
-
message: "this Inspector build carries no runtime pack signing key, so it cannot verify that a downloaded pack came from MCPJam. Packs are installable from a local path for development only."
|
|
818
|
-
};
|
|
819
|
-
}
|
|
820
|
-
let signature;
|
|
821
|
-
try {
|
|
822
|
-
signature = Buffer.from(signatureBase64.trim(), "base64");
|
|
823
|
-
if (signature.length === 0) throw new Error("empty");
|
|
824
|
-
} catch {
|
|
825
|
-
return {
|
|
826
|
-
ok: false,
|
|
827
|
-
reason: "malformed",
|
|
828
|
-
message: "the pack manifest signature is not valid base64"
|
|
829
|
-
};
|
|
830
|
-
}
|
|
831
|
-
for (const key of keys) {
|
|
832
|
-
try {
|
|
833
|
-
const publicKey = createPublicKey(key.publicKeyPem);
|
|
834
|
-
if (edVerify(null, manifestBytes, publicKey, signature)) {
|
|
835
|
-
return { ok: true, keyId: key.keyId };
|
|
836
|
-
}
|
|
837
|
-
} catch {
|
|
838
|
-
continue;
|
|
839
|
-
}
|
|
840
|
-
}
|
|
841
|
-
return {
|
|
842
|
-
ok: false,
|
|
843
|
-
reason: "bad-signature",
|
|
844
|
-
message: "the runtime pack manifest is not signed by any key this Inspector trusts, so the pack is refused"
|
|
845
|
-
};
|
|
846
|
-
}
|
|
847
|
-
|
|
848
|
-
// server/utils/harness/local/runtime-identity.ts
|
|
849
|
-
import { createHash } from "crypto";
|
|
850
|
-
import { execFile as execFile2 } from "child_process";
|
|
851
|
-
import { readdir as readdir3, readFile as readFile4, realpath, stat as stat3 } from "fs/promises";
|
|
852
|
-
import { dirname, isAbsolute, join as join4, normalize, relative, sep } from "path";
|
|
853
|
-
|
|
854
|
-
// server/utils/harness/local/process-identity.ts
|
|
855
|
-
import { execFile, spawn } from "child_process";
|
|
856
|
-
import { readdir as readdir2, readFile as readFile3 } from "fs/promises";
|
|
857
|
-
import { join as join3 } from "path";
|
|
858
|
-
var PS_TIMEOUT_MS = 3e3;
|
|
859
|
-
function parseLinuxProcStat(raw) {
|
|
860
|
-
const close = raw.lastIndexOf(")");
|
|
861
|
-
if (close === -1) return null;
|
|
862
|
-
const fields = raw.slice(close + 2).split(" ");
|
|
863
|
-
const state = fields[0];
|
|
864
|
-
const starttime = fields[19];
|
|
865
|
-
if (!state || !/^[A-Za-z]$/.test(state)) return null;
|
|
866
|
-
if (!starttime || !/^\d+$/.test(starttime)) return null;
|
|
867
|
-
return { state, starttime };
|
|
868
|
-
}
|
|
869
|
-
function isDeadState(state) {
|
|
870
|
-
return state === "Z" || state === "X" || state === "x";
|
|
871
|
-
}
|
|
872
|
-
async function probeLinux(pid) {
|
|
873
|
-
let raw;
|
|
874
|
-
try {
|
|
875
|
-
raw = await readFile3(`/proc/${pid}/stat`, "utf8");
|
|
876
|
-
} catch (error) {
|
|
877
|
-
const code = error.code;
|
|
878
|
-
if (code === "ENOENT" || code === "ESRCH") return { state: "gone" };
|
|
879
|
-
return {
|
|
880
|
-
state: "unknown",
|
|
881
|
-
reason: `/proc read failed (${code ?? "unknown"})`
|
|
882
|
-
};
|
|
883
|
-
}
|
|
884
|
-
const parsed = parseLinuxProcStat(raw);
|
|
885
|
-
if (parsed === null) {
|
|
886
|
-
return { state: "unknown", reason: "unparseable /proc stat line" };
|
|
887
|
-
}
|
|
888
|
-
if (isDeadState(parsed.state)) return { state: "gone" };
|
|
889
|
-
return { state: "alive", identity: `linux:${parsed.starttime}` };
|
|
890
|
-
}
|
|
891
|
-
function parseDarwinPsLine(raw) {
|
|
892
|
-
const line = raw.trim();
|
|
893
|
-
if (line.length === 0) return null;
|
|
894
|
-
const match = /^(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+([\s\S]+)$/.exec(line);
|
|
895
|
-
if (match === null) return null;
|
|
896
|
-
const state = match[1];
|
|
897
|
-
const lstart = [match[2], match[3], match[4], match[5], match[6]].join(" ");
|
|
898
|
-
const command = match[7];
|
|
899
|
-
return { state, lstart, command };
|
|
900
|
-
}
|
|
901
|
-
async function probeDarwin(pid) {
|
|
902
|
-
const result = await new Promise((resolve) => {
|
|
903
|
-
execFile(
|
|
904
|
-
"/bin/ps",
|
|
905
|
-
["-o", "state=,lstart=,command=", "-p", String(pid)],
|
|
906
|
-
{
|
|
907
|
-
timeout: PS_TIMEOUT_MS,
|
|
908
|
-
maxBuffer: 16 * 1024,
|
|
909
|
-
encoding: "utf8",
|
|
910
|
-
env: {}
|
|
911
|
-
},
|
|
912
|
-
(error, out) => {
|
|
913
|
-
if (!error) {
|
|
914
|
-
resolve({ ok: true, stdout: typeof out === "string" ? out : "" });
|
|
915
|
-
return;
|
|
916
|
-
}
|
|
917
|
-
const err = error;
|
|
918
|
-
resolve({
|
|
919
|
-
ok: false,
|
|
920
|
-
// `ps` exits 1 when no process matches — that IS an answer. A kill
|
|
921
|
-
// (timeout) or a spawn failure is not.
|
|
922
|
-
exitCode: typeof err.code === "number" ? err.code : null,
|
|
923
|
-
reason: err.killed ? "ps timed out" : `ps failed (${String(err.code ?? "unknown")})`
|
|
924
|
-
});
|
|
925
|
-
}
|
|
926
|
-
);
|
|
927
|
-
});
|
|
928
|
-
if (!result.ok) {
|
|
929
|
-
if (result.exitCode === 1) return { state: "gone" };
|
|
930
|
-
return { state: "unknown", reason: result.reason };
|
|
931
|
-
}
|
|
932
|
-
const parsed = parseDarwinPsLine(result.stdout);
|
|
933
|
-
if (parsed === null) {
|
|
934
|
-
return result.stdout.trim().length === 0 ? { state: "gone" } : { state: "unknown", reason: "unparseable ps output" };
|
|
935
|
-
}
|
|
936
|
-
if (isDeadState(parsed.state.charAt(0))) return { state: "gone" };
|
|
937
|
-
return {
|
|
938
|
-
state: "alive",
|
|
939
|
-
identity: `darwin:${parsed.lstart}|${parsed.command}`
|
|
940
|
-
};
|
|
941
|
-
}
|
|
942
|
-
var WIN32_PROBE_TIMEOUT_MS = 15e3;
|
|
943
|
-
function win32SystemRoot() {
|
|
944
|
-
return process.env.SYSTEMROOT ?? process.env.WINDIR ?? "C:\\Windows";
|
|
945
|
-
}
|
|
946
|
-
function win32PowerShellPath() {
|
|
947
|
-
return join3(
|
|
948
|
-
win32SystemRoot(),
|
|
949
|
-
"System32",
|
|
950
|
-
"WindowsPowerShell",
|
|
951
|
-
"v1.0",
|
|
952
|
-
"powershell.exe"
|
|
953
|
-
);
|
|
954
|
-
}
|
|
955
|
-
function parseWin32ProbeLine(raw) {
|
|
956
|
-
const line = raw.trim();
|
|
957
|
-
const match = /^(\d+)\|(.+)$/.exec(line);
|
|
958
|
-
if (match === null) return null;
|
|
959
|
-
return { fileTime: match[1], name: match[2] };
|
|
960
|
-
}
|
|
961
|
-
async function probeWin32(pid) {
|
|
962
|
-
try {
|
|
963
|
-
process.kill(pid, 0);
|
|
964
|
-
} catch (error) {
|
|
965
|
-
const code = error.code;
|
|
966
|
-
if (code === "ESRCH") return { state: "gone" };
|
|
967
|
-
if (code !== "EPERM") {
|
|
968
|
-
return {
|
|
969
|
-
state: "unknown",
|
|
970
|
-
reason: `kill(0) failed (${code ?? "unknown"})`
|
|
971
|
-
};
|
|
972
|
-
}
|
|
973
|
-
}
|
|
974
|
-
const script = [
|
|
975
|
-
`$p = Get-Process -Id ${pid} -ErrorAction SilentlyContinue`,
|
|
976
|
-
"if ($null -eq $p) { exit 1 }",
|
|
977
|
-
"try { $t = $p.StartTime.ToFileTimeUtc() } catch { exit 3 }",
|
|
978
|
-
"Write-Output ('{0}|{1}' -f $t, $p.ProcessName)"
|
|
979
|
-
].join("; ");
|
|
980
|
-
const result = await new Promise((resolve) => {
|
|
981
|
-
let settled = false;
|
|
982
|
-
let timer;
|
|
983
|
-
const done = (value) => {
|
|
984
|
-
if (settled) return;
|
|
985
|
-
settled = true;
|
|
986
|
-
if (timer !== void 0) clearTimeout(timer);
|
|
987
|
-
resolve(value);
|
|
988
|
-
};
|
|
989
|
-
let child;
|
|
990
|
-
try {
|
|
991
|
-
child = spawn(
|
|
992
|
-
win32PowerShellPath(),
|
|
993
|
-
[
|
|
994
|
-
"-NoProfile",
|
|
995
|
-
"-NonInteractive",
|
|
996
|
-
"-InputFormat",
|
|
997
|
-
"None",
|
|
998
|
-
"-ExecutionPolicy",
|
|
999
|
-
"Bypass",
|
|
1000
|
-
"-Command",
|
|
1001
|
-
script
|
|
1002
|
-
],
|
|
1003
|
-
{ stdio: ["ignore", "pipe", "pipe"], env: process.env, windowsHide: true }
|
|
1004
|
-
);
|
|
1005
|
-
} catch (error) {
|
|
1006
|
-
done({
|
|
1007
|
-
ok: false,
|
|
1008
|
-
exitCode: null,
|
|
1009
|
-
reason: `PowerShell failed to start (${String(
|
|
1010
|
-
error.code ?? "unknown"
|
|
1011
|
-
)})`
|
|
1012
|
-
});
|
|
1013
|
-
return;
|
|
1014
|
-
}
|
|
1015
|
-
let stdout = "";
|
|
1016
|
-
child.stdout?.setEncoding("utf8");
|
|
1017
|
-
child.stdout?.on("data", (chunk) => {
|
|
1018
|
-
if (stdout.length < 16 * 1024) stdout += chunk;
|
|
1019
|
-
});
|
|
1020
|
-
child.stderr?.resume();
|
|
1021
|
-
timer = setTimeout(() => {
|
|
1022
|
-
try {
|
|
1023
|
-
child.kill();
|
|
1024
|
-
} catch {
|
|
1025
|
-
}
|
|
1026
|
-
done({ ok: false, exitCode: null, reason: "Get-Process timed out" });
|
|
1027
|
-
}, WIN32_PROBE_TIMEOUT_MS);
|
|
1028
|
-
child.on(
|
|
1029
|
-
"error",
|
|
1030
|
-
(error) => done({
|
|
1031
|
-
ok: false,
|
|
1032
|
-
exitCode: null,
|
|
1033
|
-
reason: `PowerShell failed (${String(error.code ?? "unknown")})`
|
|
1034
|
-
})
|
|
1035
|
-
);
|
|
1036
|
-
child.on("close", (code) => {
|
|
1037
|
-
if (code === 0) done({ ok: true, stdout });
|
|
1038
|
-
else done({ ok: false, exitCode: code, reason: `Get-Process exited ${code}` });
|
|
1039
|
-
});
|
|
1040
|
-
});
|
|
1041
|
-
if (!result.ok) {
|
|
1042
|
-
if (result.exitCode === 1) return { state: "gone" };
|
|
1043
|
-
return { state: "unknown", reason: result.reason };
|
|
1044
|
-
}
|
|
1045
|
-
const parsed = parseWin32ProbeLine(result.stdout);
|
|
1046
|
-
if (parsed === null) {
|
|
1047
|
-
return { state: "unknown", reason: "unparseable Get-Process output" };
|
|
1048
|
-
}
|
|
1049
|
-
return {
|
|
1050
|
-
state: "alive",
|
|
1051
|
-
identity: `win32:${parsed.fileTime}|${parsed.name}`
|
|
1052
|
-
};
|
|
1053
|
-
}
|
|
1054
|
-
async function probeProcess(pid, platform = process.platform) {
|
|
1055
|
-
if (!Number.isInteger(pid) || pid <= 0) {
|
|
1056
|
-
return { state: "unknown", reason: "implausible pid" };
|
|
1057
|
-
}
|
|
1058
|
-
if (platform === "linux") return probeLinux(pid);
|
|
1059
|
-
if (platform === "darwin") return probeDarwin(pid);
|
|
1060
|
-
if (platform === "win32") return probeWin32(pid);
|
|
1061
|
-
return { state: "unknown", reason: `no liveness primitive on ${platform}` };
|
|
1062
|
-
}
|
|
1063
|
-
async function readProcessBirthIdentity(pid, platform = process.platform) {
|
|
1064
|
-
const probe = await probeProcess(pid, platform);
|
|
1065
|
-
return probe.state === "alive" ? probe.identity : null;
|
|
1066
|
-
}
|
|
1067
|
-
function supportsOwnershipProof(platform = process.platform) {
|
|
1068
|
-
if (platform === "linux" || platform === "darwin") return true;
|
|
1069
|
-
if (platform === "win32") return windowsJobLauncherVerified;
|
|
1070
|
-
return false;
|
|
1071
|
-
}
|
|
1072
|
-
var windowsJobLauncherVerified = false;
|
|
1073
|
-
function setWindowsJobLauncherVerified(verified) {
|
|
1074
|
-
windowsJobLauncherVerified = verified;
|
|
1075
|
-
}
|
|
1076
|
-
function sameBirthIdentity(recorded, current) {
|
|
1077
|
-
if (recorded === current) return true;
|
|
1078
|
-
const r = /^darwin:([^|]+)\|([\s\S]*)$/.exec(recorded);
|
|
1079
|
-
const c = /^darwin:([^|]+)\|([\s\S]*)$/.exec(current);
|
|
1080
|
-
if (r === null || c === null) return false;
|
|
1081
|
-
return r[1] === c[1] && /^\([^()]+\)$/.test(c[2]);
|
|
1082
|
-
}
|
|
1083
|
-
async function listGroupMembers(pgid, platform = process.platform) {
|
|
1084
|
-
let pids = [];
|
|
1085
|
-
if (platform === "darwin") {
|
|
1086
|
-
const out = await new Promise((resolve) => {
|
|
1087
|
-
execFile(
|
|
1088
|
-
"/bin/ps",
|
|
1089
|
-
["-o", "pid=,state=", "-g", String(pgid)],
|
|
1090
|
-
{ timeout: PS_TIMEOUT_MS, maxBuffer: 64 * 1024, encoding: "utf8", env: {} },
|
|
1091
|
-
(error, stdout) => resolve(error ? error.code === 1 ? "" : null : String(stdout))
|
|
1092
|
-
);
|
|
1093
|
-
});
|
|
1094
|
-
if (out === null) return null;
|
|
1095
|
-
pids = out.split("\n").map((l) => l.trim().split(/\s+/)).filter((f) => f.length >= 2 && /^\d+$/.test(f[0]) && !isDeadState(f[1].charAt(0))).map((f) => Number(f[0]));
|
|
1096
|
-
} else if (platform === "linux") {
|
|
1097
|
-
let entries;
|
|
1098
|
-
try {
|
|
1099
|
-
entries = await readdir2("/proc");
|
|
1100
|
-
} catch {
|
|
1101
|
-
return null;
|
|
1102
|
-
}
|
|
1103
|
-
for (const entry of entries) {
|
|
1104
|
-
if (!/^\d+$/.test(entry)) continue;
|
|
1105
|
-
let raw;
|
|
1106
|
-
try {
|
|
1107
|
-
raw = await readFile3(`/proc/${entry}/stat`, "utf8");
|
|
1108
|
-
} catch {
|
|
1109
|
-
continue;
|
|
1110
|
-
}
|
|
1111
|
-
const parsed = parseProcStatGroup(raw);
|
|
1112
|
-
if (parsed !== null && parsed.pgrp === pgid && !isDeadState(parsed.state.charAt(0))) pids.push(Number(entry));
|
|
1113
|
-
}
|
|
1114
|
-
} else {
|
|
1115
|
-
return null;
|
|
1116
|
-
}
|
|
1117
|
-
const members = [];
|
|
1118
|
-
for (const pid of pids) {
|
|
1119
|
-
if (pid === pgid) continue;
|
|
1120
|
-
const identity = await readProcessBirthIdentity(pid, platform);
|
|
1121
|
-
if (identity !== null) members.push({ pid, identity });
|
|
1122
|
-
}
|
|
1123
|
-
return members;
|
|
1124
|
-
}
|
|
1125
|
-
async function terminateOwnedProcess(args) {
|
|
1126
|
-
const platform = args.platform ?? process.platform;
|
|
1127
|
-
const initial = await probeProcess(args.pid, platform);
|
|
1128
|
-
if (initial.state === "gone") return "already-gone";
|
|
1129
|
-
if (initial.state === "unknown") return "unknown";
|
|
1130
|
-
if (!sameBirthIdentity(args.identity, initial.identity)) return "not-owned";
|
|
1131
|
-
const waitGone = async (ms) => {
|
|
1132
|
-
const until = Date.now() + ms;
|
|
1133
|
-
while (Date.now() < until) {
|
|
1134
|
-
const p = await probeProcess(args.pid, platform);
|
|
1135
|
-
if (p.state === "gone") return true;
|
|
1136
|
-
await new Promise((r) => setTimeout(r, 50));
|
|
1137
|
-
}
|
|
1138
|
-
return false;
|
|
1139
|
-
};
|
|
1140
|
-
try {
|
|
1141
|
-
process.kill(args.pid, "SIGTERM");
|
|
1142
|
-
} catch {
|
|
1143
|
-
return "already-gone";
|
|
1144
|
-
}
|
|
1145
|
-
if (await waitGone(args.graceMs)) return "graceful";
|
|
1146
|
-
const again = await probeProcess(args.pid, platform);
|
|
1147
|
-
if (again.state === "gone") return "graceful";
|
|
1148
|
-
if (again.state === "unknown") return "unknown";
|
|
1149
|
-
if (!sameBirthIdentity(args.identity, again.identity)) return "not-owned";
|
|
1150
|
-
try {
|
|
1151
|
-
process.kill(args.pid, "SIGKILL");
|
|
1152
|
-
} catch {
|
|
1153
|
-
return "graceful";
|
|
1154
|
-
}
|
|
1155
|
-
return await waitGone(500) ? "forced" : "escaped";
|
|
1156
|
-
}
|
|
1157
|
-
async function probeProcessGroup(pid, platform = process.platform) {
|
|
1158
|
-
if (!Number.isInteger(pid) || pid <= 0) return "unknown";
|
|
1159
|
-
if (platform === "linux") return probeLinuxGroup(pid);
|
|
1160
|
-
if (platform === "darwin") return probeDarwinGroup(pid);
|
|
1161
|
-
if (platform === "win32") {
|
|
1162
|
-
const root = await probeProcess(pid, platform);
|
|
1163
|
-
if (root.state === "gone") return "empty";
|
|
1164
|
-
if (root.state === "alive") return "live";
|
|
1165
|
-
return "unknown";
|
|
1166
|
-
}
|
|
1167
|
-
return "unknown";
|
|
1168
|
-
}
|
|
1169
|
-
async function readProcessGroupId(pid, platform = process.platform) {
|
|
1170
|
-
if (!Number.isInteger(pid) || pid <= 0) return null;
|
|
1171
|
-
if (platform === "linux") {
|
|
1172
|
-
try {
|
|
1173
|
-
const raw = await readFile3(`/proc/${pid}/stat`, "utf8");
|
|
1174
|
-
return parseProcStatGroup(raw)?.pgrp ?? null;
|
|
1175
|
-
} catch {
|
|
1176
|
-
return null;
|
|
1177
|
-
}
|
|
1178
|
-
}
|
|
1179
|
-
if (platform === "darwin") {
|
|
1180
|
-
return new Promise((resolvePromise) => {
|
|
1181
|
-
execFile(
|
|
1182
|
-
"/bin/ps",
|
|
1183
|
-
["-o", "pgid=", "-p", String(pid)],
|
|
1184
|
-
{
|
|
1185
|
-
timeout: PS_TIMEOUT_MS,
|
|
1186
|
-
maxBuffer: 4 * 1024,
|
|
1187
|
-
encoding: "utf8",
|
|
1188
|
-
env: {}
|
|
1189
|
-
},
|
|
1190
|
-
(error, stdout) => {
|
|
1191
|
-
if (error) {
|
|
1192
|
-
resolvePromise(null);
|
|
1193
|
-
return;
|
|
1194
|
-
}
|
|
1195
|
-
const parsed = Number(String(stdout).trim());
|
|
1196
|
-
resolvePromise(Number.isInteger(parsed) && parsed > 0 ? parsed : null);
|
|
1197
|
-
}
|
|
1198
|
-
);
|
|
1199
|
-
});
|
|
1200
|
-
}
|
|
1201
|
-
return null;
|
|
1202
|
-
}
|
|
1203
|
-
function parseProcStatGroup(raw) {
|
|
1204
|
-
const close = raw.lastIndexOf(")");
|
|
1205
|
-
if (close === -1) return null;
|
|
1206
|
-
const fields = raw.slice(close + 1).trim().split(/\s+/);
|
|
1207
|
-
const state = fields[0];
|
|
1208
|
-
const pgrp = Number(fields[2]);
|
|
1209
|
-
if (state === void 0 || !Number.isInteger(pgrp)) return null;
|
|
1210
|
-
return { state, pgrp };
|
|
1211
|
-
}
|
|
1212
|
-
async function probeLinuxGroup(pgid) {
|
|
1213
|
-
let entries;
|
|
1214
|
-
try {
|
|
1215
|
-
entries = await readdir2("/proc");
|
|
1216
|
-
} catch {
|
|
1217
|
-
return "unknown";
|
|
1218
|
-
}
|
|
1219
|
-
let blind = false;
|
|
1220
|
-
for (const entry of entries) {
|
|
1221
|
-
if (!/^\d+$/.test(entry)) continue;
|
|
1222
|
-
let raw;
|
|
1223
|
-
try {
|
|
1224
|
-
raw = await readFile3(`/proc/${entry}/stat`, "utf8");
|
|
1225
|
-
} catch (error) {
|
|
1226
|
-
const code = error.code;
|
|
1227
|
-
if (code !== "ENOENT" && code !== "ESRCH") blind = true;
|
|
1228
|
-
continue;
|
|
1229
|
-
}
|
|
1230
|
-
const parsed = parseProcStatGroup(raw);
|
|
1231
|
-
if (parsed === null) {
|
|
1232
|
-
blind = true;
|
|
1233
|
-
continue;
|
|
1234
|
-
}
|
|
1235
|
-
if (parsed.pgrp !== pgid) continue;
|
|
1236
|
-
if (!isDeadState(parsed.state.charAt(0))) return "live";
|
|
1237
|
-
}
|
|
1238
|
-
return blind ? "unknown" : "empty";
|
|
1239
|
-
}
|
|
1240
|
-
async function probeDarwinGroup(pgid) {
|
|
1241
|
-
const result = await new Promise((resolve) => {
|
|
1242
|
-
execFile(
|
|
1243
|
-
"/bin/ps",
|
|
1244
|
-
["-o", "state=", "-g", String(pgid)],
|
|
1245
|
-
{
|
|
1246
|
-
timeout: PS_TIMEOUT_MS,
|
|
1247
|
-
maxBuffer: 64 * 1024,
|
|
1248
|
-
encoding: "utf8",
|
|
1249
|
-
env: {}
|
|
1250
|
-
},
|
|
1251
|
-
(error, out) => {
|
|
1252
|
-
if (!error) {
|
|
1253
|
-
resolve({ ok: true, stdout: typeof out === "string" ? out : "" });
|
|
1254
|
-
return;
|
|
1255
|
-
}
|
|
1256
|
-
const err = error;
|
|
1257
|
-
resolve({ ok: false, empty: err.killed !== true && err.code === 1 });
|
|
1258
|
-
}
|
|
1259
|
-
);
|
|
1260
|
-
});
|
|
1261
|
-
if (!result.ok) return result.empty ? "empty" : "unknown";
|
|
1262
|
-
const states = result.stdout.split("\n").map((line) => line.trim()).filter((line) => line.length > 0);
|
|
1263
|
-
if (states.some((state) => !isDeadState(state.charAt(0)))) return "live";
|
|
1264
|
-
return "empty";
|
|
1265
|
-
}
|
|
1266
|
-
function signalProcessGroup(pid, signal, platform = process.platform) {
|
|
1267
|
-
if (!Number.isInteger(pid) || pid <= 0) return false;
|
|
1268
|
-
try {
|
|
1269
|
-
if (platform === "win32") {
|
|
1270
|
-
process.kill(pid, signal);
|
|
1271
|
-
return true;
|
|
1272
|
-
}
|
|
1273
|
-
process.kill(-pid, signal);
|
|
1274
|
-
return true;
|
|
1275
|
-
} catch (error) {
|
|
1276
|
-
if (error.code === "ESRCH") return true;
|
|
1277
|
-
return false;
|
|
1278
|
-
}
|
|
1279
|
-
}
|
|
1280
|
-
async function terminateOwnedProcessGroup(args) {
|
|
1281
|
-
const platform = args.platform ?? process.platform;
|
|
1282
|
-
const pollMs = args.pollMs ?? 50;
|
|
1283
|
-
const settleGroup = async (goneOutcome, anchored) => {
|
|
1284
|
-
const probeGroup = args.probeGroup ?? probeProcessGroup;
|
|
1285
|
-
const before = await probeGroup(args.pid, platform);
|
|
1286
|
-
if (before === "empty") return { outcome: goneOutcome };
|
|
1287
|
-
if (before === "unknown") {
|
|
1288
|
-
return {
|
|
1289
|
-
outcome: "unknown",
|
|
1290
|
-
reason: "the process group could not be enumerated, so a survivor could be neither ruled out nor signalled without risking a reused group id"
|
|
1291
|
-
};
|
|
1292
|
-
}
|
|
1293
|
-
if (!anchored) {
|
|
1294
|
-
return {
|
|
1295
|
-
outcome: "unknown",
|
|
1296
|
-
reason: "a live process group carries this id, but the root was already gone when the stop began, so the group cannot be tied to this tree"
|
|
1297
|
-
};
|
|
1298
|
-
}
|
|
1299
|
-
signalProcessGroup(args.pid, "SIGKILL", platform);
|
|
1300
|
-
await new Promise((r) => setTimeout(r, Math.min(args.graceMs, 500)));
|
|
1301
|
-
const after = await probeGroup(args.pid, platform);
|
|
1302
|
-
if (after === "empty") return { outcome: "forced" };
|
|
1303
|
-
if (after === "unknown") {
|
|
1304
|
-
return {
|
|
1305
|
-
outcome: "unknown",
|
|
1306
|
-
reason: "the process group could not be enumerated after SIGKILL"
|
|
1307
|
-
};
|
|
1308
|
-
}
|
|
1309
|
-
return { outcome: "escaped" };
|
|
1310
|
-
};
|
|
1311
|
-
const initial = await probeProcess(args.pid, platform);
|
|
1312
|
-
if (initial.state === "gone") return settleGroup("already-gone", false);
|
|
1313
|
-
if (initial.state === "unknown") {
|
|
1314
|
-
return { outcome: "unknown", reason: initial.reason };
|
|
1315
|
-
}
|
|
1316
|
-
if (!sameBirthIdentity(args.birthIdentity, initial.identity)) {
|
|
1317
|
-
return { outcome: "not-owned" };
|
|
1318
|
-
}
|
|
1319
|
-
signalProcessGroup(args.pid, "SIGTERM", platform);
|
|
1320
|
-
const deadline = Date.now() + args.graceMs;
|
|
1321
|
-
while (Date.now() < deadline) {
|
|
1322
|
-
await new Promise((r) => setTimeout(r, pollMs));
|
|
1323
|
-
if ((await probeProcess(args.pid, platform)).state === "gone") {
|
|
1324
|
-
return settleGroup("graceful", true);
|
|
1325
|
-
}
|
|
1326
|
-
}
|
|
1327
|
-
const afterGrace = await probeProcess(args.pid, platform);
|
|
1328
|
-
if (afterGrace.state === "gone") return settleGroup("graceful", true);
|
|
1329
|
-
if (afterGrace.state === "unknown") {
|
|
1330
|
-
return { outcome: "unknown", reason: afterGrace.reason };
|
|
1331
|
-
}
|
|
1332
|
-
if (!sameBirthIdentity(args.birthIdentity, afterGrace.identity)) {
|
|
1333
|
-
return settleGroup("graceful", true);
|
|
1334
|
-
}
|
|
1335
|
-
signalProcessGroup(args.pid, "SIGKILL", platform);
|
|
1336
|
-
const killDeadline = Date.now() + Math.max(args.graceMs, 1e3);
|
|
1337
|
-
while (Date.now() < killDeadline) {
|
|
1338
|
-
await new Promise((r) => setTimeout(r, pollMs));
|
|
1339
|
-
if ((await probeProcess(args.pid, platform)).state === "gone") {
|
|
1340
|
-
return settleGroup("forced", true);
|
|
1341
|
-
}
|
|
1342
|
-
}
|
|
1343
|
-
const settled = await probeProcess(args.pid, platform);
|
|
1344
|
-
if (settled.state === "gone") return settleGroup("forced", true);
|
|
1345
|
-
if (settled.state === "unknown") {
|
|
1346
|
-
return { outcome: "unknown", reason: settled.reason };
|
|
1347
|
-
}
|
|
1348
|
-
return { outcome: "escaped" };
|
|
1349
|
-
}
|
|
1350
|
-
|
|
1351
|
-
// server/utils/harness/local/runtime-identity.ts
|
|
1352
|
-
var MAX_BUNDLE_FILES = 5e4;
|
|
1353
|
-
var MAX_BUNDLE_BYTES = 2 * 1024 * 1024 * 1024;
|
|
1354
|
-
var PROBE_TIMEOUT_MS = 5e3;
|
|
1355
|
-
var PROBE_MAX_BUFFER = 64 * 1024;
|
|
1356
|
-
async function computeTreeDigest(root) {
|
|
1357
|
-
return (await digestTreeWithSnapshot(root)).digest;
|
|
1358
|
-
}
|
|
1359
|
-
async function digestTreeWithSnapshot(root) {
|
|
1360
|
-
const hash = createHash("sha256");
|
|
1361
|
-
const entriesSnapshot = [];
|
|
1362
|
-
const executableDigests = {};
|
|
1363
|
-
let files = 0;
|
|
1364
|
-
let bytes = 0;
|
|
1365
|
-
const walk = async (dir) => {
|
|
1366
|
-
const entries = await readdir3(dir, { withFileTypes: true });
|
|
1367
|
-
entries.sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
|
|
1368
|
-
for (const entry of entries) {
|
|
1369
|
-
const full = join4(dir, entry.name);
|
|
1370
|
-
const rel = relative(root, full).split(sep).join("/");
|
|
1371
|
-
if (entry.isSymbolicLink()) {
|
|
1372
|
-
throw new Error(
|
|
1373
|
-
`managed runtime bundle contains a symlink at ${rel}; bundles are built as plain files so their digest describes exactly what runs`
|
|
1374
|
-
);
|
|
1375
|
-
}
|
|
1376
|
-
if (entry.isDirectory()) {
|
|
1377
|
-
hash.update(`d\0${rel}\0`);
|
|
1378
|
-
await walk(full);
|
|
1379
|
-
continue;
|
|
1380
|
-
}
|
|
1381
|
-
if (!entry.isFile()) {
|
|
1382
|
-
throw new Error(
|
|
1383
|
-
`managed runtime bundle contains a non-regular file at ${rel}`
|
|
1384
|
-
);
|
|
1385
|
-
}
|
|
1386
|
-
if (++files > MAX_BUNDLE_FILES) {
|
|
1387
|
-
throw new Error(
|
|
1388
|
-
"managed runtime bundle exceeds the file-count ceiling"
|
|
1389
|
-
);
|
|
1390
|
-
}
|
|
1391
|
-
const info = await stat3(full);
|
|
1392
|
-
bytes += info.size;
|
|
1393
|
-
if (bytes > MAX_BUNDLE_BYTES) {
|
|
1394
|
-
throw new Error("managed runtime bundle exceeds the size ceiling");
|
|
1395
|
-
}
|
|
1396
|
-
const content = await readFile4(full);
|
|
1397
|
-
const executable = (info.mode & 73) !== 0 ? "1" : "0";
|
|
1398
|
-
const contentDigest = createHash("sha256").update(content).digest();
|
|
1399
|
-
hash.update(`f\0${rel}\0${executable}\0${info.size}\0`);
|
|
1400
|
-
hash.update(contentDigest);
|
|
1401
|
-
entriesSnapshot.push({
|
|
1402
|
-
path: rel,
|
|
1403
|
-
size: info.size,
|
|
1404
|
-
mtimeMs: info.mtimeMs,
|
|
1405
|
-
ctimeMs: info.ctimeMs,
|
|
1406
|
-
ino: Number(info.ino),
|
|
1407
|
-
mode: info.mode
|
|
1408
|
-
});
|
|
1409
|
-
if (isBaselineHashed(rel)) {
|
|
1410
|
-
executableDigests[rel] = contentDigest.toString("hex");
|
|
1411
|
-
}
|
|
1412
|
-
}
|
|
1413
|
-
};
|
|
1414
|
-
await walk(root);
|
|
1415
|
-
return {
|
|
1416
|
-
root,
|
|
1417
|
-
digest: `sha256:${hash.digest("hex")}`,
|
|
1418
|
-
entries: entriesSnapshot,
|
|
1419
|
-
executableDigests
|
|
1420
|
-
};
|
|
1421
|
-
}
|
|
1422
|
-
var ALWAYS_REHASHED_RELATIVE_PATHS = [
|
|
1423
|
-
"launcher.mjs",
|
|
1424
|
-
"bridge.mjs"
|
|
1425
|
-
];
|
|
1426
|
-
var STRICT_REHASHED_PATH_PATTERNS = [
|
|
1427
|
-
/^bin\/node(\.exe)?$/,
|
|
1428
|
-
/(^|\/)claude-agent-sdk-[a-z0-9-]+\/(claude|claude\.exe)$/,
|
|
1429
|
-
/(^|\/)claude-code-[a-z0-9-]+\/(claude|claude\.exe)$/
|
|
1430
|
-
];
|
|
1431
|
-
function strictReverifyEnabled() {
|
|
1432
|
-
return process.env.MCPJAM_LOCAL_HARNESS_STRICT_REVERIFY === "true";
|
|
1433
|
-
}
|
|
1434
|
-
function isBaselineHashed(relativePath) {
|
|
1435
|
-
return ALWAYS_REHASHED_RELATIVE_PATHS.includes(relativePath) || STRICT_REHASHED_PATH_PATTERNS.some((pattern) => pattern.test(relativePath));
|
|
1436
|
-
}
|
|
1437
|
-
function isRehashedOnRevalidate(relativePath) {
|
|
1438
|
-
if (ALWAYS_REHASHED_RELATIVE_PATHS.includes(relativePath)) return true;
|
|
1439
|
-
return strictReverifyEnabled() && STRICT_REHASHED_PATH_PATTERNS.some((pattern) => pattern.test(relativePath));
|
|
1440
|
-
}
|
|
1441
|
-
var verifiedRuntimeCache = /* @__PURE__ */ new Map();
|
|
1442
|
-
var inFlightVerifications = /* @__PURE__ */ new Map();
|
|
1443
|
-
function verificationCacheKey(root, expectedDigest) {
|
|
1444
|
-
return `${root}\0${expectedDigest}`;
|
|
1445
|
-
}
|
|
1446
|
-
var cacheGeneration = 0;
|
|
1447
|
-
function clearRuntimeVerificationCache() {
|
|
1448
|
-
cacheGeneration += 1;
|
|
1449
|
-
verifiedRuntimeCache.clear();
|
|
1450
|
-
inFlightVerifications.clear();
|
|
1451
|
-
}
|
|
1452
|
-
async function verifyRuntime(root, expectedDigest) {
|
|
1453
|
-
const key = verificationCacheKey(root, expectedDigest);
|
|
1454
|
-
const cached = verifiedRuntimeCache.get(key);
|
|
1455
|
-
if (cached !== void 0) {
|
|
1456
|
-
return { ok: true, digest: cached.digest, snapshot: cached, cached: true };
|
|
1457
|
-
}
|
|
1458
|
-
const running = inFlightVerifications.get(key);
|
|
1459
|
-
if (running !== void 0) return running;
|
|
1460
|
-
const started = digestOnce(root, expectedDigest, key, cacheGeneration);
|
|
1461
|
-
inFlightVerifications.set(key, started);
|
|
1462
|
-
try {
|
|
1463
|
-
return await started;
|
|
1464
|
-
} finally {
|
|
1465
|
-
if (inFlightVerifications.get(key) === started) {
|
|
1466
|
-
inFlightVerifications.delete(key);
|
|
1467
|
-
}
|
|
1468
|
-
}
|
|
1469
|
-
}
|
|
1470
|
-
async function digestOnce(root, expectedDigest, key, generation) {
|
|
1471
|
-
let snapshot;
|
|
1472
|
-
try {
|
|
1473
|
-
snapshot = await digestTreeWithSnapshot(root);
|
|
1474
|
-
} catch (error) {
|
|
1475
|
-
return {
|
|
1476
|
-
ok: false,
|
|
1477
|
-
reason: "unreadable",
|
|
1478
|
-
message: error instanceof Error ? error.message : String(error)
|
|
1479
|
-
};
|
|
1480
|
-
}
|
|
1481
|
-
if (snapshot.digest !== expectedDigest) {
|
|
1482
|
-
return { ok: false, reason: "digest-mismatch", digest: snapshot.digest };
|
|
1483
|
-
}
|
|
1484
|
-
if (generation !== cacheGeneration) {
|
|
1485
|
-
return {
|
|
1486
|
-
ok: false,
|
|
1487
|
-
reason: "unreadable",
|
|
1488
|
-
message: "the runtime tree was replaced while it was being verified; verify again"
|
|
1489
|
-
};
|
|
1490
|
-
}
|
|
1491
|
-
verifiedRuntimeCache.set(key, snapshot);
|
|
1492
|
-
return { ok: true, digest: snapshot.digest, snapshot, cached: false };
|
|
1493
|
-
}
|
|
1494
|
-
function runtimeIdOf(parts) {
|
|
1495
|
-
return `rt_${createHash("sha256").update(parts.join("\0")).digest("hex").slice(0, 32)}`;
|
|
1496
|
-
}
|
|
1497
|
-
async function resolveManagedBundle(args) {
|
|
1498
|
-
const { manifest, runtimeRoot, platform } = args;
|
|
1499
|
-
if (manifest.runtime.source !== "managed-bundle") {
|
|
1500
|
-
return {
|
|
1501
|
-
ok: false,
|
|
1502
|
-
status: "bundle-absent",
|
|
1503
|
-
message: `${manifest.harnessId} is not configured for a managed bundle`
|
|
1504
|
-
};
|
|
1505
|
-
}
|
|
1506
|
-
const policy = manifest.runtime;
|
|
1507
|
-
const root = join4(runtimeRoot, policy.bundleName);
|
|
1508
|
-
let canonicalRoot;
|
|
1509
|
-
try {
|
|
1510
|
-
canonicalRoot = await realpath(root);
|
|
1511
|
-
const info = await stat3(canonicalRoot);
|
|
1512
|
-
if (!info.isDirectory()) throw new Error("not a directory");
|
|
1513
|
-
} catch {
|
|
1514
|
-
return {
|
|
1515
|
-
ok: false,
|
|
1516
|
-
status: "bundle-absent",
|
|
1517
|
-
message: `the ${manifest.harnessId} runtime bundle is not present at ${root}. It ships with the Inspector install; reinstall or run the setup step that downloads it. Nothing is installed while a session starts.`
|
|
1518
|
-
};
|
|
1519
|
-
}
|
|
1520
|
-
const arch = args.arch ?? process.arch;
|
|
1521
|
-
const target = localPackTarget(platform, arch);
|
|
1522
|
-
const expectedDigest = target === null ? void 0 : policy.bundleDigest[target];
|
|
1523
|
-
if (expectedDigest === void 0) {
|
|
1524
|
-
return {
|
|
1525
|
-
ok: false,
|
|
1526
|
-
status: "bundle-absent",
|
|
1527
|
-
// The TARGET, not just the OS: on a machine whose architecture nobody
|
|
1528
|
-
// builds for, "no pack for darwin" reads as a platform outage when the
|
|
1529
|
-
// real answer is "no pack for darwin-x64". A user comparing that against
|
|
1530
|
-
// the release assets needs the string that appears there.
|
|
1531
|
-
message: `no ${manifest.harnessId} runtime pack has been built for ${platform}-${arch}, so there is no digest to verify one against`
|
|
1532
|
-
};
|
|
1533
|
-
}
|
|
1534
|
-
const verification = await verifyRuntime(canonicalRoot, expectedDigest);
|
|
1535
|
-
if (!verification.ok && verification.reason === "unreadable") {
|
|
1536
|
-
return {
|
|
1537
|
-
ok: false,
|
|
1538
|
-
status: "bundle-corrupt",
|
|
1539
|
-
message: `the ${manifest.harnessId} runtime bundle could not be digested: ${verification.message}`
|
|
1540
|
-
};
|
|
1541
|
-
}
|
|
1542
|
-
if (!verification.ok) {
|
|
1543
|
-
return {
|
|
1544
|
-
ok: false,
|
|
1545
|
-
status: "bundle-digest-mismatch",
|
|
1546
|
-
message: `the ${manifest.harnessId} runtime bundle does not match the digest this Inspector was built with. Expected ${expectedDigest}, found ${verification.digest}. The bundle is not user- or session-writable by design, so a mismatch means it was replaced \u2014 local execution stays disabled until it is reinstalled.`
|
|
1547
|
-
};
|
|
1548
|
-
}
|
|
1549
|
-
const digest = verification.digest;
|
|
1550
|
-
const insideBundle = async (relativePath, label, requireExecutable) => {
|
|
1551
|
-
const full = join4(canonicalRoot, relativePath);
|
|
1552
|
-
if (!normalize(full).startsWith(canonicalRoot + sep)) {
|
|
1553
|
-
return {
|
|
1554
|
-
ok: false,
|
|
1555
|
-
message: `the ${manifest.harnessId} manifest points its ${label} outside the bundle whose digest was verified`
|
|
1556
|
-
};
|
|
1557
|
-
}
|
|
1558
|
-
try {
|
|
1559
|
-
const info = await stat3(full);
|
|
1560
|
-
if (!info.isFile()) throw new Error("not a file");
|
|
1561
|
-
if (requireExecutable && platform !== "win32" && (info.mode & 73) === 0) {
|
|
1562
|
-
throw new Error("not executable");
|
|
1563
|
-
}
|
|
1564
|
-
} catch {
|
|
1565
|
-
return {
|
|
1566
|
-
ok: false,
|
|
1567
|
-
message: `the ${manifest.harnessId} runtime bundle has no usable ${label} at ${relativePath}`
|
|
1568
|
-
};
|
|
1569
|
-
}
|
|
1570
|
-
return { ok: true, path: full };
|
|
1571
|
-
};
|
|
1572
|
-
const launcher = await insideBundle(
|
|
1573
|
-
policy.launcherRelativePath,
|
|
1574
|
-
"launcher",
|
|
1575
|
-
false
|
|
1576
|
-
);
|
|
1577
|
-
if (!launcher.ok) {
|
|
1578
|
-
return { ok: false, status: "bundle-corrupt", message: launcher.message };
|
|
1579
|
-
}
|
|
1580
|
-
const launcherPath = launcher.path;
|
|
1581
|
-
const bundledNode = await insideBundle(
|
|
1582
|
-
platform === "win32" ? `${policy.nodeLauncherRelativePath}.exe` : policy.nodeLauncherRelativePath,
|
|
1583
|
-
"Node binary",
|
|
1584
|
-
true
|
|
1585
|
-
);
|
|
1586
|
-
if (!bundledNode.ok) {
|
|
1587
|
-
return { ok: false, status: "bundle-corrupt", message: bundledNode.message };
|
|
1588
|
-
}
|
|
1589
|
-
let jobLauncherPath;
|
|
1590
|
-
if (platform === "win32" && policy.jobLauncherRelativePath) {
|
|
1591
|
-
const helper = await insideBundle(
|
|
1592
|
-
policy.jobLauncherRelativePath,
|
|
1593
|
-
"job launcher",
|
|
1594
|
-
true
|
|
1595
|
-
);
|
|
1596
|
-
if (helper.ok) jobLauncherPath = helper.path;
|
|
1597
|
-
}
|
|
1598
|
-
setWindowsJobLauncherVerified(jobLauncherPath !== void 0);
|
|
1599
|
-
return {
|
|
1600
|
-
ok: true,
|
|
1601
|
-
runtime: {
|
|
1602
|
-
runtimeId: runtimeIdOf([
|
|
1603
|
-
"managed-bundle",
|
|
1604
|
-
manifest.harnessId,
|
|
1605
|
-
manifest.adapterVersion,
|
|
1606
|
-
platform,
|
|
1607
|
-
digest
|
|
1608
|
-
]),
|
|
1609
|
-
source: "managed-bundle",
|
|
1610
|
-
harnessId: manifest.harnessId,
|
|
1611
|
-
platform,
|
|
1612
|
-
adapterVersion: manifest.adapterVersion,
|
|
1613
|
-
rootPath: canonicalRoot,
|
|
1614
|
-
launcherPath,
|
|
1615
|
-
nodePath: bundledNode.path,
|
|
1616
|
-
...jobLauncherPath !== void 0 ? { jobLauncherPath } : {},
|
|
1617
|
-
digest,
|
|
1618
|
-
vendorPackages: policy.vendorPackages
|
|
1619
|
-
}
|
|
1620
|
-
};
|
|
1621
|
-
}
|
|
1622
|
-
function systemInstallSearchPaths(platform) {
|
|
1623
|
-
switch (platform) {
|
|
1624
|
-
case "darwin":
|
|
1625
|
-
return ["/usr/local/bin", "/opt/homebrew/bin", "/usr/bin"];
|
|
1626
|
-
case "linux":
|
|
1627
|
-
return ["/usr/local/bin", "/usr/bin", "/bin"];
|
|
1628
|
-
case "win32":
|
|
1629
|
-
return ["C:\\Program Files", "C:\\Program Files (x86)"];
|
|
1630
|
-
}
|
|
1631
|
-
}
|
|
1632
|
-
function isUntrustedInstallPath(canonical, forbiddenRoots) {
|
|
1633
|
-
for (const root of forbiddenRoots) {
|
|
1634
|
-
if (canonical === root || canonical.startsWith(root + sep)) {
|
|
1635
|
-
return root;
|
|
1636
|
-
}
|
|
1637
|
-
}
|
|
1638
|
-
if (/(^|[\\/])node_modules([\\/]|$)/.test(canonical)) {
|
|
1639
|
-
return "a node_modules directory";
|
|
1640
|
-
}
|
|
1641
|
-
return null;
|
|
1642
|
-
}
|
|
1643
|
-
function extractVersion(line) {
|
|
1644
|
-
return /(\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?)/.exec(line)?.[1] ?? null;
|
|
1645
|
-
}
|
|
1646
|
-
function isSupportedVersionRange(range) {
|
|
1647
|
-
return /^>=\s*\d+\.\d+\.\d+$/.test(range.trim());
|
|
1648
|
-
}
|
|
1649
|
-
function satisfiesMinimumRange(version, range) {
|
|
1650
|
-
const match = /^>=\s*(\d+)\.(\d+)\.(\d+)$/.exec(range.trim());
|
|
1651
|
-
if (!match) return false;
|
|
1652
|
-
if (version.includes("-")) return false;
|
|
1653
|
-
const parts = version.split(".").map((n) => Number.parseInt(n, 10));
|
|
1654
|
-
if (parts.length !== 3 || parts.some((n) => !Number.isFinite(n)))
|
|
1655
|
-
return false;
|
|
1656
|
-
const min = [Number(match[1]), Number(match[2]), Number(match[3])];
|
|
1657
|
-
for (let i = 0; i < 3; i += 1) {
|
|
1658
|
-
if (parts[i] > min[i]) return true;
|
|
1659
|
-
if (parts[i] < min[i]) return false;
|
|
1660
|
-
}
|
|
1661
|
-
return true;
|
|
1662
|
-
}
|
|
1663
|
-
async function defaultProbe(executable, args) {
|
|
1664
|
-
return await new Promise((resolvePromise) => {
|
|
1665
|
-
execFile2(
|
|
1666
|
-
executable,
|
|
1667
|
-
[...args],
|
|
1668
|
-
{
|
|
1669
|
-
timeout: PROBE_TIMEOUT_MS,
|
|
1670
|
-
maxBuffer: PROBE_MAX_BUFFER,
|
|
1671
|
-
encoding: "utf8",
|
|
1672
|
-
windowsHide: true,
|
|
1673
|
-
env: { PATH: "", LANG: "C" }
|
|
1674
|
-
},
|
|
1675
|
-
(error, stdout) => {
|
|
1676
|
-
resolvePromise({
|
|
1677
|
-
stdout: typeof stdout === "string" ? stdout : "",
|
|
1678
|
-
exitCode: error ? 1 : 0
|
|
1679
|
-
});
|
|
1680
|
-
}
|
|
1681
|
-
);
|
|
1682
|
-
});
|
|
1683
|
-
}
|
|
1684
|
-
async function firstUntrustedAncestor(path, platform) {
|
|
1685
|
-
if (platform === "win32") return null;
|
|
1686
|
-
let dir = dirname(path);
|
|
1687
|
-
for (; ; ) {
|
|
1688
|
-
let info;
|
|
1689
|
-
try {
|
|
1690
|
-
info = await stat3(dir);
|
|
1691
|
-
} catch {
|
|
1692
|
-
return dir;
|
|
1693
|
-
}
|
|
1694
|
-
const looselyWritable = (info.mode & 18) !== 0 && (info.mode & 512) === 0;
|
|
1695
|
-
if (info.uid !== 0 || looselyWritable) return dir;
|
|
1696
|
-
const parent = dirname(dir);
|
|
1697
|
-
if (parent === dir) return null;
|
|
1698
|
-
dir = parent;
|
|
1699
|
-
}
|
|
1700
|
-
}
|
|
1701
|
-
async function resolveSystemInstall(opts) {
|
|
1702
|
-
const { manifest, platform } = opts;
|
|
1703
|
-
if (manifest.runtime.source !== "system-install") {
|
|
1704
|
-
return {
|
|
1705
|
-
ok: false,
|
|
1706
|
-
status: "system-runtime-not-installed",
|
|
1707
|
-
message: `${manifest.harnessId} is not configured for a system install`
|
|
1708
|
-
};
|
|
1709
|
-
}
|
|
1710
|
-
if (platform === "darwin") {
|
|
1711
|
-
return {
|
|
1712
|
-
ok: false,
|
|
1713
|
-
status: "system-runtime-untrusted-path",
|
|
1714
|
-
message: `a system installation cannot be trusted on macOS by this Inspector: directory ACLs there can grant replacement rights without appearing in the file mode, and nothing here can read them. Use a managed bundle, whose digest is verified in full.`
|
|
1715
|
-
};
|
|
1716
|
-
}
|
|
1717
|
-
const policy = manifest.runtime;
|
|
1718
|
-
const searchPaths = opts.searchPaths ?? systemInstallSearchPaths(platform);
|
|
1719
|
-
const probe = opts.probe ?? defaultProbe;
|
|
1720
|
-
const accepted = [];
|
|
1721
|
-
const rejections = [];
|
|
1722
|
-
for (const dir of searchPaths) {
|
|
1723
|
-
for (const name of policy.executableNames) {
|
|
1724
|
-
const candidate = join4(dir, name);
|
|
1725
|
-
let canonical;
|
|
1726
|
-
try {
|
|
1727
|
-
canonical = await realpath(candidate);
|
|
1728
|
-
} catch {
|
|
1729
|
-
continue;
|
|
1730
|
-
}
|
|
1731
|
-
if (!isAbsolute(canonical)) continue;
|
|
1732
|
-
const untrusted = isUntrustedInstallPath(canonical, opts.forbiddenRoots);
|
|
1733
|
-
if (untrusted) {
|
|
1734
|
-
rejections.push({
|
|
1735
|
-
status: "system-runtime-untrusted-path",
|
|
1736
|
-
message: `${candidate} resolves into ${untrusted}, which the session or the workspace can write`
|
|
1737
|
-
});
|
|
1738
|
-
continue;
|
|
1739
|
-
}
|
|
1740
|
-
let info;
|
|
1741
|
-
try {
|
|
1742
|
-
info = await stat3(canonical);
|
|
1743
|
-
} catch {
|
|
1744
|
-
continue;
|
|
1745
|
-
}
|
|
1746
|
-
if (!info.isFile() || (info.mode & 73) === 0) {
|
|
1747
|
-
rejections.push({
|
|
1748
|
-
status: "system-runtime-not-installed",
|
|
1749
|
-
message: `${candidate} is not an executable file`
|
|
1750
|
-
});
|
|
1751
|
-
continue;
|
|
1752
|
-
}
|
|
1753
|
-
if ((info.mode & 18) !== 0) {
|
|
1754
|
-
rejections.push({
|
|
1755
|
-
status: "system-runtime-untrusted-path",
|
|
1756
|
-
message: `${candidate} is group- or world-writable, so its identity cannot be held between verification and launch`
|
|
1757
|
-
});
|
|
1758
|
-
continue;
|
|
1759
|
-
}
|
|
1760
|
-
if (platform !== "win32" && info.uid !== 0) {
|
|
1761
|
-
rejections.push({
|
|
1762
|
-
status: "system-runtime-untrusted-path",
|
|
1763
|
-
message: `${candidate} is owned by uid ${info.uid} rather than a system owner, so the supervised agent \u2014 which runs as that user \u2014 could replace it between verification and launch`
|
|
1764
|
-
});
|
|
1765
|
-
continue;
|
|
1766
|
-
}
|
|
1767
|
-
const untrustedAncestor = await firstUntrustedAncestor(
|
|
1768
|
-
canonical,
|
|
1769
|
-
platform
|
|
1770
|
-
);
|
|
1771
|
-
if (untrustedAncestor !== null) {
|
|
1772
|
-
rejections.push({
|
|
1773
|
-
status: "system-runtime-untrusted-path",
|
|
1774
|
-
message: `${candidate} lives under ${untrustedAncestor}, which is writable by a non-system owner. Replacing the executable there needs only directory permissions, so its verified identity cannot be held between verification and launch`
|
|
1775
|
-
});
|
|
1776
|
-
continue;
|
|
1777
|
-
}
|
|
1778
|
-
if (policy.vendorIdentityPolicy.requirePlatformProvenance) {
|
|
1779
|
-
rejections.push({
|
|
1780
|
-
status: "system-runtime-identity-mismatch",
|
|
1781
|
-
message: `${manifest.harnessId} requires platform code-signing/package provenance, and this Inspector has no verifier for ${platform} yet, so the candidate at ${candidate} cannot be accepted`
|
|
1782
|
-
});
|
|
1783
|
-
continue;
|
|
1784
|
-
}
|
|
1785
|
-
const result = await probe(
|
|
1786
|
-
canonical,
|
|
1787
|
-
policy.vendorIdentityPolicy.probeArgs
|
|
1788
|
-
);
|
|
1789
|
-
const line = result.stdout.trim().split("\n")[0] ?? "";
|
|
1790
|
-
if (result.exitCode !== 0 || !new RegExp(policy.vendorIdentityPolicy.stdoutPattern).test(line)) {
|
|
1791
|
-
rejections.push({
|
|
1792
|
-
status: "system-runtime-identity-mismatch",
|
|
1793
|
-
message: `${candidate} did not identify itself as ${manifest.harnessId} (probe output ${JSON.stringify(line.slice(0, 120))})`
|
|
1794
|
-
});
|
|
1795
|
-
continue;
|
|
1796
|
-
}
|
|
1797
|
-
if (!isSupportedVersionRange(policy.executableVersionRange)) {
|
|
1798
|
-
rejections.push({
|
|
1799
|
-
status: "system-runtime-identity-mismatch",
|
|
1800
|
-
message: `the ${manifest.harnessId} manifest declares version range ${JSON.stringify(policy.executableVersionRange)}, which is not one of the shapes this Inspector evaluates (">=x.y.z")`
|
|
1801
|
-
});
|
|
1802
|
-
continue;
|
|
1803
|
-
}
|
|
1804
|
-
const version = extractVersion(line);
|
|
1805
|
-
if (version === null || !satisfiesMinimumRange(version, policy.executableVersionRange)) {
|
|
1806
|
-
rejections.push({
|
|
1807
|
-
status: "system-runtime-identity-mismatch",
|
|
1808
|
-
message: `${candidate} reports version ${version ?? "(unparseable)"}, which is outside the manifest range ${policy.executableVersionRange}`
|
|
1809
|
-
});
|
|
1810
|
-
continue;
|
|
1811
|
-
}
|
|
1812
|
-
const content = await readFile4(canonical);
|
|
1813
|
-
const digest = `sha256:${createHash("sha256").update(content).digest("hex")}`;
|
|
1814
|
-
accepted.push({
|
|
1815
|
-
runtimeId: runtimeIdOf([
|
|
1816
|
-
"system-install",
|
|
1817
|
-
manifest.harnessId,
|
|
1818
|
-
manifest.adapterVersion,
|
|
1819
|
-
platform,
|
|
1820
|
-
canonical,
|
|
1821
|
-
digest,
|
|
1822
|
-
String(info.ino)
|
|
1823
|
-
]),
|
|
1824
|
-
source: "system-install",
|
|
1825
|
-
harnessId: manifest.harnessId,
|
|
1826
|
-
platform,
|
|
1827
|
-
adapterVersion: manifest.adapterVersion,
|
|
1828
|
-
rootPath: canonical,
|
|
1829
|
-
launcherPath: canonical,
|
|
1830
|
-
digest,
|
|
1831
|
-
vendorPackages: {},
|
|
1832
|
-
vendorVersionLine: line
|
|
1833
|
-
});
|
|
1834
|
-
}
|
|
1835
|
-
}
|
|
1836
|
-
if (accepted.length === 0) {
|
|
1837
|
-
return {
|
|
1838
|
-
ok: false,
|
|
1839
|
-
// Report the FIRST real rejection's own status, not a blanket one.
|
|
1840
|
-
status: rejections[0]?.status ?? "system-runtime-not-installed",
|
|
1841
|
-
message: `no acceptable ${manifest.harnessId} installation was found in ${searchPaths.join(", ")}.` + (rejections.length ? ` Rejected: ${rejections.map((r) => r.message).join("; ")}.` : "") + ` Inspector never installs or upgrades a harness during a session.`
|
|
1842
|
-
};
|
|
1843
|
-
}
|
|
1844
|
-
if (accepted.length > 1) {
|
|
1845
|
-
const distinct = new Set(accepted.map((r) => r.rootPath));
|
|
1846
|
-
if (distinct.size > 1) {
|
|
1847
|
-
return {
|
|
1848
|
-
ok: false,
|
|
1849
|
-
status: "system-runtime-ambiguous",
|
|
1850
|
-
message: `more than one ${manifest.harnessId} installation is acceptable (${[...distinct].join(
|
|
1851
|
-
", "
|
|
1852
|
-
)}). Remove or disambiguate them: consent must name exactly one runtime.`
|
|
1853
|
-
};
|
|
1854
|
-
}
|
|
1855
|
-
}
|
|
1856
|
-
return { ok: true, runtime: accepted[0] };
|
|
1857
|
-
}
|
|
1858
|
-
async function detectSnapshotDrift(snapshot) {
|
|
1859
|
-
const recorded = new Map(snapshot.entries.map((e) => [e.path, e]));
|
|
1860
|
-
let seen = 0;
|
|
1861
|
-
const walk = async (dir) => {
|
|
1862
|
-
const entries = await readdir3(dir, { withFileTypes: true });
|
|
1863
|
-
for (const entry of entries) {
|
|
1864
|
-
const full = join4(dir, entry.name);
|
|
1865
|
-
const rel = relative(snapshot.root, full).split(sep).join("/");
|
|
1866
|
-
if (entry.isSymbolicLink()) return `a symlink appeared at ${rel}`;
|
|
1867
|
-
if (entry.isDirectory()) {
|
|
1868
|
-
const nested = await walk(full);
|
|
1869
|
-
if (nested !== null) return nested;
|
|
1870
|
-
continue;
|
|
1871
|
-
}
|
|
1872
|
-
if (!entry.isFile()) return `a non-regular file appeared at ${rel}`;
|
|
1873
|
-
const expected = recorded.get(rel);
|
|
1874
|
-
if (expected === void 0) return `an unexpected file appeared at ${rel}`;
|
|
1875
|
-
seen += 1;
|
|
1876
|
-
const info = await stat3(full);
|
|
1877
|
-
if (info.size !== expected.size || info.mtimeMs !== expected.mtimeMs || info.ctimeMs !== expected.ctimeMs || Number(info.ino) !== expected.ino || info.mode !== expected.mode) {
|
|
1878
|
-
return `${rel} was modified`;
|
|
1879
|
-
}
|
|
1880
|
-
if (isRehashedOnRevalidate(rel)) {
|
|
1881
|
-
const content = await readFile4(full);
|
|
1882
|
-
const fileDigest = createHash("sha256").update(content).digest("hex");
|
|
1883
|
-
if (fileDigest !== snapshot.executableDigests[rel]) {
|
|
1884
|
-
return `${rel} was rewritten in place`;
|
|
1885
|
-
}
|
|
1886
|
-
}
|
|
1887
|
-
}
|
|
1888
|
-
return null;
|
|
1889
|
-
};
|
|
1890
|
-
const reason = await walk(snapshot.root);
|
|
1891
|
-
if (reason !== null) return reason;
|
|
1892
|
-
if (seen !== snapshot.entries.length) {
|
|
1893
|
-
return `${snapshot.entries.length - seen} file(s) went missing`;
|
|
1894
|
-
}
|
|
1895
|
-
return null;
|
|
1896
|
-
}
|
|
1897
|
-
async function revalidateRuntime(runtime) {
|
|
1898
|
-
try {
|
|
1899
|
-
if (runtime.source === "managed-bundle") {
|
|
1900
|
-
const snapshot = verifiedRuntimeCache.get(
|
|
1901
|
-
verificationCacheKey(runtime.rootPath, runtime.digest)
|
|
1902
|
-
);
|
|
1903
|
-
if (snapshot === void 0) {
|
|
1904
|
-
const verification = await verifyRuntime(
|
|
1905
|
-
runtime.rootPath,
|
|
1906
|
-
runtime.digest
|
|
1907
|
-
);
|
|
1908
|
-
if (!verification.ok) {
|
|
1909
|
-
return {
|
|
1910
|
-
ok: false,
|
|
1911
|
-
message: verification.reason === "digest-mismatch" ? `the ${runtime.harnessId} runtime bundle changed after consent was granted (expected ${runtime.digest}, found ${verification.digest})` : `the ${runtime.harnessId} runtime could not be re-verified: ${verification.message}`
|
|
1912
|
-
};
|
|
1913
|
-
}
|
|
1914
|
-
return { ok: true };
|
|
1915
|
-
}
|
|
1916
|
-
const drift = await detectSnapshotDrift(snapshot);
|
|
1917
|
-
if (drift === null) return { ok: true };
|
|
1918
|
-
verifiedRuntimeCache.delete(
|
|
1919
|
-
verificationCacheKey(runtime.rootPath, runtime.digest)
|
|
1920
|
-
);
|
|
1921
|
-
const reverified = await verifyRuntime(runtime.rootPath, runtime.digest);
|
|
1922
|
-
if (reverified.ok) return { ok: true };
|
|
1923
|
-
return {
|
|
1924
|
-
ok: false,
|
|
1925
|
-
message: reverified.reason === "digest-mismatch" ? `the ${runtime.harnessId} runtime bundle changed after consent was granted (${drift}; expected ${runtime.digest}, found ${reverified.digest})` : `the ${runtime.harnessId} runtime could not be re-verified: ${reverified.message}`
|
|
1926
|
-
};
|
|
1927
|
-
}
|
|
1928
|
-
const content = await readFile4(runtime.launcherPath);
|
|
1929
|
-
const digest = `sha256:${createHash("sha256").update(content).digest("hex")}`;
|
|
1930
|
-
if (digest !== runtime.digest) {
|
|
1931
|
-
return {
|
|
1932
|
-
ok: false,
|
|
1933
|
-
message: `the ${runtime.harnessId} executable at ${runtime.launcherPath} was replaced after consent was granted`
|
|
1934
|
-
};
|
|
1935
|
-
}
|
|
1936
|
-
return { ok: true };
|
|
1937
|
-
} catch (error) {
|
|
1938
|
-
return {
|
|
1939
|
-
ok: false,
|
|
1940
|
-
message: `the ${runtime.harnessId} runtime could not be re-verified: ${error instanceof Error ? error.message : String(error)}`
|
|
1941
|
-
};
|
|
1942
|
-
}
|
|
1943
|
-
}
|
|
1944
|
-
|
|
1945
|
-
// server/utils/harness/local/compatibility.ts
|
|
1946
|
-
var LOCAL_HARNESS_MANIFEST = {
|
|
1947
|
-
"claude-code": {
|
|
1948
|
-
harnessId: "claude-code",
|
|
1949
|
-
adapterVersion: "1.0.100",
|
|
1950
|
-
runtime: {
|
|
1951
|
-
source: "managed-bundle",
|
|
1952
|
-
bundleName: "claude-code",
|
|
1953
|
-
// Generated by the release pack build, and EMPTY until one has run.
|
|
1954
|
-
// Either way the result is `bundle-absent` before any tree is read, but
|
|
1955
|
-
// WHICH message depends on what is on disk: with no bundle directory —
|
|
1956
|
-
// today's state — `resolveManagedBundle` reports the missing bundle
|
|
1957
|
-
// first; with a directory present, the empty map has no entry for this
|
|
1958
|
-
// machine's `<os>-<arch>` and it names the target instead ("no pack has
|
|
1959
|
-
// been built for linux-x64"). Both fail closed; only the second names a
|
|
1960
|
-
// pack a user could go looking for.
|
|
1961
|
-
bundleDigest: PACK_TREE_DIGESTS["claude-code"],
|
|
1962
|
-
launcherRelativePath: "launcher.mjs",
|
|
1963
|
-
nodeLauncherRelativePath: "bin/node",
|
|
1964
|
-
jobLauncherRelativePath: "bin/mcpjam-job-launcher.exe",
|
|
1965
|
-
vendorPackages: {
|
|
1966
|
-
"@anthropic-ai/claude-code": "pinned-by-adapter-bridge-lockfile"
|
|
1967
|
-
}
|
|
1968
|
-
},
|
|
1969
|
-
argvPolicy: { requiredFlags: [], deniedFlags: [] },
|
|
1970
|
-
configStrategy: "synthetic-home",
|
|
1971
|
-
supportsBuiltinToolApprovals: true,
|
|
1972
|
-
permissionProfileMapping: {
|
|
1973
|
-
"read-only": "allow-reads",
|
|
1974
|
-
"workspace-edits": "allow-edits",
|
|
1975
|
-
unrestricted: "allow-all"
|
|
1976
|
-
},
|
|
1977
|
-
// Native eligibility is per platform. macOS and Linux have POSIX process
|
|
1978
|
-
// groups, which is what whole-tree cleanup is built on there.
|
|
1979
|
-
//
|
|
1980
|
-
// Windows has no process group; its whole-tree guarantee is a Job Object
|
|
1981
|
-
// with KILL_ON_JOB_CLOSE, created by `tools/mcpjam-job-launcher`, which
|
|
1982
|
-
// ships INSIDE the Windows pack so its bytes are covered by the tree
|
|
1983
|
-
// digest. Listing `win32` here is necessary but not sufficient:
|
|
1984
|
-
// `supportsOwnershipProof('win32')` still answers false until runtime
|
|
1985
|
-
// resolution has verified that launcher, so a pack without one keeps the
|
|
1986
|
-
// platform refused exactly as before.
|
|
1987
|
-
//
|
|
1988
|
-
// Earned, not asserted: the conformance suite's `windows-latest` leg runs
|
|
1989
|
-
// the full scenario and the abort scenario against the real pack and the
|
|
1990
|
-
// real vendor CLI, and its survivor scan is what turns "we wrote a Job
|
|
1991
|
-
// Object" into evidence that stopping a session stops everything it
|
|
1992
|
-
// started. That leg is gating; the day it goes red, this entry is wrong.
|
|
1993
|
-
nativePlatforms: ["darwin", "linux", "win32"],
|
|
1994
|
-
// Empty until a backend's escape probes actually pass (I6).
|
|
1995
|
-
isolatedBackends: {},
|
|
1996
|
-
lifecycleConformanceVersion: "",
|
|
1997
|
-
adapterBootstrapDir: ".harness-bootstrap/claude-code",
|
|
1998
|
-
adapterBootstrapFiles: [
|
|
1999
|
-
"package.json",
|
|
2000
|
-
"pnpm-lock.yaml",
|
|
2001
|
-
"pnpm-workspace.yaml",
|
|
2002
|
-
"bridge.mjs",
|
|
2003
|
-
".npmrc"
|
|
2004
|
-
],
|
|
2005
|
-
bridgeBundleDigest: `sha256:${"0".repeat(64)}`
|
|
2006
|
-
},
|
|
2007
|
-
codex: {
|
|
2008
|
-
harnessId: "codex",
|
|
2009
|
-
adapterVersion: "1.0.98",
|
|
2010
|
-
runtime: {
|
|
2011
|
-
source: "managed-bundle",
|
|
2012
|
-
bundleName: "codex",
|
|
2013
|
-
bundleDigest: PACK_TREE_DIGESTS.codex,
|
|
2014
|
-
launcherRelativePath: "launcher.mjs",
|
|
2015
|
-
nodeLauncherRelativePath: "bin/node",
|
|
2016
|
-
vendorPackages: {
|
|
2017
|
-
"@openai/codex-sdk": "pinned-by-adapter-bridge-lockfile"
|
|
2018
|
-
}
|
|
2019
|
-
},
|
|
2020
|
-
argvPolicy: { requiredFlags: [], deniedFlags: [] },
|
|
2021
|
-
configStrategy: "explicit-config-root",
|
|
2022
|
-
supportsBuiltinToolApprovals: false,
|
|
2023
|
-
// No mapping at all: the adapter rejects every mode but `allow-all`, and
|
|
2024
|
-
// `allow-all` on a host with no outer boundary is the thing this plan
|
|
2025
|
-
// exists to prevent. Codex earns a mapping when its adapter gains a
|
|
2026
|
-
// reviewed restricted mode, or inside a verified isolation backend.
|
|
2027
|
-
permissionProfileMapping: {},
|
|
2028
|
-
nativePlatforms: [],
|
|
2029
|
-
isolatedBackends: {},
|
|
2030
|
-
lifecycleConformanceVersion: "",
|
|
2031
|
-
adapterBootstrapDir: ".harness-bootstrap/codex",
|
|
2032
|
-
adapterBootstrapFiles: ["package.json", "pnpm-lock.yaml", "bridge.mjs"],
|
|
2033
|
-
bridgeBundleDigest: `sha256:${"0".repeat(64)}`
|
|
2034
|
-
}
|
|
2035
|
-
};
|
|
2036
|
-
function localPermissionModeFor(harnessId, permissionProfile, targetKind, scope = "attended") {
|
|
2037
|
-
const manifests = LOCAL_HARNESS_MANIFEST;
|
|
2038
|
-
const manifest = Object.prototype.hasOwnProperty.call(manifests, harnessId) ? manifests[harnessId] : void 0;
|
|
2039
|
-
if (manifest === void 0) return null;
|
|
2040
|
-
if (permissionProfile === "unrestricted" && targetKind === "local-native" && scope !== "unattended") {
|
|
2041
|
-
return null;
|
|
2042
|
-
}
|
|
2043
|
-
return manifest.permissionProfileMapping[permissionProfile] ?? null;
|
|
2044
|
-
}
|
|
2045
|
-
function resolveLocalCompatibility(query, manifests = LOCAL_HARNESS_MANIFEST) {
|
|
2046
|
-
const manifest = Object.prototype.hasOwnProperty.call(
|
|
2047
|
-
manifests,
|
|
2048
|
-
query.harnessId
|
|
2049
|
-
) ? manifests[query.harnessId] : void 0;
|
|
2050
|
-
if (!manifest) {
|
|
2051
|
-
return {
|
|
2052
|
-
ok: false,
|
|
2053
|
-
status: "harness-not-supported",
|
|
2054
|
-
message: `${query.harnessId} has no reviewed local compatibility manifest. Run it hosted, or add a manifest entry with conformance evidence.`
|
|
2055
|
-
};
|
|
2056
|
-
}
|
|
2057
|
-
if (query.installedAdapterVersion !== manifest.adapterVersion) {
|
|
2058
|
-
return {
|
|
2059
|
-
ok: false,
|
|
2060
|
-
status: "adapter-version-mismatch",
|
|
2061
|
-
message: `${query.harnessId} adapter ${query.installedAdapterVersion ?? "(version not supplied)"} is installed but the local manifest was reviewed against ${manifest.adapterVersion}. An adapter upgrade can change the command shapes the local provider translates, so it must be re-reviewed before local execution is enabled.`
|
|
2062
|
-
};
|
|
2063
|
-
}
|
|
2064
|
-
if (manifest.lifecycleConformanceVersion === "") {
|
|
2065
|
-
return {
|
|
2066
|
-
ok: false,
|
|
2067
|
-
status: "conformance-missing",
|
|
2068
|
-
message: `${query.harnessId} has no recorded lifecycle conformance evidence. Local execution stays disabled until the conformance suite has been run for this harness/runtime/platform/mode tuple and its version is recorded in the manifest.`
|
|
2069
|
-
};
|
|
2070
|
-
}
|
|
2071
|
-
if (query.platform === null) {
|
|
2072
|
-
return {
|
|
2073
|
-
ok: false,
|
|
2074
|
-
status: "platform-not-supported",
|
|
2075
|
-
// NOT "run the harness hosted instead". A requested-local turn has Send
|
|
2076
|
-
// disabled in this state (`localHarnessBlocksSend`), so nothing falls
|
|
2077
|
-
// back — and on a local Inspector with no cloud data plane there is no
|
|
2078
|
-
// hosted target to switch to either, which makes the instruction
|
|
2079
|
-
// unactionable exactly where it is most likely to be read.
|
|
2080
|
-
message: `local execution is not supported on this platform.`
|
|
2081
|
-
};
|
|
2082
|
-
}
|
|
2083
|
-
if (query.targetKind === "local-native") {
|
|
2084
|
-
if (!manifest.nativePlatforms.includes(query.platform)) {
|
|
2085
|
-
const reason = manifest.nativePlatforms.length === 0 ? `${query.harnessId} is not eligible for native mode on any platform: its adapter cannot surface tool approvals, so native execution would give it the OS user's full authority with no approval gate. Use hosted, or a verified isolation backend.` : `${query.harnessId} native mode is not supported on ${query.platform} (supported: ${manifest.nativePlatforms.join(", ")}).`;
|
|
2086
|
-
return {
|
|
2087
|
-
ok: false,
|
|
2088
|
-
status: "native-not-eligible",
|
|
2089
|
-
message: reason
|
|
2090
|
-
};
|
|
2091
|
-
}
|
|
2092
|
-
} else {
|
|
2093
|
-
if (query.backend === void 0) {
|
|
2094
|
-
return {
|
|
2095
|
-
ok: false,
|
|
2096
|
-
status: "backend-not-verified",
|
|
2097
|
-
message: "an isolated target must name its isolation backend."
|
|
2098
|
-
};
|
|
2099
|
-
}
|
|
2100
|
-
const verifiedHere = manifest.isolatedBackends[query.platform] ?? [];
|
|
2101
|
-
if (!verifiedHere.includes(query.backend)) {
|
|
2102
|
-
return {
|
|
2103
|
-
ok: false,
|
|
2104
|
-
status: "backend-not-verified",
|
|
2105
|
-
message: `isolation backend ${query.backend} has not passed conformance for ${query.harnessId} on ${query.platform}. Isolated mode never falls back to native \u2014 run hosted until the backend is verified for this platform.`
|
|
2106
|
-
};
|
|
2107
|
-
}
|
|
2108
|
-
}
|
|
2109
|
-
const permissionMode = manifest.permissionProfileMapping[query.permissionProfile];
|
|
2110
|
-
if (permissionMode === void 0) {
|
|
2111
|
-
const offered = Object.keys(manifest.permissionProfileMapping);
|
|
2112
|
-
return {
|
|
2113
|
-
ok: false,
|
|
2114
|
-
status: "permission-profile-not-supported",
|
|
2115
|
-
message: `${query.harnessId} does not offer the ${query.permissionProfile} permission profile locally` + (offered.length ? ` (offered: ${offered.join(", ")}).` : `; it has no locally offered profile at all.`)
|
|
2116
|
-
};
|
|
2117
|
-
}
|
|
2118
|
-
if (query.scope !== "unattended" && query.permissionProfile === "unrestricted" && query.targetKind === "local-native") {
|
|
2119
|
-
return {
|
|
2120
|
-
ok: false,
|
|
2121
|
-
status: "permission-profile-not-supported",
|
|
2122
|
-
message: `the unrestricted profile requires a verified isolation backend. Native mode has no host containment, so an unrestricted turn there would run with the OS user's full authority.`
|
|
2123
|
-
};
|
|
2124
|
-
}
|
|
2125
|
-
return { ok: true, manifest, permissionMode };
|
|
2126
|
-
}
|
|
2127
|
-
|
|
2128
|
-
// server/utils/harness/local/runtime-install.ts
|
|
2129
|
-
var MAX_ARCHIVE_BYTES = 1500 * 1024 * 1024;
|
|
2130
|
-
var MAX_EXTRACTED_BYTES = 2 * 1024 * 1024 * 1024;
|
|
2131
|
-
var MAX_MANIFEST_BYTES = 1024 * 1024;
|
|
2132
|
-
function runtimeInstallRoot() {
|
|
2133
|
-
const override = process.env.MCPJAM_RUNTIME_ROOT;
|
|
2134
|
-
if (override && override.trim().length > 0) return override.trim();
|
|
2135
|
-
return join5(homedir(), ".mcpjam", "harness-local", "runtime");
|
|
2136
|
-
}
|
|
2137
|
-
function packVersionRoot(packVersion, target = localPackTarget()) {
|
|
2138
|
-
return join5(targetInstallRoot(target), packVersion);
|
|
2139
|
-
}
|
|
2140
|
-
function targetInstallRoot(target) {
|
|
2141
|
-
return join5(runtimeInstallRoot(), target ?? packPlatformKey());
|
|
2142
|
-
}
|
|
2143
|
-
function expectedPackFor(harnessId, target) {
|
|
2144
|
-
const override = developmentPackExpectation();
|
|
2145
|
-
if (override !== null) return override;
|
|
2146
|
-
const record = PACK_RECORDS[harnessId]?.[target];
|
|
2147
|
-
if (record === void 0) return null;
|
|
2148
|
-
return { packVersion: record.packVersion, treeDigest: record.treeDigest };
|
|
2149
|
-
}
|
|
2150
|
-
function developmentPackExpectation() {
|
|
2151
|
-
const source = process.env.MCPJAM_LOCAL_HARNESS_PACK_SOURCE;
|
|
2152
|
-
const expected = process.env.MCPJAM_LOCAL_HARNESS_EXPECTED_PACK;
|
|
2153
|
-
if (!source || !expected) return null;
|
|
2154
|
-
const separator = expected.indexOf(":");
|
|
2155
|
-
if (separator <= 0) return null;
|
|
2156
|
-
const packVersion = expected.slice(0, separator).trim();
|
|
2157
|
-
const treeDigest = expected.slice(separator + 1).trim();
|
|
2158
|
-
if (packVersion.length === 0) return null;
|
|
2159
|
-
if (!/^sha256:[0-9a-f]{64}$/.test(treeDigest)) return null;
|
|
2160
|
-
return { packVersion, treeDigest };
|
|
2161
|
-
}
|
|
2162
|
-
function packSourceFor(packVersion, platformKey) {
|
|
2163
|
-
const override = process.env.MCPJAM_LOCAL_HARNESS_PACK_SOURCE;
|
|
2164
|
-
if (override && override.trim().length > 0) {
|
|
2165
|
-
const value = override.trim();
|
|
2166
|
-
return /^https?:\/\//.test(value) ? { kind: "url", location: value } : { kind: "file", location: value.replace(/^file:\/\//, "") };
|
|
2167
|
-
}
|
|
2168
|
-
return {
|
|
2169
|
-
kind: "url",
|
|
2170
|
-
location: `https://github.com/MCPJam/inspector/releases/download/local-harness-pack-v${packVersion}/local-harness-pack-${platformKey}-${packVersion}.tar.gz`
|
|
2171
|
-
};
|
|
2172
|
-
}
|
|
2173
|
-
function packPlatformKey(platform = process.platform, arch = process.arch) {
|
|
2174
|
-
return `${platform}-${arch}`;
|
|
2175
|
-
}
|
|
2176
|
-
async function readRuntimeInstallStatus(args) {
|
|
2177
|
-
const resolved = resolveInstallTarget(args);
|
|
2178
|
-
if (!resolved.ok) return resolved.status;
|
|
2179
|
-
const { key, expected, versionRoot } = resolved;
|
|
2180
|
-
await recoverInterruptedActivation({ key, versionRoot });
|
|
2181
|
-
const inProcess = active.get(operationKeyString(key));
|
|
2182
|
-
if (inProcess !== void 0) return inProcess.status;
|
|
2183
|
-
const record = await readRuntimeOperation(key);
|
|
2184
|
-
if (record !== null && !isRecordTerminal(record)) {
|
|
2185
|
-
return operationRecordStatus(record);
|
|
2186
|
-
}
|
|
2187
|
-
const onDisk = await readMarkerStatus({
|
|
2188
|
-
harnessId: args.harnessId,
|
|
2189
|
-
versionRoot,
|
|
2190
|
-
expected
|
|
2191
|
-
});
|
|
2192
|
-
if (onDisk.state === "ready") return onDisk;
|
|
2193
|
-
if (record !== null && isRecordTerminal(record) && record.state !== "ready") {
|
|
2194
|
-
return operationRecordStatus(record);
|
|
2195
|
-
}
|
|
2196
|
-
return onDisk;
|
|
2197
|
-
}
|
|
2198
|
-
function manifestWithExpectedBundleDigest(manifest, harnessId, target) {
|
|
2199
|
-
if (target === null) return manifest;
|
|
2200
|
-
if (manifest.runtime.source !== "managed-bundle") return manifest;
|
|
2201
|
-
const expected = expectedPackFor(harnessId, target);
|
|
2202
|
-
if (expected === null) return manifest;
|
|
2203
|
-
if (manifest.runtime.bundleDigest[target] === expected.treeDigest) {
|
|
2204
|
-
return manifest;
|
|
2205
|
-
}
|
|
2206
|
-
return {
|
|
2207
|
-
...manifest,
|
|
2208
|
-
runtime: {
|
|
2209
|
-
...manifest.runtime,
|
|
2210
|
-
bundleDigest: {
|
|
2211
|
-
...manifest.runtime.bundleDigest,
|
|
2212
|
-
[target]: expected.treeDigest
|
|
2213
|
-
}
|
|
2214
|
-
}
|
|
2215
|
-
};
|
|
2216
|
-
}
|
|
2217
|
-
async function readVerifiedRuntimeStatus(args) {
|
|
2218
|
-
const status = await readRuntimeInstallStatus(args);
|
|
2219
|
-
if (status.state !== "ready") return status;
|
|
2220
|
-
const platform = currentLocalPlatform(args.platform ?? process.platform);
|
|
2221
|
-
if (platform === null) return status;
|
|
2222
|
-
const resolvedBundle = await resolveManagedBundle({
|
|
2223
|
-
manifest: manifestWithExpectedBundleDigest(
|
|
2224
|
-
LOCAL_HARNESS_MANIFEST[args.harnessId],
|
|
2225
|
-
args.harnessId,
|
|
2226
|
-
localPackTarget(args.platform, args.arch)
|
|
2227
|
-
),
|
|
2228
|
-
runtimeRoot: status.runtimeRoot,
|
|
2229
|
-
platform,
|
|
2230
|
-
...args.arch ? { arch: args.arch } : {}
|
|
2231
|
-
});
|
|
2232
|
-
if (resolvedBundle.ok) return status;
|
|
2233
|
-
return {
|
|
2234
|
-
state: "corrupt",
|
|
2235
|
-
packVersion: status.packVersion,
|
|
2236
|
-
message: resolvedBundle.message
|
|
2237
|
-
};
|
|
2238
|
-
}
|
|
2239
|
-
async function readMarkerStatus(args) {
|
|
2240
|
-
try {
|
|
2241
|
-
const marker = JSON.parse(
|
|
2242
|
-
await readFile5(join5(args.versionRoot, INSTALL_MARKER), "utf8")
|
|
2243
|
-
);
|
|
2244
|
-
if (marker.treeDigest !== args.expected.treeDigest) {
|
|
2245
|
-
return {
|
|
2246
|
-
state: "corrupt",
|
|
2247
|
-
packVersion: args.expected.packVersion,
|
|
2248
|
-
message: "the installed runtime pack does not match the digest this Inspector expects; reinstall it"
|
|
2249
|
-
};
|
|
2250
|
-
}
|
|
2251
|
-
await stat4(join5(args.versionRoot, args.harnessId));
|
|
2252
|
-
return {
|
|
2253
|
-
state: "ready",
|
|
2254
|
-
packVersion: args.expected.packVersion,
|
|
2255
|
-
runtimeRoot: args.versionRoot,
|
|
2256
|
-
digest: args.expected.treeDigest
|
|
2257
|
-
};
|
|
2258
|
-
} catch {
|
|
2259
|
-
return { state: "absent", packVersion: args.expected.packVersion };
|
|
2260
|
-
}
|
|
2261
|
-
}
|
|
2262
|
-
function isRecordTerminal(record) {
|
|
2263
|
-
return record.state === "ready" || record.state === "failed" || record.state === "interrupted";
|
|
2264
|
-
}
|
|
2265
|
-
function operationRecordStatus(record) {
|
|
2266
|
-
switch (record.state) {
|
|
2267
|
-
case "reserved":
|
|
2268
|
-
case "downloading":
|
|
2269
|
-
return {
|
|
2270
|
-
state: "downloading",
|
|
2271
|
-
packVersion: record.packVersion,
|
|
2272
|
-
percent: record.percent ?? 0,
|
|
2273
|
-
attemptId: record.attemptId
|
|
2274
|
-
};
|
|
2275
|
-
case "verifying":
|
|
2276
|
-
case "activating":
|
|
2277
|
-
return {
|
|
2278
|
-
state: "verifying",
|
|
2279
|
-
packVersion: record.packVersion,
|
|
2280
|
-
attemptId: record.attemptId
|
|
2281
|
-
};
|
|
2282
|
-
case "failed":
|
|
2283
|
-
return {
|
|
2284
|
-
state: "failed",
|
|
2285
|
-
packVersion: record.packVersion,
|
|
2286
|
-
reason: record.reason ?? "unknown",
|
|
2287
|
-
message: record.message ?? "the install did not complete",
|
|
2288
|
-
attemptId: record.attemptId
|
|
2289
|
-
};
|
|
2290
|
-
case "interrupted":
|
|
2291
|
-
return {
|
|
2292
|
-
state: "interrupted",
|
|
2293
|
-
packVersion: record.packVersion,
|
|
2294
|
-
message: record.message ?? "setup was interrupted before it finished",
|
|
2295
|
-
attemptId: record.attemptId
|
|
2296
|
-
};
|
|
2297
|
-
case "ready":
|
|
2298
|
-
return {
|
|
2299
|
-
state: "ready",
|
|
2300
|
-
packVersion: record.packVersion,
|
|
2301
|
-
runtimeRoot: packVersionRoot(record.packVersion, record.target),
|
|
2302
|
-
digest: record.treeDigest
|
|
2303
|
-
};
|
|
2304
|
-
}
|
|
2305
|
-
}
|
|
2306
|
-
function resolveInstallTarget(args) {
|
|
2307
|
-
const platform = currentLocalPlatform(args.platform ?? process.platform);
|
|
2308
|
-
if (platform === null) {
|
|
2309
|
-
return {
|
|
2310
|
-
ok: false,
|
|
2311
|
-
status: {
|
|
2312
|
-
state: "unsupported-platform",
|
|
2313
|
-
message: `${args.platform ?? process.platform} has no local harness runtime`
|
|
2314
|
-
}
|
|
2315
|
-
};
|
|
2316
|
-
}
|
|
2317
|
-
const target = localPackTarget(args.platform, args.arch);
|
|
2318
|
-
const expected = target === null ? null : expectedPackFor(args.harnessId, target);
|
|
2319
|
-
if (expected === null || target === null) {
|
|
2320
|
-
return {
|
|
2321
|
-
ok: false,
|
|
2322
|
-
status: {
|
|
2323
|
-
state: "unsupported-platform",
|
|
2324
|
-
message: `no ${args.harnessId} runtime pack has been built for ${packPlatformKey(args.platform, args.arch)}`
|
|
2325
|
-
}
|
|
2326
|
-
};
|
|
2327
|
-
}
|
|
2328
|
-
return {
|
|
2329
|
-
ok: true,
|
|
2330
|
-
platform,
|
|
2331
|
-
target,
|
|
2332
|
-
expected,
|
|
2333
|
-
versionRoot: packVersionRoot(expected.packVersion, target),
|
|
2334
|
-
key: {
|
|
2335
|
-
runtimeRoot: runtimeInstallRoot(),
|
|
2336
|
-
harnessId: args.harnessId,
|
|
2337
|
-
target,
|
|
2338
|
-
packVersion: expected.packVersion,
|
|
2339
|
-
treeDigest: expected.treeDigest
|
|
2340
|
-
}
|
|
2341
|
-
};
|
|
2342
|
-
}
|
|
2343
|
-
var INSTALL_MARKER = ".mcpjam-pack-installed.json";
|
|
2344
|
-
var active = /* @__PURE__ */ new Map();
|
|
2345
|
-
async function startRuntimeInstall(options) {
|
|
2346
|
-
const resolved = resolveInstallTarget(options);
|
|
2347
|
-
if (!resolved.ok) {
|
|
2348
|
-
return {
|
|
2349
|
-
kind: "refused",
|
|
2350
|
-
status: resolved.status,
|
|
2351
|
-
reason: resolved.status.state === "unsupported-platform" ? resolved.status.message : "this machine has no runtime pack to install"
|
|
2352
|
-
};
|
|
2353
|
-
}
|
|
2354
|
-
const { key, expected, versionRoot } = resolved;
|
|
2355
|
-
if (options.expectedPack !== void 0 && (options.expectedPack.packVersion !== expected.packVersion || options.expectedPack.treeDigest !== expected.treeDigest)) {
|
|
2356
|
-
return {
|
|
2357
|
-
kind: "refused",
|
|
2358
|
-
reason: "this Inspector now expects a different runtime than the one that was approved, so it will not download it under that approval",
|
|
2359
|
-
status: {
|
|
2360
|
-
state: "failed",
|
|
2361
|
-
packVersion: expected.packVersion,
|
|
2362
|
-
reason: "verification",
|
|
2363
|
-
message: `the approved runtime was ${options.expectedPack.packVersion} (${options.expectedPack.treeDigest.slice(0, 19)}\u2026) but this Inspector now expects ${expected.packVersion} (${expected.treeDigest.slice(0, 19)}\u2026). Authorize the new one.`
|
|
2364
|
-
}
|
|
2365
|
-
};
|
|
2366
|
-
}
|
|
2367
|
-
const keyString = operationKeyString(key);
|
|
2368
|
-
const running = active.get(keyString);
|
|
2369
|
-
if (running !== void 0) {
|
|
2370
|
-
return { kind: "joined", status: running.status };
|
|
2371
|
-
}
|
|
2372
|
-
await recoverInterruptedActivation({ key, versionRoot });
|
|
2373
|
-
const verified = await readVerifiedRuntimeStatus(options);
|
|
2374
|
-
if (verified.state === "ready") return { kind: "ready", status: verified };
|
|
2375
|
-
const attempt = await beginInstallAttempt(key);
|
|
2376
|
-
if (attempt.kind === "joined") {
|
|
2377
|
-
return {
|
|
2378
|
-
kind: "joined",
|
|
2379
|
-
status: operationRecordStatus(attempt.record),
|
|
2380
|
-
attemptId: attempt.record.attemptId
|
|
2381
|
-
};
|
|
2382
|
-
}
|
|
2383
|
-
const record = {
|
|
2384
|
-
status: {
|
|
2385
|
-
state: "downloading",
|
|
2386
|
-
packVersion: expected.packVersion,
|
|
2387
|
-
percent: 0,
|
|
2388
|
-
attemptId: attempt.record.attemptId
|
|
2389
|
-
},
|
|
2390
|
-
promise: Promise.resolve({
|
|
2391
|
-
state: "absent",
|
|
2392
|
-
packVersion: expected.packVersion
|
|
2393
|
-
})
|
|
2394
|
-
};
|
|
2395
|
-
active.set(keyString, record);
|
|
2396
|
-
record.promise = runInstallAttempt({
|
|
2397
|
-
options,
|
|
2398
|
-
resolved,
|
|
2399
|
-
attemptId: attempt.record.attemptId,
|
|
2400
|
-
record,
|
|
2401
|
-
keyString
|
|
2402
|
-
});
|
|
2403
|
-
void record.promise;
|
|
2404
|
-
return {
|
|
2405
|
-
kind: "started",
|
|
2406
|
-
status: record.status,
|
|
2407
|
-
attemptId: attempt.record.attemptId
|
|
2408
|
-
};
|
|
2409
|
-
}
|
|
2410
|
-
async function installRuntimePack(options) {
|
|
2411
|
-
const started = await startRuntimeInstall(options);
|
|
2412
|
-
if (started.kind === "ready" || started.kind === "refused") {
|
|
2413
|
-
return started.status;
|
|
2414
|
-
}
|
|
2415
|
-
const resolved = resolveInstallTarget(options);
|
|
2416
|
-
if (!resolved.ok) return resolved.status;
|
|
2417
|
-
const running = active.get(operationKeyString(resolved.key));
|
|
2418
|
-
if (running !== void 0) return running.promise;
|
|
2419
|
-
return awaitForeignAttempt(resolved.key, options);
|
|
2420
|
-
}
|
|
2421
|
-
async function awaitForeignAttempt(key, options) {
|
|
2422
|
-
for (; ; ) {
|
|
2423
|
-
if (options.signal?.aborted === true) {
|
|
2424
|
-
return readRuntimeInstallStatus(options);
|
|
2425
|
-
}
|
|
2426
|
-
const record = await readRuntimeOperation(key);
|
|
2427
|
-
if (record === null) return readRuntimeInstallStatus(options);
|
|
2428
|
-
if (isRecordTerminal(record)) {
|
|
2429
|
-
return record.state === "ready" ? readRuntimeInstallStatus(options) : operationRecordStatus(record);
|
|
2430
|
-
}
|
|
2431
|
-
options.onProgress?.(operationRecordStatus(record));
|
|
2432
|
-
await new Promise((resolvePromise) => setTimeout(resolvePromise, 500));
|
|
2433
|
-
}
|
|
2434
|
-
}
|
|
2435
|
-
async function runInstallAttempt(args) {
|
|
2436
|
-
const { options, resolved, attemptId, record, keyString } = args;
|
|
2437
|
-
const { key, expected } = resolved;
|
|
2438
|
-
const setStatus = (status) => {
|
|
2439
|
-
record.status = status;
|
|
2440
|
-
options.onProgress?.(status);
|
|
2441
|
-
void updateInstallAttempt(key, attemptId, {
|
|
2442
|
-
state: status.state === "downloading" ? "downloading" : status.state === "verifying" ? "verifying" : "reserved",
|
|
2443
|
-
...status.state === "downloading" ? { percent: status.percent } : {}
|
|
2444
|
-
}).catch(() => {
|
|
2445
|
-
});
|
|
2446
|
-
};
|
|
2447
|
-
try {
|
|
2448
|
-
const result = await performInstall({
|
|
2449
|
-
...options,
|
|
2450
|
-
platform: resolved.platform,
|
|
2451
|
-
expected,
|
|
2452
|
-
key,
|
|
2453
|
-
attemptId,
|
|
2454
|
-
setStatus
|
|
2455
|
-
});
|
|
2456
|
-
record.status = result;
|
|
2457
|
-
await updateInstallAttempt(key, attemptId, {
|
|
2458
|
-
state: result.state === "ready" ? "ready" : "failed",
|
|
2459
|
-
...result.state === "failed" ? { reason: result.reason, message: result.message } : {}
|
|
2460
|
-
}).catch(() => {
|
|
2461
|
-
});
|
|
2462
|
-
return result;
|
|
2463
|
-
} catch (error) {
|
|
2464
|
-
const failure = classifyInstallFailure(error, expected.packVersion);
|
|
2465
|
-
logger.warn("[local-harness] runtime pack install failed", {
|
|
2466
|
-
reason: failure.reason,
|
|
2467
|
-
message: failure.message
|
|
2468
|
-
});
|
|
2469
|
-
record.status = failure;
|
|
2470
|
-
await updateInstallAttempt(key, attemptId, {
|
|
2471
|
-
state: "failed",
|
|
2472
|
-
reason: failure.reason,
|
|
2473
|
-
message: failure.message
|
|
2474
|
-
}).catch(() => {
|
|
2475
|
-
});
|
|
2476
|
-
return failure;
|
|
2477
|
-
} finally {
|
|
2478
|
-
active.delete(keyString);
|
|
2479
|
-
}
|
|
2480
|
-
}
|
|
2481
|
-
function classifyInstallFailure(error, packVersion) {
|
|
2482
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
2483
|
-
const code = error?.code;
|
|
2484
|
-
const causeCode = error?.cause?.code;
|
|
2485
|
-
const reason = code === "ENOSPC" || code === "EACCES" || code === "EPERM" || code === "EROFS" || code === "EDQUOT" ? "disk" : code === "ENOTFOUND" || code === "ECONNRESET" || code === "ETIMEDOUT" || code === "ECONNREFUSED" || causeCode === "ENOTFOUND" || causeCode === "ECONNRESET" || causeCode === "ETIMEDOUT" || causeCode === "ECONNREFUSED" || /could not be downloaded|responded \d{3}|fetch failed|network/i.test(
|
|
2486
|
-
message
|
|
2487
|
-
) ? "network" : /does not match|signature|signed manifest|no signed manifest|digest|exceeds its size ceiling|has no .* directory at its root/i.test(
|
|
2488
|
-
message
|
|
2489
|
-
) ? "verification" : "unknown";
|
|
2490
|
-
return { state: "failed", packVersion, reason, message };
|
|
2491
|
-
}
|
|
2492
|
-
async function performInstall(args) {
|
|
2493
|
-
const { expected, setStatus, key, attemptId } = args;
|
|
2494
|
-
const platformKey = packPlatformKey(args.platform, args.arch);
|
|
2495
|
-
const target = localPackTarget(args.platform, args.arch);
|
|
2496
|
-
const versionRoot = packVersionRoot(expected.packVersion, target);
|
|
2497
|
-
const installRoot = targetInstallRoot(target);
|
|
2498
|
-
await mkdir3(installRoot, { recursive: true, mode: 448 });
|
|
2499
|
-
await sweepAbandonedStaging(key);
|
|
2500
|
-
const staging = join5(installRoot, `${STAGING_PREFIX}${randomUUID3()}`);
|
|
2501
|
-
await mkdir3(staging, { recursive: true, mode: 448 });
|
|
2502
|
-
await claimStagingDirectory({ staging, attemptId });
|
|
2503
|
-
try {
|
|
2504
|
-
const source = packSourceFor(expected.packVersion, platformKey);
|
|
2505
|
-
const archivePath = join5(staging, "pack.tar.gz");
|
|
2506
|
-
setStatus({
|
|
2507
|
-
state: "downloading",
|
|
2508
|
-
packVersion: expected.packVersion,
|
|
2509
|
-
percent: 0,
|
|
2510
|
-
attemptId
|
|
2511
|
-
});
|
|
2512
|
-
const archiveSha = await fetchArchive({
|
|
2513
|
-
source,
|
|
2514
|
-
destination: archivePath,
|
|
2515
|
-
onPercent: (percent) => setStatus({
|
|
2516
|
-
state: "downloading",
|
|
2517
|
-
packVersion: expected.packVersion,
|
|
2518
|
-
percent,
|
|
2519
|
-
attemptId
|
|
2520
|
-
}),
|
|
2521
|
-
...args.signal ? { signal: args.signal } : {}
|
|
2522
|
-
});
|
|
2523
|
-
setStatus({
|
|
2524
|
-
state: "verifying",
|
|
2525
|
-
packVersion: expected.packVersion,
|
|
2526
|
-
attemptId
|
|
2527
|
-
});
|
|
2528
|
-
const manifest = await loadAndVerifyManifest({
|
|
2529
|
-
source,
|
|
2530
|
-
packVersion: expected.packVersion,
|
|
2531
|
-
platformKey,
|
|
2532
|
-
staging
|
|
2533
|
-
});
|
|
2534
|
-
if (manifest !== null && manifest.archive?.sha256 !== void 0) {
|
|
2535
|
-
if (manifest.archive.sha256 !== archiveSha) {
|
|
2536
|
-
throw new Error(
|
|
2537
|
-
`the downloaded runtime pack archive does not match its signed manifest (expected ${manifest.archive.sha256}, got ${archiveSha})`
|
|
2538
|
-
);
|
|
2539
|
-
}
|
|
2540
|
-
}
|
|
2541
|
-
const extractRoot = join5(staging, "extracted");
|
|
2542
|
-
await mkdir3(extractRoot, { recursive: true, mode: 448 });
|
|
2543
|
-
await extractTar({
|
|
2544
|
-
file: archivePath,
|
|
2545
|
-
cwd: extractRoot,
|
|
2546
|
-
// No links of any kind survive extraction, and nothing may be written
|
|
2547
|
-
// outside `cwd`. The digest would refuse a symlink later; refusing it
|
|
2548
|
-
// here means it never touches the disk.
|
|
2549
|
-
filter: (path, entry) => {
|
|
2550
|
-
const type = entry.type;
|
|
2551
|
-
if (type !== "File" && type !== "Directory") return false;
|
|
2552
|
-
return !path.split("/").includes("..");
|
|
2553
|
-
},
|
|
2554
|
-
preservePaths: false,
|
|
2555
|
-
strict: true
|
|
2556
|
-
});
|
|
2557
|
-
const packRoot = join5(extractRoot, args.harnessId);
|
|
2558
|
-
const info = await stat4(packRoot).catch(() => null);
|
|
2559
|
-
if (info === null || !info.isDirectory()) {
|
|
2560
|
-
throw new Error(
|
|
2561
|
-
`the runtime pack archive has no ${args.harnessId} directory at its root`
|
|
2562
|
-
);
|
|
2563
|
-
}
|
|
2564
|
-
await assertExtractedSize(packRoot);
|
|
2565
|
-
const digest = await computeTreeDigest(packRoot);
|
|
2566
|
-
if (manifest !== null && digest !== manifest.treeDigest) {
|
|
2567
|
-
throw new Error(
|
|
2568
|
-
`the extracted runtime pack does not match its signed manifest (expected ${manifest.treeDigest}, got ${digest})`
|
|
2569
|
-
);
|
|
2570
|
-
}
|
|
2571
|
-
if (digest !== expected.treeDigest) {
|
|
2572
|
-
throw new Error(
|
|
2573
|
-
`the runtime pack does not match the digest this Inspector was built with (expected ${expected.treeDigest}, got ${digest})`
|
|
2574
|
-
);
|
|
2575
|
-
}
|
|
2576
|
-
if (args.platform === "darwin") await clearQuarantine(extractRoot);
|
|
2577
|
-
await writeFile3(
|
|
2578
|
-
join5(extractRoot, INSTALL_MARKER),
|
|
2579
|
-
`${JSON.stringify(
|
|
2580
|
-
{
|
|
2581
|
-
packVersion: expected.packVersion,
|
|
2582
|
-
harnessId: args.harnessId,
|
|
2583
|
-
platform: platformKey,
|
|
2584
|
-
treeDigest: digest,
|
|
2585
|
-
installedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
2586
|
-
},
|
|
2587
|
-
null,
|
|
2588
|
-
2
|
|
2589
|
-
)}
|
|
2590
|
-
`,
|
|
2591
|
-
{ mode: 384 }
|
|
2592
|
-
);
|
|
2593
|
-
setStatus({
|
|
2594
|
-
state: "verifying",
|
|
2595
|
-
packVersion: expected.packVersion,
|
|
2596
|
-
attemptId
|
|
2597
|
-
});
|
|
2598
|
-
await updateInstallAttempt(key, attemptId, { state: "activating" });
|
|
2599
|
-
await activateVerifiedPack({
|
|
2600
|
-
key,
|
|
2601
|
-
attemptId,
|
|
2602
|
-
versionRoot,
|
|
2603
|
-
extractRoot
|
|
2604
|
-
});
|
|
2605
|
-
logger.info("[local-harness] runtime pack installed", {
|
|
2606
|
-
packVersion: expected.packVersion,
|
|
2607
|
-
platform: platformKey
|
|
2608
|
-
});
|
|
2609
|
-
return {
|
|
2610
|
-
state: "ready",
|
|
2611
|
-
packVersion: expected.packVersion,
|
|
2612
|
-
runtimeRoot: versionRoot,
|
|
2613
|
-
digest
|
|
2614
|
-
};
|
|
2615
|
-
} finally {
|
|
2616
|
-
await rm3(staging, { recursive: true, force: true }).catch(() => {
|
|
2617
|
-
});
|
|
2618
|
-
}
|
|
2619
|
-
}
|
|
2620
|
-
async function activateVerifiedPack(args) {
|
|
2621
|
-
const { key, versionRoot, extractRoot } = args;
|
|
2622
|
-
if (!await attemptStillOwns(key, args.attemptId)) {
|
|
2623
|
-
throw new Error(
|
|
2624
|
-
"another install took over this runtime while this one was downloading, so it was not activated"
|
|
2625
|
-
);
|
|
2626
|
-
}
|
|
2627
|
-
const inUse = await runtimeUseState({ key, runtimeRoot: versionRoot });
|
|
2628
|
-
if (inUse.busy) {
|
|
2629
|
-
throw new Error(
|
|
2630
|
-
`this runtime is in use by ${inUse.holders.length} running session(s) on this machine, so it was not replaced. Stop them and retry.`
|
|
2631
|
-
);
|
|
2632
|
-
}
|
|
2633
|
-
await withRuntimeLifecycleLock(key, async () => {
|
|
2634
|
-
const stillFree = await runtimeUseState({ key, runtimeRoot: versionRoot });
|
|
2635
|
-
if (stillFree.busy) {
|
|
2636
|
-
throw new Error(
|
|
2637
|
-
"a session started using this runtime while it was being replaced, so it was left alone. Stop it and retry."
|
|
2638
|
-
);
|
|
2639
|
-
}
|
|
2640
|
-
const previous = `${versionRoot}${PREVIOUS_SUFFIX}`;
|
|
2641
|
-
await rm3(previous, { recursive: true, force: true }).catch(() => {
|
|
2642
|
-
});
|
|
2643
|
-
const hasCurrent = await stat4(versionRoot).then(
|
|
2644
|
-
() => true,
|
|
2645
|
-
() => false
|
|
2646
|
-
);
|
|
2647
|
-
if (hasCurrent) await rename2(versionRoot, previous);
|
|
2648
|
-
try {
|
|
2649
|
-
await rename2(extractRoot, versionRoot);
|
|
2650
|
-
} catch (error) {
|
|
2651
|
-
if (hasCurrent) await rename2(previous, versionRoot).catch(() => {
|
|
2652
|
-
});
|
|
2653
|
-
throw error;
|
|
2654
|
-
}
|
|
2655
|
-
await rm3(previous, { recursive: true, force: true }).catch(() => {
|
|
2656
|
-
});
|
|
2657
|
-
});
|
|
2658
|
-
clearRuntimeVerificationCache();
|
|
2659
|
-
}
|
|
2660
|
-
async function assertExtractedSize(root) {
|
|
2661
|
-
let bytes = 0;
|
|
2662
|
-
const walk = async (dir) => {
|
|
2663
|
-
for (const entry of await readdir4(dir, { withFileTypes: true })) {
|
|
2664
|
-
const full = join5(dir, entry.name);
|
|
2665
|
-
if (entry.isDirectory()) {
|
|
2666
|
-
await walk(full);
|
|
2667
|
-
continue;
|
|
2668
|
-
}
|
|
2669
|
-
bytes += (await stat4(full)).size;
|
|
2670
|
-
if (bytes > MAX_EXTRACTED_BYTES) {
|
|
2671
|
-
throw new Error("the extracted runtime pack exceeds its size ceiling");
|
|
2672
|
-
}
|
|
2673
|
-
}
|
|
2674
|
-
};
|
|
2675
|
-
await walk(root);
|
|
2676
|
-
}
|
|
2677
|
-
async function clearQuarantine(root) {
|
|
2678
|
-
const { execFile: execFile3 } = await import("child_process");
|
|
2679
|
-
await new Promise((resolvePromise) => {
|
|
2680
|
-
execFile3(
|
|
2681
|
-
"/usr/bin/xattr",
|
|
2682
|
-
["-r", "-d", "com.apple.quarantine", root],
|
|
2683
|
-
{ timeout: 6e4 },
|
|
2684
|
-
() => resolvePromise()
|
|
2685
|
-
);
|
|
2686
|
-
});
|
|
2687
|
-
}
|
|
2688
|
-
async function loadAndVerifyManifest(args) {
|
|
2689
|
-
const stem = `local-harness-pack-${args.platformKey}-${args.packVersion}`;
|
|
2690
|
-
const manifestName = `${stem}.manifest.json`;
|
|
2691
|
-
const signatureName = `${manifestName}.sig`;
|
|
2692
|
-
let manifestBytes;
|
|
2693
|
-
let signature;
|
|
2694
|
-
try {
|
|
2695
|
-
if (args.source.kind === "file") {
|
|
2696
|
-
const dir = args.source.location.endsWith(".tar.gz") ? args.source.location.slice(0, -basename(args.source.location).length) : args.source.location;
|
|
2697
|
-
manifestBytes = await readFile5(join5(dir, manifestName));
|
|
2698
|
-
signature = await readFile5(join5(dir, signatureName), "utf8");
|
|
2699
|
-
} else {
|
|
2700
|
-
const base = args.source.location.slice(
|
|
2701
|
-
0,
|
|
2702
|
-
args.source.location.lastIndexOf("/") + 1
|
|
2703
|
-
);
|
|
2704
|
-
manifestBytes = Buffer.from(
|
|
2705
|
-
await (await fetchOrThrow(base + manifestName)).arrayBuffer()
|
|
2706
|
-
);
|
|
2707
|
-
signature = await (await fetchOrThrow(base + signatureName)).text();
|
|
2708
|
-
}
|
|
2709
|
-
} catch (error) {
|
|
2710
|
-
if (args.source.kind === "file") {
|
|
2711
|
-
logger.warn(
|
|
2712
|
-
"[local-harness] local pack source has no signed manifest; installing on the digest alone",
|
|
2713
|
-
{ message: error instanceof Error ? error.message : String(error) }
|
|
2714
|
-
);
|
|
2715
|
-
return null;
|
|
2716
|
-
}
|
|
2717
|
-
throw new Error(
|
|
2718
|
-
`the runtime pack has no signed manifest alongside it, so it cannot be shown to have come from MCPJam`
|
|
2719
|
-
);
|
|
2720
|
-
}
|
|
2721
|
-
if (manifestBytes.length > MAX_MANIFEST_BYTES) {
|
|
2722
|
-
throw new Error("the runtime pack manifest is implausibly large");
|
|
2723
|
-
}
|
|
2724
|
-
const verified = verifyPackManifestSignature(manifestBytes, signature);
|
|
2725
|
-
if (!verified.ok) {
|
|
2726
|
-
if (args.source.kind === "file") {
|
|
2727
|
-
logger.warn(
|
|
2728
|
-
"[local-harness] local pack manifest signature not verified; installing on the digest alone",
|
|
2729
|
-
{ reason: verified.reason }
|
|
2730
|
-
);
|
|
2731
|
-
return null;
|
|
2732
|
-
}
|
|
2733
|
-
throw new Error(verified.message);
|
|
2734
|
-
}
|
|
2735
|
-
const manifest = JSON.parse(manifestBytes.toString("utf8"));
|
|
2736
|
-
if (manifest.packVersion !== args.packVersion) {
|
|
2737
|
-
throw new Error(
|
|
2738
|
-
`the signed manifest is for pack version ${manifest.packVersion}, not ${args.packVersion}`
|
|
2739
|
-
);
|
|
2740
|
-
}
|
|
2741
|
-
if (manifest.platform !== args.platformKey) {
|
|
2742
|
-
throw new Error(
|
|
2743
|
-
`the signed manifest is for ${manifest.platform}, not ${args.platformKey}`
|
|
2744
|
-
);
|
|
2745
|
-
}
|
|
2746
|
-
return manifest;
|
|
2747
|
-
}
|
|
2748
|
-
async function fetchOrThrow(url) {
|
|
2749
|
-
const response = await fetch(url);
|
|
2750
|
-
if (!response.ok) {
|
|
2751
|
-
throw new Error(`${url} responded ${response.status}`);
|
|
2752
|
-
}
|
|
2753
|
-
return response;
|
|
2754
|
-
}
|
|
2755
|
-
async function fetchArchive(args) {
|
|
2756
|
-
const hash = createHash2("sha256");
|
|
2757
|
-
let received = 0;
|
|
2758
|
-
let total = 0;
|
|
2759
|
-
const track = new TransformStream({
|
|
2760
|
-
transform(chunk, controller) {
|
|
2761
|
-
hash.update(chunk);
|
|
2762
|
-
received += chunk.byteLength;
|
|
2763
|
-
if (received > MAX_ARCHIVE_BYTES) {
|
|
2764
|
-
throw new Error("the runtime pack archive exceeds its size ceiling");
|
|
2765
|
-
}
|
|
2766
|
-
if (total > 0) {
|
|
2767
|
-
args.onPercent(Math.min(99, Math.floor(received / total * 100)));
|
|
2768
|
-
}
|
|
2769
|
-
controller.enqueue(chunk);
|
|
2770
|
-
}
|
|
2771
|
-
});
|
|
2772
|
-
if (args.source.kind === "file") {
|
|
2773
|
-
const path = args.source.location;
|
|
2774
|
-
const info = await stat4(path);
|
|
2775
|
-
total = info.size;
|
|
2776
|
-
if (total > MAX_ARCHIVE_BYTES) {
|
|
2777
|
-
throw new Error("the runtime pack archive exceeds its size ceiling");
|
|
2778
|
-
}
|
|
2779
|
-
await pipeline(
|
|
2780
|
-
createReadStream(path),
|
|
2781
|
-
async function* (chunks) {
|
|
2782
|
-
for await (const chunk of chunks) {
|
|
2783
|
-
const buffer = chunk;
|
|
2784
|
-
hash.update(buffer);
|
|
2785
|
-
received += buffer.byteLength;
|
|
2786
|
-
args.onPercent(Math.min(99, Math.floor(received / total * 100)));
|
|
2787
|
-
yield buffer;
|
|
2788
|
-
}
|
|
2789
|
-
},
|
|
2790
|
-
createWriteStream(args.destination, { mode: 384 })
|
|
2791
|
-
);
|
|
2792
|
-
return hash.digest("hex");
|
|
2793
|
-
}
|
|
2794
|
-
const response = await fetch(args.source.location, {
|
|
2795
|
-
...args.signal ? { signal: args.signal } : {}
|
|
2796
|
-
});
|
|
2797
|
-
if (!response.ok || response.body === null) {
|
|
2798
|
-
throw new Error(
|
|
2799
|
-
`the runtime pack could not be downloaded: ${args.source.location} responded ${response.status}`
|
|
2800
|
-
);
|
|
2801
|
-
}
|
|
2802
|
-
const declared = Number(response.headers.get("content-length") ?? "0");
|
|
2803
|
-
if (declared > MAX_ARCHIVE_BYTES) {
|
|
2804
|
-
throw new Error("the runtime pack archive exceeds its size ceiling");
|
|
2805
|
-
}
|
|
2806
|
-
total = declared;
|
|
2807
|
-
await pipeline(
|
|
2808
|
-
Readable.fromWeb(
|
|
2809
|
-
response.body.pipeThrough(track)
|
|
2810
|
-
),
|
|
2811
|
-
createWriteStream(args.destination, { mode: 384 })
|
|
2812
|
-
);
|
|
2813
|
-
args.onPercent(100);
|
|
2814
|
-
return hash.digest("hex");
|
|
2815
|
-
}
|
|
2816
|
-
function reportLocalHarnessRuntimeStatusInBackground() {
|
|
2817
|
-
void (async () => {
|
|
2818
|
-
try {
|
|
2819
|
-
const status = await readRuntimeInstallStatus({
|
|
2820
|
-
harnessId: "claude-code"
|
|
2821
|
-
});
|
|
2822
|
-
if (status.state === "ready") {
|
|
2823
|
-
logger.info("[local-harness] runtime pack present", {
|
|
2824
|
-
packVersion: status.packVersion
|
|
2825
|
-
});
|
|
2826
|
-
return;
|
|
2827
|
-
}
|
|
2828
|
-
logger.debug("[local-harness] no runtime pack installed", {
|
|
2829
|
-
state: status.state,
|
|
2830
|
-
expected: EXPECTED_PACK_VERSION || "(none built)"
|
|
2831
|
-
});
|
|
2832
|
-
} catch {
|
|
2833
|
-
}
|
|
2834
|
-
})();
|
|
2835
|
-
}
|
|
2836
|
-
|
|
2837
|
-
export {
|
|
2838
|
-
resolveEnvironment,
|
|
2839
|
-
resolveAppVersion,
|
|
2840
|
-
resolveRelease,
|
|
2841
|
-
redactSecretShapes,
|
|
2842
|
-
markOriginCaptureHandled,
|
|
2843
|
-
ensureStampable,
|
|
2844
|
-
isOriginCaptureHandled,
|
|
2845
|
-
captureOriginErrorToSentry,
|
|
2846
|
-
logger,
|
|
2847
|
-
localPackTarget,
|
|
2848
|
-
LOCAL_HARNESS_POLICY_VERSION,
|
|
2849
|
-
LOCAL_ISOLATION_POLICY_VERSION,
|
|
2850
|
-
currentLocalPlatform,
|
|
2851
|
-
probeProcess,
|
|
2852
|
-
readProcessBirthIdentity,
|
|
2853
|
-
supportsOwnershipProof,
|
|
2854
|
-
listGroupMembers,
|
|
2855
|
-
terminateOwnedProcess,
|
|
2856
|
-
probeProcessGroup,
|
|
2857
|
-
readProcessGroupId,
|
|
2858
|
-
terminateOwnedProcessGroup,
|
|
2859
|
-
resolveManagedBundle,
|
|
2860
|
-
resolveSystemInstall,
|
|
2861
|
-
revalidateRuntime,
|
|
2862
|
-
LOCAL_HARNESS_MANIFEST,
|
|
2863
|
-
localPermissionModeFor,
|
|
2864
|
-
resolveLocalCompatibility,
|
|
2865
|
-
createLocalStateMutationLock,
|
|
2866
|
-
reserveRuntimeUse,
|
|
2867
|
-
runtimeInstallRoot,
|
|
2868
|
-
expectedPackFor,
|
|
2869
|
-
readRuntimeInstallStatus,
|
|
2870
|
-
manifestWithExpectedBundleDigest,
|
|
2871
|
-
readVerifiedRuntimeStatus,
|
|
2872
|
-
startRuntimeInstall,
|
|
2873
|
-
installRuntimePack,
|
|
2874
|
-
reportLocalHarnessRuntimeStatusInBackground
|
|
2875
|
-
};
|
|
2876
|
-
//# sourceMappingURL=chunk-WZVZ6LQX.js.map
|