@mcpjam/inspector 3.12.9 → 3.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/bin/runtime-profile.mjs +774 -0
  2. package/bin/start.js +138 -19
  3. package/dist/client/assets/OAuthDesktopReturnNotice-BZEaGzn6.css +2 -0
  4. package/dist/client/assets/{OAuthDesktopReturnNotice-DlTJhJwy.js → OAuthDesktopReturnNotice-D7d-faB1.js} +2 -2
  5. package/dist/client/assets/{app-bootstrap-BtbHLWDU.js → app-bootstrap-BtDjj9nz.js} +370 -387
  6. package/dist/client/assets/{button-12hqsTUk.js → button-B99pZFz_.js} +2 -2
  7. package/dist/client/assets/chunk-D32TOXHM-Bcyg0ZVj.js +160 -0
  8. package/dist/client/assets/dead-clicks-autocapture-CnUHv5CB.js +3 -0
  9. package/dist/client/assets/error-reporting-BohBwcQQ.js +120 -0
  10. package/dist/client/assets/{error-reporting-D3byeSLw.js → error-reporting-p6G1ojum.js} +1 -1
  11. package/dist/client/assets/{exception-autocapture-CzpTtsxv.js → exception-autocapture-Q-isBTHp.js} +4 -4
  12. package/dist/client/assets/{failed-request-tracker-CmHxaDPF.js → failed-request-tracker-BBJW8izb.js} +2 -2
  13. package/dist/client/assets/highlighted-body-KQOG7T2V-zsXWRnSM.js +3 -0
  14. package/dist/client/assets/{index-C0SfPmai.js → index-C9oFRqoK.js} +3 -3
  15. package/dist/client/assets/{jszip.min-BmAHHtmZ.js → jszip.min-C86zG41a.js} +2 -2
  16. package/dist/client/assets/mermaid-MCJ5UELQ-DAW4LYwz.js +1 -0
  17. package/dist/client/assets/posthog-recorder-trUd0BXy.js +110 -0
  18. package/dist/client/assets/{preload-helper-B22rzauv.js → preload-helper-Buauuydw.js} +2 -2
  19. package/dist/client/assets/{react-BzkNdoI5.js → react-CZb-kDOs.js} +2 -2
  20. package/dist/client/assets/{rolldown-runtime-BNuWddGb.js → rolldown-runtime-Bkua2_Tb.js} +1 -1
  21. package/dist/client/assets/surveys-BISK_WOT.js +3 -0
  22. package/dist/client/assets/trace-timeline-CRewsP1E.js +71 -0
  23. package/dist/client/assets/{trace-timeline-Bg58ukyI.js → trace-timeline-D-DWE-sO.js} +1 -1
  24. package/dist/client/assets/{web-vitals-D4bU8W1t.js → web-vitals-DqmZ9w02.js} +2 -2
  25. package/dist/client/index.html +8 -8
  26. package/dist/server/authorization-MA42CNYT.js +22 -0
  27. package/dist/server/chunk-7M3XVZCQ.js +381 -0
  28. package/dist/server/{chunk-SH24KJBI.js → chunk-7ZIR7SX7.js} +17 -45
  29. package/dist/server/chunk-C47PTIDS.js +487 -0
  30. package/dist/server/chunk-DHRTCKJA.js +3979 -0
  31. package/dist/server/chunk-HJTKF2X6.js +45 -0
  32. package/dist/server/{chunk-DGAFFBDM.js → chunk-KNO4KZJF.js} +728 -682
  33. package/dist/server/{chunk-4PYR7GMQ.js → chunk-RWFTW2EW.js} +7 -5
  34. package/dist/server/chunk-SDWJSPSI.js +252 -0
  35. package/dist/server/chunk-VFRLMHOC.js +33 -0
  36. package/dist/server/chunk-XSQ2GC45.js +438 -0
  37. package/dist/server/chunk-YQ2BTE46.js +88 -0
  38. package/dist/server/{consent-lifetime-M7PS6RUU.js → consent-lifetime-OXQM37RV.js} +4 -3
  39. package/dist/server/grants-UVE62NGN.js +37 -0
  40. package/dist/server/harness-install-cli.js +259 -7
  41. package/dist/server/index.js +14252 -12005
  42. package/dist/server/local-turn-XSUGEKTL.js +19 -0
  43. package/dist/server/runtime-health-TCF3ZEKS.js +28 -0
  44. package/dist/server/runtime-lifecycle-YQ3KWDLJ.js +53 -0
  45. package/package.json +62 -59
  46. package/dist/client/assets/OAuthDesktopReturnNotice-FnFv52Ym.css +0 -2
  47. package/dist/client/assets/chunk-YOKDWASO--Bd-6XAf.js +0 -145
  48. package/dist/client/assets/dead-clicks-autocapture-RCao2exY.js +0 -3
  49. package/dist/client/assets/error-reporting-StyhxjHz.js +0 -102
  50. package/dist/client/assets/highlighted-body-KPVGNVTW-BweERQbm.js +0 -3
  51. package/dist/client/assets/mermaid-HWGCJPDP-C6s_jIuz.js +0 -1
  52. package/dist/client/assets/posthog-recorder-wc41pimR.js +0 -110
  53. package/dist/client/assets/surveys-D-NcCeqw.js +0 -3
  54. package/dist/client/assets/trace-timeline-CxoCCEiW.js +0 -137
  55. package/dist/server/chunk-WZVZ6LQX.js +0 -2876
  56. package/dist/server/local-turn-ZWMMQGV3.js +0 -12
@@ -1,19 +1,15 @@
1
1
  import {
2
+ CODEX_LOCAL_ADAPTER_IDENTITY,
2
3
  LOCAL_HARNESS_MANIFEST,
3
- LOCAL_HARNESS_POLICY_VERSION,
4
- LOCAL_ISOLATION_POLICY_VERSION,
5
- createLocalStateMutationLock,
6
- currentLocalPlatform,
4
+ isSelectablePack,
7
5
  listGroupMembers,
8
- localPackTarget,
9
- logger,
10
6
  manifestWithExpectedBundleDigest,
7
+ noteRuntimeLaunch,
11
8
  probeProcess,
12
9
  probeProcessGroup,
13
10
  readProcessBirthIdentity,
14
11
  readProcessGroupId,
15
12
  readRuntimeInstallStatus,
16
- reserveRuntimeUse,
17
13
  resolveLocalCompatibility,
18
14
  resolveManagedBundle,
19
15
  resolveSystemInstall,
@@ -22,15 +18,38 @@ import {
22
18
  supportsOwnershipProof,
23
19
  terminateOwnedProcess,
24
20
  terminateOwnedProcessGroup
25
- } from "./chunk-WZVZ6LQX.js";
21
+ } from "./chunk-DHRTCKJA.js";
22
+ import {
23
+ reserveRuntimeUse
24
+ } from "./chunk-7M3XVZCQ.js";
25
+ import {
26
+ endLocalHarnessSession,
27
+ forgetLocalHarnessSession,
28
+ forgetLocalHarnessSessionRecord,
29
+ getLocalHarnessSession,
30
+ readLocalHarnessAuthorization,
31
+ registerLocalHarnessSession
32
+ } from "./chunk-SDWJSPSI.js";
33
+ import {
34
+ getLocalMachineId,
35
+ localHarnessStateRoot,
36
+ resolveWorkspaceGrant,
37
+ verifyLocalHarnessGrant
38
+ } from "./chunk-XSQ2GC45.js";
39
+ import {
40
+ LOCAL_HARNESS_POLICY_VERSION,
41
+ SUPPORTED_LOCAL_HARNESS_IDS,
42
+ currentLocalPlatform,
43
+ localPackTarget
44
+ } from "./chunk-VFRLMHOC.js";
45
+ import {
46
+ createLocalStateMutationLock,
47
+ logger
48
+ } from "./chunk-C47PTIDS.js";
26
49
  import {
27
50
  HOSTED_MODE,
28
- LOCAL_HARNESS_ENABLED,
29
- capabilityFingerprint,
30
- capabilityMatches,
31
- mintCapabilityToken,
32
- persistCapabilityState
33
- } from "./chunk-SH24KJBI.js";
51
+ LOCAL_HARNESS_ENABLED
52
+ } from "./chunk-7ZIR7SX7.js";
34
53
 
35
54
  // shared/harness-model-support-evidence.json
36
55
  var harness_model_support_evidence_default = {
@@ -277,7 +296,8 @@ async function startHarnessModelBroker(args) {
277
296
  ...harnessRuntimeVersionField(args.harnessId),
278
297
  modelId: args.modelId,
279
298
  ...args.runId ? { runId: args.runId } : {},
280
- ...args.maxOutputTokens !== void 0 ? { maxOutputTokens: args.maxOutputTokens } : {}
299
+ ...args.maxOutputTokens !== void 0 ? { maxOutputTokens: args.maxOutputTokens } : {},
300
+ ...args.reasoningEffort ? { reasoningEffort: args.reasoningEffort } : {}
281
301
  }),
282
302
  signal: args.signal
283
303
  });
@@ -304,7 +324,8 @@ async function startHarnessModelBroker(args) {
304
324
  return {
305
325
  ok: false,
306
326
  status: response.ok ? 502 : response.status,
307
- error: typeof payload?.error === "string" ? payload.error : `Harness model-broker failed (${response.status})`
327
+ error: typeof payload?.error === "string" ? payload.error : `Harness model-broker failed (${response.status})`,
328
+ ...!response.ok && typeof payload?.code === "string" ? { code: payload.code } : {}
308
329
  };
309
330
  }
310
331
  return {
@@ -401,7 +422,8 @@ async function startLoopbackModelBroker(args) {
401
422
  machineId: args.machineId,
402
423
  keyId: args.keyId,
403
424
  ...args.runId ? { runId: args.runId } : {},
404
- ...args.maxOutputTokens !== void 0 ? { maxOutputTokens: args.maxOutputTokens } : {}
425
+ ...args.maxOutputTokens !== void 0 ? { maxOutputTokens: args.maxOutputTokens } : {},
426
+ ...args.reasoningEffort ? { reasoningEffort: args.reasoningEffort } : {}
405
427
  }),
406
428
  ...args.signal ? { signal: args.signal } : {}
407
429
  });
@@ -623,412 +645,6 @@ async function releaseHarnessBoxReservation(args) {
623
645
  }
624
646
  }
