@mcpjam/inspector 3.13.0 → 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.
Files changed (46) hide show
  1. package/bin/runtime-profile.mjs +774 -0
  2. package/bin/start.js +117 -24
  3. package/dist/client/assets/{OAuthDesktopReturnNotice-D5tJNqny.js → OAuthDesktopReturnNotice-D7d-faB1.js} +2 -2
  4. package/dist/client/assets/{app-bootstrap-baadQQNk.js → app-bootstrap-BtDjj9nz.js} +350 -350
  5. package/dist/client/assets/{button-DHPqnOj6.js → button-B99pZFz_.js} +2 -2
  6. package/dist/client/assets/{chunk-D32TOXHM-BPB6AqSK.js → chunk-D32TOXHM-Bcyg0ZVj.js} +5 -5
  7. package/dist/client/assets/{dead-clicks-autocapture-Cbczl2El.js → dead-clicks-autocapture-CnUHv5CB.js} +2 -2
  8. package/dist/client/assets/{error-reporting-CORfsjyM.js → error-reporting-BohBwcQQ.js} +4 -4
  9. package/dist/client/assets/{error-reporting-B4hGM_ob.js → error-reporting-p6G1ojum.js} +1 -1
  10. package/dist/client/assets/{exception-autocapture-CMOUrnel.js → exception-autocapture-Q-isBTHp.js} +2 -2
  11. package/dist/client/assets/{failed-request-tracker-DoQRXuIy.js → failed-request-tracker-BBJW8izb.js} +2 -2
  12. package/dist/client/assets/{highlighted-body-KQOG7T2V-_ljE4u1k.js → highlighted-body-KQOG7T2V-zsXWRnSM.js} +2 -2
  13. package/dist/client/assets/{index-BBr8TZVx.js → index-C9oFRqoK.js} +3 -3
  14. package/dist/client/assets/{jszip.min-C-vIQbxH.js → jszip.min-C86zG41a.js} +2 -2
  15. package/dist/client/assets/{mermaid-MCJ5UELQ-DTJaEEBm.js → mermaid-MCJ5UELQ-DAW4LYwz.js} +1 -1
  16. package/dist/client/assets/{posthog-recorder-Dby9Z8HR.js → posthog-recorder-trUd0BXy.js} +2 -2
  17. package/dist/client/assets/{preload-helper-Dvt1a6xa.js → preload-helper-Buauuydw.js} +2 -2
  18. package/dist/client/assets/{react-CD7Pk4KS.js → react-CZb-kDOs.js} +2 -2
  19. package/dist/client/assets/{rolldown-runtime-mzU9SaVm.js → rolldown-runtime-Bkua2_Tb.js} +1 -1
  20. package/dist/client/assets/{surveys-DYqpu8xl.js → surveys-BISK_WOT.js} +2 -2
  21. package/dist/client/assets/{trace-timeline-PnE1ouRj.js → trace-timeline-CRewsP1E.js} +2 -2
  22. package/dist/client/assets/{trace-timeline-WXINST5z.js → trace-timeline-D-DWE-sO.js} +1 -1
  23. package/dist/client/assets/{web-vitals-BLq6M5vx.js → web-vitals-DqmZ9w02.js} +2 -2
  24. package/dist/client/index.html +7 -7
  25. package/dist/server/authorization-MA42CNYT.js +22 -0
  26. package/dist/server/chunk-7M3XVZCQ.js +381 -0
  27. package/dist/server/{chunk-MBS3EZ3U.js → chunk-7ZIR7SX7.js} +5 -44
  28. package/dist/server/chunk-C47PTIDS.js +487 -0
  29. package/dist/server/chunk-DHRTCKJA.js +3979 -0
  30. package/dist/server/chunk-HJTKF2X6.js +45 -0
  31. package/dist/server/{chunk-2FVSBJQF.js → chunk-KNO4KZJF.js} +224 -758
  32. package/dist/server/{chunk-QHYREDE3.js → chunk-RWFTW2EW.js} +7 -5
  33. package/dist/server/chunk-SDWJSPSI.js +252 -0
  34. package/dist/server/chunk-VFRLMHOC.js +33 -0
  35. package/dist/server/chunk-XSQ2GC45.js +438 -0
  36. package/dist/server/chunk-YQ2BTE46.js +88 -0
  37. package/dist/server/{consent-lifetime-TYLDY64H.js → consent-lifetime-OXQM37RV.js} +4 -3
  38. package/dist/server/grants-UVE62NGN.js +37 -0
  39. package/dist/server/harness-install-cli.js +239 -4
  40. package/dist/server/index.js +9044 -9216
  41. package/dist/server/local-turn-XSUGEKTL.js +19 -0
  42. package/dist/server/runtime-health-TCF3ZEKS.js +28 -0
  43. package/dist/server/runtime-lifecycle-YQ3KWDLJ.js +53 -0
  44. package/package.json +26 -23
  45. package/dist/server/chunk-I7ZVTBZP.js +0 -3100
  46. package/dist/server/local-turn-VQDSTY6T.js +0 -12
