@mcpjam/inspector 3.12.9 → 3.13.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 (43) hide show
  1. package/bin/start.js +32 -6
  2. package/dist/client/assets/OAuthDesktopReturnNotice-BZEaGzn6.css +2 -0
  3. package/dist/client/assets/{OAuthDesktopReturnNotice-DlTJhJwy.js → OAuthDesktopReturnNotice-D5tJNqny.js} +2 -2
  4. package/dist/client/assets/{app-bootstrap-BtbHLWDU.js → app-bootstrap-baadQQNk.js} +351 -368
  5. package/dist/client/assets/{button-12hqsTUk.js → button-DHPqnOj6.js} +2 -2
  6. package/dist/client/assets/chunk-D32TOXHM-BPB6AqSK.js +160 -0
  7. package/dist/client/assets/dead-clicks-autocapture-Cbczl2El.js +3 -0
  8. package/dist/client/assets/{error-reporting-D3byeSLw.js → error-reporting-B4hGM_ob.js} +1 -1
  9. package/dist/client/assets/error-reporting-CORfsjyM.js +120 -0
  10. package/dist/client/assets/{exception-autocapture-CzpTtsxv.js → exception-autocapture-CMOUrnel.js} +4 -4
  11. package/dist/client/assets/{failed-request-tracker-CmHxaDPF.js → failed-request-tracker-DoQRXuIy.js} +2 -2
  12. package/dist/client/assets/highlighted-body-KQOG7T2V-_ljE4u1k.js +3 -0
  13. package/dist/client/assets/{index-C0SfPmai.js → index-BBr8TZVx.js} +3 -3
  14. package/dist/client/assets/{jszip.min-BmAHHtmZ.js → jszip.min-C-vIQbxH.js} +2 -2
  15. package/dist/client/assets/mermaid-MCJ5UELQ-DTJaEEBm.js +1 -0
  16. package/dist/client/assets/posthog-recorder-Dby9Z8HR.js +110 -0
  17. package/dist/client/assets/{preload-helper-B22rzauv.js → preload-helper-Dvt1a6xa.js} +2 -2
  18. package/dist/client/assets/{react-BzkNdoI5.js → react-CD7Pk4KS.js} +2 -2
  19. package/dist/client/assets/{rolldown-runtime-BNuWddGb.js → rolldown-runtime-mzU9SaVm.js} +1 -1
  20. package/dist/client/assets/surveys-DYqpu8xl.js +3 -0
  21. package/dist/client/assets/trace-timeline-PnE1ouRj.js +71 -0
  22. package/dist/client/assets/{trace-timeline-Bg58ukyI.js → trace-timeline-WXINST5z.js} +1 -1
  23. package/dist/client/assets/{web-vitals-D4bU8W1t.js → web-vitals-BLq6M5vx.js} +2 -2
  24. package/dist/client/index.html +8 -8
  25. package/dist/server/{chunk-DGAFFBDM.js → chunk-2FVSBJQF.js} +1470 -890
  26. package/dist/server/chunk-I7ZVTBZP.js +3100 -0
  27. package/dist/server/{chunk-SH24KJBI.js → chunk-MBS3EZ3U.js} +13 -2
  28. package/dist/server/{chunk-4PYR7GMQ.js → chunk-QHYREDE3.js} +4 -4
  29. package/dist/server/{consent-lifetime-M7PS6RUU.js → consent-lifetime-TYLDY64H.js} +3 -3
  30. package/dist/server/harness-install-cli.js +23 -6
  31. package/dist/server/index.js +21146 -18727
  32. package/dist/server/{local-turn-ZWMMQGV3.js → local-turn-VQDSTY6T.js} +4 -4
  33. package/package.json +38 -38
  34. package/dist/client/assets/OAuthDesktopReturnNotice-FnFv52Ym.css +0 -2
  35. package/dist/client/assets/chunk-YOKDWASO--Bd-6XAf.js +0 -145
  36. package/dist/client/assets/dead-clicks-autocapture-RCao2exY.js +0 -3
  37. package/dist/client/assets/error-reporting-StyhxjHz.js +0 -102
  38. package/dist/client/assets/highlighted-body-KPVGNVTW-BweERQbm.js +0 -3
  39. package/dist/client/assets/mermaid-HWGCJPDP-C6s_jIuz.js +0 -1
  40. package/dist/client/assets/posthog-recorder-wc41pimR.js +0 -110
  41. package/dist/client/assets/surveys-D-NcCeqw.js +0 -3
  42. package/dist/client/assets/trace-timeline-CxoCCEiW.js +0 -137
  43. package/dist/server/chunk-WZVZ6LQX.js +0 -2876