625
647
 
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
- }
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;
769
- };
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
- }
802
- async function validateWorkspaceCandidate(rawPath) {
803
- let canonicalPath;
804
- 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) {
811
- return {
812
- ok: false,
813
- message: `the selected workspace could not be resolved: ${error instanceof Error ? error.message : String(error)}`
814
- };
815
- }
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)) {
820
- return {
821
- 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."
823
- };
824
- }
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()
843
- };
844
- state.workspaces.push(grant);
845
- await writeState(state);
846
- logger.info("[local-harness] workspace grant registered");
847
- return { ok: true, grant };
848
- });
849
- }
850
- async function resolveWorkspaceGrant(workspaceGrantId) {
851
- let state;
852
- try {
853
- state = await readState();
854
- } catch (error) {
855
- return {
856
- ok: false,
857
- message: error instanceof Error ? error.message : "the local harness grant store could not be read"
858
- };
859
- }
860
- const grant = state.workspaces.find(
861
- (w) => w.workspaceGrantId === workspaceGrantId
862
- );
863
- if (!grant) {
864
- return { ok: false, message: "unknown workspace grant" };
865
- }
866
- 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 };
884
- } catch {
885
- return {
886
- ok: false,
887
- message: "the granted workspace is no longer reachable"
888
- };
889
- }
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()
903
- };
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
- });
918
- }
919
- async function verifyLocalHarnessGrant(token, binding, opts) {
920
- if (!token || token.length < 16 || token.length > 256) {
921
- return {
922
- ok: false,
923
- reason: "invalid",
924
- message: "no local harness grant was presented"
925
- };
926
- }
927
- if (binding.policyVersion !== LOCAL_HARNESS_POLICY_VERSION) {
928
- return {
929
- 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.`
932
- };
933
- }
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) {
943
- return {
944
- ok: false,
945
- reason: "binding-mismatch",
946
- message: "a native grant must not carry an isolation policy version"
947
- };
948
- }
949
- const bindingHash = hashGrantBinding(binding);
950
- let state;
951
- try {
952
- state = await readState();
953
- } catch (error) {
954
- return {
955
- ok: false,
956
- reason: "invalid",
957
- message: error instanceof Error ? error.message : "the local harness grant store could not be read"
958
- };
959
- }
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
- return {
980
- ok: false,
981
- reason: "absent",
982
- message: "no local harness grant matches the presented capability"
983
- };
984
- }
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
1001
- );
1002
- }
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
1017
- );
1018
- const removed = before - state.harnessGrants.length;
1019
- if (removed > 0) await writeState(state);
1020
- return removed;
1021
- });
1022
- }
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
- });
1030
- }
1031
-
1032
648
  // server/utils/harness/local/availability.ts
1033
649
  function isActorEligibleForLocalHarness(actor, scope = "attended") {
1034
650
  return !actor.isGuest && !actor.isScenarioSession && (scope === "unattended" || !actor.isJourneySession && (actor.executionScopeKind === void 0 || actor.executionScopeKind === "project"));
@@ -1044,7 +660,10 @@ function localHarnessManifestsForDevelopment(manifests = LOCAL_HARNESS_MANIFEST)
1044
660
  return Object.fromEntries(
1045
661
  Object.entries(manifests).map(([id, manifest]) => [
1046
662
  id,
1047
- manifest.lifecycleConformanceVersion || id !== "claude-code" ? manifest : { ...manifest, lifecycleConformanceVersion: version }
663
+ // Every harness the manifest names, not only Claude Code: an unpublished
664
+ // Codex pack has to be exercisable through the same override before its
665
+ // conformance is recorded. Development builds only (see above).
666
+ manifest.lifecycleConformanceVersion ? manifest : { ...manifest, lifecycleConformanceVersion: version }
1048
667
  ])
1049
668
  );
1050
669
  }
@@ -1100,6 +719,9 @@ async function resolveLocalHarnessAvailability(query) {
1100
719
  targetKind: target.kind,
1101
720
  permissionProfile: target.permissionProfile,
1102
721
  ...target.kind === "local-isolated" ? { backend: target.backend } : {},
722
+ // The exact pack target, so a manifest certified per architecture (D8)
723
+ // refuses an uncertified one rather than trusting the OS alone.
724
+ packTarget: localPackTarget(platform),
1103
725
  installedAdapterVersion: query.installedAdapterVersion
1104
726
  },
1105
727
  query.manifests ?? localHarnessManifestsForDevelopment()
@@ -1111,16 +733,28 @@ async function resolveLocalHarnessAvailability(query) {
1111
733
  if (!workspace.ok) {
1112
734
  return unavailable("workspace-grant-invalid", workspace.message);
1113
735
  }
736
+ const packTarget = localPackTarget(platform);
737
+ if (query.runtimeDigest !== void 0 && query.manifests === void 0 && compatibility.manifest.runtime.source === "managed-bundle" && packTarget !== null) {
738
+ const selectable = await isSelectablePack(compatibility.manifest.harnessId, packTarget, query.runtimeDigest);
739
+ if (!selectable.ok) return unavailable("runtime-unavailable", selectable.message);
740
+ }
1114
741
  const runtimeResolution = compatibility.manifest.runtime.source === "managed-bundle" ? await resolveManagedBundle({
1115
742
  // Through `manifestWithExpectedBundleDigest`, so this path verifies
1116
743
  // against the digest the INSTALLER accepted rather than a second
1117
744
  // reading of the same table. They differ only under the documented
1118
745
  // development override — and there they differed fatally: a locally
1119
746
  // built pack installed and then could never run.
1120
- manifest: manifestWithExpectedBundleDigest(
747
+ //
748
+ // EXCEPT for a caller that supplied its own manifests (the
749
+ // conformance runners): their manifest names the pack under test,
750
+ // and replacing its digest with the pinned one made a pack built
751
+ // from changed inputs — exactly what a pack-input change or a new
752
+ // pack's pre-pin conformance has to run — unrunnable.
753
+ manifest: query.manifests !== void 0 ? compatibility.manifest : manifestWithExpectedBundleDigest(
1121
754
  compatibility.manifest,
1122
755
  compatibility.manifest.harnessId,
1123
- localPackTarget(platform)
756
+ packTarget,
757
+ query.runtimeDigest
1124
758
  ),
1125
759
  runtimeRoot: query.runtimeRoot,
1126
760
  platform: currentLocalPlatform(platform)
@@ -1197,14 +831,14 @@ function resolveNodeLauncher(opts) {
1197
831
  // server/utils/harness/local/model-gateway.ts
1198
832
  import { randomBytes, timingSafeEqual } from "crypto";
1199
833
  import { execFile as execFile2 } from "child_process";
1200
- import { readdir as readdir2, readFile as readFile4, readlink as readlink2 } from "fs/promises";
834
+ import { readdir as readdir2, readFile as readFile3, readlink as readlink2 } from "fs/promises";
1201
835
  import {
1202
836
  createServer as createServer2
1203
837
  } from "http";
1204
838
 
1205
839
  // server/utils/harness/local/bridge-endpoint.ts
1206
840
  import { execFile } from "child_process";
1207
- import { readdir, readFile as readFile2, readlink } from "fs/promises";
841
+ import { readdir, readFile, readlink } from "fs/promises";
1208
842
  import { createConnection, createServer } from "net";
1209
843
  import { networkInterfaces } from "os";
1210
844
  var LOOPBACK_HOST_V4 = "127.0.0.1";
@@ -1399,7 +1033,7 @@ async function readLinuxListenAddresses(pid) {
1399
1033
  for (const table of ["/proc/net/tcp", "/proc/net/tcp6"]) {
1400
1034
  let raw;
1401
1035
  try {
1402
- raw = await readFile2(table, "utf8");
1036
+ raw = await readFile(table, "utf8");
1403
1037
  } catch {
1404
1038
  continue;
1405
1039
  }
@@ -1470,8 +1104,8 @@ async function assertBridgeBindingIsLoopback(args) {
1470
1104
 
1471
1105
  // server/utils/harness/local/instance-key.ts
1472
1106
  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";
1107
+ import { chmod, mkdir, readFile as readFile2, stat, writeFile } from "fs/promises";
1108
+ import { join } from "path";
1475
1109
  var POP_SCHEME_PREFIX = "mcpjam-pop-v1";
1476
1110
  var KEY_FILE = "instance-key.json";
1477
1111
  var KeystoreUnavailableError = class extends Error {
@@ -1481,7 +1115,7 @@ var cached = null;
1481
1115
  var cachedKeyId = null;
1482
1116
  var loading = null;
1483
1117
  function keyFilePath() {
1484
- return join2(localHarnessStateRoot(), KEY_FILE);
1118
+ return join(localHarnessStateRoot(), KEY_FILE);
1485
1119
  }
1486
1120
  function toBase64Url(bytes) {
1487
1121
  return bytes.toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, "");
@@ -1495,7 +1129,7 @@ async function loadLocalInstanceKey() {
1495
1129
  let stored = null;
1496
1130
  let fileExists = true;
1497
1131
  try {
1498
- stored = JSON.parse(await readFile3(path, "utf8"));
1132
+ stored = JSON.parse(await readFile2(path, "utf8"));
1499
1133
  } catch (error) {
1500
1134
  fileExists = error?.code !== "ENOENT";
1501
1135
  stored = null;
@@ -1534,12 +1168,12 @@ async function loadLocalInstanceKey() {
1534
1168
  next.protection = "os-keystore";
1535
1169
  next.privateKey = keystore.encrypt(privateKeyPem);
1536
1170
  }
1537
- await mkdir2(localHarnessStateRoot(), { recursive: true, mode: 448 });
1171
+ await mkdir(localHarnessStateRoot(), { recursive: true, mode: 448 });
1538
1172
  const serialized = `${JSON.stringify(next, null, 2)}
1539
1173
  `;
1540
1174
  if (!fileExists) {
1541
1175
  try {
1542
- await writeFile2(path, serialized, { mode: 384, flag: "wx" });
1176
+ await writeFile(path, serialized, { mode: 384, flag: "wx" });
1543
1177
  } catch (error) {
1544
1178
  if (error?.code !== "EEXIST") throw error;
1545
1179
  const adopted = await adoptExistingKey(path, machineId);
@@ -1547,10 +1181,10 @@ async function loadLocalInstanceKey() {
1547
1181
  cached = adopted;
1548
1182
  return adopted;
1549
1183
  }
1550
- await writeFile2(path, serialized, { mode: 384 });
1184
+ await writeFile(path, serialized, { mode: 384 });
1551
1185
  }
1552
1186
  } else {
1553
- await writeFile2(path, serialized, { mode: 384 });
1187
+ await writeFile(path, serialized, { mode: 384 });
1554
1188
  }
1555
1189
  await repairKeyFileMode(path, true);
1556
1190
  const loaded = {
@@ -1569,7 +1203,7 @@ async function loadLocalInstanceKey() {
1569
1203
  }
1570
1204
  async function adoptExistingKey(path, machineId) {
1571
1205
  try {
1572
- const stored = JSON.parse(await readFile3(path, "utf8"));
1206
+ const stored = JSON.parse(await readFile2(path, "utf8"));
1573
1207
  return {
1574
1208
  machineId,
1575
1209
  publicKey: stored.publicKey,
@@ -1582,9 +1216,9 @@ async function adoptExistingKey(path, machineId) {
1582
1216
  async function repairKeyFileMode(path, quiet = false) {
1583
1217
  if (process.platform === "win32") return;
1584
1218
  try {
1585
- const mode = (await stat2(path)).mode & 511;
1219
+ const mode = (await stat(path)).mode & 511;
1586
1220
  if ((mode & 63) === 0) return;
1587
- await chmod2(path, 384);
1221
+ await chmod(path, 384);
1588
1222
  if (!quiet) {
1589
1223
  logger.warn("[local-harness] instance key file was not owner-only", {
1590
1224
  // The mode, never the path: the path is a home directory.
@@ -1663,6 +1297,12 @@ var ALLOWED_PATHS = [
1663
1297
  { method: "POST", prefix: "/responses" }
1664
1298
  ];
1665
1299
  var HELLO_PROBE = { method: "HEAD", path: "/api/hello" };
1300
+ function proofOfPossessionPath(upstreamPathname) {
1301
+ const match = upstreamPathname.match(
1302
+ /\/web\/harness\/model-proxy\/[^/]+(\/.*)?$/
1303
+ );
1304
+ return match === null ? upstreamPathname : match[1] || "/";
1305
+ }
1666
1306
  async function startLocalModelGateway(options) {
1667
1307
  const sessionCapability = randomBytes(32).toString("base64url");
1668
1308
  const capabilityBytes = Buffer.from(sessionCapability, "utf8");
@@ -1672,7 +1312,9 @@ async function startLocalModelGateway(options) {
1672
1312
  "the harness model lease is not a token this gateway can bind a proof of possession to"
1673
1313
  );
1674
1314
  }
1675
- const jti = parsedJti;
1315
+ let jti = parsedJti;
1316
+ let lease = options.lease;
1317
+ let held = false;
1676
1318
  const upstream = new URL(options.upstreamBaseUrl);
1677
1319
  if (upstream.protocol !== "https:" && !isLoopbackHost(upstream.host)) {
1678
1320
  throw new Error(
@@ -1730,11 +1372,15 @@ async function startLocalModelGateway(options) {
1730
1372
  refuse(res, 401, "session ended");
1731
1373
  return;
1732
1374
  }
1375
+ if (held) {
1376
+ refuse(res, 503, "session paused awaiting approval");
1377
+ return;
1378
+ }
1733
1379
  if (!isAllowedPath(method, path)) {
1734
1380
  refuse(res, 404, "endpoint not allowed");
1735
1381
  return;
1736
1382
  }
1737
- if (!capabilityMatches2(req, capabilityBytes)) {
1383
+ if (!capabilityMatches(req, capabilityBytes)) {
1738
1384
  refuse(res, 401, "capability rejected");
1739
1385
  return;
1740
1386
  }
@@ -1757,7 +1403,7 @@ async function startLocalModelGateway(options) {
1757
1403
  }
1758
1404
  const pop = await signProxiedRequest({
1759
1405
  method,
1760
- path: stripQuery(target.pathname),
1406
+ path: proofOfPossessionPath(stripQuery(target.pathname)),
1761
1407
  jti,
1762
1408
  nonce: randomBytes(16).toString("base64url")
1763
1409
  });
@@ -1770,8 +1416,8 @@ async function startLocalModelGateway(options) {
1770
1416
  // and the two that matter here are ours to set.
1771
1417
  "content-type": "application/json",
1772
1418
  accept: String(req.headers.accept ?? "application/json"),
1773
- authorization: `Bearer ${options.lease}`,
1774
- "x-mcpjam-harness-lease": options.lease,
1419
+ authorization: `Bearer ${lease}`,
1420
+ "x-mcpjam-harness-lease": lease,
1775
1421
  "x-mcpjam-pop": pop,
1776
1422
  ...typeof req.headers["anthropic-version"] === "string" ? { "anthropic-version": req.headers["anthropic-version"] } : {},
1777
1423
  ...typeof req.headers["anthropic-beta"] === "string" ? { "anthropic-beta": req.headers["anthropic-beta"] } : {}
@@ -1847,6 +1493,20 @@ async function startLocalModelGateway(options) {
1847
1493
  revoke: () => {
1848
1494
  revoked = true;
1849
1495
  },
1496
+ hold: () => {
1497
+ held = true;
1498
+ },
1499
+ rebind: (nextLease) => {
1500
+ const nextJti = leaseJti(nextLease);
1501
+ if (nextJti === null) {
1502
+ throw new Error(
1503
+ "the renewed harness model lease is not a token this gateway can bind a proof of possession to"
1504
+ );
1505
+ }
1506
+ lease = nextLease;
1507
+ jti = nextJti;
1508
+ held = false;
1509
+ },
1850
1510
  close: async () => {
1851
1511
  revoked = true;
1852
1512
  await closeServer(server);
@@ -1901,7 +1561,7 @@ function isAllowedPath(method, path) {
1901
1561
  (entry) => entry.method === method && (bare === entry.prefix || bare.startsWith(`${entry.prefix}/`))
1902
1562
  );
1903
1563
  }
1904
- function capabilityMatches2(req, expected) {
1564
+ function capabilityMatches(req, expected) {
1905
1565
  const header = req.headers["x-api-key"] ?? req.headers.authorization;
1906
1566
  const presented = typeof header === "string" ? header.replace(/^Bearer\s+/i, "") : Array.isArray(header) ? "" : "";
1907
1567
  const presentedBytes = Buffer.from(presented, "utf8");
@@ -1980,7 +1640,7 @@ async function findLocalSocketInode(port) {
1980
1640
  for (const table of ["/proc/net/tcp", "/proc/net/tcp6"]) {
1981
1641
  let raw;
1982
1642
  try {
1983
- raw = await readFile4(table, "utf8");
1643
+ raw = await readFile3(table, "utf8");
1984
1644
  } catch {
1985
1645
  continue;
1986
1646
  }
@@ -1995,32 +1655,212 @@ async function findLocalSocketInode(port) {
1995
1655
  return null;
1996
1656
  }
1997
1657
 
1658
+ // server/utils/harness/local/approval-park.ts
1659
+ var DEFAULT_APPROVAL_PARK_TTL_MS = 30 * 60 * 1e3;
1660
+ var realClock = {
1661
+ now: () => Date.now(),
1662
+ setTimer: (fn, ms) => {
1663
+ const timer = setTimeout(fn, ms);
1664
+ timer.unref?.();
1665
+ return timer;
1666
+ },
1667
+ clearTimer: (timer) => clearTimeout(timer)
1668
+ };
1669
+ var clock = realClock;
1670
+ var parked = /* @__PURE__ */ new Map();
1671
+ function parkLocalSession(args) {
1672
+ if (args.pendingApprovalIds.length === 0) {
1673
+ throw new Error("a parked session must be waiting on at least one approval");
1674
+ }
1675
+ const existing = parked.get(args.sessionId);
1676
+ if (existing && existing.generation !== args.generation) {
1677
+ if (existing.timer) clock.clearTimer(existing.timer);
1678
+ parked.delete(args.sessionId);
1679
+ } else if (existing?.state === "terminal") {
1680
+ return false;
1681
+ }
1682
+ const prior = parked.get(args.sessionId);
1683
+ const now = clock.now();
1684
+ const ttl = args.ttlMs ?? DEFAULT_APPROVAL_PARK_TTL_MS;
1685
+ if (prior?.timer) clock.clearTimer(prior.timer);
1686
+ args.holdModelTraffic();
1687
+ const entry = {
1688
+ sessionId: args.sessionId,
1689
+ generation: args.generation,
1690
+ userId: args.userId,
1691
+ projectId: args.projectId,
1692
+ state: "awaiting-approval",
1693
+ pending: new Set(args.pendingApprovalIds),
1694
+ // Carried across re-parks: an id decided in an earlier pause of the same
1695
+ // process can never be replayed against this one.
1696
+ consumed: new Set(prior?.consumed ?? []),
1697
+ parkedAt: now,
1698
+ expiresAt: now + ttl,
1699
+ resources: args.resources,
1700
+ end: args.end,
1701
+ isAlive: args.isAlive,
1702
+ holdModelTraffic: args.holdModelTraffic,
1703
+ timer: null
1704
+ };
1705
+ for (const id of entry.pending) {
1706
+ if (entry.consumed.has(id)) {
1707
+ throw new Error(`approval ${id} was already decided in this session`);
1708
+ }
1709
+ }
1710
+ entry.timer = clock.setTimer(() => {
1711
+ void invalidateParkedLocalSession(args.sessionId, "idle-expired");
1712
+ }, ttl);
1713
+ parked.set(args.sessionId, entry);
1714
+ logger.info("[local-harness] session parked awaiting approval", {
1715
+ sessionId: args.sessionId,
1716
+ pending: entry.pending.size,
1717
+ ttlMs: ttl
1718
+ });
1719
+ return true;
1720
+ }
1721
+ function claimParkedLocalSession(args) {
1722
+ const entry = parked.get(args.sessionId);
1723
+ if (entry === void 0) {
1724
+ return refusal(
1725
+ "absent",
1726
+ "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."
1727
+ );
1728
+ }
1729
+ if (entry.state === "terminal") {
1730
+ return refusal(
1731
+ "terminal",
1732
+ `The local session holding this approval ended (${entry.invalidatedBy ?? "stopped"}). Start a new turn; any action proposed then will ask for approval again.`
1733
+ );
1734
+ }
1735
+ if (entry.userId !== args.userId || entry.projectId !== args.projectId) {
1736
+ return refusal(
1737
+ "actor-mismatch",
1738
+ "This approval belongs to a different user or project."
1739
+ );
1740
+ }
1741
+ if (entry.generation !== args.generation) {
1742
+ return refusal(
1743
+ "generation-mismatch",
1744
+ "This approval was asked by an earlier run of the local runtime, which has since restarted. It cannot approve anything the new run proposes."
1745
+ );
1746
+ }
1747
+ if (args.approvalIds.length === 0) {
1748
+ return refusal("no-decision", "The continuation carried no approval decision.");
1749
+ }
1750
+ for (const id of args.approvalIds) {
1751
+ if (entry.consumed.has(id)) {
1752
+ return refusal(
1753
+ "duplicate-approval",
1754
+ "This approval was already answered; the action will not run twice."
1755
+ );
1756
+ }
1757
+ }
1758
+ if (entry.state !== "awaiting-approval") {
1759
+ return refusal(
1760
+ "not-awaiting",
1761
+ "This approval is already being continued."
1762
+ );
1763
+ }
1764
+ for (const id of args.approvalIds) {
1765
+ if (!entry.pending.has(id)) {
1766
+ return refusal(
1767
+ "stale-approval",
1768
+ "That decision answers an approval this session is not waiting on."
1769
+ );
1770
+ }
1771
+ }
1772
+ if (!entry.isAlive()) {
1773
+ void invalidateParkedLocalSession(args.sessionId, "process-died");
1774
+ return refusal(
1775
+ "process-died",
1776
+ "The local runtime holding this approval stopped. Its pending action will not run; start a new turn to continue the conversation."
1777
+ );
1778
+ }
1779
+ if (entry.timer) clock.clearTimer(entry.timer);
1780
+ entry.timer = null;
1781
+ entry.state = "continuing";
1782
+ for (const id of args.approvalIds) {
1783
+ entry.consumed.add(id);
1784
+ entry.pending.delete(id);
1785
+ }
1786
+ return { ok: true, parked: entry };
1787
+ }
1788
+ function releaseParkedLocalSession(sessionId) {
1789
+ const entry = parked.get(sessionId);
1790
+ if (entry === void 0) return;
1791
+ if (entry.timer) clock.clearTimer(entry.timer);
1792
+ parked.delete(sessionId);
1793
+ }
1794
+ var TOMBSTONE_TTL_MS = 6e4;
1795
+ function expireTombstone(sessionId, entry) {
1796
+ entry.timer = clock.setTimer(() => {
1797
+ if (parked.get(sessionId) === entry) parked.delete(sessionId);
1798
+ }, TOMBSTONE_TTL_MS);
1799
+ }
1800
+ async function invalidateParkedLocalSession(sessionId, reason) {
1801
+ const entry = parked.get(sessionId);
1802
+ if (entry === void 0 || entry.state === "terminal") return;
1803
+ entry.state = "terminal";
1804
+ entry.invalidatedBy = reason;
1805
+ entry.pending.clear();
1806
+ if (entry.timer) clock.clearTimer(entry.timer);
1807
+ entry.timer = null;
1808
+ logger.info("[local-harness] parked session ended", { sessionId, reason });
1809
+ try {
1810
+ await entry.end(reason);
1811
+ } catch (error) {
1812
+ logger.warn("[local-harness] parked session teardown failed", {
1813
+ sessionId,
1814
+ reason,
1815
+ message: error instanceof Error ? error.message : String(error)
1816
+ });
1817
+ } finally {
1818
+ if (parked.get(sessionId) === entry) expireTombstone(sessionId, entry);
1819
+ }
1820
+ }
1821
+ function noteParkedLocalSessionEnded(sessionId) {
1822
+ const entry = parked.get(sessionId);
1823
+ if (entry === void 0 || entry.state === "terminal") return;
1824
+ entry.state = "terminal";
1825
+ entry.invalidatedBy = "stopped";
1826
+ entry.pending.clear();
1827
+ if (entry.timer) clock.clearTimer(entry.timer);
1828
+ expireTombstone(sessionId, entry);
1829
+ }
1830
+ function hasParkedLocalSession(sessionId) {
1831
+ const entry = parked.get(sessionId);
1832
+ return entry !== void 0 && entry.state !== "terminal";
1833
+ }
1834
+ function refusal(reason, message) {
1835
+ return { ok: false, reason, message };
1836
+ }
1837
+
1998
1838
  // server/utils/harness/local/supervised-provider.ts
1999
- import { randomUUID as randomUUID2 } from "crypto";
1839
+ import { randomUUID } from "crypto";
2000
1840
  import {
2001
1841
  lstat as lstat2,
2002
- mkdir as mkdir3,
1842
+ mkdir as mkdir2,
2003
1843
  open,
2004
1844
  readlink as readlink4,
2005
- realpath as realpath3,
2006
- rename as rename2,
1845
+ realpath as realpath2,
1846
+ rename,
2007
1847
  rm,
2008
- stat as stat3,
1848
+ stat as stat2,
2009
1849
  symlink
2010
1850
  } from "fs/promises";
2011
1851
  import {
2012
1852
  basename,
2013
1853
  dirname as dirname2,
2014
1854
  isAbsolute as isAbsolute3,
2015
- join as join3,
1855
+ join as join2,
2016
1856
  posix as posix4,
2017
1857
  resolve as resolve2,
2018
- sep as sep4
1858
+ sep as sep3
2019
1859
  } from "path";
2020
1860
 
2021
1861
  // server/utils/harness/local/confine.ts
2022
- import { lstat, readlink as readlink3, realpath as realpath2 } from "fs/promises";
2023
- import { dirname, isAbsolute as isAbsolute2, normalize, resolve, sep as sep2 } from "path";
1862
+ import { lstat, readlink as readlink3, realpath } from "fs/promises";
1863
+ import { dirname, isAbsolute as isAbsolute2, normalize, resolve, sep } from "path";
2024
1864
  var MAX_PATH_LENGTH = 4096;
2025
1865
  var PathConfinementError = class extends Error {
2026
1866
  constructor(message, requestedPath) {
@@ -2030,20 +1870,20 @@ var PathConfinementError = class extends Error {
2030
1870
  }
2031
1871
  };
2032
1872
  function isUnder(candidate, root) {
2033
- return candidate === root || candidate.startsWith(root + sep2);
1873
+ return candidate === root || candidate.startsWith(root + sep);
2034
1874
  }
2035
1875
  async function resolveExistingAncestor(path) {
2036
1876
  const tail = [];
2037
1877
  let current = path;
2038
1878
  for (; ; ) {
2039
1879
  try {
2040
- return { base: await realpath2(current), tail };
1880
+ return { base: await realpath(current), tail };
2041
1881
  } catch {
2042
1882
  const parent = dirname(current);
2043
1883
  if (parent === current) {
2044
1884
  return { base: current, tail };
2045
1885
  }
2046
- const cut = parent.endsWith(sep2) ? parent.length : parent.length + 1;
1886
+ const cut = parent.endsWith(sep) ? parent.length : parent.length + 1;
2047
1887
  tail.unshift(current.slice(cut));
2048
1888
  current = parent;
2049
1889
  }
@@ -2069,7 +1909,7 @@ async function resolveDanglingLinks(base, tail, requested) {
2069
1909
  return resolve(next, ...tail.slice(index + 1));
2070
1910
  }
2071
1911
  if (!isLink) {
2072
- next = await realpath2(next).catch(() => next);
1912
+ next = await realpath(next).catch(() => next);
2073
1913
  break;
2074
1914
  }
2075
1915
  if ((hops += 1) > MAX_LINK_HOPS) {
@@ -2151,7 +1991,7 @@ function fromAdapterPath(adapterPath, platform = process.platform) {
2151
1991
  }
2152
1992
 
2153
1993
  // server/utils/harness/local/command-translation.ts
2154
- import { normalize as normalize2, posix as posix2, sep as sep3 } from "path";
1994
+ import { normalize as normalize2, posix as posix2, sep as sep2 } from "path";
2155
1995
 
2156
1996
  // server/utils/harness/local/argv-policy.ts
2157
1997
  var MAX_ARG_LENGTH = 4096;
@@ -2358,9 +2198,9 @@ function remapBootstrapPath(path, ctx) {
2358
2198
  );
2359
2199
  }
2360
2200
  const rest = normalizedPath.slice(root.length).replace(/^\//, "");
2361
- const mapped = rest ? `${ctx.managedBundleRoot}${sep3}${rest.split("/").join(sep3)}` : ctx.managedBundleRoot;
2201
+ const mapped = rest ? `${ctx.managedBundleRoot}${sep2}${rest.split("/").join(sep2)}` : ctx.managedBundleRoot;
2362
2202
  const normalized = normalize2(mapped);
2363
- if (normalized !== ctx.managedBundleRoot && !normalized.startsWith(ctx.managedBundleRoot + sep3)) {
2203
+ if (normalized !== ctx.managedBundleRoot && !normalized.startsWith(ctx.managedBundleRoot + sep2)) {
2364
2204
  throw new CommandTranslationError(
2365
2205
  `bootstrap path ${JSON.stringify(path)} escapes the managed bundle root`,
2366
2206
  path
@@ -2383,10 +2223,17 @@ function classifyBootstrapPath(path, ctx) {
2383
2223
  if (BOOTSTRAP_MARKER.test(relative)) {
2384
2224
  return {
2385
2225
  kind: "session-overlay",
2386
- overlayPath: `${ctx.bootstrapOverlayDir}${sep3}${relative}`
2226
+ overlayPath: `${ctx.bootstrapOverlayDir}${sep2}${relative}`
2387
2227
  };
2388
2228
  }
2389
2229
  if (ctx.adapterBootstrapFiles.includes(relative)) {
2230
+ if (ctx.layerRoot !== void 0 && ctx.layerFiles?.includes(relative) === true && !relative.includes("/")) {
2231
+ return {
2232
+ kind: "bundle-asset",
2233
+ bundlePath: `${ctx.layerRoot}${sep2}${relative}`,
2234
+ relativePath: relative
2235
+ };
2236
+ }
2390
2237
  return {
2391
2238
  kind: "bundle-asset",
2392
2239
  bundlePath: remapBootstrapPath(normalized, ctx),
@@ -2473,7 +2320,7 @@ function matchBootstrapInstall(command, ctx) {
2473
2320
  reason: "vendor dependency graph is supplied by the digest-verified managed runtime bundle; no package manager runs during a session"
2474
2321
  };
2475
2322
  }
2476
- if (ctx.harnessId === "claude-code" && command === "./node_modules/.bin/claude --version") {
2323
+ 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
2324
  return {
2478
2325
  kind: "noop",
2479
2326
  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 +2333,12 @@ async function matchBridgeLaunch(command, ctx) {
2486
2333
  const tokens = splitQuotedTokens(command.slice("node ".length), command);
2487
2334
  const expected = {
2488
2335
  "claude-code": ["--workdir", "--bridge-state-dir"],
2489
- codex: ["--workdir", "--bridge-state-dir", "--cli-shim-dir"]
2336
+ codex: [
2337
+ "--workdir",
2338
+ "--bridge-state-dir",
2339
+ "--session-data-dir",
2340
+ "--bootstrap-dir"
2341
+ ]
2490
2342
  };
2491
2343
  const flags = expected[ctx.harnessId];
2492
2344
  if (tokens.length !== 1 + flags.length * 2) {
@@ -2505,7 +2357,10 @@ async function matchBridgeLaunch(command, ctx) {
2505
2357
  );
2506
2358
  }
2507
2359
  const args = [
2508
- ctx.bridgeLauncherPath ?? remapBootstrapPath(expectedBridge, ctx)
2360
+ ctx.bridgeLauncherPath ?? (ctx.layerRoot !== void 0 ? `${ctx.layerRoot}${sep2}bridge.mjs` : remapBootstrapPath(expectedBridge, ctx)),
2361
+ // The launcher's own argument, never the bridge's: only where a launcher
2362
+ // is in front, and only the verified pack.
2363
+ ...ctx.bridgeLauncherPath !== void 0 && ctx.launcherVendorRoot !== void 0 ? ["--mcpjam-vendor-root", ctx.launcherVendorRoot] : []
2509
2364
  ];
2510
2365
  for (let i = 0; i < flags.length; i += 1) {
2511
2366
  const flag = tokens[1 + i * 2];
@@ -2517,6 +2372,29 @@ async function matchBridgeLaunch(command, ctx) {
2517
2372
  );
2518
2373
  }
2519
2374
  assertPlainPathOperand(value, command);
2375
+ if (flag === "--bootstrap-dir") {
2376
+ if (posix2.normalize(value) !== posix2.normalize(ctx.adapterBootstrapDir)) {
2377
+ throw new CommandTranslationError(
2378
+ `--bootstrap-dir names ${JSON.stringify(value)}, but the only bootstrap this session may load is its managed bundle`,
2379
+ command
2380
+ );
2381
+ }
2382
+ if (ctx.layerRoot !== void 0) {
2383
+ args.push(
2384
+ "--vendor-dir",
2385
+ remapBootstrapPath(value, ctx),
2386
+ "--layer-dir",
2387
+ ctx.layerRoot
2388
+ );
2389
+ } else {
2390
+ args.push(flag, remapBootstrapPath(value, ctx));
2391
+ }
2392
+ continue;
2393
+ }
2394
+ if (ctx.harnessId === "codex" && (flag === "--bridge-state-dir" || flag === "--session-data-dir")) {
2395
+ args.push(flag, await (ctx.confineToSessionState ?? ctx.confine)(value));
2396
+ continue;
2397
+ }
2520
2398
  args.push(flag, await ctx.confine(value));
2521
2399
  }
2522
2400
  assertArgvAllowed(args);
@@ -2663,7 +2541,11 @@ var SCOPED_NAME_DENYLIST = /* @__PURE__ */ new Set([
2663
2541
  // Names the shell the vendor CLI runs commands through. A scoped override
2664
2542
  // would point it at any executable; the provider sets it from a path it
2665
2543
  // has verified exists.
2666
- "CLAUDE_CODE_GIT_BASH_PATH"
2544
+ "CLAUDE_CODE_GIT_BASH_PATH",
2545
+ // Codex's config root. The bridge renders a per-session CODEX_HOME (auth,
2546
+ // model provider, the relay's MCP server); an injected one would point Codex
2547
+ // back at a user's real `~/.codex` — its servers, its credentials.
2548
+ "CODEX_HOME"
2667
2549
  ]);
2668
2550
  var LocalHarnessEnvError = class extends Error {
2669
2551
  };
@@ -2697,6 +2579,12 @@ function buildLocalHarnessEnv(opts) {
2697
2579
  } catch {
2698
2580
  }
2699
2581
  }
2582
+ for (const root of opts.extraDeniedRoots ?? []) {
2583
+ if (!path.isAbsolute(root)) {
2584
+ throw new LocalHarnessEnvError("a denied runtime root must be an absolute path");
2585
+ }
2586
+ if (!deniedRoots.includes(root)) deniedRoots.push(root);
2587
+ }
2700
2588
  env.MCPJAM_LOCAL_DENIED_ROOTS = JSON.stringify(deniedRoots);
2701
2589
  env.TMPDIR = path.join(opts.syntheticHome, "tmp");
2702
2590
  env.CLAUDE_CODE_TMPDIR = env.TMPDIR;
@@ -2742,10 +2630,21 @@ function validateLocalHarnessScopedEnv(scoped) {
2742
2630
  }
2743
2631
  }
2744
2632
  }
2745
- function validateLocalHarnessSecretEnv(scoped) {
2633
+ var RUNTIME_RESERVED_SECRET_PREFIXES = {
2634
+ "claude-code": /^(ANTHROPIC_|AI_GATEWAY_|BRIDGE_|CLAUDE_CODE_)/i,
2635
+ codex: /^(CODEX_|OPENAI_|AI_GATEWAY_|BRIDGE_)/i
2636
+ };
2637
+ function validateLocalHarnessSecretEnv(scoped, harnessId = "claude-code") {
2746
2638
  validateLocalHarnessScopedEnv(scoped);
2639
+ const reserved = Object.prototype.hasOwnProperty.call(
2640
+ RUNTIME_RESERVED_SECRET_PREFIXES,
2641
+ harnessId
2642
+ ) ? RUNTIME_RESERVED_SECRET_PREFIXES[harnessId] : (
2643
+ // An unknown harness gets the union, never nothing.
2644
+ /^(ANTHROPIC_|AI_GATEWAY_|BRIDGE_|CLAUDE_CODE_|CODEX_|OPENAI_)/i
2645
+ );
2747
2646
  for (const name of Object.keys(scoped)) {
2748
- if (/^(ANTHROPIC_|AI_GATEWAY_|BRIDGE_|CLAUDE_CODE_)/i.test(name)) {
2647
+ if (reserved.test(name)) {
2749
2648
  throw new LocalHarnessEnvError(
2750
2649
  `Project secret ${name} conflicts with the local harness runtime.`
2751
2650
  );
@@ -2949,14 +2848,14 @@ async function writeBytesAtomically(path, bytes, abortSignal) {
2949
2848
  const abortError = () => abortSignal?.reason instanceof Error ? abortSignal.reason : new Error("aborted");
2950
2849
  if (abortSignal?.aborted) throw abortError();
2951
2850
  const parent = dirname2(path);
2952
- await mkdir3(parent, { recursive: true, mode: 448 });
2851
+ await mkdir2(parent, { recursive: true, mode: 448 });
2953
2852
  let mode = 384;
2954
2853
  try {
2955
- mode = (await stat3(path)).mode & 511;
2854
+ mode = (await stat2(path)).mode & 511;
2956
2855
  } catch (error) {
2957
2856
  if (error.code !== "ENOENT") throw error;
2958
2857
  }
2959
- const temp = join3(parent, `.${basename(path)}.${randomUUID2()}.tmp`);
2858
+ const temp = join2(parent, `.${basename(path)}.${randomUUID()}.tmp`);
2960
2859
  const handle = await open(temp, "wx", mode);
2961
2860
  let closed = false;
2962
2861
  try {
@@ -2968,7 +2867,7 @@ async function writeBytesAtomically(path, bytes, abortSignal) {
2968
2867
  if (abortSignal?.aborted) throw abortError();
2969
2868
  await handle.close();
2970
2869
  closed = true;
2971
- await rename2(temp, path);
2870
+ await rename(temp, path);
2972
2871
  } catch (error) {
2973
2872
  if (!closed) await handle.close().catch(() => {
2974
2873
  });
@@ -2982,7 +2881,7 @@ async function resolveGitBashPath(platform) {
2982
2881
  const configured = process.env.CLAUDE_CODE_GIT_BASH_PATH;
2983
2882
  const candidates = [
2984
2883
  ...configured && isAbsolute3(configured) ? [configured] : [],
2985
- join3(
2884
+ join2(
2986
2885
  process.env.ProgramFiles ?? "C:\\Program Files",
2987
2886
  "Git",
2988
2887
  "bin",
@@ -2991,7 +2890,7 @@ async function resolveGitBashPath(platform) {
2991
2890
  ];
2992
2891
  for (const candidate of candidates) {
2993
2892
  try {
2994
- if ((await stat3(candidate)).isFile()) return candidate;
2893
+ if ((await stat2(candidate)).isFile()) return candidate;
2995
2894
  } catch {
2996
2895
  }
2997
2896
  }
@@ -3049,9 +2948,9 @@ function createSupervisedLocalHarnessProvider(opts) {
3049
2948
  );
3050
2949
  }
3051
2950
  };
3052
- const syntheticHome = join3(opts.sessionStateDir, "home");
3053
- const bootstrapOverlay = join3(opts.sessionStateDir, "bootstrap");
3054
- const workRoot = join3(opts.sessionStateDir, "work");
2951
+ const syntheticHome = join2(opts.sessionStateDir, "home");
2952
+ const bootstrapOverlay = join2(opts.sessionStateDir, "bootstrap");
2953
+ const workRoot = join2(opts.sessionStateDir, "work");
3055
2954
  const WORKSPACE_LINK_NAME = "project";
3056
2955
  const platform = opts.platform ?? process.platform;
3057
2956
  const adapterWorkRoot = toAdapterPath(workRoot, platform);
@@ -3065,18 +2964,18 @@ function createSupervisedLocalHarnessProvider(opts) {
3065
2964
  };
3066
2965
  const buildSession = async (sessionId, abortSignal) => {
3067
2966
  for (const dir of syntheticHomeDirectories(syntheticHome, platform)) {
3068
- await mkdir3(dir, { recursive: true, mode: 448 });
2967
+ await mkdir2(dir, { recursive: true, mode: 448 });
3069
2968
  }
3070
- await mkdir3(bootstrapOverlay, { recursive: true, mode: 448 });
3071
- await mkdir3(workRoot, { recursive: true, mode: 448 });
3072
- const workspaceLink = join3(workRoot, WORKSPACE_LINK_NAME);
2969
+ await mkdir2(bootstrapOverlay, { recursive: true, mode: 448 });
2970
+ await mkdir2(workRoot, { recursive: true, mode: 448 });
2971
+ const workspaceLink = join2(workRoot, WORKSPACE_LINK_NAME);
3073
2972
  try {
3074
2973
  const existing = await lstat2(workspaceLink);
3075
2974
  if (!existing.isSymbolicLink()) {
3076
2975
  throw new Error(`${workspaceLink} exists and is not the workspace link`);
3077
2976
  }
3078
2977
  const current = await readlink4(workspaceLink);
3079
- const resolved = await realpath3(workspaceLink).catch(
2978
+ const resolved = await realpath2(workspaceLink).catch(
3080
2979
  (error) => {
3081
2980
  if (error.code === "ENOENT") return null;
3082
2981
  throw error;
@@ -3094,16 +2993,34 @@ function createSupervisedLocalHarnessProvider(opts) {
3094
2993
  if (error.code !== "ENOENT") throw error;
3095
2994
  await linkWorkspace(workspaceLink);
3096
2995
  }
3097
- const roots = [await realpath3(opts.sessionStateDir), opts.workspacePath];
2996
+ const roots = [await realpath2(opts.sessionStateDir), opts.workspacePath];
3098
2997
  const confine = (path) => confinePath(fromAdapterPath(path, platform), { roots });
3099
- const gitBashPath = await resolveGitBashPath(platform);
2998
+ const confineToSessionState = (path) => confinePath(fromAdapterPath(path, platform), { roots: [roots[0]] });
2999
+ const gitBashPath = opts.harnessId === "claude-code" ? await resolveGitBashPath(platform) : void 0;
3000
+ for (const runtimeDir of [
3001
+ opts.runtime.rootPath,
3002
+ ...opts.runtime.layer !== void 0 ? [opts.runtime.layer.root] : []
3003
+ ]) {
3004
+ for (const writable of roots) {
3005
+ if (runtimeDir === writable || runtimeDir.startsWith(writable + sep3)) {
3006
+ throw new Error(
3007
+ `the local runtime at ${runtimeDir} is inside a directory this session may write, so it cannot be protected from the agent it launches. Pick a workspace that does not contain the Inspector's runtime directory.`
3008
+ );
3009
+ }
3010
+ }
3011
+ }
3100
3012
  const env = {
3101
3013
  ...buildLocalHarnessEnv({
3102
3014
  syntheticHome,
3103
3015
  sessionRoot: opts.workspacePath,
3104
3016
  platform,
3105
3017
  ...opts.scopedEnv ? { scoped: opts.scopedEnv } : {},
3106
- ...gitBashPath !== void 0 ? { gitBashPath } : {}
3018
+ ...gitBashPath !== void 0 ? { gitBashPath } : {},
3019
+ // Named in the agent's own deny rules, alongside sibling sessions.
3020
+ extraDeniedRoots: [
3021
+ ...opts.runtime.layer !== void 0 ? [opts.runtime.layer.root] : [],
3022
+ opts.runtime.rootPath
3023
+ ]
3107
3024
  }),
3108
3025
  ...opts.launcher.requiredEnv
3109
3026
  };