@@ -1,3100 +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.13.0";
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 SUPPORTED_LOCAL_HARNESS_IDS = [
372
- "claude-code",
373
- "codex"
374
- ];
375
- var LOCAL_PACK_TARGETS = /* @__PURE__ */ new Set([
376
- "darwin-arm64",
377
- "darwin-x64",
378
- "linux-x64",
379
- "linux-arm64",
380
- "win32-x64"
381
- ]);
382
- function localPackTarget(platform = process.platform, arch = process.arch) {
383
- const key = `${platform}-${arch}`;
384
- return LOCAL_PACK_TARGETS.has(key) ? key : null;
385
- }
386
- var LOCAL_HARNESS_POLICY_VERSION = "local-harness-policy-2026-09-28";
387
- var LOCAL_ISOLATION_POLICY_VERSION = "local-isolation-policy-2026-09-01";
388
- function currentLocalPlatform(platform = process.platform) {
389
- if (platform === "darwin" || platform === "linux" || platform === "win32") {
390
- return platform;
391
- }
392
- return null;
393
- }
394
-
395
- // server/utils/harness/codex-appserver/local-identity.ts
396
- import { createHash } from "crypto";
397
-
398
- // server/utils/harness/codex-appserver/bootstrap/generated/codex-appserver-bridge.bundled.ts
399
- var CODEX_APPSERVER_BRIDGE_SOURCE = '// Generated by scripts/bundle-codex-appserver-bridge.mjs \u2014 do not edit.\n\n// server/utils/harness/codex-appserver/bridge/index.ts\nimport { mkdirSync as mkdirSync2 } from "node:fs";\nimport { join as join2 } from "node:path";\n\n// node_modules/@ai-sdk/harness/dist/bridge/index.js\nimport { appendFile, mkdir, writeFile } from "fs/promises";\nimport { existsSync, readFileSync } from "fs";\nimport { randomUUID } from "crypto";\nimport { env as procEnv, pid, stdout } from "process";\nimport { WebSocketServer } from "ws";\nvar DEBUG_LEVEL_WEIGHT = {\n error: 0,\n warn: 1,\n info: 2,\n debug: 3,\n trace: 4\n};\nfunction subsystemMatches(filters, subsystem) {\n if (!filters || filters.length === 0) return true;\n return filters.some(\n (filter) => subsystem === filter || subsystem.startsWith(`${filter}.`)\n );\n}\nfunction formatBridgeError(err) {\n if (err instanceof Error) {\n return { name: err.name, message: err.message, stack: err.stack };\n }\n if (typeof err === "string") {\n return { message: err };\n }\n if (err !== null && typeof err === "object") {\n try {\n return { message: JSON.stringify(err) };\n } catch {\n }\n }\n return { message: String(err) };\n}\nfunction createBridgeUserMessageQueue(options) {\n const messages = [];\n const waiters = [];\n const entries = /* @__PURE__ */ new Map();\n let closed = false;\n let pendingCount = 0;\n const enqueue = (input) => {\n const existing = entries.get(input.messageId);\n if (existing != null) {\n if (existing.response != null) {\n options.respond(existing.response);\n }\n return;\n }\n let settled = false;\n const settle = (response) => {\n if (settled) return;\n settled = true;\n pendingCount--;\n const entry = entries.get(input.messageId);\n if (entry != null) entry.response = response;\n options.respond(response);\n };\n const message = {\n messageId: input.messageId,\n text: input.text,\n accept: () => {\n settle({\n type: "user-message-response",\n messageId: input.messageId,\n accepted: true\n });\n },\n reject: (error) => {\n settle({\n type: "user-message-response",\n messageId: input.messageId,\n accepted: false,\n error: { message: formatBridgeError(error).message }\n });\n }\n };\n entries.set(input.messageId, {\n reject: message.reject\n });\n pendingCount++;\n if (closed) {\n message.reject(\n new Error("The bridge turn is no longer accepting user messages.")\n );\n return;\n }\n const waiter = waiters.shift();\n if (waiter != null) {\n waiter({ done: false, value: message });\n } else {\n messages.push(message);\n }\n };\n const close = (error) => {\n if (closed) return;\n closed = true;\n const reason = error ?? new Error("The bridge turn ended before accepting the user message.");\n for (const entry of entries.values()) {\n if (entry.response == null) entry.reject(reason);\n }\n messages.length = 0;\n while (waiters.length > 0) {\n waiters.shift()({ done: true, value: void 0 });\n }\n };\n return {\n get pendingCount() {\n return pendingCount;\n },\n enqueue,\n close,\n [Symbol.asyncIterator]() {\n return {\n next: () => {\n const message = messages.shift();\n if (message != null) {\n return Promise.resolve({ done: false, value: message });\n }\n if (closed) {\n return Promise.resolve({\n done: true,\n value: void 0\n });\n }\n return new Promise(\n (resolve) => {\n waiters.push(resolve);\n }\n );\n }\n };\n }\n };\n}\nfunction parseEnvList(value) {\n if (!value) return void 0;\n const items = value.split(",").map((item) => item.trim()).filter(Boolean);\n return items.length > 0 ? items : void 0;\n}\nvar ENV_TRUTHY = /* @__PURE__ */ new Set(["1", "true", "yes", "on"]);\nvar WS_OPEN = 1;\nasync function runBridge(options) {\n const { bridgeType, bridgeStateDir, onStart, onStop, onDestroy } = options;\n const teardownGraceMs = options.turnTeardownGraceMs ?? 1e4;\n const expectedToken = options.token ?? procEnv.BRIDGE_CHANNEL_TOKEN ?? "";\n const bridgeWsPort = options.port ?? parseInt(procEnv.BRIDGE_WS_PORT ?? "0", 10);\n const bridgeMetaPath = `${bridgeStateDir}/bridge-meta.json`;\n const startConfigPath = `${bridgeStateDir}/start-config.json`;\n const rerunStartConfigPath = `${bridgeStateDir}/rerun-start-config.json`;\n const eventLogPath = `${bridgeStateDir}/event-log.ndjson`;\n try {\n await mkdir(bridgeStateDir, { recursive: true });\n } catch {\n }\n let currentBoundPort = 0;\n let currentTurnState = "init";\n let activeSocket;\n let isFirstTurn = true;\n let turnAbort;\n let currentUserMessages;\n let activeTurn;\n let debugConfig;\n let consoleCaptureInstalled = false;\n const envDebugEnabled = ENV_TRUTHY.has(\n (procEnv.HARNESS_DEBUG ?? "").toLowerCase()\n );\n let seqCounter = 0;\n let eventLog = [];\n let diskBuffer = "";\n let flushPromise = null;\n const flushEventsToDisk = async () => {\n while (diskBuffer.length > 0) {\n const buf = diskBuffer;\n diskBuffer = "";\n await appendFile(eventLogPath, buf).catch(() => {\n });\n }\n };\n const scheduleEventFlush = () => {\n if (flushPromise) return;\n flushPromise = new Promise((resolve) => {\n setImmediate(() => {\n void flushEventsToDisk().finally(resolve);\n });\n }).finally(() => {\n flushPromise = null;\n if (diskBuffer.length > 0) {\n scheduleEventFlush();\n }\n });\n };\n const flushPendingEventsToDisk = async () => {\n if (diskBuffer.length > 0 && !flushPromise) {\n scheduleEventFlush();\n }\n let inFlight = flushPromise;\n while (inFlight) {\n await inFlight;\n inFlight = flushPromise;\n }\n };\n const replayFromDisk = procEnv.BRIDGE_REPLAY_FROM_DISK === "1";\n if (replayFromDisk && existsSync(eventLogPath)) {\n try {\n const lines = readFileSync(eventLogPath, "utf8").split("\\n").map((line) => line.trim()).filter(Boolean);\n eventLog = lines.map((line) => ({\n seq: JSON.parse(line).seq,\n line\n }));\n seqCounter = eventLog.at(-1)?.seq ?? 0;\n } catch {\n eventLog = [];\n seqCounter = 0;\n }\n }\n const pendingToolResults = /* @__PURE__ */ new Map();\n const pendingToolApprovals = /* @__PURE__ */ new Map();\n const writeBridgeMeta = async (state) => {\n try {\n await writeFile(\n bridgeMetaPath,\n JSON.stringify({\n type: bridgeType,\n port: currentBoundPort,\n state,\n pid\n })\n );\n } catch {\n }\n };\n const writeStartConfig = async (start) => {\n try {\n const serialized = JSON.stringify(start);\n await writeFile(startConfigPath, serialized);\n if (!existsSync(rerunStartConfigPath)) {\n await writeFile(rerunStartConfigPath, serialized);\n }\n } catch {\n }\n };\n const emit = (event) => {\n const seq = ++seqCounter;\n const line = JSON.stringify({ ...event, seq });\n eventLog.push({ seq, line });\n diskBuffer += `${line}\n`;\n scheduleEventFlush();\n if (activeSocket?.readyState === WS_OPEN) {\n try {\n activeSocket.send(line);\n } catch {\n }\n }\n };\n const replay = (ws, afterSeq) => {\n for (const entry of eventLog) {\n if (entry.seq > afterSeq && ws.readyState === WS_OPEN) {\n ws.send(entry.line);\n }\n }\n };\n const shouldEmitDebugEvent = (level, subsystem) => {\n if (!debugConfig?.enabled) return false;\n const threshold = debugConfig.level ?? "debug";\n if (DEBUG_LEVEL_WEIGHT[level] > DEBUG_LEVEL_WEIGHT[threshold]) return false;\n return subsystemMatches(debugConfig.subsystems, subsystem);\n };\n const rawStdoutWrite = process.stdout.write.bind(process.stdout);\n const rawStderrWrite = process.stderr.write.bind(process.stderr);\n const writeErrorToStderr = (input) => {\n try {\n const formatted = formatBridgeError(input.error);\n rawStderrWrite(\n `[harness:${bridgeType}:error] ${input.message}: ${formatted.message}\n`\n );\n if (formatted.stack) {\n rawStderrWrite(`${formatted.stack}\n`);\n }\n } catch {\n }\n };\n const emitWarning = (input) => {\n try {\n for (const line of input.message.split("\\n")) {\n if (line.trim().length > 0) {\n rawStderrWrite(`[harness:${bridgeType}:warn] ${line}\n`);\n }\n }\n } catch {\n }\n };\n const emitError = (input) => {\n writeErrorToStderr({\n message: input.message ?? "bridge error",\n error: input.error\n });\n emit({ type: "error", error: serialiseError(input.error) });\n };\n const installConsoleCapture = () => {\n if (consoleCaptureInstalled) return;\n consoleCaptureInstalled = true;\n const buffers = {\n stdout: "",\n stderr: ""\n };\n const patch = (stream, raw) => (chunk, encoding, cb) => {\n if (debugConfig?.enabled) {\n try {\n const enc = typeof encoding === "string" ? encoding : "utf8";\n const text = typeof chunk === "string" ? chunk : Buffer.from(chunk).toString(\n enc\n );\n const combined = buffers[stream] + text.replace(/\\r\\n/g, "\\n");\n const parts = combined.split("\\n");\n buffers[stream] = parts.pop() ?? "";\n for (const line of parts) {\n const trimmed = line.replace(/\\s+$/, "");\n if (trimmed) {\n emit({\n type: "sandbox-log",\n source: bridgeType,\n stream,\n line: trimmed\n });\n }\n }\n } catch {\n }\n }\n return raw(\n chunk,\n encoding,\n cb\n );\n };\n process.stdout.write = patch(\n "stdout",\n rawStdoutWrite\n );\n process.stderr.write = patch(\n "stderr",\n rawStderrWrite\n );\n };\n const handleInbound = async (msg, ws) => {\n switch (msg.type) {\n case "start": {\n for (; ; ) {\n const pendingTurn = activeTurn;\n if (pendingTurn == null) break;\n turnAbort?.abort();\n currentUserMessages?.close(\n new Error("A new bridge turn replaced the active turn.")\n );\n let graceTimer;\n const settled = await Promise.race([\n pendingTurn.then(() => true),\n new Promise((resolve) => {\n graceTimer = setTimeout(() => resolve(false), teardownGraceMs);\n graceTimer.unref?.();\n })\n ]);\n clearTimeout(graceTimer);\n if (!settled) break;\n }\n let turnFinished;\n const thisTurn = new Promise((resolve) => turnFinished = resolve);\n activeTurn = thisTurn;\n activeSocket = ws;\n const firstTurn = isFirstTurn;\n isFirstTurn = false;\n eventLog = [];\n diskBuffer = "";\n void writeFile(eventLogPath, "").catch(() => {\n });\n turnAbort = new AbortController();\n currentTurnState = "running";\n void writeStartConfig(msg);\n void writeBridgeMeta("running");\n const startDebug = msg.debug;\n debugConfig = {\n enabled: startDebug?.enabled ?? envDebugEnabled,\n level: startDebug?.level ?? procEnv.HARNESS_DEBUG_LEVEL,\n subsystems: startDebug?.subsystems ?? parseEnvList(procEnv.HARNESS_DEBUG_SUBSYSTEMS)\n };\n if (debugConfig.enabled) {\n installConsoleCapture();\n }\n const userMessages = createBridgeUserMessageQueue({ respond: emit });\n const turn = {\n emit,\n requestToolResult: (toolCallId) => new Promise((resolve) => {\n pendingToolResults.set(toolCallId, resolve);\n }),\n requestToolApproval: (approvalId) => new Promise((resolve) => {\n pendingToolApprovals.set(approvalId, resolve);\n }),\n experimental_userMessages: userMessages,\n abortSignal: turnAbort.signal,\n firstTurn,\n bridgeLog: (input) => {\n const level = input.level ?? "debug";\n if (!shouldEmitDebugEvent(level, input.subsystem)) return;\n emit({\n type: "debug-event",\n level,\n subsystem: input.subsystem,\n message: input.message,\n ...input.attrs ? { attrs: input.attrs } : {},\n ...input.error !== void 0 ? { error: formatBridgeError(input.error) } : {}\n });\n },\n emitWarning,\n emitError\n };\n currentUserMessages = userMessages;\n try {\n await onStart(msg, turn);\n } catch (err) {\n emitError({ error: err, message: "bridge turn failed" });\n } finally {\n userMessages.close();\n if (currentUserMessages === userMessages) {\n currentUserMessages = void 0;\n }\n if (activeTurn === thisTurn) {\n activeTurn = void 0;\n currentTurnState = "waiting";\n void writeBridgeMeta("waiting");\n }\n turnFinished();\n }\n return;\n }\n case "tool-result": {\n const resolver = pendingToolResults.get(msg.toolCallId);\n if (resolver) {\n pendingToolResults.delete(msg.toolCallId);\n resolver({ output: msg.output, isError: msg.isError });\n }\n return;\n }\n case "tool-approval-response": {\n const resolver = pendingToolApprovals.get(msg.approvalId);\n if (resolver) {\n pendingToolApprovals.delete(msg.approvalId);\n resolver({ approved: msg.approved, reason: msg.reason });\n }\n return;\n }\n case "user-message": {\n const messageId = msg.messageId ?? randomUUID();\n if (currentUserMessages == null) {\n sendControl(ws, {\n type: "user-message-response",\n messageId,\n accepted: false,\n error: { message: "The bridge has no active turn to steer." }\n });\n return;\n }\n if (ws !== activeSocket) {\n sendControl(ws, {\n type: "user-message-response",\n messageId,\n accepted: false,\n error: {\n message: "The connection does not own the active bridge turn."\n }\n });\n return;\n }\n currentUserMessages.enqueue({\n messageId,\n text: msg.text\n });\n return;\n }\n case "abort":\n turnAbort?.abort();\n return;\n case "resume":\n activeSocket = ws;\n replay(ws, msg.lastSeenEventId);\n return;\n case "destroy":\n currentTurnState = "done";\n void writeBridgeMeta("done");\n await onDestroy?.();\n drainThenExit(ws, 1e3, "destroy");\n return;\n case "stop": {\n currentTurnState = "done";\n void writeBridgeMeta("done");\n const data = await onStop?.() ?? {};\n sendControl(ws, { type: "bridge-stop", data });\n drainThenExit(ws, 1e3, "stop");\n return;\n }\n }\n };\n void writeBridgeMeta("init");\n const wss = new WebSocketServer({ port: bridgeWsPort, host: "0.0.0.0" });\n const exit = () => {\n if (options.onExit) {\n options.onExit();\n return;\n }\n wss.close(() => process.exit(0));\n setTimeout(() => process.exit(0), 1e3).unref();\n };\n const drainThenExit = (ws, code, reason) => {\n const start = Date.now();\n const tick = () => {\n const drained = ws.bufferedAmount === 0 || ws.readyState !== WS_OPEN;\n if (drained || Date.now() - start >= 5e3) {\n void flushPendingEventsToDisk().finally(() => {\n try {\n ws.close(code, reason);\n } finally {\n exit();\n }\n });\n return;\n }\n setTimeout(tick, 10).unref();\n };\n tick();\n };\n wss.on("listening", () => {\n const addr = wss.address();\n currentBoundPort = typeof addr === "object" && addr ? addr.port : 0;\n currentTurnState = "waiting";\n void writeBridgeMeta("waiting");\n stdout.write(\n JSON.stringify({\n type: "bridge-ready",\n port: currentBoundPort\n }) + "\\n"\n );\n options.onListening?.(currentBoundPort);\n });\n wss.on("connection", (ws, req) => {\n const url = new URL(req.url ?? "/", "http://localhost");\n if (url.searchParams.get("agent_bridge_token") !== expectedToken) {\n ws.close(1008, "unauthorized");\n return;\n }\n sendControl(ws, {\n type: "bridge-hello",\n state: currentTurnState,\n lastSeq: seqCounter,\n capabilities: { experimental_userMessageResponses: true }\n });\n ws.on("message", (raw) => {\n let parsed;\n try {\n const text = typeof raw === "string" ? raw : Buffer.from(raw).toString("utf8");\n parsed = JSON.parse(text);\n } catch (err) {\n sendControl(ws, {\n type: "error",\n error: `protocol parse error: ${err.message}`\n });\n return;\n }\n void handleInbound(parsed, ws);\n });\n ws.on("close", () => {\n if (activeSocket === ws) {\n activeSocket = void 0;\n }\n });\n ws.on("error", () => {\n });\n });\n process.on("uncaughtException", (err) => {\n emitError({ error: err, message: "uncaught exception" });\n });\n process.on("unhandledRejection", (err) => {\n emitError({ error: err, message: "unhandled rejection" });\n });\n await new Promise((resolve, reject) => {\n if (wss.address() != null) {\n resolve();\n return;\n }\n wss.once("listening", resolve);\n wss.once("error", reject);\n });\n return {\n port: currentBoundPort,\n close: () => new Promise((resolve) => {\n wss.close(() => resolve());\n })\n };\n}\nfunction sendControl(socket, message) {\n if (socket?.readyState === WS_OPEN) {\n try {\n socket.send(JSON.stringify(message));\n } catch {\n }\n }\n}\nfunction serialiseError(err) {\n if (err instanceof Error) {\n return { name: err.name, message: err.message, stack: err.stack };\n }\n return err;\n}\n\n// server/utils/harness/codex-appserver/shared/tool-names.ts\nvar RELAY_MCP_SERVER_NAME = "mcpjam";\nvar MCPJAM_MCP_TOOL_PREFIX = "mcp__";\nfunction aliasHostToolName(hostToolName) {\n return hostToolName.startsWith(MCPJAM_MCP_TOOL_PREFIX) ? hostToolName.slice(MCPJAM_MCP_TOOL_PREFIX.length) : hostToolName;\n}\nfunction buildHostToolAliases(hostToolNames) {\n const reserved = new Set(hostToolNames);\n const claimed = /* @__PURE__ */ new Set();\n const aliasToCanonical = /* @__PURE__ */ new Map();\n const canonicalToAlias = /* @__PURE__ */ new Map();\n for (const name of hostToolNames) {\n const stripped = aliasHostToolName(name);\n const canUseStripped = stripped !== name && !reserved.has(stripped) && !claimed.has(stripped);\n const alias = canUseStripped ? stripped : name;\n claimed.add(alias);\n aliasToCanonical.set(alias, name);\n canonicalToAlias.set(name, alias);\n }\n return { aliasToCanonical, canonicalToAlias };\n}\nvar CODEX_APPSERVER_TOOL_NAMES = {\n commandExecution: "bash",\n fileChange: "fileChange",\n webSearch: "webSearch"\n};\nvar CODEX_APPSERVER_NATIVE_TOOL_NAMES = {\n commandExecution: "exec_command",\n fileChange: "apply_patch",\n webSearch: "web_search"\n};\n\n// server/utils/harness/codex-appserver/shared/turn-fingerprint.ts\nfunction stableStringify(value) {\n if (value === null || typeof value !== "object")\n return JSON.stringify(value) ?? "null";\n if (Array.isArray(value)) {\n return `[${value.map((item) => stableStringify(item)).join(",")}]`;\n }\n const entries = Object.entries(value).filter(([, v]) => v !== void 0).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);\n return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${stableStringify(v)}`).join(",")}}`;\n}\nfunction toolCatalogFingerprint(tools) {\n return stableStringify(\n [...tools].map((tool) => ({\n name: tool.name,\n description: tool.description ?? "",\n inputSchema: tool.inputSchema ?? null\n })).sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0)\n );\n}\nfunction runtimeConfigFingerprint(input) {\n return stableStringify({\n webSearch: input.webSearch ?? false,\n tools: toolCatalogFingerprint(input.tools ?? [])\n });\n}\nfunction turnConfigurationFingerprintInput(input) {\n return stableStringify({\n instructions: input.instructions ?? "",\n tools: toolCatalogFingerprint(input.tools)\n });\n}\n\n// server/utils/harness/codex-appserver/shared/sandbox-policy.ts\nfunction parseWorkspaceWriteSandboxPolicy(value) {\n if (typeof value !== "object" || value === null || Array.isArray(value)) {\n return null;\n }\n const record = value;\n const expected = [\n "excludeSlashTmp",\n "excludeTmpdirEnvVar",\n "networkAccess",\n "type",\n "writableRoots"\n ];\n const keys = Object.keys(record).sort();\n if (keys.length !== expected.length || keys.some((key, i) => key !== expected[i])) {\n return null;\n }\n if (record.type !== "workspaceWrite" || !Array.isArray(record.writableRoots) || !record.writableRoots.every((root) => typeof root === "string") || typeof record.networkAccess !== "boolean" || typeof record.excludeSlashTmp !== "boolean" || typeof record.excludeTmpdirEnvVar !== "boolean") {\n return null;\n }\n return {\n type: "workspaceWrite",\n writableRoots: [...record.writableRoots],\n networkAccess: record.networkAccess,\n excludeSlashTmp: record.excludeSlashTmp,\n excludeTmpdirEnvVar: record.excludeTmpdirEnvVar\n };\n}\nvar LOCAL_UNATTENDED_SANDBOX_POLICY = Object.freeze({\n type: "workspaceWrite",\n writableRoots: [],\n networkAccess: false,\n excludeSlashTmp: true,\n excludeTmpdirEnvVar: false\n});\nfunction sandboxPolicyFingerprint(policy) {\n if (policy === void 0) return "none";\n return JSON.stringify({\n type: policy.type,\n writableRoots: [...policy.writableRoots].sort(),\n networkAccess: policy.networkAccess,\n excludeSlashTmp: policy.excludeSlashTmp,\n excludeTmpdirEnvVar: policy.excludeTmpdirEnvVar\n });\n}\n\n// server/utils/harness/codex-appserver/bridge/app-server-client.ts\nimport { spawn } from "node:child_process";\nvar AppServerExitedError = class extends Error {\n code;\n signal;\n constructor(code, signal, tail) {\n super(\n `codex app-server exited (code=${code ?? "null"} signal=${signal ?? "null"})` + (tail ? `: ${tail}` : "")\n );\n this.name = "AppServerExitedError";\n this.code = code;\n this.signal = signal;\n }\n};\nfunction spawnAppServerClient(options) {\n const child = spawn(\n options.command,\n options.args ?? ["app-server"],\n { cwd: options.cwd, env: options.env, stdio: ["pipe", "pipe", "pipe"] }\n );\n const pending = /* @__PURE__ */ new Map();\n let nextId = 1;\n let dead;\n let notificationHandler = () => {\n };\n let serverRequestHandler = async () => {\n throw new Error("no server-request handler installed");\n };\n const stderrTail = [];\n const write = (frame) => {\n if (dead) return;\n child.stdin.write(`${JSON.stringify({ jsonrpc: "2.0", ...frame })}\n`);\n };\n const handleFrame = (frame) => {\n const asRequest = frame;\n if (asRequest.id !== void 0 && asRequest.method !== void 0) {\n void Promise.resolve().then(() => serverRequestHandler(asRequest)).then(\n (result) => write({ id: asRequest.id, result }),\n (error) => write({\n id: asRequest.id,\n error: {\n code: -32603,\n message: error instanceof Error ? error.message : String(error)\n }\n })\n );\n return;\n }\n if (frame.method !== void 0) {\n notificationHandler(frame);\n return;\n }\n const response = frame;\n const entry = pending.get(response.id);\n if (!entry) return;\n pending.delete(response.id);\n if (response.error) entry.reject(new Error(response.error.message));\n else entry.resolve(response.result);\n };\n let stdoutBuffer = "";\n child.stdout.setEncoding("utf8");\n child.stdout.on("data", (chunk) => {\n stdoutBuffer += chunk;\n let index;\n while ((index = stdoutBuffer.indexOf("\\n")) !== -1) {\n const line = stdoutBuffer.slice(0, index).trim();\n stdoutBuffer = stdoutBuffer.slice(index + 1);\n if (!line) continue;\n try {\n handleFrame(JSON.parse(line));\n } catch (error) {\n options.onFrameError?.(line, error);\n failClient(\n `app-server sent a frame that is not JSON: ${line.slice(0, 200)}`\n );\n return;\n }\n }\n });\n let stderrBuffer = "";\n child.stderr.setEncoding("utf8");\n child.stderr.on("data", (chunk) => {\n stderrBuffer += chunk;\n let index;\n while ((index = stderrBuffer.indexOf("\\n")) !== -1) {\n const line = stderrBuffer.slice(0, index);\n stderrBuffer = stderrBuffer.slice(index + 1);\n if (!line.trim()) continue;\n stderrTail.push(line);\n if (stderrTail.length > 20) stderrTail.shift();\n options.onStderrLine?.(line);\n }\n });\n let settleExit = () => {\n };\n const exited = new Promise((resolve) => {\n settleExit = resolve;\n });\n let exitSeen = false;\n let settleProcessExit = () => {\n };\n const processExit = new Promise((resolve) => {\n settleProcessExit = resolve;\n });\n const onProcessGone = () => {\n exitSeen = true;\n settleProcessExit();\n };\n const onGone = (code, signal) => {\n onProcessGone();\n if (dead) return;\n dead = new AppServerExitedError(code, signal, stderrTail.join("\\n"));\n for (const entry of pending.values()) entry.reject(dead);\n pending.clear();\n settleExit(dead);\n };\n child.on("exit", onGone);\n const failClient = (reason) => {\n if (dead) return;\n dead = new AppServerExitedError(null, null, reason);\n for (const entry of pending.values()) entry.reject(dead);\n pending.clear();\n settleExit(dead);\n try {\n child.kill("SIGKILL");\n } catch {\n }\n };\n child.stdin.on("error", (error) => {\n failClient(`app-server stdin failed: ${String(error)}`);\n });\n child.on("error", (error) => {\n if (child.pid === void 0) onProcessGone();\n if (dead) return;\n dead = new AppServerExitedError(null, null, String(error));\n for (const entry of pending.values()) entry.reject(dead);\n pending.clear();\n settleExit(dead);\n });\n return {\n request(method, params) {\n if (dead) return Promise.reject(dead);\n const id = nextId++;\n return new Promise((resolve, reject) => {\n pending.set(id, {\n resolve,\n reject\n });\n write({ id, method, params });\n });\n },\n notify(method, params) {\n write({ method, params });\n },\n onNotification(handler) {\n notificationHandler = handler;\n },\n onServerRequest(handler) {\n serverRequestHandler = handler;\n },\n exited,\n async kill() {\n if (exitSeen) return;\n child.stdin.end();\n child.kill("SIGTERM");\n const escalate = setTimeout(() => child.kill("SIGKILL"), 5e3);\n let giveUp;\n try {\n await Promise.race([\n processExit,\n new Promise((resolve) => {\n giveUp = setTimeout(resolve, 1e4);\n giveUp.unref?.();\n })\n ]);\n } finally {\n clearTimeout(escalate);\n if (giveUp) clearTimeout(giveUp);\n }\n }\n };\n}\n\n// server/utils/harness/codex-appserver/bridge/approval-controller.ts\nimport { randomUUID as randomUUID2 } from "node:crypto";\nfunction createApprovalController(input) {\n const { turn, translator } = input;\n const approvalIdPrefix = `codex-approval-${randomUUID2().slice(0, 8)}`;\n let approvalSeq = 0;\n let cancelled = false;\n const waiting = /* @__PURE__ */ new Set();\n const pause = async (toolCallId) => {\n if (cancelled) return "cancel";\n const approvalId = `${approvalIdPrefix}-${++approvalSeq}`;\n turn.emit({ type: "tool-approval-request", approvalId, toolCallId });\n let settle;\n const cancellation = new Promise((resolve) => {\n settle = resolve;\n waiting.add(resolve);\n });\n try {\n const decision = await Promise.race([\n turn.requestToolApproval(approvalId).then(\n ({ approved }) => (\n // `decline` and not `cancel`: cancel reads to Codex as "the user\n // walked away", decline as "the user said no". Verified live that\n // decline is honoured even when `availableDecisions` omits it, and\n // it produces the `declined` item status the trace should show.\n approved ? "accept" : "decline"\n )\n ),\n cancellation\n ]);\n return decision;\n } catch (error) {\n turn.bridgeLog({\n level: "warn",\n subsystem: "approval",\n message: "approval request failed; cancelling",\n error\n });\n return "cancel";\n } finally {\n if (settle) waiting.delete(settle);\n }\n };\n const handleCommandExecution = async (params) => {\n const toolCallId = translator.ensureToolCall(params.itemId, {\n toolName: CODEX_APPSERVER_TOOL_NAMES.commandExecution,\n nativeName: CODEX_APPSERVER_NATIVE_TOOL_NAMES.commandExecution,\n input: {\n command: params.command ?? "",\n ...params.cwd ? { cwd: params.cwd } : {},\n ...params.commandActions?.length ? { commandActions: params.commandActions } : {},\n ...params.reason ? { reason: params.reason } : {}\n }\n });\n return { decision: await pause(toolCallId) };\n };\n const handleFileChange = async (params) => {\n const toolCallId = translator.ensureToolCall(params.itemId, {\n toolName: CODEX_APPSERVER_TOOL_NAMES.fileChange,\n nativeName: CODEX_APPSERVER_NATIVE_TOOL_NAMES.fileChange,\n input: {\n ...params.reason ? { reason: params.reason } : {},\n ...params.grantRoot ? { grantRoot: params.grantRoot } : {}\n }\n });\n return { decision: await pause(toolCallId) };\n };\n const handlePermissions = async (params) => {\n turn.emitWarning({\n message: `Codex asked to widen its permissions mid-turn; MCPJam granted none (cwd: ${params.cwd}).`\n });\n return { permissions: {}, scope: "turn" };\n };\n const handleUserInput = async (params) => {\n turn.emitWarning({\n message: `Codex asked the user a question mid-turn (${params.questions.map((q) => q.question).join(" / ")}); MCPJam answered with no input.`\n });\n return { answers: {} };\n };\n const handleElicitation = async () => {\n turn.emitWarning({\n message: "An MCP server asked for interactive input; MCPJam declined it. Configure the server\'s credentials on the host instead."\n });\n return { action: "decline", content: null };\n };\n return {\n async handle(request) {\n const params = request.params ?? {};\n switch (request.method) {\n case "item/commandExecution/requestApproval":\n return handleCommandExecution(\n params\n );\n case "item/fileChange/requestApproval":\n return handleFileChange(\n params\n );\n case "item/permissions/requestApproval":\n return handlePermissions(\n params\n );\n case "item/tool/requestUserInput":\n return handleUserInput(\n params\n );\n case "mcpServer/elicitation/request":\n return handleElicitation();\n default:\n throw new Error(`unsupported server request: ${request.method}`);\n }\n },\n cancelAll() {\n cancelled = true;\n for (const resolve of waiting) resolve("cancel");\n waiting.clear();\n input.onInterrupt?.();\n }\n };\n}\n\n// server/utils/harness/codex-appserver/bridge/mcp-isolation.ts\nimport { readFileSync as readFileSync2 } from "node:fs";\nvar CODEX_SYSTEM_CONFIG_PATHS = [\n "/etc/codex/config.toml",\n "/etc/codex/managed_config.toml"\n];\nfunction mcpServerNamesInToml(text) {\n const names = /* @__PURE__ */ new Set();\n const key = String.raw`(?:"((?:[^"\\\\]|\\\\.)*)"|\'([^\']*)\'|([A-Za-z0-9_-]+))`;\n const take = (match) => {\n const name = match[1] ?? match[2] ?? match[3];\n if (name) names.add(name.replace(/\\\\(.)/g, "$1"));\n };\n const header = new RegExp(String.raw`^\\s*\\[\\[?\\s*mcp_servers\\s*\\.\\s*${key}`, "gm");\n for (const match of text.matchAll(header)) take(match);\n const dotted = new RegExp(String.raw`^\\s*mcp_servers\\s*\\.\\s*${key}\\s*[.=]`, "gm");\n for (const match of text.matchAll(dotted)) take(match);\n const sections = text.split(/^\\s*\\[/m);\n for (const section of sections) {\n if (!/^\\s*mcp_servers\\s*\\]/.test(section)) continue;\n const bodyKey = new RegExp(String.raw`^\\s*${key}\\s*(?:=|\\.)`, "gm");\n for (const match of section.replace(/^[^\\n]*\\n/, "").matchAll(bodyKey)) {\n take(match);\n }\n }\n return [...names].sort();\n}\nfunction foreignMcpServerOverrides(options) {\n const platform = options.platform ?? process.platform;\n if (platform === "win32") return {};\n const read = options.readFile ?? ((path) => {\n try {\n return readFileSync2(path, "utf8");\n } catch {\n return null;\n }\n });\n const overrides = {};\n for (const path of options.paths ?? CODEX_SYSTEM_CONFIG_PATHS) {\n const text = read(path);\n if (text === null) continue;\n for (const name of mcpServerNamesInToml(text)) {\n if (name !== options.keep) overrides[name] = { enabled: false };\n }\n }\n return overrides;\n}\n\n// server/utils/harness/codex-appserver/bridge/host-tool-catalog.ts\nvar PERMISSIVE_SCHEMA = {\n type: "object",\n properties: {},\n additionalProperties: true\n};\nvar OBJECT_ONLY_KEYWORDS = [\n "properties",\n "patternProperties",\n "additionalProperties",\n "unevaluatedProperties",\n "propertyNames",\n "required",\n "dependentRequired",\n "dependentSchemas",\n // draft-07\'s predecessor to the two above. MCP tool schemas in the wild are\n // routinely draft-07, so leaving it out would drop exactly the dependent\n // argument constraints this list exists to preserve.\n "dependencies",\n "minProperties",\n "maxProperties"\n];\nfunction asObjectSchema(schema) {\n if (!schema || typeof schema !== "object" || Array.isArray(schema)) {\n return { ...PERMISSIVE_SCHEMA };\n }\n const candidate = schema;\n if (candidate.type === "object") return { ...candidate };\n if (candidate.type === void 0 && OBJECT_ONLY_KEYWORDS.some((key) => candidate[key] !== void 0)) {\n return { ...candidate, type: "object" };\n }\n return { ...PERMISSIVE_SCHEMA };\n}\nfunction buildHostToolCatalog(tools) {\n const { aliasToCanonical, canonicalToAlias } = buildHostToolAliases(\n tools.map((tool) => tool.name)\n );\n const descriptors = tools.map((tool) => ({\n name: canonicalToAlias.get(tool.name) ?? tool.name,\n ...tool.description ? { description: tool.description } : {},\n inputSchema: asObjectSchema(tool.inputSchema)\n }));\n return { descriptors, aliasToCanonical };\n}\n\n// server/utils/harness/codex-appserver/bridge/codex-home.ts\nimport { existsSync as existsSync2, mkdirSync, realpathSync, writeFileSync } from "node:fs";\nimport { dirname, join } from "node:path";\nvar tomlString = (value) => JSON.stringify(value);\nfunction untrustedProjectPathsFor(workdir) {\n const paths = /* @__PURE__ */ new Set([workdir]);\n let real = workdir;\n try {\n real = realpathSync(workdir);\n paths.add(real);\n } catch {\n }\n for (const start of /* @__PURE__ */ new Set([workdir, real])) {\n for (let dir = start; ; dir = dirname(dir)) {\n if (existsSync2(join(dir, ".git"))) {\n paths.add(dir);\n break;\n }\n if (dirname(dir) === dir) break;\n }\n }\n return [...paths];\n}\nfunction renderCodexConfigToml(input) {\n const lines = [\n "# Generated per session by MCPJam\'s codex app-server bridge. Do not edit:",\n "# it is rewritten on every session start.",\n "",\n // The custom provider is the whole broker story: Codex talks to MCPJam\'s\n // metered proxy, the placeholder credential satisfies its auth check, and\n // the real lease is injected outside the VM by E2B.\n `model_provider = ${tomlString("mcpjam")}`,\n // The credential is an API-key-shaped capability, never a ChatGPT login:\n // without this Codex can prefer an interactive auth flow it will never\n // complete. Parity with the published adapter\'s bridge.\n \'preferred_auth_method = "apikey"\',\n // `detailed` is what makes reasoning summaries stream at all; without it\n // the reasoning parts are empty and the trace looks like the model thought\n // about nothing.\n \'model_reasoning_summary = "detailed"\',\n `web_search = ${input.webSearch ? \'"live"\' : \'"disabled"\'}`,\n "",\n "[model_providers.mcpjam]",\n \'name = "MCPJam model proxy"\',\n `base_url = ${tomlString(input.baseUrl)}`,\n `env_key = ${tomlString(input.apiKeyEnvVar)}`,\n // The proxy allowlists exactly `POST /v1/responses` and `GET /v1/models`;\n // the responses wire API is what stays inside it.\n \'wire_api = "responses"\',\n // Neither the hosted proxy nor the local gateway speaks the realtime\n // WebSocket transport; Codex must stay on plain HTTP streaming.\n "supports_websockets = false",\n "",\n "[features]",\n // Measured (PROBES.md (a2/a3)): by default codex contacts github.com,\n // api.github.com and chatgpt.com at startup and clones ~100 MB of plugins\n // into every fresh CODEX_HOME. None of it is MCPJam\'s, all of it is egress\n // and disk the session never asked for, and on a user\'s machine it is\n // traffic they did not agree to.\n "plugins = false"\n ];\n if (input.hostToolsEntrypoint && input.relayUrl && input.relayCredential) {\n lines.push(\n "",\n `[mcp_servers.${RELAY_MCP_SERVER_NAME}]`,\n `command = ${tomlString(input.nodeExecutable ?? process.execPath)}`,\n `args = [${tomlString(input.hostToolsEntrypoint)}]`,\n // Generous: the server is a local node process, but a cold `node` start\n // on a loaded box is not instant.\n "startup_timeout_sec = 30",\n // An HOUR, not zero. A host tool can be gated behind a human approval,\n // so the call legitimately takes as long as a person takes to answer \u2014\n // but Codex reads `0` as a zero-second budget, not "no limit": every\n // relayed call timed out immediately. There is no unlimited setting, so\n // the wait is bounded at an hour, longer than any approval the host\n // keeps a session parked for. Never restore 0.\n "tool_timeout_sec = 3600",\n // Codex gates MCP calls ITSELF (PROBES.md (d)): under `never` it refuses\n // every relayed call ("requires approval, but approval policy is\n // never"), and under `untrusted` it raises an `mcp_tool_call`\n // elicitation the bridge declines. Either way no host tool ran. MCPJam\'s\n // own gate \u2014 the framework\'s `toolApproval`, evaluated on the host\n // before `execute` \u2014 is the single authority for relayed tools, so\n // codex is told not to add a second one.\n \'default_tools_approval_mode = "approve"\',\n "",\n `[mcp_servers.${RELAY_MCP_SERVER_NAME}.env]`,\n `MCPJAM_HOST_TOOL_RELAY_URL = ${tomlString(input.relayUrl)}`,\n `MCPJAM_HOST_TOOL_RELAY_CREDENTIAL = ${tomlString(\n input.relayCredential\n )}`,\n ...input.hostToolCatalogPath ? [\n `MCPJAM_HOST_TOOL_CATALOG = ${tomlString(\n input.hostToolCatalogPath\n )}`\n ] : []\n );\n }\n for (const path of new Set(input.untrustedProjectPaths ?? [])) {\n lines.push("", `[projects.${tomlString(path)}]`, \'trust_level = "untrusted"\');\n }\n return `${lines.join("\\n")}\n`;\n}\nfunction prepareCodexHome(input) {\n mkdirSync(input.codexHome, { recursive: true });\n writeFileSync(\n join(input.codexHome, "config.toml"),\n renderCodexConfigToml(input),\n "utf8"\n );\n return input.codexHome;\n}\n\n// server/utils/harness/codex-appserver/bridge/host-tool-relay.ts\nimport { createServer } from "node:http";\nimport { randomBytes, timingSafeEqual, createHash } from "node:crypto";\nvar MAX_CALL_BODY_BYTES = 8 * 1024 * 1024;\nfunction credentialMatches(presented, expected) {\n const a = createHash("sha256").update(presented, "utf8").digest();\n const b = createHash("sha256").update(expected, "utf8").digest();\n return timingSafeEqual(a, b);\n}\nasync function startHostToolRelay(handlers) {\n const credential = randomBytes(32).toString("hex");\n const inFlight = /* @__PURE__ */ new Set();\n const server = createServer((req, res) => {\n const reply = (status, body2) => {\n const payload = JSON.stringify(body2);\n res.writeHead(status, {\n "content-type": "application/json",\n "content-length": Buffer.byteLength(payload)\n });\n res.end(payload);\n };\n const presented = req.headers["x-mcpjam-relay-credential"] ?? "";\n if (!presented || !credentialMatches(presented, credential)) {\n reply(401, { error: "unauthorized" });\n return;\n }\n const path = (req.url ?? "").split("?")[0];\n if (req.method === "GET" && path === "/tools") {\n reply(200, { tools: handlers.listTools() });\n return;\n }\n if (req.method !== "POST" || path !== "/call") {\n reply(404, { error: "not found" });\n return;\n }\n let body = "";\n let bodyBytes = 0;\n let aborted = false;\n req.setEncoding("utf8");\n req.on("data", (chunk) => {\n if (aborted) return;\n const chunkBytes = Buffer.byteLength(chunk, "utf8");\n if (bodyBytes + chunkBytes > MAX_CALL_BODY_BYTES) {\n aborted = true;\n reply(413, { error: "request body too large" });\n res.once("finish", () => req.destroy());\n return;\n }\n bodyBytes += chunkBytes;\n body += chunk;\n });\n req.on("end", () => {\n if (aborted) return;\n let invocation;\n try {\n invocation = JSON.parse(body);\n } catch {\n reply(400, { error: "malformed body" });\n return;\n }\n let rejectInFlight;\n const cancellation = new Promise((_, reject) => {\n rejectInFlight = reject;\n inFlight.add(reject);\n });\n Promise.race([handlers.callTool(invocation), cancellation]).then(\n (result) => reply(200, { ok: true, result }),\n (error) => reply(200, {\n ok: false,\n error: error instanceof Error ? error.message : String(error)\n })\n ).finally(() => {\n if (rejectInFlight) inFlight.delete(rejectInFlight);\n });\n });\n });\n await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));\n const address = server.address();\n const port = typeof address === "object" && address ? address.port : 0;\n return {\n url: `http://127.0.0.1:${port}`,\n credential,\n async close() {\n for (const reject of inFlight) {\n reject(new Error("bridge is shutting down"));\n }\n inFlight.clear();\n await new Promise((resolve) => server.close(() => resolve()));\n },\n cancelAll(reason) {\n for (const reject of inFlight) reject(new Error(reason));\n inFlight.clear();\n }\n };\n}\n\n// server/utils/harness/codex-appserver/bridge/step-tracker.ts\nvar TOOL_ITEM_TYPES = /* @__PURE__ */ new Set([\n "commandExecution",\n "fileChange",\n "mcpToolCall",\n "webSearch",\n "dynamicToolCall"\n]);\nfunction createStepTracker() {\n const openTools = /* @__PURE__ */ new Set();\n let stepOpen = false;\n return {\n itemStarted(itemId, itemType) {\n const opened = !stepOpen;\n stepOpen = true;\n if (TOOL_ITEM_TYPES.has(itemType)) openTools.add(itemId);\n return opened;\n },\n itemCompleted(itemId, itemType) {\n if (TOOL_ITEM_TYPES.has(itemType)) openTools.delete(itemId);\n if (!stepOpen || openTools.size > 0) return false;\n if (!TOOL_ITEM_TYPES.has(itemType)) return false;\n stepOpen = false;\n return true;\n },\n isStepOpen: () => stepOpen,\n closeStep() {\n if (!stepOpen) return false;\n stepOpen = false;\n openTools.clear();\n return true;\n },\n hasOpenTools: () => openTools.size > 0\n };\n}\n\n// server/utils/harness/codex-appserver/bridge/usage.ts\nfunction zeroUsage() {\n return { inputTokens: {}, outputTokens: {} };\n}\nfunction toHarnessUsage(breakdown) {\n if (!breakdown) return zeroUsage();\n const input = breakdown.inputTokens;\n const cacheRead = breakdown.cachedInputTokens;\n const cacheWrite = breakdown.cacheWriteInputTokens;\n const output = breakdown.outputTokens;\n const reasoning = breakdown.reasoningOutputTokens;\n return {\n inputTokens: {\n ...input !== void 0 ? { total: input } : {},\n ...input !== void 0 && cacheRead !== void 0 ? { noCache: Math.max(0, input - cacheRead - (cacheWrite ?? 0)) } : {},\n ...cacheRead !== void 0 ? { cacheRead } : {},\n ...cacheWrite !== void 0 ? { cacheWrite } : {}\n },\n outputTokens: {\n ...output !== void 0 ? { total: output } : {},\n ...output !== void 0 && reasoning !== void 0 ? { text: Math.max(0, output - reasoning) } : {},\n ...reasoning !== void 0 ? { reasoning } : {}\n },\n raw: { ...breakdown }\n };\n}\nvar sub = (a, b) => a === void 0 ? void 0 : a - (b ?? 0);\nfunction diffUsage(end, start) {\n if (!end) return void 0;\n const diff = {\n totalTokens: sub(end.totalTokens, start?.totalTokens),\n inputTokens: sub(end.inputTokens, start?.inputTokens),\n cachedInputTokens: sub(end.cachedInputTokens, start?.cachedInputTokens),\n cacheWriteInputTokens: sub(\n end.cacheWriteInputTokens,\n start?.cacheWriteInputTokens\n ),\n outputTokens: sub(end.outputTokens, start?.outputTokens),\n reasoningOutputTokens: sub(\n end.reasoningOutputTokens,\n start?.reasoningOutputTokens\n )\n };\n const negative = Object.values(diff).some(\n (value) => typeof value === "number" && value < 0\n );\n return negative ? void 0 : toHarnessUsage(diff);\n}\nfunction addBreakdowns(a, b) {\n if (!b) return a;\n const add = (x, y) => x === void 0 && y === void 0 ? void 0 : (x ?? 0) + (y ?? 0);\n return {\n totalTokens: add(a.totalTokens, b.totalTokens),\n inputTokens: add(a.inputTokens, b.inputTokens),\n cachedInputTokens: add(a.cachedInputTokens, b.cachedInputTokens),\n cacheWriteInputTokens: add(\n a.cacheWriteInputTokens,\n b.cacheWriteInputTokens\n ),\n outputTokens: add(a.outputTokens, b.outputTokens),\n reasoningOutputTokens: add(\n a.reasoningOutputTokens,\n b.reasoningOutputTokens\n )\n };\n}\n\n// server/utils/harness/codex-appserver/bridge/stream-translator.ts\nfunction createStreamTranslator(input) {\n const { emit, emitWarning, emitError, relayServerName } = input;\n const emitRaw = input.emitRaw ?? true;\n const steps = input.stepTracker ?? createStepTracker();\n const items = /* @__PURE__ */ new Map();\n let usageAtTurnStart;\n let latestTotal;\n let latestLast;\n let summedLast = {};\n let sawUsage = false;\n let finished = false;\n let pendingCompaction;\n let tokensBeforeCompaction;\n let resolveTurn;\n const turnPromise = new Promise((resolve) => {\n resolveTurn = resolve;\n });\n const state = (itemId, type) => {\n const existing = items.get(itemId);\n if (existing) return existing;\n const created = {\n type,\n streamedText: "",\n streamedReasoning: "",\n summaryIndex: 0\n };\n items.set(itemId, created);\n return created;\n };\n const closeText = (item) => {\n if (item.textId === void 0) return;\n emit({ type: "text-end", id: item.textId });\n item.textId = void 0;\n };\n const closeReasoning = (item) => {\n if (item.reasoningId === void 0) return;\n emit({ type: "reasoning-end", id: item.reasoningId });\n item.reasoningId = void 0;\n };\n const closeAllBlocks = () => {\n for (const item of items.values()) {\n closeText(item);\n closeReasoning(item);\n }\n };\n const emitStepFinish = (reason) => {\n emit({\n type: "finish-step",\n finishReason: { unified: reason },\n usage: toHarnessUsage(latestLast)\n });\n };\n const turnUsage = () => {\n if (!sawUsage) return zeroUsage();\n return diffUsage(latestTotal, usageAtTurnStart) ?? toHarnessUsage(summedLast);\n };\n const ensureToolCall = (itemId, seed) => {\n const item = state(itemId, seed.toolName);\n if (item.toolCallId) return item.toolCallId;\n item.toolCallId = itemId;\n item.toolName = seed.toolName;\n emit({\n type: "tool-call",\n toolCallId: itemId,\n toolName: seed.toolName,\n // The harness wire type is a JSON STRING, not an object. Passing the\n // object through here is the single easiest way to produce a part that\n // fails schema validation downstream, so it is stringified once, here.\n input: JSON.stringify(seed.input ?? {}),\n providerExecuted: seed.providerExecuted ?? true,\n ...seed.dynamic ? { dynamic: true } : {},\n ...seed.nativeName ? { nativeName: seed.nativeName } : {}\n });\n return itemId;\n };\n const emitToolResult = (itemId, toolName, result, isError) => {\n const item = state(itemId, toolName);\n if (item.emittedResult) return;\n item.emittedResult = true;\n emit({\n type: "tool-result",\n toolCallId: itemId,\n toolName,\n result,\n ...isError ? { isError: true } : {}\n });\n };\n const seedForItem = (item) => {\n switch (item.type) {\n case "commandExecution": {\n const command = item.command;\n const cwd = item.cwd;\n const actions = item.commandActions;\n return {\n toolName: CODEX_APPSERVER_TOOL_NAMES.commandExecution,\n nativeName: CODEX_APPSERVER_NATIVE_TOOL_NAMES.commandExecution,\n input: {\n command,\n ...typeof cwd === "string" ? { cwd } : {},\n ...actions?.length ? { commandActions: actions } : {}\n }\n };\n }\n case "fileChange": {\n const changes = item.changes ?? [];\n return {\n toolName: CODEX_APPSERVER_TOOL_NAMES.fileChange,\n nativeName: CODEX_APPSERVER_NATIVE_TOOL_NAMES.fileChange,\n input: {\n changes: changes.map((change) => ({\n path: change.path,\n ...change.kind?.type ? { kind: change.kind.type } : {}\n }))\n }\n };\n }\n case "webSearch":\n return {\n toolName: CODEX_APPSERVER_TOOL_NAMES.webSearch,\n nativeName: CODEX_APPSERVER_NATIVE_TOOL_NAMES.webSearch,\n input: { query: item.query }\n };\n case "mcpToolCall": {\n const mcp = item;\n if (mcp.server === relayServerName) return void 0;\n return {\n toolName: `${mcp.server}__${mcp.tool}`,\n input: mcp.arguments ?? {},\n dynamic: true\n };\n }\n default:\n return void 0;\n }\n };\n const resultForItem = (item) => {\n switch (item.type) {\n case "commandExecution": {\n const command = item;\n return {\n result: {\n status: command.status,\n ...command.exitCode != null ? { exitCode: command.exitCode } : {},\n ...command.aggregatedOutput != null ? { output: command.aggregatedOutput } : {},\n ...command.durationMs != null ? { durationMs: command.durationMs } : {}\n },\n isError: command.status === "failed" || command.status === "declined"\n };\n }\n case "fileChange": {\n const change = item;\n return {\n result: {\n status: change.status,\n changes: (change.changes ?? []).map((entry) => ({\n path: entry.path,\n ...entry.kind?.type ? { kind: entry.kind.type } : {}\n }))\n },\n isError: change.status === "failed" || change.status === "declined"\n };\n }\n case "webSearch": {\n const search = item;\n return { result: search.results ?? null, isError: false };\n }\n case "mcpToolCall": {\n const mcp = item;\n return {\n result: mcp.error ?? mcp.result ?? null,\n isError: mcp.status === "failed" || Boolean(mcp.error)\n };\n }\n default:\n return { result: null, isError: false };\n }\n };\n const onItemStarted = (item) => {\n const tracked = state(item.id, item.type);\n tracked.type = item.type;\n steps.itemStarted(item.id, item.type);\n const seed = seedForItem(item);\n if (seed) ensureToolCall(item.id, seed);\n };\n const onItemCompleted = (item) => {\n const tracked = state(item.id, item.type);\n if (item.type === "agentMessage") {\n const text = item.text ?? "";\n if (text.length > tracked.streamedText.length) {\n const id = tracked.textId ?? `${item.id}`;\n if (tracked.textId === void 0) {\n emit({ type: "text-start", id });\n tracked.textId = id;\n }\n emit({\n type: "text-delta",\n id,\n delta: text.slice(tracked.streamedText.length)\n });\n tracked.streamedText = text;\n }\n closeText(tracked);\n }\n if (item.type === "reasoning") {\n const summary = (item.summary ?? []).join(\n "\\n\\n"\n );\n if (summary.length > tracked.streamedReasoning.length) {\n const id = tracked.reasoningId ?? `${item.id}`;\n if (tracked.reasoningId === void 0) {\n emit({ type: "reasoning-start", id });\n tracked.reasoningId = id;\n }\n emit({\n type: "reasoning-delta",\n id,\n delta: summary.slice(tracked.streamedReasoning.length)\n });\n tracked.streamedReasoning = summary;\n }\n closeReasoning(tracked);\n }\n if (item.type === "contextCompaction") {\n emit({\n type: "compaction",\n trigger: pendingCompaction ?? "auto",\n summary: "",\n ...tokensBeforeCompaction !== void 0 ? { tokensBefore: tokensBeforeCompaction } : {},\n ...latestTotal?.totalTokens !== void 0 ? { tokensAfter: latestTotal.totalTokens } : {}\n });\n pendingCompaction = void 0;\n }\n const seed = seedForItem(item);\n if (seed) {\n const toolCallId = ensureToolCall(item.id, seed);\n const { result, isError } = resultForItem(item);\n emitToolResult(toolCallId, seed.toolName, result, isError);\n }\n if (steps.itemCompleted(item.id, item.type)) emitStepFinish("tool-calls");\n };\n const handleNotification = (notification) => {\n const { method } = notification;\n const params = notification.params ?? {};\n if (emitRaw) emit({ type: "raw", rawValue: notification });\n switch (method) {\n case "thread/started": {\n const thread = params.thread;\n if (thread?.id) emit({ type: "bridge-thread", threadId: thread.id });\n return;\n }\n case "item/agentMessage/delta": {\n const itemId = String(params.itemId ?? "");\n const delta = String(params.delta ?? "");\n if (!itemId || !delta) return;\n const item = state(itemId, "agentMessage");\n if (item.textId === void 0) {\n item.textId = itemId;\n emit({ type: "text-start", id: itemId });\n }\n item.streamedText += delta;\n emit({ type: "text-delta", id: itemId, delta });\n return;\n }\n case "item/reasoning/summaryPartAdded": {\n const itemId = String(params.itemId ?? "");\n if (!itemId) return;\n const item = state(itemId, "reasoning");\n if (item.reasoningId !== void 0 && item.streamedReasoning) {\n item.streamedReasoning += "\\n\\n";\n emit({ type: "reasoning-delta", id: itemId, delta: "\\n\\n" });\n }\n return;\n }\n case "item/reasoning/summaryTextDelta": {\n const itemId = String(params.itemId ?? "");\n const delta = String(params.delta ?? "");\n if (!itemId || !delta) return;\n const item = state(itemId, "reasoning");\n if (item.reasoningId === void 0) {\n item.reasoningId = itemId;\n emit({ type: "reasoning-start", id: itemId });\n }\n item.streamedReasoning += delta;\n emit({ type: "reasoning-delta", id: itemId, delta });\n return;\n }\n case "item/started": {\n const item = params.item;\n if (item?.id) onItemStarted(item);\n return;\n }\n case "item/completed": {\n const item = params.item;\n if (item?.id) onItemCompleted(item);\n return;\n }\n case "item/fileChange/patchUpdated": {\n const changes = params.changes ?? [];\n for (const change of changes) {\n if (!change?.path) continue;\n const kind = change.kind?.type ?? "";\n const event = kind === "add" || kind === "create" ? "create" : kind === "delete" || kind === "remove" ? "delete" : "modify";\n emit({ type: "file-change", event, path: change.path });\n }\n return;\n }\n case "thread/tokenUsage/updated": {\n const usage = params.tokenUsage;\n if (!usage) return;\n sawUsage = true;\n if (usage.total) {\n if (usageAtTurnStart === void 0) {\n usageAtTurnStart = subtractLast(usage.total, usage.last);\n }\n latestTotal = usage.total;\n tokensBeforeCompaction = usage.total.totalTokens;\n }\n if (usage.last) {\n latestLast = usage.last;\n summedLast = addBreakdowns(summedLast, usage.last);\n }\n return;\n }\n case "thread/compacted":\n pendingCompaction = pendingCompaction ?? "auto";\n return;\n case "turn/completed": {\n const turn = params.turn;\n finishTurn({\n status: turn?.status ?? "completed",\n ...turn?.error?.message ? { error: { message: turn.error.message } } : {}\n });\n return;\n }\n case "error": {\n const error = params.error;\n const willRetry = params.willRetry === true;\n if (willRetry) {\n emitWarning({ message: error?.message ?? "codex retrying" });\n } else {\n lastTerminalError = error?.message ?? "codex error";\n emitError({ error: lastTerminalError });\n }\n return;\n }\n case "warning":\n case "configWarning": {\n const message = params.message ?? params.summary;\n if (message) emitWarning({ message });\n return;\n }\n case "mcpServer/startupStatus/updated": {\n const status = String(params.status ?? "");\n if (status === "failed" || status === "cancelled") {\n emitWarning({\n message: `MCP server \'${String(params.name ?? "?")}\' ${status}` + (params.error ? `: ${String(params.error)}` : "")\n });\n }\n return;\n }\n default:\n return;\n }\n };\n let lastTerminalError;\n const finishTurn = (outcome) => {\n if (finished) return;\n finished = true;\n for (const [itemId, item] of items) {\n if (!item.toolCallId || item.emittedResult) continue;\n emitToolResult(\n itemId,\n item.toolName ?? item.type,\n {\n status: "inProgress",\n note: "still running when the turn ended"\n },\n false\n );\n }\n closeAllBlocks();\n if (steps.closeStep()) emitStepFinish("stop");\n if (outcome.error && outcome.error.message !== lastTerminalError) {\n emitError({ error: outcome.error.message });\n }\n emit({\n type: "finish",\n finishReason: {\n unified: outcome.status === "completed" ? "stop" : outcome.status === "failed" ? "error" : "other",\n raw: outcome.status\n },\n totalUsage: turnUsage()\n });\n resolveTurn?.(outcome);\n };\n return {\n handleNotification,\n ensureToolCall,\n finishTurn,\n waitForTurn: () => turnPromise\n };\n function subtractLast(total, last) {\n if (!last) return total;\n const sub2 = (a, b) => a === void 0 ? void 0 : Math.max(0, a - (b ?? 0));\n return {\n totalTokens: sub2(total.totalTokens, last.totalTokens),\n inputTokens: sub2(total.inputTokens, last.inputTokens),\n cachedInputTokens: sub2(total.cachedInputTokens, last.cachedInputTokens),\n cacheWriteInputTokens: sub2(\n total.cacheWriteInputTokens,\n last.cacheWriteInputTokens\n ),\n outputTokens: sub2(total.outputTokens, last.outputTokens),\n reasoningOutputTokens: sub2(\n total.reasoningOutputTokens,\n last.reasoningOutputTokens\n )\n };\n }\n}\n\n// server/utils/harness/codex-appserver/bridge/index.ts\nfunction parseArgs(argv) {\n const read = (flag) => {\n const index = argv.indexOf(`--${flag}`);\n return index === -1 ? void 0 : argv[index + 1];\n };\n const workdir = read("workdir") ?? process.cwd();\n return {\n workdir,\n bridgeStateDir: read("bridge-state-dir") ?? join2(workdir, ".harness-bridge"),\n sessionDataDir: read("session-data-dir") ?? join2(workdir, ".codex-session"),\n bootstrapDir: read("bootstrap-dir") ?? process.cwd()\n };\n}\nfunction isSupervisedLocally(env = process.env) {\n return typeof env.MCPJAM_LOCAL_CONTROL_ROOT === "string" && env.MCPJAM_LOCAL_CONTROL_ROOT.length > 0;\n}\nvar CodexPermissionRefusedError = class extends Error {\n constructor(message) {\n super(message);\n this.name = "CodexPermissionRefusedError";\n }\n};\nfunction toCodexPermissions(mode, options = {}) {\n let sandboxPolicy;\n if (options.sandboxPolicy !== void 0) {\n const parsed = parseWorkspaceWriteSandboxPolicy(options.sandboxPolicy);\n if (parsed === null) {\n throw new CodexPermissionRefusedError(\n "Refusing a command-sandbox policy that is not MCPJam\'s workspace-write policy."\n );\n }\n if (options.supervisedLocally && parsed.networkAccess) {\n throw new CodexPermissionRefusedError(\n "Refusing command network access for a turn on a user\'s machine."\n );\n }\n sandboxPolicy = parsed;\n }\n switch (mode ?? "allow-all") {\n case "allow-reads":\n case "allow-edits":\n return {\n approvalPolicy: "untrusted",\n sandbox: "workspace-write",\n ...sandboxPolicy ? { sandboxPolicy: { ...sandboxPolicy } } : {}\n };\n case "allow-all":\n if (sandboxPolicy) {\n return {\n approvalPolicy: "never",\n sandbox: "workspace-write",\n sandboxPolicy: { ...sandboxPolicy }\n };\n }\n if (options.supervisedLocally) {\n throw new CodexPermissionRefusedError(\n "Refusing to start Codex with danger-full-access on a user\'s machine: an unattended local turn must carry an explicit workspace-write sandbox policy."\n );\n }\n return { approvalPolicy: "never", sandbox: "danger-full-access" };\n default:\n throw new CodexPermissionRefusedError(\n `Unknown permission mode ${JSON.stringify(mode)}; refusing rather than guessing how much access to grant.`\n );\n }\n}\nfunction withThreadConfig(start) {\n const config = threadConfig(start);\n return Object.keys(config).length > 0 ? { config } : {};\n}\nfunction threadConfig(start) {\n const config = { ...start.codexConfig ?? {} };\n const foreign = foreignMcpServerOverrides({ keep: RELAY_MCP_SERVER_NAME });\n if (Object.keys(foreign).length > 0) {\n const existing = config.mcp_servers && typeof config.mcp_servers === "object" ? config.mcp_servers : {};\n config.mcp_servers = { ...foreign, ...existing };\n }\n return config;\n}\nfunction turnConfigurationFingerprint(start) {\n return JSON.stringify({\n // Shared with the host so the two cannot disagree about what a "changed\n // tool" is \u2014 and over the whole descriptor, not just the name: a tool whose\n // schema changed under a fixed name is invisible to a live thread.\n turn: turnConfigurationFingerprintInput({\n instructions: start.instructions,\n tools: start.tools ?? []\n }),\n permissionMode: start.permissionMode ?? "allow-all",\n // A changed command sandbox is a changed configuration: a resumed thread\n // would otherwise keep running under the previous one.\n sandboxPolicy: sandboxPolicyFingerprint(start.sandboxPolicy),\n webSearch: start.webSearch ?? false,\n model: start.model ?? ""\n });\n}\nasync function main() {\n const args = parseArgs(process.argv.slice(2));\n mkdirSync2(args.sessionDataDir, { recursive: true });\n let client;\n let relay;\n let threadId;\n let lastFingerprint;\n let activeTurn;\n let catalog = buildHostToolCatalog([]);\n let runtimeConfig;\n const runtimeConfigOf = (start) => runtimeConfigFingerprint(start);\n const ensureRuntime = async (start) => {\n const wanted = runtimeConfigOf(start);\n if (client && runtimeConfig !== void 0 && runtimeConfig !== wanted) {\n await client.kill();\n await relay?.close();\n client = void 0;\n relay = void 0;\n threadId = void 0;\n }\n runtimeConfig = wanted;\n if (client) return;\n relay = await startHostToolRelay({\n listTools: () => catalog.descriptors,\n callTool: async ({ toolName, input }) => {\n const active = activeTurn;\n if (!active) throw new Error("no active turn for a host tool call");\n const canonical = active.aliasToCanonical.get(toolName) ?? toolName;\n const toolCallId = `mcpjam-host-${++active.toolCallSeq}`;\n active.turn.emit({\n type: "tool-call",\n toolCallId,\n toolName: canonical,\n input: JSON.stringify(input ?? {}),\n providerExecuted: false\n });\n const result = await active.turn.requestToolResult(toolCallId);\n active.turn.emit({\n type: "tool-result",\n toolCallId,\n toolName: canonical,\n result\n });\n return result;\n }\n });\n const codexHome = prepareCodexHome({\n codexHome: join2(args.sessionDataDir, "codex-home"),\n // Delivered per session as the adapter\'s credential environment: the\n // hosted proxy\'s `\u2026/openai/v1`, or the local gateway\'s bare origin. The\n // real lease is injected outside the process; `CODEX_API_KEY` is the\n // placeholder (or local capability) that satisfies Codex\'s auth check.\n baseUrl: process.env.OPENAI_BASE_URL ?? "https://api.openai.com/v1",\n apiKeyEnvVar: "CODEX_API_KEY",\n hostToolsEntrypoint: join2(args.bootstrapDir, "host-tools-mcp.mjs"),\n relayUrl: relay.url,\n relayCredential: relay.credential,\n webSearch: start.webSearch ?? false,\n // Keeps the folder\'s own `.codex/config.toml` (MCP servers, hooks, exec\n // policies) out: see `untrustedProjectPathsFor`.\n untrustedProjectPaths: untrustedProjectPathsFor(args.workdir)\n });\n client = spawnAppServerClient({\n command: process.execPath,\n args: [\n join2(\n args.bootstrapDir,\n "node_modules",\n "@openai",\n "codex",\n "bin",\n "codex.js"\n ),\n "app-server"\n ],\n cwd: args.workdir,\n env: { ...process.env, CODEX_HOME: codexHome },\n // Codex\'s own diagnostics, forwarded to the bridge\'s stderr \u2014 which the\n // host already tails into a bridge startup error and its logs. Without\n // this a Codex that failed to start (a sandbox it could not initialise,\n // a config it rejected) surfaced only as an opaque exit code.\n onStderrLine: (line) => {\n process.stderr.write(`[codex] ${line}\n`);\n }\n });\n const spawned = client;\n void spawned.exited.then(() => {\n if (client !== spawned) return;\n client = void 0;\n threadId = void 0;\n const orphaned = relay;\n relay = void 0;\n void orphaned?.close();\n });\n await client.request("initialize", {\n clientInfo: {\n name: "mcpjam-inspector",\n title: "MCPJam Inspector",\n version: "1.0.0"\n }\n });\n client.notify("initialized", {});\n };\n await runBridge({\n // Kept as `codex`: `bridge-meta.json`\'s type is matched by the framework\'s\n // `waitForBridgeReady`, and both Codex transports are the same harness id.\n bridgeType: "codex",\n bridgeStateDir: args.bridgeStateDir,\n onStop: () => ({ threadId }),\n onDestroy: async () => {\n await client?.kill();\n await relay?.close();\n },\n async onStart(start, turn) {\n const { approvalPolicy, sandbox, sandboxPolicy } = toCodexPermissions(\n start.permissionMode,\n {\n sandboxPolicy: start.sandboxPolicy,\n supervisedLocally: isSupervisedLocally()\n }\n );\n catalog = buildHostToolCatalog(start.tools ?? []);\n await ensureRuntime(start);\n const runtime = client;\n if (!runtime) throw new Error("codex app-server failed to start");\n activeTurn = {\n turn,\n aliasToCanonical: catalog.aliasToCanonical,\n toolCallSeq: 0\n };\n const translator = createStreamTranslator({\n emit: (event) => turn.emit(event),\n emitWarning: (input) => turn.emitWarning(input),\n emitError: (input) => turn.emitError(input),\n relayServerName: RELAY_MCP_SERVER_NAME\n });\n const approvals = createApprovalController({ turn, translator });\n runtime.onNotification((notification) => {\n translator.handleNotification(notification);\n });\n runtime.onServerRequest((request) => approvals.handle(request));\n const fingerprint = turnConfigurationFingerprint(start);\n const mustRestart = start.restartThread === true || lastFingerprint !== void 0 && lastFingerprint !== fingerprint;\n if (mustRestart) threadId = void 0;\n lastFingerprint = fingerprint;\n const threadParams = {\n cwd: args.workdir,\n approvalPolicy,\n sandbox,\n // Only meaningful when the policy asks anyone at all; harmless\n // otherwise, and explicit beats relying on a default.\n approvalsReviewer: "user",\n ...start.model ? { model: start.model } : {},\n ...start.instructions ? { developerInstructions: start.instructions } : {},\n ...withThreadConfig(start),\n serviceName: "mcpjam-inspector"\n };\n const resumeId = mustRestart ? void 0 : threadId ?? start.resumeThreadId;\n const thread = resumeId ? await runtime.request("thread/resume", {\n ...threadParams,\n threadId: resumeId\n }) : await runtime.request(\n "thread/start",\n threadParams\n );\n threadId = thread.thread?.id ?? resumeId;\n if (threadId) turn.emit({ type: "bridge-thread", threadId });\n turn.emit({\n type: "stream-start",\n ...thread.model ? { modelId: thread.model } : {}\n });\n const started = await runtime.request("turn/start", {\n threadId,\n input: [{ type: "text", text: start.prompt }],\n ...start.model ? { model: start.model } : {},\n ...start.reasoningEffort ? { effort: start.reasoningEffort } : {},\n // Explicit, every turn it applies to. The schema\'s own workspace-write\n // default leaves /tmp writable; see `shared/sandbox-policy.ts`.\n ...sandboxPolicy ? { sandboxPolicy } : {},\n summary: "detailed",\n ...start.responseFormat?.type === "json" && start.responseFormat.schema ? { outputSchema: start.responseFormat.schema } : {}\n });\n const turnId = started.turn?.id;\n const onAbort = () => {\n approvals.cancelAll();\n relay?.cancelAll("turn aborted");\n if (turnId) {\n void runtime.request("turn/interrupt", { threadId, turnId }).catch(() => {\n });\n }\n };\n if (turn.abortSignal.aborted) onAbort();\n else turn.abortSignal.addEventListener("abort", onAbort, { once: true });\n let settled = false;\n await Promise.race([\n translator.waitForTurn().then(() => {\n settled = true;\n }),\n runtime.exited.then((error) => {\n if (settled || !error) return;\n settled = true;\n turn.emitError({ error });\n translator.finishTurn({ status: "failed" });\n })\n ]);\n settled = true;\n activeTurn = void 0;\n }\n });\n}\nif (process.env.MCPJAM_CODEX_APPSERVER_BRIDGE_AUTOSTART === "true") {\n void main();\n}\nexport {\n CodexPermissionRefusedError,\n isSupervisedLocally,\n toCodexPermissions\n};\n\nmain();\n';
400
- var CODEX_APPSERVER_HOST_TOOLS_MCP_SOURCE = '// Generated by scripts/bundle-codex-appserver-bridge.mjs \u2014 do not edit.\n\n// server/utils/harness/codex-appserver/bridge/host-tools-mcp.ts\nimport { appendFileSync } from "node:fs";\nimport { request as httpRequest } from "node:http";\nvar relayFetch = ((input, init) => new Promise((resolve, reject) => {\n const req = httpRequest(\n String(input),\n { method: init?.method ?? "GET", headers: init?.headers ?? {} },\n (res) => {\n const chunks = [];\n res.on("data", (chunk) => chunks.push(chunk));\n res.on("error", reject);\n res.on("end", () => {\n const text = Buffer.concat(chunks).toString("utf8");\n const status = res.statusCode ?? 0;\n resolve({\n ok: status >= 200 && status < 300,\n status,\n json: async () => JSON.parse(text),\n text: async () => text\n });\n });\n }\n );\n req.on("error", reject);\n if (init?.body !== void 0) req.write(init.body);\n req.end();\n}));\nvar FALLBACK_PROTOCOL_VERSION = "2025-06-18";\nfunction createHostToolMcpServer(options) {\n const doFetch = options.fetchImpl ?? relayFetch;\n async function relay(path, init) {\n if (!options.relayUrl || !options.relayCredential) {\n throw new Error("host-tool relay is not configured for this session");\n }\n const response = await doFetch(`${options.relayUrl}${path}`, {\n method: init?.method ?? "GET",\n headers: {\n "x-mcpjam-relay-credential": options.relayCredential,\n ...init?.body ? { "content-type": "application/json" } : {}\n },\n ...init?.body ? { body: JSON.stringify(init.body) } : {}\n });\n if (!response.ok) {\n throw new Error(`relay ${path} failed with ${response.status}`);\n }\n return response.json();\n }\n const errorResult = (message) => ({\n content: [{ type: "text", text: message }],\n isError: true\n });\n return {\n async handle(frame) {\n const { id, method, params } = frame;\n if (id === void 0) return void 0;\n if (id === null) {\n return {\n id: null,\n error: {\n code: -32600,\n message: "Invalid Request: id must not be null"\n }\n };\n }\n if (method === "initialize") {\n return {\n id,\n result: {\n protocolVersion: params?.protocolVersion ?? FALLBACK_PROTOCOL_VERSION,\n capabilities: { tools: { listChanged: false } },\n serverInfo: { name: "mcpjam", version: "1.0.0" }\n }\n };\n }\n if (method === "tools/list") {\n try {\n const result = await relay("/tools");\n return { id, result: { tools: result.tools ?? [] } };\n } catch (error) {\n return {\n id,\n error: {\n code: -32603,\n message: error instanceof Error ? error.message : String(error)\n }\n };\n }\n }\n if (method === "tools/call") {\n const toolName = String(params?.name ?? "");\n try {\n const result = await relay("/call", {\n method: "POST",\n body: { toolName, input: params?.arguments ?? {} }\n });\n if (result.ok === false) {\n return {\n id,\n result: errorResult(result.error ?? "host tool failed")\n };\n }\n return { id, result: toMcpToolResult(result.result) };\n } catch (error) {\n return {\n id,\n result: errorResult(\n error instanceof Error ? error.message : String(error)\n )\n };\n }\n }\n if (method === "resources/list") return { id, result: { resources: [] } };\n if (method === "resources/templates/list") {\n return { id, result: { resourceTemplates: [] } };\n }\n if (method === "prompts/list") return { id, result: { prompts: [] } };\n return {\n id,\n error: { code: -32601, message: `method not found: ${method}` }\n };\n }\n };\n}\nfunction toMcpToolResult(result) {\n if (typeof result === "string") {\n return { content: [{ type: "text", text: result }] };\n }\n if (result && typeof result === "object" && Array.isArray(result.content)) {\n return result;\n }\n return {\n content: [{ type: "text", text: JSON.stringify(result ?? null) }],\n structuredContent: result\n };\n}\nfunction pumpJsonLines(input) {\n let buffer = "";\n input.stdin.setEncoding("utf8");\n input.stdin.on("data", (chunk) => {\n buffer += chunk;\n let index;\n while ((index = buffer.indexOf("\\n")) !== -1) {\n const line = buffer.slice(0, index).trim();\n buffer = buffer.slice(index + 1);\n if (!line) continue;\n let frame;\n try {\n frame = JSON.parse(line);\n } catch (error) {\n input.onParseError?.(line, error);\n continue;\n }\n void input.server.handle(frame).then((reply) => {\n if (reply)\n input.write(`${JSON.stringify({ jsonrpc: "2.0", ...reply })}\n`);\n });\n }\n });\n}\nfunction startHostToolMcpServer() {\n const debugLog = process.env.MCPJAM_HOST_TOOL_LOG;\n pumpJsonLines({\n server: createHostToolMcpServer({\n relayUrl: process.env.MCPJAM_HOST_TOOL_RELAY_URL,\n relayCredential: process.env.MCPJAM_HOST_TOOL_RELAY_CREDENTIAL\n }),\n stdin: process.stdin,\n write: (line) => process.stdout.write(line),\n onParseError: (line, error) => {\n if (!debugLog) return;\n try {\n appendFileSync(\n debugLog,\n `${JSON.stringify({ t: Date.now(), line, error: String(error) })}\n`\n );\n } catch {\n }\n }\n });\n process.stdin.on("end", () => process.exit(0));\n}\nif (process.env.MCPJAM_HOST_TOOL_MCP_AUTOSTART === "true") {\n startHostToolMcpServer();\n}\nexport {\n createHostToolMcpServer,\n pumpJsonLines,\n relayFetch,\n startHostToolMcpServer,\n toMcpToolResult\n};\n\nstartHostToolMcpServer();\n';
401
- var CODEX_APPSERVER_BOOTSTRAP_PACKAGE_JSON = '{\n "name": "mcpjam-codex-appserver-bootstrap",\n "version": "0.0.0",\n "private": true,\n "type": "module",\n "dependencies": {\n "@openai/codex": "0.149.1",\n "ws": "8.21.0"\n }\n}\n';
402
- var CODEX_APPSERVER_BOOTSTRAP_PNPM_LOCK = "lockfileVersion: '9.0'\n\nsettings:\n autoInstallPeers: true\n excludeLinksFromLockfile: false\n\nimporters:\n\n .:\n dependencies:\n '@openai/codex':\n specifier: 0.149.1\n version: 0.149.1\n ws:\n specifier: 8.21.0\n version: 8.21.0\n\npackages:\n\n '@openai/codex@0.149.1':\n resolution: {integrity: sha512-6q5pbcpFbJbqOpkubSDBwXmktQ55aD8eUzGzBF1zASob2DjwhBKDSNGtdZKalfrNJUdTDTPDMmzCXEXs5tMBYA==}\n engines: {node: '>=16'}\n hasBin: true\n\n '@openai/codex@0.149.1-darwin-arm64':\n resolution: {integrity: sha512-6X84kTCbnTgPIJ2EdcPsrvwS0Wxsqpa+bCswGmRf4BjhcQ5nPMnBC6yCAaCMj+vrbXQHj+L6sa9FaR4QkmA1qw==}\n engines: {node: '>=16'}\n cpu: [arm64]\n os: [darwin]\n\n '@openai/codex@0.149.1-darwin-x64':\n resolution: {integrity: sha512-MfLBQLfcElJL9tvj6y45qVHHMGSXCPnQOixuD3/Zq0g1BW/eFizkrGLdn48cFpc+l8cK+gt5nYG5pQYwVs6g4A==}\n engines: {node: '>=16'}\n cpu: [x64]\n os: [darwin]\n\n '@openai/codex@0.149.1-linux-arm64':\n resolution: {integrity: sha512-OqxUfZ1TVvHd18zHPKK/8ZRlpk8Vy11mg5CMHaLxNWldTbwVImDKtSLWT+m8m4NM5Sz4PbjtZMrVT/RfpBW/mQ==}\n engines: {node: '>=16'}\n cpu: [arm64]\n os: [linux]\n\n '@openai/codex@0.149.1-linux-x64':\n resolution: {integrity: sha512-Of5fGYgr7tAMsyj6vhXb4/RM/UoA3Zq8BLegUBDC09UNy1XTLGYP/2XD+UX8z3qh0NDwxYdCjFIWdDNijKZggQ==}\n engines: {node: '>=16'}\n cpu: [x64]\n os: [linux]\n\n '@openai/codex@0.149.1-win32-arm64':\n resolution: {integrity: sha512-5K0DmOKGK9Bos627p8sK8ATHjovPK0sDyT6h9Cb+4v+5CW5SGw1HLgjGxoLfJ8g3cg6mtg/pRCXXo2L/j71UVA==}\n engines: {node: '>=16'}\n cpu: [arm64]\n os: [win32]\n\n '@openai/codex@0.149.1-win32-x64':\n resolution: {integrity: sha512-G3QXGAg7nyyhqOeooAMUekBCeHd8a1QByhKcVAFyzNBaI06t6Ft7nsF+1SzFS0spuIdU4YyMi5YD26ukADBQUQ==}\n engines: {node: '>=16'}\n cpu: [x64]\n os: [win32]\n\n ws@8.21.0:\n resolution: {integrity: sha512-Vsp28b7DRcimFQvrqu2Wek3z1iYxDCWqHYB8Qsnk/S4RfaCQzPGPyBNuVjJV3cd6UiKtUtp6sNM77gWvzcCH+g==}\n engines: {node: '>=10.0.0'}\n peerDependencies:\n bufferutil: ^4.0.1\n utf-8-validate: '>=5.0.2'\n peerDependenciesMeta:\n bufferutil:\n optional: true\n utf-8-validate:\n optional: true\n\nsnapshots:\n\n '@openai/codex@0.149.1':\n optionalDependencies:\n '@openai/codex-darwin-arm64': '@openai/codex@0.149.1-darwin-arm64'\n '@openai/codex-darwin-x64': '@openai/codex@0.149.1-darwin-x64'\n '@openai/codex-linux-arm64': '@openai/codex@0.149.1-linux-arm64'\n '@openai/codex-linux-x64': '@openai/codex@0.149.1-linux-x64'\n '@openai/codex-win32-arm64': '@openai/codex@0.149.1-win32-arm64'\n '@openai/codex-win32-x64': '@openai/codex@0.149.1-win32-x64'\n\n '@openai/codex@0.149.1-darwin-arm64':\n optional: true\n\n '@openai/codex@0.149.1-darwin-x64':\n optional: true\n\n '@openai/codex@0.149.1-linux-arm64':\n optional: true\n\n '@openai/codex@0.149.1-linux-x64':\n optional: true\n\n '@openai/codex@0.149.1-win32-arm64':\n optional: true\n\n '@openai/codex@0.149.1-win32-x64':\n optional: true\n\n ws@8.21.0: {}\n";
403
- var CODEX_APPSERVER_BUNDLE_VERSION = "3934369f895e4a7fa5c302b7a1e69f6e";
404
-
405
- // server/utils/harness/codex-appserver/bridge/app-server-protocol.ts
406
- var PINNED_CODEX_VERSION = "0.149.1";
407
-
408
- // server/utils/harness/codex-appserver/local-identity.ts
409
- var CODEX_LOCAL_ADAPTER_IDENTITY = `app-server/${CODEX_APPSERVER_BUNDLE_VERSION}+@openai/codex@${PINNED_CODEX_VERSION}`;
410
- var CODEX_BRIDGE_BUNDLE_DIGEST = `sha256:${createHash("sha256").update(CODEX_APPSERVER_BRIDGE_SOURCE, "utf8").digest("hex")}`;
411
-
412
- // server/utils/harness/local/runtime-lifecycle.ts
413
- import { randomUUID as randomUUID2 } from "crypto";
414
- import {
415
- mkdir as mkdir2,
416
- readdir,
417
- readFile as readFile2,
418
- rename,
419
- rm as rm2,
420
- stat as stat2,
421
- writeFile as writeFile2
422
- } from "fs/promises";
423
- import { join as join2 } from "path";
424
-
425
- // server/utils/harness/local/local-state-lock.ts
426
- import { randomUUID } from "crypto";
427
- import { mkdir, readFile, rm, stat, writeFile } from "fs/promises";
428
- import { join } from "path";
429
- var DEFAULT_STALE_MS = 3e4;
430
- var DEFAULT_POLL_MS = 25;
431
- var DEFAULT_TIMEOUT_MS = 45e3;
432
- async function readLockBody(file) {
433
- try {
434
- const parsed = JSON.parse(await readFile(file, "utf8"));
435
- if (!parsed || typeof parsed !== "object") return null;
436
- const body = parsed;
437
- if (typeof body.pid !== "number" || !Number.isInteger(body.pid) || body.pid <= 0 || typeof body.nonce !== "string" || body.nonce.length === 0) {
438
- return null;
439
- }
440
- return { pid: body.pid, nonce: body.nonce, at: Number(body.at) || 0 };
441
- } catch {
442
- return null;
443
- }
444
- }
445
- function lockHolderProvablyGone(body) {
446
- if (body === null || body.pid === process.pid) return false;
447
- try {
448
- process.kill(body.pid, 0);
449
- return false;
450
- } catch (error) {
451
- return error.code === "ESRCH";
452
- }
453
- }
454
- function createLocalStateMutationLock(options) {
455
- let mutationChain = Promise.resolve();
456
- const staleMs = options.staleMs ?? DEFAULT_STALE_MS;
457
- const pollMs = options.pollMs ?? DEFAULT_POLL_MS;
458
- const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
459
- const acquire = async () => {
460
- const root = options.rootDir();
461
- const file = join(root, options.lockFileName);
462
- await mkdir(root, { recursive: true, mode: 448 });
463
- const nonce = randomUUID();
464
- const deadline = Date.now() + timeoutMs;
465
- for (; ; ) {
466
- try {
467
- await writeFile(
468
- file,
469
- JSON.stringify({ pid: process.pid, nonce, at: Date.now() }),
470
- { flag: "wx", mode: 384 }
471
- );
472
- return async () => {
473
- const held = await readLockBody(file);
474
- if (held?.nonce !== nonce) {
475
- logger.warn(
476
- `[local-harness] ${options.resourceLabel} lock was taken over; not releasing`
477
- );
478
- return;
479
- }
480
- await rm(file, { force: true }).catch(() => {
481
- });
482
- };
483
- } catch (error) {
484
- if (error.code !== "EEXIST") throw error;
485
- const body = await readLockBody(file);
486
- const age = await stat(file).then(
487
- (info) => Date.now() - info.mtimeMs,
488
- () => 0
489
- );
490
- const holderGone = lockHolderProvablyGone(body);
491
- const unattributable = body === null && age > staleMs;
492
- if (holderGone || unattributable) {
493
- logger.warn(
494
- `[local-harness] breaking an abandoned ${options.resourceLabel} lock`,
495
- { age, holderGone, unattributable }
496
- );
497
- await rm(file, { force: true }).catch(() => {
498
- });
499
- continue;
500
- }
501
- if (Date.now() > deadline) {
502
- throw new Error(
503
- `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."
504
- );
505
- }
506
- await new Promise(
507
- (resolvePromise) => setTimeout(resolvePromise, pollMs)
508
- );
509
- }
510
- }
511
- };
512
- return (operation) => {
513
- const guarded = async () => {
514
- const release = await acquire();
515
- try {
516
- return await operation();
517
- } finally {
518
- await release();
519
- }
520
- };
521
- const run = mutationChain.then(guarded, guarded);
522
- mutationChain = run.then(
523
- () => void 0,
524
- () => void 0
525
- );
526
- return run;
527
- };
528
- }
529
-
530
- // server/utils/harness/local/runtime-lifecycle.ts
531
- var OPERATION_FILE = ".mcpjam-operation.json";
532
- var USE_DIR = ".mcpjam-inuse";
533
- var STAGING_PREFIX = ".mcpjam-tmp-";
534
- var STAGING_OWNER_FILE = ".mcpjam-staging-owner.json";
535
- function operationKeyString(key) {
536
- return [
537
- key.runtimeRoot,
538
- key.harnessId,
539
- key.target,
540
- key.packVersion,
541
- key.treeDigest
542
- ].join("\0");
543
- }
544
- function harnessTargetInstallRoot(runtimeRoot, harnessId, target) {
545
- return harnessId === "claude-code" ? join2(runtimeRoot, target) : join2(runtimeRoot, harnessId, target);
546
- }
547
- function installRootOf(key) {
548
- return harnessTargetInstallRoot(key.runtimeRoot, key.harnessId, key.target);
549
- }
550
- var locksByRoot = /* @__PURE__ */ new Map();
551
- function lockFor(key) {
552
- const root = installRootOf(key);
553
- let lock = locksByRoot.get(root);
554
- if (lock === void 0) {
555
- lock = createLocalStateMutationLock({
556
- rootDir: () => root,
557
- lockFileName: ".mcpjam-runtime-lifecycle.lock",
558
- resourceLabel: "runtime lifecycle",
559
- // Short by construction: every critical section here is a read, a
560
- // compare and an atomic write. A caller waiting longer than this is
561
- // waiting on something that is not doing that.
562
- timeoutMs: 15e3
563
- });
564
- locksByRoot.set(root, lock);
565
- }
566
- return lock;
567
- }
568
- function ownerProvablyGone(record) {
569
- if (record.ownerPid === process.pid) {
570
- return record.ownerStartedAt !== processStartedAt();
571
- }
572
- try {
573
- process.kill(record.ownerPid, 0);
574
- return false;
575
- } catch (error) {
576
- return error.code === "ESRCH";
577
- }
578
- }
579
- var cachedStartedAt = null;
580
- function processStartedAt() {
581
- if (cachedStartedAt === null) {
582
- cachedStartedAt = Math.floor((Date.now() - process.uptime() * 1e3) / 1e3);
583
- }
584
- return cachedStartedAt;
585
- }
586
- async function writeJsonAtomic(file, value) {
587
- const tmp = `${file}.${process.pid}.${randomUUID2()}.tmp`;
588
- await writeFile2(tmp, `${JSON.stringify(value, null, 2)}
589
- `, { mode: 384 });
590
- await rename(tmp, file);
591
- }
592
- async function readJson(file) {
593
- try {
594
- return JSON.parse(await readFile2(file, "utf8"));
595
- } catch {
596
- return null;
597
- }
598
- }
599
- async function readRuntimeOperation(key) {
600
- const file = join2(installRootOf(key), OPERATION_FILE);
601
- const record = await readJson(file);
602
- if (record === null) return null;
603
- if (record.packVersion !== key.packVersion || record.treeDigest !== key.treeDigest || record.harnessId !== key.harnessId) {
604
- return null;
605
- }
606
- const terminal = record.state === "ready" || record.state === "failed" || record.state === "interrupted";
607
- if (terminal || !ownerProvablyGone(record)) return record;
608
- return lockFor(key)(async () => {
609
- const fresh = await readJson(file);
610
- if (fresh === null) return null;
611
- if (fresh.attemptId !== record.attemptId) return fresh;
612
- if (fresh.state === "ready" || fresh.state === "failed" || fresh.state === "interrupted") {
613
- return fresh;
614
- }
615
- if (!ownerProvablyGone(fresh)) return fresh;
616
- const reconciled = {
617
- ...fresh,
618
- state: "interrupted",
619
- message: "the Inspector that started this install is no longer running, so the attempt was abandoned partway through",
620
- updatedAt: Date.now()
621
- };
622
- await writeJsonAtomic(file, reconciled);
623
- logger.info("[local-harness] recovered an interrupted install attempt", {
624
- attemptId: reconciled.attemptId,
625
- packVersion: reconciled.packVersion
626
- });
627
- return reconciled;
628
- });
629
- }
630
- async function beginInstallAttempt(key) {
631
- const root = installRootOf(key);
632
- await mkdir2(root, { recursive: true, mode: 448 });
633
- const file = join2(root, OPERATION_FILE);
634
- return lockFor(key)(async () => {
635
- const existing = await readJson(file);
636
- if (existing !== null && existing.packVersion === key.packVersion && existing.treeDigest === key.treeDigest && existing.harnessId === key.harnessId) {
637
- const live = existing.state !== "ready" && existing.state !== "failed" && existing.state !== "interrupted";
638
- if (live && !ownerProvablyGone(existing)) {
639
- return { kind: "joined", record: existing };
640
- }
641
- }
642
- const record = {
643
- attemptId: `att_${randomUUID2()}`,
644
- ownerPid: process.pid,
645
- ownerStartedAt: processStartedAt(),
646
- harnessId: key.harnessId,
647
- target: key.target,
648
- packVersion: key.packVersion,
649
- treeDigest: key.treeDigest,
650
- state: "reserved",
651
- startedAt: Date.now(),
652
- updatedAt: Date.now()
653
- };
654
- await writeJsonAtomic(file, record);
655
- return { kind: "started", record };
656
- });
657
- }
658
- async function updateInstallAttempt(key, attemptId, patch) {
659
- const file = join2(installRootOf(key), OPERATION_FILE);
660
- return lockFor(key)(async () => {
661
- const existing = await readJson(file);
662
- if (existing === null || existing.attemptId !== attemptId) return false;
663
- await writeJsonAtomic(file, {
664
- ...existing,
665
- ...patch,
666
- updatedAt: Date.now()
667
- });
668
- return true;
669
- });
670
- }
671
- async function attemptStillOwns(key, attemptId) {
672
- const record = await readJson(
673
- join2(installRootOf(key), OPERATION_FILE)
674
- );
675
- return record?.attemptId === attemptId;
676
- }
677
- async function reserveRuntimeUse(args) {
678
- const dir = join2(installRootOf(args.key), USE_DIR);
679
- await mkdir2(dir, { recursive: true, mode: 448 });
680
- const file = join2(dir, `${process.pid}-${randomUUID2()}.json`);
681
- const record = {
682
- pid: process.pid,
683
- startedAt: processStartedAt(),
684
- runtimeRoot: args.runtimeRoot,
685
- at: Date.now(),
686
- ...args.label ? { label: args.label } : {}
687
- };
688
- await writeJsonAtomic(file, record);
689
- let released = false;
690
- return {
691
- release: async () => {
692
- if (released) return;
693
- released = true;
694
- await rm2(file, { force: true }).catch(() => {
695
- });
696
- }
697
- };
698
- }
699
- async function runtimeUseState(args) {
700
- const dir = join2(installRootOf(args.key), USE_DIR);
701
- let entries;
702
- try {
703
- entries = await readdir(dir);
704
- } catch {
705
- return { busy: false, holders: [] };
706
- }
707
- const holders = [];
708
- for (const entry of entries) {
709
- if (!entry.endsWith(".json")) continue;
710
- const file = join2(dir, entry);
711
- const record = await readJson(file);
712
- if (record === null) {
713
- continue;
714
- }
715
- if (record.runtimeRoot !== args.runtimeRoot) continue;
716
- if (ownerProvablyGone({ ownerPid: record.pid, ownerStartedAt: record.startedAt })) {
717
- await rm2(file, { force: true }).catch(() => {
718
- });
719
- continue;
720
- }
721
- holders.push(record.pid);
722
- }
723
- return { busy: holders.length > 0, holders };
724
- }
725
- async function claimStagingDirectory(args) {
726
- await writeJsonAtomic(join2(args.staging, STAGING_OWNER_FILE), {
727
- pid: process.pid,
728
- startedAt: processStartedAt(),
729
- attemptId: args.attemptId,
730
- at: Date.now()
731
- });
732
- }
733
- async function sweepAbandonedStaging(key) {
734
- const root = installRootOf(key);
735
- let entries;
736
- try {
737
- entries = await readdir(root);
738
- } catch {
739
- return { removed: 0, left: 0 };
740
- }
741
- let removed = 0;
742
- let left = 0;
743
- for (const entry of entries) {
744
- if (!entry.startsWith(STAGING_PREFIX)) continue;
745
- const path = join2(root, entry);
746
- const owner = await readJson(join2(path, STAGING_OWNER_FILE));
747
- if (owner === null) {
748
- left += 1;
749
- continue;
750
- }
751
- if (!ownerProvablyGone({ ownerPid: owner.pid, ownerStartedAt: owner.startedAt })) {
752
- left += 1;
753
- continue;
754
- }
755
- await rm2(path, { recursive: true, force: true }).catch(() => {
756
- });
757
- removed += 1;
758
- }
759
- if (removed > 0 || left > 0) {
760
- logger.debug("[local-harness] staging sweep", { removed, left });
761
- }
762
- return { removed, left };
763
- }
764
- async function recoverInterruptedActivation(args) {
765
- const previous = `${args.versionRoot}${PREVIOUS_SUFFIX}`;
766
- const hasPrevious = await stat2(previous).then(
767
- (info) => info.isDirectory(),
768
- () => false
769
- );
770
- if (!hasPrevious) return false;
771
- return lockFor(args.key)(async () => {
772
- const current = await stat2(args.versionRoot).then(
773
- (info) => info.isDirectory(),
774
- () => false
775
- );
776
- if (current) {
777
- await rm2(previous, { recursive: true, force: true }).catch(() => {
778
- });
779
- return false;
780
- }
781
- await rename(previous, args.versionRoot);
782
- logger.warn("[local-harness] restored a runtime after an interrupted activation", {
783
- packVersion: args.key.packVersion
784
- });
785
- return true;
786
- });
787
- }
788
- var PREVIOUS_SUFFIX = ".mcpjam-previous";
789
- function withRuntimeLifecycleLock(key, operation) {
790
- return lockFor(key)(operation);
791
- }
792
-
793
- // server/utils/harness/local/runtime-install.ts
794
- import { createHash as createHash3, randomUUID as randomUUID3 } from "crypto";
795
- import { createReadStream, createWriteStream } from "fs";
796
- import {
797
- mkdir as mkdir3,
798
- readdir as readdir4,
799
- readFile as readFile5,
800
- rename as rename2,
801
- rm as rm3,
802
- stat as stat4,
803
- writeFile as writeFile3
804
- } from "fs/promises";
805
- import { homedir } from "os";
806
- import { basename, join as join5 } from "path";
807
- import { pipeline } from "stream/promises";
808
- import { Readable } from "stream";
809
- import { x as extractTar } from "tar";
810
-
811
- // server/utils/harness/local/pack-digests.generated.ts
812
- var PACK_TREE_DIGESTS = {
813
- "claude-code": {
814
- "darwin-arm64": "sha256:6be44d7bf98cfb4eb536079835b1516883af2d076fa7911c51dfa4125424fe99",
815
- "darwin-x64": "sha256:174abc72bacec5d4bc73d6dbfabd7d350a17be78e8b0f2380c642424a62f749f",
816
- "linux-arm64": "sha256:06c84a9eae32a0eed410c7a757ee7847218a15bbb41c9e42b87b87496a2684c5",
817
- "linux-x64": "sha256:3e780532617863c2b8350a20e42bed091a76ca21f79a19106ccf6694712c6668",
818
- "win32-x64": "sha256:13a895fc012dc6d0ccb132a0a895c07e4ae80c9135629028a2508b155903ef5d"
819
- },
820
- "codex": {
821
- "darwin-arm64": "sha256:497de272c280b6ba555445703b45fc21c916754e18caa3476f17acbe36fa4eea",
822
- "darwin-x64": "sha256:70a5ef882831b15caaf5111a22daf444cd52e2ab5a725331c342c2a72b5b2afd",
823
- "linux-arm64": "sha256:4e402779f50063f3f983781c0e363306b6d5389b20a43c1c9910fd95db8866bd",
824
- "linux-x64": "sha256:446052eea51ca42947f4012b2a10ee63e936d772b64a1e00e153f8ff1dbec81f",
825
- "win32-x64": "sha256:4293b1a9cc8ed5484cb504a5c0d6a9bd5dec2b7a7e1ee4268e68bcb9e8421f82"
826
- }
827
- };
828
- var PACK_RECORDS = {
829
- "claude-code": {
830
- "darwin-arm64": {
831
- packVersion: "1.0.0",
832
- treeDigest: "sha256:6be44d7bf98cfb4eb536079835b1516883af2d076fa7911c51dfa4125424fe99"
833
- },
834
- "darwin-x64": {
835
- packVersion: "1.0.0",
836
- treeDigest: "sha256:174abc72bacec5d4bc73d6dbfabd7d350a17be78e8b0f2380c642424a62f749f"
837
- },
838
- "linux-arm64": {
839
- packVersion: "1.0.0",
840
- treeDigest: "sha256:06c84a9eae32a0eed410c7a757ee7847218a15bbb41c9e42b87b87496a2684c5"
841
- },
842
- "linux-x64": {
843
- packVersion: "1.0.0",
844
- treeDigest: "sha256:3e780532617863c2b8350a20e42bed091a76ca21f79a19106ccf6694712c6668"
845
- },
846
- "win32-x64": {
847
- packVersion: "1.0.0",
848
- treeDigest: "sha256:13a895fc012dc6d0ccb132a0a895c07e4ae80c9135629028a2508b155903ef5d"
849
- }
850
- },
851
- "codex": {
852
- "darwin-arm64": {
853
- packVersion: "1.0.0",
854
- treeDigest: "sha256:497de272c280b6ba555445703b45fc21c916754e18caa3476f17acbe36fa4eea"
855
- },
856
- "darwin-x64": {
857
- packVersion: "1.0.0",
858
- treeDigest: "sha256:70a5ef882831b15caaf5111a22daf444cd52e2ab5a725331c342c2a72b5b2afd"
859
- },
860
- "linux-arm64": {
861
- packVersion: "1.0.0",
862
- treeDigest: "sha256:4e402779f50063f3f983781c0e363306b6d5389b20a43c1c9910fd95db8866bd"
863
- },
864
- "linux-x64": {
865
- packVersion: "1.0.0",
866
- treeDigest: "sha256:446052eea51ca42947f4012b2a10ee63e936d772b64a1e00e153f8ff1dbec81f"
867
- },
868
- "win32-x64": {
869
- packVersion: "1.0.0",
870
- treeDigest: "sha256:4293b1a9cc8ed5484cb504a5c0d6a9bd5dec2b7a7e1ee4268e68bcb9e8421f82"
871
- }
872
- }
873
- };
874
- var EXPECTED_PACK_VERSIONS = {
875
- "claude-code": "1.0.0",
876
- "codex": "1.0.0"
877
- };
878
-
879
- // server/utils/harness/local/pack-naming.ts
880
- var LEGACY_NAMED_HARNESS = "claude-code";
881
- function packReleaseTag(harnessId, packVersion) {
882
- return harnessId === LEGACY_NAMED_HARNESS ? `local-harness-pack-v${packVersion}` : `local-harness-pack-${harnessId}-v${packVersion}`;
883
- }
884
- function packAssetStem(harnessId, target, packVersion) {
885
- return harnessId === LEGACY_NAMED_HARNESS ? `local-harness-pack-${target}-${packVersion}` : `local-harness-pack-${harnessId}-${target}-${packVersion}`;
886
- }
887
- function packReleaseBaseUrl(harnessId, packVersion) {
888
- return `https://github.com/MCPJam/inspector/releases/download/${packReleaseTag(harnessId, packVersion)}/`;
889
- }
890
-
891
- // server/utils/harness/local/pack-signing-key.ts
892
- import { createPublicKey, verify as edVerify } from "crypto";
893
- var PACK_SIGNING_KEYS = [
894
- {
895
- // Rotated before the first pack publication on 2026-09-28. The private
896
- // key was uploaded directly to the protected release environment; no
897
- // file or repository-level secret retains it. Recovery is rotation.
898
- keyId: "pack-2026-09-28",
899
- publicKeyPem: `-----BEGIN PUBLIC KEY-----
900
- MCowBQYDK2VwAyEA/8fkvTTgyzjmmlLmN4veODTVpexBi4Ib6SGVq8xmyTs=
901
- -----END PUBLIC KEY-----
902
- `
903
- }
904
- ];
905
- function verifyPackManifestSignature(manifestBytes, signatureBase64, keys = PACK_SIGNING_KEYS) {
906
- if (keys.length === 0) {
907
- return {
908
- ok: false,
909
- reason: "no-keys",
910
- 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."
911
- };
912
- }
913
- let signature;
914
- try {
915
- signature = Buffer.from(signatureBase64.trim(), "base64");
916
- if (signature.length === 0) throw new Error("empty");
917
- } catch {
918
- return {
919
- ok: false,
920
- reason: "malformed",
921
- message: "the pack manifest signature is not valid base64"
922
- };
923
- }
924
- for (const key of keys) {
925
- try {
926
- const publicKey = createPublicKey(key.publicKeyPem);
927
- if (edVerify(null, manifestBytes, publicKey, signature)) {
928
- return { ok: true, keyId: key.keyId };
929
- }
930
- } catch {
931
- continue;
932
- }
933
- }
934
- return {
935
- ok: false,
936
- reason: "bad-signature",
937
- message: "the runtime pack manifest is not signed by any key this Inspector trusts, so the pack is refused"
938
- };
939
- }
940
-
941
- // server/utils/harness/local/runtime-identity.ts
942
- import { createHash as createHash2 } from "crypto";
943
- import { execFile as execFile2 } from "child_process";
944
- import { readdir as readdir3, readFile as readFile4, realpath, stat as stat3 } from "fs/promises";
945
- import { dirname, isAbsolute, join as join4, normalize, relative, sep } from "path";
946
-
947
- // server/utils/harness/local/process-identity.ts
948
- import { execFile, spawn } from "child_process";
949
- import { readdir as readdir2, readFile as readFile3 } from "fs/promises";
950
- import { join as join3 } from "path";
951
- var PS_TIMEOUT_MS = 3e3;
952
- function parseLinuxProcStat(raw) {
953
- const close = raw.lastIndexOf(")");
954
- if (close === -1) return null;
955
- const fields = raw.slice(close + 2).split(" ");
956
- const state = fields[0];
957
- const starttime = fields[19];
958
- if (!state || !/^[A-Za-z]$/.test(state)) return null;
959
- if (!starttime || !/^\d+$/.test(starttime)) return null;
960
- return { state, starttime };
961
- }
962
- function isDeadState(state) {
963
- return state === "Z" || state === "X" || state === "x";
964
- }
965
- async function probeLinux(pid) {
966
- let raw;
967
- try {
968
- raw = await readFile3(`/proc/${pid}/stat`, "utf8");
969
- } catch (error) {
970
- const code = error.code;
971
- if (code === "ENOENT" || code === "ESRCH") return { state: "gone" };
972
- return {
973
- state: "unknown",
974
- reason: `/proc read failed (${code ?? "unknown"})`
975
- };
976
- }
977
- const parsed = parseLinuxProcStat(raw);
978
- if (parsed === null) {
979
- return { state: "unknown", reason: "unparseable /proc stat line" };
980
- }
981
- if (isDeadState(parsed.state)) return { state: "gone" };
982
- return { state: "alive", identity: `linux:${parsed.starttime}` };
983
- }
984
- function parseDarwinPsLine(raw) {
985
- const line = raw.trim();
986
- if (line.length === 0) return null;
987
- const match = /^(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+([\s\S]+)$/.exec(line);
988
- if (match === null) return null;
989
- const state = match[1];
990
- const lstart = [match[2], match[3], match[4], match[5], match[6]].join(" ");
991
- const command = match[7];
992
- return { state, lstart, command };
993
- }
994
- async function probeDarwin(pid) {
995
- const result = await new Promise((resolve) => {
996
- execFile(
997
- "/bin/ps",
998
- ["-o", "state=,lstart=,command=", "-p", String(pid)],
999
- {
1000
- timeout: PS_TIMEOUT_MS,
1001
- maxBuffer: 16 * 1024,
1002
- encoding: "utf8",
1003
- env: {}
1004
- },
1005
- (error, out) => {
1006
- if (!error) {
1007
- resolve({ ok: true, stdout: typeof out === "string" ? out : "" });
1008
- return;
1009
- }
1010
- const err = error;
1011
- resolve({
1012
- ok: false,
1013
- // `ps` exits 1 when no process matches — that IS an answer. A kill
1014
- // (timeout) or a spawn failure is not.
1015
- exitCode: typeof err.code === "number" ? err.code : null,
1016
- reason: err.killed ? "ps timed out" : `ps failed (${String(err.code ?? "unknown")})`
1017
- });
1018
- }
1019
- );
1020
- });
1021
- if (!result.ok) {
1022
- if (result.exitCode === 1) return { state: "gone" };
1023
- return { state: "unknown", reason: result.reason };
1024
- }
1025
- const parsed = parseDarwinPsLine(result.stdout);
1026
- if (parsed === null) {
1027
- return result.stdout.trim().length === 0 ? { state: "gone" } : { state: "unknown", reason: "unparseable ps output" };
1028
- }
1029
- if (isDeadState(parsed.state.charAt(0))) return { state: "gone" };
1030
- return {
1031
- state: "alive",
1032
- identity: `darwin:${parsed.lstart}|${parsed.command}`
1033
- };
1034
- }
1035
- var WIN32_PROBE_TIMEOUT_MS = 15e3;
1036
- function win32SystemRoot() {
1037
- return process.env.SYSTEMROOT ?? process.env.WINDIR ?? "C:\\Windows";
1038
- }
1039
- function win32PowerShellPath() {
1040
- return join3(
1041
- win32SystemRoot(),
1042
- "System32",
1043
- "WindowsPowerShell",
1044
- "v1.0",
1045
- "powershell.exe"
1046
- );
1047
- }
1048
- function parseWin32ProbeLine(raw) {
1049
- const line = raw.trim();
1050
- const match = /^(\d+)\|(.+)$/.exec(line);
1051
- if (match === null) return null;
1052
- return { fileTime: match[1], name: match[2] };
1053
- }
1054
- async function probeWin32(pid) {
1055
- try {
1056
- process.kill(pid, 0);
1057
- } catch (error) {
1058
- const code = error.code;
1059
- if (code === "ESRCH") return { state: "gone" };
1060
- if (code !== "EPERM") {
1061
- return {
1062
- state: "unknown",
1063
- reason: `kill(0) failed (${code ?? "unknown"})`
1064
- };
1065
- }
1066
- }
1067
- const script = [
1068
- `$p = Get-Process -Id ${pid} -ErrorAction SilentlyContinue`,
1069
- "if ($null -eq $p) { exit 1 }",
1070
- "try { $t = $p.StartTime.ToFileTimeUtc() } catch { exit 3 }",
1071
- "Write-Output ('{0}|{1}' -f $t, $p.ProcessName)"
1072
- ].join("; ");
1073
- const result = await new Promise((resolve) => {
1074
- let settled = false;
1075
- let timer;
1076
- const done = (value) => {
1077
- if (settled) return;
1078
- settled = true;
1079
- if (timer !== void 0) clearTimeout(timer);
1080
- resolve(value);
1081
- };
1082
- let child;
1083
- try {
1084
- child = spawn(
1085
- win32PowerShellPath(),
1086
- [
1087
- "-NoProfile",
1088
- "-NonInteractive",
1089
- "-InputFormat",
1090
- "None",
1091
- "-ExecutionPolicy",
1092
- "Bypass",
1093
- "-Command",
1094
- script
1095
- ],
1096
- { stdio: ["ignore", "pipe", "pipe"], env: process.env, windowsHide: true }
1097
- );
1098
- } catch (error) {
1099
- done({
1100
- ok: false,
1101
- exitCode: null,
1102
- reason: `PowerShell failed to start (${String(
1103
- error.code ?? "unknown"
1104
- )})`
1105
- });
1106
- return;
1107
- }
1108
- let stdout = "";
1109
- child.stdout?.setEncoding("utf8");
1110
- child.stdout?.on("data", (chunk) => {
1111
- if (stdout.length < 16 * 1024) stdout += chunk;
1112
- });
1113
- child.stderr?.resume();
1114
- timer = setTimeout(() => {
1115
- try {
1116
- child.kill();
1117
- } catch {
1118
- }
1119
- done({ ok: false, exitCode: null, reason: "Get-Process timed out" });
1120
- }, WIN32_PROBE_TIMEOUT_MS);
1121
- child.on(
1122
- "error",
1123
- (error) => done({
1124
- ok: false,
1125
- exitCode: null,
1126
- reason: `PowerShell failed (${String(error.code ?? "unknown")})`
1127
- })
1128
- );
1129
- child.on("close", (code) => {
1130
- if (code === 0) done({ ok: true, stdout });
1131
- else done({ ok: false, exitCode: code, reason: `Get-Process exited ${code}` });
1132
- });
1133
- });
1134
- if (!result.ok) {
1135
- if (result.exitCode === 1) return { state: "gone" };
1136
- return { state: "unknown", reason: result.reason };
1137
- }
1138
- const parsed = parseWin32ProbeLine(result.stdout);
1139
- if (parsed === null) {
1140
- return { state: "unknown", reason: "unparseable Get-Process output" };
1141
- }
1142
- return {
1143
- state: "alive",
1144
- identity: `win32:${parsed.fileTime}|${parsed.name}`
1145
- };
1146
- }
1147
- async function probeProcess(pid, platform = process.platform) {
1148
- if (!Number.isInteger(pid) || pid <= 0) {
1149
- return { state: "unknown", reason: "implausible pid" };
1150
- }
1151
- if (platform === "linux") return probeLinux(pid);
1152
- if (platform === "darwin") return probeDarwin(pid);
1153
- if (platform === "win32") return probeWin32(pid);
1154
- return { state: "unknown", reason: `no liveness primitive on ${platform}` };
1155
- }
1156
- async function readProcessBirthIdentity(pid, platform = process.platform) {
1157
- const probe = await probeProcess(pid, platform);
1158
- return probe.state === "alive" ? probe.identity : null;
1159
- }
1160
- function supportsOwnershipProof(platform = process.platform) {
1161
- if (platform === "linux" || platform === "darwin") return true;
1162
- if (platform === "win32") return windowsJobLauncherVerified;
1163
- return false;
1164
- }
1165
- var windowsJobLauncherVerified = false;
1166
- function setWindowsJobLauncherVerified(verified) {
1167
- windowsJobLauncherVerified = verified;
1168
- }
1169
- function sameBirthIdentity(recorded, current) {
1170
- if (recorded === current) return true;
1171
- const r = /^darwin:([^|]+)\|([\s\S]*)$/.exec(recorded);
1172
- const c = /^darwin:([^|]+)\|([\s\S]*)$/.exec(current);
1173
- if (r === null || c === null) return false;
1174
- return r[1] === c[1] && /^\([^()]+\)$/.test(c[2]);
1175
- }
1176
- async function listGroupMembers(pgid, platform = process.platform) {
1177
- let pids = [];
1178
- if (platform === "darwin") {
1179
- const out = await new Promise((resolve) => {
1180
- execFile(
1181
- "/bin/ps",
1182
- ["-o", "pid=,state=", "-g", String(pgid)],
1183
- { timeout: PS_TIMEOUT_MS, maxBuffer: 64 * 1024, encoding: "utf8", env: {} },
1184
- (error, stdout) => resolve(error ? error.code === 1 ? "" : null : String(stdout))
1185
- );
1186
- });
1187
- if (out === null) return null;
1188
- 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]));
1189
- } else if (platform === "linux") {
1190
- let entries;
1191
- try {
1192
- entries = await readdir2("/proc");
1193
- } catch {
1194
- return null;
1195
- }
1196
- for (const entry of entries) {
1197
- if (!/^\d+$/.test(entry)) continue;
1198
- let raw;
1199
- try {
1200
- raw = await readFile3(`/proc/${entry}/stat`, "utf8");
1201
- } catch {
1202
- continue;
1203
- }
1204
- const parsed = parseProcStatGroup(raw);
1205
- if (parsed !== null && parsed.pgrp === pgid && !isDeadState(parsed.state.charAt(0))) pids.push(Number(entry));
1206
- }
1207
- } else {
1208
- return null;
1209
- }
1210
- const members = [];
1211
- for (const pid of pids) {
1212
- if (pid === pgid) continue;
1213
- const identity = await readProcessBirthIdentity(pid, platform);
1214
- if (identity !== null) members.push({ pid, identity });
1215
- }
1216
- return members;
1217
- }
1218
- async function terminateOwnedProcess(args) {
1219
- const platform = args.platform ?? process.platform;
1220
- const initial = await probeProcess(args.pid, platform);
1221
- if (initial.state === "gone") return "already-gone";
1222
- if (initial.state === "unknown") return "unknown";
1223
- if (!sameBirthIdentity(args.identity, initial.identity)) return "not-owned";
1224
- const waitGone = async (ms) => {
1225
- const until = Date.now() + ms;
1226
- while (Date.now() < until) {
1227
- const p = await probeProcess(args.pid, platform);
1228
- if (p.state === "gone") return true;
1229
- await new Promise((r) => setTimeout(r, 50));
1230
- }
1231
- return false;
1232
- };
1233
- try {
1234
- process.kill(args.pid, "SIGTERM");
1235
- } catch {
1236
- return "already-gone";
1237
- }
1238
- if (await waitGone(args.graceMs)) return "graceful";
1239
- const again = await probeProcess(args.pid, platform);
1240
- if (again.state === "gone") return "graceful";
1241
- if (again.state === "unknown") return "unknown";
1242
- if (!sameBirthIdentity(args.identity, again.identity)) return "not-owned";
1243
- try {
1244
- process.kill(args.pid, "SIGKILL");
1245
- } catch {
1246
- return "graceful";
1247
- }
1248
- return await waitGone(500) ? "forced" : "escaped";
1249
- }
1250
- async function probeProcessGroup(pid, platform = process.platform) {
1251
- if (!Number.isInteger(pid) || pid <= 0) return "unknown";
1252
- if (platform === "linux") return probeLinuxGroup(pid);
1253
- if (platform === "darwin") return probeDarwinGroup(pid);
1254
- if (platform === "win32") {
1255
- const root = await probeProcess(pid, platform);
1256
- if (root.state === "gone") return "empty";
1257
- if (root.state === "alive") return "live";
1258
- return "unknown";
1259
- }
1260
- return "unknown";
1261
- }
1262
- async function readProcessGroupId(pid, platform = process.platform) {
1263
- if (!Number.isInteger(pid) || pid <= 0) return null;
1264
- if (platform === "linux") {
1265
- try {
1266
- const raw = await readFile3(`/proc/${pid}/stat`, "utf8");
1267
- return parseProcStatGroup(raw)?.pgrp ?? null;
1268
- } catch {
1269
- return null;
1270
- }
1271
- }
1272
- if (platform === "darwin") {
1273
- return new Promise((resolvePromise) => {
1274
- execFile(
1275
- "/bin/ps",
1276
- ["-o", "pgid=", "-p", String(pid)],
1277
- {
1278
- timeout: PS_TIMEOUT_MS,
1279
- maxBuffer: 4 * 1024,
1280
- encoding: "utf8",
1281
- env: {}
1282
- },
1283
- (error, stdout) => {
1284
- if (error) {
1285
- resolvePromise(null);
1286
- return;
1287
- }
1288
- const parsed = Number(String(stdout).trim());
1289
- resolvePromise(Number.isInteger(parsed) && parsed > 0 ? parsed : null);
1290
- }
1291
- );
1292
- });
1293
- }
1294
- return null;
1295
- }
1296
- function parseProcStatGroup(raw) {
1297
- const close = raw.lastIndexOf(")");
1298
- if (close === -1) return null;
1299
- const fields = raw.slice(close + 1).trim().split(/\s+/);
1300
- const state = fields[0];
1301
- const pgrp = Number(fields[2]);
1302
- if (state === void 0 || !Number.isInteger(pgrp)) return null;
1303
- return { state, pgrp };
1304
- }
1305
- async function probeLinuxGroup(pgid) {
1306
- let entries;
1307
- try {
1308
- entries = await readdir2("/proc");
1309
- } catch {
1310
- return "unknown";
1311
- }
1312
- let blind = false;
1313
- for (const entry of entries) {
1314
- if (!/^\d+$/.test(entry)) continue;
1315
- let raw;
1316
- try {
1317
- raw = await readFile3(`/proc/${entry}/stat`, "utf8");
1318
- } catch (error) {
1319
- const code = error.code;
1320
- if (code !== "ENOENT" && code !== "ESRCH") blind = true;
1321
- continue;
1322
- }
1323
- const parsed = parseProcStatGroup(raw);
1324
- if (parsed === null) {
1325
- blind = true;
1326
- continue;
1327
- }
1328
- if (parsed.pgrp !== pgid) continue;
1329
- if (!isDeadState(parsed.state.charAt(0))) return "live";
1330
- }
1331
- return blind ? "unknown" : "empty";
1332
- }
1333
- async function probeDarwinGroup(pgid) {
1334
- const result = await new Promise((resolve) => {
1335
- execFile(
1336
- "/bin/ps",
1337
- ["-o", "state=", "-g", String(pgid)],
1338
- {
1339
- timeout: PS_TIMEOUT_MS,
1340
- maxBuffer: 64 * 1024,
1341
- encoding: "utf8",
1342
- env: {}
1343
- },
1344
- (error, out) => {
1345
- if (!error) {
1346
- resolve({ ok: true, stdout: typeof out === "string" ? out : "" });
1347
- return;
1348
- }
1349
- const err = error;
1350
- resolve({ ok: false, empty: err.killed !== true && err.code === 1 });
1351
- }
1352
- );
1353
- });
1354
- if (!result.ok) return result.empty ? "empty" : "unknown";
1355
- const states = result.stdout.split("\n").map((line) => line.trim()).filter((line) => line.length > 0);
1356
- if (states.some((state) => !isDeadState(state.charAt(0)))) return "live";
1357
- return "empty";
1358
- }
1359
- function signalProcessGroup(pid, signal, platform = process.platform) {
1360
- if (!Number.isInteger(pid) || pid <= 0) return false;
1361
- try {
1362
- if (platform === "win32") {
1363
- process.kill(pid, signal);
1364
- return true;
1365
- }
1366
- process.kill(-pid, signal);
1367
- return true;
1368
- } catch (error) {
1369
- if (error.code === "ESRCH") return true;
1370
- return false;
1371
- }
1372
- }
1373
- async function terminateOwnedProcessGroup(args) {
1374
- const platform = args.platform ?? process.platform;
1375
- const pollMs = args.pollMs ?? 50;
1376
- const settleGroup = async (goneOutcome, anchored) => {
1377
- const probeGroup = args.probeGroup ?? probeProcessGroup;
1378
- const before = await probeGroup(args.pid, platform);
1379
- if (before === "empty") return { outcome: goneOutcome };
1380
- if (before === "unknown") {
1381
- return {
1382
- outcome: "unknown",
1383
- reason: "the process group could not be enumerated, so a survivor could be neither ruled out nor signalled without risking a reused group id"
1384
- };
1385
- }
1386
- if (!anchored) {
1387
- return {
1388
- outcome: "unknown",
1389
- 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"
1390
- };
1391
- }
1392
- signalProcessGroup(args.pid, "SIGKILL", platform);
1393
- await new Promise((r) => setTimeout(r, Math.min(args.graceMs, 500)));
1394
- const after = await probeGroup(args.pid, platform);
1395
- if (after === "empty") return { outcome: "forced" };
1396
- if (after === "unknown") {
1397
- return {
1398
- outcome: "unknown",
1399
- reason: "the process group could not be enumerated after SIGKILL"
1400
- };
1401
- }
1402
- return { outcome: "escaped" };
1403
- };
1404
- const initial = await probeProcess(args.pid, platform);
1405
- if (initial.state === "gone") return settleGroup("already-gone", false);
1406
- if (initial.state === "unknown") {
1407
- return { outcome: "unknown", reason: initial.reason };
1408
- }
1409
- if (!sameBirthIdentity(args.birthIdentity, initial.identity)) {
1410
- return { outcome: "not-owned" };
1411
- }
1412
- signalProcessGroup(args.pid, "SIGTERM", platform);
1413
- const deadline = Date.now() + args.graceMs;
1414
- while (Date.now() < deadline) {
1415
- await new Promise((r) => setTimeout(r, pollMs));
1416
- if ((await probeProcess(args.pid, platform)).state === "gone") {
1417
- return settleGroup("graceful", true);
1418
- }
1419
- }
1420
- const afterGrace = await probeProcess(args.pid, platform);
1421
- if (afterGrace.state === "gone") return settleGroup("graceful", true);
1422
- if (afterGrace.state === "unknown") {
1423
- return { outcome: "unknown", reason: afterGrace.reason };
1424
- }
1425
- if (!sameBirthIdentity(args.birthIdentity, afterGrace.identity)) {
1426
- return settleGroup("graceful", true);
1427
- }
1428
- signalProcessGroup(args.pid, "SIGKILL", platform);
1429
- const killDeadline = Date.now() + Math.max(args.graceMs, 1e3);
1430
- while (Date.now() < killDeadline) {
1431
- await new Promise((r) => setTimeout(r, pollMs));
1432
- if ((await probeProcess(args.pid, platform)).state === "gone") {
1433
- return settleGroup("forced", true);
1434
- }
1435
- }
1436
- const settled = await probeProcess(args.pid, platform);
1437
- if (settled.state === "gone") return settleGroup("forced", true);
1438
- if (settled.state === "unknown") {
1439
- return { outcome: "unknown", reason: settled.reason };
1440
- }
1441
- return { outcome: "escaped" };
1442
- }
1443
-
1444
- // server/utils/harness/local/runtime-rehash-policy.ts
1445
- var BUNDLED_NODE = /^bin\/node(\.exe)?$/;
1446
- var RUNTIME_REHASH_POLICIES = {
1447
- "claude-code": {
1448
- always: ["launcher.mjs", "bridge.mjs"],
1449
- strict: [
1450
- BUNDLED_NODE,
1451
- /(^|\/)claude-agent-sdk-[a-z0-9-]+\/(claude|claude\.exe)$/,
1452
- /(^|\/)claude-code-[a-z0-9-]+\/(claude|claude\.exe)$/
1453
- ]
1454
- },
1455
- codex: {
1456
- // `host-tools-mcp.mjs` is the second entrypoint: Codex spawns it as its
1457
- // MCP server, so it executes exactly like the bridge does.
1458
- always: ["launcher.mjs", "bridge.mjs", "host-tools-mcp.mjs"],
1459
- strict: [
1460
- BUNDLED_NODE,
1461
- // `@openai/codex-<platform>/vendor/<triple>/…`: the CLI and its
1462
- // code-mode host, the bundled ripgrep, and the sandbox helpers Codex
1463
- // execs (bubblewrap on Linux, the shell it wraps commands in).
1464
- /(^|\/)@openai\/codex-[a-z0-9-]+\/vendor\/[^/]+\/(bin\/[^/]+|codex-path\/[^/]+|codex-resources\/bwrap|codex-resources\/zsh\/bin\/zsh|codex-resources\/[^/]+\.exe)$/,
1465
- // The wrapper the bridge runs (`node …/bin/codex.js`) to find that CLI.
1466
- /(^|\/)@openai\/codex\/bin\/codex\.js$/
1467
- ]
1468
- }
1469
- };
1470
- function rehashPolicyFor(harnessId) {
1471
- return Object.prototype.hasOwnProperty.call(RUNTIME_REHASH_POLICIES, harnessId) ? RUNTIME_REHASH_POLICIES[harnessId] : { always: ["launcher.mjs", "bridge.mjs"], strict: [BUNDLED_NODE] };
1472
- }
1473
-
1474
- // server/utils/harness/local/runtime-identity.ts
1475
- var MAX_BUNDLE_FILES = 5e4;
1476
- var MAX_BUNDLE_BYTES = 2 * 1024 * 1024 * 1024;
1477
- var PROBE_TIMEOUT_MS = 5e3;
1478
- var PROBE_MAX_BUFFER = 64 * 1024;
1479
- async function computeTreeDigest(root) {
1480
- return (await digestTreeWithSnapshot(root, "")).digest;
1481
- }
1482
- async function digestTreeWithSnapshot(root, harnessId) {
1483
- const policy = rehashPolicyFor(harnessId);
1484
- const hash = createHash2("sha256");
1485
- const entriesSnapshot = [];
1486
- const executableDigests = {};
1487
- let files = 0;
1488
- let bytes = 0;
1489
- const walk = async (dir) => {
1490
- const entries = await readdir3(dir, { withFileTypes: true });
1491
- entries.sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
1492
- for (const entry of entries) {
1493
- const full = join4(dir, entry.name);
1494
- const rel = relative(root, full).split(sep).join("/");
1495
- if (entry.isSymbolicLink()) {
1496
- throw new Error(
1497
- `managed runtime bundle contains a symlink at ${rel}; bundles are built as plain files so their digest describes exactly what runs`
1498
- );
1499
- }
1500
- if (entry.isDirectory()) {
1501
- hash.update(`d\0${rel}\0`);
1502
- await walk(full);
1503
- continue;
1504
- }
1505
- if (!entry.isFile()) {
1506
- throw new Error(
1507
- `managed runtime bundle contains a non-regular file at ${rel}`
1508
- );
1509
- }
1510
- if (++files > MAX_BUNDLE_FILES) {
1511
- throw new Error(
1512
- "managed runtime bundle exceeds the file-count ceiling"
1513
- );
1514
- }
1515
- const info = await stat3(full);
1516
- bytes += info.size;
1517
- if (bytes > MAX_BUNDLE_BYTES) {
1518
- throw new Error("managed runtime bundle exceeds the size ceiling");
1519
- }
1520
- const content = await readFile4(full);
1521
- const executable = (info.mode & 73) !== 0 ? "1" : "0";
1522
- const contentDigest = createHash2("sha256").update(content).digest();
1523
- hash.update(`f\0${rel}\0${executable}\0${info.size}\0`);
1524
- hash.update(contentDigest);
1525
- entriesSnapshot.push({
1526
- path: rel,
1527
- size: info.size,
1528
- mtimeMs: info.mtimeMs,
1529
- ctimeMs: info.ctimeMs,
1530
- ino: Number(info.ino),
1531
- mode: info.mode
1532
- });
1533
- if (isBaselineHashed(policy, rel)) {
1534
- executableDigests[rel] = contentDigest.toString("hex");
1535
- }
1536
- }
1537
- };
1538
- await walk(root);
1539
- return {
1540
- root,
1541
- harnessId,
1542
- digest: `sha256:${hash.digest("hex")}`,
1543
- entries: entriesSnapshot,
1544
- executableDigests
1545
- };
1546
- }
1547
- function strictReverifyEnabled() {
1548
- return process.env.MCPJAM_LOCAL_HARNESS_STRICT_REVERIFY === "true";
1549
- }
1550
- function isBaselineHashed(policy, relativePath) {
1551
- return policy.always.includes(relativePath) || policy.strict.some((pattern) => pattern.test(relativePath));
1552
- }
1553
- function isRehashedOnRevalidate(policy, relativePath) {
1554
- if (policy.always.includes(relativePath)) return true;
1555
- return strictReverifyEnabled() && policy.strict.some((pattern) => pattern.test(relativePath));
1556
- }
1557
- var verifiedRuntimeCache = /* @__PURE__ */ new Map();
1558
- var inFlightVerifications = /* @__PURE__ */ new Map();
1559
- function verificationCacheKey(root, expectedDigest, harnessId) {
1560
- return `${root}\0${expectedDigest}\0${harnessId}`;
1561
- }
1562
- var cacheGeneration = 0;
1563
- function clearRuntimeVerificationCache() {
1564
- cacheGeneration += 1;
1565
- verifiedRuntimeCache.clear();
1566
- inFlightVerifications.clear();
1567
- }
1568
- async function verifyRuntime(root, expectedDigest, harnessId) {
1569
- const key = verificationCacheKey(root, expectedDigest, harnessId);
1570
- const cached = verifiedRuntimeCache.get(key);
1571
- if (cached !== void 0) {
1572
- return { ok: true, digest: cached.digest, snapshot: cached, cached: true };
1573
- }
1574
- const running = inFlightVerifications.get(key);
1575
- if (running !== void 0) return running;
1576
- const started = digestOnce(
1577
- root,
1578
- expectedDigest,
1579
- harnessId,
1580
- key,
1581
- cacheGeneration
1582
- );
1583
- inFlightVerifications.set(key, started);
1584
- try {
1585
- return await started;
1586
- } finally {
1587
- if (inFlightVerifications.get(key) === started) {
1588
- inFlightVerifications.delete(key);
1589
- }
1590
- }
1591
- }
1592
- async function digestOnce(root, expectedDigest, harnessId, key, generation) {
1593
- let snapshot;
1594
- try {
1595
- snapshot = await digestTreeWithSnapshot(root, harnessId);
1596
- } catch (error) {
1597
- return {
1598
- ok: false,
1599
- reason: "unreadable",
1600
- message: error instanceof Error ? error.message : String(error)
1601
- };
1602
- }
1603
- if (snapshot.digest !== expectedDigest) {
1604
- return { ok: false, reason: "digest-mismatch", digest: snapshot.digest };
1605
- }
1606
- if (generation !== cacheGeneration) {
1607
- return {
1608
- ok: false,
1609
- reason: "unreadable",
1610
- message: "the runtime tree was replaced while it was being verified; verify again"
1611
- };
1612
- }
1613
- verifiedRuntimeCache.set(key, snapshot);
1614
- return { ok: true, digest: snapshot.digest, snapshot, cached: false };
1615
- }
1616
- function runtimeIdOf(parts) {
1617
- return `rt_${createHash2("sha256").update(parts.join("\0")).digest("hex").slice(0, 32)}`;
1618
- }
1619
- async function resolveManagedBundle(args) {
1620
- const { manifest, runtimeRoot, platform } = args;
1621
- if (manifest.runtime.source !== "managed-bundle") {
1622
- return {
1623
- ok: false,
1624
- status: "bundle-absent",
1625
- message: `${manifest.harnessId} is not configured for a managed bundle`
1626
- };
1627
- }
1628
- const policy = manifest.runtime;
1629
- const root = join4(runtimeRoot, policy.bundleName);
1630
- let canonicalRoot;
1631
- try {
1632
- canonicalRoot = await realpath(root);
1633
- const info = await stat3(canonicalRoot);
1634
- if (!info.isDirectory()) throw new Error("not a directory");
1635
- } catch {
1636
- return {
1637
- ok: false,
1638
- status: "bundle-absent",
1639
- 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.`
1640
- };
1641
- }
1642
- const arch = args.arch ?? process.arch;
1643
- const target = localPackTarget(platform, arch);
1644
- const expectedDigest = target === null ? void 0 : policy.bundleDigest[target];
1645
- if (expectedDigest === void 0) {
1646
- return {
1647
- ok: false,
1648
- status: "bundle-absent",
1649
- // The TARGET, not just the OS: on a machine whose architecture nobody
1650
- // builds for, "no pack for darwin" reads as a platform outage when the
1651
- // real answer is "no pack for darwin-x64". A user comparing that against
1652
- // the release assets needs the string that appears there.
1653
- message: `no ${manifest.harnessId} runtime pack has been built for ${platform}-${arch}, so there is no digest to verify one against`
1654
- };
1655
- }
1656
- const verification = await verifyRuntime(
1657
- canonicalRoot,
1658
- expectedDigest,
1659
- manifest.harnessId
1660
- );
1661
- if (!verification.ok && verification.reason === "unreadable") {
1662
- return {
1663
- ok: false,
1664
- status: "bundle-corrupt",
1665
- message: `the ${manifest.harnessId} runtime bundle could not be digested: ${verification.message}`
1666
- };
1667
- }
1668
- if (!verification.ok) {
1669
- return {
1670
- ok: false,
1671
- status: "bundle-digest-mismatch",
1672
- 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.`
1673
- };
1674
- }
1675
- const digest = verification.digest;
1676
- const insideBundle = async (relativePath, label, requireExecutable) => {
1677
- const full = join4(canonicalRoot, relativePath);
1678
- if (!normalize(full).startsWith(canonicalRoot + sep)) {
1679
- return {
1680
- ok: false,
1681
- message: `the ${manifest.harnessId} manifest points its ${label} outside the bundle whose digest was verified`
1682
- };
1683
- }
1684
- try {
1685
- const info = await stat3(full);
1686
- if (!info.isFile()) throw new Error("not a file");
1687
- if (requireExecutable && platform !== "win32" && (info.mode & 73) === 0) {
1688
- throw new Error("not executable");
1689
- }
1690
- } catch {
1691
- return {
1692
- ok: false,
1693
- message: `the ${manifest.harnessId} runtime bundle has no usable ${label} at ${relativePath}`
1694
- };
1695
- }
1696
- return { ok: true, path: full };
1697
- };
1698
- const launcher = await insideBundle(
1699
- policy.launcherRelativePath,
1700
- "launcher",
1701
- false
1702
- );
1703
- if (!launcher.ok) {
1704
- return { ok: false, status: "bundle-corrupt", message: launcher.message };
1705
- }
1706
- const launcherPath = launcher.path;
1707
- const bundledNode = await insideBundle(
1708
- platform === "win32" ? `${policy.nodeLauncherRelativePath}.exe` : policy.nodeLauncherRelativePath,
1709
- "Node binary",
1710
- true
1711
- );
1712
- if (!bundledNode.ok) {
1713
- return { ok: false, status: "bundle-corrupt", message: bundledNode.message };
1714
- }
1715
- let jobLauncherPath;
1716
- if (platform === "win32" && policy.jobLauncherRelativePath) {
1717
- const helper = await insideBundle(
1718
- policy.jobLauncherRelativePath,
1719
- "job launcher",
1720
- true
1721
- );
1722
- if (helper.ok) jobLauncherPath = helper.path;
1723
- }
1724
- setWindowsJobLauncherVerified(jobLauncherPath !== void 0);
1725
- return {
1726
- ok: true,
1727
- runtime: {
1728
- runtimeId: runtimeIdOf([
1729
- "managed-bundle",
1730
- manifest.harnessId,
1731
- manifest.adapterVersion,
1732
- platform,
1733
- digest
1734
- ]),
1735
- source: "managed-bundle",
1736
- harnessId: manifest.harnessId,
1737
- platform,
1738
- adapterVersion: manifest.adapterVersion,
1739
- rootPath: canonicalRoot,
1740
- launcherPath,
1741
- nodePath: bundledNode.path,
1742
- ...jobLauncherPath !== void 0 ? { jobLauncherPath } : {},
1743
- digest,
1744
- vendorPackages: policy.vendorPackages
1745
- }
1746
- };
1747
- }
1748
- function systemInstallSearchPaths(platform) {
1749
- switch (platform) {
1750
- case "darwin":
1751
- return ["/usr/local/bin", "/opt/homebrew/bin", "/usr/bin"];
1752
- case "linux":
1753
- return ["/usr/local/bin", "/usr/bin", "/bin"];
1754
- case "win32":
1755
- return ["C:\\Program Files", "C:\\Program Files (x86)"];
1756
- }
1757
- }
1758
- function isUntrustedInstallPath(canonical, forbiddenRoots) {
1759
- for (const root of forbiddenRoots) {
1760
- if (canonical === root || canonical.startsWith(root + sep)) {
1761
- return root;
1762
- }
1763
- }
1764
- if (/(^|[\\/])node_modules([\\/]|$)/.test(canonical)) {
1765
- return "a node_modules directory";
1766
- }
1767
- return null;
1768
- }
1769
- function extractVersion(line) {
1770
- return /(\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?)/.exec(line)?.[1] ?? null;
1771
- }
1772
- function isSupportedVersionRange(range) {
1773
- return /^>=\s*\d+\.\d+\.\d+$/.test(range.trim());
1774
- }
1775
- function satisfiesMinimumRange(version, range) {
1776
- const match = /^>=\s*(\d+)\.(\d+)\.(\d+)$/.exec(range.trim());
1777
- if (!match) return false;
1778
- if (version.includes("-")) return false;
1779
- const parts = version.split(".").map((n) => Number.parseInt(n, 10));
1780
- if (parts.length !== 3 || parts.some((n) => !Number.isFinite(n)))
1781
- return false;
1782
- const min = [Number(match[1]), Number(match[2]), Number(match[3])];
1783
- for (let i = 0; i < 3; i += 1) {
1784
- if (parts[i] > min[i]) return true;
1785
- if (parts[i] < min[i]) return false;
1786
- }
1787
- return true;
1788
- }
1789
- async function defaultProbe(executable, args) {
1790
- return await new Promise((resolvePromise) => {
1791
- execFile2(
1792
- executable,
1793
- [...args],
1794
- {
1795
- timeout: PROBE_TIMEOUT_MS,
1796
- maxBuffer: PROBE_MAX_BUFFER,
1797
- encoding: "utf8",
1798
- windowsHide: true,
1799
- env: { PATH: "", LANG: "C" }
1800
- },
1801
- (error, stdout) => {
1802
- resolvePromise({
1803
- stdout: typeof stdout === "string" ? stdout : "",
1804
- exitCode: error ? 1 : 0
1805
- });
1806
- }
1807
- );
1808
- });
1809
- }
1810
- async function firstUntrustedAncestor(path, platform) {
1811
- if (platform === "win32") return null;
1812
- let dir = dirname(path);
1813
- for (; ; ) {
1814
- let info;
1815
- try {
1816
- info = await stat3(dir);
1817
- } catch {
1818
- return dir;
1819
- }
1820
- const looselyWritable = (info.mode & 18) !== 0 && (info.mode & 512) === 0;
1821
- if (info.uid !== 0 || looselyWritable) return dir;
1822
- const parent = dirname(dir);
1823
- if (parent === dir) return null;
1824
- dir = parent;
1825
- }
1826
- }
1827
- async function resolveSystemInstall(opts) {
1828
- const { manifest, platform } = opts;
1829
- if (manifest.runtime.source !== "system-install") {
1830
- return {
1831
- ok: false,
1832
- status: "system-runtime-not-installed",
1833
- message: `${manifest.harnessId} is not configured for a system install`
1834
- };
1835
- }
1836
- if (platform === "darwin") {
1837
- return {
1838
- ok: false,
1839
- status: "system-runtime-untrusted-path",
1840
- 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.`
1841
- };
1842
- }
1843
- const policy = manifest.runtime;
1844
- const searchPaths = opts.searchPaths ?? systemInstallSearchPaths(platform);
1845
- const probe = opts.probe ?? defaultProbe;
1846
- const accepted = [];
1847
- const rejections = [];
1848
- for (const dir of searchPaths) {
1849
- for (const name of policy.executableNames) {
1850
- const candidate = join4(dir, name);
1851
- let canonical;
1852
- try {
1853
- canonical = await realpath(candidate);
1854
- } catch {
1855
- continue;
1856
- }
1857
- if (!isAbsolute(canonical)) continue;
1858
- const untrusted = isUntrustedInstallPath(canonical, opts.forbiddenRoots);
1859
- if (untrusted) {
1860
- rejections.push({
1861
- status: "system-runtime-untrusted-path",
1862
- message: `${candidate} resolves into ${untrusted}, which the session or the workspace can write`
1863
- });
1864
- continue;
1865
- }
1866
- let info;
1867
- try {
1868
- info = await stat3(canonical);
1869
- } catch {
1870
- continue;
1871
- }
1872
- if (!info.isFile() || (info.mode & 73) === 0) {
1873
- rejections.push({
1874
- status: "system-runtime-not-installed",
1875
- message: `${candidate} is not an executable file`
1876
- });
1877
- continue;
1878
- }
1879
- if ((info.mode & 18) !== 0) {
1880
- rejections.push({
1881
- status: "system-runtime-untrusted-path",
1882
- message: `${candidate} is group- or world-writable, so its identity cannot be held between verification and launch`
1883
- });
1884
- continue;
1885
- }
1886
- if (platform !== "win32" && info.uid !== 0) {
1887
- rejections.push({
1888
- status: "system-runtime-untrusted-path",
1889
- 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`
1890
- });
1891
- continue;
1892
- }
1893
- const untrustedAncestor = await firstUntrustedAncestor(
1894
- canonical,
1895
- platform
1896
- );
1897
- if (untrustedAncestor !== null) {
1898
- rejections.push({
1899
- status: "system-runtime-untrusted-path",
1900
- 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`
1901
- });
1902
- continue;
1903
- }
1904
- if (policy.vendorIdentityPolicy.requirePlatformProvenance) {
1905
- rejections.push({
1906
- status: "system-runtime-identity-mismatch",
1907
- 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`
1908
- });
1909
- continue;
1910
- }
1911
- const result = await probe(
1912
- canonical,
1913
- policy.vendorIdentityPolicy.probeArgs
1914
- );
1915
- const line = result.stdout.trim().split("\n")[0] ?? "";
1916
- if (result.exitCode !== 0 || !new RegExp(policy.vendorIdentityPolicy.stdoutPattern).test(line)) {
1917
- rejections.push({
1918
- status: "system-runtime-identity-mismatch",
1919
- message: `${candidate} did not identify itself as ${manifest.harnessId} (probe output ${JSON.stringify(line.slice(0, 120))})`
1920
- });
1921
- continue;
1922
- }
1923
- if (!isSupportedVersionRange(policy.executableVersionRange)) {
1924
- rejections.push({
1925
- status: "system-runtime-identity-mismatch",
1926
- 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")`
1927
- });
1928
- continue;
1929
- }
1930
- const version = extractVersion(line);
1931
- if (version === null || !satisfiesMinimumRange(version, policy.executableVersionRange)) {
1932
- rejections.push({
1933
- status: "system-runtime-identity-mismatch",
1934
- message: `${candidate} reports version ${version ?? "(unparseable)"}, which is outside the manifest range ${policy.executableVersionRange}`
1935
- });
1936
- continue;
1937
- }
1938
- const content = await readFile4(canonical);
1939
- const digest = `sha256:${createHash2("sha256").update(content).digest("hex")}`;
1940
- accepted.push({
1941
- runtimeId: runtimeIdOf([
1942
- "system-install",
1943
- manifest.harnessId,
1944
- manifest.adapterVersion,
1945
- platform,
1946
- canonical,
1947
- digest,
1948
- String(info.ino)
1949
- ]),
1950
- source: "system-install",
1951
- harnessId: manifest.harnessId,
1952
- platform,
1953
- adapterVersion: manifest.adapterVersion,
1954
- rootPath: canonical,
1955
- launcherPath: canonical,
1956
- digest,
1957
- vendorPackages: {},
1958
- vendorVersionLine: line
1959
- });
1960
- }
1961
- }
1962
- if (accepted.length === 0) {
1963
- return {
1964
- ok: false,
1965
- // Report the FIRST real rejection's own status, not a blanket one.
1966
- status: rejections[0]?.status ?? "system-runtime-not-installed",
1967
- 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.`
1968
- };
1969
- }
1970
- if (accepted.length > 1) {
1971
- const distinct = new Set(accepted.map((r) => r.rootPath));
1972
- if (distinct.size > 1) {
1973
- return {
1974
- ok: false,
1975
- status: "system-runtime-ambiguous",
1976
- message: `more than one ${manifest.harnessId} installation is acceptable (${[...distinct].join(
1977
- ", "
1978
- )}). Remove or disambiguate them: consent must name exactly one runtime.`
1979
- };
1980
- }
1981
- }
1982
- return { ok: true, runtime: accepted[0] };
1983
- }
1984
- async function detectSnapshotDrift(snapshot) {
1985
- const policy = rehashPolicyFor(snapshot.harnessId);
1986
- const recorded = new Map(snapshot.entries.map((e) => [e.path, e]));
1987
- let seen = 0;
1988
- const walk = async (dir) => {
1989
- const entries = await readdir3(dir, { withFileTypes: true });
1990
- for (const entry of entries) {
1991
- const full = join4(dir, entry.name);
1992
- const rel = relative(snapshot.root, full).split(sep).join("/");
1993
- if (entry.isSymbolicLink()) return `a symlink appeared at ${rel}`;
1994
- if (entry.isDirectory()) {
1995
- const nested = await walk(full);
1996
- if (nested !== null) return nested;
1997
- continue;
1998
- }
1999
- if (!entry.isFile()) return `a non-regular file appeared at ${rel}`;
2000
- const expected = recorded.get(rel);
2001
- if (expected === void 0) return `an unexpected file appeared at ${rel}`;
2002
- seen += 1;
2003
- const info = await stat3(full);
2004
- if (info.size !== expected.size || info.mtimeMs !== expected.mtimeMs || info.ctimeMs !== expected.ctimeMs || Number(info.ino) !== expected.ino || info.mode !== expected.mode) {
2005
- return `${rel} was modified`;
2006
- }
2007
- if (isRehashedOnRevalidate(policy, rel)) {
2008
- const content = await readFile4(full);
2009
- const fileDigest = createHash2("sha256").update(content).digest("hex");
2010
- if (fileDigest !== snapshot.executableDigests[rel]) {
2011
- return `${rel} was rewritten in place`;
2012
- }
2013
- }
2014
- }
2015
- return null;
2016
- };
2017
- const reason = await walk(snapshot.root);
2018
- if (reason !== null) return reason;
2019
- if (seen !== snapshot.entries.length) {
2020
- return `${snapshot.entries.length - seen} file(s) went missing`;
2021
- }
2022
- return null;
2023
- }
2024
- async function revalidateRuntime(runtime) {
2025
- try {
2026
- if (runtime.source === "managed-bundle") {
2027
- const snapshot = verifiedRuntimeCache.get(
2028
- verificationCacheKey(runtime.rootPath, runtime.digest, runtime.harnessId)
2029
- );
2030
- if (snapshot === void 0) {
2031
- const verification = await verifyRuntime(
2032
- runtime.rootPath,
2033
- runtime.digest,
2034
- runtime.harnessId
2035
- );
2036
- if (!verification.ok) {
2037
- return {
2038
- ok: false,
2039
- 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}`
2040
- };
2041
- }
2042
- return { ok: true };
2043
- }
2044
- const drift = await detectSnapshotDrift(snapshot);
2045
- if (drift === null) return { ok: true };
2046
- verifiedRuntimeCache.delete(
2047
- verificationCacheKey(runtime.rootPath, runtime.digest, runtime.harnessId)
2048
- );
2049
- const reverified = await verifyRuntime(
2050
- runtime.rootPath,
2051
- runtime.digest,
2052
- runtime.harnessId
2053
- );
2054
- if (reverified.ok) return { ok: true };
2055
- return {
2056
- ok: false,
2057
- 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}`
2058
- };
2059
- }
2060
- const content = await readFile4(runtime.launcherPath);
2061
- const digest = `sha256:${createHash2("sha256").update(content).digest("hex")}`;
2062
- if (digest !== runtime.digest) {
2063
- return {
2064
- ok: false,
2065
- message: `the ${runtime.harnessId} executable at ${runtime.launcherPath} was replaced after consent was granted`
2066
- };
2067
- }
2068
- return { ok: true };
2069
- } catch (error) {
2070
- return {
2071
- ok: false,
2072
- message: `the ${runtime.harnessId} runtime could not be re-verified: ${error instanceof Error ? error.message : String(error)}`
2073
- };
2074
- }
2075
- }
2076
-
2077
- // server/utils/harness/codex-appserver/shared/sandbox-policy.ts
2078
- var LOCAL_UNATTENDED_SANDBOX_POLICY = Object.freeze({
2079
- type: "workspaceWrite",
2080
- writableRoots: [],
2081
- networkAccess: false,
2082
- excludeSlashTmp: true,
2083
- excludeTmpdirEnvVar: false
2084
- });
2085
- function sandboxPolicyFingerprint(policy) {
2086
- if (policy === void 0) return "none";
2087
- return JSON.stringify({
2088
- type: policy.type,
2089
- writableRoots: [...policy.writableRoots].sort(),
2090
- networkAccess: policy.networkAccess,
2091
- excludeSlashTmp: policy.excludeSlashTmp,
2092
- excludeTmpdirEnvVar: policy.excludeTmpdirEnvVar
2093
- });
2094
- }
2095
-
2096
- // server/utils/harness/local/compatibility.ts
2097
- var LOCAL_HARNESS_MANIFEST = {
2098
- "claude-code": {
2099
- harnessId: "claude-code",
2100
- adapterVersion: "1.0.100",
2101
- runtime: {
2102
- source: "managed-bundle",
2103
- bundleName: "claude-code",
2104
- // Generated by the release pack build, and EMPTY until one has run.
2105
- // Either way the result is `bundle-absent` before any tree is read, but
2106
- // WHICH message depends on what is on disk: with no bundle directory —
2107
- // today's state — `resolveManagedBundle` reports the missing bundle
2108
- // first; with a directory present, the empty map has no entry for this
2109
- // machine's `<os>-<arch>` and it names the target instead ("no pack has
2110
- // been built for linux-x64"). Both fail closed; only the second names a
2111
- // pack a user could go looking for.
2112
- bundleDigest: PACK_TREE_DIGESTS["claude-code"],
2113
- launcherRelativePath: "launcher.mjs",
2114
- nodeLauncherRelativePath: "bin/node",
2115
- jobLauncherRelativePath: "bin/mcpjam-job-launcher.exe",
2116
- vendorPackages: {
2117
- "@anthropic-ai/claude-code": "pinned-by-adapter-bridge-lockfile"
2118
- }
2119
- },
2120
- argvPolicy: { requiredFlags: [], deniedFlags: [] },
2121
- configStrategy: "synthetic-home",
2122
- supportsBuiltinToolApprovals: true,
2123
- permissionProfileMapping: {
2124
- "read-only": "allow-reads",
2125
- "workspace-edits": "allow-edits",
2126
- unrestricted: "allow-all"
2127
- },
2128
- // Native eligibility is per platform. macOS and Linux have POSIX process
2129
- // groups, which is what whole-tree cleanup is built on there.
2130
- //
2131
- // Windows has no process group; its whole-tree guarantee is a Job Object
2132
- // with KILL_ON_JOB_CLOSE, created by `tools/mcpjam-job-launcher`, which
2133
- // ships INSIDE the Windows pack so its bytes are covered by the tree
2134
- // digest. Listing `win32` here is necessary but not sufficient:
2135
- // `supportsOwnershipProof('win32')` still answers false until runtime
2136
- // resolution has verified that launcher, so a pack without one keeps the
2137
- // platform refused exactly as before.
2138
- //
2139
- // Earned, not asserted: the conformance suite's `windows-latest` leg runs
2140
- // the full scenario and the abort scenario against the real pack and the
2141
- // real vendor CLI, and its survivor scan is what turns "we wrote a Job
2142
- // Object" into evidence that stopping a session stops everything it
2143
- // started. That leg is gating; the day it goes red, this entry is wrong.
2144
- nativePlatforms: ["darwin", "linux", "win32"],
2145
- // Empty until a backend's escape probes actually pass (I6).
2146
- isolatedBackends: {},
2147
- lifecycleConformanceVersion: "published-1.0.0-c2bc887b85b1",
2148
- adapterBootstrapDir: ".harness-bootstrap/claude-code",
2149
- adapterBootstrapFiles: [
2150
- "package.json",
2151
- "pnpm-lock.yaml",
2152
- "pnpm-workspace.yaml",
2153
- "bridge.mjs",
2154
- ".npmrc"
2155
- ],
2156
- bridgeBundleDigest: `sha256:${"0".repeat(64)}`
2157
- },
2158
- codex: {
2159
- harnessId: "codex",
2160
- // MCPJam's app-server adapter, not an npm package: the bridge bundle hash
2161
- // plus the exact CLI (see `codex-appserver/local-identity.ts`). The pack
2162
- // byte-compare is what actually enforces it.
2163
- adapterVersion: CODEX_LOCAL_ADAPTER_IDENTITY,
2164
- runtime: {
2165
- source: "managed-bundle",
2166
- bundleName: "codex",
2167
- bundleDigest: PACK_TREE_DIGESTS.codex,
2168
- launcherRelativePath: "launcher.mjs",
2169
- nodeLauncherRelativePath: "bin/node",
2170
- jobLauncherRelativePath: "bin/mcpjam-job-launcher.exe",
2171
- vendorPackages: {
2172
- "@openai/codex": PINNED_CODEX_VERSION,
2173
- ws: "8.21.0"
2174
- }
2175
- },
2176
- argvPolicy: { requiredFlags: [], deniedFlags: [] },
2177
- configStrategy: "explicit-config-root",
2178
- // The app-server adapter raises real approval requests.
2179
- supportsBuiltinToolApprovals: true,
2180
- // Attended profiles map to Codex `untrusted` (every command and file
2181
- // change asks). `unrestricted` — unattended evals and swarms only, never
2182
- // the Playground (`localPermissionModeFor` / `resolveLocalCompatibility`)
2183
- // — is `allow-all` ONLY together with `unattendedSandboxPolicy` below, and
2184
- // only on a target in `unattendedSandboxTargets`. The bridge refuses
2185
- // `allow-all` without that policy when supervised locally, so it can
2186
- // never become `danger-full-access` on a user's machine.
2187
- permissionProfileMapping: {
2188
- "read-only": "allow-reads",
2189
- "workspace-edits": "allow-edits",
2190
- unrestricted: "allow-all"
2191
- },
2192
- // Evidence: the 2026-09-30 macOS arm64 product-assembly probe and the
2193
- // linux-x64 app-server probes (`codex-appserver/README.md`). Every other
2194
- // target stays refused until its own evidence lands (D8).
2195
- nativePlatforms: ["darwin", "linux"],
2196
- nativeTargets: ["darwin-arm64", "linux-x64"],
2197
- // No target has passed the unattended sandbox probe on the pinned binary
2198
- // yet, so unattended local Codex is refused everywhere.
2199
- unattendedSandboxTargets: [],
2200
- unattendedSandboxPolicy: LOCAL_UNATTENDED_SANDBOX_POLICY,
2201
- isolatedBackends: {},
2202
- // Dark until the Codex lifecycle conformance legs pass and are recorded.
2203
- lifecycleConformanceVersion: "published-codex-1.0.0-c2bc887b85b1",
2204
- adapterBootstrapDir: ".harness-bootstrap/codex-appserver",
2205
- adapterBootstrapFiles: [
2206
- "package.json",
2207
- "pnpm-lock.yaml",
2208
- "bridge.mjs",
2209
- "host-tools-mcp.mjs"
2210
- ],
2211
- bridgeBundleDigest: CODEX_BRIDGE_BUNDLE_DIGEST
2212
- }
2213
- };
2214
- function localPermissionModeFor(harnessId, permissionProfile, targetKind, scope = "attended") {
2215
- const manifests = LOCAL_HARNESS_MANIFEST;
2216
- const manifest = Object.prototype.hasOwnProperty.call(manifests, harnessId) ? manifests[harnessId] : void 0;
2217
- if (manifest === void 0) return null;
2218
- if (permissionProfile === "unrestricted" && targetKind === "local-native" && scope !== "unattended") {
2219
- return null;
2220
- }
2221
- return manifest.permissionProfileMapping[permissionProfile] ?? null;
2222
- }
2223
- function localSandboxPolicyFor(harnessId, permissionProfile, targetKind, scope = "attended") {
2224
- const manifests = LOCAL_HARNESS_MANIFEST;
2225
- const manifest = Object.prototype.hasOwnProperty.call(manifests, harnessId) ? manifests[harnessId] : void 0;
2226
- if (manifest?.unattendedSandboxPolicy === void 0 || permissionProfile !== "unrestricted" || targetKind !== "local-native" || scope !== "unattended") {
2227
- return null;
2228
- }
2229
- return manifest.unattendedSandboxPolicy;
2230
- }
2231
- function resolveLocalCompatibility(query, manifests = LOCAL_HARNESS_MANIFEST) {
2232
- const manifest = Object.prototype.hasOwnProperty.call(
2233
- manifests,
2234
- query.harnessId
2235
- ) ? manifests[query.harnessId] : void 0;
2236
- if (!manifest) {
2237
- return {
2238
- ok: false,
2239
- status: "harness-not-supported",
2240
- message: `${query.harnessId} has no reviewed local compatibility manifest. Run it hosted, or add a manifest entry with conformance evidence.`
2241
- };
2242
- }
2243
- if (query.installedAdapterVersion !== manifest.adapterVersion) {
2244
- return {
2245
- ok: false,
2246
- status: "adapter-version-mismatch",
2247
- 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.`
2248
- };
2249
- }
2250
- if (manifest.lifecycleConformanceVersion === "") {
2251
- return {
2252
- ok: false,
2253
- status: "conformance-missing",
2254
- 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.`
2255
- };
2256
- }
2257
- if (query.platform === null) {
2258
- return {
2259
- ok: false,
2260
- status: "platform-not-supported",
2261
- // NOT "run the harness hosted instead". A requested-local turn has Send
2262
- // disabled in this state (`localHarnessBlocksSend`), so nothing falls
2263
- // back — and on a local Inspector with no cloud data plane there is no
2264
- // hosted target to switch to either, which makes the instruction
2265
- // unactionable exactly where it is most likely to be read.
2266
- message: `local execution is not supported on this platform.`
2267
- };
2268
- }
2269
- if (query.targetKind === "local-native") {
2270
- if (!manifest.nativePlatforms.includes(query.platform)) {
2271
- 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(", ")}).`;
2272
- return {
2273
- ok: false,
2274
- status: "native-not-eligible",
2275
- message: reason
2276
- };
2277
- }
2278
- if (manifest.nativeTargets !== void 0 && query.packTarget !== void 0 && (query.packTarget === null || !manifest.nativeTargets.includes(query.packTarget))) {
2279
- return {
2280
- ok: false,
2281
- status: "native-not-eligible",
2282
- message: `${query.harnessId} has not been certified on ${query.packTarget ?? "this architecture"} yet (certified: ${manifest.nativeTargets.join(", ") || "none"}).`
2283
- };
2284
- }
2285
- } else {
2286
- if (query.backend === void 0) {
2287
- return {
2288
- ok: false,
2289
- status: "backend-not-verified",
2290
- message: "an isolated target must name its isolation backend."
2291
- };
2292
- }
2293
- const verifiedHere = manifest.isolatedBackends[query.platform] ?? [];
2294
- if (!verifiedHere.includes(query.backend)) {
2295
- return {
2296
- ok: false,
2297
- status: "backend-not-verified",
2298
- 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.`
2299
- };
2300
- }
2301
- }
2302
- const permissionMode = manifest.permissionProfileMapping[query.permissionProfile];
2303
- if (permissionMode === void 0) {
2304
- const offered = Object.keys(manifest.permissionProfileMapping);
2305
- return {
2306
- ok: false,
2307
- status: "permission-profile-not-supported",
2308
- 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.`)
2309
- };
2310
- }
2311
- if (query.scope !== "unattended" && query.permissionProfile === "unrestricted" && query.targetKind === "local-native") {
2312
- return {
2313
- ok: false,
2314
- status: "permission-profile-not-supported",
2315
- 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.`
2316
- };
2317
- }
2318
- if (query.permissionProfile === "unrestricted" && query.targetKind === "local-native" && manifest.unattendedSandboxTargets !== void 0 && (query.packTarget == null || !manifest.unattendedSandboxTargets.includes(query.packTarget))) {
2319
- return {
2320
- ok: false,
2321
- status: "backend-not-verified",
2322
- message: `unattended local ${query.harnessId} runs inside its own command sandbox, and that sandbox has not been verified on ${query.packTarget ?? "this architecture"} yet (verified: ${manifest.unattendedSandboxTargets.join(", ") || "none"}). Run this eval or swarm in the cloud.`
2323
- };
2324
- }
2325
- return { ok: true, manifest, permissionMode };
2326
- }
2327
-
2328
- // server/utils/harness/local/runtime-install.ts
2329
- var MAX_ARCHIVE_BYTES = 1500 * 1024 * 1024;
2330
- var MAX_EXTRACTED_BYTES = 2 * 1024 * 1024 * 1024;
2331
- var MAX_MANIFEST_BYTES = 1024 * 1024;
2332
- function runtimeInstallRoot() {
2333
- const override = process.env.MCPJAM_RUNTIME_ROOT;
2334
- if (override && override.trim().length > 0) return override.trim();
2335
- return join5(homedir(), ".mcpjam", "harness-local", "runtime");
2336
- }
2337
- function packVersionRoot(harnessId, packVersion, target = localPackTarget()) {
2338
- return join5(targetInstallRoot(harnessId, target), packVersion);
2339
- }
2340
- function targetInstallRoot(harnessId, target) {
2341
- return harnessTargetInstallRoot(
2342
- runtimeInstallRoot(),
2343
- harnessId,
2344
- target ?? packPlatformKey()
2345
- );
2346
- }
2347
- function expectedPackFor(harnessId, target) {
2348
- const override = developmentPackExpectation();
2349
- if (override !== null) return override;
2350
- const record = PACK_RECORDS[harnessId]?.[target];
2351
- if (record === void 0) return null;
2352
- return { packVersion: record.packVersion, treeDigest: record.treeDigest };
2353
- }
2354
- function developmentPackExpectation() {
2355
- const source = process.env.MCPJAM_LOCAL_HARNESS_PACK_SOURCE;
2356
- const expected = process.env.MCPJAM_LOCAL_HARNESS_EXPECTED_PACK;
2357
- if (!source || !expected) return null;
2358
- const separator = expected.indexOf(":");
2359
- if (separator <= 0) return null;
2360
- const packVersion = expected.slice(0, separator).trim();
2361
- const treeDigest = expected.slice(separator + 1).trim();
2362
- if (packVersion.length === 0) return null;
2363
- if (!/^sha256:[0-9a-f]{64}$/.test(treeDigest)) return null;
2364
- return { packVersion, treeDigest };
2365
- }
2366
- function packSourceFor(harnessId, packVersion, platformKey) {
2367
- const override = process.env.MCPJAM_LOCAL_HARNESS_PACK_SOURCE;
2368
- if (override && override.trim().length > 0) {
2369
- const value = override.trim();
2370
- return /^https?:\/\//.test(value) ? { kind: "url", location: value } : { kind: "file", location: value.replace(/^file:\/\//, "") };
2371
- }
2372
- return {
2373
- kind: "url",
2374
- location: packReleaseBaseUrl(harnessId, packVersion) + `${packAssetStem(harnessId, platformKey, packVersion)}.tar.gz`
2375
- };
2376
- }
2377
- function packPlatformKey(platform = process.platform, arch = process.arch) {
2378
- return `${platform}-${arch}`;
2379
- }
2380
- async function readRuntimeInstallStatus(args) {
2381
- const resolved = resolveInstallTarget(args);
2382
- if (!resolved.ok) return resolved.status;
2383
- const { key, expected, versionRoot } = resolved;
2384
- await recoverInterruptedActivation({ key, versionRoot });
2385
- const inProcess = active.get(operationKeyString(key));
2386
- if (inProcess !== void 0) return inProcess.status;
2387
- const record = await readRuntimeOperation(key);
2388
- if (record !== null && !isRecordTerminal(record)) {
2389
- return operationRecordStatus(record);
2390
- }
2391
- const onDisk = await readMarkerStatus({
2392
- harnessId: args.harnessId,
2393
- versionRoot,
2394
- expected
2395
- });
2396
- if (onDisk.state === "ready") return onDisk;
2397
- if (record !== null && isRecordTerminal(record) && record.state !== "ready") {
2398
- return operationRecordStatus(record);
2399
- }
2400
- return onDisk;
2401
- }
2402
- function manifestWithExpectedBundleDigest(manifest, harnessId, target) {
2403
- if (target === null) return manifest;
2404
- if (manifest.runtime.source !== "managed-bundle") return manifest;
2405
- const expected = expectedPackFor(harnessId, target);
2406
- if (expected === null) return manifest;
2407
- if (manifest.runtime.bundleDigest[target] === expected.treeDigest) {
2408
- return manifest;
2409
- }
2410
- return {
2411
- ...manifest,
2412
- runtime: {
2413
- ...manifest.runtime,
2414
- bundleDigest: {
2415
- ...manifest.runtime.bundleDigest,
2416
- [target]: expected.treeDigest
2417
- }
2418
- }
2419
- };
2420
- }
2421
- async function readVerifiedRuntimeStatus(args) {
2422
- const status = await readRuntimeInstallStatus(args);
2423
- if (status.state !== "ready") return status;
2424
- const platform = currentLocalPlatform(args.platform ?? process.platform);
2425
- if (platform === null) return status;
2426
- const resolvedBundle = await resolveManagedBundle({
2427
- manifest: manifestWithExpectedBundleDigest(
2428
- LOCAL_HARNESS_MANIFEST[args.harnessId],
2429
- args.harnessId,
2430
- localPackTarget(args.platform, args.arch)
2431
- ),
2432
- runtimeRoot: status.runtimeRoot,
2433
- platform,
2434
- ...args.arch ? { arch: args.arch } : {}
2435
- });
2436
- if (resolvedBundle.ok) return status;
2437
- return {
2438
- state: "corrupt",
2439
- packVersion: status.packVersion,
2440
- message: resolvedBundle.message
2441
- };
2442
- }
2443
- async function readMarkerStatus(args) {
2444
- try {
2445
- const marker = JSON.parse(
2446
- await readFile5(join5(args.versionRoot, INSTALL_MARKER), "utf8")
2447
- );
2448
- if (marker.treeDigest !== args.expected.treeDigest) {
2449
- return {
2450
- state: "corrupt",
2451
- packVersion: args.expected.packVersion,
2452
- message: "the installed runtime pack does not match the digest this Inspector expects; reinstall it"
2453
- };
2454
- }
2455
- await stat4(join5(args.versionRoot, args.harnessId));
2456
- return {
2457
- state: "ready",
2458
- packVersion: args.expected.packVersion,
2459
- runtimeRoot: args.versionRoot,
2460
- digest: args.expected.treeDigest
2461
- };
2462
- } catch {
2463
- return { state: "absent", packVersion: args.expected.packVersion };
2464
- }
2465
- }
2466
- function isRecordTerminal(record) {
2467
- return record.state === "ready" || record.state === "failed" || record.state === "interrupted";
2468
- }
2469
- function operationRecordStatus(record) {
2470
- switch (record.state) {
2471
- case "reserved":
2472
- case "downloading":
2473
- return {
2474
- state: "downloading",
2475
- packVersion: record.packVersion,
2476
- percent: record.percent ?? 0,
2477
- attemptId: record.attemptId
2478
- };
2479
- case "verifying":
2480
- case "activating":
2481
- return {
2482
- state: "verifying",
2483
- packVersion: record.packVersion,
2484
- attemptId: record.attemptId
2485
- };
2486
- case "failed":
2487
- return {
2488
- state: "failed",
2489
- packVersion: record.packVersion,
2490
- reason: record.reason ?? "unknown",
2491
- message: record.message ?? "the install did not complete",
2492
- attemptId: record.attemptId
2493
- };
2494
- case "interrupted":
2495
- return {
2496
- state: "interrupted",
2497
- packVersion: record.packVersion,
2498
- message: record.message ?? "setup was interrupted before it finished",
2499
- attemptId: record.attemptId
2500
- };
2501
- case "ready":
2502
- return {
2503
- state: "ready",
2504
- packVersion: record.packVersion,
2505
- runtimeRoot: packVersionRoot(
2506
- record.harnessId,
2507
- record.packVersion,
2508
- record.target
2509
- ),
2510
- digest: record.treeDigest
2511
- };
2512
- }
2513
- }
2514
- function resolveInstallTarget(args) {
2515
- const platform = currentLocalPlatform(args.platform ?? process.platform);
2516
- if (platform === null) {
2517
- return {
2518
- ok: false,
2519
- status: {
2520
- state: "unsupported-platform",
2521
- message: `${args.platform ?? process.platform} has no local harness runtime`
2522
- }
2523
- };
2524
- }
2525
- const target = localPackTarget(args.platform, args.arch);
2526
- const expected = target === null ? null : expectedPackFor(args.harnessId, target);
2527
- if (expected === null || target === null) {
2528
- return {
2529
- ok: false,
2530
- status: {
2531
- state: "unsupported-platform",
2532
- message: `no ${args.harnessId} runtime pack has been built for ${packPlatformKey(args.platform, args.arch)}`
2533
- }
2534
- };
2535
- }
2536
- return {
2537
- ok: true,
2538
- platform,
2539
- target,
2540
- expected,
2541
- versionRoot: packVersionRoot(args.harnessId, expected.packVersion, target),
2542
- key: {
2543
- runtimeRoot: runtimeInstallRoot(),
2544
- harnessId: args.harnessId,
2545
- target,
2546
- packVersion: expected.packVersion,
2547
- treeDigest: expected.treeDigest
2548
- }
2549
- };
2550
- }
2551
- var INSTALL_MARKER = ".mcpjam-pack-installed.json";
2552
- var active = /* @__PURE__ */ new Map();
2553
- async function startRuntimeInstall(options) {
2554
- const resolved = resolveInstallTarget(options);
2555
- if (!resolved.ok) {
2556
- return {
2557
- kind: "refused",
2558
- status: resolved.status,
2559
- reason: resolved.status.state === "unsupported-platform" ? resolved.status.message : "this machine has no runtime pack to install"
2560
- };
2561
- }
2562
- const { key, expected, versionRoot } = resolved;
2563
- if (options.expectedPack !== void 0 && (options.expectedPack.packVersion !== expected.packVersion || options.expectedPack.treeDigest !== expected.treeDigest)) {
2564
- return {
2565
- kind: "refused",
2566
- reason: "this Inspector now expects a different runtime than the one that was approved, so it will not download it under that approval",
2567
- status: {
2568
- state: "failed",
2569
- packVersion: expected.packVersion,
2570
- reason: "verification",
2571
- 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.`
2572
- }
2573
- };
2574
- }
2575
- const keyString = operationKeyString(key);
2576
- const running = active.get(keyString);
2577
- if (running !== void 0) {
2578
- return { kind: "joined", status: running.status };
2579
- }
2580
- await recoverInterruptedActivation({ key, versionRoot });
2581
- const verified = await readVerifiedRuntimeStatus(options);
2582
- if (verified.state === "ready") return { kind: "ready", status: verified };
2583
- const attempt = await beginInstallAttempt(key);
2584
- if (attempt.kind === "joined") {
2585
- return {
2586
- kind: "joined",
2587
- status: operationRecordStatus(attempt.record),
2588
- attemptId: attempt.record.attemptId
2589
- };
2590
- }
2591
- const record = {
2592
- status: {
2593
- state: "downloading",
2594
- packVersion: expected.packVersion,
2595
- percent: 0,
2596
- attemptId: attempt.record.attemptId
2597
- },
2598
- promise: Promise.resolve({
2599
- state: "absent",
2600
- packVersion: expected.packVersion
2601
- })
2602
- };
2603
- active.set(keyString, record);
2604
- record.promise = runInstallAttempt({
2605
- options,
2606
- resolved,
2607
- attemptId: attempt.record.attemptId,
2608
- record,
2609
- keyString
2610
- });
2611
- void record.promise;
2612
- return {
2613
- kind: "started",
2614
- status: record.status,
2615
- attemptId: attempt.record.attemptId
2616
- };
2617
- }
2618
- async function installRuntimePack(options) {
2619
- const started = await startRuntimeInstall(options);
2620
- if (started.kind === "ready" || started.kind === "refused") {
2621
- return started.status;
2622
- }
2623
- const resolved = resolveInstallTarget(options);
2624
- if (!resolved.ok) return resolved.status;
2625
- const running = active.get(operationKeyString(resolved.key));
2626
- if (running !== void 0) return running.promise;
2627
- return awaitForeignAttempt(resolved.key, options);
2628
- }
2629
- async function awaitForeignAttempt(key, options) {
2630
- for (; ; ) {
2631
- if (options.signal?.aborted === true) {
2632
- return readRuntimeInstallStatus(options);
2633
- }
2634
- const record = await readRuntimeOperation(key);
2635
- if (record === null) return readRuntimeInstallStatus(options);
2636
- if (isRecordTerminal(record)) {
2637
- return record.state === "ready" ? readRuntimeInstallStatus(options) : operationRecordStatus(record);
2638
- }
2639
- options.onProgress?.(operationRecordStatus(record));
2640
- await new Promise((resolvePromise) => setTimeout(resolvePromise, 500));
2641
- }
2642
- }
2643
- async function runInstallAttempt(args) {
2644
- const { options, resolved, attemptId, record, keyString } = args;
2645
- const { key, expected } = resolved;
2646
- const setStatus = (status) => {
2647
- record.status = status;
2648
- options.onProgress?.(status);
2649
- void updateInstallAttempt(key, attemptId, {
2650
- state: status.state === "downloading" ? "downloading" : status.state === "verifying" ? "verifying" : "reserved",
2651
- ...status.state === "downloading" ? { percent: status.percent } : {}
2652
- }).catch(() => {
2653
- });
2654
- };
2655
- try {
2656
- const result = await performInstall({
2657
- ...options,
2658
- platform: resolved.platform,
2659
- expected,
2660
- key,
2661
- attemptId,
2662
- setStatus
2663
- });
2664
- record.status = result;
2665
- await updateInstallAttempt(key, attemptId, {
2666
- state: result.state === "ready" ? "ready" : "failed",
2667
- ...result.state === "failed" ? { reason: result.reason, message: result.message } : {}
2668
- }).catch(() => {
2669
- });
2670
- return result;
2671
- } catch (error) {
2672
- const failure = classifyInstallFailure(error, expected.packVersion);
2673
- logger.warn("[local-harness] runtime pack install failed", {
2674
- reason: failure.reason,
2675
- message: failure.message
2676
- });
2677
- record.status = failure;
2678
- await updateInstallAttempt(key, attemptId, {
2679
- state: "failed",
2680
- reason: failure.reason,
2681
- message: failure.message
2682
- }).catch(() => {
2683
- });
2684
- return failure;
2685
- } finally {
2686
- active.delete(keyString);
2687
- }
2688
- }
2689
- function classifyInstallFailure(error, packVersion) {
2690
- const message = error instanceof Error ? error.message : String(error);
2691
- const code = error?.code;
2692
- const causeCode = error?.cause?.code;
2693
- 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(
2694
- message
2695
- ) ? "network" : /does not match|signature|signed manifest|no signed manifest|digest|exceeds its size ceiling|has no .* directory at its root/i.test(
2696
- message
2697
- ) ? "verification" : "unknown";
2698
- return { state: "failed", packVersion, reason, message };
2699
- }
2700
- async function performInstall(args) {
2701
- const { expected, setStatus, key, attemptId } = args;
2702
- const platformKey = packPlatformKey(args.platform, args.arch);
2703
- const target = localPackTarget(args.platform, args.arch);
2704
- const versionRoot = packVersionRoot(args.harnessId, expected.packVersion, target);
2705
- const installRoot = targetInstallRoot(args.harnessId, target);
2706
- await mkdir3(installRoot, { recursive: true, mode: 448 });
2707
- await sweepAbandonedStaging(key);
2708
- const staging = join5(installRoot, `${STAGING_PREFIX}${randomUUID3()}`);
2709
- await mkdir3(staging, { recursive: true, mode: 448 });
2710
- await claimStagingDirectory({ staging, attemptId });
2711
- try {
2712
- const source = packSourceFor(args.harnessId, expected.packVersion, platformKey);
2713
- const archivePath = join5(staging, "pack.tar.gz");
2714
- setStatus({
2715
- state: "downloading",
2716
- packVersion: expected.packVersion,
2717
- percent: 0,
2718
- attemptId
2719
- });
2720
- const archiveSha = await fetchArchive({
2721
- source,
2722
- destination: archivePath,
2723
- onPercent: (percent) => setStatus({
2724
- state: "downloading",
2725
- packVersion: expected.packVersion,
2726
- percent,
2727
- attemptId
2728
- }),
2729
- ...args.signal ? { signal: args.signal } : {}
2730
- });
2731
- setStatus({
2732
- state: "verifying",
2733
- packVersion: expected.packVersion,
2734
- attemptId
2735
- });
2736
- const manifest = await loadAndVerifyManifest({
2737
- harnessId: args.harnessId,
2738
- source,
2739
- packVersion: expected.packVersion,
2740
- platformKey,
2741
- staging
2742
- });
2743
- if (manifest !== null && manifest.archive?.sha256 !== void 0) {
2744
- if (manifest.archive.sha256 !== archiveSha) {
2745
- throw new Error(
2746
- `the downloaded runtime pack archive does not match its signed manifest (expected ${manifest.archive.sha256}, got ${archiveSha})`
2747
- );
2748
- }
2749
- }
2750
- const extractRoot = join5(staging, "extracted");
2751
- await mkdir3(extractRoot, { recursive: true, mode: 448 });
2752
- await extractTar({
2753
- file: archivePath,
2754
- cwd: extractRoot,
2755
- // No links of any kind survive extraction, and nothing may be written
2756
- // outside `cwd`. The digest would refuse a symlink later; refusing it
2757
- // here means it never touches the disk.
2758
- filter: (path, entry) => {
2759
- const type = entry.type;
2760
- if (type !== "File" && type !== "Directory") return false;
2761
- return !path.split("/").includes("..");
2762
- },
2763
- preservePaths: false,
2764
- strict: true
2765
- });
2766
- const packRoot = join5(extractRoot, args.harnessId);
2767
- const info = await stat4(packRoot).catch(() => null);
2768
- if (info === null || !info.isDirectory()) {
2769
- throw new Error(
2770
- `the runtime pack archive has no ${args.harnessId} directory at its root`
2771
- );
2772
- }
2773
- await assertExtractedSize(packRoot);
2774
- const digest = await computeTreeDigest(packRoot);
2775
- if (manifest !== null && digest !== manifest.treeDigest) {
2776
- throw new Error(
2777
- `the extracted runtime pack does not match its signed manifest (expected ${manifest.treeDigest}, got ${digest})`
2778
- );
2779
- }
2780
- if (digest !== expected.treeDigest) {
2781
- throw new Error(
2782
- `the runtime pack does not match the digest this Inspector was built with (expected ${expected.treeDigest}, got ${digest})`
2783
- );
2784
- }
2785
- if (args.platform === "darwin") await clearQuarantine(extractRoot);
2786
- await writeFile3(
2787
- join5(extractRoot, INSTALL_MARKER),
2788
- `${JSON.stringify(
2789
- {
2790
- packVersion: expected.packVersion,
2791
- harnessId: args.harnessId,
2792
- platform: platformKey,
2793
- treeDigest: digest,
2794
- installedAt: (/* @__PURE__ */ new Date()).toISOString()
2795
- },
2796
- null,
2797
- 2
2798
- )}
2799
- `,
2800
- { mode: 384 }
2801
- );
2802
- setStatus({
2803
- state: "verifying",
2804
- packVersion: expected.packVersion,
2805
- attemptId
2806
- });
2807
- await updateInstallAttempt(key, attemptId, { state: "activating" });
2808
- await activateVerifiedPack({
2809
- key,
2810
- attemptId,
2811
- versionRoot,
2812
- extractRoot
2813
- });
2814
- logger.info("[local-harness] runtime pack installed", {
2815
- packVersion: expected.packVersion,
2816
- platform: platformKey
2817
- });
2818
- return {
2819
- state: "ready",
2820
- packVersion: expected.packVersion,
2821
- runtimeRoot: versionRoot,
2822
- digest
2823
- };
2824
- } finally {
2825
- await rm3(staging, { recursive: true, force: true }).catch(() => {
2826
- });
2827
- }
2828
- }
2829
- async function activateVerifiedPack(args) {
2830
- const { key, versionRoot, extractRoot } = args;
2831
- if (!await attemptStillOwns(key, args.attemptId)) {
2832
- throw new Error(
2833
- "another install took over this runtime while this one was downloading, so it was not activated"
2834
- );
2835
- }
2836
- const inUse = await runtimeUseState({ key, runtimeRoot: versionRoot });
2837
- if (inUse.busy) {
2838
- throw new Error(
2839
- `this runtime is in use by ${inUse.holders.length} running session(s) on this machine, so it was not replaced. Stop them and retry.`
2840
- );
2841
- }
2842
- await withRuntimeLifecycleLock(key, async () => {
2843
- const stillFree = await runtimeUseState({ key, runtimeRoot: versionRoot });
2844
- if (stillFree.busy) {
2845
- throw new Error(
2846
- "a session started using this runtime while it was being replaced, so it was left alone. Stop it and retry."
2847
- );
2848
- }
2849
- const previous = `${versionRoot}${PREVIOUS_SUFFIX}`;
2850
- await rm3(previous, { recursive: true, force: true }).catch(() => {
2851
- });
2852
- const hasCurrent = await stat4(versionRoot).then(
2853
- () => true,
2854
- () => false
2855
- );
2856
- if (hasCurrent) await rename2(versionRoot, previous);
2857
- try {
2858
- await rename2(extractRoot, versionRoot);
2859
- } catch (error) {
2860
- if (hasCurrent) await rename2(previous, versionRoot).catch(() => {
2861
- });
2862
- throw error;
2863
- }
2864
- await rm3(previous, { recursive: true, force: true }).catch(() => {
2865
- });
2866
- });
2867
- clearRuntimeVerificationCache();
2868
- }
2869
- async function assertExtractedSize(root) {
2870
- let bytes = 0;
2871
- const walk = async (dir) => {
2872
- for (const entry of await readdir4(dir, { withFileTypes: true })) {
2873
- const full = join5(dir, entry.name);
2874
- if (entry.isDirectory()) {
2875
- await walk(full);
2876
- continue;
2877
- }
2878
- bytes += (await stat4(full)).size;
2879
- if (bytes > MAX_EXTRACTED_BYTES) {
2880
- throw new Error("the extracted runtime pack exceeds its size ceiling");
2881
- }
2882
- }
2883
- };
2884
- await walk(root);
2885
- }
2886
- async function clearQuarantine(root) {
2887
- const { execFile: execFile3 } = await import("child_process");
2888
- await new Promise((resolvePromise) => {
2889
- execFile3(
2890
- "/usr/bin/xattr",
2891
- ["-r", "-d", "com.apple.quarantine", root],
2892
- { timeout: 6e4 },
2893
- () => resolvePromise()
2894
- );
2895
- });
2896
- }
2897
- async function loadAndVerifyManifest(args) {
2898
- const stem = packAssetStem(args.harnessId, args.platformKey, args.packVersion);
2899
- const manifestName = `${stem}.manifest.json`;
2900
- const signatureName = `${manifestName}.sig`;
2901
- let manifestBytes;
2902
- let signature;
2903
- try {
2904
- if (args.source.kind === "file") {
2905
- const dir = args.source.location.endsWith(".tar.gz") ? args.source.location.slice(0, -basename(args.source.location).length) : args.source.location;
2906
- manifestBytes = await readFile5(join5(dir, manifestName));
2907
- signature = await readFile5(join5(dir, signatureName), "utf8");
2908
- } else {
2909
- const base = args.source.location.slice(
2910
- 0,
2911
- args.source.location.lastIndexOf("/") + 1
2912
- );
2913
- manifestBytes = Buffer.from(
2914
- await (await fetchOrThrow(base + manifestName)).arrayBuffer()
2915
- );
2916
- signature = await (await fetchOrThrow(base + signatureName)).text();
2917
- }
2918
- } catch (error) {
2919
- if (args.source.kind === "file") {
2920
- logger.warn(
2921
- "[local-harness] local pack source has no signed manifest; installing on the digest alone",
2922
- { message: error instanceof Error ? error.message : String(error) }
2923
- );
2924
- return null;
2925
- }
2926
- throw new Error(
2927
- `the runtime pack has no signed manifest alongside it, so it cannot be shown to have come from MCPJam`
2928
- );
2929
- }
2930
- if (manifestBytes.length > MAX_MANIFEST_BYTES) {
2931
- throw new Error("the runtime pack manifest is implausibly large");
2932
- }
2933
- const verified = verifyPackManifestSignature(manifestBytes, signature);
2934
- if (!verified.ok) {
2935
- if (args.source.kind === "file") {
2936
- logger.warn(
2937
- "[local-harness] local pack manifest signature not verified; installing on the digest alone",
2938
- { reason: verified.reason }
2939
- );
2940
- return null;
2941
- }
2942
- throw new Error(verified.message);
2943
- }
2944
- const manifest = JSON.parse(manifestBytes.toString("utf8"));
2945
- if (manifest.packVersion !== args.packVersion) {
2946
- throw new Error(
2947
- `the signed manifest is for pack version ${manifest.packVersion}, not ${args.packVersion}`
2948
- );
2949
- }
2950
- if (manifest.platform !== args.platformKey) {
2951
- throw new Error(
2952
- `the signed manifest is for ${manifest.platform}, not ${args.platformKey}`
2953
- );
2954
- }
2955
- if (manifest.harnessId !== args.harnessId) {
2956
- throw new Error(
2957
- `the signed manifest is for the ${manifest.harnessId} runtime, not ${args.harnessId}`
2958
- );
2959
- }
2960
- return manifest;
2961
- }
2962
- async function fetchOrThrow(url) {
2963
- const response = await fetch(url);
2964
- if (!response.ok) {
2965
- throw new Error(`${url} responded ${response.status}`);
2966
- }
2967
- return response;
2968
- }
2969
- async function fetchArchive(args) {
2970
- const hash = createHash3("sha256");
2971
- let received = 0;
2972
- let total = 0;
2973
- const track = new TransformStream({
2974
- transform(chunk, controller) {
2975
- hash.update(chunk);
2976
- received += chunk.byteLength;
2977
- if (received > MAX_ARCHIVE_BYTES) {
2978
- throw new Error("the runtime pack archive exceeds its size ceiling");
2979
- }
2980
- if (total > 0) {
2981
- args.onPercent(Math.min(99, Math.floor(received / total * 100)));
2982
- }
2983
- controller.enqueue(chunk);
2984
- }
2985
- });
2986
- if (args.source.kind === "file") {
2987
- const path = args.source.location;
2988
- const info = await stat4(path);
2989
- total = info.size;
2990
- if (total > MAX_ARCHIVE_BYTES) {
2991
- throw new Error("the runtime pack archive exceeds its size ceiling");
2992
- }
2993
- await pipeline(
2994
- createReadStream(path),
2995
- async function* (chunks) {
2996
- for await (const chunk of chunks) {
2997
- const buffer = chunk;
2998
- hash.update(buffer);
2999
- received += buffer.byteLength;
3000
- args.onPercent(Math.min(99, Math.floor(received / total * 100)));
3001
- yield buffer;
3002
- }
3003
- },
3004
- createWriteStream(args.destination, { mode: 384 })
3005
- );
3006
- return hash.digest("hex");
3007
- }
3008
- const response = await fetch(args.source.location, {
3009
- ...args.signal ? { signal: args.signal } : {}
3010
- });
3011
- if (!response.ok || response.body === null) {
3012
- throw new Error(
3013
- `the runtime pack could not be downloaded: ${args.source.location} responded ${response.status}`
3014
- );
3015
- }
3016
- const declared = Number(response.headers.get("content-length") ?? "0");
3017
- if (declared > MAX_ARCHIVE_BYTES) {
3018
- throw new Error("the runtime pack archive exceeds its size ceiling");
3019
- }
3020
- total = declared;
3021
- await pipeline(
3022
- Readable.fromWeb(
3023
- response.body.pipeThrough(track)
3024
- ),
3025
- createWriteStream(args.destination, { mode: 384 })
3026
- );
3027
- args.onPercent(100);
3028
- return hash.digest("hex");
3029
- }
3030
- function reportLocalHarnessRuntimeStatusInBackground() {
3031
- void (async () => {
3032
- for (const harnessId of SUPPORTED_LOCAL_HARNESS_IDS) {
3033
- try {
3034
- const status = await readRuntimeInstallStatus({ harnessId });
3035
- if (status.state === "ready") {
3036
- logger.info("[local-harness] runtime pack present", {
3037
- harnessId,
3038
- packVersion: status.packVersion
3039
- });
3040
- continue;
3041
- }
3042
- logger.debug("[local-harness] no runtime pack installed", {
3043
- harnessId,
3044
- state: status.state,
3045
- expected: EXPECTED_PACK_VERSIONS[harnessId] || "(none built)"
3046
- });
3047
- } catch {
3048
- }
3049
- }
3050
- })();
3051
- }
3052
-
3053
- export {
3054
- resolveEnvironment,
3055
- resolveAppVersion,
3056
- resolveRelease,
3057
- redactSecretShapes,
3058
- markOriginCaptureHandled,
3059
- ensureStampable,
3060
- isOriginCaptureHandled,
3061
- captureOriginErrorToSentry,
3062
- logger,
3063
- SUPPORTED_LOCAL_HARNESS_IDS,
3064
- localPackTarget,
3065
- LOCAL_HARNESS_POLICY_VERSION,
3066
- LOCAL_ISOLATION_POLICY_VERSION,
3067
- currentLocalPlatform,
3068
- probeProcess,
3069
- readProcessBirthIdentity,
3070
- supportsOwnershipProof,
3071
- listGroupMembers,
3072
- terminateOwnedProcess,
3073
- probeProcessGroup,
3074
- readProcessGroupId,
3075
- terminateOwnedProcessGroup,
3076
- resolveManagedBundle,
3077
- resolveSystemInstall,
3078
- revalidateRuntime,
3079
- CODEX_APPSERVER_BRIDGE_SOURCE,
3080
- CODEX_APPSERVER_HOST_TOOLS_MCP_SOURCE,
3081
- CODEX_APPSERVER_BOOTSTRAP_PACKAGE_JSON,
3082
- CODEX_APPSERVER_BOOTSTRAP_PNPM_LOCK,
3083
- CODEX_LOCAL_ADAPTER_IDENTITY,
3084
- sandboxPolicyFingerprint,
3085
- LOCAL_HARNESS_MANIFEST,
3086
- localPermissionModeFor,
3087
- localSandboxPolicyFor,
3088
- resolveLocalCompatibility,
3089
- createLocalStateMutationLock,
3090
- reserveRuntimeUse,
3091
- runtimeInstallRoot,
3092
- expectedPackFor,
3093
- readRuntimeInstallStatus,
3094
- manifestWithExpectedBundleDigest,
3095
- readVerifiedRuntimeStatus,
3096
- startRuntimeInstall,
3097
- installRuntimePack,
3098
- reportLocalHarnessRuntimeStatusInBackground
3099
- };
3100
- //# sourceMappingURL=chunk-I7ZVTBZP.js.map