@@ -1,7 +1,9 @@
1
1
  import {
2
+ CODEX_LOCAL_ADAPTER_IDENTITY,
2
3
  LOCAL_HARNESS_MANIFEST,
3
4
  LOCAL_HARNESS_POLICY_VERSION,
4
5
  LOCAL_ISOLATION_POLICY_VERSION,
6
+ SUPPORTED_LOCAL_HARNESS_IDS,
5
7
  createLocalStateMutationLock,
6
8
  currentLocalPlatform,
7
9
  listGroupMembers,
@@ -22,7 +24,7 @@ import {
22
24
  supportsOwnershipProof,
23
25
  terminateOwnedProcess,
24
26
  terminateOwnedProcessGroup
25
- } from "./chunk-WZVZ6LQX.js";
27
+ } from "./chunk-I7ZVTBZP.js";
26
28
  import {
27
29
  HOSTED_MODE,
28
30
  LOCAL_HARNESS_ENABLED,
@@ -30,7 +32,631 @@ import {
30
32
  capabilityMatches,
31
33
  mintCapabilityToken,
32
34
  persistCapabilityState
33
- } from "./chunk-SH24KJBI.js";
35
+ } from "./chunk-MBS3EZ3U.js";
36
+
37
+ // server/utils/harness/local/grants.ts
38
+ import { randomUUID } from "crypto";
39
+ import { mkdir, readFile, rename, writeFile, chmod } from "fs/promises";
40
+ import { homedir } from "os";
41
+ import { join, sep } from "path";
42
+ import { realpath, stat } from "fs/promises";
43
+ var LOCAL_HARNESS_GRANT_HEADER = "x-mcpjam-local-harness-grant";
44
+ function localHarnessStateRoot() {
45
+ return join(homedir(), ".mcpjam", "harness-local");
46
+ }
47
+ function grantsFilePath() {
48
+ return join(localHarnessStateRoot(), "grants.json");
49
+ }
50
+ function machineFilePath() {
51
+ return join(localHarnessStateRoot(), "machine.json");
52
+ }
53
+ function emptyState() {
54
+ return { version: 1, workspaces: [], harnessGrants: [] };
55
+ }
56
+ var GRANT_TTL_MS = 12 * 60 * 60 * 1e3;
57
+ var withGrantLock = createLocalStateMutationLock({
58
+ rootDir: localHarnessStateRoot,
59
+ lockFileName: "grants.lock",
60
+ resourceLabel: "grant store"
61
+ });
62
+ function hashGrantBinding(binding) {
63
+ return capabilityFingerprint(
64
+ JSON.stringify([
65
+ binding.scope ?? "attended",
66
+ binding.userId,
67
+ binding.machineId,
68
+ binding.projectId,
69
+ binding.workspaceGrantId,
70
+ binding.harnessId,
71
+ binding.targetKind,
72
+ binding.backend ?? null,
73
+ binding.runtimeId,
74
+ binding.permissionProfile,
75
+ binding.policyVersion,
76
+ // Only isolated bindings carry one, and only they hash it. A native
77
+ // binding has no isolation policy to be bound to, so folding a constant
78
+ // `null` into its hash would change every native hash for a value that
79
+ // means nothing there — invalidating consents that the local policy
80
+ // never touched. A native binding that carries one anyway is refused
81
+ // outright by `verifyLocalHarnessGrant`, not admitted by the hash.
82
+ ...binding.targetKind === "local-isolated" ? [binding.isolationPolicyVersion ?? null] : []
83
+ ])
84
+ );
85
+ }
86
+ var GrantStateUnreadableError = class extends Error {
87
+ };
88
+ function isValidDate(value) {
89
+ return typeof value === "string" && Number.isFinite(Date.parse(value));
90
+ }
91
+ function isWorkspaceGrant(value) {
92
+ if (!value || typeof value !== "object") return false;
93
+ const workspace = value;
94
+ return typeof workspace.workspaceGrantId === "string" && workspace.workspaceGrantId.length > 0 && typeof workspace.canonicalPath === "string" && workspace.canonicalPath.length > 0 && isValidDate(workspace.createdAt);
95
+ }
96
+ function isHarnessGrantBinding(value) {
97
+ if (!value || typeof value !== "object") return false;
98
+ const binding = value;
99
+ const isolatedBackend = binding.backend === "linux-bwrap" || binding.backend === "darwin-seatbelt" || binding.backend === "oci-v1" || binding.backend === "vm-v1";
100
+ return typeof binding.userId === "string" && binding.userId.length > 0 && typeof binding.machineId === "string" && binding.machineId.length > 0 && (binding.scope === void 0 || binding.scope === "attended" || binding.scope === "unattended") && typeof binding.projectId === "string" && binding.projectId.length > 0 && typeof binding.workspaceGrantId === "string" && binding.workspaceGrantId.length > 0 && (binding.harnessId === "claude-code" || binding.harnessId === "codex") && (binding.targetKind === "local-native" || binding.targetKind === "local-isolated") && typeof binding.runtimeId === "string" && binding.runtimeId.length > 0 && (binding.permissionProfile === "read-only" || binding.permissionProfile === "workspace-edits" || binding.permissionProfile === "unrestricted") && typeof binding.policyVersion === "string" && binding.policyVersion.length > 0 && (binding.targetKind === "local-native" ? binding.backend === void 0 && binding.isolationPolicyVersion === void 0 : isolatedBackend && typeof binding.isolationPolicyVersion === "string" && binding.isolationPolicyVersion.length > 0);
101
+ }
102
+ function isPersistedHarnessGrant(value) {
103
+ if (!value || typeof value !== "object") return false;
104
+ const grant = value;
105
+ return typeof grant.grantId === "string" && grant.grantId.length > 0 && typeof grant.tokenHash === "string" && /^[0-9a-f]{64}$/.test(grant.tokenHash) && typeof grant.bindingHash === "string" && /^[0-9a-f]{64}$/.test(grant.bindingHash) && isHarnessGrantBinding(grant.binding) && isValidDate(grant.grantedAt) && isValidDate(grant.expiresAt);
106
+ }
107
+ async function readState() {
108
+ let raw;
109
+ try {
110
+ raw = await readFile(grantsFilePath(), "utf8");
111
+ } catch (error) {
112
+ if (error.code === "ENOENT") return emptyState();
113
+ throw new GrantStateUnreadableError(
114
+ `the local harness grant store could not be read: ${error instanceof Error ? error.message : String(error)}`
115
+ );
116
+ }
117
+ let parsed;
118
+ try {
119
+ parsed = JSON.parse(raw);
120
+ } catch {
121
+ throw new GrantStateUnreadableError(
122
+ "the local harness grant store is corrupt; refusing to treat it as empty or overwrite it"
123
+ );
124
+ }
125
+ if (!parsed || typeof parsed !== "object") {
126
+ throw new GrantStateUnreadableError(
127
+ "the local harness grant store is not an object"
128
+ );
129
+ }
130
+ const record = parsed;
131
+ if (record.version !== 1 || !Array.isArray(record.workspaces) || !Array.isArray(record.harnessGrants) || !record.workspaces.every(isWorkspaceGrant) || !record.harnessGrants.every(isPersistedHarnessGrant)) {
132
+ throw new GrantStateUnreadableError(
133
+ "the local harness grant store has an unrecognized or malformed shape"
134
+ );
135
+ }
136
+ return {
137
+ version: 1,
138
+ workspaces: [...record.workspaces],
139
+ harnessGrants: [...record.harnessGrants]
140
+ };
141
+ }
142
+ async function writeState(state) {
143
+ const dir = localHarnessStateRoot();
144
+ await mkdir(dir, { recursive: true, mode: 448 });
145
+ await chmod(dir, 448).catch(() => {
146
+ });
147
+ await persistCapabilityState(grantsFilePath(), state);
148
+ }
149
+ async function getLocalMachineId() {
150
+ const readExisting = async () => {
151
+ let raw;
152
+ try {
153
+ raw = await readFile(machineFilePath(), "utf8");
154
+ } catch (error) {
155
+ if (error.code === "ENOENT") return null;
156
+ throw new GrantStateUnreadableError(
157
+ `the local harness machine identity could not be read: ${error instanceof Error ? error.message : String(error)}`
158
+ );
159
+ }
160
+ let parsed;
161
+ try {
162
+ parsed = JSON.parse(raw);
163
+ } catch {
164
+ throw new GrantStateUnreadableError(
165
+ "the local harness machine identity is corrupt; refusing to replace it"
166
+ );
167
+ }
168
+ if (!parsed || typeof parsed !== "object") {
169
+ throw new GrantStateUnreadableError(
170
+ "the local harness machine identity has an unrecognized shape"
171
+ );
172
+ }
173
+ const machineId = parsed.machineId;
174
+ if (typeof machineId !== "string" || machineId.length < 8) {
175
+ throw new GrantStateUnreadableError(
176
+ "the local harness machine identity has an invalid id"
177
+ );
178
+ }
179
+ return machineId;
180
+ };
181
+ const existing = await readExisting();
182
+ if (existing !== null) return existing;
183
+ return withGrantLock(async () => {
184
+ const raced = await readExisting();
185
+ if (raced !== null) return raced;
186
+ const machineId = `mach_${randomUUID()}`;
187
+ const dir = localHarnessStateRoot();
188
+ await mkdir(dir, { recursive: true, mode: 448 });
189
+ const file2 = machineFilePath();
190
+ const tmp = `${file2}.tmp`;
191
+ await writeFile(tmp, JSON.stringify({ machineId }), { mode: 384 });
192
+ await rename(tmp, file2);
193
+ return machineId;
194
+ });
195
+ }
196
+ function isFilesystemRoot(canonicalPath) {
197
+ return canonicalPath === sep || canonicalPath === "/" || // A drive root: `C:`, `C:\`, `C:/`.
198
+ /^[A-Za-z]:[\\/]?$/.test(canonicalPath) || // A UNC share root: `\\server\share` and its trailing-separator form, and
199
+ // a bare `\\server`. Scoping a session to a whole network share is the
200
+ // same mistake as scoping it to a whole volume, and the earlier rule
201
+ // covered only the volume. Anything BELOW the share
202
+ // (`\\server\share\project`) stays acceptable.
203
+ //
204
+ // Matched on the BACKSLASH form only. Accepting `//` here as well read a
205
+ // POSIX path with a doubled leading slash — `//tmp/project`, which POSIX
206
+ // expressly permits an implementation to keep — as a share root, and
207
+ // refused an ordinary directory. Windows has no such ambiguity to trade
208
+ // against: `realpath` and `path.resolve` both answer `\\server\share`
209
+ // there, so the canonical path this predicate is given is always the
210
+ // backslash form.
211
+ /^\\{2}[^\\/]+([\\/][^\\/]+)?[\\/]?$/.test(canonicalPath);
212
+ }
213
+ async function validateWorkspaceCandidate(rawPath) {
214
+ let canonicalPath;
215
+ try {
216
+ canonicalPath = await realpath(rawPath);
217
+ const info = await stat(canonicalPath);
218
+ if (!info.isDirectory()) {
219
+ return { ok: false, message: "the selection is not a directory" };
220
+ }
221
+ } catch (error) {
222
+ return {
223
+ ok: false,
224
+ message: `the selected workspace could not be resolved: ${error instanceof Error ? error.message : String(error)}`
225
+ };
226
+ }
227
+ const home = await realpath(homedir()).catch(() => homedir());
228
+ const appRoot = join(home, ".mcpjam");
229
+ const workspaces = join(appRoot, "harness-workspaces");
230
+ if (canonicalPath === home || isFilesystemRoot(canonicalPath) || (canonicalPath === appRoot || canonicalPath.startsWith(appRoot + sep)) && !canonicalPath.startsWith(workspaces + sep)) {
231
+ return {
232
+ ok: false,
233
+ message: "pick a project directory rather than your home directory or the filesystem root \u2014 the workspace is what the session is scoped to."
234
+ };
235
+ }
236
+ return { ok: true, canonicalPath };
237
+ }
238
+ function registerWorkspaceGrant(rawPath) {
239
+ return withGrantLock(async () => {
240
+ const candidate = await validateWorkspaceCandidate(rawPath);
241
+ if (!candidate.ok) {
242
+ return { ok: false, message: candidate.message };
243
+ }
244
+ const canonicalPath = candidate.canonicalPath;
245
+ const state = await readState();
246
+ const existing = state.workspaces.find(
247
+ (w) => w.canonicalPath === canonicalPath
248
+ );
249
+ if (existing) return { ok: true, grant: existing };
250
+ const grant = {
251
+ workspaceGrantId: `ws_${randomUUID()}`,
252
+ canonicalPath,
253
+ createdAt: (/* @__PURE__ */ new Date()).toISOString()
254
+ };
255
+ state.workspaces.push(grant);
256
+ await writeState(state);
257
+ logger.info("[local-harness] workspace grant registered");
258
+ return { ok: true, grant };
259
+ });
260
+ }
261
+ async function resolveWorkspaceGrant(workspaceGrantId) {
262
+ let state;
263
+ try {
264
+ state = await readState();
265
+ } catch (error) {
266
+ return {
267
+ ok: false,
268
+ message: error instanceof Error ? error.message : "the local harness grant store could not be read"
269
+ };
270
+ }
271
+ const grant = state.workspaces.find(
272
+ (w) => w.workspaceGrantId === workspaceGrantId
273
+ );
274
+ if (!grant) {
275
+ return { ok: false, message: "unknown workspace grant" };
276
+ }
277
+ try {
278
+ const canonical = await realpath(grant.canonicalPath);
279
+ if (canonical !== grant.canonicalPath) {
280
+ return {
281
+ ok: false,
282
+ message: "the granted workspace now resolves somewhere else; re-select it before running locally"
283
+ };
284
+ }
285
+ const info = await stat(canonical);
286
+ if (!info.isDirectory()) {
287
+ return {
288
+ ok: false,
289
+ message: "the granted workspace is no longer a directory"
290
+ };
291
+ }
292
+ const candidate = await validateWorkspaceCandidate(canonical);
293
+ if (!candidate.ok) return candidate;
294
+ return { ok: true, canonicalPath: canonical };
295
+ } catch {
296
+ return {
297
+ ok: false,
298
+ message: "the granted workspace is no longer reachable"
299
+ };
300
+ }
301
+ }
302
+ function grantLocalHarnessConsent(binding, opts) {
303
+ return withGrantLock(async () => {
304
+ const now = opts?.now ?? Date.now();
305
+ const ttlMs = Math.min(opts?.ttlMs ?? GRANT_TTL_MS, GRANT_TTL_MS);
306
+ const token = mintCapabilityToken();
307
+ const grant = {
308
+ grantId: `grant_${randomUUID()}`,
309
+ tokenHash: capabilityFingerprint(token),
310
+ bindingHash: hashGrantBinding(binding),
311
+ binding,
312
+ grantedAt: new Date(now).toISOString(),
313
+ expiresAt: new Date(now + ttlMs).toISOString()
314
+ };
315
+ const state = await readState();
316
+ state.harnessGrants = state.harnessGrants.filter(
317
+ (g) => Date.parse(g.expiresAt) > now
318
+ );
319
+ state.harnessGrants.push(grant);
320
+ await writeState(state);
321
+ logger.info("[local-harness] consent granted", {
322
+ harnessId: binding.harnessId,
323
+ targetKind: binding.targetKind,
324
+ permissionProfile: binding.permissionProfile,
325
+ policyVersion: binding.policyVersion
326
+ });
327
+ return { grantId: grant.grantId, token, expiresAt: grant.expiresAt };
328
+ });
329
+ }
330
+ async function verifyLocalHarnessGrant(token, binding, opts) {
331
+ if (!token || token.length < 16 || token.length > 256) {
332
+ return {
333
+ ok: false,
334
+ reason: "invalid",
335
+ message: "no local harness grant was presented"
336
+ };
337
+ }
338
+ if (binding.policyVersion !== LOCAL_HARNESS_POLICY_VERSION) {
339
+ return {
340
+ ok: false,
341
+ reason: "binding-mismatch",
342
+ message: `this grant was minted under policy ${binding.policyVersion}; the current policy is ${LOCAL_HARNESS_POLICY_VERSION}. The terms changed, so consent is asked again.`
343
+ };
344
+ }
345
+ if (binding.targetKind === "local-isolated") {
346
+ if (binding.isolationPolicyVersion !== LOCAL_ISOLATION_POLICY_VERSION) {
347
+ return {
348
+ ok: false,
349
+ reason: "binding-mismatch",
350
+ message: `this grant was minted under isolation policy ${binding.isolationPolicyVersion ?? "(none)"}; the current isolation policy is ${LOCAL_ISOLATION_POLICY_VERSION}.`
351
+ };
352
+ }
353
+ } else if (binding.isolationPolicyVersion !== void 0) {
354
+ return {
355
+ ok: false,
356
+ reason: "binding-mismatch",
357
+ message: "a native grant must not carry an isolation policy version"
358
+ };
359
+ }
360
+ const bindingHash = hashGrantBinding(binding);
361
+ let state;
362
+ try {
363
+ state = await readState();
364
+ } catch (error) {
365
+ return {
366
+ ok: false,
367
+ reason: "invalid",
368
+ message: error instanceof Error ? error.message : "the local harness grant store could not be read"
369
+ };
370
+ }
371
+ const now = opts?.now ?? Date.now();
372
+ for (const grant of state.harnessGrants) {
373
+ if (!capabilityMatches(token, grant.tokenHash)) continue;
374
+ if (grant.bindingHash !== bindingHash) {
375
+ return {
376
+ ok: false,
377
+ reason: "binding-mismatch",
378
+ message: "the presented grant was issued for different terms (workspace, harness, runtime, target mode, permission profile, or policy version). Local execution never runs under terms the user did not see."
379
+ };
380
+ }
381
+ if (Date.parse(grant.expiresAt) <= now) {
382
+ return {
383
+ ok: false,
384
+ reason: "expired",
385
+ message: "the local harness grant expired; consent is attended and short-lived"
386
+ };
387
+ }
388
+ return { ok: true, grantId: grant.grantId };
389
+ }
390
+ return {
391
+ ok: false,
392
+ reason: "absent",
393
+ message: "no local harness grant matches the presented capability"
394
+ };
395
+ }
396
+ function revokeLocalHarnessGrants(selector) {
397
+ return withGrantLock(async () => {
398
+ const state = await readState();
399
+ const before = state.harnessGrants.length;
400
+ if (!selector) {
401
+ state.harnessGrants = [];
402
+ } else if (selector.userId) {
403
+ state.harnessGrants = state.harnessGrants.filter((g) => g.binding.userId !== selector.userId || selector.projectId !== void 0 && g.binding.projectId !== selector.projectId);
404
+ } else if (selector.grantId) {
405
+ state.harnessGrants = state.harnessGrants.filter(
406
+ (g) => g.grantId !== selector.grantId
407
+ );
408
+ } else if (selector.binding) {
409
+ const hash = hashGrantBinding(selector.binding);
410
+ state.harnessGrants = state.harnessGrants.filter(
411
+ (g) => g.bindingHash !== hash
412
+ );
413
+ }
414
+ const removed = before - state.harnessGrants.length;
415
+ if (removed > 0) {
416
+ await writeState(state);
417
+ logger.info("[local-harness] consent revoked", { removed });
418
+ }
419
+ return removed;
420
+ });
421
+ }
422
+ function pruneExpiredHarnessGrants(now = Date.now()) {
423
+ return withGrantLock(async () => {
424
+ const state = await readState();
425
+ const before = state.harnessGrants.length;
426
+ state.harnessGrants = state.harnessGrants.filter(
427
+ (g) => Date.parse(g.expiresAt) > now
428
+ );
429
+ const removed = before - state.harnessGrants.length;
430
+ if (removed > 0) await writeState(state);
431
+ return removed;
432
+ });
433
+ }
434
+ function forgetWorkspaceGrant(workspaceGrantId) {
435
+ return withGrantLock(async () => {
436
+ const state = await readState();
437
+ state.workspaces = state.workspaces.filter((w) => w.workspaceGrantId !== workspaceGrantId);
438
+ state.harnessGrants = state.harnessGrants.filter((g) => g.binding.workspaceGrantId !== workspaceGrantId);
439
+ await writeState(state);
440
+ });
441
+ }
442
+
443
+ // server/utils/harness/local/session-registry.ts
444
+ var sessions = /* @__PURE__ */ new Map();
445
+ var unstopped = /* @__PURE__ */ new Set();
446
+ function registerLocalHarnessSession(record) {
447
+ sessions.set(record.sessionId, record);
448
+ }
449
+ function getLocalHarnessSession(sessionId) {
450
+ return sessions.get(sessionId);
451
+ }
452
+ function forgetLocalHarnessSession(sessionId) {
453
+ sessions.delete(sessionId);
454
+ }
455
+ function forgetLocalHarnessSessionRecord(record) {
456
+ unstopped.delete(record);
457
+ if (sessions.get(record.sessionId) !== record) return false;
458
+ sessions.delete(record.sessionId);
459
+ return true;
460
+ }
461
+ function claimRecord(record) {
462
+ const claimed = sessions.get(record.sessionId) === record || unstopped.has(record);
463
+ if (!claimed) return false;
464
+ if (sessions.get(record.sessionId) === record) {
465
+ sessions.delete(record.sessionId);
466
+ }
467
+ unstopped.delete(record);
468
+ return true;
469
+ }
470
+ async function endLocalHarnessSession(sessionId) {
471
+ const record = sessions.get(sessionId);
472
+ if (record === void 0) return { stopped: true, errors: [] };
473
+ if (!claimRecord(record)) return { stopped: true, errors: [] };
474
+ return endRecord(record);
475
+ }
476
+ async function endRecord(record) {
477
+ const sessionId = record.sessionId;
478
+ const errors = [];
479
+ try {
480
+ record.onEnded?.();
481
+ } catch (error) {
482
+ errors.push(`end hook: ${messageOf(error)}`);
483
+ }
484
+ try {
485
+ record.gateway?.revoke();
486
+ } catch (error) {
487
+ errors.push(`gateway revoke: ${messageOf(error)}`);
488
+ }
489
+ try {
490
+ await record.gateway?.close();
491
+ } catch (error) {
492
+ errors.push(`gateway close: ${messageOf(error)}`);
493
+ }
494
+ try {
495
+ await record.revokeLease?.();
496
+ } catch (error) {
497
+ errors.push(`lease revoke: ${messageOf(error)}`);
498
+ }
499
+ let stopped = true;
500
+ try {
501
+ const outcome = await record.stop();
502
+ if (outcome?.stopped !== true) {
503
+ stopped = false;
504
+ errors.push(
505
+ `stop: ${outcome?.escaped ?? "some"} process(es) escaped the session`
506
+ );
507
+ }
508
+ } catch (error) {
509
+ stopped = false;
510
+ errors.push(`stop: ${messageOf(error)}`);
511
+ }
512
+ if (stopped) {
513
+ unstopped.delete(record);
514
+ try {
515
+ await record.releaseRuntime?.();
516
+ } catch (error) {
517
+ errors.push(`runtime release: ${messageOf(error)}`);
518
+ }
519
+ } else {
520
+ unstopped.add(record);
521
+ if (!sessions.has(sessionId)) sessions.set(sessionId, record);
522
+ }
523
+ if (errors.length > 0) {
524
+ logger.warn("[local-harness] session teardown had failures", {
525
+ sessionId,
526
+ errors
527
+ });
528
+ }
529
+ return { stopped, errors };
530
+ }
531
+ async function stopAllLocalHarnessSessions() {
532
+ const candidates = [.../* @__PURE__ */ new Set([...sessions.values(), ...unstopped])];
533
+ const mine = candidates.filter(claimRecord);
534
+ const results = await Promise.all(
535
+ mine.map(
536
+ (record) => endRecord(record).catch(() => ({
537
+ stopped: false,
538
+ errors: ["unexpected"]
539
+ }))
540
+ )
541
+ );
542
+ const failed = results.filter((result) => !result.stopped).length;
543
+ return { ok: failed === 0, stopped: results.length - failed, failed };
544
+ }
545
+ function messageOf(error) {
546
+ return error instanceof Error ? error.message : String(error);
547
+ }
548
+ async function stopLocalHarnessWorkspace(workspaceGrantId) {
549
+ const records = new Set([...sessions.values(), ...unstopped].filter((record) => record.workspaceGrantId === workspaceGrantId));
550
+ let stopped = true;
551
+ for (const record of records) {
552
+ if (claimRecord(record)) stopped = (await endRecord(record)).stopped && stopped;
553
+ else stopped = false;
554
+ }
555
+ return stopped;
556
+ }
557
+ async function stopLocalHarnessProject(userId, projectId) {
558
+ const records = new Set([...sessions.values(), ...unstopped].filter((record) => record.userId === userId && (projectId === void 0 || record.projectId === projectId)));
559
+ await Promise.all([...records].filter(claimRecord).map(endRecord));
560
+ }
561
+
562
+ // server/utils/harness/local/authorization.ts
563
+ import { readFile as readFile2 } from "fs/promises";
564
+ import { join as join2 } from "path";
565
+ import { z } from "zod";
566
+ var harnessIdSchema = z.enum(["claude-code", "codex"]);
567
+ var authorization = z.object({
568
+ userId: z.string().min(1),
569
+ machineId: z.string().min(1),
570
+ projectId: z.string().min(1),
571
+ harnessId: harnessIdSchema,
572
+ autoApproveAcknowledgedAt: z.string().datetime().optional(),
573
+ workspaceGrantId: z.string().min(1),
574
+ policyVersion: z.string().min(1),
575
+ authorizedAt: z.string().datetime(),
576
+ unattended: z.literal(true)
577
+ });
578
+ var legacyAuthorization = authorization.extend({ harnessId: harnessIdSchema.optional() });
579
+ var schema = z.object({
580
+ version: z.literal(1),
581
+ authorizations: z.array(legacyAuthorization),
582
+ harnessAuthorizations: z.array(authorization).optional()
583
+ });
584
+ var file = () => join2(localHarnessStateRoot(), "authorizations.json");
585
+ var lock = createLocalStateMutationLock({ rootDir: localHarnessStateRoot, lockFileName: "authorizations.lock", resourceLabel: "authorization" });
586
+ async function read() {
587
+ try {
588
+ const stored = schema.parse(JSON.parse(await readFile2(file(), "utf8")));
589
+ return {
590
+ authorizations: [
591
+ ...stored.authorizations.map((a) => ({ ...a, harnessId: a.harnessId ?? "claude-code" })),
592
+ ...stored.harnessAuthorizations ?? []
593
+ ]
594
+ };
595
+ } catch (error) {
596
+ if (error.code === "ENOENT") return { authorizations: [] };
597
+ throw new Error("Local authorization could not be read. Restore the authorization store or authorize this client again.", { cause: error });
598
+ }
599
+ }
600
+ async function write(state) {
601
+ await persistCapabilityState(file(), {
602
+ version: 1,
603
+ authorizations: state.authorizations.filter((a) => a.harnessId === "claude-code").map(({ harnessId: _harnessId, ...legacy }) => legacy),
604
+ harnessAuthorizations: state.authorizations.filter((a) => a.harnessId !== "claude-code")
605
+ });
606
+ }
607
+ async function readLocalHarnessAuthorization(userId, machineId, projectId, harnessId = "claude-code") {
608
+ return (await read()).authorizations.find((a) => a.userId === userId && a.machineId === machineId && a.projectId === projectId && a.harnessId === harnessId && a.policyVersion === LOCAL_HARNESS_POLICY_VERSION) ?? null;
609
+ }
610
+ async function authorizeLocalHarness(args) {
611
+ return lock(async () => {
612
+ const state = await read();
613
+ const harnessId = args.harnessId ?? "claude-code";
614
+ const existing = state.authorizations.find((a) => a.userId === args.userId && a.machineId === args.machineId && a.projectId === args.projectId && a.harnessId === harnessId && a.policyVersion === LOCAL_HARNESS_POLICY_VERSION);
615
+ const record = { ...existing?.autoApproveAcknowledgedAt ? { autoApproveAcknowledgedAt: existing.autoApproveAcknowledgedAt } : {}, ...args, harnessId, policyVersion: LOCAL_HARNESS_POLICY_VERSION, authorizedAt: (/* @__PURE__ */ new Date()).toISOString(), unattended: true };
616
+ state.authorizations = state.authorizations.filter((a) => !(a.userId === args.userId && a.machineId === args.machineId && a.projectId === args.projectId && a.harnessId === harnessId));
617
+ state.authorizations.push(record);
618
+ await write(state);
619
+ return record;
620
+ });
621
+ }
622
+ async function revokeLocalHarnessAuthorization(userId, projectId) {
623
+ await lock(async () => {
624
+ const state = await read();
625
+ const revoked = state.authorizations.filter((a) => a.userId === userId && (projectId === void 0 || a.projectId === projectId));
626
+ state.authorizations = state.authorizations.filter((a) => !revoked.includes(a));
627
+ await write(state);
628
+ await revokeLocalHarnessGrants({ userId, projectId });
629
+ await stopLocalHarnessProject(userId, projectId);
630
+ await Promise.all(
631
+ revoked.map((a) => stopLocalHarnessWorkspace(a.workspaceGrantId))
632
+ );
633
+ });
634
+ }
635
+ async function updateAuthorizedWorkspace(args) {
636
+ await lock(async () => {
637
+ const state = await read();
638
+ const harnessId = args.harnessId ?? "claude-code";
639
+ const record = state.authorizations.find((a) => a.userId === args.userId && a.machineId === args.machineId && a.projectId === args.projectId && a.harnessId === harnessId && a.policyVersion === LOCAL_HARNESS_POLICY_VERSION);
640
+ if (!record) return;
641
+ record.workspaceGrantId = args.workspaceGrantId;
642
+ await write(state);
643
+ });
644
+ }
645
+ async function acknowledgeLocalHarnessAutoApprove(args) {
646
+ return lock(async () => {
647
+ const state = await read();
648
+ const record = state.authorizations.find(
649
+ (a) => a.userId === args.userId && a.machineId === args.machineId && a.projectId === args.projectId && a.harnessId === args.harnessId && a.policyVersion === LOCAL_HARNESS_POLICY_VERSION
650
+ );
651
+ if (!record)
652
+ throw new Error(
653
+ "Set up this local harness before allowing commands without asking"
654
+ );
655
+ record.autoApproveAcknowledgedAt ??= (/* @__PURE__ */ new Date()).toISOString();
656
+ await write(state);
657
+ return record;
658
+ });
659
+ }
34
660
 