@@ -3117,11 +3034,18 @@ function createSupervisedLocalHarnessProvider(opts) {
3117
3034
  opts.manifest.adapterBootstrapDir
3118
3035
  ),
3119
3036
  managedBundleRoot: opts.runtime.rootPath,
3037
+ ...opts.runtime.layer !== void 0 ? {
3038
+ layerRoot: opts.runtime.layer.root,
3039
+ layerFiles: opts.runtime.layer.files,
3040
+ // The layer's launcher resolves a vendor SDK import into the
3041
+ // verified pack and nowhere else.
3042
+ launcherVendorRoot: opts.runtime.rootPath
3043
+ } : {},
3120
3044
  adapterBootstrapFiles: opts.manifest.adapterBootstrapFiles,
3121
3045
  bootstrapOverlayDir: bootstrapOverlay,
3122
3046
  nodeExecutable: opts.launcher.executable,
3123
- // Launch the pack's loopback wrapper rather than the remapped
3124
- // `bridge.mjs`, which stays byte-identical so the recipe compare holds.
3047
+ // Launch the loopback/resolution wrapper (the Inspector layer's, or a
3048
+ // legacy pack's) rather than `bridge.mjs` directly.
3125
3049
  bridgeLauncherPath: opts.runtime.launcherPath,
