@primitive.ai/prim 0.1.0-alpha.126 → 0.1.0-alpha.128

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 (45) hide show
  1. package/README.md +211 -1
  2. package/SKILL.md +6 -1
  3. package/dist/{chunk-ZKXNJB6U.js → chunk-3KPTVK4N.js} +70 -78
  4. package/dist/{chunk-6KXQQ7CQ.js → chunk-4DYEBYKM.js} +3 -5
  5. package/dist/{chunk-NJBN3WXF.js → chunk-6QAXVFRJ.js} +1900 -179
  6. package/dist/{chunk-R6NDP7OF.js → chunk-ANMNGGTN.js} +2 -2
  7. package/dist/{chunk-PPZ56EVJ.js → chunk-B3ICJZXV.js} +4 -2
  8. package/dist/{chunk-5D2C6RCH.js → chunk-C357P37M.js} +4 -4
  9. package/dist/{chunk-DT7E3SD5.js → chunk-E57UVUJL.js} +6 -6
  10. package/dist/{chunk-KKUDAQQZ.js → chunk-EQWUCFXK.js} +3 -3
  11. package/dist/{chunk-JFWJN2ME.js → chunk-M6KIDB5R.js} +119 -5
  12. package/dist/{chunk-NBNQI3YJ.js → chunk-N6PZE7HX.js} +6 -3
  13. package/dist/{chunk-O73J3KQQ.js → chunk-NYDM4HSS.js} +8 -5
  14. package/dist/{chunk-74DQDWLW.js → chunk-P4O7L7JZ.js} +7 -2
  15. package/dist/{chunk-L32WYFJT.js → chunk-PRJ7P6J5.js} +135 -12
  16. package/dist/{chunk-ND6TYHNI.js → chunk-PTZ6BWSU.js} +2 -2
  17. package/dist/{chunk-BFYJLI7V.js → chunk-QQ3G5SXX.js} +1 -1
  18. package/dist/{chunk-EZXIKEMA.js → chunk-RDT2IV2Z.js} +9 -7
  19. package/dist/{chunk-TI37ME2D.js → chunk-VLT2KGPE.js} +47 -38
  20. package/dist/{chunk-YP4OXKNX.js → chunk-WEGZGF3K.js} +1 -1
  21. package/dist/{chunk-C5VBPHOS.js → chunk-XINFTNA2.js} +23 -9
  22. package/dist/{chunk-FYYHBOOM.js → chunk-ZCT23NBS.js} +2 -2
  23. package/dist/daemon/server.js +1976 -442
  24. package/dist/hook-runtime/daemon/server.js +1976 -442
  25. package/dist/hook-runtime/hooks/post-commit.js +592 -212
  26. package/dist/hook-runtime/hooks/post-rewrite.js +584 -204
  27. package/dist/hook-runtime/hooks/post-tool-use.js +1997 -575
  28. package/dist/hook-runtime/hooks/pre-commit.js +1742 -350
  29. package/dist/hook-runtime/hooks/pre-tool-use-worker.js +1656 -261
  30. package/dist/hook-runtime/hooks/prim-hook.js +1992 -573
  31. package/dist/hook-runtime/hooks/session-end.js +549 -180
  32. package/dist/hook-runtime/hooks/session-start.js +2213 -596
  33. package/dist/hook-runtime/index.js +5318 -2423
  34. package/dist/hook-runtime/statusline-main.js +531 -150
  35. package/dist/hooks/post-commit.js +7 -7
  36. package/dist/hooks/post-rewrite.js +6 -6
  37. package/dist/hooks/post-tool-use.js +18 -18
  38. package/dist/hooks/pre-commit.js +4 -4
  39. package/dist/hooks/pre-tool-use-worker.js +14 -15
  40. package/dist/hooks/prim-hook.js +16 -16
  41. package/dist/hooks/session-end.js +4 -4
  42. package/dist/hooks/session-start.js +95 -21
  43. package/dist/index.js +1386 -299
  44. package/dist/statusline-main.js +531 -150
  45. package/package.json +1 -1