35
661
  // shared/harness-model-support-evidence.json
36
662
  var harness_model_support_evidence_default = {
@@ -246,254 +872,17 @@ function boxRequestFields(box) {
246
872
  projectId: box.projectId,
247
873
  computerId: box.computerId,
248
874
  ...box.executionScope ? { executionScope: box.executionScope } : {}
249
- } : { sandboxRowId: box.sandboxRowId };
250
- }
251
- async function startHarnessModelBroker(args) {
252
- let url;
253
- try {
254
- url = new URL(
255
- "/web/harness/model-broker/start",
256
- getConvexHttpUrl()
257
- ).toString();
258
- } catch (err) {
259
- logger.error("[harness-model-broker] missing endpoint config", err);
260
- return {
261
- ok: false,
262
- status: 500,
263
- error: "Harness model-broker endpoint is not configured"
264
- };
265
- }
266
- let response;
267
- try {
268
- response = await fetch(url, {
269
- method: "POST",
270
- headers: {
271
- "content-type": "application/json",
272
- authorization: bearerHeader(args.bearer)
273
- },
274
- body: JSON.stringify({
275
- ...boxRequestFields(args.box),
276
- harnessId: args.harnessId,
277
- ...harnessRuntimeVersionField(args.harnessId),
278
- modelId: args.modelId,
279
- ...args.runId ? { runId: args.runId } : {},
280
- ...args.maxOutputTokens !== void 0 ? { maxOutputTokens: args.maxOutputTokens } : {}
281
- }),
282
- signal: args.signal
283
- });
284
- } catch (err) {
285
- logger.error("[harness-model-broker] network error", err);
286
- return {
287
- ok: false,
288
- status: 502,
289
- error: "Failed to reach harness model-broker endpoint"
290
- };
291
- }
292
- let payload = null;
293
- try {
294
- payload = await response.json();
295
- } catch {
296
- return {
297
- ok: false,
298
- status: response.ok ? 502 : response.status,
299
- error: `Harness model-broker returned ${response.status} with non-JSON body`
300
- };
301
- }
302
- const validShape = response.ok && payload?.ok === true && typeof payload?.runId === "string" && payload.runId.length > 0 && typeof payload?.proxyBaseUrl === "string" && payload.proxyBaseUrl.length > 0 && typeof payload?.expiresAt === "number" && Number.isFinite(payload.expiresAt) && (payload?.protocol === "anthropic" || payload?.protocol === "openai") && payload?.delivery === "e2b-network-transform";
303
- if (!validShape) {
304
- return {
305
- ok: false,
306
- status: response.ok ? 502 : response.status,
307
- error: typeof payload?.error === "string" ? payload.error : `Harness model-broker failed (${response.status})`
308
- };
309
- }
310
- return {
311
- ok: true,
312
- runId: payload.runId,
313
- expiresAt: payload.expiresAt,
314
- protocol: payload.protocol,
315
- proxyBaseUrl: payload.proxyBaseUrl,
316
- delivery: "e2b-network-transform"
317
- };
318
- }
319
- async function registerLocalInstance(args) {
320
- let url;
321
- try {
322
- url = new URL(
323
- "/web/harness/local-instance/register",
324
- getConvexHttpUrl()
325
- ).toString();
326
- } catch (err) {
327
- logger.error("[harness-model-broker] missing register endpoint config", err);
328
- return {
329
- ok: false,
330
- status: 500,
331
- error: "Harness local-instance endpoint is not configured"
332
- };
333
- }
334
- let response;
335
- try {
336
- response = await fetch(url, {
337
- method: "POST",
338
- headers: {
339
- "content-type": "application/json",
340
- authorization: bearerHeader(args.bearer)
341
- },
342
- body: JSON.stringify({
343
- machineId: args.machineId,
344
- publicKey: args.publicKey
345
- }),
346
- ...args.signal ? { signal: args.signal } : {}
347
- });
348
- } catch (err) {
349
- logger.error("[harness-model-broker] register network error", err);
350
- return {
351
- ok: false,
352
- status: 502,
353
- error: "Failed to reach the harness local-instance endpoint"
354
- };
355
- }
356
- const payload = await response.json().catch(() => null);
357
- if (!response.ok || payload?.ok !== true || typeof payload?.keyId !== "string") {
358
- return {
359
- ok: false,
360
- status: response.ok ? 502 : response.status,
361
- error: typeof payload?.error === "string" ? payload.error : `Local instance registration failed (${response.status})`
362
- };
363
- }
364
- return { ok: true, keyId: payload.keyId };
365
- }
366
- async function startLoopbackModelBroker(args) {
367
- let url;
368
- try {
369
- url = new URL(
370
- "/web/harness/model-broker/start",
371
- getConvexHttpUrl()
372
- ).toString();
373
- } catch (err) {
374
- logger.error("[harness-model-broker] missing endpoint config", err);
375
- return {
376
- ok: false,
377
- status: 500,
378
- error: "Harness model-broker endpoint is not configured"
379
- };
380
- }
381
- let response;
382
- try {
383
- response = await fetch(url, {
384
- method: "POST",
385
- headers: {
386
- "content-type": "application/json",
387
- authorization: bearerHeader(args.bearer)
388
- },
389
- body: JSON.stringify({
390
- // Declared, not inferred: the backend forks on this, and a caller that
391
- // means "local" says so rather than being detected by an absent
392
- // computerId. No box fields travel — the backend refuses a local
393
- // request that carries one.
394
- delivery: "inspector-loopback-gateway",
395
- projectId: args.projectId,
396
- harnessId: args.harnessId,
397
- ...harnessRuntimeVersionField(args.harnessId),
398
- modelId: args.modelId,
399
- ...args.evalIterationId ? { evalIterationId: args.evalIterationId } : {},
400
- ...args.journeyRunId ? { journeyRunId: args.journeyRunId, hostId: args.hostId, targetId: args.targetId, sessionIdx: args.sessionIdx } : {},
401
- machineId: args.machineId,
402
- keyId: args.keyId,
403
- ...args.runId ? { runId: args.runId } : {},
404
- ...args.maxOutputTokens !== void 0 ? { maxOutputTokens: args.maxOutputTokens } : {}
405
- }),
406
- ...args.signal ? { signal: args.signal } : {}
407
- });
408
- } catch (err) {
409
- logger.error("[harness-model-broker] network error", err);
410
- return {
411
- ok: false,
412
- status: 502,
413
- error: "Failed to reach harness model-broker endpoint"
414
- };
415
- }
416
- let payload = null;
417
- try {
418
- payload = await response.json();
419
- } catch {
420
- return {
421
- ok: false,
422
- status: response.ok ? 502 : response.status,
423
- error: `Harness model-broker returned ${response.status} with non-JSON body`
424
- };
425
- }
426
- const validShape = response.ok && payload?.ok === true && typeof payload?.runId === "string" && payload.runId.length > 0 && typeof payload?.proxyBaseUrl === "string" && payload.proxyBaseUrl.length > 0 && typeof payload?.expiresAt === "number" && Number.isFinite(payload.expiresAt) && (payload?.protocol === "anthropic" || payload?.protocol === "openai") && payload?.delivery === "inspector-loopback-gateway" && // The lease is the point of this delivery. A response without one is not a
427
- // usable local start, whatever else it says.
428
- typeof payload?.lease === "string" && payload.lease.length > 0;
429
- if (!validShape) {
430
- return {
431
- ok: false,
432
- status: response.ok ? 502 : response.status,
433
- error: typeof payload?.error === "string" ? payload.error : `Harness model-broker failed (${response.status})`
434
- };
435
- }
436
- return {
437
- ok: true,
438
- runId: payload.runId,
439
- expiresAt: payload.expiresAt,
440
- protocol: payload.protocol,
441
- proxyBaseUrl: payload.proxyBaseUrl,
442
- delivery: "inspector-loopback-gateway",
443
- lease: payload.lease
444
- };
445
- }
446
- async function revokeHarnessModelBroker(args) {
447
- let url;
448
- try {
449
- url = new URL(
450
- "/web/harness/model-broker/revoke",
451
- getConvexHttpUrl()
452
- ).toString();
453
- } catch (err) {
454
- logger.error("[harness-model-broker] missing revoke endpoint config", err);
455
- return { ok: false };
456
- }
457
- try {
458
- const response = await fetch(url, {
459
- method: "POST",
460
- headers: {
461
- "content-type": "application/json",
462
- authorization: bearerHeader(args.bearer)
463
- },
464
- body: JSON.stringify({
465
- ...args.projectId ? { projectId: args.projectId } : {},
466
- ...args.computerId ? { computerId: args.computerId } : {},
467
- runId: args.runId
468
- }),
469
- signal: args.signal ? AbortSignal.any([args.signal, AbortSignal.timeout(1e4)]) : AbortSignal.timeout(1e4)
470
- });
471
- const payload = await response.json().catch(() => null);
472
- if (!response.ok || payload?.ok !== true) {
473
- logger.warn(`[harness-model-broker] revoke returned ${response.status}`);
474
- return { ok: false };
475
- }
476
- return {
477
- ok: true,
478
- revoked: payload.revoked,
479
- networkCleared: payload.networkCleared
480
- };
481
- } catch (err) {
482
- logger.warn("[harness-model-broker] revoke network error", {
483
- error: err instanceof Error ? err.message : String(err)
484
- });
485
- return { ok: false };
486
- }
875
+ } : { sandboxRowId: box.sandboxRowId };
487
876
  }