3126
3050
  // The framework's default working directory (and the bridge's cwd), in
3127
3051
  // the shape the adapter composes with. `confine` turns it native.
@@ -3132,7 +3056,8 @@ function createSupervisedLocalHarnessProvider(opts) {
3132
3056
  // `--workdir` and `--bridge-state-dir`, which nothing downstream would
3133
3057
  // otherwise check: they are consumed by the child, not by a filesystem
3134
3058
  // call we make.
3135
- confine
3059
+ confine,
3060
+ confineToSessionState
3136
3061
  };
3137
3062
  const resolveForRead = async (path) => {
3138
3063
  const target = classifyBootstrapPath(path, translationContext);
@@ -3199,7 +3124,7 @@ function createSupervisedLocalHarnessProvider(opts) {
3199
3124
  // were confined to the synthetic home by the translator; no shell is
3200
3125
  // involved at any point.
3201
3126
  case "rename": {
3202
- await rename2(translated.from, translated.to);
3127
+ await rename(translated.from, translated.to);
3203
3128
  return { exitCode: 0, stdout: "", stderr: "" };
3204
3129
  }
3205
3130
  case "remove": {
@@ -3210,7 +3135,7 @@ function createSupervisedLocalHarnessProvider(opts) {
3210
3135
  }
3211
3136
  case "probe-absent": {
3212
3137
  try {
3213
- await stat3(translated.path);
3138
+ await stat2(translated.path);
3214
3139
  return { exitCode: 1, stdout: "", stderr: "" };
3215
3140
  } catch (error) {
3216
3141
  if (error.code === "ENOENT") {
@@ -3226,7 +3151,7 @@ function createSupervisedLocalHarnessProvider(opts) {
3226
3151
  return { exitCode: 0, stdout: "", stderr: "" };
3227
3152
  case "mkdir": {
3228
3153
  for (const path of translated.paths) {
3229
- await mkdir3(path, { recursive: true, mode: 448 });
3154
+ await mkdir2(path, { recursive: true, mode: 448 });
3230
3155
  }
3231
3156
  return { exitCode: 0, stdout: "", stderr: "" };
3232
3157
  }
@@ -3375,11 +3300,14 @@ function createSupervisedLocalHarnessProvider(opts) {
3375
3300
  if (isBridge) bridgeClaimed = false;
3376
3301
  };
3377
3302
  let handle;
3303
+ const aborted = () => (signal ?? abortSignal)?.aborted === true;
3304
+ let spawning = false;
3378
3305
  try {
3379
3306
  await assertRuntimeUnchanged();
3380
3307
  if (isBridge) {
3381
3308
  await assertBridgePortUnclaimed({ port: opts.bridgePort });
3382
3309
  }
3310
+ spawning = true;
3383
3311
  handle = await opts.supervisor.spawnSupervised({
3384
3312
  sessionId,
3385
3313
  executable: translated.executable,
@@ -3398,9 +3326,13 @@ function createSupervisedLocalHarnessProvider(opts) {
3398
3326
  });
3399
3327
  } catch (error) {
3400
3328
  releaseBridgeClaim();
3329
+ if (isBridge && spawning && !aborted()) {
3330
+ opts.onBridgeFailed?.({ phase: "spawn", message: error instanceof Error ? error.message : String(error) });
3331
+ }
3401
3332
  throw error;
3402
3333
  }
3403
3334
  if (isBridge) {
3335
+ let bridgeReady = false;
3404
3336
  try {
3405
3337
  await assertBridgeLoopbackOnly({
3406
3338
  port: opts.bridgePort,
@@ -3413,6 +3345,7 @@ function createSupervisedLocalHarnessProvider(opts) {
3413
3345
  // after our bridge died is somebody else's.
3414
3346
  isBridgeAlive: async () => opts.supervisor.liveProcessCount(sessionId) > 0
3415
3347
  });
3348
+ bridgeReady = true;
3416
3349
  if (opts.onBridgeStarted) {
3417
3350
  await opts.onBridgeStarted({
3418
3351
  pid: handle.pid,
@@ -3431,6 +3364,12 @@ function createSupervisedLocalHarnessProvider(opts) {
3431
3364
  ).catch(() => "no diagnosis could be read");
3432
3365
  error.message = `${error.message} (bridge: ${said})`;
3433
3366
  }
3367
+ if (!bridgeReady && !aborted()) {
3368
+ opts.onBridgeFailed?.({
3369
+ phase: "readiness",
3370
+ message: error instanceof Error ? error.message : String(error)
3371
+ });
3372
+ }
3434
3373
  throw error;
3435
3374
  }
3436
3375
  }
@@ -3514,7 +3453,7 @@ function createSupervisedLocalHarnessProvider(opts) {
3514
3453
  async function removeSessionStateDir(dir) {
3515
3454
  const root = resolve2(`${localHarnessStateRoot()}-sessions`);
3516
3455
  const target = resolve2(dir);
3517
- if (target === root || !target.startsWith(root + sep4)) {
3456
+ if (target === root || !target.startsWith(root + sep3)) {
3518
3457
  logger.warn("[local-harness] refusing to remove state outside the root", {
3519
3458
  dir
3520
3459
  });
@@ -3530,27 +3469,27 @@ function sessionStateDirFor(stateRoot, sessionId) {
3530
3469
  )} is not a single safe path segment`
3531
3470
  );
3532
3471
  }
3533
- return join3(`${stateRoot}-sessions`, sessionId);
3472
+ return join2(`${stateRoot}-sessions`, sessionId);
3534
3473
  }
3535
3474
 
3536
3475
  // server/utils/harness/local/supervisor.ts
3537
3476
  import { spawn } from "child_process";
3538
- import { mkdir as mkdir5, chmod as chmod4 } from "fs/promises";
3477
+ import { mkdir as mkdir4, chmod as chmod3 } from "fs/promises";
3539
3478
  import { isAbsolute as isAbsolute4 } from "path";
3540
3479
 
3541
3480
  // server/utils/harness/local/process-registry.ts
3542
- import { randomUUID as randomUUID3 } from "crypto";
3481
+ import { randomUUID as randomUUID2 } from "crypto";
3543
3482
  import {
3544
- mkdir as mkdir4,
3545
- readFile as readFile5,
3546
- rename as rename3,
3547
- writeFile as writeFile3,
3548
- chmod as chmod3,
3483
+ mkdir as mkdir3,
3484
+ readFile as readFile4,
3485
+ rename as rename2,
3486
+ writeFile as writeFile2,
3487
+ chmod as chmod2,
3549
3488
  rm as rm2
3550
3489
  } from "fs/promises";
3551
- import { join as join4, resolve as resolve3, sep as sep5 } from "path";
3490
+ import { join as join3, resolve as resolve3, sep as sep4 } from "path";
3552
3491
  function registryPath() {
3553
- return join4(localHarnessStateRoot(), "processes.json");
3492
+ return join3(localHarnessStateRoot(), "processes.json");
3554
3493
  }
3555
3494
  var withRegistryLock = createLocalStateMutationLock({
3556
3495
  rootDir: localHarnessStateRoot,
@@ -3562,7 +3501,7 @@ var RegistryUnreadableError = class extends Error {
3562
3501
  async function readRegistry() {
3563
3502
  let raw;
3564
3503
  try {
3565
- raw = await readFile5(registryPath(), "utf8");
3504
+ raw = await readFile4(registryPath(), "utf8");
3566
3505
  } catch (error) {
3567
3506
  if (error.code === "ENOENT") {
3568
3507
  return { version: 1, records: [] };
@@ -3594,16 +3533,16 @@ async function readRegistry() {
3594
3533
  }
3595
3534
  async function writeRegistry(registry) {
3596
3535
  const dir = localHarnessStateRoot();
3597
- await mkdir4(dir, { recursive: true, mode: 448 });
3598
- await chmod3(dir, 448).catch(() => {
3536
+ await mkdir3(dir, { recursive: true, mode: 448 });
3537
+ await chmod2(dir, 448).catch(() => {
3599
3538
  });
3600
3539
  const file = registryPath();
3601
3540
  const tmp = `${file}.tmp`;
3602
- await writeFile3(tmp, JSON.stringify(registry), { mode: 384 });
3603
- await rename3(tmp, file);
3541
+ await writeFile2(tmp, JSON.stringify(registry), { mode: 384 });
3542
+ await rename2(tmp, file);
3604
3543
  }
3605
3544
  function mintSupervisorNonce() {
3606
- return `sup_${randomUUID3()}`;
3545
+ return `sup_${randomUUID2()}`;
3607
3546
  }
3608
3547
  function recordProcess(record) {
3609
3548
  return withRegistryLock(async () => {
@@ -3654,7 +3593,7 @@ function janitorOutcomeForUnsettled(outcome) {
3654
3593
  async function removeSessionState(dir) {
3655
3594
  const root = resolve3(`${localHarnessStateRoot()}-sessions`);
3656
3595
  const target = resolve3(dir);
3657
- if (target === root || !target.startsWith(root + sep5)) {
3596
+ if (target === root || !target.startsWith(root + sep4)) {
3658
3597
  logger.warn("[local-harness] refusing to clean state outside the root", {
3659
3598
  dir
3660
3599
  });
@@ -3886,8 +3825,8 @@ var LocalHarnessSupervisor = class {
3886
3825
  }
3887
3826
  /** Create a directory inside the session's own state, owner-only. */
3888
3827
  async ensureDirectory(path) {
3889
- await mkdir5(path, { recursive: true, mode: 448 });
3890
- await chmod4(path, 448).catch(() => {
3828
+ await mkdir4(path, { recursive: true, mode: 448 });
3829
+ await chmod3(path, 448).catch(() => {
3891
3830
  });
3892
3831
  }
3893
3832
  /**
@@ -4343,140 +4282,80 @@ var LocalHarnessSupervisor = class {
4343
4282
  }
4344
4283
  };
4345
4284
 
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
4285
  // server/utils/harness/local/local-turn.ts
4455
- import { join as join5 } from "path";
4456
- import { mkdir as mkdir6, stat as stat4 } from "fs/promises";
4286
+ import { join as join4 } from "path";
4287
+ import { mkdir as mkdir5, stat as stat3 } from "fs/promises";
4457
4288
  import { createRequire } from "module";
4458
4289
  var sharedSupervisor = null;
4459
4290
  function localHarnessSupervisor() {
4460
4291
  sharedSupervisor ??= new LocalHarnessSupervisor();
4461
4292
  return sharedSupervisor;
4462
4293
  }
4294
+ var LOCAL_HARNESS_DISPLAY_NAME = {
4295
+ "claude-code": "Claude Code",
4296
+ codex: "Codex"
4297
+ };
4298
+ function asLocalHarnessId(harnessId) {
4299
+ return SUPPORTED_LOCAL_HARNESS_IDS.includes(harnessId) ? harnessId : null;
4300
+ }
4301
+ function localChildAuth(harnessId, gateway) {
4302
+ switch (harnessId) {
4303
+ case "claude-code":
4304
+ return {
4305
+ ANTHROPIC_AUTH_TOKEN: gateway.sessionCapability,
4306
+ ANTHROPIC_API_KEY: gateway.sessionCapability,
4307
+ ANTHROPIC_BASE_URL: gateway.baseUrl
4308
+ };
4309
+ case "codex":
4310
+ return {
4311
+ CODEX_API_KEY: gateway.sessionCapability,
4312
+ OPENAI_BASE_URL: gateway.baseUrl
4313
+ };
4314
+ }
4315
+ }
4316
+ var LOCAL_SKILLS_SUBDIR = {
4317
+ "claude-code": [".claude", "skills"],
4318
+ codex: [".agents", "skills"]
4319
+ };
4463
4320
  async function prepareLocalHarnessTurn(args) {
4464
- validateLocalHarnessSecretEnv(args.scopedEnv ?? {});
4321
+ const harnessId = asLocalHarnessId(args.harnessId);
4322
+ if (harnessId === null) {
4323
+ return {
4324
+ ok: false,
4325
+ status: "harness-not-supported",
4326
+ message: `${args.harnessId} cannot run on this machine.`
4327
+ };
4328
+ }
4329
+ validateLocalHarnessSecretEnv(args.scopedEnv ?? {}, harnessId);
4330
+ const displayName = LOCAL_HARNESS_DISPLAY_NAME[harnessId];
4331
+ if (args.approvalContinuation) {
4332
+ return adoptParkedLocalTurn(args, harnessId);
4333
+ }
4334
+ if (hasParkedLocalSession(args.sessionId)) {
4335
+ await invalidateParkedLocalSession(args.sessionId, "superseded");
4336
+ }
4337
+ if (args.scope !== "unattended" && args.requireToolApproval === false) {
4338
+ const authorization = await readLocalHarnessAuthorization(args.target.actingUserId, args.target.machineId, args.projectId, harnessId);
4339
+ if (!authorization?.autoApproveAcknowledgedAt) {
4340
+ return { ok: false, status: "auto-approve-consent-required", message: "Allow commands without asking before turning Tool Approval off on this computer." };
4341
+ }
4342
+ }
4465
4343
  const verifyStartedAt = Date.now();
4466
4344
  const runtimeStatus = await readRuntimeInstallStatus({
4467
- harnessId: "claude-code"
4345
+ harnessId,
4346
+ preferRuntimeId: args.target.runtimeId
4468
4347
  });
4469
4348
  if (runtimeStatus.state !== "ready") {
4470
4349
  return {
4471
4350
  ok: false,
4472
4351
  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}).`
4352
+ message: runtimeStatus.state === "absent" ? `The local ${displayName} runtime is not installed on this machine yet.` : runtimeStatus.state === "revoked" ? runtimeStatus.message : `The local ${displayName} runtime is not usable (${runtimeStatus.state}).`
4474
4353
  };
4475
4354
  }
4476
4355
  const target = localPackTarget();
4477
4356
  const lifecycleKey = target === null ? null : {
4478
4357
  runtimeRoot: runtimeInstallRoot(),
4479
- harnessId: "claude-code",
4358
+ harnessId,
4480
4359
  target,
4481
4360
  packVersion: runtimeStatus.packVersion,
4482
4361
  treeDigest: runtimeStatus.digest
@@ -4505,6 +4384,7 @@ async function prepareLocalHarnessTurn(args) {
4505
4384
  try {
4506
4385
  const prepared = await prepareWithReservedRuntime({
4507
4386
  args,
4387
+ harnessId,
4508
4388
  runtimeStatus,
4509
4389
  verifyStartedAt,
4510
4390
  releaseRuntimeUse
@@ -4518,6 +4398,7 @@ async function prepareLocalHarnessTurn(args) {
4518
4398
  }
4519
4399
  async function prepareWithReservedRuntime(outer) {
4520
4400
  const args = outer.args;
4401
+ const harnessId = outer.harnessId;
4521
4402
  const runtimeStatus = outer.runtimeStatus;
4522
4403
  const verifyStartedAt = outer.verifyStartedAt;
4523
4404
  const sessionStateDir = sessionStateDirFor(
@@ -4534,7 +4415,7 @@ async function prepareWithReservedRuntime(outer) {
4534
4415
  const availability = await resolveLocalHarnessAvailability({
4535
4416
  target: {
4536
4417
  kind: "local-native",
4537
- harnessId: args.harnessId,
4418
+ harnessId,
4538
4419
  machineId: args.target.machineId,
4539
4420
  workspaceGrantId: args.target.workspaceGrantId,
4540
4421
  runtimeId: args.target.runtimeId,
@@ -4549,7 +4430,8 @@ async function prepareWithReservedRuntime(outer) {
4549
4430
  projectId: args.projectId,
4550
4431
  grantToken: args.target.grantToken,
4551
4432
  runtimeRoot: runtimeStatus.runtimeRoot,
4552
- installedAdapterVersion: args.installedAdapterVersion ?? await readInstalledAdapterVersion()
4433
+ runtimeDigest: runtimeStatus.digest,
4434
+ installedAdapterVersion: args.installedAdapterVersion ?? await readInstalledAdapterVersion(harnessId)
4553
4435
  });
4554
4436
  if (!availability.available) {
4555
4437
  return {
@@ -4560,7 +4442,7 @@ async function prepareWithReservedRuntime(outer) {
4560
4442
  }
4561
4443
  const plan = availability.plan;
4562
4444
  const localRuntimeVerifyMs = Date.now() - verifyStartedAt;
4563
- const permissionMode = args.requireToolApproval ? "allow-reads" : plan.permissionMode;
4445
+ const permissionMode = args.scope !== "unattended" || args.requireToolApproval ? "allow-reads" : plan.permissionMode;
4564
4446
  const identity = await readLocalInstanceIdentity();
4565
4447
  const keyId = identity.keyId ?? getRegisteredKeyId();
4566
4448
  if (keyId === null) {
@@ -4583,6 +4465,7 @@ async function prepareWithReservedRuntime(outer) {
4583
4465
  keyId,
4584
4466
  runId: args.runId,
4585
4467
  ...args.maxOutputTokens !== void 0 ? { maxOutputTokens: args.maxOutputTokens } : {},
4468
+ ...args.reasoningEffort ? { reasoningEffort: args.reasoningEffort } : {},
4586
4469
  bearer: args.bearer,
4587
4470
  ...args.signal ? { signal: args.signal } : {}
4588
4471
  });
@@ -4595,14 +4478,15 @@ async function prepareWithReservedRuntime(outer) {
4595
4478
  }
4596
4479
  const supervisor = localHarnessSupervisor();
4597
4480
  let gateway = null;
4481
+ let currentRunId = broker.runId;
4598
4482
  try {
4599
- const sessionStateExists = await stat4(sessionStateDir).then((entry) => entry.isDirectory()).catch((error) => {
4483
+ const sessionStateExists = await stat3(sessionStateDir).then((entry) => entry.isDirectory()).catch((error) => {
4600
4484
  if (error.code === "ENOENT") return false;
4601
4485
  throw error;
4602
4486
  });
4603
- await mkdir6(sessionStateDir, { recursive: true, mode: 448 });
4604
- const hooksPath = join5(sessionStateDir, "empty-git-hooks");
4605
- if (args.scope === "unattended") await mkdir6(hooksPath, { recursive: true, mode: 448 });
4487
+ await mkdir5(sessionStateDir, { recursive: true, mode: 448 });
4488
+ const hooksPath = join4(sessionStateDir, "empty-git-hooks");
4489
+ if (args.scope === "unattended") await mkdir5(hooksPath, { recursive: true, mode: 448 });
4606
4490
  const gatewayStartedAt = Date.now();
4607
4491
  try {
4608
4492
  gateway = await startLocalModelGateway({
@@ -4631,7 +4515,7 @@ async function prepareWithReservedRuntime(outer) {
4631
4515
  bundledNodePath: plan.runtime.nodePath ?? ""
4632
4516
  });
4633
4517
  const sandbox = createSupervisedLocalHarnessProvider({
4634
- harnessId: "claude-code",
4518
+ harnessId,
4635
4519
  manifest: plan.manifest,
4636
4520
  runtime: plan.runtime,
4637
4521
  supervisor,
@@ -4639,11 +4523,17 @@ async function prepareWithReservedRuntime(outer) {
4639
4523
  workspacePath: plan.workspacePath,
4640
4524
  workspaceGrantId: plan.target.workspaceGrantId,
4641
4525
  sessionStateDir,
4642
- ...args.onSecretEnvDelivered && Object.keys(args.scopedEnv ?? {}).length ? {
4643
- onBridgeStarted: async () => {
4644
- args.onSecretEnvDelivered?.();
4645
- }
4646
- } : {},
4526
+ onBridgeStarted: async () => {
4527
+ void noteRuntimeLaunch({ harnessId, status: runtimeStatus, outcome: { ok: true } });
4528
+ if (Object.keys(args.scopedEnv ?? {}).length) args.onSecretEnvDelivered?.();
4529
+ },
4530
+ onBridgeFailed: ({ phase, message }) => {
4531
+ void noteRuntimeLaunch({
4532
+ harnessId,
4533
+ status: runtimeStatus,
4534
+ outcome: { ok: false, reason: `${phase}: ${message.slice(0, 300)}` }
4535
+ });
4536
+ },
4647
4537
  targetKind: "local-native",
4648
4538
  bridgePort,
4649
4539
  scopedEnv: {
@@ -4651,6 +4541,7 @@ async function prepareWithReservedRuntime(outer) {
4651
4541
  ...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
4542
  }
4653
4543
  });
4544
+ let leaseBearer = args.bearer;
4654
4545
  const sessionRecord = {
4655
4546
  userId: args.target.actingUserId,
4656
4547
  projectId: args.projectId,
@@ -4660,8 +4551,11 @@ async function prepareWithReservedRuntime(outer) {
4660
4551
  brokerRunId: broker.runId,
4661
4552
  gateway: started,
4662
4553
  stop: async () => await supervisor.stopSession(args.sessionId),
4663
- revokeLease: () => revokeLease(broker.runId, args.bearer),
4554
+ revokeLease: () => revokeLease(currentRunId, leaseBearer),
4664
4555
  releaseRuntime: outer.releaseRuntimeUse,
4556
+ // A Stop, stop-all, workspace or project stop ends a parked session
4557
+ // through this registry; the parked record must stop answering at once.
4558
+ onEnded: () => noteParkedLocalSessionEnded(args.sessionId),
4665
4559
  startedAt: Date.now()
4666
4560
  };
4667
4561
  let treeStopped = false;
@@ -4670,7 +4564,7 @@ async function prepareWithReservedRuntime(outer) {
4670
4564
  started.revoke();
4671
4565
  await started.close();
4672
4566
  } finally {
4673
- await revokeLease(broker.runId, args.bearer);
4567
+ await revokeLease(currentRunId, leaseBearer);
4674
4568
  const stop = await supervisor.stopSession(args.sessionId);
4675
4569
  if (stop.stopped) {
4676
4570
  treeStopped = true;
@@ -4687,33 +4581,64 @@ async function prepareWithReservedRuntime(outer) {
4687
4581
  localRuntimeVerifyMs,
4688
4582
  localGatewayReadyMs
4689
4583
  });
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
4584
+ const live = {
4585
+ prepared: void 0,
4586
+ userId: args.target.actingUserId,
4587
+ projectId: args.projectId,
4588
+ runtimeId: plan.runtime.runtimeId,
4589
+ workspaceGrantId: plan.target.workspaceGrantId,
4590
+ rebindLease: (next) => {
4591
+ started.rebind(next.lease);
4592
+ currentRunId = next.runId;
4593
+ leaseBearer = next.bearer;
4594
+ sessionRecord.brokerRunId = next.runId;
4595
+ },
4596
+ revokeCurrentLease: () => revokeLease(currentRunId, leaseBearer)
4597
+ };
4598
+ const prepared = {
4599
+ plan,
4600
+ sandbox,
4601
+ auth: localChildAuth(harnessId, started),
4602
+ sandboxWorkDir: "project",
4603
+ skillsBaseDir: toAdapterPath(
4604
+ join4(sessionStateDir, "home", ...LOCAL_SKILLS_SUBDIR[harnessId])
4605
+ ),
4606
+ sessionStateExists,
4607
+ permissionMode,
4608
+ brokerRunId: broker.runId,
4609
+ timings: { localRuntimeVerifyMs, localGatewayReadyMs },
4610
+ teardown: teardownOnce,
4611
+ discardState: onceAsync(async () => {
4612
+ await teardownOnce();
4613
+ if (treeStopped) await removeSessionStateDir(sessionStateDir);
4614
+ }),
4615
+ park: (parkArgs) => parkLocalSession({
4616
+ sessionId: args.sessionId,
4617
+ generation: parkArgs.generation,
4618
+ userId: args.target.actingUserId,
4619
+ projectId: args.projectId,
4620
+ pendingApprovalIds: parkArgs.pendingApprovalIds,
4621
+ resources: live,
4622
+ ...parkArgs.ttlMs !== void 0 ? { ttlMs: parkArgs.ttlMs } : {},
4623
+ // ONE owner for cleanup: the registry, which revokes the gateway and
4624
+ // the lease, stops the tree and releases the runtime together.
4625
+ end: async (reason) => {
4626
+ logger.info("[local-harness] ending parked session", {
4627
+ sessionId: args.sessionId,
4628
+ reason
4629
+ });
4630
+ await endLocalHarnessSession(args.sessionId);
4701
4631
  },
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
- }
4632
+ isAlive: () => supervisor.liveProcessCount(args.sessionId) > 0,
4633
+ holdModelTraffic: () => {
4634
+ started.hold();
4635
+ void revokeLease(currentRunId, leaseBearer);
4636
+ }
4637
+ }),
4638
+ unpark: () => releaseParkedLocalSession(args.sessionId)
4716
4639
  };
4640
+ live.prepared = prepared;
4641
+ return { ok: true, prepared };
4717
4642
  } catch (error) {
4718
4643
  await abandonLocalSetup({
4719
4644
  gateway,
@@ -4724,6 +4649,138 @@ async function prepareWithReservedRuntime(outer) {
4724
4649
  throw error;
4725
4650
  }
4726
4651
  }
4652
+ async function adoptParkedLocalTurn(args, harnessId) {
4653
+ const continuation = args.approvalContinuation;
4654
+ const claim = claimParkedLocalSession({
4655
+ sessionId: args.sessionId,
4656
+ generation: continuation.generation,
4657
+ userId: args.target.actingUserId,
4658
+ projectId: args.projectId,
4659
+ approvalIds: continuation.approvalIds
4660
+ });
4661
+ if (!claim.ok) {
4662
+ return { ok: false, status: `approval-${claim.reason}`, message: claim.message };
4663
+ }
4664
+ const live = claim.parked.resources;
4665
+ const fail = async (reason, status, message) => {
4666
+ await invalidateParkedLocalSession(args.sessionId, reason);
4667
+ return { ok: false, status, message };
4668
+ };
4669
+ const verifyStartedAt = Date.now();
4670
+ const runtimeStatus = await readRuntimeInstallStatus({
4671
+ harnessId,
4672
+ preferRuntimeId: args.target.runtimeId
4673
+ });
4674
+ if (runtimeStatus.state !== "ready") {
4675
+ return fail(
4676
+ "authorization-revoked",
4677
+ "runtime-unavailable",
4678
+ "The local runtime holding this approval is no longer installed; the pending action will not run."
4679
+ );
4680
+ }
4681
+ const availability = await resolveLocalHarnessAvailability({
4682
+ target: {
4683
+ kind: "local-native",
4684
+ harnessId,
4685
+ machineId: args.target.machineId,
4686
+ workspaceGrantId: args.target.workspaceGrantId,
4687
+ runtimeId: args.target.runtimeId,
4688
+ permissionProfile: args.target.permissionProfile,
4689
+ policyVersion: args.target.policyVersion
4690
+ },
4691
+ actor: args.actor,
4692
+ scope: args.scope,
4693
+ userId: args.target.actingUserId,
4694
+ projectId: args.projectId,
4695
+ grantToken: args.target.grantToken,
4696
+ runtimeRoot: runtimeStatus.runtimeRoot,
4697
+ runtimeDigest: runtimeStatus.digest,
4698
+ installedAdapterVersion: args.installedAdapterVersion ?? await readInstalledAdapterVersion(harnessId)
4699
+ });
4700
+ if (!availability.available) {
4701
+ return fail("authorization-revoked", availability.status, availability.message);
4702
+ }
4703
+ const plan = availability.plan;
4704
+ if (plan.runtime.runtimeId !== live.runtimeId || plan.target.workspaceGrantId !== live.workspaceGrantId) {
4705
+ return fail(
4706
+ "authorization-revoked",
4707
+ "approval-runtime-changed",
4708
+ "The runtime or workspace changed while this approval was waiting; the pending action will not run."
4709
+ );
4710
+ }
4711
+ const permissionMode = args.scope !== "unattended" || args.requireToolApproval ? "allow-reads" : plan.permissionMode;
4712
+ if (permissionMode !== live.prepared.permissionMode) {
4713
+ return fail(
4714
+ "authorization-revoked",
4715
+ "approval-permission-changed",
4716
+ "The permission this session was approved under changed while the approval was waiting; the pending action will not run."
4717
+ );
4718
+ }
4719
+ const identity = await readLocalInstanceIdentity();
4720
+ const keyId = identity.keyId ?? getRegisteredKeyId();
4721
+ if (keyId === null) {
4722
+ return fail(
4723
+ "authorization-revoked",
4724
+ "consent-required",
4725
+ "This installation is no longer registered for local execution."
4726
+ );
4727
+ }
4728
+ const gatewayStartedAt = Date.now();
4729
+ const broker = await startLoopbackModelBroker({
4730
+ projectId: args.projectId,
4731
+ evalIterationId: args.evalIterationId,
4732
+ journeyRunId: args.journeyRunId,
4733
+ targetId: args.targetId,
4734
+ sessionIdx: args.sessionIdx,
4735
+ hostId: args.hostId,
4736
+ harnessId: args.harnessId,
4737
+ modelId: args.modelId,
4738
+ machineId: identity.machineId,
4739
+ keyId,
4740
+ runId: args.runId,
4741
+ ...args.maxOutputTokens !== void 0 ? { maxOutputTokens: args.maxOutputTokens } : {},
4742
+ bearer: args.bearer,
4743
+ ...args.signal ? { signal: args.signal } : {}
4744
+ });
4745
+ if (!broker.ok) {
4746
+ return fail("renewal-failed", "broker-unavailable", broker.error);
4747
+ }
4748
+ if (claim.parked.state !== "continuing" || !claim.parked.isAlive()) {
4749
+ await revokeLease(broker.runId, args.bearer);
4750
+ return fail(
4751
+ "process-died",
4752
+ "approval-process-died",
4753
+ "The local runtime holding this approval stopped while the decision was being delivered; the pending action will not run."
4754
+ );
4755
+ }
4756
+ try {
4757
+ live.rebindLease({ runId: broker.runId, lease: broker.lease, bearer: args.bearer });
4758
+ } catch (error) {
4759
+ await revokeLease(broker.runId, args.bearer);
4760
+ return fail(
4761
+ "renewal-failed",
4762
+ "gateway-unavailable",
4763
+ `The renewed model lease could not be bound: ${error instanceof Error ? error.message : String(error)}`
4764
+ );
4765
+ }
4766
+ logger.info("[local-harness] parked session re-adopted for an approval", {
4767
+ sessionId: args.sessionId,
4768
+ approvals: continuation.approvalIds.length
4769
+ });
4770
+ return {
4771
+ ok: true,
4772
+ prepared: {
4773
+ ...live.prepared,
4774
+ plan,
4775
+ sessionStateExists: true,
4776
+ brokerRunId: broker.runId,
4777
+ timings: {
4778
+ localRuntimeVerifyMs: gatewayStartedAt - verifyStartedAt,
4779
+ localGatewayReadyMs: Date.now() - gatewayStartedAt
4780
+ }
4781
+ }
4782
+ };
4783
+ }
4727
4784
  async function abandonLocalSetup(args) {
4728
4785
  try {
4729
4786
  args.gateway?.revoke();
@@ -4746,7 +4803,8 @@ async function revokeLease(runId, bearer) {
4746
4803
  }
4747
4804
  }
4748
4805
  var cachedAdapterVersion = null;
4749
- async function readInstalledAdapterVersion() {
4806
+ async function readInstalledAdapterVersion(harnessId) {
4807
+ if (harnessId === "codex") return CODEX_LOCAL_ADAPTER_IDENTITY;
4750
4808
  if (cachedAdapterVersion !== null) return cachedAdapterVersion;
4751
4809
  if (typeof __MCPJAM_CLAUDE_ADAPTER_VERSION__ === "string") return __MCPJAM_CLAUDE_ADAPTER_VERSION__;
4752
4810
  try {
@@ -4767,16 +4825,6 @@ function onceAsync(fn) {
4767
4825
  }
4768
4826
 
4769
4827
  export {
4770
- LOCAL_HARNESS_GRANT_HEADER,
4771
- localHarnessStateRoot,
4772
- getLocalMachineId,
4773
- validateWorkspaceCandidate,
4774
- registerWorkspaceGrant,
4775
- resolveWorkspaceGrant,
4776
- grantLocalHarnessConsent,
4777
- revokeLocalHarnessGrants,
4778
- pruneExpiredHarnessGrants,
4779
- forgetWorkspaceGrant,
4780
4828
  listProcessRecords,
4781
4829
  harnessPinnedVersion,
4782
4830
  harnessModelSupport,
@@ -4790,12 +4838,10 @@ export {
4790
4838
  readLocalInstanceIdentity,
4791
4839
  setRegisteredKeyId,
4792
4840
  instanceKeyFingerprint,
4841
+ invalidateParkedLocalSession,
4793
4842
  resolveGitBashPath,
4794
4843
  sessionStateDirFor,
4795
- stopAllLocalHarnessSessions,
4796
- stopLocalHarnessWorkspace,
4797
- stopLocalHarnessProject,
4798
4844
  localHarnessSupervisor,
4799
4845
  prepareLocalHarnessTurn
4800
4846
  };
4801
- //# sourceMappingURL=chunk-DGAFFBDM.js.map
4847
+ //# sourceMappingURL=chunk-KNO4KZJF.js.map