@@ -54,25 +54,34 @@ var require_ucs2length = __commonJS({
54
54
 
55
55
  // src/hooks/prim-hook.ts
56
56
  import { spawn as spawn2 } from "child_process";
57
- import { readFileSync as readFileSync21 } from "fs";
58
- import { dirname as dirname15, join as join25 } from "path";
57
+ import { readFileSync as readFileSync23 } from "fs";
58
+ import { dirname as dirname15, join as join28 } from "path";
59
59
  import { fileURLToPath as fileURLToPath5 } from "url";
60
60
 
61
61
  // src/binding.ts
62
- import { existsSync as existsSync4, readFileSync as readFileSync7 } from "fs";
63
- import { dirname as dirname5, join as join8 } from "path";
62
+ import { existsSync as existsSync4, readFileSync as readFileSync8 } from "fs";
63
+ import { dirname as dirname6, join as join10 } from "path";
64
64
 
65
65
  // src/lib/credentials.ts
66
- import { createHash as createHash4 } from "crypto";
67
- import { readFileSync as readFileSync6 } from "fs";
68
- import { join as join7 } from "path";
66
+ import { createHash as createHash6 } from "crypto";
67
+ import { readFileSync as readFileSync7 } from "fs";
68
+ import { join as join9 } from "path";
69
69
 
70
70
  // src/lib/machine-credentials.ts
71
- import { execFileSync } from "child_process";
72
- import { createHash as createHash3, randomUUID as randomUUID2 } from "crypto";
73
- import { chmodSync, existsSync as existsSync3, lstatSync as lstatSync3, mkdirSync as mkdirSync3, readFileSync as readFileSync5, rmSync as rmSync5 } from "fs";
71
+ import { execFileSync as execFileSync2 } from "child_process";
72
+ import { createHash as createHash5, randomBytes as randomBytes3, randomUUID as randomUUID2 } from "crypto";
73
+ import {
74
+ chmodSync,
75
+ existsSync as existsSync3,
76
+ linkSync,
77
+ lstatSync as lstatSync4,
78
+ mkdirSync as mkdirSync3,
79
+ readFileSync as readFileSync6,
80
+ rmSync as rmSync6,
81
+ writeFileSync as writeFileSync3
82
+ } from "fs";
74
83
  import { createRequire } from "module";
75
- import { dirname as dirname4, join as join6 } from "path";
84
+ import { dirname as dirname5, join as join8 } from "path";
76
85
  import { fileURLToPath as fileURLToPath3 } from "url";
77
86
 
78
87
  // src/lib/atomic-file.ts
@@ -389,6 +398,7 @@ var PRIM_CONFIG_SHELL_RESOLVER = [
389
398
  'else prim_home=${HOME:-}; prim_absolute "$prim_home" || exit 78; case "$prim_home" in /) prim_config=/.config/prim ;; *) prim_config="$prim_home/.config/prim" ;; esac; ',
390
399
  "fi; fi; "
391
400
  ].join("");
401
+ var LAUNCHER_EXEC = 'exec "$prim_launcher" "$@"';
392
402
  function stableHookCommand(bin, args = "") {
393
403
  if (!STABLE_HOOK_BIN_RE.test(bin) || !STABLE_HOOK_ARGUMENTS_RE.test(args)) {
394
404
  throw new Error("invalid stable hook command");
@@ -400,7 +410,7 @@ function stableHookCommand(bin, args = "") {
400
410
  `prim_legacy_reader='-p ${PKG_NAME}@stable prim-shim.sh ${bin} '; `,
401
411
  PRIM_CONFIG_SHELL_RESOLVER,
402
412
  `case "$prim_config" in /) prim_launcher=/${STABLE_HOOK_LAUNCHER_NAME} ;; *) prim_launcher="$prim_config/${STABLE_HOOK_LAUNCHER_NAME}" ;; esac; `,
403
- 'exec "$prim_launcher" "$@"'
413
+ LAUNCHER_EXEC
404
414
  ].join("");
405
415
  const suffix = args ? ` ${args}` : "";
406
416
  return `/bin/sh -c ${shellQuote(resolver)} ${STABLE_HOOK_LAUNCHER_NAME} ${bin}${suffix}`;
@@ -409,6 +419,49 @@ function detachedHookShimCommand(bin, args = "") {
409
419
  return `payload=$(cat); { trap '' HUP; printf '%s' "$payload" | { ${stableHookCommand(bin, args)}; }; } </dev/null >/dev/null 2>&1 &`;
410
420
  }
411
421
 
422
+ // src/lib/loopback-fetch.ts
423
+ import { request } from "http";
424
+ import { Readable } from "stream";
425
+ function loopbackFetch(url, init = {}) {
426
+ const target = new URL(url);
427
+ if (target.protocol !== "http:" || !["127.0.0.1", "[::1]", "localhost"].includes(target.hostname))
428
+ return Promise.reject(new Error(`not a loopback URL: ${url}`));
429
+ return new Promise((resolve9, reject) => {
430
+ const outgoing = request(
431
+ target,
432
+ { method: init.method ?? "GET", headers: init.headers, agent: false, signal: init.signal },
433
+ (incoming) => {
434
+ try {
435
+ const headers = new Headers();
436
+ for (const [name2, value] of Object.entries(incoming.headers))
437
+ if (typeof value === "string") headers.set(name2, value);
438
+ const status = incoming.statusCode ?? 502;
439
+ const body = [101, 204, 205, 304].includes(status) ? null : Readable.toWeb(incoming);
440
+ resolve9(new Response(body, { status, headers }));
441
+ } catch (error) {
442
+ incoming.destroy();
443
+ reject(error);
444
+ }
445
+ }
446
+ );
447
+ outgoing.once("error", reject);
448
+ outgoing.end(init.body);
449
+ });
450
+ }
451
+
452
+ // src/lib/cloud-env.ts
453
+ function isClaudeCloudSession(env = process.env) {
454
+ return env.CLAUDE_CODE_REMOTE === "true";
455
+ }
456
+ var CLOUD_CREDENTIALS_REMEDY = 'give the cloud environment PRIM_M2M_CLIENT_ID and PRIM_M2M_CLIENT_SECRET, as variables or with the secret held as a network secret; mint them on your own machine with `prim auth enroll --new-installation "Claude Code cloud" --print-env`, which says where each value goes';
457
+ var CLOUD_REJECTED_CREDENTIALS_REMEDY = 'correct the credentials in the cloud environment\'s settings, or if the installation was revoked mint a replacement on your own machine with `prim auth enroll --new-installation "Claude Code cloud" --print-env`; then start a new cloud session';
458
+ var CLOUD_REJECTED_CREDENTIALS_NOTICE = `Primitive is not connected in this Claude Code cloud session: its credentials were rejected. To fix it, ${CLOUD_REJECTED_CREDENTIALS_REMEDY}.`;
459
+ var CLOUD_GITHUB_CONNECT_REMEDY = "run `prim github connect` in a clone of it on your own machine, then start a new cloud session";
460
+ function cloudSetupPointer(message, env = process.env) {
461
+ return isClaudeCloudSession(env) ? `${message.replace(/[.;\s]+$/u, "")}${CLOUD_SETUP_POINTER}` : message;
462
+ }
463
+ var CLOUD_SETUP_POINTER = "; in this Claude Code cloud session, run `prim setup --cloud` for the fix";
464
+
412
465
  // src/lib/workos-connect.ts
413
466
  var TOKEN_PATH = "/oauth2/token";
414
467
  var DISCOVERY_MAX_BYTES = 16 * 1024;
@@ -545,10 +598,10 @@ function parseWorkosConnectTokens(value, options = {}) {
545
598
  "access_token",
546
599
  WORKOS_CONNECT_RESPONSE_MAX_BYTES
547
600
  );
548
- const refreshToken2 = record.refresh_token === void 0 && options.fallbackRefreshToken !== void 0 ? options.fallbackRefreshToken : exactString(record.refresh_token, "refresh_token", WORKOS_CONNECT_RESPONSE_MAX_BYTES);
601
+ const refreshToken3 = record.refresh_token === void 0 && options.fallbackRefreshToken !== void 0 ? options.fallbackRefreshToken : exactString(record.refresh_token, "refresh_token", WORKOS_CONNECT_RESPONSE_MAX_BYTES);
549
602
  return {
550
603
  accessToken,
551
- refreshToken: refreshToken2,
604
+ refreshToken: refreshToken3,
552
605
  expiresIn: record.expires_in === void 0 ? void 0 : safeInteger(record.expires_in, "expires_in", 1, MAX_TOKEN_LIFETIME_SECONDS)
553
606
  };
554
607
  }
@@ -604,9 +657,19 @@ function parseMachineConfiguration(value) {
604
657
  ...record.developer_enrollment === true ? { developerEnrollment: true } : {}
605
658
  };
606
659
  }
660
+ function rejectedCredentialsMessage(message, env = process.env) {
661
+ return isClaudeCloudSession(env) ? `The cloud environment's credentials were rejected. To fix it, ${CLOUD_REJECTED_CREDENTIALS_REMEDY}.` : message;
662
+ }
607
663
  function machineSignal(signal) {
608
664
  return signal ? AbortSignal.any([signal, AbortSignal.timeout(1e4)]) : AbortSignal.timeout(1e4);
609
665
  }
666
+ function hostOf(url) {
667
+ try {
668
+ return new URL(url).hostname;
669
+ } catch {
670
+ return "Primitive";
671
+ }
672
+ }
610
673
  async function fetchMachine(url, options, fetchImpl) {
611
674
  try {
612
675
  return await fetchImpl(url, options);
@@ -614,7 +677,9 @@ async function fetchMachine(url, options, fetchImpl) {
614
677
  options.signal?.throwIfAborted();
615
678
  throw new MachineAuthError(
616
679
  "authentication_unavailable",
617
- "Machine authentication is temporarily unavailable. Check the connection and retry."
680
+ // A cloud VM reaches only the hosts its environment allows, and both of
681
+ // Primitive's are blocked by default: name the one that failed.
682
+ isClaudeCloudSession() ? `Machine authentication could not reach ${hostOf(url)}. If this Claude Code cloud environment blocks it, add it to the environment's Allowed domains (Network access: Limited), then start a new cloud session (a running session keeps the network rules it started with).` : "Machine authentication is temporarily unavailable. Check the connection and retry."
618
683
  );
619
684
  }
620
685
  }
@@ -641,8 +706,9 @@ async function discoverMachineConfiguration(apiUrl, signal, fetchImpl = fetch) {
641
706
  );
642
707
  return parseMachineConfiguration(await readMachineJson(response, 16 * 1024));
643
708
  }
644
- async function exchangeMachineCredentials(configuration, clientId, clientSecret, signal, fetchImpl = fetch) {
645
- if (!/^client_[\w-]+$/u.test(clientId) || !machineString(clientSecret)) {
709
+ async function exchangeMachineCredentials(configuration, clientId, clientSecret, signal, fetchImpl = fetch, options = {}) {
710
+ const network = options.secretInjection === "network";
711
+ if (!/^client_[\w-]+$/u.test(clientId) || !network && !machineString(clientSecret)) {
646
712
  throw new MachineAuthError(
647
713
  "invalid_credentials",
648
714
  "A machine client ID and secret are required.",
@@ -656,11 +722,11 @@ async function exchangeMachineCredentials(configuration, clientId, clientSecret,
656
722
  redirect: "error",
657
723
  signal: machineSignal(signal),
658
724
  headers: { "Content-Type": "application/x-www-form-urlencoded" },
659
- body: new URLSearchParams({
660
- grant_type: "client_credentials",
661
- client_id: clientId,
662
- client_secret: clientSecret
663
- })
725
+ // With a network secret the agent proxy authenticates the client with
726
+ // HTTP Basic (client_secret_basic); the body carries no credential.
727
+ body: new URLSearchParams(
728
+ network ? { grant_type: "client_credentials" } : { grant_type: "client_credentials", client_id: clientId, client_secret: clientSecret }
729
+ )
664
730
  },
665
731
  fetchImpl
666
732
  );
@@ -668,7 +734,9 @@ async function exchangeMachineCredentials(configuration, clientId, clientSecret,
668
734
  const terminal = response.status === 400 || response.status === 401 || response.status === 403;
669
735
  throw new MachineAuthError(
670
736
  terminal ? "machine_credentials_rejected" : "token_service_unavailable",
671
- terminal ? "Machine credentials were rejected. Ask your administrator to rotate or enable them." : "The machine token service is temporarily unavailable.",
737
+ terminal ? network ? `The token service rejected the request. Check the cloud environment's network secret for ${new URL(configuration.issuer).hostname}: username = the client ID, password = the client secret.` : rejectedCredentialsMessage(
738
+ "Machine credentials were rejected. Ask your administrator to rotate or enable them."
739
+ ) : "The machine token service is temporarily unavailable.",
672
740
  terminal,
673
741
  terminal ? void 0 : machineRetryAt(response)
674
742
  );
@@ -688,6 +756,11 @@ async function exchangeMachineCredentials(configuration, clientId, clientSecret,
688
756
  } catch {
689
757
  throw new MachineAuthError("invalid_response", "The token service returned an invalid JWT.");
690
758
  }
759
+ if (claims.iss === configuration.issuer && claims.aud === configuration.audience && (claims.sub !== clientId || claims.client_id !== clientId))
760
+ throw new MachineAuthError(
761
+ "token_client_mismatch",
762
+ "The token service issued a token for another machine client."
763
+ );
691
764
  if (claims.iss !== configuration.issuer || claims.aud !== configuration.audience || claims.sub !== clientId || claims.client_id !== clientId || !machineString(claims.org_id, 256) || typeof claims.exp !== "number" || !Number.isFinite(claims.exp) || claims.exp * 1e3 <= Date.now()) {
692
765
  throw new MachineAuthError(
693
766
  "token_identity_mismatch",
@@ -733,12 +806,51 @@ async function verifyMachineIdentity(apiUrl, accessToken, clientId, signal, fetc
733
806
  const terminal = response.status === 401 || response.status === 403;
734
807
  throw new MachineAuthError(
735
808
  terminal ? "machine_access_rejected" : "verification_unavailable",
736
- terminal ? "The API rejected this machine. Ask your administrator to check its registration and scopes." : "Machine verification is temporarily unavailable.",
809
+ terminal ? rejectedCredentialsMessage(
810
+ "The API rejected this machine. Ask your administrator to check its registration and scopes."
811
+ ) : "Machine verification is temporarily unavailable.",
737
812
  terminal
738
813
  );
739
814
  }
740
815
  return parseMachineIdentity(await readMachineJson(response, 16 * 1024), clientId);
741
816
  }
817
+ function parseInjectedMachineIdentity(status, value, apiUrl, clientId) {
818
+ const rejected = () => new MachineAuthError(
819
+ "network_token_rejected",
820
+ `Primitive did not accept this machine: the cloud environment's proxy attached no token it accepts, or the installation was revoked. Check the environment's OAuth 2.0 client credentials network secret: allowed website ${new URL(apiUrl).hostname}, the client ID (${clientId}), the client secret, and the token URL.`,
821
+ true
822
+ );
823
+ if (status === 401 || status === 403) throw rejected();
824
+ if (status < 200 || status > 299)
825
+ throw new MachineAuthError(
826
+ "verification_unavailable",
827
+ "Machine verification is temporarily unavailable."
828
+ );
829
+ let data;
830
+ try {
831
+ data = machineRecord(value);
832
+ } catch {
833
+ throw new MachineAuthError("invalid_response", "Invalid machine authentication response.");
834
+ }
835
+ if (data.authenticated !== true) throw rejected();
836
+ const principal = data.principal && typeof data.principal === "object" ? data.principal : {};
837
+ if (principal.kind === "machine" && typeof principal.clientId === "string" && principal.clientId !== clientId)
838
+ throw new MachineAuthError(
839
+ "network_secret_mismatch",
840
+ `The proxy's token belongs to another machine. Check that the network secret's client ID equals PRIM_M2M_CLIENT_ID (${clientId}).`,
841
+ true
842
+ );
843
+ return parseMachineIdentity(data, clientId);
844
+ }
845
+ async function verifyInjectedMachineIdentity(apiUrl, clientId, signal, fetchImpl = fetch) {
846
+ const response = await fetchMachine(
847
+ `${machineApiUrl(apiUrl)}/api/cli/auth/status`,
848
+ { redirect: "error", signal: machineSignal(signal) },
849
+ fetchImpl
850
+ );
851
+ const value = response.ok ? await readMachineJson(response, 16 * 1024) : void 0;
852
+ return parseInjectedMachineIdentity(response.status, value, apiUrl, clientId);
853
+ }
742
854
 
743
855
  // src/lib/paths.ts
744
856
  import { homedir } from "os";
@@ -770,6 +882,11 @@ function primConfigDirectory(options = {}) {
770
882
 
771
883
  // src/lib/machine-broker.ts
772
884
  var MAX_RESPONSE_BYTES = 96 * 1024;
885
+ var MAX_FORWARD_REQUEST_BYTES = 12 * 1024 * 1024;
886
+ var MAX_API_RESPONSE_BYTES = 8 * 1024 * 1024;
887
+ var MAX_FORWARD_RESPONSE_BYTES = 36 * 1024 * 1024;
888
+ var FORWARD_REQUEST_PROOF = "forward-request";
889
+ var FORWARD_ANSWER_PROOF = "forward-answer";
773
890
  var IDLE_MS = 5 * 6e4;
774
891
  function descriptorPath(directory, generation) {
775
892
  return join4(directory, `machine_broker_${generation}.json`);
@@ -785,8 +902,8 @@ function readDescriptor(path) {
785
902
  return void 0;
786
903
  }
787
904
  }
788
- function signature(secret, nonce, body) {
789
- return createHmac("sha256", secret).update(`${nonce}\0${body}`).digest("hex");
905
+ function signature(secret, nonce, body, purpose) {
906
+ return createHmac("sha256", secret).update(purpose ? `${nonce}\0${purpose}\0${body}` : `${nonce}\0${body}`).digest("hex");
790
907
  }
791
908
  function matches(left, right) {
792
909
  return typeof right === "string" && /^[a-f0-9]{64}$/u.test(right) && timingSafeEqual(Buffer.from(left, "hex"), Buffer.from(right, "hex"));
@@ -801,10 +918,9 @@ async function brokerRequest(descriptor, environment, options) {
801
918
  observedTokenHash: tokenHash(options.observedToken),
802
919
  timestamp: Date.now()
803
920
  });
804
- const response = await fetch(`http://127.0.0.1:${descriptor.port}/credential`, {
921
+ const response = await loopbackFetch(`http://127.0.0.1:${descriptor.port}/credential`, {
805
922
  method: "POST",
806
923
  body,
807
- redirect: "error",
808
924
  signal: options.signal,
809
925
  headers: {
810
926
  "Content-Type": "application/json",
@@ -835,6 +951,15 @@ async function brokerRequest(descriptor, environment, options) {
835
951
  );
836
952
  return credential;
837
953
  }
954
+ function brokerEnvironment(options) {
955
+ const routed = options.environment.secretInjection || options.environment.tokenInjection;
956
+ return {
957
+ ...options.env,
958
+ PRIM_API_URL: options.apiUrl,
959
+ PRIM_CONFIG_DIR: options.directory,
960
+ ...routed ? { NODE_USE_ENV_PROXY: "1" } : {}
961
+ };
962
+ }
838
963
  async function acquireBrokerCredential(options) {
839
964
  const path = descriptorPath(options.directory, options.environment.generation);
840
965
  const existing = readDescriptor(path);
@@ -846,15 +971,28 @@ async function acquireBrokerCredential(options) {
846
971
  if (error instanceof MachineAuthError) throw error;
847
972
  }
848
973
  }
849
- const descriptor = await withFileLock(
974
+ const descriptor = await ensureBroker(options);
975
+ try {
976
+ return await brokerRequest(descriptor, options.environment, options);
977
+ } catch (error) {
978
+ options.signal.throwIfAborted();
979
+ if (error instanceof MachineAuthError) throw error;
980
+ throw new MachineAuthError(
981
+ "broker_unavailable",
982
+ "Machine credential broker is unavailable. Retry the command."
983
+ );
984
+ }
985
+ }
986
+ async function ensureBroker(options) {
987
+ const path = descriptorPath(options.directory, options.environment.generation);
988
+ return withFileLock(
850
989
  join4(options.directory, "machine-broker.lock"),
851
990
  async () => {
852
991
  const current = readDescriptor(path);
853
992
  if (current) {
854
993
  try {
855
- const response = await fetch(`http://127.0.0.1:${current.port}/health`, {
856
- signal: AbortSignal.any([options.signal, AbortSignal.timeout(500)]),
857
- redirect: "error"
994
+ const response = await loopbackFetch(`http://127.0.0.1:${current.port}/health`, {
995
+ signal: AbortSignal.any([options.signal, AbortSignal.timeout(500)])
858
996
  });
859
997
  if (response.ok && await response.text() === current.nonce) return current;
860
998
  } catch {
@@ -873,7 +1011,7 @@ async function acquireBrokerCredential(options) {
873
1011
  detached: true,
874
1012
  stdio: ["ignore", "ignore", "ignore", "ipc"],
875
1013
  windowsHide: true,
876
- env: { ...options.env, PRIM_API_URL: options.apiUrl, PRIM_CONFIG_DIR: options.directory }
1014
+ env: brokerEnvironment(options)
877
1015
  });
878
1016
  let settled = false;
879
1017
  const finish = (error) => {
@@ -925,27 +1063,93 @@ async function acquireBrokerCredential(options) {
925
1063
  },
926
1064
  { signal: options.signal }
927
1065
  );
1066
+ }
1067
+ async function forwardOnce(descriptor, environment, request3, signal) {
1068
+ const body = JSON.stringify({
1069
+ generation: environment.generation,
1070
+ timestamp: Date.now(),
1071
+ method: request3.method,
1072
+ path: request3.path,
1073
+ headers: request3.headers ?? {},
1074
+ ...request3.body === void 0 ? {} : { body: request3.body }
1075
+ });
1076
+ const response = await loopbackFetch(`http://127.0.0.1:${descriptor.port}/forward`, {
1077
+ method: "POST",
1078
+ body,
1079
+ signal,
1080
+ headers: {
1081
+ "Content-Type": "application/json",
1082
+ "X-Prim-Proof": signature(
1083
+ environment.clientSecret,
1084
+ descriptor.nonce,
1085
+ body,
1086
+ FORWARD_REQUEST_PROOF
1087
+ )
1088
+ }
1089
+ });
1090
+ const envelope = machineRecord(await readBoundedJson(response, MAX_FORWARD_RESPONSE_BYTES));
1091
+ if (typeof envelope.body !== "string" || !matches(
1092
+ signature(environment.clientSecret, descriptor.nonce, envelope.body, FORWARD_ANSWER_PROOF),
1093
+ envelope.proof
1094
+ ))
1095
+ throw new MachineAuthError(
1096
+ "broker_unavailable",
1097
+ "Machine credential broker could not be authenticated. Retry the command."
1098
+ );
1099
+ const data = machineRecord(JSON.parse(envelope.body));
1100
+ if (data.error) {
1101
+ const error = machineRecord(data.error);
1102
+ throw new MachineAuthError(String(error.code), String(error.message), error.terminal === true);
1103
+ }
1104
+ const status = data.status;
1105
+ if (typeof status !== "number" || !Number.isInteger(status) || status < 200 || status > 599)
1106
+ throw new MachineAuthError("broker_unavailable", "Machine credential broker answered oddly.");
1107
+ const headers = new Headers();
1108
+ for (const [name2, value] of Object.entries(machineRecord(data.headers ?? {})))
1109
+ if (typeof value === "string") headers.set(name2, value);
1110
+ const text = typeof data.body === "string" ? data.body : "";
1111
+ return new Response([204, 205, 304].includes(status) ? null : text, { status, headers });
1112
+ }
1113
+ async function forwardBrokerRequest(options) {
1114
+ const path = descriptorPath(options.directory, options.environment.generation);
1115
+ const unavailable = () => new MachineAuthError(
1116
+ "broker_unavailable",
1117
+ "Machine credential broker is unavailable. Retry the command."
1118
+ );
1119
+ const existing = readDescriptor(path);
1120
+ if (existing) {
1121
+ try {
1122
+ return await forwardOnce(existing, options.environment, options.request, options.signal);
1123
+ } catch (error) {
1124
+ options.signal.throwIfAborted();
1125
+ if (error instanceof MachineAuthError) throw error;
1126
+ if (error.code !== "ECONNREFUSED") throw unavailable();
1127
+ }
1128
+ }
1129
+ const descriptor = await ensureBroker(options);
928
1130
  try {
929
- return await brokerRequest(descriptor, options.environment, options);
1131
+ return await forwardOnce(descriptor, options.environment, options.request, options.signal);
930
1132
  } catch (error) {
931
1133
  options.signal.throwIfAborted();
932
1134
  if (error instanceof MachineAuthError) throw error;
933
- throw new MachineAuthError(
934
- "broker_unavailable",
935
- "Machine credential broker is unavailable. Retry the command."
936
- );
1135
+ throw unavailable();
937
1136
  }
938
1137
  }
939
1138
 
940
1139
  // src/lib/machine-retry.ts
941
1140
  import { createHash as createHash2 } from "crypto";
942
- import { lstatSync as lstatSync2, readFileSync as readFileSync4, rmSync as rmSync4 } from "fs";
1141
+ import { lstatSync as lstatSync2, readFileSync as readFileSync4, readdirSync, rmSync as rmSync4 } from "fs";
943
1142
  import { join as join5 } from "path";
944
- async function withMachineCooldown(directory, apiUrl, clientId, signal, request2) {
1143
+ var SERVER_WAIT_PREFIX = "The sign-in service asked prim to wait";
1144
+ var MAX_SERVER_WAIT_MS = 15 * 6e4;
1145
+ async function withMachineCooldown(directory, apiUrl, clientId, signal, request3) {
945
1146
  signal?.throwIfAborted();
946
1147
  const key = createHash2("sha256").update(`${apiUrl}\0${clientId}`).digest("hex");
947
1148
  const path = join5(directory, `machine_retry_${key}.json`);
948
- let state = { failures: 0, retryAt: 0 };
1149
+ let state = {
1150
+ failures: 0,
1151
+ retryAt: 0
1152
+ };
949
1153
  try {
950
1154
  const stat = lstatSync2(path);
951
1155
  if (!stat.isFile() || stat.size > 1024) throw new Error("Invalid retry state");
@@ -960,12 +1164,19 @@ async function withMachineCooldown(directory, apiUrl, clientId, signal, request2
960
1164
  if (state.retryAt > Date.now())
961
1165
  throw new MachineAuthError(
962
1166
  "token_service_unavailable",
963
- "Machine authentication is cooling down after a temporary failure. Retry later.",
1167
+ !isClaudeCloudSession() ? "Machine authentication is cooling down after a temporary failure. Retry later." : state.serverRetryAfter === true ? (
1168
+ // Cloud setup keeps this wait too, so pointing at it would loop.
1169
+ `${SERVER_WAIT_PREFIX}; retry in about ${Math.ceil((state.retryAt - Date.now()) / 1e3)}s`
1170
+ ) : (
1171
+ // The cooldown hides the failure that started it; cloud setup
1172
+ // retries at once and names the cause.
1173
+ cloudSetupPointer("Machine authentication is cooling down after a temporary failure")
1174
+ ),
964
1175
  false,
965
1176
  state.retryAt
966
1177
  );
967
1178
  try {
968
- const result = await request2();
1179
+ const result = await request3();
969
1180
  rmSync4(path, { force: true });
970
1181
  return result;
971
1182
  } catch (error) {
@@ -977,40 +1188,1283 @@ async function withMachineCooldown(directory, apiUrl, clientId, signal, request2
977
1188
  ].includes(error.code)) {
978
1189
  const failures = Math.min(16, state.failures + 1);
979
1190
  const backoff = Math.min(6e4, 1e3 * 2 ** (failures - 1));
980
- const retryAt = error.retryAt ?? Date.now() + Math.ceil(backoff * (1 + Math.random()));
981
- atomicWriteFile(path, JSON.stringify({ failures, retryAt }), { mode: 384 });
1191
+ const retryAt = error.retryAt === void 0 ? Date.now() + Math.ceil(backoff * (1 + Math.random())) : Math.min(error.retryAt, Date.now() + MAX_SERVER_WAIT_MS);
1192
+ atomicWriteFile(
1193
+ path,
1194
+ JSON.stringify({
1195
+ failures,
1196
+ retryAt,
1197
+ ...error.retryAt === void 0 ? {} : { serverRetryAfter: true }
1198
+ }),
1199
+ { mode: 384 }
1200
+ );
982
1201
  throw new MachineAuthError(error.code, error.message, false, retryAt);
983
1202
  }
984
1203
  throw error;
985
1204
  }
986
1205
  }
987
1206
 
1207
+ // src/lib/session-identity.ts
1208
+ import { execFile } from "child_process";
1209
+ import { createHash as createHash4 } from "crypto";
1210
+ import { rmSync as rmSync5 } from "fs";
1211
+ import { join as join7 } from "path";
1212
+ import { promisify } from "util";
1213
+
1214
+ // src/lib/git.ts
1215
+ import { execFileSync } from "child_process";
1216
+ import { createHash as createHash3 } from "crypto";
1217
+ import { lstatSync as lstatSync3, readFileSync as readFileSync5, realpathSync } from "fs";
1218
+ import { basename as basename2, dirname as dirname4, isAbsolute as isAbsolute3, join as join6, relative, resolve, sep } from "path";
1219
+ var GIT_TIMEOUT_MS = 1e3;
1220
+ var MAX_SETTINGS_BYTES = 1024 * 1024;
1221
+ var GITHUB_OWNER_PATTERN = /^(?![A-Za-z0-9-]*--)[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?$/u;
1222
+ var GITHUB_REPOSITORY_PATTERN = /^(?!\.{1,2}$)[A-Za-z0-9._-]{1,100}$/u;
1223
+ var CREDENTIAL_VARIABLE = /^(?:PRIM_TOKEN|PRIM_M2M_\w+)$/u;
1224
+ function gitChildEnvironment(env = process.env) {
1225
+ return Object.fromEntries(
1226
+ Object.entries(env).filter(([name2]) => !CREDENTIAL_VARIABLE.test(name2))
1227
+ );
1228
+ }
1229
+ function gitToplevel(cwd) {
1230
+ try {
1231
+ return execFileSync("git", ["rev-parse", "--show-toplevel"], {
1232
+ cwd,
1233
+ encoding: "utf-8",
1234
+ stdio: ["ignore", "pipe", "ignore"],
1235
+ timeout: GIT_TIMEOUT_MS,
1236
+ env: gitChildEnvironment()
1237
+ }).trim();
1238
+ } catch {
1239
+ return null;
1240
+ }
1241
+ }
1242
+ function gitValue(cwd, args) {
1243
+ try {
1244
+ const value = execFileSync("git", args, {
1245
+ cwd,
1246
+ encoding: "utf-8",
1247
+ stdio: ["ignore", "pipe", "ignore"],
1248
+ timeout: GIT_TIMEOUT_MS,
1249
+ env: gitChildEnvironment()
1250
+ }).trim();
1251
+ return value || void 0;
1252
+ } catch {
1253
+ return void 0;
1254
+ }
1255
+ }
1256
+ function currentBranch(cwd) {
1257
+ return gitValue(cwd, ["symbolic-ref", "--quiet", "--short", "HEAD"]);
1258
+ }
1259
+ function parseGithubRepositoryName(path) {
1260
+ const parts = path.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "").split("/");
1261
+ if (parts.length !== 2 || !GITHUB_OWNER_PATTERN.test(parts[0] ?? "") || !GITHUB_REPOSITORY_PATTERN.test(parts[1] ?? "")) {
1262
+ return null;
1263
+ }
1264
+ return `${parts[0]}/${parts[1]}`;
1265
+ }
1266
+ function githubRepositoryFromRemote(remote) {
1267
+ if ([...remote].some((char) => char < " " || char === "\x7F")) return null;
1268
+ const match = /^(?:git@github\.com:([^?#]+)|(?:https|ssh):\/\/(?:[^/@]+@)?github\.com(?::\d+)?\/([^?#]+))$/i.exec(
1269
+ remote
1270
+ );
1271
+ const path = match?.[1] ?? match?.[2];
1272
+ return path ? parseGithubRepositoryName(path) : null;
1273
+ }
1274
+ function checkoutSettingsText(repoRoot) {
1275
+ const path = join6(repoRoot, ".claude", "settings.json");
1276
+ try {
1277
+ if (!lstatSync3(join6(repoRoot, ".claude")).isDirectory()) return null;
1278
+ const stat = lstatSync3(path);
1279
+ if (!stat.isFile() || stat.size > MAX_SETTINGS_BYTES) return null;
1280
+ return readFileSync5(path, "utf8");
1281
+ } catch {
1282
+ return null;
1283
+ }
1284
+ }
1285
+ function checkoutDeclaration(repoRoot, name2) {
1286
+ const text = checkoutSettingsText(repoRoot);
1287
+ if (text === null) return null;
1288
+ let parsed;
1289
+ try {
1290
+ parsed = JSON.parse(text);
1291
+ } catch {
1292
+ return null;
1293
+ }
1294
+ const env = typeof parsed === "object" && parsed !== null ? parsed.env : void 0;
1295
+ const value = typeof env === "object" && env !== null ? env[name2] : void 0;
1296
+ return typeof value === "string" ? value : null;
1297
+ }
1298
+ function declaredGithubRepository(repoRoot) {
1299
+ const value = checkoutDeclaration(repoRoot, "PRIM_REPOSITORY");
1300
+ return value === null ? null : parseGithubRepositoryName(value.trim());
1301
+ }
1302
+ function githubRepositoryFullName(cwd) {
1303
+ const remote = gitValue(cwd, ["config", "--get", "remote.origin.url"]);
1304
+ if (remote) {
1305
+ const fromOrigin = githubRepositoryFromRemote(remote);
1306
+ if (fromOrigin || normalizeOriginRemote(remote)) return fromOrigin;
1307
+ }
1308
+ const root = gitToplevel(cwd);
1309
+ return root ? declaredGithubRepository(root) : null;
1310
+ }
1311
+ function canonicalGitRoot(cwd) {
1312
+ try {
1313
+ const top = gitToplevel(cwd);
1314
+ return top ? realpathSync.native(top) : null;
1315
+ } catch {
1316
+ return null;
1317
+ }
1318
+ }
1319
+ function relatedWorktreeTarget(path, cwd, origin) {
1320
+ let parent = dirname4(resolve(cwd, path));
1321
+ while (true) {
1322
+ try {
1323
+ realpathSync.native(parent);
1324
+ break;
1325
+ } catch {
1326
+ const next = dirname4(parent);
1327
+ if (next === parent) return null;
1328
+ parent = next;
1329
+ }
1330
+ }
1331
+ const target = resolveRepositoryContext(parent);
1332
+ if (!target || !target.repoKey || target.repoKey !== origin.repoKey) return null;
1333
+ const common = (root) => {
1334
+ const value = gitValue(root, ["rev-parse", "--git-common-dir"]);
1335
+ try {
1336
+ return value ? realpathSync.native(resolve(root, value)) : void 0;
1337
+ } catch {
1338
+ return void 0;
1339
+ }
1340
+ };
1341
+ const originCommon = common(origin.repoRoot);
1342
+ return originCommon && originCommon === common(target.repoRoot) ? target : null;
1343
+ }
1344
+ function normalizeOriginRemote(remote) {
1345
+ const value = remote.trim();
1346
+ if (!value) return void 0;
1347
+ const scp = !value.includes("://") ? /^(?:[^@/\s]+@)?(?<host>[^:/\s]+):(?<path>.+)$/.exec(value)?.groups : void 0;
1348
+ if (scp?.host && scp.path) {
1349
+ const path = scp.path.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "");
1350
+ return path ? `${scp.host.toLowerCase()}/${path}` : void 0;
1351
+ }
1352
+ try {
1353
+ const url = new URL(value);
1354
+ url.username = "";
1355
+ url.password = "";
1356
+ url.search = "";
1357
+ url.hash = "";
1358
+ const path = url.pathname.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "");
1359
+ if (url.host && path) return `${url.host.toLowerCase()}/${path}`;
1360
+ return void 0;
1361
+ } catch {
1362
+ return void 0;
1363
+ }
1364
+ }
1365
+ function opaqueRepoKey(source, value) {
1366
+ return `repo_v1_${createHash3("sha256").update(`${source}\0${value}`).digest("hex")}`;
1367
+ }
1368
+ function resolveRepositoryContext(cwd = process.cwd()) {
1369
+ const top = gitToplevel(cwd);
1370
+ if (!top) return null;
1371
+ let repoRoot;
1372
+ try {
1373
+ repoRoot = realpathSync.native(top);
1374
+ } catch {
1375
+ repoRoot = resolve(top);
1376
+ }
1377
+ const origin = gitValue(repoRoot, ["config", "--get", "remote.origin.url"]);
1378
+ const repoFullName = githubRepositoryFullName(repoRoot) ?? void 0;
1379
+ const normalizedOrigin = origin ? normalizeOriginRemote(origin) : void 0;
1380
+ if (normalizedOrigin) {
1381
+ return {
1382
+ repoRoot,
1383
+ repoKey: opaqueRepoKey("origin", normalizedOrigin),
1384
+ identitySource: "origin",
1385
+ repoFullName
1386
+ };
1387
+ }
1388
+ if (repoFullName) {
1389
+ return {
1390
+ repoRoot,
1391
+ repoKey: opaqueRepoKey("origin", `github.com/${repoFullName}`),
1392
+ identitySource: "declared",
1393
+ repoFullName
1394
+ };
1395
+ }
1396
+ const roots = gitValue(repoRoot, ["rev-list", "--max-parents=0", "HEAD"])?.split(/\s+/).filter(Boolean).sort();
1397
+ if (roots && roots.length > 0) {
1398
+ return {
1399
+ repoRoot,
1400
+ repoKey: opaqueRepoKey("root_commit", roots.join("\n")),
1401
+ identitySource: "root_commit",
1402
+ repoFullName
1403
+ };
1404
+ }
1405
+ return { repoRoot, repoFullName };
1406
+ }
1407
+ function nearestExistingAncestor(path) {
1408
+ const suffix = [];
1409
+ let cursor = path;
1410
+ while (true) {
1411
+ try {
1412
+ lstatSync3(cursor);
1413
+ break;
1414
+ } catch (error) {
1415
+ const code = typeof error === "object" && error !== null && "code" in error ? error.code : void 0;
1416
+ if (code !== "ENOENT" && code !== "ENOTDIR") return null;
1417
+ const parent = dirname4(cursor);
1418
+ if (parent === cursor) return null;
1419
+ suffix.unshift(cursor.slice(parent.length + (parent.endsWith(sep) ? 0 : 1)));
1420
+ cursor = parent;
1421
+ }
1422
+ }
1423
+ try {
1424
+ return { real: realpathSync.native(cursor), suffix };
1425
+ } catch {
1426
+ return null;
1427
+ }
1428
+ }
1429
+ function canonicalRepositoryPathScoped(filePath, context, baseDir) {
1430
+ if (!filePath || filePath !== filePath.trim() || filePath.includes("\0")) {
1431
+ return { ok: false, reason: "invalid_path" };
1432
+ }
1433
+ const absolute = resolve(baseDir, filePath);
1434
+ const resolved = nearestExistingAncestor(absolute);
1435
+ if (!resolved) return { ok: false, reason: "invalid_path" };
1436
+ const target = resolve(resolved.real, ...resolved.suffix);
1437
+ const rel = relative(context.repoRoot, target);
1438
+ if (!rel || rel === ".") return { ok: false, reason: "invalid_path" };
1439
+ if (isAbsolute3(rel) || rel === ".." || rel.startsWith(`..${sep}`)) {
1440
+ return { ok: false, reason: "outside_repository" };
1441
+ }
1442
+ return { ok: true, file: sep === "/" ? rel : rel.split(sep).join("/") };
1443
+ }
1444
+ function canonicalRepositoryPathLegacy(filePath, cwd, repositoryRoot = canonicalGitRoot(cwd)) {
1445
+ if (!repositoryRoot || !filePath || [...filePath].some((char) => char < " " || char === "\x7F" || "~*?[]{}$`\\".includes(char)))
1446
+ return null;
1447
+ const absolute = resolve(cwd, filePath);
1448
+ let target;
1449
+ try {
1450
+ const stat = lstatSync3(absolute);
1451
+ if (!stat.isFile() || stat.isSymbolicLink()) return null;
1452
+ target = realpathSync.native(absolute);
1453
+ } catch (error) {
1454
+ if (!(error instanceof Error) || error.code !== "ENOENT") {
1455
+ return null;
1456
+ }
1457
+ try {
1458
+ const parent = realpathSync.native(dirname4(absolute));
1459
+ if (!lstatSync3(parent).isDirectory()) return null;
1460
+ target = resolve(parent, basename2(absolute));
1461
+ } catch {
1462
+ return null;
1463
+ }
1464
+ }
1465
+ const rel = relative(repositoryRoot, target);
1466
+ if (!rel || isAbsolute3(rel) || rel === ".." || rel.startsWith(`..${sep}`)) {
1467
+ return null;
1468
+ }
1469
+ return sep === "/" ? rel : rel.split(sep).join("/");
1470
+ }
1471
+ function canonicalRepositoryPath(filePath, contextOrCwd, baseDirOrRoot) {
1472
+ if (typeof contextOrCwd === "string") {
1473
+ return canonicalRepositoryPathLegacy(filePath, contextOrCwd, baseDirOrRoot);
1474
+ }
1475
+ return canonicalRepositoryPathScoped(
1476
+ filePath,
1477
+ contextOrCwd,
1478
+ baseDirOrRoot ?? contextOrCwd.repoRoot
1479
+ );
1480
+ }
1481
+
1482
+ // src/lib/terminal-safe.ts
1483
+ function replaceIsolatedSurrogates(value) {
1484
+ let out = "";
1485
+ for (let index = 0; index < value.length; index += 1) {
1486
+ const unit = value.charCodeAt(index);
1487
+ if (unit >= 55296 && unit <= 56319) {
1488
+ const next = value.charCodeAt(index + 1);
1489
+ if (next >= 56320 && next <= 57343) {
1490
+ out += value[index] + value[index + 1];
1491
+ index += 1;
1492
+ } else {
1493
+ out += "\uFFFD";
1494
+ }
1495
+ } else if (unit >= 56320 && unit <= 57343) {
1496
+ out += "\uFFFD";
1497
+ } else {
1498
+ out += value[index];
1499
+ }
1500
+ }
1501
+ return out;
1502
+ }
1503
+ function isUnsafeTerminalCodePoint(point) {
1504
+ const c0OrC1 = point <= 31 || point >= 127 && point <= 159;
1505
+ const bidiOrZeroWidth = point === 173 || // soft hyphen
1506
+ point === 1564 || // Arabic letter mark
1507
+ point === 6158 || // Mongolian vowel separator
1508
+ point >= 8203 && point <= 8207 || // zero-width + directional marks
1509
+ point >= 8234 && point <= 8238 || // bidi embeddings/overrides
1510
+ point >= 8288 && point <= 8303 || // word joiner + bidi isolates/controls
1511
+ point >= 65529 && point <= 65531 || // interlinear annotation controls
1512
+ point === 65279 || // zero-width no-break space / BOM
1513
+ point >= 917504 && point <= 917631;
1514
+ return c0OrC1 || bidiOrZeroWidth;
1515
+ }
1516
+ function terminalSafeText(value) {
1517
+ return Array.from(replaceIsolatedSurrogates(value)).filter((character) => !isUnsafeTerminalCodePoint(character.codePointAt(0) ?? 0)).join("");
1518
+ }
1519
+ function terminalSafeLine(value) {
1520
+ return terminalSafeText(value.replace(/\s+/gu, " ")).replace(/\s+/gu, " ").trim();
1521
+ }
1522
+ function isTerminalSafeText(value) {
1523
+ return terminalSafeText(value) === value;
1524
+ }
1525
+ var stripControlChars = terminalSafeText;
1526
+
1527
+ // src/lib/session-identity.ts
1528
+ var SESSION_IDENTITY_VARIABLE = "PRIM_CLOUD_IDENTITY";
1529
+ var SESSION_IDENTITY_VALUE = "session";
1530
+ var SESSION_ID_VARIABLE = "CLAUDE_CODE_REMOTE_SESSION_ID";
1531
+ var USER_EMAIL_VARIABLE = "CLAUDE_CODE_USER_EMAIL";
1532
+ var SESSION_TOKEN_PREFIX = "prim_sess_";
1533
+ var SESSION_BRANCH = /^claude\/[A-Za-z0-9][A-Za-z0-9._/-]{0,199}$/u;
1534
+ var SHA = /^[a-f0-9]{40}(?:[a-f0-9]{24})?$/u;
1535
+ var SESSION_ID = /^[A-Za-z0-9._:-]{1,200}$/u;
1536
+ var EMAIL_HINT = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9-]*\.)+[A-Za-z]{2,}$/u;
1537
+ var CHALLENGE_REUSE_MARGIN_MS = 3e4;
1538
+ var SESSION_IDENTITY_ROUTES = {
1539
+ challenge: "/api/cli/session-identity/challenge",
1540
+ token: "/api/cli/session-identity/token",
1541
+ refresh: "/api/cli/session-identity/token/refresh",
1542
+ link: "/api/cli/session-identity/link"
1543
+ };
1544
+ var DEFAULT_API_URL = "https://api.getprimitive.ai";
1545
+ var RENEW_BEFORE_MS = 6e4;
1546
+ var GIT_TIMEOUT_MS2 = 1e4;
1547
+ var POLL_BUDGET_MS = 15e3;
1548
+ var POLL_FIRST_DELAY_MS = 500;
1549
+ var POLL_MAX_DELAY_MS = 3e3;
1550
+ var BACKGROUND_RETRY_MS = 5 * 6e4;
1551
+ var LOCK_TIMEOUT_MS = 6e4;
1552
+ var RESPONSE_MAX_BYTES = 64 * 1024;
1553
+ function sessionIdentityRequested(env = process.env) {
1554
+ return isClaudeCloudSession(env) && env[SESSION_IDENTITY_VARIABLE]?.trim() === SESSION_IDENTITY_VALUE;
1555
+ }
1556
+ function sessionIdentityMode(deps = {}) {
1557
+ const env = deps.env ?? process.env;
1558
+ return sessionIdentityRequested(env) && (env.PRIM_M2M_CLIENT_ID !== void 0 || env.PRIM_M2M_CLIENT_SECRET !== void 0 || env.PRIM_M2M_CLIENT_AUTH !== void 0);
1559
+ }
1560
+ function failure(code, cause, remedy) {
1561
+ return { status: "failed", code, cause, remedy };
1562
+ }
1563
+ var RETRY_REMEDY = "run `prim setup --cloud` to try again";
1564
+ var NEW_SESSION_REMEDY = "start a new cloud session";
1565
+ var ENVIRONMENT_CREDENTIAL_REMEDY = 'ask the organization admin who set up the environment to check its credential, or to mint a replacement with `prim auth enroll --new-environment "<name>" --print-env`; then start a new cloud session';
1566
+ var SESSION_REVOKED = failure(
1567
+ "session_revoked",
1568
+ "Primitive no longer accepts this session's member token: an organization admin revoked the session or the member's GitHub link, the member left the organization, or the token was renewed elsewhere",
1569
+ `${NEW_SESSION_REMEDY}, which identifies you again through GitHub (if your GitHub link was removed, run \`prim auth link\` there when it asks)`
1570
+ );
1571
+ var CHALLENGE_WINDOW_PASSED = failure(
1572
+ "challenge_expired",
1573
+ "this session's identity check expired before it was exchanged for a token (a verified check stays usable, including for linking a GitHub account, for 30 minutes)",
1574
+ `${NEW_SESSION_REMEDY}, and if it asks you to link your GitHub account, run \`prim auth link\` there right away`
1575
+ );
1576
+ var CHALLENGE_GONE = failure(
1577
+ "challenge_not_found",
1578
+ "Primitive no longer knows this session's identity check (the environment credential may have been replaced since)",
1579
+ NEW_SESSION_REMEDY
1580
+ );
1581
+ var FINAL_CODES = /* @__PURE__ */ new Set(["session_revoked", "environment_credential_rejected"]);
1582
+ function rejectionFailure(reason, repository) {
1583
+ switch (reason) {
1584
+ case "identity_mismatch":
1585
+ return failure(
1586
+ "identity_mismatch",
1587
+ "the session branch was created by a GitHub account linked to a different Primitive member than the one signed in to Claude, so Primitive attributes this session to no one",
1588
+ `${NEW_SESSION_REMEDY}; if it happens again, ask an organization admin to check members' GitHub links`
1589
+ );
1590
+ case "push_after_expiry":
1591
+ return failure(
1592
+ "push_after_expiry",
1593
+ `GitHub's notice of the identity push to ${repository} reached Primitive after the identity check had expired`,
1594
+ `${NEW_SESSION_REMEDY}; if it happens again, check that Primitive's GitHub App on ${repository} delivers its notices`
1595
+ );
1596
+ case "repository_mismatch":
1597
+ return failure(
1598
+ "repository_mismatch",
1599
+ `Primitive received the identity push from a different repository than ${repository}`,
1600
+ `check that this checkout's origin is ${repository} on GitHub, then ${NEW_SESSION_REMEDY}`
1601
+ );
1602
+ case "conflicting_push":
1603
+ return failure(
1604
+ "conflicting_push",
1605
+ `more than one GitHub account created the session branch on ${repository}, so Primitive cannot tell who started this session`,
1606
+ NEW_SESSION_REMEDY
1607
+ );
1608
+ case "unsupported_sender":
1609
+ return failure(
1610
+ "unsupported_sender",
1611
+ `the session branch on ${repository} was created by a GitHub App or bot, not by a person's GitHub account`,
1612
+ `check that the cloud environment pushes to GitHub as the person who started the session, then ${NEW_SESSION_REMEDY}`
1613
+ );
1614
+ default:
1615
+ return failure(
1616
+ "challenge_rejected",
1617
+ `Primitive rejected the identity push to ${repository}${typeof reason === "string" ? ` (${terminalSafeLine(reason).slice(0, 120)})` : ""}`,
1618
+ `${NEW_SESSION_REMEDY}; if it happens again, ask an organization admin to check Primitive's GitHub App on ${repository}`
1619
+ );
1620
+ }
1621
+ }
1622
+ function sessionIdentityMessage(outcome) {
1623
+ if (outcome.status === "link_required")
1624
+ return `GitHub account @${outcome.githubLogin} started this Claude Code cloud session but is not linked to a Primitive account yet. To link it once, run \`prim auth link\` and sign in at the URL it prints with the code it shows; later sessions then identify you automatically.`;
1625
+ return `Primitive could not identify who started this Claude Code cloud session: ${outcome.cause}. To fix it, ${outcome.remedy}.`;
1626
+ }
1627
+ function hash(value) {
1628
+ return createHash4("sha256").update(value).digest("hex");
1629
+ }
1630
+ function sessionContext(deps) {
1631
+ const env = deps.env ?? process.env;
1632
+ const environment = environmentCredentials(deps);
1633
+ if (!environment)
1634
+ return failure(
1635
+ "environment_credential_missing",
1636
+ "the cloud environment has no environment credential",
1637
+ 'ask an organization admin to create one with `prim auth enroll --new-environment "<name>" --print-env` and add it to the environment, then start a new cloud session'
1638
+ );
1639
+ const sessionId = env[SESSION_ID_VARIABLE]?.trim();
1640
+ if (!sessionId || !SESSION_ID.test(sessionId))
1641
+ return failure(
1642
+ "session_id_missing",
1643
+ `this Claude Code cloud session does not report a session ID Primitive accepts (${SESSION_ID_VARIABLE})`,
1644
+ NEW_SESSION_REMEDY
1645
+ );
1646
+ const apiUrl = machineApiUrl(env.PRIM_API_URL?.trim() || DEFAULT_API_URL);
1647
+ const directory = deps.directory ?? primConfigDirectory({ env });
1648
+ const key = hash(`${apiUrl}\0${environment.clientId}\0${sessionId}`);
1649
+ return {
1650
+ directory,
1651
+ apiUrl,
1652
+ clientId: environment.clientId,
1653
+ generation: environment.generation,
1654
+ sessionId,
1655
+ tokenPath: join7(directory, `session_identity_${key}.json`),
1656
+ statePath: join7(directory, `session_identity_${key}.state.json`),
1657
+ lockPath: join7(directory, "session-identity.lock")
1658
+ };
1659
+ }
1660
+ function readRecord(path) {
1661
+ try {
1662
+ const value = readMachineMetadata(path);
1663
+ return value === void 0 ? void 0 : machineRecord(value);
1664
+ } catch {
1665
+ return void 0;
1666
+ }
1667
+ }
1668
+ function finiteNumber(value) {
1669
+ return typeof value === "number" && Number.isFinite(value);
1670
+ }
1671
+ function readToken(context) {
1672
+ const data = readRecord(context.tokenPath);
1673
+ if (!data || data.version !== 1 || data.apiUrl !== context.apiUrl || data.clientId !== context.clientId || data.generation !== context.generation || data.sessionId !== context.sessionId || !machineString(data.accessToken, 8192) || !data.accessToken.startsWith(SESSION_TOKEN_PREFIX) || !finiteNumber(data.expiresAt) || !finiteNumber(data.refreshAfter) || !machineString(data.userId, 256) || !machineString(data.displayName, 256) || !machineString(data.organizationId, 256) || !machineString(data.issuer, 2048) || !machineString(data.audience, 256))
1674
+ return void 0;
1675
+ const identity = data.identity;
1676
+ if (!identity || identity.clientId !== context.clientId || identity.authorizedUserId !== data.userId || identity.organizationId !== data.organizationId)
1677
+ return void 0;
1678
+ return data;
1679
+ }
1680
+ function readState(context) {
1681
+ const data = readRecord(context.statePath);
1682
+ if (!data || data.version !== 1 || data.sessionId !== context.sessionId || data.status !== "link_required" && data.status !== "failed" || typeof data.code !== "string" || !finiteNumber(data.at))
1683
+ return void 0;
1684
+ return data;
1685
+ }
1686
+ function writeToken(context, record) {
1687
+ prepareMachineMetadataDirectory(context.directory);
1688
+ writeMachineMetadata(context.tokenPath, record);
1689
+ rmSync5(context.statePath, { force: true });
1690
+ }
1691
+ function writeState(context, state) {
1692
+ try {
1693
+ prepareMachineMetadataDirectory(context.directory);
1694
+ writeMachineMetadata(context.statePath, { version: 1, ...state });
1695
+ } catch {
1696
+ }
1697
+ }
1698
+ function tokenValid(record, now = Date.now()) {
1699
+ return now < record.expiresAt - RENEW_BEFORE_MS;
1700
+ }
1701
+ function tokenFresh(record, now = Date.now()) {
1702
+ return tokenValid(record, now) && now < record.refreshAfter;
1703
+ }
1704
+ function toCredential(record) {
1705
+ return {
1706
+ issuer: record.issuer,
1707
+ audience: record.audience,
1708
+ ...record.identity,
1709
+ accessToken: record.accessToken,
1710
+ expiresAt: record.expiresAt,
1711
+ apiUrl: record.apiUrl,
1712
+ generation: record.generation,
1713
+ storage: "environment",
1714
+ session: {
1715
+ userId: record.userId,
1716
+ displayName: record.displayName,
1717
+ ...record.githubLogin ? { githubLogin: record.githubLogin } : {},
1718
+ refreshAfter: record.refreshAfter
1719
+ }
1720
+ };
1721
+ }
1722
+ function identified(record, reused) {
1723
+ return {
1724
+ status: "ok",
1725
+ credential: toCredential(record),
1726
+ displayName: record.displayName,
1727
+ ...record.githubLogin ? { githubLogin: record.githubLogin } : {},
1728
+ reused
1729
+ };
1730
+ }
1731
+ function cachedSessionCredential(deps = {}) {
1732
+ if (!sessionIdentityMode(deps)) return void 0;
1733
+ let context;
1734
+ try {
1735
+ context = sessionContext(deps);
1736
+ } catch {
1737
+ return void 0;
1738
+ }
1739
+ if ("status" in context) return void 0;
1740
+ const record = readToken(context);
1741
+ return record && tokenValid(record) ? toCredential(record) : void 0;
1742
+ }
1743
+ function outcomeFromState(state) {
1744
+ if (state.status === "link_required" && state.githubLogin && state.challengeId)
1745
+ return {
1746
+ status: "link_required",
1747
+ githubLogin: state.githubLogin,
1748
+ challengeId: state.challengeId,
1749
+ challengeExpiresAt: state.challengeExpiresAt ?? 0
1750
+ };
1751
+ return failure(
1752
+ state.code,
1753
+ state.cause ?? "the last identity check failed",
1754
+ state.remedy ?? RETRY_REMEDY
1755
+ );
1756
+ }
1757
+ function parseInstant(value) {
1758
+ if (finiteNumber(value) && value > 0) return value < 1e12 ? value * 1e3 : value;
1759
+ if (typeof value === "string" && value.length <= 64) {
1760
+ const parsed = Date.parse(value);
1761
+ return Number.isFinite(parsed) ? parsed : void 0;
1762
+ }
1763
+ return void 0;
1764
+ }
1765
+ async function sendJson(url, init, fetchImpl) {
1766
+ const response = await fetchImpl(url, { ...init, redirect: "error" });
1767
+ let value;
1768
+ try {
1769
+ const parsed = await readBoundedJson(response, RESPONSE_MAX_BYTES);
1770
+ value = parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : void 0;
1771
+ } catch {
1772
+ value = void 0;
1773
+ }
1774
+ return { status: response.status, value };
1775
+ }
1776
+ function environmentOnly(deps) {
1777
+ return { ...deps, environmentOnly: true };
1778
+ }
1779
+ async function environmentRequest(method, path, body, deps, signal) {
1780
+ const send = async (credential2) => {
1781
+ const headers = { "Content-Type": "application/json" };
1782
+ const text = body === void 0 ? void 0 : JSON.stringify(body);
1783
+ if (credential2.tokenInjection) {
1784
+ const response = await forwardMachineRequest(
1785
+ { method, path, headers, ...text === void 0 ? {} : { body: text } },
1786
+ signal,
1787
+ environmentOnly(deps)
1788
+ );
1789
+ const parsed = await response.json().catch(() => void 0);
1790
+ return {
1791
+ status: response.status,
1792
+ value: parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : void 0
1793
+ };
1794
+ }
1795
+ return sendJson(
1796
+ `${credential2.apiUrl}${path}`,
1797
+ {
1798
+ method,
1799
+ headers: { ...headers, Authorization: `Bearer ${credential2.accessToken}` },
1800
+ ...text === void 0 ? {} : { body: text },
1801
+ signal: signal ?? AbortSignal.timeout(GIT_TIMEOUT_MS2)
1802
+ },
1803
+ deps.fetch ?? fetch
1804
+ );
1805
+ };
1806
+ let credential = await acquireMachineCredential({ signal }, environmentOnly(deps));
1807
+ if (!credential) throw new MachineAuthError("identity_unavailable", "No environment credential.");
1808
+ let answer = await send(credential);
1809
+ if (answer.status === 401) {
1810
+ credential = await acquireMachineCredential({ force: true, signal }, environmentOnly(deps));
1811
+ if (!credential)
1812
+ throw new MachineAuthError("identity_unavailable", "No environment credential.");
1813
+ answer = await send(credential);
1814
+ }
1815
+ return answer;
1816
+ }
1817
+ function environmentFailure(error, apiUrl) {
1818
+ if (error instanceof MachineAuthError && error.terminal)
1819
+ return failure(
1820
+ "environment_credential_rejected",
1821
+ "Primitive rejected the cloud environment's credential",
1822
+ ENVIRONMENT_CREDENTIAL_REMEDY
1823
+ );
1824
+ const host = (() => {
1825
+ try {
1826
+ return new URL(apiUrl).hostname;
1827
+ } catch {
1828
+ return "Primitive";
1829
+ }
1830
+ })();
1831
+ return failure(
1832
+ "identity_unavailable",
1833
+ `Primitive could not be reached for the identity check${error instanceof MachineAuthError ? ` (${terminalSafeLine(error.message).slice(0, 200)})` : ""}`,
1834
+ `check that ${host} is under the cloud environment's Allowed domains, then ${RETRY_REMEDY}`
1835
+ );
1836
+ }
1837
+ function answerError(answer) {
1838
+ return typeof answer.value?.error === "string" ? answer.value.error : void 0;
1839
+ }
1840
+ async function git(root, args, signal) {
1841
+ try {
1842
+ const { stdout, stderr } = await promisify(execFile)("git", args, {
1843
+ cwd: root,
1844
+ encoding: "utf8",
1845
+ timeout: GIT_TIMEOUT_MS2,
1846
+ signal,
1847
+ env: { ...gitChildEnvironment(), GIT_TERMINAL_PROMPT: "0" },
1848
+ maxBuffer: 1024 * 1024
1849
+ });
1850
+ return { ok: true, code: 0, stdout, stderr, timedOut: false };
1851
+ } catch (error) {
1852
+ const failed = error;
1853
+ return {
1854
+ ok: false,
1855
+ code: typeof failed.code === "number" ? failed.code : void 0,
1856
+ stdout: failed.stdout ?? "",
1857
+ stderr: failed.stderr ?? "",
1858
+ timedOut: failed.killed === true || failed.signal === "SIGTERM"
1859
+ };
1860
+ }
1861
+ }
1862
+ function gitDetail(stderr) {
1863
+ const lines = stderr.split("\n").map((line) => terminalSafeLine(line.replace(/\/\/[^/\s@]+@/gu, "//"))).filter(Boolean);
1864
+ return (lines.find((line) => /error|denied|refused|forbidden|403|fatal/iu.test(line)) ?? lines.at(-1) ?? "no detail").slice(0, 200);
1865
+ }
1866
+ async function defaultSleep2(milliseconds, signal) {
1867
+ await new Promise((resolve9, reject) => {
1868
+ const timer = setTimeout(resolve9, milliseconds);
1869
+ signal?.addEventListener(
1870
+ "abort",
1871
+ () => {
1872
+ clearTimeout(timer);
1873
+ reject(signal.reason);
1874
+ },
1875
+ { once: true }
1876
+ );
1877
+ });
1878
+ }
1879
+ async function pollChallenge(apiUrl, challengeId, repository, deps, signal) {
1880
+ const sleep = deps.sleep ?? defaultSleep2;
1881
+ const deadline = Date.now() + (deps.pollBudgetMs ?? POLL_BUDGET_MS);
1882
+ let delay = POLL_FIRST_DELAY_MS;
1883
+ let unreachable;
1884
+ for (; ; ) {
1885
+ const remaining = deadline - Date.now();
1886
+ if (remaining <= 0) break;
1887
+ await sleep(Math.min(delay, remaining), signal);
1888
+ delay = Math.min(POLL_MAX_DELAY_MS, Math.round(delay * 1.5));
1889
+ let answer;
1890
+ try {
1891
+ answer = await environmentRequest(
1892
+ "GET",
1893
+ `${SESSION_IDENTITY_ROUTES.challenge}/${encodeURIComponent(challengeId)}`,
1894
+ void 0,
1895
+ deps,
1896
+ signal
1897
+ );
1898
+ } catch (error) {
1899
+ signal?.throwIfAborted();
1900
+ unreachable = error;
1901
+ continue;
1902
+ }
1903
+ if (answer.status === 404) return CHALLENGE_GONE;
1904
+ if (answer.status === 401 || answer.status === 403)
1905
+ return environmentFailure(new MachineAuthError("rejected", "rejected", true), apiUrl);
1906
+ if (answer.status < 200 || answer.status > 299) {
1907
+ unreachable = new MachineAuthError("identity_unavailable", `HTTP ${answer.status}`);
1908
+ continue;
1909
+ }
1910
+ unreachable = void 0;
1911
+ const status = answer.value;
1912
+ if (status?.status === "verified")
1913
+ return {
1914
+ ...machineString(status.githubLogin, 64) ? { githubLogin: status.githubLogin } : {}
1915
+ };
1916
+ if (status?.status === "expired")
1917
+ return failure(
1918
+ "challenge_expired",
1919
+ `the identity check expired before Primitive received GitHub's notice of the push to ${repository}`,
1920
+ NEW_SESSION_REMEDY
1921
+ );
1922
+ if (status?.status === "rejected")
1923
+ return rejectionFailure(status.reason, repository);
1924
+ }
1925
+ if (unreachable) return environmentFailure(unreachable, apiUrl);
1926
+ return failure(
1927
+ "webhook_timeout",
1928
+ `GitHub's notice of the identity push to ${repository} did not reach Primitive within ${Math.round((deps.pollBudgetMs ?? POLL_BUDGET_MS) / 1e3)} s`,
1929
+ `check that Primitive's GitHub App is installed with access to ${repository}, then ${RETRY_REMEDY}`
1930
+ );
1931
+ }
1932
+ function parseTokenAnswer(value) {
1933
+ if (!value) return void 0;
1934
+ const user = value.user;
1935
+ const expiresAt = parseInstant(value.expiresAt);
1936
+ const refreshAfter = parseInstant(value.refreshAfter) ?? expiresAt;
1937
+ if (!machineString(value.accessToken, 8192) || !value.accessToken.startsWith(SESSION_TOKEN_PREFIX) || !expiresAt || !refreshAfter || !user || !machineString(user.id, 256) || !machineString(user.displayName, 256) || !machineString(value.organizationId, 256))
1938
+ return void 0;
1939
+ return {
1940
+ accessToken: value.accessToken,
1941
+ expiresAt,
1942
+ refreshAfter: Math.min(refreshAfter, expiresAt),
1943
+ userId: user.id,
1944
+ displayName: user.displayName,
1945
+ organizationId: value.organizationId
1946
+ };
1947
+ }
1948
+ var SERVER_CONTRACT_FAILURE = failure(
1949
+ "server_contract",
1950
+ "Primitive's answer did not identify the linked member",
1951
+ "update prim (`npx --yes @primitive.ai/prim@latest`) and run `prim setup --cloud`; if it persists, report it to Primitive"
1952
+ );
1953
+ async function recordFor(context, answer, extra, deps, signal) {
1954
+ let identity;
1955
+ let environment;
1956
+ try {
1957
+ environment = await acquireMachineCredential({ signal }, environmentOnly(deps));
1958
+ identity = await verifyMachineIdentity(
1959
+ context.apiUrl,
1960
+ answer.accessToken,
1961
+ context.clientId,
1962
+ signal,
1963
+ deps.fetch
1964
+ );
1965
+ } catch (error) {
1966
+ if (error instanceof MachineAuthError && error.code === "machine_identity_rejected")
1967
+ return SERVER_CONTRACT_FAILURE;
1968
+ return environmentFailure(error, context.apiUrl);
1969
+ }
1970
+ if (!environment || identity.authorizedUserId !== answer.userId || identity.organizationId !== answer.organizationId)
1971
+ return SERVER_CONTRACT_FAILURE;
1972
+ return {
1973
+ version: 1,
1974
+ apiUrl: context.apiUrl,
1975
+ clientId: context.clientId,
1976
+ generation: context.generation,
1977
+ sessionId: context.sessionId,
1978
+ issuer: environment.issuer,
1979
+ audience: environment.audience,
1980
+ accessToken: answer.accessToken,
1981
+ expiresAt: answer.expiresAt,
1982
+ refreshAfter: answer.refreshAfter,
1983
+ userId: answer.userId,
1984
+ displayName: answer.displayName,
1985
+ organizationId: answer.organizationId,
1986
+ ...extra.githubLogin ? { githubLogin: extra.githubLogin } : {},
1987
+ identity,
1988
+ ...extra.repositoryRoot ? { repositoryRoot: extra.repositoryRoot } : {}
1989
+ };
1990
+ }
1991
+ async function refreshToken(context, record, deps, signal) {
1992
+ let answer;
1993
+ try {
1994
+ answer = await environmentRequest(
1995
+ "POST",
1996
+ SESSION_IDENTITY_ROUTES.refresh,
1997
+ { accessToken: record.accessToken },
1998
+ deps,
1999
+ signal
2000
+ );
2001
+ } catch (error) {
2002
+ signal?.throwIfAborted();
2003
+ return error instanceof MachineAuthError && error.terminal ? { status: "refused", failure: environmentFailure(error, context.apiUrl) } : { status: "unavailable" };
2004
+ }
2005
+ const code = answerError(answer);
2006
+ if (answer.status === 401 && (code === "session_revoked" || code === "invalid_session_token"))
2007
+ return { status: "refused", failure: SESSION_REVOKED };
2008
+ if (answer.status === 401 || answer.status === 403)
2009
+ return {
2010
+ status: "refused",
2011
+ failure: environmentFailure(
2012
+ new MachineAuthError("rejected", "rejected", true),
2013
+ context.apiUrl
2014
+ )
2015
+ };
2016
+ const token = answer.status === 200 ? parseTokenAnswer(answer.value) : void 0;
2017
+ if (!token || token.userId !== record.userId || token.organizationId !== record.organizationId)
2018
+ return { status: "unavailable" };
2019
+ return {
2020
+ status: "ok",
2021
+ record: {
2022
+ ...record,
2023
+ accessToken: token.accessToken,
2024
+ expiresAt: token.expiresAt,
2025
+ refreshAfter: token.refreshAfter,
2026
+ displayName: token.displayName
2027
+ }
2028
+ };
2029
+ }
2030
+ function exchangeRefusal(answer, repository) {
2031
+ if (answer.status === 404) return CHALLENGE_GONE;
2032
+ if (answer.status !== 409) return void 0;
2033
+ switch (answerError(answer)) {
2034
+ case "identity_mismatch":
2035
+ return rejectionFailure("identity_mismatch", repository);
2036
+ case "challenge_rejected":
2037
+ return rejectionFailure(answer.value?.reason, repository);
2038
+ case "challenge_expired":
2039
+ return CHALLENGE_WINDOW_PASSED;
2040
+ case "challenge_already_exchanged":
2041
+ return failure(
2042
+ "challenge_already_exchanged",
2043
+ "this session's identity check was already exchanged for a token this VM does not hold",
2044
+ NEW_SESSION_REMEDY
2045
+ );
2046
+ case "challenge_pending":
2047
+ return failure(
2048
+ "webhook_timeout",
2049
+ `GitHub's notice of the identity push to ${repository} has not reached Primitive yet`,
2050
+ `check that Primitive's GitHub App is installed with access to ${repository}, then ${RETRY_REMEDY}`
2051
+ );
2052
+ default:
2053
+ return void 0;
2054
+ }
2055
+ }
2056
+ async function exchangeChallenge(context, challenge, repositoryRoot, deps, signal) {
2057
+ let answer;
2058
+ try {
2059
+ answer = await environmentRequest(
2060
+ "POST",
2061
+ SESSION_IDENTITY_ROUTES.token,
2062
+ { challengeId: challenge.challengeId },
2063
+ deps,
2064
+ signal
2065
+ );
2066
+ } catch (error) {
2067
+ signal?.throwIfAborted();
2068
+ return environmentFailure(error, context.apiUrl);
2069
+ }
2070
+ if (answer.status === 409 && answerError(answer) === "github_account_not_linked") {
2071
+ const login = answer.value?.githubLogin;
2072
+ return {
2073
+ status: "link_required",
2074
+ githubLogin: machineString(login, 64) ? login : challenge.githubLogin ?? "unknown",
2075
+ challengeId: challenge.challengeId,
2076
+ challengeExpiresAt: challenge.challengeExpiresAt
2077
+ };
2078
+ }
2079
+ const refused = exchangeRefusal(
2080
+ answer,
2081
+ repositoryRoot && githubRepositoryFullName(repositoryRoot) || "the repository"
2082
+ );
2083
+ if (refused) return refused;
2084
+ const token = answer.status === 200 ? parseTokenAnswer(answer.value) : void 0;
2085
+ if (!token) {
2086
+ if (answer.status === 401 || answer.status === 403)
2087
+ return environmentFailure(new MachineAuthError("rejected", "rejected", true), context.apiUrl);
2088
+ return answer.status >= 500 ? environmentFailure(
2089
+ new MachineAuthError("identity_unavailable", `HTTP ${answer.status}`),
2090
+ context.apiUrl
2091
+ ) : SERVER_CONTRACT_FAILURE;
2092
+ }
2093
+ return recordFor(
2094
+ context,
2095
+ token,
2096
+ { githubLogin: challenge.githubLogin, repositoryRoot },
2097
+ deps,
2098
+ signal
2099
+ );
2100
+ }
2101
+ async function challengeAndPush(context, root, previous, deps, attempt, signal) {
2102
+ const env = deps.env ?? process.env;
2103
+ const repository = githubRepositoryFullName(root);
2104
+ if (!repository)
2105
+ return failure(
2106
+ "repository_unidentified",
2107
+ "this checkout does not name its GitHub repository",
2108
+ "run it in the repository the session cloned; for a checkout with no GitHub origin, commit its repository declaration with `prim claude install --scope project` from a clone whose origin is on GitHub"
2109
+ );
2110
+ const branch = currentBranch(root);
2111
+ if (!branch || !SESSION_BRANCH.test(branch) || branch.includes("..") || branch.endsWith(".lock"))
2112
+ return failure(
2113
+ "not_session_branch",
2114
+ `this checkout is on ${branch ? `branch ${terminalSafeLine(branch).slice(0, 120)}` : "a detached HEAD"}, not the session's own claude/\u2026 branch, so prim cannot prove who started the session and pushed nothing`,
2115
+ `${NEW_SESSION_REMEDY} and let it identify you before switching branches`
2116
+ );
2117
+ attempt.branch = branch;
2118
+ let baseSha = previous?.branch === branch && previous.baseSha ? previous.baseSha : void 0;
2119
+ if (!baseSha) {
2120
+ const head = await git(root, ["rev-parse", "--verify", "HEAD^{commit}"], signal);
2121
+ baseSha = head.stdout.trim();
2122
+ if (!head.ok || !SHA.test(baseSha))
2123
+ return failure(
2124
+ "no_commit",
2125
+ "this checkout has no commit to create the session branch at",
2126
+ NEW_SESSION_REMEDY
2127
+ );
2128
+ }
2129
+ const published = await git(
2130
+ root,
2131
+ [
2132
+ "for-each-ref",
2133
+ "--count=1",
2134
+ "--format=%(refname)",
2135
+ "--contains",
2136
+ baseSha,
2137
+ "refs/remotes/origin/"
2138
+ ],
2139
+ signal
2140
+ );
2141
+ if (!published.ok || published.stdout.trim() === "")
2142
+ return failure(
2143
+ "unpublished_commits",
2144
+ `this checkout's commit ${baseSha.slice(0, 12)} is not on GitHub yet, and creating the session branch at it would publish it, so prim pushed nothing`,
2145
+ `${NEW_SESSION_REMEDY} and let it identify you before committing`
2146
+ );
2147
+ attempt.baseSha = baseSha;
2148
+ const remote = await git(
2149
+ root,
2150
+ ["ls-remote", "--exit-code", "origin", `refs/heads/${branch}`],
2151
+ signal
2152
+ );
2153
+ const recorded = previous?.branch === branch && previous.challengeId ? { challengeId: previous.challengeId, challengeExpiresAt: previous.challengeExpiresAt ?? 0 } : void 0;
2154
+ if (remote.ok && recorded) {
2155
+ Object.assign(attempt, recorded);
2156
+ return { ...recorded, repository };
2157
+ }
2158
+ if (remote.ok)
2159
+ return failure(
2160
+ "branch_exists",
2161
+ `the session branch ${branch} already exists on GitHub, so this session cannot prove who started it`,
2162
+ NEW_SESSION_REMEDY
2163
+ );
2164
+ if (remote.code !== 2)
2165
+ return failure(
2166
+ remote.timedOut ? "push_timeout" : "remote_unavailable",
2167
+ `prim could not check ${repository} for the session branch (${remote.timedOut ? "timed out" : gitDetail(remote.stderr)})`,
2168
+ `check the session's access to ${repository} on GitHub, then ${RETRY_REMEDY}`
2169
+ );
2170
+ if (recorded && previous?.baseSha === baseSha && recorded.challengeExpiresAt > Date.now() + CHALLENGE_REUSE_MARGIN_MS) {
2171
+ Object.assign(attempt, recorded);
2172
+ return pushSessionBranch(root, repository, branch, baseSha, recorded, signal);
2173
+ }
2174
+ let answer;
2175
+ try {
2176
+ const email = env[USER_EMAIL_VARIABLE]?.trim();
2177
+ answer = await environmentRequest(
2178
+ "POST",
2179
+ SESSION_IDENTITY_ROUTES.challenge,
2180
+ {
2181
+ repositoryFullName: repository,
2182
+ claudeSessionId: context.sessionId,
2183
+ branch,
2184
+ baseSha,
2185
+ // Only a cross-check: one Primitive would refuse is left out, not sent.
2186
+ ...email && email.length <= 320 && EMAIL_HINT.test(email) ? { userEmailHint: email } : {}
2187
+ },
2188
+ deps,
2189
+ signal
2190
+ );
2191
+ } catch (error) {
2192
+ signal?.throwIfAborted();
2193
+ return environmentFailure(error, context.apiUrl);
2194
+ }
2195
+ if (answer.status === 404 && answerError(answer) === "repository_not_connected")
2196
+ return failure(
2197
+ "repository_not_connected",
2198
+ `${repository} is not connected to Primitive`,
2199
+ CLOUD_GITHUB_CONNECT_REMEDY
2200
+ );
2201
+ if (answer.status === 401 || answer.status === 403)
2202
+ return environmentFailure(new MachineAuthError("rejected", "rejected", true), context.apiUrl);
2203
+ if (answer.status === 409 && answerError(answer) === "challenge_already_open")
2204
+ return failure(
2205
+ "challenge_open",
2206
+ `an identity check for ${branch} on ${repository} is still open from an earlier attempt that this VM did not record`,
2207
+ `wait five minutes, then ${RETRY_REMEDY}`
2208
+ );
2209
+ if (answer.status === 429)
2210
+ return failure(
2211
+ "too_many_challenges",
2212
+ "too many sessions of this cloud environment are being identified at once",
2213
+ `wait a few minutes, then ${RETRY_REMEDY}`
2214
+ );
2215
+ const challengeId = answer.value?.challengeId;
2216
+ const challengeExpiresAt = parseInstant(answer.value?.expiresAt);
2217
+ if (answer.status !== 200 || !machineString(challengeId, 256) || !challengeExpiresAt)
2218
+ return answer.status >= 500 ? environmentFailure(
2219
+ new MachineAuthError("identity_unavailable", `HTTP ${answer.status}`),
2220
+ context.apiUrl
2221
+ ) : SERVER_CONTRACT_FAILURE;
2222
+ if (answer.value?.ref !== `refs/heads/${branch}`) return SERVER_CONTRACT_FAILURE;
2223
+ attempt.challengeId = challengeId;
2224
+ attempt.challengeExpiresAt = challengeExpiresAt;
2225
+ return pushSessionBranch(
2226
+ root,
2227
+ repository,
2228
+ branch,
2229
+ baseSha,
2230
+ { challengeId, challengeExpiresAt },
2231
+ signal
2232
+ );
2233
+ }
2234
+ async function pushSessionBranch(root, repository, branch, baseSha, challenge, signal) {
2235
+ const push = await git(
2236
+ root,
2237
+ [
2238
+ "-c",
2239
+ "core.hooksPath=/dev/null",
2240
+ "-c",
2241
+ "push.followTags=false",
2242
+ "-c",
2243
+ "push.recurseSubmodules=no",
2244
+ "-c",
2245
+ "push.gpgSign=false",
2246
+ "-c",
2247
+ "push.pushOption=",
2248
+ "push",
2249
+ "--no-verify",
2250
+ "--no-follow-tags",
2251
+ "--no-recurse-submodules",
2252
+ "--no-signed",
2253
+ "--quiet",
2254
+ "origin",
2255
+ `${baseSha}:refs/heads/${branch}`
2256
+ ],
2257
+ signal
2258
+ );
2259
+ if (!push.ok)
2260
+ return push.timedOut ? failure(
2261
+ "push_timeout",
2262
+ `creating the session branch ${branch} on ${repository} did not finish in ${GIT_TIMEOUT_MS2 / 1e3} s`,
2263
+ `check the session's network access to GitHub, then ${RETRY_REMEDY}`
2264
+ ) : failure(
2265
+ "push_refused",
2266
+ `creating the session branch ${branch} on ${repository} was refused (${gitDetail(push.stderr)})`,
2267
+ `check that the GitHub account that started this session can push to ${repository} and that the cloud environment lets the session push, then ${NEW_SESSION_REMEDY}`
2268
+ );
2269
+ return { ...challenge, repository };
2270
+ }
2271
+ async function ensureSessionIdentity(options = {}, deps = {}) {
2272
+ let context;
2273
+ try {
2274
+ context = sessionContext(deps);
2275
+ } catch (error) {
2276
+ return failure(
2277
+ "environment_credential_invalid",
2278
+ error instanceof MachineAuthError ? terminalSafeLine(error.message).replace(/\.$/u, "") : "the environment credential is misconfigured",
2279
+ "correct the cloud environment's PRIM_M2M_* variables, then start a new cloud session"
2280
+ );
2281
+ }
2282
+ if ("status" in context) return context;
2283
+ const ctx = context;
2284
+ const startedAt = Date.now();
2285
+ prepareMachineMetadataDirectory(ctx.directory);
2286
+ return withFileLock(
2287
+ ctx.lockPath,
2288
+ async () => {
2289
+ const record = readToken(ctx);
2290
+ const forced = options.force === true && (!options.observedToken || options.observedToken === record?.accessToken);
2291
+ if (record && !forced && tokenFresh(record)) return identified(record, true);
2292
+ if (record) {
2293
+ const refreshed = await refreshToken(ctx, record, deps, options.signal);
2294
+ if (refreshed.status === "ok") {
2295
+ writeToken(ctx, refreshed.record);
2296
+ return identified(refreshed.record, true);
2297
+ }
2298
+ if (refreshed.status === "refused") {
2299
+ rmSync5(ctx.tokenPath, { force: true });
2300
+ writeState(ctx, {
2301
+ sessionId: ctx.sessionId,
2302
+ status: "failed",
2303
+ code: refreshed.failure.code,
2304
+ cause: refreshed.failure.cause,
2305
+ remedy: refreshed.failure.remedy,
2306
+ ...record.repositoryRoot ? { repositoryRoot: record.repositoryRoot } : {},
2307
+ at: Date.now()
2308
+ });
2309
+ return refreshed.failure;
2310
+ }
2311
+ if (!forced && tokenValid(record)) return identified(record, true);
2312
+ }
2313
+ const state = readState(ctx);
2314
+ if (!record && state && FINAL_CODES.has(state.code)) return outcomeFromState(state);
2315
+ const root = (options.cwd ? gitToplevel(options.cwd) : null) ?? record?.repositoryRoot ?? state?.repositoryRoot;
2316
+ if (!options.explicit) {
2317
+ if (!root || !(record || state))
2318
+ return failure(
2319
+ "not_identified",
2320
+ "this session has not identified who started it yet",
2321
+ RETRY_REMEDY
2322
+ );
2323
+ if (state && state.at > Date.now() - BACKGROUND_RETRY_MS) return outcomeFromState(state);
2324
+ } else if (state && state.at >= startedAt) {
2325
+ return outcomeFromState(state);
2326
+ }
2327
+ if (!root)
2328
+ return failure(
2329
+ "repository_missing",
2330
+ "this is not a git repository",
2331
+ "run it in the repository the session cloned"
2332
+ );
2333
+ const attempt = { root };
2334
+ const remember = (outcome) => {
2335
+ writeState(ctx, {
2336
+ sessionId: ctx.sessionId,
2337
+ status: outcome.status,
2338
+ code: outcome.status === "failed" ? outcome.code : "github_account_not_linked",
2339
+ ...outcome.status === "failed" ? { cause: outcome.cause, remedy: outcome.remedy } : {
2340
+ githubLogin: outcome.githubLogin
2341
+ },
2342
+ challengeId: outcome.status === "link_required" ? outcome.challengeId : attempt.challengeId,
2343
+ challengeExpiresAt: outcome.status === "link_required" ? outcome.challengeExpiresAt : attempt.challengeExpiresAt,
2344
+ repositoryRoot: root,
2345
+ branch: attempt.branch ?? state?.branch,
2346
+ baseSha: attempt.baseSha ?? state?.baseSha,
2347
+ at: Date.now()
2348
+ });
2349
+ return outcome;
2350
+ };
2351
+ let challenge;
2352
+ if (state?.code === "webhook_timeout" && state.challengeId && (state.challengeExpiresAt ?? 0) > Date.now()) {
2353
+ attempt.challengeId = state.challengeId;
2354
+ attempt.challengeExpiresAt = state.challengeExpiresAt;
2355
+ attempt.branch = state.branch;
2356
+ attempt.baseSha = state.baseSha;
2357
+ challenge = {
2358
+ challengeId: state.challengeId,
2359
+ challengeExpiresAt: state.challengeExpiresAt ?? 0,
2360
+ repository: githubRepositoryFullName(root) ?? "the repository"
2361
+ };
2362
+ } else if (state?.status === "link_required" && state.challengeId) {
2363
+ attempt.challengeId = state.challengeId;
2364
+ attempt.challengeExpiresAt = state.challengeExpiresAt;
2365
+ const exchanged2 = await exchangeChallenge(
2366
+ ctx,
2367
+ {
2368
+ challengeId: state.challengeId,
2369
+ challengeExpiresAt: state.challengeExpiresAt ?? 0,
2370
+ githubLogin: state.githubLogin
2371
+ },
2372
+ root,
2373
+ deps,
2374
+ options.signal
2375
+ );
2376
+ if ("status" in exchanged2) return remember(exchanged2);
2377
+ writeToken(ctx, exchanged2);
2378
+ return identified(exchanged2, false);
2379
+ } else if (!options.explicit) {
2380
+ return state ? outcomeFromState(state) : failure(
2381
+ "not_identified",
2382
+ "this session has not identified who started it yet",
2383
+ RETRY_REMEDY
2384
+ );
2385
+ } else {
2386
+ const pushed = await challengeAndPush(ctx, root, state, deps, attempt, options.signal);
2387
+ if ("status" in pushed) return remember(pushed);
2388
+ challenge = pushed;
2389
+ }
2390
+ const verified = await pollChallenge(
2391
+ ctx.apiUrl,
2392
+ challenge.challengeId,
2393
+ challenge.repository,
2394
+ // A hook process waits only briefly for a late notice.
2395
+ options.explicit ? deps : { ...deps, pollBudgetMs: Math.min(deps.pollBudgetMs ?? POLL_BUDGET_MS, 3e3) },
2396
+ options.signal
2397
+ );
2398
+ if ("status" in verified) return remember(verified);
2399
+ const exchanged = await exchangeChallenge(
2400
+ ctx,
2401
+ { ...challenge, githubLogin: verified.githubLogin },
2402
+ root,
2403
+ deps,
2404
+ options.signal
2405
+ );
2406
+ if ("status" in exchanged) return remember(exchanged);
2407
+ writeToken(ctx, exchanged);
2408
+ return identified(exchanged, false);
2409
+ },
2410
+ { signal: options.signal, timeoutMs: LOCK_TIMEOUT_MS }
2411
+ );
2412
+ }
2413
+ async function acquireSessionCredential(options = {}, deps = {}) {
2414
+ const cached2 = cachedSessionCredential(deps);
2415
+ const fresh = cached2?.session !== void 0 && Date.now() < cached2.session.refreshAfter;
2416
+ if (cached2 && fresh && !options.force) return cached2;
2417
+ const signal = options.signal ? AbortSignal.any([options.signal, AbortSignal.timeout(1e4)]) : AbortSignal.timeout(1e4);
2418
+ let outcome;
2419
+ try {
2420
+ outcome = await ensureSessionIdentity(
2421
+ { force: options.force, observedToken: cached2?.accessToken, signal },
2422
+ deps
2423
+ );
2424
+ } catch (error) {
2425
+ options.signal?.throwIfAborted();
2426
+ if (error instanceof MachineAuthError) throw error;
2427
+ throw new MachineAuthError(
2428
+ "identity_unavailable",
2429
+ "Identifying who started this cloud session is still in progress; retry shortly."
2430
+ );
2431
+ }
2432
+ if (outcome.status === "ok") return outcome.credential;
2433
+ throw new MachineAuthError(
2434
+ outcome.status === "link_required" ? "github_account_not_linked" : outcome.code,
2435
+ sessionIdentityMessage(outcome)
2436
+ );
2437
+ }
2438
+
988
2439
  // src/lib/machine-credentials.ts
2440
+ function sessionScoped(deps) {
2441
+ return !deps.localEnvironment && !deps.environmentOnly && sessionIdentityMode(deps);
2442
+ }
989
2443
  var require2 = createRequire(import.meta.url);
990
2444
  var SERVICE = "ai.primitive.prim.machine";
991
- var DEFAULT_API_URL = "https://api.getprimitive.ai";
2445
+ var DEFAULT_API_URL2 = "https://api.getprimitive.ai";
992
2446
  var PROFILE_FILE = "machine_profile.json";
993
- var RENEW_BEFORE_MS = 6e4;
2447
+ var RENEW_BEFORE_MS2 = 6e4;
994
2448
  var cached;
995
2449
  function configurationDirectory(deps) {
996
2450
  return deps.directory ?? primConfigDirectory({ env: deps.env });
997
2451
  }
998
2452
  function apiUrlFor(deps) {
999
- return machineApiUrl((deps.env ?? process.env).PRIM_API_URL?.trim() || DEFAULT_API_URL);
2453
+ return machineApiUrl((deps.env ?? process.env).PRIM_API_URL?.trim() || DEFAULT_API_URL2);
1000
2454
  }
1001
- function hash(value) {
1002
- return createHash3("sha256").update(value).digest("hex");
2455
+ function hash2(value) {
2456
+ return createHash5("sha256").update(value).digest("hex");
1003
2457
  }
1004
2458
  function recordPath(directory, generation) {
1005
- return join6(directory, `machine_${generation}.json`);
2459
+ return join8(directory, `machine_${generation}.json`);
1006
2460
  }
1007
2461
  function storageKey(directory, generation) {
1008
- return `${hash(directory)}:${generation}`;
2462
+ return `${hash2(directory)}:${generation}`;
1009
2463
  }
1010
2464
  function environmentContextPath(deps, clientId) {
1011
- return join6(
2465
+ return join8(
1012
2466
  configurationDirectory(deps),
1013
- `machine_context_${hash(`${apiUrlFor(deps)}\0${clientId}`)}.json`
2467
+ `machine_context_${hash2(`${apiUrlFor(deps)}\0${clientId}`)}.json`
1014
2468
  );
1015
2469
  }
1016
2470
  function writeEnvironmentContext(credential, deps) {
@@ -1069,14 +2523,14 @@ function readEnvironmentContext(environment, deps) {
1069
2523
  }
1070
2524
  }
1071
2525
  function keyringEntry(key) {
1072
- let directory = dirname4(fileURLToPath3(import.meta.url));
2526
+ let directory = dirname5(fileURLToPath3(import.meta.url));
1073
2527
  for (let depth = 0; depth < 5; depth++) {
1074
- const loader = join6(directory, "native", "keyring.cjs");
2528
+ const loader = join8(directory, "native", "keyring.cjs");
1075
2529
  if (existsSync3(loader)) {
1076
2530
  const module2 = require2(loader);
1077
2531
  return new module2.AsyncEntry(SERVICE, key, { linux: { store: "secret-service" } });
1078
2532
  }
1079
- directory = dirname4(directory);
2533
+ directory = dirname5(directory);
1080
2534
  }
1081
2535
  const module = require2("@napi-rs/keyring");
1082
2536
  return new module.AsyncEntry(SERVICE, key, { linux: { store: "secret-service" } });
@@ -1088,7 +2542,7 @@ function protectPath(path, directory) {
1088
2542
  }
1089
2543
  const encodedPath = Buffer.from(path).toString("base64");
1090
2544
  const script = `$ErrorActionPreference = 'Stop'; $p = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${encodedPath}')); $sid = [Security.Principal.WindowsIdentity]::GetCurrent().User; $acl = [System.Security.AccessControl.${directory ? "DirectorySecurity" : "FileSecurity"}]::new(); $acl.SetOwner($sid); $acl.SetAccessRuleProtection($true, $false); $rule = [System.Security.AccessControl.FileSystemAccessRule]::new($sid, 'FullControl', '${directory ? "ContainerInherit, ObjectInherit" : "None"}', 'None', 'Allow'); $acl.AddAccessRule($rule); [System.IO.${directory ? "Directory" : "File"}]::SetAccessControl($p, $acl)`;
1091
- execFileSync(
2545
+ execFileSync2(
1092
2546
  "powershell.exe",
1093
2547
  [
1094
2548
  "-NoProfile",
@@ -1101,7 +2555,7 @@ function protectPath(path, directory) {
1101
2555
  }
1102
2556
  function ensureDirectory(directory) {
1103
2557
  mkdirSync3(directory, { recursive: true, mode: 448 });
1104
- if (lstatSync3(directory).isSymbolicLink())
2558
+ if (lstatSync4(directory).isSymbolicLink())
1105
2559
  throw new MachineAuthError(
1106
2560
  "unsafe_storage",
1107
2561
  "Credential directory must not be a symbolic link."
@@ -1113,17 +2567,20 @@ function writePrivate(path, value) {
1113
2567
  `, { mode: 384 });
1114
2568
  protectPath(path, false);
1115
2569
  }
2570
+ function readMachineMetadata(path) {
2571
+ return readPrivate(path);
2572
+ }
1116
2573
  function readPrivate(path) {
1117
2574
  let raw;
1118
2575
  try {
1119
- const stat = lstatSync3(path);
2576
+ const stat = lstatSync4(path);
1120
2577
  if (!stat.isFile() || stat.size > 96 * 1024 || process.platform !== "win32" && ((stat.mode & 63) !== 0 || stat.uid !== process.getuid?.())) {
1121
2578
  throw new MachineAuthError(
1122
2579
  "unsafe_storage",
1123
2580
  "Machine credential files must be owner-only regular files."
1124
2581
  );
1125
2582
  }
1126
- raw = readFileSync5(path, "utf8");
2583
+ raw = readFileSync6(path, "utf8");
1127
2584
  } catch (error) {
1128
2585
  if (error.code === "ENOENT") return void 0;
1129
2586
  throw error;
@@ -1168,13 +2625,101 @@ function parseProfile(value) {
1168
2625
  };
1169
2626
  }
1170
2627
  function readMachineProfile(deps = {}) {
1171
- const value = readPrivate(join6(configurationDirectory(deps), PROFILE_FILE));
2628
+ const value = readPrivate(join8(configurationDirectory(deps), PROFILE_FILE));
1172
2629
  return value === void 0 ? void 0 : parseProfile(value);
1173
2630
  }
2631
+ var NETWORK_SECRET_AUTH = "network-secret";
2632
+ var NETWORK_TOKEN_AUTH = "network-token";
2633
+ var INJECTED_IDENTITY_TTL_MS = 60 * 6e4;
2634
+ var brokerKeys = /* @__PURE__ */ new Map();
2635
+ function networkSecretBrokerKey(deps, clientId) {
2636
+ const directory = configurationDirectory(deps);
2637
+ const path = join8(directory, `machine_network_${hash2(`${apiUrlFor(deps)}\0${clientId}`)}.key`);
2638
+ const known = brokerKeys.get(path);
2639
+ if (known) return known;
2640
+ ensureDirectory(directory);
2641
+ const read = () => {
2642
+ try {
2643
+ const stat = lstatSync4(path);
2644
+ if (!stat.isFile() || process.platform !== "win32" && ((stat.mode & 63) !== 0 || typeof process.getuid === "function" && stat.uid !== process.getuid()))
2645
+ throw new MachineAuthError(
2646
+ "unsafe_storage",
2647
+ `The machine broker key at ${path} is not an owner-only file. Delete it and retry.`,
2648
+ true
2649
+ );
2650
+ const value = readFileSync6(path, "utf8").trim();
2651
+ return { key: /^[a-f0-9]{64}$/u.test(value) ? value : void 0 };
2652
+ } catch (error) {
2653
+ if (error.code === "ENOENT") return void 0;
2654
+ throw error;
2655
+ }
2656
+ };
2657
+ for (let attempt = 0; attempt < 2; attempt += 1) {
2658
+ const existing = read();
2659
+ if (existing?.key) {
2660
+ brokerKeys.set(path, existing.key);
2661
+ return existing.key;
2662
+ }
2663
+ if (existing)
2664
+ throw new MachineAuthError(
2665
+ "unsafe_storage",
2666
+ `The machine broker key at ${path} is damaged. Delete it and retry.`,
2667
+ true
2668
+ );
2669
+ const staged = `${path}.${process.pid}.${randomBytes3(6).toString("hex")}`;
2670
+ try {
2671
+ writeFileSync3(staged, `${randomBytes3(32).toString("hex")}
2672
+ `, { mode: 384, flag: "wx" });
2673
+ protectPath(staged, false);
2674
+ linkSync(staged, path);
2675
+ } catch (error) {
2676
+ if (error.code !== "EEXIST") throw error;
2677
+ } finally {
2678
+ rmSync6(staged, { force: true });
2679
+ }
2680
+ }
2681
+ const key = read()?.key;
2682
+ if (!key)
2683
+ throw new MachineAuthError("unsafe_storage", "The machine broker key is unreadable.", true);
2684
+ brokerKeys.set(path, key);
2685
+ return key;
2686
+ }
1174
2687
  function environmentCredentials(deps) {
1175
2688
  const env = deps.env ?? process.env;
1176
- const { PRIM_M2M_CLIENT_ID: clientId, PRIM_M2M_CLIENT_SECRET: clientSecret } = env;
1177
- if (clientId === void 0 && clientSecret === void 0) return void 0;
2689
+ const {
2690
+ PRIM_M2M_CLIENT_ID: clientId,
2691
+ PRIM_M2M_CLIENT_SECRET: clientSecret,
2692
+ PRIM_M2M_CLIENT_AUTH: auth
2693
+ } = env;
2694
+ if (clientId === void 0 && clientSecret === void 0 && auth === void 0) return void 0;
2695
+ if (auth !== void 0 && auth !== NETWORK_SECRET_AUTH && auth !== NETWORK_TOKEN_AUTH)
2696
+ throw new MachineAuthError(
2697
+ "incomplete_machine_credentials",
2698
+ `PRIM_M2M_CLIENT_AUTH accepts ${NETWORK_SECRET_AUTH} or ${NETWORK_TOKEN_AUTH}.`
2699
+ );
2700
+ if (auth !== void 0) {
2701
+ if (!clientId || !/^client_[\w-]+$/u.test(clientId))
2702
+ throw new MachineAuthError(
2703
+ "incomplete_machine_credentials",
2704
+ `Set PRIM_M2M_CLIENT_ID with PRIM_M2M_CLIENT_AUTH=${auth}.`
2705
+ );
2706
+ if (clientSecret !== void 0)
2707
+ throw new MachineAuthError(
2708
+ "conflicting_credentials",
2709
+ `Unset PRIM_M2M_CLIENT_SECRET: with PRIM_M2M_CLIENT_AUTH=${auth} the environment's network secret supplies it.`
2710
+ );
2711
+ const generation = hash2(`${apiUrlFor(deps)}\0${clientId}\0${auth}\0broker-proxy`);
2712
+ const credentials = {
2713
+ clientId,
2714
+ generation,
2715
+ ...auth === NETWORK_TOKEN_AUTH ? { tokenInjection: "network" } : { secretInjection: "network" }
2716
+ };
2717
+ Object.defineProperty(credentials, "clientSecret", {
2718
+ enumerable: true,
2719
+ get: () => networkSecretBrokerKey(deps, clientId)
2720
+ });
2721
+ return credentials;
2722
+ }
1178
2723
  if (!clientId || !clientSecret || !/^client_[\w-]+$/u.test(clientId) || !machineString(clientSecret)) {
1179
2724
  throw new MachineAuthError(
1180
2725
  "incomplete_machine_credentials",
@@ -1184,12 +2729,12 @@ function environmentCredentials(deps) {
1184
2729
  return {
1185
2730
  clientId,
1186
2731
  clientSecret,
1187
- generation: hash(`${apiUrlFor(deps)}\0${clientId}\0${clientSecret}`)
2732
+ generation: hash2(`${apiUrlFor(deps)}\0${clientId}\0${clientSecret}`)
1188
2733
  };
1189
2734
  }
1190
2735
  function hasMachineConfiguration(deps = {}) {
1191
2736
  const env = deps.env ?? process.env;
1192
- const configured = env.PRIM_M2M_CLIENT_ID !== void 0 || env.PRIM_M2M_CLIENT_SECRET !== void 0 || existsSync3(join6(configurationDirectory(deps), PROFILE_FILE));
2737
+ const configured = env.PRIM_M2M_CLIENT_ID !== void 0 || env.PRIM_M2M_CLIENT_SECRET !== void 0 || env.PRIM_M2M_CLIENT_AUTH !== void 0 || existsSync3(join8(configurationDirectory(deps), PROFILE_FILE));
1193
2738
  if (configured && env.PRIM_TOKEN?.trim()) {
1194
2739
  throw new MachineAuthError(
1195
2740
  "conflicting_credentials",
@@ -1201,6 +2746,7 @@ function hasMachineConfiguration(deps = {}) {
1201
2746
  }
1202
2747
  function machineContext(deps = {}) {
1203
2748
  if (!hasMachineConfiguration(deps)) return void 0;
2749
+ if (sessionScoped(deps)) return cachedSessionCredential(deps);
1204
2750
  const environment = environmentCredentials(deps);
1205
2751
  if (environment) {
1206
2752
  if (environmentTerminal === environment.generation) return void 0;
@@ -1215,6 +2761,7 @@ function machineContext(deps = {}) {
1215
2761
  return profile;
1216
2762
  }
1217
2763
  function cachedMachineCredential(deps = {}) {
2764
+ if (sessionScoped(deps)) return cachedSessionCredential(deps);
1218
2765
  const context = machineContext(deps);
1219
2766
  return context && cached?.generation === context.generation && cached.apiUrl === context.apiUrl ? cached : void 0;
1220
2767
  }
@@ -1223,9 +2770,11 @@ function machineSessionEnded(deps = {}) {
1223
2770
  const generation = environmentCredentials(deps)?.generation ?? readMachineProfile(deps)?.generation;
1224
2771
  if (!generation) return false;
1225
2772
  if (environmentCredentials(deps)) return environmentTerminal === generation;
1226
- return readPrivate(join6(configurationDirectory(deps), "machine_terminal.json")) === generation;
2773
+ return readPrivate(join8(configurationDirectory(deps), "machine_terminal.json")) === generation;
1227
2774
  }
1228
2775
  var environmentTerminal;
2776
+ var NETWORK_REJECTION_PAUSE_MS = 3e4;
2777
+ var networkRejection;
1229
2778
  async function loadRecord(profile, deps, signal) {
1230
2779
  const directory = configurationDirectory(deps);
1231
2780
  let value;
@@ -1285,10 +2834,12 @@ async function persistRecord(record, deps, signal) {
1285
2834
  }
1286
2835
  async function acquireMachineCredential(options = {}, deps = {}) {
1287
2836
  if (!hasMachineConfiguration(deps)) return void 0;
2837
+ if (sessionScoped(deps)) return acquireSessionCredential(options, deps);
1288
2838
  const signal = options.signal ? AbortSignal.any([options.signal, AbortSignal.timeout(1e4)]) : AbortSignal.timeout(1e4);
1289
2839
  const apiUrl = apiUrlFor(deps);
1290
2840
  const environment = environmentCredentials(deps);
1291
2841
  if (environment) {
2842
+ const networkManaged = Boolean(environment.secretInjection || environment.tokenInjection);
1292
2843
  const observedToken2 = cached?.generation === environment.generation ? cached.accessToken : void 0;
1293
2844
  const directory2 = configurationDirectory(deps);
1294
2845
  ensureDirectory(directory2);
@@ -1306,22 +2857,24 @@ async function acquireMachineCredential(options = {}, deps = {}) {
1306
2857
  writeEnvironmentContext(cached, deps);
1307
2858
  return cached;
1308
2859
  } catch (error) {
1309
- if (error instanceof MachineAuthError && error.terminal)
2860
+ if (error instanceof MachineAuthError && error.terminal && !networkManaged)
1310
2861
  environmentTerminal = environment.generation;
1311
2862
  throw error;
1312
2863
  }
1313
2864
  }
1314
2865
  return withFileLock(
1315
- join6(directory2, "credentials.lock"),
2866
+ join8(directory2, "credentials.lock"),
1316
2867
  async () => {
1317
2868
  if (machineSessionEnded(deps))
1318
2869
  throw new MachineAuthError(
1319
2870
  "machine_credentials_rejected",
1320
- "Rotate the injected machine credentials.",
2871
+ rejectedCredentialsMessage("Rotate the injected machine credentials.", deps.env),
1321
2872
  true
1322
2873
  );
1323
- if ((!options.force || observedToken2 && cached?.accessToken !== observedToken2) && cached?.generation === environment.generation && cached.expiresAt > Date.now() + RENEW_BEFORE_MS)
2874
+ if ((!options.force || observedToken2 && cached?.accessToken !== observedToken2) && cached?.generation === environment.generation && cached.expiresAt > Date.now() + RENEW_BEFORE_MS2)
1324
2875
  return cached;
2876
+ if (networkManaged && networkRejection?.generation === environment.generation && networkRejection.until > Date.now())
2877
+ throw networkRejection.error;
1325
2878
  try {
1326
2879
  const { configuration, tokens, identity } = await withMachineCooldown(
1327
2880
  directory2,
@@ -1330,13 +2883,36 @@ async function acquireMachineCredential(options = {}, deps = {}) {
1330
2883
  signal,
1331
2884
  async () => {
1332
2885
  const configuration2 = await discoverMachineConfiguration(apiUrl, signal, deps.fetch);
2886
+ if (environment.tokenInjection) {
2887
+ const identity3 = await verifyInjectedMachineIdentity(
2888
+ apiUrl,
2889
+ environment.clientId,
2890
+ signal,
2891
+ deps.fetch
2892
+ );
2893
+ const tokens3 = {
2894
+ accessToken: "",
2895
+ expiresAt: Date.now() + INJECTED_IDENTITY_TTL_MS
2896
+ };
2897
+ return { configuration: configuration2, tokens: tokens3, identity: identity3 };
2898
+ }
1333
2899
  const tokens2 = await exchangeMachineCredentials(
1334
2900
  configuration2,
1335
2901
  environment.clientId,
1336
- environment.clientSecret,
2902
+ // The broker key is not a client secret; the proxy supplies that.
2903
+ environment.secretInjection ? "" : environment.clientSecret,
1337
2904
  signal,
1338
- deps.fetch
1339
- );
2905
+ deps.fetch,
2906
+ { secretInjection: environment.secretInjection }
2907
+ ).catch((error) => {
2908
+ if (environment.secretInjection && error instanceof MachineAuthError && error.code === "token_client_mismatch")
2909
+ throw new MachineAuthError(
2910
+ "network_secret_mismatch",
2911
+ `The token service issued a token for another machine. Check that the network secret's username equals PRIM_M2M_CLIENT_ID (${environment.clientId}).`,
2912
+ true
2913
+ );
2914
+ throw error;
2915
+ });
1340
2916
  const identity2 = await verifyMachineIdentity(
1341
2917
  apiUrl,
1342
2918
  tokens2.accessToken,
@@ -1353,17 +2929,33 @@ async function acquireMachineCredential(options = {}, deps = {}) {
1353
2929
  ...identity,
1354
2930
  apiUrl,
1355
2931
  generation: environment.generation,
1356
- storage: "environment"
2932
+ storage: "environment",
2933
+ ...environment.tokenInjection ? { tokenInjection: "network" } : {}
1357
2934
  };
1358
2935
  writeEnvironmentContext(cached, deps);
1359
2936
  return cached;
1360
2937
  } catch (error) {
2938
+ if (networkManaged && error instanceof MachineAuthError && error.terminal) {
2939
+ networkRejection = {
2940
+ generation: environment.generation,
2941
+ until: Date.now() + NETWORK_REJECTION_PAUSE_MS,
2942
+ error
2943
+ };
2944
+ if (cached?.generation === environment.generation) cached = void 0;
2945
+ const contextPath = environmentContextPath(deps, environment.clientId);
2946
+ try {
2947
+ if (machineRecord(readPrivate(contextPath)).generation === environment.generation)
2948
+ rmSync6(contextPath, { force: true });
2949
+ } catch {
2950
+ }
2951
+ throw error;
2952
+ }
1361
2953
  if (error instanceof MachineAuthError && error.terminal) {
1362
2954
  environmentTerminal = environment.generation;
1363
2955
  const contextPath = environmentContextPath(deps, environment.clientId);
1364
2956
  try {
1365
2957
  if (machineRecord(readPrivate(contextPath)).generation === environment.generation)
1366
- rmSync5(contextPath, { force: true });
2958
+ rmSync6(contextPath, { force: true });
1367
2959
  } catch {
1368
2960
  }
1369
2961
  }
@@ -1377,7 +2969,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
1377
2969
  const expected = machineContext(deps);
1378
2970
  const directory = configurationDirectory(deps);
1379
2971
  return withFileLock(
1380
- join6(directory, "credentials.lock"),
2972
+ join8(directory, "credentials.lock"),
1381
2973
  async () => {
1382
2974
  const profile = readMachineProfile(deps);
1383
2975
  if (!profile || profile.generation !== expected?.generation || profile.apiUrl !== apiUrl)
@@ -1392,7 +2984,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
1392
2984
  true
1393
2985
  );
1394
2986
  let record = await loadRecord(profile, deps, signal);
1395
- if (options.force && (!observedToken || observedToken === record.accessToken) || record.expiresAt <= Date.now() + RENEW_BEFORE_MS) {
2987
+ if (options.force && (!observedToken || observedToken === record.accessToken) || record.expiresAt <= Date.now() + RENEW_BEFORE_MS2) {
1396
2988
  try {
1397
2989
  const { tokens, identity } = await withMachineCooldown(
1398
2990
  directory,
@@ -1427,7 +3019,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
1427
3019
  await persistRecord(record, deps, signal);
1428
3020
  } catch (error) {
1429
3021
  if (error instanceof MachineAuthError && error.terminal)
1430
- writePrivate(join6(directory, "machine_terminal.json"), profile.generation);
3022
+ writePrivate(join8(directory, "machine_terminal.json"), profile.generation);
1431
3023
  throw error;
1432
3024
  }
1433
3025
  }
@@ -1438,6 +3030,24 @@ async function acquireMachineCredential(options = {}, deps = {}) {
1438
3030
  { signal }
1439
3031
  );
1440
3032
  }
3033
+ async function forwardMachineRequest(request3, signal, deps = {}) {
3034
+ const environment = environmentCredentials(deps);
3035
+ if (!environment?.tokenInjection)
3036
+ throw new MachineAuthError(
3037
+ "identity_changed",
3038
+ "Machine identity changed; restart the operation."
3039
+ );
3040
+ const directory = configurationDirectory(deps);
3041
+ ensureDirectory(directory);
3042
+ return forwardBrokerRequest({
3043
+ directory,
3044
+ apiUrl: apiUrlFor(deps),
3045
+ environment,
3046
+ env: deps.env ?? process.env,
3047
+ request: request3,
3048
+ signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(3e4)]) : AbortSignal.timeout(3e4)
3049
+ });
3050
+ }
1441
3051
  function machineCaptureActor(deps = {}) {
1442
3052
  if (!hasMachineConfiguration(deps)) return void 0;
1443
3053
  const context = machineContext(deps);
@@ -1455,25 +3065,37 @@ function machineCaptureActor(deps = {}) {
1455
3065
  return injected ? { kind: "machine", apiUrl: apiUrlFor(deps), clientId: injected.clientId } : void 0;
1456
3066
  }
1457
3067
  function machineJournalBucket(identity) {
1458
- return `_machine_${hash(`${identity.apiUrl}\0${identity.clientId}${identity.authorizedUserId ? `\0${identity.authorizedUserId}` : ""}`)}`;
3068
+ return `_machine_${hash2(`${identity.apiUrl}\0${identity.clientId}${identity.authorizedUserId ? `\0${identity.authorizedUserId}` : ""}`)}`;
3069
+ }
3070
+ function identityPending(actor) {
3071
+ return actor.machineId === void 0 && actor.organizationId === void 0 && actor.authorizedUserId === void 0;
3072
+ }
3073
+ function machinePendingBucket(identity) {
3074
+ return `_machine_pending_${hash2(`${identity.apiUrl}\0${identity.clientId}`)}`;
3075
+ }
3076
+ function prepareMachineMetadataDirectory(directory) {
3077
+ ensureDirectory(directory);
3078
+ }
3079
+ function writeMachineMetadata(path, value) {
3080
+ writePrivate(path, value);
1459
3081
  }
1460
3082
 
1461
3083
  // src/lib/credentials.ts
1462
3084
  var CONFIG_DIRECTORY = primConfigDirectory();
1463
- var TOKEN_FILE_PATH = join7(CONFIG_DIRECTORY, "token");
1464
- var REFRESH_TOKEN_PATH = join7(CONFIG_DIRECTORY, "refresh_token");
1465
- var TOKEN_EXPIRES_PATH = join7(CONFIG_DIRECTORY, "token_expires_at");
1466
- var TERMINAL_REFRESH_PATH = join7(CONFIG_DIRECTORY, "refresh_terminal");
1467
- var CREDENTIAL_METADATA_PATH = join7(CONFIG_DIRECTORY, "credential_metadata.json");
1468
- var CREDENTIAL_FAMILY_PATH = join7(CONFIG_DIRECTORY, "credential_family.json");
1469
- var CREDENTIAL_MIGRATION_PATH = join7(CONFIG_DIRECTORY, "credential_migration.json");
1470
- var CREDENTIAL_LOCK_PATH = join7(CONFIG_DIRECTORY, "credentials.lock");
3085
+ var TOKEN_FILE_PATH = join9(CONFIG_DIRECTORY, "token");
3086
+ var REFRESH_TOKEN_PATH = join9(CONFIG_DIRECTORY, "refresh_token");
3087
+ var TOKEN_EXPIRES_PATH = join9(CONFIG_DIRECTORY, "token_expires_at");
3088
+ var TERMINAL_REFRESH_PATH = join9(CONFIG_DIRECTORY, "refresh_terminal");
3089
+ var CREDENTIAL_METADATA_PATH = join9(CONFIG_DIRECTORY, "credential_metadata.json");
3090
+ var CREDENTIAL_FAMILY_PATH = join9(CONFIG_DIRECTORY, "credential_family.json");
3091
+ var CREDENTIAL_MIGRATION_PATH = join9(CONFIG_DIRECTORY, "credential_migration.json");
3092
+ var CREDENTIAL_LOCK_PATH = join9(CONFIG_DIRECTORY, "credentials.lock");
1471
3093
  var MAX_CREDENTIAL_METADATA_BYTES = 4096;
1472
3094
  var CREDENTIAL_MIGRATION_VERSION = 1;
1473
3095
  var CREDENTIAL_MIGRATION_STATE = "family_bound";
1474
3096
  function readTrimmed(path) {
1475
3097
  try {
1476
- const value = readFileSync6(path, "utf8").trim();
3098
+ const value = readFileSync7(path, "utf8").trim();
1477
3099
  return value || void 0;
1478
3100
  } catch {
1479
3101
  return void 0;
@@ -1482,7 +3104,7 @@ function readTrimmed(path) {
1482
3104
  function resolveAuthCredential(options = {}) {
1483
3105
  if (!options.tokenFilePath && hasMachineConfiguration({ env: options.env })) {
1484
3106
  const machine = cachedMachineCredential({ env: options.env });
1485
- return machine ? { token: machine.accessToken, source: "machine" } : void 0;
3107
+ return machine?.accessToken ? { token: machine.accessToken, source: "machine" } : void 0;
1486
3108
  }
1487
3109
  const envToken = (options.env ?? process.env).PRIM_TOKEN?.trim();
1488
3110
  if (envToken) return { token: envToken, source: "environment" };
@@ -1495,22 +3117,22 @@ function resolveAuthCredential(options = {}) {
1495
3117
  );
1496
3118
  if (metadata.state === "legacy_broker") {
1497
3119
  if (metadata.metadata) {
1498
- const refreshToken3 = readTrimmed(options.refreshTokenPath ?? REFRESH_TOKEN_PATH);
1499
- if (!refreshToken3 || metadata.metadata.accessTokenHash !== credentialFingerprint(stored) || metadata.metadata.refreshTokenHash !== credentialFingerprint(refreshToken3)) {
3120
+ const refreshToken4 = readTrimmed(options.refreshTokenPath ?? REFRESH_TOKEN_PATH);
3121
+ if (!refreshToken4 || metadata.metadata.accessTokenHash !== credentialFingerprint(stored) || metadata.metadata.refreshTokenHash !== credentialFingerprint(refreshToken4)) {
1500
3122
  return void 0;
1501
3123
  }
1502
3124
  }
1503
3125
  return { token: stored, source: "token_file" };
1504
3126
  }
1505
3127
  if (metadata.state === "invalid") return void 0;
1506
- const refreshToken2 = readTrimmed(options.refreshTokenPath ?? REFRESH_TOKEN_PATH);
1507
- if (!refreshToken2 || metadata.metadata.accessTokenHash !== credentialFingerprint(stored) || metadata.metadata.refreshTokenHash !== credentialFingerprint(refreshToken2)) {
3128
+ const refreshToken3 = readTrimmed(options.refreshTokenPath ?? REFRESH_TOKEN_PATH);
3129
+ if (!refreshToken3 || metadata.metadata.accessTokenHash !== credentialFingerprint(stored) || metadata.metadata.refreshTokenHash !== credentialFingerprint(refreshToken3)) {
1508
3130
  return void 0;
1509
3131
  }
1510
3132
  return { token: stored, source: "token_file" };
1511
3133
  }
1512
3134
  function credentialFingerprint(value) {
1513
- return createHash4("sha256").update(value).digest("hex");
3135
+ return createHash6("sha256").update(value).digest("hex");
1514
3136
  }
1515
3137
  function parseLegacyBrokerCredentialMetadata(value) {
1516
3138
  if (value === null || typeof value !== "object" || Array.isArray(value)) {
@@ -1530,7 +3152,7 @@ function parseLegacyBrokerCredentialMetadata(value) {
1530
3152
  function readBoundedCredentialJson(path) {
1531
3153
  let raw;
1532
3154
  try {
1533
- raw = readFileSync6(path, "utf8");
3155
+ raw = readFileSync7(path, "utf8");
1534
3156
  } catch (error) {
1535
3157
  return error.code === "ENOENT" ? void 0 : null;
1536
3158
  }
@@ -1607,14 +3229,14 @@ function jwtOrganizationId(token) {
1607
3229
 
1608
3230
  // src/binding.ts
1609
3231
  var PRIM_CONFIG_DIR = primConfigDirectory();
1610
- var SESSIONS_DIR = join8(PRIM_CONFIG_DIR, "sessions");
3232
+ var SESSIONS_DIR = join10(PRIM_CONFIG_DIR, "sessions");
1611
3233
  var WORKSPACE_FILE = ".prim/workspace.json";
1612
3234
  function readJsonSafe(path) {
1613
3235
  if (!existsSync4(path)) {
1614
3236
  return;
1615
3237
  }
1616
3238
  try {
1617
- return JSON.parse(readFileSync7(path, "utf-8"));
3239
+ return JSON.parse(readFileSync8(path, "utf-8"));
1618
3240
  } catch {
1619
3241
  return;
1620
3242
  }
@@ -1623,17 +3245,17 @@ function fromSessionMarker(sessionId) {
1623
3245
  if (!sessionId) {
1624
3246
  return;
1625
3247
  }
1626
- const marker = readJsonSafe(join8(SESSIONS_DIR, `${sessionId}.json`));
3248
+ const marker = readJsonSafe(join10(SESSIONS_DIR, `${sessionId}.json`));
1627
3249
  return marker?.orgId;
1628
3250
  }
1629
3251
  function fromWorkspaceFile(startDir) {
1630
3252
  let dir = startDir;
1631
3253
  while (true) {
1632
- const config = readJsonSafe(join8(dir, WORKSPACE_FILE));
3254
+ const config = readJsonSafe(join10(dir, WORKSPACE_FILE));
1633
3255
  if (config?.orgId) {
1634
3256
  return config.orgId;
1635
3257
  }
1636
- const parent = dirname5(dir);
3258
+ const parent = dirname6(dir);
1637
3259
  if (parent === dir) {
1638
3260
  return;
1639
3261
  }
@@ -1743,14 +3365,14 @@ function publicDecisionResponse(value) {
1743
3365
  }
1744
3366
 
1745
3367
  // src/client.ts
1746
- import { createHash as createHash5 } from "crypto";
1747
- import { chmodSync as chmodSync3, existsSync as existsSync5, mkdirSync as mkdirSync4, readFileSync as readFileSync9, rmSync as rmSync6 } from "fs";
1748
- import { dirname as dirname6 } from "path";
3368
+ import { createHash as createHash7 } from "crypto";
3369
+ import { chmodSync as chmodSync3, existsSync as existsSync5, mkdirSync as mkdirSync4, readFileSync as readFileSync10, rmSync as rmSync7 } from "fs";
3370
+ import { dirname as dirname7 } from "path";
1749
3371
 
1750
3372
  // src/daemon/client-instance-id.ts
1751
- import { randomBytes as randomBytes3 } from "crypto";
1752
- import { chmodSync as chmodSync2, lstatSync as lstatSync4, readFileSync as readFileSync8 } from "fs";
1753
- import { join as join9 } from "path";
3373
+ import { randomBytes as randomBytes4 } from "crypto";
3374
+ import { chmodSync as chmodSync2, lstatSync as lstatSync5, readFileSync as readFileSync9 } from "fs";
3375
+ import { join as join11 } from "path";
1754
3376
  var CONFIG_DIRECTORY_MODE = 448;
1755
3377
  var INSTANCE_FILE_MODE = 384;
1756
3378
  var INSTANCE_ENTROPY_BYTES = 32;
@@ -1763,7 +3385,7 @@ function isClientInstanceId(value) {
1763
3385
  }
1764
3386
  function ensurePrivateConfigDirectory(configDir) {
1765
3387
  ensureDurableDirectory(configDir, CONFIG_DIRECTORY_MODE);
1766
- const metadata = lstatSync4(configDir);
3388
+ const metadata = lstatSync5(configDir);
1767
3389
  if (!metadata.isDirectory() || metadata.isSymbolicLink()) {
1768
3390
  throw new Error("prim config path must be a private directory");
1769
3391
  }
@@ -1773,7 +3395,7 @@ function ensurePrivateConfigDirectory(configDir) {
1773
3395
  function readExisting(path) {
1774
3396
  let metadata;
1775
3397
  try {
1776
- metadata = lstatSync4(path);
3398
+ metadata = lstatSync5(path);
1777
3399
  } catch (error) {
1778
3400
  if (error.code === "ENOENT") {
1779
3401
  return;
@@ -1787,7 +3409,7 @@ function readExisting(path) {
1787
3409
  if (metadata.size > MAX_STORED_BYTES) {
1788
3410
  throw new Error("stored client instance identity is invalid");
1789
3411
  }
1790
- const raw = readFileSync8(path, "utf8");
3412
+ const raw = readFileSync9(path, "utf8");
1791
3413
  const value = raw.endsWith("\n") ? raw.slice(0, -1) : raw;
1792
3414
  if (raw !== value && raw !== `${value}
1793
3415
  ` || !isClientInstanceId(value)) {
@@ -1801,8 +3423,8 @@ function atomicWrite(path, value) {
1801
3423
  }
1802
3424
  async function getOrCreateClientInstanceId(options) {
1803
3425
  const configDir = options.configDir;
1804
- const path = join9(configDir, "client_instance_id");
1805
- const lockPath = join9(configDir, "client-instance.lock");
3426
+ const path = join11(configDir, "client_instance_id");
3427
+ const lockPath = join11(configDir, "client-instance.lock");
1806
3428
  ensurePrivateConfigDirectory(configDir);
1807
3429
  return withFileLock(
1808
3430
  lockPath,
@@ -1811,7 +3433,7 @@ async function getOrCreateClientInstanceId(options) {
1811
3433
  if (existing !== void 0) {
1812
3434
  return existing;
1813
3435
  }
1814
- const generated = `${INSTANCE_PREFIX}${randomBytes3(INSTANCE_ENTROPY_BYTES).toString(
3436
+ const generated = `${INSTANCE_PREFIX}${randomBytes4(INSTANCE_ENTROPY_BYTES).toString(
1815
3437
  "base64url"
1816
3438
  )}`;
1817
3439
  if (!isClientInstanceId(generated)) {
@@ -1846,60 +3468,18 @@ async function ingestUploaderHeaders() {
1846
3468
  return headers;
1847
3469
  }
1848
3470
 
1849
- // src/lib/terminal-safe.ts
1850
- function replaceIsolatedSurrogates(value) {
1851
- let out = "";
1852
- for (let index = 0; index < value.length; index += 1) {
1853
- const unit = value.charCodeAt(index);
1854
- if (unit >= 55296 && unit <= 56319) {
1855
- const next = value.charCodeAt(index + 1);
1856
- if (next >= 56320 && next <= 57343) {
1857
- out += value[index] + value[index + 1];
1858
- index += 1;
1859
- } else {
1860
- out += "\uFFFD";
1861
- }
1862
- } else if (unit >= 56320 && unit <= 57343) {
1863
- out += "\uFFFD";
1864
- } else {
1865
- out += value[index];
1866
- }
1867
- }
1868
- return out;
1869
- }
1870
- function isUnsafeTerminalCodePoint(point) {
1871
- const c0OrC1 = point <= 31 || point >= 127 && point <= 159;
1872
- const bidiOrZeroWidth = point === 173 || // soft hyphen
1873
- point === 1564 || // Arabic letter mark
1874
- point === 6158 || // Mongolian vowel separator
1875
- point >= 8203 && point <= 8207 || // zero-width + directional marks
1876
- point >= 8234 && point <= 8238 || // bidi embeddings/overrides
1877
- point >= 8288 && point <= 8303 || // word joiner + bidi isolates/controls
1878
- point >= 65529 && point <= 65531 || // interlinear annotation controls
1879
- point === 65279 || // zero-width no-break space / BOM
1880
- point >= 917504 && point <= 917631;
1881
- return c0OrC1 || bidiOrZeroWidth;
1882
- }
1883
- function terminalSafeText(value) {
1884
- return Array.from(replaceIsolatedSurrogates(value)).filter((character) => !isUnsafeTerminalCodePoint(character.codePointAt(0) ?? 0)).join("");
1885
- }
1886
- function terminalSafeLine(value) {
1887
- return terminalSafeText(value.replace(/\s+/gu, " ")).replace(/\s+/gu, " ").trim();
1888
- }
1889
- function isTerminalSafeText(value) {
1890
- return terminalSafeText(value) === value;
1891
- }
1892
- var stripControlChars = terminalSafeText;
1893
-
1894
3471
  // src/client.ts
1895
3472
  var CONFIG_DIR_MODE = 448;
1896
3473
  var CREDENTIAL_FILE_MODE = 384;
1897
3474
  var REFRESH_THRESHOLD_MS = 6e4;
1898
- var DEFAULT_API_URL2 = "https://api.getprimitive.ai";
3475
+ var DEFAULT_API_URL3 = "https://api.getprimitive.ai";
1899
3476
  var AUTH_EXPIRED_MESSAGE = "Authentication expired. Run `prim auth login` to re-authenticate.";
3477
+ function authExpiredMessage() {
3478
+ return isClaudeCloudSession() ? `Primitive credentials are missing or rejected in this Claude Code cloud session: ${CLOUD_CREDENTIALS_REMEDY}.` : AUTH_EXPIRED_MESSAGE;
3479
+ }
1900
3480
  function readTrimmed2(path) {
1901
3481
  try {
1902
- const value = readFileSync9(path, "utf8").trim();
3482
+ const value = readFileSync10(path, "utf8").trim();
1903
3483
  return value || void 0;
1904
3484
  } catch {
1905
3485
  return void 0;
@@ -1909,13 +3489,13 @@ function getSiteUrl() {
1909
3489
  return getSiteUrlForEnvironment(process.env.PRIM_API_URL);
1910
3490
  }
1911
3491
  function getSiteUrlForEnvironment(primApiUrl) {
1912
- return primApiUrl?.trim() || DEFAULT_API_URL2;
3492
+ return primApiUrl?.trim() || DEFAULT_API_URL3;
1913
3493
  }
1914
3494
  function expiresAtFor(token, expiresIn) {
1915
3495
  return expiresIn === void 0 ? jwtExpiresAt(token) : Date.now() + expiresIn * 1e3;
1916
3496
  }
1917
3497
  function ensureConfigDirectory() {
1918
- const directory = dirname6(TOKEN_FILE_PATH);
3498
+ const directory = dirname7(TOKEN_FILE_PATH);
1919
3499
  mkdirSync4(directory, { recursive: true, mode: CONFIG_DIR_MODE });
1920
3500
  chmodSync3(directory, CONFIG_DIR_MODE);
1921
3501
  }
@@ -1925,7 +3505,7 @@ function atomicWrite2(path, content2) {
1925
3505
  }
1926
3506
  function removeCredentialFile(path) {
1927
3507
  if (!existsSync5(path)) return false;
1928
- rmSync6(path, { force: true });
3508
+ rmSync7(path, { force: true });
1929
3509
  return true;
1930
3510
  }
1931
3511
  function getTokenExpiresAt() {
@@ -1940,23 +3520,23 @@ function isTokenExpiringSoon(credential) {
1940
3520
  const expiresAt = getTokenExpiresAt();
1941
3521
  return expiresAt !== void 0 && Date.now() >= expiresAt - REFRESH_THRESHOLD_MS;
1942
3522
  }
1943
- function refreshFingerprint(refreshToken2) {
1944
- return createHash5("sha256").update(refreshToken2).digest("hex");
3523
+ function refreshFingerprint(refreshToken3) {
3524
+ return createHash7("sha256").update(refreshToken3).digest("hex");
1945
3525
  }
1946
- function legacyBrokerCredentialMetadata(accessToken, refreshToken2) {
3526
+ function legacyBrokerCredentialMetadata(accessToken, refreshToken3) {
1947
3527
  return {
1948
3528
  version: 1,
1949
3529
  family: "legacy_broker",
1950
3530
  accessTokenHash: refreshFingerprint(accessToken),
1951
- refreshTokenHash: refreshFingerprint(refreshToken2)
3531
+ refreshTokenHash: refreshFingerprint(refreshToken3)
1952
3532
  };
1953
3533
  }
1954
- function credentialFamilyMetadata(accessToken, refreshToken2, metadata) {
3534
+ function credentialFamilyMetadata(accessToken, refreshToken3, metadata) {
1955
3535
  const hashes = {
1956
3536
  accessTokenHash: refreshFingerprint(accessToken),
1957
- refreshTokenHash: refreshFingerprint(refreshToken2)
3537
+ refreshTokenHash: refreshFingerprint(refreshToken3)
1958
3538
  };
1959
- return metadata === void 0 ? legacyBrokerCredentialMetadata(accessToken, refreshToken2) : { ...metadata, ...hashes };
3539
+ return metadata === void 0 ? legacyBrokerCredentialMetadata(accessToken, refreshToken3) : { ...metadata, ...hashes };
1960
3540
  }
1961
3541
  function writeCredentialMigrationSentinel() {
1962
3542
  atomicWrite2(
@@ -1968,11 +3548,11 @@ function writeCredentialMigrationSentinel() {
1968
3548
  `
1969
3549
  );
1970
3550
  }
1971
- function bindLegacyBrokerGeneration(accessToken, refreshToken2, metadata) {
1972
- if (metadata.state !== "legacy_broker" || !accessToken || !refreshToken2) {
3551
+ function bindLegacyBrokerGeneration(accessToken, refreshToken3, metadata) {
3552
+ if (metadata.state !== "legacy_broker" || !accessToken || !refreshToken3) {
1973
3553
  return { state: "invalid" };
1974
3554
  }
1975
- const familyMetadata = legacyBrokerCredentialMetadata(accessToken, refreshToken2);
3555
+ const familyMetadata = legacyBrokerCredentialMetadata(accessToken, refreshToken3);
1976
3556
  if (metadata.metadata !== void 0 && (metadata.metadata.accessTokenHash !== familyMetadata.accessTokenHash || metadata.metadata.refreshTokenHash !== familyMetadata.refreshTokenHash)) {
1977
3557
  return { state: "invalid" };
1978
3558
  }
@@ -1989,17 +3569,17 @@ function preserveMarkerlessLegacyGeneration() {
1989
3569
  const metadata = readStoredCredentialMetadata();
1990
3570
  if (metadata.state !== "legacy_broker" || metadata.metadata !== void 0) return;
1991
3571
  const accessToken = readTrimmed2(TOKEN_FILE_PATH);
1992
- const refreshToken2 = readTrimmed2(REFRESH_TOKEN_PATH);
1993
- if (!(accessToken && refreshToken2)) return;
1994
- const familyMetadata = legacyBrokerCredentialMetadata(accessToken, refreshToken2);
3572
+ const refreshToken3 = readTrimmed2(REFRESH_TOKEN_PATH);
3573
+ if (!(accessToken && refreshToken3)) return;
3574
+ const familyMetadata = legacyBrokerCredentialMetadata(accessToken, refreshToken3);
1995
3575
  atomicWrite2(CREDENTIAL_FAMILY_PATH, `${JSON.stringify(familyMetadata)}
1996
3576
  `);
1997
3577
  }
1998
3578
  function terminalFingerprint() {
1999
3579
  return readTrimmed2(TERMINAL_REFRESH_PATH);
2000
3580
  }
2001
- function writeTerminalFingerprint(refreshToken2) {
2002
- atomicWrite2(TERMINAL_REFRESH_PATH, `${refreshFingerprint(refreshToken2)}
3581
+ function writeTerminalFingerprint(refreshToken3) {
3582
+ atomicWrite2(TERMINAL_REFRESH_PATH, `${refreshFingerprint(refreshToken3)}
2003
3583
  `);
2004
3584
  }
2005
3585
  function clearTerminalFingerprint() {
@@ -2008,20 +3588,20 @@ function clearTerminalFingerprint() {
2008
3588
  function isSessionEnded() {
2009
3589
  if (hasMachineConfiguration()) return machineSessionEnded();
2010
3590
  if (resolveAuthCredential()?.source !== "token_file") return false;
2011
- const refreshToken2 = readTrimmed2(REFRESH_TOKEN_PATH);
3591
+ const refreshToken3 = readTrimmed2(REFRESH_TOKEN_PATH);
2012
3592
  const ended = terminalFingerprint();
2013
- return Boolean(refreshToken2 && ended && refreshFingerprint(refreshToken2) === ended);
3593
+ return Boolean(refreshToken3 && ended && refreshFingerprint(refreshToken3) === ended);
2014
3594
  }
2015
3595
  function withCredentialLock(operation, options = {}) {
2016
3596
  return withFileLock(CREDENTIAL_LOCK_PATH, operation, options);
2017
3597
  }
2018
3598
  function commitCredentialsUnlocked(credentials) {
2019
3599
  const accessToken = credentials.accessToken.trim();
2020
- const refreshToken2 = credentials.refreshToken.trim();
2021
- if (!accessToken || !refreshToken2) {
3600
+ const refreshToken3 = credentials.refreshToken.trim();
3601
+ if (!accessToken || !refreshToken3) {
2022
3602
  throw new Error("OAuth credentials require both access and refresh tokens");
2023
3603
  }
2024
- const familyMetadata = credentialFamilyMetadata(accessToken, refreshToken2, credentials.metadata);
3604
+ const familyMetadata = credentialFamilyMetadata(accessToken, refreshToken3, credentials.metadata);
2025
3605
  if (credentials.metadata !== void 0) {
2026
3606
  preserveMarkerlessLegacyGeneration();
2027
3607
  writeCredentialMigrationSentinel();
@@ -2029,10 +3609,10 @@ function commitCredentialsUnlocked(credentials) {
2029
3609
  `);
2030
3610
  atomicWrite2(CREDENTIAL_METADATA_PATH, `${JSON.stringify(familyMetadata)}
2031
3611
  `);
2032
- atomicWrite2(REFRESH_TOKEN_PATH, `${refreshToken2}
3612
+ atomicWrite2(REFRESH_TOKEN_PATH, `${refreshToken3}
2033
3613
  `);
2034
3614
  } else {
2035
- atomicWrite2(REFRESH_TOKEN_PATH, `${refreshToken2}
3615
+ atomicWrite2(REFRESH_TOKEN_PATH, `${refreshToken3}
2036
3616
  `);
2037
3617
  atomicWrite2(CREDENTIAL_FAMILY_PATH, `${JSON.stringify(familyMetadata)}
2038
3618
  `);
@@ -2069,15 +3649,15 @@ function refreshDiagnostic(response, detail, quiet, provider) {
2069
3649
  `
2070
3650
  );
2071
3651
  }
2072
- function metadataMatchesCredentialGeneration(expected, accessToken, refreshToken2) {
3652
+ function metadataMatchesCredentialGeneration(expected, accessToken, refreshToken3) {
2073
3653
  const current = readStoredCredentialMetadata();
2074
3654
  if (expected.state === "legacy_broker") {
2075
3655
  if (current.state !== "legacy_broker") return false;
2076
3656
  if (!expected.metadata) return current.metadata === void 0;
2077
- return current.metadata !== void 0 && current.metadata.accessTokenHash === refreshFingerprint(accessToken) && current.metadata.accessTokenHash === expected.metadata.accessTokenHash && current.metadata.refreshTokenHash === refreshFingerprint(refreshToken2) && current.metadata.refreshTokenHash === expected.metadata.refreshTokenHash;
3657
+ return current.metadata !== void 0 && current.metadata.accessTokenHash === refreshFingerprint(accessToken) && current.metadata.accessTokenHash === expected.metadata.accessTokenHash && current.metadata.refreshTokenHash === refreshFingerprint(refreshToken3) && current.metadata.refreshTokenHash === expected.metadata.refreshTokenHash;
2078
3658
  }
2079
3659
  if (expected.state !== "workos_connect" || current.state !== "workos_connect") return false;
2080
- return current.metadata.issuer === expected.metadata.issuer && current.metadata.clientId === expected.metadata.clientId && current.metadata.accessTokenHash === refreshFingerprint(accessToken) && current.metadata.accessTokenHash === expected.metadata.accessTokenHash && current.metadata.refreshTokenHash === refreshFingerprint(refreshToken2) && current.metadata.refreshTokenHash === expected.metadata.refreshTokenHash;
3660
+ return current.metadata.issuer === expected.metadata.issuer && current.metadata.clientId === expected.metadata.clientId && current.metadata.accessTokenHash === refreshFingerprint(accessToken) && current.metadata.accessTokenHash === expected.metadata.accessTokenHash && current.metadata.refreshTokenHash === refreshFingerprint(refreshToken3) && current.metadata.refreshTokenHash === expected.metadata.refreshTokenHash;
2081
3661
  }
2082
3662
  function uncoordinatedLegacyWinnerAccessToken(expected, currentGeneration) {
2083
3663
  if (!expected || readCredentialMigrationState() !== "valid") return void 0;
@@ -2246,7 +3826,7 @@ async function performTokenRefresh(options = {}) {
2246
3826
  );
2247
3827
  }
2248
3828
  var _refreshInFlight;
2249
- function refreshToken(options = {}) {
3829
+ function refreshToken2(options = {}) {
2250
3830
  if (hasMachineConfiguration())
2251
3831
  return acquireMachineCredential(options).then((credential) => credential?.accessToken);
2252
3832
  if (_refreshInFlight) return _refreshInFlight;
@@ -2278,7 +3858,7 @@ var CliManagementResponseError = class extends Error {
2278
3858
  var CLI_MANAGEMENT_RESPONSE_MAX_BYTES = 2 * 1024 * 1024;
2279
3859
  async function managementResponseValue(response) {
2280
3860
  if (response.status === 401) {
2281
- throw new HttpError(401, AUTH_EXPIRED_MESSAGE);
3861
+ throw new HttpError(401, authExpiredMessage());
2282
3862
  }
2283
3863
  let value;
2284
3864
  try {
@@ -2300,23 +3880,50 @@ function selectedCredential() {
2300
3880
  }
2301
3881
  return _cachedCredential;
2302
3882
  }
3883
+ async function requestHeaders(method, path) {
3884
+ return {
3885
+ "Content-Type": "application/json",
3886
+ ...method === "POST" && path === "/api/cli/moves/ingest" ? await ingestUploaderHeaders() : {}
3887
+ };
3888
+ }
2303
3889
  async function fetchWithToken(method, path, body, options, token, siteUrl) {
2304
3890
  return fetch(`${siteUrl}${path}`, {
2305
3891
  method,
2306
- headers: {
2307
- Authorization: `Bearer ${token}`,
2308
- "Content-Type": "application/json",
2309
- ...method === "POST" && path === "/api/cli/moves/ingest" ? await ingestUploaderHeaders() : {}
2310
- },
3892
+ headers: { Authorization: `Bearer ${token}`, ...await requestHeaders(method, path) },
2311
3893
  body: body === void 0 ? void 0 : JSON.stringify(body),
2312
3894
  signal: options?.signal,
2313
3895
  redirect: options?.redirect
2314
3896
  });
2315
3897
  }
3898
+ async function fetchAsMachine(credential, method, path, body, options) {
3899
+ if (!credential.tokenInjection)
3900
+ return fetchWithToken(
3901
+ method,
3902
+ path,
3903
+ body,
3904
+ { ...options, redirect: "error" },
3905
+ credential.accessToken,
3906
+ credential.apiUrl
3907
+ );
3908
+ try {
3909
+ return await forwardMachineRequest(
3910
+ {
3911
+ method,
3912
+ path,
3913
+ headers: await requestHeaders(method, path),
3914
+ ...body === void 0 ? {} : { body: JSON.stringify(body) }
3915
+ },
3916
+ options.signal
3917
+ );
3918
+ } catch (error) {
3919
+ if (!(error instanceof MachineAuthError)) throw error;
3920
+ throw new HttpError(error.terminal ? 401 : 503, error.message, { error: error.code });
3921
+ }
3922
+ }
2316
3923
  async function responseValue(response) {
2317
3924
  if (!response.ok) {
2318
3925
  if (response.status === 401) {
2319
- throw new HttpError(401, AUTH_EXPIRED_MESSAGE);
3926
+ throw new HttpError(401, authExpiredMessage());
2320
3927
  }
2321
3928
  const errorBody = await response.json().catch(() => null);
2322
3929
  const errorRecord = typeof errorBody === "object" && errorBody !== null && !Array.isArray(errorBody) ? errorBody : void 0;
@@ -2343,14 +3950,7 @@ async function machineClient(options = {}, management = false) {
2343
3950
  const current = await acquireMachineCredential({ signal: requestOptions.signal });
2344
3951
  if (!current || current.generation !== selected.generation || current.machineId !== selected.machineId || current.authorizedUserId !== selected.authorizedUserId || current.organizationId !== selected.organizationId)
2345
3952
  throw new HttpError(409, "Machine identity changed; restart the operation.");
2346
- let response = await fetchWithToken(
2347
- method,
2348
- path,
2349
- body,
2350
- { ...requestOptions, redirect: "error" },
2351
- current.accessToken,
2352
- selected.apiUrl
2353
- );
3953
+ let response = await fetchAsMachine(current, method, path, body, requestOptions);
2354
3954
  if (response.status === 401) {
2355
3955
  const renewed = await acquireMachineCredential({
2356
3956
  force: true,
@@ -2359,19 +3959,14 @@ async function machineClient(options = {}, management = false) {
2359
3959
  if (!renewed || renewed.generation !== selected.generation || renewed.machineId !== selected.machineId || renewed.authorizedUserId !== selected.authorizedUserId || renewed.organizationId !== selected.organizationId) {
2360
3960
  throw new HttpError(409, "Machine identity changed; restart the operation.");
2361
3961
  }
2362
- response = await fetchWithToken(
2363
- method,
2364
- path,
2365
- body,
2366
- { ...requestOptions, redirect: "error" },
2367
- renewed.accessToken,
2368
- renewed.apiUrl
2369
- );
3962
+ response = await fetchAsMachine(renewed, method, path, body, requestOptions);
2370
3963
  }
2371
3964
  if (response.status === 401)
2372
3965
  throw new HttpError(
2373
3966
  401,
2374
- "Machine access was rejected. Ask your administrator to check or rotate its credentials."
3967
+ selected.session ? "Primitive rejected this cloud session's token after renewing it. To fix it, start a new cloud session, which identifies you again through GitHub." : selected.tokenInjection ? "Machine access was rejected. Check the cloud environment's OAuth 2.0 client credentials network secret, or mint a replacement credential if this one was revoked." : rejectedCredentialsMessage(
3968
+ "Machine access was rejected. Ask your administrator to check or rotate its credentials."
3969
+ )
2375
3970
  );
2376
3971
  return parse2(response);
2377
3972
  };
@@ -2381,7 +3976,7 @@ async function machineClient(options = {}, management = false) {
2381
3976
  delete: (path, body, opts) => send("DELETE", path, body, opts)
2382
3977
  };
2383
3978
  }
2384
- async function request(method, path, body, options) {
3979
+ async function request2(method, path, body, options) {
2385
3980
  const machine = await machineClient(options);
2386
3981
  if (machine)
2387
3982
  return method === "GET" ? machine.get(path, options) : machine.post(path, body, options);
@@ -2390,17 +3985,17 @@ async function request(method, path, body, options) {
2390
3985
  let refreshAttempted = false;
2391
3986
  if (credential && isTokenExpiringSoon(credential)) {
2392
3987
  refreshAttempted = true;
2393
- const token = await refreshToken({
3988
+ const token = await refreshToken2({
2394
3989
  signal: options?.signal,
2395
3990
  quiet: options?.quietRefresh
2396
3991
  });
2397
3992
  if (token) credential = { token, source: "token_file" };
2398
3993
  }
2399
3994
  if (!credential) {
2400
- throw new HttpError(401, AUTH_EXPIRED_MESSAGE);
3995
+ throw new HttpError(401, authExpiredMessage());
2401
3996
  }
2402
3997
  if (isTokenExpiringSoon(credential) && isSessionEnded()) {
2403
- throw new HttpError(401, AUTH_EXPIRED_MESSAGE);
3998
+ throw new HttpError(401, authExpiredMessage());
2404
3999
  }
2405
4000
  const tokenUsed = credential.token;
2406
4001
  let response = await fetchWithToken(method, path, body, options, tokenUsed, siteUrl);
@@ -2409,7 +4004,7 @@ async function request(method, path, body, options) {
2409
4004
  let retryToken = latest?.token !== tokenUsed ? latest?.token : void 0;
2410
4005
  if (!retryToken && latest?.source === "token_file" && !refreshAttempted) {
2411
4006
  refreshAttempted = true;
2412
- retryToken = await refreshToken({ signal: options?.signal, quiet: options?.quietRefresh });
4007
+ retryToken = await refreshToken2({ signal: options?.signal, quiet: options?.quietRefresh });
2413
4008
  }
2414
4009
  if (retryToken) {
2415
4010
  _cachedCredential = {
@@ -2423,8 +4018,8 @@ async function request(method, path, body, options) {
2423
4018
  }
2424
4019
  function getClient() {
2425
4020
  return {
2426
- get: (path, options) => request("GET", path, void 0, options),
2427
- post: (path, body, options) => request("POST", path, body, options)
4021
+ get: (path, options) => request2("GET", path, void 0, options),
4022
+ post: (path, body, options) => request2("POST", path, body, options)
2428
4023
  };
2429
4024
  }
2430
4025
 
@@ -2614,29 +4209,29 @@ import { existsSync as existsSync10 } from "fs";
2614
4209
 
2615
4210
  // src/demo/diagnostics.ts
2616
4211
  import { existsSync as existsSync9 } from "fs";
2617
- import { join as join14 } from "path";
4212
+ import { join as join16 } from "path";
2618
4213
 
2619
4214
  // src/lib/hook-runtime.ts
2620
- import { createHash as createHash6, randomBytes as randomBytes4 } from "crypto";
4215
+ import { createHash as createHash8, randomBytes as randomBytes5 } from "crypto";
2621
4216
  import {
2622
4217
  constants as constants2,
2623
4218
  accessSync,
2624
4219
  chmodSync as chmodSync4,
2625
4220
  copyFileSync,
2626
4221
  existsSync as existsSync7,
2627
- lstatSync as lstatSync5,
4222
+ lstatSync as lstatSync6,
2628
4223
  mkdirSync as mkdirSync5,
2629
4224
  mkdtempSync,
2630
- readFileSync as readFileSync10,
2631
- readdirSync,
2632
- realpathSync,
4225
+ readFileSync as readFileSync11,
4226
+ readdirSync as readdirSync2,
4227
+ realpathSync as realpathSync2,
2633
4228
  renameSync as renameSync2,
2634
- rmSync as rmSync7,
4229
+ rmSync as rmSync8,
2635
4230
  statSync as statSync2,
2636
4231
  utimesSync,
2637
- writeFileSync as writeFileSync3
4232
+ writeFileSync as writeFileSync4
2638
4233
  } from "fs";
2639
- import { delimiter, dirname as dirname8, isAbsolute as isAbsolute3, join as join12, resolve as resolve2 } from "path";
4234
+ import { delimiter, dirname as dirname9, isAbsolute as isAbsolute4, join as join14, resolve as resolve3 } from "path";
2640
4235
 
2641
4236
  // src/lib/git-hook-contract.ts
2642
4237
  var GIT_HOOK_ENTRYPOINT_CONTENT = `#!/bin/sh
@@ -2686,7 +4281,7 @@ exit 0
2686
4281
  // src/lib/native-keyring.ts
2687
4282
  import { existsSync as existsSync6 } from "fs";
2688
4283
  import { createRequire as createRequire2 } from "module";
2689
- import { dirname as dirname7, join as join11 } from "path";
4284
+ import { dirname as dirname8, join as join13 } from "path";
2690
4285
  import { fileURLToPath as fileURLToPath4 } from "url";
2691
4286
  var require3 = createRequire2(import.meta.url);
2692
4287
 
@@ -2737,9 +4332,9 @@ exec "$prim_node" "$prim_entry" "$@"
2737
4332
  `;
2738
4333
 
2739
4334
  // src/demo/state.ts
2740
- import { createHash as createHash7, randomUUID as randomUUID3 } from "crypto";
2741
- import { existsSync as existsSync8, lstatSync as lstatSync6, readFileSync as readFileSync11, readdirSync as readdirSync2 } from "fs";
2742
- import { join as join13, resolve as resolve3 } from "path";
4335
+ import { createHash as createHash9, randomUUID as randomUUID3 } from "crypto";
4336
+ import { existsSync as existsSync8, lstatSync as lstatSync7, readFileSync as readFileSync12, readdirSync as readdirSync3 } from "fs";
4337
+ import { join as join15, resolve as resolve4 } from "path";
2743
4338
 
2744
4339
  // src/generated/cli-http-v1.validators.js
2745
4340
  var import_ucs2length = __toESM(require_ucs2length(), 1);
@@ -29425,15 +31020,15 @@ validate84.evaluated = { "props": true, "dynamicProps": false, "dynamicItems": f
29425
31020
 
29426
31021
  // src/demo/state.ts
29427
31022
  var RUN_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/u;
29428
- var demoDirectory = () => join13(primConfigDirectory(), "demo");
31023
+ var demoDirectory = () => join15(primConfigDirectory(), "demo");
29429
31024
  var runPath = (id2) => {
29430
31025
  if (!RUN_ID.test(id2)) throw new Error("invalid demo run ID");
29431
- return join13(demoDirectory(), "runs", `${id2}.json`);
31026
+ return join15(demoDirectory(), "runs", `${id2}.json`);
29432
31027
  };
29433
31028
  function readDemoJson(path) {
29434
- const stat = lstatSync6(path);
31029
+ const stat = lstatSync7(path);
29435
31030
  if (!stat.isFile() || stat.size > 16384) throw new Error(`invalid demo state: ${path}`);
29436
- return JSON.parse(readFileSync11(path, "utf8"));
31031
+ return JSON.parse(readFileSync12(path, "utf8"));
29437
31032
  }
29438
31033
  function saveDemoJson(path, value) {
29439
31034
  atomicWriteFile(path, `${JSON.stringify(value)}
@@ -29470,11 +31065,11 @@ function demoCommand(run, action, choice, reason) {
29470
31065
  ].map(quote).join(" ");
29471
31066
  }
29472
31067
  function sessionKey(agent, session) {
29473
- return createHash7("sha256").update(`${agent}\0${session}`).digest("hex");
31068
+ return createHash9("sha256").update(`${agent}\0${session}`).digest("hex");
29474
31069
  }
29475
31070
  function exclusionPath(key) {
29476
31071
  if (!/^[0-9a-f]{64}$/u.test(key)) throw new Error("invalid demo session identity");
29477
- return join13(demoDirectory(), "excluded-sessions", `${key}.json`);
31072
+ return join15(demoDirectory(), "excluded-sessions", `${key}.json`);
29478
31073
  }
29479
31074
  function sessionExcluded(agent, session) {
29480
31075
  if (typeof session !== "string" || !session) return false;
@@ -29513,7 +31108,7 @@ function demoArgv(command) {
29513
31108
  }
29514
31109
 
29515
31110
  // src/demo/diagnostics.ts
29516
- var observationPath = (id2) => join14(demoDirectory(), "observations", `${id2}.json`);
31111
+ var observationPath = (id2) => join16(demoDirectory(), "observations", `${id2}.json`);
29517
31112
  function observeRun(id2, observation) {
29518
31113
  try {
29519
31114
  saveDemoJson(observationPath(id2), observation);
@@ -29607,25 +31202,25 @@ import {
29607
31202
  mkdirSync as mkdirSync6,
29608
31203
  openSync as openSync2,
29609
31204
  opendirSync,
29610
- readFileSync as readFileSync13,
31205
+ readFileSync as readFileSync14,
29611
31206
  readSync,
29612
- readdirSync as readdirSync4
31207
+ readdirSync as readdirSync5
29613
31208
  } from "fs";
29614
- import { dirname as dirname10, join as join16 } from "path";
31209
+ import { dirname as dirname11, join as join18 } from "path";
29615
31210
 
29616
31211
  // src/drain-progress.ts
29617
31212
  import {
29618
31213
  chmodSync as chmodSync5,
29619
31214
  existsSync as existsSync11,
29620
- readFileSync as readFileSync12,
29621
- readdirSync as readdirSync3,
29622
- rmSync as rmSync8,
31215
+ readFileSync as readFileSync13,
31216
+ readdirSync as readdirSync4,
31217
+ rmSync as rmSync9,
29623
31218
  rmdirSync
29624
31219
  } from "fs";
29625
- import { basename as basename2, dirname as dirname9, join as join15 } from "path";
31220
+ import { basename as basename3, dirname as dirname10, join as join17 } from "path";
29626
31221
 
29627
31222
  // src/journal.ts
29628
- var JOURNAL_DIR = join16(primConfigDirectory(), "moves");
31223
+ var JOURNAL_DIR = join18(primConfigDirectory(), "moves");
29629
31224
  var UNBOUND_BUCKET = "_unbound";
29630
31225
  var JOURNAL_BASENAME = "journal.ndjson";
29631
31226
  var JOURNAL_STATS_SAMPLE_BYTES = 64 * 1024;
@@ -29637,14 +31232,14 @@ function envSlug(apiUrl) {
29637
31232
  return slug;
29638
31233
  }
29639
31234
  function currentEnvDir() {
29640
- return join16(JOURNAL_DIR, envSlug(getSiteUrl()));
31235
+ return join18(JOURNAL_DIR, envSlug(getSiteUrl()));
29641
31236
  }
29642
31237
  var DIR_MODE = 448;
29643
31238
  var FILE_MODE2 = 384;
29644
31239
  var SAFE_BUCKET = /^[A-Za-z0-9_-]+$/;
29645
31240
  var RESERVED_BUCKETS = /* @__PURE__ */ new Set([UNBOUND_BUCKET, "_legacy"]);
29646
31241
  function appendMoveToPath(path, move) {
29647
- const dir = dirname10(path);
31242
+ const dir = dirname11(path);
29648
31243
  if (!existsSync12(dir)) {
29649
31244
  mkdirSync6(dir, { recursive: true, mode: DIR_MODE });
29650
31245
  }
@@ -29653,37 +31248,54 @@ function appendMoveToPath(path, move) {
29653
31248
  }
29654
31249
  function bucketDir(orgId) {
29655
31250
  const safe = orgId !== void 0 && SAFE_BUCKET.test(orgId) && !RESERVED_BUCKETS.has(orgId);
29656
- return join16(currentEnvDir(), safe ? orgId : UNBOUND_BUCKET);
31251
+ return join18(currentEnvDir(), safe ? orgId : UNBOUND_BUCKET);
29657
31252
  }
29658
31253
  function journalPath(orgId) {
29659
- return join16(bucketDir(orgId), JOURNAL_BASENAME);
31254
+ return join18(bucketDir(orgId), JOURNAL_BASENAME);
29660
31255
  }
29661
31256
  function appendMove(move, orgId) {
29662
31257
  const actor = machineCaptureActor();
29663
31258
  const captured = actor ? { ...move, captureActor: actor } : move;
29664
- appendMoveToPath(journalPath(actor ? machineJournalBucket(actor) : orgId), captured);
31259
+ const bucket = actor ? identityPending(actor) ? machinePendingBucket(actor) : machineJournalBucket(actor) : orgId;
31260
+ appendMoveToPath(journalPath(bucket), captured);
29665
31261
  return captured;
29666
31262
  }
29667
31263
  var FLUSHING_PREFIX = `${JOURNAL_BASENAME}.flushing.`;
29668
31264
 
29669
31265
  // src/lib/activation.ts
29670
31266
  import { execFileSync as execFileSync4 } from "child_process";
29671
- import { existsSync as existsSync13, readFileSync as readFileSync14 } from "fs";
31267
+ import { existsSync as existsSync14, readFileSync as readFileSync16 } from "fs";
29672
31268
  import { homedir as homedir2 } from "os";
29673
- import { join as join17 } from "path";
31269
+ import { join as join20 } from "path";
31270
+
31271
+ // src/lib/cloud-prepared.ts
31272
+ import { existsSync as existsSync13, mkdirSync as mkdirSync7, readFileSync as readFileSync15, rmSync as rmSync10, writeFileSync as writeFileSync5 } from "fs";
31273
+ import { join as join19 } from "path";
31274
+ var CLOUD_PREPARED_MARKER = "cloud-prepared";
31275
+ function cloudPreparedPath(env = process.env) {
31276
+ return join19(primConfigDirectory({ env }), CLOUD_PREPARED_MARKER);
31277
+ }
31278
+ function isPreparedCloudSession(env = process.env) {
31279
+ if (!isClaudeCloudSession(env)) return false;
31280
+ try {
31281
+ return existsSync13(cloudPreparedPath(env));
31282
+ } catch {
31283
+ return false;
31284
+ }
31285
+ }
29674
31286
 
29675
31287
  // src/lib/demo-pause.ts
29676
- import { execFileSync as execFileSync2 } from "child_process";
31288
+ import { execFileSync as execFileSync3 } from "child_process";
29677
31289
  var DEMO_PAUSE_MS = 30 * 6e4;
29678
31290
  var PAUSE_KEY = "prim.demoPause";
29679
- var GIT_TIMEOUT_MS = 1e3;
29680
- function git(cwd, args) {
31291
+ var GIT_TIMEOUT_MS3 = 1e3;
31292
+ function git2(cwd, args) {
29681
31293
  try {
29682
- return execFileSync2("git", args, {
31294
+ return execFileSync3("git", args, {
29683
31295
  cwd,
29684
31296
  encoding: "utf-8",
29685
31297
  stdio: ["ignore", "pipe", "ignore"],
29686
- timeout: GIT_TIMEOUT_MS
31298
+ timeout: GIT_TIMEOUT_MS3
29687
31299
  });
29688
31300
  } catch {
29689
31301
  return void 0;
@@ -29691,10 +31303,10 @@ function git(cwd, args) {
29691
31303
  }
29692
31304
  function setLocal(cwd, key, value) {
29693
31305
  try {
29694
- execFileSync2(
31306
+ execFileSync3(
29695
31307
  "git",
29696
31308
  value === null ? ["config", "--local", "--unset", key] : ["config", "--local", key, value],
29697
- { cwd, stdio: ["ignore", "ignore", "pipe"], timeout: GIT_TIMEOUT_MS }
31309
+ { cwd, stdio: ["ignore", "ignore", "pipe"], timeout: GIT_TIMEOUT_MS3 }
29698
31310
  );
29699
31311
  } catch (error) {
29700
31312
  if (value !== null || error.status !== 5) throw error;
@@ -29708,7 +31320,7 @@ function parsePause(value) {
29708
31320
  function readCaptureConfig(cwd) {
29709
31321
  let active;
29710
31322
  let pause;
29711
- const out = git(cwd, ["config", "--get-regexp", "^prim\\.(active|demopause)$"]) ?? "";
31323
+ const out = git2(cwd, ["config", "--get-regexp", "^prim\\.(active|demopause)$"]) ?? "";
29712
31324
  for (const line of out.split("\n")) {
29713
31325
  const space3 = line.indexOf(" ");
29714
31326
  const key = line.slice(0, space3).toLowerCase();
@@ -29733,225 +31345,13 @@ function healDemoPause(cwd, pause, options = {}) {
29733
31345
  }
29734
31346
  }
29735
31347
 
29736
- // src/lib/git.ts
29737
- import { execFileSync as execFileSync3 } from "child_process";
29738
- import { createHash as createHash8 } from "crypto";
29739
- import { lstatSync as lstatSync7, realpathSync as realpathSync2 } from "fs";
29740
- import { basename as basename3, dirname as dirname11, isAbsolute as isAbsolute4, relative, resolve as resolve4, sep } from "path";
29741
- var GIT_TIMEOUT_MS2 = 1e3;
29742
- var GITHUB_OWNER_PATTERN = /^(?![A-Za-z0-9-]*--)[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?$/u;
29743
- var GITHUB_REPOSITORY_PATTERN = /^[A-Za-z0-9._-]{1,100}$/u;
29744
- function gitToplevel(cwd) {
29745
- try {
29746
- return execFileSync3("git", ["rev-parse", "--show-toplevel"], {
29747
- cwd,
29748
- encoding: "utf-8",
29749
- stdio: ["ignore", "pipe", "ignore"],
29750
- timeout: GIT_TIMEOUT_MS2
29751
- }).trim();
29752
- } catch {
29753
- return null;
29754
- }
29755
- }
29756
- function gitValue(cwd, args) {
29757
- try {
29758
- const value = execFileSync3("git", args, {
29759
- cwd,
29760
- encoding: "utf-8",
29761
- stdio: ["ignore", "pipe", "ignore"],
29762
- timeout: GIT_TIMEOUT_MS2
29763
- }).trim();
29764
- return value || void 0;
29765
- } catch {
29766
- return void 0;
29767
- }
29768
- }
29769
- function currentBranch(cwd) {
29770
- return gitValue(cwd, ["symbolic-ref", "--quiet", "--short", "HEAD"]);
29771
- }
29772
- function githubRepositoryFullName(cwd) {
29773
- const remote = gitValue(cwd, ["config", "--get", "remote.origin.url"]);
29774
- if (!remote || [...remote].some((char) => char < " " || char === "\x7F")) return null;
29775
- const match = /^(?:git@github\.com:([^?#]+)|(?:https|ssh):\/\/(?:[^/@]+@)?github\.com(?::\d+)?\/([^?#]+))$/i.exec(
29776
- remote
29777
- );
29778
- const path = match?.[1] ?? match?.[2];
29779
- if (!path) return null;
29780
- const parts = path.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "").split("/");
29781
- if (parts.length !== 2 || !GITHUB_OWNER_PATTERN.test(parts[0] ?? "") || !GITHUB_REPOSITORY_PATTERN.test(parts[1] ?? "")) {
29782
- return null;
29783
- }
29784
- return `${parts[0]}/${parts[1]}`;
29785
- }
29786
- function canonicalGitRoot(cwd) {
29787
- try {
29788
- const top = gitToplevel(cwd);
29789
- return top ? realpathSync2.native(top) : null;
29790
- } catch {
29791
- return null;
29792
- }
29793
- }
29794
- function relatedWorktreeTarget(path, cwd, origin) {
29795
- let parent = dirname11(resolve4(cwd, path));
29796
- while (true) {
29797
- try {
29798
- realpathSync2.native(parent);
29799
- break;
29800
- } catch {
29801
- const next = dirname11(parent);
29802
- if (next === parent) return null;
29803
- parent = next;
29804
- }
29805
- }
29806
- const target = resolveRepositoryContext(parent);
29807
- if (!target || !target.repoKey || target.repoKey !== origin.repoKey) return null;
29808
- const common = (root) => {
29809
- const value = gitValue(root, ["rev-parse", "--git-common-dir"]);
29810
- try {
29811
- return value ? realpathSync2.native(resolve4(root, value)) : void 0;
29812
- } catch {
29813
- return void 0;
29814
- }
29815
- };
29816
- const originCommon = common(origin.repoRoot);
29817
- return originCommon && originCommon === common(target.repoRoot) ? target : null;
29818
- }
29819
- function normalizeOriginRemote(remote) {
29820
- const value = remote.trim();
29821
- if (!value) return void 0;
29822
- const scp = !value.includes("://") ? /^(?:[^@/\s]+@)?(?<host>[^:/\s]+):(?<path>.+)$/.exec(value)?.groups : void 0;
29823
- if (scp?.host && scp.path) {
29824
- const path = scp.path.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "");
29825
- return path ? `${scp.host.toLowerCase()}/${path}` : void 0;
29826
- }
29827
- try {
29828
- const url = new URL(value);
29829
- url.username = "";
29830
- url.password = "";
29831
- url.search = "";
29832
- url.hash = "";
29833
- const path = url.pathname.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "");
29834
- if (url.host && path) return `${url.host.toLowerCase()}/${path}`;
29835
- return void 0;
29836
- } catch {
29837
- return void 0;
29838
- }
29839
- }
29840
- function opaqueRepoKey(source, value) {
29841
- return `repo_v1_${createHash8("sha256").update(`${source}\0${value}`).digest("hex")}`;
29842
- }
29843
- function resolveRepositoryContext(cwd = process.cwd()) {
29844
- const top = gitToplevel(cwd);
29845
- if (!top) return null;
29846
- let repoRoot;
29847
- try {
29848
- repoRoot = realpathSync2.native(top);
29849
- } catch {
29850
- repoRoot = resolve4(top);
29851
- }
29852
- const origin = gitValue(repoRoot, ["config", "--get", "remote.origin.url"]);
29853
- const repoFullName = githubRepositoryFullName(repoRoot) ?? void 0;
29854
- const normalizedOrigin = origin ? normalizeOriginRemote(origin) : void 0;
29855
- if (normalizedOrigin) {
29856
- return {
29857
- repoRoot,
29858
- repoKey: opaqueRepoKey("origin", normalizedOrigin),
29859
- identitySource: "origin",
29860
- repoFullName
29861
- };
29862
- }
29863
- const roots = gitValue(repoRoot, ["rev-list", "--max-parents=0", "HEAD"])?.split(/\s+/).filter(Boolean).sort();
29864
- if (roots && roots.length > 0) {
29865
- return {
29866
- repoRoot,
29867
- repoKey: opaqueRepoKey("root_commit", roots.join("\n")),
29868
- identitySource: "root_commit",
29869
- repoFullName
29870
- };
29871
- }
29872
- return { repoRoot, repoFullName };
29873
- }
29874
- function nearestExistingAncestor(path) {
29875
- const suffix = [];
29876
- let cursor = path;
29877
- while (true) {
29878
- try {
29879
- lstatSync7(cursor);
29880
- break;
29881
- } catch (error) {
29882
- const code = typeof error === "object" && error !== null && "code" in error ? error.code : void 0;
29883
- if (code !== "ENOENT" && code !== "ENOTDIR") return null;
29884
- const parent = dirname11(cursor);
29885
- if (parent === cursor) return null;
29886
- suffix.unshift(cursor.slice(parent.length + (parent.endsWith(sep) ? 0 : 1)));
29887
- cursor = parent;
29888
- }
29889
- }
29890
- try {
29891
- return { real: realpathSync2.native(cursor), suffix };
29892
- } catch {
29893
- return null;
29894
- }
29895
- }
29896
- function canonicalRepositoryPathScoped(filePath, context, baseDir) {
29897
- if (!filePath || filePath !== filePath.trim() || filePath.includes("\0")) {
29898
- return { ok: false, reason: "invalid_path" };
29899
- }
29900
- const absolute = resolve4(baseDir, filePath);
29901
- const resolved = nearestExistingAncestor(absolute);
29902
- if (!resolved) return { ok: false, reason: "invalid_path" };
29903
- const target = resolve4(resolved.real, ...resolved.suffix);
29904
- const rel = relative(context.repoRoot, target);
29905
- if (!rel || rel === ".") return { ok: false, reason: "invalid_path" };
29906
- if (isAbsolute4(rel) || rel === ".." || rel.startsWith(`..${sep}`)) {
29907
- return { ok: false, reason: "outside_repository" };
29908
- }
29909
- return { ok: true, file: sep === "/" ? rel : rel.split(sep).join("/") };
29910
- }
29911
- function canonicalRepositoryPathLegacy(filePath, cwd, repositoryRoot = canonicalGitRoot(cwd)) {
29912
- if (!repositoryRoot || !filePath || [...filePath].some((char) => char < " " || char === "\x7F" || "~*?[]{}$`\\".includes(char)))
29913
- return null;
29914
- const absolute = resolve4(cwd, filePath);
29915
- let target;
29916
- try {
29917
- const stat = lstatSync7(absolute);
29918
- if (!stat.isFile() || stat.isSymbolicLink()) return null;
29919
- target = realpathSync2.native(absolute);
29920
- } catch (error) {
29921
- if (!(error instanceof Error) || error.code !== "ENOENT") {
29922
- return null;
29923
- }
29924
- try {
29925
- const parent = realpathSync2.native(dirname11(absolute));
29926
- if (!lstatSync7(parent).isDirectory()) return null;
29927
- target = resolve4(parent, basename3(absolute));
29928
- } catch {
29929
- return null;
29930
- }
29931
- }
29932
- const rel = relative(repositoryRoot, target);
29933
- if (!rel || isAbsolute4(rel) || rel === ".." || rel.startsWith(`..${sep}`)) {
29934
- return null;
29935
- }
29936
- return sep === "/" ? rel : rel.split(sep).join("/");
29937
- }
29938
- function canonicalRepositoryPath(filePath, contextOrCwd, baseDirOrRoot) {
29939
- if (typeof contextOrCwd === "string") {
29940
- return canonicalRepositoryPathLegacy(filePath, contextOrCwd, baseDirOrRoot);
29941
- }
29942
- return canonicalRepositoryPathScoped(
29943
- filePath,
29944
- contextOrCwd,
29945
- baseDirOrRoot ?? contextOrCwd.repoRoot
29946
- );
29947
- }
29948
-
29949
31348
  // src/lib/activation.ts
29950
31349
  var PRIM_ACTIVE_KEY = "prim.active";
31350
+ var PRIM_ACTIVE_DECLARATION = "PRIM_ACTIVE";
29951
31351
  var PRIM_REPO_SYNC_ID_KEY = "prim.repoSyncId";
29952
31352
  var PRIM_REPO_SYNC_REPOSITORY_KEY = "prim.repoSyncRepository";
29953
31353
  var PRIM_REPO_BINDING_STATE_KEY = "prim.repoBindingState";
29954
- var GIT_TIMEOUT_MS3 = 1e3;
31354
+ var GIT_TIMEOUT_MS4 = 1e3;
29955
31355
  var REPO_SYNC_ID_RE = /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;
29956
31356
  var PROJECT_INSTALL_FILES = [".claude/settings.json", ".codex/hooks.json", ".cursor/hooks.json"];
29957
31357
  var PRIM_HOOK_BINS = ["prim-hook", "prim-pre-tool-use", "prim-post-tool-use"];
@@ -29961,7 +31361,7 @@ function repoActiveFlag(cwd, strict = false) {
29961
31361
  cwd,
29962
31362
  encoding: "utf-8",
29963
31363
  stdio: ["ignore", "pipe", "ignore"],
29964
- timeout: GIT_TIMEOUT_MS3
31364
+ timeout: GIT_TIMEOUT_MS4
29965
31365
  }).trim();
29966
31366
  if (value === "true") return "true";
29967
31367
  if (value === "false") return "false";
@@ -29982,7 +31382,7 @@ function localGitConfigValue(cwd, key) {
29982
31382
  cwd,
29983
31383
  encoding: "utf-8",
29984
31384
  stdio: ["ignore", "pipe", "ignore"],
29985
- timeout: GIT_TIMEOUT_MS3
31385
+ timeout: GIT_TIMEOUT_MS4
29986
31386
  }).trim();
29987
31387
  return value || void 0;
29988
31388
  } catch {
@@ -30004,14 +31404,13 @@ function repositoryBindingState(cwd) {
30004
31404
  if (marker !== void 0) return "invalid";
30005
31405
  return rawId === void 0 ? "unbound" : repoSyncId(cwd) ? void 0 : "unbound";
30006
31406
  }
30007
- function hasProjectPrimInstall(cwd) {
30008
- const root = gitToplevel(cwd);
31407
+ function projectPrimInstallAt(root) {
30009
31408
  if (root === null || root === homedir2()) return false;
30010
31409
  for (const rel of PROJECT_INSTALL_FILES) {
30011
- const path = join17(root, rel);
30012
- if (existsSync13(path)) {
31410
+ const path = join20(root, rel);
31411
+ if (existsSync14(path)) {
30013
31412
  try {
30014
- const content2 = readFileSync14(path, "utf-8");
31413
+ const content2 = readFileSync16(path, "utf-8");
30015
31414
  if (PRIM_HOOK_BINS.some((bin) => content2.includes(bin))) return true;
30016
31415
  } catch {
30017
31416
  }
@@ -30019,12 +31418,27 @@ function hasProjectPrimInstall(cwd) {
30019
31418
  }
30020
31419
  return false;
30021
31420
  }
31421
+ var UNPARSED_OPT_OUT = /"PRIM_ACTIVE"\s*:\s*"\s*false\s*"/u;
31422
+ function declaresInactiveAt(root) {
31423
+ if (root === null || root === homedir2()) return false;
31424
+ if (checkoutDeclaration(root, PRIM_ACTIVE_DECLARATION)?.trim() === "false") return true;
31425
+ const text = checkoutSettingsText(root);
31426
+ if (text === null || !UNPARSED_OPT_OUT.test(text)) return false;
31427
+ try {
31428
+ JSON.parse(text);
31429
+ return false;
31430
+ } catch {
31431
+ return true;
31432
+ }
31433
+ }
30022
31434
  function isRepoActiveForCapture(cwd, options = {}) {
30023
31435
  let { active: flag, pause } = readCaptureConfig(cwd);
30024
31436
  if (pause && healDemoPause(cwd, pause, options)) flag = repoActiveFlag(cwd);
30025
31437
  if (flag === "true") return true;
30026
31438
  if (flag === "false") return false;
30027
- return hasProjectPrimInstall(cwd);
31439
+ const root = gitToplevel(cwd);
31440
+ if (declaresInactiveAt(root)) return false;
31441
+ return projectPrimInstallAt(root) || isPreparedCloudSession() && root !== null;
30028
31442
  }
30029
31443
  function decisionIngestionStatus(cwd) {
30030
31444
  return isRepoActiveForCapture(cwd) ? "enabled" : "disabled";
@@ -30319,22 +31733,22 @@ function cachedCollectScopeAdmits(cwd, facts) {
30319
31733
 
30320
31734
  // src/lib/commit-heartbeat.ts
30321
31735
  import { execFileSync as execFileSync5 } from "child_process";
30322
- import { mkdirSync as mkdirSync7, readFileSync as readFileSync15, readdirSync as readdirSync5, unlinkSync } from "fs";
30323
- import { dirname as dirname12, join as join18, resolve as resolve5 } from "path";
30324
- var GIT_TIMEOUT_MS4 = 1e3;
31736
+ import { mkdirSync as mkdirSync8, readFileSync as readFileSync17, readdirSync as readdirSync6, unlinkSync } from "fs";
31737
+ import { dirname as dirname12, join as join21, resolve as resolve5 } from "path";
31738
+ var GIT_TIMEOUT_MS5 = 1e3;
30325
31739
  function gitPath(cwd, relative3) {
30326
31740
  const value = execFileSync5("git", ["rev-parse", "--git-path", relative3], {
30327
31741
  cwd,
30328
31742
  encoding: "utf8",
30329
31743
  stdio: ["ignore", "pipe", "ignore"],
30330
- timeout: GIT_TIMEOUT_MS4
31744
+ timeout: GIT_TIMEOUT_MS5
30331
31745
  }).replace(/\r?\n$/u, "");
30332
31746
  if (value === "" || /[\0\r\n]/u.test(value)) throw new Error("Git returned an unsafe path");
30333
31747
  return resolve5(cwd, value);
30334
31748
  }
30335
31749
  function ensurePrivateParent(path) {
30336
- mkdirSync7(dirname12(dirname12(path)), { recursive: true, mode: 448 });
30337
- mkdirSync7(dirname12(path), { recursive: true, mode: 448 });
31750
+ mkdirSync8(dirname12(dirname12(path)), { recursive: true, mode: 448 });
31751
+ mkdirSync8(dirname12(path), { recursive: true, mode: 448 });
30338
31752
  }
30339
31753
  function writeStamp(path, at) {
30340
31754
  ensurePrivateParent(path);
@@ -30363,17 +31777,17 @@ import {
30363
31777
  closeSync as closeSync3,
30364
31778
  fchmodSync as fchmodSync2,
30365
31779
  fsyncSync as fsyncSync2,
30366
- linkSync,
31780
+ linkSync as linkSync2,
30367
31781
  lstatSync as lstatSync8,
30368
- mkdirSync as mkdirSync8,
31782
+ mkdirSync as mkdirSync9,
30369
31783
  openSync as openSync3,
30370
- readFileSync as readFileSync16,
31784
+ readFileSync as readFileSync18,
30371
31785
  statSync as statSync3,
30372
31786
  unlinkSync as unlinkSync2,
30373
- writeFileSync as writeFileSync4
31787
+ writeFileSync as writeFileSync6
30374
31788
  } from "fs";
30375
- import { dirname as dirname13, isAbsolute as isAbsolute5, join as join19, resolve as resolve6 } from "path";
30376
- var WORKSPACE_ID_RELATIVE_PATH = join19("prim", "workspace-id");
31789
+ import { dirname as dirname13, isAbsolute as isAbsolute5, join as join22, resolve as resolve6 } from "path";
31790
+ var WORKSPACE_ID_RELATIVE_PATH = join22("prim", "workspace-id");
30377
31791
  var MAX_ANCESTORS = 64;
30378
31792
  var MAX_GIT_FILE_BYTES = 4096;
30379
31793
  var MAX_ID_FILE_BYTES = 128;
@@ -30432,19 +31846,19 @@ function resolveWorkspaceIdPath(cwd) {
30432
31846
  function resolveFromFilesystem(cwd) {
30433
31847
  let current = resolve6(cwd);
30434
31848
  for (let depth = 0; depth < MAX_ANCESTORS; depth += 1) {
30435
- const dotGit = join19(current, ".git");
31849
+ const dotGit = join22(current, ".git");
30436
31850
  try {
30437
31851
  const stat = lstatSync8(dotGit);
30438
31852
  if (stat.isDirectory() && isGitDirectory(dotGit)) {
30439
- return join19(dotGit, WORKSPACE_ID_RELATIVE_PATH);
31853
+ return join22(dotGit, WORKSPACE_ID_RELATIVE_PATH);
30440
31854
  }
30441
31855
  if (stat.isFile() && stat.size <= MAX_GIT_FILE_BYTES) {
30442
- const contents = readFileSync16(dotGit, "utf8");
31856
+ const contents = readFileSync18(dotGit, "utf8");
30443
31857
  const match = /^gitdir: (.+?)(?:\r?\n)?$/.exec(contents);
30444
31858
  if (match?.[1]) {
30445
31859
  const gitDirectory = isAbsolute5(match[1]) ? resolve6(match[1]) : resolve6(current, match[1]);
30446
31860
  if (isGitDirectory(gitDirectory)) {
30447
- return join19(gitDirectory, WORKSPACE_ID_RELATIVE_PATH);
31861
+ return join22(gitDirectory, WORKSPACE_ID_RELATIVE_PATH);
30448
31862
  }
30449
31863
  }
30450
31864
  }
@@ -30463,7 +31877,7 @@ function resolveFromFilesystem(cwd) {
30463
31877
  }
30464
31878
  function isGitDirectory(path) {
30465
31879
  try {
30466
- return statSync3(join19(path, "HEAD")).isFile();
31880
+ return statSync3(join22(path, "HEAD")).isFile();
30467
31881
  } catch {
30468
31882
  return false;
30469
31883
  }
@@ -30482,7 +31896,7 @@ function inspectPath(path) {
30482
31896
  return { status: "corrupt", path, reason: "invalid_content" };
30483
31897
  }
30484
31898
  try {
30485
- const contents = readFileSync16(path, "utf8");
31899
+ const contents = readFileSync18(path, "utf8");
30486
31900
  const workspaceId = contents.endsWith("\n") ? contents.slice(0, -1) : contents;
30487
31901
  if ((contents === workspaceId || contents === `${workspaceId}
30488
31902
  `) && isCanonicalWorkspaceId(workspaceId)) {
@@ -30501,11 +31915,11 @@ function inspectPath(path) {
30501
31915
  function createWorkspaceId(path) {
30502
31916
  const parent = dirname13(path);
30503
31917
  const workspaceId = randomUUID4();
30504
- const temporaryPath = join19(parent, `.workspace-id-${process.pid}-${randomUUID4()}.tmp`);
31918
+ const temporaryPath = join22(parent, `.workspace-id-${process.pid}-${randomUUID4()}.tmp`);
30505
31919
  let temporaryCreated = false;
30506
31920
  let publishing = false;
30507
31921
  try {
30508
- mkdirSync8(parent, { recursive: true, mode: 448 });
31922
+ mkdirSync9(parent, { recursive: true, mode: 448 });
30509
31923
  chmodSync6(parent, 448);
30510
31924
  const fd = openSync3(
30511
31925
  temporaryPath,
@@ -30514,7 +31928,7 @@ function createWorkspaceId(path) {
30514
31928
  );
30515
31929
  temporaryCreated = true;
30516
31930
  try {
30517
- writeFileSync4(fd, `${workspaceId}
31931
+ writeFileSync6(fd, `${workspaceId}
30518
31932
  `, "utf8");
30519
31933
  fchmodSync2(fd, 384);
30520
31934
  fsyncSync2(fd);
@@ -30522,7 +31936,7 @@ function createWorkspaceId(path) {
30522
31936
  closeSync3(fd);
30523
31937
  }
30524
31938
  publishing = true;
30525
- linkSync(temporaryPath, path);
31939
+ linkSync2(temporaryPath, path);
30526
31940
  return { status: "ready", workspaceId, path, created: true };
30527
31941
  } catch (error) {
30528
31942
  if (publishing && errorCode(error) === "EEXIST") return inspectAfterRace(path);
@@ -30571,29 +31985,29 @@ function parseAgent(argv) {
30571
31985
  }
30572
31986
 
30573
31987
  // src/hooks/codex-context.ts
30574
- import { createHash as createHash10, randomBytes as randomBytes6 } from "crypto";
31988
+ import { createHash as createHash11, randomBytes as randomBytes7 } from "crypto";
30575
31989
  import {
30576
31990
  chmodSync as chmodSync7,
30577
- existsSync as existsSync14,
30578
- mkdirSync as mkdirSync9,
30579
- readFileSync as readFileSync17,
30580
- readdirSync as readdirSync6,
31991
+ existsSync as existsSync15,
31992
+ mkdirSync as mkdirSync10,
31993
+ readFileSync as readFileSync19,
31994
+ readdirSync as readdirSync7,
30581
31995
  renameSync as renameSync3,
30582
- rmSync as rmSync9,
31996
+ rmSync as rmSync11,
30583
31997
  statSync as statSync4,
30584
31998
  unlinkSync as unlinkSync3,
30585
- writeFileSync as writeFileSync5
31999
+ writeFileSync as writeFileSync7
30586
32000
  } from "fs";
30587
- import { join as join21 } from "path";
32001
+ import { join as join24 } from "path";
30588
32002
 
30589
32003
  // src/daemon/principal.ts
30590
- import { createHash as createHash9 } from "crypto";
32004
+ import { createHash as createHash10 } from "crypto";
30591
32005
  var PRINCIPAL_COMPONENT_MAX_LENGTH = 512;
30592
32006
  function boundedClaim(value) {
30593
32007
  return typeof value === "string" && value.length > 0 && value.length <= PRINCIPAL_COMPONENT_MAX_LENGTH ? value : void 0;
30594
32008
  }
30595
32009
  function sha256(value) {
30596
- return createHash9("sha256").update(value).digest("hex");
32010
+ return createHash10("sha256").update(value).digest("hex");
30597
32011
  }
30598
32012
  function resolveDaemonPrincipal(token = resolveAuthCredential()?.token) {
30599
32013
  if (hasMachineConfiguration()) {
@@ -30647,14 +32061,14 @@ function parseDaemonResponseEnvelope(value) {
30647
32061
 
30648
32062
  // src/daemon/client.ts
30649
32063
  import { createConnection } from "net";
30650
- import { join as join20 } from "path";
30651
- var SOCK_PATH = join20(primConfigDirectory(), "sock");
32064
+ import { join as join23 } from "path";
32065
+ var SOCK_PATH = join23(primConfigDirectory(), "sock");
30652
32066
  var DEFAULT_TIMEOUT_MS2 = 250;
30653
32067
  var nextRequestId = 1;
30654
32068
  function daemonRequest(method, params = {}, opts = {}) {
30655
32069
  const id2 = nextRequestId++;
30656
32070
  const caller = resolveDaemonPrincipal();
30657
- const request2 = {
32071
+ const request3 = {
30658
32072
  id: id2,
30659
32073
  method,
30660
32074
  params,
@@ -30693,7 +32107,7 @@ function daemonRequest(method, params = {}, opts = {}) {
30693
32107
  });
30694
32108
  socket.on("connect", () => {
30695
32109
  try {
30696
- socket?.write(`${JSON.stringify(request2)}
32110
+ socket?.write(`${JSON.stringify(request3)}
30697
32111
  `);
30698
32112
  } catch {
30699
32113
  clearTimeout(timer);
@@ -30738,7 +32152,7 @@ function daemonRequest(method, params = {}, opts = {}) {
30738
32152
  }
30739
32153
 
30740
32154
  // src/daemon/decision-digest-cache.ts
30741
- import { randomBytes as randomBytes5 } from "crypto";
32155
+ import { randomBytes as randomBytes6 } from "crypto";
30742
32156
  var DECISION_DIGEST_CACHE_LIMIT = 100;
30743
32157
  var DECISION_DIGEST_CACHE_WINDOW = "24h";
30744
32158
  var DECISION_DIGEST_CACHE_PATH = `/api/cli/decisions/recent?limit=${String(DECISION_DIGEST_CACHE_LIMIT)}&since=${DECISION_DIGEST_CACHE_WINDOW}`;
@@ -30897,10 +32311,10 @@ var STATE_VERSION = 1;
30897
32311
  var DRAFT_STATE_VERSION = 2;
30898
32312
  var NO_CURSOR = -1;
30899
32313
  function stateRoot(namespace) {
30900
- return join21(primConfigDirectory(), namespace, "decision-digests");
32314
+ return join24(primConfigDirectory(), namespace, "decision-digests");
30901
32315
  }
30902
32316
  function draftStateRoot(namespace) {
30903
- return join21(primConfigDirectory(), namespace, "decision-draft-deliveries");
32317
+ return join24(primConfigDirectory(), namespace, "decision-draft-deliveries");
30904
32318
  }
30905
32319
  function workspaceFor(cwd) {
30906
32320
  try {
@@ -30911,13 +32325,13 @@ function workspaceFor(cwd) {
30911
32325
  }
30912
32326
  function statePath(args) {
30913
32327
  const identity = `${args.siteUrl}\0${workspaceFor(args.cwd)}\0${args.sessionId}`;
30914
- const key = createHash10("sha256").update(identity).digest("hex");
30915
- return join21(stateRoot(args.namespace), `${key}.json`);
32328
+ const key = createHash11("sha256").update(identity).digest("hex");
32329
+ return join24(stateRoot(args.namespace), `${key}.json`);
30916
32330
  }
30917
32331
  function draftStatePath(args) {
30918
32332
  const identity = `${args.siteUrl}\0${workspaceFor(args.cwd)}\0${args.sessionId}\0${args.principalId}\0${args.organizationId}\0${args.credentialFingerprint}`;
30919
- const key = createHash10("sha256").update(identity).digest("hex");
30920
- return join21(draftStateRoot(args.namespace), `${key}.json`);
32333
+ const key = createHash11("sha256").update(identity).digest("hex");
32334
+ return join24(draftStateRoot(args.namespace), `${key}.json`);
30921
32335
  }
30922
32336
  function parseState(value) {
30923
32337
  if (typeof value !== "object" || value === null || Array.isArray(value)) return void 0;
@@ -30955,31 +32369,31 @@ function parseDraftState(value) {
30955
32369
  updatedAt: record.updatedAt
30956
32370
  };
30957
32371
  }
30958
- function readState(path) {
30959
- if (!existsSync14(path)) return void 0;
32372
+ function readState2(path) {
32373
+ if (!existsSync15(path)) return void 0;
30960
32374
  try {
30961
- return parseState(JSON.parse(readFileSync17(path, "utf8")));
32375
+ return parseState(JSON.parse(readFileSync19(path, "utf8")));
30962
32376
  } catch {
30963
32377
  return void 0;
30964
32378
  }
30965
32379
  }
30966
32380
  function readDraftState(path) {
30967
- if (!existsSync14(path)) return void 0;
32381
+ if (!existsSync15(path)) return void 0;
30968
32382
  try {
30969
- return parseDraftState(JSON.parse(readFileSync17(path, "utf8")));
32383
+ return parseDraftState(JSON.parse(readFileSync19(path, "utf8")));
30970
32384
  } catch {
30971
32385
  return void 0;
30972
32386
  }
30973
32387
  }
30974
32388
  function writeStateFile(path, directory, state) {
30975
- mkdirSync9(directory, { recursive: true, mode: 448 });
32389
+ mkdirSync10(directory, { recursive: true, mode: 448 });
30976
32390
  chmodSync7(directory, 448);
30977
- const temporary = join21(
32391
+ const temporary = join24(
30978
32392
  directory,
30979
- `.${path.slice(directory.length + 1)}.tmp-${process.pid}-${randomBytes6(8).toString("hex")}`
32393
+ `.${path.slice(directory.length + 1)}.tmp-${process.pid}-${randomBytes7(8).toString("hex")}`
30980
32394
  );
30981
32395
  try {
30982
- writeFileSync5(temporary, `${JSON.stringify(state)}
32396
+ writeFileSync7(temporary, `${JSON.stringify(state)}
30983
32397
  `, {
30984
32398
  encoding: "utf8",
30985
32399
  mode: 384,
@@ -30995,17 +32409,17 @@ function writeStateFile(path, directory, state) {
30995
32409
  }
30996
32410
  }
30997
32411
  function cleanupStateFiles(directory, now) {
30998
- if (!existsSync14(directory)) return;
32412
+ if (!existsSync15(directory)) return;
30999
32413
  let names;
31000
32414
  try {
31001
- names = readdirSync6(directory);
32415
+ names = readdirSync7(directory);
31002
32416
  } catch {
31003
32417
  return;
31004
32418
  }
31005
32419
  const files = [];
31006
32420
  const residue = [];
31007
32421
  for (const name2 of names) {
31008
- const path = join21(directory, name2);
32422
+ const path = join24(directory, name2);
31009
32423
  try {
31010
32424
  const mtimeMs = statSync4(path).mtimeMs;
31011
32425
  if (name2.endsWith(".json")) {
@@ -31027,7 +32441,7 @@ function cleanupStateFiles(directory, now) {
31027
32441
  for (const path of residue) {
31028
32442
  try {
31029
32443
  if (now - statSync4(path).mtimeMs > CODEX_DIGEST_STATE_RETENTION_MS) {
31030
- rmSync9(path, { recursive: true, force: true });
32444
+ rmSync11(path, { recursive: true, force: true });
31031
32445
  }
31032
32446
  } catch {
31033
32447
  }
@@ -31113,7 +32527,7 @@ async function commitState(path, args, namespace) {
31113
32527
  await withFileLock(
31114
32528
  `${path}.lock`,
31115
32529
  () => {
31116
- const latest = readState(path);
32530
+ const latest = readState2(path);
31117
32531
  writeStateFile(path, stateRoot(namespace), mergeState(latest, args));
31118
32532
  cleanupStateFiles(stateRoot(namespace), args.now);
31119
32533
  },
@@ -31160,7 +32574,7 @@ async function prepareCodexContext(options) {
31160
32574
  const siteUrl = getSiteUrl();
31161
32575
  const workspace = workspaceFor(options.cwd);
31162
32576
  const path = statePath({ cwd: options.cwd, sessionId: options.sessionId, siteUrl, namespace });
31163
- const previous = readState(path);
32577
+ const previous = readState2(path);
31164
32578
  const principal = resolveDaemonPrincipal();
31165
32579
  const privatePath = principal ? draftStatePath({
31166
32580
  cwd: options.cwd,
@@ -31343,17 +32757,17 @@ async function processCodexMessageContext(envelope, deps = defaultDeps) {
31343
32757
  }
31344
32758
 
31345
32759
  // src/commands/cursor-install.ts
31346
- import { existsSync as existsSync16, readFileSync as readFileSync19 } from "fs";
32760
+ import { existsSync as existsSync17, readFileSync as readFileSync21 } from "fs";
31347
32761
  import { homedir as homedir4 } from "os";
31348
- import { isAbsolute as isAbsolute6, join as join23 } from "path";
32762
+ import { isAbsolute as isAbsolute6, join as join26 } from "path";
31349
32763
 
31350
32764
  // src/lib/preflight-host.ts
31351
32765
  import { execFileSync as execFileSync7 } from "child_process";
31352
32766
 
31353
32767
  // src/commands/claude-install.ts
31354
- import { existsSync as existsSync15, readFileSync as readFileSync18 } from "fs";
32768
+ import { existsSync as existsSync16, lstatSync as lstatSync9, readFileSync as readFileSync20 } from "fs";
31355
32769
  import { homedir as homedir3 } from "os";
31356
- import { join as join22 } from "path";
32770
+ import { join as join25 } from "path";
31357
32771
  var CAPTURE_BIN = "prim-hook";
31358
32772
  var GATE_BIN = "prim-pre-tool-use";
31359
32773
  var POST_TOOL_USE_BIN = "prim-post-tool-use";
@@ -31362,7 +32776,7 @@ var SESSION_END_BIN = "prim-session-end";
31362
32776
  var STATUSLINE_BIN = "prim-statusline";
31363
32777
  var STATUSLINE_ARGS = "";
31364
32778
  var STATUSLINE_COMMAND = stableHookCommand(STATUSLINE_BIN, STATUSLINE_ARGS);
31365
- var USER_SCOPE_PATH = join22(homedir3(), ".claude", "settings.json");
32779
+ var USER_SCOPE_PATH = join25(homedir3(), ".claude", "settings.json");
31366
32780
  function projectRoot() {
31367
32781
  return gitToplevel() ?? process.cwd();
31368
32782
  }
@@ -31442,20 +32856,20 @@ function cursorConfigDirectory(env = process.env, home = homedir4(), platform2 =
31442
32856
  const explicit = env.CURSOR_CONFIG_DIR?.trim();
31443
32857
  if (explicit && isAbsolute6(explicit)) return explicit;
31444
32858
  const xdg = env.XDG_CONFIG_HOME?.trim();
31445
- if (platform2 !== "darwin" && xdg && isAbsolute6(xdg)) return join23(xdg, "cursor");
31446
- return join23(home, ".cursor");
32859
+ if (platform2 !== "darwin" && xdg && isAbsolute6(xdg)) return join26(xdg, "cursor");
32860
+ return join26(home, ".cursor");
31447
32861
  }
31448
32862
  function cursorHooksPath(scope, root = projectRoot()) {
31449
- return scope === "user" ? join23(cursorConfigDirectory(), "hooks.json") : join23(root, ".cursor", "hooks.json");
32863
+ return scope === "user" ? join26(cursorConfigDirectory(), "hooks.json") : join26(root, ".cursor", "hooks.json");
31450
32864
  }
31451
32865
  function plainObject(value) {
31452
32866
  return typeof value === "object" && value !== null && !Array.isArray(value);
31453
32867
  }
31454
32868
  function readCursorHooks(path) {
31455
- if (!existsSync16(path)) return {};
32869
+ if (!existsSync17(path)) return {};
31456
32870
  let parsed;
31457
32871
  try {
31458
- parsed = JSON.parse(readFileSync19(path, "utf8"));
32872
+ parsed = JSON.parse(readFileSync21(path, "utf8"));
31459
32873
  } catch {
31460
32874
  throw new Error(`invalid Cursor hooks JSON at ${path}`);
31461
32875
  }
@@ -31727,8 +33141,8 @@ function extractFileTargets(toolName, toolInput, agent = "claude_code") {
31727
33141
  }
31728
33142
 
31729
33143
  // src/hooks/redact.ts
31730
- import { existsSync as existsSync17, readFileSync as readFileSync20, statSync as statSync5 } from "fs";
31731
- import { join as join24 } from "path";
33144
+ import { existsSync as existsSync18, readFileSync as readFileSync22, statSync as statSync5 } from "fs";
33145
+ import { join as join27 } from "path";
31732
33146
  import { Worker } from "worker_threads";
31733
33147
  var USER_HOME_RULES = [
31734
33148
  {
@@ -31772,6 +33186,11 @@ var DEFAULT_RULES = [
31772
33186
  pattern: /\bAWS_(?:SECRET_ACCESS_KEY|SESSION_TOKEN)"?\s*[:=]\s*["']?[A-Za-z0-9/+=]{20,}["']?/gi,
31773
33187
  reason: "aws-secret"
31774
33188
  },
33189
+ {
33190
+ // `prim auth enroll --print-env` output an agent may write into a file.
33191
+ pattern: /\bPRIM_M2M_CLIENT_SECRET"?\s*[:=]\s*["']?[^\s"']+["']?/g,
33192
+ reason: "prim-m2m-secret"
33193
+ },
31775
33194
  { pattern: /\bAIza[0-9A-Za-z_-]{35}(?![0-9A-Za-z_-])/g, reason: "gcp-api-key" },
31776
33195
  {
31777
33196
  pattern: /\bya29\.[0-9A-Za-z_-]{20,}(?![0-9A-Za-z_-])/g,
@@ -31804,15 +33223,15 @@ function normalizedWorkspaceFlags(value) {
31804
33223
  return [...new Set(`g${requested}`)].sort().join("");
31805
33224
  }
31806
33225
  function loadWorkspaceRules(cwd) {
31807
- const path = join24(cwd, WORKSPACE_FILE2);
31808
- if (!existsSync17(path)) return [];
33226
+ const path = join27(cwd, WORKSPACE_FILE2);
33227
+ if (!existsSync18(path)) return [];
31809
33228
  let cfg;
31810
33229
  try {
31811
33230
  if (statSync5(path).size > MAX_WORKSPACE_CONFIG_BYTES) {
31812
33231
  debugRedaction(`ignoring oversized ${WORKSPACE_FILE2}`);
31813
33232
  return [];
31814
33233
  }
31815
- cfg = JSON.parse(readFileSync20(path, "utf-8"));
33234
+ cfg = JSON.parse(readFileSync22(path, "utf-8"));
31816
33235
  } catch {
31817
33236
  debugRedaction(`ignoring unparseable ${WORKSPACE_FILE2}`);
31818
33237
  return [];
@@ -38168,7 +39587,7 @@ var TokenGroup = class {
38168
39587
  }
38169
39588
  token(input, stack) {
38170
39589
  let { parser: parser3 } = stack.p;
38171
- readToken(this.data, input, stack, this.id, parser3.data, parser3.tokenPrecTable);
39590
+ readToken2(this.data, input, stack, this.id, parser3.data, parser3.tokenPrecTable);
38172
39591
  }
38173
39592
  };
38174
39593
  TokenGroup.prototype.contextual = TokenGroup.prototype.fallback = TokenGroup.prototype.extend = false;
@@ -38182,7 +39601,7 @@ var LocalTokenGroup = class {
38182
39601
  let start = input.pos, skipped = 0;
38183
39602
  for (; ; ) {
38184
39603
  let atEof = input.next < 0, nextPos = input.resolveOffset(1, 1);
38185
- readToken(this.data, input, stack, 0, this.data, this.precTable);
39604
+ readToken2(this.data, input, stack, 0, this.data, this.precTable);
38186
39605
  if (input.token.value > -1)
38187
39606
  break;
38188
39607
  if (this.elseToken == null)
@@ -38215,7 +39634,7 @@ var ExternalTokenizer = class {
38215
39634
  this.extend = !!options.extend;
38216
39635
  }
38217
39636
  };
38218
- function readToken(data, input, stack, group, precTable, precOffset) {
39637
+ function readToken2(data, input, stack, group, precTable, precOffset) {
38219
39638
  let state = 0, groupMask = 1 << group, { dialect } = stack.p.parser;
38220
39639
  scan: for (; ; ) {
38221
39640
  if ((groupMask & data[state]) == 0)
@@ -40028,7 +41447,7 @@ var newline2 = 10;
40028
41447
  var carriageReturn = 13;
40029
41448
  var space2 = 32;
40030
41449
  var tab = 9;
40031
- var hash2 = 35;
41450
+ var hash3 = 35;
40032
41451
  var parenOpen = 40;
40033
41452
  var dot2 = 46;
40034
41453
  var braceOpen = 123;
@@ -40081,7 +41500,7 @@ var newlines = new ExternalTokenizer((input, stack) => {
40081
41500
  input.advance();
40082
41501
  spaces2++;
40083
41502
  }
40084
- if (input.next == newline2 || input.next == carriageReturn || input.next == hash2)
41503
+ if (input.next == newline2 || input.next == carriageReturn || input.next == hash3)
40085
41504
  input.acceptToken(blankLineStart, -spaces2);
40086
41505
  } else if (isLineBreak(input.next)) {
40087
41506
  input.acceptToken(newline$1, 1);
@@ -40100,7 +41519,7 @@ var indentation = new ExternalTokenizer((input, stack) => {
40100
41519
  input.advance();
40101
41520
  chars++;
40102
41521
  }
40103
- if (depth != context.indent && input.next != newline2 && input.next != carriageReturn && input.next != hash2) {
41522
+ if (depth != context.indent && input.next != newline2 && input.next != carriageReturn && input.next != hash3) {
40104
41523
  if (depth < context.indent) input.acceptToken(dedent, -chars);
40105
41524
  else input.acceptToken(indent);
40106
41525
  }
@@ -40174,7 +41593,7 @@ var legacyPrint = new ExternalTokenizer((input) => {
40174
41593
  for (let off = 0; ; off++) {
40175
41594
  let next = input.peek(off);
40176
41595
  if (next == space2 || next == tab) continue;
40177
- if (next != parenOpen && next != dot2 && next != newline2 && next != carriageReturn && next != hash2)
41596
+ if (next != parenOpen && next != dot2 && next != newline2 && next != carriageReturn && next != hash3)
40178
41597
  input.acceptToken(printKeyword);
40179
41598
  return;
40180
41599
  }
@@ -41385,7 +42804,7 @@ function readHookStdin(timeoutMs = 1e3, maxBytes = DEFAULT_MAX_BYTES) {
41385
42804
  }
41386
42805
 
41387
42806
  // src/hooks/normalize.ts
41388
- import { createHash as createHash11 } from "crypto";
42807
+ import { createHash as createHash12 } from "crypto";
41389
42808
  import { realpathSync as realpathSync4 } from "fs";
41390
42809
  import { isAbsolute as isAbsolute8, resolve as resolve8 } from "path";
41391
42810
  var HERMES_EVENT_MAP = {
@@ -41430,7 +42849,7 @@ function requiredId(value, field) {
41430
42849
  }
41431
42850
  function cursorToolUseId(value) {
41432
42851
  if (SAFE_CORRELATION_ID_RE.test(value)) return value;
41433
- return `cursor:tool:v1:${createHash11("sha256").update(value).digest("hex")}`;
42852
+ return `cursor:tool:v1:${createHash12("sha256").update(value).digest("hex")}`;
41434
42853
  }
41435
42854
  function workspaceCandidates(value) {
41436
42855
  if (!Array.isArray(value)) return [];
@@ -41527,7 +42946,7 @@ function normalizeEnvelope(parsed, agent) {
41527
42946
  ]);
41528
42947
  return {
41529
42948
  ...parsed,
41530
- tool_use_id: `codex:fallback:v1:${createHash11("sha256").update(stableToolIdentity).digest("hex")}`
42949
+ tool_use_id: `codex:fallback:v1:${createHash12("sha256").update(stableToolIdentity).digest("hex")}`
41531
42950
  };
41532
42951
  }
41533
42952
  return parsed;
@@ -41543,7 +42962,7 @@ function normalizeEnvelope(parsed, agent) {
41543
42962
  }
41544
42963
 
41545
42964
  // src/hooks/prim-hook-core.ts
41546
- import { createHash as createHash12, randomUUID as randomUUID5 } from "crypto";
42965
+ import { createHash as createHash13, randomUUID as randomUUID5 } from "crypto";
41547
42966
  import { platform } from "os";
41548
42967
 
41549
42968
  // src/protocol/move.ts
@@ -41617,9 +43036,9 @@ function toMove(parsed, cliVersion, agent = "claude_code", workspaceId, reposito
41617
43036
  const toolOutcome = toolOutcomeFor(parsed, agent);
41618
43037
  let moveId;
41619
43038
  if (CORRELATED_TOOL_EVENTS.has(eventType) && sessionId && invocationId) {
41620
- moveId = `posttool:v1:${createHash12("sha256").update(JSON.stringify([agent, sessionId, eventType, invocationId])).digest("hex")}`;
43039
+ moveId = `posttool:v1:${createHash13("sha256").update(JSON.stringify([agent, sessionId, eventType, invocationId])).digest("hex")}`;
41621
43040
  } else if (CORRELATED_TOOL_EVENTS.has(eventType) && sessionId && agent !== "cursor") {
41622
- moveId = `posttool:fallback:v1:${createHash12("sha256").update(
43041
+ moveId = `posttool:fallback:v1:${createHash13("sha256").update(
41623
43042
  JSON.stringify([
41624
43043
  agent,
41625
43044
  sessionId,
@@ -41670,14 +43089,14 @@ function emitOutput(output, acknowledge) {
41670
43089
  }
41671
43090
  function resolveCliVersion() {
41672
43091
  try {
41673
- const pkg = JSON.parse(readFileSync21(join25(here, "..", "..", "package.json"), "utf-8"));
43092
+ const pkg = JSON.parse(readFileSync23(join28(here, "..", "..", "package.json"), "utf-8"));
41674
43093
  return pkg.version ?? "unknown";
41675
43094
  } catch {
41676
43095
  return "unknown";
41677
43096
  }
41678
43097
  }
41679
43098
  function spawnBackgroundFlush() {
41680
- const entry = join25(here, "..", "index.js");
43099
+ const entry = join28(here, "..", "index.js");
41681
43100
  spawn2(process.execPath, [entry, "moves", "flush"], {
41682
43101
  detached: true,
41683
43102
  stdio: "ignore",