488
- async function reserveHarnessBox(args) {
877
+ async function startHarnessModelBroker(args) {
489
878
  let url;
490
879
  try {
491
880
  url = new URL(
492
- "/web/harness/model-broker/reserve",
881
+ "/web/harness/model-broker/start",
493
882
  getConvexHttpUrl()
494
883
  ).toString();
495
884
  } catch (err) {
496
- logger.error("[harness-model-broker] missing reserve endpoint config", err);
885
+ logger.error("[harness-model-broker] missing endpoint config", err);
497
886
  return {
498
887
  ok: false,
499
888
  status: 500,
@@ -510,523 +899,356 @@ async function reserveHarnessBox(args) {
510
899
  },
511
900
  body: JSON.stringify({
512
901
  ...boxRequestFields(args.box),
513
- // The same harness + model the lease will name: the backend authorizes a
514
- // reservation exactly as it authorizes a lease, which for an ephemeral
515
- // box means checking both against what the run actually pinned.
516
902
  harnessId: args.harnessId,
517
903
  ...harnessRuntimeVersionField(args.harnessId),
518
904
  modelId: args.modelId,
519
- runId: args.runId
905
+ ...args.runId ? { runId: args.runId } : {},
906
+ ...args.maxOutputTokens !== void 0 ? { maxOutputTokens: args.maxOutputTokens } : {},
907
+ ...args.reasoningEffort ? { reasoningEffort: args.reasoningEffort } : {}
520
908
  }),
521
909
  signal: args.signal
522
910
  });
523
911
  } catch (err) {
524
- logger.error("[harness-model-broker] reserve network error", err);
912
+ logger.error("[harness-model-broker] network error", err);
525
913
  return {
526
914
  ok: false,
527
915
  status: 502,
528
916
  error: "Failed to reach harness model-broker endpoint"
529
917
  };
530
918
  }
531
- const payload = await response.json().catch(() => null);
532
- if (!response.ok || payload?.ok !== true) {
533
- return {
534
- ok: false,
535
- status: response.status,
536
- error: typeof payload?.error === "string" ? payload.error : `Couldn't reserve the computer (${response.status})`
537
- };
538
- }
539
- return {
540
- ok: true,
541
- ...typeof payload.expiresAt === "number" ? { expiresAt: payload.expiresAt } : {}
542
- };
543
- }
544
- async function renewHarnessBoxReservation(args) {
545
- let url;
919
+ let payload = null;
546
920
  try {
547
- url = new URL(
548
- "/web/harness/model-broker/reserve/renew",
549
- getConvexHttpUrl()
550
- ).toString();
921
+ payload = await response.json();
551
922
  } catch {
552
- return { ok: false };
553
- }
554
- try {
555
- const response = await fetch(url, {
556
- method: "POST",
557
- headers: {
558
- "content-type": "application/json",
559
- authorization: bearerHeader(args.bearer)
560
- },
561
- body: JSON.stringify({
562
- ...boxRequestFields(args.box),
563
- harnessId: args.harnessId,
564
- modelId: args.modelId,
565
- runId: args.runId
566
- }),
567
- signal: args.signal
568
- });
569
- const payload = await response.json().catch(() => null);
570
- if (!response.ok || payload?.ok !== true) {
571
- logger.error(
572
- `[harness-model-broker] reservation renewal returned ${response.status}`
573
- );
574
- return { ok: false };
575
- }
576
923
  return {
577
- ok: true,
578
- ...typeof payload.expiresAt === "number" ? { expiresAt: payload.expiresAt } : {}
924
+ ok: false,
925
+ status: response.ok ? 502 : response.status,
926
+ error: `Harness model-broker returned ${response.status} with non-JSON body`
579
927
  };
580
- } catch (err) {
581
- logger.error(
582
- "[harness-model-broker] reservation renewal network error",
583
- err
584
- );
585
- return { ok: false };
586
- }
587
- }
588
- async function releaseHarnessBoxReservation(args) {
589
- let url;
590
- try {
591
- url = new URL(
592
- "/web/harness/model-broker/reserve/release",
593
- getConvexHttpUrl()
594
- ).toString();
595
- } catch {
596
- return { ok: false };
597
- }
598
- try {
599
- const response = await fetch(url, {
600
- method: "POST",
601
- headers: {
602
- "content-type": "application/json",
603
- authorization: bearerHeader(args.bearer)
604
- },
605
- body: JSON.stringify({
606
- ...boxRequestFields(args.box),
607
- harnessId: args.harnessId,
608
- modelId: args.modelId,
609
- runId: args.runId
610
- }),
611
- signal: args.signal
612
- });
613
- if (!response.ok) {
614
- logger.warn(
615
- `[harness-model-broker] reservation release returned ${response.status}`
616
- );
617
- return { ok: false };
618
- }
619
- return { ok: true };
620
- } catch (err) {
621
- logger.error("[harness-model-broker] reservation release network error", err);
622
- return { ok: false };
623
- }
624
- }
625
-
626
- // server/utils/harness/local/grants.ts
627
- import { randomUUID } from "crypto";
628
- import { mkdir, readFile, rename, writeFile, chmod } from "fs/promises";
629
- import { homedir } from "os";
630
- import { join, sep } from "path";
631
- import { realpath, stat } from "fs/promises";
632
- var LOCAL_HARNESS_GRANT_HEADER = "x-mcpjam-local-harness-grant";
633
- function localHarnessStateRoot() {
634
- return join(homedir(), ".mcpjam", "harness-local");
635
- }
636
- function grantsFilePath() {
637
- return join(localHarnessStateRoot(), "grants.json");
638
- }
639
- function machineFilePath() {
640
- return join(localHarnessStateRoot(), "machine.json");
641
- }
642
- function emptyState() {
643
- return { version: 1, workspaces: [], harnessGrants: [] };
644
- }
645
- var GRANT_TTL_MS = 12 * 60 * 60 * 1e3;
646
- var withGrantLock = createLocalStateMutationLock({
647
- rootDir: localHarnessStateRoot,
648
- lockFileName: "grants.lock",
649
- resourceLabel: "grant store"
650
- });
651
- function hashGrantBinding(binding) {
652
- return capabilityFingerprint(
653
- JSON.stringify([
654
- binding.scope ?? "attended",
655
- binding.userId,
656
- binding.machineId,
657
- binding.projectId,
658
- binding.workspaceGrantId,
659
- binding.harnessId,
660
- binding.targetKind,
661
- binding.backend ?? null,
662
- binding.runtimeId,
663
- binding.permissionProfile,
664
- binding.policyVersion,
665
- // Only isolated bindings carry one, and only they hash it. A native
666
- // binding has no isolation policy to be bound to, so folding a constant
667
- // `null` into its hash would change every native hash for a value that
668
- // means nothing there — invalidating consents that the local policy
669
- // never touched. A native binding that carries one anyway is refused
670
- // outright by `verifyLocalHarnessGrant`, not admitted by the hash.
671
- ...binding.targetKind === "local-isolated" ? [binding.isolationPolicyVersion ?? null] : []
672
- ])
673
- );
674
- }
675
- var GrantStateUnreadableError = class extends Error {
676
- };
677
- function isValidDate(value) {
678
- return typeof value === "string" && Number.isFinite(Date.parse(value));
679
- }
680
- function isWorkspaceGrant(value) {
681
- if (!value || typeof value !== "object") return false;
682
- const workspace = value;
683
- return typeof workspace.workspaceGrantId === "string" && workspace.workspaceGrantId.length > 0 && typeof workspace.canonicalPath === "string" && workspace.canonicalPath.length > 0 && isValidDate(workspace.createdAt);
684
- }
685
- function isHarnessGrantBinding(value) {
686
- if (!value || typeof value !== "object") return false;
687
- const binding = value;
688
- const isolatedBackend = binding.backend === "linux-bwrap" || binding.backend === "darwin-seatbelt" || binding.backend === "oci-v1" || binding.backend === "vm-v1";
689
- return typeof binding.userId === "string" && binding.userId.length > 0 && typeof binding.machineId === "string" && binding.machineId.length > 0 && (binding.scope === void 0 || binding.scope === "attended" || binding.scope === "unattended") && typeof binding.projectId === "string" && binding.projectId.length > 0 && typeof binding.workspaceGrantId === "string" && binding.workspaceGrantId.length > 0 && (binding.harnessId === "claude-code" || binding.harnessId === "codex") && (binding.targetKind === "local-native" || binding.targetKind === "local-isolated") && typeof binding.runtimeId === "string" && binding.runtimeId.length > 0 && (binding.permissionProfile === "read-only" || binding.permissionProfile === "workspace-edits" || binding.permissionProfile === "unrestricted") && typeof binding.policyVersion === "string" && binding.policyVersion.length > 0 && (binding.targetKind === "local-native" ? binding.backend === void 0 && binding.isolationPolicyVersion === void 0 : isolatedBackend && typeof binding.isolationPolicyVersion === "string" && binding.isolationPolicyVersion.length > 0);
690
- }
691
- function isPersistedHarnessGrant(value) {
692
- if (!value || typeof value !== "object") return false;
693
- const grant = value;
694
- return typeof grant.grantId === "string" && grant.grantId.length > 0 && typeof grant.tokenHash === "string" && /^[0-9a-f]{64}$/.test(grant.tokenHash) && typeof grant.bindingHash === "string" && /^[0-9a-f]{64}$/.test(grant.bindingHash) && isHarnessGrantBinding(grant.binding) && isValidDate(grant.grantedAt) && isValidDate(grant.expiresAt);
695
- }
696
- async function readState() {
697
- let raw;
698
- try {
699
- raw = await readFile(grantsFilePath(), "utf8");
700
- } catch (error) {
701
- if (error.code === "ENOENT") return emptyState();
702
- throw new GrantStateUnreadableError(
703
- `the local harness grant store could not be read: ${error instanceof Error ? error.message : String(error)}`
704
- );
705
- }
706
- let parsed;
707
- try {
708
- parsed = JSON.parse(raw);
709
- } catch {
710
- throw new GrantStateUnreadableError(
711
- "the local harness grant store is corrupt; refusing to treat it as empty or overwrite it"
712
- );
713
- }
714
- if (!parsed || typeof parsed !== "object") {
715
- throw new GrantStateUnreadableError(
716
- "the local harness grant store is not an object"
717
- );
718
- }
719
- const record = parsed;
720
- if (record.version !== 1 || !Array.isArray(record.workspaces) || !Array.isArray(record.harnessGrants) || !record.workspaces.every(isWorkspaceGrant) || !record.harnessGrants.every(isPersistedHarnessGrant)) {
721
- throw new GrantStateUnreadableError(
722
- "the local harness grant store has an unrecognized or malformed shape"
723
- );
724
928
  }
725
- return {
726
- version: 1,
727
- workspaces: [...record.workspaces],
728
- harnessGrants: [...record.harnessGrants]
729
- };
730
- }
731
- async function writeState(state) {
732
- const dir = localHarnessStateRoot();
733
- await mkdir(dir, { recursive: true, mode: 448 });
734
- await chmod(dir, 448).catch(() => {
735
- });
736
- await persistCapabilityState(grantsFilePath(), state);
737
- }
738
- async function getLocalMachineId() {
739
- const readExisting = async () => {
740
- let raw;
741
- try {
742
- raw = await readFile(machineFilePath(), "utf8");
743
- } catch (error) {
744
- if (error.code === "ENOENT") return null;
745
- throw new GrantStateUnreadableError(
746
- `the local harness machine identity could not be read: ${error instanceof Error ? error.message : String(error)}`
747
- );
748
- }
749
- let parsed;
750
- try {
751
- parsed = JSON.parse(raw);
752
- } catch {
753
- throw new GrantStateUnreadableError(
754
- "the local harness machine identity is corrupt; refusing to replace it"
755
- );
756
- }
757
- if (!parsed || typeof parsed !== "object") {
758
- throw new GrantStateUnreadableError(
759
- "the local harness machine identity has an unrecognized shape"
760
- );
761
- }
762
- const machineId = parsed.machineId;
763
- if (typeof machineId !== "string" || machineId.length < 8) {
764
- throw new GrantStateUnreadableError(
765
- "the local harness machine identity has an invalid id"
766
- );
767
- }
768
- return machineId;
929
+ const validShape = response.ok && payload?.ok === true && typeof payload?.runId === "string" && payload.runId.length > 0 && typeof payload?.proxyBaseUrl === "string" && payload.proxyBaseUrl.length > 0 && typeof payload?.expiresAt === "number" && Number.isFinite(payload.expiresAt) && (payload?.protocol === "anthropic" || payload?.protocol === "openai") && payload?.delivery === "e2b-network-transform";
930
+ if (!validShape) {
931
+ return {
932
+ ok: false,
933
+ status: response.ok ? 502 : response.status,
934
+ error: typeof payload?.error === "string" ? payload.error : `Harness model-broker failed (${response.status})`
935
+ };
936
+ }
937
+ return {
938
+ ok: true,
939
+ runId: payload.runId,
940
+ expiresAt: payload.expiresAt,
941
+ protocol: payload.protocol,
942
+ proxyBaseUrl: payload.proxyBaseUrl,
943
+ delivery: "e2b-network-transform"
769
944
  };
770
- const existing = await readExisting();
771
- if (existing !== null) return existing;
772
- return withGrantLock(async () => {
773
- const raced = await readExisting();
774
- if (raced !== null) return raced;
775
- const machineId = `mach_${randomUUID()}`;
776
- const dir = localHarnessStateRoot();
777
- await mkdir(dir, { recursive: true, mode: 448 });
778
- const file = machineFilePath();
779
- const tmp = `${file}.tmp`;
780
- await writeFile(tmp, JSON.stringify({ machineId }), { mode: 384 });
781
- await rename(tmp, file);
782
- return machineId;
783
- });
784
- }
785
- function isFilesystemRoot(canonicalPath) {
786
- return canonicalPath === sep || canonicalPath === "/" || // A drive root: `C:`, `C:\`, `C:/`.
787
- /^[A-Za-z]:[\\/]?$/.test(canonicalPath) || // A UNC share root: `\\server\share` and its trailing-separator form, and
788
- // a bare `\\server`. Scoping a session to a whole network share is the
789
- // same mistake as scoping it to a whole volume, and the earlier rule
790
- // covered only the volume. Anything BELOW the share
791
- // (`\\server\share\project`) stays acceptable.
792
- //
793
- // Matched on the BACKSLASH form only. Accepting `//` here as well read a
794
- // POSIX path with a doubled leading slash — `//tmp/project`, which POSIX
795
- // expressly permits an implementation to keep — as a share root, and
796
- // refused an ordinary directory. Windows has no such ambiguity to trade
797
- // against: `realpath` and `path.resolve` both answer `\\server\share`
798
- // there, so the canonical path this predicate is given is always the
799
- // backslash form.
800
- /^\\{2}[^\\/]+([\\/][^\\/]+)?[\\/]?$/.test(canonicalPath);
801
945
  }
802
- async function validateWorkspaceCandidate(rawPath) {
803
- let canonicalPath;
946
+ async function registerLocalInstance(args) {
947
+ let url;
804
948
  try {
805
- canonicalPath = await realpath(rawPath);
806
- const info = await stat(canonicalPath);
807
- if (!info.isDirectory()) {
808
- return { ok: false, message: "the selection is not a directory" };
809
- }
810
- } catch (error) {
949
+ url = new URL(
950
+ "/web/harness/local-instance/register",
951
+ getConvexHttpUrl()
952
+ ).toString();
953
+ } catch (err) {
954
+ logger.error("[harness-model-broker] missing register endpoint config", err);
811
955
  return {
812
956
  ok: false,
813
- message: `the selected workspace could not be resolved: ${error instanceof Error ? error.message : String(error)}`
957
+ status: 500,
958
+ error: "Harness local-instance endpoint is not configured"
814
959
  };
815
960
  }
816
- const home = await realpath(homedir()).catch(() => homedir());
817
- const appRoot = join(home, ".mcpjam");
818
- const workspaces = join(appRoot, "harness-workspaces");
819
- if (canonicalPath === home || isFilesystemRoot(canonicalPath) || (canonicalPath === appRoot || canonicalPath.startsWith(appRoot + sep)) && !canonicalPath.startsWith(workspaces + sep)) {
961
+ let response;
962
+ try {
963
+ response = await fetch(url, {
964
+ method: "POST",
965
+ headers: {
966
+ "content-type": "application/json",
967
+ authorization: bearerHeader(args.bearer)
968
+ },
969
+ body: JSON.stringify({
970
+ machineId: args.machineId,
971
+ publicKey: args.publicKey
972
+ }),
973
+ ...args.signal ? { signal: args.signal } : {}
974
+ });
975
+ } catch (err) {
976
+ logger.error("[harness-model-broker] register network error", err);
820
977
  return {
821
978
  ok: false,
822
- message: "pick a project directory rather than your home directory or the filesystem root \u2014 the workspace is what the session is scoped to."
979
+ status: 502,
980
+ error: "Failed to reach the harness local-instance endpoint"
823
981
  };
824
982
  }
825
- return { ok: true, canonicalPath };
826
- }
827
- function registerWorkspaceGrant(rawPath) {
828
- return withGrantLock(async () => {
829
- const candidate = await validateWorkspaceCandidate(rawPath);
830
- if (!candidate.ok) {
831
- return { ok: false, message: candidate.message };
832
- }
833
- const canonicalPath = candidate.canonicalPath;
834
- const state = await readState();
835
- const existing = state.workspaces.find(
836
- (w) => w.canonicalPath === canonicalPath
837
- );
838
- if (existing) return { ok: true, grant: existing };
839
- const grant = {
840
- workspaceGrantId: `ws_${randomUUID()}`,
841
- canonicalPath,
842
- createdAt: (/* @__PURE__ */ new Date()).toISOString()
983
+ const payload = await response.json().catch(() => null);
984
+ if (!response.ok || payload?.ok !== true || typeof payload?.keyId !== "string") {
985
+ return {
986
+ ok: false,
987
+ status: response.ok ? 502 : response.status,
988
+ error: typeof payload?.error === "string" ? payload.error : `Local instance registration failed (${response.status})`
843
989
  };
844
- state.workspaces.push(grant);
845
- await writeState(state);
846
- logger.info("[local-harness] workspace grant registered");
847
- return { ok: true, grant };
848
- });
990
+ }
991
+ return { ok: true, keyId: payload.keyId };
849
992
  }
850
- async function resolveWorkspaceGrant(workspaceGrantId) {
851
- let state;
993
+ async function startLoopbackModelBroker(args) {
994
+ let url;
852
995
  try {
853
- state = await readState();
854
- } catch (error) {
996
+ url = new URL(
997
+ "/web/harness/model-broker/start",
998
+ getConvexHttpUrl()
999
+ ).toString();
1000
+ } catch (err) {
1001
+ logger.error("[harness-model-broker] missing endpoint config", err);
855
1002
  return {
856
1003
  ok: false,
857
- message: error instanceof Error ? error.message : "the local harness grant store could not be read"
1004
+ status: 500,
1005
+ error: "Harness model-broker endpoint is not configured"
858
1006
  };
859
1007
  }
860
- const grant = state.workspaces.find(
861
- (w) => w.workspaceGrantId === workspaceGrantId
862
- );
863
- if (!grant) {
864
- return { ok: false, message: "unknown workspace grant" };
1008
+ let response;
1009
+ try {
1010
+ response = await fetch(url, {
1011
+ method: "POST",
1012
+ headers: {
1013
+ "content-type": "application/json",
1014
+ authorization: bearerHeader(args.bearer)
1015
+ },
1016
+ body: JSON.stringify({
1017
+ // Declared, not inferred: the backend forks on this, and a caller that
1018
+ // means "local" says so rather than being detected by an absent
1019
+ // computerId. No box fields travel — the backend refuses a local
1020
+ // request that carries one.
1021
+ delivery: "inspector-loopback-gateway",
1022
+ projectId: args.projectId,
1023
+ harnessId: args.harnessId,
1024
+ ...harnessRuntimeVersionField(args.harnessId),
1025
+ modelId: args.modelId,
1026
+ ...args.evalIterationId ? { evalIterationId: args.evalIterationId } : {},
1027
+ ...args.journeyRunId ? { journeyRunId: args.journeyRunId, hostId: args.hostId, targetId: args.targetId, sessionIdx: args.sessionIdx } : {},
1028
+ machineId: args.machineId,
1029
+ keyId: args.keyId,
1030
+ ...args.runId ? { runId: args.runId } : {},
1031
+ ...args.maxOutputTokens !== void 0 ? { maxOutputTokens: args.maxOutputTokens } : {},
1032
+ ...args.reasoningEffort ? { reasoningEffort: args.reasoningEffort } : {}
1033
+ }),
1034
+ ...args.signal ? { signal: args.signal } : {}
1035
+ });
1036
+ } catch (err) {
1037
+ logger.error("[harness-model-broker] network error", err);
1038
+ return {
1039
+ ok: false,
1040
+ status: 502,
1041
+ error: "Failed to reach harness model-broker endpoint"
1042
+ };
865
1043
  }
1044
+ let payload = null;
866
1045
  try {
867
- const canonical = await realpath(grant.canonicalPath);
868
- if (canonical !== grant.canonicalPath) {
869
- return {
870
- ok: false,
871
- message: "the granted workspace now resolves somewhere else; re-select it before running locally"
872
- };
873
- }
874
- const info = await stat(canonical);
875
- if (!info.isDirectory()) {
876
- return {
877
- ok: false,
878
- message: "the granted workspace is no longer a directory"
879
- };
880
- }
881
- const candidate = await validateWorkspaceCandidate(canonical);
882
- if (!candidate.ok) return candidate;
883
- return { ok: true, canonicalPath: canonical };
1046
+ payload = await response.json();
884
1047
  } catch {
885
1048
  return {
886
1049
  ok: false,
887
- message: "the granted workspace is no longer reachable"
1050
+ status: response.ok ? 502 : response.status,
1051
+ error: `Harness model-broker returned ${response.status} with non-JSON body`
888
1052
  };
889
1053
  }
890
- }
891
- function grantLocalHarnessConsent(binding, opts) {
892
- return withGrantLock(async () => {
893
- const now = opts?.now ?? Date.now();
894
- const ttlMs = Math.min(opts?.ttlMs ?? GRANT_TTL_MS, GRANT_TTL_MS);
895
- const token = mintCapabilityToken();
896
- const grant = {
897
- grantId: `grant_${randomUUID()}`,
898
- tokenHash: capabilityFingerprint(token),
899
- bindingHash: hashGrantBinding(binding),
900
- binding,
901
- grantedAt: new Date(now).toISOString(),
902
- expiresAt: new Date(now + ttlMs).toISOString()
1054
+ const validShape = response.ok && payload?.ok === true && typeof payload?.runId === "string" && payload.runId.length > 0 && typeof payload?.proxyBaseUrl === "string" && payload.proxyBaseUrl.length > 0 && typeof payload?.expiresAt === "number" && Number.isFinite(payload.expiresAt) && (payload?.protocol === "anthropic" || payload?.protocol === "openai") && payload?.delivery === "inspector-loopback-gateway" && // The lease is the point of this delivery. A response without one is not a
1055
+ // usable local start, whatever else it says.
1056
+ typeof payload?.lease === "string" && payload.lease.length > 0;
1057
+ if (!validShape) {
1058
+ return {
1059
+ ok: false,
1060
+ status: response.ok ? 502 : response.status,
1061
+ error: typeof payload?.error === "string" ? payload.error : `Harness model-broker failed (${response.status})`
903
1062
  };
904
- const state = await readState();
905
- state.harnessGrants = state.harnessGrants.filter(
906
- (g) => Date.parse(g.expiresAt) > now
907
- );
908
- state.harnessGrants.push(grant);
909
- await writeState(state);
910
- logger.info("[local-harness] consent granted", {
911
- harnessId: binding.harnessId,
912
- targetKind: binding.targetKind,
913
- permissionProfile: binding.permissionProfile,
914
- policyVersion: binding.policyVersion
915
- });
916
- return { grantId: grant.grantId, token, expiresAt: grant.expiresAt };
917
- });
1063
+ }
1064
+ return {
1065
+ ok: true,
1066
+ runId: payload.runId,
1067
+ expiresAt: payload.expiresAt,
1068
+ protocol: payload.protocol,
1069
+ proxyBaseUrl: payload.proxyBaseUrl,
1070
+ delivery: "inspector-loopback-gateway",
1071
+ lease: payload.lease
1072
+ };
918
1073
  }
919
- async function verifyLocalHarnessGrant(token, binding, opts) {
920
- if (!token || token.length < 16 || token.length > 256) {
1074
+ async function revokeHarnessModelBroker(args) {
1075
+ let url;
1076
+ try {
1077
+ url = new URL(
1078
+ "/web/harness/model-broker/revoke",
1079
+ getConvexHttpUrl()
1080
+ ).toString();
1081
+ } catch (err) {
1082
+ logger.error("[harness-model-broker] missing revoke endpoint config", err);
1083
+ return { ok: false };
1084
+ }
1085
+ try {
1086
+ const response = await fetch(url, {
1087
+ method: "POST",
1088
+ headers: {
1089
+ "content-type": "application/json",
1090
+ authorization: bearerHeader(args.bearer)
1091
+ },
1092
+ body: JSON.stringify({
1093
+ ...args.projectId ? { projectId: args.projectId } : {},
1094
+ ...args.computerId ? { computerId: args.computerId } : {},
1095
+ runId: args.runId
1096
+ }),
1097
+ signal: args.signal ? AbortSignal.any([args.signal, AbortSignal.timeout(1e4)]) : AbortSignal.timeout(1e4)
1098
+ });
1099
+ const payload = await response.json().catch(() => null);
1100
+ if (!response.ok || payload?.ok !== true) {
1101
+ logger.warn(`[harness-model-broker] revoke returned ${response.status}`);
1102
+ return { ok: false };
1103
+ }
921
1104
  return {
922
- ok: false,
923
- reason: "invalid",
924
- message: "no local harness grant was presented"
1105
+ ok: true,
1106
+ revoked: payload.revoked,
1107
+ networkCleared: payload.networkCleared
925
1108
  };
1109
+ } catch (err) {
1110
+ logger.warn("[harness-model-broker] revoke network error", {
1111
+ error: err instanceof Error ? err.message : String(err)
1112
+ });
1113
+ return { ok: false };
926
1114
  }
927
- if (binding.policyVersion !== LOCAL_HARNESS_POLICY_VERSION) {
1115
+ }
1116
+ async function reserveHarnessBox(args) {
1117
+ let url;
1118
+ try {
1119
+ url = new URL(
1120
+ "/web/harness/model-broker/reserve",
1121
+ getConvexHttpUrl()
1122
+ ).toString();
1123
+ } catch (err) {
1124
+ logger.error("[harness-model-broker] missing reserve endpoint config", err);
928
1125
  return {
929
1126
  ok: false,
930
- reason: "binding-mismatch",
931
- message: `this grant was minted under policy ${binding.policyVersion}; the current policy is ${LOCAL_HARNESS_POLICY_VERSION}. The terms changed, so consent is asked again.`
1127
+ status: 500,
1128
+ error: "Harness model-broker endpoint is not configured"
932
1129
  };
933
1130
  }
934
- if (binding.targetKind === "local-isolated") {
935
- if (binding.isolationPolicyVersion !== LOCAL_ISOLATION_POLICY_VERSION) {
936
- return {
937
- ok: false,
938
- reason: "binding-mismatch",
939
- message: `this grant was minted under isolation policy ${binding.isolationPolicyVersion ?? "(none)"}; the current isolation policy is ${LOCAL_ISOLATION_POLICY_VERSION}.`
940
- };
941
- }
942
- } else if (binding.isolationPolicyVersion !== void 0) {
1131
+ let response;
1132
+ try {
1133
+ response = await fetch(url, {
1134
+ method: "POST",
1135
+ headers: {
1136
+ "content-type": "application/json",
1137
+ authorization: bearerHeader(args.bearer)
1138
+ },
1139
+ body: JSON.stringify({
1140
+ ...boxRequestFields(args.box),
1141
+ // The same harness + model the lease will name: the backend authorizes a
1142
+ // reservation exactly as it authorizes a lease, which for an ephemeral
1143
+ // box means checking both against what the run actually pinned.
1144
+ harnessId: args.harnessId,
1145
+ ...harnessRuntimeVersionField(args.harnessId),
1146
+ modelId: args.modelId,
1147
+ runId: args.runId
1148
+ }),
1149
+ signal: args.signal
1150
+ });
1151
+ } catch (err) {
1152
+ logger.error("[harness-model-broker] reserve network error", err);
943
1153
  return {
944
1154
  ok: false,
945
- reason: "binding-mismatch",
946
- message: "a native grant must not carry an isolation policy version"
1155
+ status: 502,
1156
+ error: "Failed to reach harness model-broker endpoint"
947
1157
  };
948
1158
  }
949
- const bindingHash = hashGrantBinding(binding);
950
- let state;
951
- try {
952
- state = await readState();
953
- } catch (error) {
1159
+ const payload = await response.json().catch(() => null);
1160
+ if (!response.ok || payload?.ok !== true) {
954
1161
  return {
955
1162
  ok: false,
956
- reason: "invalid",
957
- message: error instanceof Error ? error.message : "the local harness grant store could not be read"
1163
+ status: response.status,
1164
+ error: typeof payload?.error === "string" ? payload.error : `Couldn't reserve the computer (${response.status})`
958
1165
  };
959
1166
  }
960
- const now = opts?.now ?? Date.now();
961
- for (const grant of state.harnessGrants) {
962
- if (!capabilityMatches(token, grant.tokenHash)) continue;
963
- if (grant.bindingHash !== bindingHash) {
964
- return {
965
- ok: false,
966
- reason: "binding-mismatch",
967
- message: "the presented grant was issued for different terms (workspace, harness, runtime, target mode, permission profile, or policy version). Local execution never runs under terms the user did not see."
968
- };
969
- }
970
- if (Date.parse(grant.expiresAt) <= now) {
971
- return {
972
- ok: false,
973
- reason: "expired",
974
- message: "the local harness grant expired; consent is attended and short-lived"
975
- };
976
- }
977
- return { ok: true, grantId: grant.grantId };
978
- }
979
1167
  return {
980
- ok: false,
981
- reason: "absent",
982
- message: "no local harness grant matches the presented capability"
1168
+ ok: true,
1169
+ ...typeof payload.expiresAt === "number" ? { expiresAt: payload.expiresAt } : {}
983
1170
  };
984
1171
  }
985
- function revokeLocalHarnessGrants(selector) {
986
- return withGrantLock(async () => {
987
- const state = await readState();
988
- const before = state.harnessGrants.length;
989
- if (!selector) {
990
- state.harnessGrants = [];
991
- } else if (selector.userId) {
992
- state.harnessGrants = state.harnessGrants.filter((g) => g.binding.userId !== selector.userId || selector.projectId !== void 0 && g.binding.projectId !== selector.projectId);
993
- } else if (selector.grantId) {
994
- state.harnessGrants = state.harnessGrants.filter(
995
- (g) => g.grantId !== selector.grantId
996
- );
997
- } else if (selector.binding) {
998
- const hash = hashGrantBinding(selector.binding);
999
- state.harnessGrants = state.harnessGrants.filter(
1000
- (g) => g.bindingHash !== hash
1172
+ async function renewHarnessBoxReservation(args) {
1173
+ let url;
1174
+ try {
1175
+ url = new URL(
1176
+ "/web/harness/model-broker/reserve/renew",
1177
+ getConvexHttpUrl()
1178
+ ).toString();
1179
+ } catch {
1180
+ return { ok: false };
1181
+ }
1182
+ try {
1183
+ const response = await fetch(url, {
1184
+ method: "POST",
1185
+ headers: {
1186
+ "content-type": "application/json",
1187
+ authorization: bearerHeader(args.bearer)
1188
+ },
1189
+ body: JSON.stringify({
1190
+ ...boxRequestFields(args.box),
1191
+ harnessId: args.harnessId,
1192
+ modelId: args.modelId,
1193
+ runId: args.runId
1194
+ }),
1195
+ signal: args.signal
1196
+ });
1197
+ const payload = await response.json().catch(() => null);
1198
+ if (!response.ok || payload?.ok !== true) {
1199
+ logger.error(
1200
+ `[harness-model-broker] reservation renewal returned ${response.status}`
1001
1201
  );
1202
+ return { ok: false };
1002
1203
  }
1003
- const removed = before - state.harnessGrants.length;
1004
- if (removed > 0) {
1005
- await writeState(state);
1006
- logger.info("[local-harness] consent revoked", { removed });
1007
- }
1008
- return removed;
1009
- });
1010
- }
1011
- function pruneExpiredHarnessGrants(now = Date.now()) {
1012
- return withGrantLock(async () => {
1013
- const state = await readState();
1014
- const before = state.harnessGrants.length;
1015
- state.harnessGrants = state.harnessGrants.filter(
1016
- (g) => Date.parse(g.expiresAt) > now
1204
+ return {
1205
+ ok: true,
1206
+ ...typeof payload.expiresAt === "number" ? { expiresAt: payload.expiresAt } : {}
1207
+ };
1208
+ } catch (err) {
1209
+ logger.error(
1210
+ "[harness-model-broker] reservation renewal network error",
1211
+ err
1017
1212
  );
1018
- const removed = before - state.harnessGrants.length;
1019
- if (removed > 0) await writeState(state);
1020
- return removed;
1021
- });
1213
+ return { ok: false };
1214
+ }
1022
1215
  }
1023
- function forgetWorkspaceGrant(workspaceGrantId) {
1024
- return withGrantLock(async () => {
1025
- const state = await readState();
1026
- state.workspaces = state.workspaces.filter((w) => w.workspaceGrantId !== workspaceGrantId);
1027
- state.harnessGrants = state.harnessGrants.filter((g) => g.binding.workspaceGrantId !== workspaceGrantId);
1028
- await writeState(state);
1029
- });
1216
+ async function releaseHarnessBoxReservation(args) {
1217
+ let url;
1218
+ try {
1219
+ url = new URL(
1220
+ "/web/harness/model-broker/reserve/release",
1221
+ getConvexHttpUrl()
1222
+ ).toString();
1223
+ } catch {
1224
+ return { ok: false };
1225
+ }
1226
+ try {
1227
+ const response = await fetch(url, {
1228
+ method: "POST",
1229
+ headers: {
1230
+ "content-type": "application/json",
1231
+ authorization: bearerHeader(args.bearer)
1232
+ },
1233
+ body: JSON.stringify({
1234
+ ...boxRequestFields(args.box),
1235
+ harnessId: args.harnessId,
1236
+ modelId: args.modelId,
1237
+ runId: args.runId
1238
+ }),
1239
+ signal: args.signal
1240
+ });
1241
+ if (!response.ok) {
1242
+ logger.warn(
1243
+ `[harness-model-broker] reservation release returned ${response.status}`
1244
+ );
1245
+ return { ok: false };
1246
+ }
1247
+ return { ok: true };
1248
+ } catch (err) {
1249
+ logger.error("[harness-model-broker] reservation release network error", err);
1250
+ return { ok: false };
1251
+ }
1030
1252
  }
1031
1253
 
1032
1254
  // server/utils/harness/local/availability.ts
@@ -1044,7 +1266,10 @@ function localHarnessManifestsForDevelopment(manifests = LOCAL_HARNESS_MANIFEST)
1044
1266
  return Object.fromEntries(
1045
1267
  Object.entries(manifests).map(([id, manifest]) => [
1046
1268
  id,
1047
- manifest.lifecycleConformanceVersion || id !== "claude-code" ? manifest : { ...manifest, lifecycleConformanceVersion: version }
1269
+ // Every harness the manifest names, not only Claude Code: an unpublished
1270
+ // Codex pack has to be exercisable through the same override before its
1271
+ // conformance is recorded. Development builds only (see above).
1272
+ manifest.lifecycleConformanceVersion ? manifest : { ...manifest, lifecycleConformanceVersion: version }
1048
1273
  ])
1049
1274
  );
1050
1275
  }
@@ -1100,6 +1325,9 @@ async function resolveLocalHarnessAvailability(query) {
1100
1325
  targetKind: target.kind,
1101
1326
  permissionProfile: target.permissionProfile,
1102
1327
  ...target.kind === "local-isolated" ? { backend: target.backend } : {},
1328
+ // The exact pack target, so a manifest certified per architecture (D8)
1329
+ // refuses an uncertified one rather than trusting the OS alone.
1330
+ packTarget: localPackTarget(platform),
1103
1331
  installedAdapterVersion: query.installedAdapterVersion
1104
1332
  },
1105
1333
  query.manifests ?? localHarnessManifestsForDevelopment()
@@ -1197,14 +1425,14 @@ function resolveNodeLauncher(opts) {
1197
1425
  // server/utils/harness/local/model-gateway.ts
1198
1426
  import { randomBytes, timingSafeEqual } from "crypto";
1199
1427
  import { execFile as execFile2 } from "child_process";
1200
- import { readdir as readdir2, readFile as readFile4, readlink as readlink2 } from "fs/promises";
1428
+ import { readdir as readdir2, readFile as readFile5, readlink as readlink2 } from "fs/promises";
1201
1429
  import {
1202
1430
  createServer as createServer2
1203
1431
  } from "http";
1204
1432
 
1205
1433
  // server/utils/harness/local/bridge-endpoint.ts
1206
1434
  import { execFile } from "child_process";
1207
- import { readdir, readFile as readFile2, readlink } from "fs/promises";
1435
+ import { readdir, readFile as readFile3, readlink } from "fs/promises";
1208
1436
  import { createConnection, createServer } from "net";
1209
1437
  import { networkInterfaces } from "os";
1210
1438
  var LOOPBACK_HOST_V4 = "127.0.0.1";
@@ -1399,7 +1627,7 @@ async function readLinuxListenAddresses(pid) {
1399
1627
  for (const table of ["/proc/net/tcp", "/proc/net/tcp6"]) {
1400
1628
  let raw;
1401
1629
  try {
1402
- raw = await readFile2(table, "utf8");
1630
+ raw = await readFile3(table, "utf8");
1403
1631
  } catch {
1404
1632
  continue;
1405
1633
  }
@@ -1455,8 +1683,8 @@ function isLoopbackBoundAddress(address) {
1455
1683
  }
1456
1684
  async function assertBridgeBindingIsLoopback(args) {
1457
1685
  const platform = args.platform ?? process.platform;
1458
- const read = args.read ?? readProcessListenAddresses;
1459
- const addresses = await read(args.pid, platform);
1686
+ const read2 = args.read ?? readProcessListenAddresses;
1687
+ const addresses = await read2(args.pid, platform);
1460
1688
  if (addresses === null) return;
1461
1689
  const offBox = addresses.filter(
1462
1690
  (address) => !isLoopbackBoundAddress(address)
@@ -1470,8 +1698,8 @@ async function assertBridgeBindingIsLoopback(args) {
1470
1698
 
1471
1699
  // server/utils/harness/local/instance-key.ts
1472
1700
  import { createHash, generateKeyPairSync, sign as edSign } from "crypto";
1473
- import { chmod as chmod2, mkdir as mkdir2, readFile as readFile3, stat as stat2, writeFile as writeFile2 } from "fs/promises";
1474
- import { join as join2 } from "path";
1701
+ import { chmod as chmod2, mkdir as mkdir2, readFile as readFile4, stat as stat2, writeFile as writeFile2 } from "fs/promises";
1702
+ import { join as join3 } from "path";
1475
1703
  var POP_SCHEME_PREFIX = "mcpjam-pop-v1";
1476
1704
  var KEY_FILE = "instance-key.json";
1477
1705
  var KeystoreUnavailableError = class extends Error {
@@ -1481,7 +1709,7 @@ var cached = null;
1481
1709
  var cachedKeyId = null;
1482
1710
  var loading = null;
1483
1711
  function keyFilePath() {
1484
- return join2(localHarnessStateRoot(), KEY_FILE);
1712
+ return join3(localHarnessStateRoot(), KEY_FILE);
1485
1713
  }
1486
1714
  function toBase64Url(bytes) {
1487
1715
  return bytes.toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, "");
@@ -1495,7 +1723,7 @@ async function loadLocalInstanceKey() {
1495
1723
  let stored = null;
1496
1724
  let fileExists = true;
1497
1725
  try {
1498
- stored = JSON.parse(await readFile3(path, "utf8"));
1726
+ stored = JSON.parse(await readFile4(path, "utf8"));
1499
1727
  } catch (error) {
1500
1728
  fileExists = error?.code !== "ENOENT";
1501
1729
  stored = null;
@@ -1569,7 +1797,7 @@ async function loadLocalInstanceKey() {
1569
1797
  }
1570
1798
  async function adoptExistingKey(path, machineId) {
1571
1799
  try {
1572
- const stored = JSON.parse(await readFile3(path, "utf8"));
1800
+ const stored = JSON.parse(await readFile4(path, "utf8"));
1573
1801
  return {
1574
1802
  machineId,
1575
1803
  publicKey: stored.publicKey,
@@ -1663,6 +1891,12 @@ var ALLOWED_PATHS = [
1663
1891
  { method: "POST", prefix: "/responses" }
1664
1892
  ];
1665
1893
  var HELLO_PROBE = { method: "HEAD", path: "/api/hello" };
1894
+ function proofOfPossessionPath(upstreamPathname) {
1895
+ const match = upstreamPathname.match(
1896
+ /\/web\/harness\/model-proxy\/[^/]+(\/.*)?$/
1897
+ );
1898
+ return match === null ? upstreamPathname : match[1] || "/";
1899
+ }
1666
1900
  async function startLocalModelGateway(options) {
1667
1901
  const sessionCapability = randomBytes(32).toString("base64url");
1668
1902
  const capabilityBytes = Buffer.from(sessionCapability, "utf8");
@@ -1672,7 +1906,9 @@ async function startLocalModelGateway(options) {
1672
1906
  "the harness model lease is not a token this gateway can bind a proof of possession to"
1673
1907
  );
1674
1908
  }
1675
- const jti = parsedJti;
1909
+ let jti = parsedJti;
1910
+ let lease = options.lease;
1911
+ let held = false;
1676
1912
  const upstream = new URL(options.upstreamBaseUrl);
1677
1913
  if (upstream.protocol !== "https:" && !isLoopbackHost(upstream.host)) {
1678
1914
  throw new Error(
@@ -1730,6 +1966,10 @@ async function startLocalModelGateway(options) {
1730
1966
  refuse(res, 401, "session ended");
1731
1967
  return;
1732
1968
  }
1969
+ if (held) {
1970
+ refuse(res, 503, "session paused awaiting approval");
1971
+ return;
1972
+ }
1733
1973
  if (!isAllowedPath(method, path)) {
1734
1974
  refuse(res, 404, "endpoint not allowed");
1735
1975
  return;
@@ -1757,7 +1997,7 @@ async function startLocalModelGateway(options) {
1757
1997
  }
1758
1998
  const pop = await signProxiedRequest({
1759
1999
  method,
1760
- path: stripQuery(target.pathname),
2000
+ path: proofOfPossessionPath(stripQuery(target.pathname)),
1761
2001
  jti,
1762
2002
  nonce: randomBytes(16).toString("base64url")
1763
2003
  });
@@ -1770,8 +2010,8 @@ async function startLocalModelGateway(options) {
1770
2010
  // and the two that matter here are ours to set.
1771
2011
  "content-type": "application/json",
1772
2012
  accept: String(req.headers.accept ?? "application/json"),
1773
- authorization: `Bearer ${options.lease}`,
1774
- "x-mcpjam-harness-lease": options.lease,
2013
+ authorization: `Bearer ${lease}`,
2014
+ "x-mcpjam-harness-lease": lease,
1775
2015
  "x-mcpjam-pop": pop,
1776
2016
  ...typeof req.headers["anthropic-version"] === "string" ? { "anthropic-version": req.headers["anthropic-version"] } : {},
1777
2017
  ...typeof req.headers["anthropic-beta"] === "string" ? { "anthropic-beta": req.headers["anthropic-beta"] } : {}
@@ -1847,6 +2087,20 @@ async function startLocalModelGateway(options) {
1847
2087
  revoke: () => {
1848
2088
  revoked = true;
1849
2089
  },
2090
+ hold: () => {
2091
+ held = true;
2092
+ },
2093
+ rebind: (nextLease) => {
2094
+ const nextJti = leaseJti(nextLease);
2095
+ if (nextJti === null) {
2096
+ throw new Error(
2097
+ "the renewed harness model lease is not a token this gateway can bind a proof of possession to"
2098
+ );
2099
+ }
2100
+ lease = nextLease;
2101
+ jti = nextJti;
2102
+ held = false;
2103
+ },
1850
2104
  close: async () => {
1851
2105
  revoked = true;
1852
2106
  await closeServer(server);
@@ -1980,19 +2234,199 @@ async function findLocalSocketInode(port) {
1980
2234
  for (const table of ["/proc/net/tcp", "/proc/net/tcp6"]) {
1981
2235
  let raw;
1982
2236
  try {
1983
- raw = await readFile4(table, "utf8");
2237
+ raw = await readFile5(table, "utf8");
1984
2238
  } catch {
1985
2239
  continue;
1986
2240
  }
1987
- for (const line of raw.split("\n").slice(1)) {
1988
- const fields = line.trim().split(/\s+/);
1989
- if (fields.length < 10) continue;
1990
- const local = fields[1] ?? "";
1991
- if (!local.endsWith(`:${hexPort}`)) continue;
1992
- return fields[9] ?? null;
2241
+ for (const line of raw.split("\n").slice(1)) {
2242
+ const fields = line.trim().split(/\s+/);
2243
+ if (fields.length < 10) continue;
2244
+ const local = fields[1] ?? "";
2245
+ if (!local.endsWith(`:${hexPort}`)) continue;
2246
+ return fields[9] ?? null;
2247
+ }
2248
+ }
2249
+ return null;
2250
+ }
2251
+
2252
+ // server/utils/harness/local/approval-park.ts
2253
+ var DEFAULT_APPROVAL_PARK_TTL_MS = 30 * 60 * 1e3;
2254
+ var realClock = {
2255
+ now: () => Date.now(),
2256
+ setTimer: (fn, ms) => {
2257
+ const timer = setTimeout(fn, ms);
2258
+ timer.unref?.();
2259
+ return timer;
2260
+ },
2261
+ clearTimer: (timer) => clearTimeout(timer)
2262
+ };
2263
+ var clock = realClock;
2264
+ var parked = /* @__PURE__ */ new Map();
2265
+ function parkLocalSession(args) {
2266
+ if (args.pendingApprovalIds.length === 0) {
2267
+ throw new Error("a parked session must be waiting on at least one approval");
2268
+ }
2269
+ const existing = parked.get(args.sessionId);
2270
+ if (existing && existing.generation !== args.generation) {
2271
+ if (existing.timer) clock.clearTimer(existing.timer);
2272
+ parked.delete(args.sessionId);
2273
+ } else if (existing?.state === "terminal") {
2274
+ return false;
2275
+ }
2276
+ const prior = parked.get(args.sessionId);
2277
+ const now = clock.now();
2278
+ const ttl = args.ttlMs ?? DEFAULT_APPROVAL_PARK_TTL_MS;
2279
+ if (prior?.timer) clock.clearTimer(prior.timer);
2280
+ args.holdModelTraffic();
2281
+ const entry = {
2282
+ sessionId: args.sessionId,
2283
+ generation: args.generation,
2284
+ userId: args.userId,
2285
+ projectId: args.projectId,
2286
+ state: "awaiting-approval",
2287
+ pending: new Set(args.pendingApprovalIds),
2288
+ // Carried across re-parks: an id decided in an earlier pause of the same
2289
+ // process can never be replayed against this one.
2290
+ consumed: new Set(prior?.consumed ?? []),
2291
+ parkedAt: now,
2292
+ expiresAt: now + ttl,
2293
+ resources: args.resources,
2294
+ end: args.end,
2295
+ isAlive: args.isAlive,
2296
+ holdModelTraffic: args.holdModelTraffic,
2297
+ timer: null
2298
+ };
2299
+ for (const id of entry.pending) {
2300
+ if (entry.consumed.has(id)) {
2301
+ throw new Error(`approval ${id} was already decided in this session`);
2302
+ }
2303
+ }
2304
+ entry.timer = clock.setTimer(() => {
2305
+ void invalidateParkedLocalSession(args.sessionId, "idle-expired");
2306
+ }, ttl);
2307
+ parked.set(args.sessionId, entry);
2308
+ logger.info("[local-harness] session parked awaiting approval", {
2309
+ sessionId: args.sessionId,
2310
+ pending: entry.pending.size,
2311
+ ttlMs: ttl
2312
+ });
2313
+ return true;
2314
+ }
2315
+ function claimParkedLocalSession(args) {
2316
+ const entry = parked.get(args.sessionId);
2317
+ if (entry === void 0) {
2318
+ return refusal(
2319
+ "absent",
2320
+ "The local session holding this approval has ended, so the decision cannot be applied. Start a new turn; any action proposed then will ask for approval again."
2321
+ );
2322
+ }
2323
+ if (entry.state === "terminal") {
2324
+ return refusal(
2325
+ "terminal",
2326
+ `The local session holding this approval ended (${entry.invalidatedBy ?? "stopped"}). Start a new turn; any action proposed then will ask for approval again.`
2327
+ );
2328
+ }
2329
+ if (entry.userId !== args.userId || entry.projectId !== args.projectId) {
2330
+ return refusal(
2331
+ "actor-mismatch",
2332
+ "This approval belongs to a different user or project."
2333
+ );
2334
+ }
2335
+ if (entry.generation !== args.generation) {
2336
+ return refusal(
2337
+ "generation-mismatch",
2338
+ "This approval was asked by an earlier run of the local runtime, which has since restarted. It cannot approve anything the new run proposes."
2339
+ );
2340
+ }
2341
+ if (args.approvalIds.length === 0) {
2342
+ return refusal("no-decision", "The continuation carried no approval decision.");
2343
+ }
2344
+ for (const id of args.approvalIds) {
2345
+ if (entry.consumed.has(id)) {
2346
+ return refusal(
2347
+ "duplicate-approval",
2348
+ "This approval was already answered; the action will not run twice."
2349
+ );
2350
+ }
2351
+ }
2352
+ if (entry.state !== "awaiting-approval") {
2353
+ return refusal(
2354
+ "not-awaiting",
2355
+ "This approval is already being continued."
2356
+ );
2357
+ }
2358
+ for (const id of args.approvalIds) {
2359
+ if (!entry.pending.has(id)) {
2360
+ return refusal(
2361
+ "stale-approval",
2362
+ "That decision answers an approval this session is not waiting on."
2363
+ );
1993
2364
  }
1994
2365
  }
1995
- return null;
2366
+ if (!entry.isAlive()) {
2367
+ void invalidateParkedLocalSession(args.sessionId, "process-died");
2368
+ return refusal(
2369
+ "process-died",
2370
+ "The local runtime holding this approval stopped. Its pending action will not run; start a new turn to continue the conversation."
2371
+ );
2372
+ }
2373
+ if (entry.timer) clock.clearTimer(entry.timer);
2374
+ entry.timer = null;
2375
+ entry.state = "continuing";
2376
+ for (const id of args.approvalIds) {
2377
+ entry.consumed.add(id);
2378
+ entry.pending.delete(id);
2379
+ }
2380
+ return { ok: true, parked: entry };
2381
+ }
2382
+ function releaseParkedLocalSession(sessionId) {
2383
+ const entry = parked.get(sessionId);
2384
+ if (entry === void 0) return;
2385
+ if (entry.timer) clock.clearTimer(entry.timer);
2386
+ parked.delete(sessionId);
2387
+ }
2388
+ var TOMBSTONE_TTL_MS = 6e4;
2389
+ function expireTombstone(sessionId, entry) {
2390
+ entry.timer = clock.setTimer(() => {
2391
+ if (parked.get(sessionId) === entry) parked.delete(sessionId);
2392
+ }, TOMBSTONE_TTL_MS);
2393
+ }
2394
+ async function invalidateParkedLocalSession(sessionId, reason) {
2395
+ const entry = parked.get(sessionId);
2396
+ if (entry === void 0 || entry.state === "terminal") return;
2397
+ entry.state = "terminal";
2398
+ entry.invalidatedBy = reason;
2399
+ entry.pending.clear();
2400
+ if (entry.timer) clock.clearTimer(entry.timer);
2401
+ entry.timer = null;
2402
+ logger.info("[local-harness] parked session ended", { sessionId, reason });
2403
+ try {
2404
+ await entry.end(reason);
2405
+ } catch (error) {
2406
+ logger.warn("[local-harness] parked session teardown failed", {
2407
+ sessionId,
2408
+ reason,
2409
+ message: error instanceof Error ? error.message : String(error)
2410
+ });
2411
+ } finally {
2412
+ if (parked.get(sessionId) === entry) expireTombstone(sessionId, entry);
2413
+ }
2414
+ }
2415
+ function noteParkedLocalSessionEnded(sessionId) {
2416
+ const entry = parked.get(sessionId);
2417
+ if (entry === void 0 || entry.state === "terminal") return;
2418
+ entry.state = "terminal";
2419
+ entry.invalidatedBy = "stopped";
2420
+ entry.pending.clear();
2421
+ if (entry.timer) clock.clearTimer(entry.timer);
2422
+ expireTombstone(sessionId, entry);
2423
+ }
2424
+ function hasParkedLocalSession(sessionId) {
2425
+ const entry = parked.get(sessionId);
2426
+ return entry !== void 0 && entry.state !== "terminal";
2427
+ }
2428
+ function refusal(reason, message) {
2429
+ return { ok: false, reason, message };
1996
2430
  }
1997
2431
 
1998
2432
  // server/utils/harness/local/supervised-provider.ts
@@ -2012,7 +2446,7 @@ import {
2012
2446
  basename,
2013
2447
  dirname as dirname2,
2014
2448
  isAbsolute as isAbsolute3,
2015
- join as join3,
2449
+ join as join4,
2016
2450
  posix as posix4,
2017
2451
  resolve as resolve2,
2018
2452
  sep as sep4
@@ -2473,7 +2907,7 @@ function matchBootstrapInstall(command, ctx) {
2473
2907
  reason: "vendor dependency graph is supplied by the digest-verified managed runtime bundle; no package manager runs during a session"
2474
2908
  };
2475
2909
  }
2476
- if (ctx.harnessId === "claude-code" && command === "./node_modules/.bin/claude --version") {
2910
+ if (ctx.harnessId === "claude-code" && command === "./node_modules/.bin/claude --version" || ctx.harnessId === "codex" && command === "node node_modules/@openai/codex/bin/codex.js --version") {
2477
2911
  return {
2478
2912
  kind: "noop",
2479
2913
  reason: "vendor CLI is installed and version-verified in the managed runtime bundle at build time; the session does not re-run its version probe"
@@ -2486,7 +2920,12 @@ async function matchBridgeLaunch(command, ctx) {
2486
2920
  const tokens = splitQuotedTokens(command.slice("node ".length), command);
2487
2921
  const expected = {
2488
2922
  "claude-code": ["--workdir", "--bridge-state-dir"],
2489
- codex: ["--workdir", "--bridge-state-dir", "--cli-shim-dir"]
2923
+ codex: [
2924
+ "--workdir",
2925
+ "--bridge-state-dir",
2926
+ "--session-data-dir",
2927
+ "--bootstrap-dir"
2928
+ ]
2490
2929
  };
2491
2930
  const flags = expected[ctx.harnessId];
2492
2931
  if (tokens.length !== 1 + flags.length * 2) {
@@ -2517,6 +2956,20 @@ async function matchBridgeLaunch(command, ctx) {
2517
2956
  );
2518
2957
  }
2519
2958
  assertPlainPathOperand(value, command);
2959
+ if (flag === "--bootstrap-dir") {
2960
+ if (posix2.normalize(value) !== posix2.normalize(ctx.adapterBootstrapDir)) {
2961
+ throw new CommandTranslationError(
2962
+ `--bootstrap-dir names ${JSON.stringify(value)}, but the only bootstrap this session may load is its managed bundle`,
2963
+ command
2964
+ );
2965
+ }
2966
+ args.push(flag, remapBootstrapPath(value, ctx));
2967
+ continue;
2968
+ }
2969
+ if (ctx.harnessId === "codex" && (flag === "--bridge-state-dir" || flag === "--session-data-dir")) {
2970
+ args.push(flag, await (ctx.confineToSessionState ?? ctx.confine)(value));
2971
+ continue;
2972
+ }
2520
2973
  args.push(flag, await ctx.confine(value));
2521
2974
  }
2522
2975
  assertArgvAllowed(args);
@@ -2663,7 +3116,11 @@ var SCOPED_NAME_DENYLIST = /* @__PURE__ */ new Set([
2663
3116
  // Names the shell the vendor CLI runs commands through. A scoped override
2664
3117
  // would point it at any executable; the provider sets it from a path it
2665
3118
  // has verified exists.
2666
- "CLAUDE_CODE_GIT_BASH_PATH"
3119
+ "CLAUDE_CODE_GIT_BASH_PATH",
3120
+ // Codex's config root. The bridge renders a per-session CODEX_HOME (auth,
3121
+ // model provider, the relay's MCP server); an injected one would point Codex
3122
+ // back at a user's real `~/.codex` — its servers, its credentials.
3123
+ "CODEX_HOME"
2667
3124
  ]);
2668
3125
  var LocalHarnessEnvError = class extends Error {
2669
3126
  };
@@ -2742,10 +3199,21 @@ function validateLocalHarnessScopedEnv(scoped) {
2742
3199
  }
2743
3200
  }
2744
3201
  }
2745
- function validateLocalHarnessSecretEnv(scoped) {
3202
+ var RUNTIME_RESERVED_SECRET_PREFIXES = {
3203
+ "claude-code": /^(ANTHROPIC_|AI_GATEWAY_|BRIDGE_|CLAUDE_CODE_)/i,
3204
+ codex: /^(CODEX_|OPENAI_|AI_GATEWAY_|BRIDGE_)/i
3205
+ };
3206
+ function validateLocalHarnessSecretEnv(scoped, harnessId = "claude-code") {
2746
3207
  validateLocalHarnessScopedEnv(scoped);
3208
+ const reserved = Object.prototype.hasOwnProperty.call(
3209
+ RUNTIME_RESERVED_SECRET_PREFIXES,
3210
+ harnessId
3211
+ ) ? RUNTIME_RESERVED_SECRET_PREFIXES[harnessId] : (
3212
+ // An unknown harness gets the union, never nothing.
3213
+ /^(ANTHROPIC_|AI_GATEWAY_|BRIDGE_|CLAUDE_CODE_|CODEX_|OPENAI_)/i
3214
+ );
2747
3215
  for (const name of Object.keys(scoped)) {
2748
- if (/^(ANTHROPIC_|AI_GATEWAY_|BRIDGE_|CLAUDE_CODE_)/i.test(name)) {
3216
+ if (reserved.test(name)) {
2749
3217
  throw new LocalHarnessEnvError(
2750
3218
  `Project secret ${name} conflicts with the local harness runtime.`
2751
3219
  );
@@ -2956,7 +3424,7 @@ async function writeBytesAtomically(path, bytes, abortSignal) {
2956
3424
  } catch (error) {
2957
3425
  if (error.code !== "ENOENT") throw error;
2958
3426
  }
2959
- const temp = join3(parent, `.${basename(path)}.${randomUUID2()}.tmp`);
3427
+ const temp = join4(parent, `.${basename(path)}.${randomUUID2()}.tmp`);
2960
3428
  const handle = await open(temp, "wx", mode);
2961
3429
  let closed = false;
2962
3430
  try {
@@ -2982,7 +3450,7 @@ async function resolveGitBashPath(platform) {
2982
3450
  const configured = process.env.CLAUDE_CODE_GIT_BASH_PATH;
2983
3451
  const candidates = [
2984
3452
  ...configured && isAbsolute3(configured) ? [configured] : [],
2985
- join3(
3453
+ join4(
2986
3454
  process.env.ProgramFiles ?? "C:\\Program Files",
2987
3455
  "Git",
2988
3456
  "bin",
@@ -3049,9 +3517,9 @@ function createSupervisedLocalHarnessProvider(opts) {
3049
3517
  );
3050
3518
  }
3051
3519
  };
3052
- const syntheticHome = join3(opts.sessionStateDir, "home");
3053
- const bootstrapOverlay = join3(opts.sessionStateDir, "bootstrap");
3054
- const workRoot = join3(opts.sessionStateDir, "work");
3520
+ const syntheticHome = join4(opts.sessionStateDir, "home");
3521
+ const bootstrapOverlay = join4(opts.sessionStateDir, "bootstrap");
3522
+ const workRoot = join4(opts.sessionStateDir, "work");
3055
3523
  const WORKSPACE_LINK_NAME = "project";
3056
3524
  const platform = opts.platform ?? process.platform;
3057
3525
  const adapterWorkRoot = toAdapterPath(workRoot, platform);
@@ -3069,7 +3537,7 @@ function createSupervisedLocalHarnessProvider(opts) {
3069
3537
  }
3070
3538
  await mkdir3(bootstrapOverlay, { recursive: true, mode: 448 });
3071
3539
  await mkdir3(workRoot, { recursive: true, mode: 448 });
3072
- const workspaceLink = join3(workRoot, WORKSPACE_LINK_NAME);
3540
+ const workspaceLink = join4(workRoot, WORKSPACE_LINK_NAME);
3073
3541
  try {
3074
3542
  const existing = await lstat2(workspaceLink);
3075
3543
  if (!existing.isSymbolicLink()) {
@@ -3096,7 +3564,8 @@ function createSupervisedLocalHarnessProvider(opts) {
3096
3564
  }
3097
3565
  const roots = [await realpath3(opts.sessionStateDir), opts.workspacePath];
3098
3566
  const confine = (path) => confinePath(fromAdapterPath(path, platform), { roots });
3099
- const gitBashPath = await resolveGitBashPath(platform);
3567
+ const confineToSessionState = (path) => confinePath(fromAdapterPath(path, platform), { roots: [roots[0]] });
3568
+ const gitBashPath = opts.harnessId === "claude-code" ? await resolveGitBashPath(platform) : void 0;
3100
3569
  const env = {
3101
3570
  ...buildLocalHarnessEnv({
3102
3571
  syntheticHome,
@@ -3132,7 +3601,8 @@ function createSupervisedLocalHarnessProvider(opts) {
3132
3601
  // `--workdir` and `--bridge-state-dir`, which nothing downstream would
3133
3602
  // otherwise check: they are consumed by the child, not by a filesystem
3134
3603
  // call we make.
3135
- confine
3604
+ confine,
3605
+ confineToSessionState
3136
3606
  };
3137
3607
  const resolveForRead = async (path) => {
3138
3608
  const target = classifyBootstrapPath(path, translationContext);
@@ -3530,7 +4000,7 @@ function sessionStateDirFor(stateRoot, sessionId) {
3530
4000
  )} is not a single safe path segment`
3531
4001
  );
3532
4002
  }
3533
- return join3(`${stateRoot}-sessions`, sessionId);
4003
+ return join4(`${stateRoot}-sessions`, sessionId);
3534
4004
  }
3535
4005
 
3536
4006
  // server/utils/harness/local/supervisor.ts
@@ -3542,15 +4012,15 @@ import { isAbsolute as isAbsolute4 } from "path";
3542
4012
  import { randomUUID as randomUUID3 } from "crypto";
3543
4013
  import {
3544
4014
  mkdir as mkdir4,
3545
- readFile as readFile5,
4015
+ readFile as readFile6,
3546
4016
  rename as rename3,
3547
4017
  writeFile as writeFile3,
3548
4018
  chmod as chmod3,
3549
4019
  rm as rm2
3550
4020
  } from "fs/promises";
3551
- import { join as join4, resolve as resolve3, sep as sep5 } from "path";
4021
+ import { join as join5, resolve as resolve3, sep as sep5 } from "path";
3552
4022
  function registryPath() {
3553
- return join4(localHarnessStateRoot(), "processes.json");
4023
+ return join5(localHarnessStateRoot(), "processes.json");
3554
4024
  }
3555
4025
  var withRegistryLock = createLocalStateMutationLock({
3556
4026
  rootDir: localHarnessStateRoot,
@@ -3562,7 +4032,7 @@ var RegistryUnreadableError = class extends Error {
3562
4032
  async function readRegistry() {
3563
4033
  let raw;
3564
4034
  try {
3565
- raw = await readFile5(registryPath(), "utf8");
4035
+ raw = await readFile6(registryPath(), "utf8");
3566
4036
  } catch (error) {
3567
4037
  if (error.code === "ENOENT") {
3568
4038
  return { version: 1, records: [] };
@@ -3597,10 +4067,10 @@ async function writeRegistry(registry) {
3597
4067
  await mkdir4(dir, { recursive: true, mode: 448 });
3598
4068
  await chmod3(dir, 448).catch(() => {
3599
4069
  });
3600
- const file = registryPath();
3601
- const tmp = `${file}.tmp`;
4070
+ const file2 = registryPath();
4071
+ const tmp = `${file2}.tmp`;
3602
4072
  await writeFile3(tmp, JSON.stringify(registry), { mode: 384 });
3603
- await rename3(tmp, file);
4073
+ await rename3(tmp, file2);
3604
4074
  }
3605
4075
  function mintSupervisorNonce() {
3606
4076
  return `sup_${randomUUID3()}`;
@@ -4343,116 +4813,8 @@ var LocalHarnessSupervisor = class {
4343
4813
  }
4344
4814
  };
4345
4815
 
4346
- // server/utils/harness/local/session-registry.ts
4347
- var sessions = /* @__PURE__ */ new Map();
4348
- var unstopped = /* @__PURE__ */ new Set();
4349
- function registerLocalHarnessSession(record) {
4350
- sessions.set(record.sessionId, record);
4351
- }
4352
- function getLocalHarnessSession(sessionId) {
4353
- return sessions.get(sessionId);
4354
- }
4355
- function forgetLocalHarnessSession(sessionId) {
4356
- sessions.delete(sessionId);
4357
- }
4358
- function forgetLocalHarnessSessionRecord(record) {
4359
- unstopped.delete(record);
4360
- if (sessions.get(record.sessionId) !== record) return false;
4361
- sessions.delete(record.sessionId);
4362
- return true;
4363
- }
4364
- function claimRecord(record) {
4365
- const claimed = sessions.get(record.sessionId) === record || unstopped.has(record);
4366
- if (!claimed) return false;
4367
- if (sessions.get(record.sessionId) === record) {
4368
- sessions.delete(record.sessionId);
4369
- }
4370
- unstopped.delete(record);
4371
- return true;
4372
- }
4373
- async function endRecord(record) {
4374
- const sessionId = record.sessionId;
4375
- const errors = [];
4376
- try {
4377
- record.gateway?.revoke();
4378
- } catch (error) {
4379
- errors.push(`gateway revoke: ${messageOf(error)}`);
4380
- }
4381
- try {
4382
- await record.gateway?.close();
4383
- } catch (error) {
4384
- errors.push(`gateway close: ${messageOf(error)}`);
4385
- }
4386
- try {
4387
- await record.revokeLease?.();
4388
- } catch (error) {
4389
- errors.push(`lease revoke: ${messageOf(error)}`);
4390
- }
4391
- let stopped = true;
4392
- try {
4393
- const outcome = await record.stop();
4394
- if (outcome?.stopped !== true) {
4395
- stopped = false;
4396
- errors.push(
4397
- `stop: ${outcome?.escaped ?? "some"} process(es) escaped the session`
4398
- );
4399
- }
4400
- } catch (error) {
4401
- stopped = false;
4402
- errors.push(`stop: ${messageOf(error)}`);
4403
- }
4404
- if (stopped) {
4405
- unstopped.delete(record);
4406
- try {
4407
- await record.releaseRuntime?.();
4408
- } catch (error) {
4409
- errors.push(`runtime release: ${messageOf(error)}`);
4410
- }
4411
- } else {
4412
- unstopped.add(record);
4413
- if (!sessions.has(sessionId)) sessions.set(sessionId, record);
4414
- }
4415
- if (errors.length > 0) {
4416
- logger.warn("[local-harness] session teardown had failures", {
4417
- sessionId,
4418
- errors
4419
- });
4420
- }
4421
- return { stopped, errors };
4422
- }
4423
- async function stopAllLocalHarnessSessions() {
4424
- const candidates = [.../* @__PURE__ */ new Set([...sessions.values(), ...unstopped])];
4425
- const mine = candidates.filter(claimRecord);
4426
- const results = await Promise.all(
4427
- mine.map(
4428
- (record) => endRecord(record).catch(() => ({
4429
- stopped: false,
4430
- errors: ["unexpected"]
4431
- }))
4432
- )
4433
- );
4434
- const failed = results.filter((result) => !result.stopped).length;
4435
- return { ok: failed === 0, stopped: results.length - failed, failed };
4436
- }
4437
- function messageOf(error) {
4438
- return error instanceof Error ? error.message : String(error);
4439
- }
4440
- async function stopLocalHarnessWorkspace(workspaceGrantId) {
4441
- const records = new Set([...sessions.values(), ...unstopped].filter((record) => record.workspaceGrantId === workspaceGrantId));
4442
- let stopped = true;
4443
- for (const record of records) {
4444
- if (claimRecord(record)) stopped = (await endRecord(record)).stopped && stopped;
4445
- else stopped = false;
4446
- }
4447
- return stopped;
4448
- }
4449
- async function stopLocalHarnessProject(userId, projectId) {
4450
- const records = new Set([...sessions.values(), ...unstopped].filter((record) => record.userId === userId && (projectId === void 0 || record.projectId === projectId)));
4451
- await Promise.all([...records].filter(claimRecord).map(endRecord));
4452
- }
4453
-
4454
4816
  // server/utils/harness/local/local-turn.ts
4455
- import { join as join5 } from "path";
4817
+ import { join as join6 } from "path";
4456
4818
  import { mkdir as mkdir6, stat as stat4 } from "fs/promises";
4457
4819
  import { createRequire } from "module";
4458
4820
  var sharedSupervisor = null;
@@ -4460,23 +4822,68 @@ function localHarnessSupervisor() {
4460
4822
  sharedSupervisor ??= new LocalHarnessSupervisor();
4461
4823
  return sharedSupervisor;
4462
4824
  }
4825
+ var LOCAL_HARNESS_DISPLAY_NAME = {
4826
+ "claude-code": "Claude Code",
4827
+ codex: "Codex"
4828
+ };
4829
+ function asLocalHarnessId(harnessId) {
4830
+ return SUPPORTED_LOCAL_HARNESS_IDS.includes(harnessId) ? harnessId : null;
4831
+ }
4832
+ function localChildAuth(harnessId, gateway) {
4833
+ switch (harnessId) {
4834
+ case "claude-code":
4835
+ return {
4836
+ ANTHROPIC_AUTH_TOKEN: gateway.sessionCapability,
4837
+ ANTHROPIC_API_KEY: gateway.sessionCapability,
4838
+ ANTHROPIC_BASE_URL: gateway.baseUrl
4839
+ };
4840
+ case "codex":
4841
+ return {
4842
+ CODEX_API_KEY: gateway.sessionCapability,
4843
+ OPENAI_BASE_URL: gateway.baseUrl
4844
+ };
4845
+ }
4846
+ }
4847
+ var LOCAL_SKILLS_SUBDIR = {
4848
+ "claude-code": [".claude", "skills"],
4849
+ codex: [".agents", "skills"]
4850
+ };
4463
4851
  async function prepareLocalHarnessTurn(args) {
4464
- validateLocalHarnessSecretEnv(args.scopedEnv ?? {});
4852
+ const harnessId = asLocalHarnessId(args.harnessId);
4853
+ if (harnessId === null) {
4854
+ return {
4855
+ ok: false,
4856
+ status: "harness-not-supported",
4857
+ message: `${args.harnessId} cannot run on this machine.`
4858
+ };
4859
+ }
4860
+ validateLocalHarnessSecretEnv(args.scopedEnv ?? {}, harnessId);
4861
+ const displayName = LOCAL_HARNESS_DISPLAY_NAME[harnessId];
4862
+ if (args.approvalContinuation) {
4863
+ return adoptParkedLocalTurn(args, harnessId);
4864
+ }
4865
+ if (hasParkedLocalSession(args.sessionId)) {
4866
+ await invalidateParkedLocalSession(args.sessionId, "superseded");
4867
+ }
4868
+ if (args.scope !== "unattended" && args.requireToolApproval === false) {
4869
+ const authorization2 = await readLocalHarnessAuthorization(args.target.actingUserId, args.target.machineId, args.projectId, harnessId);
4870
+ if (!authorization2?.autoApproveAcknowledgedAt) {
4871
+ return { ok: false, status: "auto-approve-consent-required", message: "Allow commands without asking before turning Tool Approval off on this computer." };
4872
+ }
4873
+ }
4465
4874
  const verifyStartedAt = Date.now();
4466
- const runtimeStatus = await readRuntimeInstallStatus({
4467
- harnessId: "claude-code"
4468
- });
4875
+ const runtimeStatus = await readRuntimeInstallStatus({ harnessId });
4469
4876
  if (runtimeStatus.state !== "ready") {
4470
4877
  return {
4471
4878
  ok: false,
4472
4879
  status: "runtime-unavailable",
4473
- message: runtimeStatus.state === "absent" ? "The local Claude Code runtime is not installed on this machine yet." : `The local Claude Code runtime is not usable (${runtimeStatus.state}).`
4880
+ message: runtimeStatus.state === "absent" ? `The local ${displayName} runtime is not installed on this machine yet.` : `The local ${displayName} runtime is not usable (${runtimeStatus.state}).`
4474
4881
  };
4475
4882
  }
4476
4883
  const target = localPackTarget();
4477
4884
  const lifecycleKey = target === null ? null : {
4478
4885
  runtimeRoot: runtimeInstallRoot(),
4479
- harnessId: "claude-code",
4886
+ harnessId,
4480
4887
  target,
4481
4888
  packVersion: runtimeStatus.packVersion,
4482
4889
  treeDigest: runtimeStatus.digest
@@ -4505,6 +4912,7 @@ async function prepareLocalHarnessTurn(args) {
4505
4912
  try {
4506
4913
  const prepared = await prepareWithReservedRuntime({
4507
4914
  args,
4915
+ harnessId,
4508
4916
  runtimeStatus,
4509
4917
  verifyStartedAt,
4510
4918
  releaseRuntimeUse
@@ -4518,6 +4926,7 @@ async function prepareLocalHarnessTurn(args) {
4518
4926
  }
4519
4927
  async function prepareWithReservedRuntime(outer) {
4520
4928
  const args = outer.args;
4929
+ const harnessId = outer.harnessId;
4521
4930
  const runtimeStatus = outer.runtimeStatus;
4522
4931
  const verifyStartedAt = outer.verifyStartedAt;
4523
4932
  const sessionStateDir = sessionStateDirFor(
@@ -4534,7 +4943,7 @@ async function prepareWithReservedRuntime(outer) {
4534
4943
  const availability = await resolveLocalHarnessAvailability({
4535
4944
  target: {
4536
4945
  kind: "local-native",
4537
- harnessId: args.harnessId,
4946
+ harnessId,
4538
4947
  machineId: args.target.machineId,
4539
4948
  workspaceGrantId: args.target.workspaceGrantId,
4540
4949
  runtimeId: args.target.runtimeId,
@@ -4549,7 +4958,7 @@ async function prepareWithReservedRuntime(outer) {
4549
4958
  projectId: args.projectId,
4550
4959
  grantToken: args.target.grantToken,
4551
4960
  runtimeRoot: runtimeStatus.runtimeRoot,
4552
- installedAdapterVersion: args.installedAdapterVersion ?? await readInstalledAdapterVersion()
4961
+ installedAdapterVersion: args.installedAdapterVersion ?? await readInstalledAdapterVersion(harnessId)
4553
4962
  });
4554
4963
  if (!availability.available) {
4555
4964
  return {
@@ -4560,7 +4969,7 @@ async function prepareWithReservedRuntime(outer) {
4560
4969
  }
4561
4970
  const plan = availability.plan;
4562
4971
  const localRuntimeVerifyMs = Date.now() - verifyStartedAt;
4563
- const permissionMode = args.requireToolApproval ? "allow-reads" : plan.permissionMode;
4972
+ const permissionMode = args.scope !== "unattended" || args.requireToolApproval ? "allow-reads" : plan.permissionMode;
4564
4973
  const identity = await readLocalInstanceIdentity();
4565
4974
  const keyId = identity.keyId ?? getRegisteredKeyId();
4566
4975
  if (keyId === null) {
@@ -4583,6 +4992,7 @@ async function prepareWithReservedRuntime(outer) {
4583
4992
  keyId,
4584
4993
  runId: args.runId,
4585
4994
  ...args.maxOutputTokens !== void 0 ? { maxOutputTokens: args.maxOutputTokens } : {},
4995
+ ...args.reasoningEffort ? { reasoningEffort: args.reasoningEffort } : {},
4586
4996
  bearer: args.bearer,
4587
4997
  ...args.signal ? { signal: args.signal } : {}
4588
4998
  });
@@ -4595,13 +5005,14 @@ async function prepareWithReservedRuntime(outer) {
4595
5005
  }
4596
5006
  const supervisor = localHarnessSupervisor();
4597
5007
  let gateway = null;
5008
+ let currentRunId = broker.runId;
4598
5009
  try {
4599
5010
  const sessionStateExists = await stat4(sessionStateDir).then((entry) => entry.isDirectory()).catch((error) => {
4600
5011
  if (error.code === "ENOENT") return false;
4601
5012
  throw error;
4602
5013
  });
4603
5014
  await mkdir6(sessionStateDir, { recursive: true, mode: 448 });
4604
- const hooksPath = join5(sessionStateDir, "empty-git-hooks");
5015
+ const hooksPath = join6(sessionStateDir, "empty-git-hooks");
4605
5016
  if (args.scope === "unattended") await mkdir6(hooksPath, { recursive: true, mode: 448 });
4606
5017
  const gatewayStartedAt = Date.now();
4607
5018
  try {
@@ -4631,7 +5042,7 @@ async function prepareWithReservedRuntime(outer) {
4631
5042
  bundledNodePath: plan.runtime.nodePath ?? ""
4632
5043
  });
4633
5044
  const sandbox = createSupervisedLocalHarnessProvider({
4634
- harnessId: "claude-code",
5045
+ harnessId,
4635
5046
  manifest: plan.manifest,
4636
5047
  runtime: plan.runtime,
4637
5048
  supervisor,
@@ -4651,6 +5062,7 @@ async function prepareWithReservedRuntime(outer) {
4651
5062
  ...args.scope === "unattended" ? { GIT_CONFIG_NOSYSTEM: "1", GIT_TERMINAL_PROMPT: "0", GCM_INTERACTIVE: "never", GIT_CONFIG_COUNT: "2", GIT_CONFIG_KEY_0: "core.hooksPath", GIT_CONFIG_VALUE_0: hooksPath, GIT_CONFIG_KEY_1: "credential.helper", GIT_CONFIG_VALUE_1: "" } : {}
4652
5063
  }
4653
5064
  });
5065
+ let leaseBearer = args.bearer;
4654
5066
  const sessionRecord = {
4655
5067
  userId: args.target.actingUserId,
4656
5068
  projectId: args.projectId,
@@ -4660,8 +5072,11 @@ async function prepareWithReservedRuntime(outer) {
4660
5072
  brokerRunId: broker.runId,
4661
5073
  gateway: started,
4662
5074
  stop: async () => await supervisor.stopSession(args.sessionId),
4663
- revokeLease: () => revokeLease(broker.runId, args.bearer),
5075
+ revokeLease: () => revokeLease(currentRunId, leaseBearer),
4664
5076
  releaseRuntime: outer.releaseRuntimeUse,
5077
+ // A Stop, stop-all, workspace or project stop ends a parked session
5078
+ // through this registry; the parked record must stop answering at once.
5079
+ onEnded: () => noteParkedLocalSessionEnded(args.sessionId),
4665
5080
  startedAt: Date.now()
4666
5081
  };
4667
5082
  let treeStopped = false;
@@ -4670,7 +5085,7 @@ async function prepareWithReservedRuntime(outer) {
4670
5085
  started.revoke();
4671
5086
  await started.close();
4672
5087
  } finally {
4673
- await revokeLease(broker.runId, args.bearer);
5088
+ await revokeLease(currentRunId, leaseBearer);
4674
5089
  const stop = await supervisor.stopSession(args.sessionId);
4675
5090
  if (stop.stopped) {
4676
5091
  treeStopped = true;
@@ -4687,33 +5102,64 @@ async function prepareWithReservedRuntime(outer) {
4687
5102
  localRuntimeVerifyMs,
4688
5103
  localGatewayReadyMs
4689
5104
  });
4690
- return {
4691
- ok: true,
4692
- prepared: {
4693
- plan,
4694
- sandbox,
4695
- // The child's credential: the gateway, and a capability that means
4696
- // nothing anywhere else. The lease is not in here and never will be.
4697
- auth: {
4698
- ANTHROPIC_AUTH_TOKEN: started.sessionCapability,
4699
- ANTHROPIC_API_KEY: started.sessionCapability,
4700
- ANTHROPIC_BASE_URL: started.baseUrl
5105
+ const live = {
5106
+ prepared: void 0,
5107
+ userId: args.target.actingUserId,
5108
+ projectId: args.projectId,
5109
+ runtimeId: plan.runtime.runtimeId,
5110
+ workspaceGrantId: plan.target.workspaceGrantId,
5111
+ rebindLease: (next) => {
5112
+ started.rebind(next.lease);
5113
+ currentRunId = next.runId;
5114
+ leaseBearer = next.bearer;
5115
+ sessionRecord.brokerRunId = next.runId;
5116
+ },
5117
+ revokeCurrentLease: () => revokeLease(currentRunId, leaseBearer)
5118
+ };
5119
+ const prepared = {
5120
+ plan,
5121
+ sandbox,
5122
+ auth: localChildAuth(harnessId, started),
5123
+ sandboxWorkDir: "project",
5124
+ skillsBaseDir: toAdapterPath(
5125
+ join6(sessionStateDir, "home", ...LOCAL_SKILLS_SUBDIR[harnessId])
5126
+ ),
5127
+ sessionStateExists,
5128
+ permissionMode,
5129
+ brokerRunId: broker.runId,
5130
+ timings: { localRuntimeVerifyMs, localGatewayReadyMs },
5131
+ teardown: teardownOnce,
5132
+ discardState: onceAsync(async () => {
5133
+ await teardownOnce();
5134
+ if (treeStopped) await removeSessionStateDir(sessionStateDir);
5135
+ }),
5136
+ park: (parkArgs) => parkLocalSession({
5137
+ sessionId: args.sessionId,
5138
+ generation: parkArgs.generation,
5139
+ userId: args.target.actingUserId,
5140
+ projectId: args.projectId,
5141
+ pendingApprovalIds: parkArgs.pendingApprovalIds,
5142
+ resources: live,
5143
+ ...parkArgs.ttlMs !== void 0 ? { ttlMs: parkArgs.ttlMs } : {},
5144
+ // ONE owner for cleanup: the registry, which revokes the gateway and
5145
+ // the lease, stops the tree and releases the runtime together.
5146
+ end: async (reason) => {
5147
+ logger.info("[local-harness] ending parked session", {
5148
+ sessionId: args.sessionId,
5149
+ reason
5150
+ });
5151
+ await endLocalHarnessSession(args.sessionId);
4701
5152
  },
4702
- sandboxWorkDir: "project",
4703
- skillsBaseDir: toAdapterPath(
4704
- join5(sessionStateDir, "home", ".claude", "skills")
4705
- ),
4706
- sessionStateExists,
4707
- permissionMode,
4708
- brokerRunId: broker.runId,
4709
- timings: { localRuntimeVerifyMs, localGatewayReadyMs },
4710
- teardown: teardownOnce,
4711
- discardState: onceAsync(async () => {
4712
- await teardownOnce();
4713
- if (treeStopped) await removeSessionStateDir(sessionStateDir);
4714
- })
4715
- }
5153
+ isAlive: () => supervisor.liveProcessCount(args.sessionId) > 0,
5154
+ holdModelTraffic: () => {
5155
+ started.hold();
5156
+ void revokeLease(currentRunId, leaseBearer);
5157
+ }
5158
+ }),
5159
+ unpark: () => releaseParkedLocalSession(args.sessionId)
4716
5160
  };
5161
+ live.prepared = prepared;
5162
+ return { ok: true, prepared };
4717
5163
  } catch (error) {
4718
5164
  await abandonLocalSetup({
4719
5165
  gateway,
@@ -4724,6 +5170,134 @@ async function prepareWithReservedRuntime(outer) {
4724
5170
  throw error;
4725
5171
  }
4726
5172
  }
5173
+ async function adoptParkedLocalTurn(args, harnessId) {
5174
+ const continuation = args.approvalContinuation;
5175
+ const claim = claimParkedLocalSession({
5176
+ sessionId: args.sessionId,
5177
+ generation: continuation.generation,
5178
+ userId: args.target.actingUserId,
5179
+ projectId: args.projectId,
5180
+ approvalIds: continuation.approvalIds
5181
+ });
5182
+ if (!claim.ok) {
5183
+ return { ok: false, status: `approval-${claim.reason}`, message: claim.message };
5184
+ }
5185
+ const live = claim.parked.resources;
5186
+ const fail = async (reason, status, message) => {
5187
+ await invalidateParkedLocalSession(args.sessionId, reason);
5188
+ return { ok: false, status, message };
5189
+ };
5190
+ const verifyStartedAt = Date.now();
5191
+ const runtimeStatus = await readRuntimeInstallStatus({ harnessId });
5192
+ if (runtimeStatus.state !== "ready") {
5193
+ return fail(
5194
+ "authorization-revoked",
5195
+ "runtime-unavailable",
5196
+ "The local runtime holding this approval is no longer installed; the pending action will not run."
5197
+ );
5198
+ }
5199
+ const availability = await resolveLocalHarnessAvailability({
5200
+ target: {
5201
+ kind: "local-native",
5202
+ harnessId,
5203
+ machineId: args.target.machineId,
5204
+ workspaceGrantId: args.target.workspaceGrantId,
5205
+ runtimeId: args.target.runtimeId,
5206
+ permissionProfile: args.target.permissionProfile,
5207
+ policyVersion: args.target.policyVersion
5208
+ },
5209
+ actor: args.actor,
5210
+ scope: args.scope,
5211
+ userId: args.target.actingUserId,
5212
+ projectId: args.projectId,
5213
+ grantToken: args.target.grantToken,
5214
+ runtimeRoot: runtimeStatus.runtimeRoot,
5215
+ installedAdapterVersion: args.installedAdapterVersion ?? await readInstalledAdapterVersion(harnessId)
5216
+ });
5217
+ if (!availability.available) {
5218
+ return fail("authorization-revoked", availability.status, availability.message);
5219
+ }
5220
+ const plan = availability.plan;
5221
+ if (plan.runtime.runtimeId !== live.runtimeId || plan.target.workspaceGrantId !== live.workspaceGrantId) {
5222
+ return fail(
5223
+ "authorization-revoked",
5224
+ "approval-runtime-changed",
5225
+ "The runtime or workspace changed while this approval was waiting; the pending action will not run."
5226
+ );
5227
+ }
5228
+ const permissionMode = args.scope !== "unattended" || args.requireToolApproval ? "allow-reads" : plan.permissionMode;
5229
+ if (permissionMode !== live.prepared.permissionMode) {
5230
+ return fail(
5231
+ "authorization-revoked",
5232
+ "approval-permission-changed",
5233
+ "The permission this session was approved under changed while the approval was waiting; the pending action will not run."
5234
+ );
5235
+ }
5236
+ const identity = await readLocalInstanceIdentity();
5237
+ const keyId = identity.keyId ?? getRegisteredKeyId();
5238
+ if (keyId === null) {
5239
+ return fail(
5240
+ "authorization-revoked",
5241
+ "consent-required",
5242
+ "This installation is no longer registered for local execution."
5243
+ );
5244
+ }
5245
+ const gatewayStartedAt = Date.now();
5246
+ const broker = await startLoopbackModelBroker({
5247
+ projectId: args.projectId,
5248
+ evalIterationId: args.evalIterationId,
5249
+ journeyRunId: args.journeyRunId,
5250
+ targetId: args.targetId,
5251
+ sessionIdx: args.sessionIdx,
5252
+ hostId: args.hostId,
5253
+ harnessId: args.harnessId,
5254
+ modelId: args.modelId,
5255
+ machineId: identity.machineId,
5256
+ keyId,
5257
+ runId: args.runId,
5258
+ ...args.maxOutputTokens !== void 0 ? { maxOutputTokens: args.maxOutputTokens } : {},
5259
+ bearer: args.bearer,
5260
+ ...args.signal ? { signal: args.signal } : {}
5261
+ });
5262
+ if (!broker.ok) {
5263
+ return fail("renewal-failed", "broker-unavailable", broker.error);
5264
+ }
5265
+ if (claim.parked.state !== "continuing" || !claim.parked.isAlive()) {
5266
+ await revokeLease(broker.runId, args.bearer);
5267
+ return fail(
5268
+ "process-died",
5269
+ "approval-process-died",
5270
+ "The local runtime holding this approval stopped while the decision was being delivered; the pending action will not run."
5271
+ );
5272
+ }
5273
+ try {
5274
+ live.rebindLease({ runId: broker.runId, lease: broker.lease, bearer: args.bearer });
5275
+ } catch (error) {
5276
+ await revokeLease(broker.runId, args.bearer);
5277
+ return fail(
5278
+ "renewal-failed",
5279
+ "gateway-unavailable",
5280
+ `The renewed model lease could not be bound: ${error instanceof Error ? error.message : String(error)}`
5281
+ );
5282
+ }
5283
+ logger.info("[local-harness] parked session re-adopted for an approval", {
5284
+ sessionId: args.sessionId,
5285
+ approvals: continuation.approvalIds.length
5286
+ });
5287
+ return {
5288
+ ok: true,
5289
+ prepared: {
5290
+ ...live.prepared,
5291
+ plan,
5292
+ sessionStateExists: true,
5293
+ brokerRunId: broker.runId,
5294
+ timings: {
5295
+ localRuntimeVerifyMs: gatewayStartedAt - verifyStartedAt,
5296
+ localGatewayReadyMs: Date.now() - gatewayStartedAt
5297
+ }
5298
+ }
5299
+ };
5300
+ }
4727
5301
  async function abandonLocalSetup(args) {
4728
5302
  try {
4729
5303
  args.gateway?.revoke();
@@ -4746,7 +5320,8 @@ async function revokeLease(runId, bearer) {
4746
5320
  }
4747
5321
  }
4748
5322
  var cachedAdapterVersion = null;
4749
- async function readInstalledAdapterVersion() {
5323
+ async function readInstalledAdapterVersion(harnessId) {
5324
+ if (harnessId === "codex") return CODEX_LOCAL_ADAPTER_IDENTITY;
4750
5325
  if (cachedAdapterVersion !== null) return cachedAdapterVersion;
4751
5326
  if (typeof __MCPJAM_CLAUDE_ADAPTER_VERSION__ === "string") return __MCPJAM_CLAUDE_ADAPTER_VERSION__;
4752
5327
  try {
@@ -4778,6 +5353,13 @@ export {
4778
5353
  pruneExpiredHarnessGrants,
4779
5354
  forgetWorkspaceGrant,
4780
5355
  listProcessRecords,
5356
+ stopAllLocalHarnessSessions,
5357
+ stopLocalHarnessWorkspace,
5358
+ readLocalHarnessAuthorization,
5359
+ authorizeLocalHarness,
5360
+ revokeLocalHarnessAuthorization,
5361
+ updateAuthorizedWorkspace,
5362
+ acknowledgeLocalHarnessAutoApprove,
4781
5363
  harnessPinnedVersion,
4782
5364
  harnessModelSupport,
4783
5365
  startHarnessModelBroker,
@@ -4790,12 +5372,10 @@ export {
4790
5372
  readLocalInstanceIdentity,
4791
5373
  setRegisteredKeyId,
4792
5374
  instanceKeyFingerprint,
5375
+ invalidateParkedLocalSession,
4793
5376
  resolveGitBashPath,
4794
5377
  sessionStateDirFor,
4795
- stopAllLocalHarnessSessions,
4796
- stopLocalHarnessWorkspace,
4797
- stopLocalHarnessProject,
4798
5378
  localHarnessSupervisor,
4799
5379
  prepareLocalHarnessTurn
4800
5380
  };
4801
- //# sourceMappingURL=chunk-DGAFFBDM.js.map
5381
+ //# sourceMappingURL=chunk-2FVSBJQF.js.map